Files
sloop-fm1/tools/level_presets.py
T

77 lines
3.5 KiB
Python

#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-only
"""Measures every factory preset and writes firmware/src/preset_trim.h: a level trim per preset
(1/2 dB, the steps of LEVEL), so every sound comes out as loud as the others at the same LEVEL.
Loudness: ITU-R BS.1770 integrated (gated) over a phrase that fits the sound (tests/preset_level.c:
a bass line, held chords, comping or a melody).
cc -O2 -Ibuild/gen -Ifirmware/src -Ifirmware/hal tests/preset_level.c -lm -o build/host/preset_level
build/host/preset_level build/host/presets.wav build/host/presets.txt build/host/presets.raw
tools/level_presets.py build/host/presets.raw build/host/presets.txt
(rebuild and run it again until nothing moves: the trims add to the ones in preset_trim.h)
Needs numpy and scipy."""
import re
import sys
from pathlib import Path
import numpy as np
from scipy.signal import lfilter
FS, CTL = 44100, 32
SEG = (FS * 9 // 2) // CTL * CTL + (FS // 4) // CTL * CTL
OUT = Path(__file__).resolve().parent.parent / "firmware/src/preset_trim.h"
TARGET = -15.0 # LUFS (integrated), at the default LEVEL
ROLE = {0: 0.0, 1: -1.0, 2: 0.0, 3: 0.0, 4: 0.0} # bass, chords held (pads, organs), comping, melody, one-key chords
SKIP = {"GM KIT"} # (the drum map on a synth track: as it is)
def lufs(x):
b1 = [1.53512485958697, -2.69169618940638, 1.19839281085285]
a1 = [1, -1.69065929318241, 0.73248077421585]
b2, a2 = [1, -2, 1], [1, -1.99004745483398, 0.99007225036621]
k = lfilter(b2, a2, lfilter(b1, a1, x)) ** 2
w, h = int(0.4 * FS), int(0.1 * FS)
bl = np.array([k[i:i + w].mean() for i in range(0, len(k) - w, h)])
bl = bl[bl > 1e-7]
if not len(bl):
return None
g = bl[10 * np.log10(bl) - 0.691 > -70]
rel = 10 * np.log10(g.mean()) - 0.691 - 10
g = g[10 * np.log10(g) - 0.691 > rel]
return 10 * np.log10(g.mean()) - 0.691
def main(raw, rep):
rows = [l.split(None, 3) for l in Path(rep).read_text().splitlines()]
d = np.fromfile(raw, np.int32).astype(float) / 32768.0
old = {}
if OUT.exists():
for e, name, v in re.findall(r"/\* (\d+)\.\d+ (.*?) \*/ (-?\d+)", OUT.read_text()):
old[(int(e), name)] = int(v) # (by name: presets may move in their table)
neng = max(int(r[0]) for r in rows) + 1
pmax = 16
tab = [[0] * pmax for _ in range(neng)]
names = [[""] * pmax for _ in range(neng)]
for i, (e, p, role, name) in enumerate(rows):
e, p, role = int(e), int(p), int(role)
assert p < pmax, name
names[e][p] = name
L = lufs(d[i * SEG:(i + 1) * SEG])
t = old.get((e, name), 0)
if L is not None and name not in SKIP:
t += int(round((TARGET + ROLE[role] - L) * 2))
tab[e][p] = max(-40, min(23, t)) # (LEVEL 104 + 23 = 127: the top of the table)
lines = ["/* generated by tools/level_presets.py: the level trim of each factory preset, 1/2 dB */",
"#pragma once", f"#define PT_ENGINES {neng}u", f"#define PT_MAX {pmax}u",
"static const int8_t PRESET_TRIM[PT_ENGINES][PT_MAX] = {"]
for e in range(neng):
cells = [f"/* {e}.{p} {names[e][p] or '-'} */ {tab[e][p]}" for p in range(pmax) if names[e][p]]
lines.append(" {" + ", ".join(cells) + "},")
lines.append("};")
OUT.write_text("\n".join(lines) + "\n")
print(f"{len(rows)} presets levelled -> {OUT}")
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])