- Python stdlib server with SSE live updates, PIN login, remote access - Vanilla JS web UI (English/German): mixer, channel, routing, links, limiter calculator - Preset file export/import with undo, settings backup, lock for the desktop app - Network (TCP 9761) and USB HID transport (Windows, macOS, Linux) - Desktop app via pywebview, Raspberry Pi SD card writer, simulator and protocol tests - README with import guide for Claude Code, CLAUDE.md, protocol documentation Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1730 lines
94 KiB
JavaScript
1730 lines
94 KiB
JavaScript
"use strict";
|
||
|
||
// ------------------------------------------------------------------ value scales (see PROTOCOL.md)
|
||
|
||
const Q_TABLE = [0.4,0.42,0.45,0.47,0.5,0.53,0.56,0.59,0.63,0.67,0.71,0.75,0.79,0.84,0.89,0.94,1.0,1.06,1.12,1.19,
|
||
1.26,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,2.4,2.5,2.7,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.2,4.5,4.8,5.0,5.3,5.7,6.0,
|
||
6.3,6.7,7.1,7.6,8.0,8.5,9.0,9.5,10.1,10.7,11.3,12.0,12.7,13.5,14.0,15,16,17,18,19,20,21,23,24,25,27,29,30,32,34,
|
||
36,38,40,43,45,48,51,54,57,60,64,68,72,76,81,85,91,96,102,108,114,121,128];
|
||
const RATIOS = ["1:1.0","1:1.1","1:1.3","1:1.5","1:1.7","1:2.0","1:2.5","1:3.0","1:3.5","1:4.0","1:5.0","1:6.0",
|
||
"1:8.0","1:10","1:20","Limit"];
|
||
const PEQ_TYPES = ["Peak","Low Shelf","High Shelf","HPF -6","HPF -12","LPF -6","LPF -12","Allpass 1","Allpass 2"];
|
||
const PEQ_SHORT = ["PK","LS","HS","HP6","HP12","LP6","LP12","AP1","AP2"];
|
||
const SLOPES = ["Bypass","BW -6","BL -6","BW -12","BL -12","LK -12","BW -18","BL -18","BW -24","BL -24","LK -24",
|
||
"BW -30","BL -30","BW -36","BL -36","LK -36","BW -42","BL -42","BW -48","BL -48","LK -48"];
|
||
const GEQ_FREQS = ["20","25","31","40","50","63","80","100","125","160","200","250","315","400","500","630","800",
|
||
"1k","1.2k","1.6k","2k","2.5k","3.1k","4k","5k","6.3k","8k","10k","12k","16k","20k"];
|
||
const IN_COLORS = ["#38bdf8", "#a78bfa", "#34d399", "#f472b6"];
|
||
|
||
const gainDb = r => r < 80 ? r / 2 - 60 : (r - 280) / 10;
|
||
const dbGain = db => Math.max(0, Math.min(400, db < -20 ? Math.round((db + 60) * 2) : Math.round(db * 10 + 280)));
|
||
const freqHz = r => 1000 * Math.pow(2, (r - 170) / 30);
|
||
const hzFreq = hz => Math.max(0, Math.min(300, Math.round(170 + 30 * Math.log2(Math.max(hz, 1) / 1000))));
|
||
const eqDb = r => (r - 120) / 10;
|
||
const sign = v => (v > 0 ? "+" : "") + v.toFixed(1);
|
||
const fmtHz = hz => hz >= 1000 ? (hz / 1000).toFixed(hz >= 10000 ? 1 : 2) + " kHz" : hz.toFixed(hz < 100 ? 1 : 0) + " Hz";
|
||
const fmtHzShort = hz => hz >= 1000 ? +(hz / 1000).toFixed(hz >= 10000 ? 0 : 1) + "k" : String(Math.round(hz));
|
||
const nearestQ = q => Q_TABLE.reduce((best, v, i) => Math.abs(v - q) < Math.abs(Q_TABLE[best] - q) ? i : best, 0);
|
||
const num = s => parseFloat(String(s).replace(",", ".").replace(/[^0-9.+-]/g, ""));
|
||
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
|
||
|
||
// Parameter specs: raw range, display/parse in user units, optional 0-dB detent ("zero")
|
||
const SPEC = {
|
||
gain: { min: 0, max: 400, zero: 280, fmt: r => sign(gainDb(r)) + " dB", parse: s => dbGain(num(s)), hint: "-60 … +12 dB" },
|
||
mix: { min: 0, max: 280, zero: 280, fmt: r => sign(gainDb(r)) + " dB", parse: s => Math.min(280, dbGain(num(s))), hint: "-60 … 0 dB" },
|
||
delay: { min: 0, max: 65280, def: 0, fmt: r => (r / 96).toFixed(2) + " ms · " + (r / 96 * 0.343).toFixed(2) + " m",
|
||
parse: s => /m\s*$/i.test(s) && !/ms/i.test(s) ? Math.round(num(s) / 0.343 * 96) : Math.round(num(s) * 96),
|
||
hint: t("in ms, or metres with “m” (e.g. 2.5m)") },
|
||
freq: { min: 0, max: 300, fmt: r => fmtHz(freqHz(r)), parse: s => hzFreq(/k/i.test(s) ? num(s) * 1000 : num(s)), hint: t("20 Hz … 20 kHz, e.g. 1.2k") },
|
||
eqgain: { min: 0, max: 240, zero: 120, fmt: r => sign(eqDb(r)) + " dB", parse: s => Math.round(num(s) * 10 + 120), hint: "-12 … +12 dB" },
|
||
q: { min: 0, max: 100, fmt: r => "Q " + Q_TABLE[r], parse: s => nearestQ(num(s)), hint: "0.4 … 128" },
|
||
gthresh: { min: 0, max: 180, fmt: r => sign((r - 180) / 2) + " dB", parse: s => Math.round(num(s) * 2 + 180), hint: "-90 … 0 dB" },
|
||
thresh: { min: 0, max: 220, fmt: r => sign((r - 180) / 2) + " dB", parse: s => Math.round(num(s) * 2 + 180), hint: "-90 … +20 dB" },
|
||
attack: { min: 0, max: 998, fmt: r => (r + 1) + " ms", parse: s => Math.round(num(s)) - 1, hint: "1 … 999 ms" },
|
||
release: { min: 9, max: 2999, fmt: r => (r + 1) + " ms", parse: s => Math.round(num(s)) - 1, hint: "10 … 3000 ms" },
|
||
hold: { min: 9, max: 998, fmt: r => (r + 1) + " ms", parse: s => Math.round(num(s)) - 1, hint: "10 … 999 ms" },
|
||
ratio: { min: 0, max: 15, fmt: r => RATIOS[r], parse: s => Math.max(0, RATIOS.findIndex(x => x.endsWith(s))), hint: t("e.g. 4.0") },
|
||
knee: { min: 0, max: 12, fmt: r => r + " dB", parse: s => Math.round(num(s)), hint: "0 … 12 dB" },
|
||
};
|
||
const GAIN_TICKS = [[400, "+12"], [340, "+6"], [280, "0"], [220, "-6"], [160, "-12"], [80, "-20"], [40, "-40"], [0, "-60"]];
|
||
|
||
// ------------------------------------------------------------------ app state
|
||
|
||
const store = {
|
||
get: k => { try { return localStorage.getItem(k); } catch { return null; } },
|
||
set: (k, v) => { try { localStorage.setItem(k, v); } catch { /* private mode */ } },
|
||
};
|
||
const S = {
|
||
devices: {}, order: [], cur: store.get("dsp.cur"),
|
||
view: store.get("dsp.view") || "mixer", settings: false,
|
||
sel: { kind: "in", idx: 0 }, band: 0, busy: false, dirty: false,
|
||
routeOpen: null, es: null, linkSel: { in: [], out: [] },
|
||
lim: { amps: [], assign: {}, ref: {} },
|
||
};
|
||
const $ = sel => document.querySelector(sel);
|
||
const main = $("#main");
|
||
|
||
function h(tag, attrs = {}, ...children) {
|
||
const el = document.createElement(tag);
|
||
for (const [k, v] of Object.entries(attrs || {})) {
|
||
if (v == null || v === false) continue;
|
||
if (k.startsWith("on")) el.addEventListener(k.slice(2), v);
|
||
else if (k === "class") el.className = v;
|
||
else if (k === "style") el.style.cssText = v;
|
||
else el.setAttribute(k, v === true ? "" : v);
|
||
}
|
||
for (const c of children.flat()) if (c != null && c !== false) el.append(c.nodeType ? c : document.createTextNode(c));
|
||
return el;
|
||
}
|
||
const svgIcon = d => { const s = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||
s.setAttribute("viewBox", "0 0 24 24"); s.innerHTML = d; return s; };
|
||
const ICON = {
|
||
prev: '<path d="M15 5l-7 7 7 7"/>', next: '<path d="M9 5l7 7-7 7"/>',
|
||
edit: '<path d="M4 20h4L19 9l-4-4L4 16z"/>', logout: '<path d="M15 4h4v16h-4M10 8l-4 4 4 4M6 12h10"/>',
|
||
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"/>',
|
||
unlock: '<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 7.5-2"/>',
|
||
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"/>',
|
||
};
|
||
|
||
function toast(msg) {
|
||
const el = $("#toast");
|
||
el.textContent = msg; el.hidden = false;
|
||
clearTimeout(toast.timer); toast.timer = setTimeout(() => (el.hidden = true), 2500);
|
||
}
|
||
const buzz = () => { try { navigator.vibrate && navigator.vibrate(8); } catch { /* unsupported */ } };
|
||
|
||
async function api(method, path, body) {
|
||
const r = await fetch(path, { method, headers: { "Content-Type": "application/json" },
|
||
body: body ? JSON.stringify(body) : undefined, credentials: "same-origin" });
|
||
const data = await r.json().catch(() => ({}));
|
||
if (r.status === 401 && !path.startsWith("/api/login")) { showLogin(); throw new Error(t("Please log in")); }
|
||
if (!r.ok) throw new Error(trMsg(data.error || r.statusText));
|
||
return data;
|
||
}
|
||
|
||
const dev = () => S.devices[S.cur];
|
||
const where = d => d.transport === "usb" ? "USB" : d.host; // connection label
|
||
const chans = (d, kind) => d.state[kind === "in" ? "inputs" : "outputs"];
|
||
const chLabel = (kind, i) => kind === "in" ? "In " + String.fromCharCode(65 + i) : "Out " + (i + 1);
|
||
// Channel names: the DSP keeps 8 ASCII characters; on top of that a name must fit the mixer strip,
|
||
// so wide letters (W, M, @) count more. Every other place showing names is at least as wide.
|
||
const NAME_MAX = 8, NAME_PX = 76;
|
||
const UMLAUT = { ä: "ae", ö: "oe", ü: "ue", Ä: "Ae", Ö: "Oe", Ü: "Ue", ß: "ss" };
|
||
let nameCtx;
|
||
function nameWidth(s) {
|
||
if (!nameCtx) {
|
||
nameCtx = document.createElement("canvas").getContext("2d");
|
||
const probe = h("span", { class: "nm", style: "position:absolute;visibility:hidden" });
|
||
const head = h("div", { class: "strip-head", style: "position:absolute;visibility:hidden" }, probe);
|
||
document.body.append(head);
|
||
const cs = getComputedStyle(probe);
|
||
nameCtx.font = `${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;
|
||
head.remove();
|
||
}
|
||
return nameCtx.measureText(s).width;
|
||
}
|
||
function cleanName(s) {
|
||
s = [...s.replace(/[äöüÄÖÜß]/g, c => UMLAUT[c])].filter(c => c >= " " && c <= "~").join("").slice(0, NAME_MAX);
|
||
while (s && nameWidth(s) > NAME_PX) s = s.slice(0, -1);
|
||
return s;
|
||
}
|
||
|
||
const chTitle = (d, kind, i) => { const n = chans(d, kind)[i].name; return n ? `${chLabel(kind, i)} · ${n}` : chLabel(kind, i); };
|
||
|
||
// Channel links (see protocol.py): a free channel's mask is its own bit, the first channel of a
|
||
// group holds all members' bits, the others 0. The DSP mirrors changes within a group itself.
|
||
const LINK_COLORS = ["#f59e0b", "#22d3ee", "#a3e635", "#f472b6"];
|
||
function linkGroups(list) {
|
||
const seen = new Set(), groups = [];
|
||
list.forEach((ch, i) => {
|
||
if (seen.has(i)) return;
|
||
const mask = ch.link ?? (1 << i);
|
||
const g = list.map((_, j) => j).filter(j => (j === i || mask >> j & 1) && !seen.has(j));
|
||
g.forEach(j => seen.add(j));
|
||
groups.push(g);
|
||
});
|
||
return groups;
|
||
}
|
||
const linkedGroups = (d, kind) => linkGroups(chans(d, kind)).filter(g => g.length > 1);
|
||
function linkInfo(d, kind, i) { // {group, color} if the channel is linked, else null
|
||
const gs = linkedGroups(d, kind), n = gs.findIndex(g => g.includes(i));
|
||
return n < 0 ? null : { group: gs[n], color: LINK_COLORS[n % LINK_COLORS.length] };
|
||
}
|
||
const linkBadge = (d, kind, i) => {
|
||
const l = linkInfo(d, kind, i);
|
||
return l ? h("span", { class: "lnk", style: `--lc:${l.color}`, title: t("Linked: ") + l.group.map(j => chLabel(kind, j)).join(" + ") },
|
||
svgIcon(ICON.link)) : null;
|
||
};
|
||
|
||
function getPath(obj, path) {
|
||
return path.split(".").reduce((o, k) => o[Array.isArray(o) ? +k : k], obj);
|
||
}
|
||
function setPath(obj, path, value) {
|
||
const keys = path.split(".");
|
||
const last = keys.pop();
|
||
const node = keys.reduce((o, k) => o[Array.isArray(o) ? +k : k], obj);
|
||
node[Array.isArray(node) ? +last : last] = value;
|
||
}
|
||
|
||
// While the user drags something, incoming updates must not rebuild the DOM under their finger.
|
||
function beginBusy() { S.busy = true; }
|
||
function endBusy() { S.busy = false; if (S.dirty) { S.dirty = false; render(); } }
|
||
|
||
// ------------------------------------------------------------------ dialogs (no native prompt/confirm: they are blocked in some webviews)
|
||
|
||
function modal({ title, body, actions, onOpen }) {
|
||
return new Promise(resolve => {
|
||
const root = $("#modal");
|
||
let done = false;
|
||
const close = v => {
|
||
if (done) return; done = true;
|
||
root.hidden = true; root.replaceChildren();
|
||
document.removeEventListener("keydown", onKey, true);
|
||
resolve(v);
|
||
};
|
||
const primary = actions.find(a => a.primary);
|
||
const btns = actions.map(a => h("button", { class: a.cls || (a.primary ? "on" : ""),
|
||
onclick: () => { const v = a.value ? a.value() : null; if (v !== undefined) close(v); } }, a.label));
|
||
const onKey = e => {
|
||
if (e.key === "Escape") { e.preventDefault(); close(null); }
|
||
else if (e.key === "Enter" && primary && e.target.tagName !== "TEXTAREA") {
|
||
e.preventDefault(); btns[actions.indexOf(primary)].click();
|
||
}
|
||
};
|
||
document.addEventListener("keydown", onKey, true);
|
||
root.replaceChildren(
|
||
h("div", { class: "backdrop", onclick: () => close(null) }),
|
||
h("div", { class: "dialog", role: "dialog", "aria-modal": "true", "aria-label": title },
|
||
h("h2", {}, title), body, h("div", { class: "dlg-actions" }, btns)));
|
||
root.hidden = false;
|
||
const first = root.querySelector("input, select");
|
||
setTimeout(() => { if (first) { first.focus(); first.select && first.select(); } else if (primary) btns[actions.indexOf(primary)].focus(); onOpen && onOpen(); }, 30);
|
||
});
|
||
}
|
||
|
||
const askConfirm = (title, text, okLabel = "OK", danger = false) => modal({
|
||
title, body: h("p", { class: "dlg-text" }, text),
|
||
actions: [{ label: t("Cancel") }, { label: okLabel, primary: true, cls: danger ? "danger-on" : "on", value: () => true }],
|
||
});
|
||
|
||
// ------------------------------------------------------------------ files (desktop app: native dialogs via pywebview)
|
||
|
||
const today = () => new Date().toISOString().slice(0, 10);
|
||
const fileSafe = s => (s || "").replace(/[^\w\- .]+/g, "").trim().replace(/\s+/g, "_") || "preset";
|
||
|
||
async function saveFile(name, obj) {
|
||
const text = JSON.stringify(obj, null, 2);
|
||
const papi = window.pywebview && window.pywebview.api;
|
||
if (papi && papi.save_file) return papi.save_file(name, text);
|
||
const a = h("a", { href: URL.createObjectURL(new Blob([text], { type: "application/json" })), download: name });
|
||
document.body.append(a); a.click(); a.remove();
|
||
setTimeout(() => URL.revokeObjectURL(a.href), 10000);
|
||
return true;
|
||
}
|
||
|
||
// -> { name, b64, json } (json = parsed content if the file is JSON, else null), or null if cancelled
|
||
async function openFile() {
|
||
let name, bytes;
|
||
const papi = window.pywebview && window.pywebview.api;
|
||
if (papi && papi.open_file) {
|
||
const f = await papi.open_file();
|
||
if (!f) return null;
|
||
name = f.name; bytes = Uint8Array.from(atob(f.data), c => c.charCodeAt(0));
|
||
} else {
|
||
const file = await new Promise(resolve => {
|
||
const inp = h("input", { type: "file", accept: ".json,.bin,application/json,application/octet-stream", hidden: true });
|
||
inp.addEventListener("change", () => resolve(inp.files[0] || null));
|
||
document.body.append(inp); inp.click(); setTimeout(() => inp.remove(), 60000);
|
||
});
|
||
if (!file) return null;
|
||
if (file.size > 5e6) throw new Error(t("File is too large"));
|
||
name = file.name; bytes = new Uint8Array(await file.arrayBuffer());
|
||
}
|
||
let json = null;
|
||
try { json = JSON.parse(new TextDecoder().decode(bytes)); } catch { /* binary */ }
|
||
let bin = "";
|
||
bytes.forEach(b => (bin += String.fromCharCode(b)));
|
||
return { name, b64: btoa(bin), json };
|
||
}
|
||
|
||
function askValue(label, spec, raw) {
|
||
const input = h("input", { type: "text", value: spec.fmt(raw).replace(/^Q /, "").replace(/ ·.*$/, ""),
|
||
autocomplete: "off", spellcheck: "false", enterkeyhint: "done" });
|
||
const quick = spec.zero != null
|
||
? h("button", { class: "chip", onclick: () => { input.value = "0"; input.focus(); } }, "0 dB") : null;
|
||
return modal({
|
||
title: label,
|
||
body: h("div", {}, h("div", { class: "row" }, input, quick), h("p", { class: "info" }, spec.hint || "")),
|
||
actions: [{ label: t("Cancel") }, { label: t("Apply"), primary: true, value: () => {
|
||
const s = input.value.trim();
|
||
if (!s || isNaN(num(s))) { input.classList.add("bad"); return undefined; }
|
||
return clamp(spec.parse(s), spec.min, spec.max);
|
||
} }],
|
||
});
|
||
}
|
||
|
||
// ------------------------------------------------------------------ sending (throttled per parameter)
|
||
|
||
// Controls on screen that can follow a value without re-rendering (linked channels, other devices'
|
||
// changes while a fader is held): "dev|kind|idx|param" -> [update functions]. Rebuilt on every render.
|
||
const live = new Map();
|
||
function onLive(kind, idx, param, fn) {
|
||
const key = `${S.cur}|${kind}|${idx}|${param}`;
|
||
live.set(key, [...(live.get(key) || []), fn]);
|
||
}
|
||
const showLive = (key, v) => (live.get(key) || []).forEach(fn => fn(v));
|
||
const LINK_OWN = ["name", "mix", "matrix", "link"]; // per channel even when linked (see protocol.py)
|
||
|
||
const sendTimers = new Map(), sendPending = new Map(), recentlySet = new Map();
|
||
function setParam(kind, idx, param, value) {
|
||
const d = dev();
|
||
if (!d || !d.state) return;
|
||
setPath(chans(d, kind)[idx], param, value);
|
||
const key = `${d.id}|${kind}|${idx}|${param}`;
|
||
recentlySet.set(key, Date.now());
|
||
// the DSP applies it to linked channels itself: move them along right away
|
||
const li = !LINK_OWN.includes(param.split(".")[0]) && linkInfo(d, kind, idx);
|
||
if (li) for (const j of li.group) if (j !== idx) {
|
||
setPath(chans(d, kind)[j], param, JSON.parse(JSON.stringify(value)));
|
||
recentlySet.set(`${d.id}|${kind}|${j}|${param}`, Date.now());
|
||
showLive(`${d.id}|${kind}|${j}|${param}`, value);
|
||
}
|
||
const body = { kind, idx, param, value };
|
||
const fire = b => api("POST", `/api/devices/${d.id}/set`, b).catch(e => toast(t("Error: ") + e.message));
|
||
if (sendTimers.has(key)) { sendPending.set(key, body); return; }
|
||
fire(body);
|
||
sendTimers.set(key, setTimeout(function tick() {
|
||
if (sendPending.has(key)) {
|
||
fire(sendPending.get(key)); sendPending.delete(key);
|
||
sendTimers.set(key, setTimeout(tick, 60));
|
||
} else sendTimers.delete(key);
|
||
}, 60));
|
||
}
|
||
|
||
// ------------------------------------------------------------------ controls
|
||
|
||
// −/+ button with press-and-hold auto-repeat that speeds up the longer it is held
|
||
function stepper(dir, fn) {
|
||
const b = h("button", { class: "step", "aria-label": dir > 0 ? t("Increase") : t("Decrease"), tabindex: "-1" }, dir > 0 ? "+" : "−");
|
||
let timer = null, n = 0;
|
||
const stop = () => { if (timer !== null) { clearTimeout(timer); timer = null; endBusy(); } };
|
||
b.addEventListener("pointerdown", e => {
|
||
e.preventDefault(); beginBusy(); n = 0; fn(dir);
|
||
timer = setTimeout(function rep() { n++; fn(dir * (n > 30 ? 10 : n > 12 ? 3 : 1)); timer = setTimeout(rep, 70); }, 380);
|
||
});
|
||
for (const ev of ["pointerup", "pointerleave", "pointercancel"]) b.addEventListener(ev, stop);
|
||
b.addEventListener("click", e => { if (e.detail === 0) fn(dir); }); // keyboard activation
|
||
return b;
|
||
}
|
||
|
||
// Snap to the detent if a dragged value lands within `px` pixels of it.
|
||
function detent(v, zero, range, lengthPx, px = 10) {
|
||
if (zero == null) return v;
|
||
return Math.abs(v - zero) <= Math.max(1, range * px / Math.max(60, lengthPx)) ? zero : v;
|
||
}
|
||
|
||
function paramSlider(label, kind, idx, path, specName, onChange) {
|
||
const spec = SPEC[specName];
|
||
const cur = () => getPath(chans(dev(), kind)[idx], path);
|
||
const val = h("button", { class: "val", title: t("Enter value") }, spec.fmt(cur()));
|
||
const input = h("input", { type: "range", min: spec.min, max: spec.max, step: 1, value: cur(), "aria-label": label });
|
||
const home = spec.zero ?? spec.def;
|
||
const wrap = h("div", { class: "param" + (cur() === spec.zero ? " atzero" : "") });
|
||
let dragging = false;
|
||
const commit = v => {
|
||
v = clamp(Math.round(v), spec.min, spec.max);
|
||
input.value = v;
|
||
if (v === cur()) return;
|
||
if (v === spec.zero) buzz();
|
||
val.textContent = spec.fmt(v);
|
||
wrap.classList.toggle("atzero", v === spec.zero);
|
||
setParam(kind, idx, path, v);
|
||
onChange && onChange(v);
|
||
};
|
||
onLive(kind, idx, path, v => { input.value = v; val.textContent = spec.fmt(v); wrap.classList.toggle("atzero", v === spec.zero); });
|
||
input.addEventListener("input", () => {
|
||
let v = +input.value;
|
||
if (dragging) v = detent(v, spec.zero, spec.max - spec.min, input.clientWidth - 26);
|
||
commit(v);
|
||
});
|
||
let lastTap = 0;
|
||
input.addEventListener("pointerdown", () => {
|
||
dragging = true; beginBusy();
|
||
const now = Date.now();
|
||
if (home != null && now - lastTap < 320) setTimeout(() => commit(home), 0);
|
||
lastTap = now;
|
||
});
|
||
const release = () => { if (dragging) { dragging = false; endBusy(); } };
|
||
input.addEventListener("pointerup", release);
|
||
input.addEventListener("pointercancel", release);
|
||
input.addEventListener("blur", release);
|
||
val.addEventListener("click", async () => {
|
||
const v = await askValue(label, spec, cur());
|
||
if (v != null) commit(v);
|
||
});
|
||
const track = h("div", { class: "rangewrap" },
|
||
spec.zero != null ? h("div", { class: "zmark", style: `--f:${(spec.zero - spec.min) / (spec.max - spec.min)}` }) : null, input);
|
||
wrap.append(
|
||
h("div", { class: "lbl" }, h("span", {}, label),
|
||
h("div", { class: "valbox" }, stepper(-1, d => commit(cur() + d)), val, stepper(1, d => commit(cur() + d)))),
|
||
track);
|
||
return wrap;
|
||
}
|
||
|
||
function paramSelect(kind, idx, path, options, onChange, label) {
|
||
const ch = chans(dev(), kind)[idx];
|
||
const sel = h("select", { "aria-label": label || path, onchange: () => { setParam(kind, idx, path, +sel.value); onChange && onChange(+sel.value); } },
|
||
options.map((o, i) => h("option", { value: i, selected: getPath(ch, path) === i }, o)));
|
||
return sel;
|
||
}
|
||
|
||
function toggleBtn(label, kind, idx, path, cls = "", onChange) {
|
||
const ch = chans(dev(), kind)[idx];
|
||
const b = h("button", { class: (getPath(ch, path) ? "on " : "") + cls, "aria-pressed": String(!!getPath(ch, path)) }, label);
|
||
b.addEventListener("click", () => {
|
||
const v = !getPath(chans(dev(), kind)[idx], path);
|
||
b.classList.toggle("on", v); b.setAttribute("aria-pressed", String(v));
|
||
setParam(kind, idx, path, v);
|
||
onChange && onChange(v);
|
||
});
|
||
onLive(kind, idx, path, v => { b.classList.toggle("on", !!v); b.setAttribute("aria-pressed", String(!!v)); onChange && onChange(v); });
|
||
return b;
|
||
}
|
||
|
||
// Vertical fader: drag the cap (relative), 0-dB detent, double tap on the cap = 0 dB, wheel, keyboard.
|
||
// Touching the fader anywhere else does nothing, so a swipe there scrolls (e.g. the mixer sideways).
|
||
function fader({ min, max, value, zero, ticks, label, onInput }) {
|
||
const cap = h("div", { class: "cap" });
|
||
const tickEls = (ticks || []).map(([v, label]) => h("div", { class: "tick" + (v === zero ? " z" : ""), style: `--f:${(v - min) / (max - min)}` }, label ? h("span", {}, label) : null));
|
||
const el = h("div", { class: "fader", tabindex: "0", role: "slider", "aria-label": label || "Fader",
|
||
"aria-valuemin": min, "aria-valuemax": max }, h("div", { class: "track" }), tickEls, cap);
|
||
let cur = value;
|
||
const place = () => {
|
||
cap.style.setProperty("--f", (cur - min) / (max - min));
|
||
el.setAttribute("aria-valuenow", cur);
|
||
el.classList.toggle("atzero", cur === zero);
|
||
};
|
||
const set = (v, snap) => {
|
||
v = clamp(Math.round(v), min, max);
|
||
if (v === cur) return;
|
||
if (v === zero && snap !== false) buzz();
|
||
cur = v; place(); onInput(v);
|
||
};
|
||
el.setValue = v => { cur = v; place(); };
|
||
place();
|
||
let startY = 0, startV = 0, lastTap = 0, active = null;
|
||
el.addEventListener("pointerdown", e => {
|
||
if (active !== null || !e.target.closest(".cap")) return;
|
||
active = e.pointerId;
|
||
el.setPointerCapture(e.pointerId);
|
||
beginBusy();
|
||
startY = e.clientY; startV = cur;
|
||
const now = Date.now();
|
||
if (zero != null && now - lastTap < 300) { set(zero); startV = zero; }
|
||
lastTap = now;
|
||
el.classList.add("grab");
|
||
e.preventDefault();
|
||
});
|
||
el.addEventListener("pointermove", e => {
|
||
if (e.pointerId !== active) return;
|
||
const H = el.clientHeight - 24;
|
||
const fine = e.shiftKey ? 0.25 : 1;
|
||
const raw = startV + (startY - e.clientY) / H * (max - min) * fine;
|
||
set(detent(raw, zero, max - min, H / fine));
|
||
});
|
||
const end = e => { if (e.pointerId !== active) return; active = null; el.classList.remove("grab"); endBusy(); };
|
||
el.addEventListener("pointerup", end);
|
||
el.addEventListener("pointercancel", end);
|
||
el.addEventListener("wheel", e => { e.preventDefault(); set(cur - Math.sign(e.deltaY) * (e.shiftKey ? 1 : 4), false); }, { passive: false });
|
||
el.addEventListener("keydown", e => {
|
||
const step = { ArrowUp: 1, ArrowRight: 1, ArrowDown: -1, ArrowLeft: -1, PageUp: 20, PageDown: -20 }[e.key];
|
||
if (step) { e.preventDefault(); set(cur + step, false); }
|
||
else if (e.key === "Home") { e.preventDefault(); set(max, false); }
|
||
else if (e.key === "End") { e.preventDefault(); set(min, false); }
|
||
else if (e.key === "0" && zero != null) { e.preventDefault(); set(zero); }
|
||
});
|
||
return el;
|
||
}
|
||
|
||
// ------------------------------------------------------------------ LED meters (Pioneer-style segment bars)
|
||
|
||
// Segment thresholds in dB (bottom to top) and their colour
|
||
const SEGS = [-48, -40, -34, -28, -24, -20, -16, -12, -9, -6, -4, -2, 0, 2, 4, 6]
|
||
.map(db => ({ db, c: db >= 4 ? "r" : db >= 0 ? "o" : "g" }));
|
||
(function meterCss() {
|
||
let css = "";
|
||
for (let n = 1; n <= SEGS.length; n++) css += `.led[data-n="${n}"]>i:nth-child(-n+${n}),.led[data-p="${n}"]>i:nth-child(${n}){opacity:1;box-shadow:0 0 6px var(--c)}`;
|
||
document.head.append(h("style", {}, css));
|
||
})();
|
||
|
||
const meterTarget = new Map(); // key -> dB from the device
|
||
const meterState = new Map(); // key -> {lvl, pk, pkT}
|
||
let meterEls = [];
|
||
|
||
function ledMeter(devId, kind, idx, orient = "v") {
|
||
return h("div", { class: "led " + orient, "data-key": `${devId}|${kind}|${idx}`, "aria-hidden": "true" },
|
||
SEGS.map(s => h("i", { class: s.c })));
|
||
}
|
||
function collectMeters() { meterEls = [...document.querySelectorAll(".led[data-key]")]; limEls = [...document.querySelectorAll("[data-lim]")]; }
|
||
|
||
// Limiter LEDs (outputs): the DSP reports "limiter active" per output with every meter reading
|
||
const limitOn = new Map(); // "dev|idx" -> time it was last reported active
|
||
let limEls = [];
|
||
const LIM_HOLD = 300; // ms an LED stays lit, so short hits are visible
|
||
const limLed = (devId, i, cls = "") => h("span", { class: "limled " + cls, "data-lim": `${devId}|${i}`, title: t("Limiter active"), "aria-hidden": "true" },
|
||
cls ? "LIM" : null);
|
||
|
||
function updateMeters(ev) {
|
||
for (const kind of ["in", "out"])
|
||
(ev[kind] || []).forEach((v, i) => meterTarget.set(`${ev.device}|${kind}|${i}`, v > 0 ? 20 * Math.log10(v) : -120));
|
||
(ev.limit || []).forEach((on, i) => { if (on) limitOn.set(`${ev.device}|${i}`, performance.now()); });
|
||
}
|
||
|
||
let lastFrame = performance.now();
|
||
function meterFrame(now) {
|
||
const dt = Math.min(0.1, (now - lastFrame) / 1000); lastFrame = now;
|
||
for (const el of limEls) {
|
||
const on = now - (limitOn.get(el.dataset.lim) ?? -1e9) < LIM_HOLD;
|
||
if (el.classList.contains("on") !== on) el.classList.toggle("on", on);
|
||
}
|
||
for (const el of meterEls) {
|
||
const key = el.dataset.key;
|
||
let st = meterState.get(key);
|
||
if (!st) meterState.set(key, st = { lvl: -120, pk: 0, pkT: 0 });
|
||
const target = meterTarget.get(key) ?? -120;
|
||
st.lvl = target > st.lvl ? target : Math.max(target, st.lvl - 26 * dt); // instant attack, ~26 dB/s fall
|
||
let n = 0;
|
||
while (n < SEGS.length && st.lvl >= SEGS[n].db) n++;
|
||
if (n >= st.pk) { st.pk = n; st.pkT = now; }
|
||
else if (now - st.pkT > 1200) { st.pk = Math.max(n, st.pk - 1); st.pkT = now - 1120; }
|
||
const ns = n ? String(n) : "", ps = st.pk ? String(st.pk) : "";
|
||
if (el.dataset.n !== ns) el.dataset.n = ns;
|
||
if (el.dataset.p !== ps) el.dataset.p = ps;
|
||
}
|
||
requestAnimationFrame(meterFrame);
|
||
}
|
||
requestAnimationFrame(meterFrame);
|
||
|
||
// ------------------------------------------------------------------ header / status
|
||
|
||
function renderTabs() {
|
||
const tabs = $("#devtabs");
|
||
tabs.replaceChildren(...S.order.map(id => {
|
||
const d = S.devices[id];
|
||
const model = d.detected_model || (d.model !== "auto" ? d.model : "");
|
||
return h("button", { class: "devtab" + (id === S.cur && !S.settings ? " active" : ""), title: `${d.name} · ${where(d)}`,
|
||
onclick: () => { S.cur = id; S.settings = false; store.set("dsp.cur", id); render(); } },
|
||
h("span", { class: "dot " + d.status }), h("span", { class: "dn" }, d.name), model ? h("small", {}, model) : null);
|
||
}));
|
||
$("#btn-settings").classList.toggle("on", S.settings);
|
||
document.querySelectorAll("#viewtabs button").forEach(b => b.classList.toggle("active", !S.settings && b.dataset.view === S.view));
|
||
}
|
||
|
||
const STATUS_TEXT = { disconnected: t("Disconnected"), connecting: t("Connecting…"), loading: t("Loading configuration…"),
|
||
online: "Online", error: t("Error") };
|
||
|
||
async function storePresetDialog(d) {
|
||
const slot = h("select", {}, d.presets.map((p, i) => h("option", { value: i }, `U${String(i + 1).padStart(2, "0")} ${p || t("— empty —")}`)));
|
||
const name = h("input", { type: "text", maxlength: 14, value: d.state.preset_name || "", placeholder: t("Name (max. 14 characters)") });
|
||
const cur = d.presets.indexOf(d.state.preset_name);
|
||
if (cur >= 0) slot.value = cur;
|
||
const res = await modal({
|
||
title: t("Store preset"),
|
||
body: h("div", { class: "form" }, h("label", {}, t("Memory slot"), slot), h("label", {}, "Name", name),
|
||
h("p", { class: "info" }, t("Overwrites the selected memory slot in the DSP."))),
|
||
actions: [{ label: t("Cancel") }, { label: t("Save"), primary: true,
|
||
value: () => ({ index: +slot.value, name: name.value.trim().slice(0, 14) || `Preset ${+slot.value + 1}` }) }],
|
||
});
|
||
if (!res) return;
|
||
try { await api("POST", `/api/devices/${d.id}/preset/store`, res); toast(t("Stored in U{n}", { n: res.index + 1 })); }
|
||
catch (e) { toast(t("Error: ") + e.message); }
|
||
}
|
||
|
||
async function presetFileDialog(d) {
|
||
const backups = await api("POST", `/api/devices/${d.id}/backups`).catch(() => []);
|
||
const last = backups[0] && new Date(backups[0].time * 1000).toLocaleString(LOCALE, { dateStyle: "short", timeStyle: "short" });
|
||
const choice = await modal({
|
||
title: t("Preset file"),
|
||
body: h("div", {},
|
||
h("p", { class: "dlg-text" }, t("Export saves the DSP’s current state ({name}) to a file. Import loads a file into the " +
|
||
"active state – stored presets (U01 …) stay unchanged.", { name: q(d.state.preset_name || "—") })),
|
||
last ? h("p", { class: "dlg-text" }, t("A backup is made automatically before every import. Last backup: {last}.", { last })) : null),
|
||
actions: [{ label: t("Close") },
|
||
...(last && !S.locked ? [{ label: t("Undo import"), value: () => "undo" }] : []),
|
||
...(S.locked ? [] : [{ label: t("Import…"), value: () => "import" }]),
|
||
{ label: t("Export"), primary: true, value: () => "export" }],
|
||
});
|
||
try {
|
||
if (choice === "export") await exportPreset(d);
|
||
else if (choice === "import") await importPreset(d);
|
||
else if (choice === "undo") {
|
||
if (!await askConfirm(t("Undo import"), t("Restore the state from {last}?", { last }), t("Restore"))) return;
|
||
toast(t("Restoring…"));
|
||
reportImport(await api("POST", `/api/devices/${d.id}/undo`), t("Previous state restored"));
|
||
}
|
||
} catch (e) { toast(t("Error: ") + e.message); }
|
||
}
|
||
|
||
async function exportPreset(d) {
|
||
toast(t("Reading the state from the DSP…"));
|
||
const doc = await api("POST", `/api/devices/${d.id}/export`);
|
||
if (await saveFile(`${fileSafe(doc.preset_name)}_DSP${doc.model}_${today()}.json`, doc)) toast(t("Preset exported"));
|
||
}
|
||
|
||
async function importPreset(d) {
|
||
const f = await openFile();
|
||
if (!f) return;
|
||
const doc = f.json;
|
||
const what = doc && doc.preset_name != null
|
||
? `${q(doc.preset_name || "—")} (DSP ${doc.model}${doc.exported ? ", " + t("exported") + " " + doc.exported.replace("T", " ").slice(0, 16) : ""})`
|
||
: q(f.name);
|
||
if (!await askConfirm(t("Import preset"), t("Load {what} into the active state? The current state is backed up automatically first and " +
|
||
"can be brought back via File → “Undo import”. Stored presets stay unchanged – to keep it, store it into a memory slot with “Save” afterwards.",
|
||
{ what }), t("Import"))) return;
|
||
toast(t("Importing… (a few seconds)"));
|
||
reportImport(await api("POST", `/api/devices/${d.id}/import`, doc ? { doc } : { raw: f.b64 }),
|
||
doc && doc.preset_name ? t("Preset {name} imported", { name: q(doc.preset_name) }) : t("Preset imported"));
|
||
}
|
||
|
||
function reportImport(res, okMsg) {
|
||
if (res.ok) return toast(okMsg);
|
||
modal({ title: t("Import incomplete"), body: h("div", {},
|
||
h("p", { class: "dlg-text" }, t("The DSP did not take these values:")),
|
||
h("p", { class: "dlg-text" }, h("code", {}, res.differences.join(", ")))),
|
||
actions: [{ label: "OK", primary: true, value: () => true }] });
|
||
}
|
||
|
||
function renderStatus() {
|
||
const bar = $("#statusbar");
|
||
const d = dev();
|
||
if (S.settings || !d) { bar.replaceChildren(); return; }
|
||
if (d.status !== "online" || !d.state) {
|
||
bar.replaceChildren(
|
||
h("div", { class: "preset" }, h("small", {}, `${STATUS_TEXT[d.status] || d.status} · ${d.transport === "usb" ? "USB" : d.host + ":" + d.port}`), h("b", {}, d.name),
|
||
d.error ? h("div", { class: "err" }, trMsg(d.error)) : null),
|
||
d.status === "disconnected" || d.status === "error"
|
||
? h("button", { class: "on", onclick: () => api("POST", `/api/devices/${d.id}/connect`).catch(e => toast(e.message)) }, t("Connect"))
|
||
: h("button", { onclick: () => api("POST", `/api/devices/${d.id}/disconnect`) }, t("Cancel")));
|
||
return;
|
||
}
|
||
const presetSel = h("select", { "aria-label": t("Recall preset") },
|
||
h("option", { value: "" }, t("Recall preset…")),
|
||
d.presets.map((p, i) => h("option", { value: i, disabled: !p }, `U${String(i + 1).padStart(2, "0")} ${p || "—"}`)));
|
||
presetSel.addEventListener("change", async () => {
|
||
if (presetSel.value === "") return;
|
||
const i = +presetSel.value;
|
||
presetSel.value = "";
|
||
if (!await askConfirm(t("Recall preset"), t("Recall {name} (U{n})? Unsaved changes will be lost.", { name: q(d.presets[i]), n: i + 1 }), t("Recall"))) return;
|
||
presetSel.disabled = true;
|
||
try { await api("POST", `/api/devices/${d.id}/preset/recall`, { index: i }); toast(t("Preset U{n} recalled", { n: i + 1 })); }
|
||
catch (e) { toast(t("Error: ") + e.message); }
|
||
presetSel.disabled = false;
|
||
});
|
||
bar.replaceChildren(
|
||
h("div", { class: "preset" }, h("small", {}, `${d.info || d.name} · ${where(d)}`), h("b", {}, d.state.preset_name || "—")),
|
||
h("div", { class: "presetrow" }, presetSel, h("button", { onclick: () => storePresetDialog(d) }, t("Save")),
|
||
h("button", { onclick: () => presetFileDialog(d), title: t("Export / import preset"), "data-view-ok": "" }, t("File…"))));
|
||
}
|
||
|
||
// ------------------------------------------------------------------ mixer
|
||
|
||
function openChannel(kind, idx) {
|
||
S.sel = { kind, idx }; S.view = "channel"; store.set("dsp.view", "channel"); render(); window.scrollTo(0, 0);
|
||
}
|
||
|
||
function strip(d, kind, i) {
|
||
const ch = chans(d, kind)[i];
|
||
const db = h("button", { class: "db" + (ch.gain === 280 ? " z" : ""), title: t("Enter value") }, sign(gainDb(ch.gain)));
|
||
const showDb = v => { db.textContent = sign(gainDb(v)); db.classList.toggle("z", v === 280); };
|
||
const el = h("div", { class: `strip ${kind}` + (ch.mute ? " muted" : ""), style: kind === "in" ? `--cc:${IN_COLORS[i]}` : "" });
|
||
const f = fader({ min: 0, max: 400, value: ch.gain, zero: 280, ticks: GAIN_TICKS, label: `${chLabel(kind, i)} Gain`,
|
||
onInput: v => { showDb(v); setParam(kind, i, "gain", v); } });
|
||
onLive(kind, i, "gain", v => { f.setValue(v); showDb(v); });
|
||
db.addEventListener("click", async () => {
|
||
const v = await askValue(`${chTitle(d, kind, i)} – Gain`, SPEC.gain, chans(dev(), kind)[i].gain);
|
||
if (v != null) { f.setValue(v); showDb(v); setParam(kind, i, "gain", v); }
|
||
});
|
||
el.append(
|
||
h("button", { class: "strip-head", onclick: () => openChannel(kind, i), title: t("Edit channel") },
|
||
h("span", { class: "kind" }, chLabel(kind, i), linkBadge(d, kind, i)), h("span", { class: "nm" }, ch.name || " "),
|
||
kind === "out" ? limLed(d.id, i) : h("span", { class: "limled ph", "aria-hidden": "true" })), // keeps faders level with the outputs
|
||
h("div", { class: "faderbox" }, ledMeter(d.id, kind, i), f),
|
||
db,
|
||
toggleBtn("MUTE", kind, i, "mute", "mute", v => el.classList.toggle("muted", v)));
|
||
return el;
|
||
}
|
||
|
||
function viewMixer(d) {
|
||
const group = (kind, title) => h("section", { class: "mgroup", style: `flex-grow:${chans(d, kind).length}` },
|
||
h("h4", {}, title), h("div", { class: "strips" }, chans(d, kind).map((_, i) => strip(d, kind, i))));
|
||
return [h("div", { class: "mixer" }, group("in", t("Inputs")), group("out", t("Outputs"))),
|
||
h("p", { class: "info hint" }, t("Drag a fader by its knob · snaps at 0 dB · double-tap the knob = 0 dB · tap the dB value to type one · tap the name = edit channel"))];
|
||
}
|
||
|
||
// ------------------------------------------------------------------ filter response (for the PEQ curve)
|
||
|
||
const FS = 96000;
|
||
function biquadMag(type, f0, dbGain, q, f) {
|
||
const A = Math.pow(10, dbGain / 40), w0 = 2 * Math.PI * f0 / FS, cs = Math.cos(w0), sn = Math.sin(w0);
|
||
const alpha = sn / (2 * q);
|
||
let b0, b1, b2, a0, a1, a2;
|
||
switch (type) {
|
||
case 0: b0 = 1 + alpha * A; b1 = -2 * cs; b2 = 1 - alpha * A; a0 = 1 + alpha / A; a1 = -2 * cs; a2 = 1 - alpha / A; break;
|
||
case 1: case 2: {
|
||
const s = type === 1 ? 1 : -1, sq = 2 * Math.sqrt(A) * alpha;
|
||
b0 = A * ((A + 1) - s * (A - 1) * cs + sq); b1 = s * 2 * A * ((A - 1) - s * (A + 1) * cs); b2 = A * ((A + 1) - s * (A - 1) * cs - sq);
|
||
a0 = (A + 1) + s * (A - 1) * cs + sq; a1 = -s * 2 * ((A - 1) + s * (A + 1) * cs); a2 = (A + 1) + s * (A - 1) * cs - sq; break;
|
||
}
|
||
case 3: { const k = Math.tan(w0 / 2); b0 = 1; b1 = -1; b2 = 0; a0 = 1 + k; a1 = k - 1; a2 = 0; break; }
|
||
case 4: b0 = (1 + cs) / 2; b1 = -(1 + cs); b2 = (1 + cs) / 2; a0 = 1 + alpha; a1 = -2 * cs; a2 = 1 - alpha; break;
|
||
case 5: { const k = Math.tan(w0 / 2); b0 = k; b1 = k; b2 = 0; a0 = 1 + k; a1 = k - 1; a2 = 0; break; }
|
||
case 6: b0 = (1 - cs) / 2; b1 = 1 - cs; b2 = (1 - cs) / 2; a0 = 1 + alpha; a1 = -2 * cs; a2 = 1 - alpha; break;
|
||
default: return 0;
|
||
}
|
||
const w = 2 * Math.PI * f / FS, c1 = Math.cos(w), s1 = Math.sin(w), c2 = Math.cos(2 * w), s2 = Math.sin(2 * w);
|
||
const nr = b0 + b1 * c1 + b2 * c2, ni = -(b1 * s1 + b2 * s2), dr = a0 + a1 * c1 + a2 * c2, di = -(a1 * s1 + a2 * s2);
|
||
return 10 * Math.log10((nr * nr + ni * ni) / (dr * dr + di * di));
|
||
}
|
||
function xoverMag(filter, f, high) {
|
||
if (!filter.slope) return 0;
|
||
const name = SLOPES[filter.slope], order = parseInt(name.split("-")[1], 10) / 6, fc = freqHz(filter.freq);
|
||
const r = high ? fc / f : f / fc;
|
||
if (name.startsWith("LK")) return -20 * Math.log10(1 + Math.pow(r, order));
|
||
return -10 * Math.log10(1 + Math.pow(r, 2 * order));
|
||
}
|
||
const hasGain = type => type <= 2;
|
||
const hasQ = type => [0, 4, 6, 7, 8].includes(type);
|
||
|
||
function drawCurve(canvas, ch, selBand) {
|
||
const dpr = window.devicePixelRatio || 1, W = canvas.clientWidth, H = canvas.clientHeight;
|
||
if (!W || !H) return null;
|
||
canvas.width = W * dpr; canvas.height = H * dpr;
|
||
const g = canvas.getContext("2d");
|
||
g.scale(dpr, dpr);
|
||
const fx = f => Math.log(f / 20) / Math.log(1000) * W;
|
||
const dy = db => H / 2 - db / 15 * (H / 2 - 10);
|
||
g.font = "10px system-ui"; g.fillStyle = "#5b6673"; g.lineWidth = 1;
|
||
for (const f of [30, 50, 100, 200, 500, 1000, 2000, 5000, 10000]) {
|
||
g.strokeStyle = [100, 1000, 10000].includes(f) ? "#252d37" : "#1a2028";
|
||
g.beginPath(); g.moveTo(fx(f), 0); g.lineTo(fx(f), H); g.stroke();
|
||
g.fillText(f >= 1000 ? f / 1000 + "k" : f, fx(f) + 3, H - 4);
|
||
}
|
||
for (const db of [-12, -6, 0, 6, 12]) {
|
||
g.strokeStyle = db === 0 ? "#3a4552" : "#1a2028";
|
||
g.beginPath(); g.moveTo(0, dy(db)); g.lineTo(W, dy(db)); g.stroke();
|
||
g.fillText((db > 0 ? "+" : "") + db, 3, dy(db) - 3);
|
||
}
|
||
const resp = f => {
|
||
let s = xoverMag(ch.hp, f, true) + xoverMag(ch.lp, f, false);
|
||
for (const b of ch.peq) if (!b.bypass) s += biquadMag(b.type, freqHz(b.freq), eqDb(b.gain), Q_TABLE[b.q], f);
|
||
return s;
|
||
};
|
||
// selected band's own contribution, filled
|
||
const sb = ch.peq[selBand];
|
||
if (sb && !sb.bypass) {
|
||
g.beginPath(); g.moveTo(0, dy(0));
|
||
for (let x = 0; x <= W; x += 3) g.lineTo(x, clamp(dy(biquadMag(sb.type, freqHz(sb.freq), eqDb(sb.gain), Q_TABLE[sb.q], 20 * Math.pow(1000, x / W))), 0, H));
|
||
g.lineTo(W, dy(0)); g.closePath(); g.fillStyle = "#f59e0b22"; g.fill();
|
||
}
|
||
const pts = [];
|
||
for (let x = 0; x <= W; x += 2) pts.push([x, clamp(dy(resp(20 * Math.pow(1000, x / W))), 0, H)]);
|
||
g.beginPath(); g.moveTo(0, H); pts.forEach(([x, y]) => g.lineTo(x, y)); g.lineTo(W, H); g.closePath();
|
||
const grad = g.createLinearGradient(0, 0, 0, H); grad.addColorStop(0, "#38bdf833"); grad.addColorStop(1, "#38bdf800");
|
||
g.fillStyle = grad; g.fill();
|
||
g.strokeStyle = "#38bdf8"; g.lineWidth = 2; g.beginPath();
|
||
pts.forEach(([x, y], i) => i ? g.lineTo(x, y) : g.moveTo(x, y));
|
||
g.stroke();
|
||
ch.peq.forEach((b, i) => {
|
||
const x = fx(freqHz(b.freq)), y = dy(hasGain(b.type) ? eqDb(b.gain) : 0);
|
||
g.beginPath(); g.arc(x, y, i === selBand ? 10 : 7, 0, 2 * Math.PI);
|
||
g.fillStyle = b.bypass ? "#2a333d" : i === selBand ? "#f59e0b" : "#38bdf8cc"; g.fill();
|
||
g.fillStyle = b.bypass ? "#6b7682" : "#0b0c0f"; g.font = "bold 10px system-ui"; g.textAlign = "center"; g.textBaseline = "middle";
|
||
g.fillText(i + 1, x, y + 0.5); g.textAlign = "start"; g.textBaseline = "alphabetic";
|
||
});
|
||
return { fx, dy, W, H };
|
||
}
|
||
|
||
function peqCard(d, kind, idx) {
|
||
const ch = chans(d, kind)[idx];
|
||
S.band = Math.min(S.band, ch.peq.length - 1);
|
||
const canvas = h("canvas", { class: "curve", "aria-label": t("EQ curve – drag the points") });
|
||
const redraw = () => drawCurve(canvas, chans(dev(), kind)[idx], S.band);
|
||
const body = h("div", { class: "bandparams" });
|
||
const bandBtns = h("div", { class: "bands", role: "tablist" });
|
||
const renderBand = () => {
|
||
const c = chans(dev(), kind)[idx], b = c.peq[S.band], p = `peq.${S.band}`;
|
||
bandBtns.replaceChildren(...c.peq.map((bb, i) => h("button", {
|
||
class: "band" + (i === S.band ? " on" : "") + (bb.bypass ? " bypassed" : "") + (hasGain(bb.type) && bb.gain !== 120 ? " active" : ""),
|
||
role: "tab", "aria-selected": String(i === S.band),
|
||
onclick: () => { S.band = i; renderBand(); redraw(); } },
|
||
h("b", {}, String(i + 1)), h("small", {}, fmtHzShort(freqHz(bb.freq))),
|
||
h("small", {}, hasGain(bb.type) ? sign(eqDb(bb.gain)) : PEQ_SHORT[bb.type]))));
|
||
const both = () => { renderBand(); redraw(); };
|
||
body.replaceChildren(
|
||
h("div", { class: "row bandhead" },
|
||
h("label", { class: "inline" }, t("Type"), paramSelect(kind, idx, p + ".type", PEQ_TYPES, both, t("Filter type"))),
|
||
toggleBtn("Bypass", kind, idx, p + ".bypass", "", both),
|
||
hasGain(b.type) ? h("button", { onclick: () => { setParam(kind, idx, p + ".gain", 120); both(); } }, "0 dB") : null),
|
||
h("div", { class: "pgrid" },
|
||
paramSlider(t("Frequency"), kind, idx, p + ".freq", "freq", both),
|
||
hasGain(b.type) ? paramSlider("Gain", kind, idx, p + ".gain", "eqgain", both) : null,
|
||
hasQ(b.type) ? paramSlider("Q", kind, idx, p + ".q", "q", both) : null));
|
||
};
|
||
// drag points on the curve (gain snaps to 0 dB)
|
||
let drag = null;
|
||
canvas.addEventListener("pointerdown", e => {
|
||
const c = chans(dev(), kind)[idx], r = canvas.getBoundingClientRect(), geo = drawCurve(canvas, c, S.band);
|
||
if (!geo) return;
|
||
let best = -1, bd = 1600;
|
||
c.peq.forEach((b, i) => {
|
||
const dx = geo.fx(freqHz(b.freq)) - (e.clientX - r.left);
|
||
const dyy = geo.dy(hasGain(b.type) ? eqDb(b.gain) : 0) - (e.clientY - r.top);
|
||
if (dx * dx + dyy * dyy < bd) { bd = dx * dx + dyy * dyy; best = i; }
|
||
});
|
||
if (best < 0) return;
|
||
e.preventDefault();
|
||
S.band = best; beginBusy(); drag = { geo, r, id: e.pointerId };
|
||
canvas.setPointerCapture(e.pointerId); renderBand(); redraw();
|
||
});
|
||
canvas.addEventListener("pointermove", e => {
|
||
if (!drag || e.pointerId !== drag.id) return;
|
||
const { geo, r } = drag, c = chans(dev(), kind)[idx], b = c.peq[S.band];
|
||
const x = clamp(e.clientX - r.left, 0, geo.W);
|
||
const f = hzFreq(20 * Math.pow(1000, x / geo.W));
|
||
if (f !== b.freq) setParam(kind, idx, `peq.${S.band}.freq`, f);
|
||
if (hasGain(b.type)) {
|
||
const db = (geo.H / 2 - (e.clientY - r.top)) / (geo.H / 2 - 10) * 15;
|
||
let g = clamp(Math.round(db * 10 + 120), 0, 240);
|
||
g = detent(g, 120, 300, geo.H - 20, 8);
|
||
if (g !== b.gain) { if (g === 120) buzz(); setParam(kind, idx, `peq.${S.band}.gain`, g); }
|
||
}
|
||
redraw();
|
||
});
|
||
const end = () => { if (drag) { drag = null; renderBand(); endBusy(); } };
|
||
canvas.addEventListener("pointerup", end);
|
||
canvas.addEventListener("pointercancel", end);
|
||
renderBand();
|
||
requestAnimationFrame(redraw);
|
||
new ResizeObserver(redraw).observe(canvas);
|
||
return h("div", { class: "card wide" },
|
||
h("h3", {}, h("span", { class: "grow" }, t("Parametric EQ")),
|
||
h("button", { class: "small", onclick: async () => {
|
||
if (!await askConfirm(t("Reset EQ"), t("Set all PEQ bands of this channel to 0 dB and clear bypass?"), t("All flat"))) return;
|
||
chans(dev(), kind)[idx].peq.forEach((bb, i) => {
|
||
if (bb.gain !== 120) setParam(kind, idx, `peq.${i}.gain`, 120);
|
||
if (bb.bypass) setParam(kind, idx, `peq.${i}.bypass`, false);
|
||
});
|
||
renderBand(); redraw(); toast(t("All bands flat"));
|
||
} }, t("All flat"))),
|
||
canvas, h("p", { class: "info" }, t("Drag the points in the curve · gain snaps at 0 dB")), bandBtns, body);
|
||
}
|
||
|
||
function geqCard(d, idx) {
|
||
const ch = chans(d, "in")[idx];
|
||
const faders = [];
|
||
const bands = ch.geq.map((v, b) => {
|
||
const lbl = h("span", { class: "gv" }, eqDb(v).toFixed(1));
|
||
const f = fader({ min: 0, max: 240, value: v, zero: 120, ticks: [[240, ""], [120, ""], [0, ""]], label: `GEQ ${GEQ_FREQS[b]} Hz`,
|
||
onInput: x => { lbl.textContent = eqDb(x).toFixed(1); lbl.classList.toggle("nz", x !== 120); setParam("in", idx, `geq.${b}`, x); } });
|
||
lbl.classList.toggle("nz", v !== 120);
|
||
faders.push([f, lbl]);
|
||
return h("div", { class: "gb" }, lbl, f, h("span", { class: "gf" }, GEQ_FREQS[b]));
|
||
});
|
||
return h("div", { class: "card wide" },
|
||
h("h3", {}, h("span", { class: "grow" }, t("Graphic EQ · 31 bands")),
|
||
h("button", { class: "small", onclick: async () => {
|
||
if (!await askConfirm(t("Reset GEQ"), t("Set all 31 bands to 0 dB?"), t("Reset"))) return;
|
||
chans(dev(), "in")[idx].geq.forEach((g, b) => { if (g !== 120) setParam("in", idx, `geq.${b}`, 120); });
|
||
faders.forEach(([f, l]) => { f.setValue(120); l.textContent = "0.0"; l.classList.remove("nz"); });
|
||
} }, t("All flat"))),
|
||
h("div", { class: "geq" }, bands),
|
||
h("p", { class: "info" }, t("Snaps at 0 dB · double-tap the knob = 0 dB")));
|
||
}
|
||
|
||
// ------------------------------------------------------------------ channel view
|
||
|
||
function channelBar(d) {
|
||
const { kind, idx } = S.sel;
|
||
const all = [...chans(d, "in").map((_, i) => ["in", i]), ...chans(d, "out").map((_, i) => ["out", i])];
|
||
const pos = all.findIndex(([k, i]) => k === kind && i === idx);
|
||
const go = p => { const [k, i] = all[(p + all.length) % all.length]; S.sel = { kind: k, idx: i }; render(); };
|
||
const sel = h("select", { class: "chsel", "aria-label": t("Choose channel"), onchange: () => go(+sel.value) },
|
||
h("optgroup", { label: t("Inputs") }, chans(d, "in").map((_, i) => h("option", { value: i, selected: pos === i }, chTitle(d, "in", i)))),
|
||
h("optgroup", { label: t("Outputs") }, chans(d, "out").map((_, i) => {
|
||
const p = chans(d, "in").length + i;
|
||
return h("option", { value: p, selected: pos === p }, chTitle(d, "out", i));
|
||
})));
|
||
return h("div", { class: "chbar" },
|
||
h("button", { class: "icon nav", "aria-label": t("Previous channel"), onclick: () => go(pos - 1) }, svgIcon(ICON.prev)),
|
||
h("div", { class: "chselwrap", style: kind === "in" ? `--cc:${IN_COLORS[idx]}` : "" }, sel),
|
||
h("button", { class: "icon nav", "aria-label": t("Next channel"), onclick: () => go(pos + 1) }, svgIcon(ICON.next)),
|
||
ledMeter(d.id, kind, idx, "h"),
|
||
kind === "out" ? limLed(d.id, idx, "h") : null,
|
||
toggleBtn("MUTE", kind, idx, "mute", "mute"));
|
||
}
|
||
|
||
function viewChannel(d) {
|
||
if (S.sel.idx >= chans(d, S.sel.kind).length) S.sel = { kind: "in", idx: 0 };
|
||
const k = S.sel.kind, i = S.sel.idx, ch = chans(d, k)[i];
|
||
const redrawPeq = () => { const c = main.querySelector("canvas.curve"); c && drawCurve(c, chans(dev(), k)[i], S.band); };
|
||
|
||
const li = linkInfo(d, k, i);
|
||
const basics = h("div", { class: "card" }, h("h3", {}, t("Channel")),
|
||
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)."
|
||
: "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,
|
||
h("div", { class: "row" },
|
||
h("label", { class: "inline grow2" }, "Name",
|
||
h("input", { type: "text", maxlength: NAME_MAX, value: ch.name, placeholder: chLabel(k, i), "aria-label": t("Channel name"),
|
||
oninput: e => { // stop typing where the name would no longer fit
|
||
const c = cleanName(e.target.value);
|
||
if (c !== e.target.value) {
|
||
const pos = Math.min(e.target.selectionStart, c.length);
|
||
e.target.value = c; e.target.setSelectionRange(pos, pos);
|
||
if (Date.now() - (S.nameToast || 0) > 2000) { S.nameToast = Date.now(); toast(t("Name is full (max. 8 characters, wide letters count more)")); }
|
||
}
|
||
},
|
||
onchange: e => { setParam(k, i, "name", cleanName(e.target.value).trim()); render(); } })),
|
||
toggleBtn("Phase Ø", k, i, "polarity")),
|
||
paramSlider("Gain", k, i, "gain", "gain"),
|
||
paramSlider("Delay", k, i, "delay", "delay"));
|
||
|
||
const xo = (title, key) => h("div", { class: "xo" },
|
||
h("div", { class: "row" }, h("span", { class: "sub" }, title), paramSelect(k, i, key + ".slope", SLOPES, () => { redrawPeq(); render(); }, title)),
|
||
chans(d, k)[i][key].slope ? paramSlider(t("Frequency"), k, i, key + ".freq", "freq", redrawPeq) : h("p", { class: "info off" }, t("Off (bypass)")));
|
||
const xover = h("div", { class: "card" }, h("h3", {}, t("High- / low-pass")),
|
||
xo(t("High-pass"), "hp"), xo(t("Low-pass"), "lp"));
|
||
|
||
const cards = [basics, xover];
|
||
if (k === "in") {
|
||
cards.push(h("div", { class: "card" }, h("h3", {}, "Noise Gate"),
|
||
paramSlider("Threshold", k, i, "gate.threshold", "gthresh"),
|
||
paramSlider("Attack", k, i, "gate.attack", "attack"),
|
||
paramSlider("Hold", k, i, "gate.hold", "hold"),
|
||
paramSlider("Release", k, i, "gate.release", "release")));
|
||
cards.push(peqCard(d, k, i), geqCard(d, i));
|
||
} else {
|
||
cards.push(routingCard(d, i), peqCard(d, k, i));
|
||
cards.push(h("div", { class: "card" }, h("h3", {}, t("Compressor")),
|
||
paramSlider("Threshold", k, i, "comp.threshold", "thresh"),
|
||
paramSlider("Ratio", k, i, "comp.ratio", "ratio"),
|
||
paramSlider("Attack", k, i, "comp.attack", "attack"),
|
||
paramSlider("Release", k, i, "comp.release", "release"),
|
||
paramSlider("Knee", k, i, "comp.knee", "knee")));
|
||
const lc = limCalc(d.id, i, ch.limit.threshold);
|
||
cards.push(h("div", { class: "card" }, h("h3", {}, "Limiter"),
|
||
h("div", { class: "row" }, h("span", { class: "grow" }, "Threshold ", h("b", {}, SPEC.thresh.fmt(ch.limit.threshold)),
|
||
lc ? [" → ", h("b", {}, fmtW(lc.p)), ` @ ${lc.as.ohm} Ω`] : null),
|
||
h("button", { class: "small", onclick: () => { S.view = "limiter"; store.set("dsp.view", "limiter"); render(); window.scrollTo(0, 0); } }, t("Limiter tab")))));
|
||
}
|
||
return [channelBar(d), h("div", { class: "cards" }, cards)];
|
||
}
|
||
|
||
// Per-output source list: on/off + level per input
|
||
function mixList(d, o) {
|
||
return chans(d, "in").map((inp, i) => {
|
||
const on = chans(d, "out")[o].matrix >> i & 1;
|
||
const btn = h("button", { class: "src" + (on ? " on" : ""), style: `--cc:${IN_COLORS[i]}`, "aria-pressed": String(!!on),
|
||
onclick: () => {
|
||
const m = chans(dev(), "out")[o].matrix ^ (1 << i);
|
||
setParam("out", o, "matrix", m); render();
|
||
} }, h("span", { class: "sw" }), chTitle(d, "in", i));
|
||
return h("div", { class: "mixrow" + (on ? "" : " off") }, btn, paramSlider(t("Level"), "out", o, `mix.${i}`, "mix"));
|
||
});
|
||
}
|
||
|
||
function routingCard(d, o) {
|
||
return h("div", { class: "card" }, h("h3", {}, t("Sources → ") + chLabel("out", o)), mixList(d, o));
|
||
}
|
||
|
||
// ------------------------------------------------------------------ routing view
|
||
|
||
function viewRouting(d) {
|
||
const ins = chans(d, "in"), outs = chans(d, "out");
|
||
const grid = h("div", { class: "xmatrix", style: `--n:${ins.length}` });
|
||
grid.append(h("div", { class: "xcorner" }, h("span", {}, t("Input →")), h("span", {}, t("Output ↓"))));
|
||
ins.forEach((c, i) => grid.append(h("div", { class: "xin", style: `--cc:${IN_COLORS[i]}` },
|
||
h("b", {}, chLabel("in", i)), h("small", {}, c.name || " "), ledMeter(d.id, "in", i, "h"))));
|
||
outs.forEach((oc, o) => {
|
||
const open = S.routeOpen === o;
|
||
const srcs = ins.map((_, i) => oc.matrix >> i & 1 ? chLabel("in", i).slice(3) : null).filter(Boolean);
|
||
grid.append(h("button", { class: "xout" + (open ? " open" : ""), "aria-expanded": String(open),
|
||
onclick: () => { S.routeOpen = open ? null : o; render(); } },
|
||
h("span", { class: "xo-t" }, h("b", {}, chLabel("out", o)), h("small", {}, oc.name || " ")),
|
||
h("span", { class: "xo-s" }, srcs.length ? "← " + srcs.join("+") : "—"),
|
||
h("span", { class: "chev" }, open ? "▴" : "▾")));
|
||
ins.forEach((_, i) => {
|
||
const on = oc.matrix >> i & 1;
|
||
grid.append(h("button", { class: "xp" + (on ? " on" : ""), style: `--cc:${IN_COLORS[i]}`,
|
||
"aria-label": `${chLabel("in", i)} → ${chLabel("out", o)}`, "aria-pressed": String(!!on),
|
||
onclick: () => {
|
||
const m = chans(dev(), "out")[o].matrix ^ (1 << i);
|
||
setParam("out", o, "matrix", m); render();
|
||
} }, h("span", { class: "node" }), on ? h("small", {}, gainDb(oc.mix[i]) === 0 ? "0 dB" : sign(gainDb(oc.mix[i]))) : null));
|
||
});
|
||
if (open) grid.append(h("div", { class: "xpanel" }, h("div", { class: "xpanel-h" }, t("Level for {ch}", { ch: chTitle(d, "out", o) }),
|
||
h("button", { class: "small", onclick: () => openChannel("out", o) }, t("Open channel"))), mixList(d, o)));
|
||
});
|
||
return h("div", { class: "card routing" }, h("h3", {}, t("Routing matrix")), grid,
|
||
h("p", { class: "info" }, t("Tap a crosspoint = connect/disconnect · tap an output = level per input")));
|
||
}
|
||
|
||
// ------------------------------------------------------------------ channel links
|
||
|
||
async function saveLinks(d, kind, groups, msg) {
|
||
S.linkBusy = true; render();
|
||
try { await api("POST", `/api/devices/${d.id}/link`, { kind, groups }); toast(msg); }
|
||
catch (e) { toast(t("Error: ") + e.message); }
|
||
S.linkBusy = false; S.linkSel[kind] = []; render();
|
||
}
|
||
|
||
function linkCard(d, kind) {
|
||
const list = chans(d, kind), linked = linkedGroups(d, kind);
|
||
const sel = S.linkSel[kind] = S.linkSel[kind].filter(i => i < list.length);
|
||
const btns = list.map((ch, i) => {
|
||
const l = linkInfo(d, kind, i), on = sel.includes(i);
|
||
return h("button", { class: "lkch" + (on ? " sel" : ""), style: l ? `--lc:${l.color}` : "", "aria-pressed": String(on),
|
||
disabled: S.linkBusy, onclick: () => { S.linkSel[kind] = on ? sel.filter(j => j !== i) : [...sel, i].sort((a, b) => a - b); render(); } },
|
||
h("b", {}, chLabel(kind, i)), h("small", {}, ch.name || "\u00a0"),
|
||
h("span", { class: "lkmark" }, l ? svgIcon(ICON.link) : null));
|
||
});
|
||
const link = async () => {
|
||
const first = chLabel(kind, sel[0]);
|
||
const names = sel.map(i => chLabel(kind, i)).join(", ");
|
||
if (!await askConfirm(t("Link channels"), t(kind === "out" ? "Link {names}? They all take over the settings of {first} (names and routing stay)."
|
||
: "Link {names}? They all take over the settings of {first} (names stay).", { names, first }), t("Link"))) return;
|
||
const rest = linked.map(g => g.filter(i => !sel.includes(i))).filter(g => g.length > 1);
|
||
saveLinks(d, kind, [...rest, sel], t("{names} linked", { names }));
|
||
};
|
||
const unlink = g => saveLinks(d, kind, linked.filter(x => x !== g), t("{names} unlinked", { names: g.map(i => chLabel(kind, i)).join(" + ") }));
|
||
return h("div", { class: "card" }, h("h3", {}, kind === "in" ? t("Inputs") : t("Outputs")),
|
||
h("div", { class: "lkgrid" }, btns),
|
||
h("div", { class: "row lkactions" },
|
||
h("span", { class: "grow info" }, sel.length < 2 ? t("Tap at least two channels") : t("{n} channels selected", { n: sel.length })),
|
||
h("button", { class: "on", disabled: sel.length < 2 || S.linkBusy, onclick: link }, t("Link"))),
|
||
linked.length ? h("div", { class: "lkgroups" }, linked.map((g, n) =>
|
||
h("div", { class: "row lkgroup", style: `--lc:${LINK_COLORS[n % LINK_COLORS.length]}` },
|
||
svgIcon(ICON.link), h("span", { class: "grow" }, g.map(i => chLabel(kind, i)).join(" + ")),
|
||
h("button", { class: "small", disabled: S.linkBusy, onclick: () => unlink(g) }, t("Unlink")))))
|
||
: h("p", { class: "info" }, t("No channels linked.")));
|
||
}
|
||
|
||
function viewLink(d) {
|
||
return [h("div", { class: "cards" }, linkCard(d, "in"), linkCard(d, "out")),
|
||
h("p", { class: "info hint" }, t("Linked channels share all settings (gain, delay, filters, EQ, dynamics, mute) – ") +
|
||
t("a change on one channel applies to the whole group. Name, routing and mix levels stay per channel. ") +
|
||
t("The link is stored in the DSP and also applies in the Thomann editor."))];
|
||
}
|
||
|
||
// ------------------------------------------------------------------ limiter calculator
|
||
|
||
// Limiter threshold -> amplifier output power. Chain: DSP output (threshold, referenced to `ref` dBu)
|
||
// × amplifier voltage gain, capped at the amplifier's clip voltage sqrt(P_rated × R).
|
||
const DBU_V = 0.7746;
|
||
const OHMS = [2, 4, 6, 8, 16];
|
||
const limKey = (devId, o) => `${devId}:${o}`;
|
||
const limRef = devId => S.lim.ref[devId] ?? 0;
|
||
const fmtW = w => w >= 1000 ? (w / 1000).toFixed(w >= 10000 ? 1 : 2) + " kW" : Math.round(w) + " W";
|
||
|
||
// Rated power at any impedance from the 2/4/8 Ω datasheet values (0 = not rated that low)
|
||
function ampRated(a, ohm) {
|
||
const pts = [[2, a.p2], [4, a.p4], [8, a.p8]].filter(p => p[1] > 0);
|
||
if (!pts.length) return 0;
|
||
const hit = pts.find(p => p[0] === ohm);
|
||
if (hit) return hit[1];
|
||
const lo = [...pts].reverse().find(p => p[0] < ohm), hi = pts.find(p => p[0] > ohm);
|
||
if (lo && hi) return lo[1] + (hi[1] - lo[1]) * (ohm - lo[0]) / (hi[0] - lo[0]);
|
||
if (lo) return lo[1] * lo[0] / ohm; // above the highest rating: same clip voltage
|
||
return 0;
|
||
}
|
||
// Linear voltage gain: from the gain in dB, or rated output voltage / input sensitivity
|
||
function ampGain(a) {
|
||
if (a.mode === "gain") return Math.pow(10, a.gain / 20);
|
||
const [r, p] = a.p8 ? [8, a.p8] : a.p4 ? [4, a.p4] : [2, a.p2];
|
||
return p && a.sens ? Math.sqrt(p * r) / a.sens : 0;
|
||
}
|
||
|
||
function limCalc(devId, o, thrRaw) {
|
||
const as = S.lim.assign[limKey(devId, o)];
|
||
const amp = as && S.lim.amps.find(a => a.id === as.amp);
|
||
if (!amp) return null;
|
||
const vin = DBU_V * Math.pow(10, ((thrRaw - 180) / 2 + limRef(devId)) / 20);
|
||
const g = ampGain(amp), rated = ampRated(amp, as.ohm);
|
||
const vout = vin * g, vmax = Math.sqrt(rated * as.ohm);
|
||
const p = rated ? Math.min(vout, vmax) ** 2 / as.ohm : vout ** 2 / as.ohm;
|
||
return { amp, as, p, rated, g, over: rated ? 20 * Math.log10(vout / vmax) : 0 };
|
||
}
|
||
// Threshold (raw) that limits to `watts` at the assigned speaker
|
||
function limThreshFor(devId, o, watts) {
|
||
const c = limCalc(devId, o, 180);
|
||
if (!c || !c.g || watts <= 0) return null;
|
||
const db = 20 * Math.log10(Math.sqrt(watts * c.as.ohm) / c.g / DBU_V) - limRef(devId);
|
||
return clamp(Math.floor(db * 2 + 1e-9) + 180, 0, 220); // round down: never above the target
|
||
}
|
||
|
||
async function saveLim(next) {
|
||
S.lim = next;
|
||
try { S.lim = await api("PUT", "/api/limiter", next); } catch (e) { toast(t("Error: ") + e.message); }
|
||
}
|
||
const limCopy = () => JSON.parse(JSON.stringify(S.lim));
|
||
|
||
async function ampDialog(amp) {
|
||
const isNew = !amp;
|
||
amp = amp || { name: "", mode: "sens", sens: 1.4, gain: 32, p8: 0, p4: 0, p2: 0 };
|
||
const numIn = (v, ph) => h("input", { type: "text", inputmode: "decimal", value: v || "", placeholder: ph, autocomplete: "off" });
|
||
const f = { name: h("input", { type: "text", value: amp.name, placeholder: t("e.g. Crown XLS 1502"), maxlength: 40 }),
|
||
p8: numIn(amp.p8, "W"), p4: numIn(amp.p4, "W"), p2: numIn(amp.p2, "W"),
|
||
sens: numIn(amp.sens, t("e.g. 1.4")), gain: numIn(amp.gain, t("e.g. 32")) };
|
||
let mode = amp.mode;
|
||
const modeBtns = h("div", { class: "seg" });
|
||
const sensRow = h("label", {}, t("Input sensitivity (V RMS)"), f.sens);
|
||
const gainRow = h("label", {}, t("Gain (dB)"), f.gain);
|
||
const setMode = m => {
|
||
mode = m;
|
||
modeBtns.replaceChildren(...[["sens", t("Sensitivity")], ["gain", t("Gain")]].map(([k, label]) =>
|
||
h("button", { class: k === mode ? "on" : "", onclick: () => setMode(k) }, label)));
|
||
sensRow.hidden = mode !== "sens"; gainRow.hidden = mode !== "gain";
|
||
};
|
||
setMode(mode);
|
||
const err = h("div", { class: "err full" });
|
||
const v = await modal({
|
||
title: isNew ? t("New amplifier") : t("Edit amplifier"),
|
||
body: h("div", { class: "devform ampform" },
|
||
h("label", { class: "full" }, "Name", f.name),
|
||
h("div", { class: "full sub" }, t("Rated RMS power per channel (datasheet, empty = not specified)")),
|
||
h("label", {}, t("into 8 Ω"), f.p8), h("label", {}, t("into 4 Ω"), f.p4), h("label", {}, t("into 2 Ω"), f.p2),
|
||
h("div", { class: "full sub" }, t("Input")), h("div", { class: "full" }, modeBtns),
|
||
h("div", { class: "full" }, sensRow, gainRow),
|
||
h("p", { class: "info full" }, t("Sensitivity = input voltage for full power (e.g. 0.775 V or 1.4 V). "),
|
||
t("If the amplifier has a gain control, the value applies with it turned fully up.")),
|
||
err),
|
||
actions: [{ label: t("Cancel") }, { label: t("Save"), primary: true, value: () => {
|
||
const n = k => Math.max(0, num(f[k].value) || 0);
|
||
const r = { id: amp.id, name: f.name.value.trim() || t("Amplifier"), mode, sens: n("sens"), gain: n("gain"),
|
||
p8: n("p8"), p4: n("p4"), p2: n("p2") };
|
||
if (!r.p8 && !r.p4 && !r.p2) { err.textContent = t("At least one power rating is missing."); return undefined; }
|
||
if (mode === "sens" && !r.sens) { err.textContent = t("Sensitivity is missing."); return undefined; }
|
||
return r;
|
||
} }],
|
||
});
|
||
if (!v) return null;
|
||
const next = limCopy();
|
||
if (isNew) { v.id = Math.random().toString(36).slice(2, 10); next.amps.push(v); }
|
||
else next.amps[next.amps.findIndex(a => a.id === v.id)] = v;
|
||
await saveLim(next);
|
||
render();
|
||
return v.id;
|
||
}
|
||
|
||
function ampCard(a) {
|
||
const used = Object.entries(S.lim.assign).filter(([, v]) => v.amp === a.id).map(([k]) => {
|
||
const [devId, o] = k.split(":"); const d = S.devices[devId];
|
||
return (d ? d.name + " " : "") + chLabel("out", +o);
|
||
});
|
||
const specs = [[8, a.p8], [4, a.p4], [2, a.p2]].filter(p => p[1]).map(([r, p]) => `${fmtW(p)} @ ${r} Ω`).join(" · ");
|
||
return h("div", { class: "card amp" },
|
||
h("h3", {}, h("span", { class: "grow" }, a.name),
|
||
h("button", { class: "icon small", "aria-label": t("Edit"), title: t("Edit"), onclick: () => ampDialog(a) }, svgIcon(ICON.edit))),
|
||
h("div", { class: "ampspec" }, specs),
|
||
h("div", { class: "info" }, a.mode === "gain" ? t("Gain {v} dB", { v: a.gain }) : t("Sensitivity {v} V", { v: a.sens }),
|
||
` (≙ ${(20 * Math.log10(ampGain(a) || 1)).toFixed(1)} dB Gain)`),
|
||
h("div", { class: "info" }, used.length ? t("Used by: ") + used.join(", ") : t("Not assigned to any output")),
|
||
h("div", { class: "actions" }, h("button", { class: "danger small", onclick: async () => {
|
||
if (!await askConfirm(t("Delete amplifier"), t("Delete {name}?", { name: q(a.name) }) + (used.length ? " " + t("Its assignments will be removed.") : ""), t("Delete"), true)) return;
|
||
const next = limCopy();
|
||
next.amps = next.amps.filter(x => x.id !== a.id);
|
||
for (const k of Object.keys(next.assign)) if (next.assign[k].amp === a.id) delete next.assign[k];
|
||
await saveLim(next); render();
|
||
} }, t("Delete"))));
|
||
}
|
||
|
||
// Live result box; returns [element, update(thrRaw)]
|
||
function limResult(d, o) {
|
||
const big = h("div", { class: "lw" }), sub = h("div", { class: "lsub" });
|
||
const bar = h("div", { class: "lbar" }, h("i"), h("b"));
|
||
const notes = h("div", { class: "lnotes" });
|
||
const box = h("div", { class: "lres" }, big, sub, bar, notes);
|
||
const update = raw => {
|
||
const c = limCalc(d.id, o, raw);
|
||
if (!c) { box.className = "lres none"; big.textContent = "—"; sub.textContent = t("No amplifier assigned"); notes.replaceChildren(); return; }
|
||
const spk = c.as.spk, top = Math.max(c.rated, spk, c.p) || 1;
|
||
big.replaceChildren(fmtW(c.p), h("small", {}, ` RMS @ ${c.as.ohm} Ω`));
|
||
sub.textContent = c.rated ? t("{pct} % of {rated}", { pct: Math.round(c.p / c.rated * 100), rated: fmtW(c.rated) }) + " · " + c.amp.name : c.amp.name;
|
||
bar.style.cssText = `--p:${Math.min(1, c.p / top)};--a:${c.rated ? c.rated / top : 0};--s:${spk ? spk / top : 0}`;
|
||
bar.classList.toggle("hasspk", !!spk);
|
||
const n = [];
|
||
let lvl = "ok";
|
||
if (!c.rated) { n.push(["bad", t("Amplifier is not rated for {ohm} Ω", { ohm: c.as.ohm })]); lvl = "bad"; }
|
||
else if (c.over > 0.05) { n.push(["bad", t("Amplifier clips – the limiter engages {db} dB too late", { db: c.over.toFixed(1) })]); lvl = "bad"; }
|
||
else n.push(["ok", t("{db} dB headroom to amplifier clipping", { db: Math.max(0, -c.over).toFixed(1) })]);
|
||
if (spk && c.p > spk * 1.01) { n.push(["warn", t("{pct} % of the speaker rating ({w} RMS)", { pct: Math.round(c.p / spk * 100), w: fmtW(spk) })]); if (lvl === "ok") lvl = "warn"; }
|
||
else if (spk) n.push(["ok", t("Speaker at {pct} % of its rating ({w} RMS)", { pct: Math.round(c.p / spk * 100), w: fmtW(spk) })]);
|
||
box.className = "lres " + lvl;
|
||
notes.replaceChildren(...n.map(([cls, text]) => h("div", { class: cls }, text)));
|
||
};
|
||
return [box, update];
|
||
}
|
||
|
||
function limiterCard(d, o) {
|
||
const oc = chans(d, "out")[o], key = limKey(d.id, o);
|
||
const as = S.lim.assign[key];
|
||
const [res, update] = limResult(d, o);
|
||
const setAssign = async patch => {
|
||
const next = limCopy();
|
||
if (patch === null) delete next.assign[key];
|
||
else next.assign[key] = { ohm: 8, spk: 0, ...(next.assign[key] || {}), ...patch };
|
||
await saveLim(next); render();
|
||
};
|
||
const ampSel = h("select", { "aria-label": t("Amplifier"), onchange: async () => {
|
||
if (ampSel.value === "+") { const id = await ampDialog(null); if (id) setAssign({ amp: id }); else render(); }
|
||
else setAssign(ampSel.value ? { amp: ampSel.value } : null);
|
||
} }, h("option", { value: "" }, t("— no amplifier —")),
|
||
S.lim.amps.map(a => h("option", { value: a.id, selected: as && as.amp === a.id }, a.name)),
|
||
h("option", { value: "+" }, t("+ New amplifier…")));
|
||
const ohmSel = h("select", { "aria-label": t("Impedance"), disabled: !as, onchange: () => setAssign({ ohm: +ohmSel.value }) },
|
||
OHMS.map(r => h("option", { value: r, selected: (as ? as.ohm : 8) === r }, r + " Ω")));
|
||
const spkIn = h("input", { type: "text", inputmode: "decimal", value: as && as.spk ? as.spk : "", placeholder: "optional",
|
||
disabled: !as, "aria-label": t("Speaker RMS"), onchange: () => setAssign({ spk: Math.max(0, num(spkIn.value) || 0) }) });
|
||
|
||
const target = h("input", { type: "text", inputmode: "decimal", placeholder: t("Watts"), "aria-label": t("Target power"), autocomplete: "off" });
|
||
const apply = w => {
|
||
const raw = limThreshFor(d.id, o, w);
|
||
if (raw == null) return toast(t("Assign an amplifier first"));
|
||
setParam("out", o, "limit.threshold", raw);
|
||
target.value = "";
|
||
target.blur();
|
||
const hitEdge = raw === 0 || raw === 220;
|
||
toast(`Threshold ${sign((raw - 180) / 2)} dB → ${fmtW(limCalc(d.id, o, raw).p)}` + (hitEdge ? t(" (end of range reached)") : ""));
|
||
render();
|
||
};
|
||
const c0 = as ? limCalc(d.id, o, 180) : null;
|
||
const ampSafe = c0 && c0.rated ? c0.rated * Math.pow(10, -1 / 10) : 0; // 1 dB below amp clipping
|
||
const chips = c0 ? [
|
||
c0.as.spk ? h("button", { class: "chip", onclick: () => apply(c0.as.spk) }, t("Speaker ") + fmtW(c0.as.spk)) : null,
|
||
ampSafe ? h("button", { class: "chip", onclick: () => apply(ampSafe) }, t("Amplifier −1 dB")) : null,
|
||
ampSafe && c0.as.spk ? h("button", { class: "chip", onclick: () => apply(Math.min(ampSafe, c0.as.spk)) }, t("Lower value")) : null,
|
||
] : [];
|
||
|
||
const card = h("div", { class: "card limcard" },
|
||
h("h3", {}, h("span", { class: "grow" }, chTitle(d, "out", o)), ledMeter(d.id, "out", o, "h"),
|
||
h("button", { class: "small", onclick: () => openChannel("out", o) }, t("Channel"))),
|
||
res,
|
||
h("div", { class: "limgrid" },
|
||
h("label", { class: "full" }, t("Amplifier"), ampSel),
|
||
h("label", {}, t("Load on channel"), ohmSel),
|
||
h("label", {}, t("Speaker RMS (W)"), spkIn)),
|
||
paramSlider("Threshold", "out", o, "limit.threshold", "thresh", update),
|
||
as ? h("div", { class: "target" },
|
||
h("div", { class: "row" }, h("span", { class: "sub" }, t("Limit to")), target,
|
||
h("button", { class: "on", onclick: () => { const w = num(target.value); if (w > 0) apply(w); else target.focus(); } }, t("Set"))),
|
||
chips.filter(Boolean).length ? h("div", { class: "chips" }, chips) : null) : null,
|
||
timingBox(d, o));
|
||
update(oc.limit.threshold);
|
||
return card;
|
||
}
|
||
|
||
// Limiter timing presets per band. Rule of thumb: attack ≈ one period of the lowest frequency
|
||
// the way passes (faster distorts the waveform), release ≈ 16 × attack (slower pumps less).
|
||
// Infra/Sub/Hochton follow the MC2 Delta "auto" table and Dolby SLS LF settings (16 ms / 256 ms).
|
||
const LIM_PRESETS = [
|
||
{ id: "infra", name: "Infra", range: "< 31 Hz", a: 45, r: 720, k: 3 },
|
||
{ id: "sub", name: "Sub", range: "31–63 Hz", a: 16, r: 256, k: 2 },
|
||
{ id: "kick", name: "Kick", range: "63–250 Hz", a: 10, r: 160, k: 2 },
|
||
{ id: "mid", name: t("Mids"), range: "250 Hz–2 kHz", a: 4, r: 64, k: 1 },
|
||
{ id: "high", name: t("Highs"), range: "> 2 kHz", a: 1, r: 16, k: 0 },
|
||
{ id: "full", name: "Fullrange", range: t("no crossover"), a: 8, r: 120, k: 2 },
|
||
];
|
||
// Band preset picked by the channel's high-pass, i.e. its lowest frequency (20 Hz when it has none)
|
||
const AUTO_BANDS = [[31, "infra"], [63, "sub"], [250, "kick"], [2000, "mid"], [Infinity, "high"]];
|
||
function autoPreset(ch) {
|
||
const f = ch.hp.slope ? freqHz(ch.hp.freq) : 20;
|
||
const band = AUTO_BANDS.find(([upTo]) => f < upTo)[1];
|
||
const p = LIM_PRESETS.find(x => x.id === band);
|
||
return { ...p, id: "auto", name: "Auto", range: `${ch.hp.slope ? "HP" : t("no HP")} ${fmtHzShort(f)} → ${p.name}` };
|
||
}
|
||
|
||
const limOpen = new Set();
|
||
function timingBox(d, o) {
|
||
const lim = chans(d, "out")[o].limit, key = limKey(d.id, o);
|
||
const auto = autoPreset(chans(d, "out")[o]);
|
||
const isOn = p => lim.attack === p.a - 1 && lim.release === p.r - 1 && lim.knee === p.k;
|
||
const active = [auto, ...LIM_PRESETS].find(isOn);
|
||
const set = p => {
|
||
setParam("out", o, "limit.attack", p.a - 1);
|
||
setParam("out", o, "limit.release", p.r - 1);
|
||
setParam("out", o, "limit.knee", p.k);
|
||
toast(`${p.name}: Attack ${p.a} ms · Release ${p.r} ms · Knee ${p.k} dB`);
|
||
render();
|
||
};
|
||
const chip = p => h("button", { class: "chip preset" + (isOn(p) ? " on" : ""), title: `${p.a} / ${p.r} ms · Knee ${p.k} dB`, onclick: () => set(p) },
|
||
h("b", {}, p.name), h("small", {}, p.range));
|
||
const box = h("details", { class: "more", open: limOpen.has(key),
|
||
ontoggle: () => box.open ? limOpen.add(key) : limOpen.delete(key) },
|
||
h("summary", {}, `Attack ${lim.attack + 1} ms · Release ${lim.release + 1} ms · Knee ${lim.knee} dB`,
|
||
active ? h("span", { class: "tag" }, active.name) : null),
|
||
h("div", { class: "chips presets" }, chip(auto), LIM_PRESETS.map(chip)),
|
||
paramSlider("Attack", "out", o, "limit.attack", "attack"),
|
||
paramSlider("Release", "out", o, "limit.release", "release"),
|
||
paramSlider("Knee", "out", o, "limit.knee", "knee"),
|
||
h("p", { class: "info" }, t("Rule of thumb: attack ≈ one period of the lowest frequency (faster distorts the bass), "),
|
||
t("release ≈ 16 × attack (shorter pumps). “Auto” picks the band preset matching this channel’s high-pass.")));
|
||
return box;
|
||
}
|
||
|
||
function refCard(d) {
|
||
const inp = h("input", { type: "text", inputmode: "decimal", value: limRef(d.id), "aria-label": t("Reference level in dBu"), class: "short",
|
||
onchange: async () => { const next = limCopy(); next.ref[d.id] = clamp(num(inp.value) || 0, -20, 30); await saveLim(next); render(); } });
|
||
return h("div", { class: "card" }, h("h3", {}, t("Reference level · ") + d.name),
|
||
h("div", { class: "row" }, h("span", { class: "grow" }, t("Limiter 0 dB equals at the output")), inp, h("span", {}, "dBu")),
|
||
h("p", { class: "info" }, t("Thomann does not specify the reference level – 0 dBu (0.775 V) is assumed. To measure: feed a 1 kHz sine, "),
|
||
t("set the threshold to 0 dB, turn up until the limiter engages and measure the output voltage with a multimeter (AC). "),
|
||
t("dBu = 20 · log₁₀(U / 0.775 V).")));
|
||
}
|
||
|
||
function viewLimiter(d) {
|
||
return [
|
||
h("div", { class: "cards" }, chans(d, "out").map((_, o) => limiterCard(d, o))),
|
||
h("p", { class: "info" }, t("Shown is the continuous sine power (RMS) once the limiter engages – music is well below that on average. "),
|
||
t("Assumes the amplifier’s gain control turned fully up (or as entered).")),
|
||
h("h2", { class: "section" }, t("Amplifiers")),
|
||
h("div", { class: "cards" }, S.lim.amps.map(ampCard),
|
||
h("button", { class: "card addcard", onclick: () => ampDialog(null) }, t("+ Add amplifier"))),
|
||
h("h2", { class: "section" }, t("Calibration")),
|
||
h("div", { class: "cards" }, refCard(d)),
|
||
];
|
||
}
|
||
|
||
// ------------------------------------------------------------------ settings
|
||
|
||
function deviceForm(d) {
|
||
const isNew = !d;
|
||
d = d || { name: "", host: "", port: 9761, model: "auto", addr: 1, autoconnect: true, transport: "tcp", usb: "" };
|
||
const f = {
|
||
name: h("input", { type: "text", value: d.name, placeholder: t("e.g. DSP 204 stage") }),
|
||
host: h("input", { type: "text", value: d.host, placeholder: "192.168.1.101", inputmode: "decimal" }),
|
||
port: h("input", { type: "number", value: d.port }),
|
||
model: h("select", {}, [["auto", t("Automatic")], ["204", "DSP 204"], ["408", "DSP 408"]]
|
||
.map(([v, label]) => h("option", { value: v, selected: d.model === v }, label))),
|
||
autoconnect: h("input", { type: "checkbox", checked: d.autoconnect }),
|
||
usb: h("select", { "aria-label": t("USB device") }),
|
||
};
|
||
let transport = d.transport || "tcp";
|
||
// USB device list (both DSP models share one USB ID, so several are told apart by port/path)
|
||
const fillUsb = list => {
|
||
const opts = [["", list.length ? t("First device found") : t("No DSP found via USB")],
|
||
...list.map((u, i) => [u.path, `${u.product || "DSP"} #${i + 1}${u.serial ? " · " + u.serial : ""}`])];
|
||
if (d.usb && !list.some(u => u.path === d.usb)) opts.push([d.usb, t("Saved device (not plugged in)")]);
|
||
f.usb.replaceChildren(...opts.map(([v, label]) => h("option", { value: v, selected: v === (d.usb || "") }, label)));
|
||
};
|
||
const loadUsb = () => api("GET", "/api/usb").then(fillUsb).catch(() => fillUsb([]));
|
||
fillUsb([]);
|
||
const netRows = [h("label", {}, t("IP address"), f.host), h("label", {}, "Port", f.port)];
|
||
const usbRow = h("label", { class: "full" }, t("USB device"),
|
||
h("div", { class: "row" }, f.usb, h("button", { class: "small", type: "button", onclick: loadUsb, title: t("Search again") }, "↻")));
|
||
const seg = h("div", { class: "seg full" });
|
||
// existing device: the connection type and USB device are saved right away, so t("Connect") uses them
|
||
const saveConn = () => isNew || api("PUT", `/api/devices/${d.id}`, { transport, usb: f.usb.value }).catch(e => toast(e.message));
|
||
f.usb.addEventListener("change", saveConn);
|
||
const setTransport = (mode, save) => {
|
||
transport = mode;
|
||
if (save && mode !== (d.transport || "tcp")) saveConn();
|
||
seg.replaceChildren(...[["tcp", t("Network")], ["usb", t("USB cable")]].map(([k, label]) =>
|
||
h("button", { type: "button", class: k === mode ? "on" : "", onclick: () => setTransport(k, true) }, label)));
|
||
netRows.forEach(r => (r.hidden = mode === "usb"));
|
||
usbRow.hidden = mode !== "usb";
|
||
if (mode === "usb") loadUsb();
|
||
};
|
||
setTransport(transport);
|
||
const values = () => ({ name: f.name.value.trim() || (transport === "usb" ? "DSP (USB)" : f.host.value.trim()),
|
||
host: f.host.value.trim(), port: +f.port.value || 9761, model: f.model.value, autoconnect: f.autoconnect.checked,
|
||
transport, usb: f.usb.value });
|
||
const actions = isNew
|
||
? [h("button", { class: "on", onclick: async () => {
|
||
if (transport === "tcp" && !values().host) return toast(t("IP address missing"));
|
||
try { const nd = await api("POST", "/api/devices", values()); S.cur = nd.id; toast(t("Added")); }
|
||
catch (e) { toast(e.message); }
|
||
} }, t("Add"))]
|
||
: [
|
||
h("button", { onclick: async () => { try { await api("PUT", `/api/devices/${d.id}`, values()); toast(t("Saved")); } catch (e) { toast(e.message); } } }, t("Save")),
|
||
d.status === "disconnected" || d.status === "error"
|
||
? h("button", { class: "on", onclick: async () => { // connects with what the form shows, saved or not
|
||
try { await api("PUT", `/api/devices/${d.id}`, values()); await api("POST", `/api/devices/${d.id}/connect`); }
|
||
catch (e) { toast(e.message); }
|
||
} }, t("Connect"))
|
||
: h("button", { onclick: () => api("POST", `/api/devices/${d.id}/disconnect`).catch(e => toast(e.message)) }, t("Disconnect")),
|
||
h("button", { class: "danger", onclick: async () => {
|
||
if (await askConfirm(t("Remove device"), t("Remove {name} from the list?", { name: q(d.name) }), t("Remove"), true))
|
||
await api("DELETE", `/api/devices/${d.id}`).catch(e => toast(e.message));
|
||
} }, t("Remove")),
|
||
];
|
||
return h("div", { class: "card" },
|
||
h("h3", {}, isNew ? null : h("span", { class: "dot " + d.status }), h("span", { class: "grow" }, isNew ? t("New device") : d.name),
|
||
isNew ? null : h("span", { class: "info" }, STATUS_TEXT[d.status])),
|
||
!isNew && d.info ? h("div", { class: "info" }, t("Device reports: ") + d.info) : null,
|
||
!isNew && d.error ? h("div", { class: "err" }, trMsg(d.error)) : null,
|
||
h("div", { class: "devform" },
|
||
h("label", { class: "full" }, "Name", f.name),
|
||
h("div", { class: "full sub" }, t("Connection")), seg,
|
||
...netRows, usbRow,
|
||
h("label", {}, t("Model"), f.model),
|
||
h("label", { class: "chk" }, f.autoconnect, t("Connect automatically")),
|
||
h("div", { class: "actions" }, actions)));
|
||
}
|
||
|
||
// App settings backup: devices, amplifiers/limiter data, PIN, remote access (not the DSP presets)
|
||
function backupCard() {
|
||
const exportCfg = async () => {
|
||
try { if (await saveFile(`DSP-Control-${t("Settings")}_${today()}.json`, await api("GET", "/api/backup"))) toast(t("Settings backed up")); }
|
||
catch (e) { toast(t("Error: ") + e.message); }
|
||
};
|
||
const restore = async () => {
|
||
try {
|
||
const f = await openFile();
|
||
if (!f) return;
|
||
const doc = f.json;
|
||
if (!doc || doc.format !== "dsp-control-config") return toast(t("Not a DSP Control settings backup"));
|
||
const when = doc.exported ? doc.exported.replace("T", " ").slice(0, 16) : "?";
|
||
const pin = h("input", { type: "password", inputmode: "numeric", maxlength: 4, autocomplete: "off", placeholder: "••••" });
|
||
const ok = await modal({ title: t("Restore settings"),
|
||
body: h("div", { class: "form" },
|
||
h("p", { class: "dlg-text" }, t("Devices ({n}), amplifier and limiter data, PIN and remote access will be replaced by the " +
|
||
"backup from {when}. The presets inside the DSPs stay unchanged.", { n: (doc.devices || []).length, when })),
|
||
S.isApp ? null : h("label", {}, t("Current PIN"), pin)),
|
||
actions: [{ label: t("Cancel") }, { label: t("Restore"), primary: true, value: () => true }] });
|
||
if (!ok) return;
|
||
await api("POST", "/api/backup", { doc, pin: pin.value });
|
||
toast(t("Settings restored"));
|
||
setTimeout(() => location.reload(), 800);
|
||
} catch (e) { toast(t("Error: ") + e.message); }
|
||
};
|
||
return h("div", { class: "card" }, h("h3", {}, t("App settings")),
|
||
h("p", { class: "info" }, t("Saves devices, amplifiers & limiter calculator, PIN and remote access to a file. ") +
|
||
t("The settings inside the DSPs are saved per device via “File…” at the top.")),
|
||
h("div", { class: "row" }, h("button", { onclick: exportCfg }, t("Back up…")), h("button", { onclick: restore }, t("Restore…"))));
|
||
}
|
||
|
||
// Desktop app only: let phones/tablets on the LAN use this PC as server (they need the PIN)
|
||
function remoteCard() {
|
||
const r = S.remote || { enabled: false, port: 8080, urls: [] };
|
||
const port = h("input", { type: "number", min: 1, max: 65535, value: r.port, class: "short", "aria-label": "Port" });
|
||
const put = async body => {
|
||
try { S.remote = await api("PUT", "/api/remote", body); } catch (e) { toast(e.message); }
|
||
render();
|
||
};
|
||
const sw = h("button", { class: r.enabled ? "on" : "", "aria-pressed": String(r.enabled), onclick: () => put({ enabled: !r.enabled, port: +port.value || 8080 }) },
|
||
r.enabled ? t("On") : t("Off"));
|
||
let status;
|
||
if (r.error) status = h("div", { class: "err" }, trMsg(r.error));
|
||
else if (r.running) status = h("div", { class: "remote-urls" }, h("div", { class: "info" }, t("Open on a phone in the same Wi-Fi:")),
|
||
r.urls.length ? r.urls.map(u => h("code", {}, u)) : h("code", {}, `http://<${t("IP of this computer")}>:${r.port}`));
|
||
else status = h("p", { class: "info" }, t("Off – only this window has access."));
|
||
return h("div", { class: "card" }, h("h3", {}, h("span", { class: "dot " + (r.running ? "online" : r.error ? "error" : "disconnected") }),
|
||
h("span", { class: "grow" }, t("Remote access (web server)"))),
|
||
h("div", { class: "row" }, h("span", { class: "grow" }, t("Allow phones & tablets")), sw),
|
||
h("div", { class: "row" }, h("span", { class: "grow" }, "Port"), port,
|
||
h("button", { class: "small", onclick: () => put({ port: +port.value || 8080 }) }, t("Apply"))),
|
||
status,
|
||
h("p", { class: "info" }, t("Other devices log in with the PIN (changeable below). Only runs while this app is open. "),
|
||
r.platform === "darwin"
|
||
? t("If the macOS firewall is on, it asks the first time – choose “Allow”.")
|
||
: t("The first time, Windows Firewall asks – choose “Allow” for private networks.")));
|
||
}
|
||
|
||
function pinCard() {
|
||
const pin = ph => h("input", { type: "password", inputmode: "numeric", pattern: "[0-9]*", maxlength: 4, autocomplete: "off", placeholder: ph });
|
||
const cur = pin("••••"), nw = pin("••••"), rep = pin("••••");
|
||
const err = h("div", { class: "err" });
|
||
return h("div", { class: "card" }, h("h3", {}, S.isApp ? t("PIN for remote access") : t("Access (PIN)")),
|
||
h("div", { class: "devform" },
|
||
S.isApp ? null : h("label", { class: "full" }, t("Current PIN"), cur),
|
||
h("label", {}, t("New PIN"), nw), h("label", {}, t("Repeat"), rep),
|
||
err,
|
||
h("div", { class: "actions" },
|
||
h("button", { class: "on", onclick: async () => {
|
||
err.textContent = "";
|
||
if (!/^\d{4}$/.test(nw.value)) return (err.textContent = t("The new PIN must be 4 digits."));
|
||
if (nw.value !== rep.value) return (err.textContent = t("The new PINs do not match."));
|
||
try {
|
||
await api("POST", "/api/pin", { current: cur.value, new: nw.value });
|
||
cur.value = nw.value = rep.value = ""; toast(t("PIN changed – other devices were logged out"));
|
||
} catch (e) { err.textContent = e.message; }
|
||
} }, t("Change PIN")),
|
||
S.isApp ? null : h("button", { onclick: logout }, svgIcon(ICON.logout), t(" Log out")))),
|
||
h("p", { class: "info" }, S.isApp
|
||
? t("This app needs no PIN. The default is 1234; changing it logs out all phones.")
|
||
: t("The default PIN is 1234. After changing it only this device stays logged in.")));
|
||
}
|
||
|
||
// Language per device (stored in the browser); the desktop app also tells the server, for its own dialogs
|
||
function langCard() {
|
||
const set = async lang => {
|
||
if (lang === LANG) return;
|
||
store.set("dsp.lang", lang);
|
||
if (S.isApp) await api("PUT", "/api/lang", { lang }).catch(() => {});
|
||
location.reload();
|
||
};
|
||
return h("div", { class: "card" }, h("h3", {}, "Language / Sprache"),
|
||
h("div", { class: "seg" }, Object.entries(LANGS).map(([k, label]) =>
|
||
h("button", { class: k === LANG ? "on" : "", "aria-pressed": String(k === LANG), "data-view-ok": "", onclick: () => set(k) }, label))));
|
||
}
|
||
|
||
function viewSettings() {
|
||
return [
|
||
h("div", { class: "cards" }, langCard()),
|
||
h("h2", { class: "section" }, t("Devices")),
|
||
h("div", { class: "cards" }, ...S.order.map(id => deviceForm(S.devices[id])), deviceForm(null)),
|
||
h("p", { class: "info" }, t("Both DSPs can be connected at the same time – switch between them at the top. "),
|
||
t("The DSPs accept only one connection: close the Thomann editor first.")),
|
||
h("h2", { class: "section" }, S.isApp ? t("Remote access") : t("Security")),
|
||
h("div", { class: "cards" }, S.isApp ? remoteCard() : null, pinCard()),
|
||
h("h2", { class: "section" }, t("Backup")),
|
||
h("div", { class: "cards" }, backupCard()),
|
||
];
|
||
}
|
||
|
||
// ------------------------------------------------------------------ render
|
||
|
||
const H_SCROLL = ".mixer, .bands, .geq, .routing";
|
||
function render() {
|
||
if (S.busy) { S.dirty = true; return; }
|
||
if ($("#app").hidden) return;
|
||
if (!S.devices[S.cur]) S.cur = S.order[0] || null;
|
||
// keep focus on a text field (e.g. while typing a device name) – re-rendering would steal it
|
||
const ae = document.activeElement;
|
||
if (ae && main.contains(ae) && ae.matches("input[type=text], input[type=number], input[type=password]")) { S.dirty = true; return; }
|
||
renderTabs();
|
||
renderStatus();
|
||
const y = window.scrollY;
|
||
// keep sideways scroll positions (mixer on a phone, EQ bands …) while the view stays the same
|
||
const viewKey = `${S.cur}|${S.settings}|${S.view}|${S.sel.kind}|${S.sel.idx}`;
|
||
const xs = viewKey === render.viewKey ? [...main.querySelectorAll(H_SCROLL)].map(e => e.scrollLeft) : [];
|
||
render.viewKey = viewKey;
|
||
live.clear();
|
||
let content;
|
||
const d = dev();
|
||
document.body.dataset.view = S.settings || !d ? "settings" : S.view;
|
||
if (S.settings || !d) content = viewSettings();
|
||
else if (d.status !== "online" || !d.state)
|
||
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 === "connecting" ? t("Connecting to {where}…", { where: where(d) }) : t("Not connected."));
|
||
else content = ({ mixer: viewMixer, channel: viewChannel, routing: viewRouting, link: viewLink, limiter: viewLimiter }[S.view] || viewMixer)(d);
|
||
main.replaceChildren(...[content].flat().filter(Boolean));
|
||
main.querySelectorAll(H_SCROLL).forEach((e, i) => { if (xs[i]) e.scrollLeft = xs[i]; });
|
||
window.scrollTo(0, y);
|
||
collectMeters();
|
||
}
|
||
// flush deferred renders once a text field loses focus
|
||
main.addEventListener("focusout", () => setTimeout(() => {
|
||
if (S.dirty && !S.busy && !main.contains(document.activeElement)) { S.dirty = false; render(); }
|
||
}, 0));
|
||
|
||
document.querySelectorAll("#viewtabs button").forEach(b => b.addEventListener("click", () => {
|
||
S.view = b.dataset.view; S.settings = false; store.set("dsp.view", S.view); render(); window.scrollTo(0, 0);
|
||
}));
|
||
$("#btn-settings").addEventListener("click", () => { S.settings = !S.settings; render(); window.scrollTo(0, 0); });
|
||
|
||
// header / status bar heights -> CSS vars (sticky channel bar, fader height that fits the screen)
|
||
new ResizeObserver(() => {
|
||
document.documentElement.style.setProperty("--hdr", $("#top").offsetHeight + "px");
|
||
document.documentElement.style.setProperty("--sb", $("#statusbar").offsetHeight + "px");
|
||
}).observe($("#top"));
|
||
new ResizeObserver(() => document.documentElement.style.setProperty("--sb", $("#statusbar").offsetHeight + "px")).observe($("#statusbar"));
|
||
|
||
// ------------------------------------------------------------------ lock (desktop app window: look, don't touch)
|
||
|
||
function showLock() {
|
||
const b = $("#btn-lock");
|
||
b.hidden = !S.isApp;
|
||
document.body.classList.toggle("locked", !!S.locked);
|
||
b.classList.toggle("on", !!S.locked);
|
||
b.title = S.locked ? t("Locked – click to unlock") : t("Lock (view only)");
|
||
b.setAttribute("aria-label", b.title);
|
||
b.replaceChildren(...[svgIcon(S.locked ? ICON.lock : ICON.unlock), S.locked ? h("span", {}, t("Locked")) : null].filter(Boolean));
|
||
}
|
||
|
||
$("#btn-lock").addEventListener("click", async () => {
|
||
if (!S.locked) {
|
||
try { await api("POST", "/api/lock"); S.locked = true; showLock(); render(); toast(t("Locked – values are view-only")); }
|
||
catch (e) { toast(t("Error: ") + e.message); }
|
||
return;
|
||
}
|
||
const pin = h("input", { type: "password", inputmode: "numeric", maxlength: 4, autocomplete: "off", placeholder: "••••", "aria-label": "PIN" });
|
||
const err = h("div", { class: "err" });
|
||
await modal({ title: t("Unlock"), body: h("div", { class: "form" }, h("label", {}, t("PIN (same as on the phone)"), pin), err),
|
||
actions: [{ label: t("Cancel") }, { label: t("Unlock"), primary: true, value: () => {
|
||
api("POST", "/api/unlock", { pin: pin.value }).then(() => {
|
||
S.locked = false; showLock(); render(); toast(t("Unlocked"));
|
||
$("#modal .dlg-actions button").click(); // close the dialog
|
||
}).catch(e => {
|
||
err.textContent = e.message === "locked" ? t("Too many attempts – please wait a moment") : t("Wrong PIN");
|
||
pin.value = ""; pin.focus();
|
||
});
|
||
return undefined; // keep the dialog open until the PIN is confirmed
|
||
} }] });
|
||
});
|
||
|
||
// 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]";
|
||
for (const type of ["pointerdown", "mousedown", "click", "dblclick", "keydown", "wheel"]) {
|
||
document.addEventListener(type, e => {
|
||
if (!S.locked || !(e.target instanceof Element)) return;
|
||
const tgt = e.target;
|
||
if (!tgt.closest("#main, #statusbar") || tgt.closest(VIEW_OK)) return;
|
||
if (type === "wheel" && !tgt.closest(".fader, input, select")) return; // page scrolling stays
|
||
if (type === "keydown" && !tgt.closest("button, input, select, textarea, .fader, [tabindex]")) return;
|
||
if (type === "pointerdown" && !tgt.closest("button, input, select, textarea, .fader, canvas, a")) return;
|
||
e.preventDefault(); e.stopPropagation();
|
||
if (type === "click" && Date.now() - (S.lockToast || 0) > 1500) { S.lockToast = Date.now(); toast(t("Locked – unlock at the top right to make changes")); }
|
||
}, { capture: true, passive: false });
|
||
}
|
||
|
||
// ------------------------------------------------------------------ live events
|
||
|
||
function setDevices(list) {
|
||
S.devices = {}; S.order = [];
|
||
for (const d of list) { S.devices[d.id] = d; S.order.push(d.id); }
|
||
}
|
||
|
||
function connectEvents() {
|
||
if (S.es) S.es.close();
|
||
const es = S.es = new EventSource("/api/events");
|
||
es.onmessage = m => {
|
||
const ev = JSON.parse(m.data);
|
||
switch (ev.type) {
|
||
case "hello":
|
||
setDevices(ev.devices);
|
||
if (ev.limiter) S.lim = ev.limiter;
|
||
if (!S.order.length) S.settings = true;
|
||
render(); break;
|
||
case "device":
|
||
if (!S.devices[ev.device]) S.order.push(ev.device);
|
||
S.devices[ev.device] = ev.data;
|
||
render(); break;
|
||
case "removed":
|
||
delete S.devices[ev.device]; S.order = S.order.filter(id => id !== ev.device);
|
||
render(); break;
|
||
case "status": {
|
||
const d = S.devices[ev.device];
|
||
if (!d) break;
|
||
Object.assign(d, { status: ev.status, error: ev.error, info: ev.info });
|
||
if (ev.status !== "online") render(); else renderTabs();
|
||
break;
|
||
}
|
||
case "param": {
|
||
const d = S.devices[ev.device];
|
||
if (!d || !d.state) break;
|
||
const ch = chans(d, ev.kind)[ev.idx];
|
||
if (Date.now() - (recentlySet.get(`${ev.device}|${ev.kind}|${ev.idx}|${ev.param}`) || 0) < 1500) break; // own echo
|
||
if (JSON.stringify(getPath(ch, ev.param)) === JSON.stringify(ev.value)) break;
|
||
setPath(ch, ev.param, ev.value);
|
||
showLive(`${ev.device}|${ev.kind}|${ev.idx}|${ev.param}`, ev.value); // even while a fader is held
|
||
if (ev.device === S.cur && !S.settings) render();
|
||
break;
|
||
}
|
||
case "lock":
|
||
if (S.isApp) { S.locked = ev.locked; showLock(); render(); }
|
||
break;
|
||
case "meters":
|
||
updateMeters(ev); break;
|
||
case "limiter":
|
||
S.lim = ev.data;
|
||
if (!S.busy && (S.view === "limiter" || S.view === "channel")) render();
|
||
break;
|
||
}
|
||
};
|
||
es.onerror = async () => {
|
||
renderTabs();
|
||
try { const a = await (await fetch("/api/auth")).json(); if (!a.authenticated) showLogin(); } catch { /* server down: EventSource retries */ }
|
||
};
|
||
}
|
||
|
||
// ------------------------------------------------------------------ login
|
||
|
||
function showLogin() {
|
||
if (S.es) { S.es.close(); S.es = null; }
|
||
$("#app").hidden = true;
|
||
$("#modal").hidden = true;
|
||
const root = $("#login");
|
||
if (!root.hidden) return;
|
||
let pin = "", busy = false, lockT = null;
|
||
const dots = h("div", { class: "pindots" }, [0, 1, 2, 3].map(() => h("i")));
|
||
const msg = h("div", { class: "pinmsg" }, " ");
|
||
const paint = () => [...dots.children].forEach((d, i) => d.classList.toggle("on", i < pin.length));
|
||
const lock = secs => {
|
||
clearInterval(lockT); busy = true;
|
||
const end = Date.now() + secs * 1000;
|
||
const tick = () => {
|
||
const left = Math.ceil((end - Date.now()) / 1000);
|
||
if (left <= 0) { clearInterval(lockT); busy = false; msg.textContent = " "; pad.classList.remove("locked"); return; }
|
||
msg.textContent = t("Too many attempts – locked for {s} s", { s: left });
|
||
};
|
||
pad.classList.add("locked"); tick(); lockT = setInterval(tick, 500);
|
||
};
|
||
const submit = async () => {
|
||
busy = true;
|
||
try {
|
||
const r = await fetch("/api/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pin }) });
|
||
const data = await r.json().catch(() => ({}));
|
||
if (r.ok) { root.hidden = true; root.replaceChildren(); clearInterval(lockT); startApp(); return; }
|
||
pin = ""; paint();
|
||
dots.classList.remove("shake"); void dots.offsetWidth; dots.classList.add("shake");
|
||
buzz();
|
||
busy = false;
|
||
if (data.retry) lock(data.retry);
|
||
else msg.textContent = r.status === 401 ? (data.left ? t("Wrong PIN – {n} attempts left", { n: data.left }) : t("Wrong PIN")) : t("Error: ") + trMsg(data.error || r.status);
|
||
} catch { msg.textContent = t("Server not reachable"); pin = ""; paint(); busy = false; }
|
||
};
|
||
const press = k => {
|
||
if (busy) return;
|
||
if (k === "del") pin = pin.slice(0, -1);
|
||
else if (pin.length < 4) pin += k;
|
||
paint();
|
||
if (pin.length === 4) submit();
|
||
};
|
||
const key = (k, label) => h("button", { class: "pk" + (k === "del" ? " del" : ""), "aria-label": k === "del" ? t("Delete") : k,
|
||
onpointerdown: e => { e.preventDefault(); press(k); }, onclick: e => { if (e.detail === 0) press(k); } }, label ?? k);
|
||
const pad = h("div", { class: "pinpad" },
|
||
["1", "2", "3", "4", "5", "6", "7", "8", "9"].map(k => key(k)), h("span"), key("0"), key("del", "⌫"));
|
||
root.replaceChildren(h("div", { class: "loginbox" },
|
||
h("div", { class: "logo" }, $(".brand svg").cloneNode(true)),
|
||
h("h1", {}, "DSP Control"), h("p", {}, t("Enter PIN")), dots, msg, pad));
|
||
root.hidden = false;
|
||
root.onkeydown = null;
|
||
document.onkeydown = e => {
|
||
if (root.hidden) return;
|
||
if (/^\d$/.test(e.key)) press(e.key);
|
||
else if (e.key === "Backspace") press("del");
|
||
};
|
||
}
|
||
|
||
async function logout() {
|
||
await fetch("/api/logout", { method: "POST" }).catch(() => {});
|
||
showLogin();
|
||
}
|
||
|
||
async function startApp() {
|
||
$("#app").hidden = false;
|
||
try {
|
||
const a = await (await fetch("/api/auth")).json();
|
||
S.isApp = !!a.app;
|
||
// desktop app: the language chosen there is kept by the server too (survives a reset web view)
|
||
if (S.isApp && a.lang && a.lang !== LANG) {
|
||
store.set("dsp.lang", a.lang);
|
||
if (store.get("dsp.lang") === a.lang) return location.reload();
|
||
}
|
||
S.locked = !!a.locked;
|
||
showLock();
|
||
if (S.isApp) S.remote = await api("GET", "/api/remote");
|
||
} catch { /* plain web UI */ }
|
||
connectEvents();
|
||
}
|
||
|
||
(async function init() {
|
||
try {
|
||
const a = await (await fetch("/api/auth")).json();
|
||
if (a.authenticated) startApp(); else showLogin();
|
||
} catch { showLogin(); }
|
||
})();
|