File size: 13,951 Bytes
db3e932
 
 
9ceefcc
db3e932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Mastering studio (DoD): client-side WebAudio chain EQ → compressor → limiter, loudness normalisation to target LUFS
// (ITU-R BS.1770-4 K-weighting + gating, measured offline), live meter, A/B, WAV/MP3 export, save to workspace.
import { STUDIOS, onStop, loop, cv } from './widgets.js?v=50';
import { result, MODULES, esc, setS, keep } from './real.js?v=136';

/* ---------- BS.1770 loudness ---------- */
function biquad(x, b0, b1, b2, a0, a1, a2) { const y = new Float32Array(x.length); b0 /= a0; b1 /= a0; b2 /= a0; a1 /= a0; a2 /= a0; let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
  for (let i = 0; i < x.length; i++) { const v = b0 * x[i] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2; x2 = x1; x1 = x[i]; y2 = y1; y1 = v; y[i] = v; } return y; }
function kweight(x, fs) {
  let w0 = 2 * Math.PI * 1681.974450955533 / fs, A = Math.pow(10, 3.99984385397 / 40), Q = 0.7071752369554196, al = Math.sin(w0) / (2 * Q), c = Math.cos(w0), sA = Math.sqrt(A);
  const s1 = biquad(x, A * ((A + 1) + (A - 1) * c + 2 * sA * al), -2 * A * ((A - 1) + (A + 1) * c), A * ((A + 1) + (A - 1) * c - 2 * sA * al), (A + 1) - (A - 1) * c + 2 * sA * al, 2 * ((A - 1) - (A + 1) * c), (A + 1) - (A - 1) * c - 2 * sA * al);
  w0 = 2 * Math.PI * 38.13547087602444 / fs; Q = 0.5003270373238773; al = Math.sin(w0) / (2 * Q); c = Math.cos(w0);
  return biquad(s1, (1 + c) / 2, -(1 + c), (1 + c) / 2, 1 + al, -2 * c, 1 - al);
}
export function lufs(buf) {
  const fs = buf.sampleRate, ch = Math.min(buf.numberOfChannels, 2), K = [...Array(ch)].map((_, c) => kweight(buf.getChannelData(c), fs));
  const blk = Math.round(0.4 * fs), hop = Math.round(0.1 * fs), z = [];
  for (let s = 0; s + blk <= buf.length; s += hop) { let sum = 0; for (let c = 0; c < ch; c++) { const k = K[c]; let a = 0; for (let i = s; i < s + blk; i++) a += k[i] * k[i]; sum += a / blk; } z.push(sum); }
  if (!z.length) return -70;
  const L = (v) => -0.691 + 10 * Math.log10(v); const g1 = z.filter(v => L(v) > -70); if (!g1.length) return -70;
  const rel = L(g1.reduce((a, b) => a + b, 0) / g1.length) - 10; const g2 = g1.filter(v => L(v) > rel);
  return L(g2.reduce((a, b) => a + b, 0) / g2.length);
}
const peakDb = (buf) => { let p = 0; for (let c = 0; c < buf.numberOfChannels; c++) { const d = buf.getChannelData(c); for (let i = 0; i < d.length; i++) { const v = Math.abs(d[i]); if (v > p) p = v; } } return 20 * Math.log10(p || 1e-9); };

