cacophony 0.38.0 → 0.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -1
- package/README.md +7 -3
- package/dist/basePlayback.cjs +1 -1
- package/dist/basePlayback.cjs.map +1 -1
- package/dist/basePlayback.d.ts +9 -0
- package/dist/basePlayback.mjs +7 -1
- package/dist/basePlayback.mjs.map +1 -1
- package/dist/playback.cjs +1 -1
- package/dist/playback.cjs.map +1 -1
- package/dist/playback.d.ts +26 -4
- package/dist/playback.mjs +20 -10
- package/dist/playback.mjs.map +1 -1
- package/dist/reflections.cjs.map +1 -1
- package/dist/reflections.d.ts +3 -2
- package/dist/reflections.mjs.map +1 -1
- package/dist/routableSource.cjs +1 -1
- package/dist/routableSource.cjs.map +1 -1
- package/dist/routableSource.d.ts +2 -0
- package/dist/routableSource.mjs +3 -3
- package/dist/routableSource.mjs.map +1 -1
- package/dist/sound.cjs +1 -1
- package/dist/sound.cjs.map +1 -1
- package/dist/sound.mjs +3 -5
- package/dist/sound.mjs.map +1 -1
- package/docs/assets/hierarchy.js +1 -1
- package/docs/assets/search.js +1 -1
- package/docs/classes/AudioCache.html +4 -4
- package/docs/classes/AudioSprite.html +7 -7
- package/docs/classes/BarberpoleEffect.html +6 -6
- package/docs/classes/BiquadEffect.html +3 -3
- package/docs/classes/Bus.html +21 -21
- package/docs/classes/Cacophony.html +92 -92
- package/docs/classes/DynamicsEffect.html +6 -6
- package/docs/classes/FdnReverbEffect.html +6 -6
- package/docs/classes/FoaDecoder.html +5 -5
- package/docs/classes/FoaDecoderEffect.html +3 -3
- package/docs/classes/FrequencyShifterEffect.html +6 -6
- package/docs/classes/Group.html +33 -33
- package/docs/classes/HarmonizerEffect.html +6 -6
- package/docs/classes/ImpulseResponseEffect.html +3 -3
- package/docs/classes/KWeightingFilter.html +4 -4
- package/docs/classes/LoudnessMeter.html +11 -11
- package/docs/classes/MediaStreamPlayback.html +102 -72
- package/docs/classes/MediaStreamSound.html +55 -53
- package/docs/classes/MicrophoneStream.html +56 -54
- package/docs/classes/ModulatedDelayEffect.html +6 -6
- package/docs/classes/PcmStreamPlayback.html +103 -73
- package/docs/classes/PcmStreamSound.html +65 -63
- package/docs/classes/PhaserEffect.html +6 -6
- package/docs/classes/Playback.html +136 -101
- package/docs/classes/ReverbEffect.html +6 -6
- package/docs/classes/Scheduler.html +3 -3
- package/docs/classes/ShareEffect.html +3 -3
- package/docs/classes/Sound.html +76 -74
- package/docs/classes/SpectralFreezeEffect.html +6 -6
- package/docs/classes/StereoWidenerEffect.html +3 -3
- package/docs/classes/Synth.html +66 -64
- package/docs/classes/SynthGroup.html +28 -28
- package/docs/classes/TremoloEffect.html +6 -6
- package/docs/classes/TruePeakDetector.html +8 -8
- package/docs/classes/WaveshaperEffect.html +6 -6
- package/docs/functions/encodeMonoToFoaSN3D.html +1 -1
- package/docs/functions/integratedLoudness.html +1 -1
- package/docs/functions/integratedUngatedLoudness.html +1 -1
- package/docs/functions/loudnessRange.html +1 -1
- package/docs/functions/timeStretch.html +1 -1
- package/docs/functions/timeStretchChannels.html +1 -1
- package/docs/functions/truePeakDb.html +1 -1
- package/docs/hierarchy.html +7 -7
- package/docs/index.html +7 -3
- package/docs/interfaces/AudioBuffer.html +8 -8
- package/docs/interfaces/AudioBufferSourceNode.html +21 -21
- package/docs/interfaces/AudioEventCallbacks.html +1 -1
- package/docs/interfaces/AudioListener.html +12 -12
- package/docs/interfaces/AudioNode.html +13 -13
- package/docs/interfaces/AudioParam.html +7 -7
- package/docs/interfaces/AudioWorklet.html +2 -2
- package/docs/interfaces/AudioWorkletNode.html +15 -15
- package/docs/interfaces/BarberpoleOptions.html +5 -5
- package/docs/interfaces/BaseContext.html +26 -26
- package/docs/interfaces/BaseSound.html +16 -16
- package/docs/interfaces/BiquadCoefficients.html +6 -6
- package/docs/interfaces/BiquadFilterNode.html +19 -19
- package/docs/interfaces/BuiltEffectGraph.html +6 -6
- package/docs/interfaces/CacheErrorEvent.html +5 -5
- package/docs/interfaces/CacheHitEvent.html +4 -4
- package/docs/interfaces/CacheMissEvent.html +4 -4
- package/docs/interfaces/CacophonyEffect.html +2 -2
- package/docs/interfaces/CacophonyLogger.html +4 -4
- package/docs/interfaces/ChannelMergerNode.html +13 -13
- package/docs/interfaces/ChannelSplitterNode.html +13 -13
- package/docs/interfaces/ConvolverNode.html +15 -15
- package/docs/interfaces/CreateSpriteOptions.html +3 -3
- package/docs/interfaces/DelayNode.html +14 -14
- package/docs/interfaces/DeviceChangeEvent.html +3 -3
- package/docs/interfaces/DynamicsOptions.html +7 -7
- package/docs/interfaces/FadeStartEvent.html +4 -4
- package/docs/interfaces/FdnReverbOptions.html +5 -5
- package/docs/interfaces/FoaDecoderOptions.html +2 -2
- package/docs/interfaces/FrequencyShifterOptions.html +3 -3
- package/docs/interfaces/GainNode.html +14 -14
- package/docs/interfaces/GlobalPlaybackEvent.html +3 -3
- package/docs/interfaces/HarmonizerOptions.html +6 -6
- package/docs/interfaces/ImpulseResponseOptions.html +5 -5
- package/docs/interfaces/LoadingCompleteEvent.html +5 -5
- package/docs/interfaces/LoadingErrorEvent.html +5 -5
- package/docs/interfaces/LoadingProgressEvent.html +6 -6
- package/docs/interfaces/LoadingStartEvent.html +3 -3
- package/docs/interfaces/LoudnessChannelInput.html +3 -3
- package/docs/interfaces/LoudnessReading.html +5 -5
- package/docs/interfaces/MediaElementSourceNode.html +14 -14
- package/docs/interfaces/MediaStreamAudioSourceNode.html +14 -14
- package/docs/interfaces/MediaStreamSoundOptions.html +4 -4
- package/docs/interfaces/MicrophoneStreamOptions.html +8 -8
- package/docs/interfaces/ModulatedDelayOptions.html +8 -8
- package/docs/interfaces/OfflineOptions.html +5 -5
- package/docs/interfaces/OscillatorNode.html +19 -19
- package/docs/interfaces/PannerNode.html +27 -27
- package/docs/interfaces/PcmStreamBufferEvent.html +2 -2
- package/docs/interfaces/PcmStreamSoundOptions.html +6 -6
- package/docs/interfaces/PhaserOptions.html +7 -7
- package/docs/interfaces/PlayOptions.html +13 -13
- package/docs/interfaces/PlaybackErrorEvent.html +5 -5
- package/docs/interfaces/PrepareSeekOptions.html +3 -3
- package/docs/interfaces/ReflectionImage.html +5 -5
- package/docs/interfaces/ReverbOptions.html +13 -13
- package/docs/interfaces/RuntimeOptions.html +8 -8
- package/docs/interfaces/ScheduledCallbackHandle.html +2 -2
- package/docs/interfaces/SendGainOptions.html +3 -3
- package/docs/interfaces/SoundCleanupHoldings.html +4 -4
- package/docs/interfaces/SoundErrorEvent.html +6 -6
- package/docs/interfaces/SpectralFreezeOptions.html +4 -4
- package/docs/interfaces/SpriteRegion.html +4 -4
- package/docs/interfaces/StereoPannerNode.html +14 -14
- package/docs/interfaces/StereoToBFormatOptions.html +2 -2
- package/docs/interfaces/StereoWidenerOptions.html +4 -4
- package/docs/interfaces/StreamCapabilities.html +5 -5
- package/docs/interfaces/TimeStretchOptions.html +5 -5
- package/docs/interfaces/TremoloOptions.html +5 -5
- package/docs/interfaces/WaveshaperOptions.html +5 -5
- package/docs/types/AudioSinkId.html +1 -1
- package/docs/types/BaseAudioEvents.html +11 -11
- package/docs/types/BuiltEffect.html +1 -1
- package/docs/types/BusConnectionTarget.html +1 -1
- package/docs/types/CacheEventCallback.html +1 -1
- package/docs/types/CacophonyEvents.html +20 -20
- package/docs/types/ErrorEventCallback.html +1 -1
- package/docs/types/FadeType.html +1 -1
- package/docs/types/HrtfPannerOptions.html +1 -1
- package/docs/types/ImpulseResponseSource.html +1 -1
- package/docs/types/LoadingEventCallback.html +1 -1
- package/docs/types/LoopCount.html +1 -1
- package/docs/types/LoudnessChannel.html +1 -1
- package/docs/types/Orientation.html +3 -3
- package/docs/types/PanCloneOverrides.html +6 -6
- package/docs/types/PanType.html +1 -1
- package/docs/types/PcmStreamEvents.html +6 -6
- package/docs/types/PcmStreamState.html +1 -1
- package/docs/types/PlaybackEvents.html +1 -1
- package/docs/types/Position.html +1 -1
- package/docs/types/SoundEvents.html +1 -1
- package/docs/types/SoundType.html +1 -1
- package/docs/types/SourceNode.html +1 -1
- package/docs/types/SpriteMap.html +1 -1
- package/docs/types/SynthEvents.html +1 -1
- package/docs/types/ThreeDOptions.html +1 -1
- package/docs/types/WebCodecsStreamSound.html +1 -1
- package/docs/variables/CHANNEL_WEIGHTS.html +1 -1
- package/docs/variables/K_WEIGHTING_STAGE1_48K.html +1 -1
- package/docs/variables/K_WEIGHTING_STAGE2_48K.html +1 -1
- package/docs/variables/MAX_REFLECTION_DELAY.html +1 -1
- package/docs/variables/OCTAVE_BAND_CENTERS.html +1 -1
- package/docs/variables/OCTAVE_BAND_COUNT.html +1 -1
- package/docs/variables/consoleLogger.html +1 -1
- package/docs/variables/noopLogger.html +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -17,6 +17,14 @@ someone upgrading, not as a commit message. `npm version` stamps the release; se
|
|
|
17
17
|
|
|
18
18
|
## [Unreleased]
|
|
19
19
|
|
|
20
|
+
## [0.39.0] - 2026-11-29
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
- `Playback.outputNode` is now a unity node after the volume node rather than the volume node itself; it still carries the full voice (direct sound and early-reflection images) and is what `connect`, `disconnect` and primary routes use. Volume and fades now apply ahead of the band stage and panner, which changes nothing in steady state; in Chromium a fade reaches the output after the HRTF panner's latency (about 6 ms).
|
|
24
|
+
|
|
25
|
+
### Fixed
|
|
26
|
+
- Aux sends (`routeTo(bus, gain)`) no longer carry a voice's early-reflection images. They carry the direct path after volume, fades, band gains and panning, so a room reverb on a send is driven by the direct sound only, while the images stay heard dry. Before, the images were fed into the reverb as well as heard: in a 3.8 x 5.1 x 2.4 m room the tail was up to 9.5 dB too loud in some octave bands and kept the listener's early-reflection comb for its whole length.
|
|
27
|
+
|
|
20
28
|
## [0.38.0] - 2026-11-28
|
|
21
29
|
|
|
22
30
|
### ⚠ Breaking
|
|
@@ -1465,7 +1473,8 @@ _0.1.0–0.1.2 were published to npm but not tagged; this block covers everythin
|
|
|
1465
1473
|
- Sounds loaded from URLs are cached with the browser Cache API (`CacheManager`), and concurrent loads of the same URL are de-duplicated.
|
|
1466
1474
|
- `Playback.fadeIn()` and `Playback.fadeOut()` with `'linear'` or `'exponential'` fades.
|
|
1467
1475
|
|
|
1468
|
-
[Unreleased]: https://github.com/ctoth/cacophony/compare/v0.
|
|
1476
|
+
[Unreleased]: https://github.com/ctoth/cacophony/compare/v0.39.0...HEAD
|
|
1477
|
+
[0.39.0]: https://github.com/ctoth/cacophony/compare/v0.38.0...v0.39.0
|
|
1469
1478
|
[0.38.0]: https://github.com/ctoth/cacophony/compare/v0.37.0...v0.38.0
|
|
1470
1479
|
[0.37.0]: https://github.com/ctoth/cacophony/compare/v0.36.0...v0.37.0
|
|
1471
1480
|
[0.36.0]: https://github.com/ctoth/cacophony/compare/v0.35.0...v0.36.0
|
package/README.md
CHANGED
|
@@ -132,7 +132,10 @@ voice.setReflections([]); // Remove them.
|
|
|
132
132
|
Each image taps the voice after its effects and before its band stage and
|
|
133
133
|
panner, then passes a delay (0 to `MAX_REFLECTION_DELAY`, 1 s), the same band
|
|
134
134
|
cascade as `setBandGains` with `gain` as an extra broadband factor, and its own
|
|
135
|
-
`PannerNode`, and joins the voice's output, so volume and fades apply.
|
|
135
|
+
`PannerNode`, and joins the voice's output, so volume and fades apply. Aux sends
|
|
136
|
+
(`routeTo(bus, gain)`) carry the direct path only: the images are heard dry and
|
|
137
|
+
never feed a reverb bus, so a room reverb is driven by the direct sound, as a
|
|
138
|
+
real room's reverberant field is driven by the source. The image
|
|
136
139
|
panner applies no distance attenuation; `gain` carries it. Positions use the same
|
|
137
140
|
frame as the listener and the voice. Image panners take the voice's panning
|
|
138
141
|
model when it is HRTF-panned and equal-power panning otherwise. An update with
|
|
@@ -957,8 +960,9 @@ function draw() {
|
|
|
957
960
|
|
|
958
961
|
### Architecture Notes
|
|
959
962
|
|
|
960
|
-
- **Internal chain**: `source →
|
|
961
|
-
- **outputNode** exposes the
|
|
963
|
+
- **Internal chain**: `source → [filters/effects] → gainNode (volume, fades) → [band stage] → panner → direct tap → output`; early-reflection images branch after `gainNode` and join `output`
|
|
964
|
+
- **outputNode** exposes `output`, the full voice (direct sound and images)
|
|
965
|
+
- Aux sends (`routeTo(bus, gain)`) tap the direct path after volume, fades, band stage and panner, without the images
|
|
962
966
|
- Default routing: `outputNode → globalGainNode → destination`
|
|
963
967
|
- Calling `disconnect()` breaks the default routing, allowing full manual control
|
|
964
968
|
|
package/dist/basePlayback.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./effectChain.cjs"),t=require("./eventEmitter.cjs"),n=require("./filters.cjs"),r=require("./pannerMixin.cjs"),i=require("./volumeMixin.cjs");var a=class extends r.PannerMixin(i.VolumeMixin(n.FilterManager)){source;_effectChain;_effectContext;_sendGains=new Map;_state=`unplayed`;origin;eventEmitter=new t.TypedEventEmitter;constructor(e){super(),this.origin=e,this.spatialSmoothingTau=e.spatialSmoothingTau??0}get _spatialSmoothingActive(){return this._state===`playing`||this._state===`paused`}setEffectChainEndpoints(t,n){if(this._effectContext=t.context??this.origin.context,this._effectChain){this._effectChain.setEndpoints(t,n);return}this._effectChain=new e.EffectChain(t,n,this.constructor.name)}addEffect(e){try{return this.materializeEffect(e)}catch(e){return Promise.reject(e)}}_addSourceEffect(e){return this.materializeEffect(e)}_addFilterEffect(e){return this.materializeEffect(e,e=>{this._filters.push(e)})}materializeEffect(e,t){if(!this._effectChain||!this._effectContext)throw Error(`Cannot add an effect before the playback effect chain is initialized`);let n=this._effectChain,r=n.reserve(),i;try{i=e.build(this._effectContext)}catch(e){throw n.cancel(r),e}if(i instanceof Promise||typeof i==`object`&&i&&`then`in i)return Promise.resolve(i).then(e=>{let i=n.resolve(r,e);return t?.(i),i},e=>{throw n.cancel(r),e});try{let e=n.resolve(r,i);return t?.(e),Promise.resolve(e)}catch(e){throw n.cancel(r),e}}rampEffectParam(e,t,n,r){if(!this._effectChain)throw Error(`Cannot automate an effect before the playback effect chain is initialized`);this._effectChain.rampParam(e,t,n,r)}addFilter(e){if(!this._effectChain)throw Error(`Cannot add a filter before the playback effect chain is initialized`);this._effectChain.add(e,this._filters.length),this._filters.push(e)}removeFilter(e){if(!this._effectChain)throw Error(`Cannot remove a filter before the playback effect chain is initialized`);this._effectChain.remove(e),this._filters=this._filters.filter(t=>t!==e)}setFilterOrder(e){if(!this._effectChain)throw Error(`Cannot reorder filters before the playback effect chain is initialized`);let t=this._effectChain.nodes.filter(e=>!this._filters.includes(e));this._effectChain.setOrder([...e,...t]),this._filters=[...e]}setFilterBypassed(e,t){if(!this._effectChain)throw Error(`Cannot bypass a filter before the playback effect chain is initialized`);this._effectChain.setBypassed(e,t)}isFilterBypassed(e){return this._effectChain?.isBypassed(e)??!1}rampFilterParam(e,t,n,r){if(!this._effectChain)throw Error(`Cannot automate a filter before the playback effect chain is initialized`);this._effectChain.rampParam(e,t,n,r)}setPanType(e,t){let n=this.panner;super.setPanType(e,t),!(this.panner===n||!this.panner||!this.source||!this.gainNode)&&(this.setEffectChainEndpoints(this.source,this.panner),this.panner.connect(this.
|
|
1
|
+
const e=require("./effectChain.cjs"),t=require("./eventEmitter.cjs"),n=require("./filters.cjs"),r=require("./pannerMixin.cjs"),i=require("./volumeMixin.cjs");var a=class extends r.PannerMixin(i.VolumeMixin(n.FilterManager)){source;_effectChain;_effectContext;_sendGains=new Map;_state=`unplayed`;origin;eventEmitter=new t.TypedEventEmitter;constructor(e){super(),this.origin=e,this.spatialSmoothingTau=e.spatialSmoothingTau??0}get _spatialSmoothingActive(){return this._state===`playing`||this._state===`paused`}setEffectChainEndpoints(t,n){if(this._effectContext=t.context??this.origin.context,this._effectChain){this._effectChain.setEndpoints(t,n);return}this._effectChain=new e.EffectChain(t,n,this.constructor.name)}addEffect(e){try{return this.materializeEffect(e)}catch(e){return Promise.reject(e)}}_addSourceEffect(e){return this.materializeEffect(e)}_addFilterEffect(e){return this.materializeEffect(e,e=>{this._filters.push(e)})}materializeEffect(e,t){if(!this._effectChain||!this._effectContext)throw Error(`Cannot add an effect before the playback effect chain is initialized`);let n=this._effectChain,r=n.reserve(),i;try{i=e.build(this._effectContext)}catch(e){throw n.cancel(r),e}if(i instanceof Promise||typeof i==`object`&&i&&`then`in i)return Promise.resolve(i).then(e=>{let i=n.resolve(r,e);return t?.(i),i},e=>{throw n.cancel(r),e});try{let e=n.resolve(r,i);return t?.(e),Promise.resolve(e)}catch(e){throw n.cancel(r),e}}rampEffectParam(e,t,n,r){if(!this._effectChain)throw Error(`Cannot automate an effect before the playback effect chain is initialized`);this._effectChain.rampParam(e,t,n,r)}addFilter(e){if(!this._effectChain)throw Error(`Cannot add a filter before the playback effect chain is initialized`);this._effectChain.add(e,this._filters.length),this._filters.push(e)}removeFilter(e){if(!this._effectChain)throw Error(`Cannot remove a filter before the playback effect chain is initialized`);this._effectChain.remove(e),this._filters=this._filters.filter(t=>t!==e)}setFilterOrder(e){if(!this._effectChain)throw Error(`Cannot reorder filters before the playback effect chain is initialized`);let t=this._effectChain.nodes.filter(e=>!this._filters.includes(e));this._effectChain.setOrder([...e,...t]),this._filters=[...e]}setFilterBypassed(e,t){if(!this._effectChain)throw Error(`Cannot bypass a filter before the playback effect chain is initialized`);this._effectChain.setBypassed(e,t)}isFilterBypassed(e){return this._effectChain?.isBypassed(e)??!1}rampFilterParam(e,t,n,r){if(!this._effectChain)throw Error(`Cannot automate a filter before the playback effect chain is initialized`);this._effectChain.rampParam(e,t,n,r)}setPanType(e,t){let n=this.panner;super.setPanType(e,t),!(this.panner===n||!this.panner||!this.source||!this.gainNode)&&(this.setEffectChainEndpoints(this.source,this.panner),this.panner.connect(this.pannerDestination))}get pannerDestination(){return this.gainNode}get _sendTap(){return this.outputNode}get state(){return this._state}get isPlaying(){return this._state===`playing`}get isPaused(){return this._state===`paused`}markPlaying(){this._state=`playing`}markPaused(){this._state=`paused`}markStopped(){this._state=`stopped`,this._snapSpatialMotion()}emitPlayStarted(e){this.markPlaying(),this.emit(`play`,this),e&&this.emit(`resume`,void 0),this.origin.cacophony?.emit(`globalPlay`,{source:this.origin,timestamp:Date.now()})}emitPaused(){this.markPaused(),this.emit(`pause`,void 0),this.origin.cacophony?.emit(`globalPause`,{source:this.origin,timestamp:Date.now()})}emitStopped(){this.markStopped(),this.emit(`stop`,void 0),this.origin.cacophony?.emit(`globalStop`,{source:this.origin,timestamp:Date.now()})}on(e,t){return this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}emit(e,t){this.eventEmitter.emit(e,t)}async emitAsync(e,t){return this.eventEmitter.emitAsync(e,t)}fadeTo(e,t,n=`linear`,r){return this.emit(`fadeStart`,{target:e,duration:t,type:n}),super.fadeTo(e,t,n,r).then(()=>{this.emit(`fadeEnd`,void 0)})}cancelFade(){let e=this._isFading;super.cancelFade(),e&&this.emit(`fadeCancel`,void 0)}cleanup(){for(let e of this._sendGains.values())try{e.disconnect()}catch{}this._sendGains.clear(),this._effectChain?.destroy(),this._effectChain=void 0,this._effectContext=void 0,this.eventEmitter.removeAllListeners(),super.cleanup()}};exports.BasePlayback=a;
|
|
2
2
|
//# sourceMappingURL=basePlayback.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"basePlayback.cjs","names":[],"sources":["../src/basePlayback.ts"],"sourcesContent":["import type { Bus } from \"./bus\";\nimport type { FadeType, PanType, PlayOptions } from \"./cacophony\";\nimport type { PlaybackContainer } from \"./container\";\nimport type { AudioNode, BaseContext, BiquadFilterNode, GainNode } from \"./context\";\nimport { EffectChain } from \"./effectChain\";\nimport type { CacophonyEffect } from \"./effects\";\nimport { TypedEventEmitter } from \"./eventEmitter\";\nimport type { PlaybackEvents } from \"./events\";\nimport { FilterManager } from \"./filters\";\nimport { PannerMixin } from \"./pannerMixin\";\nimport { VolumeMixin } from \"./volumeMixin\";\n\nexport type PlaybackState = \"unplayed\" | \"playing\" | \"paused\" | \"stopped\";\n\nexport abstract class BasePlayback extends /* @__PURE__ */ PannerMixin(/* @__PURE__ */ VolumeMixin(FilterManager)) {\n public source?: AudioNode;\n protected _effectChain?: EffectChain;\n private _effectContext?: BaseContext;\n /**\n * Per-playback send-gain allocations owned by the shared routing state\n * machine. Cleanup disconnects every allocation deterministically.\n */\n _sendGains: Map<Bus, GainNode> = new Map();\n protected _state: PlaybackState = \"unplayed\";\n public origin: PlaybackContainer;\n public eventEmitter: TypedEventEmitter<PlaybackEvents> = new TypedEventEmitter<PlaybackEvents>();\n\n constructor(origin: PlaybackContainer) {\n super();\n this.origin = origin;\n this.spatialSmoothingTau = origin.spatialSmoothingTau ?? 0;\n }\n\n /**\n * @internal Smooth only while a voice can be heard or resumed. Unplayed and stopped\n * voices take poses immediately, so a replayed voice starts at its requested pose.\n */\n override get _spatialSmoothingActive(): boolean {\n return this._state === \"playing\" || this._state === \"paused\";\n }\n\n protected setEffectChainEndpoints(input: AudioNode, output: AudioNode): void {\n this._effectContext =\n (input.context as BaseContext | undefined) ??\n (this.origin as PlaybackContainer & { context?: BaseContext }).context;\n if (this._effectChain) {\n this._effectChain.setEndpoints(input, output);\n return;\n }\n this._effectChain = new EffectChain(input, output, this.constructor.name);\n }\n\n /** Build and splice an effect into this live playback's pre-panner chain. */\n addEffect(effect: CacophonyEffect): Promise<AudioNode> {\n try {\n return this.materializeEffect(effect);\n } catch (error) {\n return Promise.reject(error);\n }\n }\n\n /** @internal Source preplay path that preserves synchronous native-build failures. */\n _addSourceEffect(effect: CacophonyEffect): Promise<AudioNode> {\n return this.materializeEffect(effect);\n }\n\n /** @internal Materialize a source-level biquad recipe and retain filter API compatibility. */\n _addFilterEffect(effect: CacophonyEffect): Promise<AudioNode> {\n return this.materializeEffect(effect, (handle) => {\n this._filters.push(handle as BiquadFilterNode);\n });\n }\n\n private materializeEffect(effect: CacophonyEffect, onBuilt?: (handle: AudioNode) => void): Promise<AudioNode> {\n if (!this._effectChain || !this._effectContext) {\n throw new Error(\"Cannot add an effect before the playback effect chain is initialized\");\n }\n const chain = this._effectChain;\n const reservation = chain.reserve();\n let built;\n try {\n built = effect.build(this._effectContext);\n } catch (error) {\n chain.cancel(reservation);\n throw error;\n }\n if (built instanceof Promise || (typeof built === \"object\" && built !== null && \"then\" in built)) {\n return Promise.resolve(built).then(\n (resolved) => {\n const handle = chain.resolve(reservation, resolved);\n onBuilt?.(handle);\n return handle;\n },\n (error) => {\n chain.cancel(reservation);\n throw error;\n },\n );\n }\n try {\n const handle = chain.resolve(reservation, built);\n onBuilt?.(handle);\n return Promise.resolve(handle);\n } catch (error) {\n chain.cancel(reservation);\n throw error;\n }\n }\n\n rampEffectParam(\n handle: AudioNode,\n paramName: string,\n value: number,\n options?: { duration?: number; type?: FadeType },\n ): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot automate an effect before the playback effect chain is initialized\");\n }\n this._effectChain.rampParam(handle, paramName, value, options);\n }\n\n addFilter(filter: BiquadFilterNode): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot add a filter before the playback effect chain is initialized\");\n }\n this._effectChain.add(filter, this._filters.length);\n this._filters.push(filter);\n }\n\n removeFilter(filter: BiquadFilterNode): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot remove a filter before the playback effect chain is initialized\");\n }\n this._effectChain.remove(filter);\n this._filters = this._filters.filter((candidate) => candidate !== filter);\n }\n\n setFilterOrder(filters: readonly BiquadFilterNode[]): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot reorder filters before the playback effect chain is initialized\");\n }\n const nonFilters = this._effectChain.nodes.filter((node) => !this._filters.includes(node as BiquadFilterNode));\n this._effectChain.setOrder([...filters, ...nonFilters]);\n this._filters = [...filters];\n }\n\n setFilterBypassed(filter: BiquadFilterNode, bypassed: boolean): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot bypass a filter before the playback effect chain is initialized\");\n }\n this._effectChain.setBypassed(filter, bypassed);\n }\n\n isFilterBypassed(filter: BiquadFilterNode): boolean {\n return this._effectChain?.isBypassed(filter) ?? false;\n }\n\n rampFilterParam(\n filter: BiquadFilterNode,\n paramName: string,\n value: number,\n options?: { duration?: number; type?: FadeType },\n ): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot automate a filter before the playback effect chain is initialized\");\n }\n this._effectChain.rampParam(filter, paramName, value, options);\n }\n\n override setPanType(panType: PanType, audioContext: BaseContext): void {\n const previousPanner = this.panner;\n super.setPanType(panType, audioContext);\n if (this.panner === previousPanner || !this.panner || !this.source || !this.gainNode) return;\n this.setEffectChainEndpoints(this.source, this.panner);\n this.panner.connect(this.gainNode);\n }\n\n abstract play(options?: PlayOptions): [this];\n abstract pause(): void;\n abstract stop(): void;\n\n /**\n * Gets the current lifecycle state without changing playback.\n */\n\n get state(): PlaybackState {\n return this._state;\n }\n\n /** Checks if the audio is currently playing. */\n get isPlaying(): boolean {\n return this._state === \"playing\";\n }\n\n get isPaused(): boolean {\n return this._state === \"paused\";\n }\n\n protected markPlaying(): void {\n this._state = \"playing\";\n }\n\n protected markPaused(): void {\n this._state = \"paused\";\n }\n\n protected markStopped(): void {\n this._state = \"stopped\";\n // A stopped voice is silent, so pending motion can finish without an audible jump.\n this._snapSpatialMotion();\n }\n\n protected emitPlayStarted(isResume: boolean): void {\n this.markPlaying();\n this.emit(\"play\", this);\n if (isResume) {\n this.emit(\"resume\", undefined);\n }\n this.origin.cacophony?.emit(\"globalPlay\", {\n source: this.origin,\n timestamp: Date.now(),\n });\n }\n\n protected emitPaused(): void {\n this.markPaused();\n this.emit(\"pause\", undefined);\n this.origin.cacophony?.emit(\"globalPause\", {\n source: this.origin,\n timestamp: Date.now(),\n });\n }\n\n protected emitStopped(): void {\n this.markStopped();\n this.emit(\"stop\", undefined);\n this.origin.cacophony?.emit(\"globalStop\", {\n source: this.origin,\n timestamp: Date.now(),\n });\n }\n\n /**\n * Register event listener.\n * @returns Cleanup function\n */\n on<K extends keyof PlaybackEvents>(event: K, listener: (data: PlaybackEvents[K]) => void): () => void {\n return this.eventEmitter.on(event, listener);\n }\n\n /**\n * Remove event listener.\n */\n off<K extends keyof PlaybackEvents>(event: K, listener: (data: PlaybackEvents[K]) => void): void {\n this.eventEmitter.off(event, listener);\n }\n\n public emit<K extends keyof PlaybackEvents>(event: K, data: PlaybackEvents[K]): void {\n this.eventEmitter.emit(event, data);\n }\n\n public async emitAsync<K extends keyof PlaybackEvents>(event: K, data: PlaybackEvents[K]): Promise<void> {\n return this.eventEmitter.emitAsync(event, data);\n }\n\n /**\n * Fades the volume to a target value, emitting fadeStart and fadeEnd events.\n */\n fadeTo(\n value: number,\n duration: number,\n type: FadeType = \"linear\",\n options?: { startTime?: number; startValue?: number },\n ): Promise<void> {\n this.emit(\"fadeStart\", { target: value, duration, type });\n return super.fadeTo(value, duration, type, options).then(() => {\n this.emit(\"fadeEnd\", undefined);\n });\n }\n\n /**\n * Cancels any in-progress fade, emitting fadeCancel if a fade was active.\n */\n cancelFade(): void {\n const wasFading = this._isFading;\n super.cancelFade();\n if (wasFading) {\n this.emit(\"fadeCancel\", undefined);\n }\n }\n\n cleanup(): void {\n for (const sendGain of this._sendGains.values()) {\n try {\n sendGain.disconnect();\n } catch {\n // The node may already have been disconnected externally.\n }\n }\n this._sendGains.clear();\n this._effectChain?.destroy();\n this._effectChain = undefined;\n this._effectContext = undefined;\n this.eventEmitter.removeAllListeners();\n super.cleanup();\n }\n}\n"],"mappings":"8JAcA,IAAsB,EAAtB,cAA2D,EAAA,YAA4B,EAAA,YAAY,EAAA,aAAa,CAAC,CAAE,CACjH,OACA,aACA,eAKA,WAAiC,IAAI,IACrC,OAAkC,WAClC,OACA,aAAyD,IAAI,EAAA,kBAE7D,YAAY,EAA2B,CACrC,MAAM,EACN,KAAK,OAAS,EACd,KAAK,oBAAsB,EAAO,qBAAuB,CAC3D,CAMA,IAAa,yBAAmC,CAC9C,OAAO,KAAK,SAAW,WAAa,KAAK,SAAW,QACtD,CAEA,wBAAkC,EAAkB,EAAyB,CAI3E,GAHA,KAAK,eACF,EAAM,SACN,KAAK,OAAyD,QAC7D,KAAK,aAAc,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CAChC,CAAC,CACH,CAKA,YAAmB,CACjB,IAAM,EAAY,KAAK,UACvB,MAAM,WAAW,EACb,GACF,KAAK,KAAK,aAAc,IAAA,EAAS,CAErC,CAEA,SAAgB,CACd,IAAK,IAAM,KAAY,KAAK,WAAW,OAAO,EAC5C,GAAI,CACF,EAAS,WAAW,CACtB,MAAQ,CAER,CAEF,KAAK,WAAW,MAAM,EACtB,KAAK,cAAc,QAAQ,EAC3B,KAAK,aAAe,IAAA,GACpB,KAAK,eAAiB,IAAA,GACtB,KAAK,aAAa,mBAAmB,EACrC,MAAM,QAAQ,CAChB,CACF"}
|
|
1
|
+
{"version":3,"file":"basePlayback.cjs","names":[],"sources":["../src/basePlayback.ts"],"sourcesContent":["import type { Bus } from \"./bus\";\nimport type { FadeType, PanType, PlayOptions } from \"./cacophony\";\nimport type { PlaybackContainer } from \"./container\";\nimport type { AudioNode, BaseContext, BiquadFilterNode, GainNode } from \"./context\";\nimport { EffectChain } from \"./effectChain\";\nimport type { CacophonyEffect } from \"./effects\";\nimport { TypedEventEmitter } from \"./eventEmitter\";\nimport type { PlaybackEvents } from \"./events\";\nimport { FilterManager } from \"./filters\";\nimport { PannerMixin } from \"./pannerMixin\";\nimport { VolumeMixin } from \"./volumeMixin\";\n\nexport type PlaybackState = \"unplayed\" | \"playing\" | \"paused\" | \"stopped\";\n\nexport abstract class BasePlayback extends /* @__PURE__ */ PannerMixin(/* @__PURE__ */ VolumeMixin(FilterManager)) {\n public source?: AudioNode;\n protected _effectChain?: EffectChain;\n private _effectContext?: BaseContext;\n /**\n * Per-playback send-gain allocations owned by the shared routing state\n * machine. Cleanup disconnects every allocation deterministically.\n */\n _sendGains: Map<Bus, GainNode> = new Map();\n protected _state: PlaybackState = \"unplayed\";\n public origin: PlaybackContainer;\n public eventEmitter: TypedEventEmitter<PlaybackEvents> = new TypedEventEmitter<PlaybackEvents>();\n\n constructor(origin: PlaybackContainer) {\n super();\n this.origin = origin;\n this.spatialSmoothingTau = origin.spatialSmoothingTau ?? 0;\n }\n\n /**\n * @internal Smooth only while a voice can be heard or resumed. Unplayed and stopped\n * voices take poses immediately, so a replayed voice starts at its requested pose.\n */\n override get _spatialSmoothingActive(): boolean {\n return this._state === \"playing\" || this._state === \"paused\";\n }\n\n protected setEffectChainEndpoints(input: AudioNode, output: AudioNode): void {\n this._effectContext =\n (input.context as BaseContext | undefined) ??\n (this.origin as PlaybackContainer & { context?: BaseContext }).context;\n if (this._effectChain) {\n this._effectChain.setEndpoints(input, output);\n return;\n }\n this._effectChain = new EffectChain(input, output, this.constructor.name);\n }\n\n /** Build and splice an effect into this live playback's pre-panner chain. */\n addEffect(effect: CacophonyEffect): Promise<AudioNode> {\n try {\n return this.materializeEffect(effect);\n } catch (error) {\n return Promise.reject(error);\n }\n }\n\n /** @internal Source preplay path that preserves synchronous native-build failures. */\n _addSourceEffect(effect: CacophonyEffect): Promise<AudioNode> {\n return this.materializeEffect(effect);\n }\n\n /** @internal Materialize a source-level biquad recipe and retain filter API compatibility. */\n _addFilterEffect(effect: CacophonyEffect): Promise<AudioNode> {\n return this.materializeEffect(effect, (handle) => {\n this._filters.push(handle as BiquadFilterNode);\n });\n }\n\n private materializeEffect(effect: CacophonyEffect, onBuilt?: (handle: AudioNode) => void): Promise<AudioNode> {\n if (!this._effectChain || !this._effectContext) {\n throw new Error(\"Cannot add an effect before the playback effect chain is initialized\");\n }\n const chain = this._effectChain;\n const reservation = chain.reserve();\n let built;\n try {\n built = effect.build(this._effectContext);\n } catch (error) {\n chain.cancel(reservation);\n throw error;\n }\n if (built instanceof Promise || (typeof built === \"object\" && built !== null && \"then\" in built)) {\n return Promise.resolve(built).then(\n (resolved) => {\n const handle = chain.resolve(reservation, resolved);\n onBuilt?.(handle);\n return handle;\n },\n (error) => {\n chain.cancel(reservation);\n throw error;\n },\n );\n }\n try {\n const handle = chain.resolve(reservation, built);\n onBuilt?.(handle);\n return Promise.resolve(handle);\n } catch (error) {\n chain.cancel(reservation);\n throw error;\n }\n }\n\n rampEffectParam(\n handle: AudioNode,\n paramName: string,\n value: number,\n options?: { duration?: number; type?: FadeType },\n ): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot automate an effect before the playback effect chain is initialized\");\n }\n this._effectChain.rampParam(handle, paramName, value, options);\n }\n\n addFilter(filter: BiquadFilterNode): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot add a filter before the playback effect chain is initialized\");\n }\n this._effectChain.add(filter, this._filters.length);\n this._filters.push(filter);\n }\n\n removeFilter(filter: BiquadFilterNode): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot remove a filter before the playback effect chain is initialized\");\n }\n this._effectChain.remove(filter);\n this._filters = this._filters.filter((candidate) => candidate !== filter);\n }\n\n setFilterOrder(filters: readonly BiquadFilterNode[]): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot reorder filters before the playback effect chain is initialized\");\n }\n const nonFilters = this._effectChain.nodes.filter((node) => !this._filters.includes(node as BiquadFilterNode));\n this._effectChain.setOrder([...filters, ...nonFilters]);\n this._filters = [...filters];\n }\n\n setFilterBypassed(filter: BiquadFilterNode, bypassed: boolean): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot bypass a filter before the playback effect chain is initialized\");\n }\n this._effectChain.setBypassed(filter, bypassed);\n }\n\n isFilterBypassed(filter: BiquadFilterNode): boolean {\n return this._effectChain?.isBypassed(filter) ?? false;\n }\n\n rampFilterParam(\n filter: BiquadFilterNode,\n paramName: string,\n value: number,\n options?: { duration?: number; type?: FadeType },\n ): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot automate a filter before the playback effect chain is initialized\");\n }\n this._effectChain.rampParam(filter, paramName, value, options);\n }\n\n override setPanType(panType: PanType, audioContext: BaseContext): void {\n const previousPanner = this.panner;\n super.setPanType(panType, audioContext);\n if (this.panner === previousPanner || !this.panner || !this.source || !this.gainNode) return;\n this.setEffectChainEndpoints(this.source, this.panner);\n this.panner.connect(this.pannerDestination);\n }\n\n /** The node the panner feeds; the volume node unless a subclass places volume earlier. */\n protected get pannerDestination(): AudioNode {\n return this.gainNode!;\n }\n\n /** The full output of this playback: every consumer that hears the voice connects here. */\n abstract get outputNode(): GainNode;\n\n /**\n * @internal The node aux sends connect from. Defaults to {@link outputNode};\n * a playback with early reflections taps its direct path only.\n */\n get _sendTap(): AudioNode {\n return this.outputNode;\n }\n\n abstract play(options?: PlayOptions): [this];\n abstract pause(): void;\n abstract stop(): void;\n\n /**\n * Gets the current lifecycle state without changing playback.\n */\n\n get state(): PlaybackState {\n return this._state;\n }\n\n /** Checks if the audio is currently playing. */\n get isPlaying(): boolean {\n return this._state === \"playing\";\n }\n\n get isPaused(): boolean {\n return this._state === \"paused\";\n }\n\n protected markPlaying(): void {\n this._state = \"playing\";\n }\n\n protected markPaused(): void {\n this._state = \"paused\";\n }\n\n protected markStopped(): void {\n this._state = \"stopped\";\n // A stopped voice is silent, so pending motion can finish without an audible jump.\n this._snapSpatialMotion();\n }\n\n protected emitPlayStarted(isResume: boolean): void {\n this.markPlaying();\n this.emit(\"play\", this);\n if (isResume) {\n this.emit(\"resume\", undefined);\n }\n this.origin.cacophony?.emit(\"globalPlay\", {\n source: this.origin,\n timestamp: Date.now(),\n });\n }\n\n protected emitPaused(): void {\n this.markPaused();\n this.emit(\"pause\", undefined);\n this.origin.cacophony?.emit(\"globalPause\", {\n source: this.origin,\n timestamp: Date.now(),\n });\n }\n\n protected emitStopped(): void {\n this.markStopped();\n this.emit(\"stop\", undefined);\n this.origin.cacophony?.emit(\"globalStop\", {\n source: this.origin,\n timestamp: Date.now(),\n });\n }\n\n /**\n * Register event listener.\n * @returns Cleanup function\n */\n on<K extends keyof PlaybackEvents>(event: K, listener: (data: PlaybackEvents[K]) => void): () => void {\n return this.eventEmitter.on(event, listener);\n }\n\n /**\n * Remove event listener.\n */\n off<K extends keyof PlaybackEvents>(event: K, listener: (data: PlaybackEvents[K]) => void): void {\n this.eventEmitter.off(event, listener);\n }\n\n public emit<K extends keyof PlaybackEvents>(event: K, data: PlaybackEvents[K]): void {\n this.eventEmitter.emit(event, data);\n }\n\n public async emitAsync<K extends keyof PlaybackEvents>(event: K, data: PlaybackEvents[K]): Promise<void> {\n return this.eventEmitter.emitAsync(event, data);\n }\n\n /**\n * Fades the volume to a target value, emitting fadeStart and fadeEnd events.\n */\n fadeTo(\n value: number,\n duration: number,\n type: FadeType = \"linear\",\n options?: { startTime?: number; startValue?: number },\n ): Promise<void> {\n this.emit(\"fadeStart\", { target: value, duration, type });\n return super.fadeTo(value, duration, type, options).then(() => {\n this.emit(\"fadeEnd\", undefined);\n });\n }\n\n /**\n * Cancels any in-progress fade, emitting fadeCancel if a fade was active.\n */\n cancelFade(): void {\n const wasFading = this._isFading;\n super.cancelFade();\n if (wasFading) {\n this.emit(\"fadeCancel\", undefined);\n }\n }\n\n cleanup(): void {\n for (const sendGain of this._sendGains.values()) {\n try {\n sendGain.disconnect();\n } catch {\n // The node may already have been disconnected externally.\n }\n }\n this._sendGains.clear();\n this._effectChain?.destroy();\n this._effectChain = undefined;\n this._effectContext = undefined;\n this.eventEmitter.removeAllListeners();\n super.cleanup();\n }\n}\n"],"mappings":"8JAcA,IAAsB,EAAtB,cAA2D,EAAA,YAA4B,EAAA,YAAY,EAAA,aAAa,CAAC,CAAE,CACjH,OACA,aACA,eAKA,WAAiC,IAAI,IACrC,OAAkC,WAClC,OACA,aAAyD,IAAI,EAAA,kBAE7D,YAAY,EAA2B,CACrC,MAAM,EACN,KAAK,OAAS,EACd,KAAK,oBAAsB,EAAO,qBAAuB,CAC3D,CAMA,IAAa,yBAAmC,CAC9C,OAAO,KAAK,SAAW,WAAa,KAAK,SAAW,QACtD,CAEA,wBAAkC,EAAkB,EAAyB,CAI3E,GAHA,KAAK,eACF,EAAM,SACN,KAAK,OAAyD,QAC7D,KAAK,aAAc,CACrB,KAAK,aAAa,aAAa,EAAO,CAAM,EAC5C,MACF,CACA,KAAK,aAAe,IAAI,EAAA,YAAY,EAAO,EAAQ,KAAK,YAAY,IAAI,CAC1E,CAGA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AM,EAAY,KAAK,UACvB,MAAM,WAAW,EACb,GACF,KAAK,KAAK,aAAc,IAAA,EAAS,CAErC,CAEA,SAAgB,CACd,IAAK,IAAM,KAAY,KAAK,WAAW,OAAO,EAC5C,GAAI,CACF,EAAS,WAAW,CACtB,MAAQ,CAER,CAEF,KAAK,WAAW,MAAM,EACtB,KAAK,cAAc,QAAQ,EAC3B,KAAK,aAAe,IAAA,GACpB,KAAK,eAAiB,IAAA,GACtB,KAAK,aAAa,mBAAmB,EACrC,MAAM,QAAQ,CAChB,CACF"}
|
package/dist/basePlayback.d.ts
CHANGED
|
@@ -49,6 +49,15 @@ export declare abstract class BasePlayback extends /* @__PURE__ */ BasePlayback_
|
|
|
49
49
|
type?: FadeType;
|
|
50
50
|
}): void;
|
|
51
51
|
setPanType(panType: PanType, audioContext: BaseContext): void;
|
|
52
|
+
/** The node the panner feeds; the volume node unless a subclass places volume earlier. */
|
|
53
|
+
protected get pannerDestination(): AudioNode;
|
|
54
|
+
/** The full output of this playback: every consumer that hears the voice connects here. */
|
|
55
|
+
abstract get outputNode(): GainNode;
|
|
56
|
+
/**
|
|
57
|
+
* @internal The node aux sends connect from. Defaults to {@link outputNode};
|
|
58
|
+
* a playback with early reflections taps its direct path only.
|
|
59
|
+
*/
|
|
60
|
+
get _sendTap(): AudioNode;
|
|
52
61
|
abstract play(options?: PlayOptions): [this];
|
|
53
62
|
abstract pause(): void;
|
|
54
63
|
abstract stop(): void;
|
package/dist/basePlayback.mjs
CHANGED
|
@@ -91,7 +91,13 @@ var a = class extends r(/* @__PURE__ */ i(n)) {
|
|
|
91
91
|
}
|
|
92
92
|
setPanType(e, t) {
|
|
93
93
|
let n = this.panner;
|
|
94
|
-
super.setPanType(e, t), !(this.panner === n || !this.panner || !this.source || !this.gainNode) && (this.setEffectChainEndpoints(this.source, this.panner), this.panner.connect(this.
|
|
94
|
+
super.setPanType(e, t), !(this.panner === n || !this.panner || !this.source || !this.gainNode) && (this.setEffectChainEndpoints(this.source, this.panner), this.panner.connect(this.pannerDestination));
|
|
95
|
+
}
|
|
96
|
+
get pannerDestination() {
|
|
97
|
+
return this.gainNode;
|
|
98
|
+
}
|
|
99
|
+
get _sendTap() {
|
|
100
|
+
return this.outputNode;
|
|
95
101
|
}
|
|
96
102
|
get state() {
|
|
97
103
|
return this._state;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"basePlayback.mjs","names":[],"sources":["../src/basePlayback.ts"],"sourcesContent":["import type { Bus } from \"./bus\";\nimport type { FadeType, PanType, PlayOptions } from \"./cacophony\";\nimport type { PlaybackContainer } from \"./container\";\nimport type { AudioNode, BaseContext, BiquadFilterNode, GainNode } from \"./context\";\nimport { EffectChain } from \"./effectChain\";\nimport type { CacophonyEffect } from \"./effects\";\nimport { TypedEventEmitter } from \"./eventEmitter\";\nimport type { PlaybackEvents } from \"./events\";\nimport { FilterManager } from \"./filters\";\nimport { PannerMixin } from \"./pannerMixin\";\nimport { VolumeMixin } from \"./volumeMixin\";\n\nexport type PlaybackState = \"unplayed\" | \"playing\" | \"paused\" | \"stopped\";\n\nexport abstract class BasePlayback extends /* @__PURE__ */ PannerMixin(/* @__PURE__ */ VolumeMixin(FilterManager)) {\n public source?: AudioNode;\n protected _effectChain?: EffectChain;\n private _effectContext?: BaseContext;\n /**\n * Per-playback send-gain allocations owned by the shared routing state\n * machine. Cleanup disconnects every allocation deterministically.\n */\n _sendGains: Map<Bus, GainNode> = new Map();\n protected _state: PlaybackState = \"unplayed\";\n public origin: PlaybackContainer;\n public eventEmitter: TypedEventEmitter<PlaybackEvents> = new TypedEventEmitter<PlaybackEvents>();\n\n constructor(origin: PlaybackContainer) {\n super();\n this.origin = origin;\n this.spatialSmoothingTau = origin.spatialSmoothingTau ?? 0;\n }\n\n /**\n * @internal Smooth only while a voice can be heard or resumed. Unplayed and stopped\n * voices take poses immediately, so a replayed voice starts at its requested pose.\n */\n override get _spatialSmoothingActive(): boolean {\n return this._state === \"playing\" || this._state === \"paused\";\n }\n\n protected setEffectChainEndpoints(input: AudioNode, output: AudioNode): void {\n this._effectContext =\n (input.context as BaseContext | undefined) ??\n (this.origin as PlaybackContainer & { context?: BaseContext }).context;\n if (this._effectChain) {\n this._effectChain.setEndpoints(input, output);\n return;\n }\n this._effectChain = new EffectChain(input, output, this.constructor.name);\n }\n\n /** Build and splice an effect into this live playback's pre-panner chain. */\n addEffect(effect: CacophonyEffect): Promise<AudioNode> {\n try {\n return this.materializeEffect(effect);\n } catch (error) {\n return Promise.reject(error);\n }\n }\n\n /** @internal Source preplay path that preserves synchronous native-build failures. */\n _addSourceEffect(effect: CacophonyEffect): Promise<AudioNode> {\n return this.materializeEffect(effect);\n }\n\n /** @internal Materialize a source-level biquad recipe and retain filter API compatibility. */\n _addFilterEffect(effect: CacophonyEffect): Promise<AudioNode> {\n return this.materializeEffect(effect, (handle) => {\n this._filters.push(handle as BiquadFilterNode);\n });\n }\n\n private materializeEffect(effect: CacophonyEffect, onBuilt?: (handle: AudioNode) => void): Promise<AudioNode> {\n if (!this._effectChain || !this._effectContext) {\n throw new Error(\"Cannot add an effect before the playback effect chain is initialized\");\n }\n const chain = this._effectChain;\n const reservation = chain.reserve();\n let built;\n try {\n built = effect.build(this._effectContext);\n } catch (error) {\n chain.cancel(reservation);\n throw error;\n }\n if (built instanceof Promise || (typeof built === \"object\" && built !== null && \"then\" in built)) {\n return Promise.resolve(built).then(\n (resolved) => {\n const handle = chain.resolve(reservation, resolved);\n onBuilt?.(handle);\n return handle;\n },\n (error) => {\n chain.cancel(reservation);\n throw error;\n },\n );\n }\n try {\n const handle = chain.resolve(reservation, built);\n onBuilt?.(handle);\n return Promise.resolve(handle);\n } catch (error) {\n chain.cancel(reservation);\n throw error;\n }\n }\n\n rampEffectParam(\n handle: AudioNode,\n paramName: string,\n value: number,\n options?: { duration?: number; type?: FadeType },\n ): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot automate an effect before the playback effect chain is initialized\");\n }\n this._effectChain.rampParam(handle, paramName, value, options);\n }\n\n addFilter(filter: BiquadFilterNode): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot add a filter before the playback effect chain is initialized\");\n }\n this._effectChain.add(filter, this._filters.length);\n this._filters.push(filter);\n }\n\n removeFilter(filter: BiquadFilterNode): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot remove a filter before the playback effect chain is initialized\");\n }\n this._effectChain.remove(filter);\n this._filters = this._filters.filter((candidate) => candidate !== filter);\n }\n\n setFilterOrder(filters: readonly BiquadFilterNode[]): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot reorder filters before the playback effect chain is initialized\");\n }\n const nonFilters = this._effectChain.nodes.filter((node) => !this._filters.includes(node as BiquadFilterNode));\n this._effectChain.setOrder([...filters, ...nonFilters]);\n this._filters = [...filters];\n }\n\n setFilterBypassed(filter: BiquadFilterNode, bypassed: boolean): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot bypass a filter before the playback effect chain is initialized\");\n }\n this._effectChain.setBypassed(filter, bypassed);\n }\n\n isFilterBypassed(filter: BiquadFilterNode): boolean {\n return this._effectChain?.isBypassed(filter) ?? false;\n }\n\n rampFilterParam(\n filter: BiquadFilterNode,\n paramName: string,\n value: number,\n options?: { duration?: number; type?: FadeType },\n ): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot automate a filter before the playback effect chain is initialized\");\n }\n this._effectChain.rampParam(filter, paramName, value, options);\n }\n\n override setPanType(panType: PanType, audioContext: BaseContext): void {\n const previousPanner = this.panner;\n super.setPanType(panType, audioContext);\n if (this.panner === previousPanner || !this.panner || !this.source || !this.gainNode) return;\n this.setEffectChainEndpoints(this.source, this.panner);\n this.panner.connect(this.gainNode);\n }\n\n abstract play(options?: PlayOptions): [this];\n abstract pause(): void;\n abstract stop(): void;\n\n /**\n * Gets the current lifecycle state without changing playback.\n */\n\n get state(): PlaybackState {\n return this._state;\n }\n\n /** Checks if the audio is currently playing. */\n get isPlaying(): boolean {\n return this._state === \"playing\";\n }\n\n get isPaused(): boolean {\n return this._state === \"paused\";\n }\n\n protected markPlaying(): void {\n this._state = \"playing\";\n }\n\n protected markPaused(): void {\n this._state = \"paused\";\n }\n\n protected markStopped(): void {\n this._state = \"stopped\";\n // A stopped voice is silent, so pending motion can finish without an audible jump.\n this._snapSpatialMotion();\n }\n\n protected emitPlayStarted(isResume: boolean): void {\n this.markPlaying();\n this.emit(\"play\", this);\n if (isResume) {\n this.emit(\"resume\", undefined);\n }\n this.origin.cacophony?.emit(\"globalPlay\", {\n source: this.origin,\n timestamp: Date.now(),\n });\n }\n\n protected emitPaused(): void {\n this.markPaused();\n this.emit(\"pause\", undefined);\n this.origin.cacophony?.emit(\"globalPause\", {\n source: this.origin,\n timestamp: Date.now(),\n });\n }\n\n protected emitStopped(): void {\n this.markStopped();\n this.emit(\"stop\", undefined);\n this.origin.cacophony?.emit(\"globalStop\", {\n source: this.origin,\n timestamp: Date.now(),\n });\n }\n\n /**\n * Register event listener.\n * @returns Cleanup function\n */\n on<K extends keyof PlaybackEvents>(event: K, listener: (data: PlaybackEvents[K]) => void): () => void {\n return this.eventEmitter.on(event, listener);\n }\n\n /**\n * Remove event listener.\n */\n off<K extends keyof PlaybackEvents>(event: K, listener: (data: PlaybackEvents[K]) => void): void {\n this.eventEmitter.off(event, listener);\n }\n\n public emit<K extends keyof PlaybackEvents>(event: K, data: PlaybackEvents[K]): void {\n this.eventEmitter.emit(event, data);\n }\n\n public async emitAsync<K extends keyof PlaybackEvents>(event: K, data: PlaybackEvents[K]): Promise<void> {\n return this.eventEmitter.emitAsync(event, data);\n }\n\n /**\n * Fades the volume to a target value, emitting fadeStart and fadeEnd events.\n */\n fadeTo(\n value: number,\n duration: number,\n type: FadeType = \"linear\",\n options?: { startTime?: number; startValue?: number },\n ): Promise<void> {\n this.emit(\"fadeStart\", { target: value, duration, type });\n return super.fadeTo(value, duration, type, options).then(() => {\n this.emit(\"fadeEnd\", undefined);\n });\n }\n\n /**\n * Cancels any in-progress fade, emitting fadeCancel if a fade was active.\n */\n cancelFade(): void {\n const wasFading = this._isFading;\n super.cancelFade();\n if (wasFading) {\n this.emit(\"fadeCancel\", undefined);\n }\n }\n\n cleanup(): void {\n for (const sendGain of this._sendGains.values()) {\n try {\n sendGain.disconnect();\n } catch {\n // The node may already have been disconnected externally.\n }\n }\n this._sendGains.clear();\n this._effectChain?.destroy();\n this._effectChain = undefined;\n this._effectContext = undefined;\n this.eventEmitter.removeAllListeners();\n super.cleanup();\n }\n}\n"],"mappings":";;;;;;AAcA,IAAsB,IAAtB,cAA2D,EAA4B,kBAAY,CAAa,CAAC,EAAE;CACjH;CACA;CACA;CAKA,6BAAiC,IAAI,IAAI;CACzC,SAAkC;CAClC;CACA,eAAyD,IAAI,EAAkC;CAE/F,YAAY,GAA2B;EAGrC,AAFA,MAAM,GACN,KAAK,SAAS,GACd,KAAK,sBAAsB,EAAO,uBAAuB;CAC3D;CAMA,IAAa,0BAAmC;EAC9C,OAAO,KAAK,WAAW,aAAa,KAAK,WAAW;CACtD;CAEA,wBAAkC,GAAkB,GAAyB;EAI3E,IAHA,KAAK,iBACF,EAAM,WACN,KAAK,OAAyD,SAC7D,KAAK,cAAc;GACrB,KAAK,aAAa,aAAa,GAAO,CAAM;GAC5C;EACF;EACA,KAAK,eAAe,IAAI,EAAY,GAAO,GAAQ,KAAK,YAAY,IAAI;CAC1E;CAGA,UAAU,GAA6C;EACrD,IAAI;GACF,OAAO,KAAK,kBAAkB,CAAM;EACtC,SAAS,GAAO;GACd,OAAO,QAAQ,OAAO,CAAK;EAC7B;CACF;CAGA,iBAAiB,GAA6C;EAC5D,OAAO,KAAK,kBAAkB,CAAM;CACtC;CAGA,iBAAiB,GAA6C;EAC5D,OAAO,KAAK,kBAAkB,IAAS,MAAW;GAChD,KAAK,SAAS,KAAK,CAA0B;EAC/C,CAAC;CACH;CAEA,kBAA0B,GAAyB,GAA2D;EAC5G,IAAI,CAAC,KAAK,gBAAgB,CAAC,KAAK,gBAC9B,MAAU,MAAM,sEAAsE;EAExF,IA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O,WAAW,KAAK,eAAe;GACzC,QAAQ,KAAK;GACb,WAAW,KAAK,IAAI;EACtB,CAAC;CACH;CAEA,cAA8B;EAG5B,AAFA,KAAK,YAAY,GACjB,KAAK,KAAK,QAAQ,KAAA,CAAS,GAC3B,KAAK,OAAO,WAAW,KAAK,cAAc;GACxC,QAAQ,KAAK;GACb,WAAW,KAAK,IAAI;EACtB,CAAC;CACH;CAMA,GAAmC,GAAU,GAAyD;EACpG,OAAO,KAAK,aAAa,GAAG,GAAO,CAAQ;CAC7C;CAKA,IAAoC,GAAU,GAAmD;EAC/F,KAAK,aAAa,IAAI,GAAO,CAAQ;CACvC;CAEA,KAA4C,GAAU,GAA+B;EACnF,KAAK,aAAa,KAAK,GAAO,CAAI;CACpC;CAEA,MAAa,UAA0C,GAAU,GAAwC;EACvG,OAAO,KAAK,aAAa,UAAU,GAAO,CAAI;CAChD;CAKA,OACE,GACA,GACA,IAAiB,UACjB,GACe;EAEf,OADA,KAAK,KAAK,aAAa;GAAE,QAAQ;GAAO;GAAU;EAAK,CAAC,GACjD,MAAM,OAAO,GAAO,GAAU,GAAM,CAAO,EAAE,WAAW;GAC7D,KAAK,KAAK,WAAW,KAAA,CAAS;EAChC,CAAC;CACH;CAKA,aAAmB;EACjB,IAAM,IAAY,KAAK;EAEvB,AADA,MAAM,WAAW,GACb,KACF,KAAK,KAAK,cAAc,KAAA,CAAS;CAErC;CAEA,UAAgB;EACd,KAAK,IAAM,KAAY,KAAK,WAAW,OAAO,GAC5C,IAAI;GACF,EAAS,WAAW;EACtB,QAAQ,CAER;EAOF,AALA,KAAK,WAAW,MAAM,GACtB,KAAK,cAAc,QAAQ,GAC3B,KAAK,eAAe,KAAA,GACpB,KAAK,iBAAiB,KAAA,GACtB,KAAK,aAAa,mBAAmB,GACrC,MAAM,QAAQ;CAChB;AACF"}
|
|
1
|
+
{"version":3,"file":"basePlayback.mjs","names":[],"sources":["../src/basePlayback.ts"],"sourcesContent":["import type { Bus } from \"./bus\";\nimport type { FadeType, PanType, PlayOptions } from \"./cacophony\";\nimport type { PlaybackContainer } from \"./container\";\nimport type { AudioNode, BaseContext, BiquadFilterNode, GainNode } from \"./context\";\nimport { EffectChain } from \"./effectChain\";\nimport type { CacophonyEffect } from \"./effects\";\nimport { TypedEventEmitter } from \"./eventEmitter\";\nimport type { PlaybackEvents } from \"./events\";\nimport { FilterManager } from \"./filters\";\nimport { PannerMixin } from \"./pannerMixin\";\nimport { VolumeMixin } from \"./volumeMixin\";\n\nexport type PlaybackState = \"unplayed\" | \"playing\" | \"paused\" | \"stopped\";\n\nexport abstract class BasePlayback extends /* @__PURE__ */ PannerMixin(/* @__PURE__ */ VolumeMixin(FilterManager)) {\n public source?: AudioNode;\n protected _effectChain?: EffectChain;\n private _effectContext?: BaseContext;\n /**\n * Per-playback send-gain allocations owned by the shared routing state\n * machine. Cleanup disconnects every allocation deterministically.\n */\n _sendGains: Map<Bus, GainNode> = new Map();\n protected _state: PlaybackState = \"unplayed\";\n public origin: PlaybackContainer;\n public eventEmitter: TypedEventEmitter<PlaybackEvents> = new TypedEventEmitter<PlaybackEvents>();\n\n constructor(origin: PlaybackContainer) {\n super();\n this.origin = origin;\n this.spatialSmoothingTau = origin.spatialSmoothingTau ?? 0;\n }\n\n /**\n * @internal Smooth only while a voice can be heard or resumed. Unplayed and stopped\n * voices take poses immediately, so a replayed voice starts at its requested pose.\n */\n override get _spatialSmoothingActive(): boolean {\n return this._state === \"playing\" || this._state === \"paused\";\n }\n\n protected setEffectChainEndpoints(input: AudioNode, output: AudioNode): void {\n this._effectContext =\n (input.context as BaseContext | undefined) ??\n (this.origin as PlaybackContainer & { context?: BaseContext }).context;\n if (this._effectChain) {\n this._effectChain.setEndpoints(input, output);\n return;\n }\n this._effectChain = new EffectChain(input, output, this.constructor.name);\n }\n\n /** Build and splice an effect into this live playback's pre-panner chain. */\n addEffect(effect: CacophonyEffect): Promise<AudioNode> {\n try {\n return this.materializeEffect(effect);\n } catch (error) {\n return Promise.reject(error);\n }\n }\n\n /** @internal Source preplay path that preserves synchronous native-build failures. */\n _addSourceEffect(effect: CacophonyEffect): Promise<AudioNode> {\n return this.materializeEffect(effect);\n }\n\n /** @internal Materialize a source-level biquad recipe and retain filter API compatibility. */\n _addFilterEffect(effect: CacophonyEffect): Promise<AudioNode> {\n return this.materializeEffect(effect, (handle) => {\n this._filters.push(handle as BiquadFilterNode);\n });\n }\n\n private materializeEffect(effect: CacophonyEffect, onBuilt?: (handle: AudioNode) => void): Promise<AudioNode> {\n if (!this._effectChain || !this._effectContext) {\n throw new Error(\"Cannot add an effect before the playback effect chain is initialized\");\n }\n const chain = this._effectChain;\n const reservation = chain.reserve();\n let built;\n try {\n built = effect.build(this._effectContext);\n } catch (error) {\n chain.cancel(reservation);\n throw error;\n }\n if (built instanceof Promise || (typeof built === \"object\" && built !== null && \"then\" in built)) {\n return Promise.resolve(built).then(\n (resolved) => {\n const handle = chain.resolve(reservation, resolved);\n onBuilt?.(handle);\n return handle;\n },\n (error) => {\n chain.cancel(reservation);\n throw error;\n },\n );\n }\n try {\n const handle = chain.resolve(reservation, built);\n onBuilt?.(handle);\n return Promise.resolve(handle);\n } catch (error) {\n chain.cancel(reservation);\n throw error;\n }\n }\n\n rampEffectParam(\n handle: AudioNode,\n paramName: string,\n value: number,\n options?: { duration?: number; type?: FadeType },\n ): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot automate an effect before the playback effect chain is initialized\");\n }\n this._effectChain.rampParam(handle, paramName, value, options);\n }\n\n addFilter(filter: BiquadFilterNode): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot add a filter before the playback effect chain is initialized\");\n }\n this._effectChain.add(filter, this._filters.length);\n this._filters.push(filter);\n }\n\n removeFilter(filter: BiquadFilterNode): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot remove a filter before the playback effect chain is initialized\");\n }\n this._effectChain.remove(filter);\n this._filters = this._filters.filter((candidate) => candidate !== filter);\n }\n\n setFilterOrder(filters: readonly BiquadFilterNode[]): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot reorder filters before the playback effect chain is initialized\");\n }\n const nonFilters = this._effectChain.nodes.filter((node) => !this._filters.includes(node as BiquadFilterNode));\n this._effectChain.setOrder([...filters, ...nonFilters]);\n this._filters = [...filters];\n }\n\n setFilterBypassed(filter: BiquadFilterNode, bypassed: boolean): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot bypass a filter before the playback effect chain is initialized\");\n }\n this._effectChain.setBypassed(filter, bypassed);\n }\n\n isFilterBypassed(filter: BiquadFilterNode): boolean {\n return this._effectChain?.isBypassed(filter) ?? false;\n }\n\n rampFilterParam(\n filter: BiquadFilterNode,\n paramName: string,\n value: number,\n options?: { duration?: number; type?: FadeType },\n ): void {\n if (!this._effectChain) {\n throw new Error(\"Cannot automate a filter before the playback effect chain is initialized\");\n }\n this._effectChain.rampParam(filter, paramName, value, options);\n }\n\n override setPanType(panType: PanType, audioContext: BaseContext): void {\n const previousPanner = this.panner;\n super.setPanType(panType, audioContext);\n if (this.panner === previousPanner || !this.panner || !this.source || !this.gainNode) return;\n this.setEffectChainEndpoints(this.source, this.panner);\n this.panner.connect(this.pannerDestination);\n }\n\n /** The node the panner feeds; the volume node unless a subclass places volume earlier. */\n protected get pannerDestination(): AudioNode {\n return this.gainNode!;\n }\n\n /** The full output of this playback: every consumer that hears the voice connects here. */\n abstract get outputNode(): GainNode;\n\n /**\n * @internal The node aux sends connect from. Defaults to {@link outputNode};\n * a playback with early reflections taps its direct path only.\n */\n get _sendTap(): AudioNode {\n return this.outputNode;\n }\n\n abstract play(options?: PlayOptions): [this];\n abstract pause(): void;\n abstract stop(): void;\n\n /**\n * Gets the current lifecycle state without changing playback.\n */\n\n get state(): PlaybackState {\n return this._state;\n }\n\n /** Checks if the audio is currently playing. */\n get isPlaying(): boolean {\n return this._state === \"playing\";\n }\n\n get isPaused(): boolean {\n return this._state === \"paused\";\n }\n\n protected markPlaying(): void {\n this._state = \"playing\";\n }\n\n protected markPaused(): void {\n this._state = \"paused\";\n }\n\n protected markStopped(): void {\n this._state = \"stopped\";\n // A stopped voice is silent, so pending motion can finish without an audible jump.\n this._snapSpatialMotion();\n }\n\n protected emitPlayStarted(isResume: boolean): void {\n this.markPlaying();\n this.emit(\"play\", this);\n if (isResume) {\n this.emit(\"resume\", undefined);\n }\n this.origin.cacophony?.emit(\"globalPlay\", {\n source: this.origin,\n timestamp: Date.now(),\n });\n }\n\n protected emitPaused(): void {\n this.markPaused();\n this.emit(\"pause\", undefined);\n this.origin.cacophony?.emit(\"globalPause\", {\n source: this.origin,\n timestamp: Date.now(),\n });\n }\n\n protected emitStopped(): void {\n this.markStopped();\n this.emit(\"stop\", undefined);\n this.origin.cacophony?.emit(\"globalStop\", {\n source: this.origin,\n timestamp: Date.now(),\n });\n }\n\n /**\n * Register event listener.\n * @returns Cleanup function\n */\n on<K extends keyof PlaybackEvents>(event: K, listener: (data: PlaybackEvents[K]) => void): () => void {\n return this.eventEmitter.on(event, listener);\n }\n\n /**\n * Remove event listener.\n */\n off<K extends keyof PlaybackEvents>(event: K, listener: (data: PlaybackEvents[K]) => void): void {\n this.eventEmitter.off(event, listener);\n }\n\n public emit<K extends keyof PlaybackEvents>(event: K, data: PlaybackEvents[K]): void {\n this.eventEmitter.emit(event, data);\n }\n\n public async emitAsync<K extends keyof PlaybackEvents>(event: K, data: PlaybackEvents[K]): Promise<void> {\n return this.eventEmitter.emitAsync(event, data);\n }\n\n /**\n * Fades the volume to a target value, emitting fadeStart and fadeEnd events.\n */\n fadeTo(\n value: number,\n duration: number,\n type: FadeType = \"linear\",\n options?: { startTime?: number; startValue?: number },\n ): Promise<void> {\n this.emit(\"fadeStart\", { target: value, duration, type });\n return super.fadeTo(value, duration, type, options).then(() => {\n this.emit(\"fadeEnd\", undefined);\n });\n }\n\n /**\n * Cancels any in-progress fade, emitting fadeCancel if a fade was active.\n */\n cancelFade(): void {\n const wasFading = this._isFading;\n super.cancelFade();\n if (wasFading) {\n this.emit(\"fadeCancel\", undefined);\n }\n }\n\n cleanup(): void {\n for (const sendGain of this._sendGains.values()) {\n try {\n sendGain.disconnect();\n } catch {\n // The node may already have been disconnected externally.\n }\n }\n this._sendGains.clear();\n this._effectChain?.destroy();\n this._effectChain = undefined;\n this._effectContext = undefined;\n this.eventEmitter.removeAllListeners();\n super.cleanup();\n }\n}\n"],"mappings":";;;;;;AAcA,IAAsB,IAAtB,cAA2D,EAA4B,kBAAY,CAAa,CAAC,EAAE;CACjH;CACA;CACA;CAKA,6BAAiC,IAAI,IAAI;CACzC,SAAkC;CAClC;CACA,eAAyD,IAAI,EAAkC;CAE/F,YAAY,GAA2B;EAGrC,AAFA,MAAM,GACN,KAAK,SAAS,GACd,KAAK,sBAAsB,EAAO,uBAAuB;CAC3D;CAMA,IAAa,0BAAmC;EAC9C,OAAO,KAAK,WAAW,aAAa,KAAK,WAAW;CACtD;CAEA,wBAAkC,GAAkB,GAAyB;EAI3E,IAHA,KAAK,iBACF,EAAM,WACN,KAAK,OAAyD,SAC7D,KAAK,cAAc;GACrB,KAAK,aAAa,aAAa,GAAO,CAAM;GAC5C;EACF;EACA,KAAK,eAAe,IAAI,EAAY,GAAO,GAAQ,KAAK,YAAY,IAAI;CAC1E;CAGA,UAAU,GAA6C;EACrD,IAAI;GACF,OAAO,KAAK,kBAAkB,CAAM;EACtC,SAAS,GAAO;GACd,OAAO,QAAQ,OAAO,CAAK;EAC7B;CACF;CAGA,iBAAiB,GAA6C;EAC5D,OAAO,KAAK,kBAAkB,CAAM;CACtC;CAGA,iBAAiB,GAA6C;EAC5D,OAAO,KAAK,kBAAkB,IAAS,MAAW;GAChD,KAAK,SAAS,KAAK,CAA0B;EAC/C,CAAC;CACH;CAEA,kBAA0B,GAAyB,GAA2D;EAC5G,IAAI,CAAC,KAAK,gBAAgB,CAAC,KAAK,gBAC9B,MAAU,MAAM,sEAAsE;EAExF,IAAM,IAAQ,KAAK,cACb,IAAc,EAAM,QAAQ,GAC9B;EACJ,IAAI;GACF,IAAQ,EAA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./worklets.cjs"),n=require("./playOptions.cjs"),r=require("./spatialAutomation.cjs"),i=require("./basePlayback.cjs"),a=require("./bandGainStage.cjs"),o=require("./reflections.cjs");var s=class s extends i.BasePlayback{origin;context;loopCount=0;currentLoop=0;buffer;_offset=0;_startTime=0;_playbackRate=1;_clipRegion;_scheduledStop;_mediaPlayPromise;_cancelPrepareSeek;_mediaPreparationGate;_fadeInConfig;_fadeOutConfig;_loopEndCallback;_pitchFactor=1;_bandStage;_bandGains=c;_reflections;_rateRamp={start:0,end:0,from:1,to:1};_rateParamRamped;constructor(e,t,n){super(e),this.origin=e,this.context=e.context,this.loopCount=e.loopCount,this.setPanType(e.panType,e.context),this.source=t,`buffer`in t&&t.buffer&&(this.buffer=t.buffer),this.setupSourceNode(t),this.setGainNode(n),this.setEffectChainEndpoints(this.source,this.panner),this.panner.connect(this.gainNode)}setupSourceNode(e){if(`mediaElement`in e&&e.mediaElement)e.mediaElement.onended=this.loopEnded;else if(`onended`in e)e.onended=()=>{this.source===e&&this.loopEnded()};else throw Error(`Unsupported source type`)}get bandGains(){return this._bandGains}setBandGains(t,n=50){this.assertNotCleanedUp();let r=e.validateBandGains(t,`setBandGains`);if(l(n,`Band-gain`),!this._bandStage){if(r.every(e=>e===1)){this._bandGains=r;return}this._bandStage=new a.BandGainStage(this.context),this.setEffectChainEndpoints(this.source,this.panner)}this._bandStage.setGains(r,n),this._bandGains=r}get reflections(){return this._reflections?.images??[]}setReflections(e,t=50){this.assertNotCleanedUp();let n=o.validateReflectionImages(e);if(l(t,`Reflection`),n.length===0){if(!this._reflections)return;let e=this._reflections;this._reflections=void 0,this.setEffectChainEndpoints(this.source,this.panner),e.destroy();return}if(!this._reflections){let e=this.panType===`HRTF`?this.threeDOptions.panningModel:`equalpower`;this._reflections=new o.Reflections(this.context,this.gainNode,e),this.setEffectChainEndpoints(this.source,this.panner)}this._reflections.setImages(n,t)}setEffectChainEndpoints(e,t){let n=t;this._bandStage&&(this._bandStage.setOutput(t),n=this._bandStage.input),this._reflections&&(this._reflections.setDirect(n),n=this._reflections.input),super.setEffectChainEndpoints(this._mediaPreparationGate??e,n)}get duration(){if(this.origin.region)return this.origin.region.duration;if(!this.source)throw Error(`Cannot get duration of a sound that has been cleaned up`);return`mediaElement`in this.source&&this.source.mediaElement?this.source.mediaElement.duration:this.buffer&&this.buffer.duration||NaN}get playbackRate(){return this._playbackRate}get supportsClipLoop(){return!!this.source&&`buffer`in this.source&&!!this.buffer}setLoopRegion(e,t){if(this.assertNotCleanedUp(),!this.supportsClipLoop)throw new DOMException(`Clip bounds require a decoded buffer`,`NotSupportedError`);if(this._state===`playing`)throw Error(`Pause playback before configuring clip bounds`);if(!this.buffer||!Number.isFinite(e)||!Number.isFinite(t)||e<0||t>this.duration||(t-e)*this.buffer.sampleRate+2**-52*Math.max(1,Math.abs(e*this.buffer.sampleRate),Math.abs(t*this.buffer.sampleRate))*4<1||Math.round(t*this.buffer.sampleRate)<=Math.round(e*this.buffer.sampleRate))throw RangeError(`Clip bounds must span at least one sample within the Sound duration`);if(this._offset>=t)throw RangeError(`The current offset must precede the clip end`);if(this.loopCount!==0&&this.loopCount!==`infinite`)throw Error(`Clip bounds support only zero or infinite loop count`);if(this._fadeInConfig?.perLoop)throw Error(`Per-loop fades are not supported with clip bounds`);this._clipRegion={start:e,end:t},this.configureBufferLoopSource()}scheduleStop(e){if(this.assertNotCleanedUp(),!this.supportsClipLoop||!this.source||!(`stop`in this.source))throw new DOMException(`Scheduled ends require a decoded buffer`,`NotSupportedError`);if(!Number.isFinite(e)||e<0)throw RangeError(`End time must be finite and non-negative`);if(this._state!==`playing`)throw Error(`Start the buffer before scheduling its end`);if(this.loopCount!==0&&this.loopCount!==`infinite`)throw Error(`Scheduled ends do not support legacy numeric repeats`);if(this._fadeOutConfig)throw Error(`An absolute end cannot use an ended-time fade-out`);let t=Math.max(this.context.currentTime,e);this.source.stop(t),this._scheduledStop={source:this.source,at:t}}_validateLoopCount(e){if(this._clipRegion&&e!==0&&e!==`infinite`)throw Error(`Clip bounds support only zero or infinite loop count`);if(this._scheduledStop&&e!==0&&e!==`infinite`)throw Error(`Scheduled ends do not support legacy numeric repeats`)}get volume(){return super.volume}set volume(e){super.volume=e,this.emit(`volumeChange`,e)}set playbackRate(e){this.setPlaybackRate(e,0)}setPlaybackRate(e,t=0){if(!(e>0)||!Number.isFinite(e))throw Error(`Playback rate must be greater than 0`);l(t,`Playback-rate`);let n=this.context.currentTime,r=!!this.source&&`mediaElement`in this.source;this._state===`playing`&&!r&&(this._offset=this.regionRelativeOffset(this._offset+this.elapsedSourceTime(n)),n>=this._startTime&&(this._startTime=n));let i=r?0:t/1e3;this._rateRamp={start:n,end:n+i,from:i>0?this.rateAt(n):e,to:e},this._playbackRate=e,this.applyRateToSource()}rateAt(e){let{start:t,end:n,from:r,to:i}=this._rateRamp;return e>=n?i:e<=t?r:r+(i-r)*(e-t)/(n-t)}elapsedSourceTime(e){let t=this._startTime;if(e<=t)return 0;let{start:n,end:r}=this._rateRamp,i=[t,Math.min(Math.max(n,t),e),Math.min(Math.max(r,t),e),e],a=0;for(let e=0;e<i.length-1;e++){let t=i[e],n=i[e+1];n>t&&(a+=(this.rateAt(t)+this.rateAt(n))/2*(n-t))}return a}applyRateToSource(){if(this.source){if(`playbackRate`in this.source){let e=this.source.playbackRate,t=this.context.currentTime,{end:n,to:r}=this._rateRamp;n>t?(e.cancelScheduledValues(t),e.setValueAtTime(this.rateAt(t),t),e.linearRampToValueAtTime(r,n),this._rateParamRamped=e):(this._rateParamRamped===e&&e.cancelScheduledValues(t),this._rateParamRamped=void 0,e.value=r)}`mediaElement`in this.source&&this.source.mediaElement&&(this.source.mediaElement.playbackRate=this._playbackRate)}}loopEnded=()=>{if(!(!this.source||this._state!==`playing`)){if(this._scheduledStop?.source===this.source){let e=this.source;this._scheduledStop=void 0,`onended`in e&&(e.onended=null);try{this.emit(`ended`,void 0)}finally{this.source===e&&this._state===`playing`&&this.stop(),this.source===e&&this.state===`stopped`&&this.removeFromOrigin()}return}if(`mediaElement`in this.source&&this._mediaPlayPromise){this._mediaPlayPromise.then(()=>this._runLoopEnded());return}this._runLoopEnded()}};_runLoopEnded(){if(!this.source||this._state!==`playing`)return;let e=this.source;if(this.currentLoop++,this.loopCount!==`infinite`&&this.currentLoop>this.loopCount){if(this.emit(`ended`,void 0),this.source!==e||this._state!==`playing`)return;this._fadeOutConfig?this.fadeOut(this._fadeOutConfig.duration,this._fadeOutConfig.type).then(()=>{this._state!==`stopped`&&this.source===e&&(this.stop(),this.source===e&&this.state===`stopped`&&this.removeFromOrigin())}):(this.stop(),this.source===e&&this.state===`stopped`&&this.removeFromOrigin())}else{if(this._loopEndCallback?.(),this.source!==e||this._state!==`playing`)return;this.seek(0),this._state!==`playing`&&this.source&&!(`mediaElement`in this.source)&&this.play(),this._fadeInConfig?.perLoop&&this.gainNode&&(this.gainNode.gain.setValueAtTime(1e-4,this.gainNode.context.currentTime),this.fadeTo(this._fadeInConfig.targetVolume,this._fadeInConfig.duration,this._fadeInConfig.type))}}play(e){if(!this.source)throw Error(`Cannot play a sound that has been cleaned up`);if(n.validatePlayOptions(e,this.panType,`mediaElement`in this.source?`media`:`buffer`),e?.loopCount!==void 0&&this._validateLoopCount(e.loopCount),this._clipRegion&&e?.fadeInPerLoop)throw Error(`Per-loop fades are not supported with clip bounds`);if(this._scheduledStop&&e?.fadeOut!==void 0)throw Error(`An absolute end cannot use an ended-time fade-out`);if(this._state===`playing`)return[this];this._cancelPrepareSeek?.(),this._scheduledStop=void 0,n.applyPlayOptions(this,this.context,e),e?.playbackRate!==void 0&&(this.playbackRate=e.playbackRate),e?.loopCount!==void 0&&this.loop(e.loopCount),e?.fadeIn!==void 0&&this.fadeIn(e.fadeIn,e.fadeType,{perLoop:e.fadeInPerLoop,startTime:e.at}),e?.fadeOut!==void 0&&this.configureFadeOut(e.fadeOut,e.fadeType);let t=this._state===`paused`;this._state===`stopped`&&(this.currentLoop=0);let r=this.origin._playbackGeneration;try{let n;if(this._state===`paused`){if(`mediaElement`in this.source&&this.source.mediaElement)this.source.mediaElement.currentTime!==this._offset&&(this.source.mediaElement.currentTime=this._offset),n=this.source.mediaElement.play();else if(this.recreateSource(),`start`in this.source&&!this.startBufferSource(e?.at??0))return[this]}else if(`mediaElement`in this.source&&this.source.mediaElement)this.source.mediaElement.currentTime!==this._offset&&(this.source.mediaElement.currentTime=this._offset),n=this.source.mediaElement.play();else if(`start`in this.source&&(this.recreateSource(),!this.startBufferSource(e?.at??0)))return[this];if(n){let e=n.then(()=>{if(!(this._mediaPlayPromise!==e||!this.source)){if(this.origin._playbackGeneration!==r){`mediaElement`in this.source&&this.source.mediaElement.pause();return}this._startTime=this.context.currentTime,this.emitPlayStarted(t)}},t=>{this._mediaPlayPromise!==e||this.origin._playbackGeneration!==r||this.emitAsync(`error`,{error:t,errorType:`source`,timestamp:Date.now(),recoverable:!0})}).finally(()=>{this._mediaPlayPromise===e&&(this._mediaPlayPromise=void 0)});this._mediaPlayPromise=e}else this._startTime=Math.max(e?.at??this.context.currentTime,this.context.currentTime),this.emitPlayStarted(t);return[this]}catch(e){throw this.emitAsync(`error`,{error:e,errorType:`source`,timestamp:Date.now(),recoverable:!0}),e}}emitPlayStarted(e){this._mediaPreparationGate?.gain.setValueAtTime(1,this.context.currentTime),this._state===`stopped`&&!this.origin.playbacks.includes(this)&&this.origin._readmitPlayback(this),super.emitPlayStarted(e)}pause(){if(!(!this.source||this._state!==`playing`)){if(this._mediaPlayPromise=void 0,this._scheduledStop=void 0,`mediaElement`in this.source&&this.source.mediaElement)this._mediaPreparationGate?.gain.setValueAtTime(0,this.context.currentTime),this.source.mediaElement.pause(),this._offset=this.source.mediaElement.currentTime;else{let e=this.elapsedSourceTime(this.context.currentTime);this._offset=this.regionRelativeOffset(this._offset+e),`stop`in this.source&&this.source.stop()}this.emitPaused()}}stop(){if(!this.source)throw Error(`Cannot stop a sound that has been cleaned up`);this._cancelPrepareSeek?.(),this._scheduledStop=void 0,this._mediaPreparationGate?.gain.setValueAtTime(0,this.context.currentTime);let e=this._mediaPlayPromise!==void 0;this._mediaPlayPromise=void 0,!(!e&&(this._state===`stopped`||this._state===`unplayed`))&&(this.cancelFade(),`stop`in this.source&&this._state===`playing`&&this.source.stop(),`mediaElement`in this.source&&this.source.mediaElement&&(this.source.mediaElement.pause(),this.source.mediaElement.currentTime=0),this._offset=0,this._startTime=0,this.emitStopped())}fadeIn(e,t,n){if(n?.perLoop&&this._clipRegion)throw Error(`Per-loop fades are not supported with clip bounds`);return n?.perLoop&&(this._fadeInConfig={duration:e,type:t??`linear`,perLoop:!0,targetVolume:this.gainNode.gain.value}),super.fadeIn(e,t,{startTime:n?.startTime})}configureFadeOut(e,t){if(this._scheduledStop)throw Error(`An absolute end cannot use an ended-time fade-out`);this._fadeOutConfig={duration:e,type:t??`linear`}}stopWithFade(e,t){return this.fadeOut(e,t).then(()=>{this._state!==`stopped`&&this.source&&this.stop()})}async prepareSeek(e,t={}){if(this.assertNotCleanedUp(),!Number.isFinite(e)||e<0)throw RangeError(`Seek time must be finite and non-negative`);let n=t.timeoutMs??1e4;if(!Number.isFinite(n)||n<=0||n>2147483647)throw RangeError(`Seek timeout must be positive and at most 2147483647 milliseconds`);if(t.signal?.aborted)throw new DOMException(`Seek preparation aborted`,`AbortError`);if(this._state===`playing`||this._mediaPlayPromise)throw Error(`Pause playback before preparing a seek`);this._cancelPrepareSeek?.();let r=this.source;if(!(`mediaElement`in r)){if(this._clipRegion&&e>=this._clipRegion.end)throw RangeError(`Seek time must precede the clip end`);if(!Number.isFinite(this.duration)||e>this.duration)throw RangeError(`Seek time exceeds duration`);this._offset=e,this.emit(`seek`,e);return}let i=r.mediaElement;if(!i.paused)throw Error(`Pause playback before preparing a seek`);if(!this._mediaPreparationGate){let e=this.context.createGain();e.gain.value=0,this._mediaPreparationGate=e,this.setEffectChainEndpoints(r,this.panner),r.connect(e)}this._mediaPreparationGate.gain.setValueAtTime(0,this.context.currentTime),await new Promise((r,a)=>{let o=!1,s=!1,c=!1,l=[`loadedmetadata`,`durationchange`,`progress`,`loadeddata`,`canplay`,`seeked`,`error`,`emptied`,`play`],u=n=>{if(!o){o=!0,clearTimeout(p);for(let e of l)i.removeEventListener(e,f);t.signal?.removeEventListener(`abort`,d),this._cancelPrepareSeek===d&&(this._cancelPrepareSeek=void 0),n===void 0?(this._offset=e,r()):a(n)}},d=()=>u(new DOMException(`Seek preparation aborted`,`AbortError`)),f=t=>{if(!o)try{if(i.error||t?.type===`error`){u(Error(i.error?.message||`Media failed during seek preparation`));return}if(t?.type===`emptied`&&s||t?.type===`play`){d();return}if(i.readyState<1)return;if(!Number.isFinite(i.duration)){u(new DOMException(`Seek preparation requires finite-duration media`,`NotSupportedError`));return}if(e>i.duration){u(RangeError(`Seek time exceeds duration`));return}if(s)t?.type===`seeked`&&(c=!1);else{let t=!1;for(let n=0;n<i.seekable.length;n++)e>=i.seekable.start(n)&&e<=i.seekable.end(n)&&(t=!0);if(!t)return;s=!0,c=i.seeking||i.currentTime!==e,i.currentTime!==e&&(i.currentTime=e)}!c&&!i.seeking&&i.readyState>=2&&Math.abs(i.currentTime-e)<.001&&u()}catch(e){u(e)}},p=setTimeout(()=>u(new DOMException(`Seek preparation timed out`,`TimeoutError`)),n);this._cancelPrepareSeek=d;for(let e of l)i.addEventListener(e,f);t.signal?.addEventListener(`abort`,d,{once:!0}),f()}),this.emit(`seek`,e)}seek(e){if(!this.source||!this.gainNode||!this.panner)throw Error(`Cannot seek a sound that has been cleaned up`);if(!Number.isFinite(e)||e<0||this.origin.region!==void 0&&e>this.duration)throw Error(`Invalid time value for seek`);if(this._clipRegion&&e>=this._clipRegion.end)throw RangeError(`Seek time must precede the clip end`);if(this._cancelPrepareSeek?.(),this.origin.soundType===`streaming`&&`mediaElement`in this.source&&(this.source.mediaElement.seekable?.length??0)===0)throw this.source.mediaElement.duration===1/0?Error(`Live media-element streams do not expose a seekable range`):Error(`Media-element stream does not currently expose a seekable range`);let t=this._state===`playing`;t&&this.pause(),this._offset=e,`mediaElement`in this.source&&this.source.mediaElement&&(this.source.mediaElement.currentTime=e),t&&this.play(),this.emit(`seek`,e)}get currentTime(){if(this._state===`playing`){if(this.source&&`mediaElement`in this.source)return this.source.mediaElement.currentTime;let e=this.elapsedSourceTime(this.context.currentTime),t=this._offset+e;return this.regionRelativeOffset(t)}else return this._offset}removeFromOrigin(){let e=this.origin.playbacks.indexOf(this);e!==-1&&this.origin.playbacks.splice(e,1)}recreateSource(){if(!this.buffer||!this.panner||!this.context||!this.gainNode)throw Error(`Cannot recreate source of a sound that has been cleaned up`);try{this.source&&(!(`mediaElement`in this.source)&&`onended`in this.source&&(this.source.onended=null),this.source.disconnect()),this.source=this.context.createBufferSource(),this._scheduledStop=void 0,this.source.buffer=this.buffer,this.setEffectChainEndpoints(this.source,this.panner),this.setupSourceNode(this.source),this.applyRateToSource(),this.configureBufferLoopSource()}catch(e){throw this.emitAsync(`error`,{error:e,errorType:`source`,timestamp:Date.now(),recoverable:!1}),e}}set sourceLoop(e){if(!this.source)throw Error(`Cannot set loop on a sound that has been cleaned up`);`loop`in this.source&&(this.source.loop=e),`mediaElement`in this.source&&this.source.mediaElement&&(this.source.mediaElement.loop=e)}cleanup(){if(this._scheduledStop=void 0,this._cancelPrepareSeek?.(),this._mediaPreparationGate?.gain.setValueAtTime(0,this.context.currentTime),this._mediaPlayPromise=void 0,this.source){if(`mediaElement`in this.source&&this.source.mediaElement){let e=this.source.mediaElement;e.pause();try{e.currentTime=0}catch{}e.loop=!1,e.onended=null,e.src=``,e.load()}else `onended`in this.source&&(this.source.onended=null,`stop`in this.source&&this._state===`playing`&&this.source.stop());this._offset=0,this._startTime=0,this.markStopped(),this.currentLoop=0,this.source.disconnect(),this.source=void 0,super.cleanup(),this._mediaPreparationGate?.disconnect(),this._mediaPreparationGate=void 0,this._bandStage?.destroy(),this._bandStage=void 0,this._reflections?.destroy(),this._reflections=void 0}}assertNotCleanedUp(){if(!this.source||!this.gainNode||!this.panner)throw Error(`Cannot perform operation on a sound that has been cleaned up`)}addFilter(e){this.assertNotCleanedUp(),super.addFilter(e)}removeFilter(e){this.assertNotCleanedUp(),super.removeFilter(e)}loop(e){if(!this.source)throw Error(`Cannot loop a sound that has been cleaned up`);if(e!==void 0){this._validateLoopCount(e);let t=this.loopCount,n=e===`infinite`?`infinite`:Math.max(0,e),r=t===`infinite`!=(n===`infinite`);if(r&&(this.origin.region||this._clipRegion)&&this._state===`playing`&&`loop`in this.source&&`stop`in this.source){let e=Math.max(this._startTime,this.context.currentTime),r=this.elapsedSourceTime(this.context.currentTime);return this._offset=this.regionRelativeOffset(this.regionRelativeOffset(this._offset+r,t),n),`onended`in this.source&&(this.source.onended=null),this.source.stop(),this._scheduledStop=void 0,this.loopCount=n,this.currentLoop=0,this._startTime=e,this.recreateSource(),this.startBufferSource(e),this.loopCount}if(r&&this._state===`playing`&&`buffer`in this.source){let e=this.elapsedSourceTime(this.context.currentTime);this._offset=this.regionRelativeOffset(this._offset+e,t),this._startTime=Math.max(this._startTime,this.context.currentTime)}this.loopCount=n,this.currentLoop=0}if(`mediaElement`in this.source&&this.source.mediaElement){let e=this.source.mediaElement;e.loop=this.loopCount===`infinite`}else if(`loop`in this.source)this.configureBufferLoopSource();else throw Error(`Unsupported source type`);return this.loopCount}configureBufferLoopSource(){!this.source||!(`loop`in this.source)||(this.source.loop=this.loopCount===`infinite`,this.source.buffer&&(this.source.loopEnd=this._clipRegion?(this.origin.region?.start??0)+this._clipRegion.end:this.origin.region?this.origin.region.start+this.origin.region.duration:this.source.buffer.duration,this.source.loopStart=(this.origin.region?.start??0)+(this._clipRegion?.start??0)))}regionRelativeOffset(e,t=this.loopCount){if(this._clipRegion){let{start:n,end:r}=this._clipRegion;return t===`infinite`&&e>=r?n+(e-n)%(r-n):Math.min(r,e)}let n=this.origin.region;return n?t===`infinite`?e%n.duration:Math.min(n.duration,e):t===`infinite`&&this.buffer&&this.buffer.duration>0?e%this.buffer.duration:e}startBufferSource(e){if(!this.source||!(`start`in this.source))return!1;let t=this.origin.region;if(this._clipRegion){if(this._offset>=this._clipRegion.end)return!1;let n=(t?.start??0)+this._offset;return this.loopCount===`infinite`?this.source.start(e,n):this.source.start(e,n,this._clipRegion.end-this._offset),!0}if(!t)return this.source.start(e,this._offset),!0;if(this._offset===t.duration)return!1;let n=t.start+this._offset;return this.loopCount===`infinite`?this.source.start(e,n):this.source.start(e,n,t.duration-this._offset),!0}async setPitchShift(e){if(this.assertNotCleanedUp(),!Number.isFinite(e)||e<=0)throw Error(`Pitch-shift factor must be greater than 0`);this._pitchFactor=e;let n=this._effectChain;if(!n)throw Error(`Cannot pitch-shift a playback before its effect chain is initialized`);let r=n.nodes.find(e=>{let t=e.parameters;return t&&typeof t.get==`function`&&t.get(`pitchFactor`)!==void 0});if(e===1){r&&n.remove(r);return}if(!r){let e=this.origin.cacophony;if(!e)throw Error(`Cannot pitch-shift a playback whose Sound has no Cacophony instance`);r=await e.buildWorkletEffect(t.WORKLETS.phaseVocoder,{},this.context),n.add(r)}let i=r.parameters?.get(`pitchFactor`);i&&(i.value=e)}get pitchShift(){return this._pitchFactor}get outputNode(){if(!this.gainNode)throw Error(`Cannot access output node of a playback that has been cleaned up`);return this.gainNode}connect(e){return this.outputNode.connect(e)}disconnect(e){e?this.outputNode.disconnect(e):this.outputNode.disconnect()}clone(e={}){if(!this.source||!this.gainNode||!this.context)throw Error(`Cannot clone a sound that has been cleaned up`);if(this._scheduledStop)throw Error(`Cannot clone a playback with an armed absolute end`);this._validateLoopCount(e.loopCount??this.loopCount),r.validateSpatialSmoothingTau(e.spatialSmoothingTau??this.spatialSmoothingTau);let t=e.panType??this.panType;n.validateSpatialOptions(e,t);let i=this.context.createGain();i.connect(this.origin._resolveRouteTargetNode());let a;if(`buffer`in this.source&&this.source.buffer)a=this.context.createBufferSource(),a.buffer=this.source.buffer;else if(`mediaElement`in this.source&&this.source.mediaElement){if(!this.context.createMediaElementSource)throw Error(`Media element sources are not supported on this audio context.`);let e=this.source.mediaElement.cloneNode(!0);a=this.context.createMediaElementSource(e)}else throw Error(`Unsupported source type`);let o=e.loopCount===void 0?this.loopCount:e.loopCount,c=new s(this.origin,a,i);return c.loopCount=o,c._clipRegion=this._clipRegion&&{...this._clipRegion},c.currentLoop=this.currentLoop,c.setPanType(t,this.context),c.spatialSmoothingTau=e.spatialSmoothingTau??this.spatialSmoothingTau,t===`HRTF`?(this.panType===`HRTF`&&(c.threeDOptions=this.threeDOptions),e.threeDOptions!==void 0&&(c.threeDOptions=e.threeDOptions),e.position!==void 0&&(c.position=e.position)):c.stereoPan=e.stereoPan??this.stereoPan??0,c.volume=this.volume,c.playbackRate=this._playbackRate,c._offset=this._clipRegion&&this._state===`playing`?this.currentTime:this._offset,c.setBandGains(this._bandGains,0),this._reflections&&c.setReflections(this._reflections.images,0),this._fadeInConfig&&(c._fadeInConfig={...this._fadeInConfig}),this._fadeOutConfig&&(c._fadeOutConfig={...this._fadeOutConfig}),this._state===`paused`?c.markPaused():this._state===`stopped`&&c.markStopped(),this._filters.forEach(e=>{let t=this.context.createBiquadFilter();t.type=e.type,t.frequency.value=e.frequency.value,t.Q.value=e.Q.value,t.gain.value=e.gain.value,c.addFilter(t)}),this._pitchFactor!==1&&c.setPitchShift(this._pitchFactor).catch(()=>{}),this._state===`playing`&&c.play(),this.origin.playbacks.push(c),c}},c=Object.freeze(Array(8).fill(1));function l(e,t){if(!Number.isFinite(e)||e<0)throw RangeError(`${t} duration must be finite and non-negative`)}exports.Playback=s;
|
|
1
|
+
const e=require("./bandGains.cjs"),t=require("./worklets.cjs"),n=require("./playOptions.cjs"),r=require("./spatialAutomation.cjs"),i=require("./basePlayback.cjs"),a=require("./bandGainStage.cjs"),o=require("./reflections.cjs");var s=class s extends i.BasePlayback{origin;context;loopCount=0;currentLoop=0;buffer;_offset=0;_startTime=0;_playbackRate=1;_clipRegion;_scheduledStop;_mediaPlayPromise;_cancelPrepareSeek;_mediaPreparationGate;_fadeInConfig;_fadeOutConfig;_loopEndCallback;_pitchFactor=1;_bandStage;_bandGains=c;_reflections;_volumeTarget;_directTap;_output;_rateRamp={start:0,end:0,from:1,to:1};_rateParamRamped;constructor(e,t,n){super(e),this.origin=e,this.context=e.context,this.loopCount=e.loopCount,this.setPanType(e.panType,e.context),this.source=t,`buffer`in t&&t.buffer&&(this.buffer=t.buffer),this.setupSourceNode(t),this.setGainNode(n),this._output=this.context.createGain(),this._directTap=this.context.createGain(),this._directTap.connect(this._output),this.setEffectChainEndpoints(this.source,this.panner),this.panner.connect(this._directTap)}get pannerDestination(){return this._directTap}get _sendTap(){if(!this._directTap)throw Error(`Cannot access the send tap of a playback that has been cleaned up`);return this._directTap}setupSourceNode(e){if(`mediaElement`in e&&e.mediaElement)e.mediaElement.onended=this.loopEnded;else if(`onended`in e)e.onended=()=>{this.source===e&&this.loopEnded()};else throw Error(`Unsupported source type`)}get bandGains(){return this._bandGains}setBandGains(t,n=50){this.assertNotCleanedUp();let r=e.validateBandGains(t,`setBandGains`);if(l(n,`Band-gain`),!this._bandStage){if(r.every(e=>e===1)){this._bandGains=r;return}this._bandStage=new a.BandGainStage(this.context),this.setEffectChainEndpoints(this.source,this.panner)}this._bandStage.setGains(r,n),this._bandGains=r}get reflections(){return this._reflections?.images??[]}setReflections(e,t=50){this.assertNotCleanedUp();let n=o.validateReflectionImages(e);if(l(t,`Reflection`),n.length===0){if(!this._reflections)return;let e=this._reflections;this._reflections=void 0,this.setEffectChainEndpoints(this.source,this.panner),e.destroy();return}if(!this._reflections){let e=this.panType===`HRTF`?this.threeDOptions.panningModel:`equalpower`;this._reflections=new o.Reflections(this.context,this._output,e),this.setEffectChainEndpoints(this.source,this.panner)}this._reflections.setImages(n,t)}setEffectChainEndpoints(e,t){let n=t;this._bandStage&&(this._bandStage.setOutput(t),n=this._bandStage.input),this._reflections&&(this._reflections.setDirect(n),n=this._reflections.input);let r=this.gainNode;this._volumeTarget!==n&&(this._volumeTarget&&r.disconnect(this._volumeTarget),r.connect(n),this._volumeTarget=n),super.setEffectChainEndpoints(this._mediaPreparationGate??e,r)}get duration(){if(this.origin.region)return this.origin.region.duration;if(!this.source)throw Error(`Cannot get duration of a sound that has been cleaned up`);return`mediaElement`in this.source&&this.source.mediaElement?this.source.mediaElement.duration:this.buffer&&this.buffer.duration||NaN}get playbackRate(){return this._playbackRate}get supportsClipLoop(){return!!this.source&&`buffer`in this.source&&!!this.buffer}setLoopRegion(e,t){if(this.assertNotCleanedUp(),!this.supportsClipLoop)throw new DOMException(`Clip bounds require a decoded buffer`,`NotSupportedError`);if(this._state===`playing`)throw Error(`Pause playback before configuring clip bounds`);if(!this.buffer||!Number.isFinite(e)||!Number.isFinite(t)||e<0||t>this.duration||(t-e)*this.buffer.sampleRate+2**-52*Math.max(1,Math.abs(e*this.buffer.sampleRate),Math.abs(t*this.buffer.sampleRate))*4<1||Math.round(t*this.buffer.sampleRate)<=Math.round(e*this.buffer.sampleRate))throw RangeError(`Clip bounds must span at least one sample within the Sound duration`);if(this._offset>=t)throw RangeError(`The current offset must precede the clip end`);if(this.loopCount!==0&&this.loopCount!==`infinite`)throw Error(`Clip bounds support only zero or infinite loop count`);if(this._fadeInConfig?.perLoop)throw Error(`Per-loop fades are not supported with clip bounds`);this._clipRegion={start:e,end:t},this.configureBufferLoopSource()}scheduleStop(e){if(this.assertNotCleanedUp(),!this.supportsClipLoop||!this.source||!(`stop`in this.source))throw new DOMException(`Scheduled ends require a decoded buffer`,`NotSupportedError`);if(!Number.isFinite(e)||e<0)throw RangeError(`End time must be finite and non-negative`);if(this._state!==`playing`)throw Error(`Start the buffer before scheduling its end`);if(this.loopCount!==0&&this.loopCount!==`infinite`)throw Error(`Scheduled ends do not support legacy numeric repeats`);if(this._fadeOutConfig)throw Error(`An absolute end cannot use an ended-time fade-out`);let t=Math.max(this.context.currentTime,e);this.source.stop(t),this._scheduledStop={source:this.source,at:t}}_validateLoopCount(e){if(this._clipRegion&&e!==0&&e!==`infinite`)throw Error(`Clip bounds support only zero or infinite loop count`);if(this._scheduledStop&&e!==0&&e!==`infinite`)throw Error(`Scheduled ends do not support legacy numeric repeats`)}get volume(){return super.volume}set volume(e){super.volume=e,this.emit(`volumeChange`,e)}set playbackRate(e){this.setPlaybackRate(e,0)}setPlaybackRate(e,t=0){if(!(e>0)||!Number.isFinite(e))throw Error(`Playback rate must be greater than 0`);l(t,`Playback-rate`);let n=this.context.currentTime,r=!!this.source&&`mediaElement`in this.source;this._state===`playing`&&!r&&(this._offset=this.regionRelativeOffset(this._offset+this.elapsedSourceTime(n)),n>=this._startTime&&(this._startTime=n));let i=r?0:t/1e3;this._rateRamp={start:n,end:n+i,from:i>0?this.rateAt(n):e,to:e},this._playbackRate=e,this.applyRateToSource()}rateAt(e){let{start:t,end:n,from:r,to:i}=this._rateRamp;return e>=n?i:e<=t?r:r+(i-r)*(e-t)/(n-t)}elapsedSourceTime(e){let t=this._startTime;if(e<=t)return 0;let{start:n,end:r}=this._rateRamp,i=[t,Math.min(Math.max(n,t),e),Math.min(Math.max(r,t),e),e],a=0;for(let e=0;e<i.length-1;e++){let t=i[e],n=i[e+1];n>t&&(a+=(this.rateAt(t)+this.rateAt(n))/2*(n-t))}return a}applyRateToSource(){if(this.source){if(`playbackRate`in this.source){let e=this.source.playbackRate,t=this.context.currentTime,{end:n,to:r}=this._rateRamp;n>t?(e.cancelScheduledValues(t),e.setValueAtTime(this.rateAt(t),t),e.linearRampToValueAtTime(r,n),this._rateParamRamped=e):(this._rateParamRamped===e&&e.cancelScheduledValues(t),this._rateParamRamped=void 0,e.value=r)}`mediaElement`in this.source&&this.source.mediaElement&&(this.source.mediaElement.playbackRate=this._playbackRate)}}loopEnded=()=>{if(!(!this.source||this._state!==`playing`)){if(this._scheduledStop?.source===this.source){let e=this.source;this._scheduledStop=void 0,`onended`in e&&(e.onended=null);try{this.emit(`ended`,void 0)}finally{this.source===e&&this._state===`playing`&&this.stop(),this.source===e&&this.state===`stopped`&&this.removeFromOrigin()}return}if(`mediaElement`in this.source&&this._mediaPlayPromise){this._mediaPlayPromise.then(()=>this._runLoopEnded());return}this._runLoopEnded()}};_runLoopEnded(){if(!this.source||this._state!==`playing`)return;let e=this.source;if(this.currentLoop++,this.loopCount!==`infinite`&&this.currentLoop>this.loopCount){if(this.emit(`ended`,void 0),this.source!==e||this._state!==`playing`)return;this._fadeOutConfig?this.fadeOut(this._fadeOutConfig.duration,this._fadeOutConfig.type).then(()=>{this._state!==`stopped`&&this.source===e&&(this.stop(),this.source===e&&this.state===`stopped`&&this.removeFromOrigin())}):(this.stop(),this.source===e&&this.state===`stopped`&&this.removeFromOrigin())}else{if(this._loopEndCallback?.(),this.source!==e||this._state!==`playing`)return;this.seek(0),this._state!==`playing`&&this.source&&!(`mediaElement`in this.source)&&this.play(),this._fadeInConfig?.perLoop&&this.gainNode&&(this.gainNode.gain.setValueAtTime(1e-4,this.gainNode.context.currentTime),this.fadeTo(this._fadeInConfig.targetVolume,this._fadeInConfig.duration,this._fadeInConfig.type))}}play(e){if(!this.source)throw Error(`Cannot play a sound that has been cleaned up`);if(n.validatePlayOptions(e,this.panType,`mediaElement`in this.source?`media`:`buffer`),e?.loopCount!==void 0&&this._validateLoopCount(e.loopCount),this._clipRegion&&e?.fadeInPerLoop)throw Error(`Per-loop fades are not supported with clip bounds`);if(this._scheduledStop&&e?.fadeOut!==void 0)throw Error(`An absolute end cannot use an ended-time fade-out`);if(this._state===`playing`)return[this];this._cancelPrepareSeek?.(),this._scheduledStop=void 0,n.applyPlayOptions(this,this.context,e),e?.playbackRate!==void 0&&(this.playbackRate=e.playbackRate),e?.loopCount!==void 0&&this.loop(e.loopCount),e?.fadeIn!==void 0&&this.fadeIn(e.fadeIn,e.fadeType,{perLoop:e.fadeInPerLoop,startTime:e.at}),e?.fadeOut!==void 0&&this.configureFadeOut(e.fadeOut,e.fadeType);let t=this._state===`paused`;this._state===`stopped`&&(this.currentLoop=0);let r=this.origin._playbackGeneration;try{let n;if(this._state===`paused`){if(`mediaElement`in this.source&&this.source.mediaElement)this.source.mediaElement.currentTime!==this._offset&&(this.source.mediaElement.currentTime=this._offset),n=this.source.mediaElement.play();else if(this.recreateSource(),`start`in this.source&&!this.startBufferSource(e?.at??0))return[this]}else if(`mediaElement`in this.source&&this.source.mediaElement)this.source.mediaElement.currentTime!==this._offset&&(this.source.mediaElement.currentTime=this._offset),n=this.source.mediaElement.play();else if(`start`in this.source&&(this.recreateSource(),!this.startBufferSource(e?.at??0)))return[this];if(n){let e=n.then(()=>{if(!(this._mediaPlayPromise!==e||!this.source)){if(this.origin._playbackGeneration!==r){`mediaElement`in this.source&&this.source.mediaElement.pause();return}this._startTime=this.context.currentTime,this.emitPlayStarted(t)}},t=>{this._mediaPlayPromise!==e||this.origin._playbackGeneration!==r||this.emitAsync(`error`,{error:t,errorType:`source`,timestamp:Date.now(),recoverable:!0})}).finally(()=>{this._mediaPlayPromise===e&&(this._mediaPlayPromise=void 0)});this._mediaPlayPromise=e}else this._startTime=Math.max(e?.at??this.context.currentTime,this.context.currentTime),this.emitPlayStarted(t);return[this]}catch(e){throw this.emitAsync(`error`,{error:e,errorType:`source`,timestamp:Date.now(),recoverable:!0}),e}}emitPlayStarted(e){this._mediaPreparationGate?.gain.setValueAtTime(1,this.context.currentTime),this._state===`stopped`&&!this.origin.playbacks.includes(this)&&this.origin._readmitPlayback(this),super.emitPlayStarted(e)}pause(){if(!(!this.source||this._state!==`playing`)){if(this._mediaPlayPromise=void 0,this._scheduledStop=void 0,`mediaElement`in this.source&&this.source.mediaElement)this._mediaPreparationGate?.gain.setValueAtTime(0,this.context.currentTime),this.source.mediaElement.pause(),this._offset=this.source.mediaElement.currentTime;else{let e=this.elapsedSourceTime(this.context.currentTime);this._offset=this.regionRelativeOffset(this._offset+e),`stop`in this.source&&this.source.stop()}this.emitPaused()}}stop(){if(!this.source)throw Error(`Cannot stop a sound that has been cleaned up`);this._cancelPrepareSeek?.(),this._scheduledStop=void 0,this._mediaPreparationGate?.gain.setValueAtTime(0,this.context.currentTime);let e=this._mediaPlayPromise!==void 0;this._mediaPlayPromise=void 0,!(!e&&(this._state===`stopped`||this._state===`unplayed`))&&(this.cancelFade(),`stop`in this.source&&this._state===`playing`&&this.source.stop(),`mediaElement`in this.source&&this.source.mediaElement&&(this.source.mediaElement.pause(),this.source.mediaElement.currentTime=0),this._offset=0,this._startTime=0,this.emitStopped())}fadeIn(e,t,n){if(n?.perLoop&&this._clipRegion)throw Error(`Per-loop fades are not supported with clip bounds`);return n?.perLoop&&(this._fadeInConfig={duration:e,type:t??`linear`,perLoop:!0,targetVolume:this.gainNode.gain.value}),super.fadeIn(e,t,{startTime:n?.startTime})}configureFadeOut(e,t){if(this._scheduledStop)throw Error(`An absolute end cannot use an ended-time fade-out`);this._fadeOutConfig={duration:e,type:t??`linear`}}stopWithFade(e,t){return this.fadeOut(e,t).then(()=>{this._state!==`stopped`&&this.source&&this.stop()})}async prepareSeek(e,t={}){if(this.assertNotCleanedUp(),!Number.isFinite(e)||e<0)throw RangeError(`Seek time must be finite and non-negative`);let n=t.timeoutMs??1e4;if(!Number.isFinite(n)||n<=0||n>2147483647)throw RangeError(`Seek timeout must be positive and at most 2147483647 milliseconds`);if(t.signal?.aborted)throw new DOMException(`Seek preparation aborted`,`AbortError`);if(this._state===`playing`||this._mediaPlayPromise)throw Error(`Pause playback before preparing a seek`);this._cancelPrepareSeek?.();let r=this.source;if(!(`mediaElement`in r)){if(this._clipRegion&&e>=this._clipRegion.end)throw RangeError(`Seek time must precede the clip end`);if(!Number.isFinite(this.duration)||e>this.duration)throw RangeError(`Seek time exceeds duration`);this._offset=e,this.emit(`seek`,e);return}let i=r.mediaElement;if(!i.paused)throw Error(`Pause playback before preparing a seek`);if(!this._mediaPreparationGate){let e=this.context.createGain();e.gain.value=0,this._mediaPreparationGate=e,this.setEffectChainEndpoints(r,this.panner),r.connect(e)}this._mediaPreparationGate.gain.setValueAtTime(0,this.context.currentTime),await new Promise((r,a)=>{let o=!1,s=!1,c=!1,l=[`loadedmetadata`,`durationchange`,`progress`,`loadeddata`,`canplay`,`seeked`,`error`,`emptied`,`play`],u=n=>{if(!o){o=!0,clearTimeout(p);for(let e of l)i.removeEventListener(e,f);t.signal?.removeEventListener(`abort`,d),this._cancelPrepareSeek===d&&(this._cancelPrepareSeek=void 0),n===void 0?(this._offset=e,r()):a(n)}},d=()=>u(new DOMException(`Seek preparation aborted`,`AbortError`)),f=t=>{if(!o)try{if(i.error||t?.type===`error`){u(Error(i.error?.message||`Media failed during seek preparation`));return}if(t?.type===`emptied`&&s||t?.type===`play`){d();return}if(i.readyState<1)return;if(!Number.isFinite(i.duration)){u(new DOMException(`Seek preparation requires finite-duration media`,`NotSupportedError`));return}if(e>i.duration){u(RangeError(`Seek time exceeds duration`));return}if(s)t?.type===`seeked`&&(c=!1);else{let t=!1;for(let n=0;n<i.seekable.length;n++)e>=i.seekable.start(n)&&e<=i.seekable.end(n)&&(t=!0);if(!t)return;s=!0,c=i.seeking||i.currentTime!==e,i.currentTime!==e&&(i.currentTime=e)}!c&&!i.seeking&&i.readyState>=2&&Math.abs(i.currentTime-e)<.001&&u()}catch(e){u(e)}},p=setTimeout(()=>u(new DOMException(`Seek preparation timed out`,`TimeoutError`)),n);this._cancelPrepareSeek=d;for(let e of l)i.addEventListener(e,f);t.signal?.addEventListener(`abort`,d,{once:!0}),f()}),this.emit(`seek`,e)}seek(e){if(!this.source||!this.gainNode||!this.panner)throw Error(`Cannot seek a sound that has been cleaned up`);if(!Number.isFinite(e)||e<0||this.origin.region!==void 0&&e>this.duration)throw Error(`Invalid time value for seek`);if(this._clipRegion&&e>=this._clipRegion.end)throw RangeError(`Seek time must precede the clip end`);if(this._cancelPrepareSeek?.(),this.origin.soundType===`streaming`&&`mediaElement`in this.source&&(this.source.mediaElement.seekable?.length??0)===0)throw this.source.mediaElement.duration===1/0?Error(`Live media-element streams do not expose a seekable range`):Error(`Media-element stream does not currently expose a seekable range`);let t=this._state===`playing`;t&&this.pause(),this._offset=e,`mediaElement`in this.source&&this.source.mediaElement&&(this.source.mediaElement.currentTime=e),t&&this.play(),this.emit(`seek`,e)}get currentTime(){if(this._state===`playing`){if(this.source&&`mediaElement`in this.source)return this.source.mediaElement.currentTime;let e=this.elapsedSourceTime(this.context.currentTime),t=this._offset+e;return this.regionRelativeOffset(t)}else return this._offset}removeFromOrigin(){let e=this.origin.playbacks.indexOf(this);e!==-1&&this.origin.playbacks.splice(e,1)}recreateSource(){if(!this.buffer||!this.panner||!this.context||!this.gainNode)throw Error(`Cannot recreate source of a sound that has been cleaned up`);try{this.source&&(!(`mediaElement`in this.source)&&`onended`in this.source&&(this.source.onended=null),this.source.disconnect()),this.source=this.context.createBufferSource(),this._scheduledStop=void 0,this.source.buffer=this.buffer,this.setEffectChainEndpoints(this.source,this.panner),this.setupSourceNode(this.source),this.applyRateToSource(),this.configureBufferLoopSource()}catch(e){throw this.emitAsync(`error`,{error:e,errorType:`source`,timestamp:Date.now(),recoverable:!1}),e}}set sourceLoop(e){if(!this.source)throw Error(`Cannot set loop on a sound that has been cleaned up`);`loop`in this.source&&(this.source.loop=e),`mediaElement`in this.source&&this.source.mediaElement&&(this.source.mediaElement.loop=e)}cleanup(){if(this._scheduledStop=void 0,this._cancelPrepareSeek?.(),this._mediaPreparationGate?.gain.setValueAtTime(0,this.context.currentTime),this._mediaPlayPromise=void 0,this.source){if(`mediaElement`in this.source&&this.source.mediaElement){let e=this.source.mediaElement;e.pause();try{e.currentTime=0}catch{}e.loop=!1,e.onended=null,e.src=``,e.load()}else `onended`in this.source&&(this.source.onended=null,`stop`in this.source&&this._state===`playing`&&this.source.stop());this._offset=0,this._startTime=0,this.markStopped(),this.currentLoop=0,this.source.disconnect(),this.source=void 0,super.cleanup(),this._mediaPreparationGate?.disconnect(),this._mediaPreparationGate=void 0,this._bandStage?.destroy(),this._bandStage=void 0,this._reflections?.destroy(),this._reflections=void 0,this._volumeTarget=void 0,this._directTap?.disconnect(),this._directTap=void 0,this._output?.disconnect(),this._output=void 0}}assertNotCleanedUp(){if(!this.source||!this.gainNode||!this.panner)throw Error(`Cannot perform operation on a sound that has been cleaned up`)}addFilter(e){this.assertNotCleanedUp(),super.addFilter(e)}removeFilter(e){this.assertNotCleanedUp(),super.removeFilter(e)}loop(e){if(!this.source)throw Error(`Cannot loop a sound that has been cleaned up`);if(e!==void 0){this._validateLoopCount(e);let t=this.loopCount,n=e===`infinite`?`infinite`:Math.max(0,e),r=t===`infinite`!=(n===`infinite`);if(r&&(this.origin.region||this._clipRegion)&&this._state===`playing`&&`loop`in this.source&&`stop`in this.source){let e=Math.max(this._startTime,this.context.currentTime),r=this.elapsedSourceTime(this.context.currentTime);return this._offset=this.regionRelativeOffset(this.regionRelativeOffset(this._offset+r,t),n),`onended`in this.source&&(this.source.onended=null),this.source.stop(),this._scheduledStop=void 0,this.loopCount=n,this.currentLoop=0,this._startTime=e,this.recreateSource(),this.startBufferSource(e),this.loopCount}if(r&&this._state===`playing`&&`buffer`in this.source){let e=this.elapsedSourceTime(this.context.currentTime);this._offset=this.regionRelativeOffset(this._offset+e,t),this._startTime=Math.max(this._startTime,this.context.currentTime)}this.loopCount=n,this.currentLoop=0}if(`mediaElement`in this.source&&this.source.mediaElement){let e=this.source.mediaElement;e.loop=this.loopCount===`infinite`}else if(`loop`in this.source)this.configureBufferLoopSource();else throw Error(`Unsupported source type`);return this.loopCount}configureBufferLoopSource(){!this.source||!(`loop`in this.source)||(this.source.loop=this.loopCount===`infinite`,this.source.buffer&&(this.source.loopEnd=this._clipRegion?(this.origin.region?.start??0)+this._clipRegion.end:this.origin.region?this.origin.region.start+this.origin.region.duration:this.source.buffer.duration,this.source.loopStart=(this.origin.region?.start??0)+(this._clipRegion?.start??0)))}regionRelativeOffset(e,t=this.loopCount){if(this._clipRegion){let{start:n,end:r}=this._clipRegion;return t===`infinite`&&e>=r?n+(e-n)%(r-n):Math.min(r,e)}let n=this.origin.region;return n?t===`infinite`?e%n.duration:Math.min(n.duration,e):t===`infinite`&&this.buffer&&this.buffer.duration>0?e%this.buffer.duration:e}startBufferSource(e){if(!this.source||!(`start`in this.source))return!1;let t=this.origin.region;if(this._clipRegion){if(this._offset>=this._clipRegion.end)return!1;let n=(t?.start??0)+this._offset;return this.loopCount===`infinite`?this.source.start(e,n):this.source.start(e,n,this._clipRegion.end-this._offset),!0}if(!t)return this.source.start(e,this._offset),!0;if(this._offset===t.duration)return!1;let n=t.start+this._offset;return this.loopCount===`infinite`?this.source.start(e,n):this.source.start(e,n,t.duration-this._offset),!0}async setPitchShift(e){if(this.assertNotCleanedUp(),!Number.isFinite(e)||e<=0)throw Error(`Pitch-shift factor must be greater than 0`);this._pitchFactor=e;let n=this._effectChain;if(!n)throw Error(`Cannot pitch-shift a playback before its effect chain is initialized`);let r=n.nodes.find(e=>{let t=e.parameters;return t&&typeof t.get==`function`&&t.get(`pitchFactor`)!==void 0});if(e===1){r&&n.remove(r);return}if(!r){let e=this.origin.cacophony;if(!e)throw Error(`Cannot pitch-shift a playback whose Sound has no Cacophony instance`);r=await e.buildWorkletEffect(t.WORKLETS.phaseVocoder,{},this.context),n.add(r)}let i=r.parameters?.get(`pitchFactor`);i&&(i.value=e)}get pitchShift(){return this._pitchFactor}get outputNode(){if(!this._output)throw Error(`Cannot access output node of a playback that has been cleaned up`);return this._output}connect(e){return this.outputNode.connect(e)}disconnect(e){e?this.outputNode.disconnect(e):this.outputNode.disconnect()}clone(e={}){if(!this.source||!this.gainNode||!this.context)throw Error(`Cannot clone a sound that has been cleaned up`);if(this._scheduledStop)throw Error(`Cannot clone a playback with an armed absolute end`);this._validateLoopCount(e.loopCount??this.loopCount),r.validateSpatialSmoothingTau(e.spatialSmoothingTau??this.spatialSmoothingTau);let t=e.panType??this.panType;n.validateSpatialOptions(e,t);let i=this.context.createGain(),a;if(`buffer`in this.source&&this.source.buffer)a=this.context.createBufferSource(),a.buffer=this.source.buffer;else if(`mediaElement`in this.source&&this.source.mediaElement){if(!this.context.createMediaElementSource)throw Error(`Media element sources are not supported on this audio context.`);let e=this.source.mediaElement.cloneNode(!0);a=this.context.createMediaElementSource(e)}else throw Error(`Unsupported source type`);let o=e.loopCount===void 0?this.loopCount:e.loopCount,c=new s(this.origin,a,i);return c.outputNode.connect(this.origin._resolveRouteTargetNode()),c.loopCount=o,c._clipRegion=this._clipRegion&&{...this._clipRegion},c.currentLoop=this.currentLoop,c.setPanType(t,this.context),c.spatialSmoothingTau=e.spatialSmoothingTau??this.spatialSmoothingTau,t===`HRTF`?(this.panType===`HRTF`&&(c.threeDOptions=this.threeDOptions),e.threeDOptions!==void 0&&(c.threeDOptions=e.threeDOptions),e.position!==void 0&&(c.position=e.position)):c.stereoPan=e.stereoPan??this.stereoPan??0,c.volume=this.volume,c.playbackRate=this._playbackRate,c._offset=this._clipRegion&&this._state===`playing`?this.currentTime:this._offset,c.setBandGains(this._bandGains,0),this._reflections&&c.setReflections(this._reflections.images,0),this._fadeInConfig&&(c._fadeInConfig={...this._fadeInConfig}),this._fadeOutConfig&&(c._fadeOutConfig={...this._fadeOutConfig}),this._state===`paused`?c.markPaused():this._state===`stopped`&&c.markStopped(),this._filters.forEach(e=>{let t=this.context.createBiquadFilter();t.type=e.type,t.frequency.value=e.frequency.value,t.Q.value=e.Q.value,t.gain.value=e.gain.value,c.addFilter(t)}),this._pitchFactor!==1&&c.setPitchShift(this._pitchFactor).catch(()=>{}),this._state===`playing`&&c.play(),this.origin.playbacks.push(c),c}},c=Object.freeze(Array(8).fill(1));function l(e,t){if(!Number.isFinite(e)||e<0)throw RangeError(`${t} duration must be finite and non-negative`)}exports.Playback=s;
|
|
2
2
|
//# sourceMappingURL=playback.cjs.map
|