@codexo/exojs-audio-fx 0.15.3 → 0.16.1

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 +6 -6
  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,432 +1,374 @@
1
- import { Signal, onAudioContextReady, isAudioContextReady, getAudioContext, registerAudioWorkletProcessor } from '@codexo/exojs';
2
- import { beatDetectorWorkletSource } from './worklets/beat-detector.worklet.js';
1
+ import beat_detector_worklet_default from "./worklets/beat-detector.worklet.js";
2
+ import { Signal, getAudioContext, isAudioContextReady, onAudioContextReady, registerAudioWorkletProcessor } from "@codexo/exojs";
3
3
 
4
- const workletName = 'exojs-beat-detector';
4
+ //#region src/BeatDetector.ts
5
+ const workletName = "exojs-beat-detector";
5
6
  /**
6
- * Real-time tempo + beat tracker. Splits work between the audio-rendering
7
- * thread (an AudioWorklet that runs onset detection, tempogram analysis,
8
- * and parallel 3/4 and 4/4 posterior estimation) and the main thread (this
9
- * class — receives beats, fires Signals, handles configuration and source
10
- * routing).
11
- *
12
- * Accepts a wide range of {@link BeatDetectorSource}s — a bus, an individual
13
- * {@link Voice}, a raw MediaStream, or any AudioNode — and exposes a Signal
14
- * for each notable event:
15
- * - {@link BeatDetector.onBeat} — every detected beat
16
- * - {@link BeatDetector.onDownbeat} — first beat of each bar
17
- * - {@link BeatDetector.onBarStart} — bar boundary
18
- * - {@link BeatDetector.onTempoChange} — when the tracked BPM changes
19
- * - {@link BeatDetector.onBeatPredicted} — look-ahead schedule notice
20
- *
21
- * Early beats arrive with low latency tagged `status: 'provisional'` (after a
22
- * short `minSettlingMs` warm-up, default 400 ms) for snappy visual reactivity,
23
- * then promote to `status: 'locked'` once the tempo grid is trustworthy — a
24
- * single {@link BeatDetector.onBeat} signal carries both via {@link BeatInfo.status}.
25
- * Set `emitProvisionalBeats: false` to receive only locked beats. Time-signature
26
- * detection (3/4 vs 4/4) is on by default; lock to 4/4 by setting
27
- * `enableTimeSignatureDetection: false`.
28
- */
29
- class BeatDetector {
30
- // ---- Signals ----
31
- onBeat = new Signal();
32
- onTempoChange = new Signal();
33
- onDownbeat = new Signal();
34
- onBarStart = new Signal();
35
- onBeatPredicted = new Signal();
36
- // ---- Options ----
37
- // enableTimeSignatureDetection not in Required<> since it has a default; keep as full explicit type
38
- _options;
39
- // ---- Audio plumbing ----
40
- _workletNode = null;
41
- _source = null;
42
- _tapSource = null;
43
- _streamSource = null;
44
- _ready = null;
45
- _pendingSourceSetup = null;
46
- _onAudioContextReady = (ctx) => {
47
- onAudioContextReady.remove(this._onAudioContextReady);
48
- this._setup(ctx);
49
- };
50
- // ---- Cached state from worklet ----
51
- _tempo = 0;
52
- _beatPhase = 0;
53
- _nextBeatTime = 0;
54
- _confidence = 0;
55
- _gridStability = 0;
56
- _tempoCandidates = [];
57
- _rms = 0;
58
- _onsetStrength = 0;
59
- _bandEnergy = { low: 0, mid: 0, high: 0 };
60
- _barPosition = 1;
61
- _barLength = 4;
62
- _timeSignature = { numerator: 4, denominator: 4 };
63
- _nextDownbeatTime = 0;
64
- _lookahead = Object.freeze([]);
65
- /**
66
- * Half-life in seconds for the {@link pulse} envelope. Mutable; default 0.15.
67
- * Smaller values give a snappier pulse, larger values a longer afterglow.
68
- */
69
- pulseHalfLife;
70
- /** Half-life for the {@link barPulse} envelope. Mutable; default 0.3. */
71
- barPulseHalfLife;
72
- /** Time window for {@link justBeat}. Mutable; default 0.03 (30ms). */
73
- justBeatWindow;
74
- constructor(options) {
75
- this._options = {
76
- minBpm: options?.minBpm ?? 50,
77
- maxBpm: options?.maxBpm ?? 300,
78
- fftSize: options?.fftSize ?? 2048,
79
- hopSize: options?.hopSize ?? 512,
80
- fastTempoWindowSec: options?.fastTempoWindowSec ?? 2.5,
81
- stableTempoWindowSec: options?.stableTempoWindowSec ?? 8,
82
- acfIntervalHops: options?.acfIntervalHops ?? 15,
83
- minSettlingMs: options?.minSettlingMs ?? 400,
84
- emitProvisionalBeats: options?.emitProvisionalBeats ?? true,
85
- melBands: options?.melBands ?? 24,
86
- enableTimeSignatureDetection: options?.enableTimeSignatureDetection ?? true,
87
- // Visual-state options aren't part of worklet config; cached in the public
88
- // fields below but kept in the Required<> shape for type completeness.
89
- source: options?.source ?? null,
90
- pulseHalfLife: options?.pulseHalfLife ?? 0.15,
91
- barPulseHalfLife: options?.barPulseHalfLife ?? 0.3,
92
- justBeatWindow: options?.justBeatWindow ?? 0.03,
93
- };
94
- this.pulseHalfLife = this._options.pulseHalfLife;
95
- this.barPulseHalfLife = this._options.barPulseHalfLife;
96
- this.justBeatWindow = this._options.justBeatWindow;
97
- if (isAudioContextReady()) {
98
- this._setup(getAudioContext());
99
- }
100
- else {
101
- onAudioContextReady.add(this._onAudioContextReady);
102
- }
103
- if (options?.source !== undefined && options.source !== null) {
104
- this.source = options.source;
105
- }
106
- }
107
- // -----------------------------------------------------------------------
108
- // Source setter (polymorphic tap)
109
- // -----------------------------------------------------------------------
110
- get source() {
111
- return this._source;
112
- }
113
- set source(value) {
114
- if (value === this._source)
115
- return;
116
- this._disconnectTap();
117
- this._source = value;
118
- if (value === null)
119
- return;
120
- if (isAudioContextReady()) {
121
- this._pendingSourceSetup = null;
122
- this._connectSource(value, getAudioContext());
123
- }
124
- else {
125
- if (this._pendingSourceSetup !== null) {
126
- onAudioContextReady.remove(this._pendingSourceSetup);
127
- }
128
- const handler = (ctx) => {
129
- onAudioContextReady.remove(handler);
130
- this._pendingSourceSetup = null;
131
- this._connectSource(value, ctx);
132
- };
133
- this._pendingSourceSetup = handler;
134
- onAudioContextReady.add(handler);
135
- }
136
- }
137
- // -----------------------------------------------------------------------
138
- // Ready promise
139
- // -----------------------------------------------------------------------
140
- get ready() {
141
- return this._ready ?? Promise.resolve();
142
- }
143
- // -----------------------------------------------------------------------
144
- // Stage 1 state accessors
145
- // -----------------------------------------------------------------------
146
- get tempo() {
147
- return this._tempo;
148
- }
149
- get beatPhase() {
150
- return this._beatPhase;
151
- }
152
- get nextBeatTime() {
153
- return this._nextBeatTime;
154
- }
155
- get confidence() {
156
- return this._confidence;
157
- }
158
- get gridStability() {
159
- return this._gridStability;
160
- }
161
- get rms() {
162
- return this._rms;
163
- }
164
- get onsetStrength() {
165
- return this._onsetStrength;
166
- }
167
- get bandEnergy() {
168
- return this._bandEnergy;
169
- }
170
- get tempoCandidates() {
171
- return this._tempoCandidates;
172
- }
173
- // -----------------------------------------------------------------------
174
- // Stage 2 state accessors
175
- // -----------------------------------------------------------------------
176
- get barPosition() {
177
- return this._barPosition;
178
- }
179
- get barLength() {
180
- return this._barLength;
181
- }
182
- get timeSignature() {
183
- return this._timeSignature;
184
- }
185
- get nextDownbeatTime() {
186
- return this._nextDownbeatTime;
187
- }
188
- get lookahead() {
189
- return this._lookahead;
190
- }
191
- // -----------------------------------------------------------------------
192
- // Visual derived state — pure getters for per-frame polling
193
- // -----------------------------------------------------------------------
194
- /**
195
- * Seconds elapsed since the most recent beat, derived from {@link beatPhase}
196
- * and {@link tempo}. Returns 0 when the detector hasn't locked yet.
197
- */
198
- get secondsSinceLastBeat() {
199
- if (this._tempo === 0)
200
- return 0;
201
- return this._beatPhase * (60 / this._tempo);
202
- }
203
- /**
204
- * 0..1 envelope, peaks at 1.0 the moment a beat fires and halves every
205
- * {@link pulseHalfLife} seconds. Drives "pulse on the beat" visuals
206
- * with a single multiplication: `sprite.scale = 1 + clock.pulse * 0.3`.
207
- */
208
- get pulse() {
209
- if (this._tempo === 0)
210
- return 0;
211
- return Math.pow(0.5, this.secondsSinceLastBeat / this.pulseHalfLife);
212
- }
213
- /**
214
- * Like {@link pulse} but resets on downbeats and decays per
215
- * {@link barPulseHalfLife}. Useful for emphasizing the first beat of
216
- * each bar (e.g. brighter flash on "1" vs "2,3,4").
217
- */
218
- get barPulse() {
219
- if (this._tempo === 0 || this._barLength === 0)
220
- return 0;
221
- const secondsPerBeat = 60 / this._tempo;
222
- const lastDownbeat = this._nextDownbeatTime - this._barLength * secondsPerBeat;
223
- const elapsed = Math.max(0, getAudioContext().currentTime - lastDownbeat);
224
- return Math.pow(0.5, elapsed / this.barPulseHalfLife);
225
- }
226
- /**
227
- * True for the visual frame(s) within {@link justBeatWindow} seconds of
228
- * a beat onset. Use for one-shot triggers (strobe flash, particle burst,
229
- * sample retrigger). Default window 30ms covers a typical 60fps frame.
230
- */
231
- get justBeat() {
232
- return this._tempo > 0 && this.secondsSinceLastBeat < this.justBeatWindow;
233
- }
234
- /**
235
- * Phase 0..1 within a subdivision of the current beat. `division` is the
236
- * number of subdivisions per beat: 2 for 8th notes, 4 for 16th notes,
237
- * 3 for triplets. Use to drive sub-beat-resolution effects:
238
- *
239
- * const sixteenth = clock.subdivisionPhase(4);
240
- * if (sixteenth < 0.05) flash();
241
- */
242
- subdivisionPhase(division) {
243
- if (!Number.isFinite(division) || division <= 0)
244
- return 0;
245
- return (this._beatPhase * division) % 1;
246
- }
247
- // -----------------------------------------------------------------------
248
- // Lifecycle
249
- // -----------------------------------------------------------------------
250
- destroy() {
251
- onAudioContextReady.remove(this._onAudioContextReady);
252
- if (this._pendingSourceSetup !== null) {
253
- onAudioContextReady.remove(this._pendingSourceSetup);
254
- this._pendingSourceSetup = null;
255
- }
256
- this._disconnectTap();
257
- this._workletNode?.disconnect();
258
- this._workletNode = null;
259
- this._ready = null;
260
- this.onBeat.clear();
261
- this.onTempoChange.clear();
262
- this.onDownbeat.clear();
263
- this.onBarStart.clear();
264
- this.onBeatPredicted.clear();
265
- }
266
- // -----------------------------------------------------------------------
267
- // Private helpers — setup
268
- // -----------------------------------------------------------------------
269
- _setup(audioContext) {
270
- const opts = this._options;
271
- this._ready = registerAudioWorkletProcessor(audioContext, workletName, beatDetectorWorkletSource).then(() => {
272
- const node = new AudioWorkletNode(audioContext, workletName, {
273
- numberOfInputs: 1,
274
- numberOfOutputs: 0,
275
- processorOptions: {
276
- fftSize: opts.fftSize,
277
- hopSize: opts.hopSize,
278
- minBpm: opts.minBpm,
279
- maxBpm: opts.maxBpm,
280
- melBands: opts.melBands,
281
- minSettlingMs: opts.minSettlingMs,
282
- emitProvisionalBeats: opts.emitProvisionalBeats,
283
- fastTempoWindowSec: opts.fastTempoWindowSec,
284
- stableTempoWindowSec: opts.stableTempoWindowSec,
285
- acfIntervalHops: opts.acfIntervalHops,
286
- enableTimeSignatureDetection: opts.enableTimeSignatureDetection,
287
- },
288
- });
289
- this._workletNode = node;
290
- node.port.onmessage = this._onWorkletMessage.bind(this);
291
- // If a source was set before worklet was ready, connect it now.
292
- if (this._source !== null) {
293
- this._connectSource(this._source, audioContext);
294
- }
295
- });
296
- }
297
- _onWorkletMessage(event) {
298
- const message = event.data;
299
- switch (message.type) {
300
- case 'state':
301
- this._tempo = message.tempo ?? 0;
302
- this._beatPhase = message.beatPhase ?? 0;
303
- this._nextBeatTime = message.nextBeatTime ?? 0;
304
- this._nextDownbeatTime = message.nextDownbeatTime ?? 0;
305
- this._confidence = message.confidence ?? 0;
306
- this._gridStability = message.gridStability ?? 0;
307
- this._tempoCandidates = Object.freeze(message.tempoCandidates ?? []);
308
- this._rms = message.rms ?? 0;
309
- this._onsetStrength = message.onsetStrength ?? 0;
310
- this._bandEnergy = message.bandEnergy ?? { low: 0, mid: 0, high: 0 };
311
- this._barPosition = message.barPosition ?? 1;
312
- this._barLength = message.barLength ?? 4;
313
- this._timeSignature = message.timeSignature ?? { numerator: 4, denominator: 4 };
314
- {
315
- const lookahead = message.lookahead ?? [];
316
- this._lookahead = Object.freeze(lookahead);
317
- if (lookahead.length > 0) {
318
- this.onBeatPredicted.dispatch(lookahead[0]);
319
- }
320
- }
321
- break;
322
- case 'beat': {
323
- const bi = {
324
- audioTime: message.audioTime,
325
- tempo: message.tempo,
326
- confidence: message.confidence,
327
- beatPhase: message.beatPhase,
328
- energy: message.energy,
329
- isDownbeat: message.isDownbeat,
330
- beatInBar: message.beatInBar,
331
- status: message.status ?? 'locked',
332
- };
333
- this.onBeat.dispatch(bi);
334
- if (bi.isDownbeat)
335
- this.onDownbeat.dispatch(bi);
336
- break;
337
- }
338
- case 'tempoChange':
339
- this.onTempoChange.dispatch(message.newTempo, message.oldTempo);
340
- break;
341
- case 'barStart': {
342
- const info = {
343
- audioTime: message.audioTime,
344
- tempo: message.tempo,
345
- confidence: message.confidence,
346
- barNumber: message.barNumber,
347
- };
348
- this.onBarStart.dispatch(info);
349
- break;
350
- }
351
- }
352
- }
353
- // -----------------------------------------------------------------------
354
- // Private helpers — source tap
355
- // -----------------------------------------------------------------------
356
- _connectSource(source, audioContext) {
357
- if (!this._workletNode)
358
- return;
359
- const tap = this._resolveToAudioNode(source, audioContext);
360
- if (!tap) {
361
- this._deferConnectionViaBus(source);
362
- return;
363
- }
364
- this._tapSource = tap;
365
- tap.connect(this._workletNode, 0, 0);
366
- }
367
- _resolveToAudioNode(source, audioContext) {
368
- if (source === null)
369
- return null;
370
- // MediaStream — duck-type via getTracks
371
- const asStream = source;
372
- if (typeof asStream.getTracks === 'function') {
373
- if (this._streamSource) {
374
- this._streamSource.disconnect();
375
- this._streamSource = null;
376
- }
377
- const msNode = audioContext.createMediaStreamSource(source);
378
- this._streamSource = msNode;
379
- return msNode;
380
- }
381
- // AudioBus — has _getOutputNode (checked before raw AudioNode)
382
- const asBus = source;
383
- if (typeof asBus._getOutputNode === 'function') {
384
- return asBus._getOutputNode();
385
- }
386
- // Voice — tap its output node
387
- const asVoice = source;
388
- if ('output' in asVoice && asVoice.output) {
389
- return asVoice.output;
390
- }
391
- // Raw AudioNode — duck-type: has connect & disconnect
392
- const asNode = source;
393
- if (typeof asNode.connect === 'function' && typeof asNode.disconnect === 'function') {
394
- return source;
395
- }
396
- return null;
397
- }
398
- _deferConnectionViaBus(source) {
399
- const asBus = source;
400
- if (typeof asBus.onceSetup === 'function') {
401
- asBus.onceSetup(() => {
402
- if (this._source === source && this._workletNode && isAudioContextReady()) {
403
- this._connectSource(source, getAudioContext());
404
- }
405
- });
406
- return;
407
- }
408
- onAudioContextReady.once(() => {
409
- if (this._source === source && this._workletNode && isAudioContextReady()) {
410
- this._connectSource(source, getAudioContext());
411
- }
412
- });
413
- }
414
- _disconnectTap() {
415
- if (this._tapSource && this._workletNode) {
416
- try {
417
- this._tapSource.disconnect(this._workletNode);
418
- }
419
- catch {
420
- // Ignore
421
- }
422
- }
423
- this._tapSource = null;
424
- if (this._streamSource) {
425
- this._streamSource.disconnect();
426
- this._streamSource = null;
427
- }
428
- }
429
- }
7
+ * Real-time tempo + beat tracker. Splits work between the audio-rendering
8
+ * thread (an AudioWorklet that runs onset detection, tempogram analysis,
9
+ * and parallel 3/4 and 4/4 posterior estimation) and the main thread (this
10
+ * class - receives beats, fires Signals, handles configuration and source
11
+ * routing).
12
+ *
13
+ * Accepts a wide range of {@link BeatDetectorSource}s - a bus, an individual
14
+ * {@link Voice}, a raw MediaStream, or any AudioNode - and exposes a Signal
15
+ * for each notable event:
16
+ * - {@link BeatDetector.onBeat} - every detected beat
17
+ * - {@link BeatDetector.onDownbeat} - first beat of each bar
18
+ * - {@link BeatDetector.onBarStart} - bar boundary
19
+ * - {@link BeatDetector.onTempoChange} - when the tracked BPM changes
20
+ * - {@link BeatDetector.onBeatPredicted} - look-ahead schedule notice
21
+ *
22
+ * Early beats arrive with low latency tagged `status: 'provisional'` (after a
23
+ * short `minSettlingMs` warm-up, default 400 ms) for snappy visual reactivity,
24
+ * then promote to `status: 'locked'` once the tempo grid is trustworthy - a
25
+ * single {@link BeatDetector.onBeat} signal carries both via {@link BeatInfo.status}.
26
+ * Set `emitProvisionalBeats: false` to receive only locked beats. Time-signature
27
+ * detection (3/4 vs 4/4) is on by default; lock to 4/4 by setting
28
+ * `enableTimeSignatureDetection: false`.
29
+ */
30
+ var BeatDetector = class {
31
+ onBeat = new Signal();
32
+ onTempoChange = new Signal();
33
+ onDownbeat = new Signal();
34
+ onBarStart = new Signal();
35
+ onBeatPredicted = new Signal();
36
+ _options;
37
+ _workletNode = null;
38
+ _source = null;
39
+ _tapSource = null;
40
+ _streamSource = null;
41
+ _ready = null;
42
+ _pendingSourceSetup = null;
43
+ _onAudioContextReady = (ctx) => {
44
+ onAudioContextReady.remove(this._onAudioContextReady);
45
+ this._setup(ctx);
46
+ };
47
+ _tempo = 0;
48
+ _beatPhase = 0;
49
+ _nextBeatTime = 0;
50
+ _confidence = 0;
51
+ _gridStability = 0;
52
+ _tempoCandidates = [];
53
+ _rms = 0;
54
+ _onsetStrength = 0;
55
+ _bandEnergy = {
56
+ low: 0,
57
+ mid: 0,
58
+ high: 0
59
+ };
60
+ _barPosition = 1;
61
+ _barLength = 4;
62
+ _timeSignature = {
63
+ numerator: 4,
64
+ denominator: 4
65
+ };
66
+ _nextDownbeatTime = 0;
67
+ _lookahead = Object.freeze([]);
68
+ /**
69
+ * Half-life in seconds for the {@link pulse} envelope. Mutable; default 0.15.
70
+ * Smaller values give a snappier pulse, larger values a longer afterglow.
71
+ */
72
+ pulseHalfLife;
73
+ /** Half-life for the {@link barPulse} envelope. Mutable; default 0.3. */
74
+ barPulseHalfLife;
75
+ /** Time window for {@link justBeat}. Mutable; default 0.03 (30ms). */
76
+ justBeatWindow;
77
+ constructor(options) {
78
+ this._options = {
79
+ minBpm: options?.minBpm ?? 50,
80
+ maxBpm: options?.maxBpm ?? 300,
81
+ fftSize: options?.fftSize ?? 2048,
82
+ hopSize: options?.hopSize ?? 512,
83
+ fastTempoWindowSec: options?.fastTempoWindowSec ?? 2.5,
84
+ stableTempoWindowSec: options?.stableTempoWindowSec ?? 8,
85
+ acfIntervalHops: options?.acfIntervalHops ?? 15,
86
+ minSettlingMs: options?.minSettlingMs ?? 400,
87
+ emitProvisionalBeats: options?.emitProvisionalBeats ?? true,
88
+ melBands: options?.melBands ?? 24,
89
+ enableTimeSignatureDetection: options?.enableTimeSignatureDetection ?? true,
90
+ source: options?.source ?? null,
91
+ pulseHalfLife: options?.pulseHalfLife ?? .15,
92
+ barPulseHalfLife: options?.barPulseHalfLife ?? .3,
93
+ justBeatWindow: options?.justBeatWindow ?? .03
94
+ };
95
+ this.pulseHalfLife = this._options.pulseHalfLife;
96
+ this.barPulseHalfLife = this._options.barPulseHalfLife;
97
+ this.justBeatWindow = this._options.justBeatWindow;
98
+ if (isAudioContextReady()) this._setup(getAudioContext());
99
+ else onAudioContextReady.add(this._onAudioContextReady);
100
+ if (options?.source !== void 0 && options.source !== null) this.source = options.source;
101
+ }
102
+ get source() {
103
+ return this._source;
104
+ }
105
+ set source(value) {
106
+ if (value === this._source) return;
107
+ this._disconnectTap();
108
+ this._source = value;
109
+ if (value === null) return;
110
+ if (isAudioContextReady()) {
111
+ this._pendingSourceSetup = null;
112
+ this._connectSource(value, getAudioContext());
113
+ } else {
114
+ if (this._pendingSourceSetup !== null) onAudioContextReady.remove(this._pendingSourceSetup);
115
+ const handler = (ctx) => {
116
+ onAudioContextReady.remove(handler);
117
+ this._pendingSourceSetup = null;
118
+ this._connectSource(value, ctx);
119
+ };
120
+ this._pendingSourceSetup = handler;
121
+ onAudioContextReady.add(handler);
122
+ }
123
+ }
124
+ get ready() {
125
+ return this._ready ?? Promise.resolve();
126
+ }
127
+ get tempo() {
128
+ return this._tempo;
129
+ }
130
+ get beatPhase() {
131
+ return this._beatPhase;
132
+ }
133
+ get nextBeatTime() {
134
+ return this._nextBeatTime;
135
+ }
136
+ get confidence() {
137
+ return this._confidence;
138
+ }
139
+ get gridStability() {
140
+ return this._gridStability;
141
+ }
142
+ get rms() {
143
+ return this._rms;
144
+ }
145
+ get onsetStrength() {
146
+ return this._onsetStrength;
147
+ }
148
+ get bandEnergy() {
149
+ return this._bandEnergy;
150
+ }
151
+ get tempoCandidates() {
152
+ return this._tempoCandidates;
153
+ }
154
+ get barPosition() {
155
+ return this._barPosition;
156
+ }
157
+ get barLength() {
158
+ return this._barLength;
159
+ }
160
+ get timeSignature() {
161
+ return this._timeSignature;
162
+ }
163
+ get nextDownbeatTime() {
164
+ return this._nextDownbeatTime;
165
+ }
166
+ get lookahead() {
167
+ return this._lookahead;
168
+ }
169
+ /**
170
+ * Seconds elapsed since the most recent beat, derived from {@link beatPhase}
171
+ * and {@link tempo}. Returns 0 when the detector hasn't locked yet.
172
+ */
173
+ get secondsSinceLastBeat() {
174
+ if (this._tempo === 0) return 0;
175
+ return this._beatPhase * (60 / this._tempo);
176
+ }
177
+ /**
178
+ * 0..1 envelope, peaks at 1.0 the moment a beat fires and halves every
179
+ * {@link pulseHalfLife} seconds. Drives "pulse on the beat" visuals
180
+ * with a single multiplication: `sprite.scale = 1 + clock.pulse * 0.3`.
181
+ */
182
+ get pulse() {
183
+ if (this._tempo === 0) return 0;
184
+ return Math.pow(.5, this.secondsSinceLastBeat / this.pulseHalfLife);
185
+ }
186
+ /**
187
+ * Like {@link pulse} but resets on downbeats and decays per
188
+ * {@link barPulseHalfLife}. Useful for emphasizing the first beat of
189
+ * each bar (e.g. brighter flash on "1" vs "2,3,4").
190
+ */
191
+ get barPulse() {
192
+ if (this._tempo === 0 || this._barLength === 0) return 0;
193
+ const secondsPerBeat = 60 / this._tempo;
194
+ const lastDownbeat = this._nextDownbeatTime - this._barLength * secondsPerBeat;
195
+ const elapsed = Math.max(0, getAudioContext().currentTime - lastDownbeat);
196
+ return Math.pow(.5, elapsed / this.barPulseHalfLife);
197
+ }
198
+ /**
199
+ * True for the visual frame(s) within {@link justBeatWindow} seconds of
200
+ * a beat onset. Use for one-shot triggers (strobe flash, particle burst,
201
+ * sample retrigger). Default window 30ms covers a typical 60fps frame.
202
+ */
203
+ get justBeat() {
204
+ return this._tempo > 0 && this.secondsSinceLastBeat < this.justBeatWindow;
205
+ }
206
+ /**
207
+ * Phase 0..1 within a subdivision of the current beat. `division` is the
208
+ * number of subdivisions per beat: 2 for 8th notes, 4 for 16th notes,
209
+ * 3 for triplets. Use to drive sub-beat-resolution effects:
210
+ *
211
+ * const sixteenth = clock.subdivisionPhase(4);
212
+ * if (sixteenth < 0.05) flash();
213
+ */
214
+ subdivisionPhase(division) {
215
+ if (!Number.isFinite(division) || division <= 0) return 0;
216
+ return this._beatPhase * division % 1;
217
+ }
218
+ destroy() {
219
+ onAudioContextReady.remove(this._onAudioContextReady);
220
+ if (this._pendingSourceSetup !== null) {
221
+ onAudioContextReady.remove(this._pendingSourceSetup);
222
+ this._pendingSourceSetup = null;
223
+ }
224
+ this._disconnectTap();
225
+ this._workletNode?.disconnect();
226
+ this._workletNode = null;
227
+ this._ready = null;
228
+ this.onBeat.clear();
229
+ this.onTempoChange.clear();
230
+ this.onDownbeat.clear();
231
+ this.onBarStart.clear();
232
+ this.onBeatPredicted.clear();
233
+ }
234
+ _setup(audioContext) {
235
+ const opts = this._options;
236
+ this._ready = registerAudioWorkletProcessor(audioContext, workletName, beat_detector_worklet_default).then(() => {
237
+ const node = new AudioWorkletNode(audioContext, workletName, {
238
+ numberOfInputs: 1,
239
+ numberOfOutputs: 0,
240
+ processorOptions: {
241
+ fftSize: opts.fftSize,
242
+ hopSize: opts.hopSize,
243
+ minBpm: opts.minBpm,
244
+ maxBpm: opts.maxBpm,
245
+ melBands: opts.melBands,
246
+ minSettlingMs: opts.minSettlingMs,
247
+ emitProvisionalBeats: opts.emitProvisionalBeats,
248
+ fastTempoWindowSec: opts.fastTempoWindowSec,
249
+ stableTempoWindowSec: opts.stableTempoWindowSec,
250
+ acfIntervalHops: opts.acfIntervalHops,
251
+ enableTimeSignatureDetection: opts.enableTimeSignatureDetection
252
+ }
253
+ });
254
+ this._workletNode = node;
255
+ node.port.onmessage = this._onWorkletMessage.bind(this);
256
+ if (this._source !== null) this._connectSource(this._source, audioContext);
257
+ });
258
+ }
259
+ _onWorkletMessage(event) {
260
+ const message = event.data;
261
+ switch (message.type) {
262
+ case "state":
263
+ this._tempo = message.tempo ?? 0;
264
+ this._beatPhase = message.beatPhase ?? 0;
265
+ this._nextBeatTime = message.nextBeatTime ?? 0;
266
+ this._nextDownbeatTime = message.nextDownbeatTime ?? 0;
267
+ this._confidence = message.confidence ?? 0;
268
+ this._gridStability = message.gridStability ?? 0;
269
+ this._tempoCandidates = Object.freeze(message.tempoCandidates ?? []);
270
+ this._rms = message.rms ?? 0;
271
+ this._onsetStrength = message.onsetStrength ?? 0;
272
+ this._bandEnergy = message.bandEnergy ?? {
273
+ low: 0,
274
+ mid: 0,
275
+ high: 0
276
+ };
277
+ this._barPosition = message.barPosition ?? 1;
278
+ this._barLength = message.barLength ?? 4;
279
+ this._timeSignature = message.timeSignature ?? {
280
+ numerator: 4,
281
+ denominator: 4
282
+ };
283
+ {
284
+ const lookahead = message.lookahead ?? [];
285
+ this._lookahead = Object.freeze(lookahead);
286
+ if (lookahead.length > 0) this.onBeatPredicted.dispatch(lookahead[0]);
287
+ }
288
+ break;
289
+ case "beat": {
290
+ const bi = {
291
+ audioTime: message.audioTime,
292
+ tempo: message.tempo,
293
+ confidence: message.confidence,
294
+ beatPhase: message.beatPhase,
295
+ energy: message.energy,
296
+ isDownbeat: message.isDownbeat,
297
+ beatInBar: message.beatInBar,
298
+ status: message.status ?? "locked"
299
+ };
300
+ this.onBeat.dispatch(bi);
301
+ if (bi.isDownbeat) this.onDownbeat.dispatch(bi);
302
+ break;
303
+ }
304
+ case "tempoChange":
305
+ this.onTempoChange.dispatch(message.newTempo, message.oldTempo);
306
+ break;
307
+ case "barStart": {
308
+ const info = {
309
+ audioTime: message.audioTime,
310
+ tempo: message.tempo,
311
+ confidence: message.confidence,
312
+ barNumber: message.barNumber
313
+ };
314
+ this.onBarStart.dispatch(info);
315
+ break;
316
+ }
317
+ }
318
+ }
319
+ _connectSource(source, audioContext) {
320
+ if (!this._workletNode) return;
321
+ const tap = this._resolveToAudioNode(source, audioContext);
322
+ if (!tap) {
323
+ this._deferConnectionViaBus(source);
324
+ return;
325
+ }
326
+ this._tapSource = tap;
327
+ tap.connect(this._workletNode, 0, 0);
328
+ }
329
+ _resolveToAudioNode(source, audioContext) {
330
+ if (source === null) return null;
331
+ if (typeof source.getTracks === "function") {
332
+ if (this._streamSource) {
333
+ this._streamSource.disconnect();
334
+ this._streamSource = null;
335
+ }
336
+ const msNode = audioContext.createMediaStreamSource(source);
337
+ this._streamSource = msNode;
338
+ return msNode;
339
+ }
340
+ const asBus = source;
341
+ if (typeof asBus._getOutputNode === "function") return asBus._getOutputNode();
342
+ const asVoice = source;
343
+ if ("output" in asVoice && asVoice.output) return asVoice.output;
344
+ const asNode = source;
345
+ if (typeof asNode.connect === "function" && typeof asNode.disconnect === "function") return source;
346
+ return null;
347
+ }
348
+ _deferConnectionViaBus(source) {
349
+ const asBus = source;
350
+ if (typeof asBus.onceSetup === "function") {
351
+ asBus.onceSetup(() => {
352
+ if (this._source === source && this._workletNode && isAudioContextReady()) this._connectSource(source, getAudioContext());
353
+ });
354
+ return;
355
+ }
356
+ onAudioContextReady.once(() => {
357
+ if (this._source === source && this._workletNode && isAudioContextReady()) this._connectSource(source, getAudioContext());
358
+ });
359
+ }
360
+ _disconnectTap() {
361
+ if (this._tapSource && this._workletNode) try {
362
+ this._tapSource.disconnect(this._workletNode);
363
+ } catch {}
364
+ this._tapSource = null;
365
+ if (this._streamSource) {
366
+ this._streamSource.disconnect();
367
+ this._streamSource = null;
368
+ }
369
+ }
370
+ };
430
371
 
372
+ //#endregion
431
373
  export { BeatDetector };
432
- //# sourceMappingURL=BeatDetector.js.map
374
+ //# sourceMappingURL=BeatDetector.js.map