1// Audio thread for the lab slides' level stage, the non-linear end of the
2// chain: optional loudness normalization, then a limiter. Messages:
3// { type: 'normalize', on }
4// With normalization, an automatic gain control holds the loudness (the mean
5// square over about LEVEL_TIME) near TARGET_RMS, boosting by at most MAX_BOOST
6// so near-silence is not turned into noise, and changing the gain smoothly
7// (over about GAIN_TIME). The limiter keeps a strong resonance from clipping:
8// it leaves the sound untouched below LIMIT and rounds off peaks above it
9// (approaching 1), so at normal levels it adds no distortion.
11const TARGET_RMS = 0.3;
12const MAX_BOOST = 20; // +26 dB
13const MIN_GAIN = 0.05;
14const LEVEL_TIME = 0.2; // seconds
15const GAIN_TIME = 0.05; // seconds
16const LIMIT = 0.8;
18function limit(x) {
19 const a = Math.abs(x);
20 if (a <= LIMIT) return x;
21 return Math.sign(x) * (LIMIT + (1 - LIMIT) * Math.tanh((a - LIMIT) / (1 - LIMIT)));
22}
24class LevelProcessor extends AudioWorkletProcessor {
25 constructor() {
26 super();
27 this.normalize = false;
28 this.ms = TARGET_RMS ** 2; // measured mean square
29 this.gain = 1;
30 this.port.onmessage = (e) => {
31 if (e.data.type === 'normalize') this.normalize = e.data.on;
32 };
33 }
35 process(inputs, outputs) {
36 const input = inputs[0][0];
37 const out = outputs[0][0];
38 const kLevel = 1 - Math.exp(-1 / (LEVEL_TIME * sampleRate));
39 const kGain = 1 - Math.exp(-1 / (GAIN_TIME * sampleRate));
40 for (let i = 0; i < out.length; i++) {
41 const y = input ? input[i] : 0;
42 this.ms += kLevel * (y * y - this.ms);
43 const target = this.normalize
44 ? Math.min(MAX_BOOST, Math.max(MIN_GAIN, TARGET_RMS / Math.sqrt(this.ms + 1e-12)))
45 : 1;
46 this.gain += kGain * (target - this.gain);
47 out[i] = limit(y * this.gain);
48 }
49 return true;
50 }
51}
53registerProcessor('level-processor', LevelProcessor);