/* ---------- processing chain (offline render) ---------- */
export const PRESETS = { streaming: { name: 'Streaming −14 LUFS', target: -14, ceiling: -1 }, club: { name: 'Club −9 LUFS', target: -9, ceiling: -0.5 }, podcast: { name: 'Podcast −16 LUFS', target: -16, ceiling: -1.5 }, broadcast: { name: 'EBU R128 −23 LUFS', target: -23, ceiling: -1 } };
async function render(buf, p, makeupDb) {
  const oc = new OfflineAudioContext(buf.numberOfChannels, buf.length, buf.sampleRate); const s = oc.createBufferSource(); s.buffer = buf;
  const lo = oc.createBiquadFilter(); lo.type = 'lowshelf'; lo.frequency.value = 100; lo.gain.value = p.low;
  const mid = oc.createBiquadFilter(); mid.type = 'peaking'; mid.frequency.value = 1000; mid.Q.value = 0.8; mid.gain.value = p.mid;
  const hi = oc.createBiquadFilter(); hi.type = 'highshelf'; hi.frequency.value = 8000; hi.gain.value = p.high;
  const comp = oc.createDynamicsCompressor(); comp.threshold.value = p.thr; comp.ratio.value = p.ratio; comp.knee.value = 6; comp.attack.value = 0.01; comp.release.value = 0.2;
  const g = oc.createGain(); g.gain.value = Math.pow(10, makeupDb / 20);
  const lim = oc.createDynamicsCompressor(); lim.threshold.value = p.ceiling - 0.5; lim.knee.value = 0; lim.ratio.value = 20; lim.attack.value = 0.001; lim.release.value = 0.05;
  s.connect(lo); lo.connect(mid); mid.connect(hi); hi.connect(comp); comp.connect(g); g.connect(lim); lim.connect(oc.destination); s.start();
  const out = await oc.startRendering();
  const pk = peakDb(out); if (pk > p.ceiling) { const k = Math.pow(10, (p.ceiling - pk) / 20); for (let c = 0; c < out.numberOfChannels; c++) { const d = out.getChannelData(c); for (let i = 0; i < d.length; i++) d[i] *= k; } } // safety ceiling
  return out;
}
export async function master(buf, p) {
  const before = lufs(buf); let mk = p.target - lufs(await render(buf, p, 0)), out;
  for (let i = 0; i < 3; i++) { out = await render(buf, p, mk); const l = lufs(out); if (Math.abs(l - p.target) < 0.3) break; mk += p.target - l; } // limiter eats gain → iterate
  return { out, before, after: lufs(out), peakBefore: peakDb(buf), peakAfter: peakDb(out), makeup: mk };
}

/* ---------- export ---------- */
export function toWav(buf) { const ch = buf.numberOfChannels, sr = buf.sampleRate, n = buf.length, dv = new DataView(new ArrayBuffer(44 + n * ch * 2)); const w = (o, s) => [...s].forEach((c, i) => dv.setUint8(o + i, c.charCodeAt(0)));
  w(0, 'RIFF'); dv.setUint32(4, 36 + n * ch * 2, true); w(8, 'WAVEfmt '); dv.setUint32(16, 16, true); dv.setUint16(20, 1, true); dv.setUint16(22, ch, true); dv.setUint32(24, sr, true); dv.setUint32(28, sr * ch * 2, true); dv.setUint16(32, ch * 2, true); dv.setUint16(34, 16, true); w(36, 'data'); dv.setUint32(40, n * ch * 2, true);
  const D = [...Array(ch)].map((_, c) => buf.getChannelData(c)); for (let i = 0, o = 44; i < n; i++) for (let c = 0; c < ch; c++, o += 2) dv.setInt16(o, Math.max(-1, Math.min(1, D[c][i])) * 32767, true); return new Blob([dv], { type: 'audio/wav' }); }
export async function toMp3(buf, kbps = 192, onP) { const { Mp3Encoder } = await import('./vendor/lame.js?v=1'); const ch = Math.min(2, buf.numberOfChannels), enc = new Mp3Encoder(ch, buf.sampleRate, kbps);
  const I = (d) => { const o = new Int16Array(d.length); for (let i = 0; i < d.length; i++) o[i] = Math.max(-1, Math.min(1, d[i])) * 32767; return o; }; const L = I(buf.getChannelData(0)), R = ch > 1 ? I(buf.getChannelData(1)) : null; const parts = [];
  for (let i = 0; i < L.length; i += 1152 * 50) { const e = R ? enc.encodeBuffer(L.subarray(i, i + 1152 * 50), R.subarray(i, i + 1152 * 50)) : enc.encodeBuffer(L.subarray(i, i + 1152 * 50)); if (e.length) parts.push(new Uint8Array(e)); onP?.(i / L.length); await new Promise(r => setTimeout(r)); }
  const f = enc.flush(); if (f.length) parts.push(new Uint8Array(f)); return new Blob(parts, { type: 'audio/mpeg' }); }
const decode = async (blob) => { const ac = new OfflineAudioContext(2, 1, 44100); return ac.decodeAudioData(await blob.arrayBuffer()); };
const toBlob = async (a) => a.blob || a.file || (await fetch(a.url, { credentials: 'include' })).blob();

