@margoengine/audio 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +987 -2
  4. package/dist/ambisonics.d.ts +54 -0
  5. package/dist/ambisonics.js +118 -0
  6. package/dist/analyser.d.ts +45 -0
  7. package/dist/audio.d.ts +282 -0
  8. package/dist/binaural.d.ts +35 -0
  9. package/dist/binaural.js +123 -0
  10. package/dist/doppler.d.ts +44 -0
  11. package/dist/doppler.js +82 -0
  12. package/dist/errors-D8rc8kzg.js +7 -0
  13. package/dist/events.d.ts +54 -0
  14. package/dist/events.js +78 -0
  15. package/dist/index.d.ts +12 -0
  16. package/dist/index.js +303 -0
  17. package/dist/listener.d.ts +116 -0
  18. package/dist/loader.d.ts +22 -0
  19. package/dist/math-C82bLsED.js +44 -0
  20. package/dist/math.d.ts +19 -0
  21. package/dist/music.d.ts +76 -0
  22. package/dist/music.js +106 -0
  23. package/dist/occlusion.d.ts +50 -0
  24. package/dist/occlusion.js +75 -0
  25. package/dist/outdoor.d.ts +37 -0
  26. package/dist/outdoor.js +52 -0
  27. package/dist/pan.d.ts +21 -0
  28. package/dist/pan.js +28 -0
  29. package/dist/rate-control-BiZ5FnNk.js +4 -0
  30. package/dist/rate-control.d.ts +5 -0
  31. package/dist/resample.d.ts +53 -0
  32. package/dist/resample.js +245 -0
  33. package/dist/scan.d.ts +66 -0
  34. package/dist/scan.js +75 -0
  35. package/dist/sinc-CbjImCBh.js +36 -0
  36. package/dist/sinc.d.ts +5 -0
  37. package/dist/spectrogram-fft-CRLetuHA.js +59 -0
  38. package/dist/spectrogram-fft.d.ts +26 -0
  39. package/dist/spectrogram-windows.d.ts +24 -0
  40. package/dist/spectrogram.d.ts +143 -0
  41. package/dist/spectrogram.js +384 -0
  42. package/dist/sprites.d.ts +59 -0
  43. package/dist/sprites.js +99 -0
  44. package/dist/stretch.d.ts +25 -0
  45. package/dist/stretch.js +55 -0
  46. package/dist/vocoder-envelope.d.ts +5 -0
  47. package/dist/vocoder-phase.d.ts +7 -0
  48. package/dist/vocoder-split.d.ts +10 -0
  49. package/dist/vocoder.d.ts +59 -0
  50. package/dist/vocoder.js +291 -0
  51. package/dist/voice-manager.d.ts +100 -0
  52. package/dist/voice-manager.js +178 -0
  53. package/dist/voices-CdfPmzIo.js +425 -0
  54. package/dist/voices.d.ts +45 -0
  55. package/dist/wav.d.ts +47 -0
  56. package/dist/wav.js +156 -0
  57. package/dist/zones.d.ts +43 -0
  58. package/dist/zones.js +75 -0
  59. package/package.json +130 -4
