// Audio thread for the lab slides' level stage, the non-linear end of the // chain: optional loudness normalization, then a limiter. Messages: // { type: 'normalize', on } // With normalization, an automatic gain control holds the loudness (the mean // square over about LEVEL_TIME) near TARGET_RMS, boosting by at most MAX_BOOST // so near-silence is not turned into noise, and changing the gain smoothly // (over about GAIN_TIME). The limiter keeps a strong resonance from clipping: // it leaves the sound untouched below LIMIT and rounds off peaks above it // (approaching 1), so at normal levels it adds no distortion. const TARGET_RMS = 0.3; const MAX_BOOST = 20; // +26 dB const MIN_GAIN = 0.05; const LEVEL_TIME = 0.2; // seconds const GAIN_TIME = 0.05; // seconds const LIMIT = 0.8; function limit(x) { const a = Math.abs(x); if (a <= LIMIT) return x; return Math.sign(x) * (LIMIT + (1 - LIMIT) * Math.tanh((a - LIMIT) / (1 - LIMIT))); } class LevelProcessor extends AudioWorkletProcessor { constructor() { super(); this.normalize = false; this.ms = TARGET_RMS ** 2; // measured mean square this.gain = 1; this.port.onmessage = (e) => { if (e.data.type === 'normalize') this.normalize = e.data.on; }; } process(inputs, outputs) { const input = inputs[0][0]; const out = outputs[0][0]; const kLevel = 1 - Math.exp(-1 / (LEVEL_TIME * sampleRate)); const kGain = 1 - Math.exp(-1 / (GAIN_TIME * sampleRate)); for (let i = 0; i < out.length; i++) { const y = input ? input[i] : 0; this.ms += kLevel * (y * y - this.ms); const target = this.normalize ? Math.min(MAX_BOOST, Math.max(MIN_GAIN, TARGET_RMS / Math.sqrt(this.ms + 1e-12))) : 1; this.gain += kGain * (target - this.gain); out[i] = limit(y * this.gain); } return true; } } registerProcessor('level-processor', LevelProcessor);