DJ Brake: use the offset measured on a real DSP 204

Measured: limiter threshold minus output meter is about 26 dB when the limiter
starts (25.1 to 27.7, one DSP 204, one output, one piece of music), and the meter
is after the output gain. So the distance is right before the first hit.
The limiter flag also stayed on after raising a threshold, which would have
taught a false value: only limiters starting by themselves teach now.
The measuring tool no longer draws conclusions the data doesn't carry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
GivouandClaude Opus 5.5 committed 2026-11-02 21:54:29 +01:00
1 parent 4cd771eb5c
commit 63b3c17fb7
5 files changed
+106 -24

No files matched your search

+3 -2
View File
@@ -145,8 +145,9 @@ 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) 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 * 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 tested against the simulator only; no command to remove a lock is known
* DJ Brake distance to the limiter: output meter dB minus threshold dB, corrected by what real limiter hits show (`dj_cal`); * DJ Brake distance to the limiter: threshold minus output meter minus an offset: `DJ_METER_OFFSET` (measured once with
only the light, from the limiter-active bits, is certain `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) * 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) * Pi Writer: raw write to a real SD card and first boot on a real Pi (only tested with an image file)
+7 -2
View File
@@ -56,10 +56,15 @@ All 16-bit words are little endian.
* Level = float32 from the bytes `00 b2 b0 b1` (little endian) → linear, dB = 20·log10. * Level = float32 from the bytes `00 b2 b0 b1` (little endian) → linear, dB = 20·log10.
* Positions: 0–3 = In A–D, 4–11 = Out 1–8. The 204 uses 0, 1 and 4–7. * Positions: 0–3 = In A–D, 4–11 = Out 1–8. The 204 uses 0, 1 and 4–7.
* The level is measured before mute. * The level is measured before mute and after the output gain (one DSP 204: -6 dB gain moved it by -6.3 dB against the input).
* The level is far below the limiter threshold's scale. One DSP 204 (V0104P), one output, one piece of music: when the limiter
starts, threshold minus the loudest level read is 26 dB (25.1 to 27.7 in five rounds, the same with -6 dB gain). How much of
that is a fixed offset and how much are peaks between the readings is not separated. Whether the level is before or after
the limiter is open: 6 dB below the start of limiting it fell only 0.9 dB against the input.
* **Limiter active**: the status bytes are a bit mask of the outputs (bit 0 = Out 1). Measured on a DSP 204: * **Limiter active**: the status bytes are a bit mask of the outputs (bit 0 = Out 1). Measured on a DSP 204:
`00 03` while Out 1+2 limit, `00 0C` for Out 3+4. That Out 5–8 of the 408 continue in the same 16-bit value `00 03` while Out 1+2 limit, `00 0C` for Out 3+4. That Out 5–8 of the 408 continue in the same 16-bit value
is *assumed*. is *assumed*. The bit does not simply follow the level: it stayed on for 4 s, in two of six cases also after the threshold had
been raised to +20 dB, and went off within 0.2 s in others. Why is not known.
## Channel numbers ## Channel numbers
+26 -8
View File
@@ -217,6 +217,11 @@ DJ_HOLD = 1.5 # s the light of /djbrake stays on after a limiter acted, so it d
DJ_PEAK_HOLD = 1.5 # s the peak marker stays, then it falls ... 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_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 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: def clean_dj_margin(value) -> int:
@@ -958,7 +963,14 @@ class App:
# ------------------------------------------------------------ events # ------------------------------------------------------------ events
def dj_track(self, key: str, level: float, limit: bool, threshold: int, now: float) -> tuple: 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).""" """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}) e = self.dj_env.setdefault(key, {"peak": -120.0, "until": 0.0, "pow": 0.0, "t": now})
dt = min(now - e["t"], 1.0) dt = min(now - e["t"], 1.0)
@@ -972,12 +984,18 @@ class App:
thr = P.threshold_to_db(threshold) 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 # 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 # left of it. One DSP has one meter, so this counts for all its outputs
dev_id = key.rsplit(":", 1)[0] # only a limiter that starts by itself counts: not after a threshold jumped, up or down, and not
if limit and not e.get("acting") and e["peak"] > -70: # while it flickers on and off in the middle of limiting
seen = max(-6.0, min(30.0, thr - e["peak"])) if thr > e.get("thr", thr) or thr < e.get("thr", thr) - 2:
self.dj_cal[dev_id] = (self.dj_cal[dev_id] + seen) / 2 if dev_id in self.dj_cal else seen e["jumped"] = now
e["acting"] = limit e["thr"] = thr
top = thr - self.dj_cal.get(dev_id, 0.0) - self.dj_margin 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 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 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) return left, mean, limit or bool(self.dj_margin and db >= top)
@@ -994,7 +1012,7 @@ class App:
if i in ignore or ch["mute"]: if i in ignore or ch["mute"]:
self.dj_env.pop(key, None) self.dj_env.pop(key, None)
continue continue
left, mean, warn = self.dj_track(key, level, limit, ch["limit"]["threshold"], now) left, mean, warn = self.dj_track(dev, key, level, limit, ch["limit"]["threshold"], now)
if warn: if warn:
self.dj_hit = now self.dj_hit = now
room = left if room is False or room is None else room if left is None else min(room, left) room = left if room is False or room is None else room if left is None else min(room, left)
+44
View File
@@ -261,6 +261,50 @@ def test_dj_brake_one_hit_counts_for_the_whole_dsp():
assert abs(app.dj_rooms["x"] - 6) < 0.01 assert abs(app.dj_rooms["x"] - 6) < 0.01
def test_dj_brake_measured_offset():
import server, tempfile
from types import SimpleNamespace
lv = lambda db: 10 ** (db / 20)
with tempfile.TemporaryDirectory() as d:
app = server.App(Path(d) / "c.json")
app.save = lambda: None
out = {"mute": False, "limit": {"threshold": 220}} # +20 dB
dev = SimpleNamespace(id="x", demo=False, model_name="204", info="DSP204 V0104P", state={"outputs": [out]}, status="online")
app.devices["x"] = dev
note = lambda db, t, limit=False: app.dj_note({"device": "x", "out": [lv(db)], "limit": [limit]}, now=t)
# measured: at +20 dB and a meter of -25 the limiter is about 19 dB away, before any hit
note(-25, 100.0)
assert app.dj_cal == {} and abs(app.dj_rooms["x"] - 19) < 0.01
# the flag right after raising the threshold teaches nothing: seen on real hardware
out["limit"]["threshold"] = 184
note(-25, 110.0)
out["limit"]["threshold"] = 220
note(-25, 111.0, True)
assert app.dj_cal == {}
note(-25, 111.2)
# a real hit moves the offset, it doesn't replace it
out["limit"]["threshold"] = 180
note(-20, 130.0)
note(-20, 130.2, True)
assert app.dj_cal == {} # that threshold has only just jumped
note(-20, 140.0)
note(-20, 140.2, True)
assert abs(app.dj_cal["x"] - 24.5) < 0.01
# it flickers: nothing new. And a jump of the threshold down teaches nothing either
note(-30, 140.4)
note(-30, 140.6, True)
assert abs(app.dj_cal["x"] - 24.5) < 0.01
out["limit"]["threshold"] = 160
note(-30, 150.0)
note(-30, 150.2, True)
assert abs(app.dj_cal["x"] - 24.5) < 0.01
with tempfile.TemporaryDirectory() as d:
app = server.App(Path(d) / "c.json")
for dev in (SimpleNamespace(id="s", demo=False, model_name="204", info="DSP204 V010 SIM"), SimpleNamespace(id="d", demo=True, model_name="204", info=""),
SimpleNamespace(id="o", demo=False, model_name="408", info="DSP408 V0104P")):
assert app.dj_offset(dev) == 0.0
def test_reset_config(): def test_reset_config():
import asyncio, json, server, tempfile import asyncio, json, server, tempfile
with tempfile.TemporaryDirectory() as d: with tempfile.TemporaryDirectory() as d:
+26 -12
View File
@@ -7,7 +7,7 @@ Play steady music into the DSP, close every other control software and run:
It only ever lowers one output's gain (by 6 dB) and limiter threshold, never raises anything above where it was, stores It only ever lowers one output's gain (by 6 dB) and limiter threshold, never raises anything above where it was, stores
nothing in a preset slot and puts both back at the end, also on Ctrl+C. A preset export is written first as a backup. nothing in a preset slot and puts both back at the end, also on Ctrl+C. A preset export is written first as a backup.
Takes about three minutes. The result goes to dsp-measure-<time>.json. Takes about two minutes. The result goes to dsp-measure-<time>.json.
""" """
import argparse import argparse
@@ -40,8 +40,8 @@ class Run:
self.polls: list[dict] = [] self.polls: list[dict] = []
self.o = 0 self.o = 0
self.ins: list[int] = [] self.ins: list[int] = []
self.gain = 0 self.gain = None # known once the output is chosen
self.thr = 0 self.thr = None
def on_event(self, ev: dict): def on_event(self, ev: dict):
if ev["type"] == "meters" and self.dev.state: if ev["type"] == "meters" and self.dev.state:
@@ -94,9 +94,21 @@ class Run:
break break
raw -= 2 raw -= 2
await self.set(thr=self.start_thr, gain=self.start_gain) await self.set(thr=self.start_thr, gain=self.start_gain)
await asyncio.sleep(3.0) # let the limiter release result["flag_after_raise_s"] = await self.flag_clear()
return result return result
async def flag_clear(self) -> float:
"""The flag was seen staying on for 4 s after raising the threshold: the next round must not take that for a hit."""
start = time.monotonic()
await asyncio.sleep(3.0)
while time.monotonic() - start < 15:
recent = self.window(time.monotonic() - 0.8)
if recent and not any(p["limit"][self.o] for p in recent):
break
await asyncio.sleep(0.2)
on = [p["t"] for p in self.window(start) if p["limit"][self.o]]
return round(on[-1] - start, 2) if on else 0.0
def conclude(res: dict) -> list[str]: def conclude(res: dict) -> list[str]:
lines = [] lines = []
@@ -115,15 +127,16 @@ def conclude(res: dict) -> list[str]:
f"(rounds: {plain}, spread {max(plain) - min(plain):.1f} dB).") f"(rounds: {plain}, spread {max(plain) - min(plain):.1f} dB).")
low = [r for r in hits if r["gain_db"] != res["start"]["gain_db"]] low = [r for r in hits if r["gain_db"] != res["start"]["gain_db"]]
if plain and low: if plain and low:
base = statistics.fmean(r["threshold_db"] for r in hits if r["gain_db"] == res["start"]["gain_db"]) # the threshold alone moves with the music between rounds, threshold minus meter doesn't
moved = statistics.fmean(r["threshold_db"] for r in low) - base a = statistics.fmean(r["offset_max_db"] for r in hits if r["gain_db"] == res["start"]["gain_db"])
lines.append(f"With -6 dB gain the limiter started {moved:+.1f} dB in threshold: " b = statistics.fmean(r["offset_max_db"] for r in low)
+ ("it works AFTER the gain." if abs(moved + 6) < 2 else "it works BEFORE the gain." if abs(moved) < 2 else "unclear.")) lines.append(f"Threshold minus loudest meter reading: {a:+.1f} dB, with -6 dB gain {b:+.1f} dB. "
+ ("About the same, so meter and limiter seem to see the same level." if abs(a - b) < 2 else "They differ: compare with another run before concluding anything."))
c = res.get("limiting") c = res.get("limiting")
if c: if c:
drop = c["limiting"]["mean_db"] - c["free"]["mean_db"] drop = (c["limiting"]["mean_db"] - c["limiting"]["in_db"]) - (c["free"]["mean_db"] - c["free"]["in_db"])
lines.append(f"Holding the threshold 6 dB below the start of limiting changed the meter by {drop:+.1f} dB: " lines.append(f"Holding the threshold 6 dB below the start of limiting changed the meter by {drop:+.1f} dB against the input: "
+ ("the meter shows the level AFTER the limiter." if drop < -1.5 else "the meter shows the level BEFORE the limiter.")) + ("the meter shows the level AFTER the limiter." if drop < -3 else "too little to say whether the meter is before or after the limiter."))
lines.append(f"While limiting, threshold minus meter: p95 {c['threshold_db'] - c['limiting']['p95_db']:+.1f} dB, " lines.append(f"While limiting, threshold minus meter: p95 {c['threshold_db'] - c['limiting']['p95_db']:+.1f} dB, "
f"mean {c['threshold_db'] - c['limiting']['mean_db']:+.1f} dB.") f"mean {c['threshold_db'] - c['limiting']['mean_db']:+.1f} dB.")
return lines return lines
@@ -237,7 +250,8 @@ async def main(args):
res["error"] = error res["error"] = error
res["polls"] = [[round(p["t"] - run.polls[0]["t"], 2), round(db(p["out"][run.o] ** 2), 1), round(db(sum(p["in"][i] ** 2 for i in run.ins)), 1), res["polls"] = [[round(p["t"] - run.polls[0]["t"], 2), round(db(p["out"][run.o] ** 2), 1), round(db(sum(p["in"][i] ** 2 for i in run.ins)), 1),
int(p["limit"][run.o]), P.gain_to_db(p["gain"]), P.threshold_to_db(p["thr"])] for p in run.polls] if run.ins else [] int(p["limit"][run.o]), None if p["gain"] is None else P.gain_to_db(p["gain"]),
None if p["thr"] is None else P.threshold_to_db(p["thr"])] for p in run.polls] if run.ins else []
out = outdir / f"dsp-measure-{stamp}.json" out = outdir / f"dsp-measure-{stamp}.json"
out.write_text(json.dumps(res), encoding="utf-8") out.write_text(json.dumps(res), encoding="utf-8")
print("\nResult:", out) print("\nResult:", out)