@codexo/exojs-audio-fx 0.16.2 → 0.18.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/README.md CHANGED
@@ -2,16 +2,10 @@
2
2
 
3
3
  Audio effects, DSP, beat detection, and analysis for [ExoJS](https://github.com/Exoridus/ExoJS).
4
4
 
5
- A peer-dependency library on top of `@codexo/exojs`. Core ships the audio engine
6
- (buses, voices, the `AudioEffect`/`WorkletEffect` bases, and the native
7
- `BiquadEffect`); this package adds the richer effects plus analysis tooling:
5
+ A peer-dependency library on top of `@codexo/exojs`. Core ships the audio engine (buses, voices, the `AudioEffect`/`WorkletEffect` bases, and the native `BiquadEffect`); this package adds the richer effects plus analysis tooling:
8
6
 
9
- - **Effects** — `ReverbEffect`, `DelayEffect`, `ChorusEffect`, `CompressorEffect`,
10
- `EqualizerEffect`, `GranularEffect`, `PitchShiftEffect`, `VocoderEffect`,
11
- `DuckingEffect`. Insert on a bus (`bus.addEffect(fx)`) or a voice
12
- (`voice.addEffect(fx)`).
13
- - **Analysis** — `AudioAnalyser` (spectrum / waveform / mel-log mapping) and
14
- `BeatDetector` (real-time tempo + beat tracking).
7
+ - **Effects** — `ReverbEffect`, `DelayEffect`, `ChorusEffect`, `CompressorEffect`, `EqualizerEffect`, `GranularEffect`, `PitchShiftEffect`, `VocoderEffect`, `DuckingEffect`. Insert on a bus (`bus.addEffect(fx)`) or a voice (`voice.addEffect(fx)`).
8
+ - **Analysis** — `AudioAnalyser` (spectrum / waveform / mel-log mapping) and `BeatDetector` (real-time tempo + beat tracking).
15
9
 
16
10
  ```ts
17
11
  import { ReverbEffect, AudioAnalyser } from '@codexo/exojs-audio-fx';
@@ -298,7 +298,7 @@ var AudioAnalyser = class {
298
298
  return msNode;
299
299
  }
300
300
  const asBus = source;
301
- if (typeof asBus._getOutputNode === "function") return asBus._getOutputNode();
301
+ if (typeof asBus.getOutputNode === "function") return asBus.getOutputNode();
302
302
  const asVoice = source;
303
303
  if ("output" in asVoice && asVoice.output) return asVoice.output;
304
304
  const asNode = source;
@@ -1 +1 @@
1
- {"version":3,"file":"AudioAnalyser.js","names":["asStream"],"sources":["../../src/AudioAnalyser.ts"],"sourcesContent":["import { type AudioBus, getAudioContext, isAudioContextReady, onAudioContextReady, type Voice } from '@codexo/exojs';\n\nimport { buildMelFilterbank, type MelBand } from './dsp/mel';\n\nexport type AudioAnalyserSource = AudioBus | Voice | MediaStream | AudioNode | null;\n\n/** Construction options for {@link AudioAnalyser}. */\nexport interface AudioAnalyserOptions {\n /** FFT window size; must be a power of two between 32 and 32768. Default 2048. */\n fftSize?: number;\n /** Time-domain smoothing constant in 0..1 applied between successive analyses. Default 0.8. */\n smoothingTimeConstant?: number;\n /** Minimum dBFS rendered by the byte-domain spectrum getters. Default -100. */\n minDecibels?: number;\n /** Maximum dBFS rendered by the byte-domain spectrum getters. Default -30. */\n maxDecibels?: number;\n /**\n * Optional initial source. Equivalent to `analyser.source = value` after\n * construction; provided for ergonomic one-shot construction. The setter\n * remains usable for runtime source switches.\n */\n source?: AudioAnalyserSource;\n}\n\n/** Mapping options for {@link AudioAnalyser.getSpectrumMel} and {@link AudioAnalyser.getSpectrumLog}. */\nexport interface SpectrumMappingOptions {\n /** Number of output bands. Default 32. */\n bands?: number;\n /** Lower frequency bound in Hz. Default 20. */\n fMin?: number;\n /** Upper frequency bound in Hz. Default 20000 (clamped to nyquist at runtime). */\n fMax?: number;\n}\n\ntype RequiredAnalyserOptions = Required<AudioAnalyserOptions>;\n\n/**\n * Lightweight visualisation analyser backed by a Web Audio AnalyserNode.\n *\n * Accepts any of: AudioBus, Voice, MediaStream, AudioNode, or null. The tap is\n * a parallel branch - it does not affect the source's main routing. Tap a bus\n * for a whole submix, or an individual {@link Voice} (its `output` node) for a\n * single playing instance.\n */\nexport class AudioAnalyser {\n private _analyser: AnalyserNode | null = null;\n private readonly _options: RequiredAnalyserOptions;\n private _source: AudioAnalyserSource = null;\n private _tapSource: AudioNode | null = null;\n private _streamSource: MediaStreamAudioSourceNode | null = null;\n private _pendingSourceSetup: ((ctx: AudioContext) => void) | null = null;\n private readonly _onAudioContextReady = (ctx: AudioContext): void => {\n onAudioContextReady.remove(this._onAudioContextReady);\n this._setupAnalyser(ctx);\n };\n\n // Pre-allocated buffers\n private _byteSpectrum: Uint8Array<ArrayBuffer>;\n private _floatSpectrum: Float32Array<ArrayBuffer>;\n private _byteWaveform: Uint8Array<ArrayBuffer>;\n private _floatWaveform: Float32Array<ArrayBuffer>;\n\n // Cached mel/log filterbanks. Key: `${bands}|${fMin}|${fMax}|${fftSize}`.\n // Filterbank construction is non-trivial; caching avoids per-frame allocation.\n private _melCache = new Map<string, MelBand[]>();\n private _logCache = new Map<string, LogBandRange[]>();\n\n /**\n * Create an `AudioAnalyser` with the given options. The underlying\n * `AnalyserNode` is created immediately if the `AudioContext` is already\n * running, or deferred until {@link onAudioContextReady} fires.\n */\n public constructor(options?: AudioAnalyserOptions) {\n this._options = {\n fftSize: options?.fftSize ?? 2048,\n smoothingTimeConstant: options?.smoothingTimeConstant ?? 0.8,\n minDecibels: options?.minDecibels ?? -100,\n maxDecibels: options?.maxDecibels ?? -30,\n source: options?.source ?? null,\n };\n\n const binCount = this._options.fftSize >> 1;\n this._byteSpectrum = new Uint8Array(binCount);\n this._floatSpectrum = new Float32Array(binCount);\n this._byteWaveform = new Uint8Array(binCount);\n this._floatWaveform = new Float32Array(binCount);\n\n if (isAudioContextReady()) {\n this._setupAnalyser(getAudioContext());\n } else {\n onAudioContextReady.add(this._onAudioContextReady);\n }\n\n if (options?.source !== undefined && options.source !== null) {\n this.source = options.source;\n }\n }\n\n // -----------------------------------------------------------------------\n // Source setter\n // -----------------------------------------------------------------------\n\n /**\n * The currently tapped audio source, or `null` if none is set.\n * Assigning a new value disconnects the previous tap and connects the new\n * source as a parallel branch without affecting the source's main routing.\n */\n public get source(): AudioAnalyserSource {\n return this._source;\n }\n\n public set source(value: AudioAnalyserSource) {\n if (value === this._source) return;\n\n // 1. Disconnect current tap\n this._disconnectTap();\n\n this._source = value;\n\n if (value === null) return;\n\n // 2. Resolve and connect new tap\n if (isAudioContextReady()) {\n this._pendingSourceSetup = null;\n this._connectSource(value, getAudioContext());\n } else {\n if (this._pendingSourceSetup !== null) {\n onAudioContextReady.remove(this._pendingSourceSetup);\n }\n\n const handler = (ctx: AudioContext): void => {\n onAudioContextReady.remove(handler);\n this._pendingSourceSetup = null;\n this._connectSource(value, ctx);\n };\n\n this._pendingSourceSetup = handler;\n onAudioContextReady.add(handler);\n }\n }\n\n // -----------------------------------------------------------------------\n // AnalyserNode property pass-throughs\n // -----------------------------------------------------------------------\n\n public get fftSize(): number {\n return this._options.fftSize;\n }\n\n /** Number of frequency bins available - half of `fftSize`. */\n public get frequencyBinCount(): number {\n return this._options.fftSize >> 1;\n }\n\n public get smoothingTimeConstant(): number {\n return this._analyser?.smoothingTimeConstant ?? this._options.smoothingTimeConstant;\n }\n\n public set smoothingTimeConstant(v: number) {\n this._options.smoothingTimeConstant = v;\n if (this._analyser) this._analyser.smoothingTimeConstant = v;\n }\n\n public get minDecibels(): number {\n return this._analyser?.minDecibels ?? this._options.minDecibels;\n }\n\n public set minDecibels(v: number) {\n this._options.minDecibels = v;\n if (this._analyser) this._analyser.minDecibels = v;\n }\n\n public get maxDecibels(): number {\n return this._analyser?.maxDecibels ?? this._options.maxDecibels;\n }\n\n public set maxDecibels(v: number) {\n this._options.maxDecibels = v;\n if (this._analyser) this._analyser.maxDecibels = v;\n }\n\n // -----------------------------------------------------------------------\n // Raw data\n // -----------------------------------------------------------------------\n\n /** Fill and return the byte frequency spectrum (0..255 per bin). */\n public getSpectrum(into?: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer> {\n const buf = into ?? this._byteSpectrum;\n if (this._analyser) {\n this._analyser.getByteFrequencyData(buf);\n } else {\n buf.fill(0);\n }\n return buf;\n }\n\n /** Fill and return the float frequency spectrum (dB per bin). */\n public getSpectrumFloat(into?: Float32Array<ArrayBuffer>): Float32Array<ArrayBuffer> {\n const buf = into ?? this._floatSpectrum;\n if (this._analyser) {\n this._analyser.getFloatFrequencyData(buf);\n } else {\n buf.fill(0);\n }\n return buf;\n }\n\n /** Fill and return the byte time-domain waveform (0..255 per sample). */\n public getWaveform(into?: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer> {\n const buf = into ?? this._byteWaveform;\n if (this._analyser) {\n this._analyser.getByteTimeDomainData(buf);\n } else {\n buf.fill(0);\n }\n return buf;\n }\n\n /** Fill and return the float time-domain waveform (-1..1 per sample). */\n public getWaveformFloat(into?: Float32Array<ArrayBuffer>): Float32Array<ArrayBuffer> {\n const buf = into ?? this._floatWaveform;\n if (this._analyser) {\n this._analyser.getFloatTimeDomainData(buf);\n } else {\n buf.fill(0);\n }\n return buf;\n }\n\n // -----------------------------------------------------------------------\n // Convenience helpers\n // -----------------------------------------------------------------------\n\n /**\n * Return the mean energy of frequency bins in the given Hz range, normalised 0..1.\n * Uses the byte spectrum (0..255), normalised by dividing by 255.\n */\n public getBandEnergy(fromHz: number, toHz: number): number {\n if (!this._analyser) return 0;\n const ctx = getAudioContext();\n const nyquist = ctx.sampleRate / 2;\n const binCount = this.frequencyBinCount;\n const fromBin = Math.max(0, Math.min(binCount - 1, Math.round((fromHz / nyquist) * binCount)));\n const toBin = Math.max(0, Math.min(binCount - 1, Math.round((toHz / nyquist) * binCount)));\n\n const lo = Math.min(fromBin, toBin);\n const hi = Math.max(fromBin, toBin);\n\n const spectrum = this.getSpectrum();\n let sum = 0;\n const count = hi - lo + 1;\n for (let i = lo; i <= hi; i++) {\n sum += spectrum[i]!;\n }\n return sum / (count * 255);\n }\n\n /** Return low (0-250 Hz), mid (250-2 kHz), and high (2 k-20 kHz) band energies (0..1 each). */\n public getLowMidHigh(): { low: number; mid: number; high: number } {\n return {\n low: this.getBandEnergy(0, 250),\n mid: this.getBandEnergy(250, 2000),\n high: this.getBandEnergy(2000, 20000),\n };\n }\n\n /** Return overall RMS energy across all bins, normalised 0..1. */\n public getRms(): number {\n if (!this._analyser) return 0;\n const ctx = getAudioContext();\n const nyquist = ctx.sampleRate / 2;\n return this.getBandEnergy(0, nyquist);\n }\n\n // -----------------------------------------------------------------------\n // Spectrum mapping (mel / log scaling)\n //\n // The raw FFT bins from AnalyserNode are linearly distributed across\n // 0..nyquist, which gives bass a few bins and treble hundreds. For\n // visualisations you typically want perceptually-weighted spacing.\n //\n // Both `getSpectrumMel` and `getSpectrumLog` operate on the byte-domain\n // spectrum (0..255) and produce byte output by default. The float\n // variants operate on dBFS values and produce float output.\n //\n // Filterbanks are cached on the analyser; they only rebuild when fftSize\n // or the (bands, fMin, fMax) parameters change.\n // -----------------------------------------------------------------------\n\n /**\n * Mel-scaled spectrum, byte domain (0..255). Output length = `bands`.\n * Each output bin is a triangular-weighted sum of the linear FFT bins\n * underneath it, mel-spaced from `fMin` to `fMax`.\n */\n public getSpectrumMel(into?: Uint8Array<ArrayBuffer>, options?: SpectrumMappingOptions): Uint8Array<ArrayBuffer> {\n const bandCount = options?.bands ?? 32;\n const out = into ?? new Uint8Array(bandCount);\n const filterbank = this._getMelFilterbank(bandCount, options?.fMin ?? 20, options?.fMax ?? 20000);\n\n if (!this._analyser || filterbank === null) {\n out.fill(0);\n return out;\n }\n\n this._analyser.getByteFrequencyData(this._byteSpectrum);\n applyFilterbank(this._byteSpectrum, filterbank, out);\n\n return out;\n }\n\n /** Mel-scaled spectrum, float domain (dBFS values). Output length = `bands`. */\n public getSpectrumMelFloat(into?: Float32Array<ArrayBuffer>, options?: SpectrumMappingOptions): Float32Array<ArrayBuffer> {\n const bandCount = options?.bands ?? 32;\n const out = into ?? new Float32Array(bandCount);\n const filterbank = this._getMelFilterbank(bandCount, options?.fMin ?? 20, options?.fMax ?? 20000);\n\n if (!this._analyser || filterbank === null) {\n out.fill(0);\n return out;\n }\n\n this._analyser.getFloatFrequencyData(this._floatSpectrum);\n applyFilterbank(this._floatSpectrum, filterbank, out);\n\n return out;\n }\n\n /**\n * Log-scaled spectrum, byte domain (0..255). Output length = `bands`.\n * Bins are spaced so each output covers an equal fraction of the\n * `log2(fMax / fMin)` octave range - useful when you want a\n * frequency-axis visualization where each octave gets the same width.\n */\n public getSpectrumLog(into?: Uint8Array<ArrayBuffer>, options?: SpectrumMappingOptions): Uint8Array<ArrayBuffer> {\n const bandCount = options?.bands ?? 32;\n const out = into ?? new Uint8Array(bandCount);\n const ranges = this._getLogRanges(bandCount, options?.fMin ?? 20, options?.fMax ?? 20000);\n\n if (!this._analyser || ranges === null) {\n out.fill(0);\n return out;\n }\n\n this._analyser.getByteFrequencyData(this._byteSpectrum);\n applyLogRanges(this._byteSpectrum, ranges, out);\n\n return out;\n }\n\n /** Log-scaled spectrum, float domain (dBFS values). Output length = `bands`. */\n public getSpectrumLogFloat(into?: Float32Array<ArrayBuffer>, options?: SpectrumMappingOptions): Float32Array<ArrayBuffer> {\n const bandCount = options?.bands ?? 32;\n const out = into ?? new Float32Array(bandCount);\n const ranges = this._getLogRanges(bandCount, options?.fMin ?? 20, options?.fMax ?? 20000);\n\n if (!this._analyser || ranges === null) {\n out.fill(0);\n return out;\n }\n\n this._analyser.getFloatFrequencyData(this._floatSpectrum);\n applyLogRanges(this._floatSpectrum, ranges, out);\n\n return out;\n }\n\n // -----------------------------------------------------------------------\n // Lifecycle\n // -----------------------------------------------------------------------\n\n /**\n * Disconnect the analyser tap, release the internal `AnalyserNode`, and\n * cancel any pending setup callbacks. Call when the analyser is no longer\n * needed to avoid memory leaks.\n */\n public destroy(): void {\n onAudioContextReady.remove(this._onAudioContextReady);\n\n if (this._pendingSourceSetup !== null) {\n onAudioContextReady.remove(this._pendingSourceSetup);\n this._pendingSourceSetup = null;\n }\n this._disconnectTap();\n this._analyser?.disconnect();\n this._analyser = null;\n this._source = null;\n }\n\n // -----------------------------------------------------------------------\n // Private helpers\n // -----------------------------------------------------------------------\n\n private _getMelFilterbank(bands: number, fMin: number, fMax: number): MelBand[] | null {\n if (!this._analyser) return null;\n const ctx = getAudioContext();\n const fftSize = this._options.fftSize;\n const clampedFmax = Math.min(fMax, ctx.sampleRate / 2);\n const key = `${bands}|${fMin}|${clampedFmax}|${fftSize}`;\n\n let cached = this._melCache.get(key);\n if (cached === undefined) {\n cached = buildMelFilterbank(bands, fMin, clampedFmax, fftSize, ctx.sampleRate);\n this._melCache.set(key, cached);\n }\n return cached;\n }\n\n private _getLogRanges(bands: number, fMin: number, fMax: number): LogBandRange[] | null {\n if (!this._analyser) return null;\n const ctx = getAudioContext();\n const fftSize = this._options.fftSize;\n const clampedFmax = Math.min(fMax, ctx.sampleRate / 2);\n const key = `${bands}|${fMin}|${clampedFmax}|${fftSize}`;\n\n let cached = this._logCache.get(key);\n if (cached === undefined) {\n cached = buildLogRanges(bands, fMin, clampedFmax, fftSize, ctx.sampleRate);\n this._logCache.set(key, cached);\n }\n return cached;\n }\n\n private _setupAnalyser(audioContext: AudioContext): void {\n const node = audioContext.createAnalyser();\n node.fftSize = this._options.fftSize;\n node.minDecibels = this._options.minDecibels;\n node.maxDecibels = this._options.maxDecibels;\n node.smoothingTimeConstant = this._options.smoothingTimeConstant;\n this._analyser = node;\n\n // If a source was set before the context was ready, connect it now.\n if (this._source !== null) {\n this._connectSource(this._source, audioContext);\n }\n }\n\n private _connectSource(source: AudioAnalyserSource, audioContext: AudioContext): void {\n if (!this._analyser) return;\n\n const tap = this._resolveToAudioNode(source, audioContext);\n if (!tap) {\n // AudioBus not ready yet - defer via its onceSetup\n this._deferConnectionViaBus(source);\n return;\n }\n\n this._tapSource = tap;\n tap.connect(this._analyser);\n }\n\n private _resolveToAudioNode(source: AudioAnalyserSource, audioContext: AudioContext): AudioNode | null {\n if (source === null) return null;\n\n // MediaStream - detect by getTracks (duck-type, since AudioNode also doesn't exist in jsdom)\n const asStream = source as Partial<{ getTracks: unknown }>;\n if (typeof asStream.getTracks === 'function') {\n if (this._streamSource) {\n this._streamSource.disconnect();\n this._streamSource = null;\n }\n const msNode = audioContext.createMediaStreamSource(source as MediaStream);\n this._streamSource = msNode;\n return msNode;\n }\n\n // AudioBus - has _getOutputNode (checked first since bus nodes also have connect/disconnect)\n const asBus = source as Partial<{ _getOutputNode: () => AudioNode | null }>;\n if (typeof asBus._getOutputNode === 'function') {\n return asBus._getOutputNode();\n }\n\n // Voice - tap its output node\n const asVoice = source as Partial<{ output: AudioNode }>;\n if ('output' in asVoice && asVoice.output) {\n return asVoice.output;\n }\n\n // Raw AudioNode - duck-type: has connect & disconnect\n const asNode = source as Partial<{ connect: unknown; disconnect: unknown }>;\n if (typeof asNode.connect === 'function' && typeof asNode.disconnect === 'function') {\n return source as unknown as AudioNode;\n }\n\n return null;\n }\n\n private _deferConnectionViaBus(source: AudioAnalyserSource): void {\n // AudioBus exposes onceSetup\n const asBus = source as Partial<{ onceSetup: (callback: () => void) => void }>;\n if (typeof asBus.onceSetup === 'function') {\n asBus.onceSetup(() => {\n if (this._source === source && this._analyser && isAudioContextReady()) {\n this._connectSource(source, getAudioContext());\n }\n });\n return;\n }\n\n // Otherwise retry once the audioContext is ready (same signal).\n onAudioContextReady.once(() => {\n if (this._source === source && this._analyser && isAudioContextReady()) {\n this._connectSource(source, getAudioContext());\n }\n });\n }\n\n private _disconnectTap(): void {\n if (this._tapSource && this._analyser) {\n try {\n this._tapSource.disconnect(this._analyser);\n } catch {\n // Ignore if already disconnected\n }\n }\n this._tapSource = null;\n\n // Clean up cached stream source\n if (this._streamSource) {\n this._streamSource.disconnect();\n this._streamSource = null;\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Filterbank helpers - module-private, shared between byte and float variants.\n// ---------------------------------------------------------------------------\n\ninterface LogBandRange {\n /** Inclusive start FFT bin. */\n readonly startBin: number;\n /** Inclusive end FFT bin. */\n readonly endBin: number;\n}\n\nconst buildLogRanges = (bandCount: number, fMin: number, fMax: number, fftSize: number, sampleRate: number): LogBandRange[] => {\n const binCount = fftSize >> 1;\n const nyquist = sampleRate / 2;\n const logMin = Math.log(fMin);\n const logMax = Math.log(fMax);\n const ranges: LogBandRange[] = [];\n\n for (let b = 0; b < bandCount; b++) {\n const lowHz = Math.exp(logMin + ((logMax - logMin) * b) / bandCount);\n const highHz = Math.exp(logMin + ((logMax - logMin) * (b + 1)) / bandCount);\n const startBin = Math.max(0, Math.min(binCount - 1, Math.floor((lowHz / nyquist) * binCount)));\n const endBin = Math.max(startBin, Math.min(binCount - 1, Math.ceil((highHz / nyquist) * binCount) - 1));\n ranges.push({ startBin, endBin });\n }\n\n return ranges;\n};\n\nconst applyFilterbank = (spectrum: Uint8Array | Float32Array, bands: MelBand[], out: Uint8Array | Float32Array): void => {\n for (let b = 0; b < bands.length; b++) {\n const { startBin, weights } = bands[b]!;\n let sum = 0;\n for (let i = 0; i < weights.length; i++) {\n sum += spectrum[startBin + i]! * weights[i]!;\n }\n out[b] = sum;\n }\n};\n\nconst applyLogRanges = (spectrum: Uint8Array | Float32Array, ranges: LogBandRange[], out: Uint8Array | Float32Array): void => {\n for (let b = 0; b < ranges.length; b++) {\n const { startBin, endBin } = ranges[b]!;\n let sum = 0;\n const count = endBin - startBin + 1;\n for (let i = startBin; i <= endBin; i++) {\n sum += spectrum[i]!;\n }\n out[b] = sum / count;\n }\n};\n"],"mappings":";;;;;;;;;;;;AA4CA,IAAa,gBAAb,MAA2B;CACzB,AAAQ,YAAiC;CACzC,AAAiB;CACjB,AAAQ,UAA+B;CACvC,AAAQ,aAA+B;CACvC,AAAQ,gBAAmD;CAC3D,AAAQ,sBAA4D;CACpE,AAAiB,wBAAwB,QAA4B;EACnE,oBAAoB,OAAO,KAAK,oBAAoB;EACpD,KAAK,eAAe,GAAG;CACzB;CAGA,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAIR,AAAQ,4BAAY,IAAI,IAAuB;CAC/C,AAAQ,4BAAY,IAAI,IAA4B;;;;;;CAOpD,AAAO,YAAY,SAAgC;EACjD,KAAK,WAAW;GACd,SAAS,SAAS,WAAW;GAC7B,uBAAuB,SAAS,yBA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I;CAC5B,MAAM,SAAyB,CAAC;CAEhC,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,KAAK;EAClC,MAAM,QAAQ,KAAK,IAAI,UAAW,SAAS,UAAU,IAAK,SAAS;EACnE,MAAM,SAAS,KAAK,IAAI,UAAW,SAAS,WAAW,IAAI,KAAM,SAAS;EAC1E,MAAM,WAAW,KAAK,IAAI,GAAG,KAAK,IAAI,WAAW,GAAG,KAAK,MAAO,QAAQ,UAAW,QAAQ,CAAC,CAAC;EAC7F,MAAM,SAAS,KAAK,IAAI,UAAU,KAAK,IAAI,WAAW,GAAG,KAAK,KAAM,SAAS,UAAW,QAAQ,IAAI,CAAC,CAAC;EACtG,OAAO,KAAK;GAAE;GAAU;EAAO,CAAC;CAClC;CAEA,OAAO;AACT;AAEA,MAAM,mBAAmB,UAAqC,OAAkB,QAAyC;CACvH,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,EAAE,UAAU,YAAY,MAAM;EACpC,IAAI,MAAM;EACV,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAClC,OAAO,SAAS,WAAW,KAAM,QAAQ;EAE3C,IAAI,KAAK;CACX;AACF;AAEA,MAAM,kBAAkB,UAAqC,QAAwB,QAAyC;CAC5H,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;EACtC,MAAM,EAAE,UAAU,WAAW,OAAO;EACpC,IAAI,MAAM;EACV,MAAM,QAAQ,SAAS,WAAW;EAClC,KAAK,IAAI,IAAI,UAAU,KAAK,QAAQ,KAClC,OAAO,SAAS;EAElB,IAAI,KAAK,MAAM;CACjB;AACF"}
1
+ {"version":3,"file":"AudioAnalyser.js","names":["asStream"],"sources":["../../src/AudioAnalyser.ts"],"sourcesContent":["import { type AudioBus, getAudioContext, isAudioContextReady, onAudioContextReady, type Voice } from '@codexo/exojs';\n\nimport { buildMelFilterbank, type MelBand } from './dsp/mel';\n\nexport type AudioAnalyserSource = AudioBus | Voice | MediaStream | AudioNode | null;\n\n/** Construction options for {@link AudioAnalyser}. */\nexport interface AudioAnalyserOptions {\n /** FFT window size; must be a power of two between 32 and 32768. Default 2048. */\n fftSize?: number;\n /** Time-domain smoothing constant in 0..1 applied between successive analyses. Default 0.8. */\n smoothingTimeConstant?: number;\n /** Minimum dBFS rendered by the byte-domain spectrum getters. Default -100. */\n minDecibels?: number;\n /** Maximum dBFS rendered by the byte-domain spectrum getters. Default -30. */\n maxDecibels?: number;\n /**\n * Optional initial source. Equivalent to `analyser.source = value` after\n * construction; provided for ergonomic one-shot construction. The setter\n * remains usable for runtime source switches.\n */\n source?: AudioAnalyserSource;\n}\n\n/** Mapping options for {@link AudioAnalyser.getSpectrumMel} and {@link AudioAnalyser.getSpectrumLog}. */\nexport interface SpectrumMappingOptions {\n /** Number of output bands. Default 32. */\n bands?: number;\n /** Lower frequency bound in Hz. Default 20. */\n fMin?: number;\n /** Upper frequency bound in Hz. Default 20000 (clamped to nyquist at runtime). */\n fMax?: number;\n}\n\ntype RequiredAnalyserOptions = Required<AudioAnalyserOptions>;\n\n/**\n * Lightweight visualisation analyser backed by a Web Audio AnalyserNode.\n *\n * Accepts any of: AudioBus, Voice, MediaStream, AudioNode, or null. The tap is\n * a parallel branch - it does not affect the source's main routing. Tap a bus\n * for a whole submix, or an individual {@link Voice} (its `output` node) for a\n * single playing instance.\n */\nexport class AudioAnalyser {\n private _analyser: AnalyserNode | null = null;\n private readonly _options: RequiredAnalyserOptions;\n private _source: AudioAnalyserSource = null;\n private _tapSource: AudioNode | null = null;\n private _streamSource: MediaStreamAudioSourceNode | null = null;\n private _pendingSourceSetup: ((ctx: AudioContext) => void) | null = null;\n private readonly _onAudioContextReady = (ctx: AudioContext): void => {\n onAudioContextReady.remove(this._onAudioContextReady);\n this._setupAnalyser(ctx);\n };\n\n // Pre-allocated buffers\n private _byteSpectrum: Uint8Array<ArrayBuffer>;\n private _floatSpectrum: Float32Array<ArrayBuffer>;\n private _byteWaveform: Uint8Array<ArrayBuffer>;\n private _floatWaveform: Float32Array<ArrayBuffer>;\n\n // Cached mel/log filterbanks. Key: `${bands}|${fMin}|${fMax}|${fftSize}`.\n // Filterbank construction is non-trivial; caching avoids per-frame allocation.\n private _melCache = new Map<string, MelBand[]>();\n private _logCache = new Map<string, LogBandRange[]>();\n\n /**\n * Create an `AudioAnalyser` with the given options. The underlying\n * `AnalyserNode` is created immediately if the `AudioContext` is already\n * running, or deferred until {@link onAudioContextReady} fires.\n */\n public constructor(options?: AudioAnalyserOptions) {\n this._options = {\n fftSize: options?.fftSize ?? 2048,\n smoothingTimeConstant: options?.smoothingTimeConstant ?? 0.8,\n minDecibels: options?.minDecibels ?? -100,\n maxDecibels: options?.maxDecibels ?? -30,\n source: options?.source ?? null,\n };\n\n const binCount = this._options.fftSize >> 1;\n this._byteSpectrum = new Uint8Array(binCount);\n this._floatSpectrum = new Float32Array(binCount);\n this._byteWaveform = new Uint8Array(binCount);\n this._floatWaveform = new Float32Array(binCount);\n\n if (isAudioContextReady()) {\n this._setupAnalyser(getAudioContext());\n } else {\n onAudioContextReady.add(this._onAudioContextReady);\n }\n\n if (options?.source !== undefined && options.source !== null) {\n this.source = options.source;\n }\n }\n\n // -----------------------------------------------------------------------\n // Source setter\n // -----------------------------------------------------------------------\n\n /**\n * The currently tapped audio source, or `null` if none is set.\n * Assigning a new value disconnects the previous tap and connects the new\n * source as a parallel branch without affecting the source's main routing.\n */\n public get source(): AudioAnalyserSource {\n return this._source;\n }\n\n public set source(value: AudioAnalyserSource) {\n if (value === this._source) return;\n\n // 1. Disconnect current tap\n this._disconnectTap();\n\n this._source = value;\n\n if (value === null) return;\n\n // 2. Resolve and connect new tap\n if (isAudioContextReady()) {\n this._pendingSourceSetup = null;\n this._connectSource(value, getAudioContext());\n } else {\n if (this._pendingSourceSetup !== null) {\n onAudioContextReady.remove(this._pendingSourceSetup);\n }\n\n const handler = (ctx: AudioContext): void => {\n onAudioContextReady.remove(handler);\n this._pendingSourceSetup = null;\n this._connectSource(value, ctx);\n };\n\n this._pendingSourceSetup = handler;\n onAudioContextReady.add(handler);\n }\n }\n\n // -----------------------------------------------------------------------\n // AnalyserNode property pass-throughs\n // -----------------------------------------------------------------------\n\n public get fftSize(): number {\n return this._options.fftSize;\n }\n\n /** Number of frequency bins available - half of `fftSize`. */\n public get frequencyBinCount(): number {\n return this._options.fftSize >> 1;\n }\n\n public get smoothingTimeConstant(): number {\n return this._analyser?.smoothingTimeConstant ?? this._options.smoothingTimeConstant;\n }\n\n public set smoothingTimeConstant(v: number) {\n this._options.smoothingTimeConstant = v;\n if (this._analyser) this._analyser.smoothingTimeConstant = v;\n }\n\n public get minDecibels(): number {\n return this._analyser?.minDecibels ?? this._options.minDecibels;\n }\n\n public set minDecibels(v: number) {\n this._options.minDecibels = v;\n if (this._analyser) this._analyser.minDecibels = v;\n }\n\n public get maxDecibels(): number {\n return this._analyser?.maxDecibels ?? this._options.maxDecibels;\n }\n\n public set maxDecibels(v: number) {\n this._options.maxDecibels = v;\n if (this._analyser) this._analyser.maxDecibels = v;\n }\n\n // -----------------------------------------------------------------------\n // Raw data\n // -----------------------------------------------------------------------\n\n /** Fill and return the byte frequency spectrum (0..255 per bin). */\n public getSpectrum(into?: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer> {\n const buf = into ?? this._byteSpectrum;\n if (this._analyser) {\n this._analyser.getByteFrequencyData(buf);\n } else {\n buf.fill(0);\n }\n return buf;\n }\n\n /** Fill and return the float frequency spectrum (dB per bin). */\n public getSpectrumFloat(into?: Float32Array<ArrayBuffer>): Float32Array<ArrayBuffer> {\n const buf = into ?? this._floatSpectrum;\n if (this._analyser) {\n this._analyser.getFloatFrequencyData(buf);\n } else {\n buf.fill(0);\n }\n return buf;\n }\n\n /** Fill and return the byte time-domain waveform (0..255 per sample). */\n public getWaveform(into?: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer> {\n const buf = into ?? this._byteWaveform;\n if (this._analyser) {\n this._analyser.getByteTimeDomainData(buf);\n } else {\n buf.fill(0);\n }\n return buf;\n }\n\n /** Fill and return the float time-domain waveform (-1..1 per sample). */\n public getWaveformFloat(into?: Float32Array<ArrayBuffer>): Float32Array<ArrayBuffer> {\n const buf = into ?? this._floatWaveform;\n if (this._analyser) {\n this._analyser.getFloatTimeDomainData(buf);\n } else {\n buf.fill(0);\n }\n return buf;\n }\n\n // -----------------------------------------------------------------------\n // Convenience helpers\n // -----------------------------------------------------------------------\n\n /**\n * Return the mean energy of frequency bins in the given Hz range, normalised 0..1.\n * Uses the byte spectrum (0..255), normalised by dividing by 255.\n */\n public getBandEnergy(fromHz: number, toHz: number): number {\n if (!this._analyser) return 0;\n const ctx = getAudioContext();\n const nyquist = ctx.sampleRate / 2;\n const binCount = this.frequencyBinCount;\n const fromBin = Math.max(0, Math.min(binCount - 1, Math.round((fromHz / nyquist) * binCount)));\n const toBin = Math.max(0, Math.min(binCount - 1, Math.round((toHz / nyquist) * binCount)));\n\n const lo = Math.min(fromBin, toBin);\n const hi = Math.max(fromBin, toBin);\n\n const spectrum = this.getSpectrum();\n let sum = 0;\n const count = hi - lo + 1;\n for (let i = lo; i <= hi; i++) {\n sum += spectrum[i]!;\n }\n return sum / (count * 255);\n }\n\n /** Return low (0-250 Hz), mid (250-2 kHz), and high (2 k-20 kHz) band energies (0..1 each). */\n public getLowMidHigh(): { low: number; mid: number; high: number } {\n return {\n low: this.getBandEnergy(0, 250),\n mid: this.getBandEnergy(250, 2000),\n high: this.getBandEnergy(2000, 20000),\n };\n }\n\n /** Return overall RMS energy across all bins, normalised 0..1. */\n public getRms(): number {\n if (!this._analyser) return 0;\n const ctx = getAudioContext();\n const nyquist = ctx.sampleRate / 2;\n return this.getBandEnergy(0, nyquist);\n }\n\n // -----------------------------------------------------------------------\n // Spectrum mapping (mel / log scaling)\n //\n // The raw FFT bins from AnalyserNode are linearly distributed across\n // 0..nyquist, which gives bass a few bins and treble hundreds. For\n // visualisations you typically want perceptually-weighted spacing.\n //\n // Both `getSpectrumMel` and `getSpectrumLog` operate on the byte-domain\n // spectrum (0..255) and produce byte output by default. The float\n // variants operate on dBFS values and produce float output.\n //\n // Filterbanks are cached on the analyser; they only rebuild when fftSize\n // or the (bands, fMin, fMax) parameters change.\n // -----------------------------------------------------------------------\n\n /**\n * Mel-scaled spectrum, byte domain (0..255). Output length = `bands`.\n * Each output bin is a triangular-weighted sum of the linear FFT bins\n * underneath it, mel-spaced from `fMin` to `fMax`.\n */\n public getSpectrumMel(into?: Uint8Array<ArrayBuffer>, options?: SpectrumMappingOptions): Uint8Array<ArrayBuffer> {\n const bandCount = options?.bands ?? 32;\n const out = into ?? new Uint8Array(bandCount);\n const filterbank = this._getMelFilterbank(bandCount, options?.fMin ?? 20, options?.fMax ?? 20000);\n\n if (!this._analyser || filterbank === null) {\n out.fill(0);\n return out;\n }\n\n this._analyser.getByteFrequencyData(this._byteSpectrum);\n applyFilterbank(this._byteSpectrum, filterbank, out);\n\n return out;\n }\n\n /** Mel-scaled spectrum, float domain (dBFS values). Output length = `bands`. */\n public getSpectrumMelFloat(into?: Float32Array<ArrayBuffer>, options?: SpectrumMappingOptions): Float32Array<ArrayBuffer> {\n const bandCount = options?.bands ?? 32;\n const out = into ?? new Float32Array(bandCount);\n const filterbank = this._getMelFilterbank(bandCount, options?.fMin ?? 20, options?.fMax ?? 20000);\n\n if (!this._analyser || filterbank === null) {\n out.fill(0);\n return out;\n }\n\n this._analyser.getFloatFrequencyData(this._floatSpectrum);\n applyFilterbank(this._floatSpectrum, filterbank, out);\n\n return out;\n }\n\n /**\n * Log-scaled spectrum, byte domain (0..255). Output length = `bands`.\n * Bins are spaced so each output covers an equal fraction of the\n * `log2(fMax / fMin)` octave range - useful when you want a\n * frequency-axis visualization where each octave gets the same width.\n */\n public getSpectrumLog(into?: Uint8Array<ArrayBuffer>, options?: SpectrumMappingOptions): Uint8Array<ArrayBuffer> {\n const bandCount = options?.bands ?? 32;\n const out = into ?? new Uint8Array(bandCount);\n const ranges = this._getLogRanges(bandCount, options?.fMin ?? 20, options?.fMax ?? 20000);\n\n if (!this._analyser || ranges === null) {\n out.fill(0);\n return out;\n }\n\n this._analyser.getByteFrequencyData(this._byteSpectrum);\n applyLogRanges(this._byteSpectrum, ranges, out);\n\n return out;\n }\n\n /** Log-scaled spectrum, float domain (dBFS values). Output length = `bands`. */\n public getSpectrumLogFloat(into?: Float32Array<ArrayBuffer>, options?: SpectrumMappingOptions): Float32Array<ArrayBuffer> {\n const bandCount = options?.bands ?? 32;\n const out = into ?? new Float32Array(bandCount);\n const ranges = this._getLogRanges(bandCount, options?.fMin ?? 20, options?.fMax ?? 20000);\n\n if (!this._analyser || ranges === null) {\n out.fill(0);\n return out;\n }\n\n this._analyser.getFloatFrequencyData(this._floatSpectrum);\n applyLogRanges(this._floatSpectrum, ranges, out);\n\n return out;\n }\n\n // -----------------------------------------------------------------------\n // Lifecycle\n // -----------------------------------------------------------------------\n\n /**\n * Disconnect the analyser tap, release the internal `AnalyserNode`, and\n * cancel any pending setup callbacks. Call when the analyser is no longer\n * needed to avoid memory leaks.\n */\n public destroy(): void {\n onAudioContextReady.remove(this._onAudioContextReady);\n\n if (this._pendingSourceSetup !== null) {\n onAudioContextReady.remove(this._pendingSourceSetup);\n this._pendingSourceSetup = null;\n }\n this._disconnectTap();\n this._analyser?.disconnect();\n this._analyser = null;\n this._source = null;\n }\n\n // -----------------------------------------------------------------------\n // Private helpers\n // -----------------------------------------------------------------------\n\n private _getMelFilterbank(bands: number, fMin: number, fMax: number): MelBand[] | null {\n if (!this._analyser) return null;\n const ctx = getAudioContext();\n const fftSize = this._options.fftSize;\n const clampedFmax = Math.min(fMax, ctx.sampleRate / 2);\n const key = `${bands}|${fMin}|${clampedFmax}|${fftSize}`;\n\n let cached = this._melCache.get(key);\n if (cached === undefined) {\n cached = buildMelFilterbank(bands, fMin, clampedFmax, fftSize, ctx.sampleRate);\n this._melCache.set(key, cached);\n }\n return cached;\n }\n\n private _getLogRanges(bands: number, fMin: number, fMax: number): LogBandRange[] | null {\n if (!this._analyser) return null;\n const ctx = getAudioContext();\n const fftSize = this._options.fftSize;\n const clampedFmax = Math.min(fMax, ctx.sampleRate / 2);\n const key = `${bands}|${fMin}|${clampedFmax}|${fftSize}`;\n\n let cached = this._logCache.get(key);\n if (cached === undefined) {\n cached = buildLogRanges(bands, fMin, clampedFmax, fftSize, ctx.sampleRate);\n this._logCache.set(key, cached);\n }\n return cached;\n }\n\n private _setupAnalyser(audioContext: AudioContext): void {\n const node = audioContext.createAnalyser();\n node.fftSize = this._options.fftSize;\n node.minDecibels = this._options.minDecibels;\n node.maxDecibels = this._options.maxDecibels;\n node.smoothingTimeConstant = this._options.smoothingTimeConstant;\n this._analyser = node;\n\n // If a source was set before the context was ready, connect it now.\n if (this._source !== null) {\n this._connectSource(this._source, audioContext);\n }\n }\n\n private _connectSource(source: AudioAnalyserSource, audioContext: AudioContext): void {\n if (!this._analyser) return;\n\n const tap = this._resolveToAudioNode(source, audioContext);\n if (!tap) {\n // AudioBus not ready yet - defer via its onceSetup\n this._deferConnectionViaBus(source);\n return;\n }\n\n this._tapSource = tap;\n tap.connect(this._analyser);\n }\n\n private _resolveToAudioNode(source: AudioAnalyserSource, audioContext: AudioContext): AudioNode | null {\n if (source === null) return null;\n\n // MediaStream - detect by getTracks (duck-type, since AudioNode also doesn't exist in jsdom)\n const asStream = source as Partial<{ getTracks: unknown }>;\n if (typeof asStream.getTracks === 'function') {\n if (this._streamSource) {\n this._streamSource.disconnect();\n this._streamSource = null;\n }\n const msNode = audioContext.createMediaStreamSource(source as MediaStream);\n this._streamSource = msNode;\n return msNode;\n }\n\n // AudioBus - has getOutputNode (checked first since bus nodes also have connect/disconnect)\n const asBus = source as Partial<{ getOutputNode: () => AudioNode | null }>;\n if (typeof asBus.getOutputNode === 'function') {\n return asBus.getOutputNode();\n }\n\n // Voice - tap its output node\n const asVoice = source as Partial<{ output: AudioNode }>;\n if ('output' in asVoice && asVoice.output) {\n return asVoice.output;\n }\n\n // Raw AudioNode - duck-type: has connect & disconnect\n const asNode = source as Partial<{ connect: unknown; disconnect: unknown }>;\n if (typeof asNode.connect === 'function' && typeof asNode.disconnect === 'function') {\n return source as unknown as AudioNode;\n }\n\n return null;\n }\n\n private _deferConnectionViaBus(source: AudioAnalyserSource): void {\n // AudioBus exposes onceSetup\n const asBus = source as Partial<{ onceSetup: (callback: () => void) => void }>;\n if (typeof asBus.onceSetup === 'function') {\n asBus.onceSetup(() => {\n if (this._source === source && this._analyser && isAudioContextReady()) {\n this._connectSource(source, getAudioContext());\n }\n });\n return;\n }\n\n // Otherwise retry once the audioContext is ready (same signal).\n onAudioContextReady.once(() => {\n if (this._source === source && this._analyser && isAudioContextReady()) {\n this._connectSource(source, getAudioContext());\n }\n });\n }\n\n private _disconnectTap(): void {\n if (this._tapSource && this._analyser) {\n try {\n this._tapSource.disconnect(this._analyser);\n } catch {\n // Ignore if already disconnected\n }\n }\n this._tapSource = null;\n\n // Clean up cached stream source\n if (this._streamSource) {\n this._streamSource.disconnect();\n this._streamSource = null;\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Filterbank helpers - module-private, shared between byte and float variants.\n// ---------------------------------------------------------------------------\n\ninterface LogBandRange {\n /** Inclusive start FFT bin. */\n readonly startBin: number;\n /** Inclusive end FFT bin. */\n readonly endBin: number;\n}\n\nconst buildLogRanges = (bandCount: number, fMin: number, fMax: number, fftSize: number, sampleRate: number): LogBandRange[] => {\n const binCount = fftSize >> 1;\n const nyquist = sampleRate / 2;\n const logMin = Math.log(fMin);\n const logMax = Math.log(fMax);\n const ranges: LogBandRange[] = [];\n\n for (let b = 0; b < bandCount; b++) {\n const lowHz = Math.exp(logMin + ((logMax - logMin) * b) / bandCount);\n const highHz = Math.exp(logMin + ((logMax - logMin) * (b + 1)) / bandCount);\n const startBin = Math.max(0, Math.min(binCount - 1, Math.floor((lowHz / nyquist) * binCount)));\n const endBin = Math.max(startBin, Math.min(binCount - 1, Math.ceil((highHz / nyquist) * binCount) - 1));\n ranges.push({ startBin, endBin });\n }\n\n return ranges;\n};\n\nconst applyFilterbank = (spectrum: Uint8Array | Float32Array, bands: MelBand[], out: Uint8Array | Float32Array): void => {\n for (let b = 0; b < bands.length; b++) {\n const { startBin, weights } = bands[b]!;\n let sum = 0;\n for (let i = 0; i < weights.length; i++) {\n sum += spectrum[startBin + i]! * weights[i]!;\n }\n out[b] = sum;\n }\n};\n\nconst applyLogRanges = (spectrum: Uint8Array | Float32Array, ranges: LogBandRange[], out: Uint8Array | Float32Array): void => {\n for (let b = 0; b < ranges.length; b++) {\n const { startBin, endBin } = ranges[b]!;\n let sum = 0;\n const count = endBin - startBin + 1;\n for (let i = startBin; i <= endBin; i++) {\n sum += spectrum[i]!;\n }\n out[b] = sum / count;\n }\n};\n"],"mappings":";;;;;;;;;;;;AA4CA,IAAa,gBAAb,MAA2B;CACzB,AAAQ,YAAiC;CACzC,AAAiB;CACjB,AAAQ,UAA+B;CACvC,AAAQ,aAA+B;CACvC,AAAQ,gBAAmD;CAC3D,AAAQ,sBAA4D;CACpE,AAAiB,wBAAwB,QAA4B;EACnE,oBAAoB,OAAO,KAAK,oBAAoB;EACpD,KAAK,eAAe,GAAG;CACzB;CAGA,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAIR,AAAQ,4BAAY,IAAI,IAAuB;CAC/C,AAAQ,4BAAY,IAAI,IAA4B;;;;;;CAOpD,AAAO,YAAY,SAAgC;EACjD,KAAK,WAAW;GACd,SAAS,SAAS,WAAW;GAC7B,uBAAuB,SAAS,yBAAyB;GACzD,aAAa,SAAS,eAAe;GACrC,aAAa,SAAS,eAAe;GACrC,QAAQ,SAAS,UAAU;EAC7B;EAEA,MAAM,WAAW,KAAK,SAAS,WAAW;EAC1C,KAAK,gBAAgB,IAAI,WAAW,QAAQ;EAC5C,KAAK,iBAAiB,IAAI,aAAa,QAAQ;EAC/C,KAAK,gBAAgB,IAAI,WAAW,QAAQ;EAC5C,KAAK,iBAAiB,IA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AAK,MAAO,QAAQ,UAAW,QAAQ,CAAC,CAAC;EAC7F,MAAM,SAAS,KAAK,IAAI,UAAU,KAAK,IAAI,WAAW,GAAG,KAAK,KAAM,SAAS,UAAW,QAAQ,IAAI,CAAC,CAAC;EACtG,OAAO,KAAK;GAAE;GAAU;EAAO,CAAC;CAClC;CAEA,OAAO;AACT;AAEA,MAAM,mBAAmB,UAAqC,OAAkB,QAAyC;CACvH,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,EAAE,UAAU,YAAY,MAAM;EACpC,IAAI,MAAM;EACV,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAClC,OAAO,SAAS,WAAW,KAAM,QAAQ;EAE3C,IAAI,KAAK;CACX;AACF;AAEA,MAAM,kBAAkB,UAAqC,QAAwB,QAAyC;CAC5H,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;EACtC,MAAM,EAAE,UAAU,WAAW,OAAO;EACpC,IAAI,MAAM;EACV,MAAM,QAAQ,SAAS,WAAW;EAClC,KAAK,IAAI,IAAI,UAAU,KAAK,QAAQ,KAClC,OAAO,SAAS;EAElB,IAAI,KAAK,MAAM;CACjB;AACF"}
@@ -170,7 +170,10 @@ export declare class BeatDetector {
170
170
  private _beatPhase;
171
171
  private _nextBeatTime;
172
172
  private _confidence;
173
+ private _phaseConfidence;
173
174
  private _gridStability;
175
+ private _analysisTime;
176
+ private _analysisLatency;
174
177
  private _tempoCandidates;
175
178
  private _rms;
176
179
  private _onsetStrength;
@@ -197,7 +200,40 @@ export declare class BeatDetector {
197
200
  get beatPhase(): number;
198
201
  get nextBeatTime(): number;
199
202
  get confidence(): number;
203
+ /**
204
+ * How well recent onsets support the beat grid's phase, 0 to 1, or 0 before
205
+ * the grid locks.
206
+ *
207
+ * Distinct from {@link confidence}, which reports how sure the detector is of
208
+ * the tempo. A metronomic loop at a wrong-by-an-octave tempo reads high
209
+ * confidence and high phase confidence; a rubato passage at a known tempo
210
+ * reads high confidence and low phase confidence. Gate anything that must
211
+ * land exactly on the beat - a scored hit, a quantised trigger - on this
212
+ * rather than on {@link confidence}.
213
+ */
214
+ get phaseConfidence(): number;
200
215
  get gridStability(): number;
216
+ /**
217
+ * The `AudioContext.currentTime` of the newest sample the current state
218
+ * describes. 0 until the first state message arrives.
219
+ *
220
+ * Every timestamp this detector reports - this one, {@link BeatInfo.audioTime},
221
+ * {@link nextBeatTime}, {@link lookahead} - is on the audio context's clock,
222
+ * so `AudioOutputClock` converts them to the `performance.now()` timeline
223
+ * without further correction.
224
+ */
225
+ get analysisTime(): number;
226
+ /**
227
+ * Seconds between {@link analysisTime} and the moment the main thread
228
+ * received that state, measured rather than assumed.
229
+ *
230
+ * Covers the analysis hop and the worklet-to-main-thread delivery together,
231
+ * and is quantised to the context's render-quantum boundary, so treat it as
232
+ * a budget figure rather than an exact age. It says nothing about the output
233
+ * path: what a listener hears lags the analysed audio by the output latency
234
+ * on top, which `AudioOutputClock` reports.
235
+ */
236
+ get analysisLatency(): number;
201
237
  get rms(): number;
202
238
  get onsetStrength(): number;
203
239
  get bandEnergy(): BandEnergy;
@@ -1 +1 @@
1
- {"version":3,"file":"BeatDetector.d.ts","sourceRoot":"","sources":["../../src/BeatDetector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,QAAQ,EAA4F,MAAM,EAAE,KAAK,KAAK,EAAE,MAAM,eAAe,CAAC;AAQ5J,MAAM,MAAM,kBAAkB,GAAG,QAAQ,GAAG,KAAK,GAAG,WAAW,GAAG,SAAS,GAAG,IAAI,CAAC;AAEnF,MAAM,WAAW,mBAAmB;IAClC,0CAA0C;IAC1C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,2CAA2C;IAC3C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,kDAAkD;IAClD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gEAAgE;IAChE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;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,YAAY,IAAI,MAAM,CAEhC;IACD,IAAW,UAAU,IAAI,MAAM,CAE9B;IAED;;;;;;;;;;OAUG;IACH,IAAW,eAAe,IAAI,MAAM,CAEnC;IAED,IAAW,aAAa,IAAI,MAAM,CAEjC;IAED;;;;;;;;OAQG;IACH,IAAW,YAAY,IAAI,MAAM,CAEhC;IAED;;;;;;;;;OASG;IACH,IAAW,eAAe,IAAI,MAAM,CAEnC;IACD,IAAW,GAAG,IAAI,MAAM,CAEvB;IACD,IAAW,aAAa,IAAI,MAAM,CAEjC;IACD,IAAW,UAAU,IAAI,UAAU,CAElC;IAED,IAAW,eAAe,IAAI,SAAS,cAAc,EAAE,CAEtD;IAMD,IAAW,WAAW,IAAI,MAAM,CAE/B;IACD,IAAW,SAAS,IAAI,MAAM,CAE7B;IACD,IAAW,aAAa,IAAI,aAAa,CAExC;IACD,IAAW,gBAAgB,IAAI,MAAM,CAEpC;IAED,IAAW,SAAS,IAAI,SAAS,YAAY,EAAE,CAE9C;IAMD;;;OAGG;IACH,IAAW,oBAAoB,IAAI,MAAM,CAGxC;IAED;;;;OAIG;IACH,IAAW,KAAK,IAAI,MAAM,CAGzB;IAED;;;;OAIG;IACH,IAAW,QAAQ,IAAI,MAAM,CAM5B;IAED;;;;OAIG;IACH,IAAW,QAAQ,IAAI,OAAO,CAE7B;IAED;;;;;;;OAOG;IACI,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM;IAS1C,OAAO,IAAI,IAAI;IAsBtB,OAAO,CAAC,MAAM;IA+Bd,OAAO,CAAC,iBAAiB;IAkEzB,OAAO,CAAC,cAAc;IAatB,OAAO,CAAC,mBAAmB;IAoC3B,OAAO,CAAC,sBAAsB;IAkB9B,OAAO,CAAC,cAAc;CAevB"}
@@ -48,7 +48,10 @@ var BeatDetector = class {
48
48
  _beatPhase = 0;
49
49
  _nextBeatTime = 0;
50
50
  _confidence = 0;
51
+ _phaseConfidence = 0;
51
52
  _gridStability = 0;
53
+ _analysisTime = 0;
54
+ _analysisLatency = 0;
52
55
  _tempoCandidates = [];
53
56
  _rms = 0;
54
57
  _onsetStrength = 0;
@@ -136,9 +139,48 @@ var BeatDetector = class {
136
139
  get confidence() {
137
140
  return this._confidence;
138
141
  }
142
+ /**
143
+ * How well recent onsets support the beat grid's phase, 0 to 1, or 0 before
144
+ * the grid locks.
145
+ *
146
+ * Distinct from {@link confidence}, which reports how sure the detector is of
147
+ * the tempo. A metronomic loop at a wrong-by-an-octave tempo reads high
148
+ * confidence and high phase confidence; a rubato passage at a known tempo
149
+ * reads high confidence and low phase confidence. Gate anything that must
150
+ * land exactly on the beat - a scored hit, a quantised trigger - on this
151
+ * rather than on {@link confidence}.
152
+ */
153
+ get phaseConfidence() {
154
+ return this._phaseConfidence;
155
+ }
139
156
  get gridStability() {
140
157
  return this._gridStability;
141
158
  }
159
+ /**
160
+ * The `AudioContext.currentTime` of the newest sample the current state
161
+ * describes. 0 until the first state message arrives.
162
+ *
163
+ * Every timestamp this detector reports - this one, {@link BeatInfo.audioTime},
164
+ * {@link nextBeatTime}, {@link lookahead} - is on the audio context's clock,
165
+ * so `AudioOutputClock` converts them to the `performance.now()` timeline
166
+ * without further correction.
167
+ */
168
+ get analysisTime() {
169
+ return this._analysisTime;
170
+ }
171
+ /**
172
+ * Seconds between {@link analysisTime} and the moment the main thread
173
+ * received that state, measured rather than assumed.
174
+ *
175
+ * Covers the analysis hop and the worklet-to-main-thread delivery together,
176
+ * and is quantised to the context's render-quantum boundary, so treat it as
177
+ * a budget figure rather than an exact age. It says nothing about the output
178
+ * path: what a listener hears lags the analysed audio by the output latency
179
+ * on top, which `AudioOutputClock` reports.
180
+ */
181
+ get analysisLatency() {
182
+ return this._analysisLatency;
183
+ }
142
184
  get rms() {
143
185
  return this._rms;
144
186
  }
@@ -260,11 +302,14 @@ var BeatDetector = class {
260
302
  const message = event.data;
261
303
  switch (message.type) {
262
304
  case "state":
305
+ this._analysisTime = message.analysisTime ?? 0;
306
+ this._analysisLatency = Math.max(0, (this._workletNode?.context.currentTime ?? this._analysisTime) - this._analysisTime);
263
307
  this._tempo = message.tempo ?? 0;
264
308
  this._beatPhase = message.beatPhase ?? 0;
265
309
  this._nextBeatTime = message.nextBeatTime ?? 0;
266
310
  this._nextDownbeatTime = message.nextDownbeatTime ?? 0;
267
311
  this._confidence = message.confidence ?? 0;
312
+ this._phaseConfidence = message.phaseConfidence ?? 0;
268
313
  this._gridStability = message.gridStability ?? 0;
269
314
  this._tempoCandidates = Object.freeze(message.tempoCandidates ?? []);
270
315
  this._rms = message.rms ?? 0;
@@ -338,7 +383,7 @@ var BeatDetector = class {
338
383
  return msNode;
339
384
  }
340
385
  const asBus = source;
341
- if (typeof asBus._getOutputNode === "function") return asBus._getOutputNode();
386
+ if (typeof asBus.getOutputNode === "function") return asBus.getOutputNode();
342
387
  const asVoice = source;
343
388
  if ("output" in asVoice && asVoice.output) return asVoice.output;
344
389
  const asNode = source;
@@ -1 +1 @@
1
- {"version":3,"file":"BeatDetector.js","names":["beatDetectorWorkletSource","asStream"],"sources":["../../src/BeatDetector.ts"],"sourcesContent":["import { type AudioBus, getAudioContext, isAudioContextReady, onAudioContextReady, registerAudioWorkletProcessor, Signal, type Voice } from '@codexo/exojs';\n\nimport beatDetectorWorkletSource from './worklets/beat-detector.worklet.ts?worklet';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport type BeatDetectorSource = AudioBus | Voice | MediaStream | AudioNode | null;\n\nexport interface BeatDetectorOptions {\n /** Minimum detectable BPM. Default 50. */\n minBpm?: number;\n /** Maximum detectable BPM. Default 300. */\n maxBpm?: number;\n /** FFT size for onset detection. Default 2048. */\n fftSize?: number;\n /** Hop size in samples between successive FFTs. Default 512. */\n hopSize?: number;\n /**\n * Short tempogram window (seconds) that reacts quickly to a genuine tempo\n * change. Default 2.5. The tracked tempo follows this FAST window only when it\n * disagrees with {@link stableTempoWindowSec} consistently over several\n * analysis hops, so a real DJ drift is tracked without making a steady tempo\n * nervous.\n */\n fastTempoWindowSec?: number;\n /**\n * Long tempogram window (seconds) that holds the tempo grid steady against\n * noise and octave ambiguity. Default 8. Should be ≥ {@link fastTempoWindowSec}\n * and large enough to hold ≳ 2 periods of the slowest tempo; it also sizes the\n * internal flux ring buffer.\n */\n stableTempoWindowSec?: number;\n /**\n * Hops between successive autocorrelation (tempogram) recomputations.\n * Default 15 (~160 ms at 48 kHz with the default 512-sample hop). Lower values\n * react faster to tempo changes at the cost of more CPU.\n */\n acfIntervalHops?: number;\n /**\n * Minimum warm-up (ms) before the first beat may be emitted. Default 400.\n * The detector starts hunting a tempo once this much analysis history exists\n * instead of waiting a full slowest-tempo period, so early {@link BeatInfo}\n * beats (tagged `status: 'provisional'`) arrive with low latency for visual\n * reactivity. A beat is promoted to `status: 'locked'` only once the tempo grid\n * is trustworthy (full analysis window + sustained on-grid tracking). Replaces\n * the former `settlingMs` (default 1500).\n */\n minSettlingMs?: number;\n /**\n * When true (default), early low-confidence beats are emitted tagged\n * `status: 'provisional'` (then promoted to `'locked'`) for snappy visual\n * reactivity. Set false to suppress provisional beats entirely - {@link onBeat}\n * then fires only for `'locked'` beats, matching the pre-provisional behaviour.\n */\n emitProvisionalBeats?: boolean;\n /** Number of mel filterbank bands. Default 24. */\n melBands?: number;\n /**\n * When true (default), the worklet runs parallel 3/4 and 4/4 posteriors and\n * switches active time signature via hysteresis. Set false to lock to 4/4.\n */\n enableTimeSignatureDetection?: boolean;\n /**\n * Optional initial source. Equivalent to constructing then assigning\n * `detector.source = value`; provided for ergonomic one-shot construction.\n * The setter remains usable for runtime source switches.\n */\n source?: BeatDetectorSource;\n /**\n * Half-life in seconds for the {@link BeatDetector.pulse} envelope.\n * Default 0.15 - `pulse` halves every 150ms after each beat.\n */\n pulseHalfLife?: number;\n /**\n * Half-life in seconds for the {@link BeatDetector.barPulse} envelope.\n * Default 0.3 - slower than beat pulse for downbeat-emphasized visuals.\n */\n barPulseHalfLife?: number;\n /**\n * Time window in seconds for {@link BeatDetector.justBeat}. Default 0.03\n * - true for the visual frame(s) within 30ms of a beat onset.\n */\n justBeatWindow?: number;\n}\n\nexport interface BeatInfo {\n /** audioContext.currentTime when the beat occurred. */\n audioTime: number;\n /** BPM at this beat. */\n tempo: number;\n /** Confidence 0..1. */\n confidence: number;\n /** Phase within beat (0 = start). */\n beatPhase: number;\n /** Novelty/onset strength at the beat. */\n energy: number;\n /** Is this beat the first in a bar? */\n isDownbeat: boolean;\n /** Beat position within the bar (1..N). */\n beatInBar: number;\n /**\n * Detection trust level:\n * - `'provisional'` - an early, low-latency beat emitted before the tempo grid\n * is fully settled. Good for visual reactivity (a \"blink\"); may be revised.\n * - `'locked'` - the tempo grid is settled and trustworthy. Safe for\n * sync-critical use. Each stable segment yields exactly one provisional→locked\n * transition.\n */\n status: 'provisional' | 'locked';\n}\n\nexport interface UpcomingBeat {\n audioTime: number;\n tempo: number;\n isDownbeat: boolean;\n beatInBar: number;\n}\n\nexport interface BarInfo {\n audioTime: number;\n tempo: number;\n confidence: number;\n /** Monotonically increasing bar counter since detector start. */\n barNumber: number;\n}\n\nexport interface TimeSignature {\n numerator: number;\n denominator: number;\n}\n\nexport interface TempoCandidate {\n bpm: number;\n /** Peak strength 0..1. */\n score: number;\n}\n\nexport interface BandEnergy {\n low: number;\n mid: number;\n high: number;\n}\n\nconst workletName = 'exojs-beat-detector';\n\n/**\n * Real-time tempo + beat tracker. Splits work between the audio-rendering\n * thread (an AudioWorklet that runs onset detection, tempogram analysis,\n * and parallel 3/4 and 4/4 posterior estimation) and the main thread (this\n * class - receives beats, fires Signals, handles configuration and source\n * routing).\n *\n * Accepts a wide range of {@link BeatDetectorSource}s - a bus, an individual\n * {@link Voice}, a raw MediaStream, or any AudioNode - and exposes a Signal\n * for each notable event:\n * - {@link BeatDetector.onBeat} - every detected beat\n * - {@link BeatDetector.onDownbeat} - first beat of each bar\n * - {@link BeatDetector.onBarStart} - bar boundary\n * - {@link BeatDetector.onTempoChange} - when the tracked BPM changes\n * - {@link BeatDetector.onBeatPredicted} - look-ahead schedule notice\n *\n * Early beats arrive with low latency tagged `status: 'provisional'` (after a\n * short `minSettlingMs` warm-up, default 400 ms) for snappy visual reactivity,\n * then promote to `status: 'locked'` once the tempo grid is trustworthy - a\n * single {@link BeatDetector.onBeat} signal carries both via {@link BeatInfo.status}.\n * Set `emitProvisionalBeats: false` to receive only locked beats. Time-signature\n * detection (3/4 vs 4/4) is on by default; lock to 4/4 by setting\n * `enableTimeSignatureDetection: false`.\n */\nexport class BeatDetector {\n // ---- Signals ----\n public readonly onBeat = new Signal<[BeatInfo]>();\n public readonly onTempoChange = new Signal<[number, number]>();\n public readonly onDownbeat = new Signal<[BeatInfo]>();\n public readonly onBarStart = new Signal<[BarInfo]>();\n public readonly onBeatPredicted = new Signal<[UpcomingBeat]>();\n\n // ---- Options ----\n // enableTimeSignatureDetection not in Required<> since it has a default; keep as full explicit type\n private readonly _options: Required<BeatDetectorOptions>;\n\n // ---- Audio plumbing ----\n private _workletNode: AudioWorkletNode | null = null;\n private _source: BeatDetectorSource = null;\n private _tapSource: AudioNode | null = null;\n private _streamSource: MediaStreamAudioSourceNode | null = null;\n private _ready: Promise<void> | null = null;\n private _pendingSourceSetup: ((ctx: AudioContext) => void) | null = null;\n private readonly _onAudioContextReady = (ctx: AudioContext): void => {\n onAudioContextReady.remove(this._onAudioContextReady);\n this._setup(ctx);\n };\n\n // ---- Cached state from worklet ----\n private _tempo = 0;\n private _beatPhase = 0;\n private _nextBeatTime = 0;\n private _confidence = 0;\n private _gridStability = 0;\n private _tempoCandidates: readonly TempoCandidate[] = [];\n private _rms = 0;\n private _onsetStrength = 0;\n private _bandEnergy: BandEnergy = { low: 0, mid: 0, high: 0 };\n private _barPosition = 1;\n private _barLength = 4;\n private _timeSignature: TimeSignature = { numerator: 4, denominator: 4 };\n private _nextDownbeatTime = 0;\n private _lookahead: readonly UpcomingBeat[] = Object.freeze([]);\n\n /**\n * Half-life in seconds for the {@link pulse} envelope. Mutable; default 0.15.\n * Smaller values give a snappier pulse, larger values a longer afterglow.\n */\n public pulseHalfLife: number;\n\n /** Half-life for the {@link barPulse} envelope. Mutable; default 0.3. */\n public barPulseHalfLife: number;\n\n /** Time window for {@link justBeat}. Mutable; default 0.03 (30ms). */\n public justBeatWindow: number;\n\n public constructor(options?: BeatDetectorOptions) {\n this._options = {\n minBpm: options?.minBpm ?? 50,\n maxBpm: options?.maxBpm ?? 300,\n fftSize: options?.fftSize ?? 2048,\n hopSize: options?.hopSize ?? 512,\n fastTempoWindowSec: options?.fastTempoWindowSec ?? 2.5,\n stableTempoWindowSec: options?.stableTempoWindowSec ?? 8,\n acfIntervalHops: options?.acfIntervalHops ?? 15,\n minSettlingMs: options?.minSettlingMs ?? 400,\n emitProvisionalBeats: options?.emitProvisionalBeats ?? true,\n melBands: options?.melBands ?? 24,\n enableTimeSignatureDetection: options?.enableTimeSignatureDetection ?? true,\n // Visual-state options aren't part of worklet config; cached in the public\n // fields below but kept in the Required<> shape for type completeness.\n source: options?.source ?? null,\n pulseHalfLife: options?.pulseHalfLife ?? 0.15,\n barPulseHalfLife: options?.barPulseHalfLife ?? 0.3,\n justBeatWindow: options?.justBeatWindow ?? 0.03,\n };\n\n this.pulseHalfLife = this._options.pulseHalfLife;\n this.barPulseHalfLife = this._options.barPulseHalfLife;\n this.justBeatWindow = this._options.justBeatWindow;\n\n if (isAudioContextReady()) {\n this._setup(getAudioContext());\n } else {\n onAudioContextReady.add(this._onAudioContextReady);\n }\n\n if (options?.source !== undefined && options.source !== null) {\n this.source = options.source;\n }\n }\n\n // -----------------------------------------------------------------------\n // Source setter (polymorphic tap)\n // -----------------------------------------------------------------------\n\n public get source(): BeatDetectorSource {\n return this._source;\n }\n\n public set source(value: BeatDetectorSource) {\n if (value === this._source) return;\n\n this._disconnectTap();\n this._source = value;\n\n if (value === null) return;\n\n if (isAudioContextReady()) {\n this._pendingSourceSetup = null;\n this._connectSource(value, getAudioContext());\n } else {\n if (this._pendingSourceSetup !== null) {\n onAudioContextReady.remove(this._pendingSourceSetup);\n }\n\n const handler = (ctx: AudioContext): void => {\n onAudioContextReady.remove(handler);\n this._pendingSourceSetup = null;\n this._connectSource(value, ctx);\n };\n\n this._pendingSourceSetup = handler;\n onAudioContextReady.add(handler);\n }\n }\n\n // -----------------------------------------------------------------------\n // Ready promise\n // -----------------------------------------------------------------------\n\n public get ready(): Promise<void> {\n return this._ready ?? Promise.resolve();\n }\n\n // -----------------------------------------------------------------------\n // Stage 1 state accessors\n // -----------------------------------------------------------------------\n\n public get tempo(): number {\n return this._tempo;\n }\n public get beatPhase(): number {\n return this._beatPhase;\n }\n public get nextBeatTime(): number {\n return this._nextBeatTime;\n }\n public get confidence(): number {\n return this._confidence;\n }\n public get gridStability(): number {\n return this._gridStability;\n }\n public get rms(): number {\n return this._rms;\n }\n public get onsetStrength(): number {\n return this._onsetStrength;\n }\n public get bandEnergy(): BandEnergy {\n return this._bandEnergy;\n }\n\n public get tempoCandidates(): readonly TempoCandidate[] {\n return this._tempoCandidates;\n }\n\n // -----------------------------------------------------------------------\n // Stage 2 state accessors\n // -----------------------------------------------------------------------\n\n public get barPosition(): number {\n return this._barPosition;\n }\n public get barLength(): number {\n return this._barLength;\n }\n public get timeSignature(): TimeSignature {\n return this._timeSignature;\n }\n public get nextDownbeatTime(): number {\n return this._nextDownbeatTime;\n }\n\n public get lookahead(): readonly UpcomingBeat[] {\n return this._lookahead;\n }\n\n // -----------------------------------------------------------------------\n // Visual derived state - pure getters for per-frame polling\n // -----------------------------------------------------------------------\n\n /**\n * Seconds elapsed since the most recent beat, derived from {@link beatPhase}\n * and {@link tempo}. Returns 0 when the detector hasn't locked yet.\n */\n public get secondsSinceLastBeat(): number {\n if (this._tempo === 0) return 0;\n return this._beatPhase * (60 / this._tempo);\n }\n\n /**\n * 0..1 envelope, peaks at 1.0 the moment a beat fires and halves every\n * {@link pulseHalfLife} seconds. Drives \"pulse on the beat\" visuals\n * with a single multiplication: `sprite.scale = 1 + clock.pulse * 0.3`.\n */\n public get pulse(): number {\n if (this._tempo === 0) return 0;\n return Math.pow(0.5, this.secondsSinceLastBeat / this.pulseHalfLife);\n }\n\n /**\n * Like {@link pulse} but resets on downbeats and decays per\n * {@link barPulseHalfLife}. Useful for emphasizing the first beat of\n * each bar (e.g. brighter flash on \"1\" vs \"2,3,4\").\n */\n public get barPulse(): number {\n if (this._tempo === 0 || this._barLength === 0) return 0;\n const secondsPerBeat = 60 / this._tempo;\n const lastDownbeat = this._nextDownbeatTime - this._barLength * secondsPerBeat;\n const elapsed = Math.max(0, getAudioContext().currentTime - lastDownbeat);\n return Math.pow(0.5, elapsed / this.barPulseHalfLife);\n }\n\n /**\n * True for the visual frame(s) within {@link justBeatWindow} seconds of\n * a beat onset. Use for one-shot triggers (strobe flash, particle burst,\n * sample retrigger). Default window 30ms covers a typical 60fps frame.\n */\n public get justBeat(): boolean {\n return this._tempo > 0 && this.secondsSinceLastBeat < this.justBeatWindow;\n }\n\n /**\n * Phase 0..1 within a subdivision of the current beat. `division` is the\n * number of subdivisions per beat: 2 for 8th notes, 4 for 16th notes,\n * 3 for triplets. Use to drive sub-beat-resolution effects:\n *\n * const sixteenth = clock.subdivisionPhase(4);\n * if (sixteenth < 0.05) flash();\n */\n public subdivisionPhase(division: number): number {\n if (!Number.isFinite(division) || division <= 0) return 0;\n return (this._beatPhase * division) % 1;\n }\n\n // -----------------------------------------------------------------------\n // Lifecycle\n // -----------------------------------------------------------------------\n\n public destroy(): void {\n onAudioContextReady.remove(this._onAudioContextReady);\n\n if (this._pendingSourceSetup !== null) {\n onAudioContextReady.remove(this._pendingSourceSetup);\n this._pendingSourceSetup = null;\n }\n this._disconnectTap();\n this._workletNode?.disconnect();\n this._workletNode = null;\n this._ready = null;\n this.onBeat.clear();\n this.onTempoChange.clear();\n this.onDownbeat.clear();\n this.onBarStart.clear();\n this.onBeatPredicted.clear();\n }\n\n // -----------------------------------------------------------------------\n // Private helpers - setup\n // -----------------------------------------------------------------------\n\n private _setup(audioContext: AudioContext): void {\n const opts = this._options;\n this._ready = registerAudioWorkletProcessor(audioContext, workletName, beatDetectorWorkletSource).then(() => {\n const node = new AudioWorkletNode(audioContext, workletName, {\n numberOfInputs: 1,\n numberOfOutputs: 0,\n processorOptions: {\n fftSize: opts.fftSize,\n hopSize: opts.hopSize,\n minBpm: opts.minBpm,\n maxBpm: opts.maxBpm,\n melBands: opts.melBands,\n minSettlingMs: opts.minSettlingMs,\n emitProvisionalBeats: opts.emitProvisionalBeats,\n fastTempoWindowSec: opts.fastTempoWindowSec,\n stableTempoWindowSec: opts.stableTempoWindowSec,\n acfIntervalHops: opts.acfIntervalHops,\n enableTimeSignatureDetection: opts.enableTimeSignatureDetection,\n },\n });\n\n this._workletNode = node;\n node.port.onmessage = this._onWorkletMessage.bind(this);\n\n // If a source was set before worklet was ready, connect it now.\n if (this._source !== null) {\n this._connectSource(this._source, audioContext);\n }\n });\n }\n\n private _onWorkletMessage(event: MessageEvent): void {\n const message = event.data as Record<string, unknown>;\n switch (message.type) {\n case 'state':\n this._tempo = (message.tempo as number) ?? 0;\n this._beatPhase = (message.beatPhase as number) ?? 0;\n this._nextBeatTime = (message.nextBeatTime as number) ?? 0;\n this._nextDownbeatTime = (message.nextDownbeatTime as number) ?? 0;\n this._confidence = (message.confidence as number) ?? 0;\n this._gridStability = (message.gridStability as number) ?? 0;\n this._tempoCandidates = Object.freeze((message.tempoCandidates as TempoCandidate[]) ?? []);\n this._rms = (message.rms as number) ?? 0;\n this._onsetStrength = (message.onsetStrength as number) ?? 0;\n this._bandEnergy = (message.bandEnergy as BandEnergy) ?? { low: 0, mid: 0, high: 0 };\n this._barPosition = (message.barPosition as number) ?? 1;\n this._barLength = (message.barLength as number) ?? 4;\n this._timeSignature = (message.timeSignature as TimeSignature) ?? { numerator: 4, denominator: 4 };\n {\n const lookahead = (message.lookahead as UpcomingBeat[]) ?? [];\n this._lookahead = Object.freeze(lookahead);\n if (lookahead.length > 0) {\n this.onBeatPredicted.dispatch(lookahead[0]!);\n }\n }\n break;\n\n case 'beat': {\n const bi: BeatInfo = {\n audioTime: message.audioTime as number,\n tempo: message.tempo as number,\n confidence: message.confidence as number,\n beatPhase: message.beatPhase as number,\n energy: message.energy as number,\n isDownbeat: message.isDownbeat as boolean,\n beatInBar: message.beatInBar as number,\n status: (message.status as 'provisional' | 'locked' | undefined) ?? 'locked',\n };\n this.onBeat.dispatch(bi);\n if (bi.isDownbeat) this.onDownbeat.dispatch(bi);\n break;\n }\n\n case 'tempoChange':\n this.onTempoChange.dispatch(message.newTempo as number, message.oldTempo as number);\n break;\n\n case 'barStart': {\n const info: BarInfo = {\n audioTime: message.audioTime as number,\n tempo: message.tempo as number,\n confidence: message.confidence as number,\n barNumber: message.barNumber as number,\n };\n this.onBarStart.dispatch(info);\n break;\n }\n }\n }\n\n // -----------------------------------------------------------------------\n // Private helpers - source tap\n // -----------------------------------------------------------------------\n\n private _connectSource(source: BeatDetectorSource, audioContext: AudioContext): void {\n if (!this._workletNode) return;\n\n const tap = this._resolveToAudioNode(source, audioContext);\n if (!tap) {\n this._deferConnectionViaBus(source);\n return;\n }\n\n this._tapSource = tap;\n tap.connect(this._workletNode, 0, 0);\n }\n\n private _resolveToAudioNode(source: BeatDetectorSource, audioContext: AudioContext): AudioNode | null {\n if (source === null) return null;\n\n // MediaStream - duck-type via getTracks\n const asStream = source as Partial<{ getTracks: unknown }>;\n if (typeof asStream.getTracks === 'function') {\n if (this._streamSource) {\n this._streamSource.disconnect();\n this._streamSource = null;\n }\n const msNode = audioContext.createMediaStreamSource(source as MediaStream);\n this._streamSource = msNode;\n return msNode;\n }\n\n // AudioBus - has _getOutputNode (checked before raw AudioNode)\n const asBus = source as Partial<{ _getOutputNode: () => AudioNode | null }>;\n if (typeof asBus._getOutputNode === 'function') {\n return asBus._getOutputNode();\n }\n\n // Voice - tap its output node\n const asVoice = source as Partial<{ output: AudioNode }>;\n if ('output' in asVoice && asVoice.output) {\n return asVoice.output;\n }\n\n // Raw AudioNode - duck-type: has connect & disconnect\n const asNode = source as Partial<{ connect: unknown; disconnect: unknown }>;\n if (typeof asNode.connect === 'function' && typeof asNode.disconnect === 'function') {\n return source as unknown as AudioNode;\n }\n\n return null;\n }\n\n private _deferConnectionViaBus(source: BeatDetectorSource): void {\n const asBus = source as Partial<{ onceSetup: (callback: () => void) => void }>;\n if (typeof asBus.onceSetup === 'function') {\n asBus.onceSetup(() => {\n if (this._source === source && this._workletNode && isAudioContextReady()) {\n this._connectSource(source, getAudioContext());\n }\n });\n return;\n }\n\n onAudioContextReady.once(() => {\n if (this._source === source && this._workletNode && isAudioContextReady()) {\n this._connectSource(source, getAudioContext());\n }\n });\n }\n\n private _disconnectTap(): void {\n if (this._tapSource && this._workletNode) {\n try {\n this._tapSource.disconnect(this._workletNode);\n } catch {\n // Ignore\n }\n }\n this._tapSource = null;\n\n if (this._streamSource) {\n this._streamSource.disconnect();\n this._streamSource = null;\n }\n }\n}\n"],"mappings":";;;;AAiJA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;AA0BpB,IAAa,eAAb,MAA0B;CAExB,AAAgB,SAAS,IAAI,OAAmB;CAChD,AAAgB,gBAAgB,IAAI,OAAyB;CAC7D,AAAgB,aAAa,IAAI,OAAmB;CACpD,AAAgB,aAAa,IAAI,OAAkB;CACnD,AAAgB,kBAAkB,IAAI,OAAuB;CAI7D,AAAiB;CAGjB,AAAQ,eAAwC;CAChD,AAAQ,UAA8B;CACtC,AAAQ,aAA+B;CACvC,AAAQ,gBAAmD;CAC3D,AAAQ,SAA+B;CACvC,AAAQ,sBAA4D;CACpE,AAAiB,wBAAwB,QAA4B;EACnE,oBAAoB,OAAO,KAAK,oBAAoB;EACpD,KAAK,OAAO,GAAG;CACjB;CAGA,AAAQ,SAAS;CACjB,AAAQ,aAAa;CACrB,AAAQ,gBAAgB;CACxB,AAAQ,cAAc;CACtB,AAAQ,iBAAiB;CACzB,AAAQ,mBAA8C,CAAC;CACvD,AAAQ,OAAO;CACf,AAA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K,gBAAgB,oBAAoB,GACtE,KAAK,eAAe,QAAQ,gBAAgB,CAAC;EAEjD,CAAC;CACH;CAEA,AAAQ,iBAAuB;EAC7B,IAAI,KAAK,cAAc,KAAK,cAC1B,IAAI;GACF,KAAK,WAAW,WAAW,KAAK,YAAY;EAC9C,QAAQ,CAER;EAEF,KAAK,aAAa;EAElB,IAAI,KAAK,eAAe;GACtB,KAAK,cAAc,WAAW;GAC9B,KAAK,gBAAgB;EACvB;CACF;AACF"}
1
+ {"version":3,"file":"BeatDetector.js","names":["beatDetectorWorkletSource","asStream"],"sources":["../../src/BeatDetector.ts"],"sourcesContent":["import { type AudioBus, getAudioContext, isAudioContextReady, onAudioContextReady, registerAudioWorkletProcessor, Signal, type Voice } from '@codexo/exojs';\n\nimport beatDetectorWorkletSource from './worklets/beat-detector.worklet.ts?worklet';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport type BeatDetectorSource = AudioBus | Voice | MediaStream | AudioNode | null;\n\nexport interface BeatDetectorOptions {\n /** Minimum detectable BPM. Default 50. */\n minBpm?: number;\n /** Maximum detectable BPM. Default 300. */\n maxBpm?: number;\n /** FFT size for onset detection. Default 2048. */\n fftSize?: number;\n /** Hop size in samples between successive FFTs. Default 512. */\n hopSize?: number;\n /**\n * Short tempogram window (seconds) that reacts quickly to a genuine tempo\n * change. Default 2.5. The tracked tempo follows this FAST window only when it\n * disagrees with {@link stableTempoWindowSec} consistently over several\n * analysis hops, so a real DJ drift is tracked without making a steady tempo\n * nervous.\n */\n fastTempoWindowSec?: number;\n /**\n * Long tempogram window (seconds) that holds the tempo grid steady against\n * noise and octave ambiguity. Default 8. Should be ≥ {@link fastTempoWindowSec}\n * and large enough to hold ≳ 2 periods of the slowest tempo; it also sizes the\n * internal flux ring buffer.\n */\n stableTempoWindowSec?: number;\n /**\n * Hops between successive autocorrelation (tempogram) recomputations.\n * Default 15 (~160 ms at 48 kHz with the default 512-sample hop). Lower values\n * react faster to tempo changes at the cost of more CPU.\n */\n acfIntervalHops?: number;\n /**\n * Minimum warm-up (ms) before the first beat may be emitted. Default 400.\n * The detector starts hunting a tempo once this much analysis history exists\n * instead of waiting a full slowest-tempo period, so early {@link BeatInfo}\n * beats (tagged `status: 'provisional'`) arrive with low latency for visual\n * reactivity. A beat is promoted to `status: 'locked'` only once the tempo grid\n * is trustworthy (full analysis window + sustained on-grid tracking). Replaces\n * the former `settlingMs` (default 1500).\n */\n minSettlingMs?: number;\n /**\n * When true (default), early low-confidence beats are emitted tagged\n * `status: 'provisional'` (then promoted to `'locked'`) for snappy visual\n * reactivity. Set false to suppress provisional beats entirely - {@link onBeat}\n * then fires only for `'locked'` beats, matching the pre-provisional behaviour.\n */\n emitProvisionalBeats?: boolean;\n /** Number of mel filterbank bands. Default 24. */\n melBands?: number;\n /**\n * When true (default), the worklet runs parallel 3/4 and 4/4 posteriors and\n * switches active time signature via hysteresis. Set false to lock to 4/4.\n */\n enableTimeSignatureDetection?: boolean;\n /**\n * Optional initial source. Equivalent to constructing then assigning\n * `detector.source = value`; provided for ergonomic one-shot construction.\n * The setter remains usable for runtime source switches.\n */\n source?: BeatDetectorSource;\n /**\n * Half-life in seconds for the {@link BeatDetector.pulse} envelope.\n * Default 0.15 - `pulse` halves every 150ms after each beat.\n */\n pulseHalfLife?: number;\n /**\n * Half-life in seconds for the {@link BeatDetector.barPulse} envelope.\n * Default 0.3 - slower than beat pulse for downbeat-emphasized visuals.\n */\n barPulseHalfLife?: number;\n /**\n * Time window in seconds for {@link BeatDetector.justBeat}. Default 0.03\n * - true for the visual frame(s) within 30ms of a beat onset.\n */\n justBeatWindow?: number;\n}\n\nexport interface BeatInfo {\n /** audioContext.currentTime when the beat occurred. */\n audioTime: number;\n /** BPM at this beat. */\n tempo: number;\n /** Confidence 0..1. */\n confidence: number;\n /** Phase within beat (0 = start). */\n beatPhase: number;\n /** Novelty/onset strength at the beat. */\n energy: number;\n /** Is this beat the first in a bar? */\n isDownbeat: boolean;\n /** Beat position within the bar (1..N). */\n beatInBar: number;\n /**\n * Detection trust level:\n * - `'provisional'` - an early, low-latency beat emitted before the tempo grid\n * is fully settled. Good for visual reactivity (a \"blink\"); may be revised.\n * - `'locked'` - the tempo grid is settled and trustworthy. Safe for\n * sync-critical use. Each stable segment yields exactly one provisional→locked\n * transition.\n */\n status: 'provisional' | 'locked';\n}\n\nexport interface UpcomingBeat {\n audioTime: number;\n tempo: number;\n isDownbeat: boolean;\n beatInBar: number;\n}\n\nexport interface BarInfo {\n audioTime: number;\n tempo: number;\n confidence: number;\n /** Monotonically increasing bar counter since detector start. */\n barNumber: number;\n}\n\nexport interface TimeSignature {\n numerator: number;\n denominator: number;\n}\n\nexport interface TempoCandidate {\n bpm: number;\n /** Peak strength 0..1. */\n score: number;\n}\n\nexport interface BandEnergy {\n low: number;\n mid: number;\n high: number;\n}\n\nconst workletName = 'exojs-beat-detector';\n\n/**\n * Real-time tempo + beat tracker. Splits work between the audio-rendering\n * thread (an AudioWorklet that runs onset detection, tempogram analysis,\n * and parallel 3/4 and 4/4 posterior estimation) and the main thread (this\n * class - receives beats, fires Signals, handles configuration and source\n * routing).\n *\n * Accepts a wide range of {@link BeatDetectorSource}s - a bus, an individual\n * {@link Voice}, a raw MediaStream, or any AudioNode - and exposes a Signal\n * for each notable event:\n * - {@link BeatDetector.onBeat} - every detected beat\n * - {@link BeatDetector.onDownbeat} - first beat of each bar\n * - {@link BeatDetector.onBarStart} - bar boundary\n * - {@link BeatDetector.onTempoChange} - when the tracked BPM changes\n * - {@link BeatDetector.onBeatPredicted} - look-ahead schedule notice\n *\n * Early beats arrive with low latency tagged `status: 'provisional'` (after a\n * short `minSettlingMs` warm-up, default 400 ms) for snappy visual reactivity,\n * then promote to `status: 'locked'` once the tempo grid is trustworthy - a\n * single {@link BeatDetector.onBeat} signal carries both via {@link BeatInfo.status}.\n * Set `emitProvisionalBeats: false` to receive only locked beats. Time-signature\n * detection (3/4 vs 4/4) is on by default; lock to 4/4 by setting\n * `enableTimeSignatureDetection: false`.\n */\nexport class BeatDetector {\n // ---- Signals ----\n public readonly onBeat = new Signal<[BeatInfo]>();\n public readonly onTempoChange = new Signal<[number, number]>();\n public readonly onDownbeat = new Signal<[BeatInfo]>();\n public readonly onBarStart = new Signal<[BarInfo]>();\n public readonly onBeatPredicted = new Signal<[UpcomingBeat]>();\n\n // ---- Options ----\n // enableTimeSignatureDetection not in Required<> since it has a default; keep as full explicit type\n private readonly _options: Required<BeatDetectorOptions>;\n\n // ---- Audio plumbing ----\n private _workletNode: AudioWorkletNode | null = null;\n private _source: BeatDetectorSource = null;\n private _tapSource: AudioNode | null = null;\n private _streamSource: MediaStreamAudioSourceNode | null = null;\n private _ready: Promise<void> | null = null;\n private _pendingSourceSetup: ((ctx: AudioContext) => void) | null = null;\n private readonly _onAudioContextReady = (ctx: AudioContext): void => {\n onAudioContextReady.remove(this._onAudioContextReady);\n this._setup(ctx);\n };\n\n // ---- Cached state from worklet ----\n private _tempo = 0;\n private _beatPhase = 0;\n private _nextBeatTime = 0;\n private _confidence = 0;\n private _phaseConfidence = 0;\n private _gridStability = 0;\n private _analysisTime = 0;\n private _analysisLatency = 0;\n private _tempoCandidates: readonly TempoCandidate[] = [];\n private _rms = 0;\n private _onsetStrength = 0;\n private _bandEnergy: BandEnergy = { low: 0, mid: 0, high: 0 };\n private _barPosition = 1;\n private _barLength = 4;\n private _timeSignature: TimeSignature = { numerator: 4, denominator: 4 };\n private _nextDownbeatTime = 0;\n private _lookahead: readonly UpcomingBeat[] = Object.freeze([]);\n\n /**\n * Half-life in seconds for the {@link pulse} envelope. Mutable; default 0.15.\n * Smaller values give a snappier pulse, larger values a longer afterglow.\n */\n public pulseHalfLife: number;\n\n /** Half-life for the {@link barPulse} envelope. Mutable; default 0.3. */\n public barPulseHalfLife: number;\n\n /** Time window for {@link justBeat}. Mutable; default 0.03 (30ms). */\n public justBeatWindow: number;\n\n public constructor(options?: BeatDetectorOptions) {\n this._options = {\n minBpm: options?.minBpm ?? 50,\n maxBpm: options?.maxBpm ?? 300,\n fftSize: options?.fftSize ?? 2048,\n hopSize: options?.hopSize ?? 512,\n fastTempoWindowSec: options?.fastTempoWindowSec ?? 2.5,\n stableTempoWindowSec: options?.stableTempoWindowSec ?? 8,\n acfIntervalHops: options?.acfIntervalHops ?? 15,\n minSettlingMs: options?.minSettlingMs ?? 400,\n emitProvisionalBeats: options?.emitProvisionalBeats ?? true,\n melBands: options?.melBands ?? 24,\n enableTimeSignatureDetection: options?.enableTimeSignatureDetection ?? true,\n // Visual-state options aren't part of worklet config; cached in the public\n // fields below but kept in the Required<> shape for type completeness.\n source: options?.source ?? null,\n pulseHalfLife: options?.pulseHalfLife ?? 0.15,\n barPulseHalfLife: options?.barPulseHalfLife ?? 0.3,\n justBeatWindow: options?.justBeatWindow ?? 0.03,\n };\n\n this.pulseHalfLife = this._options.pulseHalfLife;\n this.barPulseHalfLife = this._options.barPulseHalfLife;\n this.justBeatWindow = this._options.justBeatWindow;\n\n if (isAudioContextReady()) {\n this._setup(getAudioContext());\n } else {\n onAudioContextReady.add(this._onAudioContextReady);\n }\n\n if (options?.source !== undefined && options.source !== null) {\n this.source = options.source;\n }\n }\n\n // -----------------------------------------------------------------------\n // Source setter (polymorphic tap)\n // -----------------------------------------------------------------------\n\n public get source(): BeatDetectorSource {\n return this._source;\n }\n\n public set source(value: BeatDetectorSource) {\n if (value === this._source) return;\n\n this._disconnectTap();\n this._source = value;\n\n if (value === null) return;\n\n if (isAudioContextReady()) {\n this._pendingSourceSetup = null;\n this._connectSource(value, getAudioContext());\n } else {\n if (this._pendingSourceSetup !== null) {\n onAudioContextReady.remove(this._pendingSourceSetup);\n }\n\n const handler = (ctx: AudioContext): void => {\n onAudioContextReady.remove(handler);\n this._pendingSourceSetup = null;\n this._connectSource(value, ctx);\n };\n\n this._pendingSourceSetup = handler;\n onAudioContextReady.add(handler);\n }\n }\n\n // -----------------------------------------------------------------------\n // Ready promise\n // -----------------------------------------------------------------------\n\n public get ready(): Promise<void> {\n return this._ready ?? Promise.resolve();\n }\n\n // -----------------------------------------------------------------------\n // Stage 1 state accessors\n // -----------------------------------------------------------------------\n\n public get tempo(): number {\n return this._tempo;\n }\n public get beatPhase(): number {\n return this._beatPhase;\n }\n public get nextBeatTime(): number {\n return this._nextBeatTime;\n }\n public get confidence(): number {\n return this._confidence;\n }\n\n /**\n * How well recent onsets support the beat grid's phase, 0 to 1, or 0 before\n * the grid locks.\n *\n * Distinct from {@link confidence}, which reports how sure the detector is of\n * the tempo. A metronomic loop at a wrong-by-an-octave tempo reads high\n * confidence and high phase confidence; a rubato passage at a known tempo\n * reads high confidence and low phase confidence. Gate anything that must\n * land exactly on the beat - a scored hit, a quantised trigger - on this\n * rather than on {@link confidence}.\n */\n public get phaseConfidence(): number {\n return this._phaseConfidence;\n }\n\n public get gridStability(): number {\n return this._gridStability;\n }\n\n /**\n * The `AudioContext.currentTime` of the newest sample the current state\n * describes. 0 until the first state message arrives.\n *\n * Every timestamp this detector reports - this one, {@link BeatInfo.audioTime},\n * {@link nextBeatTime}, {@link lookahead} - is on the audio context's clock,\n * so `AudioOutputClock` converts them to the `performance.now()` timeline\n * without further correction.\n */\n public get analysisTime(): number {\n return this._analysisTime;\n }\n\n /**\n * Seconds between {@link analysisTime} and the moment the main thread\n * received that state, measured rather than assumed.\n *\n * Covers the analysis hop and the worklet-to-main-thread delivery together,\n * and is quantised to the context's render-quantum boundary, so treat it as\n * a budget figure rather than an exact age. It says nothing about the output\n * path: what a listener hears lags the analysed audio by the output latency\n * on top, which `AudioOutputClock` reports.\n */\n public get analysisLatency(): number {\n return this._analysisLatency;\n }\n public get rms(): number {\n return this._rms;\n }\n public get onsetStrength(): number {\n return this._onsetStrength;\n }\n public get bandEnergy(): BandEnergy {\n return this._bandEnergy;\n }\n\n public get tempoCandidates(): readonly TempoCandidate[] {\n return this._tempoCandidates;\n }\n\n // -----------------------------------------------------------------------\n // Stage 2 state accessors\n // -----------------------------------------------------------------------\n\n public get barPosition(): number {\n return this._barPosition;\n }\n public get barLength(): number {\n return this._barLength;\n }\n public get timeSignature(): TimeSignature {\n return this._timeSignature;\n }\n public get nextDownbeatTime(): number {\n return this._nextDownbeatTime;\n }\n\n public get lookahead(): readonly UpcomingBeat[] {\n return this._lookahead;\n }\n\n // -----------------------------------------------------------------------\n // Visual derived state - pure getters for per-frame polling\n // -----------------------------------------------------------------------\n\n /**\n * Seconds elapsed since the most recent beat, derived from {@link beatPhase}\n * and {@link tempo}. Returns 0 when the detector hasn't locked yet.\n */\n public get secondsSinceLastBeat(): number {\n if (this._tempo === 0) return 0;\n return this._beatPhase * (60 / this._tempo);\n }\n\n /**\n * 0..1 envelope, peaks at 1.0 the moment a beat fires and halves every\n * {@link pulseHalfLife} seconds. Drives \"pulse on the beat\" visuals\n * with a single multiplication: `sprite.scale = 1 + clock.pulse * 0.3`.\n */\n public get pulse(): number {\n if (this._tempo === 0) return 0;\n return Math.pow(0.5, this.secondsSinceLastBeat / this.pulseHalfLife);\n }\n\n /**\n * Like {@link pulse} but resets on downbeats and decays per\n * {@link barPulseHalfLife}. Useful for emphasizing the first beat of\n * each bar (e.g. brighter flash on \"1\" vs \"2,3,4\").\n */\n public get barPulse(): number {\n if (this._tempo === 0 || this._barLength === 0) return 0;\n const secondsPerBeat = 60 / this._tempo;\n const lastDownbeat = this._nextDownbeatTime - this._barLength * secondsPerBeat;\n const elapsed = Math.max(0, getAudioContext().currentTime - lastDownbeat);\n return Math.pow(0.5, elapsed / this.barPulseHalfLife);\n }\n\n /**\n * True for the visual frame(s) within {@link justBeatWindow} seconds of\n * a beat onset. Use for one-shot triggers (strobe flash, particle burst,\n * sample retrigger). Default window 30ms covers a typical 60fps frame.\n */\n public get justBeat(): boolean {\n return this._tempo > 0 && this.secondsSinceLastBeat < this.justBeatWindow;\n }\n\n /**\n * Phase 0..1 within a subdivision of the current beat. `division` is the\n * number of subdivisions per beat: 2 for 8th notes, 4 for 16th notes,\n * 3 for triplets. Use to drive sub-beat-resolution effects:\n *\n * const sixteenth = clock.subdivisionPhase(4);\n * if (sixteenth < 0.05) flash();\n */\n public subdivisionPhase(division: number): number {\n if (!Number.isFinite(division) || division <= 0) return 0;\n return (this._beatPhase * division) % 1;\n }\n\n // -----------------------------------------------------------------------\n // Lifecycle\n // -----------------------------------------------------------------------\n\n public destroy(): void {\n onAudioContextReady.remove(this._onAudioContextReady);\n\n if (this._pendingSourceSetup !== null) {\n onAudioContextReady.remove(this._pendingSourceSetup);\n this._pendingSourceSetup = null;\n }\n this._disconnectTap();\n this._workletNode?.disconnect();\n this._workletNode = null;\n this._ready = null;\n this.onBeat.clear();\n this.onTempoChange.clear();\n this.onDownbeat.clear();\n this.onBarStart.clear();\n this.onBeatPredicted.clear();\n }\n\n // -----------------------------------------------------------------------\n // Private helpers - setup\n // -----------------------------------------------------------------------\n\n private _setup(audioContext: AudioContext): void {\n const opts = this._options;\n this._ready = registerAudioWorkletProcessor(audioContext, workletName, beatDetectorWorkletSource).then(() => {\n const node = new AudioWorkletNode(audioContext, workletName, {\n numberOfInputs: 1,\n numberOfOutputs: 0,\n processorOptions: {\n fftSize: opts.fftSize,\n hopSize: opts.hopSize,\n minBpm: opts.minBpm,\n maxBpm: opts.maxBpm,\n melBands: opts.melBands,\n minSettlingMs: opts.minSettlingMs,\n emitProvisionalBeats: opts.emitProvisionalBeats,\n fastTempoWindowSec: opts.fastTempoWindowSec,\n stableTempoWindowSec: opts.stableTempoWindowSec,\n acfIntervalHops: opts.acfIntervalHops,\n enableTimeSignatureDetection: opts.enableTimeSignatureDetection,\n },\n });\n\n this._workletNode = node;\n node.port.onmessage = this._onWorkletMessage.bind(this);\n\n // If a source was set before worklet was ready, connect it now.\n if (this._source !== null) {\n this._connectSource(this._source, audioContext);\n }\n });\n }\n\n private _onWorkletMessage(event: MessageEvent): void {\n const message = event.data as Record<string, unknown>;\n switch (message.type) {\n case 'state':\n this._analysisTime = (message.analysisTime as number) ?? 0;\n this._analysisLatency = Math.max(0, (this._workletNode?.context.currentTime ?? this._analysisTime) - this._analysisTime);\n this._tempo = (message.tempo as number) ?? 0;\n this._beatPhase = (message.beatPhase as number) ?? 0;\n this._nextBeatTime = (message.nextBeatTime as number) ?? 0;\n this._nextDownbeatTime = (message.nextDownbeatTime as number) ?? 0;\n this._confidence = (message.confidence as number) ?? 0;\n this._phaseConfidence = (message.phaseConfidence as number) ?? 0;\n this._gridStability = (message.gridStability as number) ?? 0;\n this._tempoCandidates = Object.freeze((message.tempoCandidates as TempoCandidate[]) ?? []);\n this._rms = (message.rms as number) ?? 0;\n this._onsetStrength = (message.onsetStrength as number) ?? 0;\n this._bandEnergy = (message.bandEnergy as BandEnergy) ?? { low: 0, mid: 0, high: 0 };\n this._barPosition = (message.barPosition as number) ?? 1;\n this._barLength = (message.barLength as number) ?? 4;\n this._timeSignature = (message.timeSignature as TimeSignature) ?? { numerator: 4, denominator: 4 };\n {\n const lookahead = (message.lookahead as UpcomingBeat[]) ?? [];\n this._lookahead = Object.freeze(lookahead);\n if (lookahead.length > 0) {\n this.onBeatPredicted.dispatch(lookahead[0]!);\n }\n }\n break;\n\n case 'beat': {\n const bi: BeatInfo = {\n audioTime: message.audioTime as number,\n tempo: message.tempo as number,\n confidence: message.confidence as number,\n beatPhase: message.beatPhase as number,\n energy: message.energy as number,\n isDownbeat: message.isDownbeat as boolean,\n beatInBar: message.beatInBar as number,\n status: (message.status as 'provisional' | 'locked' | undefined) ?? 'locked',\n };\n this.onBeat.dispatch(bi);\n if (bi.isDownbeat) this.onDownbeat.dispatch(bi);\n break;\n }\n\n case 'tempoChange':\n this.onTempoChange.dispatch(message.newTempo as number, message.oldTempo as number);\n break;\n\n case 'barStart': {\n const info: BarInfo = {\n audioTime: message.audioTime as number,\n tempo: message.tempo as number,\n confidence: message.confidence as number,\n barNumber: message.barNumber as number,\n };\n this.onBarStart.dispatch(info);\n break;\n }\n }\n }\n\n // -----------------------------------------------------------------------\n // Private helpers - source tap\n // -----------------------------------------------------------------------\n\n private _connectSource(source: BeatDetectorSource, audioContext: AudioContext): void {\n if (!this._workletNode) return;\n\n const tap = this._resolveToAudioNode(source, audioContext);\n if (!tap) {\n this._deferConnectionViaBus(source);\n return;\n }\n\n this._tapSource = tap;\n tap.connect(this._workletNode, 0, 0);\n }\n\n private _resolveToAudioNode(source: BeatDetectorSource, audioContext: AudioContext): AudioNode | null {\n if (source === null) return null;\n\n // MediaStream - duck-type via getTracks\n const asStream = source as Partial<{ getTracks: unknown }>;\n if (typeof asStream.getTracks === 'function') {\n if (this._streamSource) {\n this._streamSource.disconnect();\n this._streamSource = null;\n }\n const msNode = audioContext.createMediaStreamSource(source as MediaStream);\n this._streamSource = msNode;\n return msNode;\n }\n\n // AudioBus - has getOutputNode (checked before raw AudioNode)\n const asBus = source as Partial<{ getOutputNode: () => AudioNode | null }>;\n if (typeof asBus.getOutputNode === 'function') {\n return asBus.getOutputNode();\n }\n\n // Voice - tap its output node\n const asVoice = source as Partial<{ output: AudioNode }>;\n if ('output' in asVoice && asVoice.output) {\n return asVoice.output;\n }\n\n // Raw AudioNode - duck-type: has connect & disconnect\n const asNode = source as Partial<{ connect: unknown; disconnect: unknown }>;\n if (typeof asNode.connect === 'function' && typeof asNode.disconnect === 'function') {\n return source as unknown as AudioNode;\n }\n\n return null;\n }\n\n private _deferConnectionViaBus(source: BeatDetectorSource): void {\n const asBus = source as Partial<{ onceSetup: (callback: () => void) => void }>;\n if (typeof asBus.onceSetup === 'function') {\n asBus.onceSetup(() => {\n if (this._source === source && this._workletNode && isAudioContextReady()) {\n this._connectSource(source, getAudioContext());\n }\n });\n return;\n }\n\n onAudioContextReady.once(() => {\n if (this._source === source && this._workletNode && isAudioContextReady()) {\n this._connectSource(source, getAudioContext());\n }\n });\n }\n\n private _disconnectTap(): void {\n if (this._tapSource && this._workletNode) {\n try {\n this._tapSource.disconnect(this._workletNode);\n } catch {\n // Ignore\n }\n }\n this._tapSource = null;\n\n if (this._streamSource) {\n this._streamSource.disconnect();\n this._streamSource = null;\n }\n }\n}\n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QAAQ,CAER;EAEF,KAAK,aAAa;EAElB,IAAI,KAAK,eAAe;GACtB,KAAK,cAAc,WAAW;GAC9B,KAAK,gBAAgB;EACvB;CACF;AACF"}
@@ -44,10 +44,10 @@ var DuckingEffect = class extends WorkletEffect {
44
44
  this._setAudioParam("attack", this._msToCoeff(this._attackMs, audioContext.sampleRate));
45
45
  this._setAudioParam("release", this._msToCoeff(this._releaseMs, audioContext.sampleRate));
46
46
  const sidechain = this._sidechain;
47
- const sidechainOut = sidechain._getOutputNode();
47
+ const sidechainOut = sidechain.getOutputNode();
48
48
  if (sidechainOut && this._workletNode) sidechainOut.connect(this._workletNode, 0, 1);
49
49
  else sidechain.onceSetup(() => {
50
- const node = sidechain._getOutputNode();
50
+ const node = sidechain.getOutputNode();
51
51
  if (node && this._workletNode) node.connect(this._workletNode, 0, 1);
52
52
  });
53
53
  }
@@ -1 +1 @@
1
- {"version":3,"file":"DuckingEffect.js","names":["duckingWorkletSource"],"sources":["../../../src/effects/DuckingEffect.ts"],"sourcesContent":["import { type AudioBus, WorkletEffect } from '@codexo/exojs';\n\nimport duckingWorkletSource from '../worklets/ducking.worklet.ts?worklet';\n\n/** Construction options for {@link DuckingEffect}. `sidechain` is required. */\nexport interface DuckingEffectOptions {\n sidechain: AudioBus;\n threshold?: number;\n ratio?: number;\n attackMs?: number;\n releaseMs?: number;\n}\n\n/**\n * Sidechain compressor (ducker) implemented as an {@link WorkletEffect}.\n * Attenuates the main audio signal whenever the `sidechain` {@link AudioBus}\n * exceeds the threshold, then releases when it drops back down. Commonly used\n * to duck background music under dialogue or sound effects. Attack and release\n * times are expressed in milliseconds and converted internally to one-pole\n * filter coefficients.\n */\nexport class DuckingEffect extends WorkletEffect {\n // Declared nullable because super() may trigger _onWorkletReady before the\n // subclass constructor body runs (if construction is aborted by a throw).\n private readonly _sidechain: AudioBus | null = null;\n private _threshold: number;\n private _ratio: number;\n private _attackMs: number;\n private _releaseMs: number;\n\n public constructor(options: DuckingEffectOptions) {\n super();\n if (!options.sidechain) {\n throw new Error('DuckingEffect requires a sidechain AudioBus.');\n }\n this._sidechain = options.sidechain;\n this._threshold = options.threshold ?? -20;\n this._ratio = options.ratio ?? 4;\n this._attackMs = options.attackMs ?? 30;\n this._releaseMs = options.releaseMs ?? 300;\n }\n\n protected get _workletName(): string {\n return 'exojs-ducking';\n }\n\n protected get _workletSource(): string {\n return duckingWorkletSource;\n }\n\n protected override get _workletOptions(): AudioWorkletNodeOptions {\n return { numberOfInputs: 2, numberOfOutputs: 1 };\n }\n\n protected override _onWorkletReady(audioContext: AudioContext): void {\n // Guard against partially-constructed instances (constructor threw after super()).\n if (!this._sidechain) return;\n\n // Apply current parameter values\n this._setAudioParam('threshold', this._threshold);\n this._setAudioParam('ratio', this._ratio);\n this._setAudioParam('attack', this._msToCoeff(this._attackMs, audioContext.sampleRate));\n this._setAudioParam('release', this._msToCoeff(this._releaseMs, audioContext.sampleRate));\n\n // Wire sidechain to input 1 of the worklet\n const sidechain = this._sidechain;\n const sidechainOut = sidechain._getOutputNode();\n if (sidechainOut && this._workletNode) {\n sidechainOut.connect(this._workletNode, 0, 1);\n } else {\n sidechain.onceSetup(() => {\n const node = sidechain._getOutputNode();\n if (node && this._workletNode) {\n node.connect(this._workletNode, 0, 1);\n }\n });\n }\n }\n\n /** Convert ms time-constant to one-pole filter coefficient at given sample rate. */\n private _msToCoeff(ms: number, sampleRate: number): number {\n const tau = ms * 0.001 * sampleRate;\n return 1 - Math.exp(-1 / Math.max(1, tau));\n }\n\n /** Sidechain level above which the main signal is attenuated, in dBFS. Range −100..0, default −20. */\n public get threshold(): number {\n return this._threshold;\n }\n public set threshold(value: number) {\n this._threshold = Math.max(-100, Math.min(0, value));\n this._setAudioParam('threshold', this._threshold);\n }\n\n /** Compression ratio applied to the main signal above the threshold. Range 1..20, default 4. */\n public get ratio(): number {\n return this._ratio;\n }\n public set ratio(value: number) {\n this._ratio = Math.max(1, Math.min(20, value));\n this._setAudioParam('ratio', this._ratio);\n }\n\n /** Attack time in milliseconds - how quickly the ducker engages. Default 30. */\n public get attackMs(): number {\n return this._attackMs;\n }\n public set attackMs(value: number) {\n this._attackMs = Math.max(0.001, value);\n if (this._workletNode) {\n this._setAudioParam('attack', this._msToCoeff(this._attackMs, this._workletNode.context.sampleRate));\n }\n }\n\n /** Release time in milliseconds - how quickly the ducker disengages. Default 300. */\n public get releaseMs(): number {\n return this._releaseMs;\n }\n public set releaseMs(value: number) {\n this._releaseMs = Math.max(0.001, value);\n if (this._workletNode) {\n this._setAudioParam('release', this._msToCoeff(this._releaseMs, this._workletNode.context.sampleRate));\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;AAqBA,IAAa,gBAAb,cAAmC,cAAc;CAG/C,AAAiB,aAA8B;CAC/C,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,AAAO,YAAY,SAA+B;EAChD,MAAM;EACN,IAAI,CAAC,QAAQ,WACX,MAAM,IAAI,MAAM,8CAA8C;EAEhE,KAAK,aAAa,QAAQ;EAC1B,KAAK,aAAa,QAAQ,aAAa;EACvC,KAAK,SAAS,QAAQ,SAAS;EAC/B,KAAK,YAAY,QAAQ,YAAY;EACrC,KAAK,aAAa,QAAQ,aAAa;CACzC;CAEA,IAAc,eAAuB;EACnC,OAAO;CACT;CAEA,IAAc,iBAAyB;EACrC,OAAOA;CACT;CAEA,IAAuB,kBAA2C;EAChE,OAAO;GAAE,gBAAgB;GAAG,iBAAiB;EAAE;CACjD;CAEA,AAAmB,gBAAgB,cAAkC;EAEnE,IAAI,CAAC,KAAK,YAAY;EAGtB,KAAK,eAAe,aAAa,KAAK,UAAU;EAChD,KAAK,eAAe,SAAS,KAAK,MAAM;EACxC,KAAK,eAAe,UAAU,KAAK,WAAW,KAAK,WAAW,aAAa,UAAU,CAAC;EACtF,KAAK,eAAe,WAAW,KAAK,WAAW,KAAK,YAAY,aAAa,UAAU,CAAC;EAGxF,MAAM,YAAY,KAAK;EACvB,MAAM,eAAe,UAAU,eAAe;EAC9C,IAAI,gBAAgB,KAAK,cACvB,aAAa,QAAQ,KAAK,cAAc,GAAG,CAAC;OAE5C,UAAU,gBAAgB;GACxB,MAAM,OAAO,UAAU,eAAe;GACtC,IAAI,QAAQ,KAAK,cACf,KAAK,QAAQ,KAAK,cAAc,GAAG,CAAC;EAExC,CAAC;CAEL;;CAGA,AAAQ,WAAW,IAAY,YAA4B;EACzD,MAAM,MAAM,KAAK,OAAQ;EACzB,OAAO,IAAI,KAAK,IAAI,KAAK,KAAK,IAAI,GAAG,GAAG,CAAC;CAC3C;;CAGA,IAAW,YAAoB;EAC7B,OAAO,KAAK;CACd;CACA,IAAW,UAAU,OAAe;EAClC,KAAK,aAAa,KAAK,IAAI,MAAM,KAAK,IAAI,GAAG,KAAK,CAAC;EACnD,KAAK,eAAe,aAAa,KAAK,UAAU;CAClD;;CAGA,IAAW,QAAgB;EACzB,OAAO,KAAK;CACd;CACA,IAAW,MAAM,OAAe;EAC9B,KAAK,SAAS,KAAK,IAAI,GAAG,KAAK,IAAI,IAAI,KAAK,CAAC;EAC7C,KAAK,eAAe,SAAS,KAAK,MAAM;CAC1C;;CAGA,IAAW,WAAmB;EAC5B,OAAO,KAAK;CACd;CACA,IAAW,SAAS,OAAe;EACjC,KAAK,YAAY,KAAK,IAAI,MAAO,KAAK;EACtC,IAAI,KAAK,cACP,KAAK,eAAe,UAAU,KAAK,WAAW,KAAK,WAAW,KAAK,aAAa,QAAQ,UAAU,CAAC;CAEvG;;CAGA,IAAW,YAAoB;EAC7B,OAAO,KAAK;CACd;CACA,IAAW,UAAU,OAAe;EAClC,KAAK,aAAa,KAAK,IAAI,MAAO,KAAK;EACvC,IAAI,KAAK,cACP,KAAK,eAAe,WAAW,KAAK,WAAW,KAAK,YAAY,KAAK,aAAa,QAAQ,UAAU,CAAC;CAEzG;AACF"}
1
+ {"version":3,"file":"DuckingEffect.js","names":["duckingWorkletSource"],"sources":["../../../src/effects/DuckingEffect.ts"],"sourcesContent":["import { type AudioBus, WorkletEffect } from '@codexo/exojs';\n\nimport duckingWorkletSource from '../worklets/ducking.worklet.ts?worklet';\n\n/** Construction options for {@link DuckingEffect}. `sidechain` is required. */\nexport interface DuckingEffectOptions {\n sidechain: AudioBus;\n threshold?: number;\n ratio?: number;\n attackMs?: number;\n releaseMs?: number;\n}\n\n/**\n * Sidechain compressor (ducker) implemented as an {@link WorkletEffect}.\n * Attenuates the main audio signal whenever the `sidechain` {@link AudioBus}\n * exceeds the threshold, then releases when it drops back down. Commonly used\n * to duck background music under dialogue or sound effects. Attack and release\n * times are expressed in milliseconds and converted internally to one-pole\n * filter coefficients.\n */\nexport class DuckingEffect extends WorkletEffect {\n // Declared nullable because super() may trigger _onWorkletReady before the\n // subclass constructor body runs (if construction is aborted by a throw).\n private readonly _sidechain: AudioBus | null = null;\n private _threshold: number;\n private _ratio: number;\n private _attackMs: number;\n private _releaseMs: number;\n\n public constructor(options: DuckingEffectOptions) {\n super();\n if (!options.sidechain) {\n throw new Error('DuckingEffect requires a sidechain AudioBus.');\n }\n this._sidechain = options.sidechain;\n this._threshold = options.threshold ?? -20;\n this._ratio = options.ratio ?? 4;\n this._attackMs = options.attackMs ?? 30;\n this._releaseMs = options.releaseMs ?? 300;\n }\n\n protected get _workletName(): string {\n return 'exojs-ducking';\n }\n\n protected get _workletSource(): string {\n return duckingWorkletSource;\n }\n\n protected override get _workletOptions(): AudioWorkletNodeOptions {\n return { numberOfInputs: 2, numberOfOutputs: 1 };\n }\n\n protected override _onWorkletReady(audioContext: AudioContext): void {\n // Guard against partially-constructed instances (constructor threw after super()).\n if (!this._sidechain) return;\n\n // Apply current parameter values\n this._setAudioParam('threshold', this._threshold);\n this._setAudioParam('ratio', this._ratio);\n this._setAudioParam('attack', this._msToCoeff(this._attackMs, audioContext.sampleRate));\n this._setAudioParam('release', this._msToCoeff(this._releaseMs, audioContext.sampleRate));\n\n // Wire sidechain to input 1 of the worklet\n const sidechain = this._sidechain;\n const sidechainOut = sidechain.getOutputNode();\n if (sidechainOut && this._workletNode) {\n sidechainOut.connect(this._workletNode, 0, 1);\n } else {\n sidechain.onceSetup(() => {\n const node = sidechain.getOutputNode();\n if (node && this._workletNode) {\n node.connect(this._workletNode, 0, 1);\n }\n });\n }\n }\n\n /** Convert ms time-constant to one-pole filter coefficient at given sample rate. */\n private _msToCoeff(ms: number, sampleRate: number): number {\n const tau = ms * 0.001 * sampleRate;\n return 1 - Math.exp(-1 / Math.max(1, tau));\n }\n\n /** Sidechain level above which the main signal is attenuated, in dBFS. Range −100..0, default −20. */\n public get threshold(): number {\n return this._threshold;\n }\n public set threshold(value: number) {\n this._threshold = Math.max(-100, Math.min(0, value));\n this._setAudioParam('threshold', this._threshold);\n }\n\n /** Compression ratio applied to the main signal above the threshold. Range 1..20, default 4. */\n public get ratio(): number {\n return this._ratio;\n }\n public set ratio(value: number) {\n this._ratio = Math.max(1, Math.min(20, value));\n this._setAudioParam('ratio', this._ratio);\n }\n\n /** Attack time in milliseconds - how quickly the ducker engages. Default 30. */\n public get attackMs(): number {\n return this._attackMs;\n }\n public set attackMs(value: number) {\n this._attackMs = Math.max(0.001, value);\n if (this._workletNode) {\n this._setAudioParam('attack', this._msToCoeff(this._attackMs, this._workletNode.context.sampleRate));\n }\n }\n\n /** Release time in milliseconds - how quickly the ducker disengages. Default 300. */\n public get releaseMs(): number {\n return this._releaseMs;\n }\n public set releaseMs(value: number) {\n this._releaseMs = Math.max(0.001, value);\n if (this._workletNode) {\n this._setAudioParam('release', this._msToCoeff(this._releaseMs, this._workletNode.context.sampleRate));\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;AAqBA,IAAa,gBAAb,cAAmC,cAAc;CAG/C,AAAiB,aAA8B;CAC/C,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,AAAO,YAAY,SAA+B;EAChD,MAAM;EACN,IAAI,CAAC,QAAQ,WACX,MAAM,IAAI,MAAM,8CAA8C;EAEhE,KAAK,aAAa,QAAQ;EAC1B,KAAK,aAA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AAK,CAAC;EAC7C,KAAK,eAAe,SAAS,KAAK,MAAM;CAC1C;;CAGA,IAAW,WAAmB;EAC5B,OAAO,KAAK;CACd;CACA,IAAW,SAAS,OAAe;EACjC,KAAK,YAAY,KAAK,IAAI,MAAO,KAAK;EACtC,IAAI,KAAK,cACP,KAAK,eAAe,UAAU,KAAK,WAAW,KAAK,WAAW,KAAK,aAAa,QAAQ,UAAU,CAAC;CAEvG;;CAGA,IAAW,YAAoB;EAC7B,OAAO,KAAK;CACd;CACA,IAAW,UAAU,OAAe;EAClC,KAAK,aAAa,KAAK,IAAI,MAAO,KAAK;EACvC,IAAI,KAAK,cACP,KAAK,eAAe,WAAW,KAAK,WAAW,KAAK,YAAY,KAAK,aAAa,QAAQ,UAAU,CAAC;CAEzG;AACF"}
@@ -51,10 +51,10 @@ var VocoderEffect = class extends WorkletEffect {
51
51
  if (!this._modulator) return;
52
52
  this._setAudioParam("envelopeSmoothing", this._envelopeSmoothing);
53
53
  const modulator = this._modulator;
54
- const modOutput = modulator._getOutputNode();
54
+ const modOutput = modulator.getOutputNode();
55
55
  if (modOutput && this._workletNode) modOutput.connect(this._workletNode, 0, 1);
56
56
  else modulator.onceSetup(() => {
57
- const node = modulator._getOutputNode();
57
+ const node = modulator.getOutputNode();
58
58
  if (node && this._workletNode) node.connect(this._workletNode, 0, 1);
59
59
  });
60
60
  }
@@ -1 +1 @@
1
- {"version":3,"file":"VocoderEffect.js","names":["vocoderWorkletSource"],"sources":["../../../src/effects/VocoderEffect.ts"],"sourcesContent":["import { type AudioBus, WorkletEffect } from '@codexo/exojs';\n\nimport vocoderWorkletSource from '../worklets/vocoder.worklet.ts?worklet';\n\nexport interface VocoderEffectOptions {\n /** Modulator AudioBus - its output drives the spectral envelope.\n * Typically routed from a microphone or voice sample. */\n modulator: AudioBus;\n /** Number of frequency bands. More bands = better resolution, more CPU. Default 16. */\n numBands?: number;\n /** Lowest band center frequency in Hz. Default 80. */\n minHz?: number;\n /** Highest band center frequency in Hz. Default 8000. */\n maxHz?: number;\n /** Bandpass Q factor. Higher = narrower bands. Default 4. */\n bandQ?: number;\n /** Dry/wet mix, 0..1. Default 1.0. */\n wet?: number;\n /** Envelope follower smoothing factor (one-pole coefficient).\n * Smaller = smoother / slower. Default 0.005. */\n envelopeSmoothing?: number;\n}\n\n/**\n * Phase-vocoder-style effect implemented as a {@link WorkletEffect}. Analyzes\n * the spectral envelope of a `modulator` {@link AudioBus} across a bank of\n * log-spaced bandpass filters and applies that envelope to the carrier signal\n * (the main input). The result is the classic \"robot voice\" or talking-synth\n * effect. Band count, frequency range, and Q are compile-time parameters set\n * at construction; only `wet` and `envelopeSmoothing` are adjustable at\n * runtime.\n */\nexport class VocoderEffect extends WorkletEffect {\n // Declared nullable because super() may trigger _onWorkletReady before the\n // subclass constructor body runs (if construction is aborted by a throw).\n private readonly _modulator: AudioBus | null = null;\n private readonly _numBands: number;\n private readonly _minHz: number;\n private readonly _maxHz: number;\n private readonly _bandQ: number;\n private _envelopeSmoothing: number;\n\n public constructor(options: VocoderEffectOptions) {\n super();\n if (!options.modulator) {\n throw new Error('VocoderEffect requires a modulator AudioBus.');\n }\n this._modulator = options.modulator;\n this._numBands = options.numBands ?? 16;\n this._minHz = options.minHz ?? 80;\n this._maxHz = options.maxHz ?? 8000;\n this._bandQ = options.bandQ ?? 4;\n this._envelopeSmoothing = Math.max(0.0001, Math.min(0.1, options.envelopeSmoothing ?? 0.005));\n this.wet = options.wet ?? 1;\n }\n\n protected get _workletName(): string {\n return 'exojs-vocoder';\n }\n protected get _workletSource(): string {\n return vocoderWorkletSource;\n }\n protected override get _workletOptions(): AudioWorkletNodeOptions {\n return {\n numberOfInputs: 2,\n numberOfOutputs: 1,\n processorOptions: {\n numBands: this._numBands,\n minHz: this._minHz,\n maxHz: this._maxHz,\n bandQ: this._bandQ,\n },\n };\n }\n\n protected override _onWorkletReady(_audioContext: AudioContext): void {\n // Guard against partially-constructed instances (constructor threw after super()).\n if (!this._modulator) return;\n\n this._setAudioParam('envelopeSmoothing', this._envelopeSmoothing);\n\n // Wire modulator bus output to input 1 of the worklet\n const modulator = this._modulator;\n const modOutput = modulator._getOutputNode();\n if (modOutput && this._workletNode) {\n modOutput.connect(this._workletNode, 0, 1);\n } else {\n modulator.onceSetup(() => {\n const node = modulator._getOutputNode();\n if (node && this._workletNode) {\n node.connect(this._workletNode, 0, 1);\n }\n });\n }\n }\n\n /** One-pole envelope follower coefficient. Smaller values produce slower, smoother envelope tracking. Range 0.0001..0.1, default 0.005. */\n public get envelopeSmoothing(): number {\n return this._envelopeSmoothing;\n }\n public set envelopeSmoothing(value: number) {\n this._envelopeSmoothing = Math.max(0.0001, Math.min(0.1, value));\n this._setAudioParam('envelopeSmoothing', this._envelopeSmoothing);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgCA,IAAa,gBAAb,cAAmC,cAAc;CAG/C,AAAiB,aAA8B;CAC/C,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAQ;CAER,AAAO,YAAY,SAA+B;EAChD,MAAM;EACN,IAAI,CAAC,QAAQ,WACX,MAAM,IAAI,MAAM,8CAA8C;EAEhE,KAAK,aAAa,QAAQ;EAC1B,KAAK,YAAY,QAAQ,YAAY;EACrC,KAAK,SAAS,QAAQ,SAAS;EAC/B,KAAK,SAAS,QAAQ,SAAS;EAC/B,KAAK,SAAS,QAAQ,SAAS;EAC/B,KAAK,qBAAqB,KAAK,IAAI,MAAQ,KAAK,IAAI,IAAK,QAAQ,qBAAqB,IAAK,CAAC;EAC5F,KAAK,MAAM,QAAQ,OAAO;CAC5B;CAEA,IAAc,eAAuB;EACnC,OAAO;CACT;CACA,IAAc,iBAAyB;EACrC,OAAOA;CACT;CACA,IAAuB,kBAA2C;EAChE,OAAO;GACL,gBAAgB;GAChB,iBAAiB;GACjB,kBAAkB;IAChB,UAAU,KAAK;IACf,OAAO,KAAK;IACZ,OAAO,KAAK;IACZ,OAAO,KAAK;GACd;EACF;CACF;CAEA,AAAmB,gBAAgB,eAAmC;EAEpE,IAAI,CAAC,KAAK,YAAY;EAEtB,KAAK,eAAe,qBAAqB,KAAK,kBAAkB;EAGhE,MAAM,YAAY,KAAK;EACvB,MAAM,YAAY,UAAU,eAAe;EAC3C,IAAI,aAAa,KAAK,cACpB,UAAU,QAAQ,KAAK,cAAc,GAAG,CAAC;OAEzC,UAAU,gBAAgB;GACxB,MAAM,OAAO,UAAU,eAAe;GACtC,IAAI,QAAQ,KAAK,cACf,KAAK,QAAQ,KAAK,cAAc,GAAG,CAAC;EAExC,CAAC;CAEL;;CAGA,IAAW,oBAA4B;EACrC,OAAO,KAAK;CACd;CACA,IAAW,kBAAkB,OAAe;EAC1C,KAAK,qBAAqB,KAAK,IAAI,MAAQ,KAAK,IAAI,IAAK,KAAK,CAAC;EAC/D,KAAK,eAAe,qBAAqB,KAAK,kBAAkB;CAClE;AACF"}
1
+ {"version":3,"file":"VocoderEffect.js","names":["vocoderWorkletSource"],"sources":["../../../src/effects/VocoderEffect.ts"],"sourcesContent":["import { type AudioBus, WorkletEffect } from '@codexo/exojs';\n\nimport vocoderWorkletSource from '../worklets/vocoder.worklet.ts?worklet';\n\nexport interface VocoderEffectOptions {\n /** Modulator AudioBus - its output drives the spectral envelope.\n * Typically routed from a microphone or voice sample. */\n modulator: AudioBus;\n /** Number of frequency bands. More bands = better resolution, more CPU. Default 16. */\n numBands?: number;\n /** Lowest band center frequency in Hz. Default 80. */\n minHz?: number;\n /** Highest band center frequency in Hz. Default 8000. */\n maxHz?: number;\n /** Bandpass Q factor. Higher = narrower bands. Default 4. */\n bandQ?: number;\n /** Dry/wet mix, 0..1. Default 1.0. */\n wet?: number;\n /** Envelope follower smoothing factor (one-pole coefficient).\n * Smaller = smoother / slower. Default 0.005. */\n envelopeSmoothing?: number;\n}\n\n/**\n * Phase-vocoder-style effect implemented as a {@link WorkletEffect}. Analyzes\n * the spectral envelope of a `modulator` {@link AudioBus} across a bank of\n * log-spaced bandpass filters and applies that envelope to the carrier signal\n * (the main input). The result is the classic \"robot voice\" or talking-synth\n * effect. Band count, frequency range, and Q are compile-time parameters set\n * at construction; only `wet` and `envelopeSmoothing` are adjustable at\n * runtime.\n */\nexport class VocoderEffect extends WorkletEffect {\n // Declared nullable because super() may trigger _onWorkletReady before the\n // subclass constructor body runs (if construction is aborted by a throw).\n private readonly _modulator: AudioBus | null = null;\n private readonly _numBands: number;\n private readonly _minHz: number;\n private readonly _maxHz: number;\n private readonly _bandQ: number;\n private _envelopeSmoothing: number;\n\n public constructor(options: VocoderEffectOptions) {\n super();\n if (!options.modulator) {\n throw new Error('VocoderEffect requires a modulator AudioBus.');\n }\n this._modulator = options.modulator;\n this._numBands = options.numBands ?? 16;\n this._minHz = options.minHz ?? 80;\n this._maxHz = options.maxHz ?? 8000;\n this._bandQ = options.bandQ ?? 4;\n this._envelopeSmoothing = Math.max(0.0001, Math.min(0.1, options.envelopeSmoothing ?? 0.005));\n this.wet = options.wet ?? 1;\n }\n\n protected get _workletName(): string {\n return 'exojs-vocoder';\n }\n protected get _workletSource(): string {\n return vocoderWorkletSource;\n }\n protected override get _workletOptions(): AudioWorkletNodeOptions {\n return {\n numberOfInputs: 2,\n numberOfOutputs: 1,\n processorOptions: {\n numBands: this._numBands,\n minHz: this._minHz,\n maxHz: this._maxHz,\n bandQ: this._bandQ,\n },\n };\n }\n\n protected override _onWorkletReady(_audioContext: AudioContext): void {\n // Guard against partially-constructed instances (constructor threw after super()).\n if (!this._modulator) return;\n\n this._setAudioParam('envelopeSmoothing', this._envelopeSmoothing);\n\n // Wire modulator bus output to input 1 of the worklet\n const modulator = this._modulator;\n const modOutput = modulator.getOutputNode();\n if (modOutput && this._workletNode) {\n modOutput.connect(this._workletNode, 0, 1);\n } else {\n modulator.onceSetup(() => {\n const node = modulator.getOutputNode();\n if (node && this._workletNode) {\n node.connect(this._workletNode, 0, 1);\n }\n });\n }\n }\n\n /** One-pole envelope follower coefficient. Smaller values produce slower, smoother envelope tracking. Range 0.0001..0.1, default 0.005. */\n public get envelopeSmoothing(): number {\n return this._envelopeSmoothing;\n }\n public set envelopeSmoothing(value: number) {\n this._envelopeSmoothing = Math.max(0.0001, Math.min(0.1, value));\n this._setAudioParam('envelopeSmoothing', this._envelopeSmoothing);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgCA,IAAa,gBAAb,cAAmC,cAAc;CAG/C,AAAiB,aAA8B;CAC/C,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAQ;CAER,AAAO,YAAY,SAA+B;EAChD,MAAM;EACN,IAAI,CAAC,QAAQ,WACX,MAAM,IAAI,MAAM,8CAA8C;EAEhE,KAAK,aAAa,QAAQ;EAC1B,KAAK,YAAY,QAAQ,YAAY;EACrC,KAAK,SAAS,QAAQ,SAAS;EAC/B,KAAK,SAAS,QAAQ,SAAS;EAC/B,KAAK,SAAS,QAAQ,SAAS;EAC/B,KAAK,qBAAqB,KAAK,IAAI,MAAQ,KAAK,IAAI,IAAK,QAAQ,qBAAqB,IAAK,CAAC;EAC5F,KAAK,MAAM,QAAQ,OAAO;CAC5B;CAEA,IAAc,eAAuB;EACnC,OAAO;CACT;CACA,IAAc,iBAAyB;EACrC,OAAOA;CACT;CACA,IAAuB,kBAA2C;EAChE,OAAO;GACL,gBAAgB;GAChB,iBAAiB;GACjB,kBAAkB;IAChB,UAAU,KAAK;IACf,OAAO,KAAK;IACZ,OAAO,KAAK;IACZ,OAAO,KAAK;GACd;EACF;CACF;CAEA,AAAmB,gBAAgB,eAAmC;EAEpE,IAAI,CAAC,KAAK,YAAY;EAEtB,KAAK,eAAe,qBAAqB,KAAK,kBAAkB;EAGhE,MAAM,YAAY,KAAK;EACvB,MAAM,YAAY,UAAU,cAAc;EAC1C,IAAI,aAAa,KAAK,cACpB,UAAU,QAAQ,KAAK,cAAc,GAAG,CAAC;OAEzC,UAAU,gBAAgB;GACxB,MAAM,OAAO,UAAU,cAAc;GACrC,IAAI,QAAQ,KAAK,cACf,KAAK,QAAQ,KAAK,cAAc,GAAG,CAAC;EAExC,CAAC;CAEL;;CAGA,IAAW,oBAA4B;EACrC,OAAO,KAAK;CACd;CACA,IAAW,kBAAkB,OAAe;EAC1C,KAAK,qBAAqB,KAAK,IAAI,MAAQ,KAAK,IAAI,IAAK,KAAK,CAAC;EAC/D,KAAK,eAAe,qBAAqB,KAAK,kBAAkB;CAClE;AACF"}
@@ -1,5 +1,5 @@
1
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";
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 PHASE_CONFIDENCE_GAIN = 0.25;\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 _lastBeatContextTime;\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 _phaseConfidence;\n /**\n * Context frames minus analysed samples, refreshed every render quantum.\n * `_sampleCount` counts only samples that reached `process()`, so it stalls\n * whenever no source is connected and cannot name a point on the context\n * clock by itself.\n */\n _frameOffset;\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._lastBeatContextTime = 0;\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 this._phaseConfidence = 0;\n this._frameOffset = 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 this._frameOffset = currentFrame - this._sampleCount;\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 /** Audio-context seconds of an analysed sample position from the current render quantum. */\n _contextTimeAt(sample) {\n return (sample + this._frameOffset) / this._sampleRate;\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 = this._contextTimeAt(beatSample);\n this._lastBeatContextTime = beatTime;\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 this._observePhase(1 - Math.min(1, Math.abs(error) / acceptWin));\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 this._observePhase(0);\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 /**\n * Fold one beat's worth of phase evidence into the running estimate. `quality`\n * is 1 when the matched onset landed exactly on the prediction, 0 at the edge\n * of the accept window, and 0 for a beat the grid had to free-run because no\n * onset supported it.\n */\n _observePhase(quality) {\n this._phaseConfidence += (quality - this._phaseConfidence) * PHASE_CONFIDENCE_GAIN;\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 this._phaseConfidence = 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 analysedNow = this._sampleCount / this._sampleRate;\n const analysedLastBeat = this._lastBeatSample >= 0 ? this._lastBeatSample / this._sampleRate : 0;\n const beatPhase = beatInterval > 0 ? Math.min(1, (analysedNow - analysedLastBeat) / beatInterval) : 0;\n const analysisTime = this._contextTimeAt(this._sampleCount);\n const lastBeatTime = this._lastBeatContextTime;\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 analysisTime,\n tempo: settled ? this._bestBpm : 0,\n beatPhase,\n confidence: settled ? this._confidence : 0,\n phaseConfidence: settled ? this._phaseConfidence : 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";
3
3
 
4
4
  //#endregion
5
5
  export { beat_detector_worklet_default as default };
@@ -1 +1 @@
1
- {"version":3,"file":"beat-detector.worklet.js","names":[],"sources":["../../../src/worklets/beat-detector.worklet.ts?worklet"],"sourcesContent":["export 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\";"],"mappings":";AAAA,oCAAe"}
1
+ {"version":3,"file":"beat-detector.worklet.js","names":[],"sources":["../../../src/worklets/beat-detector.worklet.ts?worklet"],"sourcesContent":["export 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 PHASE_CONFIDENCE_GAIN = 0.25;\\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 _lastBeatContextTime;\\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 _phaseConfidence;\\n /**\\n * Context frames minus analysed samples, refreshed every render quantum.\\n * `_sampleCount` counts only samples that reached `process()`, so it stalls\\n * whenever no source is connected and cannot name a point on the context\\n * clock by itself.\\n */\\n _frameOffset;\\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._lastBeatContextTime = 0;\\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 this._phaseConfidence = 0;\\n this._frameOffset = 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 this._frameOffset = currentFrame - this._sampleCount;\\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 /** Audio-context seconds of an analysed sample position from the current render quantum. */\\n _contextTimeAt(sample) {\\n return (sample + this._frameOffset) / this._sampleRate;\\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 = this._contextTimeAt(beatSample);\\n this._lastBeatContextTime = beatTime;\\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 this._observePhase(1 - Math.min(1, Math.abs(error) / acceptWin));\\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 this._observePhase(0);\\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 /**\\n * Fold one beat's worth of phase evidence into the running estimate. `quality`\\n * is 1 when the matched onset landed exactly on the prediction, 0 at the edge\\n * of the accept window, and 0 for a beat the grid had to free-run because no\\n * onset supported it.\\n */\\n _observePhase(quality) {\\n this._phaseConfidence += (quality - this._phaseConfidence) * PHASE_CONFIDENCE_GAIN;\\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 this._phaseConfidence = 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 analysedNow = this._sampleCount / this._sampleRate;\\n const analysedLastBeat = this._lastBeatSample >= 0 ? this._lastBeatSample / this._sampleRate : 0;\\n const beatPhase = beatInterval > 0 ? Math.min(1, (analysedNow - analysedLastBeat) / beatInterval) : 0;\\n const analysisTime = this._contextTimeAt(this._sampleCount);\\n const lastBeatTime = this._lastBeatContextTime;\\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 analysisTime,\\n tempo: settled ? this._bestBpm : 0,\\n beatPhase,\\n confidence: settled ? this._confidence : 0,\\n phaseConfidence: settled ? this._phaseConfidence : 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\";"],"mappings":";AAAA,oCAAe"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codexo/exojs-audio-fx",
3
- "version": "0.16.2",
3
+ "version": "0.18.0",
4
4
  "description": "Audio effects, DSP, beat detection and analysis for ExoJS.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,10 +26,10 @@
26
26
  "LICENSE"
27
27
  ],
28
28
  "peerDependencies": {
29
- "@codexo/exojs": "0.16.x"
29
+ "@codexo/exojs": "0.18.x"
30
30
  },
31
31
  "devDependencies": {
32
- "@codexo/exojs": "0.16.2",
32
+ "@codexo/exojs": "0.18.0",
33
33
  "@codexo/exojs-config": "0.0.0"
34
34
  },
35
35
  "license": "MIT",