merge ws/audio2
This commit is contained in:
commit
f0a23eb676
149 files changed
+23004
-312
No files matched your search
@@ -1538,3 +1538,201 @@ do
|
||||
Exr.encode(img)
|
||||
end)
|
||||
end
|
||||
-- ------------------------------------------------------------------------------------------- ws-video2-legacy: fps
|
||||
do
|
||||
-- the legacy codecs (codecs/video/Legacy) through F.video.open, rgba8 frames out: ffmpeg's encoders at 320x240
|
||||
-- (tools/fixtures/legacy.py), a 320x200 FLC (fli.py) and a 320x200 SMK4 (smk.py, textured: mostly FULL blocks);
|
||||
-- frames per second of the whole decode (and the Smacker audio track, seconds of audio per second)
|
||||
local F = require("@formats")
|
||||
local LB = require("@tests/gen/legacy_bench")
|
||||
local cases = table.clone(LB)
|
||||
table.insert(cases, { name = "fli.flc", data = require("@tests/gen/fli_bench").data, width = 320, height = 200 })
|
||||
table.insert(cases, { name = "smk4.smk", data = require("@tests/gen/smk_bench").data, width = 320, height = 200 })
|
||||
for _, c in cases do
|
||||
local data = buffer.fromstring(c.data)
|
||||
local frames = 0
|
||||
local dt = math.huge
|
||||
for _ = 1, 3 do
|
||||
local t0 = os.clock()
|
||||
local v = assert(F.video.open(data, { audio = false }))
|
||||
frames = 0
|
||||
while v:nextFrame() do
|
||||
frames += 1
|
||||
end
|
||||
dt = math.min(dt, os.clock() - t0)
|
||||
end
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, string.format("legacy %s %dx%d", c.name, c.width, c.height), dt * 1000 / frames, frames / dt))
|
||||
end
|
||||
local v = assert(F.video.open(buffer.fromstring(require("@tests/gen/smk_bench").data)))
|
||||
local a = assert(v.audio)
|
||||
local t0 = os.clock()
|
||||
local n = 0
|
||||
while true do
|
||||
local _, got = a:read(4096)
|
||||
if got == 0 then
|
||||
break
|
||||
end
|
||||
n += got
|
||||
end
|
||||
local dt = os.clock() - t0
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1fx real time", runtime, "smacker audio 22 kHz stereo", dt * 1000, n / a.sampleRate / dt))
|
||||
end
|
||||
-- ws-audio2: chip/midi
|
||||
do
|
||||
-- AHX / HVL (codecs/audio/Hively): a whole song rendered at 44.1 kHz (tools/fixtures/ahx.py karma.ahx, 3 s; hvl.py
|
||||
-- the 6-channel demo with ring modulation); MB/s of stereo f32 output, and how many times faster than real time
|
||||
local Ahx, Hvl = require("@formats/music/ahx"), require("@formats/music/hvl")
|
||||
local AC, HC = require("@tests/gen/ahx_cases"), require("@tests/gen/hvl_cases")
|
||||
for _, spec in { { Ahx, AC, "karma.ahx", "ahx render karma (4 ch)" }, { Hvl, HC, "demo", "hvl render demo (6 ch)" } } do
|
||||
for _, c in spec[2] do
|
||||
if c.name == spec[3] then
|
||||
local song = assert(spec[1].decode(Bytes.reader(buffer.fromstring(c.data))))
|
||||
local frames = 0
|
||||
local dt = bench(spec[4], 3, c.frames * 8, function()
|
||||
local dec = song:render({ maxDuration = c.maxDuration })
|
||||
frames = dec.frames
|
||||
dec:read(frames)
|
||||
end)
|
||||
print(string.format("%-8s %-30s %8.1f x real time", runtime, "", frames / 44100 / dt))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- ws-audio2: lossy
|
||||
do
|
||||
-- Musepack (codecs/audio/Musepack) SV8 / SV7 and AC-3 5.1 (codecs/audio/Ac3): whole-file decodes, MB/s of f32 output
|
||||
-- (tools/fixtures/mpc.py: 1.2 s of 44.1 kHz stereo at quality 5; tools/fixtures/ac3.py: 0.16 s of 48 kHz 5.1 at
|
||||
-- 448 kbps, decoded 4 times per run)
|
||||
local Mpc = require("@formats/audio/mpc")
|
||||
local MpcFx = require("@tests/gen/mpc_cases")
|
||||
local Ac3F = require("@formats/audio/ac3")
|
||||
local Ac3Fx = require("@tests/gen/ac3_cases")
|
||||
for _, c in MpcFx do
|
||||
if c.name == "sv8_q5_stereo" or c.name == "sv7_q5_stereo" then
|
||||
local b = buffer.fromstring(c.data)
|
||||
bench("mpc " .. c.name, 5, c.frames * c.channels * 4, function()
|
||||
assert(Mpc.decode(Bytes.reader(b)))
|
||||
end)
|
||||
end
|
||||
end
|
||||
for _, c in Ac3Fx do
|
||||
if c.name == "5.1_448" then
|
||||
local b = buffer.fromstring(c.data)
|
||||
bench("ac3 5.1 448 kbps", 5, c.frames * c.channels * 4 * 4, function()
|
||||
for _ = 1, 4 do
|
||||
assert(Ac3F.decode(Bytes.reader(b)))
|
||||
end
|
||||
end)
|
||||
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
|
||||
-- ws-audio2: lossless
|
||||
do
|
||||
-- WavPack / Monkey's Audio / TTA decoders (tools/fixtures/wavpack.py, ape.py, tta.py): MB/s of f32 output
|
||||
local function lossless(label: string, mod: any, data: string)
|
||||
local b = buffer.fromstring(data)
|
||||
local dec = assert(mod.open(Bytes.reader(b)))
|
||||
bench(label, 5, dec.frames * dec.channels * 4, function()
|
||||
mod.decode(Bytes.reader(b))
|
||||
end)
|
||||
end
|
||||
local Wv = require("@formats/audio/wavpack")
|
||||
for _, c in require("@tests/gen/wavpack_cases") do
|
||||
if c.name == "s16_long" or c.name == "s16_hh" or c.name == "s24_hh" or c.name == "f32" or c.name == "hyb_b3" then
|
||||
lossless("wavpack " .. c.name, Wv, c.data)
|
||||
end
|
||||
end
|
||||
local ApeF = require("@formats/audio/ape")
|
||||
for _, c in require("@tests/gen/ape_cases") do
|
||||
if c.name == "s16_long" or c.name == "s16_long_c4000" or c.name == "s16_c5000" or c.name == "s24" or c.name == "s16_c1000" then
|
||||
lossless("ape " .. c.name, ApeF, c.data)
|
||||
end
|
||||
end
|
||||
local TtaF = require("@formats/audio/tta")
|
||||
for _, c in require("@tests/gen/tta_cases") do
|
||||
if c.name == "s16_long" or c.name == "s24" or c.name == "ch6" then
|
||||
lossless("tta " .. c.name, TtaF, c.data)
|
||||
end
|
||||
end
|
||||
end
|
||||
-- ws-audio2: trackers
|
||||
do
|
||||
-- the other tracker loaders on the shared engine: a 669 (Hz periods, auto slides) and an MMD1 (hold / decay
|
||||
-- envelopes, instruments) from tools/fixtures/{669,med}.py, decoded and rendered at 44.1 kHz
|
||||
local Six69 = require("@formats/music/669")
|
||||
local Med = require("@formats/music/med")
|
||||
local songs = { { Six69, require("@tests/gen/669_cases")[1].data }, { Med, require("@tests/gen/med_cases")[2].data } }
|
||||
local best, frames = math.huge, 0
|
||||
local out = buffer.create(4096 * 8)
|
||||
for _ = 1, 3 do
|
||||
frames = 0
|
||||
local t0 = os.clock()
|
||||
for _, s in songs do
|
||||
local dec = (s[1].decode(Bytes.reader(buffer.fromstring(s[2]))) :: any):render()
|
||||
while true do
|
||||
local _, n = dec:read(4096, out)
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
frames += n
|
||||
end
|
||||
end
|
||||
best = math.min(best, os.clock() - t0)
|
||||
end
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1f x realtime", runtime, "render 669 / med", best * 1000, frames / 44100 / best))
|
||||
end
|
||||
@@ -0,0 +1,94 @@
|
||||
# 669 fixtures (tools/fixtures.py): generated Composer 669 / UNIS 669 modules exercising the effects, rendered by
|
||||
# openmpt123.
|
||||
# tests/gen/669_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py),
|
||||
# duration (openmpt's song length) }
|
||||
import os, sys
|
||||
|
||||
# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
|
||||
T = sys.modules.get("_tracker")
|
||||
if T is None:
|
||||
import importlib.util
|
||||
_spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py"))
|
||||
T = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["_tracker"] = T
|
||||
_spec.loader.exec_module(T)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tracker.py"]
|
||||
|
||||
|
||||
def empty():
|
||||
return [[(0, 0, None, None) for _ in range(8)] for _ in range(64)]
|
||||
|
||||
|
||||
def put(p, row, ch, note=0, ins=0, vol=None, cmd=None, param=0):
|
||||
p[row][ch] = (note, ins, vol, None if cmd is None else (cmd << 4) | param)
|
||||
|
||||
|
||||
def samples():
|
||||
return [
|
||||
{"name": "sine", "data": T.u8(T.synth("sine", 64, 64)), "loop": (0, 64)},
|
||||
{"name": "square", "data": T.u8(T.synth("square", 64, 64, 0.5)), "loop": (0, 64)},
|
||||
{"name": "saw", "data": T.u8(T.synth("saw", 100, 100, 0.6)), "loop": (0, 100)},
|
||||
{"name": "noise", "data": T.u8(T.synth("noise", 6000, 1, 0.7, decay=1500))},
|
||||
{"name": "tri", "data": T.u8(T.synth("tri", 50, 50, 0.8)), "loop": (0, 50)},
|
||||
]
|
||||
|
||||
|
||||
def song_effects(keep=None):
|
||||
a, b = empty(), empty()
|
||||
mel = [61, 65, 68, 73, 68, 65, 63, 61]
|
||||
for i in range(16):
|
||||
put(a, i * 4, 0, mel[i % 8], 1, 15)
|
||||
put(a, 0, 1, 49, 2, 12)
|
||||
put(a, 8, 1, 0, 0, None, 0, 2) # auto portamento up (runs until the next effect)
|
||||
put(a, 16, 1, 0, 0, None, 1, 3) # auto portamento down
|
||||
put(a, 24, 1, 0, 0, None, 5, 3) # speed (stops the auto slide)
|
||||
put(a, 28, 1, 56, 2, 10)
|
||||
put(a, 32, 1, 61, 2, None, 2, 2) # tone portamento (keeps going)
|
||||
put(a, 40, 1, 49, 2, None, 2, 4)
|
||||
put(a, 48, 1, 0, 0, 6, 3, 5) # frequency adjust
|
||||
put(a, 52, 1, 0, 0, None, 4, 3) # frequency vibrato
|
||||
for r in range(0, 64, 8):
|
||||
put(a, r, 3, 61, 4, 15 - r // 8)
|
||||
put(a, 4, 2, 37, 3, 15)
|
||||
put(a, 36, 2, 0, 0, 4)
|
||||
put(a, 10, 4, 73, 5, 9)
|
||||
put(a, 20, 4, 0, 0, None, 4, 6)
|
||||
# b: speed per pattern, a break row, more slides
|
||||
put(b, 0, 0, 49, 1, 15)
|
||||
put(b, 4, 0, 0, 0, None, 1, 1)
|
||||
put(b, 12, 0, 61, 1, 15)
|
||||
put(b, 16, 0, 0, 0, None, 0, 1)
|
||||
put(b, 20, 0, 0, 0, 10, None)
|
||||
put(b, 0, 2, 37, 3, 12)
|
||||
put(b, 8, 2, 44, 3, None, 2, 1)
|
||||
put(b, 24, 2, 0, 0, None, 3, 2)
|
||||
put(b, 0, 5, 56, 5, 13)
|
||||
put(b, 16, 5, 52, 2, 13)
|
||||
if keep is not None:
|
||||
for p in (a, b):
|
||||
for row in p:
|
||||
for ch in range(8):
|
||||
if ch not in keep:
|
||||
row[ch] = (0, 0, None, None)
|
||||
return T.write_669("effects 669", samples(), [0, 1], [a, b], [4, 3], [63, 40])
|
||||
|
||||
|
||||
def song_unis():
|
||||
"""UNIS 669: balance slides, slot retrigger, a restart position"""
|
||||
a = empty()
|
||||
put(a, 0, 0, 61, 1, 15, 6, 0) # balance slide left (repeats until the next note)
|
||||
put(a, 16, 0, 64, 1, 15, 6, 1) # right
|
||||
put(a, 32, 1, 49, 4, 15, 7, 3) # slot retrigger
|
||||
put(a, 40, 1, 49, 4, 15, 7, 6)
|
||||
put(a, 8, 2, 68, 2, 11)
|
||||
put(a, 48, 3, 56, 3, 14)
|
||||
return T.write_669("unis", samples(), [0, 0], [a], [5], [63], extended=True)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for nm, data in (("effects", song_effects()), ("unis", song_unis())):
|
||||
ref = T.reference(ctx, data, "669")
|
||||
cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]})
|
||||
ctx.emit("669_cases", cases)
|
||||
@@ -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
|
||||
@@ -0,0 +1,205 @@
|
||||
# AHX / HVL fixture helpers (not a generator; tools/fixtures/ahx.py and hvl.py load it): small writers for both module
|
||||
# formats (the layouts hvl2wav's replay.c reads), hand-made and random songs exercising the waveforms, filters, square
|
||||
# modulation, PList commands, effects, ring modulation and panning, and the reference render through hvl2wav
|
||||
# (nixpkgs#hivelytracker). hvl2wav on Linux is built with -D_BIG_ENDIAN_ and so byte-swaps every 16-bit sample it
|
||||
# writes: the swap is undone here. Songs from the HivelyTracker source tree (Songs/, BSD-3) add real-world cases.
|
||||
import os, struct, subprocess, tempfile
|
||||
|
||||
AHX_FX = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 12: 6, 15: 7}
|
||||
|
||||
|
||||
def ins_header(ins):
|
||||
a = ins.get("env", (1, 64, 10, 48, 10, 10, 0))
|
||||
fs = ins.get("filter_speed", 0)
|
||||
vib = ins.get("vib", (0, 0, 0))
|
||||
hc = ins.get("hardcut", (0, 0))
|
||||
sq = ins.get("square", (0x20, 0x3f, 1))
|
||||
return bytes([
|
||||
ins.get("volume", 64), ((fs & 0x1f) << 3) | ins.get("wavelen", 3),
|
||||
a[0], a[1], a[2], a[3], a[4], a[5], a[6], 0, 0, 0,
|
||||
((fs & 0x20) << 2) | ins.get("filter_lower", 1), vib[0], (0x80 if hc[0] else 0) | ((hc[1] & 7) << 4) | (vib[2] & 15), vib[1],
|
||||
sq[0], sq[1], sq[2], ins.get("filter_upper", 0x3f), ins.get("plist_speed", 1), len(ins.get("plist", [])),
|
||||
])
|
||||
|
||||
|
||||
def names(song):
|
||||
return b"".join(s.encode("latin-1") + b"\0" for s in [song.get("title", "")] + [i.get("name", "") for i in song["instruments"]])
|
||||
|
||||
|
||||
def header_common(song):
|
||||
posn = len(song["positions"])
|
||||
flag6 = (0x80 if song.get("empty_track0") else 0) | ((song.get("speedmult", 1) - 1) << 5) | (posn >> 8)
|
||||
return flag6, posn
|
||||
|
||||
|
||||
def write_ahx(song):
|
||||
trkl = song["trkl"]
|
||||
tracks = song["tracks"]
|
||||
flag6, posn = header_common(song)
|
||||
body = b"".join(struct.pack(">H", s) for s in song.get("subsongs", []))
|
||||
for pos in song["positions"]:
|
||||
for tr, tp in pos:
|
||||
body += bytes([tr, tp & 0xff])
|
||||
for i, t in enumerate(tracks):
|
||||
if i == 0 and song.get("empty_track0"):
|
||||
continue
|
||||
for j in range(trkl):
|
||||
note, ins, fx, par = (t[j] + (0, 0, 0, 0))[:4] if j < len(t) else (0, 0, 0, 0)
|
||||
body += bytes([(note << 2) | (ins >> 4), ((ins & 15) << 4) | fx, par])
|
||||
for ins in song["instruments"]:
|
||||
body += ins_header(ins)
|
||||
for (note, fixed, wave, fx0, p0, fx1, p1) in ins.get("plist", []):
|
||||
body += bytes([(AHX_FX[fx1] << 5) | (AHX_FX[fx0] << 2) | (wave >> 1), ((wave & 1) << 7) | (fixed << 6) | note, p0, p1])
|
||||
nameat = 14 + len(body)
|
||||
hdr = b"THX" + bytes([song.get("version", 1)]) + struct.pack(">HBBHBBBB", nameat, flag6, posn & 0xff,
|
||||
song.get("restart", 0), trkl, len(tracks) - 1,
|
||||
len(song["instruments"]), len(song.get("subsongs", [])))
|
||||
return hdr + body + names(song)
|
||||
|
||||
|
||||
def write_hvl(song):
|
||||
trkl = song["trkl"]
|
||||
tracks = song["tracks"]
|
||||
ch = song["channels"]
|
||||
flag6, posn = header_common(song)
|
||||
restart = song.get("restart", 0)
|
||||
body = b"".join(struct.pack(">H", s) for s in song.get("subsongs", []))
|
||||
for pos in song["positions"]:
|
||||
for tr, tp in pos:
|
||||
body += bytes([tr, tp & 0xff])
|
||||
for i, t in enumerate(tracks):
|
||||
if i == 0 and song.get("empty_track0"):
|
||||
continue
|
||||
for j in range(trkl):
|
||||
row = (tuple(t[j]) + (0,) * 6)[:6] if j < len(t) else (0,) * 6
|
||||
if row == (0,) * 6 and j % 3 == 0:
|
||||
body += b"\x3f" # the one-byte empty step (sometimes: both encodings are valid)
|
||||
else:
|
||||
note, ins, fx, par, fxb, parb = row
|
||||
body += bytes([note, ins, (fx << 4) | fxb, par, parb])
|
||||
for ins in song["instruments"]:
|
||||
body += ins_header(ins)
|
||||
for (note, fixed, wave, fx0, p0, fx1, p1) in ins.get("plist", []):
|
||||
body += bytes([fx0, (fx1 << 3) | wave, (fixed << 6) | note, p0, p1])
|
||||
nameat = 16 + len(body)
|
||||
hdr = b"HVL" + bytes([song.get("version", 1)]) + struct.pack(">HBBBBBBBBBB", nameat, flag6, posn & 0xff,
|
||||
((ch - 4) << 2) | (restart >> 8), restart & 0xff, trkl,
|
||||
len(tracks) - 1, len(song["instruments"]),
|
||||
len(song.get("subsongs", [])), song.get("mixgain", 100),
|
||||
song.get("stereo", 2))
|
||||
return hdr + body + names(song)
|
||||
|
||||
|
||||
def hvl2wav(ctx, data, ext, args=()):
|
||||
"""the reference render: (s16le interleaved stereo bytes, frames)"""
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
src = os.path.join(d, "song." + ext)
|
||||
out = os.path.join(d, "out.wav")
|
||||
with open(src, "wb") as f:
|
||||
f.write(data)
|
||||
ctx.nix("hivelytracker", ["hvl2wav", "-o" + out] + list(args) + [src])
|
||||
raw = open(out, "rb").read()
|
||||
assert raw[:4] == b"RIFF" and raw[36:40] == b"data", "hvl2wav: unexpected wav"
|
||||
pcm = bytearray(raw[44:])
|
||||
pcm[0::2], pcm[1::2] = pcm[1::2], pcm[0::2] # undo the -D_BIG_ENDIAN_ byte swap
|
||||
return bytes(pcm), len(pcm) // 4
|
||||
|
||||
|
||||
def source_songs(ctx):
|
||||
"""{name: bytes} from the HivelyTracker source's Songs/ directory"""
|
||||
path = subprocess.run(["nix", "build", "nixpkgs#hivelytracker.src", "--no-link", "--print-out-paths"],
|
||||
capture_output=True, check=True).stdout.decode().strip()
|
||||
songs = {}
|
||||
for f in sorted(os.listdir(os.path.join(path, "Songs"))):
|
||||
with open(os.path.join(path, "Songs", f), "rb") as fh:
|
||||
songs[f] = fh.read()
|
||||
return songs
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------- songs
|
||||
def instruments(hvl):
|
||||
"""a set exercising every waveform, the filter and square sweeps and the PList commands"""
|
||||
ins = [
|
||||
# 1: triangle lead with vibrato and a filter set (cmd 0) + perf slide up (cmd 1)
|
||||
dict(name="tri", wavelen=4, env=(2, 64, 8, 40, 20, 12, 0), vib=(6, 3, 4), plist_speed=2,
|
||||
plist=[(0, 0, 1, 0, 0x18, 1, 2), (0, 0, 0, 2, 3, 0, 0), (0, 0, 0, 12, 0x30, 0, 0)]),
|
||||
# 2: sawtooth with the filter sweep (cmd 4 high nibble) and fixed notes
|
||||
dict(name="saw", wavelen=5, filter_speed=3, filter_lower=8, filter_upper=50, env=(1, 64, 20, 30, 10, 20, 0),
|
||||
plist_speed=3, plist=[(1, 0, 2, 4, 0x10, 0, 0), (25, 1, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0)]),
|
||||
# 3: square with modulation (cmd 4 low nibble, cmd 3 offset), hard cut release
|
||||
dict(name="square", wavelen=3, square=(0x08, 0x38, 2), hardcut=(1, 3), env=(3, 50, 6, 40, 30, 8, 10),
|
||||
plist_speed=1, plist=[(0, 0, 3, 3, 0x20, 4, 0x01), (0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 15, 4, 0, 0),
|
||||
(0, 0, 0, 5, 1, 0, 0)]),
|
||||
# 4: noise drum: fixed note, falling filter, volume steps (cmd C)
|
||||
dict(name="noise", wavelen=2, env=(1, 64, 4, 20, 2, 6, 0), filter_speed=1, filter_lower=1, filter_upper=40,
|
||||
plist_speed=1, plist=[(40, 1, 4, 12, 0x40, 4, 0xf0), (30, 1, 0, 12, 0x20, 0, 0), (20, 1, 1, 0, 0, 0, 0)]),
|
||||
# 5: square + filter toggles together (cmd 4 0xff: negative directions), perf slide down
|
||||
dict(name="pwm", wavelen=5, square=(0x3f, 0x10, 1), filter_speed=5, filter_lower=20, filter_upper=60,
|
||||
env=(4, 60, 10, 50, 40, 10, 0), plist_speed=2,
|
||||
plist=[(0, 0, 3, 4, 0xff, 2, 4), (0, 0, 0, 0, 0, 1, 1), (12, 0, 2, 3, 0x10, 0, 0)]),
|
||||
]
|
||||
if hvl:
|
||||
# 6: ring modulation (cmd 7 triangle relative / cmd 8 saw fixed) and PList panning (cmd 9)
|
||||
ins.append(dict(name="ring", wavelen=4, env=(1, 64, 10, 48, 20, 10, 0), plist_speed=2,
|
||||
plist=[(0, 0, 2, 7, 0x8c, 9, 0x40), (0, 0, 0, 8, 0x20, 0, 0), (0, 0, 3, 7, 0x85, 9, 0xc0),
|
||||
(0, 0, 0, 7, 0, 0, 0)]))
|
||||
return ins
|
||||
|
||||
|
||||
def demo_song(hvl):
|
||||
"""hand-written: notes on every instrument and the main effects"""
|
||||
E = []
|
||||
t1 = [(25, 1), (), (27, 0, 0xA, 0x02), (), (29, 2, 0x1, 0x04), (), (0, 0, 0x2, 0x04), (), (30, 3), (), (0, 0, 0xE, 0x13),
|
||||
(32, 4), (25, 5, 0xC, 0x30), (), (37, 1, 0x3, 0x08), (0, 0, 0x4, 0x50)]
|
||||
t2 = [(13, 4), (), (13, 4, 0xE, 0xD2), (), (20, 3, 0x9, 0x10), (), (13, 4, 0xE, 0xC2), (), (13, 2, 0xE, 0xA4), (),
|
||||
(15, 2, 0xE, 0x24), (), (13, 4, 0xC, 0x60), (), (17, 5, 0x5, 0x31), ()]
|
||||
t3 = [(37, 2), (), (), (), (39, 1, 0xE, 0x44), (), (), (), (41, 5), (), (), (), (36, 3, 0xF, 0x04), (), (), (0, 0, 0xD, 0x00)]
|
||||
if hvl:
|
||||
t2 = [r + ((0x7, 0x30) if len(r) == 4 else ()) if r else r for r in t2]
|
||||
t1[0] = (25, 6, 0x7, 0xd0, 0x1, 0x01)
|
||||
t3[4] = (39, 6, 0xE, 0x44, 0xC, 0x20)
|
||||
tracks = [E, t1, t2, t3]
|
||||
ch = 6 if hvl else 4
|
||||
pos = []
|
||||
for k in range(2):
|
||||
row = [(1, 0), (2, 0), (3, k * 2), (0, 0)]
|
||||
if hvl:
|
||||
row += [(3, -12), (1, 5)]
|
||||
pos.append(row)
|
||||
return dict(title="demo", trkl=16, tracks=tracks, positions=pos, channels=ch, instruments=instruments(hvl),
|
||||
empty_track0=True, mixgain=110, stereo=3, subsongs=[1])
|
||||
|
||||
|
||||
def random_song(rng, hvl, n_tracks=6, trkl=16, n_pos=3):
|
||||
ins = instruments(hvl)
|
||||
ch = rng.choice([4, 5, 8]) if hvl else 4
|
||||
fxs = [0x1, 0x2, 0x3, 0x4, 0x5, 0x9, 0xA, 0xC, 0xE] + ([0x7] if hvl else [])
|
||||
tracks = [[]]
|
||||
for _ in range(n_tracks):
|
||||
t = []
|
||||
for _ in range(trkl):
|
||||
r = rng.random()
|
||||
if r < 0.45:
|
||||
t.append(())
|
||||
continue
|
||||
note = rng.randint(1, 60) if rng.random() < 0.8 else 0
|
||||
inst = rng.randint(1, len(ins)) if rng.random() < 0.7 else 0
|
||||
fx, par = 0, 0
|
||||
if rng.random() < 0.5:
|
||||
fx = rng.choice(fxs)
|
||||
par = rng.randint(0, 255)
|
||||
if fx == 0xE:
|
||||
par = rng.choice([0x1, 0x2, 0x4, 0xA, 0xB, 0xC, 0xD]) << 4 | rng.randint(0, 5)
|
||||
if fx == 0xC:
|
||||
par = rng.choice([rng.randint(0, 0x40), 0x50 + rng.randint(0, 0x40), 0xa0 + rng.randint(0, 0x40)])
|
||||
if fx == 0x4:
|
||||
par = rng.randint(0x41, 0x7f) if rng.random() < 0.6 else rng.randint(1, 0x3f)
|
||||
row = (note, inst, fx, par)
|
||||
if hvl and rng.random() < 0.3:
|
||||
row += (rng.choice([0x1, 0x2, 0xA, 0xC, 0x7]), rng.randint(0, 0x40))
|
||||
t.append(row)
|
||||
tracks.append(t)
|
||||
pos = [[(rng.randint(0, n_tracks), rng.randint(-5, 5)) for _ in range(ch)] for _ in range(n_pos)]
|
||||
return dict(title="random", trkl=trkl, tracks=tracks, positions=pos, channels=ch, instruments=ins,
|
||||
speedmult=rng.choice([1, 1, 2, 3]), mixgain=rng.choice([80, 100, 140]), stereo=rng.randint(0, 4),
|
||||
version=rng.choice([0, 1, 2]) if not hvl else 1)
|
||||
@@ -0,0 +1,320 @@
|
||||
# MIDI-variant fixture helpers (not a generator; tools/fixtures/mus.py, xmi.py and hmp.py load it): small writers for
|
||||
# Doom MUS, Miles XMIDI and HMI HMP, random event streams, and the reference conversion through wildmidi -x
|
||||
# (nixpkgs#wildmidi: it writes a Standard MIDI File; only its event stream is used, read back by the small SMF reader
|
||||
# below into channel events with times in seconds).
|
||||
import os, random, struct, subprocess, tempfile
|
||||
|
||||
|
||||
def vlq(v):
|
||||
out = [v & 127]
|
||||
v >>= 7
|
||||
while v:
|
||||
out.insert(0, (v & 127) | 128)
|
||||
v >>= 7
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def vlq_hmp(v):
|
||||
"""HMP deltas: 7-bit groups least significant first, the last byte has bit 7 set"""
|
||||
out = []
|
||||
while True:
|
||||
b = v & 127
|
||||
v >>= 7
|
||||
if v == 0:
|
||||
out.append(b | 128)
|
||||
return bytes(out)
|
||||
out.append(b)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------- MUS
|
||||
def write_mus(events, instruments=(), primary=4, secondary=0):
|
||||
"""events: [(delay_after, type, channel, data bytes)]; the last flag is set when delay_after > 0"""
|
||||
score = b""
|
||||
for delay, typ, ch, data in events:
|
||||
score += bytes([(0x80 if delay else 0) | (typ << 4) | ch]) + bytes(data)
|
||||
if delay:
|
||||
score += vlq(delay)
|
||||
hdr_len = 16 + 2 * len(instruments)
|
||||
hdr = b"MUS\x1a" + struct.pack("<HHHHHH", len(score), hdr_len, primary, secondary, len(instruments), 0)
|
||||
hdr += b"".join(struct.pack("<H", i) for i in instruments)
|
||||
return hdr + score
|
||||
|
||||
|
||||
def random_mus(rng, n=120, extras=0):
|
||||
"""a random score; extras > 0 inserts that many system events (type 3, which wildmidi misreads: it takes two data
|
||||
bytes) and measure ends (type 5, which wildmidi refuses), each with no delay, without changing anything else"""
|
||||
ev = []
|
||||
held = {}
|
||||
for ch in [0, 1, 2, 15]:
|
||||
ev.append((0, 4, ch, [0, rng.randint(0, 127) if ch != 15 else 0])) # program change
|
||||
for _ in range(n):
|
||||
ch = rng.choice([0, 1, 2, 3, 15, 9])
|
||||
r = rng.random()
|
||||
delay = rng.choice([0, 0, 1, 5, 17, 140, 200])
|
||||
if r < 0.45:
|
||||
note = rng.randint(30, 90)
|
||||
if rng.random() < 0.6:
|
||||
ev.append((delay, 1, ch, [note | 0x80, rng.randint(1, 127)]))
|
||||
else:
|
||||
ev.append((delay, 1, ch, [note]))
|
||||
held.setdefault(ch, []).append(note)
|
||||
elif r < 0.75 and held.get(ch):
|
||||
ev.append((delay, 0, ch, [held[ch].pop(0)]))
|
||||
elif r < 0.85:
|
||||
ev.append((delay, 2, ch, [rng.randint(0, 255)]))
|
||||
else:
|
||||
ev.append((delay, 4, ch, [rng.randint(0, 9), rng.randint(0, 127)]))
|
||||
for ch, notes in held.items():
|
||||
for nt in notes:
|
||||
ev.append((3, 0, ch, [nt]))
|
||||
xr = random.Random(extras)
|
||||
for _ in range(extras):
|
||||
at = xr.randint(1, len(ev) - 1)
|
||||
ch = ev[at][2]
|
||||
ev.insert(at, (0, 5, ch, []) if xr.random() < 0.5 else (0, 3, ch, [xr.choice([10, 11, 12, 13, 14])]))
|
||||
ev.append((0, 6, 0, []))
|
||||
return write_mus(ev, instruments=[1, 30, 128 + 7])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------- XMI
|
||||
def iff(cid, body):
|
||||
return cid + struct.pack(">I", len(body)) + body + (b"\0" if len(body) % 2 else b"")
|
||||
|
||||
|
||||
def xmi_events(events):
|
||||
"""events: [(delay, bytes)]: a delay is written as interval bytes (each <= 0x7F) before the event"""
|
||||
out = b""
|
||||
for delay, ev in events:
|
||||
while delay > 0x7f:
|
||||
out += b"\x7f"
|
||||
delay -= 0x7f
|
||||
if delay:
|
||||
out += bytes([delay])
|
||||
out += ev
|
||||
return out
|
||||
|
||||
|
||||
def write_xmi(songs, with_xdir=True, timb=True):
|
||||
forms = []
|
||||
for evs in songs:
|
||||
body = b"XMID"
|
||||
if timb:
|
||||
body += iff(b"TIMB", struct.pack("<H", 2) + bytes([0, 0, 30, 0]))
|
||||
body += iff(b"EVNT", xmi_events(evs))
|
||||
forms.append(iff(b"FORM", body))
|
||||
if not with_xdir:
|
||||
return forms[0]
|
||||
xdir = iff(b"FORM", b"XDIR" + iff(b"INFO", struct.pack("<H", len(songs))))
|
||||
return xdir + iff(b"CAT ", b"XMID" + b"".join(forms))
|
||||
|
||||
|
||||
def random_xmi_song(rng, n=100, tempo=None):
|
||||
ev = [(0, bytes([0xC0 | c, rng.randint(0, 127)])) for c in (0, 1, 2)]
|
||||
if tempo:
|
||||
ev.append((0, b"\xff\x51\x03" + tempo.to_bytes(3, "big")))
|
||||
ev.append((0, b"\xff\x01\x05hello"))
|
||||
for _ in range(n):
|
||||
delay = rng.choice([0, 0, 3, 12, 30, 60, 200])
|
||||
ch = rng.choice([0, 1, 2, 9])
|
||||
r = rng.random()
|
||||
if r < 0.6:
|
||||
ev.append((delay, bytes([0x90 | ch, rng.randint(30, 90), rng.randint(1, 127)]) + vlq(rng.choice([1, 10, 30, 60, 150, 300]))))
|
||||
elif r < 0.75:
|
||||
ev.append((delay, bytes([0xB0 | ch, rng.choice([1, 7, 10, 11, 64]), rng.randint(0, 127)])))
|
||||
elif r < 0.85:
|
||||
ev.append((delay, bytes([0xE0 | ch, rng.randint(0, 127), rng.randint(0, 127)])))
|
||||
elif r < 0.9:
|
||||
ev.append((delay, bytes([0xC0 | ch, rng.randint(0, 127)])))
|
||||
elif r < 0.95:
|
||||
ev.append((delay, bytes([0xD0 | ch, rng.randint(0, 127)])))
|
||||
else:
|
||||
ev.append((delay, b"\xf0" + vlq(3) + b"\x7e\x7f\xf7"))
|
||||
ev.append((rng.randint(0, 50), b"\xff\x2f\x00"))
|
||||
return ev
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------- HMP
|
||||
def write_hmp(tracks, bpm=120, new=False):
|
||||
"""tracks: [bytes of event data (deltas already in HMP form)]"""
|
||||
head = (b"HMIMIDIP013195" if new else b"HMIMIDIP").ljust(32, b"\0")
|
||||
start = 0x388 if new else 0x308
|
||||
chunks = b""
|
||||
for i, data in enumerate(tracks):
|
||||
chunks += struct.pack("<III", i, len(data) + 12, i) + data
|
||||
body = struct.pack("<I", start + len(chunks)) + b"\0" * 12 + struct.pack("<IIII", len(tracks), 0, bpm, 0)
|
||||
out = head + body
|
||||
return out + b"\0" * (start - len(out)) + chunks
|
||||
|
||||
|
||||
def hmp_track(events):
|
||||
"""events: [(delta, bytes)] -> HMP track data (ends with an end-of-track meta)"""
|
||||
return b"".join(vlq_hmp(d) + e for d, e in events)
|
||||
|
||||
|
||||
def random_hmp_tracks(rng, ntracks=3, n=60, running=True):
|
||||
tracks = [hmp_track([(0, b"\xff\x2f\x00")])] # track 0: tempo / meta only, as in game files
|
||||
for t in range(1, ntracks):
|
||||
ch = t - 1 if t < 4 else 9
|
||||
ev = [(0, bytes([0xC0 | ch, rng.randint(0, 127)]))]
|
||||
on = []
|
||||
running_ok, running = running, False
|
||||
for _ in range(n):
|
||||
d = rng.choice([0, 0, 5, 30, 60, 120, 400])
|
||||
r = rng.random()
|
||||
if r < 0.5:
|
||||
note = rng.randint(30, 90)
|
||||
on.append(note)
|
||||
# running status (status byte left out) now and then
|
||||
ev.append((d, (b"" if running else bytes([0x90 | ch])) + bytes([note, rng.randint(1, 127)])))
|
||||
running = running_ok and rng.random() < 0.5
|
||||
elif r < 0.8 and on:
|
||||
ev.append((d, bytes([0x80 | ch, on.pop(0), 64])))
|
||||
running = False
|
||||
elif r < 0.9:
|
||||
ev.append((d, bytes([0xB0 | ch, rng.choice([7, 10, 64]), rng.randint(0, 127)])))
|
||||
running = False
|
||||
else:
|
||||
ev.append((d, bytes([0xE0 | ch, rng.randint(0, 127), rng.randint(0, 127)])))
|
||||
running = False
|
||||
for note in on:
|
||||
ev.append((10, bytes([0x80 | ch, note, 0])))
|
||||
ev.append((0, b"\xff\x2f\x00"))
|
||||
tracks.append(hmp_track(ev))
|
||||
return tracks
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------- wildmidi
|
||||
def read_smf(data):
|
||||
"""-> (division, [(tick, track, status, d1, d2)] channel events, [(tick, us)] tempos); format 2: track 1 only (its
|
||||
first song: wildmidi writes every XMIDI song as a track of a format 2 file)"""
|
||||
assert data[:4] == b"MThd"
|
||||
fmt, ntrk, div = struct.unpack(">HHH", data[8:14])
|
||||
if fmt == 2:
|
||||
ntrk = 1
|
||||
p = 8 + struct.unpack(">I", data[4:8])[0]
|
||||
events, tempos = [], []
|
||||
for ti in range(ntrk):
|
||||
assert data[p:p + 4] == b"MTrk"
|
||||
n = struct.unpack(">I", data[p + 4:p + 8])[0]
|
||||
q, e = p + 8, p + 8 + n
|
||||
tick, run = 0, 0
|
||||
while q < e:
|
||||
d = 0
|
||||
while True:
|
||||
c = data[q]
|
||||
q += 1
|
||||
d = d * 128 + (c & 127)
|
||||
if c < 128:
|
||||
break
|
||||
tick += d
|
||||
st = data[q]
|
||||
if st < 0x80:
|
||||
st = run
|
||||
else:
|
||||
q += 1
|
||||
if st == 0xFF:
|
||||
typ = data[q]
|
||||
q += 1
|
||||
ln = 0
|
||||
while True:
|
||||
c = data[q]
|
||||
q += 1
|
||||
ln = ln * 128 + (c & 127)
|
||||
if c < 128:
|
||||
break
|
||||
if typ == 0x51:
|
||||
tempos.append((tick, int.from_bytes(data[q:q + 3], "big")))
|
||||
q += ln
|
||||
elif st in (0xF0, 0xF7):
|
||||
ln = 0
|
||||
while True:
|
||||
c = data[q]
|
||||
q += 1
|
||||
ln = ln * 128 + (c & 127)
|
||||
if c < 128:
|
||||
break
|
||||
q += ln
|
||||
else:
|
||||
run = st
|
||||
k = 1 if st >> 4 in (0xC, 0xD) else 2
|
||||
d1 = data[q]
|
||||
d2 = data[q + 1] if k == 2 else 0
|
||||
q += k
|
||||
events.append((tick, ti, st, d1, d2))
|
||||
p = e
|
||||
return div, events, tempos
|
||||
|
||||
|
||||
def seconds(div, tempos, tick):
|
||||
tempos = sorted(tempos)
|
||||
t, last, us = 0.0, 0, 500000
|
||||
for tk, u in tempos:
|
||||
if tk >= tick:
|
||||
break
|
||||
t += (tk - last) * us / 1e6 / div
|
||||
last, us = tk, u
|
||||
return t + (tick - last) * us / 1e6 / div
|
||||
|
||||
|
||||
def wildmidi(ctx, data, ext, args=()):
|
||||
"""the reference: wildmidi -x's SMF as { division, tempo (first), events = { {time, status, d1, d2} } }"""
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
src = os.path.join(d, "in." + ext)
|
||||
out = os.path.join(d, "out.mid")
|
||||
with open(src, "wb") as f:
|
||||
f.write(data)
|
||||
r = subprocess.run(["nix", "shell", "nixpkgs#wildmidi", "-c", "wildmidi"] + list(args) + ["-x", out, src],
|
||||
capture_output=True)
|
||||
if not os.path.exists(out):
|
||||
raise RuntimeError("wildmidi failed: " + r.stdout.decode(errors="replace")[-400:] + r.stderr.decode(errors="replace")[-400:])
|
||||
smf = open(out, "rb").read()
|
||||
div, events, tempos = read_smf(smf)
|
||||
events.sort(key=lambda e: (e[0], e[1]))
|
||||
return {"division": div, "tempo": tempos[0][1] if tempos else 500000,
|
||||
"events": [[seconds(div, tempos, tk), st, d1, d2] for tk, _, st, d1, d2 in events]}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------- HMI
|
||||
def write_hmi(tracks, bpm=120):
|
||||
"""tracks: [bytes of event data (MIDI deltas; note-ons followed by a duration)]"""
|
||||
hdr_len = 0x5B
|
||||
head = bytearray(b"HMI-MIDISONG061595".ljust(370, b"\0"))
|
||||
head[212] = bpm
|
||||
head[228] = len(tracks)
|
||||
table = b""
|
||||
body = b""
|
||||
at = 370 + 4 * len(tracks)
|
||||
for data in tracks:
|
||||
table += struct.pack("<I", at + len(body))
|
||||
th = bytearray(b"HMI-MIDITRACK".ljust(hdr_len, b"\0"))
|
||||
th[0x57:0x5B] = struct.pack("<I", hdr_len)
|
||||
body += bytes(th) + data
|
||||
return bytes(head) + table + body
|
||||
|
||||
|
||||
def random_hmi_tracks(rng, ntracks=3, n=50):
|
||||
tracks = []
|
||||
for t in range(ntracks):
|
||||
ch = t if t < 3 else 9
|
||||
ev = vlq(0) + bytes([0xC0 | ch, rng.randint(0, 127)])
|
||||
ev += vlq(0) + b"\xfe\x15\x00\x00\x00\x00\x00\x00" # an HMI-only event (8 bytes)
|
||||
ev += vlq(0) + b"\xfe\x10\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00" # FE 10 with a 3-byte payload: 12 bytes
|
||||
running = False
|
||||
for _ in range(n):
|
||||
d = rng.choice([0, 0, 5, 30, 60, 120])
|
||||
r = rng.random()
|
||||
if r < 0.6:
|
||||
ev += vlq(d) + (b"" if running else bytes([0x90 | ch])) + bytes([rng.randint(30, 90), rng.randint(1, 127)])
|
||||
ev += vlq(rng.choice([1, 10, 40, 100, 300]))
|
||||
running = rng.random() < 0.5
|
||||
elif r < 0.8:
|
||||
ev += vlq(d) + bytes([0xB0 | ch, rng.choice([7, 10, 64]), rng.randint(0, 127)])
|
||||
running = False
|
||||
elif r < 0.9:
|
||||
ev += vlq(d) + b"\xfe\x01\x00\x00" # a plain 4-byte FE event
|
||||
else:
|
||||
ev += vlq(d) + bytes([0xE0 | ch, rng.randint(0, 127), rng.randint(0, 127)])
|
||||
running = False
|
||||
ev += vlq(rng.randint(0, 40)) + b"\xff\x2f\x00"
|
||||
tracks.append(ev)
|
||||
return tracks
|
||||
+439
-2
@@ -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)
|
||||
|
||||
|
||||
@@ -493,3 +494,439 @@ def reference(ctx, data, ext, extra=()):
|
||||
f = features(left, right)
|
||||
f["duration"] = duration(ctx, data, ext)
|
||||
return f
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- other trackers
|
||||
# (ws-audio2: MTM, 669, STM, ULT, OKT, MED, PTM, FAR, UMX writers for tools/fixtures/{mtm,669,...}.py)
|
||||
def write_mtm(title, samples, orders, patterns, channels, pans=None, rows=64, comment=b""):
|
||||
"""samples: [{name, data (raw unsigned bytes; 16-bit: little-endian unsigned), bits 8|16, volume 0..64,
|
||||
finetune -8..7, loop: (start, end) in bytes | None}]; patterns: [[row: [(note, ins, fx, param)] * channels] * rows]
|
||||
with note 0 = none else our note (1 = C-0; 49 = C-4 plays at 8363 Hz; >= 25)"""
|
||||
tracks, index = [], {}
|
||||
table = []
|
||||
for pat in patterns:
|
||||
ids = []
|
||||
for ch in range(32):
|
||||
if ch >= channels:
|
||||
ids.append(0)
|
||||
continue
|
||||
tb = bytearray()
|
||||
for r in range(rows):
|
||||
note, ins, fx, param = pat[r][ch] if r < len(pat) else (0, 0, 0, 0)
|
||||
n = note - 25 if note else 0
|
||||
tb += bytes([(n << 2) | (ins >> 4), ((ins & 15) << 4) | fx, param])
|
||||
tb = bytes(tb) + b"\0" * (192 - len(tb))
|
||||
if not any(tb):
|
||||
ids.append(0)
|
||||
continue
|
||||
if tb not in index:
|
||||
tracks.append(tb)
|
||||
index[tb] = len(tracks)
|
||||
ids.append(index[tb])
|
||||
table.append(ids)
|
||||
out = bytearray(b"MTM\x10" + name(title, 20))
|
||||
out += struct.pack("<HBBHBBBB", len(tracks), len(patterns) - 1, len(orders) - 1, len(comment), len(samples), 0, rows,
|
||||
channels)
|
||||
pp = list(pans or [(i % 2) * 15 for i in range(channels)])
|
||||
out += bytes(pp + [0] * (32 - len(pp)))
|
||||
for s in samples:
|
||||
ls, le = s.get("loop") or (0, 0)
|
||||
out += name(s.get("name", ""), 22) + struct.pack("<IIIbBB", len(s["data"]), ls, le, s.get("finetune", 0),
|
||||
s.get("volume", 64), 1 if s.get("bits", 8) == 16 else 0)
|
||||
out += bytes(orders) + b"\0" * (128 - len(orders))
|
||||
for tb in tracks:
|
||||
out += tb
|
||||
for ids in table:
|
||||
out += b"".join(struct.pack("<H", t) for t in ids)
|
||||
out += comment
|
||||
for s in samples:
|
||||
out += s["data"]
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def u16(xs):
|
||||
return b"".join(struct.pack("<H", max(0, min(65535, int(round(x * 32767)) + 32768))) for x in xs)
|
||||
|
||||
|
||||
def write_669(message, samples, orders, patterns, tempos, breaks, restart=0, extended=False):
|
||||
"""samples: [{name, data (unsigned bytes), loop: (start, end) | None}]; patterns: [[row: [(note, ins, vol, effect)]
|
||||
* 8] * 64] with note 0 = none else our note (>= 37), ins 1-based, vol 0..15 or None, effect byte (cmd << 4 | param)
|
||||
or None; tempos / breaks: per pattern"""
|
||||
out = bytearray(b"JN" if extended else b"if")
|
||||
msg = message.encode()[:108]
|
||||
out += msg + b" " * (108 - len(msg))
|
||||
out += bytes([len(samples), len(patterns), restart])
|
||||
out += bytes(orders) + b"\xff" * (128 - len(orders))
|
||||
out += bytes(tempos) + b"\x04" * (128 - len(tempos))
|
||||
out += bytes(breaks) + b"\x3f" * (128 - len(breaks))
|
||||
for s in samples:
|
||||
ls, le = s.get("loop") or (0, 0xFFFFF)
|
||||
out += name(s.get("name", ""), 13) + struct.pack("<III", len(s["data"]), ls, le)
|
||||
for pat in patterns:
|
||||
for row in pat:
|
||||
for (note, ins, vol, eff) in row:
|
||||
if note:
|
||||
n, i = note - 37, ins - 1
|
||||
out += bytes([(n << 2) | (i >> 4), ((i & 15) << 4) | (vol if vol is not None else 0)])
|
||||
elif vol is not None:
|
||||
out += bytes([0xFE, vol])
|
||||
else:
|
||||
out += b"\xff\x00"
|
||||
out.append(0xFF if eff is None else eff)
|
||||
for s in samples:
|
||||
out += s["data"]
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def write_stm(title, samples, orders, patterns, tempo=0x60, gvol=64, minor=21):
|
||||
"""samples: [{name, data (signed bytes), volume, c2spd, loop: (start, end) | None}] (up to 31); patterns: [[row:
|
||||
[(note, ins, vol, cmd, info)] * 4] * 64] with note 0 = none, 254 = cut, else our note (>= 37); vol None = none;
|
||||
cmd 0 = none (A = 1, letters as in S3M)"""
|
||||
head = bytearray(name(title, 20) + b"!Scream!" + bytes([0x1A, 2, 2, minor, tempo, len(patterns), gvol]) + b"\0" * 13)
|
||||
smp_at = len(head)
|
||||
head += b"\0" * (31 * 32)
|
||||
head += bytes(orders) + bytes([99] * ((64 if minor == 0 else 128) - len(orders)))
|
||||
for pat in patterns:
|
||||
for row in pat:
|
||||
for (note, ins, vol, cmd, info) in row:
|
||||
if note in ("skip", "fb"):
|
||||
head.append(0xFC if note == "skip" else 0xFB) # nothing / a C-0 at volume 0
|
||||
continue
|
||||
if note == 254:
|
||||
nb = 0xFE
|
||||
elif note:
|
||||
n = note - 37
|
||||
nb = (n // 12) << 4 | (n % 12)
|
||||
else:
|
||||
nb = 0xFF
|
||||
v = 65 if vol is None else vol
|
||||
head += bytes([nb, (ins << 3) | (v & 7), ((v >> 3) << 4) | cmd, info])
|
||||
body = head
|
||||
for i in range(31):
|
||||
h = bytearray(32)
|
||||
if i < len(samples):
|
||||
s = samples[i]
|
||||
while len(body) % 16:
|
||||
body.append(0)
|
||||
off = len(body) // 16
|
||||
body += s["data"]
|
||||
ls, le = s.get("loop") or (0, 0xFFFF)
|
||||
h[0:12] = name(s.get("name", ""), 12)
|
||||
struct.pack_into("<HHHHBBH", h, 14, off, len(s["data"]), ls, le, s.get("volume", 64), 0, s.get("c2spd", 8363))
|
||||
else:
|
||||
struct.pack_into("<HHHH", h, 14, 0, 0, 0, 0xFFFF)
|
||||
body[smp_at + 32 * i:smp_at + 32 * i + 32] = h
|
||||
return bytes(body)
|
||||
|
||||
|
||||
def write_ult(title, samples, orders, patterns, channels, version=4, pans=None, message=b""):
|
||||
"""samples: [{name, data (signed bytes; 16-bit little-endian), bits 8|16, volume 0..255, speed (c2spd / 2... the
|
||||
file's C-4 rate), finetune, loop: (start, end) in frames | None, pingpong}]; patterns: [[row: [(note, ins, e1, p1,
|
||||
e2, p2)] * channels] * 64] with note 0 = none else our note (25..120), e1 / e2 effect nibbles (low / high nibble of
|
||||
the effect byte); repeated identical events are run-length packed"""
|
||||
out = bytearray(b"MAS_UTrack_V00" + bytes([0x30 + version]) + name(title, 32).replace(b"\0", b" "))
|
||||
out.append(len(message) // 32)
|
||||
out += message
|
||||
out.append(len(samples))
|
||||
pos = 0
|
||||
for s in samples:
|
||||
bps = 2 if s.get("bits", 8) == 16 else 1
|
||||
n = len(s["data"]) // bps
|
||||
ls, le = s.get("loop") or (0, 0)
|
||||
fl = (4 if bps == 2 else 0) | (8 if s.get("loop") else 0) | (16 if s.get("pingpong") else 0)
|
||||
out += name(s.get("name", ""), 32) + name(s.get("name", "")[:8] + ".smp", 12)
|
||||
out += struct.pack("<IIIIBB", ls * bps, le * bps, pos, pos + n, s.get("volume", 255), fl)
|
||||
if version >= 4:
|
||||
out += struct.pack("<Hh", s.get("speed", 8363), s.get("finetune", 0))
|
||||
else:
|
||||
out += struct.pack("<h", s.get("finetune", 0))
|
||||
pos += n
|
||||
out += bytes(orders) + b"\xff" * (256 - len(orders))
|
||||
out += bytes([channels - 1, len(patterns) - 1])
|
||||
if version >= 3:
|
||||
out += bytes(pans or [(i % 2) * 15 for i in range(channels)])
|
||||
for ch in range(channels):
|
||||
for pat in patterns:
|
||||
evs = []
|
||||
for row in pat:
|
||||
note, ins, e1, p1, e2, p2 = row[ch]
|
||||
evs.append(bytes([note - 24 if note else 0, ins, (e2 << 4) | e1, p1, p2]))
|
||||
i = 0
|
||||
while i < len(evs):
|
||||
j = i
|
||||
while j + 1 < len(evs) and evs[j + 1] == evs[i] and j - i < 250:
|
||||
j += 1
|
||||
if j > i:
|
||||
out += bytes([0xFC, j - i + 1]) + evs[i]
|
||||
else:
|
||||
out += evs[i]
|
||||
i = j + 1
|
||||
for s in samples:
|
||||
out += s["data"]
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def write_ptm(title, samples, orders, patterns, channels, pans=None):
|
||||
"""samples: [{name, data (signed bytes; 16-bit little-endian), bits 8|16, volume, c4spd, loop: (start, end) in
|
||||
frames | None, pingpong}] (stored delta coded: 8-bit deltas of the byte stream, also for 16-bit); patterns: [[row:
|
||||
[(note, ins, vol, cmd, param)] * channels] * 64] with note 0 = none, 254 = cut, else our note (1..120); vol None =
|
||||
none; cmd None = none, else 0..0x16 (MOD effects 0..F, then PolyTracker's G..)"""
|
||||
head = bytearray(name(title, 28) + bytes([26, 3, 2, 0]))
|
||||
head += struct.pack("<HHHHH", len(orders), len(samples), len(patterns), channels, 0) + b"\0\0PTMF" + b"\0" * 16
|
||||
pp = list(pans or [(i % 2) * 15 for i in range(channels)])
|
||||
head += bytes(pp + [0] * (32 - len(pp)))
|
||||
head += bytes(orders) + b"\xff" * (256 - len(orders))
|
||||
pat_at = len(head)
|
||||
head += b"\0" * 256
|
||||
smp_at = len(head)
|
||||
head += b"\0" * (80 * len(samples))
|
||||
body = head
|
||||
for k, pat in enumerate(patterns):
|
||||
while len(body) % 16:
|
||||
body.append(0)
|
||||
struct.pack_into("<H", body, pat_at + 2 * k, len(body) // 16)
|
||||
for row in pat:
|
||||
for ch, (note, ins, vol, cmd, param) in enumerate(row):
|
||||
what = (0x20 if note or ins else 0) | (0x40 if cmd is not None else 0) | (0x80 if vol is not None else 0)
|
||||
if what:
|
||||
body.append(what | ch)
|
||||
if what & 0x20:
|
||||
body += bytes([note, ins])
|
||||
if what & 0x40:
|
||||
body += bytes([cmd, param])
|
||||
if what & 0x80:
|
||||
body.append(vol)
|
||||
body.append(0)
|
||||
for i, s in enumerate(samples):
|
||||
bps = 2 if s.get("bits", 8) == 16 else 1
|
||||
raw = s["data"]
|
||||
enc, prev = bytearray(), 0
|
||||
for b in raw:
|
||||
enc.append((b - prev) & 255)
|
||||
prev = b
|
||||
off = len(body)
|
||||
body += enc
|
||||
ls, le = s.get("loop") or (0, 0)
|
||||
fl = 1 | (4 if s.get("loop") else 0) | (8 if s.get("pingpong") else 0) | (16 if bps == 2 else 0)
|
||||
h = bytearray(80)
|
||||
h[0] = fl
|
||||
h[1:13] = name(s.get("name", "")[:8] + ".smp", 12)
|
||||
h[13] = s.get("volume", 64)
|
||||
struct.pack_into("<HHIIII", h, 14, s.get("c4spd", 8363), 0, off, len(raw), ls * bps, (le * bps + 1) if s.get("loop") else 0)
|
||||
h[48:76] = name(s.get("name", ""), 28)
|
||||
h[76:80] = b"PTMS"
|
||||
body[smp_at + 80 * i:smp_at + 80 * i + 80] = h
|
||||
return bytes(body)
|
||||
|
||||
|
||||
def write_far(title, samples, orders, patterns, speed=4, pans=None, breaks=None, message=b"", restart=0, mute=()):
|
||||
"""samples: [{name, data (signed bytes; 16-bit little-endian), bits 8|16, volume 0..15, loop: (start, end) in
|
||||
frames | None}] (at most 64, stored in order); patterns: [[row: [(note, ins, vol, effect)] * 16] * rows] with note 0
|
||||
= none else our note (37..108), ins 1-based, vol 0 = none else 1..16, effect byte (cmd << 4 | param); breaks: the
|
||||
break-row byte per pattern"""
|
||||
head = bytearray(b"FAR\xfe" + name(title, 40) + b"\r\n\x1a")
|
||||
hl_at = len(head)
|
||||
head += b"\0\0" + bytes([0x10]) + bytes([0 if i in mute else 1 for i in range(16)]) + b"\0" * 9 + bytes([speed])
|
||||
head += bytes(list(pans or [(i % 2) * 15 for i in range(16)]))
|
||||
head += b"\0" * 4 + struct.pack("<H", len(message)) + message
|
||||
head += bytes(orders) + b"\xff" * (256 - len(orders)) + bytes([len(patterns), len(orders), restart])
|
||||
sizes = [2 + len(p) * 64 for p in patterns] + [0] * (256 - len(patterns))
|
||||
head += b"".join(struct.pack("<H", s) for s in sizes)
|
||||
struct.pack_into("<H", head, hl_at, len(head))
|
||||
body = head
|
||||
for k, pat in enumerate(patterns):
|
||||
body += bytes([(breaks or [0] * len(patterns))[k], 0])
|
||||
for row in pat:
|
||||
for (note, ins, vol, eff) in row:
|
||||
body += bytes([note - 36 if note else 0, max(0, ins - 1), vol, eff])
|
||||
smap = bytearray(8)
|
||||
for i in range(len(samples)):
|
||||
smap[i >> 3] |= 1 << (i & 7)
|
||||
body += smap
|
||||
for s in samples:
|
||||
bps = 2 if s.get("bits", 8) == 16 else 1
|
||||
ls, le = s.get("loop") or (0, 0)
|
||||
body += name(s.get("name", ""), 32) + struct.pack("<IBBIIBB", len(s["data"]), 0, s.get("volume", 15), ls * bps, le * bps,
|
||||
1 if bps == 2 else 0, 8 if s.get("loop") else 0)
|
||||
body += s["data"]
|
||||
return bytes(body)
|
||||
|
||||
|
||||
def write_okt(samples, orders, patterns, cmod=(0, 0, 0, 0), speed=6):
|
||||
"""samples: [{name, data (signed bytes, even length), volume 0..64, type 0 paired / 1 raw / 2 both, loop: (start,
|
||||
length) in bytes (even) | None}]; patterns: [[row: [(note, ins, effect, param)] * channels] * rows] with note 0 =
|
||||
none else 1..36 (13 = C-5 of the module), ins 1-based; cmod: the four Amiga channels, 1 = a mixed pair"""
|
||||
def chunk(cid, data):
|
||||
return cid + struct.pack(">I", len(data)) + data
|
||||
out = bytearray(b"OKTASONG")
|
||||
out += chunk(b"CMOD", b"".join(struct.pack(">H", c) for c in cmod))
|
||||
sh = bytearray()
|
||||
for i in range(36):
|
||||
if i < len(samples):
|
||||
s = samples[i]
|
||||
ls, ll = s.get("loop") or (0, 0)
|
||||
sh += name(s.get("name", ""), 20) + struct.pack(">IHHHH", len(s["data"]), ls // 2, ll // 2, s.get("volume", 64), s.get("type", 2))
|
||||
else:
|
||||
sh += b"\0" * 32
|
||||
out += chunk(b"SAMP", bytes(sh))
|
||||
out += chunk(b"SPEE", struct.pack(">H", speed))
|
||||
out += chunk(b"SLEN", struct.pack(">H", len(patterns)))
|
||||
out += chunk(b"PLEN", struct.pack(">H", len(orders)))
|
||||
out += chunk(b"PATT", bytes(orders) + b"\0" * (128 - len(orders)))
|
||||
for pat in patterns:
|
||||
pb = bytearray(struct.pack(">H", len(pat)))
|
||||
for row in pat:
|
||||
for (note, ins, fx, param) in row:
|
||||
pb += bytes([note, max(0, ins - 1), fx, param])
|
||||
out += chunk(b"PBOD", bytes(pb))
|
||||
for s in samples:
|
||||
out += chunk(b"SBOD", s["data"])
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def write_med(version, samples, blocks, sequence, tempo=125, tempo2=6, flags=0, flags2=0, trackvols=None,
|
||||
pans=None, master=64, play_transpose=0, sections=None, title=None):
|
||||
"""an MMD0 .. MMD3 module. samples: [{data (signed 8-bit bytes, or big-endian 16-bit with bits 16), bits, volume,
|
||||
transpose, loop: (start, length) in bytes (even) | None, hold, decay, finetune, octaves (IFF multi-octave count:
|
||||
data holds the octaves from the lowest, each twice as long)}]; blocks: [[row: [(note, ins, cmd, param)] * tracks]
|
||||
* rows] with note 0 = none else the MED note (1 = C-1; MMD1+: 0x80 = note off); sequence: block numbers (MMD0 / 1)
|
||||
or the play sequence (MMD2 / 3; sections: [[playseq numbers]] and playseqs = [sequence])"""
|
||||
out = bytearray(52)
|
||||
song_at = 52
|
||||
out += b"\0" * (63 * 8 + 284)
|
||||
need_ext = any(s.get("hold") or s.get("finetune") for s in samples) or title is not None
|
||||
|
||||
def align():
|
||||
while len(out) % 4:
|
||||
out.append(0)
|
||||
|
||||
# blocks
|
||||
block_ptrs = []
|
||||
for blk in blocks:
|
||||
align()
|
||||
block_ptrs.append(len(out))
|
||||
ntr = len(blk[0])
|
||||
if version == 0:
|
||||
out += bytes([ntr, len(blk) - 1])
|
||||
else:
|
||||
out += struct.pack(">HHI", ntr, len(blk) - 1, 0)
|
||||
for row in blk:
|
||||
for (note, ins, cmd, param) in row:
|
||||
if version == 0:
|
||||
out += bytes([(note & 0x3F) | ((ins & 0x10) << 3) | ((ins & 0x20) << 1), ((ins & 15) << 4) | (cmd & 15), param])
|
||||
else:
|
||||
out += bytes([note, ins & 0x3F, cmd, param])
|
||||
align()
|
||||
block_arr = len(out)
|
||||
for p in block_ptrs:
|
||||
out += struct.pack(">I", p)
|
||||
# instruments
|
||||
inst_ptrs = []
|
||||
for s in samples:
|
||||
align()
|
||||
inst_ptrs.append(len(out))
|
||||
oct_ = s.get("octaves", 1)
|
||||
typ = {1: 0, 5: 1, 3: 2, 2: 3, 4: 4, 6: 5, 7: 6}[oct_] | (0x10 if s.get("bits", 8) == 16 else 0)
|
||||
out += struct.pack(">Ih", len(s["data"]), typ) + s["data"]
|
||||
align()
|
||||
smp_arr = len(out)
|
||||
for p in inst_ptrs:
|
||||
out += struct.pack(">I", p)
|
||||
# play sequences (MMD2 / 3)
|
||||
seq_info = None
|
||||
if version >= 2:
|
||||
align()
|
||||
psq = []
|
||||
for sq in [sequence]:
|
||||
psq.append(len(out))
|
||||
out += name("seq", 32) + struct.pack(">IIH", 0, 0, len(sq)) + b"".join(struct.pack(">H", b) for b in sq)
|
||||
align()
|
||||
ps_table = len(out)
|
||||
for p in psq:
|
||||
out += struct.pack(">I", p)
|
||||
sec_table = len(out)
|
||||
secs = sections or [0]
|
||||
for sc in secs:
|
||||
out += struct.pack(">H", sc)
|
||||
align()
|
||||
tv = len(out)
|
||||
out += bytes(trackvols or [64] * len(blocks[0][0]))
|
||||
tp = 0
|
||||
if pans:
|
||||
tp = len(out)
|
||||
out += bytes([p & 255 for p in pans])
|
||||
seq_info = (ps_table, sec_table, tv, tp, len(secs))
|
||||
# expansion: instrument extras + song name
|
||||
exp = 0
|
||||
if need_ext:
|
||||
align()
|
||||
ie = len(out)
|
||||
for s in samples:
|
||||
ls, ll = s.get("loop") or (0, 0)
|
||||
out += struct.pack(">BBBbBBHBBIIBBH", s.get("hold", 0), s.get("decay", 0), 0, s.get("finetune", 0), 0,
|
||||
1 if s.get("loop") else 0, 0, 0, 0, ls, ll, 127, 0, 0)
|
||||
nm = (title or "").encode() + b"\0"
|
||||
na = len(out)
|
||||
out += nm
|
||||
align()
|
||||
exp = len(out)
|
||||
e = bytearray(80)
|
||||
struct.pack_into(">IIHH", e, 0, 0, ie, len(samples), 22)
|
||||
struct.pack_into(">II", e, 44, na, len(nm))
|
||||
out += e
|
||||
# the song header
|
||||
for i, s in enumerate(samples):
|
||||
ls, ll = s.get("loop") or (0, 0)
|
||||
struct.pack_into(">HHBBBb", out, song_at + 8 * i, ls // 2, ll // 2, 0, 0, s.get("volume", 64), s.get("transpose", 0))
|
||||
sh = song_at + 63 * 8
|
||||
if version < 2:
|
||||
struct.pack_into(">HH", out, sh, len(blocks), len(sequence))
|
||||
out[sh + 4:sh + 4 + len(sequence)] = bytes(sequence)
|
||||
else:
|
||||
ps_table, sec_table, tv, tp, nsec = seq_info
|
||||
struct.pack_into(">HH", out, sh, len(blocks), nsec)
|
||||
struct.pack_into(">IIIHHIIHH", out, sh + 4, ps_table, sec_table, tv, len(blocks[0][0]), 1, tp, 0, 100, 0)
|
||||
struct.pack_into(">HbBBB", out, sh + 260, tempo, play_transpose, flags, flags2, tempo2)
|
||||
out[sh + 266:sh + 282] = bytes((trackvols or [64] * 16)[:16]) + bytes(max(0, 16 - len(trackvols or [0] * 16)))
|
||||
out[sh + 282] = master
|
||||
out[sh + 283] = len(samples)
|
||||
hdr = bytearray(b"MMD" + bytes([0x30 + version]))
|
||||
hdr += struct.pack(">IIHHIB3sIIII11sB", len(out), song_at, 0, 0, block_arr, 0, b"\0\0\0", smp_arr, 0, exp, 0, b"\0" * 11, 0)
|
||||
out[0:52] = hdr
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def umx_index(v):
|
||||
"""an Unreal compact index"""
|
||||
neg, v = v < 0, abs(v)
|
||||
out = bytearray([(0x80 if neg else 0) | (v & 0x3F) | (0x40 if v > 0x3F else 0)])
|
||||
v >>= 6
|
||||
while v:
|
||||
out.append((v & 0x7F) | (0x80 if v > 0x7F else 0))
|
||||
v >>= 7
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def write_umx(modules, version=69):
|
||||
"""an Unreal package (UT99-era, package version 61..99) whose exports are Music objects: modules = [(object
|
||||
name, module bytes)]"""
|
||||
names = ["None", "Music", "Core", "Class"] + [n for n, _ in modules]
|
||||
out = bytearray(36)
|
||||
name_at = len(out)
|
||||
for n in names:
|
||||
b = n.encode() + b"\0"
|
||||
out += (umx_index(len(b)) if version >= 64 else b"") + b + struct.pack("<I", 0x04070010)
|
||||
imp_at = len(out)
|
||||
out += umx_index(names.index("Core")) + umx_index(names.index("Class")) + struct.pack("<i", 0) + umx_index(names.index("Music"))
|
||||
bodies = []
|
||||
for i, (n, data) in enumerate(modules):
|
||||
bodies.append(len(out))
|
||||
out += umx_index(0) + umx_index(0) + struct.pack("<I", 0) + umx_index(len(data)) + data
|
||||
exp_at = len(out)
|
||||
for i, (n, data) in enumerate(modules):
|
||||
size = len(umx_index(0)) * 2 + 4 + len(umx_index(len(data))) + len(data)
|
||||
out += umx_index(-1) + umx_index(0) + struct.pack("<i", 0) + umx_index(names.index(n)) + struct.pack("<I", 0x70004)
|
||||
out += umx_index(size) + umx_index(bodies[i])
|
||||
hdr = b"\xc1\x83\x2a\x9e" + struct.pack("<HHIIIIIII", version, 0, 1, len(names), name_at, len(modules), exp_at, 1, imp_at)
|
||||
out[0:36] = hdr
|
||||
return bytes(out)
|
||||
@@ -0,0 +1,229 @@
|
||||
# AC-3 fixtures (tools/fixtures.py). Encoders: ffmpeg (every channel layout, coupling, rematrixing, 32 / 44.1 /
|
||||
# 48 kHz) and aften (block switching, dual mono 1+1, dynamic range profiles, the alternate bit stream syntax).
|
||||
# References: ffmpeg's float decode with -drc_scale 0 (dynamic range off, our default), except for block-switched
|
||||
# streams: ffmpeg (as packaged) mis-decodes the first of the two short transforms, so those use liba52's a52dec
|
||||
# (-r -a: no dynamic range, no level adjustment; float for stereo, 16-bit wav6 for more channels), which agrees with
|
||||
# the A/52 transform equations. AC-3 tracks in Matroska / MP4 / MPEG-TS / AVI (remuxed by ffmpeg) for the api's audio hook.
|
||||
#
|
||||
# Both encoders set dithflag, and decoders draw their own random dither for the zero-bit mantissas, so two correct
|
||||
# decoders differ by about the coding noise. The reference streams therefore have their dithflags cleared (the bit
|
||||
# positions come from our decoder's dec.blocks, the CRCs are recomputed): the reference and we decode the same
|
||||
# numbers. `dithered` keeps the encoder's original stream for a few cases.
|
||||
# tests/gen/ac3_cases.luau { name, data, channels, rate, frames, ref (f32le, WAVE order), refTool, refDrc?,
|
||||
# dithered? }
|
||||
# tests/gen/ac3_tracks.luau { name, data (the container), channels, rate, ref (ffmpeg's decode of the AC-3) }
|
||||
import importlib.util, math, os, random, shutil, struct, tempfile
|
||||
|
||||
_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)
|
||||
|
||||
INPUTS = ["tools/fixtures/_audio.py", "src/Formats/codecs/audio/Ac3"]
|
||||
SECONDS = 0.15
|
||||
DITHERED = ("stereo_44k", "aften_5.1_blksw")
|
||||
NFCHANS = [2, 1, 2, 3, 3, 4, 4, 5]
|
||||
|
||||
|
||||
def _lit(b):
|
||||
return '"' + "".join("\\x%02x" % x for x in b) + '"'
|
||||
|
||||
|
||||
def crc16(data, crc=0):
|
||||
"""A/52 section 7.10.1: x^16 + x^15 + x^2 + 1, MSB first, zero start"""
|
||||
for b in data:
|
||||
crc ^= b << 8
|
||||
for _ in range(8):
|
||||
crc = ((crc << 1) ^ 0x8005) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
|
||||
return crc
|
||||
|
||||
|
||||
def fix_crcs(f):
|
||||
"""recompute crc1 (the CRC of the first 5/8 of the frame after the sync word is 0) and crc2 (all of it)"""
|
||||
words = len(f) // 2
|
||||
n58 = ((words >> 1) + (words >> 3)) * 2
|
||||
# crc1 is the first word of the span: solve the linear map W -> crc(W || 0...) for crc(W || rest) == 0
|
||||
rest = crc16(bytes(2) + bytes(f[4:n58]))
|
||||
basis = [crc16(bytes([(1 << i) >> 8, (1 << i) & 255]) + bytes(n58 - 4)) for i in range(16)]
|
||||
rows = [(basis[i], 1 << i) for i in range(16)]
|
||||
pivots = {}
|
||||
for v, m in rows:
|
||||
for bit in range(15, -1, -1):
|
||||
if not v >> bit & 1:
|
||||
continue
|
||||
if bit in pivots:
|
||||
pv, pm = pivots[bit]
|
||||
v, m = v ^ pv, m ^ pm
|
||||
else:
|
||||
pivots[bit] = (v, m)
|
||||
break
|
||||
w, target = 0, rest
|
||||
for bit in range(15, -1, -1):
|
||||
if target >> bit & 1:
|
||||
pv, pm = pivots[bit]
|
||||
target ^= pv
|
||||
w ^= pm
|
||||
f[2], f[3] = w >> 8, w & 255
|
||||
assert crc16(bytes(f[2:n58])) == 0
|
||||
c2 = crc16(bytes(f[2:-2]))
|
||||
f[-2], f[-1] = c2 >> 8, c2 & 255
|
||||
assert crc16(bytes(f[2:])) == 0
|
||||
|
||||
|
||||
def undither(ctx, data):
|
||||
"""clear every dithflag (after the blksw flags at each audio block's start) and fix the CRCs"""
|
||||
code = """
|
||||
local Ac3 = require("@formats/codecs/audio/Ac3")
|
||||
local b = buffer.fromstring(%s)
|
||||
local dec = Ac3.decoder()
|
||||
local o, n = 0, buffer.len(b)
|
||||
while o + 8 <= n do
|
||||
local h = Ac3.header(b, o, n)
|
||||
if not h then break end
|
||||
assert(dec:decode(b, o, h.frameSize))
|
||||
print(o, h.frameSize, h.acmod, table.concat(dec.blocks, " "))
|
||||
o += h.frameSize
|
||||
end
|
||||
""" % _lit(data)
|
||||
out = bytearray(data)
|
||||
for line in A.luau(ctx, code).decode().strip().split("\n"):
|
||||
v = [int(x) for x in line.split()]
|
||||
o, size, acmod, blocks = v[0], v[1], v[2], v[3:]
|
||||
nf = NFCHANS[acmod]
|
||||
f = out[o:o + size]
|
||||
for p in blocks:
|
||||
for k in range(nf):
|
||||
bit = p + nf + k
|
||||
f[bit >> 3] &= ~(0x80 >> (bit & 7)) & 255
|
||||
fix_crcs(f)
|
||||
out[o:o + size] = f
|
||||
return bytes(out)
|
||||
|
||||
|
||||
# name, encoder, layout (ffmpeg) or (acmod, lfe) (aften), rate, kbps, extra options
|
||||
CASES = [
|
||||
("mono_48k", "ffmpeg", "mono", 48000, 96, []),
|
||||
("stereo_44k", "ffmpeg", "stereo", 44100, 192, []),
|
||||
("stereo_cpl_48k", "ffmpeg", "stereo", 48000, 96, ["-channel_coupling", "1", "-cpl_start_band", "1"]),
|
||||
("stereo_cpl0_48k", "ffmpeg", "stereo", 48000, 64, ["-channel_coupling", "1", "-cpl_start_band", "0"]),
|
||||
("stereo_32k", "ffmpeg", "stereo", 32000, 64, []),
|
||||
("3.0_48k", "ffmpeg", "3.0", 48000, 256, []),
|
||||
("2.1_48k", "ffmpeg", "2.1", 48000, 192, []),
|
||||
("3.0back_48k", "ffmpeg", "3.0(back)", 48000, 192, []),
|
||||
("4.0_48k", "ffmpeg", "4.0", 48000, 256, []),
|
||||
("4.1_44k", "ffmpeg", "4.1", 44100, 320, []),
|
||||
("quad_side_48k", "ffmpeg", "quad(side)", 48000, 256, []),
|
||||
("5.0_side_32k", "ffmpeg", "5.0(side)", 32000, 320, []),
|
||||
("5.1_448", "ffmpeg", "5.1(side)", 48000, 448, []),
|
||||
("5.1_cpl_256", "ffmpeg", "5.1(side)", 48000, 256, ["-channel_coupling", "1"]),
|
||||
("aften_blksw_stereo", "aften", (2, 0), 48000, 192, ["-s", "1"]),
|
||||
("aften_dualmono", "aften", (0, 0), 48000, 128, []),
|
||||
("aften_5.1_blksw", "aften", (7, 1), 48000, 384, ["-s", "1"]),
|
||||
("aften_5.1_drc", "aften", (7, 1), 48000, 384, ["-dynrng", "1"]),
|
||||
("aften_xbsi_2.2", "aften", (6, 0), 44100, 256, ["-xbsi1", "1", "-xbsi2", "1", "-s", "1"]),
|
||||
]
|
||||
CHANNELS = {"mono": 1, "stereo": 2, "3.0": 3, "2.1": 3, "3.0(back)": 3, "4.0": 4, "4.1": 5, "quad(side)": 4,
|
||||
"5.0(side)": 5, "5.1(side)": 6}
|
||||
ACMOD_CH = {0: 2, 1: 1, 2: 2, 3: 3, 4: 3, 5: 4, 6: 4, 7: 5}
|
||||
|
||||
|
||||
def signal(frames, ch, rate, seed):
|
||||
"""per-channel tones with vibrato, noise bursts and clicks (transients for block switching)"""
|
||||
rng = random.Random(seed)
|
||||
out = [0.0] * (frames * ch)
|
||||
for c in range(ch):
|
||||
f = 110.0 * (c + 2) * (1.0 + 0.07 * c)
|
||||
for i in range(frames):
|
||||
t = i / rate
|
||||
v = 0.2 * math.sin(2 * math.pi * f * t + 2 * math.sin(2 * math.pi * 4 * t))
|
||||
v += 0.06 * math.sin(2 * math.pi * (2500 + 700 * c) * t)
|
||||
if (i // (rate // 10) + c) % 4 == 1:
|
||||
v += 0.12 * (rng.random() * 2 - 1)
|
||||
k = i % (rate // 7)
|
||||
if k < 60:
|
||||
v += 0.5 * (1 - k / 60) * (1 if (i // 5) % 2 else -1)
|
||||
out[i * ch + c] = v
|
||||
return out
|
||||
|
||||
|
||||
def raw(samples):
|
||||
return struct.pack("<%df" % len(samples), *samples)
|
||||
|
||||
|
||||
def a52dec(run, d, name, ch):
|
||||
"""liba52's decode: float (planar per 256-sample block) for stereo, 16-bit wav6 otherwise -> f32le, WAVE order"""
|
||||
flags = "-a -r"
|
||||
if ch == 2:
|
||||
raw_ = run("a52dec -o float %s %s 2>/dev/null" % (flags, name))
|
||||
v = struct.unpack("<%df" % (len(raw_) // 4), raw_)
|
||||
out = [0.0] * len(v)
|
||||
for b in range(len(v) // 512):
|
||||
for i in range(256):
|
||||
out[(b * 256 + i) * 2] = v[b * 512 + i]
|
||||
out[(b * 256 + i) * 2 + 1] = v[b * 512 + 256 + i]
|
||||
return raw(out)
|
||||
wav = run("a52dec -o wav6 %s %s 2>/dev/null" % (flags, name))
|
||||
p = wav.index(b"data") + 8
|
||||
pcm = struct.unpack("<%dh" % ((len(wav) - p) // 2), wav[p:p + (len(wav) - p) // 2 * 2])
|
||||
return raw([x / 32768 for x in pcm])
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
d = tempfile.mkdtemp(prefix="fmt-ac3-")
|
||||
cases, tracks = [], []
|
||||
try:
|
||||
def run(cmd):
|
||||
return ctx.nix(["ffmpeg", "aften", "a52dec"], ["sh", "-c", "cd '%s' && %s" % (d, cmd)])
|
||||
|
||||
for name, enc, layout, rate, kbps, extra in CASES:
|
||||
ch = CHANNELS[layout] if enc == "ffmpeg" else ACMOD_CH[layout[0]] + layout[1]
|
||||
frames = int(rate * SECONDS)
|
||||
sig = signal(frames, ch, rate, len(name))
|
||||
with open(os.path.join(d, name + ".raw"), "wb") as f:
|
||||
f.write(raw(sig))
|
||||
out = name + ".ac3"
|
||||
if enc == "ffmpeg":
|
||||
run("ffmpeg -v error -y -f f32le -ar %d -ch_layout '%s' -i %s.raw -c:a ac3 -b:a %dk %s %s"
|
||||
% (rate, layout, name, kbps, " ".join(extra), out))
|
||||
else:
|
||||
with open(os.path.join(d, name + ".wav"), "wb") as f:
|
||||
f.write(A.wav(sig, rate, ch))
|
||||
run("aften -v 0 -threads 1 -b %d -acmod %d -lfe %d %s %s.wav %s" % (kbps, layout[0], layout[1], " ".join(extra), name, out))
|
||||
with open(os.path.join(d, out), "rb") as f:
|
||||
orig = f.read()
|
||||
data = undither(ctx, orig)
|
||||
with open(os.path.join(d, "u_" + out), "wb") as f:
|
||||
f.write(data)
|
||||
c = {"name": name, "data": data, "channels": ch, "rate": rate}
|
||||
if "-s" in extra:
|
||||
c["ref"], c["refTool"] = a52dec(run, d, "u_" + out, ch), "a52dec"
|
||||
else:
|
||||
c["ref"], c["refTool"] = run("ffmpeg -v error -drc_scale 0 -i u_%s -f f32le -" % out), "ffmpeg"
|
||||
if "-dynrng" in extra:
|
||||
c["refDrc"] = run("ffmpeg -v error -drc_scale 1 -i u_%s -f f32le -" % out)
|
||||
c["frames"] = len(c["ref"]) // (4 * ch)
|
||||
if name in DITHERED:
|
||||
c["dithered"] = orig
|
||||
cases.append(c)
|
||||
# AC-3 tracks in containers: the (undithered) AC-3 remuxed with a tiny Motion-JPEG / MPEG-1 picture track
|
||||
sig = signal(int(48000 * 0.3), 6, 48000, 7)
|
||||
with open(os.path.join(d, "t.raw"), "wb") as f:
|
||||
f.write(raw(sig))
|
||||
for name, video, layout in (("ac3.mkv", "-c:v mjpeg -pix_fmt yuvj420p", "5.1(side)"),
|
||||
("ac3.mp4", "-c:v mjpeg -pix_fmt yuvj420p", "stereo"), ("ac3.ts", "-c:v mpeg1video", "stereo"),
|
||||
("ac3.avi", "-c:v mjpeg -pix_fmt yuvj420p", "stereo")):
|
||||
run("ffmpeg -v error -y -f f32le -ar 48000 -ch_layout '5.1(side)' -i t.raw -af aformat=channel_layouts='%s' "
|
||||
"-c:a ac3 -b:a 192k t.ac3" % layout)
|
||||
with open(os.path.join(d, "t.ac3"), "rb") as f:
|
||||
es = undither(ctx, f.read())
|
||||
with open(os.path.join(d, "u.ac3"), "wb") as f:
|
||||
f.write(es)
|
||||
run("ffmpeg -v error -y -f lavfi -i testsrc=size=64x48:rate=25:duration=0.3 -i u.ac3 %s -c:a copy -shortest %s"
|
||||
% (video, name))
|
||||
with open(os.path.join(d, name), "rb") as f:
|
||||
data = f.read()
|
||||
ref = run("ffmpeg -v error -drc_scale 0 -i u.ac3 -f f32le -")
|
||||
tracks.append({"name": name, "data": data, "channels": CHANNELS[layout], "rate": 48000, "ref": ref})
|
||||
finally:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
ctx.emit("ac3_cases", cases)
|
||||
ctx.emit("ac3_tracks", tracks)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,36 @@
|
||||
# AHX fixtures (tools/fixtures.py): songs written by tools/fixtures/_hively.py (a hand-made demo over every waveform,
|
||||
# filter / square sweeps, PList commands and effects; random songs) plus karma.ahx from the HivelyTracker source, each
|
||||
# rendered by hvl2wav (nixpkgs#hivelytracker) as the reference.
|
||||
# tests/gen/ahx_cases.luau { { name, data, crc (CRC-32 of hvl2wav's s16le stereo output), head (its first HEAD frames), frames, sampleRate, stereo, subsong, maxDuration?,
|
||||
# prefix (true: hvl2wav ran with a time limit, compare the first frames only) } }
|
||||
import importlib.util, os, zlib
|
||||
|
||||
INPUTS = ["tools/fixtures/_hively.py"]
|
||||
_spec = importlib.util.spec_from_file_location("_hively", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_hively.py"))
|
||||
H = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(H)
|
||||
|
||||
|
||||
HEAD = 11025 # frames of hvl2wav output kept as raw samples (to locate a mismatch); the rest is checked by CRC
|
||||
|
||||
|
||||
def case(ctx, name, data, rate=44100, stereo=0, subsong=0, limit=None):
|
||||
args = ["-f%d" % rate, "-x%d" % stereo, "-s%d" % subsong] + (["-t0:%02d" % limit] if limit else [])
|
||||
pcm, frames = H.hvl2wav(ctx, data, "ahx", args)
|
||||
c = {"name": name, "data": data, "crc": zlib.crc32(pcm), "head": pcm[:HEAD * 4], "frames": frames, "sampleRate": rate, "stereo": stereo,
|
||||
"subsong": subsong, "prefix": limit is not None}
|
||||
if limit:
|
||||
c["maxDuration"] = limit
|
||||
return c
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(0xA4)
|
||||
demo = H.write_ahx(H.demo_song(False))
|
||||
cases = [case(ctx, "demo", demo), case(ctx, "demo stereo 4", demo, stereo=4),
|
||||
case(ctx, "demo 22050 Hz stereo 2", demo, rate=22050, stereo=2), case(ctx, "demo subsong 1", demo, subsong=1)]
|
||||
for i in range(4):
|
||||
cases.append(case(ctx, "random %d" % i, H.write_ahx(H.random_song(rng, False)), stereo=i))
|
||||
songs = H.source_songs(ctx)
|
||||
cases.append(case(ctx, "karma.ahx", songs["karma.ahx"], stereo=4, limit=3))
|
||||
ctx.emit("ahx_cases", cases)
|
||||
@@ -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,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)
|
||||
@@ -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)
|
||||
@@ -2,11 +2,13 @@
|
||||
# tiny ffmpeg test clips (testsrc 64x48, 10 frames at 10 fps, with a sine track): MP4 (H.264 + AAC), AVI (MJPEG +
|
||||
# PCM), WebM (VP8 + Vorbis), MPEG-TS (interlaced MPEG-2 + MP2); a MIDI file written here (SMF 1: a tempo track and a
|
||||
# melody), the SoundFont of tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py
|
||||
# (song_basic), and SRT / WebVTT / ASS subtitles.
|
||||
# (song_basic), MultiTracker / MED modules and an Unreal package (tools/fixtures/mtm.py, med.py, s3m.py), and SRT /
|
||||
# WebVTT / ASS subtitles.
|
||||
# tests/gen/docs_av.luau { files = { [name] = bytes }, vars = { mp4Bytes = "clip.mp4", ... } }
|
||||
import importlib.util, os, struct, tempfile
|
||||
|
||||
INPUTS = ["tools/docs_check.py", "tools/fixtures/sf2.py", "tools/fixtures/mod.py"]
|
||||
INPUTS = ["tools/docs_check.py", "tools/fixtures/sf2.py", "tools/fixtures/mod.py", "tools/fixtures/mtm.py",
|
||||
"tools/fixtures/med.py", "tools/fixtures/s3m.py", "tools/fixtures/_tracker.py"]
|
||||
|
||||
|
||||
def load(ctx, name):
|
||||
@@ -103,6 +105,11 @@ def generate(ctx):
|
||||
files["bank.sf2"] = sf2.build_sf2(False)[0]
|
||||
mod = load(ctx, "fixtures/mod")
|
||||
files["song.mod"] = mod.song_basic()
|
||||
# ws-audio2: more tracker formats (tools/fixtures/mtm.py, med.py; an Unreal package around an S3M)
|
||||
files["song.mtm"] = load(ctx, "fixtures/mtm").song_effects()
|
||||
files["song.med"] = load(ctx, "fixtures/med").song_basic(version=1)
|
||||
tracker = load(ctx, "fixtures/_tracker")
|
||||
files["music.umx"] = tracker.write_umx([("Theme", load(ctx, "fixtures/s3m").song_mono())])
|
||||
files["subs.srt"] = SRT
|
||||
files["subs.vtt"] = VTT
|
||||
files["subs.ass"] = ASS
|
||||
@@ -114,6 +121,9 @@ def generate(ctx):
|
||||
"midiBytes": "tune.mid",
|
||||
"sf2Bytes": "bank.sf2",
|
||||
"modBytes": "song.mod",
|
||||
"mtmBytes": "song.mtm",
|
||||
"medBytes": "song.med",
|
||||
"umxBytes": "music.umx",
|
||||
"srtText": "subs.srt",
|
||||
"vttText": "subs.vtt",
|
||||
"assText": "subs.ass",
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Docs inputs for the AHX / HVL / MIDI-variant section of docs/guide/music.md (tools/fixtures.py; tools/docs_check.py
|
||||
# reads them): the demo songs of tools/fixtures/_hively.py, small MUS / XMI / HMP files from tools/fixtures/_midivar.py
|
||||
# and a .kar karaoke file written here.
|
||||
# tests/gen/docs_chip.luau { files = { [name] = bytes }, vars = { ahxBytes = "demo.ahx", ... } }
|
||||
import importlib.util, os, random, struct
|
||||
|
||||
INPUTS = ["tools/docs_check.py", "tools/fixtures/_hively.py", "tools/fixtures/_midivar.py"]
|
||||
|
||||
|
||||
def load(ctx, name):
|
||||
spec = importlib.util.spec_from_file_location("docs_chip_" + name.replace("/", "_"), os.path.join(ctx.root, "tools", name + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def kar(V):
|
||||
"""SMF 1 with a melody track and a "Words" track: @ headers, then syllables with \\ / line markers"""
|
||||
def trk(events):
|
||||
body = b"".join(V.vlq(dt) + data for dt, data in events) + b"\x00\xff\x2f\x00"
|
||||
return b"MTrk" + struct.pack(">I", len(body)) + body
|
||||
|
||||
def text(s, kind=1):
|
||||
s = s.encode()
|
||||
return bytes([0xFF, kind]) + V.vlq(len(s)) + s
|
||||
|
||||
melody = [(0, b"\xff\x51\x03\x07\xa1\x20"), (0, b"\xc0\x00")]
|
||||
for n in (60, 62, 64, 65):
|
||||
melody += [(0, bytes([0x90, n, 100])), (480, bytes([0x80, n, 0]))]
|
||||
words = [(0, text("Words", 3)), (0, text("@KMIDI KARAOKE FILE")), (0, text("@TLittle Song")), (0, text("@TThe Docs")),
|
||||
(0, text("\\Hel")), (480, text("lo ")), (480, text("/kar")), (480, text("aoke"))]
|
||||
return b"MThd" + struct.pack(">IHHh", 6, 1, 2, 480) + trk(melody) + trk(words)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
dc = load(ctx, "docs_check")
|
||||
H = load(ctx, "fixtures/_hively")
|
||||
V = load(ctx, "fixtures/_midivar")
|
||||
rng = random.Random(5)
|
||||
files = {
|
||||
"demo.ahx": H.write_ahx(H.demo_song(False)),
|
||||
"demo.hvl": H.write_hvl(H.demo_song(True)),
|
||||
"e1m1.mus": V.random_mus(rng, n=40),
|
||||
"song.xmi": V.write_xmi([V.random_xmi_song(rng, n=30, tempo=500000), V.random_xmi_song(rng, n=10, tempo=500000)]),
|
||||
"song.hmp": V.write_hmp(V.random_hmp_tracks(rng, ntracks=3, n=20, running=False)),
|
||||
"song.kar": kar(V),
|
||||
}
|
||||
dc.emit_inputs(ctx, files, {"ahxBytes": "demo.ahx", "hvlBytes": "demo.hvl", "musBytes": "e1m1.mus",
|
||||
"xmiBytes": "song.xmi", "hmpBytes": "song.hmp", "karBytes": "song.kar"})
|
||||
@@ -0,0 +1,40 @@
|
||||
# Docs inputs for the guide's lossless audio section (tools/fixtures.py; tools/docs_check.py reads them): the docs
|
||||
# stereo tone (tools/fixtures/docs_inputs.py) encoded by the reference encoders, with tags: WavPack lossless, WavPack
|
||||
# hybrid (.wv + its .wvc correction file), Monkey's Audio (-c2000) and TTA.
|
||||
# tests/gen/docs_lossless.luau { files = { [name] = bytes }, vars = { wvBytes = "tone.wv", ... } }
|
||||
# tests/gen/docs_files/assets/<name> the same files, for the snippets that load by path
|
||||
import importlib.util, os, tempfile
|
||||
|
||||
INPUTS = ["tools/docs_check.py", "tools/fixtures/docs_inputs.py"]
|
||||
|
||||
|
||||
def load(ctx, name):
|
||||
spec = importlib.util.spec_from_file_location("docs_lossless_" + name.replace("/", "_"),
|
||||
os.path.join(ctx.root, "tools", name + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
dc = load(ctx, "docs_check")
|
||||
di = load(ctx, "fixtures/docs_inputs")
|
||||
files = {}
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
wav = os.path.join(d, "tone.wav")
|
||||
with open(wav, "wb") as f:
|
||||
f.write(di.tone(44100, 1.0))
|
||||
tags = ["-w", "Title=Docs Tone", "-w", "Artist=formats-luau"]
|
||||
ctx.nix("wavpack", ["wavpack", "-q", "-y", "-h"] + tags + [wav, "-o", os.path.join(d, "tone.wv")])
|
||||
ctx.nix("wavpack", ["wavpack", "-q", "-y", "-b3", "-c"] + tags + [wav, "-o", os.path.join(d, "tone_hybrid.wv")])
|
||||
ctx.nix("monkeys-audio", ["mac", wav, os.path.join(d, "tone.ape"), "-c2000", "-t", "Title=Docs Tone|Artist=formats-luau"])
|
||||
ctx.nix("ttaenc", ["ttaenc", "-e", wav, "-o", os.path.join(d, "tone.tta")])
|
||||
for name in ("tone.wv", "tone_hybrid.wv", "tone_hybrid.wvc", "tone.ape", "tone.tta"):
|
||||
files[name] = open(os.path.join(d, name), "rb").read()
|
||||
dc.emit_inputs(ctx, files, {
|
||||
"wvBytes": "tone.wv",
|
||||
"hybridWvBytes": "tone_hybrid.wv",
|
||||
"hybridWvcBytes": "tone_hybrid.wvc",
|
||||
"apeBytes": "tone.ape",
|
||||
"ttaBytes": "tone.tta",
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
# Docs inputs for the Musepack / AC-3 section of docs/guide/audio.md (tools/docs_check.py): a tagged stereo tone as
|
||||
# Musepack SV8 (mpcenc, built by tools/fixtures/mpc.py's nix expression) and a 5.1 tone as AC-3 (ffmpeg).
|
||||
# tests/gen/docs_lossy.luau { files = { [name] = bytes }, vars = { mpcBytes = "tone.mpc", ac3Bytes = "tone.ac3" } }
|
||||
import importlib.util, math, os, shutil, struct, subprocess, tempfile
|
||||
|
||||
INPUTS = ["tools/docs_check.py", "tools/fixtures/mpc.py"]
|
||||
|
||||
|
||||
def load(ctx, rel, name):
|
||||
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, rel))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
dc = load(ctx, "tools/docs_check.py", "docs_check")
|
||||
mpc = load(ctx, "tools/fixtures/mpc.py", "docs_lossy_mpc")
|
||||
d = tempfile.mkdtemp(prefix="fmt-docs-lossy-")
|
||||
try:
|
||||
rate, n = 44100, 44100
|
||||
st = [0.3 * math.sin(2 * math.pi * f * i / rate) for i in range(n) for f in (440, 660)]
|
||||
with open(os.path.join(d, "tone.wav"), "wb") as f:
|
||||
f.write(mpc.A.wav(st, rate, 2))
|
||||
subprocess.run([os.path.join(mpc.tools(), "mpcenc"), "--silent", "--overwrite", "--quality", "4",
|
||||
"--tag", "Title=Docs Tone", "--artist", "formats-luau", os.path.join(d, "tone.wav"),
|
||||
os.path.join(d, "tone.mpc")], capture_output=True, check=True)
|
||||
six = [0.2 * math.sin(2 * math.pi * (200 + 100 * c) * i / 48000) for i in range(24000) for c in range(6)]
|
||||
with open(os.path.join(d, "six.raw"), "wb") as f:
|
||||
f.write(struct.pack("<%df" % len(six), *six))
|
||||
ctx.nix("ffmpeg", ["sh", "-c", "cd '%s' && ffmpeg -v error -y -f f32le -ar 48000 -ch_layout '5.1(side)' -i six.raw "
|
||||
"-c:a ac3 -b:a 384k tone.ac3" % d])
|
||||
files = {}
|
||||
for name in ("tone.mpc", "tone.ac3"):
|
||||
with open(os.path.join(d, name), "rb") as f:
|
||||
files[name] = f.read()
|
||||
finally:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
dc.emit_inputs(ctx, files, {"mpcBytes": "tone.mpc", "ac3Bytes": "tone.ac3"})
|
||||
@@ -0,0 +1,81 @@
|
||||
# FAR fixtures (tools/fixtures.py): generated Farandole Composer modules exercising the effects, rendered by openmpt123.
|
||||
# tests/gen/far_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py),
|
||||
# duration (openmpt's song length) }
|
||||
import os, sys
|
||||
|
||||
# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
|
||||
T = sys.modules.get("_tracker")
|
||||
if T is None:
|
||||
import importlib.util
|
||||
_spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py"))
|
||||
T = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["_tracker"] = T
|
||||
_spec.loader.exec_module(T)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tracker.py"]
|
||||
|
||||
|
||||
def empty(rows=64):
|
||||
return [[(0, 0, 0, 0) for _ in range(16)] for _ in range(rows)]
|
||||
|
||||
|
||||
def put(p, row, ch, note=0, ins=0, vol=0, cmd=None, param=0):
|
||||
p[row][ch] = (note, ins, vol, 0 if cmd is None else (cmd << 4) | param)
|
||||
|
||||
|
||||
def samples():
|
||||
return [
|
||||
{"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 15, "loop": (0, 64)},
|
||||
{"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 11, "loop": (0, 64)},
|
||||
{"name": "saw16", "data": T.s16(T.synth("saw", 200, 100, 0.6)), "bits": 16, "volume": 15, "loop": (0, 200)},
|
||||
{"name": "noise", "data": T.s8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 14},
|
||||
{"name": "tri", "data": T.s8(T.synth("tri", 50, 50, 0.8)), "volume": 12, "loop": (0, 50)},
|
||||
]
|
||||
|
||||
|
||||
def song_effects(keep=None):
|
||||
a, b = empty(), empty(48)
|
||||
mel = [61, 65, 68, 73, 68, 65, 63, 61]
|
||||
for i in range(16):
|
||||
put(a, i * 4, 0, mel[i % 8], 1, 16 - i % 4)
|
||||
put(a, 0, 1, 49, 2, 12)
|
||||
put(a, 4, 1, 0, 0, 0, 0x1, 0x3) # fine porta up
|
||||
put(a, 8, 1, 0, 0, 0, 0x2, 0x5)
|
||||
put(a, 12, 1, 0, 0, 0, 0x8, 0x2) # volume slide down
|
||||
put(a, 16, 1, 51, 2, 14, 0x7, 0x1) # up
|
||||
put(a, 20, 1, 0, 0, 0, 0x5, 0x4) # vibrato depth
|
||||
put(a, 21, 1, 0, 0, 0, 0x6, 0x2) # vibrato speed
|
||||
put(a, 28, 1, 56, 2, 14)
|
||||
put(a, 32, 1, 61, 2, 0, 0x3, 0x4) # tone portamento (keeps going)
|
||||
put(a, 40, 1, 49, 2, 0, 0x3, 0x2)
|
||||
put(a, 48, 1, 0, 0, 0, 0xA, 0x8) # volume portamento
|
||||
for r in range(0, 64, 8):
|
||||
put(a, r, 3, 61, 4, 16 - r // 8)
|
||||
put(a, 36, 3, 61, 4, 16, 0x4, 0x2) # retrigger
|
||||
put(a, 4, 2, 37, 3, 12)
|
||||
put(a, 2, 4, 73, 5, 10, 0xB, 0x2) # panning
|
||||
put(a, 30, 4, 0, 0, 0, 0xB, 0xD)
|
||||
put(a, 10, 5, 56, 1, 12)
|
||||
put(a, 24, 5, 0, 0, 0, 0xF, 0x3) # speed
|
||||
put(b, 0, 0, 49, 1, 16)
|
||||
put(b, 8, 0, 61, 1, 16, 0x2, 0x8)
|
||||
put(b, 0, 2, 37, 3, 12)
|
||||
put(b, 16, 2, 44, 3, 10, 0x9, 0x3)
|
||||
put(b, 20, 6, 68, 5, 16)
|
||||
put(b, 24, 9, 56, 2, 16) # a muted channel
|
||||
if keep is not None:
|
||||
for p in (a, b):
|
||||
for row in p:
|
||||
for ch in range(16):
|
||||
if ch not in keep and (row[ch][3] >> 4) != 0xF:
|
||||
row[ch] = (0, 0, 0, 0)
|
||||
return T.write_far("effects", samples(), [0, 1], [a, b], speed=5, breaks=[0, 30], mute=(9,),
|
||||
pans=[3, 12, 7, 0, 15, 9, 5, 10, 8, 8, 8, 8, 8, 8, 8, 8], message=b"far test")
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for nm, data in (("effects", song_effects()),):
|
||||
ref = T.reference(ctx, data, "far")
|
||||
cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]})
|
||||
ctx.emit("far_cases", cases)
|
||||
@@ -0,0 +1,24 @@
|
||||
# HMP / HMI fixtures (tools/fixtures.py): HMP (old and "013195" headers) and HMI files written by
|
||||
# tools/fixtures/_midivar.py (several tracks, running status in HMI, HMI note durations and FE events, tick rates) and
|
||||
# wildmidi -x's conversion of each as the reference event stream (wildmidi reads HMP without running status, so the
|
||||
# HMP files use none).
|
||||
# tests/gen/hmp_cases.luau { { name, data, kind, rate, ref = { division, tempo, events = { {seconds, status, d1, d2} } } } }
|
||||
import importlib.util, os
|
||||
|
||||
INPUTS = ["tools/fixtures/_midivar.py"]
|
||||
_spec = importlib.util.spec_from_file_location("_midivar", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_midivar.py"))
|
||||
M = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(M)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(0x484D50)
|
||||
cases = []
|
||||
for i, (new, rate) in enumerate([(False, 120), (True, 120), (False, 60), (True, 140)]):
|
||||
data = M.write_hmp(M.random_hmp_tracks(rng, ntracks=2 + i, n=40, running=False), bpm=rate, new=new)
|
||||
cases.append({"name": "hmp %d%s" % (i, " 013195" if new else ""), "data": data, "kind": "hmp", "rate": rate,
|
||||
"ref": M.wildmidi(ctx, data, "hmp")})
|
||||
for i, rate in enumerate([120, 100]):
|
||||
data = M.write_hmi(M.random_hmi_tracks(rng, ntracks=2 + i), bpm=rate)
|
||||
cases.append({"name": "hmi %d" % i, "data": data, "kind": "hmi", "rate": rate, "ref": M.wildmidi(ctx, data, "hmi")})
|
||||
ctx.emit("hmp_cases", cases)
|
||||
@@ -0,0 +1,35 @@
|
||||
# HVL fixtures (tools/fixtures.py): songs written by tools/fixtures/_hively.py (a hand-made 6-channel demo with ring
|
||||
# modulation, panning and two effect columns; random 4..8 channel songs) plus songs from the HivelyTracker source, each
|
||||
# rendered by hvl2wav (nixpkgs#hivelytracker) as the reference.
|
||||
# tests/gen/hvl_cases.luau { { name, data, crc (CRC-32 of hvl2wav's s16le stereo output), head (its first HEAD frames), frames, sampleRate, subsong, maxDuration?, prefix } }
|
||||
import importlib.util, os, zlib
|
||||
|
||||
INPUTS = ["tools/fixtures/_hively.py"]
|
||||
_spec = importlib.util.spec_from_file_location("_hively", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_hively.py"))
|
||||
H = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(H)
|
||||
|
||||
|
||||
HEAD = 11025 # frames of hvl2wav output kept as raw samples (to locate a mismatch); the rest is checked by CRC
|
||||
|
||||
|
||||
def case(ctx, name, data, rate=44100, subsong=0, limit=None):
|
||||
args = ["-f%d" % rate, "-s%d" % subsong] + (["-t0:%02d" % limit] if limit else [])
|
||||
pcm, frames = H.hvl2wav(ctx, data, "hvl", args)
|
||||
c = {"name": name, "data": data, "crc": zlib.crc32(pcm), "head": pcm[:HEAD * 4], "frames": frames, "sampleRate": rate, "subsong": subsong,
|
||||
"prefix": limit is not None}
|
||||
if limit:
|
||||
c["maxDuration"] = limit
|
||||
return c
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(0x4E1)
|
||||
demo = H.write_hvl(H.demo_song(True))
|
||||
cases = [case(ctx, "demo", demo), case(ctx, "demo 48000 Hz", demo, rate=48000), case(ctx, "demo subsong 1", demo, subsong=1)]
|
||||
for i in range(4):
|
||||
cases.append(case(ctx, "random %d" % i, H.write_hvl(H.random_song(rng, True))))
|
||||
songs = H.source_songs(ctx)
|
||||
for name in ["chiprolled.hvl", "sunspots.hvl", "syphus-Afterstorm.hvl"]:
|
||||
cases.append(case(ctx, name, songs[name], limit=3))
|
||||
ctx.emit("hvl_cases", cases)
|
||||
@@ -0,0 +1,113 @@
|
||||
# MED fixtures (tools/fixtures.py): generated MED / OctaMED modules (MMD0, MMD1 with instrument extras, MMD2 with a play
|
||||
# sequence) exercising the effects, rendered by openmpt123.
|
||||
# tests/gen/med_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py),
|
||||
# duration (openmpt's song length) }
|
||||
import os, sys
|
||||
|
||||
# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
|
||||
T = sys.modules.get("_tracker")
|
||||
if T is None:
|
||||
import importlib.util
|
||||
_spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py"))
|
||||
T = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["_tracker"] = T
|
||||
_spec.loader.exec_module(T)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tracker.py"]
|
||||
|
||||
|
||||
def empty(ch, rows=64):
|
||||
return [[(0, 0, 0, 0) for _ in range(ch)] for _ in range(rows)]
|
||||
|
||||
|
||||
def put(p, row, ch, note=0, ins=0, cmd=0, param=0):
|
||||
p[row][ch] = (note, ins, cmd, param)
|
||||
|
||||
|
||||
def samples(extras=False):
|
||||
s = [
|
||||
{"data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "loop": (0, 64)},
|
||||
{"data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 44, "loop": (0, 64)},
|
||||
{"data": T.s8(T.synth("saw", 128, 64, 0.6)), "volume": 64, "loop": (64, 64), "transpose": -12},
|
||||
{"data": T.s8(T.synth("noise", 4000, 1, 0.7, decay=1200)), "volume": 60},
|
||||
{"data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 52, "loop": (0, 32)},
|
||||
]
|
||||
if extras:
|
||||
s[0]["hold"], s[0]["decay"] = 6, 4 # hold / decay: a volume envelope
|
||||
s[1]["finetune"] = 3
|
||||
s[4]["hold"], s[4]["decay"] = 2, 0
|
||||
return s
|
||||
|
||||
|
||||
def song_basic(keep=None, version=0):
|
||||
a, b = empty(4), empty(4, 32)
|
||||
mel = [13, 17, 20, 25, 20, 17, 15, 13]
|
||||
for i in range(16):
|
||||
put(a, i * 4, 0, mel[i % 8], 1)
|
||||
put(a, 2, 0, 0, 0, 0x0, 0x37) # arpeggio
|
||||
put(a, 0, 1, 1, 2)
|
||||
put(a, 4, 1, 0, 0, 0x1, 0x02)
|
||||
put(a, 12, 1, 0, 0, 0x2, 0x03)
|
||||
put(a, 20, 1, 13, 2, 0xC, 0x32) # volume (decimal: 32)
|
||||
put(a, 24, 1, 0, 0, 0xD, 0x03) # volume slide down (every tick)
|
||||
put(a, 28, 1, 0, 0, 0xD, 0x20)
|
||||
put(a, 32, 1, 8, 2, 0x4, 0x34) # vibrato (twice as deep)
|
||||
put(a, 40, 1, 13, 2)
|
||||
put(a, 41, 1, 20, 0, 0x3, 0x10) # tone portamento
|
||||
put(a, 48, 1, 0, 0, 0x5, 0x01)
|
||||
for r in range(0, 64, 8):
|
||||
put(a, r, 3, 13, 4, 0xC, 0x64 - r)
|
||||
put(a, 2, 2, 25, 3)
|
||||
put(a, 36, 2, 1, 5, 0xF, 0xF2) # delay note
|
||||
put(a, 44, 2, 1, 5, 0xF, 0xF1) # play twice
|
||||
put(a, 34, 3, 0, 0, 0x9, 0x04) # secondary speed
|
||||
put(a, 50, 3, 0, 0, 0xF, 0x90) # tempo 0x90 (BPM 144 / 0.264...)
|
||||
put(b, 0, 0, 13, 1)
|
||||
put(b, 8, 1, 20, 2)
|
||||
put(b, 16, 2, 13, 3, 0x8, 0x40) # panning (8xx)
|
||||
put(b, 24, 3, 25, 5, 0xF, 0x00) # pattern break
|
||||
if keep is not None:
|
||||
for p in (a, b):
|
||||
for row in p:
|
||||
for ch in range(4):
|
||||
if ch not in keep and row[ch][2] not in (0x9, 0xF):
|
||||
row[ch] = (0, 0, 0, 0)
|
||||
return T.write_med(version, samples(version > 0), [a, b], [0, 1, 0], tempo=0x21 if version == 0 else 125, tempo2=6,
|
||||
flags=0x10 if version > 0 else 0, flags2=0x23 if version > 0 else 0, title="med test" if version > 0 else None)
|
||||
|
||||
|
||||
def song_mmd2():
|
||||
"""MMD2: 6 tracks, a play sequence with a section, ProTracker-style slides, BPM tempo, track volumes"""
|
||||
a = empty(6, 48)
|
||||
for r in range(0, 48, 4):
|
||||
put(a, r, r // 4 % 6, 13 + (r // 4) % 12, 1 + r // 4 % 5)
|
||||
put(a, 6, 1, 0, 0, 0x1, 0x04)
|
||||
put(a, 10, 2, 0, 0, 0xD, 0x02)
|
||||
put(a, 20, 4, 0, 0, 0x16, 0x00) # loop start
|
||||
put(a, 23, 4, 0, 0, 0x16, 0x01) # loop once
|
||||
put(a, 30, 5, 0, 0, 0x1F, 0x20) # note delay 2
|
||||
put(a, 44, 0, 0, 0, 0x1D, 0x08) # break to row 8 (hex)
|
||||
b = empty(6, 16)
|
||||
put(b, 0, 0, 25, 2, 0x0C, 0x20)
|
||||
put(b, 8, 3, 30, 4)
|
||||
return T.write_med(2, samples(), [a, b], [0, 1], tempo=120, tempo2=5, flags=0x20 | 0x10, flags2=0x20 | 3,
|
||||
trackvols=[64, 48, 64, 32, 64, 64])
|
||||
|
||||
|
||||
def song_octaves():
|
||||
"""MMD1 with an IFF 3-octave sample (three copies of a waveform, each twice as long as the last): a keymap"""
|
||||
w = T.s8(T.synth("saw", 32, 32, 0.7)) + T.s8(T.synth("saw", 64, 64, 0.7)) + T.s8(T.synth("saw", 128, 128, 0.7))
|
||||
smp = [{"data": w, "volume": 64, "octaves": 3, "loop": (0, 32)}, samples()[0]]
|
||||
a = empty(2, 48)
|
||||
for i, n in enumerate([1, 8, 13, 20, 25, 32, 37, 30, 18, 6, 13, 25]):
|
||||
put(a, i * 4, 0, n, 1)
|
||||
put(a, i * 4 + 2, 1, n, 2, 0xC, 0x20)
|
||||
return T.write_med(1, smp, [a], [0], tempo=125, tempo2=6, flags=0x10, flags2=0x23)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for nm, data in (("mmd0", song_basic()), ("mmd1", song_basic(version=1)), ("mmd2", song_mmd2()), ("octaves", song_octaves())):
|
||||
ref = T.reference(ctx, data, "med")
|
||||
cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]})
|
||||
ctx.emit("med_cases", cases)
|
||||
@@ -0,0 +1,130 @@
|
||||
# Musepack fixtures (tools/fixtures.py). There is no Musepack encoder in nixpkgs, so the reference tools are built
|
||||
# here from the official sources through nix (fetchurl with pinned hashes): mpcenc / libmpcdec from musepack_src_r475
|
||||
# (SV8, BSD / LGPL tools), mppenc 1.16 (SV7), and `mpcf32`, a 20-line C program linked against r475's libmpcdec that
|
||||
# writes its float output (gapless, the reference) as f32le, optionally after mpc_demux_seek_sample.
|
||||
# tests/gen/mpc_cases.luau { name, data, version, channels, rate, frames, exact (frames that match libmpcdec
|
||||
# exactly), ref (mpcf32's f32le, the first REF frames), ff? (ffmpeg's s16 decode as f32le,
|
||||
# aligned: ffmpeg is not gapless), tags? }
|
||||
# tests/gen/mpc_seek.luau { name (a case), at (sample), ref (mpcf32 after seeking to `at`, SEEK_REF stereo frames) }
|
||||
import importlib.util, os, subprocess, tempfile, shutil
|
||||
|
||||
_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)
|
||||
|
||||
INPUTS = ["tools/fixtures/_audio.py"]
|
||||
|
||||
NIX = r'''
|
||||
with import <nixpkgs> {};
|
||||
let
|
||||
flags = "-fcommon -Wno-error -Wno-implicit-function-declaration -Wno-incompatible-pointer-types -Wno-int-conversion";
|
||||
f32 = writeText "mpcf32.c" ''
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <mpc/mpcdec.h>
|
||||
int main(int argc, char **argv) {
|
||||
mpc_reader r; mpc_streaminfo si; MPC_SAMPLE_FORMAT b[MPC_DECODER_BUFFER_LENGTH];
|
||||
if (argc < 2 || mpc_reader_init_stdio(&r, argv[1]) < 0) return 1;
|
||||
mpc_demux *d = mpc_demux_init(&r); if (!d) return 2;
|
||||
mpc_demux_get_info(d, &si);
|
||||
if (argc > 2) mpc_demux_seek_sample(d, (mpc_uint64_t) atoll(argv[2]));
|
||||
for (;;) { mpc_frame_info f; f.buffer = b;
|
||||
if (mpc_demux_decode(d, &f) != MPC_STATUS_OK) { fprintf(stderr, "error\n"); return 3; }
|
||||
if (f.bits == -1) break;
|
||||
fwrite(b, sizeof(float), f.samples * si.channels, stdout); }
|
||||
return 0; }
|
||||
'';
|
||||
in symlinkJoin { name = "musepack-tools"; paths = [
|
||||
(stdenv.mkDerivation {
|
||||
pname = "musepack"; version = "r475";
|
||||
src = fetchurl { url = "https://files.musepack.net/source/musepack_src_r475.tar.gz"; sha256 = "a4b1742f997f83e1056142d556a8c20845ba764b70365ff9ccf2e3f81c427b2b"; };
|
||||
nativeBuildInputs = [ cmake ];
|
||||
NIX_CFLAGS_COMPILE = flags;
|
||||
postPatch = "sed -i -e /mpcgain/d -e /mpcchap/d -e /wavcmp/d -e /mpccut/d CMakeLists.txt";
|
||||
cmakeFlags = [ "-DCMAKE_POLICY_VERSION_MINIMUM=3.5" "-DSHARED=OFF" ];
|
||||
postBuild = "$CC -O2 -I../include ${f32} libmpcdec/libmpcdec_static.a -lm -o mpcf32";
|
||||
installPhase = "mkdir -p $out/bin; cp mpcenc/mpcenc mpcdec/mpcdec mpcf32 $out/bin/";
|
||||
})
|
||||
(stdenv.mkDerivation {
|
||||
pname = "mppenc"; version = "1.16";
|
||||
src = fetchurl { url = "https://files.musepack.net/source/mppenc-1.16.tar.bz2"; sha256 = "f90781856ca7b6ce1ec7033321fadbcd04fe264d0349c20b49ad05f7cb2655ad"; };
|
||||
nativeBuildInputs = [ cmake ];
|
||||
NIX_CFLAGS_COMPILE = flags;
|
||||
cmakeFlags = [ "-DCMAKE_POLICY_VERSION_MINIMUM=3.5" ];
|
||||
installPhase = "mkdir -p $out/bin; cp src/mppenc $out/bin/";
|
||||
})
|
||||
]; }
|
||||
'''
|
||||
|
||||
# name, encoder (mpcenc = SV8, mppenc = SV7), signal, rate, channels, seconds, extra options
|
||||
CASES = [
|
||||
("sv8_q5_stereo", "mpcenc", "music", 44100, 2, 1.2, ["--quality", "5", "--num_frames", "1"]),
|
||||
("sv8_q3_mono32k", "mpcenc", "sweep", 32000, 1, 0.5, ["--quality", "3"]),
|
||||
("sv8_q9_noise48k", "mpcenc", "noise", 48000, 2, 0.4, ["--quality", "9", "--num_frames", "2"]),
|
||||
("sv8_q1_sine", "mpcenc", "sine", 44100, 2, 0.3, ["--quality", "1", "--num_frames", "0",
|
||||
"--artist", "Some One", "--tag", "Title=Mpc Tone", "--tag", "Year=2026"]),
|
||||
("sv7_q5_stereo", "mppenc", "music", 44100, 2, 1.2, ["--quality", "5"]),
|
||||
("sv7_q8_noise", "mppenc", "noise", 44100, 2, 0.3, ["--quality", "8"]),
|
||||
("sv7_q2_sweep", "mppenc", "sweep", 48000, 2, 0.5, ["--quality", "2"]),
|
||||
]
|
||||
REF = 22050 # frames of reference output kept per case (the fixture module stays small)
|
||||
FF = ("sv8_q5_stereo", "sv7_q5_stereo") # cases also compared with ffmpeg
|
||||
SEEKS = [("sv8_q5_stereo", 30000), ("sv8_q9_noise48k", 9000), ("sv7_q5_stereo", 40000)]
|
||||
SEEK_REF = 4096
|
||||
|
||||
|
||||
def tools():
|
||||
out = subprocess.run(["nix", "build", "--impure", "--no-link", "--print-out-paths", "--expr", NIX],
|
||||
capture_output=True, check=True).stdout.decode().strip().split("\n")[-1]
|
||||
return os.path.join(out, "bin")
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
bin_ = tools()
|
||||
d = tempfile.mkdtemp(prefix="fmt-mpc-")
|
||||
cases, seeks, files = [], [], {}
|
||||
try:
|
||||
for name, enc, kind, rate, ch, secs, extra in CASES:
|
||||
frames = int(rate * secs)
|
||||
sig = A.signal(kind, rate, ch, frames, seed=len(name))
|
||||
wav = os.path.join(d, name + ".wav")
|
||||
mpc = os.path.join(d, name + ".mpc")
|
||||
with open(wav, "wb") as f:
|
||||
f.write(A.wav(sig, rate, ch))
|
||||
subprocess.run([os.path.join(bin_, enc)] + extra + ["--silent", "--overwrite", wav, mpc], capture_output=True, check=True)
|
||||
with open(mpc, "rb") as f:
|
||||
data = f.read()
|
||||
files[name] = mpc
|
||||
ref = subprocess.run([os.path.join(bin_, "mpcf32"), mpc], capture_output=True, check=True).stdout
|
||||
got = len(ref) // (4 * ch)
|
||||
assert got == frames, (name, got, frames)
|
||||
# SV7: libmpcdec decodes the zero-filled data past the last frame for the synthesis tail (reading past
|
||||
# its tables); we decode silence there, so only the frames before it compare exactly
|
||||
exact = frames
|
||||
if enc == "mppenc":
|
||||
exact = min(frames, int.from_bytes(data[4:8], "little") * 1152 - 481)
|
||||
c = {"name": name, "data": data, "version": 8 if enc == "mpcenc" else 7, "channels": ch, "rate": rate,
|
||||
"frames": frames, "exact": exact, "ref": ref[:REF * ch * 4]}
|
||||
if name in FF:
|
||||
_, _, ff = A.ffdecode(ctx, data, ext="mpc")
|
||||
# ffmpeg decodes without the gapless trimming: find the lag of the reference inside its output
|
||||
refl = A.from_f32le(ref)
|
||||
best = None
|
||||
for lag in range(0, 2400):
|
||||
if (lag + 200) * ch > len(ff):
|
||||
break
|
||||
e = sum((ff[(lag + i) * ch] - refl[i * ch]) ** 2 for i in range(100, 200))
|
||||
if best is None or e < best[0]:
|
||||
best = (e, lag)
|
||||
c["ff"] = A.f32le(ff[best[1] * ch:(best[1] + REF) * ch])
|
||||
if "--artist" in extra:
|
||||
c["tags"] = {"artist": "Some One", "title": "Mpc Tone", "date": "2026"}
|
||||
cases.append(c)
|
||||
for name, at in SEEKS:
|
||||
ref = subprocess.run([os.path.join(bin_, "mpcf32"), files[name], str(at)], capture_output=True, check=True).stdout
|
||||
data = next(c["data"] for c in cases if c["name"] == name)
|
||||
seeks.append({"name": name, "at": at, "ref": ref[:SEEK_REF * 8]})
|
||||
finally:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
ctx.emit("mpc_cases", cases)
|
||||
ctx.emit("mpc_seek", seeks)
|
||||
@@ -0,0 +1,105 @@
|
||||
# MTM fixtures (tools/fixtures.py): generated MultiTracker modules exercising the effects, rendered by openmpt123.
|
||||
# tests/gen/mtm_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py),
|
||||
# duration (openmpt's song length) }
|
||||
import os, sys
|
||||
|
||||
# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
|
||||
T = sys.modules.get("_tracker")
|
||||
if T is None:
|
||||
import importlib.util
|
||||
_spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py"))
|
||||
T = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["_tracker"] = T
|
||||
_spec.loader.exec_module(T)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tracker.py"]
|
||||
|
||||
|
||||
def empty(ch, rows=64):
|
||||
return [[(0, 0, 0, 0) for _ in range(ch)] for _ in range(rows)]
|
||||
|
||||
|
||||
def put(p, row, ch, note=0, ins=0, fx=0, param=0):
|
||||
p[row][ch] = (note, ins, fx, param)
|
||||
|
||||
|
||||
def samples():
|
||||
return [
|
||||
{"name": "sine", "data": T.u8(T.synth("sine", 64, 64)), "volume": 64, "loop": (0, 64)},
|
||||
{"name": "square", "data": T.u8(T.synth("square", 64, 64, 0.5)), "volume": 44, "loop": (0, 64)},
|
||||
{"name": "saw16", "data": T.u16(T.synth("saw", 128, 64, 0.6)), "bits": 16, "volume": 64, "loop": (0, 256)},
|
||||
{"name": "noise", "data": T.u8(T.synth("noise", 5000, 1, 0.7, decay=1500)), "volume": 60},
|
||||
{"name": "tri ft", "data": T.u8(T.synth("tri", 32, 32, 0.8)), "volume": 52, "finetune": 3, "loop": (0, 32)},
|
||||
]
|
||||
|
||||
|
||||
def song_effects(keep=None):
|
||||
a, b = empty(6), empty(6)
|
||||
mel = [49, 53, 56, 61, 56, 53, 51, 49]
|
||||
for i in range(16):
|
||||
put(a, i * 4, 0, mel[i % 8], 1)
|
||||
put(a, i * 4, 1, 37 + (i % 4) * 2, 2, 0x0, 0x37 if i % 2 else 0)
|
||||
put(a, 0, 2, 49, 3, 0x1, 0x02)
|
||||
put(a, 16, 2, 0, 0, 0x2, 0x03)
|
||||
put(a, 32, 2, 61, 3, 0xC, 0x30)
|
||||
put(a, 33, 2, 0, 0, 0xA, 0x02)
|
||||
put(a, 48, 2, 0, 0, 0xA, 0x40)
|
||||
for r in range(0, 64, 8):
|
||||
put(a, r, 3, 61, 4, 0xC, 0x40 - r // 2)
|
||||
put(a, 60, 3, 61, 4, 0xE, 0xC2)
|
||||
put(a, 2, 4, 56, 5, 0xE, 0x84)
|
||||
put(a, 20, 4, 0, 0, 0xE, 0x8C)
|
||||
put(a, 8, 5, 44, 2, 0xE, 0x82)
|
||||
put(a, 40, 5, 0, 0, 0x0, 0x00)
|
||||
# pattern b: portamento, vibrato, tremolo, offsets, fine slides, break
|
||||
put(b, 0, 0, 49, 1)
|
||||
put(b, 4, 0, 61, 0, 0x3, 0x08)
|
||||
put(b, 8, 0, 0, 0, 0x3, 0x00)
|
||||
put(b, 12, 0, 49, 0, 0x5, 0x02)
|
||||
put(b, 16, 0, 56, 5, 0x4, 0x46)
|
||||
put(b, 20, 0, 0, 0, 0x6, 0x01)
|
||||
put(b, 24, 0, 0, 0, 0x4, 0x8F)
|
||||
put(b, 0, 1, 37, 2, 0x7, 0x48)
|
||||
put(b, 8, 1, 0, 0, 0x7, 0x00)
|
||||
put(b, 16, 1, 44, 2, 0xE, 0x12)
|
||||
put(b, 17, 1, 0, 0, 0xE, 0x12)
|
||||
put(b, 20, 1, 0, 0, 0xE, 0x24)
|
||||
put(b, 24, 1, 0, 0, 0xE, 0xB8)
|
||||
put(b, 28, 1, 0, 0, 0xE, 0xA4)
|
||||
put(b, 0, 3, 49, 4, 0x9, 0x08)
|
||||
put(b, 24, 2, 49, 3, 0xF, 0x03)
|
||||
put(b, 24, 4, 0, 0, 0xF, 0x8C)
|
||||
put(b, 40, 2, 53, 3, 0xF, 0x06)
|
||||
put(b, 40, 4, 0, 0, 0xF, 0x7D)
|
||||
put(b, 44, 0, 49, 5)
|
||||
put(b, 48, 0, 0, 0, 0xD, 0x00)
|
||||
if keep is not None: # debugging: only some channels
|
||||
for p in (a, b):
|
||||
for row in p:
|
||||
for ch in range(6):
|
||||
if ch not in keep and row[ch][2] not in (0xB, 0xD, 0xF):
|
||||
row[ch] = (0, 0, 0, 0)
|
||||
return T.write_mtm("effects", samples(), [0, 1], [a, b], 6, pans=[3, 12, 7, 0, 15, 9], comment=b"test song".ljust(40, b"\0"))
|
||||
|
||||
|
||||
def song_quirk():
|
||||
"""speed and tempo commands never on one row: MultiTracker's reset (speed -> tempo 125, tempo -> speed 6)"""
|
||||
a, b = empty(4), empty(4)
|
||||
for r in range(0, 64, 4):
|
||||
put(a, r, 0, 49 + (r // 4) % 12, 1)
|
||||
put(b, r, 1, 61 - (r // 4) % 12, 2)
|
||||
put(a, 0, 3, 0, 0, 0xF, 0x03)
|
||||
put(a, 32, 3, 0, 0, 0xF, 0xA0)
|
||||
put(b, 16, 3, 0, 0, 0xF, 0x04)
|
||||
put(b, 40, 3, 0, 0, 0xF, 0x50)
|
||||
put(b, 0, 2, 37, 4, 0xB, 0x02)
|
||||
return T.write_mtm("quirk", samples(), [0, 1, 0], [a, b], 4)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for nm, data in (("effects", song_effects()), ("quirk", song_quirk())):
|
||||
ref = T.reference(ctx, data, "mtm")
|
||||
cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]})
|
||||
ctx.emit("mtm_cases", cases)
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# MUS fixtures (tools/fixtures.py): Doom MUS files written by tools/fixtures/_midivar.py (notes with and without volume,
|
||||
# releases, pitch wheel, controllers, program changes; system events and measure ends only in mus_measures, as wildmidi
|
||||
# misreads the first and refuses the second) and wildmidi -x's conversion of each as the reference event stream.
|
||||
# tests/gen/mus_cases.luau { { name, data, rate (wildmidi's effective tick rate), ref = { division, tempo,
|
||||
# events = { {seconds, status, d1, d2} } } } }
|
||||
import importlib.util, os
|
||||
|
||||
INPUTS = ["tools/fixtures/_midivar.py"]
|
||||
_spec = importlib.util.spec_from_file_location("_midivar", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_midivar.py"))
|
||||
M = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(M)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(0x4D55)
|
||||
cases = []
|
||||
for i in range(4):
|
||||
data = M.random_mus(rng, n=60 + 60 * i)
|
||||
ref = M.wildmidi(ctx, data, "mus")
|
||||
# wildmidi writes its tempo bytes in the wrong order (0x1B8A06 for 0x068A1B) at division 257: its MUS tick
|
||||
# rate is 257 / 1.804806 s, not Doom's 140 Hz
|
||||
rate = ref["division"] * 1e6 / ref["tempo"]
|
||||
cases.append({"name": "random %d" % i, "data": data, "rate": rate, "ref": ref})
|
||||
# system events and measure ends inserted with no delay: the same notes at the same times, more controllers
|
||||
plain = M.random_mus(ctx.rng(7), n=80)
|
||||
marked = M.random_mus(ctx.rng(7), n=80, extras=12)
|
||||
ctx.emit("mus_cases", cases)
|
||||
ctx.emit("mus_measures", {"plain": plain, "marked": marked})
|
||||
@@ -0,0 +1,105 @@
|
||||
# OKT fixtures (tools/fixtures.py): generated Oktalyzer modules exercising the effects and the mixed channel pairs,
|
||||
# rendered by openmpt123.
|
||||
# tests/gen/okt_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py),
|
||||
# duration (openmpt's song length) }
|
||||
import os, sys
|
||||
|
||||
# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
|
||||
T = sys.modules.get("_tracker")
|
||||
if T is None:
|
||||
import importlib.util
|
||||
_spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py"))
|
||||
T = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["_tracker"] = T
|
||||
_spec.loader.exec_module(T)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tracker.py"]
|
||||
|
||||
|
||||
def empty(ch, rows=64):
|
||||
return [[(0, 0, 0, 0) for _ in range(ch)] for _ in range(rows)]
|
||||
|
||||
|
||||
def put(p, row, ch, note=0, ins=0, fx=0, param=0):
|
||||
p[row][ch] = (note, ins, fx, param)
|
||||
|
||||
|
||||
def samples():
|
||||
return [
|
||||
{"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "type": 2, "loop": (0, 64)},
|
||||
{"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 44, "type": 1, "loop": (0, 64)},
|
||||
{"name": "saw", "data": T.s8(T.synth("saw", 128, 64, 0.6)), "volume": 64, "type": 0, "loop": (64, 64)},
|
||||
{"name": "noise", "data": T.s8(T.synth("noise", 4000, 1, 0.7, decay=1200)), "volume": 60, "type": 2},
|
||||
{"name": "tri", "data": T.s8(T.synth("tri", 32, 32, 0.8)), "volume": 52, "type": 2, "loop": (0, 32)},
|
||||
]
|
||||
|
||||
|
||||
def song_raw(keep=None):
|
||||
"""four raw Paula channels: slides, arpeggios, note slides, volume, release"""
|
||||
a, b = empty(4), empty(4, 48)
|
||||
mel = [13, 17, 20, 25, 20, 17, 15, 13]
|
||||
for i in range(16):
|
||||
put(a, i * 4, 0, mel[i % 8], 1)
|
||||
put(a, 2, 0, 0, 0, 10, 0x37) # arpeggio 1
|
||||
put(a, 10, 0, 0, 0, 11, 0x37) # arpeggio 2
|
||||
put(a, 18, 0, 0, 0, 12, 0x37) # arpeggio 3
|
||||
put(a, 0, 1, 1, 2)
|
||||
put(a, 4, 1, 0, 0, 1, 0x02) # period down (pitch up)
|
||||
put(a, 12, 1, 0, 0, 2, 0x03)
|
||||
put(a, 20, 1, 13, 2, 31, 0x20) # volume 0x20
|
||||
put(a, 24, 1, 0, 0, 31, 0x43) # slide down
|
||||
put(a, 28, 1, 0, 0, 31, 0x52) # slide up
|
||||
put(a, 32, 1, 0, 0, 31, 0x64) # fine down
|
||||
put(a, 36, 1, 0, 0, 31, 0x76) # fine up
|
||||
put(a, 40, 1, 8, 2, 30, 0x01) # note slide up every tick
|
||||
put(a, 44, 1, 0, 0, 13, 0x02)
|
||||
put(a, 48, 1, 0, 0, 17, 0x03) # once
|
||||
put(a, 52, 1, 0, 0, 21, 0x05)
|
||||
for r in range(0, 64, 8):
|
||||
put(a, r, 3, 13, 4)
|
||||
put(a, 2, 2, 25, 5)
|
||||
put(a, 30, 2, 0, 0, 27, 0) # release: the sustain loop ends
|
||||
put(a, 36, 2, 1, 5)
|
||||
put(a, 34, 3, 0, 0, 28, 0x04) # speed
|
||||
put(b, 0, 0, 13, 1)
|
||||
put(b, 8, 1, 20, 2)
|
||||
put(b, 16, 2, 13, 3) # a paired-only sample on a raw channel: stops it
|
||||
put(b, 24, 3, 25, 5, 25, 0x00) # jump to 0 (song end)
|
||||
if keep is not None:
|
||||
for p in (a, b):
|
||||
for row in p:
|
||||
for ch in range(4):
|
||||
if ch not in keep and row[ch][2] not in (25, 28):
|
||||
row[ch] = (0, 0, 0, 0)
|
||||
return T.write_okt(samples(), [0, 1], [a, b], speed=6)
|
||||
|
||||
|
||||
def song_pairs(keep=None):
|
||||
"""two mixed pairs (channels 2 / 3 and 5 / 6) and two raw channels"""
|
||||
a = empty(6)
|
||||
for r in range(0, 64, 4):
|
||||
put(a, r, 0, 13 + (r // 4) % 12, 1)
|
||||
put(a, r, 1, 1 + (r // 4) % 7, 3)
|
||||
put(a, r + 2, 2, 20, 1)
|
||||
put(a, 16, 1, 0, 0, 31, 0x30) # pair volume (shared)
|
||||
put(a, 32, 2, 0, 0, 31, 0x10) # the second channel's volume wins
|
||||
put(a, 40, 1, 0, 0, 31, 0x52) # pair volume slide
|
||||
put(a, 0, 3, 13, 2)
|
||||
put(a, 8, 4, 25, 4)
|
||||
put(a, 10, 5, 13, 5)
|
||||
put(a, 20, 5, 30, 1) # too high on a pair: clamped
|
||||
put(a, 48, 4, 13, 1, 31, 0x18)
|
||||
if keep is not None:
|
||||
for row in a:
|
||||
for ch in range(6):
|
||||
if ch not in keep:
|
||||
row[ch] = (0, 0, 0, 0)
|
||||
return T.write_okt(samples(), [0], [a], cmod=(1, 0, 1, 0), speed=5)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for nm, data in (("raw", song_raw()), ("pairs", song_pairs())):
|
||||
ref = T.reference(ctx, data, "okt")
|
||||
cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]})
|
||||
ctx.emit("okt_cases", cases)
|
||||
@@ -0,0 +1,89 @@
|
||||
# PTM fixtures (tools/fixtures.py): generated PolyTracker modules exercising the effects, rendered by openmpt123.
|
||||
# tests/gen/ptm_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py),
|
||||
# duration (openmpt's song length) }
|
||||
import os, sys
|
||||
|
||||
# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
|
||||
T = sys.modules.get("_tracker")
|
||||
if T is None:
|
||||
import importlib.util
|
||||
_spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py"))
|
||||
T = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["_tracker"] = T
|
||||
_spec.loader.exec_module(T)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tracker.py"]
|
||||
|
||||
|
||||
def empty(ch):
|
||||
return [[(0, 0, None, None, 0) for _ in range(ch)] for _ in range(64)]
|
||||
|
||||
|
||||
def put(p, row, ch, note=0, ins=0, vol=None, cmd=None, param=0):
|
||||
p[row][ch] = (note, ins, vol, cmd, param)
|
||||
|
||||
|
||||
def samples():
|
||||
return [
|
||||
{"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "c4spd": 8363, "loop": (0, 64)},
|
||||
{"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 40, "c4spd": 16726, "loop": (0, 64)},
|
||||
{"name": "saw16", "data": T.s16(T.synth("saw", 200, 100, 0.6)), "bits": 16, "volume": 64, "c4spd": 13000, "loop": (0, 200), "pingpong": True},
|
||||
{"name": "noise", "data": T.s8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 60, "c4spd": 8363},
|
||||
{"name": "tri", "data": T.s8(T.synth("tri", 50, 50, 0.8)), "volume": 50, "c4spd": 10000, "loop": (0, 50)},
|
||||
]
|
||||
|
||||
|
||||
def song_effects(keep=None):
|
||||
a, b = empty(6), empty(6)
|
||||
mel = [61, 65, 68, 73, 68, 65, 63, 61]
|
||||
for i in range(16):
|
||||
put(a, i * 4, 0, mel[i % 8], 1, None, 0x0 if i % 4 == 1 else None, 0x37)
|
||||
put(a, 0, 1, 49, 2, 48)
|
||||
put(a, 4, 1, 0, 0, None, 0xA, 0x04)
|
||||
put(a, 8, 1, 0, 0, None, 0xA, 0x20)
|
||||
put(a, 12, 1, 0, 0, None, 0xA, 0xF2) # S3M-style fine slide
|
||||
put(a, 16, 1, 51, 2, None, 0x2, 0x03)
|
||||
put(a, 20, 1, 0, 0, None, 0x1, 0x06)
|
||||
put(a, 24, 1, 0, 0, None, 0x1, 0xF4) # fine porta
|
||||
put(a, 28, 1, 56, 2, None, 0x4, 0x46)
|
||||
put(a, 36, 1, 0, 0, None, 0x6, 0x02)
|
||||
put(a, 40, 1, 49, 2)
|
||||
put(a, 41, 1, 61, 0, None, 0x3, 0x10)
|
||||
put(a, 44, 1, 0, 0, None, 0x5, 0x01)
|
||||
put(a, 48, 1, 54, 2, None, 0x7, 0x58)
|
||||
put(a, 56, 1, 0, 0, None, 0xC, 0x20)
|
||||
for r in range(0, 64, 8):
|
||||
put(a, r, 3, 61, 4, 64 - r // 2)
|
||||
put(a, 20, 3, 61, 4, None, 0x9, 0x08)
|
||||
put(a, 32, 3, 61, 4, None, 0xE, 0xC3)
|
||||
put(a, 40, 3, 61, 4, None, 0xE, 0xD2)
|
||||
put(a, 48, 3, 61, 4, None, 0x11, 0x03) # retrigger
|
||||
put(a, 4, 2, 37, 3, 50)
|
||||
put(a, 2, 4, 73, 5, None, 0x8, 0x30) # panning
|
||||
put(a, 18, 4, 0, 0, None, 0x8, 0xD0)
|
||||
put(a, 10, 5, 56, 1, None, 0x12, 0x46) # fine vibrato
|
||||
put(a, 24, 5, 0, 0, None, 0x13, 0x22) # note slide up: every 2 ticks by 2
|
||||
put(a, 30, 5, 0, 0, None, 0x14, 0x31) # note slide down
|
||||
put(a, 36, 5, 60, 1, None, 0x15, 0x21) # with retrigger
|
||||
put(b, 0, 0, 49, 1, None, 0xF, 0x04)
|
||||
put(b, 4, 0, 0, 0, None, 0xF, 0x90)
|
||||
put(b, 8, 0, 61, 1, None, 0x10, 0x20) # global volume
|
||||
put(b, 24, 0, 0, 0, None, 0x10, 0x40)
|
||||
put(b, 0, 2, 37, 3)
|
||||
put(b, 16, 2, 0, 0, None, 0xE, 0x92)
|
||||
put(b, 32, 4, 68, 5, None, 0xD, 0x00)
|
||||
if keep is not None:
|
||||
for p in (a, b):
|
||||
for row in p:
|
||||
for ch in range(6):
|
||||
if ch not in keep and row[ch][3] not in (0xD, 0xF, 0x10):
|
||||
row[ch] = (0, 0, None, None, 0)
|
||||
return T.write_ptm("effects", samples(), [0, 1], [a, b], 6, pans=[3, 12, 7, 0, 15, 9])
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for nm, data in (("effects", song_effects()),):
|
||||
ref = T.reference(ctx, data, "ptm")
|
||||
cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]})
|
||||
ctx.emit("ptm_cases", 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,90 @@
|
||||
# STM fixtures (tools/fixtures.py): generated Scream Tracker 2 modules exercising the effects, rendered by openmpt123.
|
||||
# tests/gen/stm_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py),
|
||||
# duration (openmpt's song length) }
|
||||
import os, sys
|
||||
|
||||
# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
|
||||
T = sys.modules.get("_tracker")
|
||||
if T is None:
|
||||
import importlib.util
|
||||
_spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py"))
|
||||
T = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["_tracker"] = T
|
||||
_spec.loader.exec_module(T)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tracker.py"]
|
||||
|
||||
A, B, C, D, E, F, G, H, I, J = range(1, 11)
|
||||
|
||||
|
||||
def empty():
|
||||
return [[(0, 0, None, 0, 0) for _ in range(4)] for _ in range(64)]
|
||||
|
||||
|
||||
def put(p, row, ch, note=0, ins=0, vol=None, cmd=0, info=0):
|
||||
p[row][ch] = (note, ins, vol, cmd, info)
|
||||
|
||||
|
||||
def samples():
|
||||
return [
|
||||
{"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 64, "c2spd": 8363, "loop": (0, 64)},
|
||||
{"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 40, "c2spd": 16726, "loop": (0, 64)},
|
||||
{"name": "saw", "data": T.s8(T.synth("saw", 100, 100, 0.6)), "volume": 64, "c2spd": 13000, "loop": (0, 100)},
|
||||
{"name": "noise", "data": T.s8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 60, "c2spd": 8363},
|
||||
{"name": "tri", "data": T.s8(T.synth("tri", 50, 50, 0.8)), "volume": 50, "c2spd": 10000, "loop": (0, 50)},
|
||||
]
|
||||
|
||||
|
||||
def song_effects():
|
||||
a, b, c = empty(), empty(), empty()
|
||||
mel = [61, 65, 68, 73, 68, 65, 63, 61]
|
||||
for i in range(16):
|
||||
put(a, i * 4, 0, mel[i % 8], 1, None, J if i % 4 == 1 else 0, 0x47 if i % 4 == 1 else 0)
|
||||
put(a, 0, 1, 49, 2, 48)
|
||||
put(a, 4, 1, 0, 0, None, D, 0x04)
|
||||
put(a, 8, 1, 0, 0, None, D, 0x20)
|
||||
put(a, 16, 1, 51, 2, None, E, 0x03)
|
||||
put(a, 20, 1, 0, 0, None, F, 0x06)
|
||||
put(a, 28, 1, 56, 2, None, H, 0x46)
|
||||
put(a, 40, 1, 49, 2, None, G, 0x00)
|
||||
put(a, 41, 1, 61, 0, None, G, 0x10)
|
||||
put(a, 52, 1, 0, 0, None, I, 0x21)
|
||||
for r in range(0, 64, 8):
|
||||
put(a, r, 3, 61, 4, 64 - r // 2)
|
||||
put(a, 24, 3, 254)
|
||||
put(a, 48, 2, 37, 3)
|
||||
put(a, 32, 2, 0, 0, None, A, 0x40) # ST2 tempo byte: speed 4, a fine tick length
|
||||
put(b, 0, 2, 49, 3, None, A, 0x63)
|
||||
put(b, 8, 2, 52, 5)
|
||||
put(b, 10, 0, 64, 1)
|
||||
put(b, 20, 0, 61, 1, 30)
|
||||
put(b, 24, 0, 254)
|
||||
put(b, 16, 1, 0, 0, None, B, 0x02) # deferred: taken at the C below (unreachable orders would be openmpt subsongs)
|
||||
put(b, 40, 3, 0, 0, None, C, 0x08)
|
||||
put(c, 8, 0, 49, 1, 32)
|
||||
put(c, 12, 1, 61, 2)
|
||||
put(c, 20, 0, 0, 0, None, B, 0x00) # deferred to the end of the pattern
|
||||
put(c, 30, 2, 0, 0, None, A, 0x8F)
|
||||
return T.write_stm("effects", samples(), [0, 1, 2], [a, b, c], tempo=0x60)
|
||||
|
||||
|
||||
def song_old():
|
||||
"""an ST 2.00 file: decimal tempo bytes, a short order list, no global volume"""
|
||||
a = empty()
|
||||
put(a, 0, 0, 61, 1)
|
||||
put(a, 8, 1, 68, 2)
|
||||
put(a, 16, 0, 0, 0, None, H, 0x28)
|
||||
put(a, 32, 1, 0, 0, None, A, 50) # decimal 50 = 0x50
|
||||
put(a, 40, 2, 49, 5, 40)
|
||||
put(a, 44, 3, 56, 3)
|
||||
put(a, 52, 3, "fb")
|
||||
put(a, 2, 0, "skip")
|
||||
return T.write_stm("old", samples(), [0], [a], tempo=72, gvol=20, minor=0)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for nm, data in (("effects", song_effects()), ("old", song_old())):
|
||||
ref = T.reference(ctx, data, "stm")
|
||||
cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]})
|
||||
ctx.emit("stm_cases", cases)
|
||||
@@ -0,0 +1,93 @@
|
||||
# TTA fixtures (tools/fixtures.py): audio/tta, codecs/audio/Tta.
|
||||
# tests/gen/tta_cases.luau synthetic signals encoded by the reference encoder (ttaenc 3.4.1: 8 / 16 / 24 bits,
|
||||
# 1 / 2 / 3 / 6 channels, odd rates, short and odd lengths, several frames, silence, noise,
|
||||
# full scale) and the ffmpeg FATE sample inside.tta (downloaded at fixture time, cut after 2
|
||||
# frames, not committed); each with the CRC-32 of `ttaenc -d`'s samples (i32 LE)
|
||||
import importlib.util, os, struct, tempfile, urllib.request, zlib
|
||||
|
||||
_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
_spec = importlib.util.spec_from_file_location("_wv", os.path.join(_dir, "wavpack.py"))
|
||||
WV = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(WV)
|
||||
_spec = importlib.util.spec_from_file_location("_ape", os.path.join(_dir, "ape.py"))
|
||||
APE = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(APE)
|
||||
|
||||
CTX = None
|
||||
TMP = None
|
||||
CASES = []
|
||||
FATE = "https://fate-suite.ffmpeg.org/lossless-audio/"
|
||||
|
||||
|
||||
def emit(name, tta, note, partial=False, keep=None):
|
||||
out = tta + ".out.wav"
|
||||
try:
|
||||
CTX.nix("ttaenc", ["ttaenc", "-d", tta, "-o", out])
|
||||
except Exception:
|
||||
if not partial:
|
||||
raise
|
||||
rate, ch, bits, fl, s = APE.wav_samples(out)
|
||||
if keep is not None: # a cut file: ttaenc also writes the broken frame; keep the whole ones
|
||||
s = s[:keep * ch]
|
||||
CASES.append({"name": name, "note": note, "data": open(tta, "rb").read(), "rate": rate, "channels": ch,
|
||||
"bits": bits, "float": False, "frames": len(s) // ch,
|
||||
"crc": zlib.crc32(b"".join(struct.pack("<i", v) for v in s)), "partial": partial})
|
||||
|
||||
|
||||
def plain_wav(path, vals, ch, rate, bits):
|
||||
"""a plain PCM WAV (ttaenc reads WAVE_FORMAT_PCM)"""
|
||||
w = bits // 8
|
||||
top = (1 << (bits - 1)) - 1
|
||||
data = bytearray()
|
||||
for v in vals:
|
||||
x = max(-top - 1, min(top, int(round(v * top))))
|
||||
data += bytes([(x + 128) & 255]) if w == 1 else x.to_bytes(w, "little", signed=True)
|
||||
fmt = struct.pack("<HHIIHH", 1, ch, rate, rate * ch * w, ch * w, bits)
|
||||
body = b"WAVE" + b"fmt " + struct.pack("<I", len(fmt)) + fmt + b"data" + struct.pack("<I", len(data)) + bytes(data)
|
||||
open(path, "wb").write(b"RIFF" + struct.pack("<I", len(body)) + body)
|
||||
|
||||
|
||||
def case(name, secs=0.3, rate=44100, ch=2, bits=16, kind="music", seed=1, frames=None, note=None):
|
||||
wav = os.path.join(TMP, name + ".wav")
|
||||
tta = os.path.join(TMP, name + ".tta")
|
||||
plain_wav(wav, WV.signal(secs, rate, ch, kind, seed, frames), ch, rate, bits)
|
||||
CTX.nix("ttaenc", ["ttaenc", "-e", wav, "-o", tta])
|
||||
emit(name, tta, note or "ttaenc -e, %d-bit, %d ch, %d Hz" % (bits, ch, rate))
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
global CTX, TMP
|
||||
CTX = ctx
|
||||
APE.CTX = ctx
|
||||
TMP = tempfile.mkdtemp()
|
||||
CASES.clear()
|
||||
case("s16")
|
||||
case("s16_long", secs=3.0, seed=2, note="3 s, 3 frames (bench + seek)")
|
||||
case("mono", ch=1)
|
||||
case("u8", bits=8, ch=1, rate=8000, kind="mixed")
|
||||
case("u8_stereo", bits=8, rate=11025)
|
||||
case("s24", bits=24, rate=48000, secs=0.3)
|
||||
case("s24_mixed", bits=24, rate=96000, secs=0.2, kind="mixed")
|
||||
case("s24_mono", bits=24, ch=1, rate=48000)
|
||||
case("ch3", ch=3, secs=0.2)
|
||||
case("ch6", ch=6, rate=48000, secs=0.2)
|
||||
case("noise", kind="noise", secs=0.2)
|
||||
case("noise24", bits=24, kind="noise", secs=0.1)
|
||||
case("silence", kind="silence")
|
||||
case("mixed", kind="mixed", secs=0.4)
|
||||
case("one_frame", frames=1)
|
||||
case("seven_frames", frames=7, ch=1)
|
||||
case("odd_len", frames=100001, rate=48000, seed=7, note="100001 frames: 3 TTA frames, a short last one")
|
||||
case("rate37000", rate=37000, secs=0.2)
|
||||
case("rate8000", rate=8000, secs=1.5, ch=1, note="8 kHz: 8359-sample frames")
|
||||
path = os.path.join(TMP, "inside.tta")
|
||||
try:
|
||||
with urllib.request.urlopen(FATE + "inside.tta", timeout=60) as r:
|
||||
data = r.read()
|
||||
frames = (struct.unpack_from("<I", data, 18)[0] + 46079) // 46080
|
||||
sizes = struct.unpack_from("<%dI" % frames, data, 22)
|
||||
open(path, "wb").write(data[:22 + frames * 4 + 4 + sizes[0] + sizes[1] + 100])
|
||||
emit("fate_inside", path, "ffmpeg FATE sample inside.tta (cut after 2 frames)", partial=True, keep=2 * 46080)
|
||||
except OSError as e: # offline: skip the FATE sample
|
||||
print("tta: skipping inside.tta (%s)" % e)
|
||||
ctx.emit("tta_cases", CASES)
|
||||
@@ -0,0 +1,95 @@
|
||||
# ULT fixtures (tools/fixtures.py): generated UltraTracker modules exercising the effects (two per cell), rendered by
|
||||
# openmpt123.
|
||||
# tests/gen/ult_cases.luau { name, data (the module), ref (features of openmpt's render, tools/fixtures/_tracker.py),
|
||||
# duration (openmpt's song length) }
|
||||
import os, sys
|
||||
|
||||
# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
|
||||
T = sys.modules.get("_tracker")
|
||||
if T is None:
|
||||
import importlib.util
|
||||
_spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py"))
|
||||
T = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["_tracker"] = T
|
||||
_spec.loader.exec_module(T)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tracker.py"]
|
||||
|
||||
|
||||
def empty(ch):
|
||||
return [[(0, 0, 0, 0, 0, 0) for _ in range(ch)] for _ in range(64)]
|
||||
|
||||
|
||||
def put(p, row, ch, note=0, ins=0, e1=0, p1=0, e2=0, p2=0):
|
||||
p[row][ch] = (note, ins, e1, p1, e2, p2)
|
||||
|
||||
|
||||
def samples():
|
||||
return [
|
||||
{"name": "sine", "data": T.s8(T.synth("sine", 64, 64)), "volume": 255, "loop": (0, 64)},
|
||||
{"name": "square", "data": T.s8(T.synth("square", 64, 64, 0.5)), "volume": 180, "speed": 16726, "loop": (0, 64)},
|
||||
{"name": "saw16", "data": T.s16(T.synth("saw", 200, 100, 0.6)), "bits": 16, "volume": 240, "loop": (0, 200), "pingpong": True},
|
||||
{"name": "noise", "data": T.s8(T.synth("noise", 6000, 1, 0.7, decay=1500)), "volume": 230},
|
||||
{"name": "tri", "data": T.s8(T.synth("tri", 50, 50, 0.8)), "volume": 200, "speed": 10000, "finetune": 3000, "loop": (0, 50)},
|
||||
]
|
||||
|
||||
|
||||
def song_effects(keep=None):
|
||||
a, b = empty(6), empty(6)
|
||||
mel = [61, 65, 68, 73, 68, 65, 63, 61]
|
||||
for i in range(16):
|
||||
put(a, i * 4, 0, mel[i % 8], 1, 0xC, 0x80 + i * 8) # note + set volume (volume column)
|
||||
put(a, 0, 1, 49, 2)
|
||||
put(a, 4, 1, 0, 0, 0xA, 0x04) # volume slide down
|
||||
put(a, 8, 1, 0, 0, 0xA, 0x20, 0x4, 0x46) # slide + vibrato: two columns
|
||||
put(a, 16, 1, 51, 2, 0x2, 0x03)
|
||||
put(a, 20, 1, 0, 0, 0x1, 0x06, 0xB, 0x0C) # porta up + panning
|
||||
put(a, 24, 1, 0, 0, 0xE, 0x14) # fine porta up
|
||||
put(a, 28, 1, 56, 2, 0x4, 0x46)
|
||||
put(a, 40, 1, 49, 2)
|
||||
put(a, 41, 1, 61, 0, 0x3, 0x10) # tone portamento (keeps going)
|
||||
put(a, 48, 1, 54, 2, 0x7, 0x58) # tremolo (v4)
|
||||
put(a, 56, 1, 0, 0, 0xE, 0xA4)
|
||||
put(a, 58, 1, 0, 0, 0xE, 0xB8)
|
||||
for r in range(0, 64, 8):
|
||||
put(a, r, 3, 61, 4, 0xC, 255 - r * 3)
|
||||
put(a, 20, 3, 61, 4, 0x9, 0x20) # offset (x 4)
|
||||
put(a, 32, 3, 61, 4, 0xE, 0xC3) # note cut
|
||||
put(a, 40, 3, 61, 4, 0xE, 0xD2) # note delay
|
||||
put(a, 4, 2, 37, 3)
|
||||
put(a, 30, 2, 0, 0, 0x5, 0x0C) # key off: the sustain loop ends
|
||||
put(a, 36, 2, 44, 3, 0x0, 0x47) # arpeggio
|
||||
put(a, 2, 4, 73, 5, 0xB, 0x03)
|
||||
put(a, 44, 4, 0, 0, 0xE, 0x93) # retrigger
|
||||
put(a, 10, 5, 56, 1, 0xF, 0x04) # speed
|
||||
put(a, 34, 5, 0, 0, 0xF, 0x90) # tempo
|
||||
put(b, 0, 0, 49, 1, 0xC, 0xFF, 0xF, 0x05) # volume + speed in one cell
|
||||
put(b, 8, 0, 61, 1, 0x1, 0x04, 0xA, 0x03) # porta up -> volume column
|
||||
put(b, 16, 0, 56, 1, 0x3, 0x08, 0x4, 0x05) # tone porta + vibrato depth
|
||||
put(b, 24, 2, 49, 3, 0xE, 0x84) # fine pattern delay
|
||||
put(b, 0, 5, 37, 2, 0xA, 0xF0, 0x3, 0x00)
|
||||
put(b, 32, 4, 68, 5, 0xD, 0x00, 0xC, 0x60) # break + volume
|
||||
if keep is not None: # debugging: only some channels (their speed / tempo / break effects stay)
|
||||
for p in (a, b):
|
||||
for row in p:
|
||||
for ch in range(6):
|
||||
if ch not in keep and row[ch][2] not in (0xD, 0xF) and row[ch][4] not in (0xD, 0xF):
|
||||
row[ch] = (0, 0, 0, 0, 0, 0)
|
||||
return T.write_ult("effects", samples(), [0, 1], [a, b], 6, pans=[3, 12, 7, 0, 15, 9])
|
||||
|
||||
|
||||
def song_old():
|
||||
"""a v1.3 file: no tremolo, no sample speed; arpeggio"""
|
||||
a = empty(4)
|
||||
for r in range(0, 64, 4):
|
||||
put(a, r, r // 4 % 4, 49 + (r // 4) % 12, 1 + r // 4 % 3, 0x0, 0x37)
|
||||
put(a, 32, 0, 0, 0, 0xF, 0x03)
|
||||
return T.write_ult("old", samples(), [0, 0], [a], 4, version=3)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for nm, data in (("effects", song_effects()), ("old", song_old())):
|
||||
ref = T.reference(ctx, data, "ult")
|
||||
cases.append({"name": nm, "data": data, "ref": ref, "duration": ref["duration"]})
|
||||
ctx.emit("ult_cases", cases)
|
||||
@@ -0,0 +1,34 @@
|
||||
# UMX fixtures (tools/fixtures.py): Unreal music packages wrapping generated modules (an S3M from tools/fixtures/s3m.py,
|
||||
# an IT from tools/fixtures/it.py), rendered by openmpt123 (which unwraps the package itself).
|
||||
# tests/gen/umx_cases.luau { name, data (the package), inner (the embedded module), format (its format), ref
|
||||
# (features of openmpt's render, tools/fixtures/_tracker.py), duration }
|
||||
import importlib.util, os, sys
|
||||
|
||||
# the shared tracker module, loaded by path (tools/fixtures/ must not go on sys.path: xml.py there would shadow xml)
|
||||
T = sys.modules.get("_tracker")
|
||||
if T is None:
|
||||
_spec = importlib.util.spec_from_file_location("_tracker", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tracker.py"))
|
||||
T = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["_tracker"] = T
|
||||
_spec.loader.exec_module(T)
|
||||
|
||||
INPUTS = ["tools/fixtures/_tracker.py", "tools/fixtures/s3m.py", "tools/fixtures/it.py"]
|
||||
|
||||
|
||||
def sibling(name):
|
||||
spec = importlib.util.spec_from_file_location("umx_" + name, os.path.join(os.path.dirname(os.path.abspath(__file__)), name + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
s3m = sibling("s3m").song_mono()
|
||||
it = sibling("it").song_effects()
|
||||
cases = []
|
||||
items = [("s3m", "Mono_Theme", s3m, 69), ("it", "Effects", it, 63)]
|
||||
for fmt, nm, data, ver in items:
|
||||
pkg = T.write_umx([(nm, data)], version=ver)
|
||||
ref = T.reference(ctx, pkg, "umx")
|
||||
cases.append({"name": nm, "data": pkg, "inner": data, "format": fmt, "ref": ref, "duration": ref["duration"]})
|
||||
ctx.emit("umx_cases", cases)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,177 @@
|
||||
# WavPack fixtures (tools/fixtures.py): audio/wavpack, codecs/audio/WavPack.
|
||||
# tests/gen/wavpack_cases.luau synthetic signals encoded by the reference encoder (wavpack 5.9: -f / default / -h /
|
||||
# -hh / -x1..6, joint stereo on / off, 8 / 12 / 16 / 20 / 24 / 32-bit int and 32-bit
|
||||
# float, 1 / 2 / 3 / 6 / 8 channels, odd rates, short and odd lengths, small blocks,
|
||||
# hybrid lossy (-b, noise shaping) and hybrid lossless (+ the .wvc), APEv2 tags, MD5)
|
||||
# and by ffmpeg's encoder; each with the CRC-32 of wvunpack's raw output (integers as
|
||||
# i32 LE, floats as their f32 bytes)
|
||||
import math, os, random, struct, tempfile, zlib
|
||||
|
||||
CTX = None
|
||||
TMP = None
|
||||
CASES = []
|
||||
|
||||
|
||||
def signal(secs, rate, ch, kind="music", seed=1, frames=None):
|
||||
"""floats in -1..1, interleaved"""
|
||||
rnd = random.Random(seed)
|
||||
n = frames if frames is not None else int(secs * rate)
|
||||
out = []
|
||||
notes = [(rnd.uniform(80, 1500), rnd.uniform(0, max(n, 1)), rnd.uniform(0.1, 0.5) * rate) for _ in range(int(n / rate * 6) + 3)]
|
||||
for i in range(n):
|
||||
t = i / rate
|
||||
for c in range(ch):
|
||||
if kind == "noise":
|
||||
v = rnd.uniform(-0.95, 0.95)
|
||||
elif kind == "silence":
|
||||
v = 0.0
|
||||
elif kind == "mixed": # silence, a tone, noise bursts, full scale
|
||||
seg = (i * 8 // max(n, 1))
|
||||
if seg in (0, 4):
|
||||
v = 0.0
|
||||
elif seg == 5:
|
||||
v = rnd.uniform(-1, 1)
|
||||
elif seg == 6:
|
||||
v = 0.999 if (i // 37) % 2 else -1.0
|
||||
else:
|
||||
v = 0.7 * math.sin(2 * math.pi * (300 + 50 * c) * t)
|
||||
else:
|
||||
v = 0.0
|
||||
for f, st, dur in notes:
|
||||
if st <= i < st + dur:
|
||||
e = math.exp(-3 * (i - st) / dur) * min(1.0, (i - st) / 100)
|
||||
v += 0.25 * e * (math.sin(2 * math.pi * f * (1 + 0.002 * c) * t) + 0.3 * math.sin(6 * math.pi * f * t + c))
|
||||
v += 0.003 * (rnd.random() - 0.5) + 0.04 * math.sin(2 * math.pi * (60 + 7 * c) * t)
|
||||
out.append(max(-1.0, min(1.0, v)))
|
||||
return out
|
||||
|
||||
|
||||
def write_wav(path, vals, ch, rate, bits, fl=False):
|
||||
container = 32 if fl else (bits + 7) // 8 * 8
|
||||
data = bytearray()
|
||||
top = (1 << (bits - 1)) - 1
|
||||
for v in vals:
|
||||
if fl:
|
||||
data += struct.pack("<f", v)
|
||||
continue
|
||||
x = int(round(v * top)) if v < 1 else top
|
||||
x = max(-top - 1, min(top, x)) << (container - bits)
|
||||
if container == 8:
|
||||
data.append((x + 128) & 255)
|
||||
else:
|
||||
data += x.to_bytes(container // 8, "little", signed=True)
|
||||
sub = b"\x03\x00" if fl else b"\x01\x00"
|
||||
guid = sub + b"\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x00\x38\x9b\x71"
|
||||
mask = {1: 4, 2: 3, 3: 7, 4: 0x33, 6: 0x3F, 8: 0x63F}.get(ch, 0)
|
||||
fmt = struct.pack("<HHIIHHHHI16s", 0xFFFE, ch, rate, rate * ch * container // 8, ch * container // 8, container,
|
||||
22, bits, mask, guid)
|
||||
body = b"WAVE" + b"fmt " + struct.pack("<I", len(fmt)) + fmt + b"data" + struct.pack("<I", len(data)) + bytes(data)
|
||||
open(path, "wb").write(b"RIFF" + struct.pack("<I", len(body)) + body)
|
||||
|
||||
|
||||
def reference(wv, container, fl, ignore_wvc=False):
|
||||
raw = wv + ".raw"
|
||||
CTX.nix("wavpack", ["wvunpack", "-q", "-y", "-r"] + (["-i"] if ignore_wvc else []) + [wv, "-o", raw])
|
||||
d = open(raw, "rb").read()
|
||||
if fl:
|
||||
return zlib.crc32(d), len(d) // 4
|
||||
w = container // 8
|
||||
if w == 1:
|
||||
ints = [b - 128 for b in d]
|
||||
else:
|
||||
ints = [int.from_bytes(d[i:i + w], "little", signed=True) for i in range(0, len(d), w)]
|
||||
return zlib.crc32(b"".join(struct.pack("<i", v) for v in ints)), len(ints)
|
||||
|
||||
|
||||
def case(name, args, secs=0.3, rate=44100, ch=2, bits=16, fl=False, kind="music", seed=1, frames=None, note=None,
|
||||
wvc=False, lossy=False, tags=None, ffmpeg=None):
|
||||
if fl:
|
||||
bits = 32
|
||||
wav = os.path.join(TMP, name + ".wav")
|
||||
wv = os.path.join(TMP, name + ".wv")
|
||||
write_wav(wav, signal(secs, rate, ch, kind, seed, frames), ch, rate, bits, fl)
|
||||
if ffmpeg is not None:
|
||||
CTX.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y", "-i", wav] + ffmpeg + [wv])
|
||||
else:
|
||||
CTX.nix("wavpack", ["wavpack", "-q", "-y"] + args + [wav, "-o", wv])
|
||||
data = open(wv, "rb").read()
|
||||
k = 0
|
||||
while struct.unpack_from("<I", data, k + 20)[0] == 0: # the first audio block's flags give the container
|
||||
k += 8 + struct.unpack_from("<I", data, k + 4)[0]
|
||||
flags = struct.unpack_from("<I", data, k + 24)[0]
|
||||
container = ((flags & 3) + 1) * 8
|
||||
crc, count = reference(wv, container, fl, ignore_wvc=lossy)
|
||||
c = {"name": name, "note": note or ("ffmpeg " + " ".join(ffmpeg) if ffmpeg is not None else "wavpack " + " ".join(args)),
|
||||
"data": data, "rate": rate, "channels": ch, "bits": bits, "container": container,
|
||||
"float": fl, "frames": count // ch, "crc": crc, "lossy": lossy}
|
||||
if wvc:
|
||||
c["wvc"] = open(wv + "c", "rb").read()
|
||||
c["lossy_crc"] = reference(wv, container, fl, ignore_wvc=True)[0]
|
||||
if tags:
|
||||
c["tags"] = tags
|
||||
CASES.append(c)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
global CTX, TMP
|
||||
CTX = ctx
|
||||
TMP = tempfile.mkdtemp()
|
||||
CASES.clear()
|
||||
for mode in ("-f", "-g", "-h", "-hh"):
|
||||
case("s16" + mode.replace("-", "_"), [mode])
|
||||
for x in range(1, 7):
|
||||
case("s16_x%d" % x, ["-x%d" % x], secs=0.2, seed=x)
|
||||
case("s16_hhx6", ["-hh", "-x6"], seed=7)
|
||||
case("s16_j0", ["-j0"], seed=8)
|
||||
case("s16_j1_hh", ["-j1", "-hh"], seed=9)
|
||||
case("s16_long", ["-h"], secs=3.0, seed=2, note="wavpack -h, 3 s (bench + seek)")
|
||||
case("mono16", ["-g"], ch=1)
|
||||
case("mono16_hh", ["-hh", "-x4"], ch=1, rate=22050)
|
||||
case("u8", ["-g"], bits=8, ch=1, rate=8000, kind="mixed")
|
||||
case("u8_stereo", ["-h"], bits=8, rate=11025)
|
||||
case("s12", ["-g"], bits=12, rate=32000)
|
||||
case("s20", ["-hh"], bits=20, rate=48000)
|
||||
case("s24", ["-g"], bits=24, rate=96000, secs=0.2)
|
||||
case("s24_hh", ["-hh", "-x3"], bits=24, rate=48000, kind="mixed")
|
||||
case("s32", ["-g"], bits=32, rate=48000, secs=0.2)
|
||||
case("s32_hh", ["-hh"], bits=32, rate=48000, secs=0.2, kind="mixed")
|
||||
case("s32_opt", ["--optimize-int32"], bits=32, rate=48000, secs=0.2)
|
||||
case("f32", ["-g"], fl=True, rate=48000, secs=0.2)
|
||||
case("f32_hh", ["-hh", "-x2"], fl=True, rate=44100, kind="mixed")
|
||||
case("f32_mono", ["-f"], fl=True, ch=1, rate=22050)
|
||||
case("ch3", ["-g"], ch=3, bits=24, secs=0.2)
|
||||
case("ch6", ["-h"], ch=6, rate=48000, secs=0.2)
|
||||
case("ch8", ["-f"], ch=8, rate=48000, secs=0.1)
|
||||
case("noise", ["-g"], kind="noise", secs=0.2)
|
||||
case("silence", ["-g"], kind="silence", secs=0.3)
|
||||
case("mixed", ["-hh"], kind="mixed", secs=0.4)
|
||||
case("one_frame", ["-g"], frames=1)
|
||||
case("seven_frames", ["-h"], frames=7, ch=1)
|
||||
case("odd_len", ["-g", "--blocksize=1001"], frames=12345, seed=3, note="block size 1001, 12345 frames")
|
||||
case("rate37000", ["-g"], rate=37000, secs=0.2, note="a rate without a header code")
|
||||
case("rate7", ["-g"], rate=7, frames=300, note="7 Hz")
|
||||
case("md5_tags", ["-g", "-m", "-w", "Title=Lossless Tone", "-w", "Artist=formats-luau", "-w", "Year=2026",
|
||||
"-w", "Track=3/9", "-w", "Album Artist=Some Band"],
|
||||
tags={"title": "Lossless Tone", "artist": "formats-luau", "date": "2026", "track": "3/9",
|
||||
"albumartist": "Some Band"})
|
||||
# hybrid: lossy (no correction file), and lossless with the .wvc
|
||||
case("hyb_b3", ["-b3"], lossy=True, note="hybrid lossy, 3 bits / sample")
|
||||
case("hyb_b2_mono", ["-b2.5", "-h"], ch=1, lossy=True)
|
||||
case("hyb_b4_s0", ["-b4", "-s0"], lossy=True, note="hybrid lossy, no noise shaping")
|
||||
case("hyb_b3_24", ["-b3.5", "-hh"], bits=24, rate=48000, lossy=True)
|
||||
case("hyb_c3", ["-b3", "-c"], wvc=True, note="hybrid lossless (wv + wvc)")
|
||||
case("hyb_c3_shape", ["-b3", "-c", "-s0.5"], wvc=True, seed=4, note="hybrid lossless, positive noise shaping")
|
||||
case("hyb_c3_neg", ["-b3", "-c", "-s-0.5"], wvc=True, seed=5, note="hybrid lossless, negative shaping (NEW_SHAPING)")
|
||||
case("hyb_cc", ["-b2.5", "-cc", "-h"], wvc=True, seed=6, note="hybrid lossless, max compression (cross decorr)")
|
||||
case("hyb_c_mono", ["-b3", "-c", "-hh"], ch=1, wvc=True)
|
||||
case("hyb_c_dns", ["-b3", "-c", "--use-dns"], wvc=True, seed=10, note="dynamic noise shaping")
|
||||
case("hyb_c_24", ["-b4", "-c", "-x3"], bits=24, rate=48000, wvc=True)
|
||||
case("hyb_c_f32", ["-b4", "-c"], fl=True, wvc=True, note="hybrid lossless float (wvx in the wvc)")
|
||||
case("hyb_c_ch6", ["-b3", "-c"], ch=6, rate=48000, secs=0.2, wvc=True)
|
||||
# ffmpeg's encoder
|
||||
case("ff_s16", [], ffmpeg=["-c:a", "wavpack"])
|
||||
case("ff_l8", [], ffmpeg=["-c:a", "wavpack", "-compression_level", "8"], seed=11)
|
||||
case("ff_s24", [], bits=24, ffmpeg=["-c:a", "wavpack", "-sample_fmt", "s32p"], seed=12)
|
||||
case("ff_f32", [], fl=True, ffmpeg=["-c:a", "wavpack"], seed=13)
|
||||
case("ff_mono", [], ch=1, ffmpeg=["-c:a", "wavpack", "-compression_level", "3"], seed=14)
|
||||
ctx.emit("wavpack_cases", CASES)
|
||||
+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)
|
||||
@@ -0,0 +1,26 @@
|
||||
# XMIDI fixtures (tools/fixtures.py): XMI files written by tools/fixtures/_midivar.py (FORM XDIR + CAT XMID with one or
|
||||
# two songs, a bare FORM XMID (its reference converted from the same song with XDIR); every channel event, note durations, sysex, meta) and wildmidi -x's conversion of song 1
|
||||
# as the reference event stream. Each song starts with a tempo event, as real files do (wildmidi derives its 120 Hz
|
||||
# conversion from the first tempo event).
|
||||
# tests/gen/xmi_cases.luau { { name, data, songs, ref = { division, tempo, events = { {seconds, status, d1, d2} } } } }
|
||||
import importlib.util, os
|
||||
|
||||
INPUTS = ["tools/fixtures/_midivar.py"]
|
||||
_spec = importlib.util.spec_from_file_location("_midivar", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_midivar.py"))
|
||||
M = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(M)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(0x584D49)
|
||||
cases = []
|
||||
for i in range(4):
|
||||
songs = [M.random_xmi_song(rng, n=60 + 40 * i, tempo=rng.choice([500000, 1000000, 400000]))]
|
||||
if i == 1:
|
||||
songs.append(M.random_xmi_song(rng, n=20, tempo=500000))
|
||||
data = M.write_xmi(songs, timb=(i != 3))
|
||||
ref = M.wildmidi(ctx, data, "xmi")
|
||||
if i == 2:
|
||||
data = M.write_xmi(songs, with_xdir=False) # a bare FORM XMID (wildmidi wants XDIR: the reference comes from the full file)
|
||||
cases.append({"name": "random %d" % i, "data": data, "songs": len(songs), "ref": ref})
|
||||
ctx.emit("xmi_cases", cases)
|
||||
Reference in new issue
Block a user