@codexo/exojs-audio-fx 0.14.0 → 0.15.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 (64) hide show
  1. package/dist/esm/BeatDetector.d.ts +55 -9
  2. package/dist/esm/BeatDetector.js +19 -9
  3. package/dist/esm/BeatDetector.js.map +1 -1
  4. package/dist/esm/dsp/tempogram.d.ts +122 -21
  5. package/dist/esm/effects/AutoWahEffect.d.ts +127 -0
  6. package/dist/esm/effects/AutoWahEffect.js +241 -0
  7. package/dist/esm/effects/AutoWahEffect.js.map +1 -0
  8. package/dist/esm/effects/BitCrusherEffect.d.ts +63 -0
  9. package/dist/esm/effects/BitCrusherEffect.js +74 -0
  10. package/dist/esm/effects/BitCrusherEffect.js.map +1 -0
  11. package/dist/esm/effects/ConvolutionEffect.d.ts +114 -0
  12. package/dist/esm/effects/ConvolutionEffect.js +193 -0
  13. package/dist/esm/effects/ConvolutionEffect.js.map +1 -0
  14. package/dist/esm/effects/DistortionEffect.d.ts +119 -0
  15. package/dist/esm/effects/DistortionEffect.js +199 -0
  16. package/dist/esm/effects/DistortionEffect.js.map +1 -0
  17. package/dist/esm/effects/DuckingEffect.js +6 -2
  18. package/dist/esm/effects/DuckingEffect.js.map +1 -1
  19. package/dist/esm/effects/FlangerEffect.d.ts +98 -0
  20. package/dist/esm/effects/FlangerEffect.js +205 -0
  21. package/dist/esm/effects/FlangerEffect.js.map +1 -0
  22. package/dist/esm/effects/GranularEffect.d.ts +8 -4
  23. package/dist/esm/effects/GranularEffect.js +4 -12
  24. package/dist/esm/effects/GranularEffect.js.map +1 -1
  25. package/dist/esm/effects/LimiterEffect.d.ts +124 -0
  26. package/dist/esm/effects/LimiterEffect.js +198 -0
  27. package/dist/esm/effects/LimiterEffect.js.map +1 -0
  28. package/dist/esm/effects/PhaserEffect.d.ts +126 -0
  29. package/dist/esm/effects/PhaserEffect.js +258 -0
  30. package/dist/esm/effects/PhaserEffect.js.map +1 -0
  31. package/dist/esm/effects/PingPongDelayEffect.d.ts +83 -0
  32. package/dist/esm/effects/PingPongDelayEffect.js +189 -0
  33. package/dist/esm/effects/PingPongDelayEffect.js.map +1 -0
  34. package/dist/esm/effects/PitchShiftEffect.d.ts +14 -13
  35. package/dist/esm/effects/PitchShiftEffect.js +16 -18
  36. package/dist/esm/effects/PitchShiftEffect.js.map +1 -1
  37. package/dist/esm/effects/RingModulatorEffect.d.ts +95 -0
  38. package/dist/esm/effects/RingModulatorEffect.js +165 -0
  39. package/dist/esm/effects/RingModulatorEffect.js.map +1 -0
  40. package/dist/esm/effects/TremoloEffect.d.ts +110 -0
  41. package/dist/esm/effects/TremoloEffect.js +205 -0
  42. package/dist/esm/effects/TremoloEffect.js.map +1 -0
  43. package/dist/esm/effects/VocoderEffect.d.ts +0 -4
  44. package/dist/esm/effects/VocoderEffect.js +1 -11
  45. package/dist/esm/effects/VocoderEffect.js.map +1 -1
  46. package/dist/esm/index.d.ts +10 -0
  47. package/dist/esm/index.js +10 -0
  48. package/dist/esm/index.js.map +1 -1
  49. package/dist/esm/worklets/beat-detector.worklet.d.ts +1 -1
  50. package/dist/esm/worklets/beat-detector.worklet.js +628 -112
  51. package/dist/esm/worklets/beat-detector.worklet.js.map +1 -1
  52. package/dist/esm/worklets/bit-crusher.worklet.d.ts +1 -0
  53. package/dist/esm/worklets/bit-crusher.worklet.js +45 -0
  54. package/dist/esm/worklets/bit-crusher.worklet.js.map +1 -0
  55. package/dist/esm/worklets/granular.worklet.d.ts +1 -1
  56. package/dist/esm/worklets/granular.worklet.js +13 -4
  57. package/dist/esm/worklets/granular.worklet.js.map +1 -1
  58. package/dist/esm/worklets/pitch-shift.worklet.d.ts +1 -1
  59. package/dist/esm/worklets/pitch-shift.worklet.js +87 -32
  60. package/dist/esm/worklets/pitch-shift.worklet.js.map +1 -1
  61. package/dist/esm/worklets/vocoder.worklet.d.ts +1 -1
  62. package/dist/esm/worklets/vocoder.worklet.js +5 -3
  63. package/dist/esm/worklets/vocoder.worklet.js.map +1 -1
  64. package/package.json +3 -3
