158 lines
9.7 KiB
JavaScript
158 lines
9.7 KiB
JavaScript
"use strict";
|
||
|
||
// Sound Lab: working together with REW (Room EQ Wizard). Take filters from a measurement or a filter file, compare them
|
||
// with the channel before applying, send a channel's EQ back. Desktop apps only: REW's API only answers on the computer
|
||
// it runs on, so the server inside the app talks to it (see rew_call).
|
||
|
||
const REW_IN = { PK: 0, PEAK: 0, LS: 1, LSC: 1, LSQ: 1, HS: 2, HSC: 2, HSQ: 2, HP1: 3, HP: 4, HPQ: 4, LP1: 5, LP: 6, LPQ: 6, AP: 8 };
|
||
const REW_OUT = ["PK", "LS", "HS", "HP1", "HP", "LP1", "LP", "AP", "AP"];
|
||
const lab = { dev: null, sel: { kind: "out", idx: 0 }, rows: null, from: "", rew: null, measId: "", checked: false };
|
||
|
||
const num2 = s => Number(String(s).replace(",", "."));
|
||
|
||
// "Filter 1: ON PK Fc 100.0 Hz Gain -3.0 dB Q 2.00" from REW's filter settings text
|
||
function rewParseText(text) {
|
||
const out = [];
|
||
for (const line of text.split(/\r?\n/)) {
|
||
const m = /^\s*Filter\s+(\d+)\s*:\s*(ON|OFF)\s+(\S+)(.*)$/i.exec(line);
|
||
if (!m || /^none$/i.test(m[3])) continue;
|
||
const rest = m[4];
|
||
const fc = /Fc\s*([\d.,]+)\s*(k?)Hz/i.exec(rest), gain = /Gain\s*([-+\d.,]+)\s*dB/i.exec(rest), q = /\bQ\s*([\d.,]+)/i.exec(rest);
|
||
out.push({ type: m[3].toUpperCase(), enabled: m[2].toUpperCase() === "ON",
|
||
frequency: fc ? num2(fc[1]) * (fc[2] ? 1000 : 1) : 0, gaindB: gain ? num2(gain[1]) : 0, q: q ? num2(q[1]) : 0 });
|
||
}
|
||
return out;
|
||
}
|
||
|
||
const rewNearestQ = q => Q_TABLE.reduce((best, v, i) => (Math.abs(Math.log(v / q)) < Math.abs(Math.log(Q_TABLE[best] / q)) ? i : best), 0);
|
||
|
||
// REW filter -> band of the DSP, with a note where the DSP can't take it exactly
|
||
function rewToBand(f) {
|
||
if (/^none$/i.test(String(f.type || "None"))) return null;
|
||
const type = REW_IN[String(f.type).toUpperCase().replace(/\s/g, "")];
|
||
if (type === undefined) return { unsupported: true };
|
||
const gain = clamp(Math.round(120 + (f.gaindB || 0) * 10), 0, 240), q = f.q > 0 ? rewNearestQ(f.q) : 32;
|
||
const notes = [];
|
||
if (Math.abs(f.gaindB || 0) > 12) notes.push(t("gain limited to ±12 dB"));
|
||
if (f.frequency < 20 || f.frequency > 20000) notes.push(t("frequency limited to 20 Hz … 20 kHz"));
|
||
return { band: { type, freq: hzFreq(f.frequency), gain, q, bypass: f.enabled === false }, notes };
|
||
}
|
||
function rewFromBand(b, i) {
|
||
return { index: i + 1, type: REW_OUT[b.type], enabled: !b.bypass, isAuto: false, frequency: +freqHz(b.freq).toFixed(1),
|
||
gaindB: hasGain(b.type) ? eqDb(b.gain) : 0, q: Q_TABLE[b.q] };
|
||
}
|
||
|
||
function rewCurve(d, kind, idx) {
|
||
const ch = chans(d, kind)[idx], ppo = 96, n = Math.floor(Math.log2(1000) * ppo) + 1, magnitude = [], phase = [];
|
||
for (let i = 0; i < n; i++) {
|
||
const hh = channelH(ch, 20 * 2 ** (i / ppo));
|
||
magnitude.push(+cdb(hh).toFixed(3));
|
||
phase.push(+cdeg(hh).toFixed(2));
|
||
}
|
||
return { identifier: `${d.name} ${chLabel(kind, idx)}`.slice(0, 60), startFreq: 20, ppo, magnitude, phase };
|
||
}
|
||
|
||
async function labCheck() {
|
||
try {
|
||
const st = await api("GET", "/api/rew/status"), meas = await api("GET", "/api/rew/measurements");
|
||
lab.rew = { version: st.version, meas };
|
||
if (!meas.some(m => m.id === lab.measId)) lab.measId = meas[0] ? meas[0].id : "";
|
||
} catch { lab.rew = null; lab.measId = ""; }
|
||
lab.checked = true;
|
||
if (S.view === "lab" && !S.settings) render();
|
||
}
|
||
|
||
function openLab(kind, idx) {
|
||
lab.sel = { kind, idx }; lab.rows = null;
|
||
S.view = "lab"; store.set("dsp.view", "lab"); render(); window.scrollTo(0, 0);
|
||
}
|
||
|
||
function labTake(filters, from) { lab.rows = filters.map(rewToBand).filter(Boolean); lab.from = from; render(); }
|
||
async function labFromFile() {
|
||
let f;
|
||
try { f = await openFile(".txt,text/plain"); } catch (e) { return toast(trMsg(e.message)); }
|
||
if (!f) return;
|
||
const list = rewParseText(atob(f.b64));
|
||
if (!list.length) return toast(t("No REW filters found in this file."));
|
||
labTake(list, f.name);
|
||
}
|
||
|
||
function viewLab(d) {
|
||
if (lab.dev !== d.id) { lab.dev = d.id; lab.rows = null; lab.sel = { kind: "out", idx: 0 }; }
|
||
if (lab.sel.idx >= chans(d, lab.sel.kind).length) lab.sel = { kind: "out", idx: 0 };
|
||
if (!lab.checked) { lab.checked = true; labCheck(); }
|
||
const { kind, idx } = lab.sel, ch = chans(d, kind)[idx], name = chTitle(d, kind, idx), n = ch.peq.length;
|
||
const measName = () => (lab.rew.meas.find(m => m.id === lab.measId) || {}).title || "";
|
||
|
||
const chip = (k, i) => h("button", { class: "firch" + (k === kind && i === idx ? " on" : "") + (chans(d, k)[i].peq.some(b => !b.bypass && b.gain !== 120) ? " used" : ""), "data-view-ok": "",
|
||
onclick: () => { lab.sel = { kind: k, idx: i }; lab.rows = null; render(); } },
|
||
h("b", {}, chLabel(k, i)), h("small", {}, chans(d, k)[i].name || " "));
|
||
|
||
// proposal from REW: bands that fit, what doesn't
|
||
const usable = (lab.rows || []).filter(r => r.band), kept = usable.slice(0, n), bands = kept.map(r => r.band);
|
||
const skipped = (lab.rows || []).length - usable.length, cut = usable.length - kept.length;
|
||
const proposed = lab.rows && kept.length ? { ...ch, peq: ch.peq.map((old, i) => bands[i] || { ...old, gain: 120, bypass: false }) } : null;
|
||
|
||
const canvas = h("canvas", { class: "labcurve" });
|
||
requestAnimationFrame(() => drawCurve(canvas, ch, -1, { mode: "mag", overlays: proposed ? [{ ch: proposed, color: "#f59e0b" }] : [] }));
|
||
|
||
const apply = () => {
|
||
proposed.peq.forEach((b, i) => setParam(kind, idx, `peq.${i}`, b));
|
||
toast(t("{n} filters applied to {ch}", { n: bands.length, ch: name }));
|
||
lab.rows = null; render();
|
||
};
|
||
const warn = [...new Set(kept.flatMap(r => r.notes))];
|
||
if (cut > 0) warn.push(t("{cut} filters left out: this channel has {n} bands", { cut, n }));
|
||
if (skipped > 0) warn.push(t("{n} filters skipped: type not available on the DSP", { n: skipped }));
|
||
|
||
const proposal = lab.rows ? h("div", { class: "labprop" }, h("div", { class: "sub" }, lab.from),
|
||
kept.length ? h("table", { class: "rewtable" },
|
||
h("tr", {}, ["", t("Type"), t("Frequency"), "Gain", "Q"].map(x => h("th", {}, x))),
|
||
kept.map((r, i) => h("tr", { class: r.band.bypass ? "off" : "" }, h("td", {}, String(i + 1)), h("td", {}, PEQ_SHORT[r.band.type]), h("td", {}, fmtHz(freqHz(r.band.freq))),
|
||
h("td", {}, hasGain(r.band.type) ? `${sign(eqDb(r.band.gain))} dB` : "–"), h("td", {}, hasQ(r.band.type) ? String(Q_TABLE[r.band.q]) : "–"))))
|
||
: h("p", { class: "info" }, t("No usable filters found.")),
|
||
warn.length ? h("p", { class: "rewwarn" }, warn.join(" · ")) : null,
|
||
h("div", { class: "row" },
|
||
kept.length && !viewOnly() ? h("button", { class: "on", onclick: apply }, t("Apply to {ch}", { ch: name })) : null,
|
||
h("button", { "data-view-ok": "", onclick: () => { lab.rows = null; render(); } }, t("Discard")))) : null;
|
||
|
||
const on = !!lab.rew, has = on && lab.rew.meas.length > 0;
|
||
const measSel = h("select", { "aria-label": t("Measurement"), disabled: !has, "data-view-ok": "", onchange: e => { lab.measId = e.target.value; } },
|
||
has ? lab.rew.meas.map(m => h("option", { value: m.id, selected: m.id === lab.measId }, m.title)) : h("option", { value: "" }, on ? t("No measurements in REW") : "–"));
|
||
const take = async () => {
|
||
try { labTake(await api("POST", "/api/rew/filters", { id: lab.measId }), measName()); }
|
||
catch (e) { toast(t("Error: ") + trMsg(e.message)); }
|
||
};
|
||
const sendFilters = async () => {
|
||
try {
|
||
await api("POST", "/api/rew/send-filters", { id: lab.measId, filters: ch.peq.map(rewFromBand).filter(x => (x.type === "PK" ? x.gaindB !== 0 : true)) });
|
||
toast(t("Filters sent to “{m}”", { m: measName() }));
|
||
} catch (e) { toast(t("Error: ") + trMsg(e.message)); }
|
||
};
|
||
const sendCurve = async () => {
|
||
try { await api("POST", "/api/rew/send-curve", rewCurve(d, kind, idx)); toast(t("Curve sent to REW as a new measurement")); labCheck(); }
|
||
catch (e) { toast(t("Error: ") + trMsg(e.message)); }
|
||
};
|
||
|
||
return [
|
||
h("div", { class: "dhead" }, h("h2", {}, "Sound Lab"),
|
||
h("div", { class: "row labstate" },
|
||
h("span", { class: "dot " + (on ? "online" : "disconnected") }),
|
||
h("span", { class: "info" }, on ? t("REW {v} · {n} measurements", { v: lab.rew.version, n: lab.rew.meas.length }) : t("REW not connected")),
|
||
h("button", { class: "small", "data-view-ok": "", onclick: labCheck }, t("Check")),
|
||
docButton(DOC_LAB))),
|
||
h("div", { class: "cards labcards" },
|
||
h("div", { class: "card wide" }, h("div", { class: "firchs" }, chans(d, "in").map((_, i) => chip("in", i)), h("span", { class: "firsep" }), chans(d, "out").map((_, i) => chip("out", i)))),
|
||
h("div", { class: "card wide" }, h("h3", {}, h("span", { class: "grow" }, name), proposed ? h("span", { class: "lablegend" }, h("i", { style: "background:#38bdf8" }), t("now"), h("i", { style: "background:#f59e0b" }), t("after applying")) : null), canvas),
|
||
h("div", { class: "card" }, h("h3", {}, t("From REW to this channel")),
|
||
on ? null : h("p", { class: "info" }, t("REW can't be reached. Start REW on the computer running this app and switch on its API (Preferences → API). The filter file works anyway.")),
|
||
h("div", { class: "row" }, measSel, h("button", { disabled: !has, "data-view-ok": "", onclick: take }, t("Take filters"))),
|
||
h("div", { class: "row" }, h("button", { "data-view-ok": "", onclick: labFromFile }, t("Load REW filter file…"))),
|
||
proposal),
|
||
h("div", { class: "card" }, h("h3", {}, t("From this channel to REW")),
|
||
h("p", { class: "info" }, t("As a measurement you can compare the channel's curve with real measurements in REW. Filters on a measurement let REW predict the result.")),
|
||
h("div", { class: "row" }, h("button", { disabled: !on, "data-view-ok": "", onclick: sendCurve }, t("Send curve as a new measurement"))),
|
||
h("div", { class: "row" }, h("button", { disabled: !has, "data-view-ok": "", onclick: sendFilters }, t("Send filters to the chosen measurement"))))),
|
||
];
|
||
}
|