@@ -0,0 +1,143 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ // @ts-ignore optional peer: its types apply when it is installed
3
+ import type { ComputeContext } from '@margoengine/compute';
4
+ import { type WindowName, windows } from './spectrogram-windows.js';
5
+ export { windows };
6
+ export type { WindowName };
7
+ /** Options for `stft`. */
8
+ export interface StftOptions {
9
+ /** Samples per second, kept on the result. Default 44100. */
10
+ readonly sampleRate?: number;
11
+ /** Frame length, a power of two from 32 to 65536. Default 2048. */
12
+ readonly size?: number;
13
+ /** Samples between frame starts, 1 to `size`. Default `size / 4`. */
14
+ readonly hop?: number;
15
+ /** A window name, or `size` coefficients. Default `'hann'`. */
16
+ readonly window?: WindowName | ArrayLike<number>;
17
+ /** Centre frame k on sample k * hop by padding `size / 2` samples each side. Default true. */
18
+ readonly center?: boolean;
19
+ /** What the centre padding holds: `'reflect'` (default), `'zero'` or `'edge'`. */
20
+ readonly pad?: 'reflect' | 'zero' | 'edge';
21
+ /** Stops the work between frames; the call throws the signal's reason. */
22
+ readonly signal?: AbortSignal;
23
+ }
24
+ /** `stft` options that run the transforms on the GPU (through `@margoengine/compute/fft`, loaded then). */
25
+ export interface StftGpuOptions extends StftOptions {
26
+ /** A compute context. Resolves a promise instead of returning at once. Output agrees with the CPU path within 1e-4 of the peak. */
27
+ readonly gpu: ComputeContext;
28
+ }
29
+ /** A short-time spectrum: `frames` rows of `bins = size / 2 + 1` complex values, row-major. */
30
+ export interface Spectrum {
31
+ readonly real: Float32Array;
32
+ readonly imag: Float32Array;
33
+ readonly frames: number;
34
+ readonly bins: number;
35
+ readonly size: number;
36
+ readonly hop: number;
37
+ readonly sampleRate: number;
38
+ readonly center: boolean;
39
+ /** Samples analysed (before padding): the default length of `istft`. */
40
+ readonly length: number;
41
+ /** The window coefficients used (`size` values). */
42
+ readonly window: Float64Array;
43
+ }
44
+ /**
45
+ * The reconstruction conditioning of a window at a hop: the smallest over the largest of the steady-state sum of
46
+ * squared windows `sum_k w[r + k hop]^2`, r in [0, hop). 1 is perfect constant overlap-add; `istft` and `resynthesize`
47
+ * refuse a ratio under 0.1 (Hann at hop 3/4 of its size gives 0.04, at hop 1/2 gives 0.5, at 1/4 gives 1).
48
+ */
49
+ export declare function overlapRatio(window: ArrayLike<number>, hop: number): number;
50
+ /**
51
+ * Short-time Fourier transform of `samples`: `frames` windowed frames of `size` samples, `hop` apart, each transformed to
52
+ * `size / 2 + 1` bins. Pass `gpu` (a compute context) to transform frames in batches on the GPU; that returns a promise.
53
+ * @example const spec = stft(samples, { sampleRate: 48000, size: 2048 }); // spec.real, spec.imag
54
+ */
55
+ export declare function stft(samples: ArrayLike<number>, options?: StftOptions): Spectrum;
56
+ export declare function stft(samples: ArrayLike<number>, options: StftGpuOptions): Promise<Spectrum>;
57
+ /** Options for `istft`. */
58
+ export interface IstftOptions {
59
+ /** Samples to return. Default the analysed length (`spec.length`). */
60
+ readonly length?: number;
61
+ readonly signal?: AbortSignal;
62
+ }
63
+ /**
64
+ * Inverse transform by weighted overlap-add: each frame's inverse FFT is multiplied by the window and added in place,
65
+ * and the sum is divided by the sum of squared windows. Exact (to rounding) wherever a window reaches. Throws a coded
66
+ * `state` error when the window and hop overlap too unevenly (see `overlapRatio`).
67
+ * @example const same = istft(stft(samples)); // same[i] equals samples[i] within 1e-6
68
+ */
69
+ export declare function istft(spec: Spectrum, options?: IstftOptions): Float32Array;
70
+ /** Image data of a spectrogram. */
71
+ export interface SpectrogramImage {
72
+ /** Frames (columns). */
73
+ readonly width: number;
74
+ /** Bins (rows). */
75
+ readonly height: number;
76
+ /** 1 for plain values, 4 (RGBA) when a colormap was given. */
77
+ readonly channels: 1 | 4;
78
+ /** Row-major, `width` per row. */
79
+ readonly data: Uint8Array | Float32Array;
80
+ }
81
+ /** Options for `spectrogram`. */
82
+ export interface SpectrogramOptions {
83
+ /** Decibels (10 log10 of power over `ref`) instead of linear power. Default true. */
84
+ readonly dB?: boolean;
85
+ /** Lowest decibel value kept, relative to `ref`. Default -100. */
86
+ readonly floor?: number;
87
+ /** [low, high] decibels mapped to 0 and 1 (or 0 and 255). Default [floor, 0]. */
88
+ readonly range?: readonly [number, number];
89
+ /** Reference power: `'max'` (default, the loudest cell is 0 dB) or a number. */
90
+ readonly ref?: 'max' | number;
91
+ /** `'u8'` (default) normalised 0 to 255 over `range`, or `'f32'` the raw decibel (or power) values. */
92
+ readonly format?: 'u8' | 'f32';
93
+ /** `'heat'` or a function from 0..1 to [r, g, b] (0..255): output RGBA bytes. */
94
+ readonly colormap?: 'heat' | ((t: number) => readonly [number, number, number]);
95
+ /** Which end is row 0: `'low'` (default, the lowest frequency) or `'high'` (top-down images). */
96
+ readonly origin?: 'low' | 'high';
97
+ }
98
+ /**
99
+ * A spectrogram image of a spectrum: power per frame and bin, in decibels by default, normalised to bytes (and
100
+ * optionally coloured) ready to upload as a texture of `width` x `height`.
101
+ * @example const { width, height, data } = spectrogram(stft(samples), { colormap: 'heat' });
102
+ */
103
+ export declare function spectrogram(spec: Spectrum, options?: SpectrogramOptions): SpectrogramImage;
104
+ /** A magnitude spectrogram to invert: `frames` rows of `bins` non-negative values, plus the analysis settings. */
105
+ export interface Magnitude {
106
+ readonly magnitude: Float32Array | Float64Array;
107
+ readonly frames: number;
108
+ readonly size: number;
109
+ readonly hop: number;
110
+ /** Default `'hann'`. */
111
+ readonly window?: WindowName | ArrayLike<number>;
112
+ /** Default true. */
113
+ readonly center?: boolean;
114
+ /** Samples to return. Default (frames - 1) * hop when centred. */
115
+ readonly length?: number;
116
+ }
117
+ /** Options for `resynthesize`. */
118
+ export interface ResynthesizeOptions {
119
+ /** Griffin-Lim iterations, 1 to 10000. Default 32. */
120
+ readonly iterations?: number;
121
+ /** Momentum alpha of the fast algorithm, 0 (plain Griffin-Lim) to 0.999. Default 0.99. */
122
+ readonly momentum?: number;
123
+ /** Starting phase: `'random'` (default, seeded), `'zero'`, or a spectrum whose phase is used. */
124
+ readonly init?: 'random' | 'zero' | Spectrum;
125
+ /** Seed of the random phase. Default 1. */
126
+ readonly seed?: number;
127
+ readonly signal?: AbortSignal;
128
+ }
129
+ /** What `resynthesize` returns. */
130
+ export interface Resynthesis {
131
+ readonly samples: Float32Array;
132
+ /** Spectral convergence ||target - |STFT(estimate)|| / ||target|| after each iteration (smaller is better). */
133
+ readonly convergence: Float64Array;
134
+ /** Frame FFTs run: iterations x 2 x frames for the projections plus frames for the final inverse. */
135
+ readonly transforms: number;
136
+ }
137
+ /**
138
+ * Estimates a signal whose STFT magnitude matches `magnitude` by the fast Griffin-Lim algorithm: alternate projecting
139
+ * onto consistent spectrograms (inverse then forward transform) and onto the given magnitude, with a momentum step.
140
+ * Momentum 0 is the original Griffin and Lim algorithm, whose spectral convergence never gets worse.
141
+ * @example const { samples } = resynthesize({ magnitude, frames, size: 2048, hop: 512 }, { iterations: 64 });
142
+ */
143
+ export declare function resynthesize(target: Magnitude, options?: ResynthesizeOptions): Resynthesis;
@@ -0,0 +1,384 @@
1
+ import { i as e, r as t, t as n } from "./errors-D8rc8kzg.js";
2
+ import { i as r, n as i, r as a } from "./spectrogram-fft-CRLetuHA.js";
3
+ //#region src/spectrogram-windows.ts
4
+ function o(e, t, n) {
5
+ s(e);
6
+ let r = new Float64Array(e), i = n.symmetric ? Math.max(e - 1, 1) : e;
7
+ for (let n = 0; n < e; n++) {
8
+ let e = 0;
9
+ for (let r = 0; r < t.length; r++) e += (r % 2 ? -1 : 1) * t[r] * Math.cos(2 * Math.PI * r * n / i);
10
+ r[n] = e;
11
+ }
12
+ return r;
13
+ }
14
+ function s(e) {
15
+ if (!Number.isInteger(e) || e < 1) throw t(`Window size must be a whole number of at least 1, got ${e}`, "state");
16
+ }
17
+ function c(e) {
18
+ let t = 1, n = 1;
19
+ for (let r = 1; r < 200 && n > 1e-17 * t; r++) n *= (e / (2 * r)) ** 2, t += n;
20
+ return t;
21
+ }
22
+ var l = {
23
+ rectangular(e) {
24
+ return s(e), new Float64Array(e).fill(1);
25
+ },
26
+ hann: (e, t = {}) => o(e, [.5, .5], t),
27
+ hamming: (e, t = {}) => o(e, [.54, .46], t),
28
+ blackman: (e, t = {}) => o(e, [
29
+ .42,
30
+ .5,
31
+ .08
32
+ ], t),
33
+ blackmanHarris: (e, t = {}) => o(e, [
34
+ .35875,
35
+ .48829,
36
+ .14128,
37
+ .01168
38
+ ], t),
39
+ kaiser(e, n = 8.6, r = {}) {
40
+ if (s(e), !(n >= 0) || !Number.isFinite(n)) throw t(`Kaiser beta must be 0 or more, got ${n}`, "state");
41
+ let i = new Float64Array(e), a = (r.symmetric ? Math.max(e - 1, 1) : e) / 2, o = c(n);
42
+ for (let t = 0; t < e; t++) {
43
+ let e = (t - a) / a;
44
+ i[t] = c(n * Math.sqrt(Math.max(0, 1 - e * e))) / o;
45
+ }
46
+ return i;
47
+ }
48
+ };
49
+ function u(e, n) {
50
+ if (e === void 0 || e === "hann") return l.hann(n);
51
+ if (typeof e != "string") {
52
+ if (e.length !== n) throw t(`A window array must hold ${n} numbers, got ${e.length}`, "state");
53
+ return Float64Array.from(e);
54
+ }
55
+ switch (e) {
56
+ case "hamming": return l.hamming(n);
57
+ case "blackman": return l.blackman(n);
58
+ case "blackman-harris": return l.blackmanHarris(n);
59
+ case "kaiser": return l.kaiser(n);
60
+ case "rectangular": return l.rectangular(n);
61
+ }
62
+ throw t(`Unknown window "${String(e)}"; use hann, hamming, blackman, blackman-harris, kaiser or rectangular`, "state");
63
+ }
64
+ //#endregion
65
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/usingCtx.js
66
+ function d() {
67
+ var e = typeof SuppressedError == "function" ? SuppressedError : function(e, t) {
68
+ var n = Error();
69
+ return n.name = "SuppressedError", n.error = e, n.suppressed = t, n;
70
+ }, t = {}, n = [];
71
+ function r(e, t) {
72
+ if (t != null) {
73
+ if (Object(t) !== t) throw TypeError("using declarations can only be used with objects, functions, null, or undefined.");
74
+ if (e) var r = t[Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose")];
75
+ if (r === void 0 && (r = t[Symbol.dispose || Symbol.for("Symbol.dispose")], e)) var i = r;
76
+ if (typeof r != "function") throw TypeError("Object is not disposable.");
77
+ i && (r = function() {
78
+ try {
79
+ i.call(t);
80
+ } catch (e) {
81
+ return Promise.reject(e);
82
+ }
83
+ }), n.push({
84
+ v: t,
85
+ d: r,
86
+ a: e
87
+ });
88
+ } else e && n.push({
89
+ d: t,
90
+ a: e
91
+ });
92
+ return t;
93
+ }
94
+ return {
95
+ e: t,
96
+ u: r.bind(null, !1),
97
+ a: r.bind(null, !0),
98
+ d: function() {
99
+ var r, i = this.e, a = 0;
100
+ function o() {
101
+ for (; r = n.pop();) try {
102
+ if (!r.a && a === 1) return a = 0, n.push(r), Promise.resolve().then(o);
103
+ if (r.d) {
104
+ var e = r.d.call(r.v);
105
+ if (r.a) return a |= 2, Promise.resolve(e).then(o, s);
106
+ } else a |= 1;
107
+ } catch (e) {
108
+ return s(e);
109
+ }
110
+ if (a === 1) return i === t ? Promise.resolve() : Promise.reject(i);
111
+ if (i !== t) throw i;
112
+ }
113
+ function s(n) {
114
+ return i = i === t ? n : new e(n, i), o();
115
+ }
116
+ return o();
117
+ }
118
+ };
119
+ }
120
+ //#endregion
121
+ //#region src/spectrogram.ts
122
+ var f = (e) => {
123
+ throw t(e, "state");
124
+ }, p = 2 ** 27;
125
+ function m(e, t) {
126
+ let n = t.size ?? 2048, r = t.hop ?? Math.max(1, n / 4), i = t.center ?? !0, a = t.sampleRate ?? 44100, o = t.pad ?? "reflect";
127
+ (!Number.isInteger(n) || n < 32 || n > 65536 || n & n - 1) && f(`STFT size must be a power of two from 32 to 65536, got ${n}`), (!Number.isInteger(r) || r < 1 || r > n) && f(`STFT hop must be a whole number from 1 to size (${n}), got ${r}`), (!(a > 0) || !Number.isFinite(a)) && f(`Sample rate must be a positive number, got ${a}`), o !== "reflect" && o !== "zero" && o !== "edge" && f(`Unknown pad "${String(o)}"; use reflect, zero or edge`), e < 1 && f("STFT needs at least one sample"), !i && e < n && f(`Without centring the signal needs at least size (${n}) samples, got ${e}`);
128
+ let s = i ? 1 + Math.floor(e / r) : 1 + Math.floor((e - n) / r), c = n / 2 + 1;
129
+ return s * c > p && f(`${s} frames of ${c} bins is over ${p} values; use a larger hop or a shorter signal`), {
130
+ size: n,
131
+ hop: r,
132
+ window: u(t.window, n),
133
+ center: i,
134
+ sampleRate: a,
135
+ frames: s,
136
+ bins: c,
137
+ pad: o
138
+ };
139
+ }
140
+ function h(t) {
141
+ if (typeof t != "object" || !t || typeof t.length != "number") throw e("Samples must be a Float32Array, Float64Array or array of numbers", "state");
142
+ for (let e = 0; e < t.length; e++) Number.isFinite(t[e]) || f(`Sample ${e} is ${t[e]}; samples must be finite numbers`);
143
+ return t;
144
+ }
145
+ var g = (e, t) => {
146
+ if (t === 1) return 0;
147
+ let n = 2 * (t - 1), r = (e % n + n) % n;
148
+ return r < t ? r : n - r;
149
+ };
150
+ function _(e, t) {
151
+ let n = e.length, r = t.center ? t.size / 2 : 0, i = new Float64Array(t.center ? n + t.size : n);
152
+ for (let a = 0; a < i.length; a++) {
153
+ let o = a - r;
154
+ o >= 0 && o < n ? i[a] = e[o] : t.pad === "reflect" ? i[a] = e[g(o, n)] : t.pad === "edge" && (i[a] = e[o < 0 ? 0 : n - 1]);
155
+ }
156
+ return i;
157
+ }
158
+ var v = class {
159
+ #e;
160
+ #t;
161
+ #n;
162
+ #r;
163
+ #i;
164
+ #a;
165
+ #o;
166
+ #s;
167
+ constructor(e, t, n, r) {
168
+ this.size = e, this.hop = t, this.window = n, this.frames = r, this.fft = i(e), this.bins = e / 2 + 1, this.span = (r - 1) * t + e, this.#e = new Float64Array(e), this.#t = new Float64Array(e), this.#n = new Float64Array(e), this.#r = new Float64Array(e), this.#i = new Float64Array(this.bins), this.#a = new Float64Array(this.bins), this.#o = new Float64Array(this.bins), this.#s = new Float64Array(this.bins);
169
+ let a = new Float64Array(this.span);
170
+ for (let i = 0; i < r; i++) for (let r = 0; r < e; r++) a[i * t + r] += n[r] * n[r];
171
+ this.inverseEnvelope = a.map((e) => e > 1e-12 ? 1 / e : 0);
172
+ }
173
+ analyse(e, t, n, i) {
174
+ let { size: a, hop: o, window: s, frames: c, bins: l } = this;
175
+ for (let u = 0; u < c; u += 2) {
176
+ i?.throwIfAborted();
177
+ let d = u + 1 < c;
178
+ for (let t = 0; t < a; t++) this.#e[t] = e[u * o + t] * s[t], this.#t[t] = d ? e[(u + 1) * o + t] * s[t] : 0;
179
+ r(this.fft, this.#e, this.#t, this.#n, this.#r, this.#i, this.#a, this.#o, this.#s);
180
+ for (let e = 0; e < l; e++) t[u * l + e] = this.#i[e], n[u * l + e] = this.#a[e], d && (t[(u + 1) * l + e] = this.#o[e], n[(u + 1) * l + e] = this.#s[e]);
181
+ }
182
+ }
183
+ synthesise(e, t, n, r) {
184
+ let { size: i, hop: o, window: s, frames: c, bins: l } = this;
185
+ n.fill(0);
186
+ for (let u = 0; u < c; u += 2) {
187
+ r?.throwIfAborted();
188
+ let d = u + 1 < c;
189
+ for (let n = 0; n < l; n++) this.#i[n] = e[u * l + n], this.#a[n] = t[u * l + n], this.#o[n] = d ? e[(u + 1) * l + n] : 0, this.#s[n] = d ? t[(u + 1) * l + n] : 0;
190
+ a(this.fft, this.#i, this.#a, this.#o, this.#s, this.#n, this.#r, this.#e, this.#t);
191
+ for (let e = 0; e < i; e++) n[u * o + e] += this.#e[e] * s[e], d && (n[(u + 1) * o + e] += this.#t[e] * s[e]);
192
+ }
193
+ for (let e = 0; e < n.length; e++) n[e] *= this.inverseEnvelope[e];
194
+ }
195
+ };
196
+ function y(e, t) {
197
+ let n = Infinity, r = 0;
198
+ for (let i = 0; i < Math.min(t, e.length); i++) {
199
+ let a = 0;
200
+ for (let n = i; n < e.length; n += t) a += e[n] * e[n];
201
+ n = Math.min(n, a), r = Math.max(r, a);
202
+ }
203
+ return r > 0 ? n / r : 0;
204
+ }
205
+ function b(e, t) {
206
+ let r = y(e, t);
207
+ if (!(r >= .1)) throw n("state", `Window and hop do not overlap-add evenly (smallest over largest summed squared window is ${r.toFixed(3)}, needs 0.1); use a hop of size / 4 or size / 2 with a Hann window`);
208
+ }
209
+ function x(e, t = {}) {
210
+ let n = h(e), r = m(n.length, t), i = t.signal, a = _(n, r);
211
+ i?.throwIfAborted();
212
+ let o = new Float32Array(r.frames * r.bins), s = new Float32Array(r.frames * r.bins), c = {
213
+ real: o,
214
+ imag: s,
215
+ frames: r.frames,
216
+ bins: r.bins,
217
+ size: r.size,
218
+ hop: r.hop,
219
+ sampleRate: r.sampleRate,
220
+ center: r.center,
221
+ length: n.length,
222
+ window: r.window
223
+ };
224
+ return "gpu" in t && t.gpu ? S(t.gpu, a, r, c, i) : (new v(r.size, r.hop, r.window, r.frames).analyse(a, o, s, i), c);
225
+ }
226
+ async function S(e, t, n, r, i) {
227
+ let { fft: a } = await import("@margoengine/compute/fft"), { size: o, hop: s, window: c, bins: l } = n, u = Math.max(1, Math.floor(2 ** 22 / o));
228
+ for (let p = 0; p < n.frames; p += u) try {
229
+ var f = d();
230
+ i?.throwIfAborted();
231
+ let m = Math.min(u, n.frames - p), h = new Float32Array(m * o);
232
+ for (let e = 0; e < m; e++) for (let n = 0; n < o; n++) h[e * o + n] = t[(p + e) * s + n] * c[n];
233
+ let { re: g, im: _ } = a(f.u(e.array(h, { shape: [m, o] })));
234
+ try {
235
+ let [e, t] = await Promise.all([g.read({ signal: i }), _.read({ signal: i })]);
236
+ for (let n = 0; n < m; n++) for (let i = 0; i < l; i++) r.real[(p + n) * l + i] = e[n * o + i], r.imag[(p + n) * l + i] = t[n * o + i];
237
+ } finally {
238
+ g.dispose(), _.dispose();
239
+ }
240
+ } catch (e) {
241
+ f.e = e;
242
+ } finally {
243
+ f.d();
244
+ }
245
+ return r;
246
+ }
247
+ function C(e, t = {}) {
248
+ b(e.window, e.hop);
249
+ let n = new v(e.size, e.hop, e.window, e.frames), r = new Float64Array(n.span);
250
+ return n.synthesise(e.real, e.imag, r, t.signal), w(r, e, t.length);
251
+ }
252
+ function w(e, t, n) {
253
+ let r = t.center ? t.size / 2 : 0, i = n ?? t.length;
254
+ return (!Number.isInteger(i) || i < 0 || r + i > e.length) && f(`Length must be a whole number from 0 to ${e.length - r}, got ${i}`), Float32Array.from(e.subarray(r, r + i));
255
+ }
256
+ var T = [
257
+ [
258
+ 0,
259
+ 0,
260
+ 0
261
+ ],
262
+ [
263
+ 60,
264
+ 0,
265
+ 100
266
+ ],
267
+ [
268
+ 190,
269
+ 40,
270
+ 80
271
+ ],
272
+ [
273
+ 250,
274
+ 150,
275
+ 20
276
+ ],
277
+ [
278
+ 255,
279
+ 250,
280
+ 200
281
+ ]
282
+ ], E = (e) => {
283
+ let t = Math.min(.999999, Math.max(0, e)) * (T.length - 1), n = Math.floor(t), r = t - n;
284
+ return [
285
+ 0,
286
+ 1,
287
+ 2
288
+ ].map((e) => T[n][e] + r * (T[n + 1][e] - T[n][e]));
289
+ };
290
+ function D(e, t = {}) {
291
+ let n = t.dB ?? !0, r = t.floor ?? -100, [i, a] = t.range ?? [r, 0], o = e.frames * e.bins, s = new Float64Array(o);
292
+ (!(r < 0) || !(i < a)) && f(`Floor must be below 0 and range [low, high] needs low < high, got floor ${r}, range [${i}, ${a}]`);
293
+ let c = 0;
294
+ for (let t = 0; t < o; t++) s[t] = e.real[t] ** 2 + e.imag[t] ** 2, s[t] > c && (c = s[t]);
295
+ let l = t.ref === void 0 || t.ref === "max" ? c : t.ref;
296
+ !(l >= 0) && l !== 0 && f(`Reference power must be a number of 0 or more, got ${String(t.ref)}`);
297
+ let u = new Float32Array(o);
298
+ for (let e = 0; e < o; e++) u[e] = n ? Math.max(r, 10 * Math.log10(Math.max(s[e], 1e-30) / Math.max(l, 1e-30))) : s[e];
299
+ let d = t.origin === "high", p = (t) => d ? e.bins - 1 - t : t, m = t.colormap === "heat" ? E : t.colormap, h = (e) => Math.min(1, Math.max(0, (e - i) / (a - i)));
300
+ if (t.format === "f32" && !m) {
301
+ let t = new Float32Array(o);
302
+ for (let n = 0; n < e.bins; n++) for (let r = 0; r < e.frames; r++) t[n * e.frames + r] = u[r * e.bins + p(n)];
303
+ return {
304
+ width: e.frames,
305
+ height: e.bins,
306
+ channels: 1,
307
+ data: t
308
+ };
309
+ }
310
+ if (m) {
311
+ let t = new Uint8Array(4 * o);
312
+ for (let n = 0; n < e.bins; n++) for (let r = 0; r < e.frames; r++) {
313
+ let [i, a, o] = m(h(u[r * e.bins + p(n)])), s = 4 * (n * e.frames + r);
314
+ t[s] = Math.round(i), t[s + 1] = Math.round(a), t[s + 2] = Math.round(o), t[s + 3] = 255;
315
+ }
316
+ return {
317
+ width: e.frames,
318
+ height: e.bins,
319
+ channels: 4,
320
+ data: t
321
+ };
322
+ }
323
+ let g = new Uint8Array(o);
324
+ for (let t = 0; t < e.bins; t++) for (let n = 0; n < e.frames; n++) g[t * e.frames + n] = Math.round(255 * h(u[n * e.bins + p(t)]));
325
+ return {
326
+ width: e.frames,
327
+ height: e.bins,
328
+ channels: 1,
329
+ data: g
330
+ };
331
+ }
332
+ function O(e, t = {}) {
333
+ let { size: n, hop: r, frames: i } = e, a = e.center ?? !0, o = t.iterations ?? 32, s = t.momentum ?? .99, c = u(e.window, n), l = n / 2 + 1;
334
+ m(a ? Math.max(1, (i - 1) * r) : n + (i - 1) * r, {
335
+ size: n,
336
+ hop: r,
337
+ center: a,
338
+ window: c
339
+ }), (!Number.isInteger(i) || i < 1 || e.magnitude.length !== i * l) && f(`Magnitude needs frames x ${l} values; got ${e.magnitude.length} for ${i} frames`), (!Number.isInteger(o) || o < 1 || o > 1e4) && f(`Iterations must be a whole number from 1 to 10000, got ${o}`), s >= 0 && s <= .999 || f(`Momentum must be from 0 to 0.999, got ${s}`), b(c, r);
340
+ let d = i * l, p = Float64Array.from(e.magnitude), h = 0;
341
+ for (let e = 0; e < d; e++) (!(p[e] >= 0) || !Number.isFinite(p[e])) && f(`Magnitude ${e} is ${p[e]}; magnitudes must be finite and at least 0`), h += p[e] * p[e];
342
+ let g = new v(n, r, c, i), _ = new Float64Array(d), y = new Float64Array(d), x = new Float64Array(d), S = new Float64Array(d), C = new Float64Array(d), T = new Float64Array(d), E = new Float64Array(g.span), D = new Float64Array(o), O = t.init ?? "random";
343
+ if (typeof O == "object") {
344
+ (O.frames !== i || O.size !== n) && f("The init spectrum must have the same frames and size as the magnitude");
345
+ for (let e = 0; e < d; e++) {
346
+ let t = Math.hypot(O.real[e], O.imag[e]);
347
+ _[e] = t > 0 ? p[e] * O.real[e] / t : p[e], y[e] = t > 0 ? p[e] * O.imag[e] / t : 0;
348
+ }
349
+ } else if (O === "zero") _.set(p);
350
+ else if (O === "random") {
351
+ let e = (t.seed ?? 1) >>> 0;
352
+ for (let t = 0; t < d; t++) {
353
+ e = e + 1831565813 >>> 0;
354
+ let n = e;
355
+ n = Math.imul(n ^ n >>> 15, n | 1), n ^= n + Math.imul(n ^ n >>> 7, n | 61);
356
+ let r = 2 * Math.PI * ((n ^ n >>> 14) >>> 0) / 4294967296;
357
+ _[t] = p[t] * Math.cos(r), y[t] = p[t] * Math.sin(r);
358
+ }
359
+ } else f(`Unknown init "${String(O)}"; use random, zero or a Spectrum`);
360
+ for (let e = 0; e < i; e++) y[e * l] = 0, y[e * l + l - 1] = 0;
361
+ x.set(_), S.set(y);
362
+ for (let e = 0; e < o; e++) {
363
+ t.signal?.throwIfAborted(), g.synthesise(x, S, E, t.signal), g.analyse(E, C, T, t.signal);
364
+ let n = 0;
365
+ for (let e = 0; e < d; e++) {
366
+ let t = Math.hypot(C[e], T[e]), r = p[e] - t;
367
+ n += r * r;
368
+ let i = t > 1e-30 ? p[e] * C[e] / t : p[e], a = t > 1e-30 ? p[e] * T[e] / t : 0;
369
+ x[e] = i + s * (i - _[e]), S[e] = a + s * (a - y[e]), _[e] = i, y[e] = a;
370
+ }
371
+ D[e] = h > 0 ? Math.sqrt(n / h) : 0;
372
+ }
373
+ return g.synthesise(_, y, E, t.signal), {
374
+ samples: w(E, {
375
+ size: n,
376
+ center: a,
377
+ length: e.length ?? (a ? (i - 1) * r : g.span)
378
+ }, e.length),
379
+ convergence: D,
380
+ transforms: o * 2 * i + i
381
+ };
382
+ }
383
+ //#endregion
384
+ export { C as istft, y as overlapRatio, O as resynthesize, D as spectrogram, x as stft, l as windows };
@@ -0,0 +1,59 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import { Audio, type AudioListener, type AudioOptions, type LoadAudioOptions } from '@margoengine/audio';
3
+ /** A named interval in a shared decoded audio buffer, in seconds. */
4
+ export interface AudioSprite {
5
+ /** Start in buffer seconds, finite and nonnegative. */
6
+ offset: number;
7
+ /** Positive finite buffer seconds, wholly within the buffer. */
8
+ duration: number;
9
+ /** Repeat only this interval. Default false. */
10
+ loop?: boolean;
11
+ }
12
+ /** Sound options independent of the sprite's authored interval/loop. */
13
+ export type AudioSpritePlayOptions = Omit<AudioOptions, 'offset' | 'duration' | 'loopStart' | 'loopEnd' | 'loop' | 'autoplay'>;
14
+ /** Named, overlapping clips sharing one buffer; no per-play buffer slicing or copying. */
15
+ export declare class AudioSpriteBank {
16
+ readonly listener: AudioListener;
17
+ readonly buffer: AudioBuffer;
18
+ private readonly sprites;
19
+ private readonly sounds;
20
+ /** Instances started by play(): released by the bank on natural end or stopAll. */
21
+ private readonly oneShots;
22
+ private disposed;
23
+ constructor(listener: AudioListener, buffer: AudioBuffer, sprites: Readonly<Record<string, AudioSprite>>);
24
+ /** Available sprite names, copied in map order. */
25
+ get names(): readonly string[];
26
+ /**
27
+ * Create a stopped clip with its authored loop bounds. The caller owns it: it can be played again after it ends or
28
+ * is stopped, until the caller or the bank disposes it.
29
+ */
30
+ create(name: string, options?: AudioSpritePlayOptions): Audio;
31
+ /**
32
+ * Create and start an independent fire-and-forget instance; delay defaults to 0 audio-clock seconds. The bank
33
+ * releases it when it ends naturally or {@link stopAll} stops it; dispose one you stop yourself.
34
+ */
35
+ play(name: string, options?: AudioSpritePlayOptions, delay?: number): Audio;
36
+ /** Stop every instance. play() instances are released; create() clips stay owned and can play again. */
37
+ stopAll(): void;
38
+ private release;
39
+ /** @internal Forget caller-disposed sounds on listener updates. */
40
+ update(): void;
41
+ /** Stop/release all owned instances. The shared buffer remains usable. Idempotent. */
42
+ dispose(): void;
43
+ [Symbol.dispose]: () => void;
44
+ }
45
+ /** A URL and optional explicit MIME/codec declaration, or a URL with a known extension. */
46
+ export type AudioCodecCandidate = string | {
47
+ readonly url: string;
48
+ readonly type: string;
49
+ };
50
+ /** Loading controls plus an injectable browser capability probe for workers or server-side tests. */
51
+ export interface AudioCodecFallbackOptions extends LoadAudioOptions {
52
+ /** Default lazily creates an HTML audio element. Order is the candidate list order; both maybe/probably are eligible. */
53
+ canPlayType?: (type: string) => CanPlayTypeResult;
54
+ }
55
+ /**
56
+ * Try each browser-supported URL once in order until fetching/decoding succeeds.
57
+ * Abort stops the complete operation; exhaustion preserves every failure as an AggregateError cause.
58
+ */
59
+ export declare function loadAudioFallback(listener: AudioListener, candidates: readonly AudioCodecCandidate[], options?: AudioCodecFallbackOptions): Promise<AudioBuffer>;
@@ -0,0 +1,99 @@
1
+ import { r as e, t } from "./errors-D8rc8kzg.js";
2
+ import { Audio as n } from "@margoengine/audio";
3
+ //#region src/sprites.ts
4
+ var r = class {
5
+ constructor(n, r, i) {
6
+ if (this.listener = n, this.buffer = r, this.sprites = /* @__PURE__ */ new Map(), this.sounds = /* @__PURE__ */ new Set(), this.oneShots = /* @__PURE__ */ new WeakSet(), this.disposed = !1, !r || !Number.isFinite(r.duration) || r.duration <= 0) throw t("state", "Audio sprites need a positive-duration decoded buffer; use listener.load first");
7
+ for (let [t, n] of Object.entries(i)) {
8
+ if (!t || !n || !Number.isFinite(n.offset) || n.offset < 0 || !Number.isFinite(n.duration) || n.duration <= 0 || n.offset + n.duration > r.duration || n.loop !== void 0 && typeof n.loop != "boolean") throw e("Audio sprite names and intervals must be valid and within the buffer; use a nonempty name and offset/duration in seconds", "state");
9
+ this.sprites.set(t, Object.freeze({ ...n }));
10
+ }
11
+ n.addSource(this);
12
+ }
13
+ get names() {
14
+ return [...this.sprites.keys()];
15
+ }
16
+ create(e, r = {}) {
17
+ if (this.disposed) throw t("disposed", "AudioSpriteBank is disposed; create a new bank");
18
+ let i = this.sprites.get(e);
19
+ if (!i) throw t("state", `Unknown audio sprite ${e}; choose a name from bank.names`);
20
+ let a = new n(this.listener, {
21
+ ...r,
22
+ autoplay: !1,
23
+ offset: i.offset,
24
+ duration: i.duration,
25
+ loop: i.loop ?? !1,
26
+ loopStart: i.offset,
27
+ loopEnd: i.offset + i.duration,
28
+ onEnded: (e) => {
29
+ try {
30
+ r.onEnded?.(e);
31
+ } finally {
32
+ this.oneShots.has(e) && this.release(e);
33
+ }
34
+ }
35
+ }).setBuffer(this.buffer);
36
+ return this.sounds.add(a), a;
37
+ }
38
+ play(t, n = {}, r = 0) {
39
+ if (!Number.isFinite(r) || r < 0) throw e("Sprite delay must be finite and nonnegative; use seconds", "state");
40
+ let i = this.create(t, n);
41
+ return this.oneShots.add(i), i.play(r);
42
+ }
43
+ stopAll() {
44
+ for (let e of this.sounds) e.isDisposed ? this.sounds.delete(e) : this.oneShots.has(e) ? this.release(e) : e.stop();
45
+ }
46
+ release(e) {
47
+ this.sounds.delete(e), e.dispose();
48
+ }
49
+ update() {
50
+ for (let e of this.sounds) e.isDisposed && this.sounds.delete(e);
51
+ }
52
+ dispose() {
53
+ if (!this.disposed) {
54
+ this.disposed = !0, this.listener.removeSource(this);
55
+ for (let e of this.sounds) e.dispose();
56
+ this.sounds.clear();
57
+ }
58
+ }
59
+ [Symbol.dispose ?? Symbol()]() {
60
+ this.dispose();
61
+ }
62
+ }, i = {
63
+ mp3: "audio/mpeg",
64
+ ogg: "audio/ogg",
65
+ opus: "audio/ogg; codecs=\"opus\"",
66
+ wav: "audio/wav",
67
+ m4a: "audio/mp4",
68
+ mp4: "audio/mp4",
69
+ aac: "audio/aac",
70
+ webm: "audio/webm",
71
+ flac: "audio/flac"
72
+ };
73
+ async function a(e, n, r = {}) {
74
+ if (r.signal?.throwIfAborted(), !n.length) throw t("state", "Audio fallback needs at least one candidate; pass URLs or {url,type} entries");
75
+ let a = r.canPlayType ?? (() => {
76
+ if (typeof document > "u") throw t("unsupported", "Audio fallback needs canPlayType; pass options.canPlayType outside a document");
77
+ let e = document.createElement("audio");
78
+ return e.canPlayType.bind(e);
79
+ })(), o = n.map((e) => {
80
+ let n = typeof e == "string" ? e : e?.url, r = typeof e == "string" ? i[e.split(/[?#]/)[0].split(".").at(-1).toLowerCase()] : e?.type;
81
+ if (typeof n != "string" || !n || typeof r != "string" || !r) throw t("state", "Audio fallback candidate needs a URL and a known type; pass {url,type} for extensionless URLs");
82
+ return {
83
+ url: n,
84
+ type: r
85
+ };
86
+ }), s = [];
87
+ for (let { url: t, type: n } of o) {
88
+ r.signal?.throwIfAborted();
89
+ let i = a(n);
90
+ if (i === "maybe" || i === "probably") try {
91
+ return await e.load(t, r);
92
+ } catch (e) {
93
+ r.signal?.throwIfAborted(), s.push(e);
94
+ }
95
+ }
96
+ throw s.length ? Object.assign(t("failed", "Every supported audio candidate failed; inspect cause.errors and supply a working URL/codec"), { cause: AggregateError(s, "Audio codec fallback exhausted") }) : t("unsupported", "No audio candidate is supported by this browser; supply another MIME/codec alternative");
97
+ }
98
+ //#endregion
99
+ export { r as AudioSpriteBank, a as loadAudioFallback };