@codexo/exojs-audio-fx 0.19.1 → 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 -123
- package/dist/esm/AudioAnalyser.d.ts.map +0 -1
- package/dist/esm/AudioAnalyser.js +0 -295
- package/dist/esm/AudioAnalyser.js.map +0 -1
- package/dist/esm/AudioTap.d.ts +0 -33
- package/dist/esm/AudioTap.d.ts.map +0 -1
- package/dist/esm/AudioTap.js +0 -126
- package/dist/esm/AudioTap.js.map +0 -1
- package/dist/esm/BeatDetector.d.ts +0 -291
- package/dist/esm/BeatDetector.d.ts.map +0 -1
- package/dist/esm/BeatDetector.js +0 -365
- package/dist/esm/BeatDetector.js.map +0 -1
- package/dist/esm/PcmStreamSource.d.ts +0 -132
- package/dist/esm/PcmStreamSource.d.ts.map +0 -1
- package/dist/esm/PcmStreamSource.js +0 -313
- package/dist/esm/PcmStreamSource.js.map +0 -1
- package/dist/esm/ReadyGate.d.ts +0 -25
- package/dist/esm/ReadyGate.d.ts.map +0 -1
- package/dist/esm/ReadyGate.js +0 -69
- package/dist/esm/ReadyGate.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 -127
- package/dist/esm/effects/AutoWahEffect.d.ts.map +0 -1
- package/dist/esm/effects/AutoWahEffect.js +0 -209
- 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 -60
- package/dist/esm/effects/ChorusEffect.d.ts.map +0 -1
- package/dist/esm/effects/ChorusEffect.js +0 -139
- package/dist/esm/effects/ChorusEffect.js.map +0 -1
- package/dist/esm/effects/CompressorEffect.d.ts +0 -55
- package/dist/esm/effects/CompressorEffect.d.ts.map +0 -1
- package/dist/esm/effects/CompressorEffect.js +0 -103
- package/dist/esm/effects/CompressorEffect.js.map +0 -1
- package/dist/esm/effects/ConvolutionEffect.d.ts +0 -118
- package/dist/esm/effects/ConvolutionEffect.d.ts.map +0 -1
- package/dist/esm/effects/ConvolutionEffect.js +0 -207
- package/dist/esm/effects/ConvolutionEffect.js.map +0 -1
- package/dist/esm/effects/DelayEffect.d.ts +0 -35
- package/dist/esm/effects/DelayEffect.d.ts.map +0 -1
- package/dist/esm/effects/DelayEffect.js +0 -104
- package/dist/esm/effects/DelayEffect.js.map +0 -1
- package/dist/esm/effects/DistortionEffect.d.ts +0 -116
- package/dist/esm/effects/DistortionEffect.d.ts.map +0 -1
- package/dist/esm/effects/DistortionEffect.js +0 -189
- 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 -89
- package/dist/esm/effects/DuckingEffect.js.map +0 -1
- package/dist/esm/effects/EqualizerEffect.d.ts +0 -50
- package/dist/esm/effects/EqualizerEffect.d.ts.map +0 -1
- package/dist/esm/effects/EqualizerEffect.js +0 -119
- package/dist/esm/effects/EqualizerEffect.js.map +0 -1
- package/dist/esm/effects/FlangerEffect.d.ts +0 -107
- package/dist/esm/effects/FlangerEffect.d.ts.map +0 -1
- package/dist/esm/effects/FlangerEffect.js +0 -178
- 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 -129
- package/dist/esm/effects/LimiterEffect.d.ts.map +0 -1
- package/dist/esm/effects/LimiterEffect.js +0 -185
- package/dist/esm/effects/LimiterEffect.js.map +0 -1
- package/dist/esm/effects/PhaserEffect.d.ts +0 -126
- package/dist/esm/effects/PhaserEffect.d.ts.map +0 -1
- package/dist/esm/effects/PhaserEffect.js +0 -213
- package/dist/esm/effects/PhaserEffect.js.map +0 -1
- package/dist/esm/effects/PingPongDelayEffect.d.ts +0 -83
- package/dist/esm/effects/PingPongDelayEffect.d.ts.map +0 -1
- package/dist/esm/effects/PingPongDelayEffect.js +0 -171
- 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 -37
- package/dist/esm/effects/ReverbEffect.d.ts.map +0 -1
- package/dist/esm/effects/ReverbEffect.js +0 -112
- package/dist/esm/effects/ReverbEffect.js.map +0 -1
- package/dist/esm/effects/RingModulatorEffect.d.ts +0 -95
- package/dist/esm/effects/RingModulatorEffect.d.ts.map +0 -1
- package/dist/esm/effects/RingModulatorEffect.js +0 -152
- package/dist/esm/effects/RingModulatorEffect.js.map +0 -1
- package/dist/esm/effects/TremoloEffect.d.ts +0 -108
- package/dist/esm/effects/TremoloEffect.d.ts.map +0 -1
- package/dist/esm/effects/TremoloEffect.js +0 -192
- 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 -68
- 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/disposable-processor.d.ts +0 -13
- package/dist/esm/worklets/disposable-processor.d.ts.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,313 +0,0 @@
|
|
|
1
|
-
import pcm_stream_worklet_default from "./worklets/pcm-stream.worklet.js";
|
|
2
|
-
import { Signal, getAudioContext, registerAudioWorkletProcessor } from "@codexo/exojs";
|
|
3
|
-
|
|
4
|
-
//#region src/PcmStreamSource.ts
|
|
5
|
-
/**
|
|
6
|
-
* A bounded, externally fed Float32 PCM source at the shared AudioContext's
|
|
7
|
-
* sample rate. Lives in `@codexo/exojs-audio-fx`; no extension registration is
|
|
8
|
-
* required. Feed a bus or connect {@link output} to an analysis tap.
|
|
9
|
-
*
|
|
10
|
-
* Await {@link ready}, enqueue a caller-chosen amount of audio, then call
|
|
11
|
-
* {@link start}. The worklet consumes FIFO samples without waiting for the
|
|
12
|
-
* producer. An empty running queue emits silence; later blocks resume at the
|
|
13
|
-
* next available render quantum, without catching up or skipping samples.
|
|
14
|
-
* Browser suspension freezes the audio clock and playback, but writes remain
|
|
15
|
-
* bounded. Readiness does not unlock browser autoplay.
|
|
16
|
-
*
|
|
17
|
-
* Input arrays are copied synchronously and never detached. The private copy
|
|
18
|
-
* is transferred without requiring cross-origin isolation. Values must be
|
|
19
|
-
* finite; nominal full scale is -1..1, with no clipping or normalization here.
|
|
20
|
-
* Resampling, producer timestamps and audiovisual lookahead belong to callers.
|
|
21
|
-
*
|
|
22
|
-
* Own and destroy the source separately from its bus, for example with a scene
|
|
23
|
-
* DestroyScope. Destroying an AudioSystem or bus does not destroy this source.
|
|
24
|
-
*/
|
|
25
|
-
var PcmStreamSource = class {
|
|
26
|
-
channels;
|
|
27
|
-
capacityFrames;
|
|
28
|
-
sampleRate;
|
|
29
|
-
/** Resolves after module loading, even while audio is suspended. Rejects on loading failure or destruction during loading (`AbortError`). */
|
|
30
|
-
ready;
|
|
31
|
-
/** Fires once after close has drained, not on destroy or failure. */
|
|
32
|
-
onEnd = new Signal();
|
|
33
|
-
/** Reports module loading, processor or context closure failures. The source is terminal afterwards. */
|
|
34
|
-
onError = new Signal();
|
|
35
|
-
/**
|
|
36
|
-
* Stable source tap for Web Audio interop; routing through a bus needs no
|
|
37
|
-
* access to it. Bus routing changes preserve caller-created connections;
|
|
38
|
-
* terminal cleanup disconnects it.
|
|
39
|
-
* @advanced
|
|
40
|
-
*/
|
|
41
|
-
output;
|
|
42
|
-
_context;
|
|
43
|
-
_state = "loading";
|
|
44
|
-
_node = null;
|
|
45
|
-
_bus = null;
|
|
46
|
-
_busNode = null;
|
|
47
|
-
_cancelBusSetup = null;
|
|
48
|
-
_submittedFrames = 0;
|
|
49
|
-
_highWaterFrames = 0;
|
|
50
|
-
_releasedFrames = 0;
|
|
51
|
-
_playedFrames = 0;
|
|
52
|
-
_underrunFrames = 0;
|
|
53
|
-
_underruns = 0;
|
|
54
|
-
_overflowCount = 0;
|
|
55
|
-
_droppedFrames = 0;
|
|
56
|
-
_clearing = false;
|
|
57
|
-
_resolveReady;
|
|
58
|
-
_rejectReady;
|
|
59
|
-
_onContextState = () => {
|
|
60
|
-
if (this._context.state === "closed" && !this._terminal) this._fail(/* @__PURE__ */ new Error("PcmStreamSource: the audio context was closed."));
|
|
61
|
-
};
|
|
62
|
-
constructor(options) {
|
|
63
|
-
const capacity = options.capacityFrames ?? 8192;
|
|
64
|
-
if (options.channels !== 1 && options.channels !== 2) throw new RangeError("PcmStreamSource requires one or two channels.");
|
|
65
|
-
if (!Number.isInteger(capacity) || capacity < 1 || capacity > 1048576) throw new RangeError("PcmStreamSource capacityFrames must be an integer from 1 to 1048576.");
|
|
66
|
-
this.channels = options.channels;
|
|
67
|
-
this.capacityFrames = capacity;
|
|
68
|
-
this._context = getAudioContext();
|
|
69
|
-
this.sampleRate = this._context.sampleRate;
|
|
70
|
-
this.output = this._context.createGain();
|
|
71
|
-
this.ready = new Promise((resolve, reject) => {
|
|
72
|
-
this._resolveReady = resolve;
|
|
73
|
-
this._rejectReady = reject;
|
|
74
|
-
});
|
|
75
|
-
this.ready.catch(() => {});
|
|
76
|
-
this.bus = options.bus ?? null;
|
|
77
|
-
this._context.addEventListener?.("statechange", this._onContextState);
|
|
78
|
-
if (this._context.state === "closed") this._onContextState();
|
|
79
|
-
else this._load();
|
|
80
|
-
}
|
|
81
|
-
get state() {
|
|
82
|
-
return this._state;
|
|
83
|
-
}
|
|
84
|
-
/** Conservative occupancy: submitted frames minus acknowledged consumed/discarded frames. May lag playback while messages are in flight. */
|
|
85
|
-
get bufferedFrames() {
|
|
86
|
-
return this._submittedFrames - this._releasedFrames;
|
|
87
|
-
}
|
|
88
|
-
/** Queue occupancy in seconds, excluding output-device latency. */
|
|
89
|
-
get bufferedSeconds() {
|
|
90
|
-
return this.bufferedFrames / this.sampleRate;
|
|
91
|
-
}
|
|
92
|
-
/** Lifetime accepted frames. Refused, invalid and empty writes do not increase this count; clear and teardown preserve it. */
|
|
93
|
-
get enqueuedFrames() {
|
|
94
|
-
return this._submittedFrames;
|
|
95
|
-
}
|
|
96
|
-
/** Lifetime maximum bufferedFrames after an accepted write, including transport and unacknowledged consumption. Never exceeds capacityFrames; clear and teardown preserve it. */
|
|
97
|
-
get highWaterFrames() {
|
|
98
|
-
return this._highWaterFrames;
|
|
99
|
-
}
|
|
100
|
-
/** True until the worklet acknowledges clear; writes are refused during this interval. */
|
|
101
|
-
get clearing() {
|
|
102
|
-
return this._clearing;
|
|
103
|
-
}
|
|
104
|
-
/** Lifetime frames actually rendered from PCM, as of the latest worklet report. */
|
|
105
|
-
get playedFrames() {
|
|
106
|
-
return this._playedFrames;
|
|
107
|
-
}
|
|
108
|
-
/** Lifetime silent frames caused by starvation after start; excludes idle, suspended and drained time. */
|
|
109
|
-
get underrunFrames() {
|
|
110
|
-
return this._underrunFrames;
|
|
111
|
-
}
|
|
112
|
-
/** Lifetime contiguous starvation episodes, as of the latest report. */
|
|
113
|
-
get underruns() {
|
|
114
|
-
return this._underruns;
|
|
115
|
-
}
|
|
116
|
-
/** Lifetime blocks refused for insufficient capacity. Other refused writes are not overflow. */
|
|
117
|
-
get overflowCount() {
|
|
118
|
-
return this._overflowCount;
|
|
119
|
-
}
|
|
120
|
-
/** Lifetime frames refused for insufficient capacity; not frames discarded by clear or destroy. */
|
|
121
|
-
get droppedFrames() {
|
|
122
|
-
return this._droppedFrames;
|
|
123
|
-
}
|
|
124
|
-
get bus() {
|
|
125
|
-
return this._bus;
|
|
126
|
-
}
|
|
127
|
-
/** Reroute to a bus input, or disconnect that route with `null`. Does not take ownership of the bus or its effects. */
|
|
128
|
-
set bus(bus) {
|
|
129
|
-
if (this._terminal || bus === this._bus) return;
|
|
130
|
-
this._disconnectBus();
|
|
131
|
-
this._bus = bus;
|
|
132
|
-
if (!bus) return;
|
|
133
|
-
const connect = () => {
|
|
134
|
-
if (this._terminal || this._bus !== bus) return;
|
|
135
|
-
const input = bus.getInputNode();
|
|
136
|
-
if (input) {
|
|
137
|
-
this.output.connect(input);
|
|
138
|
-
this._busNode = input;
|
|
139
|
-
}
|
|
140
|
-
};
|
|
141
|
-
if (bus.getInputNode()) connect();
|
|
142
|
-
else this._cancelBusSetup = bus.onceSetup(connect);
|
|
143
|
-
}
|
|
144
|
-
/**
|
|
145
|
-
* Begin once, no earlier than `time` in audio-context seconds (default now).
|
|
146
|
-
* Sample positions round up to the next audio frame; a past time starts at
|
|
147
|
-
* the next available quantum. Returns false unless ready and not yet started.
|
|
148
|
-
*/
|
|
149
|
-
start(time = this._context.currentTime) {
|
|
150
|
-
if (this._state !== "ready") return false;
|
|
151
|
-
if (!Number.isFinite(time) || time < 0) throw new RangeError("PcmStreamSource start time must be finite and nonnegative.");
|
|
152
|
-
this._node.port.postMessage({
|
|
153
|
-
type: "start",
|
|
154
|
-
time
|
|
155
|
-
});
|
|
156
|
-
this._state = "running";
|
|
157
|
-
return true;
|
|
158
|
-
}
|
|
159
|
-
/**
|
|
160
|
-
* Copy equal-length mono/stereo channel arrays in FIFO order. Returns false
|
|
161
|
-
* before ready, during clear, after close/failure/destroy, or on overflow.
|
|
162
|
-
* Overflow rejects the entire block before copying. Empty blocks succeed
|
|
163
|
-
* without sending a message. Invalid layout or nonfinite samples throw.
|
|
164
|
-
*/
|
|
165
|
-
enqueuePlanar(channels) {
|
|
166
|
-
if (!this._writable) return false;
|
|
167
|
-
if (channels.length !== this.channels) throw new RangeError("PCM channel count does not match the source.");
|
|
168
|
-
const frames = channels[0].length;
|
|
169
|
-
for (const channel of channels) if (!(channel instanceof Float32Array) || channel.length !== frames) throw new RangeError("PCM channels must be equal-length Float32Arrays.");
|
|
170
|
-
if (!this._admit(frames)) return false;
|
|
171
|
-
for (const channel of channels) this._validateSamples(channel);
|
|
172
|
-
if (frames === 0) return true;
|
|
173
|
-
const packed = new Float32Array(frames * this.channels);
|
|
174
|
-
for (let channel = 0; channel < this.channels; channel++) packed.set(channels[channel], channel * frames);
|
|
175
|
-
return this._submit(packed, frames);
|
|
176
|
-
}
|
|
177
|
-
/** Copy interleaved frames (L,R,L,R for stereo). Same acceptance and ownership contract as {@link enqueuePlanar}. */
|
|
178
|
-
enqueueInterleaved(data) {
|
|
179
|
-
if (!this._writable) return false;
|
|
180
|
-
if (!(data instanceof Float32Array) || data.length % this.channels !== 0) throw new RangeError("PCM must contain whole Float32 frames.");
|
|
181
|
-
const frames = data.length / this.channels;
|
|
182
|
-
if (!this._admit(frames)) return false;
|
|
183
|
-
this._validateSamples(data);
|
|
184
|
-
if (frames === 0) return true;
|
|
185
|
-
const packed = new Float32Array(data.length);
|
|
186
|
-
for (let channel = 0; channel < this.channels; channel++) for (let frame = 0; frame < frames; frame++) packed[channel * frames + frame] = data[frame * this.channels + channel];
|
|
187
|
-
return this._submit(packed, frames);
|
|
188
|
-
}
|
|
189
|
-
/**
|
|
190
|
-
* Discard queued PCM once the worklet receives the command, retaining the
|
|
191
|
-
* start schedule and lifetime counters. Coalesces while pending and refuses
|
|
192
|
-
* new writes until acknowledged. No-op while loading or after close.
|
|
193
|
-
*/
|
|
194
|
-
clear() {
|
|
195
|
-
if (!this._writable) return;
|
|
196
|
-
this._node.port.postMessage({ type: "clear" });
|
|
197
|
-
this._clearing = true;
|
|
198
|
-
}
|
|
199
|
-
/**
|
|
200
|
-
* Refuse further writes and drain. If not started, begin draining immediately;
|
|
201
|
-
* otherwise preserve the scheduled start. Empty tails do not count as
|
|
202
|
-
* underruns. Completes only when the context processes audio; use destroy for
|
|
203
|
-
* immediate cancellation while suspended. Idempotent and terminal.
|
|
204
|
-
*/
|
|
205
|
-
close() {
|
|
206
|
-
if (this._terminal || this._state === "closing") return;
|
|
207
|
-
this._state = "closing";
|
|
208
|
-
this._node?.port.postMessage({ type: "close" });
|
|
209
|
-
}
|
|
210
|
-
/** Stop immediately, discard pending PCM, detach routes and release the port. Idempotent; never destroys the bus or shared context. */
|
|
211
|
-
destroy() {
|
|
212
|
-
if (this._state === "destroyed") return;
|
|
213
|
-
this._state = "destroyed";
|
|
214
|
-
this._rejectReady(new DOMException("PcmStreamSource was destroyed during loading.", "AbortError"));
|
|
215
|
-
this._dispose(true);
|
|
216
|
-
this.onEnd.destroy();
|
|
217
|
-
this.onError.destroy();
|
|
218
|
-
}
|
|
219
|
-
get _terminal() {
|
|
220
|
-
return this._state === "closed" || this._state === "destroyed" || this._state === "failed";
|
|
221
|
-
}
|
|
222
|
-
get _writable() {
|
|
223
|
-
return (this._state === "ready" || this._state === "running") && !this._clearing;
|
|
224
|
-
}
|
|
225
|
-
_admit(frames) {
|
|
226
|
-
if (frames <= this.capacityFrames - this.bufferedFrames) return true;
|
|
227
|
-
this._overflowCount++;
|
|
228
|
-
this._droppedFrames += frames;
|
|
229
|
-
return false;
|
|
230
|
-
}
|
|
231
|
-
_validateSamples(data) {
|
|
232
|
-
for (const sample of data) if (!Number.isFinite(sample)) throw new RangeError("PCM samples must be finite.");
|
|
233
|
-
}
|
|
234
|
-
_submit(data, frames) {
|
|
235
|
-
this._node.port.postMessage({
|
|
236
|
-
type: "write",
|
|
237
|
-
data
|
|
238
|
-
}, [data.buffer]);
|
|
239
|
-
this._submittedFrames += frames;
|
|
240
|
-
this._highWaterFrames = Math.max(this._highWaterFrames, this.bufferedFrames);
|
|
241
|
-
return true;
|
|
242
|
-
}
|
|
243
|
-
async _load() {
|
|
244
|
-
try {
|
|
245
|
-
await registerAudioWorkletProcessor(this._context, "exojs-pcm-stream", pcm_stream_worklet_default);
|
|
246
|
-
if (this._terminal) return;
|
|
247
|
-
const node = new AudioWorkletNode(this._context, "exojs-pcm-stream", {
|
|
248
|
-
numberOfInputs: 0,
|
|
249
|
-
numberOfOutputs: 1,
|
|
250
|
-
outputChannelCount: [this.channels],
|
|
251
|
-
processorOptions: {
|
|
252
|
-
channels: this.channels,
|
|
253
|
-
capacityFrames: this.capacityFrames
|
|
254
|
-
}
|
|
255
|
-
});
|
|
256
|
-
this._node = node;
|
|
257
|
-
node.port.onmessage = (event) => this._receive(event.data);
|
|
258
|
-
node.onprocessorerror = () => this._fail(/* @__PURE__ */ new Error("PcmStreamSource: the audio processor failed."));
|
|
259
|
-
node.connect(this.output);
|
|
260
|
-
if (this._state === "closing") node.port.postMessage({ type: "close" });
|
|
261
|
-
else this._state = "ready";
|
|
262
|
-
this._resolveReady();
|
|
263
|
-
} catch (error) {
|
|
264
|
-
if (!this._terminal) this._fail(error instanceof Error ? error : new Error(String(error)));
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
_receive(status) {
|
|
268
|
-
if (this._terminal) return;
|
|
269
|
-
this._releasedFrames = status.releasedFrames;
|
|
270
|
-
this._playedFrames = status.playedFrames;
|
|
271
|
-
this._underrunFrames = status.underrunFrames;
|
|
272
|
-
this._underruns = status.underruns;
|
|
273
|
-
if (status.type === "status") this._node.port.postMessage({ type: "ack" });
|
|
274
|
-
if (status.type === "cleared") this._clearing = false;
|
|
275
|
-
if (status.type === "ended") {
|
|
276
|
-
this._state = "closed";
|
|
277
|
-
this._dispose(false);
|
|
278
|
-
this.onEnd.dispatch();
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
_fail(error) {
|
|
282
|
-
if (this._terminal) return;
|
|
283
|
-
this._state = "failed";
|
|
284
|
-
this._rejectReady(error);
|
|
285
|
-
this._dispose(true);
|
|
286
|
-
this.onError.dispatch(error);
|
|
287
|
-
}
|
|
288
|
-
_disconnectBus() {
|
|
289
|
-
this._cancelBusSetup?.();
|
|
290
|
-
this._cancelBusSetup = null;
|
|
291
|
-
if (this._busNode) this.output.disconnect(this._busNode);
|
|
292
|
-
this._busNode = null;
|
|
293
|
-
}
|
|
294
|
-
_dispose(terminate) {
|
|
295
|
-
this._context.removeEventListener?.("statechange", this._onContextState);
|
|
296
|
-
this._disconnectBus();
|
|
297
|
-
if (this._node) {
|
|
298
|
-
if (terminate) this._node.port.postMessage({ type: "destroy" });
|
|
299
|
-
this._node.port.onmessage = null;
|
|
300
|
-
this._node.onprocessorerror = null;
|
|
301
|
-
this._node.disconnect();
|
|
302
|
-
this._node.port.close();
|
|
303
|
-
this._node = null;
|
|
304
|
-
}
|
|
305
|
-
this.output.disconnect();
|
|
306
|
-
this._releasedFrames = this._submittedFrames;
|
|
307
|
-
this._clearing = false;
|
|
308
|
-
}
|
|
309
|
-
};
|
|
310
|
-
|
|
311
|
-
//#endregion
|
|
312
|
-
export { PcmStreamSource };
|
|
313
|
-
//# sourceMappingURL=PcmStreamSource.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"PcmStreamSource.js","names":["pcmStreamWorkletSource"],"sources":["../../src/PcmStreamSource.ts"],"sourcesContent":["import { type AudioBus, getAudioContext, registerAudioWorkletProcessor, type Seconds, Signal } from '@codexo/exojs';\n\nimport pcmStreamWorkletSource from './worklets/pcm-stream.worklet.ts?worklet';\n\nexport interface PcmStreamSourceOptions {\n /** Fixed channel count. PCM is not remixed or resampled by this source. */\n channels: 1 | 2;\n /** Maximum outstanding frames, including messages in transit. Integer 1..1048576; default 8192. This is a capacity, not a target latency. */\n capacityFrames?: number;\n /** Destination bus. Default `null` leaves the output disconnected. Ownership stays with the caller. */\n bus?: AudioBus | null;\n}\n\nexport type PcmStreamState = 'loading' | 'ready' | 'running' | 'closing' | 'closed' | 'failed' | 'destroyed';\n\ninterface PcmStatus {\n type: 'status' | 'cleared' | 'ended';\n releasedFrames: number;\n playedFrames: number;\n underrunFrames: number;\n underruns: number;\n}\n\n/**\n * A bounded, externally fed Float32 PCM source at the shared AudioContext's\n * sample rate. Lives in `@codexo/exojs-audio-fx`; no extension registration is\n * required. Feed a bus or connect {@link output} to an analysis tap.\n *\n * Await {@link ready}, enqueue a caller-chosen amount of audio, then call\n * {@link start}. The worklet consumes FIFO samples without waiting for the\n * producer. An empty running queue emits silence; later blocks resume at the\n * next available render quantum, without catching up or skipping samples.\n * Browser suspension freezes the audio clock and playback, but writes remain\n * bounded. Readiness does not unlock browser autoplay.\n *\n * Input arrays are copied synchronously and never detached. The private copy\n * is transferred without requiring cross-origin isolation. Values must be\n * finite; nominal full scale is -1..1, with no clipping or normalization here.\n * Resampling, producer timestamps and audiovisual lookahead belong to callers.\n *\n * Own and destroy the source separately from its bus, for example with a scene\n * DestroyScope. Destroying an AudioSystem or bus does not destroy this source.\n */\nexport class PcmStreamSource {\n public readonly channels: 1 | 2;\n public readonly capacityFrames: number;\n public readonly sampleRate: number;\n /** Resolves after module loading, even while audio is suspended. Rejects on loading failure or destruction during loading (`AbortError`). */\n public readonly ready: Promise<void>;\n /** Fires once after close has drained, not on destroy or failure. */\n public readonly onEnd = new Signal();\n /** Reports module loading, processor or context closure failures. The source is terminal afterwards. */\n public readonly onError = new Signal<[Error]>();\n /**\n * Stable source tap for Web Audio interop; routing through a bus needs no\n * access to it. Bus routing changes preserve caller-created connections;\n * terminal cleanup disconnects it.\n * @advanced\n */\n public readonly output: GainNode;\n\n private readonly _context: AudioContext;\n private _state: PcmStreamState = 'loading';\n private _node: AudioWorkletNode | null = null;\n private _bus: AudioBus | null = null;\n private _busNode: AudioNode | null = null;\n private _cancelBusSetup: (() => void) | null = null;\n private _submittedFrames = 0;\n private _highWaterFrames = 0;\n private _releasedFrames = 0;\n private _playedFrames = 0;\n private _underrunFrames = 0;\n private _underruns = 0;\n private _overflowCount = 0;\n private _droppedFrames = 0;\n private _clearing = false;\n private _resolveReady!: () => void;\n private _rejectReady!: (error: Error) => void;\n private readonly _onContextState = (): void => {\n if (this._context.state === 'closed' && !this._terminal) {\n this._fail(new Error('PcmStreamSource: the audio context was closed.'));\n }\n };\n\n public constructor(options: PcmStreamSourceOptions) {\n const capacity = options.capacityFrames ?? 8192;\n if (options.channels !== 1 && options.channels !== 2) {\n throw new RangeError('PcmStreamSource requires one or two channels.');\n }\n if (!Number.isInteger(capacity) || capacity < 1 || capacity > 1048576) {\n throw new RangeError('PcmStreamSource capacityFrames must be an integer from 1 to 1048576.');\n }\n this.channels = options.channels;\n this.capacityFrames = capacity;\n this._context = getAudioContext();\n this.sampleRate = this._context.sampleRate;\n this.output = this._context.createGain();\n this.ready = new Promise<void>((resolve, reject) => {\n this._resolveReady = resolve;\n this._rejectReady = reject;\n });\n void this.ready.catch(() => {\n // Cancellation may precede the caller's await; keep that original rejection observable.\n });\n this.bus = options.bus ?? null;\n this._context.addEventListener?.('statechange', this._onContextState);\n if (this._context.state === 'closed') {\n this._onContextState();\n } else {\n void this._load();\n }\n }\n\n public get state(): PcmStreamState {\n return this._state;\n }\n\n /** Conservative occupancy: submitted frames minus acknowledged consumed/discarded frames. May lag playback while messages are in flight. */\n public get bufferedFrames(): number {\n return this._submittedFrames - this._releasedFrames;\n }\n\n /** Queue occupancy in seconds, excluding output-device latency. */\n public get bufferedSeconds(): Seconds {\n return (this.bufferedFrames / this.sampleRate) as Seconds;\n }\n\n /** Lifetime accepted frames. Refused, invalid and empty writes do not increase this count; clear and teardown preserve it. */\n public get enqueuedFrames(): number {\n return this._submittedFrames;\n }\n\n /** Lifetime maximum bufferedFrames after an accepted write, including transport and unacknowledged consumption. Never exceeds capacityFrames; clear and teardown preserve it. */\n public get highWaterFrames(): number {\n return this._highWaterFrames;\n }\n\n /** True until the worklet acknowledges clear; writes are refused during this interval. */\n public get clearing(): boolean {\n return this._clearing;\n }\n\n /** Lifetime frames actually rendered from PCM, as of the latest worklet report. */\n public get playedFrames(): number {\n return this._playedFrames;\n }\n\n /** Lifetime silent frames caused by starvation after start; excludes idle, suspended and drained time. */\n public get underrunFrames(): number {\n return this._underrunFrames;\n }\n\n /** Lifetime contiguous starvation episodes, as of the latest report. */\n public get underruns(): number {\n return this._underruns;\n }\n\n /** Lifetime blocks refused for insufficient capacity. Other refused writes are not overflow. */\n public get overflowCount(): number {\n return this._overflowCount;\n }\n\n /** Lifetime frames refused for insufficient capacity; not frames discarded by clear or destroy. */\n public get droppedFrames(): number {\n return this._droppedFrames;\n }\n\n public get bus(): AudioBus | null {\n return this._bus;\n }\n\n /** Reroute to a bus input, or disconnect that route with `null`. Does not take ownership of the bus or its effects. */\n public set bus(bus: AudioBus | null) {\n if (this._terminal || bus === this._bus) return;\n this._disconnectBus();\n this._bus = bus;\n if (!bus) return;\n const connect = (): void => {\n if (this._terminal || this._bus !== bus) return;\n const input = bus.getInputNode();\n if (input) {\n this.output.connect(input);\n this._busNode = input;\n }\n };\n if (bus.getInputNode()) connect();\n else this._cancelBusSetup = bus.onceSetup(connect);\n }\n\n /**\n * Begin once, no earlier than `time` in audio-context seconds (default now).\n * Sample positions round up to the next audio frame; a past time starts at\n * the next available quantum. Returns false unless ready and not yet started.\n */\n public start(time = this._context.currentTime): boolean {\n if (this._state !== 'ready') return false;\n if (!Number.isFinite(time) || time < 0) throw new RangeError('PcmStreamSource start time must be finite and nonnegative.');\n this._node!.port.postMessage({ type: 'start', time });\n this._state = 'running';\n return true;\n }\n\n /**\n * Copy equal-length mono/stereo channel arrays in FIFO order. Returns false\n * before ready, during clear, after close/failure/destroy, or on overflow.\n * Overflow rejects the entire block before copying. Empty blocks succeed\n * without sending a message. Invalid layout or nonfinite samples throw.\n */\n public enqueuePlanar(channels: readonly Float32Array[]): boolean {\n if (!this._writable) return false;\n if (channels.length !== this.channels) throw new RangeError('PCM channel count does not match the source.');\n const frames = channels[0]!.length;\n for (const channel of channels) {\n if (!(channel instanceof Float32Array) || channel.length !== frames) throw new RangeError('PCM channels must be equal-length Float32Arrays.');\n }\n if (!this._admit(frames)) return false;\n for (const channel of channels) this._validateSamples(channel);\n if (frames === 0) return true;\n const packed = new Float32Array(frames * this.channels);\n for (let channel = 0; channel < this.channels; channel++) packed.set(channels[channel]!, channel * frames);\n return this._submit(packed, frames);\n }\n\n /** Copy interleaved frames (L,R,L,R for stereo). Same acceptance and ownership contract as {@link enqueuePlanar}. */\n public enqueueInterleaved(data: Float32Array): boolean {\n if (!this._writable) return false;\n if (!(data instanceof Float32Array) || data.length % this.channels !== 0) throw new RangeError('PCM must contain whole Float32 frames.');\n const frames = data.length / this.channels;\n if (!this._admit(frames)) return false;\n this._validateSamples(data);\n if (frames === 0) return true;\n const packed = new Float32Array(data.length);\n for (let channel = 0; channel < this.channels; channel++) {\n for (let frame = 0; frame < frames; frame++) packed[channel * frames + frame] = data[frame * this.channels + channel]!;\n }\n return this._submit(packed, frames);\n }\n\n /**\n * Discard queued PCM once the worklet receives the command, retaining the\n * start schedule and lifetime counters. Coalesces while pending and refuses\n * new writes until acknowledged. No-op while loading or after close.\n */\n public clear(): void {\n if (!this._writable) return;\n this._node!.port.postMessage({ type: 'clear' });\n this._clearing = true;\n }\n\n /**\n * Refuse further writes and drain. If not started, begin draining immediately;\n * otherwise preserve the scheduled start. Empty tails do not count as\n * underruns. Completes only when the context processes audio; use destroy for\n * immediate cancellation while suspended. Idempotent and terminal.\n */\n public close(): void {\n if (this._terminal || this._state === 'closing') return;\n this._state = 'closing';\n this._node?.port.postMessage({ type: 'close' });\n }\n\n /** Stop immediately, discard pending PCM, detach routes and release the port. Idempotent; never destroys the bus or shared context. */\n public destroy(): void {\n if (this._state === 'destroyed') return;\n this._state = 'destroyed';\n this._rejectReady(new DOMException('PcmStreamSource was destroyed during loading.', 'AbortError'));\n this._dispose(true);\n this.onEnd.destroy();\n this.onError.destroy();\n }\n\n private get _terminal(): boolean {\n return this._state === 'closed' || this._state === 'destroyed' || this._state === 'failed';\n }\n\n private get _writable(): boolean {\n return (this._state === 'ready' || this._state === 'running') && !this._clearing;\n }\n\n private _admit(frames: number): boolean {\n if (frames <= this.capacityFrames - this.bufferedFrames) return true;\n this._overflowCount++;\n this._droppedFrames += frames;\n return false;\n }\n\n private _validateSamples(data: Float32Array): void {\n for (const sample of data) {\n if (!Number.isFinite(sample)) throw new RangeError('PCM samples must be finite.');\n }\n }\n\n private _submit(data: Float32Array, frames: number): boolean {\n this._node!.port.postMessage({ type: 'write', data }, [data.buffer]);\n this._submittedFrames += frames;\n this._highWaterFrames = Math.max(this._highWaterFrames, this.bufferedFrames);\n return true;\n }\n\n private async _load(): Promise<void> {\n try {\n await registerAudioWorkletProcessor(this._context, 'exojs-pcm-stream', pcmStreamWorkletSource);\n if (this._terminal) return;\n const node = new AudioWorkletNode(this._context, 'exojs-pcm-stream', {\n numberOfInputs: 0,\n numberOfOutputs: 1,\n outputChannelCount: [this.channels],\n processorOptions: { channels: this.channels, capacityFrames: this.capacityFrames },\n });\n this._node = node;\n node.port.onmessage = (event: MessageEvent<PcmStatus>): void => this._receive(event.data);\n node.onprocessorerror = (): void => this._fail(new Error('PcmStreamSource: the audio processor failed.'));\n node.connect(this.output);\n if (this._state === 'closing') node.port.postMessage({ type: 'close' });\n else this._state = 'ready';\n this._resolveReady();\n } catch (error) {\n if (!this._terminal) this._fail(error instanceof Error ? error : new Error(String(error)));\n }\n }\n\n private _receive(status: PcmStatus): void {\n if (this._terminal) return;\n this._releasedFrames = status.releasedFrames;\n this._playedFrames = status.playedFrames;\n this._underrunFrames = status.underrunFrames;\n this._underruns = status.underruns;\n if (status.type === 'status') this._node!.port.postMessage({ type: 'ack' });\n if (status.type === 'cleared') this._clearing = false;\n if (status.type === 'ended') {\n this._state = 'closed';\n this._dispose(false);\n this.onEnd.dispatch();\n }\n }\n\n private _fail(error: Error): void {\n if (this._terminal) return;\n this._state = 'failed';\n this._rejectReady(error);\n this._dispose(true);\n this.onError.dispatch(error);\n }\n\n private _disconnectBus(): void {\n this._cancelBusSetup?.();\n this._cancelBusSetup = null;\n if (this._busNode) this.output.disconnect(this._busNode);\n this._busNode = null;\n }\n\n private _dispose(terminate: boolean): void {\n this._context.removeEventListener?.('statechange', this._onContextState);\n this._disconnectBus();\n if (this._node) {\n if (terminate) this._node.port.postMessage({ type: 'destroy' });\n this._node.port.onmessage = null;\n this._node.onprocessorerror = null;\n this._node.disconnect();\n this._node.port.close();\n this._node = null;\n }\n this.output.disconnect();\n this._releasedFrames = this._submittedFrames;\n this._clearing = false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA2CA,IAAa,kBAAb,MAA6B;CAC3B,AAAgB;CAChB,AA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AAK,eAAe;EACvE,KAAK,eAAe;EACpB,IAAI,KAAK,OAAO;GACd,IAAI,WAAW,KAAK,MAAM,KAAK,YAAY,EAAE,MAAM,UAAU,CAAC;GAC9D,KAAK,MAAM,KAAK,YAAY;GAC5B,KAAK,MAAM,mBAAmB;GAC9B,KAAK,MAAM,WAAW;GACtB,KAAK,MAAM,KAAK,MAAM;GACtB,KAAK,QAAQ;EACf;EACA,KAAK,OAAO,WAAW;EACvB,KAAK,kBAAkB,KAAK;EAC5B,KAAK,YAAY;CACnB;AACF"}
|
package/dist/esm/ReadyGate.d.ts
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The `ready` contract `AudioEffect` gives effects, for the package's
|
|
3
|
-
* non-effect worklet components: pending until set up, resolved once ready,
|
|
4
|
-
* rejected with the setup error, or with an `AbortError` when destroyed first.
|
|
5
|
-
*
|
|
6
|
-
* The promise is created only when someone asks for it, so a failure nobody
|
|
7
|
-
* awaits raises no unhandled rejection.
|
|
8
|
-
*/
|
|
9
|
-
export declare class ReadyGate {
|
|
10
|
-
private readonly _abortMessage;
|
|
11
|
-
private _state;
|
|
12
|
-
private _failure;
|
|
13
|
-
private _promise;
|
|
14
|
-
private _resolve;
|
|
15
|
-
private _reject;
|
|
16
|
-
constructor(_abortMessage: string);
|
|
17
|
-
get promise(): Promise<void>;
|
|
18
|
-
resolve(): void;
|
|
19
|
-
fail(error: unknown): void;
|
|
20
|
-
/** Rejects a gate that is still pending; a settled gate keeps its outcome. */
|
|
21
|
-
abort(): void;
|
|
22
|
-
private _createAbortError;
|
|
23
|
-
private _clear;
|
|
24
|
-
}
|
|
25
|
-
//# sourceMappingURL=ReadyGate.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ReadyGate.d.ts","sourceRoot":"","sources":["../../src/ReadyGate.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,qBAAa,SAAS;IAOD,OAAO,CAAC,QAAQ,CAAC,aAAa;IANjD,OAAO,CAAC,MAAM,CAAyD;IACvE,OAAO,CAAC,QAAQ,CAAsB;IACtC,OAAO,CAAC,QAAQ,CAA8B;IAC9C,OAAO,CAAC,QAAQ,CAA6B;IAC7C,OAAO,CAAC,OAAO,CAA0C;IAEzD,YAAoC,aAAa,EAAE,MAAM,EAAI;IAE7D,IAAW,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAsBlC;IAEM,OAAO,IAAI,IAAI,CAKrB;IAEM,IAAI,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAMhC;IAED,8EAA8E;IACvE,KAAK,IAAI,IAAI,CAKnB;IAED,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,MAAM;CAIf"}
|
package/dist/esm/ReadyGate.js
DELETED
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
//#region src/ReadyGate.ts
|
|
2
|
-
/**
|
|
3
|
-
* The `ready` contract `AudioEffect` gives effects, for the package's
|
|
4
|
-
* non-effect worklet components: pending until set up, resolved once ready,
|
|
5
|
-
* rejected with the setup error, or with an `AbortError` when destroyed first.
|
|
6
|
-
*
|
|
7
|
-
* The promise is created only when someone asks for it, so a failure nobody
|
|
8
|
-
* awaits raises no unhandled rejection.
|
|
9
|
-
*/
|
|
10
|
-
var ReadyGate = class {
|
|
11
|
-
_abortMessage;
|
|
12
|
-
_state = "pending";
|
|
13
|
-
_failure = null;
|
|
14
|
-
_promise = null;
|
|
15
|
-
_resolve = null;
|
|
16
|
-
_reject = null;
|
|
17
|
-
constructor(_abortMessage) {
|
|
18
|
-
this._abortMessage = _abortMessage;
|
|
19
|
-
}
|
|
20
|
-
get promise() {
|
|
21
|
-
if (this._promise === null) switch (this._state) {
|
|
22
|
-
case "ready":
|
|
23
|
-
this._promise = Promise.resolve();
|
|
24
|
-
break;
|
|
25
|
-
case "failed":
|
|
26
|
-
this._promise = Promise.reject(this._failure ?? /* @__PURE__ */ new Error("Setup failed."));
|
|
27
|
-
break;
|
|
28
|
-
case "aborted":
|
|
29
|
-
this._promise = Promise.reject(this._createAbortError());
|
|
30
|
-
break;
|
|
31
|
-
case "pending": this._promise = new Promise((resolve, reject) => {
|
|
32
|
-
this._resolve = resolve;
|
|
33
|
-
this._reject = reject;
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
return this._promise;
|
|
37
|
-
}
|
|
38
|
-
resolve() {
|
|
39
|
-
if (this._state !== "pending") return;
|
|
40
|
-
this._state = "ready";
|
|
41
|
-
this._resolve?.();
|
|
42
|
-
this._clear();
|
|
43
|
-
}
|
|
44
|
-
fail(error) {
|
|
45
|
-
if (this._state !== "pending") return;
|
|
46
|
-
this._state = "failed";
|
|
47
|
-
this._failure = error instanceof Error ? error : new Error(String(error));
|
|
48
|
-
this._reject?.(this._failure);
|
|
49
|
-
this._clear();
|
|
50
|
-
}
|
|
51
|
-
/** Rejects a gate that is still pending; a settled gate keeps its outcome. */
|
|
52
|
-
abort() {
|
|
53
|
-
if (this._state !== "pending") return;
|
|
54
|
-
this._state = "aborted";
|
|
55
|
-
this._reject?.(this._createAbortError());
|
|
56
|
-
this._clear();
|
|
57
|
-
}
|
|
58
|
-
_createAbortError() {
|
|
59
|
-
return new DOMException(this._abortMessage, "AbortError");
|
|
60
|
-
}
|
|
61
|
-
_clear() {
|
|
62
|
-
this._resolve = null;
|
|
63
|
-
this._reject = null;
|
|
64
|
-
}
|
|
65
|
-
};
|
|
66
|
-
|
|
67
|
-
//#endregion
|
|
68
|
-
export { ReadyGate };
|
|
69
|
-
//# sourceMappingURL=ReadyGate.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ReadyGate.js","names":[],"sources":["../../src/ReadyGate.ts"],"sourcesContent":["/**\n * The `ready` contract `AudioEffect` gives effects, for the package's\n * non-effect worklet components: pending until set up, resolved once ready,\n * rejected with the setup error, or with an `AbortError` when destroyed first.\n *\n * The promise is created only when someone asks for it, so a failure nobody\n * awaits raises no unhandled rejection.\n */\nexport class ReadyGate {\n private _state: 'pending' | 'ready' | 'failed' | 'aborted' = 'pending';\n private _failure: Error | null = null;\n private _promise: Promise<void> | null = null;\n private _resolve: (() => void) | null = null;\n private _reject: ((reason: Error) => void) | null = null;\n\n public constructor(private readonly _abortMessage: string) {}\n\n public get promise(): Promise<void> {\n if (this._promise === null) {\n switch (this._state) {\n case 'ready':\n this._promise = Promise.resolve();\n break;\n case 'failed':\n this._promise = Promise.reject(this._failure ?? new Error('Setup failed.'));\n break;\n case 'aborted':\n this._promise = Promise.reject(this._createAbortError());\n break;\n case 'pending':\n this._promise = new Promise<void>((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n break;\n }\n }\n\n return this._promise;\n }\n\n public resolve(): void {\n if (this._state !== 'pending') return;\n this._state = 'ready';\n this._resolve?.();\n this._clear();\n }\n\n public fail(error: unknown): void {\n if (this._state !== 'pending') return;\n this._state = 'failed';\n this._failure = error instanceof Error ? error : new Error(String(error));\n this._reject?.(this._failure);\n this._clear();\n }\n\n /** Rejects a gate that is still pending; a settled gate keeps its outcome. */\n public abort(): void {\n if (this._state !== 'pending') return;\n this._state = 'aborted';\n this._reject?.(this._createAbortError());\n this._clear();\n }\n\n private _createAbortError(): DOMException {\n return new DOMException(this._abortMessage, 'AbortError');\n }\n\n private _clear(): void {\n this._resolve = null;\n this._reject = null;\n }\n}\n"],"mappings":";;;;;;;;;AAQA,IAAa,YAAb,MAAuB;CAOe;CANpC,AAAQ,SAAqD;CAC7D,AAAQ,WAAyB;CACjC,AAAQ,WAAiC;CACzC,AAAQ,WAAgC;CACxC,AAAQ,UAA4C;CAEpD,AAAO,YAAY,AAAiB,eAAuB;EAAvB;CAAwB;CAE5D,IAAW,UAAyB;EAClC,IAAI,KAAK,aAAa,MACpB,QAAQ,KAAK,QAAb;GACE,KAAK;IACH,KAAK,WAAW,QAAQ,QAAQ;IAChC;GACF,KAAK;IACH,KAAK,WAAW,QAAQ,OAAO,KAAK,4BAAY,IAAI,MAAM,eAAe,CAAC;IAC1E;GACF,KAAK;IACH,KAAK,WAAW,QAAQ,OAAO,KAAK,kBAAkB,CAAC;IACvD;GACF,KAAK,WACH,KAAK,WAAW,IAAI,SAAe,SAAS,WAAW;IACrD,KAAK,WAAW;IAChB,KAAK,UAAU;GACjB,CAAC;EAEL;EAGF,OAAO,KAAK;CACd;CAEA,AAAO,UAAgB;EACrB,IAAI,KAAK,WAAW,WAAW;EAC/B,KAAK,SAAS;EACd,KAAK,WAAW;EAChB,KAAK,OAAO;CACd;CAEA,AAAO,KAAK,OAAsB;EAChC,IAAI,KAAK,WAAW,WAAW;EAC/B,KAAK,SAAS;EACd,KAAK,WAAW,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;EACxE,KAAK,UAAU,KAAK,QAAQ;EAC5B,KAAK,OAAO;CACd;;CAGA,AAAO,QAAc;EACnB,IAAI,KAAK,WAAW,WAAW;EAC/B,KAAK,SAAS;EACd,KAAK,UAAU,KAAK,kBAAkB,CAAC;EACvC,KAAK,OAAO;CACd;CAEA,AAAQ,oBAAkC;EACxC,OAAO,IAAI,aAAa,KAAK,eAAe,YAAY;CAC1D;CAEA,AAAQ,SAAe;EACrB,KAAK,WAAW;EAChB,KAAK,UAAU;CACjB;AACF"}
|
package/dist/esm/dsp/fft.d.ts
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* In-place radix-2 Cooley-Tukey FFT.
|
|
3
|
-
*
|
|
4
|
-
* Operates on the supplied real/imag arrays (length must be a power of 2).
|
|
5
|
-
* After the call, real[i] and imag[i] hold the complex spectrum.
|
|
6
|
-
* A Hann window is applied to the input before the transform.
|
|
7
|
-
*
|
|
8
|
-
* The beat-detector worklet imports these directly; its build bundles them in.
|
|
9
|
-
*/
|
|
10
|
-
/** Apply a Hann window in-place to `real`. `imag` is zeroed. */
|
|
11
|
-
export declare const hannWindow: (real: Float32Array, imag: Float32Array) => void;
|
|
12
|
-
/**
|
|
13
|
-
* In-place FFT. `real` and `imag` must have the same length (power of 2).
|
|
14
|
-
* A Hann window is applied to `real` before the transform; `imag` is zeroed.
|
|
15
|
-
*/
|
|
16
|
-
export declare const fft: (real: Float32Array, imag: Float32Array) => void;
|
|
17
|
-
/**
|
|
18
|
-
* Compute magnitude spectrum from complex FFT output.
|
|
19
|
-
* Returns a Float32Array of length `n/2` (positive frequencies only).
|
|
20
|
-
*/
|
|
21
|
-
export declare const magnitudeSpectrum: (real: Float32Array, imag: Float32Array) => Float32Array;
|
|
22
|
-
//# sourceMappingURL=fft.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"fft.d.ts","sourceRoot":"","sources":["../../../src/dsp/fft.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,gEAAgE;AAChE,eAAO,MAAM,UAAU,SAAU,YAAY,QAAQ,YAAY,KAAG,IAOnE,CAAC;AAuBF;;;GAGG;AACH,eAAO,MAAM,GAAG,SAAU,YAAY,QAAQ,YAAY,KAAG,IAsB5D,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,iBAAiB,SAAU,YAAY,QAAQ,YAAY,KAAG,YAO1E,CAAC"}
|
package/dist/esm/dsp/mel.d.ts
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Mel-scale filterbank generator.
|
|
3
|
-
*
|
|
4
|
-
* Generates `numBands` triangular filters log-spaced from `fMin` to `fMax` Hz
|
|
5
|
-
* on the mel scale. Each filter is a typed array of weights for the FFT
|
|
6
|
-
* magnitude bins.
|
|
7
|
-
*
|
|
8
|
-
* The beat-detector worklet imports these directly; its build bundles them in.
|
|
9
|
-
*/
|
|
10
|
-
/** Convert Hz to mel. */
|
|
11
|
-
export declare const hzToMel: (hz: number) => number;
|
|
12
|
-
/** Convert mel to Hz. */
|
|
13
|
-
export declare const melToHz: (mel: number) => number;
|
|
14
|
-
export interface MelBand {
|
|
15
|
-
/** Index of the FFT bin where this filter starts (weight 0). */
|
|
16
|
-
readonly startBin: number;
|
|
17
|
-
/** Index of the peak FFT bin (weight 1). */
|
|
18
|
-
readonly peakBin: number;
|
|
19
|
-
/** Index of the FFT bin where this filter ends (weight 0). */
|
|
20
|
-
readonly endBin: number;
|
|
21
|
-
/** Pre-computed triangular weights, indexed from startBin..endBin (inclusive). */
|
|
22
|
-
readonly weights: Float32Array;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Build a mel filterbank.
|
|
26
|
-
*
|
|
27
|
-
* @param numBands Number of mel bands (default 24).
|
|
28
|
-
* @param fMin Lowest frequency in Hz (default 80).
|
|
29
|
-
* @param fMax Highest frequency in Hz (default 8000).
|
|
30
|
-
* @param fftSize Number of FFT points (e.g., 2048).
|
|
31
|
-
* @param sampleRate Audio sample rate in Hz (e.g., 48000).
|
|
32
|
-
*/
|
|
33
|
-
export declare const buildMelFilterbank: (bandCount: number, fMin: number, fMax: number, fftSize: number, sampleRate: number) => MelBand[];
|
|
34
|
-
/**
|
|
35
|
-
* Compute mel band energies from a magnitude spectrum.
|
|
36
|
-
*
|
|
37
|
-
* @param mag FFT magnitude spectrum (length = fftSize/2).
|
|
38
|
-
* @param bands Filterbank from `buildMelFilterbank`.
|
|
39
|
-
* @param out Optional pre-allocated output array of length `bands.length`.
|
|
40
|
-
* @returns Log-compressed mel band energies.
|
|
41
|
-
*/
|
|
42
|
-
export declare const computeMelBands: (mag: Float32Array, bands: readonly MelBand[], out?: Float32Array) => Float32Array;
|
|
43
|
-
//# sourceMappingURL=mel.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mel.d.ts","sourceRoot":"","sources":["../../../src/dsp/mel.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,yBAAyB;AACzB,eAAO,MAAM,OAAO,OAAQ,MAAM,KAAG,MAAyC,CAAC;AAE/E,yBAAyB;AACzB,eAAO,MAAM,OAAO,QAAS,MAAM,KAAG,MAA8C,CAAC;AAErF,MAAM,WAAW,OAAO;IACtB,gEAAgE;IAChE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,4CAA4C;IAC5C,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,8DAA8D;IAC9D,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,kFAAkF;IAClF,QAAQ,CAAC,OAAO,EAAE,YAAY,CAAC;CAChC;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,kBAAkB,cAAe,MAAM,QAAQ,MAAM,QAAQ,MAAM,WAAW,MAAM,cAAc,MAAM,KAAG,OAAO,EA2C9H,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,QAAS,YAAY,SAAS,SAAS,OAAO,EAAE,QAAQ,YAAY,KAAG,YAWlG,CAAC"}
|
package/dist/esm/dsp/mel.js
DELETED
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
//#region src/dsp/mel.ts
|
|
2
|
-
/**
|
|
3
|
-
* Mel-scale filterbank generator.
|
|
4
|
-
*
|
|
5
|
-
* Generates `numBands` triangular filters log-spaced from `fMin` to `fMax` Hz
|
|
6
|
-
* on the mel scale. Each filter is a typed array of weights for the FFT
|
|
7
|
-
* magnitude bins.
|
|
8
|
-
*
|
|
9
|
-
* The beat-detector worklet imports these directly; its build bundles them in.
|
|
10
|
-
*/
|
|
11
|
-
/** Convert Hz to mel. */
|
|
12
|
-
const hzToMel = (hz) => 2595 * Math.log10(1 + hz / 700);
|
|
13
|
-
/** Convert mel to Hz. */
|
|
14
|
-
const melToHz = (mel) => 700 * (Math.pow(10, mel / 2595) - 1);
|
|
15
|
-
/**
|
|
16
|
-
* Build a mel filterbank.
|
|
17
|
-
*
|
|
18
|
-
* @param numBands Number of mel bands (default 24).
|
|
19
|
-
* @param fMin Lowest frequency in Hz (default 80).
|
|
20
|
-
* @param fMax Highest frequency in Hz (default 8000).
|
|
21
|
-
* @param fftSize Number of FFT points (e.g., 2048).
|
|
22
|
-
* @param sampleRate Audio sample rate in Hz (e.g., 48000).
|
|
23
|
-
*/
|
|
24
|
-
const buildMelFilterbank = (bandCount, fMin, fMax, fftSize, sampleRate) => {
|
|
25
|
-
const binCount = fftSize >> 1;
|
|
26
|
-
const nyquist = sampleRate / 2;
|
|
27
|
-
const melMin = hzToMel(fMin);
|
|
28
|
-
const melMax = hzToMel(fMax);
|
|
29
|
-
const melPoints = new Float32Array(bandCount + 2);
|
|
30
|
-
for (let i = 0; i < bandCount + 2; i++) melPoints[i] = melMin + (melMax - melMin) * i / (bandCount + 1);
|
|
31
|
-
const binPoints = new Float32Array(bandCount + 2);
|
|
32
|
-
for (let i = 0; i < bandCount + 2; i++) {
|
|
33
|
-
const hz = melToHz(melPoints[i]);
|
|
34
|
-
binPoints[i] = Math.round(hz / nyquist * (binCount - 1));
|
|
35
|
-
}
|
|
36
|
-
const bands = [];
|
|
37
|
-
for (let b = 0; b < bandCount; b++) {
|
|
38
|
-
const startBin = Math.max(0, Math.min(binCount - 1, binPoints[b]));
|
|
39
|
-
const peakBin = Math.max(0, Math.min(binCount - 1, binPoints[b + 1]));
|
|
40
|
-
const endBin = Math.max(0, Math.min(binCount - 1, binPoints[b + 2]));
|
|
41
|
-
const len = endBin - startBin + 1;
|
|
42
|
-
const weights = new Float32Array(len);
|
|
43
|
-
for (let i = 0; i < len; i++) {
|
|
44
|
-
const bin = startBin + i;
|
|
45
|
-
if (bin <= peakBin && peakBin > startBin) weights[i] = (bin - startBin) / (peakBin - startBin);
|
|
46
|
-
else if (bin > peakBin && endBin > peakBin) weights[i] = (endBin - bin) / (endBin - peakBin);
|
|
47
|
-
else weights[i] = 1;
|
|
48
|
-
}
|
|
49
|
-
bands.push({
|
|
50
|
-
startBin,
|
|
51
|
-
peakBin,
|
|
52
|
-
endBin,
|
|
53
|
-
weights
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
return bands;
|
|
57
|
-
};
|
|
58
|
-
|
|
59
|
-
//#endregion
|
|
60
|
-
export { buildMelFilterbank, hzToMel, melToHz };
|
|
61
|
-
//# sourceMappingURL=mel.js.map
|
package/dist/esm/dsp/mel.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mel.js","names":[],"sources":["../../../src/dsp/mel.ts"],"sourcesContent":["/**\n * Mel-scale filterbank generator.\n *\n * Generates `numBands` triangular filters log-spaced from `fMin` to `fMax` Hz\n * on the mel scale. Each filter is a typed array of weights for the FFT\n * magnitude bins.\n *\n * The beat-detector worklet imports these directly; its build bundles them in.\n */\n\n/** Convert Hz to mel. */\nexport const hzToMel = (hz: number): number => 2595 * Math.log10(1 + hz / 700);\n\n/** Convert mel to Hz. */\nexport const melToHz = (mel: number): number => 700 * (Math.pow(10, mel / 2595) - 1);\n\nexport interface MelBand {\n /** Index of the FFT bin where this filter starts (weight 0). */\n readonly startBin: number;\n /** Index of the peak FFT bin (weight 1). */\n readonly peakBin: number;\n /** Index of the FFT bin where this filter ends (weight 0). */\n readonly endBin: number;\n /** Pre-computed triangular weights, indexed from startBin..endBin (inclusive). */\n readonly weights: Float32Array;\n}\n\n/**\n * Build a mel filterbank.\n *\n * @param numBands Number of mel bands (default 24).\n * @param fMin Lowest frequency in Hz (default 80).\n * @param fMax Highest frequency in Hz (default 8000).\n * @param fftSize Number of FFT points (e.g., 2048).\n * @param sampleRate Audio sample rate in Hz (e.g., 48000).\n */\nexport const buildMelFilterbank = (bandCount: number, fMin: number, fMax: number, fftSize: number, sampleRate: number): MelBand[] => {\n const binCount = fftSize >> 1; // positive frequencies\n const nyquist = sampleRate / 2;\n\n // Equally-spaced mel points: bandCount+2 points spanning fMin..fMax\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\n // Convert mel points to FFT bin indices\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\n const bands: MelBand[] = [];\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\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 // Degenerate: startBin === peakBin === endBin\n weights[i] = 1;\n }\n }\n\n bands.push({ startBin, peakBin, endBin, weights });\n }\n\n return bands;\n};\n\n/**\n * Compute mel band energies from a magnitude spectrum.\n *\n * @param mag FFT magnitude spectrum (length = fftSize/2).\n * @param bands Filterbank from `buildMelFilterbank`.\n * @param out Optional pre-allocated output array of length `bands.length`.\n * @returns Log-compressed mel band energies.\n */\nexport const computeMelBands = (mag: Float32Array, bands: readonly MelBand[], out?: Float32Array): Float32Array => {\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"],"mappings":";;;;;;;;;;;AAWA,MAAa,WAAW,OAAuB,OAAO,KAAK,MAAM,IAAI,KAAK,GAAG;;AAG7E,MAAa,WAAW,QAAwB,OAAO,KAAK,IAAI,IAAI,MAAM,IAAI,IAAI;;;;;;;;;;AAsBlF,MAAa,sBAAsB,WAAmB,MAAc,MAAc,SAAiB,eAAkC;CACnI,MAAM,WAAW,WAAW;CAC5B,MAAM,UAAU,aAAa;CAG7B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