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>
This commit is contained in:
GivouandClaude Opus 5.5 committed 2026-11-02 17:11:46 +01:00
1 parent f7d5e22bb0
commit 5597fae3f3
13 files changed
+622 -35

No files matched your search

+9 -4
View File
@@ -47,6 +47,9 @@ pi_writer.py → pi_image.py (cloud-init SD card, installs server.py as a system
until it is below the limit again. The client mirrors this in `gainCap` (faders, sliders, `setParam`).
* **Link group names** – `Device.linknames` (app-side, like the colours), keyed by kind and members (`"out:0,1"`), so a
changed group starts without a name. The mixer draws them as brackets in row 1 of the `.strips` grid (`linkBands`).
* **FIR tab** (`viewFir`, only `d.fir`) – outputs: `0x4B` type/window/cut-offs/taps index, the DSP calculates the filter;
the curve is the app's own windowed sinc. Files: `Device.upload_fir` (`0x5B` name, `0x4E` packets of 12 floats). The DSP
can't send coefficients back, so the curve of a file only exists in the session (`S.firCoef`).
* **Network search** – `App.scan_network` probes the local /24 networks on TCP 9761 (handshake + device info),
skipping DSPs this app is connected to.
* **Copy settings / mute all** – `App.copy_settings` (`POST /api/copy`, groups level/filters/eq/dynamics/routing) and
@@ -109,10 +112,12 @@ and the DSP's own mirroring inside groups, limiter-active bit mask, preset impor
Not verified yet – ask for a log (`python server.py -v`) from real hardware before changing protocol code here:
* **Beta models** `206` and `408fir` – never seen on real hardware, same protocol and memory layout are only assumed
(also the USB ID). Never auto-detected (`detect_model`, a FIR device must not pass as a 408); the only hint is the
note in the add-device form, afterwards they work like the others. The FIR filters are deliberately not implemented;
ask testers for a preset export (it holds the raw image) and a log first.
* **Beta models** `206` and `408fir` – never seen on real hardware. Never auto-detected (`detect_model`, a FIR device
must not pass as a 408); the only hint is the note in the add-device form, afterwards they work like the others.
`206`: same protocol and layout as the 204/408 are only assumed (no control software looked at), also the USB ID.
`408fir`: own layout and commands derived from its control software (`Model.fir`, `_parse_fir`, `_fir_command`), simulator
only. Not done: dynamic EQs (kept untouched), saving coefficients into a preset slot of the DSP (`0x5A`, format
not worked out), where it keeps the test signal (the app remembers it). Ask testers for a preset export and a log.
* **DSP 408 on real hardware** (layout and frames match published captures, limiter bits for Out 5–8 assumed)
* USB on Windows and Linux against a real DSP (only tested against a fake HID device)
* Where the PEQ bypass flag lives in the memory image; format of the set-command acknowledgement; where the number
+28
View File
@@ -186,3 +186,31 @@ Where the PEQ bypass flag is stored in the image is not known yet.
* Send: report ID `00` + one complete frame (`10 02 … 10 03 CHK`), zero-padded to the output report length.
* Receive: every input report holds exactly one frame starting at byte 0, length = `LEN + 8`, then padding.
* The frames are identical to TCP; the longest (config chunk, 50 data bytes) is 60 bytes and fits a 64-byte report.
## FIR DSP 408 (unverified)
Derived from the behaviour of its control software, not yet seen on a device. Same frames; device info starts with
`FIR408`. The memory image has 1573 bytes (32 chunks) and its own layout:
| Offset | Content |
|---|---|
| `0x010` + 138·n | Input: name 8, gate 4×u16, 3 dynamic EQs of 16 bytes, 8 PEQ bands of 6 bytes, compressor (ratio, attack, release, knee, threshold, EQ frequency as u16, 2 bytes), FIR taps u16, FIR bypass u16, gain, polarity, delay, link |
| `0x238` + 108·n | Output: name 8, matrix u16, mix 4×u16, u16, HP frequency u16, LP frequency u16, HP slope, LP slope, HP bypass, LP bypass (bytes), FIR type, window (bytes), low Hz, high Hz, taps index (u16), 9 PEQ bands, limiter (ratio, attack, release, knee, threshold), gain, polarity, delay, link |
| `0x598` | Mute masks: inputs u16, outputs u16 |
| `0x59C` | Bypassed PEQ bands, u16 bit mask per channel (inputs, then outputs) |
| `0x5B4` | FIR name per channel, 8 characters each |
No GEQ on this model, no master bypass commands. Slope index without the "bypass" entry (0 = BW -6). Changed commands:
| Cmd | Payload |
|---|---|
| `0x31` / `0x32` | `[ch][u16 freq][slope][1 = bypass]` |
| `0x30` | `[ch]` ratio, attack, release, knee, threshold, EQ frequency as u16, `[EQ type][EQ bypass]` (inputs) |
| `0x3F` | `[ch]` ratio, attack, release, knee, threshold as u16 |
| `0x4B` | `[ch][type][window][u16 low Hz][u16 high Hz][u16 taps index]`, outputs. Type: bypass, low, high, band, external. Window: rectangle, Bartlett, Hanning, Hamming, Blackman, sine, sinc, Nuttall, Kaiser, Blackman-Nuttall, Blackman-Harris. Taps = 256 + 32·index |
| `0x4E` | `[ch][packet][u16 total]` + up to 12 floats, most significant byte first |
| `0x4F` | `[ch][1 = bypass]`, inputs |
| `0x5B` | `[ch]` + 8 characters of FIR name |
At most 2048 coefficients per input, 1024 per output, 4096 over all channels.
+5 -1
View File
@@ -78,7 +78,11 @@ Control both devices at the same time from your phone, tablet or computer – ov
| t.racks DSP 204 | ✓ | ✓ | yes (firmware V0104P, USB on macOS) |
| t.racks DSP 408 | ✓ | ✓ | not yet – frames match published captures |
| t.racks DSP 206 (beta) | ✓ | ? | no – assumed to work like the others, testers wanted |
| t.racks FIR DSP 408 (beta) | ✓ | ? | no – as above; the FIR filters themselves are not supported |
| t.racks FIR DSP 408 (beta) | ✓ | ? | no – memory layout and FIR commands derived from the control software, simulator only |
The FIR DSP 408 gets its own **FIR** tab: low-, high- and band-pass with window and taps on the outputs, coefficients
from a txt/csv file on inputs (up to 2048) and outputs (up to 1024), a curve and the shared budget of 4096 taps. Its
dynamic EQs are not supported.
Beta models are not detected automatically: choose them by hand when adding the device (amplifiers off for the first
test). If the shown values don't match the DSP, please send the file from File… → Export.
+34 -1
View File
@@ -85,6 +85,7 @@ class Device:
"detected_model": self.model_name or None,
"n_in": self.model.n_in if self.model else 0,
"n_out": self.model.n_out if self.model else 0,
"fir": bool(self.model and self.model.fir),
"presets": self.presets, "state": self.state}
def start(self):
@@ -138,6 +139,35 @@ class Device:
await asyncio.sleep(0.3)
await self.refresh()
def fir_taps_used(self, skip: tuple[str, int] | None = None) -> int:
"""FIR taps taken by all channels together (they share P.FIR_MAX_TOTAL)."""
total = 0
for kind, key in (("in", "inputs"), ("out", "outputs")):
for i, ch in enumerate(self.state[key]):
if (kind, i) != skip:
total += P.fir_channel_taps(ch)
return total
async def upload_fir(self, kind: str, idx: int, coeffs: list[float], name: str) -> int:
"""Send FIR coefficients to a channel. Returns how many frames were not answered."""
if self.status != "online" or not self.state or not self.model.fir:
raise RuntimeError("DSP is not connected")
await self.flush()
c = self.model.channel(kind, idx)
name = P.clean_name(name)[:8]
failed = 0
if await self._request(P.CMD_FIR_NAME, bytes([c]) + name.encode("ascii").ljust(8, b" ")) is None:
failed += 1
for payload in P.fir_coef_frames(c, coeffs):
if await self._request(P.CMD_FIR_COEF, payload) is None:
failed += 1
fir = self.state["inputs" if kind == "in" else "outputs"][idx]["fir"]
fir["name"] = name
if kind == "in":
fir["taps"] = len(coeffs)
self._emit_state()
return failed
def gain_cap(self, kind: str, idx: int, value: int) -> int:
"""Software limit of a channel's gain: never above the limit - unless the DSP itself is set higher,
then only downwards (it snaps back into the limit once it is below)."""
@@ -406,7 +436,10 @@ class Device:
self._codes = None
async def _load_config(self):
self.state = await self._read_config()
state = await self._read_config()
if self.model.fir and self.state: # where this model keeps the test signal in its memory is not known
state["test"] = self.state.get("test", state["test"])
self.state = state
async def _read_config(self) -> dict:
model = self.model
+18 -10
View File
@@ -49,16 +49,16 @@ def _peq(src, cur: list) -> list:
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()}
return {k: _int(src.get(k), *ranges.get(k, (0, 0xFFFF)), v) for k, v in cur.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"]),
return {"name": P.clean_name(name).strip(), **{k: _filter(s.get(k), c[k]) for k in ("hp", "lp") if k in c},
"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"])), "peq_bypass": bool(s.get("peq_bypass", c.get("peq_bypass", False)))}
"mute": bool(s.get("mute", c["mute"])),
**({"peq_bypass": bool(s.get("peq_bypass", c.get("peq_bypass", False)))} if "peq_bypass" in c else {})}
def clean_state(model: P.Model, src: dict, base: dict) -> dict:
@@ -69,16 +69,24 @@ def clean_state(model: P.Model, src: dict, base: dict) -> dict:
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_bypass=bool(s.get("geq_bypass", c.get("geq_bypass", False))),
c.update(_common(s, c), peq=_peq(s.get("peq"), c["peq"]), gate=_group(s.get("gate"), c["gate"], _GATE))
if model.fir:
c.update(comp=_group(s.get("comp"), c["comp"], _COMP))
c["fir"]["bypass"] = bool((s.get("fir") if isinstance(s.get("fir"), dict) else {}).get("bypass", c["fir"]["bypass"]))
continue
c.update(geq_bypass=bool(s.get("geq_bypass", c.get("geq_bypass", False))),
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),
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 model.fir:
c["fir"] = P.clean_fir(s.get("fir"), c["fir"])
else:
c.update(comp=_group(s.get("comp"), c["comp"], _COMP))
if isinstance(src.get("preset_name"), str):
st["preset_name"] = src["preset_name"][:14]
return st
@@ -132,11 +140,11 @@ def import_commands(model: P.Model, st: dict, current: dict) -> list[tuple[int,
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", "peq_bypass"] + [f"peq.{b}" for b in range(len(ch["peq"]))]
params = ["name", "gain", "polarity", "delay"] + [k for k in ("hp", "lp", "peq_bypass") if k in ch] + [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", "geq_bypass"]
params += ["gate", "comp", "fir"] if model.fir else [f"geq.{b}" for b in range(len(ch["geq"]))] + ["gate", "geq_bypass"]
else:
params += ["comp", "limit", "matrix"] + [f"mix.{k}" for k in range(len(ch["mix"]))]
params += (["fir", "limit"] if model.fir else ["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):
+223 -5
View File
@@ -46,6 +46,11 @@ 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")
@@ -209,15 +214,16 @@ class Model:
name: str
n_in: int
n_out: int
beta: bool = False # layout assumed from the other models, never seen on a real device; only selectable by hand
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 140
return 138 if self.fir else 140
@property
def out_size(self) -> int:
return 96 + 2 * self.n_in
return 108 if self.fir else 96 + 2 * self.n_in
@property
def out_base(self) -> int:
@@ -234,6 +240,8 @@ class Model:
@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
@@ -249,7 +257,10 @@ class Model:
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)}
"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:
@@ -289,6 +300,8 @@ def _peq(buf: bytes, off: int, n: int) -> list[dict]:
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)
@@ -339,8 +352,207 @@ def parse_state(model: Model, buf: bytes) -> dict:
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"
@@ -389,6 +601,8 @@ def build_state_buffer(model: Model, state: dict) -> bytearray:
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 {
@@ -471,6 +685,8 @@ def param_command(model: Model, kind: str, idx: int, ch: dict, param: str) -> tu
"""
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":
@@ -541,7 +757,9 @@ def apply_command(model: Model, state: dict, cmd: int, p: bytes):
return
ch = chans[idx]
w = lambda o: struct.unpack_from("<H", p, o)[0]
if cmd == CMD_PEQ_BYPASS:
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])
+50 -2
View File
@@ -12,6 +12,7 @@ import errno
import hashlib
import json
import logging
import math
import mimetypes
import re
import secrets
@@ -385,6 +386,8 @@ class App:
return {"ok": True}
async def device_online(self, dev: Device):
if dev.model.fir and dev.test_saved is not None: # its test signal can't be read back: make sure it is off
await dev.set_test_signal(0, 0)
await self.check_audio_test(dev)
if not self.mute_all["active"] and self.mute_all["restore"].get(dev.id):
self.unmute_device(dev) # released while this DSP was offline
@@ -421,6 +424,44 @@ class App:
self.broadcast({"type": "muteall", "data": self.mute_all_info()})
return self.mute_all_info()
# ------------------------------------------------------------ FIR filters (FIR DSP 408)
@staticmethod
def check_fir_param(dev: Device, idx: int, value) -> dict:
value = P.clean_fir(value, dev.state["outputs"][idx]["fir"])
if value["type"] and dev.fir_taps_used(skip=("out", idx)) + 256 + 32 * value["taps"] > P.FIR_MAX_TOTAL:
raise RuntimeError("Out of FIR taps: all channels together have 4096")
return value
async def upload_fir(self, dev: Device, body: dict) -> dict:
kind = "in" if body.get("kind") == "in" else "out"
idx = int(body.get("idx", 0))
if not dev.state or not dev.model.fir or not 0 <= idx < len(dev.state["inputs" if kind == "in" else "outputs"]):
raise RuntimeError("DSP is not connected")
raw = body.get("coeffs")
limit = P.FIR_MAX_IN if kind == "in" else P.FIR_MAX_OUT
if not isinstance(raw, list) or not 1 <= len(raw) <= limit:
raise RuntimeError(f"Too many FIR coefficients: at most {limit} here")
try:
coeffs = [float(c) for c in raw]
except (TypeError, ValueError):
raise RuntimeError("Not valid FIR coefficients") from None
if not all(math.isfinite(c) for c in coeffs):
raise RuntimeError("Not valid FIR coefficients")
name = str(body.get("name") or "")
if kind == "out":
taps = max(0, -((256 - len(coeffs)) // 32)) # taps index that holds them
cur = dev.state["outputs"][idx]["fir"]
dev.set_param("out", idx, "fir", self.check_fir_param(dev, idx, {**cur, "type": 4, "taps": taps}))
elif dev.fir_taps_used(skip=("in", idx)) + len(coeffs) > P.FIR_MAX_TOTAL:
raise RuntimeError("Out of FIR taps: all channels together have 4096")
failed = await dev.upload_fir(kind, idx, coeffs, name)
if kind == "in" and dev.state["inputs"][idx]["fir"]["bypass"]:
dev.set_param("in", idx, "fir.bypass", False)
if failed:
raise RuntimeError(f"The DSP did not answer {failed} frames")
return {"ok": True, "count": len(coeffs)}
# ------------------------------------------------------------ copy channel settings
def copy_settings(self, body: dict) -> dict:
@@ -453,10 +494,13 @@ class App:
if kind == "in":
params += ["geq_bypass"] + [f"geq.{b}" for b in range(31)]
if "dynamics" in groups:
params += ["gate"] if kind == "in" else ["comp", "limit"]
params += ["gate", "comp"] if kind == "in" else ["comp", "limit"]
if "routing" in groups and kind == "out":
params += [f"mix.{k}" for k in range(min(len(sch["mix"]), len(tch["mix"])))]
for p in params:
top = p.split(".")[0]
if top not in sch or top not in tch or (isinstance(sch[top], dict) and sch[top].keys() != tch[top].keys()):
continue # a setting only one of the two models has
v = copy.deepcopy(self._get(sch, p))
if p == "gain":
v = dev.gain_cap(kind, idx, v)
@@ -791,7 +835,7 @@ class App:
if dev.demo and (method in ("DELETE", "PUT") or action in ("unlock", "lockcode")):
raise RuntimeError("Not available for the demo device")
# during the audio test only the test controls work: generator, test fader, output mutes
if dev.test_active and (action in ("preset/recall", "preset/store", "export", "import", "undo", "link")
if dev.test_active and (action in ("preset/recall", "preset/store", "export", "import", "undo", "link", "fir")
or action == "set" and body.get("param") != "mute"):
raise RuntimeError("Audio test is on – switch it off first")
if self.demo["enabled"] and not dev.demo and action == "connect":
@@ -837,8 +881,12 @@ class App:
kind, idx, value = body["kind"], int(body["idx"]), body["value"]
if body["param"] == "gain" and not body.get("force"): # force: confirmed twice in the app
value = dev.gain_cap(kind, idx, int(value)) # software max level
if body["param"] == "fir" and dev.state:
value = self.check_fir_param(dev, int(body["idx"]), value)
dev.set_param(kind, idx, body["param"], value)
return {"ok": True, "value": value}
if action == "fir":
return await self.upload_fir(dev, body)
if action == "maxgain": # app-side setting, the DSP doesn't know it
dev.maxgain = clean_maxgain(body.get("maxgain"))
self.save()
+1 -1
View File
@@ -34,7 +34,7 @@ class SimDSP:
def handle(self, cmd: int, p: bytes) -> tuple[int, bytes]:
m = self.model
if cmd == P.CMD_DEVICE_INFO:
return cmd, f"{m.name.replace(' ', '')} V010 SIM".encode()
return cmd, f"{'FIR408' if m.fir else m.name.replace(' ', '')} V010 SIM".encode()
if cmd == P.CMD_PRESET_COUNT:
return cmd, bytes([0, 0, 0, 0, 0, 0 if self.unlocked else 1])
if cmd == P.CMD_UNLOCK:
+173 -9
View File
@@ -58,7 +58,7 @@ const S = {
devices: {}, order: [], cur: store.get("dsp.cur"),
view: store.get("dsp.view") || "mixer", settings: false,
sel: { kind: "in", idx: 0 }, band: 0, busy: false, dirty: false,
routeOpen: null, es: null, linkSel: { in: [], out: [] }, linkEdit: { in: null, out: null },
routeOpen: null, es: null, linkSel: { in: [], out: [] }, linkEdit: { in: null, out: null }, firSel: { kind: "out", idx: 0 }, firDraft: null, firCoef: {},
lim: { amps: [], assign: {}, ref: {} },
demo: { enabled: false, model: "408" },
muteAll: false,
@@ -625,6 +625,7 @@ function renderTabs() {
$("#btn-settings").classList.toggle("on", S.settings);
$("#btn-settings").disabled = testLock;
document.querySelectorAll("#viewtabs button").forEach(b => {
if (b.dataset.view === "fir") b.hidden = !(dev() && dev().fir);
b.classList.toggle("active", !S.settings && b.dataset.view === S.view);
b.disabled = testLock && b.dataset.view !== "test";
});
@@ -938,6 +939,156 @@ function viewMixer(d) {
h("p", { class: "info hint" }, t("Drag a fader by its knob · snaps at 0 dB · double-tap the knob = 0 dB · tap the dB value to type one · tap the name = edit channel"))];
}
// ------------------------------------------------------------------ FIR filters (FIR DSP 408)
const FIR_TYPES = () => [t("Bypass"), t("Low-pass"), t("High-pass"), t("Band-pass"), t("From file")];
const FIR_WINDOWS = ["Rectangle", "Bartlett", "Hanning", "Hamming", "Blackman", "Sine", "Sinc", "Nuttall", "Kaiser", "Blackman-Nuttall", "Blackman-Harris"];
const firTapCount = i => 256 + 32 * i;
const firKey = (d, kind, i) => `${d.id}|${kind}${i}`;
const firMax = kind => (kind === "in" ? 2048 : 1024);
function firTapsOf(ch) { const f = ch.fir; return "type" in f ? (f.type ? firTapCount(f.taps) : 0) : (f.bypass ? 0 : f.taps); }
const firUsed = d => [...chans(d, "in"), ...chans(d, "out")].reduce((s, ch) => s + firTapsOf(ch), 0);
function firWindow(kind, n, N) {
const x = N > 1 ? n / (N - 1) : 0, c = k => Math.cos(2 * Math.PI * k * x);
const sum = a => a.reduce((s, v, k) => s + (k % 2 ? -v : v) * c(k), 0);
switch (kind) {
case 1: return 1 - Math.abs(2 * x - 1);
case 2: return 0.5 - 0.5 * c(1);
case 3: return 0.54 - 0.46 * c(1);
case 4: return sum([0.42, 0.5, 0.08]);
case 5: return Math.sin(Math.PI * x);
case 6: { const u = 2 * x - 1; return u ? Math.sin(Math.PI * u) / (Math.PI * u) : 1; }
case 7: return sum([0.355768, 0.487396, 0.144232, 0.012604]);
case 8: { const i0 = v => { let s = 1, e = 1; for (let k = 1; k < 30; k++) { e *= (v / (2 * k)) ** 2; s += e; } return s; };
const u = 2 * x - 1; return i0(8.6 * Math.sqrt(Math.max(0, 1 - u * u))) / i0(8.6); }
case 9: return sum([0.3635819, 0.4891775, 0.1365995, 0.0106411]);
case 10: return sum([0.35875, 0.48829, 0.14128, 0.01168]);
default: return 1;
}
}
// windowed sinc, only for the preview: the DSP calculates the filter itself from type, window, cut-offs and taps
function firDesign(f) {
const N = firTapCount(f.taps), M = (N - 1) / 2, lp = c => n => { const v = n - M, w = 2 * c / FS; return v ? Math.sin(Math.PI * w * v) / (Math.PI * v) : w; };
const lo = lp(f.low), hi = lp(f.high), out = new Float64Array(N);
for (let n = 0; n < N; n++) {
const ideal = f.type === 1 ? hi(n) : f.type === 2 ? (n === M ? 1 : 0) - lo(n) : hi(n) - lo(n);
out[n] = ideal * firWindow(f.window, n, N);
}
return out;
}
function firResponseDb(h, hz) {
const w = -2 * Math.PI * hz / FS; let re = 0, im = 0;
for (let n = 0; n < h.length; n++) { re += h[n] * Math.cos(w * n); im += h[n] * Math.sin(w * n); }
return 10 * Math.log10(re * re + im * im || 1e-12);
}
function drawFir(canvas, h) {
const dpr = window.devicePixelRatio || 1, W = canvas.clientWidth, H = canvas.clientHeight;
if (!W || !H) return;
canvas.width = W * dpr; canvas.height = H * dpr;
const c = canvas.getContext("2d"); c.scale(dpr, dpr);
const x = hz => W * Math.log(hz / 20) / Math.log(1000), y = db => H * (6 - db) / 86;
c.font = "10px sans-serif"; c.lineWidth = 1;
for (const hz of [20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]) {
c.strokeStyle = "#2a303a"; c.beginPath(); c.moveTo(x(hz), 0); c.lineTo(x(hz), H); c.stroke();
c.fillStyle = "#7b8594"; c.fillText(hz >= 1000 ? hz / 1000 + "k" : hz, Math.min(x(hz) + 3, W - 22), H - 4);
}
for (const db of [0, -20, -40, -60]) {
c.strokeStyle = db ? "#2a303a" : "#46505e"; c.beginPath(); c.moveTo(0, y(db)); c.lineTo(W, y(db)); c.stroke();
c.fillStyle = "#7b8594"; c.fillText(db + " dB", 3, y(db) - 3);
}
if (!h) return;
c.strokeStyle = "#38bdf8"; c.lineWidth = 2; c.beginPath();
for (let px = 0; px <= W; px += 2) {
const py = y(Math.max(-80, firResponseDb(h, 20 * 1000 ** (px / W))));
px ? c.lineTo(px, py) : c.moveTo(px, py);
}
c.stroke();
}
function parseFirFile(text) {
const parts = text.split(/[\s,;]+/).filter(Boolean);
const values = parts.map(Number);
if (!values.length || values.some(v => !Number.isFinite(v))) throw new Error(t("This is not a list of FIR coefficients"));
return values;
}
async function importFir(d, kind, i) {
let f;
try { f = await openFile(".txt,.csv,text/plain,text/csv"); } catch (e) { return toast(trMsg(e.message)); }
if (!f) return;
let coeffs;
try { coeffs = parseFirFile(atob(f.b64)); } catch (e) { return toast(e.message); }
if (coeffs.length > firMax(kind)) return toast(t("Too many coefficients: {n}, at most {max} here", { n: coeffs.length, max: firMax(kind) }));
const name = cleanName(f.name.replace(/\.[^.]*$/, "")).trim().slice(0, 8);
if (!await askConfirm(t("Load FIR filter"), t("Send {n} coefficients from {file} to {ch}? This changes the sound immediately – keep the amplifiers low.",
{ n: coeffs.length, file: f.name, ch: chTitle(d, kind, i) }), t("Send"))) return;
S.firBusy = true; render();
try {
await api("POST", `/api/devices/${d.id}/fir`, { kind, idx: i, coeffs, name });
S.firCoef[firKey(d, kind, i)] = Float64Array.from(coeffs);
toast(t("FIR filter loaded"));
} catch (e) { toast(t("Error: ") + trMsg(e.message)); }
S.firBusy = false; S.firDraft = null; render();
}
function viewFir(d) {
if (S.firSel.idx >= chans(d, S.firSel.kind).length) S.firSel = { kind: "out", idx: 0 };
const { kind, idx } = S.firSel, ch = chans(d, kind)[idx], key = firKey(d, kind, idx), isOut = kind === "out";
const used = firUsed(d), loaded = S.firCoef[key];
const canvas = h("canvas", { class: "fircurve" });
const pick = (k, i) => { S.firSel = { kind: k, idx: i }; S.firDraft = null; render(); };
const chip = (k, i) => h("button", { class: "firch" + (k === kind && i === idx ? " on" : "") + (firTapsOf(chans(d, k)[i]) ? " used" : ""), "data-view-ok": "", onclick: () => pick(k, i) },
h("b", {}, chLabel(k, i)), h("small", {}, firTapsOf(chans(d, k)[i]) ? `${firTapsOf(chans(d, k)[i])} ${t("taps")}` : t("off")));
const picker = h("div", { class: "card wide" }, h("h3", {}, h("span", { class: "grow" }, t("FIR filters")),
h("span", { class: "firuse" + (used > 4096 ? " over" : "") }, t("{used} of 4096 taps in use", { used }))),
h("div", { class: "firmeter" }, h("span", { style: `width:${Math.min(100, used / 40.96)}%` })),
h("div", { class: "firchs" }, chans(d, "in").map((_, i) => chip("in", i)), h("span", { class: "firsep" }), chans(d, "out").map((_, i) => chip("out", i))));
let settings, preview = null, note = "";
if (isOut) {
if (!S.firDraft || S.firDraft.key !== key) S.firDraft = { key, ...ch.fir };
const f = S.firDraft, external = f.type === 4, changed = ["type", "window", "low", "high", "taps"].some(k => f[k] !== ch.fir[k]);
const others = used - firTapsOf(ch), needed = f.type ? firTapCount(f.taps) : 0, over = others + needed > 4096;
const set = (k, v) => { f[k] = v; render(); };
const select = (label, k, items) => h("label", {}, label, h("select", { onchange: e => set(k, +e.target.value) },
items.map((o, i) => h("option", { value: i, selected: f[k] === i }, o))));
const hz = (label, k) => h("label", {}, label, h("input", { type: "number", min: 150, max: 20000, value: f[k],
onchange: e => set(k, clamp(Math.round(+e.target.value) || f[k], 150, 20000)) }));
settings = h("div", { class: "card" }, h("h3", {}, chTitle(d, kind, idx)),
h("div", { class: "form firform" },
select(t("Type"), "type", FIR_TYPES()),
f.type && !external ? select(t("Window"), "window", FIR_WINDOWS) : null,
f.type && !external ? select(t("Taps"), "taps", Array.from({ length: 25 }, (_, i) => String(firTapCount(i)))) : null,
f.type === 2 || f.type === 3 ? hz(t("Low cut (Hz)"), "low") : null,
f.type === 1 || f.type === 3 ? hz(t("High cut (Hz)"), "high") : null),
f.type === 3 && f.low >= f.high ? h("p", { class: "err" }, t("The low cut must be below the high cut.")) : null,
over ? h("p", { class: "err" }, t("Not enough taps left: {free} free, this needs {need}.", { free: 4096 - others, need: needed })) : null,
f.type && !external && needed > 512 ? h("p", { class: "info" }, t("More than 512 taps add noticeable delay (over 10 ms at 1024).")) : null,
external
? [h("p", { class: "info" }, ch.fir.type === 4 && ch.fir.name ? t("Loaded: {name}", { name: ch.fir.name }) : t("Choose a file with up to {max} coefficients (txt or csv).", { max: 1024 })),
h("div", { class: "row" }, h("button", { class: "on", disabled: S.firBusy, onclick: () => importFir(d, kind, idx) }, S.firBusy ? t("Sending…") : t("Load file…")))]
: h("div", { class: "row lkactions" }, h("button", { class: "on", disabled: !changed || over || (f.type === 3 && f.low >= f.high), onclick: () => {
setParam(kind, idx, "fir", { type: f.type, window: f.window, low: f.low, high: f.high, taps: f.taps, name: ch.fir.name }); toast(t("FIR filter set")); render();
} }, t("Apply")), changed ? h("button", { onclick: () => { S.firDraft = null; render(); } }, t("Cancel")) : null));
if (external) { preview = loaded; note = loaded ? "" : t("The DSP can't send coefficients back, so the curve only appears after loading a file here."); }
else if (f.type) { preview = firDesign(f); note = t("Calculated by this app – the DSP calculates the filter itself, so details can differ."); }
else note = t("Filter is off.");
} else {
settings = h("div", { class: "card" }, h("h3", {}, chTitle(d, kind, idx)),
h("p", { class: "info" }, ch.fir.taps ? t("Loaded: {name} ({n} taps)", { name: ch.fir.name || "–", n: ch.fir.taps }) : t("Inputs only take filters from a file: up to {max} coefficients (txt or csv).", { max: 2048 })),
h("div", { class: "row lkactions" },
h("button", { class: "on", disabled: S.firBusy, onclick: () => importFir(d, kind, idx) }, S.firBusy ? t("Sending…") : t("Load file…")),
ch.fir.taps ? toggleBtn("Bypass", kind, idx, "fir.bypass", "bypass", () => render()) : null),
ch.fir.taps > 512 ? h("p", { class: "info" }, t("More than 512 taps add noticeable delay (over 10 ms at 1024).")) : null);
preview = ch.fir.bypass ? null : loaded;
note = ch.fir.bypass ? t("Filter is off.") : loaded ? "" : t("The DSP can't send coefficients back, so the curve only appears after loading a file here.");
}
requestAnimationFrame(() => drawFir(canvas, preview));
return h("div", { class: "cards" }, picker, settings,
h("div", { class: "card" }, h("h3", {}, t("Frequency response")), canvas, note ? h("p", { class: "info" }, note) : null));
}
// ------------------------------------------------------------------ filter response (for the PEQ curve)
const FS = 96000;
@@ -994,7 +1145,7 @@ function bessel(n, s) {
return b(s);
}
function xoverH(filter, f, high) {
if (!filter.slope) return [1, 0];
if (!filter || !filter.slope) return [1, 0];
const [kind, db] = SLOPES[filter.slope].split(" -"), n = +db / 6, x = f / freqHz(filter.freq);
const s = high ? [0, -1 / x] : [0, x]; // high pass: s -> 1/s
if (kind === "LK") { const b = butterworth(n / 2, s); return cmul(b, b); }
@@ -1204,7 +1355,7 @@ function peqCard(d, kind, idx) {
setMode(store.get("dsp.curve") || "mag");
const card = h("div", { class: "card wide" + (ch.peq_bypass ? " eq-off" : "") },
h("h3", {}, h("span", { class: "grow" }, t("Parametric EQ")), modeSeg,
toggleBtn("EQ Bypass", kind, idx, "peq_bypass", "small bypass", v => { card.classList.toggle("eq-off", v); renderBand(); redraw(); }),
d.fir ? null : toggleBtn("EQ Bypass", kind, idx, "peq_bypass", "small bypass", v => { card.classList.toggle("eq-off", v); renderBand(); redraw(); }),
h("button", { class: "small", onclick: async () => {
if (!await askConfirm(t("Reset EQ"), t("Set all PEQ bands of this channel to 0 dB and clear bypass?"), t("All flat"))) return;
chans(dev(), kind)[idx].peq.forEach((bb, i) => {
@@ -1294,11 +1445,24 @@ function viewChannel(d) {
const xo = (title, key) => h("div", { class: "xo" },
h("div", { class: "row" }, h("span", { class: "sub" }, title), paramSelect(k, i, key + ".slope", SLOPES, () => { redrawPeq(); render(); }, title)),
chans(d, k)[i][key].slope ? paramSlider(t("Frequency"), k, i, key + ".freq", "freq", redrawPeq) : h("p", { class: "info off" }, t("Off (bypass)")));
const xover = h("div", { class: "card" }, h("h3", {}, t("High- / low-pass")),
xo(t("High-pass"), "hp"), xo(t("Low-pass"), "lp"));
const xover = ch.hp ? h("div", { class: "card" }, h("h3", {}, t("High- / low-pass")),
xo(t("High-pass"), "hp"), xo(t("Low-pass"), "lp")) : null;
const cards = [basics, xover];
if (k === "in") {
const cards = [basics, xover].filter(Boolean);
const dynCard = (title, key, thresh) => h("div", { class: "card" }, h("h3", {}, title),
paramSlider("Threshold", k, i, key + ".threshold", thresh),
paramSlider("Ratio", k, i, key + ".ratio", "ratio"),
paramSlider("Attack", k, i, key + ".attack", "attack"),
paramSlider("Release", k, i, key + ".release", "release"),
paramSlider("Knee", k, i, key + ".knee", "knee"));
if (d.fir && k === "in") {
cards.push(h("div", { class: "card" }, h("h3", {}, "Noise Gate"),
paramSlider("Threshold", k, i, "gate.threshold", "gthresh"),
paramSlider("Attack", k, i, "gate.attack", "attack"),
paramSlider("Hold", k, i, "gate.hold", "hold"),
paramSlider("Release", k, i, "gate.release", "release")));
cards.push(dynCard(t("Compressor"), "comp", "thresh"), peqCard(d, k, i));
} else if (k === "in") {
cards.push(h("div", { class: "card" }, h("h3", {}, "Noise Gate"),
paramSlider("Threshold", k, i, "gate.threshold", "gthresh"),
paramSlider("Attack", k, i, "gate.attack", "attack"),
@@ -1307,7 +1471,7 @@ function viewChannel(d) {
cards.push(peqCard(d, k, i), geqCard(d, i));
} else {
cards.push(routingCard(d, i), peqCard(d, k, i));
cards.push(h("div", { class: "card" }, h("h3", {}, t("Compressor")),
if (ch.comp) cards.push(h("div", { class: "card" }, h("h3", {}, t("Compressor")),
paramSlider("Threshold", k, i, "comp.threshold", "thresh"),
paramSlider("Ratio", k, i, "comp.ratio", "ratio"),
paramSlider("Attack", k, i, "comp.attack", "attack"),
@@ -2271,7 +2435,7 @@ function render() {
: d.status === "locked" ? h("div", {}, h("p", {}, t("This DSP is locked with a code.")),
h("button", { class: "on", onclick: () => unlockDialog(d) }, t("Enter code")))
: S.demo.enabled && !d.demo ? t("Disconnected while demo mode is on") : t("Not connected."));
else content = ({ mixer: viewMixer, channel: viewChannel, routing: viewRouting, link: viewLink, limiter: viewLimiter, test: viewTest }[S.view] || viewMixer)(d);
else content = ({ mixer: viewMixer, channel: viewChannel, routing: viewRouting, link: viewLink, fir: d.fir ? viewFir : viewMixer, limiter: viewLimiter, test: viewTest }[S.view] || viewMixer)(d);
main.replaceChildren(...[content].flat().filter(Boolean));
main.querySelectorAll(H_SCROLL).forEach((e, i) => { if (xs[i]) e.scrollLeft = xs[i]; });
window.scrollTo(0, y);
+35
View File
@@ -517,9 +517,44 @@ const DE = {
"{names} joins the group and takes over its settings (name{routing} stays).": "{names} kommt in die Gruppe und übernimmt ihre Einstellungen – außer Name{routing}.",
"{names} leaves the group and keeps its current settings.": "{names} verlässt die Gruppe und behält seine aktuellen Einstellungen.",
"Beta: this model has not been tested on a real device yet. Keep the amplifiers off for the first test.": "Beta: Dieses Modell wurde noch nicht an einem echten Gerät getestet. Beim ersten Test die Endstufen ausgeschaltet lassen.",
"Band-pass": "Bandpass",
"From file": "Aus Datei",
"Bypass": "Bypass",
"This is not a list of FIR coefficients": "Das ist keine Liste von FIR-Koeffizienten",
"Too many coefficients: {n}, at most {max} here": "Zu viele Koeffizienten: {n}, hier höchstens {max}",
"Load FIR filter": "FIR-Filter laden",
"Send {n} coefficients from {file} to {ch}? This changes the sound immediately – keep the amplifiers low.": "{n} Koeffizienten aus {file} an {ch} senden? Das ändert den Klang sofort – Endstufen leise halten.",
"Send": "Senden",
"FIR filter loaded": "FIR-Filter geladen",
"taps": "Taps",
"off": "aus",
"FIR filters": "FIR-Filter",
"{used} of 4096 taps in use": "{used} von 4096 Taps belegt",
"Window": "Fenster",
"Taps": "Taps",
"Low cut (Hz)": "Untere Grenze (Hz)",
"High cut (Hz)": "Obere Grenze (Hz)",
"The low cut must be below the high cut.": "Die untere Grenze muss unter der oberen liegen.",
"Not enough taps left: {free} free, this needs {need}.": "Nicht genug Taps frei: {free} frei, nötig sind {need}.",
"More than 512 taps add noticeable delay (over 10 ms at 1024).": "Mehr als 512 Taps bringen spürbare Verzögerung (über 10 ms bei 1024).",
"Loaded: {name}": "Geladen: {name}",
"Choose a file with up to {max} coefficients (txt or csv).": "Datei mit bis zu {max} Koeffizienten wählen (txt oder csv).",
"Sending…": "Wird gesendet…",
"Load file…": "Datei laden…",
"FIR filter set": "FIR-Filter gesetzt",
"The DSP can't send coefficients back, so the curve only appears after loading a file here.": "Der DSP kann Koeffizienten nicht zurücksenden, die Kurve erscheint daher erst nach dem Laden einer Datei hier.",
"Calculated by this app – the DSP calculates the filter itself, so details can differ.": "Von dieser App berechnet – der DSP berechnet den Filter selbst, Details können abweichen.",
"Filter is off.": "Filter ist aus.",
"Loaded: {name} ({n} taps)": "Geladen: {name} ({n} Taps)",
"Inputs only take filters from a file: up to {max} coefficients (txt or csv).": "Eingänge nehmen nur Filter aus einer Datei: bis zu {max} Koeffizienten (txt oder csv).",
"Frequency response": "Frequenzgang",
"Out of FIR taps: all channels together have 4096": "Keine FIR-Taps mehr frei: alle Kanäle zusammen haben 4096",
"Not valid FIR coefficients": "Keine gültigen FIR-Koeffizienten",
};
const DE_PATTERNS = [
[/^Too many FIR coefficients: at most (\d+) here$/, "Zu viele FIR-Koeffizienten: hier höchstens $1"],
[/^The DSP did not answer (\d+) frames$/, "Der DSP hat auf $1 Datenpakete nicht geantwortet"],
[/^Port (\d+) is already in use – please choose another port$/, "Port $1 ist schon belegt – bitte einen anderen Port wählen"],
[/^Port (\d+) is not available \((.*)\)$/, "Port $1 ist nicht verfügbar ($2)"],
[/^Cannot open USB device \(error (.*)\)$/, "USB-Gerät lässt sich nicht öffnen (Fehler $1)"],
+1
View File
@@ -24,6 +24,7 @@
<button data-view="channel"><svg viewBox="0 0 24 24"><path d="M2 14c3 0 3-7 6-7s3 10 6 10 3-6 6-6h2"/></svg><span data-t="Channel">Channel</span></button>
<button data-view="routing"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h16M8 3v18M16 3v18"/><circle cx="8" cy="6" r="2.2" class="f"/><circle cx="16" cy="12" r="2.2" class="f"/><circle cx="8" cy="18" r="2.2" class="f"/></svg><span>Routing</span></button>
<button data-view="link"><svg viewBox="0 0 24 24"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/></svg><span data-t="Channel settings">Channel settings</span><span class="short" data-t="Channels">Channels</span></button>
<button data-view="fir" hidden><svg viewBox="0 0 24 24"><path d="M2 12h3l2-7 3 14 3-11 2 6 2-3 1 1h4"/></svg><span>FIR</span></button>
<button data-view="limiter"><svg viewBox="0 0 24 24"><path d="M2 7h20" stroke-dasharray="2.5 2.5"/><path d="M2 14c2 0 3-7 5-7h3c2 0 3 11 6 11s3-5 6-5"/></svg><span>Limiter</span></button>
<button data-view="soundfield"><svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M8 7l-2 2 2 2M16 7l2 2-2 2"/><path d="M7 15.5a7 7 0 0 1 10 0" stroke-dasharray="2 2"/><circle cx="12" cy="18" r="1.2" class="f"/></svg><span>SoundField</span><span class="short">Field</span></button>
<button data-view="test"><svg viewBox="0 0 24 24"><path d="M4 9v6h4l5 4V5L8 9z"/><path d="M16.5 8.5a5 5 0 0 1 0 7M19 6a8.5 8.5 0 0 1 0 12"/></svg><span data-t="Audio test">Audio test</span><span class="short" data-t="Test">Test</span></button>
+15
View File
@@ -747,3 +747,18 @@ input[type=range].haslim::-moz-range-track {
/* ---- note on beta models in the add-device form */
.betanote { margin: 0; padding: 8px 10px; border-radius: 8px; color: var(--text); background: #f59e0b1f; border: 1px solid #f59e0b66; }
.betanote[hidden] { display: none; }
/* ---- FIR tab */
#viewtabs button[hidden] { display: none; }
.firuse { font-size: 12px; font-weight: 600; color: var(--dim); text-transform: none; letter-spacing: 0; }
.firuse.over { color: #f87171; }
.firmeter { height: 6px; margin: 2px 0 12px; border-radius: 3px; background: var(--line); overflow: hidden; }
.firmeter span { display: block; height: 100%; background: var(--accent); }
.firchs { display: flex; flex-wrap: wrap; gap: 6px; }
.firsep { width: 1px; margin: 0 4px; background: var(--line); }
.firch { flex-direction: column; gap: 0; min-width: 66px; min-height: 48px; padding: 4px 8px; }
.firch small { color: var(--dim); font-size: 11px; font-weight: 400; }
.firch.used small { color: var(--accent); }
.firch.on { background: var(--accent2); border-color: var(--accent); color: #fff; }
.firch.on small { color: #dbeafe; }
.firform { margin-bottom: 8px; }
canvas.fircurve { display: block; width: 100%; height: 240px; background: var(--bg2); border-radius: 8px; }
+30 -2
View File
@@ -35,7 +35,7 @@ def test_layout_matches_devices():
def test_state_roundtrip():
for m in P.MODELS.values():
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
@@ -140,7 +140,7 @@ def test_device_lock():
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 P.MODELS.values():
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}
@@ -178,6 +178,34 @@ def test_beta_models():
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"
if __name__ == "__main__":
for name, fn in list(globals().items()):
if name.startswith("test_"):