@codexo/exojs-audio-fx 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +7 -53
  2. package/index.d.ts +1 -0
  3. package/index.js +1 -0
  4. package/package.json +12 -20
  5. package/dist/esm/AudioAnalyser.d.ts +0 -125
  6. package/dist/esm/AudioAnalyser.d.ts.map +0 -1
  7. package/dist/esm/AudioAnalyser.js +0 -369
  8. package/dist/esm/AudioAnalyser.js.map +0 -1
  9. package/dist/esm/BeatDetector.d.ts +0 -286
  10. package/dist/esm/BeatDetector.d.ts.map +0 -1
  11. package/dist/esm/BeatDetector.js +0 -419
  12. package/dist/esm/BeatDetector.js.map +0 -1
  13. package/dist/esm/PcmStreamSource.d.ts +0 -127
  14. package/dist/esm/PcmStreamSource.d.ts.map +0 -1
  15. package/dist/esm/PcmStreamSource.js +0 -308
  16. package/dist/esm/PcmStreamSource.js.map +0 -1
  17. package/dist/esm/dsp/fft.d.ts +0 -22
  18. package/dist/esm/dsp/fft.d.ts.map +0 -1
  19. package/dist/esm/dsp/mel.d.ts +0 -43
  20. package/dist/esm/dsp/mel.d.ts.map +0 -1
  21. package/dist/esm/dsp/mel.js +0 -61
  22. package/dist/esm/dsp/mel.js.map +0 -1
  23. package/dist/esm/dsp/tempogram.d.ts +0 -192
  24. package/dist/esm/dsp/tempogram.d.ts.map +0 -1
  25. package/dist/esm/effects/AutoWahEffect.d.ts +0 -128
  26. package/dist/esm/effects/AutoWahEffect.d.ts.map +0 -1
  27. package/dist/esm/effects/AutoWahEffect.js +0 -214
  28. package/dist/esm/effects/AutoWahEffect.js.map +0 -1
  29. package/dist/esm/effects/BitCrusherEffect.d.ts +0 -64
  30. package/dist/esm/effects/BitCrusherEffect.d.ts.map +0 -1
  31. package/dist/esm/effects/BitCrusherEffect.js +0 -76
  32. package/dist/esm/effects/BitCrusherEffect.js.map +0 -1
  33. package/dist/esm/effects/ChorusEffect.d.ts +0 -54
  34. package/dist/esm/effects/ChorusEffect.d.ts.map +0 -1
  35. package/dist/esm/effects/ChorusEffect.js +0 -136
  36. package/dist/esm/effects/ChorusEffect.js.map +0 -1
  37. package/dist/esm/effects/CompressorEffect.d.ts +0 -56
  38. package/dist/esm/effects/CompressorEffect.d.ts.map +0 -1
  39. package/dist/esm/effects/CompressorEffect.js +0 -108
  40. package/dist/esm/effects/CompressorEffect.js.map +0 -1
  41. package/dist/esm/effects/ConvolutionEffect.d.ts +0 -119
  42. package/dist/esm/effects/ConvolutionEffect.d.ts.map +0 -1
  43. package/dist/esm/effects/ConvolutionEffect.js +0 -212
  44. package/dist/esm/effects/ConvolutionEffect.js.map +0 -1
  45. package/dist/esm/effects/DelayEffect.d.ts +0 -36
  46. package/dist/esm/effects/DelayEffect.d.ts.map +0 -1
  47. package/dist/esm/effects/DelayEffect.js +0 -109
  48. package/dist/esm/effects/DelayEffect.js.map +0 -1
  49. package/dist/esm/effects/DistortionEffect.d.ts +0 -120
  50. package/dist/esm/effects/DistortionEffect.d.ts.map +0 -1
  51. package/dist/esm/effects/DistortionEffect.js +0 -194
  52. package/dist/esm/effects/DistortionEffect.js.map +0 -1
  53. package/dist/esm/effects/DuckingEffect.d.ts +0 -44
  54. package/dist/esm/effects/DuckingEffect.d.ts.map +0 -1
  55. package/dist/esm/effects/DuckingEffect.js +0 -95
  56. package/dist/esm/effects/DuckingEffect.js.map +0 -1
  57. package/dist/esm/effects/EqualizerEffect.d.ts +0 -51
  58. package/dist/esm/effects/EqualizerEffect.d.ts.map +0 -1
  59. package/dist/esm/effects/EqualizerEffect.js +0 -124
  60. package/dist/esm/effects/EqualizerEffect.js.map +0 -1
  61. package/dist/esm/effects/FlangerEffect.d.ts +0 -99
  62. package/dist/esm/effects/FlangerEffect.d.ts.map +0 -1
  63. package/dist/esm/effects/FlangerEffect.js +0 -176
  64. package/dist/esm/effects/FlangerEffect.js.map +0 -1
  65. package/dist/esm/effects/GranularEffect.d.ts +0 -67
  66. package/dist/esm/effects/GranularEffect.d.ts.map +0 -1
  67. package/dist/esm/effects/GranularEffect.js +0 -104
  68. package/dist/esm/effects/GranularEffect.js.map +0 -1
  69. package/dist/esm/effects/LimiterEffect.d.ts +0 -125
  70. package/dist/esm/effects/LimiterEffect.d.ts.map +0 -1
  71. package/dist/esm/effects/LimiterEffect.js +0 -186
  72. package/dist/esm/effects/LimiterEffect.js.map +0 -1
  73. package/dist/esm/effects/PhaserEffect.d.ts +0 -127
  74. package/dist/esm/effects/PhaserEffect.d.ts.map +0 -1
  75. package/dist/esm/effects/PhaserEffect.js +0 -218
  76. package/dist/esm/effects/PhaserEffect.js.map +0 -1
  77. package/dist/esm/effects/PingPongDelayEffect.d.ts +0 -84
  78. package/dist/esm/effects/PingPongDelayEffect.d.ts.map +0 -1
  79. package/dist/esm/effects/PingPongDelayEffect.js +0 -176
  80. package/dist/esm/effects/PingPongDelayEffect.js.map +0 -1
  81. package/dist/esm/effects/PitchShiftEffect.d.ts +0 -46
  82. package/dist/esm/effects/PitchShiftEffect.d.ts.map +0 -1
  83. package/dist/esm/effects/PitchShiftEffect.js +0 -64
  84. package/dist/esm/effects/PitchShiftEffect.js.map +0 -1
  85. package/dist/esm/effects/ReverbEffect.d.ts +0 -38
  86. package/dist/esm/effects/ReverbEffect.d.ts.map +0 -1
  87. package/dist/esm/effects/ReverbEffect.js +0 -117
  88. package/dist/esm/effects/ReverbEffect.js.map +0 -1
  89. package/dist/esm/effects/RingModulatorEffect.d.ts +0 -96
  90. package/dist/esm/effects/RingModulatorEffect.d.ts.map +0 -1
  91. package/dist/esm/effects/RingModulatorEffect.js +0 -157
  92. package/dist/esm/effects/RingModulatorEffect.js.map +0 -1
  93. package/dist/esm/effects/TremoloEffect.d.ts +0 -111
  94. package/dist/esm/effects/TremoloEffect.d.ts.map +0 -1
  95. package/dist/esm/effects/TremoloEffect.js +0 -197
  96. package/dist/esm/effects/TremoloEffect.js.map +0 -1
  97. package/dist/esm/effects/VocoderEffect.d.ts +0 -45
  98. package/dist/esm/effects/VocoderEffect.d.ts.map +0 -1
  99. package/dist/esm/effects/VocoderEffect.js +0 -73
  100. package/dist/esm/effects/VocoderEffect.js.map +0 -1
  101. package/dist/esm/index.d.ts +0 -25
  102. package/dist/esm/index.d.ts.map +0 -1
  103. package/dist/esm/index.js +0 -24
  104. package/dist/esm/worklets/beat-detector.worklet.js +0 -6
  105. package/dist/esm/worklets/beat-detector.worklet.js.map +0 -1
  106. package/dist/esm/worklets/bit-crusher.worklet.js +0 -6
  107. package/dist/esm/worklets/bit-crusher.worklet.js.map +0 -1
  108. package/dist/esm/worklets/ducking.worklet.js +0 -6
  109. package/dist/esm/worklets/ducking.worklet.js.map +0 -1
  110. package/dist/esm/worklets/granular.worklet.js +0 -6
  111. package/dist/esm/worklets/granular.worklet.js.map +0 -1
  112. package/dist/esm/worklets/pcm-stream.worklet.js +0 -6
  113. package/dist/esm/worklets/pcm-stream.worklet.js.map +0 -1
  114. package/dist/esm/worklets/pitch-shift.worklet.js +0 -6
  115. package/dist/esm/worklets/pitch-shift.worklet.js.map +0 -1
  116. package/dist/esm/worklets/vocoder.worklet.js +0 -6
  117. package/dist/esm/worklets/vocoder.worklet.js.map +0 -1
