@zeeuw/riff 0.0.0-stage → 0.1.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +46 -2
- package/data/registry-data.js +3 -0
- package/data/signatures.js +3 -0
- package/docs/clean-room.md +450 -0
- package/package.json +69 -4
- package/src/audio/clock.js +383 -0
- package/src/audio/engine.js +678 -0
- package/src/audio/index.js +394 -0
- package/src/audio/offline.js +73 -0
- package/src/audio/params.js +397 -0
- package/src/audio/samples.js +274 -0
- package/src/audio/unlock.js +70 -0
- package/src/audio/voices.js +44 -0
- package/src/combinators.js +150 -0
- package/src/compat.js +16 -0
- package/src/constructors.js +236 -0
- package/src/controls.js +199 -0
- package/src/draw.js +252 -0
- package/src/euclid.js +57 -0
- package/src/evaluate.js +251 -0
- package/src/extras/check.js +678 -0
- package/src/extras/describe.js +433 -0
- package/src/extras/editor.js +369 -0
- package/src/extras/index.js +10 -0
- package/src/fraction.js +300 -0
- package/src/hap.js +64 -0
- package/src/helpers.js +68 -0
- package/src/index.js +74 -0
- package/src/mini/index.js +36 -0
- package/src/mini/parser.js +400 -0
- package/src/ops.js +293 -0
- package/src/outline.js +175 -0
- package/src/pattern.js +365 -0
- package/src/random.js +344 -0
- package/src/register.js +83 -0
- package/src/registry.js +52 -0
- package/src/samples.js +14 -0
- package/src/sampling.js +123 -0
- package/src/scope.js +77 -0
- package/src/signals.js +76 -0
- package/src/stepwise.js +150 -0
- package/src/structure.js +636 -0
- package/src/time.js +70 -0
- package/src/tonal.js +583 -0
- package/src/transforms.js +125 -0
- package/src/transpile.js +394 -0
- package/src/util.js +80 -0
- package/src/visuals.js +216 -0
|
@@ -0,0 +1,678 @@
|
|
|
1
|
+
// Web Audio output (plan 4.3-4.5): synth and sample voices, the per-voice
|
|
2
|
+
// effect chain, per-orbit delay and reverb, analysers. One engine per
|
|
3
|
+
// AudioContext. Graph per voice:
|
|
4
|
+
// source(s) → envelope → [lpf] → [hpf] → [bpf] → amp → pan → [crush]
|
|
5
|
+
// → [shape] → [distort] → [post] → orbit dry, delay send, reverb send,
|
|
6
|
+
// [analyser tap]. The shapers sit after the level and the panner: their
|
|
7
|
+
// curves act on the signal at its playing level (spec/sound.md 6).
|
|
8
|
+
// orbit → master → limiter → destination (plan 8.4; limiter: false skips it).
|
|
9
|
+
import {
|
|
10
|
+
voiceParams, envelopePoints, shaperCurve, limiterCurve, unusedControls, LEVEL,
|
|
11
|
+
voiceDetune, wideGain, noiseMix, crackleSamples, fmPhase, fmIndex, fmSamples,
|
|
12
|
+
vowelFormants, phaserParams, phaserWave, tremoloParams, tremoloCurve,
|
|
13
|
+
} from './params.js';
|
|
14
|
+
import { VoicePool } from './voices.js';
|
|
15
|
+
import { controlKeys } from '../controls.js';
|
|
16
|
+
|
|
17
|
+
let controlNames = null; // value keys of every registered control, made on first use
|
|
18
|
+
|
|
19
|
+
const FADE = 0.01; // s, fade for stolen, cut and hushed voices
|
|
20
|
+
const REVERBS = 4; // convolvers kept per orbit (one per room size)
|
|
21
|
+
|
|
22
|
+
// Get or make `key` in a Map kept to `max` entries, least recently used out.
|
|
23
|
+
const lru = (map, key, make, max) => {
|
|
24
|
+
let v = map.get(key);
|
|
25
|
+
if (v === undefined) { v = make(); if (map.size >= max) map.delete(map.keys().next().value); } else map.delete(key);
|
|
26
|
+
map.set(key, v);
|
|
27
|
+
return v;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
// Master safety limiter (plan 8.4): a static soft clipper (limiterCurve).
|
|
31
|
+
// Mixes peaking below -3 dBFS pass bit-for-bit; louder peaks bend smoothly
|
|
32
|
+
// toward 0 dBFS (up to +12 dBFS input) instead of clipping. No lookahead, so
|
|
33
|
+
// no added latency (decisions, p2-sound).
|
|
34
|
+
export const LIMITER = Object.freeze({ threshold: -3, range: 4 });
|
|
35
|
+
|
|
36
|
+
// sampleSource: { getBuffer({ s, n, bank, note, freq }) →
|
|
37
|
+
// Promise<AudioBuffer | { buffer, playbackRate } | null>, has(s, bank)?,
|
|
38
|
+
// resolve(controls)? → { rate } }. The sample loader (src/audio/samples.js,
|
|
39
|
+
// plan 4.2) is the default; its resolve().rate pitches the buffer. Without
|
|
40
|
+
// resolve, a pitched hap is re-pitched from c3 = MIDI 48 (spec/samples.md 5).
|
|
41
|
+
// Options: maxVoices (cap, 128; invalid → 128), log, sampleSource, limiter,
|
|
42
|
+
// sampleDeadline (s, 0.5: a sample decoded after its onset still plays at
|
|
43
|
+
// once when at most this late), warnUnused (true: log once per control name
|
|
44
|
+
// that reaches the engine but has no effect, docs/improvements.md 15).
|
|
45
|
+
// Hap values are only read, never written (docs/improvements.md 12).
|
|
46
|
+
export class AudioEngine {
|
|
47
|
+
constructor(ctx, { maxVoices = 128, log = console.warn, sampleSource = null, limiter = true, sampleDeadline = 0.5, warnUnused = true } = {}) {
|
|
48
|
+
this.ctx = ctx;
|
|
49
|
+
this.log = log;
|
|
50
|
+
const d = Number(sampleDeadline);
|
|
51
|
+
this.sampleDeadline = Number.isFinite(d) && d >= 0 ? d : 0.5;
|
|
52
|
+
this.warnUnused = warnUnused !== false;
|
|
53
|
+
this.sampleSource = sampleSource;
|
|
54
|
+
this.pool = new VoicePool(maxVoices);
|
|
55
|
+
this.analysers = new Map();
|
|
56
|
+
this.curves = new Map();
|
|
57
|
+
this.impulses = new Map();
|
|
58
|
+
this.noise = new Map();
|
|
59
|
+
this.fm = new Map();
|
|
60
|
+
this.lfos = new Map(); // phaser LFOs, one running oscillator per rate
|
|
61
|
+
this.trem = new Map(); // tremolo gain periods
|
|
62
|
+
this.reversed = new WeakMap();
|
|
63
|
+
this.warned = new Set();
|
|
64
|
+
this.generation = 0;
|
|
65
|
+
this.voiceCount = 0; // seeds the per-voice random draws (noise offset, phases, crackle)
|
|
66
|
+
this.limiter = null;
|
|
67
|
+
this.limiting = limiter !== false;
|
|
68
|
+
this.makeOutput();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
makeOutput() {
|
|
72
|
+
this.master = this.ctx.createGain();
|
|
73
|
+
this.master.connect(this.output());
|
|
74
|
+
this.orbits = new Map();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Where the master goes: the limiter (made once) or the destination.
|
|
78
|
+
output() {
|
|
79
|
+
if (!this.limiting || typeof this.ctx.createWaveShaper !== 'function') return this.ctx.destination;
|
|
80
|
+
if (!this.limiter) {
|
|
81
|
+
const l = this.ctx.createGain();
|
|
82
|
+
l.gain.value = 1 / LIMITER.range;
|
|
83
|
+
const sh = this.ctx.createWaveShaper();
|
|
84
|
+
sh.curve = limiterCurve(LIMITER.threshold, LIMITER.range);
|
|
85
|
+
l.connect(sh);
|
|
86
|
+
sh.connect(this.ctx.destination);
|
|
87
|
+
this.limiter = l;
|
|
88
|
+
this.limiterShaper = sh;
|
|
89
|
+
}
|
|
90
|
+
return this.limiter;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Turn the master limiter on or off while playing.
|
|
94
|
+
setLimiter(on) {
|
|
95
|
+
this.limiting = on !== false;
|
|
96
|
+
try { this.master.disconnect(); } catch { /* not connected */ }
|
|
97
|
+
this.master.connect(this.output());
|
|
98
|
+
return this.limiting;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Crossfade on a pattern swap (plan 8.5): voices that started before
|
|
102
|
+
// \`time\` and still sound after it fade out over \`fade\` seconds.
|
|
103
|
+
fadeOut(time, fade = FADE) {
|
|
104
|
+
let n = 0;
|
|
105
|
+
for (const v of [...this.pool.voices]) {
|
|
106
|
+
if (v.start < time && v.end > time) { this.pool.remove(v); v.stop(time, fade); n++; }
|
|
107
|
+
}
|
|
108
|
+
return n;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
warnOnce(key, msg) {
|
|
112
|
+
if (this.warned.has(key)) return;
|
|
113
|
+
this.warned.add(key);
|
|
114
|
+
this.log(msg);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// The analyser for `id`: created on first use, the same node afterwards.
|
|
118
|
+
analyser(id) {
|
|
119
|
+
const key = String(id);
|
|
120
|
+
let a = this.analysers.get(key);
|
|
121
|
+
if (!a) {
|
|
122
|
+
a = this.ctx.createAnalyser();
|
|
123
|
+
a.fftSize = 2048;
|
|
124
|
+
this.analysers.set(key, a);
|
|
125
|
+
}
|
|
126
|
+
return a;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
orbit(n) {
|
|
130
|
+
let o = this.orbits.get(n);
|
|
131
|
+
if (o) return o;
|
|
132
|
+
const c = this.ctx;
|
|
133
|
+
// Dry voices go straight to the master. Delay: sends → delay ⇄
|
|
134
|
+
// feedback → master.
|
|
135
|
+
o = { delay: c.createDelay(10), feedback: c.createGain() };
|
|
136
|
+
o.delay.connect(o.feedback);
|
|
137
|
+
o.feedback.connect(o.delay);
|
|
138
|
+
o.delay.connect(this.master);
|
|
139
|
+
// Reverb: send → convolver per room size (reverb()) → master.
|
|
140
|
+
o.reverbs = new Map();
|
|
141
|
+
this.orbits.set(n, o);
|
|
142
|
+
return o;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Exponentially decaying stereo noise, `size` seconds long. Seeded LCG so
|
|
146
|
+
// the same size always gives the same impulse.
|
|
147
|
+
impulse(size) {
|
|
148
|
+
const key = Math.round(size * 100) / 100;
|
|
149
|
+
return lru(this.impulses, key, () => {
|
|
150
|
+
const rate = this.ctx.sampleRate;
|
|
151
|
+
const len = Math.max(1, Math.floor(rate * key));
|
|
152
|
+
const b = this.ctx.createBuffer(2, len, rate);
|
|
153
|
+
let seed = 0x2545f491;
|
|
154
|
+
for (let ch = 0; ch < 2; ch++) {
|
|
155
|
+
const d = b.getChannelData(ch);
|
|
156
|
+
for (let i = 0; i < len; i++) {
|
|
157
|
+
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
|
|
158
|
+
const t = i / len;
|
|
159
|
+
d[i] = ((seed / 2 ** 32) * 2 - 1) * (1 - t) ** 2 * Math.exp(-4 * t);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return b;
|
|
163
|
+
}, 8);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// The convolver for room `size` on orbit `o`: one per size, so a voice with
|
|
167
|
+
// another size never swaps the impulse under a sounding tail. Past REVERBS
|
|
168
|
+
// per orbit, least recently used ones whose tail has decayed are dropped.
|
|
169
|
+
reverb(o, size, end) {
|
|
170
|
+
const key = Math.round(size * 100) / 100;
|
|
171
|
+
let r = o.reverbs.get(key);
|
|
172
|
+
if (r) o.reverbs.delete(key);
|
|
173
|
+
else {
|
|
174
|
+
for (const [k, x] of o.reverbs) if (o.reverbs.size >= REVERBS && x.until < this.ctx.currentTime) { x.node.disconnect(); o.reverbs.delete(k); }
|
|
175
|
+
r = { node: this.ctx.createConvolver(), until: 0 };
|
|
176
|
+
r.node.buffer = this.impulse(size);
|
|
177
|
+
r.node.connect(this.master);
|
|
178
|
+
}
|
|
179
|
+
r.until = Math.max(r.until, end + key);
|
|
180
|
+
o.reverbs.set(key, r);
|
|
181
|
+
return r.node;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// A shared bus parameter: written only when it changes, then ramped over
|
|
185
|
+
// 15 ms from the old value (the first value is set at once).
|
|
186
|
+
setBus(o, key, param, v, time) {
|
|
187
|
+
const old = o[key];
|
|
188
|
+
if (old === v) return;
|
|
189
|
+
o[key] = v;
|
|
190
|
+
if (old === undefined) param.setValueAtTime(v, time);
|
|
191
|
+
else { param.setValueAtTime(old, time); param.linearRampToValueAtTime(v, time + 0.015); }
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// 2 s noise loop. Generated 10 ms longer, detrended (least-squares line
|
|
195
|
+
// out: no DC, no drift), and the last 10 ms crossfade (equal power) into
|
|
196
|
+
// the extra samples made just before the start: no click at the wrap.
|
|
197
|
+
noiseBuffer(color) {
|
|
198
|
+
let b = this.noise.get(color);
|
|
199
|
+
if (b) return b;
|
|
200
|
+
const rate = this.ctx.sampleRate;
|
|
201
|
+
const len = Math.floor(rate * 2), x = Math.min(len >> 1, Math.round(rate / 100)), n = len + x;
|
|
202
|
+
const d = new Float64Array(n);
|
|
203
|
+
let seed = 0x9e3779b9;
|
|
204
|
+
const rnd = () => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return (seed / 2 ** 32) * 2 - 1; };
|
|
205
|
+
let last = 0;
|
|
206
|
+
const p = [0, 0, 0, 0, 0, 0, 0];
|
|
207
|
+
for (let i = 0; i < n; i++) {
|
|
208
|
+
const w = rnd();
|
|
209
|
+
if (color === 'brown') { last = (last + 0.02 * w) / 1.02; d[i] = last * 0.9; }
|
|
210
|
+
else if (color === 'pink') {
|
|
211
|
+
// Sum of leaky integrators at spread corner frequencies.
|
|
212
|
+
p[0] = 0.99886 * p[0] + w * 0.0555179; p[1] = 0.99332 * p[1] + w * 0.0750759;
|
|
213
|
+
p[2] = 0.969 * p[2] + w * 0.153852; p[3] = 0.8665 * p[3] + w * 0.3104856;
|
|
214
|
+
p[4] = 0.55 * p[4] + w * 0.5329522; p[5] = -0.7616 * p[5] - w * 0.016898;
|
|
215
|
+
d[i] = (p[0] + p[1] + p[2] + p[3] + p[4] + p[5] + p[6] + w * 0.5362) * 0.11;
|
|
216
|
+
p[6] = w * 0.115926;
|
|
217
|
+
} else d[i] = w;
|
|
218
|
+
}
|
|
219
|
+
let sy = 0, sxy = 0;
|
|
220
|
+
for (let i = 0; i < n; i++) { sy += d[i]; sxy += i * d[i]; }
|
|
221
|
+
const m = (n - 1) / 2, k = (sxy - m * sy) / ((n * (n * n - 1)) / 12);
|
|
222
|
+
for (let i = 0; i < n; i++) d[i] -= sy / n + k * (i - m);
|
|
223
|
+
b = this.ctx.createBuffer(1, len, rate);
|
|
224
|
+
const o = b.getChannelData(0);
|
|
225
|
+
o.set(d.subarray(x));
|
|
226
|
+
for (let i = 0, j = len - x; i < x; i++, j++) {
|
|
227
|
+
const w = ((i + 0.5) / x) * (Math.PI / 2);
|
|
228
|
+
o[j] = o[j] * Math.cos(w) + d[i] * Math.sin(w);
|
|
229
|
+
}
|
|
230
|
+
this.noise.set(color, b);
|
|
231
|
+
return b;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// A seeded random source for the next voice: renders repeat exactly, but
|
|
235
|
+
// successive voices differ (noise segment, supersaw phases, crackle).
|
|
236
|
+
voiceRandom() {
|
|
237
|
+
let seed = (Math.imul(++this.voiceCount, 0x9e3779b1) ^ 0x5bd1e995) >>> 0;
|
|
238
|
+
return () => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return seed / 2 ** 32; };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
curve(kind, amount) {
|
|
242
|
+
return lru(this.curves, `${kind}:${amount}`, () => shaperCurve(kind, amount), 64);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Plays one scheduler trigger. Returns the voice, a promise of it (sample
|
|
246
|
+
// still loading) or null.
|
|
247
|
+
playTrigger(trigger) {
|
|
248
|
+
if (this.warnUnused && trigger.value && typeof trigger.value === 'object') {
|
|
249
|
+
controlNames ??= new Set(controlKeys.values());
|
|
250
|
+
for (const k of unusedControls(trigger.value, controlNames)) {
|
|
251
|
+
this.warnOnce(`ctl:${k}`, `[riff] control "${k}" has no effect in RIFF's audio engine (kept for compatibility)`);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
const p = voiceParams(trigger.value, trigger.cps ?? 0.5);
|
|
255
|
+
if (p.kind === 'none') return null;
|
|
256
|
+
// An unknown vowel silences the event (spec/sound.md 14.1).
|
|
257
|
+
if (p.vowel !== undefined && !vowelFormants(p.vowel)) return null;
|
|
258
|
+
p.cycle = trigger.cycle ?? trigger.time * p.cps;
|
|
259
|
+
if (p.kind === 'synth') return this.startVoice(p, trigger.time, trigger.duration, this.synthSources(p, trigger.time, trigger.duration));
|
|
260
|
+
return this.playSample(p, trigger);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
playSample(p, trigger) {
|
|
264
|
+
const src = this.sampleSource;
|
|
265
|
+
if (!src || (typeof src.has === 'function' && !src.has(p.s, p.bank))) {
|
|
266
|
+
const name = p.bank ? `${p.bank}_${p.s}` : p.s;
|
|
267
|
+
this.warnOnce(`s:${name}`, `[riff] no sound "${name}": not a synth and not a loaded sample`);
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
const gen = this.generation;
|
|
271
|
+
const req = { s: p.s, n: p.n, bank: p.bank, note: p.pitched ? p.midi : undefined, freq: undefined };
|
|
272
|
+
return Promise.resolve(src.getBuffer(req)).then((res) => {
|
|
273
|
+
if (gen !== this.generation) return null; // hushed meanwhile
|
|
274
|
+
const buffer = res?.buffer ?? res;
|
|
275
|
+
if (!buffer || typeof buffer.getChannelData !== 'function') return null; // loader warned
|
|
276
|
+
// Pitch: the loader's resolve() rate (pitched maps, note shifts), else
|
|
277
|
+
// an object result's own rate, else c3 = MIDI 48 (spec/samples.md 5).
|
|
278
|
+
let rate;
|
|
279
|
+
if (res?.buffer) rate = res.playbackRate ?? 1;
|
|
280
|
+
else if (typeof src.resolve === 'function') rate = src.resolve(req)?.rate ?? 1;
|
|
281
|
+
else rate = p.pitched ? 2 ** ((p.midi - 36) / 12) : 1;
|
|
282
|
+
let time = trigger.time;
|
|
283
|
+
const now = this.ctx.currentTime;
|
|
284
|
+
if (time < now) {
|
|
285
|
+
if (now - time > this.sampleDeadline) { this.warnOnce(`late:${p.s}`, `[riff] sample "${p.s}" loaded too late to play`); return null; }
|
|
286
|
+
time = now + 0.01; // full attack, not an envelope in the past
|
|
287
|
+
}
|
|
288
|
+
return this.startVoice(p, time, trigger.duration, this.sampleSources(p, buffer, rate), true);
|
|
289
|
+
}, (err) => {
|
|
290
|
+
this.warnOnce(`err:${p.s}`, `[riff] sample "${p.s}" failed: ${err?.message ?? err}`);
|
|
291
|
+
return null;
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// → { nodes: [AudioScheduledSourceNode], out: AudioNode, length?, starts? }
|
|
296
|
+
// Gains fixed at 1 are left out: out is a source itself when it is alone.
|
|
297
|
+
// where length (s) is the natural sample length when it is not looped and
|
|
298
|
+
// starts[i] = [when, offset] overrides node i's start (time, sources.offset).
|
|
299
|
+
synthSources(p, time = 0, duration = 0) {
|
|
300
|
+
const c = this.ctx;
|
|
301
|
+
const nodes = [], starts = [], feeds = [];
|
|
302
|
+
// A summing gain only where it scales or several nodes meet.
|
|
303
|
+
const sum = (ns, v = 1) => {
|
|
304
|
+
if (ns.length === 1 && v === 1) return ns[0];
|
|
305
|
+
const g = c.createGain();
|
|
306
|
+
g.gain.value = v;
|
|
307
|
+
for (const n of ns) n.connect(g);
|
|
308
|
+
return g;
|
|
309
|
+
};
|
|
310
|
+
const rnd = this.voiceRandom();
|
|
311
|
+
const hold = p.clip !== undefined && p.clip >= 0 ? p.clip * duration : duration;
|
|
312
|
+
// Samples a computed voice needs (note, release, margin), at most 30 s; a
|
|
313
|
+
// longer voice loops its buffer.
|
|
314
|
+
const seconds = Math.min(30, Math.max(0.05, hold + Math.max(0.01, p.release ?? 0.01) + 0.05));
|
|
315
|
+
const buf = (data) => {
|
|
316
|
+
const b = c.createBuffer(1, data.length, c.sampleRate);
|
|
317
|
+
b.getChannelData(0).set(data);
|
|
318
|
+
return b;
|
|
319
|
+
};
|
|
320
|
+
const loop = (b) => {
|
|
321
|
+
const src = c.createBufferSource();
|
|
322
|
+
src.buffer = b;
|
|
323
|
+
src.loop = true;
|
|
324
|
+
return src;
|
|
325
|
+
};
|
|
326
|
+
if (p.wave === 'white' || p.wave === 'pink' || p.wave === 'brown') {
|
|
327
|
+
const src = c.createBufferSource();
|
|
328
|
+
src.buffer = this.noiseBuffer(p.wave);
|
|
329
|
+
src.loop = true;
|
|
330
|
+
// Each voice reads its own segment of the noise loop.
|
|
331
|
+
return { nodes: [src], out: src, starts: [[time, rnd() * src.buffer.duration]] };
|
|
332
|
+
}
|
|
333
|
+
if (p.wave === 'crackle') {
|
|
334
|
+
const len = Math.max(1, Math.round(seconds * c.sampleRate));
|
|
335
|
+
const src = loop(buf(crackleSamples(len, c.sampleRate, p.density, rnd)));
|
|
336
|
+
return { nodes: [src], out: src };
|
|
337
|
+
}
|
|
338
|
+
const wide = p.wave === 'supersaw' || p.wave === 'supersquare';
|
|
339
|
+
const type = p.wave === 'supersaw' ? 'sawtooth' : p.wave === 'supersquare' ? 'square' : p.wave;
|
|
340
|
+
const count = wide ? p.unison : 1;
|
|
341
|
+
// .noise(x): the oscillators fade, pink noise comes in (spec/sound.md 3).
|
|
342
|
+
const mix = p.noise > 0 ? noiseMix(p.noise) : null;
|
|
343
|
+
const level = (wide ? wideGain(count) : 1) * (mix ? mix.osc : 1), oscs = [];
|
|
344
|
+
if (mix) {
|
|
345
|
+
const n = c.createBufferSource();
|
|
346
|
+
n.buffer = this.noiseBuffer('pink');
|
|
347
|
+
n.loop = true;
|
|
348
|
+
const g = c.createGain();
|
|
349
|
+
g.gain.value = mix.noise;
|
|
350
|
+
n.connect(g);
|
|
351
|
+
feeds.push(g);
|
|
352
|
+
nodes.push(n);
|
|
353
|
+
starts.push([time, rnd() * n.buffer.duration]);
|
|
354
|
+
}
|
|
355
|
+
const index = p.fmi ? fmIndex(p) : null;
|
|
356
|
+
// FM on a single sine: computed exactly (the fold-over levels at fmh 1, 2
|
|
357
|
+
// and .5 depend on the start phase, spec/sound.md 7.1). Equal note
|
|
358
|
+
// parameters give equal samples: the buffer is shared (LRU).
|
|
359
|
+
if (index && type === 'sine' && count === 1) {
|
|
360
|
+
const len = Math.max(1, Math.round(seconds * c.sampleRate));
|
|
361
|
+
const key = [len, p.freq, p.fmh, p.fmi, p.fmattack, p.fmdecay, p.fmsustain, p.fmenv].join();
|
|
362
|
+
const src = loop(lru(this.fm, key, () => buf(fmSamples(len, c.sampleRate, p.freq, p.fmh, index, fmPhase(p.fmi, p.fmh))), 16));
|
|
363
|
+
nodes.push(src);
|
|
364
|
+
starts.push(undefined);
|
|
365
|
+
return { nodes, out: sum([sum([src], level), ...feeds]), starts };
|
|
366
|
+
}
|
|
367
|
+
let mod = null;
|
|
368
|
+
if (index) {
|
|
369
|
+
const mf = p.freq * p.fmh;
|
|
370
|
+
const osc = c.createOscillator();
|
|
371
|
+
osc.type = 'sine';
|
|
372
|
+
osc.frequency.value = mf;
|
|
373
|
+
mod = c.createGain();
|
|
374
|
+
mod.gain.value = p.fmi * mf;
|
|
375
|
+
// FM envelope: the index curve sampled every 5 ms over its ramps.
|
|
376
|
+
if (index(0) !== p.fmi || index(seconds) !== p.fmi) {
|
|
377
|
+
const end = Math.min(seconds, (p.fmattack ?? 0.001) + (p.fmdecay ?? 0.01));
|
|
378
|
+
mod.gain.setValueAtTime(index(0) * mf, time);
|
|
379
|
+
for (let t = 0.005; t < end; t += 0.005) mod.gain.linearRampToValueAtTime(index(t) * mf, time + t);
|
|
380
|
+
mod.gain.linearRampToValueAtTime(index(end) * mf, time + end);
|
|
381
|
+
}
|
|
382
|
+
osc.connect(mod);
|
|
383
|
+
nodes.push(osc);
|
|
384
|
+
starts.push(undefined);
|
|
385
|
+
}
|
|
386
|
+
// Wide synths spread their voices evenly across the stereo field; each
|
|
387
|
+
// voice starts at a random phase (started up to one period early, the
|
|
388
|
+
// envelope is still closed then).
|
|
389
|
+
const spread = count > 1 && typeof c.createStereoPanner === 'function';
|
|
390
|
+
for (let i = 0; i < count; i++) {
|
|
391
|
+
const osc = c.createOscillator();
|
|
392
|
+
osc.type = type;
|
|
393
|
+
osc.frequency.value = p.freq;
|
|
394
|
+
if (count > 1) osc.detune.value = voiceDetune(i, count, p.detune);
|
|
395
|
+
if (mod) mod.connect(osc.frequency);
|
|
396
|
+
if (spread) {
|
|
397
|
+
const pn = c.createStereoPanner();
|
|
398
|
+
pn.pan.value = (i / (count - 1)) * 2 - 1;
|
|
399
|
+
osc.connect(pn);
|
|
400
|
+
oscs.push(pn);
|
|
401
|
+
} else oscs.push(osc);
|
|
402
|
+
nodes.push(osc);
|
|
403
|
+
starts.push(wide ? [Math.max(0, time - rnd() / p.freq), undefined] : undefined);
|
|
404
|
+
}
|
|
405
|
+
return { nodes, out: sum([sum(oscs, level), ...feeds]), starts };
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
reverse(buffer) {
|
|
409
|
+
let r = this.reversed.get(buffer);
|
|
410
|
+
if (r) return r;
|
|
411
|
+
r = this.ctx.createBuffer(buffer.numberOfChannels, buffer.length, buffer.sampleRate);
|
|
412
|
+
for (let ch = 0; ch < buffer.numberOfChannels; ch++) {
|
|
413
|
+
const src = buffer.getChannelData(ch);
|
|
414
|
+
const dst = r.getChannelData(ch);
|
|
415
|
+
for (let i = 0, n = src.length; i < n; i++) dst[i] = src[n - 1 - i];
|
|
416
|
+
}
|
|
417
|
+
this.reversed.set(buffer, r);
|
|
418
|
+
return r;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
sampleSources(p, buffer, pitchRate) {
|
|
422
|
+
const src = this.ctx.createBufferSource();
|
|
423
|
+
const reverse = p.speed < 0;
|
|
424
|
+
src.buffer = reverse ? this.reverse(buffer) : buffer;
|
|
425
|
+
const len = buffer.duration ?? buffer.length / buffer.sampleRate;
|
|
426
|
+
// unit 'c': rate = |speed| · sample length in seconds, no cps factor
|
|
427
|
+
// (spec/sound.md 10.1; loopAt/fit put the cps into speed). The pitch rate
|
|
428
|
+
// does not apply.
|
|
429
|
+
const rate = p.unit === 'c' ? Math.abs(p.speed) * len : Math.abs(p.speed) * pitchRate;
|
|
430
|
+
src.playbackRate.value = rate;
|
|
431
|
+
let begin = Math.min(p.begin, p.end);
|
|
432
|
+
let end = Math.max(p.begin, p.end);
|
|
433
|
+
if (reverse) [begin, end] = [1 - end, 1 - begin];
|
|
434
|
+
const out = src;
|
|
435
|
+
if (p.loop) {
|
|
436
|
+
// Looping (spec/sound.md 10.2): start at begin, loop loopBegin..loopEnd
|
|
437
|
+
// (whole buffer by default); end has no effect.
|
|
438
|
+
// Set loop points count from the start point (measured: begin .1 with
|
|
439
|
+
// loopBegin .5 / loopEnd .75 loops 0.4..0.65); unset ones = whole buffer.
|
|
440
|
+
let lb = 0, le = 1;
|
|
441
|
+
if (p.loopBegin !== undefined || p.loopEnd !== undefined) {
|
|
442
|
+
lb = Math.max(0, (p.loopBegin ?? 0) - p.begin);
|
|
443
|
+
le = Math.min(1, (p.loopEnd ?? 1) - p.begin);
|
|
444
|
+
if (!(le > lb)) [lb, le] = [0, 1];
|
|
445
|
+
}
|
|
446
|
+
if (reverse) [lb, le] = [1 - le, 1 - lb];
|
|
447
|
+
src.loop = true;
|
|
448
|
+
src.loopStart = lb * len;
|
|
449
|
+
src.loopEnd = le * len;
|
|
450
|
+
return { nodes: [src], out, offset: reverse ? 0 : p.begin * len };
|
|
451
|
+
}
|
|
452
|
+
const offset = begin * len;
|
|
453
|
+
return { nodes: [src], out, offset, length: rate > 0 ? ((end - begin) * len) / rate : 0 };
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// Wires the effect chain behind `sources` and schedules start, envelope
|
|
457
|
+
// and stop. Samples play to their natural length unless looped or given a
|
|
458
|
+
// release; synths are held for the hap's duration.
|
|
459
|
+
startVoice(p, time, duration, sources, isSample = false) {
|
|
460
|
+
const c = this.ctx;
|
|
461
|
+
const env = c.createGain();
|
|
462
|
+
env.gain.value = 0; // closed until the voice starts (sources may start early)
|
|
463
|
+
sources.out.connect(env);
|
|
464
|
+
let hold = duration;
|
|
465
|
+
let tail;
|
|
466
|
+
if (isSample && sources.length !== undefined && p.release === undefined) {
|
|
467
|
+
// To the natural end: the 5 ms fade ends with the buffer.
|
|
468
|
+
tail = Math.min(0.005, sources.length);
|
|
469
|
+
hold = sources.length - tail;
|
|
470
|
+
}
|
|
471
|
+
// clip: cut at clip × the event's duration with the usual release.
|
|
472
|
+
if (p.clip !== undefined && p.clip >= 0) {
|
|
473
|
+
hold = p.clip * duration;
|
|
474
|
+
tail = undefined;
|
|
475
|
+
}
|
|
476
|
+
const pts = envelopePoints(isSample && p.decay === undefined ? { ...p, decay: 0, sustain: 1 } : p, hold);
|
|
477
|
+
env.gain.setValueAtTime(0, time);
|
|
478
|
+
for (let i = 1; i < pts.length; i++) {
|
|
479
|
+
const [t, v] = pts[i];
|
|
480
|
+
if (i === pts.length - 1 && tail !== undefined) env.gain.linearRampToValueAtTime(0, time + hold + tail);
|
|
481
|
+
else env.gain.linearRampToValueAtTime(v, time + t);
|
|
482
|
+
}
|
|
483
|
+
const endTime = time + (tail !== undefined ? hold + tail : pts[pts.length - 1][0]);
|
|
484
|
+
|
|
485
|
+
let node = env;
|
|
486
|
+
const chain = (n) => { node.connect(n); node = n; return n; };
|
|
487
|
+
const filter = (type, f, q) => {
|
|
488
|
+
const b = chain(c.createBiquadFilter());
|
|
489
|
+
b.type = type;
|
|
490
|
+
b.frequency.value = Math.min(c.sampleRate / 2, Math.max(10, f));
|
|
491
|
+
b.Q.value = q ?? 1;
|
|
492
|
+
};
|
|
493
|
+
if (p.cutoff !== undefined) filter('lowpass', p.cutoff, p.resonance);
|
|
494
|
+
if (p.hcutoff !== undefined) filter('highpass', p.hcutoff, p.hresonance);
|
|
495
|
+
if (p.bandf !== undefined) filter('bandpass', p.bandf, p.bandq);
|
|
496
|
+
const fx = this.voiceEffects(p, time, endTime, sources, node);
|
|
497
|
+
node = fx.node;
|
|
498
|
+
const amp = chain(c.createGain());
|
|
499
|
+
amp.gain.value = p.gain * (isSample ? LEVEL.sample : LEVEL.synth);
|
|
500
|
+
let out = amp;
|
|
501
|
+
if (p.pan !== undefined && typeof c.createStereoPanner === 'function') {
|
|
502
|
+
out = chain(c.createStereoPanner());
|
|
503
|
+
out.pan.value = p.pan * 2 - 1;
|
|
504
|
+
}
|
|
505
|
+
let post = 1;
|
|
506
|
+
if (p.crush !== undefined) { out = chain(c.createWaveShaper()); out.curve = this.curve('crush', p.crush); }
|
|
507
|
+
if (p.shape !== undefined) { out = chain(c.createWaveShaper()); out.curve = this.curve('shape', p.shape); post *= p.shapevol ?? 1; }
|
|
508
|
+
if (p.distort !== undefined) { out = chain(c.createWaveShaper()); out.curve = this.curve('distort', p.distort); post *= p.distortvol ?? 1; }
|
|
509
|
+
if (post !== 1) { out = chain(c.createGain()); out.gain.value = post; }
|
|
510
|
+
const orbit = this.orbit(p.orbit);
|
|
511
|
+
out.connect(this.master);
|
|
512
|
+
const sends = [];
|
|
513
|
+
if (p.delay > 0) {
|
|
514
|
+
const g = c.createGain();
|
|
515
|
+
g.gain.value = p.delay;
|
|
516
|
+
out.connect(g);
|
|
517
|
+
g.connect(orbit.delay);
|
|
518
|
+
this.setBus(orbit, 'dt', orbit.delay.delayTime, Math.min(10, Math.max(0, p.delaytime)), time);
|
|
519
|
+
this.setBus(orbit, 'fb', orbit.feedback.gain, p.delayfeedback, time);
|
|
520
|
+
sends.push(g);
|
|
521
|
+
}
|
|
522
|
+
if (p.room > 0) {
|
|
523
|
+
const g = c.createGain();
|
|
524
|
+
g.gain.value = p.room;
|
|
525
|
+
out.connect(g);
|
|
526
|
+
g.connect(this.reverb(orbit, p.roomsize, endTime));
|
|
527
|
+
sends.push(g);
|
|
528
|
+
}
|
|
529
|
+
if (p.analyze !== undefined) out.connect(this.analyser(p.analyze));
|
|
530
|
+
|
|
531
|
+
sources.nodes.forEach((n, i) => {
|
|
532
|
+
const at = sources.starts?.[i];
|
|
533
|
+
if (at) { if (at[1] !== undefined) n.start(at[0], at[1]); else n.start(at[0]); }
|
|
534
|
+
else if (sources.offset !== undefined) n.start(time, sources.offset);
|
|
535
|
+
else n.start(time);
|
|
536
|
+
n.stop(endTime + 0.01);
|
|
537
|
+
});
|
|
538
|
+
const voice = {
|
|
539
|
+
start: time,
|
|
540
|
+
end: endTime,
|
|
541
|
+
cut: p.cut,
|
|
542
|
+
amp,
|
|
543
|
+
nodes: fx.nodes.length ? [...sources.nodes, ...fx.nodes] : sources.nodes,
|
|
544
|
+
stopped: false,
|
|
545
|
+
stop: (at = c.currentTime, fade = FADE) => {
|
|
546
|
+
if (voice.stopped) return;
|
|
547
|
+
voice.stopped = true;
|
|
548
|
+
const t = Math.max(at, c.currentTime);
|
|
549
|
+
amp.gain.cancelScheduledValues(t);
|
|
550
|
+
amp.gain.setTargetAtTime(0, t, fade / 3);
|
|
551
|
+
for (const n of voice.nodes) { try { n.stop(t + fade * 3); } catch { /* already stopped */ } }
|
|
552
|
+
},
|
|
553
|
+
};
|
|
554
|
+
const first = sources.nodes[0];
|
|
555
|
+
first.onended = () => {
|
|
556
|
+
this.pool.remove(voice);
|
|
557
|
+
for (const n of [sources.out, env, ...sends, ...fx.links, node]) { try { n.disconnect(); } catch { /* gone */ } }
|
|
558
|
+
};
|
|
559
|
+
for (const v of this.pool.add(voice)) v.stop(Math.max(time, c.currentTime));
|
|
560
|
+
return voice;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// Vowel, phaser, tremolo and vibrato (spec/sound.md 14-17) behind `node`.
|
|
564
|
+
// → { node: the new chain end, nodes: extra sources started here, links:
|
|
565
|
+
// nodes to disconnect at the voice's end }.
|
|
566
|
+
voiceEffects(p, time, endTime, sources, node) {
|
|
567
|
+
const c = this.ctx, nodes = [], links = [];
|
|
568
|
+
const start = (n, at) => { n.start(at); n.stop(endTime + 0.01); nodes.push(n); return n; };
|
|
569
|
+
const formants = p.vowel === undefined ? null : vowelFormants(p.vowel);
|
|
570
|
+
if (formants) {
|
|
571
|
+
// Parallel band-passes, each scaled to its formant level, summed.
|
|
572
|
+
const sum = c.createGain();
|
|
573
|
+
for (const [f, g, q] of formants) {
|
|
574
|
+
const b = c.createBiquadFilter();
|
|
575
|
+
b.type = 'bandpass';
|
|
576
|
+
b.frequency.value = Math.min(c.sampleRate / 2, f);
|
|
577
|
+
b.Q.value = q;
|
|
578
|
+
const a = c.createGain();
|
|
579
|
+
a.gain.value = g;
|
|
580
|
+
node.connect(b); b.connect(a); a.connect(sum);
|
|
581
|
+
}
|
|
582
|
+
node = sum;
|
|
583
|
+
}
|
|
584
|
+
const ph = phaserParams(p);
|
|
585
|
+
if (ph) {
|
|
586
|
+
const b = c.createBiquadFilter();
|
|
587
|
+
b.type = 'notch';
|
|
588
|
+
b.frequency.value = Math.min(c.sampleRate / 2, ph.freq);
|
|
589
|
+
b.Q.value = ph.q;
|
|
590
|
+
if (ph.rate > 0 && ph.cents > 0) {
|
|
591
|
+
// The sweep follows the audio clock: one shared LFO per rate.
|
|
592
|
+
const depth = c.createGain();
|
|
593
|
+
depth.gain.value = ph.cents;
|
|
594
|
+
this.phaserLfo(ph.rate).connect(depth);
|
|
595
|
+
depth.connect(b.detune);
|
|
596
|
+
links.push(depth);
|
|
597
|
+
} else b.detune.value = -ph.cents; // rate 0: parked at the bottom
|
|
598
|
+
node.connect(b);
|
|
599
|
+
node = b;
|
|
600
|
+
}
|
|
601
|
+
const tr = tremoloParams(p);
|
|
602
|
+
if (tr) {
|
|
603
|
+
// One LFO period of the gain law in a looped buffer, read from the note's
|
|
604
|
+
// cycle-locked phase; the buffer is shared, the reader is per voice.
|
|
605
|
+
const len = 1024;
|
|
606
|
+
const buffer = lru(this.trem, tr.key, () => {
|
|
607
|
+
const b = c.createBuffer(1, len, c.sampleRate);
|
|
608
|
+
b.getChannelData(0).set(tremoloCurve(p, len));
|
|
609
|
+
return b;
|
|
610
|
+
}, 32);
|
|
611
|
+
const src = c.createBufferSource();
|
|
612
|
+
src.buffer = buffer;
|
|
613
|
+
src.loop = true;
|
|
614
|
+
src.playbackRate.value = (tr.rate * len) / c.sampleRate;
|
|
615
|
+
const g = c.createGain();
|
|
616
|
+
g.gain.value = 0;
|
|
617
|
+
src.connect(g.gain);
|
|
618
|
+
node.connect(g);
|
|
619
|
+
node = g;
|
|
620
|
+
src.start(time, tr.phase * buffer.duration);
|
|
621
|
+
src.stop(endTime + 0.01);
|
|
622
|
+
nodes.push(src);
|
|
623
|
+
}
|
|
624
|
+
if (p.vib > 0 && p.vibmod !== 0) {
|
|
625
|
+
// Pitch: vibmod · sin(2π · vib · (t − onset)) semitones on every source.
|
|
626
|
+
const targets = sources.nodes.filter((n) => n.detune);
|
|
627
|
+
if (targets.length) {
|
|
628
|
+
const lfo = c.createOscillator();
|
|
629
|
+
lfo.frequency.value = p.vib;
|
|
630
|
+
const g = c.createGain();
|
|
631
|
+
g.gain.value = 100 * p.vibmod;
|
|
632
|
+
lfo.connect(g);
|
|
633
|
+
for (const n of targets) g.connect(n.detune);
|
|
634
|
+
start(lfo, time);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
return { node, nodes, links };
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
// The phaser's triangle LFO at `rate` Hz: -1 at clock time 0, so every voice
|
|
641
|
+
// at that rate shares one running oscillator. At most 16 rates are kept.
|
|
642
|
+
phaserLfo(rate) {
|
|
643
|
+
let osc = this.lfos.get(rate);
|
|
644
|
+
if (osc) return osc;
|
|
645
|
+
const c = this.ctx;
|
|
646
|
+
const now = c.currentTime;
|
|
647
|
+
const { real, imag } = phaserWave((rate * now) % 1);
|
|
648
|
+
osc = c.createOscillator();
|
|
649
|
+
osc.setPeriodicWave(c.createPeriodicWave(real, imag, { disableNormalization: true }));
|
|
650
|
+
osc.frequency.value = rate;
|
|
651
|
+
osc.start(now);
|
|
652
|
+
if (this.lfos.size >= 16) {
|
|
653
|
+
const [k, old] = this.lfos.entries().next().value;
|
|
654
|
+
this.lfos.delete(k);
|
|
655
|
+
try { old.stop(); old.disconnect(); } catch { /* gone */ }
|
|
656
|
+
}
|
|
657
|
+
this.lfos.set(rate, osc);
|
|
658
|
+
return osc;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// Stop everything at once (hush): fade the master out, stop every voice,
|
|
662
|
+
// drop the orbits (delay/reverb tails) and start a fresh output.
|
|
663
|
+
silence() {
|
|
664
|
+
this.generation++;
|
|
665
|
+
const now = this.ctx.currentTime;
|
|
666
|
+
const old = this.master;
|
|
667
|
+
old.gain.cancelScheduledValues(now);
|
|
668
|
+
old.gain.setTargetAtTime(0, now, FADE / 3);
|
|
669
|
+
for (const v of this.pool.clear()) v.stop(now);
|
|
670
|
+
const orbits = [...this.orbits.values()];
|
|
671
|
+
const drop = () => {
|
|
672
|
+
try { old.disconnect(); } catch { /* gone */ }
|
|
673
|
+
for (const o of orbits) for (const n of [o.delay, o.feedback, ...[...o.reverbs.values()].map((r) => r.node)]) { try { n.disconnect(); } catch { /* gone */ } }
|
|
674
|
+
};
|
|
675
|
+
if (typeof setTimeout === 'function') setTimeout(drop, 100); else drop();
|
|
676
|
+
this.makeOutput();
|
|
677
|
+
}
|
|
678
|
+
}
|