@margoengine/audio 0.0.0-stage → 0.1.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 (51) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +748 -3
  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 +46 -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 +270 -0
  33. package/dist/scan.d.ts +66 -0
  34. package/dist/scan.js +75 -0
  35. package/dist/spectrogram-fft.d.ts +26 -0
  36. package/dist/spectrogram-windows.d.ts +24 -0
  37. package/dist/spectrogram.d.ts +143 -0
  38. package/dist/spectrogram.js +440 -0
  39. package/dist/sprites.d.ts +59 -0
  40. package/dist/sprites.js +99 -0
  41. package/dist/stretch.d.ts +25 -0
  42. package/dist/stretch.js +55 -0
  43. package/dist/voice-manager.d.ts +100 -0
  44. package/dist/voice-manager.js +178 -0
  45. package/dist/voices-CdfPmzIo.js +425 -0
  46. package/dist/voices.d.ts +45 -0
  47. package/dist/wav.d.ts +47 -0
  48. package/dist/wav.js +156 -0
  49. package/dist/zones.d.ts +43 -0
  50. package/dist/zones.js +75 -0
  51. package/package.json +127 -6
@@ -0,0 +1,5 @@
1
+ /** Internal authored-rate validation and modulation shared by sounds and optional controllers. */
2
+ export declare const playbackRateModifiers: WeakMap<object, {
3
+ apply(value: number): number;
4
+ validate(value: number): void;
5
+ }>;
@@ -0,0 +1,53 @@
1
+ /** Audio as `decodeWav` returns it: a rate and one Float32Array per channel. */
2
+ export interface ResampleInput {
3
+ sampleRate: number;
4
+ channels: Float32Array[];
5
+ }
6
+ /** What {@link resample} returns. */
7
+ export interface ResampledAudio {
8
+ sampleRate: number;
9
+ channels: Float32Array[];
10
+ }
11
+ /** Options of {@link resample}. */
12
+ export interface ResampleOptions {
13
+ /**
14
+ * Output channel count, mixed by {@link mixChannels} (the Web Audio speaker rules for 1, 2, 4 and 6 channels,
15
+ * discrete otherwise). Default: the input's count.
16
+ */
17
+ channels?: number;
18
+ /** Zero crossings of the windowed sinc on each side of an output sample, 4 to 256. Default 32. */
19
+ zeroCrossings?: number;
20
+ /**
21
+ * The filter's cutoff as a share of the lower of the two Nyquist frequencies, 0.5 to 1. Default 0.92: with 32 zero
22
+ * crossings and a 90 dB Kaiser window a tone at or above the lower Nyquist frequency comes out at least 90 dB down,
23
+ * so nothing folds back, and the response is flat within 0.1 dB to 0.86 of it (19.0 kHz for 44.1 kHz to 48 kHz).
24
+ */
25
+ rolloff?: number;
26
+ /** Stopband attenuation of the Kaiser window in dB, 40 to 160. Default 90. */
27
+ attenuation?: number;
28
+ }
29
+ /**
30
+ * Channels mixed to `count` by the Web Audio speaker rules: mono, stereo, quad (L, R, SL, SR) and 5.1 (L, R, C, LFE,
31
+ * SL, SR) up and down; any other pair is discrete (channels copied in order, missing ones silent, extra ones dropped).
32
+ * Returns new arrays.
33
+ *
34
+ * @example
35
+ * import {mixChannels} from '@margoengine/audio/resample';
36
+ * const [mono] = mixChannels([new Float32Array([1, 0.5]), new Float32Array([0, 0.5])], 1);
37
+ * console.log([...mono]); // [0.5, 0.5]
38
+ */
39
+ export declare function mixChannels(channels: readonly Float32Array[], count: number): Float32Array[];
40
+ /**
41
+ * Converts audio to `sampleRate` by bandlimited interpolation (a Kaiser-windowed sinc, Smith and Gossett 1984), on
42
+ * plain Float32Array channels, in Node or a page. The output holds `ceil(length * sampleRate / input rate)` samples,
43
+ * so one second stays one second; samples before the start and after the end count as silence. Converting to the
44
+ * same rate copies the samples. A rate drop also filters out what the new rate cannot hold, so nothing aliases.
45
+ *
46
+ * @example
47
+ * import {resample} from '@margoengine/audio/resample';
48
+ * const take = {sampleRate: 44100, channels: [new Float32Array(44100)]};
49
+ * const voice = resample(take, 48000, {channels: 2});
50
+ * console.log(voice.sampleRate, voice.channels.length, voice.channels[0].length); // 48000 2 48000
51
+ * @throws RangeError for a rate that is not a positive integer up to 768000, or an option out of range.
52
+ */
53
+ export declare function resample(audio: ResampleInput, sampleRate: number, options?: ResampleOptions): ResampledAudio;
@@ -0,0 +1,270 @@
1
+ import { i as e, r as t } from "./errors-D8rc8kzg.js";
2
+ //#region src/resample.ts
3
+ var n = Math.SQRT1_2, r = 1024;
4
+ function i(e) {
5
+ let t = 1, n = 1, r = e * e / 4;
6
+ for (let e = 1; e < 64 && (n *= r / (e * e), t += n, !(n < t * 1e-17)); e++);
7
+ return t;
8
+ }
9
+ function a(e, t) {
10
+ let n = e * r, a = new Float64Array(n + 2), o = i(t);
11
+ a[0] = 1;
12
+ for (let s = 1; s <= n; s++) {
13
+ let n = s / r, c = n / e, l = c < 1 ? i(t * Math.sqrt(1 - c * c)) / o : 0;
14
+ a[s] = Math.sin(Math.PI * n) / (Math.PI * n) * l;
15
+ }
16
+ return a;
17
+ }
18
+ function o(r, i) {
19
+ if (!Array.isArray(r) || !r.length || !r.every((e) => e instanceof Float32Array)) throw e("Pass the channels as an array of Float32Array", "audio-resample");
20
+ let a = r[0].length;
21
+ if (!r.every((e) => e.length === a)) throw t("Every channel must hold the same number of samples", "audio-resample");
22
+ if (!Number.isInteger(i) || i < 1 || i > 32) throw t("Pass an output channel count from 1 to 32", "audio-resample");
23
+ let o = r.length, s = Array.from({ length: i }, () => new Float32Array(a)), c = (e, t, n) => {
24
+ let i = s[e], o = r[t];
25
+ for (let e = 0; e < a; e++) i[e] += n * o[e];
26
+ }, l = o === i ? void 0 : {
27
+ "1>2": [[
28
+ 0,
29
+ 0,
30
+ 1
31
+ ], [
32
+ 1,
33
+ 0,
34
+ 1
35
+ ]],
36
+ "1>4": [[
37
+ 0,
38
+ 0,
39
+ 1
40
+ ], [
41
+ 1,
42
+ 0,
43
+ 1
44
+ ]],
45
+ "1>6": [[
46
+ 2,
47
+ 0,
48
+ 1
49
+ ]],
50
+ "2>4": [[
51
+ 0,
52
+ 0,
53
+ 1
54
+ ], [
55
+ 1,
56
+ 1,
57
+ 1
58
+ ]],
59
+ "2>6": [[
60
+ 0,
61
+ 0,
62
+ 1
63
+ ], [
64
+ 1,
65
+ 1,
66
+ 1
67
+ ]],
68
+ "4>6": [
69
+ [
70
+ 0,
71
+ 0,
72
+ 1
73
+ ],
74
+ [
75
+ 1,
76
+ 1,
77
+ 1
78
+ ],
79
+ [
80
+ 4,
81
+ 2,
82
+ 1
83
+ ],
84
+ [
85
+ 5,
86
+ 3,
87
+ 1
88
+ ]
89
+ ],
90
+ "2>1": [[
91
+ 0,
92
+ 0,
93
+ .5
94
+ ], [
95
+ 0,
96
+ 1,
97
+ .5
98
+ ]],
99
+ "4>1": [
100
+ [
101
+ 0,
102
+ 0,
103
+ .25
104
+ ],
105
+ [
106
+ 0,
107
+ 1,
108
+ .25
109
+ ],
110
+ [
111
+ 0,
112
+ 2,
113
+ .25
114
+ ],
115
+ [
116
+ 0,
117
+ 3,
118
+ .25
119
+ ]
120
+ ],
121
+ "6>1": [
122
+ [
123
+ 0,
124
+ 0,
125
+ n
126
+ ],
127
+ [
128
+ 0,
129
+ 1,
130
+ n
131
+ ],
132
+ [
133
+ 0,
134
+ 2,
135
+ 1
136
+ ],
137
+ [
138
+ 0,
139
+ 4,
140
+ .5
141
+ ],
142
+ [
143
+ 0,
144
+ 5,
145
+ .5
146
+ ]
147
+ ],
148
+ "4>2": [
149
+ [
150
+ 0,
151
+ 0,
152
+ .5
153
+ ],
154
+ [
155
+ 0,
156
+ 2,
157
+ .5
158
+ ],
159
+ [
160
+ 1,
161
+ 1,
162
+ .5
163
+ ],
164
+ [
165
+ 1,
166
+ 3,
167
+ .5
168
+ ]
169
+ ],
170
+ "6>2": [
171
+ [
172
+ 0,
173
+ 0,
174
+ 1
175
+ ],
176
+ [
177
+ 0,
178
+ 2,
179
+ n
180
+ ],
181
+ [
182
+ 0,
183
+ 4,
184
+ n
185
+ ],
186
+ [
187
+ 1,
188
+ 1,
189
+ 1
190
+ ],
191
+ [
192
+ 1,
193
+ 2,
194
+ n
195
+ ],
196
+ [
197
+ 1,
198
+ 5,
199
+ n
200
+ ]
201
+ ],
202
+ "6>4": [
203
+ [
204
+ 0,
205
+ 0,
206
+ 1
207
+ ],
208
+ [
209
+ 0,
210
+ 2,
211
+ n
212
+ ],
213
+ [
214
+ 1,
215
+ 1,
216
+ 1
217
+ ],
218
+ [
219
+ 1,
220
+ 2,
221
+ n
222
+ ],
223
+ [
224
+ 2,
225
+ 4,
226
+ 1
227
+ ],
228
+ [
229
+ 3,
230
+ 5,
231
+ 1
232
+ ]
233
+ ]
234
+ }[`${o}>${i}`];
235
+ if (l) for (let [e, t, n] of l) c(e, t, n);
236
+ else for (let e = 0; e < Math.min(o, i); e++) s[e].set(r[e]);
237
+ return s;
238
+ }
239
+ function s(n, i, s = {}) {
240
+ if (!n || typeof n != "object") throw e("Pass {sampleRate, channels} audio", "audio-resample");
241
+ let { zeroCrossings: c = 32, rolloff: l = .92, attenuation: u = 90 } = s;
242
+ for (let e of [n.sampleRate, i]) if (!Number.isInteger(e) || e < 1 || e > 768e3) throw t("Sample rates must be whole numbers from 1 to 768000", "audio-resample");
243
+ if (!Number.isInteger(c) || c < 4 || c > 256) throw t("zeroCrossings must be a whole number from 4 to 256", "audio-resample");
244
+ if (!(l >= .5 && l <= 1)) throw t("rolloff must be from 0.5 to 1", "audio-resample");
245
+ if (!(u >= 40 && u <= 160)) throw t("attenuation must be from 40 to 160 dB", "audio-resample");
246
+ let d = o(n.channels, s.channels ?? n.channels.length), f = n.sampleRate, p = d[0].length;
247
+ if (f === i) return {
248
+ sampleRate: i,
249
+ channels: d
250
+ };
251
+ let m = Math.floor((p * i + f - 1) / f), h = l * Math.min(1, i / f), g = c / h, _ = a(c, u > 50 ? .1102 * (u - 8.7) : .5842 * (u - 21) ** .4 + .07886 * (u - 21)), v = new Float64Array(Math.ceil(2 * g) + 2), y = d.map(() => new Float32Array(m));
252
+ for (let e = 0; e < m; e++) {
253
+ let t = e * f / i, n = Math.max(0, Math.ceil(t - g)), a = Math.min(p - 1, Math.floor(t + g)), o = 0;
254
+ for (let e = n; e <= a; e++) {
255
+ let n = Math.abs(t - e) * h * r, i = Math.floor(n), a = n - i;
256
+ v[o++] = i >= _.length - 1 ? 0 : h * (_[i] + (_[i + 1] - _[i]) * a);
257
+ }
258
+ for (let t = 0; t < d.length; t++) {
259
+ let r = d[t], i = 0;
260
+ for (let e = 0; e < o; e++) i += v[e] * r[n + e];
261
+ y[t][e] = i;
262
+ }
263
+ }
264
+ return {
265
+ sampleRate: i,
266
+ channels: y
267
+ };
268
+ }
269
+ //#endregion
270
+ export { o as mixChannels, s as resample };
package/dist/scan.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ /** One clipped run: at least `run` samples in a row on one channel at or over `level` of full scale (either sign). */
2
+ export interface ClipRun {
3
+ /** The channel index. */
4
+ channel: number;
5
+ /** First sample of the run. */
6
+ startSample: number;
7
+ /** Samples in the run. */
8
+ length: number;
9
+ /** Seconds from the start: `startSample / sampleRate`. */
10
+ start: number;
11
+ /** Seconds: `(startSample + length) / sampleRate`. */
12
+ end: number;
13
+ }
14
+ /** Options of {@link scanClipping}. */
15
+ export interface ClippingOptions {
16
+ /** Share of full scale (0 to 1) a sample's magnitude must reach to sit at the rail. Default 0.999 (-0.009 dBFS
17
+ * sample peak), which also catches clipped audio that went through a lossy codec. */
18
+ level?: number;
19
+ /** Samples in a row at the rail that make a clip. Default 3: one full-scale sample is a peak, not a clip. */
20
+ run?: number;
21
+ }
22
+ /** What {@link scanClipping} gives back. */
23
+ export interface ClippingReport {
24
+ /** Every clipped run, ordered by start time, then channel. */
25
+ runs: ClipRun[];
26
+ /** Samples inside the runs, all channels. */
27
+ clippedSamples: number;
28
+ /** The largest |sample| anywhere (the sample peak, linear). */
29
+ peak: number;
30
+ }
31
+ /** Options of {@link findSilences}. */
32
+ export interface SilenceOptions {
33
+ /** A window whose level (dBFS, AES17: a full-scale sine is 0) is under this is silent. Default -50. */
34
+ floorDb?: number;
35
+ /** Silences shorter than this many seconds are not reported (pauses between words). Default 2. */
36
+ minSeconds?: number;
37
+ /** Window length in seconds. Default 0.01: 10 ms, so edges are found to within 10 ms. */
38
+ window?: number;
39
+ /** Only look inside these `[start, end]` spans in seconds (a section of a script, say); a silence never crosses a
40
+ * span's edge. Default: the whole signal. */
41
+ spans?: ReadonlyArray<readonly [number, number]>;
42
+ }
43
+ /** One silence: windows under the floor, in a row, lasting at least `minSeconds`. */
44
+ export interface Silence {
45
+ /** Seconds from the start of the signal. */
46
+ start: number;
47
+ /** Seconds from the start of the signal. */
48
+ end: number;
49
+ /** `end - start`. */
50
+ duration: number;
51
+ /** The loudest window inside, in dBFS (AES17); -Infinity when every sample is zero. */
52
+ level: number;
53
+ }
54
+ type Channels = ArrayLike<number> | ReadonlyArray<ArrayLike<number>>;
55
+ /**
56
+ * Finds clipped runs in decoded audio: `run` or more samples in a row on one channel whose magnitude is at or over
57
+ * `level` of full scale. `channels` is one channel or an array of them (`decodeWav(file).channels`).
58
+ */
59
+ export declare function scanClipping(channels: Channels, sampleRate: number, options?: ClippingOptions): ClippingReport;
60
+ /**
61
+ * Finds silences: runs of windows whose level (the mean square of all channels, in dBFS as AES17 defines it) is under
62
+ * `floorDb`, lasting at least `minSeconds`, inside `spans` when given. A trailing partial window counts by its own
63
+ * samples.
64
+ */
65
+ export declare function findSilences(samples: Channels, sampleRate: number, options?: SilenceOptions): Silence[];
66
+ export {};
package/dist/scan.js ADDED
@@ -0,0 +1,75 @@
1
+ import { i as e, r as t } from "./errors-D8rc8kzg.js";
2
+ //#region src/scan.ts
3
+ function n(n, r) {
4
+ let i = (e) => ArrayBuffer.isView(e) || Array.isArray(e) && e.length > 0 && typeof e[0] == "number", a = i(n) ? [n] : Array.isArray(n) ? n : null;
5
+ if (!a || !a.length || !a.every(i)) throw e(`${r} needs a channel (a Float32Array) or an array of channels`, "audio-scan");
6
+ if (a.some((e) => e.length !== a[0].length)) throw t(`${r} needs channels of one length`, "audio-scan");
7
+ return a;
8
+ }
9
+ var r = (e, n) => {
10
+ if (!(Number.isFinite(e) && e > 0)) throw t(`${n} needs a sampleRate above 0`, "audio-scan");
11
+ };
12
+ function i(e, i, a = {}) {
13
+ let o = n(e, "scanClipping");
14
+ r(i, "scanClipping");
15
+ let { level: s = .999, run: c = 3 } = a;
16
+ if (!(s > 0 && s <= 1)) throw t("scanClipping needs a level above 0 and at most 1", "audio-scan");
17
+ if (!(Number.isInteger(c) && c >= 1)) throw t("scanClipping needs a run of 1 or more samples", "audio-scan");
18
+ let l = [], u = 0, d = 0;
19
+ return o.forEach((e, t) => {
20
+ let n = 0;
21
+ for (let r = 0; r <= e.length; r++) {
22
+ let a = r < e.length ? Math.abs(e[r]) : 0;
23
+ if (a > d && (d = a), a >= s) n++;
24
+ else {
25
+ if (n >= c) {
26
+ let e = r - n;
27
+ l.push({
28
+ channel: t,
29
+ startSample: e,
30
+ length: n,
31
+ start: e / i,
32
+ end: r / i
33
+ }), u += n;
34
+ }
35
+ n = 0;
36
+ }
37
+ }
38
+ }), l.sort((e, t) => e.startSample - t.startSample || e.channel - t.channel), {
39
+ runs: l,
40
+ clippedSamples: u,
41
+ peak: d
42
+ };
43
+ }
44
+ function a(e, i, a = {}) {
45
+ let o = n(e, "findSilences");
46
+ r(i, "findSilences");
47
+ let { floorDb: s = -50, minSeconds: c = 2, window: l = .01 } = a;
48
+ if (!Number.isFinite(s)) throw t("findSilences needs a finite floorDb", "audio-scan");
49
+ if (!(c >= 0 && c < Infinity)) throw t("findSilences needs minSeconds of 0 or more", "audio-scan");
50
+ let u = Math.round(l * i);
51
+ if (!(u >= 1)) throw t("findSilences needs a window of at least one sample", "audio-scan");
52
+ let d = o[0].length, f = d / i, p = a.spans ?? [[0, f]];
53
+ for (let e of p) if (!(e.length === 2 && Number.isFinite(e[0]) && Number.isFinite(e[1]) && e[0] <= e[1])) throw t("findSilences needs spans of [start, end] seconds with start <= end", "audio-scan");
54
+ let m = .5 * 10 ** (s / 10), h = (e) => 10 * Math.log10(2 * e), g = [];
55
+ for (let [e, t] of p) {
56
+ let n = Math.max(0, Math.round(e * i)), r = Math.min(d, Math.round(t * i)), a = -1, s = 0, l = (e) => {
57
+ a >= 0 && (e - a) / i >= c && g.push({
58
+ start: a / i,
59
+ end: e / i,
60
+ duration: (e - a) / i,
61
+ level: s > 0 ? h(s) : -Infinity
62
+ }), a = -1, s = 0;
63
+ };
64
+ for (let e = n; e < r; e += u) {
65
+ let t = Math.min(e + u, r), n = 0;
66
+ for (let r of o) for (let i = e; i < t; i++) n += r[i] * r[i];
67
+ let i = n / ((t - e) * o.length);
68
+ i < m ? (a < 0 && (a = e), i > s && (s = i)) : l(e);
69
+ }
70
+ l(r);
71
+ }
72
+ return g.sort((e, t) => e.start - t.start);
73
+ }
74
+ //#endregion
75
+ export { a as findSilences, i as scanClipping };
@@ -0,0 +1,26 @@
1
+ /** Twiddles and bit-reversal order of one transform size. */
2
+ export interface FftPlan {
3
+ readonly size: number;
4
+ readonly cos: Float64Array;
5
+ readonly sin: Float64Array;
6
+ readonly reverse: Uint32Array;
7
+ }
8
+ /** The cached plan for a power-of-two `size` from 2 to 65536 (an FFT of 32 to 65536 points is what the entry accepts). */
9
+ export declare function fftPlan(size: number): FftPlan;
10
+ /**
11
+ * Complex transform of re/im in place: forward (exp(-2 pi i k n / N), unscaled) or inverse (conjugate twiddles, unscaled).
12
+ * Work: (N/2) log2 N butterflies.
13
+ */
14
+ export declare function fft(plan: FftPlan, re: Float64Array, im: Float64Array, inverse?: boolean): void;
15
+ /** Butterflies of one complex transform of `size` points, the unit of the entry's work counts. */
16
+ export declare const butterflies: (size: number) => number;
17
+ /**
18
+ * Forward transforms of two real frames `a` and `b` (length N) at once; writes bins 0..N/2 of each into
19
+ * (aRe, aIm) and (bRe, bIm), which hold at least N/2 + 1 values. `zr` and `zi` are N-point scratch.
20
+ */
21
+ export declare function realPair(plan: FftPlan, a: Float64Array, b: Float64Array, zr: Float64Array, zi: Float64Array, aRe: Float64Array, aIm: Float64Array, bRe: Float64Array, bIm: Float64Array): void;
22
+ /**
23
+ * Inverse transforms of two Hermitian spectra (bins 0..N/2 given) at once, scaled by 1/N: the real frames land in
24
+ * `a` and `b` (length N). `zr` and `zi` are N-point scratch.
25
+ */
26
+ export declare function inverseRealPair(plan: FftPlan, aRe: Float64Array, aIm: Float64Array, bRe: Float64Array, bIm: Float64Array, zr: Float64Array, zi: Float64Array, a: Float64Array, b: Float64Array): void;
@@ -0,0 +1,24 @@
1
+ /** Window names understood by `stft`: `'hann'` (default), `'hamming'`, `'blackman'`, `'blackman-harris'`, `'kaiser'` or `'rectangular'`. */
2
+ export type WindowName = 'hann' | 'hamming' | 'blackman' | 'blackman-harris' | 'kaiser' | 'rectangular';
3
+ /** Options for the window builders. */
4
+ export interface WindowOptions {
5
+ /** Symmetric (filter design) instead of periodic (spectral analysis) form. Default false. */
6
+ readonly symmetric?: boolean;
7
+ }
8
+ /** Window builders. Each returns a Float64Array of `size` coefficients. */
9
+ export declare const windows: {
10
+ /** Rectangular window, all ones. */
11
+ readonly rectangular: (size: number) => Float64Array;
12
+ /** Hann: 0.5 - 0.5 cos(2 pi n / N). */
13
+ readonly hann: (size: number, options?: WindowOptions) => Float64Array<ArrayBufferLike>;
14
+ /** Hamming: 0.54 - 0.46 cos(2 pi n / N). */
15
+ readonly hamming: (size: number, options?: WindowOptions) => Float64Array<ArrayBufferLike>;
16
+ /** Blackman, the three-term form with Harris's rounded coefficients 0.42, 0.5, 0.08. */
17
+ readonly blackman: (size: number, options?: WindowOptions) => Float64Array<ArrayBufferLike>;
18
+ /** The four-term minimum-sidelobe Blackman-Harris window (-92 dB sidelobes). */
19
+ readonly blackmanHarris: (size: number, options?: WindowOptions) => Float64Array<ArrayBufferLike>;
20
+ /** Kaiser-Bessel with shape `beta` (default 8.6, about -80 dB sidelobes): I0(beta sqrt(1 - r^2)) / I0(beta). */
21
+ readonly kaiser: (size: number, beta?: number, options?: WindowOptions) => Float64Array;
22
+ };
23
+ /** A window by name, or the coefficients themselves (which must hold `size` numbers). */
24
+ export declare function windowOf(window: WindowName | ArrayLike<number> | undefined, size: number): Float64Array;
@@ -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;