2748 lines
158 KiB
JavaScript
2748 lines
158 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") || "dash", settings: false, dash: null,
|
||
sel: { kind: "in", idx: 0 }, band: 0, busy: false, dirty: false,
|
||
routeOpen: null, es: null, linkSel: { in: [], out: [] }, linkEdit: { in: null, out: null }, firSel: { kind: "out", idx: 0 }, firDraft: null, firCoef: {},
|
||
lim: { amps: [], assign: {}, ref: {} },
|
||
demo: { enabled: false, model: "408" },
|
||
muteAll: false,
|
||
};
|
||
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"/>',
|
||
muteall: '<path d="M4 9v6h4l5 4V5L8 9z"/><path d="M16.5 9.5l5 5M21.5 9.5l-5 5"/>',
|
||
link: '<path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/>',
|
||
};
|
||
|
||
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 MODEL_LABEL = { "204": "DSP 204", "408": "DSP 408", "206": "DSP 206", "408fir": "FIR DSP 408" };
|
||
const MODEL_CH = { "204": [2, 4], "408": [4, 8], "206": [2, 6], "408fir": [4, 8] }; // inputs, outputs (before a DSP has connected)
|
||
const BETA_MODELS = ["206", "408fir"];
|
||
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] };
|
||
}
|
||
// group names are kept by the app, keyed by the members (a changed group starts without a name)
|
||
const linkKey = (kind, g) => `${kind}:${g.join(",")}`;
|
||
const linkName = (d, kind, g) => (d.linknames || {})[linkKey(kind, g)] || "";
|
||
const linkBadge = (d, kind, i) => {
|
||
const l = linkInfo(d, kind, i);
|
||
return l ? h("span", { class: "lnk", style: `--lc:${custColor(d, kind, i) || l.color}`, title: t("Linked: ") + l.group.map(j => chLabel(kind, j)).join(" + ") },
|
||
svgIcon(ICON.link)) : null;
|
||
};
|
||
// polarity inverted ("Phase Ø" in the channel view)
|
||
const polBadge = (d, kind, i) => chans(d, kind)[i].polarity
|
||
? h("span", { class: "pol", title: t("Phase inverted") }, "Ø") : null;
|
||
|
||
// ------------------------------------------------------------------ channel colours (chosen in the settings, kept by the app)
|
||
|
||
const CH_PALETTE = ["#ef4444", "#f97316", "#f59e0b", "#eab308", "#84cc16", "#22c55e", "#14b8a6", "#06b6d4",
|
||
"#38bdf8", "#3b82f6", "#6366f1", "#8b5cf6", "#a855f7", "#d946ef", "#ec4899", "#f43f5e", "#e5e7eb", "#94a3b8"];
|
||
// channel groups of one kind: linked channels together, the others on their own
|
||
function chanGroups(d, kind) {
|
||
if (d.state) return linkGroups(chans(d, kind));
|
||
const n = (kind === "in" ? d.n_in : d.n_out) || (MODEL_CH[d.model] || MODEL_CH["204"])[kind === "in" ? 0 : 1];
|
||
return Array.from({ length: n }, (_, i) => [i]);
|
||
}
|
||
// the colour chosen for a channel; linked channels show their group's colour
|
||
function custColor(d, kind, i) {
|
||
const cols = d.colors || {}, li = d.state && linkInfo(d, kind, i);
|
||
for (const j of li ? li.group : [i]) if (cols[kind + j]) return cols[kind + j];
|
||
return null;
|
||
}
|
||
const inColor = (d, i) => custColor(d, "in", i) || IN_COLORS[i];
|
||
// software max level of a channel's gain (raw), null = none; above it a fader can only go down (see gain_cap in device.py)
|
||
const maxGain = (d, kind, i) => (d && d.maxgain || {})[kind + i] ?? null;
|
||
function gainCap(d, kind, i) {
|
||
const lim = maxGain(d, kind, i);
|
||
return lim == null ? null : Math.max(lim, chans(d, kind)[i].gain);
|
||
}
|
||
const ccStyle = (d, kind, i) => { const c = custColor(d, kind, i) || (kind === "in" ? IN_COLORS[i] : null); return c ? `--cc:${c}` : ""; };
|
||
|
||
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(accept = ".json,.bin,application/json,application/octet-stream") {
|
||
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, 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 };
|
||
}
|
||
|
||
// cap: highest raw value allowed without confirmation (software max level), or null.
|
||
// Above it the dialog warns and Apply has to be clicked twice; the result is then {value, force: true}.
|
||
function askValue(label, spec, raw, cap = null) {
|
||
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(); check(); } }, "0 dB") : null;
|
||
const warn = h("div", { class: "overlim", hidden: true });
|
||
let armed = false;
|
||
const parsed = () => { const s = input.value.trim(); return !s || isNaN(num(s)) ? null : clamp(spec.parse(s), spec.min, spec.max); };
|
||
const applyBtn = () => document.querySelector("#modal .dlg-actions button:last-child");
|
||
const check = () => {
|
||
const v = parsed(), over = cap != null && v != null && v > cap;
|
||
warn.hidden = !over;
|
||
if (over) warn.replaceChildren(svgIcon(ICON.lock), h("span", {}, t("Above the max level of {lim} – press Apply twice to set it anyway.", { lim: spec.fmt(cap) })));
|
||
if (armed && !over) { armed = false; const b = applyBtn(); if (b) { b.textContent = t("Apply"); b.className = "on"; } }
|
||
};
|
||
input.addEventListener("input", check);
|
||
return modal({
|
||
title: label,
|
||
body: h("div", {}, h("div", { class: "row" }, input, quick),
|
||
cap != null ? h("p", { class: "info limnote" }, svgIcon(ICON.lock), t("Max level: {lim}", { lim: spec.fmt(cap) })) : null,
|
||
warn, h("p", { class: "info" }, spec.hint || "")),
|
||
onOpen: check,
|
||
actions: [{ label: t("Cancel") }, { label: t("Apply"), primary: true, value: () => {
|
||
const v = parsed();
|
||
if (v == null) { input.classList.add("bad"); return undefined; }
|
||
if (cap != null && v > cap) {
|
||
if (!armed) { // first click: ask again
|
||
armed = true;
|
||
const b = applyBtn();
|
||
if (b) { b.textContent = t("Set anyway"); b.className = "danger-on"; }
|
||
return undefined;
|
||
}
|
||
return { value: v, force: true };
|
||
}
|
||
return v;
|
||
} }],
|
||
});
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 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, force = false) {
|
||
const d = dev();
|
||
if (!d || !d.state) return;
|
||
if (param === "gain" && !force) { const c = gainCap(d, kind, idx); if (c != null) value = Math.min(value, c); }
|
||
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, ...(force ? { force: true } : {}) };
|
||
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, force = false) => {
|
||
v = clamp(Math.round(v), spec.min, spec.max);
|
||
if (path === "gain" && !force) { const c = gainCap(dev(), kind, idx); if (c != null) v = Math.min(v, c); } // software max level
|
||
input.value = v;
|
||
input.limSync && input.limSync();
|
||
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, force);
|
||
onChange && onChange(v);
|
||
};
|
||
onLive(kind, idx, path, v => { input.value = v; input.limSync && input.limSync(); 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(), path === "gain" ? gainCap(dev(), kind, idx) : null);
|
||
if (v != null) typeof v === "object" ? commit(v.value, true) : commit(v);
|
||
});
|
||
const lim = path === "gain" ? maxGain(dev(), kind, idx) : null;
|
||
if (lim != null) { // locked range above the max level, part of the track (stays behind the knob)
|
||
input.classList.add("haslim");
|
||
input.style.setProperty("--lim", (lim - spec.min) / (spec.max - spec.min));
|
||
const showVal = () => input.style.setProperty("--val", (Math.max(+input.value, lim) - spec.min) / (spec.max - spec.min));
|
||
showVal();
|
||
input.addEventListener("input", showVal);
|
||
new MutationObserver(showVal).observe(input, { attributes: true, attributeFilter: ["value"] });
|
||
input.limSync = showVal;
|
||
input.title = `${t("Max level")}: ${spec.fmt(lim)}`;
|
||
}
|
||
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, cap, limit }) {
|
||
const capEl = 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,
|
||
limit != null ? h("div", { class: "limzone", style: `--f:${(limit - min) / (max - min)}`, title: t("Max level") }) : null,
|
||
limit != null ? h("div", { class: "limbelow", style: `--f:${(limit - min) / (max - min)}` }) : null, capEl);
|
||
let cur = value;
|
||
const place = () => {
|
||
capEl.style.setProperty("--f", (cur - min) / (max - min));
|
||
el.style.setProperty("--v", (cur - min) / (max - min)); // used by the max level zone
|
||
el.setAttribute("aria-valuenow", cur);
|
||
el.classList.toggle("atzero", cur === zero);
|
||
};
|
||
const set = (v, snap) => {
|
||
v = clamp(Math.round(v), min, max);
|
||
if (cap) { const c = cap(); if (c != null) v = Math.min(v, c); } // software max level
|
||
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
|
||
|
||
// DSP selection: one button with the current DSP, the others in a drop-down menu (room for many devices)
|
||
function renderTabs() {
|
||
const tabs = $("#devtabs");
|
||
const order = [...S.order].sort((a, b) => !!S.devices[b].demo - !!S.devices[a].demo); // demo first
|
||
const testLock = testOn(dev());
|
||
const badge = d => {
|
||
const model = d.detected_model || (d.model !== "auto" ? d.model : "");
|
||
return testOn(d) ? h("small", { class: "test-badge" }, "TEST") : d.demo ? h("small", { class: "demo-badge" }, "DEMO")
|
||
: model ? h("small", {}, (MODEL_LABEL[model] || model).replace("DSP ", "")) : null;
|
||
};
|
||
const cur = S.devices[S.cur];
|
||
if (!cur) {
|
||
S.devMenu = false;
|
||
tabs.replaceChildren(h("button", { class: "devtab devpick", onclick: () => { S.settings = true; render(); } }, h("span", { class: "dn" }, t("Add a DSP…"))));
|
||
} else {
|
||
const others = order.filter(id => id !== S.cur).slice(0, 8);
|
||
const pick = h("button", { class: "devtab devpick" + (S.settings ? "" : " active") + (cur.demo ? " demo" : ""), "aria-haspopup": "listbox",
|
||
"aria-expanded": String(!!S.devMenu), title: cur.demo ? t("Demo mode – simulated DSP") : `${cur.name} · ${where(cur)}`,
|
||
onclick: e => { e.stopPropagation(); S.devMenu = !S.devMenu; renderTabs(); } },
|
||
h("span", { class: "dot " + cur.status }), h("span", { class: "dn" }, cur.name), badge(cur),
|
||
others.length ? h("span", { class: "minidots", "aria-hidden": "true" }, others.map(id => h("i", { class: "dot " + S.devices[id].status }))) : null,
|
||
h("span", { class: "chev" + (S.devMenu ? " open" : "") }, svgIcon('<path d="M6 9l6 6 6-6"/>')));
|
||
const menu = S.devMenu ? h("div", { class: "devmenu", role: "listbox" }, order.map(id => {
|
||
const d = S.devices[id], paused = S.demo.enabled && !d.demo; // demo mode: the real DSPs are disconnected
|
||
return h("button", { class: "devitem" + (id === S.cur ? " on" : "") + (paused ? " paused" : ""), role: "option", "aria-selected": String(id === S.cur),
|
||
disabled: paused || (testLock && id !== S.cur),
|
||
title: paused ? t("Disconnected while demo mode is on") : `${d.name} · ${where(d)}`,
|
||
onclick: () => { S.devMenu = false; S.cur = id; S.settings = false; store.set("dsp.cur", id); render(); } },
|
||
h("span", { class: "dot " + d.status }), h("span", { class: "dn" }, d.name),
|
||
h("span", { class: "where" }, d.demo ? t("simulated") : STATUS_TEXT[d.status] || d.status), badge(d));
|
||
})) : null;
|
||
tabs.replaceChildren(...[pick, menu].filter(Boolean));
|
||
}
|
||
document.body.classList.toggle("testlock", testLock);
|
||
$("#btn-settings").classList.toggle("on", S.settings);
|
||
$("#btn-settings").disabled = testLock;
|
||
document.querySelectorAll("#viewtabs button").forEach(b => {
|
||
if (b.dataset.view === "fir") b.hidden = !(dev() && dev().fir);
|
||
b.classList.toggle("active", !S.settings && b.dataset.view === S.view);
|
||
b.disabled = testLock && b.dataset.view !== "test";
|
||
});
|
||
fitNav(); // the DSP button's width changes with the name
|
||
if (renderTabs.view !== S.view && window.innerWidth < 760) $("#viewtabs .active")?.scrollIntoView({ inline: "center", block: "nearest" }); // scrollable bottom bar
|
||
renderTabs.view = S.view;
|
||
}
|
||
// close the DSP menu on a click elsewhere or Escape
|
||
document.addEventListener("pointerdown", e => { if (S.devMenu && !e.target.closest("#devtabs")) { S.devMenu = false; renderTabs(); } });
|
||
document.addEventListener("keydown", e => { if (S.devMenu && e.key === "Escape") { S.devMenu = false; renderTabs(); } });
|
||
|
||
const STATUS_TEXT = { disconnected: t("Disconnected"), connecting: t("Connecting…"), loading: t("Loading configuration…"),
|
||
locked: t("Locked with a code"), online: "Online", error: t("Error") };
|
||
|
||
// ------------------------------------------------------------------ hardware lock of the DSP (not the app lock)
|
||
|
||
const LOCK_RE = /^[A-Z0-9]{4}$/;
|
||
const codeInput = () => {
|
||
const el = h("input", { type: "text", maxlength: 4, autocomplete: "off", autocapitalize: "characters", spellcheck: "false",
|
||
class: "code", placeholder: "A1B2", "aria-label": t("Lock code") });
|
||
el.addEventListener("input", () => { el.value = el.value.toUpperCase().replace(/[^A-Z0-9]/g, "").slice(0, 4); });
|
||
return el;
|
||
};
|
||
|
||
async function unlockDialog(d) {
|
||
let error = "";
|
||
for (;;) {
|
||
const code = codeInput();
|
||
const remember = h("input", { type: "checkbox", checked: !!d.auto_unlock || !d.lock_code });
|
||
const res = await modal({
|
||
title: t("DSP locked"),
|
||
body: h("div", {},
|
||
h("p", { class: "dlg-text" }, t("{name} is locked with a code. Enter the 4-character code (digits and letters A–Z).", { name: q(d.name) })),
|
||
code,
|
||
error ? h("div", { class: "err" }, error) : null,
|
||
h("label", { class: "chk" }, remember, t("Remember the code and unlock automatically"))),
|
||
actions: [{ label: t("Cancel") },
|
||
{ label: t("Unlock"), primary: true, value: () => LOCK_RE.test(code.value) ? { code: code.value, remember: remember.checked } : (code.focus(), undefined) }],
|
||
});
|
||
if (!res) return false;
|
||
try {
|
||
const r = await api("POST", `/api/devices/${d.id}/unlock`, res);
|
||
if (r.ok) { toast(t("DSP unlocked")); return true; }
|
||
error = t("Wrong code – please try again.");
|
||
} catch (e) { error = trMsg(e.message); }
|
||
}
|
||
}
|
||
|
||
// ask once per lock episode when the DSP on screen turns out to be locked
|
||
const lockAsked = new Set();
|
||
function maybeAskUnlock(d) {
|
||
if (d.status !== "locked") { lockAsked.delete(d.id); return; }
|
||
if (lockAsked.has(d.id) || d.id !== S.cur || S.settings || S.locked) return;
|
||
lockAsked.add(d.id);
|
||
setTimeout(() => unlockDialog(S.devices[d.id] || d), 50);
|
||
}
|
||
|
||
async function colorDialog(d, kind, members) {
|
||
// colours already taken by other channels / groups of this DSP (also the hidden ones of linked members,
|
||
// so no colour turns up twice when a group is dissolved again)
|
||
const taken = new Map();
|
||
for (const [key, c] of Object.entries(d.colors || {})) {
|
||
const k = key.startsWith("in") ? "in" : "out", j = +key.replace(/\D/g, "");
|
||
if (k === kind && members.includes(j)) continue;
|
||
const g = chanGroups(d, k).find(x => x.includes(j)) || [j];
|
||
taken.set(c.toLowerCase(), g.map(x => chLabel(k, x)).join(" + "));
|
||
}
|
||
let chosen = custColor(d, kind, members[0]) || "";
|
||
const sw = [];
|
||
const mark = () => sw.forEach(b => b.classList.toggle("on", b.dataset.c === chosen));
|
||
const swatches = CH_PALETTE.map(c => {
|
||
const by = taken.get(c);
|
||
const b = h("button", { class: "swatch big", type: "button", style: `background:${c}`, "data-c": c, disabled: !!by,
|
||
title: by ? t("Used by {ch}", { ch: by }) : c, onclick: () => { chosen = c; picker.value = c; mark(); } });
|
||
sw.push(b);
|
||
return b;
|
||
});
|
||
const picker = h("input", { type: "color", value: chosen || "#38bdf8", "aria-label": t("Custom colour") });
|
||
picker.addEventListener("input", () => {
|
||
const c = picker.value.toLowerCase();
|
||
if (taken.has(c)) { toast(t("Used by {ch}", { ch: taken.get(c) })); return; }
|
||
chosen = c; mark();
|
||
});
|
||
mark();
|
||
const label = members.map(j => chLabel(kind, j)).join(" + ");
|
||
const res = await modal({
|
||
title: t("Colour for {ch}", { ch: label }),
|
||
body: h("div", { class: "coldlg" }, h("div", { class: "swatches" }, swatches),
|
||
h("label", { class: "row custom" }, h("span", { class: "grow" }, t("Custom colour")), picker),
|
||
members.length > 1 ? h("p", { class: "info" }, t("Linked channels always share their colour.")) : null),
|
||
actions: [{ label: t("Cancel") }, { label: t("Default"), value: () => "" },
|
||
{ label: t("Apply"), primary: true, value: () => chosen || undefined }],
|
||
});
|
||
if (res === null) return;
|
||
const colors = { ...(d.colors || {}) };
|
||
for (const j of members) { if (res) colors[kind + j] = res; else delete colors[kind + j]; }
|
||
try { await api("POST", `/api/devices/${d.id}/colors`, { colors }); }
|
||
catch (e) { toast(t("Error: ") + trMsg(e.message)); }
|
||
}
|
||
|
||
const lockOpen = new Set(); // device ids whose lock section is open (survives re-rendering)
|
||
function lockSection(d) {
|
||
const online = d.status === "online";
|
||
const auto = h("input", { type: "checkbox", checked: !!d.auto_unlock, disabled: !d.lock_code,
|
||
onchange: () => api("PUT", `/api/devices/${d.id}`, { auto_unlock: auto.checked }).catch(e => toast(e.message)) });
|
||
const code = codeInput();
|
||
const setCode = async () => {
|
||
if (!LOCK_RE.test(code.value)) { code.focus(); return toast(t("The code has 4 characters: digits and letters A–Z")); }
|
||
if (!await askConfirm(t("Set lock code"), t("From the next connection on, {name} asks for the code {code} – also in the original software. Note it down: this app cannot remove the lock again.",
|
||
{ name: q(d.name), code: code.value }), t("Set code"), true)) return;
|
||
try { await api("POST", `/api/devices/${d.id}/lockcode`, { code: code.value }); toast(t("Lock code set")); }
|
||
catch (e) { toast(t("Error: ") + trMsg(e.message)); }
|
||
};
|
||
const box = h("details", { class: "more full lockbox", open: lockOpen.has(d.id),
|
||
ontoggle: () => box.open ? lockOpen.add(d.id) : lockOpen.delete(d.id) },
|
||
h("summary", {}, t("Device lock (code)"), d.lock_code ? h("span", { class: "tag" }, t("code remembered")) : null),
|
||
h("p", { class: "info" }, t("Hardware lock of the DSP: a locked DSP only accepts a connection after its code was entered. Independent of the lock of this app.")),
|
||
h("label", { class: "chk" }, auto, t("Unlock automatically with the remembered code")),
|
||
d.lock_code
|
||
? h("div", { class: "row" }, h("span", { class: "grow info" }, t("A code is remembered for this DSP.")),
|
||
h("button", { class: "small", onclick: () => api("PUT", `/api/devices/${d.id}`, { lock_code: "" }).then(() => toast(t("Code forgotten"))).catch(e => toast(e.message)) }, t("Forget code")))
|
||
: h("div", { class: "info" }, t("No code remembered – it is asked for when the DSP is locked.")),
|
||
h("div", { class: "sub" }, t("Set a new lock code")),
|
||
h("div", { class: "row" }, code, h("button", { class: "small", disabled: !online, onclick: setCode }, t("Set code"))),
|
||
online ? null : h("div", { class: "info" }, t("Connect the DSP to set a code.")));
|
||
return box;
|
||
}
|
||
|
||
// ------------------------------------------------------------------ demo mode
|
||
|
||
async function setDemo(body) {
|
||
try {
|
||
S.demo = await api("PUT", "/api/demo", body);
|
||
if (S.demo.enabled) S.cur = "demo"; // ready at the top; the settings stay open
|
||
render();
|
||
} catch (e) { toast(t("Error: ") + trMsg(e.message)); }
|
||
}
|
||
|
||
function demoCard() {
|
||
const on = S.demo.enabled;
|
||
return h("div", { class: "card" + (on ? " demo-on" : "") },
|
||
h("h3", {}, h("span", { class: "grow" }, t("Demo mode")), on ? h("span", { class: "demo-badge" }, "DEMO") : null),
|
||
h("p", { class: "info" }, t("Try everything with a simulated DSP – nothing is sent to real devices. While demo mode is on, the real DSPs are disconnected.")),
|
||
h("div", { class: "row" },
|
||
h("div", { class: "seg grow" }, [[false, t("Off")], [true, t("On")]].map(([v, label]) =>
|
||
h("button", { class: v === on ? "on" : "", "aria-pressed": String(v === on), onclick: () => v !== on && setDemo({ enabled: v }) }, label))),
|
||
h("div", { class: "seg" }, ["204", "408"].map(m =>
|
||
h("button", { class: m === S.demo.model ? "on" : "", onclick: () => m !== S.demo.model && setDemo({ model: m }) }, "DSP " + m)))));
|
||
}
|
||
|
||
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 && !viewOnly() ? [{ label: t("Undo import"), value: () => "undo" }] : []),
|
||
...(viewOnly() ? [] : [{ 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 || S.view === "dash") { 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 === "locked"
|
||
? h("div", { class: "presetrow" }, h("button", { class: "on", onclick: () => unlockDialog(d) }, t("Enter code")),
|
||
h("button", { onclick: () => api("POST", `/api/devices/${d.id}/disconnect`) }, t("Disconnect")))
|
||
: d.status === "disconnected" || d.status === "error"
|
||
? h("button", { class: "on", disabled: S.demo.enabled && !d.demo, onclick: () => api("POST", `/api/devices/${d.id}/connect`).catch(e => toast(trMsg(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 || "—"}`)));
|
||
const testing = testOn(d);
|
||
presetSel.disabled = testing;
|
||
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.demo ? t("Demo mode · simulated DSP") : `${d.info || d.name} · ${where(d)}`), h("b", {}, d.state.preset_name || "—")),
|
||
h("div", { class: "presetrow" }, presetSel, h("button", { disabled: testing, title: testing ? t("Not possible during the audio test") : "", onclick: () => storePresetDialog(d) }, t("Save")),
|
||
h("button", { disabled: testing, onclick: () => presetFileDialog(d), title: testing ? t("Not possible during the audio test") : 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" : "") + (custColor(d, kind, i) ? " tinted" : ""), style: `${ccStyle(d, kind, i)};grid-column:${i + 1}` });
|
||
const f = fader({ min: 0, max: 400, value: ch.gain, zero: 280, ticks: GAIN_TICKS, label: `${chLabel(kind, i)} Gain`,
|
||
cap: () => gainCap(dev(), kind, i), limit: maxGain(d, kind, i),
|
||
onInput: v => { showDb(v); setParam(kind, i, "gain", v); } });
|
||
onLive(kind, i, "gain", v => { f.setValue(v); showDb(v); });
|
||
db.addEventListener("click", async () => {
|
||
const r = await askValue(`${chTitle(d, kind, i)} – Gain`, SPEC.gain, chans(dev(), kind)[i].gain, gainCap(dev(), kind, i));
|
||
if (r == null) return;
|
||
const force = typeof r === "object", v = force ? r.value : Math.min(r, gainCap(dev(), kind, i) ?? r);
|
||
f.setValue(v); showDb(v); setParam(kind, i, "gain", v, force);
|
||
});
|
||
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), polBadge(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;
|
||
}
|
||
|
||
// bracket over a run of neighbouring strips of one link group (a group with gaps gets one per run)
|
||
function linkBands(d, kind) {
|
||
const bands = [];
|
||
linkedGroups(d, kind).forEach(g => {
|
||
const color = custColor(d, kind, g[0]) || linkInfo(d, kind, g[0]).color, name = linkName(d, kind, g);
|
||
const title = (name ? name + " · " : "") + g.map(j => chLabel(kind, j)).join(" + ");
|
||
g.forEach((j, n) => {
|
||
if (n && g[n - 1] === j - 1) return;
|
||
let len = 1;
|
||
while (g.includes(j + len)) len++;
|
||
bands.push(h("div", { class: "lkband" + (len === 1 ? " single" : ""), style: `--lc:${color};grid-column:${j + 1} / span ${len}`, title },
|
||
h("span", { class: "lkname" + (name ? "" : " anon") }, svgIcon(ICON.link), name ? h("b", {}, name) : null)));
|
||
});
|
||
});
|
||
return bands;
|
||
}
|
||
|
||
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", style: `--n:${chans(d, kind).length}` },
|
||
linkBands(d, kind), chans(d, kind).map((_, i) => strip(d, kind, i))));
|
||
const bands = linkedGroups(d, "in").length + linkedGroups(d, "out").length > 0;
|
||
return [h("div", { class: "mixer" + (bands ? " hasbands" : "") }, 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"))];
|
||
}
|
||
|
||
// ------------------------------------------------------------------ FIR filters (FIR DSP 408)
|
||
|
||
const FIR_TYPES = () => [t("Bypass"), t("Low-pass"), t("High-pass"), t("Band-pass"), t("From file")];
|
||
const FIR_WINDOWS = ["Rectangle", "Bartlett", "Hanning", "Hamming", "Blackman", "Sine", "Sinc", "Nuttall", "Kaiser", "Blackman-Nuttall", "Blackman-Harris"];
|
||
const firTapCount = i => 256 + 32 * i;
|
||
const firKey = (d, kind, i) => `${d.id}|${kind}${i}`;
|
||
const firMax = kind => (kind === "in" ? 2048 : 1024);
|
||
function firTapsOf(ch) { const f = ch.fir; return "type" in f ? (f.type ? firTapCount(f.taps) : 0) : (f.bypass ? 0 : f.taps); }
|
||
const firUsed = d => [...chans(d, "in"), ...chans(d, "out")].reduce((s, ch) => s + firTapsOf(ch), 0);
|
||
|
||
function firWindow(kind, n, N) {
|
||
const x = N > 1 ? n / (N - 1) : 0, c = k => Math.cos(2 * Math.PI * k * x);
|
||
const sum = a => a.reduce((s, v, k) => s + (k % 2 ? -v : v) * c(k), 0);
|
||
switch (kind) {
|
||
case 1: return 1 - Math.abs(2 * x - 1);
|
||
case 2: return 0.5 - 0.5 * c(1);
|
||
case 3: return 0.54 - 0.46 * c(1);
|
||
case 4: return sum([0.42, 0.5, 0.08]);
|
||
case 5: return Math.sin(Math.PI * x);
|
||
case 6: { const u = 2 * x - 1; return u ? Math.sin(Math.PI * u) / (Math.PI * u) : 1; }
|
||
case 7: return sum([0.355768, 0.487396, 0.144232, 0.012604]);
|
||
case 8: { const i0 = v => { let s = 1, e = 1; for (let k = 1; k < 30; k++) { e *= (v / (2 * k)) ** 2; s += e; } return s; };
|
||
const u = 2 * x - 1; return i0(8.6 * Math.sqrt(Math.max(0, 1 - u * u))) / i0(8.6); }
|
||
case 9: return sum([0.3635819, 0.4891775, 0.1365995, 0.0106411]);
|
||
case 10: return sum([0.35875, 0.48829, 0.14128, 0.01168]);
|
||
default: return 1;
|
||
}
|
||
}
|
||
// windowed sinc, only for the preview: the DSP calculates the filter itself from type, window, cut-offs and taps
|
||
function firDesign(f) {
|
||
const N = firTapCount(f.taps), M = (N - 1) / 2, lp = c => n => { const v = n - M, w = 2 * c / FS; return v ? Math.sin(Math.PI * w * v) / (Math.PI * v) : w; };
|
||
const lo = lp(f.low), hi = lp(f.high), out = new Float64Array(N);
|
||
for (let n = 0; n < N; n++) {
|
||
const ideal = f.type === 1 ? hi(n) : f.type === 2 ? (n === M ? 1 : 0) - lo(n) : hi(n) - lo(n);
|
||
out[n] = ideal * firWindow(f.window, n, N);
|
||
}
|
||
return out;
|
||
}
|
||
function firResponseDb(h, hz) {
|
||
const w = -2 * Math.PI * hz / FS; let re = 0, im = 0;
|
||
for (let n = 0; n < h.length; n++) { re += h[n] * Math.cos(w * n); im += h[n] * Math.sin(w * n); }
|
||
return 10 * Math.log10(re * re + im * im || 1e-12);
|
||
}
|
||
function drawFir(canvas, h) {
|
||
const dpr = window.devicePixelRatio || 1, W = canvas.clientWidth, H = canvas.clientHeight;
|
||
if (!W || !H) return;
|
||
canvas.width = W * dpr; canvas.height = H * dpr;
|
||
const c = canvas.getContext("2d"); c.scale(dpr, dpr);
|
||
const x = hz => W * Math.log(hz / 20) / Math.log(1000), y = db => H * (6 - db) / 86;
|
||
c.font = "10px sans-serif"; c.lineWidth = 1;
|
||
for (const hz of [20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]) {
|
||
c.strokeStyle = "#2a303a"; c.beginPath(); c.moveTo(x(hz), 0); c.lineTo(x(hz), H); c.stroke();
|
||
c.fillStyle = "#7b8594"; c.fillText(hz >= 1000 ? hz / 1000 + "k" : hz, Math.min(x(hz) + 3, W - 22), H - 4);
|
||
}
|
||
for (const db of [0, -20, -40, -60]) {
|
||
c.strokeStyle = db ? "#2a303a" : "#46505e"; c.beginPath(); c.moveTo(0, y(db)); c.lineTo(W, y(db)); c.stroke();
|
||
c.fillStyle = "#7b8594"; c.fillText(db + " dB", 3, y(db) - 3);
|
||
}
|
||
if (!h) return;
|
||
c.strokeStyle = "#38bdf8"; c.lineWidth = 2; c.beginPath();
|
||
for (let px = 0; px <= W; px += 2) {
|
||
const py = y(Math.max(-80, firResponseDb(h, 20 * 1000 ** (px / W))));
|
||
px ? c.lineTo(px, py) : c.moveTo(px, py);
|
||
}
|
||
c.stroke();
|
||
}
|
||
|
||
function parseFirFile(text) {
|
||
const parts = text.split(/[\s,;]+/).filter(Boolean);
|
||
const values = parts.map(Number);
|
||
if (!values.length || values.some(v => !Number.isFinite(v))) throw new Error(t("This is not a list of FIR coefficients"));
|
||
return values;
|
||
}
|
||
|
||
async function importFir(d, kind, i) {
|
||
let f;
|
||
try { f = await openFile(".txt,.csv,text/plain,text/csv"); } catch (e) { return toast(trMsg(e.message)); }
|
||
if (!f) return;
|
||
let coeffs;
|
||
try { coeffs = parseFirFile(atob(f.b64)); } catch (e) { return toast(e.message); }
|
||
if (coeffs.length > firMax(kind)) return toast(t("Too many coefficients: {n}, at most {max} here", { n: coeffs.length, max: firMax(kind) }));
|
||
const name = cleanName(f.name.replace(/\.[^.]*$/, "")).trim().slice(0, 8);
|
||
if (!await askConfirm(t("Load FIR filter"), t("Send {n} coefficients from {file} to {ch}? This changes the sound immediately – keep the amplifiers low.",
|
||
{ n: coeffs.length, file: f.name, ch: chTitle(d, kind, i) }), t("Send"))) return;
|
||
S.firBusy = true; render();
|
||
try {
|
||
await api("POST", `/api/devices/${d.id}/fir`, { kind, idx: i, coeffs, name });
|
||
S.firCoef[firKey(d, kind, i)] = Float64Array.from(coeffs);
|
||
toast(t("FIR filter loaded"));
|
||
} catch (e) { toast(t("Error: ") + trMsg(e.message)); }
|
||
S.firBusy = false; S.firDraft = null; render();
|
||
}
|
||
|
||
function viewFir(d) {
|
||
if (S.firSel.idx >= chans(d, S.firSel.kind).length) S.firSel = { kind: "out", idx: 0 };
|
||
const { kind, idx } = S.firSel, ch = chans(d, kind)[idx], key = firKey(d, kind, idx), isOut = kind === "out";
|
||
const used = firUsed(d), loaded = S.firCoef[key];
|
||
const canvas = h("canvas", { class: "fircurve" });
|
||
const pick = (k, i) => { S.firSel = { kind: k, idx: i }; S.firDraft = null; render(); };
|
||
const chip = (k, i) => h("button", { class: "firch" + (k === kind && i === idx ? " on" : "") + (firTapsOf(chans(d, k)[i]) ? " used" : ""), "data-view-ok": "", onclick: () => pick(k, i) },
|
||
h("b", {}, chLabel(k, i)), h("small", {}, firTapsOf(chans(d, k)[i]) ? `${firTapsOf(chans(d, k)[i])} ${t("taps")}` : t("off")));
|
||
const picker = h("div", { class: "card wide" }, h("h3", {}, h("span", { class: "grow" }, t("FIR filters")),
|
||
h("span", { class: "firuse" + (used > 4096 ? " over" : "") }, t("{used} of 4096 taps in use", { used }))),
|
||
h("div", { class: "firmeter" }, h("span", { style: `width:${Math.min(100, used / 40.96)}%` })),
|
||
h("div", { class: "firchs" }, chans(d, "in").map((_, i) => chip("in", i)), h("span", { class: "firsep" }), chans(d, "out").map((_, i) => chip("out", i))));
|
||
|
||
let settings, preview = null, note = "";
|
||
if (isOut) {
|
||
if (!S.firDraft || S.firDraft.key !== key) S.firDraft = { key, ...ch.fir };
|
||
const f = S.firDraft, external = f.type === 4, changed = ["type", "window", "low", "high", "taps"].some(k => f[k] !== ch.fir[k]);
|
||
const others = used - firTapsOf(ch), needed = f.type ? firTapCount(f.taps) : 0, over = others + needed > 4096;
|
||
const set = (k, v) => { f[k] = v; render(); };
|
||
const select = (label, k, items) => h("label", {}, label, h("select", { onchange: e => set(k, +e.target.value) },
|
||
items.map((o, i) => h("option", { value: i, selected: f[k] === i }, o))));
|
||
const hz = (label, k) => h("label", {}, label, h("input", { type: "number", min: 150, max: 20000, value: f[k],
|
||
onchange: e => set(k, clamp(Math.round(+e.target.value) || f[k], 150, 20000)) }));
|
||
settings = h("div", { class: "card" }, h("h3", {}, chTitle(d, kind, idx)),
|
||
h("div", { class: "form firform" },
|
||
select(t("Type"), "type", FIR_TYPES()),
|
||
f.type && !external ? select(t("Window"), "window", FIR_WINDOWS) : null,
|
||
f.type && !external ? select(t("Taps"), "taps", Array.from({ length: 25 }, (_, i) => String(firTapCount(i)))) : null,
|
||
f.type === 2 || f.type === 3 ? hz(t("Low cut (Hz)"), "low") : null,
|
||
f.type === 1 || f.type === 3 ? hz(t("High cut (Hz)"), "high") : null),
|
||
f.type === 3 && f.low >= f.high ? h("p", { class: "err" }, t("The low cut must be below the high cut.")) : null,
|
||
over ? h("p", { class: "err" }, t("Not enough taps left: {free} free, this needs {need}.", { free: 4096 - others, need: needed })) : null,
|
||
f.type && !external && needed > 512 ? h("p", { class: "info" }, t("More than 512 taps add noticeable delay (over 10 ms at 1024).")) : null,
|
||
external
|
||
? [h("p", { class: "info" }, ch.fir.type === 4 && ch.fir.name ? t("Loaded: {name}", { name: ch.fir.name }) : t("Choose a file with up to {max} coefficients (txt or csv).", { max: 1024 })),
|
||
h("div", { class: "row" }, h("button", { class: "on", disabled: S.firBusy, onclick: () => importFir(d, kind, idx) }, S.firBusy ? t("Sending…") : t("Load file…")))]
|
||
: h("div", { class: "row lkactions" }, h("button", { class: "on", disabled: !changed || over || (f.type === 3 && f.low >= f.high), onclick: () => {
|
||
setParam(kind, idx, "fir", { type: f.type, window: f.window, low: f.low, high: f.high, taps: f.taps, name: ch.fir.name }); toast(t("FIR filter set")); render();
|
||
} }, t("Apply")), changed ? h("button", { onclick: () => { S.firDraft = null; render(); } }, t("Cancel")) : null));
|
||
if (external) { preview = loaded; note = loaded ? "" : t("The DSP can't send coefficients back, so the curve only appears after loading a file here."); }
|
||
else if (f.type) { preview = firDesign(f); note = t("Calculated by this app – the DSP calculates the filter itself, so details can differ."); }
|
||
else note = t("Filter is off.");
|
||
} else {
|
||
settings = h("div", { class: "card" }, h("h3", {}, chTitle(d, kind, idx)),
|
||
h("p", { class: "info" }, ch.fir.taps ? t("Loaded: {name} ({n} taps)", { name: ch.fir.name || "–", n: ch.fir.taps }) : t("Inputs only take filters from a file: up to {max} coefficients (txt or csv).", { max: 2048 })),
|
||
h("div", { class: "row lkactions" },
|
||
h("button", { class: "on", disabled: S.firBusy, onclick: () => importFir(d, kind, idx) }, S.firBusy ? t("Sending…") : t("Load file…")),
|
||
ch.fir.taps ? toggleBtn("Bypass", kind, idx, "fir.bypass", "bypass", () => render()) : null),
|
||
ch.fir.taps > 512 ? h("p", { class: "info" }, t("More than 512 taps add noticeable delay (over 10 ms at 1024).")) : null);
|
||
preview = ch.fir.bypass ? null : loaded;
|
||
note = ch.fir.bypass ? t("Filter is off.") : loaded ? "" : t("The DSP can't send coefficients back, so the curve only appears after loading a file here.");
|
||
}
|
||
requestAnimationFrame(() => drawFir(canvas, preview));
|
||
return h("div", { class: "cards" }, picker, settings,
|
||
h("div", { class: "card" }, h("h3", {}, t("Frequency response")), canvas, note ? h("p", { class: "info" }, note) : null));
|
||
}
|
||
|
||
// ------------------------------------------------------------------ filter response (for the PEQ curve)
|
||
|
||
const FS = 96000;
|
||
// complex numbers as [re, im]
|
||
const cmul = (a, b) => [a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0]];
|
||
const cdiv = (a, b) => { const n = b[0] * b[0] + b[1] * b[1]; return [(a[0] * b[0] + a[1] * b[1]) / n, (a[1] * b[0] - a[0] * b[1]) / n]; };
|
||
const cdb = h => 10 * Math.log10(h[0] * h[0] + h[1] * h[1] || 1e-30);
|
||
const cdeg = h => Math.atan2(h[1], h[0]) * 180 / Math.PI;
|
||
|
||
// PEQ band as a digital biquad (RBJ cookbook), complex response at f
|
||
function biquadH(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;
|
||
case 7: { const k = Math.tan(w0 / 2), a = (k - 1) / (k + 1); b0 = a; b1 = 1; b2 = 0; a0 = 1; a1 = a; a2 = 0; break; } // allpass 1st order
|
||
case 8: b0 = 1 - alpha; b1 = -2 * cs; b2 = 1 + alpha; a0 = 1 + alpha; a1 = -2 * cs; a2 = 1 - alpha; break; // allpass 2nd order
|
||
default: return [1, 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);
|
||
return cdiv([b0 + b1 * c1 + b2 * c2, -(b1 * s1 + b2 * s2)], [a0 + a1 * c1 + a2 * c2, -(a1 * s1 + a2 * s2)]);
|
||
}
|
||
|
||
// crossover filters from their analog prototypes (Butterworth, Bessel, Linkwitz-Riley = Butterworth squared)
|
||
function butterworth(n, s) {
|
||
let hh = [1, 0];
|
||
for (let k = 1; k <= n; k++) {
|
||
const a = (2 * k - 1) * Math.PI / (2 * n), p = [-Math.sin(a), Math.cos(a)];
|
||
hh = cmul(hh, cdiv([-p[0], -p[1]], [s[0] - p[0], s[1] - p[1]]));
|
||
}
|
||
return hh;
|
||
}
|
||
const besselCache = {};
|
||
function bessel(n, s) {
|
||
let b = besselCache[n];
|
||
if (!b) { // reverse Bessel polynomial, frequency scaled to −3 dB at 1
|
||
const fact = k => k < 2 ? 1 : k * fact(k - 1);
|
||
const a = Array.from({ length: n + 1 }, (_, k) => fact(2 * n - k) / (2 ** (n - k) * fact(k) * fact(n - k)));
|
||
const at = (sc, x) => { let den = [0, 0], pw = [1, 0]; const z = cmul(x, [sc, 0]); for (const c of a) { den = [den[0] + c * pw[0], den[1] + c * pw[1]]; pw = cmul(pw, z); } return cdiv([a[0], 0], den); };
|
||
let lo = 0.1, hi = 10;
|
||
for (let i = 0; i < 60; i++) { const m = (lo + hi) / 2; cdb(at(m, [0, 1])) > -3.0103 ? (lo = m) : (hi = m); }
|
||
b = besselCache[n] = x => at((lo + hi) / 2, x);
|
||
}
|
||
return b(s);
|
||
}
|
||
function xoverH(filter, f, high) {
|
||
if (!filter || !filter.slope) return [1, 0];
|
||
const [kind, db] = SLOPES[filter.slope].split(" -"), n = +db / 6, x = f / freqHz(filter.freq);
|
||
const s = high ? [0, -1 / x] : [0, x]; // high pass: s -> 1/s
|
||
if (kind === "LK") { const b = butterworth(n / 2, s); return cmul(b, b); }
|
||
return kind === "BL" ? bessel(n, s) : butterworth(n, s);
|
||
}
|
||
const bandH = (b, f) => biquadH(b.type, freqHz(b.freq), eqDb(b.gain), Q_TABLE[b.q], f);
|
||
function channelH(ch, f) {
|
||
let hh = cmul(xoverH(ch.hp, f, true), xoverH(ch.lp, f, false));
|
||
if (!ch.peq_bypass) for (const b of ch.peq) if (!b.bypass) hh = cmul(hh, bandH(b, f));
|
||
return hh;
|
||
}
|
||
const hasGain = type => type <= 2;
|
||
const hasQ = type => [0, 4, 6, 7, 8].includes(type);
|
||
const OUT_COLORS = ["#f97316", "#facc15", "#4ade80", "#e879f9", "#60a5fa", "#fb7185", "#2dd4bf", "#c084fc"];
|
||
const chColor = (d, kind, i) => custColor(d, kind, i) || (kind === "in" ? IN_COLORS[i] : OUT_COLORS[i]);
|
||
|
||
// opts: { mode: "mag" | "phase", overlays: [{ ch, color }] }
|
||
function drawCurve(canvas, ch, selBand, opts = canvas.curveOpts ? canvas.curveOpts() : {}) {
|
||
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 phase = opts.mode === "phase";
|
||
const fx = f => Math.log(f / 20) / Math.log(1000) * W;
|
||
const dy = db => H / 2 - db / 15 * (H / 2 - 10);
|
||
const py = deg => H / 2 - deg / 180 * (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 v of phase ? [-180, -90, 0, 90, 180] : [-12, -6, 0, 6, 12]) {
|
||
const y = phase ? py(v) : dy(v);
|
||
g.strokeStyle = v === 0 ? "#3a4552" : "#1a2028";
|
||
g.beginPath(); g.moveTo(0, y); g.lineTo(W, y); g.stroke();
|
||
g.fillText((v > 0 ? "+" : "") + v + (phase ? "°" : ""), 3, y + (v === 180 ? 11 : -3));
|
||
}
|
||
const fAt = x => 20 * Math.pow(1000, x / W);
|
||
// a curve as polyline segments; the phase wraps at ±180°, so it is broken there instead of drawing a jump
|
||
const trace = hf => {
|
||
const segs = [[]];
|
||
let last = null;
|
||
for (let x = 0; x <= W; x += 2) {
|
||
const hh = hf(fAt(x));
|
||
if (phase) {
|
||
const deg = cdeg(hh);
|
||
if (last !== null && Math.abs(deg - last) > 180) { // wrapped: run to the edge, continue from the other one
|
||
const down = deg > last; // falling phase passes −180° and comes back at +180°
|
||
segs[segs.length - 1].push([x, py(down ? -180 : 180)]);
|
||
segs.push([[x, py(-180)], [x, py(180)]], [[x, py(down ? 180 : -180)]]); // the jump itself, then on
|
||
}
|
||
last = deg;
|
||
segs[segs.length - 1].push([x, py(deg)]);
|
||
} else segs[0].push([x, clamp(dy(cdb(hh)), 0, H)]);
|
||
}
|
||
return segs;
|
||
};
|
||
const stroke = (segs, color, width) => {
|
||
g.strokeStyle = color; g.lineWidth = width; g.lineJoin = "round";
|
||
for (const sg of segs) { g.beginPath(); sg.forEach(([x, y], i) => i ? g.lineTo(x, y) : g.moveTo(x, y)); g.stroke(); }
|
||
};
|
||
for (const o of opts.overlays || []) stroke(trace(f => channelH(o.ch, f)), o.color + "cc", 1.5);
|
||
const sb = ch.peq[selBand];
|
||
if (!phase && sb && !sb.bypass && !ch.peq_bypass) { // selected band's own contribution, filled
|
||
g.beginPath(); g.moveTo(0, dy(0));
|
||
for (let x = 0; x <= W; x += 3) g.lineTo(x, clamp(dy(cdb(bandH(sb, fAt(x)))), 0, H));
|
||
g.lineTo(W, dy(0)); g.closePath(); g.fillStyle = "#f59e0b22"; g.fill();
|
||
}
|
||
const segs = trace(f => channelH(ch, f));
|
||
if (!phase) {
|
||
g.beginPath(); g.moveTo(0, H); segs[0].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();
|
||
}
|
||
stroke(segs, "#38bdf8", 2);
|
||
const off = !!ch.peq_bypass;
|
||
ch.peq.forEach((b, i) => {
|
||
const x = fx(freqHz(b.freq)), y = hasGain(b.type) ? dy(eqDb(b.gain)) : dy(0);
|
||
g.beginPath(); g.arc(x, y, i === selBand ? 10 : 7, 0, 2 * Math.PI);
|
||
g.fillStyle = b.bypass || off ? "#2a333d" : i === selBand ? "#f59e0b" : "#38bdf8cc"; g.fill();
|
||
g.fillStyle = b.bypass || off ? "#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";
|
||
});
|
||
if (sb && !off) { // values of the selected band next to its point, as in the original software
|
||
const x = fx(freqHz(sb.freq)), y = hasGain(sb.type) ? dy(eqDb(sb.gain)) : dy(0);
|
||
const lines = [hasQ(sb.type) ? `Q ${Q_TABLE[sb.q]}` : PEQ_TYPES[sb.type], fmtHz(freqHz(sb.freq)), hasGain(sb.type) ? `${sign(eqDb(sb.gain))} dB` : ""].filter(Boolean);
|
||
g.font = "11px system-ui"; g.fillStyle = "#fbbf24";
|
||
const right = x > W - 90, tx = right ? x - 14 : x + 14;
|
||
g.textAlign = right ? "end" : "start";
|
||
lines.forEach((l, i) => g.fillText(l, tx, clamp(y + 18 + i * 13, 12, H - 30 + i * 13)));
|
||
g.textAlign = "start";
|
||
}
|
||
if (off) { // master bypass: written across the curve
|
||
g.font = "bold 34px system-ui"; g.textAlign = "center"; g.textBaseline = "middle"; g.fillStyle = "#ef444499";
|
||
g.fillText("BYPASS", W / 2, H / 3); g.textAlign = "start"; g.textBaseline = "alphabetic";
|
||
}
|
||
return { fx, dy, W, H, phase };
|
||
}
|
||
|
||
// other channels drawn into the curve (per device, remembered in the browser)
|
||
const overlayKey = d => "dsp.overlay." + d.id;
|
||
const overlaySet = d => new Set((store.get(overlayKey(d)) || "").split(",").filter(Boolean));
|
||
function overlayChips(d, kind, idx, onChange) {
|
||
const sel = overlaySet(d);
|
||
const all = [...chans(d, "in").map((_, i) => ["in", i]), ...chans(d, "out").map((_, i) => ["out", i])]
|
||
.filter(([k, i]) => !(k === kind && i === idx));
|
||
return h("div", { class: "chips overlay" }, h("span", { class: "sub" }, t("Overlay")),
|
||
all.map(([k, i]) => {
|
||
const key = `${k}${i}`, on = sel.has(key);
|
||
const btn = h("button", { class: "chip ov" + (on ? " on" : ""), style: `--oc:${chColor(d, k, i)}`, "aria-pressed": String(on),
|
||
title: chTitle(d, k, i), "data-view-ok": "",
|
||
onclick: () => { // always from the stored set: the chip may be older than the last change
|
||
const cur = overlaySet(d), now = !cur.has(key);
|
||
now ? cur.add(key) : cur.delete(key);
|
||
store.set(overlayKey(d), [...cur].join(","));
|
||
btn.classList.toggle("on", now); btn.setAttribute("aria-pressed", String(now));
|
||
onChange();
|
||
} }, h("i", {}), chLabel(k, i));
|
||
return btn;
|
||
}));
|
||
}
|
||
function overlaysFor(d, kind, idx) {
|
||
return [...overlaySet(d)].map(key => {
|
||
const k = key.startsWith("in") ? "in" : "out", i = +key.replace(/\D/g, "");
|
||
const list = chans(d, k);
|
||
return i < list.length && !(k === kind && i === idx) ? { ch: list[i], color: chColor(d, k, i) } : null;
|
||
}).filter(Boolean);
|
||
}
|
||
|
||
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") });
|
||
canvas.curveOpts = () => ({ mode: store.get("dsp.curve") === "phase" ? "phase" : "mag", overlays: overlaysFor(dev(), kind, idx) });
|
||
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 renderBtns = () => {
|
||
const c = chans(dev(), kind)[idx];
|
||
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 renderBand = () => {
|
||
const c = chans(dev(), kind)[idx], b = c.peq[S.band], p = `peq.${S.band}`;
|
||
renderBtns();
|
||
const both = () => { renderBand(); redraw(); };
|
||
// sliders must not rebuild themselves while being dragged (the mouse would lose them): buttons + curve only
|
||
const light = () => { renderBtns(); 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", light),
|
||
hasGain(b.type) ? paramSlider("Gain", kind, idx, p + ".gain", "eqgain", light) : null,
|
||
hasQ(b.type) ? paramSlider("Q", kind, idx, p + ".q", "q", light) : 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);
|
||
const modeSeg = h("div", { class: "seg small" });
|
||
const setMode = m => {
|
||
store.set("dsp.curve", m);
|
||
modeSeg.replaceChildren(...[["mag", "Mag"], ["phase", t("Phase")]].map(([k, label]) =>
|
||
h("button", { class: (store.get("dsp.curve") || "mag") === k ? "on" : "", "data-view-ok": "", onclick: () => { setMode(k); redraw(); } }, label)));
|
||
};
|
||
setMode(store.get("dsp.curve") || "mag");
|
||
const card = h("div", { class: "card wide" + (ch.peq_bypass ? " eq-off" : "") },
|
||
h("h3", {}, h("span", { class: "grow" }, t("Parametric EQ")), modeSeg,
|
||
d.fir ? null : toggleBtn("EQ Bypass", kind, idx, "peq_bypass", "small bypass", v => { card.classList.toggle("eq-off", v); renderBand(); redraw(); }),
|
||
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, overlayChips(d, kind, idx, redraw),
|
||
h("p", { class: "info" }, t("Drag the points in the curve · gain snaps at 0 dB")), bandBtns, body);
|
||
return card;
|
||
}
|
||
|
||
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]));
|
||
});
|
||
const geqBox = h("div", { class: "geq" + (ch.geq_bypass ? " bypassed" : "") }, bands);
|
||
return h("div", { class: "card wide" },
|
||
h("h3", {}, h("span", { class: "grow" }, t("Graphic EQ · 31 bands")),
|
||
toggleBtn("GEQ Bypass", "in", idx, "geq_bypass", "small bypass", v => geqBox.classList.toggle("bypassed", v)),
|
||
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"))),
|
||
geqBox,
|
||
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: ccStyle(d, kind, 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", {}, h("span", { class: "grow" }, t("Channel")),
|
||
h("button", { class: "small", onclick: () => copyDialog(d, k, i) }, t("Copy to…"))),
|
||
li ? h("p", { class: "info linknote", style: `--lc:${li.color}` }, svgIcon(ICON.link),
|
||
" " + 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 = ch.hp ? h("div", { class: "card" }, h("h3", {}, t("High- / low-pass")),
|
||
xo(t("High-pass"), "hp"), xo(t("Low-pass"), "lp")) : null;
|
||
|
||
const cards = [basics, xover].filter(Boolean);
|
||
const dynCard = (title, key, thresh) => h("div", { class: "card" }, h("h3", {}, title),
|
||
paramSlider("Threshold", k, i, key + ".threshold", thresh),
|
||
paramSlider("Ratio", k, i, key + ".ratio", "ratio"),
|
||
paramSlider("Attack", k, i, key + ".attack", "attack"),
|
||
paramSlider("Release", k, i, key + ".release", "release"),
|
||
paramSlider("Knee", k, i, key + ".knee", "knee"));
|
||
if (d.fir && 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(dynCard(t("Compressor"), "comp", "thresh"), peqCard(d, k, i));
|
||
} else 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));
|
||
if (ch.comp) 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:${inColor(d, 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:${inColor(d, 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:${inColor(d, 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();
|
||
let ok = false;
|
||
try { await api("POST", `/api/devices/${d.id}/link`, { kind, groups }); toast(msg); ok = true; }
|
||
catch (e) { toast(t("Error: ") + e.message); }
|
||
S.linkBusy = false; S.linkSel[kind] = []; S.linkEdit[kind] = null; render();
|
||
return ok;
|
||
}
|
||
|
||
function linkNameInput(d, kind, g) {
|
||
const input = h("input", { type: "text", class: "lkname-in", maxlength: 16, value: linkName(d, kind, g),
|
||
placeholder: t("Group name"), "aria-label": t("Group name"), autocomplete: "off", spellcheck: "false", enterkeyhint: "done" });
|
||
const save = async () => {
|
||
const v = input.value.trim();
|
||
if (v === linkName(dev(), kind, g)) return;
|
||
const next = { ...(dev().linknames || {}) };
|
||
if (v) next[linkKey(kind, g)] = v; else delete next[linkKey(kind, g)];
|
||
try { await api("POST", `/api/devices/${d.id}/linknames`, { linknames: next }); toast(v ? t("Group name saved") : t("Group name removed")); }
|
||
catch (e) { toast(t("Error: ") + trMsg(e.message)); }
|
||
};
|
||
input.addEventListener("change", save);
|
||
input.addEventListener("keydown", e => { if (e.key === "Enter") input.blur(); });
|
||
return input;
|
||
}
|
||
|
||
function linkCard(d, kind) {
|
||
const list = chans(d, kind), linked = linkedGroups(d, kind);
|
||
// editing an existing group: its members start selected, channels of other groups stay locked
|
||
let edit = S.linkEdit[kind];
|
||
if (edit && !linked.some(g => linkKey(kind, g) === linkKey(kind, edit))) edit = S.linkEdit[kind] = null; // changed meanwhile
|
||
const free = i => !linkInfo(d, kind, i) || (edit && edit.includes(i));
|
||
const sel = S.linkSel[kind] = S.linkSel[kind].filter(i => i < list.length && free(i));
|
||
const btns = list.map((ch, i) => {
|
||
const l = linkInfo(d, kind, i), on = sel.includes(i), locked = !free(i);
|
||
return h("button", { class: "lkch" + (on ? " sel" : "") + (locked ? " taken" : ""), style: l ? `--lc:${custColor(d, kind, i) || l.color}` : "", "aria-pressed": String(on),
|
||
title: locked ? t("Already linked – unlink the group first") : "", disabled: S.linkBusy || locked, 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 label = g => g.map(i => chLabel(kind, i)).join(" + ");
|
||
const unlink = async g => {
|
||
const names = label(g);
|
||
if (!await askConfirm(t("Unlink group"), t("Unlink {names}? Every channel keeps its current settings.", { names }), t("Unlink"), true)) return;
|
||
if (await saveLinks(d, kind, linked.filter(x => linkKey(kind, x) !== linkKey(kind, g)), t("{names} unlinked", { names }))) moveLinkName(d, kind, g, null);
|
||
};
|
||
const startEdit = g => { S.linkEdit[kind] = g.slice(); S.linkSel[kind] = g.slice(); render(); };
|
||
const cancelEdit = () => { S.linkEdit[kind] = null; S.linkSel[kind] = []; render(); };
|
||
const saveEdit = async () => {
|
||
const next = sel.slice(), added = next.filter(i => !edit.includes(i)), removed = edit.filter(i => !next.includes(i));
|
||
if (!added.length && !removed.length) return cancelEdit();
|
||
const others = linked.filter(g => linkKey(kind, g) !== linkKey(kind, edit));
|
||
if (next.length < 2) return unlink(edit); // one channel alone is no group
|
||
const lines = [
|
||
added.length ? t(added.length > 1 ? "{names} join the group and take over its settings (names{routing} stay)."
|
||
: "{names} joins the group and takes over its settings (name{routing} stays).", { names: label(added), routing: kind === "out" ? t(" and routing") : "" }) : null,
|
||
removed.length ? t(removed.length > 1 ? "{names} leave the group and keep their current settings."
|
||
: "{names} leaves the group and keeps its current settings.", { names: label(removed) }) : null];
|
||
if (!await askConfirm(t("Change group"), lines.filter(Boolean).join(" "), t("Save"))) return;
|
||
// the DSP copies the first channel's settings to the others – a new first channel gets the group's settings beforehand
|
||
if (next[0] !== edit[0] && !edit.includes(next[0])) {
|
||
try {
|
||
await api("POST", "/api/copy", { device: d.id, kind, idx: edit[0], groups: ["level", "filters", "eq", "dynamics"],
|
||
targets: [{ device: d.id, idx: next[0] }] });
|
||
} catch (e) { toast(t("Error: ") + trMsg(e.message)); return; }
|
||
}
|
||
if (await saveLinks(d, kind, [...others, next], t("Group changed: {names}", { names: label(next) }))) moveLinkName(d, kind, edit, next);
|
||
};
|
||
const editing = !!edit;
|
||
return h("div", { class: "card" + (editing ? " lkediting" : "") }, h("h3", {}, kind === "in" ? t("Inputs") : t("Outputs")),
|
||
h("div", { class: "lkgrid" }, btns),
|
||
editing
|
||
? h("div", { class: "row lkactions" },
|
||
h("span", { class: "grow info" }, sel.length < 2 ? t("Fewer than two channels – the group will be dissolved")
|
||
: t("Edit {names}: tap channels to add or remove them", { names: label(edit) })),
|
||
h("button", { disabled: S.linkBusy, onclick: cancelEdit }, t("Cancel")),
|
||
h("button", { class: sel.length < 2 ? "danger-on" : "on", disabled: S.linkBusy, onclick: saveEdit }, sel.length < 2 ? t("Dissolve group") : t("Save")))
|
||
: 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) => {
|
||
const mine = editing && linkKey(kind, g) === linkKey(kind, edit);
|
||
return h("div", { class: "lkgroup" + (mine ? " editing" : editing ? " dim" : ""), style: `--lc:${custColor(d, kind, g[0]) || LINK_COLORS[n % LINK_COLORS.length]}` },
|
||
h("div", { class: "row" }, svgIcon(ICON.link), h("span", { class: "grow lkmembers" }, label(g)),
|
||
h("button", { class: "small", disabled: S.linkBusy || editing, onclick: () => startEdit(g) }, t("Edit")),
|
||
h("button", { class: "small", disabled: S.linkBusy || editing, onclick: () => unlink(g) }, t("Unlink"))),
|
||
linkNameInput(d, kind, g));
|
||
}))
|
||
: h("p", { class: "info" }, t("No channels linked.")));
|
||
}
|
||
|
||
// a group's name follows it when its members change (to = null: the group is gone)
|
||
async function moveLinkName(d, kind, from, to) {
|
||
const names = { ...(dev().linknames || {}) }, name = names[linkKey(kind, from)];
|
||
if (!name) return;
|
||
delete names[linkKey(kind, from)];
|
||
if (to) names[linkKey(kind, to)] = name;
|
||
try { await api("POST", `/api/devices/${d.id}/linknames`, { linknames: names }); }
|
||
catch (e) { toast(t("Error: ") + trMsg(e.message)); }
|
||
}
|
||
|
||
// channel colours of the current DSP: one row per channel or link group
|
||
function colorCard(d) {
|
||
const row = (kind, g) => {
|
||
const c = custColor(d, kind, g[0]), label = g.map(j => chLabel(kind, j)).join(" + "), name = chans(d, kind)[g[0]].name;
|
||
return h("button", { class: "colrow", type: "button", onclick: () => colorDialog(d, kind, g) },
|
||
h("span", { class: "swatch" + (c ? "" : " none"), style: c ? `background:${c}` : "" }),
|
||
h("span", { class: "grow" }, label, name ? h("small", {}, name) : null),
|
||
g.length > 1 ? h("span", { class: "lnk" }, svgIcon(ICON.link)) : null);
|
||
};
|
||
return h("div", { class: "card wide colorbox" }, h("h3", {}, t("Channel colours")),
|
||
h("p", { class: "info" }, t("Shown on the mixer strips and in the channel view. Linked channels share one colour; every colour can only be used once per DSP.")),
|
||
h("div", { class: "colgrid" },
|
||
h("div", {}, h("div", { class: "sub" }, t("Inputs")), chanGroups(d, "in").map(g => row("in", g))),
|
||
h("div", {}, h("div", { class: "sub" }, t("Outputs")), chanGroups(d, "out").map(g => row("out", g)))));
|
||
}
|
||
|
||
// software max level per channel / link group
|
||
function maxLevelCard(d) {
|
||
const save = async next => {
|
||
try { await api("POST", `/api/devices/${d.id}/maxgain`, { maxgain: next }); }
|
||
catch (e) { toast(t("Error: ") + trMsg(e.message)); }
|
||
};
|
||
const row = (kind, g) => {
|
||
const lim = maxGain(d, kind, g[0]) ?? 400, label = g.map(j => chLabel(kind, j)).join(" + ");
|
||
const val = h("span", { class: "mlval" + (lim < 400 ? " on" : "") }, lim < 400 ? `${sign(gainDb(lim))} dB` : t("no limit"));
|
||
const input = h("input", { type: "range", min: 0, max: 400, step: 1, value: lim, "aria-label": `${label} – ${t("Max level")}` });
|
||
let timer = null;
|
||
input.addEventListener("input", () => {
|
||
const v = +input.value;
|
||
val.textContent = v < 400 ? `${sign(gainDb(v))} dB` : t("no limit"); val.classList.toggle("on", v < 400);
|
||
clearTimeout(timer);
|
||
timer = setTimeout(() => {
|
||
const next = { ...(d.maxgain || {}) };
|
||
for (const j of g) { if (v < 400) next[kind + j] = v; else delete next[kind + j]; }
|
||
save(next);
|
||
}, 300);
|
||
});
|
||
const over = chans(d, kind)[g[0]].gain > lim;
|
||
return h("div", { class: "mlrow" }, h("span", { class: "mllabel" }, label, g.length > 1 ? h("span", { class: "lnk" }, svgIcon(ICON.link)) : null),
|
||
input, val, over ? h("small", { class: "mlwarn" }, t("now above – set on the DSP")) : null);
|
||
};
|
||
return h("div", { class: "card wide" }, h("h3", {}, t("Max level")),
|
||
h("p", { class: "info" }, t("Software lock for the gain faders: the app does not let them go higher. If the DSP itself is turned up further, the app shows it and the fader can only be pulled down until it snaps into the limit again.")),
|
||
h("div", { class: "colgrid" },
|
||
h("div", {}, h("div", { class: "sub" }, t("Inputs")), chanGroups(d, "in").map(g => row("in", g))),
|
||
h("div", {}, h("div", { class: "sub" }, t("Outputs")), chanGroups(d, "out").map(g => row("out", g)))));
|
||
}
|
||
|
||
function viewLink(d) {
|
||
return [h("h2", { class: "section" }, t("Links")),
|
||
h("div", { class: "cards" }, linkCard(d, "in"), linkCard(d, "out")),
|
||
h("p", { class: "info" }, 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.")),
|
||
h("h2", { class: "section" }, t("Colours")),
|
||
h("div", { class: "cards" }, colorCard(d)),
|
||
h("h2", { class: "section" }, t("Max level")),
|
||
h("div", { class: "cards" }, maxLevelCard(d))];
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 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),
|
||
as ? h("label", {}, t("Load on channel"), ohmSel) : null,
|
||
as ? h("label", {}, t("Speaker RMS (W)"), spkIn) : null),
|
||
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", {}, `${"ratio" in lim ? `Ratio ${RATIOS[lim.ratio]} · ` : ""}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)),
|
||
"ratio" in lim ? paramSlider("Ratio", "out", o, "limit.ratio", "ratio") : null,
|
||
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)),
|
||
];
|
||
}
|
||
|
||
// ------------------------------------------------------------------ copy channel settings
|
||
|
||
const COPY_GROUPS = kind => [["level", t("Gain, delay, polarity")], ["filters", t("High / low pass")],
|
||
["eq", kind === "in" ? t("PEQ + GEQ") : "PEQ"], ["dynamics", kind === "in" ? "Noise gate" : t("Compressor + limiter")],
|
||
...(kind === "out" ? [["routing", t("Routing + mix levels")]] : [])];
|
||
|
||
async function copyDialog(d, kind, idx) {
|
||
const groups = new Set(store.get("dsp.copygroups." + kind)?.split(",").filter(Boolean) || ["eq", "filters", "dynamics"]);
|
||
const targets = new Set();
|
||
const groupBoxes = COPY_GROUPS(kind).map(([g, label]) => {
|
||
const cb = h("input", { type: "checkbox", checked: groups.has(g), onchange: () => cb.checked ? groups.add(g) : groups.delete(g) });
|
||
return h("label", { class: "chk" }, cb, label);
|
||
});
|
||
const devs = S.order.map(id => S.devices[id]).filter(x => x.status === "online" && x.state);
|
||
const targetRows = devs.map(x => {
|
||
const chips = chans(x, kind).map((_, j) => {
|
||
if (x.id === d.id && j === idx) return null;
|
||
const key = `${x.id}|${j}`;
|
||
const b = h("button", { class: "chip", "aria-pressed": "false",
|
||
onclick: () => { const on = !targets.has(key); on ? targets.add(key) : targets.delete(key); b.classList.toggle("on", on); b.setAttribute("aria-pressed", String(on)); } },
|
||
chLabel(kind, j) + (chans(x, kind)[j].name ? " · " + chans(x, kind)[j].name : ""));
|
||
return b;
|
||
}).filter(Boolean);
|
||
return h("div", { class: "copydev" }, devs.length > 1 ? h("div", { class: "sub" }, x.name) : null, h("div", { class: "chips" }, chips));
|
||
});
|
||
const res = await modal({
|
||
title: t("Copy {ch} to…", { ch: chTitle(d, kind, idx) }),
|
||
body: h("div", { class: "copydlg" }, h("div", { class: "sub" }, t("What")), h("div", { class: "copygroups" }, groupBoxes),
|
||
h("div", { class: "sub" }, t("To")), targetRows,
|
||
h("p", { class: "info" }, t("The name stays. Linked target channels take the values for their whole group."))),
|
||
actions: [{ label: t("Cancel") }, { label: t("Copy"), primary: true, value: () => (groups.size && targets.size ? true : undefined) }],
|
||
});
|
||
if (!res) return;
|
||
store.set("dsp.copygroups." + kind, [...groups].join(","));
|
||
try {
|
||
const r = await api("POST", "/api/copy", { device: d.id, kind, idx, groups: [...groups],
|
||
targets: [...targets].map(k => { const [device, j] = k.split("|"); return { device, idx: +j }; }) });
|
||
toast(r.changed ? t("{n} values copied", { n: r.changed }) : t("Nothing to change – the settings are already the same"));
|
||
} catch (e) { toast(t("Error: ") + trMsg(e.message)); }
|
||
}
|
||
|
||
// ------------------------------------------------------------------ global mute (all channels of all connected DSPs)
|
||
|
||
function showMuteAll() {
|
||
const b = $("#btn-muteall");
|
||
b.classList.toggle("on", !!S.muteAll);
|
||
b.title = S.muteAll ? t("All muted – click to unmute what was open before") : t("Mute all channels of all connected DSPs");
|
||
b.setAttribute("aria-label", b.title);
|
||
b.replaceChildren(svgIcon(ICON.muteall));
|
||
}
|
||
$("#btn-muteall").addEventListener("click", async () => {
|
||
try {
|
||
const r = await api("POST", "/api/muteall", { mute: !S.muteAll });
|
||
S.muteAll = r.active; showMuteAll();
|
||
toast(r.active ? t("All channels muted") : t("Unmuted – channels that were muted before stay muted"));
|
||
} catch (e) { toast(t("Error: ") + trMsg(e.message)); }
|
||
});
|
||
|
||
// ------------------------------------------------------------------ audio test (test generator of the DSP)
|
||
|
||
const testOn = d => !!(d && d.state && d.state.test && d.state.test.source);
|
||
const TEST_SRC = () => [[0, t("Analog input"), t("normal operation")], [1, t("Pink noise"), ""], [2, t("White noise"), ""], [3, t("Sine"), ""]];
|
||
const LVL_MIN = -60, LVL_MAX = 0; // test fader range in dB (all outputs at the same level)
|
||
|
||
async function setTestSignal(d, source, freq) {
|
||
try { await api("POST", `/api/devices/${d.id}/test`, { source, freq: freq ?? d.state.test.freq }); }
|
||
catch (e) { toast(t("Error: ") + trMsg(e.message)); }
|
||
}
|
||
|
||
// one request in flight at a time, always ending with the latest fader position
|
||
function sendTestLevel(d, db) {
|
||
sendTestLevel.next = db;
|
||
if (sendTestLevel.busy) return;
|
||
sendTestLevel.busy = true;
|
||
(async () => {
|
||
while (sendTestLevel.next != null) {
|
||
const v = sendTestLevel.next;
|
||
sendTestLevel.next = null;
|
||
try { await api("POST", `/api/devices/${d.id}/testlevel`, { db: v }); } catch (e) { toast(trMsg(e.message)); }
|
||
}
|
||
sendTestLevel.busy = false;
|
||
})();
|
||
}
|
||
|
||
function viewTest(d) {
|
||
const on = testOn(d), test = d.state.test;
|
||
const freqSel = h("select", { "aria-label": t("Sine frequency"), onchange: () => setTestSignal(d, 3, +freqSel.value) },
|
||
GEQ_FREQS.map((f, i) => h("option", { value: i, selected: i === test.freq }, f.endsWith("k") ? `${f.slice(0, -1)} kHz` : `${f} Hz`)));
|
||
const signalCard = h("div", { class: "card" },
|
||
h("h3", {}, t("Input signal")),
|
||
h("div", { class: "srcgrid" }, TEST_SRC().map(([v, label, sub]) =>
|
||
h("button", { class: "src" + (test.source === v ? " on" : "") + (v ? " noise" : ""), "aria-pressed": String(test.source === v),
|
||
onclick: () => test.source !== v && setTestSignal(d, v, v === 3 ? +freqSel.value : test.freq) },
|
||
h("b", {}, label), sub ? h("small", {}, sub) : null))),
|
||
h("label", { class: "row sinefreq" + (test.source === 3 ? "" : " dim") }, h("span", { class: "grow" }, t("Sine frequency")), freqSel),
|
||
h("p", { class: "info" }, t("The test signal replaces the analog inputs of the DSP. When it is switched on, all outputs are lowered to −50 dB first – raise them slowly with the test fader.")));
|
||
|
||
const lvl = d.test_level ?? -50;
|
||
const val = h("div", { class: "testval" }, on ? `${lvl.toFixed(1)} dB` : "—");
|
||
const f = fader({ min: 0, max: (LVL_MAX - LVL_MIN) * 2, value: Math.round((lvl - LVL_MIN) * 2), label: t("Test fader"),
|
||
ticks: [-60, -50, -40, -30, -20, -10, 0].map(db => [(db - LVL_MIN) * 2, String(db)]),
|
||
onInput: v => { const db = LVL_MIN + v / 2; d.test_level = db; val.textContent = `${db.toFixed(1)} dB`; sendTestLevel(d, db); } });
|
||
const outs = chans(d, "out").map((ch, i) => {
|
||
const m = h("div", { class: "tmeter" + (ch.mute ? " muted" : "") }, ledMeter(d.id, "out", i), h("small", {}, chLabel("out", i)), limLed(d.id, i));
|
||
m.append(toggleBtn("MUTE", "out", i, "mute", "mute small", v => m.classList.toggle("muted", v)));
|
||
return m;
|
||
});
|
||
const faderCard = h("div", { class: "card testfader" + (on ? "" : " off") },
|
||
h("h3", {}, t("Test fader"), h("span", { class: "info" }, t("all outputs"))),
|
||
h("div", { class: "testbody" }, h("div", { class: "tf" }, f, val), h("div", { class: "tmeters" }, outs)),
|
||
on ? h("button", { class: "danger-on wide", onclick: () => setTestSignal(d, 0) }, t("Stop test – back to the analog input")) : null,
|
||
h("p", { class: "info" }, on
|
||
? t("Saving and recalling presets is blocked during the test. Stopping it switches the noise off first and then puts every fader back where it was.")
|
||
: t("Choose a test signal above to start.")));
|
||
return [
|
||
on ? h("div", { class: "testbanner" }, t("Audio test running – the DSP plays {signal} instead of its inputs.", { signal: TEST_SRC()[test.source][1] }),
|
||
h("small", {}, t("The rest of the app is locked until the analog input is selected again."))) : null,
|
||
h("div", { class: "cards testcards" }, signalCard, faderCard),
|
||
];
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 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"],
|
||
["206", "DSP 206 (Beta)"], ["408fir", "FIR DSP 408 (Beta)"]]
|
||
.map(([v, label]) => h("option", { value: v, selected: d.model === v }, label))),
|
||
autoconnect: h("input", { type: "checkbox", checked: d.autoconnect }),
|
||
addr: h("input", { type: "number", min: 1, max: 250, value: d.addr || 1, class: "short" }),
|
||
usb: h("select", { "aria-label": t("USB device") }),
|
||
};
|
||
const betaNote = h("p", { class: "info betanote full", hidden: true },
|
||
t("Beta: this model has not been tested on a real device yet. Keep the amplifiers off for the first test."));
|
||
const showBeta = () => { betaNote.hidden = !isNew || !f.model.value || !BETA_MODELS.includes(f.model.value); };
|
||
f.model.addEventListener("change", showBeta);
|
||
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, addr: clamp(Math.round(+f.addr.value || 1), 1, 250) });
|
||
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; S.addDev = false; toast(t("Added")); }
|
||
catch (e) { toast(e.message); }
|
||
} }, t("Add")), h("button", { onclick: () => { S.addDev = false; render(); } }, t("Cancel"))]
|
||
: [
|
||
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", disabled: S.demo.enabled, 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")),
|
||
];
|
||
const paused = S.demo.enabled && !isNew;
|
||
return h("div", { class: "card" + (paused ? " paused" : "") },
|
||
paused ? h("div", { class: "info" }, t("Disconnected while demo mode is on")) : null,
|
||
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")),
|
||
betaNote,
|
||
h("details", { class: "more full" }, h("summary", {}, t("Advanced")),
|
||
h("label", { class: "inline idrow" }, t("Device ID"), f.addr),
|
||
h("p", { class: "info" }, t("Only needed if the ID was changed on the DSP (e.g. several DSPs on one RS-485 cable). Default 1."))),
|
||
isNew ? null : lockSection(d)),
|
||
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.")));
|
||
}
|
||
|
||
// ------------------------------------------------------------------ custom logo (top left and browser icon)
|
||
|
||
const LOGO_PX = 128, LOGO_MIN = 64;
|
||
const DEFAULT_LOGO = $(".brand").innerHTML;
|
||
function showLogo() {
|
||
const b = $(".brand");
|
||
b.replaceChildren();
|
||
if (S.logo) b.append(h("img", { src: S.logo, alt: "", width: 26, height: 26 }));
|
||
else b.innerHTML = DEFAULT_LOGO;
|
||
let icon = document.querySelector("link[rel=icon]");
|
||
if (!icon) { icon = h("link", { rel: "icon" }); document.head.append(icon); }
|
||
if (S.logo) icon.href = S.logo; else icon.removeAttribute("href");
|
||
}
|
||
|
||
// any picture -> 128×128 PNG, centred without distortion (transparent where it isn't square)
|
||
async function logoFromFile() {
|
||
const f = await openFile(".png,.jpg,.jpeg,.webp,.svg,.gif,image/*");
|
||
if (!f) return null;
|
||
const ext = (f.name.split(".").pop() || "").toLowerCase();
|
||
const mime = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp", gif: "image/gif", svg: "image/svg+xml" }[ext];
|
||
if (!mime) throw new Error(t("Please choose a PNG, JPG, WebP or SVG image"));
|
||
const img = new Image();
|
||
await new Promise((ok, bad) => { img.onload = ok; img.onerror = () => bad(new Error(t("The logo could not be read"))); img.src = `data:${mime};base64,${f.b64}`; });
|
||
const w = img.naturalWidth || LOGO_PX, hh = img.naturalHeight || LOGO_PX; // SVGs without a size count as fine
|
||
if (mime !== "image/svg+xml" && (w < LOGO_MIN || hh < LOGO_MIN)) throw new Error(t("The image is too small – at least {n}×{n} pixels", { n: LOGO_MIN }));
|
||
const cv = h("canvas", { width: LOGO_PX, height: LOGO_PX }), g = cv.getContext("2d"), sc = Math.min(LOGO_PX / w, LOGO_PX / hh);
|
||
g.imageSmoothingQuality = "high";
|
||
g.drawImage(img, (LOGO_PX - w * sc) / 2, (LOGO_PX - hh * sc) / 2, w * sc, hh * sc);
|
||
return { url: cv.toDataURL("image/png"), square: Math.abs(w - hh) <= Math.max(w, hh) * 0.02 };
|
||
}
|
||
|
||
function logoCard() {
|
||
const preview = h("div", { class: "logoprev" });
|
||
if (S.logo) preview.append(h("img", { src: S.logo, alt: "" })); else preview.innerHTML = DEFAULT_LOGO;
|
||
const set = async logo => {
|
||
try { S.logo = (await api("PUT", "/api/logo", { logo })).logo; showLogo(); render(); }
|
||
catch (e) { toast(t("Error: ") + trMsg(e.message)); }
|
||
};
|
||
return h("div", { class: "card" }, h("h3", {}, t("Logo")),
|
||
h("div", { class: "row logorow" }, preview,
|
||
h("div", { class: "grow" },
|
||
h("p", { class: "info" }, t("Your own logo top left (and as the browser icon). PNG, JPG, WebP or SVG, ideally square, at least 64×64 pixels, transparent background recommended. It is scaled to 128×128 pixels; other shapes are centred without distortion.")))),
|
||
h("div", { class: "actions" },
|
||
h("button", { class: "on", onclick: async () => {
|
||
try {
|
||
const r = await logoFromFile();
|
||
if (!r) return;
|
||
await set(r.url);
|
||
toast(r.square ? t("Logo replaced") : t("Logo replaced – the image was not square and has been centred"));
|
||
} catch (e) { toast(trMsg(e.message)); }
|
||
} }, t("Choose image…")),
|
||
S.logo ? h("button", { onclick: () => set("") }, t("Default logo")) : null));
|
||
}
|
||
|
||
// 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(() => {});
|
||
// the texts are set when the page loads: reload, but come back to the settings where we were
|
||
try { sessionStorage.setItem("dsp.reopen", JSON.stringify({ settings: S.settings, y: window.scrollY })); } catch { /* private mode */ }
|
||
location.reload();
|
||
};
|
||
return h("div", { class: "card" }, h("h3", {}, "Language / Sprache"),
|
||
h("p", { class: "info" }, t("Language of the app on this device.")),
|
||
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))));
|
||
}
|
||
|
||
async function scanDialog() {
|
||
const box = h("div", { class: "scanres" }, h("div", { class: "empty small" }, h("div", { class: "spinner" }), t("Searching the network for DSPs…")));
|
||
const done = modal({ title: t("Search network"), body: box, actions: [{ label: t("Close"), primary: true, value: () => true }] });
|
||
try {
|
||
const list = await api("POST", "/api/scan");
|
||
const used = new Set(S.order.map(id => S.devices[id].host));
|
||
box.replaceChildren(...(list.length ? list.map(x => {
|
||
const title = MODEL_LABEL[x.model] || t("Unknown device");
|
||
const add = async b => {
|
||
b.disabled = true;
|
||
try {
|
||
await api("POST", "/api/devices", { name: `${title} (${x.host})`, host: x.host, port: x.port, model: x.model || "auto", autoconnect: true });
|
||
b.textContent = t("Added"); toast(t("Added"));
|
||
} catch (e) { toast(trMsg(e.message)); b.disabled = false; }
|
||
};
|
||
const btn = h("button", { class: "small on", disabled: !!x.known || used.has(x.host) });
|
||
btn.textContent = x.known || used.has(x.host) ? t("in the list") : t("Add");
|
||
btn.onclick = () => add(btn);
|
||
return h("div", { class: "scanrow" }, h("span", { class: "dot " + (x.busy ? "online" : x.model ? "connecting" : "disconnected") }),
|
||
h("div", { class: "grow" }, h("b", {}, title), h("small", {}, `${x.host}:${x.port}` + (x.info ? " · " + x.info : "") + (x.busy ? " · " + t("connected") : !x.info ? " · " + t("no answer (another program connected, or a different device ID)") : ""))),
|
||
btn);
|
||
}) : [h("p", { class: "info" }, t("No DSP found. Is it in the same network and switched on? Close the Thomann editor – a DSP accepts only one connection."))]));
|
||
} catch (e) { box.replaceChildren(h("p", { class: "err" }, trMsg(e.message))); }
|
||
await done;
|
||
}
|
||
|
||
function addDeviceCard() {
|
||
if (S.addDev) return deviceForm(null);
|
||
return h("button", { class: "card addcard devadd", onclick: () => { S.addDev = true; render(); } },
|
||
h("span", { class: "plus" }, "+"), h("b", {}, t("Add a DSP")),
|
||
h("small", {}, t("Over the network or with a USB cable")));
|
||
}
|
||
function scanCard() {
|
||
return h("button", { class: "card addcard devadd", onclick: scanDialog },
|
||
h("span", { class: "plus" }, svgIcon('<circle cx="11" cy="11" r="6"/><path d="M20 20l-4.5-4.5"/>')), h("b", {}, t("Search network")),
|
||
h("small", {}, t("Finds DSPs in your network automatically")));
|
||
}
|
||
|
||
function viewSettings() {
|
||
const sections = [
|
||
["general", t("General"), t("Language, demo mode and your logo."), "", [langCard(), demoCard(), logoCard()]],
|
||
["devices", t("Devices"), t("Several DSPs can be connected at the same time – pick one at the top. A DSP accepts only one connection: close the Thomann editor first."),
|
||
"wide", [...S.order.filter(id => !S.devices[id].demo).map(id => deviceForm(S.devices[id])), scanCard(), addDeviceCard()]],
|
||
["access", S.isApp ? t("Remote access") : t("Security"), S.isApp ? t("Let phones and tablets in your network control this computer – they log in with the PIN.") : t("Who may use this web interface."),
|
||
"wide", [S.isApp ? remoteCard() : null, pinCard()]],
|
||
["backup", t("Backup"), t("Save and restore the settings of this app."), "wide", [backupCard()]],
|
||
];
|
||
const nav = h("nav", { class: "setnav", "aria-label": t("Settings") }, sections.map(([id, title]) =>
|
||
h("button", { class: "chip", "data-view-ok": "", onclick: () => document.getElementById("set-" + id)?.scrollIntoView({ behavior: "smooth", block: "start" }) }, title)));
|
||
return h("div", { class: "setwrap" }, nav, sections.map(([id, title, desc, cls, cards]) =>
|
||
h("section", { class: "setsec", id: "set-" + id },
|
||
h("header", {}, h("h2", {}, title), h("p", {}, desc)),
|
||
h("div", { class: "setgrid " + cls }, cards.filter(Boolean)))));
|
||
}
|
||
|
||
// ------------------------------------------------------------------ render
|
||
|
||
const H_SCROLL = ".mixer, .bands, .geq, .routing";
|
||
// first start: nothing added yet
|
||
function noDspView() {
|
||
return h("div", { class: "empty nodsp" }, svgIcon('<rect x="3" y="7" width="18" height="10" rx="2"/><path d="M7 12h.01M11 12h6"/>'),
|
||
h("b", {}, t("No DSP added yet")),
|
||
h("p", {}, t("Add your DSP over the network or USB. To look around first, switch on demo mode in the settings.")),
|
||
h("button", { class: "on", "data-view-ok": "", onclick: () => {
|
||
S.settings = true; S.addDev = true; render();
|
||
document.getElementById("set-devices")?.scrollIntoView({ block: "start" });
|
||
} }, t("Add a DSP")));
|
||
}
|
||
|
||
function render() {
|
||
if (S.busy) { S.dirty = true; return; }
|
||
if ($("#app").hidden) return;
|
||
if (!S.devices[S.cur]) S.cur = S.order[0] || null;
|
||
if (testOn(S.devices[S.cur])) { S.view = "test"; S.settings = false; } // stays in the audio test until the analog input is back
|
||
// 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();
|
||
const field = !S.settings && S.view === "soundfield"; // the room plan works without a connected DSP
|
||
const dash = !S.settings && S.view === "dash"; // shows all DSPs, works without any
|
||
document.body.dataset.view = field ? "soundfield" : dash ? "dash" : S.settings ? "settings" : S.view;
|
||
if (field) content = viewSoundField();
|
||
else if (dash) content = viewDash();
|
||
else if (S.settings) content = viewSettings();
|
||
else if (!d) content = noDspView();
|
||
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) })
|
||
: d.status === "locked" ? h("div", {}, h("p", {}, t("This DSP is locked with a code.")),
|
||
h("button", { class: "on", onclick: () => unlockDialog(d) }, t("Enter code")))
|
||
: S.demo.enabled && !d.demo ? t("Disconnected while demo mode is on") : t("Not connected."));
|
||
else content = ({ mixer: viewMixer, channel: viewChannel, routing: viewRouting, link: viewLink, fir: d.fir ? viewFir : viewMixer, limiter: viewLimiter, test: viewTest }[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();
|
||
if (d) maybeAskUnlock(d);
|
||
}
|
||
// 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", () => {
|
||
if (testOn(dev()) && b.dataset.view !== "test") return;
|
||
S.view = b.dataset.view; S.settings = false; store.set("dsp.view", S.view); render(); window.scrollTo(0, 0);
|
||
}));
|
||
$("#btn-settings").addEventListener("click", () => { if (testOn(dev())) return; S.settings = !S.settings; render(); window.scrollTo(0, 0); });
|
||
|
||
// menu at the top while it fits next to the DSP choice, otherwise a sidebar on the left (phones: bottom bar)
|
||
function fitNav() {
|
||
const top = $("#top"), b = document.body;
|
||
if (window.innerWidth < 760) { b.classList.remove("navside"); return; }
|
||
b.classList.remove("navside"); // measure the one-row layout (no paint happens in between)
|
||
const kids = [...top.children].filter(el => !el.hidden && getComputedStyle(el).display !== "none");
|
||
const cs = getComputedStyle(top), gap = parseFloat(cs.columnGap) || 0;
|
||
// natural widths: the DSP button may be squeezed by flexbox, so take its content width
|
||
const need = kids.reduce((w, el) => w + (el.id === "devtabs" ? Math.max(el.scrollWidth, 210) : el.getBoundingClientRect().width), 0)
|
||
+ gap * (kids.length - 1) + parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight);
|
||
if (need > top.clientWidth + 1) b.classList.add("navside");
|
||
}
|
||
window.addEventListener("resize", fitNav);
|
||
|
||
// 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)
|
||
|
||
// Phones and tablets on the web UI start read-only, so nothing changes by touching it by accident.
|
||
// Only a safety catch in this browser tab: it is not stored and the server knows nothing about it.
|
||
const viewOnly = () => !!S.locked || !!S.guard;
|
||
function showGuard() {
|
||
const b = $("#btn-guard"), used = !S.isApp && S.guardUsed;
|
||
b.hidden = !used;
|
||
b.setAttribute("aria-checked", String(!S.guard));
|
||
b.classList.toggle("on", !S.guard);
|
||
b.title = S.guard ? t("Read-only – tap to edit") : t("Editing – tap for read-only");
|
||
b.setAttribute("aria-label", b.title);
|
||
b.replaceChildren(h("span", { class: "guardlab" }, S.guard ? t("View") : t("Edit")), h("span", { class: "guardtrack" }, h("i")));
|
||
document.body.classList.toggle("locked", viewOnly());
|
||
}
|
||
$("#btn-guard").addEventListener("click", () => {
|
||
S.guard = !S.guard; showGuard(); render();
|
||
toast(S.guard ? t("Read-only") : t("Edit mode – changes go to the DSP"));
|
||
});
|
||
|
||
function showLock() {
|
||
const b = $("#btn-lock");
|
||
b.hidden = !S.isApp;
|
||
document.body.classList.toggle("locked", viewOnly());
|
||
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, #btn-muteall, [data-view-ok]";
|
||
for (const type of ["pointerdown", "mousedown", "click", "dblclick", "keydown", "wheel"]) {
|
||
document.addEventListener(type, e => {
|
||
if (!viewOnly() || !(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(S.locked ? t("Locked – unlock at the top right to make changes") : t("Read-only – switch to edit at the top")); }
|
||
}, { 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 (ev.demo) S.demo = ev.demo;
|
||
if (ev.muteall) { S.muteAll = ev.muteall.active; showMuteAll(); }
|
||
if (ev.soundfield) S.sf = ev.soundfield;
|
||
if ("dashboard" in ev) S.dash = ev.dashboard && ev.dashboard.modules;
|
||
if ("logo" in ev) { S.logo = ev.logo; showLogo(); }
|
||
if (S.demo.enabled && S.devices.demo && !S.devices[S.cur]?.demo) S.cur = "demo";
|
||
S.order.forEach(id => maybeAskUnlock(S.devices[id]));
|
||
if (!S.order.length) S.settings = true;
|
||
render();
|
||
if (S.reopenY != null) { window.scrollTo(0, S.reopenY); S.reopenY = null; }
|
||
break;
|
||
case "device": {
|
||
if (!S.devices[ev.device]) S.order.push(ev.device);
|
||
const was = testOn(S.devices[ev.device]);
|
||
S.devices[ev.device] = ev.data;
|
||
if (!was && testOn(ev.data) && ev.device === S.cur) { S.view = "test"; S.settings = false; } // e.g. DSP found playing noise
|
||
render(); break;
|
||
}
|
||
case "test": {
|
||
const d = S.devices[ev.device];
|
||
if (d && d.state) { d.state.test = ev.test; 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();
|
||
maybeAskUnlock(d);
|
||
break;
|
||
}
|
||
case "soundfield":
|
||
sfOnRemote(ev.data); break;
|
||
case "dashboard":
|
||
dashRemote(ev.data); break;
|
||
case "logo":
|
||
S.logo = ev.data; showLogo(); if (S.settings) render(); break;
|
||
case "muteall":
|
||
S.muteAll = ev.data.active; showMuteAll(); break;
|
||
case "demo":
|
||
S.demo = ev.data;
|
||
if (!S.demo.enabled && S.cur === "demo") S.cur = S.order.find(id => id !== "demo") || null;
|
||
render(); 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 (S.view === "dash") dashSoon();
|
||
// the test fader moves every output: the audio test view only shows meters, no need to redraw
|
||
if (ev.device === S.cur && !S.settings && !(S.view === "test" && ev.param === "gain")) 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" || S.view === "dash")) 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;
|
||
S.guardUsed = !S.isApp && matchMedia("(max-width: 759px), (pointer: coarse)").matches;
|
||
S.guard = S.guardUsed;
|
||
showGuard();
|
||
showLock();
|
||
showMuteAll();
|
||
if (S.isApp) S.remote = await api("GET", "/api/remote");
|
||
} catch { /* plain web UI */ }
|
||
try { // after a language switch: back to the settings and the scroll position
|
||
const r = JSON.parse(sessionStorage.getItem("dsp.reopen") || "null");
|
||
sessionStorage.removeItem("dsp.reopen");
|
||
if (r && r.settings) { S.settings = true; S.reopenY = r.y || 0; }
|
||
} catch { /* private mode */ }
|
||
connectEvents();
|
||
}
|
||
|
||
(async function init() {
|
||
try {
|
||
const a = await (await fetch("/api/auth")).json();
|
||
if (a.authenticated) startApp(); else showLogin();
|
||
} catch { showLogin(); }
|
||
})();
|