@zeeuw/riff 0.0.0-stage → 0.1.0-beta.2
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 +195 -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,397 @@
|
|
|
1
|
+
// Hap value → voice parameters (plan 4.3/4.4). Pure: no Web Audio here, so
|
|
2
|
+
// the control mapping is unit-tested in node. Sound defaults are RIFF
|
|
3
|
+
// decisions (docs/decisions.md, Epic 4 audio).
|
|
4
|
+
import { toMidi as noteMidi, midiToFreq, freqToMidi } from '../util.js';
|
|
5
|
+
|
|
6
|
+
// Sound name → oscillator family.
|
|
7
|
+
export const SYNTHS = Object.freeze({
|
|
8
|
+
sine: 'sine', sin: 'sine',
|
|
9
|
+
sawtooth: 'sawtooth', saw: 'sawtooth',
|
|
10
|
+
square: 'square', sqr: 'square',
|
|
11
|
+
triangle: 'triangle', tri: 'triangle',
|
|
12
|
+
supersaw: 'supersaw', supersquare: 'supersquare',
|
|
13
|
+
white: 'white', pink: 'pink', brown: 'brown', crackle: 'crackle',
|
|
14
|
+
});
|
|
15
|
+
export const isSynth = (s) => Object.prototype.hasOwnProperty.call(SYNTHS, s);
|
|
16
|
+
|
|
17
|
+
export const DEFAULTS = Object.freeze({
|
|
18
|
+
s: 'triangle', gain: 0.8, midi: 36,
|
|
19
|
+
attack: 0.001, decay: 0.05, sustain: 0.6, release: 0.01,
|
|
20
|
+
pan: 0.5, orbit: 0, delaytime: 0.375, delayfeedback: 0.5, roomsize: 2,
|
|
21
|
+
unison: 5, detune: 0.18, fmh: 1, density: 0.02,
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
// Envelope values for the controls that are not set, once at least one of
|
|
25
|
+
// attack, decay, sustain, release is given (spec/sound.md 4, def-adsr-*).
|
|
26
|
+
export const PARTIAL_ADSR = Object.freeze({ attack: 0.001, decay: 0.01, release: 0.01 });
|
|
27
|
+
|
|
28
|
+
// Output level per voice kind, a factor on gain (decisions, p2-sound):
|
|
29
|
+
// synths sit about 10.5 dB under a full-scale oscillator, samples play at
|
|
30
|
+
// their file level. A voice without \`pan\` is not panned (both channels get
|
|
31
|
+
// the full signal); an explicit pan uses the equal-power law. Measured
|
|
32
|
+
// against the Strudel 1.2.5 renders (spec/sound.md 1, docs/parity-report.md).
|
|
33
|
+
export const LEVEL = Object.freeze({ synth: 0.3, sample: 1 });
|
|
34
|
+
|
|
35
|
+
// Colon values that were not split arrive as arrays: the first part counts.
|
|
36
|
+
const first = (v) => (Array.isArray(v) ? v[0] : v);
|
|
37
|
+
const num = (v) => {
|
|
38
|
+
v = first(v);
|
|
39
|
+
if (v === undefined || v === null || v === '') return undefined;
|
|
40
|
+
const n = Number(v);
|
|
41
|
+
return Number.isFinite(n) ? n : undefined;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
// Note name or number → MIDI number (undefined when neither).
|
|
45
|
+
export function toMidi(v) {
|
|
46
|
+
v = first(v);
|
|
47
|
+
if (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v))) return Number(v);
|
|
48
|
+
return noteMidi(v);
|
|
49
|
+
}
|
|
50
|
+
export { midiToFreq, freqToMidi };
|
|
51
|
+
|
|
52
|
+
// voiceParams(value, cps) → the parameters one voice needs, or
|
|
53
|
+
// { kind: 'none' } for a value that is not a control map.
|
|
54
|
+
// kind: 'synth' (wave = SYNTHS entry) or 'sample' (any other `s`).
|
|
55
|
+
// Times in seconds, delaytime too (measured, spec/sound.md 8). pan is
|
|
56
|
+
// undefined when the value has none (the voice is then not panned).
|
|
57
|
+
export function voiceParams(value, cps = 0.5) {
|
|
58
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return { kind: 'none' };
|
|
59
|
+
const v = value;
|
|
60
|
+
const s = first(v.s) === undefined ? DEFAULTS.s : String(first(v.s));
|
|
61
|
+
const synth = isSynth(s);
|
|
62
|
+
const freqIn = num(v.freq);
|
|
63
|
+
const noteMidi = toMidi(v.note);
|
|
64
|
+
// Pitch: freq, else note, else C2. `n` does not set a synth's pitch
|
|
65
|
+
// (spec/sound.md 12, def-n-synth).
|
|
66
|
+
let midi = freqIn !== undefined ? freqToMidi(freqIn) : noteMidi;
|
|
67
|
+
const pitched = midi !== undefined;
|
|
68
|
+
if (midi === undefined) midi = DEFAULTS.midi;
|
|
69
|
+
const p = {
|
|
70
|
+
kind: synth ? 'synth' : 'sample',
|
|
71
|
+
s,
|
|
72
|
+
wave: synth ? SYNTHS[s] : undefined,
|
|
73
|
+
n: synth ? undefined : (num(v.n) ?? 0),
|
|
74
|
+
bank: first(v.bank) === undefined ? undefined : String(first(v.bank)),
|
|
75
|
+
pitched,
|
|
76
|
+
midi,
|
|
77
|
+
freq: freqIn ?? midiToFreq(midi),
|
|
78
|
+
gain: (num(v.gain) ?? DEFAULTS.gain) * (num(v.velocity) ?? 1) * (num(v.postgain) ?? 1),
|
|
79
|
+
attack: num(v.attack),
|
|
80
|
+
decay: num(v.decay),
|
|
81
|
+
sustain: num(v.sustain),
|
|
82
|
+
release: num(v.release),
|
|
83
|
+
cutoff: num(v.cutoff), resonance: num(v.resonance),
|
|
84
|
+
hcutoff: num(v.hcutoff), hresonance: num(v.hresonance),
|
|
85
|
+
bandf: num(v.bandf), bandq: num(v.bandq),
|
|
86
|
+
pan: num(v.pan) === undefined ? undefined : Math.min(1, Math.max(0, num(v.pan))),
|
|
87
|
+
crush: num(v.crush),
|
|
88
|
+
shape: num(v.shape), shapevol: num(v.shapevol),
|
|
89
|
+
distort: num(v.distort), distortvol: num(v.distortvol),
|
|
90
|
+
fmi: num(v.fmi), fmh: num(v.fmh) ?? DEFAULTS.fmh,
|
|
91
|
+
fmattack: num(v.fmattack), fmdecay: num(v.fmdecay), fmsustain: num(v.fmsustain),
|
|
92
|
+
fmenv: first(v.fmenv) === undefined ? undefined : String(first(v.fmenv)),
|
|
93
|
+
// crackle impulse density; .noise(x) pink-noise amount (spec/sound.md 3).
|
|
94
|
+
density: Math.max(0, num(v.density) ?? DEFAULTS.density),
|
|
95
|
+
noise: num(v.noise) === undefined ? 0 : Math.min(1, Math.max(0, num(v.noise))),
|
|
96
|
+
orbit: num(v.orbit) ?? DEFAULTS.orbit,
|
|
97
|
+
delay: num(v.delay) ?? 0,
|
|
98
|
+
delaytime: num(v.delaytime) ?? DEFAULTS.delaytime,
|
|
99
|
+
delayfeedback: Math.min(0.98, Math.max(0, num(v.delayfeedback) ?? DEFAULTS.delayfeedback)),
|
|
100
|
+
room: num(v.room) ?? 0,
|
|
101
|
+
roomsize: Math.min(20, Math.max(0.05, num(v.roomsize) ?? DEFAULTS.roomsize)),
|
|
102
|
+
cut: num(v.cut),
|
|
103
|
+
speed: num(v.speed) ?? 1,
|
|
104
|
+
begin: Math.min(1, Math.max(0, num(v.begin) ?? 0)),
|
|
105
|
+
end: Math.min(1, Math.max(0, num(v.end) ?? 1)),
|
|
106
|
+
loop: Boolean(num(v.loop)),
|
|
107
|
+
loopBegin: num(v.loopBegin) === undefined ? undefined : Math.min(1, Math.max(0, num(v.loopBegin))),
|
|
108
|
+
loopEnd: num(v.loopEnd) === undefined ? undefined : Math.min(1, Math.max(0, num(v.loopEnd))),
|
|
109
|
+
// unit 'c': speed counts sample lengths per cycle (decisions, x10-unit).
|
|
110
|
+
unit: first(v.unit) === undefined ? undefined : String(first(v.unit)),
|
|
111
|
+
cps,
|
|
112
|
+
// clip: hold the voice for clip × the event's duration, then release.
|
|
113
|
+
clip: num(v.clip),
|
|
114
|
+
unison: Math.max(1, Math.round(num(v.unison) ?? DEFAULTS.unison)),
|
|
115
|
+
detune: num(v.detune) ?? DEFAULTS.detune,
|
|
116
|
+
analyze: first(v.analyze) === undefined ? undefined : String(first(v.analyze)),
|
|
117
|
+
// spec/sound.md 14-17: vowel formants, phaser notch, vibrato, tremolo.
|
|
118
|
+
vowel: first(v.vowel) === undefined ? undefined : String(first(v.vowel)),
|
|
119
|
+
phaserrate: num(v.phaserrate),
|
|
120
|
+
phaserdepth: Math.min(1, Math.max(0, num(v.phaserdepth) ?? 0.75)),
|
|
121
|
+
phasercenter: num(v.phasercenter) ?? 1000,
|
|
122
|
+
phasersweep: num(v.phasersweep) ?? 2000,
|
|
123
|
+
vib: num(v.vib),
|
|
124
|
+
vibmod: num(v.vibmod) ?? 0.5,
|
|
125
|
+
tremolo: num(v.tremolo),
|
|
126
|
+
tremolosync: num(v.tremolosync),
|
|
127
|
+
tremolodepth: num(v.tremolodepth) ?? 1,
|
|
128
|
+
tremolophase: num(v.tremolophase) ?? 0,
|
|
129
|
+
tremoloshape: first(v.tremoloshape) === undefined ? undefined : String(first(v.tremoloshape)),
|
|
130
|
+
tremoloskew: num(v.tremoloskew),
|
|
131
|
+
};
|
|
132
|
+
return p;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// --- vowel (spec/sound.md 14) ---------------------------------------------------
|
|
136
|
+
// Five band-pass resonances per vowel: [Hz, dB vs dry, Q]. Peaks and levels
|
|
137
|
+
// from the 14.2 table; levels the table leaves blank use the measured means
|
|
138
|
+
// (F2 +4, F3 -5, F4 -8, F5 -13 dB); F1 Q 40 (79 a/ae/aa, 69 e), F2 Q 80, the
|
|
139
|
+
// upper formants a 30 Hz wide peak (docs/decisions.md, s7-fx-impl).
|
|
140
|
+
const VOWEL_TABLE = {
|
|
141
|
+
a: [660, 1120, 2750, 3000, 3350, 18, 12, -4.9, -5.8, -17.5],
|
|
142
|
+
e: [440, 1800, 2700, 3000, 3300, 18, 4, 0, -1.9, -1.8],
|
|
143
|
+
i: [270, 1850, 2900, 3350, 3590, 18, -6, -5.9, -17.4, -17.3],
|
|
144
|
+
o: [430, 820, 2700, 3000, 3300, 18, 8.1, -7.9, -3.9, -14.5],
|
|
145
|
+
u: [370, 630, 2750, 3000, 3400, 18, -1.7, -5, -11.5, -15.3],
|
|
146
|
+
ae: [650, 1515, 2400, 3000, 3355, 18, 12],
|
|
147
|
+
aa: [560, 900, 2570, 3000, 3305, 18, 12],
|
|
148
|
+
oe: [500, 1430, 2300, 3000, 3305],
|
|
149
|
+
ue: [250, 1750, 2150, 3200, 3305],
|
|
150
|
+
y: [400, 1460, 2400, 3000, 3305],
|
|
151
|
+
uh: [600, 1250, 2100, 3100, 3505],
|
|
152
|
+
un: [500, 1240, 2280, 3000, 3505],
|
|
153
|
+
en: [600, 1480, 2450, 3200, 3305],
|
|
154
|
+
an: [700, 1050, 2500, 3000, 3305],
|
|
155
|
+
on: [500, 1080, 2350, 3000, 3305],
|
|
156
|
+
};
|
|
157
|
+
const VOWEL_DB = [18, 4, -5, -8, -13];
|
|
158
|
+
const F1Q = { a: 79, ae: 79, aa: 79, e: 69 };
|
|
159
|
+
// → [[Hz, linear gain, Q] x 5], or null for a name that is not a vowel (the
|
|
160
|
+
// event is then silent, spec 14.1).
|
|
161
|
+
export function vowelFormants(name) {
|
|
162
|
+
const row = Object.prototype.hasOwnProperty.call(VOWEL_TABLE, name) ? VOWEL_TABLE[name] : null;
|
|
163
|
+
if (!row) return null;
|
|
164
|
+
return [0, 1, 2, 3, 4].map((i) => {
|
|
165
|
+
const f = row[i];
|
|
166
|
+
const q = i === 0 ? F1Q[name] ?? 40 : i === 1 ? 80 : f / 30;
|
|
167
|
+
return [f, 10 ** ((row[5 + i] ?? VOWEL_DB[i]) / 20), q];
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// --- phaser (spec/sound.md 15) ----------------------------------------------------
|
|
172
|
+
// One 2nd-order notch: f(t) = (centre + 280) · 2^((sweep/1260) · tri(rate·t)),
|
|
173
|
+
// tri -1 at clock time 0; Q ≈ 2.06·(1 − depth), floor 0.105. null: no effect
|
|
174
|
+
// (no rate, or depth 0).
|
|
175
|
+
export function phaserParams(p) {
|
|
176
|
+
if (p.phaserrate === undefined || !(p.phaserdepth > 0)) return null;
|
|
177
|
+
return {
|
|
178
|
+
rate: Math.max(0, p.phaserrate),
|
|
179
|
+
freq: Math.max(10, p.phasercenter + 280),
|
|
180
|
+
cents: (1200 * Math.max(0, p.phasersweep)) / 1260,
|
|
181
|
+
q: Math.max(0.105, 2.06 * (1 - p.phaserdepth)),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
// Fourier terms of that triangle (-1 at x = 0) shifted by `phase` cycles,
|
|
185
|
+
// for a PeriodicWave: real = cosine, imag = sine terms; odd harmonics to 31.
|
|
186
|
+
export function phaserWave(phase, terms = 32) {
|
|
187
|
+
const real = new Float32Array(terms), imag = new Float32Array(terms);
|
|
188
|
+
for (let k = 1; k < terms; k += 2) {
|
|
189
|
+
const c = 8 / (Math.PI * Math.PI * k * k), a = 2 * Math.PI * k * phase;
|
|
190
|
+
real[k] = -c * Math.cos(a);
|
|
191
|
+
imag[k] = c * Math.sin(a);
|
|
192
|
+
}
|
|
193
|
+
return { real, imag };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// --- tremolo (spec/sound.md 17) ---------------------------------------------------
|
|
197
|
+
// LFO l(f) in [0, 1] for the fractional LFO position f.
|
|
198
|
+
export function tremoloShape(shape, skew) {
|
|
199
|
+
const tri = (s) => (f) => (f < s ? f / s : (1 - f) / (1 - s));
|
|
200
|
+
if (shape === 'sine') return (f) => (1 + Math.sin(2 * Math.PI * f)) / 2;
|
|
201
|
+
if (shape === 'square') { const s = skew ?? 0.5; return (f) => (f < s ? 1 : 0); }
|
|
202
|
+
if (shape === 'saw') return (f) => 1 - f;
|
|
203
|
+
if (shape === 'ramp' || (shape === undefined && skew === undefined)) return (f) => f;
|
|
204
|
+
const s = Math.min(1, Math.max(0, skew ?? 0.5));
|
|
205
|
+
return tri(s); // no shape with skew, tri and unknown names
|
|
206
|
+
}
|
|
207
|
+
// Gain law: min(1, max(0, 1 − d) + (d · l)^1.5).
|
|
208
|
+
export const tremoloGain = (d, l) => Math.min(1, Math.max(0, 1 - d) + Math.max(0, d * l) ** 1.5);
|
|
209
|
+
// One LFO period of the gain, `length` samples. null: no tremolo. Rate in Hz
|
|
210
|
+
// (sync wins: sync · cps); phase x0 at the note, in LFO cycles, cycle-locked.
|
|
211
|
+
export function tremoloParams(p) {
|
|
212
|
+
if (p.tremolo === undefined && p.tremolosync === undefined) return null;
|
|
213
|
+
const rate = Math.max(0, p.tremolosync !== undefined ? p.tremolosync * p.cps : p.tremolo);
|
|
214
|
+
const cycle = p.cycle ?? 0;
|
|
215
|
+
const x0 = (p.tremolosync !== undefined ? p.tremolosync * cycle : (rate * cycle) / p.cps) + p.tremolophase;
|
|
216
|
+
return { rate, phase: ((x0 % 1) + 1) % 1, key: [p.tremolodepth, p.tremoloshape, p.tremoloskew].join() };
|
|
217
|
+
}
|
|
218
|
+
export function tremoloCurve(p, length = 1024) {
|
|
219
|
+
const l = tremoloShape(p.tremoloshape, p.tremoloskew), out = new Float32Array(length);
|
|
220
|
+
for (let i = 0; i < length; i++) out[i] = tremoloGain(p.tremolodepth, l(i / length));
|
|
221
|
+
return out;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Envelope breakpoints [[t, level], ...] relative to the voice start, for a
|
|
225
|
+
// note held `hold` seconds and then released. With no ADSR control set the
|
|
226
|
+
// defaults apply (decay 0.05 to sustain 0.6); with any of them set the others
|
|
227
|
+
// are PARTIAL_ADSR and sustain is 1 without a decay, 0 with one (measured,
|
|
228
|
+
// spec/sound.md 4). A hold shorter than attack+decay releases from the level
|
|
229
|
+
// reached.
|
|
230
|
+
export function envelopePoints({ attack, decay, sustain, release } = {}, hold) {
|
|
231
|
+
const partial = attack !== undefined || decay !== undefined || sustain !== undefined || release !== undefined;
|
|
232
|
+
const D = partial ? { ...PARTIAL_ADSR, sustain: decay === undefined ? 1 : 0 } : DEFAULTS;
|
|
233
|
+
const a = Math.max(0.001, attack ?? D.attack);
|
|
234
|
+
const d = Math.max(0, decay ?? D.decay);
|
|
235
|
+
const s = Math.min(1, Math.max(0, sustain ?? D.sustain));
|
|
236
|
+
const r = Math.max(0.005, release ?? D.release);
|
|
237
|
+
const h = Math.max(0, hold);
|
|
238
|
+
const pts = [[0, 0]];
|
|
239
|
+
if (h >= a) {
|
|
240
|
+
pts.push([a, 1]);
|
|
241
|
+
if (h >= a + d) { pts.push([a + d, s]); pts.push([h, s]); }
|
|
242
|
+
else pts.push([h, 1 + (s - 1) * ((h - a) / (d || 1))]);
|
|
243
|
+
} else pts.push([h, h / a]);
|
|
244
|
+
pts.push([h + r, 0]);
|
|
245
|
+
return pts;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Supersaw/supersquare voice detune in cents: `detune` is the total spread
|
|
249
|
+
// in semitones, voices evenly spaced and centred on the note (spec/sound.md 2).
|
|
250
|
+
export const voiceDetune = (i, count, detune) => (count > 1 ? (i / (count - 1) - 0.5) * detune * 100 : 0);
|
|
251
|
+
// Per-voice gain of a wide synth: power-normalised, one voice 1.6 dB under a
|
|
252
|
+
// plain oscillator; spread voices go through equal-power panners (half the
|
|
253
|
+
// power per channel), hence the sqrt(2) (spec/sound.md 2, def-ss-*).
|
|
254
|
+
export const wideGain = (count) => (count > 1 ? 0.832 * Math.SQRT2 : 0.832) / Math.sqrt(count);
|
|
255
|
+
|
|
256
|
+
// .noise(x): oscillator and pink-noise factors (fitted, spec/sound.md 3):
|
|
257
|
+
// noise rises in proportion to x and is full from x = .5, the oscillator
|
|
258
|
+
// fades as 1 - x^3 and is gone at x = 1.
|
|
259
|
+
export const noiseMix = (x) => ({ osc: 1 - x ** 3, noise: Math.min(1, 2 * x) });
|
|
260
|
+
|
|
261
|
+
// crackle: single-sample impulses at random times, rate 480 x density per
|
|
262
|
+
// second, heights uniform in [0, 1). Fitted to spec/sound.md 3 through the
|
|
263
|
+
// harness's own detector (its click count misses the smallest impulses, which
|
|
264
|
+
// is why it reads about 350 x density). rnd: () => [0, 1).
|
|
265
|
+
export function crackleSamples(length, sampleRate, density, rnd) {
|
|
266
|
+
const d = new Float32Array(length);
|
|
267
|
+
const p = (480 * density) / sampleRate;
|
|
268
|
+
for (let i = 0; i < length; i++) if (rnd() < p) d[i] = rnd();
|
|
269
|
+
return d;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// FM (spec/sound.md 7): carrier phase w_c t + phi - beta(t) sin(w_m t), the
|
|
273
|
+
// modulator at fmh x the carrier frequency, beta = fmi, no level compensation.
|
|
274
|
+
// phi only matters where sidebands fold over 0 Hz onto other lines (fmh 1, 2,
|
|
275
|
+
// .5); the values are the fitted start phases of sound.md 7.1 (degrees, mod
|
|
276
|
+
// 180): fmh 1 interpolates the table, fmh 2 doubles it (one point: beta 2 ->
|
|
277
|
+
// 60), fmh .5 is 90 (one point). Other ratios do not fold; they take the fmh 1
|
|
278
|
+
// rule scaled by fmh.
|
|
279
|
+
const FM_PHASE = [[0, 0], [0.5, 0], [1, 7.5], [2, 30], [4, 75], [8, 165]];
|
|
280
|
+
export function fmPhase(beta, fmh = 1) {
|
|
281
|
+
if (Math.abs(fmh - 0.5) < 1e-9) return 90;
|
|
282
|
+
const b = Math.abs(beta);
|
|
283
|
+
let deg;
|
|
284
|
+
if (b >= 8) deg = 165 + 22.5 * (b - 8);
|
|
285
|
+
else {
|
|
286
|
+
let i = 1;
|
|
287
|
+
while (FM_PHASE[i][0] < b) i++;
|
|
288
|
+
const [b0, p0] = FM_PHASE[i - 1], [b1, p1] = FM_PHASE[i];
|
|
289
|
+
deg = p0 + ((p1 - p0) * (b - b0)) / (b1 - b0);
|
|
290
|
+
}
|
|
291
|
+
return (deg * fmh) % 180;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// FM index over the note, as a function of t (s from the onset): constant fmi
|
|
295
|
+
// without FM envelope controls; with any of fmattack/fmdecay/fmsustain set,
|
|
296
|
+
// an exponential rise from 0.001 x fmi over fmattack (default 0.001), then an
|
|
297
|
+
// exponential fall to fmsustain x fmi over fmdecay (default 0.01); fmsustain
|
|
298
|
+
// defaults like the amplitude envelope: 1 without fmdecay, 0 with one.
|
|
299
|
+
// fmenv 'lin' makes both ramps linear (unmeasured; 'exp' is the default).
|
|
300
|
+
const FM_FLOOR = 0.001;
|
|
301
|
+
export function fmIndex({ fmi = 0, fmattack, fmdecay, fmsustain, fmenv } = {}) {
|
|
302
|
+
if (fmattack === undefined && fmdecay === undefined && fmsustain === undefined) return () => fmi;
|
|
303
|
+
const a = Math.max(0, fmattack ?? 0.001), d = Math.max(0, fmdecay ?? 0.01);
|
|
304
|
+
const s = Math.min(1, Math.max(0, fmsustain ?? (fmdecay === undefined ? 1 : 0)));
|
|
305
|
+
const lin = fmenv === 'lin';
|
|
306
|
+
return (t) => {
|
|
307
|
+
if (t < a) return fmi * (lin ? t / a : FM_FLOOR ** (1 - t / a));
|
|
308
|
+
if (t < a + d) {
|
|
309
|
+
const u = (t - a) / d;
|
|
310
|
+
return fmi * (lin ? 1 + (s - 1) * u : Math.max(s, FM_FLOOR) ** u);
|
|
311
|
+
}
|
|
312
|
+
return fmi * s;
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// One FM sine voice as samples (mono, amplitude 1), `length` samples.
|
|
317
|
+
export function fmSamples(length, sampleRate, freq, fmh, index, phaseDeg) {
|
|
318
|
+
const out = new Float32Array(length);
|
|
319
|
+
const wc = (2 * Math.PI * freq) / sampleRate, wm = wc * fmh, phi = (phaseDeg * Math.PI) / 180;
|
|
320
|
+
for (let i = 0; i < length; i++) out[i] = Math.sin(wc * i + phi - index(i / sampleRate) * Math.sin(wm * i));
|
|
321
|
+
return out;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// Waveshaper curves (crush = bit depth; shape and distort = drive amounts).
|
|
325
|
+
export function shaperCurve(kind, amount, size = 2048) {
|
|
326
|
+
const c = new Float32Array(size);
|
|
327
|
+
for (let i = 0; i < size; i++) {
|
|
328
|
+
const x = (i / (size - 1)) * 2 - 1;
|
|
329
|
+
let y;
|
|
330
|
+
if (kind === 'crush') {
|
|
331
|
+
const steps = 2 ** (Math.max(1, Math.min(16, amount)) - 1);
|
|
332
|
+
y = Math.round(x * steps) / steps;
|
|
333
|
+
} else {
|
|
334
|
+
// shape and distort: the same rational soft clip (1+k)x / (1+k|x|),
|
|
335
|
+
// small-signal gain 1+k; shape k = 2s/(1-s), distort 1+k = e^d.
|
|
336
|
+
// Fitted to spec/sound.md 6 with the shaper after the panner.
|
|
337
|
+
const k = kind === 'shape'
|
|
338
|
+
? (2 * Math.min(0.999, Math.max(0, amount))) / (1 - Math.min(0.999, Math.max(0, amount)))
|
|
339
|
+
: Math.exp(Math.min(10, Math.max(0, amount))) - 1;
|
|
340
|
+
y = ((1 + k) * x) / (1 + k * Math.abs(x));
|
|
341
|
+
}
|
|
342
|
+
c[i] = y;
|
|
343
|
+
}
|
|
344
|
+
return c;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// Master limiter curve for a WaveShaper fed through a gain of 1/range: the
|
|
348
|
+
// identity up to `threshold` dBFS, above it a tanh knee that approaches
|
|
349
|
+
// full scale; inputs up to `range` (linear) are covered. A static curve has
|
|
350
|
+
// no lookahead, so the limiter adds no latency (the DynamicsCompressor it
|
|
351
|
+
// replaces delayed everything by 6 ms, docs/parity-report.md).
|
|
352
|
+
export function limiterCurve(threshold = -3, range = 4, size = 8193) {
|
|
353
|
+
const t = 10 ** (threshold / 20);
|
|
354
|
+
const c = new Float32Array(size);
|
|
355
|
+
for (let i = 0; i < size; i++) {
|
|
356
|
+
const x = ((i / (size - 1)) * 2 - 1) * range;
|
|
357
|
+
const a = Math.abs(x);
|
|
358
|
+
c[i] = a <= t ? x : Math.sign(x) * (t + (1 - t) * Math.tanh((a - t) / (1 - t)));
|
|
359
|
+
}
|
|
360
|
+
return c;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Controls the Web Audio engine acts on (voiceParams above, plus `cps` when
|
|
364
|
+
// the scheduler's patternCps option is on). docs/improvements.md 15.
|
|
365
|
+
// Derived (audit 8), not hand-kept: voiceParams is run once on a recording
|
|
366
|
+
// Proxy, as a synth and as a sample (the only branch that changes which keys
|
|
367
|
+
// it reads), so a control the engine starts reading is listed at once.
|
|
368
|
+
export const AUDIO_CONTROLS = (() => {
|
|
369
|
+
const keys = new Set();
|
|
370
|
+
for (const s of [undefined, 'bd']) {
|
|
371
|
+
voiceParams(new Proxy({}, { get: (_, k) => { if (typeof k === 'string') keys.add(k); return k === 's' ? s : undefined; } }));
|
|
372
|
+
}
|
|
373
|
+
return keys;
|
|
374
|
+
})();
|
|
375
|
+
|
|
376
|
+
// Controls that are not meant for the synth at all (visuals, tonal helpers,
|
|
377
|
+
// MIDI/OSC output, scheduler): never reported as "no effect".
|
|
378
|
+
export const NON_SOUND_CONTROLS = new Set([
|
|
379
|
+
'cps', 'color', 'label', 'activeLabel', 'chord', 'dictionary', 'anchor', 'mode', 'offset',
|
|
380
|
+
'octave', 'octaveR', 'degree', 'mtranspose', 'ctranspose', 'harmonic', 'stepsPerOctave', 'semitone',
|
|
381
|
+
'voice', 'uid', 'val', 'duration', 'legato', 'gate', 'expression', 'channel', 'channels',
|
|
382
|
+
'ccn', 'ccv', 'ctlNum', 'nrpnn', 'nrpv', 'midibend', 'midichan', 'midicmd', 'midimap', 'midiport',
|
|
383
|
+
'miditouch', 'polyTouch', 'progNum', 'songPtr', 'sysexdata', 'sysexid', 'oschost', 'oscport',
|
|
384
|
+
'frames', 'frameRate', 'hours', 'minutes', 'seconds',
|
|
385
|
+
]);
|
|
386
|
+
|
|
387
|
+
// Control names (value keys) of `value` that RIFF's audio engine ignores:
|
|
388
|
+
// registered controls (`known`: a Set of value keys) that are neither played
|
|
389
|
+
// nor meant for another layer. [] for a non-object value.
|
|
390
|
+
export function unusedControls(value, known) {
|
|
391
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return [];
|
|
392
|
+
const out = [];
|
|
393
|
+
for (const k in value) {
|
|
394
|
+
if (!AUDIO_CONTROLS.has(k) && !NON_SOUND_CONTROLS.has(k) && known.has(k)) out.push(k);
|
|
395
|
+
}
|
|
396
|
+
return out;
|
|
397
|
+
}
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
// Sample loader (plan 4.2, spec/samples.md). Turns sample maps into a registry
|
|
2
|
+
// of sound names, fetches and decodes files on demand, and keeps the decoded
|
|
3
|
+
// buffers in an LRU cache bounded by a byte budget.
|
|
4
|
+
//
|
|
5
|
+
// createSampleBank(opts) -> bank, independent of any global; the default bank
|
|
6
|
+
// (configureSamples) is what `samples()` from src/samples.js feeds once the
|
|
7
|
+
// sound layer is set up, and what the module-level `sampleSource` reads.
|
|
8
|
+
import { noteToMidi } from '../ops.js';
|
|
9
|
+
import { setSamplesLoader, getSampleSources } from '../samples.js';
|
|
10
|
+
|
|
11
|
+
const GITHUB = 'github:';
|
|
12
|
+
const RAW = 'https://raw.githubusercontent.com/';
|
|
13
|
+
const DEFAULT_BUDGET = 192 * 1024 * 1024; // bytes of decoded float32 audio
|
|
14
|
+
// A pitched hap on an unpitched sample: rate 2^((midi - 36) / 12), so c3 plays
|
|
15
|
+
// an octave up (measured, spec/sound.md 10; decisions p2-sound).
|
|
16
|
+
const UNPITCHED_REF = 36;
|
|
17
|
+
const DEFAULT_KEY = 48; // c3: the file a pitched map plays without a note (spec/samples.md 5)
|
|
18
|
+
|
|
19
|
+
// `github:user/repo[/branch][/]` -> { user, repo, branch } (spec 2.3).
|
|
20
|
+
function githubParts(s) {
|
|
21
|
+
const parts = s.slice(GITHUB.length).replace(/\/+$/, '').split('/');
|
|
22
|
+
if (parts.length < 2 || !parts[0] || !parts[1]) throw new Error(`samples: bad github source "${s}" (want github:user/repo[/branch])`);
|
|
23
|
+
return { user: parts[0], repo: parts[1], branch: parts.slice(2).join('/') || 'main' };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// A map source -> URL of its JSON.
|
|
27
|
+
export function resolveMapUrl(source) {
|
|
28
|
+
if (source.startsWith(GITHUB)) {
|
|
29
|
+
const { user, repo, branch } = githubParts(source);
|
|
30
|
+
return `${RAW}${user}/${repo}/${branch}/strudel.json`;
|
|
31
|
+
}
|
|
32
|
+
if (/^https?:\/\//i.test(source)) return source;
|
|
33
|
+
throw new Error(`samples: unsupported source "${source}" (RIFF loads map objects, http(s) URLs and github:user/repo)`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// A baseUrl argument -> base string; github: shorthand gives the repo folder.
|
|
37
|
+
export function resolveBase(base) {
|
|
38
|
+
if (base == null || base === '') return '';
|
|
39
|
+
base = String(base);
|
|
40
|
+
if (base.startsWith(GITHUB)) {
|
|
41
|
+
const { user, repo, branch } = githubParts(base);
|
|
42
|
+
return `${RAW}${user}/${repo}/${branch}/`;
|
|
43
|
+
}
|
|
44
|
+
return base;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Directory of a map URL: everything up to the last '/' before any query.
|
|
48
|
+
export function urlDirectory(url) {
|
|
49
|
+
const path = url.split(/[?#]/)[0];
|
|
50
|
+
return path.slice(0, path.lastIndexOf('/') + 1);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Files may hold '#' (never a fragment in a sample path): escape every one.
|
|
54
|
+
const fileUrl = (base, path) => (base + path).replaceAll('#', '%23');
|
|
55
|
+
|
|
56
|
+
// Map object -> Map(name -> entry). entry: { kind: 'list', urls } or
|
|
57
|
+
// { kind: 'pitched', keys: [{ midi, url }] sorted by midi }.
|
|
58
|
+
export function parseSampleMap(map, baseUrl, warn = () => {}) {
|
|
59
|
+
if (map === null || typeof map !== 'object' || Array.isArray(map)) throw new Error('samples: a sample map must be an object');
|
|
60
|
+
const base = resolveBase(typeof map._base === 'string' ? map._base : baseUrl);
|
|
61
|
+
const out = new Map();
|
|
62
|
+
for (const [name, v] of Object.entries(map)) {
|
|
63
|
+
if (name.startsWith('_')) continue;
|
|
64
|
+
if (typeof v === 'string') out.set(name, { kind: 'list', urls: [fileUrl(base, v)] });
|
|
65
|
+
else if (Array.isArray(v)) {
|
|
66
|
+
const urls = v.filter((p) => typeof p === 'string').map((p) => fileUrl(base, p));
|
|
67
|
+
if (urls.length) out.set(name, { kind: 'list', urls });
|
|
68
|
+
} else if (v && typeof v === 'object') {
|
|
69
|
+
const keys = [];
|
|
70
|
+
for (const [k, p] of Object.entries(v)) {
|
|
71
|
+
const midi = noteToMidi(k);
|
|
72
|
+
const path = Array.isArray(p) ? p[0] : p;
|
|
73
|
+
if (midi === undefined || typeof path !== 'string') { warn(`samples: "${name}" key "${k}" is not a note name, skipped`); continue; }
|
|
74
|
+
keys.push({ midi, url: fileUrl(base, path) });
|
|
75
|
+
}
|
|
76
|
+
keys.sort((a, b) => a.midi - b.midi);
|
|
77
|
+
if (keys.length) out.set(name, { kind: 'pitched', keys });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export const soundName = (s, bank) => (bank == null || bank === '' ? String(s) : `${bank}_${s}`);
|
|
84
|
+
|
|
85
|
+
// Index wrap (spec 3): floor, mathematical modulo, default 0.
|
|
86
|
+
export function wrapIndex(n, k) {
|
|
87
|
+
let i = Math.floor(Number(n ?? 0));
|
|
88
|
+
if (!Number.isFinite(i)) i = 0;
|
|
89
|
+
return ((i % k) + k) % k;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Hap pitch -> MIDI number, or undefined. note: name or number; freq in Hz.
|
|
93
|
+
export function pitchOf({ note, freq } = {}) {
|
|
94
|
+
if (typeof note === 'number' && Number.isFinite(note)) return note;
|
|
95
|
+
if (typeof note === 'string') {
|
|
96
|
+
const m = Number.isFinite(Number(note)) && note.trim() !== '' ? Number(note) : noteToMidi(note);
|
|
97
|
+
if (m !== undefined) return m;
|
|
98
|
+
}
|
|
99
|
+
if (typeof freq === 'number' && freq > 0) return 69 + 12 * Math.log2(freq / 440);
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Nearest key, ties to the lower key (spec 5). `keys` is sorted by midi
|
|
104
|
+
// (parseSampleMap), so a binary search finds it (docs/improvements.md 34).
|
|
105
|
+
export function nearestKey(keys, midi) {
|
|
106
|
+
let lo = 0, hi = keys.length;
|
|
107
|
+
while (lo < hi) { const mid = (lo + hi) >> 1; if (keys[mid].midi < midi) lo = mid + 1; else hi = mid; }
|
|
108
|
+
if (lo >= keys.length) lo = keys.length - 1;
|
|
109
|
+
else if (lo > 0 && midi - keys[lo - 1].midi <= keys[lo].midi - midi) lo--;
|
|
110
|
+
while (lo > 0 && keys[lo - 1].midi === keys[lo].midi) lo--; // first of equal keys
|
|
111
|
+
return keys[lo];
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const bufferBytes = (b) => (b?.length ?? 0) * (b?.numberOfChannels ?? 1) * 4;
|
|
115
|
+
|
|
116
|
+
export function createSampleBank({
|
|
117
|
+
fetch: fetchFn = globalThis.fetch?.bind(globalThis),
|
|
118
|
+
audioContext = null,
|
|
119
|
+
budgetBytes = DEFAULT_BUDGET,
|
|
120
|
+
retryMs = 1000,
|
|
121
|
+
maxRetryMs = 30_000,
|
|
122
|
+
now = () => Date.now(),
|
|
123
|
+
warn = (m) => console.warn(m),
|
|
124
|
+
} = {}) {
|
|
125
|
+
const sounds = new Map(); // name -> entry
|
|
126
|
+
const cache = new Map(); // url -> { state, promise, buffer, bytes, failures, failedAt }; insertion order = LRU
|
|
127
|
+
const warned = new Set();
|
|
128
|
+
let ctx = audioContext;
|
|
129
|
+
let bytes = 0;
|
|
130
|
+
|
|
131
|
+
const warnOnce = (key, msg) => { if (!warned.has(key)) { warned.add(key); warn(msg); } };
|
|
132
|
+
|
|
133
|
+
async function fetchOk(url, init) {
|
|
134
|
+
if (!fetchFn) throw new Error('samples: no fetch available');
|
|
135
|
+
const res = await fetchFn(url, init);
|
|
136
|
+
if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`);
|
|
137
|
+
return res;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// samples(source, baseUrl): register names; resolves to the names added.
|
|
141
|
+
// A failed map is reported and leaves no names; it never rejects (spec 6).
|
|
142
|
+
async function samples(source, baseUrl) {
|
|
143
|
+
try {
|
|
144
|
+
let map = source, base = baseUrl;
|
|
145
|
+
if (typeof source === 'string') {
|
|
146
|
+
const url = resolveMapUrl(source);
|
|
147
|
+
map = await (await fetchOk(url, { cache: 'no-cache' })).json();
|
|
148
|
+
if (base == null && (map == null || typeof map._base !== 'string')) base = urlDirectory(url);
|
|
149
|
+
}
|
|
150
|
+
const parsed = parseSampleMap(map, base, warn);
|
|
151
|
+
for (const [name, e] of parsed) { sounds.set(name, e); warned.delete(`sound:${name}`); }
|
|
152
|
+
return [...parsed.keys()];
|
|
153
|
+
} catch (err) {
|
|
154
|
+
warn(`samples: could not load ${typeof source === 'string' ? source : 'map'}: ${err.message}`);
|
|
155
|
+
return [];
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Which file and playback rate a hap's controls select, or null.
|
|
160
|
+
function resolve({ s, n, bank, note, freq } = {}) {
|
|
161
|
+
if (s == null) return null;
|
|
162
|
+
const name = soundName(s, bank);
|
|
163
|
+
const e = sounds.get(name);
|
|
164
|
+
if (!e) { warnOnce(`sound:${name}`, `samples: unknown sound "${name}"`); return null; }
|
|
165
|
+
const midi = pitchOf({ note, freq });
|
|
166
|
+
if (e.kind === 'pitched') {
|
|
167
|
+
const key = nearestKey(e.keys, midi ?? DEFAULT_KEY);
|
|
168
|
+
return { name, url: key.url, rate: midi === undefined ? 1 : 2 ** ((midi - key.midi) / 12) };
|
|
169
|
+
}
|
|
170
|
+
return { name, url: e.urls[wrapIndex(n, e.urls.length)], rate: midi === undefined ? 1 : 2 ** ((midi - UNPITCHED_REF) / 12) };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function evict(keep) {
|
|
174
|
+
for (const [url, c] of cache) {
|
|
175
|
+
if (bytes <= budgetBytes) break;
|
|
176
|
+
if (c.state !== 'ready' || url === keep) continue;
|
|
177
|
+
cache.delete(url);
|
|
178
|
+
bytes -= c.bytes;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function load(url, entry) {
|
|
183
|
+
entry.state = 'loading';
|
|
184
|
+
entry.promise = (async () => {
|
|
185
|
+
try {
|
|
186
|
+
if (!ctx) throw new Error('samples: no AudioContext to decode with');
|
|
187
|
+
const data = await (await fetchOk(url)).arrayBuffer();
|
|
188
|
+
const buffer = await ctx.decodeAudioData(data);
|
|
189
|
+
if (cache.get(url) !== entry) return buffer; // cleared meanwhile
|
|
190
|
+
Object.assign(entry, { state: 'ready', buffer, bytes: bufferBytes(buffer), failures: 0 });
|
|
191
|
+
bytes += entry.bytes;
|
|
192
|
+
evict(url);
|
|
193
|
+
return buffer;
|
|
194
|
+
} catch (err) {
|
|
195
|
+
Object.assign(entry, { state: 'failed', failures: entry.failures + 1, failedAt: now() });
|
|
196
|
+
warnOnce(`url:${url}`, `samples: failed to load ${url}: ${err.message}`);
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
})();
|
|
200
|
+
return entry.promise;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function bufferFor(url) {
|
|
204
|
+
let c = cache.get(url);
|
|
205
|
+
if (c) { cache.delete(url); cache.set(url, c); } // touch
|
|
206
|
+
else { c = { state: 'new', failures: 0 }; cache.set(url, c); }
|
|
207
|
+
if (c.state === 'ready') return Promise.resolve(c.buffer);
|
|
208
|
+
if (c.state === 'loading') return c.promise;
|
|
209
|
+
if (c.state === 'failed') {
|
|
210
|
+
const wait = Math.min(retryMs * 2 ** (c.failures - 1), maxRetryMs);
|
|
211
|
+
if (now() - c.failedAt < wait) return Promise.resolve(null);
|
|
212
|
+
}
|
|
213
|
+
return load(url, c);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Interface for the playback layer: never rejects, null when nothing plays.
|
|
217
|
+
const sampleSource = {
|
|
218
|
+
getBuffer(controls) {
|
|
219
|
+
const r = resolve(controls);
|
|
220
|
+
return r ? bufferFor(r.url) : Promise.resolve(null);
|
|
221
|
+
},
|
|
222
|
+
has: (s, bank) => sounds.has(soundName(s, bank)),
|
|
223
|
+
resolve,
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
// Fetch every sound the pattern plays in [from, from + cycles).
|
|
227
|
+
async function preload(pattern, cycles = 1, from = 0) {
|
|
228
|
+
const urls = new Set();
|
|
229
|
+
for (const hap of pattern.queryArc(from, from + cycles)) {
|
|
230
|
+
const v = hap.value;
|
|
231
|
+
if (!v || typeof v !== 'object' || typeof v.s !== 'string') continue;
|
|
232
|
+
if (!sounds.has(soundName(v.s, v.bank))) continue;
|
|
233
|
+
const r = resolve(v);
|
|
234
|
+
if (r) urls.add(r.url);
|
|
235
|
+
}
|
|
236
|
+
const bufs = await Promise.all([...urls].map(bufferFor));
|
|
237
|
+
return bufs.filter(Boolean).length;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return {
|
|
241
|
+
samples, sampleSource, resolve, preload,
|
|
242
|
+
getBuffer: sampleSource.getBuffer, has: sampleSource.has,
|
|
243
|
+
setAudioContext(c) { ctx = c; },
|
|
244
|
+
hasAudioContext: () => ctx !== null,
|
|
245
|
+
names: () => [...sounds.keys()],
|
|
246
|
+
stats: () => ({ sounds: sounds.size, cached: cache.size, bytes, budgetBytes }),
|
|
247
|
+
clear() { cache.clear(); bytes = 0; warned.clear(); },
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Default bank: created by configureSamples, fed by samples() from user code.
|
|
252
|
+
let defaultBank = null;
|
|
253
|
+
|
|
254
|
+
// Set up the default bank (audioContext, fetch, budget …) and route samples()
|
|
255
|
+
// to it; sources registered before this call are loaded now.
|
|
256
|
+
export async function configureSamples(opts = {}) {
|
|
257
|
+
defaultBank = createSampleBank(opts);
|
|
258
|
+
setSamplesLoader(defaultBank.samples);
|
|
259
|
+
await Promise.all(getSampleSources().map(({ source, baseUrl }) => defaultBank.samples(source, baseUrl)));
|
|
260
|
+
return defaultBank;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export const getSampleBank = () => defaultBank;
|
|
264
|
+
|
|
265
|
+
// Module-level view of the default bank for the playback layer.
|
|
266
|
+
export const sampleSource = {
|
|
267
|
+
getBuffer: (controls) => (defaultBank ? defaultBank.getBuffer(controls) : Promise.resolve(null)),
|
|
268
|
+
has: (s, bank) => (defaultBank ? defaultBank.has(s, bank) : false),
|
|
269
|
+
resolve: (controls) => (defaultBank ? defaultBank.resolve(controls) : null),
|
|
270
|
+
// Fetch what `pattern` plays in [from, from + cycles) (docs/improvements.md 5).
|
|
271
|
+
preload: (pattern, cycles, from) => (defaultBank ? defaultBank.preload(pattern, cycles, from) : Promise.resolve(0)),
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
export const preload = (pattern, cycles, from) => (defaultBank ? defaultBank.preload(pattern, cycles, from) : Promise.resolve(0));
|