Add BetterDSPControl: web UI, desktop app and Pi writer for t.racks DSP 204/408
- Python stdlib server with SSE live updates, PIN login, remote access - Vanilla JS web UI (English/German): mixer, channel, routing, links, limiter calculator - Preset file export/import with undo, settings backup, lock for the desktop app - Network (TCP 9761) and USB HID transport (Windows, macOS, Linux) - Desktop app via pywebview, Raspberry Pi SD card writer, simulator and protocol tests - README with import guide for Claude Code, CLAUDE.md, protocol documentation Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ce02ae65a9
commit
fe13f261f7
31 files changed
+6445
No files matched your search
+172
@@ -0,0 +1,172 @@
|
||||
"""Preset files: export the DSP's current state and import it again.
|
||||
|
||||
A file holds the decoded state (readable, see protocol.parse_state) plus the raw memory image.
|
||||
Importing only changes the DSP's working state - the stored presets (U01...) stay untouched.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import time
|
||||
|
||||
from . import protocol as P
|
||||
|
||||
FORMAT = "dsp-control-preset"
|
||||
|
||||
# valid raw ranges (PROTOCOL.md, "Werte-Kodierung")
|
||||
_GATE = {"attack": (0, 998), "release": (9, 2999), "hold": (9, 998), "threshold": (0, 180)}
|
||||
_COMP = {"ratio": (0, 15), "attack": (0, 998), "release": (9, 2999), "knee": (0, 12), "threshold": (0, 220)}
|
||||
_LIMIT = {"attack": (0, 998), "release": (9, 2999), "knee": (0, 12), "threshold": (0, 220)}
|
||||
|
||||
|
||||
def export_doc(model_key: str, info: str, state: dict, raw: bytes) -> dict:
|
||||
return {"format": FORMAT, "version": 1, "model": model_key, "device": info,
|
||||
"preset_name": state.get("preset_name", ""),
|
||||
"exported": time.strftime("%Y-%m-%dT%H:%M:%S"), "state": state, "raw": raw.hex()}
|
||||
|
||||
|
||||
def _int(v, lo: int, hi: int, default: int) -> int:
|
||||
try:
|
||||
v = int(v)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return min(hi, max(lo, v))
|
||||
|
||||
|
||||
def _filter(src, cur: dict) -> dict:
|
||||
src = src if isinstance(src, dict) else {}
|
||||
return {"freq": _int(src.get("freq"), 0, 300, cur["freq"]), "slope": _int(src.get("slope"), 0, 20, cur["slope"])}
|
||||
|
||||
|
||||
def _peq(src, cur: list) -> list:
|
||||
src = src if isinstance(src, list) else []
|
||||
out = []
|
||||
for i, c in enumerate(cur):
|
||||
b = src[i] if i < len(src) and isinstance(src[i], dict) else {}
|
||||
out.append({"gain": _int(b.get("gain"), 0, 240, c["gain"]), "freq": _int(b.get("freq"), 0, 300, c["freq"]),
|
||||
"q": _int(b.get("q"), 0, 100, c["q"]), "type": _int(b.get("type"), 0, 8, c["type"]),
|
||||
"bypass": bool(b.get("bypass", c["bypass"]))})
|
||||
return out
|
||||
|
||||
|
||||
def _group(src, cur: dict, ranges: dict) -> dict:
|
||||
src = src if isinstance(src, dict) else {}
|
||||
return {k: _int(src.get(k), lo, hi, cur[k]) for k, (lo, hi) in ranges.items()}
|
||||
|
||||
|
||||
def _common(s: dict, c: dict) -> dict:
|
||||
name = s.get("name", c["name"])
|
||||
return {"name": P.clean_name(name).strip(),
|
||||
"hp": _filter(s.get("hp"), c["hp"]), "lp": _filter(s.get("lp"), c["lp"]),
|
||||
"gain": _int(s.get("gain"), 0, 400, c["gain"]), "polarity": bool(s.get("polarity", c["polarity"])),
|
||||
"delay": _int(s.get("delay"), 0, 65280, c["delay"]), "link": _int(s.get("link"), 0, 0xFFFF, c["link"]),
|
||||
"mute": bool(s.get("mute", c["mute"]))}
|
||||
|
||||
|
||||
def clean_state(model: P.Model, src: dict, base: dict) -> dict:
|
||||
"""`src` limited to valid values; anything missing or broken is taken from `base`."""
|
||||
st = copy.deepcopy(base)
|
||||
ins = src.get("inputs") if isinstance(src.get("inputs"), list) else []
|
||||
outs = src.get("outputs") if isinstance(src.get("outputs"), list) else []
|
||||
for i, c in enumerate(st["inputs"]):
|
||||
s = ins[i] if i < len(ins) and isinstance(ins[i], dict) else {}
|
||||
geq = s.get("geq") if isinstance(s.get("geq"), list) else []
|
||||
c.update(_common(s, c), peq=_peq(s.get("peq"), c["peq"]), gate=_group(s.get("gate"), c["gate"], _GATE),
|
||||
geq=[_int(geq[b], 0, 240, v) if b < len(geq) else v for b, v in enumerate(c["geq"])])
|
||||
for i, c in enumerate(st["outputs"]):
|
||||
s = outs[i] if i < len(outs) and isinstance(outs[i], dict) else {}
|
||||
mix = s.get("mix") if isinstance(s.get("mix"), list) else []
|
||||
c.update(_common(s, c), peq=_peq(s.get("peq"), c["peq"]),
|
||||
comp=_group(s.get("comp"), c["comp"], _COMP), limit=_group(s.get("limit"), c["limit"], _LIMIT),
|
||||
matrix=_int(s.get("matrix"), 0, (1 << model.n_in) - 1, c["matrix"]),
|
||||
mix=[_int(mix[k], 0, 400, v) if k < len(mix) else v for k, v in enumerate(c["mix"])])
|
||||
if isinstance(src.get("preset_name"), str):
|
||||
st["preset_name"] = src["preset_name"][:14]
|
||||
return st
|
||||
|
||||
|
||||
def read_file(model_key: str, model: P.Model, current: dict, doc: dict | None = None,
|
||||
raw: bytes | None = None) -> dict:
|
||||
"""The state to import from an uploaded file: our JSON (`doc`) or a bare memory image (`raw`)."""
|
||||
if raw is not None:
|
||||
if len(raw) not in (model.size, model.chunks * P.CHUNK_SIZE):
|
||||
raise ValueError(f"Unknown file format ({len(raw)} bytes) – expected a DSP Control preset file "
|
||||
f"or a memory image of the {model.name} ({model.size} bytes)")
|
||||
return _linked_alike(clean_state(model, P.parse_state(model, raw.ljust(model.chunks * P.CHUNK_SIZE, b"\0")), current))
|
||||
if not isinstance(doc, dict) or doc.get("format") != FORMAT:
|
||||
raise ValueError("Not a DSP Control preset file")
|
||||
if str(doc.get("model")) != model_key:
|
||||
raise ValueError(f"The file is for a DSP {doc.get('model')}, the connected device is a {model.name}")
|
||||
base = current
|
||||
try: # the raw image fills in anything the readable part lacks
|
||||
img = bytes.fromhex(doc.get("raw") or "")
|
||||
if len(img) in (model.size, model.chunks * P.CHUNK_SIZE):
|
||||
base = clean_state(model, P.parse_state(model, img.ljust(model.chunks * P.CHUNK_SIZE, b"\0")), current)
|
||||
except ValueError:
|
||||
pass
|
||||
return _linked_alike(clean_state(model, doc.get("state") if isinstance(doc.get("state"), dict) else {}, base))
|
||||
|
||||
|
||||
def _linked_alike(st: dict) -> dict:
|
||||
"""Linked channels share their settings on the DSP: take them from each group's first channel."""
|
||||
for chans in (st["inputs"], st["outputs"]):
|
||||
for g in P.link_groups(chans):
|
||||
for i in g[1:]:
|
||||
P.copy_linked(chans, g[0], i)
|
||||
return st
|
||||
|
||||
|
||||
def import_commands(model: P.Model, st: dict, current: dict) -> list[tuple[int, bytes]]:
|
||||
"""Commands that take the DSP from `current` to `st` - only values that actually change.
|
||||
|
||||
If the links change, they are dissolved first (otherwise the DSP would copy every value onto
|
||||
the whole group), then the parameters are set, then the new links are formed. Forming a group
|
||||
copies the first channel's settings to the others, so names, routing and mix levels (which
|
||||
links don't share) are sent once more at the end.
|
||||
"""
|
||||
kinds = (("in", "inputs"), ("out", "outputs"))
|
||||
relink = any(P.link_groups(st[key]) != P.link_groups(current[key]) for _, key in kinds)
|
||||
cmds = []
|
||||
if relink:
|
||||
for kind, key in kinds:
|
||||
for i in range(len(st[key])):
|
||||
cmds.append((P.CMD_LINK, bytes([model.channel(kind, i)]) + (1 << i).to_bytes(2, "little")))
|
||||
for kind, key in kinds:
|
||||
for i, ch in enumerate(st[key]):
|
||||
params = ["name", "gain", "polarity", "delay", "hp", "lp"] + [f"peq.{b}" for b in range(len(ch["peq"]))]
|
||||
if kind == "in":
|
||||
params += [f"geq.{b}" for b in range(len(ch["geq"]))] + ["gate"]
|
||||
else:
|
||||
params += ["comp", "limit", "matrix"] + [f"mix.{k}" for k in range(len(ch["mix"]))]
|
||||
for p in params + ["mute"]:
|
||||
cmd = P.param_command(model, kind, i, ch, p)
|
||||
if relink or cmd != P.param_command(model, kind, i, current[key][i], p):
|
||||
cmds.append(cmd)
|
||||
if relink:
|
||||
for kind, key in kinds:
|
||||
chans = st[key]
|
||||
groups = P.link_groups(chans)
|
||||
for i, mask in enumerate(P.link_masks(len(chans), groups)):
|
||||
if mask != 1 << i:
|
||||
cmds.append((P.CMD_LINK, bytes([model.channel(kind, i)]) + mask.to_bytes(2, "little")))
|
||||
for g in groups:
|
||||
for i in g[1:]:
|
||||
extra = ["name"] + (["matrix"] + [f"mix.{k}" for k in range(len(chans[i]["mix"]))] if kind == "out" else [])
|
||||
cmds += [P.param_command(model, kind, i, chans[i], p) for p in extra]
|
||||
return cmds
|
||||
|
||||
|
||||
def differences(target: dict, actual: dict) -> list[str]:
|
||||
"""Paths where the DSP's state differs from the imported one (the preset name is not settable)."""
|
||||
diffs = []
|
||||
|
||||
def walk(a, b, path):
|
||||
if isinstance(a, dict):
|
||||
for k in a:
|
||||
walk(a[k], b.get(k) if isinstance(b, dict) else None, f"{path}.{k}" if path else k)
|
||||
elif isinstance(a, list):
|
||||
for i, v in enumerate(a):
|
||||
walk(v, b[i] if isinstance(b, list) and i < len(b) else None, f"{path}.{i}")
|
||||
elif a != b:
|
||||
diffs.append(path)
|
||||
|
||||
walk({k: v for k, v in target.items() if k != "preset_name"}, actual, "")
|
||||
return diffs
|
||||
Reference in new issue
Block a user