@schmooky/zvuk 1.14.0 → 1.14.1
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/dist/index.d.ts +27 -0
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1211,6 +1211,8 @@ declare class MusicVoice {
|
|
|
1211
1211
|
private loopArmTimer;
|
|
1212
1212
|
private outroTimer;
|
|
1213
1213
|
private nextLoopBoundaryAt;
|
|
1214
|
+
private loopAnchorAt;
|
|
1215
|
+
private introEndsAt;
|
|
1214
1216
|
constructor(deps: MusicVoiceDeps);
|
|
1215
1217
|
/** Currently-sounding part. Transitions automatically as parts hand off. */
|
|
1216
1218
|
get currentPart(): MusicState;
|
|
@@ -1240,6 +1242,19 @@ declare class MusicVoice {
|
|
|
1240
1242
|
private armNextLoopSegment;
|
|
1241
1243
|
private crossfadeViable;
|
|
1242
1244
|
private releaseLoopSegment;
|
|
1245
|
+
/**
|
|
1246
|
+
* Audio time of the next natural loop boundary.
|
|
1247
|
+
*
|
|
1248
|
+
* Under crossfade the chain re-anchors `nextLoopBoundaryAt` every time it
|
|
1249
|
+
* spawns a segment, so that marker is current by construction. The
|
|
1250
|
+
* native-loop path has no chain — one source loops itself for the whole
|
|
1251
|
+
* playback — so its boundaries are a grid off the loop's start, and the
|
|
1252
|
+
* answer has to be computed against the clock each time it's asked for.
|
|
1253
|
+
* Reading a marker that was written once, at the first boundary, is how
|
|
1254
|
+
* `skipToOutro({ at: 'loop-end' })` came to fire instantly on every
|
|
1255
|
+
* iteration but the first.
|
|
1256
|
+
*/
|
|
1257
|
+
private nextLoopBoundary;
|
|
1243
1258
|
private skipToOutroAtLoopEnd;
|
|
1244
1259
|
private skipToOutroNow;
|
|
1245
1260
|
private cancelLoopArm;
|
|
@@ -1600,6 +1615,18 @@ interface Engine<TBusName extends string = string> {
|
|
|
1600
1615
|
* left untouched.
|
|
1601
1616
|
*/
|
|
1602
1617
|
crossfade(from: string, to: string, options?: CrossfadeOptions): Voice;
|
|
1618
|
+
/**
|
|
1619
|
+
* Run `fn` when the audio clock reaches `audioTime`. Returns a cancel
|
|
1620
|
+
* function.
|
|
1621
|
+
*
|
|
1622
|
+
* Dispatch is a JS callback, so it is not sample-accurate and can run late —
|
|
1623
|
+
* by a tick when the main thread is keeping up, by however long it was
|
|
1624
|
+
* wedged when it isn't. Stamp Web Audio parameters with the `audioTime` you
|
|
1625
|
+
* scheduled against for sample accuracy, but clamp it to the clock first:
|
|
1626
|
+
* `Math.max(audioTime, ctx.currentTime)`. Engines pull a past-dated event up
|
|
1627
|
+
* to the current time rather than refusing it, so two of them land on the
|
|
1628
|
+
* same instant and the second is refused with NotSupportedError.
|
|
1629
|
+
*/
|
|
1603
1630
|
scheduleAt(audioTime: number, fn: () => void): () => void;
|
|
1604
1631
|
/** All currently active voices (across all buses). */
|
|
1605
1632
|
activeVoices(): readonly Voice[];
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
1
|
+
var P=class extends Error{constructor(t,e){super(t,e),this.name="ZvukError";}},S=class extends P{constructor(){super("Engine is closed. Create a new engine with createEngine()."),this.name="EngineClosedError";}};function mt(o){return o?` Did you mean "${o}"?`:""}var T=class extends P{constructor(t,e){super(`Bus "${t}" is not configured. Declare it in createEngine({ buses: { ... } }).${mt(e)}`),this.name="BusNotFoundError";}},A=class extends P{constructor(t,e){super(`Sound "${t}" is not loaded. Call engine.loadSound() or load a bank that contains it.${mt(e)}`),this.name="SoundNotFoundError";}};function et(o){return o instanceof Error?o.message:String(o)}var M=class extends P{constructor(t,e,i){super(i??`Failed to decode audio at "${t}": ${et(e)}`,{cause:e}),this.name="DecodeError";}},N=class extends P{failures;constructor(t){let e=t.map(i=>` - ${i.name}: ${et(i.cause)}`).join(`
|
|
2
2
|
`);super(`Failed to preload ${t.length} item(s):
|
|
3
|
-
${e}`,{cause:t[0]?.cause}),this.name="PreloadError",this.failures=t;}},B=class extends M{attempts;constructor(t,e){let i=e[e.length-1],s=e.map(r=>` - ${r.url}: ${
|
|
3
|
+
${e}`,{cause:t[0]?.cause}),this.name="PreloadError",this.failures=t;}},B=class extends M{attempts;constructor(t,e){let i=e[e.length-1],s=e.map(r=>` - ${r.url}: ${et(r.cause)}`).join(`
|
|
4
4
|
`);super(t[t.length-1]??"<empty>",i?.cause,`Failed to load any of ${t.length} fallback URLs:
|
|
5
|
-
${s}`),this.name="AggregateDecodeError",this.attempts=e;}};var
|
|
5
|
+
${s}`),this.name="AggregateDecodeError",this.attempts=e;}};var it=class{input;output;compressor;makeup;ctx;_bypassed=false;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.output=t.createGain(),this.compressor=t.createDynamicsCompressor(),this.makeup=t.createGain(),this.applyConfig(e),this.wire();}applyConfig(t){let e=this.ctx.currentTime;t.threshold!=null&&this.compressor.threshold.setValueAtTime(t.threshold,e),t.knee!=null&&this.compressor.knee.setValueAtTime(t.knee,e),t.ratio!=null&&this.compressor.ratio.setValueAtTime(t.ratio,e),t.attack!=null&&this.compressor.attack.setValueAtTime(t.attack,e),t.release!=null&&this.compressor.release.setValueAtTime(t.release,e),t.makeupGain!=null&&this.makeup.gain.setValueAtTime(10**(t.makeupGain/20),e);}get reduction(){return this.compressor.reduction}get bypassed(){return this._bypassed}set bypassed(t){this._bypassed!==t&&(this._bypassed=t,this.wire());}dispose(){try{this.input.disconnect(),this.compressor.disconnect(),this.makeup.disconnect(),this.output.disconnect();}catch{}}wire(){try{this.input.disconnect(),this.compressor.disconnect(),this.makeup.disconnect();}catch{}this._bypassed?this.input.connect(this.output):(this.input.connect(this.compressor),this.compressor.connect(this.makeup),this.makeup.connect(this.output));}};var st=class{input;output;gain;analyser;buf;rafId=null;lastTickMs=0;envelope=1;targetGain=1;ctx;cfg;_bypassed=false;sourceBus;constructor(t,e,i={}){this.ctx=t,this.sourceBus=e,this.cfg={amount:i.amount??.5,attack:i.attack??.08,release:i.release??.4,threshold:i.threshold??.05},this.input=t.createGain(),this.output=t.createGain(),this.gain=t.createGain(),this.input.connect(this.gain).connect(this.output),this.analyser=t.createAnalyser(),this.analyser.fftSize=1024,this.buf=new Float32Array(this.analyser.fftSize),e.output.connect(this.analyser),typeof document<"u"&&document.addEventListener("visibilitychange",this.handleVisibility),this.startLoop();}setAmount(t){this.cfg.amount=Math.max(0,Math.min(1,t));}setThreshold(t){this.cfg.threshold=Math.max(0,t);}get bypassed(){return this._bypassed}set bypassed(t){this._bypassed!==t&&(this._bypassed=t,t?(this.releaseToUnity(),this.stopLoop()):(this.resetEnvelope(),this.startLoop()));}dispose(){this.stopLoop(),typeof document<"u"&&document.removeEventListener("visibilitychange",this.handleVisibility);try{this.sourceBus.output.disconnect(this.analyser);}catch{}try{this.input.disconnect(),this.gain.disconnect(),this.analyser.disconnect(),this.output.disconnect();}catch{}}tick=t=>{let e=.016666666666666666;if(t!=null&&this.lastTickMs>0&&(e=Math.min(.1,Math.max(.001,(t-this.lastTickMs)/1e3))),t!=null&&(this.lastTickMs=t),this._bypassed){this.rafId=null;return}this.analyser.getFloatTimeDomainData(this.buf);let i=0;for(let l=0;l<this.buf.length;l++){let d=this.buf[l]??0;i+=d*d;}let s=Math.sqrt(i/this.buf.length),n=Math.max(0,s-this.cfg.threshold)>0?1-this.cfg.amount:1,u=(n<this.envelope?this.cfg.attack:this.cfg.release)||.001,c=1-Math.exp(-e/u);this.envelope=this.envelope+c*(n-this.envelope),Math.abs(this.envelope-this.targetGain)>.001&&(this.targetGain=this.envelope,this.gain.gain.setTargetAtTime(this.envelope,this.ctx.currentTime,.005)),this.rafId=requestAnimationFrame(this.tick);};handleVisibility=()=>{document.visibilityState==="visible"&&(this.resetEnvelope(),this._bypassed||this.startLoop());};resetEnvelope(){this.envelope=1,this.targetGain=1,this.lastTickMs=0,this.releaseToUnity();}releaseToUnity(){this.gain.gain.setTargetAtTime(1,this.ctx.currentTime,.005);}startLoop(){typeof requestAnimationFrame>"u"||this.rafId==null&&this.tick();}stopLoop(){this.rafId!=null&&cancelAnimationFrame(this.rafId),this.rafId=null;}};var rt=class{input;output;filter;ctx;_bypassed=false;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.output=t.createGain(),this.filter=t.createBiquadFilter(),this.filter.type=e.type??"lowpass",this.filter.frequency.value=e.frequency??1e3,this.filter.Q.value=e.q??1,this.filter.gain.value=e.gain??0,this.wire();}setFrequency(t){this.filter.frequency.setValueAtTime(t,this.ctx.currentTime);}setQ(t){this.filter.Q.setValueAtTime(t,this.ctx.currentTime);}setType(t){this.filter.type=t;}setGain(t){this.filter.gain.setValueAtTime(t,this.ctx.currentTime);}get bypassed(){return this._bypassed}set bypassed(t){this._bypassed!==t&&(this._bypassed=t,this.wire());}dispose(){try{this.input.disconnect(),this.filter.disconnect(),this.output.disconnect();}catch{}}wire(){try{this.input.disconnect(),this.filter.disconnect();}catch{}this._bypassed?this.input.connect(this.output):(this.input.connect(this.filter),this.filter.connect(this.output));}};var ot=class{input;output;dry;wet;convolver;preDelay;ctx;_bypassed=false;_wet;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.output=t.createGain(),this.dry=t.createGain(),this.wet=t.createGain(),this.preDelay=t.createDelay(1),this.convolver=t.createConvolver();let i=e.wet??.3;this._wet=i,this.dry.gain.value=1-i,this.wet.gain.value=i,e.impulse?this.convolver.buffer=e.impulse:this.convolver.buffer=this.synthIR(e.decay?.seconds??1.5),this.preDelay.delayTime.value=e.decay?.preDelay??0,this.input.connect(this.dry).connect(this.output),this.input.connect(this.preDelay).connect(this.convolver).connect(this.wet).connect(this.output);}setWet(t){let e=Math.max(0,Math.min(1,t));if(this._wet=e,this._bypassed)return;let i=this.ctx.currentTime;this.dry.gain.setValueAtTime(1-e,i),this.wet.gain.setValueAtTime(e,i);}setImpulse(t){this.convolver.buffer=t;}get bypassed(){return this._bypassed}set bypassed(t){if(this._bypassed===t)return;this._bypassed=t;let e=this.ctx.currentTime;t?(this.dry.gain.setValueAtTime(1,e),this.wet.gain.setValueAtTime(0,e)):(this.dry.gain.setValueAtTime(1-this._wet,e),this.wet.gain.setValueAtTime(this._wet,e));}dispose(){try{this.input.disconnect(),this.dry.disconnect(),this.wet.disconnect(),this.preDelay.disconnect(),this.convolver.disconnect(),this.output.disconnect();}catch{}}synthIR(t){let e=this.ctx.sampleRate,i=Math.floor(e*t),s=this.ctx.createBuffer(2,i,e);for(let r=0;r<2;r++){let n=s.getChannelData(r);for(let a=0;a<i;a++){let u=a/i;n[a]=(Math.random()*2-1)*(1-u)**3;}}return s}};var nt=class o{factor;constructor(t=1){this.factor=t;}process(t){if(this.factor===1)return new Float32Array(t);let e=Math.floor(t.length/this.factor),i=new Float32Array(e),r=Math.max(160,Math.floor(4096/Math.sqrt(this.factor))),n=Math.max(48,Math.floor(r/4)),a=Math.max(1,r-n),u=Math.max(1,Math.floor(a/this.factor)),c=new Float32Array(n),l=new Float32Array(n);for(let p=0;p<n;p++){let b=p/(n-1),h=Math.sin(Math.PI*b/2),v=Math.cos(Math.PI*b/2);c[p]=h*h,l[p]=v*v;}let d=Math.max(0,Math.floor(a*.03)),m=0,g=0;for(;m+r<t.length&&g+r<e;){let p=m;if(this.factor<2.5&&g>=n){let f=-1/0,y=Math.min(64,a);for(let _=-y;_<=y;_+=4){let j=m+_;if(j>=0&&j+n<t.length){let tt=0;for(let W=0;W<n;W++)tt+=(i[g-n+W]??0)*(t[j+W]??0);tt>f&&(f=tt,p=j);}}}d>0&&(p=Math.max(0,Math.min(t.length-r,p+(Math.random()*2-1)*d|0)));let b=0,h=0;if(g>0)for(let f=0;f<n;f++){let y=i[g-n+f]??0,_=t[p+f]??0;b+=y*y,h+=_*_;}let v=1;h>1e-8&&b>0&&(v=Math.sqrt(b/h)),v=Math.min(1.1,Math.max(.9,v));for(let f=0;f<r&&g+f<e;f++){let y=t[p+f]??0;if(f<n&&g>0){let _=i[g+f]??0;i[g+f]=_*(l[f]??0)+y*v*(c[f]??0);}else i[g+f]=y;}m+=a,g+=u;}for(let p=g;p<e;p++){let b=p*this.factor,h=Math.floor(b),v=b-h;h>=0&&h+1<t.length?i[p]=(t[h]??0)*(1-v)+(t[h+1]??0)*v:i[p]=t[Math.min(t.length-1,Math.max(0,h))]??0;}if(this.factor>1){let p=Math.min(.12,Math.max(.05,.18/this.factor)),b=0;for(let h=0;h<i.length;h++){let v=i[h]??0;i[h]=v+p*(v-b),b=v;}}return i}static stretchBuffer(t,e,i){if(i===1)return e;let s=new o(i),r=[];for(let u=0;u<e.numberOfChannels;u++)r.push(s.process(e.getChannelData(u)));let n=Math.max(...r.map(u=>u.length)),a=t.createBuffer(e.numberOfChannels,n,e.sampleRate);for(let u=0;u<e.numberOfChannels;u++)a.copyToChannel(r[u],u);return a}};var vt="zvuk-realtime-stretch",gt=new WeakSet,_t=`
|
|
6
6
|
class ZvukRealtimeStretchProcessor extends AudioWorkletProcessor {
|
|
7
7
|
static get parameterDescriptors() {
|
|
8
8
|
return [
|
|
@@ -66,6 +66,6 @@ class ZvukRealtimeStretchProcessor extends AudioWorkletProcessor {
|
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
-
registerProcessor('${
|
|
70
|
-
`;async function Ot(o){if(mt.has(o))return;let t=o.audioWorklet;if(!t)throw new Error("AudioWorklet not supported in this context");let e=new Blob([Mt],{type:"application/javascript"}),i=URL.createObjectURL(e);try{await t.addModule(i);}finally{URL.revokeObjectURL(i);}mt.add(o);}function _t(o,t={}){let e=globalThis.AudioWorkletNode;if(!e)throw new Error("AudioWorkletNode not available");let i=new e(o,gt,{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2],processorOptions:{grainSize:t.grainSize??1024}}),s=i.parameters.get("stretch");s&&t.stretchFactor!=null&&(s.value=t.stretchFactor);let r=i;return Object.defineProperty(r,"stretch",{value:s,enumerable:true}),r.dispose=()=>{try{i.disconnect();}catch{}},r}function w(o,t,e){let i=Math.max(0,t);if(i===0)return Promise.resolve();if(o.state!=="running")return Pt(i,e);let s=o.currentTime+i;return new Promise(r=>{let n=null,a=false,u=()=>{a||(a=true,n!=null&&clearTimeout(n),n=null,r());},c=()=>{if(n=null,a)return;let l=s-o.currentTime;if(l<=0){u();return}n=setTimeout(c,Math.min(l*1e3,250));};e&&e.then(u,u),n=setTimeout(c,i*1e3);})}function Pt(o,t){return new Promise(e=>{let i=setTimeout(e,o*1e3);t&&t.then(()=>{clearTimeout(i),e();},()=>{clearTimeout(i),e();});})}function S(o,t,e,i,s){let r=Math.max(0,i),n=o.value;if(kt(o,t,n),r===0){nt(o,e,()=>o.setValueAtTime(e,t));return}if(s==="linear"){nt(o,e,()=>o.linearRampToValueAtTime(e,t+r));return}let a=vt(n,e,s,64);nt(o,e,()=>o.setValueCurveAtTime(a,t,r));}function kt(o,t,e){let i=o;if(typeof i.cancelAndHoldAtTime=="function")try{i.cancelAndHoldAtTime(t);}catch{o.cancelScheduledValues(t);}else o.cancelScheduledValues(t);try{o.setValueAtTime(e,t);}catch{}}function nt(o,t,e){try{e();}catch{o.value=t;}}function P(o,t,e=33){return vt(o,t,"equal-power",e)}function vt(o,t,e,i){let s=new Float32Array(i),r=t>=o;for(let n=0;n<i;n++){let a=n/(i-1),u=Nt(a,e,r);s[n]=o+(t-o)*u;}return s}function Nt(o,t,e=true){switch(t){case "easeIn":return o*o;case "easeOut":return 1-(1-o)*(1-o);case "easeInOut":return o<.5?2*o*o:1-2*(1-o)*(1-o);case "equal-power":return e?Math.sin(o*Math.PI/2):1-Math.cos(o*Math.PI/2);default:return o}}var Z=class{source;target;post;gainNode;ctx;disposed=false;constructor(t,e,i,s){this.source=t,this.target=e,this.post=i.post??true,this.ctx=s,this.gainNode=s.createGain(),this.gainNode.gain.value=E(i.amount??1),(this.post?t.output:t.input).connect(this.gainNode),this.gainNode.connect(e.input);}get amount(){return this.gainNode.gain.value}set amount(t){this.disposed||S(this.gainNode.gain,this.ctx.currentTime,E(t),.01,"linear");}fadeTo(t,e,i="linear"){return this.disposed?Promise.resolve():(S(this.gainNode.gain,this.ctx.currentTime,E(t),e,i),w(this.ctx,e))}dispose(){if(!this.disposed){this.disposed=true;try{this.gainNode.disconnect();}catch{}}}},F=class{name;input;fxInput;output;_level;_muted;_soloed=false;_soloVeiled=false;ctx;_concurrency;_voices=new Set;_fxChain=[];_sends=[];_meterAnalyser=null;_meterBuf=null;notifySoloChange;constructor(t,e,i={}){this.ctx=t,this.name=e,this._level=i.level??1,this._muted=i.mute??false,this._concurrency=i.concurrency??null,this.input=t.createGain(),this.fxInput=t.createGain(),this.output=t.createGain(),this.input.connect(this.fxInput),this.fxInput.connect(this.output),this.output.gain.value=this._muted?0:this._level;}get level(){return this._level}set level(t){this._level=E(t),!this._muted&&!this._soloVeiled&&this.rampOutput(this._level,.01);}get muted(){return this._muted}set muted(t){this._muted!==t&&(this._muted=t,this.rampOutput(t||this._soloVeiled?0:this._level,.01));}fadeTo(t,e,i="linear"){let s=E(t);return this._level=s,this._muted||this._soloVeiled?w(this.ctx,e):this.ramp(s,e,i)}get voiceCount(){return this._voices.size}voices(){return Array.from(this._voices)}get concurrency(){return this._concurrency}setConcurrency(t){this._concurrency=t;}applyConcurrencyOnSpawn(t,e){let i=this._concurrency;if(!i||this._voices.size<=i.max)return null;let s=i.steal??"oldest";if(s==="none")return e(),null;let r=Bt(this._voices,s,t);return r?(r.stop(),r):(e(),null)}trackVoice(t){this._voices.add(t);}releaseVoice(t){this._voices.delete(t);}addFx(t){this._fxChain.push(t),this.rewireFxChain();}removeFx(t){let e=this._fxChain.indexOf(t);e!==-1&&(this._fxChain.splice(e,1),this.rewireFxChain());}fx(){return [...this._fxChain]}meter(){if(!this._meterAnalyser){let s=this.ctx.createAnalyser();s.fftSize=1024,this.output.connect(s),this._meterAnalyser=s,this._meterBuf=new Float32Array(s.fftSize);}let t=this._meterBuf;this._meterAnalyser.getFloatTimeDomainData(t);let e=0,i=0;for(let s=0;s<t.length;s++){let r=t[s]??0;e+=r*r;let n=Math.abs(r);n>i&&(i=n);}return {rms:Math.sqrt(e/t.length),peak:i}}send(t,e={}){let i=new Z(this,t,e,this.ctx);return this._sends.push(i),i}removeSend(t){let e=this._sends.indexOf(t);e!==-1&&(this._sends.splice(e,1),t.dispose());}sends(){return [...this._sends]}solo(t=true){this._soloed!==t&&(this._soloed=t,this.notifySoloChange?.(this,t));}unsolo(){this.solo(false);}get soloed(){return this._soloed}applySoloVeil(t){this._soloVeiled=t;let e=this._muted||t?0:this._level;this.rampOutput(e,.01);}rewireFxChain(){try{this.fxInput.disconnect();for(let e of this._fxChain)e.output.disconnect();}catch{}let t=this.fxInput;for(let e of this._fxChain)t.connect(e.input),t=e.output;t.connect(this.output);}rampOutput(t,e){this.ramp(t,e,"linear");}ramp(t,e,i){let s=this.output.gain,r=this.ctx.currentTime;return S(s,r,t,e,i),w(this.ctx,e)}dispose(){for(let t of this._sends)t.dispose();this._sends=[];for(let t of this._fxChain)t.dispose();this._fxChain=[];try{this.input.disconnect(),this.fxInput.disconnect(),this.output.disconnect(),this._meterAnalyser?.disconnect();}catch{}this._meterAnalyser=null,this._meterBuf=null;}};function E(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}function Bt(o,t,e){let i=t==="quietest"?new Map:null;if(i)for(let r of o)r!==e&&i.set(r,r.levelHint());let s=null;for(let r of o)if(r!==e){if(!s){s=r;continue}switch(t){case "oldest":r.startedAt<s.startedAt&&(s=r);break;case "lowest-priority":r.priority<s.priority&&(s=r);break;case "quietest":{let n=i?.get(r)??0,a=i?.get(s)??0;n<a&&(s=r);break}}}return s}var L=class{name;members;constructor(t,e){this.name=t,this.members=e;}set level(t){for(let e of this.members)e.level=t;}get level(){if(this.members.length===0)return 0;let t=0;for(let e of this.members)t+=e.level;return t/this.members.length}set muted(t){for(let e of this.members)e.muted=t;}get muted(){return this.members.length===0?false:this.members.every(t=>t.muted)}fadeTo(t,e,i="linear"){return Promise.all(this.members.map(s=>s.fadeTo(t,e,i))).then(()=>{})}solo(t=true){for(let e of this.members)e.solo(t);}unsolo(){this.solo(false);}};var V=class{name;_value;subs=new Set;constructor(t,e){this.name=t,this._value=e;}get value(){return this._value}set(t){if(t!==this._value){this._value=t;for(let e of this.subs)e(t);}}subscribe(t){return this.subs.add(t),t(this._value),()=>this.subs.delete(t)}bindTo(t,e={}){let i=e.from??0,s=e.to??1,r=e.curve??"linear",n=s>=i;return this.subscribe(a=>{let u=Math.max(0,Math.min(1,a)),c=Et(u,r,n);t(i+(s-i)*c);})}};function Et(o,t,e=true){switch(t){case "easeIn":return o*o;case "easeOut":return 1-(1-o)*(1-o);case "easeInOut":return o<.5?2*o*o:1-2*(1-o)*(1-o);case "equal-power":return e?Math.sin(o*Math.PI/2):1-Math.cos(o*Math.PI/2);default:return o}}var Ft={webm:'audio/webm; codecs="opus"',opus:'audio/ogg; codecs="opus"',ogg:'audio/ogg; codecs="vorbis"',m4a:'audio/mp4; codecs="mp4a.40.2"',mp4:'audio/mp4; codecs="mp4a.40.2"',aac:'audio/mp4; codecs="mp4a.40.2"',mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac"},at=null;function ut(o){if(typeof document>"u")return true;if(!at)try{at=document.createElement("audio");}catch{return true}let t=at.canPlayType(o);return t==="probably"||t==="maybe"}function ct(o){let t=/\.([a-z0-9]+)(?:[?#]|$)/i.exec(o);return t?.[1]?Ft[t[1].toLowerCase()]??null:null}function lt(o){if(o.length===0)throw new Error("pickSource requires at least one URL");for(let t of o){let e=ct(t);if(e&&ut(e))return t}return o[0]}function ht(o){if(o.length===0)return o;let t=[],e=[];for(let i of o){let s=ct(i);s&&ut(s)?t.push(i):e.push(i);}return [...t,...e]}var X=class{_ctx=null;_state="cold";_unlocking=null;_listeners=new Set;opts;constructor(t={}){this.opts=t;}get state(){return this._state}touch(){if(this._state==="closed")throw new x;if(!this._ctx){let t={};this.opts.latencyHint!=null&&(t.latencyHint=this.opts.latencyHint);let e=Lt();this._ctx=new e(t),this.attachVisibilityHandler(),this.attachStateChangeHandler(this._ctx);}return this._ctx}peek(){return this._ctx}async unlock(){if(this._state==="closed")throw new x;if(this._unlocking)return this._unlocking;if(this._state==="live"&&this._ctx?.state==="running")return;this.setState("unlocking");let t=this.touch();return this._unlocking=(async()=>{try{t.state==="suspended"&&await t.resume(),this.setState("live");}catch(e){throw this.setState("cold"),e}finally{this._unlocking=null;}})(),this._unlocking}get now(){return this._ctx?.currentTime??0}onStateChange(t){return this._listeners.add(t),()=>this._listeners.delete(t)}async close(){this._state!=="closed"&&(typeof document<"u"&&document.removeEventListener("visibilitychange",this.handleVisibility),this._ctx&&(this._ctx.removeEventListener("statechange",this.handleCtxStateChange),this._ctx.state!=="closed"&&await this._ctx.close().catch(()=>{})),this._ctx=null,this.setState("closed"),this._listeners.clear());}setState(t){if(this._state!==t){this._state=t;for(let e of this._listeners)e(t);}}attachVisibilityHandler(){this.opts.autoPauseOnHidden!==false&&(typeof document>"u"||document.addEventListener("visibilitychange",this.handleVisibility));}handleVisibility=()=>{if(!this._ctx||this._state==="closed")return;document.visibilityState==="visible"?setTimeout(()=>{document.visibilityState==="visible"&&this._ctx?.state==="suspended"&&this._ctx.resume().catch(()=>{});},200):this._ctx.suspend().catch(()=>{});};attachStateChangeHandler(t){t.addEventListener("statechange",this.handleCtxStateChange);}handleCtxStateChange=()=>{let t=this._ctx;if(!t||this._state==="closed")return;let e=t.state;if(e==="interrupted"){this.setState("interrupted");return}if(e==="suspended"){if(this._state==="interrupted"){setTimeout(()=>{this._ctx===t&&t.state==="suspended"&&t.resume().catch(()=>{});},200);return}(this._state==="live"||this._state==="unlocking")&&this.setState("suspended");return}e==="running"&&this._state!=="live"&&this.setState("live");}};function Lt(){let o=globalThis,t=o.AudioContext??o.webkitAudioContext;if(!t)throw new Error("No AudioContext constructor available in this environment.");return t}var Vt=64*1024*1024,Dt=128;function It(o){return o.length*o.numberOfChannels*4}var Y=class{constructor(t,e={}){this.getCtx=t;let i=typeof e=="number"?{maxEntries:e}:e;this.maxBytes=Math.max(1,i.maxBytes??Vt),this.maxEntries=Math.max(1,i.maxEntries??Dt);}getCtx;cache=new Map;bytes=0;inflight=new Map;maxBytes;maxEntries;has(t){return this.cache.has(t)}get cachedBytes(){return this.bytes}async load(t,e={}){let i=this.cache.get(t);if(i)return this.touch(t,i.buffer),i.buffer;let s=this.inflight.get(t);if(s)return this.join(s,e.signal);let r=new AbortController,n;return n={promise:this.fetchAndDecode(t,r.signal,e.onProgress).finally(()=>{this.inflight.get(t)===n&&this.inflight.delete(t);}),controller:r,waiters:0},this.inflight.set(t,n),this.join(n,e.signal)}join(t,e){t.waiters++;let i=()=>{t.waiters--,t.waiters<=0&&t.controller.abort();};return e?e.aborted?(i(),Promise.reject(bt(e))):new Promise((s,r)=>{let n=false,a=()=>{n||(n=true,i(),r(bt(e)));};e.addEventListener("abort",a,{once:true}),t.promise.then(u=>{n||(n=true,t.waiters--,e.removeEventListener("abort",a),s(u));},u=>{n||(n=true,t.waiters--,e.removeEventListener("abort",a),r(u));});}):t.promise.finally(()=>t.waiters--)}async fetchAndDecode(t,e,i){let s;try{s=await fetch(t,{signal:e});}catch(u){throw u.name==="AbortError"?u:new M(t,u)}if(!s.ok)throw new M(t,new Error(`${s.status} ${s.statusText}`));let r=i?await Rt(s,i):await s.arrayBuffer(),n=this.getCtx(),a;try{a=await n.decodeAudioData(r);}catch(u){throw new M(t,u)}return this.touch(t,a),a}async loadFirst(t,e={}){if(t.length===0)throw new Error("loadFirst requires at least one URL");for(let s of t){let r=this.cache.get(s);if(r)return this.touch(s,r.buffer),r.buffer}let i=[];for(let s of t)try{return await this.load(s,e)}catch(r){if(r.name==="AbortError")throw r;i.push({url:s,cause:r});}if(t.length===1){let s=i[0]?.cause;throw s instanceof Error?s:new M(t[0],s)}throw new B(t,i)}evict(t){let e=this.cache.get(t);e&&(this.bytes-=e.bytes,this.cache.delete(t));}clear(){this.cache.clear(),this.bytes=0;}touch(t,e){this.evict(t);let i=It(e);for(this.cache.set(t,{buffer:e,bytes:i}),this.bytes+=i;this.cache.size>this.maxEntries||this.bytes>this.maxBytes&&this.cache.size>1;){let s=this.cache.keys().next().value;if(s===void 0)break;this.evict(s);}}};function bt(o){return o.reason??new DOMException("load aborted","AbortError")}async function Rt(o,t){let e=o.body;if(!e||typeof e.getReader!="function"){let d=await o.arrayBuffer();return t(d.byteLength,d.byteLength),d}let i=o.headers.get("content-length"),s=i?Number.parseInt(i,10):Number.NaN,r=Number.isFinite(s)?s:null,n=e.getReader(),a=[],u=0;for(;;){let{done:d,value:m}=await n.read();if(d)break;m&&(a.push(m),u+=m.byteLength,t(u,r));}let c=new Uint8Array(u),l=0;for(let d of a)c.set(d,l),l+=d.byteLength;return c.buffer}var Gt={targetRms:.1,peakCeiling:.99};function k(o,t,e){if(!t)return o;let i={...Gt,...typeof t=="object"?t:{}},s=yt(o,i);return Math.abs(s-1)<.001?o:qt(o,s,e)}function yt(o,t){let e=zt(o);if(e<=1e-6)return 1;let i=t.targetRms/e,s=Ut(o)*i;return s>t.peakCeiling&&(i*=t.peakCeiling/s),i}function zt(o){let t=0,e=0;for(let i=0;i<o.numberOfChannels;i++){let s=o.getChannelData(i);for(let r=0;r<s.length;r++)t+=s[r]*s[r];e+=s.length;}return e===0?0:Math.sqrt(t/e)}function Ut(o){let t=0;for(let e=0;e<o.numberOfChannels;e++){let i=o.getChannelData(e);for(let s=0;s<i.length;s++){let r=Math.abs(i[s]);r>t&&(t=r);}}return t}function qt(o,t,e){if(e){let i=e.createBuffer(o.numberOfChannels,o.length,o.sampleRate);for(let s=0;s<o.numberOfChannels;s++){let r=o.getChannelData(s),n=i.getChannelData(s);for(let a=0;a<r.length;a++)n[a]=r[a]*t;}return i}for(let i=0;i<o.numberOfChannels;i++){let s=o.getChannelData(i);for(let r=0;r<s.length;r++)s[r]=s[r]*t;}return o}var K=class{constructor(t,e){this.host=t;this.tickSource=e;}host;tickSource;tasks=[];cancelled=0;timer=null;unsubscribe=null;scheduleAt(t,e){let i={audioTime:t,fn:e,cancelled:false};return this.tasks.splice(this.insertionIndex(t),0,i),this.arm(),()=>{i.cancelled||(i.cancelled=true,this.cancelled++,this.cancelled>32&&this.cancelled*2>this.tasks.length&&this.compact());}}insertionIndex(t){let e=0,i=this.tasks.length;for(;e<i;){let s=e+i>>>1;this.tasks[s].audioTime<=t?e=s+1:i=s;}return e}compact(){this.tasks=this.tasks.filter(t=>!t.cancelled),this.cancelled=0;}arm(){if(this.tickSource){this.unsubscribe||(this.unsubscribe=this.tickSource.subscribe(()=>this.tick()));return}this.rearmTimer();}rearmTimer(){this.timer!=null&&(clearTimeout(this.timer),this.timer=null);let t=this.tasks.find(s=>!s.cancelled);if(!t)return;let e=this.host.now,i=Math.max(0,(t.audioTime-e)*1e3);this.timer=setTimeout(()=>this.tick(),i);}tick(){this.timer!=null&&(this.timer=null);let t=this.host.now,e=[],i=[];for(let s of this.tasks)s.cancelled||(s.audioTime<=t?e.push(s):i.push(s));this.tasks=i,this.cancelled=0;for(let s of e)try{s.fn();}catch(r){console.error("[zvuk] scheduled task threw",r);}if(this.tasks.length===0){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null);return}this.tickSource||this.rearmTimer();}dispose(){this.timer!=null&&clearTimeout(this.timer),this.timer=null,this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.tasks=[],this.cancelled=0;}};var Ht=.008,$t=.05,D=class{name;deps;live=new Set;constructor(t,e){this.name=t,this.deps=e;}get loopDuration(){return this.deps.buffers.loop.duration}get hasIntro(){return this.deps.buffers.intro!=null}get hasOutro(){return this.deps.buffers.outro!=null}play(t={}){let e=new Q({ctx:this.deps.ctx,buffers:this.deps.buffers,destination:this.deps.destination,loopCrossfade:this.deps.loopCrossfade,defaultStopFade:this.deps.defaultStopFade,options:t});return this.live.add(e),e.ended.then(()=>this.live.delete(e)),e}voices(){return Array.from(this.live)}stopAll(t={}){for(let e of Array.from(this.live))e.stop(t);this.live.clear();}},Q=class{ended;ctx;buffers;destination;gain;state="intro";done=false;resolveEnded;stopFade;loopCrossfadeSec;introSource=null;outroSource=null;loopChain=[];loopArmTimer=null;outroTimer=null;nextLoopBoundaryAt=Number.POSITIVE_INFINITY;constructor(t){this.ctx=t.ctx,this.buffers=t.buffers,this.destination=t.destination,this.loopCrossfadeSec=Math.max(0,t.loopCrossfade),this.stopFade=Math.max(0,t.defaultStopFade??Ht),this.gain=this.ctx.createGain();let e=St(t.options.volume??1),i=Math.max(0,t.options.fadeIn??0);i>0?(this.gain.gain.setValueAtTime(0,this.ctx.currentTime),this.gain.gain.linearRampToValueAtTime(e,this.ctx.currentTime+i)):this.gain.gain.value=e,this.gain.connect(this.destination),this.ended=new Promise(s=>{this.resolveEnded=s;}),this.start(this.ctx.currentTime);}get currentPart(){return this.state}fade(t){let e=this.gain.gain,i=this.ctx.currentTime;return S(e,i,St(t.to),t.duration,t.curve??"linear"),w(this.ctx,t.duration,this.ended)}stop(t={}){if(this.done)return;let e=Math.max(0,t.fade??this.stopFade);if(this.cancelTimers(),e===0){this.stopAllSources(0),this.finish();return}let i=this.ctx.currentTime,s=i+e;try{let r=this.gain.gain;r.cancelScheduledValues(i),r.setValueAtTime(r.value,i),r.linearRampToValueAtTime(0,s),this.stopAllSources(s);}catch{this.finish();return}setTimeout(()=>this.finish(),e*1e3);}skipToOutro(t={}){if(this.done||this.state==="outro"||this.state==="ended")return;if(!this.buffers.outro){this.stop();return}(t.at??"loop-end")==="now"?this.skipToOutroNow():this.skipToOutroAtLoopEnd();}start(t){this.buffers.intro?(this.scheduleIntro(t),this.scheduleLoopStart(t+this.buffers.intro.duration)):(this.state="loop",this.scheduleLoopStart(t));}scheduleIntro(t){let e=this.ctx.createBufferSource();e.buffer=this.buffers.intro,e.connect(this.gain),e.start(t),e.onended=()=>{this.introSource===e&&(this.introSource=null);},this.introSource=e;}scheduleLoopStart(t){if(this.done)return;let e=this.spawnLoopSegment(t,false);if(this.nextLoopBoundaryAt=t+this.buffers.loop.duration,this.loopCrossfadeSec>0&&this.crossfadeViable())this.armNextLoopSegment(t);else {e.source.loop=true;let i=this.buffers.loop;if(e.source.loopStart=0,e.source.loopEnd=i.duration,!this.buffers.intro)this.state="loop";else {let s=Math.max(0,(t-this.ctx.currentTime)*1e3);setTimeout(()=>{!this.done&&this.state==="intro"&&(this.state="loop");},s);}}}spawnLoopSegment(t,e){let i=this.ctx.createBufferSource();i.buffer=this.buffers.loop,i.loop=false;let s=this.ctx.createGain();if(e?(s.gain.setValueAtTime(0,t),s.gain.setValueCurveAtTime(P(0,1),t,this.loopCrossfadeSec)):s.gain.setValueAtTime(1,t),this.crossfadeViable()){let n=t+this.buffers.loop.duration-this.loopCrossfadeSec;s.gain.setValueAtTime(1,n),s.gain.setValueCurveAtTime(P(1,0),n,this.loopCrossfadeSec);}i.connect(s).connect(this.gain);try{this.crossfadeViable()?i.start(t,0,this.buffers.loop.duration):i.start(t);}catch{}i.onended=()=>this.releaseLoopSegment(i,s);let r={source:i,gain:s,startTime:t};return this.loopChain.push(r),r}armNextLoopSegment(t){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null);let e=t+this.buffers.loop.duration-this.loopCrossfadeSec,s=Math.max(0,(e-this.ctx.currentTime)*1e3-50);this.loopArmTimer=setTimeout(()=>{this.loopArmTimer=null,!(this.done||this.state!=="loop"&&this.state!=="intro")&&(this.state="loop",this.spawnLoopSegment(e,true),this.nextLoopBoundaryAt=e+this.buffers.loop.duration,this.armNextLoopSegment(e));},s);}crossfadeViable(){return this.loopCrossfadeSec>0&&this.buffers.loop.duration>this.loopCrossfadeSec*2}releaseLoopSegment(t,e){let i=this.loopChain.findIndex(s=>s.source===t);i>=0&&this.loopChain.splice(i,1);try{t.disconnect(),e.disconnect();}catch{}}skipToOutroAtLoopEnd(){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null);let t;this.state==="intro"?(t=this.ctx.currentTime+(this.buffers.intro?.duration??0),this.cancelLoopArm()):t=this.nextLoopBoundaryAt,this.stopLoopSourcesAt(t),this.scheduleOutro(t);}skipToOutroNow(){this.cancelLoopArm();let t=this.ctx.currentTime,e=t+$t;for(let i of this.loopChain){try{let s=i.gain.gain;s.cancelScheduledValues(t),s.setValueAtTime(s.value,t),s.linearRampToValueAtTime(0,e);}catch{}try{i.source.stop(e);}catch{}}if(this.introSource)try{this.introSource.stop(e);}catch{}this.scheduleOutro(e);}cancelLoopArm(){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null);}stopLoopSourcesAt(t){for(let e of this.loopChain)try{e.source.stop(t);}catch{}}scheduleOutro(t){let e=this.buffers.outro;if(!e){let r=Math.max(0,(t-this.ctx.currentTime)*1e3);this.outroTimer=setTimeout(()=>this.finish(),r);return}let i=this.ctx.createBufferSource();i.buffer=e,i.connect(this.gain);try{i.start(t);}catch{}i.onended=()=>{this.outroSource===i&&(this.outroSource=null),this.finish();},this.outroSource=i;let s=Math.max(0,(t-this.ctx.currentTime)*1e3);this.outroTimer=setTimeout(()=>{this.outroTimer=null,this.done||(this.state="outro");},s);}cancelTimers(){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null),this.outroTimer!=null&&(clearTimeout(this.outroTimer),this.outroTimer=null);}stopAllSources(t){let e=[];this.introSource&&e.push(this.introSource);for(let i of this.loopChain)e.push(i.source);this.outroSource&&e.push(this.outroSource);for(let i of e)try{i.onended=null,t===0?i.stop():i.stop(t);}catch{}}finish(){if(!this.done){this.done=true,this.state="ended",this.cancelTimers();try{this.introSource&&this.introSource.disconnect();for(let t of this.loopChain)t.source.disconnect(),t.gain.disconnect();this.outroSource&&this.outroSource.disconnect(),this.gain.disconnect();}catch{}this.introSource=null,this.outroSource=null,this.loopChain=[],this.resolveEnded();}}};function St(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}var Wt=.008,I=class o{id;priority;bus;startedAt;sourceName;ended;ctx;gain;source;buffer;loop;basePitch;done=false;stopping=false;paused=false;resolveEnded;cueListeners=new Set;startCtxTime;pausedOffset=0;currentOffset=0;_spatializer;startOffset;regionDuration;loopStart;loopEnd;regionTimer=null;stopFade;crossfadeSec=0;crossfadeRegionStart=0;crossfadeRegionLen=0;crossfadeChain=[];crossfadeArmTimer=null;levelAnalyser=null;levelBuf=null;static nextId=1;constructor(t){let{ctx:e,buffer:i,destination:s,options:r}=t;this.id=o.nextId++,this.ctx=e,this.priority=r.priority??0,this.bus=r.bus,this.sourceName=t.sourceName,this.startedAt=e.currentTime,this.buffer=i,this.loop=r.loop??false,this.basePitch=xt(r.pitch??1,1),this._spatializer=t.spatializer,this.startOffset=r.offset??0,this.currentOffset=this.startOffset,this.regionDuration=r.duration,this.loopStart=r.loopStart,this.loopEnd=r.loopEnd,this.stopFade=Math.max(0,t.defaultStopFade??Wt),this.gain=e.createGain();let n=At(xt(r.volume??1)),a=Math.max(0,r.fadeIn??0);if(a>0?(this.gain.gain.setValueAtTime(0,e.currentTime),this.gain.gain.linearRampToValueAtTime(n,e.currentTime+a)):this.gain.gain.value=n,this.gain.connect(s),this.startCtxTime=e.currentTime,this.ended=new Promise(u=>{this.resolveEnded=u;}),r.signal&&(r.signal.aborted?queueMicrotask(()=>this.stop()):r.signal.addEventListener("abort",()=>this.stop(),{once:true})),this.shouldUseLoopCrossfade(r)){this.crossfadeSec=r.loopCrossfade,this.crossfadeRegionStart=r.loopStart??this.startOffset;let u=r.loopEnd??i.duration;this.crossfadeRegionLen=Math.max(0,u-this.crossfadeRegionStart),this.source=this.startCrossfadeChain(e.currentTime);}else {this.source=this.createSourceNode(this.basePitch),this.bindSourceLifecycle(this.source,()=>{});try{this.source.start(0,this.startOffset);}catch{}this.armRegionTimer(this.regionDuration);}queueMicrotask(()=>this.emit("started")),this.ended.then(()=>t.onEnded(this));}shouldUseLoopCrossfade(t){if(!this.loop)return false;let e=t.loopCrossfade;if(e==null||e<=0)return false;let i=t.loopStart??this.startOffset;return (t.loopEnd??this.buffer.duration)-i>e*2}fade(t){let e=this.gain.gain,i=this.ctx.currentTime;return S(e,i,At(t.to),t.duration,t.curve??"linear"),w(this.ctx,t.duration,this.ended)}stop(t={}){if(this.done||this.stopping)return;let e=Math.max(0,t.fade??this.stopFade);if(this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null),e===0){this.stopAllSources(0),this.finish("ended");return}this.stopping=true;let i=this.ctx.currentTime,s=i+e;for(let r of this.activeSources())r.onended=null;this.regionTimer!=null&&(clearTimeout(this.regionTimer),this.regionTimer=null);try{let r=this.gain.gain;r.cancelScheduledValues(i),r.setValueAtTime(r.value,i),r.linearRampToValueAtTime(0,s),this.stopAllSources(s);}catch{this.finish("ended");return}setTimeout(()=>this.finish("ended"),e*1e3);}activeSources(){return this.inCrossfadeMode?this.crossfadeChain.map(t=>t.source):[this.source]}stopAllSources(t){for(let e of this.activeSources())try{t===0?e.stop():e.stop(t);}catch{}}pause(){if(this.done||this.paused)return;let t=this.computeOffset();this.pausedOffset=t,this.currentOffset=t,this.paused=true,this.regionTimer!=null&&(clearTimeout(this.regionTimer),this.regionTimer=null),this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null);for(let e of this.activeSources()){try{e.onended=null,e.stop();}catch{}try{e.disconnect();}catch{}}this.inCrossfadeMode&&(this.crossfadeChain=[]),this.emit("paused");}resume(){if(!(this.done||!this.paused)){if(this.paused=false,this.startCtxTime=this.ctx.currentTime,this.inCrossfadeMode)this.source=this.startCrossfadeChain(this.startCtxTime);else {this.source=this.createSourceNode(this.basePitch),this.bindSourceLifecycle(this.source,()=>{});try{this.source.start(0,this.pausedOffset);}catch{}if(this.regionDuration!=null){let t=Math.max(0,this.pausedOffset-this.startOffset),e=Math.max(0,this.regionDuration-t);this.armRegionTimer(e);}}this.emit("resumed");}}get isPaused(){return this.paused}setPlaybackRate(t,e={}){if(this.done)return;let i=Math.max(0,t),s=Math.max(0,e.duration??0);if(this.paused||(this.currentOffset=this.computeOffset(),this.startCtxTime=this.ctx.currentTime),this.basePitch=i,!this.paused){if(this.regionTimer!=null&&this.regionDuration!=null){let r=Math.max(0,this.currentOffset-this.startOffset);this.armRegionTimer(Math.max(0,this.regionDuration-r));}for(let r of this.activeSources()){let n=r.playbackRate;s===0?n.value=i:S(n,this.ctx.currentTime,i,s,e.curve??"linear");}}}get playbackRate(){return this.basePitch}get spatializer(){return this._spatializer}level(){if(this.done)return {rms:0,peak:0};if(!this.levelAnalyser){let s=this.ctx.createAnalyser();s.fftSize=512,this.gain.connect(s),this.levelAnalyser=s,this.levelBuf=new Float32Array(s.fftSize);}let t=this.levelBuf;this.levelAnalyser.getFloatTimeDomainData(t);let e=0,i=0;for(let s=0;s<t.length;s++){let r=t[s]??0;e+=r*r;let n=Math.abs(r);n>i&&(i=n);}return {rms:Math.sqrt(e/t.length),peak:i}}levelHint(){return this.done?0:this.levelAnalyser?this.level().rms:this.gain.gain.value}async*cues(){if(this.done){yield "ended";return}let t=[],e=null,i=r=>{if(e){let n=e;e=null,n({value:r,done:false});}else t.push(r);},s=r=>i(r);this.cueListeners.add(s);try{for(;;){if(t.length>0){let n=t.shift();if(yield n,n==="ended")return;continue}if(this.done){yield "ended";return}let r=await new Promise(n=>{e=n;});if(r.done||(yield r.value,r.value==="ended"))return}}finally{this.cueListeners.delete(s);}}finish(t,e){if(!this.done){this.done=true,this.regionTimer!=null&&(clearTimeout(this.regionTimer),this.regionTimer=null),this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null);try{for(let i of this.activeSources())i.disconnect();for(let i of this.crossfadeChain)i.gain.disconnect();this.levelAnalyser?.disconnect(),this.gain.disconnect();}catch{}this.levelAnalyser=null,this.levelBuf=null,this.crossfadeChain=[],this.emit(t),this.resolveEnded(),e?.(this);}}emit(t){for(let e of this.cueListeners)e(t);}createSourceNode(t){let e=this.ctx.createBufferSource();return e.buffer=this.buffer,e.loop=this.loop,this.loop&&this.loopStart!=null&&(e.loopStart=this.loopStart),this.loop&&this.loopEnd!=null&&(e.loopEnd=this.loopEnd),e.playbackRate.value=t,e.connect(this.gain),e}armRegionTimer(t){if(this.regionTimer!=null&&(clearTimeout(this.regionTimer),this.regionTimer=null),t==null||this.loop)return;let e=Math.max(0,t*1e3)/Math.max(1e-4,this.basePitch);this.regionTimer=setTimeout(()=>{this.regionTimer=null,this.done||this.stop();},e);}bindSourceLifecycle(t,e){t.onended=()=>{this.paused||t.loop||this.finish("ended",e);};}startCrossfadeChain(t){let e=this.spawnCrossfadeSegment(t,false);return this.armNextCrossfadeSegment(t),e.source}spawnCrossfadeSegment(t,e){let i=this.ctx.createBufferSource();i.buffer=this.buffer,i.loop=false,i.playbackRate.value=this.basePitch;let s=this.ctx.createGain();e?(s.gain.setValueAtTime(0,t),s.gain.setValueCurveAtTime(P(0,1),t,this.crossfadeSec)):s.gain.setValueAtTime(1,t);let r=t+this.crossfadeRegionLen-this.crossfadeSec;s.gain.setValueAtTime(1,r),s.gain.setValueCurveAtTime(P(1,0),r,this.crossfadeSec),i.connect(s).connect(this.gain);try{i.start(t,this.crossfadeRegionStart,this.crossfadeRegionLen);}catch{}i.onended=()=>this.releaseCrossfadeSegment(i,s);let n={source:i,gain:s,startTime:t};return this.crossfadeChain.push(n),n}armNextCrossfadeSegment(t){this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null);let e=t+this.crossfadeRegionLen-this.crossfadeSec,s=Math.max(0,(e-this.ctx.currentTime)*1e3-50);this.crossfadeArmTimer=setTimeout(()=>{this.crossfadeArmTimer=null,!(this.done||this.stopping||this.paused)&&(this.spawnCrossfadeSegment(e,true),this.armNextCrossfadeSegment(e));},s);}releaseCrossfadeSegment(t,e){let i=this.crossfadeChain.findIndex(s=>s.source===t);i>=0&&this.crossfadeChain.splice(i,1);try{t.disconnect(),e.disconnect();}catch{}}get inCrossfadeMode(){return this.crossfadeSec>0}computeOffset(){if(this.paused)return this.pausedOffset;let t=(this.ctx.currentTime-this.startCtxTime)*this.basePitch,e=this.currentOffset+t;return this.loop?e=(e%this.buffer.duration+this.buffer.duration)%this.buffer.duration:e=Math.min(e,this.buffer.duration),e}};function xt(o,t=1){if(typeof o=="number")return o;if(!o)return t;let e=o.base??t;return o.jitter==null?e:e+(Math.random()*2-1)*o.jitter}function At(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}var R=class{name;deps;constructor(t,e){this.name=t,this.deps=e;}get duration(){return this.deps.buffer.duration}play(t={}){let e=t.bus??this.deps.defaultBus,i=this.deps.resolveBusInput(e),s=this.deps.resolveSpatializer?.(e,t.spatializer),r=s?s.connectInto(i):i,n=new I({ctx:this.deps.ctx,buffer:this.deps.buffer,destination:r,options:{...t,bus:e},spatializer:s,sourceName:this.deps.sourceName??this.name,defaultStopFade:this.deps.defaultStopFade,onEnded:u=>{this.deps.releaseVoice(u,e),s?.dispose();}});return this.deps.trackVoice(n,e),(this.deps.applyConcurrency?.(n,e)??true)||n.stop(),n}};var G=class{name;regions;sound;constructor(t,e,i){this.name=t,this.sound=e,this.regions={...i};}list(){return Object.keys(this.regions)}has(t){return t in this.regions}region(t){let e=this.regions[t];if(!e)throw new A(`${this.name}#${t}`);return e}play(t,e={}){let i=this.region(t),s=e.loop??i.loop??false;return this.sound.play({...e,loop:s,offset:i.start,duration:i.duration,loopStart:i.start,loopEnd:i.start+i.duration})}};var z=class{name;ctx;url;destination;el=null;node=null;gain=null;disposed=false;constructor(t,e,i,s){this.name=t,this.ctx=e,this.url=i,this.destination=s;}ensure(){if(this.el||this.disposed||typeof document>"u"||typeof Audio>"u")return;let t=new Audio;t.src=this.url,t.crossOrigin="anonymous",t.preload="auto";let e=this.ctx.createMediaElementSource;if(typeof e!="function"){this.el=t;return}let i=e.call(this.ctx,t),s=this.ctx.createGain();i.connect(s),s.connect(this.destination),this.el=t,this.node=i,this.gain=s;}async play(t={}){if(this.ensure(),!!this.el){this.gain&&(this.gain.gain.value=dt(t.volume??1)),this.el.loop=t.loop??false;try{await this.el.play();}catch{}}}pause(){this.el?.pause();}stop(){if(this.el){this.el.pause();try{this.el.currentTime=0;}catch{}}}seek(t){if(this.el)try{this.el.currentTime=Math.max(0,t);}catch{}}get currentTime(){return this.el?.currentTime??0}get duration(){return this.el?.duration??0}get paused(){return this.el?.paused??true}setVolume(t){this.gain&&(this.gain.gain.value=dt(t));}fade(t){return this.gain?(S(this.gain.gain,this.ctx.currentTime,dt(t.to),t.duration,t.curve??"linear"),w(this.ctx,t.duration)):Promise.resolve()}dispose(){this.disposed=true;try{this.node?.disconnect(),this.gain?.disconnect();}catch{}this.el&&(this.el.pause(),this.el.src=""),this.el=null,this.node=null,this.gain=null;}};function dt(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}var U=class{name;count;sounds;strategy;lastIndex=-1;bag=[];constructor(t,e,i={}){if(e.length===0)throw new Error(`Variants "${t}" requires at least one sound`);this.name=t,this.sounds=e,this.count=e.length,this.strategy=i.strategy??"no-repeat";}get lastPick(){return this.lastIndex}play(t={}){return this.sounds[this.pick()].play(t)}playIndex(t,e={}){let i=(t%this.count+this.count)%this.count;return this.lastIndex=i,this.sounds[i].play(e)}pick(){let t=this.count;if(t===1)return 0;if(this.strategy==="random"){let i=Math.floor(Math.random()*t);return this.lastIndex=i,i}if(this.strategy==="shuffle-bag"){if(this.bag.length===0){this.bag=Array.from({length:t},(s,r)=>r);for(let s=t-1;s>0;s--){let r=Math.floor(Math.random()*(s+1));[this.bag[s],this.bag[r]]=[this.bag[r],this.bag[s]];}t>1&&this.bag[0]===this.lastIndex&&([this.bag[0],this.bag[1]]=[this.bag[1],this.bag[0]]);}let i=this.bag.shift();return this.lastIndex=i,i}let e=Math.floor(Math.random()*(t-1));return e>=this.lastIndex&&e++,this.lastIndex=e,e}};var jt="inverse";var q=class{ctx;kind;input;output;stereoPan=null;panner=null;occlusionFilter=null;occlusionGain=null;constructor(t,e){if(this.ctx=t,e.position){let i=t.createPanner();i.panningModel="HRTF",i.distanceModel=e.distanceModel??jt,i.refDistance=e.refDistance??1,i.maxDistance=e.maxDistance??1e4,i.rolloffFactor=e.rolloffFactor??1;let[s,r,n]=e.position;this.setPanner3D(i,s,r,n);let a=t.createBiquadFilter();a.type="lowpass",a.frequency.value=22050,a.Q.value=Math.SQRT1_2;let u=t.createGain();u.gain.value=1,i.connect(a).connect(u),this.panner=i,this.occlusionFilter=a,this.occlusionGain=u,this.input=i,this.output=u,this.kind="3d",e.occlusion!=null&&this.setOcclusion(e.occlusion);}else {let i=t.createStereoPanner();i.pan.value=Ct(e.pan??0),this.stereoPan=i,this.input=i,this.output=i,this.kind="2d";}}setPan(t){this.kind!=="2d"||!this.stereoPan||(this.stereoPan.pan.value=Ct(t));}setPosition(t,e,i){this.kind!=="3d"||!this.panner||this.setPanner3D(this.panner,t,e,i);}setRefDistance(t){this.panner&&(this.panner.refDistance=Math.max(0,t));}setMaxDistance(t){this.panner&&(this.panner.maxDistance=Math.max(0,t));}setRolloffFactor(t){this.panner&&(this.panner.rolloffFactor=Math.max(0,t));}setDistanceModel(t){this.panner&&(this.panner.distanceModel=t);}setOcclusion(t){if(!this.occlusionFilter||!this.occlusionGain)return;let e=Zt(t),i=22050*(500/22050)**e,s=this.ctx.currentTime;this.occlusionFilter.frequency.setValueAtTime(i,s);let r=10**(-6*e/20);this.occlusionGain.gain.setValueAtTime(r,s);}connectInto(t){return this.output.connect(t),this.input}dispose(){try{this.input.disconnect(),this.occlusionFilter?.disconnect(),this.occlusionGain?.disconnect();}catch{}}setPanner3D(t,e,i,s){if(typeof t.positionX?.setValueAtTime=="function"){let r=this.ctx.currentTime;t.positionX.setValueAtTime(e,r),t.positionY.setValueAtTime(i,r),t.positionZ.setValueAtTime(s,r);}else t.setPosition?.(e,i,s);}};function Ct(o){return Math.max(-1,Math.min(1,o))}function Zt(o){return Number.isNaN(o)?0:Math.max(0,Math.min(1,o))}var H=class{input;headroomDb;ctx;limiterNode=null;limiterCfg;destination;_meterAnalyser=null;_meterBuf=null;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.headroomDb=e.headroom??0,this.input.gain.value=Tt(this.headroomDb),this.destination=t.destination,this.limiterCfg=e.limiter??null,this.rewire();}setHeadroom(t){this.headroomDb=t,S(this.input.gain,this.ctx.currentTime,Tt(t),.01,"linear");}get headroom(){return this.headroomDb}setLimiter(t){this.limiterCfg=t,this.rewire();}get reduction(){return this.limiterNode?.reduction??0}meter(){if(!this._meterAnalyser){let s=this.ctx.createAnalyser();s.fftSize=1024,this.input.connect(s),this._meterAnalyser=s,this._meterBuf=new Float32Array(s.fftSize);}let t=this._meterBuf;this._meterAnalyser.getFloatTimeDomainData(t);let e=0,i=0;for(let s=0;s<t.length;s++){let r=t[s]??0;e+=r*r;let n=Math.abs(r);n>i&&(i=n);}return {rms:Math.sqrt(e/t.length),peak:i}}dispose(){try{this.input.disconnect(),this.limiterNode?.disconnect(),this._meterAnalyser?.disconnect();}catch{}this.limiterNode=null,this._meterAnalyser=null,this._meterBuf=null;}rewire(){try{this.input.disconnect(),this.limiterNode?.disconnect();}catch{}if(this.limiterNode=null,this.limiterCfg){let t=this.limiterCfg,e=this.ctx.createDynamicsCompressor();e.threshold.value=t.threshold??-1,e.knee.value=0,e.ratio.value=Math.max(20,t.ratio??20),e.attack.value=t.attack??.001,e.release.value=t.release??.05,this.input.connect(e),e.connect(this.destination),this.limiterNode=e;}else this.input.connect(this.destination);this._meterAnalyser&&this.input.connect(this._meterAnalyser);}};function Tt(o){return 10**(o/20)}var $=class{name;state;getBus;getParam;constructor(t,e,i,s){this.name=t,this.state=e,this.getBus=i,this.getParam=s;}apply(t={}){let e=t.fade??0,i=[];for(let[s,r]of Object.entries(this.state.buses)){let n=this.getBus(s);n&&(n.muted=r.muted,i.push(n.fadeTo(r.level,e)));}for(let[s,r]of Object.entries(this.state.parameters)){let n=this.getParam(s);n&&n.set(r);}return Promise.all(i).then(()=>{})}blendWith(t,e){let i=e<0?0:e>1?1:e,s=1-i;for(let[r,n]of Object.entries(this.state.buses)){let a=t.state.buses[r];if(!a)continue;let u=this.getBus(r);u&&(u.muted=i<.5?n.muted:a.muted,u.level=n.level*s+a.level*i);}for(let[r,n]of Object.entries(this.state.parameters)){let a=t.state.parameters[r];if(a===void 0)continue;let u=this.getParam(r);u&&u.set(n*s+a*i);}}};function Xt(o={}){return new pt(o)}var pt=class{host;decoder;scheduler=null;master=null;buses=new Map;busOrder=[];sounds=new Map;internalSounds=new Map;sprites=new Map;streams=new Map;musics=new Map;variantsByName=new Map;busGroups=new Map;soloedBuses=new Set;soundUrls=new Map;voices=new Map;parameters=new Map;config;constructor(t){this.config=t,this.host=new X({autoPauseOnHidden:t.autoPauseOnHidden,latencyHint:t.latencyHint}),this.decoder=new Y(()=>this.host.touch(),t.cache??{});let e=Object.keys(t.buses??{});this.busOrder=e.length>0?e:["default"];for(let i of this.busOrder)this.voices.set(i,new Set);}get state(){return this.host.state}get now(){return this.host.now}get context(){return this.host.touch()}async unlock(){await this.host.unlock(),this.ensureGraph();}async close(){if(this.host.state!=="closed"){for(let t of this.voices.values()){for(let e of t)e.stop();t.clear();}this.scheduler?.dispose(),this.scheduler=null;for(let t of this.buses.values()){for(let e of t.fx())e.dispose();t.dispose();}this.buses.clear(),this.master?.dispose(),this.master=null,this.sounds.clear(),this.internalSounds.clear(),this.sprites.clear();for(let t of this.musics.values())t.stopAll({fade:0});this.musics.clear(),this.variantsByName.clear(),this.busGroups.clear(),this.soloedBuses.clear(),this.soundUrls.clear();for(let t of this.streams.values())t.dispose();this.streams.clear(),this.parameters.clear(),this.decoder.clear(),await this.host.close();}}async loadSound(t,e,i={}){return this.loadSoundAs(t,t,e,i,false)}async loadSoundAs(t,e,i,s,r){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let n={signal:s.signal},a=await this.resolveBuffer(t,i,n);return s.normalize&&(a=k(a,s.normalize,this.host.touch())),this.soundUrls.set(t,typeof i=="string"?[i]:[...i]),this.registerSound(t,e,a,{bus:s.bus},r)}async resolveBuffer(t,e,i){let s=this.config.resolveAsset;if(s){let n=await s({name:t,url:e,signal:i.signal});if(n!=null){if(n instanceof AudioBuffer)return n;if(n instanceof ArrayBuffer)return await this.host.touch().decodeAudioData(n.slice(0));if(typeof n=="string")return await this.decoder.load(n,i)}}let r=typeof e=="string"?[e]:ht(e);return await this.decoder.loadFirst(r,i)}async preload(t,e={}){if(this.host.state==="closed")throw new x;if(t.length===0)return;let i=Math.max(1,e.concurrency??wt),s=e.onProgress,r=e.signal,n=t.length,a=0,u=[],c=0,l=Math.min(i,n),d=[];for(let p=0;p<l;p++)d.push((async()=>{for(;;){let b=c++;if(b>=n)return;if(r?.aborted)throw r.reason??new DOMException("preload aborted","AbortError");let h=t[b],v=Kt(r,h.options?.signal),f={...h.options??{},signal:v};try{await this.loadSound(h.name,h.url,f),a++,s?.({name:h.name,status:"loaded",completed:a,total:n});}catch(y){if(y.name==="AbortError")throw y;a++,u.push({name:h.name,cause:y}),s?.({name:h.name,status:"failed",error:y,completed:a,total:n});}}})());let g=(await Promise.allSettled(d)).find(p=>p.status==="rejected");if(g&&g.status==="rejected")throw g.reason;if(u.length>0)throw new N(u)}async loadSprite(t,e,i,s={}){let r=await this.loadSoundAs(`__sprite:${t}`,t,e,s,true),n=new G(t,r,i);return this.sprites.set(t,n),n}sprite(t){let e=this.sprites.get(t);if(!e)throw new A(t,C(t,[...this.sprites.keys()]));return e}hasSprite(t){return this.sprites.has(t)}async loadVariants(t,e,i={}){if(e.length===0)throw new Error(`engine.loadVariants("${t}") requires at least one URL set`);let{strategy:s,...r}=i,n=await Yt(e,wt,(u,c)=>this.loadSoundAs(`__variant:${t}:${c}`,t,u,r,true)),a=new U(t,n,{strategy:s});return this.variantsByName.set(t,a),a}variants(t){let e=this.variantsByName.get(t);if(!e)throw new A(t,C(t,[...this.variantsByName.keys()]));return e}hasVariants(t){return this.variantsByName.has(t)}async loadMusic(t,e,i={}){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let s={signal:i.signal},[r,n,a]=await Promise.all([this.resolveBuffer(`__music:${t}:loop`,e.loop,s),e.intro?this.resolveBuffer(`__music:${t}:intro`,e.intro,s):Promise.resolve(void 0),e.outro?this.resolveBuffer(`__music:${t}:outro`,e.outro,s):Promise.resolve(void 0)]),u=this.host.touch(),c={intro:n?i.normalize?k(n,i.normalize,u):n:void 0,loop:i.normalize?k(r,i.normalize,u):r,outro:a?i.normalize?k(a,i.normalize,u):a:void 0},l=i.bus??this.busOrder[0],d=this.buses.get(l);if(!d)throw new T(l,C(l,[...this.buses.keys()]));let m=new D(t,{ctx:this.host.touch(),buffers:c,destination:d.input,loopCrossfade:i.loopCrossfade??0,defaultStopFade:this.config.voice?.stopFade});return this.musics.set(t,m),m}music(t){let e=this.musics.get(t);if(!e)throw new A(t,C(t,[...this.musics.keys()]));return e}hasMusic(t){return this.musics.has(t)}loadStream(t,e,i={}){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let s=typeof e=="string"?e:lt(e),r=i.bus??this.busOrder[0],n=this.buses.get(r);if(!n)throw new T(r,C(r,[...this.buses.keys()]));let a=new z(t,this.host.touch(),s,n.input);return this.streams.set(t,a),a}stream(t){let e=this.streams.get(t);if(!e)throw new A(t,C(t,[...this.streams.keys()]));return e}hasStream(t){return this.streams.has(t)}crossfade(t,e,i={}){let s=i.duration??1.5,r=i.curve??"equal-power",n=i.toVolume??1,u=this.sound(e).play({bus:i.bus,loop:i.loop??true,volume:0});u.fade({to:n,duration:s,curve:r}).catch(()=>{});let c=this.activeVoices().filter(l=>l!==u&&l.sourceName===t&&l.bus===u.bus);for(let l of c)l.fade({to:0,duration:s,curve:r}).then(()=>l.stop()).catch(()=>{});return u}createSound(t,e,i={}){return this.registerSound(t,t,e,i,false)}registerSound(t,e,i,s,r){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let n=s.bus??this.busOrder[0];if(!this.buses.has(n))throw new T(n,C(n,[...this.buses.keys()]));let a=new R(t,{ctx:this.host.touch(),buffer:i,defaultBus:n,sourceName:e,defaultStopFade:this.config.voice?.stopFade,resolveBusInput:u=>{let c=this.buses.get(u);if(!c)throw new T(u,C(u,[...this.buses.keys()]));return c.input},resolveSpatializer:(u,c)=>{if(c)return new q(this.host.touch(),c)},trackVoice:(u,c)=>{this.voices.get(c)?.add(u),this.buses.get(c)?.trackVoice(u);},releaseVoice:(u,c)=>{this.voices.get(c)?.delete(u),this.buses.get(c)?.releaseVoice(u);},applyConcurrency:(u,c)=>{let l=this.buses.get(c);if(!l)return true;let d=false,m=l.applyConcurrencyOnSpawn(u,()=>{d=true;});return m&&(this.voices.get(c)?.delete(m),l.releaseVoice(m)),d&&(this.voices.get(c)?.delete(u),l.releaseVoice(u)),!d}});return (r?this.internalSounds:this.sounds).set(t,a),a}removeSound(t){this.sounds.delete(t);}unloadSound(t,e={}){if(this.sounds.delete(t),e.evictBuffer??true){let i=this.soundUrls.get(t);if(i)for(let s of i)this.decoder.evict(s);}this.soundUrls.delete(t);}hasSound(t){return this.sounds.has(t)}sound(t){let e=this.sounds.get(t);if(!e)throw new A(t,C(t,[...this.sounds.keys()]));return e}bus(t){this.ensureGraph();let e=this.buses.get(t);if(!e)throw new T(t,C(t,[...this.buses.keys()]));return e}busGroup(t,e){if(e!=null){let s=new L(t,e);return this.busGroups.set(t,s),s}let i=this.busGroups.get(t);if(!i)throw new T(t,C(t,[...this.busGroups.keys()]));return i}masterMeter(){return this.ensureGraph(),this.master.meter()}scheduleAt(t,e){return this.host.touch(),this.ensureGraph(),this.scheduler.scheduleAt(t,e)}activeVoices(){let t=[];for(let e of this.voices.values())for(let i of e)t.push(i);return t}onStateChange(t){return this.host.onStateChange(t)}parameter(t,e=0){let i=this.parameters.get(t);return i||(i=new V(t,e),this.parameters.set(t,i)),i}captureSnapshot(t){let e={};for(let[s,r]of this.buses)e[s]={level:r.level,muted:r.muted};let i={};for(let[s,r]of this.parameters)i[s]=r.value;return this.snapshot(t,{buses:e,parameters:i})}snapshot(t,e){return new $(t,e,i=>this.buses.get(i),i=>this.parameters.get(i))}blendSnapshots(t,e,i){t.blendWith(e,i);}ensureGraph(){if(this.master)return;let t=this.host.touch();this.master=new H(t,this.config.master),this.scheduler=new K(this.host,this.config.tickSource);for(let e of this.busOrder){let i=this.config.buses?.[e]??{},s=new F(t,e,i);s.output.connect(this.master.input),s.notifySoloChange=(r,n)=>this.handleSoloChange(r,n),this.buses.set(e,s),this.voices.has(e)||this.voices.set(e,new Set);}}handleSoloChange(t,e){e?this.soloedBuses.add(t):this.soloedBuses.delete(t);let i=this.soloedBuses.size>0;for(let s of this.buses.values())i?s.applySoloVeil(!this.soloedBuses.has(s)):s.applySoloVeil(false);}},wt=4;async function Yt(o,t,e){let i=new Array(o.length),s=0,r=async()=>{for(;;){let a=s++;if(a>=o.length)return;i[a]=await e(o[a],a);}},n=Array.from({length:Math.min(t,o.length)},r);return await Promise.all(n),i}function C(o,t){if(t.length===0)return null;let e=null,i=1/0;for(let n of t){let a=Qt(o,n);a<i&&(i=a,e=n);}let s=Math.max(o.length,e?.length??0),r=Math.max(1,Math.ceil(s/2));return e&&i<=r?e:null}function Kt(o,t){if(!o)return t;if(!t||o.aborted)return o;if(t.aborted)return t;let e=new AbortController,i=()=>{o.removeEventListener("abort",s),t.removeEventListener("abort",r);},s=()=>{i(),e.abort(o.reason);},r=()=>{i(),e.abort(t.reason);};return o.addEventListener("abort",s),t.addEventListener("abort",r),e.signal}function Qt(o,t){if(o===t)return 0;if(o.length===0)return t.length;if(t.length===0)return o.length;let e=new Array(t.length+1),i=new Array(t.length+1);for(let s=0;s<=t.length;s++)e[s]=s;for(let s=1;s<=o.length;s++){i[0]=s;for(let r=1;r<=t.length;r++){let n=o.charCodeAt(s-1)===t.charCodeAt(r-1)?0:1;i[r]=Math.min(i[r-1]+1,e[r]+1,e[r-1]+n);}for(let r=0;r<=t.length;r++)e[r]=i[r];}return e[t.length]}export{B as AggregateDecodeError,F as Bus,L as BusGroup,T as BusNotFoundError,et as Compressor,M as DecodeError,it as Ducker,x as EngineClosedError,st as Filter,H as Master,D as Music,Q as MusicVoice,V as Parameter,N as PreloadError,rt as Reverb,Z as Send,$ as Snapshot,R as Sound,A as SoundNotFoundError,q as Spatializer,G as Sprite,z as StreamSound,ot as StretchProcessor,U as Variants,I as Voice,_ as ZvukError,k as applyLoudnessNormalization,ut as canPlay,yt as computeNormalizationGain,Xt as createEngine,_t as createStretchWorkletNode,Ot as ensureStretchWorklet,ct as mimeForUrl,lt as pickSource,ht as pickSourceOrder};//# sourceMappingURL=index.js.map
|
|
69
|
+
registerProcessor('${vt}', ZvukRealtimeStretchProcessor);
|
|
70
|
+
`;async function Pt(o){if(gt.has(o))return;let t=o.audioWorklet;if(!t)throw new Error("AudioWorklet not supported in this context");let e=new Blob([_t],{type:"application/javascript"}),i=URL.createObjectURL(e);try{await t.addModule(i);}finally{URL.revokeObjectURL(i);}gt.add(o);}function kt(o,t={}){let e=globalThis.AudioWorkletNode;if(!e)throw new Error("AudioWorkletNode not available");let i=new e(o,vt,{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2],processorOptions:{grainSize:t.grainSize??1024}}),s=i.parameters.get("stretch");s&&t.stretchFactor!=null&&(s.value=t.stretchFactor);let r=i;return Object.defineProperty(r,"stretch",{value:s,enumerable:true}),r.dispose=()=>{try{i.disconnect();}catch{}},r}function w(o,t,e){let i=Math.max(0,t);return i===0?Promise.resolve():new Promise(s=>{let r=null,n=false,a=()=>{n||(n=true,r?.(),r=null,s());};e&&e.then(a,a),r=O(o,i,a);})}function O(o,t,e){let i=Math.max(0,t);if(o.state!=="running"){let u=setTimeout(e,i*1e3);return ()=>clearTimeout(u)}let s=o.currentTime+i,r=null,n=false,a=()=>{if(r=null,n)return;let u=s-o.currentTime;if(u<=0||o.state==="closed"){e();return}r=setTimeout(a,Math.min(u*1e3,250));};return r=setTimeout(a,i*1e3),()=>{n=true,r!=null&&clearTimeout(r),r=null;}}function x(o,t,e,i,s){let r=Math.max(0,i),n=o.value;if(Nt(o,t,n),r===0){at(o,e,()=>o.setValueAtTime(e,t));return}if(s==="linear"){at(o,e,()=>o.linearRampToValueAtTime(e,t+r));return}let a=yt(n,e,s,64);at(o,e,()=>o.setValueCurveAtTime(a,t,r));}function Nt(o,t,e){let i=o;if(typeof i.cancelAndHoldAtTime=="function")try{i.cancelAndHoldAtTime(t);}catch{o.cancelScheduledValues(t);}else o.cancelScheduledValues(t);try{o.setValueAtTime(e,t);}catch{}}function at(o,t,e){try{e();}catch{o.value=t;}}function bt(o,t,e=33){return yt(o,t,"equal-power",e)}function Y(o,t,e,i,s){try{s.fadeIn?(o.setValueAtTime(0,t),o.setValueCurveAtTime(bt(0,1),t,i)):o.setValueAtTime(1,t);}catch{o.value=1;}if(!s.fadeOut)return;let r=t+e-i;try{o.setValueAtTime(1,r),o.setValueCurveAtTime(bt(1,0),r,i);}catch{}}function yt(o,t,e,i){let s=new Float32Array(i),r=t>=o;for(let n=0;n<i;n++){let a=n/(i-1),u=Bt(a,e,r);s[n]=o+(t-o)*u;}return s}function Bt(o,t,e=true){switch(t){case "easeIn":return o*o;case "easeOut":return 1-(1-o)*(1-o);case "easeInOut":return o<.5?2*o*o:1-2*(1-o)*(1-o);case "equal-power":return e?Math.sin(o*Math.PI/2):1-Math.cos(o*Math.PI/2);default:return o}}var Z=class{source;target;post;gainNode;ctx;disposed=false;constructor(t,e,i,s){this.source=t,this.target=e,this.post=i.post??true,this.ctx=s,this.gainNode=s.createGain(),this.gainNode.gain.value=E(i.amount??1),(this.post?t.output:t.input).connect(this.gainNode),this.gainNode.connect(e.input);}get amount(){return this.gainNode.gain.value}set amount(t){this.disposed||x(this.gainNode.gain,this.ctx.currentTime,E(t),.01,"linear");}fadeTo(t,e,i="linear"){return this.disposed?Promise.resolve():(x(this.gainNode.gain,this.ctx.currentTime,E(t),e,i),w(this.ctx,e))}dispose(){if(!this.disposed){this.disposed=true;try{this.gainNode.disconnect();}catch{}}}},F=class{name;input;fxInput;output;_level;_muted;_soloed=false;_soloVeiled=false;ctx;_concurrency;_voices=new Set;_fxChain=[];_sends=[];_meterAnalyser=null;_meterBuf=null;notifySoloChange;constructor(t,e,i={}){this.ctx=t,this.name=e,this._level=i.level??1,this._muted=i.mute??false,this._concurrency=i.concurrency??null,this.input=t.createGain(),this.fxInput=t.createGain(),this.output=t.createGain(),this.input.connect(this.fxInput),this.fxInput.connect(this.output),this.output.gain.value=this._muted?0:this._level;}get level(){return this._level}set level(t){this._level=E(t),!this._muted&&!this._soloVeiled&&this.rampOutput(this._level,.01);}get muted(){return this._muted}set muted(t){this._muted!==t&&(this._muted=t,this.rampOutput(t||this._soloVeiled?0:this._level,.01));}fadeTo(t,e,i="linear"){let s=E(t);return this._level=s,this._muted||this._soloVeiled?w(this.ctx,e):this.ramp(s,e,i)}get voiceCount(){return this._voices.size}voices(){return Array.from(this._voices)}get concurrency(){return this._concurrency}setConcurrency(t){this._concurrency=t;}applyConcurrencyOnSpawn(t,e){let i=this._concurrency;if(!i||this._voices.size<=i.max)return null;let s=i.steal??"oldest";if(s==="none")return e(),null;let r=Et(this._voices,s,t);return r?(r.stop(),r):(e(),null)}trackVoice(t){this._voices.add(t);}releaseVoice(t){this._voices.delete(t);}addFx(t){this._fxChain.push(t),this.rewireFxChain();}removeFx(t){let e=this._fxChain.indexOf(t);e!==-1&&(this._fxChain.splice(e,1),this.rewireFxChain());}fx(){return [...this._fxChain]}meter(){if(!this._meterAnalyser){let s=this.ctx.createAnalyser();s.fftSize=1024,this.output.connect(s),this._meterAnalyser=s,this._meterBuf=new Float32Array(s.fftSize);}let t=this._meterBuf;this._meterAnalyser.getFloatTimeDomainData(t);let e=0,i=0;for(let s=0;s<t.length;s++){let r=t[s]??0;e+=r*r;let n=Math.abs(r);n>i&&(i=n);}return {rms:Math.sqrt(e/t.length),peak:i}}send(t,e={}){let i=new Z(this,t,e,this.ctx);return this._sends.push(i),i}removeSend(t){let e=this._sends.indexOf(t);e!==-1&&(this._sends.splice(e,1),t.dispose());}sends(){return [...this._sends]}solo(t=true){this._soloed!==t&&(this._soloed=t,this.notifySoloChange?.(this,t));}unsolo(){this.solo(false);}get soloed(){return this._soloed}applySoloVeil(t){this._soloVeiled=t;let e=this._muted||t?0:this._level;this.rampOutput(e,.01);}rewireFxChain(){try{this.fxInput.disconnect();for(let e of this._fxChain)e.output.disconnect();}catch{}let t=this.fxInput;for(let e of this._fxChain)t.connect(e.input),t=e.output;t.connect(this.output);}rampOutput(t,e){this.ramp(t,e,"linear");}ramp(t,e,i){let s=this.output.gain,r=this.ctx.currentTime;return x(s,r,t,e,i),w(this.ctx,e)}dispose(){for(let t of this._sends)t.dispose();this._sends=[];for(let t of this._fxChain)t.dispose();this._fxChain=[];try{this.input.disconnect(),this.fxInput.disconnect(),this.output.disconnect(),this._meterAnalyser?.disconnect();}catch{}this._meterAnalyser=null,this._meterBuf=null;}};function E(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}function Et(o,t,e){let i=t==="quietest"?new Map:null;if(i)for(let r of o)r!==e&&i.set(r,r.levelHint());let s=null;for(let r of o)if(r!==e){if(!s){s=r;continue}switch(t){case "oldest":r.startedAt<s.startedAt&&(s=r);break;case "lowest-priority":r.priority<s.priority&&(s=r);break;case "quietest":{let n=i?.get(r)??0,a=i?.get(s)??0;n<a&&(s=r);break}}}return s}var L=class{name;members;constructor(t,e){this.name=t,this.members=e;}set level(t){for(let e of this.members)e.level=t;}get level(){if(this.members.length===0)return 0;let t=0;for(let e of this.members)t+=e.level;return t/this.members.length}set muted(t){for(let e of this.members)e.muted=t;}get muted(){return this.members.length===0?false:this.members.every(t=>t.muted)}fadeTo(t,e,i="linear"){return Promise.all(this.members.map(s=>s.fadeTo(t,e,i))).then(()=>{})}solo(t=true){for(let e of this.members)e.solo(t);}unsolo(){this.solo(false);}};var V=class{name;_value;subs=new Set;constructor(t,e){this.name=t,this._value=e;}get value(){return this._value}set(t){if(t!==this._value){this._value=t;for(let e of this.subs)e(t);}}subscribe(t){return this.subs.add(t),t(this._value),()=>this.subs.delete(t)}bindTo(t,e={}){let i=e.from??0,s=e.to??1,r=e.curve??"linear",n=s>=i;return this.subscribe(a=>{let u=Math.max(0,Math.min(1,a)),c=Ft(u,r,n);t(i+(s-i)*c);})}};function Ft(o,t,e=true){switch(t){case "easeIn":return o*o;case "easeOut":return 1-(1-o)*(1-o);case "easeInOut":return o<.5?2*o*o:1-2*(1-o)*(1-o);case "equal-power":return e?Math.sin(o*Math.PI/2):1-Math.cos(o*Math.PI/2);default:return o}}var Lt={webm:'audio/webm; codecs="opus"',opus:'audio/ogg; codecs="opus"',ogg:'audio/ogg; codecs="vorbis"',m4a:'audio/mp4; codecs="mp4a.40.2"',mp4:'audio/mp4; codecs="mp4a.40.2"',aac:'audio/mp4; codecs="mp4a.40.2"',mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac"},ut=null;function ct(o){if(typeof document>"u")return true;if(!ut)try{ut=document.createElement("audio");}catch{return true}let t=ut.canPlayType(o);return t==="probably"||t==="maybe"}function lt(o){let t=/\.([a-z0-9]+)(?:[?#]|$)/i.exec(o);return t?.[1]?Lt[t[1].toLowerCase()]??null:null}function ht(o){if(o.length===0)throw new Error("pickSource requires at least one URL");for(let t of o){let e=lt(t);if(e&&ct(e))return t}return o[0]}function dt(o){if(o.length===0)return o;let t=[],e=[];for(let i of o){let s=lt(i);s&&ct(s)?t.push(i):e.push(i);}return [...t,...e]}var X=class{_ctx=null;_state="cold";_unlocking=null;_listeners=new Set;opts;constructor(t={}){this.opts=t;}get state(){return this._state}touch(){if(this._state==="closed")throw new S;if(!this._ctx){let t={};this.opts.latencyHint!=null&&(t.latencyHint=this.opts.latencyHint);let e=Vt();this._ctx=new e(t),this.attachVisibilityHandler(),this.attachStateChangeHandler(this._ctx);}return this._ctx}peek(){return this._ctx}async unlock(){if(this._state==="closed")throw new S;if(this._unlocking)return this._unlocking;if(this._state==="live"&&this._ctx?.state==="running")return;this.setState("unlocking");let t=this.touch();return this._unlocking=(async()=>{try{t.state==="suspended"&&await t.resume(),this.setState("live");}catch(e){throw this.setState("cold"),e}finally{this._unlocking=null;}})(),this._unlocking}get now(){return this._ctx?.currentTime??0}onStateChange(t){return this._listeners.add(t),()=>this._listeners.delete(t)}async close(){this._state!=="closed"&&(typeof document<"u"&&document.removeEventListener("visibilitychange",this.handleVisibility),this._ctx&&(this._ctx.removeEventListener("statechange",this.handleCtxStateChange),this._ctx.state!=="closed"&&await this._ctx.close().catch(()=>{})),this._ctx=null,this.setState("closed"),this._listeners.clear());}setState(t){if(this._state!==t){this._state=t;for(let e of this._listeners)e(t);}}attachVisibilityHandler(){this.opts.autoPauseOnHidden!==false&&(typeof document>"u"||document.addEventListener("visibilitychange",this.handleVisibility));}handleVisibility=()=>{if(!this._ctx||this._state==="closed")return;document.visibilityState==="visible"?setTimeout(()=>{document.visibilityState==="visible"&&this._ctx?.state==="suspended"&&this._ctx.resume().catch(()=>{});},200):this._ctx.suspend().catch(()=>{});};attachStateChangeHandler(t){t.addEventListener("statechange",this.handleCtxStateChange);}handleCtxStateChange=()=>{let t=this._ctx;if(!t||this._state==="closed")return;let e=t.state;if(e==="interrupted"){this.setState("interrupted");return}if(e==="suspended"){if(this._state==="interrupted"){setTimeout(()=>{this._ctx===t&&t.state==="suspended"&&t.resume().catch(()=>{});},200);return}(this._state==="live"||this._state==="unlocking")&&this.setState("suspended");return}e==="running"&&this._state!=="live"&&this.setState("live");}};function Vt(){let o=globalThis,t=o.AudioContext??o.webkitAudioContext;if(!t)throw new Error("No AudioContext constructor available in this environment.");return t}var Dt=64*1024*1024,It=128;function Rt(o){return o.length*o.numberOfChannels*4}var K=class{constructor(t,e={}){this.getCtx=t;let i=typeof e=="number"?{maxEntries:e}:e;this.maxBytes=Math.max(1,i.maxBytes??Dt),this.maxEntries=Math.max(1,i.maxEntries??It);}getCtx;cache=new Map;bytes=0;inflight=new Map;maxBytes;maxEntries;has(t){return this.cache.has(t)}get cachedBytes(){return this.bytes}async load(t,e={}){let i=this.cache.get(t);if(i)return this.touch(t,i.buffer),i.buffer;let s=this.inflight.get(t);if(s)return this.join(s,e.signal);let r=new AbortController,n;return n={promise:this.fetchAndDecode(t,r.signal,e.onProgress).finally(()=>{this.inflight.get(t)===n&&this.inflight.delete(t);}),controller:r,waiters:0},this.inflight.set(t,n),this.join(n,e.signal)}join(t,e){t.waiters++;let i=()=>{t.waiters--,t.waiters<=0&&t.controller.abort();};return e?e.aborted?(i(),Promise.reject(xt(e))):new Promise((s,r)=>{let n=false,a=()=>{n||(n=true,i(),r(xt(e)));};e.addEventListener("abort",a,{once:true}),t.promise.then(u=>{n||(n=true,t.waiters--,e.removeEventListener("abort",a),s(u));},u=>{n||(n=true,t.waiters--,e.removeEventListener("abort",a),r(u));});}):t.promise.finally(()=>t.waiters--)}async fetchAndDecode(t,e,i){let s;try{s=await fetch(t,{signal:e});}catch(u){throw u.name==="AbortError"?u:new M(t,u)}if(!s.ok)throw new M(t,new Error(`${s.status} ${s.statusText}`));let r=i?await Gt(s,i):await s.arrayBuffer(),n=this.getCtx(),a;try{a=await n.decodeAudioData(r);}catch(u){throw new M(t,u)}return this.touch(t,a),a}async loadFirst(t,e={}){if(t.length===0)throw new Error("loadFirst requires at least one URL");for(let s of t){let r=this.cache.get(s);if(r)return this.touch(s,r.buffer),r.buffer}let i=[];for(let s of t)try{return await this.load(s,e)}catch(r){if(r.name==="AbortError")throw r;i.push({url:s,cause:r});}if(t.length===1){let s=i[0]?.cause;throw s instanceof Error?s:new M(t[0],s)}throw new B(t,i)}evict(t){let e=this.cache.get(t);e&&(this.bytes-=e.bytes,this.cache.delete(t));}clear(){this.cache.clear(),this.bytes=0;}touch(t,e){this.evict(t);let i=Rt(e);for(this.cache.set(t,{buffer:e,bytes:i}),this.bytes+=i;this.cache.size>this.maxEntries||this.bytes>this.maxBytes&&this.cache.size>1;){let s=this.cache.keys().next().value;if(s===void 0)break;this.evict(s);}}};function xt(o){return o.reason??new DOMException("load aborted","AbortError")}async function Gt(o,t){let e=o.body;if(!e||typeof e.getReader!="function"){let d=await o.arrayBuffer();return t(d.byteLength,d.byteLength),d}let i=o.headers.get("content-length"),s=i?Number.parseInt(i,10):Number.NaN,r=Number.isFinite(s)?s:null,n=e.getReader(),a=[],u=0;for(;;){let{done:d,value:m}=await n.read();if(d)break;m&&(a.push(m),u+=m.byteLength,t(u,r));}let c=new Uint8Array(u),l=0;for(let d of a)c.set(d,l),l+=d.byteLength;return c.buffer}var zt={targetRms:.1,peakCeiling:.99};function k(o,t,e){if(!t)return o;let i={...zt,...typeof t=="object"?t:{}},s=St(o,i);return Math.abs(s-1)<.001?o:Ht(o,s,e)}function St(o,t){let e=Ut(o);if(e<=1e-6)return 1;let i=t.targetRms/e,s=qt(o)*i;return s>t.peakCeiling&&(i*=t.peakCeiling/s),i}function Ut(o){let t=0,e=0;for(let i=0;i<o.numberOfChannels;i++){let s=o.getChannelData(i);for(let r=0;r<s.length;r++)t+=s[r]*s[r];e+=s.length;}return e===0?0:Math.sqrt(t/e)}function qt(o){let t=0;for(let e=0;e<o.numberOfChannels;e++){let i=o.getChannelData(e);for(let s=0;s<i.length;s++){let r=Math.abs(i[s]);r>t&&(t=r);}}return t}function Ht(o,t,e){if(e){let i=e.createBuffer(o.numberOfChannels,o.length,o.sampleRate);for(let s=0;s<o.numberOfChannels;s++){let r=o.getChannelData(s),n=i.getChannelData(s);for(let a=0;a<r.length;a++)n[a]=r[a]*t;}return i}for(let i=0;i<o.numberOfChannels;i++){let s=o.getChannelData(i);for(let r=0;r<s.length;r++)s[r]=s[r]*t;}return o}var Q=class{constructor(t,e){this.host=t;this.tickSource=e;}host;tickSource;tasks=[];cancelled=0;timer=null;unsubscribe=null;scheduleAt(t,e){let i={audioTime:t,fn:e,cancelled:false};return this.tasks.splice(this.insertionIndex(t),0,i),this.arm(),()=>{i.cancelled||(i.cancelled=true,this.cancelled++,this.cancelled>32&&this.cancelled*2>this.tasks.length&&this.compact());}}insertionIndex(t){let e=0,i=this.tasks.length;for(;e<i;){let s=e+i>>>1;this.tasks[s].audioTime<=t?e=s+1:i=s;}return e}compact(){this.tasks=this.tasks.filter(t=>!t.cancelled),this.cancelled=0;}arm(){if(this.tickSource){this.unsubscribe||(this.unsubscribe=this.tickSource.subscribe(()=>this.tick()));return}this.rearmTimer();}rearmTimer(){this.timer!=null&&(clearTimeout(this.timer),this.timer=null);let t=this.tasks.find(s=>!s.cancelled);if(!t)return;let e=this.host.now,i=Math.max(0,(t.audioTime-e)*1e3);this.timer=setTimeout(()=>this.tick(),i);}tick(){this.timer!=null&&(this.timer=null);let t=this.host.now,e=[],i=[];for(let s of this.tasks)s.cancelled||(s.audioTime<=t?e.push(s):i.push(s));this.tasks=i,this.cancelled=0;for(let s of e)try{s.fn();}catch(r){console.error("[zvuk] scheduled task threw",r);}if(this.tasks.length===0){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null);return}this.tickSource||this.rearmTimer();}dispose(){this.timer!=null&&clearTimeout(this.timer),this.timer=null,this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.tasks=[],this.cancelled=0;}};var $t=.008,jt=.05,D=class{name;deps;live=new Set;constructor(t,e){this.name=t,this.deps=e;}get loopDuration(){return this.deps.buffers.loop.duration}get hasIntro(){return this.deps.buffers.intro!=null}get hasOutro(){return this.deps.buffers.outro!=null}play(t={}){let e=new J({ctx:this.deps.ctx,buffers:this.deps.buffers,destination:this.deps.destination,loopCrossfade:this.deps.loopCrossfade,defaultStopFade:this.deps.defaultStopFade,options:t});return this.live.add(e),e.ended.then(()=>this.live.delete(e)),e}voices(){return Array.from(this.live)}stopAll(t={}){for(let e of Array.from(this.live))e.stop(t);this.live.clear();}},J=class{ended;ctx;buffers;destination;gain;state="intro";done=false;resolveEnded;stopFade;loopCrossfadeSec;introSource=null;outroSource=null;loopChain=[];loopArmTimer=null;outroTimer=null;nextLoopBoundaryAt=Number.POSITIVE_INFINITY;loopAnchorAt=Number.POSITIVE_INFINITY;introEndsAt=Number.NEGATIVE_INFINITY;constructor(t){this.ctx=t.ctx,this.buffers=t.buffers,this.destination=t.destination,this.loopCrossfadeSec=Math.max(0,t.loopCrossfade),this.stopFade=Math.max(0,t.defaultStopFade??$t),this.gain=this.ctx.createGain();let e=At(t.options.volume??1),i=Math.max(0,t.options.fadeIn??0);i>0?(this.gain.gain.setValueAtTime(0,this.ctx.currentTime),this.gain.gain.linearRampToValueAtTime(e,this.ctx.currentTime+i)):this.gain.gain.value=e,this.gain.connect(this.destination),this.ended=new Promise(s=>{this.resolveEnded=s;}),this.start(this.ctx.currentTime);}get currentPart(){return this.state}fade(t){let e=this.gain.gain,i=this.ctx.currentTime;return x(e,i,At(t.to),t.duration,t.curve??"linear"),w(this.ctx,t.duration,this.ended)}stop(t={}){if(this.done)return;let e=Math.max(0,t.fade??this.stopFade);if(this.cancelTimers(),e===0){this.stopAllSources(0),this.finish();return}let i=this.ctx.currentTime,s=i+e;try{let r=this.gain.gain;r.cancelScheduledValues(i),r.setValueAtTime(r.value,i),r.linearRampToValueAtTime(0,s),this.stopAllSources(s);}catch{this.finish();return}O(this.ctx,e,()=>this.finish());}skipToOutro(t={}){if(this.done||this.state==="outro"||this.state==="ended")return;if(!this.buffers.outro){this.stop();return}(t.at??"loop-end")==="now"?this.skipToOutroNow():this.skipToOutroAtLoopEnd();}start(t){this.buffers.intro?(this.scheduleIntro(t),this.scheduleLoopStart(t+this.buffers.intro.duration)):(this.state="loop",this.scheduleLoopStart(t));}scheduleIntro(t){let e=this.ctx.createBufferSource();e.buffer=this.buffers.intro,e.connect(this.gain);try{e.start(t);}catch{}this.introEndsAt=t+this.buffers.intro.duration,e.onended=()=>{this.introSource===e&&(this.introSource=null);},this.introSource=e;}scheduleLoopStart(t){if(this.done)return;let e=this.spawnLoopSegment(t,false),i=e.startTime;if(this.loopAnchorAt=i,this.nextLoopBoundaryAt=i+this.buffers.loop.duration,this.loopCrossfadeSec>0&&this.crossfadeViable())this.armNextLoopSegment(i);else {e.source.loop=true;let s=this.buffers.loop;e.source.loopStart=0,e.source.loopEnd=s.duration,this.buffers.intro?O(this.ctx,i-this.ctx.currentTime,()=>{!this.done&&this.state==="intro"&&(this.state="loop");}):this.state="loop";}}spawnLoopSegment(t,e){let i=this.ctx.currentTime,s=Math.max(t,i),r=e&&i-t<this.loopCrossfadeSec,n=this.ctx.createBufferSource();n.buffer=this.buffers.loop,n.loop=false;let a=this.ctx.createGain();Y(a.gain,s,this.buffers.loop.duration,this.loopCrossfadeSec,{fadeIn:r,fadeOut:this.crossfadeViable()}),n.connect(a).connect(this.gain);try{this.crossfadeViable()?n.start(s,0,this.buffers.loop.duration):n.start(s);}catch{}n.onended=()=>this.releaseLoopSegment(n,a);let u={source:n,gain:a,startTime:s};return this.loopChain.push(u),u}armNextLoopSegment(t){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null);let e=t+this.buffers.loop.duration-this.loopCrossfadeSec,s=Math.max(0,(e-this.ctx.currentTime)*1e3-50);this.loopArmTimer=setTimeout(()=>{if(this.loopArmTimer=null,this.done||this.state!=="loop"&&this.state!=="intro")return;this.state="loop";let r=e;try{r=this.spawnLoopSegment(e,!0).startTime;}finally{this.nextLoopBoundaryAt=r+this.buffers.loop.duration,this.armNextLoopSegment(r);}},s);}crossfadeViable(){return this.loopCrossfadeSec>0&&this.buffers.loop.duration>this.loopCrossfadeSec*2}releaseLoopSegment(t,e){let i=this.loopChain.findIndex(s=>s.source===t);i>=0&&this.loopChain.splice(i,1);try{t.disconnect(),e.disconnect();}catch{}}nextLoopBoundary(){if(this.crossfadeViable())return this.nextLoopBoundaryAt;if(!Number.isFinite(this.loopAnchorAt))return this.loopAnchorAt;let t=this.ctx.currentTime-this.loopAnchorAt,e=this.buffers.loop.duration;return t<0||e<=0?this.loopAnchorAt:this.loopAnchorAt+(Math.floor(t/e)+1)*e}skipToOutroAtLoopEnd(){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null);let t;this.state==="intro"?(t=this.introEndsAt,this.cancelLoopArm()):t=this.nextLoopBoundary(),t=Math.max(t,this.ctx.currentTime),this.stopLoopSourcesAt(t),this.scheduleOutro(t);}skipToOutroNow(){this.cancelLoopArm();let t=this.ctx.currentTime,e=t+jt;for(let i of this.loopChain){try{let s=i.gain.gain;s.cancelScheduledValues(t),s.setValueAtTime(s.value,t),s.linearRampToValueAtTime(0,e);}catch{}try{i.source.stop(e);}catch{}}if(this.introSource)try{this.introSource.stop(e);}catch{}this.scheduleOutro(e);}cancelLoopArm(){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null);}stopLoopSourcesAt(t){for(let e of this.loopChain)try{e.source.stop(t);}catch{}}scheduleOutro(t){let e=this.buffers.outro;if(!e){this.outroTimer=O(this.ctx,t-this.ctx.currentTime,()=>this.finish());return}let i=this.ctx.createBufferSource();i.buffer=e,i.connect(this.gain);try{i.start(t);}catch{}i.onended=()=>{this.outroSource===i&&(this.outroSource=null),this.finish();},this.outroSource=i,this.outroTimer=O(this.ctx,t-this.ctx.currentTime,()=>{this.outroTimer=null,this.done||(this.state="outro");});}cancelTimers(){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null),this.outroTimer!=null&&(this.outroTimer(),this.outroTimer=null);}stopAllSources(t){let e=[];this.introSource&&e.push(this.introSource);for(let i of this.loopChain)e.push(i.source);this.outroSource&&e.push(this.outroSource);for(let i of e)try{i.onended=null,t===0?i.stop():i.stop(t);}catch{}}finish(){if(!this.done){this.done=true,this.state="ended",this.cancelTimers();try{this.introSource&&this.introSource.disconnect();for(let t of this.loopChain)t.source.disconnect(),t.gain.disconnect();this.outroSource&&this.outroSource.disconnect(),this.gain.disconnect();}catch{}this.introSource=null,this.outroSource=null,this.loopChain=[],this.resolveEnded();}}};function At(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}var Wt=.008,I=class o{id;priority;bus;startedAt;sourceName;ended;ctx;gain;source;buffer;loop;basePitch;done=false;stopping=false;paused=false;resolveEnded;cueListeners=new Set;startCtxTime;pausedOffset=0;currentOffset=0;_spatializer;startOffset;regionDuration;loopStart;loopEnd;regionTimer=null;stopFade;crossfadeSec=0;crossfadeRegionStart=0;crossfadeRegionLen=0;crossfadeChain=[];crossfadeArmTimer=null;levelAnalyser=null;levelBuf=null;static nextId=1;constructor(t){let{ctx:e,buffer:i,destination:s,options:r}=t;this.id=o.nextId++,this.ctx=e,this.priority=r.priority??0,this.bus=r.bus,this.sourceName=t.sourceName,this.startedAt=e.currentTime,this.buffer=i,this.loop=r.loop??false,this.basePitch=Ct(r.pitch??1,1),this._spatializer=t.spatializer,this.startOffset=r.offset??0,this.currentOffset=this.startOffset,this.regionDuration=r.duration,this.loopStart=r.loopStart,this.loopEnd=r.loopEnd,this.stopFade=Math.max(0,t.defaultStopFade??Wt),this.gain=e.createGain();let n=Tt(Ct(r.volume??1)),a=Math.max(0,r.fadeIn??0);if(a>0?(this.gain.gain.setValueAtTime(0,e.currentTime),this.gain.gain.linearRampToValueAtTime(n,e.currentTime+a)):this.gain.gain.value=n,this.gain.connect(s),this.startCtxTime=e.currentTime,this.ended=new Promise(u=>{this.resolveEnded=u;}),r.signal&&(r.signal.aborted?queueMicrotask(()=>this.stop()):r.signal.addEventListener("abort",()=>this.stop(),{once:true})),this.shouldUseLoopCrossfade(r)){this.crossfadeSec=r.loopCrossfade,this.crossfadeRegionStart=r.loopStart??this.startOffset;let u=r.loopEnd??i.duration;this.crossfadeRegionLen=Math.max(0,u-this.crossfadeRegionStart),this.source=this.startCrossfadeChain(e.currentTime);}else {this.source=this.createSourceNode(this.basePitch),this.bindSourceLifecycle(this.source,()=>{});try{this.source.start(0,this.startOffset);}catch{}this.armRegionTimer(this.regionDuration);}queueMicrotask(()=>this.emit("started")),this.ended.then(()=>t.onEnded(this));}shouldUseLoopCrossfade(t){if(!this.loop)return false;let e=t.loopCrossfade;if(e==null||e<=0)return false;let i=t.loopStart??this.startOffset;return (t.loopEnd??this.buffer.duration)-i>e*2}fade(t){let e=this.gain.gain,i=this.ctx.currentTime;return x(e,i,Tt(t.to),t.duration,t.curve??"linear"),w(this.ctx,t.duration,this.ended)}stop(t={}){if(this.done||this.stopping)return;let e=Math.max(0,t.fade??this.stopFade);if(this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null),e===0){this.stopAllSources(0),this.finish("ended");return}this.stopping=true;let i=this.ctx.currentTime,s=i+e;for(let r of this.activeSources())r.onended=null;this.regionTimer!=null&&(this.regionTimer(),this.regionTimer=null);try{let r=this.gain.gain;r.cancelScheduledValues(i),r.setValueAtTime(r.value,i),r.linearRampToValueAtTime(0,s),this.stopAllSources(s);}catch{this.finish("ended");return}O(this.ctx,e,()=>this.finish("ended"));}activeSources(){return this.inCrossfadeMode?this.crossfadeChain.map(t=>t.source):[this.source]}stopAllSources(t){for(let e of this.activeSources())try{t===0?e.stop():e.stop(t);}catch{}}pause(){if(this.done||this.paused)return;let t=this.computeOffset();this.pausedOffset=t,this.currentOffset=t,this.paused=true,this.regionTimer!=null&&(this.regionTimer(),this.regionTimer=null),this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null);for(let e of this.activeSources()){try{e.onended=null,e.stop();}catch{}try{e.disconnect();}catch{}}this.inCrossfadeMode&&(this.crossfadeChain=[]),this.emit("paused");}resume(){if(!(this.done||!this.paused)){if(this.paused=false,this.startCtxTime=this.ctx.currentTime,this.inCrossfadeMode)this.source=this.startCrossfadeChain(this.startCtxTime);else {this.source=this.createSourceNode(this.basePitch),this.bindSourceLifecycle(this.source,()=>{});try{this.source.start(0,this.pausedOffset);}catch{}if(this.regionDuration!=null){let t=Math.max(0,this.pausedOffset-this.startOffset),e=Math.max(0,this.regionDuration-t);this.armRegionTimer(e);}}this.emit("resumed");}}get isPaused(){return this.paused}setPlaybackRate(t,e={}){if(this.done)return;let i=Math.max(0,t),s=Math.max(0,e.duration??0);if(this.paused||(this.currentOffset=this.computeOffset(),this.startCtxTime=this.ctx.currentTime),this.basePitch=i,!this.paused){if(this.regionTimer!=null&&this.regionDuration!=null){let r=Math.max(0,this.currentOffset-this.startOffset);this.armRegionTimer(Math.max(0,this.regionDuration-r));}for(let r of this.activeSources()){let n=r.playbackRate;s===0?n.value=i:x(n,this.ctx.currentTime,i,s,e.curve??"linear");}}}get playbackRate(){return this.basePitch}get spatializer(){return this._spatializer}level(){if(this.done)return {rms:0,peak:0};if(!this.levelAnalyser){let s=this.ctx.createAnalyser();s.fftSize=512,this.gain.connect(s),this.levelAnalyser=s,this.levelBuf=new Float32Array(s.fftSize);}let t=this.levelBuf;this.levelAnalyser.getFloatTimeDomainData(t);let e=0,i=0;for(let s=0;s<t.length;s++){let r=t[s]??0;e+=r*r;let n=Math.abs(r);n>i&&(i=n);}return {rms:Math.sqrt(e/t.length),peak:i}}levelHint(){return this.done?0:this.levelAnalyser?this.level().rms:this.gain.gain.value}async*cues(){if(this.done){yield "ended";return}let t=[],e=null,i=r=>{if(e){let n=e;e=null,n({value:r,done:false});}else t.push(r);},s=r=>i(r);this.cueListeners.add(s);try{for(;;){if(t.length>0){let n=t.shift();if(yield n,n==="ended")return;continue}if(this.done){yield "ended";return}let r=await new Promise(n=>{e=n;});if(r.done||(yield r.value,r.value==="ended"))return}}finally{this.cueListeners.delete(s);}}finish(t,e){if(!this.done){this.done=true,this.regionTimer!=null&&(this.regionTimer(),this.regionTimer=null),this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null);try{for(let i of this.activeSources())i.disconnect();for(let i of this.crossfadeChain)i.gain.disconnect();this.levelAnalyser?.disconnect(),this.gain.disconnect();}catch{}this.levelAnalyser=null,this.levelBuf=null,this.crossfadeChain=[],this.emit(t),this.resolveEnded(),e?.(this);}}emit(t){for(let e of this.cueListeners)e(t);}createSourceNode(t){let e=this.ctx.createBufferSource();return e.buffer=this.buffer,e.loop=this.loop,this.loop&&this.loopStart!=null&&(e.loopStart=this.loopStart),this.loop&&this.loopEnd!=null&&(e.loopEnd=this.loopEnd),e.playbackRate.value=t,e.connect(this.gain),e}armRegionTimer(t){if(this.regionTimer!=null&&(this.regionTimer(),this.regionTimer=null),t==null||this.loop)return;let e=Math.max(0,t)/Math.max(1e-4,this.basePitch);this.regionTimer=O(this.ctx,e,()=>{this.regionTimer=null,this.done||this.stop();});}bindSourceLifecycle(t,e){t.onended=()=>{this.paused||t.loop||this.finish("ended",e);};}startCrossfadeChain(t){let e=this.spawnCrossfadeSegment(t,false);return this.armNextCrossfadeSegment(e.startTime),e.source}spawnCrossfadeSegment(t,e){let i=this.ctx.currentTime,s=Math.max(t,i),r=e&&i-t<this.crossfadeSec,n=this.ctx.createBufferSource();n.buffer=this.buffer,n.loop=false,n.playbackRate.value=this.basePitch;let a=this.ctx.createGain();Y(a.gain,s,this.crossfadeRegionLen,this.crossfadeSec,{fadeIn:r,fadeOut:true}),n.connect(a).connect(this.gain);try{n.start(s,this.crossfadeRegionStart,this.crossfadeRegionLen);}catch{}n.onended=()=>this.releaseCrossfadeSegment(n,a);let u={source:n,gain:a,startTime:s};return this.crossfadeChain.push(u),u}armNextCrossfadeSegment(t){this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null);let e=t+this.crossfadeRegionLen-this.crossfadeSec,s=Math.max(0,(e-this.ctx.currentTime)*1e3-50);this.crossfadeArmTimer=setTimeout(()=>{if(this.crossfadeArmTimer=null,this.done||this.stopping||this.paused)return;let r=e;try{r=this.spawnCrossfadeSegment(e,!0).startTime;}finally{this.armNextCrossfadeSegment(r);}},s);}releaseCrossfadeSegment(t,e){let i=this.crossfadeChain.findIndex(s=>s.source===t);i>=0&&this.crossfadeChain.splice(i,1);try{t.disconnect(),e.disconnect();}catch{}}get inCrossfadeMode(){return this.crossfadeSec>0}computeOffset(){if(this.paused)return this.pausedOffset;let t=(this.ctx.currentTime-this.startCtxTime)*this.basePitch,e=this.currentOffset+t;return this.loop?e=(e%this.buffer.duration+this.buffer.duration)%this.buffer.duration:e=Math.min(e,this.buffer.duration),e}};function Ct(o,t=1){if(typeof o=="number")return o;if(!o)return t;let e=o.base??t;return o.jitter==null?e:e+(Math.random()*2-1)*o.jitter}function Tt(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}var R=class{name;deps;constructor(t,e){this.name=t,this.deps=e;}get duration(){return this.deps.buffer.duration}play(t={}){let e=t.bus??this.deps.defaultBus,i=this.deps.resolveBusInput(e),s=this.deps.resolveSpatializer?.(e,t.spatializer),r=s?s.connectInto(i):i,n=new I({ctx:this.deps.ctx,buffer:this.deps.buffer,destination:r,options:{...t,bus:e},spatializer:s,sourceName:this.deps.sourceName??this.name,defaultStopFade:this.deps.defaultStopFade,onEnded:u=>{this.deps.releaseVoice(u,e),s?.dispose();}});return this.deps.trackVoice(n,e),(this.deps.applyConcurrency?.(n,e)??true)||n.stop(),n}};var G=class{name;regions;sound;constructor(t,e,i){this.name=t,this.sound=e,this.regions={...i};}list(){return Object.keys(this.regions)}has(t){return t in this.regions}region(t){let e=this.regions[t];if(!e)throw new A(`${this.name}#${t}`);return e}play(t,e={}){let i=this.region(t),s=e.loop??i.loop??false;return this.sound.play({...e,loop:s,offset:i.start,duration:i.duration,loopStart:i.start,loopEnd:i.start+i.duration})}};var z=class{name;ctx;url;destination;el=null;node=null;gain=null;disposed=false;constructor(t,e,i,s){this.name=t,this.ctx=e,this.url=i,this.destination=s;}ensure(){if(this.el||this.disposed||typeof document>"u"||typeof Audio>"u")return;let t=new Audio;t.src=this.url,t.crossOrigin="anonymous",t.preload="auto";let e=this.ctx.createMediaElementSource;if(typeof e!="function"){this.el=t;return}let i=e.call(this.ctx,t),s=this.ctx.createGain();i.connect(s),s.connect(this.destination),this.el=t,this.node=i,this.gain=s;}async play(t={}){if(this.ensure(),!!this.el){this.gain&&(this.gain.gain.value=pt(t.volume??1)),this.el.loop=t.loop??false;try{await this.el.play();}catch{}}}pause(){this.el?.pause();}stop(){if(this.el){this.el.pause();try{this.el.currentTime=0;}catch{}}}seek(t){if(this.el)try{this.el.currentTime=Math.max(0,t);}catch{}}get currentTime(){return this.el?.currentTime??0}get duration(){return this.el?.duration??0}get paused(){return this.el?.paused??true}setVolume(t){this.gain&&(this.gain.gain.value=pt(t));}fade(t){return this.gain?(x(this.gain.gain,this.ctx.currentTime,pt(t.to),t.duration,t.curve??"linear"),w(this.ctx,t.duration)):Promise.resolve()}dispose(){this.disposed=true;try{this.node?.disconnect(),this.gain?.disconnect();}catch{}this.el&&(this.el.pause(),this.el.src=""),this.el=null,this.node=null,this.gain=null;}};function pt(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}var U=class{name;count;sounds;strategy;lastIndex=-1;bag=[];constructor(t,e,i={}){if(e.length===0)throw new Error(`Variants "${t}" requires at least one sound`);this.name=t,this.sounds=e,this.count=e.length,this.strategy=i.strategy??"no-repeat";}get lastPick(){return this.lastIndex}play(t={}){return this.sounds[this.pick()].play(t)}playIndex(t,e={}){let i=(t%this.count+this.count)%this.count;return this.lastIndex=i,this.sounds[i].play(e)}pick(){let t=this.count;if(t===1)return 0;if(this.strategy==="random"){let i=Math.floor(Math.random()*t);return this.lastIndex=i,i}if(this.strategy==="shuffle-bag"){if(this.bag.length===0){this.bag=Array.from({length:t},(s,r)=>r);for(let s=t-1;s>0;s--){let r=Math.floor(Math.random()*(s+1));[this.bag[s],this.bag[r]]=[this.bag[r],this.bag[s]];}t>1&&this.bag[0]===this.lastIndex&&([this.bag[0],this.bag[1]]=[this.bag[1],this.bag[0]]);}let i=this.bag.shift();return this.lastIndex=i,i}let e=Math.floor(Math.random()*(t-1));return e>=this.lastIndex&&e++,this.lastIndex=e,e}};var Yt="inverse";var q=class{ctx;kind;input;output;stereoPan=null;panner=null;occlusionFilter=null;occlusionGain=null;constructor(t,e){if(this.ctx=t,e.position){let i=t.createPanner();i.panningModel="HRTF",i.distanceModel=e.distanceModel??Yt,i.refDistance=e.refDistance??1,i.maxDistance=e.maxDistance??1e4,i.rolloffFactor=e.rolloffFactor??1;let[s,r,n]=e.position;this.setPanner3D(i,s,r,n);let a=t.createBiquadFilter();a.type="lowpass",a.frequency.value=22050,a.Q.value=Math.SQRT1_2;let u=t.createGain();u.gain.value=1,i.connect(a).connect(u),this.panner=i,this.occlusionFilter=a,this.occlusionGain=u,this.input=i,this.output=u,this.kind="3d",e.occlusion!=null&&this.setOcclusion(e.occlusion);}else {let i=t.createStereoPanner();i.pan.value=wt(e.pan??0),this.stereoPan=i,this.input=i,this.output=i,this.kind="2d";}}setPan(t){this.kind!=="2d"||!this.stereoPan||(this.stereoPan.pan.value=wt(t));}setPosition(t,e,i){this.kind!=="3d"||!this.panner||this.setPanner3D(this.panner,t,e,i);}setRefDistance(t){this.panner&&(this.panner.refDistance=Math.max(0,t));}setMaxDistance(t){this.panner&&(this.panner.maxDistance=Math.max(0,t));}setRolloffFactor(t){this.panner&&(this.panner.rolloffFactor=Math.max(0,t));}setDistanceModel(t){this.panner&&(this.panner.distanceModel=t);}setOcclusion(t){if(!this.occlusionFilter||!this.occlusionGain)return;let e=Zt(t),i=22050*(500/22050)**e,s=this.ctx.currentTime;this.occlusionFilter.frequency.setValueAtTime(i,s);let r=10**(-6*e/20);this.occlusionGain.gain.setValueAtTime(r,s);}connectInto(t){return this.output.connect(t),this.input}dispose(){try{this.input.disconnect(),this.occlusionFilter?.disconnect(),this.occlusionGain?.disconnect();}catch{}}setPanner3D(t,e,i,s){if(typeof t.positionX?.setValueAtTime=="function"){let r=this.ctx.currentTime;t.positionX.setValueAtTime(e,r),t.positionY.setValueAtTime(i,r),t.positionZ.setValueAtTime(s,r);}else t.setPosition?.(e,i,s);}};function wt(o){return Math.max(-1,Math.min(1,o))}function Zt(o){return Number.isNaN(o)?0:Math.max(0,Math.min(1,o))}var H=class{input;headroomDb;ctx;limiterNode=null;limiterCfg;destination;_meterAnalyser=null;_meterBuf=null;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.headroomDb=e.headroom??0,this.input.gain.value=Mt(this.headroomDb),this.destination=t.destination,this.limiterCfg=e.limiter??null,this.rewire();}setHeadroom(t){this.headroomDb=t,x(this.input.gain,this.ctx.currentTime,Mt(t),.01,"linear");}get headroom(){return this.headroomDb}setLimiter(t){this.limiterCfg=t,this.rewire();}get reduction(){return this.limiterNode?.reduction??0}meter(){if(!this._meterAnalyser){let s=this.ctx.createAnalyser();s.fftSize=1024,this.input.connect(s),this._meterAnalyser=s,this._meterBuf=new Float32Array(s.fftSize);}let t=this._meterBuf;this._meterAnalyser.getFloatTimeDomainData(t);let e=0,i=0;for(let s=0;s<t.length;s++){let r=t[s]??0;e+=r*r;let n=Math.abs(r);n>i&&(i=n);}return {rms:Math.sqrt(e/t.length),peak:i}}dispose(){try{this.input.disconnect(),this.limiterNode?.disconnect(),this._meterAnalyser?.disconnect();}catch{}this.limiterNode=null,this._meterAnalyser=null,this._meterBuf=null;}rewire(){try{this.input.disconnect(),this.limiterNode?.disconnect();}catch{}if(this.limiterNode=null,this.limiterCfg){let t=this.limiterCfg,e=this.ctx.createDynamicsCompressor();e.threshold.value=t.threshold??-1,e.knee.value=0,e.ratio.value=Math.max(20,t.ratio??20),e.attack.value=t.attack??.001,e.release.value=t.release??.05,this.input.connect(e),e.connect(this.destination),this.limiterNode=e;}else this.input.connect(this.destination);this._meterAnalyser&&this.input.connect(this._meterAnalyser);}};function Mt(o){return 10**(o/20)}var $=class{name;state;getBus;getParam;constructor(t,e,i,s){this.name=t,this.state=e,this.getBus=i,this.getParam=s;}apply(t={}){let e=t.fade??0,i=[];for(let[s,r]of Object.entries(this.state.buses)){let n=this.getBus(s);n&&(n.muted=r.muted,i.push(n.fadeTo(r.level,e)));}for(let[s,r]of Object.entries(this.state.parameters)){let n=this.getParam(s);n&&n.set(r);}return Promise.all(i).then(()=>{})}blendWith(t,e){let i=e<0?0:e>1?1:e,s=1-i;for(let[r,n]of Object.entries(this.state.buses)){let a=t.state.buses[r];if(!a)continue;let u=this.getBus(r);u&&(u.muted=i<.5?n.muted:a.muted,u.level=n.level*s+a.level*i);}for(let[r,n]of Object.entries(this.state.parameters)){let a=t.state.parameters[r];if(a===void 0)continue;let u=this.getParam(r);u&&u.set(n*s+a*i);}}};function Xt(o={}){return new ft(o)}var ft=class{host;decoder;scheduler=null;master=null;buses=new Map;busOrder=[];sounds=new Map;internalSounds=new Map;sprites=new Map;streams=new Map;musics=new Map;variantsByName=new Map;busGroups=new Map;soloedBuses=new Set;soundUrls=new Map;voices=new Map;parameters=new Map;config;constructor(t){this.config=t,this.host=new X({autoPauseOnHidden:t.autoPauseOnHidden,latencyHint:t.latencyHint}),this.decoder=new K(()=>this.host.touch(),t.cache??{});let e=Object.keys(t.buses??{});this.busOrder=e.length>0?e:["default"];for(let i of this.busOrder)this.voices.set(i,new Set);}get state(){return this.host.state}get now(){return this.host.now}get context(){return this.host.touch()}async unlock(){await this.host.unlock(),this.ensureGraph();}async close(){if(this.host.state!=="closed"){for(let t of this.voices.values()){for(let e of t)e.stop();t.clear();}this.scheduler?.dispose(),this.scheduler=null;for(let t of this.buses.values()){for(let e of t.fx())e.dispose();t.dispose();}this.buses.clear(),this.master?.dispose(),this.master=null,this.sounds.clear(),this.internalSounds.clear(),this.sprites.clear();for(let t of this.musics.values())t.stopAll({fade:0});this.musics.clear(),this.variantsByName.clear(),this.busGroups.clear(),this.soloedBuses.clear(),this.soundUrls.clear();for(let t of this.streams.values())t.dispose();this.streams.clear(),this.parameters.clear(),this.decoder.clear(),await this.host.close();}}async loadSound(t,e,i={}){return this.loadSoundAs(t,t,e,i,false)}async loadSoundAs(t,e,i,s,r){if(this.host.state==="closed")throw new S;this.host.touch(),this.ensureGraph();let n={signal:s.signal},a=await this.resolveBuffer(t,i,n);return s.normalize&&(a=k(a,s.normalize,this.host.touch())),this.soundUrls.set(t,typeof i=="string"?[i]:[...i]),this.registerSound(t,e,a,{bus:s.bus},r)}async resolveBuffer(t,e,i){let s=this.config.resolveAsset;if(s){let n=await s({name:t,url:e,signal:i.signal});if(n!=null){if(n instanceof AudioBuffer)return n;if(n instanceof ArrayBuffer)return await this.host.touch().decodeAudioData(n.slice(0));if(typeof n=="string")return await this.decoder.load(n,i)}}let r=typeof e=="string"?[e]:dt(e);return await this.decoder.loadFirst(r,i)}async preload(t,e={}){if(this.host.state==="closed")throw new S;if(t.length===0)return;let i=Math.max(1,e.concurrency??Ot),s=e.onProgress,r=e.signal,n=t.length,a=0,u=[],c=0,l=Math.min(i,n),d=[];for(let p=0;p<l;p++)d.push((async()=>{for(;;){let b=c++;if(b>=n)return;if(r?.aborted)throw r.reason??new DOMException("preload aborted","AbortError");let h=t[b],v=Qt(r,h.options?.signal),f={...h.options??{},signal:v};try{await this.loadSound(h.name,h.url,f),a++,s?.({name:h.name,status:"loaded",completed:a,total:n});}catch(y){if(y.name==="AbortError")throw y;a++,u.push({name:h.name,cause:y}),s?.({name:h.name,status:"failed",error:y,completed:a,total:n});}}})());let g=(await Promise.allSettled(d)).find(p=>p.status==="rejected");if(g&&g.status==="rejected")throw g.reason;if(u.length>0)throw new N(u)}async loadSprite(t,e,i,s={}){let r=await this.loadSoundAs(`__sprite:${t}`,t,e,s,true),n=new G(t,r,i);return this.sprites.set(t,n),n}sprite(t){let e=this.sprites.get(t);if(!e)throw new A(t,C(t,[...this.sprites.keys()]));return e}hasSprite(t){return this.sprites.has(t)}async loadVariants(t,e,i={}){if(e.length===0)throw new Error(`engine.loadVariants("${t}") requires at least one URL set`);let{strategy:s,...r}=i,n=await Kt(e,Ot,(u,c)=>this.loadSoundAs(`__variant:${t}:${c}`,t,u,r,true)),a=new U(t,n,{strategy:s});return this.variantsByName.set(t,a),a}variants(t){let e=this.variantsByName.get(t);if(!e)throw new A(t,C(t,[...this.variantsByName.keys()]));return e}hasVariants(t){return this.variantsByName.has(t)}async loadMusic(t,e,i={}){if(this.host.state==="closed")throw new S;this.host.touch(),this.ensureGraph();let s={signal:i.signal},[r,n,a]=await Promise.all([this.resolveBuffer(`__music:${t}:loop`,e.loop,s),e.intro?this.resolveBuffer(`__music:${t}:intro`,e.intro,s):Promise.resolve(void 0),e.outro?this.resolveBuffer(`__music:${t}:outro`,e.outro,s):Promise.resolve(void 0)]),u=this.host.touch(),c={intro:n?i.normalize?k(n,i.normalize,u):n:void 0,loop:i.normalize?k(r,i.normalize,u):r,outro:a?i.normalize?k(a,i.normalize,u):a:void 0},l=i.bus??this.busOrder[0],d=this.buses.get(l);if(!d)throw new T(l,C(l,[...this.buses.keys()]));let m=new D(t,{ctx:this.host.touch(),buffers:c,destination:d.input,loopCrossfade:i.loopCrossfade??0,defaultStopFade:this.config.voice?.stopFade});return this.musics.set(t,m),m}music(t){let e=this.musics.get(t);if(!e)throw new A(t,C(t,[...this.musics.keys()]));return e}hasMusic(t){return this.musics.has(t)}loadStream(t,e,i={}){if(this.host.state==="closed")throw new S;this.host.touch(),this.ensureGraph();let s=typeof e=="string"?e:ht(e),r=i.bus??this.busOrder[0],n=this.buses.get(r);if(!n)throw new T(r,C(r,[...this.buses.keys()]));let a=new z(t,this.host.touch(),s,n.input);return this.streams.set(t,a),a}stream(t){let e=this.streams.get(t);if(!e)throw new A(t,C(t,[...this.streams.keys()]));return e}hasStream(t){return this.streams.has(t)}crossfade(t,e,i={}){let s=i.duration??1.5,r=i.curve??"equal-power",n=i.toVolume??1,u=this.sound(e).play({bus:i.bus,loop:i.loop??true,volume:0});u.fade({to:n,duration:s,curve:r}).catch(()=>{});let c=this.activeVoices().filter(l=>l!==u&&l.sourceName===t&&l.bus===u.bus);for(let l of c)l.fade({to:0,duration:s,curve:r}).then(()=>l.stop()).catch(()=>{});return u}createSound(t,e,i={}){return this.registerSound(t,t,e,i,false)}registerSound(t,e,i,s,r){if(this.host.state==="closed")throw new S;this.host.touch(),this.ensureGraph();let n=s.bus??this.busOrder[0];if(!this.buses.has(n))throw new T(n,C(n,[...this.buses.keys()]));let a=new R(t,{ctx:this.host.touch(),buffer:i,defaultBus:n,sourceName:e,defaultStopFade:this.config.voice?.stopFade,resolveBusInput:u=>{let c=this.buses.get(u);if(!c)throw new T(u,C(u,[...this.buses.keys()]));return c.input},resolveSpatializer:(u,c)=>{if(c)return new q(this.host.touch(),c)},trackVoice:(u,c)=>{this.voices.get(c)?.add(u),this.buses.get(c)?.trackVoice(u);},releaseVoice:(u,c)=>{this.voices.get(c)?.delete(u),this.buses.get(c)?.releaseVoice(u);},applyConcurrency:(u,c)=>{let l=this.buses.get(c);if(!l)return true;let d=false,m=l.applyConcurrencyOnSpawn(u,()=>{d=true;});return m&&(this.voices.get(c)?.delete(m),l.releaseVoice(m)),d&&(this.voices.get(c)?.delete(u),l.releaseVoice(u)),!d}});return (r?this.internalSounds:this.sounds).set(t,a),a}removeSound(t){this.sounds.delete(t);}unloadSound(t,e={}){if(this.sounds.delete(t),e.evictBuffer??true){let i=this.soundUrls.get(t);if(i)for(let s of i)this.decoder.evict(s);}this.soundUrls.delete(t);}hasSound(t){return this.sounds.has(t)}sound(t){let e=this.sounds.get(t);if(!e)throw new A(t,C(t,[...this.sounds.keys()]));return e}bus(t){this.ensureGraph();let e=this.buses.get(t);if(!e)throw new T(t,C(t,[...this.buses.keys()]));return e}busGroup(t,e){if(e!=null){let s=new L(t,e);return this.busGroups.set(t,s),s}let i=this.busGroups.get(t);if(!i)throw new T(t,C(t,[...this.busGroups.keys()]));return i}masterMeter(){return this.ensureGraph(),this.master.meter()}scheduleAt(t,e){return this.host.touch(),this.ensureGraph(),this.scheduler.scheduleAt(t,e)}activeVoices(){let t=[];for(let e of this.voices.values())for(let i of e)t.push(i);return t}onStateChange(t){return this.host.onStateChange(t)}parameter(t,e=0){let i=this.parameters.get(t);return i||(i=new V(t,e),this.parameters.set(t,i)),i}captureSnapshot(t){let e={};for(let[s,r]of this.buses)e[s]={level:r.level,muted:r.muted};let i={};for(let[s,r]of this.parameters)i[s]=r.value;return this.snapshot(t,{buses:e,parameters:i})}snapshot(t,e){return new $(t,e,i=>this.buses.get(i),i=>this.parameters.get(i))}blendSnapshots(t,e,i){t.blendWith(e,i);}ensureGraph(){if(this.master)return;let t=this.host.touch();this.master=new H(t,this.config.master),this.scheduler=new Q(this.host,this.config.tickSource);for(let e of this.busOrder){let i=this.config.buses?.[e]??{},s=new F(t,e,i);s.output.connect(this.master.input),s.notifySoloChange=(r,n)=>this.handleSoloChange(r,n),this.buses.set(e,s),this.voices.has(e)||this.voices.set(e,new Set);}}handleSoloChange(t,e){e?this.soloedBuses.add(t):this.soloedBuses.delete(t);let i=this.soloedBuses.size>0;for(let s of this.buses.values())i?s.applySoloVeil(!this.soloedBuses.has(s)):s.applySoloVeil(false);}},Ot=4;async function Kt(o,t,e){let i=new Array(o.length),s=0,r=async()=>{for(;;){let a=s++;if(a>=o.length)return;i[a]=await e(o[a],a);}},n=Array.from({length:Math.min(t,o.length)},r);return await Promise.all(n),i}function C(o,t){if(t.length===0)return null;let e=null,i=1/0;for(let n of t){let a=Jt(o,n);a<i&&(i=a,e=n);}let s=Math.max(o.length,e?.length??0),r=Math.max(1,Math.ceil(s/2));return e&&i<=r?e:null}function Qt(o,t){if(!o)return t;if(!t||o.aborted)return o;if(t.aborted)return t;let e=new AbortController,i=()=>{o.removeEventListener("abort",s),t.removeEventListener("abort",r);},s=()=>{i(),e.abort(o.reason);},r=()=>{i(),e.abort(t.reason);};return o.addEventListener("abort",s),t.addEventListener("abort",r),e.signal}function Jt(o,t){if(o===t)return 0;if(o.length===0)return t.length;if(t.length===0)return o.length;let e=new Array(t.length+1),i=new Array(t.length+1);for(let s=0;s<=t.length;s++)e[s]=s;for(let s=1;s<=o.length;s++){i[0]=s;for(let r=1;r<=t.length;r++){let n=o.charCodeAt(s-1)===t.charCodeAt(r-1)?0:1;i[r]=Math.min(i[r-1]+1,e[r]+1,e[r-1]+n);}for(let r=0;r<=t.length;r++)e[r]=i[r];}return e[t.length]}export{B as AggregateDecodeError,F as Bus,L as BusGroup,T as BusNotFoundError,it as Compressor,M as DecodeError,st as Ducker,S as EngineClosedError,rt as Filter,H as Master,D as Music,J as MusicVoice,V as Parameter,N as PreloadError,ot as Reverb,Z as Send,$ as Snapshot,R as Sound,A as SoundNotFoundError,q as Spatializer,G as Sprite,z as StreamSound,nt as StretchProcessor,U as Variants,I as Voice,P as ZvukError,k as applyLoudnessNormalization,ct as canPlay,St as computeNormalizationGain,Xt as createEngine,kt as createStretchWorkletNode,Pt as ensureStretchWorklet,lt as mimeForUrl,ht as pickSource,dt as pickSourceOrder};//# sourceMappingURL=index.js.map
|
|
71
71
|
//# sourceMappingURL=index.js.map
|