@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.
- package/README.md +7 -53
- package/index.d.ts +1 -0
- package/index.js +1 -0
- package/package.json +12 -20
- package/dist/esm/AudioAnalyser.d.ts +0 -125
- package/dist/esm/AudioAnalyser.d.ts.map +0 -1
- package/dist/esm/AudioAnalyser.js +0 -369
- package/dist/esm/AudioAnalyser.js.map +0 -1
- package/dist/esm/BeatDetector.d.ts +0 -286
- package/dist/esm/BeatDetector.d.ts.map +0 -1
- package/dist/esm/BeatDetector.js +0 -419
- package/dist/esm/BeatDetector.js.map +0 -1
- package/dist/esm/PcmStreamSource.d.ts +0 -127
- package/dist/esm/PcmStreamSource.d.ts.map +0 -1
- package/dist/esm/PcmStreamSource.js +0 -308
- package/dist/esm/PcmStreamSource.js.map +0 -1
- package/dist/esm/dsp/fft.d.ts +0 -22
- package/dist/esm/dsp/fft.d.ts.map +0 -1
- package/dist/esm/dsp/mel.d.ts +0 -43
- package/dist/esm/dsp/mel.d.ts.map +0 -1
- package/dist/esm/dsp/mel.js +0 -61
- package/dist/esm/dsp/mel.js.map +0 -1
- package/dist/esm/dsp/tempogram.d.ts +0 -192
- package/dist/esm/dsp/tempogram.d.ts.map +0 -1
- package/dist/esm/effects/AutoWahEffect.d.ts +0 -128
- package/dist/esm/effects/AutoWahEffect.d.ts.map +0 -1
- package/dist/esm/effects/AutoWahEffect.js +0 -214
- package/dist/esm/effects/AutoWahEffect.js.map +0 -1
- package/dist/esm/effects/BitCrusherEffect.d.ts +0 -64
- package/dist/esm/effects/BitCrusherEffect.d.ts.map +0 -1
- package/dist/esm/effects/BitCrusherEffect.js +0 -76
- package/dist/esm/effects/BitCrusherEffect.js.map +0 -1
- package/dist/esm/effects/ChorusEffect.d.ts +0 -54
- package/dist/esm/effects/ChorusEffect.d.ts.map +0 -1
- package/dist/esm/effects/ChorusEffect.js +0 -136
- package/dist/esm/effects/ChorusEffect.js.map +0 -1
- package/dist/esm/effects/CompressorEffect.d.ts +0 -56
- package/dist/esm/effects/CompressorEffect.d.ts.map +0 -1
- package/dist/esm/effects/CompressorEffect.js +0 -108
- package/dist/esm/effects/CompressorEffect.js.map +0 -1
- package/dist/esm/effects/ConvolutionEffect.d.ts +0 -119
- package/dist/esm/effects/ConvolutionEffect.d.ts.map +0 -1
- package/dist/esm/effects/ConvolutionEffect.js +0 -212
- package/dist/esm/effects/ConvolutionEffect.js.map +0 -1
- package/dist/esm/effects/DelayEffect.d.ts +0 -36
- package/dist/esm/effects/DelayEffect.d.ts.map +0 -1
- package/dist/esm/effects/DelayEffect.js +0 -109
- package/dist/esm/effects/DelayEffect.js.map +0 -1
- package/dist/esm/effects/DistortionEffect.d.ts +0 -120
- package/dist/esm/effects/DistortionEffect.d.ts.map +0 -1
- package/dist/esm/effects/DistortionEffect.js +0 -194
- package/dist/esm/effects/DistortionEffect.js.map +0 -1
- package/dist/esm/effects/DuckingEffect.d.ts +0 -44
- package/dist/esm/effects/DuckingEffect.d.ts.map +0 -1
- package/dist/esm/effects/DuckingEffect.js +0 -95
- package/dist/esm/effects/DuckingEffect.js.map +0 -1
- package/dist/esm/effects/EqualizerEffect.d.ts +0 -51
- package/dist/esm/effects/EqualizerEffect.d.ts.map +0 -1
- package/dist/esm/effects/EqualizerEffect.js +0 -124
- package/dist/esm/effects/EqualizerEffect.js.map +0 -1
- package/dist/esm/effects/FlangerEffect.d.ts +0 -99
- package/dist/esm/effects/FlangerEffect.d.ts.map +0 -1
- package/dist/esm/effects/FlangerEffect.js +0 -176
- package/dist/esm/effects/FlangerEffect.js.map +0 -1
- package/dist/esm/effects/GranularEffect.d.ts +0 -67
- package/dist/esm/effects/GranularEffect.d.ts.map +0 -1
- package/dist/esm/effects/GranularEffect.js +0 -104
- package/dist/esm/effects/GranularEffect.js.map +0 -1
- package/dist/esm/effects/LimiterEffect.d.ts +0 -125
- package/dist/esm/effects/LimiterEffect.d.ts.map +0 -1
- package/dist/esm/effects/LimiterEffect.js +0 -186
- package/dist/esm/effects/LimiterEffect.js.map +0 -1
- package/dist/esm/effects/PhaserEffect.d.ts +0 -127
- package/dist/esm/effects/PhaserEffect.d.ts.map +0 -1
- package/dist/esm/effects/PhaserEffect.js +0 -218
- package/dist/esm/effects/PhaserEffect.js.map +0 -1
- package/dist/esm/effects/PingPongDelayEffect.d.ts +0 -84
- package/dist/esm/effects/PingPongDelayEffect.d.ts.map +0 -1
- package/dist/esm/effects/PingPongDelayEffect.js +0 -176
- package/dist/esm/effects/PingPongDelayEffect.js.map +0 -1
- package/dist/esm/effects/PitchShiftEffect.d.ts +0 -46
- package/dist/esm/effects/PitchShiftEffect.d.ts.map +0 -1
- package/dist/esm/effects/PitchShiftEffect.js +0 -64
- package/dist/esm/effects/PitchShiftEffect.js.map +0 -1
- package/dist/esm/effects/ReverbEffect.d.ts +0 -38
- package/dist/esm/effects/ReverbEffect.d.ts.map +0 -1
- package/dist/esm/effects/ReverbEffect.js +0 -117
- package/dist/esm/effects/ReverbEffect.js.map +0 -1
- package/dist/esm/effects/RingModulatorEffect.d.ts +0 -96
- package/dist/esm/effects/RingModulatorEffect.d.ts.map +0 -1
- package/dist/esm/effects/RingModulatorEffect.js +0 -157
- package/dist/esm/effects/RingModulatorEffect.js.map +0 -1
- package/dist/esm/effects/TremoloEffect.d.ts +0 -111
- package/dist/esm/effects/TremoloEffect.d.ts.map +0 -1
- package/dist/esm/effects/TremoloEffect.js +0 -197
- package/dist/esm/effects/TremoloEffect.js.map +0 -1
- package/dist/esm/effects/VocoderEffect.d.ts +0 -45
- package/dist/esm/effects/VocoderEffect.d.ts.map +0 -1
- package/dist/esm/effects/VocoderEffect.js +0 -73
- package/dist/esm/effects/VocoderEffect.js.map +0 -1
- package/dist/esm/index.d.ts +0 -25
- package/dist/esm/index.d.ts.map +0 -1
- package/dist/esm/index.js +0 -24
- package/dist/esm/worklets/beat-detector.worklet.js +0 -6
- package/dist/esm/worklets/beat-detector.worklet.js.map +0 -1
- package/dist/esm/worklets/bit-crusher.worklet.js +0 -6
- package/dist/esm/worklets/bit-crusher.worklet.js.map +0 -1
- package/dist/esm/worklets/ducking.worklet.js +0 -6
- package/dist/esm/worklets/ducking.worklet.js.map +0 -1
- package/dist/esm/worklets/granular.worklet.js +0 -6
- package/dist/esm/worklets/granular.worklet.js.map +0 -1
- package/dist/esm/worklets/pcm-stream.worklet.js +0 -6
- package/dist/esm/worklets/pcm-stream.worklet.js.map +0 -1
- package/dist/esm/worklets/pitch-shift.worklet.js +0 -6
- package/dist/esm/worklets/pitch-shift.worklet.js.map +0 -1
- package/dist/esm/worklets/vocoder.worklet.js +0 -6
- package/dist/esm/worklets/vocoder.worklet.js.map +0 -1
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
import vocoder_worklet_default from "../worklets/vocoder.worklet.js";
|
|
2
|
-
import { WorkletEffect } from "@codexo/exojs";
|
|
3
|
-
|
|
4
|
-
//#region src/effects/VocoderEffect.ts
|
|
5
|
-
/**
|
|
6
|
-
* Phase-vocoder-style effect implemented as a {@link WorkletEffect}. Analyzes
|
|
7
|
-
* the spectral envelope of a `modulator` {@link AudioBus} across a bank of
|
|
8
|
-
* log-spaced bandpass filters and applies that envelope to the carrier signal
|
|
9
|
-
* (the main input). The result is the classic "robot voice" or talking-synth
|
|
10
|
-
* effect. Band count, frequency range, and Q are compile-time parameters set
|
|
11
|
-
* at construction; only `wet` and `envelopeSmoothing` are adjustable at
|
|
12
|
-
* runtime.
|
|
13
|
-
*/
|
|
14
|
-
var VocoderEffect = class extends WorkletEffect {
|
|
15
|
-
_modulator = null;
|
|
16
|
-
_numBands;
|
|
17
|
-
_minHz;
|
|
18
|
-
_maxHz;
|
|
19
|
-
_bandQ;
|
|
20
|
-
_envelopeSmoothing;
|
|
21
|
-
constructor(options) {
|
|
22
|
-
super();
|
|
23
|
-
if (!options.modulator) throw new Error("VocoderEffect requires a modulator AudioBus.");
|
|
24
|
-
this._modulator = options.modulator;
|
|
25
|
-
this._numBands = options.numBands ?? 16;
|
|
26
|
-
this._minHz = options.minHz ?? 80;
|
|
27
|
-
this._maxHz = options.maxHz ?? 8e3;
|
|
28
|
-
this._bandQ = options.bandQ ?? 4;
|
|
29
|
-
this._envelopeSmoothing = Math.max(1e-4, Math.min(.1, options.envelopeSmoothing ?? .005));
|
|
30
|
-
this.wet = options.wet ?? 1;
|
|
31
|
-
}
|
|
32
|
-
get _workletName() {
|
|
33
|
-
return "exojs-vocoder";
|
|
34
|
-
}
|
|
35
|
-
get _workletSource() {
|
|
36
|
-
return vocoder_worklet_default;
|
|
37
|
-
}
|
|
38
|
-
get _workletOptions() {
|
|
39
|
-
return {
|
|
40
|
-
numberOfInputs: 2,
|
|
41
|
-
numberOfOutputs: 1,
|
|
42
|
-
processorOptions: {
|
|
43
|
-
numBands: this._numBands,
|
|
44
|
-
minHz: this._minHz,
|
|
45
|
-
maxHz: this._maxHz,
|
|
46
|
-
bandQ: this._bandQ
|
|
47
|
-
}
|
|
48
|
-
};
|
|
49
|
-
}
|
|
50
|
-
_onWorkletReady(_audioContext) {
|
|
51
|
-
if (!this._modulator) return;
|
|
52
|
-
this._setAudioParam("envelopeSmoothing", this._envelopeSmoothing);
|
|
53
|
-
const modulator = this._modulator;
|
|
54
|
-
const modOutput = modulator.getOutputNode();
|
|
55
|
-
if (modOutput && this._workletNode) modOutput.connect(this._workletNode, 0, 1);
|
|
56
|
-
else modulator.onceSetup(() => {
|
|
57
|
-
const node = modulator.getOutputNode();
|
|
58
|
-
if (node && this._workletNode) node.connect(this._workletNode, 0, 1);
|
|
59
|
-
});
|
|
60
|
-
}
|
|
61
|
-
/** One-pole envelope follower coefficient. Smaller values produce slower, smoother envelope tracking. Range 0.0001..0.1, default 0.005. */
|
|
62
|
-
get envelopeSmoothing() {
|
|
63
|
-
return this._envelopeSmoothing;
|
|
64
|
-
}
|
|
65
|
-
set envelopeSmoothing(value) {
|
|
66
|
-
this._envelopeSmoothing = Math.max(1e-4, Math.min(.1, value));
|
|
67
|
-
this._setAudioParam("envelopeSmoothing", this._envelopeSmoothing);
|
|
68
|
-
}
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
//#endregion
|
|
72
|
-
export { VocoderEffect };
|
|
73
|
-
//# sourceMappingURL=VocoderEffect.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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"}
|
package/dist/esm/index.d.ts
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
export type { AudioAnalyserOptions, AudioAnalyserSource, SpectrumMappingOptions } from './AudioAnalyser';
|
|
2
|
-
export { AudioAnalyser } from './AudioAnalyser';
|
|
3
|
-
export type { BandEnergy, BarInfo, BeatDetectorOptions, BeatDetectorSource, BeatInfo, TempoCandidate, TimeSignature, UpcomingBeat } from './BeatDetector';
|
|
4
|
-
export { BeatDetector } from './BeatDetector';
|
|
5
|
-
export { AutoWahEffect, type AutoWahEffectOptions } from './effects/AutoWahEffect';
|
|
6
|
-
export { BitCrusherEffect, type BitCrusherEffectOptions } from './effects/BitCrusherEffect';
|
|
7
|
-
export { ChorusEffect, type ChorusEffectOptions } from './effects/ChorusEffect';
|
|
8
|
-
export { CompressorEffect, type CompressorEffectOptions } from './effects/CompressorEffect';
|
|
9
|
-
export { ConvolutionEffect, type ConvolutionEffectOptions } from './effects/ConvolutionEffect';
|
|
10
|
-
export { DelayEffect, type DelayEffectOptions } from './effects/DelayEffect';
|
|
11
|
-
export { DistortionEffect, type DistortionEffectOptions } from './effects/DistortionEffect';
|
|
12
|
-
export { DuckingEffect, type DuckingEffectOptions } from './effects/DuckingEffect';
|
|
13
|
-
export { EqualizerEffect, type EqualizerEffectOptions } from './effects/EqualizerEffect';
|
|
14
|
-
export { FlangerEffect, type FlangerEffectOptions } from './effects/FlangerEffect';
|
|
15
|
-
export { GranularEffect, type GranularEffectOptions } from './effects/GranularEffect';
|
|
16
|
-
export { LimiterEffect, type LimiterEffectOptions } from './effects/LimiterEffect';
|
|
17
|
-
export { PhaserEffect, type PhaserEffectOptions } from './effects/PhaserEffect';
|
|
18
|
-
export { PingPongDelayEffect, type PingPongDelayEffectOptions } from './effects/PingPongDelayEffect';
|
|
19
|
-
export { PitchShiftEffect, type PitchShiftEffectOptions } from './effects/PitchShiftEffect';
|
|
20
|
-
export { ReverbEffect, type ReverbEffectOptions } from './effects/ReverbEffect';
|
|
21
|
-
export { RingModulatorEffect, type RingModulatorEffectOptions } from './effects/RingModulatorEffect';
|
|
22
|
-
export { TremoloEffect, type TremoloEffectOptions } from './effects/TremoloEffect';
|
|
23
|
-
export { VocoderEffect, type VocoderEffectOptions } from './effects/VocoderEffect';
|
|
24
|
-
export { PcmStreamSource, type PcmStreamSourceOptions, type PcmStreamState } from './PcmStreamSource';
|
|
25
|
-
//# sourceMappingURL=index.d.ts.map
|
package/dist/esm/index.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAIA,YAAY,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AACzG,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,YAAY,EAAE,UAAU,EAAE,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,QAAQ,EAAE,cAAc,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC1J,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,KAAK,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACnF,OAAO,EAAE,gBAAgB,EAAE,KAAK,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAC5F,OAAO,EAAE,YAAY,EAAE,KAAK,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,gBAAgB,EAAE,KAAK,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAC5F,OAAO,EAAE,iBAAiB,EAAE,KAAK,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAC/F,OAAO,EAAE,WAAW,EAAE,KAAK,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,KAAK,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAC5F,OAAO,EAAE,aAAa,EAAE,KAAK,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,KAAK,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACzF,OAAO,EAAE,aAAa,EAAE,KAAK,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACnF,OAAO,EAAE,cAAc,EAAE,KAAK,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACtF,OAAO,EAAE,aAAa,EAAE,KAAK,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACnF,OAAO,EAAE,YAAY,EAAE,KAAK,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,mBAAmB,EAAE,KAAK,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AACrG,OAAO,EAAE,gBAAgB,EAAE,KAAK,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAC5F,OAAO,EAAE,YAAY,EAAE,KAAK,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,mBAAmB,EAAE,KAAK,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AACrG,OAAO,EAAE,aAAa,EAAE,KAAK,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACnF,OAAO,EAAE,aAAa,EAAE,KAAK,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,KAAK,sBAAsB,EAAE,KAAK,cAAc,EAAE,MAAM,mBAAmB,CAAC"}
|
package/dist/esm/index.js
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { AudioAnalyser } from "./AudioAnalyser.js";
|
|
2
|
-
import { BeatDetector } from "./BeatDetector.js";
|
|
3
|
-
import { AutoWahEffect } from "./effects/AutoWahEffect.js";
|
|
4
|
-
import { BitCrusherEffect } from "./effects/BitCrusherEffect.js";
|
|
5
|
-
import { ChorusEffect } from "./effects/ChorusEffect.js";
|
|
6
|
-
import { CompressorEffect } from "./effects/CompressorEffect.js";
|
|
7
|
-
import { ConvolutionEffect } from "./effects/ConvolutionEffect.js";
|
|
8
|
-
import { DelayEffect } from "./effects/DelayEffect.js";
|
|
9
|
-
import { DistortionEffect } from "./effects/DistortionEffect.js";
|
|
10
|
-
import { DuckingEffect } from "./effects/DuckingEffect.js";
|
|
11
|
-
import { EqualizerEffect } from "./effects/EqualizerEffect.js";
|
|
12
|
-
import { FlangerEffect } from "./effects/FlangerEffect.js";
|
|
13
|
-
import { GranularEffect } from "./effects/GranularEffect.js";
|
|
14
|
-
import { LimiterEffect } from "./effects/LimiterEffect.js";
|
|
15
|
-
import { PhaserEffect } from "./effects/PhaserEffect.js";
|
|
16
|
-
import { PingPongDelayEffect } from "./effects/PingPongDelayEffect.js";
|
|
17
|
-
import { PitchShiftEffect } from "./effects/PitchShiftEffect.js";
|
|
18
|
-
import { ReverbEffect } from "./effects/ReverbEffect.js";
|
|
19
|
-
import { RingModulatorEffect } from "./effects/RingModulatorEffect.js";
|
|
20
|
-
import { TremoloEffect } from "./effects/TremoloEffect.js";
|
|
21
|
-
import { VocoderEffect } from "./effects/VocoderEffect.js";
|
|
22
|
-
import { PcmStreamSource } from "./PcmStreamSource.js";
|
|
23
|
-
|
|
24
|
-
export { AudioAnalyser, AutoWahEffect, BeatDetector, BitCrusherEffect, ChorusEffect, CompressorEffect, ConvolutionEffect, DelayEffect, DistortionEffect, DuckingEffect, EqualizerEffect, FlangerEffect, GranularEffect, LimiterEffect, PcmStreamSource, PhaserEffect, PingPongDelayEffect, PitchShiftEffect, ReverbEffect, RingModulatorEffect, TremoloEffect, VocoderEffect };
|
|
@@ -1,6 +0,0 @@
|
|
|
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 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
|
-
|
|
4
|
-
//#endregion
|
|
5
|
-
export { beat_detector_worklet_default as default };
|
|
6
|
-
//# sourceMappingURL=beat-detector.worklet.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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"}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
//#region src/worklets/bit-crusher.worklet.ts?worklet
|
|
2
|
-
var bit_crusher_worklet_default = "\"use strict\";\n(() => {\n // bit-crusher.worklet.ts\n var BitCrusherProcessor = class extends AudioWorkletProcessor {\n static get parameterDescriptors() {\n return [\n { name: \"bits\", defaultValue: 8, minValue: 1, maxValue: 16, automationRate: \"k-rate\" },\n { name: \"normFreq\", defaultValue: 0.5, minValue: 0, maxValue: 1, automationRate: \"k-rate\" }\n ];\n }\n // Phase accumulator for sample-and-hold; `_held` keeps the last latched value.\n _phase = 0;\n _held = 0;\n process(inputs, outputs, parameters) {\n const input = inputs[0]?.[0];\n const output = outputs[0]?.[0];\n if (!input || !output) return true;\n const bitsParam = parameters[\"bits\"]?.[0] ?? 8;\n const normFreqParam = parameters[\"normFreq\"]?.[0] ?? 0.5;\n const bits = Math.round(Math.max(1, Math.min(16, bitsParam)));\n const normFreq = Math.max(0, Math.min(1, normFreqParam));\n const step = 2 / Math.pow(2, bits);\n for (let i = 0; i < input.length; i++) {\n this._phase += normFreq;\n if (this._phase >= 1) {\n this._phase -= 1;\n this._held = step * Math.round(input[i] / step);\n }\n output[i] = this._held;\n }\n return true;\n }\n };\n registerProcessor(\"exojs-bit-crusher\", BitCrusherProcessor);\n})();\n";
|
|
3
|
-
|
|
4
|
-
//#endregion
|
|
5
|
-
export { bit_crusher_worklet_default as default };
|
|
6
|
-
//# sourceMappingURL=bit-crusher.worklet.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"bit-crusher.worklet.js","names":[],"sources":["../../../src/worklets/bit-crusher.worklet.ts?worklet"],"sourcesContent":["export default \"\\\"use strict\\\";\\n(() => {\\n // bit-crusher.worklet.ts\\n var BitCrusherProcessor = class extends AudioWorkletProcessor {\\n static get parameterDescriptors() {\\n return [\\n { name: \\\"bits\\\", defaultValue: 8, minValue: 1, maxValue: 16, automationRate: \\\"k-rate\\\" },\\n { name: \\\"normFreq\\\", defaultValue: 0.5, minValue: 0, maxValue: 1, automationRate: \\\"k-rate\\\" }\\n ];\\n }\\n // Phase accumulator for sample-and-hold; `_held` keeps the last latched value.\\n _phase = 0;\\n _held = 0;\\n process(inputs, outputs, parameters) {\\n const input = inputs[0]?.[0];\\n const output = outputs[0]?.[0];\\n if (!input || !output) return true;\\n const bitsParam = parameters[\\\"bits\\\"]?.[0] ?? 8;\\n const normFreqParam = parameters[\\\"normFreq\\\"]?.[0] ?? 0.5;\\n const bits = Math.round(Math.max(1, Math.min(16, bitsParam)));\\n const normFreq = Math.max(0, Math.min(1, normFreqParam));\\n const step = 2 / Math.pow(2, bits);\\n for (let i = 0; i < input.length; i++) {\\n this._phase += normFreq;\\n if (this._phase >= 1) {\\n this._phase -= 1;\\n this._held = step * Math.round(input[i] / step);\\n }\\n output[i] = this._held;\\n }\\n return true;\\n }\\n };\\n registerProcessor(\\\"exojs-bit-crusher\\\", BitCrusherProcessor);\\n})();\\n\";"],"mappings":";AAAA,kCAAe"}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
//#region src/worklets/ducking.worklet.ts?worklet
|
|
2
|
-
var ducking_worklet_default = "\"use strict\";\n(() => {\n // ducking.worklet.ts\n var DuckingProcessor = class extends AudioWorkletProcessor {\n static get parameterDescriptors() {\n return [\n { name: \"threshold\", defaultValue: -20, minValue: -100, maxValue: 0, automationRate: \"k-rate\" },\n { name: \"ratio\", defaultValue: 4, minValue: 1, maxValue: 20, automationRate: \"k-rate\" },\n // attack/release are one-pole smoothing coefficients (1 - exp(-1/tau)),\n // not times - their value lives in [0, 1]. A 0.001 floor clipped the\n // small coefficients of typical attack/release times (e.g. 30 ms at\n // 48 kHz ≈ 0.0007), so the browser clamped them and logged a warning.\n { name: \"attack\", defaultValue: 0.03, minValue: 0, maxValue: 1, automationRate: \"k-rate\" },\n { name: \"release\", defaultValue: 0.3, minValue: 0, maxValue: 1, automationRate: \"k-rate\" }\n ];\n }\n _envelope = 0;\n process(inputs, outputs, parameters) {\n const main = inputs[0];\n const sidechain = inputs[1];\n const output = outputs[0];\n if (!main || main.length === 0 || !output || output.length === 0) {\n return true;\n }\n const threshold = parameters[\"threshold\"][0];\n const ratio = parameters[\"ratio\"][0];\n const attackCoeff = parameters[\"attack\"][0];\n const releaseCoeff = parameters[\"release\"][0];\n const blockLength = main[0]?.length ?? 0;\n for (let i = 0; i < blockLength; i++) {\n let scSample = 0;\n if (sidechain && sidechain.length > 0) {\n const left = sidechain[0]?.[i] ?? 0;\n const right = sidechain[1]?.[i] ?? left;\n scSample = (Math.abs(left) + Math.abs(right)) * 0.5;\n }\n const coeff = scSample > this._envelope ? attackCoeff : releaseCoeff;\n this._envelope += (scSample - this._envelope) * coeff;\n const envDb = 20 * Math.log10(this._envelope + 1e-9);\n const overshoot = Math.max(0, envDb - threshold);\n const reduction = overshoot * (1 - 1 / ratio);\n const gain = Math.pow(10, -reduction / 20);\n for (let ch = 0; ch < main.length; ch++) {\n const mainCh = main[ch];\n const outCh = output[ch];\n if (mainCh && outCh && i < mainCh.length) {\n outCh[i] = mainCh[i] * gain;\n }\n }\n }\n return true;\n }\n };\n registerProcessor(\"exojs-ducking\", DuckingProcessor);\n})();\n";
|
|
3
|
-
|
|
4
|
-
//#endregion
|
|
5
|
-
export { ducking_worklet_default as default };
|
|
6
|
-
//# sourceMappingURL=ducking.worklet.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ducking.worklet.js","names":[],"sources":["../../../src/worklets/ducking.worklet.ts?worklet"],"sourcesContent":["export default \"\\\"use strict\\\";\\n(() => {\\n // ducking.worklet.ts\\n var DuckingProcessor = class extends AudioWorkletProcessor {\\n static get parameterDescriptors() {\\n return [\\n { name: \\\"threshold\\\", defaultValue: -20, minValue: -100, maxValue: 0, automationRate: \\\"k-rate\\\" },\\n { name: \\\"ratio\\\", defaultValue: 4, minValue: 1, maxValue: 20, automationRate: \\\"k-rate\\\" },\\n // attack/release are one-pole smoothing coefficients (1 - exp(-1/tau)),\\n // not times - their value lives in [0, 1]. A 0.001 floor clipped the\\n // small coefficients of typical attack/release times (e.g. 30 ms at\\n // 48 kHz ≈ 0.0007), so the browser clamped them and logged a warning.\\n { name: \\\"attack\\\", defaultValue: 0.03, minValue: 0, maxValue: 1, automationRate: \\\"k-rate\\\" },\\n { name: \\\"release\\\", defaultValue: 0.3, minValue: 0, maxValue: 1, automationRate: \\\"k-rate\\\" }\\n ];\\n }\\n _envelope = 0;\\n process(inputs, outputs, parameters) {\\n const main = inputs[0];\\n const sidechain = inputs[1];\\n const output = outputs[0];\\n if (!main || main.length === 0 || !output || output.length === 0) {\\n return true;\\n }\\n const threshold = parameters[\\\"threshold\\\"][0];\\n const ratio = parameters[\\\"ratio\\\"][0];\\n const attackCoeff = parameters[\\\"attack\\\"][0];\\n const releaseCoeff = parameters[\\\"release\\\"][0];\\n const blockLength = main[0]?.length ?? 0;\\n for (let i = 0; i < blockLength; i++) {\\n let scSample = 0;\\n if (sidechain && sidechain.length > 0) {\\n const left = sidechain[0]?.[i] ?? 0;\\n const right = sidechain[1]?.[i] ?? left;\\n scSample = (Math.abs(left) + Math.abs(right)) * 0.5;\\n }\\n const coeff = scSample > this._envelope ? attackCoeff : releaseCoeff;\\n this._envelope += (scSample - this._envelope) * coeff;\\n const envDb = 20 * Math.log10(this._envelope + 1e-9);\\n const overshoot = Math.max(0, envDb - threshold);\\n const reduction = overshoot * (1 - 1 / ratio);\\n const gain = Math.pow(10, -reduction / 20);\\n for (let ch = 0; ch < main.length; ch++) {\\n const mainCh = main[ch];\\n const outCh = output[ch];\\n if (mainCh && outCh && i < mainCh.length) {\\n outCh[i] = mainCh[i] * gain;\\n }\\n }\\n }\\n return true;\\n }\\n };\\n registerProcessor(\\\"exojs-ducking\\\", DuckingProcessor);\\n})();\\n\";"],"mappings":";AAAA,8BAAe"}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
//#region src/worklets/granular.worklet.ts?worklet
|
|
2
|
-
var granular_worklet_default = "\"use strict\";\n(() => {\n // granular.worklet.ts\n var sampleRate = globalThis.sampleRate;\n var GranularProcessor = class extends AudioWorkletProcessor {\n static get parameterDescriptors() {\n return [\n { name: \"grainSize\", defaultValue: 0.05, minValue: 5e-3, maxValue: 0.5, automationRate: \"k-rate\" },\n { name: \"density\", defaultValue: 50, minValue: 1, maxValue: 500, automationRate: \"k-rate\" },\n { name: \"spread\", defaultValue: 0.5, minValue: 0, maxValue: 1, automationRate: \"k-rate\" },\n { name: \"pitchMin\", defaultValue: 1, minValue: 0.25, maxValue: 4, automationRate: \"k-rate\" },\n { name: \"pitchMax\", defaultValue: 1, minValue: 0.25, maxValue: 4, automationRate: \"k-rate\" }\n ];\n }\n _bufferLength;\n _buffer;\n _writePos = 0;\n _timeUntilNextGrainSamples = 0;\n _grains = [];\n _normalizeGain;\n constructor(options) {\n super();\n const opts = options?.processorOptions ?? {};\n const bufferSeconds = opts.bufferSeconds ?? 2;\n this._bufferLength = Math.floor(bufferSeconds * sampleRate);\n this._buffer = new Float32Array(this._bufferLength);\n this._normalizeGain = opts.normalizeGain ?? false;\n }\n process(inputs, outputs, parameters) {\n const input = inputs[0]?.[0];\n const output = outputs[0]?.[0];\n if (!input || !output) return true;\n const grainSize = parameters[\"grainSize\"][0];\n const density = parameters[\"density\"][0];\n const spread = parameters[\"spread\"][0];\n const pitchMin = parameters[\"pitchMin\"][0];\n const pitchMax = parameters[\"pitchMax\"][0];\n const grainSizeSamples = Math.max(8, Math.floor(grainSize * sampleRate));\n const samplesPerGrain = sampleRate / Math.max(1, density);\n let normFactor = 1;\n if (this._normalizeGain) {\n const expectedGrains = density * grainSize;\n normFactor = 1 / (0.6123724356957945 * Math.sqrt(Math.max(1e-6, expectedGrains)));\n }\n for (let i = 0; i < input.length; i++) {\n this._buffer[this._writePos] = input[i];\n this._writePos = (this._writePos + 1) % this._bufferLength;\n this._timeUntilNextGrainSamples -= 1;\n if (this._timeUntilNextGrainSamples <= 0) {\n const maxOffset = Math.floor(spread * this._bufferLength);\n const offset = Math.floor(Math.random() * Math.max(1, maxOffset));\n const startPos = (this._writePos - offset - grainSizeSamples + this._bufferLength) % this._bufferLength;\n const pitch = pitchMin + Math.random() * Math.max(0, pitchMax - pitchMin);\n this._grains.push({ startPos, ageSamples: 0, lengthSamples: grainSizeSamples, pitch });\n this._timeUntilNextGrainSamples = samplesPerGrain;\n }\n let grainSum = 0;\n for (let g = this._grains.length - 1; g >= 0; g--) {\n const grain = this._grains[g];\n if (grain.ageSamples >= grain.lengthSamples) {\n this._grains.splice(g, 1);\n continue;\n }\n const phase = grain.ageSamples / grain.lengthSamples;\n const window = 0.5 * (1 - Math.cos(2 * Math.PI * phase));\n const readPos = grain.startPos + grain.ageSamples * grain.pitch;\n const sampleIndex = Math.floor(readPos) % this._bufferLength;\n const safeIndex = (sampleIndex + this._bufferLength) % this._bufferLength;\n grainSum += this._buffer[safeIndex] * window;\n grain.ageSamples++;\n }\n output[i] = grainSum * normFactor;\n }\n return true;\n }\n };\n registerProcessor(\"exojs-granular\", GranularProcessor);\n})();\n";
|
|
3
|
-
|
|
4
|
-
//#endregion
|
|
5
|
-
export { granular_worklet_default as default };
|
|
6
|
-
//# sourceMappingURL=granular.worklet.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"granular.worklet.js","names":[],"sources":["../../../src/worklets/granular.worklet.ts?worklet"],"sourcesContent":["export default \"\\\"use strict\\\";\\n(() => {\\n // granular.worklet.ts\\n var sampleRate = globalThis.sampleRate;\\n var GranularProcessor = class extends AudioWorkletProcessor {\\n static get parameterDescriptors() {\\n return [\\n { name: \\\"grainSize\\\", defaultValue: 0.05, minValue: 5e-3, maxValue: 0.5, automationRate: \\\"k-rate\\\" },\\n { name: \\\"density\\\", defaultValue: 50, minValue: 1, maxValue: 500, automationRate: \\\"k-rate\\\" },\\n { name: \\\"spread\\\", defaultValue: 0.5, minValue: 0, maxValue: 1, automationRate: \\\"k-rate\\\" },\\n { name: \\\"pitchMin\\\", defaultValue: 1, minValue: 0.25, maxValue: 4, automationRate: \\\"k-rate\\\" },\\n { name: \\\"pitchMax\\\", defaultValue: 1, minValue: 0.25, maxValue: 4, automationRate: \\\"k-rate\\\" }\\n ];\\n }\\n _bufferLength;\\n _buffer;\\n _writePos = 0;\\n _timeUntilNextGrainSamples = 0;\\n _grains = [];\\n _normalizeGain;\\n constructor(options) {\\n super();\\n const opts = options?.processorOptions ?? {};\\n const bufferSeconds = opts.bufferSeconds ?? 2;\\n this._bufferLength = Math.floor(bufferSeconds * sampleRate);\\n this._buffer = new Float32Array(this._bufferLength);\\n this._normalizeGain = opts.normalizeGain ?? false;\\n }\\n process(inputs, outputs, parameters) {\\n const input = inputs[0]?.[0];\\n const output = outputs[0]?.[0];\\n if (!input || !output) return true;\\n const grainSize = parameters[\\\"grainSize\\\"][0];\\n const density = parameters[\\\"density\\\"][0];\\n const spread = parameters[\\\"spread\\\"][0];\\n const pitchMin = parameters[\\\"pitchMin\\\"][0];\\n const pitchMax = parameters[\\\"pitchMax\\\"][0];\\n const grainSizeSamples = Math.max(8, Math.floor(grainSize * sampleRate));\\n const samplesPerGrain = sampleRate / Math.max(1, density);\\n let normFactor = 1;\\n if (this._normalizeGain) {\\n const expectedGrains = density * grainSize;\\n normFactor = 1 / (0.6123724356957945 * Math.sqrt(Math.max(1e-6, expectedGrains)));\\n }\\n for (let i = 0; i < input.length; i++) {\\n this._buffer[this._writePos] = input[i];\\n this._writePos = (this._writePos + 1) % this._bufferLength;\\n this._timeUntilNextGrainSamples -= 1;\\n if (this._timeUntilNextGrainSamples <= 0) {\\n const maxOffset = Math.floor(spread * this._bufferLength);\\n const offset = Math.floor(Math.random() * Math.max(1, maxOffset));\\n const startPos = (this._writePos - offset - grainSizeSamples + this._bufferLength) % this._bufferLength;\\n const pitch = pitchMin + Math.random() * Math.max(0, pitchMax - pitchMin);\\n this._grains.push({ startPos, ageSamples: 0, lengthSamples: grainSizeSamples, pitch });\\n this._timeUntilNextGrainSamples = samplesPerGrain;\\n }\\n let grainSum = 0;\\n for (let g = this._grains.length - 1; g >= 0; g--) {\\n const grain = this._grains[g];\\n if (grain.ageSamples >= grain.lengthSamples) {\\n this._grains.splice(g, 1);\\n continue;\\n }\\n const phase = grain.ageSamples / grain.lengthSamples;\\n const window = 0.5 * (1 - Math.cos(2 * Math.PI * phase));\\n const readPos = grain.startPos + grain.ageSamples * grain.pitch;\\n const sampleIndex = Math.floor(readPos) % this._bufferLength;\\n const safeIndex = (sampleIndex + this._bufferLength) % this._bufferLength;\\n grainSum += this._buffer[safeIndex] * window;\\n grain.ageSamples++;\\n }\\n output[i] = grainSum * normFactor;\\n }\\n return true;\\n }\\n };\\n registerProcessor(\\\"exojs-granular\\\", GranularProcessor);\\n})();\\n\";"],"mappings":";AAAA,+BAAe"}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
//#region src/worklets/pcm-stream.worklet.ts?worklet
|
|
2
|
-
var pcm_stream_worklet_default = "\"use strict\";\n(() => {\n // pcm-stream.worklet.ts\n var PcmStreamProcessor = class extends AudioWorkletProcessor {\n _channels;\n _capacity;\n _ring;\n _read = 0;\n _write = 0;\n _queued = 0;\n _startFrame = null;\n _closed = false;\n _destroyed = false;\n _starving = false;\n _statusPending = false;\n _dirty = false;\n _telemetry = {\n type: \"status\",\n releasedFrames: 0,\n playedFrames: 0,\n underrunFrames: 0,\n underruns: 0\n };\n constructor(options) {\n super(options);\n const config = options.processorOptions;\n this._channels = config.channels;\n this._capacity = config.capacityFrames;\n this._ring = Array.from({ length: this._channels }, () => new Float32Array(this._capacity));\n this.port.onmessage = (event) => {\n const message = event.data;\n switch (message.type) {\n case \"write\":\n this._enqueue(message.data);\n break;\n case \"start\":\n if (this._startFrame === null && Number.isFinite(message.time)) this._startFrame = Math.ceil(message.time * sampleRate);\n break;\n case \"ack\":\n this._statusPending = false;\n break;\n case \"clear\":\n this._clear();\n this._send(\"cleared\");\n break;\n case \"close\":\n this._closed = true;\n this._startFrame ??= currentFrame;\n break;\n case \"destroy\":\n this._clear();\n this._destroyed = true;\n this.port.onmessage = null;\n break;\n }\n };\n }\n _enqueue(data) {\n if (!(data instanceof Float32Array)) return;\n const frames = Math.floor(data.length / this._channels);\n if (this._closed || data.length % this._channels !== 0 || frames > this._capacity - this._queued) {\n this._telemetry.releasedFrames += frames;\n this._dirty ||= frames > 0;\n return;\n }\n for (let channel = 0; channel < this._channels; channel++) {\n const ring = this._ring[channel];\n const offset = channel * frames;\n for (let frame = 0; frame < frames; frame++) ring[(this._write + frame) % this._capacity] = data[offset + frame];\n }\n this._write = (this._write + frames) % this._capacity;\n this._queued += frames;\n }\n _clear() {\n this._telemetry.releasedFrames += this._queued;\n this._queued = 0;\n this._read = 0;\n this._write = 0;\n }\n _send(type) {\n this._telemetry.type = type;\n this.port.postMessage(this._telemetry);\n this._dirty = false;\n if (type === \"status\") this._statusPending = true;\n }\n process(_inputs, outputs) {\n const output = outputs[0];\n if (output) {\n for (let channel = 0; channel < output.length; channel++) output[channel].fill(0);\n }\n if (this._destroyed) return false;\n const quantum = output?.[0]?.length ?? 0;\n if (this._startFrame !== null) {\n const offset = Math.min(quantum, Math.max(0, this._startFrame - currentFrame));\n const available = quantum - offset;\n const played = Math.min(available, this._queued);\n if (played > 0) {\n for (let channel = 0; channel < this._channels; channel++) {\n const target = output?.[channel];\n if (!target) continue;\n const ring = this._ring[channel];\n for (let frame = 0; frame < played; frame++) target[offset + frame] = ring[(this._read + frame) % this._capacity];\n }\n this._read = (this._read + played) % this._capacity;\n this._queued -= played;\n this._telemetry.playedFrames += played;\n this._telemetry.releasedFrames += played;\n this._starving = false;\n this._dirty = true;\n }\n const missing = available - played;\n if (missing > 0 && !this._closed) {\n this._telemetry.underrunFrames += missing;\n if (!this._starving) this._telemetry.underruns++;\n this._starving = true;\n this._dirty = true;\n }\n }\n if (this._closed && this._queued === 0) {\n this._send(\"ended\");\n this._destroyed = true;\n this.port.onmessage = null;\n return false;\n }\n if (this._dirty && !this._statusPending) this._send(\"status\");\n return true;\n }\n };\n registerProcessor(\"exojs-pcm-stream\", PcmStreamProcessor);\n})();\n";
|
|
3
|
-
|
|
4
|
-
//#endregion
|
|
5
|
-
export { pcm_stream_worklet_default as default };
|
|
6
|
-
//# sourceMappingURL=pcm-stream.worklet.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"pcm-stream.worklet.js","names":[],"sources":["../../../src/worklets/pcm-stream.worklet.ts?worklet"],"sourcesContent":["export default \"\\\"use strict\\\";\\n(() => {\\n // pcm-stream.worklet.ts\\n var PcmStreamProcessor = class extends AudioWorkletProcessor {\\n _channels;\\n _capacity;\\n _ring;\\n _read = 0;\\n _write = 0;\\n _queued = 0;\\n _startFrame = null;\\n _closed = false;\\n _destroyed = false;\\n _starving = false;\\n _statusPending = false;\\n _dirty = false;\\n _telemetry = {\\n type: \\\"status\\\",\\n releasedFrames: 0,\\n playedFrames: 0,\\n underrunFrames: 0,\\n underruns: 0\\n };\\n constructor(options) {\\n super(options);\\n const config = options.processorOptions;\\n this._channels = config.channels;\\n this._capacity = config.capacityFrames;\\n this._ring = Array.from({ length: this._channels }, () => new Float32Array(this._capacity));\\n this.port.onmessage = (event) => {\\n const message = event.data;\\n switch (message.type) {\\n case \\\"write\\\":\\n this._enqueue(message.data);\\n break;\\n case \\\"start\\\":\\n if (this._startFrame === null && Number.isFinite(message.time)) this._startFrame = Math.ceil(message.time * sampleRate);\\n break;\\n case \\\"ack\\\":\\n this._statusPending = false;\\n break;\\n case \\\"clear\\\":\\n this._clear();\\n this._send(\\\"cleared\\\");\\n break;\\n case \\\"close\\\":\\n this._closed = true;\\n this._startFrame ??= currentFrame;\\n break;\\n case \\\"destroy\\\":\\n this._clear();\\n this._destroyed = true;\\n this.port.onmessage = null;\\n break;\\n }\\n };\\n }\\n _enqueue(data) {\\n if (!(data instanceof Float32Array)) return;\\n const frames = Math.floor(data.length / this._channels);\\n if (this._closed || data.length % this._channels !== 0 || frames > this._capacity - this._queued) {\\n this._telemetry.releasedFrames += frames;\\n this._dirty ||= frames > 0;\\n return;\\n }\\n for (let channel = 0; channel < this._channels; channel++) {\\n const ring = this._ring[channel];\\n const offset = channel * frames;\\n for (let frame = 0; frame < frames; frame++) ring[(this._write + frame) % this._capacity] = data[offset + frame];\\n }\\n this._write = (this._write + frames) % this._capacity;\\n this._queued += frames;\\n }\\n _clear() {\\n this._telemetry.releasedFrames += this._queued;\\n this._queued = 0;\\n this._read = 0;\\n this._write = 0;\\n }\\n _send(type) {\\n this._telemetry.type = type;\\n this.port.postMessage(this._telemetry);\\n this._dirty = false;\\n if (type === \\\"status\\\") this._statusPending = true;\\n }\\n process(_inputs, outputs) {\\n const output = outputs[0];\\n if (output) {\\n for (let channel = 0; channel < output.length; channel++) output[channel].fill(0);\\n }\\n if (this._destroyed) return false;\\n const quantum = output?.[0]?.length ?? 0;\\n if (this._startFrame !== null) {\\n const offset = Math.min(quantum, Math.max(0, this._startFrame - currentFrame));\\n const available = quantum - offset;\\n const played = Math.min(available, this._queued);\\n if (played > 0) {\\n for (let channel = 0; channel < this._channels; channel++) {\\n const target = output?.[channel];\\n if (!target) continue;\\n const ring = this._ring[channel];\\n for (let frame = 0; frame < played; frame++) target[offset + frame] = ring[(this._read + frame) % this._capacity];\\n }\\n this._read = (this._read + played) % this._capacity;\\n this._queued -= played;\\n this._telemetry.playedFrames += played;\\n this._telemetry.releasedFrames += played;\\n this._starving = false;\\n this._dirty = true;\\n }\\n const missing = available - played;\\n if (missing > 0 && !this._closed) {\\n this._telemetry.underrunFrames += missing;\\n if (!this._starving) this._telemetry.underruns++;\\n this._starving = true;\\n this._dirty = true;\\n }\\n }\\n if (this._closed && this._queued === 0) {\\n this._send(\\\"ended\\\");\\n this._destroyed = true;\\n this.port.onmessage = null;\\n return false;\\n }\\n if (this._dirty && !this._statusPending) this._send(\\\"status\\\");\\n return true;\\n }\\n };\\n registerProcessor(\\\"exojs-pcm-stream\\\", PcmStreamProcessor);\\n})();\\n\";"],"mappings":";AAAA,iCAAe"}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
//#region src/worklets/pitch-shift.worklet.ts?worklet
|
|
2
|
-
var pitch_shift_worklet_default = "\"use strict\";\n(() => {\n // pitch-shift.worklet.ts\n var PitchShiftProcessor = class extends AudioWorkletProcessor {\n static get parameterDescriptors() {\n return [{ name: \"pitch\", defaultValue: 1, minValue: 0.25, maxValue: 4, automationRate: \"k-rate\" }];\n }\n _frameLen;\n // analysis/synthesis frame\n _hop;\n // synthesis hop (50% overlap)\n _overlap;\n _seek;\n // correlation search radius (±)\n _win;\n // Input ring buffer: holds enough past input for the correlation search.\n _inLen;\n _inBuf;\n _inCount = 0;\n // total input samples written\n // Stretched-stream overlap-add accumulator (also a ring).\n _outLen;\n _outBuf;\n _synthPos = 0;\n // total stretched samples synthesized\n _readPos = 0;\n // fractional resample read position\n _aPos = 0;\n // analysis position (absolute input coords)\n _first = true;\n // Pitch shift = SOLA time-stretch by `pitch` followed by resampling by\n // `pitch`. SOLA (synchronized overlap-add) realigns each synthesis grain by\n // cross-correlation so grain restarts stay phase coherent - this is what\n // keeps the carrier exactly at f_in * pitch. A naive granular delay drifts\n // the pitch because its grain-boundary phase jumps accumulate into a\n // frequency offset.\n constructor(options) {\n super();\n const grainSize = options?.processorOptions?.grainSize ?? 1024;\n this._frameLen = grainSize;\n this._hop = grainSize >> 1;\n this._overlap = grainSize - this._hop;\n this._seek = grainSize >> 2;\n this._win = this._buildHannWindow(grainSize);\n this._inLen = grainSize * 4 + 2 * this._seek;\n this._inBuf = new Float32Array(this._inLen);\n this._outLen = grainSize * 4;\n this._outBuf = new Float32Array(this._outLen);\n }\n _buildHannWindow(n) {\n const w = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n w[i] = 0.5 * (1 - Math.cos(2 * Math.PI * i / n));\n }\n return w;\n }\n // Find the input offset (within ±seek of `nominal`) whose grain head best\n // matches the existing output overlap region - the waveform-similarity step\n // that keeps successive grains in phase.\n _correlate(nominal) {\n const ov = this._overlap;\n const ib = this._inBuf;\n const iL = this._inLen;\n const ob = this._outBuf;\n const oL = this._outLen;\n const sp = this._synthPos;\n const seek = this._seek;\n let bestD = 0;\n let bestC = -Infinity;\n for (let d = -seek; d <= seek; d++) {\n const base = nominal + d;\n if (base < 0 || base + ov > this._inCount) continue;\n let c = 0;\n for (let k = 0; k < ov; k++) c += ob[(sp + k) % oL] * ib[(base + k) % iL];\n if (c > bestC) {\n bestC = c;\n bestD = d;\n }\n }\n return bestD;\n }\n // True once the input buffer covers the next analysis frame plus its search.\n _canGenerate() {\n const nominal = Math.round(this._aPos);\n const oldest = this._inCount - this._inLen;\n return nominal >= 0 && nominal + this._frameLen + this._seek <= this._inCount && nominal - this._seek >= oldest;\n }\n // Emit one phase-aligned grain into the stretched-stream accumulator.\n _generate(pitch) {\n const F = this._frameLen;\n const H = this._hop;\n const win = this._win;\n const ib = this._inBuf;\n const iL = this._inLen;\n const ob = this._outBuf;\n const oL = this._outLen;\n const nominal = Math.round(this._aPos);\n const d = this._first ? 0 : this._correlate(nominal);\n this._first = false;\n const base = nominal + d;\n for (let j = H; j < F; j++) ob[(this._synthPos + j) % oL] = 0;\n for (let j = 0; j < F; j++) ob[(this._synthPos + j) % oL] += ib[(base + j) % iL] * win[j];\n this._synthPos += H;\n this._aPos += H / pitch;\n }\n process(inputs, outputs, parameters) {\n const input = inputs[0]?.[0];\n const output = outputs[0]?.[0];\n if (!input || !output) return true;\n const pitch = parameters[\"pitch\"][0];\n const ob = this._outBuf;\n const oL = this._outLen;\n for (let i = 0; i < input.length; i++) {\n this._inBuf[this._inCount % this._inLen] = input[i];\n this._inCount++;\n let guard = 0;\n while (this._synthPos < this._readPos + 2 && this._canGenerate() && guard++ < 64) {\n this._generate(pitch);\n }\n let shifted = 0;\n if (this._readPos + 1 < this._synthPos) {\n const p = this._readPos;\n const i0 = Math.floor(p);\n const frac = p - i0;\n const a = ob[(i0 % oL + oL) % oL];\n const b = ob[((i0 + 1) % oL + oL) % oL];\n shifted = a + (b - a) * frac;\n this._readPos += pitch;\n }\n output[i] = shifted;\n }\n return true;\n }\n };\n registerProcessor(\"exojs-pitch-shift\", PitchShiftProcessor);\n})();\n";
|
|
3
|
-
|
|
4
|
-
//#endregion
|
|
5
|
-
export { pitch_shift_worklet_default as default };
|
|
6
|
-
//# sourceMappingURL=pitch-shift.worklet.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"pitch-shift.worklet.js","names":[],"sources":["../../../src/worklets/pitch-shift.worklet.ts?worklet"],"sourcesContent":["export default \"\\\"use strict\\\";\\n(() => {\\n // pitch-shift.worklet.ts\\n var PitchShiftProcessor = class extends AudioWorkletProcessor {\\n static get parameterDescriptors() {\\n return [{ name: \\\"pitch\\\", defaultValue: 1, minValue: 0.25, maxValue: 4, automationRate: \\\"k-rate\\\" }];\\n }\\n _frameLen;\\n // analysis/synthesis frame\\n _hop;\\n // synthesis hop (50% overlap)\\n _overlap;\\n _seek;\\n // correlation search radius (±)\\n _win;\\n // Input ring buffer: holds enough past input for the correlation search.\\n _inLen;\\n _inBuf;\\n _inCount = 0;\\n // total input samples written\\n // Stretched-stream overlap-add accumulator (also a ring).\\n _outLen;\\n _outBuf;\\n _synthPos = 0;\\n // total stretched samples synthesized\\n _readPos = 0;\\n // fractional resample read position\\n _aPos = 0;\\n // analysis position (absolute input coords)\\n _first = true;\\n // Pitch shift = SOLA time-stretch by `pitch` followed by resampling by\\n // `pitch`. SOLA (synchronized overlap-add) realigns each synthesis grain by\\n // cross-correlation so grain restarts stay phase coherent - this is what\\n // keeps the carrier exactly at f_in * pitch. A naive granular delay drifts\\n // the pitch because its grain-boundary phase jumps accumulate into a\\n // frequency offset.\\n constructor(options) {\\n super();\\n const grainSize = options?.processorOptions?.grainSize ?? 1024;\\n this._frameLen = grainSize;\\n this._hop = grainSize >> 1;\\n this._overlap = grainSize - this._hop;\\n this._seek = grainSize >> 2;\\n this._win = this._buildHannWindow(grainSize);\\n this._inLen = grainSize * 4 + 2 * this._seek;\\n this._inBuf = new Float32Array(this._inLen);\\n this._outLen = grainSize * 4;\\n this._outBuf = new Float32Array(this._outLen);\\n }\\n _buildHannWindow(n) {\\n const w = new Float32Array(n);\\n for (let i = 0; i < n; i++) {\\n w[i] = 0.5 * (1 - Math.cos(2 * Math.PI * i / n));\\n }\\n return w;\\n }\\n // Find the input offset (within ±seek of `nominal`) whose grain head best\\n // matches the existing output overlap region - the waveform-similarity step\\n // that keeps successive grains in phase.\\n _correlate(nominal) {\\n const ov = this._overlap;\\n const ib = this._inBuf;\\n const iL = this._inLen;\\n const ob = this._outBuf;\\n const oL = this._outLen;\\n const sp = this._synthPos;\\n const seek = this._seek;\\n let bestD = 0;\\n let bestC = -Infinity;\\n for (let d = -seek; d <= seek; d++) {\\n const base = nominal + d;\\n if (base < 0 || base + ov > this._inCount) continue;\\n let c = 0;\\n for (let k = 0; k < ov; k++) c += ob[(sp + k) % oL] * ib[(base + k) % iL];\\n if (c > bestC) {\\n bestC = c;\\n bestD = d;\\n }\\n }\\n return bestD;\\n }\\n // True once the input buffer covers the next analysis frame plus its search.\\n _canGenerate() {\\n const nominal = Math.round(this._aPos);\\n const oldest = this._inCount - this._inLen;\\n return nominal >= 0 && nominal + this._frameLen + this._seek <= this._inCount && nominal - this._seek >= oldest;\\n }\\n // Emit one phase-aligned grain into the stretched-stream accumulator.\\n _generate(pitch) {\\n const F = this._frameLen;\\n const H = this._hop;\\n const win = this._win;\\n const ib = this._inBuf;\\n const iL = this._inLen;\\n const ob = this._outBuf;\\n const oL = this._outLen;\\n const nominal = Math.round(this._aPos);\\n const d = this._first ? 0 : this._correlate(nominal);\\n this._first = false;\\n const base = nominal + d;\\n for (let j = H; j < F; j++) ob[(this._synthPos + j) % oL] = 0;\\n for (let j = 0; j < F; j++) ob[(this._synthPos + j) % oL] += ib[(base + j) % iL] * win[j];\\n this._synthPos += H;\\n this._aPos += H / pitch;\\n }\\n process(inputs, outputs, parameters) {\\n const input = inputs[0]?.[0];\\n const output = outputs[0]?.[0];\\n if (!input || !output) return true;\\n const pitch = parameters[\\\"pitch\\\"][0];\\n const ob = this._outBuf;\\n const oL = this._outLen;\\n for (let i = 0; i < input.length; i++) {\\n this._inBuf[this._inCount % this._inLen] = input[i];\\n this._inCount++;\\n let guard = 0;\\n while (this._synthPos < this._readPos + 2 && this._canGenerate() && guard++ < 64) {\\n this._generate(pitch);\\n }\\n let shifted = 0;\\n if (this._readPos + 1 < this._synthPos) {\\n const p = this._readPos;\\n const i0 = Math.floor(p);\\n const frac = p - i0;\\n const a = ob[(i0 % oL + oL) % oL];\\n const b = ob[((i0 + 1) % oL + oL) % oL];\\n shifted = a + (b - a) * frac;\\n this._readPos += pitch;\\n }\\n output[i] = shifted;\\n }\\n return true;\\n }\\n };\\n registerProcessor(\\\"exojs-pitch-shift\\\", PitchShiftProcessor);\\n})();\\n\";"],"mappings":";AAAA,kCAAe"}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
//#region src/worklets/vocoder.worklet.ts?worklet
|
|
2
|
-
var vocoder_worklet_default = "\"use strict\";\n(() => {\n // vocoder.worklet.ts\n var sampleRate = globalThis.sampleRate;\n var VocoderProcessor = class extends AudioWorkletProcessor {\n static get parameterDescriptors() {\n return [{ name: \"envelopeSmoothing\", defaultValue: 5e-3, minValue: 1e-4, maxValue: 0.1, automationRate: \"k-rate\" }];\n }\n // Log-spaced band centers + biquad coefficients\n _bands = [];\n // Per-band biquad state (one for carrier, one for modulator)\n _carrierStates;\n _modulatorStates;\n // Per-band envelope follower\n _envelopes;\n constructor(options) {\n super();\n const opts = options?.processorOptions ?? {};\n const bandCount = opts.numBands ?? 16;\n const minHz = opts.minHz ?? 80;\n const maxHz = opts.maxHz ?? 8e3;\n const Q = opts.bandQ ?? 4;\n for (let i = 0; i < bandCount; i++) {\n const ratio = bandCount === 1 ? 0 : i / (bandCount - 1);\n const centerHz = minHz * Math.pow(maxHz / minHz, ratio);\n const omega = 2 * Math.PI * centerHz / sampleRate;\n const cos = Math.cos(omega);\n const sin = Math.sin(omega);\n const alpha = sin / (2 * Q);\n const a0 = 1 + alpha;\n const b0 = alpha / a0;\n const b1 = 0;\n const b2 = -alpha / a0;\n const a1 = -2 * cos / a0;\n const a2 = (1 - alpha) / a0;\n this._bands.push({ b0, b1, b2, a1, a2 });\n }\n this._carrierStates = this._bands.map(() => ({ x1: 0, x2: 0, y1: 0, y2: 0 }));\n this._modulatorStates = this._bands.map(() => ({ x1: 0, x2: 0, y1: 0, y2: 0 }));\n this._envelopes = new Float32Array(bandCount);\n }\n _processBiquad(state, coef, x) {\n const y = coef.b0 * x + coef.b1 * state.x1 + coef.b2 * state.x2 - coef.a1 * state.y1 - coef.a2 * state.y2;\n state.x2 = state.x1;\n state.x1 = x;\n state.y2 = state.y1;\n state.y1 = y;\n return y;\n }\n process(inputs, outputs, parameters) {\n const carrier = inputs[0]?.[0];\n const modulator = inputs[1]?.[0];\n const output = outputs[0]?.[0];\n if (!carrier || !output) return true;\n const envSmoothing = parameters[\"envelopeSmoothing\"][0];\n const bandCount = this._bands.length;\n for (let i = 0; i < carrier.length; i++) {\n const carrierSample = carrier[i];\n const modulatorSample = modulator?.[i] ?? 0;\n let bandSum = 0;\n for (let b = 0; b < bandCount; b++) {\n const coef = this._bands[b];\n const modBand = this._processBiquad(this._modulatorStates[b], coef, modulatorSample);\n const target = Math.abs(modBand);\n this._envelopes[b] += (target - this._envelopes[b]) * envSmoothing;\n const carBand = this._processBiquad(this._carrierStates[b], coef, carrierSample);\n bandSum += carBand * this._envelopes[b];\n }\n output[i] = bandSum * bandCount;\n }\n return true;\n }\n };\n registerProcessor(\"exojs-vocoder\", VocoderProcessor);\n})();\n";
|
|
3
|
-
|
|
4
|
-
//#endregion
|
|
5
|
-
export { vocoder_worklet_default as default };
|
|
6
|
-
//# sourceMappingURL=vocoder.worklet.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"vocoder.worklet.js","names":[],"sources":["../../../src/worklets/vocoder.worklet.ts?worklet"],"sourcesContent":["export default \"\\\"use strict\\\";\\n(() => {\\n // vocoder.worklet.ts\\n var sampleRate = globalThis.sampleRate;\\n var VocoderProcessor = class extends AudioWorkletProcessor {\\n static get parameterDescriptors() {\\n return [{ name: \\\"envelopeSmoothing\\\", defaultValue: 5e-3, minValue: 1e-4, maxValue: 0.1, automationRate: \\\"k-rate\\\" }];\\n }\\n // Log-spaced band centers + biquad coefficients\\n _bands = [];\\n // Per-band biquad state (one for carrier, one for modulator)\\n _carrierStates;\\n _modulatorStates;\\n // Per-band envelope follower\\n _envelopes;\\n constructor(options) {\\n super();\\n const opts = options?.processorOptions ?? {};\\n const bandCount = opts.numBands ?? 16;\\n const minHz = opts.minHz ?? 80;\\n const maxHz = opts.maxHz ?? 8e3;\\n const Q = opts.bandQ ?? 4;\\n for (let i = 0; i < bandCount; i++) {\\n const ratio = bandCount === 1 ? 0 : i / (bandCount - 1);\\n const centerHz = minHz * Math.pow(maxHz / minHz, ratio);\\n const omega = 2 * Math.PI * centerHz / sampleRate;\\n const cos = Math.cos(omega);\\n const sin = Math.sin(omega);\\n const alpha = sin / (2 * Q);\\n const a0 = 1 + alpha;\\n const b0 = alpha / a0;\\n const b1 = 0;\\n const b2 = -alpha / a0;\\n const a1 = -2 * cos / a0;\\n const a2 = (1 - alpha) / a0;\\n this._bands.push({ b0, b1, b2, a1, a2 });\\n }\\n this._carrierStates = this._bands.map(() => ({ x1: 0, x2: 0, y1: 0, y2: 0 }));\\n this._modulatorStates = this._bands.map(() => ({ x1: 0, x2: 0, y1: 0, y2: 0 }));\\n this._envelopes = new Float32Array(bandCount);\\n }\\n _processBiquad(state, coef, x) {\\n const y = coef.b0 * x + coef.b1 * state.x1 + coef.b2 * state.x2 - coef.a1 * state.y1 - coef.a2 * state.y2;\\n state.x2 = state.x1;\\n state.x1 = x;\\n state.y2 = state.y1;\\n state.y1 = y;\\n return y;\\n }\\n process(inputs, outputs, parameters) {\\n const carrier = inputs[0]?.[0];\\n const modulator = inputs[1]?.[0];\\n const output = outputs[0]?.[0];\\n if (!carrier || !output) return true;\\n const envSmoothing = parameters[\\\"envelopeSmoothing\\\"][0];\\n const bandCount = this._bands.length;\\n for (let i = 0; i < carrier.length; i++) {\\n const carrierSample = carrier[i];\\n const modulatorSample = modulator?.[i] ?? 0;\\n let bandSum = 0;\\n for (let b = 0; b < bandCount; b++) {\\n const coef = this._bands[b];\\n const modBand = this._processBiquad(this._modulatorStates[b], coef, modulatorSample);\\n const target = Math.abs(modBand);\\n this._envelopes[b] += (target - this._envelopes[b]) * envSmoothing;\\n const carBand = this._processBiquad(this._carrierStates[b], coef, carrierSample);\\n bandSum += carBand * this._envelopes[b];\\n }\\n output[i] = bandSum * bandCount;\\n }\\n return true;\\n }\\n };\\n registerProcessor(\\\"exojs-vocoder\\\", VocoderProcessor);\\n})();\\n\";"],"mappings":";AAAA,8BAAe"}
|