/* ---------- studio ---------- */
STUDIOS.push({ id: 'master', cat: 'Audio', icon: '🎛', name: 'Mastering', like: 'Mastering-Suite', real: 'LOKAL', accepts: ['audio'], build(el) {
  el.innerHTML = `<div class="row" style="margin:0 0 6px"><span class="badge real">LOKAL</span><span class="stat">Audio laden oder aus Music Gen senden</span></div>
  <div class="row"><input type="file" accept="audio/*" aria-label="Audiodatei"></div>
  <div class="row"><label class="fl inline">Ziel<select class="pre" aria-label="Loudness-Ziel">${Object.entries(PRESETS).map(([k, v]) => `<option value="${k}">${v.name}</option>`).join('')}</select></label></div>
  <div class="knobs">${[['low', 'Bass', -6, 6, 1.5], ['mid', 'Mitten', -6, 6, 0], ['high', 'Höhen', -6, 6, 1], ['thr', 'Comp-Threshold', -40, 0, -18], ['ratio', 'Comp-Ratio', 1, 8, 2.5]].map(([k, n, a, b, v]) => `<label class="fl">${n} <b data-v="${k}">${v}</b><input type="range" data-k="${k}" min="${a}" max="${b}" step="0.5" value="${v}" aria-label="${n}"></label>`).join('')}</div>
  <div class="row"><button class="btn go" disabled>🎛 Mastern</button><button class="btn alt ab" disabled aria-pressed="false">▶ A/B</button><span class="abl code">A = Original</span></div>
  <canvas class="meter"></canvas><div class="lu code">Integrated: – · Peak: –</div>
  <div class="row"><button class="btn alt wav" disabled>⬇ WAV</button><button class="btn alt mp3" disabled>⬇ MP3 192k</button></div><div class="out"></div>
  <div class="credit">100 % im Browser: WebAudio (EQ, Kompressor, Limiter) · BS.1770-4 LUFS-Messung · MP3 via lame.js (gebündelt)</div>`;
  keep(el); const q = (s) => el.querySelector(s); let src = null, name = 'track', res = null, ac = null, node = null, an = null, playB = false, t0 = 0, off = 0;
  const P = () => { const o = { ...PRESETS[q('.pre').value] }; el.querySelectorAll('[data-k]').forEach(i => o[i.dataset.k] = +i.value); return o; };
  el.querySelectorAll('[data-k]').forEach(i => i.oninput = () => q(`[data-v="${i.dataset.k}"]`).textContent = i.value);
  const load = async (blob, nm) => { stop(); setS(el, 'Dekodiere…'); try { src = await decode(blob); name = (nm || 'track').replace(/\.[^.]+$/, ''); res = null; const l = lufs(src);
      q('.lu').textContent = `Original: ${l.toFixed(1)} LUFS · Peak ${peakDb(src).toFixed(1)} dBFS · ${src.duration.toFixed(1)} s`; q('.go').disabled = false; q('.ab').disabled = false; ['.wav', '.mp3'].forEach(s => q(s).disabled = true); setS(el, '✔ geladen: ' + nm); window.__master = { loaded: nm, before: l }; }
    catch (e) { setS(el, '⚠ Audio nicht lesbar: ' + e.message, true); } };
  q('input[type=file]').onchange = (e) => { const f = e.target.files[0]; if (f) load(f, f.name); };
  q('.go').onclick = async () => { if (!src) return; q('.go').disabled = true; setS(el, 'Mastere (offline render, BS.1770-Messung)…'); const p = P();
    try { res = await master(src, p); if (!el.isConnected) return; q('.lu').textContent = `Vorher ${res.before.toFixed(1)} LUFS / ${res.peakBefore.toFixed(1)} dBFS → Nachher ${res.after.toFixed(1)} LUFS / ${res.peakAfter.toFixed(1)} dBFS (Ziel ${p.target})`;
      ['.wav', '.mp3'].forEach(s => q(s).disabled = false); setS(el, `✔ gemastert: ${res.after.toFixed(1)} LUFS (Makeup ${res.makeup.toFixed(1)} dB)`); window.__master = { ...window.__master, after: res.after, peak: res.peakAfter, target: p.target };
      if (ac) { playB = true; restart(); } } catch (e) { setS(el, '⚠ ' + e.message, true); } finally { q('.go').disabled = false; } };
  // A/B playback with live meter
  const stop = () => { try { node?.stop(); } catch (e) {} node = null; };
  const restart = () => { const pos = ac ? off + (ac.currentTime - t0) : 0; stop(); const b = playB && res ? res.out : src; if (!b) return; node = ac.createBufferSource(); node.buffer = b; node.loop = true; node.connect(an); off = pos % b.duration; node.start(0, off); t0 = ac.currentTime; q('.abl').textContent = playB && res ? 'B = Gemastert' : 'A = Original'; };
  q('.ab').onclick = async () => { if (!ac) { ac = new AudioContext(); an = ac.createAnalyser(); an.fftSize = 2048; an.connect(ac.destination); onStop(() => { stop(); ac.close(); }); playB = false; restart(); q('.ab').textContent = '⇄ A/B'; q('.ab').setAttribute('aria-pressed', 'true'); return; }
    playB = !playB; restart(); };
  const [c, x, w, h] = cv(el, 38); const buf = new Float32Array(2048); let hold = -60;
  loop(() => { x.fillStyle = '#000'; x.fillRect(0, 0, w, h); if (!an || !node) { x.fillStyle = '#555'; x.font = '10px Outfit'; x.fillText('Meter: A/B starten', 8, 22); return; }
    an.getFloatTimeDomainData(buf); let s = 0; for (const v of buf) s += v * v; const db = 10 * Math.log10(s / buf.length || 1e-9) - 0.691 + 3; hold = Math.max(db, hold - 0.4);
    const X = (d) => Math.max(0, Math.min(1, (d + 40) / 40)) * w; const g = x.createLinearGradient(0, 0, w, 0); g.addColorStop(0, '#028391'); g.addColorStop(.7, '#f2c94c'); g.addColorStop(1, '#f85525'); x.fillStyle = g; x.fillRect(0, 8, X(db), h - 16);
    const tg = PRESETS[q('.pre').value].target; x.fillStyle = '#fff'; x.fillRect(X(tg), 2, 2, h - 4); x.fillStyle = '#f6dcac'; x.fillRect(X(hold), 6, 1, h - 12); x.font = '10px Outfit'; x.fillText(`${db.toFixed(1)} LU(M)≈ · Ziel ${tg}`, 6, h - 2); });
  const exp = async (kind) => { const b = res.out; setS(el, kind === 'mp3' ? 'MP3-Encoding…' : 'WAV…'); const blob = kind === 'mp3' ? await toMp3(b, 192, p => setS(el, `MP3 ${Math.round(p * 100)} %`)) : toWav(b);
    const u = URL.createObjectURL(blob); onStop(() => URL.revokeObjectURL(u)); const fn = `${name}-master-${Math.round(res.after)}LUFS.${kind}`;
    q('.out').innerHTML = `<audio controls src="${u}"></audio><a class="btn alt" href="${u}" download="${esc(fn)}">⬇ ${esc(fn)}</a>`; result(q('.out'), { kind: 'audio', mime: blob.type, blob, name: fn, studio: 'master', prompt: `master ${PRESETS[q('.pre').value].name}` });
    window.__masterExport = { kind, size: blob.size, name: fn }; setS(el, `✔ ${kind.toUpperCase()} bereit (${(blob.size / 1e6).toFixed(2)} MB)`); };
  q('.wav').onclick = () => exp('wav'); q('.mp3').onclick = () => exp('mp3');
  el.__load = load;
} });
const M = STUDIOS.find(s => s.id === 'master');
M.accept = async (el, a) => { await el.__load(await toBlob(a), a.name); return true; };

