ws-audio2: merge ws/audio2-adpcm (codecs/audio/Adpcm, Qoa; adx, vag, brstm/bcstm/bfstm, raw adpcm, qoa; wav/aiff/caf/xm ADPCM)
This commit is contained in:
commit
703af4cc71
43 files changed
+5121
-197
No files matched your search
@@ -1127,3 +1127,58 @@ do
|
||||
end
|
||||
end
|
||||
end
|
||||
-- ws-audio2: adpcm / qoa
|
||||
do
|
||||
-- codecs/audio/Adpcm (IMA nibble stream, Nintendo DSP frames) and QOA decode / encode, over generated signals; MB/s
|
||||
-- of f32 output (MB/s of input for the encoder)
|
||||
local Adpcm = require("@formats/codecs/audio/Adpcm")
|
||||
local QoaCodec = require("@formats/codecs/audio/Qoa")
|
||||
local Qoa = require("@formats/audio/qoa")
|
||||
local n = 44100 * 5
|
||||
local sig = Types.Audio.new(44100, 2, n)
|
||||
for i = 0, n - 1 do
|
||||
local t = i / 44100
|
||||
buffer.writef32(sig.samples, i * 8, 0.5 * math.sin(2 * math.pi * 440 * t) + 0.1 * math.sin(2 * math.pi * 3000 * t))
|
||||
buffer.writef32(sig.samples, i * 8 + 4, 0.4 * math.sin(2 * math.pi * 660 * t + 1))
|
||||
end
|
||||
-- IMA: encode the left channel as a nibble stream, then decode it
|
||||
local ima = buffer.create(n // 2)
|
||||
Adpcm.imaEncode(sig.samples, 0, 2, n, buffer.create(8), 0, ima, 0, 0, 1, false)
|
||||
local out = buffer.create(n * 4)
|
||||
bench("adpcm ima decode", 5, n * 4, function()
|
||||
Adpcm.ima(ima, 0, 0, 1, n, false, buffer.create(8), 0, out, 0, 1)
|
||||
end)
|
||||
-- DSP: random frames with 8 coefficient pairs
|
||||
local frames = n // 14
|
||||
local dsp = buffer.create(frames * 8)
|
||||
local seed = 1
|
||||
for i = 0, frames * 8 - 1 do
|
||||
seed = (seed * 1103515245 + 12345) % 2147483648
|
||||
local v = seed // 65536 % 256
|
||||
buffer.writeu8(dsp, i, if i % 8 == 0 then (v % 8) * 16 + v % 12 else v)
|
||||
end
|
||||
local coefs = buffer.create(64)
|
||||
for k = 0, 7 do
|
||||
buffer.writei32(coefs, k * 8, 1800 + k * 200)
|
||||
buffer.writei32(coefs, k * 8 + 4, -900 - k * 100)
|
||||
end
|
||||
bench("adpcm dsp decode", 5, frames * 14 * 4, function()
|
||||
Adpcm.dsp(dsp, 0, frames * 14, coefs, 0, buffer.create(8), 0, out, 0, 1)
|
||||
end)
|
||||
-- QOA (stereo 44.1 kHz)
|
||||
local file = assert(Qoa.encode(sig))
|
||||
bench("qoa encode", 2, n * 2 * 4, function()
|
||||
Qoa.encode(sig)
|
||||
end)
|
||||
local pcm = buffer.create(QoaCodec.FRAME_LEN * 2 * 4)
|
||||
bench("qoa decode", 5, n * 2 * 4, function()
|
||||
local p = 8
|
||||
while p < buffer.len(file) do
|
||||
local _, size = QoaCodec.decodeFrame(file, p, buffer.len(file) - p, pcm, 0)
|
||||
p += size :: number
|
||||
end
|
||||
end)
|
||||
bench("qoa decode (F.load path)", 5, n * 2 * 4, function()
|
||||
Qoa.decode(Bytes.reader(file))
|
||||
end)
|
||||
end
|
||||
@@ -0,0 +1,377 @@
|
||||
# Shared helpers for the ADPCM fixture generators (adpcm, adx, vag, brstm): small Python ADPCM encoders that build the
|
||||
# game containers ffmpeg cannot write (Sony VAG, Nintendo BRSTM / BCSTM / BFSTM, Simon & Schuster KVAG); the files are
|
||||
# decoded by vgmstream / ffmpeg as the references, so these encoders only need to be valid, not good.
|
||||
# A = _adpcm.load()
|
||||
# A.ima_encode(samples, ch, high_first=False) -> raw IMA nibble stream (state 0 / 0; channels interleaved by nibble)
|
||||
# A.kvag(samples, rate, ch) -> a KVAG file (IMA, high nibble first)
|
||||
# A.psx_encode(samples) -> bytes of 16-byte PS-ADPCM frames (mono); A.vag(samples, rate, name, loop=None)
|
||||
# A.dsp_encode(samples, coefs) -> bytes of 8-byte DSP frames (mono); A.DSP_COEFS: the 16 coefficients used
|
||||
# A.rstm(samples, rate, ch, kind="RSTM"|"CSTM"|"FSTM", loop=None, block=0x2000, le=None, codec="dsp"|"pcm16"|"pcm8")
|
||||
# A.s16(floats) -> clipped ints
|
||||
import math, struct, sys
|
||||
|
||||
IMA_STEP = [
|
||||
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
|
||||
130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060,
|
||||
1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484,
|
||||
7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767]
|
||||
IMA_INDEX = [-1, -1, -1, -1, 2, 4, 6, 8]
|
||||
|
||||
|
||||
def load():
|
||||
return sys.modules[__name__]
|
||||
|
||||
|
||||
def s16(floats):
|
||||
return [max(-32768, min(32767, int(math.floor(v * 32768 + 0.5)))) for v in floats]
|
||||
|
||||
|
||||
def clamp16(v):
|
||||
return -32768 if v < -32768 else 32767 if v > 32767 else v
|
||||
|
||||
|
||||
def ima_step(pred, index, nib):
|
||||
step = IMA_STEP[index]
|
||||
d = step >> 3
|
||||
if nib & 1:
|
||||
d += step >> 2
|
||||
if nib & 2:
|
||||
d += step >> 1
|
||||
if nib & 4:
|
||||
d += step
|
||||
pred = clamp16(pred - d if nib & 8 else pred + d)
|
||||
index = max(0, min(88, index + IMA_INDEX[nib & 7]))
|
||||
return pred, index
|
||||
|
||||
|
||||
def ima_nibble(pred, index, x):
|
||||
best = None
|
||||
for nib in range(16):
|
||||
p, _ = ima_step(pred, index, nib)
|
||||
e = abs(x - p)
|
||||
if best is None or e < best[0]:
|
||||
best = (e, nib)
|
||||
return best[1]
|
||||
|
||||
|
||||
def ima_encode(samples, ch, high_first=False):
|
||||
ints = s16(samples)
|
||||
st = [[0, 0] for _ in range(ch)]
|
||||
nibs = []
|
||||
for i, x in enumerate(ints):
|
||||
c = i % ch
|
||||
n = ima_nibble(st[c][0], st[c][1], x)
|
||||
st[c][0], st[c][1] = ima_step(st[c][0], st[c][1], n)
|
||||
nibs.append(n)
|
||||
if len(nibs) % 2:
|
||||
nibs.append(0)
|
||||
out = bytearray()
|
||||
for k in range(0, len(nibs), 2):
|
||||
a, b = nibs[k], nibs[k + 1]
|
||||
out.append((a << 4 | b) if high_first else (b << 4 | a))
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def kvag(samples, rate, ch):
|
||||
data = ima_encode(samples, ch, high_first=True) # DVI order: the high nibble first (ffmpeg adpcm_ima_ssi, vgmstream)
|
||||
return b"KVAG" + struct.pack("<IIH", len(data), rate, 1 if ch == 2 else 0) + data
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ PS-ADPCM
|
||||
PSX_COEFS = [(0, 0), (60, 0), (115, -52), (98, -55), (122, -60)]
|
||||
|
||||
|
||||
def psx_frame(xs, h1, h2):
|
||||
"""the best (filter, shift) for 28 samples: (error, header byte, nibbles, h1, h2) with vgmstream's decode"""
|
||||
best = None
|
||||
for f, (c1, c2) in enumerate(PSX_COEFS):
|
||||
for shift in range(13):
|
||||
a, b = h1, h2
|
||||
err = 0
|
||||
nibs = []
|
||||
for x in xs:
|
||||
pred = 4 * (c1 * a + c2 * b) # (c1 * a + c2 * b) / 64 * 256
|
||||
# sample = (nib << (20 - shift) + pred) >> 8; pick the nibble closest to x
|
||||
want = ((x << 8) - pred) / (1 << (20 - shift))
|
||||
n = max(-8, min(7, int(round(want))))
|
||||
s = (n * (1 << (20 - shift)) + pred) >> 8
|
||||
cs = clamp16(s)
|
||||
err += (x - cs) ** 2
|
||||
nibs.append(n & 15)
|
||||
a, b = s, a
|
||||
if best is not None and err >= best[0]:
|
||||
break
|
||||
else:
|
||||
if best is None or err < best[0]:
|
||||
best = (err, f << 4 | shift, nibs, a, b)
|
||||
return best
|
||||
|
||||
|
||||
def psx_encode(samples, loop=None):
|
||||
"""PS-ADPCM frames (mono ints) after the usual blank frame; loop = (start frame, end frame) sets the flags"""
|
||||
out = bytearray(16)
|
||||
h1 = h2 = 0
|
||||
n = (len(samples) + 27) // 28
|
||||
for k in range(n):
|
||||
xs = samples[k * 28:(k + 1) * 28]
|
||||
xs = xs + [0] * (28 - len(xs))
|
||||
_, head, nibs, h1, h2 = psx_frame(xs, h1, h2)
|
||||
flag = 0
|
||||
if loop:
|
||||
if k == loop[0]:
|
||||
flag = 6
|
||||
elif k == loop[1] - 1:
|
||||
flag = 3
|
||||
elif loop[0] < k < loop[1] - 1:
|
||||
flag = 2
|
||||
elif k == n - 1:
|
||||
flag = 1
|
||||
out += bytes([head, flag]) + bytes(nibs[i] | nibs[i + 1] << 4 for i in range(0, 28, 2))
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def vag(samples, rate, name=b"formats-luau", loop=None):
|
||||
data = psx_encode(s16(samples), loop)
|
||||
head = b"VAGp" + struct.pack(">IIII", 0x20, 0, len(data), rate) + b"\0" * 12 + name[:16].ljust(16, b"\0")
|
||||
return head + data
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ Nintendo DSP
|
||||
DSP_COEFS = [0, 0, 2048, 0, 0, 2048, 4096, -2048, 3600, -1700, 3000, -1100, 1024, 0, 3900, -1950]
|
||||
|
||||
|
||||
def dsp_frame(xs, h1, h2, coefs):
|
||||
best = None
|
||||
for p in range(8):
|
||||
c1, c2 = coefs[2 * p], coefs[2 * p + 1]
|
||||
for sc in range(12):
|
||||
scale = 1 << sc
|
||||
a, b = h1, h2
|
||||
err = 0
|
||||
nibs = []
|
||||
outs = []
|
||||
for x in xs:
|
||||
base = 1024 + c1 * a + c2 * b
|
||||
want = ((x << 11) - base) / (scale << 11)
|
||||
n = max(-8, min(7, int(round(want))))
|
||||
s = clamp16(((n * scale) << 11) + base >> 11)
|
||||
err += (x - s) ** 2
|
||||
nibs.append(n & 15)
|
||||
outs.append(s)
|
||||
a, b = s, a
|
||||
if best is not None and err >= best[0]:
|
||||
break
|
||||
else:
|
||||
if best is None or err < best[0]:
|
||||
best = (err, p << 4 | sc, nibs, outs)
|
||||
return best
|
||||
|
||||
|
||||
def dsp_encode(samples, coefs=DSP_COEFS, decoded=None):
|
||||
"""DSP frames; decoded (a list) receives the decoded samples (the history a seek table stores)"""
|
||||
out = bytearray()
|
||||
h1 = h2 = 0
|
||||
for k in range(0, len(samples), 14):
|
||||
xs = samples[k:k + 14]
|
||||
n = len(xs)
|
||||
xs = xs + [0] * (14 - n)
|
||||
_, head, nibs, outs = dsp_frame(xs, h1, h2, coefs)
|
||||
out.append(head)
|
||||
out += bytes(nibs[i] << 4 | nibs[i + 1] for i in range(0, 14, 2))
|
||||
h1, h2 = outs[-1], outs[-2]
|
||||
if decoded is not None:
|
||||
decoded += outs[:n]
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def hist(dec, b, spb):
|
||||
"""(yn1, yn2) before block b: the last two decoded samples of the previous block"""
|
||||
if b == 0 or not dec:
|
||||
return (0, 0)
|
||||
return (dec[b * spb - 1], dec[b * spb - 2])
|
||||
|
||||
|
||||
def rstm(samples, rate, ch, kind="RSTM", loop=None, block=0x2000, le=None, codec="dsp", coefs=DSP_COEFS):
|
||||
"""a BRSTM (kind RSTM, big-endian), BCSTM (CSTM, little-endian) or BFSTM (FSTM, big-endian unless le) file"""
|
||||
ints = s16(samples)
|
||||
frames = len(ints) // ch
|
||||
chans = [ints[c::ch] for c in range(ch)]
|
||||
decs = [[] for _ in range(ch)]
|
||||
if codec == "dsp":
|
||||
enc = [dsp_encode(x, coefs, decs[c]) for c, x in enumerate(chans)]
|
||||
spb = block // 8 * 14
|
||||
elif codec == "pcm16":
|
||||
big = kind == "RSTM" or (kind == "FSTM" and not le)
|
||||
enc = [b"".join(struct.pack(">h" if big else "<h", v) for v in x) for x in chans]
|
||||
spb = block // 2
|
||||
else:
|
||||
enc = [bytes((v >> 8) & 255 for v in x) for x in chans]
|
||||
spb = block
|
||||
nblocks = (frames + spb - 1) // spb
|
||||
last_samples = frames - (nblocks - 1) * spb
|
||||
last_size = len(enc[0]) - (nblocks - 1) * block
|
||||
last_padded = (last_size + 31) // 32 * 32
|
||||
data = bytearray()
|
||||
for b in range(nblocks):
|
||||
for c in range(ch):
|
||||
part = enc[c][b * block:(b + 1) * block]
|
||||
if b == nblocks - 1:
|
||||
part = part.ljust(last_padded, b"\0")
|
||||
data += part
|
||||
codec_id = {"pcm8": 0, "pcm16": 1, "dsp": 2}[codec]
|
||||
ls, le_ = (loop if loop else (0, frames))
|
||||
if kind == "RSTM":
|
||||
info = struct.pack(">BBBBHHIIIIIIIIIIII", codec_id, 1 if loop else 0, ch, 0, rate, 0, ls, frames, 0, nblocks,
|
||||
block, spb, last_size, last_samples, last_padded, spb, 4, 0)
|
||||
# HEAD: 3 references, the stream info, track info, channel info
|
||||
|
||||
def ref(off):
|
||||
return struct.pack(">II", 0x01000000, off)
|
||||
p_info = 0x18
|
||||
p_track = p_info + len(info)
|
||||
track_table = struct.pack(">BBBB", 1, 0, 0, 0) # 1 track, type 0
|
||||
p_trackent = p_track + 4 + 8
|
||||
track_ent = struct.pack(">BBBB", 127, 64, 0, 0) + struct.pack(">I", 0) + struct.pack(">BBBB", ch, 0, 1, 0)
|
||||
track_blob = track_table + ref(p_trackent) + track_ent
|
||||
p_chan = p_track + len(track_blob)
|
||||
chan_head = struct.pack(">BBBB", ch, 0, 0, 0)
|
||||
p_chinfo = p_chan + 4 + 8 * ch
|
||||
chan_refs = b""
|
||||
chan_infos = b""
|
||||
for c in range(ch):
|
||||
me = p_chinfo + len(chan_infos)
|
||||
chan_refs += ref(me)
|
||||
adp = struct.pack(">16h", *coefs) + struct.pack(">HHhhHhhH", 0, enc[c][0] if codec == "dsp" else 0, 0, 0, 0, 0, 0, 0)
|
||||
chan_infos += ref(me + 8) + adp
|
||||
body = info + track_blob + chan_head + chan_refs + chan_infos
|
||||
body = ref(p_info) + ref(p_track) + ref(p_chan) + body
|
||||
head = b"HEAD" + struct.pack(">I", 0) + body
|
||||
head = head.ljust((len(head) + 31) // 32 * 32, b"\0")
|
||||
head = head[:4] + struct.pack(">I", len(head)) + head[8:]
|
||||
adpc_body = b"".join(b"".join(struct.pack(">hh", *hist(decs[c], b, spb)) for c in range(ch)) for b in range(nblocks))
|
||||
adpc = b"ADPC" + struct.pack(">I", 0) + adpc_body
|
||||
adpc = adpc.ljust((len(adpc) + 31) // 32 * 32, b"\0")
|
||||
adpc = adpc[:4] + struct.pack(">I", len(adpc)) + adpc[8:]
|
||||
hsize = 0x40
|
||||
o_head = hsize
|
||||
o_adpc = o_head + len(head)
|
||||
o_data = o_adpc + len(adpc)
|
||||
datac = b"DATA" + struct.pack(">II", len(data) + 0x20, 0x18) + b"\0" * 0x14 + bytes(data)
|
||||
start = o_data + 0x20
|
||||
head = bytearray(head)
|
||||
struct.pack_into(">I", head, 8 + 8 * 3 + 0x10, start) # data offset (absolute)
|
||||
total = o_data + len(datac)
|
||||
hdr = b"RSTM" + struct.pack(">HHIHH", 0xFEFF, 0x0100, total, hsize, 2) + struct.pack(">IIIIII", o_head, len(head), o_adpc,
|
||||
len(adpc), o_data, len(datac))
|
||||
hdr = hdr.ljust(hsize, b"\0")
|
||||
return hdr + bytes(head) + adpc + datac
|
||||
# CSTM / FSTM
|
||||
E = ">" if (kind == "FSTM" and not le) else "<"
|
||||
|
||||
def ref(t, off):
|
||||
return struct.pack(E + "HHi", t, 0, off)
|
||||
# INFO: refs (stream info, track table, channel table), stream info, channel table, channel infos, dsp infos
|
||||
stream_info = struct.pack(E + "BBBB", codec_id, 1 if loop else 0, ch, 0) + struct.pack(
|
||||
E + "IIIIIIIIIII", rate, ls, frames, nblocks, block, spb, last_size, last_samples, last_padded, 4 * ch, spb)
|
||||
stream_info += ref(0x1F00, 0x18) # sample data: DATA + 8 + 0x18
|
||||
p_stream = 0x18
|
||||
p_chtab = p_stream + len(stream_info)
|
||||
chtab = struct.pack(E + "I", ch)
|
||||
p_chinfo = p_chtab + 4 + 8 * ch
|
||||
infos = b""
|
||||
adps = b""
|
||||
for c in range(ch):
|
||||
chtab += ref(0x4102, p_chinfo + 8 * c - p_chtab)
|
||||
p_adp = p_chinfo + 8 * ch
|
||||
for c in range(ch):
|
||||
me = p_chinfo + 8 * c
|
||||
adp_at = p_adp + len(adps)
|
||||
infos += ref(0x0300, adp_at - me) if codec == "dsp" else ref(0, -1)
|
||||
adps += struct.pack(E + "16h", *coefs) + struct.pack(E + "HhhHhhH", enc[c][0] if codec == "dsp" else 0, 0, 0, 0, 0, 0, 0)
|
||||
body = ref(0x4100, p_stream) + ref(0, -1) + ref(0x0101, p_chtab) + stream_info + chtab + infos + adps
|
||||
info = b"INFO" + struct.pack(E + "I", 0) + body
|
||||
info = info.ljust((len(info) + 31) // 32 * 32, b"\0")
|
||||
info = info[:4] + struct.pack(E + "I", len(info)) + info[8:]
|
||||
seek = b"SEEK" + struct.pack(E + "I", 0) + b"".join(b"".join(struct.pack(E + "hh", *hist(decs[c], b, spb)) for c in range(ch)) for b in range(nblocks))
|
||||
seek = seek.ljust((len(seek) + 31) // 32 * 32, b"\0")
|
||||
seek = seek[:4] + struct.pack(E + "I", len(seek)) + seek[8:]
|
||||
datac = b"DATA" + struct.pack(E + "I", len(data) + 0x20) + b"\0" * 0x18 + bytes(data)
|
||||
hsize = 0x40
|
||||
o_info = hsize
|
||||
o_seek = o_info + len(info)
|
||||
o_data = o_seek + len(seek)
|
||||
total = o_data + len(datac)
|
||||
ver = 0x02000000 if kind == "CSTM" else 0x00040000
|
||||
hdr = kind.encode() + (b"\xfe\xff" if E == ">" else b"\xff\xfe") + struct.pack(E + "HII", hsize, ver, total)
|
||||
hdr += struct.pack(E + "HH", 3, 0)
|
||||
hdr += struct.pack(E + "HHII", 0x4000, 0, o_info, len(info))
|
||||
hdr += struct.pack(E + "HHII", 0x4001, 0, o_seek, len(seek))
|
||||
hdr += struct.pack(E + "HHII", 0x4002, 0, o_data, len(datac))
|
||||
hdr = hdr.ljust(hsize, b"\0")
|
||||
return hdr + info + seek + datac
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ references
|
||||
def wav_pcm(data):
|
||||
"""(rate, channels, s16le bytes) of a 16-bit PCM WAV (vgmstream's output)"""
|
||||
p = 12
|
||||
rate = ch = None
|
||||
while p + 8 <= len(data):
|
||||
cid, size = data[p:p + 4], struct.unpack_from("<I", data, p + 4)[0]
|
||||
if cid == b"fmt ":
|
||||
ch, rate = struct.unpack_from("<HI", data, p + 10)
|
||||
elif cid == b"data":
|
||||
return rate, ch, data[p + 8:p + 8 + size]
|
||||
p += 8 + size + (size & 1)
|
||||
raise ValueError("no data chunk")
|
||||
|
||||
|
||||
def vgdecode(ctx, data, ext):
|
||||
"""vgmstream's decode of a file: (rate, channels, s16le bytes); loop facts come from vgminfo"""
|
||||
A = _audio()
|
||||
out = A.tool(ctx, "vgmstream", ["vgmstream-cli", "-i", "-o", "{out}", "{in}"], data, ext, outext="wav")
|
||||
return wav_pcm(out)
|
||||
|
||||
|
||||
def vginfo(ctx, data, ext):
|
||||
A = _audio()
|
||||
return A.tool(ctx, "vgmstream", ["vgmstream-cli", "-m", "{in}"], data, ext).decode(errors="replace")
|
||||
|
||||
|
||||
def ffs16(ctx, data, ext, fmt=None):
|
||||
"""ffmpeg's decode as s16le bytes"""
|
||||
A = _audio()
|
||||
return A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error"] + (["-f", fmt] if fmt else []) + ["-i", "{in}", "-f", "s16le",
|
||||
"-acodec", "pcm_s16le", "-"], data, ext)
|
||||
|
||||
|
||||
def ffencode(ctx, wavdata, args, ext):
|
||||
"""ffmpeg encodes a WAV input with args into a file of extension ext"""
|
||||
A = _audio()
|
||||
return A.tool(ctx, "ffmpeg", ["ffmpeg", "-v", "error", "-i", "{in}"] + list(args) + ["-y", "{out}"], wavdata, "wav",
|
||||
outext=ext)
|
||||
|
||||
|
||||
_A = None
|
||||
|
||||
|
||||
def _audio():
|
||||
global _A
|
||||
if _A is None:
|
||||
import importlib.util, os
|
||||
spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_audio.py"))
|
||||
_A = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(_A)
|
||||
return _A
|
||||
|
||||
|
||||
def vagi(samples, rate, ch=2, interleave=0x400):
|
||||
"""a VAGi file (stereo PS-ADPCM, channels interleaved every `interleave` bytes, data at 0x800)"""
|
||||
ints = s16(samples)
|
||||
chans = [psx_encode(ints[c::ch]) for c in range(ch)]
|
||||
size = max(len(x) for x in chans)
|
||||
size = (size + interleave - 1) // interleave * interleave
|
||||
chans = [x.ljust(size, b"\0") for x in chans]
|
||||
data = b"".join(chans[c][k:k + interleave] for k in range(0, size, interleave) for c in range(ch))
|
||||
head = b"VAGi" + struct.pack(">I", 0x20) + struct.pack("<I", interleave) + struct.pack(">II", size, rate)
|
||||
return head.ljust(0x800, b"\0") + data
|
||||
@@ -242,9 +242,10 @@ def write_xm(title, instruments, orders, patterns, channels, speed=6, tempo=125,
|
||||
ls, ll, lt = s.get("loop") or (0, 0, 0)
|
||||
t = lt | (16 if bpsm == 2 else 0)
|
||||
out += struct.pack("<IIIBbBBbB", len(s["data"]), ls * bpsm, ll * bpsm, s.get("volume", 64), s.get("finetune", 0),
|
||||
t, s.get("pan", 128), s.get("relnote", 0), 0) + name(s.get("name", ""), 22)
|
||||
t, s.get("pan", 128), s.get("relnote", 0), 0xAD if s.get("adpcm") else 0) + name(s.get("name", ""), 22)
|
||||
for s in smps:
|
||||
out += delta16(s["data"]) if s.get("bits", 8) == 16 else delta8(s["data"])
|
||||
# "adpcm": ModPlug ADPCM bytes (16-byte delta table + nibbles) stored instead of the delta samples
|
||||
out += s["adpcm"] if s.get("adpcm") else delta16(s["data"]) if s.get("bits", 8) == 16 else delta8(s["data"])
|
||||
return bytes(out)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
# ADPCM fixtures (tools/fixtures.py): codecs/audio/Adpcm and the raw audio/adpcm format.
|
||||
# tests/gen/adpcm_codec.luau raw codec streams with the reference decoder's s16le output: { name, kind, data, ch,
|
||||
# frames, ref, rate?, cutoff?, v3?, coefs? }
|
||||
# adx ffmpeg -f adx (version 3), the frames after the header; vgmstream decodes (scale + 1, v3 rounding)
|
||||
# psx our Python PS-ADPCM encoder (tools/fixtures/_adpcm.py) in a VAG; vgmstream decodes
|
||||
# dsp our Python DSP encoder in a mono BRSTM; vgmstream decodes
|
||||
# ima_qt ffmpeg adpcm_ima_qt in AIFF-C (the SSND packets); ffmpeg decodes
|
||||
# ima our Python IMA encoder in KVAG (high nibble first, stereo by nibble); ffmpeg (adpcm_ima_ssi) decodes
|
||||
# tests/gen/adpcm_raw.luau headerless streams for audio/adpcm: { name, codec, data, rate, ch, blockAlign?, ref }
|
||||
# ima / ima-stereo (KVAG data, ffmpeg), ms (ffmpeg adpcm_ms WAV data chunk, ffmpeg), ima_wav (ffmpeg
|
||||
# adpcm_ima_wav), ima_qt (the AIFF-C packets), psx (VAG data), dsp (mono), adx-free
|
||||
# tests/gen/adpcm_ours.luau our encoder's raw output (audio/adpcm encode, run in this step) wrapped in a container
|
||||
# ffmpeg reads, ffmpeg's decode, and our own decode of the same bytes (must match)
|
||||
# tests/gen/adpcm_sig.luau the encoder input (stereo)
|
||||
import importlib.util, os, struct
|
||||
|
||||
_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def _load(name):
|
||||
spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
A = _load("_audio")
|
||||
D = _load("_adpcm")
|
||||
|
||||
INPUTS = ["tools/fixtures/_adpcm.py", "src/Formats/codecs/audio/Adpcm", "src/Formats/audio/adpcm"]
|
||||
RATE = 22050
|
||||
|
||||
|
||||
def aiff_ssnd(d):
|
||||
p = 12
|
||||
while p + 8 <= len(d):
|
||||
cid, size = d[p:p + 4], struct.unpack_from(">I", d, p + 4)[0]
|
||||
if cid == b"SSND":
|
||||
off = struct.unpack_from(">I", d, p + 8)[0]
|
||||
return d[p + 16 + off:p + 8 + size]
|
||||
p += 8 + size + (size & 1)
|
||||
raise ValueError("no SSND")
|
||||
|
||||
|
||||
def wav_data(d):
|
||||
p = 12
|
||||
fmt = None
|
||||
while p + 8 <= len(d):
|
||||
cid, size = d[p:p + 4], struct.unpack_from("<I", d, p + 4)[0]
|
||||
if cid == b"fmt ":
|
||||
fmt = d[p + 8:p + 8 + size]
|
||||
elif cid == b"data":
|
||||
return fmt, d[p + 8:p + 8 + size]
|
||||
p += 8 + size + (size & 1)
|
||||
raise ValueError("no data")
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
stereo = A.signal("music", RATE, 2, 5000, seed=7)
|
||||
mono = A.signal("sweep", RATE, 1, 4100, seed=8)
|
||||
w2, w1 = A.wav(stereo, RATE, 2), A.wav(mono, RATE, 1)
|
||||
codec, raw = [], []
|
||||
|
||||
# ADX (ffmpeg writes version 3; vgmstream is the reference: CRI's scale + 1)
|
||||
for name, w, ch in (("adx-mono", w1, 1), ("adx-stereo", w2, 2)):
|
||||
f = D.ffencode(ctx, w, ["-c:a", "adpcm_adx", "-f", "adx"], "adx")
|
||||
start = struct.unpack_from(">H", f, 2)[0] + 4
|
||||
rate, frames, cutoff, ver = struct.unpack_from(">IIHH", f, 8)
|
||||
_, rch, ref = D.vgdecode(ctx, f, "adx")
|
||||
assert rch == ch and len(ref) == frames * ch * 2, (len(ref), frames)
|
||||
codec.append(dict(name=name, kind="adx", data=f[start:], ch=ch, frames=frames, ref=ref, rate=rate,
|
||||
cutoff=cutoff, v3=ver == 0x0300))
|
||||
|
||||
# PS-ADPCM in a VAG (mono)
|
||||
v = D.vag(mono, RATE)
|
||||
_, _, ref = D.vgdecode(ctx, v, "vag")
|
||||
codec.append(dict(name="psx", kind="psx", data=v[0x30:], ch=1, frames=len(ref) // 2, ref=ref))
|
||||
raw.append(dict(name="psx", codec="psx", data=v[0x30:], rate=RATE, ch=1, ref=ref))
|
||||
|
||||
# DSP in a mono BRSTM (one block holds everything)
|
||||
ints = D.s16(mono)
|
||||
dspdata = D.dsp_encode(ints)
|
||||
f = D.rstm(mono, RATE, 1, "RSTM", block=(len(dspdata) + 31) // 32 * 32)
|
||||
_, _, ref = D.vgdecode(ctx, f, "brstm")
|
||||
assert len(ref) == len(ints) * 2
|
||||
codec.append(dict(name="dsp", kind="dsp", data=dspdata, ch=1, frames=len(ints), ref=ref, coefs=D.DSP_COEFS))
|
||||
|
||||
# Apple ima4 (AIFF-C)
|
||||
for name, w, ch in (("ima_qt-mono", w1, 1), ("ima_qt-stereo", w2, 2)):
|
||||
f = D.ffencode(ctx, w, ["-c:a", "adpcm_ima_qt", "-f", "aiff"], "aiff")
|
||||
data = aiff_ssnd(f)
|
||||
ref = D.ffs16(ctx, f, "aiff")
|
||||
codec.append(dict(name=name, kind="ima_qt", data=data, ch=ch, frames=len(ref) // (2 * ch), ref=ref))
|
||||
raw.append(dict(name=name, codec="ima_qt", data=data, rate=RATE, ch=ch, ref=ref))
|
||||
|
||||
# IMA nibble streams (KVAG, high nibble first)
|
||||
for name, sig, ch in (("ima-mono", mono, 1), ("ima-stereo", stereo, 2)):
|
||||
f = D.kvag(sig, RATE, ch)
|
||||
ref = D.ffs16(ctx, f, "vag", fmt="kvag")
|
||||
codec.append(dict(name=name, kind="ima", data=f[14:], ch=ch, frames=len(ref) // (2 * ch), ref=ref))
|
||||
raw.append(dict(name=name, codec="ima", data=f[14:], rate=RATE, ch=ch, ref=ref))
|
||||
|
||||
# MS ADPCM / IMA WAV blocks (ffmpeg), as raw block streams
|
||||
for name, codec_, w, ch in (("ms-stereo", "adpcm_ms", w2, 2), ("ms-mono", "adpcm_ms", w1, 1),
|
||||
("ima_wav-stereo", "adpcm_ima_wav", w2, 2)):
|
||||
f = D.ffencode(ctx, w, ["-c:a", codec_, "-f", "wav"], "wav")
|
||||
fmt, data = wav_data(f)
|
||||
ba = struct.unpack_from("<H", fmt, 12)[0]
|
||||
ref = D.ffs16(ctx, f, "wav")
|
||||
raw.append(dict(name=name, codec="ms" if codec_ == "adpcm_ms" else "ima_wav", data=data, rate=RATE, ch=ch,
|
||||
blockAlign=ba, ref=ref))
|
||||
|
||||
ctx.emit("adpcm_codec", codec)
|
||||
ctx.emit("adpcm_raw", raw)
|
||||
|
||||
# our encoder (audio/adpcm) -> containers ffmpeg reads -> ffmpeg's decode; the test decodes the same bytes itself
|
||||
A.emit_signal(ctx, "adpcm_sig", stereo, RATE, 2)
|
||||
ours = []
|
||||
for codec_, opts in (("ima", '{ codec = "ima" }'), ("ms", '{ codec = "ms", blockAlign = 512 }'),
|
||||
("ima_wav", '{ codec = "ima_wav", blockAlign = 512 }')):
|
||||
data = A.encode_luau(ctx, "audio/adpcm", "adpcm_sig", opts)
|
||||
if codec_ == "ima":
|
||||
f = b"KVAG" + struct.pack("<IIH", len(data), RATE, 1) + data
|
||||
ref = D.ffs16(ctx, f, "vag", fmt="kvag")
|
||||
else:
|
||||
ba = 512
|
||||
spb = (ba - 7 * 2) * 2 // 2 + 2 if codec_ == "ms" else (ba - 8) + 1
|
||||
if codec_ == "ms":
|
||||
coefs = b"".join(struct.pack("<hh", a, b) for a, b in zip([256, 512, 0, 192, 240, 460, 392], [0, -256, 0, 64, 0, -208, -232]))
|
||||
ext = struct.pack("<HH", spb, 7) + coefs
|
||||
fmt = struct.pack("<HHIIHHH", 2, 2, RATE, RATE * ba // spb, ba, 4, len(ext)) + ext
|
||||
else:
|
||||
fmt = struct.pack("<HHIIHHHH", 0x11, 2, RATE, RATE * ba // spb, ba, 4, 2, spb)
|
||||
body = b"WAVE" + b"fmt " + struct.pack("<I", len(fmt)) + fmt + b"data" + struct.pack("<I", len(data)) + data
|
||||
f = b"RIFF" + struct.pack("<I", len(body)) + body
|
||||
ref = D.ffs16(ctx, f, "wav")
|
||||
ours.append(dict(name=codec_, opts=opts, data=data, ref=ref))
|
||||
ctx.emit("adpcm_ours", ours)
|
||||
@@ -0,0 +1,69 @@
|
||||
# CRI ADX fixtures (tools/fixtures.py): audio/adx. vgmstream is the reference decoder (CRI's scale + 1 and version 3
|
||||
# rounding; ffmpeg's ADX decoder differs a little on both).
|
||||
# tests/gen/adx_cases.luau { name, data, rate, ch, frames, ref (vgmstream s16le), loopStart?, loopEnd? }
|
||||
# ffmpeg -f adx files (version 3, mono / stereo), and a version 4 file rebuilt around ffmpeg's frames with an
|
||||
# initial history and loop points (vgmstream -m reports the loop)
|
||||
# tests/gen/adx_ours.luau our encoder's files (run in this step) with vgmstream's decode and loop report
|
||||
# tests/gen/adx_sig.luau the encoder input
|
||||
import importlib.util, os, re, struct
|
||||
|
||||
_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def _load(name):
|
||||
spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
A = _load("_audio")
|
||||
D = _load("_adpcm")
|
||||
|
||||
INPUTS = ["tools/fixtures/_adpcm.py", "src/Formats/codecs/audio/Adpcm", "src/Formats/audio/adx"]
|
||||
|
||||
|
||||
def loops(info):
|
||||
m = re.search(r"loop start: (\d+) samples.*?loop end: (\d+) samples", info, re.S)
|
||||
return (int(m.group(1)), int(m.group(2))) if m else None
|
||||
|
||||
|
||||
def case(ctx, name, data):
|
||||
rate, ch, ref = D.vgdecode(ctx, data, "adx")
|
||||
e = dict(name=name, data=data, rate=rate, ch=ch, frames=len(ref) // (2 * ch), ref=ref)
|
||||
lp = loops(D.vginfo(ctx, data, "adx"))
|
||||
if lp:
|
||||
e["loopStart"], e["loopEnd"] = lp
|
||||
return e
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for name, rate, ch, kind in (("ffmpeg-mono-22k", 22050, 1, "sweep"), ("ffmpeg-stereo-44k", 44100, 2, "music"),
|
||||
("ffmpeg-stereo-32k", 32000, 2, "sine")):
|
||||
sig = A.signal(kind, rate, ch, 7000, seed=ch)
|
||||
f = D.ffencode(ctx, A.wav(sig, rate, ch), ["-c:a", "adpcm_adx", "-f", "adx"], "adx")
|
||||
cases.append(case(ctx, name, f))
|
||||
# version 4 with history and loops, around the stereo frames
|
||||
f = cases[1]["data"]
|
||||
start = struct.unpack_from(">H", f, 2)[0] + 4
|
||||
frames_ = f[start:]
|
||||
rate, n = struct.unpack_from(">II", f, 8)
|
||||
head = bytearray(f[:0x14])
|
||||
struct.pack_into(">H", head, 0x12, 0x0400)
|
||||
head += b"\0" * 4 + struct.pack(">hhhh", 300, -200, -150, 90) # 0x14 flags, 0x18 history (2 channels)
|
||||
head += struct.pack(">HHIIIII", 0, 1, 1, 1024, 0, 6000, 0)
|
||||
newstart = len(head) + 6
|
||||
struct.pack_into(">H", head, 2, newstart - 4)
|
||||
cases.append(case(ctx, "v4-hist-loop", bytes(head) + b"(c)CRI" + frames_))
|
||||
ctx.emit("adx_cases", cases)
|
||||
|
||||
sig = A.signal("music", 32000, 2, 9000, seed=11)
|
||||
A.emit_signal(ctx, "adx_sig", sig, 32000, 2)
|
||||
ours = []
|
||||
for name, opts in (("plain", "nil"), ("loop", "{ loop = { start = 1000, stop = 8000 } }")):
|
||||
data = A.encode_luau(ctx, "audio/adx", "adx_sig", opts)
|
||||
e = case(ctx, name, data)
|
||||
e["opts"] = opts
|
||||
ours.append(e)
|
||||
ctx.emit("adx_ours", ours)
|
||||
@@ -10,7 +10,7 @@ _spec = importlib.util.spec_from_file_location("_audio", os.path.join(os.path.di
|
||||
A = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(A)
|
||||
|
||||
INPUTS = ["src/Formats/audio/aiff", "src/Formats/codecs/audio/Pcm"]
|
||||
INPUTS = ["src/Formats/audio/aiff", "src/Formats/codecs/audio/Pcm", "src/Formats/codecs/audio/Adpcm"]
|
||||
|
||||
|
||||
def ff(codec, src="{in}", extra=()):
|
||||
@@ -34,6 +34,8 @@ def generate(ctx):
|
||||
("sox-aiff-s16", "sox", ["sox", "{in}", "-t", "aiff", "{out}"]),
|
||||
("sox-aiff-s24-mono", "sox", ["sox", "{in_mono}", "-b", "24", "-t", "aiff", "{out}"]),
|
||||
("sox-aifc-s16", "sox", ["sox", "{in}", "-t", "aifc", "{out}"]),
|
||||
("ffmpeg-ima4", "ffmpeg", ff("adpcm_ima_qt")),
|
||||
("ffmpeg-ima4-mono", "ffmpeg", ff("adpcm_ima_qt", "{in_mono}")),
|
||||
]
|
||||
encodes = [
|
||||
("s16", "nil", 2),
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# Nintendo stream fixtures (tools/fixtures.py): audio/brstm. Our Python writer and DSP encoder (tools/fixtures/_adpcm.py)
|
||||
# build BRSTM / BCSTM / BFSTM files (DSP ADPCM with a filled ADPC / SEEK history table, PCM16, PCM8; several blocks
|
||||
# with a short padded last block; loops); vgmstream decodes them and reports the loops.
|
||||
# tests/gen/brstm_cases.luau { name, data, rate, ch, ref (s16le), loopStart?, loopEnd? }
|
||||
import importlib.util, os, re
|
||||
|
||||
_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def _load(name):
|
||||
spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
A = _load("_audio")
|
||||
D = _load("_adpcm")
|
||||
|
||||
INPUTS = ["tools/fixtures/_adpcm.py", "src/Formats/codecs/audio/Adpcm", "src/Formats/audio/brstm"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
stereo = A.signal("music", 32000, 2, 9000, seed=31)
|
||||
mono = A.signal("sweep", 22050, 1, 8000, seed=32)
|
||||
made = [
|
||||
("rstm-dsp-stereo", "RSTM", stereo, 32000, 2, dict(block=0x800)),
|
||||
("rstm-dsp-mono-loop", "RSTM", mono, 22050, 1, dict(block=0x400, loop=(1000, 8000))),
|
||||
("rstm-pcm16-stereo", "RSTM", stereo, 32000, 2, dict(block=0x2000, codec="pcm16")),
|
||||
("cstm-dsp-stereo-loop", "CSTM", stereo, 32000, 2, dict(block=0x800, loop=(4000, 9000))),
|
||||
("cstm-pcm8-mono", "CSTM", mono, 22050, 1, dict(block=0x1000, codec="pcm8")),
|
||||
("fstm-be-dsp-stereo", "FSTM", stereo, 32000, 2, dict(block=0x1000)),
|
||||
("fstm-le-dsp-mono", "FSTM", mono, 22050, 1, dict(block=0x800, le=True)),
|
||||
("fstm-le-pcm16-stereo", "FSTM", stereo, 32000, 2, dict(block=0x1000, le=True, codec="pcm16")),
|
||||
]
|
||||
cases = []
|
||||
for name, kind, sig, rate, ch, kw in made:
|
||||
data = D.rstm(sig, rate, ch, kind, **kw)
|
||||
ext = {"RSTM": "brstm", "CSTM": "bcstm", "FSTM": "bfstm"}[kind]
|
||||
r, c, ref = D.vgdecode(ctx, data, ext)
|
||||
assert (r, c) == (rate, ch) and len(ref) == len(sig) * 2, (name, r, c, len(ref))
|
||||
e = dict(name=name, data=data, rate=rate, ch=ch, ref=ref)
|
||||
m = re.search(r"loop start: (\d+) samples.*?loop end: (\d+) samples", D.vginfo(ctx, data, ext), re.S)
|
||||
if m:
|
||||
e["loopStart"], e["loopEnd"] = int(m.group(1)), int(m.group(2))
|
||||
cases.append(e)
|
||||
ctx.emit("brstm_cases", cases)
|
||||
@@ -0,0 +1,27 @@
|
||||
# CAF IMA4 fixtures (tools/fixtures.py): audio/caf's Apple IMA ADPCM (codecs/audio/Adpcm), written and decoded by ffmpeg.
|
||||
# tests/gen/caf_ima4.luau { name, data, rate, ch, ref (ffmpeg s16le) }
|
||||
import importlib.util, os
|
||||
|
||||
_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def _load(name):
|
||||
spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
A = _load("_audio")
|
||||
D = _load("_adpcm")
|
||||
|
||||
INPUTS = ["src/Formats/codecs/audio/Adpcm", "src/Formats/audio/caf"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for name, kind, rate, ch, frames in (("ima4-stereo", "music", 44100, 2, 9000), ("ima4-mono", "sweep", 22050, 1, 4410)):
|
||||
sig = A.signal(kind, rate, ch, frames, seed=ch + 50)
|
||||
data = D.ffencode(ctx, A.wav(sig, rate, ch), ["-c:a", "adpcm_ima_qt"], "caf")
|
||||
cases.append(dict(name=name, data=data, rate=rate, ch=ch, ref=D.ffs16(ctx, data, "caf")))
|
||||
ctx.emit("caf_ima4", cases)
|
||||
@@ -0,0 +1,48 @@
|
||||
# QOA fixtures (tools/fixtures.py): audio/qoa and codecs/audio/Qoa. The reference is qoa.h itself
|
||||
# (tests/fixtures/qoa/qoa.h, MIT, compiled here with nix gcc through tests/fixtures/qoa/qoa_ref.c) plus ffmpeg's decoder.
|
||||
# tests/gen/qoa_cases.luau { name, data (qoa.h's encoding of the signal), rate, ch, ref (ffmpeg s16le),
|
||||
# qoaref (qoa.h's decode, s16le), sig (the signal module name) }
|
||||
# tests/gen/qoa_sig_*.luau the signals (our encoder must write the same bytes as qoa.h)
|
||||
import importlib.util, os, shutil, struct, subprocess, tempfile
|
||||
|
||||
_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def _load(name):
|
||||
spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
A = _load("_audio")
|
||||
D = _load("_adpcm")
|
||||
|
||||
INPUTS = ["tests/fixtures/qoa", "src/Formats/codecs/audio/Qoa"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
work = tempfile.mkdtemp(prefix="fmt-qoa-")
|
||||
try:
|
||||
exe = os.path.join(work, "qoa_ref")
|
||||
ctx.nix("gcc", ["gcc", "-O2", "-o", exe, os.path.join(ctx.root, "tests/fixtures/qoa/qoa_ref.c")])
|
||||
cases = []
|
||||
for name, kind, rate, ch, frames in (("stereo-44k", "music", 44100, 2, 12000), ("mono-22k", "sweep", 22050, 1, 5120),
|
||||
("6ch-48k", "sine", 48000, 6, 700), ("loud-mono", "loud", 8000, 1, 5121),
|
||||
("square-stereo", "square", 32000, 2, 6000)):
|
||||
sig = A.signal(kind, rate, ch, frames, seed=len(cases) + 40)
|
||||
mod = "qoa_sig_" + name.replace("-", "_")
|
||||
A.emit_signal(ctx, mod, sig, rate, ch)
|
||||
raw = os.path.join(work, "in.raw")
|
||||
with open(raw, "wb") as f:
|
||||
f.write(struct.pack("<%dh" % len(sig), *D.s16(sig)))
|
||||
qoa = os.path.join(work, "out.qoa")
|
||||
subprocess.run([exe, "enc", str(ch), str(rate), raw, qoa], check=True)
|
||||
data = open(qoa, "rb").read()
|
||||
dec = os.path.join(work, "dec.raw")
|
||||
subprocess.run([exe, "dec", qoa, dec], check=True, capture_output=True)
|
||||
ref = D.ffs16(ctx, data, "qoa")
|
||||
cases.append(dict(name=name, data=data, rate=rate, ch=ch, ref=ref, qoaref=open(dec, "rb").read(), sig=mod))
|
||||
ctx.emit("qoa_cases", cases)
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
@@ -0,0 +1,55 @@
|
||||
# Sony VAG / KVAG fixtures (tools/fixtures.py): audio/vag. Our Python PS-ADPCM / IMA encoders (tools/fixtures/_adpcm.py)
|
||||
# write the files; vgmstream decodes VAGp / VAGi (and reports the loops), ffmpeg decodes KVAG (adpcm_ima_ssi).
|
||||
# tests/gen/vag_cases.luau { name, data, rate, ch, ref (s16le), loopStart?, loopEnd?, title? }
|
||||
# tests/gen/vag_ours.luau our encoder's files (run in this step) as vgmstream decodes them
|
||||
# tests/gen/vag_sig.luau / vag_sig1.luau the encoder inputs (stereo / mono)
|
||||
import importlib.util, os, re
|
||||
|
||||
_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def _load(name):
|
||||
spec = importlib.util.spec_from_file_location(name, os.path.join(_dir, name + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
A = _load("_audio")
|
||||
D = _load("_adpcm")
|
||||
|
||||
INPUTS = ["tools/fixtures/_adpcm.py", "src/Formats/codecs/audio/Adpcm", "src/Formats/audio/vag"]
|
||||
|
||||
|
||||
def vgcase(ctx, name, data, **extra):
|
||||
rate, ch, ref = D.vgdecode(ctx, data, "vag")
|
||||
e = dict(name=name, data=data, rate=rate, ch=ch, ref=ref, **extra)
|
||||
m = re.search(r"loop start: (\d+) samples.*?loop end: (\d+) samples", D.vginfo(ctx, data, "vag"), re.S)
|
||||
if m:
|
||||
e["loopStart"], e["loopEnd"] = int(m.group(1)), int(m.group(2))
|
||||
return e
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
mono = A.signal("music", 22050, 1, 6000, seed=21)
|
||||
stereo = A.signal("sine", 32000, 2, 5000, seed=22)
|
||||
cases = [
|
||||
vgcase(ctx, "vagp-mono", D.vag(mono, 22050, b"Mono Song"), title="Mono Song"),
|
||||
vgcase(ctx, "vagp-loop", D.vag(mono, 22050, loop=(20, 150))),
|
||||
vgcase(ctx, "vagi-stereo", D.vagi(stereo, 32000)),
|
||||
]
|
||||
for name, sig, ch, rate in (("kvag-mono", mono, 1, 22050), ("kvag-stereo", stereo, 2, 32000)):
|
||||
f = D.kvag(sig, rate, ch)
|
||||
cases.append(dict(name=name, data=f, rate=rate, ch=ch, ref=D.ffs16(ctx, f, "vag", fmt="kvag")))
|
||||
ctx.emit("vag_cases", cases)
|
||||
|
||||
A.emit_signal(ctx, "vag_sig", stereo, 32000, 2)
|
||||
A.emit_signal(ctx, "vag_sig1", mono, 22050, 1)
|
||||
ours = []
|
||||
for name, sigmod, opts in (("mono", "vag_sig1", "nil"), ("mono-loop", "vag_sig1", "{ loop = { start = 600, stop = 5000 } }"),
|
||||
("stereo", "vag_sig", "nil")):
|
||||
data = A.encode_luau(ctx, "audio/vag", sigmod, opts)
|
||||
e = vgcase(ctx, name, data)
|
||||
e["opts"] = opts
|
||||
ours.append(e)
|
||||
ctx.emit("vag_ours", ours)
|
||||
+30
-1
@@ -159,9 +159,38 @@ def song_effects(linear=True):
|
||||
return T.write_xm("effects", instruments(), [0, 1], [a, b], 6, speed=5, tempo=130, linear=linear, restart=1)
|
||||
|
||||
|
||||
TABLE = [0, 1, 2, 4, 8, 16, 32, 64, -1, -2, -4, -8, -16, -32, -64, -128]
|
||||
|
||||
|
||||
def modplug_adpcm(raw):
|
||||
"""ModPlug ADPCM of 8-bit sample bytes: the delta table, then one nibble per sample (low first), each nibble the
|
||||
table delta that lands nearest (the running value wraps as a signed byte)"""
|
||||
cur, nibs = 0, []
|
||||
for b in raw:
|
||||
want = b - 256 if b >= 128 else b
|
||||
best = min(range(16), key=lambda k: abs(((cur + TABLE[k] + 128) % 256 - 128) - want))
|
||||
cur = (cur + TABLE[best] + 128) % 256 - 128
|
||||
nibs.append(best)
|
||||
if len(nibs) % 2:
|
||||
nibs.append(0)
|
||||
return bytes(t & 255 for t in TABLE) + bytes(nibs[i] | nibs[i + 1] << 4 for i in range(0, len(nibs), 2))
|
||||
|
||||
|
||||
def song_adpcm():
|
||||
"""a ModPlug ADPCM sample (OpenMPT's compressed 8-bit samples) played at a few pitches"""
|
||||
raw = T.s8(T.synth("saw", 400, 100, 0.6))
|
||||
smp = {"name": "adpcm", "data": raw, "adpcm": modplug_adpcm(raw), "volume": 64, "pan": 128, "loop": (0, 400, 1)}
|
||||
p = empty(2)
|
||||
for i, note in enumerate((49, 53, 56, 61)):
|
||||
put(p, i * 8, 0, note, 1)
|
||||
put(p, i * 8 + 4, 1, note - 12, 1)
|
||||
return T.write_xm("adpcm", [{"name": "adpcm", "samples": [smp]}], [0], [p], 2, speed=4, tempo=125)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for nm, data in (("instruments", song_instruments()), ("effects", song_effects()), ("amiga", song_effects(False))):
|
||||
for nm, data in (("instruments", song_instruments()), ("effects", song_effects()), ("amiga", song_effects(False)),
|
||||
("adpcm", song_adpcm())):
|
||||
ref = T.reference(ctx, data, "xm")
|
||||
cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]})
|
||||
ctx.emit("xm_cases", cases)
|
||||
Reference in new issue
Block a user