Files
rosetta/tools/fixtures/_hively.py
T

206 lines
11 KiB
Python

# 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)