From 4a6eb2f513c0f09c473d6de89318781924d6f4fd Mon Sep 17 00:00:00 2001 From: Givou Date: Mon, 2 Nov 2026 22:18:09 +0100 Subject: [PATCH] DJ Brake only shows the limiter acting; presets without a look start empty The distance to the limiter, its bar, the warn-earlier slider and the learning are gone: the page follows the DSP's limiter bits, with one second hold. Left out limiters stay. A preset without colours and group names of its own no longer inherits the ones from the preset before. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 11 ++-- README.md | 7 +-- dsp/device.py | 25 ++++++-- server.py | 113 ++++++--------------------------- static/app.js | 24 +------- static/djbrake.html | 88 ++++++-------------------- static/i18n.js | 7 +-- static/style.css | 2 - tests/test_protocol.py | 137 +++++++++++++---------------------------- 9 files changed, 110 insertions(+), 304 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index abfc36b..4233f0a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,12 +58,12 @@ pi_writer.py → pi_image.py (cloud-init SD card, installs server.py as a system * **Sound Lab / REW** (`static/rew.js`, handbooks in `static/docs.js`, `rew_call` in `server.py`) – the server talks to REW's API on `127.0.0.1:4735`, which only answers on REW's own computer; so Sound Lab is only in the desktop apps (`S.isApp`, the server refuses `/api/rew/` otherwise). Only checked against a fake server built from its OpenAPI spec. Pictures of the handbooks: `static/docimg/..jpg`, one per language, only ever from this app itself. -* **DJ Brake** (`static/djbrake.html`, `App.dj_stream`) – the only page without a login, off by default. It may only ever learn - `{on, ready, room, avg, hint}` from `/djbrake/state`: never add device data or controls there. `dj_margin` moves its limit - down on purpose, so the page must never reveal it. On its own on purpose, without `app.js`. +* **DJ Brake** (`static/djbrake.html`, `App.dj_note`, `App.dj_state`) – the only page without a login, off by default. It may only ever + learn `{on, ready, hint}` from `/djbrake/state`: never add device data or controls there. On its own on purpose, without `app.js`. + It only follows the DSP's limiter bits. A distance to the limiter was tried and dropped: see the measurement in `PROTOCOL.md`. Its settings sit in the access section; in the apps it needs remote access, since the app itself only listens on 127.0.0.1. * **Preset looks** – `Device.looks` keeps `colors`/`linknames` per preset name; `sync_look` swaps them whenever a read of the DSP - shows another name (the DSP has no preset IDs: same name = same look). Preset files carry them as `look`. + shows another name (the DSP has no preset IDs: same name = same look), a preset without a look starts empty. Preset files carry them as `look`. * **Reset** (`App.reset_config`, `POST /api/reset`, app window only, never remote) – stops all devices before anything else and sends them nothing, then defaults from a fresh `App`. Refused during an audio test or mute all, because the DSP would stay changed. Keeps `config.before-reset.json`. * **Network search** – `App.scan_network` probes the local /24 networks on TCP 9761 (handshake + device info), @@ -145,9 +145,6 @@ Not verified yet – ask for a log (`python server.py -v`) from real hardware be only; whether the generator is pre or post input gain is unknown (the app therefore only lowers the outputs) * Device lock (`0x2C` byte 5, `0x2D`, `0x2F`, `0x11`) – implemented from the control software's behaviour and tested against the simulator only; no command to remove a lock is known -* DJ Brake distance to the limiter: threshold minus output meter minus an offset: `DJ_METER_OFFSET` (measured once with - `tools/dsp_measure.py`, DSP 204 only, one output and one piece of music, see `PROTOCOL.md`), then what real hits show (`dj_cal`). Other - models start at 0 until measured. Only the light, from the limiter-active bits, is certain * Limiter calculator reference level (assumes limiter 0 dB = 0 dBu at the output; adjustable per device) * Pi Writer: raw write to a real SD card and first boot on a real Pi (only tested with an image file) diff --git a/README.md b/README.md index 9cfc080..1d55ba4 100644 --- a/README.md +++ b/README.md @@ -34,11 +34,8 @@ Control both devices at the same time from your phone, tablet or computer – ov * **Read-only switch** – on phones and tablets the web UI starts read-only; a small switch at the top allows changes * **Sound Lab** (Windows and macOS apps) – together with REW (Room EQ Wizard): take the filters of a measurement or a REW filter file onto a channel, compare before applying, send a channel's curve or filters back to REW. Handbook with real cases here and in SoundField -* **DJ Brake** – optional page `/djbrake` for a tablet at the DJ booth: a big red light while a limiter is working and a horizontal - bar with the distance to the limiter. You can leave out limiters (a monitor, say) and make it warn a few dB before - the real limiter. The bar shows the average of the last seconds, a mark the recent peaks, and the page learns from real limiter - hits where the limiter sits on the meter. Needs no PIN and shows - nothing else +* **DJ Brake** – optional page `/djbrake` for a tablet at the DJ booth: a big red light when a limiter acts, on for one more second + afterwards. You can leave out limiters (a monitor, say). Needs no PIN and shows nothing else * **Preset looks** – colours and link group names belong to the preset (by its name) and also travel in preset files * **Mixer** – faders, mute and live meters for all inputs and outputs, limiter LED on every output (status read from the DSP) diff --git a/dsp/device.py b/dsp/device.py index f95971a..1861c2c 100644 --- a/dsp/device.py +++ b/dsp/device.py @@ -45,6 +45,8 @@ class Device: self.looks: dict[str, dict] = looks or {} self.look_name = look_name self.look_dirty = False + self.recalled = "" # the preset last loaded through the app, as listed by the DSP ... + self.recalled_image = None # ... and the name its memory image showed right after self.maxgain: dict[str, int] = maxgain or {} # software limit of the gain fader per channel (raw), e.g. {"out0": 260} # audio test: output gains from before the test (restored when it ends) and the test fader level self.test_saved: list[int] | None = test_saved if isinstance(test_saved, list) else None @@ -261,12 +263,23 @@ class Device: self.look_dirty = True def sync_look(self): - """After reading the DSP: another preset brings its own look. One not seen yet starts with the current one.""" - name = (self.state or {}).get("preset_name", "").strip() - if self.state is None or (name == self.look_name and name in self.looks): + """After reading the DSP: another preset brings its own look, one that has none starts without. + Only the very first preset ever seen keeps what is there: those are the settings from before looks existed.""" + if self.state is None: return - look = self.looks.get(name) - if look: + name = self.state.get("preset_name", "").strip() + # that the memory image shows the new name after loading a preset is not verified on hardware: trust the list + if self.recalled: + if self.recalled_image is None: + self.recalled_image = name + if name == self.recalled_image: + name = self.recalled + else: + self.recalled = "" + if name == self.look_name and name in self.looks: + return + if self.looks: + look = self.looks.get(name, {"colors": {}, "linknames": {}}) self.colors, self.linknames = dict(look["colors"]), dict(look["linknames"]) self.look_name = name self.remember_look() @@ -274,6 +287,7 @@ class Device: async def recall_preset(self, index: int): await self._request(P.CMD_PRESET_RECALL, bytes([index + 1]), timeout=2.0) await asyncio.sleep(0.3) + self.recalled, self.recalled_image = (self.presets[index].strip() if index < len(self.presets) else ""), None await self._load_config() self._emit_state() @@ -286,6 +300,7 @@ class Device: if self.state: self.state["preset_name"] = name self.look_name = name.strip() # also when overwriting: what is stored now is what we see now + self.recalled = "" self.remember_look() self._emit_state() diff --git a/server.py b/server.py index 6d9eee9..5893f41 100644 --- a/server.py +++ b/server.py @@ -213,20 +213,7 @@ def rew_send_curve(body: dict): "magnitude": rew_floats(mag), "phase": rew_floats(phase)}) -DJ_HOLD = 1.5 # s the light of /djbrake stays on after a limiter acted, so it doesn't flicker with the music -DJ_PEAK_HOLD = 1.5 # s the peak marker stays, then it falls ... -DJ_PEAK_FALL = 3.0 # ... this many dB/s: the display follows the music, not every single beat -DJ_AVG_TAU = 3.0 # s time constant of the average level -# dB between the limiter threshold and the output meter when a limiter starts, until real hits say otherwise. Measured with -# tools/dsp_measure.py: one DSP 204 (V0104P), one output, one piece of music: 25.1 to 27.7 in five rounds, with and without -# -6 dB gain. It holds a share of the music's peaks the meter doesn't catch, so other music can differ by a few dB. -DJ_METER_OFFSET = {"204": 26.0} -DJ_LEARN_QUIET = 6.0 # s after a jump of a threshold the limiter flag teaches nothing: it was seen on for 4 s at +20 dB - - -def clean_dj_margin(value) -> int: - """dB the page puts its limit below the real one, 0-12.""" - return int(max(0, min(12, value))) if type(value) in (int, float) else 0 +DJ_HOLD = 1.0 # s the light of /djbrake stays on after a limiter acted def clean_dj_ignore(data) -> dict: @@ -329,15 +316,10 @@ class App: self.dashboard: dict | None = None self.djbrake = False # page /djbrake for the DJ: without PIN, shows only whether a limiter acts self.dj_ignore: dict = {} # device id -> outputs not watched - self.dj_margin = 0 # the page warns this many dB before the real limiter, and never says so self.dj_hint = True # short text on the page: the limiter is not the goal self.dj_hint_en = True # that text always in English, else in the language of the browser self.dj_hit = 0.0 # when a limiter was last seen acting - self.dj_rooms: dict = {} # device id -> dB left to the nearest watched limiter, False = nothing watched - self.dj_avgs: dict = {} # the same for the average level - self.dj_env: dict = {} # "device:output" -> peak and average of the level - self.dj_cal: dict = {} # device id -> dB the limiters sit below their threshold on the meter, learned from hits - self.dj_cal_saved = 0.0 + self.dj_ready: dict = {} # device id -> has it an output that is watched self.dj_streams = 0 self.logo = "" # desktop app: its own window logs in with a one-time token, other devices need the PIN @@ -389,9 +371,6 @@ class App: self.dashboard = clean_dashboard(cfg.get("dashboard")) self.djbrake = bool(cfg.get("djbrake")) self.dj_ignore = clean_dj_ignore(cfg.get("dj_ignore")) - self.dj_margin = clean_dj_margin(cfg.get("dj_margin")) - self.dj_cal = {str(k)[:64]: float(v) for k, v in (cfg.get("dj_cal") if isinstance(cfg.get("dj_cal"), dict) else {}).items() - if type(v) in (int, float) and ":" not in str(k)} self.dj_hint = bool(cfg.get("dj_hint", True)) self.dj_hint_en = bool(cfg.get("dj_hint_en", True)) if "logo" in cfg: @@ -410,7 +389,7 @@ class App: return {"format": CONFIG_FORMAT, "version": 1, "exported": time.strftime("%Y-%m-%dT%H:%M:%S"), "devices": [d.config() for d in self.real_devices()], "auth": self.auth, "limiter": self.limiter, "remote": self.remote, "soundfield": self.soundfield, "logo": self.logo, - "dashboard": self.dashboard, "djbrake": self.djbrake, "dj_ignore": self.dj_ignore, "dj_hint": self.dj_hint, "dj_hint_en": self.dj_hint_en, "dj_margin": self.dj_margin, "dj_cal": self.dj_cal} + "dashboard": self.dashboard, "djbrake": self.djbrake, "dj_ignore": self.dj_ignore, "dj_hint": self.dj_hint, "dj_hint_en": self.dj_hint_en} async def reset_config(self): """Back to a fresh app. Only the app: the DSPs get disconnected first and receive nothing.""" @@ -506,7 +485,7 @@ class App: sessions = {k: v for k, v in self.sessions.items() if k not in self.app_sessions} cfg = {"devices": [d.config() for d in self.real_devices()], "auth": self.auth, "sessions": sessions, "limiter": self.limiter, "remote": self.remote, "locked": self.locked, "lock_dash": self.lock_dash, - "soundfield": self.soundfield, "logo": self.logo, "dashboard": self.dashboard, "djbrake": self.djbrake, "dj_ignore": self.dj_ignore, "dj_hint": self.dj_hint, "dj_hint_en": self.dj_hint_en, "dj_margin": self.dj_margin, "dj_cal": self.dj_cal, + "soundfield": self.soundfield, "logo": self.logo, "dashboard": self.dashboard, "djbrake": self.djbrake, "dj_ignore": self.dj_ignore, "dj_hint": self.dj_hint, "dj_hint_en": self.dj_hint_en, "mute_all": {"active": self.mute_all["active"], "restore": {k: v for k, v in self.mute_all["restore"].items() if k != "demo"}}} if self.lang: @@ -963,64 +942,25 @@ class App: # ------------------------------------------------------------ events - def dj_offset(self, dev) -> float: - """Learned from this DSP's hits, else what was measured on this model. The simulator has no such offset.""" - if dev.id in self.dj_cal: - return self.dj_cal[dev.id] - real = "SIM" not in getattr(dev, "info", "") and not getattr(dev, "demo", False) - return DJ_METER_OFFSET.get(getattr(dev, "model_name", ""), 0.0) if real else 0.0 - - def dj_track(self, dev, key: str, level: float, limit: bool, threshold: int, now: float) -> tuple: - """One meter reading of a watched output: (dB left by the peak, dB left by the average, warn now).""" - e = self.dj_env.setdefault(key, {"peak": -120.0, "until": 0.0, "pow": 0.0, "t": now}) - dt = min(now - e["t"], 1.0) - e["t"] = now - db = 20 * math.log10(level) if level > 0 else -120.0 - if db >= e["peak"]: - e["peak"], e["until"] = db, now + DJ_PEAK_HOLD - elif now > e["until"]: - e["peak"] = max(db, e["peak"] - DJ_PEAK_FALL * dt) - e["pow"] += (level * level - e["pow"]) * (1 - math.exp(-dt / DJ_AVG_TAU)) - thr = P.threshold_to_db(threshold) - # the moment a limiter starts is where it really sits on the meter. Later the level is what the limiter - # left of it. One DSP has one meter, so this counts for all its outputs - # only a limiter that starts by itself counts: not after a threshold jumped, up or down, and not - # while it flickers on and off in the middle of limiting - if thr > e.get("thr", thr) or thr < e.get("thr", thr) - 2: - e["jumped"] = now - e["thr"] = thr - if limit and now - e.get("last_on", -1e9) > 3 and now - e.get("jumped", -1e9) > DJ_LEARN_QUIET and e["peak"] > -70: - seen = max(-6.0, min(40.0, thr - e["peak"])) - known = self.dj_offset(dev) - self.dj_cal[dev.id] = (known * 3 + seen) / 4 if known or dev.id in self.dj_cal else seen - if limit: - e["last_on"] = now - top = thr - self.dj_offset(dev) - self.dj_margin - left = 0.0 if limit else max(0.0, top - e["peak"]) if e["peak"] > -70 else None - mean = max(0.0, top - 10 * math.log10(e["pow"])) if e["pow"] > 1e-7 else None - return left, mean, limit or bool(self.dj_margin and db >= top) - def dj_note(self, ev: dict, now: float | None = None): """Keeps the state of the /djbrake page. A muted output is not watched: nobody hears it.""" dev = self.devices.get(ev["device"]) if not dev or not dev.state: return now = time.monotonic() if now is None else now - room, avg, ignore = False, None, self.dj_ignore.get(dev.id, ()) - for i, (level, limit) in enumerate(zip(ev["out"], ev["limit"])): - ch, key = dev.state["outputs"][i], f"{dev.id}:{i}" - if i in ignore or ch["mute"]: - self.dj_env.pop(key, None) - continue - left, mean, warn = self.dj_track(dev, key, level, limit, ch["limit"]["threshold"], now) - if warn: - self.dj_hit = now - room = left if room is False or room is None else room if left is None else min(room, left) - avg = mean if avg is None else avg if mean is None else min(avg, mean) - self.dj_rooms[dev.id], self.dj_avgs[dev.id] = room, avg - if self.dj_cal and now - self.dj_cal_saved > 60: # an SD card is not for writing with every beat - self.dj_cal_saved = now - self.save() + watched, ignore = False, self.dj_ignore.get(dev.id, ()) + for i, limit in enumerate(ev["limit"]): + if i not in ignore and not dev.state["outputs"][i]["mute"]: + watched = True + if limit: + self.dj_hit = now + self.dj_ready[dev.id] = watched + + def dj_state(self, now: float) -> dict: + """All /djbrake may know, without a login. Nothing else leaves here.""" + return {"on": now - self.dj_hit < DJ_HOLD, + "ready": any(self.dj_ready.get(d.id) for d in self.devices.values() if d.status == "online"), + "hint": ("en" if self.dj_hint_en else "auto") if self.dj_hint else None} def broadcast(self, ev: dict): if ev["type"] == "meters": @@ -1057,17 +997,12 @@ class App: self.djbrake = bool(body["enabled"]) if "ignore" in body: self.dj_ignore = clean_dj_ignore(body["ignore"]) - if body.get("relearn"): - self.dj_cal = {} - if "margin" in body: - self.dj_margin = clean_dj_margin(body["margin"]) if "hint" in body: self.dj_hint = bool(body["hint"]) if "hint_en" in body: self.dj_hint_en = bool(body["hint_en"]) self.save() - ans = {"enabled": self.djbrake, "ignore": self.dj_ignore, "hint": self.dj_hint, "hint_en": self.dj_hint_en, - "margin": self.dj_margin} + ans = {"enabled": self.djbrake, "ignore": self.dj_ignore, "hint": self.dj_hint, "hint_en": self.dj_hint_en} self.broadcast({"type": "djbrake", **ans}) return ans if path == "/api/dashboard" and method == "PUT": @@ -1423,7 +1358,6 @@ class App: await self.respond(writer, 200, f.read_bytes(), ctype) async def dj_stream(self, writer): - """All /djbrake may know, without a login: is a limiter acting and how far away is it. Nothing else leaves here.""" if not self.djbrake or self.dj_streams >= 20: await self.respond(writer, 404, b"not found", "text/plain") return @@ -1434,14 +1368,7 @@ class App: try: while self.djbrake: now = time.monotonic() - online = [d.id for d in self.devices.values() if d.status == "online"] - rooms = [r for r in (self.dj_rooms.get(i, False) for i in online) if r is not False] - known = [r for r in rooms if r is not None] - avgs = [r for r in (self.dj_avgs.get(i) for i in online) if r is not None] - state = {"on": now - self.dj_hit < DJ_HOLD, "ready": bool(rooms), - "room": round(min(known) * 2) / 2 if known else None, - "avg": round(min(avgs)) if avgs else None, - "hint": ("en" if self.dj_hint_en else "auto") if self.dj_hint else None} + state = self.dj_state(now) if state != last: writer.write(f"data: {json.dumps(state)}\n\n".encode()) last, idle = state, 0.0 @@ -1462,7 +1389,7 @@ class App: try: hello = {"type": "hello", "devices": [d.snapshot() for d in self.devices.values()], "limiter": self.limiter, "demo": self.demo_info(), "muteall": self.mute_all_info(), "soundfield": self.soundfield, "logo": self.logo, - "dashboard": self.dashboard, "djbrake": self.djbrake, "dj_ignore": self.dj_ignore, "dj_hint": self.dj_hint, "dj_hint_en": self.dj_hint_en, "dj_margin": self.dj_margin} + "dashboard": self.dashboard, "djbrake": self.djbrake, "dj_ignore": self.dj_ignore, "dj_hint": self.dj_hint, "dj_hint_en": self.dj_hint_en} writer.write(f"data: {json.dumps(hello)}\n\n".encode()) await writer.drain() while True: diff --git a/static/app.js b/static/app.js index 767d2a5..75109b5 100644 --- a/static/app.js +++ b/static/app.js @@ -2422,26 +2422,8 @@ function djBrakeCard() { try { await navigator.clipboard.writeText(url); toast(t("Address copied")); } catch { toast(url); } } }, t("Copy")))) : null, S.djbrake && reachable ? djLimiters() : null, - S.djbrake && reachable ? djMarginOption() : null, S.djbrake && reachable ? djHintOptions() : null, - S.djbrake && reachable ? h("p", { class: "info" }, t("Anyone in your network can open it without a PIN. It shows only the light and the distance to the limiter and changes nothing.")) : null); -} - -function djMarginOption() { - const val = h("b", {}, `${S.djMargin} dB`); - const input = h("input", { type: "range", min: 0, max: 12, step: 1, value: S.djMargin, "aria-label": t("Warn earlier"), - oninput: () => { val.textContent = `${input.value} dB`; }, - onchange: async () => { - try { S.djMargin = (await api("PUT", "/api/djbrake", { margin: +input.value })).margin; } - catch (e) { toast(t("Error: ") + trMsg(e.message)); render(); } - } }); - return h("div", { class: "djlim" }, h("div", { class: "row" }, h("b", { class: "grow" }, t("Warn earlier")), val), input, - h("p", { class: "info" }, t("The page acts as if the limiter came this much earlier, so the DJ stays below the real one. The limiter itself does not change and the page does not show this setting.")), - h("p", { class: "info" }, t("With every real limiter hit the page learns where the limiter sits on the meter, so the distance gets more accurate.")), - h("button", { class: "small", onclick: async () => { - try { await api("PUT", "/api/djbrake", { relearn: true }); toast(t("Learned limiter levels forgotten")); } - catch (e) { toast(t("Error: ") + trMsg(e.message)); } - } }, t("Forget learned levels"))); + S.djbrake && reachable ? h("p", { class: "info" }, t("Anyone in your network can open it without a PIN. It shows only the light and changes nothing.")) : null); } function djHintOptions() { @@ -2726,7 +2708,7 @@ function connectEvents() { if (ev.muteall) { S.muteAll = ev.muteall.active; showMuteAll(); } if (ev.soundfield) S.sf = ev.soundfield; if ("dashboard" in ev) S.dash = ev.dashboard && ev.dashboard.modules; - S.djbrake = !!ev.djbrake; S.djIgnore = ev.dj_ignore || {}; S.djHint = ev.dj_hint !== false; S.djHintEn = ev.dj_hint_en !== false; S.djMargin = ev.dj_margin || 0; + S.djbrake = !!ev.djbrake; S.djIgnore = ev.dj_ignore || {}; S.djHint = ev.dj_hint !== false; S.djHintEn = ev.dj_hint_en !== false; if ("logo" in ev) { S.logo = ev.logo; showLogo(); } if (S.demo.enabled && S.devices.demo && !S.devices[S.cur]?.demo) S.cur = "demo"; S.order.forEach(id => maybeAskUnlock(S.devices[id])); @@ -2764,7 +2746,7 @@ function connectEvents() { case "reset": appWasReset(); break; case "djbrake": - S.djbrake = ev.enabled; S.djIgnore = ev.ignore; S.djHint = ev.hint; S.djHintEn = ev.hint_en; S.djMargin = ev.margin; if (S.settings && !S.busy) render(); break; + S.djbrake = ev.enabled; S.djIgnore = ev.ignore; S.djHint = ev.hint; S.djHintEn = ev.hint_en; if (S.settings && !S.busy) render(); break; case "logo": S.logo = ev.data; showLogo(); if (S.settings) render(); break; case "muteall": diff --git a/static/djbrake.html b/static/djbrake.html index d4e2e96..2c3b0f7 100644 --- a/static/djbrake.html +++ b/static/djbrake.html @@ -10,45 +10,26 @@