@@ -1,3 +1,4 @@
1
+ /* eslint-disable max-lines */ // worklet body is a single template-literal string that cannot be import-split
1
2
  const beatDetectorWorkletSource = `
2
3
  // ---- Hann window + FFT (radix-2 Cooley-Tukey) ----
3
4
  function applyHannWindow(real, imag) {
@@ -94,6 +95,139 @@ function computeMelBands(mag, bands, out) {
94
95
  }
95
96
  }
96
97
 
98
+ // ---- Tempogram (single source of truth — transliterated from src/dsp/tempogram.ts) ----
99
+ // Guarded by test/dsp/worklet-parity.test.ts: these MUST stay numerically identical to
100
+ // computeAcf / scoreTempoHypotheses / computeTempoCandidates in src/dsp/tempogram.ts.
101
+ var TEMPO_PRIOR_MU = 140;
102
+ var TEMPO_PRIOR_SIGMA = Math.log(2) * 0.9;
103
+ var COMB_W_FUNDAMENTAL = 1.0;
104
+ var COMB_W_HALF = 0.5;
105
+ var COMB_W_THIRD = 0.3;
106
+ var COMB_PENALTY_DOUBLE = 1.0;
107
+ var COMB_PENALTY_TRIPLE = 0.5;
108
+
109
+ // ---- Utility ----
110
+ // Sorts arr[0..n-1] in-place using insertion sort. Avoids creating a subarray view so
111
+ // the hot path (_detectOnset, ~93 calls/s) produces zero per-call GC pressure.
112
+ function partialSort(arr, n) {
113
+ for (var i = 1; i < n; i++) {
114
+ var v = arr[i], j = i - 1;
115
+ while (j >= 0 && arr[j] > v) { arr[j + 1] = arr[j]; j--; }
116
+ arr[j + 1] = v;
117
+ }
118
+ }
119
+
120
+ // ---- Onset peak-picker (T3): adaptive normalization + noise gate + refractory ----
121
+ // The raw spectral flux is normalised against a running median/MAD baseline so that
122
+ // soft onsets (low, broad novelty) and hard transients become comparable, then a
123
+ // rising-edge picker (upward crossing of an adaptive threshold) with a noise-floor gate
124
+ // and an IBI-derived refractory turns the novelty curve into a clean onset stream. This
125
+ // stream (per-hop strength + sub-hop onset positions) is what the T4 PLL anchors to.
126
+ var ONSET_NORM_WINDOW_SEC = 1.5; // running median/MAD window for novelty normalization
127
+ var ONSET_MAD_SCALE = 1.4826; // MAD → σ consistency factor (Gaussian)
128
+ var ONSET_THRESHOLD = 3.0; // normalized-novelty peak threshold (robust z-score)
129
+ var ONSET_NOISE_FLOOR_FRAC = 0.1; // a peak must clear this fraction of the running flux peak
130
+ var ONSET_ABS_FLOOR = 1e-4; // absolute novelty floor — kills divide-by-noise in silence
131
+ var ONSET_PEAK_DECAY = 0.999; // per-hop decay of the running flux peak (noise-floor reference)
132
+ var ONSET_MIN_REFRACTORY_SEC = 0.1; // minimum spacing between detected onsets (~100 ms)
133
+ var ONSET_REFRACTORY_IBI_FRAC = 0.4; // once locked, refractory = max(min, frac × IBI)
134
+ var ONSET_BEAT_COAST_IBI = 2.0; // suppress beat emission after this many IBIs without an onset
135
+ var ONSET_RING_SIZE = 16; // recent onsets retained for T4's PLL nearestOnset()
136
+
137
+ // ---- PLL beat-phase tracker (T4) ----
138
+ // A bounded phase-locked loop replaces the old constant-IBI predictor + buggy snap. Each
139
+ // predicted beat is corrected toward the nearest detected onset (sub-hop precise, from the
140
+ // T3 onset ring): a proportional phase nudge plus a small period adjustment, BOTH clamped so
141
+ // a single noisy onset can never yank the grid. Exactly one beat is emitted per predicted
142
+ // beat (the old snap double-advanced and timestamped a beat an IBI ahead). The first beat is
143
+ // bootstrapped to a real recent onset, never an arbitrary settling boundary. The gains are
144
+ // INTERNAL constants (API decision: not public). Tempo selection (T1/T1b/T2) is untouched —
145
+ // the PLL only refines phase/period locally around the ACF-chosen tempo.
146
+ var PLL_PHASE_GAIN = 0.25; // fraction of phase error applied as a phase nudge per beat
147
+ var PLL_TEMPO_GAIN = 0.03; // fraction of phase error folded into the period per beat
148
+ var PLL_MAX_PHASE_FRAC = 0.08; // |phaseCorr| clamp, fraction of the IBI
149
+ var PLL_MAX_TEMPO_FRAC = 0.02; // |ibiCorr| clamp, fraction of the IBI
150
+ var PLL_ACCEPT_FRAC = 0.25; // an onset within ±this·IBI of the prediction is "the" beat onset
151
+ var PLL_FREERUN_FRAC = 0.25; // free-run (grid) emit once the prediction is passed by this·IBI
152
+ var PLL_RESYNC_FRAC = 0.25; // re-seed the PLL period from the ACF tempo if it drifts beyond this
153
+ var PLL_BOOTSTRAP_MAX_AGE_IBI = 2.0; // bootstrap anchors to the newest onset within this many IBIs
154
+
155
+ // ---- DJ-drift dual-window tracking (T5) ----
156
+ // The tracked tempo normally follows the long STABLE window (octave-safe, steady). When the
157
+ // short FAST window consistently reports a DIFFERENT, non-octave tempo over several ACF hops,
158
+ // the grid follows it — a genuine DJ drift, not noise. A single noisy hop can never move the
159
+ // grid (the persistence streak below), and octave-scale disagreements are left to the stable
160
+ // hysteresis (they are metrical ambiguity, owned by the octave guards there).
161
+ var DRIFT_MIN_FRAC = 0.012; // fast must differ from the grid by > this to count as drift (~1.2%)
162
+ var DRIFT_MAX_FRAC = 0.20; // beyond this it is a hard jump → owned by the stable hysteresis
163
+ var DRIFT_AGREE_FRAC = 0.04; // consecutive fast estimates within this keep the confirmation streak
164
+ var DRIFT_CONFIRM_HOPS = 3; // consecutive confirming ACF hops required before the grid follows
165
+
166
+ // ---- Provisional vs locked beats (T7) ----
167
+ // Beats are emitted as soon as the early ACF finds ANY in-range tempo (gated at _minEmitHops,
168
+ // derived from minSettlingMs ≈ 400 ms instead of waiting the full slowest-tempo window), tagged
169
+ // status:'provisional' — this drives the low-latency "blink" visual reactivity. A beat is only
170
+ // PROMOTED to status:'locked' once the evidence matches what the detector used to wait for: the
171
+ // full stable window has filled (fluxCount ≥ maxLag+1 — one period of the slowest tempo, exactly
172
+ // the old emission gate → the AUTHORITATIVE lock) AND at least LOCK_PROMOTE_BEATS beats have since
173
+ // been emitted on that validated grid AND confidence clears a floor. (Persistence is counted as
174
+ // beats-after-authoritative-lock, not onset-MATCHED beats: on syncopated material the IBI-derived
175
+ // refractory hides the on-grid onsets so the grid legitimately free-runs — the full-window lock +
176
+ // confidence already establish trustworthiness.) The promotion latches (one provisional→locked
177
+ // transition per stable segment) and also gates the state-message tempo report, so sync-critical
178
+ // consumers and the public tempo/confidence getters only ever see post-lock (trustworthy) values
179
+ // while the visual layer still reacts early. The gains are INTERNAL constants (API decision: not
180
+ // public). When emitProvisionalBeats is false, provisional beats are suppressed (grid bookkeeping
181
+ // still runs) and only locked beats are posted — the pre-T7 emission shape.
182
+ var LOCK_PROMOTE_BEATS = 3; // beats emitted after the authoritative lock before promotion to locked
183
+ var LOCK_PROMOTE_CONFIDENCE = 0.1; // confidence floor that must be cleared to promote to locked
184
+
185
+ // Mean-subtracted, biased (÷n), zero-lag-normalised ACF. Writes lagCount values into out.
186
+ function computeAcfInline(flux, n, minLag, maxLag, out) {
187
+ var lagCount = maxLag - minLag + 1;
188
+ var mean = 0;
189
+ for (var t = 0; t < n; t++) { mean += flux[t]; }
190
+ mean = n > 0 ? mean / n : 0;
191
+ var zeroLag = 0;
192
+ for (var z = 0; z < n; z++) { var cz = flux[z] - mean; zeroLag += cz * cz; }
193
+ zeroLag = n > 0 ? zeroLag / n : 1;
194
+ var norm = zeroLag > 0 ? zeroLag : 1;
195
+ for (var lagIndex = 0; lagIndex < lagCount; lagIndex++) {
196
+ var lag = minLag + lagIndex;
197
+ var sum = 0;
198
+ for (var t2 = lag; t2 < n; t2++) { sum += (flux[t2] - mean) * (flux[t2 - lag] - mean); }
199
+ out[lagIndex] = n > 0 ? sum / n / norm : 0;
200
+ }
201
+ }
202
+
203
+ // Linear-interpolated ACF sample; 0 outside range, negative correlation clamped to 0.
204
+ function acfAtLagInline(acf, acfLen, minLag, lag) {
205
+ var maxIndex = acfLen - 1;
206
+ var f = lag - minLag;
207
+ if (f < 0 || f > maxIndex) { return 0; }
208
+ var i0 = Math.floor(f);
209
+ var i1 = i0 < maxIndex ? i0 + 1 : maxIndex;
210
+ var frac = f - i0;
211
+ var v = acf[i0] * (1 - frac) + acf[i1] * frac;
212
+ return v > 0 ? v : 0;
213
+ }
214
+
215
+ function tempoPriorInline(bpm, mu, sigma) {
216
+ var zp = Math.log(bpm / mu) / sigma;
217
+ return Math.exp(-0.5 * zp * zp);
218
+ }
219
+
220
+ // Sub-lag peak refinement: fit a parabola through (i-1, i, i+1) and return the vertex
221
+ // offset in [-0.5, 0.5]. Gives sub-hop BPM resolution where the lag grid is coarse (the
222
+ // 300 BPM top end sits at lag ~19 hops, ~5 ms/lag). Mirrors parabolicPeakOffset.
223
+ function parabolicPeakOffsetInline(yPrev, yMid, yNext) {
224
+ var denom = yPrev - 2 * yMid + yNext;
225
+ if (denom >= 0) { return 0; }
226
+ var d = (0.5 * (yPrev - yNext)) / denom;
227
+ if (d < -0.5) { d = -0.5; } else if (d > 0.5) { d = 0.5; }
228
+ return d;
229
+ }
230
+
97
231
  // ---- Processor ----
98
232
  class BeatDetectorProcessor extends AudioWorkletProcessor {
99
233
  constructor(options) {
@@ -103,10 +237,18 @@ class BeatDetectorProcessor extends AudioWorkletProcessor {
103
237
  this._fftSize = opts.fftSize || 2048;
104
238
  this._hopSize = opts.hopSize || 512;
105
239
  this._minBpm = opts.minBpm || 50;
106
- this._maxBpm = opts.maxBpm || 250;
240
+ this._maxBpm = opts.maxBpm || 300;
107
241
  this._melBands = opts.melBands || 24;
108
- this._settlingMs = opts.settlingMs !== undefined ? opts.settlingMs : 1500;
109
- this._tempoWindowSec = opts.tempoWindowSec || 6;
242
+ // T7 low-latency emission: minSettlingMs replaces the old settlingMs (1500). It sets the
243
+ // EARLIEST point a (provisional) beat may be emitted — the ACF starts hunting a tempo once
244
+ // the flux ring holds this many hops instead of waiting a full slowest-tempo period.
245
+ this._minSettlingMs = opts.minSettlingMs !== undefined ? opts.minSettlingMs : 400;
246
+ this._emitProvisionalBeats = opts.emitProvisionalBeats !== false; // default true
247
+ // T5 dual tempo windows. The short FAST window detects a genuine tempo change quickly;
248
+ // the long STABLE window holds the grid steady against noise/octave artefacts. A single
249
+ // flux ring is sized to the stable window and the fast window is its most-recent sub-span.
250
+ this._fastTempoWindowSec = opts.fastTempoWindowSec || 2.5;
251
+ this._stableTempoWindowSec = opts.stableTempoWindowSec || 8;
110
252
  this._enableTsDetection = opts.enableTimeSignatureDetection !== false;
111
253
 
112
254
  var numBins = this._fftSize >> 1;
@@ -120,10 +262,15 @@ class BeatDetectorProcessor extends AudioWorkletProcessor {
120
262
 
121
263
  this._melBandFilters = buildMelFilterbank(this._melBands, 80, 8000, this._fftSize, this._sampleRate);
122
264
  this._melOut = new Float32Array(this._melBands);
123
- var fluxWindowLen = Math.ceil(this._tempoWindowSec * this._sampleRate / this._hopSize);
265
+ var fluxWindowLen = Math.ceil(this._stableTempoWindowSec * this._sampleRate / this._hopSize);
124
266
  this._fluxWindow = new Float32Array(fluxWindowLen);
267
+ this._linFlux = new Float32Array(fluxWindowLen); // scratch: ring → linear (oldest first)
125
268
  this._fluxWritePos = 0;
126
269
  this._fluxCount = 0;
270
+ // Window spans in hops. The STABLE span is the whole ring; the FAST span is its most
271
+ // recent slice. Both still hold ≥ maxLag+1 hops so the slowest tempo stays resolvable.
272
+ this._stableWindowHops = fluxWindowLen;
273
+ this._fastWindowHops = Math.min(fluxWindowLen, Math.ceil(this._fastTempoWindowSec * this._sampleRate / this._hopSize));
127
274
  var LAG_K = 3;
128
275
  this._prevMelFrames = [];
129
276
  for (var i = 0; i < LAG_K; i++) {
@@ -134,18 +281,31 @@ class BeatDetectorProcessor extends AudioWorkletProcessor {
134
281
  // Lag range in hops for BPM range
135
282
  this._minLag = Math.max(1, Math.round(60 / this._maxBpm * this._sampleRate / this._hopSize));
136
283
  this._maxLag = Math.round(60 / this._minBpm * this._sampleRate / this._hopSize);
284
+ // ACF is computed down to a shorter lag than the candidate band (see tempogram.ts
285
+ // acfExtendedMinLag): high-BPM fundamentals become interior peaks and the 2f/3f
286
+ // super-harmonic penalty can read energy above maxBpm.
287
+ this._acfMinLag = Math.max(1, Math.round(this._minLag / 3));
288
+ this._acf = new Float32Array(this._maxLag - this._acfMinLag + 1); // scratch ACF buffer
137
289
 
138
290
  this._hopsSinceACF = 0;
139
- var ACF_INTERVAL = 15;
140
- this._acfInterval = ACF_INTERVAL;
291
+ // ACF cadence: hops between tempogram recomputations. Configurable via acfIntervalHops
292
+ // (default 15). Lower = faster reaction at more CPU; keep ≥ 1.
293
+ this._acfInterval = Math.max(1, Math.round(opts.acfIntervalHops !== undefined ? opts.acfIntervalHops : 15));
141
294
 
142
295
  // Tempo state
143
- this._bestBpm = 0;
144
- this._bestScore = 0;
145
- this._candidates = [];
296
+ this._bestBpm = 0;
297
+ this._bestScore = 0;
298
+ this._candidates = [];
299
+ this._firstLockSample = -1; // sample index of first lock (for hysteresis grace window)
300
+
301
+ // T5 drift-tracking state. The fast window must point at a different, non-octave tempo
302
+ // CONSISTENTLY (over several ACF hops) before the held grid follows it.
303
+ this._driftBpm = 0; // tempo the fast window is currently pointing at (the streak target)
304
+ this._driftHops = 0; // consecutive ACF hops the fast window has confirmed that target
146
305
 
147
306
  // Phase state
148
307
  this._lastBeatSample = -1;
308
+ this._ibiSamples = 0; // PLL-tracked inter-beat interval (samples); seeded from ACF tempo
149
309
  this._ibiHistory = new Float32Array(4); // last 4 inter-beat intervals
150
310
  this._ibiIdx = 0;
151
311
 
@@ -168,16 +328,46 @@ class BeatDetectorProcessor extends AudioWorkletProcessor {
168
328
  this._stateInterval = Math.max(1, STATE_INTERVAL_HOPS);
169
329
  this._hopsSinceState = 0;
170
330
 
171
- // Settling
172
- this._startSample = currentFrame;
173
- this._settledSamples = Math.round(this._settlingMs * 0.001 * this._sampleRate);
331
+ // T7 emission gate + provisional/locked state. _minEmitHops is the earliest hop at which
332
+ // the ACF may run (derived from minSettlingMs); _locked latches once the full-window
333
+ // evidence + beat persistence + confidence floor are met (see LOCK_PROMOTE_* and
334
+ // _emitBeat). _onGridStreak counts consecutive onset-matched beats toward promotion.
335
+ this._minEmitHops = Math.max(1, Math.round(this._minSettlingMs * 0.001 * this._sampleRate / this._hopSize));
336
+ // _authLocked flips true the first time the flux ring holds a full slowest-tempo period
337
+ // (fluxCount ≥ maxLag+1) — the AUTHORITATIVE lock, identical to the pre-T7 first lock.
338
+ // Before it, any ACF tempo is an early estimate that drives provisional beats only and is
339
+ // re-adopted every hop (never frozen). After it, the octave-aware hysteresis owns the grid.
340
+ this._authLocked = false;
341
+ this._locked = false;
342
+ this._beatsSinceAuthLock = 0; // beats emitted since the authoritative lock (promotion gate)
174
343
 
175
344
  // Lookahead
176
345
  this._lookahead = [];
177
346
 
178
347
  // RMS / onset state
179
348
  this._rms = 0;
180
- this._onsetStrength = 0;
349
+ this._onsetStrength = 0; // per-hop normalised novelty (exposed to state + T4 PLL)
350
+
351
+ // ---- Onset peak-picker state (T3) ----
352
+ var onsetWinLen = Math.max(8, Math.round(ONSET_NORM_WINDOW_SEC * this._sampleRate / this._hopSize));
353
+ this._onsetWin = new Float32Array(onsetWinLen); // ring of recent raw flux (normalization)
354
+ this._onsetWinPos = 0;
355
+ this._onsetWinCount = 0;
356
+ this._onsetSort = new Float32Array(onsetWinLen); // scratch — sorted copy for median
357
+ this._onsetDev = new Float32Array(onsetWinLen); // scratch — |x − median| for MAD
358
+ this._fluxPeak = 0; // decaying running flux maximum (noise-floor reference)
359
+ this._onsetPrev1 = 0; // normalised novelty at the previous hop (rising-edge detect)
360
+ this._onsetHopCount = 0;
361
+ this._onsetFiredThisHop = false; // a confirmed onset peak was registered this hop
362
+ // ---- Onset stream exposed for T4's PLL ----
363
+ // _lastOnsetSample / _lastOnsetStrength = most recent confirmed onset (sub-hop precise);
364
+ // the ring holds the last ONSET_RING_SIZE onsets so the PLL can pick nearestOnset().
365
+ this._lastOnsetSample = -1;
366
+ this._lastOnsetStrength = 0;
367
+ this._onsetRingSamples = new Float32Array(ONSET_RING_SIZE);
368
+ this._onsetRingStrengths = new Float32Array(ONSET_RING_SIZE);
369
+ this._onsetRingPos = 0;
370
+ this._onsetRingCount = 0;
181
371
 
182
372
  // Band energy (for state messages)
183
373
  var LOW_BANDS = Math.round(this._melBands * 0.25);
@@ -257,7 +447,6 @@ class BeatDetectorProcessor extends AudioWorkletProcessor {
257
447
  var diff = this._melOut[b] - localMax;
258
448
  if (diff > 0) flux += diff;
259
449
  }
260
- this._onsetStrength = flux;
261
450
 
262
451
  // Store current mel frame in circular buffer
263
452
  var prevFrame = this._prevMelFrames[this._prevMelFrameIdx];
@@ -271,16 +460,32 @@ class BeatDetectorProcessor extends AudioWorkletProcessor {
271
460
  this._fluxWritePos = (this._fluxWritePos + 1) % this._fluxWindow.length;
272
461
  if (this._fluxCount < this._fluxWindow.length) this._fluxCount++;
273
462
 
274
- // Tempogram: compute ACF periodically
463
+ // Adaptive onset normalization + peak-picking (T3). Runs every hop (independent
464
+ // of the ACF/tempo path, which still consumes the raw _fluxWindow above).
465
+ this._detectOnset(flux);
466
+
467
+ // Tempogram: compute ACF periodically. T7 lowers the warm-up gate from a full slowest-
468
+ // tempo period (_maxLag+1, ~1.2 s at minBpm) to _minEmitHops (~0.4 s) so a fast/core tempo
469
+ // can lock — and a provisional beat can fire — far earlier. The ACF over a short span only
470
+ // resolves tempos that already have ≳1 period of evidence in it, so slow tempos still wait
471
+ // (physically) for their period; promotion to 'locked' still requires the full window.
275
472
  this._hopsSinceACF++;
276
- if (this._hopsSinceACF >= this._acfInterval && this._fluxCount >= this._maxLag + 1) {
473
+ var dueForAcf = this._hopsSinceACF >= this._acfInterval && this._fluxCount >= this._minEmitHops;
474
+ // Force the AUTHORITATIVE compute the instant the full window first fills (independent of
475
+ // the earlier provisional ACF cadence), so the authoritative lock + phase re-bootstrap land
476
+ // on exactly the evidence the pre-T7 detector used for its first lock. That makes every
477
+ // LOCKED beat identical to the pre-T7 output (same tempo, same grid phase).
478
+ var firstFullWindow = !this._authLocked && this._fluxCount >= this._maxLag + 1;
479
+ if (dueForAcf || firstFullWindow) {
277
480
  this._hopsSinceACF = 0;
278
481
  this._computeACFAndCandidates();
279
482
  }
280
483
 
281
- // Phase tracker
282
- var settled = (this._sampleCount - this._settledSamples) > 0;
283
- if (this._bestBpm > 0 && settled) {
484
+ // Phase tracker — runs as soon as a tempo is locked. It is no longer gated on the
485
+ // full settling window: the PLL bootstraps its phase from a real onset, so beats are
486
+ // not lost to warm-up (the state-message tempo report still honours settling). Lock
487
+ // itself cannot occur before the flux window holds ≥ maxLag+1 hops (~1.2 s at minBpm).
488
+ if (this._bestBpm > 0) {
284
489
  this._tickPhase(flux);
285
490
  }
286
491
 
@@ -292,62 +497,152 @@ class BeatDetectorProcessor extends AudioWorkletProcessor {
292
497
  }
293
498
  }
294
499
 
295
- _computeACFAndCandidates() {
296
- var n = this._fluxCount;
500
+ // Score tempo candidates over the most-recent spanHops of the flux ring (capped at the
501
+ // available count). Mirrors src/dsp/tempogram.computeTempoCandidates over that span: ACF →
502
+ // positive peaks (parabola-refined interior, raw endpoints) → comb − super-harmonic penalty
503
+ // × tempo prior → top-3 sorted by score. The STABLE span (whole ring) is the parity-checked
504
+ // candidate set. Shares the _linFlux / _acf scratch buffers, so the caller must consume the
505
+ // returned array before the next call.
506
+ _scoreSpan(spanHops) {
297
507
  var buf = this._fluxWindow;
298
508
  var wp = this._fluxWritePos;
299
509
  var len = buf.length;
300
-
301
- // Compute ACF for lags in [minLag, maxLag]
302
- var numLags = this._maxLag - this._minLag + 1;
303
- var acf = new Float32Array(numLags);
304
- for (var lagIdx = 0; lagIdx < numLags; lagIdx++) {
305
- var lag = this._minLag + lagIdx;
306
- var sum = 0, count = 0;
307
- for (var t = lag; t < n; t++) {
308
- var idxT = (wp - 1 - (n - 1 - t) + len) % len;
309
- var idxTL = (wp - 1 - (n - 1 - (t - lag)) + len) % len;
310
- sum += buf[idxT] * buf[idxTL];
311
- count++;
312
- }
313
- acf[lagIdx] = count > 0 ? sum / count : 0;
510
+ var n = spanHops < this._fluxCount ? spanHops : this._fluxCount;
511
+ var minLag = this._acfMinLag; // extended ACF base (see constructor)
512
+ var maxLag = this._maxLag;
513
+ var numLags = maxLag - minLag + 1;
514
+ var loBpm = this._minBpm * 0.95; // CANDIDATE_EDGE_TOLERANCE = 0.05
515
+ var hiBpm = this._maxBpm * 1.05;
516
+
517
+ // Linearise the most-recent n hops of the flux ring (oldest first) into a scratch array
518
+ // so the ACF operates on the same layout src/dsp/tempogram.computeAcf expects.
519
+ var lin = this._linFlux;
520
+ for (var t = 0; t < n; t++) {
521
+ lin[t] = buf[((wp - 1 - (n - 1 - t)) % len + len) % len];
314
522
  }
315
523
 
316
- // Normalise
317
- var norm = 0;
318
- for (var i = 0; i < numLags; i++) { if (acf[i] > norm) norm = acf[i]; }
319
- if (norm > 0) {
320
- for (var i = 0; i < numLags; i++) acf[i] /= norm;
321
- }
524
+ // ACF (mean-subtracted, biased, zero-lag normalised) — mirrors computeAcf.
525
+ var acf = this._acf;
526
+ computeAcfInline(lin, n, minLag, maxLag, acf);
322
527
 
323
- // Find top peaks
528
+ // Raw positive peaks (interior + endpoints) — mirrors findTempoPeaks.
324
529
  var peaks = [];
325
- for (var i = 1; i < numLags - 1; i++) {
530
+ var lastIdx = numLags - 1;
531
+ if (numLags > 1 && acf[0] > acf[1] && acf[0] > 0) {
532
+ peaks.push({ bpm: 60 * this._sampleRate / (minLag * this._hopSize), score: acf[0], lag: minLag });
533
+ }
534
+ for (var i = 1; i < lastIdx; i++) {
326
535
  if (acf[i] > acf[i-1] && acf[i] > acf[i+1] && acf[i] > 0) {
327
- var lag2 = this._minLag + i;
328
- var bpm = 60 * this._sampleRate / (lag2 * this._hopSize);
329
- if (bpm >= this._minBpm && bpm <= this._maxBpm) {
330
- peaks.push({ bpm: bpm, score: acf[i], lag: lag2 });
331
- }
536
+ var lagI = minLag + i + parabolicPeakOffsetInline(acf[i-1], acf[i], acf[i+1]);
537
+ peaks.push({ bpm: 60 * this._sampleRate / (lagI * this._hopSize), score: acf[i], lag: lagI });
332
538
  }
333
539
  }
540
+ if (numLags > 1 && acf[lastIdx] > acf[lastIdx-1] && acf[lastIdx] > 0) {
541
+ var lagL = minLag + lastIdx;
542
+ peaks.push({ bpm: 60 * this._sampleRate / (lagL * this._hopSize), score: acf[lastIdx], lag: lagL });
543
+ }
334
544
  peaks.sort(function(a, b) { return b.score - a.score; });
335
- this._candidates = peaks.slice(0, 3);
336
545
 
546
+ // Filter to BPM range (with edge tolerance) — mirrors computeTempoCandidates filter.
547
+ var inRange = [];
548
+ for (var pf = 0; pf < peaks.length; pf++) {
549
+ if (peaks[pf].bpm >= loBpm && peaks[pf].bpm <= hiBpm) inRange.push(peaks[pf]);
550
+ }
551
+
552
+ // Comb (own sub-multiples) − super-harmonic penalty, × tempo prior.
553
+ // Mirrors scoreTempoHypotheses. The penalty is what defeats the octave-down bias.
554
+ // The penalty is SUBDIVISION-AWARE: a super-harmonic kf only demotes f when kf is
555
+ // itself a plausible beat (kf <= maxBpm). Energy above maxBpm is a subdivision (hats
556
+ // on 8ths over a 180 kick), not a competing fundamental, so it must not demote f.
557
+ var superHi = hiBpm; // maxBpm * 1.05 (CANDIDATE_EDGE_TOLERANCE)
558
+ var scored = [];
559
+ for (var q = 0; q < inRange.length; q++) {
560
+ var lag = inRange[q].lag;
561
+ var aF = acfAtLagInline(acf, numLags, minLag, lag);
562
+ var aHalf = acfAtLagInline(acf, numLags, minLag, lag * 2);
563
+ var aThird = acfAtLagInline(acf, numLags, minLag, lag * 3);
564
+ var aDouble = acfAtLagInline(acf, numLags, minLag, lag / 2);
565
+ var aTriple = acfAtLagInline(acf, numLags, minLag, lag / 3);
566
+ var support = COMB_W_FUNDAMENTAL * aF + COMB_W_HALF * aHalf + COMB_W_THIRD * aThird;
567
+ var penDbl = inRange[q].bpm * 2 <= superHi ? COMB_PENALTY_DOUBLE * aDouble : 0;
568
+ var penTrip = inRange[q].bpm * 3 <= superHi ? COMB_PENALTY_TRIPLE * aTriple : 0;
569
+ var comb = support - penDbl - penTrip;
570
+ if (comb < 0) comb = 0;
571
+ var w = tempoPriorInline(inRange[q].bpm, TEMPO_PRIOR_MU, TEMPO_PRIOR_SIGMA);
572
+ scored.push({ bpm: inRange[q].bpm, score: comb * w, lag: lag });
573
+ }
574
+ scored.sort(function(a, b) { return b.score - a.score; });
575
+
576
+ return scored.slice(0, 3);
577
+ }
578
+
579
+ _computeACFAndCandidates() {
580
+ // T5 dual ACF windows over the SAME flux ring. The long STABLE span holds the grid (and
581
+ // is the parity-checked candidate set the state message reports); the short FAST span
582
+ // detects a genuine tempo change quickly. Both feed the octave-aware hysteresis below.
583
+ var stable = this._scoreSpan(this._stableWindowHops);
584
+ var fast = this._scoreSpan(this._fastWindowHops);
585
+
586
+ this._candidates = stable;
337
587
  if (this._candidates.length === 0) return;
338
588
 
339
589
  var top = this._candidates[0];
340
590
 
341
- // Hysteresis
342
- if (this._bestBpm <= 0) {
343
- // First lock
591
+ // Octave-aware hysteresis with a short first-lock grace window.
592
+ if (!this._authLocked) {
593
+ // Pre-authoritative (provisional) phase: the flux ring does not yet hold a full
594
+ // slowest-tempo period, so this tempo is an EARLY, possibly under-resolved estimate
595
+ // used only to drive provisional beats. Re-adopt the current best estimate every hop —
596
+ // never freeze it (an under-resolved edge lock must not stick). The AUTHORITATIVE lock
597
+ // fires the instant the full window is available; that value is identical to the pre-T7
598
+ // first lock, so the locked grid + hysteresis (and every locked beat) are unchanged.
344
599
  this._bestBpm = top.bpm;
345
600
  this._bestScore = top.score;
601
+ if (this._fluxCount >= this._maxLag + 1) {
602
+ this._authLocked = true;
603
+ this._firstLockSample = this._sampleCount;
604
+ this._beatsSinceAuthLock = 0;
605
+ // Re-anchor the beat phase + period to the full-window evidence, SILENTLY (no
606
+ // re-emit → no duplicate beat next to the last provisional one). A provisional beat
607
+ // may have anchored the grid on an early under-resolved tempo or, on syncopated
608
+ // material, an off-beat onset; snap _lastBeatSample to the same strongest recent
609
+ // onset the pre-T7 detector locked to here so locked beats sit on the trustworthy
610
+ // grid. If no provisional beat has run yet (_lastBeatSample < 0), leave it so
611
+ // _tickPhase bootstraps the first beat normally.
612
+ if (this._lastBeatSample >= 0) {
613
+ var reIbi = 60 / this._bestBpm * this._sampleRate;
614
+ var reAnchor = this._bootstrapOnset(PLL_BOOTSTRAP_MAX_AGE_IBI * reIbi);
615
+ if (reAnchor >= 0) {
616
+ this._lastBeatSample = reAnchor;
617
+ this._ibiSamples = reIbi;
618
+ }
619
+ }
620
+ }
346
621
  } else {
347
- var isOctave = (Math.abs(top.bpm / this._bestBpm - 2) < 0.1) ||
348
- (Math.abs(top.bpm / this._bestBpm - 0.5) < 0.05);
349
- var margin = isOctave ? 1.5 : 1.15;
350
- if (top.score > this._bestScore * margin) {
622
+ // --- Stable-window hysteresis: holds the grid against noise + octave artefacts. ---
623
+ // Fresh score of the currently-tracked tempo from this frame.
624
+ var currentScore = 0;
625
+ for (var c = 0; c < this._candidates.length; c++) {
626
+ if (Math.abs(this._candidates[c].bpm / this._bestBpm - 1) < 0.03) {
627
+ if (this._candidates[c].score > currentScore) currentScore = this._candidates[c].score;
628
+ }
629
+ }
630
+ if (currentScore <= 0) currentScore = this._bestScore * 0.9;
631
+
632
+ var inGrace = this._firstLockSample >= 0 &&
633
+ (this._sampleCount - this._firstLockSample) < 2 * this._sampleRate;
634
+ var ratio = top.bpm / this._bestBpm;
635
+ // Metrically-related = same beat at another level (octaves + 3:2/2:3 dotted/triple).
636
+ // Switching across these needs the strong margin so subdivision artefacts (e.g. the
637
+ // 120 "dotted" grouping of a drifting 180 kit) cannot steal the lock. Independent
638
+ // reimplementation of isOctaveRelated (src/dsp/tempogram.ts) — constants must stay in sync.
639
+ var isOctave = Math.abs(ratio - 0.5) < 0.05 || Math.abs(ratio - 2) < 0.1 ||
640
+ Math.abs(ratio - 3) < 0.15 || Math.abs(ratio - 1/3) < 0.05 ||
641
+ Math.abs(ratio - 2/3) < 0.04 || Math.abs(ratio - 3/2) < 0.06;
642
+ var margin = inGrace ? 1.0 : (isOctave ? 1.5 : 1.15);
643
+ var diff = Math.abs(top.bpm - this._bestBpm) / this._bestBpm;
644
+
645
+ if (diff > 0.03 && top.score > currentScore * margin) {
351
646
  var oldBpm = this._bestBpm;
352
647
  this._bestBpm = top.bpm;
353
648
  this._bestScore = top.score;
@@ -356,83 +651,301 @@ class BeatDetectorProcessor extends AudioWorkletProcessor {
356
651
  this.port.postMessage({ type: 'tempoChange', newTempo: this._bestBpm, oldTempo: oldBpm });
357
652
  }
358
653
  } else {
359
- this._bestScore = this._bestScore * 0.99 + top.score * 0.01; // slowly decay
654
+ this._bestScore = currentScore;
360
655
  }
656
+
657
+ // --- Fast-window drift adaptation: follows a genuine, sustained DJ drift. ---
658
+ this._trackDrift(fast);
361
659
  }
362
660
 
363
661
  this._updateConfidence();
364
662
  }
365
663
 
366
- _tickPhase(flux) {
367
- if (this._lastBeatSample < 0) {
368
- // Bootstrap: set first beat at current sample
369
- this._lastBeatSample = this._sampleCount;
664
+ // T5 DJ-drift adaptation. The fast window leads a genuine tempo drift that the long stable
665
+ // window (and thus the held grid) lags. When the fast window points at a non-octave tempo a
666
+ // small-but-meaningful distance from the grid, and keeps pointing there for DRIFT_CONFIRM_HOPS
667
+ // consecutive ACF hops, the grid follows it. Octave-scale and hard-jump disagreements are
668
+ // left to the stable hysteresis above (it carries the octave guards); single noisy hops are
669
+ // filtered out by the persistence streak — so a static tempo is never made nervous.
670
+ _trackDrift(fast) {
671
+ if (fast.length === 0) { this._driftHops = 0; this._driftBpm = 0; return; }
672
+ var fastTop = fast[0];
673
+ var r = fastTop.bpm / this._bestBpm;
674
+ var diff = r > 1 ? r - 1 : 1 - r;
675
+
676
+ var octave = Math.abs(r - 0.5) < 0.05 || Math.abs(r - 2) < 0.1 ||
677
+ Math.abs(r - 3) < 0.15 || Math.abs(r - 1/3) < 0.05 ||
678
+ Math.abs(r - 2/3) < 0.04 || Math.abs(r - 3/2) < 0.06;
679
+
680
+ // Fast agrees with the grid, or disagrees at octave / hard-jump scale → not a drift.
681
+ if (octave || diff <= DRIFT_MIN_FRAC || diff > DRIFT_MAX_FRAC) {
682
+ this._driftHops = 0;
683
+ this._driftBpm = 0;
370
684
  return;
371
685
  }
372
686
 
373
- var beatIntervalSamples = 60 / this._bestBpm * this._sampleRate;
374
- var phase = (this._sampleCount - this._lastBeatSample) / beatIntervalSamples;
375
-
376
- // Snap correction: if novelty peak is strong and phase is 0.7..1.3, snap
377
- if (phase >= 0.7 && phase <= 1.3 && flux > 0) {
378
- // Compute mean recent flux
379
- var recentMean = 0;
380
- var count = Math.min(this._fluxCount, 16);
381
- var wp = this._fluxWritePos;
382
- var len = this._fluxWindow.length;
383
- for (var i = 0; i < count; i++) {
384
- recentMean += this._fluxWindow[(wp - 1 - i + len) % len];
385
- }
386
- recentMean /= count || 1;
387
- if (flux > 1.5 * recentMean && recentMean > 0) {
388
- // Snap to this sample
389
- this._lastBeatSample = this._sampleCount;
390
- phase = 1.0;
687
+ // Diverging within the drift band — accumulate a confirmation streak on a stable target.
688
+ if (this._driftBpm > 0 && Math.abs(fastTop.bpm / this._driftBpm - 1) < DRIFT_AGREE_FRAC) {
689
+ this._driftHops++;
690
+ } else {
691
+ this._driftHops = 1;
692
+ }
693
+ this._driftBpm = fastTop.bpm;
694
+
695
+ if (this._driftHops >= DRIFT_CONFIRM_HOPS) {
696
+ var oldBpm = this._bestBpm;
697
+ this._bestBpm = fastTop.bpm;
698
+ this._bestScore = fastTop.score;
699
+ this._driftHops = 0; // restart the streak; the next step must re-confirm
700
+ if (Math.abs(this._bestBpm - oldBpm) / oldBpm > 0.05) {
701
+ this.port.postMessage({ type: 'tempoChange', newTempo: this._bestBpm, oldTempo: oldBpm });
391
702
  }
392
703
  }
704
+ }
393
705
 
394
- if (phase >= 1.0) {
395
- var beatTime = (this._lastBeatSample + beatIntervalSamples) / this._sampleRate;
396
- this._lastBeatSample += beatIntervalSamples;
706
+ // Minimum spacing (samples) between two detected onsets. Once a tempo is locked the
707
+ // refractory tracks the beat (a fraction of the IBI); before lock it is a fixed floor.
708
+ _onsetRefractorySamples() {
709
+ var minR = ONSET_MIN_REFRACTORY_SEC * this._sampleRate;
710
+ if (this._bestBpm > 0) {
711
+ var r = ONSET_REFRACTORY_IBI_FRAC * (60 / this._bestBpm * this._sampleRate);
712
+ return r > minR ? r : minR;
713
+ }
714
+ return minR;
715
+ }
397
716
 
398
- // Update IBI history
399
- this._ibiHistory[this._ibiIdx] = beatIntervalSamples;
400
- this._ibiIdx = (this._ibiIdx + 1) & 3;
717
+ // Adaptive onset detection (T3). Normalises the raw flux against a running median/MAD
718
+ // baseline (so soft and hard onsets are comparable), then picks onsets on the UPWARD
719
+ // crossing of an adaptive threshold (the onset attack), gated by a noise floor and an
720
+ // IBI-derived refractory. Updates the per-hop _onsetStrength and the detected-onset
721
+ // stream consumed by T4's PLL.
722
+ _detectOnset(flux) {
723
+ // Decaying running flux maximum — the reference level for the noise floor.
724
+ this._fluxPeak *= ONSET_PEAK_DECAY;
725
+ if (flux > this._fluxPeak) this._fluxPeak = flux;
726
+
727
+ // Push raw flux into the normalization ring.
728
+ var W = this._onsetWin.length;
729
+ this._onsetWin[this._onsetWinPos] = flux;
730
+ this._onsetWinPos = (this._onsetWinPos + 1) % W;
731
+ if (this._onsetWinCount < W) this._onsetWinCount++;
732
+ var count = this._onsetWinCount;
733
+
734
+ // Robust baseline: median of the window, then MAD = median(|x − median|).
735
+ var s = this._onsetSort;
736
+ for (var i = 0; i < count; i++) s[i] = this._onsetWin[i];
737
+ partialSort(s, count);
738
+ var median = s[count >> 1];
739
+ var d = this._onsetDev;
740
+ for (var j = 0; j < count; j++) { var dv = this._onsetWin[j] - median; d[j] = dv < 0 ? -dv : dv; }
741
+ partialSort(d, count);
742
+ var mad = d[count >> 1];
743
+
744
+ // Normalised novelty: deviation above baseline in robust-σ units, with the scale
745
+ // floored at a fraction of the running peak so a clean (MAD≈0) clicktrack still
746
+ // yields a finite, comparable onset strength instead of a divide-by-zero spike.
747
+ var floorScale = ONSET_NOISE_FLOOR_FRAC * this._fluxPeak;
748
+ var madScaled = ONSET_MAD_SCALE * mad;
749
+ var denom = madScaled > floorScale ? madScaled : floorScale;
750
+ if (denom < 1e-9) denom = 1e-9;
751
+ var norm = (flux - median) / denom;
752
+ if (norm < 0) norm = 0;
753
+ this._onsetStrength = norm;
754
+
755
+ // Rising-edge onset detection on the normalised novelty: fire on the UPWARD crossing
756
+ // of the adaptive threshold — the onset attack, exactly where the old crude heuristic
757
+ // fired, so the shipped beat-offset behaviour is preserved — gated by the noise floor
758
+ // and an IBI-derived refractory. Zero lookahead latency.
759
+ this._onsetFiredThisHop = false;
760
+ var noiseFloor = floorScale;
761
+ var refractory = this._onsetRefractorySamples();
762
+ var crossedUp = this._onsetHopCount >= 1 && this._onsetPrev1 <= ONSET_THRESHOLD && norm > ONSET_THRESHOLD;
763
+ var aboveFloor = flux > noiseFloor && flux > ONSET_ABS_FLOOR;
764
+ var pastRefractory = this._lastOnsetSample < 0 || (this._sampleCount - this._lastOnsetSample) >= refractory;
765
+ if (crossedUp && aboveFloor && pastRefractory) {
766
+ // Sub-hop onset position: linear-interpolate the threshold crossing between the
767
+ // previous hop and this one (stored for T4's PLL; the T3 grid snap uses the integer
768
+ // hop so the shipped beat-offset numbers are preserved).
769
+ var span = norm - this._onsetPrev1;
770
+ var frac = span > 1e-9 ? (ONSET_THRESHOLD - this._onsetPrev1) / span : 0;
771
+ if (frac < 0) frac = 0; else if (frac > 1) frac = 1;
772
+ var onsetSample = (this._sampleCount - this._hopSize) + frac * this._hopSize;
773
+ this._lastOnsetSample = onsetSample;
774
+ this._lastOnsetStrength = norm;
775
+ this._onsetFiredThisHop = true;
776
+ this._onsetRingSamples[this._onsetRingPos] = onsetSample;
777
+ this._onsetRingStrengths[this._onsetRingPos] = norm;
778
+ this._onsetRingPos = (this._onsetRingPos + 1) % this._onsetRingSamples.length;
779
+ if (this._onsetRingCount < this._onsetRingSamples.length) this._onsetRingCount++;
780
+ }
401
781
 
402
- this._beatsSinceStart++;
782
+ // Shift history for the next hop.
783
+ this._onsetPrev1 = norm;
784
+ this._onsetHopCount++;
785
+ }
403
786
 
404
- // Update bar position
405
- this._updateBarPosition(flux);
787
+ // Onset CLOSEST to targetSample within ±windowSamples (sub-hop precise, from the T3 ring) —
788
+ // the PLL's nearestOnset(): the phase-error reference for the period/phase correction. Using
789
+ // the closest (not the loudest) onset keeps the loop locked to the phase it is tracking; a
790
+ // louder neighbour (e.g. a bright off-beat hat) must not be allowed to yank the grid.
791
+ // Returns the onset sample, or -1 if none.
792
+ _nearestOnset(targetSample, windowSamples) {
793
+ var best = -1;
794
+ var bestDist = windowSamples + 1;
795
+ var cnt = this._onsetRingCount;
796
+ for (var i = 0; i < cnt; i++) {
797
+ var s = this._onsetRingSamples[i];
798
+ if (s < 0) continue;
799
+ var d = s - targetSample;
800
+ if (d < 0) d = -d;
801
+ if (d <= windowSamples && d < bestDist) { bestDist = d; best = s; }
802
+ }
803
+ return best;
804
+ }
406
805
 
407
- // Compute confidence
408
- this._updateConfidence();
806
+ // Strongest onset no older than maxAgeSamples (ties → most recent) — the phase anchor for
807
+ // the first beat. Anchoring to the strongest recent transient, rather than merely the
808
+ // latest, biases the bootstrap toward a real beat onset. Always a real onset — never the old
809
+ // arbitrary settling boundary. Returns the anchor sample, or -1 if the ring is empty.
810
+ _bootstrapOnset(maxAgeSamples) {
811
+ var best = -1;
812
+ var bestStrength = -1;
813
+ var cnt = this._onsetRingCount;
814
+ for (var i = 0; i < cnt; i++) {
815
+ var s = this._onsetRingSamples[i];
816
+ if (s < 0 || (this._sampleCount - s) > maxAgeSamples) continue;
817
+ var st = this._onsetRingStrengths[i];
818
+ if (st > bestStrength || (st === bestStrength && s > best)) { bestStrength = st; best = s; }
819
+ }
820
+ return best;
821
+ }
822
+
823
+ // Emit exactly one beat at beatSample (samples). Centralises the bar/confidence/lookahead
824
+ // bookkeeping + the provisional→locked promotion + port messages so the PLL and the bootstrap
825
+ // share one emission path. The grid bookkeeping ALWAYS runs (so confidence/IBI history build
826
+ // and the bar grid stays consistent even while provisional beats are suppressed); only the port
827
+ // messages are gated.
828
+ _emitBeat(beatSample, flux) {
829
+ var beatTime = beatSample / this._sampleRate;
409
830
 
410
- // Lookahead
411
- this._updateLookahead(beatTime);
831
+ // Update IBI history with the current PLL period.
832
+ this._ibiHistory[this._ibiIdx] = this._ibiSamples;
833
+ this._ibiIdx = (this._ibiIdx + 1) & 3;
412
834
 
413
- var isDownbeat = this._barPosition === 1;
414
- var beatInfo = {
415
- type: 'beat',
835
+ this._beatsSinceStart++;
836
+ this._updateBarPosition(flux);
837
+ this._updateConfidence();
838
+ this._updateLookahead(beatTime);
839
+
840
+ // Provisional→locked promotion (latched, one transition per stable segment). Locked needs
841
+ // the SAME evidence the old detector waited for before emitting at all — the full stable
842
+ // window (the AUTHORITATIVE lock) — PLUS LOCK_PROMOTE_BEATS beats sustained on that grid
843
+ // and a confidence floor, so a 'locked' beat is at least as trustworthy as a pre-T7 beat.
844
+ if (this._authLocked) { this._beatsSinceAuthLock++; }
845
+ if (!this._locked &&
846
+ this._authLocked &&
847
+ this._beatsSinceAuthLock >= LOCK_PROMOTE_BEATS &&
848
+ this._confidence >= LOCK_PROMOTE_CONFIDENCE) {
849
+ this._locked = true;
850
+ }
851
+ var status = this._locked ? 'locked' : 'provisional';
852
+
853
+ // Provisional gating: when emitProvisionalBeats is false, suppress the message until the
854
+ // beat is locked (grid bookkeeping above already ran). Locked beats always post.
855
+ if (!this._emitProvisionalBeats && !this._locked) return;
856
+
857
+ var isDownbeat = this._barPosition === 1;
858
+ this.port.postMessage({
859
+ type: 'beat',
860
+ audioTime: beatTime,
861
+ tempo: this._bestBpm,
862
+ confidence: this._confidence,
863
+ beatPhase: 0,
864
+ energy: flux,
865
+ isDownbeat: isDownbeat,
866
+ beatInBar: this._barPosition,
867
+ status: status,
868
+ });
869
+
870
+ if (isDownbeat) {
871
+ this.port.postMessage({
872
+ type: 'barStart',
416
873
  audioTime: beatTime,
417
874
  tempo: this._bestBpm,
418
875
  confidence: this._confidence,
419
- beatPhase: 0,
420
- energy: flux,
421
- isDownbeat: isDownbeat,
422
- beatInBar: this._barPosition,
423
- };
424
- this.port.postMessage(beatInfo);
425
-
426
- if (isDownbeat) {
427
- this.port.postMessage({
428
- type: 'barStart',
429
- audioTime: beatTime,
430
- tempo: this._bestBpm,
431
- confidence: this._confidence,
432
- barNumber: this._barNumber,
433
- });
434
- }
876
+ barNumber: this._barNumber,
877
+ });
878
+ }
879
+ }
880
+
881
+ // Bounded PLL beat-phase tracker (T4). Predicts the next beat at lastBeat + ibi, corrects
882
+ // phase + period toward the nearest onset (clamped), and emits exactly one beat per
883
+ // predicted beat. Free-runs on the grid when an onset is missing; coasts (advances the
884
+ // grid but stops emitting) during sustained silence so breaks don't spawn phantom beats.
885
+ _tickPhase(flux) {
886
+ var acfIbi = 60 / this._bestBpm * this._sampleRate;
887
+
888
+ // Bootstrap: anchor the first beat to a real recent onset (never an arbitrary
889
+ // boundary). Emit it — it is a genuine, just-detected transient — so the leading
890
+ // on-grid beat is not lost to warm-up. If no onset has arrived yet, wait.
891
+ if (this._lastBeatSample < 0) {
892
+ var anchor = this._bootstrapOnset(PLL_BOOTSTRAP_MAX_AGE_IBI * acfIbi);
893
+ if (anchor < 0) return;
894
+ this._ibiSamples = acfIbi;
895
+ this._lastBeatSample = anchor;
896
+ this._emitBeat(anchor, flux);
897
+ return;
898
+ }
899
+
900
+ // Keep the PLL period anchored to the ACF tempo: it may track drift within the bounded
901
+ // tempoGain, but a large gap (octave re-lock / tempoChange) re-seeds it so the loop
902
+ // never chases a stale interval. Tempo SELECTION is unchanged — this only refines the
903
+ // local period the phase tracker runs on.
904
+ if (this._ibiSamples <= 0) this._ibiSamples = acfIbi;
905
+ if (Math.abs(this._ibiSamples - acfIbi) > PLL_RESYNC_FRAC * acfIbi) {
906
+ this._ibiSamples = acfIbi;
435
907
  }
908
+ var ibi = this._ibiSamples;
909
+
910
+ var predicted = this._lastBeatSample + ibi;
911
+ var acceptWin = PLL_ACCEPT_FRAC * ibi;
912
+
913
+ // Still early in the beat cycle — wait until we approach the prediction.
914
+ if (this._sampleCount < predicted - acceptWin) return;
915
+
916
+ var onset = this._nearestOnset(predicted, acceptWin);
917
+
918
+ var beatSample;
919
+ if (onset >= 0) {
920
+ // Bounded phase + period correction toward the matched onset.
921
+ var error = onset - predicted;
922
+ var maxPhase = PLL_MAX_PHASE_FRAC * ibi;
923
+ var phaseCorr = error * PLL_PHASE_GAIN;
924
+ if (phaseCorr > maxPhase) phaseCorr = maxPhase; else if (phaseCorr < -maxPhase) phaseCorr = -maxPhase;
925
+ var maxTempo = PLL_MAX_TEMPO_FRAC * ibi;
926
+ var ibiCorr = error * PLL_TEMPO_GAIN;
927
+ if (ibiCorr > maxTempo) ibiCorr = maxTempo; else if (ibiCorr < -maxTempo) ibiCorr = -maxTempo;
928
+ beatSample = predicted + phaseCorr;
929
+ this._ibiSamples = ibi + ibiCorr;
930
+ } else if (this._sampleCount >= predicted + PLL_FREERUN_FRAC * ibi) {
931
+ // Prediction passed with no matching onset → free-run on the grid (period held).
932
+ beatSample = predicted;
933
+ } else {
934
+ // Inside the accept window with no onset yet — give a late onset a chance next hop.
935
+ return;
936
+ }
937
+
938
+ // Advance the grid by exactly one beat.
939
+ this._lastBeatSample = beatSample;
940
+
941
+ // Coast gate (T3): after a sustained onset gap (break / silence) keep the grid
942
+ // advancing but STOP emitting — this is what holds the breakDrop false-positive rate
943
+ // down. Onset-rich material never trips it.
944
+ var coasting = this._lastOnsetSample >= 0 &&
945
+ (this._sampleCount - this._lastOnsetSample) > ONSET_BEAT_COAST_IBI * ibi;
946
+ if (coasting) return;
947
+
948
+ this._emitBeat(beatSample, flux);
436
949
  }
437
950
 
438
951
  _computeBeatLikelihood(flux) {
@@ -597,7 +1110,10 @@ class BeatDetectorProcessor extends AudioWorkletProcessor {
597
1110
  }
598
1111
 
599
1112
  _sendStateMessage() {
600
- var settled = (this._sampleCount - this._settledSamples) > 0;
1113
+ // T7: the state tempo report honours the LOCKED latch (not the old fixed settling window).
1114
+ // Provisional early beats drive the visual layer, but tempo/confidence/tempoCandidates
1115
+ // and the sync-critical fields stay zero until the detector has a trustworthy locked grid.
1116
+ var settled = this._locked;
601
1117
  var beatInterval = this._bestBpm > 0 ? 60 / this._bestBpm : 0;
602
1118
  var currentTime = this._sampleCount / this._sampleRate;
603
1119
  var lastBeatTime = this._lastBeatSample >= 0 ? this._lastBeatSample / this._sampleRate : 0;