@codexo/exojs-audio-fx 0.15.3 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/AudioAnalyser.d.ts +4 -3
- package/dist/esm/AudioAnalyser.d.ts.map +1 -0
- package/dist/esm/AudioAnalyser.js +365 -468
- package/dist/esm/AudioAnalyser.js.map +1 -1
- package/dist/esm/BeatDetector.d.ts +16 -15
- package/dist/esm/BeatDetector.d.ts.map +1 -0
- package/dist/esm/BeatDetector.js +370 -428
- package/dist/esm/BeatDetector.js.map +1 -1
- package/dist/esm/dsp/fft.d.ts +5 -5
- package/dist/esm/dsp/fft.d.ts.map +1 -0
- package/dist/esm/dsp/mel.d.ts +6 -6
- package/dist/esm/dsp/mel.d.ts.map +1 -0
- package/dist/esm/dsp/mel.js +55 -64
- package/dist/esm/dsp/mel.js.map +1 -1
- package/dist/esm/dsp/tempogram.d.ts +60 -20
- package/dist/esm/dsp/tempogram.d.ts.map +1 -0
- package/dist/esm/effects/AutoWahEffect.d.ts +3 -2
- package/dist/esm/effects/AutoWahEffect.d.ts.map +1 -0
- package/dist/esm/effects/AutoWahEffect.js +210 -237
- package/dist/esm/effects/AutoWahEffect.js.map +1 -1
- package/dist/esm/effects/BitCrusherEffect.d.ts +3 -2
- package/dist/esm/effects/BitCrusherEffect.d.ts.map +1 -0
- package/dist/esm/effects/BitCrusherEffect.js +72 -70
- package/dist/esm/effects/BitCrusherEffect.js.map +1 -1
- package/dist/esm/effects/ChorusEffect.d.ts +2 -1
- package/dist/esm/effects/ChorusEffect.d.ts.map +1 -0
- package/dist/esm/effects/ChorusEffect.js +132 -150
- package/dist/esm/effects/ChorusEffect.js.map +1 -1
- package/dist/esm/effects/CompressorEffect.d.ts +2 -1
- package/dist/esm/effects/CompressorEffect.d.ts.map +1 -0
- package/dist/esm/effects/CompressorEffect.js +104 -118
- package/dist/esm/effects/CompressorEffect.js.map +1 -1
- package/dist/esm/effects/ConvolutionEffect.d.ts +10 -5
- package/dist/esm/effects/ConvolutionEffect.d.ts.map +1 -0
- package/dist/esm/effects/ConvolutionEffect.js +208 -189
- package/dist/esm/effects/ConvolutionEffect.js.map +1 -1
- package/dist/esm/effects/DelayEffect.d.ts +1 -0
- package/dist/esm/effects/DelayEffect.d.ts.map +1 -0
- package/dist/esm/effects/DelayEffect.js +105 -109
- package/dist/esm/effects/DelayEffect.js.map +1 -1
- package/dist/esm/effects/DistortionEffect.d.ts +4 -3
- package/dist/esm/effects/DistortionEffect.d.ts.map +1 -0
- package/dist/esm/effects/DistortionEffect.js +190 -195
- package/dist/esm/effects/DistortionEffect.js.map +1 -1
- package/dist/esm/effects/DuckingEffect.d.ts +3 -2
- package/dist/esm/effects/DuckingEffect.d.ts.map +1 -0
- package/dist/esm/effects/DuckingEffect.js +91 -172
- package/dist/esm/effects/DuckingEffect.js.map +1 -1
- package/dist/esm/effects/EqualizerEffect.d.ts +1 -0
- package/dist/esm/effects/EqualizerEffect.d.ts.map +1 -0
- package/dist/esm/effects/EqualizerEffect.js +120 -133
- package/dist/esm/effects/EqualizerEffect.js.map +1 -1
- package/dist/esm/effects/FlangerEffect.d.ts +7 -6
- package/dist/esm/effects/FlangerEffect.d.ts.map +1 -0
- package/dist/esm/effects/FlangerEffect.js +172 -201
- package/dist/esm/effects/FlangerEffect.js.map +1 -1
- package/dist/esm/effects/GranularEffect.d.ts +3 -2
- package/dist/esm/effects/GranularEffect.d.ts.map +1 -0
- package/dist/esm/effects/GranularEffect.js +100 -95
- package/dist/esm/effects/GranularEffect.js.map +1 -1
- package/dist/esm/effects/LimiterEffect.d.ts +1 -0
- package/dist/esm/effects/LimiterEffect.d.ts.map +1 -0
- package/dist/esm/effects/LimiterEffect.js +182 -194
- package/dist/esm/effects/LimiterEffect.js.map +1 -1
- package/dist/esm/effects/PhaserEffect.d.ts +2 -1
- package/dist/esm/effects/PhaserEffect.d.ts.map +1 -0
- package/dist/esm/effects/PhaserEffect.js +214 -254
- package/dist/esm/effects/PhaserEffect.js.map +1 -1
- package/dist/esm/effects/PingPongDelayEffect.d.ts +2 -1
- package/dist/esm/effects/PingPongDelayEffect.d.ts.map +1 -0
- package/dist/esm/effects/PingPongDelayEffect.js +172 -185
- package/dist/esm/effects/PingPongDelayEffect.js.map +1 -1
- package/dist/esm/effects/PitchShiftEffect.d.ts +3 -2
- package/dist/esm/effects/PitchShiftEffect.d.ts.map +1 -0
- package/dist/esm/effects/PitchShiftEffect.js +60 -60
- package/dist/esm/effects/PitchShiftEffect.js.map +1 -1
- package/dist/esm/effects/ReverbEffect.d.ts +2 -1
- package/dist/esm/effects/ReverbEffect.d.ts.map +1 -0
- package/dist/esm/effects/ReverbEffect.js +113 -117
- package/dist/esm/effects/ReverbEffect.js.map +1 -1
- package/dist/esm/effects/RingModulatorEffect.d.ts +4 -3
- package/dist/esm/effects/RingModulatorEffect.d.ts.map +1 -0
- package/dist/esm/effects/RingModulatorEffect.js +153 -161
- package/dist/esm/effects/RingModulatorEffect.js.map +1 -1
- package/dist/esm/effects/TremoloEffect.d.ts +1 -0
- package/dist/esm/effects/TremoloEffect.d.ts.map +1 -0
- package/dist/esm/effects/TremoloEffect.js +193 -201
- package/dist/esm/effects/TremoloEffect.js.map +1 -1
- package/dist/esm/effects/VocoderEffect.d.ts +2 -1
- package/dist/esm/effects/VocoderEffect.d.ts.map +1 -0
- package/dist/esm/effects/VocoderEffect.js +69 -80
- package/dist/esm/effects/VocoderEffect.js.map +1 -1
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +23 -22
- package/dist/esm/worklets/beat-detector.worklet.js +5 -1162
- package/dist/esm/worklets/beat-detector.worklet.js.map +1 -1
- package/dist/esm/worklets/bit-crusher.worklet.js +5 -44
- package/dist/esm/worklets/bit-crusher.worklet.js.map +1 -1
- package/dist/esm/worklets/ducking.worklet.js +6 -0
- package/dist/esm/worklets/ducking.worklet.js.map +1 -0
- package/dist/esm/worklets/granular.worklet.js +5 -97
- package/dist/esm/worklets/granular.worklet.js.map +1 -1
- package/dist/esm/worklets/pitch-shift.worklet.js +5 -128
- package/dist/esm/worklets/pitch-shift.worklet.js.map +1 -1
- package/dist/esm/worklets/vocoder.worklet.js +5 -93
- package/dist/esm/worklets/vocoder.worklet.js.map +1 -1
- package/package.json +7 -7
- package/dist/esm/index.js.map +0 -1
- package/dist/esm/worklets/beat-detector.worklet.d.ts +0 -1
- package/dist/esm/worklets/bit-crusher.worklet.d.ts +0 -1
- package/dist/esm/worklets/granular.worklet.d.ts +0 -1
- package/dist/esm/worklets/pitch-shift.worklet.d.ts +0 -1
- package/dist/esm/worklets/vocoder.worklet.d.ts +0 -1
package/dist/esm/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const beatDetectorWorkletSource = "\n// ---- Hann window + FFT (radix-2 Cooley-Tukey) ----\nfunction applyHannWindow(real, imag) {\n var n = real.length;\n for (var i = 0; i < n; i++) {\n var w = 0.5 * (1 - Math.cos(2 * Math.PI * i / (n - 1)));\n real[i] *= w;\n imag[i] = 0;\n }\n}\n\nfunction bitReversePermute(real, imag) {\n var n = real.length;\n var j = 0;\n for (var i = 1; i < n; i++) {\n var bit = n >> 1;\n for (; j & bit; bit >>= 1) { j ^= bit; }\n j ^= bit;\n if (i < j) {\n var t = real[i]; real[i] = real[j]; real[j] = t;\n t = imag[i]; imag[i] = imag[j]; imag[j] = t;\n }\n }\n}\n\nfunction fftInPlace(real, imag) {\n applyHannWindow(real, imag);\n bitReversePermute(real, imag);\n var n = real.length;\n for (var len = 2; len <= n; len <<= 1) {\n var halfLen = len >> 1;\n var step = -2 * Math.PI / len;\n for (var i = 0; i < n; i += len) {\n for (var k = 0; k < halfLen; k++) {\n var angle = step * k;\n var cos = Math.cos(angle);\n var sin = Math.sin(angle);\n var re = real[i+k+halfLen]*cos - imag[i+k+halfLen]*sin;\n var 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// ---- Mel filterbank ----\nfunction buildMelFilterbank(numBands, fMin, fMax, fftSize, sampleRate) {\n var numBins = fftSize >> 1;\n var nyquist = sampleRate / 2;\n var melMin = 2595 * Math.log10(1 + fMin / 700);\n var melMax = 2595 * Math.log10(1 + fMax / 700);\n var melPoints = new Float32Array(numBands + 2);\n for (var i = 0; i < numBands + 2; i++) {\n melPoints[i] = melMin + (melMax - melMin) * i / (numBands + 1);\n }\n var binPoints = new Float32Array(numBands + 2);\n for (var i = 0; i < numBands + 2; i++) {\n var hz = 700 * (Math.pow(10, melPoints[i] / 2595) - 1);\n binPoints[i] = Math.round(hz / nyquist * (numBins - 1));\n }\n var bands = [];\n for (var b = 0; b < numBands; b++) {\n var startBin = Math.max(0, Math.min(numBins - 1, binPoints[b]));\n var peakBin = Math.max(0, Math.min(numBins - 1, binPoints[b+1]));\n var endBin = Math.max(0, Math.min(numBins - 1, binPoints[b+2]));\n var len = endBin - startBin + 1;\n var weights = new Float32Array(len);\n for (var i = 0; i < len; i++) {\n var 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: startBin, peakBin: peakBin, endBin: endBin, weights: weights });\n }\n return bands;\n}\n\nfunction computeMelBands(mag, bands, out) {\n for (var b = 0; b < bands.length; b++) {\n var band = bands[b];\n var energy = 0;\n for (var i = 0; i < band.weights.length; i++) {\n energy += mag[band.startBin + i] * band.weights[i];\n }\n out[b] = Math.log(1 + energy);\n }\n}\n\n// ---- Tempogram (single source of truth \u2014 transliterated from src/dsp/tempogram.ts) ----\n// Guarded by test/dsp/worklet-parity.test.ts: these MUST stay numerically identical to\n// computeAcf / scoreTempoHypotheses / computeTempoCandidates in src/dsp/tempogram.ts.\nvar TEMPO_PRIOR_MU = 140;\nvar TEMPO_PRIOR_SIGMA = Math.log(2) * 0.9;\nvar COMB_W_FUNDAMENTAL = 1.0;\nvar COMB_W_HALF = 0.5;\nvar COMB_W_THIRD = 0.3;\nvar COMB_PENALTY_DOUBLE = 1.0;\nvar COMB_PENALTY_TRIPLE = 0.5;\n\n// ---- Utility ----\n// Sorts arr[0..n-1] in-place using insertion sort. Avoids creating a subarray view so\n// the hot path (_detectOnset, ~93 calls/s) produces zero per-call GC pressure.\nfunction partialSort(arr, n) {\n for (var i = 1; i < n; i++) {\n var v = arr[i], j = i - 1;\n while (j >= 0 && arr[j] > v) { arr[j + 1] = arr[j]; j--; }\n arr[j + 1] = v;\n }\n}\n\n// ---- Onset peak-picker (T3): adaptive normalization + noise gate + refractory ----\n// The raw spectral flux is normalised against a running median/MAD baseline so that\n// soft onsets (low, broad novelty) and hard transients become comparable, then a\n// rising-edge picker (upward crossing of an adaptive threshold) with a noise-floor gate\n// and an IBI-derived refractory turns the novelty curve into a clean onset stream. This\n// stream (per-hop strength + sub-hop onset positions) is what the T4 PLL anchors to.\nvar ONSET_NORM_WINDOW_SEC = 1.5; // running median/MAD window for novelty normalization\nvar ONSET_MAD_SCALE = 1.4826; // MAD \u2192 \u03C3 consistency factor (Gaussian)\nvar ONSET_THRESHOLD = 3.0; // normalized-novelty peak threshold (robust z-score)\nvar ONSET_NOISE_FLOOR_FRAC = 0.1; // a peak must clear this fraction of the running flux peak\nvar ONSET_ABS_FLOOR = 1e-4; // absolute novelty floor \u2014 kills divide-by-noise in silence\nvar ONSET_PEAK_DECAY = 0.999; // per-hop decay of the running flux peak (noise-floor reference)\nvar ONSET_MIN_REFRACTORY_SEC = 0.1; // minimum spacing between detected onsets (~100 ms)\nvar ONSET_REFRACTORY_IBI_FRAC = 0.4; // once locked, refractory = max(min, frac \u00D7 IBI)\nvar ONSET_BEAT_COAST_IBI = 2.0; // suppress beat emission after this many IBIs without an onset\nvar ONSET_RING_SIZE = 16; // recent onsets retained for T4's PLL nearestOnset()\n\n// ---- PLL beat-phase tracker (T4) ----\n// A bounded phase-locked loop replaces the old constant-IBI predictor + buggy snap. Each\n// predicted beat is corrected toward the nearest detected onset (sub-hop precise, from the\n// T3 onset ring): a proportional phase nudge plus a small period adjustment, BOTH clamped so\n// a single noisy onset can never yank the grid. Exactly one beat is emitted per predicted\n// beat (the old snap double-advanced and timestamped a beat an IBI ahead). The first beat is\n// bootstrapped to a real recent onset, never an arbitrary settling boundary. The gains are\n// INTERNAL constants (API decision: not public). Tempo selection (T1/T1b/T2) is untouched \u2014\n// the PLL only refines phase/period locally around the ACF-chosen tempo.\nvar PLL_PHASE_GAIN = 0.25; // fraction of phase error applied as a phase nudge per beat\nvar PLL_TEMPO_GAIN = 0.03; // fraction of phase error folded into the period per beat\nvar PLL_MAX_PHASE_FRAC = 0.08; // |phaseCorr| clamp, fraction of the IBI\nvar PLL_MAX_TEMPO_FRAC = 0.02; // |ibiCorr| clamp, fraction of the IBI\nvar PLL_ACCEPT_FRAC = 0.25; // an onset within \u00B1this\u00B7IBI of the prediction is \"the\" beat onset\nvar PLL_FREERUN_FRAC = 0.25; // free-run (grid) emit once the prediction is passed by this\u00B7IBI\nvar PLL_RESYNC_FRAC = 0.25; // re-seed the PLL period from the ACF tempo if it drifts beyond this\nvar PLL_BOOTSTRAP_MAX_AGE_IBI = 2.0; // bootstrap anchors to the newest onset within this many IBIs\n\n// ---- DJ-drift dual-window tracking (T5) ----\n// The tracked tempo normally follows the long STABLE window (octave-safe, steady). When the\n// short FAST window consistently reports a DIFFERENT, non-octave tempo over several ACF hops,\n// the grid follows it \u2014 a genuine DJ drift, not noise. A single noisy hop can never move the\n// grid (the persistence streak below), and octave-scale disagreements are left to the stable\n// hysteresis (they are metrical ambiguity, owned by the octave guards there).\nvar DRIFT_MIN_FRAC = 0.012; // fast must differ from the grid by > this to count as drift (~1.2%)\nvar DRIFT_MAX_FRAC = 0.20; // beyond this it is a hard jump \u2192 owned by the stable hysteresis\nvar DRIFT_AGREE_FRAC = 0.04; // consecutive fast estimates within this keep the confirmation streak\nvar DRIFT_CONFIRM_HOPS = 3; // consecutive confirming ACF hops required before the grid follows\n\n// ---- Provisional vs locked beats (T7) ----\n// Beats are emitted as soon as the early ACF finds ANY in-range tempo (gated at _minEmitHops,\n// derived from minSettlingMs \u2248 400 ms instead of waiting the full slowest-tempo window), tagged\n// status:'provisional' \u2014 this drives the low-latency \"blink\" visual reactivity. A beat is only\n// PROMOTED to status:'locked' once the evidence matches what the detector used to wait for: the\n// full stable window has filled (fluxCount \u2265 maxLag+1 \u2014 one period of the slowest tempo, exactly\n// the old emission gate \u2192 the AUTHORITATIVE lock) AND at least LOCK_PROMOTE_BEATS beats have since\n// been emitted on that validated grid AND confidence clears a floor. (Persistence is counted as\n// beats-after-authoritative-lock, not onset-MATCHED beats: on syncopated material the IBI-derived\n// refractory hides the on-grid onsets so the grid legitimately free-runs \u2014 the full-window lock +\n// confidence already establish trustworthiness.) The promotion latches (one provisional\u2192locked\n// transition per stable segment) and also gates the state-message tempo report, so sync-critical\n// consumers and the public tempo/confidence getters only ever see post-lock (trustworthy) values\n// while the visual layer still reacts early. The gains are INTERNAL constants (API decision: not\n// public). When emitProvisionalBeats is false, provisional beats are suppressed (grid bookkeeping\n// still runs) and only locked beats are posted \u2014 the pre-T7 emission shape.\nvar LOCK_PROMOTE_BEATS = 3; // beats emitted after the authoritative lock before promotion to locked\nvar LOCK_PROMOTE_CONFIDENCE = 0.1; // confidence floor that must be cleared to promote to locked\n\n// Mean-subtracted, biased (\u00F7n), zero-lag-normalised ACF. Writes lagCount values into out.\nfunction computeAcfInline(flux, n, minLag, maxLag, out) {\n var lagCount = maxLag - minLag + 1;\n var mean = 0;\n for (var t = 0; t < n; t++) { mean += flux[t]; }\n mean = n > 0 ? mean / n : 0;\n var zeroLag = 0;\n for (var z = 0; z < n; z++) { var cz = flux[z] - mean; zeroLag += cz * cz; }\n zeroLag = n > 0 ? zeroLag / n : 1;\n var norm = zeroLag > 0 ? zeroLag : 1;\n for (var lagIndex = 0; lagIndex < lagCount; lagIndex++) {\n var lag = minLag + lagIndex;\n var sum = 0;\n for (var t2 = lag; t2 < n; t2++) { sum += (flux[t2] - mean) * (flux[t2 - lag] - mean); }\n out[lagIndex] = n > 0 ? sum / n / norm : 0;\n }\n}\n\n// Linear-interpolated ACF sample; 0 outside range, negative correlation clamped to 0.\nfunction acfAtLagInline(acf, acfLen, minLag, lag) {\n var maxIndex = acfLen - 1;\n var f = lag - minLag;\n if (f < 0 || f > maxIndex) { return 0; }\n var i0 = Math.floor(f);\n var i1 = i0 < maxIndex ? i0 + 1 : maxIndex;\n var frac = f - i0;\n var v = acf[i0] * (1 - frac) + acf[i1] * frac;\n return v > 0 ? v : 0;\n}\n\nfunction tempoPriorInline(bpm, mu, sigma) {\n var zp = Math.log(bpm / mu) / sigma;\n return Math.exp(-0.5 * zp * zp);\n}\n\n// Sub-lag peak refinement: fit a parabola through (i-1, i, i+1) and return the vertex\n// offset in [-0.5, 0.5]. Gives sub-hop BPM resolution where the lag grid is coarse (the\n// 300 BPM top end sits at lag ~19 hops, ~5 ms/lag). Mirrors parabolicPeakOffset.\nfunction parabolicPeakOffsetInline(yPrev, yMid, yNext) {\n var denom = yPrev - 2 * yMid + yNext;\n if (denom >= 0) { return 0; }\n var d = (0.5 * (yPrev - yNext)) / denom;\n if (d < -0.5) { d = -0.5; } else if (d > 0.5) { d = 0.5; }\n return d;\n}\n\n// ---- Processor ----\nclass BeatDetectorProcessor extends AudioWorkletProcessor {\n constructor(options) {\n super();\n var opts = (options && 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 // T7 low-latency emission: minSettlingMs replaces the old settlingMs (1500). It sets the\n // EARLIEST point a (provisional) beat may be emitted \u2014 the ACF starts hunting a tempo once\n // the flux ring holds this many hops instead of waiting a full slowest-tempo period.\n this._minSettlingMs = opts.minSettlingMs !== undefined ? opts.minSettlingMs : 400;\n this._emitProvisionalBeats = opts.emitProvisionalBeats !== false; // default true\n // T5 dual tempo windows. The short FAST window detects a genuine tempo change quickly;\n // the long STABLE window holds the grid steady against noise/octave artefacts. A single\n // flux ring is sized to the stable window and the fast window is its most-recent sub-span.\n this._fastTempoWindowSec = opts.fastTempoWindowSec || 2.5;\n this._stableTempoWindowSec = opts.stableTempoWindowSec || 8;\n this._enableTsDetection = opts.enableTimeSignatureDetection !== false;\n\n var 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\n this._melBandFilters = buildMelFilterbank(this._melBands, 80, 8000, this._fftSize, this._sampleRate);\n this._melOut = new Float32Array(this._melBands);\n var fluxWindowLen = Math.ceil(this._stableTempoWindowSec * this._sampleRate / this._hopSize);\n this._fluxWindow = new Float32Array(fluxWindowLen);\n this._linFlux = new Float32Array(fluxWindowLen); // scratch: ring \u2192 linear (oldest first)\n this._fluxWritePos = 0;\n this._fluxCount = 0;\n // Window spans in hops. The STABLE span is the whole ring; the FAST span is its most\n // recent slice. Both still hold \u2265 maxLag+1 hops so the slowest tempo stays resolvable.\n this._stableWindowHops = fluxWindowLen;\n this._fastWindowHops = Math.min(fluxWindowLen, Math.ceil(this._fastTempoWindowSec * this._sampleRate / this._hopSize));\n var LAG_K = 3;\n this._prevMelFrames = [];\n for (var i = 0; i < LAG_K; i++) {\n this._prevMelFrames.push(new Float32Array(this._melBands));\n }\n this._prevMelFrameIdx = 0;\n\n // Lag range in hops for BPM range\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 // ACF is computed down to a shorter lag than the candidate band (see tempogram.ts\n // acfExtendedMinLag): high-BPM fundamentals become interior peaks and the 2f/3f\n // super-harmonic penalty can read energy above maxBpm.\n this._acfMinLag = Math.max(1, Math.round(this._minLag / 3));\n this._acf = new Float32Array(this._maxLag - this._acfMinLag + 1); // scratch ACF buffer\n\n this._hopsSinceACF = 0;\n // ACF cadence: hops between tempogram recomputations. Configurable via acfIntervalHops\n // (default 15). Lower = faster reaction at more CPU; keep \u2265 1.\n this._acfInterval = Math.max(1, Math.round(opts.acfIntervalHops !== undefined ? opts.acfIntervalHops : 15));\n\n // Tempo state\n this._bestBpm = 0;\n this._bestScore = 0;\n this._candidates = [];\n this._firstLockSample = -1; // sample index of first lock (for hysteresis grace window)\n\n // T5 drift-tracking state. The fast window must point at a different, non-octave tempo\n // CONSISTENTLY (over several ACF hops) before the held grid follows it.\n this._driftBpm = 0; // tempo the fast window is currently pointing at (the streak target)\n this._driftHops = 0; // consecutive ACF hops the fast window has confirmed that target\n\n // Phase state\n this._lastBeatSample = -1;\n this._ibiSamples = 0; // PLL-tracked inter-beat interval (samples); seeded from ACF tempo\n this._ibiHistory = new Float32Array(4); // last 4 inter-beat intervals\n this._ibiIdx = 0;\n\n // Bar position state \u2014 parallel posteriors for 4/4 and 3/4\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; // 1-indexed\n this._barNumber = 0;\n this._beatsSinceStart = 0;\n\n // Confidence\n this._confidence = 0;\n\n // State snapshot cadence (~20 Hz)\n var STATE_INTERVAL_HOPS = Math.round(this._sampleRate / this._hopSize / 20);\n this._stateInterval = Math.max(1, STATE_INTERVAL_HOPS);\n this._hopsSinceState = 0;\n\n // T7 emission gate + provisional/locked state. _minEmitHops is the earliest hop at which\n // the ACF may run (derived from minSettlingMs); _locked latches once the full-window\n // evidence + beat persistence + confidence floor are met (see LOCK_PROMOTE_* and\n // _emitBeat). _onGridStreak counts consecutive onset-matched beats toward promotion.\n this._minEmitHops = Math.max(1, Math.round(this._minSettlingMs * 0.001 * this._sampleRate / this._hopSize));\n // _authLocked flips true the first time the flux ring holds a full slowest-tempo period\n // (fluxCount \u2265 maxLag+1) \u2014 the AUTHORITATIVE lock, identical to the pre-T7 first lock.\n // Before it, any ACF tempo is an early estimate that drives provisional beats only and is\n // re-adopted every hop (never frozen). After it, the octave-aware hysteresis owns the grid.\n this._authLocked = false;\n this._locked = false;\n this._beatsSinceAuthLock = 0; // beats emitted since the authoritative lock (promotion gate)\n\n // Lookahead\n this._lookahead = [];\n\n // RMS / onset state\n this._rms = 0;\n this._onsetStrength = 0; // per-hop normalised novelty (exposed to state + T4 PLL)\n\n // ---- Onset peak-picker state (T3) ----\n var onsetWinLen = Math.max(8, Math.round(ONSET_NORM_WINDOW_SEC * this._sampleRate / this._hopSize));\n this._onsetWin = new Float32Array(onsetWinLen); // ring of recent raw flux (normalization)\n this._onsetWinPos = 0;\n this._onsetWinCount = 0;\n this._onsetSort = new Float32Array(onsetWinLen); // scratch \u2014 sorted copy for median\n this._onsetDev = new Float32Array(onsetWinLen); // scratch \u2014 |x \u2212 median| for MAD\n this._fluxPeak = 0; // decaying running flux maximum (noise-floor reference)\n this._onsetPrev1 = 0; // normalised novelty at the previous hop (rising-edge detect)\n this._onsetHopCount = 0;\n this._onsetFiredThisHop = false; // a confirmed onset peak was registered this hop\n // ---- Onset stream exposed for T4's PLL ----\n // _lastOnsetSample / _lastOnsetStrength = most recent confirmed onset (sub-hop precise);\n // the ring holds the last ONSET_RING_SIZE onsets so the PLL can pick nearestOnset().\n this._lastOnsetSample = -1;\n this._lastOnsetStrength = 0;\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\n // Band energy (for state messages)\n var LOW_BANDS = Math.round(this._melBands * 0.25);\n var MID_BANDS = Math.round(this._melBands * 0.6);\n this._lowBandEnd = LOW_BANDS;\n this._midBandEnd = MID_BANDS;\n }\n\n process(inputs, _outputs, _parameters) {\n var input = inputs[0];\n if (!input || input.length === 0) return true;\n\n var left = input[0] || [];\n var right = input[1] || left;\n var blockLen = left.length;\n\n for (var s = 0; s < blockLen; s++) {\n // Mono downmix\n var mono = (left[s] + right[s]) * 0.5;\n\n // Accumulate RMS\n this._rms += mono * mono;\n\n // Fill ring buffer\n this._ringBuffer[this._ringWritePos] = mono;\n this._ringWritePos = (this._ringWritePos + 1) & (this._fftSize - 1);\n\n this._hopAccum++;\n this._sampleCount++;\n\n if (this._hopAccum >= this._hopSize) {\n this._hopAccum = 0;\n this._processHop();\n }\n }\n\n return true;\n }\n\n _processHop() {\n // Read ring buffer into real[] (oldest first)\n var rb = this._ringBuffer;\n var wp = this._ringWritePos;\n var n = this._fftSize;\n for (var i = 0; i < n; i++) {\n this._real[i] = rb[(wp + i) & (n - 1)];\n }\n\n // FFT\n fftInPlace(this._real, this._imag);\n\n // Magnitude spectrum\n var bins = n >> 1;\n for (var 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\n // RMS (from time domain, using ring buffer)\n var rmsAccum = 0;\n for (var 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\n // Mel bands\n computeMelBands(this._mag, this._melBandFilters, this._melOut);\n\n // Spectral flux (SuperFlux-lite, lag k=3)\n var K = this._prevMelFrames.length;\n var flux = 0;\n for (var b = 0; b < this._melBands; b++) {\n var localMax = -Infinity;\n for (var k = 0; k < K; k++) {\n var prevVal = this._prevMelFrames[k][b];\n if (prevVal > localMax) localMax = prevVal;\n }\n var diff = this._melOut[b] - localMax;\n if (diff > 0) flux += diff;\n }\n\n // Store current mel frame in circular buffer\n var prevFrame = this._prevMelFrames[this._prevMelFrameIdx];\n for (var b = 0; b < this._melBands; b++) {\n prevFrame[b] = this._melOut[b];\n }\n this._prevMelFrameIdx = (this._prevMelFrameIdx + 1) % K;\n\n // Add flux to sliding window\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\n // Adaptive onset normalization + peak-picking (T3). Runs every hop (independent\n // of the ACF/tempo path, which still consumes the raw _fluxWindow above).\n this._detectOnset(flux);\n\n // Tempogram: compute ACF periodically. T7 lowers the warm-up gate from a full slowest-\n // tempo period (_maxLag+1, ~1.2 s at minBpm) to _minEmitHops (~0.4 s) so a fast/core tempo\n // can lock \u2014 and a provisional beat can fire \u2014 far earlier. The ACF over a short span only\n // resolves tempos that already have \u22731 period of evidence in it, so slow tempos still wait\n // (physically) for their period; promotion to 'locked' still requires the full window.\n this._hopsSinceACF++;\n var dueForAcf = this._hopsSinceACF >= this._acfInterval && this._fluxCount >= this._minEmitHops;\n // Force the AUTHORITATIVE compute the instant the full window first fills (independent of\n // the earlier provisional ACF cadence), so the authoritative lock + phase re-bootstrap land\n // on exactly the evidence the pre-T7 detector used for its first lock. That makes every\n // LOCKED beat identical to the pre-T7 output (same tempo, same grid phase).\n var firstFullWindow = !this._authLocked && this._fluxCount >= this._maxLag + 1;\n if (dueForAcf || firstFullWindow) {\n this._hopsSinceACF = 0;\n this._computeACFAndCandidates();\n }\n\n // Phase tracker \u2014 runs as soon as a tempo is locked. It is no longer gated on the\n // full settling window: the PLL bootstraps its phase from a real onset, so beats are\n // not lost to warm-up (the state-message tempo report still honours settling). Lock\n // itself cannot occur before the flux window holds \u2265 maxLag+1 hops (~1.2 s at minBpm).\n if (this._bestBpm > 0) {\n this._tickPhase(flux);\n }\n\n // State snapshot\n this._hopsSinceState++;\n if (this._hopsSinceState >= this._stateInterval) {\n this._hopsSinceState = 0;\n this._sendStateMessage();\n }\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 \u2192\n // positive peaks (parabola-refined interior, raw endpoints) \u2192 comb \u2212 super-harmonic penalty\n // \u00D7 tempo prior \u2192 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 var buf = this._fluxWindow;\n var wp = this._fluxWritePos;\n var len = buf.length;\n var n = spanHops < this._fluxCount ? spanHops : this._fluxCount;\n var minLag = this._acfMinLag; // extended ACF base (see constructor)\n var maxLag = this._maxLag;\n var numLags = maxLag - minLag + 1;\n var loBpm = this._minBpm * 0.95; // CANDIDATE_EDGE_TOLERANCE = 0.05\n var hiBpm = this._maxBpm * 1.05;\n\n // Linearise the most-recent n hops of the flux ring (oldest first) into a scratch array\n // so the ACF operates on the same layout src/dsp/tempogram.computeAcf expects.\n var lin = this._linFlux;\n for (var t = 0; t < n; t++) {\n lin[t] = buf[((wp - 1 - (n - 1 - t)) % len + len) % len];\n }\n\n // ACF (mean-subtracted, biased, zero-lag normalised) \u2014 mirrors computeAcf.\n var acf = this._acf;\n computeAcfInline(lin, n, minLag, maxLag, acf);\n\n // Raw positive peaks (interior + endpoints) \u2014 mirrors findTempoPeaks.\n var peaks = [];\n var 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 (var i = 1; i < lastIdx; i++) {\n if (acf[i] > acf[i-1] && acf[i] > acf[i+1] && acf[i] > 0) {\n var lagI = minLag + i + parabolicPeakOffsetInline(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 var lagL = minLag + lastIdx;\n peaks.push({ bpm: 60 * this._sampleRate / (lagL * this._hopSize), score: acf[lastIdx], lag: lagL });\n }\n peaks.sort(function(a, b) { return b.score - a.score; });\n\n // Filter to BPM range (with edge tolerance) \u2014 mirrors computeTempoCandidates filter.\n var inRange = [];\n for (var pf = 0; pf < peaks.length; pf++) {\n if (peaks[pf].bpm >= loBpm && peaks[pf].bpm <= hiBpm) inRange.push(peaks[pf]);\n }\n\n // Comb (own sub-multiples) \u2212 super-harmonic penalty, \u00D7 tempo prior.\n // Mirrors scoreTempoHypotheses. The penalty is what defeats the octave-down bias.\n // The penalty is SUBDIVISION-AWARE: a super-harmonic kf only demotes f when kf is\n // itself a plausible beat (kf <= maxBpm). Energy above maxBpm is a subdivision (hats\n // on 8ths over a 180 kick), not a competing fundamental, so it must not demote f.\n var superHi = hiBpm; // maxBpm * 1.05 (CANDIDATE_EDGE_TOLERANCE)\n var scored = [];\n for (var q = 0; q < inRange.length; q++) {\n var lag = inRange[q].lag;\n var aF = acfAtLagInline(acf, numLags, minLag, lag);\n var aHalf = acfAtLagInline(acf, numLags, minLag, lag * 2);\n var aThird = acfAtLagInline(acf, numLags, minLag, lag * 3);\n var aDouble = acfAtLagInline(acf, numLags, minLag, lag / 2);\n var aTriple = acfAtLagInline(acf, numLags, minLag, lag / 3);\n var support = COMB_W_FUNDAMENTAL * aF + COMB_W_HALF * aHalf + COMB_W_THIRD * aThird;\n var penDbl = inRange[q].bpm * 2 <= superHi ? COMB_PENALTY_DOUBLE * aDouble : 0;\n var penTrip = inRange[q].bpm * 3 <= superHi ? COMB_PENALTY_TRIPLE * aTriple : 0;\n var comb = support - penDbl - penTrip;\n if (comb < 0) comb = 0;\n var w = tempoPriorInline(inRange[q].bpm, TEMPO_PRIOR_MU, TEMPO_PRIOR_SIGMA);\n scored.push({ bpm: inRange[q].bpm, score: comb * w, lag: lag });\n }\n scored.sort(function(a, b) { return b.score - a.score; });\n\n return scored.slice(0, 3);\n }\n\n _computeACFAndCandidates() {\n // T5 dual ACF windows over the SAME flux ring. The long STABLE span holds the grid (and\n // is the parity-checked candidate set the state message reports); the short FAST span\n // detects a genuine tempo change quickly. Both feed the octave-aware hysteresis below.\n var stable = this._scoreSpan(this._stableWindowHops);\n var fast = this._scoreSpan(this._fastWindowHops);\n\n this._candidates = stable;\n if (this._candidates.length === 0) return;\n\n var top = this._candidates[0];\n\n // Octave-aware hysteresis with a short first-lock grace window.\n if (!this._authLocked) {\n // Pre-authoritative (provisional) phase: the flux ring does not yet hold a full\n // slowest-tempo period, so this tempo is an EARLY, possibly under-resolved estimate\n // used only to drive provisional beats. Re-adopt the current best estimate every hop \u2014\n // never freeze it (an under-resolved edge lock must not stick). The AUTHORITATIVE lock\n // fires the instant the full window is available; that value is identical to the pre-T7\n // first lock, so the locked grid + hysteresis (and every locked beat) are unchanged.\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 // Re-anchor the beat phase + period to the full-window evidence, SILENTLY (no\n // re-emit \u2192 no duplicate beat next to the last provisional one). A provisional beat\n // may have anchored the grid on an early under-resolved tempo or, on syncopated\n // material, an off-beat onset; snap _lastBeatSample to the same strongest recent\n // onset the pre-T7 detector locked to here so locked beats sit on the trustworthy\n // grid. If no provisional beat has run yet (_lastBeatSample < 0), leave it so\n // _tickPhase bootstraps the first beat normally.\n if (this._lastBeatSample >= 0) {\n var reIbi = 60 / this._bestBpm * this._sampleRate;\n var 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 // --- Stable-window hysteresis: holds the grid against noise + octave artefacts. ---\n // Fresh score of the currently-tracked tempo from this frame.\n var currentScore = 0;\n for (var c = 0; c < this._candidates.length; c++) {\n if (Math.abs(this._candidates[c].bpm / this._bestBpm - 1) < 0.03) {\n if (this._candidates[c].score > currentScore) currentScore = this._candidates[c].score;\n }\n }\n if (currentScore <= 0) currentScore = this._bestScore * 0.9;\n\n var inGrace = this._firstLockSample >= 0 &&\n (this._sampleCount - this._firstLockSample) < 2 * this._sampleRate;\n var ratio = top.bpm / this._bestBpm;\n // Metrically-related = same beat at another level (octaves + 3:2/2:3 dotted/triple).\n // Switching across these needs the strong margin so subdivision artefacts (e.g. the\n // 120 \"dotted\" grouping of a drifting 180 kit) cannot steal the lock. Independent\n // reimplementation of isOctaveRelated (src/dsp/tempogram.ts) \u2014 constants must stay in sync.\n var isOctave = Math.abs(ratio - 0.5) < 0.05 || Math.abs(ratio - 2) < 0.1 ||\n Math.abs(ratio - 3) < 0.15 || Math.abs(ratio - 1/3) < 0.05 ||\n Math.abs(ratio - 2/3) < 0.04 || Math.abs(ratio - 3/2) < 0.06;\n var margin = inGrace ? 1.0 : (isOctave ? 1.5 : 1.15);\n var diff = Math.abs(top.bpm - this._bestBpm) / this._bestBpm;\n\n if (diff > 0.03 && top.score > currentScore * margin) {\n var oldBpm = this._bestBpm;\n this._bestBpm = top.bpm;\n this._bestScore = top.score;\n // Only fire tempoChange if > 5% different\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\n // --- Fast-window drift adaptation: follows a genuine, sustained DJ drift. ---\n this._trackDrift(fast);\n }\n\n this._updateConfidence();\n }\n\n // T5 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 \u2014 so a static tempo is never made nervous.\n _trackDrift(fast) {\n if (fast.length === 0) { this._driftHops = 0; this._driftBpm = 0; return; }\n var fastTop = fast[0];\n var r = fastTop.bpm / this._bestBpm;\n var diff = r > 1 ? r - 1 : 1 - r;\n\n var octave = Math.abs(r - 0.5) < 0.05 || Math.abs(r - 2) < 0.1 ||\n Math.abs(r - 3) < 0.15 || Math.abs(r - 1/3) < 0.05 ||\n Math.abs(r - 2/3) < 0.04 || Math.abs(r - 3/2) < 0.06;\n\n // Fast agrees with the grid, or disagrees at octave / hard-jump scale \u2192 not a drift.\n if (octave || diff <= DRIFT_MIN_FRAC || diff > DRIFT_MAX_FRAC) {\n this._driftHops = 0;\n this._driftBpm = 0;\n return;\n }\n\n // Diverging within the drift band \u2014 accumulate a confirmation streak on a stable target.\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\n if (this._driftHops >= DRIFT_CONFIRM_HOPS) {\n var oldBpm = this._bestBpm;\n this._bestBpm = fastTop.bpm;\n this._bestScore = fastTop.score;\n this._driftHops = 0; // restart the streak; the next step must re-confirm\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\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 var minR = ONSET_MIN_REFRACTORY_SEC * this._sampleRate;\n if (this._bestBpm > 0) {\n var r = ONSET_REFRACTORY_IBI_FRAC * (60 / this._bestBpm * this._sampleRate);\n return r > minR ? r : minR;\n }\n return minR;\n }\n\n // Adaptive onset detection (T3). 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 T4's PLL.\n _detectOnset(flux) {\n // Decaying running flux maximum \u2014 the reference level for the noise floor.\n this._fluxPeak *= ONSET_PEAK_DECAY;\n if (flux > this._fluxPeak) this._fluxPeak = flux;\n\n // Push raw flux into the normalization ring.\n var 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 var count = this._onsetWinCount;\n\n // Robust baseline: median of the window, then MAD = median(|x \u2212 median|).\n var s = this._onsetSort;\n for (var i = 0; i < count; i++) s[i] = this._onsetWin[i];\n partialSort(s, count);\n var median = s[count >> 1];\n var d = this._onsetDev;\n for (var j = 0; j < count; j++) { var dv = this._onsetWin[j] - median; d[j] = dv < 0 ? -dv : dv; }\n partialSort(d, count);\n var mad = d[count >> 1];\n\n // Normalised novelty: deviation above baseline in robust-\u03C3 units, with the scale\n // floored at a fraction of the running peak so a clean (MAD\u22480) clicktrack still\n // yields a finite, comparable onset strength instead of a divide-by-zero spike.\n var floorScale = ONSET_NOISE_FLOOR_FRAC * this._fluxPeak;\n var madScaled = ONSET_MAD_SCALE * mad;\n var denom = madScaled > floorScale ? madScaled : floorScale;\n if (denom < 1e-9) denom = 1e-9;\n var norm = (flux - median) / denom;\n if (norm < 0) norm = 0;\n this._onsetStrength = norm;\n\n // Rising-edge onset detection on the normalised novelty: fire on the UPWARD crossing\n // of the adaptive threshold \u2014 the onset attack, exactly where the old crude heuristic\n // fired, so the shipped beat-offset behaviour is preserved \u2014 gated by the noise floor\n // and an IBI-derived refractory. Zero lookahead latency.\n this._onsetFiredThisHop = false;\n var noiseFloor = floorScale;\n var refractory = this._onsetRefractorySamples();\n var crossedUp = this._onsetHopCount >= 1 && this._onsetPrev1 <= ONSET_THRESHOLD && norm > ONSET_THRESHOLD;\n var aboveFloor = flux > noiseFloor && flux > ONSET_ABS_FLOOR;\n var pastRefractory = this._lastOnsetSample < 0 || (this._sampleCount - this._lastOnsetSample) >= refractory;\n if (crossedUp && aboveFloor && pastRefractory) {\n // Sub-hop onset position: linear-interpolate the threshold crossing between the\n // previous hop and this one (stored for T4's PLL; the T3 grid snap uses the integer\n // hop so the shipped beat-offset numbers are preserved).\n var span = norm - this._onsetPrev1;\n var frac = span > 1e-9 ? (ONSET_THRESHOLD - this._onsetPrev1) / span : 0;\n if (frac < 0) frac = 0; else if (frac > 1) frac = 1;\n var onsetSample = (this._sampleCount - this._hopSize) + frac * this._hopSize;\n this._lastOnsetSample = onsetSample;\n this._lastOnsetStrength = norm;\n this._onsetFiredThisHop = true;\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\n // Shift history for the next hop.\n this._onsetPrev1 = norm;\n this._onsetHopCount++;\n }\n\n // Onset CLOSEST to targetSample within \u00B1windowSamples (sub-hop precise, from the T3 ring) \u2014\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 var best = -1;\n var bestDist = windowSamples + 1;\n var cnt = this._onsetRingCount;\n for (var i = 0; i < cnt; i++) {\n var s = this._onsetRingSamples[i];\n if (s < 0) continue;\n var d = s - targetSample;\n if (d < 0) d = -d;\n if (d <= windowSamples && d < bestDist) { bestDist = d; best = s; }\n }\n return best;\n }\n\n // Strongest onset no older than maxAgeSamples (ties \u2192 most recent) \u2014 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 \u2014 never the old\n // arbitrary settling boundary. Returns the anchor sample, or -1 if the ring is empty.\n _bootstrapOnset(maxAgeSamples) {\n var best = -1;\n var bestStrength = -1;\n var cnt = this._onsetRingCount;\n for (var i = 0; i < cnt; i++) {\n var s = this._onsetRingSamples[i];\n if (s < 0 || (this._sampleCount - s) > maxAgeSamples) continue;\n var st = this._onsetRingStrengths[i];\n if (st > bestStrength || (st === bestStrength && s > best)) { bestStrength = st; best = s; }\n }\n return best;\n }\n\n // Emit exactly one beat at beatSample (samples). Centralises the bar/confidence/lookahead\n // bookkeeping + the provisional\u2192locked 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 var beatTime = beatSample / this._sampleRate;\n\n // Update IBI history with the current PLL period.\n this._ibiHistory[this._ibiIdx] = this._ibiSamples;\n this._ibiIdx = (this._ibiIdx + 1) & 3;\n\n this._beatsSinceStart++;\n this._updateBarPosition(flux);\n this._updateConfidence();\n this._updateLookahead(beatTime);\n\n // Provisional\u2192locked promotion (latched, one transition per stable segment). Locked needs\n // the SAME evidence the old detector waited for before emitting at all \u2014 the full stable\n // window (the AUTHORITATIVE lock) \u2014 PLUS LOCK_PROMOTE_BEATS beats sustained on that grid\n // and a confidence floor, so a 'locked' beat is at least as trustworthy as a pre-T7 beat.\n if (this._authLocked) { this._beatsSinceAuthLock++; }\n if (!this._locked &&\n this._authLocked &&\n this._beatsSinceAuthLock >= LOCK_PROMOTE_BEATS &&\n this._confidence >= LOCK_PROMOTE_CONFIDENCE) {\n this._locked = true;\n }\n var status = this._locked ? 'locked' : 'provisional';\n\n // Provisional gating: when emitProvisionalBeats is false, suppress the message until the\n // beat is locked (grid bookkeeping above already ran). Locked beats always post.\n if (!this._emitProvisionalBeats && !this._locked) return;\n\n var 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: isDownbeat,\n beatInBar: this._barPosition,\n status: status,\n });\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\n // Bounded PLL beat-phase tracker (T4). 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 var acfIbi = 60 / this._bestBpm * this._sampleRate;\n\n // Bootstrap: anchor the first beat to a real recent onset (never an arbitrary\n // boundary). Emit it \u2014 it is a genuine, just-detected transient \u2014 so the leading\n // on-grid beat is not lost to warm-up. If no onset has arrived yet, wait.\n if (this._lastBeatSample < 0) {\n var 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\n // Keep the PLL period anchored to the ACF tempo: it may track drift within the bounded\n // tempoGain, but a large gap (octave re-lock / tempoChange) re-seeds it so the loop\n // never chases a stale interval. Tempo SELECTION is unchanged \u2014 this only refines the\n // local period the phase tracker runs on.\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 var ibi = this._ibiSamples;\n\n var predicted = this._lastBeatSample + ibi;\n var acceptWin = PLL_ACCEPT_FRAC * ibi;\n\n // Still early in the beat cycle \u2014 wait until we approach the prediction.\n if (this._sampleCount < predicted - acceptWin) return;\n\n var onset = this._nearestOnset(predicted, acceptWin);\n\n var beatSample;\n if (onset >= 0) {\n // Bounded phase + period correction toward the matched onset.\n var error = onset - predicted;\n var maxPhase = PLL_MAX_PHASE_FRAC * ibi;\n var phaseCorr = error * PLL_PHASE_GAIN;\n if (phaseCorr > maxPhase) phaseCorr = maxPhase; else if (phaseCorr < -maxPhase) phaseCorr = -maxPhase;\n var maxTempo = PLL_MAX_TEMPO_FRAC * ibi;\n var ibiCorr = error * PLL_TEMPO_GAIN;\n if (ibiCorr > maxTempo) ibiCorr = maxTempo; 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 // Prediction passed with no matching onset \u2192 free-run on the grid (period held).\n beatSample = predicted;\n } else {\n // Inside the accept window with no onset yet \u2014 give a late onset a chance next hop.\n return;\n }\n\n // Advance the grid by exactly one beat.\n this._lastBeatSample = beatSample;\n\n // Coast gate (T3): after a sustained onset gap (break / silence) keep the grid\n // advancing but STOP emitting \u2014 this is what holds the breakDrop false-positive rate\n // down. Onset-rich material never trips it.\n var coasting = this._lastOnsetSample >= 0 &&\n (this._sampleCount - this._lastOnsetSample) > ONSET_BEAT_COAST_IBI * ibi;\n if (coasting) return;\n\n this._emitBeat(beatSample, flux);\n }\n\n _computeBeatLikelihood(flux) {\n var count = Math.min(this._fluxCount, 32);\n var wp = this._fluxWritePos;\n var len = this._fluxWindow.length;\n var totalFlux = 0;\n for (var i = 0; i < count; i++) {\n totalFlux += this._fluxWindow[(wp - 1 - i + len) % len];\n }\n var mean = count > 0 ? totalFlux / count : 1;\n return Math.max(0.5, Math.min(1.5, mean > 0 ? flux / mean : 1));\n }\n\n _updateBarPosition(flux) {\n var likelihood = this._computeBeatLikelihood(flux);\n\n // --- 4/4 posterior ---\n var p4 = this._posterior4;\n var s4 = new Float32Array(4);\n s4[0] = p4[3]; s4[1] = p4[0]; s4[2] = p4[1]; s4[3] = p4[2];\n var sum4 = 0;\n for (var 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) { for (var i = 0; i < 4; i++) p4[i] /= sum4; }\n\n // --- 3/4 posterior ---\n var p3 = this._posterior3;\n var s3 = new Float32Array(3);\n s3[0] = p3[2]; s3[1] = p3[0]; s3[2] = p3[1];\n var sum3 = 0;\n for (var 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) { for (var i = 0; i < 3; i++) p3[i] /= sum3; }\n\n // --- Update TS confidences (EMA) ---\n var max4 = 0;\n for (var i = 0; i < 4; i++) { if (p4[i] > max4) max4 = p4[i]; }\n var max3 = 0;\n for (var i = 0; i < 3; i++) { if (p3[i] > max3) max3 = p3[i]; }\n var alpha = 0.1;\n this._ts4Confidence = (1 - alpha) * this._ts4Confidence + alpha * max4;\n this._ts3Confidence = (1 - alpha) * this._ts3Confidence + alpha * max3;\n\n // --- Hysteresis switching ---\n if (this._enableTsDetection && this._beatsSinceStart > 8) {\n var minSwitchMargin = 1.4;\n var minSustainBeats = 12; // ~4 bars * 3 beats\n var threeFavored = this._ts3Confidence > this._ts4Confidence * minSwitchMargin;\n var fourFavored = this._ts4Confidence > this._ts3Confidence * minSwitchMargin;\n\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) { // 16 beats for 4/4\n this._activeTs = '4/4';\n this._sustainCounter = 0;\n }\n } else {\n this._sustainCounter = 0;\n }\n }\n\n // --- Determine bar position from active TS ---\n var barLen = this._activeTs === '3/4' ? 3 : 4;\n var posterior = this._activeTs === '3/4' ? p3 : p4;\n\n if (this._beatsSinceStart >= barLen) {\n var maxP = -1, maxI = 0;\n for (var i = 0; i < barLen; i++) {\n if (posterior[i] > maxP) { maxP = posterior[i]; maxI = i; }\n }\n var newPos = maxI + 1; // 1-indexed\n if (newPos === 1 && this._barPosition !== 1) {\n this._barNumber++;\n }\n this._barPosition = newPos;\n } else {\n // Just advance sequentially\n this._barPosition = ((this._barPosition) % barLen) + 1;\n if (this._barPosition === 1) this._barNumber++;\n }\n }\n\n _updateConfidence() {\n if (this._candidates.length === 0) {\n this._confidence = 0;\n return;\n }\n\n // Peak contrast\n var top1 = this._candidates[0] ? this._candidates[0].score : 0;\n var top2 = this._candidates[1] ? this._candidates[1].score : top1;\n var top3 = this._candidates[2] ? this._candidates[2].score : top2;\n var peakContrast = (top2 + top3) > 0 ? top1 / ((top2 + top3) / 2) : 1;\n\n // Phase consistency from IBI variance\n var ibiMean = 0;\n for (var i = 0; i < 4; i++) ibiMean += this._ibiHistory[i];\n ibiMean /= 4;\n var ibiVar = 0;\n for (var i = 0; i < 4; i++) {\n var d = this._ibiHistory[i] - ibiMean;\n ibiVar += d * d;\n }\n ibiVar /= 4;\n var phaseConsistency = ibiMean > 0 ? Math.max(0, 1 - ibiVar / (ibiMean * ibiMean)) : 0;\n\n // Bar consistency (use the active posterior)\n var activePosterior = this._activeTs === '3/4' ? this._posterior3 : this._posterior4;\n var activeLen = this._activeTs === '3/4' ? 3 : 4;\n var maxP = 0;\n for (var i = 0; i < activeLen; i++) {\n if (activePosterior[i] > maxP) maxP = activePosterior[i];\n }\n var barConsistency = maxP;\n\n var c = Math.sqrt(Math.max(0, peakContrast / 2)) *\n Math.sqrt(Math.max(0, phaseConsistency)) *\n (0.5 + 0.5 * barConsistency);\n this._confidence = Math.max(0, Math.min(1, c));\n }\n\n _updateLookahead(lastBeatTime) {\n var lookahead = [];\n var beatInterval = 60 / this._bestBpm;\n var barPos = this._barPosition;\n var barLen = this._activeTs === '3/4' ? 3 : 4;\n for (var i = 0; i < 8; i++) {\n var t = lastBeatTime + (i + 1) * beatInterval;\n var 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\n _computeBandEnergy() {\n var low = 0, mid = 0, high = 0;\n for (var b = 0; b < this._lowBandEnd; b++) low += this._melOut[b];\n for (var b = this._lowBandEnd; b < this._midBandEnd; b++) mid += this._melOut[b];\n for (var b = this._midBandEnd; b < this._melBands; b++) high += this._melOut[b];\n var 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\n _sendStateMessage() {\n // T7: the state tempo report honours the LOCKED latch (not the old fixed settling window).\n // Provisional early beats drive the visual layer, but tempo/confidence/tempoCandidates\n // and the sync-critical fields stay zero until the detector has a trustworthy locked grid.\n var settled = this._locked;\n var beatInterval = this._bestBpm > 0 ? 60 / this._bestBpm : 0;\n var currentTime = this._sampleCount / this._sampleRate;\n var lastBeatTime = this._lastBeatSample >= 0 ? this._lastBeatSample / this._sampleRate : 0;\n var beatPhase = beatInterval > 0\n ? Math.min(1, (currentTime - lastBeatTime) / beatInterval)\n : 0;\n var nextBeatTime = lastBeatTime + beatInterval;\n\n var nextDownbeatTime = nextBeatTime;\n for (var i = 0; i < this._lookahead.length; i++) {\n if (this._lookahead[i].isDownbeat) {\n nextDownbeatTime = this._lookahead[i].audioTime;\n break;\n }\n }\n\n var be = this._computeBandEnergy();\n\n this.port.postMessage({\n type: 'state',\n tempo: settled ? this._bestBpm : 0,\n beatPhase: beatPhase,\n confidence: settled ? this._confidence : 0,\n gridStability: settled ? this._confidence : 0,\n tempoCandidates: settled ? this._candidates.map(function(c) {\n return { bpm: c.bpm, score: c.score };\n }) : [],\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'\n ? { numerator: 3, denominator: 4 }\n : { numerator: 4, denominator: 4 },\n lookahead: this._lookahead,\n nextBeatTime: settled ? nextBeatTime : 0,\n nextDownbeatTime: settled ? nextDownbeatTime : 0,\n });\n }\n}\n\nregisterProcessor('exojs-beat-detector', BeatDetectorProcessor);\n";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const bitCrusherWorkletSource = "\nclass BitCrusherProcessor extends AudioWorkletProcessor {\n static get parameterDescriptors() {\n return [\n { name: 'bits', defaultValue: 8, minValue: 1, maxValue: 16, automationRate: 'k-rate' },\n { name: 'normFreq', defaultValue: 0.5, minValue: 0, maxValue: 1, automationRate: 'k-rate' },\n ];\n }\n\n constructor() {\n super();\n // Phase accumulator for sample-and-hold; held keeps the last latched value.\n this._phase = 0;\n this._held = 0;\n }\n\n process(inputs, outputs, parameters) {\n const input = inputs[0]?.[0];\n const output = outputs[0]?.[0];\n if (!input || !output) return true;\n\n const bits = Math.round(Math.max(1, Math.min(16, parameters.bits[0])));\n const normFreq = Math.max(0, Math.min(1, parameters.normFreq[0]));\n // Quantization step: 2 / 2^bits (maps [-1, 1] onto 2^bits levels)\n const step = 2 / Math.pow(2, bits);\n\n for (let i = 0; i < input.length; i++) {\n // Advance the sample-and-hold phase accumulator.\n this._phase += normFreq;\n if (this._phase >= 1) {\n // Wrap phase and latch a fresh, quantized sample.\n this._phase -= 1;\n this._held = step * Math.round(input[i] / step);\n }\n // Emit the held (quantized) sample \u2014 pure wet, no dry mixing here.\n output[i] = this._held;\n }\n return true;\n }\n}\nregisterProcessor('exojs-bit-crusher', BitCrusherProcessor);\n";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const granularWorkletSource = "\nconst sampleRate = globalThis.sampleRate;\n\nclass GranularProcessor extends AudioWorkletProcessor {\n static get parameterDescriptors() {\n return [\n { name: 'grainSize', defaultValue: 0.05, minValue: 0.005, maxValue: 0.5, automationRate: 'k-rate' },\n { name: 'density', defaultValue: 50, minValue: 1, maxValue: 500, automationRate: 'k-rate' },\n { name: 'spread', defaultValue: 0.5, minValue: 0, maxValue: 1.0, automationRate: 'k-rate' },\n { name: 'pitchMin', defaultValue: 1.0, minValue: 0.25, maxValue: 4.0, automationRate: 'k-rate' },\n { name: 'pitchMax', defaultValue: 1.0, minValue: 0.25, maxValue: 4.0, automationRate: 'k-rate' },\n ];\n }\n\n constructor(options) {\n super();\n const opts = options.processorOptions ?? {};\n const bufferSeconds = opts.bufferSeconds ?? 2;\n this._bufferLength = Math.floor(bufferSeconds * sampleRate);\n this._buffer = new Float32Array(this._bufferLength);\n this._writePos = 0;\n this._timeUntilNextGrainSamples = 0;\n this._grains = []; // { startPos, ageSamples, lengthSamples, pitch }\n this._normalizeGain = opts.normalizeGain ?? false;\n }\n\n process(inputs, outputs, parameters) {\n const input = inputs[0]?.[0];\n const output = outputs[0]?.[0];\n if (!input || !output) return true;\n\n const grainSize = parameters.grainSize[0];\n const density = parameters.density[0];\n const spread = parameters.spread[0];\n const pitchMin = parameters.pitchMin[0];\n const pitchMax = parameters.pitchMax[0];\n const grainSizeSamples = Math.max(8, Math.floor(grainSize * sampleRate));\n const samplesPerGrain = sampleRate / Math.max(1, density);\n\n // Optional level normalization. Output RMS scales as sqrt(3/8) (the Hann\n // window RMS) times sqrt(density * grainSize) \u2014 overlapping uncorrelated\n // grains add in power. Dividing by that factor holds the wet level near\n // unity regardless of density/grainSize. Default off keeps the expressive\n // density dynamics that make granular sound the way it does.\n let normFactor = 1;\n if (this._normalizeGain) {\n const expectedGrains = density * grainSize; // simultaneous grains (dimensionless)\n normFactor = 1 / (0.6123724356957945 * Math.sqrt(Math.max(1e-6, expectedGrains)));\n }\n\n for (let i = 0; i < input.length; i++) {\n // Write input to circular buffer\n this._buffer[this._writePos] = input[i];\n this._writePos = (this._writePos + 1) % this._bufferLength;\n\n // Spawn new grain if scheduled\n this._timeUntilNextGrainSamples -= 1;\n if (this._timeUntilNextGrainSamples <= 0) {\n // Random offset into recent past, biased by spread\n const maxOffset = Math.floor(spread * this._bufferLength);\n const offset = Math.floor(Math.random() * Math.max(1, maxOffset));\n const startPos = (this._writePos - offset - grainSizeSamples + this._bufferLength) % this._bufferLength;\n // Random pitch in [pitchMin, pitchMax]\n const pitch = pitchMin + Math.random() * Math.max(0, pitchMax - pitchMin);\n\n this._grains.push({ startPos, ageSamples: 0, lengthSamples: grainSizeSamples, pitch });\n this._timeUntilNextGrainSamples = samplesPerGrain;\n }\n\n // Mix all active grains (apply Hann window)\n let grainSum = 0;\n for (let g = this._grains.length - 1; g >= 0; g--) {\n const grain = this._grains[g];\n if (grain.ageSamples >= grain.lengthSamples) {\n this._grains.splice(g, 1);\n continue;\n }\n\n const phase = grain.ageSamples / grain.lengthSamples;\n const window = 0.5 * (1 - Math.cos(2 * Math.PI * phase));\n const readPos = grain.startPos + grain.ageSamples * grain.pitch;\n const sampleIndex = Math.floor(readPos) % this._bufferLength;\n const safeIndex = (sampleIndex + this._bufferLength) % this._bufferLength;\n grainSum += this._buffer[safeIndex] * window;\n\n grain.ageSamples++;\n }\n\n output[i] = grainSum * normFactor;\n }\n return true;\n }\n}\nregisterProcessor('exojs-granular', GranularProcessor);\n";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const pitchShiftWorkletSource = "\nclass PitchShiftProcessor extends AudioWorkletProcessor {\n static get parameterDescriptors() {\n return [\n { name: 'pitch', defaultValue: 1.0, minValue: 0.25, maxValue: 4.0, automationRate: 'k-rate' },\n ];\n }\n\n // Pitch shift = SOLA time-stretch by `pitch` followed by resampling by\n // `pitch`. SOLA (synchronized overlap-add) realigns each synthesis grain by\n // cross-correlation so grain restarts stay phase coherent \u2014 this is what\n // keeps the carrier exactly at f_in * pitch. A naive granular delay drifts\n // the pitch because its grain-boundary phase jumps accumulate into a\n // frequency offset.\n constructor(options) {\n super();\n const grainSize = options.processorOptions?.grainSize ?? 1024;\n this._frameLen = grainSize; // analysis/synthesis frame\n this._hop = grainSize >> 1; // synthesis hop (50% overlap)\n this._overlap = grainSize - this._hop;\n this._seek = grainSize >> 2; // correlation search radius (\u00B1)\n this._win = this._buildHannWindow(grainSize);\n\n // Input ring buffer: holds enough past input for the correlation search.\n this._inLen = grainSize * 4 + 2 * this._seek;\n this._inBuf = new Float32Array(this._inLen);\n this._inCount = 0; // total input samples written\n\n // Stretched-stream overlap-add accumulator (also a ring).\n this._outLen = grainSize * 4;\n this._outBuf = new Float32Array(this._outLen);\n this._synthPos = 0; // total stretched samples synthesized\n this._readPos = 0; // fractional resample read position\n this._aPos = 0; // analysis position (absolute input coords)\n this._first = true;\n }\n\n _buildHannWindow(n) {\n // Periodic Hann: w(p) + w(p + n/2) === 1, i.e. constant-overlap-add at\n // 50% overlap, so two adjacent grains reconstruct unity amplitude.\n const w = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n w[i] = 0.5 * (1 - Math.cos(2 * Math.PI * i / n));\n }\n return w;\n }\n\n // Find the input offset (within \u00B1seek of `nominal`) whose grain head best\n // matches the existing output overlap region \u2014 the waveform-similarity step\n // that keeps successive grains in phase.\n _correlate(nominal) {\n const ov = this._overlap;\n const ib = this._inBuf, iL = this._inLen;\n const ob = this._outBuf, oL = this._outLen;\n const sp = this._synthPos, seek = this._seek;\n let bestD = 0, bestC = -Infinity;\n for (let d = -seek; d <= seek; d++) {\n const base = nominal + d;\n if (base < 0 || base + ov > this._inCount) continue;\n let c = 0;\n for (let k = 0; k < ov; k++) c += ob[(sp + k) % oL] * ib[(base + k) % iL];\n if (c > bestC) { bestC = c; bestD = d; }\n }\n return bestD;\n }\n\n // True once the input buffer covers the next analysis frame plus its search.\n _canGenerate() {\n const nominal = Math.round(this._aPos);\n const oldest = this._inCount - this._inLen;\n return nominal >= 0\n && nominal + this._frameLen + this._seek <= this._inCount\n && nominal - this._seek >= oldest;\n }\n\n // Emit one phase-aligned grain into the stretched-stream accumulator.\n _generate(pitch) {\n const F = this._frameLen, H = this._hop, win = this._win;\n const ib = this._inBuf, iL = this._inLen;\n const ob = this._outBuf, oL = this._outLen;\n const nominal = Math.round(this._aPos);\n const d = this._first ? 0 : this._correlate(nominal);\n this._first = false;\n const base = nominal + d;\n // Zero the newly exposed tail, then overlap-add the windowed grain.\n for (let j = H; j < F; j++) ob[(this._synthPos + j) % oL] = 0;\n for (let j = 0; j < F; j++) ob[(this._synthPos + j) % oL] += ib[(base + j) % iL] * win[j];\n this._synthPos += H;\n this._aPos += H / pitch; // analysis hop = synthesis hop / stretch\n }\n\n process(inputs, outputs, parameters) {\n const input = inputs[0]?.[0];\n const output = outputs[0]?.[0];\n if (!input || !output) return true;\n\n const pitch = parameters.pitch[0];\n const ob = this._outBuf, oL = this._outLen;\n\n for (let i = 0; i < input.length; i++) {\n this._inBuf[this._inCount % this._inLen] = input[i];\n this._inCount++;\n\n // Pull-generate stretched samples until the read pointer has a margin.\n let guard = 0;\n while (this._synthPos < this._readPos + 2 && this._canGenerate() && guard++ < 64) {\n this._generate(pitch);\n }\n\n let shifted = 0;\n if (this._readPos + 1 < this._synthPos) {\n const p = this._readPos;\n const i0 = Math.floor(p), frac = p - i0;\n const a = ob[((i0 % oL) + oL) % oL];\n const b = ob[(((i0 + 1) % oL) + oL) % oL];\n shifted = a + (b - a) * frac;\n this._readPos += pitch;\n }\n\n output[i] = shifted;\n }\n return true;\n }\n}\nregisterProcessor('exojs-pitch-shift', PitchShiftProcessor);\n";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const vocoderWorkletSource = "\nconst sampleRate = globalThis.sampleRate;\n\nclass VocoderProcessor extends AudioWorkletProcessor {\n static get parameterDescriptors() {\n return [\n { name: 'envelopeSmoothing', defaultValue: 0.005, minValue: 0.0001, maxValue: 0.1, automationRate: 'k-rate' },\n ];\n }\n\n constructor(options) {\n super();\n const opts = options.processorOptions ?? {};\n const bandCount = opts.numBands ?? 16;\n const minHz = opts.minHz ?? 80;\n const maxHz = opts.maxHz ?? 8000;\n const Q = opts.bandQ ?? 4;\n\n // Log-spaced band centers + biquad coefficients\n this._bands = [];\n for (let i = 0; i < bandCount; i++) {\n const ratio = bandCount === 1 ? 0 : i / (bandCount - 1);\n const centerHz = minHz * Math.pow(maxHz / minHz, ratio);\n const omega = 2 * Math.PI * centerHz / sampleRate;\n const cos = Math.cos(omega);\n const sin = Math.sin(omega);\n const alpha = sin / (2 * Q);\n\n // Bandpass (constant 0 dB peak) biquad\n const a0 = 1 + alpha;\n const b0 = alpha / a0;\n const b1 = 0;\n const b2 = -alpha / a0;\n const a1 = (-2 * cos) / a0;\n const a2 = (1 - alpha) / a0;\n this._bands.push({ b0, b1, b2, a1, a2 });\n }\n\n // Per-band biquad state (one for carrier, one for modulator)\n this._carrierStates = this._bands.map(() => ({ x1: 0, x2: 0, y1: 0, y2: 0 }));\n this._modulatorStates = this._bands.map(() => ({ x1: 0, x2: 0, y1: 0, y2: 0 }));\n\n // Per-band envelope follower\n this._envelopes = new Float32Array(bandCount);\n }\n\n _processBiquad(state, coef, x) {\n const y = coef.b0 * x + coef.b1 * state.x1 + coef.b2 * state.x2 - coef.a1 * state.y1 - coef.a2 * state.y2;\n state.x2 = state.x1; state.x1 = x;\n state.y2 = state.y1; state.y1 = y;\n return y;\n }\n\n process(inputs, outputs, parameters) {\n const carrier = inputs[0]?.[0];\n const modulator = inputs[1]?.[0];\n const output = outputs[0]?.[0];\n if (!carrier || !output) return true;\n\n const envSmoothing = parameters.envelopeSmoothing[0];\n const bandCount = this._bands.length;\n\n for (let i = 0; i < carrier.length; i++) {\n const carrierSample = carrier[i];\n const modulatorSample = modulator?.[i] ?? 0;\n\n let bandSum = 0;\n for (let b = 0; b < bandCount; b++) {\n const coef = this._bands[b];\n\n // Modulator band \u2192 envelope follower\n const modBand = this._processBiquad(this._modulatorStates[b], coef, modulatorSample);\n const target = Math.abs(modBand);\n this._envelopes[b] += (target - this._envelopes[b]) * envSmoothing;\n\n // Carrier band, scaled by modulator envelope\n const carBand = this._processBiquad(this._carrierStates[b], coef, carrierSample);\n bandSum += carBand * this._envelopes[b];\n }\n\n // Multiply bandSum by bandCount: for a broadband carrier the energy is\n // split across N bands, so the raw product (carBand \u00D7 envelope) is\n // O(1/N) of the carrier amplitude. Scaling by N restores unity gain\n // for typical broadband carrier + voice modulator inputs.\n output[i] = bandSum * bandCount;\n }\n return true;\n }\n}\nregisterProcessor('exojs-vocoder', VocoderProcessor);\n";
|