Add SoundField room planner, copy channel settings and global mute

SoundField (new tab, static/soundfield.js):
- top view of the room with stage, speakers placed by dragging and aimed with a handle,
  type presets, height, coverage, max SPL and DSP output assignment
- level map (tops by energy), sub map with phase at a chosen frequency, timing map
  for delay/fill speakers, audience statistics
- suggestions with one-click apply: aiming, main height, delay line, sub centre cluster
  (power alley), front fills, quick start layout
- delays from the speed of sound and temperature, written to the assigned DSP outputs
- plan stored by the server (shared, part of the settings backup)

Copy channel settings: level/filters/EQ/dynamics/routing to any channels of all connected DSPs.
Mute all: mutes every channel of every connected DSP and unmutes only what was open before,
also on DSPs that reconnect later; works while the app window is locked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
GivouandClaude Opus 5.5 committed 2026-11-01 22:38:49 +01:00
1 parent ffb6c05d47
commit a7ee66d761
8 files changed
+998 -12

No files matched your search

+9
View File
@@ -36,6 +36,15 @@ pi_writer.py → pi_image.py (cloud-init SD card, installs server.py as a system
lowers every output to −50 dB, flushes the queue and only then starts the generator (`0x39`); leaving switches the lowers every output to −50 dB, flushes the queue and only then starts the generator (`0x39`); leaving switches the
generator off first, then restores the gains. While `Device.test_active` the server only accepts the test generator off first, then restores the gains. While `Device.test_active` the server only accepts the test
controls (generator, test fader, output mutes) and the UI stays locked in the audio test tab. The state field is `state["test"] = {source, freq}`. controls (generator, test fader, output mutes) and the UI stays locked in the audio test tab. The state field is `state["test"] = {source, freq}`.
* **SoundField** (`static/soundfield.js`, plan stored by the server as `soundfield` in `config.json`, API
`/api/soundfield`) – room plan in metres (x across, y from the stage wall, aim 0° = into the room). Free-field model:
−6 dB per distance doubling, directivity from the coverage angle (−6 dB at its edges), tops summed by energy, subs
with phase at the chosen frequency. Delays: mains/subs aligned at the reference point, delay/fill speakers at their
target point plus the precedence offset. The canvas is only redrawn while dragging (never rebuilt), the side panels
are rebuilt after a change; the local plan object stays the one being edited (a save does not replace it).
* **Copy settings / mute all** – `App.copy_settings` (`POST /api/copy`, groups level/filters/eq/dynamics/routing) and
`App.set_mute_all` (`POST /api/muteall`; remembers per device which channels were open, persisted in `config.json`
as `mute_all`, released devices that were offline are unmuted when they reconnect; allowed while the app is locked).
* **`dsp/preset.py`** – preset files (`dsp-control-preset` JSON with state + raw image), validation, and the minimal * **`dsp/preset.py`** – preset files (`dsp-control-preset` JSON with state + raw image), validation, and the minimal
command sequence for an import. Undo backups go to `backups/` next to `config.json` (last 20 per device). command sequence for an import. Undo backups go to `backups/` next to `config.json` (last 20 per device).
* **`dsp/usbhid.py`** – HID via ctypes only: Windows `hid.dll`/SetupAPI, macOS IOKit, Linux `/dev/hidraw*`. * **`dsp/usbhid.py`** – HID via ctypes only: Windows `hid.dll`/SetupAPI, macOS IOKit, Linux `/dev/hidraw*`.
+9 -2
View File
@@ -30,7 +30,14 @@ Control both devices at the same time from your phone, tablet or computer – ov
* **Limiter calculator** – enter your amplifiers' datasheet values (power at 8/4/2 Ω, sensitivity or gain), assign * **Limiter calculator** – enter your amplifiers' datasheet values (power at 8/4/2 Ω, sensitivity or gain), assign
outputs, and see the resulting power when the limiter engages, the clipping headroom and the speaker load. outputs, and see the resulting power when the limiter engages, the clipping headroom and the speaker load.
"Limit to … W" calculates the threshold. Attack/release presets per band (infra, sub, kick, mid, high) "Limit to … W" calculates the threshold. Attack/release presets per band (infra, sub, kick, mid, high)
* **Settings backup** – devices, amplifier data, PIN and remote access in one file * **SoundField** – top view of the room: place mains, subs, delays and fills by dragging, see a level map, a sub
map at a chosen frequency (phase-correct, shows cancellation lanes) and a timing map for delay speakers. It
suggests aiming, height, delay lines, sub placement and front fills (one click to apply), calculates the delays
from the speed of sound and writes them to the assigned DSP outputs
* **Copy channel settings** – level/delay/polarity, filters, EQ, dynamics and routing from one channel to any number
of channels on all connected DSPs
* **Mute all** – one button mutes every channel of every connected DSP; releasing it unmutes only what was open before
* **Settings backup** – devices, amplifier data, SoundField plan, PIN and remote access in one file
* **Device lock** – DSPs locked with their 4-character code (e.g. `A1BA`) are detected on connect and the app asks * **Device lock** – DSPs locked with their 4-character code (e.g. `A1BA`) are detected on connect and the app asks
for the code; optionally it remembers the code and unlocks automatically. A new code can be set under ⚙ for the code; optionally it remembers the code and unlocks automatically. A new code can be set under ⚙
* **Audio test** – switch the DSP's test generator (pink noise, white noise, sine 20 Hz–20 kHz) on and off. All * **Audio test** – switch the DSP's test generator (pink noise, white noise, sine 20 Hz–20 kHz) on and off. All
@@ -160,7 +167,7 @@ python tests/test_protocol.py
| `sim.py` | Simulated DSP 204/408 | | `sim.py` | Simulated DSP 204/408 |
| `desktop.py` | Desktop app (Windows/macOS): server + own window (pywebview) | | `desktop.py` | Desktop app (Windows/macOS): server + own window (pywebview) |
| `pi_writer.py`, `pi_image.py`, `win_disk.py` | Raspberry Pi SD card writer: GUI, OS image + cloud-init, raw disk writes | | `pi_writer.py`, `pi_image.py`, `win_disk.py` | Raspberry Pi SD card writer: GUI, OS image + cloud-init, raw disk writes |
| `static/` | Web UI (`app.js`, `style.css`, `index.html`), translations in `static/i18n.js` | | `static/` | Web UI (`app.js`, `style.css`, `index.html`), SoundField in `static/soundfield.js`, translations in `static/i18n.js` |
| `packaging/` | Build script and icons | | `packaging/` | Build script and icons |
| `tests/` | Protocol tests | | `tests/` | Protocol tests |
| `PROTOCOL.md` | Protocol documentation | | `PROTOCOL.md` | Protocol documentation |
+160 -6
View File
@@ -7,6 +7,7 @@ Then open http://<this-computer>:8080 on your phone.
import argparse import argparse
import asyncio import asyncio
import base64 import base64
import copy
import errno import errno
import hashlib import hashlib
import json import json
@@ -89,6 +90,42 @@ def clean_limiter(data: dict) -> dict:
return {"amps": amps, "assign": assign, "ref": ref} return {"amps": amps, "assign": assign, "ref": ref}
SF_ROLES = ("main", "sub", "delay", "fill")
def clean_soundfield(data) -> dict:
"""SoundField room plan: room, stage, reference position and speakers (positions in metres)."""
data = data if isinstance(data, dict) else {}
room = data.get("room") if isinstance(data.get("room"), dict) else {}
w, d = _num(room.get("w"), 4, 200, 20), _num(room.get("d"), 4, 300, 30)
stage = data.get("stage") if isinstance(data.get("stage"), dict) else {}
ref = data.get("ref") if isinstance(data.get("ref"), dict) else {}
speakers = []
for s in (data.get("speakers") or [])[:48]:
if not isinstance(s, dict):
continue
sid = re.sub(r"[^\w-]", "", str(s.get("id") or ""))[:16] or uuid.uuid4().hex[:8]
speakers.append({
"id": sid, "name": str(s.get("name") or "Speaker")[:24],
"role": s.get("role") if s.get("role") in SF_ROLES else "main",
"type": re.sub(r"[^\w-]", "", str(s.get("type") or "custom"))[:16],
"x": _num(s.get("x"), 0, w, w / 2), "y": _num(s.get("y"), 0, d, 1), "h": _num(s.get("h"), 0, 30, 2),
"aim": _num(s.get("aim"), -180, 180, 0), "cov": _num(s.get("cov"), 20, 360, 90),
"spl": _num(s.get("spl"), 80, 160, 128),
"tx": _num(s.get("tx"), 0, w, w / 2), "ty": _num(s.get("ty"), 0, d, d / 2),
"outs": [o for o in (s.get("outs") or [])[:8] if re.fullmatch(r"[\w-]+:\d{1,2}", str(o))],
})
return {
"room": {"w": w, "d": d},
"stage": {"w": _num(stage.get("w"), 0, w, min(8, w)), "d": _num(stage.get("d"), 0, d / 2, 4)},
"temp": _num(data.get("temp"), -10, 45, 20),
"precedence": _num(data.get("precedence"), 0, 30, 5),
"ear": _num(data.get("ear"), 0.5, 3, 1.7),
"ref": {"x": _num(ref.get("x"), 0, w, w / 2), "y": _num(ref.get("y"), 0, d, d * 0.6)},
"speakers": speakers,
}
def clean_gains(v) -> list[int] | None: def clean_gains(v) -> list[int] | None:
"""Saved output gains of an interrupted audio test (from config.json).""" """Saved output gains of an interrupted audio test (from config.json)."""
if not isinstance(v, list) or not v or len(v) > 8: if not isinstance(v, list) or not v or len(v) > 8:
@@ -114,6 +151,7 @@ class App:
self.sessions: dict[str, float] = {} # token hash -> expiry self.sessions: dict[str, float] = {} # token hash -> expiry
self.failures: dict[str, tuple[int, float]] = {} # ip -> (failed attempts, locked until) self.failures: dict[str, tuple[int, float]] = {} # ip -> (failed attempts, locked until)
self.limiter: dict = clean_limiter({}) self.limiter: dict = clean_limiter({})
self.soundfield: dict = clean_soundfield({})
# desktop app: its own window logs in with a one-time token, other devices need the PIN # desktop app: its own window logs in with a one-time token, other devices need the PIN
self.app_token: str | None = None self.app_token: str | None = None
self.app_sessions: set[str] = set() self.app_sessions: set[str] = set()
@@ -127,6 +165,8 @@ class App:
self.demo = {"enabled": False, "model": "408"} self.demo = {"enabled": False, "model": "408"}
self.demo_server: asyncio.Server | None = None self.demo_server: asyncio.Server | None = None
self.demo_resume: set[str] = set() # real devices to reconnect when the demo ends self.demo_resume: set[str] = set() # real devices to reconnect when the demo ends
# global mute: per device the channels that were open before, unmuted again on release
self.mute_all = {"active": False, "restore": {}}
# ------------------------------------------------------------ config # ------------------------------------------------------------ config
@@ -142,6 +182,10 @@ class App:
self.sessions = {k: v for k, v in cfg.get("sessions", {}).items() if v > now} self.sessions = {k: v for k, v in cfg.get("sessions", {}).items() if v > now}
self.locked = bool(cfg.get("locked")) self.locked = bool(cfg.get("locked"))
self.lang = cfg.get("lang") if cfg.get("lang") in ("en", "de") else "" self.lang = cfg.get("lang") if cfg.get("lang") in ("en", "de") else ""
m = cfg.get("mute_all") or {}
self.mute_all = {"active": bool(m.get("active")), "restore": {
str(k): [[c[0], int(c[1])] for c in v if isinstance(c, list) and len(c) == 2 and c[0] in ("in", "out")]
for k, v in (m.get("restore") or {}).items() if isinstance(v, list)}}
self.apply_config(cfg) self.apply_config(cfg)
def apply_config(self, cfg: dict): def apply_config(self, cfg: dict):
@@ -152,6 +196,8 @@ class App:
elif not self.auth: # first start (a backup without PIN keeps the current one) elif not self.auth: # first start (a backup without PIN keeps the current one)
self.set_pin(DEFAULT_PIN, save=False) self.set_pin(DEFAULT_PIN, save=False)
self.limiter = clean_limiter(cfg.get("limiter") or {}) self.limiter = clean_limiter(cfg.get("limiter") or {})
if "soundfield" in cfg:
self.soundfield = clean_soundfield(cfg.get("soundfield"))
r = cfg.get("remote") or {} r = cfg.get("remote") or {}
self.remote = {"enabled": bool(r.get("enabled")), "port": int(_num(r.get("port"), 1, 65535, 8080))} self.remote = {"enabled": bool(r.get("enabled")), "port": int(_num(r.get("port"), 1, 65535, 8080))}
for d in cfg.get("devices", [])[:20]: for d in cfg.get("devices", [])[:20]:
@@ -165,7 +211,7 @@ class App:
"""App backup: devices, PIN (hashed), amplifiers/limiter data, remote access - no logins.""" """App backup: devices, PIN (hashed), amplifiers/limiter data, remote access - no logins."""
return {"format": CONFIG_FORMAT, "version": 1, "exported": time.strftime("%Y-%m-%dT%H:%M:%S"), 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, "devices": [d.config() for d in self.real_devices()], "auth": self.auth,
"limiter": self.limiter, "remote": self.remote} "limiter": self.limiter, "remote": self.remote, "soundfield": self.soundfield}
async def restore_config(self, doc: dict, session: str): async def restore_config(self, doc: dict, session: str):
if not isinstance(doc, dict) or doc.get("format") != CONFIG_FORMAT: if not isinstance(doc, dict) or doc.get("format") != CONFIG_FORMAT:
@@ -182,6 +228,7 @@ class App:
for dev in self.devices.values(): for dev in self.devices.values():
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()}) self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
self.broadcast({"type": "limiter", "data": self.limiter}) self.broadcast({"type": "limiter", "data": self.limiter})
self.broadcast({"type": "soundfield", "data": self.soundfield})
if self.app_token: # desktop app: (re)start or stop the LAN listener as restored if self.app_token: # desktop app: (re)start or stop the LAN listener as restored
await self.start_remote() await self.start_remote()
@@ -220,7 +267,10 @@ class App:
def save(self): def save(self):
sessions = {k: v for k, v in self.sessions.items() if k not in self.app_sessions} 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, cfg = {"devices": [d.config() for d in self.real_devices()], "auth": self.auth,
"sessions": sessions, "limiter": self.limiter, "remote": self.remote, "locked": self.locked} "sessions": sessions, "limiter": self.limiter, "remote": self.remote, "locked": self.locked,
"soundfield": self.soundfield,
"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: if self.lang:
cfg["lang"] = self.lang cfg["lang"] = self.lang
self.config_path.write_text(json.dumps(cfg, indent=2), encoding="utf-8") self.config_path.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
@@ -234,7 +284,7 @@ class App:
transport="usb" if usb else "tcp", usb=str(d.get("usb") or ""), transport="usb" if usb else "tcp", usb=str(d.get("usb") or ""),
lock_code=str(d.get("lock_code") or ""), auto_unlock=bool(d.get("auto_unlock")), lock_code=str(d.get("lock_code") or ""), auto_unlock=bool(d.get("auto_unlock")),
test_saved=clean_gains(d.get("test_saved"))) test_saved=clean_gains(d.get("test_saved")))
dev.on_online = self.check_audio_test dev.on_online = self.device_online
self.devices[dev_id] = dev self.devices[dev_id] = dev
if dev.autoconnect: if dev.autoconnect:
if self.demo["enabled"]: if self.demo["enabled"]:
@@ -280,6 +330,97 @@ class App:
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()}) self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
return {"ok": True} return {"ok": True}
async def device_online(self, dev: Device):
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
self.save()
# ------------------------------------------------------------ global mute
def mute_all_info(self) -> dict:
return {"active": self.mute_all["active"]}
def unmute_device(self, dev: Device):
for kind, i in self.mute_all["restore"].pop(dev.id, []):
chans = dev.state["inputs" if kind == "in" else "outputs"]
if i < len(chans) and chans[i]["mute"]:
dev.set_param(kind, i, "mute", False)
def set_mute_all(self, mute: bool) -> dict:
"""Mute every channel of every connected DSP; releasing unmutes only what was open before."""
online = [d for d in self.devices.values() if d.status == "online" and d.state]
if mute and not self.mute_all["active"]:
self.mute_all["restore"] = {}
for dev in online:
opened = [[kind, i] for kind, key in (("in", "inputs"), ("out", "outputs"))
for i, ch in enumerate(dev.state[key]) if not ch["mute"]]
for kind, i in opened:
dev.set_param(kind, i, "mute", True)
self.mute_all["restore"][dev.id] = opened
self.mute_all["active"] = True
elif not mute and self.mute_all["active"]:
self.mute_all["active"] = False
for dev in online:
self.unmute_device(dev) # offline ones follow when they connect again
self.save()
self.broadcast({"type": "muteall", "data": self.mute_all_info()})
return self.mute_all_info()
# ------------------------------------------------------------ copy channel settings
def copy_settings(self, body: dict) -> dict:
"""Copy groups of settings from one channel to channels of the same kind (any connected DSP)."""
src = self.devices.get(str(body.get("device")))
kind = "in" if body.get("kind") == "in" else "out"
key = "inputs" if kind == "in" else "outputs"
if not src or not src.state:
raise RuntimeError("DSP is not connected")
sch = src.state[key][int(body.get("idx", 0))]
groups = set(body.get("groups") or [])
changed = 0
for t in body.get("targets") or []:
dev = self.devices.get(str(t.get("device")))
if not dev or dev.status != "online" or not dev.state:
continue
if dev.test_active:
raise RuntimeError("Audio test is on – switch it off first")
idx = int(t.get("idx", -1))
if not 0 <= idx < len(dev.state[key]) or (dev is src and idx == int(body.get("idx", 0))):
continue
tch = dev.state[key][idx]
params = []
if "level" in groups:
params += ["gain", "delay", "polarity"]
if "filters" in groups:
params += ["hp", "lp"]
if "eq" in groups:
params += ["peq_bypass"] + [f"peq.{b}" for b in range(min(len(sch["peq"]), len(tch["peq"])))]
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"]
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:
v = copy.deepcopy(self._get(sch, p))
if self._get(tch, p) != v:
dev.set_param(kind, idx, p, v)
changed += 1
if "routing" in groups and kind == "out":
m = sch["matrix"] & ((1 << len(tch["mix"])) - 1)
if tch["matrix"] != m:
dev.set_param(kind, idx, "matrix", m)
changed += 1
return {"ok": True, "changed": changed}
@staticmethod
def _get(ch: dict, path: str):
node = ch
for k in path.split("."):
node = node[int(k)] if isinstance(node, list) else node[k]
return node
async def check_audio_test(self, dev: Device): async def check_audio_test(self, dev: Device):
"""On connect: a DSP still playing a test signal goes straight into the audio test (outputs lowered); """On connect: a DSP still playing a test signal goes straight into the audio test (outputs lowered);
one back on its analog inputs gets the faders saved by an interrupted test back.""" one back on its analog inputs gets the faders saved by an interrupted test back."""
@@ -331,7 +472,7 @@ class App:
port = self.demo_server.sockets[0].getsockname()[1] port = self.demo_server.sockets[0].getsockname()[1]
dev = Device("demo", f"Demo DSP {model}", "127.0.0.1", port, model, autoconnect=False, on_event=self.broadcast) dev = Device("demo", f"Demo DSP {model}", "127.0.0.1", port, model, autoconnect=False, on_event=self.broadcast)
dev.demo = True dev.demo = True
dev.on_online = self.check_audio_test dev.on_online = self.device_online
self.devices[dev.id] = dev self.devices[dev.id] = dev
self.demo["enabled"] = True self.demo["enabled"] = True
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()}) self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
@@ -436,7 +577,7 @@ class App:
@staticmethod @staticmethod
def allowed_while_locked(method: str, path: str) -> bool: def allowed_while_locked(method: str, path: str) -> bool:
"""What the locked app window may still do: look at everything, export presets.""" """What the locked app window may still do: look at everything, export presets."""
if path in ("/api/unlock", "/api/events", "/api/lang"): if path in ("/api/unlock", "/api/events", "/api/lang", "/api/muteall"):
return True return True
if method == "GET": if method == "GET":
return path != "/api/backup" # holds the PIN hash return path != "/api/backup" # holds the PIN hash
@@ -505,6 +646,19 @@ class App:
return [d.snapshot() for d in self.devices.values()] return [d.snapshot() for d in self.devices.values()]
if path == "/api/devices" and method == "POST": if path == "/api/devices" and method == "POST":
return self.add_device(body).snapshot() return self.add_device(body).snapshot()
if path == "/api/soundfield" and method == "PUT":
self.soundfield = clean_soundfield(body)
self.save()
self.broadcast({"type": "soundfield", "data": self.soundfield})
return self.soundfield
if path == "/api/soundfield":
return self.soundfield
if path == "/api/muteall" and method == "POST":
return self.set_mute_all(bool(body.get("mute")))
if path == "/api/muteall":
return self.mute_all_info()
if path == "/api/copy" and method == "POST":
return self.copy_settings(body)
if path == "/api/demo": if path == "/api/demo":
return await self.set_demo(body) if method == "PUT" else self.demo_info() return await self.set_demo(body) if method == "PUT" else self.demo_info()
if path == "/api/usb" and method == "GET": if path == "/api/usb" and method == "GET":
@@ -773,7 +927,7 @@ class App:
self.clients.add(q) self.clients.add(q)
try: try:
hello = {"type": "hello", "devices": [d.snapshot() for d in self.devices.values()], "limiter": self.limiter, hello = {"type": "hello", "devices": [d.snapshot() for d in self.devices.values()], "limiter": self.limiter,
"demo": self.demo_info()} "demo": self.demo_info(), "muteall": self.mute_all_info(), "soundfield": self.soundfield}
writer.write(f"data: {json.dumps(hello)}\n\n".encode()) writer.write(f"data: {json.dumps(hello)}\n\n".encode())
await writer.drain() await writer.drain()
while True: while True:
+74 -4
View File
@@ -61,6 +61,7 @@ const S = {
routeOpen: null, es: null, linkSel: { in: [], out: [] }, routeOpen: null, es: null, linkSel: { in: [], out: [] },
lim: { amps: [], assign: {}, ref: {} }, lim: { amps: [], assign: {}, ref: {} },
demo: { enabled: false, model: "408" }, demo: { enabled: false, model: "408" },
muteAll: false,
}; };
const $ = sel => document.querySelector(sel); const $ = sel => document.querySelector(sel);
const main = $("#main"); const main = $("#main");
@@ -85,6 +86,7 @@ const ICON = {
back: '<path d="M14 6v4h6v4h-6v4l-7-6z"/>', back: '<path d="M14 6v4h6v4h-6v4l-7-6z"/>',
lock: '<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>', lock: '<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>',
unlock: '<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 7.5-2"/>', unlock: '<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 7.5-2"/>',
muteall: '<path d="M4 9v6h4l5 4V5L8 9z"/><path d="M16.5 9.5l5 5M21.5 9.5l-5 5"/>',
link: '<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"/>', link: '<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"/>',
}; };
@@ -1107,7 +1109,8 @@ function viewChannel(d) {
const redrawPeq = () => { const c = main.querySelector("canvas.curve"); c && drawCurve(c, chans(dev(), k)[i], S.band); }; const redrawPeq = () => { const c = main.querySelector("canvas.curve"); c && drawCurve(c, chans(dev(), k)[i], S.band); };
const li = linkInfo(d, k, i); const li = linkInfo(d, k, i);
const basics = h("div", { class: "card" }, h("h3", {}, t("Channel")), const basics = h("div", { class: "card" }, h("h3", {}, h("span", { class: "grow" }, t("Channel")),
h("button", { class: "small", onclick: () => copyDialog(d, k, i) }, t("Copy to…"))),
li ? h("p", { class: "info linknote", style: `--lc:${li.color}` }, svgIcon(ICON.link), li ? h("p", { class: "info linknote", style: `--lc:${li.color}` }, svgIcon(ICON.link),
" " + t(k === "out" ? "Linked with {list} – changes apply to all of them (except name, routing and mix levels)." " " + t(k === "out" ? "Linked with {list} – changes apply to all of them (except name, routing and mix levels)."
: "Linked with {list} – changes apply to all of them (except the name).", { list: li.group.filter(j => j !== i).map(j => chLabel(k, j)).join(", ") })) : null, : "Linked with {list} – changes apply to all of them (except the name).", { list: li.group.filter(j => j !== i).map(j => chLabel(k, j)).join(", ") })) : null,
@@ -1532,6 +1535,64 @@ function viewLimiter(d) {
]; ];
} }
// ------------------------------------------------------------------ copy channel settings
const COPY_GROUPS = kind => [["level", t("Gain, delay, polarity")], ["filters", t("High / low pass")],
["eq", kind === "in" ? t("PEQ + GEQ") : "PEQ"], ["dynamics", kind === "in" ? "Noise gate" : t("Compressor + limiter")],
...(kind === "out" ? [["routing", t("Routing + mix levels")]] : [])];
async function copyDialog(d, kind, idx) {
const groups = new Set(store.get("dsp.copygroups." + kind)?.split(",").filter(Boolean) || ["eq", "filters", "dynamics"]);
const targets = new Set();
const groupBoxes = COPY_GROUPS(kind).map(([g, label]) => {
const cb = h("input", { type: "checkbox", checked: groups.has(g), onchange: () => cb.checked ? groups.add(g) : groups.delete(g) });
return h("label", { class: "chk" }, cb, label);
});
const devs = S.order.map(id => S.devices[id]).filter(x => x.status === "online" && x.state);
const targetRows = devs.map(x => {
const chips = chans(x, kind).map((_, j) => {
if (x.id === d.id && j === idx) return null;
const key = `${x.id}|${j}`;
const b = h("button", { class: "chip", "aria-pressed": "false",
onclick: () => { const on = !targets.has(key); on ? targets.add(key) : targets.delete(key); b.classList.toggle("on", on); b.setAttribute("aria-pressed", String(on)); } },
chLabel(kind, j) + (chans(x, kind)[j].name ? " · " + chans(x, kind)[j].name : ""));
return b;
}).filter(Boolean);
return h("div", { class: "copydev" }, devs.length > 1 ? h("div", { class: "sub" }, x.name) : null, h("div", { class: "chips" }, chips));
});
const res = await modal({
title: t("Copy {ch} to…", { ch: chTitle(d, kind, idx) }),
body: h("div", { class: "copydlg" }, h("div", { class: "sub" }, t("What")), h("div", { class: "copygroups" }, groupBoxes),
h("div", { class: "sub" }, t("To")), targetRows,
h("p", { class: "info" }, t("The name stays. Linked target channels take the values for their whole group."))),
actions: [{ label: t("Cancel") }, { label: t("Copy"), primary: true, value: () => (groups.size && targets.size ? true : undefined) }],
});
if (!res) return;
store.set("dsp.copygroups." + kind, [...groups].join(","));
try {
const r = await api("POST", "/api/copy", { device: d.id, kind, idx, groups: [...groups],
targets: [...targets].map(k => { const [device, j] = k.split("|"); return { device, idx: +j }; }) });
toast(r.changed ? t("{n} values copied", { n: r.changed }) : t("Nothing to change – the settings are already the same"));
} catch (e) { toast(t("Error: ") + trMsg(e.message)); }
}
// ------------------------------------------------------------------ global mute (all channels of all connected DSPs)
function showMuteAll() {
const b = $("#btn-muteall");
b.classList.toggle("on", !!S.muteAll);
b.title = S.muteAll ? t("All muted – click to unmute what was open before") : t("Mute all channels of all connected DSPs");
b.setAttribute("aria-label", b.title);
b.replaceChildren(...[svgIcon(ICON.muteall), S.muteAll ? h("span", {}, t("MUTED")) : null].filter(Boolean));
}
$("#btn-muteall").addEventListener("click", async () => {
try {
const r = await api("POST", "/api/muteall", { mute: !S.muteAll });
S.muteAll = r.active; showMuteAll();
toast(r.active ? t("All channels muted") : t("Unmuted – channels that were muted before stay muted"));
} catch (e) { toast(t("Error: ") + trMsg(e.message)); }
});
// ------------------------------------------------------------------ audio test (test generator of the DSP) // ------------------------------------------------------------------ audio test (test generator of the DSP)
const testOn = d => !!(d && d.state && d.state.test && d.state.test.source); const testOn = d => !!(d && d.state && d.state.test && d.state.test.source);
@@ -1807,8 +1868,10 @@ function render() {
live.clear(); live.clear();
let content; let content;
const d = dev(); const d = dev();
document.body.dataset.view = S.settings || !d ? "settings" : S.view; const field = !S.settings && S.view === "soundfield"; // the room plan works without a connected DSP
if (S.settings || !d) content = viewSettings(); document.body.dataset.view = field ? "soundfield" : S.settings || !d ? "settings" : S.view;
if (field) content = viewSoundField();
else if (S.settings || !d) content = viewSettings();
else if (d.status !== "online" || !d.state) else if (d.status !== "online" || !d.state)
content = h("div", { class: "empty" }, h("div", { class: "spinner" + (["loading", "connecting"].includes(d.status) ? "" : " off") }), content = h("div", { class: "empty" }, h("div", { class: "spinner" + (["loading", "connecting"].includes(d.status) ? "" : " off") }),
d.status === "loading" ? t("Loading the configuration from the DSP…") d.status === "loading" ? t("Loading the configuration from the DSP…")
@@ -1875,7 +1938,7 @@ $("#btn-lock").addEventListener("click", async () => {
}); });
// While locked, everything that would change a value is swallowed; navigating and looking still works. // While locked, everything that would change a value is swallowed; navigating and looking still works.
const VIEW_OK = ".chsel, .nav, .strip-head, .xout, .band, [data-view-ok]"; const VIEW_OK = ".chsel, .nav, .strip-head, .xout, .band, #btn-muteall, [data-view-ok]";
for (const type of ["pointerdown", "mousedown", "click", "dblclick", "keydown", "wheel"]) { for (const type of ["pointerdown", "mousedown", "click", "dblclick", "keydown", "wheel"]) {
document.addEventListener(type, e => { document.addEventListener(type, e => {
if (!S.locked || !(e.target instanceof Element)) return; if (!S.locked || !(e.target instanceof Element)) return;
@@ -1906,6 +1969,8 @@ function connectEvents() {
setDevices(ev.devices); setDevices(ev.devices);
if (ev.limiter) S.lim = ev.limiter; if (ev.limiter) S.lim = ev.limiter;
if (ev.demo) S.demo = ev.demo; if (ev.demo) S.demo = ev.demo;
if (ev.muteall) { S.muteAll = ev.muteall.active; showMuteAll(); }
if (ev.soundfield) S.sf = ev.soundfield;
if (S.demo.enabled && S.devices.demo && !S.devices[S.cur]?.demo) S.cur = "demo"; if (S.demo.enabled && S.devices.demo && !S.devices[S.cur]?.demo) S.cur = "demo";
S.order.forEach(id => maybeAskUnlock(S.devices[id])); S.order.forEach(id => maybeAskUnlock(S.devices[id]));
if (!S.order.length) S.settings = true; if (!S.order.length) S.settings = true;
@@ -1933,6 +1998,10 @@ function connectEvents() {
maybeAskUnlock(d); maybeAskUnlock(d);
break; break;
} }
case "soundfield":
sfOnRemote(ev.data); break;
case "muteall":
S.muteAll = ev.data.active; showMuteAll(); break;
case "demo": case "demo":
S.demo = ev.data; S.demo = ev.data;
if (!S.demo.enabled && S.cur === "demo") S.cur = S.order.find(id => id !== "demo") || null; if (!S.demo.enabled && S.cur === "demo") S.cur = S.order.find(id => id !== "demo") || null;
@@ -2042,6 +2111,7 @@ async function startApp() {
} }
S.locked = !!a.locked; S.locked = !!a.locked;
showLock(); showLock();
showMuteAll();
if (S.isApp) S.remote = await api("GET", "/api/remote"); if (S.isApp) S.remote = await api("GET", "/api/remote");
} catch { /* plain web UI */ } } catch { /* plain web UI */ }
connectEvents(); connectEvents();
+86
View File
@@ -345,6 +345,92 @@ const DE = {
"Phase": "Phase", "Phase": "Phase",
"The rest of the app is locked until the analog input is selected again.": "Der Rest der App ist gesperrt, bis wieder der Analog-Eingang gewählt ist.", "The rest of the app is locked until the analog input is selected again.": "Der Rest der App ist gesperrt, bis wieder der Analog-Eingang gewählt ist.",
"Phase inverted": "Phase invertiert", "Phase inverted": "Phase invertiert",
// copy settings, global mute
"Copy to…": "Kopieren nach…",
"Gain, delay, polarity": "Gain, Delay, Phase",
"High / low pass": "Hoch- / Tiefpass",
"PEQ + GEQ": "PEQ + GEQ",
"Compressor + limiter": "Kompressor + Limiter",
"Routing + mix levels": "Routing + Mix-Pegel",
"Copy {ch} to…": "{ch} kopieren nach…",
"What": "Was",
"To": "Wohin",
"Copy": "Kopieren",
"The name stays. Linked target channels take the values for their whole group.": "Der Name bleibt. Verknüpfte Zielkanäle übernehmen die Werte für ihre ganze Gruppe.",
"{n} values copied": "{n} Werte kopiert",
"Nothing to change – the settings are already the same": "Nichts zu ändern – die Einstellungen sind schon gleich",
"All muted – click to unmute what was open before": "Alles stumm – klicken gibt frei, was vorher offen war",
"Mute all channels of all connected DSPs": "Alle Kanäle aller verbundenen DSPs stummschalten",
"MUTED": "STUMM",
"All channels muted": "Alle Kanäle stumm",
"Unmuted – channels that were muted before stay muted": "Freigegeben – vorher stumme Kanäle bleiben stumm",
// SoundField
">30 ms echo": ">30 ms Echo",
"A planning aid: free field without reflections, coverage from the nominal angle. Check the result by ear or measurement.": "Eine Planungshilfe: Freifeld ohne Reflexionen, Abdeckung aus dem Nennwinkel. Das Ergebnis mit dem Ohr oder einer Messung prüfen.",
"Add delay line": "Delay-Linie hinzufügen",
"Add front fills": "Front-Fills hinzufügen",
"Add speakers to calculate delays.": "Lautsprecher hinzufügen, um Delays zu berechnen.",
"Aim": "Ausrichten",
"Aim (°)": "Ausrichtung (°)",
"Aim the mains at ⅔ of the room depth on the centre line ({list}).": "Die Mains auf ⅔ der Raumtiefe in der Mitte ausrichten ({list}).",
"Apply all": "Alle übernehmen",
"Centre cluster": "Mittig bündeln",
"Column": "Säule",
"Coverage (°)": "Abstrahlwinkel (°)",
"Custom": "Eigener",
"DSP outputs": "DSP-Ausgänge",
"Delay": "Delay",
"Delays": "Delays",
"Depth (m)": "Tiefe (m)",
"Distance": "Abstand",
"Ear height (m)": "Ohrhöhe (m)",
"Fill 8″": "Fill 8″",
"Height (m)": "Höhe (m)",
"Its delay is aligned at the dashed target point (drag it to the middle of the area this speaker covers).": "Sein Delay wird am gestrichelten Zielpunkt ausgerichtet (in die Mitte des Bereichs ziehen, den dieser Lautsprecher beschallt).",
"Level in the audience area: {spread} dB spread, {pct} % within ±3 dB of the median.": "Pegel im Publikumsbereich: {spread} dB Streuung, {pct} % innerhalb ±3 dB vom Mittelwert.",
"Main": "Main",
"Main L": "Main L",
"Main R": "Main R",
"Mains and subs are aligned at the reference position, delay and fill speakers at their target point plus {ms} ms so the mains are heard first.": "Mains und Subs werden an der Referenzposition ausgerichtet, Delay- und Fill-Lautsprecher an ihrem Zielpunkt plus {ms} ms, damit man die Mains zuerst hört.",
"Max SPL @1 m (dB)": "Max. SPL @1 m (dB)",
"No DSP in the device list yet.": "Noch kein DSP in der Geräteliste.",
"Nothing to improve with the current layout.": "Mit dem aktuellen Aufbau gibt es nichts zu verbessern.",
"Now on DSP": "Jetzt im DSP",
"Offset (ms)": "Versatz (ms)",
"Quick start": "Schnellstart",
"REF": "REF",
"Raise": "Anheben",
"Raise the mains to {h} m: front-to-back difference {a} dB → {b} dB.": "Mains auf {h} m anheben: Unterschied vorne/hinten {a} dB → {b} dB.",
"Role": "Rolle",
"Room": "Raum",
"Room plan": "Raumplan",
"STAGE": "BÜHNE",
"Select a speaker in the plan, or add one above. Drag to move, use the white handle to aim, drag the reference cross to your listening / mixing position.": "Einen Lautsprecher im Plan wählen oder oben hinzufügen. Ziehen zum Verschieben, mit dem weißen Griff ausrichten, das Referenzkreuz an deine Hör- bzw. Mischposition ziehen.",
"Speaker": "Lautsprecher",
"Speed of sound at {t} °C: {c} m/s.": "Schallgeschwindigkeit bei {t} °C: {c} m/s.",
"Stage depth (m)": "Bühnentiefe (m)",
"Stage width (m)": "Bühnenbreite (m)",
"Start with a stereo pair at the front edge of the stage and a sub in the centre.": "Mit einem Stereo-Paar an der Bühnenkante und einem Sub in der Mitte beginnen.",
"Sub 18″": "Sub 18″",
"Sub 2×18″": "Sub 2×18″",
"Sub frequency": "Sub-Frequenz",
"Suggestions": "Vorschläge",
"Temperature (°C)": "Temperatur (°C)",
"The back of the room is {db} dB quieter than the front third. A delay line with {n} speaker(s) at about {y} m keeps it even.": "Hinten ist es {db} dB leiser als im vorderen Drittel. Eine Delay-Linie mit {n} Lautsprecher(n) bei etwa {y} m gleicht das aus.",
"The first rows in the centre get {db} dB less than the middle of the room – front fills at the stage edge help.": "Die ersten Reihen in der Mitte bekommen {db} dB weniger als die Raummitte – Front-Fills an der Bühnenkante helfen.",
"The subs are {m} m apart – at 80 Hz that causes cancellation lanes through the room (power alley). A centre cluster sounds even everywhere.": "Die Subs stehen {m} m auseinander – bei 80 Hz entstehen dadurch Auslöschungs-Gassen durch den Raum (Power Alley). Mittig gebündelt klingt es überall gleichmäßig.",
"Timing": "Timing",
"Timing: in {a} % of the area a delay/fill arrives before the mains, in {b} % more than 30 ms late. Check positions and apply the calculated delays.": "Timing: In {a} % der Fläche kommt ein Delay/Fill vor den Mains an, in {b} % mehr als 30 ms zu spät. Positionen prüfen und die berechneten Delays übernehmen.",
"Top 12″": "Top 12″",
"Top 15″": "Top 15″",
"Width (m)": "Breite (m)",
"audience: {spread} dB spread · {pct} % within ±3 dB": "Publikum: {spread} dB Streuung · {pct} % innerhalb ±3 dB",
"delay too early": "Delay zu früh",
"median": "Median",
"no output": "kein Ausgang",
"{m} m to the nearest main": "{m} m zum nächsten Main",
"{n} output delay(s) set": "{n} Ausgangs-Delay(s) gesetzt",
"{n} output(s) not connected": "{n} Ausgang/Ausgänge nicht verbunden",
}; };
const DE_PATTERNS = [ const DE_PATTERNS = [
+3
View File
@@ -25,8 +25,10 @@
<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="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>Link</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>Link</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="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></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></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></button>
</nav> </nav>
<button id="btn-muteall" class="icon" aria-label="Mute all" title="Mute all"></button>
<button id="btn-lock" class="icon" hidden aria-label="Lock" title="Lock"></button> <button id="btn-lock" class="icon" hidden aria-label="Lock" title="Lock"></button>
<button id="btn-settings" class="icon" aria-label="Settings" title="Settings" data-t-label="Settings"> <button id="btn-settings" class="icon" aria-label="Settings" title="Settings" data-t-label="Settings">
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg> <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>
@@ -39,5 +41,6 @@
<div id="toast" hidden></div> <div id="toast" hidden></div>
<script src="/i18n.js"></script> <script src="/i18n.js"></script>
<script src="/app.js"></script> <script src="/app.js"></script>
<script src="/soundfield.js"></script>
</body> </body>
</html> </html>
+602
View File
@@ -0,0 +1,602 @@
"use strict";
/* SoundField – top view of the room: place speakers, see level / sub / timing maps, get placement
suggestions and the delays to set on the DSP outputs.
Free-field model (no reflections, no air absorption): level falls 6 dB per doubling of distance,
directivity from the horizontal coverage angle (−6 dB at its edges, about −24 dB behind the box).
Subs are summed with phase (they interfere), everything else by energy. Positions are metres:
x across the room (0 = left wall), y from the stage wall into the room. Aim 0° points into the room. */
const SF_TYPES = {
top12: { role: "main", cov: 90, spl: 128, h: 2.4 },
top15: { role: "main", cov: 75, spl: 131, h: 2.6 },
column: { role: "main", cov: 120, spl: 124, h: 2.0 },
fill8: { role: "fill", cov: 100, spl: 118, h: 1.1 },
sub18: { role: "sub", cov: 360, spl: 132, h: 0.4 },
sub218: { role: "sub", cov: 360, spl: 137, h: 0.5 },
custom: {},
};
const sfTypeLabel = k => ({ top12: t("Top 12″"), top15: t("Top 15″"), column: t("Column"), fill8: t("Fill 8″"),
sub18: t("Sub 18″"), sub218: t("Sub 2×18″"), custom: t("Custom") }[k] || k);
const SF_ROLE_COLOR = { main: "#38bdf8", sub: "#f472b6", delay: "#f59e0b", fill: "#a3e635" };
const sfRoleLabel = r => ({ main: t("Main"), sub: "Sub", delay: "Delay", fill: "Fill" }[r] || r);
const SF_SUB_HZ = [40, 50, 63, 80, 100, 125];
const sf = { // view state (the plan itself is S.sf, shared through the server)
sel: null, canvas: null, geo: null, drag: null, hover: null, savedAt: 0, saveTimer: null,
panels: {}, // side panels, rebuilt after a change (never the canvas while dragging)
};
const sfMode = () => store.get("dsp.sfmap") || "level";
const sfSubHz = () => +(store.get("dsp.sfhz") || 63);
// ------------------------------------------------------------------ plan helpers
function sfDefault() {
return { room: { w: 20, d: 30 }, stage: { w: 8, d: 4 }, temp: 20, precedence: 5, ear: 1.7,
ref: { x: 10, y: 18 }, speakers: [] };
}
const sfPlan = () => S.sf || (S.sf = sfDefault());
const sfSpeed = p => 331.3 + 0.606 * p.temp; // speed of sound in m/s
const sfR = (p, s, x, y) => Math.max(0.5, Math.hypot(x - s.x, y - s.y, s.h - p.ear));
const sfMs = (p, s, x, y) => sfR(p, s, x, y) / sfSpeed(p) * 1000;
const sfDir = s => [Math.sin(s.aim * Math.PI / 180), Math.cos(s.aim * Math.PI / 180)];
const sfInAudience = (p, x, y) => !(y < p.stage.d && Math.abs(x - p.room.w / 2) < p.stage.w / 2);
function sfDirectivity(s, x, y) {
if (s.cov >= 360) return 0;
const [dx, dy] = sfDir(s), vx = x - s.x, vy = y - s.y, len = Math.hypot(vx, vy) || 1;
const th = Math.acos(clamp((vx * dx + vy * dy) / len, -1, 1)) * 180 / Math.PI, half = s.cov / 2;
return th <= half ? -6 * (th / half) ** 2 : -6 - 18 * Math.min(1, (th - half) / Math.max(1, 180 - half));
}
const sfLevel = (p, s, x, y) => s.spl - 20 * Math.log10(sfR(p, s, x, y)) + sfDirectivity(s, x, y);
function sfSave() {
sf.savedAt = Date.now();
clearTimeout(sf.saveTimer);
// the local plan stays the one being edited (panels and drags hold references into it)
sf.saveTimer = setTimeout(() => api("PUT", "/api/soundfield", S.sf)
.then(() => { sf.savedAt = Date.now(); }).catch(e => toast(t("Error: ") + trMsg(e.message))), 350);
}
function sfOnRemote(data) { // another device changed the plan
if (Date.now() - sf.savedAt < 1500 || sf.drag) return; // our own echo, or we are in the middle of a drag
S.sf = data;
if (S.view === "soundfield" && !S.settings) sfRefresh();
}
// ------------------------------------------------------------------ delays
function sfDelays(p) {
const mains = p.speakers.filter(s => s.role === "main"), subs = p.speakers.filter(s => s.role === "sub");
const out = {}, info = {};
const R = p.ref;
const mainT = mains.length ? mains.reduce((a, s) => a + sfMs(p, s, R.x, R.y), 0) / mains.length : null;
let base = 0;
if (mainT != null) {
const subD = subs.map(s => mainT - sfMs(p, s, R.x, R.y));
base = Math.max(0, -Math.min(0, ...subD)); // a sub further away than the mains: delay the mains instead
subs.forEach((s, i) => { out[s.id] = subD[i] + base; info[s.id] = "ref"; });
}
mains.forEach(s => { out[s.id] = base; info[s.id] = "ref"; });
for (const s of p.speakers.filter(s => s.role === "delay" || s.role === "fill")) {
const tMain = mains.length ? Math.min(...mains.map(m => sfMs(p, m, s.tx, s.ty) + out[m.id])) : null;
out[s.id] = tMain == null ? 0 : Math.max(0, tMain - sfMs(p, s, s.tx, s.ty) + p.precedence);
info[s.id] = "target";
}
if (!mains.length) subs.forEach(s => { out[s.id] = 0; info[s.id] = "none"; });
return { ms: out, info };
}
// ------------------------------------------------------------------ maps
// level colours relative to the median of the audience area: cyan = clearly louder, green = typical, red = too quiet
const LEVEL_STOPS = [[9, [125, 211, 252]], [4.5, [45, 212, 191]], [0, [34, 197, 94]], [-3, [163, 230, 53]], [-6, [234, 179, 8]],
[-9, [249, 115, 22]], [-12, [239, 68, 68]], [-20, [110, 20, 20]]];
const TIME_STOPS = [[0, [34, 197, 94]], [10, [132, 204, 22]], [20, [234, 179, 8]], [30, [249, 115, 22]], [45, [239, 68, 68]]];
function sfStops(stops, v, desc) {
for (let i = 0; i < stops.length - 1; i++) {
const [a, ca] = stops[i], [b, cb] = stops[i + 1];
if (desc ? v >= b : v <= b) { const f = (v - a) / (b - a); return ca.map((c, k) => Math.round(c + (cb[k] - c) * clamp(f, 0, 1))); }
}
return stops[stops.length - 1][1];
}
// value grid over the room for the current map mode; null cells are left empty
function sfField(p, mode) {
const step = Math.max(0.2, Math.max(p.room.w, p.room.d) / 130);
const cols = Math.ceil(p.room.w / step), rows = Math.ceil(p.room.d / step);
const vals = new Float32Array(cols * rows).fill(NaN);
const dl = sfDelays(p).ms;
const tops = p.speakers.filter(s => s.role !== "sub"), subs = p.speakers.filter(s => s.role === "sub");
const mains = p.speakers.filter(s => s.role === "main"), late = p.speakers.filter(s => s.role === "delay" || s.role === "fill");
const k = 2 * Math.PI * sfSubHz() / 1000; // phase per ms
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) {
const x = (c + 0.5) * step, y = (r + 0.5) * step;
let v = NaN;
if (mode === "level" && tops.length) {
let e = 0; for (const s of tops) e += 10 ** (sfLevel(p, s, x, y) / 10);
v = 10 * Math.log10(e);
} else if (mode === "sub" && subs.length) {
let re = 0, im = 0;
for (const s of subs) { const a = 10 ** (sfLevel(p, s, x, y) / 20), ph = k * (sfMs(p, s, x, y) + (dl[s.id] || 0)); re += a * Math.cos(ph); im -= a * Math.sin(ph); }
v = 10 * Math.log10(re * re + im * im || 1e-12);
} else if (mode === "time" && mains.length && late.length) {
// arrival of the strongest delay/fill speaker relative to the first main arrival, where it matters (≥ main − 6 dB)
let tm = Infinity, lm = -Infinity;
for (const s of mains) { tm = Math.min(tm, sfMs(p, s, x, y) + (dl[s.id] || 0)); lm = Math.max(lm, sfLevel(p, s, x, y)); }
let best = null, bl = -Infinity;
for (const s of late) { const l = sfLevel(p, s, x, y); if (l > bl) { bl = l; best = s; } }
if (best && bl >= lm - 6) v = sfMs(p, best, x, y) + (dl[best.id] || 0) - tm;
}
vals[r * cols + c] = v;
}
return { step, cols, rows, vals };
}
function sfStats(p, field) {
const a = [];
for (let r = 0; r < field.rows; r++) for (let c = 0; c < field.cols; c++) {
const v = field.vals[r * field.cols + c];
if (!isNaN(v) && sfInAudience(p, (c + 0.5) * field.step, (r + 0.5) * field.step)) a.push(v);
}
if (!a.length) return null;
a.sort((x, y) => x - y);
const q = f => a[Math.min(a.length - 1, Math.floor(f * a.length))], med = q(0.5);
return { max: a[a.length - 1], min: a[0], med, spread: q(0.95) - q(0.05), within3: a.filter(v => Math.abs(v - med) <= 3).length / a.length,
early: a.filter(v => v < -1).length / a.length, echo: a.filter(v => v > 30).length / a.length };
}
// ------------------------------------------------------------------ suggestions
// level of the mains alone at (x, y), for the suggestions
const sfMainLevel = (p, x, y, mains = p.speakers.filter(s => s.role === "main")) =>
10 * Math.log10(mains.reduce((e, s) => e + 10 ** (sfLevel(p, s, x, y) / 10), 0) || 1e-12);
function sfSuggestions(p) {
const out = [], W = p.room.w, D = p.room.d, sd = p.stage.d;
const mains = p.speakers.filter(s => s.role === "main"), subs = p.speakers.filter(s => s.role === "sub");
const delays = p.speakers.filter(s => s.role === "delay"), fills = p.speakers.filter(s => s.role === "fill");
const add = (kind, text, apply, label) => out.push({ kind, text, apply, label });
if (!mains.length) {
add("tip", t("Start with a stereo pair at the front edge of the stage and a sub in the centre."), q => {
const x0 = W / 2 - Math.max(2, q.stage.w / 2), x1 = W / 2 + Math.max(2, q.stage.w / 2), y = Math.max(0.5, sd - 0.3);
q.speakers.push(sfNew(q, "top12", x0, y, t("Main L")), sfNew(q, "top12", x1, y, t("Main R")),
sfNew(q, "sub18", W / 2, Math.min(D - 1, sd + 0.6), "Sub"));
sfAimMains(q);
}, t("Quick start"));
return out;
}
// 1. aim of the mains: towards ⅔ of the audience depth on the centre line
const aimFor = s => Math.round(Math.atan2(W / 2 - s.x, sd + (D - sd) * 2 / 3 - s.y) * 180 / Math.PI);
const offAim = mains.filter(s => s.cov < 360 && Math.abs(aimFor(s) - s.aim) > 8);
if (offAim.length)
add("tip", t("Aim the mains at ⅔ of the room depth on the centre line ({list}).", { list: offAim.map(s => `${s.name} ${aimFor(s)}°`).join(", ") }),
q => sfAimMains(q), t("Aim"));
// 2. height of the mains: smaller difference between front and back
const fb = h => { const m = mains.map(s => ({ ...s, h })); return sfMainLevel(p, W / 2, sd + 1, m) - sfMainLevel(p, W / 2, D - 1, m); };
const hNow = mains.reduce((a, s) => a + s.h, 0) / mains.length, now = fb(hNow);
let best = hNow, bestV = now;
for (let h = 2; h <= 5.01; h += 0.5) { const v = fb(h); if (v < bestV - 0.01) { bestV = v; best = h; } }
if (best > hNow + 0.3 && now - bestV >= 1.5)
add("tip", t("Raise the mains to {h} m: front-to-back difference {a} dB → {b} dB.", { h: best.toFixed(1), a: now.toFixed(1), b: bestV.toFixed(1) }),
q => q.speakers.forEach(s => { if (s.role === "main") s.h = best; }), t("Raise"));
// 3. delay line when the back gets too quiet
const L0 = sfMainLevel(p, W / 2, sd + (D - sd) * 0.3), back = sfMainLevel(p, W / 2, D - 1);
if (!delays.length && L0 - back > 6 && D - sd > 12) {
let yd = D - 1;
for (let y = sd + 4; y < D - 2; y += 0.25) if (sfMainLevel(p, W / 2, y) <= L0 - 4.5) { yd = y; break; }
const throwM = D - yd, n = clamp(Math.ceil(W / Math.max(5, 2 * throwM * Math.tan(45 * Math.PI / 180))), 1, 4);
add("warn", t("The back of the room is {db} dB quieter than the front third. A delay line with {n} speaker(s) at about {y} m keeps it even.",
{ db: (L0 - back).toFixed(0), n, y: yd.toFixed(1) }), q => {
for (let i = 0; i < n; i++) {
const s = sfNew(q, "top12", W * (i + 0.5) / n, yd, `Delay ${i + 1}`);
Object.assign(s, { role: "delay", h: 3, aim: 0, tx: s.x, ty: Math.min(D - 0.5, yd + throwM * 0.5) });
q.speakers.push(s);
}
}, t("Add delay line"));
}
// 4. subs: spacing creates cancellation lanes ("power alley")
if (subs.length > 1) {
const xs = subs.map(s => s.x), spread = Math.max(...xs) - Math.min(...xs), half = sfSpeed(p) / 80 / 2;
if (spread > half)
add("warn", t("The subs are {m} m apart – at 80 Hz that causes cancellation lanes through the room (power alley). A centre cluster sounds even everywhere.",
{ m: spread.toFixed(1) }), q => {
const ss = q.speakers.filter(s => s.role === "sub");
ss.forEach((s, i) => Object.assign(s, { x: W / 2 + (i - (ss.length - 1) / 2) * 0.7, y: Math.min(D - 1, sd + 0.6), aim: 0 }));
}, t("Centre cluster"));
}
// 5. front rows in the shadow of high mains
const front = sfMainLevel(p, W / 2, sd + 1.2), mid = sfMainLevel(p, W / 2, sd + (D - sd) * 0.4);
if (!fills.length && mid - front > 3 && p.stage.w >= 2)
add("tip", t("The first rows in the centre get {db} dB less than the middle of the room – front fills at the stage edge help.", { db: (mid - front).toFixed(0) }), q => {
const n = clamp(Math.round(q.stage.w / 4), 1, 4);
for (let i = 0; i < n; i++) {
const s = sfNew(q, "fill8", W / 2 - q.stage.w / 2 + q.stage.w * (i + 0.5) / n, Math.max(0.3, sd - 0.2), `Fill ${i + 1}`);
Object.assign(s, { tx: s.x, ty: Math.min(D - 1, sd + 3) });
q.speakers.push(s);
}
}, t("Add front fills"));
// 6. coverage and timing summary
const lv = sfStats(p, sfField(p, "level"));
if (lv) add(lv.spread <= 6 ? "ok" : "info", t("Level in the audience area: {spread} dB spread, {pct} % within ±3 dB of the median.",
{ spread: lv.spread.toFixed(1), pct: Math.round(lv.within3 * 100) }));
if (delays.length || fills.length) {
const tm = sfStats(p, sfField(p, "time"));
if (tm && (tm.early > 0.05 || tm.echo > 0.05))
add("warn", t("Timing: in {a} % of the area a delay/fill arrives before the mains, in {b} % more than 30 ms late. Check positions and apply the calculated delays.",
{ a: Math.round(tm.early * 100), b: Math.round(tm.echo * 100) }));
}
return out;
}
function sfAimMains(q) {
const W = q.room.w, aimY = q.stage.d + (q.room.d - q.stage.d) * 2 / 3;
q.speakers.forEach(s => { if (s.role === "main" && s.cov < 360) s.aim = Math.round(Math.atan2(W / 2 - s.x, aimY - s.y) * 180 / Math.PI); });
}
function sfNew(q, type, x, y, name) {
const d = SF_TYPES[type] || {};
const s = { id: Math.random().toString(36).slice(2, 10), name: name || sfTypeLabel(type), role: d.role || "main", type,
x: clamp(x, 0, q.room.w), y: clamp(y, 0, q.room.d), h: d.h ?? 2, aim: 0, cov: d.cov ?? 90, spl: d.spl ?? 125, outs: [] };
s.tx = s.x; s.ty = Math.min(q.room.d, s.y + 6);
return s;
}
// ------------------------------------------------------------------ drawing
function sfDraw() {
const cv = sf.canvas, p = sfPlan();
if (!cv || !cv.isConnected) return;
const W = cv.clientWidth;
if (!W) return;
const m = 30, maxH = Math.max(320, Math.min(window.innerHeight * 0.7, 900));
const sc = Math.min((W - 2 * m) / p.room.w, (maxH - 2 * m) / p.room.d);
const H = Math.round(p.room.d * sc + 2 * m), ox = (W - p.room.w * sc) / 2;
if (cv.style.height !== H + "px") cv.style.height = H + "px";
const dpr = window.devicePixelRatio || 1;
cv.width = W * dpr; cv.height = H * dpr;
const g = cv.getContext("2d");
g.scale(dpr, dpr);
const X = x => ox + x * sc, Y = y => m + y * sc;
sf.geo = { X, Y, sc, toM: (px, py) => [(px - ox) / sc, (py - m) / sc] };
// room
g.fillStyle = "#0e1116"; g.fillRect(X(0), Y(0), p.room.w * sc, p.room.d * sc);
// map
const mode = sfMode();
let field = null;
if (mode !== "off") {
field = sfField(p, mode);
const st = sfStats(p, field), ref = mode === "time" ? 0 : st ? st.med : 0;
const img = new ImageData(field.cols, field.rows);
for (let i = 0; i < field.vals.length; i++) {
const v = field.vals[i];
if (isNaN(v)) continue;
let col;
if (mode === "time") col = v < -1 ? [217, 70, 239] : sfStops(TIME_STOPS, v, false);
else col = sfStops(LEVEL_STOPS, Math.min(9, v - ref), true);
img.data.set([...col, 120], i * 4);
}
const off = document.createElement("canvas");
off.width = field.cols; off.height = field.rows;
off.getContext("2d").putImageData(img, 0, 0);
g.imageSmoothingEnabled = true;
g.drawImage(off, X(0), Y(0), field.cols * field.step * sc, field.rows * field.step * sc);
sf.field = field; sf.fieldRef = ref; sf.stats = st;
} else { sf.field = null; sf.stats = null; }
// grid
g.font = "10px system-ui"; g.fillStyle = "#5b6673"; g.lineWidth = 1;
for (let x = 0; x <= p.room.w + 0.001; x++) {
g.strokeStyle = x % 5 ? "#ffffff0d" : "#ffffff22"; g.beginPath(); g.moveTo(X(x), Y(0)); g.lineTo(X(x), Y(p.room.d)); g.stroke();
if (x % 5 === 0) g.fillText(x + " m", X(x) - 6, m - 8);
}
for (let y = 0; y <= p.room.d + 0.001; y++) {
g.strokeStyle = y % 5 ? "#ffffff0d" : "#ffffff22"; g.beginPath(); g.moveTo(X(0), Y(y)); g.lineTo(X(p.room.w), Y(y)); g.stroke();
if (y % 5 === 0) { g.textAlign = "end"; g.fillText(y, X(0) - 5, Y(y) + 3); g.textAlign = "start"; }
}
g.strokeStyle = "#3a4552"; g.lineWidth = 2; g.strokeRect(X(0), Y(0), p.room.w * sc, p.room.d * sc);
// stage
if (p.stage.w > 0 && p.stage.d > 0) {
const sx = X(p.room.w / 2 - p.stage.w / 2), sw = p.stage.w * sc, sh = p.stage.d * sc;
g.fillStyle = "#1c2027e6"; g.fillRect(sx, Y(0), sw, sh);
g.save(); g.beginPath(); g.rect(sx, Y(0), sw, sh); g.clip(); g.strokeStyle = "#ffffff12"; g.lineWidth = 1;
for (let i = -sh; i < sw; i += 10) { g.beginPath(); g.moveTo(sx + i, Y(0)); g.lineTo(sx + i + sh, Y(0) + sh); g.stroke(); }
g.restore();
g.fillStyle = "#8a95a3"; g.font = "600 11px system-ui"; g.textAlign = "center"; g.fillText(t("STAGE"), sx + sw / 2, Y(0) + Math.min(sh - 6, 16)); g.textAlign = "start";
}
// delay / fill targets
for (const s of p.speakers.filter(s => s.role === "delay" || s.role === "fill")) {
g.strokeStyle = SF_ROLE_COLOR[s.role] + "99"; g.setLineDash([4, 4]); g.lineWidth = 1.2;
g.beginPath(); g.moveTo(X(s.x), Y(s.y)); g.lineTo(X(s.tx), Y(s.ty)); g.stroke(); g.setLineDash([]);
g.beginPath(); g.arc(X(s.tx), Y(s.ty), 6, 0, 2 * Math.PI); g.stroke();
}
// speakers (names step aside when boxes stand close together)
const labels = [];
for (const s of p.speakers) {
const col = SF_ROLE_COLOR[s.role], sel = s.id === sf.sel, x = X(s.x), y = Y(s.y);
if (s.cov < 360) { // coverage wedge
const r = Math.max(40, 3 * sc), a0 = Math.PI / 2 - (s.aim + s.cov / 2) * Math.PI / 180, a1 = Math.PI / 2 - (s.aim - s.cov / 2) * Math.PI / 180;
g.beginPath(); g.moveTo(x, y); g.arc(x, y, r, a0, a1); g.closePath();
g.fillStyle = col + (sel ? "33" : "1f"); g.fill(); g.strokeStyle = col + (sel ? "aa" : "55"); g.lineWidth = 1; g.stroke();
}
g.fillStyle = col; g.strokeStyle = sel ? "#fff" : "#0b0c0f"; g.lineWidth = sel ? 2.5 : 1.5;
g.beginPath();
if (s.role === "sub") g.rect(x - 9, y - 9, 18, 18);
else { const [dx, dy] = sfDir(s); g.moveTo(x + dx * 11, y + dy * 11); g.lineTo(x - dy * 9 - dx * 7, y + dx * 9 - dy * 7); g.lineTo(x + dy * 9 - dx * 7, y - dx * 9 - dy * 7); g.closePath(); }
g.fill(); g.stroke();
g.fillStyle = "#e8edf3"; g.font = (sel ? "600 " : "") + "11px system-ui"; g.textAlign = "center";
const lw = g.measureText(s.name).width + 6;
let ly = y + 24;
for (let k = 0; k < 4 && labels.some(b => Math.abs(b.x - x) < (b.w + lw) / 2 && Math.abs(b.y - ly) < 13); k++) ly = k % 2 ? y + 24 + 13 * (k + 1) / 2 : y - 16 - 13 * k / 2;
labels.push({ x, y: ly, w: lw });
g.fillText(s.name, x, ly); g.textAlign = "start";
if (sel && s.cov < 360) { // rotation handle
const [dx, dy] = sfDir(s), hr = Math.max(34, 1.6 * sc);
g.strokeStyle = "#ffffffaa"; g.lineWidth = 1.5; g.beginPath(); g.moveTo(x, y); g.lineTo(x + dx * hr, y + dy * hr); g.stroke();
g.fillStyle = "#fff"; g.beginPath(); g.arc(x + dx * hr, y + dy * hr, 6, 0, 2 * Math.PI); g.fill();
}
}
// reference position
const rx = X(p.ref.x), ry = Y(p.ref.y);
g.strokeStyle = "#e8edf3"; g.lineWidth = 2;
g.beginPath(); g.moveTo(rx - 10, ry); g.lineTo(rx + 10, ry); g.moveTo(rx, ry - 10); g.lineTo(rx, ry + 10); g.stroke();
g.beginPath(); g.arc(rx, ry, 6, 0, 2 * Math.PI); g.stroke();
g.fillStyle = "#e8edf3"; g.font = "600 10px system-ui"; g.fillText(t("REF"), rx + 9, ry - 8);
sfLegend();
}
function sfLegend() {
const el = sf.panels.legend;
if (!el) return;
const mode = sfMode(), st = sf.stats;
const sw = (c, label) => h("span", { class: "sw" }, h("i", { style: `background:rgb(${c.join(",")})` }), label);
if (mode === "off") return el.replaceChildren();
if (mode === "time") return el.replaceChildren(sw([217, 70, 239], t("delay too early")), sw(TIME_STOPS[0][1], "0–10 ms"),
sw(TIME_STOPS[2][1], "20 ms"), sw(TIME_STOPS[4][1], t(">30 ms echo")));
el.replaceChildren(...[[6, LEVEL_STOPS[1][1]], [0, LEVEL_STOPS[2][1]], [-3, LEVEL_STOPS[3][1]], [-6, LEVEL_STOPS[4][1]], [-9, LEVEL_STOPS[5][1]], [-12, LEVEL_STOPS[6][1]]]
.map(([db, c]) => sw(c, db ? `${db > 0 ? "+" : ""}${db} dB` : t("median"))),
...(st ? [h("span", { class: "stat" }, mode === "sub" ? `${sfSubHz()} Hz · ` : "", t("audience: {spread} dB spread · {pct} % within ±3 dB",
{ spread: st.spread.toFixed(1), pct: Math.round(st.within3 * 100) }))] : []));
}
// ------------------------------------------------------------------ interaction
function sfHit(px, py) {
const p = sfPlan(), { X, Y, sc } = sf.geo;
const sel = p.speakers.find(s => s.id === sf.sel);
if (sel && sel.cov < 360) {
const [dx, dy] = sfDir(sel), hr = Math.max(34, 1.6 * sc);
if (Math.hypot(px - (X(sel.x) + dx * hr), py - (Y(sel.y) + dy * hr)) < 12) return { kind: "rot", s: sel };
}
for (const s of [...p.speakers].reverse()) if (Math.hypot(px - X(s.x), py - Y(s.y)) < 15) return { kind: "move", s };
for (const s of p.speakers) if ((s.role === "delay" || s.role === "fill") && Math.hypot(px - X(s.tx), py - Y(s.ty)) < 10) return { kind: "target", s };
if (Math.hypot(px - X(p.ref.x), py - Y(p.ref.y)) < 14) return { kind: "ref" };
return null;
}
function sfBindCanvas(cv) {
const pos = e => { const r = cv.getBoundingClientRect(); return [e.clientX - r.left, e.clientY - r.top]; };
const snap = v => Math.round(v * 10) / 10;
cv.addEventListener("pointerdown", e => {
if (!sf.geo) return;
const [px, py] = pos(e), hit = sfHit(px, py);
if (!hit) { if (sf.sel) { sf.sel = null; sfDraw(); sfPanels(); } return; }
e.preventDefault();
if (hit.s && sf.sel !== hit.s.id) { sf.sel = hit.s.id; sfPanels(); }
sf.drag = { ...hit, id: e.pointerId, moved: false };
cv.setPointerCapture(e.pointerId);
beginBusy();
sfDraw();
});
cv.addEventListener("pointermove", e => {
const [px, py] = pos(e);
if (!sf.drag) { sfHover(px, py); return; }
if (e.pointerId !== sf.drag.id) return;
const p = sfPlan(), [mx, my] = sf.geo.toM(px, py), x = clamp(snap(mx), 0, p.room.w), y = clamp(snap(my), 0, p.room.d);
const d = sf.drag;
if (d.kind === "move") { const dx = x - d.s.x, dy = y - d.s.y; d.s.x = x; d.s.y = y; if (d.s.role === "delay" || d.s.role === "fill") { d.s.tx = clamp(snap(d.s.tx + dx), 0, p.room.w); d.s.ty = clamp(snap(d.s.ty + dy), 0, p.room.d); } }
else if (d.kind === "rot") { let a = Math.atan2(mx - d.s.x, my - d.s.y) * 180 / Math.PI; if (!e.shiftKey) a = Math.round(a); else a = Math.round(a / 15) * 15; d.s.aim = a; }
else if (d.kind === "target") { d.s.tx = x; d.s.ty = y; }
else if (d.kind === "ref") { p.ref.x = x; p.ref.y = y; }
d.moved = true;
sfDraw(); sfHover(px, py);
});
const end = e => {
if (!sf.drag || e.pointerId !== sf.drag.id) return;
const moved = sf.drag.moved;
sf.drag = null;
endBusy();
if (moved) { sfSave(); sfPanels(); }
};
cv.addEventListener("pointerup", end);
cv.addEventListener("pointercancel", end);
cv.addEventListener("pointerleave", () => { if (!sf.drag && sf.panels.readout) sf.panels.readout.textContent = ""; });
cv.addEventListener("keydown", e => {
if ((e.key === "Delete" || e.key === "Backspace") && sf.sel) { e.preventDefault(); sfRemove(sf.sel); }
});
}
function sfHover(px, py) {
const el = sf.panels.readout;
if (!el || !sf.geo) return;
const p = sfPlan(), [x, y] = sf.geo.toM(px, py);
if (x < 0 || y < 0 || x > p.room.w || y > p.room.d) { el.textContent = ""; return; }
let txt = `x ${x.toFixed(1)} m · y ${y.toFixed(1)} m`;
const f = sf.field;
if (f) {
const c = Math.floor(x / f.step), r = Math.floor(y / f.step), v = f.vals[r * f.cols + c];
if (!isNaN(v)) txt += sfMode() === "time" ? ` · ${v >= 0 ? "+" : ""}${v.toFixed(1)} ms` : ` · ${v.toFixed(1)} dB (${(v - sf.fieldRef).toFixed(1)})`;
}
const mains = p.speakers.filter(s => s.role === "main");
if (mains.length) txt += " · " + t("{m} m to the nearest main", { m: Math.min(...mains.map(s => Math.hypot(x - s.x, y - s.y))).toFixed(1) });
el.textContent = txt;
}
function sfChange(fn, full = true) { // change the plan from a panel
fn(sfPlan());
sfSave();
sfDraw();
if (full) sfPanels();
}
function sfRemove(id) {
sfChange(p => { p.speakers = p.speakers.filter(s => s.id !== id); });
if (sf.sel === id) { sf.sel = null; sfPanels(); }
}
// ------------------------------------------------------------------ panels
const sfNum = (value, step, onset, attrs = {}) => {
const el = h("input", { type: "number", value: +(+value).toFixed(2), step, ...attrs });
el.addEventListener("change", () => { const v = parseFloat(el.value); if (!isNaN(v)) onset(v); });
return el;
};
function sfOutputs() { // every DSP output known from the device list (also offline ones)
return S.order.map(id => S.devices[id]).filter(d => !d.demo || S.demo.enabled).map(d => {
const n = d.n_out || (d.model === "204" ? 4 : d.model === "408" ? 8 : 0);
return { d, outs: Array.from({ length: n }, (_, o) => o) };
}).filter(x => x.outs.length);
}
function sfEditor() {
const p = sfPlan(), s = p.speakers.find(x => x.id === sf.sel);
if (!s) return h("div", { class: "card sfedit" }, h("h3", {}, t("Speaker")),
h("p", { class: "info" }, t("Select a speaker in the plan, or add one above. Drag to move, use the white handle to aim, drag the reference cross to your listening / mixing position.")));
const up = (k, conv = v => v) => v => sfChange(() => { s[k] = conv(v); });
const typeSel = h("select", { onchange: () => sfChange(() => { const d = SF_TYPES[typeSel.value]; s.type = typeSel.value; Object.assign(s, d.role ? { role: d.role, cov: d.cov, spl: d.spl, h: d.h } : {}); }) },
Object.keys(SF_TYPES).map(k => h("option", { value: k, selected: s.type === k }, sfTypeLabel(k))));
const roleSel = h("select", { onchange: () => sfChange(() => { s.role = roleSel.value; if ((s.role === "delay" || s.role === "fill") && s.tx === s.x && s.ty === s.y) s.ty = Math.min(p.room.d, s.y + 6); }) },
["main", "sub", "delay", "fill"].map(r => h("option", { value: r, selected: s.role === r }, sfRoleLabel(r))));
const name = h("input", { type: "text", value: s.name, maxlength: 24 });
name.addEventListener("change", () => sfChange(() => { s.name = name.value.trim() || s.name; }));
const outs = sfOutputs().map(({ d, outs }) => h("div", { class: "sfouts" }, h("small", {}, d.name),
h("div", { class: "chips" }, outs.map(o => {
const key = `${d.id}:${o}`, on = s.outs.includes(key);
return h("button", { class: "chip" + (on ? " on" : ""), "aria-pressed": String(on),
onclick: () => sfChange(() => { s.outs = s.outs.includes(key) ? s.outs.filter(x => x !== key) : [...s.outs, key]; }) }, `Out ${o + 1}`);
}))));
return h("div", { class: "card sfedit", style: `--rc:${SF_ROLE_COLOR[s.role]}` },
h("h3", {}, h("span", { class: "dotc" }), h("span", { class: "grow" }, s.name),
h("button", { class: "small danger", onclick: () => sfRemove(s.id) }, t("Remove"))),
h("div", { class: "sfgrid" },
h("label", { class: "full" }, "Name", name),
h("label", {}, t("Type"), typeSel), h("label", {}, t("Role"), roleSel),
h("label", {}, "x (m)", sfNum(s.x, 0.1, up("x", v => clamp(v, 0, p.room.w)))),
h("label", {}, "y (m)", sfNum(s.y, 0.1, up("y", v => clamp(v, 0, p.room.d)))),
h("label", {}, t("Height (m)"), sfNum(s.h, 0.1, up("h", v => clamp(v, 0, 30)))),
h("label", {}, t("Aim (°)"), sfNum(s.aim, 1, up("aim", v => ((v + 540) % 360) - 180))),
h("label", {}, t("Coverage (°)"), sfNum(s.cov, 5, up("cov", v => clamp(v, 20, 360)))),
h("label", {}, t("Max SPL @1 m (dB)"), sfNum(s.spl, 1, up("spl", v => clamp(v, 80, 160))))),
s.role === "delay" || s.role === "fill" ? h("p", { class: "info" }, t("Its delay is aligned at the dashed target point (drag it to the middle of the area this speaker covers).")) : null,
h("div", { class: "sub" }, t("DSP outputs")), outs.length ? outs : h("p", { class: "info" }, t("No DSP in the device list yet.")));
}
function sfRoomCard() {
const p = sfPlan();
const set = (fn) => v => sfChange(q => {
fn(q, v);
for (const s of q.speakers) { s.x = clamp(s.x, 0, q.room.w); s.y = clamp(s.y, 0, q.room.d); s.tx = clamp(s.tx, 0, q.room.w); s.ty = clamp(s.ty, 0, q.room.d); }
q.ref.x = clamp(q.ref.x, 0, q.room.w); q.ref.y = clamp(q.ref.y, 0, q.room.d);
});
return h("div", { class: "card" }, h("h3", {}, t("Room")),
h("div", { class: "sfgrid" },
h("label", {}, t("Width (m)"), sfNum(p.room.w, 0.5, set((q, v) => { q.room.w = clamp(v, 4, 200); }))),
h("label", {}, t("Depth (m)"), sfNum(p.room.d, 0.5, set((q, v) => { q.room.d = clamp(v, 4, 300); }))),
h("label", {}, t("Stage width (m)"), sfNum(p.stage.w, 0.5, set((q, v) => { q.stage.w = clamp(v, 0, q.room.w); }))),
h("label", {}, t("Stage depth (m)"), sfNum(p.stage.d, 0.5, set((q, v) => { q.stage.d = clamp(v, 0, q.room.d / 2); }))),
h("label", {}, t("Temperature (°C)"), sfNum(p.temp, 1, set((q, v) => { q.temp = clamp(v, -10, 45); }))),
h("label", {}, t("Ear height (m)"), sfNum(p.ear, 0.1, set((q, v) => { q.ear = clamp(v, 0.5, 3); })))),
h("p", { class: "info" }, t("Speed of sound at {t} °C: {c} m/s.", { t: p.temp, c: sfSpeed(p).toFixed(1) })));
}
function sfSuggestCard() {
const items = sfSuggestions(sfPlan());
return h("div", { class: "card sfsug" }, h("h3", {}, t("Suggestions")),
items.length ? items.map(it => h("div", { class: "sfitem " + it.kind },
h("span", { class: "grow" }, it.text),
it.apply ? h("button", { class: "small on", onclick: () => sfChange(q => it.apply(q)) }, it.label) : null))
: h("p", { class: "info" }, t("Nothing to improve with the current layout.")));
}
function sfDelayCard() {
const p = sfPlan(), { ms, info } = sfDelays(p);
const rows = p.speakers.filter(s => ms[s.id] != null);
const cur = s => s.outs.map(k => {
const [id, o] = k.split(":"), d = S.devices[id];
return d && d.status === "online" && d.state ? d.state.outputs[+o]?.delay / 96 : null;
});
const apply = async list => {
let n = 0, skipped = 0;
for (const s of list) for (const k of s.outs) {
const [id, o] = k.split(":"), d = S.devices[id];
if (!d || d.status !== "online" || !d.state) { skipped++; continue; }
try { await api("POST", `/api/devices/${id}/set`, { kind: "out", idx: +o, param: "delay", value: clamp(Math.round(ms[s.id] * 96), 0, 65280) }); n++; }
catch (e) { toast(t("Error: ") + trMsg(e.message)); return; }
}
toast(t("{n} output delay(s) set", { n }) + (skipped ? " · " + t("{n} output(s) not connected", { n: skipped }) : ""));
};
const withOuts = rows.filter(s => s.outs.length);
return h("div", { class: "card sfdelays" },
h("h3", {}, h("span", { class: "grow" }, t("Delays")),
withOuts.length ? h("button", { class: "small on", onclick: () => apply(withOuts) }, t("Apply all")) : null),
rows.length ? h("table", { class: "sftable" },
h("tr", {}, h("th", {}, t("Speaker")), h("th", {}, t("Distance")), h("th", {}, t("Delay")), h("th", {}, t("Now on DSP")), h("th", {}, "")),
rows.map(s => {
const pt = info[s.id] === "target" ? [s.tx, s.ty] : [p.ref.x, p.ref.y], now = cur(s).filter(v => v != null);
return h("tr", {},
h("td", {}, h("span", { class: "dotc", style: `--rc:${SF_ROLE_COLOR[s.role]}` }), s.name,
h("small", {}, s.outs.length ? s.outs.map(k => { const [id, o] = k.split(":"); return `${S.devices[id]?.name || id} Out ${+o + 1}`; }).join(", ") : t("no output"))),
h("td", {}, `${sfR(p, s, pt[0], pt[1]).toFixed(1)} m`),
h("td", { class: "num" }, `${ms[s.id].toFixed(2)} ms`),
h("td", { class: "num" }, now.length ? now.map(v => v.toFixed(2)).join(" / ") + " ms" : "—"),
h("td", {}, s.outs.length ? h("button", { class: "small", onclick: () => apply([s]) }, t("Apply")) : null));
})) : h("p", { class: "info" }, t("Add speakers to calculate delays.")),
h("p", { class: "info" }, t("Mains and subs are aligned at the reference position, delay and fill speakers at their target point plus {ms} ms so the mains are heard first.", { ms: p.precedence }),
" ", h("label", { class: "inline" }, t("Offset (ms)"), sfNum(p.precedence, 0.5, v => sfChange(q => { q.precedence = clamp(v, 0, 30); }), { class: "short" }))));
}
function sfPanels() { // rebuild everything except the canvas
const box = sf.panels.side;
if (!box || !box.isConnected) return;
box.replaceChildren(sfEditor(), sfSuggestCard(), sfDelayCard(), sfRoomCard());
sfLegend();
}
function sfRefresh() { sfDraw(); sfPanels(); }
function viewSoundField() {
const p = sfPlan();
if (sf.sel && !p.speakers.some(s => s.id === sf.sel)) sf.sel = null;
const cv = h("canvas", { class: "sfcanvas", tabindex: "0", "aria-label": t("Room plan") });
sf.canvas = cv;
sfBindCanvas(cv);
const addBtn = (type, role, label) => h("button", { class: "small", onclick: () => sfChange(q => {
const n = q.speakers.filter(s => s.role === role).length + 1;
const y = role === "delay" ? q.room.d * 0.55 : role === "fill" ? Math.max(0.3, q.stage.d - 0.2) : role === "sub" ? Math.min(q.room.d, q.stage.d + 0.6) : Math.max(0.5, q.stage.d - 0.3);
const s = sfNew(q, type, q.room.w / 2 + (n - 1) * 1.5, y, `${label} ${n}`);
s.role = role;
if (role === "delay") s.h = 3;
q.speakers.push(s); sf.sel = s.id;
}) }, "+ " + label);
const modeSeg = h("div", { class: "seg small" });
const hzSel = h("select", { class: "short", "aria-label": t("Sub frequency"), onchange: () => { store.set("dsp.sfhz", hzSel.value); sfDraw(); } },
SF_SUB_HZ.map(f => h("option", { value: f, selected: f === sfSubHz() }, `${f} Hz`)));
const setMode = m => {
store.set("dsp.sfmap", m);
modeSeg.replaceChildren(...[["level", t("Level")], ["sub", "Sub"], ["time", t("Timing")], ["off", t("Off")]].map(([k, label]) =>
h("button", { class: sfMode() === k ? "on" : "", onclick: () => { setMode(k); sfDraw(); } }, label)));
hzSel.hidden = m !== "sub";
};
setMode(sfMode());
sf.panels.legend = h("div", { class: "sflegend" });
sf.panels.readout = h("div", { class: "sfreadout" });
sf.panels.side = h("div", { class: "sfside" });
requestAnimationFrame(() => { sfDraw(); sfPanels(); });
new ResizeObserver(() => { if (!sf.drag) sfDraw(); }).observe(cv);
return h("div", { class: "sflayout" },
h("div", { class: "card sfmain" },
h("div", { class: "sfbar" },
h("h3", {}, "SoundField"),
h("div", { class: "sfadd" }, addBtn("top12", "main", t("Main")), addBtn("sub18", "sub", "Sub"), addBtn("top12", "delay", "Delay"), addBtn("fill8", "fill", "Fill")),
h("div", { class: "sfmode" }, modeSeg, hzSel)),
cv, h("div", { class: "sffoot" }, sf.panels.legend, sf.panels.readout),
h("p", { class: "info" }, t("A planning aid: free field without reflections, coverage from the nominal angle. Check the result by ear or measurement."))),
sf.panels.side);
}
+55
View File
@@ -510,3 +510,58 @@ button.chip.ov.on i { background: var(--oc); }
body.testlock #viewtabs button:disabled, body.testlock #btn-settings:disabled, body.testlock .devtab:disabled { opacity: .35; cursor: not-allowed; } body.testlock #viewtabs button:disabled, body.testlock #btn-settings:disabled, body.testlock .devtab:disabled { opacity: .35; cursor: not-allowed; }
.testbanner small { display: block; font-weight: 400; margin-top: 2px; color: var(--dim); } .testbanner small { display: block; font-weight: 400; margin-top: 2px; color: var(--dim); }
.pol { display: inline-block; margin-left: 4px; font-size: 13px; font-weight: 700; line-height: 14px; color: #e879f9; vertical-align: -1px; } .pol { display: inline-block; margin-left: 4px; font-size: 13px; font-weight: 700; line-height: 14px; color: #e879f9; vertical-align: -1px; }
/* ---- global mute */
#btn-muteall svg { width: 22px; height: 22px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
#btn-muteall.on { width: auto; padding: 0 12px; gap: 6px; background: #991b1b; border-color: var(--bad); color: #fff; font-weight: 700;
letter-spacing: .06em; animation: mutepulse 1.6s ease-in-out infinite; }
@keyframes mutepulse { 50% { box-shadow: 0 0 14px #ef4444aa; } }
/* ---- copy dialog */
.copydlg .sub { margin: 12px 0 6px; }
.copygroups { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 6px 14px; }
.copygroups label.chk { display: flex; align-items: center; gap: 8px; font-size: 14px; }
.copygroups label.chk input { width: 18px; height: 18px; }
.copydev .chips { margin-top: 0; }
button.chip.on { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 20%, var(--panel)); color: var(--text); }
/* ---- SoundField */
.sflayout { display: grid; grid-template-columns: minmax(0, 1fr); gap: 14px; }
@media (min-width: 1100px) { .sflayout { grid-template-columns: minmax(0, 1.65fr) minmax(320px, 1fr); align-items: start; } }
.sfmain { padding-bottom: 10px; }
.sfbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin-bottom: 10px; }
.sfbar h3 { margin: 0 auto 0 0; }
.sfadd { display: flex; flex-wrap: wrap; gap: 6px; }
.sfmode { display: flex; gap: 6px; align-items: center; }
.sfmode select.short { width: auto; padding: 4px 8px; min-height: 0; font-size: 12px; }
.sfcanvas { display: block; width: 100%; height: 480px; touch-action: none; border-radius: 8px; outline: none; cursor: crosshair; }
.sffoot { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 6px 16px; margin-top: 8px; min-height: 18px; font-size: 12px; color: var(--dim); }
.sflegend { display: flex; flex-wrap: wrap; gap: 4px 12px; align-items: center; }
.sflegend .sw { display: inline-flex; align-items: center; gap: 5px; }
.sflegend .sw i { width: 12px; height: 12px; border-radius: 3px; opacity: .85; }
.sflegend .stat { color: var(--text); }
.sfreadout { font-variant-numeric: tabular-nums; }
.sfside { display: grid; gap: 14px; }
.sfgrid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px 10px; }
.sfgrid label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--dim); }
.sfgrid label.full { grid-column: 1 / -1; }
.sfgrid input, .sfgrid select { width: 100%; min-width: 0; }
.sfedit .dotc, .sftable .dotc { display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: var(--rc); margin-right: 8px; flex: none; }
.sfedit h3 { display: flex; align-items: center; }
.sfedit .sub { margin: 12px 0 4px; }
.sfouts { margin-top: 6px; }
.sfouts small { color: var(--dim); }
.sfouts .chips { margin-top: 4px; }
.sfsug .sfitem { display: flex; gap: 10px; align-items: center; padding: 9px 10px; border-radius: 8px; margin-top: 8px; font-size: 13px;
background: var(--panel2); border-left: 3px solid var(--accent); }
.sfsug .sfitem.warn { border-left-color: var(--warn); }
.sfsug .sfitem.ok { border-left-color: var(--ok); }
.sfsug .sfitem.info { border-left-color: var(--dim); }
.sfsug .sfitem button { flex: none; }
.sftable { width: 100%; border-collapse: collapse; font-size: 13px; }
.sftable th { text-align: left; font-weight: 600; color: var(--dim); font-size: 11px; text-transform: uppercase; letter-spacing: .05em; padding: 4px 6px; }
.sftable td { padding: 6px; border-top: 1px solid var(--line); vertical-align: middle; }
.sftable td small { display: block; color: var(--dim); font-size: 11px; margin-left: 18px; }
.sftable td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.sfdelays .info label.inline { display: inline-flex; align-items: center; gap: 6px; margin-top: 6px; }
.sfdelays .info input.short { width: 70px; }