@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,54 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { AudioListener } from './listener.js';
3
+ /** First-order ACN/SN3D playback settings. */
4
+ export interface AmbisonicAudioOptions {
5
+ /** Channel convention. Default 'ambix': W,Y,Z,X in SN3D. Other conventions raise unsupported. */
6
+ format?: 'ambix';
7
+ /** Loop the complete buffer. Default true. */
8
+ loop?: boolean;
9
+ /** Linear output gain, 0..1. Default 1. */
10
+ volume?: number;
11
+ /** Matrix/gain smoothing time constant in seconds. Default listener.smoothing. */
12
+ smoothing?: number;
13
+ }
14
+ /**
15
+ * First-order AmbiX bed decoded to two virtual cardioids at +/-30 degrees.
16
+ * Follows listener orientation, supports full 3D field rotation, and ignores listener translation.
17
+ */
18
+ export declare class AmbisonicAudio {
19
+ /** Shared four-channel W,Y,Z,X buffer. No cloning or format inference. */
20
+ readonly buffer: AudioBuffer;
21
+ private readonly listener;
22
+ private readonly splitter;
23
+ private readonly merger;
24
+ private readonly output;
25
+ private readonly matrix;
26
+ private readonly values;
27
+ private readonly forward;
28
+ private readonly left;
29
+ private rotation;
30
+ private readonly smoothing;
31
+ private readonly loop;
32
+ private level;
33
+ private source;
34
+ private disposed;
35
+ constructor(listener: AudioListener, buffer: AudioBuffer, options?: AmbisonicAudioOptions);
36
+ /** True while a source is playing or scheduled. */
37
+ get isPlaying(): boolean;
38
+ /** Linear output gain 0..1, independent of field orientation. */
39
+ get volume(): number;
40
+ set volume(value: number);
41
+ /** Start at audio-clock time at (default now), from buffer phase zero. Already playing raises state. */
42
+ play(at?: number): this;
43
+ /** Stop and disconnect the current source, including a scheduled start. */
44
+ stop(): void;
45
+ /** World-space active field rotation as [x,y,z,w] quaternion. Normalized and copied; identity faces -Z. */
46
+ setRotation(value: readonly [number, number, number, number]): this;
47
+ /** Update from listener forward/up directions. Listener frame updates call this automatically, including XR poses. */
48
+ update(): void;
49
+ /** Release sources and decoder graph. Shared buffers remain usable. Idempotent; listener teardown also disposes. */
50
+ dispose(): void;
51
+ private validVolume;
52
+ private assertLive;
53
+ [Symbol.dispose]: () => void;
54
+ }
@@ -0,0 +1,118 @@
1
+ import { r as e, t } from "./errors-D8rc8kzg.js";
2
+ import { i as n } from "./math-C82bLsED.js";
3
+ //#region src/ambisonics.ts
4
+ var r = class {
5
+ constructor(n, r, i = {}) {
6
+ if (this.matrix = [], this.values = (/* @__PURE__ */ new Float64Array(8)).fill(NaN), this.forward = [
7
+ 0,
8
+ 0,
9
+ -1
10
+ ], this.left = [
11
+ -1,
12
+ 0,
13
+ 0
14
+ ], this.rotation = [
15
+ 0,
16
+ 0,
17
+ 0,
18
+ 1
19
+ ], this.source = null, this.disposed = !1, this.listener = n, (i.format ?? "ambix") !== "ambix" || r?.numberOfChannels !== 4) throw t("unsupported", "AmbisonicAudio needs four-channel first-order AmbiX ACN/SN3D; convert FuMa/HOA or choose the correct buffer");
20
+ if (!Number.isFinite(r.duration) || r.duration <= 0) throw t("state", "AmbisonicAudio needs a decoded positive-duration buffer; use listener.load(url, {signal})");
21
+ if (this.buffer = r, this.loop = i.loop ?? !0, typeof this.loop != "boolean") throw t("state", "Ambisonic loop needs a boolean; choose true or false");
22
+ if (this.level = this.validVolume(i.volume ?? 1), this.smoothing = i.smoothing ?? n.smoothing, !Number.isFinite(this.smoothing) || this.smoothing < 0) throw e("Ambisonic smoothing must be finite and nonnegative; use seconds or 0 for immediate changes", "state");
23
+ let a = n.context;
24
+ if (typeof a.createChannelSplitter != "function" || typeof a.createChannelMerger != "function") throw t("unsupported", "AmbisonicAudio needs Web Audio channel splitters/mergers; use a supporting AudioContext");
25
+ this.splitter = a.createChannelSplitter(4), this.merger = a.createChannelMerger(2), this.splitter.channelInterpretation = "discrete", this.output = a.createGain(), this.output.gain.value = this.level;
26
+ for (let e = 0; e < 2; e++) for (let t = 0; t < 4; t++) {
27
+ let n = a.createGain();
28
+ n.channelCount = 1, n.channelCountMode = "explicit", n.channelInterpretation = "discrete", this.splitter.connect(n, t), n.connect(this.merger, 0, e), this.matrix.push(n);
29
+ }
30
+ this.merger.connect(this.output).connect(n.input), n.addSource(this);
31
+ try {
32
+ this.update();
33
+ } catch (e) {
34
+ throw this.dispose(), e;
35
+ }
36
+ }
37
+ get isPlaying() {
38
+ return this.source !== null;
39
+ }
40
+ get volume() {
41
+ return this.level;
42
+ }
43
+ set volume(e) {
44
+ this.assertLive(), this.level = this.validVolume(e), n(this.output.gain, e, this.listener.context, this.smoothing);
45
+ }
46
+ play(n = this.listener.context.currentTime) {
47
+ if (this.assertLive(), !Number.isFinite(n) || n < this.listener.context.currentTime) throw e("Ambisonic start needs a finite time at or after now; use context.currentTime", "state");
48
+ if (this.source) throw t("state", "Ambisonic bed is already playing; stop before restarting");
49
+ let r = this.listener.context.createBufferSource();
50
+ return r.buffer = this.buffer, r.loop = this.loop, r.connect(this.splitter), r.onended = () => {
51
+ this.source === r && (r.disconnect(), this.source = null);
52
+ }, r.start(n), this.source = r, this;
53
+ }
54
+ stop() {
55
+ this.assertLive(), this.source &&= (this.source.onended = null, this.source.stop(), this.source.disconnect(), null);
56
+ }
57
+ setRotation(t) {
58
+ if (this.assertLive(), t.length !== 4 || [
59
+ 0,
60
+ 1,
61
+ 2,
62
+ 3
63
+ ].some((e) => !Number.isFinite(t[e]))) throw e("Ambisonic rotation needs four finite quaternion components; pass [x,y,z,w]", "state");
64
+ let n = Math.max(...t.map(Math.abs));
65
+ if (n === 0) throw e("Ambisonic rotation must be nonzero; use [0,0,0,1] for identity", "state");
66
+ let r = t.map((e) => e / n), i = Math.hypot(...r);
67
+ return this.rotation = r.map((e) => e / i), this.update(), this;
68
+ }
69
+ update() {
70
+ this.assertLive();
71
+ let e = this.listener.forward, t = this.listener.up, r = [
72
+ t[1] * e[2] - t[2] * e[1],
73
+ t[2] * e[0] - t[0] * e[2],
74
+ t[0] * e[1] - t[1] * e[0]
75
+ ], i = Math.hypot(...r), a = this.forward, o = this.left;
76
+ if (Number.isFinite(i) && i >= 1e-12) for (let t = 0; t < 3; t++) o[t] = r[t] / i, a[t] = e[t];
77
+ let [s, c, l, u] = this.rotation;
78
+ for (let e = 0; e < 2; e++) {
79
+ let t = e === 0 ? 1 : -1, r = [
80
+ 0,
81
+ 1,
82
+ 2
83
+ ].map((e) => a[e] * Math.sqrt(3) / 2 + t * o[e] / 2), i = 2 * (-c * r[2] + l * r[1]), d = 2 * (-l * r[0] + s * r[2]), f = 2 * (-s * r[1] + c * r[0]), p = [
84
+ r[0] + u * i - c * f + l * d,
85
+ r[1] + u * d - l * i + s * f,
86
+ r[2] + u * f - s * d + c * i
87
+ ];
88
+ [
89
+ .5,
90
+ -p[0] / 2,
91
+ p[1] / 2,
92
+ -p[2] / 2
93
+ ].forEach((t, r) => {
94
+ let i = e * 4 + r;
95
+ t !== this.values[i] && n(this.matrix[i].gain, t, this.listener.context, this.smoothing, Number.isNaN(this.values[i])), this.values[i] = t;
96
+ });
97
+ }
98
+ }
99
+ dispose() {
100
+ if (!this.disposed) {
101
+ this.stop(), this.disposed = !0, this.listener.removeSource(this), this.splitter.disconnect();
102
+ for (let e of this.matrix) e.disconnect();
103
+ this.merger.disconnect(), this.output.disconnect();
104
+ }
105
+ }
106
+ validVolume(t) {
107
+ if (!Number.isFinite(t) || t < 0 || t > 1) throw e("Ambisonic volume needs a finite value in 0..1; choose a linear output gain", "state");
108
+ return t;
109
+ }
110
+ assertLive() {
111
+ if (this.disposed) throw t("disposed", "AmbisonicAudio is disposed; create a new bed");
112
+ }
113
+ [Symbol.dispose ?? Symbol()]() {
114
+ this.dispose();
115
+ }
116
+ };
117
+ //#endregion
118
+ export { r as AmbisonicAudio };
@@ -0,0 +1,45 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { Audio } from './audio.js';
3
+ /**
4
+ * Options for {@link AudioAnalyser}.
5
+ * @example
6
+ * new AudioAnalyser(music, {fftSize: 1024, smoothingTimeConstant: 0.6});
7
+ */
8
+ export interface AudioAnalyserOptions {
9
+ /** FFT size, a power of two from 32 to 32768. Default 2048. */
10
+ fftSize?: number;
11
+ /** Averaging between successive frames, 0..1. Default 0.8 (the Web Audio default). */
12
+ smoothingTimeConstant?: number;
13
+ /** Lowest decibel value mapped to 0 in byte data. Default -100 (the Web Audio default). */
14
+ minDecibels?: number;
15
+ /** Highest decibel value mapped to 255 in byte data. Default -30 (the Web Audio default). */
16
+ maxDecibels?: number;
17
+ }
18
+ /**
19
+ * Taps the output of a sound (after its volume stage and panner) with an AnalyserNode.
20
+ * The tap is a side branch and does not change what reaches the speakers.
21
+ */
22
+ export declare class AudioAnalyser {
23
+ readonly analyser: AnalyserNode;
24
+ /** Byte frequency bins from the last getFrequencyData call. */
25
+ readonly data: Uint8Array<ArrayBuffer>;
26
+ private readonly input;
27
+ private readonly waveform;
28
+ private readonly spectrum;
29
+ private disposed;
30
+ constructor(source: Audio | AudioNode, options?: AudioAnalyserOptions | number);
31
+ /** Byte magnitudes per frequency bin (0..255), written into `data`. */
32
+ getFrequencyData(): Uint8Array<ArrayBuffer>;
33
+ /** Decibel magnitudes per frequency bin. */
34
+ getFloatFrequencyData(out?: Float32Array<ArrayBuffer>): Float32Array<ArrayBuffer>;
35
+ /** Byte waveform samples (128 is silence). */
36
+ getWaveformData(): Uint8Array<ArrayBuffer>;
37
+ /** Float waveform samples in -1..1. */
38
+ getFloatWaveformData(out?: Float32Array<ArrayBuffer>): Float32Array<ArrayBuffer>;
39
+ /** Mean of the byte frequency bins, 0..255. */
40
+ getAverageFrequency(): number;
41
+ /** Peak frequency in Hz, from the decibel spectrum (byte data saturates at maxDecibels). */
42
+ getDominantFrequency(): number;
43
+ dispose(): void;
44
+ [Symbol.dispose]: () => void;
45
+ }
@@ -0,0 +1,282 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel, Mesh } from '@margoengine/core';
3
+ import type { AudioListener, ListenerSource } from './listener.js';
4
+ import { type DistanceModel, type Vec3 } from './math.js';
5
+ /**
6
+ * Options for {@link Audio}. Every field is optional; a sound with no options plays its buffer once at full volume.
7
+ * @example
8
+ * new Audio(listener, {volume: 0.5, loop: true});
9
+ */
10
+ export interface AudioOptions {
11
+ /** Volume of this sound, default 1. */
12
+ volume?: number;
13
+ /** Restart from the loop start when the end is reached. Default false. */
14
+ loop?: boolean;
15
+ /** Loop region start in seconds (buffer sources). */
16
+ loopStart?: number;
17
+ /** Loop region end in seconds; 0 means the end of the buffer. */
18
+ loopEnd?: number;
19
+ /** Speed multiplier; 2 plays an octave higher and twice as fast. Default 1. */
20
+ playbackRate?: number;
21
+ /** Detune in cents (buffer sources). */
22
+ detune?: number;
23
+ /** Start position in seconds within the buffer. */
24
+ offset?: number;
25
+ /** Seconds to play (buffer sources, ignored while looping). */
26
+ duration?: number;
27
+ /** Timeline second where {@link Audio.sync} starts this sound, default 0. */
28
+ timelineStart?: number;
29
+ /** Start as soon as a buffer is set. */
30
+ autoplay?: boolean;
31
+ /** Effect chain between the source and the volume stage, e.g. BiquadFilterNodes. */
32
+ filters?: AudioNode[];
33
+ /** Called when playback reaches its natural end (not on pause or stop). */
34
+ onEnded?: (audio: Audio) => void;
35
+ }
36
+ /**
37
+ * Options for {@link PositionalAudio}: everything in {@link AudioOptions} plus the panner. The distance fields follow
38
+ * the Web Audio PannerNode defaults.
39
+ * @example
40
+ * new PositionalAudio(listener, {mesh: truck, refDistance: 2, distanceModel: 'inverse'});
41
+ */
42
+ export interface PositionalAudioOptions extends AudioOptions {
43
+ /** Spatialisation algorithm. Default 'equalpower'. */
44
+ panningModel?: PanningModelType;
45
+ /** How volume falls with distance. Default 'inverse'. */
46
+ distanceModel?: DistanceModel;
47
+ /** Distance in metres at which attenuation starts. Default 1. */
48
+ refDistance?: number;
49
+ /** Distance beyond which attenuation stops (the 'linear' model reaches silence here). Default 10000. */
50
+ maxDistance?: number;
51
+ /** How fast the volume falls with distance. Default 1. */
52
+ rolloffFactor?: number;
53
+ /** Cone angles in degrees (360 disables the cone). */
54
+ coneInnerAngle?: number;
55
+ coneOuterAngle?: number;
56
+ coneOuterGain?: number;
57
+ /** Mesh to follow. Position comes from its world matrix; orientation from its local `direction` axis. */
58
+ mesh?: Mesh | null;
59
+ /** Local axis the cone points along, default +Z. */
60
+ direction?: Vec3;
61
+ /** Silence the sound (smoothly) while the mesh or any ancestor is hidden. Default false. */
62
+ muteWhenHidden?: boolean;
63
+ }
64
+ type SourceKind = 'buffer' | 'media' | 'stream' | 'node' | null;
65
+ /**
66
+ * A non-positional sound routed straight to the listener's master gain.
67
+ * Graph: source -> filters -> fade gain -> volume gain -> [panner] -> listener.input.
68
+ */
69
+ export declare class Audio implements ListenerSource {
70
+ /**
71
+ * Seconds {@link Audio.sync} lets a playing sound drift from the timeline before it re-seeks, default 0.05:
72
+ * above audio-clock and frame jitter, below what reads as out of sync. Raise it if steady playback stutters.
73
+ */
74
+ static syncTolerance: number;
75
+ readonly listener: AudioListener;
76
+ readonly context: BaseAudioContext;
77
+ /** Volume stage (user volume times hidden-mute). */
78
+ readonly gain: GainNode;
79
+ /** Fade stage driven by fadeIn and fadeOut. */
80
+ readonly fade: GainNode;
81
+ onEnded: ((audio: Audio) => void) | null;
82
+ autoplay: boolean;
83
+ buffer: AudioBuffer | null;
84
+ /** Current source node, if any (AudioBufferSourceNode while a buffer plays). */
85
+ source: AudioNode | null;
86
+ private kind;
87
+ private media;
88
+ private playing;
89
+ private endedNaturally;
90
+ /** Context time the current buffer node started, or will start for a delayed play. */
91
+ private startedAt;
92
+ /** Buffer seconds played past `offset` over earlier stretches, kept wrapped into the buffer or loop region. */
93
+ private progress;
94
+ private filterList;
95
+ private loopValue;
96
+ private loopStartValue;
97
+ private loopEndValue;
98
+ private rateValue;
99
+ private detuneValue;
100
+ private offsetValue;
101
+ private durationValue;
102
+ private timelineStartValue;
103
+ private volumeValue;
104
+ private muted;
105
+ private disposed;
106
+ private fadeTimer;
107
+ private fading;
108
+ private readonly onMediaEnded;
109
+ constructor(listener: AudioListener, options?: AudioOptions);
110
+ /** Last node of this sound before the listener (the volume gain, or the panner for positional audio). */
111
+ getOutput(): AudioNode;
112
+ protected connectOutput(): void;
113
+ get isPlaying(): boolean;
114
+ /** True after dispose; controllers use this without inferring lifecycle from the source kind. */
115
+ get isDisposed(): boolean;
116
+ get sourceType(): SourceKind;
117
+ /** Plays an AudioBuffer (decoded file). */
118
+ setBuffer(buffer: AudioBuffer): this;
119
+ /** Routes an `<audio>` or `<video>` element. One element can feed only one context node, which is reused. */
120
+ setMediaElementSource(element: HTMLMediaElement): this;
121
+ /** Routes a MediaStream (microphone, WebRTC). play() connects it, pause() and stop() disconnect it. */
122
+ setMediaStreamSource(stream: MediaStream): this;
123
+ /** Routes any AudioNode (oscillator, constant source, worklet). play() connects it, pause() and stop() disconnect it. */
124
+ setNodeSource(node: AudioNode): this;
125
+ /** Starts or resumes playback after `delay` seconds. */
126
+ play(delay?: number): this;
127
+ /** Pauses and remembers the position (buffer sources) so play() continues from there. */
128
+ pause(): this;
129
+ /** Stops after `delay` seconds and rewinds to `offset`. */
130
+ stop(delay?: number): this;
131
+ /**
132
+ * Moves the playhead to `seconds` within the buffer (or the media element's time), whether playing, paused or
133
+ * stopped. A playing buffer restarts on one new source node at the new position; the old node is stopped and
134
+ * disconnected first, so the two never overlap. Looping wraps the position into the loop region. Without looping
135
+ * it clamps to the end of the buffer, where a playing sound ends as if it had played through (`onEnded` fires).
136
+ * Stream and node sources cannot seek and ignore it.
137
+ */
138
+ seek(seconds: number): this;
139
+ /**
140
+ * Follows an external timeline clock, such as an editor's animation timeline; call it every frame. The sound is
141
+ * silent before timeline second `timelineStart`; after it the buffer position is
142
+ * `offset + timelineSeconds - timelineStart`, wrapped by the loop region, and a non-looping sound is silent past
143
+ * its end. While `playing` it plays and re-seeks only when it drifts more than {@link Audio.syncTolerance} from
144
+ * the timeline, so steady playback is never chopped. With `playing` false (a paused timeline, scrubbing) it only
145
+ * moves the playhead and stays silent. `rate` is the timeline speed and sets `playbackRate`; zero or negative
146
+ * (reverse) is silent, as Web Audio cannot play a buffer backwards. Buffer sources only; before setBuffer it does
147
+ * nothing.
148
+ */
149
+ sync(timelineSeconds: number, playing: boolean, rate?: number): this;
150
+ /** Ramps from silence to full volume over `seconds`, starting playback if needed. */
151
+ fadeIn(seconds: number): this;
152
+ /** Ramps to silence over `seconds`, then stops (or pauses with `{pause: true}`). */
153
+ fadeOut(seconds: number, { pause }?: {
154
+ pause?: boolean;
155
+ }): this;
156
+ /** Replaces the effect chain. Nodes are wired in order between the source and the volume stage. */
157
+ setFilters(filters: AudioNode[]): this;
158
+ getFilters(): AudioNode[];
159
+ setFilter(filter: AudioNode | null): this;
160
+ getFilter(): AudioNode | null;
161
+ get volume(): number;
162
+ set volume(value: number);
163
+ get loop(): boolean;
164
+ set loop(value: boolean);
165
+ get loopStart(): number;
166
+ set loopStart(value: number);
167
+ get loopEnd(): number;
168
+ set loopEnd(value: number);
169
+ /**
170
+ * The loopEnd a buffer node gets. AudioBufferSourceNode loops the whole buffer whenever its loopEnd is 0, whatever
171
+ * loopStart says (Web Audio API, "Playback of AudioBuffer Contents"), so loopEnd 0, which here means the end of the
172
+ * buffer, is passed as the buffer's duration: loopStart 2 with loopEnd 0 loops from 2 s to the end, as the playhead
173
+ * counts it.
174
+ */
175
+ private get nodeLoopEnd();
176
+ get playbackRate(): number;
177
+ set playbackRate(value: number);
178
+ get detune(): number;
179
+ /** Detune in cents. It changes speed as well as pitch: a buffer plays at playbackRate * 2^(detune/1200). */
180
+ set detune(value: number);
181
+ /**
182
+ * Buffer seconds per context second: AudioBufferSourceNode's computed playback rate, playbackRate times
183
+ * 2^(detune/1200). Detune speeds the buffer up like playbackRate does, so the playhead counts it too.
184
+ */
185
+ private get speed();
186
+ /**
187
+ * Keeps the position continuous across a speed change: counts the time so far at the old speed, then restarts the
188
+ * clock (a delayed start keeps its future start time).
189
+ */
190
+ private foldProgress;
191
+ get offset(): number;
192
+ set offset(value: number);
193
+ get duration(): number | undefined;
194
+ set duration(value: number | undefined);
195
+ /** Timeline second where {@link Audio.sync} starts this sound. */
196
+ get timelineStart(): number;
197
+ set timelineStart(value: number);
198
+ /** Current playhead in seconds within the buffer (buffer sources) or media element time. */
199
+ get currentTime(): number;
200
+ /** @internal Per-frame hook from the listener; global audio has nothing to update. */
201
+ update(_engine: EngineKernel | null): void;
202
+ /** Stops playback, disconnects every node and unregisters from the listener. */
203
+ dispose(): void;
204
+ [Symbol.dispose]: () => void;
205
+ protected get head(): AudioNode;
206
+ protected setMuted(muted: boolean): void;
207
+ get isMuted(): boolean;
208
+ private get isSourceConnected();
209
+ private writeGain;
210
+ private setFade;
211
+ private assertLive;
212
+ private clearTimer;
213
+ /**
214
+ * Buffer position in seconds for `progress` seconds past `offset`. Without looping it clamps to the buffer. With
215
+ * looping it follows AudioBufferSourceNode's rules: the region is [loopStart, loopEnd), loopEnd 0 meaning the buffer
216
+ * end and capped at it; positions at or past the region end wrap into it, earlier ones (an intro) are kept; an empty
217
+ * or inverted region loops the whole buffer.
218
+ */
219
+ private playhead;
220
+ /**
221
+ * Replaces the live buffer node with a new one that starts at context time `when` from the wrapped playhead.
222
+ * Buffer source nodes are one-shot, so every play, resume and playing seek needs a fresh node. A sound with nothing
223
+ * left to play (at the end of the buffer, or of `duration`) plays one silent frame instead: WebKit never fires
224
+ * `ended` on a node started with nothing to play, and this way the end arrives through the same `onended` everywhere.
225
+ */
226
+ private startBuffer;
227
+ /** The `onended` of a buffer node: a natural end only when it is still the live node of a playing sound. */
228
+ private nodeEnded;
229
+ /**
230
+ * Stops the live buffer node. With `delay` > 0 it is scheduled to stop then and stays live until it ends or a
231
+ * later play replaces it; otherwise it stops now, is disconnected and released without firing `onEnded`.
232
+ */
233
+ private stopNode;
234
+ private haltOther;
235
+ private replaceSource;
236
+ }
237
+ /**
238
+ * A sound placed in the world through a PannerNode. Attach it to a core Mesh
239
+ * and the listener reads the mesh world matrix from the engine every frame, or place it with setPosition.
240
+ */
241
+ export declare class PositionalAudio extends Audio {
242
+ readonly panner: PannerNode;
243
+ /** Last world position and cone direction written to the panner. */
244
+ readonly worldPosition: Float64Array<ArrayBuffer>;
245
+ readonly worldDirection: Float64Array<ArrayBuffer>;
246
+ muteWhenHidden: boolean;
247
+ private meshValue;
248
+ private readonly localDirection;
249
+ private readonly directionScratch;
250
+ private written;
251
+ constructor(listener: AudioListener, options?: PositionalAudioOptions);
252
+ getOutput(): AudioNode;
253
+ /** The panner does not exist yet while the base constructor runs; the subclass wires gain -> panner -> input. */
254
+ protected connectOutput(): void;
255
+ get panningModel(): PanningModelType;
256
+ set panningModel(value: PanningModelType);
257
+ get distanceModel(): DistanceModel;
258
+ set distanceModel(value: DistanceModel);
259
+ get refDistance(): number;
260
+ set refDistance(value: number);
261
+ get maxDistance(): number;
262
+ set maxDistance(value: number);
263
+ get rolloffFactor(): number;
264
+ set rolloffFactor(value: number);
265
+ /** Cone angles in degrees and the gain outside the outer cone (0..1). */
266
+ setDirectionalCone(innerAngle: number, outerAngle: number, outerGain: number): this;
267
+ /** The mesh this sound follows. */
268
+ get mesh(): Mesh | null;
269
+ /** Follows `mesh` (world position from the engine's matrices). Pass null to keep the last pose. */
270
+ attach(mesh: Mesh | null): this;
271
+ detach(): this;
272
+ /** Places the sound at a world position and stops following any mesh. */
273
+ setPosition(x: number, y: number, z: number): this;
274
+ /** World direction of the cone when not following a mesh; the local axis when following one. */
275
+ setDirection(direction: Vec3): this;
276
+ /** @internal Reads the attached mesh's world matrix and visibility. Called by the listener every frame. */
277
+ update(engine: EngineKernel | null): void;
278
+ dispose(): void;
279
+ [Symbol.dispose]: () => void;
280
+ private writePose;
281
+ }
282
+ export {};
@@ -0,0 +1,35 @@
1
+ import { Audio, type AudioListener, type AudioOptions } from '@margoengine/audio';
2
+ /** Options for a full-sphere ACN/SN3D AmbiX bed. */
3
+ export interface BinauralAudioOptions extends AudioOptions {
4
+ /** Only AmbiX ACN/SN3D is accepted. Default 'ambix'. */
5
+ format?: 'ambix';
6
+ }
7
+ /** Real ACN/SN3D harmonics, orders 0..3, for a unit direction [front, left, up]. */
8
+ export declare function ambixBasis(order: number, direction: readonly [number, number, number]): Float64Array;
9
+ /**
10
+ * First/second/third-order AmbiX decoded over a 32-direction Gauss-Legendre sphere
11
+ * through native Web Audio HRTFs. Inherits buffer transport, seeks, fades and filters.
12
+ */
13
+ export declare class BinauralAudio extends Audio {
14
+ /** Ambisonic order inferred from the complete channel set: 1, 2 or 3. */
15
+ readonly order: number;
16
+ /** Number of native HRTF virtual loudspeakers, always 32. */
17
+ readonly speakerCount = 32;
18
+ private readonly splitter;
19
+ private readonly output;
20
+ private readonly matrix;
21
+ private readonly speakers;
22
+ private rotation;
23
+ private written;
24
+ constructor(listener: AudioListener, buffer: AudioBuffer, options?: BinauralAudioOptions);
25
+ /** Replace with the same AmbiX order. Validate before interrupting a playing bed. */
26
+ setBuffer(buffer: AudioBuffer): this;
27
+ /** Last stereo node, for analysers or wet sends. */
28
+ getOutput(): AudioNode;
29
+ /** Active field rotation in engine world coordinates, normalized [x,y,z,w]. */
30
+ setRotation(value: readonly [number, number, number, number]): this;
31
+ /** Translate the distant speaker sphere with the listener; native HRTFs follow listener orientation. */
32
+ update(): void;
33
+ /** Disconnect the entire HRTF graph and source. Idempotent; listener teardown also disposes. */
34
+ dispose(): void;
35
+ }
@@ -0,0 +1,123 @@
1
+ import { r as e, t } from "./errors-D8rc8kzg.js";
2
+ import { i as n } from "./math-C82bLsED.js";
3
+ import { Audio as r } from "@margoengine/audio";
4
+ //#region src/binaural.ts
5
+ var i = (e) => {
6
+ let n = Math.sqrt(e?.numberOfChannels) - 1;
7
+ if (![
8
+ 1,
9
+ 2,
10
+ 3
11
+ ].includes(n) || !Number.isFinite(e.duration) || e.duration <= 0) throw t("unsupported", "BinauralAudio needs a positive-duration 4, 9 or 16 channel AmbiX buffer; convert the recording to ACN/SN3D first");
12
+ return n;
13
+ };
14
+ function a(t, n) {
15
+ if (!Number.isInteger(t) || t < 0 || t > 3 || n.length !== 3 || n.some((e) => !Number.isFinite(e)) || Math.abs(Math.hypot(...n) - 1) > 1e-10) throw e("AmbiX basis needs order 0..3 and a unit [front,left,up] vector; normalize the direction first", "state");
16
+ let r = n[2], i = Math.atan2(n[1], n[0]), a = new Float64Array((t + 1) ** 2), o = (e) => {
17
+ let t = 1;
18
+ for (let n = 2; n <= e; n++) t *= n;
19
+ return t;
20
+ }, s = 1;
21
+ for (let e = 0; e <= t; e++) {
22
+ e > 0 && (s *= (2 * e - 1) * Math.sqrt(Math.max(0, 1 - r * r)));
23
+ let n = 0, c = s;
24
+ for (let s = e; s <= t; s++) {
25
+ if (s > e) {
26
+ let t = ((2 * s - 1) * r * c - (s + e - 1) * n) / (s - e);
27
+ n = c, c = t;
28
+ }
29
+ let t = Math.sqrt((e === 0 ? 1 : 2) * o(s - e) / o(s + e));
30
+ a[s * s + s + e] = t * c * Math.cos(e * i), e > 0 && (a[s * s + s - e] = t * c * Math.sin(e * i));
31
+ }
32
+ }
33
+ return a;
34
+ }
35
+ var o = class extends r {
36
+ constructor(e, n, r = {}) {
37
+ let o = i(n);
38
+ if ((r.format ?? "ambix") !== "ambix") throw t("unsupported", "BinauralAudio accepts AmbiX only; convert the recording to ACN/SN3D");
39
+ super(e, {
40
+ ...r,
41
+ loop: r.loop ?? !0
42
+ }), this.speakerCount = 32, this.matrix = [], this.speakers = [], this.rotation = [
43
+ 0,
44
+ 0,
45
+ 0,
46
+ 1
47
+ ], this.written = !1, this.order = o;
48
+ let s = e.context;
49
+ this.splitter = s.createChannelSplitter(n.numberOfChannels), this.splitter.channelInterpretation = "discrete", this.output = s.createGain(), this.output.connect(e.input), this.gain.disconnect(e.input), this.gain.channelCount = n.numberOfChannels, this.gain.channelCountMode = "explicit", this.gain.channelInterpretation = "discrete", this.gain.connect(this.splitter);
50
+ for (let e of [-1, 1]) for (let t of [-1, 1]) {
51
+ let n = e * Math.sqrt((3 + t * 2 * Math.sqrt(6 / 5)) / 7), r = (18 - t * Math.sqrt(30)) / 36 / 16;
52
+ for (let e = 0; e < 8; e++) {
53
+ let t = e * Math.PI / 4, i = Math.sqrt(1 - n * n), c = [
54
+ i * Math.cos(t),
55
+ i * Math.sin(t),
56
+ n
57
+ ], l = s.createPanner();
58
+ l.panningModel = "HRTF", l.rolloffFactor = 0, l.channelCount = 1, l.channelCountMode = "explicit", l.connect(this.output), this.speakers.push({
59
+ node: l,
60
+ direction: c
61
+ });
62
+ let u = a(o, c);
63
+ for (let e = 0; e < u.length; e++) {
64
+ let t = s.createGain();
65
+ t.gain.value = r * (2 * Math.floor(Math.sqrt(e)) + 1) * u[e], t.channelCount = 1, t.channelCountMode = "explicit", t.channelInterpretation = "discrete", this.splitter.connect(t, e), t.connect(l), this.matrix.push(t);
66
+ }
67
+ }
68
+ }
69
+ this.update(), this.setBuffer(n);
70
+ }
71
+ setBuffer(e) {
72
+ if (i(e) !== this.order) throw t("unsupported", "Replacement AmbiX order differs; create another BinauralAudio for that order");
73
+ return super.setBuffer(e);
74
+ }
75
+ getOutput() {
76
+ return this.output ?? this.gain;
77
+ }
78
+ setRotation(n) {
79
+ if (this.isDisposed) throw t("disposed", "BinauralAudio is disposed; create a new bed");
80
+ if (n.length !== 4 || [
81
+ 0,
82
+ 1,
83
+ 2,
84
+ 3
85
+ ].some((e) => !Number.isFinite(n[e]))) throw e("Field rotation needs four finite components; use [0,0,0,1] for identity", "state");
86
+ let r = Math.max(...n.map(Math.abs));
87
+ if (!r) throw e("Field rotation must be nonzero; use [0,0,0,1] for identity", "state");
88
+ let i = n.map((e) => e / r), a = Math.hypot(...i);
89
+ return this.rotation = i.map((e) => e / a), this.update(), this;
90
+ }
91
+ update() {
92
+ if (this.isDisposed) return;
93
+ let [e, t, r, i] = this.rotation, a = this.listener.position;
94
+ for (let { node: o, direction: [s, c, l] } of this.speakers) {
95
+ let u = [
96
+ -c,
97
+ l,
98
+ -s
99
+ ], d = 2 * (t * u[2] - r * u[1]), f = 2 * (r * u[0] - e * u[2]), p = 2 * (e * u[1] - t * u[0]), m = [
100
+ u[0] + i * d + t * p - r * f,
101
+ u[1] + i * f + r * d - e * p,
102
+ u[2] + i * p + e * f - t * d
103
+ ];
104
+ [
105
+ o.positionX,
106
+ o.positionY,
107
+ o.positionZ
108
+ ].forEach((e, t) => {
109
+ let r = a[t] + m[t];
110
+ e.value !== r && n(e, r, this.context, this.listener.smoothing, !this.written);
111
+ });
112
+ }
113
+ this.written = !0;
114
+ }
115
+ dispose() {
116
+ super.dispose(), this.splitter?.disconnect();
117
+ for (let e of this.matrix) e.disconnect();
118
+ for (let { node: e } of this.speakers) e.disconnect();
119
+ this.output?.disconnect();
120
+ }
121
+ };
122
+ //#endregion
123
+ export { o as BinauralAudio, a as ambixBasis };