"""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() 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(" 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("> 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 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: 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("= 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("> 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} 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(" 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, "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(" 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 == "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("> 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)