@@ -1 +0,0 @@
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,IAAI,aAAa,QAAQ;EAE/C,IAAI,oBAAoB,GACtB,KAAK,eAAe,gBAAgB,CAAC;OAErC,oBAAoB,IAAI,KAAK,oBAAoB;EAGnD,IAAI,SAAS,WAAW,UAAa,QAAQ,WAAW,MACtD,KAAK,SAAS,QAAQ;CAE1B;;;;;;CAWA,IAAW,SAA8B;EACvC,OAAO,KAAK;CACd;CAEA,IAAW,OAAO,OAA4B;E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yC;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,286 +0,0 @@
1
- import { type AudioBus, Signal, type Voice } from '@codexo/exojs';
2
- export type BeatDetectorSource = AudioBus | Voice | MediaStream | AudioNode | null;
3
- export interface BeatDetectorOptions {
4
- /** Minimum detectable BPM. Default 50. */
5
- minBpm?: number;
6
- /** Maximum detectable BPM. Default 300. */
7
- maxBpm?: number;
8
- /** FFT size for onset detection. Default 2048. */
9
- fftSize?: number;
10
- /** Hop size in samples between successive FFTs. Default 512. */
11
- hopSize?: number;
12
- /**
13
- * Short tempogram window (seconds) that reacts quickly to a genuine tempo
14
- * change. Default 2.5. The tracked tempo follows this FAST window only when it
15
- * disagrees with {@link stableTempoWindowSec} consistently over several
16
- * analysis hops, so a real DJ drift is tracked without making a steady tempo
17
- * nervous.
18
- */
19
- fastTempoWindowSec?: number;
20
- /**
21
- * Long tempogram window (seconds) that holds the tempo grid steady against
22
- * noise and octave ambiguity. Default 8. Should be ≥ {@link fastTempoWindowSec}
23
- * and large enough to hold ≳ 2 periods of the slowest tempo; it also sizes the
24
- * internal flux ring buffer.
25
- */
26
- stableTempoWindowSec?: number;
27
- /**
28
- * Hops between successive autocorrelation (tempogram) recomputations.
29
- * Default 15 (~160 ms at 48 kHz with the default 512-sample hop). Lower values
30
- * react faster to tempo changes at the cost of more CPU.
31
- */
32
- acfIntervalHops?: number;
33
- /**
34
- * Minimum warm-up (ms) before the first beat may be emitted. Default 400.
35
- * The detector starts hunting a tempo once this much analysis history exists
36
- * instead of waiting a full slowest-tempo period, so early {@link BeatInfo}
37
- * beats (tagged `status: 'provisional'`) arrive with low latency for visual
38
- * reactivity. A beat is promoted to `status: 'locked'` only once the tempo grid
39
- * is trustworthy (full analysis window + sustained on-grid tracking). Replaces
40
- * the former `settlingMs` (default 1500).
41
- */
42
- minSettlingMs?: number;
43
- /**
44
- * When true (default), early low-confidence beats are emitted tagged
45
- * `status: 'provisional'` (then promoted to `'locked'`) for snappy visual
46
- * reactivity. Set false to suppress provisional beats entirely - {@link onBeat}
47
- * then fires only for `'locked'` beats, matching the pre-provisional behaviour.
48
- */
49
- emitProvisionalBeats?: boolean;
50
- /** Number of mel filterbank bands. Default 24. */
51
- melBands?: number;
52
- /**
53
- * When true (default), the worklet runs parallel 3/4 and 4/4 posteriors and
54
- * switches active time signature via hysteresis. Set false to lock to 4/4.
55
- */
56
- enableTimeSignatureDetection?: boolean;
57
- /**
58
- * Optional initial source. Equivalent to constructing then assigning
59
- * `detector.source = value`; provided for ergonomic one-shot construction.
60
- * The setter remains usable for runtime source switches.
61
- */
62
- source?: BeatDetectorSource;
63
- /**
64
- * Half-life in seconds for the {@link BeatDetector.pulse} envelope.
65
- * Default 0.15 - `pulse` halves every 150ms after each beat.
66
- */
67
- pulseHalfLife?: number;
68
- /**
69
- * Half-life in seconds for the {@link BeatDetector.barPulse} envelope.
70
- * Default 0.3 - slower than beat pulse for downbeat-emphasized visuals.
71
- */
72
- barPulseHalfLife?: number;
73
- /**
74
- * Time window in seconds for {@link BeatDetector.justBeat}. Default 0.03
75
- * - true for the visual frame(s) within 30ms of a beat onset.
76
- */
77
- justBeatWindow?: number;
78
- }
79
- export interface BeatInfo {
80
- /** audioContext.currentTime when the beat occurred. */
81
- audioTime: number;
82
- /** BPM at this beat. */
83
- tempo: number;
84
- /** Confidence 0..1. */
85
- confidence: number;
86
- /** Phase within beat (0 = start). */
87
- beatPhase: number;
88
- /** Novelty/onset strength at the beat. */
89
- energy: number;
90
- /** Is this beat the first in a bar? */
91
- isDownbeat: boolean;
92
- /** Beat position within the bar (1..N). */
93
- beatInBar: number;
94
- /**
95
- * Detection trust level:
96
- * - `'provisional'` - an early, low-latency beat emitted before the tempo grid
97
- * is fully settled. Good for visual reactivity (a "blink"); may be revised.
98
- * - `'locked'` - the tempo grid is settled and trustworthy. Safe for
99
- * sync-critical use. Each stable segment yields exactly one provisional→locked
100
- * transition.
101
- */
102
- status: 'provisional' | 'locked';
103
- }
104
- export interface UpcomingBeat {
105
- audioTime: number;
106
- tempo: number;
107
- isDownbeat: boolean;
108
- beatInBar: number;
109
- }
110
- export interface BarInfo {
111
- audioTime: number;
112
- tempo: number;
113
- confidence: number;
114
- /** Monotonically increasing bar counter since detector start. */
115
- barNumber: number;
116
- }
117
- export interface TimeSignature {
118
- numerator: number;
119
- denominator: number;
120
- }
121
- export interface TempoCandidate {
122
- bpm: number;
123
- /** Peak strength 0..1. */
124
- score: number;
125
- }
126
- export interface BandEnergy {
127
- low: number;
128
- mid: number;
129
- high: number;
130
- }
131
- /**
132
- * Real-time tempo + beat tracker. Splits work between the audio-rendering
133
- * thread (an AudioWorklet that runs onset detection, tempogram analysis,
134
- * and parallel 3/4 and 4/4 posterior estimation) and the main thread (this
135
- * class - receives beats, fires Signals, handles configuration and source
136
- * routing).
137
- *
138
- * Accepts a wide range of {@link BeatDetectorSource}s - a bus, an individual
139
- * {@link Voice}, a raw MediaStream, or any AudioNode - and exposes a Signal
140
- * for each notable event:
141
- * - {@link BeatDetector.onBeat} - every detected beat
142
- * - {@link BeatDetector.onDownbeat} - first beat of each bar
143
- * - {@link BeatDetector.onBarStart} - bar boundary
144
- * - {@link BeatDetector.onTempoChange} - when the tracked BPM changes
145
- * - {@link BeatDetector.onBeatPredicted} - look-ahead schedule notice
146
- *
147
- * Early beats arrive with low latency tagged `status: 'provisional'` (after a
148
- * short `minSettlingMs` warm-up, default 400 ms) for snappy visual reactivity,
149
- * then promote to `status: 'locked'` once the tempo grid is trustworthy - a
150
- * single {@link BeatDetector.onBeat} signal carries both via {@link BeatInfo.status}.
151
- * Set `emitProvisionalBeats: false` to receive only locked beats. Time-signature
152
- * detection (3/4 vs 4/4) is on by default; lock to 4/4 by setting
153
- * `enableTimeSignatureDetection: false`.
154
- */
155
- export declare class BeatDetector {
156
- readonly onBeat: Signal<[BeatInfo]>;
157
- readonly onTempoChange: Signal<[number, number]>;
158
- readonly onDownbeat: Signal<[BeatInfo]>;
159
- readonly onBarStart: Signal<[BarInfo]>;
160
- readonly onBeatPredicted: Signal<[UpcomingBeat]>;
161
- private readonly _options;
162
- private _workletNode;
163
- private _source;
164
- private _tapSource;
165
- private _streamSource;
166
- private _ready;
167
- private _pendingSourceSetup;
168
- private readonly _onAudioContextReady;
169
- private _tempo;
170
- private _beatPhase;
171
- private _nextBeatTime;
172
- private _confidence;
173
- private _phaseConfidence;
174
- private _gridStability;
175
- private _analysisTime;
176
- private _analysisLatency;
177
- private _tempoCandidates;
178
- private _rms;
179
- private _onsetStrength;
180
- private _bandEnergy;
181
- private _barPosition;
182
- private _barLength;
183
- private _timeSignature;
184
- private _nextDownbeatTime;
185
- private _lookahead;
186
- /**
187
- * Half-life in seconds for the {@link pulse} envelope. Mutable; default 0.15.
188
- * Smaller values give a snappier pulse, larger values a longer afterglow.
189
- */
190
- pulseHalfLife: number;
191
- /** Half-life for the {@link barPulse} envelope. Mutable; default 0.3. */
192
- barPulseHalfLife: number;
193
- /** Time window for {@link justBeat}. Mutable; default 0.03 (30ms). */
194
- justBeatWindow: number;
195
- constructor(options?: BeatDetectorOptions);
196
- get source(): BeatDetectorSource;
197
- set source(value: BeatDetectorSource);
198
- get ready(): Promise<void>;
199
- get tempo(): number;
200
- get beatPhase(): number;
201
- get nextBeatTime(): number;
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;
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;
237
- get rms(): number;
238
- get onsetStrength(): number;
239
- get bandEnergy(): BandEnergy;
240
- get tempoCandidates(): readonly TempoCandidate[];
241
- get barPosition(): number;
242
- get barLength(): number;
243
- get timeSignature(): TimeSignature;
244
- get nextDownbeatTime(): number;
245
- get lookahead(): readonly UpcomingBeat[];
246
- /**
247
- * Seconds elapsed since the most recent beat, derived from {@link beatPhase}
248
- * and {@link tempo}. Returns 0 when the detector hasn't locked yet.
249
- */
250
- get secondsSinceLastBeat(): number;
251
- /**
252
- * 0..1 envelope, peaks at 1.0 the moment a beat fires and halves every
253
- * {@link pulseHalfLife} seconds. Drives "pulse on the beat" visuals
254
- * with a single multiplication: `sprite.scale = 1 + clock.pulse * 0.3`.
255
- */
256
- get pulse(): number;
257
- /**
258
- * Like {@link pulse} but resets on downbeats and decays per
259
- * {@link barPulseHalfLife}. Useful for emphasizing the first beat of
260
- * each bar (e.g. brighter flash on "1" vs "2,3,4").
261
- */
262
- get barPulse(): number;
263
- /**
264
- * True for the visual frame(s) within {@link justBeatWindow} seconds of
265
- * a beat onset. Use for one-shot triggers (strobe flash, particle burst,
266
- * sample retrigger). Default window 30ms covers a typical 60fps frame.
267
- */
268
- get justBeat(): boolean;
269
- /**
270
- * Phase 0..1 within a subdivision of the current beat. `division` is the
271
- * number of subdivisions per beat: 2 for 8th notes, 4 for 16th notes,
272
- * 3 for triplets. Use to drive sub-beat-resolution effects:
273
- *
274
- * const sixteenth = clock.subdivisionPhase(4);
275
- * if (sixteenth < 0.05) flash();
276
- */
277
- subdivisionPhase(division: number): number;
278
- destroy(): void;
279
- private _setup;
280
- private _onWorkletMessage;
281
- private _connectSource;
282
- private _resolveToAudioNode;
283
- private _deferConnectionViaBus;
284
- private _disconnectTap;
285
- }
286
- //# sourceMappingURL=BeatDetector.d.ts.map
@@ -1 +0,0 @@
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;;;;;;OAMG;IACH,kBAA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