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

+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);
}