Files
BetterDSPControl/dsp/protocol.py
T
GivouandClaude Opus 5.5 61400df667 Add device lock support and demo mode
Device lock (hardware lock of the DSP, independent of the app lock):
- detect a locked DSP from the 0x2C answer during connect and wait for the code
- unlock with 0x2D, optionally remember the code and unlock automatically
- set a new code (0x2F) from the device settings
- simulator: --lock CODE

Demo mode:
- switch in the settings starts a simulated DSP 204/408 inside the server
- real DSPs are disconnected and greyed out meanwhile and resume afterwards
- demo devices are never saved or exported; sim.py ships with the Pi image and EXEs

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

547 lines
20 KiB
Python

"""t.racks DSP 204 / DSP 408 wire protocol (see PROTOCOL.md)."""
import copy
import math
import re
import struct
from dataclasses import dataclass
PORT = 9761
# Read / system commands
CMD_ACK = 0x01
CMD_HANDSHAKE = 0x10
CMD_LOGOUT = 0x11 # sent after setting a lock code
CMD_STATUS = 0x12
CMD_DEVICE_INFO = 0x13
CMD_INIT_14 = 0x14
CMD_PRESET_RECALL = 0x20
CMD_PRESET_STORE = 0x21
CMD_INIT_22 = 0x22
CMD_CONFIG_CHUNK = 0x24
CMD_PRESET_STORE_NAME = 0x26
CMD_CONFIG_REQUEST = 0x27
CMD_PRESET_NAME = 0x29
CMD_PRESET_COUNT = 0x2C # answer: [time lock][4 bytes time lock data][device lock] (see device_locked)
CMD_UNLOCK = 0x2D # [0][code 4] -> answer [0][1 = unlocked, 0 = wrong code]
CMD_SET_LOCK_CODE = 0x2F # [code 4]
CMD_METER = 0x40
# Parameter commands
CMD_COMP = 0x30
CMD_LOW_PASS = 0x31
CMD_HIGH_PASS = 0x32
CMD_PEQ = 0x33
CMD_GAIN = 0x34
CMD_MUTE = 0x35
CMD_POLARITY = 0x36
CMD_DELAY = 0x38
CMD_MATRIX = 0x3A
CMD_CHANNEL_NAME = 0x3D
CMD_GATE = 0x3E
CMD_LIMIT = 0x3F
CMD_MIX = 0x41
CMD_GEQ = 0x48
CMD_LINK = 0x3B # [ch][u16 link mask], see link_masks()
CHUNK_SIZE = 50
LOCK_CODE = re.compile(r"[A-Z0-9]{4}") # device lock code: 4 characters, digits and upper-case letters
def device_locked(count_payload: bytes) -> bool:
"""True if the answer to CMD_PRESET_COUNT says the DSP waits for its lock code."""
return len(count_payload) > 5 and count_payload[5] != 0
def checksum(data: bytes) -> int:
"""XOR over 02 .. 03 of the frame; the 02 and 03 bytes fold into the initial 0x01."""
c = 0x01
for b in data:
c ^= b
return c
def build_frame(cmd: int, payload: bytes = b"", addr: int = 1, src: int = 0) -> bytes:
body = bytes([src, addr, len(payload) + 1, cmd]) + bytes(payload)
return b"\x10\x02" + body + b"\x10\x03" + bytes([checksum(body)])
@dataclass
class Frame:
src: int
dst: int
cmd: int
payload: bytes
checksum_ok: bool = True
class FrameParser:
"""Reassembles frames from a TCP byte stream (length based, no byte stuffing)."""
def __init__(self):
self.buf = bytearray()
def feed(self, data: bytes) -> list[Frame]:
self.buf += data
frames = []
while True:
start = self.buf.find(b"\x10\x02")
if start < 0:
# keep a trailing 0x10 that might start the next header
del self.buf[: max(0, len(self.buf) - 1)]
return frames
if start:
del self.buf[:start]
if len(self.buf) < 6:
return frames
length = self.buf[4]
total = 5 + length + 3
if len(self.buf) < total:
return frames
if self.buf[5 + length] != 0x10 or self.buf[6 + length] != 0x03 or length == 0:
del self.buf[:2] # not a real header, resync
continue
body = bytes(self.buf[2 : 5 + length])
frames.append(
Frame(
src=body[0],
dst=body[1],
cmd=body[3],
payload=body[4:],
checksum_ok=checksum(body) == self.buf[7 + length],
)
)
del self.buf[:total]
# ---------------------------------------------------------------- value scales
Q_TABLE = [
0.4, 0.42, 0.45, 0.47, 0.5, 0.53, 0.56, 0.59, 0.63, 0.67, 0.71, 0.75, 0.79, 0.84, 0.89,
0.94, 1.0, 1.06, 1.12, 1.19, 1.26, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.4,
2.5, 2.7, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.2, 4.5, 4.8, 5.0, 5.3, 5.7, 6.0, 6.3, 6.7,
7.1, 7.6, 8.0, 8.5, 9.0, 9.5, 10.1, 10.7, 11.3, 12.0, 12.7, 13.5, 14.0, 15.0, 16.0, 17.0,
18.0, 19.0, 20.0, 21.0, 23.0, 24.0, 25.0, 27.0, 29.0, 30.0, 32.0, 34.0, 36.0, 38.0, 40.0,
43.0, 45.0, 48.0, 51.0, 54.0, 57.0, 60.0, 64.0, 68.0, 72.0, 76.0, 81.0, 85.0, 91.0, 96.0,
102.0, 108.0, 114.0, 121.0, 128.0,
]
RATIO_NAMES = ["1.0", "1.1", "1.3", "1.5", "1.7", "2.0", "2.5", "3.0", "3.5", "4.0", "5.0",
"6.0", "8.0", "10", "20", "Limit"]
PEQ_TYPES = ["Peak", "Low Shelf", "High Shelf", "HPF -6", "HPF -12", "LPF -6", "LPF -12",
"Allpass 1", "Allpass 2"]
SLOPES = ["Bypass", "BW -6", "BL -6", "BW -12", "BL -12", "LK -12", "BW -18", "BL -18", "BW -24",
"BL -24", "LK -24", "BW -30", "BL -30", "BW -36", "BL -36", "LK -36", "BW -42", "BL -42",
"BW -48", "BL -48", "LK -48"]
def gain_to_db(raw: int) -> float:
return raw / 2 - 60 if raw < 80 else (raw - 280) / 10
def db_to_gain(db: float) -> int:
raw = round((db + 60) * 2) if db < -20 else round(db * 10 + 280)
return max(0, min(400, raw))
def freq_to_hz(raw: int) -> float:
return 1000.0 * 2 ** ((raw - 170) / 30)
def hz_to_freq(hz: float) -> int:
return max(0, min(300, round(170 + 30 * math.log2(max(hz, 1.0) / 1000.0))))
def eq_gain_to_db(raw: int) -> float:
return (raw - 120) / 10
def threshold_to_db(raw: int) -> float:
return (raw - 180) / 2
def delay_to_ms(raw: int) -> float:
return raw / 96
def decode_meters(payload: bytes) -> list[float]:
"""12 linear levels (In A-D, Out 1-8) from a 0x40 response payload."""
levels = []
for i in range(12):
b = payload[i * 3 : i * 3 + 3]
if len(b) < 3:
levels.append(0.0)
continue
v = struct.unpack("<f", bytes([0, b[2], b[0], b[1]]))[0]
levels.append(v if math.isfinite(v) and v > 0 else 0.0)
return levels
def decode_limit_flags(payload: bytes, n_out: int) -> list[bool]:
"""Limiter active per output, from the 2 status bytes after the levels (bit i = output i).
Seen on a DSP 204: 00 03 while Out 1+2 limit, 00 0C for Out 3+4. That outputs 5-8 of the 408
continue in the same 16-bit value is an assumption.
"""
if len(payload) < 38:
return [False] * n_out
flags = payload[36] << 8 | payload[37]
return [bool(flags >> i & 1) for i in range(n_out)]
def encode_meters(levels: list[float], limit_flags: int = 0) -> bytes:
"""Inverse of decode_meters / decode_limit_flags (used by the simulator)."""
out = bytearray()
for v in levels:
raw = struct.pack("<f", v)
out += bytes([raw[2], raw[3], raw[1]])
return bytes(out) + bytes([limit_flags >> 8 & 0xFF, limit_flags & 0xFF])
# ---------------------------------------------------------------- device models
@dataclass(frozen=True)
class Model:
name: str
n_in: int
n_out: int
@property
def in_size(self) -> int:
return 140
@property
def out_size(self) -> int:
return 96 + 2 * self.n_in
@property
def out_base(self) -> int:
return 0x10 + self.n_in * self.in_size
@property
def globals_base(self) -> int:
return self.out_base + self.n_out * self.out_size
@property
def size(self) -> int:
return self.globals_base + 4 + 2 * self.n_in + 2 * self.n_out + 12
@property
def chunks(self) -> int:
return -(-self.size // CHUNK_SIZE)
def channel(self, kind: str, idx: int) -> int:
"""Wire channel number for input/output index."""
return idx if kind == "in" else self.n_in + idx
def meter_index(self, kind: str, idx: int) -> int:
return idx if kind == "in" else 4 + idx
MODELS = {"204": Model("DSP 204", 2, 4), "408": Model("DSP 408", 4, 8)}
def detect_model(info: str) -> str | None:
for key in MODELS:
if f"DSP{key}" in info.replace(" ", ""):
return key
return None
# ---------------------------------------------------------------- state (de)serialisation
_UMLAUTS = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "Ä": "Ae", "Ö": "Oe", "Ü": "Ue", "ß": "ss"})
def clean_name(name) -> str:
"""Channel name as the DSP stores it: printable ASCII, at most 8 characters."""
s = str(name or "").translate(_UMLAUTS)
return "".join(c for c in s if " " <= c <= "~")[:8]
def _name(b: bytes) -> str:
return b.split(b"\x00")[0].decode("latin1").strip()
def _peq(buf: bytes, off: int, n: int) -> list[dict]:
bands = []
for i in range(n):
gain, freq, q, typ = struct.unpack_from("<HHBB", buf, off + i * 6)
bands.append({"gain": gain, "freq": freq, "q": q, "type": typ % 9, "bypass": typ >= 9})
return bands
def parse_state(model: Model, buf: bytes) -> dict:
"""Decode the reassembled config dump into a JSON friendly dict (raw values)."""
u16 = lambda off: struct.unpack_from("<H", buf, off)[0]
g = model.globals_base
in_mute, out_mute = u16(g), u16(g + 2)
inputs = []
for i in range(model.n_in):
o = 0x10 + i * model.in_size
inputs.append({
"name": _name(buf[o : o + 8]),
"gate": dict(zip(("attack", "release", "hold", "threshold"),
struct.unpack_from("<4H", buf, o + 8))),
"geq": list(struct.unpack_from("<31H", buf, o + 16)),
"peq": _peq(buf, o + 78, 8),
"hp": {"freq": u16(o + 126), "slope": buf[o + 130]},
"lp": {"freq": u16(o + 128), "slope": buf[o + 131]},
"gain": u16(o + 132),
"polarity": u16(o + 134) != 0,
"delay": u16(o + 136),
"link": u16(o + 138),
"mute": bool(in_mute >> i & 1),
})
outputs = []
for i in range(model.n_out):
o = model.out_base + i * model.out_size
p = o + 10 + 2 * model.n_in
outputs.append({
"name": _name(buf[o : o + 8]),
"matrix": u16(o + 8),
"mix": list(struct.unpack_from(f"<{model.n_in}H", buf, o + 10)),
"hp": {"freq": u16(p), "slope": buf[p + 4]},
"lp": {"freq": u16(p + 2), "slope": buf[p + 5]},
"peq": _peq(buf, p + 6, 9),
"comp": dict(zip(("ratio", "attack", "release", "knee", "threshold"),
struct.unpack_from("<5H", buf, p + 60))),
"limit": dict(zip(("attack", "release", "knee", "threshold"),
struct.unpack_from("<4H", buf, p + 70))),
"gain": u16(p + 78),
"polarity": u16(p + 80) != 0,
"delay": u16(p + 82),
"link": u16(p + 84),
"mute": bool(out_mute >> i & 1),
})
return {"preset_name": _name(buf[2:16]), "inputs": inputs, "outputs": outputs}
def build_state_buffer(model: Model, state: dict) -> bytearray:
"""Inverse of parse_state (used by the simulator)."""
buf = bytearray(model.chunks * CHUNK_SIZE)
pad = lambda s, n: s.encode("latin1")[:n].ljust(n, b" ")
buf[0:2] = b"\xff\xff"
buf[2:16] = pad(state["preset_name"], 14)
def put_peq(off, bands):
for i, b in enumerate(bands):
struct.pack_into("<HHBB", buf, off + i * 6, b["gain"], b["freq"], b["q"],
b["type"] + (9 if b.get("bypass") else 0))
in_mute = out_mute = 0
for i, ch in enumerate(state["inputs"]):
o = 0x10 + i * model.in_size
buf[o : o + 8] = pad(ch["name"], 8)
gt = ch["gate"]
struct.pack_into("<4H", buf, o + 8, gt["attack"], gt["release"], gt["hold"], gt["threshold"])
struct.pack_into("<31H", buf, o + 16, *ch["geq"])
put_peq(o + 78, ch["peq"])
struct.pack_into("<HHBB", buf, o + 126, ch["hp"]["freq"], ch["lp"]["freq"],
ch["hp"]["slope"], ch["lp"]["slope"])
struct.pack_into("<4H", buf, o + 132, ch["gain"], int(ch["polarity"]), ch["delay"], ch.get("link", 1 << i))
in_mute |= int(ch["mute"]) << i
for i, ch in enumerate(state["outputs"]):
o = model.out_base + i * model.out_size
p = o + 10 + 2 * model.n_in
buf[o : o + 8] = pad(ch["name"], 8)
struct.pack_into("<H", buf, o + 8, ch["matrix"])
struct.pack_into(f"<{model.n_in}H", buf, o + 10, *ch["mix"])
struct.pack_into("<HHBB", buf, p, ch["hp"]["freq"], ch["lp"]["freq"],
ch["hp"]["slope"], ch["lp"]["slope"])
put_peq(p + 6, ch["peq"])
c, lim = ch["comp"], ch["limit"]
struct.pack_into("<5H", buf, p + 60, c["ratio"], c["attack"], c["release"], c["knee"],
c["threshold"])
struct.pack_into("<4H", buf, p + 70, lim["attack"], lim["release"], lim["knee"],
lim["threshold"])
struct.pack_into("<4H", buf, p + 78, ch["gain"], int(ch["polarity"]), ch["delay"], ch.get("link", 1 << i))
out_mute |= int(ch["mute"]) << i
struct.pack_into("<HH", buf, model.globals_base, in_mute, out_mute)
return buf
def default_state(model: Model) -> dict:
peq = lambda n: [{"gain": 120, "freq": 50 + i * 25, "q": 32, "type": 0, "bypass": False}
for i in range(n)]
return {
"preset_name": "Default",
"inputs": [{
"name": f"In{chr(65 + i)}", "gate": {"attack": 0, "release": 99, "hold": 99, "threshold": 0},
"geq": [120] * 31, "peq": peq(8), "hp": {"freq": 0, "slope": 0},
"lp": {"freq": 300, "slope": 0}, "gain": 280, "polarity": False, "delay": 0, "mute": False,
"link": 1 << i,
} for i in range(model.n_in)],
"outputs": [{
"name": f"Out{i + 1}", "matrix": 1 << (i % model.n_in), "mix": [280] * model.n_in,
"hp": {"freq": 0, "slope": 0}, "lp": {"freq": 300, "slope": 0}, "peq": peq(9),
"comp": {"ratio": 0, "attack": 49, "release": 499, "knee": 0, "threshold": 220},
"limit": {"attack": 49, "release": 499, "knee": 0, "threshold": 220},
"gain": 280, "polarity": False, "delay": 0, "mute": False, "link": 1 << i,
} for i in range(model.n_out)],
}
# ---------------------------------------------------------------- channel links
#
# Every channel stores a u16 link mask (bit = channel index within inputs resp. outputs):
# a free channel has only its own bit, the first channel of a group the bits of all members,
# the other members 0. The DSP itself applies a change on any member to the whole group
# (except name, routing and mix levels) and copies the first channel's settings when a group is formed.
LINK_EXCLUDED = ("name", "mix", "matrix", "link") # per channel even when linked (e.g. Out 1 <- A, Out 2 <- B)
def link_groups(chans: list[dict]) -> list[list[int]]:
"""Channel indices grouped by link (single channels included), in channel order."""
seen: set[int] = set()
groups = []
for i, ch in enumerate(chans):
if i in seen:
continue
mask = ch.get("link", 1 << i)
g = [j for j in range(len(chans)) if (j == i or mask >> j & 1) and j not in seen]
seen.update(g)
groups.append(g)
return groups
def link_group(chans: list[dict], idx: int) -> list[int]:
return next(g for g in link_groups(chans) if idx in g)
def link_masks(n: int, groups: list[list[int]]) -> list[int]:
"""Per-channel link masks for the given groups (channels not mentioned stay free)."""
masks = [1 << i for i in range(n)]
for g in groups:
g = sorted({i for i in g if 0 <= i < n})
if len(g) < 2:
continue
masks[g[0]] = sum(1 << i for i in g)
for i in g[1:]:
masks[i] = 0
return masks
def copy_linked(chans: list[dict], src: int, dst: int):
for k, v in chans[src].items():
if k not in LINK_EXCLUDED:
chans[dst][k] = copy.deepcopy(v)
# ---------------------------------------------------------------- parameter -> command
def _w(v: int) -> bytes:
return struct.pack("<H", int(v) & 0xFFFF)
def param_command(model: Model, kind: str, idx: int, ch: dict, param: str) -> tuple[int, bytes]:
"""Build (cmd, payload) for a changed parameter. `ch` is the already-updated channel dict.
`param` is a dotted path like "gain", "hp.freq", "peq.3.gain", "geq.10", "mix.1".
"""
c = model.channel(kind, idx)
top, *rest = param.split(".")
if top == "gain":
return CMD_GAIN, bytes([c]) + _w(ch["gain"])
if top == "mute":
return CMD_MUTE, bytes([c, int(ch["mute"])])
if top == "polarity":
return CMD_POLARITY, bytes([c, int(ch["polarity"])])
if top == "delay":
return CMD_DELAY, bytes([c]) + _w(ch["delay"])
if top == "name":
return CMD_CHANNEL_NAME, bytes([c]) + clean_name(ch["name"]).encode("ascii").ljust(8, b" ")
if top in ("hp", "lp"):
f = ch[top]
return (CMD_HIGH_PASS if top == "hp" else CMD_LOW_PASS), bytes([c]) + _w(f["freq"]) + bytes([f["slope"]])
if top == "peq":
band = int(rest[0])
b = ch["peq"][band]
return CMD_PEQ, bytes([c, band]) + _w(b["gain"]) + _w(b["freq"]) + bytes(
[b["q"], b["type"], int(b["bypass"])])
if top == "geq" and kind == "in":
band = int(rest[0])
return CMD_GEQ, bytes([c, band]) + _w(ch["geq"][band])
if top == "gate" and kind == "in":
g = ch["gate"]
return CMD_GATE, bytes([c]) + b"".join(_w(g[k]) for k in ("attack", "release", "hold", "threshold"))
if top == "comp" and kind == "out":
g = ch["comp"]
return CMD_COMP, bytes([c]) + b"".join(
_w(g[k]) for k in ("ratio", "attack", "release", "knee", "threshold"))
if top == "limit" and kind == "out":
g = ch["limit"]
return CMD_LIMIT, bytes([c]) + b"".join(_w(g[k]) for k in ("attack", "release", "knee", "threshold"))
if top == "matrix" and kind == "out":
return CMD_MATRIX, bytes([c, ch["matrix"] & 0xFF])
if top == "mix" and kind == "out":
i = int(rest[0])
return CMD_MIX, bytes([c, i]) + _w(ch["mix"][i])
raise ValueError(f"unknown parameter {kind}.{param}")
def apply_param(state_ch: dict, param: str, value):
"""Write `value` into the channel dict at the dotted `param` path."""
keys = param.split(".")
node = state_ch
for k in keys[:-1]:
node = node[int(k)] if isinstance(node, list) else node[k]
last = keys[-1]
if isinstance(node, list):
node[int(last)] = value
else:
node[last] = value
def apply_command(model: Model, state: dict, cmd: int, p: bytes):
"""Update state from an incoming set command (used by the simulator)."""
if not p:
return
c = p[0]
kind, idx = ("in", c) if c < model.n_in else ("out", c - model.n_in)
chans = state["inputs" if kind == "in" else "outputs"]
if idx >= len(chans):
return
ch = chans[idx]
w = lambda o: struct.unpack_from("<H", p, o)[0]
if cmd == CMD_GAIN:
ch["gain"] = w(1)
elif cmd == CMD_MUTE:
ch["mute"] = bool(p[1])
elif cmd == CMD_POLARITY:
ch["polarity"] = bool(p[1])
elif cmd == CMD_DELAY:
ch["delay"] = w(1)
elif cmd == CMD_CHANNEL_NAME:
ch["name"] = _name(p[1:9])
elif cmd in (CMD_HIGH_PASS, CMD_LOW_PASS):
ch["hp" if cmd == CMD_HIGH_PASS else "lp"] = {"freq": w(1), "slope": p[3]}
elif cmd == CMD_PEQ:
ch["peq"][p[1]] = {"gain": w(2), "freq": w(4), "q": p[6], "type": p[7], "bypass": bool(p[8])}
elif cmd == CMD_GEQ:
ch["geq"][p[1]] = w(2)
elif cmd == CMD_GATE:
ch["gate"] = dict(zip(("attack", "release", "hold", "threshold"), struct.unpack_from("<4H", p, 1)))
elif cmd == CMD_COMP:
ch["comp"] = dict(zip(("ratio", "attack", "release", "knee", "threshold"),
struct.unpack_from("<5H", p, 1)))
elif cmd == CMD_LIMIT:
ch["limit"] = dict(zip(("attack", "release", "knee", "threshold"), struct.unpack_from("<4H", p, 1)))
elif cmd == CMD_MATRIX:
ch["matrix"] = p[1]
elif cmd == CMD_MIX:
ch["mix"][p[1]] = w(2)
elif cmd == CMD_LINK:
ch["link"] = w(1)
for j in range(len(chans)): # forming a group copies the first channel's settings
if j != idx and ch["link"] >> j & 1:
copy_linked(chans, idx, j)
return
# like the real DSP: a change on a linked channel applies to the whole group
for j in link_group(chans, idx):
if j != idx:
copy_linked(chans, idx, j)