@codexo/exojs-audio-fx 0.15.3 → 0.16.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.
Files changed (114) hide show
  1. package/dist/esm/AudioAnalyser.d.ts +4 -3
  2. package/dist/esm/AudioAnalyser.d.ts.map +1 -0
  3. package/dist/esm/AudioAnalyser.js +365 -468
  4. package/dist/esm/AudioAnalyser.js.map +1 -1
  5. package/dist/esm/BeatDetector.d.ts +16 -15
  6. package/dist/esm/BeatDetector.d.ts.map +1 -0
  7. package/dist/esm/BeatDetector.js +370 -428
  8. package/dist/esm/BeatDetector.js.map +1 -1
  9. package/dist/esm/dsp/fft.d.ts +5 -5
  10. package/dist/esm/dsp/fft.d.ts.map +1 -0
  11. package/dist/esm/dsp/mel.d.ts +6 -6
  12. package/dist/esm/dsp/mel.d.ts.map +1 -0
  13. package/dist/esm/dsp/mel.js +55 -64
  14. package/dist/esm/dsp/mel.js.map +1 -1
  15. package/dist/esm/dsp/tempogram.d.ts +60 -20
  16. package/dist/esm/dsp/tempogram.d.ts.map +1 -0
  17. package/dist/esm/effects/AutoWahEffect.d.ts +3 -2
  18. package/dist/esm/effects/AutoWahEffect.d.ts.map +1 -0
  19. package/dist/esm/effects/AutoWahEffect.js +210 -237
  20. package/dist/esm/effects/AutoWahEffect.js.map +1 -1
  21. package/dist/esm/effects/BitCrusherEffect.d.ts +3 -2
  22. package/dist/esm/effects/BitCrusherEffect.d.ts.map +1 -0
  23. package/dist/esm/effects/BitCrusherEffect.js +72 -70
  24. package/dist/esm/effects/BitCrusherEffect.js.map +1 -1
  25. package/dist/esm/effects/ChorusEffect.d.ts +2 -1
  26. package/dist/esm/effects/ChorusEffect.d.ts.map +1 -0
  27. package/dist/esm/effects/ChorusEffect.js +132 -150
  28. package/dist/esm/effects/ChorusEffect.js.map +1 -1
  29. package/dist/esm/effects/CompressorEffect.d.ts +2 -1
  30. package/dist/esm/effects/CompressorEffect.d.ts.map +1 -0
  31. package/dist/esm/effects/CompressorEffect.js +104 -118
  32. package/dist/esm/effects/CompressorEffect.js.map +1 -1
  33. package/dist/esm/effects/ConvolutionEffect.d.ts +10 -5
  34. package/dist/esm/effects/ConvolutionEffect.d.ts.map +1 -0
  35. package/dist/esm/effects/ConvolutionEffect.js +208 -189
  36. package/dist/esm/effects/ConvolutionEffect.js.map +1 -1
  37. package/dist/esm/effects/DelayEffect.d.ts +1 -0
  38. package/dist/esm/effects/DelayEffect.d.ts.map +1 -0
  39. package/dist/esm/effects/DelayEffect.js +105 -109
  40. package/dist/esm/effects/DelayEffect.js.map +1 -1
  41. package/dist/esm/effects/DistortionEffect.d.ts +4 -3
  42. package/dist/esm/effects/DistortionEffect.d.ts.map +1 -0
  43. package/dist/esm/effects/DistortionEffect.js +190 -195
  44. package/dist/esm/effects/DistortionEffect.js.map +1 -1
  45. package/dist/esm/effects/DuckingEffect.d.ts +3 -2
  46. package/dist/esm/effects/DuckingEffect.d.ts.map +1 -0
  47. package/dist/esm/effects/DuckingEffect.js +91 -172
  48. package/dist/esm/effects/DuckingEffect.js.map +1 -1
  49. package/dist/esm/effects/EqualizerEffect.d.ts +1 -0
  50. package/dist/esm/effects/EqualizerEffect.d.ts.map +1 -0
  51. package/dist/esm/effects/EqualizerEffect.js +120 -133
  52. package/dist/esm/effects/EqualizerEffect.js.map +1 -1
  53. package/dist/esm/effects/FlangerEffect.d.ts +7 -6
  54. package/dist/esm/effects/FlangerEffect.d.ts.map +1 -0
  55. package/dist/esm/effects/FlangerEffect.js +172 -201
  56. package/dist/esm/effects/FlangerEffect.js.map +1 -1
  57. package/dist/esm/effects/GranularEffect.d.ts +3 -2
  58. package/dist/esm/effects/GranularEffect.d.ts.map +1 -0
  59. package/dist/esm/effects/GranularEffect.js +100 -95
  60. package/dist/esm/effects/GranularEffect.js.map +1 -1
  61. package/dist/esm/effects/LimiterEffect.d.ts +1 -0
  62. package/dist/esm/effects/LimiterEffect.d.ts.map +1 -0
  63. package/dist/esm/effects/LimiterEffect.js +182 -194
  64. package/dist/esm/effects/LimiterEffect.js.map +1 -1
  65. package/dist/esm/effects/PhaserEffect.d.ts +2 -1
  66. package/dist/esm/effects/PhaserEffect.d.ts.map +1 -0
  67. package/dist/esm/effects/PhaserEffect.js +214 -254
  68. package/dist/esm/effects/PhaserEffect.js.map +1 -1
  69. package/dist/esm/effects/PingPongDelayEffect.d.ts +2 -1
  70. package/dist/esm/effects/PingPongDelayEffect.d.ts.map +1 -0
  71. package/dist/esm/effects/PingPongDelayEffect.js +172 -185
  72. package/dist/esm/effects/PingPongDelayEffect.js.map +1 -1
  73. package/dist/esm/effects/PitchShiftEffect.d.ts +3 -2
  74. package/dist/esm/effects/PitchShiftEffect.d.ts.map +1 -0
  75. package/dist/esm/effects/PitchShiftEffect.js +60 -60
  76. package/dist/esm/effects/PitchShiftEffect.js.map +1 -1
  77. package/dist/esm/effects/ReverbEffect.d.ts +2 -1
  78. package/dist/esm/effects/ReverbEffect.d.ts.map +1 -0
  79. package/dist/esm/effects/ReverbEffect.js +113 -117
  80. package/dist/esm/effects/ReverbEffect.js.map +1 -1
  81. package/dist/esm/effects/RingModulatorEffect.d.ts +4 -3
  82. package/dist/esm/effects/RingModulatorEffect.d.ts.map +1 -0
  83. package/dist/esm/effects/RingModulatorEffect.js +153 -161
  84. package/dist/esm/effects/RingModulatorEffect.js.map +1 -1
  85. package/dist/esm/effects/TremoloEffect.d.ts +1 -0
  86. package/dist/esm/effects/TremoloEffect.d.ts.map +1 -0
  87. package/dist/esm/effects/TremoloEffect.js +193 -201
  88. package/dist/esm/effects/TremoloEffect.js.map +1 -1
  89. package/dist/esm/effects/VocoderEffect.d.ts +2 -1
  90. package/dist/esm/effects/VocoderEffect.d.ts.map +1 -0
  91. package/dist/esm/effects/VocoderEffect.js +69 -80
  92. package/dist/esm/effects/VocoderEffect.js.map +1 -1
  93. package/dist/esm/index.d.ts +2 -1
  94. package/dist/esm/index.d.ts.map +1 -0
  95. package/dist/esm/index.js +23 -22
  96. package/dist/esm/worklets/beat-detector.worklet.js +5 -1162
  97. package/dist/esm/worklets/beat-detector.worklet.js.map +1 -1
  98. package/dist/esm/worklets/bit-crusher.worklet.js +5 -44
  99. package/dist/esm/worklets/bit-crusher.worklet.js.map +1 -1
  100. package/dist/esm/worklets/ducking.worklet.js +6 -0
  101. package/dist/esm/worklets/ducking.worklet.js.map +1 -0
  102. package/dist/esm/worklets/granular.worklet.js +5 -97
  103. package/dist/esm/worklets/granular.worklet.js.map +1 -1
  104. package/dist/esm/worklets/pitch-shift.worklet.js +5 -128
  105. package/dist/esm/worklets/pitch-shift.worklet.js.map +1 -1
  106. package/dist/esm/worklets/vocoder.worklet.js +5 -93
  107. package/dist/esm/worklets/vocoder.worklet.js.map +1 -1
  108. package/package.json +7 -7
  109. package/dist/esm/index.js.map +0 -1
  110. package/dist/esm/worklets/beat-detector.worklet.d.ts +0 -1
  111. package/dist/esm/worklets/bit-crusher.worklet.d.ts +0 -1
  112. package/dist/esm/worklets/granular.worklet.d.ts +0 -1
  113. package/dist/esm/worklets/pitch-shift.worklet.d.ts +0 -1
  114. package/dist/esm/worklets/vocoder.worklet.d.ts +0 -1
