Files
BetterDSPControl/tests/test_protocol.py
T
GivouandClaude Opus 5.5 63b3c17fb7 DJ Brake: use the offset measured on a real DSP 204
Measured: limiter threshold minus output meter is about 26 dB when the limiter
starts (25.1 to 27.7, one DSP 204, one output, one piece of music), and the meter
is after the output gain. So the distance is right before the first hit.
The limiter flag also stayed on after raising a threshold, which would have
taught a false value: only limiters starting by themselves teach now.
The measuring tool no longer draws conclusions the data doesn't carry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 21:54:29 +01:00

359 lines
17 KiB
Python

"""Protocol self test: python tests/test_protocol.py"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from dsp import protocol as P # noqa: E402
def test_frames_match_known_captures():
# Known-good frames as sent to the devices (they also match the DSP 408 captures published by dsp-408-ui)
assert P.build_frame(0x10) == bytes.fromhex("10 02 00 01 01 10 10 03 11")
assert P.build_frame(0x40) == bytes.fromhex("10 02 00 01 01 40 10 03 41")
assert P.build_frame(0x29, b"\x13") == bytes.fromhex("10 02 00 01 02 29 13 10 03 38")
assert P.build_frame(0x35, b"\x0b\x01") == bytes.fromhex("10 02 00 01 03 35 0b 01 10 03 3c")
def test_parser_handles_split_and_embedded_dle():
payload = bytes([5]) + b"\x10\x03\x10\x02" + bytes(46)
frame = P.build_frame(P.CMD_CONFIG_CHUNK, payload, addr=0, src=1)
parser = P.FrameParser()
out = parser.feed(b"\x00garbage" + frame[:7]) + parser.feed(frame[7:] + P.build_frame(0x01, b"\x00"))
assert [f.cmd for f in out] == [P.CMD_CONFIG_CHUNK, 0x01]
assert out[0].payload == payload and out[0].checksum_ok
def test_layout_matches_devices():
m204, m408 = P.MODELS["204"], P.MODELS["408"]
assert (m204.size, m204.chunks) == (724, 15)
assert (m408.size, m408.chunks) == (1448, 29)
assert m204.out_base == 0x128 and m204.globals_base == 0x2B8
assert m408.out_base == 0x240 and m408.globals_base == 0x580
assert m204.channel("out", 0) == 2 and m408.channel("out", 0) == 4
def test_state_roundtrip():
for m in (m for m in P.MODELS.values() if not m.fir):
st = P.default_state(m)
st["outputs"][-1]["comp"]["threshold"] = 123
st["inputs"][0]["geq"][30] = 7
st["inputs"][-1]["mute"] = True
assert P.parse_state(m, bytes(P.build_state_buffer(m, st))) == st
def test_scales():
assert P.gain_to_db(0) == -60 and P.gain_to_db(80) == -20 and P.gain_to_db(280) == 0 and P.gain_to_db(400) == 12
for raw in (0, 37, 80, 150, 280, 400):
assert P.db_to_gain(P.gain_to_db(raw)) == raw
assert round(P.freq_to_hz(0), 1) == 19.7 and round(P.freq_to_hz(300)) == 20159
assert P.hz_to_freq(1000) == 170
assert len(P.Q_TABLE) == 101 and len(P.SLOPES) == 21
lv = [0.5, 0.0, 1.0, 0.001] + [0.25] * 8
dec = P.decode_meters(P.encode_meters(lv))
assert all(abs(a - b) < 1e-3 * max(a, 1e-3) for a, b in zip(lv, dec))
def test_param_commands():
m = P.MODELS["204"]
st = P.default_state(m)
out = st["outputs"][1]
P.apply_param(out, "peq.3.gain", 150)
assert P.param_command(m, "out", 1, out, "peq.3.gain") == (0x33, bytes([3, 3, 150, 0, 125, 0, 32, 0, 0]))
P.apply_param(out, "mix.1", 200)
assert P.param_command(m, "out", 1, out, "mix.1") == (0x41, bytes([3, 1, 200, 0]))
inp = st["inputs"][1]
assert P.param_command(m, "in", 1, inp, "gate.hold") == (0x3E, bytes([1, 0, 0, 99, 0, 99, 0, 0, 0]))
def test_links():
# masks as read from a real DSP 204: In A+B, Out 1+2 and Out 3+4 linked
m = P.MODELS["204"]
st = P.default_state(m)
for ch, mask in zip(st["inputs"] + st["outputs"], [3, 0, 3, 0, 12, 0]):
ch["link"] = mask
st = P.parse_state(m, bytes(P.build_state_buffer(m, st)))
assert P.link_groups(st["inputs"]) == [[0, 1]]
assert P.link_groups(st["outputs"]) == [[0, 1], [2, 3]]
assert P.link_groups(P.default_state(m)["outputs"]) == [[0], [1], [2], [3]]
assert P.link_masks(4, [[0, 1], [2, 3]]) == [3, 0, 12, 0]
assert P.link_masks(4, [[3, 1]]) == [1, 10, 4, 0]
# the DSP applies a change on any member to the whole group, but not names
P.apply_command(m, st, P.CMD_GAIN, bytes([5, 100, 0]))
P.apply_command(m, st, P.CMD_CHANNEL_NAME, bytes([4]) + b"Sub ")
assert st["outputs"][2]["gain"] == 100 and st["outputs"][3]["name"] != "Sub"
def test_preset_import_commands():
from dsp import preset
m = P.MODELS["204"]
cur = P.default_state(m)
assert preset.import_commands(m, cur, cur) == [] # identical: nothing is written
tgt = P.default_state(m)
tgt["outputs"][1]["gain"] = 300
assert preset.import_commands(m, tgt, cur) == [(0x34, bytes([3]) + (300).to_bytes(2, "little"))]
tgt["outputs"][0]["link"], tgt["outputs"][1]["link"] = 3, 0 # new link: dissolve, set, relink
cmds = preset.import_commands(m, tgt, cur)
assert cmds[0][0] == P.CMD_LINK and (P.CMD_LINK, bytes([2, 3, 0])) in cmds
# a file is read with linked channels made alike, like the DSP keeps them
doc = preset.export_doc("204", "DSP204", tgt, bytes(P.build_state_buffer(m, tgt))[: m.size])
st = preset.read_file("204", m, cur, doc=doc)
assert st["outputs"][1]["gain"] == st["outputs"][0]["gain"] == 280
assert st["outputs"][1]["matrix"] == tgt["outputs"][1]["matrix"] # routing stays per channel
def test_limit_flags():
# status bytes after the 12 levels, captured on a DSP 204 while forcing the limiters
assert P.decode_limit_flags(bytes(36) + bytes([0x00, 0x03]), 4) == [True, True, False, False]
assert P.decode_limit_flags(bytes(36) + bytes([0x00, 0x0C]), 4) == [False, False, True, True]
assert P.decode_limit_flags(bytes(36), 4) == [False] * 4
assert P.decode_limit_flags(P.encode_meters([0.0] * 12, 0x05), 4) == [True, False, True, False]
def test_channel_names():
# the DSP keeps 8 ASCII characters; umlauts are spelled out, anything else is dropped
assert P.clean_name("Bühne€ Links") == "Buehne L"
m = P.MODELS["204"]
assert P.param_command(m, "in", 0, {"name": "Süd"}, "name") == (0x3D, b"\x00Sued ")
def test_device_lock():
# answer to 0x2C: [time lock][4 bytes time lock data][device lock]
assert P.device_locked(bytes([0, 0, 0, 0, 0, 1]))
assert not P.device_locked(bytes([0, 0, 0, 0, 0, 0]))
assert not P.device_locked(bytes([0, 20])) # short answer: no lock information
assert P.LOCK_CODE.fullmatch("A1BA") and not P.LOCK_CODE.fullmatch("a1ba") and not P.LOCK_CODE.fullmatch("A1B")
assert P.build_frame(P.CMD_UNLOCK, b"\x00A1BA")[5:11] == bytes([0x2D, 0x00]) + b"A1BA"
import sim
dsp = sim.SimDSP("204", "A1BA")
assert P.device_locked(dsp.handle(P.CMD_PRESET_COUNT, b"")[1])
assert dsp.handle(P.CMD_UNLOCK, b"\x00ZZZZ") == (P.CMD_UNLOCK, bytes([0, 0]))
assert dsp.handle(P.CMD_UNLOCK, b"\x00A1BA") == (P.CMD_UNLOCK, bytes([0, 1]))
assert not P.device_locked(dsp.handle(P.CMD_PRESET_COUNT, b"")[1])
dsp.handle(P.CMD_SET_LOCK_CODE, b"B2C3")
assert dsp.lock_code == "B2C3"
def test_test_signal():
# source/frequency follow the mute masks and one word per channel (editor: 0x2C8 on the 204, 0x59C on the 408)
assert P.MODELS["204"].test_base == 0x2C8 and P.MODELS["408"].test_base == 0x59C
for m in (m for m in P.MODELS.values() if not m.fir):
st = P.default_state(m)
st["test"] = {"source": 3, "freq": 17}
assert P.parse_state(m, bytes(P.build_state_buffer(m, st)))["test"] == {"source": 3, "freq": 17}
st = P.default_state(P.MODELS["204"])
P.apply_command(P.MODELS["204"], st, P.CMD_TEST_SIGNAL, bytes([1, 5]))
assert st["test"] == {"source": 1, "freq": 5}
def test_master_bypass():
# masks after the test signal: [?][PEQ inputs][PEQ outputs][GEQ inputs] (editor: 0x2CE/0x2D0/0x2D2 on the 204)
m = P.MODELS["204"]
assert m.test_base + 6 == 0x2CE and m.test_base + 10 == 0x2D2 == m.size - 2
st = P.default_state(m)
st["inputs"][1]["peq_bypass"] = st["inputs"][0]["geq_bypass"] = st["outputs"][3]["peq_bypass"] = True
buf = P.build_state_buffer(m, st)
assert buf[0x2CE:0x2D4] == bytes([2, 0, 8, 0, 1, 0])
back = P.parse_state(m, bytes(buf))
assert back["inputs"][1]["peq_bypass"] and back["inputs"][0]["geq_bypass"] and back["outputs"][3]["peq_bypass"]
assert not back["inputs"][0]["peq_bypass"] and not back["outputs"][0]["peq_bypass"]
assert P.param_command(m, "out", 3, back["outputs"][3], "peq_bypass") == (0x3C, bytes([5, 1]))
assert P.param_command(m, "in", 0, back["inputs"][0], "geq_bypass") == (0x49, bytes([0, 1]))
assert P.MODELS["408"].test_base + 6 == 0x5A2
def test_beta_models():
assert P.detect_model("DSP408 V010") == "408" and P.detect_model("DSP 204") == "204"
for info in ("DSP206 V1", "FIR DSP408 V1", "FIRDSP408", "DSP408FIR"): # only selectable by hand
assert P.detect_model(info) is None, info
for key in ("206", "408fir"):
m = P.MODELS[key]
assert m.beta
st = P.default_state(m)
st["outputs"][m.n_out - 1]["gain"] = 123
back = P.parse_state(m, bytes(P.build_state_buffer(m, st)))
assert back["outputs"][m.n_out - 1]["gain"] == 123 and len(back["inputs"]) == m.n_in
def test_fir_model():
m = P.MODELS["408fir"]
assert (m.in_size, m.out_size, m.out_base, m.globals_base, m.size, m.chunks) == (138, 108, 0x238, 0x598, 0x625, 32)
st = P.default_state(m)
o = st["outputs"][7]
o["gain"], o["limit"]["threshold"], o["hp"], o["peq"][8]["bypass"] = 123, 77, {"freq": 40, "slope": 5}, True
o["fir"].update(type=3, window=8, low=200, high=8000, taps=24, name="SUB")
st["inputs"][3]["comp"]["threshold"], st["inputs"][3]["fir"] = 55, {"taps": 2048, "bypass": False, "name": "ROOM"}
st["inputs"][0]["peq"][7]["bypass"] = True
buf = bytes(P.build_state_buffer(m, st))
assert buf[0x238 + 7 * 108 + 28:0x238 + 7 * 108 + 36] == bytes([3, 8]) + (200).to_bytes(2, "little") + (8000).to_bytes(2, "little") + (24).to_bytes(2, "little")
assert buf[0x5B4 + 8 * 11:0x5B4 + 8 * 11 + 3] == b"SUB" and buf[0x59C:0x59E] == (128).to_bytes(2, "little")
back = P.parse_state(m, buf)
assert back["outputs"] == st["outputs"] and back["inputs"] == st["inputs"]
assert len(back["inputs"][0]["peq"]) == 8 and len(back["outputs"][0]["peq"]) == 9 and "geq" not in back["inputs"][0]
assert P.param_command(m, "out", 7, back["outputs"][7], "fir") == (0x4B, bytes.fromhex("0b 03 08 c8 00 40 1f 18 00"))
assert P.param_command(m, "out", 7, back["outputs"][7], "hp") == (0x32, bytes.fromhex("0b 28 00 04 00"))
assert P.param_command(m, "out", 0, back["outputs"][0], "hp") == (0x32, bytes.fromhex("04 00 00 00 01"))
assert P.param_command(m, "in", 3, back["inputs"][3], "fir.bypass") == (0x4F, bytes.fromhex("03 00"))
assert P.param_command(m, "out", 7, back["outputs"][7], "limit")[1][:3] == bytes.fromhex("0b 00 00")
assert P.fir_channel_taps(back["outputs"][7]) == 1024 and P.fir_channel_taps(back["inputs"][3]) == 2048
frames = P.fir_coef_frames(4, [1.0] + [0.0] * 12)
assert len(frames) == 2 and frames[0][:8] == bytes.fromhex("04 00 0d 00 3f 80 00 00") and len(frames[0]) == 4 + 48 and len(frames[1]) == 8
for cmd, p in ((0x4B, bytes.fromhex("04 01 02 96 00 20 4e 08 00")), (0x4E, frames[0]), (0x5B, b"\x04ABC ")):
P.apply_command(m, st, cmd, p)
assert st["outputs"][0]["fir"]["type"] == 1 and st["outputs"][0]["fir"]["name"] == "ABC"
def test_dj_brake_follows_music():
import server, tempfile
from types import SimpleNamespace
with tempfile.TemporaryDirectory() as d:
app = server.App(Path(d) / "c.json")
thr0 = 180 # threshold 0 dB
dev = SimpleNamespace(id="x", demo=True, state={"outputs": [{"mute": False, "limit": {"threshold": thr0}}]}, status="online")
app.devices["x"] = dev
lv = lambda db: 10 ** (db / 20)
note = lambda db, t, limit=False: app.dj_note({"device": "x", "out": [lv(db)], "limit": [limit]}, now=t)
# the peak stays while the music dips, then falls slowly
note(-10, 100.0)
note(-30, 100.5)
assert abs(app.dj_rooms["x"] - 10) < 0.01
note(-30, 102.5)
assert 10 < app.dj_rooms["x"] < 14
# the limiter acts at -12 on the meter although the threshold says 0: learned, and the distance is true afterwards
note(-12, 110.0, True)
assert abs(app.dj_cal["x"] - 12) < 3 and app.dj_rooms["x"] == 0
assert app.dj_hit == 110.0
for i in range(30):
note(-30, 120.0 + i)
note(-20, 150.0)
assert 6 < app.dj_rooms["x"] < 10
# a left out output neither warns nor counts
app.dj_ignore = {"x": [0]}
note(-1, 160.0, True)
assert app.dj_hit == 110.0 and app.dj_rooms["x"] is False
# what was learned survives a restart
app.save()
again = server.App(Path(d) / "c.json")
again.load()
assert abs(again.dj_cal["x"] - app.dj_cal["x"]) < 0.01
def test_dj_brake_one_hit_counts_for_the_whole_dsp():
import server, tempfile
from types import SimpleNamespace
with tempfile.TemporaryDirectory() as d:
app = server.App(Path(d) / "c.json")
out = {"mute": False, "limit": {"threshold": 180}}
app.devices["x"] = SimpleNamespace(id="x", demo=True, state={"outputs": [dict(out), dict(out)]}, status="online")
lv = lambda db: 10 ** (db / 20)
app.dj_ignore = {"x": [1]}
app.dj_note({"device": "x", "out": [lv(-12), lv(-40)], "limit": [True, False]}, now=100.0)
assert app.dj_cal == {"x": 12.0}
# the level the limiter leaves over while it keeps acting teaches nothing
app.dj_note({"device": "x", "out": [lv(-20), lv(-40)], "limit": [True, False]}, now=100.2)
assert app.dj_cal == {"x": 12.0}
# another output of this DSP has never limited, its distance is true anyway
app.dj_ignore = {"x": [0]}
app.dj_note({"device": "x", "out": [lv(-40), lv(-18)], "limit": [False, False]}, now=101.0)
assert abs(app.dj_rooms["x"] - 6) < 0.01
def test_dj_brake_measured_offset():
import server, tempfile
from types import SimpleNamespace
lv = lambda db: 10 ** (db / 20)
with tempfile.TemporaryDirectory() as d:
app = server.App(Path(d) / "c.json")
app.save = lambda: None
out = {"mute": False, "limit": {"threshold": 220}} # +20 dB
dev = SimpleNamespace(id="x", demo=False, model_name="204", info="DSP204 V0104P", state={"outputs": [out]}, status="online")
app.devices["x"] = dev
note = lambda db, t, limit=False: app.dj_note({"device": "x", "out": [lv(db)], "limit": [limit]}, now=t)
# measured: at +20 dB and a meter of -25 the limiter is about 19 dB away, before any hit
note(-25, 100.0)
assert app.dj_cal == {} and abs(app.dj_rooms["x"] - 19) < 0.01
# the flag right after raising the threshold teaches nothing: seen on real hardware
out["limit"]["threshold"] = 184
note(-25, 110.0)
out["limit"]["threshold"] = 220
note(-25, 111.0, True)
assert app.dj_cal == {}
note(-25, 111.2)
# a real hit moves the offset, it doesn't replace it
out["limit"]["threshold"] = 180
note(-20, 130.0)
note(-20, 130.2, True)
assert app.dj_cal == {} # that threshold has only just jumped
note(-20, 140.0)
note(-20, 140.2, True)
assert abs(app.dj_cal["x"] - 24.5) < 0.01
# it flickers: nothing new. And a jump of the threshold down teaches nothing either
note(-30, 140.4)
note(-30, 140.6, True)
assert abs(app.dj_cal["x"] - 24.5) < 0.01
out["limit"]["threshold"] = 160
note(-30, 150.0)
note(-30, 150.2, True)
assert abs(app.dj_cal["x"] - 24.5) < 0.01
with tempfile.TemporaryDirectory() as d:
app = server.App(Path(d) / "c.json")
for dev in (SimpleNamespace(id="s", demo=False, model_name="204", info="DSP204 V010 SIM"), SimpleNamespace(id="d", demo=True, model_name="204", info=""),
SimpleNamespace(id="o", demo=False, model_name="408", info="DSP408 V0104P")):
assert app.dj_offset(dev) == 0.0
def test_reset_config():
import asyncio, json, server, tempfile
with tempfile.TemporaryDirectory() as d:
path = Path(d) / "c.json"
app = server.App(path)
app.load()
app.set_pin("9999", save=False)
app.djbrake, app.lang, app.dj_cal = True, "de", {"x:0": 5.0}
app.dashboard = {"modules": []}
app.app_token = "t"
app.app_sessions, app.sessions = {"a"}, {"a": 9e12, "b": 9e12}
app.save()
app.mute_all["active"] = True
try:
asyncio.run(app.reset_config())
raise AssertionError("mute all must block the reset")
except ValueError:
assert app.djbrake
app.mute_all["active"] = False
app.remote["enabled"] = False
asyncio.run(app.reset_config())
assert not app.djbrake and app.lang == "" and app.dashboard is None and app.dj_cal == {} and app.check_pin("1234")
assert app.app_token == "t" and app.app_sessions == {"a"} and set(app.sessions) == {"a"}
assert json.loads(path.with_name("config.before-reset.json").read_text())["djbrake"] is True
def test_looks_follow_presets():
from dsp.device import Device
d = Device("x", "x", "127.0.0.1")
d.state = {"preset_name": "A"}
d.colors, d.linknames = {"out0": "#111111"}, {"out:0,1": "Tops"}
d.sync_look()
d.state = {"preset_name": "B"} # not seen yet: starts with what is there, then goes its own way
d.sync_look()
assert d.colors == {"out0": "#111111"}
d.colors, d.linknames = {"out0": "#222222"}, {"out:0,1": "Subs"}
d.remember_look()
d.state = {"preset_name": "A"}
d.sync_look()
assert d.colors == {"out0": "#111111"} and d.linknames == {"out:0,1": "Tops"}
d.state = {"preset_name": "B"}
d.sync_look()
assert d.colors == {"out0": "#222222"} and d.linknames == {"out:0,1": "Subs"}
assert "looks" not in d.snapshot()
if __name__ == "__main__":
for name, fn in list(globals().items()):
if name.startswith("test_"):
fn()
print("ok", name)