/ interactive_tutorials / duffing_islands
Sign in
interactive_tutorials / duffing_islands
duffing_islands / app / js / voices.js
432 lines · 17.6 KBBlameHistoryRaw
1// The instruments the orbits play, and the mapping from a point's x to its
2// pitch. Each orbit plays its own voice, so several can be told apart.
3//
4// Each note is rendered once into an AudioBuffer (cached per voice, pitch
5// and sustain), given a soft attack and a short fade at the end, and matched
6// in loudness to all the others. Every voice and pitch rings for the same
7// time: the sustain, the time for the fundamental to fade by 60 dB (set per
8// track). So the voices differ in timbre and attack, not in how long
9// they ring, and loudness is matched by the RMS over each note's onset (its
10// first LOUD_WINDOW s) after the K-weighting filter of ITU-R BS.1770 (a high
11// shelf of +4 dB above about 1.7 kHz, where the ear is most sensitive, and a
12// high-pass at 38 Hz): the same for every voice, pitch and sustain.
13// - Strings (harp, pizzicato) are Karplus-Strong: the string starts in a
14// rounded, fingertip-plucked shape and circulates in a delay line of one
15// period, through a gentle low-pass (so the high harmonics die away first,
16// leaving a warm tone) and a first-order all-pass that tunes the
17// fractional part of the period.
18// - Bars, tines and the ocarina are modal: a few decaying sinusoids, at the
19// instrument's partial ratios (marimba 1 : 3.93 : 9.2, vibraphone
20// 1 : 4 : 10 with tremolo, and so on).
21// - The electric piano is two-operator FM with a fading modulation index.
22// Everything goes through a soft low-pass, a dark synthetic reverb and a
23// limiter.
24// Each track has its own gain (its volume) and sustain. The presets of an
25// uploaded SoundFont (js/soundfont.js) are more voices: their samples play
26// as recorded (sustain doesn't apply), at a MIDI velocity set per track,
27// matched in loudness to the others at velocity 100 near middle C.
29export const DEFAULT_SCALE = 'Minor pentatonic';
30export const KEYS = ['C', 'C♯', 'D', 'E♭', 'E', 'F', 'F♯', 'G', 'A♭', 'A', 'B♭', 'B'];
31export const DEFAULT_KEY = 9; // A
33// Scales as semitone offsets within an octave; null: continuous pitch.
34export const SCALES = [
35 { name: 'Major pentatonic', steps: [0, 2, 4, 7, 9] },
36 { name: 'Minor pentatonic', steps: [0, 3, 5, 7, 10] },
37 { name: 'Major', steps: [0, 2, 4, 5, 7, 9, 11] },
38 { name: 'Natural minor', steps: [0, 2, 3, 5, 7, 8, 10] },
39 { name: 'Harmonic minor', steps: [0, 2, 3, 5, 7, 8, 11] },
40 { name: 'Whole tone', steps: [0, 2, 4, 6, 8, 10] },
41 { name: 'Chromatic', steps: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] },
42 { name: 'Continuous', steps: null },
43];
45const LOW = 130.81; // C3, the pitch at the left edge of the view
46export const OCTAVES = 3; // by default, up to C6 at the right edge
48// The pitch (Hz) for u in [0, 1] (the left to right edge of the view): the
49// notes of the scale in the given key (0 = C, ..., 11 = B) that lie within
50// `octaves` octaves from LOW, spread evenly across the view; or continuous.
51// The register stays put when the key changes, so a key change shifts the
52// harmony, like a chord change.
53export function pitchOf(u, scale, key = 0, octaves = OCTAVES) {
54 u = Math.min(1, Math.max(0, u));
55 if (!scale.steps) return LOW * 2 ** (octaves * u);
56 const notes = [];
57 for (let s = 0; s <= 12 * octaves; s++) {
58 if (scale.steps.includes((((s - key) % 12) + 12) % 12)) notes.push(s);
59 }
60 return LOW * 2 ** (notes[Math.round(u * (notes.length - 1))] / 12);
63export const SUSTAIN = { min: 0.1, max: 4, step: 0.1, default: 2 }; // s
64const LOUD_WINDOW = 0.3; // s
65const LOUDNESS = 0.12; // target K-weighted RMS over LOUD_WINDOW
67// Karplus-Strong string: t60 (s, for the fundamental to fade by 60 dB),
68// pluck (where along the string it is plucked: smaller is brighter).
69function string(sr, freq, t60, { pluck = 0.15 } = {}) {
70 const len = Math.ceil(sr * t60);
71 const out = new Float32Array(len);
72 // Loop delay L = sr / freq: N samples, plus one for the [1/4, 1/2, 1/4]
73 // loop filter, plus the all-pass's d (kept in [0.5, 1.5), where it is
74 // accurate and well behaved).
75 const L = sr / freq;
76 const N = Math.floor(L - 1.5);
77 const d = L - 1 - N;
78 const c = (1 - d) / (1 + d);
79 // the loop filter takes cos^2(pi f / sr) off each harmonic per pass, so
80 // the highs die away within a few periods; the loop gain makes up the
81 // fundamental's share, so it still fades over t60
82 const H1 = Math.cos((Math.PI * freq) / sr) ** 2;
83 const g = Math.min(0.99995, 10 ** (-3 / (t60 * freq)) / H1);
84 // the pluck: the string's initial shape, a triangle peaked at `pluck` of
85 // its length (harmonics falling as 1/k^2: at 0.15, about -8, -14, -21 dB
86 // for the 2nd to 4th), its corner rounded off as by a fingertip, with a
87 // trace of noise
88 const tri = new Float32Array(N);
89 for (let i = 0; i < N; i++) {
90 const u = (i + 0.5) / N;
91 tri[i] = u < pluck ? u / pluck : (1 - u) / (1 - pluck);
92 }
93 const w = Math.max(1, Math.round(N / 25));
94 const line = new Float32Array(N);
95 for (let i = 0; i < N; i++) {
96 let acc = 0;
97 for (let k = -w; k <= w; k++) acc += tri[(i + k + N) % N];
98 line[i] = acc / (2 * w + 1);
99 }
100 let mean = 0;
101 for (let i = 0; i < N; i++) { line[i] += 0.02 * (Math.random() * 2 - 1); mean += line[i] / N; }
102 for (let i = 0; i < N; i++) line[i] -= mean;
103 let pos = 0;
104 let y1 = 0;
105 let y2 = 0;
106 let apIn = 0;
107 let apOut = 0;
108 for (let n = 0; n < len; n++) {
109 const y = line[pos];
110 const lp = 0.25 * y + 0.5 * y1 + 0.25 * y2;
111 y2 = y1;
112 y1 = y;
113 const ap = c * lp + apIn - c * apOut;
114 apIn = lp;
115 apOut = ap;
116 line[pos] = g * ap;
117 pos = (pos + 1) % N;
118 out[n] = y;
119 }
120 return out;
123// Decaying sinusoids. partials: [ratio, amplitude, t60 as a fraction of the
124// fundamental's t60]; tremolo: { rate (Hz), depth }. Partials past 0.45 of
125// the sample rate are left out.
126function modal(sr, freq, t60, partials, { tremolo } = {}) {
127 const len = Math.ceil(sr * t60);
128 const out = new Float32Array(len);
129 for (const [ratio, amp, frac] of partials) {
130 if (ratio * freq > 0.45 * sr) continue;
131 const w = (2 * Math.PI * ratio * freq) / sr;
132 const k = -6.9 / (frac * t60 * sr);
133 for (let n = 0; n < len; n++) out[n] += amp * Math.sin(w * n) * Math.exp(k * n);
134 }
135 if (tremolo) {
136 const w = (2 * Math.PI * tremolo.rate) / sr;
137 for (let n = 0; n < len; n++) out[n] *= 1 - tremolo.depth * (0.5 - 0.5 * Math.cos(w * n));
138 }
139 return out;
142// Two-operator FM (a soft electric piano): the modulator at the pitch, its
143// index fading from about 1.4 to 0.15, so the tone mellows as it rings.
144function fmPiano(sr, freq, t60) {
145 const len = Math.ceil(sr * t60);
146 const out = new Float32Array(len);
147 const w = (2 * Math.PI * freq) / sr;
148 const k = -6.9 / (t60 * sr);
149 const kIndex = -1 / (Math.min(0.25, 0.4 * t60) * sr);
150 for (let n = 0; n < len; n++) {
151 const index = 1.25 * Math.exp(kIndex * n) + 0.15;
152 out[n] = Math.sin(w * n + index * Math.sin(w * n)) * Math.exp(k * n);
153 }
154 return out;
157// The voices, in the order orbits take them. attack: s (raised cosine);
158// render(sr, freq, t60).
159export const VOICES = [
160 { name: 'Harp', attack: 0.004, render: (sr, f, t) => string(sr, f, t) },
161 { name: 'Marimba', attack: 0.002, render: (sr, f, t) => modal(sr, f, t, [[1, 1, 1], [3.93, 0.25, 0.3], [9.2, 0.08, 0.12]]) },
162 { name: 'Vibraphone', attack: 0.003, render: (sr, f, t) => modal(sr, f, t, [[1, 1, 1], [4, 0.15, 0.35], [10, 0.04, 0.1]], { tremolo: { rate: 5, depth: 0.35 } }) },
163 { name: 'Electric piano', attack: 0.003, render: fmPiano },
164 { name: 'Music box', attack: 0.001, render: (sr, f, t) => modal(sr, f, t, [[1, 1, 1], [5.4, 0.2, 0.3], [11.3, 0.06, 0.12]]) },
165 { name: 'Ocarina', attack: 0.035, render: (sr, f, t) => modal(sr, f, t, [[1, 1, 1], [2, 0.15, 0.8], [3, 0.05, 0.6]]) },
166 { name: 'Pizzicato', attack: 0.003, render: (sr, f, t) => string(sr, f, t, { pluck: 0.25 }) },
167 { name: 'Kalimba', attack: 0.0015, render: (sr, f, t) => modal(sr, f, t, [[1, 1, 1], [2, 0.06, 0.3], [6.27, 0.18, 0.12]]) },
168];
170// A biquad filter applied to x, in place: [b0, b1, b2, a1, a2] (a0 = 1).
171function biquad(x, [b0, b1, b2, a1, a2]) {
172 let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
173 for (let n = 0; n < x.length; n++) {
174 const y = b0 * x[n] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2;
175 x2 = x1; x1 = x[n]; y2 = y1; y1 = y;
176 x[n] = y;
177 }
180// The K-weighting of ITU-R BS.1770 at sample rate sr (its two stages, from
181// their analog prototypes): a high shelf, then a high-pass.
182function kWeighting(sr) {
183 let K = Math.tan((Math.PI * 1681.974450955533) / sr);
184 const Q1 = 0.7071752369554196;
185 const Vh = 10 ** (3.999843853973347 / 20);
186 const Vb = Vh ** 0.4996667741545416;
187 let a0 = 1 + K / Q1 + K * K;
188 const shelf = [(Vh + (Vb * K) / Q1 + K * K) / a0, (2 * (K * K - Vh)) / a0, (Vh - (Vb * K) / Q1 + K * K) / a0, (2 * (K * K - 1)) / a0, (1 - K / Q1 + K * K) / a0];
189 K = Math.tan((Math.PI * 38.13547087602444) / sr);
190 const Q2 = 0.5003270373238773;
191 a0 = 1 + K / Q2 + K * K;
192 const highpass = [1, -2, 1, (2 * (K * K - 1)) / a0, (1 - K / Q2 + K * K) / a0];
193 return [shelf, highpass];
196// The K-weighted RMS of x (BS.1770's measure of loudness, without gating).
197function loudness(x, sr) {
198 const y = Float32Array.from(x);
199 for (const stage of kWeighting(sr)) biquad(y, stage);
200 let ss = 0;
201 for (let n = 0; n < y.length; n++) ss += y[n] * y[n];
202 return Math.sqrt(ss / y.length);
205// A voice's note at freq ringing for t60 s, as an AudioBuffer: with its
206// attack and a short fade at the end, matched in loudness.
207export function renderNote(ctx, voice, freq, t60) {
208 const sr = ctx.sampleRate;
209 const out = voice.render(sr, freq, t60);
210 const att = Math.max(1, Math.floor(voice.attack * sr));
211 const fade = Math.min(Math.floor(0.05 * sr), Math.floor(out.length / 4));
212 for (let n = 0; n < out.length; n++) {
213 const a = n < att ? 0.5 - 0.5 * Math.cos((Math.PI * n) / att) : 1;
214 out[n] *= a * Math.min(1, (out.length - n) / fade);
215 }
216 const onset = out.subarray(0, Math.min(out.length, Math.floor(LOUD_WINDOW * sr)));
217 const scale = LOUDNESS / (loudness(onset, sr) + 1e-12);
218 for (let n = 0; n < out.length; n++) out[n] *= scale;
219 const buf = ctx.createBuffer(1, out.length, sr);
220 buf.copyToChannel(out, 0);
221 return buf;
224// An exponentially decaying stereo noise tail, for the reverb.
225function reverbImpulse(ctx, seconds = 1.6) {
226 const len = Math.floor(ctx.sampleRate * seconds);
227 const buf = ctx.createBuffer(2, len, ctx.sampleRate);
228 for (let ch = 0; ch < 2; ch++) {
229 const data = buf.getChannelData(ch);
230 // noise, low-passed (about 2 kHz) so the tail is warm, not hissy
231 let lp = 0;
232 for (let n = 0; n < len; n++) {
233 lp += 0.25 * (Math.random() * 2 - 1 - lp);
234 data[n] = lp * Math.exp((-6.9 * n) / len);
235 }
236 }
237 return buf;
240// The audio worklet that records the output: stereo frames, posted in blocks
241// of 8192 (and what is left when told to stop).
242const CAPTURE_WORKLET = `
243class CaptureTap extends AudioWorkletProcessor {
244 constructor() {
245 super();
246 this.n = 0;
247 this.l = new Float32Array(8192);
248 this.r = new Float32Array(8192);
249 this.done = false;
250 this.port.onmessage = () => { this.post(true); this.done = true; };
251 }
252 post(last) {
253 this.port.postMessage({ l: this.l.slice(0, this.n), r: this.r.slice(0, this.n), last });
254 this.n = 0;
255 }
256 process(inputs) {
257 if (this.done) return false;
258 const ch = inputs[0];
259 if (ch.length) {
260 const a = ch[0], b = ch[1] || ch[0];
261 for (let i = 0; i < a.length; i++) {
262 this.l[this.n] = a[i];
263 this.r[this.n] = b[i];
264 if (++this.n === this.l.length) this.post(false);
265 }
266 }
267 return true;
268 }
270registerProcessor('capture-tap', CaptureTap);
271`;
273export function createSynth() {
274 const ctx = new AudioContext();
275 const master = ctx.createGain();
276 const limiter = ctx.createDynamicsCompressor();
277 limiter.threshold.value = -6;
278 limiter.knee.value = 6;
279 limiter.ratio.value = 12;
280 limiter.attack.value = 0.003;
281 limiter.release.value = 0.2;
282 const tone = ctx.createBiquadFilter(); // a soft roll-off of the highs
283 tone.type = 'lowpass';
284 tone.frequency.value = 3500;
285 tone.Q.value = 0.5;
286 const dry = ctx.createGain();
287 const wet = ctx.createGain();
288 wet.gain.value = 0.45;
289 const reverb = ctx.createConvolver();
290 reverb.buffer = reverbImpulse(ctx);
291 tone.connect(dry);
292 dry.connect(master);
293 dry.connect(reverb).connect(wet).connect(master);
294 master.connect(limiter).connect(ctx.destination);
295 // rendered notes, per voice, sustain and pitch
296 const cache = new Map();
297 // per track: its gain (the track's volume) and its notes still sounding,
298 // oldest first; past MAX_SOUNDING the oldest is faded out, so fast tempos
299 // with long sustains stay light (at 16 notes/s, 64 notes is 4 s)
300 const MAX_SOUNDING = 64;
301 const tracks = new Map();
302 const track = (id) => {
303 let tr = tracks.get(id);
304 if (!tr) {
305 const gain = ctx.createGain();
306 gain.connect(tone);
307 tr = { gain, sounding: [] };
308 tracks.set(id, tr);
309 }
310 return tr;
311 };
312 // per SoundFont instrument, its loudness match (at velocity 100 near middle C)
313 const sfGains = new WeakMap();
314 const sfGain = (inst) => {
315 if (!sfGains.has(inst)) {
316 const { x, rate } = inst.reference(100, LOUD_WINDOW);
317 sfGains.set(inst, LOUDNESS / (loudness(x, rate) + 1e-12));
318 }
319 return sfGains.get(inst);
320 };
322 return {
323 ctx,
324 // the master volume
325 setVolume(v) { master.gain.setTargetAtTime(v, ctx.currentTime, 0.02); },
326 // the output as heard (after the master volume and limiter), as a
327 // MediaStream, for recording
328 stream() {
329 if (!this.tap) {
330 this.tap = ctx.createMediaStreamDestination();
331 limiter.connect(this.tap);
332 }
333 return this.tap.stream;
334 },
335 // Record the output as heard, sample for sample: onData(left, right)
336 // gets Float32Arrays of frames as they come (at ctx.sampleRate).
337 // Resolves to stop(), which resolves once the last frames are in.
338 async capture(onData) {
339 if (!this.tapModule) {
340 const url = URL.createObjectURL(new Blob([CAPTURE_WORKLET], { type: 'text/javascript' }));
341 this.tapModule = ctx.audioWorklet.addModule(url).finally(() => URL.revokeObjectURL(url));
342 }
343 await this.tapModule;
344 const node = new AudioWorkletNode(ctx, 'capture-tap', {
345 numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [1],
346 channelCount: 2, channelCountMode: 'explicit', channelInterpretation: 'speakers',
347 });
348 // (an output to the destination, silent, so the node is pulled)
349 const mute = ctx.createGain();
350 mute.gain.value = 0;
351 limiter.connect(node);
352 node.connect(mute).connect(ctx.destination);
353 let finish;
354 const finished = new Promise((r) => { finish = r; });
355 node.port.onmessage = (e) => {
356 if (e.data.l.length) onData(e.data.l, e.data.r);
357 if (e.data.last) finish();
358 };
359 return async () => {
360 node.port.postMessage('stop');
361 // (a suspended context sends nothing more)
362 await Promise.race([finished, new Promise((r) => setTimeout(r, 1000))]);
363 limiter.disconnect(node);
364 node.disconnect();
365 mute.disconnect();
366 };
367 },
368 // a track's volume (its notes, sounding and to come)
369 setTrackVolume(id, v) { track(id).gain.gain.setTargetAtTime(v, ctx.currentTime, 0.02); },
370 // a track removed: its notes fade out
371 removeTrack(id) {
372 const tr = tracks.get(id);
373 if (!tr) return;
374 tracks.delete(id);
375 for (const n of tr.sounding) n.stop(ctx.currentTime);
376 setTimeout(() => tr.gain.disconnect(), 200);
377 },
378 // a note on track `id` of `voice` (an index into VOICES, or a SoundFont
379 // instrument from makeInstrument, played at MIDI velocity vel) at freq,
380 // at time `when` (the context's clock), panned by pan in [-1, 1], at
381 // level gain; the built-in voices ring for `sustain` s; mono: the track's
382 // notes still sounding fade out as it starts
383 play(id, voice, freq, when, { pan = 0, gain = 1, sustain = SUSTAIN.default, vel = 100, mono = false } = {}) {
384 const tr = track(id);
385 const level = ctx.createGain();
386 const panner = ctx.createStereoPanner();
387 panner.pan.value = pan;
388 level.connect(panner).connect(tr.gain);
389 const t = Math.max(when, ctx.currentTime);
390 let sound; // { end, stop(at): end it at `at` }
391 if (typeof voice !== 'number') {
392 level.gain.value = gain * sfGain(voice);
393 sound = voice.play(ctx, 69 + 12 * Math.log2(freq / 440), vel, t, level);
394 } else {
395 const key = `${voice}:${sustain.toFixed(2)}:${Math.round(freq * 10)}`;
396 let buf = cache.get(key);
397 if (!buf) {
398 buf = renderNote(ctx, VOICES[voice], freq, sustain);
399 if (cache.size > 800) cache.clear();
400 cache.set(key, buf);
401 }
402 const src = ctx.createBufferSource();
403 src.buffer = buf;
404 level.gain.value = gain;
405 src.connect(level);
406 src.start(t);
407 sound = { end: t + buf.duration, stop: (at) => src.stop(at) };
408 }
409 // a note stopped at `at` (perhaps still to come) fades out over 40 ms
410 // (its level is steady, so the ramp starts from where it is)
411 const note = {
412 start: t,
413 end: sound.end,
414 stop(at) {
415 if (at >= this.end) return;
416 level.gain.setValueAtTime(level.gain.value, Math.max(at, ctx.currentTime));
417 level.gain.linearRampToValueAtTime(0, Math.max(at, ctx.currentTime) + 0.04);
418 sound.stop(Math.max(at, ctx.currentTime) + 0.05);
419 this.end = Math.min(this.end, at + 0.05);
420 },
421 };
422 const list = tr.sounding;
423 if (mono) {
424 for (const n of list) if (n.start < t) n.stop(t);
425 }
426 list.push(note);
427 // drop those that have finished by now, then fade the excess
428 while (list.length && list[0].end < ctx.currentTime) list.shift();
429 while (list.length > MAX_SOUNDING) list.shift().stop(t);
430 },
431 };
↑↓ move↵openescclose