@@ -1,472 +1,369 @@
1
- import { onAudioContextReady, isAudioContextReady, getAudioContext } from '@codexo/exojs';
2
- import { buildMelFilterbank } from './dsp/mel.js';
1
+ import { buildMelFilterbank } from "./dsp/mel.js";
2
+ import { getAudioContext, isAudioContextReady, onAudioContextReady } from "@codexo/exojs";
3
3
 
4
+ //#region src/AudioAnalyser.ts
4
5
  /**
5
- * Lightweight visualisation analyser backed by a Web Audio AnalyserNode.
6
- *
7
- * Accepts any of: AudioBus, Voice, MediaStream, AudioNode, or null. The tap is
8
- * a parallel branch — it does not affect the source's main routing. Tap a bus
9
- * for a whole submix, or an individual {@link Voice} (its `output` node) for a
10
- * single playing instance.
11
- */
12
- class AudioAnalyser {
13
- _analyser = null;
14
- _options;
15
- _source = null;
16
- _tapSource = null;
17
- _streamSource = null;
18
- _pendingSourceSetup = null;
19
- _onAudioContextReady = (ctx) => {
20
- onAudioContextReady.remove(this._onAudioContextReady);
21
- this._setupAnalyser(ctx);
22
- };
23
- // Pre-allocated buffers
24
- _byteSpectrum;
25
- _floatSpectrum;
26
- _byteWaveform;
27
- _floatWaveform;
28
- // Cached mel/log filterbanks. Key: `${bands}|${fMin}|${fMax}|${fftSize}`.
29
- // Filterbank construction is non-trivial; caching avoids per-frame allocation.
30
- _melCache = new Map();
31
- _logCache = new Map();
32
- /**
33
- * Create an `AudioAnalyser` with the given options. The underlying
34
- * `AnalyserNode` is created immediately if the `AudioContext` is already
35
- * running, or deferred until {@link onAudioContextReady} fires.
36
- */
37
- constructor(options) {
38
- this._options = {
39
- fftSize: options?.fftSize ?? 2048,
40
- smoothingTimeConstant: options?.smoothingTimeConstant ?? 0.8,
41
- minDecibels: options?.minDecibels ?? -100,
42
- maxDecibels: options?.maxDecibels ?? -30,
43
- source: options?.source ?? null,
44
- };
45
- const binCount = this._options.fftSize >> 1;
46
- this._byteSpectrum = new Uint8Array(binCount);
47
- this._floatSpectrum = new Float32Array(binCount);
48
- this._byteWaveform = new Uint8Array(binCount);
49
- this._floatWaveform = new Float32Array(binCount);
50
- if (isAudioContextReady()) {
51
- this._setupAnalyser(getAudioContext());
52
- }
53
- else {
54
- onAudioContextReady.add(this._onAudioContextReady);
55
- }
56
- if (options?.source !== undefined && options.source !== null) {
57
- this.source = options.source;
58
- }
59
- }
60
- // -----------------------------------------------------------------------
61
- // Source setter
62
- // -----------------------------------------------------------------------
63
- /**
64
- * The currently tapped audio source, or `null` if none is set.
65
- * Assigning a new value disconnects the previous tap and connects the new
66
- * source as a parallel branch without affecting the source's main routing.
67
- */
68
- get source() {
69
- return this._source;
70
- }
71
- set source(value) {
72
- if (value === this._source)
73
- return;
74
- // 1. Disconnect current tap
75
- this._disconnectTap();
76
- this._source = value;
77
- if (value === null)
78
- return;
79
- // 2. Resolve and connect new tap
80
- if (isAudioContextReady()) {
81
- this._pendingSourceSetup = null;
82
- this._connectSource(value, getAudioContext());
83
- }
84
- else {
85
- if (this._pendingSourceSetup !== null) {
86
- onAudioContextReady.remove(this._pendingSourceSetup);
87
- }
88
- const handler = (ctx) => {
89
- onAudioContextReady.remove(handler);
90
- this._pendingSourceSetup = null;
91
- this._connectSource(value, ctx);
92
- };
93
- this._pendingSourceSetup = handler;
94
- onAudioContextReady.add(handler);
95
- }
96
- }
97
- // -----------------------------------------------------------------------
98
- // AnalyserNode property pass-throughs
99
- // -----------------------------------------------------------------------
100
- get fftSize() {
101
- return this._options.fftSize;
102
- }
103
- /** Number of frequency bins available — half of `fftSize`. */
104
- get frequencyBinCount() {
105
- return this._options.fftSize >> 1;
106
- }
107
- get smoothingTimeConstant() {
108
- return this._analyser?.smoothingTimeConstant ?? this._options.smoothingTimeConstant;
109
- }
110
- set smoothingTimeConstant(v) {
111
- this._options.smoothingTimeConstant = v;
112
- if (this._analyser)
113
- this._analyser.smoothingTimeConstant = v;
114
- }
115
- get minDecibels() {
116
- return this._analyser?.minDecibels ?? this._options.minDecibels;
117
- }
118
- set minDecibels(v) {
119
- this._options.minDecibels = v;
120
- if (this._analyser)
121
- this._analyser.minDecibels = v;
122
- }
123
- get maxDecibels() {
124
- return this._analyser?.maxDecibels ?? this._options.maxDecibels;
125
- }
126
- set maxDecibels(v) {
127
- this._options.maxDecibels = v;
128
- if (this._analyser)
129
- this._analyser.maxDecibels = v;
130
- }
131
- // -----------------------------------------------------------------------
132
- // Raw data
133
- // -----------------------------------------------------------------------
134
- /** Fill and return the byte frequency spectrum (0..255 per bin). */
135
- getSpectrum(into) {
136
- const buf = into ?? this._byteSpectrum;
137
- if (this._analyser) {
138
- this._analyser.getByteFrequencyData(buf);
139
- }
140
- else {
141
- buf.fill(0);
142
- }
143
- return buf;
144
- }
145
- /** Fill and return the float frequency spectrum (dB per bin). */
146
- getSpectrumFloat(into) {
147
- const buf = into ?? this._floatSpectrum;
148
- if (this._analyser) {
149
- this._analyser.getFloatFrequencyData(buf);
150
- }
151
- else {
152
- buf.fill(0);
153
- }
154
- return buf;
155
- }
156
- /** Fill and return the byte time-domain waveform (0..255 per sample). */
157
- getWaveform(into) {
158
- const buf = into ?? this._byteWaveform;
159
- if (this._analyser) {
160
- this._analyser.getByteTimeDomainData(buf);
161
- }
162
- else {
163
- buf.fill(0);
164
- }
165
- return buf;
166
- }
167
- /** Fill and return the float time-domain waveform (-1..1 per sample). */
168
- getWaveformFloat(into) {
169
- const buf = into ?? this._floatWaveform;
170
- if (this._analyser) {
171
- this._analyser.getFloatTimeDomainData(buf);
172
- }
173
- else {
174
- buf.fill(0);
175
- }
176
- return buf;
177
- }
178
- // -----------------------------------------------------------------------
179
- // Convenience helpers
180
- // -----------------------------------------------------------------------
181
- /**
182
- * Return the mean energy of frequency bins in the given Hz range, normalised 0..1.
183
- * Uses the byte spectrum (0..255), normalised by dividing by 255.
184
- */
185
- getBandEnergy(fromHz, toHz) {
186
- if (!this._analyser)
187
- return 0;
188
- const ctx = getAudioContext();
189
- const nyquist = ctx.sampleRate / 2;
190
- const binCount = this.frequencyBinCount;
191
- const fromBin = Math.max(0, Math.min(binCount - 1, Math.round((fromHz / nyquist) * binCount)));
192
- const toBin = Math.max(0, Math.min(binCount - 1, Math.round((toHz / nyquist) * binCount)));
193
- const lo = Math.min(fromBin, toBin);
194
- const hi = Math.max(fromBin, toBin);
195
- const spectrum = this.getSpectrum();
196
- let sum = 0;
197
- const count = hi - lo + 1;
198
- for (let i = lo; i <= hi; i++) {
199
- sum += spectrum[i];
200
- }
201
- return sum / (count * 255);
202
- }
203
- /** Return low (0-250 Hz), mid (250-2 kHz), and high (2 k-20 kHz) band energies (0..1 each). */
204
- getLowMidHigh() {
205
- return {
206
- low: this.getBandEnergy(0, 250),
207
- mid: this.getBandEnergy(250, 2000),
208
- high: this.getBandEnergy(2000, 20000),
209
- };
210
- }
211
- /** Return overall RMS energy across all bins, normalised 0..1. */
212
- getRms() {
213
- if (!this._analyser)
214
- return 0;
215
- const ctx = getAudioContext();
216
- const nyquist = ctx.sampleRate / 2;
217
- return this.getBandEnergy(0, nyquist);
218
- }
219
- // -----------------------------------------------------------------------
220
- // Spectrum mapping (mel / log scaling)
221
- //
222
- // The raw FFT bins from AnalyserNode are linearly distributed across
223
- // 0..nyquist, which gives bass a few bins and treble hundreds. For
224
- // visualisations you typically want perceptually-weighted spacing.
225
- //
226
- // Both `getSpectrumMel` and `getSpectrumLog` operate on the byte-domain
227
- // spectrum (0..255) and produce byte output by default. The float
228
- // variants operate on dBFS values and produce float output.
229
- //
230
- // Filterbanks are cached on the analyser; they only rebuild when fftSize
231
- // or the (bands, fMin, fMax) parameters change.
232
- // -----------------------------------------------------------------------
233
- /**
234
- * Mel-scaled spectrum, byte domain (0..255). Output length = `bands`.
235
- * Each output bin is a triangular-weighted sum of the linear FFT bins
236
- * underneath it, mel-spaced from `fMin` to `fMax`.
237
- */
238
- getSpectrumMel(into, options) {
239
- const bandCount = options?.bands ?? 32;
240
- const out = into ?? new Uint8Array(bandCount);
241
- const filterbank = this._getMelFilterbank(bandCount, options?.fMin ?? 20, options?.fMax ?? 20000);
242
- if (!this._analyser || filterbank === null) {
243
- out.fill(0);
244
- return out;
245
- }
246
- this._analyser.getByteFrequencyData(this._byteSpectrum);
247
- applyFilterbank(this._byteSpectrum, filterbank, out);
248
- return out;
249
- }
250
- /** Mel-scaled spectrum, float domain (dBFS values). Output length = `bands`. */
251
- getSpectrumMelFloat(into, options) {
252
- const bandCount = options?.bands ?? 32;
253
- const out = into ?? new Float32Array(bandCount);
254
- const filterbank = this._getMelFilterbank(bandCount, options?.fMin ?? 20, options?.fMax ?? 20000);
255
- if (!this._analyser || filterbank === null) {
256
- out.fill(0);
257
- return out;
258
- }
259
- this._analyser.getFloatFrequencyData(this._floatSpectrum);
260
- applyFilterbank(this._floatSpectrum, filterbank, out);
261
- return out;
262
- }
263
- /**
264
- * Log-scaled spectrum, byte domain (0..255). Output length = `bands`.
265
- * Bins are spaced so each output covers an equal fraction of the
266
- * `log2(fMax / fMin)` octave range — useful when you want a
267
- * frequency-axis visualization where each octave gets the same width.
268
- */
269
- getSpectrumLog(into, options) {
270
- const bandCount = options?.bands ?? 32;
271
- const out = into ?? new Uint8Array(bandCount);
272
- const ranges = this._getLogRanges(bandCount, options?.fMin ?? 20, options?.fMax ?? 20000);
273
- if (!this._analyser || ranges === null) {
274
- out.fill(0);
275
- return out;
276
- }
277
- this._analyser.getByteFrequencyData(this._byteSpectrum);
278
- applyLogRanges(this._byteSpectrum, ranges, out);
279
- return out;
280
- }
281
- /** Log-scaled spectrum, float domain (dBFS values). Output length = `bands`. */
282
- getSpectrumLogFloat(into, options) {
283
- const bandCount = options?.bands ?? 32;
284
- const out = into ?? new Float32Array(bandCount);
285
- const ranges = this._getLogRanges(bandCount, options?.fMin ?? 20, options?.fMax ?? 20000);
286
- if (!this._analyser || ranges === null) {
287
- out.fill(0);
288
- return out;
289
- }
290
- this._analyser.getFloatFrequencyData(this._floatSpectrum);
291
- applyLogRanges(this._floatSpectrum, ranges, out);
292
- return out;
293
- }
294
- // -----------------------------------------------------------------------
295
- // Lifecycle
296
- // -----------------------------------------------------------------------
297
- /**
298
- * Disconnect the analyser tap, release the internal `AnalyserNode`, and
299
- * cancel any pending setup callbacks. Call when the analyser is no longer
300
- * needed to avoid memory leaks.
301
- */
302
- destroy() {
303
- onAudioContextReady.remove(this._onAudioContextReady);
304
- if (this._pendingSourceSetup !== null) {
305
- onAudioContextReady.remove(this._pendingSourceSetup);
306
- this._pendingSourceSetup = null;
307
- }
308
- this._disconnectTap();
309
- this._analyser?.disconnect();
310
- this._analyser = null;
311
- this._source = null;
312
- }
313
- // -----------------------------------------------------------------------
314
- // Private helpers
315
- // -----------------------------------------------------------------------
316
- _getMelFilterbank(bands, fMin, fMax) {
317
- if (!this._analyser)
318
- return null;
319
- const ctx = getAudioContext();
320
- const fftSize = this._options.fftSize;
321
- const clampedFmax = Math.min(fMax, ctx.sampleRate / 2);
322
- const key = `${bands}|${fMin}|${clampedFmax}|${fftSize}`;
323
- let cached = this._melCache.get(key);
324
- if (cached === undefined) {
325
- cached = buildMelFilterbank(bands, fMin, clampedFmax, fftSize, ctx.sampleRate);
326
- this._melCache.set(key, cached);
327
- }
328
- return cached;
329
- }
330
- _getLogRanges(bands, fMin, fMax) {
331
- if (!this._analyser)
332
- return null;
333
- const ctx = getAudioContext();
334
- const fftSize = this._options.fftSize;
335
- const clampedFmax = Math.min(fMax, ctx.sampleRate / 2);
336
- const key = `${bands}|${fMin}|${clampedFmax}|${fftSize}`;
337
- let cached = this._logCache.get(key);
338
- if (cached === undefined) {
339
- cached = buildLogRanges(bands, fMin, clampedFmax, fftSize, ctx.sampleRate);
340
- this._logCache.set(key, cached);
341
- }
342
- return cached;
343
- }
344
- _setupAnalyser(audioContext) {
345
- const node = audioContext.createAnalyser();
346
- node.fftSize = this._options.fftSize;
347
- node.minDecibels = this._options.minDecibels;
348
- node.maxDecibels = this._options.maxDecibels;
349
- node.smoothingTimeConstant = this._options.smoothingTimeConstant;
350
- this._analyser = node;
351
- // If a source was set before the context was ready, connect it now.
352
- if (this._source !== null) {
353
- this._connectSource(this._source, audioContext);
354
- }
355
- }
356
- _connectSource(source, audioContext) {
357
- if (!this._analyser)
358
- return;
359
- const tap = this._resolveToAudioNode(source, audioContext);
360
- if (!tap) {
361
- // AudioBus not ready yet — defer via its onceSetup
362
- this._deferConnectionViaBus(source);
363
- return;
364
- }
365
- this._tapSource = tap;
366
- tap.connect(this._analyser);
367
- }
368
- _resolveToAudioNode(source, audioContext) {
369
- if (source === null)
370
- return null;
371
- // MediaStream — detect by getTracks (duck-type, since AudioNode also doesn't exist in jsdom)
372
- const asStream = source;
373
- if (typeof asStream.getTracks === 'function') {
374
- if (this._streamSource) {
375
- this._streamSource.disconnect();
376
- this._streamSource = null;
377
- }
378
- const msNode = audioContext.createMediaStreamSource(source);
379
- this._streamSource = msNode;
380
- return msNode;
381
- }
382
- // AudioBus — has _getOutputNode (checked first since bus nodes also have connect/disconnect)
383
- const asBus = source;
384
- if (typeof asBus._getOutputNode === 'function') {
385
- return asBus._getOutputNode();
386
- }
387
- // Voice — tap its output node
388
- const asVoice = source;
389
- if ('output' in asVoice && asVoice.output) {
390
- return asVoice.output;
391
- }
392
- // Raw AudioNode — duck-type: has connect & disconnect
393
- const asNode = source;
394
- if (typeof asNode.connect === 'function' && typeof asNode.disconnect === 'function') {
395
- return source;
396
- }
397
- return null;
398
- }
399
- _deferConnectionViaBus(source) {
400
- // AudioBus exposes onceSetup
401
- const asBus = source;
402
- if (typeof asBus.onceSetup === 'function') {
403
- asBus.onceSetup(() => {
404
- if (this._source === source && this._analyser && isAudioContextReady()) {
405
- this._connectSource(source, getAudioContext());
406
- }
407
- });
408
- return;
409
- }
410
- // Otherwise retry once the audioContext is ready (same signal).
411
- onAudioContextReady.once(() => {
412
- if (this._source === source && this._analyser && isAudioContextReady()) {
413
- this._connectSource(source, getAudioContext());
414
- }
415
- });
416
- }
417
- _disconnectTap() {
418
- if (this._tapSource && this._analyser) {
419
- try {
420
- this._tapSource.disconnect(this._analyser);
421
- }
422
- catch {
423
- // Ignore if already disconnected
424
- }
425
- }
426
- this._tapSource = null;
427
- // Clean up cached stream source
428
- if (this._streamSource) {
429
- this._streamSource.disconnect();
430
- this._streamSource = null;
431
- }
432
- }
433
- }
434
- function buildLogRanges(bandCount, fMin, fMax, fftSize, sampleRate) {
435
- const binCount = fftSize >> 1;
436
- const nyquist = sampleRate / 2;
437
- const logMin = Math.log(fMin);
438
- const logMax = Math.log(fMax);
439
- const ranges = [];
440
- for (let b = 0; b < bandCount; b++) {
441
- const lowHz = Math.exp(logMin + ((logMax - logMin) * b) / bandCount);
442
- const highHz = Math.exp(logMin + ((logMax - logMin) * (b + 1)) / bandCount);
443
- const startBin = Math.max(0, Math.min(binCount - 1, Math.floor((lowHz / nyquist) * binCount)));
444
- const endBin = Math.max(startBin, Math.min(binCount - 1, Math.ceil((highHz / nyquist) * binCount) - 1));
445
- ranges.push({ startBin, endBin });
446
- }
447
- return ranges;
448
- }
449
- function applyFilterbank(spectrum, bands, out) {
450
- for (let b = 0; b < bands.length; b++) {
451
- const { startBin, weights } = bands[b];
452
- let sum = 0;
453
- for (let i = 0; i < weights.length; i++) {
454
- sum += spectrum[startBin + i] * weights[i];
455
- }
456
- out[b] = sum;
457
- }
458
- }
459
- function applyLogRanges(spectrum, ranges, out) {
460
- for (let b = 0; b < ranges.length; b++) {
461
- const { startBin, endBin } = ranges[b];
462
- let sum = 0;
463
- const count = endBin - startBin + 1;
464
- for (let i = startBin; i <= endBin; i++) {
465
- sum += spectrum[i];
466
- }
467
- out[b] = sum / count;
468
- }
469
- }
6
+ * Lightweight visualisation analyser backed by a Web Audio AnalyserNode.
7
+ *
8
+ * Accepts any of: AudioBus, Voice, MediaStream, AudioNode, or null. The tap is
9
+ * a parallel branch - it does not affect the source's main routing. Tap a bus
10
+ * for a whole submix, or an individual {@link Voice} (its `output` node) for a
11
+ * single playing instance.
12
+ */
13
+ var AudioAnalyser = class {
14
+ _analyser = null;
15
+ _options;
16
+ _source = null;
17
+ _tapSource = null;
18
+ _streamSource = null;
19
+ _pendingSourceSetup = null;
20
+ _onAudioContextReady = (ctx) => {
21
+ onAudioContextReady.remove(this._onAudioContextReady);
22
+ this._setupAnalyser(ctx);
23
+ };
24
+ _byteSpectrum;
25
+ _floatSpectrum;
26
+ _byteWaveform;
27
+ _floatWaveform;
28
+ _melCache = /* @__PURE__ */ new Map();
29
+ _logCache = /* @__PURE__ */ new Map();
30
+ /**
31
+ * Create an `AudioAnalyser` with the given options. The underlying
32
+ * `AnalyserNode` is created immediately if the `AudioContext` is already
33
+ * running, or deferred until {@link onAudioContextReady} fires.
34
+ */
35
+ constructor(options) {
36
+ this._options = {
37
+ fftSize: options?.fftSize ?? 2048,
38
+ smoothingTimeConstant: options?.smoothingTimeConstant ?? .8,
39
+ minDecibels: options?.minDecibels ?? -100,
40
+ maxDecibels: options?.maxDecibels ?? -30,
41
+ source: options?.source ?? null
42
+ };
43
+ const binCount = this._options.fftSize >> 1;
44
+ this._byteSpectrum = new Uint8Array(binCount);
45
+ this._floatSpectrum = new Float32Array(binCount);
46
+ this._byteWaveform = new Uint8Array(binCount);
47
+ this._floatWaveform = new Float32Array(binCount);
48
+ if (isAudioContextReady()) this._setupAnalyser(getAudioContext());
49
+ else onAudioContextReady.add(this._onAudioContextReady);
50
+ if (options?.source !== void 0 && options.source !== null) this.source = options.source;
51
+ }
52
+ /**
53
+ * The currently tapped audio source, or `null` if none is set.
54
+ * Assigning a new value disconnects the previous tap and connects the new
55
+ * source as a parallel branch without affecting the source's main routing.
56
+ */
57
+ get source() {
58
+ return this._source;
59
+ }
60
+ set source(value) {
61
+ if (value === this._source) return;
62
+ this._disconnectTap();
63
+ this._source = value;
64
+ if (value === null) return;
65
+ if (isAudioContextReady()) {
66
+ this._pendingSourceSetup = null;
67
+ this._connectSource(value, getAudioContext());
68
+ } else {
69
+ if (this._pendingSourceSetup !== null) onAudioContextReady.remove(this._pendingSourceSetup);
70
+ const handler = (ctx) => {
71
+ onAudioContextReady.remove(handler);
72
+ this._pendingSourceSetup = null;
73
+ this._connectSource(value, ctx);
74
+ };
75
+ this._pendingSourceSetup = handler;
76
+ onAudioContextReady.add(handler);
77
+ }
78
+ }
79
+ get fftSize() {
80
+ return this._options.fftSize;
81
+ }
82
+ /** Number of frequency bins available - half of `fftSize`. */
83
+ get frequencyBinCount() {
84
+ return this._options.fftSize >> 1;
85
+ }
86
+ get smoothingTimeConstant() {
87
+ return this._analyser?.smoothingTimeConstant ?? this._options.smoothingTimeConstant;
88
+ }
89
+ set smoothingTimeConstant(v) {
90
+ this._options.smoothingTimeConstant = v;
91
+ if (this._analyser) this._analyser.smoothingTimeConstant = v;
92
+ }
93
+ get minDecibels() {
94
+ return this._analyser?.minDecibels ?? this._options.minDecibels;
95
+ }
96
+ set minDecibels(v) {
97
+ this._options.minDecibels = v;
98
+ if (this._analyser) this._analyser.minDecibels = v;
99
+ }
100
+ get maxDecibels() {
101
+ return this._analyser?.maxDecibels ?? this._options.maxDecibels;
102
+ }
103
+ set maxDecibels(v) {
104
+ this._options.maxDecibels = v;
105
+ if (this._analyser) this._analyser.maxDecibels = v;
106
+ }
107
+ /** Fill and return the byte frequency spectrum (0..255 per bin). */
108
+ getSpectrum(into) {
109
+ const buf = into ?? this._byteSpectrum;
110
+ if (this._analyser) this._analyser.getByteFrequencyData(buf);
111
+ else buf.fill(0);
112
+ return buf;
113
+ }
114
+ /** Fill and return the float frequency spectrum (dB per bin). */
115
+ getSpectrumFloat(into) {
116
+ const buf = into ?? this._floatSpectrum;
117
+ if (this._analyser) this._analyser.getFloatFrequencyData(buf);
118
+ else buf.fill(0);
119
+ return buf;
120
+ }
121
+ /** Fill and return the byte time-domain waveform (0..255 per sample). */
122
+ getWaveform(into) {
123
+ const buf = into ?? this._byteWaveform;
124
+ if (this._analyser) this._analyser.getByteTimeDomainData(buf);
125
+ else buf.fill(0);
126
+ return buf;
127
+ }
128
+ /** Fill and return the float time-domain waveform (-1..1 per sample). */
129
+ getWaveformFloat(into) {
130
+ const buf = into ?? this._floatWaveform;
131
+ if (this._analyser) this._analyser.getFloatTimeDomainData(buf);
132
+ else buf.fill(0);
133
+ return buf;
134
+ }
135
+ /**
136
+ * Return the mean energy of frequency bins in the given Hz range, normalised 0..1.
137
+ * Uses the byte spectrum (0..255), normalised by dividing by 255.
138
+ */
139
+ getBandEnergy(fromHz, toHz) {
140
+ if (!this._analyser) return 0;
141
+ const nyquist = getAudioContext().sampleRate / 2;
142
+ const binCount = this.frequencyBinCount;
143
+ const fromBin = Math.max(0, Math.min(binCount - 1, Math.round(fromHz / nyquist * binCount)));
144
+ const toBin = Math.max(0, Math.min(binCount - 1, Math.round(toHz / nyquist * binCount)));
145
+ const lo = Math.min(fromBin, toBin);
146
+ const hi = Math.max(fromBin, toBin);
147
+ const spectrum = this.getSpectrum();
148
+ let sum = 0;
149
+ const count = hi - lo + 1;
150
+ for (let i = lo; i <= hi; i++) sum += spectrum[i];
151
+ return sum / (count * 255);
152
+ }
153
+ /** Return low (0-250 Hz), mid (250-2 kHz), and high (2 k-20 kHz) band energies (0..1 each). */
154
+ getLowMidHigh() {
155
+ return {
156
+ low: this.getBandEnergy(0, 250),
157
+ mid: this.getBandEnergy(250, 2e3),
158
+ high: this.getBandEnergy(2e3, 2e4)
159
+ };
160
+ }
161
+ /** Return overall RMS energy across all bins, normalised 0..1. */
162
+ getRms() {
163
+ if (!this._analyser) return 0;
164
+ const nyquist = getAudioContext().sampleRate / 2;
165
+ return this.getBandEnergy(0, nyquist);
166
+ }
167
+ /**
168
+ * Mel-scaled spectrum, byte domain (0..255). Output length = `bands`.
169
+ * Each output bin is a triangular-weighted sum of the linear FFT bins
170
+ * underneath it, mel-spaced from `fMin` to `fMax`.
171
+ */
172
+ getSpectrumMel(into, options) {
173
+ const bandCount = options?.bands ?? 32;
174
+ const out = into ?? new Uint8Array(bandCount);
175
+ const filterbank = this._getMelFilterbank(bandCount, options?.fMin ?? 20, options?.fMax ?? 2e4);
176
+ if (!this._analyser || filterbank === null) {
177
+ out.fill(0);
178
+ return out;
179
+ }
180
+ this._analyser.getByteFrequencyData(this._byteSpectrum);
181
+ applyFilterbank(this._byteSpectrum, filterbank, out);
182
+ return out;
183
+ }
184
+ /** Mel-scaled spectrum, float domain (dBFS values). Output length = `bands`. */
185
+ getSpectrumMelFloat(into, options) {
186
+ const bandCount = options?.bands ?? 32;
187
+ const out = into ?? new Float32Array(bandCount);
188
+ const filterbank = this._getMelFilterbank(bandCount, options?.fMin ?? 20, options?.fMax ?? 2e4);
189
+ if (!this._analyser || filterbank === null) {
190
+ out.fill(0);
191
+ return out;
192
+ }
193
+ this._analyser.getFloatFrequencyData(this._floatSpectrum);
194
+ applyFilterbank(this._floatSpectrum, filterbank, out);
195
+ return out;
196
+ }
197
+ /**
198
+ * Log-scaled spectrum, byte domain (0..255). Output length = `bands`.
199
+ * Bins are spaced so each output covers an equal fraction of the
200
+ * `log2(fMax / fMin)` octave range - useful when you want a
201
+ * frequency-axis visualization where each octave gets the same width.
202
+ */
203
+ getSpectrumLog(into, options) {
204
+ const bandCount = options?.bands ?? 32;
205
+ const out = into ?? new Uint8Array(bandCount);
206
+ const ranges = this._getLogRanges(bandCount, options?.fMin ?? 20, options?.fMax ?? 2e4);
207
+ if (!this._analyser || ranges === null) {
208
+ out.fill(0);
209
+ return out;
210
+ }
211
+ this._analyser.getByteFrequencyData(this._byteSpectrum);
212
+ applyLogRanges(this._byteSpectrum, ranges, out);
213
+ return out;
214
+ }
215
+ /** Log-scaled spectrum, float domain (dBFS values). Output length = `bands`. */
216
+ getSpectrumLogFloat(into, options) {
217
+ const bandCount = options?.bands ?? 32;
218
+ const out = into ?? new Float32Array(bandCount);
219
+ const ranges = this._getLogRanges(bandCount, options?.fMin ?? 20, options?.fMax ?? 2e4);
220
+ if (!this._analyser || ranges === null) {
221
+ out.fill(0);
222
+ return out;
223
+ }
224
+ this._analyser.getFloatFrequencyData(this._floatSpectrum);
225
+ applyLogRanges(this._floatSpectrum, ranges, out);
226
+ return out;
227
+ }
228
+ /**
229
+ * Disconnect the analyser tap, release the internal `AnalyserNode`, and
230
+ * cancel any pending setup callbacks. Call when the analyser is no longer
231
+ * needed to avoid memory leaks.
232
+ */
233
+ destroy() {
234
+ onAudioContextReady.remove(this._onAudioContextReady);
235
+ if (this._pendingSourceSetup !== null) {
236
+ onAudioContextReady.remove(this._pendingSourceSetup);
237
+ this._pendingSourceSetup = null;
238
+ }
239
+ this._disconnectTap();
240
+ this._analyser?.disconnect();
241
+ this._analyser = null;
242
+ this._source = null;
243
+ }
244
+ _getMelFilterbank(bands, fMin, fMax) {
245
+ if (!this._analyser) return null;
246
+ const ctx = getAudioContext();
247
+ const fftSize = this._options.fftSize;
248
+ const clampedFmax = Math.min(fMax, ctx.sampleRate / 2);
249
+ const key = `${bands}|${fMin}|${clampedFmax}|${fftSize}`;
250
+ let cached = this._melCache.get(key);
251
+ if (cached === void 0) {
252
+ cached = buildMelFilterbank(bands, fMin, clampedFmax, fftSize, ctx.sampleRate);
253
+ this._melCache.set(key, cached);
254
+ }
255
+ return cached;
256
+ }
257
+ _getLogRanges(bands, fMin, fMax) {
258
+ if (!this._analyser) return null;
259
+ const ctx = getAudioContext();
260
+ const fftSize = this._options.fftSize;
261
+ const clampedFmax = Math.min(fMax, ctx.sampleRate / 2);
262
+ const key = `${bands}|${fMin}|${clampedFmax}|${fftSize}`;
263
+ let cached = this._logCache.get(key);
264
+ if (cached === void 0) {
265
+ cached = buildLogRanges(bands, fMin, clampedFmax, fftSize, ctx.sampleRate);
266
+ this._logCache.set(key, cached);
267
+ }
268
+ return cached;
269
+ }
270
+ _setupAnalyser(audioContext) {
271
+ const node = audioContext.createAnalyser();
272
+ node.fftSize = this._options.fftSize;
273
+ node.minDecibels = this._options.minDecibels;
274
+ node.maxDecibels = this._options.maxDecibels;
275
+ node.smoothingTimeConstant = this._options.smoothingTimeConstant;
276
+ this._analyser = node;
277
+ if (this._source !== null) this._connectSource(this._source, audioContext);
278
+ }
279
+ _connectSource(source, audioContext) {
280
+ if (!this._analyser) return;
281
+ const tap = this._resolveToAudioNode(source, audioContext);
282
+ if (!tap) {
283
+ this._deferConnectionViaBus(source);
284
+ return;
285
+ }
286
+ this._tapSource = tap;
287
+ tap.connect(this._analyser);
288
+ }
289
+ _resolveToAudioNode(source, audioContext) {
290
+ if (source === null) return null;
291
+ if (typeof source.getTracks === "function") {
292
+ if (this._streamSource) {
293
+ this._streamSource.disconnect();
294
+ this._streamSource = null;
295
+ }
296
+ const msNode = audioContext.createMediaStreamSource(source);
297
+ this._streamSource = msNode;
298
+ return msNode;
299
+ }
300
+ const asBus = source;
301
+ if (typeof asBus._getOutputNode === "function") return asBus._getOutputNode();
302
+ const asVoice = source;
303
+ if ("output" in asVoice && asVoice.output) return asVoice.output;
304
+ const asNode = source;
305
+ if (typeof asNode.connect === "function" && typeof asNode.disconnect === "function") return source;
306
+ return null;
307
+ }
308
+ _deferConnectionViaBus(source) {
309
+ const asBus = source;
310
+ if (typeof asBus.onceSetup === "function") {
311
+ asBus.onceSetup(() => {
312
+ if (this._source === source && this._analyser && isAudioContextReady()) this._connectSource(source, getAudioContext());
313
+ });
314
+ return;
315
+ }
316
+ onAudioContextReady.once(() => {
317
+ if (this._source === source && this._analyser && isAudioContextReady()) this._connectSource(source, getAudioContext());
318
+ });
319
+ }
320
+ _disconnectTap() {
321
+ if (this._tapSource && this._analyser) try {
322
+ this._tapSource.disconnect(this._analyser);
323
+ } catch {}
324
+ this._tapSource = null;
325
+ if (this._streamSource) {
326
+ this._streamSource.disconnect();
327
+ this._streamSource = null;
328
+ }
329
+ }
330
+ };
331
+ const buildLogRanges = (bandCount, fMin, fMax, fftSize, sampleRate) => {
332
+ const binCount = fftSize >> 1;
333
+ const nyquist = sampleRate / 2;
334
+ const logMin = Math.log(fMin);
335
+ const logMax = Math.log(fMax);
336
+ const ranges = [];
337
+ for (let b = 0; b < bandCount; b++) {
338
+ const lowHz = Math.exp(logMin + (logMax - logMin) * b / bandCount);
339
+ const highHz = Math.exp(logMin + (logMax - logMin) * (b + 1) / bandCount);
340
+ const startBin = Math.max(0, Math.min(binCount - 1, Math.floor(lowHz / nyquist * binCount)));
341
+ const endBin = Math.max(startBin, Math.min(binCount - 1, Math.ceil(highHz / nyquist * binCount) - 1));
342
+ ranges.push({
343
+ startBin,
344
+ endBin
345
+ });
346
+ }
347
+ return ranges;
348
+ };
349
+ const applyFilterbank = (spectrum, bands, out) => {
350
+ for (let b = 0; b < bands.length; b++) {
351
+ const { startBin, weights } = bands[b];
352
+ let sum = 0;
353
+ for (let i = 0; i < weights.length; i++) sum += spectrum[startBin + i] * weights[i];
354
+ out[b] = sum;
355
+ }
356
+ };
357
+ const applyLogRanges = (spectrum, ranges, out) => {
358
+ for (let b = 0; b < ranges.length; b++) {
359
+ const { startBin, endBin } = ranges[b];
360
+ let sum = 0;
361
+ const count = endBin - startBin + 1;
362
+ for (let i = startBin; i <= endBin; i++) sum += spectrum[i];
363
+ out[b] = sum / count;
364
+ }
365
+ };
470
366
 
367
+ //#endregion
471
368
  export { AudioAnalyser };
472
- //# sourceMappingURL=AudioAnalyser.js.map
369
+ //# sourceMappingURL=AudioAnalyser.js.map