Files
GivouandClaude Opus 5.5 5597fae3f3 FIR DSP 408: own memory layout and FIR tab (filters, coefficient files, tap budget)
Layout and commands derived from the behaviour of its control software, tested
against the simulator only. No GEQ on this model; dynamic EQs are left untouched.

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

803 lines
33 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_PEQ_BYPASS = 0x3C # [ch][1 = all PEQ bands bypassed]
CMD_GEQ_BYPASS = 0x49 # [ch][1 = GEQ bypassed] (inputs)
CMD_TEST_SIGNAL = 0x39 # [source][freq index]: 0 = analog input, 1 = pink noise, 2 = white noise, 3 = sine
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()
# FIR DSP 408 only
CMD_FIR = 0x4B # [ch][type][window][u16 low Hz][u16 high Hz][u16 taps index] (outputs)
CMD_FIR_COEF = 0x4E # [ch][packet][u16 total][up to 12 floats, most significant byte first]
CMD_FIR_BYPASS = 0x4F # [ch][1 = bypassed] (inputs)
CMD_FIR_NAME = 0x5B # [ch][8 characters]
CHUNK_SIZE = 50
TEST_SOURCES = ("analog", "pink", "white", "sine")
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
beta: bool = False # never seen on a real device; only selectable by hand
fir: bool = False # FIR DSP 408: own memory layout, see _parse_fir
@property
def in_size(self) -> int:
return 138 if self.fir else 140
@property
def out_size(self) -> int:
return 108 if self.fir else 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 test_base(self) -> int:
"""Test signal (source, sine frequency index), after the mute masks and one word per channel."""
return self.globals_base + 4 + 2 * self.n_in + 2 * self.n_out
@property
def size(self) -> int:
if self.fir:
return 0x625
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),
"206": Model("DSP 206", 2, 6, beta=True), "408fir": Model("FIR DSP 408", 4, 8, beta=True, fir=True)}
FIR_MAX_IN, FIR_MAX_OUT, FIR_MAX_TOTAL = 2048, 1024, 4096 # taps per input / output, all channels together
FIR_PACKET = 12 # coefficients per CMD_FIR_COEF frame
def detect_model(info: str) -> str | None:
"""Beta models are never detected, and a FIR device must not pass as a plain DSP 408."""
info = info.replace(" ", "").upper()
if "FIR" in info:
return None
for key, model in MODELS.items():
if not model.beta and f"DSP{key}" in info:
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)."""
if model.fir:
return _parse_fir(model, buf)
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),
})
source, freq, _, peq_in, peq_out, geq_in = struct.unpack_from("<6H", buf, model.test_base)
test = {"source": source if source < len(TEST_SOURCES) else 0, "freq": freq if freq < 31 else 0}
for i, ch in enumerate(inputs):
ch["peq_bypass"], ch["geq_bypass"] = bool(peq_in >> i & 1), bool(geq_in >> i & 1)
for i, ch in enumerate(outputs):
ch["peq_bypass"] = bool(peq_out >> i & 1)
return {"preset_name": _name(buf[2:16]), "inputs": inputs, "outputs": outputs, "test": test}
# ---------------------------------------------------------------- FIR DSP 408
#
# Layout: header 0x10, inputs of 138 bytes, outputs of 108, then the mute masks, one word per channel with
# the bypassed PEQ bands, 8 characters of FIR name per channel and 17 bytes of other settings.
# Inputs: name, gate, 3 dynamic EQs (not used here), 8 PEQ bands, compressor, FIR taps + bypass, gain ...
# Outputs: name, matrix, mix, HP/LP (with own bypass bytes), FIR, 9 PEQ bands, limiter, gain ...
def _fir_slope(index: int, bypass: int) -> int:
"""This model keeps slope and bypass apart, the state uses one value (0 = bypass) like the other models."""
return 0 if bypass else min(index + 1, 20)
def _fir_filter(buf: bytes, freq_off: int, slope_off: int) -> dict:
return {"freq": struct.unpack_from("<H", buf, freq_off)[0], "slope": _fir_slope(buf[slope_off], buf[slope_off + 2])}
def _parse_fir(model: Model, buf: bytes) -> dict:
u16 = lambda off: struct.unpack_from("<H", buf, off)[0]
g = model.globals_base
in_mute, out_mute = u16(g), u16(g + 2)
fir_name = lambda c: _name(buf[0x5B4 + 8 * c : 0x5BC + 8 * c])
def bands(off: int, n: int, mask: int) -> list[dict]:
out = _peq(buf, off, n)
for j, b in enumerate(out):
b["bypass"] = bool(mask >> j & 1)
return out
inputs = []
for i in range(model.n_in):
o = 0x10 + i * model.in_size
comp = dict(zip(("ratio", "attack", "release", "knee", "threshold", "eq_freq"), struct.unpack_from("<6H", buf, o + 112)))
inputs.append({
"name": _name(buf[o : o + 8]),
"gate": dict(zip(("attack", "release", "hold", "threshold"), struct.unpack_from("<4H", buf, o + 8))),
"peq": bands(o + 64, 8, u16(g + 4 + 2 * i)),
"comp": {**comp, "eq_type": buf[o + 124], "eq_bypass": buf[o + 125]},
"fir": {"taps": u16(o + 126), "bypass": bool(u16(o + 128)), "name": fir_name(i)},
"gain": u16(o + 130), "polarity": u16(o + 132) != 0, "delay": u16(o + 134), "link": u16(o + 136),
"mute": bool(in_mute >> i & 1),
})
outputs = []
for i in range(model.n_out):
o = model.out_base + i * model.out_size
typ, win, low, high, taps = struct.unpack_from("<BBHHH", buf, o + 28)
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": _fir_filter(buf, o + 20, o + 24),
"lp": _fir_filter(buf, o + 22, o + 25),
"fir": {"type": typ, "window": win, "low": low, "high": high, "taps": taps, "name": fir_name(model.channel("out", i))},
"peq": bands(o + 36, 9, u16(g + 12 + 2 * i)),
"limit": dict(zip(("ratio", "attack", "release", "knee", "threshold"), struct.unpack_from("<5H", buf, o + 90))),
"gain": u16(o + 100), "polarity": u16(o + 102) != 0, "delay": u16(o + 104), "link": u16(o + 106),
"mute": bool(out_mute >> i & 1),
})
return {"preset_name": _name(buf[2:16]), "inputs": inputs, "outputs": outputs, "test": {"source": 0, "freq": 0}}
def _build_fir(model: Model, state: dict) -> bytearray:
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)
g = model.globals_base
def put_bands(off: int, bands: list[dict]) -> int:
for j, b in enumerate(bands):
struct.pack_into("<HHBB", buf, off + j * 6, b["gain"], b["freq"], b["q"], b["type"])
return sum(int(b.get("bypass", False)) << j for j, b in enumerate(bands))
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, c = ch["gate"], ch["comp"]
struct.pack_into("<4H", buf, o + 8, gt["attack"], gt["release"], gt["hold"], gt["threshold"])
struct.pack_into("<H", buf, g + 4 + 2 * i, put_bands(o + 64, ch["peq"]))
struct.pack_into("<6HBB", buf, o + 112, c["ratio"], c["attack"], c["release"], c["knee"], c["threshold"],
c["eq_freq"], c["eq_type"], c["eq_bypass"])
struct.pack_into("<6H", buf, o + 126, ch["fir"]["taps"], int(ch["fir"]["bypass"]), ch["gain"],
int(ch["polarity"]), ch["delay"], ch.get("link", 1 << i))
buf[0x5B4 + 8 * i : 0x5BC + 8 * i] = pad(ch["fir"]["name"], 8)
in_mute |= int(ch["mute"]) << i
for i, ch in enumerate(state["outputs"]):
o = model.out_base + i * model.out_size
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"])
hp, lp, f, lim = ch["hp"], ch["lp"], ch["fir"], ch["limit"]
struct.pack_into("<HHBBBB", buf, o + 20, hp["freq"], lp["freq"], max(hp["slope"] - 1, 0), max(lp["slope"] - 1, 0),
int(not hp["slope"]), int(not lp["slope"]))
struct.pack_into("<BBHHH", buf, o + 28, f["type"], f["window"], f["low"], f["high"], f["taps"])
struct.pack_into("<H", buf, g + 12 + 2 * i, put_bands(o + 36, ch["peq"]))
struct.pack_into("<5H", buf, o + 90, lim["ratio"], lim["attack"], lim["release"], lim["knee"], lim["threshold"])
struct.pack_into("<4H", buf, o + 100, ch["gain"], int(ch["polarity"]), ch["delay"], ch.get("link", 1 << i))
c = model.channel("out", i)
buf[0x5B4 + 8 * c : 0x5BC + 8 * c] = pad(f["name"], 8)
out_mute |= int(ch["mute"]) << i
struct.pack_into("<HH", buf, g, in_mute, out_mute)
return buf
def _default_fir(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}, "peq": peq(8),
"comp": {"ratio": 0, "attack": 49, "release": 99, "knee": 0, "threshold": 120, "eq_freq": 150, "eq_type": 0, "eq_bypass": 1},
"fir": {"taps": 0, "bypass": True, "name": ""},
"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},
"fir": {"type": 0, "window": 3, "low": 150, "high": 20000, "taps": 8, "name": ""},
"peq": peq(9), "limit": {"ratio": 0, "attack": 49, "release": 99, "knee": 0, "threshold": 200},
"gain": 280, "polarity": False, "delay": 0, "mute": False, "link": 1 << i,
} for i in range(model.n_out)],
"test": {"source": 0, "freq": 0},
}
def fir_channel_taps(ch: dict) -> int:
"""How many of the shared FIR taps a channel takes."""
f = ch["fir"]
if "type" in f:
return 256 + 32 * f["taps"] if f["type"] else 0
return 0 if f["bypass"] else f["taps"]
def clean_fir(value, cur: dict) -> dict:
"""FIR settings of an output limited to valid values; anything missing stays as it is."""
value = value if isinstance(value, dict) else {}
def num(key, lo, hi):
try:
return min(hi, max(lo, int(value.get(key, cur[key]))))
except (TypeError, ValueError):
return cur[key]
return {"type": num("type", 0, 4), "window": num("window", 0, 10), "low": num("low", 20, 20000),
"high": num("high", 20, 20000), "taps": num("taps", 0, 24), "name": cur.get("name", "")}
def fir_coef_frames(channel: int, coeffs: list[float]) -> list[bytes]:
"""Payloads of the CMD_FIR_COEF frames for one channel."""
n = len(coeffs)
return [bytes([channel, p]) + struct.pack("<H", n)
+ b"".join(struct.pack(">f", c) for c in coeffs[p * FIR_PACKET : (p + 1) * FIR_PACKET])
for p in range(-(-n // FIR_PACKET))]
def _fir_command(c: int, kind: str, ch: dict, top: str, rest: list[str]) -> tuple[int, bytes] | None:
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([max(f["slope"] - 1, 0), int(not f["slope"])])
if top == "limit" and kind == "out":
return CMD_LIMIT, bytes([c]) + b"".join(_w(ch["limit"][k]) for k in ("ratio", "attack", "release", "knee", "threshold"))
if top == "comp" and kind == "in":
g = ch["comp"]
return CMD_COMP, bytes([c]) + b"".join(_w(g[k]) for k in ("ratio", "attack", "release", "knee", "threshold", "eq_freq")) + bytes([g["eq_type"], g["eq_bypass"]])
if top == "fir" and kind == "out":
f = ch["fir"]
return CMD_FIR, bytes([c, f["type"], f["window"]]) + _w(f["low"]) + _w(f["high"]) + _w(f["taps"])
if top == "fir" and kind == "in":
return CMD_FIR_BYPASS, bytes([c, int(ch["fir"]["bypass"])])
return None
def _apply_fir(ch: dict, cmd: int, p: bytes) -> bool:
"""Set commands of this model (simulator). False: handled like on the other models."""
w = lambda o: struct.unpack_from("<H", p, o)[0]
if cmd in (CMD_HIGH_PASS, CMD_LOW_PASS):
ch["hp" if cmd == CMD_HIGH_PASS else "lp"] = {"freq": w(1), "slope": _fir_slope(p[3], p[4])}
elif cmd == CMD_LIMIT:
ch["limit"] = dict(zip(("ratio", "attack", "release", "knee", "threshold"), struct.unpack_from("<5H", p, 1)))
elif cmd == CMD_COMP:
ch["comp"] = {**dict(zip(("ratio", "attack", "release", "knee", "threshold", "eq_freq"), struct.unpack_from("<6H", p, 1))),
"eq_type": p[13], "eq_bypass": p[14]}
elif cmd == CMD_FIR:
ch["fir"].update(type=p[1], window=p[2], low=w(3), high=w(5), taps=w(7))
elif cmd == CMD_FIR_BYPASS:
ch["fir"]["bypass"] = bool(p[1])
elif cmd == CMD_FIR_NAME:
ch["fir"]["name"] = _name(p[1:9])
elif cmd == CMD_FIR_COEF:
if "bypass" in ch["fir"]:
ch["fir"]["taps"] = w(2)
else:
return False
return True
def build_state_buffer(model: Model, state: dict) -> bytearray:
"""Inverse of parse_state (used by the simulator)."""
if model.fir:
return _build_fir(model, state)
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)
test = state.get("test") or {}
mask = lambda chans, key: sum(int(bool(ch.get(key))) << i for i, ch in enumerate(chans))
struct.pack_into("<HH", buf, model.test_base, test.get("source", 0), test.get("freq", 0))
struct.pack_into("<3H", buf, model.test_base + 6, mask(state["inputs"], "peq_bypass"),
mask(state["outputs"], "peq_bypass"), mask(state["inputs"], "geq_bypass"))
return buf
def default_state(model: Model) -> dict:
if model.fir:
return _default_fir(model)
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, "peq_bypass": False, "geq_bypass": False,
} 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, "peq_bypass": False,
} for i in range(model.n_out)],
"test": {"source": 0, "freq": 17},
}
# ---------------------------------------------------------------- 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 model.fir and (fir := _fir_command(c, kind, ch, top, rest)):
return fir
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 == "peq_bypass":
return CMD_PEQ_BYPASS, bytes([c, int(ch["peq_bypass"])])
if top == "geq_bypass" and kind == "in":
return CMD_GEQ_BYPASS, bytes([c, int(ch["geq_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
if cmd == CMD_TEST_SIGNAL:
state["test"] = {"source": p[0], "freq": p[1] if len(p) > 1 else 0}
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 model.fir and _apply_fir(ch, cmd, p):
pass
elif cmd == CMD_PEQ_BYPASS:
ch["peq_bypass"] = bool(p[1])
elif cmd == CMD_GEQ_BYPASS:
ch["geq_bypass"] = bool(p[1])
elif 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)