@codexo/exojs-audio-fx 0.15.2 → 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,1163 +1,6 @@
1
- /* eslint-disable max-lines */ // worklet body is a single template-literal string that cannot be import-split
2
- const beatDetectorWorkletSource = `
3
- // ---- Hann window + FFT (radix-2 Cooley-Tukey) ----
4
- function applyHannWindow(real, imag) {
5
- var n = real.length;
6
- for (var i = 0; i < n; i++) {
7
- var w = 0.5 * (1 - Math.cos(2 * Math.PI * i / (n - 1)));
8
- real[i] *= w;
9
- imag[i] = 0;
10
- }
11
- }
1
+ //#region src/worklets/beat-detector.worklet.ts?worklet
2
+ var beat_detector_worklet_default = "\"use strict\";\n(() => {\n // ../dsp/fft.ts\n var hannWindow = (real, imag) => {\n const n = real.length;\n for (let i = 0; i < n; i++) {\n const w = 0.5 * (1 - Math.cos(2 * Math.PI * i / (n - 1)));\n real[i] *= w;\n imag[i] = 0;\n }\n };\n var bitReverse = (real, imag) => {\n const n = real.length;\n let j = 0;\n for (let i = 1; i < n; i++) {\n let bit = n >> 1;\n for (; j & bit; bit >>= 1) {\n j ^= bit;\n }\n j ^= bit;\n if (i < j) {\n let tmp = real[i];\n real[i] = real[j];\n real[j] = tmp;\n tmp = imag[i];\n imag[i] = imag[j];\n imag[j] = tmp;\n }\n }\n };\n var fft = (real, imag) => {\n hannWindow(real, imag);\n bitReverse(real, imag);\n const n = real.length;\n for (let len = 2; len <= n; len <<= 1) {\n const halfLen = len >> 1;\n const angleStep = -2 * Math.PI / len;\n for (let i = 0; i < n; i += len) {\n for (let k = 0; k < halfLen; k++) {\n const angle = angleStep * k;\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n const re = real[i + k + halfLen] * cos - imag[i + k + halfLen] * sin;\n const im = real[i + k + halfLen] * sin + imag[i + k + halfLen] * cos;\n real[i + k + halfLen] = real[i + k] - re;\n imag[i + k + halfLen] = imag[i + k] - im;\n real[i + k] += re;\n imag[i + k] += im;\n }\n }\n }\n };\n\n // ../dsp/mel.ts\n var hzToMel = (hz) => 2595 * Math.log10(1 + hz / 700);\n var melToHz = (mel) => 700 * (Math.pow(10, mel / 2595) - 1);\n var buildMelFilterbank = (bandCount, fMin, fMax, fftSize, sampleRate2) => {\n const binCount = fftSize >> 1;\n const nyquist = sampleRate2 / 2;\n const melMin = hzToMel(fMin);\n const melMax = hzToMel(fMax);\n const melPoints = new Float32Array(bandCount + 2);\n for (let i = 0; i < bandCount + 2; i++) {\n melPoints[i] = melMin + (melMax - melMin) * i / (bandCount + 1);\n }\n const binPoints = new Float32Array(bandCount + 2);\n for (let i = 0; i < bandCount + 2; i++) {\n const hz = melToHz(melPoints[i]);\n binPoints[i] = Math.round(hz / nyquist * (binCount - 1));\n }\n const bands = [];\n for (let b = 0; b < bandCount; b++) {\n const startBin = Math.max(0, Math.min(binCount - 1, binPoints[b]));\n const peakBin = Math.max(0, Math.min(binCount - 1, binPoints[b + 1]));\n const endBin = Math.max(0, Math.min(binCount - 1, binPoints[b + 2]));\n const len = endBin - startBin + 1;\n const weights = new Float32Array(len);\n for (let i = 0; i < len; i++) {\n const bin = startBin + i;\n if (bin <= peakBin && peakBin > startBin) {\n weights[i] = (bin - startBin) / (peakBin - startBin);\n } else if (bin > peakBin && endBin > peakBin) {\n weights[i] = (endBin - bin) / (endBin - peakBin);\n } else {\n weights[i] = 1;\n }\n }\n bands.push({ startBin, peakBin, endBin, weights });\n }\n return bands;\n };\n var computeMelBands = (mag, bands, out) => {\n const result = out ?? new Float32Array(bands.length);\n for (let b = 0; b < bands.length; b++) {\n const { startBin, weights } = bands[b];\n let energy = 0;\n for (let i = 0; i < weights.length; i++) {\n energy += mag[startBin + i] * weights[i];\n }\n result[b] = Math.log(1 + energy);\n }\n return result;\n };\n\n // ../dsp/tempogram.ts\n var defaultPriorMu = 140;\n var defaultPriorSigma = Math.log(2) * 0.9;\n var candidateEdgeTolerance = 0.05;\n var combWeightFundamental = 1;\n var combWeightHalf = 0.5;\n var combWeightThird = 0.3;\n var combPenaltyDouble = 1;\n var combPenaltyTriple = 0.5;\n var acfExtendedMinLag = (minLag) => Math.max(1, Math.round(minLag / 3));\n var computeAcfInto = (flux, n, minLag, maxLag, out) => {\n const lagCount = maxLag - minLag + 1;\n let mean = 0;\n for (let t = 0; t < n; t++) {\n mean += flux[t];\n }\n mean = n > 0 ? mean / n : 0;\n let zeroLag = 0;\n for (let t = 0; t < n; t++) {\n const c = flux[t] - mean;\n zeroLag += c * c;\n }\n zeroLag = n > 0 ? zeroLag / n : 1;\n const norm = zeroLag > 0 ? zeroLag : 1;\n for (let lagIndex = 0; lagIndex < lagCount; lagIndex++) {\n const lag = minLag + lagIndex;\n let sum = 0;\n for (let t = lag; t < n; t++) {\n sum += (flux[t] - mean) * (flux[t - lag] - mean);\n }\n out[lagIndex] = n > 0 ? sum / n / norm : 0;\n }\n };\n var acfAtLag = (acf, minLag, lag) => {\n const maxIndex = acf.length - 1;\n const f = lag - minLag;\n if (f < 0 || f > maxIndex) return 0;\n const i0 = Math.floor(f);\n const i1 = i0 < maxIndex ? i0 + 1 : maxIndex;\n const frac = f - i0;\n const v = acf[i0] * (1 - frac) + acf[i1] * frac;\n return v > 0 ? v : 0;\n };\n var parabolicPeakOffset = (yPrev, yMid, yNext) => {\n const denom = yPrev - 2 * yMid + yNext;\n if (denom >= 0) return 0;\n let d = 0.5 * (yPrev - yNext) / denom;\n if (d < -0.5) d = -0.5;\n else if (d > 0.5) d = 0.5;\n return d;\n };\n var tempoPrior = (bpm, mu = defaultPriorMu, sigma = defaultPriorSigma) => {\n const z = Math.log(bpm / mu) / sigma;\n return Math.exp(-0.5 * z * z);\n };\n var isOctaveRelated = (bpm, reference) => {\n if (reference <= 0) return false;\n const r = bpm / reference;\n return Math.abs(r - 0.5) < 0.05 || Math.abs(r - 2) < 0.1 || Math.abs(r - 3) < 0.15 || Math.abs(r - 1 / 3) < 0.05 || Math.abs(r - 2 / 3) < 0.04 || Math.abs(r - 3 / 2) < 0.06;\n };\n\n // beat-detector.worklet.ts\n var partialSort = (arr, n) => {\n for (let i = 1; i < n; i++) {\n const v = arr[i];\n let j = i - 1;\n while (j >= 0 && arr[j] > v) {\n arr[j + 1] = arr[j];\n j--;\n }\n arr[j + 1] = v;\n }\n };\n var ONSET_NORM_WINDOW_SEC = 1.5;\n var ONSET_MAD_SCALE = 1.4826;\n var ONSET_THRESHOLD = 3;\n var ONSET_NOISE_FLOOR_FRAC = 0.1;\n var ONSET_ABS_FLOOR = 1e-4;\n var ONSET_PEAK_DECAY = 0.999;\n var ONSET_MIN_REFRACTORY_SEC = 0.1;\n var ONSET_REFRACTORY_IBI_FRAC = 0.4;\n var ONSET_BEAT_COAST_IBI = 2;\n var ONSET_RING_SIZE = 16;\n var PLL_PHASE_GAIN = 0.25;\n var PLL_TEMPO_GAIN = 0.03;\n var PLL_MAX_PHASE_FRAC = 0.08;\n var PLL_MAX_TEMPO_FRAC = 0.02;\n var PLL_ACCEPT_FRAC = 0.25;\n var PLL_FREERUN_FRAC = 0.25;\n var PLL_RESYNC_FRAC = 0.25;\n var PLL_BOOTSTRAP_MAX_AGE_IBI = 2;\n var DRIFT_MIN_FRAC = 0.012;\n var DRIFT_MAX_FRAC = 0.2;\n var DRIFT_AGREE_FRAC = 0.04;\n var DRIFT_CONFIRM_HOPS = 3;\n var LOCK_PROMOTE_BEATS = 3;\n var LOCK_PROMOTE_CONFIDENCE = 0.1;\n var BeatDetectorProcessor = class extends AudioWorkletProcessor {\n _sampleRate;\n _fftSize;\n _hopSize;\n _minBpm;\n _maxBpm;\n _melBands;\n _minSettlingMs;\n _emitProvisionalBeats;\n _fastTempoWindowSec;\n _stableTempoWindowSec;\n _enableTsDetection;\n _real;\n _imag;\n _mag;\n _ringBuffer;\n _ringWritePos;\n _sampleCount;\n _hopAccum;\n _melBandFilters;\n _melOut;\n _fluxWindow;\n _linFlux;\n _fluxWritePos;\n _fluxCount;\n _stableWindowHops;\n _fastWindowHops;\n _prevMelFrames;\n _prevMelFrameIdx;\n _minLag;\n _maxLag;\n _acfMinLag;\n _acf;\n _hopsSinceACF;\n _acfInterval;\n _bestBpm;\n _bestScore;\n _candidates;\n _firstLockSample;\n _driftBpm;\n _driftHops;\n _lastBeatSample;\n _ibiSamples;\n _ibiHistory;\n _ibiIdx;\n _posterior4;\n _posterior3;\n _ts4Confidence;\n _ts3Confidence;\n _activeTs;\n _sustainCounter;\n _barPosition;\n _barNumber;\n _beatsSinceStart;\n _confidence;\n _stateInterval;\n _hopsSinceState;\n _minEmitHops;\n _authLocked;\n _locked;\n _beatsSinceAuthLock;\n _lookahead;\n _rms;\n _onsetStrength;\n _onsetWin;\n _onsetWinPos;\n _onsetWinCount;\n _onsetSort;\n _onsetDev;\n _fluxPeak;\n _onsetPrev1;\n _onsetHopCount;\n _lastOnsetSample;\n _onsetRingSamples;\n _onsetRingStrengths;\n _onsetRingPos;\n _onsetRingCount;\n _lowBandEnd;\n _midBandEnd;\n constructor(options) {\n super();\n const opts = options?.processorOptions ?? {};\n this._sampleRate = sampleRate;\n this._fftSize = opts.fftSize || 2048;\n this._hopSize = opts.hopSize || 512;\n this._minBpm = opts.minBpm || 50;\n this._maxBpm = opts.maxBpm || 300;\n this._melBands = opts.melBands || 24;\n this._minSettlingMs = opts.minSettlingMs !== void 0 ? opts.minSettlingMs : 400;\n this._emitProvisionalBeats = opts.emitProvisionalBeats !== false;\n this._fastTempoWindowSec = opts.fastTempoWindowSec || 2.5;\n this._stableTempoWindowSec = opts.stableTempoWindowSec || 8;\n this._enableTsDetection = opts.enableTimeSignatureDetection !== false;\n const numBins = this._fftSize >> 1;\n this._real = new Float32Array(this._fftSize);\n this._imag = new Float32Array(this._fftSize);\n this._mag = new Float32Array(numBins);\n this._ringBuffer = new Float32Array(this._fftSize);\n this._ringWritePos = 0;\n this._sampleCount = 0;\n this._hopAccum = 0;\n this._melBandFilters = buildMelFilterbank(this._melBands, 80, 8e3, this._fftSize, this._sampleRate);\n this._melOut = new Float32Array(this._melBands);\n const fluxWindowLen = Math.ceil(this._stableTempoWindowSec * this._sampleRate / this._hopSize);\n this._fluxWindow = new Float32Array(fluxWindowLen);\n this._linFlux = new Float32Array(fluxWindowLen);\n this._fluxWritePos = 0;\n this._fluxCount = 0;\n this._stableWindowHops = fluxWindowLen;\n this._fastWindowHops = Math.min(fluxWindowLen, Math.ceil(this._fastTempoWindowSec * this._sampleRate / this._hopSize));\n const LAG_K = 3;\n this._prevMelFrames = [];\n for (let i = 0; i < LAG_K; i++) {\n this._prevMelFrames.push(new Float32Array(this._melBands));\n }\n this._prevMelFrameIdx = 0;\n this._minLag = Math.max(1, Math.round(60 / this._maxBpm * this._sampleRate / this._hopSize));\n this._maxLag = Math.round(60 / this._minBpm * this._sampleRate / this._hopSize);\n this._acfMinLag = acfExtendedMinLag(this._minLag);\n this._acf = new Float32Array(this._maxLag - this._acfMinLag + 1);\n this._hopsSinceACF = 0;\n this._acfInterval = Math.max(1, Math.round(opts.acfIntervalHops !== void 0 ? opts.acfIntervalHops : 15));\n this._bestBpm = 0;\n this._bestScore = 0;\n this._candidates = [];\n this._firstLockSample = -1;\n this._driftBpm = 0;\n this._driftHops = 0;\n this._lastBeatSample = -1;\n this._ibiSamples = 0;\n this._ibiHistory = new Float32Array(4);\n this._ibiIdx = 0;\n this._posterior4 = new Float32Array([0.25, 0.25, 0.25, 0.25]);\n this._posterior3 = new Float32Array([1 / 3, 1 / 3, 1 / 3]);\n this._ts4Confidence = 0.5;\n this._ts3Confidence = 0.5;\n this._activeTs = \"4/4\";\n this._sustainCounter = 0;\n this._barPosition = 1;\n this._barNumber = 0;\n this._beatsSinceStart = 0;\n this._confidence = 0;\n const STATE_INTERVAL_HOPS = Math.round(this._sampleRate / this._hopSize / 20);\n this._stateInterval = Math.max(1, STATE_INTERVAL_HOPS);\n this._hopsSinceState = 0;\n this._minEmitHops = Math.max(1, Math.round(this._minSettlingMs * 1e-3 * this._sampleRate / this._hopSize));\n this._authLocked = false;\n this._locked = false;\n this._beatsSinceAuthLock = 0;\n this._lookahead = [];\n this._rms = 0;\n this._onsetStrength = 0;\n const onsetWinLen = Math.max(8, Math.round(ONSET_NORM_WINDOW_SEC * this._sampleRate / this._hopSize));\n this._onsetWin = new Float32Array(onsetWinLen);\n this._onsetWinPos = 0;\n this._onsetWinCount = 0;\n this._onsetSort = new Float32Array(onsetWinLen);\n this._onsetDev = new Float32Array(onsetWinLen);\n this._fluxPeak = 0;\n this._onsetPrev1 = 0;\n this._onsetHopCount = 0;\n this._lastOnsetSample = -1;\n this._onsetRingSamples = new Float32Array(ONSET_RING_SIZE);\n this._onsetRingStrengths = new Float32Array(ONSET_RING_SIZE);\n this._onsetRingPos = 0;\n this._onsetRingCount = 0;\n const LOW_BANDS = Math.round(this._melBands * 0.25);\n const MID_BANDS = Math.round(this._melBands * 0.6);\n this._lowBandEnd = LOW_BANDS;\n this._midBandEnd = MID_BANDS;\n }\n process(inputs, _outputs, _parameters) {\n const input = inputs[0];\n if (!input || input.length === 0) return true;\n const left = input[0] ?? new Float32Array(0);\n const right = input[1] ?? left;\n const blockLen = left.length;\n for (let s = 0; s < blockLen; s++) {\n const mono = (left[s] + right[s]) * 0.5;\n this._rms += mono * mono;\n this._ringBuffer[this._ringWritePos] = mono;\n this._ringWritePos = this._ringWritePos + 1 & this._fftSize - 1;\n this._hopAccum++;\n this._sampleCount++;\n if (this._hopAccum >= this._hopSize) {\n this._hopAccum = 0;\n this._processHop();\n }\n }\n return true;\n }\n _processHop() {\n const rb = this._ringBuffer;\n const wp = this._ringWritePos;\n const n = this._fftSize;\n for (let i = 0; i < n; i++) {\n this._real[i] = rb[wp + i & n - 1];\n }\n fft(this._real, this._imag);\n const bins = n >> 1;\n for (let i = 0; i < bins; i++) {\n this._mag[i] = Math.sqrt(this._real[i] * this._real[i] + this._imag[i] * this._imag[i]);\n }\n let rmsAccum = 0;\n for (let i = 0; i < n; i++) {\n rmsAccum += rb[wp + i & n - 1] * rb[wp + i & n - 1];\n }\n this._rms = Math.sqrt(rmsAccum / n);\n computeMelBands(this._mag, this._melBandFilters, this._melOut);\n const K = this._prevMelFrames.length;\n let flux = 0;\n for (let b = 0; b < this._melBands; b++) {\n let localMax = -Infinity;\n for (let k = 0; k < K; k++) {\n const prevVal = this._prevMelFrames[k][b];\n if (prevVal > localMax) localMax = prevVal;\n }\n const diff = this._melOut[b] - localMax;\n if (diff > 0) flux += diff;\n }\n const prevFrame = this._prevMelFrames[this._prevMelFrameIdx];\n for (let b = 0; b < this._melBands; b++) {\n prevFrame[b] = this._melOut[b];\n }\n this._prevMelFrameIdx = (this._prevMelFrameIdx + 1) % K;\n this._fluxWindow[this._fluxWritePos] = flux;\n this._fluxWritePos = (this._fluxWritePos + 1) % this._fluxWindow.length;\n if (this._fluxCount < this._fluxWindow.length) this._fluxCount++;\n this._detectOnset(flux);\n this._hopsSinceACF++;\n const dueForAcf = this._hopsSinceACF >= this._acfInterval && this._fluxCount >= this._minEmitHops;\n const firstFullWindow = !this._authLocked && this._fluxCount >= this._maxLag + 1;\n if (dueForAcf || firstFullWindow) {\n this._hopsSinceACF = 0;\n this._computeACFAndCandidates();\n }\n if (this._bestBpm > 0) {\n this._tickPhase(flux);\n }\n this._hopsSinceState++;\n if (this._hopsSinceState >= this._stateInterval) {\n this._hopsSinceState = 0;\n this._sendStateMessage();\n }\n }\n // Score tempo candidates over the most-recent spanHops of the flux ring (capped at the\n // available count). Mirrors src/dsp/tempogram.computeTempoCandidates over that span: ACF →\n // positive peaks (parabola-refined interior, raw endpoints) → comb − super-harmonic penalty\n // × tempo prior → top-3 sorted by score. The STABLE span (whole ring) is the parity-checked\n // candidate set. Shares the _linFlux / _acf scratch buffers, so the caller must consume the\n // returned array before the next call.\n _scoreSpan(spanHops) {\n const buf = this._fluxWindow;\n const wp = this._fluxWritePos;\n const len = buf.length;\n const n = spanHops < this._fluxCount ? spanHops : this._fluxCount;\n const minLag = this._acfMinLag;\n const maxLag = this._maxLag;\n const numLags = maxLag - minLag + 1;\n const loBpm = this._minBpm * (1 - candidateEdgeTolerance);\n const hiBpm = this._maxBpm * (1 + candidateEdgeTolerance);\n const lin = this._linFlux;\n for (let t = 0; t < n; t++) {\n lin[t] = buf[((wp - 1 - (n - 1 - t)) % len + len) % len];\n }\n const acf = this._acf;\n computeAcfInto(lin, n, minLag, maxLag, acf);\n const peaks = [];\n const lastIdx = numLags - 1;\n if (numLags > 1 && acf[0] > acf[1] && acf[0] > 0) {\n peaks.push({ bpm: 60 * this._sampleRate / (minLag * this._hopSize), score: acf[0], lag: minLag });\n }\n for (let i = 1; i < lastIdx; i++) {\n if (acf[i] > acf[i - 1] && acf[i] > acf[i + 1] && acf[i] > 0) {\n const lagI = minLag + i + parabolicPeakOffset(acf[i - 1], acf[i], acf[i + 1]);\n peaks.push({ bpm: 60 * this._sampleRate / (lagI * this._hopSize), score: acf[i], lag: lagI });\n }\n }\n if (numLags > 1 && acf[lastIdx] > acf[lastIdx - 1] && acf[lastIdx] > 0) {\n const lagL = minLag + lastIdx;\n peaks.push({ bpm: 60 * this._sampleRate / (lagL * this._hopSize), score: acf[lastIdx], lag: lagL });\n }\n peaks.sort((a, b) => b.score - a.score);\n const inRange = [];\n for (let pf = 0; pf < peaks.length; pf++) {\n if (peaks[pf].bpm >= loBpm && peaks[pf].bpm <= hiBpm) inRange.push(peaks[pf]);\n }\n const superHi = hiBpm;\n const scored = [];\n for (let q = 0; q < inRange.length; q++) {\n const lag = inRange[q].lag;\n const aF = acfAtLag(acf, minLag, lag);\n const aHalf = acfAtLag(acf, minLag, lag * 2);\n const aThird = acfAtLag(acf, minLag, lag * 3);\n const aDouble = acfAtLag(acf, minLag, lag / 2);\n const aTriple = acfAtLag(acf, minLag, lag / 3);\n const support = combWeightFundamental * aF + combWeightHalf * aHalf + combWeightThird * aThird;\n const penDbl = inRange[q].bpm * 2 <= superHi ? combPenaltyDouble * aDouble : 0;\n const penTrip = inRange[q].bpm * 3 <= superHi ? combPenaltyTriple * aTriple : 0;\n let comb = support - penDbl - penTrip;\n if (comb < 0) comb = 0;\n const w = tempoPrior(inRange[q].bpm, defaultPriorMu, defaultPriorSigma);\n scored.push({ bpm: inRange[q].bpm, score: comb * w, lag });\n }\n scored.sort((a, b) => b.score - a.score);\n return scored.slice(0, 3);\n }\n _computeACFAndCandidates() {\n const stable = this._scoreSpan(this._stableWindowHops);\n const fast = this._scoreSpan(this._fastWindowHops);\n this._candidates = stable;\n if (this._candidates.length === 0) return;\n const top = this._candidates[0];\n if (!this._authLocked) {\n this._bestBpm = top.bpm;\n this._bestScore = top.score;\n if (this._fluxCount >= this._maxLag + 1) {\n this._authLocked = true;\n this._firstLockSample = this._sampleCount;\n this._beatsSinceAuthLock = 0;\n if (this._lastBeatSample >= 0) {\n const reIbi = 60 / this._bestBpm * this._sampleRate;\n const reAnchor = this._bootstrapOnset(PLL_BOOTSTRAP_MAX_AGE_IBI * reIbi);\n if (reAnchor >= 0) {\n this._lastBeatSample = reAnchor;\n this._ibiSamples = reIbi;\n }\n }\n }\n } else {\n let currentScore = 0;\n for (let c = 0; c < this._candidates.length; c++) {\n if (Math.abs(this._candidates[c].bpm / this._bestBpm - 1) < 0.03 && this._candidates[c].score > currentScore)\n currentScore = this._candidates[c].score;\n }\n if (currentScore <= 0) currentScore = this._bestScore * 0.9;\n const inGrace = this._firstLockSample >= 0 && this._sampleCount - this._firstLockSample < 2 * this._sampleRate;\n const isOctave = isOctaveRelated(top.bpm, this._bestBpm);\n let margin;\n if (inGrace) {\n margin = 1;\n } else if (isOctave) {\n margin = 1.5;\n } else {\n margin = 1.15;\n }\n const diff = Math.abs(top.bpm - this._bestBpm) / this._bestBpm;\n if (diff > 0.03 && top.score > currentScore * margin) {\n const oldBpm = this._bestBpm;\n this._bestBpm = top.bpm;\n this._bestScore = top.score;\n if (Math.abs(this._bestBpm - oldBpm) / oldBpm > 0.05) {\n this.port.postMessage({ type: \"tempoChange\", newTempo: this._bestBpm, oldTempo: oldBpm });\n }\n } else {\n this._bestScore = currentScore;\n }\n this._trackDrift(fast);\n }\n this._updateConfidence();\n }\n // DJ-drift adaptation. The fast window leads a genuine tempo drift that the long stable\n // window (and thus the held grid) lags. When the fast window points at a non-octave tempo a\n // small-but-meaningful distance from the grid, and keeps pointing there for DRIFT_CONFIRM_HOPS\n // consecutive ACF hops, the grid follows it. Octave-scale and hard-jump disagreements are\n // left to the stable hysteresis above (it carries the octave guards); single noisy hops are\n // filtered out by the persistence streak - so a static tempo is never made nervous.\n _trackDrift(fast) {\n if (fast.length === 0) {\n this._driftHops = 0;\n this._driftBpm = 0;\n return;\n }\n const fastTop = fast[0];\n const r = fastTop.bpm / this._bestBpm;\n const diff = r > 1 ? r - 1 : 1 - r;\n const octave = isOctaveRelated(fastTop.bpm, this._bestBpm);\n if (octave || diff <= DRIFT_MIN_FRAC || diff > DRIFT_MAX_FRAC) {\n this._driftHops = 0;\n this._driftBpm = 0;\n return;\n }\n if (this._driftBpm > 0 && Math.abs(fastTop.bpm / this._driftBpm - 1) < DRIFT_AGREE_FRAC) {\n this._driftHops++;\n } else {\n this._driftHops = 1;\n }\n this._driftBpm = fastTop.bpm;\n if (this._driftHops >= DRIFT_CONFIRM_HOPS) {\n const oldBpm = this._bestBpm;\n this._bestBpm = fastTop.bpm;\n this._bestScore = fastTop.score;\n this._driftHops = 0;\n if (Math.abs(this._bestBpm - oldBpm) / oldBpm > 0.05) {\n this.port.postMessage({ type: \"tempoChange\", newTempo: this._bestBpm, oldTempo: oldBpm });\n }\n }\n }\n // Minimum spacing (samples) between two detected onsets. Once a tempo is locked the\n // refractory tracks the beat (a fraction of the IBI); before lock it is a fixed floor.\n _onsetRefractorySamples() {\n const minR = ONSET_MIN_REFRACTORY_SEC * this._sampleRate;\n if (this._bestBpm > 0) {\n const r = ONSET_REFRACTORY_IBI_FRAC * (60 / this._bestBpm * this._sampleRate);\n return r > minR ? r : minR;\n }\n return minR;\n }\n // Adaptive onset detection. Normalises the raw flux against a running median/MAD\n // baseline (so soft and hard onsets are comparable), then picks onsets on the UPWARD\n // crossing of an adaptive threshold (the onset attack), gated by a noise floor and an\n // IBI-derived refractory. Updates the per-hop _onsetStrength and the detected-onset\n // stream consumed by the PLL.\n _detectOnset(flux) {\n this._fluxPeak *= ONSET_PEAK_DECAY;\n if (flux > this._fluxPeak) this._fluxPeak = flux;\n const W = this._onsetWin.length;\n this._onsetWin[this._onsetWinPos] = flux;\n this._onsetWinPos = (this._onsetWinPos + 1) % W;\n if (this._onsetWinCount < W) this._onsetWinCount++;\n const count = this._onsetWinCount;\n const s = this._onsetSort;\n for (let i = 0; i < count; i++) s[i] = this._onsetWin[i];\n partialSort(s, count);\n const median = s[count >> 1];\n const d = this._onsetDev;\n for (let j = 0; j < count; j++) {\n const dv = this._onsetWin[j] - median;\n d[j] = Math.abs(dv);\n }\n partialSort(d, count);\n const mad = d[count >> 1];\n const floorScale = ONSET_NOISE_FLOOR_FRAC * this._fluxPeak;\n const madScaled = ONSET_MAD_SCALE * mad;\n let denom = madScaled > floorScale ? madScaled : floorScale;\n if (denom < 1e-9) denom = 1e-9;\n let norm = (flux - median) / denom;\n if (norm < 0) norm = 0;\n this._onsetStrength = norm;\n const noiseFloor = floorScale;\n const refractory = this._onsetRefractorySamples();\n const crossedUp = this._onsetHopCount >= 1 && this._onsetPrev1 <= ONSET_THRESHOLD && norm > ONSET_THRESHOLD;\n const aboveFloor = flux > noiseFloor && flux > ONSET_ABS_FLOOR;\n const pastRefractory = this._lastOnsetSample < 0 || this._sampleCount - this._lastOnsetSample >= refractory;\n if (crossedUp && aboveFloor && pastRefractory) {\n const span = norm - this._onsetPrev1;\n let frac = span > 1e-9 ? (ONSET_THRESHOLD - this._onsetPrev1) / span : 0;\n if (frac < 0) frac = 0;\n else if (frac > 1) frac = 1;\n const onsetSample = this._sampleCount - this._hopSize + frac * this._hopSize;\n this._lastOnsetSample = onsetSample;\n this._onsetRingSamples[this._onsetRingPos] = onsetSample;\n this._onsetRingStrengths[this._onsetRingPos] = norm;\n this._onsetRingPos = (this._onsetRingPos + 1) % this._onsetRingSamples.length;\n if (this._onsetRingCount < this._onsetRingSamples.length) this._onsetRingCount++;\n }\n this._onsetPrev1 = norm;\n this._onsetHopCount++;\n }\n // Onset CLOSEST to targetSample within ±windowSamples (sub-hop precise, from the onset ring) -\n // the PLL's nearestOnset(): the phase-error reference for the period/phase correction. Using\n // the closest (not the loudest) onset keeps the loop locked to the phase it is tracking; a\n // louder neighbour (e.g. a bright off-beat hat) must not be allowed to yank the grid.\n // Returns the onset sample, or -1 if none.\n _nearestOnset(targetSample, windowSamples) {\n let best = -1;\n let bestDist = windowSamples + 1;\n const cnt = this._onsetRingCount;\n for (let i = 0; i < cnt; i++) {\n const s = this._onsetRingSamples[i];\n if (s < 0) continue;\n let d = s - targetSample;\n if (d < 0) d = -d;\n if (d <= windowSamples && d < bestDist) {\n bestDist = d;\n best = s;\n }\n }\n return best;\n }\n // Strongest onset no older than maxAgeSamples (ties → most recent) - the phase anchor for\n // the first beat. Anchoring to the strongest recent transient, rather than merely the\n // latest, biases the bootstrap toward a real beat onset. Always a real onset - never the old\n // arbitrary settling boundary. Returns the anchor sample, or -1 if the ring is empty.\n _bootstrapOnset(maxAgeSamples) {\n let best = -1;\n let bestStrength = -1;\n const cnt = this._onsetRingCount;\n for (let i = 0; i < cnt; i++) {\n const s = this._onsetRingSamples[i];\n if (s < 0 || this._sampleCount - s > maxAgeSamples) continue;\n const st = this._onsetRingStrengths[i];\n if (st > bestStrength || st === bestStrength && s > best) {\n bestStrength = st;\n best = s;\n }\n }\n return best;\n }\n // Emit exactly one beat at beatSample (samples). Centralises the bar/confidence/lookahead\n // bookkeeping + the provisional→locked promotion + port messages so the PLL and the bootstrap\n // share one emission path. The grid bookkeeping ALWAYS runs (so confidence/IBI history build\n // and the bar grid stays consistent even while provisional beats are suppressed); only the port\n // messages are gated.\n _emitBeat(beatSample, flux) {\n const beatTime = beatSample / this._sampleRate;\n this._ibiHistory[this._ibiIdx] = this._ibiSamples;\n this._ibiIdx = this._ibiIdx + 1 & 3;\n this._beatsSinceStart++;\n this._updateBarPosition(flux);\n this._updateConfidence();\n this._updateLookahead(beatTime);\n if (this._authLocked) {\n this._beatsSinceAuthLock++;\n }\n if (!this._locked && this._authLocked && this._beatsSinceAuthLock >= LOCK_PROMOTE_BEATS && this._confidence >= LOCK_PROMOTE_CONFIDENCE) {\n this._locked = true;\n }\n const status = this._locked ? \"locked\" : \"provisional\";\n if (!this._emitProvisionalBeats && !this._locked) return;\n const isDownbeat = this._barPosition === 1;\n this.port.postMessage({\n type: \"beat\",\n audioTime: beatTime,\n tempo: this._bestBpm,\n confidence: this._confidence,\n beatPhase: 0,\n energy: flux,\n isDownbeat,\n beatInBar: this._barPosition,\n status\n });\n if (isDownbeat) {\n this.port.postMessage({\n type: \"barStart\",\n audioTime: beatTime,\n tempo: this._bestBpm,\n confidence: this._confidence,\n barNumber: this._barNumber\n });\n }\n }\n // Bounded PLL beat-phase tracker. Predicts the next beat at lastBeat + ibi, corrects\n // phase + period toward the nearest onset (clamped), and emits exactly one beat per\n // predicted beat. Free-runs on the grid when an onset is missing; coasts (advances the\n // grid but stops emitting) during sustained silence so breaks don't spawn phantom beats.\n _tickPhase(flux) {\n const acfIbi = 60 / this._bestBpm * this._sampleRate;\n if (this._lastBeatSample < 0) {\n const anchor = this._bootstrapOnset(PLL_BOOTSTRAP_MAX_AGE_IBI * acfIbi);\n if (anchor < 0) return;\n this._ibiSamples = acfIbi;\n this._lastBeatSample = anchor;\n this._emitBeat(anchor, flux);\n return;\n }\n if (this._ibiSamples <= 0) this._ibiSamples = acfIbi;\n if (Math.abs(this._ibiSamples - acfIbi) > PLL_RESYNC_FRAC * acfIbi) {\n this._ibiSamples = acfIbi;\n }\n const ibi = this._ibiSamples;\n const predicted = this._lastBeatSample + ibi;\n const acceptWin = PLL_ACCEPT_FRAC * ibi;\n if (this._sampleCount < predicted - acceptWin) return;\n const onset = this._nearestOnset(predicted, acceptWin);\n let beatSample;\n if (onset >= 0) {\n const error = onset - predicted;\n const maxPhase = PLL_MAX_PHASE_FRAC * ibi;\n let phaseCorr = error * PLL_PHASE_GAIN;\n if (phaseCorr > maxPhase) phaseCorr = maxPhase;\n else if (phaseCorr < -maxPhase) phaseCorr = -maxPhase;\n const maxTempo = PLL_MAX_TEMPO_FRAC * ibi;\n let ibiCorr = error * PLL_TEMPO_GAIN;\n if (ibiCorr > maxTempo) ibiCorr = maxTempo;\n else if (ibiCorr < -maxTempo) ibiCorr = -maxTempo;\n beatSample = predicted + phaseCorr;\n this._ibiSamples = ibi + ibiCorr;\n } else if (this._sampleCount >= predicted + PLL_FREERUN_FRAC * ibi) {\n beatSample = predicted;\n } else {\n return;\n }\n this._lastBeatSample = beatSample;\n const coasting = this._lastOnsetSample >= 0 && this._sampleCount - this._lastOnsetSample > ONSET_BEAT_COAST_IBI * ibi;\n if (coasting) return;\n this._emitBeat(beatSample, flux);\n }\n _computeBeatLikelihood(flux) {\n const count = Math.min(this._fluxCount, 32);\n const wp = this._fluxWritePos;\n const len = this._fluxWindow.length;\n let totalFlux = 0;\n for (let i = 0; i < count; i++) {\n totalFlux += this._fluxWindow[(wp - 1 - i + len) % len];\n }\n const mean = count > 0 ? totalFlux / count : 1;\n return Math.max(0.5, Math.min(1.5, mean > 0 ? flux / mean : 1));\n }\n _updateBarPosition(flux) {\n const likelihood = this._computeBeatLikelihood(flux);\n const p4 = this._posterior4;\n const s4 = new Float32Array(4);\n s4[0] = p4[3];\n s4[1] = p4[0];\n s4[2] = p4[1];\n s4[3] = p4[2];\n let sum4 = 0;\n for (let i = 0; i < 4; i++) {\n p4[i] = s4[i] * (likelihood + (i === 0 ? 0.3 : 0));\n sum4 += p4[i];\n }\n if (sum4 > 0) {\n for (let i = 0; i < 4; i++) p4[i] /= sum4;\n }\n const p3 = this._posterior3;\n const s3 = new Float32Array(3);\n s3[0] = p3[2];\n s3[1] = p3[0];\n s3[2] = p3[1];\n let sum3 = 0;\n for (let i = 0; i < 3; i++) {\n p3[i] = s3[i] * (likelihood + (i === 0 ? 0.3 : 0));\n sum3 += p3[i];\n }\n if (sum3 > 0) {\n for (let i = 0; i < 3; i++) p3[i] /= sum3;\n }\n let max4 = 0;\n for (let i = 0; i < 4; i++) {\n if (p4[i] > max4) max4 = p4[i];\n }\n let max3 = 0;\n for (let i = 0; i < 3; i++) {\n if (p3[i] > max3) max3 = p3[i];\n }\n const alpha = 0.1;\n this._ts4Confidence = (1 - alpha) * this._ts4Confidence + alpha * max4;\n this._ts3Confidence = (1 - alpha) * this._ts3Confidence + alpha * max3;\n if (this._enableTsDetection && this._beatsSinceStart > 8) {\n const minSwitchMargin = 1.4;\n const minSustainBeats = 12;\n const threeFavored = this._ts3Confidence > this._ts4Confidence * minSwitchMargin;\n const fourFavored = this._ts4Confidence > this._ts3Confidence * minSwitchMargin;\n if (this._activeTs === \"4/4\" && threeFavored) {\n this._sustainCounter++;\n if (this._sustainCounter >= minSustainBeats) {\n this._activeTs = \"3/4\";\n this._sustainCounter = 0;\n }\n } else if (this._activeTs === \"3/4\" && fourFavored) {\n this._sustainCounter++;\n if (this._sustainCounter >= minSustainBeats + 4) {\n this._activeTs = \"4/4\";\n this._sustainCounter = 0;\n }\n } else {\n this._sustainCounter = 0;\n }\n }\n const barLen = this._activeTs === \"3/4\" ? 3 : 4;\n const posterior = this._activeTs === \"3/4\" ? p3 : p4;\n if (this._beatsSinceStart >= barLen) {\n let maxP = -1;\n let maxI = 0;\n for (let i = 0; i < barLen; i++) {\n if (posterior[i] > maxP) {\n maxP = posterior[i];\n maxI = i;\n }\n }\n const newPos = maxI + 1;\n if (newPos === 1 && this._barPosition !== 1) {\n this._barNumber++;\n }\n this._barPosition = newPos;\n } else {\n this._barPosition = this._barPosition % barLen + 1;\n if (this._barPosition === 1) this._barNumber++;\n }\n }\n _updateConfidence() {\n if (this._candidates.length === 0) {\n this._confidence = 0;\n return;\n }\n const top1 = this._candidates[0] ? this._candidates[0].score : 0;\n const top2 = this._candidates[1] ? this._candidates[1].score : top1;\n const top3 = this._candidates[2] ? this._candidates[2].score : top2;\n const peakContrast = top2 + top3 > 0 ? top1 / ((top2 + top3) / 2) : 1;\n let ibiMean = 0;\n for (let i = 0; i < 4; i++) ibiMean += this._ibiHistory[i];\n ibiMean /= 4;\n let ibiVar = 0;\n for (let i = 0; i < 4; i++) {\n const d = this._ibiHistory[i] - ibiMean;\n ibiVar += d * d;\n }\n ibiVar /= 4;\n const phaseConsistency = ibiMean > 0 ? Math.max(0, 1 - ibiVar / (ibiMean * ibiMean)) : 0;\n const activePosterior = this._activeTs === \"3/4\" ? this._posterior3 : this._posterior4;\n const activeLen = this._activeTs === \"3/4\" ? 3 : 4;\n let maxP = 0;\n for (let i = 0; i < activeLen; i++) {\n if (activePosterior[i] > maxP) maxP = activePosterior[i];\n }\n const barConsistency = maxP;\n const c = Math.sqrt(Math.max(0, peakContrast / 2)) * Math.sqrt(Math.max(0, phaseConsistency)) * (0.5 + 0.5 * barConsistency);\n this._confidence = Math.max(0, Math.min(1, c));\n }\n _updateLookahead(lastBeatTime) {\n const lookahead = [];\n const beatInterval = 60 / this._bestBpm;\n const barPos = this._barPosition;\n const barLen = this._activeTs === \"3/4\" ? 3 : 4;\n for (let i = 0; i < 8; i++) {\n const t = lastBeatTime + (i + 1) * beatInterval;\n const bp = (barPos - 1 + i) % barLen + 1;\n lookahead.push({\n audioTime: t,\n tempo: this._bestBpm,\n isDownbeat: bp === 1,\n beatInBar: bp\n });\n }\n this._lookahead = lookahead;\n }\n _computeBandEnergy() {\n let low = 0;\n let mid = 0;\n let high = 0;\n for (let b = 0; b < this._lowBandEnd; b++) low += this._melOut[b];\n for (let b = this._lowBandEnd; b < this._midBandEnd; b++) mid += this._melOut[b];\n for (let b = this._midBandEnd; b < this._melBands; b++) high += this._melOut[b];\n const denom = this._lowBandEnd || 1;\n return {\n low: low / denom,\n mid: mid / Math.max(1, this._midBandEnd - this._lowBandEnd),\n high: high / Math.max(1, this._melBands - this._midBandEnd)\n };\n }\n _sendStateMessage() {\n const settled = this._locked;\n const beatInterval = this._bestBpm > 0 ? 60 / this._bestBpm : 0;\n const currentTime = this._sampleCount / this._sampleRate;\n const lastBeatTime = this._lastBeatSample >= 0 ? this._lastBeatSample / this._sampleRate : 0;\n const beatPhase = beatInterval > 0 ? Math.min(1, (currentTime - lastBeatTime) / beatInterval) : 0;\n const nextBeatTime = lastBeatTime + beatInterval;\n let nextDownbeatTime = nextBeatTime;\n for (let i = 0; i < this._lookahead.length; i++) {\n if (this._lookahead[i].isDownbeat) {\n nextDownbeatTime = this._lookahead[i].audioTime;\n break;\n }\n }\n const be = this._computeBandEnergy();\n this.port.postMessage({\n type: \"state\",\n tempo: settled ? this._bestBpm : 0,\n beatPhase,\n confidence: settled ? this._confidence : 0,\n gridStability: settled ? this._confidence : 0,\n tempoCandidates: settled ? this._candidates.map((c) => ({ bpm: c.bpm, score: c.score })) : [],\n rms: this._rms,\n onsetStrength: this._onsetStrength,\n bandEnergy: be,\n barPosition: this._barPosition,\n barLength: this._activeTs === \"3/4\" ? 3 : 4,\n timeSignature: this._activeTs === \"3/4\" ? { numerator: 3, denominator: 4 } : { numerator: 4, denominator: 4 },\n lookahead: this._lookahead,\n nextBeatTime: settled ? nextBeatTime : 0,\n nextDownbeatTime: settled ? nextDownbeatTime : 0\n });\n }\n };\n registerProcessor(\"exojs-beat-detector\", BeatDetectorProcessor);\n})();\n";
12
3
 
13
- function bitReversePermute(real, imag) {
14
- var n = real.length;
15
- var j = 0;
16
- for (var i = 1; i < n; i++) {
17
- var bit = n >> 1;
18
- for (; j & bit; bit >>= 1) { j ^= bit; }
19
- j ^= bit;
20
- if (i < j) {
21
- var t = real[i]; real[i] = real[j]; real[j] = t;
22
- t = imag[i]; imag[i] = imag[j]; imag[j] = t;
23
- }
24
- }
25
- }
26
-
27
- function fftInPlace(real, imag) {
28
- applyHannWindow(real, imag);
29
- bitReversePermute(real, imag);
30
- var n = real.length;
31
- for (var len = 2; len <= n; len <<= 1) {
32
- var halfLen = len >> 1;
33
- var step = -2 * Math.PI / len;
34
- for (var i = 0; i < n; i += len) {
35
- for (var k = 0; k < halfLen; k++) {
36
- var angle = step * k;
37
- var cos = Math.cos(angle);
38
- var sin = Math.sin(angle);
39
- var re = real[i+k+halfLen]*cos - imag[i+k+halfLen]*sin;
40
- var im = real[i+k+halfLen]*sin + imag[i+k+halfLen]*cos;
41
- real[i+k+halfLen] = real[i+k] - re;
42
- imag[i+k+halfLen] = imag[i+k] - im;
43
- real[i+k] += re;
44
- imag[i+k] += im;
45
- }
46
- }
47
- }
48
- }
49
-
50
- // ---- Mel filterbank ----
51
- function buildMelFilterbank(numBands, fMin, fMax, fftSize, sampleRate) {
52
- var numBins = fftSize >> 1;
53
- var nyquist = sampleRate / 2;
54
- var melMin = 2595 * Math.log10(1 + fMin / 700);
55
- var melMax = 2595 * Math.log10(1 + fMax / 700);
56
- var melPoints = new Float32Array(numBands + 2);
57
- for (var i = 0; i < numBands + 2; i++) {
58
- melPoints[i] = melMin + (melMax - melMin) * i / (numBands + 1);
59
- }
60
- var binPoints = new Float32Array(numBands + 2);
61
- for (var i = 0; i < numBands + 2; i++) {
62
- var hz = 700 * (Math.pow(10, melPoints[i] / 2595) - 1);
63
- binPoints[i] = Math.round(hz / nyquist * (numBins - 1));
64
- }
65
- var bands = [];
66
- for (var b = 0; b < numBands; b++) {
67
- var startBin = Math.max(0, Math.min(numBins - 1, binPoints[b]));
68
- var peakBin = Math.max(0, Math.min(numBins - 1, binPoints[b+1]));
69
- var endBin = Math.max(0, Math.min(numBins - 1, binPoints[b+2]));
70
- var len = endBin - startBin + 1;
71
- var weights = new Float32Array(len);
72
- for (var i = 0; i < len; i++) {
73
- var bin = startBin + i;
74
- if (bin <= peakBin && peakBin > startBin) {
75
- weights[i] = (bin - startBin) / (peakBin - startBin);
76
- } else if (bin > peakBin && endBin > peakBin) {
77
- weights[i] = (endBin - bin) / (endBin - peakBin);
78
- } else {
79
- weights[i] = 1;
80
- }
81
- }
82
- bands.push({ startBin: startBin, peakBin: peakBin, endBin: endBin, weights: weights });
83
- }
84
- return bands;
85
- }
86
-
87
- function computeMelBands(mag, bands, out) {
88
- for (var b = 0; b < bands.length; b++) {
89
- var band = bands[b];
90
- var energy = 0;
91
- for (var i = 0; i < band.weights.length; i++) {
92
- energy += mag[band.startBin + i] * band.weights[i];
93
- }
94
- out[b] = Math.log(1 + energy);
95
- }
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
-
231
- // ---- Processor ----
232
- class BeatDetectorProcessor extends AudioWorkletProcessor {
233
- constructor(options) {
234
- super();
235
- var opts = (options && options.processorOptions) || {};
236
- this._sampleRate = sampleRate;
237
- this._fftSize = opts.fftSize || 2048;
238
- this._hopSize = opts.hopSize || 512;
239
- this._minBpm = opts.minBpm || 50;
240
- this._maxBpm = opts.maxBpm || 300;
241
- this._melBands = opts.melBands || 24;
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;
252
- this._enableTsDetection = opts.enableTimeSignatureDetection !== false;
253
-
254
- var numBins = this._fftSize >> 1;
255
- this._real = new Float32Array(this._fftSize);
256
- this._imag = new Float32Array(this._fftSize);
257
- this._mag = new Float32Array(numBins);
258
- this._ringBuffer = new Float32Array(this._fftSize);
259
- this._ringWritePos = 0;
260
- this._sampleCount = 0;
261
- this._hopAccum = 0;
262
-
263
- this._melBandFilters = buildMelFilterbank(this._melBands, 80, 8000, this._fftSize, this._sampleRate);
264
- this._melOut = new Float32Array(this._melBands);
265
- var fluxWindowLen = Math.ceil(this._stableTempoWindowSec * this._sampleRate / this._hopSize);
266
- this._fluxWindow = new Float32Array(fluxWindowLen);
267
- this._linFlux = new Float32Array(fluxWindowLen); // scratch: ring → linear (oldest first)
268
- this._fluxWritePos = 0;
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));
274
- var LAG_K = 3;
275
- this._prevMelFrames = [];
276
- for (var i = 0; i < LAG_K; i++) {
277
- this._prevMelFrames.push(new Float32Array(this._melBands));
278
- }
279
- this._prevMelFrameIdx = 0;
280
-
281
- // Lag range in hops for BPM range
282
- this._minLag = Math.max(1, Math.round(60 / this._maxBpm * this._sampleRate / this._hopSize));
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
289
-
290
- this._hopsSinceACF = 0;
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));
294
-
295
- // Tempo state
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
305
-
306
- // Phase state
307
- this._lastBeatSample = -1;
308
- this._ibiSamples = 0; // PLL-tracked inter-beat interval (samples); seeded from ACF tempo
309
- this._ibiHistory = new Float32Array(4); // last 4 inter-beat intervals
310
- this._ibiIdx = 0;
311
-
312
- // Bar position state — parallel posteriors for 4/4 and 3/4
313
- this._posterior4 = new Float32Array([0.25, 0.25, 0.25, 0.25]);
314
- this._posterior3 = new Float32Array([1/3, 1/3, 1/3]);
315
- this._ts4Confidence = 0.5;
316
- this._ts3Confidence = 0.5;
317
- this._activeTs = '4/4';
318
- this._sustainCounter = 0;
319
- this._barPosition = 1; // 1-indexed
320
- this._barNumber = 0;
321
- this._beatsSinceStart = 0;
322
-
323
- // Confidence
324
- this._confidence = 0;
325
-
326
- // State snapshot cadence (~20 Hz)
327
- var STATE_INTERVAL_HOPS = Math.round(this._sampleRate / this._hopSize / 20);
328
- this._stateInterval = Math.max(1, STATE_INTERVAL_HOPS);
329
- this._hopsSinceState = 0;
330
-
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)
343
-
344
- // Lookahead
345
- this._lookahead = [];
346
-
347
- // RMS / onset state
348
- this._rms = 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;
371
-
372
- // Band energy (for state messages)
373
- var LOW_BANDS = Math.round(this._melBands * 0.25);
374
- var MID_BANDS = Math.round(this._melBands * 0.6);
375
- this._lowBandEnd = LOW_BANDS;
376
- this._midBandEnd = MID_BANDS;
377
- }
378
-
379
- process(inputs, _outputs, _parameters) {
380
- var input = inputs[0];
381
- if (!input || input.length === 0) return true;
382
-
383
- var left = input[0] || [];
384
- var right = input[1] || left;
385
- var blockLen = left.length;
386
-
387
- for (var s = 0; s < blockLen; s++) {
388
- // Mono downmix
389
- var mono = (left[s] + right[s]) * 0.5;
390
-
391
- // Accumulate RMS
392
- this._rms += mono * mono;
393
-
394
- // Fill ring buffer
395
- this._ringBuffer[this._ringWritePos] = mono;
396
- this._ringWritePos = (this._ringWritePos + 1) & (this._fftSize - 1);
397
-
398
- this._hopAccum++;
399
- this._sampleCount++;
400
-
401
- if (this._hopAccum >= this._hopSize) {
402
- this._hopAccum = 0;
403
- this._processHop();
404
- }
405
- }
406
-
407
- return true;
408
- }
409
-
410
- _processHop() {
411
- // Read ring buffer into real[] (oldest first)
412
- var rb = this._ringBuffer;
413
- var wp = this._ringWritePos;
414
- var n = this._fftSize;
415
- for (var i = 0; i < n; i++) {
416
- this._real[i] = rb[(wp + i) & (n - 1)];
417
- }
418
-
419
- // FFT
420
- fftInPlace(this._real, this._imag);
421
-
422
- // Magnitude spectrum
423
- var bins = n >> 1;
424
- for (var i = 0; i < bins; i++) {
425
- this._mag[i] = Math.sqrt(this._real[i]*this._real[i] + this._imag[i]*this._imag[i]);
426
- }
427
-
428
- // RMS (from time domain, using ring buffer)
429
- var rmsAccum = 0;
430
- for (var i = 0; i < n; i++) {
431
- rmsAccum += rb[(wp + i) & (n - 1)] * rb[(wp + i) & (n - 1)];
432
- }
433
- this._rms = Math.sqrt(rmsAccum / n);
434
-
435
- // Mel bands
436
- computeMelBands(this._mag, this._melBandFilters, this._melOut);
437
-
438
- // Spectral flux (SuperFlux-lite, lag k=3)
439
- var K = this._prevMelFrames.length;
440
- var flux = 0;
441
- for (var b = 0; b < this._melBands; b++) {
442
- var localMax = -Infinity;
443
- for (var k = 0; k < K; k++) {
444
- var prevVal = this._prevMelFrames[k][b];
445
- if (prevVal > localMax) localMax = prevVal;
446
- }
447
- var diff = this._melOut[b] - localMax;
448
- if (diff > 0) flux += diff;
449
- }
450
-
451
- // Store current mel frame in circular buffer
452
- var prevFrame = this._prevMelFrames[this._prevMelFrameIdx];
453
- for (var b = 0; b < this._melBands; b++) {
454
- prevFrame[b] = this._melOut[b];
455
- }
456
- this._prevMelFrameIdx = (this._prevMelFrameIdx + 1) % K;
457
-
458
- // Add flux to sliding window
459
- this._fluxWindow[this._fluxWritePos] = flux;
460
- this._fluxWritePos = (this._fluxWritePos + 1) % this._fluxWindow.length;
461
- if (this._fluxCount < this._fluxWindow.length) this._fluxCount++;
462
-
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.
472
- this._hopsSinceACF++;
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) {
480
- this._hopsSinceACF = 0;
481
- this._computeACFAndCandidates();
482
- }
483
-
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) {
489
- this._tickPhase(flux);
490
- }
491
-
492
- // State snapshot
493
- this._hopsSinceState++;
494
- if (this._hopsSinceState >= this._stateInterval) {
495
- this._hopsSinceState = 0;
496
- this._sendStateMessage();
497
- }
498
- }
499
-
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) {
507
- var buf = this._fluxWindow;
508
- var wp = this._fluxWritePos;
509
- var len = buf.length;
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];
522
- }
523
-
524
- // ACF (mean-subtracted, biased, zero-lag normalised) — mirrors computeAcf.
525
- var acf = this._acf;
526
- computeAcfInline(lin, n, minLag, maxLag, acf);
527
-
528
- // Raw positive peaks (interior + endpoints) — mirrors findTempoPeaks.
529
- var peaks = [];
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++) {
535
- if (acf[i] > acf[i-1] && acf[i] > acf[i+1] && acf[i] > 0) {
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 });
538
- }
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
- }
544
- peaks.sort(function(a, b) { return b.score - a.score; });
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;
587
- if (this._candidates.length === 0) return;
588
-
589
- var top = this._candidates[0];
590
-
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.
599
- this._bestBpm = top.bpm;
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
- }
621
- } else {
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) {
646
- var oldBpm = this._bestBpm;
647
- this._bestBpm = top.bpm;
648
- this._bestScore = top.score;
649
- // Only fire tempoChange if > 5% different
650
- if (Math.abs(this._bestBpm - oldBpm) / oldBpm > 0.05) {
651
- this.port.postMessage({ type: 'tempoChange', newTempo: this._bestBpm, oldTempo: oldBpm });
652
- }
653
- } else {
654
- this._bestScore = currentScore;
655
- }
656
-
657
- // --- Fast-window drift adaptation: follows a genuine, sustained DJ drift. ---
658
- this._trackDrift(fast);
659
- }
660
-
661
- this._updateConfidence();
662
- }
663
-
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;
684
- return;
685
- }
686
-
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 });
702
- }
703
- }
704
- }
705
-
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
- }
716
-
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
- }
781
-
782
- // Shift history for the next hop.
783
- this._onsetPrev1 = norm;
784
- this._onsetHopCount++;
785
- }
786
-
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
- }
805
-
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;
830
-
831
- // Update IBI history with the current PLL period.
832
- this._ibiHistory[this._ibiIdx] = this._ibiSamples;
833
- this._ibiIdx = (this._ibiIdx + 1) & 3;
834
-
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',
873
- audioTime: beatTime,
874
- tempo: this._bestBpm,
875
- confidence: this._confidence,
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;
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);
949
- }
950
-
951
- _computeBeatLikelihood(flux) {
952
- var count = Math.min(this._fluxCount, 32);
953
- var wp = this._fluxWritePos;
954
- var len = this._fluxWindow.length;
955
- var totalFlux = 0;
956
- for (var i = 0; i < count; i++) {
957
- totalFlux += this._fluxWindow[(wp - 1 - i + len) % len];
958
- }
959
- var mean = count > 0 ? totalFlux / count : 1;
960
- return Math.max(0.5, Math.min(1.5, mean > 0 ? flux / mean : 1));
961
- }
962
-
963
- _updateBarPosition(flux) {
964
- var likelihood = this._computeBeatLikelihood(flux);
965
-
966
- // --- 4/4 posterior ---
967
- var p4 = this._posterior4;
968
- var s4 = new Float32Array(4);
969
- s4[0] = p4[3]; s4[1] = p4[0]; s4[2] = p4[1]; s4[3] = p4[2];
970
- var sum4 = 0;
971
- for (var i = 0; i < 4; i++) {
972
- p4[i] = s4[i] * (likelihood + (i === 0 ? 0.3 : 0));
973
- sum4 += p4[i];
974
- }
975
- if (sum4 > 0) { for (var i = 0; i < 4; i++) p4[i] /= sum4; }
976
-
977
- // --- 3/4 posterior ---
978
- var p3 = this._posterior3;
979
- var s3 = new Float32Array(3);
980
- s3[0] = p3[2]; s3[1] = p3[0]; s3[2] = p3[1];
981
- var sum3 = 0;
982
- for (var i = 0; i < 3; i++) {
983
- p3[i] = s3[i] * (likelihood + (i === 0 ? 0.3 : 0));
984
- sum3 += p3[i];
985
- }
986
- if (sum3 > 0) { for (var i = 0; i < 3; i++) p3[i] /= sum3; }
987
-
988
- // --- Update TS confidences (EMA) ---
989
- var max4 = 0;
990
- for (var i = 0; i < 4; i++) { if (p4[i] > max4) max4 = p4[i]; }
991
- var max3 = 0;
992
- for (var i = 0; i < 3; i++) { if (p3[i] > max3) max3 = p3[i]; }
993
- var alpha = 0.1;
994
- this._ts4Confidence = (1 - alpha) * this._ts4Confidence + alpha * max4;
995
- this._ts3Confidence = (1 - alpha) * this._ts3Confidence + alpha * max3;
996
-
997
- // --- Hysteresis switching ---
998
- if (this._enableTsDetection && this._beatsSinceStart > 8) {
999
- var minSwitchMargin = 1.4;
1000
- var minSustainBeats = 12; // ~4 bars * 3 beats
1001
- var threeFavored = this._ts3Confidence > this._ts4Confidence * minSwitchMargin;
1002
- var fourFavored = this._ts4Confidence > this._ts3Confidence * minSwitchMargin;
1003
-
1004
- if (this._activeTs === '4/4' && threeFavored) {
1005
- this._sustainCounter++;
1006
- if (this._sustainCounter >= minSustainBeats) {
1007
- this._activeTs = '3/4';
1008
- this._sustainCounter = 0;
1009
- }
1010
- } else if (this._activeTs === '3/4' && fourFavored) {
1011
- this._sustainCounter++;
1012
- if (this._sustainCounter >= minSustainBeats + 4) { // 16 beats for 4/4
1013
- this._activeTs = '4/4';
1014
- this._sustainCounter = 0;
1015
- }
1016
- } else {
1017
- this._sustainCounter = 0;
1018
- }
1019
- }
1020
-
1021
- // --- Determine bar position from active TS ---
1022
- var barLen = this._activeTs === '3/4' ? 3 : 4;
1023
- var posterior = this._activeTs === '3/4' ? p3 : p4;
1024
-
1025
- if (this._beatsSinceStart >= barLen) {
1026
- var maxP = -1, maxI = 0;
1027
- for (var i = 0; i < barLen; i++) {
1028
- if (posterior[i] > maxP) { maxP = posterior[i]; maxI = i; }
1029
- }
1030
- var newPos = maxI + 1; // 1-indexed
1031
- if (newPos === 1 && this._barPosition !== 1) {
1032
- this._barNumber++;
1033
- }
1034
- this._barPosition = newPos;
1035
- } else {
1036
- // Just advance sequentially
1037
- this._barPosition = ((this._barPosition) % barLen) + 1;
1038
- if (this._barPosition === 1) this._barNumber++;
1039
- }
1040
- }
1041
-
1042
- _updateConfidence() {
1043
- if (this._candidates.length === 0) {
1044
- this._confidence = 0;
1045
- return;
1046
- }
1047
-
1048
- // Peak contrast
1049
- var top1 = this._candidates[0] ? this._candidates[0].score : 0;
1050
- var top2 = this._candidates[1] ? this._candidates[1].score : top1;
1051
- var top3 = this._candidates[2] ? this._candidates[2].score : top2;
1052
- var peakContrast = (top2 + top3) > 0 ? top1 / ((top2 + top3) / 2) : 1;
1053
-
1054
- // Phase consistency from IBI variance
1055
- var ibiMean = 0;
1056
- for (var i = 0; i < 4; i++) ibiMean += this._ibiHistory[i];
1057
- ibiMean /= 4;
1058
- var ibiVar = 0;
1059
- for (var i = 0; i < 4; i++) {
1060
- var d = this._ibiHistory[i] - ibiMean;
1061
- ibiVar += d * d;
1062
- }
1063
- ibiVar /= 4;
1064
- var phaseConsistency = ibiMean > 0 ? Math.max(0, 1 - ibiVar / (ibiMean * ibiMean)) : 0;
1065
-
1066
- // Bar consistency (use the active posterior)
1067
- var activePosterior = this._activeTs === '3/4' ? this._posterior3 : this._posterior4;
1068
- var activeLen = this._activeTs === '3/4' ? 3 : 4;
1069
- var maxP = 0;
1070
- for (var i = 0; i < activeLen; i++) {
1071
- if (activePosterior[i] > maxP) maxP = activePosterior[i];
1072
- }
1073
- var barConsistency = maxP;
1074
-
1075
- var c = Math.sqrt(Math.max(0, peakContrast / 2)) *
1076
- Math.sqrt(Math.max(0, phaseConsistency)) *
1077
- (0.5 + 0.5 * barConsistency);
1078
- this._confidence = Math.max(0, Math.min(1, c));
1079
- }
1080
-
1081
- _updateLookahead(lastBeatTime) {
1082
- var lookahead = [];
1083
- var beatInterval = 60 / this._bestBpm;
1084
- var barPos = this._barPosition;
1085
- var barLen = this._activeTs === '3/4' ? 3 : 4;
1086
- for (var i = 0; i < 8; i++) {
1087
- var t = lastBeatTime + (i + 1) * beatInterval;
1088
- var bp = ((barPos - 1 + i) % barLen) + 1;
1089
- lookahead.push({
1090
- audioTime: t,
1091
- tempo: this._bestBpm,
1092
- isDownbeat: bp === 1,
1093
- beatInBar: bp,
1094
- });
1095
- }
1096
- this._lookahead = lookahead;
1097
- }
1098
-
1099
- _computeBandEnergy() {
1100
- var low = 0, mid = 0, high = 0;
1101
- for (var b = 0; b < this._lowBandEnd; b++) low += this._melOut[b];
1102
- for (var b = this._lowBandEnd; b < this._midBandEnd; b++) mid += this._melOut[b];
1103
- for (var b = this._midBandEnd; b < this._melBands; b++) high += this._melOut[b];
1104
- var denom = this._lowBandEnd || 1;
1105
- return {
1106
- low: low / denom,
1107
- mid: mid / Math.max(1, this._midBandEnd - this._lowBandEnd),
1108
- high: high / Math.max(1, this._melBands - this._midBandEnd),
1109
- };
1110
- }
1111
-
1112
- _sendStateMessage() {
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;
1117
- var beatInterval = this._bestBpm > 0 ? 60 / this._bestBpm : 0;
1118
- var currentTime = this._sampleCount / this._sampleRate;
1119
- var lastBeatTime = this._lastBeatSample >= 0 ? this._lastBeatSample / this._sampleRate : 0;
1120
- var beatPhase = beatInterval > 0
1121
- ? Math.min(1, (currentTime - lastBeatTime) / beatInterval)
1122
- : 0;
1123
- var nextBeatTime = lastBeatTime + beatInterval;
1124
-
1125
- var nextDownbeatTime = nextBeatTime;
1126
- for (var i = 0; i < this._lookahead.length; i++) {
1127
- if (this._lookahead[i].isDownbeat) {
1128
- nextDownbeatTime = this._lookahead[i].audioTime;
1129
- break;
1130
- }
1131
- }
1132
-
1133
- var be = this._computeBandEnergy();
1134
-
1135
- this.port.postMessage({
1136
- type: 'state',
1137
- tempo: settled ? this._bestBpm : 0,
1138
- beatPhase: beatPhase,
1139
- confidence: settled ? this._confidence : 0,
1140
- gridStability: settled ? this._confidence : 0,
1141
- tempoCandidates: settled ? this._candidates.map(function(c) {
1142
- return { bpm: c.bpm, score: c.score };
1143
- }) : [],
1144
- rms: this._rms,
1145
- onsetStrength: this._onsetStrength,
1146
- bandEnergy: be,
1147
- barPosition: this._barPosition,
1148
- barLength: this._activeTs === '3/4' ? 3 : 4,
1149
- timeSignature: this._activeTs === '3/4'
1150
- ? { numerator: 3, denominator: 4 }
1151
- : { numerator: 4, denominator: 4 },
1152
- lookahead: this._lookahead,
1153
- nextBeatTime: settled ? nextBeatTime : 0,
1154
- nextDownbeatTime: settled ? nextDownbeatTime : 0,
1155
- });
1156
- }
1157
- }
1158
-
1159
- registerProcessor('exojs-beat-detector', BeatDetectorProcessor);
1160
- `;
1161
-
1162
- export { beatDetectorWorkletSource };
1163
- //# sourceMappingURL=beat-detector.worklet.js.map
4
+ //#endregion
5
+ export { beat_detector_worklet_default as default };
6
+ //# sourceMappingURL=beat-detector.worklet.js.map