a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 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
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 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
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 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.
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 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
46const OCTAVES = 3; // 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) {
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);
61}
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;
121}
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;
140}
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;
155}
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 }
178}
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];
194}
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);
203}
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;
222}
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;
238}
240export function createSynth() {
241 const ctx = new AudioContext();
242 const master = ctx.createGain();
243 const limiter = ctx.createDynamicsCompressor();
244 limiter.threshold.value = -6;
245 limiter.knee.value = 6;
246 limiter.ratio.value = 12;
247 limiter.attack.value = 0.003;
248 limiter.release.value = 0.2;
249 const tone = ctx.createBiquadFilter(); // a soft roll-off of the highs
250 tone.type = 'lowpass';
251 tone.frequency.value = 3500;
252 tone.Q.value = 0.5;
253 const dry = ctx.createGain();
254 const wet = ctx.createGain();
255 wet.gain.value = 0.45;
256 const reverb = ctx.createConvolver();
257 reverb.buffer = reverbImpulse(ctx);
258 tone.connect(dry);
259 dry.connect(master);
260 dry.connect(reverb).connect(wet).connect(master);
261 master.connect(limiter).connect(ctx.destination);
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 262 // rendered notes, per voice, sustain and pitch
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 263 const cache = new Map();
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 264 // per track: its gain (the track's volume) and its notes still sounding,
265 // oldest first; past MAX_SOUNDING the oldest is faded out, so fast tempos
266 // with long sustains stay light (at 16 notes/s, 64 notes is 4 s)
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 267 const MAX_SOUNDING = 64;
269 const track = (id) => {
270 let tr = tracks.get(id);
271 if (!tr) {
272 const gain = ctx.createGain();
273 gain.connect(tone);
274 tr = { gain, sounding: [] };
275 tracks.set(id, tr);
276 }
277 return tr;
278 };
279 // per SoundFont instrument, its loudness match (at velocity 100 near middle C)
280 const sfGains = new WeakMap();
281 const sfGain = (inst) => {
282 if (!sfGains.has(inst)) {
283 const { x, rate } = inst.reference(100, LOUD_WINDOW);
284 sfGains.set(inst, LOUDNESS / (loudness(x, rate) + 1e-12));
285 }
286 return sfGains.get(inst);
287 };
289 return {
290 ctx,
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 292 setVolume(v) { master.gain.setTargetAtTime(v, ctx.currentTime, 0.02); },
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 293 // the output as heard (after the master volume and limiter), as a
294 // MediaStream, for recording
295 stream() {
296 if (!this.tap) {
297 this.tap = ctx.createMediaStreamDestination();
298 limiter.connect(this.tap);
301 },
302 // a track's volume (its notes, sounding and to come)
303 setTrackVolume(id, v) { track(id).gain.gain.setTargetAtTime(v, ctx.currentTime, 0.02); },
304 // a track removed: its notes fade out
305 removeTrack(id) {
306 const tr = tracks.get(id);
307 if (!tr) return;
308 tracks.delete(id);
309 for (const n of tr.sounding) n.stop(ctx.currentTime);
310 setTimeout(() => tr.gain.disconnect(), 200);
311 },
312 // a note on track `id` of `voice` (an index into VOICES, or a SoundFont
313 // instrument from makeInstrument, played at MIDI velocity vel) at freq,
314 // at time `when` (the context's clock), panned by pan in [-1, 1], at
315 // level gain; the built-in voices ring for `sustain` s
316 play(id, voice, freq, when, { pan = 0, gain = 1, sustain = SUSTAIN.default, vel = 100 } = {}) {
317 const tr = track(id);
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 318 const level = ctx.createGain();
319 const panner = ctx.createStereoPanner();
320 panner.pan.value = pan;
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 321 level.connect(panner).connect(tr.gain);
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 322 const t = Math.max(when, ctx.currentTime);
324 if (typeof voice !== 'number') {
325 level.gain.value = gain * sfGain(voice);
326 note = voice.play(ctx, 69 + 12 * Math.log2(freq / 440), vel, t, level);
327 } else {
328 const key = `${voice}:${sustain.toFixed(2)}:${Math.round(freq * 10)}`;
329 let buf = cache.get(key);
330 if (!buf) {
331 buf = renderNote(ctx, VOICES[voice], freq, sustain);
332 if (cache.size > 800) cache.clear();
333 cache.set(key, buf);
334 }
335 const src = ctx.createBufferSource();
336 src.buffer = buf;
337 level.gain.value = gain;
338 src.connect(level);
339 src.start(t);
340 note = {
341 end: t + buf.duration,
342 stop(at) {
343 level.gain.setValueAtTime(level.gain.value, at);
344 level.gain.linearRampToValueAtTime(0, at + 0.04);
345 src.stop(at + 0.05);
346 },
347 };
348 }
349 const list = tr.sounding;
350 list.push(note);
a1f5e15Islands in a sea of chaos: Duffing phase space with sonificationJeremy Magland 351 // drop those that have finished by now, then fade the excess
352 while (list.length && list[0].end < ctx.currentTime) list.shift();
574ea55Tracks, SoundFonts, sessions, recording and MIDIJeremy Magland 353 while (list.length > MAX_SOUNDING) list.shift().stop(t);
355 };
356}