/* ---------- Module API ---------- */
MODULES.master = { id: 'master', name: 'Mastering', backend: 'WebAudio (lokal)', inputs: [{ name: 'source', type: 'audio-url' }, { name: 'target', type: 'number' }], outputs: [{ kind: 'audio' }],
  actions: { master: { desc: 'Mastert ein Audio (URL eines vorherigen Ergebnisses) auf Ziel-LUFS und liefert MP3', params: { source: 'string', target: 'number' },
    run: async ({ source, target = -14 }) => { if (!source) throw new Error('source (Audio-URL) fehlt'); const b = await decode(await (await fetch(source, { credentials: 'include' })).blob());
      const p = { ...PRESETS.streaming, target: +target || -14, low: 1, mid: 0, high: 1, thr: -18, ratio: 2.5 }; const r = await master(b, p); const blob = await toMp3(r.out, 192);
      return { kind: 'audio', mime: 'audio/mpeg', blob, url: URL.createObjectURL(blob), name: `master-${Date.now()}-${Math.round(r.after)}LUFS.mp3`, studio: 'master', prompt: `LUFS ${r.before.toFixed(1)} → ${r.after.toFixed(1)}`, text: `Gemastert: ${r.before.toFixed(1)} → ${r.after.toFixed(1)} LUFS` }; } } } };