commit 6d65616f6bf8c97dc7349fef22ad5343976a3e68 Author: Dooho Yi Date: Sat Oct 12 15:28:34 2024 +0900 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9047e54 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.ftpconfig +.jshintrc diff --git a/archive/compass1.html b/archive/compass1.html new file mode 100644 index 0000000..6653048 --- /dev/null +++ b/archive/compass1.html @@ -0,0 +1,138 @@ + + + + + + + + + + + +

lat:

+

long:

+

heading:

+ + + + + + + + + + diff --git a/archive/get_gps_and_heading.html b/archive/get_gps_and_heading.html new file mode 100755 index 0000000..e5eeffd --- /dev/null +++ b/archive/get_gps_and_heading.html @@ -0,0 +1,67 @@ + + + + + + + + + + + +

lat:

+

long:

+

heading:

+ + + + + + + diff --git a/archive/index_alt.html b/archive/index_alt.html new file mode 100644 index 0000000..887c04b --- /dev/null +++ b/archive/index_alt.html @@ -0,0 +1,215 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/archive/index_old.html b/archive/index_old.html new file mode 100755 index 0000000..6204bb5 --- /dev/null +++ b/archive/index_old.html @@ -0,0 +1,479 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/archive/radio_heeju.html b/archive/radio_heeju.html new file mode 100644 index 0000000..63a9004 --- /dev/null +++ b/archive/radio_heeju.html @@ -0,0 +1,44 @@ + + + + + + + + + Radio + + + + + + + + + + + + diff --git a/archive/radio_test_heeju.html b/archive/radio_test_heeju.html new file mode 100755 index 0000000..a9d0658 --- /dev/null +++ b/archive/radio_test_heeju.html @@ -0,0 +1,54 @@ + + + + + + + + + + Sketch + + + + + + + + + + + + + + \ No newline at end of file diff --git a/archive/sound_finder_v1.html b/archive/sound_finder_v1.html new file mode 100644 index 0000000..c61461a --- /dev/null +++ b/archive/sound_finder_v1.html @@ -0,0 +1,375 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/archive/stream_ios.html b/archive/stream_ios.html new file mode 100644 index 0000000..98b836f --- /dev/null +++ b/archive/stream_ios.html @@ -0,0 +1,99 @@ + + + + + + + + + + Sketch + + + + + + + + + + + + + + \ No newline at end of file diff --git a/archive/webaudio_ios.html b/archive/webaudio_ios.html new file mode 100644 index 0000000..90fe8ca --- /dev/null +++ b/archive/webaudio_ios.html @@ -0,0 +1,72 @@ + + + + + + + + + + Sketch + + + + + + + + + + + + + + \ No newline at end of file diff --git a/archive/wonjung.html b/archive/wonjung.html new file mode 100644 index 0000000..3356723 --- /dev/null +++ b/archive/wonjung.html @@ -0,0 +1,447 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/audio/01.mp3 b/audio/01.mp3 new file mode 100644 index 0000000..ab1ecea Binary files /dev/null and b/audio/01.mp3 differ diff --git a/audio/02.mp3 b/audio/02.mp3 new file mode 100644 index 0000000..67b79e6 Binary files /dev/null and b/audio/02.mp3 differ diff --git a/audio/03.mp3 b/audio/03.mp3 new file mode 100644 index 0000000..a1d375c Binary files /dev/null and b/audio/03.mp3 differ diff --git a/audio/04.mp3 b/audio/04.mp3 new file mode 100644 index 0000000..47d3159 Binary files /dev/null and b/audio/04.mp3 differ diff --git a/audio/102.mp3 b/audio/102.mp3 new file mode 100644 index 0000000..26bf19d Binary files /dev/null and b/audio/102.mp3 differ diff --git a/audio/_silence.wav b/audio/_silence.wav new file mode 100644 index 0000000..6b6aed2 Binary files /dev/null and b/audio/_silence.wav differ diff --git a/audio/clap01.mp3 b/audio/clap01.mp3 new file mode 100644 index 0000000..0b7da4f Binary files /dev/null and b/audio/clap01.mp3 differ diff --git a/audio/delayecho.mp3 b/audio/delayecho.mp3 new file mode 100644 index 0000000..ae5e284 Binary files /dev/null and b/audio/delayecho.mp3 differ diff --git a/audio/minok01.mp3 b/audio/minok01.mp3 new file mode 100644 index 0000000..f35b3c3 Binary files /dev/null and b/audio/minok01.mp3 differ diff --git a/audio/minok02.mp3 b/audio/minok02.mp3 new file mode 100644 index 0000000..fb7eaa5 Binary files /dev/null and b/audio/minok02.mp3 differ diff --git a/audio/minok03.mp3 b/audio/minok03.mp3 new file mode 100644 index 0000000..1dc5f54 Binary files /dev/null and b/audio/minok03.mp3 differ diff --git a/audio/minok04.mp3 b/audio/minok04.mp3 new file mode 100644 index 0000000..27b0d7f Binary files /dev/null and b/audio/minok04.mp3 differ diff --git a/audio/minok05.mp3 b/audio/minok05.mp3 new file mode 100644 index 0000000..efd3763 Binary files /dev/null and b/audio/minok05.mp3 differ diff --git a/audio/minok1frequency.mp3 b/audio/minok1frequency.mp3 new file mode 100644 index 0000000..83efb7d Binary files /dev/null and b/audio/minok1frequency.mp3 differ diff --git a/audio/minok2transpose.mp3 b/audio/minok2transpose.mp3 new file mode 100644 index 0000000..bea6105 Binary files /dev/null and b/audio/minok2transpose.mp3 differ diff --git a/audio/minok3delay.mp3 b/audio/minok3delay.mp3 new file mode 100644 index 0000000..910bd09 Binary files /dev/null and b/audio/minok3delay.mp3 differ diff --git a/audio/minok4eq.mp3 b/audio/minok4eq.mp3 new file mode 100644 index 0000000..059dc56 Binary files /dev/null and b/audio/minok4eq.mp3 differ diff --git a/audio/집중호우와멜로디언.mp3 b/audio/집중호우와멜로디언.mp3 new file mode 100644 index 0000000..0c789cd Binary files /dev/null and b/audio/집중호우와멜로디언.mp3 differ diff --git a/css/default.css b/css/default.css new file mode 100644 index 0000000..f99387d --- /dev/null +++ b/css/default.css @@ -0,0 +1,24 @@ +html, +body { + margin: 0; + padding: 0; +} + +canvas { + display: block; +} + +.overlay-userinput { + display: grid; + justify-content: center; + align-items: center; + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background-color: rgba(255, 255, 255, 0.5); + color: white; + z-index: 2; + /* display: none; */ +} diff --git a/index.html b/index.html new file mode 100644 index 0000000..887c04b --- /dev/null +++ b/index.html @@ -0,0 +1,215 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/js/Tone-14.8.36.min.js b/js/Tone-14.8.36.min.js new file mode 100644 index 0000000..bccdaa6 --- /dev/null +++ b/js/Tone-14.8.36.min.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Tone=e():t.Tone=e()}("undefined"!=typeof self?self:this,function(){return(()=>{var s={228:t=>{t.exports=function(t,e){(null==e||e>t.length)&&(e=t.length);for(var s=0,n=new Array(e);s{t.exports=function(t){if(Array.isArray(t))return t},t.exports.default=t.exports,t.exports.__esModule=!0},575:t=>{t.exports=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},t.exports.default=t.exports,t.exports.__esModule=!0},913:t=>{function n(t,e){for(var s=0;s{t.exports=function(t,e){var s=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=s){var n,i,r=[],o=!0,a=!1;try{for(s=s.call(t);!(o=(n=s.next()).done)&&(r.push(n.value),!e||r.length!==e);o=!0);}catch(t){a=!0,i=t}finally{try{o||null==s.return||s.return()}finally{if(a)throw i}}return r}},t.exports.default=t.exports,t.exports.__esModule=!0},521:t=>{t.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},t.exports.default=t.exports,t.exports.__esModule=!0},38:(t,e,s)=>{var n=s(858),i=s(884),r=s(379),o=s(521);t.exports=function(t,e){return n(t)||i(t,e)||r(t,e)||o()},t.exports.default=t.exports,t.exports.__esModule=!0},379:(t,e,s)=>{var n=s(228);t.exports=function(t,e){if(t){if("string"==typeof t)return n(t,e);var s=Object.prototype.toString.call(t).slice(8,-1);return"Map"===(s="Object"===s&&t.constructor?t.constructor.name:s)||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?n(t,e):void 0}},t.exports.default=t.exports,t.exports.__esModule=!0},382:function(t,e,s){!function(t,e,s,n){"use strict";function i(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}function o(t,e,s){return{endTime:e,insertTime:s,type:"exponentialRampToValue",value:t}}function a(t,e,s){return{endTime:e,insertTime:s,type:"linearRampToValue",value:t}}function h(t,e){return{startTime:e,type:"setValue",value:t}}function c(t,e,s){return{duration:s,startTime:e,type:"setValueCurve",values:t}}function l(t,e,s){var n=s.startTime,i=s.target,s=s.timeConstant;return i+(e-i)*Math.exp((n-t)/s)}function u(t){return"exponentialRampToValue"===t.type}function p(t){return"linearRampToValue"===t.type}function d(t){return u(t)||p(t)}function f(t){return"setValue"===t.type}function _(t){return"setValueCurve"===t.type}function m(t,e,s,n){var i=t[e];return void 0===i?n:d(i)||f(i)?i.value:_(i)?i.values[i.values.length-1]:l(s,m(t,e-1,i.startTime,n),i)}function g(t,e,s,n,i){return void 0===s?[n.insertTime,i]:d(s)?[s.endTime,s.value]:f(s)?[s.startTime,s.value]:_(s)?[s.startTime+s.duration,s.values[s.values.length-1]]:[s.startTime,m(t,e-1,s.startTime,i)]}function v(t){return"cancelAndHold"===t.type}function y(t){return"cancelScheduledValues"===t.type}function x(t){return v(t)||y(t)?t.cancelTime:u(t)||p(t)?t.endTime:t.startTime}function w(t,e,s,n){var i=n.endTime,n=n.value;return s===n?n:0=s:x(t)>=s}),n=this._automationEvents[t];if(-1!==t&&(this._automationEvents=this._automationEvents.slice(0,t)),v(e)){var i=this._automationEvents[this._automationEvents.length-1];if(void 0!==n&&d(n)){if(T(i))throw new Error("The internal list is malformed.");var t=_(i)?i.startTime+i.duration:x(i),r=_(i)?i.values[i.values.length-1]:i.value,r=(u(n)?w:b)(s,t,r,n),r=(u(n)?o:a)(r,s,this._currenTime);this._automationEvents.push(r)}void 0!==i&&T(i)&&this._automationEvents.push(h(this.getValue(s),s)),void 0!==i&&_(i)&&i.startTime+i.duration>s&&(this._automationEvents[this._automationEvents.length-1]=c(new Float32Array([6,7]),i.startTime,s-i.startTime))}}else{r=this._automationEvents.findIndex(function(t){return x(t)>s}),i=-1===r?this._automationEvents[this._automationEvents.length-1]:this._automationEvents[r-1];if(void 0!==i&&_(i)&&x(i)+i.duration>s)return!1;i=u(e)?o(e.value,e.endTime,this._currenTime):p(e)?a(e.value,s,this._currenTime):e;if(-1===r)this._automationEvents.push(i);else{if(_(e)&&s+e.duration>x(this._automationEvents[r]))return!1;this._automationEvents.splice(r,0,i)}}return!0}},{key:"flush",value:function(e){var t,s,n=this._automationEvents.findIndex(function(t){return x(t)>e});1e}),n=this._automationEvents[s],i=(-1===s?this._automationEvents.length:s)-1,r=this._automationEvents[i];if(void 0!==r&&T(r)&&(void 0===n||!d(n)||n.insertTime>e))return l(e,m(this._automationEvents,i-1,r.startTime,this._defaultValue),r);if(void 0!==r&&f(r)&&(void 0===n||!d(n)))return r.value;if(void 0!==r&&_(r)&&(void 0===n||!d(n)||r.startTime+r.duration>e))return e{for(var s in e)qm.o(e,s)&&!qm.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},qm.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),qm.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var Fm={};return(()=>{"use strict";qm.r(Fm),qm.d(Fm,{AMOscillator:()=>sf,AMSynth:()=>If,Abs:()=>yf,Add:()=>lf,AmplitudeEnvelope:()=>Rf,Analyser:()=>nm,AudioToGain:()=>tf,AutoFilter:()=>x_,AutoPanner:()=>b_,AutoWah:()=>S_,BaseContext:()=>Bp,BiquadFilter:()=>Vf,BitCrusher:()=>A_,Buffer:()=>Mm,BufferSource:()=>Rm,Buffers:()=>Em,Channel:()=>um,Chebyshev:()=>D_,Chorus:()=>q_,Clock:()=>Dd,Compressor:()=>gm,Context:()=>Up,Convolver:()=>Tm,CrossFade:()=>g_,DCMeter:()=>am,Delay:()=>Od,Destination:()=>km,Distortion:()=>F_,Draw:()=>Dm,DuoSynth:()=>Lf,EQ3:()=>bm,Emitter:()=>Wp,Envelope:()=>Df,FFT:()=>om,FMOscillator:()=>nf,FMSynth:()=>zf,FatOscillator:()=>of,FeedbackCombFilter:()=>Hf,FeedbackDelay:()=>V_,Filter:()=>Nf,Follower:()=>T_,Freeverb:()=>z_,Frequency:()=>function(t,e){return new cd(Jp(),t,e)},FrequencyClass:()=>cd,FrequencyEnvelope:()=>Pf,FrequencyShifter:()=>P_,Gain:()=>xd,GainToAudio:()=>xf,Gate:()=>vm,GrainPlayer:()=>vf,GreaterThan:()=>Sf,GreaterThanZero:()=>Tf,IntervalTimeline:()=>Fd,JCReverb:()=>G_,LFO:()=>df,Limiter:()=>ym,Listener:()=>Cm,Loop:()=>i_,LowpassCombFilter:()=>Kf,Master:()=>Am,MembraneSynth:()=>Uf,Merge:()=>M_,MetalSynth:()=>Bf,Meter:()=>rm,MidSideCompressor:()=>xm,MidSideMerge:()=>J_,MidSideSplit:()=>H_,Midi:()=>function(t,e){return new Ed(Jp(),t,e)},MidiClass:()=>Ed,Mono:()=>pm,MonoSynth:()=>jf,MultibandCompressor:()=>wm,MultibandSplit:()=>dm,Multiply:()=>ef,Negate:()=>wf,Noise:()=>Ud,NoiseSynth:()=>Gf,Offline:()=>function(n,i,r=2,o=Jp().sampleRate){return yp(this,void 0,void 0,function*(){const t=Jp(),e=new Yp(r,i,o);Kp(e),yield n(e);var s=e.render();Kp(t);s=yield s;return new Xp(s)})},OfflineContext:()=>Yp,OmniOscillator:()=>cf,OnePoleFilter:()=>Jf,Oscillator:()=>Hd,PWMOscillator:()=>af,PanVol:()=>lm,Panner:()=>w_,Panner3D:()=>_m,Param:()=>_d,Part:()=>r_,Pattern:()=>__,Phaser:()=>Y_,PingPongDelay:()=>Z_,PitchShift:()=>X_,Player:()=>mf,Players:()=>gf,PluckSynth:()=>t_,PolySynth:()=>e_,Pow:()=>kf,PulseOscillator:()=>rf,Recorder:()=>mm,Reverb:()=>$_,Sampler:()=>s_,Scale:()=>uf,ScaleExp:()=>Af,Sequence:()=>m_,Signal:()=>Td,Solo:()=>cm,Split:()=>O_,StateTimeline:()=>fd,StereoWidener:()=>tm,Subtract:()=>bf,SyncedSignal:()=>Cf,Synth:()=>qf,Ticks:()=>function(t,e){return new Rd(Jp(),t,e)},TicksClass:()=>Rd,Time:()=>function(t,e){return new hd(Jp(),t,e)},TimeClass:()=>hd,Timeline:()=>Np,ToneAudioBuffer:()=>Xp,ToneAudioBuffers:()=>Md,ToneAudioNode:()=>md,ToneBufferSource:()=>Bd,ToneEvent:()=>n_,ToneOscillatorNode:()=>$d,Transport:()=>Sm,TransportTime:()=>function(t,e){return new pd(Jp(),t,e)},TransportTimeClass:()=>pd,Tremolo:()=>em,Unit:()=>e,UserMedia:()=>Xd,Vibrato:()=>sm,Volume:()=>Vd,WaveShaper:()=>Kd,Waveform:()=>hm,Zero:()=>pf,connect:()=>vd,connectSeries:()=>gd,connectSignal:()=>Sd,context:()=>Om,dbToGain:()=>td,debug:()=>t,defaultArg:()=>Dp,disconnect:()=>yd,fanIn:()=>function(...t){const e=t.pop();Ju(e)&&t.forEach(t=>vd(t,e))},ftom:()=>id,gainToDb:()=>ed,getContext:()=>Jp,getDestination:()=>function(){return Jp().destination},getDraw:()=>function(){return Jp().draw},getListener:()=>function(){return Jp().listener},getTransport:()=>function(){return Jp().transport},immediate:()=>function(){return Jp().immediate()},intervalToFrequencyRatio:()=>sd,isArray:()=>np,isBoolean:()=>sp,isDefined:()=>Ju,isFunction:()=>Ku,isNote:()=>rp,isNumber:()=>tp,isObject:()=>ep,isString:()=>ip,isUndef:()=>Hu,loaded:()=>function(){return Xp.loaded()},mtof:()=>od,now:()=>function(){return Jp().now()},optionsFromArguments:()=>Cp,setContext:()=>Kp,start:()=>function(){return Hp.resume()},supported:()=>$u,version:()=>s});var t={};qm.r(t),qm.d(t,{assert:()=>op,assertContextRunning:()=>hp,assertRange:()=>ap,assertUsedScheduleTime:()=>pp,enterScheduledCallback:()=>up,log:()=>fp,setLogger:()=>function(t){dp=t},warn:()=>_p});var e={};qm.r(e);const s="14.8.36";var n,i,a,o,r,h,c,l,u,p,d,f,_,m,g,v,y,x,w,b,T,S,k,A,C,D,O,M,E,R,q,F,I,V,N,P,j,L,z,W,B,U,G,Q,Z,X,Y,$,H,J,K,tt,et,st,nt=qm(382);const it=new WeakSet,rt=new WeakMap,ot=new WeakMap,at=new WeakMap,ht=new WeakMap,ct=new WeakMap,lt=new WeakMap,ut=new WeakMap,pt=new WeakMap,dt=new WeakMap,ft={construct:()=>ft},_t=/^import(?:(?:[\s]+[\w]+|(?:[\s]+[\w]+[\s]*,)?[\s]*\{[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?(?:[\s]*,[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?)*[\s]*}|(?:[\s]+[\w]+[\s]*,)?[\s]*\*[\s]+as[\s]+[\w]+)[\s]+from)?(?:[\s]*)("([^"\\]|\\.)+"|'([^'\\]|\\.)+')(?:[\s]*);?/,mt=(t,e)=>{const s=[];let n=t.replace(/^[\s]+/,""),i=n.match(_t);for(;null!==i;){const t=i[1].slice(1,-1),r=i[0].replace(/([\s]+)?;?$/,"").replace(t,new URL(t,e).toString());s.push(r),n=n.slice(i[0].length).replace(/^[\s]+/,""),i=n.match(_t)}return[s.join(";"),n]},gt=t=>{if(void 0!==t&&!Array.isArray(t))throw new TypeError("The parameterDescriptors property of given value for processorCtor is not an array.")},vt=t=>{if(!(t=>{try{new new Proxy(t,ft)}catch{return!1}return!0})(t))throw new TypeError("The given value for processorCtor should be a constructor.");if(null===t.prototype||"object"!=typeof t.prototype)throw new TypeError("The given value for processorCtor should have a prototype.")},yt=(t,e)=>{e=t.get(e);if(void 0===e)throw new Error("A value with the given key could not be found.");return e},xt=(t,e)=>{e=Array.from(t).filter(e);if(1{var i=yt(t,e),r=xt(i,t=>t[0]===s&&t[1]===n);return 0===i.size&&t.delete(e),r},bt=t=>yt(lt,t),Tt=t=>{if(it.has(t))throw new Error("The AudioNode is already stored.");it.add(t),bt(t).forEach(t=>t(!0))},St=t=>"port"in t,kt=t=>{if(!it.has(t))throw new Error("The AudioNode is not stored.");it.delete(t),bt(t).forEach(t=>t(!1))},At=(t,e)=>{!St(t)&&e.every(t=>0===t.size)&&kt(t)},Ct={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",fftSize:2048,maxDecibels:-30,minDecibels:-100,smoothingTimeConstant:.8},Dt=(t,e)=>t.context===e,Ot=t=>{try{t.copyToChannel(new Float32Array(1),0,-1)}catch{return!1}return!0},Mt=()=>new DOMException("","IndexSizeError"),Et=e=>{var s;e.getChannelData=(s=e.getChannelData,t=>{try{return s.call(e,t)}catch(t){if(12===t.code)throw Mt();throw t}})},Rt={numberOfChannels:1},qt=-34028234663852886e22,Ft=-qt,It=t=>it.has(t),Vt={buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1},Nt=t=>yt(rt,t),Pt=t=>yt(at,t),jt=(e,s)=>{const t=Nt(e)["activeInputs"];t.forEach(t=>t.forEach(([t])=>{s.includes(e)||jt(t,[...s,e])}));var n,i,n="playbackRate"in e?[e.playbackRate]:St(e)?Array.from(e.parameters.values()):"frequency"in(i=e)&&"gain"in i?[e.Q,e.detune,e.frequency,e.gain]:"offset"in e?[e.offset]:!("frequency"in(i=e))&&"gain"in i?[e.gain]:"detune"in(n=e)&&"frequency"in n?[e.detune,e.frequency]:"pan"in e?[e.pan]:[];for(const e of n){const t=Pt(e);void 0!==t&&t.activeInputs.forEach(([t])=>jt(t,s))}It(e)&&kt(e)},Lt=t=>{jt(t.destination,[])},zt=t=>"context"in t,Wt=t=>zt(t[0]),Bt=(t,e,s,n)=>{for(const e of t)if(s(e)){if(n)return!1;throw Error("The set contains at least one similar element.")}return t.add(e),!0},Ut=(t,e,[s,n],i)=>{Bt(t,[e,s,n],t=>t[0]===e&&t[1]===s,i)},Gt=(t,[e,s,n],i)=>{var r=t.get(e);void 0===r?t.set(e,new Set([[s,n]])):Bt(r,[s,n],t=>t[0]===s,i)},Qt=t=>"inputs"in t,Zt=(t,e,s,n)=>{if(Qt(e)){var i=e.inputs[n];return t.connect(i,s,0),[i,s,0]}return t.connect(e,s,n),[e,s,n]},Xt=(t,e,s)=>{for(const n of t)if(n[0]===e&&n[1]===s)return t.delete(n),n;return null},Yt=(t,e)=>{if(!bt(t).delete(e))throw new Error("Missing the expected event listener.")},$t=(t,e,s)=>{var n=yt(t,e),i=xt(n,t=>t[0]===s);return 0===n.size&&t.delete(e),i},Ht=(t,e,s,n)=>{Qt(e)?t.disconnect(e.inputs[n],s,0):t.disconnect(e,s,n)},Jt=t=>yt(ot,t),Kt=t=>yt(ht,t),te=t=>ut.has(t),ee=t=>!it.has(t),se=(r,o)=>new Promise(e=>{if(null!==o)e(!0);else{const o=r.createScriptProcessor(256,1,1),t=r.createGain(),s=r.createBuffer(1,2,44100),n=s.getChannelData(0);n[0]=1,n[1]=1;const i=r.createBufferSource();i.buffer=s,i.loop=!0,i.connect(o).connect(r.destination),i.connect(t),i.disconnect(t),o.onaudioprocess=t=>{t=t.inputBuffer.getChannelData(0);Array.prototype.some.call(t,t=>1===t)?e(!0):e(!1),i.stop(),o.onaudioprocess=null,i.disconnect(o),o.disconnect(r.destination)},i.start()}}),ne=(t,s)=>{const e=new Map;for(const s of t)for(const t of s){const s=e.get(t);e.set(t,void 0===s?1:s+1)}e.forEach((t,e)=>s(e,t))},ie=t=>"context"in t,re=(t,e,s,n,i)=>{var[r,o]=((t,e,s,n)=>{var{activeInputs:i,passiveInputs:e}=Nt(e),i=Xt(i[n],t,s);return null===i?[wt(e,t,s,n)[2],!1]:[i[2],!0]})(t,s,n,i);if(null!==r&&(Yt(t,r),!o||e||te(t)||Ht(Jt(t),Jt(s),n,i)),It(s)){const t=Nt(s)["activeInputs"];At(s,t)}},oe=(t,e,s,n)=>{var[i,r]=((t,e,s)=>{var{activeInputs:n,passiveInputs:e}=Pt(e),n=Xt(n,t,s);return null===n?[$t(e,t,s)[1],!1]:[n[2],!0]})(t,s,n);null!==i&&(Yt(t,i),!r||e||te(t)||Jt(t).disconnect(Kt(s),n))};class ae{constructor(t){this._map=new Map(t)}get size(){return this._map.size}entries(){return this._map.entries()}forEach(s,n=null){return this._map.forEach((t,e)=>s.call(n,t,e,this))}get(t){return this._map.get(t)}has(t){return this._map.has(t)}keys(){return this._map.keys()}values(){return this._map.values()}}const he={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:1,numberOfOutputs:1,parameterData:{},processorOptions:{}};function ce(t,e,s,n,i){if("function"==typeof t.copyFromChannel)0===e[s].byteLength&&(e[s]=new Float32Array(128)),t.copyFromChannel(e[s],n,i);else{const r=t.getChannelData(n);if(0===e[s].byteLength)e[s]=r.slice(i,i+128);else{const t=new Float32Array(r.buffer,i*Float32Array.BYTES_PER_ELEMENT,128);e[s].set(t)}}}const le=(t,e,s,n,i)=>{"function"==typeof t.copyToChannel?0!==e[s].byteLength&&t.copyToChannel(e[s],n,i):0!==e[s].byteLength&&t.getChannelData(n).set(e[s],i)},ue=(e,s)=>{const n=[];for(let t=0;t{const{port1:n,port2:i}=new MessageChannel;return new Promise(t=>{const e=()=>{i.onmessage=null,n.close(),i.close(),t()};i.onmessage=()=>e();try{n.postMessage(s,[s])}finally{e()}})},ve={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",delayTime:0,maxDelayTime:1},ye=(t,e,s)=>{s=e[s];if(void 0===s)throw t();return s},xe={attack:.003,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",knee:30,ratio:12,release:.25,threshold:-24},we={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",gain:1},be=()=>new DOMException("","InvalidStateError"),Te=()=>new DOMException("","InvalidAccessError"),Se={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers"},ke=(s,n,i,r,o,a,h,t,c,l,u)=>{var e=l.length;let p=t;for(let t=0;t{var e=new Uint32Array([1179011410,40,1163280727,544501094,16,131073,44100,176400,1048580,1635017060,4,0]);try{const s=t.decodeAudioData(e.buffer,()=>{});return void 0!==s&&(s.catch(()=>{}),!0)}catch{}return!1},De=(t,e,s)=>{e=e[s];void 0!==e&&e!==t[s]&&(t[s]=e)},Oe=(t,e)=>{De(t,e,"channelCount"),De(t,e,"channelCountMode"),De(t,e,"channelInterpretation")},Me=t=>"function"==typeof t.getFloatTimeDomainData,Ee=(t,e,s)=>{e=e[s];void 0!==e&&e!==t[s].value&&(t[s].value=e)},Re=n=>{var i;n.start=(i=n.start,(t=0,e=0,s)=>{if("number"==typeof s&&s<0||e<0||t<0)throw new RangeError("The parameters can't be negative.");i.call(n,t,e,s)})},qe=e=>{var s;e.stop=(s=e.stop,(t=0)=>{if(t<0)throw new RangeError("The parameter can't be negative.");s.call(e,t)})},Fe=(t,e)=>null===t?512:Math.max(512,Math.min(16384,Math.pow(2,Math.round(Math.log2(t*e))))),Ie=(t,e)=>{t=t.createBiquadFilter();return Oe(t,e),Ee(t,e,"Q"),Ee(t,e,"detune"),Ee(t,e,"frequency"),Ee(t,e,"gain"),De(t,e,"type"),t},Ve=(t,e)=>{t=t.createChannelSplitter(e.numberOfOutputs);return Oe(t,e),(t=>{const e=t.numberOfOutputs;Object.defineProperty(t,"channelCount",{get:()=>e,set:t=>{if(t!==e)throw be()}}),Object.defineProperty(t,"channelCountMode",{get:()=>"explicit",set:t=>{if("explicit"!==t)throw be()}}),Object.defineProperty(t,"channelInterpretation",{get:()=>"discrete",set:t=>{if("discrete"!==t)throw be()}})})(t),t},Ne=(t,e)=>(t.connect=e.connect.bind(e),t.disconnect=e.disconnect.bind(e),t),Pe=(t,e)=>{t=t.createDelay(e.maxDelayTime);return Oe(t,e),Ee(t,e,"delayTime"),t},je=(t,e)=>{t=t.createGain();return Oe(t,e),Ee(t,e,"gain"),t};function Le(e,s){let n=[0,0];for(let t=e.length-1;0<=t;--t)n=[(i=n)[0]*s[0]-i[1]*s[1],i[0]*s[1]+i[1]*s[0]],n[0]+=e[t];var i;return n}const ze=(t,e,s,n)=>t.createScriptProcessor(e,s,n),We=()=>new DOMException("","NotSupportedError"),Be={numberOfChannels:1},Ue={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:440,periodicWave:void 0,type:"sine"},Ge={channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",coneInnerAngle:360,coneOuterAngle:360,coneOuterGain:0,distanceModel:"inverse",maxDistance:1e4,orientationX:1,orientationY:0,orientationZ:0,panningModel:"equalpower",positionX:0,positionY:0,positionZ:0,refDistance:1,rolloffFactor:1},Qe={disableNormalization:!1},Ze={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",pan:0},Xe={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",curve:null,oversample:"none"},Ye=(t,e,s)=>void 0===t.copyFromChannel?t.getChannelData(s)[0]:(t.copyFromChannel(e,s),e[0]),$e=t=>{if(null===t)return!1;var e=t.length;return e%2!=0?0!==t[Math.floor(e/2)]:t[e/2-1]+t[e/2]!==0},He=(t,e,s,n)=>{let i=t;for(;!i.hasOwnProperty(e);)i=Object.getPrototypeOf(i);var{get:r,set:o}=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,{get:s(r),set:n(o)})},Je=(e,s,n)=>{try{e.setValueAtTime(s,n)}catch(t){if(9!==t.code)throw t;Je(e,s,n+1e-7)}},Ke=t=>{const e=t.createOscillator();try{e.start(-1)}catch(t){return t instanceof RangeError}return!1},ts=t=>{const e=t.createBuffer(1,1,44100),s=t.createBufferSource();s.buffer=e,s.start(),s.stop();try{return s.stop(),!0}catch{return!1}},es=t=>{const e=t.createOscillator();try{e.stop(-1)}catch(t){return t instanceof RangeError}return!1},ss=()=>{try{new DOMException}catch{return!1}return!0},ns=()=>new Promise(e=>{const t=new ArrayBuffer(0),{port1:s,port2:n}=new MessageChannel;s.onmessage=({data:t})=>e(null!==t),n.postMessage(t,[t])}),is=(n,t)=>{const i=t.createGain();n.connect(i);const e=(s=n.disconnect,()=>{s.call(n,i),n.removeEventListener("ended",e)});var s;n.addEventListener("ended",e),Ne(n,i),n.stop=(e=>{let s=!1;return(t=0)=>{if(s)try{e.call(n,t)}catch{i.gain.setValueAtTime(0,t)}else e.call(n,t),s=!0}})(n.stop)},rs=(s,n)=>t=>{var e={value:s};return Object.defineProperties(t,{currentTarget:e,target:e}),("function"==typeof n?n:n.handleEvent).call(s,t)},os=(o=Bt,(t,e,[s,n,i],r)=>{o(t[n],[e,s,i],t=>t[0]===e&&t[1]===s,r)}),as=(a=Bt,(t,e,[s,n,i],r)=>{var o=t.get(s);void 0===o?t.set(s,new Set([[n,e,i]])):a(o,[n,e,i],t=>t[0]===n&&t[1]===e,r)}),hs=(i=xt,(t,e,s,n)=>i(t[n],t=>t[0]===e&&t[1]===s)),cs=new WeakMap,ls=(n=cs,t=>{return null!==(t=n.get(t))&&void 0!==t?t:0}),us=(r=new Map,h=new WeakMap,(e,t)=>{const s=h.get(e);if(void 0!==s)return s;var n=r.get(e);if(void 0!==n)return n;try{const s=t();return s instanceof Promise?(r.set(e,s),s.catch(()=>!1).then(t=>(r.delete(e),h.set(e,t),t))):(h.set(e,s),s)}catch{return h.set(e,!1),!1}}),ps="undefined"==typeof window?null:window,ds=(m=us,g=Mt,(t,e)=>{const s=t.createAnalyser();if(Oe(s,e),!(e.maxDecibels>e.minDecibels))throw g();return De(s,e,"fftSize"),De(s,e,"maxDecibels"),De(s,e,"minDecibels"),De(s,e,"smoothingTimeConstant"),m(Me,()=>Me(s))||((i=s).getFloatTimeDomainData=e=>{var s=new Uint8Array(e.length);i.getByteTimeDomainData(s);var n=Math.max(s.length,i.fftSize);for(let t=0;t{t=_(t);if(null===t.renderer)throw new Error("Missing the renderer of the given AudioNode in the audio graph.");return t.renderer}),_s=(p=Nt,d=fs,f=te,async(o,a,h)=>{const t=p(o);await Promise.all(t.activeInputs.map((t,r)=>Array.from(t).map(async([t,e])=>{const s=d(t),n=await s.render(t,a),i=o.context.destination;f(t)||o===i&&f(o)||n.connect(h,e,r)})).reduce((t,e)=>[...t,...e],[]))}),ms=(c=ds,l=Jt,u=_s,()=>{const n=new WeakMap;return{render(t,e){var s=n.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=l(t);if(!Dt(s,e)){const l={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,fftSize:s.fftSize,maxDecibels:s.maxDecibels,minDecibels:s.minDecibels,smoothingTimeConstant:s.smoothingTimeConstant};s=c(e,l)}return n.set(e,s),await u(t,e,s),s})(t,e)}}}),gs=(v=ct,t=>{t=v.get(t);if(void 0===t)throw be();return t}),vs=null===(Jc=ps)?null:Jc.hasOwnProperty("OfflineAudioContext")?Jc.OfflineAudioContext:Jc.hasOwnProperty("webkitOfflineAudioContext")?Jc.webkitOfflineAudioContext:null,ys=(et=vs,t=>null!==et&&t instanceof et),xs=new WeakMap,ws=(tt=rs,class{constructor(t){this._nativeEventTarget=t,this._listeners=new WeakMap}addEventListener(e,s,n){if(null!==s){let t=this._listeners.get(s);void 0===t&&(t=tt(this,s),"function"==typeof s&&this._listeners.set(s,t)),this._nativeEventTarget.addEventListener(e,t,n)}}dispatchEvent(t){return this._nativeEventTarget.dispatchEvent(t)}removeEventListener(t,e,s){e=null===e?void 0:this._listeners.get(e);this._nativeEventTarget.removeEventListener(t,void 0===e?null:e,s)}}),bs=null===(ol=ps)?null:ol.hasOwnProperty("AudioContext")?ol.AudioContext:ol.hasOwnProperty("webkitAudioContext")?ol.webkitAudioContext:null,Ts=(K=bs,t=>null!==K&&t instanceof K),Ss=(J=ps,t=>null!==J&&"function"==typeof J.AudioNode&&t instanceof J.AudioNode),ks=(H=ps,t=>null!==H&&"function"==typeof H.AudioParam&&t instanceof H.AudioParam),As=null!==(al=ps)&&al.hasOwnProperty("AudioWorkletNode")?al.AudioWorkletNode:null,Cs=(st=rt,y=(t,e,s)=>{const n=[];for(let t=0;t{const T=new WeakMap;return(n,i,r,o,a)=>{const{activeInputs:h,passiveInputs:c}=_(i),t=_(n)["outputs"],e=g(n),s=t=>{var e=v(i),s=v(n);if(t){const u=wt(c,n,r,o);l(h,n,u,!1),a||w(n)||p(s,e,r,o),b(i)&&Tt(i)}else{const l=d(h,n,r,o);u(c,o,l,!1),a||w(n)||f(s,e,r,o);const p=m(i);if(0===p)x(i)&&At(i,h);else{const l=T.get(i);void 0!==l&&clearTimeout(l),T.set(i,setTimeout(()=>{x(i)&&At(i,h)},1e3*p))}}};return!!y(t,[i,r,o],t=>t[0]===i&&t[1]===r&&t[2]===o,!0)&&(e.add(s),x(n)?l(h,n,[r,o,s],!0):u(c,o,[n,r,s],!0),!0)}})(os,as,Zt,hs,Ht,Nt,ls,bt,Jt,Bt,It,te,ee),w=us,G=ut,Q=Ht,Z=Nt,X=Jt,Y=Kt,$=It,b=n=>(t,e)=>{var s=G.get(t);if(void 0===s){if(!n&&$(t)){const G=X(t),$=Z(t)["outputs"];for(const Z of $)if(Wt(Z)){const Y=X(Z[0]);Q(G,Y,Z[1],Z[2])}else{const Q=Y(Z[0]);G.disconnect(Q,Z[1])}}G.set(t,e)}else G.set(t,s+e)},T=Mt,S=Te,k=We,N=Zt,P=ut,j=Nt,L=Jt,z=Kt,W=gs,B=It,U=ys,A=(t,e)=>{var s=P.get(t);if(void 0===s)throw new Error("Missing the expected cycle count.");var n=W(t.context),n=U(n);if(s===e){if(P.delete(t),!n&&B(t)){const P=L(t),W=j(t)["outputs"];for(const j of W)if(Wt(j)){const z=L(j[0]);N(P,z,j[1],j[2])}else{const N=z(j[0]);P.connect(N,j[1])}}}else P.set(t,s-e)},F=xs,I=Nt,V=yt,C=function e(s,t){const n=zt(t)?t:V(F,t);if("delayTime"in n)return[];if(s[0]===n)return[s];if(s.includes(n))return[];var t=I(n)["outputs"];return Array.from(t).map(t=>e([...s,n],t[0])).reduce((t,e)=>t.concat(e),[])},Ds=ws,O=Ts,M=Ss,E=ks,q=As,class extends Ds{constructor(t,e,s,n){super(s),this._context=t,this._nativeAudioNode=s;const i=D(t);O(i)&&!0!==w(se,()=>se(i,q))&&(i=>{const r=new Map;var o,a;i.connect=(a=i.connect.bind(i),(t,e=0,s=0)=>{const n=ie(t)?a(t,e,s):a(t,e),i=r.get(t);return void 0===i?r.set(t,[{input:s,output:e}]):i.every(t=>t.input!==s||t.output!==e)&&i.push({input:s,output:e}),n}),i.disconnect=(o=i.disconnect,(e,s,n)=>{if(o.apply(i),void 0===e)r.clear();else if("number"==typeof e)for(const[i,o]of r){const s=o.filter(t=>t.output!==e);0===s.length?r.delete(i):r.set(i,s)}else if(r.has(e))if(void 0===s)r.delete(e);else{const i=r.get(e);if(void 0!==i){const o=i.filter(t=>t.output!==s&&(t.input!==n||void 0===n));0===o.length?r.delete(e):r.set(e,o)}}for(const[o,e]of r)e.forEach(t=>{ie(o)?i.connect(o,t.output,t.input):i.connect(o,t.output)})})})(s),ot.set(this,s),lt.set(this,new Set),"closed"!==t.state&&e&&Tt(this),y(this,n,s)}get channelCount(){return this._nativeAudioNode.channelCount}set channelCount(t){this._nativeAudioNode.channelCount=t}get channelCountMode(){return this._nativeAudioNode.channelCountMode}set channelCountMode(t){this._nativeAudioNode.channelCountMode=t}get channelInterpretation(){return this._nativeAudioNode.channelInterpretation}set channelInterpretation(t){this._nativeAudioNode.channelInterpretation=t}get context(){return this._context}get numberOfInputs(){return this._nativeAudioNode.numberOfInputs}get numberOfOutputs(){return this._nativeAudioNode.numberOfOutputs}connect(t,e=0,s=0){if(e<0||e>=this._nativeAudioNode.numberOfOutputs)throw T();var n=D(this._context),n=R(n);if(M(t)||E(t))throw S();if(zt(t)){const T=Jt(t);try{const x=Zt(this._nativeAudioNode,T,e,s),b=ee(this);(n||b)&&this._nativeAudioNode.disconnect(...x),"closed"!==this.context.state&&!b&&ee(t)&&Tt(t)}catch(t){if(12===t.code)throw S();throw t}if(x(this,t,e,s,n)){const x=C([this],t);ne(x,b(n))}return t}s=Kt(t);if("playbackRate"===s.name&&1024===s.maxValue)throw k();try{this._nativeAudioNode.connect(s,e),(n||ee(this))&&this._nativeAudioNode.disconnect(s,e)}catch(t){if(12===t.code)throw S();throw t}if(((r,o,a,h)=>{const{activeInputs:c,passiveInputs:l}=Pt(o),t=Nt(r)["outputs"],e=bt(r),s=t=>{const e=Jt(r),s=Kt(o);if(t){const o=$t(l,r,a);Ut(c,r,o,!1),h||te(r)||e.connect(s,a)}else{const o=(t=c,n=r,i=a,xt(t,t=>t[0]===n&&t[1]===i));Gt(l,o,!1),h||te(r)||e.disconnect(s,a)}var n,i};return!!Bt(t,[o,a],t=>t[0]===o&&t[1]===a,!0)&&(e.add(s),It(r)?Ut(c,r,[a,s],!0):Gt(l,[r,a,s],!0),!0)})(this,t,e,n)){const x=C([this],t);ne(x,b(n))}}disconnect(t,e,s){let n;var i=D(this._context),i=R(i);if(void 0===t)n=((t,e)=>{const s=Nt(t),n=[];for(const i of s.outputs)(Wt(i)?re:oe)(t,e,...i),n.push(i[0]);return s.outputs.clear(),n})(this,i);else if("number"==typeof t){if(t<0||t>=this.numberOfOutputs)throw T();n=((t,e,s)=>{const n=Nt(t),i=[];for(const r of n.outputs)r[1]===s&&((Wt(r)?re:oe)(t,e,...r),i.push(r[0]),n.outputs.delete(r));return i})(this,i,t)}else{if(void 0!==e&&(e<0||e>=this.numberOfOutputs))throw T();if(zt(t)&&void 0!==s&&(s<0||s>=t.numberOfInputs))throw T();if(n=((e,s,n,i,r)=>{const o=Nt(e);return Array.from(o.outputs).filter(t=>!(t[0]!==n||void 0!==i&&t[1]!==i||void 0!==r&&t[2]!==r)).map(t=>((Wt(t)?re:oe)(e,s,...t),o.outputs.delete(t),t[0]))})(this,i,t,e,s),0===n.length)throw S()}for(const t of n){const e=C([this],t);ne(e,A)}}});var Ds,Os,Ms,Es,Rs,qs,Fs,Is,Vs,Ns,Ps,js,Ls,zs,Ws,Bs,Us,Gs,Qs,Zs,Xs,Ys,$s,Hs,Js,Ks,tn,en,sn,nn,rn,on,an,hn,cn,ln,un,pn,dn,fn,_n,mn,gn,vn,yn,xn,wn,bn,Tn,Sn,kn,An,Cn,Dn,On,Mn,En,Rn,qn,Fn,In,Vn,Nn,Pn,jn,Ln,zn,Wn,Bn,Un,Gn,Qn,Zn,Xn,Yn,$n,Hn,Jn,Kn,ti,ei,si,ni,ii,ri,oi,ai,hi,ci,li,ui,pi,di,fi,_i,mi,gi,vi,yi,xi,wi,bi,Ti,Si,ki,Ai,Ci,Di,Oi,Mi,Ei,Ri,qi,Fi,Ii,Vi,Ni,Pi,ji,Li,zi,Wi,Bi,Ui,Gi,Qi,Zi,Xi,Yi,$i,Hi,Ji,Ki,tr,er,sr,nr,ir,rr,or,ar,hr,cr,lr,ur,pr,dr,fr,_r,mr,gr,vr,yr,xr,wr,br,Tr,Sr,kr,Ar,Cr,Dr,Or,Mr,Er,Rr,qr,Fr,Ir,Vr,Nr,Pr,jr,Lr,zr,Wr,Br,Ur,Gr,Qr,Zr,Xr,Yr,$r,Hr,Jr,Kr,to,eo,so,no,io,ro,oo,ao,ho,co,lo,uo,po,fo,_o,mo,go,vo,yo,xo,wo,bo,To,So,ko,Ao,Co,Do,Oo,Mo,Eo,Ro,qo,Fo,Io,Vo,No,Po,jo,Lo,zo,Wo,Bo,Uo,Go,Qo,Zo,Xo,Yo,$o,Ho,Jo,Ko,ta,ea,sa,na,ia,ra,oa,aa,ha,ca,la,ua,pa,da,fa,_a,ma,ga,va,ya,xa,wa,ba,Ta,Sa,ka,Aa,Ca,Da,Oa,Ma,Ea,Ra,qa,Fa,Ia,Va,Na,Pa,ja,La,za,Wa,Ba,Ua,Ga,Qa,Za,Xa,Ya,$a,Ha,Ja,Ka,th,eh,sh,nh,ih,rh,oh,ah,hh,ch,lh,uh,ph,dh,fh,_h,mh,gh,vh,yh,xh,wh,bh,Th,Sh,kh,Ah,Ch,Dh,Oh,Mh,Eh,Rh,qh,Fh,Ih,Vh,Nh,Ph,jh,Lh,zh,Wh,Bh,Uh,Gh,Qh,Zh,Xh,Yh,$h,Hh,Jh,Kh,tc,ec,sc,nc,ic,rc,oc,ac,hc,cc,lc,uc,pc,dc,fc,_c,mc,gc,vc,yc,xc,wc,bc,Tc,Sc,kc,Ac,Cc,Dc,Oc,Mc,Ec,Rc,qc,Fc,Ic,Vc,Nc,Pc,jc,Lc,zc,Wc,Bc,Uc,Gc,Qc,Zc,Xc,Yc,$c,Hc,Jc,Kc,tl,el,sl,nl,il,rl,ol=(Jc=Cs,Os=ms,Ms=Mt,Es=ds,Rs=D=gs,qs=R=ys,class extends Jc{constructor(t,e){var s=Rs(t),e={...Ct,...e},e=Es(s,e);super(t,!1,e,qs(s)?Os():null),this._nativeAnalyserNode=e}get fftSize(){return this._nativeAnalyserNode.fftSize}set fftSize(t){this._nativeAnalyserNode.fftSize=t}get frequencyBinCount(){return this._nativeAnalyserNode.frequencyBinCount}get maxDecibels(){return this._nativeAnalyserNode.maxDecibels}set maxDecibels(t){var e=this._nativeAnalyserNode.maxDecibels;if(!((this._nativeAnalyserNode.maxDecibels=t)>this._nativeAnalyserNode.minDecibels))throw this._nativeAnalyserNode.maxDecibels=e,Ms()}get minDecibels(){return this._nativeAnalyserNode.minDecibels}set minDecibels(t){var e=this._nativeAnalyserNode.minDecibels;if(this._nativeAnalyserNode.minDecibels=t,!(this._nativeAnalyserNode.maxDecibels>t))throw this._nativeAnalyserNode.minDecibels=e,Ms()}get smoothingTimeConstant(){return this._nativeAnalyserNode.smoothingTimeConstant}set smoothingTimeConstant(t){this._nativeAnalyserNode.smoothingTimeConstant=t}getByteFrequencyData(t){this._nativeAnalyserNode.getByteFrequencyData(t)}getByteTimeDomainData(t){this._nativeAnalyserNode.getByteTimeDomainData(t)}getFloatFrequencyData(t){this._nativeAnalyserNode.getFloatFrequencyData(t)}getFloatTimeDomainData(t){this._nativeAnalyserNode.getFloatTimeDomainData(t)}}),al=new WeakSet,Jc=null!==(Ds=ps)&&Ds.hasOwnProperty("AudioBuffer")?Ds.AudioBuffer:null,Ds=(Fs=new Uint32Array(1),t=>(Fs[0]=t,Fs[0]));const hl=(wn=Mt,a=>{a.copyFromChannel=(e,t,s=0)=>{var n=xn(s),t=xn(t);if(t>=a.numberOfChannels)throw wn();var i=a.length,r=a.getChannelData(t),o=e.length;for(let t=n<0?-n:0;t+n{var n=xn(s),t=xn(t);if(t>=a.numberOfChannels)throw wn();const i=a.length,r=a.getChannelData(t),o=e.length;for(let t=n<0?-n:0;t+n{var i,r;n.copyFromChannel=(r=n.copyFromChannel,(t,e,s=0)=>{s=yn(s),e=yn(e);if(s{s=yn(s),e=yn(e);if(s{let p=null;return class e{constructor(t){if(null===h)throw new Error("Missing the native OfflineAudioContext constructor.");var{length:e,numberOfChannels:s,sampleRate:t}={...Rt,...t};null===p&&(p=new h(1,1,44100));const n=null!==a&&r(c,c)?new a({length:e,numberOfChannels:s,sampleRate:t}):p.createBuffer(s,e,t);if(0===n.numberOfChannels)throw o();return"function"!=typeof n.copyFromChannel?(l(n),Et(n)):r(Ot,()=>Ot(n))||u(n),i.add(n),n}static[Symbol.hasInstance](t){return null!==t&&"object"==typeof t&&Object.getPrototypeOf(t)===e.prototype||i.has(t)}}})(al,us,We,Jc,vs,(vn=Jc,()=>{if(null===vn)return!1;try{new vn({length:1,sampleRate:44100})}catch{return!1}return!0}),hl,cl),ul=(gn=je,(t,e)=>{const s=gn(t,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});e.connect(s).connect(t.destination);const n=()=>{e.removeEventListener("ended",n),e.disconnect(s),s.disconnect()};e.addEventListener("ended",n)}),pl=(fn=fs,_n=Pt,mn=te,async(t,i,r)=>{t=_n(t);await Promise.all(Array.from(t.activeInputs).map(async([t,e])=>{const s=fn(t),n=await s.render(t,i);mn(t)||n.connect(r,e)}))}),dl=(dn=pl,(t,e,s)=>dn(e,t,s)),fl=(en=ul,sn=us,nn=t=>{const e=t.createBufferSource();e.start();try{e.start()}catch{return!0}return!1},rn=t=>{const e=t.createBufferSource(),s=t.createBuffer(1,1,44100);e.buffer=s;try{e.start(0,1)}catch{return!1}return!0},on=t=>{const e=t.createBufferSource();e.start();try{e.stop()}catch{return!1}return!0},an=Ke,hn=ts,cn=es,pn=He,ln=(s,t)=>{const n=t.createBuffer(1,1,44100);null===s.buffer&&(s.buffer=n),pn(s,"buffer",e=>()=>{var t=e.call(s);return t===n?null:t},e=>t=>e.call(s,null===t?n:t))},un=is,(t,e)=>{var i,r,o,s=t.createBufferSource();return Oe(s,e),Ee(s,e,"playbackRate"),De(s,e,"buffer"),De(s,e,"loop"),De(s,e,"loopEnd"),De(s,e,"loopStart"),sn(nn,()=>nn(t))||((o=s).start=(n=>{let i=!1;return(t=0,e=0,s)=>{if(i)throw be();n.call(o,t,e,s),i=!0}})(o.start)),sn(rn,()=>rn(t))||((i=s).start=(r=i.start,(t=0,e=0,s)=>{var n=i.buffer,e=null===n?e:Math.min(n.duration,e);null!==n&&e>n.duration-.5/i.context.sampleRate?r.call(i,t,0,0):r.call(i,t,e,s)})),sn(on,()=>on(t))||ln(s,t),sn(an,()=>an(t))||Re(s),sn(hn,()=>hn(t))||un(s,t),sn(cn,()=>cn(t))||qe(s),en(t,s),s}),_l=(tn=Pt,Js=t=>{t=tn(t);if(null===t.renderer)throw new Error("Missing the renderer of the given AudioParam in the audio graph.");return t.renderer},Ks=pl,(t,e,s)=>(Js(e).replay(s),Ks(e,t,s))),ml=(Zs=dl,Xs=fl,Ys=Jt,$s=_l,Hs=_s,()=>{const i=new WeakMap;let r=null,o=null;return{set start(t){r=t},set stop(t){o=t},render(t,e){var s=i.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=Ys(t);var n=Dt(s,e);if(!n){const Zs={buffer:s.buffer,channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,loop:s.loop,loopEnd:s.loopEnd,loopStart:s.loopStart,playbackRate:s.playbackRate.value};s=Xs(e,Zs),null!==r&&s.start(...r),null!==o&&s.stop(o)}return i.set(e,s),n?await Zs(e,t.playbackRate,s.playbackRate):await $s(e,t.playbackRate,s.playbackRate),await Hs(t,e,s),s})(t,e)}}}),gl=(bn=at,Is=(t,e)=>{bn.set(t,{activeInputs:new Set,passiveInputs:new WeakMap,renderer:e})},Vs=xs,Ns=ht,Ps=nt.createCancelAndHoldAutomationEvent,js=nt.createCancelScheduledValuesAutomationEvent,Ls=nt.createExponentialRampToValueAutomationEvent,zs=nt.createLinearRampToValueAutomationEvent,Ws=nt.createSetTargetAutomationEvent,Bs=nt.createSetValueAutomationEvent,Us=nt.createSetValueCurveAutomationEvent,Gs=bs,Qs=Je,(p,t,d,e=null,s=null)=>{const f=new nt.AutomationEventList(d.defaultValue),_=t?(c=f,{replay(t){for(const e of c)if("exponentialRampToValue"===e.type){const{endTime:c,value:s}=e;t.exponentialRampToValueAtTime(s,c)}else if("linearRampToValue"===e.type){const{endTime:c,value:n}=e;t.linearRampToValueAtTime(n,c)}else if("setTarget"===e.type){const{startTime:c,target:i,timeConstant:r}=e;t.setTargetAtTime(i,c,r)}else if("setValue"===e.type){const{startTime:c,value:o}=e;t.setValueAtTime(o,c)}else{if("setValueCurve"!==e.type)throw new Error("Can't apply an unknown automation.");{const{duration:c,startTime:a,values:h}=e;t.setValueCurveAtTime(h,a,c)}}}}):null,m={get defaultValue(){return d.defaultValue},get maxValue(){return null===e?d.maxValue:e},get minValue(){return null===s?d.minValue:s},get value(){return d.value},set value(t){d.value=t,m.setValueAtTime(t,p.context.currentTime)},cancelAndHoldAtTime(t){var e,s;return"function"==typeof d.cancelAndHoldAtTime?(null===_&&f.flush(p.context.currentTime),f.add(Ps(t)),d.cancelAndHoldAtTime(t)):(e=Array.from(f).pop(),null===_&&f.flush(p.context.currentTime),f.add(Ps(t)),s=Array.from(f).pop(),d.cancelScheduledValues(t),e!==s&&void 0!==s&&("exponentialRampToValue"===s.type?d.exponentialRampToValueAtTime(s.value,s.endTime):"linearRampToValue"===s.type?d.linearRampToValueAtTime(s.value,s.endTime):"setValue"===s.type?d.setValueAtTime(s.value,s.startTime):"setValueCurve"===s.type&&d.setValueCurveAtTime(s.values,s.startTime,s.duration))),m},cancelScheduledValues:t=>(null===_&&f.flush(p.context.currentTime),f.add(js(t)),d.cancelScheduledValues(t),m),exponentialRampToValueAtTime(t,e){if(0===t)throw new RangeError;if(!Number.isFinite(e)||e<0)throw new RangeError;return null===_&&f.flush(p.context.currentTime),f.add(Ls(t,e)),d.exponentialRampToValueAtTime(t,e),m},linearRampToValueAtTime:(t,e)=>(null===_&&f.flush(p.context.currentTime),f.add(zs(t,e)),d.linearRampToValueAtTime(t,e),m),setTargetAtTime:(t,e,s)=>(null===_&&f.flush(p.context.currentTime),f.add(Ws(t,e,s)),d.setTargetAtTime(t,e,s),m),setValueAtTime:(t,e)=>(null===_&&f.flush(p.context.currentTime),f.add(Bs(t,e)),d.setValueAtTime(t,e),m),setValueCurveAtTime(t,e,s){var n=t instanceof Float32Array?t:new Float32Array(t);if(null!==Gs&&"webkitAudioContext"===Gs.name){const i=e+s,r=p.context.sampleRate,o=Math.ceil(e*r),a=Math.floor(i*r),h=a-o,c=new Float32Array(h);for(let t=0;t{this._nativeAudioBufferSourceNode.removeEventListener("ended",t),It(this)&&kt(this)};this._nativeAudioBufferSourceNode.addEventListener("ended",t)}}stop(t=0){this._nativeAudioBufferSourceNode.stop(t),null!==this._audioBufferSourceNodeRenderer&&(this._audioBufferSourceNodeRenderer.stop=t)}}),yl=(Jc=Cs,Uc=Mt,Gc=be,$c=je,Hc=He,Qc=(t,e,s)=>{const n=t.destination;if(n.channelCount!==e)try{n.channelCount=e}catch{}s&&"explicit"!==n.channelCountMode&&(n.channelCountMode="explicit"),0===n.maxChannelCount&&Object.defineProperty(n,"maxChannelCount",{value:e});const i=$c(t,{channelCount:e,channelCountMode:n.channelCountMode,channelInterpretation:n.channelInterpretation,gain:1});return Hc(i,"channelCount",t=>()=>t.call(i),t=>e=>{t.call(i,e);try{n.channelCount=e}catch(t){if(e>n.maxChannelCount)throw t}}),Hc(i,"channelCountMode",t=>()=>t.call(i),e=>t=>{e.call(i,t),n.channelCountMode=t}),Hc(i,"channelInterpretation",t=>()=>t.call(i),e=>t=>{e.call(i,t),n.channelInterpretation=t}),Object.defineProperty(i,"maxChannelCount",{get:()=>n.maxChannelCount}),i.connect(n),i},class extends Jc{constructor(t,e){var s=Zc(t),n=Xc(s),e=Qc(s,e,n);super(t,!1,e,n?(n=>{const i=new WeakMap;return{render(t,e){var s=i.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{var s=e.destination;return i.set(e,s),await n(t,e,s),s})(t,e)}}})(Yc):null),this._isNodeOfNativeOfflineAudioContext=n,this._nativeAudioDestinationNode=e}get channelCount(){return this._nativeAudioDestinationNode.channelCount}set channelCount(t){if(this._isNodeOfNativeOfflineAudioContext)throw Gc();if(t>this._nativeAudioDestinationNode.maxChannelCount)throw Uc();this._nativeAudioDestinationNode.channelCount=t}get channelCountMode(){return this._nativeAudioDestinationNode.channelCountMode}set channelCountMode(t){if(this._isNodeOfNativeOfflineAudioContext)throw Gc();this._nativeAudioDestinationNode.channelCountMode=t}get maxChannelCount(){return this._nativeAudioDestinationNode.maxChannelCount}}),xl=(jc=dl,zc=Jt,Wc=_l,Bc=Yc=_s,()=>{const i=new WeakMap;return{render(t,e){var s=i.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=zc(t);var n=Dt(s,e);if(!n){const jc={Q:s.Q.value,channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,detune:s.detune.value,frequency:s.frequency.value,gain:s.gain.value,type:s.type};s=Lc(e,jc)}return i.set(e,s),n?(await jc(e,t.Q,s.Q),await jc(e,t.detune,s.detune),await jc(e,t.frequency,s.frequency),await jc(e,t.gain,s.gain)):(await Wc(e,t.Q,s.Q),await Wc(e,t.detune,s.detune),await Wc(e,t.frequency,s.frequency),await Wc(e,t.gain,s.gain)),await Bc(t,e,s),s})(t,e)}}}),wl=(Pc=cs,(t,e)=>Pc.set(t,e)),bl=(Jc=Cs,Ec=tl=gl,Rc=xl,qc=Te,Fc=Lc=Ie,Ic=Zc=nl=gs,Vc=Xc=il=ys,Nc=wl,class extends Jc{constructor(t,e){var s=Ic(t),e={...pe,...e},e=Fc(s,e),s=Vc(s);super(t,!1,e,s?Rc():null),this._Q=Ec(this,s,e.Q,Ft,qt),this._detune=Ec(this,s,e.detune,1200*Math.log2(Ft),-1200*Math.log2(Ft)),this._frequency=Ec(this,s,e.frequency,t.sampleRate/2,0),this._gain=Ec(this,s,e.gain,40*Math.log10(Ft),qt),this._nativeBiquadFilterNode=e,Nc(this,1)}get detune(){return this._detune}get frequency(){return this._frequency}get gain(){return this._gain}get Q(){return this._Q}get type(){return this._nativeBiquadFilterNode.type}set type(t){this._nativeBiquadFilterNode.type=t}getFrequencyResponse(t,e,s){try{this._nativeBiquadFilterNode.getFrequencyResponse(t,e,s)}catch(t){if(11===t.code)throw qc();throw t}if(t.length!==e.length||e.length!==s.length)throw qc()}}),Tl=(Oc=Bt,Mc=Ss,(r,i,o)=>{const a=new Set;return r.connect=(c=r.connect,(e,s=0,n=0)=>{var t=0===a.size;if(Mc(e))return c.call(r,e,s,n),Oc(a,[e,s,n],t=>t[0]===e&&t[1]===s&&t[2]===n,!0),t&&i(),e;c.call(r,e,s),Oc(a,[e,s],t=>t[0]===e&&t[1]===s,!0),t&&i()}),r.disconnect=(h=r.disconnect,(t,e,s)=>{var n=0{s.channelCount=1,s.channelCountMode="explicit",Object.defineProperty(s,"channelCount",{get:()=>1,set:()=>{throw Cc()}}),Object.defineProperty(s,"channelCountMode",{get:()=>"explicit",set:()=>{throw Cc()}});const n=t.createBufferSource();Dc(s,()=>{var e=s.numberOfInputs;for(let t=0;tn.disconnect(s))}),kl=(kc=bs,Ac=Sl,(t,e)=>{var s=t.createChannelMerger(e.numberOfInputs);return null!==kc&&"webkitAudioContext"===kc.name&&Ac(t,s),Oe(s,e),s}),Al=(Tc=Jt,()=>{const n=new WeakMap;return{render(t,e){var s=n.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=Tc(t);if(!Dt(s,e)){const Tc={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,numberOfInputs:s.numberOfInputs};s=bc(e,Tc)}return n.set(e,s),await Sc(t,e,s),s})(t,e)}}}),Cl=(Jc=Cs,vc=Al,class extends Jc{constructor(t,e){var s=xc(t),e={...de,...e};super(t,!1,yc(s,e),wc(s)?vc():null)}}),Dl=(mc=Jt,()=>{const n=new WeakMap;return{render(t,e){var s=n.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=mc(t);if(!Dt(s,e)){const mc={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,numberOfOutputs:s.numberOfOutputs};s=_c(e,mc)}return n.set(e,s),await gc(t,e,s),s})(t,e)}}}),Ol=(Jc=Cs,uc=Dl,pc=_c=Ve,class extends Jc{constructor(t,e){var s=dc(t),e={...e={...fe,...e},channelCount:e.numberOfOutputs};super(t,!1,pc(s,e),fc(s)?uc():null)}}),Ml=(lc=Dc=Tl,(t,{offset:e,...s})=>{const n=t.createBuffer(1,2,44100),i=hc(t,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),r=cc(t,{...s,gain:e}),o=n.getChannelData(0);o[0]=1,o[1]=1,i.buffer=n,i.loop=!0;e={get bufferSize(){},get channelCount(){return r.channelCount},set channelCount(t){r.channelCount=t},get channelCountMode(){return r.channelCountMode},set channelCountMode(t){r.channelCountMode=t},get channelInterpretation(){return r.channelInterpretation},set channelInterpretation(t){r.channelInterpretation=t},get context(){return r.context},get inputs(){return[]},get numberOfInputs(){return i.numberOfInputs},get numberOfOutputs(){return r.numberOfOutputs},get offset(){return r.gain},get onended(){return i.onended},set onended(t){i.onended=t},addEventListener:(...t)=>i.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>i.dispatchEvent(t[0]),removeEventListener:(...t)=>i.removeEventListener(t[0],t[1],t[2]),start(t=0){i.start.call(i,t)},stop(t=0){i.stop.call(i,t)}};return ac(t,i),lc(Ne(e,r),()=>i.connect(r),()=>i.disconnect(r))}),El=(sc=ac=ul,nc=us,ic=Ml,rc=Ke,oc=es,(t,e)=>{if(void 0===t.createConstantSource)return ic(t,e);var s=t.createConstantSource();return Oe(s,e),Ee(s,e,"offset"),nc(rc,()=>rc(t))||Re(s),nc(oc,()=>oc(t))||qe(s),sc(t,s),s}),Rl=(Kh=Jt,()=>{const i=new WeakMap;let r=null,o=null;return{set start(t){r=t},set stop(t){o=t},render(t,e){var s=i.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=Kh(t);var n=Dt(s,e);if(!n){const Hh={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,offset:s.offset.value};s=Jh(e,Hh),null!==r&&s.start(r),null!==o&&s.stop(o)}return i.set(e,s),n?await Hh(e,t.offset,s.offset):await tc(e,t.offset,s.offset),await ec(t,e,s),s})(t,e)}}}),ql=(Jc=Cs,Qh=Rl,$h=rs,class extends Jc{constructor(t,e){var s=Xh(t),n={..._e,...e},e=Zh(s,n),n=Yh(s),s=n?Qh():null;super(t,!1,e,s),this._constantSourceNodeRenderer=s,this._nativeConstantSourceNode=e,this._offset=Gh(this,n,e.offset,Ft,qt),this._onended=null}get offset(){return this._offset}get onended(){return this._onended}set onended(t){var e="function"==typeof t?$h(this,t):null;this._nativeConstantSourceNode.onended=e;var s=this._nativeConstantSourceNode.onended;this._onended=null!==s&&s===e?t:s}start(t=0){if(this._nativeConstantSourceNode.start(t),null!==this._constantSourceNodeRenderer&&(this._constantSourceNodeRenderer.start=t),"closed"!==this.context.state){Tt(this);const t=()=>{this._nativeConstantSourceNode.removeEventListener("ended",t),It(this)&&kt(this)};this._nativeConstantSourceNode.addEventListener("ended",t)}}stop(t=0){this._nativeConstantSourceNode.stop(t),null!==this._constantSourceNodeRenderer&&(this._constantSourceNodeRenderer.stop=t)}}),Fl=(t,e)=>{const s=t.createConvolver();if(Oe(s,e),e.disableNormalization===s.normalize&&(s.normalize=!e.disableNormalization),De(s,e,"buffer"),2()=>t.call(s),e=>t=>{if(2()=>t.call(s),e=>t=>{if("max"===t)throw Bh();return e.call(s,t)}),s},Il=(zh=Jt,()=>{const n=new WeakMap;return{render(t,e){var s=n.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=zh(t);if(!Dt(s,e)){const zh={buffer:s.buffer,channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,disableNormalization:!s.normalize};s=Lh(e,zh)}return n.set(e,s),Qt(s)?await Wh(t,e,s.inputs[0]):await Wh(t,e,s),s})(t,e)}}}),Vl=(Jc=Cs,Ih=Il,Vh=Lh=Fl,class extends Jc{constructor(t,e){var s=Nh(t),n={...me,...e},e=Vh(s,n);super(t,!1,e,Ph(s)?Ih():null),this._isBufferNullified=!1,this._nativeConvolverNode=e,null!==n.buffer&&jh(this,n.buffer.duration)}get buffer(){return this._isBufferNullified?null:this._nativeConvolverNode.buffer}set buffer(t){if(null===(this._nativeConvolverNode.buffer=t)&&null!==this._nativeConvolverNode.buffer){const t=this._nativeConvolverNode.context;this._nativeConvolverNode.buffer=t.createBuffer(1,1,44100),this._isBufferNullified=!0,jh(this,0)}else this._isBufferNullified=!1,jh(this,null===this._nativeConvolverNode.buffer?0:this._nativeConvolverNode.buffer.duration)}get normalize(){return this._nativeConvolverNode.normalize}set normalize(t){this._nativeConvolverNode.normalize=t}}),Nl=(Rh=Jt,i=>{const r=new WeakMap;return{render(t,e){var s=r.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=Rh(t);var n=Dt(s,e);if(!n){const Mh={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,delayTime:s.delayTime.value,maxDelayTime:i};s=Eh(e,Mh)}return r.set(e,s),n?await Mh(e,t.delayTime,s.delayTime):await qh(e,t.delayTime,s.delayTime),await Fh(t,e,s),s})(t,e)}}}),Pl=(Jc=Cs,kh=Nl,Ah=Eh=Pe,class extends Jc{constructor(t,e){var s=Ch(t),n={...ve,...e},e=Ah(s,n),s=Dh(s);super(t,!1,e,s?kh(n.maxDelayTime):null),this._delayTime=Sh(this,s,e.delayTime),Oh(this,n.maxDelayTime)}get delayTime(){return this._delayTime}}),jl=(t,e)=>{t=t.createDynamicsCompressor();if(Oe(t,e),2{const i=new WeakMap;return{render(t,e){var s=i.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=xh(t);var n=Dt(s,e);if(!n){const vh={attack:s.attack.value,channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,knee:s.knee.value,ratio:s.ratio.value,release:s.release.value,threshold:s.threshold.value};s=yh(e,vh)}return i.set(e,s),n?(await vh(e,t.attack,s.attack),await vh(e,t.knee,s.knee),await vh(e,t.ratio,s.ratio),await vh(e,t.release,s.release),await vh(e,t.threshold,s.threshold)):(await wh(e,t.attack,s.attack),await wh(e,t.knee,s.knee),await wh(e,t.ratio,s.ratio),await wh(e,t.release,s.release),await wh(e,t.threshold,s.threshold)),await bh(t,e,s),s})(t,e)}}}),zl=(Jc=Cs,ph=Ll,dh=yh=jl,class extends Jc{constructor(t,e){var s=_h(t),e={...xe,...e},e=dh(s,e),s=mh(s);super(t,!1,e,s?ph():null),this._attack=uh(this,s,e.attack),this._knee=uh(this,s,e.knee),this._nativeDynamicsCompressorNode=e,this._ratio=uh(this,s,e.ratio),this._release=uh(this,s,e.release),this._threshold=uh(this,s,e.threshold),gh(this,.006)}get attack(){return this._attack}get channelCount(){return this._nativeDynamicsCompressorNode.channelCount}set channelCount(t){var e=this._nativeDynamicsCompressorNode.channelCount;if(2<(this._nativeDynamicsCompressorNode.channelCount=t))throw this._nativeDynamicsCompressorNode.channelCount=e,fh()}get channelCountMode(){return this._nativeDynamicsCompressorNode.channelCountMode}set channelCountMode(t){var e=this._nativeDynamicsCompressorNode.channelCountMode;if("max"===(this._nativeDynamicsCompressorNode.channelCountMode=t))throw this._nativeDynamicsCompressorNode.channelCountMode=e,fh()}get knee(){return this._knee}get ratio(){return this._ratio}get reduction(){return"number"==typeof this._nativeDynamicsCompressorNode.reduction.value?this._nativeDynamicsCompressorNode.reduction.value:this._nativeDynamicsCompressorNode.reduction}get release(){return this._release}get threshold(){return this._threshold}}),Wl=(oh=vh=Mh=Hh=dl,hh=Jt,ch=wh=qh=tc=_l,()=>{const i=new WeakMap;return{render(t,e){var s=i.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=hh(t);var n=Dt(s,e);if(!n){const oh={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,gain:s.gain.value};s=ah(e,oh)}return i.set(e,s),n?await oh(e,t.gain,s.gain):await ch(e,t.gain,s.gain),await lh(t,e,s),s})(t,e)}}}),Bl=(Jc=Cs,sh=Wl,class extends Jc{constructor(t,e){var s=ih(t),e={...we,...e},e=nh(s,e),s=rh(s);super(t,!1,e,s?sh():null),this._gain=eh(this,s,e.gain,Ft,qt)}get gain(){return this._gain}}),Ul=(Ha=Te,Ja=be,(t,e,{channelCount:s,channelCountMode:n,channelInterpretation:i,feedback:r,feedforward:o})=>{const a=Fe(e,t.sampleRate),l=r instanceof Float64Array?r:new Float64Array(r),u=o instanceof Float64Array?o:new Float64Array(o),h=l.length,c=u.length,p=Math.min(h,c);if(0===h||20{const e=t.inputBuffer,s=t.outputBuffer,n=e.numberOfChannels;for(let t=0;td.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>d.dispatchEvent(t[0]),getFrequencyResponse(e,s,n){if(e.length!==s.length||s.length!==n.length)throw Ha();const i=e.length;for(let t=0;td.removeEventListener(t[0],t[1],t[2])},d)}),Gl=(Ga=us,Ya=Qa=nh=ah=cc=je,$a=vs,Xa=()=>{if(null===$a)return Promise.resolve(!1);const e=new $a(1,1,44100),s=Ya(e,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return new Promise(t=>{e.oncomplete=()=>{s.disconnect(),t(0!==e.currentTime)},e.startRendering()})},n=>Ga(Ce,()=>Ce(n))?Promise.resolve(Ga(Xa,Xa)).then(t=>{if(!t){const t=Za(n,512,0,1);n.oncomplete=()=>{t.onaudioprocess=null,t.disconnect()},t.onaudioprocess=()=>n.currentTime,t.connect(n.destination)}return n.startRendering()}):new Promise(e=>{const s=Qa(n,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});n.oncomplete=t=>{s.disconnect(),e(t.renderedBuffer)},s.connect(n.destination),n.startRendering()})),Ql=(La=hc=fl,za=Jt,Wa=vs,Ba=lh=bh=Fh=Wh=ec=gc=Sc=_s,Ua=Gl,(r,o)=>{const a=new WeakMap;let h=null;return{render(t,e){var s=a.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=null,n=za(t);var i=Dt(n,e);if(void 0===e.createIIRFilter?s=La(e,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}):i||(n=e.createIIRFilter(o,r)),a.set(e,null===s?n:s),null===s)return await Ba(t,e,n),n;{if(null===h){if(null===Wa)throw new Error("Missing the native OfflineAudioContext constructor.");const La=new Wa(t.context.destination.channelCount,t.context.length,e.sampleRate);h=(async()=>(await Ba(t,La,La.destination),((e,t,s,n)=>{const i=s instanceof Float64Array?s:new Float64Array(s),r=n instanceof Float64Array?n:new Float64Array(n),o=i.length,a=r.length,h=Math.min(o,a);if(1!==i[0]){for(let t=0;t{if(void 0===t.createIIRFilter)return ja(t,e,s);t=t.createIIRFilter(s.feedforward,s.feedback);return Oe(t,s),t}),Xl=(Jc=Cs,Fa=Zl,Ia=Ql,Va=ih=_h=Ch=Nh=Xh=dc=xc=gs,Pa=gh=Oh=jh=wl,class extends Jc{constructor(t,e){var n,i,s=Va(t),r=Na(s),e={...Se,...e},s=Fa(s,r?null:t.baseLatency,e);super(t,!1,s,r?Ia(e.feedback,e.feedforward):null),(n=s).getFrequencyResponse=(i=n.getFrequencyResponse,(t,e,s)=>{if(t.length!==e.length||e.length!==s.length)throw Te();return i.call(n,t,e,s)}),this._nativeIIRFilterNode=s,Pa(this,1)}getFrequencyResponse(t,e,s){return this._nativeIIRFilterNode.getFrequencyResponse(t,e,s)}}),Yl=(Aa=eh=uh=Sh=Gh=gl,Ca=yc=bc=kl,Da=Zh=Jh=El,Oa=Za=Ka=ze,Ma=th=fh=Th=Bh=We,Ea=Ye,Ra=Na=rh=mh=Dh=Ph=Yh=fc=wc=ys,qa=Uh=He,(_,m)=>{const a=m.listener,{forwardX:t,forwardY:e,forwardZ:s,positionX:n,positionY:i,positionZ:r,upX:o,upY:h,upZ:c}=void 0===a.forwardX?(()=>{const n=new Float32Array(1),p=Ca(m,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:9}),d=Ra(m);let e=!1,i=[0,0,-1,0,1,0],r=[0,0,0];const f=()=>{if(!e){e=!0;const t=Oa(m,256,9,0);t.onaudioprocess=({inputBuffer:t})=>{const e=[Ea(t,n,0),Ea(t,n,1),Ea(t,n,2),Ea(t,n,3),Ea(t,n,4),Ea(t,n,5)];e.some((t,e)=>t!==i[e])&&(a.setOrientation(...e),i=e);const s=[Ea(t,n,6),Ea(t,n,7),Ea(t,n,8)];s.some((t,e)=>t!==r[e])&&(a.setPosition(...s),r=s)},p.connect(t)}},t=e=>t=>{t!==i[e]&&(i[e]=t,a.setOrientation(...i))},s=e=>t=>{t!==r[e]&&(r[e]=t,a.setPosition(...r))},o=(t,e,s)=>{const n=Da(m,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:e});n.connect(p,0,t),n.start(),Object.defineProperty(n.offset,"defaultValue",{get:()=>e});const i=Aa({context:_},d,n.offset,Ft,qt);var r,o,a,h,c,l,u;return qa(i,"value",t=>()=>t.call(i),e=>t=>{try{e.call(i,t)}catch(t){if(9!==t.code)throw t}f(),d&&s(t)}),i.cancelAndHoldAtTime=(r=i.cancelAndHoldAtTime,d?()=>{throw Ma()}:(...t)=>{t=r.apply(i,t);return f(),t}),i.cancelScheduledValues=(o=i.cancelScheduledValues,d?()=>{throw Ma()}:(...t)=>{t=o.apply(i,t);return f(),t}),i.exponentialRampToValueAtTime=(a=i.exponentialRampToValueAtTime,d?()=>{throw Ma()}:(...t)=>{t=a.apply(i,t);return f(),t}),i.linearRampToValueAtTime=(h=i.linearRampToValueAtTime,d?()=>{throw Ma()}:(...t)=>{t=h.apply(i,t);return f(),t}),i.setTargetAtTime=(c=i.setTargetAtTime,d?()=>{throw Ma()}:(...t)=>{t=c.apply(i,t);return f(),t}),i.setValueAtTime=(l=i.setValueAtTime,d?()=>{throw Ma()}:(...t)=>{t=l.apply(i,t);return f(),t}),i.setValueCurveAtTime=(u=i.setValueCurveAtTime,d?()=>{throw Ma()}:(...t)=>{t=u.apply(i,t);return f(),t}),i};return{forwardX:o(0,0,t(0)),forwardY:o(1,0,t(1)),forwardZ:o(2,-1,t(2)),positionX:o(6,0,s(0)),positionY:o(7,0,s(1)),positionZ:o(8,0,s(2)),upX:o(3,0,t(3)),upY:o(4,1,t(4)),upZ:o(5,0,t(5))}})():a;return{get forwardX(){return t},get forwardY(){return e},get forwardZ(){return s},get positionX(){return n},get positionY(){return i},get positionZ(){return r},get upX(){return o},get upY(){return h},get upZ(){return c}}}),$l=new WeakMap,Hl=(wa=yl,ba=Yl,Sa=$l,class extends ws{constructor(t,e){super(t),this._nativeContext=t,ct.set(this,t),Ta(t)&&Sa.set(t,new Set),this._destination=new wa(this,e),this._listener=ba(this,t),this._onstatechange=null}get currentTime(){return this._nativeContext.currentTime}get destination(){return this._destination}get listener(){return this._listener}get onstatechange(){return this._onstatechange}set onstatechange(t){var e="function"==typeof t?ka(this,t):null;this._nativeContext.onstatechange=e;var s=this._nativeContext.onstatechange;this._onstatechange=null!==s&&s===e?t:s}get sampleRate(){return this._nativeContext.sampleRate}get state(){return this._nativeContext.state}}),Jl=(_a=ul,ma=us,ga=Ke,va=ts,ya=es,xa=is,(t,e)=>{const s=t.createOscillator();return Oe(s,e),Ee(s,e,"detune"),Ee(s,e,"frequency"),void 0!==e.periodicWave?s.setPeriodicWave(e.periodicWave):De(s,e,"type"),ma(ga,()=>ga(t))||Re(s),ma(va,()=>va(t))||xa(s,t),ma(ya,()=>ya(t))||qe(s),_a(t,s),s}),Kl=(pa=Jt,()=>{const i=new WeakMap;let r=null,o=null,a=null;return{set periodicWave(t){r=t},set start(t){o=t},set stop(t){a=t},render(t,e){var s=i.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=pa(t);var n=Dt(s,e);if(!n){const la={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,detune:s.detune.value,frequency:s.frequency.value,periodicWave:null===r?void 0:r,type:s.type};s=ua(e,la),null!==o&&s.start(o),null!==a&&s.stop(a)}return i.set(e,s),n?(await la(e,t.detune,s.detune),await la(e,t.frequency,s.frequency)):(await da(e,t.detune,s.detune),await da(e,t.frequency,s.frequency)),await fa(t,e,s),s})(t,e)}}}),tu=(Jc=Cs,ra=ua=Jl,oa=Kl,ca=ka=rs,class extends Jc{constructor(t,e){var s=aa(t),n={...Ue,...e},i=ra(s,n),r=ha(s),e=r?oa():null,s=t.sampleRate/2;super(t,!1,i,e),this._detune=ia(this,r,i.detune,153600,-153600),this._frequency=ia(this,r,i.frequency,s,-s),this._nativeOscillatorNode=i,this._onended=null,this._oscillatorNodeRenderer=e,null!==this._oscillatorNodeRenderer&&void 0!==n.periodicWave&&(this._oscillatorNodeRenderer.periodicWave=n.periodicWave)}get detune(){return this._detune}get frequency(){return this._frequency}get onended(){return this._onended}set onended(t){var e="function"==typeof t?ca(this,t):null;this._nativeOscillatorNode.onended=e;var s=this._nativeOscillatorNode.onended;this._onended=null!==s&&s===e?t:s}get type(){return this._nativeOscillatorNode.type}set type(t){this._nativeOscillatorNode.type=t,null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.periodicWave=null)}setPeriodicWave(t){this._nativeOscillatorNode.setPeriodicWave(t),null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.periodicWave=t)}start(t=0){if(this._nativeOscillatorNode.start(t),null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.start=t),"closed"!==this.context.state){Tt(this);const t=()=>{this._nativeOscillatorNode.removeEventListener("ended",t),It(this)&&kt(this)};this._nativeOscillatorNode.addEventListener("ended",t)}}stop(t=0){this._nativeOscillatorNode.stop(t),null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.stop=t)}}),eu=(na=fl,(t,e)=>{const s=na(t,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),n=t.createBuffer(1,2,44100);return s.buffer=n,s.loop=!0,s.connect(e),s.start(),()=>{s.stop(),s.disconnect(e)}}),su=(Ko=be,(r,{curve:t,oversample:e,...s})=>{const o=r.createWaveShaper(),a=r.createWaveShaper();Oe(o,s),Oe(a,s);const h=ta(r,{...s,gain:1}),n=ta(r,{...s,gain:-1}),i=ta(r,{...s,gain:1}),c=ta(r,{...s,gain:-1});let l=null,u=!1,p=null;const d={get bufferSize(){},get channelCount(){return o.channelCount},set channelCount(t){h.channelCount=t,n.channelCount=t,o.channelCount=t,i.channelCount=t,a.channelCount=t,c.channelCount=t},get channelCountMode(){return o.channelCountMode},set channelCountMode(t){h.channelCountMode=t,n.channelCountMode=t,o.channelCountMode=t,i.channelCountMode=t,a.channelCountMode=t,c.channelCountMode=t},get channelInterpretation(){return o.channelInterpretation},set channelInterpretation(t){h.channelInterpretation=t,n.channelInterpretation=t,o.channelInterpretation=t,i.channelInterpretation=t,a.channelInterpretation=t,c.channelInterpretation=t},get context(){return o.context},get curve(){return p},set curve(e){if(null!==e&&e.length<2)throw Ko();if(null===e)o.curve=e,a.curve=e;else{const Jo=e.length,Ko=new Float32Array(Jo+2-Jo%2),ea=new Float32Array(Jo+2-Jo%2);Ko[0]=e[0],ea[0]=-e[Jo-1];const s=Math.ceil((Jo+1)/2),r=(Jo+1)/2-1;for(let t=1;th.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>h.dispatchEvent(t[0]),removeEventListener:(...t)=>h.removeEventListener(t[0],t[1],t[2])};return null!==t&&(d.curve=t instanceof Float32Array?t:new Float32Array(t)),e!==d.oversample&&(d.oversample=e),sa(Ne(d,i),()=>{h.connect(o).connect(i),h.connect(n).connect(a).connect(c).connect(i),u=!0,ea(p)&&(l=Jo(r,h))},()=>{h.disconnect(o),o.disconnect(i),h.disconnect(n),n.disconnect(a),a.disconnect(c),c.disconnect(i),u=!1,null!==l&&(l(),l=null)})}),nu=(Go=Jo=eu,Qo=be,Zo=su,Xo=ea=$e,$o=bs,Ho=He,(s,t)=>{const n=s.createWaveShaper();if(null!==$o&&"webkitAudioContext"===$o.name&&void 0===s.createGain().gain.automationRate)return Zo(s,t);Oe(n,t);var e=null===t.curve||t.curve instanceof Float32Array?t.curve:new Float32Array(t.curve);if(null!==e&&e.length<2)throw Qo();De(n,{curve:e},"curve"),De(n,t,"oversample");let i=null,r=!1;return Ho(n,"curve",t=>()=>t.call(n),e=>t=>(e.call(n,t),r&&(Xo(t)&&null===i?i=Go(s,n):Xo(t)||null===i||(i(),i=null)),t)),Yo(n,()=>{r=!0,Xo(n.curve)&&(i=Go(s,n))},()=>{r=!1,null!==i&&(i(),i=null)})}),iu=(Io=Zt,Vo=be,jo=ze,Lo=nu,zo=We,Wo=Ht,Bo=Ye,Uo=Yo=sa=Tl,(t,{coneInnerAngle:e,coneOuterAngle:s,coneOuterGain:n,distanceModel:i,maxDistance:r,orientationX:o,orientationY:a,orientationZ:h,panningModel:c,positionX:l,positionY:u,positionZ:p,refDistance:d,rolloffFactor:f,..._})=>{const m=t.createPanner();if(2<_.channelCount)throw zo();if("max"===_.channelCountMode)throw zo();Oe(m,_);const g={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},v=No(t,{...g,channelInterpretation:"speakers",numberOfInputs:6}),y=Po(t,{..._,gain:1}),x=Po(t,{...g,gain:1}),w=Po(t,{...g,gain:0}),b=Po(t,{...g,gain:0}),T=Po(t,{...g,gain:0}),S=Po(t,{...g,gain:0}),k=Po(t,{...g,gain:0}),A=jo(t,256,6,1),C=Lo(t,{...g,curve:new Float32Array([1,1]),oversample:"none"});let D=[o,a,h],O=[l,u,p];const M=new Float32Array(1);A.onaudioprocess=({inputBuffer:t})=>{const e=[Bo(t,M,0),Bo(t,M,1),Bo(t,M,2)];e.some((t,e)=>t!==D[e])&&(m.setOrientation(...e),D=e);const s=[Bo(t,M,3),Bo(t,M,4),Bo(t,M,5)];s.some((t,e)=>t!==O[e])&&(m.setPosition(...s),O=s)},Object.defineProperty(w.gain,"defaultValue",{get:()=>0}),Object.defineProperty(b.gain,"defaultValue",{get:()=>0}),Object.defineProperty(T.gain,"defaultValue",{get:()=>0}),Object.defineProperty(S.gain,"defaultValue",{get:()=>0}),Object.defineProperty(k.gain,"defaultValue",{get:()=>0});const E={get bufferSize(){},get channelCount(){return m.channelCount},set channelCount(t){if(2y.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>y.dispatchEvent(t[0]),removeEventListener:(...t)=>y.removeEventListener(t[0],t[1],t[2])};return e!==E.coneInnerAngle&&(E.coneInnerAngle=e),s!==E.coneOuterAngle&&(E.coneOuterAngle=s),n!==E.coneOuterGain&&(E.coneOuterGain=n),i!==E.distanceModel&&(E.distanceModel=i),r!==E.maxDistance&&(E.maxDistance=r),o!==E.orientationX.value&&(E.orientationX.value=o),a!==E.orientationY.value&&(E.orientationY.value=a),h!==E.orientationZ.value&&(E.orientationZ.value=h),c!==E.panningModel&&(E.panningModel=c),l!==E.positionX.value&&(E.positionX.value=l),u!==E.positionY.value&&(E.positionY.value=u),p!==E.positionZ.value&&(E.positionZ.value=p),d!==E.refDistance&&(E.refDistance=d),f!==E.rolloffFactor&&(E.rolloffFactor=f),1===D[0]&&0===D[1]&&0===D[2]||m.setOrientation(...D),0===O[0]&&0===O[1]&&0===O[2]||m.setPosition(...O),Uo(Ne(E,m),()=>{y.connect(m),Io(y,C,0,0),C.connect(x).connect(v,0,0),C.connect(w).connect(v,0,1),C.connect(b).connect(v,0,2),C.connect(T).connect(v,0,3),C.connect(S).connect(v,0,4),C.connect(k).connect(v,0,5),v.connect(A).connect(t.destination)},()=>{y.disconnect(m),Wo(y,C,0,0),C.disconnect(x),x.disconnect(v),C.disconnect(w),w.disconnect(v),C.disconnect(b),b.disconnect(v),C.disconnect(T),T.disconnect(v),C.disconnect(S),S.disconnect(v),C.disconnect(k),k.disconnect(v),v.disconnect(A),A.disconnect(t.destination)})}),ru=(Fo=iu,(t,e)=>{var s=t.createPanner();return void 0===s.orientationX?Fo(t,e):(Oe(s,e),Ee(s,e,"orientationX"),Ee(s,e,"orientationY"),Ee(s,e,"orientationZ"),Ee(s,e,"positionX"),Ee(s,e,"positionY"),Ee(s,e,"positionZ"),De(s,e,"coneInnerAngle"),De(s,e,"coneOuterAngle"),De(s,e,"coneOuterGain"),De(s,e,"distanceModel"),De(s,e,"maxDistance"),De(s,e,"panningModel"),De(s,e,"refDistance"),De(s,e,"rolloffFactor"),s)}),ou=(So=la=dl,ko=No=kl,Ao=El,Co=Po=ta=je,Oo=Jt,Mo=vs,Eo=da=_l,Ro=fa=_s,qo=Gl,()=>{const c=new WeakMap;let l=null;return{render(t,e){var s=c.get(e);return void 0!==s?Promise.resolve(s):(async(t,r)=>{let o=null,e=Oo(t);var a={channelCount:e.channelCount,channelCountMode:e.channelCountMode,channelInterpretation:e.channelInterpretation},h={...a,coneInnerAngle:e.coneInnerAngle,coneOuterAngle:e.coneOuterAngle,coneOuterGain:e.coneOuterGain,distanceModel:e.distanceModel,maxDistance:e.maxDistance,panningModel:e.panningModel,refDistance:e.refDistance,rolloffFactor:e.rolloffFactor},s=Dt(e,r);if("bufferSize"in e)o=Co(r,{...a,gain:1});else if(!s){const So={...h,orientationX:e.orientationX.value,orientationY:e.orientationY.value,orientationZ:e.orientationZ.value,positionX:e.positionX.value,positionY:e.positionY.value,positionZ:e.positionZ.value};e=Do(r,So)}if(c.set(r,null===o?e:o),null===o)return s?(await So(r,t.orientationX,e.orientationX),await So(r,t.orientationY,e.orientationY),await So(r,t.orientationZ,e.orientationZ),await So(r,t.positionX,e.positionX),await So(r,t.positionY,e.positionY),await So(r,t.positionZ,e.positionZ)):(await Eo(r,t.orientationX,e.orientationX),await Eo(r,t.orientationY,e.orientationY),await Eo(r,t.orientationZ,e.orientationZ),await Eo(r,t.positionX,e.positionX),await Eo(r,t.positionY,e.positionY),await Eo(r,t.positionZ,e.positionZ)),Qt(e)?await Ro(t,r,e.inputs[0]):await Ro(t,r,e),e;{if(null===l){if(null===Mo)throw new Error("Missing the native OfflineAudioContext constructor.");const So=new Mo(6,t.context.length,r.sampleRate),Co=ko(So,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6});Co.connect(So.destination),l=(async()=>{const e=await Promise.all([t.orientationX,t.orientationY,t.orientationZ,t.positionX,t.positionY,t.positionZ].map(async(t,e)=>{e=Ao(So,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:0===e?1:0});return await Eo(So,t,e.offset),e}));for(let t=0;t<6;t+=1)e[t].connect(Co,0,t),e[t].start(0);return qo(So)})()}const So=await l,Oo=Co(r,{...a,gain:1});await Ro(t,r,Oo);const c=[];for(let t=0;tt!==s[e])||Ao.some((t,e)=>t!==n[e])){s=So,n=Ao;const Mo=t/r.sampleRate;e.gain.setValueAtTime(0,Mo),e=Co(r,{...a,gain:0}),i=Do(r,{...h,orientationX:s[0],orientationY:s[1],orientationZ:s[2],positionX:n[0],positionY:n[1],positionZ:n[2]}),e.gain.setValueAtTime(1,Mo),Oo.connect(e).connect(i.inputs[0]),i.connect(o)}}return o}})(t,e)}}}),au=(Jc=Cs,vo=ia=gl,yo=Do=ru,xo=ou,bo=ha=Ta=ys,To=wl,class extends Jc{constructor(t,e){var s=wo(t),e={...Ge,...e},e=yo(s,e),s=bo(s);super(t,!1,e,s?xo():null),this._nativePannerNode=e,this._orientationX=vo(this,s,e.orientationX,Ft,qt),this._orientationY=vo(this,s,e.orientationY,Ft,qt),this._orientationZ=vo(this,s,e.orientationZ,Ft,qt),this._positionX=vo(this,s,e.positionX,Ft,qt),this._positionY=vo(this,s,e.positionY,Ft,qt),this._positionZ=vo(this,s,e.positionZ,Ft,qt),To(this,1)}get coneInnerAngle(){return this._nativePannerNode.coneInnerAngle}set coneInnerAngle(t){this._nativePannerNode.coneInnerAngle=t}get coneOuterAngle(){return this._nativePannerNode.coneOuterAngle}set coneOuterAngle(t){this._nativePannerNode.coneOuterAngle=t}get coneOuterGain(){return this._nativePannerNode.coneOuterGain}set coneOuterGain(t){this._nativePannerNode.coneOuterGain=t}get distanceModel(){return this._nativePannerNode.distanceModel}set distanceModel(t){this._nativePannerNode.distanceModel=t}get maxDistance(){return this._nativePannerNode.maxDistance}set maxDistance(t){this._nativePannerNode.maxDistance=t}get orientationX(){return this._orientationX}get orientationY(){return this._orientationY}get orientationZ(){return this._orientationZ}get panningModel(){return this._nativePannerNode.panningModel}set panningModel(t){this._nativePannerNode.panningModel=t}get positionX(){return this._positionX}get positionY(){return this._positionY}get positionZ(){return this._positionZ}get refDistance(){return this._nativePannerNode.refDistance}set refDistance(t){this._nativePannerNode.refDistance=t}get rolloffFactor(){return this._nativePannerNode.rolloffFactor}set rolloffFactor(t){this._nativePannerNode.rolloffFactor=t}}),hu=(go=Mt,(t,{disableNormalization:e,imag:s,real:n})=>{var i=s instanceof Float32Array?s:new Float32Array(s),n=n instanceof Float32Array?n:new Float32Array(n),e=t.createPeriodicWave(n,i,{disableNormalization:e});if(Array.from(s).length<2)throw go();return e}),cu=(po=hu,fo=wo=aa=gs,_o=new WeakSet,class mo{constructor(t,e){t=fo(t),e=(t=>{var{imag:e,real:s}=t;return void 0===e?void 0===s?{...t,imag:[0,0],real:[0,0]}:{...t,imag:Array.from(s,()=>0),real:s}:void 0===s?{...t,imag:e,real:Array.from(e,()=>0)}:{...t,imag:e,real:s}})({...Qe,...e}),e=po(t,e);return _o.add(e),e}static[Symbol.hasInstance](t){return null!==t&&"object"==typeof t&&Object.getPrototypeOf(t)===mo.prototype||_o.has(t)}}),lu=((u,y,x,w,p,d)=>{const b=16385,T=new Float32Array([1,1]),S=Math.PI/2,k={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},A={...k,oversample:"none"},f=(t,e,s,n,i)=>{if(1===e)return((t,e,s,n)=>{const i=new Float32Array(b),r=new Float32Array(b);for(let t=0;t{const i=new Float32Array(b),r=new Float32Array(b),o=new Float32Array(b),a=new Float32Array(b),h=Math.floor(8192.5);for(let t=0;th){const y=(t-h)/(16384-h)*S;i[t]=Math.cos(y),r[t]=Math.sin(y),o[t]=0,a[t]=1}else{const y=t/(16384-h)*S;i[t]=1,r[t]=0,o[t]=Math.cos(y),a[t]=Math.sin(y)}const c=y(t,{channelCount:2,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:2}),l=x(t,{...k,gain:0}),u=w(t,{...A,curve:i}),p=x(t,{...k,gain:0}),d=w(t,{...A,curve:r}),f=w(t,{...A,curve:T}),_=x(t,{...k,gain:0}),m=w(t,{...A,curve:o}),g=x(t,{...k,gain:0}),v=w(t,{...A,curve:a});return{connectGraph(){e.connect(c),e.connect(void 0===f.inputs?f:f.inputs[0]),c.connect(l,0),c.connect(p,0),c.connect(_,1),c.connect(g,1),f.connect(s),s.connect(void 0===u.inputs?u:u.inputs[0]),s.connect(void 0===d.inputs?d:d.inputs[0]),s.connect(void 0===m.inputs?m:m.inputs[0]),s.connect(void 0===v.inputs?v:v.inputs[0]),u.connect(l.gain),d.connect(p.gain),m.connect(_.gain),v.connect(g.gain),l.connect(n,0,0),_.connect(n,0,0),p.connect(n,0,1),g.connect(n,0,1)},disconnectGraph(){e.disconnect(c),e.disconnect(void 0===f.inputs?f:f.inputs[0]),c.disconnect(l,0),c.disconnect(p,0),c.disconnect(_,1),c.disconnect(g,1),f.disconnect(s),s.disconnect(void 0===u.inputs?u:u.inputs[0]),s.disconnect(void 0===d.inputs?d:d.inputs[0]),s.disconnect(void 0===m.inputs?m:m.inputs[0]),s.disconnect(void 0===v.inputs?v:v.inputs[0]),u.disconnect(l.gain),d.disconnect(p.gain),m.disconnect(_.gain),v.disconnect(g.gain),l.disconnect(n,0,0),_.disconnect(n,0,0),p.disconnect(n,0,1),g.disconnect(n,0,1)}}})(t,s,n,i);throw p()};return(e,{channelCount:t,channelCountMode:s,pan:n,...i})=>{if("max"===s)throw p();const r=u(e,{...i,channelCount:1,channelCountMode:s,numberOfInputs:2}),o=x(e,{...i,channelCount:t,channelCountMode:s,gain:1}),a=x(e,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:n});let{connectGraph:h,disconnectGraph:c}=f(e,t,o,a,r);Object.defineProperty(a.gain,"defaultValue",{get:()=>0}),Object.defineProperty(a.gain,"maxValue",{get:()=>1}),Object.defineProperty(a.gain,"minValue",{get:()=>-1});t={get bufferSize(){},get channelCount(){return o.channelCount},set channelCount(t){o.channelCount!==t&&(l&&c(),{connectGraph:h,disconnectGraph:c}=f(e,t,o,a,r),l&&h()),o.channelCount=t},get channelCountMode(){return o.channelCountMode},set channelCountMode(t){if("clamped-max"===t||"max"===t)throw p();o.channelCountMode=t},get channelInterpretation(){return o.channelInterpretation},set channelInterpretation(t){o.channelInterpretation=t},get context(){return o.context},get inputs(){return[o]},get numberOfInputs(){return o.numberOfInputs},get numberOfOutputs(){return o.numberOfOutputs},get pan(){return a.gain},addEventListener:(...t)=>o.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>o.dispatchEvent(t[0]),removeEventListener:(...t)=>o.removeEventListener(t[0],t[1],t[2])};let l=!1;return d(Ne(t,r),()=>{h(),l=!0},()=>{c(),l=!1})}})(kl,Ve,je,nu,We,Tl),uu=(lo=lu,uo=We,(t,e)=>{const s=e.channelCountMode;if("clamped-max"===s)throw uo();if(void 0===t.createStereoPanner)return lo(t,e);t=t.createStereoPanner();return Oe(t,e),Ee(t,e,"pan"),Object.defineProperty(t,"channelCountMode",{get:()=>s,set:t=>{if(t!==s)throw uo()}}),t}),pu=(ro=dl,ao=Jt,ho=_l,()=>{const i=new WeakMap;return{render(t,e){var s=i.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=ao(t);var n=Dt(s,e);if(!n){const ro={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,pan:s.pan.value};s=oo(e,ro)}return i.set(e,s),n?await ro(e,t.pan,s.pan):await ho(e,t.pan,s.pan),Qt(s)?await co(t,e,s.inputs[0]):await co(t,e,s),s})(t,e)}}}),du=(Jc=Cs,to=gl,eo=oo=uu,so=pu,class extends Jc{constructor(t,e){var s=no(t),e={...Ze,...e},e=eo(s,e),s=io(s);super(t,!1,e,s?so():null),this._pan=to(this,s,e.pan)}get pan(){return this._pan}}),fu=(Jr=Jt,Kr=co=_s,()=>{const n=new WeakMap;return{render(t,e){var s=n.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=Jr(t);if(!Dt(s,e)){const Jr={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,curve:s.curve,oversample:s.oversample};s=Hr(e,Jr)}return n.set(e,s),Qt(s)?await Kr(t,e,s.inputs[0]):await Kr(t,e,s),s})(t,e)}}}),_u=(Jc=Cs,Gr=be,Qr=Hr=nu,Zr=fu,Xr=no=gs,Yr=io=ys,$r=wl,class extends Jc{constructor(t,e){var s=Xr(t),e={...Xe,...e},e=Qr(s,e);super(t,!0,e,Yr(s)?Zr():null),this._isCurveNullified=!1,this._nativeWaveShaperNode=e,$r(this,1)}get curve(){return this._isCurveNullified?null:this._nativeWaveShaperNode.curve}set curve(t){if(null===t)this._isCurveNullified=!0,this._nativeWaveShaperNode.curve=new Float32Array([0,0]);else{if(t.length<2)throw Gr();this._isCurveNullified=!1,this._nativeWaveShaperNode.curve=t}}get oversample(){return this._nativeWaveShaperNode.oversample}set oversample(t){this._nativeWaveShaperNode.oversample=t}}),mu=null!==(Jc=ps)&&Jc.isSecureContext,gu=(Ur=ps,(t,e,s)=>{Object.defineProperties(Ur,{currentFrame:{configurable:!0,get:()=>Math.round(t*e)},currentTime:{configurable:!0,get:()=>t}});try{return s()}finally{null!==Ur&&(delete Ur.currentFrame,delete Ur.currentTime)}}),vu=new WeakMap,yu=(Wr=vu,Br=vs,t=>{let e=Wr.get(t);if(void 0!==e)return e;if(null===Br)throw new Error("Missing the native OfflineAudioContext constructor.");return e=new Br(1,1,44100),Wr.set(t,e),e}),xu=mu?((r,o,a,l,u,p,d,f,_,m,g,v,y)=>{let x=0;return(e,s,h={credentials:"omit"})=>{const t=g.get(e);if(void 0!==t&&t.has(s))return Promise.resolve();const n=m.get(e);if(void 0!==n){const r=n.get(s);if(void 0!==r)return r}const c=p(e),i=void 0===c.audioWorklet?u(s).then(([t,e])=>{var[t,e]=mt(t,e);return a(`${t};((a,b)=>{(a[b]=a[b]||[]).push((AudioWorkletProcessor,global,registerProcessor,sampleRate,self,window)=>{${e}\n})})(window,'_AWGS')`)}).then(()=>{const t=y._AWGS.pop();if(void 0===t)throw new SyntaxError;l(c.currentTime,c.sampleRate,()=>t(class{},void 0,(t,e)=>{if(""===t.trim())throw o();const s=pt.get(c);if(void 0!==s){if(s.has(t))throw o();vt(e),gt(e.parameterDescriptors),s.set(t,e)}else vt(e),gt(e.parameterDescriptors),pt.set(c,new Map([[t,e]]))},c.sampleRate,void 0,void 0))}):Promise.all([u(s),Promise.resolve(r(v,v))]).then(([[t,e],s])=>{const n=x+1;x=n;const[i,r]=mt(t,e),o=new Blob([`${i};((AudioWorkletProcessor,registerProcessor)=>{${r}\n})(${s?"AudioWorkletProcessor":"class extends AudioWorkletProcessor {__b=new WeakSet();constructor(){super();(p=>p.postMessage=(q=>(m,t)=>q.call(p,m,t?t.filter(u=>!this.__b.has(u)):t))(p.postMessage))(this.port)}}"},(n,p)=>registerProcessor(n,class extends p{${s?"":"__c = (a) => a.forEach(e=>this.__b.add(e.buffer));"}process(i,o,p){${s?"":"i.forEach(this.__c);o.forEach(this.__c);this.__c(Object.values(p));"}return super.process(i.map(j=>j.some(k=>k.length===0)?[]:j),o,p)}}));registerProcessor('__sac${n}',class extends AudioWorkletProcessor{process(){return !1}})`],{type:"application/javascript; charset=utf-8"}),a=URL.createObjectURL(o);return c.audioWorklet.addModule(a,h).then(()=>{if(f(c))return c;const t=d(c);return t.audioWorklet.addModule(a,h).then(()=>t)}).then(t=>{if(null===_)throw new SyntaxError;try{new _(t,`__sac${n}`)}catch{throw new SyntaxError}}).finally(()=>URL.revokeObjectURL(a))});return void 0===n?m.set(e,new Map([[s,i]])):n.set(s,i),i.then(()=>{const t=g.get(e);void 0===t?g.set(e,new Set([s])):t.add(s)}).finally(()=>{const t=m.get(e);void 0!==t&&t.delete(s)}),i}})(us,We,(zr=ps,i=>new Promise((t,r)=>{if(null!==zr){const e=zr.document.head;if(null===e)r(new SyntaxError);else{const s=zr.document.createElement("script"),n=new Blob([i],{type:"application/javascript"}),o=URL.createObjectURL(n),a=zr.onerror,h=()=>{zr.onerror=a,URL.revokeObjectURL(o)};zr.onerror=(t,e,s,n,i)=>e===o||e===zr.location.href&&1===s&&1===n?(h(),r(i),!1):null!==a?a(t,e,s,n,i):void 0,s.onerror=()=>{h(),r(new SyntaxError)},s.onload=()=>{h(),t()},s.src=o,s.type="module",e.appendChild(s)}}else r(new SyntaxError)})),gu,async t=>{try{const e=await fetch(t);if(e.ok)return[await e.text(),e.url]}catch{}throw new DOMException("","AbortError")},gs,yu,ys,As,new WeakMap,new WeakMap,(jr=As,Lr=vs,async()=>{if(null===jr)return!0;if(null===Lr)return!1;const t=new Blob(['class A extends AudioWorkletProcessor{process(i){this.port.postMessage(i,[i[0][0].buffer])}}registerProcessor("a",A)'],{type:"application/javascript; charset=utf-8"}),e=new Lr(1,128,44100),s=URL.createObjectURL(t);let n=!1,i=!1;try{await e.audioWorklet.addModule(s);const Lr=new jr(e,"a",{numberOfOutputs:0}),t=e.createOscillator();Lr.port.onmessage=()=>n=!0,Lr.onprocessorerror=()=>i=!0,t.connect(Lr),t.start(0),await e.startRendering()}catch{}finally{URL.revokeObjectURL(s)}return n&&!i}),ps):void 0,wu=(Nr=Ts,Pr=ys,t=>Nr(t)||Pr(t)),bu=(Dr=al,Or=us,Mr=new WeakSet,Rr=wu,qr=Ot,Fr=Ce,Ir=hl,Vr=cl,(t,r)=>{const o=Rr(t)?t:Er(t);if(Mr.has(r)){const Dr=new DOMException("","DataCloneError");return Promise.reject(Dr)}try{Mr.add(r)}catch{}return Or(Fr,()=>Fr(o))?o.decodeAudioData(r).then(t=>(ge(r).catch(()=>{}),Or(qr,()=>qr(t))||Vr(t),Dr.add(t),t)):new Promise((e,s)=>{const n=async()=>{try{await ge(r)}catch{}},i=t=>{s(t),n()};try{o.decodeAudioData(r,t=>{"function"!=typeof t.copyFromChannel&&(Ir(t),Et(t)),Dr.add(t),n().then(()=>e(t))},t=>{i(null===t?new DOMException("","EncodingError"):t)})}catch(t){i(t)}})}),Tu=(cr=xu,lr=ol,ur=ll,pr=vl,dr=bl,fr=Cl,_r=Ol,mr=ql,gr=Vl,vr=bu,yr=Pl,xr=zl,wr=Bl,br=Xl,Tr=tu,Sr=au,kr=cu,Ar=du,Cr=_u,class extends Hl{constructor(t,e){super(t,e),this._nativeContext=t,this._audioWorklet=void 0===cr?void 0:{addModule:(t,e)=>cr(this,t,e)}}get audioWorklet(){return this._audioWorklet}createAnalyser(){return new lr(this)}createBiquadFilter(){return new dr(this)}createBuffer(t,e,s){return new ur({length:e,numberOfChannels:t,sampleRate:s})}createBufferSource(){return new pr(this)}createChannelMerger(t=6){return new fr(this,{numberOfInputs:t})}createChannelSplitter(t=6){return new _r(this,{numberOfOutputs:t})}createConstantSource(){return new mr(this)}createConvolver(){return new gr(this)}createDelay(t=1){return new yr(this,{maxDelayTime:t})}createDynamicsCompressor(){return new xr(this)}createGain(){return new wr(this)}createIIRFilter(t,e){return new br(this,{feedback:e,feedforward:t})}createOscillator(){return new Tr(this)}createPanner(){return new Sr(this)}createPeriodicWave(t,e,s={disableNormalization:!1}){return new kr(this,{...s,imag:e,real:t})}createStereoPanner(){return new Ar(this)}createWaveShaper(){return new Cr(this)}decodeAudioData(t,e,s){return vr(this._nativeContext,t).then(t=>("function"==typeof e&&e(t),t),t=>{throw"function"==typeof s&&s(t),t})}}),Su=class extends Cs{constructor(t,e){const s=ar(t),n=s.createMediaElementSource(e.mediaElement);if(hr(s))throw TypeError();super(t,!0,n,null),this._nativeMediaElementAudioSourceNode=n}get mediaElement(){return this._nativeMediaElementAudioSourceNode.mediaElement}},ku=class extends Cs{constructor(t,e){var s=rr(t);if(or(s))throw new TypeError;e=((t,e)=>{t=t.createMediaStreamDestination();return Oe(t,e),1===t.numberOfOutputs&&Object.defineProperty(t,"numberOfOutputs",{get:()=>0}),t})(s,{...Ae,...e});super(t,!1,e,null),this._nativeMediaStreamAudioDestinationNode=e}get stream(){return this._nativeMediaStreamAudioDestinationNode.stream}},Au=class extends Cs{constructor(t,e){var s=nr(t),e=((t,{mediaStream:e})=>{const s=e.getAudioTracks();s.sort((t,e)=>t.ide.id?1:0);var n=s.slice(0,1),n=t.createMediaStreamSource(new MediaStream(n));return Object.defineProperty(n,"mediaStream",{value:e}),n})(s,e);if(ir(s))throw new TypeError;super(t,!0,e,null),this._nativeMediaStreamAudioSourceNode=e}get mediaStream(){return this._nativeMediaStreamAudioSourceNode.mediaStream}},Cu=(er=be,sr=ir=or=hr=ys,(t,{mediaStreamTrack:e})=>{if("function"==typeof t.createMediaStreamTrackSource)return t.createMediaStreamTrackSource(e);var s=new MediaStream([e]),s=t.createMediaStreamSource(s);if("audio"!==e.kind)throw er();if(sr(t))throw new TypeError;return s}),Du=(ol=Cs,Ki=Cu,tr=nr=rr=ar=Er=gs,class extends ol{constructor(t,e){var s=tr(t);super(t,!0,Ki(s,e),null)}}),Ou=(ol=Tu,Gi=be,Qi=We,Zi=()=>new DOMException("","UnknownError"),Xi=Su,Yi=ku,$i=Au,Hi=Du,Ji=bs,class extends ol{constructor(t={}){if(null===Ji)throw new Error("Missing the native AudioContext constructor.");let e;try{e=new Ji(t)}catch(t){if(12===t.code&&"sampleRate is not in range"===t.message)throw Qi();throw t}if(null===e)throw Zi();if(void 0!==(n=t.latencyHint)&&"number"!=typeof n&&("string"!=typeof n||"balanced"!==n&&"interactive"!==n&&"playback"!==n))throw new TypeError(`The provided value '${t.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);if(void 0!==t.sampleRate&&e.sampleRate!==t.sampleRate)throw Qi();super(e,2);var s=t["latencyHint"],n=e["sampleRate"];if(this._baseLatency="number"==typeof e.baseLatency?e.baseLatency:"balanced"===s?512/n:"interactive"===s||void 0===s?256/n:"playback"===s?1024/n:128*Math.max(2,Math.min(128,Math.round(s*n/128)))/n,this._nativeAudioContext=e,"webkitAudioContext"===Ji.name?(this._nativeGainNode=e.createGain(),this._nativeOscillatorNode=e.createOscillator(),this._nativeGainNode.gain.value=1e-37,this._nativeOscillatorNode.connect(this._nativeGainNode).connect(e.destination),this._nativeOscillatorNode.start()):(this._nativeGainNode=null,this._nativeOscillatorNode=null),this._state=null,"running"===e.state){this._state="suspended";const t=()=>{"suspended"===this._state&&(this._state=null),e.removeEventListener("statechange",t)};e.addEventListener("statechange",t)}}get baseLatency(){return this._baseLatency}get state(){return null!==this._state?this._state:this._nativeAudioContext.state}close(){return"closed"===this.state?this._nativeAudioContext.close().then(()=>{throw Gi()}):("suspended"===this._state&&(this._state=null),this._nativeAudioContext.close().then(()=>{null!==this._nativeGainNode&&null!==this._nativeOscillatorNode&&(this._nativeOscillatorNode.stop(),this._nativeGainNode.disconnect(),this._nativeOscillatorNode.disconnect()),Lt(this)}))}createMediaElementSource(t){return new Xi(this,{mediaElement:t})}createMediaStreamDestination(){return new Yi(this)}createMediaStreamSource(t){return new $i(this,{mediaStream:t})}createMediaStreamTrackSource(t){return new Hi(this,{mediaStreamTrack:t})}resume(){return"suspended"===this._state?new Promise((t,e)=>{const s=()=>{this._nativeAudioContext.removeEventListener("statechange",s),"running"===this._nativeAudioContext.state?t():this.resume().then(t,e)};this._nativeAudioContext.addEventListener("statechange",s)}):this._nativeAudioContext.resume().catch(t=>{if(void 0===t||15===t.code)throw Gi();throw t})}suspend(){return this._nativeAudioContext.suspend().catch(t=>{if(void 0===t)throw Gi();throw t})}}),Mu=(Ui=$l,t=>{t=Ui.get(t);if(void 0===t)throw new Error("The context has no set of AudioWorkletNodes.");return t}),Eu=(t,e)=>{Bi(t).add(e)},Ru=(Wi=Mt,(t,e,s=0,n=0)=>{const i=t[s];if(void 0===i)throw Wi();return ie(e)?i.connect(e,0,n):i.connect(e,0)}),qu=(zi=Bi=Mu,(t,e)=>{zi(t).delete(e)}),Fu=(Li=Mt,(t,e,s,n=0)=>void 0===e?t.forEach(t=>t.disconnect()):"number"==typeof e?ye(Li,t,e).disconnect():ie(e)?void 0===s?t.forEach(t=>t.disconnect(e)):void 0===n?ye(Li,t,s).disconnect(e,0):ye(Li,t,s).disconnect(e,0,n):void 0===s?t.forEach(t=>t.disconnect(e)):ye(Li,t,s).disconnect(e,0)),Iu=new WeakMap,Vu=(Pi=Iu,ji=yt,t=>ji(Pi,t)),Nu=(Ai=Mt,Ci=be,Ri=ze,Vi=Vu,(o,t,e,a)=>{if(0===a.numberOfInputs&&0===a.numberOfOutputs)throw qi();const h=Array.isArray(a.outputChannelCount)?a.outputChannelCount:Array.from(a.outputChannelCount);if(h.some(t=>t<1))throw qi();if(h.length!==a.numberOfOutputs)throw Ai();if("explicit"!==a.channelCountMode)throw qi();const c=a.channelCount*a.numberOfInputs,s=h.reduce((t,e)=>t+e,0),n=void 0===e.parameterDescriptors?0:e.parameterDescriptors.length;if(6void 0===ki?0:ki},maxValue:{get:()=>void 0===Ai?Ft:Ai},minValue:{get:()=>void 0===Ci?qt:Ci}}),p.push(Oi)}const d=Di(o,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,c+n)}),f=Fe(t,o.sampleRate),_=Ri(o,f,c+n,Math.max(1,s)),r=Oi(o,{channelCount:Math.max(1,s),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,s)}),m=[];for(let t=0;t{const s=p[e];return s.connect(d,0,c+e),s.start(0),[t,s.offset]}));d.connect(_);let v=a.channelInterpretation,y=null;const x=0===a.numberOfOutputs?[_]:m,w={get bufferSize(){return f},get channelCount(){return a.channelCount},set channelCount(t){throw Ci()},get channelCountMode(){return a.channelCountMode},set channelCountMode(t){throw Ci()},get channelInterpretation(){return v},set channelInterpretation(t){for(const e of l)e.channelInterpretation=t;v=t},get context(){return _.context},get inputs(){return l},get numberOfInputs(){return a.numberOfInputs},get numberOfOutputs(){return a.numberOfOutputs},get onprocessorerror(){return y},set onprocessorerror(t){"function"==typeof y&&w.removeEventListener("processorerror",y),y="function"==typeof t?t:null,"function"==typeof y&&w.addEventListener("processorerror",y)},get parameters(){return g},get port(){return i.port2},addEventListener:(...t)=>_.addEventListener(t[0],t[1],t[2]),connect:ki.bind(null,x),disconnect:Fi.bind(null,x),dispatchEvent:(...t)=>_.dispatchEvent(t[0]),removeEventListener:(...t)=>_.removeEventListener(t[0],t[1],t[2])},b=new Map;var T,S;i.port1.addEventListener=(T=i.port1.addEventListener,(...t)=>{if("message"===t[0]){const s="function"==typeof t[1]?t[1]:"object"==typeof t[1]&&null!==t[1]&&"function"==typeof t[1].handleEvent?t[1].handleEvent:null;var e;null!==s&&(void 0!==(e=b.get(t[1]))?t[1]=e:(t[1]=t=>{Ii(o.currentTime,o.sampleRate,()=>s(t))},b.set(s,t[1])))}return T.call(i.port1,t[0],t[1],t[2])}),i.port1.removeEventListener=(S=i.port1.removeEventListener,(...t)=>{var e;return"message"!==t[0]||void 0!==(e=b.get(t[1]))&&(b.delete(t[1]),t[1]=e),S.call(i.port1,t[0],t[1],t[2])});let k=null;Object.defineProperty(i.port1,"onmessage",{get:()=>k,set:t=>{"function"==typeof k&&i.port1.removeEventListener("message",k),k="function"==typeof t?t:null,"function"==typeof k&&(i.port1.addEventListener("message",k),i.port1.start())}}),e.prototype.port=i.port1;let A=null;const C=((t,e,s,n)=>{let i=dt.get(t);void 0===i&&(i=new WeakMap,dt.set(t,i));t=(async()=>{var t;return new s((t=n,await new Promise((e,s)=>{const{port1:n,port2:i}=new MessageChannel;n.onmessage=({data:t})=>{n.close(),i.close(),e(t)},n.onmessageerror=({data:t})=>{n.close(),i.close(),s(t)},i.postMessage(t)})))})();return i.set(e,t),t})(o,w,e,a);C.then(t=>A=t);const D=ue(a.numberOfInputs,a.channelCount),O=ue(a.numberOfOutputs,h),M=void 0===e.parameterDescriptors?[]:e.parameterDescriptors.reduce((t,{name:e})=>({...t,[e]:new Float32Array(128)}),{});let E=!0;const R=()=>{0{if(null!==A){const r=Vi(w);for(let n=0;n{ce(s,M,t,c+e,n)});for(let e=0;e{if(0t.every(t=>0===t))&&(1===s?q.delete(e):q.set(e,s-1)),t)}),t=Ii(o.currentTime+n/o.sampleRate,o.sampleRate,()=>A.process(s,O,M));E=t;for(let e=0,s=0;e_.connect(I).connect(o.destination),N=()=>{_.disconnect(I),I.disconnect()};return V(),Ni(w,()=>{if(E){N(),0{E&&(V(),R()),F=!1})}),Pu=(xi=be,wi=Nu,Ti=qi=We,Si=Ni=Tl,(t,e,s,n,i,r)=>{if(null!==s)try{const wi=new s(t,n,r),Ti=new Map;let e=null;if(Object.defineProperties(wi,{channelCount:{get:()=>r.channelCount,set:()=>{throw xi()}},channelCountMode:{get:()=>"explicit",set:()=>{throw xi()}},onprocessorerror:{get:()=>e,set:t=>{"function"==typeof e&&wi.removeEventListener("processorerror",e),e="function"==typeof t?t:null,"function"==typeof e&&wi.addEventListener("processorerror",e)}}}),wi.addEventListener=(a=wi.addEventListener,(...e)=>{if("processorerror"===e[0]){const wi="function"==typeof e[1]?e[1]:"object"==typeof e[1]&&null!==e[1]&&"function"==typeof e[1].handleEvent?e[1].handleEvent:null;var t;null!==wi&&(void 0!==(t=Ti.get(e[1]))?e[1]=t:(e[1]=t=>{"error"===t.type?(Object.defineProperties(t,{type:{value:"processorerror"}}),wi(t)):wi(new ErrorEvent(e[0],{...t}))},Ti.set(wi,e[1])))}return a.call(wi,"error",e[1],e[2]),a.call(wi,...e)}),wi.removeEventListener=(o=wi.removeEventListener,(...t)=>{if("processorerror"===t[0]){const wi=Ti.get(t[1]);void 0!==wi&&(Ti.delete(t[1]),t[1]=wi)}return o.call(wi,"error",t[1],t[2]),o.call(wi,t[0],t[1],t[2])}),0===r.numberOfOutputs)return wi;{const xi=bi(t,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return wi.connect(xi).connect(t.destination),Si(wi,()=>xi.disconnect(),()=>xi.connect(t.destination))}}catch(t){if(11===t.code)throw Ti();throw t}var o,a;if(void 0===i)throw Ti();return(t=>{const e=(new MessageChannel)["port1"];try{e.postMessage(t)}finally{e.close()}})(r),wi(t,e,i,r)}),ju=(ii=dl,ri=ki=Ru,oi=fl,ai=Di=kl,hi=Oi=Ve,ci=Mi=El,li=bi=Ei=je,ui=qu,pi=Fi=Fu,di=Ii=gu,fi=Jt,_i=As,mi=vs,gi=_l,vi=_s,yi=Gl,(r,a,h)=>{const c=new WeakMap;let l=null;return{render(t,e){ui(e,t);var s=c.get(e);return void 0!==s?Promise.resolve(s):(async(o,e)=>{let t=fi(o),s=null;const n=Dt(t,e),i=Array.isArray(a.outputChannelCount)?a.outputChannelCount:Array.from(a.outputChannelCount);if(null===_i){const ii=i.reduce((t,e)=>t+e,0),oi=hi(e,{channelCount:Math.max(1,ii),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,ii)}),ci=[];for(let t=0;t{const s=new mi(oi,128*Math.ceil(o.context.length/128),e.sampleRate),n=[],i=[];for(let t=0;t{var e=ci(s,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:t.value});return await gi(s,t,e.offset),e})),r=ai(s,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,ii+ri)});for(let e=0;evi(o,s,t))),yi(s)};l=(async(t,s,e,i,r,o,a)=>{const h=null===s?128*Math.ceil(t.context.length/128):s.length,c=i.channelCount*i.numberOfInputs,n=r.reduce((t,e)=>t+e,0),l=0===n?null:e.createBuffer(n,h,e.sampleRate);if(void 0===o)throw new Error("Missing the processor constructor.");const u=Nt(t),p=await((t,e)=>{t=yt(dt,t),e=Jt(e);return yt(t,e)})(e,t),d=ue(i.numberOfInputs,i.channelCount),f=ue(i.numberOfOutputs,r),_=Array.from(t.parameters.keys()).reduce((t,e)=>({...t,[e]:new Float32Array(128)}),{});for(let n=0;n{ce(s,_,t,c+e,n)});for(let e=0;e0===u.activeInputs[e].size?[]:t),s=a(n/e.sampleRate,e.sampleRate,()=>p.process(t,f,_));if(null!==l)for(let e=0,s=0;eni.get(t)),zu=(si=Iu,(t,e)=>{si.set(t,e)}),Wu=mu?(Gn=Eu,Qn=gl,Zn=ju,Xn=Pu,Yn=Nt,$n=Lu,Hn=gs,Jn=ys,Kn=As,ti=zu,ei=rs,class extends Cs{constructor(t,e,s){var n;const i=Hn(t),r=Jn(i),o={...s={...he,...s},outputChannelCount:void 0!==s.outputChannelCount?s.outputChannelCount:1===s.numberOfInputs&&1===s.numberOfOutputs?[s.channelCount]:Array.from({length:s.numberOfOutputs},()=>1)};(t=>{const{port1:e,port2:s}=new MessageChannel;try{e.postMessage(t)}finally{e.close(),s.close()}})(o);const a=pt.get(i),h=null==a?void 0:a.get(e),c=!r&&"closed"===i.state&&null!==(n=$n(i))&&void 0!==n?n:i,l=Xn(c,r?null:t.baseLatency,Kn,e,h,o);super(t,!0,l,r?Zn(e,o,h):null);const u=[];l.parameters.forEach((t,e)=>{t=Qn(this,r,t);u.push([e,t])}),this._nativeAudioWorkletNode=l,this._onprocessorerror=null,this._parameters=new ae(u),r&&Gn(i,this);var e=Yn(this)["activeInputs"];ti(l,e)}get onprocessorerror(){return this._onprocessorerror}set onprocessorerror(t){var e="function"==typeof t?ei(this,t):null;this._nativeAudioWorkletNode.onprocessorerror=e;var s=this._nativeAudioWorkletNode.onprocessorerror;this._onprocessorerror=null!==s&&s===e?t:s}get parameters(){return null===this._parameters?this._nativeAudioWorkletNode.parameters:this._parameters}get port(){return this._nativeAudioWorkletNode.port}}):void 0,Bu=(Bn=We,Un=vs,(t,e,s)=>{if(null===Un)throw new Error("Missing the native OfflineAudioContext constructor.");try{return new Un(t,e,s)}catch(t){if("SyntaxError"===t.name)throw Bn();throw t}}),Uu=(In=al,Vn=us,Nn=fs,Pn=Mu,jn=Gl,Ln=Ot,zn=hl,Wn=cl,(t,e)=>Nn(t).render(t,e).then(()=>Promise.all(Array.from(Pn(e)).map(t=>Nn(t).render(t,e)))).then(()=>jn(e)).then(t=>("function"!=typeof t.copyFromChannel?(zn(t),Et(t)):Vn(Ln,()=>Ln(t))||Wn(t),In.add(t),t))),Gu=(En=us,Rn=be,qn=Bu,Fn=Uu,class extends Tu{constructor(t,e,s){let n;if("number"==typeof t&&void 0!==e&&void 0!==s)n={length:e,numberOfChannels:t,sampleRate:s};else{if("object"!=typeof t)throw new Error("The given parameters are not valid.");n=t}const{length:i,numberOfChannels:r,sampleRate:o}={...Be,...n},a=qn(r,i,o);En(Ce,()=>Ce(a))||a.addEventListener("statechange",(()=>{let e=0;const s=t=>{"running"===this._state&&(0{this._state=null,Lt(this)}))}_waitForThePromiseToSettle(t){null===this._state?this._nativeOfflineAudioContext.dispatchEvent(t):setTimeout(()=>this._waitForThePromiseToSettle(t))}}),Qu=(On=ct,Mn=Ts,t=>{var e=On.get(t);return Mn(e)||Mn(t)}),Zu=(Cn=ot,Dn=Ss,t=>Cn.has(t)||Dn(t)),Xu=(kn=ht,An=ks,t=>kn.has(t)||An(t)),Yu=(Tn=ct,Sn=ys,t=>{var e=Tn.get(t);return Sn(e)||Sn(t)}),$u=()=>(async(t,e,s,n,i,r,o,a,h,c,l,u,p,d,f,_)=>!!(t(e,e)&&t(s,s)&&t(i,i)&&t(r,r)&&t(a,a)&&t(h,h)&&t(c,c)&&t(l,l)&&t(u,u)&&t(p,p)&&t(d,d))&&(await Promise.all([t(n,n),t(o,o),t(f,f),t(_,_)])).every(t=>t))(us,(s=>()=>{if(null===s)return!1;const t=new s(1,1,44100).createBuffer(1,1,44100);if(void 0===t.copyToChannel)return!0;var e=new Float32Array(2);try{t.copyFromChannel(e,0,0)}catch{return!1}return!0})(vs),(s=>()=>{if(null===s)return!1;if(void 0!==s.prototype&&void 0!==s.prototype.close)return!0;const t=new s,e=void 0!==t.close;try{t.close()}catch{}return e})(bs),(t=>()=>{if(null===t)return Promise.resolve(!1);const i=new t(1,1,44100);return new Promise(e=>{let s=!0;var t=t=>{s&&(s=!1,i.startRendering(),e(t instanceof TypeError))};let n;try{n=i.decodeAudioData(null,()=>{},t)}catch(e){t(e)}void 0!==n&&n.catch(t)})})(vs),(e=>()=>{if(null===e)return!1;let t;try{t=new e({latencyHint:"balanced"})}catch{return!1}return t.close(),!0})(bs),(s=>()=>{if(null===s)return!1;const t=new s(1,1,44100).createGain(),e=t.connect(t)===t;return t.disconnect(t),e})(vs),((r,o)=>async()=>{if(null===r)return!0;if(null===o)return!1;const t=new Blob(['let c,p;class A extends AudioWorkletProcessor{constructor(){super();this.port.onmessage=(e)=>{p=e.data;p.onmessage=()=>{p.postMessage(c);p.close()};this.port.postMessage(0)}}process(){c=1}}registerProcessor("a",A)'],{type:"application/javascript; charset=utf-8"}),s=new MessageChannel,e=new o(1,128,44100),n=URL.createObjectURL(t);let i=!1;try{await e.audioWorklet.addModule(n);const o=new r(e,"a",{numberOfOutputs:0}),t=e.createOscillator();await new Promise(t=>{o.port.onmessage=()=>t(),o.port.postMessage(s.port2,[s.port2])}),o.port.onmessage=()=>i=!0,t.connect(o),t.start(0),await e.startRendering(),i=await new Promise(e=>{s.port1.onmessage=({data:t})=>e(1===t),s.port1.postMessage(0)})}catch{}finally{s.port1.close(),URL.revokeObjectURL(n)}return i})(As,vs),(e=>()=>{if(null===e)return!1;const t=new e(1,1,44100).createChannelMerger();if("max"===t.channelCountMode)return!0;try{t.channelCount=2}catch{return!0}return!1})(vs),(e=>()=>{if(null===e)return!1;const t=new e(1,1,44100);return void 0===t.createConstantSource||t.createConstantSource().offset.maxValue!==Number.POSITIVE_INFINITY})(vs),(s=>()=>{if(null===s)return!1;const t=new s(1,1,44100),e=t.createConvolver();e.buffer=t.createBuffer(1,1,t.sampleRate);try{e.buffer=t.createBuffer(1,1,t.sampleRate)}catch{return!1}return!0})(vs),(e=>()=>{if(null===e)return!1;const t=new e(1,1,44100).createConvolver();try{t.channelCount=1}catch{return!1}return!0})(vs),ss,(t=>()=>null!==t&&t.hasOwnProperty("isSecureContext"))(ps),(e=>()=>{if(null===e)return!1;const t=new e;try{return t.createMediaStreamSource(new MediaStream),!1}catch(t){return!0}finally{t.close()}})(bs),(n=>()=>{if(null===n)return Promise.resolve(!1);const t=new n(1,1,44100);if(void 0===t.createStereoPanner)return Promise.resolve(!0);if(void 0===t.createConstantSource)return Promise.resolve(!0);const e=t.createConstantSource(),s=t.createStereoPanner();return e.channelCount=1,e.offset.value=1,s.channelCount=1,e.start(),e.connect(s).connect(t.destination),t.startRendering().then(t=>1!==t.getChannelData(0)[0])})(vs),ns);function Hu(t){return void 0===t}function Ju(t){return!Hu(t)}function Ku(t){return"function"==typeof t}function tp(t){return"number"==typeof t}function ep(t){return"[object Object]"===Object.prototype.toString.call(t)&&t.constructor===Object}function sp(t){return"boolean"==typeof t}function np(t){return Array.isArray(t)}function ip(t){return"string"==typeof t}function rp(t){return ip(t)&&/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i.test(t)}function op(t,e){if(!t)throw new Error(e)}function ap(t,e,s=1/0){if(!(e<=t&&t<=s))throw new RangeError(`Value must be within [${e}, ${s}], got: ${t}`)}function hp(t){t.isOffline||"running"===t.state||_p('The AudioContext is "suspended". Invoke Tone.start() from a user action to start the audio.')}let cp=!1,lp=!1;function up(t){cp=t}function pp(t){Hu(t)&&cp&&!lp&&(lp=!0,_p("Events scheduled inside of scheduled callbacks should use the passed in scheduling time. See https://github.com/Tonejs/Tone.js/wiki/Accurate-Timing"))}let dp=console;function fp(...t){dp.log(...t)}function _p(...t){dp.warn(...t)}const mp="object"==typeof self?self:null,gp=mp&&(mp.hasOwnProperty("AudioContext")||mp.hasOwnProperty("webkitAudioContext"));function vp(t,e,s,n){var i,r=arguments.length,o=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,s):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,s,n);else for(var a=t.length-1;0<=a;a--)(i=t[a])&&(o=(r<3?i(o):3{this._createTimeout(),this._callback()},1e3*this._updateInterval)}_createClock(){if("worker"===this._type)try{this._createWorker()}catch(t){this._type="timeout",this._createClock()}else"timeout"===this._type&&this._createTimeout()}_disposeClock(){this._timeout&&clearTimeout(this._timeout),this._worker&&(this._worker.terminate(),this._worker.onmessage=null)}get updateInterval(){return this._updateInterval}set updateInterval(t){this._updateInterval=Math.max(t,128/44100),"worker"===this._type&&this._worker.postMessage(Math.max(1e3*t,1))}get type(){return this._type}set type(t){this._disposeClock(),this._type=t,this._createClock()}dispose(){this._disposeClock()}}function wp(t){return Xu(t)}function bp(t){return Zu(t)}function Tp(t){return Yu(t)}function Sp(t){return Qu(t)}function kp(t){return t instanceof ll}function Ap(t,...e){if(!e.length)return t;var s,n,i=e.shift();if(ep(t)&&ep(i))for(const e in i)s=e,n=i[e],"value"===s||wp(n)||bp(n)||kp(n)?t[e]=i[e]:ep(i[e])?(t[e]||Object.assign(t,{[e]:{}}),Ap(t[e],i[e])):Object.assign(t,{[e]:i[e]});return Ap(t,...e)}function Cp(e,t,s=[],n){const i={},r=Array.from(t);if(ep(r[0])&&n&&!Reflect.has(r[0],n)&&(Object.keys(r[0]).some(t=>Reflect.has(e,t))||(Ap(i,{[n]:r[0]}),s.splice(s.indexOf(n),1),r.shift())),1===r.length&&ep(r[0]))Ap(i,r[0]);else for(let t=0;t{Reflect.has(e,t)&&delete e[t]}),e}class Mp{constructor(){this.debug=!1,this._wasDisposed=!1}static getDefaults(){return{}}log(...t){(this.debug||mp&&this.toString()===mp.TONE_DEBUG_CLASS)&&fp(this,...t)}dispose(){return this._wasDisposed=!0,this}get disposed(){return this._wasDisposed}toString(){return this.name}}Mp.version=s;const Ep=1e-6;function Rp(t,e){return t>e+Ep}function qp(t,e){return Rp(t,e)||Ip(t,e)}function Fp(t,e){return t+Epthis.memory){const t=this.length-this.memory;this._timeline.splice(0,t)}return this}remove(t){t=this._timeline.indexOf(t);return-1!==t&&this._timeline.splice(t,1),this}get(t,e="time"){e=this._search(t,e);return-1!==e?this._timeline[e]:null}peek(){return this._timeline[0]}shift(){return this._timeline.shift()}getAfter(t,e="time"){e=this._search(t,e);return e+1=t;)s--;return this._iterate(e,s+1),this}forEachAtTime(s,n){var i=this._search(s);if(-1!==i&&Ip(this._timeline[i].time,s)){let e=i;for(let t=i;0<=t&&Ip(this._timeline[t].time,s);t--)e=t;this._iterate(t=>{n(t)},e,i)}return this}dispose(){return super.dispose(),this._timeline=[],this}}const Pp=[];function jp(t){Pp.push(t)}const Lp=[];function zp(t){Lp.push(t)}class Wp extends Mp{constructor(){super(...arguments),this.name="Emitter"}on(t,e){return t.split(/\W+/).forEach(t=>{Hu(this._events)&&(this._events={}),this._events.hasOwnProperty(t)||(this._events[t]=[]),this._events[t].push(e)}),this}once(e,s){const n=(...t)=>{s(...t),this.off(e,n)};return this.on(e,n),this}off(t,s){return t.split(/\W+/).forEach(t=>{if(Hu(this._events)&&(this._events={}),this._events.hasOwnProperty(t))if(Hu(s))this._events[t]=[];else{const e=this._events[t];for(let t=e.length-1;0<=t;t--)e[t]===s&&e.splice(t,1)}}),this}emit(t,...s){if(this._events&&this._events.hasOwnProperty(t)){const n=this._events[t].slice(0);for(let t=0,e=n.length;t{var e=Object.getOwnPropertyDescriptor(Wp.prototype,t);Object.defineProperty(s.prototype,t,e)})}dispose(){return super.dispose(),this._events=void 0,this}}class Bp extends Wp{constructor(){super(...arguments),this.isOffline=!1}toJSON(){return{}}}class Up extends Bp{constructor(){super(),this.name="Context",this._constants=new Map,this._timeouts=new Np,this._timeoutIds=0,this._initialized=!1,this.isOffline=!1,this._workletModules=new Map;var t,e=Cp(Up.getDefaults(),arguments,["context"]);e.context?this._context=e.context:this._context=(t={latencyHint:e.latencyHint},new Ou(t)),this._ticker=new xp(this.emit.bind(this,"tick"),e.clockSource,e.updateInterval),this.on("tick",this._timeoutLoop.bind(this)),this._context.onstatechange=()=>{this.emit("statechange",this.state)},this._setLatencyHint(e.latencyHint),this.lookAhead=e.lookAhead}static getDefaults(){return{clockSource:"worker",latencyHint:"interactive",lookAhead:.1,updateInterval:.05}}initialize(){var e;return this._initialized||(e=this,Pp.forEach(t=>t(e)),this._initialized=!0),this}createAnalyser(){return this._context.createAnalyser()}createOscillator(){return this._context.createOscillator()}createBufferSource(){return this._context.createBufferSource()}createBiquadFilter(){return this._context.createBiquadFilter()}createBuffer(t,e,s){return this._context.createBuffer(t,e,s)}createChannelMerger(t){return this._context.createChannelMerger(t)}createChannelSplitter(t){return this._context.createChannelSplitter(t)}createConstantSource(){return this._context.createConstantSource()}createConvolver(){return this._context.createConvolver()}createDelay(t){return this._context.createDelay(t)}createDynamicsCompressor(){return this._context.createDynamicsCompressor()}createGain(){return this._context.createGain()}createIIRFilter(t,e){return this._context.createIIRFilter(t,e)}createPanner(){return this._context.createPanner()}createPeriodicWave(t,e,s){return this._context.createPeriodicWave(t,e,s)}createStereoPanner(){return this._context.createStereoPanner()}createWaveShaper(){return this._context.createWaveShaper()}createMediaStreamSource(t){return op(Sp(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamSource(t)}createMediaElementSource(t){return op(Sp(this._context),"Not available if OfflineAudioContext"),this._context.createMediaElementSource(t)}createMediaStreamDestination(){return op(Sp(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamDestination()}decodeAudioData(t){return this._context.decodeAudioData(t)}get currentTime(){return this._context.currentTime}get state(){return this._context.state}get sampleRate(){return this._context.sampleRate}get listener(){return this.initialize(),this._listener}set listener(t){op(!this._initialized,"The listener cannot be set after initialization."),this._listener=t}get transport(){return this.initialize(),this._transport}set transport(t){op(!this._initialized,"The transport cannot be set after initialization."),this._transport=t}get draw(){return this.initialize(),this._draw}set draw(t){op(!this._initialized,"Draw cannot be set after initialization."),this._draw=t}get destination(){return this.initialize(),this._destination}set destination(t){op(!this._initialized,"The destination cannot be set after initialization."),this._destination=t}createAudioWorkletNode(t,e){return s=this.rawContext,t=t,e=e,op(Ju(Wu),"This node only works in a secure context (https or localhost)"),new Wu(s,t,e);var s}addAudioWorkletModule(t,e){return yp(this,void 0,void 0,function*(){op(Ju(this.rawContext.audioWorklet),"AudioWorkletNode is only available in a secure context (https or localhost)"),this._workletModules.has(e)||this._workletModules.set(e,this.rawContext.audioWorklet.addModule(t)),yield this._workletModules.get(e)})}workletsAreReady(){return yp(this,void 0,void 0,function*(){const e=[];this._workletModules.forEach(t=>e.push(t)),yield Promise.all(e)})}get updateInterval(){return this._ticker.updateInterval}set updateInterval(t){this._ticker.updateInterval=t}get clockSource(){return this._ticker.type}set clockSource(t){this._ticker.type=t}get latencyHint(){return this._latencyHint}_setLatencyHint(t){let e=0;if(ip(this._latencyHint=t))switch(t){case"interactive":e=.1;break;case"playback":e=.5;break;case"balanced":e=.25}this.lookAhead=e,this.updateInterval=e/2}get rawContext(){return this._context}now(){return this._context.currentTime+this.lookAhead}immediate(){return this._context.currentTime}resume(){return Sp(this._context)?this._context.resume():Promise.resolve()}close(){return yp(this,void 0,void 0,function*(){var e;Sp(this._context)&&(yield this._context.close()),this._initialized&&(e=this,Lp.forEach(t=>t(e)))})}getConstant(e){if(this._constants.has(e))return this._constants.get(e);{const t=this._context.createBuffer(1,128,this._context.sampleRate),s=t.getChannelData(0);for(let t=0;tthis._constants[t].disconnect()),this}_timeoutLoop(){var t=this.now();let e=this._timeouts.peek();for(;this._timeouts.length&&e&&e.time<=t;)e.callback(),this._timeouts.shift(),e=this._timeouts.peek()}setTimeout(t,e){this._timeoutIds++;var s=this.now();return this._timeouts.add({callback:t,id:this._timeoutIds,time:s+e}),this._timeoutIds}clearTimeout(e){return this._timeouts.forEach(t=>{t.id===e&&this._timeouts.remove(t)}),this}clearInterval(t){return this.clearTimeout(t)}setInterval(e,s){const n=++this._timeoutIds,i=()=>{var t=this.now();this._timeouts.add({callback:()=>{e(),i()},id:n,time:t+s})};return i(),n}}function Gp(e,t){np(t)?t.forEach(t=>Gp(e,t)):Object.defineProperty(e,t,{enumerable:!0,writable:!1})}function Qp(e,t){np(t)?t.forEach(t=>Qp(e,t)):Object.defineProperty(e,t,{writable:!0})}const Zp=()=>{};class Xp extends Mp{constructor(){super(),this.name="ToneAudioBuffer",this.onload=Zp;var t=Cp(Xp.getDefaults(),arguments,["url","onload","onerror"]);this.reverse=t.reverse,this.onload=t.onload,t.url&&kp(t.url)||t.url instanceof Xp?this.set(t.url):ip(t.url)&&this.load(t.url).catch(t.onerror)}static getDefaults(){return{onerror:Zp,onload:Zp,reverse:!1}}get sampleRate(){return(this._buffer||Jp()).sampleRate}set(t){return t instanceof Xp?t.loaded?this._buffer=t.get():t.onload=()=>{this.set(t),this.onload(this)}:this._buffer=t,this._reversed&&this._reverse(),this}get(){return this._buffer}load(e){return yp(this,void 0,void 0,function*(){var t=Xp.load(e).then(t=>{this.set(t),this.onload(this)});Xp.downloads.push(t);try{yield t}finally{const e=Xp.downloads.indexOf(t);Xp.downloads.splice(e,1)}return this})}dispose(){return super.dispose(),this._buffer=void 0,this}fromArray(t){const e=np(t)&&0t/n),this.fromArray(e)}return this}toArray(e){if(tp(e))return this.getChannelData(e);if(1===this.numberOfChannels)return this.toArray(0);{const e=[];for(let t=0;tsetTimeout(t,1)))}})}render(e=!0){return yp(this,void 0,void 0,function*(){yield this.workletsAreReady(),yield this._renderClock(e);var t=yield this._context.startRendering();return new Xp(t)})}close(){return Promise.resolve()}}const $p=new class extends Bp{constructor(){super(...arguments),this.lookAhead=0,this.latencyHint=0,this.isOffline=!1}createAnalyser(){return{}}createOscillator(){return{}}createBufferSource(){return{}}createBiquadFilter(){return{}}createBuffer(t,e,s){return{}}createChannelMerger(t){return{}}createChannelSplitter(t){return{}}createConstantSource(){return{}}createConvolver(){return{}}createDelay(t){return{}}createDynamicsCompressor(){return{}}createGain(){return{}}createIIRFilter(t,e){return{}}createPanner(){return{}}createPeriodicWave(t,e,s){return{}}createStereoPanner(){return{}}createWaveShaper(){return{}}createMediaStreamSource(t){return{}}createMediaElementSource(t){return{}}createMediaStreamDestination(){return{}}decodeAudioData(t){return Promise.resolve({})}createAudioWorkletNode(t,e){return{}}get rawContext(){return{}}addAudioWorkletModule(t,e){return yp(this,void 0,void 0,function*(){return Promise.resolve()})}resume(){return Promise.resolve()}setTimeout(t,e){return 0}clearTimeout(t){return this}setInterval(t,e){return 0}clearInterval(t){return this}getConstant(t){return{}}get currentTime(){return 0}get state(){return{}}get sampleRate(){return 0}get listener(){return{}}get transport(){return{}}get draw(){return{}}set draw(t){}get destination(){return{}}set destination(t){}now(){return 0}immediate(){return 0}};let Hp=$p;function Jp(){return Hp===$p&&gp&&Kp(new Up),Hp}function Kp(t,e=!1){e&&Hp.dispose(),Hp=Sp(t)?new Up(t):Tp(t)?new Yp(t):t}if(mp&&!mp.TONE_SILENCE_LOGGING){let t="v";"dev"===s&&(t="");const e=` * Tone.js ${t}${s} * `;console.log(`%c${e}`,"background: #000; color: #fff")}function td(t){return Math.pow(10,t/20)}function ed(t){return Math.log(t)/Math.LN10*20}function sd(t){return Math.pow(2,t/12)}let nd=440;function id(t){return Math.round(rd(t))}function rd(t){return 69+12*Math.log2(t/nd)}function od(t){return nd*Math.pow(2,(t-69)/12)}class ad extends Mp{constructor(t,e,s){super(),this.defaultUnits="s",this._val=e,this._units=s,this.context=t,this._expressions=this._getExpressions()}_getExpressions(){return{hz:{method:t=>this._frequencyToUnits(parseFloat(t)),regexp:/^(\d+(?:\.\d+)?)hz$/i},i:{method:t=>this._ticksToUnits(parseInt(t,10)),regexp:/^(\d+)i$/i},m:{method:t=>this._beatsToUnits(parseInt(t,10)*this._getTimeSignature()),regexp:/^(\d+)m$/i},n:{method:(t,e)=>{t=parseInt(t,10),e="."===e?1.5:1;return 1===t?this._beatsToUnits(this._getTimeSignature())*e:this._beatsToUnits(4/t)*e},regexp:/^(\d+)n(\.?)$/i},number:{method:t=>this._expressions[this.defaultUnits].method.call(this,t),regexp:/^(\d+(?:\.\d+)?)$/},s:{method:t=>this._secondsToUnits(parseFloat(t)),regexp:/^(\d+(?:\.\d+)?)s$/},samples:{method:t=>parseInt(t,10)/this.context.sampleRate,regexp:/^(\d+)samples$/},t:{method:t=>{t=parseInt(t,10);return this._beatsToUnits(8/(3*Math.floor(t)))},regexp:/^(\d+)t$/i},tr:{method:(t,e,s)=>{let n=0;return t&&"0"!==t&&(n+=this._beatsToUnits(this._getTimeSignature()*parseFloat(t))),e&&"0"!==e&&(n+=this._beatsToUnits(parseFloat(e))),s&&"0"!==s&&(n+=this._beatsToUnits(parseFloat(s)/4)),n},regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?$/}}}valueOf(){if(this._val instanceof ad&&this.fromType(this._val),Hu(this._val))return this._noArg();if(ip(this._val)&&Hu(this._units)){for(const t in this._expressions)if(this._expressions[t].regexp.test(this._val.trim())){this._units=t;break}}else if(ep(this._val)){let t=0;for(const s in this._val){var e;Ju(this._val[s])&&(e=this._val[s],t+=new this.constructor(this.context,s).valueOf()*e)}return t}if(Ju(this._units)){const n=this._expressions[this._units],i=this._val.toString().trim().match(n.regexp);return i?n.method.apply(this,i.slice(1)):n.method.call(this,this._val)}return ip(this._val)?parseFloat(this._val):this._val}_frequencyToUnits(t){return 1/t}_beatsToUnits(t){return 60/this._getBpm()*t}_secondsToUnits(t){return t}_ticksToUnits(t){return t*this._beatsToUnits(1)/this._getPPQ()}_noArg(){return this._now()}_getBpm(){return this.context.transport.bpm.value}_getTimeSignature(){return this.context.transport.timeSignature}_getPPQ(){return this.context.transport.PPQ}fromType(t){switch(this._units=void 0,this.defaultUnits){case"s":this._val=t.toSeconds();break;case"i":this._val=t.toTicks();break;case"hz":this._val=t.toFrequency();break;case"midi":this._val=t.toMidi()}return this}toFrequency(){return 1/this.toSeconds()}toSamples(){return this.toSeconds()*this.context.sampleRate}toMilliseconds(){return 1e3*this.toSeconds()}}class hd extends ad{constructor(){super(...arguments),this.name="TimeClass"}_getExpressions(){return Object.assign(super._getExpressions(),{now:{method:t=>this._now()+new this.constructor(this.context,t).valueOf(),regexp:/^\+(.+)/},quantize:{method:t=>{t=new hd(this.context,t).valueOf();return this._secondsToUnits(this.context.transport.nextSubdivision(t))},regexp:/^@(.+)/}})}quantize(t,e=1){var s=new this.constructor(this.context,t).valueOf(),t=this.valueOf();return t+(Math.round(t/s)*s-t)*e}toNotation(){const s=this.toSeconds(),e=["1m"];for(let t=1;t<9;t++){const n=Math.pow(2,t);e.push(n+"n."),e.push(n+"n"),e.push(n+"t")}e.push("0");let n=e[0],i=new hd(this.context,e[0]).toSeconds();return e.forEach(t=>{var e=new hd(this.context,t).toSeconds();Math.abs(e-s)this.transpose(t))}toMidi(){return id(this.valueOf())}toNote(){var t=this.toFrequency(),t=Math.log2(t/cd.A4);let e=Math.round(12*t)+57;const s=Math.floor(e/12);return s<0&&(e+=-12*s),ud[e%12]+s.toString()}toSeconds(){return 1/super.toSeconds()}toTicks(){var t=this._beatsToUnits(1),t=this.valueOf()/t;return Math.floor(t*this._getPPQ())}_noArg(){return 0}_frequencyToUnits(t){return t}_ticksToUnits(t){return 1/(60*t/(this._getBpm()*this._getPPQ()))}_beatsToUnits(t){return 1/super._beatsToUnits(t)}_secondsToUnits(t){return 1/t}static mtof(t){return od(t)}static ftom(t){return id(t)}}const ld={cbbb:-3,cbb:-2,cb:-1,c:0,"c#":1,cx:2,"c##":2,"c###":3,"cx#":3,"c#x":3,dbbb:-1,dbb:0,db:1,d:2,"d#":3,dx:4,"d##":4,"d###":5,"dx#":5,"d#x":5,ebbb:1,ebb:2,eb:3,e:4,"e#":5,ex:6,"e##":6,"e###":7,"ex#":7,"e#x":7,fbbb:2,fbb:3,fb:4,f:5,"f#":6,fx:7,"f##":7,"f###":8,"fx#":8,"f#x":8,gbbb:4,gbb:5,gb:6,g:7,"g#":8,gx:9,"g##":9,"g###":10,"gx#":10,"g#x":10,abbb:6,abb:7,ab:8,a:9,"a#":10,ax:11,"a##":11,"a###":12,"ax#":12,"a#x":12,bbbb:8,bbb:9,bb:10,b:11,"b#":12,bx:13,"b##":13,"b###":14,"bx#":14,"b#x":14},ud=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];class pd extends hd{constructor(){super(...arguments),this.name="TransportTime"}_now(){return this.context.transport.seconds}}class dd extends Mp{constructor(){super();var t=Cp(dd.getDefaults(),arguments,["context"]);this.defaultContext?this.context=this.defaultContext:this.context=t.context}static getDefaults(){return{context:Jp()}}now(){return this.context.currentTime+this.context.lookAhead}immediate(){return this.context.currentTime}get sampleTime(){return 1/this.context.sampleRate}get blockTime(){return 128/this.context.sampleRate}toSeconds(t){return pp(t),new hd(this.context,t).toSeconds()}toFrequency(t){return new cd(this.context,t).toFrequency()}toTicks(t){return new pd(this.context,t).toTicks()}_getPartialProperties(e){const s=this.get();return Object.keys(s).forEach(t=>{Hu(e[t])&&delete s[t]}),s}get(){const s=this.constructor.getDefaults();return Object.keys(s).forEach(t=>{if(Reflect.has(this,t)){const e=this[t];Ju(e)&&Ju(e.value)&&Ju(e.setValueAtTime)?s[t]=e.value:e instanceof dd?s[t]=e._getPartialProperties(s[t]):np(e)||tp(e)||ip(e)||sp(e)?s[t]=e:delete s[t]}}),s}set(e){return Object.keys(e).forEach(t=>{Reflect.has(this,t)&&Ju(this[t])&&(this[t]&&Ju(this[t].value)&&Ju(this[t].setValueAtTime)?this[t].value!==e[t]&&(this[t].value=e[t]):this[t]instanceof dd?this[t].set(e[t]):this[t]=e[t])}),this}}class fd extends Np{constructor(t="stopped"){super(),this.name="StateTimeline",this._initial=t,this.setStateAtTime(this._initial,0)}getValueAtTime(t){t=this.get(t);return null!==t?t.state:this._initial}setStateAtTime(t,e,s){return ap(e,0),this.add(Object.assign({},s,{state:t,time:e})),this}getLastState(e,s){for(let t=this._search(s);0<=t;t--){const s=this._timeline[t];if(s.state===e)return s}}getNextState(e,t){const s=this._search(t);if(-1!==s)for(let t=s;t{"cancelScheduledValues"===t.type?e.cancelScheduledValues(t.time):"setTargetAtTime"===t.type?e.setTargetAtTime(t.value,t.time,t.constant):e[t.type](t.value,t.time)}),this}setParam(t){op(this._swappable,"The Param must be assigned as 'swappable' in the constructor");const e=this.input;return e.disconnect(this._param),this.apply(t),this._param=t,e.connect(this._param),this}dispose(){return super.dispose(),this._events.dispose(),this}get defaultValue(){return this._toType(this._param.defaultValue)}_exponentialApproach(t,e,s,n,i){return s+(e-s)*Math.exp(-(i-t)/n)}_linearInterpolate(t,e,s,n,i){return e+(i-t)/(s-t)*(n-e)}_exponentialInterpolate(t,e,s,n,i){return e*Math.pow(n/e,(i-t)/(s-t))}}class md extends dd{constructor(){super(...arguments),this._internalChannels=[]}get numberOfInputs(){return Ju(this.input)?wp(this.input)||this.input instanceof _d?1:this.input.numberOfInputs:0}get numberOfOutputs(){return Ju(this.output)?this.output.numberOfOutputs:0}_isAudioNode(t){return Ju(t)&&(t instanceof md||bp(t))}_getInternalNodes(){const t=this._internalChannels.slice(0);return this._isAudioNode(this.input)&&t.push(this.input),this._isAudioNode(this.output)&&this.input!==this.output&&t.push(this.output),t}_setChannelProperties(e){this._getInternalNodes().forEach(t=>{t.channelCount=e.channelCount,t.channelCountMode=e.channelCountMode,t.channelInterpretation=e.channelInterpretation})}_getChannelProperties(){var t=this._getInternalNodes();op(0this.connect(t)),this}dispose(){return super.dispose(),Ju(this.input)&&(this.input instanceof md?this.input.dispose():bp(this.input)&&this.input.disconnect()),Ju(this.output)&&(this.output instanceof md?this.output.dispose():bp(this.output)&&this.output.disconnect()),this._internalChannels=[],this}}function gd(...t){var e=t.shift();t.reduce((t,e)=>(t instanceof md?t.connect(e):bp(t)&&vd(t,e),e),e)}function vd(t,e,s=0,n=0){for(op(Ju(t),"Cannot connect from undefined node"),op(Ju(e),"Cannot connect to undefined node"),(e instanceof md||bp(e))&&op(0=this._startTime&&(-1===this._stopTime||t<=this._stopTime)?"started":"stopped"},this._fadeIn=t.fadeIn,this._fadeOut=t.fadeOut,this._curve=t.curve,this.onended=t.onended}static getDefaults(){return Object.assign(md.getDefaults(),{curve:"linear",fadeIn:0,fadeOut:0,onended:Zp})}_startGain(t,e=1){op(-1===this._startTime,"Source cannot be started more than once");var s=this.toSeconds(this._fadeIn);return this._startTime=t+s,this._startTime=Math.max(this._startTime,this.context.currentTime),0{var t="exponential"===this._curve?2*e:0;this._stopSource(this.now()+t),this._onended()},this._stopTime-this.context.currentTime),this}_onended(){var t;this.onended===Zp||(this.onended(this),this.onended=Zp,this.context.isOffline)||(t=()=>this.dispose(),void 0!==window.requestIdleCallback?window.requestIdleCallback(t):setTimeout(t,1e3))}get state(){return this.getStateAtTime(this.now())}cancelStop(){return this.log("cancelStop"),op(-1!==this._startTime,"Source is not started"),this._gainNode.gain.cancelScheduledValues(this._startTime+this.sampleTime),this.context.clearTimeout(this._timeout),this._stopTime=-1,this}dispose(){return super.dispose(),this._gainNode.dispose(),this.onended=Zp,this}}class bd extends wd{constructor(){super(Cp(bd.getDefaults(),arguments,["offset"])),this.name="ToneConstantSource",this._source=this.context.createConstantSource();var t=Cp(bd.getDefaults(),arguments,["offset"]);vd(this._source,this._gainNode),this.offset=new _d({context:this.context,convert:t.convert,param:this._source.offset,units:t.units,value:t.offset,minValue:t.minValue,maxValue:t.maxValue})}static getDefaults(){return Object.assign(wd.getDefaults(),{convert:!0,offset:1,units:"number"})}start(t){t=this.toSeconds(t);return this.log("start",t),this._startGain(t),this._source.start(t),this}_stopSource(t){this._source.stop(t)}dispose(){return super.dispose(),"started"===this.state&&this.stop(),this._source.disconnect(),this.offset.dispose(),this}}class Td extends md{constructor(){super(Cp(Td.getDefaults(),arguments,["value","units"])),this.name="Signal",this.override=!0;var t=Cp(Td.getDefaults(),arguments,["value","units"]);this.output=this._constantSource=new bd({context:this.context,convert:t.convert,offset:t.value,units:t.units,minValue:t.minValue,maxValue:t.maxValue}),this._constantSource.start(0),this.input=this._param=this._constantSource.offset}static getDefaults(){return Object.assign(md.getDefaults(),{convert:!0,units:"number",value:0})}connect(t,e=0,s=0){return Sd(this,t,e,s),this}dispose(){return super.dispose(),this._param.dispose(),this._constantSource.dispose(),this}setValueAtTime(t,e){return this._param.setValueAtTime(t,e),this}getValueAtTime(t){return this._param.getValueAtTime(t)}setRampPoint(t){return this._param.setRampPoint(t),this}linearRampToValueAtTime(t,e){return this._param.linearRampToValueAtTime(t,e),this}exponentialRampToValueAtTime(t,e){return this._param.exponentialRampToValueAtTime(t,e),this}exponentialRampTo(t,e,s){return this._param.exponentialRampTo(t,e,s),this}linearRampTo(t,e,s){return this._param.linearRampTo(t,e,s),this}targetRampTo(t,e,s){return this._param.targetRampTo(t,e,s),this}exponentialApproachValueAtTime(t,e,s){return this._param.exponentialApproachValueAtTime(t,e,s),this}setTargetAtTime(t,e,s){return this._param.setTargetAtTime(t,e,s),this}setValueCurveAtTime(t,e,s,n){return this._param.setValueCurveAtTime(t,e,s,n),this}cancelScheduledValues(t){return this._param.cancelScheduledValues(t),this}cancelAndHoldAtTime(t){return this._param.cancelAndHoldAtTime(t),this}rampTo(t,e,s){return this._param.rampTo(t,e,s),this}get value(){return this._param.value}set value(t){this._param.value=t}get convert(){return this._param.convert}set convert(t){this._param.convert=t}get units(){return this._param.units}get overridden(){return this._param.overridden}set overridden(t){this._param.overridden=t}get maxValue(){return this._param.maxValue}get minValue(){return this._param.minValue}apply(t){return this._param.apply(t),this}}function Sd(t,e,s,n){(e instanceof _d||wp(e)||e instanceof Td&&e.override)&&(e.cancelScheduledValues(0),e.setValueAtTime(0,0),e instanceof Td&&(e.overridden=!0)),vd(t,e,s,n)}class kd extends _d{constructor(){super(Cp(kd.getDefaults(),arguments,["value"])),this.name="TickParam",this._events=new Np(1/0),this._multiplier=1;var t=Cp(kd.getDefaults(),arguments,["value"]);this._multiplier=t.multiplier,this._events.cancel(0),this._events.add({ticks:0,time:0,type:"setValueAtTime",value:this._fromType(t.value)}),this.setValueAtTime(t.value,0)}static getDefaults(){return Object.assign(_d.getDefaults(),{multiplier:1,units:"hertz",value:1})}setTargetAtTime(t,e,s){e=this.toSeconds(e),this.setRampPoint(e);const n=this._fromType(t),i=this._events.get(e),r=Math.round(Math.max(1/s,1));for(let t=0;t<=r;t++){const r=s*t+e,o=this._exponentialApproach(i.time,i.value,n,s,r);this.linearRampToValueAtTime(this._toType(o),r)}return this}setValueAtTime(t,e){var s=this.toSeconds(e);super.setValueAtTime(t,e);const n=this._events.get(s),i=this._events.previousEvent(n),r=this._getTicksUntilEvent(i,s);return n.ticks=Math.max(r,0),this}linearRampToValueAtTime(t,e){var s=this.toSeconds(e);super.linearRampToValueAtTime(t,e);const n=this._events.get(s),i=this._events.previousEvent(n),r=this._getTicksUntilEvent(i,s);return n.ticks=Math.max(r,0),this}exponentialRampToValueAtTime(t,e){e=this.toSeconds(e);const s=this._fromType(t),n=this._events.get(e),i=Math.round(Math.max(10*(e-n.time),1)),r=(e-n.time)/i;for(let t=0;t<=i;t++){const i=r*t+n.time,o=this._exponentialInterpolate(n.time,n.value,e,s,i);this.linearRampToValueAtTime(this._toType(o),i)}return this}_getTicksUntilEvent(t,e){if(null===t)t={ticks:0,time:0,type:"setValueAtTime",value:0};else if(Hu(t.ticks)){const e=this._events.previousEvent(t);t.ticks=this._getTicksUntilEvent(e,t.time)}var s=this._fromType(this.getValueAtTime(t.time));let n=this._fromType(this.getValueAtTime(e));var i=this._events.get(e);return i&&i.time===e&&"setValueAtTime"===i.type&&(n=this._fromType(this.getValueAtTime(e-this.sampleTime))),.5*(e-t.time)*(s+n)+t.ticks}getTicksAtTime(t){var e=this.toSeconds(t),t=this._events.get(e);return Math.max(this._getTicksUntilEvent(t,e),0)}getDurationOfTicks(t,e){var s=this.toSeconds(e),e=this.getTicksAtTime(e);return this.getTimeOfTick(e+t)-s}getTimeOfTick(t){var e=this._events.get(t,"ticks"),s=this._events.getAfter(t,"ticks");if(e&&e.ticks===t)return e.time;if(e&&s&&"linearRampToValueAtTime"===s.type&&e.value!==s.value){var n=this._fromType(this.getValueAtTime(e.time)),i=(this._fromType(this.getValueAtTime(s.time))-n)/(s.time-e.time),r=Math.sqrt(Math.pow(n,2)-2*i*(e.ticks-t)),s=(-n+r)/i;return(0{let e=r.time;var s=this._tickOffset.get(t.time);s&&s.time>=r.time&&(o=s.ticks,e=s.time),"started"===r.state&&"started"!==t.state&&(o+=this.frequency.getTicksAtTime(t.time)-this.frequency.getTicksAtTime(e),t.time!=i.time&&(a={state:t.state,time:t.time,ticks:o})),r=t}),this._state.remove(i),a&&this._ticksAtTime.add(a),o}get ticks(){return this.getTicksAtTime(this.now())}set ticks(t){this.setTicksAtTime(t,this.now())}get seconds(){return this.getSecondsAtTime(this.now())}set seconds(t){var e=this.now(),t=this.frequency.timeToTicks(t,e);this.setTicksAtTime(t,e)}getSecondsAtTime(t){t=this.toSeconds(t);const e=this._state.getLastState("stopped",t),n={state:"paused",time:t};this._state.add(n);var s=this._secondsAtTime.get(t);let i=s||e,r=s?s.seconds:0,o=null;return this._state.forEachBetween(i.time,t+this.sampleTime,t=>{let e=i.time;var s=this._tickOffset.get(t.time);s&&s.time>=i.time&&(r=s.seconds,e=s.time),"started"===i.state&&"started"!==t.state&&(r+=t.time-e,t.time!=n.time&&(o={state:t.state,time:t.time,seconds:r})),i=t}),this._state.remove(n),o&&this._secondsAtTime.add(o),r}setTicksAtTime(t,e){return e=this.toSeconds(e),this._tickOffset.cancel(e),this._tickOffset.add({seconds:this.frequency.getDurationOfTicks(t,e),ticks:t,time:e}),this._ticksAtTime.cancel(e),this._secondsAtTime.cancel(e),this}getStateAtTime(t){return t=this.toSeconds(t),this._state.getValueAtTime(t)}getTimeOfTick(t,e=this.now()){var s=this._tickOffset.get(e),e=this._state.get(e),e=Math.max(s.time,e.time),s=this.frequency.getTicksAtTime(e)+t-s.ticks;return this.frequency.getTimeOfTick(s)}forEachTickBetween(s,n,i){let r=this._state.get(s);this._state.forEachBetween(s,n,t=>{r&&"started"===r.state&&"started"!==t.state&&this.forEachTickBetween(Math.max(r.time,s),t.time-this.sampleTime,i),r=t});let o=null;if(r&&"started"===r.state){var a=Math.max(r.time,s),h=this.frequency.getTicksAtTime(a),a=h-this.frequency.getTicksAtTime(r.time);let t=Math.ceil(a)-a;t=Ip(t,1)?0:t;let e=this.frequency.getTimeOfTick(h+t);for(;e{switch(t.state){case"started":var e=this._tickSource.getTicksAtTime(t.time);this.emit("start",t.time,e);break;case"stopped":0!==t.time&&this.emit("stop",t.time);break;case"paused":this.emit("pause",t.time)}}),this._tickSource.forEachTickBetween(t,e,(t,e)=>{this.callback(t,e)}))}getStateAtTime(t){t=this.toSeconds(t);return this._state.getValueAtTime(t)}dispose(){return super.dispose(),this.context.off("tick",this._boundLoop),this._tickSource.dispose(),this._state.dispose(),this}}Wp.mixin(Dd);class Od extends md{constructor(){super(Cp(Od.getDefaults(),arguments,["delayTime","maxDelay"])),this.name="Delay";var t=Cp(Od.getDefaults(),arguments,["delayTime","maxDelay"]),e=this.toSeconds(t.maxDelay);this._maxDelay=Math.max(e,this.toSeconds(t.delayTime)),this._delayNode=this.input=this.output=this.context.createDelay(e),this.delayTime=new _d({context:this.context,param:this._delayNode.delayTime,units:"time",value:t.delayTime,minValue:0,maxValue:this.maxDelay}),Gp(this,"delayTime")}static getDefaults(){return Object.assign(md.getDefaults(),{delayTime:0,maxDelay:1})}get maxDelay(){return this._maxDelay}dispose(){return super.dispose(),this._delayNode.disconnect(),this.delayTime.dispose(),this}}class Md extends Mp{constructor(){super(),this.name="ToneAudioBuffers",this._buffers=new Map,this._loadingCount=0;const s=Cp(Md.getDefaults(),arguments,["urls","onload","baseUrl"],"urls");this.baseUrl=s.baseUrl,Object.keys(s.urls).forEach(t=>{this._loadingCount++;var e=s.urls[t];this.add(t,e,this._bufferLoaded.bind(this,s.onload),s.onerror)})}static getDefaults(){return{baseUrl:"",onerror:Zp,onload:Zp,urls:{}}}has(t){return this._buffers.has(t.toString())}get(t){return op(this.has(t),`ToneAudioBuffers has no buffer named: ${t}`),this._buffers.get(t.toString())}_bufferLoaded(t){this._loadingCount--,0===this._loadingCount&&t&&t()}get loaded(){return Array.from(this._buffers).every(([,t])=>t.loaded)}add(t,e,s=Zp,n=Zp){return ip(e)?(this.baseUrl&&"data:audio/"===e.trim().substring(0,11).toLowerCase()&&(this.baseUrl=""),this._buffers.set(t.toString(),new Xp(this.baseUrl+e,s,n))):this._buffers.set(t.toString(),new Xp(e,s,n)),this}dispose(){return super.dispose(),this._buffers.forEach(t=>t.dispose()),this._buffers.clear(),this}}class Ed extends cd{constructor(){super(...arguments),this.name="MidiClass",this.defaultUnits="midi"}_frequencyToUnits(t){return id(super._frequencyToUnits(t))}_ticksToUnits(t){return id(super._ticksToUnits(t))}_beatsToUnits(t){return id(super._beatsToUnits(t))}_secondsToUnits(t){return id(super._secondsToUnits(t))}toMidi(){return this.valueOf()}toFrequency(){return od(this.toMidi())}transpose(t){return new Ed(this.context,this.toMidi()+t)}}class Rd extends pd{constructor(){super(...arguments),this.name="Ticks",this.defaultUnits="i"}_now(){return this.context.transport.ticks}_beatsToUnits(t){return this._getPPQ()*t}_secondsToUnits(t){return Math.floor(t/(60/this._getBpm())*this._getPPQ())}_ticksToUnits(t){return t}toTicks(){return this.valueOf()}toSeconds(){return this.valueOf()/this._getPPQ()*(60/this._getBpm())}}class qd extends dd{constructor(){super(...arguments),this.name="Draw",this.expiration=.25,this.anticipation=.008,this._events=new Np,this._boundDrawLoop=this._drawLoop.bind(this),this._animationFrame=-1}schedule(t,e){return this._events.add({callback:t,time:this.toSeconds(e)}),1===this._events.length&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop)),this}cancel(t){return this._events.cancel(this.toSeconds(t)),this}_drawLoop(){for(var t=this.context.currentTime;this._events.length&&this._events.peek().time-this.anticipation<=t;){const e=this._events.shift();e&&t-e.time<=this.expiration&&e.callback()}0{t.draw=new qd({context:t})}),zp(t=>{t.draw.dispose()});class Fd extends Mp{constructor(){super(...arguments),this.name="IntervalTimeline",this._root=null,this._length=0}add(t){op(Ju(t.time),"Events must have a time property"),op(Ju(t.duration),"Events must have a duration parameter"),t.time=t.time.valueOf();let e=new Id(t.time,t.time+t.duration,t);for(null===this._root?this._root=e:this._root.insert(e),this._length++;null!==e;)e.updateHeight(),e.updateMax(),this._rebalance(e),e=e.parent;return this}remove(t){if(null!==this._root){var e=[];this._root.search(t.time,e);for(const s of e)if(s.event===t){this._removeNode(s),this._length--;break}}return this}get length(){return this._length}cancel(t){return this.forEachFrom(t,t=>this.remove(t)),this}_setRoot(t){this._root=t,null!==this._root&&(this._root.parent=null)}_replaceNodeInParent(t,e){null!==t.parent?(t.isLeftChild()?t.parent.left=e:t.parent.right=e,this._rebalance(t.parent)):this._setRoot(e)}_removeNode(s){if(null===s.left&&null===s.right)this._replaceNodeInParent(s,null);else if(null===s.right)this._replaceNodeInParent(s,s.left);else if(null===s.left)this._replaceNodeInParent(s,s.right);else{let t,e=null;if(0e.low&&(e=s[t]);return e.event}}return null}forEach(e){if(null!==this._root){const s=[];this._root.traverse(t=>s.push(t)),s.forEach(t=>{t.event&&e(t.event)})}return this}forEachAtTime(t,e){if(null!==this._root){const s=[];this._root.search(t,s),s.forEach(t=>{t.event&&e(t.event)})}return this}forEachFrom(t,e){if(null!==this._root){const s=[];this._root.searchAfter(t,s),s.forEach(t=>{t.event&&e(t.event)})}return this}dispose(){return super.dispose(),null!==this._root&&this._root.traverse(t=>t.dispose()),this._root=null,this}}class Id{constructor(t,e,s){this._left=null,this._right=null,this.parent=null,this.height=0,this.event=s,this.low=t,this.high=e,this.max=this.high}insert(t){t.low<=this.low?null===this.left?this.left=t:this.left.insert(t):null===this.right?this.right=t:this.right.insert(t)}search(t,e){t>this.max||(null!==this.left&&this.left.search(t,e),this.low<=t&&this.high>t&&e.push(this),this.low>t||null!==this.right&&this.right.search(t,e))}searchAfter(t,e){this.low>=t&&(e.push(this),null!==this.left&&this.left.searchAfter(t,e)),null!==this.right&&this.right.searchAfter(t,e)}traverse(t){t(this),null!==this.left&&this.left.traverse(t),null!==this.right&&this.right.traverse(t)}updateHeight(){null!==this.left&&null!==this.right?this.height=Math.max(this.left.height,this.right.height)+1:null!==this.right?this.height=this.right.height+1:null!==this.left?this.height=this.left.height+1:this.height=0}updateMax(){this.max=this.high,null!==this.left&&(this.max=Math.max(this.max,this.left.max)),null!==this.right&&(this.max=Math.max(this.max,this.right.max))}getBalance(){let t=0;return null!==this.left&&null!==this.right?t=this.left.height-this.right.height:null!==this.left?t=this.left.height+1:null!==this.right&&(t=-(this.right.height+1)),t}isLeftChild(){return null!==this.parent&&this.parent.left===this}get left(){return this._left}set left(t){null!==(this._left=t)&&(t.parent=this),this.updateHeight(),this.updateMax()}get right(){return this._right}set right(t){null!==(this._right=t)&&(t.parent=this),this.updateHeight(),this.updateMax()}dispose(){this.parent=null,this._left=null,this._right=null,this.event=null}}class Vd extends md{constructor(){super(Cp(Vd.getDefaults(),arguments,["volume"])),this.name="Volume";var t=Cp(Vd.getDefaults(),arguments,["volume"]);this.input=this.output=new xd({context:this.context,gain:t.volume,units:"decibels"}),this.volume=this.output.gain,Gp(this,"volume"),this._unmutedVolume=t.volume,this.mute=t.mute}static getDefaults(){return Object.assign(md.getDefaults(),{mute:!1,volume:0})}get mute(){return this.volume.value===-1/0}set mute(t){!this.mute&&t?(this._unmutedVolume=this.volume.value,this.volume.value=-1/0):this.mute&&!t&&(this.volume.value=this._unmutedVolume)}dispose(){return super.dispose(),this.input.dispose(),this.volume.dispose(),this}}class Nd extends md{constructor(){super(Cp(Nd.getDefaults(),arguments)),this.name="Destination",this.input=new Vd({context:this.context}),this.output=new xd({context:this.context}),this.volume=this.input.volume;var t=Cp(Nd.getDefaults(),arguments);gd(this.input,this.output,this.context.rawContext.destination),this.mute=t.mute,this._internalChannels=[this.input,this.context.rawContext.destination,this.output]}static getDefaults(){return Object.assign(md.getDefaults(),{mute:!1,volume:0})}get mute(){return this.input.mute}set mute(t){this.input.mute=t}chain(...t){return this.input.disconnect(),t.unshift(this.input),t.push(this.output),gd(...t),this}get maxChannelCount(){return this.context.rawContext.destination.maxChannelCount}dispose(){return super.dispose(),this.volume.dispose(),this}}jp(t=>{t.destination=new Nd({context:t})}),zp(t=>{t.destination.dispose()});class Pd extends Mp{constructor(t){super(),this.name="TimelineValue",this._timeline=new Np({memory:10}),this._initialValue=t}set(t,e){return this._timeline.add({value:t,time:e}),this}get(t){t=this._timeline.get(t);return t?t.value:this._initialValue}}class jd{constructor(t,e){this.id=jd._eventId++,this._remainderTime=0;e=Object.assign(jd.getDefaults(),e);this.transport=t,this.callback=e.callback,this._once=e.once,this.time=Math.floor(e.time),this._remainderTime=e.time-this.time}static getDefaults(){return{callback:Zp,once:!1,time:0}}get floatTime(){return this.time+this._remainderTime}invoke(t){var e;this.callback&&(e=this.transport.bpm.getDurationOfTicks(1,t),this.callback(t+this._remainderTime*e),this._once&&this.transport.clear(this.id))}dispose(){return this.callback=void 0,this}}jd._eventId=0;class Ld extends jd{constructor(t,e){super(t,e),this._currentId=-1,this._nextId=-1,this._nextTick=this.time,this._boundRestart=this._restart.bind(this);e=Object.assign(Ld.getDefaults(),e);this.duration=e.duration,this._interval=e.interval,this._nextTick=e.time,this.transport.on("start",this._boundRestart),this.transport.on("loopStart",this._boundRestart),this.transport.on("ticks",this._boundRestart),this.context=this.transport.context,this._restart()}static getDefaults(){return Object.assign({},jd.getDefaults(),{duration:1/0,interval:1,once:!1})}invoke(t){this._createEvents(t),super.invoke(t)}_createEvent(){return Fp(this._nextTick,this.floatTime+this.duration)?this.transport.scheduleOnce(this.invoke.bind(this),new Rd(this.context,this._nextTick).toSeconds()):-1}_createEvents(t){Fp(this._nextTick+this._interval,this.floatTime+this.duration)&&(this._nextTick+=this._interval,this._currentId=this._nextId,this._nextId=this.transport.scheduleOnce(this.invoke.bind(this),new Rd(this.context,this._nextTick).toSeconds()))}_restart(t){this.transport.clear(this._currentId),this.transport.clear(this._nextId),this._nextTick=this.floatTime;t=this.transport.getTicksAtTime(t);Rp(t,this.time)&&(this._nextTick=this.floatTime+Math.ceil((t-this.floatTime)/this._interval)*this._interval),this._currentId=this._createEvent(),this._nextTick+=this._interval,this._nextId=this._createEvent()}dispose(){return super.dispose(),this.transport.clear(this._currentId),this.transport.clear(this._nextId),this.transport.off("start",this._boundRestart),this.transport.off("loopStart",this._boundRestart),this.transport.off("ticks",this._boundRestart),this}}class zd extends dd{constructor(){super(Cp(zd.getDefaults(),arguments)),this.name="Transport",this._loop=new Pd(!1),this._loopStart=0,this._loopEnd=0,this._scheduledEvents={},this._timeline=new Np,this._repeatedEvents=new Fd,this._syncedSignals=[],this._swingAmount=0;var t=Cp(zd.getDefaults(),arguments);this._ppq=t.ppq,this._clock=new Dd({callback:this._processTick.bind(this),context:this.context,frequency:0,units:"bpm"}),this._bindClockEvents(),this.bpm=this._clock.frequency,this._clock.frequency.multiplier=t.ppq,this.bpm.setValueAtTime(t.bpm,0),Gp(this,"bpm"),this._timeSignature=t.timeSignature,this._swingTicks=t.ppq/2}static getDefaults(){return Object.assign(dd.getDefaults(),{bpm:120,loopEnd:"4m",loopStart:0,ppq:192,swing:0,swingSubdivision:"8n",timeSignature:4})}_processTick(e,t){var s;this._loop.get(e)&&t>=this._loopEnd&&(this.emit("loopEnd",e),this._clock.setTicksAtTime(this._loopStart,e),t=this._loopStart,this.emit("loopStart",e,this._clock.getSecondsAtTime(e)),this.emit("loop",e)),0t.invoke(e)),up(!1)}schedule(t,e){e=new jd(this,{callback:t,time:new pd(this.context,e).toTicks()});return this._addEvent(e,this._timeline)}scheduleRepeat(t,e,s,n=1/0){s=new Ld(this,{callback:t,duration:new hd(this.context,n).toTicks(),interval:new hd(this.context,e).toTicks(),time:new pd(this.context,s).toTicks()});return this._addEvent(s,this._repeatedEvents)}scheduleOnce(t,e){e=new jd(this,{callback:t,once:!0,time:new pd(this.context,e).toTicks()});return this._addEvent(e,this._timeline)}clear(t){if(this._scheduledEvents.hasOwnProperty(t)){const e=this._scheduledEvents[t.toString()];e.timeline.remove(e.event),e.event.dispose(),delete this._scheduledEvents[t.toString()]}return this}_addEvent(t,e){return this._scheduledEvents[t.id.toString()]={event:t,timeline:e},e.add(t),t.id}cancel(t=0){t=this.toTicks(t);return this._timeline.forEachFrom(t,t=>this.clear(t.id)),this._repeatedEvents.forEachFrom(t,t=>this.clear(t.id)),this}_bindClockEvents(){this._clock.on("start",(t,e)=>{e=new Rd(this.context,e).toSeconds(),this.emit("start",t,e)}),this._clock.on("stop",t=>{this.emit("stop",t)}),this._clock.on("pause",t=>{this.emit("pause",t)})}get state(){return this._clock.getStateAtTime(this.now())}start(t,e){let s;return this.context.resume(),Ju(e)&&(s=this.toTicks(e)),this._clock.start(t,s),this}stop(t){return this._clock.stop(t),this}pause(t){return this._clock.pause(t),this}toggle(t){return t=this.toSeconds(t),"started"!==this._clock.getStateAtTime(t)?this.start(t):this.stop(t),this}get timeSignature(){return this._timeSignature}set timeSignature(t){np(t)&&(t=t[0]/t[1]*4),this._timeSignature=t}get loopStart(){return new hd(this.context,this._loopStart,"i").toSeconds()}set loopStart(t){this._loopStart=this.toTicks(t)}get loopEnd(){return new hd(this.context,this._loopEnd,"i").toSeconds()}set loopEnd(t){this._loopEnd=this.toTicks(t)}get loop(){return this._loop.get(this.now())}set loop(t){this._loop.set(t,this.now())}setLoopPoints(t,e){return this.loopStart=t,this.loopEnd=e,this}get swing(){return this._swingAmount}set swing(t){this._swingAmount=t}get swingSubdivision(){return new Rd(this.context,this._swingTicks).toNotation()}set swingSubdivision(t){this._swingTicks=this.toTicks(t)}get position(){var t=this.now(),t=this._clock.getTicksAtTime(t);return new Rd(this.context,t).toBarsBeatsSixteenths()}set position(t){t=this.toTicks(t);this.ticks=t}get seconds(){return this._clock.seconds}set seconds(t){var e=this.now(),e=this._clock.frequency.timeToTicks(t,e);this.ticks=e}get progress(){if(this.loop){var t=this.now();return(this._clock.getTicksAtTime(t)-this._loopStart)/(this._loopEnd-this._loopStart)}return 0}get ticks(){return this._clock.ticks}set ticks(t){var e,s;this._clock.ticks!==t&&(e=this.now(),"started"===this.state?(s=this._clock.getTicksAtTime(e),s=e+this._clock.frequency.getDurationOfTicks(Math.ceil(s)-s,e),this.emit("stop",s),this._clock.setTicksAtTime(t,s),this.emit("start",s,this._clock.getSecondsAtTime(s))):(this.emit("ticks",e),this._clock.setTicksAtTime(t,e)))}getTicksAtTime(t){return this._clock.getTicksAtTime(t)}getSecondsAtTime(t){return this._clock.getSecondsAtTime(t)}get PPQ(){return this._clock.frequency.multiplier}set PPQ(t){this._clock.frequency.multiplier=t}nextSubdivision(t){if(t=this.toTicks(t),"started"!==this.state)return 0;var e=this.now(),t=t-this.getTicksAtTime(e)%t;return this._clock.nextTickTime(t,e)}syncSignal(t,e){if(!e){const n=this.now();var s;e=0!==t.getValueAtTime(n)?(s=1/(60/this.bpm.getValueAtTime(n)/this.PPQ),t.getValueAtTime(n)/s):0}const n=new xd(e);return this.bpm.connect(n),n.connect(t._param),this._syncedSignals.push({initial:t.value,ratio:n,signal:t}),t.value=0,this}unsyncSignal(e){for(let t=this._syncedSignals.length-1;0<=t;t--){const s=this._syncedSignals[t];s.signal===e&&(s.ratio.dispose(),s.signal.value=s.initial,this._syncedSignals.splice(t,1))}return this}dispose(){return super.dispose(),this._clock.dispose(),Qp(this,"bpm"),this._timeline.dispose(),this._repeatedEvents.dispose(),this}}Wp.mixin(zd),jp(t=>{t.transport=new zd({context:t})}),zp(t=>{t.transport.dispose()});class Wd extends md{constructor(t){super(t),this.input=void 0,this._state=new fd("stopped"),this._synced=!1,this._scheduled=[],this._syncedStart=Zp,this._syncedStop=Zp,this._state.memory=100,this._state.increasing=!0,this._volume=this.output=new Vd({context:this.context,mute:t.mute,volume:t.volume}),this.volume=this._volume.volume,Gp(this,"volume"),this.onstop=t.onstop}static getDefaults(){return Object.assign(md.getDefaults(),{mute:!1,onstop:Zp,volume:0})}get state(){return this._synced?"started"===this.context.transport.state?this._state.getValueAtTime(this.context.transport.seconds):"stopped":this._state.getValueAtTime(this.now())}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}_clampToCurrentTime(t){return this._synced?t:Math.max(t,this.context.currentTime)}start(t,e,s){var n=Hu(t)&&this._synced?this.context.transport.seconds:this.toSeconds(t),n=this._clampToCurrentTime(n);if(this._synced||"started"!==this._state.getValueAtTime(n))if(this.log("start",n),this._state.setStateAtTime("started",n),this._synced){const i=this._state.get(n);i&&(i.offset=this.toSeconds(Dp(e,0)),i.duration=s?this.toSeconds(s):void 0);t=this.context.transport.schedule(t=>{this._start(t,e,s)},n);this._scheduled.push(t),"started"===this.context.transport.state&&this.context.transport.getSecondsAtTime(this.immediate())>n&&this._syncedStart(this.now(),this.context.transport.seconds)}else hp(this.context),this._start(n,e,s);else op(Rp(n,this._state.get(n).time),"Start time must be strictly greater than previous start time"),this._state.cancel(n),this._state.setStateAtTime("started",n),this.log("restart",n),this.restart(n,e,s);return this}stop(t){t=Hu(t)&&this._synced?this.context.transport.seconds:this.toSeconds(t),t=this._clampToCurrentTime(t);if("started"===this._state.getValueAtTime(t)||Ju(this._state.getNextState("started",t))){if(this.log("stop",t),this._synced){const e=this.context.transport.schedule(this._stop.bind(this),t);this._scheduled.push(e)}else this._stop(t);this._state.cancel(t),this._state.setStateAtTime("stopped",t)}return this}restart(t,e,s){return t=this.toSeconds(t),"started"===this._state.getValueAtTime(t)&&(this._state.cancel(t),this._restart(t,e,s)),this}sync(){return this._synced||(this._synced=!0,this._syncedStart=(e,s)=>{if(Rp(s,0)){var n=this._state.get(s);if(n&&"started"===n.state&&n.time!==s){s=s-this.toSeconds(n.time);let t;n.duration&&(t=this.toSeconds(n.duration)-s),this._start(e,this.toSeconds(n.offset)+s,t)}}},this._syncedStop=t=>{var e=this.context.transport.getSecondsAtTime(Math.max(t-this.sampleTime,0));"started"===this._state.getValueAtTime(e)&&this._stop(t)},this.context.transport.on("start",this._syncedStart),this.context.transport.on("loopStart",this._syncedStart),this.context.transport.on("stop",this._syncedStop),this.context.transport.on("pause",this._syncedStop),this.context.transport.on("loopEnd",this._syncedStop)),this}unsync(){return this._synced&&(this.context.transport.off("stop",this._syncedStop),this.context.transport.off("pause",this._syncedStop),this.context.transport.off("loopEnd",this._syncedStop),this.context.transport.off("start",this._syncedStart),this.context.transport.off("loopStart",this._syncedStart)),this._synced=!1,this._scheduled.forEach(t=>this.context.transport.clear(t)),this._scheduled=[],this._state.cancel(0),this._stop(0),this}dispose(){return super.dispose(),this.onstop=Zp,this.unsync(),this._volume.dispose(),this._state.dispose(),this}}class Bd extends wd{constructor(){super(Cp(Bd.getDefaults(),arguments,["url","onload"])),this.name="ToneBufferSource",this._source=this.context.createBufferSource(),this._internalChannels=[this._source],this._sourceStarted=!1,this._sourceStopped=!1;var t=Cp(Bd.getDefaults(),arguments,["url","onload"]);vd(this._source,this._gainNode),this._source.onended=()=>this._stopSource(),this.playbackRate=new _d({context:this.context,param:this._source.playbackRate,units:"positive",value:t.playbackRate}),this.loop=t.loop,this.loopStart=t.loopStart,this.loopEnd=t.loopEnd,this._buffer=new Xp(t.url,t.onload,t.onerror),this._internalChannels.push(this._source)}static getDefaults(){return Object.assign(wd.getDefaults(),{url:new Xp,loop:!1,loopEnd:0,loopStart:0,onload:Zp,onerror:Zp,playbackRate:1})}get fadeIn(){return this._fadeIn}set fadeIn(t){this._fadeIn=t}get fadeOut(){return this._fadeOut}set fadeOut(t){this._fadeOut=t}get curve(){return this._curve}set curve(t){this._curve=t}start(t,e,s,n=1){op(this.buffer.loaded,"buffer is either not set or not loaded");t=this.toSeconds(t);this._startGain(t,n),e=this.loop?Dp(e,this.loopStart):Dp(e,0);let i=Math.max(this.toSeconds(e),0);if(this.loop){const r=this.toSeconds(this.loopEnd)||this.buffer.duration,e=this.toSeconds(this.loopStart),o=r-e;qp(i,r)&&(i=(i-e)%o+e),Ip(i,this.buffer.duration)&&(i=0)}return this._source.buffer=this.buffer.get(),this._source.loopEnd=this.toSeconds(this.loopEnd)||this.buffer.duration,Fp(i,this.buffer.duration)&&(this._sourceStarted=!0,this._source.start(t,i)),Ju(s)&&(s=this.toSeconds(s),s=Math.max(s,0),this.stop(t+s)),this}_stopSource(t){!this._sourceStopped&&this._sourceStarted&&(this._sourceStopped=!0,this._source.stop(this.toSeconds(t)),this._onended())}get loopStart(){return this._source.loopStart}set loopStart(t){this._source.loopStart=this.toSeconds(t)}get loopEnd(){return this._source.loopEnd}set loopEnd(t){this._source.loopEnd=this.toSeconds(t)}get buffer(){return this._buffer}set buffer(t){this._buffer.set(t)}get loop(){return this._source.loop}set loop(t){this._source.loop=t,this._sourceStarted&&this.cancelStop()}dispose(){return super.dispose(),this._source.onended=null,this._source.disconnect(),this._buffer.dispose(),this.playbackRate.dispose(),this}}class Ud extends Wd{constructor(){super(Cp(Ud.getDefaults(),arguments,["type"])),this.name="Noise",this._source=null;var t=Cp(Ud.getDefaults(),arguments,["type"]);this._playbackRate=t.playbackRate,this.type=t.type,this._fadeIn=t.fadeIn,this._fadeOut=t.fadeOut}static getDefaults(){return Object.assign(Wd.getDefaults(),{fadeIn:0,fadeOut:0,playbackRate:1,type:"white"})}get type(){return this._type}set type(t){if(op(t in Zd,"Noise: invalid type: "+t),this._type!==t&&(this._type=t,"started"===this.state)){const t=this.now();this._stop(t),this._start(t)}}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._source&&(this._source.playbackRate.value=t)}_start(t){var e=Zd[this._type];this._source=new Bd({url:e,context:this.context,fadeIn:this._fadeIn,fadeOut:this._fadeOut,loop:!0,onended:()=>this.onstop(this),playbackRate:this._playbackRate}).connect(this.output),this._source.start(this.toSeconds(t),Math.random()*(e.duration-.001))}_stop(t){this._source&&(this._source.stop(this.toSeconds(t)),this._source=null)}get fadeIn(){return this._fadeIn}set fadeIn(t){this._fadeIn=t,this._source&&(this._source.fadeIn=this._fadeIn)}get fadeOut(){return this._fadeOut}set fadeOut(t){this._fadeOut=t,this._source&&(this._source.fadeOut=this._fadeOut)}_restart(t){this._stop(t),this._start(t)}dispose(){return super.dispose(),this._source&&this._source.disconnect(),this}}const Gd=220500,Qd={brown:null,pink:null,white:null},Zd={get brown(){if(!Qd.brown){const n=[];for(let t=0;t<2;t++){const i=new Float32Array(Gd);n[t]=i;let e=0;for(let t=0;tt.label===n||t.deviceId===n),!this._device&&0{t.stop()}),this._stream=void 0,this._mediaStream.disconnect(),this._mediaStream=void 0),this._device=void 0,this}static enumerateDevices(){return yp(this,void 0,void 0,function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter(t=>"audioinput"===t.kind)})}get state(){return this._stream&&this._stream.active?"started":"stopped"}get deviceId(){return this._device?this._device.deviceId:void 0}get groupId(){return this._device?this._device.groupId:void 0}get label(){return this._device?this._device.label:void 0}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}dispose(){return super.dispose(),this.close(),this._volume.dispose(),this.volume.dispose(),this}static get supported(){return Ju(navigator.mediaDevices)&&Ju(navigator.mediaDevices.getUserMedia)}}function Yd(s,n){return yp(this,void 0,void 0,function*(){const t=n/s.context.sampleRate,e=new Yp(1,t,s.context.sampleRate);return new s.constructor(Object.assign(s.get(),{frequency:2/t,detune:0,context:e})).toDestination().start(0),(yield e.render()).getChannelData(0)})}class $d extends wd{constructor(){super(Cp($d.getDefaults(),arguments,["frequency","type"])),this.name="ToneOscillatorNode",this._oscillator=this.context.createOscillator(),this._internalChannels=[this._oscillator];var t=Cp($d.getDefaults(),arguments,["frequency","type"]);vd(this._oscillator,this._gainNode),this.type=t.type,this.frequency=new _d({context:this.context,param:this._oscillator.frequency,units:"frequency",value:t.frequency}),this.detune=new _d({context:this.context,param:this._oscillator.detune,units:"cents",value:t.detune}),Gp(this,["frequency","detune"])}static getDefaults(){return Object.assign(wd.getDefaults(),{detune:0,frequency:440,type:"sine"})}start(t){t=this.toSeconds(t);return this.log("start",t),this._startGain(t),this._oscillator.start(t),this}_stopSource(t){this._oscillator.stop(t)}setPeriodicWave(t){return this._oscillator.setPeriodicWave(t),this}get type(){return this._oscillator.type}set type(t){this._oscillator.type=t}dispose(){return super.dispose(),"started"===this.state&&this.stop(),this._oscillator.disconnect(),this.frequency.dispose(),this.detune.dispose(),this}}class Hd extends Wd{constructor(){super(Cp(Hd.getDefaults(),arguments,["frequency","type"])),this.name="Oscillator",this._oscillator=null;const t=Cp(Hd.getDefaults(),arguments,["frequency","type"]);this.frequency=new Td({context:this.context,units:"frequency",value:t.frequency}),Gp(this,"frequency"),this.detune=new Td({context:this.context,units:"cents",value:t.detune}),Gp(this,"detune"),this._partials=t.partials,this._partialCount=t.partialCount,this._type=t.type,t.partialCount&&"custom"!==t.type&&(this._type=this.baseType+t.partialCount.toString()),this.phase=t.phase}static getDefaults(){return Object.assign(Wd.getDefaults(),{detune:0,frequency:440,partialCount:0,partials:[],phase:0,type:"sine"})}_start(t){var e=this.toSeconds(t),t=new $d({context:this.context,onended:()=>this.onstop(this)});this._oscillator=t,this._wave?this._oscillator.setPeriodicWave(this._wave):this._oscillator.type=this._type,this._oscillator.connect(this.output),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.start(e)}_stop(t){t=this.toSeconds(t);this._oscillator&&this._oscillator.stop(t)}_restart(t){t=this.toSeconds(t);return this.log("restart",t),this._oscillator&&this._oscillator.cancelStop(),this._state.cancel(t),this}syncFrequency(){return this.context.transport.syncSignal(this.frequency),this}unsyncFrequency(){return this.context.transport.unsyncSignal(this.frequency),this}_getCachedPeriodicWave(){if("custom"===this._type)return Hd._periodicWaveCache.find(t=>{return t.phase===this._phase&&(t=t.partials,s=this._partials,t.length===s.length&&t.every((t,e)=>s[e]===t));var s});var t=Hd._periodicWaveCache.find(t=>t.type===this._type&&t.phase===this._phase);return this._partialCount=t?t.partialCount:this._partialCount,t}get type(){return this._type}set type(t){this._type=t;const e=-1!==["sine","square","sawtooth","triangle"].indexOf(t);if(0===this._phase&&e)this._wave=void 0,this._partialCount=0,null!==this._oscillator&&(this._oscillator.type=t);else{const e=this._getCachedPeriodicWave();if(Ju(e)){const{partials:t,wave:s}=e;this._wave=s,this._partials=t,null!==this._oscillator&&this._oscillator.setPeriodicWave(this._wave)}else{const[e,n]=this._getRealImaginary(t,this._phase),i=this.context.createPeriodicWave(e,n);this._wave=i,null!==this._oscillator&&this._oscillator.setPeriodicWave(this._wave),Hd._periodicWaveCache.push({imag:n,partialCount:this._partialCount,partials:this._partials,phase:this._phase,real:e,type:this._type,wave:this._wave}),100s[e]=t),this._partials=Array.from(s),this.type=this._type}}_getRealImaginary(s,n){let i=2048;const r=new Float32Array(i),o=new Float32Array(i);let a=1;if("custom"===s){if(a=this._partials.length+1,this._partialCount=this._partials.length,i=a,0===this._partials.length)return[r,o]}else{const n=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(s);n?(a=parseInt(n[2],10)+1,this._partialCount=parseInt(n[2],10),s=n[1],a=Math.max(a,2),i=a):this._partialCount=0,this._partials=[]}for(let e=1;e>1&1?-1:1):0,this._partials[e-1]=t;break;case"custom":t=this._partials[e-1];break;default:throw new TypeError("Oscillator: invalid type: "+s)}0!==t?(r[e]=-t*Math.sin(n*e),o[e]=t*Math.cos(n*e)):(r[e]=0,o[e]=0)}return[r,o]}_inverseFFT(e,s,n){let i=0;var r=e.length;for(let t=0;tt.includes(e)),"oversampling must be either 'none', '2x', or '4x'"),this._shaper.oversample=e}dispose(){return super.dispose(),this._shaper.disconnect(),this}}class tf extends Jd{constructor(){super(...arguments),this.name="AudioToGain",this._norm=new Kd({context:this.context,mapping:t=>(t+1)/2}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class ef extends Td{constructor(){super(Object.assign(Cp(ef.getDefaults(),arguments,["value"]))),this.name="Multiply",this.override=!1;var t=Cp(ef.getDefaults(),arguments,["value"]);this._mult=this.input=this.output=new xd({context:this.context,minValue:t.minValue,maxValue:t.maxValue}),this.factor=this._param=this._mult.gain,this.factor.setValueAtTime(t.value,0)}static getDefaults(){return Object.assign(Td.getDefaults(),{value:0})}dispose(){return super.dispose(),this._mult.dispose(),this}}class sf extends Wd{constructor(){super(Cp(sf.getDefaults(),arguments,["frequency","type","modulationType"])),this.name="AMOscillator",this._modulationScale=new tf({context:this.context}),this._modulationNode=new xd({context:this.context});var t=Cp(sf.getDefaults(),arguments,["frequency","type","modulationType"]);this._carrier=new Hd({context:this.context,detune:t.detune,frequency:t.frequency,onstop:()=>this.onstop(this),phase:t.phase,type:t.type}),this.frequency=this._carrier.frequency,this.detune=this._carrier.detune,this._modulator=new Hd({context:this.context,phase:t.phase,type:t.modulationType}),this.harmonicity=new ef({context:this.context,units:"positive",value:t.harmonicity}),this.frequency.chain(this.harmonicity,this._modulator.frequency),this._modulator.chain(this._modulationScale,this._modulationNode.gain),this._carrier.chain(this._modulationNode,this.output),Gp(this,["frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(Hd.getDefaults(),{harmonicity:1,modulationType:"square"})}_start(t){this._modulator.start(t),this._carrier.start(t)}_stop(t){this._modulator.stop(t),this._carrier.stop(t)}_restart(t){this._modulator.restart(t),this._carrier.restart(t)}get type(){return this._carrier.type}set type(t){this._carrier.type=t}get baseType(){return this._carrier.baseType}set baseType(t){this._carrier.baseType=t}get partialCount(){return this._carrier.partialCount}set partialCount(t){this._carrier.partialCount=t}get modulationType(){return this._modulator.type}set modulationType(t){this._modulator.type=t}get phase(){return this._carrier.phase}set phase(t){this._carrier.phase=t,this._modulator.phase=t}get partials(){return this._carrier.partials}set partials(t){this._carrier.partials=t}asArray(t=1024){return yp(this,void 0,void 0,function*(){return Yd(this,t)})}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this._modulationScale.dispose(),this}}class nf extends Wd{constructor(){super(Cp(nf.getDefaults(),arguments,["frequency","type","modulationType"])),this.name="FMOscillator",this._modulationNode=new xd({context:this.context,gain:0});var t=Cp(nf.getDefaults(),arguments,["frequency","type","modulationType"]);this._carrier=new Hd({context:this.context,detune:t.detune,frequency:0,onstop:()=>this.onstop(this),phase:t.phase,type:t.type}),this.detune=this._carrier.detune,this.frequency=new Td({context:this.context,units:"frequency",value:t.frequency}),this._modulator=new Hd({context:this.context,phase:t.phase,type:t.modulationType}),this.harmonicity=new ef({context:this.context,units:"positive",value:t.harmonicity}),this.modulationIndex=new ef({context:this.context,units:"positive",value:t.modulationIndex}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.frequency.chain(this.modulationIndex,this._modulationNode),this._modulator.connect(this._modulationNode.gain),this._modulationNode.connect(this._carrier.frequency),this._carrier.connect(this.output),this.detune.connect(this._modulator.detune),Gp(this,["modulationIndex","frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(Hd.getDefaults(),{harmonicity:1,modulationIndex:2,modulationType:"square"})}_start(t){this._modulator.start(t),this._carrier.start(t)}_stop(t){this._modulator.stop(t),this._carrier.stop(t)}_restart(t){return this._modulator.restart(t),this._carrier.restart(t),this}get type(){return this._carrier.type}set type(t){this._carrier.type=t}get baseType(){return this._carrier.baseType}set baseType(t){this._carrier.baseType=t}get partialCount(){return this._carrier.partialCount}set partialCount(t){this._carrier.partialCount=t}get modulationType(){return this._modulator.type}set modulationType(t){this._modulator.type=t}get phase(){return this._carrier.phase}set phase(t){this._carrier.phase=t,this._modulator.phase=t}get partials(){return this._carrier.partials}set partials(t){this._carrier.partials=t}asArray(t=1024){return yp(this,void 0,void 0,function*(){return Yd(this,t)})}dispose(){return super.dispose(),this.frequency.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this.modulationIndex.dispose(),this}}class rf extends Wd{constructor(){super(Cp(rf.getDefaults(),arguments,["frequency","width"])),this.name="PulseOscillator",this._widthGate=new xd({context:this.context,gain:0}),this._thresh=new Kd({context:this.context,mapping:t=>t<=0?-1:1});var t=Cp(rf.getDefaults(),arguments,["frequency","width"]);this.width=new Td({context:this.context,units:"audioRange",value:t.width}),this._triangle=new Hd({context:this.context,detune:t.detune,frequency:t.frequency,onstop:()=>this.onstop(this),phase:t.phase,type:"triangle"}),this.frequency=this._triangle.frequency,this.detune=this._triangle.detune,this._triangle.chain(this._thresh,this.output),this.width.chain(this._widthGate,this._thresh),Gp(this,["width","frequency","detune"])}static getDefaults(){return Object.assign(Wd.getDefaults(),{detune:0,frequency:440,phase:0,type:"pulse",width:.2})}_start(t){t=this.toSeconds(t),this._triangle.start(t),this._widthGate.gain.setValueAtTime(1,t)}_stop(t){t=this.toSeconds(t),this._triangle.stop(t),this._widthGate.gain.cancelScheduledValues(t),this._widthGate.gain.setValueAtTime(0,t)}_restart(t){this._triangle.restart(t),this._widthGate.gain.cancelScheduledValues(t),this._widthGate.gain.setValueAtTime(1,t)}get phase(){return this._triangle.phase}set phase(t){this._triangle.phase=t}get type(){return"pulse"}get baseType(){return"pulse"}get partials(){return[]}get partialCount(){return 0}set carrierType(t){this._triangle.type=t}asArray(t=1024){return yp(this,void 0,void 0,function*(){return Yd(this,t)})}dispose(){return super.dispose(),this._triangle.dispose(),this.width.dispose(),this._widthGate.dispose(),this._thresh.dispose(),this}}class of extends Wd{constructor(){super(Cp(of.getDefaults(),arguments,["frequency","type","spread"])),this.name="FatOscillator",this._oscillators=[];var t=Cp(of.getDefaults(),arguments,["frequency","type","spread"]);this.frequency=new Td({context:this.context,units:"frequency",value:t.frequency}),this.detune=new Td({context:this.context,units:"cents",value:t.detune}),this._spread=t.spread,this._type=t.type,this._phase=t.phase,this._partials=t.partials,this._partialCount=t.partialCount,this.count=t.count,Gp(this,["frequency","detune"])}static getDefaults(){return Object.assign(Hd.getDefaults(),{count:3,spread:20,type:"sawtooth"})}_start(e){e=this.toSeconds(e),this._forEach(t=>t.start(e))}_stop(e){e=this.toSeconds(e),this._forEach(t=>t.stop(e))}_restart(e){this._forEach(t=>t.restart(e))}_forEach(e){for(let t=0;tt.type=e)}get spread(){return this._spread}set spread(t){if(this._spread=t,1t.detune.value=s+n*e)}}get count(){return this._oscillators.length}set count(e){if(ap(e,1),this._oscillators.length!==e){this._forEach(t=>t.dispose()),this._oscillators=[];for(let t=0;tthis.onstop(this):Zp});"custom"===this.type&&(s.partials=this._partials),this.frequency.connect(s.frequency),this.detune.connect(s.detune),s.detune.overridden=!1,s.connect(this.output),this._oscillators[t]=s}this.spread=this._spread,"started"===this.state&&this._forEach(t=>t.start())}}get phase(){return this._phase}set phase(t){this._phase=t,this._forEach((t,e)=>t.phase=this._phase+e/this.count*360)}get baseType(){return this._oscillators[0].baseType}set baseType(e){this._forEach(t=>t.baseType=e),this._type=this._oscillators[0].type}get partials(){return this._oscillators[0].partials}set partials(e){this._partials=e,this._partialCount=this._partials.length,e.length&&(this._type="custom",this._forEach(t=>t.partials=e))}get partialCount(){return this._oscillators[0].partialCount}set partialCount(e){this._partialCount=e,this._forEach(t=>t.partialCount=e),this._type=this._oscillators[0].type}asArray(t=1024){return yp(this,void 0,void 0,function*(){return Yd(this,t)})}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this._forEach(t=>t.dispose()),this}}class af extends Wd{constructor(){super(Cp(af.getDefaults(),arguments,["frequency","modulationFrequency"])),this.name="PWMOscillator",this.sourceType="pwm",this._scale=new ef({context:this.context,value:2});var t=Cp(af.getDefaults(),arguments,["frequency","modulationFrequency"]);this._pulse=new rf({context:this.context,frequency:t.modulationFrequency}),this._pulse.carrierType="sine",this.modulationFrequency=this._pulse.frequency,this._modulator=new Hd({context:this.context,detune:t.detune,frequency:t.frequency,onstop:()=>this.onstop(this),phase:t.phase}),this.frequency=this._modulator.frequency,this.detune=this._modulator.detune,this._modulator.chain(this._scale,this._pulse.width),this._pulse.connect(this.output),Gp(this,["modulationFrequency","frequency","detune"])}static getDefaults(){return Object.assign(Wd.getDefaults(),{detune:0,frequency:440,modulationFrequency:.4,phase:0,type:"pwm"})}_start(t){t=this.toSeconds(t),this._modulator.start(t),this._pulse.start(t)}_stop(t){t=this.toSeconds(t),this._modulator.stop(t),this._pulse.stop(t)}_restart(t){this._modulator.restart(t),this._pulse.restart(t)}get type(){return"pwm"}get baseType(){return"pwm"}get partials(){return[]}get partialCount(){return 0}get phase(){return this._modulator.phase}set phase(t){this._modulator.phase=t}asArray(t=1024){return yp(this,void 0,void 0,function*(){return Yd(this,t)})}dispose(){return super.dispose(),this._pulse.dispose(),this._scale.dispose(),this._modulator.dispose(),this}}const hf={am:sf,fat:of,fm:nf,oscillator:Hd,pulse:rf,pwm:af};class cf extends Wd{constructor(){super(Cp(cf.getDefaults(),arguments,["frequency","type"])),this.name="OmniOscillator";var t=Cp(cf.getDefaults(),arguments,["frequency","type"]);this.frequency=new Td({context:this.context,units:"frequency",value:t.frequency}),this.detune=new Td({context:this.context,units:"cents",value:t.detune}),Gp(this,["frequency","detune"]),this.set(t)}static getDefaults(){return Object.assign(Hd.getDefaults(),nf.getDefaults(),sf.getDefaults(),of.getDefaults(),rf.getDefaults(),af.getDefaults())}_start(t){this._oscillator.start(t)}_stop(t){this._oscillator.stop(t)}_restart(t){return this._oscillator.restart(t),this}get type(){let t="";return["am","fm","fat"].some(t=>this._sourceType===t)&&(t=this._sourceType),t+this._oscillator.type}set type(t){"fm"===t.substr(0,2)?(this._createNewOscillator("fm"),this._oscillator=this._oscillator,this._oscillator.type=t.substr(2)):"am"===t.substr(0,2)?(this._createNewOscillator("am"),this._oscillator=this._oscillator,this._oscillator.type=t.substr(2)):"fat"===t.substr(0,3)?(this._createNewOscillator("fat"),this._oscillator=this._oscillator,this._oscillator.type=t.substr(3)):"pwm"===t?(this._createNewOscillator("pwm"),this._oscillator=this._oscillator):"pulse"===t?this._createNewOscillator("pulse"):(this._createNewOscillator("oscillator"),this._oscillator=this._oscillator,this._oscillator.type=t)}get partials(){return this._oscillator.partials}set partials(t){this._getOscType(this._oscillator,"pulse")||this._getOscType(this._oscillator,"pwm")||(this._oscillator.partials=t)}get partialCount(){return this._oscillator.partialCount}set partialCount(t){this._getOscType(this._oscillator,"pulse")||this._getOscType(this._oscillator,"pwm")||(this._oscillator.partialCount=t)}set(t){return Reflect.has(t,"type")&&t.type&&(this.type=t.type),super.set(t),this}_createNewOscillator(t){if(t!==this._sourceType){this._sourceType=t;const e=hf[t],s=this.now();if(this._oscillator){const t=this._oscillator;t.stop(s),this.context.setTimeout(()=>t.dispose(),this.blockTime)}this._oscillator=new e({context:this.context}),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.connect(this.output),this._oscillator.onstop=()=>this.onstop(this),"started"===this.state&&this._oscillator.start(s)}}get phase(){return this._oscillator.phase}set phase(t){this._oscillator.phase=t}get sourceType(){return this._sourceType}set sourceType(t){let e="sine";"pwm"!==this._oscillator.type&&"pulse"!==this._oscillator.type&&(e=this._oscillator.type),"fm"===t?this.type="fm"+e:"am"===t?this.type="am"+e:"fat"===t?this.type="fat"+e:"oscillator"===t?this.type=e:"pulse"===t?this.type="pulse":"pwm"===t&&(this.type="pwm")}_getOscType(t,e){return t instanceof hf[e]}get baseType(){return this._oscillator.baseType}set baseType(t){this._getOscType(this._oscillator,"pulse")||this._getOscType(this._oscillator,"pwm")||"pulse"===t||"pwm"===t||(this._oscillator.baseType=t)}get width(){return this._getOscType(this._oscillator,"pulse")?this._oscillator.width:void 0}get count(){return this._getOscType(this._oscillator,"fat")?this._oscillator.count:void 0}set count(t){this._getOscType(this._oscillator,"fat")&&tp(t)&&(this._oscillator.count=t)}get spread(){return this._getOscType(this._oscillator,"fat")?this._oscillator.spread:void 0}set spread(t){this._getOscType(this._oscillator,"fat")&&tp(t)&&(this._oscillator.spread=t)}get modulationType(){return this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am")?this._oscillator.modulationType:void 0}set modulationType(t){(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))&&ip(t)&&(this._oscillator.modulationType=t)}get modulationIndex(){return this._getOscType(this._oscillator,"fm")?this._oscillator.modulationIndex:void 0}get harmonicity(){return this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am")?this._oscillator.harmonicity:void 0}get modulationFrequency(){return this._getOscType(this._oscillator,"pwm")?this._oscillator.modulationFrequency:void 0}asArray(t=1024){return yp(this,void 0,void 0,function*(){return Yd(this,t)})}dispose(){return super.dispose(),this.detune.dispose(),this.frequency.dispose(),this._oscillator.dispose(),this}}class lf extends Td{constructor(){super(Object.assign(Cp(lf.getDefaults(),arguments,["value"]))),this.override=!1,this.name="Add",this._sum=new xd({context:this.context}),this.input=this._sum,this.output=this._sum,this.addend=this._param,gd(this._constantSource,this._sum)}static getDefaults(){return Object.assign(Td.getDefaults(),{value:0})}dispose(){return super.dispose(),this._sum.dispose(),this}}class uf extends Jd{constructor(){super(Object.assign(Cp(uf.getDefaults(),arguments,["min","max"]))),this.name="Scale";var t=Cp(uf.getDefaults(),arguments,["min","max"]);this._mult=this.input=new ef({context:this.context,value:t.max-t.min}),this._add=this.output=new lf({context:this.context,value:t.min}),this._min=t.min,this._max=t.max,this.input.connect(this.output)}static getDefaults(){return Object.assign(Jd.getDefaults(),{max:1,min:0})}get min(){return this._min}set min(t){this._min=t,this._setRange()}get max(){return this._max}set max(t){this._max=t,this._setRange()}_setRange(){this._add.value=this._min,this._mult.value=this._max-this._min}dispose(){return super.dispose(),this._add.dispose(),this._mult.dispose(),this}}class pf extends Jd{constructor(){super(Object.assign(Cp(pf.getDefaults(),arguments))),this.name="Zero",this._gain=new xd({context:this.context}),this.output=this._gain,this.input=void 0,vd(this.context.getConstant(0),this._gain)}dispose(){return super.dispose(),yd(this.context.getConstant(0),this._gain),this}}class df extends md{constructor(){super(Cp(df.getDefaults(),arguments,["frequency","min","max"])),this.name="LFO",this._stoppedValue=0,this._units="number",this.convert=!0,this._fromType=_d.prototype._fromType,this._toType=_d.prototype._toType,this._is=_d.prototype._is,this._clampValue=_d.prototype._clampValue;var t=Cp(df.getDefaults(),arguments,["frequency","min","max"]);this._oscillator=new Hd(t),this.frequency=this._oscillator.frequency,this._amplitudeGain=new xd({context:this.context,gain:t.amplitude,units:"normalRange"}),this.amplitude=this._amplitudeGain.gain,this._stoppedSignal=new Td({context:this.context,units:"audioRange",value:0}),this._zeros=new pf({context:this.context}),this._a2g=new tf({context:this.context}),this._scaler=this.output=new uf({context:this.context,max:t.max,min:t.min}),this.units=t.units,this.min=t.min,this.max=t.max,this._oscillator.chain(this._amplitudeGain,this._a2g,this._scaler),this._zeros.connect(this._a2g),this._stoppedSignal.connect(this._a2g),Gp(this,["amplitude","frequency"]),this.phase=t.phase}static getDefaults(){return Object.assign(Hd.getDefaults(),{amplitude:1,frequency:"4n",max:1,min:0,type:"sine",units:"number"})}start(t){return t=this.toSeconds(t),this._stoppedSignal.setValueAtTime(0,t),this._oscillator.start(t),this}stop(t){return t=this.toSeconds(t),this._stoppedSignal.setValueAtTime(this._stoppedValue,t),this._oscillator.stop(t),this}sync(){return this._oscillator.sync(),this._oscillator.syncFrequency(),this}unsync(){return this._oscillator.unsync(),this._oscillator.unsyncFrequency(),this}_setStoppedValue(){this._stoppedValue=this._oscillator.getInitialValue(),this._stoppedSignal.value=this._stoppedValue}get min(){return this._toType(this._scaler.min)}set min(t){t=this._fromType(t),this._scaler.min=t}get max(){return this._toType(this._scaler.max)}set max(t){t=this._fromType(t),this._scaler.max=t}get type(){return this._oscillator.type}set type(t){this._oscillator.type=t,this._setStoppedValue()}get partials(){return this._oscillator.partials}set partials(t){this._oscillator.partials=t,this._setStoppedValue()}get phase(){return this._oscillator.phase}set phase(t){this._oscillator.phase=t,this._setStoppedValue()}get units(){return this._units}set units(t){var e=this.min,s=this.max;this._units=t,this.min=e,this.max=s}get state(){return this._oscillator.state}connect(t,e,s){return(t instanceof _d||t instanceof Td)&&(this.convert=t.convert,this.units=t.units),Sd(this,t,e,s),this}dispose(){return super.dispose(),this._oscillator.dispose(),this._stoppedSignal.dispose(),this._zeros.dispose(),this._scaler.dispose(),this._a2g.dispose(),this._amplitudeGain.dispose(),this.amplitude.dispose(),this}}function ff(s,n=1/0){const i=new WeakMap;return function(t,e){Reflect.defineProperty(t,e,{configurable:!0,enumerable:!0,get:function(){return i.get(this)},set:function(t){ap(t,s,n),i.set(this,t)}})}}function _f(s,n=1/0){const i=new WeakMap;return function(t,e){Reflect.defineProperty(t,e,{configurable:!0,enumerable:!0,get:function(){return i.get(this)},set:function(t){ap(this.toSeconds(t),s,n),i.set(this,t)}})}}class mf extends Wd{constructor(){super(Cp(mf.getDefaults(),arguments,["url","onload"])),this.name="Player",this._activeSources=new Set;var t=Cp(mf.getDefaults(),arguments,["url","onload"]);this._buffer=new Xp({onload:this._onload.bind(this,t.onload),onerror:t.onerror,reverse:t.reverse,url:t.url}),this.autostart=t.autostart,this._loop=t.loop,this._loopStart=t.loopStart,this._loopEnd=t.loopEnd,this._playbackRate=t.playbackRate,this.fadeIn=t.fadeIn,this.fadeOut=t.fadeOut}static getDefaults(){return Object.assign(Wd.getDefaults(),{autostart:!1,fadeIn:0,fadeOut:0,loop:!1,loopEnd:0,loopStart:0,onload:Zp,onerror:Zp,playbackRate:1,reverse:!1})}load(t){return yp(this,void 0,void 0,function*(){return yield this._buffer.load(t),this._onload(),this})}_onload(t=Zp){t(),this.autostart&&this.start()}_onSourceEnd(t){this.onstop(this),this._activeSources.delete(t),0!==this._activeSources.size||this._synced||"started"!==this._state.getValueAtTime(this.now())||(this._state.cancel(this.now()),this._state.setStateAtTime("stopped",this.now()))}start(t,e,s){return super.start(t,e,s),this}_start(t,e,s){e=this._loop?Dp(e,this._loopStart):Dp(e,0);var n=this.toSeconds(e),e=s;s=Dp(s,Math.max(this._buffer.duration-n,0));s=this.toSeconds(s);s/=this._playbackRate,t=this.toSeconds(t);const i=new Bd({url:this._buffer,context:this.context,fadeIn:this.fadeIn,fadeOut:this.fadeOut,loop:this._loop,loopEnd:this._loopEnd,loopStart:this._loopStart,onended:this._onSourceEnd.bind(this),playbackRate:this._playbackRate}).connect(this.output);this._loop||this._synced||(this._state.cancel(t+s),this._state.setStateAtTime("stopped",t+s,{implicitEnd:!0})),this._activeSources.add(i),this._loop&&Hu(e)?i.start(t,n):i.start(t,n,s-this.toSeconds(this.fadeOut))}_stop(t){const e=this.toSeconds(t);this._activeSources.forEach(t=>t.stop(e))}restart(t,e,s){return super.restart(t,e,s),this}_restart(t,e,s){this._stop(t),this._start(t,e,s)}seek(t,e){e=this.toSeconds(e);if("started"===this._state.getValueAtTime(e)){const s=this.toSeconds(t);this._stop(e),this._start(e,s)}return this}setLoopPoints(t,e){return this.loopStart=t,this.loopEnd=e,this}get loopStart(){return this._loopStart}set loopStart(e){this._loopStart=e,this.buffer.loaded&&ap(this.toSeconds(e),0,this.buffer.duration),this._activeSources.forEach(t=>{t.loopStart=e})}get loopEnd(){return this._loopEnd}set loopEnd(e){this._loopEnd=e,this.buffer.loaded&&ap(this.toSeconds(e),0,this.buffer.duration),this._activeSources.forEach(t=>{t.loopEnd=e})}get buffer(){return this._buffer}set buffer(t){this._buffer.set(t)}get loop(){return this._loop}set loop(e){if(this._loop!==e&&(this._loop=e,this._activeSources.forEach(t=>{t.loop=e}),e)){const e=this._state.getNextState("stopped",this.now());e&&this._state.cancel(e.time)}}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e;const s=this.now(),t=this._state.getNextState("stopped",s);t&&t.implicitEnd&&(this._state.cancel(t.time),this._activeSources.forEach(t=>t.cancelStop())),this._activeSources.forEach(t=>{t.playbackRate.setValueAtTime(e,s)})}get reverse(){return this._buffer.reverse}set reverse(t){this._buffer.reverse=t}get loaded(){return this._buffer.loaded}dispose(){return super.dispose(),this._activeSources.forEach(t=>t.dispose()),this._activeSources.clear(),this._buffer.dispose(),this}}vp([_f(0)],mf.prototype,"fadeIn",void 0),vp([_f(0)],mf.prototype,"fadeOut",void 0);class gf extends md{constructor(){super(Cp(gf.getDefaults(),arguments,["urls","onload"],"urls")),this.name="Players",this.input=void 0,this._players=new Map;var t=Cp(gf.getDefaults(),arguments,["urls","onload"],"urls");this._volume=this.output=new Vd({context:this.context,volume:t.volume}),this.volume=this._volume.volume,Gp(this,"volume"),this._buffers=new Md({urls:t.urls,onload:t.onload,baseUrl:t.baseUrl,onerror:t.onerror}),this.mute=t.mute,this._fadeIn=t.fadeIn,this._fadeOut=t.fadeOut}static getDefaults(){return Object.assign(Wd.getDefaults(),{baseUrl:"",fadeIn:0,fadeOut:0,mute:!1,onload:Zp,onerror:Zp,urls:{},volume:0})}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}get fadeIn(){return this._fadeIn}set fadeIn(e){this._fadeIn=e,this._players.forEach(t=>{t.fadeIn=e})}get fadeOut(){return this._fadeOut}set fadeOut(e){this._fadeOut=e,this._players.forEach(t=>{t.fadeOut=e})}get state(){return Array.from(this._players).some(([,t])=>"started"===t.state)?"started":"stopped"}has(t){return this._buffers.has(t)}player(t){var e;return op(this.has(t),`No Player with the name ${t} exists on this object`),this._players.has(t)||(e=new mf({context:this.context,fadeIn:this._fadeIn,fadeOut:this._fadeOut,url:this._buffers.get(t)}).connect(this.output),this._players.set(t,e)),this._players.get(t)}get loaded(){return this._buffers.loaded}add(t,e,s){return op(!this._buffers.has(t),"A buffer with that name already exists on this object"),this._buffers.add(t,e,s),this}stopAll(e){return this._players.forEach(t=>t.stop(e)),this}dispose(){return super.dispose(),this._volume.dispose(),this.volume.dispose(),this._players.forEach(t=>t.dispose()),this._buffers.dispose(),this}}class vf extends Wd{constructor(){super(Cp(vf.getDefaults(),arguments,["url","onload"])),this.name="GrainPlayer",this._loopStart=0,this._loopEnd=0,this._activeSources=[];var t=Cp(vf.getDefaults(),arguments,["url","onload"]);this.buffer=new Xp({onload:t.onload,onerror:t.onerror,reverse:t.reverse,url:t.url}),this._clock=new Dd({context:this.context,callback:this._tick.bind(this),frequency:1/t.grainSize}),this._playbackRate=t.playbackRate,this._grainSize=t.grainSize,this._overlap=t.overlap,this.detune=t.detune,this.overlap=t.overlap,this.loop=t.loop,this.playbackRate=t.playbackRate,this.grainSize=t.grainSize,this.loopStart=t.loopStart,this.loopEnd=t.loopEnd,this.reverse=t.reverse,this._clock.on("stop",this._onstop.bind(this))}static getDefaults(){return Object.assign(Wd.getDefaults(),{onload:Zp,onerror:Zp,overlap:.1,grainSize:.2,playbackRate:1,detune:0,loop:!1,loopStart:0,loopEnd:0,reverse:!1})}_start(t,e,s){e=Dp(e,0),e=this.toSeconds(e),t=this.toSeconds(t);var n=1/this._clock.frequency.getValueAtTime(t);this._clock.start(t,e/n),s&&this.stop(t+this.toSeconds(s))}restart(t,e,s){return super.restart(t,e,s),this}_restart(t,e,s){this._stop(t),this._start(t,e,s)}_stop(t){this._clock.stop(t)}_onstop(e){this._activeSources.forEach(t=>{t.fadeOut=0,t.stop(e)}),this.onstop(this)}_tick(t){var e=this._clock.getTicksAtTime(t),s=e*this._grainSize;if(this.log("offset",s),!this.loop&&s>this.buffer.duration)this.stop(t);else{const n=s{var t=this._activeSources.indexOf(i);-1!==t&&this._activeSources.splice(t,1)}}}get playbackRate(){return this._playbackRate}set playbackRate(t){ap(t,.001),this._playbackRate=t,this.grainSize=this._grainSize}get loopStart(){return this._loopStart}set loopStart(t){this.buffer.loaded&&ap(this.toSeconds(t),0,this.buffer.duration),this._loopStart=this.toSeconds(t)}get loopEnd(){return this._loopEnd}set loopEnd(t){this.buffer.loaded&&ap(this.toSeconds(t),0,this.buffer.duration),this._loopEnd=this.toSeconds(t)}get reverse(){return this.buffer.reverse}set reverse(t){this.buffer.reverse=t}get grainSize(){return this._grainSize}set grainSize(t){this._grainSize=this.toSeconds(t),this._clock.frequency.setValueAtTime(this._playbackRate/this._grainSize,this.now())}get overlap(){return this._overlap}set overlap(t){t=this.toSeconds(t);ap(t,0),this._overlap=t}get loaded(){return this.buffer.loaded}dispose(){return super.dispose(),this.buffer.dispose(),this._clock.dispose(),this._activeSources.forEach(t=>t.dispose()),this}}class yf extends Jd{constructor(){super(...arguments),this.name="Abs",this._abs=new Kd({context:this.context,mapping:t=>Math.abs(t)<.001?0:Math.abs(t)}),this.input=this._abs,this.output=this._abs}dispose(){return super.dispose(),this._abs.dispose(),this}}class xf extends Jd{constructor(){super(...arguments),this.name="GainToAudio",this._norm=new Kd({context:this.context,mapping:t=>2*Math.abs(t)-1}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class wf extends Jd{constructor(){super(...arguments),this.name="Negate",this._multiply=new ef({context:this.context,value:-1}),this.input=this._multiply,this.output=this._multiply}dispose(){return super.dispose(),this._multiply.dispose(),this}}class bf extends Td{constructor(){super(Object.assign(Cp(bf.getDefaults(),arguments,["value"]))),this.override=!1,this.name="Subtract",this._sum=new xd({context:this.context}),this.input=this._sum,this.output=this._sum,this._neg=new wf({context:this.context}),this.subtrahend=this._param,gd(this._constantSource,this._neg,this._sum)}static getDefaults(){return Object.assign(Td.getDefaults(),{value:0})}dispose(){return super.dispose(),this._neg.dispose(),this._sum.dispose(),this}}class Tf extends Jd{constructor(){super(Object.assign(Cp(Tf.getDefaults(),arguments))),this.name="GreaterThanZero",this._thresh=this.output=new Kd({context:this.context,length:127,mapping:t=>t<=0?0:1}),this._scale=this.input=new ef({context:this.context,value:1e4}),this._scale.connect(this._thresh)}dispose(){return super.dispose(),this._scale.dispose(),this._thresh.dispose(),this}}class Sf extends Td{constructor(){super(Object.assign(Cp(Sf.getDefaults(),arguments,["value"]))),this.name="GreaterThan",this.override=!1;var t=Cp(Sf.getDefaults(),arguments,["value"]);this._subtract=this.input=new bf({context:this.context,value:t.value}),this._gtz=this.output=new Tf({context:this.context}),this.comparator=this._param=this._subtract.subtrahend,Gp(this,"comparator"),this._subtract.connect(this._gtz)}static getDefaults(){return Object.assign(Td.getDefaults(),{value:0})}dispose(){return super.dispose(),this._gtz.dispose(),this._subtract.dispose(),this.comparator.dispose(),this}}class kf extends Jd{constructor(){super(Object.assign(Cp(kf.getDefaults(),arguments,["value"]))),this.name="Pow";var t=Cp(kf.getDefaults(),arguments,["value"]);this._exponentScaler=this.input=this.output=new Kd({context:this.context,mapping:this._expFunc(t.value),length:8192}),this._exponent=t.value}static getDefaults(){return Object.assign(Jd.getDefaults(),{value:1})}_expFunc(e){return t=>Math.pow(Math.abs(t),e)}get value(){return this._exponent}set value(t){this._exponent=t,this._exponentScaler.setMap(this._expFunc(this._exponent))}dispose(){return super.dispose(),this._exponentScaler.dispose(),this}}class Af extends uf{constructor(){super(Object.assign(Cp(Af.getDefaults(),arguments,["min","max","exponent"]))),this.name="ScaleExp";var t=Cp(Af.getDefaults(),arguments,["min","max","exponent"]);this.input=this._exp=new kf({context:this.context,value:t.exponent}),this._exp.connect(this._mult)}static getDefaults(){return Object.assign(uf.getDefaults(),{exponent:1})}get exponent(){return this._exp.value}set exponent(t){this._exp.value=t}dispose(){return super.dispose(),this._exp.dispose(),this}}class Cf extends Td{constructor(){super(Cp(Td.getDefaults(),arguments,["value","units"])),this.name="SyncedSignal",this.override=!1;var t=Cp(Td.getDefaults(),arguments,["value","units"]);this._lastVal=t.value,this._synced=this.context.transport.scheduleRepeat(this._onTick.bind(this),"1i"),this._syncedCallback=this._anchorValue.bind(this),this.context.transport.on("start",this._syncedCallback),this.context.transport.on("pause",this._syncedCallback),this.context.transport.on("stop",this._syncedCallback),this._constantSource.disconnect(),this._constantSource.stop(0),this._constantSource=this.output=new bd({context:this.context,offset:t.value,units:t.units}).start(0),this.setValueAtTime(t.value,0)}_onTick(t){var e=super.getValueAtTime(this.context.transport.seconds);this._lastVal!==e&&(this._lastVal=e,this._constantSource.offset.setValueAtTime(e,t))}_anchorValue(t){var e=super.getValueAtTime(this.context.transport.seconds);this._lastVal=e,this._constantSource.offset.cancelAndHoldAtTime(t),this._constantSource.offset.setValueAtTime(e,t)}getValueAtTime(t){t=new pd(this.context,t).toSeconds();return super.getValueAtTime(t)}setValueAtTime(t,e){e=new pd(this.context,e).toSeconds();return super.setValueAtTime(t,e),this}linearRampToValueAtTime(t,e){e=new pd(this.context,e).toSeconds();return super.linearRampToValueAtTime(t,e),this}exponentialRampToValueAtTime(t,e){e=new pd(this.context,e).toSeconds();return super.exponentialRampToValueAtTime(t,e),this}setTargetAtTime(t,e,s){e=new pd(this.context,e).toSeconds();return super.setTargetAtTime(t,e,s),this}cancelScheduledValues(t){t=new pd(this.context,t).toSeconds();return super.cancelScheduledValues(t),this}setValueCurveAtTime(t,e,s,n){e=new pd(this.context,e).toSeconds();return s=this.toSeconds(s),super.setValueCurveAtTime(t,e,s,n),this}cancelAndHoldAtTime(t){t=new pd(this.context,t).toSeconds();return super.cancelAndHoldAtTime(t),this}setRampPoint(t){t=new pd(this.context,t).toSeconds();return super.setRampPoint(t),this}exponentialRampTo(t,e,s){s=new pd(this.context,s).toSeconds();return super.exponentialRampTo(t,e,s),this}linearRampTo(t,e,s){s=new pd(this.context,s).toSeconds();return super.linearRampTo(t,e,s),this}targetRampTo(t,e,s){s=new pd(this.context,s).toSeconds();return super.targetRampTo(t,e,s),this}dispose(){return super.dispose(),this.context.transport.clear(this._synced),this.context.transport.off("start",this._syncedCallback),this.context.transport.off("pause",this._syncedCallback),this.context.transport.off("stop",this._syncedCallback),this._constantSource.dispose(),this}}class Df extends md{constructor(){super(Cp(Df.getDefaults(),arguments,["attack","decay","sustain","release"])),this.name="Envelope",this._sig=new Td({context:this.context,value:0}),this.output=this._sig,this.input=void 0;var t=Cp(Df.getDefaults(),arguments,["attack","decay","sustain","release"]);this.attack=t.attack,this.decay=t.decay,this.sustain=t.sustain,this.release=t.release,this.attackCurve=t.attackCurve,this.releaseCurve=t.releaseCurve,this.decayCurve=t.decayCurve}static getDefaults(){return Object.assign(md.getDefaults(),{attack:.01,attackCurve:"linear",decay:.1,decayCurve:"exponential",release:1,releaseCurve:"exponential",sustain:.5})}get value(){return this.getValueAtTime(this.now())}_getCurve(e,s){if(ip(e))return e;{let t;for(t in Of)if(Of[t][s]===e)return t;return e}}_setCurve(t,e,s){if(ip(s)&&Reflect.has(Of,s)){var n=Of[s];ep(n)?"_decayCurve"!==t&&(this[t]=n[e]):this[t]=n}else{if(!np(s)||"_decayCurve"===t)throw new Error("Envelope: invalid curve: "+s);this[t]=s}}get attackCurve(){return this._getCurve(this._attackCurve,"In")}set attackCurve(t){this._setCurve("_attackCurve","In",t)}get releaseCurve(){return this._getCurve(this._releaseCurve,"Out")}set releaseCurve(t){this._setCurve("_releaseCurve","Out",t)}get decayCurve(){return this._decayCurve}set decayCurve(e){op(["linear","exponential"].some(t=>t===e),`Invalid envelope curve: ${e}`),this._decayCurve=e}triggerAttack(t,s=1){this.log("triggerAttack",t,s),t=this.toSeconds(t);let n=this.toSeconds(this.attack);const e=this.toSeconds(this.decay),i=this.getValueAtTime(t);if(0{const t=128;let e,s;const n=[];for(e=0;ethis._original_triggerRelease(t);var t=Cp(Mf.getDefaults(),arguments);this._volume=this.output=new Vd({context:this.context,volume:t.volume}),this.volume=this._volume.volume,Gp(this,"volume")}static getDefaults(){return Object.assign(md.getDefaults(),{volume:0})}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",0),this.context.transport.on("stop",this._syncedRelease),this.context.transport.on("pause",this._syncedRelease),this.context.transport.on("loopEnd",this._syncedRelease)),this}_syncState(){let t=!1;return this._synced||(this._synced=!0,t=!0),t}_syncMethod(t,s){const n=this["_original_"+t]=this[t];this[t]=(...e)=>{var t=e[s],t=this.context.transport.schedule(t=>{e[s]=t,n.apply(this,e)},t);this._scheduledEvents.push(t)}}unsync(){return this._scheduledEvents.forEach(t=>this.context.transport.clear(t)),this._scheduledEvents=[],this._synced&&(this._synced=!1,this.triggerAttack=this._original_triggerAttack,this.triggerRelease=this._original_triggerRelease,this.context.transport.off("stop",this._syncedRelease),this.context.transport.off("pause",this._syncedRelease),this.context.transport.off("loopEnd",this._syncedRelease)),this}triggerAttackRelease(t,e,s,n){s=this.toSeconds(s),e=this.toSeconds(e);return this.triggerAttack(t,s,n),this.triggerRelease(s+e),this}dispose(){return super.dispose(),this._volume.dispose(),this.unsync(),this._scheduledEvents=[],this}}class Ef extends Mf{constructor(){super(Cp(Ef.getDefaults(),arguments));var t=Cp(Ef.getDefaults(),arguments);this.portamento=t.portamento,this.onsilence=t.onsilence}static getDefaults(){return Object.assign(Mf.getDefaults(),{detune:0,onsilence:Zp,portamento:0})}triggerAttack(t,e,s=1){this.log("triggerAttack",t,e,s);e=this.toSeconds(e);return this._triggerEnvelopeAttack(e,s),this.setNote(t,e),this}triggerRelease(t){this.log("triggerRelease",t);t=this.toSeconds(t);return this._triggerEnvelopeRelease(t),this}setNote(t,e){e=this.toSeconds(e),t=t instanceof cd?t.toFrequency():t;if(0this.onsilence(this)},t.oscillator)),this.frequency=this.oscillator.frequency,this.detune=this.oscillator.detune,this.envelope=new Rf(Object.assign({context:this.context},t.envelope)),this.oscillator.chain(this.envelope,this.output),Gp(this,["oscillator","frequency","detune","envelope"])}static getDefaults(){return Object.assign(Ef.getDefaults(),{envelope:Object.assign(Op(Df.getDefaults(),Object.keys(md.getDefaults())),{attack:.005,decay:.1,release:1,sustain:.3}),oscillator:Object.assign(Op(cf.getDefaults(),[...Object.keys(Wd.getDefaults()),"frequency","detune"]),{type:"triangle"})})}_triggerEnvelopeAttack(t,e){if(this.envelope.triggerAttack(t,e),this.oscillator.start(t),0===this.envelope.sustain){const e=this.toSeconds(this.envelope.attack),s=this.toSeconds(this.envelope.decay);this.oscillator.stop(t+e+s)}}_triggerEnvelopeRelease(t){this.envelope.triggerRelease(t),this.oscillator.stop(t+this.toSeconds(this.envelope.release))}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}dispose(){return super.dispose(),this.oscillator.dispose(),this.envelope.dispose(),this}}class Ff extends Ef{constructor(){super(Cp(Ff.getDefaults(),arguments)),this.name="ModulationSynth";var t=Cp(Ff.getDefaults(),arguments);this._carrier=new qf({context:this.context,oscillator:t.oscillator,envelope:t.envelope,onsilence:()=>this.onsilence(this),volume:-10}),this._modulator=new qf({context:this.context,oscillator:t.modulation,envelope:t.modulationEnvelope,volume:-10}),this.oscillator=this._carrier.oscillator,this.envelope=this._carrier.envelope,this.modulation=this._modulator.oscillator,this.modulationEnvelope=this._modulator.envelope,this.frequency=new Td({context:this.context,units:"frequency"}),this.detune=new Td({context:this.context,value:t.detune,units:"cents"}),this.harmonicity=new ef({context:this.context,value:t.harmonicity,minValue:0}),this._modulationNode=new xd({context:this.context,gain:0}),Gp(this,["frequency","harmonicity","oscillator","envelope","modulation","modulationEnvelope","detune"])}static getDefaults(){return Object.assign(Ef.getDefaults(),{harmonicity:3,oscillator:Object.assign(Op(cf.getDefaults(),[...Object.keys(Wd.getDefaults()),"frequency","detune"]),{type:"sine"}),envelope:Object.assign(Op(Df.getDefaults(),Object.keys(md.getDefaults())),{attack:.01,decay:.01,sustain:1,release:.5}),modulation:Object.assign(Op(cf.getDefaults(),[...Object.keys(Wd.getDefaults()),"frequency","detune"]),{type:"square"}),modulationEnvelope:Object.assign(Op(Df.getDefaults(),Object.keys(md.getDefaults())),{attack:.5,decay:0,sustain:1,release:.5})})}_triggerEnvelopeAttack(t,e){this._carrier._triggerEnvelopeAttack(t,e),this._modulator._triggerEnvelopeAttack(t,e)}_triggerEnvelopeRelease(t){return this._carrier._triggerEnvelopeRelease(t),this._modulator._triggerEnvelopeRelease(t),this}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}dispose(){return super.dispose(),this._carrier.dispose(),this._modulator.dispose(),this.frequency.dispose(),this.detune.dispose(),this.harmonicity.dispose(),this._modulationNode.dispose(),this}}class If extends Ff{constructor(){super(Cp(If.getDefaults(),arguments)),this.name="AMSynth",this._modulationScale=new tf({context:this.context}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.detune.fan(this._carrier.detune,this._modulator.detune),this._modulator.chain(this._modulationScale,this._modulationNode.gain),this._carrier.chain(this._modulationNode,this.output)}dispose(){return super.dispose(),this._modulationScale.dispose(),this}}class Vf extends md{constructor(){super(Cp(Vf.getDefaults(),arguments,["frequency","type"])),this.name="BiquadFilter";var t=Cp(Vf.getDefaults(),arguments,["frequency","type"]);this._filter=this.context.createBiquadFilter(),this.input=this.output=this._filter,this.Q=new _d({context:this.context,units:"number",value:t.Q,param:this._filter.Q}),this.frequency=new _d({context:this.context,units:"frequency",value:t.frequency,param:this._filter.frequency}),this.detune=new _d({context:this.context,units:"cents",value:t.detune,param:this._filter.detune}),this.gain=new _d({context:this.context,units:"decibels",convert:!1,value:t.gain,param:this._filter.gain}),this.type=t.type}static getDefaults(){return Object.assign(md.getDefaults(),{Q:1,type:"lowpass",frequency:350,detune:0,gain:0})}get type(){return this._filter.type}set type(t){op(-1!==["lowpass","highpass","bandpass","lowshelf","highshelf","notch","allpass","peaking"].indexOf(t),`Invalid filter type: ${t}`),this._filter.type=t}getFrequencyResponse(e=128){const s=new Float32Array(e);for(let t=0;tt.type=e)}get rolloff(){return this._rolloff}set rolloff(t){const e=tp(t)?t:parseInt(t,10),s=[-12,-24,-48,-96];var n=s.indexOf(e);op(-1!==n,`rolloff can only be ${s.join(", ")}`),n+=1,this._rolloff=e,this.input.disconnect(),this._filters.forEach(t=>t.disconnect()),this._filters=new Array(n);for(let t=0;t1);return this._filters.forEach(()=>{e.getFrequencyResponse(t).forEach((t,e)=>s[e]*=t)}),e.dispose(),s}dispose(){return super.dispose(),this._filters.forEach(t=>{t.dispose()}),Qp(this,["detune","frequency","gain","Q"]),this.frequency.dispose(),this.Q.dispose(),this.detune.dispose(),this.gain.dispose(),this}}class Pf extends Df{constructor(){super(Cp(Pf.getDefaults(),arguments,["attack","decay","sustain","release"])),this.name="FrequencyEnvelope";var t=Cp(Pf.getDefaults(),arguments,["attack","decay","sustain","release"]);this._octaves=t.octaves,this._baseFrequency=this.toFrequency(t.baseFrequency),this._exponent=this.input=new kf({context:this.context,value:t.exponent}),this._scale=this.output=new uf({context:this.context,min:this._baseFrequency,max:this._baseFrequency*Math.pow(2,this._octaves)}),this._sig.chain(this._exponent,this._scale)}static getDefaults(){return Object.assign(Df.getDefaults(),{baseFrequency:200,exponent:1,octaves:4})}get baseFrequency(){return this._baseFrequency}set baseFrequency(t){t=this.toFrequency(t);ap(t,0),this._baseFrequency=t,this._scale.min=this._baseFrequency,this.octaves=this._octaves}get octaves(){return this._octaves}set octaves(t){this._octaves=t,this._scale.max=this._baseFrequency*Math.pow(2,t)}get exponent(){return this._exponent.value}set exponent(t){this._exponent.value=t}dispose(){return super.dispose(),this._exponent.dispose(),this._scale.dispose(),this}}class jf extends Ef{constructor(){super(Cp(jf.getDefaults(),arguments)),this.name="MonoSynth";var t=Cp(jf.getDefaults(),arguments);this.oscillator=new cf(Object.assign(t.oscillator,{context:this.context,detune:t.detune,onstop:()=>this.onsilence(this)})),this.frequency=this.oscillator.frequency,this.detune=this.oscillator.detune,this.filter=new Nf(Object.assign(t.filter,{context:this.context})),this.filterEnvelope=new Pf(Object.assign(t.filterEnvelope,{context:this.context})),this.envelope=new Rf(Object.assign(t.envelope,{context:this.context})),this.oscillator.chain(this.filter,this.envelope,this.output),this.filterEnvelope.connect(this.filter.frequency),Gp(this,["oscillator","frequency","detune","filter","filterEnvelope","envelope"])}static getDefaults(){return Object.assign(Ef.getDefaults(),{envelope:Object.assign(Op(Df.getDefaults(),Object.keys(md.getDefaults())),{attack:.005,decay:.1,release:1,sustain:.9}),filter:Object.assign(Op(Nf.getDefaults(),Object.keys(md.getDefaults())),{Q:1,rolloff:-12,type:"lowpass"}),filterEnvelope:Object.assign(Op(Pf.getDefaults(),Object.keys(md.getDefaults())),{attack:.6,baseFrequency:200,decay:.2,exponent:2,octaves:3,release:2,sustain:.5}),oscillator:Object.assign(Op(cf.getDefaults(),Object.keys(Wd.getDefaults())),{type:"sawtooth"})})}_triggerEnvelopeAttack(t,e=1){if(this.envelope.triggerAttack(t,e),this.filterEnvelope.triggerAttack(t),this.oscillator.start(t),0===this.envelope.sustain){const e=this.toSeconds(this.envelope.attack),s=this.toSeconds(this.envelope.decay);this.oscillator.stop(t+e+s)}}_triggerEnvelopeRelease(t){this.envelope.triggerRelease(t),this.filterEnvelope.triggerRelease(t),this.oscillator.stop(t+this.toSeconds(this.envelope.release))}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}dispose(){return super.dispose(),this.oscillator.dispose(),this.envelope.dispose(),this.filterEnvelope.dispose(),this.filter.dispose(),this}}class Lf extends Ef{constructor(){super(Cp(Lf.getDefaults(),arguments)),this.name="DuoSynth";var t=Cp(Lf.getDefaults(),arguments);this.voice0=new jf(Object.assign(t.voice0,{context:this.context,onsilence:()=>this.onsilence(this)})),this.voice1=new jf(Object.assign(t.voice1,{context:this.context})),this.harmonicity=new ef({context:this.context,units:"positive",value:t.harmonicity}),this._vibrato=new df({frequency:t.vibratoRate,context:this.context,min:-50,max:50}),this._vibrato.start(),this.vibratoRate=this._vibrato.frequency,this._vibratoGain=new xd({context:this.context,units:"normalRange",gain:t.vibratoAmount}),this.vibratoAmount=this._vibratoGain.gain,this.frequency=new Td({context:this.context,units:"frequency",value:440}),this.detune=new Td({context:this.context,units:"cents",value:t.detune}),this.frequency.connect(this.voice0.frequency),this.frequency.chain(this.harmonicity,this.voice1.frequency),this._vibrato.connect(this._vibratoGain),this._vibratoGain.fan(this.voice0.detune,this.voice1.detune),this.detune.fan(this.voice0.detune,this.voice1.detune),this.voice0.connect(this.output),this.voice1.connect(this.output),Gp(this,["voice0","voice1","frequency","vibratoAmount","vibratoRate"])}getLevelAtTime(t){return t=this.toSeconds(t),this.voice0.envelope.getValueAtTime(t)+this.voice1.envelope.getValueAtTime(t)}static getDefaults(){return Ap(Ef.getDefaults(),{vibratoAmount:.5,vibratoRate:5,harmonicity:1.5,voice0:Ap(Op(jf.getDefaults(),Object.keys(Ef.getDefaults())),{filterEnvelope:{attack:.01,decay:0,sustain:1,release:.5},envelope:{attack:.01,decay:0,sustain:1,release:.5}}),voice1:Ap(Op(jf.getDefaults(),Object.keys(Ef.getDefaults())),{filterEnvelope:{attack:.01,decay:0,sustain:1,release:.5},envelope:{attack:.01,decay:0,sustain:1,release:.5}})})}_triggerEnvelopeAttack(t,e){this.voice0._triggerEnvelopeAttack(t,e),this.voice1._triggerEnvelopeAttack(t,e)}_triggerEnvelopeRelease(t){return this.voice0._triggerEnvelopeRelease(t),this.voice1._triggerEnvelopeRelease(t),this}dispose(){return super.dispose(),this.voice0.dispose(),this.voice1.dispose(),this.frequency.dispose(),this.detune.dispose(),this._vibrato.dispose(),this.vibratoRate.dispose(),this._vibratoGain.dispose(),this.harmonicity.dispose(),this}}class zf extends Ff{constructor(){super(Cp(zf.getDefaults(),arguments)),this.name="FMSynth";var t=Cp(zf.getDefaults(),arguments);this.modulationIndex=new ef({context:this.context,value:t.modulationIndex}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.frequency.chain(this.modulationIndex,this._modulationNode),this.detune.fan(this._carrier.detune,this._modulator.detune),this._modulator.connect(this._modulationNode.gain),this._modulationNode.connect(this._carrier.frequency),this._carrier.connect(this.output)}static getDefaults(){return Object.assign(Ff.getDefaults(),{modulationIndex:10})}dispose(){return super.dispose(),this.modulationIndex.dispose(),this}}const Wf=[1,1.483,1.932,2.546,2.63,3.897];class Bf extends Ef{constructor(){super(Cp(Bf.getDefaults(),arguments)),this.name="MetalSynth",this._oscillators=[],this._freqMultipliers=[];var e=Cp(Bf.getDefaults(),arguments);this.detune=new Td({context:this.context,units:"cents",value:e.detune}),this.frequency=new Td({context:this.context,units:"frequency"}),this._amplitude=new xd({context:this.context,gain:0}).connect(this.output),this._highpass=new Nf({Q:0,context:this.context,type:"highpass"}).connect(this._amplitude);for(let t=0;tthis.onsilence(this):Zp,type:"square"});n.connect(this._highpass),this._oscillators[t]=n;var s=new ef({context:this.context,value:Wf[t]});this._freqMultipliers[t]=s,this.frequency.chain(s,n.frequency),this.detune.connect(n.detune)}this._filterFreqScaler=new uf({context:this.context,max:7e3,min:this.toFrequency(e.resonance)}),this.envelope=new Df({attack:e.envelope.attack,attackCurve:"linear",context:this.context,decay:e.envelope.decay,release:e.envelope.release,sustain:0}),this.envelope.chain(this._filterFreqScaler,this._highpass.frequency),this.envelope.connect(this._amplitude.gain),this._octaves=e.octaves,this.octaves=e.octaves}static getDefaults(){return Ap(Ef.getDefaults(),{envelope:Object.assign(Op(Df.getDefaults(),Object.keys(md.getDefaults())),{attack:.001,decay:1.4,release:.2}),harmonicity:5.1,modulationIndex:32,octaves:1.5,resonance:4e3})}_triggerEnvelopeAttack(e,t=1){return this.envelope.triggerAttack(e,t),this._oscillators.forEach(t=>t.start(e)),0===this.envelope.sustain&&this._oscillators.forEach(t=>{t.stop(e+this.toSeconds(this.envelope.attack)+this.toSeconds(this.envelope.decay))}),this}_triggerEnvelopeRelease(e){return this.envelope.triggerRelease(e),this._oscillators.forEach(t=>t.stop(e+this.toSeconds(this.envelope.release))),this}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}get modulationIndex(){return this._oscillators[0].modulationIndex.value}set modulationIndex(e){this._oscillators.forEach(t=>t.modulationIndex.value=e)}get harmonicity(){return this._oscillators[0].harmonicity.value}set harmonicity(e){this._oscillators.forEach(t=>t.harmonicity.value=e)}get resonance(){return this._filterFreqScaler.min}set resonance(t){this._filterFreqScaler.min=this.toFrequency(t),this.octaves=this._octaves}get octaves(){return this._octaves}set octaves(t){this._octaves=t,this._filterFreqScaler.max=this._filterFreqScaler.min*Math.pow(2,t)}dispose(){return super.dispose(),this._oscillators.forEach(t=>t.dispose()),this._freqMultipliers.forEach(t=>t.dispose()),this.frequency.dispose(),this.detune.dispose(),this._filterFreqScaler.dispose(),this._amplitude.dispose(),this.envelope.dispose(),this._highpass.dispose(),this}}class Uf extends qf{constructor(){super(Cp(Uf.getDefaults(),arguments)),this.name="MembraneSynth",this.portamento=0;var t=Cp(Uf.getDefaults(),arguments);this.pitchDecay=t.pitchDecay,this.octaves=t.octaves,Gp(this,["oscillator","envelope"])}static getDefaults(){return Ap(Ef.getDefaults(),qf.getDefaults(),{envelope:{attack:.001,attackCurve:"exponential",decay:.4,release:1.4,sustain:.01},octaves:10,oscillator:{type:"sine"},pitchDecay:.05})}setNote(t,e){var s=this.toSeconds(e),e=this.toFrequency(t instanceof cd?t.toFrequency():t),t=e*this.octaves;return this.oscillator.frequency.setValueAtTime(t,s),this.oscillator.frequency.exponentialRampToValueAtTime(e,s+this.toSeconds(this.pitchDecay)),this}dispose(){return super.dispose(),this}}vp([ff(0)],Uf.prototype,"octaves",void 0),vp([_f(0)],Uf.prototype,"pitchDecay",void 0);class Gf extends Mf{constructor(){super(Cp(Gf.getDefaults(),arguments)),this.name="NoiseSynth";var t=Cp(Gf.getDefaults(),arguments);this.noise=new Ud(Object.assign({context:this.context},t.noise)),this.envelope=new Rf(Object.assign({context:this.context},t.envelope)),this.noise.chain(this.envelope,this.output)}static getDefaults(){return Object.assign(Mf.getDefaults(),{envelope:Object.assign(Op(Df.getDefaults(),Object.keys(md.getDefaults())),{decay:.1,sustain:0}),noise:Object.assign(Op(Ud.getDefaults(),Object.keys(Wd.getDefaults())),{type:"white"})})}triggerAttack(t,e=1){return t=this.toSeconds(t),this.envelope.triggerAttack(t,e),this.noise.start(t),0===this.envelope.sustain&&this.noise.stop(t+this.toSeconds(this.envelope.attack)+this.toSeconds(this.envelope.decay)),this}triggerRelease(t){return t=this.toSeconds(t),this.envelope.triggerRelease(t),this.noise.stop(t+this.toSeconds(this.envelope.release)),this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",0),this._syncMethod("triggerRelease",0)),this}triggerAttackRelease(t,e,s=1){return e=this.toSeconds(e),t=this.toSeconds(t),this.triggerAttack(e,s),this.triggerRelease(e+t),this}dispose(){return super.dispose(),this.noise.dispose(),this.envelope.dispose(),this}}const Qf=new Set;function Zf(t){Qf.add(t)}function Xf(t,e){e=`registerProcessor("${t}", ${e})`;Qf.add(e)}class Yf extends md{constructor(t){super(t),this.name="ToneAudioWorklet",this.workletOptions={},this.onprocessorerror=Zp;const e=URL.createObjectURL(new Blob([Array.from(Qf).join("\n")],{type:"text/javascript"})),s=this._audioWorkletName();this._dummyGain=this.context.createGain(),this._dummyParam=this._dummyGain.gain,this.context.addAudioWorkletModule(e,s).then(()=>{this.disposed||(this._worklet=this.context.createAudioWorkletNode(s,this.workletOptions),this._worklet.onprocessorerror=this.onprocessorerror.bind(this),this.onReady(this._worklet))})}dispose(){return super.dispose(),this._dummyGain.disconnect(),this._worklet&&(this._worklet.port.postMessage("dispose"),this._worklet.disconnect()),this}}Zf('\n\t/**\n\t * The base AudioWorkletProcessor for use in Tone.js. Works with the [[ToneAudioWorklet]]. \n\t */\n\tclass ToneAudioWorkletProcessor extends AudioWorkletProcessor {\n\n\t\tconstructor(options) {\n\t\t\t\n\t\t\tsuper(options);\n\t\t\t/**\n\t\t\t * If the processor was disposed or not. Keep alive until it\'s disposed.\n\t\t\t */\n\t\t\tthis.disposed = false;\n\t\t \t/** \n\t\t\t * The number of samples in the processing block\n\t\t\t */\n\t\t\tthis.blockSize = 128;\n\t\t\t/**\n\t\t\t * the sample rate\n\t\t\t */\n\t\t\tthis.sampleRate = sampleRate;\n\n\t\t\tthis.port.onmessage = (event) => {\n\t\t\t\t// when it receives a dispose \n\t\t\t\tif (event.data === "dispose") {\n\t\t\t\t\tthis.disposed = true;\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n'),Zf("\n\t/**\n\t * Abstract class for a single input/output processor. \n\t * has a 'generate' function which processes one sample at a time\n\t */\n\tclass SingleIOProcessor extends ToneAudioWorkletProcessor {\n\n\t\tconstructor(options) {\n\t\t\tsuper(Object.assign(options, {\n\t\t\t\tnumberOfInputs: 1,\n\t\t\t\tnumberOfOutputs: 1\n\t\t\t}));\n\t\t\t/**\n\t\t\t * Holds the name of the parameter and a single value of that\n\t\t\t * parameter at the current sample\n\t\t\t * @type { [name: string]: number }\n\t\t\t */\n\t\t\tthis.params = {}\n\t\t}\n\n\t\t/**\n\t\t * Generate an output sample from the input sample and parameters\n\t\t * @abstract\n\t\t * @param input number\n\t\t * @param channel number\n\t\t * @param parameters { [name: string]: number }\n\t\t * @returns number\n\t\t */\n\t\tgenerate(){}\n\n\t\t/**\n\t\t * Update the private params object with the \n\t\t * values of the parameters at the given index\n\t\t * @param parameters { [name: string]: Float32Array },\n\t\t * @param index number\n\t\t */\n\t\tupdateParams(parameters, index) {\n\t\t\tfor (const paramName in parameters) {\n\t\t\t\tconst param = parameters[paramName];\n\t\t\t\tif (param.length > 1) {\n\t\t\t\t\tthis.params[paramName] = parameters[paramName][index];\n\t\t\t\t} else {\n\t\t\t\t\tthis.params[paramName] = parameters[paramName][0];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Process a single frame of the audio\n\t\t * @param inputs Float32Array[][]\n\t\t * @param outputs Float32Array[][]\n\t\t */\n\t\tprocess(inputs, outputs, parameters) {\n\t\t\tconst input = inputs[0];\n\t\t\tconst output = outputs[0];\n\t\t\t// get the parameter values\n\t\t\tconst channelCount = Math.max(input && input.length || 0, output.length);\n\t\t\tfor (let sample = 0; sample < this.blockSize; sample++) {\n\t\t\t\tthis.updateParams(parameters, sample);\n\t\t\t\tfor (let channel = 0; channel < channelCount; channel++) {\n\t\t\t\t\tconst inputSample = input && input.length ? input[channel][sample] : 0;\n\t\t\t\t\toutput[channel][sample] = this.generate(inputSample, channel, this.params);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn !this.disposed;\n\t\t}\n\t};\n"),Zf("\n\t/**\n\t * A multichannel buffer for use within an AudioWorkletProcessor as a delay line\n\t */\n\tclass DelayLine {\n\t\t\n\t\tconstructor(size, channels) {\n\t\t\tthis.buffer = [];\n\t\t\tthis.writeHead = []\n\t\t\tthis.size = size;\n\n\t\t\t// create the empty channels\n\t\t\tfor (let i = 0; i < channels; i++) {\n\t\t\t\tthis.buffer[i] = new Float32Array(this.size);\n\t\t\t\tthis.writeHead[i] = 0;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Push a value onto the end\n\t\t * @param channel number\n\t\t * @param value number\n\t\t */\n\t\tpush(channel, value) {\n\t\t\tthis.writeHead[channel] += 1;\n\t\t\tif (this.writeHead[channel] > this.size) {\n\t\t\t\tthis.writeHead[channel] = 0;\n\t\t\t}\n\t\t\tthis.buffer[channel][this.writeHead[channel]] = value;\n\t\t}\n\n\t\t/**\n\t\t * Get the recorded value of the channel given the delay\n\t\t * @param channel number\n\t\t * @param delay number delay samples\n\t\t */\n\t\tget(channel, delay) {\n\t\t\tlet readHead = this.writeHead[channel] - Math.floor(delay);\n\t\t\tif (readHead < 0) {\n\t\t\t\treadHead += this.size;\n\t\t\t}\n\t\t\treturn this.buffer[channel][readHead];\n\t\t}\n\t}\n");const $f="feedback-comb-filter";Xf($f,'\n\tclass FeedbackCombFilterWorklet extends SingleIOProcessor {\n\n\t\tconstructor(options) {\n\t\t\tsuper(options);\n\t\t\tthis.delayLine = new DelayLine(this.sampleRate, options.channelCount || 2);\n\t\t}\n\n\t\tstatic get parameterDescriptors() {\n\t\t\treturn [{\n\t\t\t\tname: "delayTime",\n\t\t\t\tdefaultValue: 0.1,\n\t\t\t\tminValue: 0,\n\t\t\t\tmaxValue: 1,\n\t\t\t\tautomationRate: "k-rate"\n\t\t\t}, {\n\t\t\t\tname: "feedback",\n\t\t\t\tdefaultValue: 0.5,\n\t\t\t\tminValue: 0,\n\t\t\t\tmaxValue: 0.9999,\n\t\t\t\tautomationRate: "k-rate"\n\t\t\t}];\n\t\t}\n\n\t\tgenerate(input, channel, parameters) {\n\t\t\tconst delayedSample = this.delayLine.get(channel, parameters.delayTime * this.sampleRate);\n\t\t\tthis.delayLine.push(channel, input + delayedSample * parameters.feedback);\n\t\t\treturn delayedSample;\n\t\t}\n\t}\n');class Hf extends Yf{constructor(){super(Cp(Hf.getDefaults(),arguments,["delayTime","resonance"])),this.name="FeedbackCombFilter";var t=Cp(Hf.getDefaults(),arguments,["delayTime","resonance"]);this.input=new xd({context:this.context}),this.output=new xd({context:this.context}),this.delayTime=new _d({context:this.context,value:t.delayTime,units:"time",minValue:0,maxValue:1,param:this._dummyParam,swappable:!0}),this.resonance=new _d({context:this.context,value:t.resonance,units:"normalRange",param:this._dummyParam,swappable:!0}),Gp(this,["resonance","delayTime"])}_audioWorkletName(){return $f}static getDefaults(){return Object.assign(md.getDefaults(),{delayTime:.1,resonance:.5})}onReady(t){gd(this.input,t,this.output);var e=t.parameters.get("delayTime");this.delayTime.setParam(e);t=t.parameters.get("feedback");this.resonance.setParam(t)}dispose(){return super.dispose(),this.input.dispose(),this.output.dispose(),this.delayTime.dispose(),this.resonance.dispose(),this}}class Jf extends md{constructor(){super(Cp(Jf.getDefaults(),arguments,["frequency","type"])),this.name="OnePoleFilter";var t=Cp(Jf.getDefaults(),arguments,["frequency","type"]);this._frequency=t.frequency,this._type=t.type,this.input=new xd({context:this.context}),this.output=new xd({context:this.context}),this._createFilter()}static getDefaults(){return Object.assign(md.getDefaults(),{frequency:880,type:"lowpass"})}_createFilter(){const t=this._filter,e=this.toFrequency(this._frequency),s=1/(2*Math.PI*e);if("lowpass"===this._type){const t=1/(s*this.context.sampleRate),e=t-1;this._filter=this.context.createIIRFilter([t,0],[1,e])}else{const t=1/(s*this.context.sampleRate)-1;this._filter=this.context.createIIRFilter([1,-1],[1,t])}this.input.chain(this._filter,this.output),t&&this.context.setTimeout(()=>{this.disposed||(this.input.disconnect(t),t.disconnect())},this.blockTime)}get frequency(){return this._frequency}set frequency(t){this._frequency=t,this._createFilter()}get type(){return this._type}set type(t){this._type=t,this._createFilter()}getFrequencyResponse(e=128){const s=new Float32Array(e);for(let t=0;tthis.releaseAll(t);const t=Cp(e_.getDefaults(),arguments,["voice","options"]);op(!tp(t.voice),"DEPRECATED: The polyphony count is no longer the first argument.");var e=t.voice.getDefaults();this.options=Object.assign(e,t.options),this.voice=t.voice,this.maxPolyphony=t.maxPolyphony,this._dummyVoice=this._getNextAvailableVoice();e=this._voices.indexOf(this._dummyVoice);this._voices.splice(e,1),this._gcTimeout=this.context.setInterval(this._collectGarbage.bind(this),1)}static getDefaults(){return Object.assign(Mf.getDefaults(),{maxPolyphony:32,options:{},voice:qf})}get activeVoices(){return this._activeVoices.length}_makeVoiceAvailable(e){this._availableVoices.push(e);var t=this._activeVoices.findIndex(t=>t.voice===e);this._activeVoices.splice(t,1)}_getNextAvailableVoice(){if(this._availableVoices.length)return this._availableVoices.shift();if(this._voices.lengthMath.ceil(this._averageActiveVoices+1)){const t=this._availableVoices.shift(),e=this._voices.indexOf(t);this._voices.splice(e,1),this.context.isOffline||t.dispose()}}_triggerAttack(t,n,i){t.forEach(t=>{const e=new Ed(this.context,t).toMidi(),s=this._getNextAvailableVoice();s&&(s.triggerAttack(t,n,i),this._activeVoices.push({midi:e,voice:s,released:!1}),this.log("triggerAttack",t,n))})}_triggerRelease(t,n){t.forEach(t=>{const s=new Ed(this.context,t).toMidi(),e=this._activeVoices.find(({midi:t,released:e})=>t===s&&!e);e&&(e.voice.triggerRelease(n),e.released=!0,this.log("triggerRelease",t,n))})}_scheduleEvent(t,e,s,n){op(!this.disposed,"Synth was already disposed"),s<=this.now()?"attack"===t?this._triggerAttack(e,s,n):this._triggerRelease(e,s):this.context.setTimeout(()=>{this.disposed||this._scheduleEvent(t,e,s,n)},s-this.now())}triggerAttack(t,e,s){Array.isArray(t)||(t=[t]);e=this.toSeconds(e);return this._scheduleEvent("attack",t,e,s),this}triggerRelease(t,e){Array.isArray(t)||(t=[t]);e=this.toSeconds(e);return this._scheduleEvent("release",t,e),this}triggerAttackRelease(e,s,t,n){var i=this.toSeconds(t);if(this.triggerAttack(e,i,n),np(s)){op(np(e),"If the duration is an array, the notes must also be an array");for(let t=0;tt.set(e)),this._dummyVoice.set(e),this}get(){return this._dummyVoice.get()}releaseAll(t){const e=this.toSeconds(t);return this._activeVoices.forEach(({voice:t})=>{t.triggerRelease(e)}),this}dispose(){return super.dispose(),this._dummyVoice.dispose(),this._voices.forEach(t=>t.dispose()),this._activeVoices=[],this._availableVoices=[],this.context.clearInterval(this._gcTimeout),this}}class s_ extends Mf{constructor(){super(Cp(s_.getDefaults(),arguments,["urls","onload","baseUrl"],"urls")),this.name="Sampler",this._activeSources=new Map;const s=Cp(s_.getDefaults(),arguments,["urls","onload","baseUrl"],"urls"),n={};Object.keys(s.urls).forEach(t=>{const e=parseInt(t,10);if(op(rp(t)||tp(e)&&isFinite(e),`url key is neither a note or midi pitch: ${t}`),rp(t)){const e=new cd(this.context,t).toMidi();n[e]=s.urls[t]}else tp(e)&&isFinite(e)&&(n[e]=s.urls[e])}),this._buffers=new Md({urls:n,onload:s.onload,baseUrl:s.baseUrl,onerror:s.onerror}),this.attack=s.attack,this.release=s.release,this.curve=s.curve,this._buffers.loaded&&Promise.resolve().then(s.onload)}static getDefaults(){return Object.assign(Mf.getDefaults(),{attack:0,baseUrl:"",curve:"exponential",onload:Zp,onerror:Zp,release:.1,urls:{}})}_findClosest(t){let e=0;for(;e<96;){if(this._buffers.has(t+e))return-e;if(this._buffers.has(t-e))return e;e++}throw new Error(`No available buffers for note: ${t}`)}triggerAttack(t,c,l=1){return this.log("triggerAttack",t,c,l),(t=!Array.isArray(t)?[t]:t).forEach(t=>{const e=rd(new cd(this.context,t).toFrequency()),s=Math.round(e),n=e-s,i=this._findClosest(s),r=s-i,o=this._buffers.get(r),a=sd(i+n),h=new Bd({url:o,context:this.context,curve:this.curve,fadeIn:this.attack,fadeOut:this.release,playbackRate:a}).connect(this.output);h.start(c,0,o.duration/a,l),np(this._activeSources.get(s))||this._activeSources.set(s,[]),this._activeSources.get(s).push(h),h.onended=()=>{if(this._activeSources&&this._activeSources.has(s)){const t=this._activeSources.get(s),e=t.indexOf(h);-1!==e&&t.splice(e,1)}}}),this}triggerRelease(t,s){return this.log("triggerRelease",t,s),(t=!Array.isArray(t)?[t]:t).forEach(t=>{t=new cd(this.context,t).toMidi();if(this._activeSources.has(t)&&this._activeSources.get(t).length){const e=this._activeSources.get(t);s=this.toSeconds(s),e.forEach(t=>{t.stop(s)}),this._activeSources.set(t,[])}}),this}releaseAll(t){const e=this.toSeconds(t);return this._activeSources.forEach(t=>{for(;t.length;)t.shift().stop(e)}),this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",1)),this}triggerAttackRelease(t,s,e,n=1){const i=this.toSeconds(e);return this.triggerAttack(t,i,n),np(s)?(op(np(t),"notes must be an array when duration is array"),t.forEach((t,e)=>{e=s[Math.min(e,s.length-1)];this.triggerRelease(t,i+this.toSeconds(e))})):this.triggerRelease(t,i+this.toSeconds(s)),this}add(t,e,s){var n;return op(rp(t)||isFinite(t),`note must be a pitch or midi: ${t}`),rp(t)?(n=new cd(this.context,t).toMidi(),this._buffers.add(n,e,s)):this._buffers.add(t,e,s),this}get loaded(){return this._buffers.loaded}dispose(){return super.dispose(),this._buffers.dispose(),this._activeSources.forEach(t=>{t.forEach(t=>t.dispose())}),this._activeSources.clear(),this}}vp([_f(0)],s_.prototype,"attack",void 0),vp([_f(0)],s_.prototype,"release",void 0);class n_ extends dd{constructor(){super(Cp(n_.getDefaults(),arguments,["callback","value"])),this.name="ToneEvent",this._state=new fd("stopped"),this._startOffset=0;var t=Cp(n_.getDefaults(),arguments,["callback","value"]);this._loop=t.loop,this.callback=t.callback,this.value=t.value,this._loopStart=this.toTicks(t.loopStart),this._loopEnd=this.toTicks(t.loopEnd),this._playbackRate=t.playbackRate,this._probability=t.probability,this._humanize=t.humanize,this.mute=t.mute,this._playbackRate=t.playbackRate,this._state.increasing=!0,this._rescheduleEvents()}static getDefaults(){return Object.assign(dd.getDefaults(),{callback:Zp,humanize:!1,loop:!1,loopEnd:"1m",loopStart:0,mute:!1,playbackRate:1,probability:1,value:null})}_rescheduleEvents(t=-1){this._state.forEachFrom(t,t=>{let e;var s,n;"started"===t.state&&(-1!==t.id&&this.context.transport.clear(t.id),s=t.time+Math.round(this.startOffset/this._playbackRate),!0===this._loop||tp(this._loop)&&1{this.context.transport.clear(t.id)}),this._state.cancel(t),this}_tick(e){var t=this.context.transport.getTicksAtTime(e);if(!(this.mute||"started"!==this._state.getValueAtTime(t)||this.probability<1&&Math.random()>this.probability)){if(this.humanize){let t=.02;sp(this.humanize)||(t=this.toSeconds(this.humanize)),e+=(2*Math.random()-1)*t}this.callback(e,this.value)}}_getLoopDuration(){return(this._loopEnd-this._loopStart)/this._playbackRate}get loop(){return this._loop}set loop(t){this._loop=t,this._rescheduleEvents()}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._rescheduleEvents()}get loopEnd(){return new Rd(this.context,this._loopEnd).toSeconds()}set loopEnd(t){this._loopEnd=this.toTicks(t),this._loop&&this._rescheduleEvents()}get loopStart(){return new Rd(this.context,this._loopStart).toSeconds()}set loopStart(t){this._loopStart=this.toTicks(t),this._loop&&this._rescheduleEvents()}get progress(){if(this._loop){var t=this.context.transport.ticks,e=this._state.get(t);if(null===e||"started"!==e.state)return 0;var s=this._getLoopDuration();return(t-e.time)%s/s}return 0}dispose(){return super.dispose(),this.cancel(),this._state.dispose(),this}}class i_ extends dd{constructor(){super(Cp(i_.getDefaults(),arguments,["callback","interval"])),this.name="Loop";var t=Cp(i_.getDefaults(),arguments,["callback","interval"]);this._event=new n_({context:this.context,callback:this._tick.bind(this),loop:!0,loopEnd:t.interval,playbackRate:t.playbackRate,probability:t.probability}),this.callback=t.callback,this.iterations=t.iterations}static getDefaults(){return Object.assign(dd.getDefaults(),{interval:"4n",callback:Zp,playbackRate:1,iterations:1/0,probability:1,mute:!1,humanize:!1})}start(t){return this._event.start(t),this}stop(t){return this._event.stop(t),this}cancel(t){return this._event.cancel(t),this}_tick(t){this.callback(t)}get state(){return this._event.state}get progress(){return this._event.progress}get interval(){return this._event.loopEnd}set interval(t){this._event.loopEnd=t}get playbackRate(){return this._event.playbackRate}set playbackRate(t){this._event.playbackRate=t}get humanize(){return this._event.humanize}set humanize(t){this._event.humanize=t}get probability(){return this._event.probability}set probability(t){this._event.probability=t}get mute(){return this._event.mute}set mute(t){this._event.mute=t}get iterations(){return!0===this._event.loop?1/0:this._event.loop}set iterations(t){this._event.loop=t===1/0||t}dispose(){return super.dispose(),this._event.dispose(),this}}class r_ extends n_{constructor(){super(Cp(r_.getDefaults(),arguments,["callback","events"])),this.name="Part",this._state=new fd("stopped"),this._events=new Set;const t=Cp(r_.getDefaults(),arguments,["callback","events"]);this._state.increasing=!0,t.events.forEach(t=>{np(t)?this.add(t[0],t[1]):this.add(t)})}static getDefaults(){return Object.assign(n_.getDefaults(),{events:[]})}start(e,t){const s=this.toTicks(e);if("started"!==this._state.getValueAtTime(s)){t=Dp(t,this._loop?this._loopStart:0),t=this._loop?Dp(t,this._loopStart):Dp(t,0);const e=this.toTicks(t);this._state.add({id:-1,offset:e,state:"started",time:s}),this._forEach(t=>{this._startNote(t,s,e)})}return this}_startNote(t,e,s){e-=s,this._loop?t.startOffset>=this._loopStart&&t.startOffset=s&&(t.loop=!1,t.start(new Rd(this.context,e))):t.startOffset>=s&&t.start(new Rd(this.context,e))}get startOffset(){return this._startOffset}set startOffset(t){this._startOffset=t,this._forEach(t=>{t.startOffset+=this._startOffset})}stop(e){var t=this.toTicks(e);return this._state.cancel(t),this._state.setStateAtTime("stopped",t),this._forEach(t=>{t.stop(e)}),this}at(t,e){const s=new pd(this.context,t).toTicks(),n=new Rd(this.context,1).toSeconds(),i=this._events.values();let r=i.next();for(;!r.done;){const t=r.value;if(Math.abs(s-t.startOffset){"started"===t.state?this._startNote(e,t.time,t.offset):e.stop(new Rd(this.context,t.time))})}remove(e,s){return ep(e)&&e.hasOwnProperty("time")&&(e=(s=e).time),e=this.toTicks(e),this._events.forEach(t=>{t.startOffset===e&&(Hu(s)||Ju(s)&&t.value===s)&&(this._events.delete(t),t.dispose())}),this}clear(){return this._forEach(t=>t.dispose()),this._events.clear(),this}cancel(e){return this._forEach(t=>t.cancel(e)),this._state.cancel(this.toTicks(e)),this}_forEach(e){return this._events&&this._events.forEach(t=>{t instanceof r_?t._forEach(e):e(t)}),this}_setAll(e,s){this._forEach(t=>{t[e]=s})}_tick(t,e){this.mute||this.callback(t,e)}_testLoopBoundries(t){this._loop&&(t.startOffset=this._loopEnd)?t.cancel(0):"stopped"===t.state&&this._restartEvent(t)}get probability(){return this._probability}set probability(t){this._probability=t,this._setAll("probability",t)}get humanize(){return this._humanize}set humanize(t){this._humanize=t,this._setAll("humanize",t)}get loop(){return this._loop}set loop(e){this._loop=e,this._forEach(t=>{t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.loop=e,this._testLoopBoundries(t)})}get loopEnd(){return new Rd(this.context,this._loopEnd).toSeconds()}set loopEnd(e){this._loopEnd=this.toTicks(e),this._loop&&this._forEach(t=>{t.loopEnd=e,this._testLoopBoundries(t)})}get loopStart(){return new Rd(this.context,this._loopStart).toSeconds()}set loopStart(t){this._loopStart=this.toTicks(t),this._loop&&this._forEach(t=>{t.loopStart=this.loopStart,this._testLoopBoundries(t)})}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._setAll("playbackRate",t)}get length(){return this._events.size}dispose(){return super.dispose(),this.clear(),this}}function*o_(t){let e=0;for(;e=t.length-1&&(e=!1)):(s--,s<=0&&(e=!0))}function*u_(t){let e=0,s=0;for(;et[e],set:(t,e,s)=>(ip(e)&&isFinite(parseInt(e,10))&&np(s)?t[e]=this._createSequence(s):t[e]=s,this._eventsUpdated(),!0)})}_eventsUpdated(){this._part.clear(),this._rescheduleSequence(this._eventsArray,this._subdivision,this.startOffset),this.loopEnd=this.loopEnd}_rescheduleSequence(t,s,n){t.forEach((t,e)=>{e=e*s+n;if(np(t))this._rescheduleSequence(t,s/t.length,e);else{const s=new Rd(this.context,e,"i").toSeconds();this._part.add(s,t)}})}_indexTime(t){return new Rd(this.context,t*this._subdivision+this.startOffset).toSeconds()}clear(){return this._part.clear(),this}dispose(){return super.dispose(),this._part.dispose(),this}get loop(){return this._part.loop}set loop(t){this._part.loop=t}get loopStart(){return this._loopStart}set loopStart(t){this._loopStart=t,this._part.loopStart=this._indexTime(t)}get loopEnd(){return this._loopEnd}set loopEnd(t){this._loopEnd=t,this._part.loopEnd=0===t?this._indexTime(this._eventsArray.length):this._indexTime(t)}get startOffset(){return this._part.startOffset}set startOffset(t){this._part.startOffset=t}get playbackRate(){return this._part.playbackRate}set playbackRate(t){this._part.playbackRate=t}get probability(){return this._part.probability}set probability(t){this._part.probability=t}get progress(){return this._part.progress}get humanize(){return this._part.humanize}set humanize(t){this._part.humanize=t}get length(){return this._part.length}}class g_ extends md{constructor(){super(Object.assign(Cp(g_.getDefaults(),arguments,["fade"]))),this.name="CrossFade",this._panner=this.context.createStereoPanner(),this._split=this.context.createChannelSplitter(2),this._g2a=new xf({context:this.context}),this.a=new xd({context:this.context,gain:0}),this.b=new xd({context:this.context,gain:0}),this.output=new xd({context:this.context}),this._internalChannels=[this.a,this.b];var t=Cp(g_.getDefaults(),arguments,["fade"]);this.fade=new Td({context:this.context,units:"normalRange",value:t.fade}),Gp(this,"fade"),this.context.getConstant(1).connect(this._panner),this._panner.connect(this._split),this._panner.channelCount=1,this._panner.channelCountMode="explicit",vd(this._split,this.a.gain,0),vd(this._split,this.b.gain,1),this.fade.chain(this._g2a,this._panner.pan),this.a.connect(this.output),this.b.connect(this.output)}static getDefaults(){return Object.assign(md.getDefaults(),{fade:.5})}dispose(){return super.dispose(),this.a.dispose(),this.b.dispose(),this.output.dispose(),this.fade.dispose(),this._g2a.dispose(),this._panner.disconnect(),this._split.disconnect(),this}}class v_ extends md{constructor(t){super(t),this.name="Effect",this._dryWet=new g_({context:this.context}),this.wet=this._dryWet.fade,this.effectSend=new xd({context:this.context}),this.effectReturn=new xd({context:this.context}),this.input=new xd({context:this.context}),this.output=this._dryWet,this.input.fan(this._dryWet.a,this.effectSend),this.effectReturn.connect(this._dryWet.b),this.wet.setValueAtTime(t.wet,0),this._internalChannels=[this.effectReturn,this.effectSend],Gp(this,"wet")}static getDefaults(){return Object.assign(md.getDefaults(),{wet:1})}connectEffect(t){return this._internalChannels.push(t),this.effectSend.chain(t,this.effectReturn),this}dispose(){return super.dispose(),this._dryWet.dispose(),this.effectSend.dispose(),this.effectReturn.dispose(),this.wet.dispose(),this}}class y_ extends v_{constructor(t){super(t),this.name="LFOEffect",this._lfo=new df({context:this.context,frequency:t.frequency,amplitude:t.depth}),this.depth=this._lfo.amplitude,this.frequency=this._lfo.frequency,this.type=t.type,Gp(this,["frequency","depth"])}static getDefaults(){return Object.assign(v_.getDefaults(),{frequency:1,type:"sine",depth:1})}start(t){return this._lfo.start(t),this}stop(t){return this._lfo.stop(t),this}sync(){return this._lfo.sync(),this}unsync(){return this._lfo.unsync(),this}get type(){return this._lfo.type}set type(t){this._lfo.type=t}dispose(){return super.dispose(),this._lfo.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class x_ extends y_{constructor(){super(Cp(x_.getDefaults(),arguments,["frequency","baseFrequency","octaves"])),this.name="AutoFilter";var t=Cp(x_.getDefaults(),arguments,["frequency","baseFrequency","octaves"]);this.filter=new Nf(Object.assign(t.filter,{context:this.context})),this.connectEffect(this.filter),this._lfo.connect(this.filter.frequency),this.octaves=t.octaves,this.baseFrequency=t.baseFrequency}static getDefaults(){return Object.assign(y_.getDefaults(),{baseFrequency:200,octaves:2.6,filter:{type:"lowpass",rolloff:-12,Q:1}})}get baseFrequency(){return this._lfo.min}set baseFrequency(t){this._lfo.min=this.toFrequency(t),this.octaves=this._octaves}get octaves(){return this._octaves}set octaves(t){this._octaves=t,this._lfo.max=this._lfo.min*Math.pow(2,t)}dispose(){return super.dispose(),this.filter.dispose(),this}}class w_ extends md{constructor(){super(Object.assign(Cp(w_.getDefaults(),arguments,["pan"]))),this.name="Panner",this._panner=this.context.createStereoPanner(),this.input=this._panner,this.output=this._panner;var t=Cp(w_.getDefaults(),arguments,["pan"]);this.pan=new _d({context:this.context,param:this._panner.pan,value:t.pan,minValue:-1,maxValue:1}),this._panner.channelCount=t.channelCount,this._panner.channelCountMode="explicit",Gp(this,"pan")}static getDefaults(){return Object.assign(md.getDefaults(),{pan:0,channelCount:1})}dispose(){return super.dispose(),this._panner.disconnect(),this.pan.dispose(),this}}class b_ extends y_{constructor(){super(Cp(b_.getDefaults(),arguments,["frequency"])),this.name="AutoPanner";var t=Cp(b_.getDefaults(),arguments,["frequency"]);this._panner=new w_({context:this.context,channelCount:t.channelCount}),this.connectEffect(this._panner),this._lfo.connect(this._panner.pan),this._lfo.min=-1,this._lfo.max=1}static getDefaults(){return Object.assign(y_.getDefaults(),{channelCount:1})}dispose(){return super.dispose(),this._panner.dispose(),this}}class T_ extends md{constructor(){super(Cp(T_.getDefaults(),arguments,["smoothing"])),this.name="Follower";var t=Cp(T_.getDefaults(),arguments,["smoothing"]);this._abs=this.input=new yf({context:this.context}),this._lowpass=this.output=new Jf({context:this.context,frequency:1/this.toSeconds(t.smoothing),type:"lowpass"}),this._abs.connect(this._lowpass),this._smoothing=t.smoothing}static getDefaults(){return Object.assign(md.getDefaults(),{smoothing:.05})}get smoothing(){return this._smoothing}set smoothing(t){this._smoothing=t,this._lowpass.frequency=1/this.toSeconds(this.smoothing)}dispose(){return super.dispose(),this._abs.dispose(),this._lowpass.dispose(),this}}class S_ extends v_{constructor(){super(Cp(S_.getDefaults(),arguments,["baseFrequency","octaves","sensitivity"])),this.name="AutoWah";var t=Cp(S_.getDefaults(),arguments,["baseFrequency","octaves","sensitivity"]);this._follower=new T_({context:this.context,smoothing:t.follower}),this._sweepRange=new Af({context:this.context,min:0,max:1,exponent:.5}),this._baseFrequency=this.toFrequency(t.baseFrequency),this._octaves=t.octaves,this._inputBoost=new xd({context:this.context}),this._bandpass=new Nf({context:this.context,rolloff:-48,frequency:0,Q:t.Q}),this._peaking=new Nf({context:this.context,type:"peaking"}),this._peaking.gain.value=t.gain,this.gain=this._peaking.gain,this.Q=this._bandpass.Q,this.effectSend.chain(this._inputBoost,this._follower,this._sweepRange),this._sweepRange.connect(this._bandpass.frequency),this._sweepRange.connect(this._peaking.frequency),this.effectSend.chain(this._bandpass,this._peaking,this.effectReturn),this._setSweepRange(),this.sensitivity=t.sensitivity,Gp(this,["gain","Q"])}static getDefaults(){return Object.assign(v_.getDefaults(),{baseFrequency:100,octaves:6,sensitivity:0,Q:2,gain:2,follower:.2})}get octaves(){return this._octaves}set octaves(t){this._octaves=t,this._setSweepRange()}get follower(){return this._follower.smoothing}set follower(t){this._follower.smoothing=t}get baseFrequency(){return this._baseFrequency}set baseFrequency(t){this._baseFrequency=this.toFrequency(t),this._setSweepRange()}get sensitivity(){return ed(1/this._inputBoost.gain.value)}set sensitivity(t){this._inputBoost.gain.value=1/td(t)}_setSweepRange(){this._sweepRange.min=this._baseFrequency,this._sweepRange.max=Math.min(this._baseFrequency*Math.pow(2,this._octaves),this.context.sampleRate/2)}dispose(){return super.dispose(),this._follower.dispose(),this._sweepRange.dispose(),this._bandpass.dispose(),this._peaking.dispose(),this._inputBoost.dispose(),this}}const k_="bit-crusher";Xf(k_,"\n\tclass BitCrusherWorklet extends SingleIOProcessor {\n\n\t\tstatic get parameterDescriptors() {\n\t\t\treturn [{\n\t\t\t\tname: \"bits\",\n\t\t\t\tdefaultValue: 12,\n\t\t\t\tminValue: 1,\n\t\t\t\tmaxValue: 16,\n\t\t\t\tautomationRate: 'k-rate'\n\t\t\t}];\n\t\t}\n\n\t\tgenerate(input, _channel, parameters) {\n\t\t\tconst step = Math.pow(0.5, parameters.bits - 1);\n\t\t\tconst val = step * Math.floor(input / step + 0.5);\n\t\t\treturn val;\n\t\t}\n\t}\n");class A_ extends v_{constructor(){super(Cp(A_.getDefaults(),arguments,["bits"])),this.name="BitCrusher";var t=Cp(A_.getDefaults(),arguments,["bits"]);this._bitCrusherWorklet=new C_({context:this.context,bits:t.bits}),this.connectEffect(this._bitCrusherWorklet),this.bits=this._bitCrusherWorklet.bits}static getDefaults(){return Object.assign(v_.getDefaults(),{bits:4})}dispose(){return super.dispose(),this._bitCrusherWorklet.dispose(),this}}class C_ extends Yf{constructor(){super(Cp(C_.getDefaults(),arguments)),this.name="BitCrusherWorklet";var t=Cp(C_.getDefaults(),arguments);this.input=new xd({context:this.context}),this.output=new xd({context:this.context}),this.bits=new _d({context:this.context,value:t.bits,units:"positive",minValue:1,maxValue:16,param:this._dummyParam,swappable:!0})}static getDefaults(){return Object.assign(Yf.getDefaults(),{bits:12})}_audioWorkletName(){return k_}onReady(t){gd(this.input,t,this.output);t=t.parameters.get("bits");this.bits.setParam(t)}dispose(){return super.dispose(),this.input.dispose(),this.output.dispose(),this.bits.dispose(),this}}class D_ extends v_{constructor(){super(Cp(D_.getDefaults(),arguments,["order"])),this.name="Chebyshev";var t=Cp(D_.getDefaults(),arguments,["order"]);this._shaper=new Kd({context:this.context,length:4096}),this._order=t.order,this.connectEffect(this._shaper),this.order=t.order,this.oversample=t.oversample}static getDefaults(){return Object.assign(v_.getDefaults(),{order:1,oversample:"none"})}_getCoefficient(t,e,s){return s.has(e)||(0===e?s.set(e,0):1===e?s.set(e,t):s.set(e,2*t*this._getCoefficient(t,e-1,s)-this._getCoefficient(t,e-2,s))),s.get(e)}get order(){return this._order}set order(e){op(Number.isInteger(e),"'order' must be an integer"),this._order=e,this._shaper.setMap(t=>this._getCoefficient(t,e,new Map))}get oversample(){return this._shaper.oversample}set oversample(t){this._shaper.oversample=t}dispose(){return super.dispose(),this._shaper.dispose(),this}}class O_ extends md{constructor(){super(Cp(O_.getDefaults(),arguments,["channels"])),this.name="Split";var t=Cp(O_.getDefaults(),arguments,["channels"]);this._splitter=this.input=this.output=this.context.createChannelSplitter(t.channels),this._internalChannels=[this._splitter]}static getDefaults(){return Object.assign(md.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._splitter.disconnect(),this}}class M_ extends md{constructor(){super(Cp(M_.getDefaults(),arguments,["channels"])),this.name="Merge";var t=Cp(M_.getDefaults(),arguments,["channels"]);this._merger=this.output=this.input=this.context.createChannelMerger(t.channels)}static getDefaults(){return Object.assign(md.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._merger.disconnect(),this}}class E_ extends md{constructor(t){super(t),this.name="StereoEffect",this.input=new xd({context:this.context}),this.input.channelCount=2,this.input.channelCountMode="explicit",this._dryWet=this.output=new g_({context:this.context,fade:t.wet}),this.wet=this._dryWet.fade,this._split=new O_({context:this.context,channels:2}),this._merge=new M_({context:this.context,channels:2}),this.input.connect(this._split),this.input.connect(this._dryWet.a),this._merge.connect(this._dryWet.b),Gp(this,["wet"])}connectEffectLeft(...t){this._split.connect(t[0],0,0),gd(...t),vd(t[t.length-1],this._merge,0,0)}connectEffectRight(...t){this._split.connect(t[0],1,0),gd(...t),vd(t[t.length-1],this._merge,0,1)}static getDefaults(){return Object.assign(md.getDefaults(),{wet:1})}dispose(){return super.dispose(),this._dryWet.dispose(),this._split.dispose(),this._merge.dispose(),this}}class R_ extends E_{constructor(t){super(t),this.feedback=new Td({context:this.context,value:t.feedback,units:"normalRange"}),this._feedbackL=new xd({context:this.context}),this._feedbackR=new xd({context:this.context}),this._feedbackSplit=new O_({context:this.context,channels:2}),this._feedbackMerge=new M_({context:this.context,channels:2}),this._merge.connect(this._feedbackSplit),this._feedbackMerge.connect(this._split),this._feedbackSplit.connect(this._feedbackL,0,0),this._feedbackL.connect(this._feedbackMerge,0,0),this._feedbackSplit.connect(this._feedbackR,1,0),this._feedbackR.connect(this._feedbackMerge,0,1),this.feedback.fan(this._feedbackL.gain,this._feedbackR.gain),Gp(this,["feedback"])}static getDefaults(){return Object.assign(E_.getDefaults(),{feedback:.5})}dispose(){return super.dispose(),this.feedback.dispose(),this._feedbackL.dispose(),this._feedbackR.dispose(),this._feedbackSplit.dispose(),this._feedbackMerge.dispose(),this}}class q_ extends R_{constructor(){super(Cp(q_.getDefaults(),arguments,["frequency","delayTime","depth"])),this.name="Chorus";var t=Cp(q_.getDefaults(),arguments,["frequency","delayTime","depth"]);this._depth=t.depth,this._delayTime=t.delayTime/1e3,this._lfoL=new df({context:this.context,frequency:t.frequency,min:0,max:1}),this._lfoR=new df({context:this.context,frequency:t.frequency,min:0,max:1,phase:180}),this._delayNodeL=new Od({context:this.context}),this._delayNodeR=new Od({context:this.context}),this.frequency=this._lfoL.frequency,Gp(this,["frequency"]),this._lfoL.frequency.connect(this._lfoR.frequency),this.connectEffectLeft(this._delayNodeL),this.connectEffectRight(this._delayNodeR),this._lfoL.connect(this._delayNodeL.delayTime),this._lfoR.connect(this._delayNodeR.delayTime),this.depth=this._depth,this.type=t.type,this.spread=t.spread}static getDefaults(){return Object.assign(R_.getDefaults(),{frequency:1.5,delayTime:3.5,depth:.7,type:"sine",spread:180,feedback:0,wet:.5})}get depth(){return this._depth}set depth(t){this._depth=t;t=this._delayTime*t;this._lfoL.min=Math.max(this._delayTime-t,0),this._lfoL.max=this._delayTime+t,this._lfoR.min=Math.max(this._delayTime-t,0),this._lfoR.max=this._delayTime+t}get delayTime(){return 1e3*this._delayTime}set delayTime(t){this._delayTime=t/1e3,this.depth=this._depth}get type(){return this._lfoL.type}set type(t){this._lfoL.type=t,this._lfoR.type=t}get spread(){return this._lfoR.phase-this._lfoL.phase}set spread(t){this._lfoL.phase=90-t/2,this._lfoR.phase=t/2+90}start(t){return this._lfoL.start(t),this._lfoR.start(t),this}stop(t){return this._lfoL.stop(t),this._lfoR.stop(t),this}sync(){return this._lfoL.sync(),this._lfoR.sync(),this}unsync(){return this._lfoL.unsync(),this._lfoR.unsync(),this}dispose(){return super.dispose(),this._lfoL.dispose(),this._lfoR.dispose(),this._delayNodeL.dispose(),this._delayNodeR.dispose(),this.frequency.dispose(),this}}class F_ extends v_{constructor(){super(Cp(F_.getDefaults(),arguments,["distortion"])),this.name="Distortion";var t=Cp(F_.getDefaults(),arguments,["distortion"]);this._shaper=new Kd({context:this.context,length:4096}),this._distortion=t.distortion,this.connectEffect(this._shaper),this.distortion=t.distortion,this.oversample=t.oversample}static getDefaults(){return Object.assign(v_.getDefaults(),{distortion:.4,oversample:"none"})}get distortion(){return this._distortion}set distortion(t){const e=100*(this._distortion=t),s=Math.PI/180;this._shaper.setMap(t=>Math.abs(t)<.001?0:(3+e)*t*20*s/(Math.PI+e*Math.abs(t)))}get oversample(){return this._shaper.oversample}set oversample(t){this._shaper.oversample=t}dispose(){return super.dispose(),this._shaper.dispose(),this}}class I_ extends v_{constructor(t){super(t),this.name="FeedbackEffect",this._feedbackGain=new xd({context:this.context,gain:t.feedback,units:"normalRange"}),this.feedback=this._feedbackGain.gain,Gp(this,"feedback"),this.effectReturn.chain(this._feedbackGain,this.effectSend)}static getDefaults(){return Object.assign(v_.getDefaults(),{feedback:.125})}dispose(){return super.dispose(),this._feedbackGain.dispose(),this.feedback.dispose(),this}}class V_ extends I_{constructor(){super(Cp(V_.getDefaults(),arguments,["delayTime","feedback"])),this.name="FeedbackDelay";var t=Cp(V_.getDefaults(),arguments,["delayTime","feedback"]);this._delayNode=new Od({context:this.context,delayTime:t.delayTime,maxDelay:t.maxDelay}),this.delayTime=this._delayNode.delayTime,this.connectEffect(this._delayNode),Gp(this,"delayTime")}static getDefaults(){return Object.assign(I_.getDefaults(),{delayTime:.25,maxDelay:1})}dispose(){return super.dispose(),this._delayNode.dispose(),this.delayTime.dispose(),this}}class N_ extends md{constructor(t){super(t),this.name="PhaseShiftAllpass",this.input=new xd({context:this.context}),this.output=new xd({context:this.context}),this.offset90=new xd({context:this.context}),this._bank0=this._createAllPassFilterBank([.6923878,.9360654322959,.988229522686,.9987488452737]),this._bank1=this._createAllPassFilterBank([.4021921162426,.856171088242,.9722909545651,.9952884791278]),this._oneSampleDelay=this.context.createIIRFilter([0,1],[1,0]),gd(this.input,...this._bank0,this._oneSampleDelay,this.output),gd(this.input,...this._bank1,this.offset90)}_createAllPassFilterBank(t){return t.map(t=>{t=[[t*t,0,-1],[1,0,-t*t]];return this.context.createIIRFilter(t[0],t[1])})}dispose(){return super.dispose(),this.input.dispose(),this.output.dispose(),this.offset90.dispose(),this._bank0.forEach(t=>t.disconnect()),this._bank1.forEach(t=>t.disconnect()),this._oneSampleDelay.disconnect(),this}}class P_ extends v_{constructor(){super(Cp(P_.getDefaults(),arguments,["frequency"])),this.name="FrequencyShifter";var t=Cp(P_.getDefaults(),arguments,["frequency"]);this.frequency=new Td({context:this.context,units:"frequency",value:t.frequency,minValue:-this.context.sampleRate/2,maxValue:this.context.sampleRate/2}),this._sine=new $d({context:this.context,type:"sine"}),this._cosine=new Hd({context:this.context,phase:-90,type:"sine"}),this._sineMultiply=new ef({context:this.context}),this._cosineMultiply=new ef({context:this.context}),this._negate=new wf({context:this.context}),this._add=new lf({context:this.context}),this._phaseShifter=new N_({context:this.context}),this.effectSend.connect(this._phaseShifter),this.frequency.fan(this._sine.frequency,this._cosine.frequency),this._phaseShifter.offset90.connect(this._cosineMultiply),this._cosine.connect(this._cosineMultiply.factor),this._phaseShifter.connect(this._sineMultiply),this._sine.connect(this._sineMultiply.factor),this._sineMultiply.connect(this._negate),this._cosineMultiply.connect(this._add),this._negate.connect(this._add.addend),this._add.connect(this.effectReturn);t=this.immediate();this._sine.start(t),this._cosine.start(t)}static getDefaults(){return Object.assign(v_.getDefaults(),{frequency:0})}dispose(){return super.dispose(),this.frequency.dispose(),this._add.dispose(),this._cosine.dispose(),this._cosineMultiply.dispose(),this._negate.dispose(),this._phaseShifter.dispose(),this._sine.dispose(),this._sineMultiply.dispose(),this}}const j_=[1557/44100,1617/44100,1491/44100,1422/44100,1277/44100,1356/44100,1188/44100,1116/44100],L_=[225,556,441,341];class z_ extends E_{constructor(){super(Cp(z_.getDefaults(),arguments,["roomSize","dampening"])),this.name="Freeverb",this._combFilters=[],this._allpassFiltersL=[],this._allpassFiltersR=[];const s=Cp(z_.getDefaults(),arguments,["roomSize","dampening"]);this.roomSize=new Td({context:this.context,value:s.roomSize,units:"normalRange"}),this._allpassFiltersL=L_.map(t=>{const e=this.context.createBiquadFilter();return e.type="allpass",e.frequency.value=t,e}),this._allpassFiltersR=L_.map(t=>{const e=this.context.createBiquadFilter();return e.type="allpass",e.frequency.value=t,e}),this._combFilters=j_.map((t,e)=>{t=new Kf({context:this.context,dampening:s.dampening,delayTime:t});return et.dampening=e)}dispose(){return super.dispose(),this._allpassFiltersL.forEach(t=>t.disconnect()),this._allpassFiltersR.forEach(t=>t.disconnect()),this._combFilters.forEach(t=>t.dispose()),this.roomSize.dispose(),this}}const W_=[.06748,.06404,.08212,.09004],B_=[.773,.802,.753,.733],U_=[347,113,37];class G_ extends E_{constructor(){super(Cp(G_.getDefaults(),arguments,["roomSize"])),this.name="JCReverb",this._allpassFilters=[],this._feedbackCombFilters=[];var t=Cp(G_.getDefaults(),arguments,["roomSize"]);this.roomSize=new Td({context:this.context,value:t.roomSize,units:"normalRange"}),this._scaleRoomSize=new uf({context:this.context,min:-.733,max:.197}),this._allpassFilters=U_.map(t=>{const e=this.context.createBiquadFilter();return e.type="allpass",e.frequency.value=t,e}),this._feedbackCombFilters=W_.map((t,e)=>{const s=new Hf({context:this.context,delayTime:t});return this._scaleRoomSize.connect(s.resonance),s.resonance.value=B_[e],et.disconnect()),this._feedbackCombFilters.forEach(t=>t.dispose()),this.roomSize.dispose(),this._scaleRoomSize.dispose(),this}}class Q_ extends R_{constructor(t){super(t),this._feedbackL.disconnect(),this._feedbackL.connect(this._feedbackMerge,0,1),this._feedbackR.disconnect(),this._feedbackR.connect(this._feedbackMerge,0,0),Gp(this,["feedback"])}}class Z_ extends Q_{constructor(){super(Cp(Z_.getDefaults(),arguments,["delayTime","feedback"])),this.name="PingPongDelay";var t=Cp(Z_.getDefaults(),arguments,["delayTime","feedback"]);this._leftDelay=new Od({context:this.context,maxDelay:t.maxDelay}),this._rightDelay=new Od({context:this.context,maxDelay:t.maxDelay}),this._rightPreDelay=new Od({context:this.context,maxDelay:t.maxDelay}),this.delayTime=new Td({context:this.context,units:"time",value:t.delayTime}),this.connectEffectLeft(this._leftDelay),this.connectEffectRight(this._rightPreDelay,this._rightDelay),this.delayTime.fan(this._leftDelay.delayTime,this._rightDelay.delayTime,this._rightPreDelay.delayTime),this._feedbackL.disconnect(),this._feedbackL.connect(this._rightDelay),Gp(this,["delayTime"])}static getDefaults(){return Object.assign(Q_.getDefaults(),{delayTime:.25,maxDelay:1})}dispose(){return super.dispose(),this._leftDelay.dispose(),this._rightDelay.dispose(),this._rightPreDelay.dispose(),this.delayTime.dispose(),this}}class X_ extends I_{constructor(){super(Cp(X_.getDefaults(),arguments,["pitch"])),this.name="PitchShift";var t=Cp(X_.getDefaults(),arguments,["pitch"]);this._frequency=new Td({context:this.context}),this._delayA=new Od({maxDelay:1,context:this.context}),this._lfoA=new df({context:this.context,min:0,max:.1,type:"sawtooth"}).connect(this._delayA.delayTime),this._delayB=new Od({maxDelay:1,context:this.context}),this._lfoB=new df({context:this.context,min:0,max:.1,type:"sawtooth",phase:180}).connect(this._delayB.delayTime),this._crossFade=new g_({context:this.context}),this._crossFadeLFO=new df({context:this.context,min:0,max:1,type:"triangle",phase:90}).connect(this._crossFade.fade),this._feedbackDelay=new Od({delayTime:t.delayTime,context:this.context}),this.delayTime=this._feedbackDelay.delayTime,Gp(this,"delayTime"),this._pitch=t.pitch,this._windowSize=t.windowSize,this._delayA.connect(this._crossFade.a),this._delayB.connect(this._crossFade.b),this._frequency.fan(this._lfoA.frequency,this._lfoB.frequency,this._crossFadeLFO.frequency),this.effectSend.fan(this._delayA,this._delayB),this._crossFade.chain(this._feedbackDelay,this.effectReturn);t=this.now();this._lfoA.start(t),this._lfoB.start(t),this._crossFadeLFO.start(t),this.windowSize=this._windowSize}static getDefaults(){return Object.assign(I_.getDefaults(),{pitch:0,windowSize:.1,delayTime:0,feedback:0})}get pitch(){return this._pitch}set pitch(t){this._pitch=t;let e=0;e=t<0?(this._lfoA.min=0,this._lfoA.max=this._windowSize,this._lfoB.min=0,this._lfoB.max=this._windowSize,sd(t-1)+1):(this._lfoA.min=this._windowSize,this._lfoA.max=0,this._lfoB.min=this._windowSize,this._lfoB.max=0,sd(t)-1),this._frequency.value=e*(1.2/this._windowSize)}get windowSize(){return this._windowSize}set windowSize(t){this._windowSize=this.toSeconds(t),this.pitch=this._pitch}dispose(){return super.dispose(),this._frequency.dispose(),this._delayA.dispose(),this._delayB.dispose(),this._lfoA.dispose(),this._lfoB.dispose(),this._crossFade.dispose(),this._crossFadeLFO.dispose(),this._feedbackDelay.dispose(),this}}class Y_ extends E_{constructor(){super(Cp(Y_.getDefaults(),arguments,["frequency","octaves","baseFrequency"])),this.name="Phaser";var t=Cp(Y_.getDefaults(),arguments,["frequency","octaves","baseFrequency"]);this._lfoL=new df({context:this.context,frequency:t.frequency,min:0,max:1}),this._lfoR=new df({context:this.context,frequency:t.frequency,min:0,max:1,phase:180}),this._baseFrequency=this.toFrequency(t.baseFrequency),this._octaves=t.octaves,this.Q=new Td({context:this.context,value:t.Q,units:"positive"}),this._filtersL=this._makeFilters(t.stages,this._lfoL),this._filtersR=this._makeFilters(t.stages,this._lfoR),this.frequency=this._lfoL.frequency,this.frequency.value=t.frequency,this.connectEffectLeft(...this._filtersL),this.connectEffectRight(...this._filtersR),this._lfoL.frequency.connect(this._lfoR.frequency),this.baseFrequency=t.baseFrequency,this.octaves=t.octaves,this._lfoL.start(),this._lfoR.start(),Gp(this,["frequency","Q"])}static getDefaults(){return Object.assign(E_.getDefaults(),{frequency:.5,octaves:3,stages:10,Q:10,baseFrequency:350})}_makeFilters(e,s){const n=[];for(let t=0;tt.disconnect()),this._filtersR.forEach(t=>t.disconnect()),this.frequency.dispose(),this}}class $_ extends v_{constructor(){super(Cp($_.getDefaults(),arguments,["decay"])),this.name="Reverb",this._convolver=this.context.createConvolver(),this.ready=Promise.resolve();var t=Cp($_.getDefaults(),arguments,["decay"]);this._decay=t.decay,this._preDelay=t.preDelay,this.generate(),this.connectEffect(this._convolver)}static getDefaults(){return Object.assign(v_.getDefaults(),{decay:1.5,preDelay:.01})}get decay(){return this._decay}set decay(t){ap(t=this.toSeconds(t),.001),this._decay=t,this.generate()}get preDelay(){return this._preDelay}set preDelay(t){ap(t=this.toSeconds(t),0),this._preDelay=t,this.generate()}generate(){return yp(this,void 0,void 0,function*(){const t=this.ready,e=new Yp(2,this._decay+this._preDelay,this.context.sampleRate),s=new Ud({context:e}),n=new Ud({context:e}),i=new M_({context:e});s.connect(i,0,0),n.connect(i,0,1);const r=new xd({context:e}).toDestination();i.connect(r),s.start(0),n.start(0),r.gain.setValueAtTime(0,0),r.gain.setValueAtTime(1,this._preDelay),r.gain.exponentialApproachValueAtTime(0,this._preDelay,this.decay);const o=e.render();return this.ready=o.then(Zp),yield t,this._convolver.buffer=(yield o).get(),this})}dispose(){return super.dispose(),this._convolver.disconnect(),this}}class H_ extends md{constructor(){super(Cp(H_.getDefaults(),arguments)),this.name="MidSideSplit",this._split=this.input=new O_({channels:2,context:this.context}),this._midAdd=new lf({context:this.context}),this.mid=new ef({context:this.context,value:Math.SQRT1_2}),this._sideSubtract=new bf({context:this.context}),this.side=new ef({context:this.context,value:Math.SQRT1_2}),this._split.connect(this._midAdd,0),this._split.connect(this._midAdd.addend,1),this._split.connect(this._sideSubtract,0),this._split.connect(this._sideSubtract.subtrahend,1),this._midAdd.connect(this.mid),this._sideSubtract.connect(this.side)}dispose(){return super.dispose(),this.mid.dispose(),this.side.dispose(),this._midAdd.dispose(),this._sideSubtract.dispose(),this._split.dispose(),this}}class J_ extends md{constructor(){super(Cp(J_.getDefaults(),arguments)),this.name="MidSideMerge",this.mid=new xd({context:this.context}),this.side=new xd({context:this.context}),this._left=new lf({context:this.context}),this._leftMult=new ef({context:this.context,value:Math.SQRT1_2}),this._right=new bf({context:this.context}),this._rightMult=new ef({context:this.context,value:Math.SQRT1_2}),this._merge=this.output=new M_({context:this.context}),this.mid.fan(this._left),this.side.connect(this._left.addend),this.mid.connect(this._right),this.side.connect(this._right.subtrahend),this._left.connect(this._leftMult),this._right.connect(this._rightMult),this._leftMult.connect(this._merge,0,0),this._rightMult.connect(this._merge,0,1)}dispose(){return super.dispose(),this.mid.dispose(),this.side.dispose(),this._leftMult.dispose(),this._rightMult.dispose(),this._left.dispose(),this._right.dispose(),this}}class K_ extends v_{constructor(t){super(t),this.name="MidSideEffect",this._midSideMerge=new J_({context:this.context}),this._midSideSplit=new H_({context:this.context}),this._midSend=this._midSideSplit.mid,this._sideSend=this._midSideSplit.side,this._midReturn=this._midSideMerge.mid,this._sideReturn=this._midSideMerge.side,this.effectSend.connect(this._midSideSplit),this._midSideMerge.connect(this.effectReturn)}connectEffectMid(...t){this._midSend.chain(...t,this._midReturn)}connectEffectSide(...t){this._sideSend.chain(...t,this._sideReturn)}dispose(){return super.dispose(),this._midSideSplit.dispose(),this._midSideMerge.dispose(),this._midSend.dispose(),this._sideSend.dispose(),this._midReturn.dispose(),this._sideReturn.dispose(),this}}class tm extends K_{constructor(){super(Cp(tm.getDefaults(),arguments,["width"])),this.name="StereoWidener";var t=Cp(tm.getDefaults(),arguments,["width"]);this.width=new Td({context:this.context,value:t.width,units:"normalRange"}),Gp(this,["width"]),this._twoTimesWidthMid=new ef({context:this.context,value:2}),this._twoTimesWidthSide=new ef({context:this.context,value:2}),this._midMult=new ef({context:this.context}),this._twoTimesWidthMid.connect(this._midMult.factor),this.connectEffectMid(this._midMult),this._oneMinusWidth=new bf({context:this.context}),this._oneMinusWidth.connect(this._twoTimesWidthMid),vd(this.context.getConstant(1),this._oneMinusWidth),this.width.connect(this._oneMinusWidth.subtrahend),this._sideMult=new ef({context:this.context}),this.width.connect(this._twoTimesWidthSide),this._twoTimesWidthSide.connect(this._sideMult.factor),this.connectEffectSide(this._sideMult)}static getDefaults(){return Object.assign(K_.getDefaults(),{width:.5})}dispose(){return super.dispose(),this.width.dispose(),this._midMult.dispose(),this._sideMult.dispose(),this._twoTimesWidthMid.dispose(),this._twoTimesWidthSide.dispose(),this._oneMinusWidth.dispose(),this}}class em extends E_{constructor(){super(Cp(em.getDefaults(),arguments,["frequency","depth"])),this.name="Tremolo";var t=Cp(em.getDefaults(),arguments,["frequency","depth"]);this._lfoL=new df({context:this.context,type:t.type,min:1,max:0}),this._lfoR=new df({context:this.context,type:t.type,min:1,max:0}),this._amplitudeL=new xd({context:this.context}),this._amplitudeR=new xd({context:this.context}),this.frequency=new Td({context:this.context,value:t.frequency,units:"frequency"}),this.depth=new Td({context:this.context,value:t.depth,units:"normalRange"}),Gp(this,["frequency","depth"]),this.connectEffectLeft(this._amplitudeL),this.connectEffectRight(this._amplitudeR),this._lfoL.connect(this._amplitudeL.gain),this._lfoR.connect(this._amplitudeR.gain),this.frequency.fan(this._lfoL.frequency,this._lfoR.frequency),this.depth.fan(this._lfoR.amplitude,this._lfoL.amplitude),this.spread=t.spread}static getDefaults(){return Object.assign(E_.getDefaults(),{frequency:10,type:"sine",depth:.5,spread:180})}start(t){return this._lfoL.start(t),this._lfoR.start(t),this}stop(t){return this._lfoL.stop(t),this._lfoR.stop(t),this}sync(){return this._lfoL.sync(),this._lfoR.sync(),this.context.transport.syncSignal(this.frequency),this}unsync(){return this._lfoL.unsync(),this._lfoR.unsync(),this.context.transport.unsyncSignal(this.frequency),this}get type(){return this._lfoL.type}set type(t){this._lfoL.type=t,this._lfoR.type=t}get spread(){return this._lfoR.phase-this._lfoL.phase}set spread(t){this._lfoL.phase=90-t/2,this._lfoR.phase=t/2+90}dispose(){return super.dispose(),this._lfoL.dispose(),this._lfoR.dispose(),this._amplitudeL.dispose(),this._amplitudeR.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class sm extends v_{constructor(){super(Cp(sm.getDefaults(),arguments,["frequency","depth"])),this.name="Vibrato";var t=Cp(sm.getDefaults(),arguments,["frequency","depth"]);this._delayNode=new Od({context:this.context,delayTime:0,maxDelay:t.maxDelay}),this._lfo=new df({context:this.context,type:t.type,min:0,max:t.maxDelay,frequency:t.frequency,phase:-90}).start().connect(this._delayNode.delayTime),this.frequency=this._lfo.frequency,this.depth=this._lfo.amplitude,this.depth.value=t.depth,Gp(this,["frequency","depth"]),this.effectSend.chain(this._delayNode,this.effectReturn)}static getDefaults(){return Object.assign(v_.getDefaults(),{maxDelay:.005,frequency:5,depth:.1,type:"sine"})}get type(){return this._lfo.type}set type(t){this._lfo.type=t}dispose(){return super.dispose(),this._delayNode.dispose(),this._lfo.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class nm extends md{constructor(){super(Cp(nm.getDefaults(),arguments,["type","size"])),this.name="Analyser",this._analysers=[],this._buffers=[];var e=Cp(nm.getDefaults(),arguments,["type","size"]);this.input=this.output=this._gain=new xd({context:this.context}),this._split=new O_({context:this.context,channels:e.channels}),this.input.connect(this._split),ap(e.channels,1);for(let t=0;t{e=this._buffers[e];"fft"===this._type?t.getFloatFrequencyData(e):"waveform"===this._type&&t.getFloatTimeDomainData(e)}),1===this.channels?this._buffers[0]:this._buffers}get size(){return this._analysers[0].frequencyBinCount}set size(s){this._analysers.forEach((t,e)=>{t.fftSize=2*s,this._buffers[e]=new Float32Array(s)})}get channels(){return this._analysers.length}get type(){return this._type}set type(t){op("waveform"===t||"fft"===t,`Analyser: invalid type: ${t}`),this._type=t}get smoothing(){return this._analysers[0].smoothingTimeConstant}set smoothing(e){this._analysers.forEach(t=>t.smoothingTimeConstant=e)}dispose(){return super.dispose(),this._analysers.forEach(t=>t.disconnect()),this._split.dispose(),this._gain.dispose(),this}}class im extends md{constructor(){super(Cp(im.getDefaults(),arguments)),this.name="MeterBase",this.input=this.output=this._analyser=new nm({context:this.context,size:256,type:"waveform"})}dispose(){return super.dispose(),this._analyser.dispose(),this}}class rm extends im{constructor(){super(Cp(rm.getDefaults(),arguments,["smoothing"])),this.name="Meter",this._rms=0;var t=Cp(rm.getDefaults(),arguments,["smoothing"]);this.input=this.output=this._analyser=new nm({context:this.context,size:256,type:"waveform",channels:t.channelCount}),this.smoothing=t.smoothing,this.normalRange=t.normalRange}static getDefaults(){return Object.assign(im.getDefaults(),{smoothing:.8,normalRange:!1,channelCount:1})}getLevel(){return _p("'getLevel' has been changed to 'getValue'"),this.getValue()}getValue(){const t=this._analyser.getValue(),e=(1===this.channels?[t]:t).map(t=>{var e=t.reduce((t,e)=>t+e*e,0),t=Math.sqrt(e/t.length);return this._rms=Math.max(t,this._rms*this.smoothing),this.normalRange?this._rms:ed(this._rms)});return 1===this.channels?e[0]:e}get channels(){return this._analyser.channels}dispose(){return super.dispose(),this._analyser.dispose(),this}}class om extends im{constructor(){super(Cp(om.getDefaults(),arguments,["size"])),this.name="FFT";var t=Cp(om.getDefaults(),arguments,["size"]);this.normalRange=t.normalRange,this._analyser.type="fft",this.size=t.size}static getDefaults(){return Object.assign(md.getDefaults(),{normalRange:!1,size:1024,smoothing:.8})}getValue(){return this._analyser.getValue().map(t=>this.normalRange?td(t):t)}get size(){return this._analyser.size}set size(t){this._analyser.size=t}get smoothing(){return this._analyser.smoothing}set smoothing(t){this._analyser.smoothing=t}getFrequencyOfIndex(t){return op(0<=t&&tt._updateSolo())}get muted(){return 0===this.input.gain.value}_addSolo(){cm._soloed.has(this.context)||cm._soloed.set(this.context,new Set),cm._soloed.get(this.context).add(this)}_removeSolo(){cm._soloed.has(this.context)&&cm._soloed.get(this.context).delete(this)}_isSoloed(){return cm._soloed.has(this.context)&&cm._soloed.get(this.context).has(this)}_noSolos(){return!cm._soloed.has(this.context)||cm._soloed.has(this.context)&&0===cm._soloed.get(this.context).size}_updateSolo(){this._isSoloed()||this._noSolos()?this.input.gain.value=1:this.input.gain.value=0}dispose(){return super.dispose(),cm._allSolos.get(this.context).delete(this),this._removeSolo(),this}}cm._allSolos=new Map,cm._soloed=new Map;class lm extends md{constructor(){super(Cp(lm.getDefaults(),arguments,["pan","volume"])),this.name="PanVol";var t=Cp(lm.getDefaults(),arguments,["pan","volume"]);this._panner=this.input=new w_({context:this.context,pan:t.pan,channelCount:t.channelCount}),this.pan=this._panner.pan,this._volume=this.output=new Vd({context:this.context,volume:t.volume}),this.volume=this._volume.volume,this._panner.connect(this._volume),this.mute=t.mute,Gp(this,["pan","volume"])}static getDefaults(){return Object.assign(md.getDefaults(),{mute:!1,pan:0,volume:0,channelCount:1})}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}dispose(){return super.dispose(),this._panner.dispose(),this.pan.dispose(),this._volume.dispose(),this.volume.dispose(),this}}class um extends md{constructor(){super(Cp(um.getDefaults(),arguments,["volume","pan"])),this.name="Channel";var t=Cp(um.getDefaults(),arguments,["volume","pan"]);this._solo=this.input=new cm({solo:t.solo,context:this.context}),this._panVol=this.output=new lm({context:this.context,pan:t.pan,volume:t.volume,mute:t.mute,channelCount:t.channelCount}),this.pan=this._panVol.pan,this.volume=this._panVol.volume,this._solo.connect(this._panVol),Gp(this,["pan","volume"])}static getDefaults(){return Object.assign(md.getDefaults(),{pan:0,volume:0,mute:!1,solo:!1,channelCount:1})}get solo(){return this._solo.solo}set solo(t){this._solo.solo=t}get muted(){return this._solo.muted||this.mute}get mute(){return this._panVol.mute}set mute(t){this._panVol.mute=t}_getBus(t){return um.buses.has(t)||um.buses.set(t,new xd({context:this.context})),um.buses.get(t)}send(t,e=0){const s=this._getBus(t),n=new xd({context:this.context,units:"decibels",gain:e});return this.connect(n),n.connect(s),n}receive(t){return this._getBus(t).connect(this),this}dispose(){return super.dispose(),this._panVol.dispose(),this.pan.dispose(),this.volume.dispose(),this._solo.dispose(),this}}um.buses=new Map;class pm extends md{constructor(){super(Cp(pm.getDefaults(),arguments)),this.name="Mono",this.input=new xd({context:this.context}),this._merge=this.output=new M_({channels:2,context:this.context}),this.input.connect(this._merge,0,0),this.input.connect(this._merge,0,1)}dispose(){return super.dispose(),this._merge.dispose(),this.input.dispose(),this}}class dm extends md{constructor(){super(Cp(dm.getDefaults(),arguments,["lowFrequency","highFrequency"])),this.name="MultibandSplit",this.input=new xd({context:this.context}),this.output=void 0,this.low=new Nf({context:this.context,frequency:0,type:"lowpass"}),this._lowMidFilter=new Nf({context:this.context,frequency:0,type:"highpass"}),this.mid=new Nf({context:this.context,frequency:0,type:"lowpass"}),this.high=new Nf({context:this.context,frequency:0,type:"highpass"}),this._internalChannels=[this.low,this.mid,this.high];var t=Cp(dm.getDefaults(),arguments,["lowFrequency","highFrequency"]);this.lowFrequency=new Td({context:this.context,units:"frequency",value:t.lowFrequency}),this.highFrequency=new Td({context:this.context,units:"frequency",value:t.highFrequency}),this.Q=new Td({context:this.context,units:"positive",value:t.Q}),this.input.fan(this.low,this.high),this.input.chain(this._lowMidFilter,this.mid),this.lowFrequency.fan(this.low.frequency,this._lowMidFilter.frequency),this.highFrequency.fan(this.mid.frequency,this.high.frequency),this.Q.connect(this.low.Q),this.Q.connect(this._lowMidFilter.Q),this.Q.connect(this.mid.Q),this.Q.connect(this.high.Q),Gp(this,["high","mid","low","highFrequency","lowFrequency"])}static getDefaults(){return Object.assign(md.getDefaults(),{Q:1,highFrequency:2500,lowFrequency:400})}dispose(){return super.dispose(),Qp(this,["high","mid","low","highFrequency","lowFrequency"]),this.low.dispose(),this._lowMidFilter.dispose(),this.mid.dispose(),this.high.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this.Q.dispose(),this}}class fm extends md{constructor(){super(...arguments),this.name="Listener",this.positionX=new _d({context:this.context,param:this.context.rawContext.listener.positionX}),this.positionY=new _d({context:this.context,param:this.context.rawContext.listener.positionY}),this.positionZ=new _d({context:this.context,param:this.context.rawContext.listener.positionZ}),this.forwardX=new _d({context:this.context,param:this.context.rawContext.listener.forwardX}),this.forwardY=new _d({context:this.context,param:this.context.rawContext.listener.forwardY}),this.forwardZ=new _d({context:this.context,param:this.context.rawContext.listener.forwardZ}),this.upX=new _d({context:this.context,param:this.context.rawContext.listener.upX}),this.upY=new _d({context:this.context,param:this.context.rawContext.listener.upY}),this.upZ=new _d({context:this.context,param:this.context.rawContext.listener.upZ})}static getDefaults(){return Object.assign(md.getDefaults(),{positionX:0,positionY:0,positionZ:0,forwardX:0,forwardY:0,forwardZ:-1,upX:0,upY:1,upZ:0})}dispose(){return super.dispose(),this.positionX.dispose(),this.positionY.dispose(),this.positionZ.dispose(),this.forwardX.dispose(),this.forwardY.dispose(),this.forwardZ.dispose(),this.upX.dispose(),this.upY.dispose(),this.upZ.dispose(),this}}jp(t=>{t.listener=new fm({context:t})}),zp(t=>{t.listener.dispose()});class _m extends md{constructor(){super(Cp(_m.getDefaults(),arguments,["positionX","positionY","positionZ"])),this.name="Panner3D";var t=Cp(_m.getDefaults(),arguments,["positionX","positionY","positionZ"]);this._panner=this.input=this.output=this.context.createPanner(),this.panningModel=t.panningModel,this.maxDistance=t.maxDistance,this.distanceModel=t.distanceModel,this.coneOuterGain=t.coneOuterGain,this.coneOuterAngle=t.coneOuterAngle,this.coneInnerAngle=t.coneInnerAngle,this.refDistance=t.refDistance,this.rolloffFactor=t.rolloffFactor,this.positionX=new _d({context:this.context,param:this._panner.positionX,value:t.positionX}),this.positionY=new _d({context:this.context,param:this._panner.positionY,value:t.positionY}),this.positionZ=new _d({context:this.context,param:this._panner.positionZ,value:t.positionZ}),this.orientationX=new _d({context:this.context,param:this._panner.orientationX,value:t.orientationX}),this.orientationY=new _d({context:this.context,param:this._panner.orientationY,value:t.orientationY}),this.orientationZ=new _d({context:this.context,param:this._panner.orientationZ,value:t.orientationZ})}static getDefaults(){return Object.assign(md.getDefaults(),{coneInnerAngle:360,coneOuterAngle:360,coneOuterGain:0,distanceModel:"inverse",maxDistance:1e4,orientationX:0,orientationY:0,orientationZ:0,panningModel:"equalpower",positionX:0,positionY:0,positionZ:0,refDistance:1,rolloffFactor:1})}setPosition(t,e,s){return this.positionX.value=t,this.positionY.value=e,this.positionZ.value=s,this}setOrientation(t,e,s){return this.orientationX.value=t,this.orientationY.value=e,this.orientationZ.value=s,this}get panningModel(){return this._panner.panningModel}set panningModel(t){this._panner.panningModel=t}get refDistance(){return this._panner.refDistance}set refDistance(t){this._panner.refDistance=t}get rolloffFactor(){return this._panner.rolloffFactor}set rolloffFactor(t){this._panner.rolloffFactor=t}get distanceModel(){return this._panner.distanceModel}set distanceModel(t){this._panner.distanceModel=t}get coneInnerAngle(){return this._panner.coneInnerAngle}set coneInnerAngle(t){this._panner.coneInnerAngle=t}get coneOuterAngle(){return this._panner.coneOuterAngle}set coneOuterAngle(t){this._panner.coneOuterAngle=t}get coneOuterGain(){return this._panner.coneOuterGain}set coneOuterGain(t){this._panner.coneOuterGain=t}get maxDistance(){return this._panner.maxDistance}set maxDistance(t){this._panner.maxDistance=t}dispose(){return super.dispose(),this._panner.disconnect(),this.orientationX.dispose(),this.orientationY.dispose(),this.orientationZ.dispose(),this.positionX.dispose(),this.positionY.dispose(),this.positionZ.dispose(),this}}class mm extends md{constructor(){super(Cp(mm.getDefaults(),arguments)),this.name="Recorder";var t=Cp(mm.getDefaults(),arguments);this.input=new xd({context:this.context}),op(mm.supported,"Media Recorder API is not available"),this._stream=this.context.createMediaStreamDestination(),this.input.connect(this._stream),this._recorder=new MediaRecorder(this._stream.stream,{mimeType:t.mimeType})}static getDefaults(){return md.getDefaults()}get mimeType(){return this._recorder.mimeType}static get supported(){return null!==mp&&Reflect.has(mp,"MediaRecorder")}get state(){return"inactive"===this._recorder.state?"stopped":"paused"===this._recorder.state?"paused":"started"}start(){return yp(this,void 0,void 0,function*(){op("started"!==this.state,"Recorder is already started");var t=new Promise(t=>{const e=()=>{this._recorder.removeEventListener("start",e,!1),t()};this._recorder.addEventListener("start",e,!1)});return this._recorder.start(),yield t})}stop(){return yp(this,void 0,void 0,function*(){op("stopped"!==this.state,"Recorder is not started");var t=new Promise(e=>{const s=t=>{this._recorder.removeEventListener("dataavailable",s,!1),e(t.data)};this._recorder.addEventListener("dataavailable",s,!1)});return this._recorder.stop(),yield t})}pause(){return op("started"===this.state,"Recorder must be started"),this._recorder.pause(),this}dispose(){return super.dispose(),this.input.dispose(),this._stream.disconnect(),this}}class gm extends md{constructor(){super(Cp(gm.getDefaults(),arguments,["threshold","ratio"])),this.name="Compressor",this._compressor=this.context.createDynamicsCompressor(),this.input=this._compressor,this.output=this._compressor;var t=Cp(gm.getDefaults(),arguments,["threshold","ratio"]);this.threshold=new _d({minValue:this._compressor.threshold.minValue,maxValue:this._compressor.threshold.maxValue,context:this.context,convert:!1,param:this._compressor.threshold,units:"decibels",value:t.threshold}),this.attack=new _d({minValue:this._compressor.attack.minValue,maxValue:this._compressor.attack.maxValue,context:this.context,param:this._compressor.attack,units:"time",value:t.attack}),this.release=new _d({minValue:this._compressor.release.minValue,maxValue:this._compressor.release.maxValue,context:this.context,param:this._compressor.release,units:"time",value:t.release}),this.knee=new _d({minValue:this._compressor.knee.minValue,maxValue:this._compressor.knee.maxValue,context:this.context,convert:!1,param:this._compressor.knee,units:"decibels",value:t.knee}),this.ratio=new _d({minValue:this._compressor.ratio.minValue,maxValue:this._compressor.ratio.maxValue,context:this.context,convert:!1,param:this._compressor.ratio,units:"positive",value:t.ratio}),Gp(this,["knee","release","attack","ratio","threshold"])}static getDefaults(){return Object.assign(md.getDefaults(),{attack:.003,knee:30,ratio:12,release:.25,threshold:-24})}get reduction(){return this._compressor.reduction}dispose(){return super.dispose(),this._compressor.disconnect(),this.attack.dispose(),this.release.dispose(),this.threshold.dispose(),this.ratio.dispose(),this.knee.dispose(),this}}class vm extends md{constructor(){super(Object.assign(Cp(vm.getDefaults(),arguments,["threshold","smoothing"]))),this.name="Gate";var t=Cp(vm.getDefaults(),arguments,["threshold","smoothing"]);this._follower=new T_({context:this.context,smoothing:t.smoothing}),this._gt=new Sf({context:this.context,value:td(t.threshold)}),this.input=new xd({context:this.context}),this._gate=this.output=new xd({context:this.context}),this.input.connect(this._gate),this.input.chain(this._follower,this._gt,this._gate.gain)}static getDefaults(){return Object.assign(md.getDefaults(),{smoothing:.1,threshold:-40})}get threshold(){return ed(this._gt.value)}set threshold(t){this._gt.value=td(t)}get smoothing(){return this._follower.smoothing}set smoothing(t){this._follower.smoothing=t}dispose(){return super.dispose(),this.input.dispose(),this._follower.dispose(),this._gt.dispose(),this._gate.dispose(),this}}class ym extends md{constructor(){super(Object.assign(Cp(ym.getDefaults(),arguments,["threshold"]))),this.name="Limiter";var t=Cp(ym.getDefaults(),arguments,["threshold"]);this._compressor=this.input=this.output=new gm({context:this.context,ratio:20,attack:.003,release:.01,threshold:t.threshold}),this.threshold=this._compressor.threshold,Gp(this,"threshold")}static getDefaults(){return Object.assign(md.getDefaults(),{threshold:-12})}get reduction(){return this._compressor.reduction}dispose(){return super.dispose(),this._compressor.dispose(),this.threshold.dispose(),this}}class xm extends md{constructor(){super(Object.assign(Cp(xm.getDefaults(),arguments))),this.name="MidSideCompressor";var t=Cp(xm.getDefaults(),arguments);this._midSideSplit=this.input=new H_({context:this.context}),this._midSideMerge=this.output=new J_({context:this.context}),this.mid=new gm(Object.assign(t.mid,{context:this.context})),this.side=new gm(Object.assign(t.side,{context:this.context})),this._midSideSplit.mid.chain(this.mid,this._midSideMerge.mid),this._midSideSplit.side.chain(this.side,this._midSideMerge.side),Gp(this,["mid","side"])}static getDefaults(){return Object.assign(md.getDefaults(),{mid:{ratio:3,threshold:-24,release:.03,attack:.02,knee:16},side:{ratio:6,threshold:-30,release:.25,attack:.03,knee:10}})}dispose(){return super.dispose(),this.mid.dispose(),this.side.dispose(),this._midSideSplit.dispose(),this._midSideMerge.dispose(),this}}class wm extends md{constructor(){super(Object.assign(Cp(wm.getDefaults(),arguments))),this.name="MultibandCompressor";var t=Cp(wm.getDefaults(),arguments);this._splitter=this.input=new dm({context:this.context,lowFrequency:t.lowFrequency,highFrequency:t.highFrequency}),this.lowFrequency=this._splitter.lowFrequency,this.highFrequency=this._splitter.highFrequency,this.output=new xd({context:this.context}),this.low=new gm(Object.assign(t.low,{context:this.context})),this.mid=new gm(Object.assign(t.mid,{context:this.context})),this.high=new gm(Object.assign(t.high,{context:this.context})),this._splitter.low.chain(this.low,this.output),this._splitter.mid.chain(this.mid,this.output),this._splitter.high.chain(this.high,this.output),Gp(this,["high","mid","low","highFrequency","lowFrequency"])}static getDefaults(){return Object.assign(md.getDefaults(),{lowFrequency:250,highFrequency:2e3,low:{ratio:6,threshold:-30,release:.25,attack:.03,knee:10},mid:{ratio:3,threshold:-24,release:.03,attack:.02,knee:16},high:{ratio:3,threshold:-24,release:.03,attack:.02,knee:16}})}dispose(){return super.dispose(),this._splitter.dispose(),this.low.dispose(),this.mid.dispose(),this.high.dispose(),this.output.dispose(),this}}class bm extends md{constructor(){super(Cp(bm.getDefaults(),arguments,["low","mid","high"])),this.name="EQ3",this.output=new xd({context:this.context}),this._internalChannels=[];var t=Cp(bm.getDefaults(),arguments,["low","mid","high"]);this.input=this._multibandSplit=new dm({context:this.context,highFrequency:t.highFrequency,lowFrequency:t.lowFrequency}),this._lowGain=new xd({context:this.context,gain:t.low,units:"decibels"}),this._midGain=new xd({context:this.context,gain:t.mid,units:"decibels"}),this._highGain=new xd({context:this.context,gain:t.high,units:"decibels"}),this.low=this._lowGain.gain,this.mid=this._midGain.gain,this.high=this._highGain.gain,this.Q=this._multibandSplit.Q,this.lowFrequency=this._multibandSplit.lowFrequency,this.highFrequency=this._multibandSplit.highFrequency,this._multibandSplit.low.chain(this._lowGain,this.output),this._multibandSplit.mid.chain(this._midGain,this.output),this._multibandSplit.high.chain(this._highGain,this.output),Gp(this,["low","mid","high","lowFrequency","highFrequency"]),this._internalChannels=[this._multibandSplit]}static getDefaults(){return Object.assign(md.getDefaults(),{high:0,highFrequency:2500,low:0,lowFrequency:400,mid:0})}dispose(){return super.dispose(),Qp(this,["low","mid","high","lowFrequency","highFrequency"]),this._multibandSplit.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this._lowGain.dispose(),this._midGain.dispose(),this._highGain.dispose(),this.low.dispose(),this.mid.dispose(),this.high.dispose(),this.Q.dispose(),this}}class Tm extends md{constructor(){super(Cp(Tm.getDefaults(),arguments,["url","onload"])),this.name="Convolver",this._convolver=this.context.createConvolver();const e=Cp(Tm.getDefaults(),arguments,["url","onload"]);this._buffer=new Xp(e.url,t=>{this.buffer=t,e.onload()}),this.input=new xd({context:this.context}),this.output=new xd({context:this.context}),this._buffer.loaded&&(this.buffer=this._buffer),this.normalize=e.normalize,this.input.chain(this._convolver,this.output)}static getDefaults(){return Object.assign(md.getDefaults(),{normalize:!0,onload:Zp})}load(t){return yp(this,void 0,void 0,function*(){this.buffer=yield this._buffer.load(t)})}get buffer(){return this._buffer.length?this._buffer:null}set buffer(t){t&&this._buffer.set(t),this._convolver.buffer&&(this.input.disconnect(),this._convolver.disconnect(),this._convolver=this.context.createConvolver(),this.input.chain(this._convolver,this.output));t=this._buffer.get();this._convolver.buffer=t||null}get normalize(){return this._convolver.normalize}set normalize(t){this._convolver.normalize=t}dispose(){return super.dispose(),this._buffer.dispose(),this._convolver.disconnect(),this}}const Sm=Jp().transport;const km=Jp().destination,Am=Jp().destination;const Cm=Jp().listener;const Dm=Jp().draw;const Om=Jp();const Mm=Xp,Em=Md,Rm=Bd})(),Fm})()}); \ No newline at end of file diff --git a/js/Tone.min.js b/js/Tone.min.js new file mode 100644 index 0000000..b57eac5 --- /dev/null +++ b/js/Tone.min.js @@ -0,0 +1,17 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Tone=e():t.Tone=e()}("undefined"!=typeof self?self:this,()=>{var s={871:function(t,e,s){!function(t,c,s,e){"use strict";function u(t,e,s){return{endTime:e,insertTime:s,type:"exponentialRampToValue",value:t}}function p(t,e,s){return{endTime:e,insertTime:s,type:"linearRampToValue",value:t}}function d(t,e){return{startTime:e,type:"setValue",value:t}}function f(t,e,s){return{duration:s,startTime:e,type:"setValueCurve",values:t}}function l(t,e,s){var i=s.startTime,n=s.target,s=s.timeConstant;return n+(e-n)*Math.exp((i-t)/s)}function _(t){return"exponentialRampToValue"===t.type}function m(t){return"linearRampToValue"===t.type}function g(t){return _(t)||m(t)}function v(t){return"setValue"===t.type}function y(t){return"setValueCurve"===t.type}function x(t,e,s,i){var n=t[e];return void 0===n?i:g(n)||v(n)?n.value:y(n)?n.values[n.values.length-1]:l(s,x(t,e-1,n.startTime,i),n)}function w(t,e,s,i,n){return void 0===s?[i.insertTime,n]:g(s)?[s.endTime,s.value]:v(s)?[s.startTime,s.value]:y(s)?[s.startTime+s.duration,s.values[s.values.length-1]]:[s.startTime,x(t,e-1,s.startTime,n)]}function b(t){return"cancelAndHold"===t.type}function T(t){return"cancelScheduledValues"===t.type}function S(t){return b(t)||T(t)?t.cancelTime:_(t)||m(t)?t.endTime:t.startTime}function k(t,e,s,i){var n=i.endTime,i=i.value;return s===i?i:0=s:S(t)>=s}),i=this._automationEvents[t];if(-1!==t&&(this._automationEvents=this._automationEvents.slice(0,t)),b(e)){var n=this._automationEvents[this._automationEvents.length-1];if(void 0!==i&&g(i)){if(void 0!==n&&C(n))throw new Error("The internal list is malformed.");var t=void 0===n?i.insertTime:y(n)?n.startTime+n.duration:S(n),r=void 0===n?this._defaultValue:y(n)?n.values[n.values.length-1]:n.value,t=(_(i)?k:A)(s,t,r,i),r=(_(i)?u:p)(t,s,this._currenTime);this._automationEvents.push(r)}if(void 0!==n&&C(n)&&this._automationEvents.push(d(this.getValue(s),s)),void 0!==n&&y(n)&&n.startTime+n.duration>s){var i=s-n.startTime,t=(n.values.length-1)/n.duration,o=Math.max(2,1+Math.ceil(i*t)),a=i/(o-1)*t,h=n.values.slice(0,o);if(a<1)for(var c=1;cs}),t=-1===r?this._automationEvents[this._automationEvents.length-1]:this._automationEvents[r-1];if(void 0!==t&&y(t)&&S(t)+t.duration>s)return!1;i=_(e)?u(e.value,e.endTime,this._currenTime):m(e)?p(e.value,s,this._currenTime):e;if(-1===r)this._automationEvents.push(i);else{if(y(e)&&s+e.duration>S(this._automationEvents[r]))return!1;this._automationEvents.splice(r,0,i)}}return!0}},{key:"flush",value:function(e){var t,s,i=this._automationEvents.findIndex(function(t){return S(t)>e});1e}),a=this._automationEvents[o],o=(-1===o?this._automationEvents.length:o)-1,h=this._automationEvents[o];return void 0!==h&&C(h)&&(void 0===a||!g(a)||a.insertTime>e)?l(e,x(this._automationEvents,o-1,h.startTime,this._defaultValue),h):void 0===h||!v(h)||void 0!==a&&g(a)?void 0!==h&&y(h)&&(void 0===a||!g(a)||h.startTime+h.duration>e)?e{t.exports=function(t,e){(null==e||e>t.length)&&(e=t.length);for(var s=0,i=new Array(e);s{t.exports=function(t){if(Array.isArray(t))return t},t.exports.__esModule=!0,t.exports.default=t.exports},805:t=>{t.exports=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},t.exports.__esModule=!0,t.exports.default=t.exports},989:(t,e,s)=>{var n=s(498);function i(t,e){for(var s=0;s{t.exports=function(t,e){var s=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=s){var i,n,r,o,a=[],h=!0,c=!1;try{if(r=(s=s.call(t)).next,0===e){if(Object(s)!==s)return;h=!1}else for(;!(h=(i=r.call(s)).done)&&(a.push(i.value),a.length!==e);h=!0);}catch(t){c=!0,n=t}finally{try{if(!h&&null!=s.return&&(o=s.return(),Object(o)!==o))return}finally{if(c)throw n}}return a}},t.exports.__esModule=!0,t.exports.default=t.exports},18:t=>{t.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},t.exports.__esModule=!0,t.exports.default=t.exports},821:(t,e,s)=>{var i=s(569),n=s(474),r=s(744),o=s(18);t.exports=function(t,e){return i(t)||n(t,e)||r(t,e)||o()},t.exports.__esModule=!0,t.exports.default=t.exports},327:(t,e,s)=>{var i=s(564).default;t.exports=function(t,e){if("object"!=i(t)||!t)return t;var s=t[Symbol.toPrimitive];if(void 0===s)return("string"===e?String:Number)(t);s=s.call(t,e||"default");if("object"!=i(s))return s;throw new TypeError("@@toPrimitive must return a primitive value.")},t.exports.__esModule=!0,t.exports.default=t.exports},498:(t,e,s)=>{var i=s(564).default,n=s(327);t.exports=function(t){t=n(t,"string");return"symbol"==i(t)?t:t+""},t.exports.__esModule=!0,t.exports.default=t.exports},564:e=>{function s(t){return e.exports=s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},e.exports.__esModule=!0,e.exports.default=e.exports,s(t)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports},744:(t,e,s)=>{var i=s(113);t.exports=function(t,e){if(t){if("string"==typeof t)return i(t,e);var s=Object.prototype.toString.call(t).slice(8,-1);return"Map"===(s="Object"===s&&t.constructor?t.constructor.name:s)||"Set"===s?Array.from(t):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?i(t,e):void 0}},t.exports.__esModule=!0,t.exports.default=t.exports}},i={};function Dm(t){var e=i[t];if(void 0!==e)return e.exports;e=i[t]={exports:{}};return s[t].call(e.exports,e,e.exports,Dm),e.exports}Dm.d=(t,e)=>{for(var s in e)Dm.o(e,s)&&!Dm.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},Dm.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Dm.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var Mm={};return(()=>{"use strict";Dm.r(Mm),Dm.d(Mm,{AMOscillator:()=>nf,AMSynth:()=>Ff,Abs:()=>xf,Add:()=>uf,AmplitudeEnvelope:()=>Rf,Analyser:()=>em,AudioToGain:()=>sf,AutoFilter:()=>v_,AutoPanner:()=>x_,AutoWah:()=>b_,BaseContext:()=>sd,BiquadFilter:()=>Vf,BitCrusher:()=>S_,Buffer:()=>Am,BufferSource:()=>Om,Buffers:()=>Cm,Channel:()=>hm,Chebyshev:()=>A_,Chorus:()=>E_,Clock:()=>Ed,Compressor:()=>dm,Context:()=>id,Convolver:()=>ym,CrossFade:()=>m_,DCMeter:()=>rm,Delay:()=>Rd,Destination:()=>wm,Distortion:()=>R_,Draw:()=>Sm,DuoSynth:()=>Lf,EQ3:()=>vm,Emitter:()=>ed,Envelope:()=>Of,FFT:()=>nm,FMOscillator:()=>rf,FMSynth:()=>zf,FatOscillator:()=>af,FeedbackCombFilter:()=>$f,FeedbackDelay:()=>I_,Filter:()=>Nf,Follower:()=>w_,Freeverb:()=>j_,Frequency:()=>function(t,e){return new vd(b(),t,e)},FrequencyClass:()=>vd,FrequencyEnvelope:()=>Pf,FrequencyShifter:()=>V_,Gain:()=>C,GainToAudio:()=>wf,Gate:()=>fm,GrainPlayer:()=>yf,GreaterThan:()=>kf,GreaterThanZero:()=>Sf,IntervalTimeline:()=>jd,JCReverb:()=>B_,LFO:()=>ff,Limiter:()=>_m,Listener:()=>Tm,Loop:()=>n_,LowpassCombFilter:()=>Kf,Master:()=>bm,MembraneSynth:()=>Uf,Merge:()=>O_,MetalSynth:()=>Bf,Meter:()=>im,MidSideCompressor:()=>mm,MidSideMerge:()=>H_,MidSideSplit:()=>Y_,Midi:()=>function(t,e){return new Nd(b(),t,e)},MidiClass:()=>Nd,Mono:()=>cm,MonoSynth:()=>jf,MultibandCompressor:()=>gm,MultibandSplit:()=>lm,Multiply:()=>q,Negate:()=>bf,Noise:()=>Yd,NoiseSynth:()=>Gf,Offline:()=>function(t,e){return _(this,arguments,void 0,function*(t,e,s=2,i=b().sampleRate){const n=b(),r=new rd(s,e,i);hd(r),yield t(r);s=r.render(),hd(n),e=yield s;return new w(e)})},OfflineContext:()=>rd,OmniOscillator:()=>lf,OnePoleFilter:()=>Jf,Oscillator:()=>E,PWMOscillator:()=>hf,PanVol:()=>am,Panner:()=>y_,Panner3D:()=>um,Param:()=>k,Part:()=>r_,Pattern:()=>f_,Phaser:()=>Z_,PingPongDelay:()=>G_,PitchShift:()=>Q_,Player:()=>gf,Players:()=>vf,PluckSynth:()=>t_,PolySynth:()=>e_,Pow:()=>Ud,PulseOscillator:()=>of,Recorder:()=>pm,Reverb:()=>X_,Sampler:()=>s_,Scale:()=>pf,ScaleExp:()=>Af,Sequence:()=>__,Signal:()=>O,Solo:()=>F,Split:()=>C_,StateTimeline:()=>wd,StereoWidener:()=>J_,Subtract:()=>Tf,SyncedSignal:()=>Cf,Synth:()=>qf,Ticks:()=>function(t,e){return new D(b(),t,e)},TicksClass:()=>D,Time:()=>function(t,e){return new gd(b(),t,e)},TimeClass:()=>gd,Timeline:()=>Hp,ToneAudioBuffer:()=>w,ToneAudioBuffers:()=>Vd,ToneAudioNode:()=>A,ToneBufferSource:()=>Xd,ToneEvent:()=>i_,ToneOscillatorNode:()=>ef,Transport:()=>xm,TransportTime:()=>function(t,e){return new T(b(),t,e)},TransportTimeClass:()=>T,Tremolo:()=>K_,Unit:()=>N,UserMedia:()=>Kd,Vibrato:()=>tm,Volume:()=>qd,WaveShaper:()=>Bd,Waveform:()=>om,Zero:()=>df,connect:()=>Td,connectSeries:()=>bd,connectSignal:()=>Cd,context:()=>km,dbToGain:()=>cd,debug:()=>V,defaultArg:()=>Wp,disconnect:()=>Sd,fanIn:()=>function(...t){const e=t.pop();o(e)&&t.forEach(t=>Td(t,e))},ftom:()=>dd,gainToDb:()=>ld,getContext:()=>b,getDestination:()=>function(){return b().destination},getDraw:()=>function(){return b().draw},getListener:()=>function(){return b().listener},getTransport:()=>function(){return b().transport},immediate:()=>function(){return b().immediate()},intervalToFrequencyRatio:()=>ud,isArray:()=>d,isBoolean:()=>bp,isDefined:()=>o,isFunction:()=>yp,isNote:()=>Sp,isNumber:()=>xp,isObject:()=>wp,isString:()=>Tp,isUndef:()=>vp,loaded:()=>function(){return w.loaded()},mtof:()=>_d,now:()=>function(){return b().now()},optionsFromArguments:()=>g,setContext:()=>hd,start:()=>function(){return ad.resume()},supported:()=>gp,version:()=>P});var V={},N=(Dm.r(V),Dm.d(V,{assert:()=>l,assertContextRunning:()=>kp,assertRange:()=>f,assertUsedScheduleTime:()=>Dp,enterScheduledCallback:()=>Op,log:()=>Ep,setLogger:()=>function(t){Mp=t},warn:()=>Rp}),{});Dm.r(N);const P="15.1.3";var j,L,z,W,B,U,G,Q,Z,X,Y,H,$,J,K,tt,et,st,it,nt,rt,ot,at,ht,ct,lt,ut,pt,dt,ft,_t,mt,gt,vt,yt,xt,wt,bt,Tt,St,kt,At,Ct,Ot,Dt,Mt,Et,Rt,qt,It,Ft,Vt,Nt,Pt=Dm(871);const jt=new WeakSet,Lt=new WeakMap,zt=new WeakMap,Wt=new WeakMap,Bt=new WeakMap,Ut=new WeakMap,Gt=new WeakMap,Qt=new WeakMap,Zt=new WeakMap,Xt=new WeakMap,Yt={construct:()=>Yt},Ht=/^import(?:(?:[\s]+[\w]+|(?:[\s]+[\w]+[\s]*,)?[\s]*\{[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?(?:[\s]*,[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?)*[\s]*}|(?:[\s]+[\w]+[\s]*,)?[\s]*\*[\s]+as[\s]+[\w]+)[\s]+from)?(?:[\s]*)("([^"\\]|\\.)+"|'([^'\\]|\\.)+')(?:[\s]*);?/,$t=(t,e)=>{const s=[];let i=t.replace(/^[\s]+/,""),n=i.match(Ht);for(;null!==n;){const t=n[1].slice(1,-1),r=n[0].replace(/([\s]+)?;?$/,"").replace(t,new URL(t,e).toString());s.push(r),i=i.slice(n[0].length).replace(/^[\s]+/,""),n=i.match(Ht)}return[s.join(";"),i]},Jt=t=>{if(void 0!==t&&!Array.isArray(t))throw new TypeError("The parameterDescriptors property of given value for processorCtor is not an array.")},Kt=t=>{if(!(t=>{try{new new Proxy(t,Yt)}catch{return!1}return!0})(t))throw new TypeError("The given value for processorCtor should be a constructor.");if(null===t.prototype||"object"!=typeof t.prototype)throw new TypeError("The given value for processorCtor should have a prototype.")},te=(t,e)=>{t=t.get(e);if(void 0===t)throw new Error("A value with the given key could not be found.");return t},ee=(t,e)=>{e=Array.from(t).filter(e);if(1{var n=te(t,e),r=ee(n,t=>t[0]===s&&t[1]===i);return 0===n.size&&t.delete(e),r},ie=t=>te(Gt,t),ne=t=>{if(jt.has(t))throw new Error("The AudioNode is already stored.");jt.add(t),ie(t).forEach(t=>t(!0))},re=t=>"port"in t,oe=t=>{if(!jt.has(t))throw new Error("The AudioNode is not stored.");jt.delete(t),ie(t).forEach(t=>t(!1))},ae=(t,e)=>{!re(t)&&e.every(t=>0===t.size)&&oe(t)},he={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",fftSize:2048,maxDecibels:-30,minDecibels:-100,smoothingTimeConstant:.8},u=(t,e)=>t.context===e,ce=t=>{try{t.copyToChannel(new Float32Array(1),0,-1)}catch{return!1}return!0},le=()=>new DOMException("","IndexSizeError"),ue=e=>{var s;e.getChannelData=(s=e.getChannelData,t=>{try{return s.call(e,t)}catch(t){if(12===t.code)throw le();throw t}})},pe={numberOfChannels:1},de=-34028234663852886e22,fe=-de,_e=t=>jt.has(t),me={buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1},ge=t=>te(Lt,t),ve=t=>te(Wt,t),ye=(e,s)=>{const t=ge(e)["activeInputs"];t.forEach(t=>t.forEach(([t])=>{s.includes(e)||ye(t,[...s,e])}));var i="playbackRate"in e?[e.playbackRate]:re(e)?Array.from(e.parameters.values()):"frequency"in(i=e)&&"gain"in i?[e.Q,e.detune,e.frequency,e.gain]:"offset"in e?[e.offset]:!("frequency"in(i=e))&&"gain"in i?[e.gain]:"detune"in(i=e)&&"frequency"in i?[e.detune,e.frequency]:"pan"in e?[e.pan]:[];for(const e of i){const t=ve(e);void 0!==t&&t.activeInputs.forEach(([t])=>ye(t,s))}_e(e)&&oe(e)},xe=t=>{ye(t.destination,[])},we=t=>"context"in t,be=t=>we(t[0]),Te=(t,e,s,i)=>{for(const e of t)if(s(e)){if(i)return!1;throw Error("The set contains at least one similar element.")}return t.add(e),!0},Se=(t,e,[s,i],n)=>{Te(t,[e,s,i],t=>t[0]===e&&t[1]===s,n)},ke=(t,[e,s,i],n)=>{var r=t.get(e);void 0===r?t.set(e,new Set([[s,i]])):Te(r,[s,i],t=>t[0]===s,n)},Ae=t=>"inputs"in t,Ce=(t,e,s,i)=>{var n;return Ae(e)?(n=e.inputs[i],t.connect(n,s,0),[n,s,0]):(t.connect(e,s,i),[e,s,i])},Oe=(t,e,s)=>{for(const i of t)if(i[0]===e&&i[1]===s)return t.delete(i),i;return null},De=(t,e)=>{if(!ie(t).delete(e))throw new Error("Missing the expected event listener.")},Me=(t,e,s)=>{var i=te(t,e),n=ee(i,t=>t[0]===s);return 0===i.size&&t.delete(e),n},Ee=(t,e,s,i)=>{Ae(e)?t.disconnect(e.inputs[i],s,0):t.disconnect(e,s,i)},m=t=>te(zt,t),Re=t=>te(Bt,t),qe=t=>Qt.has(t),Ie=t=>!jt.has(t),Fe=(r,o)=>new Promise(e=>{if(null!==o)e(!0);else{const o=r.createScriptProcessor(256,1,1),t=r.createGain(),s=r.createBuffer(1,2,44100),i=s.getChannelData(0),n=(i[0]=1,i[1]=1,r.createBufferSource());n.buffer=s,n.loop=!0,n.connect(o).connect(r.destination),n.connect(t),n.disconnect(t),o.onaudioprocess=t=>{t=t.inputBuffer.getChannelData(0);Array.prototype.some.call(t,t=>1===t)?e(!0):e(!1),n.stop(),o.onaudioprocess=null,n.disconnect(o),o.disconnect(r.destination)},n.start()}}),Ve=(t,s)=>{const e=new Map;for(const s of t)for(const t of s){const s=e.get(t);e.set(t,void 0===s?1:s+1)}e.forEach((t,e)=>s(e,t))},Ne=t=>"context"in t,Pe=(t,e,s,i,n)=>{var[r,o]=((t,e,s,i)=>{var{activeInputs:e,passiveInputs:n}=ge(e),e=Oe(e[i],t,s);return null===e?[se(n,t,s,i)[2],!1]:[e[2],!0]})(t,s,i,n);if(null!==r&&(De(t,r),!o||e||qe(t)||Ee(m(t),m(s),i,n)),_e(s)){const t=ge(s)["activeInputs"];ae(s,t)}},je=(t,e,s,i)=>{var[n,r]=((t,e,s)=>{var{activeInputs:e,passiveInputs:i}=ve(e),e=Oe(e,t,s);return null===e?[Me(i,t,s)[1],!1]:[e[2],!0]})(t,s,i);null!==n&&(De(t,n),!r||e||qe(t)||m(t).disconnect(Re(s),i))};class Le{constructor(t){this._map=new Map(t)}get size(){return this._map.size}entries(){return this._map.entries()}forEach(s,i=null){return this._map.forEach((t,e)=>s.call(i,t,e,this))}get(t){return this._map.get(t)}has(t){return this._map.has(t)}keys(){return this._map.keys()}values(){return this._map.values()}}const ze={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:1,numberOfOutputs:1,parameterData:{},processorOptions:{}};function We(t,e,s,i,n){if("function"==typeof t.copyFromChannel)0===e[s].byteLength&&(e[s]=new Float32Array(128)),t.copyFromChannel(e[s],i,n);else{const r=t.getChannelData(i);if(0===e[s].byteLength)e[s]=r.slice(n,n+128);else{const t=new Float32Array(r.buffer,n*Float32Array.BYTES_PER_ELEMENT,128);e[s].set(t)}}}const Be=(t,e,s,i,n)=>{"function"==typeof t.copyToChannel?0!==e[s].byteLength&&t.copyToChannel(e[s],i,n):0!==e[s].byteLength&&t.getChannelData(i).set(e[s],n)},Ue=(e,s)=>{const i=[];for(let t=0;t{const{port1:i,port2:n}=new MessageChannel;return new Promise(t=>{const e=()=>{n.onmessage=null,i.close(),n.close(),t()};n.onmessage=()=>e();try{i.postMessage(s,[s])}catch{}finally{e()}})},$e={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",delayTime:0,maxDelayTime:1},Je=(t,e,s)=>{e=e[s];if(void 0===e)throw t();return e},Ke={attack:.003,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",knee:30,ratio:12,release:.25,threshold:-24},ts={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",gain:1},a=()=>new DOMException("","InvalidStateError"),es=()=>new DOMException("","InvalidAccessError"),ss={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers"},is=(s,i,n,r,o,a,h,t,c,l,u)=>{var e=l.length;let p=t;for(let t=0;t{var e=new Uint32Array([1179011410,40,1163280727,544501094,16,131073,44100,176400,1048580,1635017060,4,0]);try{const s=t.decodeAudioData(e.buffer,()=>{});return void 0!==s&&(s.catch(()=>{}),!0)}catch{}return!1},h=(t,e,s)=>{e=e[s];void 0!==e&&e!==t[s]&&(t[s]=e)},R=(t,e)=>{h(t,e,"channelCount"),h(t,e,"channelCountMode"),h(t,e,"channelInterpretation")},os=t=>"function"==typeof t.getFloatTimeDomainData,i=(t,e,s)=>{e=e[s];void 0!==e&&e!==t[s].value&&(t[s].value=e)},as=i=>{var n;i.start=(n=i.start,(t=0,e=0,s)=>{if("number"==typeof s&&s<0||e<0||t<0)throw new RangeError("The parameters can't be negative.");n.call(i,t,e,s)})},hs=e=>{var s;e.stop=(s=e.stop,(t=0)=>{if(t<0)throw new RangeError("The parameter can't be negative.");s.call(e,t)})},cs=(t,e)=>null===t?512:Math.max(512,Math.min(16384,Math.pow(2,Math.round(Math.log2(t*e))))),ls=(t,e)=>{t=t.createBiquadFilter();return R(t,e),i(t,e,"Q"),i(t,e,"detune"),i(t,e,"frequency"),i(t,e,"gain"),h(t,e,"type"),t},us=(t,e)=>{t=t.createChannelSplitter(e.numberOfOutputs);R(t,e);{const s=(e=t).numberOfOutputs;Object.defineProperty(e,"channelCount",{get:()=>s,set:t=>{if(t!==s)throw a()}}),Object.defineProperty(e,"channelCountMode",{get:()=>"explicit",set:t=>{if("explicit"!==t)throw a()}}),Object.defineProperty(e,"channelInterpretation",{get:()=>"discrete",set:t=>{if("discrete"!==t)throw a()}})}return t},ps=(t,e)=>(t.connect=e.connect.bind(e),t.disconnect=e.disconnect.bind(e),t),ds=(t,e)=>{t=t.createDelay(e.maxDelayTime);return R(t,e),i(t,e,"delayTime"),t},fs=(t,e)=>{t=t.createGain();return R(t,e),i(t,e,"gain"),t};function _s(e,s){let i=[0,0];for(let t=e.length-1;0<=t;--t)(i=[(n=i)[0]*s[0]-n[1]*s[1],n[0]*s[1]+n[1]*s[0]])[0]+=e[t];var n;return i}const ms=(t,e,s,i)=>t.createScriptProcessor(e,s,i),gs=()=>new DOMException("","NotSupportedError"),vs={numberOfChannels:1},ys={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:440,periodicWave:void 0,type:"sine"},xs={channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",coneInnerAngle:360,coneOuterAngle:360,coneOuterGain:0,distanceModel:"inverse",maxDistance:1e4,orientationX:1,orientationY:0,orientationZ:0,panningModel:"equalpower",positionX:0,positionY:0,positionZ:0,refDistance:1,rolloffFactor:1},ws={disableNormalization:!1},bs={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",pan:0},Ts={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",curve:null,oversample:"none"},Ss=(t,e,s)=>void 0===t.copyFromChannel?t.getChannelData(s)[0]:(t.copyFromChannel(e,s),e[0]),ks=t=>{if(null===t)return!1;var e=t.length;return e%2!=0?0!==t[Math.floor(e/2)]:t[e/2-1]+t[e/2]!==0},As=(t,e,s,i)=>{let n=t;for(;!n.hasOwnProperty(e);)n=Object.getPrototypeOf(n);var{get:r,set:o}=Object.getOwnPropertyDescriptor(n,e);Object.defineProperty(t,e,{get:s(r),set:i(o)})},Cs=(e,s,i)=>{try{e.setValueAtTime(s,i)}catch(t){if(9!==t.code)throw t;Cs(e,s,i+1e-7)}},Os=t=>{const e=t.createOscillator();try{e.start(-1)}catch(t){return t instanceof RangeError}return!1},Ds=t=>{const e=t.createBuffer(1,1,44100),s=t.createBufferSource();s.buffer=e,s.start(),s.stop();try{return s.stop(),!0}catch{return!1}},Ms=t=>{const e=t.createOscillator();try{e.stop(-1)}catch(t){return t instanceof RangeError}return!1},Es=()=>{try{new DOMException}catch{return!1}return!0},Rs=()=>new Promise(e=>{const t=new ArrayBuffer(0),{port1:s,port2:i}=new MessageChannel;s.onmessage=({data:t})=>e(null!==t),i.postMessage(t,[t])}),qs=(i,t)=>{const n=t.createGain(),e=(i.connect(n),s=i.disconnect,()=>{s.call(i,n),i.removeEventListener("ended",e)});var s;i.addEventListener("ended",e),ps(i,n),i.stop=(e=>{let s=!1;return(t=0)=>{if(s)try{e.call(i,t)}catch{n.gain.setValueAtTime(0,t)}else e.call(i,t),s=!0}})(i.stop)},Is=(s,i)=>t=>{var e={value:s};return Object.defineProperties(t,{currentTarget:e,target:e}),("function"==typeof i?i:i.handleEvent).call(s,t)},Fs=(W=Te,(t,e,[s,i,n],r)=>{W(t[i],[e,s,n],t=>t[0]===e&&t[1]===s,r)}),Vs=(z=Te,(t,e,[s,i,n],r)=>{var o=t.get(s);void 0===o?t.set(s,new Set([[i,e,n]])):z(o,[i,e,n],t=>t[0]===i&&t[1]===e,r)}),Ns=(L=ee,(t,e,s,i)=>L(t[i],t=>t[0]===e&&t[1]===s)),Ps=new WeakMap,js=(j=Ps,t=>{return null!=(t=j.get(t))?t:0}),Ls=(B=new Map,U=new WeakMap,(e,t)=>{const s=U.get(e);if(void 0!==s)return s;var i=B.get(e);if(void 0!==i)return i;try{const s=t();return s instanceof Promise?(B.set(e,s),s.catch(()=>!1).then(t=>(B.delete(e),U.set(e,t),t))):(U.set(e,s),s)}catch{return U.set(e,!1),!1}}),zs="undefined"==typeof window?null:window,Ws=(J=Ls,K=le,(t,e)=>{const s=t.createAnalyser();if(R(s,e),e.maxDecibels>e.minDecibels)return h(s,e,"fftSize"),h(s,e,"maxDecibels"),h(s,e,"minDecibels"),h(s,e,"smoothingTimeConstant"),J(os,()=>os(s))||((n=s).getFloatTimeDomainData=e=>{var s=new Uint8Array(e.length),i=(n.getByteTimeDomainData(s),Math.max(s.length,n.fftSize));for(let t=0;t{t=$(t);if(null===t.renderer)throw new Error("Missing the renderer of the given AudioNode in the audio graph.");return t.renderer}),Us=(X=ge,Y=Bs,H=qe,async(o,a,h)=>{const t=X(o);await Promise.all(t.activeInputs.map((t,r)=>Array.from(t).map(async([t,e])=>{const s=Y(t),i=await s.render(t,a),n=o.context.destination;H(t)||o===n&&H(o)||i.connect(h,e,r)})).reduce((t,e)=>[...t,...e],[]))}),Gs=(G=Ws,Q=m,Z=Us,()=>{const i=new WeakMap;return{render(t,e){var s=i.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=Q(t);if(!u(s,e)){const Q={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,fftSize:s.fftSize,maxDecibels:s.maxDecibels,minDecibels:s.minDecibels,smoothingTimeConstant:s.smoothingTimeConstant};s=G(e,Q)}return i.set(e,s),await Z(t,e,s),s})(t,e)}}}),Qs=(tt=Ut,t=>{t=tt.get(t);if(void 0===t)throw a();return t}),t=null===(s=zs)?null:s.hasOwnProperty("OfflineAudioContext")?s.OfflineAudioContext:s.hasOwnProperty("webkitOfflineAudioContext")?s.webkitOfflineAudioContext:null,Zs=(Vt=t,t=>null!==Vt&&t instanceof Vt),Xs=new WeakMap,Ys=(Ft=Is,class{constructor(t){this._nativeEventTarget=t,this._listeners=new WeakMap}addEventListener(e,s,i){if(null!==s){let t=this._listeners.get(s);void 0===t&&(t=Ft(this,s),"function"==typeof s&&this._listeners.set(s,t)),this._nativeEventTarget.addEventListener(e,t,i)}}dispatchEvent(t){return this._nativeEventTarget.dispatchEvent(t)}removeEventListener(t,e,s){e=null===e?void 0:this._listeners.get(e);this._nativeEventTarget.removeEventListener(t,void 0===e?null:e,s)}}),Hs=null===(s=zs)?null:s.hasOwnProperty("AudioContext")?s.AudioContext:s.hasOwnProperty("webkitAudioContext")?s.webkitAudioContext:null,$s=(It=Hs,t=>null!==It&&t instanceof It),Js=(qt=zs,t=>null!==qt&&"function"==typeof qt.AudioNode&&t instanceof qt.AudioNode),Ks=(Rt=zs,t=>null!==Rt&&"function"==typeof Rt.AudioParam&&t instanceof Rt.AudioParam),ti=null!==(s=zs)&&s.hasOwnProperty("AudioWorkletNode")?s.AudioWorkletNode:null,e=(Nt=Lt,et=((l,u,p,d,f,_,m,g,v,y,x,w,b)=>{const T=new WeakMap;return(i,n,r,o,a)=>{const{activeInputs:h,passiveInputs:c}=_(n),t=_(i)["outputs"],e=g(i),s=t=>{var e=v(n),s=v(i);if(t){const u=se(c,i,r,o);l(h,i,u,!1),a||w(i)||p(s,e,r,o),b(n)&&ne(n)}else{const l=d(h,i,r,o),p=(u(c,o,l,!1),a||w(i)||f(s,e,r,o),m(n));if(0===p)x(n)&&ae(n,h);else{const l=T.get(n);void 0!==l&&clearTimeout(l),T.set(n,setTimeout(()=>{x(n)&&ae(n,h)},1e3*p))}}};return!!y(t,[n,r,o],t=>t[0]===n&&t[1]===r&&t[2]===o,!0)&&(e.add(s),x(i)?l(h,i,[r,o,s],!0):u(c,o,[i,r,s],!0),!0)}})(Fs,Vs,Ce,Ns,Ee,ge,js,ie,m,Te,_e,qe,Ie),st=Ls,At=Qt,Ct=Ee,Ot=ge,Dt=m,Mt=Re,Et=_e,it=i=>(t,e)=>{var s=At.get(t);if(void 0===s){if(!i&&Et(t)){const At=Dt(t),Et=Ot(t)["outputs"];for(const Ot of Et)if(be(Ot)){const Mt=Dt(Ot[0]);Ct(At,Mt,Ot[1],Ot[2])}else{const Ct=Mt(Ot[0]);At.disconnect(Ct,Ot[1])}}At.set(t,e)}else At.set(t,s+e)},nt=le,rt=es,ot=gs,vt=Ce,yt=Qt,xt=ge,wt=m,bt=Re,Tt=Qs,St=_e,kt=Zs,at=(t,e)=>{var s=yt.get(t);if(void 0===s)throw new Error("Missing the expected cycle count.");var i=Tt(t.context),i=kt(i);if(s===e){if(yt.delete(t),!i&&St(t)){const yt=wt(t),Tt=xt(t)["outputs"];for(const xt of Tt)if(be(xt)){const bt=wt(xt[0]);vt(yt,bt,xt[1],xt[2])}else{const vt=bt(xt[0]);yt.connect(vt,xt[1])}}}else yt.set(t,s-e)},_t=Xs,mt=ge,gt=te,ht=function e(s,t){const i=we(t)?t:gt(_t,t);if("delayTime"in i)return[];if(s[0]===i)return[s];if(s.includes(i))return[];t=mt(i).outputs;return Array.from(t).map(t=>e([...s,i],t[0])).reduce((t,e)=>t.concat(e),[])},s=Ys,lt=$s,ut=Js,pt=Ks,ft=ti,class extends s{constructor(t,e,s,i){super(s),this._context=t,this._nativeAudioNode=s;const n=ct(t);if(lt(n)&&!0!==st(Fe,()=>Fe(n,ft))){var r=s,o,a;const c=new Map;r.connect=(a=r.connect.bind(r),(t,e=0,s=0)=>{const i=Ne(t)?a(t,e,s):a(t,e),n=c.get(t);return void 0===n?c.set(t,[{input:s,output:e}]):n.every(t=>t.input!==s||t.output!==e)&&n.push({input:s,output:e}),i}),r.disconnect=(o=r.disconnect,(e,s,i)=>{if(o.apply(r),void 0===e)c.clear();else if("number"==typeof e)for(const[r,o]of c){const s=o.filter(t=>t.output!==e);0===s.length?c.delete(r):c.set(r,s)}else if(c.has(e))if(void 0===s)c.delete(e);else{const r=c.get(e);if(void 0!==r){const o=r.filter(t=>t.output!==s&&(t.input!==i||void 0===i));0===o.length?c.delete(e):c.set(e,o)}}for(const[o,e]of c)e.forEach(t=>{Ne(o)?r.connect(o,t.output,t.input):r.connect(o,t.output)})})}zt.set(this,s),Gt.set(this,new Set),"closed"!==t.state&&e&&ne(this);{t=this,e=i;var h=s;const l=[];for(let t=0;t=this._nativeAudioNode.numberOfOutputs)throw nt();var i=ct(this._context),i=dt(i);if(ut(t)||pt(t))throw rt();if(we(t)){const nt=m(t);try{const et=Ce(this._nativeAudioNode,nt,e,s),it=Ie(this);(i||it)&&this._nativeAudioNode.disconnect(...et),"closed"!==this.context.state&&!it&&Ie(t)&&ne(t)}catch(t){if(12===t.code)throw rt();throw t}if(et(this,t,e,s,i)){const et=ht([this],t);Ve(et,it(i))}return t}s=Re(t);if("playbackRate"===s.name&&1024===s.maxValue)throw ot();try{this._nativeAudioNode.connect(s,e),(i||Ie(this))&&this._nativeAudioNode.disconnect(s,e)}catch(t){if(12===t.code)throw rt();throw t}if(((r,o,a,h)=>{const{activeInputs:c,passiveInputs:l}=ve(o),t=ge(r)["outputs"],e=ie(r),s=t=>{const e=m(r),s=Re(o);if(t){const o=Me(l,r,a);Se(c,r,o,!1),h||qe(r)||e.connect(s,a)}else{t=c,i=r,n=a;const o=ee(t,t=>t[0]===i&&t[1]===n);ke(l,o,!1),h||qe(r)||e.disconnect(s,a)}var i,n};return!!Te(t,[o,a],t=>t[0]===o&&t[1]===a,!0)&&(e.add(s),_e(r)?Se(c,r,[a,s],!0):ke(l,[r,a,s],!0),!0)})(this,t,e,i)){const et=ht([this],t);Ve(et,it(i))}}disconnect(t,e,s){let i;var n=ct(this._context),n=dt(n);if(void 0===t)i=((t,e)=>{const s=ge(t),i=[];for(const n of s.outputs)(be(n)?Pe:je)(t,e,...n),i.push(n[0]);return s.outputs.clear(),i})(this,n);else if("number"==typeof t){if(t<0||t>=this.numberOfOutputs)throw nt();i=((t,e,s)=>{const i=ge(t),n=[];for(const r of i.outputs)r[1]===s&&((be(r)?Pe:je)(t,e,...r),n.push(r[0]),i.outputs.delete(r));return n})(this,n,t)}else{if(void 0!==e&&(e<0||e>=this.numberOfOutputs))throw nt();if(we(t)&&void 0!==s&&(s<0||s>=t.numberOfInputs))throw nt();if(0===(i=((e,s,i,n,r)=>{const o=ge(e);return Array.from(o.outputs).filter(t=>!(t[0]!==i||void 0!==n&&t[1]!==n||void 0!==r&&t[2]!==r)).map(t=>((be(t)?Pe:je)(e,s,...t),o.outputs.delete(t),t[0]))})(this,n,t,e,s)).length)throw rt()}for(const t of i){const e=ht([this],t);Ve(e,at)}}});s=e,ei=Gs,si=le,ii=Ws,ni=ct=Qs,ri=dt=Zs;var ei,si,ii,ni,ri,oi,ai,hi,ci,li,ui,pi,di,fi,_i,mi,gi,vi,yi,xi,wi,bi,Ti,Si,ki,Ai,Ci,Oi,Di,Mi,Ei,Ri,qi,Ii,Fi,Vi,Ni,Pi,ji,Li,zi,Wi,Bi,Ui,Gi,Qi,Zi,Xi,Yi,Hi,$i,Ji,Ki,tn,en,sn,nn,rn,on,an,hn,cn,ln,un,pn,dn,fn,_n,mn,gn,vn,yn,xn,wn,bn,Tn,Sn,kn,An,Cn,On,Dn,Mn,En,Rn,qn,In,Fn,Vn,Nn,Pn,jn,Ln,zn,Wn,Bn,Un,Gn,c,Qn,Zn,Xn,Yn,Hn,$n,Jn,Kn,tr,er,sr,ir,nr,rr,or,ar,hr,cr,lr,ur,pr,dr,fr,_r,mr,gr,vr,yr,xr,wr,br,Tr,Sr,kr,Ar,Cr,Or,Dr,Mr,Er,Rr,qr,Ir,Fr,Vr,Nr,Pr,jr,Lr,zr,Wr,Br,Ur,Gr,Qr,Zr,Xr,Yr,Hr,$r,Jr,Kr,to,eo,so,io,no,ro,oo,ao,ho,co,lo,uo,po,fo,_o,mo,go,vo,yo,xo,wo,bo,To,So,ko,Ao,Co,Oo,Do,Mo,Eo,Ro,qo,Io,Fo,Vo,No,Po,jo,Lo,zo,Wo,Bo,Uo,Go,Qo,Zo,p,Xo,Yo,Ho,$o,Jo,Ko,ta,ea,sa,ia,na,ra,oa,aa,ha,ca,la,ua,pa,da,fa,_a,ma,ga,va,ya,xa,wa,ba,Ta,Sa,ka,Aa,Ca,Oa,Da,Ma,Ea,Ra,qa,Ia,Fa,Va,Na,Pa,ja,La,za,Wa,Ba,Ua,Ga,Qa,Za,Xa,Ya,Ha,$a,Ja,Ka,th,eh,sh,ih,nh,rh,oh,ah,hh,ch,lh,uh,ph,dh,fh,_h,mh,gh,vh,yh,xh,wh,bh,Th,Sh,kh,Ah,Ch,Oh,Dh,Mh,Eh,Rh,qh,Ih,Fh,Vh,Nh,Ph,jh,Lh,zh,Wh,Bh,Uh,Gh,Qh,Zh,Xh,Yh,Hh,$h,Jh,Kh,tc,ec,sc,ic,nc,rc,oc,ac,hc,cc,lc,uc,pc,dc,fc,_c,mc,gc,vc,yc,xc,wc,bc,Tc,Sc,kc,Ac,Cc,Oc,Dc,Mc,Ec,Rc,qc,Ic,Fc,Vc,Nc,Pc,jc,Lc,zc,Wc,Bc,Uc,Gc,Qc,Zc,Xc,Yc,Hc,$c,Jc,Kc,tl,el,sl,il,nl,rl,ol,al,hl,cl,ll,ul,pl,dl,fl,_l,ml,gl,vl,yl,xl,wl,bl,Tl,Sl,kl,Al,Cl,s=class extends s{constructor(t,e){var s=ni(t),e={...he,...e},e=ii(s,e);super(t,!1,e,ri(s)?ei():null),this._nativeAnalyserNode=e}get fftSize(){return this._nativeAnalyserNode.fftSize}set fftSize(t){this._nativeAnalyserNode.fftSize=t}get frequencyBinCount(){return this._nativeAnalyserNode.frequencyBinCount}get maxDecibels(){return this._nativeAnalyserNode.maxDecibels}set maxDecibels(t){var e=this._nativeAnalyserNode.maxDecibels;if(!((this._nativeAnalyserNode.maxDecibels=t)>this._nativeAnalyserNode.minDecibels))throw this._nativeAnalyserNode.maxDecibels=e,si()}get minDecibels(){return this._nativeAnalyserNode.minDecibels}set minDecibels(t){var e=this._nativeAnalyserNode.minDecibels;if(this._nativeAnalyserNode.minDecibels=t,!(this._nativeAnalyserNode.maxDecibels>t))throw this._nativeAnalyserNode.minDecibels=e,si()}get smoothingTimeConstant(){return this._nativeAnalyserNode.smoothingTimeConstant}set smoothingTimeConstant(t){this._nativeAnalyserNode.smoothingTimeConstant=t}getByteFrequencyData(t){this._nativeAnalyserNode.getByteFrequencyData(t)}getByteTimeDomainData(t){this._nativeAnalyserNode.getByteTimeDomainData(t)}getFloatFrequencyData(t){this._nativeAnalyserNode.getFloatFrequencyData(t)}getFloatTimeDomainData(t){this._nativeAnalyserNode.getFloatTimeDomainData(t)}},Ol=new WeakSet,n=null!==(n=zs)&&n.hasOwnProperty("AudioBuffer")?n.AudioBuffer:null,r=(oi=new Uint32Array(1),t=>(oi[0]=t,oi[0]));Gi=le;const Dl=a=>{a.copyFromChannel=(e,t,s=0)=>{var i=Ui(s),s=Ui(t);if(s>=a.numberOfChannels)throw Gi();var n=a.length,r=a.getChannelData(s),o=e.length;for(let t=i<0?-i:0;t+i{var i=Ui(s),s=Ui(t);if(s>=a.numberOfChannels)throw Gi();const n=a.length,r=a.getChannelData(s),o=e.length;for(let t=i<0?-i:0;t+i{var n,r;i.copyFromChannel=(r=i.copyFromChannel,(t,e,s=0)=>{s=Bi(s),e=Bi(e);if(s{s=Bi(s),e=Bi(e);if(s{let p=null;return class e{constructor(t){if(null===h)throw new Error("Missing the native OfflineAudioContext constructor.");var{length:t,numberOfChannels:e,sampleRate:s}={...pe,...t};null===p&&(p=new h(1,1,44100));const i=null!==a&&r(c,c)?new a({length:t,numberOfChannels:e,sampleRate:s}):p.createBuffer(e,t,s);if(0===i.numberOfChannels)throw o();return"function"!=typeof i.copyFromChannel?(l(i),ue(i)):r(ce,()=>ce(i))||u(i),n.add(i),i}static[Symbol.hasInstance](t){return null!==t&&"object"==typeof t&&Object.getPrototypeOf(t)===e.prototype||n.has(t)}}})(Ol,Ls,gs,n,t,(Wi=n,()=>{if(null===Wi)return!1;try{new Wi({length:1,sampleRate:44100})}catch{return!1}return!0}),Dl,Ml),Rl=(zi=fs,(t,e)=>{const s=zi(t,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0}),i=(e.connect(s).connect(t.destination),()=>{e.removeEventListener("ended",i),e.disconnect(s),s.disconnect()});e.addEventListener("ended",i)}),ql=(Pi=Bs,ji=ve,Li=qe,async(t,n,r)=>{t=ji(t);await Promise.all(Array.from(t.activeInputs).map(async([t,e])=>{const s=Pi(t),i=await s.render(t,n);Li(t)||i.connect(r,e)}))}),Il=(Ni=ql,(t,e,s)=>Ni(e,t,s)),Fl=(Ai=Rl,Ci=Ls,Oi=t=>{const e=t.createBufferSource();e.start();try{e.start()}catch{return!0}return!1},Di=t=>{const e=t.createBufferSource(),s=t.createBuffer(1,1,44100);e.buffer=s;try{e.start(0,1)}catch{return!1}return!0},Mi=t=>{const e=t.createBufferSource();e.start();try{e.stop()}catch{return!1}return!0},Ei=Os,Ri=Ds,qi=Ms,Vi=As,Ii=(s,t)=>{const i=t.createBuffer(1,1,44100);null===s.buffer&&(s.buffer=i),Vi(s,"buffer",e=>()=>{var t=e.call(s);return t===i?null:t},e=>t=>e.call(s,null===t?i:t))},Fi=qs,(t,e)=>{var n,r,o,s=t.createBufferSource();return R(s,e),i(s,e,"playbackRate"),h(s,e,"buffer"),h(s,e,"loop"),h(s,e,"loopEnd"),h(s,e,"loopStart"),Ci(Oi,()=>Oi(t))||((o=s).start=(i=>{let n=!1;return(t=0,e=0,s)=>{if(n)throw a();i.call(o,t,e,s),n=!0}})(o.start)),Ci(Di,()=>Di(t))||((n=s).start=(r=n.start,(t=0,e=0,s)=>{var i=n.buffer,e=null===i?e:Math.min(i.duration,e);null!==i&&e>i.duration-.5/n.context.sampleRate?r.call(n,t,0,0):r.call(n,t,e,s)})),Ci(Mi,()=>Mi(t))||Ii(s,t),Ci(Ei,()=>Ei(t))||as(s),Ci(Ri,()=>Ri(t))||Fi(s,t),Ci(qi,()=>qi(t))||hs(s),Ai(t,s),s}),Vl=(ki=ve,Ti=t=>{t=ki(t);if(null===t.renderer)throw new Error("Missing the renderer of the given AudioParam in the audio graph.");return t.renderer},Si=ql,(t,e,s)=>(Ti(e).replay(s),Si(e,t,s))),Nl=(vi=Il,yi=Fl,xi=m,wi=Vl,bi=Us,()=>{const n=new WeakMap;let r=null,o=null;return{set start(t){r=t},set stop(t){o=t},render(t,e){var s=n.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=xi(t);var i=u(s,e);if(!i){const vi={buffer:s.buffer,channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,loop:s.loop,loopEnd:s.loopEnd,loopStart:s.loopStart,playbackRate:s.playbackRate.value};s=yi(e,vi),null!==r&&s.start(...r),null!==o&&s.stop(o)}return n.set(e,s),i?await vi(e,t.playbackRate,s.playbackRate):await wi(e,t.playbackRate,s.playbackRate),await bi(t,e,s),s})(t,e)}}}),Pl=(Qi=Wt,ai=Xs,hi=Bt,ci=Pt.createCancelAndHoldAutomationEvent,li=Pt.createCancelScheduledValuesAutomationEvent,ui=Pt.createExponentialRampToValueAutomationEvent,pi=Pt.createLinearRampToValueAutomationEvent,di=Pt.createSetTargetAutomationEvent,fi=Pt.createSetValueAutomationEvent,_i=Pt.createSetValueCurveAutomationEvent,mi=Hs,gi=Cs,(p,t,d,e=null,s=null)=>{const i=d.value,f=new Pt.AutomationEventList(i),_=t?(c=f,{replay(t){for(const e of c)if("exponentialRampToValue"===e.type){const{endTime:c,value:s}=e;t.exponentialRampToValueAtTime(s,c)}else if("linearRampToValue"===e.type){const{endTime:c,value:i}=e;t.linearRampToValueAtTime(i,c)}else if("setTarget"===e.type){const{startTime:c,target:n,timeConstant:r}=e;t.setTargetAtTime(n,c,r)}else if("setValue"===e.type){const{startTime:c,value:o}=e;t.setValueAtTime(o,c)}else{if("setValueCurve"!==e.type)throw new Error("Can't apply an unknown automation.");{const{duration:c,startTime:a,values:h}=e;t.setValueCurveAtTime(h,a,c)}}}}):null,m={get defaultValue(){return i},get maxValue(){return null===e?d.maxValue:e},get minValue(){return null===s?d.minValue:s},get value(){return d.value},set value(t){d.value=t,m.setValueAtTime(t,p.context.currentTime)},cancelAndHoldAtTime(t){var e,s;return"function"==typeof d.cancelAndHoldAtTime?(null===_&&f.flush(p.context.currentTime),f.add(ci(t)),d.cancelAndHoldAtTime(t)):(e=Array.from(f).pop(),null===_&&f.flush(p.context.currentTime),f.add(ci(t)),s=Array.from(f).pop(),d.cancelScheduledValues(t),e!==s&&void 0!==s&&("exponentialRampToValue"===s.type?d.exponentialRampToValueAtTime(s.value,s.endTime):"linearRampToValue"===s.type?d.linearRampToValueAtTime(s.value,s.endTime):"setValue"===s.type?d.setValueAtTime(s.value,s.startTime):"setValueCurve"===s.type&&d.setValueCurveAtTime(s.values,s.startTime,s.duration))),m},cancelScheduledValues:t=>(null===_&&f.flush(p.context.currentTime),f.add(li(t)),d.cancelScheduledValues(t),m),exponentialRampToValueAtTime(t,e){if(0===t)throw new RangeError;if(!Number.isFinite(e)||e<0)throw new RangeError;var s=p.context.currentTime;return null===_&&f.flush(s),0===Array.from(f).length&&(f.add(fi(i,s)),d.setValueAtTime(i,s)),f.add(ui(t,e)),d.exponentialRampToValueAtTime(t,e),m},linearRampToValueAtTime(t,e){var s=p.context.currentTime;return null===_&&f.flush(s),0===Array.from(f).length&&(f.add(fi(i,s)),d.setValueAtTime(i,s)),f.add(pi(t,e)),d.linearRampToValueAtTime(t,e),m},setTargetAtTime:(t,e,s)=>(null===_&&f.flush(p.context.currentTime),f.add(di(t,e,s)),d.setTargetAtTime(t,e,s),m),setValueAtTime:(t,e)=>(null===_&&f.flush(p.context.currentTime),f.add(fi(t,e)),d.setValueAtTime(t,e),m),setValueCurveAtTime(t,e,s){var i=t instanceof Float32Array?t:new Float32Array(t);if(null!==mi&&"webkitAudioContext"===mi.name){const t=e+s,r=p.context.sampleRate,o=Math.ceil(e*r),a=Math.floor(t*r),h=a-o,c=new Float32Array(h);for(let t=0;t{this._nativeAudioBufferSourceNode.removeEventListener("ended",t),_e(this)&&oe(this)};this._nativeAudioBufferSourceNode.addEventListener("ended",t)}}stop(t=0){this._nativeAudioBufferSourceNode.stop(t),null!==this._audioBufferSourceNodeRenderer&&(this._audioBufferSourceNodeRenderer.stop=t)}}),Ll=(n=e,dl=le,fl=a,yl=fs,xl=As,_l=(t,e,s)=>{const i=t.destination;if(i.channelCount!==e)try{i.channelCount=e}catch{}s&&"explicit"!==i.channelCountMode&&(i.channelCountMode="explicit"),0===i.maxChannelCount&&Object.defineProperty(i,"maxChannelCount",{value:e});const n=yl(t,{channelCount:e,channelCountMode:i.channelCountMode,channelInterpretation:i.channelInterpretation,gain:1});return xl(n,"channelCount",t=>()=>t.call(n),t=>e=>{t.call(n,e);try{i.channelCount=e}catch(t){if(e>i.maxChannelCount)throw t}}),xl(n,"channelCountMode",t=>()=>t.call(n),e=>t=>{e.call(n,t),i.channelCountMode=t}),xl(n,"channelInterpretation",t=>()=>t.call(n),e=>t=>{e.call(n,t),i.channelInterpretation=t}),Object.defineProperty(n,"maxChannelCount",{get:()=>i.maxChannelCount}),n.connect(i),n},class extends n{constructor(t,e){var s=ml(t),i=gl(s),s=_l(s,e,i);super(t,!1,s,i?(i=>{const n=new WeakMap;return{render(t,e){var s=n.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{var s=e.destination;return n.set(e,s),await i(t,e,s),s})(t,e)}}})(vl):null),this._isNodeOfNativeOfflineAudioContext=i,this._nativeAudioDestinationNode=s}get channelCount(){return this._nativeAudioDestinationNode.channelCount}set channelCount(t){if(this._isNodeOfNativeOfflineAudioContext)throw fl();if(t>this._nativeAudioDestinationNode.maxChannelCount)throw dl();this._nativeAudioDestinationNode.channelCount=t}get channelCountMode(){return this._nativeAudioDestinationNode.channelCountMode}set channelCountMode(t){if(this._isNodeOfNativeOfflineAudioContext)throw fl();this._nativeAudioDestinationNode.channelCountMode=t}get maxChannelCount(){return this._nativeAudioDestinationNode.maxChannelCount}}),zl=(hl=Il,ll=m,ul=Vl,pl=vl=Us,()=>{const n=new WeakMap;return{render(t,e){var s=n.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=ll(t);var i=u(s,e);if(!i){const hl={Q:s.Q.value,channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,detune:s.detune.value,frequency:s.frequency.value,gain:s.gain.value,type:s.type};s=cl(e,hl)}return n.set(e,s),i?(await hl(e,t.Q,s.Q),await hl(e,t.detune,s.detune),await hl(e,t.frequency,s.frequency),await hl(e,t.gain,s.gain)):(await ul(e,t.Q,s.Q),await ul(e,t.detune,s.detune),await ul(e,t.frequency,s.frequency),await ul(e,t.gain,s.gain)),await pl(t,e,s),s})(t,e)}}}),Wl=(al=Ps,(t,e)=>al.set(t,e)),Bl=(r=e,tl=bl=Pl,el=zl,sl=es,il=cl=ls,nl=ml=kl=Qs,rl=gl=Al=Zs,ol=Wl,class extends r{constructor(t,e){var s=nl(t),e={...Ge,...e},e=il(s,e),s=rl(s);super(t,!1,e,s?el():null),this._Q=tl(this,s,e.Q,fe,de),this._detune=tl(this,s,e.detune,1200*Math.log2(fe),-1200*Math.log2(fe)),this._frequency=tl(this,s,e.frequency,t.sampleRate/2,0),this._gain=tl(this,s,e.gain,40*Math.log10(fe),de),this._nativeBiquadFilterNode=e,ol(this,1)}get detune(){return this._detune}get frequency(){return this._frequency}get gain(){return this._gain}get Q(){return this._Q}get type(){return this._nativeBiquadFilterNode.type}set type(t){this._nativeBiquadFilterNode.type=t}getFrequencyResponse(t,e,s){try{this._nativeBiquadFilterNode.getFrequencyResponse(t,e,s)}catch(t){if(11===t.code)throw sl();throw t}if(t.length!==e.length||e.length!==s.length)throw sl()}}),Ul=(Jc=Te,Kc=Js,(r,n,o)=>{const a=new Set;return r.connect=(c=r.connect,(e,s=0,i=0)=>{var t=0===a.size;if(Kc(e))return c.call(r,e,s,i),Jc(a,[e,s,i],t=>t[0]===e&&t[1]===s&&t[2]===i,!0),t&&n(),e;c.call(r,e,s),Jc(a,[e,s],t=>t[0]===e&&t[1]===s,!0),t&&n()}),r.disconnect=(h=r.disconnect,(t,e,s)=>{var i=0{s.channelCount=1,s.channelCountMode="explicit",Object.defineProperty(s,"channelCount",{get:()=>1,set:()=>{throw Hc()}}),Object.defineProperty(s,"channelCountMode",{get:()=>"explicit",set:()=>{throw Hc()}});const i=t.createBufferSource();$c(s,()=>{var e=s.numberOfInputs;for(let t=0;ti.disconnect(s))}),Ql=(Xc=Hs,Yc=Gl,(t,e)=>{var s=t.createChannelMerger(e.numberOfInputs);return null!==Xc&&"webkitAudioContext"===Xc.name&&Yc(t,s),R(s,e),s}),Zl=(Qc=m,()=>{const i=new WeakMap;return{render(t,e){var s=i.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=Qc(t);if(!u(s,e)){const Qc={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,numberOfInputs:s.numberOfInputs};s=Gc(e,Qc)}return i.set(e,s),await Zc(t,e,s),s})(t,e)}}}),Xl=(n=e,zc=Zl,class extends n{constructor(t,e){var s=Bc(t),e={...Qe,...e};super(t,!1,Wc(s,e),Uc(s)?zc():null)}}),Yl=(jc=m,()=>{const i=new WeakMap;return{render(t,e){var s=i.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=jc(t);if(!u(s,e)){const jc={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,numberOfOutputs:s.numberOfOutputs};s=Pc(e,jc)}return i.set(e,s),await Lc(t,e,s),s})(t,e)}}}),Hl=(r=e,Ic=Yl,Fc=Pc=us,class extends r{constructor(t,e){var s=Vc(t),e={...e={...Ze,...e},channelCount:e.numberOfOutputs};super(t,!1,Fc(s,e),Nc(s)?Ic():null)}}),$l=(qc=$c=Ul,(t,{offset:e,...s})=>{const i=t.createBuffer(1,2,44100),n=Ec(t,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),r=Rc(t,{...s,gain:e}),o=i.getChannelData(0);o[0]=1,o[1]=1,n.buffer=i,n.loop=!0;s={get bufferSize(){},get channelCount(){return r.channelCount},set channelCount(t){r.channelCount=t},get channelCountMode(){return r.channelCountMode},set channelCountMode(t){r.channelCountMode=t},get channelInterpretation(){return r.channelInterpretation},set channelInterpretation(t){r.channelInterpretation=t},get context(){return r.context},get inputs(){return[]},get numberOfInputs(){return n.numberOfInputs},get numberOfOutputs(){return r.numberOfOutputs},get offset(){return r.gain},get onended(){return n.onended},set onended(t){n.onended=t},addEventListener:(...t)=>n.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>n.dispatchEvent(t[0]),removeEventListener:(...t)=>n.removeEventListener(t[0],t[1],t[2]),start(t=0){n.start.call(n,t)},stop(t=0){n.stop.call(n,t)}};return Mc(t,n),qc(ps(s,r),()=>n.connect(r),()=>n.disconnect(r))}),Jl=(kc=Mc=Rl,Ac=Ls,Cc=$l,Oc=Os,Dc=Ms,(t,e)=>{if(void 0===t.createConstantSource)return Cc(t,e);var s=t.createConstantSource();return R(s,e),i(s,e,"offset"),Ac(Oc,()=>Oc(t))||as(s),Ac(Dc,()=>Dc(t))||hs(s),kc(t,s),s}),Kl=(bc=m,()=>{const n=new WeakMap;let r=null,o=null;return{set start(t){r=t},set stop(t){o=t},render(t,e){var s=n.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=bc(t);var i=u(s,e);if(!i){const xc={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,offset:s.offset.value};s=wc(e,xc),null!==r&&s.start(r),null!==o&&s.stop(o)}return n.set(e,s),i?await xc(e,t.offset,s.offset):await Tc(e,t.offset,s.offset),await Sc(t,e,s),s})(t,e)}}}),tu=(n=e,_c=Kl,yc=Is,class extends n{constructor(t,e){var s=gc(t),e={...Xe,...e},e=mc(s,e),s=vc(s),i=s?_c():null;super(t,!1,e,i),this._constantSourceNodeRenderer=i,this._nativeConstantSourceNode=e,this._offset=fc(this,s,e.offset,fe,de),this._onended=null}get offset(){return this._offset}get onended(){return this._onended}set onended(t){var e="function"==typeof t?yc(this,t):null,s=(this._nativeConstantSourceNode.onended=e,this._nativeConstantSourceNode.onended);this._onended=null!==s&&s===e?t:s}start(t=0){if(this._nativeConstantSourceNode.start(t),null!==this._constantSourceNodeRenderer&&(this._constantSourceNodeRenderer.start=t),"closed"!==this.context.state){ne(this);const t=()=>{this._nativeConstantSourceNode.removeEventListener("ended",t),_e(this)&&oe(this)};this._nativeConstantSourceNode.addEventListener("ended",t)}}stop(t=0){this._nativeConstantSourceNode.stop(t),null!==this._constantSourceNodeRenderer&&(this._constantSourceNodeRenderer.stop=t)}}),eu=(t,e)=>{const s=t.createConvolver();if(R(s,e),e.disableNormalization===s.normalize&&(s.normalize=!e.disableNormalization),h(s,e,"buffer"),2()=>t.call(s),e=>t=>{if(2()=>t.call(s),e=>t=>{if("max"===t)throw pc();return e.call(s,t)}),s},su=(lc=m,()=>{const i=new WeakMap;return{render(t,e){var s=i.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=lc(t);if(!u(s,e)){const lc={buffer:s.buffer,channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,disableNormalization:!s.normalize};s=cc(e,lc)}return i.set(e,s),Ae(s)?await uc(t,e,s.inputs[0]):await uc(t,e,s),s})(t,e)}}}),iu=(r=e,nc=su,rc=cc=eu,class extends r{constructor(t,e){var s=oc(t),e={...Ye,...e},i=rc(s,e);super(t,!1,i,ac(s)?nc():null),this._isBufferNullified=!1,this._nativeConvolverNode=i,null!==e.buffer&&hc(this,e.buffer.duration)}get buffer(){return this._isBufferNullified?null:this._nativeConvolverNode.buffer}set buffer(t){if(null===(this._nativeConvolverNode.buffer=t)&&null!==this._nativeConvolverNode.buffer){const t=this._nativeConvolverNode.context;this._nativeConvolverNode.buffer=t.createBuffer(1,1,t.sampleRate),this._isBufferNullified=!0,hc(this,0)}else this._isBufferNullified=!1,hc(this,null===this._nativeConvolverNode.buffer?0:this._nativeConvolverNode.buffer.duration)}get normalize(){return this._nativeConvolverNode.normalize}set normalize(t){this._nativeConvolverNode.normalize=t}}),nu=(ec=m,n=>{const r=new WeakMap;return{render(t,e){var s=r.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=ec(t);var i=u(s,e);if(!i){const Kh={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,delayTime:s.delayTime.value,maxDelayTime:n};s=tc(e,Kh)}return r.set(e,s),i?await Kh(e,t.delayTime,s.delayTime):await sc(e,t.delayTime,s.delayTime),await ic(t,e,s),s})(t,e)}}}),ru=(n=e,Xh=nu,Yh=tc=ds,class extends n{constructor(t,e){var s=Hh(t),e={...$e,...e},i=Yh(s,e),s=$h(s);super(t,!1,i,s?Xh(e.maxDelayTime):null),this._delayTime=Zh(this,s,i.delayTime),Jh(this,e.maxDelayTime)}get delayTime(){return this._delayTime}}),ou=(t,e)=>{t=t.createDynamicsCompressor();if(R(t,e),2{const n=new WeakMap;return{render(t,e){var s=n.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=Bh(t);var i=u(s,e);if(!i){const zh={attack:s.attack.value,channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,knee:s.knee.value,ratio:s.ratio.value,release:s.release.value,threshold:s.threshold.value};s=Wh(e,zh)}return n.set(e,s),i?(await zh(e,t.attack,s.attack),await zh(e,t.knee,s.knee),await zh(e,t.ratio,s.ratio),await zh(e,t.release,s.release),await zh(e,t.threshold,s.threshold)):(await Uh(e,t.attack,s.attack),await Uh(e,t.knee,s.knee),await Uh(e,t.ratio,s.ratio),await Uh(e,t.release,s.release),await Uh(e,t.threshold,s.threshold)),await Gh(t,e,s),s})(t,e)}}}),hu=(r=e,Fh=au,Vh=Wh=ou,class extends r{constructor(t,e){var s=Ph(t),e={...Ke,...e},e=Vh(s,e),s=jh(s);super(t,!1,e,s?Fh():null),this._attack=Ih(this,s,e.attack),this._knee=Ih(this,s,e.knee),this._nativeDynamicsCompressorNode=e,this._ratio=Ih(this,s,e.ratio),this._release=Ih(this,s,e.release),this._threshold=Ih(this,s,e.threshold),Lh(this,.006)}get attack(){return this._attack}get channelCount(){return this._nativeDynamicsCompressorNode.channelCount}set channelCount(t){var e=this._nativeDynamicsCompressorNode.channelCount;if(2<(this._nativeDynamicsCompressorNode.channelCount=t))throw this._nativeDynamicsCompressorNode.channelCount=e,Nh()}get channelCountMode(){return this._nativeDynamicsCompressorNode.channelCountMode}set channelCountMode(t){var e=this._nativeDynamicsCompressorNode.channelCountMode;if("max"===(this._nativeDynamicsCompressorNode.channelCountMode=t))throw this._nativeDynamicsCompressorNode.channelCountMode=e,Nh()}get knee(){return this._knee}get ratio(){return this._ratio}get reduction(){return"number"==typeof this._nativeDynamicsCompressorNode.reduction.value?this._nativeDynamicsCompressorNode.reduction.value:this._nativeDynamicsCompressorNode.reduction}get release(){return this._release}get threshold(){return this._threshold}}),cu=(Dh=zh=Kh=xc=Il,Eh=m,Rh=Uh=sc=Tc=Vl,()=>{const n=new WeakMap;return{render(t,e){var s=n.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=Eh(t);var i=u(s,e);if(!i){const Dh={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,gain:s.gain.value};s=Mh(e,Dh)}return n.set(e,s),i?await Dh(e,t.gain,s.gain):await Rh(e,t.gain,s.gain),await qh(t,e,s),s})(t,e)}}}),lu=(n=e,kh=cu,class extends n{constructor(t,e){var s=Ch(t),e={...ts,...e},e=Ah(s,e),s=Oh(s);super(t,!1,e,s?kh():null),this._gain=Sh(this,s,e.gain,fe,de)}get gain(){return this._gain}}),uu=(xh=es,wh=a,(t,e,{channelCount:s,channelCountMode:i,channelInterpretation:n,feedback:r,feedforward:o})=>{const a=cs(e,t.sampleRate),l=r instanceof Float64Array?r:new Float64Array(r),u=o instanceof Float64Array?o:new Float64Array(o),h=l.length,c=u.length,p=Math.min(h,c);if(0===h||20{const e=t.inputBuffer,s=t.outputBuffer,i=e.numberOfChannels;for(let t=0;td.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>d.dispatchEvent(t[0]),getFrequencyResponse(e,s,i){if(e.length!==s.length||s.length!==i.length)throw xh();const n=e.length;for(let t=0;td.removeEventListener(t[0],t[1],t[2])},d)}),pu=(fh=Ls,vh=_h=Ah=Mh=Rc=fs,yh=t,gh=()=>{if(null===yh)return Promise.resolve(!1);const e=new yh(1,1,44100),s=vh(e,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return new Promise(t=>{e.oncomplete=()=>{s.disconnect(),t(0!==e.currentTime)},e.startRendering()})},i=>fh(rs,()=>rs(i))?Promise.resolve(fh(gh,gh)).then(t=>{if(!t){const t=mh(i,512,0,1);i.oncomplete=()=>{t.onaudioprocess=null,t.disconnect()},t.onaudioprocess=()=>i.currentTime,t.connect(i.destination)}return i.startRendering()}):new Promise(e=>{const s=_h(i,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});i.oncomplete=t=>{s.disconnect(),e(t.renderedBuffer)},s.connect(i.destination),i.startRendering()})),du=(ch=Ec=Fl,lh=m,uh=t,ph=qh=Gh=ic=uc=Sc=Lc=Zc=Us,dh=pu,(_,m)=>{const i=new WeakMap;let n=null;return{render(t,e){var s=i.get(e);return void 0!==s?Promise.resolve(s):(async(d,f)=>{let t=null,e=lh(d);var s=u(e,f);if(void 0===f.createIIRFilter?t=ch(f,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}):s||(e=f.createIIRFilter(m,_)),i.set(f,null===t?e:t),null===t)return await ph(d,f,e),e;{if(null===n){if(null===uh)throw new Error("Missing the native OfflineAudioContext constructor.");const ch=new uh(d.context.destination.channelCount,d.context.length,f.sampleRate);n=(async()=>{await ph(d,ch,ch.destination);{var e=await dh(ch),t=f,s=_,i=m;const n=s instanceof Float64Array?s:new Float64Array(s),r=i instanceof Float64Array?i:new Float64Array(i),o=n.length,a=r.length,h=Math.min(o,a);if(1!==n[0]){for(let t=0;t{if(void 0===t.createIIRFilter)return hh(t,e,s);e=t.createIIRFilter(s.feedforward,s.feedback);return R(e,s),e}),_u=(r=e,ih=fu,nh=du,rh=Ch=Ph=Hh=oc=gc=Vc=Bc=Qs,ah=Lh=Jh=hc=Wl,class extends r{constructor(t,e){var i,n,s=rh(t),r=oh(s),e={...ss,...e},s=ih(s,r?null:t.baseLatency,e);super(t,!1,s,r?nh(e.feedback,e.feedforward):null),(i=s).getFrequencyResponse=(n=i.getFrequencyResponse,(t,e,s)=>{if(t.length!==e.length||e.length!==s.length)throw es();return n.call(i,t,e,s)}),this._nativeIIRFilterNode=s,ah(this,1)}getFrequencyResponse(t,e,s){return this._nativeIIRFilterNode.getFrequencyResponse(t,e,s)}}),mu=(Ya=Sh=Ih=Zh=fc=Pl,Ha=Wc=Gc=Ql,$a=mc=wc=Jl,Ja=mh=bh=ms,Ka=Th=Nh=Qh=pc=gs,th=Ss,eh=oh=Oh=jh=$h=ac=vc=Nc=Uc=Zs,sh=dc=As,(_,m)=>{const a=m.listener,{forwardX:t,forwardY:e,forwardZ:s,positionX:i,positionY:n,positionZ:r,upX:o,upY:h,upZ:c}=void 0===a.forwardX?(()=>{const i=new Float32Array(1),p=Ha(m,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:9}),d=eh(m);let e=!1,n=[0,0,-1,0,1,0],r=[0,0,0];const f=()=>{if(!e){e=!0;const t=Ja(m,256,9,0);t.onaudioprocess=({inputBuffer:t})=>{const e=[th(t,i,0),th(t,i,1),th(t,i,2),th(t,i,3),th(t,i,4),th(t,i,5)],s=(e.some((t,e)=>t!==n[e])&&(a.setOrientation(...e),n=e),[th(t,i,6),th(t,i,7),th(t,i,8)]);s.some((t,e)=>t!==r[e])&&(a.setPosition(...s),r=s)},p.connect(t)}},t=e=>t=>{t!==n[e]&&(n[e]=t,a.setOrientation(...n))},s=e=>t=>{t!==r[e]&&(r[e]=t,a.setPosition(...r))},o=(t,e,s)=>{const i=$a(m,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:e}),n=(i.connect(p,0,t),i.start(),Object.defineProperty(i.offset,"defaultValue",{get:()=>e}),Ya({context:_},d,i.offset,fe,de));var r,o,a,h,c,l,u;return sh(n,"value",t=>()=>t.call(n),e=>t=>{try{e.call(n,t)}catch(t){if(9!==t.code)throw t}f(),d&&s(t)}),n.cancelAndHoldAtTime=(r=n.cancelAndHoldAtTime,d?()=>{throw Ka()}:(...t)=>{t=r.apply(n,t);return f(),t}),n.cancelScheduledValues=(o=n.cancelScheduledValues,d?()=>{throw Ka()}:(...t)=>{t=o.apply(n,t);return f(),t}),n.exponentialRampToValueAtTime=(a=n.exponentialRampToValueAtTime,d?()=>{throw Ka()}:(...t)=>{t=a.apply(n,t);return f(),t}),n.linearRampToValueAtTime=(h=n.linearRampToValueAtTime,d?()=>{throw Ka()}:(...t)=>{t=h.apply(n,t);return f(),t}),n.setTargetAtTime=(c=n.setTargetAtTime,d?()=>{throw Ka()}:(...t)=>{t=c.apply(n,t);return f(),t}),n.setValueAtTime=(l=n.setValueAtTime,d?()=>{throw Ka()}:(...t)=>{t=l.apply(n,t);return f(),t}),n.setValueCurveAtTime=(u=n.setValueCurveAtTime,d?()=>{throw Ka()}:(...t)=>{t=u.apply(n,t);return f(),t}),n};return{forwardX:o(0,0,t(0)),forwardY:o(1,0,t(1)),forwardZ:o(2,-1,t(2)),positionX:o(6,0,s(0)),positionY:o(7,0,s(1)),positionZ:o(8,0,s(2)),upX:o(3,0,t(3)),upY:o(4,1,t(4)),upZ:o(5,0,t(5))}})():a;return{get forwardX(){return t},get forwardY(){return e},get forwardZ(){return s},get positionX(){return i},get positionY(){return n},get positionZ(){return r},get upX(){return o},get upY(){return h},get upZ(){return c}}}),gu=new WeakMap,vu=(Ua=Ll,Ga=mu,Za=gu,class extends Ys{constructor(t,e){super(t),this._nativeContext=t,Ut.set(this,t),Qa(t)&&Za.set(t,new Set),this._destination=new Ua(this,e),this._listener=Ga(this,t),this._onstatechange=null}get currentTime(){return this._nativeContext.currentTime}get destination(){return this._destination}get listener(){return this._listener}get onstatechange(){return this._onstatechange}set onstatechange(t){var e="function"==typeof t?Xa(this,t):null,s=(this._nativeContext.onstatechange=e,this._nativeContext.onstatechange);this._onstatechange=null!==s&&s===e?t:s}get sampleRate(){return this._nativeContext.sampleRate}get state(){return this._nativeContext.state}}),yu=(Pa=Rl,ja=Ls,La=Os,za=Ds,Wa=Ms,Ba=qs,(t,e)=>{const s=t.createOscillator();return R(s,e),i(s,e,"detune"),i(s,e,"frequency"),void 0!==e.periodicWave?s.setPeriodicWave(e.periodicWave):h(s,e,"type"),ja(La,()=>La(t))||as(s),ja(za,()=>za(t))||Ba(s,t),ja(Wa,()=>Wa(t))||hs(s),Pa(t,s),s}),xu=(Fa=m,()=>{const n=new WeakMap;let r=null,o=null,a=null;return{set periodicWave(t){r=t},set start(t){o=t},set stop(t){a=t},render(t,e){var s=n.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=Fa(t);var i=u(s,e);if(!i){const qa={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,detune:s.detune.value,frequency:s.frequency.value,periodicWave:null===r?void 0:r,type:s.type};s=Ia(e,qa),null!==o&&s.start(o),null!==a&&s.stop(a)}return n.set(e,s),i?(await qa(e,t.detune,s.detune),await qa(e,t.frequency,s.frequency)):(await Va(e,t.detune,s.detune),await Va(e,t.frequency,s.frequency)),await Na(t,e,s),s})(t,e)}}}),wu=(n=e,Oa=Ia=yu,Da=xu,Ra=Xa=Is,class extends n{constructor(t,e){var s=Ma(t),e={...ys,...e},i=Oa(s,e),s=Ea(s),n=s?Da():null,r=t.sampleRate/2;super(t,!1,i,n),this._detune=Ca(this,s,i.detune,153600,-153600),this._frequency=Ca(this,s,i.frequency,r,-r),this._nativeOscillatorNode=i,this._onended=null,this._oscillatorNodeRenderer=n,null!==this._oscillatorNodeRenderer&&void 0!==e.periodicWave&&(this._oscillatorNodeRenderer.periodicWave=e.periodicWave)}get detune(){return this._detune}get frequency(){return this._frequency}get onended(){return this._onended}set onended(t){var e="function"==typeof t?Ra(this,t):null,s=(this._nativeOscillatorNode.onended=e,this._nativeOscillatorNode.onended);this._onended=null!==s&&s===e?t:s}get type(){return this._nativeOscillatorNode.type}set type(t){this._nativeOscillatorNode.type=t,null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.periodicWave=null)}setPeriodicWave(t){this._nativeOscillatorNode.setPeriodicWave(t),null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.periodicWave=t)}start(t=0){if(this._nativeOscillatorNode.start(t),null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.start=t),"closed"!==this.context.state){ne(this);const t=()=>{this._nativeOscillatorNode.removeEventListener("ended",t),_e(this)&&oe(this)};this._nativeOscillatorNode.addEventListener("ended",t)}}stop(t=0){this._nativeOscillatorNode.stop(t),null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.stop=t)}}),bu=(Aa=Fl,(t,e)=>{const s=Aa(t,{buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),i=t.createBuffer(1,2,44100);return s.buffer=i,s.loop=!0,s.connect(e),s.start(),()=>{s.stop(),s.disconnect(e)}}),Tu=(ba=a,(r,{curve:t,oversample:e,...s})=>{const o=r.createWaveShaper(),a=r.createWaveShaper(),h=(R(o,s),R(a,s),Ta(r,{...s,gain:1})),i=Ta(r,{...s,gain:-1}),n=Ta(r,{...s,gain:1}),c=Ta(r,{...s,gain:-1});let l=null,u=!1,p=null;const d={get bufferSize(){},get channelCount(){return o.channelCount},set channelCount(t){h.channelCount=t,i.channelCount=t,o.channelCount=t,n.channelCount=t,a.channelCount=t,c.channelCount=t},get channelCountMode(){return o.channelCountMode},set channelCountMode(t){h.channelCountMode=t,i.channelCountMode=t,o.channelCountMode=t,n.channelCountMode=t,a.channelCountMode=t,c.channelCountMode=t},get channelInterpretation(){return o.channelInterpretation},set channelInterpretation(t){h.channelInterpretation=t,i.channelInterpretation=t,o.channelInterpretation=t,n.channelInterpretation=t,a.channelInterpretation=t,c.channelInterpretation=t},get context(){return o.context},get curve(){return p},set curve(e){if(null!==e&&e.length<2)throw ba();if(null===e)o.curve=e,a.curve=e;else{const wa=e.length,ba=new Float32Array(wa+2-wa%2),Sa=new Float32Array(wa+2-wa%2),s=(ba[0]=e[0],Sa[0]=-e[wa-1],Math.ceil((wa+1)/2)),r=(wa+1)/2-1;for(let t=1;th.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>h.dispatchEvent(t[0]),removeEventListener:(...t)=>h.removeEventListener(t[0],t[1],t[2])};return null!==t&&(d.curve=t instanceof Float32Array?t:new Float32Array(t)),e!==d.oversample&&(d.oversample=e),ka(ps(d,n),()=>{h.connect(o).connect(n),h.connect(i).connect(a).connect(c).connect(n),u=!0,Sa(p)&&(l=wa(r,h))},()=>{h.disconnect(o),o.disconnect(n),h.disconnect(i),i.disconnect(a),a.disconnect(c),c.disconnect(n),u=!1,null!==l&&(l(),l=null)})}),Su=(fa=wa=bu,_a=a,ma=Tu,ga=Sa=ks,ya=Hs,xa=As,(s,t)=>{const i=s.createWaveShaper();if(null!==ya&&"webkitAudioContext"===ya.name&&void 0===s.createGain().gain.automationRate)return ma(s,t);R(i,t);var e=null===t.curve||t.curve instanceof Float32Array?t.curve:new Float32Array(t.curve);if(null!==e&&e.length<2)throw _a();h(i,{curve:e},"curve"),h(i,t,"oversample");let n=null,r=!1;return xa(i,"curve",t=>()=>t.call(i),e=>t=>(e.call(i,t),r&&(ga(t)&&null===n?n=fa(s,i):ga(t)||null===n||(n(),n=null)),t)),va(i,()=>{r=!0,ga(i.curve)&&(n=fa(s,i))},()=>{r=!1,null!==n&&(n(),n=null)})}),ku=(na=Ce,ra=a,ha=ms,ca=Su,la=gs,ua=Ee,pa=Ss,da=va=ka=Ul,(t,{coneInnerAngle:e,coneOuterAngle:s,coneOuterGain:i,distanceModel:n,maxDistance:r,orientationX:o,orientationY:a,orientationZ:h,panningModel:c,positionX:l,positionY:u,positionZ:p,refDistance:d,rolloffFactor:f,..._})=>{const m=t.createPanner();if(2<_.channelCount)throw la();if("max"===_.channelCountMode)throw la();R(m,_);const g={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},v=oa(t,{...g,channelInterpretation:"speakers",numberOfInputs:6}),y=aa(t,{..._,gain:1}),x=aa(t,{...g,gain:1}),w=aa(t,{...g,gain:0}),b=aa(t,{...g,gain:0}),T=aa(t,{...g,gain:0}),S=aa(t,{...g,gain:0}),k=aa(t,{...g,gain:0}),A=ha(t,256,6,1),C=ca(t,{...g,curve:new Float32Array([1,1]),oversample:"none"});let O=[o,a,h],D=[l,u,p];const M=new Float32Array(1),E=(A.onaudioprocess=({inputBuffer:t})=>{const e=[pa(t,M,0),pa(t,M,1),pa(t,M,2)],s=(e.some((t,e)=>t!==O[e])&&(m.setOrientation(...e),O=e),[pa(t,M,3),pa(t,M,4),pa(t,M,5)]);s.some((t,e)=>t!==D[e])&&(m.setPosition(...s),D=s)},Object.defineProperty(w.gain,"defaultValue",{get:()=>0}),Object.defineProperty(b.gain,"defaultValue",{get:()=>0}),Object.defineProperty(T.gain,"defaultValue",{get:()=>0}),Object.defineProperty(S.gain,"defaultValue",{get:()=>0}),Object.defineProperty(k.gain,"defaultValue",{get:()=>0}),{get bufferSize(){},get channelCount(){return m.channelCount},set channelCount(t){if(2y.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>y.dispatchEvent(t[0]),removeEventListener:(...t)=>y.removeEventListener(t[0],t[1],t[2])});return e!==E.coneInnerAngle&&(E.coneInnerAngle=e),s!==E.coneOuterAngle&&(E.coneOuterAngle=s),i!==E.coneOuterGain&&(E.coneOuterGain=i),n!==E.distanceModel&&(E.distanceModel=n),r!==E.maxDistance&&(E.maxDistance=r),o!==E.orientationX.value&&(E.orientationX.value=o),a!==E.orientationY.value&&(E.orientationY.value=a),h!==E.orientationZ.value&&(E.orientationZ.value=h),c!==E.panningModel&&(E.panningModel=c),l!==E.positionX.value&&(E.positionX.value=l),u!==E.positionY.value&&(E.positionY.value=u),p!==E.positionZ.value&&(E.positionZ.value=p),d!==E.refDistance&&(E.refDistance=d),f!==E.rolloffFactor&&(E.rolloffFactor=f),1===O[0]&&0===O[1]&&0===O[2]||m.setOrientation(...O),0===D[0]&&0===D[1]&&0===D[2]||m.setPosition(...D),da(ps(E,m),()=>{y.connect(m),na(y,C,0,0),C.connect(x).connect(v,0,0),C.connect(w).connect(v,0,1),C.connect(b).connect(v,0,2),C.connect(T).connect(v,0,3),C.connect(S).connect(v,0,4),C.connect(k).connect(v,0,5),v.connect(A).connect(t.destination)},()=>{y.disconnect(m),ua(y,C,0,0),C.disconnect(x),x.disconnect(v),C.disconnect(w),w.disconnect(v),C.disconnect(b),b.disconnect(v),C.disconnect(T),T.disconnect(v),C.disconnect(S),S.disconnect(v),C.disconnect(k),k.disconnect(v),v.disconnect(A),A.disconnect(t.destination)})}),Au=(ia=ku,(t,e)=>{var s=t.createPanner();return void 0===s.orientationX?ia(t,e):(R(s,e),i(s,e,"orientationX"),i(s,e,"orientationY"),i(s,e,"orientationZ"),i(s,e,"positionX"),i(s,e,"positionY"),i(s,e,"positionZ"),h(s,e,"coneInnerAngle"),h(s,e,"coneOuterAngle"),h(s,e,"coneOuterGain"),h(s,e,"distanceModel"),h(s,e,"maxDistance"),h(s,e,"panningModel"),h(s,e,"refDistance"),h(s,e,"rolloffFactor"),s)}),Cu=(p=qa=Il,Xo=oa=Ql,Yo=Jl,Ho=aa=Ta=fs,Jo=m,Ko=t,ta=Va=Vl,ea=Na=Us,sa=pu,()=>{const c=new WeakMap;let l=null;return{render(t,e){var s=c.get(e);return void 0!==s?Promise.resolve(s):(async(t,r)=>{let o=null,e=Jo(t);var a={channelCount:e.channelCount,channelCountMode:e.channelCountMode,channelInterpretation:e.channelInterpretation},h={...a,coneInnerAngle:e.coneInnerAngle,coneOuterAngle:e.coneOuterAngle,coneOuterGain:e.coneOuterGain,distanceModel:e.distanceModel,maxDistance:e.maxDistance,panningModel:e.panningModel,refDistance:e.refDistance,rolloffFactor:e.rolloffFactor},s=u(e,r);if("bufferSize"in e)o=Ho(r,{...a,gain:1});else if(!s){const p={...h,orientationX:e.orientationX.value,orientationY:e.orientationY.value,orientationZ:e.orientationZ.value,positionX:e.positionX.value,positionY:e.positionY.value,positionZ:e.positionZ.value};e=$o(r,p)}if(c.set(r,null===o?e:o),null===o)return s?(await p(r,t.orientationX,e.orientationX),await p(r,t.orientationY,e.orientationY),await p(r,t.orientationZ,e.orientationZ),await p(r,t.positionX,e.positionX),await p(r,t.positionY,e.positionY),await p(r,t.positionZ,e.positionZ)):(await ta(r,t.orientationX,e.orientationX),await ta(r,t.orientationY,e.orientationY),await ta(r,t.orientationZ,e.orientationZ),await ta(r,t.positionX,e.positionX),await ta(r,t.positionY,e.positionY),await ta(r,t.positionZ,e.positionZ)),Ae(e)?await ea(t,r,e.inputs[0]):await ea(t,r,e),e;{if(null===l){if(null===Ko)throw new Error("Missing the native OfflineAudioContext constructor.");const p=new Ko(6,t.context.length,r.sampleRate),Ho=Xo(p,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6});Ho.connect(p.destination),l=(async()=>{const e=await Promise.all([t.orientationX,t.orientationY,t.orientationZ,t.positionX,t.positionY,t.positionZ].map(async(t,e)=>{e=Yo(p,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:0===e?1:0});return await ta(p,t,e.offset),e}));for(let t=0;t<6;t+=1)e[t].connect(Ho,0,t),e[t].start(0);return sa(p)})()}const p=await l,Jo=Ho(r,{...a,gain:1}),c=(await ea(t,r,Jo),[]);for(let t=0;tt!==s[e])||Yo.some((t,e)=>t!==i[e])){s=p,i=Yo;const Ko=t/r.sampleRate;e.gain.setValueAtTime(0,Ko),e=Ho(r,{...a,gain:0}),n=$o(r,{...h,orientationX:s[0],orientationY:s[1],orientationZ:s[2],positionX:i[0],positionY:i[1],positionZ:i[2]}),e.gain.setValueAtTime(1,Ko),Jo.connect(e).connect(n.inputs[0]),n.connect(o)}}return o}})(t,e)}}}),Ou=(r=e,Wo=Ca=Pl,Bo=$o=Au,Uo=Cu,Qo=Ea=Qa=Zs,Zo=Wl,class extends r{constructor(t,e){var s=Go(t),e={...xs,...e},e=Bo(s,e),s=Qo(s);super(t,!1,e,s?Uo():null),this._nativePannerNode=e,this._orientationX=Wo(this,s,e.orientationX,fe,de),this._orientationY=Wo(this,s,e.orientationY,fe,de),this._orientationZ=Wo(this,s,e.orientationZ,fe,de),this._positionX=Wo(this,s,e.positionX,fe,de),this._positionY=Wo(this,s,e.positionY,fe,de),this._positionZ=Wo(this,s,e.positionZ,fe,de),Zo(this,1)}get coneInnerAngle(){return this._nativePannerNode.coneInnerAngle}set coneInnerAngle(t){this._nativePannerNode.coneInnerAngle=t}get coneOuterAngle(){return this._nativePannerNode.coneOuterAngle}set coneOuterAngle(t){this._nativePannerNode.coneOuterAngle=t}get coneOuterGain(){return this._nativePannerNode.coneOuterGain}set coneOuterGain(t){this._nativePannerNode.coneOuterGain=t}get distanceModel(){return this._nativePannerNode.distanceModel}set distanceModel(t){this._nativePannerNode.distanceModel=t}get maxDistance(){return this._nativePannerNode.maxDistance}set maxDistance(t){this._nativePannerNode.maxDistance=t}get orientationX(){return this._orientationX}get orientationY(){return this._orientationY}get orientationZ(){return this._orientationZ}get panningModel(){return this._nativePannerNode.panningModel}set panningModel(t){this._nativePannerNode.panningModel=t}get positionX(){return this._positionX}get positionY(){return this._positionY}get positionZ(){return this._positionZ}get refDistance(){return this._nativePannerNode.refDistance}set refDistance(t){this._nativePannerNode.refDistance=t}get rolloffFactor(){return this._nativePannerNode.rolloffFactor}set rolloffFactor(t){this._nativePannerNode.rolloffFactor=t}}),Du=(zo=le,(t,{disableNormalization:e,imag:s,real:i})=>{var n=s instanceof Float32Array?s:new Float32Array(s),i=i instanceof Float32Array?i:new Float32Array(i),t=t.createPeriodicWave(i,n,{disableNormalization:e});if(Array.from(s).length<2)throw zo();return t}),Mu=(No=Du,Po=Go=Ma=Qs,jo=new WeakSet,class Lo{constructor(t,e){t=Po(t),e=(t=>{var{imag:e,real:s}=t;return void 0===e?void 0===s?{...t,imag:[0,0],real:[0,0]}:{...t,imag:Array.from(s,()=>0),real:s}:void 0===s?{...t,imag:e,real:Array.from(e,()=>0)}:{...t,imag:e,real:s}})({...ws,...e}),t=No(t,e);return jo.add(t),t}static[Symbol.hasInstance](t){return null!==t&&"object"==typeof t&&Object.getPrototypeOf(t)===Lo.prototype||jo.has(t)}}),Eu=((u,I,F,V,N,p)=>{const P=16385,j=new Float32Array([1,1]),L=Math.PI/2,z={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},W={...z,oversample:"none"},d=(t,e,s,i,n)=>{if(1===e){var r=t,o=s,a=i,h=n;const p=new Float32Array(P),d=new Float32Array(P);for(let t=0;tT){const I=(t-T)/(16384-T)*L;y[t]=Math.cos(I),x[t]=Math.sin(I),w[t]=0,b[t]=1}else{const I=t/(16384-T)*L;y[t]=1,x[t]=0,w[t]=Math.cos(I),b[t]=Math.sin(I)}const S=I(r,{channelCount:2,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:2}),k=F(r,{...z,gain:0}),A=V(r,{...W,curve:y}),C=F(r,{...z,gain:0}),O=V(r,{...W,curve:x}),D=V(r,{...W,curve:j}),M=F(r,{...z,gain:0}),E=V(r,{...W,curve:w}),R=F(r,{...z,gain:0}),q=V(r,{...W,curve:b});return{connectGraph(){c.connect(S),c.connect(void 0===D.inputs?D:D.inputs[0]),S.connect(k,0),S.connect(C,0),S.connect(M,1),S.connect(R,1),D.connect(l),l.connect(void 0===A.inputs?A:A.inputs[0]),l.connect(void 0===O.inputs?O:O.inputs[0]),l.connect(void 0===E.inputs?E:E.inputs[0]),l.connect(void 0===q.inputs?q:q.inputs[0]),A.connect(k.gain),O.connect(C.gain),E.connect(M.gain),q.connect(R.gain),k.connect(u,0,0),M.connect(u,0,0),C.connect(u,0,1),R.connect(u,0,1)},disconnectGraph(){c.disconnect(S),c.disconnect(void 0===D.inputs?D:D.inputs[0]),S.disconnect(k,0),S.disconnect(C,0),S.disconnect(M,1),S.disconnect(R,1),D.disconnect(l),l.disconnect(void 0===A.inputs?A:A.inputs[0]),l.disconnect(void 0===O.inputs?O:O.inputs[0]),l.disconnect(void 0===E.inputs?E:E.inputs[0]),l.disconnect(void 0===q.inputs?q:q.inputs[0]),A.disconnect(k.gain),O.disconnect(C.gain),E.disconnect(M.gain),q.disconnect(R.gain),k.disconnect(u,0,0),M.disconnect(u,0,0),C.disconnect(u,0,1),R.disconnect(u,0,1)}}}};return(e,{channelCount:t,channelCountMode:s,pan:i,...n})=>{if("max"===s)throw N();const r=u(e,{...n,channelCount:1,channelCountMode:s,numberOfInputs:2}),o=F(e,{...n,channelCount:t,channelCountMode:s,gain:1}),a=F(e,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:i});let{connectGraph:h,disconnectGraph:c}=d(e,t,o,a,r);Object.defineProperty(a.gain,"defaultValue",{get:()=>0}),Object.defineProperty(a.gain,"maxValue",{get:()=>1}),Object.defineProperty(a.gain,"minValue",{get:()=>-1});n={get bufferSize(){},get channelCount(){return o.channelCount},set channelCount(t){o.channelCount!==t&&(l&&c(),{connectGraph:h,disconnectGraph:c}=d(e,t,o,a,r),l&&h()),o.channelCount=t},get channelCountMode(){return o.channelCountMode},set channelCountMode(t){if("clamped-max"===t||"max"===t)throw N();o.channelCountMode=t},get channelInterpretation(){return o.channelInterpretation},set channelInterpretation(t){o.channelInterpretation=t},get context(){return o.context},get inputs(){return[o]},get numberOfInputs(){return o.numberOfInputs},get numberOfOutputs(){return o.numberOfOutputs},get pan(){return a.gain},addEventListener:(...t)=>o.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>o.dispatchEvent(t[0]),removeEventListener:(...t)=>o.removeEventListener(t[0],t[1],t[2])};let l=!1;return p(ps(n,r),()=>{h(),l=!0},()=>{c(),l=!1})}})(Ql,us,fs,Su,gs,Ul),Ru=(Fo=Eu,Vo=gs,(t,e)=>{const s=e.channelCountMode;if("clamped-max"===s)throw Vo();if(void 0===t.createStereoPanner)return Fo(t,e);t=t.createStereoPanner();return R(t,e),i(t,e,"pan"),Object.defineProperty(t,"channelCountMode",{get:()=>s,set:t=>{if(t!==s)throw Vo()}}),t}),qu=(Mo=Il,Ro=m,qo=Vl,()=>{const n=new WeakMap;return{render(t,e){var s=n.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=Ro(t);var i=u(s,e);if(!i){const Mo={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,pan:s.pan.value};s=Eo(e,Mo)}return n.set(e,s),i?await Mo(e,t.pan,s.pan):await qo(e,t.pan,s.pan),Ae(s)?await Io(t,e,s.inputs[0]):await Io(t,e,s),s})(t,e)}}}),Iu=(n=e,ko=Pl,Ao=Eo=Ru,Co=qu,class extends n{constructor(t,e){var s=Oo(t),e={...bs,...e},e=Ao(s,e),s=Do(s);super(t,!1,e,s?Co():null),this._pan=ko(this,s,e.pan)}get pan(){return this._pan}}),Fu=(To=m,So=Io=Us,()=>{const i=new WeakMap;return{render(t,e){var s=i.get(e);return void 0!==s?Promise.resolve(s):(async(t,e)=>{let s=To(t);if(!u(s,e)){const To={channelCount:s.channelCount,channelCountMode:s.channelCountMode,channelInterpretation:s.channelInterpretation,curve:s.curve,oversample:s.oversample};s=bo(e,To)}return i.set(e,s),Ae(s)?await So(t,e,s.inputs[0]):await So(t,e,s),s})(t,e)}}}),Vu=(r=e,mo=a,go=bo=Su,vo=Fu,yo=Oo=Qs,xo=Do=Zs,wo=Wl,class extends r{constructor(t,e){var s=yo(t),e={...Ts,...e},e=go(s,e);super(t,!0,e,xo(s)?vo():null),this._isCurveNullified=!1,this._nativeWaveShaperNode=e,wo(this,1)}get curve(){return this._isCurveNullified?null:this._nativeWaveShaperNode.curve}set curve(t){if(null===t)this._isCurveNullified=!0,this._nativeWaveShaperNode.curve=new Float32Array([0,0]);else{if(t.length<2)throw mo();this._isCurveNullified=!1,this._nativeWaveShaperNode.curve=t}}get oversample(){return this._nativeWaveShaperNode.oversample}set oversample(t){this._nativeWaveShaperNode.oversample=t}}),Nu=null!==(n=zs)&&n.isSecureContext,Pu=(_o=zs,(t,e,s)=>{Object.defineProperties(_o,{currentFrame:{configurable:!0,get:()=>Math.round(t*e)},currentTime:{configurable:!0,get:()=>t}});try{return s()}finally{null!==_o&&(delete _o.currentFrame,delete _o.currentTime)}}),ju=new WeakMap,Lu=(po=ju,fo=t,t=>{let e=po.get(t);if(void 0!==e)return e;if(null===fo)throw new Error("Missing the native OfflineAudioContext constructor.");return e=new fo(1,1,44100),po.set(t,e),e}),zu=Nu?((r,o,a,l,u,p,d,f,_,m,g,v,y)=>{let x=0;return(e,s,h={credentials:"omit"})=>{const t=g.get(e);if(void 0!==t&&t.has(s))return Promise.resolve();const i=m.get(e);if(void 0!==i){const r=i.get(s);if(void 0!==r)return r}const c=p(e),n=void 0===c.audioWorklet?u(s).then(([t,e])=>{var[t,e]=$t(t,e);return a(t+`;((a,b)=>{(a[b]=a[b]||[]).push((AudioWorkletProcessor,global,registerProcessor,sampleRate,self,window)=>{${e} +})})(window,'_AWGS')`)}).then(()=>{const t=y._AWGS.pop();if(void 0===t)throw new SyntaxError;l(c.currentTime,c.sampleRate,()=>t(class{},void 0,(t,e)=>{if(""===t.trim())throw o();const s=Zt.get(c);if(void 0!==s){if(s.has(t))throw o();Kt(e),Jt(e.parameterDescriptors),s.set(t,e)}else Kt(e),Jt(e.parameterDescriptors),Zt.set(c,new Map([[t,e]]))},c.sampleRate,void 0,void 0))}):Promise.all([u(s),Promise.resolve(r(v,v))]).then(([[t,e],s])=>{const i=x+1,[n,r]=(x=i,$t(t,e)),o=new Blob([`${n};((AudioWorkletProcessor,registerProcessor)=>{${r}\n})(${s?"AudioWorkletProcessor":"class extends AudioWorkletProcessor {__b=new WeakSet();constructor(){super();(p=>p.postMessage=(q=>(m,t)=>q.call(p,m,t?t.filter(u=>!this.__b.has(u)):t))(p.postMessage))(this.port)}}"},(n,p)=>registerProcessor(n,class extends p{${s?"":"__c = (a) => a.forEach(e=>this.__b.add(e.buffer));"}process(i,o,p){${s?"":"i.forEach(this.__c);o.forEach(this.__c);this.__c(Object.values(p));"}return super.process(i.map(j=>j.some(k=>k.length===0)?[]:j),o,p)}}));registerProcessor('__sac${i}',class extends AudioWorkletProcessor{process(){return !1}})`],{type:"application/javascript; charset=utf-8"}),a=URL.createObjectURL(o);return c.audioWorklet.addModule(a,h).then(()=>{if(f(c))return c;const t=d(c);return t.audioWorklet.addModule(a,h).then(()=>t)}).then(t=>{if(null===_)throw new SyntaxError;try{new _(t,"__sac"+i)}catch{throw new SyntaxError}}).finally(()=>URL.revokeObjectURL(a))});return void 0===i?m.set(e,new Map([[s,n]])):i.set(s,n),n.then(()=>{const t=g.get(e);void 0===t?g.set(e,new Set([s])):t.add(s)}).finally(()=>{const t=m.get(e);void 0!==t&&t.delete(s)}),n}})(Ls,gs,(uo=zs,n=>new Promise((t,r)=>{if(null===uo)r(new SyntaxError);else{const e=uo.document.head;if(null===e)r(new SyntaxError);else{const s=uo.document.createElement("script"),i=new Blob([n],{type:"application/javascript"}),o=URL.createObjectURL(i),a=uo.onerror,h=()=>{uo.onerror=a,URL.revokeObjectURL(o)};uo.onerror=(t,e,s,i,n)=>e===o||e===uo.location.href&&1===s&&1===i?(h(),r(n),!1):null!==a?a(t,e,s,i,n):void 0,s.onerror=()=>{h(),r(new SyntaxError)},s.onload=()=>{h(),t()},s.src=o,s.type="module",e.appendChild(s)}}})),Pu,async t=>{try{const e=await fetch(t);if(e.ok)return[await e.text(),e.url]}catch{}throw new DOMException("","AbortError")},Qs,Lu,Zs,ti,new WeakMap,new WeakMap,(co=ti,lo=t,async()=>{if(null===co)return!0;if(null===lo)return!1;const t=new Blob(['class A extends AudioWorkletProcessor{process(i){this.port.postMessage(i,[i[0][0].buffer])}}registerProcessor("a",A)'],{type:"application/javascript; charset=utf-8"}),e=new lo(1,128,44100),s=URL.createObjectURL(t);let i=!1,n=!1;try{await e.audioWorklet.addModule(s);const lo=new co(e,"a",{numberOfOutputs:0}),t=e.createOscillator();lo.port.onmessage=()=>i=!0,lo.onprocessorerror=()=>n=!0,t.connect(lo),t.start(0),await e.startRendering(),await new Promise(t=>setTimeout(t))}catch{}finally{URL.revokeObjectURL(s)}return i&&!n}),zs):void 0,Wu=(ao=$s,ho=Zs,t=>ao(t)||ho(t)),Bu=(Jr=Ol,Kr=Ls,to=new WeakSet,eo=Qs,so=Wu,io=ce,no=rs,ro=Dl,oo=Ml,(t,r)=>{const o=so(t)?t:eo(t);if(to.has(r)){const Jr=new DOMException("","DataCloneError");return Promise.reject(Jr)}try{to.add(r)}catch{}return Kr(no,()=>no(o))?o.decodeAudioData(r).then(t=>(He(r).catch(()=>{}),Kr(io,()=>io(t))||oo(t),Jr.add(t),t)):new Promise((e,s)=>{const i=async()=>{try{await He(r)}catch{}},n=t=>{s(t),i()};try{o.decodeAudioData(r,t=>{"function"!=typeof t.copyFromChannel&&(ro(t),ue(t)),Jr.add(t),i().then(()=>e(t))},t=>{n(null===t?new DOMException("","EncodingError"):t)})}catch(t){n(t)}})}),Uu=(qr=zu,Ir=s,Fr=El,Vr=jl,Nr=Bl,Pr=Xl,jr=Hl,Lr=tu,zr=iu,Wr=Bu,Br=ru,Ur=hu,Gr=lu,Qr=_u,Zr=wu,Xr=Ou,Yr=Mu,Hr=Iu,$r=Vu,class extends vu{constructor(t,e){super(t,e),this._nativeContext=t,this._audioWorklet=void 0===qr?void 0:{addModule:(t,e)=>qr(this,t,e)}}get audioWorklet(){return this._audioWorklet}createAnalyser(){return new Ir(this)}createBiquadFilter(){return new Nr(this)}createBuffer(t,e,s){return new Fr({length:e,numberOfChannels:t,sampleRate:s})}createBufferSource(){return new Vr(this)}createChannelMerger(t=6){return new Pr(this,{numberOfInputs:t})}createChannelSplitter(t=6){return new jr(this,{numberOfOutputs:t})}createConstantSource(){return new Lr(this)}createConvolver(){return new zr(this)}createDelay(t=1){return new Br(this,{maxDelayTime:t})}createDynamicsCompressor(){return new Ur(this)}createGain(){return new Gr(this)}createIIRFilter(t,e){return new Qr(this,{feedback:e,feedforward:t})}createOscillator(){return new Zr(this)}createPanner(){return new Xr(this)}createPeriodicWave(t,e,s={disableNormalization:!1}){return new Yr(this,{...s,imag:e,real:t})}createStereoPanner(){return new Hr(this)}createWaveShaper(){return new $r(this)}decodeAudioData(t,e,s){return Wr(this._nativeContext,t).then(t=>("function"==typeof e&&e(t),t),t=>{throw"function"==typeof s&&s(t),t})}}),Gu=class extends e{constructor(t,e){const s=Er(t),i=s.createMediaElementSource(e.mediaElement);if(Rr(s))throw TypeError();super(t,!0,i,null),this._nativeMediaElementAudioSourceNode=i}get mediaElement(){return this._nativeMediaElementAudioSourceNode.mediaElement}},Qu=class extends e{constructor(t,e){var s=Dr(t);if(Mr(s))throw new TypeError;s=((t,e)=>{t=t.createMediaStreamDestination();return R(t,e),1===t.numberOfOutputs&&Object.defineProperty(t,"numberOfOutputs",{get:()=>0}),t})(s,{...ns,...e});super(t,!1,s,null),this._nativeMediaStreamAudioDestinationNode=s}get stream(){return this._nativeMediaStreamAudioDestinationNode.stream}},Zu=class extends e{constructor(t,e){var s=Cr(t),e=((t,{mediaStream:e})=>{const s=e.getAudioTracks();s.sort((t,e)=>t.ide.id?1:0);var i=s.slice(0,1),t=t.createMediaStreamSource(new MediaStream(i));return Object.defineProperty(t,"mediaStream",{value:e}),t})(s,e);if(Or(s))throw new TypeError;super(t,!0,e,null),this._nativeMediaStreamAudioSourceNode=e}get mediaStream(){return this._nativeMediaStreamAudioSourceNode.mediaStream}},Xu=(kr=a,Ar=Or=Mr=Rr=Zs,(t,{mediaStreamTrack:e})=>{if("function"==typeof t.createMediaStreamTrackSource)return t.createMediaStreamTrackSource(e);var s=new MediaStream([e]),s=t.createMediaStreamSource(s);if("audio"!==e.kind)throw kr();if(Ar(t))throw new TypeError;return s}),Yu=(r=e,Tr=Xu,Sr=Cr=Dr=Er=Qs,class extends r{constructor(t,e){var s=Sr(t);super(t,!0,Tr(s,e),null)}}),Hu=(n=Uu,_r=a,mr=gs,gr=()=>new DOMException("","UnknownError"),vr=Gu,yr=Qu,xr=Zu,wr=Yu,br=Hs,class extends n{constructor(t={}){if(null===br)throw new Error("Missing the native AudioContext constructor.");let e;try{e=new br(t)}catch(t){if(12===t.code&&"sampleRate is not in range"===t.message)throw mr();throw t}if(null===e)throw gr();if(void 0!==(s=t.latencyHint)&&"number"!=typeof s&&("string"!=typeof s||"balanced"!==s&&"interactive"!==s&&"playback"!==s))throw new TypeError(`The provided value '${t.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);if(void 0!==t.sampleRate&&e.sampleRate!==t.sampleRate)throw mr();super(e,2);var s=t["latencyHint"],i=e["sampleRate"];if(this._baseLatency="number"==typeof e.baseLatency?e.baseLatency:"balanced"===s?512/i:"interactive"===s||void 0===s?256/i:"playback"===s?1024/i:128*Math.max(2,Math.min(128,Math.round(s*i/128)))/i,this._nativeAudioContext=e,"webkitAudioContext"===br.name?(this._nativeGainNode=e.createGain(),this._nativeOscillatorNode=e.createOscillator(),this._nativeGainNode.gain.value=1e-37,this._nativeOscillatorNode.connect(this._nativeGainNode).connect(e.destination),this._nativeOscillatorNode.start()):(this._nativeGainNode=null,this._nativeOscillatorNode=null),this._state=null,"running"===e.state){this._state="suspended";const t=()=>{"suspended"===this._state&&(this._state=null),e.removeEventListener("statechange",t)};e.addEventListener("statechange",t)}}get baseLatency(){return this._baseLatency}get state(){return null!==this._state?this._state:this._nativeAudioContext.state}close(){return"closed"===this.state?this._nativeAudioContext.close().then(()=>{throw _r()}):("suspended"===this._state&&(this._state=null),this._nativeAudioContext.close().then(()=>{null!==this._nativeGainNode&&null!==this._nativeOscillatorNode&&(this._nativeOscillatorNode.stop(),this._nativeGainNode.disconnect(),this._nativeOscillatorNode.disconnect()),xe(this)}))}createMediaElementSource(t){return new vr(this,{mediaElement:t})}createMediaStreamDestination(){return new yr(this)}createMediaStreamSource(t){return new xr(this,{mediaStream:t})}createMediaStreamTrackSource(t){return new wr(this,{mediaStreamTrack:t})}resume(){return"suspended"===this._state?new Promise((t,e)=>{const s=()=>{this._nativeAudioContext.removeEventListener("statechange",s),"running"===this._nativeAudioContext.state?t():this.resume().then(t,e)};this._nativeAudioContext.addEventListener("statechange",s)}):this._nativeAudioContext.resume().catch(t=>{if(void 0===t||15===t.code)throw _r();throw t})}suspend(){return this._nativeAudioContext.suspend().catch(t=>{if(void 0===t)throw _r();throw t})}}),$u=(fr=gu,t=>{t=fr.get(t);if(void 0===t)throw new Error("The context has no set of AudioWorkletNodes.");return t}),Ju=(t,e)=>{dr(t).add(e)},Ku=(pr=le,(t,e,s=0,i=0)=>{const n=t[s];if(void 0===n)throw pr();return Ne(e)?n.connect(e,0,i):n.connect(e,0)}),tp=(ur=dr=$u,(t,e)=>{ur(t).delete(e)}),ep=(lr=le,(t,e=void 0,s=void 0,i=0)=>void 0===e?t.forEach(t=>t.disconnect()):"number"==typeof e?Je(lr,t,e).disconnect():Ne(e)?void 0===s?t.forEach(t=>t.disconnect(e)):void 0===i?Je(lr,t,s).disconnect(e,0):Je(lr,t,s).disconnect(e,0,i):void 0===s?t.forEach(t=>t.disconnect(e)):Je(lr,t,s).disconnect(e,0)),sp=new WeakMap,ip=(hr=sp,cr=te,t=>cr(hr,t)),np=(Hn=le,$n=a,sr=ms,or=ip,(o,t,e,a)=>{if(0===a.numberOfInputs&&0===a.numberOfOutputs)throw ir();const h=Array.isArray(a.outputChannelCount)?a.outputChannelCount:Array.from(a.outputChannelCount);if(h.some(t=>t<1))throw ir();if(h.length!==a.numberOfOutputs)throw Hn();if("explicit"!==a.channelCountMode)throw ir();const c=a.channelCount*a.numberOfInputs,s=h.reduce((t,e)=>t+e,0),i=void 0===e.parameterDescriptors?0:e.parameterDescriptors.length;if(6void 0===Yn?0:Yn},maxValue:{get:()=>void 0===Hn?fe:Hn},minValue:{get:()=>void 0===$n?de:$n}}),p.push(Kn)}const d=Jn(o,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,c+i)}),f=cs(t,o.sampleRate),_=sr(o,f,c+i,Math.max(1,s)),r=Kn(o,{channelCount:Math.max(1,s),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,s)}),m=[];for(let t=0;t{const s=p[e];return s.connect(d,0,c+e),s.start(0),[t,s.offset]}));d.connect(_);let g=a.channelInterpretation,v=null;const y=0===a.numberOfOutputs?[_]:m,x={get bufferSize(){return f},get channelCount(){return a.channelCount},set channelCount(t){throw $n()},get channelCountMode(){return a.channelCountMode},set channelCountMode(t){throw $n()},get channelInterpretation(){return g},set channelInterpretation(t){for(const e of l)e.channelInterpretation=t;g=t},get context(){return _.context},get inputs(){return l},get numberOfInputs(){return a.numberOfInputs},get numberOfOutputs(){return a.numberOfOutputs},get onprocessorerror(){return v},set onprocessorerror(t){"function"==typeof v&&x.removeEventListener("processorerror",v),"function"==typeof(v="function"==typeof t?t:null)&&x.addEventListener("processorerror",v)},get parameters(){return V},get port(){return n.port2},addEventListener:(...t)=>_.addEventListener(t[0],t[1],t[2]),connect:Yn.bind(null,y),disconnect:nr.bind(null,y),dispatchEvent:(...t)=>_.dispatchEvent(t[0]),removeEventListener:(...t)=>_.removeEventListener(t[0],t[1],t[2])},w=new Map;var b,T;n.port1.addEventListener=(b=n.port1.addEventListener,(...t)=>{if("message"===t[0]){const s="function"==typeof t[1]?t[1]:"object"==typeof t[1]&&null!==t[1]&&"function"==typeof t[1].handleEvent?t[1].handleEvent:null;var e;null!==s&&(void 0!==(e=w.get(t[1]))?t[1]=e:(t[1]=t=>{rr(o.currentTime,o.sampleRate,()=>s(t))},w.set(s,t[1])))}return b.call(n.port1,t[0],t[1],t[2])}),n.port1.removeEventListener=(T=n.port1.removeEventListener,(...t)=>{var e;return"message"===t[0]&&void 0!==(e=w.get(t[1]))&&(w.delete(t[1]),t[1]=e),T.call(n.port1,t[0],t[1],t[2])});let S=null,k=(Object.defineProperty(n.port1,"onmessage",{get:()=>S,set:t=>{"function"==typeof S&&n.port1.removeEventListener("message",S),"function"==typeof(S="function"==typeof t?t:null)&&(n.port1.addEventListener("message",S),n.port1.start())}}),e.prototype.port=n.port1,null);const N=((t,e,s,i)=>{let n=Xt.get(t);void 0===n&&(n=new WeakMap,Xt.set(t,n));t=(async()=>{var t;return t=i,new s(await new Promise((e,s)=>{const{port1:i,port2:n}=new MessageChannel;i.onmessage=({data:t})=>{i.close(),n.close(),e(t)},i.onmessageerror=({data:t})=>{i.close(),n.close(),s(t)},n.postMessage(t)}))})();return n.set(e,t),t})(o,x,e,a),A=(N.then(t=>k=t),Ue(a.numberOfInputs,a.channelCount)),C=Ue(a.numberOfOutputs,h),O=void 0===e.parameterDescriptors?[]:e.parameterDescriptors.reduce((t,{name:e})=>({...t,[e]:new Float32Array(128)}),{});let D=!0;const M=()=>{0{if(null!==k){const r=or(x);for(let i=0;i{We(s,O,t,c+e,i)});for(let e=0;e{if(0t.every(t=>0===t))&&(1===s?E.delete(e):E.set(e,s-1)),t)}),t=rr(o.currentTime+i/o.sampleRate,o.sampleRate,()=>k.process(s,C,O));D=t;for(let e=0,s=0;e_.connect(q).connect(o.destination),F=()=>{_.disconnect(q),q.disconnect()};return I(),ar(x,()=>{if(D){F(),0{D&&(I(),M()),R=!1})}),rp=(Gn=a,c=np,Zn=ir=gs,Xn=ar=Ul,(t,e,s,i,n,r)=>{if(null!==s)try{const c=new s(t,i,r),Zn=new Map;let e=null;if(Object.defineProperties(c,{channelCount:{get:()=>r.channelCount,set:()=>{throw Gn()}},channelCountMode:{get:()=>"explicit",set:()=>{throw Gn()}},onprocessorerror:{get:()=>e,set:t=>{"function"==typeof e&&c.removeEventListener("processorerror",e),"function"==typeof(e="function"==typeof t?t:null)&&c.addEventListener("processorerror",e)}}}),c.addEventListener=(a=c.addEventListener,(...e)=>{if("processorerror"===e[0]){const c="function"==typeof e[1]?e[1]:"object"==typeof e[1]&&null!==e[1]&&"function"==typeof e[1].handleEvent?e[1].handleEvent:null;var t;null!==c&&(void 0!==(t=Zn.get(e[1]))?e[1]=t:(e[1]=t=>{"error"===t.type?(Object.defineProperties(t,{type:{value:"processorerror"}}),c(t)):c(new ErrorEvent(e[0],{...t}))},Zn.set(c,e[1])))}return a.call(c,"error",e[1],e[2]),a.call(c,...e)}),c.removeEventListener=(o=c.removeEventListener,(...t)=>{if("processorerror"===t[0]){const c=Zn.get(t[1]);void 0!==c&&(Zn.delete(t[1]),t[1]=c)}return o.call(c,"error",t[1],t[2]),o.call(c,t[0],t[1],t[2])}),0===r.numberOfOutputs)return c;{const Gn=Qn(t,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return c.connect(Gn).connect(t.destination),Xn(c,()=>Gn.disconnect(),()=>Gn.connect(t.destination))}}catch(t){if(11===t.code)throw Zn();throw t}var o,a;if(void 0===n)throw Zn();{s=r;const h=(new MessageChannel)["port1"];try{h.postMessage(s)}finally{h.close()}}return c(t,e,n,r)}),op=(Dn=Il,Mn=Yn=Ku,En=Fl,Rn=Jn=Ql,qn=Kn=us,In=tr=Jl,Fn=Qn=er=fs,Vn=tp,Nn=nr=ep,Pn=rr=Pu,jn=m,Ln=ti,zn=t,Wn=Vl,Bn=Us,Un=pu,(r,a,h)=>{const c=new WeakMap;let l=null;return{render(t,e){Vn(e,t);var s=c.get(e);return void 0!==s?Promise.resolve(s):(async(o,e)=>{let t=jn(o),s=null;const i=u(t,e),n=Array.isArray(a.outputChannelCount)?a.outputChannelCount:Array.from(a.outputChannelCount);if(null===Ln){const Dn=n.reduce((t,e)=>t+e,0),En=qn(e,{channelCount:Math.max(1,Dn),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,Dn)}),In=[];for(let t=0;t{const s=new zn(En,128*Math.ceil(o.context.length/128),e.sampleRate),i=[],n=[];for(let t=0;t{var e=In(s,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:t.value});return await Wn(s,t,e.offset),e})),r=Rn(s,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,Dn+Mn)});for(let e=0;eBn(o,s,t))),Un(s)};l=(async(t,s,e,n,r,o,a)=>{const h=null===s?128*Math.ceil(t.context.length/128):s.length,c=n.channelCount*n.numberOfInputs,i=r.reduce((t,e)=>t+e,0),l=0===i?null:e.createBuffer(i,h,e.sampleRate);if(void 0===o)throw new Error("Missing the processor constructor.");const u=ge(t),p=await((t,e)=>{t=te(Xt,t),e=m(e);return te(t,e)})(e,t),d=Ue(n.numberOfInputs,n.channelCount),f=Ue(n.numberOfOutputs,r),_=Array.from(t.parameters.keys()).reduce((t,e)=>({...t,[e]:new Float32Array(128)}),{});for(let i=0;i{We(s,_,t,c+e,i)});for(let e=0;e0===u.activeInputs[e].size?[]:t),s=a(i/e.sampleRate,e.sampleRate,()=>p.process(t,f,_));if(null!==l)for(let e=0,s=0;eOn.get(t)),hp=(Cn=sp,(t,e)=>{Cn.set(t,e)}),cp=Nu?(mn=Ju,gn=Pl,vn=op,yn=rp,xn=ge,wn=ap,bn=Qs,Tn=Zs,Sn=ti,kn=hp,An=Is,class extends e{constructor(t,e,s){const i=bn(t),n=Tn(i),r={...s={...ze,...s},outputChannelCount:void 0!==s.outputChannelCount?s.outputChannelCount:1===s.numberOfInputs&&1===s.numberOfOutputs?[s.channelCount]:Array.from({length:s.numberOfOutputs},()=>1)};{var s=r;const{port1:u,port2:p}=new MessageChannel;try{u.postMessage(s)}finally{u.close(),p.close()}}const o=Zt.get(i),a=null==o?void 0:o.get(e),h=!n&&"closed"===i.state&&null!=(s=wn(i))?s:i,c=yn(h,n?null:t.baseLatency,Sn,e,a,r),l=(super(t,!0,c,n?vn(e,r,a):null),[]);c.parameters.forEach((t,e)=>{t=gn(this,n,t);l.push([e,t])}),this._nativeAudioWorkletNode=c,this._onprocessorerror=null,this._parameters=new Le(l),n&&mn(i,this);s=xn(this).activeInputs;kn(c,s)}get onprocessorerror(){return this._onprocessorerror}set onprocessorerror(t){var e="function"==typeof t?An(this,t):null,s=(this._nativeAudioWorkletNode.onprocessorerror=e,this._nativeAudioWorkletNode.onprocessorerror);this._onprocessorerror=null!==s&&s===e?t:s}get parameters(){return null===this._parameters?this._nativeAudioWorkletNode.parameters:this._parameters}get port(){return this._nativeAudioWorkletNode.port}}):void 0,lp=(fn=gs,_n=t,(t,e,s)=>{if(null===_n)throw new Error("Missing the native OfflineAudioContext constructor.");try{return new _n(t,e,s)}catch(t){if("SyntaxError"===t.name)throw fn();throw t}}),up=(on=Ol,an=Ls,hn=Bs,cn=$u,ln=pu,un=ce,pn=Dl,dn=Ml,(t,e)=>hn(t).render(t,e).then(()=>Promise.all(Array.from(cn(e)).map(t=>hn(t).render(t,e)))).then(()=>ln(e)).then(t=>("function"!=typeof t.copyFromChannel?(pn(t),ue(t)):an(un,()=>un(t))||dn(t),on.add(t),t))),pp=(en=Ls,sn=a,nn=lp,rn=up,class extends Uu{constructor(t,e,s){let i;if("number"==typeof t&&void 0!==e&&void 0!==s)i={length:e,numberOfChannels:t,sampleRate:s};else{if("object"!=typeof t)throw new Error("The given parameters are not valid.");i=t}const{length:n,numberOfChannels:r,sampleRate:o}={...vs,...i},a=nn(r,n,o);en(rs,()=>rs(a))||a.addEventListener("statechange",(()=>{let e=0;const s=t=>{"running"===this._state&&(0{this._state=null,xe(this)}))}_waitForThePromiseToSettle(t){null===this._state?this._nativeOfflineAudioContext.dispatchEvent(t):setTimeout(()=>this._waitForThePromiseToSettle(t))}}),dp=(Ki=Ut,tn=$s,t=>{var e=Ki.get(t);return tn(e)||tn(t)}),fp=($i=zt,Ji=Js,t=>$i.has(t)||Ji(t)),_p=(Yi=Bt,Hi=Ks,t=>Yi.has(t)||Hi(t)),mp=(Zi=Ut,Xi=Zs,t=>{var e=Zi.get(t);return Xi(e)||Xi(t)}),gp=()=>(async(t,e,s,i,n,r,o,a,h,c,l,u,p,d,f,_)=>!!(t(e,e)&&t(s,s)&&t(n,n)&&t(r,r)&&t(a,a)&&t(h,h)&&t(c,c)&&t(l,l)&&t(u,u)&&t(p,p)&&t(d,d))&&(await Promise.all([t(i,i),t(o,o),t(f,f),t(_,_)])).every(t=>t))(Ls,(s=>()=>{if(null===s)return!1;const t=new s(1,1,44100).createBuffer(1,1,44100);if(void 0===t.copyToChannel)return!0;var e=new Float32Array(2);try{t.copyFromChannel(e,0,0)}catch{return!1}return!0})(t),(s=>()=>{if(null===s)return!1;if(void 0!==s.prototype&&void 0!==s.prototype.close)return!0;const t=new s,e=void 0!==t.close;try{t.close()}catch{}return e})(Hs),(t=>()=>{if(null===t)return Promise.resolve(!1);const n=new t(1,1,44100);return new Promise(e=>{let s=!0;var t=t=>{s&&(s=!1,n.startRendering(),e(t instanceof TypeError))};let i;try{i=n.decodeAudioData(null,()=>{},t)}catch(e){t(e)}void 0!==i&&i.catch(t)})})(t),(e=>()=>{if(null===e)return!1;let t;try{t=new e({latencyHint:"balanced"})}catch{return!1}return t.close(),!0})(Hs),(s=>()=>{if(null===s)return!1;const t=new s(1,1,44100).createGain(),e=t.connect(t)===t;return t.disconnect(t),e})(t),((r,o)=>async()=>{if(null===r)return!0;if(null===o)return!1;const t=new Blob(['let c,p;class A extends AudioWorkletProcessor{constructor(){super();this.port.onmessage=(e)=>{p=e.data;p.onmessage=()=>{p.postMessage(c);p.close()};this.port.postMessage(0)}}process(){c=1}}registerProcessor("a",A)'],{type:"application/javascript; charset=utf-8"}),s=new MessageChannel,e=new o(1,128,44100),i=URL.createObjectURL(t);let n=!1;try{await e.audioWorklet.addModule(i);const o=new r(e,"a",{numberOfOutputs:0}),t=e.createOscillator();await new Promise(t=>{o.port.onmessage=()=>t(),o.port.postMessage(s.port2,[s.port2])}),o.port.onmessage=()=>n=!0,t.connect(o),t.start(0),await e.startRendering(),n=await new Promise(e=>{s.port1.onmessage=({data:t})=>e(1===t),s.port1.postMessage(0)})}catch{}finally{s.port1.close(),URL.revokeObjectURL(i)}return n})(ti,t),(e=>()=>{if(null===e)return!1;const t=new e(1,1,44100).createChannelMerger();if("max"===t.channelCountMode)return!0;try{t.channelCount=2}catch{return!0}return!1})(t),(e=>()=>{if(null===e)return!1;const t=new e(1,1,44100);return void 0===t.createConstantSource||t.createConstantSource().offset.maxValue!==Number.POSITIVE_INFINITY})(t),(s=>()=>{if(null===s)return!1;const t=new s(1,1,44100),e=t.createConvolver();e.buffer=t.createBuffer(1,1,t.sampleRate);try{e.buffer=t.createBuffer(1,1,t.sampleRate)}catch{return!1}return!0})(t),(e=>()=>{if(null===e)return!1;const t=new e(1,1,44100).createConvolver();try{t.channelCount=1}catch{return!1}return!0})(t),Es,(t=>()=>null!==t&&t.hasOwnProperty("isSecureContext"))(zs),(e=>()=>{if(null===e)return!1;const t=new e;try{return t.createMediaStreamSource(new MediaStream),!1}catch(t){return!0}finally{t.close()}})(Hs),(i=>()=>{if(null===i)return Promise.resolve(!1);const t=new i(1,1,44100);if(void 0===t.createStereoPanner)return Promise.resolve(!0);if(void 0===t.createConstantSource)return Promise.resolve(!0);const e=t.createConstantSource(),s=t.createStereoPanner();return e.channelCount=1,e.offset.value=1,s.channelCount=1,e.start(),e.connect(s).connect(t.destination),t.startRendering().then(t=>1!==t.getChannelData(0)[0])})(t),Rs);function vp(t){return void 0===t}function o(t){return void 0!==t}function yp(t){return"function"==typeof t}function xp(t){return"number"==typeof t}function wp(t){return"[object Object]"===Object.prototype.toString.call(t)&&t.constructor===Object}function bp(t){return"boolean"==typeof t}function d(t){return Array.isArray(t)}function Tp(t){return"string"==typeof t}function Sp(t){return Tp(t)&&/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i.test(t)}function l(t,e){if(!t)throw new Error(e)}function f(t,e,s=1/0){if(!(e<=t&&t<=s))throw new RangeError(`Value must be within [${e}, ${s}], got: `+t)}function kp(t){t.isOffline||"running"===t.state||Rp('The AudioContext is "suspended". Invoke Tone.start() from a user action to start the audio.')}let Ap=!1,Cp=!1;function Op(t){Ap=t}function Dp(t){vp(t)&&Ap&&!Cp&&(Cp=!0,Rp("Events scheduled inside of scheduled callbacks should use the passed in scheduling time. See https://github.com/Tonejs/Tone.js/wiki/Accurate-Timing"))}let Mp=console;function Ep(...t){Mp.log(...t)}function Rp(...t){Mp.warn(...t)}const qp="object"==typeof self?self:null,Ip=qp&&(qp.hasOwnProperty("AudioContext")||qp.hasOwnProperty("webkitAudioContext"));function Fp(t,e,s,i){var n,r=arguments.length,o=r<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,s):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,s,i);else for(var a=t.length-1;0<=a;a--)(n=t[a])&&(o=(r<3?n(o):3{this._createTimeout(),this._callback()},1e3*this._updateInterval)}_createClock(){if("worker"===this._type)try{this._createWorker()}catch(t){this._type="timeout",this._createClock()}else"timeout"===this._type&&this._createTimeout()}_disposeClock(){this._timeout&&clearTimeout(this._timeout),this._worker&&(this._worker.terminate(),this._worker.onmessage=null)}get updateInterval(){return this._updateInterval}set updateInterval(t){this._updateInterval=Math.max(t,this._minimumUpdateInterval),"worker"===this._type&&null!=(t=this._worker)&&t.postMessage(1e3*this._updateInterval)}get type(){return this._type}set type(t){this._disposeClock(),this._type=t,this._createClock()}dispose(){this._disposeClock()}}function Np(t){return _p(t)}function Pp(t){return fp(t)}function jp(t){return mp(t)}function Lp(t){return dp(t)}function zp(t,...e){if(!e.length)return t;var s,i,n=e.shift();if(wp(t)&&wp(n))for(const e in n)s=e,i=n[e],"value"===s||Np(i)||Pp(i)||i instanceof El?t[e]=n[e]:wp(n[e])?(t[e]||Object.assign(t,{[e]:{}}),zp(t[e],n[e])):Object.assign(t,{[e]:n[e]});return zp(t,...e)}function g(e,t,s=[],i){const n={},r=Array.from(t);if(!wp(r[0])||!i||Reflect.has(r[0],i)||Object.keys(r[0]).some(t=>Reflect.has(e,t))||(zp(n,{[i]:r[0]}),s.splice(s.indexOf(i),1),r.shift()),1===r.length&&wp(r[0]))zp(n,r[0]);else for(let t=0;t{Reflect.has(e,t)&&delete e[t]}),e}class Bp{constructor(){this.debug=!1,this._wasDisposed=!1}static getDefaults(){return{}}log(...t){(this.debug||qp&&this.toString()===qp.TONE_DEBUG_CLASS)&&Ep(this,...t)}dispose(){return this._wasDisposed=!0,this}get disposed(){return this._wasDisposed}toString(){return this.name}}Bp.version=P;const Up=1e-6;function Gp(t,e){return t>e+Up}function Qp(t,e){return Gp(t,e)||Xp(t,e)}function Zp(t,e){return t+Upthis.memory){const t=this.length-this.memory;this._timeline.splice(0,t)}return this}remove(t){t=this._timeline.indexOf(t);return-1!==t&&this._timeline.splice(t,1),this}get(t,e="time"){t=this._search(t,e);return-1!==t?this._timeline[t]:null}peek(){return this._timeline[0]}shift(){return this._timeline.shift()}getAfter(t,e="time"){t=this._search(t,e);return t+1=t;)s--;return this._iterate(e,s+1),this}forEachAtTime(s,i){var n=this._search(s);if(-1!==n&&Xp(this._timeline[n].time,s)){let e=n;for(let t=n;0<=t&&Xp(this._timeline[t].time,s);t--)e=t;this._iterate(t=>{i(t)},e,n)}return this}dispose(){return super.dispose(),this._timeline=[],this}}const $p=[];function Jp(t){$p.push(t)}const Kp=[];function td(t){Kp.push(t)}class ed extends Bp{constructor(){super(...arguments),this.name="Emitter"}on(t,e){return t.split(/\W+/).forEach(t=>{vp(this._events)&&(this._events={}),this._events.hasOwnProperty(t)||(this._events[t]=[]),this._events[t].push(e)}),this}once(e,s){const i=(...t)=>{s(...t),this.off(e,i)};return this.on(e,i),this}off(t,s){return t.split(/\W+/).forEach(t=>{if(vp(this._events)&&(this._events={}),this._events.hasOwnProperty(t))if(vp(s))this._events[t]=[];else{const e=this._events[t];for(let t=e.length-1;0<=t;t--)e[t]===s&&e.splice(t,1)}}),this}emit(t,...s){if(this._events&&this._events.hasOwnProperty(t)){const i=this._events[t].slice(0);for(let t=0,e=i.length;t{var e=Object.getOwnPropertyDescriptor(ed.prototype,t);Object.defineProperty(s.prototype,t,e)})}dispose(){return super.dispose(),this._events=void 0,this}}class sd extends ed{constructor(){super(...arguments),this.isOffline=!1}toJSON(){return{}}}class id extends sd{constructor(){super(),this.name="Context",this._constants=new Map,this._timeouts=new Hp,this._timeoutIds=0,this._initialized=!1,this._closeStarted=!1,this.isOffline=!1,this._workletPromise=null;var t,e,s=g(id.getDefaults(),arguments,["context"]);s.context?(this._context=s.context,this._latencyHint=(null==(e=arguments[0])?void 0:e.latencyHint)||""):(this._context=(e={latencyHint:s.latencyHint},new Hu(e)),this._latencyHint=s.latencyHint),this._ticker=new Vp(this.emit.bind(this,"tick"),s.clockSource,s.updateInterval,this._context.sampleRate),this.on("tick",this._timeoutLoop.bind(this)),this._context.onstatechange=()=>{this.emit("statechange",this.state)},this[null!=(t=arguments[0])&&t.hasOwnProperty("updateInterval")?"_lookAhead":"lookAhead"]=s.lookAhead}static getDefaults(){return{clockSource:"worker",latencyHint:"interactive",lookAhead:.1,updateInterval:.05}}initialize(){var e;return this._initialized||(e=this,$p.forEach(t=>t(e)),this._initialized=!0),this}createAnalyser(){return this._context.createAnalyser()}createOscillator(){return this._context.createOscillator()}createBufferSource(){return this._context.createBufferSource()}createBiquadFilter(){return this._context.createBiquadFilter()}createBuffer(t,e,s){return this._context.createBuffer(t,e,s)}createChannelMerger(t){return this._context.createChannelMerger(t)}createChannelSplitter(t){return this._context.createChannelSplitter(t)}createConstantSource(){return this._context.createConstantSource()}createConvolver(){return this._context.createConvolver()}createDelay(t){return this._context.createDelay(t)}createDynamicsCompressor(){return this._context.createDynamicsCompressor()}createGain(){return this._context.createGain()}createIIRFilter(t,e){return this._context.createIIRFilter(t,e)}createPanner(){return this._context.createPanner()}createPeriodicWave(t,e,s){return this._context.createPeriodicWave(t,e,s)}createStereoPanner(){return this._context.createStereoPanner()}createWaveShaper(){return this._context.createWaveShaper()}createMediaStreamSource(t){return l(Lp(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamSource(t)}createMediaElementSource(t){return l(Lp(this._context),"Not available if OfflineAudioContext"),this._context.createMediaElementSource(t)}createMediaStreamDestination(){return l(Lp(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamDestination()}decodeAudioData(t){return this._context.decodeAudioData(t)}get currentTime(){return this._context.currentTime}get state(){return this._context.state}get sampleRate(){return this._context.sampleRate}get listener(){return this.initialize(),this._listener}set listener(t){l(!this._initialized,"The listener cannot be set after initialization."),this._listener=t}get transport(){return this.initialize(),this._transport}set transport(t){l(!this._initialized,"The transport cannot be set after initialization."),this._transport=t}get draw(){return this.initialize(),this._draw}set draw(t){l(!this._initialized,"Draw cannot be set after initialization."),this._draw=t}get destination(){return this.initialize(),this._destination}set destination(t){l(!this._initialized,"The destination cannot be set after initialization."),this._destination=t}createAudioWorkletNode(t,e){return s=this.rawContext,t=t,e=e,l(o(cp),"AudioWorkletNode only works in a secure context (https or localhost)"),new(s instanceof(null==qp?void 0:qp.BaseAudioContext)?null==qp?void 0:qp.AudioWorkletNode:cp)(s,t,e);var s}addAudioWorkletModule(t){return _(this,void 0,void 0,function*(){l(o(this.rawContext.audioWorklet),"AudioWorkletNode is only available in a secure context (https or localhost)"),this._workletPromise||(this._workletPromise=this.rawContext.audioWorklet.addModule(t)),yield this._workletPromise})}workletsAreReady(){return _(this,void 0,void 0,function*(){(yield this._workletPromise)?this._workletPromise:Promise.resolve()})}get updateInterval(){return this._ticker.updateInterval}set updateInterval(t){this._ticker.updateInterval=t}get clockSource(){return this._ticker.type}set clockSource(t){this._ticker.type=t}get lookAhead(){return this._lookAhead}set lookAhead(t){this._lookAhead=t,this.updateInterval=t?t/2:.01}get latencyHint(){return this._latencyHint}get rawContext(){return this._context}now(){return this._context.currentTime+this._lookAhead}immediate(){return this._context.currentTime}resume(){return Lp(this._context)?this._context.resume():Promise.resolve()}close(){return _(this,void 0,void 0,function*(){var e;Lp(this._context)&&"closed"!==this.state&&!this._closeStarted&&(this._closeStarted=!0,yield this._context.close()),this._initialized&&(e=this,Kp.forEach(t=>t(e)))})}getConstant(e){if(this._constants.has(e))return this._constants.get(e);{const t=this._context.createBuffer(1,128,this._context.sampleRate),s=t.getChannelData(0);for(let t=0;tthis._constants[t].disconnect()),this.close(),this}_timeoutLoop(){var t=this.now();let e=this._timeouts.peek();for(;this._timeouts.length&&e&&e.time<=t;)e.callback(),this._timeouts.shift(),e=this._timeouts.peek()}setTimeout(t,e){this._timeoutIds++;var s=this.now();return this._timeouts.add({callback:t,id:this._timeoutIds,time:s+e}),this._timeoutIds}clearTimeout(e){return this._timeouts.forEach(t=>{t.id===e&&this._timeouts.remove(t)}),this}clearInterval(t){return this.clearTimeout(t)}setInterval(e,s){const i=++this._timeoutIds,n=()=>{var t=this.now();this._timeouts.add({callback:()=>{e(),n()},id:i,time:t+s})};return n(),i}}function y(e,t){d(t)?t.forEach(t=>y(e,t)):Object.defineProperty(e,t,{enumerable:!0,writable:!1})}function nd(e,t){d(t)?t.forEach(t=>nd(e,t)):Object.defineProperty(e,t,{writable:!0})}const x=()=>{};class w extends Bp{constructor(){super(),this.name="ToneAudioBuffer",this.onload=x;var t=g(w.getDefaults(),arguments,["url","onload","onerror"]);this.reverse=t.reverse,this.onload=t.onload,Tp(t.url)?this.load(t.url).catch(t.onerror):t.url&&this.set(t.url)}static getDefaults(){return{onerror:x,onload:x,reverse:!1}}get sampleRate(){return(this._buffer||b()).sampleRate}set(t){return t instanceof w?t.loaded?this._buffer=t.get():t.onload=()=>{this.set(t),this.onload(this)}:this._buffer=t,this._reversed&&this._reverse(),this}get(){return this._buffer}load(e){return _(this,void 0,void 0,function*(){var t=w.load(e).then(t=>{this.set(t),this.onload(this)});w.downloads.push(t);try{yield t}finally{const e=w.downloads.indexOf(t);w.downloads.splice(e,1)}return this})}dispose(){return super.dispose(),this._buffer=void 0,this}fromArray(t){const e=d(t)&&0t/i),this.fromArray(e)}return this}toArray(e){if(xp(e))return this.getChannelData(e);if(1===this.numberOfChannels)return this.toArray(0);{const e=[];for(let t=0;tsetTimeout(t,1)))}})}render(){return _(this,arguments,void 0,function*(t=!0){yield this.workletsAreReady(),yield this._renderClock(t);t=yield this._context.startRendering();return new w(t)})}close(){return Promise.resolve()}}const od=new class extends sd{constructor(){super(...arguments),this.lookAhead=0,this.latencyHint=0,this.isOffline=!1}createAnalyser(){return{}}createOscillator(){return{}}createBufferSource(){return{}}createBiquadFilter(){return{}}createBuffer(t,e,s){return{}}createChannelMerger(t){return{}}createChannelSplitter(t){return{}}createConstantSource(){return{}}createConvolver(){return{}}createDelay(t){return{}}createDynamicsCompressor(){return{}}createGain(){return{}}createIIRFilter(t,e){return{}}createPanner(){return{}}createPeriodicWave(t,e,s){return{}}createStereoPanner(){return{}}createWaveShaper(){return{}}createMediaStreamSource(t){return{}}createMediaElementSource(t){return{}}createMediaStreamDestination(){return{}}decodeAudioData(t){return Promise.resolve({})}createAudioWorkletNode(t,e){return{}}get rawContext(){return{}}addAudioWorkletModule(t){return _(this,void 0,void 0,function*(){return Promise.resolve()})}resume(){return Promise.resolve()}setTimeout(t,e){return 0}clearTimeout(t){return this}setInterval(t,e){return 0}clearInterval(t){return this}getConstant(t){return{}}get currentTime(){return 0}get state(){return{}}get sampleRate(){return 0}get listener(){return{}}get transport(){return{}}get draw(){return{}}set draw(t){}get destination(){return{}}set destination(t){}now(){return 0}immediate(){return 0}};let ad=od;function b(){return ad===od&&Ip&&hd(new id),ad}function hd(t,e=!1){e&&ad.dispose(),ad=Lp(t)?new id(t):jp(t)?new rd(t):t}if(qp&&!qp.TONE_SILENCE_LOGGING){let t="v";const N=` * Tone.js ${t="dev"===P?"":t}${P} * `;console.log("%c"+N,"background: #000; color: #fff")}function cd(t){return Math.pow(10,t/20)}function ld(t){return Math.log(t)/Math.LN10*20}function ud(t){return Math.pow(2,t/12)}let pd=440;function dd(t){return Math.round(fd(t))}function fd(t){return 69+12*Math.log2(t/pd)}function _d(t){return pd*Math.pow(2,(t-69)/12)}class md extends Bp{constructor(t,e,s){super(),this.defaultUnits="s",this._val=e,this._units=s,this.context=t,this._expressions=this._getExpressions()}_getExpressions(){return{hz:{method:t=>this._frequencyToUnits(parseFloat(t)),regexp:/^(\d+(?:\.\d+)?)hz$/i},i:{method:t=>this._ticksToUnits(parseInt(t,10)),regexp:/^(\d+)i$/i},m:{method:t=>this._beatsToUnits(parseInt(t,10)*this._getTimeSignature()),regexp:/^(\d+)m$/i},n:{method:(t,e)=>{t=parseInt(t,10),e="."===e?1.5:1;return 1===t?this._beatsToUnits(this._getTimeSignature())*e:this._beatsToUnits(4/t)*e},regexp:/^(\d+)n(\.?)$/i},number:{method:t=>this._expressions[this.defaultUnits].method.call(this,t),regexp:/^(\d+(?:\.\d+)?)$/},s:{method:t=>this._secondsToUnits(parseFloat(t)),regexp:/^(\d+(?:\.\d+)?)s$/},samples:{method:t=>parseInt(t,10)/this.context.sampleRate,regexp:/^(\d+)samples$/},t:{method:t=>{t=parseInt(t,10);return this._beatsToUnits(8/(3*Math.floor(t)))},regexp:/^(\d+)t$/i},tr:{method:(t,e,s)=>{let i=0;return t&&"0"!==t&&(i+=this._beatsToUnits(this._getTimeSignature()*parseFloat(t))),e&&"0"!==e&&(i+=this._beatsToUnits(parseFloat(e))),s&&"0"!==s&&(i+=this._beatsToUnits(parseFloat(s)/4)),i},regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?$/}}}valueOf(){if(this._val instanceof md&&this.fromType(this._val),vp(this._val))return this._noArg();if(Tp(this._val)&&vp(this._units)){for(const t in this._expressions)if(this._expressions[t].regexp.test(this._val.trim())){this._units=t;break}}else if(wp(this._val)){let t=0;for(const s in this._val){var e;o(this._val[s])&&(e=this._val[s],t+=new this.constructor(this.context,s).valueOf()*e)}return t}if(o(this._units)){const i=this._expressions[this._units],n=this._val.toString().trim().match(i.regexp);return n?i.method.apply(this,n.slice(1)):i.method.call(this,this._val)}return Tp(this._val)?parseFloat(this._val):this._val}_frequencyToUnits(t){return 1/t}_beatsToUnits(t){return 60/this._getBpm()*t}_secondsToUnits(t){return t}_ticksToUnits(t){return t*this._beatsToUnits(1)/this._getPPQ()}_noArg(){return this._now()}_getBpm(){return this.context.transport.bpm.value}_getTimeSignature(){return this.context.transport.timeSignature}_getPPQ(){return this.context.transport.PPQ}fromType(t){switch(this._units=void 0,this.defaultUnits){case"s":this._val=t.toSeconds();break;case"i":this._val=t.toTicks();break;case"hz":this._val=t.toFrequency();break;case"midi":this._val=t.toMidi()}return this}toFrequency(){return 1/this.toSeconds()}toSamples(){return this.toSeconds()*this.context.sampleRate}toMilliseconds(){return 1e3*this.toSeconds()}}class gd extends md{constructor(){super(...arguments),this.name="TimeClass"}_getExpressions(){return Object.assign(super._getExpressions(),{now:{method:t=>this._now()+new this.constructor(this.context,t).valueOf(),regexp:/^\+(.+)/},quantize:{method:t=>{t=new gd(this.context,t).valueOf();return this._secondsToUnits(this.context.transport.nextSubdivision(t))},regexp:/^@(.+)/}})}quantize(t,e=1){var t=new this.constructor(this.context,t).valueOf(),s=this.valueOf();return s+(Math.round(s/t)*t-s)*e}toNotation(){const s=this.toSeconds(),e=["1m"];for(let t=1;t<9;t++){const i=Math.pow(2,t);e.push(i+"n."),e.push(i+"n"),e.push(i+"t")}e.push("0");let i=e[0],n=new gd(this.context,e[0]).toSeconds();return e.forEach(t=>{var e=new gd(this.context,t).toSeconds();Math.abs(e-s)this.transpose(t))}toMidi(){return dd(this.valueOf())}toNote(){var t=this.toFrequency(),t=Math.log2(t/vd.A4);let e=Math.round(12*t)+57;const s=Math.floor(e/12);return s<0&&(e+=-12*s),xd[e%12]+s.toString()}toSeconds(){return 1/super.toSeconds()}toTicks(){var t=this._beatsToUnits(1),t=this.valueOf()/t;return Math.floor(t*this._getPPQ())}_noArg(){return 0}_frequencyToUnits(t){return t}_ticksToUnits(t){return 1/(60*t/(this._getBpm()*this._getPPQ()))}_beatsToUnits(t){return 1/super._beatsToUnits(t)}_secondsToUnits(t){return 1/t}static mtof(t){return _d(t)}static ftom(t){return dd(t)}}const yd={cbbb:-3,cbb:-2,cb:-1,c:0,"c#":1,cx:2,"c##":2,"c###":3,"cx#":3,"c#x":3,dbbb:-1,dbb:0,db:1,d:2,"d#":3,dx:4,"d##":4,"d###":5,"dx#":5,"d#x":5,ebbb:1,ebb:2,eb:3,e:4,"e#":5,ex:6,"e##":6,"e###":7,"ex#":7,"e#x":7,fbbb:2,fbb:3,fb:4,f:5,"f#":6,fx:7,"f##":7,"f###":8,"fx#":8,"f#x":8,gbbb:4,gbb:5,gb:6,g:7,"g#":8,gx:9,"g##":9,"g###":10,"gx#":10,"g#x":10,abbb:6,abb:7,ab:8,a:9,"a#":10,ax:11,"a##":11,"a###":12,"ax#":12,"a#x":12,bbbb:8,bbb:9,bb:10,b:11,"b#":12,bx:13,"b##":13,"b###":14,"bx#":14,"b#x":14},xd=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];class T extends gd{constructor(){super(...arguments),this.name="TransportTime"}_now(){return this.context.transport.seconds}}class S extends Bp{constructor(){super();var t=g(S.getDefaults(),arguments,["context"]);this.defaultContext?this.context=this.defaultContext:this.context=t.context}static getDefaults(){return{context:b()}}now(){return this.context.currentTime+this.context.lookAhead}immediate(){return this.context.currentTime}get sampleTime(){return 1/this.context.sampleRate}get blockTime(){return 128/this.context.sampleRate}toSeconds(t){return Dp(t),new gd(this.context,t).toSeconds()}toFrequency(t){return new vd(this.context,t).toFrequency()}toTicks(t){return new T(this.context,t).toTicks()}_getPartialProperties(e){const s=this.get();return Object.keys(s).forEach(t=>{vp(e[t])&&delete s[t]}),s}get(){const s=this.constructor.getDefaults();return Object.keys(s).forEach(t=>{if(Reflect.has(this,t)){const e=this[t];o(e)&&o(e.value)&&o(e.setValueAtTime)?s[t]=e.value:e instanceof S?s[t]=e._getPartialProperties(s[t]):d(e)||xp(e)||Tp(e)||bp(e)?s[t]=e:delete s[t]}}),s}set(e){return Object.keys(e).forEach(t=>{Reflect.has(this,t)&&o(this[t])&&(this[t]&&o(this[t].value)&&o(this[t].setValueAtTime)?this[t].value!==e[t]&&(this[t].value=e[t]):this[t]instanceof S?this[t].set(e[t]):this[t]=e[t])}),this}}class wd extends Hp{constructor(t="stopped"){super(),this.name="StateTimeline",this._initial=t,this.setStateAtTime(this._initial,0)}getValueAtTime(t){t=this.get(t);return null!==t?t.state:this._initial}setStateAtTime(t,e,s){return f(e,0),this.add(Object.assign({},s,{state:t,time:e})),this}getLastState(e,s){for(let t=this._search(s);0<=t;t--){const s=this._timeline[t];if(s.state===e)return s}}getNextState(e,t){const s=this._search(t);if(-1!==s)for(let t=s;t{"cancelScheduledValues"===t.type?e.cancelScheduledValues(t.time):"setTargetAtTime"===t.type?e.setTargetAtTime(t.value,t.time,t.constant):e[t.type](t.value,t.time)}),this}setParam(t){l(this._swappable,"The Param must be assigned as 'swappable' in the constructor");const e=this.input;return e.disconnect(this._param),this.apply(t),this._param=t,e.connect(this._param),this}dispose(){return super.dispose(),this._events.dispose(),this}get defaultValue(){return this._toType(this._param.defaultValue)}_exponentialApproach(t,e,s,i,n){return s+(e-s)*Math.exp(-(n-t)/i)}_linearInterpolate(t,e,s,i,n){return e+(n-t)/(s-t)*(i-e)}_exponentialInterpolate(t,e,s,i,n){return e*Math.pow(i/e,(n-t)/(s-t))}}class A extends S{constructor(){super(...arguments),this._internalChannels=[]}get numberOfInputs(){return o(this.input)?Np(this.input)||this.input instanceof k?1:this.input.numberOfInputs:0}get numberOfOutputs(){return o(this.output)?this.output.numberOfOutputs:0}_isAudioNode(t){return o(t)&&(t instanceof A||Pp(t))}_getInternalNodes(){const t=this._internalChannels.slice(0);return this._isAudioNode(this.input)&&t.push(this.input),this._isAudioNode(this.output)&&this.input!==this.output&&t.push(this.output),t}_setChannelProperties(e){this._getInternalNodes().forEach(t=>{t.channelCount=e.channelCount,t.channelCountMode=e.channelCountMode,t.channelInterpretation=e.channelInterpretation})}_getChannelProperties(){var t=this._getInternalNodes(),t=(l(0this.connect(t)),this}dispose(){return super.dispose(),o(this.input)&&(this.input instanceof A?this.input.dispose():Pp(this.input)&&this.input.disconnect()),o(this.output)&&(this.output instanceof A?this.output.dispose():Pp(this.output)&&this.output.disconnect()),this._internalChannels=[],this}}function bd(...t){var e=t.shift();t.reduce((t,e)=>(t instanceof A?t.connect(e):Pp(t)&&Td(t,e),e),e)}function Td(t,e,s=0,i=0){for(l(o(t),"Cannot connect from undefined node"),l(o(e),"Cannot connect to undefined node"),(e instanceof A||Pp(e))&&l(0=this._startTime&&(-1===this._stopTime||t<=this._stopTime)?"started":"stopped"},this._fadeIn=t.fadeIn,this._fadeOut=t.fadeOut,this._curve=t.curve,this.onended=t.onended}static getDefaults(){return Object.assign(A.getDefaults(),{curve:"linear",fadeIn:0,fadeOut:0,onended:x})}_startGain(t,e=1){l(-1===this._startTime,"Source cannot be started more than once");var s=this.toSeconds(this._fadeIn);return this._startTime=t+s,this._startTime=Math.max(this._startTime,this.context.currentTime),0{var t="exponential"===this._curve?2*e:0;this._stopSource(this.now()+t),this._onended()},this._stopTime-this.context.currentTime),this}_onended(){var t;this.onended===x||(this.onended(this),this.onended=x,this.context.isOffline)||(t=()=>this.dispose(),void 0!==window.requestIdleCallback?window.requestIdleCallback(t):setTimeout(t,1e3))}get state(){return this.getStateAtTime(this.now())}cancelStop(){return this.log("cancelStop"),l(-1!==this._startTime,"Source is not started"),this._gainNode.gain.cancelScheduledValues(this._startTime+this.sampleTime),this.context.clearTimeout(this._timeout),this._stopTime=-1,this}dispose(){return super.dispose(),this._gainNode.dispose(),this.onended=x,this}}class Ad extends kd{constructor(){var t=g(Ad.getDefaults(),arguments,["offset"]);super(t),this.name="ToneConstantSource",this._source=this.context.createConstantSource(),Td(this._source,this._gainNode),this.offset=new k({context:this.context,convert:t.convert,param:this._source.offset,units:t.units,value:t.offset,minValue:t.minValue,maxValue:t.maxValue})}static getDefaults(){return Object.assign(kd.getDefaults(),{convert:!0,offset:1,units:"number"})}start(t){t=this.toSeconds(t);return this.log("start",t),this._startGain(t),this._source.start(t),this}_stopSource(t){this._source.stop(t)}dispose(){return super.dispose(),"started"===this.state&&this.stop(),this._source.disconnect(),this.offset.dispose(),this}}class O extends A{constructor(){var t=g(O.getDefaults(),arguments,["value","units"]);super(t),this.name="Signal",this.override=!0,this.output=this._constantSource=new Ad({context:this.context,convert:t.convert,offset:t.value,units:t.units,minValue:t.minValue,maxValue:t.maxValue}),this._constantSource.start(0),this.input=this._param=this._constantSource.offset}static getDefaults(){return Object.assign(A.getDefaults(),{convert:!0,units:"number",value:0})}connect(t,e=0,s=0){return Cd(this,t,e,s),this}dispose(){return super.dispose(),this._param.dispose(),this._constantSource.dispose(),this}setValueAtTime(t,e){return this._param.setValueAtTime(t,e),this}getValueAtTime(t){return this._param.getValueAtTime(t)}setRampPoint(t){return this._param.setRampPoint(t),this}linearRampToValueAtTime(t,e){return this._param.linearRampToValueAtTime(t,e),this}exponentialRampToValueAtTime(t,e){return this._param.exponentialRampToValueAtTime(t,e),this}exponentialRampTo(t,e,s){return this._param.exponentialRampTo(t,e,s),this}linearRampTo(t,e,s){return this._param.linearRampTo(t,e,s),this}targetRampTo(t,e,s){return this._param.targetRampTo(t,e,s),this}exponentialApproachValueAtTime(t,e,s){return this._param.exponentialApproachValueAtTime(t,e,s),this}setTargetAtTime(t,e,s){return this._param.setTargetAtTime(t,e,s),this}setValueCurveAtTime(t,e,s,i){return this._param.setValueCurveAtTime(t,e,s,i),this}cancelScheduledValues(t){return this._param.cancelScheduledValues(t),this}cancelAndHoldAtTime(t){return this._param.cancelAndHoldAtTime(t),this}rampTo(t,e,s){return this._param.rampTo(t,e,s),this}get value(){return this._param.value}set value(t){this._param.value=t}get convert(){return this._param.convert}set convert(t){this._param.convert=t}get units(){return this._param.units}get overridden(){return this._param.overridden}set overridden(t){this._param.overridden=t}get maxValue(){return this._param.maxValue}get minValue(){return this._param.minValue}apply(t){return this._param.apply(t),this}}function Cd(t,e,s,i){(e instanceof k||Np(e)||e instanceof O&&e.override)&&(e.cancelScheduledValues(0),e.setValueAtTime(0,0),e instanceof O&&(e.overridden=!0)),Td(t,e,s,i)}class Od extends k{constructor(){var t=g(Od.getDefaults(),arguments,["value"]);super(t),this.name="TickParam",this._events=new Hp(1/0),this._multiplier=1,this._multiplier=t.multiplier,this._events.cancel(0),this._events.add({ticks:0,time:0,type:"setValueAtTime",value:this._fromType(t.value)}),this.setValueAtTime(t.value,0)}static getDefaults(){return Object.assign(k.getDefaults(),{multiplier:1,units:"hertz",value:1})}setTargetAtTime(t,e,s){e=this.toSeconds(e),this.setRampPoint(e);const i=this._fromType(t),n=this._events.get(e),r=Math.round(Math.max(1/s,1));for(let t=0;t<=r;t++){const r=s*t+e,o=this._exponentialApproach(n.time,n.value,i,s,r);this.linearRampToValueAtTime(this._toType(o),r)}return this}setValueAtTime(t,e){var s=this.toSeconds(e);super.setValueAtTime(t,e);const i=this._events.get(s),n=this._events.previousEvent(i),r=this._getTicksUntilEvent(n,s);return i.ticks=Math.max(r,0),this}linearRampToValueAtTime(t,e){var s=this.toSeconds(e);super.linearRampToValueAtTime(t,e);const i=this._events.get(s),n=this._events.previousEvent(i),r=this._getTicksUntilEvent(n,s);return i.ticks=Math.max(r,0),this}exponentialRampToValueAtTime(t,e){e=this.toSeconds(e);const s=this._fromType(t),i=this._events.get(e),n=Math.round(Math.max(10*(e-i.time),1)),r=(e-i.time)/n;for(let t=0;t<=n;t++){const n=r*t+i.time,o=this._exponentialInterpolate(i.time,i.value,e,s,n);this.linearRampToValueAtTime(this._toType(o),n)}return this}_getTicksUntilEvent(t,e){if(null===t)t={ticks:0,time:0,type:"setValueAtTime",value:0};else if(vp(t.ticks)){const e=this._events.previousEvent(t);t.ticks=this._getTicksUntilEvent(e,t.time)}var s=this._fromType(this.getValueAtTime(t.time));let i=this._fromType(this.getValueAtTime(e));var n=this._events.get(e);return n&&n.time===e&&"setValueAtTime"===n.type&&(i=this._fromType(this.getValueAtTime(e-this.sampleTime))),.5*(e-t.time)*(s+i)+t.ticks}getTicksAtTime(t){var t=this.toSeconds(t),e=this._events.get(t);return Math.max(this._getTicksUntilEvent(e,t),0)}getDurationOfTicks(t,e){var s=this.toSeconds(e),e=this.getTicksAtTime(e);return this.getTimeOfTick(e+t)-s}getTimeOfTick(t){var e,s,i,n=this._events.get(t,"ticks"),r=this._events.getAfter(t,"ticks");return n&&n.ticks===t?n.time:n&&r&&"linearRampToValueAtTime"===r.type&&n.value!==r.value?(e=this._fromType(this.getValueAtTime(n.time)),r=(this._fromType(this.getValueAtTime(r.time))-e)/(r.time-n.time),(0<(i=(-e+(s=Math.sqrt(Math.pow(e,2)-2*r*(n.ticks-t))))/r)?i:(-e-s)/r)+n.time):n?0===n.value?1/0:n.time+(t-n.ticks)/n.value:t/this._initialValue}ticksToTime(t,e){return this.getDurationOfTicks(t,e)}timeToTicks(t,e){var e=this.toSeconds(e),t=this.toSeconds(t),s=this.getTicksAtTime(e);return this.getTicksAtTime(e+t)-s}_fromType(t){return"bpm"===this.units&&this.multiplier?1/(60/t/this.multiplier):super._fromType(t)}_toType(t){return"bpm"===this.units&&this.multiplier?t/this.multiplier*60:super._toType(t)}get multiplier(){return this._multiplier}set multiplier(t){var e=this.value;this._multiplier=t,this.cancelScheduledValues(0),this.setValueAtTime(e,0)}}class Dd extends O{constructor(){var t=g(Dd.getDefaults(),arguments,["value"]);super(t),this.name="TickSignal",this.input=this._param=new Od({context:this.context,convert:t.convert,multiplier:t.multiplier,param:this._constantSource.offset,units:t.units,value:t.value})}static getDefaults(){return Object.assign(O.getDefaults(),{multiplier:1,units:"hertz",value:1})}ticksToTime(t,e){return this._param.ticksToTime(t,e)}timeToTicks(t,e){return this._param.timeToTicks(t,e)}getTimeOfTick(t){return this._param.getTimeOfTick(t)}getDurationOfTicks(t,e){return this._param.getDurationOfTicks(t,e)}getTicksAtTime(t){return this._param.getTicksAtTime(t)}get multiplier(){return this._param.multiplier}set multiplier(t){this._param.multiplier=t}dispose(){return super.dispose(),this._param.dispose(),this}}class Md extends S{constructor(){var t=g(Md.getDefaults(),arguments,["frequency"]);super(t),this.name="TickSource",this._state=new wd,this._tickOffset=new Hp,this._ticksAtTime=new Hp,this._secondsAtTime=new Hp,this.frequency=new Dd({context:this.context,units:t.units,value:t.frequency}),y(this,"frequency"),this._state.setStateAtTime("stopped",0),this.setTicksAtTime(0,0)}static getDefaults(){return Object.assign({frequency:1,units:"hertz"},S.getDefaults())}get state(){return this.getStateAtTime(this.now())}start(t,e){t=this.toSeconds(t);return"started"!==this._state.getValueAtTime(t)&&(this._state.setStateAtTime("started",t),o(e)&&this.setTicksAtTime(e,t),this._ticksAtTime.cancel(t),this._secondsAtTime.cancel(t)),this}stop(t){var e=this.toSeconds(t);if("stopped"===this._state.getValueAtTime(e)){const t=this._state.get(e);t&&0{let e=r.time;var s=this._tickOffset.get(t.time);s&&s.time>=r.time&&(o=s.ticks,e=s.time),"started"===r.state&&"started"!==t.state&&(o+=this.frequency.getTicksAtTime(t.time)-this.frequency.getTicksAtTime(e),t.time!==n.time&&(a={state:t.state,time:t.time,ticks:o})),r=t}),this._state.remove(n),a&&this._ticksAtTime.add(a),o}get ticks(){return this.getTicksAtTime(this.now())}set ticks(t){this.setTicksAtTime(t,this.now())}get seconds(){return this.getSecondsAtTime(this.now())}set seconds(t){var e=this.now(),t=this.frequency.timeToTicks(t,e);this.setTicksAtTime(t,e)}getSecondsAtTime(t){t=this.toSeconds(t);const e=this._state.getLastState("stopped",t),i={state:"paused",time:t};this._state.add(i);var s=this._secondsAtTime.get(t);let n=s||e,r=s?s.seconds:0,o=null;return this._state.forEachBetween(n.time,t+this.sampleTime,t=>{let e=n.time;var s=this._tickOffset.get(t.time);s&&s.time>=n.time&&(r=s.seconds,e=s.time),"started"===n.state&&"started"!==t.state&&(r+=t.time-e,t.time!==i.time&&(o={state:t.state,time:t.time,seconds:r})),n=t}),this._state.remove(i),o&&this._secondsAtTime.add(o),r}setTicksAtTime(t,e){return e=this.toSeconds(e),this._tickOffset.cancel(e),this._tickOffset.add({seconds:this.frequency.getDurationOfTicks(t,e),ticks:t,time:e}),this._ticksAtTime.cancel(e),this._secondsAtTime.cancel(e),this}getStateAtTime(t){return t=this.toSeconds(t),this._state.getValueAtTime(t)}getTimeOfTick(t,e=this.now()){var s=this._tickOffset.get(e),e=this._state.get(e),e=Math.max(s.time,e.time),e=this.frequency.getTicksAtTime(e)+t-s.ticks;return this.frequency.getTimeOfTick(e)}forEachTickBetween(s,i,n){let r=this._state.get(s),o=(this._state.forEachBetween(s,i,t=>{r&&"started"===r.state&&"started"!==t.state&&this.forEachTickBetween(Math.max(r.time,s),t.time-this.sampleTime,n),r=t}),null);if(r&&"started"===r.state){var a=Math.max(r.time,s),a=this.frequency.getTicksAtTime(a),h=a-this.frequency.getTicksAtTime(r.time);let t=Math.ceil(h)-h,e=(t=Xp(t,1)?0:t,this.frequency.getTimeOfTick(a+t));for(;e{switch(t.state){case"started":var e=this._tickSource.getTicksAtTime(t.time);this.emit("start",t.time,e);break;case"stopped":0!==t.time&&this.emit("stop",t.time);break;case"paused":this.emit("pause",t.time)}}),this._tickSource.forEachTickBetween(t,e,(t,e)=>{this.callback(t,e)}))}getStateAtTime(t){t=this.toSeconds(t);return this._state.getValueAtTime(t)}dispose(){return super.dispose(),this.context.off("tick",this._boundLoop),this._tickSource.dispose(),this._state.dispose(),this}}ed.mixin(Ed);class Rd extends A{constructor(){var t=g(Rd.getDefaults(),arguments,["delayTime","maxDelay"]),e=(super(t),this.name="Delay",this.toSeconds(t.maxDelay));this._maxDelay=Math.max(e,this.toSeconds(t.delayTime)),this._delayNode=this.input=this.output=this.context.createDelay(e),this.delayTime=new k({context:this.context,param:this._delayNode.delayTime,units:"time",value:t.delayTime,minValue:0,maxValue:this.maxDelay}),y(this,"delayTime")}static getDefaults(){return Object.assign(A.getDefaults(),{delayTime:0,maxDelay:1})}get maxDelay(){return this._maxDelay}dispose(){return super.dispose(),this._delayNode.disconnect(),this.delayTime.dispose(),this}}class qd extends A{constructor(){var t=g(qd.getDefaults(),arguments,["volume"]);super(t),this.name="Volume",this.input=this.output=new C({context:this.context,gain:t.volume,units:"decibels"}),this.volume=this.output.gain,y(this,"volume"),this._unmutedVolume=t.volume,this.mute=t.mute}static getDefaults(){return Object.assign(A.getDefaults(),{mute:!1,volume:0})}get mute(){return this.volume.value===-1/0}set mute(t){!this.mute&&t?(this._unmutedVolume=this.volume.value,this.volume.value=-1/0):this.mute&&!t&&(this.volume.value=this._unmutedVolume)}dispose(){return super.dispose(),this.input.dispose(),this.volume.dispose(),this}}class Id extends A{constructor(){var t=g(Id.getDefaults(),arguments);super(t),this.name="Destination",this.input=new qd({context:this.context}),this.output=new C({context:this.context}),this.volume=this.input.volume,bd(this.input,this.output,this.context.rawContext.destination),this.mute=t.mute,this._internalChannels=[this.input,this.context.rawContext.destination,this.output]}static getDefaults(){return Object.assign(A.getDefaults(),{mute:!1,volume:0})}get mute(){return this.input.mute}set mute(t){this.input.mute=t}chain(...t){return this.input.disconnect(),t.unshift(this.input),t.push(this.output),bd(...t),this}get maxChannelCount(){return this.context.rawContext.destination.maxChannelCount}dispose(){return super.dispose(),this.volume.dispose(),this}}Jp(t=>{t.destination=new Id({context:t})}),td(t=>{t.destination.dispose()});class Fd extends A{constructor(){super(...arguments),this.name="Listener",this.positionX=new k({context:this.context,param:this.context.rawContext.listener.positionX}),this.positionY=new k({context:this.context,param:this.context.rawContext.listener.positionY}),this.positionZ=new k({context:this.context,param:this.context.rawContext.listener.positionZ}),this.forwardX=new k({context:this.context,param:this.context.rawContext.listener.forwardX}),this.forwardY=new k({context:this.context,param:this.context.rawContext.listener.forwardY}),this.forwardZ=new k({context:this.context,param:this.context.rawContext.listener.forwardZ}),this.upX=new k({context:this.context,param:this.context.rawContext.listener.upX}),this.upY=new k({context:this.context,param:this.context.rawContext.listener.upY}),this.upZ=new k({context:this.context,param:this.context.rawContext.listener.upZ})}static getDefaults(){return Object.assign(A.getDefaults(),{positionX:0,positionY:0,positionZ:0,forwardX:0,forwardY:0,forwardZ:-1,upX:0,upY:1,upZ:0})}dispose(){return super.dispose(),this.positionX.dispose(),this.positionY.dispose(),this.positionZ.dispose(),this.forwardX.dispose(),this.forwardY.dispose(),this.forwardZ.dispose(),this.upX.dispose(),this.upY.dispose(),this.upZ.dispose(),this}}Jp(t=>{t.listener=new Fd({context:t})}),td(t=>{t.listener.dispose()});class Vd extends Bp{constructor(){super(),this.name="ToneAudioBuffers",this._buffers=new Map,this._loadingCount=0;const s=g(Vd.getDefaults(),arguments,["urls","onload","baseUrl"],"urls");this.baseUrl=s.baseUrl,Object.keys(s.urls).forEach(t=>{this._loadingCount++;var e=s.urls[t];this.add(t,e,this._bufferLoaded.bind(this,s.onload),s.onerror)})}static getDefaults(){return{baseUrl:"",onerror:x,onload:x,urls:{}}}has(t){return this._buffers.has(t.toString())}get(t){return l(this.has(t),"ToneAudioBuffers has no buffer named: "+t),this._buffers.get(t.toString())}_bufferLoaded(t){this._loadingCount--,0===this._loadingCount&&t&&t()}get loaded(){return Array.from(this._buffers).every(([,t])=>t.loaded)}add(t,e,s=x,i=x){return Tp(e)?(this.baseUrl&&"data:audio/"===e.trim().substring(0,11).toLowerCase()&&(this.baseUrl=""),this._buffers.set(t.toString(),new w(this.baseUrl+e,s,i))):this._buffers.set(t.toString(),new w(e,s,i)),this}dispose(){return super.dispose(),this._buffers.forEach(t=>t.dispose()),this._buffers.clear(),this}}class Nd extends vd{constructor(){super(...arguments),this.name="MidiClass",this.defaultUnits="midi"}_frequencyToUnits(t){return dd(super._frequencyToUnits(t))}_ticksToUnits(t){return dd(super._ticksToUnits(t))}_beatsToUnits(t){return dd(super._beatsToUnits(t))}_secondsToUnits(t){return dd(super._secondsToUnits(t))}toMidi(){return this.valueOf()}toFrequency(){return _d(this.toMidi())}transpose(t){return new Nd(this.context,this.toMidi()+t)}}class D extends T{constructor(){super(...arguments),this.name="Ticks",this.defaultUnits="i"}_now(){return this.context.transport.ticks}_beatsToUnits(t){return this._getPPQ()*t}_secondsToUnits(t){return Math.floor(t/(60/this._getBpm())*this._getPPQ())}_ticksToUnits(t){return t}toTicks(){return this.valueOf()}toSeconds(){return this.valueOf()/this._getPPQ()*(60/this._getBpm())}}class Pd extends S{constructor(){super(...arguments),this.name="Draw",this.expiration=.25,this.anticipation=.008,this._events=new Hp,this._boundDrawLoop=this._drawLoop.bind(this),this._animationFrame=-1}schedule(t,e){return this._events.add({callback:t,time:this.toSeconds(e)}),1===this._events.length&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop)),this}cancel(t){return this._events.cancel(this.toSeconds(t)),this}_drawLoop(){for(var t=this.context.currentTime;this._events.length&&this._events.peek().time-this.anticipation<=t;){const e=this._events.shift();e&&t-e.time<=this.expiration&&e.callback()}0{t.draw=new Pd({context:t})}),td(t=>{t.draw.dispose()});class jd extends Bp{constructor(){super(...arguments),this.name="IntervalTimeline",this._root=null,this._length=0}add(t){l(o(t.time),"Events must have a time property"),l(o(t.duration),"Events must have a duration parameter"),t.time=t.time.valueOf();let e=new Ld(t.time,t.time+t.duration,t);for(null===this._root?this._root=e:this._root.insert(e),this._length++;null!==e;)e.updateHeight(),e.updateMax(),this._rebalance(e),e=e.parent;return this}remove(t){if(null!==this._root){var e=[];this._root.search(t.time,e);for(const s of e)if(s.event===t){this._removeNode(s),this._length--;break}}return this}get length(){return this._length}cancel(t){return this.forEachFrom(t,t=>this.remove(t)),this}_setRoot(t){this._root=t,null!==this._root&&(this._root.parent=null)}_replaceNodeInParent(t,e){null!==t.parent?(t.isLeftChild()?t.parent.left=e:t.parent.right=e,this._rebalance(t.parent)):this._setRoot(e)}_removeNode(s){if(null===s.left&&null===s.right)this._replaceNodeInParent(s,null);else if(null===s.right)this._replaceNodeInParent(s,s.left);else if(null===s.left)this._replaceNodeInParent(s,s.right);else{let t,e=null;if(0e.low&&(e=s[t]);return e.event}}return null}forEach(e){if(null!==this._root){const s=[];this._root.traverse(t=>s.push(t)),s.forEach(t=>{t.event&&e(t.event)})}return this}forEachAtTime(t,e){if(null!==this._root){const s=[];this._root.search(t,s),s.forEach(t=>{t.event&&e(t.event)})}return this}forEachFrom(t,e){if(null!==this._root){const s=[];this._root.searchAfter(t,s),s.forEach(t=>{t.event&&e(t.event)})}return this}dispose(){return super.dispose(),null!==this._root&&this._root.traverse(t=>t.dispose()),this._root=null,this}}class Ld{constructor(t,e,s){this._left=null,this._right=null,this.parent=null,this.height=0,this.event=s,this.low=t,this.high=e,this.max=this.high}insert(t){t.low<=this.low?null===this.left?this.left=t:this.left.insert(t):null===this.right?this.right=t:this.right.insert(t)}search(t,e){t>this.max||(null!==this.left&&this.left.search(t,e),this.low<=t&&this.high>t&&e.push(this),this.low>t||null!==this.right&&this.right.search(t,e))}searchAfter(t,e){this.low>=t&&(e.push(this),null!==this.left&&this.left.searchAfter(t,e)),null!==this.right&&this.right.searchAfter(t,e)}traverse(t){t(this),null!==this.left&&this.left.traverse(t),null!==this.right&&this.right.traverse(t)}updateHeight(){null!==this.left&&null!==this.right?this.height=Math.max(this.left.height,this.right.height)+1:null!==this.right?this.height=this.right.height+1:null!==this.left?this.height=this.left.height+1:this.height=0}updateMax(){this.max=this.high,null!==this.left&&(this.max=Math.max(this.max,this.left.max)),null!==this.right&&(this.max=Math.max(this.max,this.right.max))}getBalance(){let t=0;return null!==this.left&&null!==this.right?t=this.left.height-this.right.height:null!==this.left?t=this.left.height+1:null!==this.right&&(t=-(this.right.height+1)),t}isLeftChild(){return null!==this.parent&&this.parent.left===this}get left(){return this._left}set left(t){null!==(this._left=t)&&(t.parent=this),this.updateHeight(),this.updateMax()}get right(){return this._right}set right(t){null!==(this._right=t)&&(t.parent=this),this.updateHeight(),this.updateMax()}dispose(){this.parent=null,this._left=null,this._right=null,this.event=null}}class zd extends Bp{constructor(t){super(),this.name="TimelineValue",this._timeline=new Hp({memory:10}),this._initialValue=t}set(t,e){return this._timeline.add({value:t,time:e}),this}get(t){t=this._timeline.get(t);return t?t.value:this._initialValue}}class Wd extends A{constructor(){super(g(Wd.getDefaults(),arguments,["context"]))}connect(t,e=0,s=0){return Cd(this,t,e,s),this}}class Bd extends Wd{constructor(){var t=g(Bd.getDefaults(),arguments,["mapping","length"]);super(t),this.name="WaveShaper",this._shaper=this.context.createWaveShaper(),this.input=this._shaper,this.output=this._shaper,d(t.mapping)||t.mapping instanceof Float32Array?this.curve=Float32Array.from(t.mapping):yp(t.mapping)&&this.setMap(t.mapping,t.length)}static getDefaults(){return Object.assign(O.getDefaults(),{length:1024})}setMap(s,i=1024){const n=new Float32Array(i);for(let t=0,e=i;tt.includes(e)),"oversampling must be either 'none', '2x', or '4x'"),this._shaper.oversample=e}dispose(){return super.dispose(),this._shaper.disconnect(),this}}class Ud extends Wd{constructor(){var t=g(Ud.getDefaults(),arguments,["value"]);super(t),this.name="Pow",this._exponentScaler=this.input=this.output=new Bd({context:this.context,mapping:this._expFunc(t.value),length:8192}),this._exponent=t.value}static getDefaults(){return Object.assign(Wd.getDefaults(),{value:1})}_expFunc(e){return t=>Math.pow(Math.abs(t),e)}get value(){return this._exponent}set value(t){this._exponent=t,this._exponentScaler.setMap(this._expFunc(this._exponent))}dispose(){return super.dispose(),this._exponentScaler.dispose(),this}}class Gd{constructor(t,e){this.id=Gd._eventId++,this._remainderTime=0;e=Object.assign(Gd.getDefaults(),e);this.transport=t,this.callback=e.callback,this._once=e.once,this.time=Math.floor(e.time),this._remainderTime=e.time-this.time}static getDefaults(){return{callback:x,once:!1,time:0}}get floatTime(){return this.time+this._remainderTime}invoke(t){var e;this.callback&&(e=this.transport.bpm.getDurationOfTicks(1,t),this.callback(t+this._remainderTime*e),this._once&&this.transport.clear(this.id))}dispose(){return this.callback=void 0,this}}Gd._eventId=0;class Qd extends Gd{constructor(t,e){super(t,e),this._currentId=-1,this._nextId=-1,this._nextTick=this.time,this._boundRestart=this._restart.bind(this);t=Object.assign(Qd.getDefaults(),e);this.duration=t.duration,this._interval=t.interval,this._nextTick=t.time,this.transport.on("start",this._boundRestart),this.transport.on("loopStart",this._boundRestart),this.transport.on("ticks",this._boundRestart),this.context=this.transport.context,this._restart()}static getDefaults(){return Object.assign({},Gd.getDefaults(),{duration:1/0,interval:1,once:!1})}invoke(t){this._createEvents(t),super.invoke(t)}_createEvent(){return Zp(this._nextTick,this.floatTime+this.duration)?this.transport.scheduleOnce(this.invoke.bind(this),new D(this.context,this._nextTick).toSeconds()):-1}_createEvents(t){Zp(this._nextTick+this._interval,this.floatTime+this.duration)&&(this._nextTick+=this._interval,this._currentId=this._nextId,this._nextId=this.transport.scheduleOnce(this.invoke.bind(this),new D(this.context,this._nextTick).toSeconds()))}_restart(t){this.transport.clear(this._currentId),this.transport.clear(this._nextId),this._nextTick=this.floatTime;t=this.transport.getTicksAtTime(t);Gp(t,this.time)&&(this._nextTick=this.floatTime+Math.ceil((t-this.floatTime)/this._interval)*this._interval),this._currentId=this._createEvent(),this._nextTick+=this._interval,this._nextId=this._createEvent()}dispose(){return super.dispose(),this.transport.clear(this._currentId),this.transport.clear(this._nextId),this.transport.off("start",this._boundRestart),this.transport.off("loopStart",this._boundRestart),this.transport.off("ticks",this._boundRestart),this}}class Zd extends S{constructor(){var t=g(Zd.getDefaults(),arguments);super(t),this.name="Transport",this._loop=new zd(!1),this._loopStart=0,this._loopEnd=0,this._scheduledEvents={},this._timeline=new Hp,this._repeatedEvents=new jd,this._syncedSignals=[],this._swingAmount=0,this._ppq=t.ppq,this._clock=new Ed({callback:this._processTick.bind(this),context:this.context,frequency:0,units:"bpm"}),this._bindClockEvents(),this.bpm=this._clock.frequency,this._clock.frequency.multiplier=t.ppq,this.bpm.setValueAtTime(t.bpm,0),y(this,"bpm"),this._timeSignature=t.timeSignature,this._swingTicks=t.ppq/2}static getDefaults(){return Object.assign(S.getDefaults(),{bpm:120,loopEnd:"4m",loopStart:0,ppq:192,swing:0,swingSubdivision:"8n",timeSignature:4})}_processTick(e,t){var s;this._loop.get(e)&&t>=this._loopEnd&&(this.emit("loopEnd",e),this._clock.setTicksAtTime(this._loopStart,e),t=this._loopStart,this.emit("loopStart",e,this._clock.getSecondsAtTime(e)),this.emit("loop",e)),0t.invoke(e)),Op(!1)}schedule(t,e){t=new Gd(this,{callback:t,time:new T(this.context,e).toTicks()});return this._addEvent(t,this._timeline)}scheduleRepeat(t,e,s,i=1/0){t=new Qd(this,{callback:t,duration:new gd(this.context,i).toTicks(),interval:new gd(this.context,e).toTicks(),time:new T(this.context,s).toTicks()});return this._addEvent(t,this._repeatedEvents)}scheduleOnce(t,e){t=new Gd(this,{callback:t,once:!0,time:new T(this.context,e).toTicks()});return this._addEvent(t,this._timeline)}clear(t){if(this._scheduledEvents.hasOwnProperty(t)){const e=this._scheduledEvents[t.toString()];e.timeline.remove(e.event),e.event.dispose(),delete this._scheduledEvents[t.toString()]}return this}_addEvent(t,e){return this._scheduledEvents[t.id.toString()]={event:t,timeline:e},e.add(t),t.id}cancel(t=0){t=this.toTicks(t);return this._timeline.forEachFrom(t,t=>this.clear(t.id)),this._repeatedEvents.forEachFrom(t,t=>this.clear(t.id)),this}_bindClockEvents(){this._clock.on("start",(t,e)=>{e=new D(this.context,e).toSeconds(),this.emit("start",t,e)}),this._clock.on("stop",t=>{this.emit("stop",t)}),this._clock.on("pause",t=>{this.emit("pause",t)})}get state(){return this._clock.getStateAtTime(this.now())}start(t,e){let s;return this.context.resume(),o(e)&&(s=this.toTicks(e)),this._clock.start(t,s),this}stop(t){return this._clock.stop(t),this}pause(t){return this._clock.pause(t),this}toggle(t){return t=this.toSeconds(t),"started"!==this._clock.getStateAtTime(t)?this.start(t):this.stop(t),this}get timeSignature(){return this._timeSignature}set timeSignature(t){d(t)&&(t=t[0]/t[1]*4),this._timeSignature=t}get loopStart(){return new gd(this.context,this._loopStart,"i").toSeconds()}set loopStart(t){this._loopStart=this.toTicks(t)}get loopEnd(){return new gd(this.context,this._loopEnd,"i").toSeconds()}set loopEnd(t){this._loopEnd=this.toTicks(t)}get loop(){return this._loop.get(this.now())}set loop(t){this._loop.set(t,this.now())}setLoopPoints(t,e){return this.loopStart=t,this.loopEnd=e,this}get swing(){return this._swingAmount}set swing(t){this._swingAmount=t}get swingSubdivision(){return new D(this.context,this._swingTicks).toNotation()}set swingSubdivision(t){this._swingTicks=this.toTicks(t)}get position(){var t=this.now(),t=this._clock.getTicksAtTime(t);return new D(this.context,t).toBarsBeatsSixteenths()}set position(t){t=this.toTicks(t);this.ticks=t}get seconds(){return this._clock.seconds}set seconds(t){var e=this.now(),t=this._clock.frequency.timeToTicks(t,e);this.ticks=t}get progress(){var t;return this.loop?(t=this.now(),(this._clock.getTicksAtTime(t)-this._loopStart)/(this._loopEnd-this._loopStart)):0}get ticks(){return this._clock.ticks}set ticks(t){var e,s;this._clock.ticks!==t&&(e=this.now(),"started"===this.state?(s=this._clock.getTicksAtTime(e),s=e+this._clock.frequency.getDurationOfTicks(Math.ceil(s)-s,e),this.emit("stop",s),this._clock.setTicksAtTime(t,s),this.emit("start",s,this._clock.getSecondsAtTime(s))):(this.emit("ticks",e),this._clock.setTicksAtTime(t,e)))}getTicksAtTime(t){return this._clock.getTicksAtTime(t)}getSecondsAtTime(t){return this._clock.getSecondsAtTime(t)}get PPQ(){return this._clock.frequency.multiplier}set PPQ(t){this._clock.frequency.multiplier=t}nextSubdivision(t){if(t=this.toTicks(t),"started"!==this.state)return 0;var e=this.now(),t=t-this.getTicksAtTime(e)%t;return this._clock.nextTickTime(t,e)}syncSignal(t,e){const s=this.now();let i=this.bpm,n=1/(60/i.getValueAtTime(s)/this.PPQ),r=[];if("time"===t.units){const t=1/64/n,e=new C(t),s=new Ud(-1),o=new C(t);i.chain(e,s,o),i=o,n=1/n,r=[e,s,o]}e=e||(0!==t.getValueAtTime(s)?t.getValueAtTime(s)/n:0);const o=new C(e);return i.connect(o),o.connect(t._param),r.push(o),this._syncedSignals.push({initial:t.value,nodes:r,signal:t}),t.value=0,this}unsyncSignal(e){for(let t=this._syncedSignals.length-1;0<=t;t--){const s=this._syncedSignals[t];s.signal===e&&(s.nodes.forEach(t=>t.dispose()),s.signal.value=s.initial,this._syncedSignals.splice(t,1))}return this}dispose(){return super.dispose(),this._clock.dispose(),nd(this,"bpm"),this._timeline.dispose(),this._repeatedEvents.dispose(),this}}ed.mixin(Zd),Jp(t=>{t.transport=new Zd({context:t})}),td(t=>{t.transport.dispose()});class M extends A{constructor(t){super(t),this.input=void 0,this._state=new wd("stopped"),this._synced=!1,this._scheduled=[],this._syncedStart=x,this._syncedStop=x,this._state.memory=100,this._state.increasing=!0,this._volume=this.output=new qd({context:this.context,mute:t.mute,volume:t.volume}),this.volume=this._volume.volume,y(this,"volume"),this.onstop=t.onstop}static getDefaults(){return Object.assign(A.getDefaults(),{mute:!1,onstop:x,volume:0})}get state(){return this._synced?"started"===this.context.transport.state?this._state.getValueAtTime(this.context.transport.seconds):"stopped":this._state.getValueAtTime(this.now())}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}_clampToCurrentTime(t){return this._synced?t:Math.max(t,this.context.currentTime)}start(t,e,s){var i=vp(t)&&this._synced?this.context.transport.seconds:this.toSeconds(t),i=this._clampToCurrentTime(i);if(this._synced||"started"!==this._state.getValueAtTime(i))if(this.log("start",i),this._state.setStateAtTime("started",i),this._synced){const t=this._state.get(i);t&&(t.offset=this.toSeconds(Wp(e,0)),t.duration=s?this.toSeconds(s):void 0);var n=this.context.transport.schedule(t=>{this._start(t,e,s)},i);this._scheduled.push(n),"started"===this.context.transport.state&&this.context.transport.getSecondsAtTime(this.immediate())>i&&this._syncedStart(this.now(),this.context.transport.seconds)}else kp(this.context),this._start(i,e,s);else l(Gp(i,this._state.get(i).time),"Start time must be strictly greater than previous start time"),this._state.cancel(i),this._state.setStateAtTime("started",i),this.log("restart",i),this.restart(i,e,s);return this}stop(t){var e=vp(t)&&this._synced?this.context.transport.seconds:this.toSeconds(t),e=this._clampToCurrentTime(e);if("started"===this._state.getValueAtTime(e)||o(this._state.getNextState("started",e))){if(this.log("stop",e),this._synced){const t=this.context.transport.schedule(this._stop.bind(this),e);this._scheduled.push(t)}else this._stop(e);this._state.cancel(e),this._state.setStateAtTime("stopped",e)}return this}restart(t,e,s){return t=this.toSeconds(t),"started"===this._state.getValueAtTime(t)&&(this._state.cancel(t),this._restart(t,e,s)),this}sync(){return this._synced||(this._synced=!0,this._syncedStart=(e,s)=>{if(Gp(s,0)){var i=this._state.get(s);if(i&&"started"===i.state&&i.time!==s){s=s-this.toSeconds(i.time);let t;i.duration&&(t=this.toSeconds(i.duration)-s),this._start(e,this.toSeconds(i.offset)+s,t)}}},this._syncedStop=t=>{var e=this.context.transport.getSecondsAtTime(Math.max(t-this.sampleTime,0));"started"===this._state.getValueAtTime(e)&&this._stop(t)},this.context.transport.on("start",this._syncedStart),this.context.transport.on("loopStart",this._syncedStart),this.context.transport.on("stop",this._syncedStop),this.context.transport.on("pause",this._syncedStop),this.context.transport.on("loopEnd",this._syncedStop)),this}unsync(){return this._synced&&(this.context.transport.off("stop",this._syncedStop),this.context.transport.off("pause",this._syncedStop),this.context.transport.off("loopEnd",this._syncedStop),this.context.transport.off("start",this._syncedStart),this.context.transport.off("loopStart",this._syncedStart)),this._synced=!1,this._scheduled.forEach(t=>this.context.transport.clear(t)),this._scheduled=[],this._state.cancel(0),this._stop(0),this}dispose(){return super.dispose(),this.onstop=x,this.unsync(),this._volume.dispose(),this._state.dispose(),this}}class Xd extends kd{constructor(){var t=g(Xd.getDefaults(),arguments,["url","onload"]);super(t),this.name="ToneBufferSource",this._source=this.context.createBufferSource(),this._internalChannels=[this._source],this._sourceStarted=!1,this._sourceStopped=!1,Td(this._source,this._gainNode),this._source.onended=()=>this._stopSource(),this.playbackRate=new k({context:this.context,param:this._source.playbackRate,units:"positive",value:t.playbackRate}),this.loop=t.loop,this.loopStart=t.loopStart,this.loopEnd=t.loopEnd,this._buffer=new w(t.url,t.onload,t.onerror),this._internalChannels.push(this._source)}static getDefaults(){return Object.assign(kd.getDefaults(),{url:new w,loop:!1,loopEnd:0,loopStart:0,onload:x,onerror:x,playbackRate:1})}get fadeIn(){return this._fadeIn}set fadeIn(t){this._fadeIn=t}get fadeOut(){return this._fadeOut}set fadeOut(t){this._fadeOut=t}get curve(){return this._curve}set curve(t){this._curve=t}start(t,e,s,i=1){l(this.buffer.loaded,"buffer is either not set or not loaded");t=this.toSeconds(t);this._startGain(t,i),e=this.loop?Wp(e,this.loopStart):Wp(e,0);let n=Math.max(this.toSeconds(e),0);if(this.loop){const t=this.toSeconds(this.loopEnd)||this.buffer.duration,e=this.toSeconds(this.loopStart),s=t-e;Xp(n=Qp(n,t)?(n-e)%s+e:n,this.buffer.duration)&&(n=0)}return this._source.buffer=this.buffer.get(),this._source.loopEnd=this.toSeconds(this.loopEnd)||this.buffer.duration,Zp(n,this.buffer.duration)&&(this._sourceStarted=!0,this._source.start(t,n)),o(s)&&(i=this.toSeconds(s),i=Math.max(i,0),this.stop(t+i)),this}_stopSource(t){!this._sourceStopped&&this._sourceStarted&&(this._sourceStopped=!0,this._source.stop(this.toSeconds(t)),this._onended())}get loopStart(){return this._source.loopStart}set loopStart(t){this._source.loopStart=this.toSeconds(t)}get loopEnd(){return this._source.loopEnd}set loopEnd(t){this._source.loopEnd=this.toSeconds(t)}get buffer(){return this._buffer}set buffer(t){this._buffer.set(t)}get loop(){return this._source.loop}set loop(t){this._source.loop=t,this._sourceStarted&&this.cancelStop()}dispose(){return super.dispose(),this._source.onended=null,this._source.disconnect(),this._buffer.dispose(),this.playbackRate.dispose(),this}}class Yd extends M{constructor(){var t=g(Yd.getDefaults(),arguments,["type"]);super(t),this.name="Noise",this._source=null,this._playbackRate=t.playbackRate,this.type=t.type,this._fadeIn=t.fadeIn,this._fadeOut=t.fadeOut}static getDefaults(){return Object.assign(M.getDefaults(),{fadeIn:0,fadeOut:0,playbackRate:1,type:"white"})}get type(){return this._type}set type(t){if(l(t in Jd,"Noise: invalid type: "+t),this._type!==t&&(this._type=t,"started"===this.state)){const t=this.now();this._stop(t),this._start(t)}}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._source&&(this._source.playbackRate.value=t)}_start(t){var e=Jd[this._type];this._source=new Xd({url:e,context:this.context,fadeIn:this._fadeIn,fadeOut:this._fadeOut,loop:!0,onended:()=>this.onstop(this),playbackRate:this._playbackRate}).connect(this.output),this._source.start(this.toSeconds(t),Math.random()*(e.duration-.001))}_stop(t){this._source&&(this._source.stop(this.toSeconds(t)),this._source=null)}get fadeIn(){return this._fadeIn}set fadeIn(t){this._fadeIn=t,this._source&&(this._source.fadeIn=this._fadeIn)}get fadeOut(){return this._fadeOut}set fadeOut(t){this._fadeOut=t,this._source&&(this._source.fadeOut=this._fadeOut)}_restart(t){this._stop(t),this._start(t)}dispose(){return super.dispose(),this._source&&this._source.disconnect(),this}}const Hd=220500,$d={brown:null,pink:null,white:null},Jd={get brown(){if(!$d.brown){const i=[];for(let t=0;t<2;t++){const n=new Float32Array(Hd);i[t]=n;let e=0;for(let t=0;tt.label===i||t.deviceId===i),!this._device&&0{t.stop()}),this._stream=void 0,this._mediaStream.disconnect(),this._mediaStream=void 0),this._device=void 0,this}static enumerateDevices(){return _(this,void 0,void 0,function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter(t=>"audioinput"===t.kind)})}get state(){return this._stream&&this._stream.active?"started":"stopped"}get deviceId(){return this._device?this._device.deviceId:void 0}get groupId(){return this._device?this._device.groupId:void 0}get label(){return this._device?this._device.label:void 0}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}dispose(){return super.dispose(),this.close(),this._volume.dispose(),this.volume.dispose(),this}static get supported(){return o(navigator.mediaDevices)&&o(navigator.mediaDevices.getUserMedia)}}function tf(s,i){return _(this,void 0,void 0,function*(){const t=i/s.context.sampleRate,e=new rd(1,t,s.context.sampleRate);return new s.constructor(Object.assign(s.get(),{frequency:2/t,detune:0,context:e})).toDestination().start(0),(yield e.render()).getChannelData(0)})}class ef extends kd{constructor(){var t=g(ef.getDefaults(),arguments,["frequency","type"]);super(t),this.name="ToneOscillatorNode",this._oscillator=this.context.createOscillator(),this._internalChannels=[this._oscillator],Td(this._oscillator,this._gainNode),this.type=t.type,this.frequency=new k({context:this.context,param:this._oscillator.frequency,units:"frequency",value:t.frequency}),this.detune=new k({context:this.context,param:this._oscillator.detune,units:"cents",value:t.detune}),y(this,["frequency","detune"])}static getDefaults(){return Object.assign(kd.getDefaults(),{detune:0,frequency:440,type:"sine"})}start(t){t=this.toSeconds(t);return this.log("start",t),this._startGain(t),this._oscillator.start(t),this}_stopSource(t){this._oscillator.stop(t)}setPeriodicWave(t){return this._oscillator.setPeriodicWave(t),this}get type(){return this._oscillator.type}set type(t){this._oscillator.type=t}dispose(){return super.dispose(),"started"===this.state&&this.stop(),this._oscillator.disconnect(),this.frequency.dispose(),this.detune.dispose(),this}}class E extends M{constructor(){const t=g(E.getDefaults(),arguments,["frequency","type"]);super(t),this.name="Oscillator",this._oscillator=null,this.frequency=new O({context:this.context,units:"frequency",value:t.frequency}),y(this,"frequency"),this.detune=new O({context:this.context,units:"cents",value:t.detune}),y(this,"detune"),this._partials=t.partials,this._partialCount=t.partialCount,this._type=t.type,t.partialCount&&"custom"!==t.type&&(this._type=this.baseType+t.partialCount.toString()),this.phase=t.phase}static getDefaults(){return Object.assign(M.getDefaults(),{detune:0,frequency:440,partialCount:0,partials:[],phase:0,type:"sine"})}_start(t){var t=this.toSeconds(t),e=new ef({context:this.context,onended:()=>this.onstop(this)});this._oscillator=e,this._wave?this._oscillator.setPeriodicWave(this._wave):this._oscillator.type=this._type,this._oscillator.connect(this.output),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.start(t)}_stop(t){t=this.toSeconds(t);this._oscillator&&this._oscillator.stop(t)}_restart(t){t=this.toSeconds(t);return this.log("restart",t),this._oscillator&&this._oscillator.cancelStop(),this._state.cancel(t),this}syncFrequency(){return this.context.transport.syncSignal(this.frequency),this}unsyncFrequency(){return this.context.transport.unsyncSignal(this.frequency),this}_getCachedPeriodicWave(){if("custom"===this._type)return E._periodicWaveCache.find(t=>{return t.phase===this._phase&&(t=t.partials,s=this._partials,t.length===s.length&&t.every((t,e)=>s[e]===t));var s});var t=E._periodicWaveCache.find(t=>t.type===this._type&&t.phase===this._phase);return this._partialCount=t?t.partialCount:this._partialCount,t}get type(){return this._type}set type(t){this._type=t;const e=-1!==["sine","square","sawtooth","triangle"].indexOf(t);if(0===this._phase&&e)this._wave=void 0,this._partialCount=0,null!==this._oscillator&&(this._oscillator.type=t);else{const e=this._getCachedPeriodicWave();if(o(e)){const{partials:t,wave:s}=e;this._wave=s,this._partials=t,null!==this._oscillator&&this._oscillator.setPeriodicWave(this._wave)}else{const[e,i]=this._getRealImaginary(t,this._phase),n=this.context.createPeriodicWave(e,i);this._wave=n,null!==this._oscillator&&this._oscillator.setPeriodicWave(this._wave),E._periodicWaveCache.push({imag:i,partialCount:this._partialCount,partials:this._partials,phase:this._phase,real:e,type:this._type,wave:this._wave}),100s[e]=t),this._partials=Array.from(s),this.type=this._type}}_getRealImaginary(s,i){let n=2048;const r=new Float32Array(n),o=new Float32Array(n);let a=1;if("custom"===s){if(a=this._partials.length+1,this._partialCount=this._partials.length,n=a,0===this._partials.length)return[r,o]}else{const i=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(s);i?(a=parseInt(i[2],10)+1,this._partialCount=parseInt(i[2],10),s=i[1],a=Math.max(a,2),n=a):this._partialCount=0,this._partials=[]}for(let e=1;e>1&1?-1:1):0,this._partials[e-1]=t;break;case"custom":t=this._partials[e-1];break;default:throw new TypeError("Oscillator: invalid type: "+s)}0!==t?(r[e]=-t*Math.sin(i*e),o[e]=t*Math.cos(i*e)):(r[e]=0,o[e]=0)}return[r,o]}_inverseFFT(e,s,i){let n=0;var r=e.length;for(let t=0;t(t+1)/2}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class q extends O{constructor(){var t=g(q.getDefaults(),arguments,["value"]);super(t),this.name="Multiply",this.override=!1,this._mult=this.input=this.output=new C({context:this.context,minValue:t.minValue,maxValue:t.maxValue}),this.factor=this._param=this._mult.gain,this.factor.setValueAtTime(t.value,0)}static getDefaults(){return Object.assign(O.getDefaults(),{value:0})}dispose(){return super.dispose(),this._mult.dispose(),this}}class nf extends M{constructor(){var t=g(nf.getDefaults(),arguments,["frequency","type","modulationType"]);super(t),this.name="AMOscillator",this._modulationScale=new sf({context:this.context}),this._modulationNode=new C({context:this.context}),this._carrier=new E({context:this.context,detune:t.detune,frequency:t.frequency,onstop:()=>this.onstop(this),phase:t.phase,type:t.type}),this.frequency=this._carrier.frequency,this.detune=this._carrier.detune,this._modulator=new E({context:this.context,phase:t.phase,type:t.modulationType}),this.harmonicity=new q({context:this.context,units:"positive",value:t.harmonicity}),this.frequency.chain(this.harmonicity,this._modulator.frequency),this._modulator.chain(this._modulationScale,this._modulationNode.gain),this._carrier.chain(this._modulationNode,this.output),y(this,["frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(E.getDefaults(),{harmonicity:1,modulationType:"square"})}_start(t){this._modulator.start(t),this._carrier.start(t)}_stop(t){this._modulator.stop(t),this._carrier.stop(t)}_restart(t){this._modulator.restart(t),this._carrier.restart(t)}get type(){return this._carrier.type}set type(t){this._carrier.type=t}get baseType(){return this._carrier.baseType}set baseType(t){this._carrier.baseType=t}get partialCount(){return this._carrier.partialCount}set partialCount(t){this._carrier.partialCount=t}get modulationType(){return this._modulator.type}set modulationType(t){this._modulator.type=t}get phase(){return this._carrier.phase}set phase(t){this._carrier.phase=t,this._modulator.phase=t}get partials(){return this._carrier.partials}set partials(t){this._carrier.partials=t}asArray(){return _(this,arguments,void 0,function*(t=1024){return tf(this,t)})}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this._modulationScale.dispose(),this}}class rf extends M{constructor(){var t=g(rf.getDefaults(),arguments,["frequency","type","modulationType"]);super(t),this.name="FMOscillator",this._modulationNode=new C({context:this.context,gain:0}),this._carrier=new E({context:this.context,detune:t.detune,frequency:0,onstop:()=>this.onstop(this),phase:t.phase,type:t.type}),this.detune=this._carrier.detune,this.frequency=new O({context:this.context,units:"frequency",value:t.frequency}),this._modulator=new E({context:this.context,phase:t.phase,type:t.modulationType}),this.harmonicity=new q({context:this.context,units:"positive",value:t.harmonicity}),this.modulationIndex=new q({context:this.context,units:"positive",value:t.modulationIndex}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.frequency.chain(this.modulationIndex,this._modulationNode),this._modulator.connect(this._modulationNode.gain),this._modulationNode.connect(this._carrier.frequency),this._carrier.connect(this.output),this.detune.connect(this._modulator.detune),y(this,["modulationIndex","frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(E.getDefaults(),{harmonicity:1,modulationIndex:2,modulationType:"square"})}_start(t){this._modulator.start(t),this._carrier.start(t)}_stop(t){this._modulator.stop(t),this._carrier.stop(t)}_restart(t){return this._modulator.restart(t),this._carrier.restart(t),this}get type(){return this._carrier.type}set type(t){this._carrier.type=t}get baseType(){return this._carrier.baseType}set baseType(t){this._carrier.baseType=t}get partialCount(){return this._carrier.partialCount}set partialCount(t){this._carrier.partialCount=t}get modulationType(){return this._modulator.type}set modulationType(t){this._modulator.type=t}get phase(){return this._carrier.phase}set phase(t){this._carrier.phase=t,this._modulator.phase=t}get partials(){return this._carrier.partials}set partials(t){this._carrier.partials=t}asArray(){return _(this,arguments,void 0,function*(t=1024){return tf(this,t)})}dispose(){return super.dispose(),this.frequency.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this.modulationIndex.dispose(),this}}class of extends M{constructor(){var t=g(of.getDefaults(),arguments,["frequency","width"]);super(t),this.name="PulseOscillator",this._widthGate=new C({context:this.context,gain:0}),this._thresh=new Bd({context:this.context,mapping:t=>t<=0?-1:1}),this.width=new O({context:this.context,units:"audioRange",value:t.width}),this._triangle=new E({context:this.context,detune:t.detune,frequency:t.frequency,onstop:()=>this.onstop(this),phase:t.phase,type:"triangle"}),this.frequency=this._triangle.frequency,this.detune=this._triangle.detune,this._triangle.chain(this._thresh,this.output),this.width.chain(this._widthGate,this._thresh),y(this,["width","frequency","detune"])}static getDefaults(){return Object.assign(M.getDefaults(),{detune:0,frequency:440,phase:0,type:"pulse",width:.2})}_start(t){t=this.toSeconds(t),this._triangle.start(t),this._widthGate.gain.setValueAtTime(1,t)}_stop(t){t=this.toSeconds(t),this._triangle.stop(t),this._widthGate.gain.cancelScheduledValues(t),this._widthGate.gain.setValueAtTime(0,t)}_restart(t){this._triangle.restart(t),this._widthGate.gain.cancelScheduledValues(t),this._widthGate.gain.setValueAtTime(1,t)}get phase(){return this._triangle.phase}set phase(t){this._triangle.phase=t}get type(){return"pulse"}get baseType(){return"pulse"}get partials(){return[]}get partialCount(){return 0}set carrierType(t){this._triangle.type=t}asArray(){return _(this,arguments,void 0,function*(t=1024){return tf(this,t)})}dispose(){return super.dispose(),this._triangle.dispose(),this.width.dispose(),this._widthGate.dispose(),this._thresh.dispose(),this}}class af extends M{constructor(){var t=g(af.getDefaults(),arguments,["frequency","type","spread"]);super(t),this.name="FatOscillator",this._oscillators=[],this.frequency=new O({context:this.context,units:"frequency",value:t.frequency}),this.detune=new O({context:this.context,units:"cents",value:t.detune}),this._spread=t.spread,this._type=t.type,this._phase=t.phase,this._partials=t.partials,this._partialCount=t.partialCount,this.count=t.count,y(this,["frequency","detune"])}static getDefaults(){return Object.assign(E.getDefaults(),{count:3,spread:20,type:"sawtooth"})}_start(e){e=this.toSeconds(e),this._forEach(t=>t.start(e))}_stop(e){e=this.toSeconds(e),this._forEach(t=>t.stop(e))}_restart(e){this._forEach(t=>t.restart(e))}_forEach(e){for(let t=0;tt.type=e)}get spread(){return this._spread}set spread(t){if(this._spread=t,1t.detune.value=s+i*e)}}get count(){return this._oscillators.length}set count(e){if(f(e,1),this._oscillators.length!==e){this._forEach(t=>t.dispose()),this._oscillators=[];for(let t=0;tthis.onstop(this):x});"custom"===this.type&&(s.partials=this._partials),this.frequency.connect(s.frequency),this.detune.connect(s.detune),s.detune.overridden=!1,s.connect(this.output),this._oscillators[t]=s}this.spread=this._spread,"started"===this.state&&this._forEach(t=>t.start())}}get phase(){return this._phase}set phase(t){this._phase=t,this._forEach((t,e)=>t.phase=this._phase+e/this.count*360)}get baseType(){return this._oscillators[0].baseType}set baseType(e){this._forEach(t=>t.baseType=e),this._type=this._oscillators[0].type}get partials(){return this._oscillators[0].partials}set partials(e){this._partials=e,this._partialCount=this._partials.length,e.length&&(this._type="custom",this._forEach(t=>t.partials=e))}get partialCount(){return this._oscillators[0].partialCount}set partialCount(e){this._partialCount=e,this._forEach(t=>t.partialCount=e),this._type=this._oscillators[0].type}asArray(){return _(this,arguments,void 0,function*(t=1024){return tf(this,t)})}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this._forEach(t=>t.dispose()),this}}class hf extends M{constructor(){var t=g(hf.getDefaults(),arguments,["frequency","modulationFrequency"]);super(t),this.name="PWMOscillator",this.sourceType="pwm",this._scale=new q({context:this.context,value:2}),this._pulse=new of({context:this.context,frequency:t.modulationFrequency}),this._pulse.carrierType="sine",this.modulationFrequency=this._pulse.frequency,this._modulator=new E({context:this.context,detune:t.detune,frequency:t.frequency,onstop:()=>this.onstop(this),phase:t.phase}),this.frequency=this._modulator.frequency,this.detune=this._modulator.detune,this._modulator.chain(this._scale,this._pulse.width),this._pulse.connect(this.output),y(this,["modulationFrequency","frequency","detune"])}static getDefaults(){return Object.assign(M.getDefaults(),{detune:0,frequency:440,modulationFrequency:.4,phase:0,type:"pwm"})}_start(t){t=this.toSeconds(t),this._modulator.start(t),this._pulse.start(t)}_stop(t){t=this.toSeconds(t),this._modulator.stop(t),this._pulse.stop(t)}_restart(t){this._modulator.restart(t),this._pulse.restart(t)}get type(){return"pwm"}get baseType(){return"pwm"}get partials(){return[]}get partialCount(){return 0}get phase(){return this._modulator.phase}set phase(t){this._modulator.phase=t}asArray(){return _(this,arguments,void 0,function*(t=1024){return tf(this,t)})}dispose(){return super.dispose(),this._pulse.dispose(),this._scale.dispose(),this._modulator.dispose(),this}}const cf={am:nf,fat:af,fm:rf,oscillator:E,pulse:of,pwm:hf};class lf extends M{constructor(){var t=g(lf.getDefaults(),arguments,["frequency","type"]);super(t),this.name="OmniOscillator",this.frequency=new O({context:this.context,units:"frequency",value:t.frequency}),this.detune=new O({context:this.context,units:"cents",value:t.detune}),y(this,["frequency","detune"]),this.set(t)}static getDefaults(){return Object.assign(E.getDefaults(),rf.getDefaults(),nf.getDefaults(),af.getDefaults(),of.getDefaults(),hf.getDefaults())}_start(t){this._oscillator.start(t)}_stop(t){this._oscillator.stop(t)}_restart(t){return this._oscillator.restart(t),this}get type(){let t="";return(t=["am","fm","fat"].some(t=>this._sourceType===t)?this._sourceType:t)+this._oscillator.type}set type(t){"fm"===t.substr(0,2)?(this._createNewOscillator("fm"),this._oscillator=this._oscillator,this._oscillator.type=t.substr(2)):"am"===t.substr(0,2)?(this._createNewOscillator("am"),this._oscillator=this._oscillator,this._oscillator.type=t.substr(2)):"fat"===t.substr(0,3)?(this._createNewOscillator("fat"),this._oscillator=this._oscillator,this._oscillator.type=t.substr(3)):"pwm"===t?(this._createNewOscillator("pwm"),this._oscillator=this._oscillator):"pulse"===t?this._createNewOscillator("pulse"):(this._createNewOscillator("oscillator"),this._oscillator=this._oscillator,this._oscillator.type=t)}get partials(){return this._oscillator.partials}set partials(t){this._getOscType(this._oscillator,"pulse")||this._getOscType(this._oscillator,"pwm")||(this._oscillator.partials=t)}get partialCount(){return this._oscillator.partialCount}set partialCount(t){this._getOscType(this._oscillator,"pulse")||this._getOscType(this._oscillator,"pwm")||(this._oscillator.partialCount=t)}set(t){return Reflect.has(t,"type")&&t.type&&(this.type=t.type),super.set(t),this}_createNewOscillator(t){if(t!==this._sourceType){this._sourceType=t;const e=cf[t],s=this.now();if(this._oscillator){const t=this._oscillator;t.stop(s),this.context.setTimeout(()=>t.dispose(),this.blockTime)}this._oscillator=new e({context:this.context}),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.connect(this.output),this._oscillator.onstop=()=>this.onstop(this),"started"===this.state&&this._oscillator.start(s)}}get phase(){return this._oscillator.phase}set phase(t){this._oscillator.phase=t}get sourceType(){return this._sourceType}set sourceType(t){let e="sine";"pwm"!==this._oscillator.type&&"pulse"!==this._oscillator.type&&(e=this._oscillator.type),"fm"===t?this.type="fm"+e:"am"===t?this.type="am"+e:"fat"===t?this.type="fat"+e:"oscillator"===t?this.type=e:"pulse"===t?this.type="pulse":"pwm"===t&&(this.type="pwm")}_getOscType(t,e){return t instanceof cf[e]}get baseType(){return this._oscillator.baseType}set baseType(t){this._getOscType(this._oscillator,"pulse")||this._getOscType(this._oscillator,"pwm")||"pulse"===t||"pwm"===t||(this._oscillator.baseType=t)}get width(){return this._getOscType(this._oscillator,"pulse")?this._oscillator.width:void 0}get count(){return this._getOscType(this._oscillator,"fat")?this._oscillator.count:void 0}set count(t){this._getOscType(this._oscillator,"fat")&&xp(t)&&(this._oscillator.count=t)}get spread(){return this._getOscType(this._oscillator,"fat")?this._oscillator.spread:void 0}set spread(t){this._getOscType(this._oscillator,"fat")&&xp(t)&&(this._oscillator.spread=t)}get modulationType(){return this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am")?this._oscillator.modulationType:void 0}set modulationType(t){(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))&&Tp(t)&&(this._oscillator.modulationType=t)}get modulationIndex(){return this._getOscType(this._oscillator,"fm")?this._oscillator.modulationIndex:void 0}get harmonicity(){return this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am")?this._oscillator.harmonicity:void 0}get modulationFrequency(){return this._getOscType(this._oscillator,"pwm")?this._oscillator.modulationFrequency:void 0}asArray(){return _(this,arguments,void 0,function*(t=1024){return tf(this,t)})}dispose(){return super.dispose(),this.detune.dispose(),this.frequency.dispose(),this._oscillator.dispose(),this}}class uf extends O{constructor(){super(g(uf.getDefaults(),arguments,["value"])),this.override=!1,this.name="Add",this._sum=new C({context:this.context}),this.input=this._sum,this.output=this._sum,this.addend=this._param,bd(this._constantSource,this._sum)}static getDefaults(){return Object.assign(O.getDefaults(),{value:0})}dispose(){return super.dispose(),this._sum.dispose(),this}}class pf extends Wd{constructor(){var t=g(pf.getDefaults(),arguments,["min","max"]);super(t),this.name="Scale",this._mult=this.input=new q({context:this.context,value:t.max-t.min}),this._add=this.output=new uf({context:this.context,value:t.min}),this._min=t.min,this._max=t.max,this.input.connect(this.output)}static getDefaults(){return Object.assign(Wd.getDefaults(),{max:1,min:0})}get min(){return this._min}set min(t){this._min=t,this._setRange()}get max(){return this._max}set max(t){this._max=t,this._setRange()}_setRange(){this._add.value=this._min,this._mult.value=this._max-this._min}dispose(){return super.dispose(),this._add.dispose(),this._mult.dispose(),this}}class df extends Wd{constructor(){super(g(df.getDefaults(),arguments)),this.name="Zero",this._gain=new C({context:this.context}),this.output=this._gain,this.input=void 0,Td(this.context.getConstant(0),this._gain)}dispose(){return super.dispose(),Sd(this.context.getConstant(0),this._gain),this}}class ff extends A{constructor(){var t=g(ff.getDefaults(),arguments,["frequency","min","max"]);super(t),this.name="LFO",this._stoppedValue=0,this._units="number",this.convert=!0,this._fromType=k.prototype._fromType,this._toType=k.prototype._toType,this._is=k.prototype._is,this._clampValue=k.prototype._clampValue,this._oscillator=new E(t),this.frequency=this._oscillator.frequency,this._amplitudeGain=new C({context:this.context,gain:t.amplitude,units:"normalRange"}),this.amplitude=this._amplitudeGain.gain,this._stoppedSignal=new O({context:this.context,units:"audioRange",value:0}),this._zeros=new df({context:this.context}),this._a2g=new sf({context:this.context}),this._scaler=this.output=new pf({context:this.context,max:t.max,min:t.min}),this.units=t.units,this.min=t.min,this.max=t.max,this._oscillator.chain(this._amplitudeGain,this._a2g,this._scaler),this._zeros.connect(this._a2g),this._stoppedSignal.connect(this._a2g),y(this,["amplitude","frequency"]),this.phase=t.phase}static getDefaults(){return Object.assign(E.getDefaults(),{amplitude:1,frequency:"4n",max:1,min:0,type:"sine",units:"number"})}start(t){return t=this.toSeconds(t),this._stoppedSignal.setValueAtTime(0,t),this._oscillator.start(t),this}stop(t){return t=this.toSeconds(t),this._stoppedSignal.setValueAtTime(this._stoppedValue,t),this._oscillator.stop(t),this}sync(){return this._oscillator.sync(),this._oscillator.syncFrequency(),this}unsync(){return this._oscillator.unsync(),this._oscillator.unsyncFrequency(),this}_setStoppedValue(){this._stoppedValue=this._oscillator.getInitialValue(),this._stoppedSignal.value=this._stoppedValue}get min(){return this._toType(this._scaler.min)}set min(t){t=this._fromType(t),this._scaler.min=t}get max(){return this._toType(this._scaler.max)}set max(t){t=this._fromType(t),this._scaler.max=t}get type(){return this._oscillator.type}set type(t){this._oscillator.type=t,this._setStoppedValue()}get partials(){return this._oscillator.partials}set partials(t){this._oscillator.partials=t,this._setStoppedValue()}get phase(){return this._oscillator.phase}set phase(t){this._oscillator.phase=t,this._setStoppedValue()}get units(){return this._units}set units(t){var e=this.min,s=this.max;this._units=t,this.min=e,this.max=s}get state(){return this._oscillator.state}connect(t,e,s){return(t instanceof k||t instanceof O)&&(this.convert=t.convert,this.units=t.units),Cd(this,t,e,s),this}dispose(){return super.dispose(),this._oscillator.dispose(),this._stoppedSignal.dispose(),this._zeros.dispose(),this._scaler.dispose(),this._a2g.dispose(),this._amplitudeGain.dispose(),this.amplitude.dispose(),this}}function _f(s,i=1/0){const n=new WeakMap;return function(t,e){Reflect.defineProperty(t,e,{configurable:!0,enumerable:!0,get:function(){return n.get(this)},set:function(t){f(t,s,i),n.set(this,t)}})}}function mf(s,i=1/0){const n=new WeakMap;return function(t,e){Reflect.defineProperty(t,e,{configurable:!0,enumerable:!0,get:function(){return n.get(this)},set:function(t){f(this.toSeconds(t),s,i),n.set(this,t)}})}}class gf extends M{constructor(){var t=g(gf.getDefaults(),arguments,["url","onload"]);super(t),this.name="Player",this._activeSources=new Set,this._buffer=new w({onload:this._onload.bind(this,t.onload),onerror:t.onerror,reverse:t.reverse,url:t.url}),this.autostart=t.autostart,this._loop=t.loop,this._loopStart=t.loopStart,this._loopEnd=t.loopEnd,this._playbackRate=t.playbackRate,this.fadeIn=t.fadeIn,this.fadeOut=t.fadeOut}static getDefaults(){return Object.assign(M.getDefaults(),{autostart:!1,fadeIn:0,fadeOut:0,loop:!1,loopEnd:0,loopStart:0,onload:x,onerror:x,playbackRate:1,reverse:!1})}load(t){return _(this,void 0,void 0,function*(){return yield this._buffer.load(t),this._onload(),this})}_onload(t=x){t(),this.autostart&&this.start()}_onSourceEnd(t){this.onstop(this),this._activeSources.delete(t),0!==this._activeSources.size||this._synced||"started"!==this._state.getValueAtTime(this.now())||(this._state.cancel(this.now()),this._state.setStateAtTime("stopped",this.now()))}start(t,e,s){return super.start(t,e,s),this}_start(t,e,s){e=this._loop?Wp(e,this._loopStart):Wp(e,0);var e=this.toSeconds(e),i=s,s=(s=Wp(s,Math.max(this._buffer.duration-e,0)),this.toSeconds(s));s/=this._playbackRate,t=this.toSeconds(t);const n=new Xd({url:this._buffer,context:this.context,fadeIn:this.fadeIn,fadeOut:this.fadeOut,loop:this._loop,loopEnd:this._loopEnd,loopStart:this._loopStart,onended:this._onSourceEnd.bind(this),playbackRate:this._playbackRate}).connect(this.output);this._loop||this._synced||(this._state.cancel(t+s),this._state.setStateAtTime("stopped",t+s,{implicitEnd:!0})),this._activeSources.add(n),this._loop&&vp(i)?n.start(t,e):n.start(t,e,s-this.toSeconds(this.fadeOut))}_stop(t){const e=this.toSeconds(t);this._activeSources.forEach(t=>t.stop(e))}restart(t,e,s){return super.restart(t,e,s),this}_restart(t,e,s){var i;null!=(i=[...this._activeSources].pop())&&i.stop(t),this._start(t,e,s)}seek(t,e){var s=this.toSeconds(e);if("started"===this._state.getValueAtTime(s)){const e=this.toSeconds(t);this._stop(s),this._start(s,e)}return this}setLoopPoints(t,e){return this.loopStart=t,this.loopEnd=e,this}get loopStart(){return this._loopStart}set loopStart(e){this._loopStart=e,this.buffer.loaded&&f(this.toSeconds(e),0,this.buffer.duration),this._activeSources.forEach(t=>{t.loopStart=e})}get loopEnd(){return this._loopEnd}set loopEnd(e){this._loopEnd=e,this.buffer.loaded&&f(this.toSeconds(e),0,this.buffer.duration),this._activeSources.forEach(t=>{t.loopEnd=e})}get buffer(){return this._buffer}set buffer(t){this._buffer.set(t)}get loop(){return this._loop}set loop(e){if(this._loop!==e&&(this._loop=e,this._activeSources.forEach(t=>{t.loop=e}),e)){const e=this._state.getNextState("stopped",this.now());e&&this._state.cancel(e.time)}}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e;const s=this.now(),t=this._state.getNextState("stopped",s);t&&t.implicitEnd&&(this._state.cancel(t.time),this._activeSources.forEach(t=>t.cancelStop())),this._activeSources.forEach(t=>{t.playbackRate.setValueAtTime(e,s)})}get reverse(){return this._buffer.reverse}set reverse(t){this._buffer.reverse=t}get loaded(){return this._buffer.loaded}dispose(){return super.dispose(),this._activeSources.forEach(t=>t.dispose()),this._activeSources.clear(),this._buffer.dispose(),this}}Fp([mf(0)],gf.prototype,"fadeIn",void 0),Fp([mf(0)],gf.prototype,"fadeOut",void 0);class vf extends A{constructor(){var t=g(vf.getDefaults(),arguments,["urls","onload"],"urls");super(t),this.name="Players",this.input=void 0,this._players=new Map,this._volume=this.output=new qd({context:this.context,volume:t.volume}),this.volume=this._volume.volume,y(this,"volume"),this._buffers=new Vd({urls:t.urls,onload:t.onload,baseUrl:t.baseUrl,onerror:t.onerror}),this.mute=t.mute,this._fadeIn=t.fadeIn,this._fadeOut=t.fadeOut}static getDefaults(){return Object.assign(M.getDefaults(),{baseUrl:"",fadeIn:0,fadeOut:0,mute:!1,onload:x,onerror:x,urls:{},volume:0})}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}get fadeIn(){return this._fadeIn}set fadeIn(e){this._fadeIn=e,this._players.forEach(t=>{t.fadeIn=e})}get fadeOut(){return this._fadeOut}set fadeOut(e){this._fadeOut=e,this._players.forEach(t=>{t.fadeOut=e})}get state(){return Array.from(this._players).some(([,t])=>"started"===t.state)?"started":"stopped"}has(t){return this._buffers.has(t)}player(t){var e;return l(this.has(t),`No Player with the name ${t} exists on this object`),this._players.has(t)||(e=new gf({context:this.context,fadeIn:this._fadeIn,fadeOut:this._fadeOut,url:this._buffers.get(t)}).connect(this.output),this._players.set(t,e)),this._players.get(t)}get loaded(){return this._buffers.loaded}add(t,e,s){return l(!this._buffers.has(t),"A buffer with that name already exists on this object"),this._buffers.add(t,e,s),this}stopAll(e){return this._players.forEach(t=>t.stop(e)),this}dispose(){return super.dispose(),this._volume.dispose(),this.volume.dispose(),this._players.forEach(t=>t.dispose()),this._buffers.dispose(),this}}class yf extends M{constructor(){var t=g(yf.getDefaults(),arguments,["url","onload"]);super(t),this.name="GrainPlayer",this._loopStart=0,this._loopEnd=0,this._activeSources=[],this.buffer=new w({onload:t.onload,onerror:t.onerror,reverse:t.reverse,url:t.url}),this._clock=new Ed({context:this.context,callback:this._tick.bind(this),frequency:1/t.grainSize}),this._playbackRate=t.playbackRate,this._grainSize=t.grainSize,this._overlap=t.overlap,this.detune=t.detune,this.overlap=t.overlap,this.loop=t.loop,this.playbackRate=t.playbackRate,this.grainSize=t.grainSize,this.loopStart=t.loopStart,this.loopEnd=t.loopEnd,this.reverse=t.reverse,this._clock.on("stop",this._onstop.bind(this))}static getDefaults(){return Object.assign(M.getDefaults(),{onload:x,onerror:x,overlap:.1,grainSize:.2,playbackRate:1,detune:0,loop:!1,loopStart:0,loopEnd:0,reverse:!1})}_start(t,e,s){e=Wp(e,0),e=this.toSeconds(e),t=this.toSeconds(t);var i=1/this._clock.frequency.getValueAtTime(t);this._clock.start(t,e/i),s&&this.stop(t+this.toSeconds(s))}restart(t,e,s){return super.restart(t,e,s),this}_restart(t,e,s){this._stop(t),this._start(t,e,s)}_stop(t){this._clock.stop(t)}_onstop(e){this._activeSources.forEach(t=>{t.fadeOut=0,t.stop(e)}),this.onstop(this)}_tick(t){var e=this._clock.getTicksAtTime(t),s=e*this._grainSize;if(this.log("offset",s),!this.loop&&s>this.buffer.duration)this.stop(t);else{const i=s{var t=this._activeSources.indexOf(n);-1!==t&&this._activeSources.splice(t,1)}}}get playbackRate(){return this._playbackRate}set playbackRate(t){f(t,.001),this._playbackRate=t,this.grainSize=this._grainSize}get loopStart(){return this._loopStart}set loopStart(t){this.buffer.loaded&&f(this.toSeconds(t),0,this.buffer.duration),this._loopStart=this.toSeconds(t)}get loopEnd(){return this._loopEnd}set loopEnd(t){this.buffer.loaded&&f(this.toSeconds(t),0,this.buffer.duration),this._loopEnd=this.toSeconds(t)}get reverse(){return this.buffer.reverse}set reverse(t){this.buffer.reverse=t}get grainSize(){return this._grainSize}set grainSize(t){this._grainSize=this.toSeconds(t),this._clock.frequency.setValueAtTime(this._playbackRate/this._grainSize,this.now())}get overlap(){return this._overlap}set overlap(t){t=this.toSeconds(t);f(t,0),this._overlap=t}get loaded(){return this.buffer.loaded}dispose(){return super.dispose(),this.buffer.dispose(),this._clock.dispose(),this._activeSources.forEach(t=>t.dispose()),this}}class xf extends Wd{constructor(){super(...arguments),this.name="Abs",this._abs=new Bd({context:this.context,mapping:t=>Math.abs(t)<.001?0:Math.abs(t)}),this.input=this._abs,this.output=this._abs}dispose(){return super.dispose(),this._abs.dispose(),this}}class wf extends Wd{constructor(){super(...arguments),this.name="GainToAudio",this._norm=new Bd({context:this.context,mapping:t=>2*Math.abs(t)-1}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class bf extends Wd{constructor(){super(...arguments),this.name="Negate",this._multiply=new q({context:this.context,value:-1}),this.input=this._multiply,this.output=this._multiply}dispose(){return super.dispose(),this._multiply.dispose(),this}}class Tf extends O{constructor(){super(g(Tf.getDefaults(),arguments,["value"])),this.override=!1,this.name="Subtract",this._sum=new C({context:this.context}),this.input=this._sum,this.output=this._sum,this._neg=new bf({context:this.context}),this.subtrahend=this._param,bd(this._constantSource,this._neg,this._sum)}static getDefaults(){return Object.assign(O.getDefaults(),{value:0})}dispose(){return super.dispose(),this._neg.dispose(),this._sum.dispose(),this}}class Sf extends Wd{constructor(){super(g(Sf.getDefaults(),arguments)),this.name="GreaterThanZero",this._thresh=this.output=new Bd({context:this.context,length:127,mapping:t=>t<=0?0:1}),this._scale=this.input=new q({context:this.context,value:1e4}),this._scale.connect(this._thresh)}dispose(){return super.dispose(),this._scale.dispose(),this._thresh.dispose(),this}}class kf extends O{constructor(){var t=g(kf.getDefaults(),arguments,["value"]);super(t),this.name="GreaterThan",this.override=!1,this._subtract=this.input=new Tf({context:this.context,value:t.value}),this._gtz=this.output=new Sf({context:this.context}),this.comparator=this._param=this._subtract.subtrahend,y(this,"comparator"),this._subtract.connect(this._gtz)}static getDefaults(){return Object.assign(O.getDefaults(),{value:0})}dispose(){return super.dispose(),this._gtz.dispose(),this._subtract.dispose(),this.comparator.dispose(),this}}class Af extends pf{constructor(){var t=g(Af.getDefaults(),arguments,["min","max","exponent"]);super(t),this.name="ScaleExp",this.input=this._exp=new Ud({context:this.context,value:t.exponent}),this._exp.connect(this._mult)}static getDefaults(){return Object.assign(pf.getDefaults(),{exponent:1})}get exponent(){return this._exp.value}set exponent(t){this._exp.value=t}dispose(){return super.dispose(),this._exp.dispose(),this}}class Cf extends O{constructor(){var t=g(O.getDefaults(),arguments,["value","units"]);super(t),this.name="SyncedSignal",this.override=!1,this._lastVal=t.value,this._synced=this.context.transport.scheduleRepeat(this._onTick.bind(this),"1i"),this._syncedCallback=this._anchorValue.bind(this),this.context.transport.on("start",this._syncedCallback),this.context.transport.on("pause",this._syncedCallback),this.context.transport.on("stop",this._syncedCallback),this._constantSource.disconnect(),this._constantSource.stop(0),this._constantSource=this.output=new Ad({context:this.context,offset:t.value,units:t.units}).start(0),this.setValueAtTime(t.value,0)}_onTick(t){var e=super.getValueAtTime(this.context.transport.seconds);this._lastVal!==e&&(this._lastVal=e,this._constantSource.offset.setValueAtTime(e,t))}_anchorValue(t){var e=super.getValueAtTime(this.context.transport.seconds);this._lastVal=e,this._constantSource.offset.cancelAndHoldAtTime(t),this._constantSource.offset.setValueAtTime(e,t)}getValueAtTime(t){t=new T(this.context,t).toSeconds();return super.getValueAtTime(t)}setValueAtTime(t,e){e=new T(this.context,e).toSeconds();return super.setValueAtTime(t,e),this}linearRampToValueAtTime(t,e){e=new T(this.context,e).toSeconds();return super.linearRampToValueAtTime(t,e),this}exponentialRampToValueAtTime(t,e){e=new T(this.context,e).toSeconds();return super.exponentialRampToValueAtTime(t,e),this}setTargetAtTime(t,e,s){e=new T(this.context,e).toSeconds();return super.setTargetAtTime(t,e,s),this}cancelScheduledValues(t){t=new T(this.context,t).toSeconds();return super.cancelScheduledValues(t),this}setValueCurveAtTime(t,e,s,i){e=new T(this.context,e).toSeconds();return s=this.toSeconds(s),super.setValueCurveAtTime(t,e,s,i),this}cancelAndHoldAtTime(t){t=new T(this.context,t).toSeconds();return super.cancelAndHoldAtTime(t),this}setRampPoint(t){t=new T(this.context,t).toSeconds();return super.setRampPoint(t),this}exponentialRampTo(t,e,s){s=new T(this.context,s).toSeconds();return super.exponentialRampTo(t,e,s),this}linearRampTo(t,e,s){s=new T(this.context,s).toSeconds();return super.linearRampTo(t,e,s),this}targetRampTo(t,e,s){s=new T(this.context,s).toSeconds();return super.targetRampTo(t,e,s),this}dispose(){return super.dispose(),this.context.transport.clear(this._synced),this.context.transport.off("start",this._syncedCallback),this.context.transport.off("pause",this._syncedCallback),this.context.transport.off("stop",this._syncedCallback),this._constantSource.dispose(),this}}class Of extends A{constructor(){var t=g(Of.getDefaults(),arguments,["attack","decay","sustain","release"]);super(t),this.name="Envelope",this._sig=new O({context:this.context,value:0}),this.output=this._sig,this.input=void 0,this.attack=t.attack,this.decay=t.decay,this.sustain=t.sustain,this.release=t.release,this.attackCurve=t.attackCurve,this.releaseCurve=t.releaseCurve,this.decayCurve=t.decayCurve}static getDefaults(){return Object.assign(A.getDefaults(),{attack:.01,attackCurve:"linear",decay:.1,decayCurve:"exponential",release:1,releaseCurve:"exponential",sustain:.5})}get value(){return this.getValueAtTime(this.now())}_getCurve(e,s){if(Tp(e))return e;{let t;for(t in Df)if(Df[t][s]===e)return t;return e}}_setCurve(t,e,s){if(Tp(s)&&Reflect.has(Df,s)){var i=Df[s];wp(i)?"_decayCurve"!==t&&(this[t]=i[e]):this[t]=i}else{if(!d(s)||"_decayCurve"===t)throw new Error("Envelope: invalid curve: "+s);this[t]=s}}get attackCurve(){return this._getCurve(this._attackCurve,"In")}set attackCurve(t){this._setCurve("_attackCurve","In",t)}get releaseCurve(){return this._getCurve(this._releaseCurve,"Out")}set releaseCurve(t){this._setCurve("_releaseCurve","Out",t)}get decayCurve(){return this._getCurve(this._decayCurve,"Out")}set decayCurve(t){this._setCurve("_decayCurve","Out",t)}triggerAttack(t,s=1){this.log("triggerAttack",t,s),t=this.toSeconds(t);let i=this.toSeconds(this.attack);const e=this.toSeconds(this.decay),n=this.getValueAtTime(t);if((i=0{const t=128;let e,s;const i=[];for(e=0;ethis._original_triggerRelease(t),this._volume=this.output=new qd({context:this.context,volume:t.volume}),this.volume=this._volume.volume,y(this,"volume")}static getDefaults(){return Object.assign(A.getDefaults(),{volume:0})}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",0),this.context.transport.on("stop",this._syncedRelease),this.context.transport.on("pause",this._syncedRelease),this.context.transport.on("loopEnd",this._syncedRelease)),this}_syncState(){let t=!1;return this._synced||(this._synced=!0,t=!0),t}_syncMethod(t,s){const i=this["_original_"+t]=this[t];this[t]=(...e)=>{var t=e[s],t=this.context.transport.schedule(t=>{e[s]=t,i.apply(this,e)},t);this._scheduledEvents.push(t)}}unsync(){return this._scheduledEvents.forEach(t=>this.context.transport.clear(t)),this._scheduledEvents=[],this._synced&&(this._synced=!1,this.triggerAttack=this._original_triggerAttack,this.triggerRelease=this._original_triggerRelease,this.context.transport.off("stop",this._syncedRelease),this.context.transport.off("pause",this._syncedRelease),this.context.transport.off("loopEnd",this._syncedRelease)),this}triggerAttackRelease(t,e,s,i){s=this.toSeconds(s),e=this.toSeconds(e);return this.triggerAttack(t,s,i),this.triggerRelease(s+e),this}dispose(){return super.dispose(),this._volume.dispose(),this.unsync(),this._scheduledEvents=[],this}}class Ef extends Mf{constructor(){var t=g(Ef.getDefaults(),arguments);super(t),this.portamento=t.portamento,this.onsilence=t.onsilence}static getDefaults(){return Object.assign(Mf.getDefaults(),{detune:0,onsilence:x,portamento:0})}triggerAttack(t,e,s=1){this.log("triggerAttack",t,e,s);e=this.toSeconds(e);return this._triggerEnvelopeAttack(e,s),this.setNote(t,e),this}triggerRelease(t){this.log("triggerRelease",t);t=this.toSeconds(t);return this._triggerEnvelopeRelease(t),this}setNote(t,e){var e=this.toSeconds(e),s=t instanceof vd?t.toFrequency():t;if(0this.onsilence(this)},t.oscillator)),this.frequency=this.oscillator.frequency,this.detune=this.oscillator.detune,this.envelope=new Rf(Object.assign({context:this.context},t.envelope)),this.oscillator.chain(this.envelope,this.output),y(this,["oscillator","frequency","detune","envelope"])}static getDefaults(){return Object.assign(Ef.getDefaults(),{envelope:Object.assign(v(Of.getDefaults(),Object.keys(A.getDefaults())),{attack:.005,decay:.1,release:1,sustain:.3}),oscillator:Object.assign(v(lf.getDefaults(),[...Object.keys(M.getDefaults()),"frequency","detune"]),{type:"triangle"})})}_triggerEnvelopeAttack(t,e){if(this.envelope.triggerAttack(t,e),this.oscillator.start(t),0===this.envelope.sustain){const e=this.toSeconds(this.envelope.attack),s=this.toSeconds(this.envelope.decay);this.oscillator.stop(t+e+s)}}_triggerEnvelopeRelease(t){this.envelope.triggerRelease(t),this.oscillator.stop(t+this.toSeconds(this.envelope.release))}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}dispose(){return super.dispose(),this.oscillator.dispose(),this.envelope.dispose(),this}}class If extends Ef{constructor(){var t=g(If.getDefaults(),arguments);super(t),this.name="ModulationSynth",this._carrier=new qf({context:this.context,oscillator:t.oscillator,envelope:t.envelope,onsilence:()=>this.onsilence(this),volume:-10}),this._modulator=new qf({context:this.context,oscillator:t.modulation,envelope:t.modulationEnvelope,volume:-10}),this.oscillator=this._carrier.oscillator,this.envelope=this._carrier.envelope,this.modulation=this._modulator.oscillator,this.modulationEnvelope=this._modulator.envelope,this.frequency=new O({context:this.context,units:"frequency"}),this.detune=new O({context:this.context,value:t.detune,units:"cents"}),this.harmonicity=new q({context:this.context,value:t.harmonicity,minValue:0}),this._modulationNode=new C({context:this.context,gain:0}),y(this,["frequency","harmonicity","oscillator","envelope","modulation","modulationEnvelope","detune"])}static getDefaults(){return Object.assign(Ef.getDefaults(),{harmonicity:3,oscillator:Object.assign(v(lf.getDefaults(),[...Object.keys(M.getDefaults()),"frequency","detune"]),{type:"sine"}),envelope:Object.assign(v(Of.getDefaults(),Object.keys(A.getDefaults())),{attack:.01,decay:.01,sustain:1,release:.5}),modulation:Object.assign(v(lf.getDefaults(),[...Object.keys(M.getDefaults()),"frequency","detune"]),{type:"square"}),modulationEnvelope:Object.assign(v(Of.getDefaults(),Object.keys(A.getDefaults())),{attack:.5,decay:0,sustain:1,release:.5})})}_triggerEnvelopeAttack(t,e){this._carrier._triggerEnvelopeAttack(t,e),this._modulator._triggerEnvelopeAttack(t,e)}_triggerEnvelopeRelease(t){return this._carrier._triggerEnvelopeRelease(t),this._modulator._triggerEnvelopeRelease(t),this}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}dispose(){return super.dispose(),this._carrier.dispose(),this._modulator.dispose(),this.frequency.dispose(),this.detune.dispose(),this.harmonicity.dispose(),this._modulationNode.dispose(),this}}class Ff extends If{constructor(){super(g(Ff.getDefaults(),arguments)),this.name="AMSynth",this._modulationScale=new sf({context:this.context}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.detune.fan(this._carrier.detune,this._modulator.detune),this._modulator.chain(this._modulationScale,this._modulationNode.gain),this._carrier.chain(this._modulationNode,this.output)}dispose(){return super.dispose(),this._modulationScale.dispose(),this}}class Vf extends A{constructor(){var t=g(Vf.getDefaults(),arguments,["frequency","type"]);super(t),this.name="BiquadFilter",this._filter=this.context.createBiquadFilter(),this.input=this.output=this._filter,this.Q=new k({context:this.context,units:"number",value:t.Q,param:this._filter.Q}),this.frequency=new k({context:this.context,units:"frequency",value:t.frequency,param:this._filter.frequency}),this.detune=new k({context:this.context,units:"cents",value:t.detune,param:this._filter.detune}),this.gain=new k({context:this.context,units:"decibels",convert:!1,value:t.gain,param:this._filter.gain}),this.type=t.type}static getDefaults(){return Object.assign(A.getDefaults(),{Q:1,type:"lowpass",frequency:350,detune:0,gain:0})}get type(){return this._filter.type}set type(t){l(-1!==["lowpass","highpass","bandpass","lowshelf","highshelf","notch","allpass","peaking"].indexOf(t),"Invalid filter type: "+t),this._filter.type=t}getFrequencyResponse(e=128){const s=new Float32Array(e);for(let t=0;tt.type=e)}get rolloff(){return this._rolloff}set rolloff(t){const e=xp(t)?t:parseInt(t,10),s=[-12,-24,-48,-96];var i=s.indexOf(e);l(-1!==i,"rolloff can only be "+s.join(", ")),i+=1,this._rolloff=e,this.input.disconnect(),this._filters.forEach(t=>t.disconnect()),this._filters=new Array(i);for(let t=0;t1);return this._filters.forEach(()=>{e.getFrequencyResponse(t).forEach((t,e)=>s[e]*=t)}),e.dispose(),s}dispose(){return super.dispose(),this._filters.forEach(t=>{t.dispose()}),nd(this,["detune","frequency","gain","Q"]),this.frequency.dispose(),this.Q.dispose(),this.detune.dispose(),this.gain.dispose(),this}}class Pf extends Of{constructor(){var t=g(Pf.getDefaults(),arguments,["attack","decay","sustain","release"]);super(t),this.name="FrequencyEnvelope",this._octaves=t.octaves,this._baseFrequency=this.toFrequency(t.baseFrequency),this._exponent=this.input=new Ud({context:this.context,value:t.exponent}),this._scale=this.output=new pf({context:this.context,min:this._baseFrequency,max:this._baseFrequency*Math.pow(2,this._octaves)}),this._sig.chain(this._exponent,this._scale)}static getDefaults(){return Object.assign(Of.getDefaults(),{baseFrequency:200,exponent:1,octaves:4})}get baseFrequency(){return this._baseFrequency}set baseFrequency(t){t=this.toFrequency(t);f(t,0),this._baseFrequency=t,this._scale.min=this._baseFrequency,this.octaves=this._octaves}get octaves(){return this._octaves}set octaves(t){this._octaves=t,this._scale.max=this._baseFrequency*Math.pow(2,t)}get exponent(){return this._exponent.value}set exponent(t){this._exponent.value=t}dispose(){return super.dispose(),this._exponent.dispose(),this._scale.dispose(),this}}class jf extends Ef{constructor(){var t=g(jf.getDefaults(),arguments);super(t),this.name="MonoSynth",this.oscillator=new lf(Object.assign(t.oscillator,{context:this.context,detune:t.detune,onstop:()=>this.onsilence(this)})),this.frequency=this.oscillator.frequency,this.detune=this.oscillator.detune,this.filter=new Nf(Object.assign(t.filter,{context:this.context})),this.filterEnvelope=new Pf(Object.assign(t.filterEnvelope,{context:this.context})),this.envelope=new Rf(Object.assign(t.envelope,{context:this.context})),this.oscillator.chain(this.filter,this.envelope,this.output),this.filterEnvelope.connect(this.filter.frequency),y(this,["oscillator","frequency","detune","filter","filterEnvelope","envelope"])}static getDefaults(){return Object.assign(Ef.getDefaults(),{envelope:Object.assign(v(Of.getDefaults(),Object.keys(A.getDefaults())),{attack:.005,decay:.1,release:1,sustain:.9}),filter:Object.assign(v(Nf.getDefaults(),Object.keys(A.getDefaults())),{Q:1,rolloff:-12,type:"lowpass"}),filterEnvelope:Object.assign(v(Pf.getDefaults(),Object.keys(A.getDefaults())),{attack:.6,baseFrequency:200,decay:.2,exponent:2,octaves:3,release:2,sustain:.5}),oscillator:Object.assign(v(lf.getDefaults(),Object.keys(M.getDefaults())),{type:"sawtooth"})})}_triggerEnvelopeAttack(t,e=1){if(this.envelope.triggerAttack(t,e),this.filterEnvelope.triggerAttack(t),this.oscillator.start(t),0===this.envelope.sustain){const e=this.toSeconds(this.envelope.attack),s=this.toSeconds(this.envelope.decay);this.oscillator.stop(t+e+s)}}_triggerEnvelopeRelease(t){this.envelope.triggerRelease(t),this.filterEnvelope.triggerRelease(t),this.oscillator.stop(t+this.toSeconds(this.envelope.release))}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}dispose(){return super.dispose(),this.oscillator.dispose(),this.envelope.dispose(),this.filterEnvelope.dispose(),this.filter.dispose(),this}}class Lf extends Ef{constructor(){var t=g(Lf.getDefaults(),arguments);super(t),this.name="DuoSynth",this.voice0=new jf(Object.assign(t.voice0,{context:this.context,onsilence:()=>this.onsilence(this)})),this.voice1=new jf(Object.assign(t.voice1,{context:this.context})),this.harmonicity=new q({context:this.context,units:"positive",value:t.harmonicity}),this._vibrato=new ff({frequency:t.vibratoRate,context:this.context,min:-50,max:50}),this._vibrato.start(),this.vibratoRate=this._vibrato.frequency,this._vibratoGain=new C({context:this.context,units:"normalRange",gain:t.vibratoAmount}),this.vibratoAmount=this._vibratoGain.gain,this.frequency=new O({context:this.context,units:"frequency",value:440}),this.detune=new O({context:this.context,units:"cents",value:t.detune}),this.frequency.connect(this.voice0.frequency),this.frequency.chain(this.harmonicity,this.voice1.frequency),this._vibrato.connect(this._vibratoGain),this._vibratoGain.fan(this.voice0.detune,this.voice1.detune),this.detune.fan(this.voice0.detune,this.voice1.detune),this.voice0.connect(this.output),this.voice1.connect(this.output),y(this,["voice0","voice1","frequency","vibratoAmount","vibratoRate"])}getLevelAtTime(t){return t=this.toSeconds(t),this.voice0.envelope.getValueAtTime(t)+this.voice1.envelope.getValueAtTime(t)}static getDefaults(){return zp(Ef.getDefaults(),{vibratoAmount:.5,vibratoRate:5,harmonicity:1.5,voice0:zp(v(jf.getDefaults(),Object.keys(Ef.getDefaults())),{filterEnvelope:{attack:.01,decay:0,sustain:1,release:.5},envelope:{attack:.01,decay:0,sustain:1,release:.5}}),voice1:zp(v(jf.getDefaults(),Object.keys(Ef.getDefaults())),{filterEnvelope:{attack:.01,decay:0,sustain:1,release:.5},envelope:{attack:.01,decay:0,sustain:1,release:.5}})})}_triggerEnvelopeAttack(t,e){this.voice0._triggerEnvelopeAttack(t,e),this.voice1._triggerEnvelopeAttack(t,e)}_triggerEnvelopeRelease(t){return this.voice0._triggerEnvelopeRelease(t),this.voice1._triggerEnvelopeRelease(t),this}dispose(){return super.dispose(),this.voice0.dispose(),this.voice1.dispose(),this.frequency.dispose(),this.detune.dispose(),this._vibrato.dispose(),this.vibratoRate.dispose(),this._vibratoGain.dispose(),this.harmonicity.dispose(),this}}class zf extends If{constructor(){var t=g(zf.getDefaults(),arguments);super(t),this.name="FMSynth",this.modulationIndex=new q({context:this.context,value:t.modulationIndex}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.frequency.chain(this.modulationIndex,this._modulationNode),this.detune.fan(this._carrier.detune,this._modulator.detune),this._modulator.connect(this._modulationNode.gain),this._modulationNode.connect(this._carrier.frequency),this._carrier.connect(this.output)}static getDefaults(){return Object.assign(If.getDefaults(),{modulationIndex:10})}dispose(){return super.dispose(),this.modulationIndex.dispose(),this}}const Wf=[1,1.483,1.932,2.546,2.63,3.897];class Bf extends Ef{constructor(){var e=g(Bf.getDefaults(),arguments);super(e),this.name="MetalSynth",this._oscillators=[],this._freqMultipliers=[],this.detune=new O({context:this.context,units:"cents",value:e.detune}),this.frequency=new O({context:this.context,units:"frequency"}),this._amplitude=new C({context:this.context,gain:0}).connect(this.output),this._highpass=new Nf({Q:0,context:this.context,type:"highpass"}).connect(this._amplitude);for(let t=0;tthis.onsilence(this):x,type:"square"});i.connect(this._highpass),this._oscillators[t]=i;var s=new q({context:this.context,value:Wf[t]});this._freqMultipliers[t]=s,this.frequency.chain(s,i.frequency),this.detune.connect(i.detune)}this._filterFreqScaler=new pf({context:this.context,max:7e3,min:this.toFrequency(e.resonance)}),this.envelope=new Of({attack:e.envelope.attack,attackCurve:"linear",context:this.context,decay:e.envelope.decay,release:e.envelope.release,sustain:0}),this.envelope.chain(this._filterFreqScaler,this._highpass.frequency),this.envelope.connect(this._amplitude.gain),this._octaves=e.octaves,this.octaves=e.octaves}static getDefaults(){return zp(Ef.getDefaults(),{envelope:Object.assign(v(Of.getDefaults(),Object.keys(A.getDefaults())),{attack:.001,decay:1.4,release:.2}),harmonicity:5.1,modulationIndex:32,octaves:1.5,resonance:4e3})}_triggerEnvelopeAttack(e,t=1){return this.envelope.triggerAttack(e,t),this._oscillators.forEach(t=>t.start(e)),0===this.envelope.sustain&&this._oscillators.forEach(t=>{t.stop(e+this.toSeconds(this.envelope.attack)+this.toSeconds(this.envelope.decay))}),this}_triggerEnvelopeRelease(e){return this.envelope.triggerRelease(e),this._oscillators.forEach(t=>t.stop(e+this.toSeconds(this.envelope.release))),this}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}get modulationIndex(){return this._oscillators[0].modulationIndex.value}set modulationIndex(e){this._oscillators.forEach(t=>t.modulationIndex.value=e)}get harmonicity(){return this._oscillators[0].harmonicity.value}set harmonicity(e){this._oscillators.forEach(t=>t.harmonicity.value=e)}get resonance(){return this._filterFreqScaler.min}set resonance(t){this._filterFreqScaler.min=this.toFrequency(t),this.octaves=this._octaves}get octaves(){return this._octaves}set octaves(t){this._octaves=t,this._filterFreqScaler.max=this._filterFreqScaler.min*Math.pow(2,t)}dispose(){return super.dispose(),this._oscillators.forEach(t=>t.dispose()),this._freqMultipliers.forEach(t=>t.dispose()),this.frequency.dispose(),this.detune.dispose(),this._filterFreqScaler.dispose(),this._amplitude.dispose(),this.envelope.dispose(),this._highpass.dispose(),this}}class Uf extends qf{constructor(){var t=g(Uf.getDefaults(),arguments);super(t),this.name="MembraneSynth",this.portamento=0,this.pitchDecay=t.pitchDecay,this.octaves=t.octaves,y(this,["oscillator","envelope"])}static getDefaults(){return zp(Ef.getDefaults(),qf.getDefaults(),{envelope:{attack:.001,attackCurve:"exponential",decay:.4,release:1.4,sustain:.01},octaves:10,oscillator:{type:"sine"},pitchDecay:.05})}setNote(t,e){var e=this.toSeconds(e),t=this.toFrequency(t instanceof vd?t.toFrequency():t),s=t*this.octaves;return this.oscillator.frequency.setValueAtTime(s,e),this.oscillator.frequency.exponentialRampToValueAtTime(t,e+this.toSeconds(this.pitchDecay)),this}dispose(){return super.dispose(),this}}Fp([_f(0)],Uf.prototype,"octaves",void 0),Fp([mf(0)],Uf.prototype,"pitchDecay",void 0);class Gf extends Mf{constructor(){var t=g(Gf.getDefaults(),arguments);super(t),this.name="NoiseSynth",this.noise=new Yd(Object.assign({context:this.context},t.noise)),this.envelope=new Rf(Object.assign({context:this.context},t.envelope)),this.noise.chain(this.envelope,this.output)}static getDefaults(){return Object.assign(Mf.getDefaults(),{envelope:Object.assign(v(Of.getDefaults(),Object.keys(A.getDefaults())),{decay:.1,sustain:0}),noise:Object.assign(v(Yd.getDefaults(),Object.keys(M.getDefaults())),{type:"white"})})}triggerAttack(t,e=1){return t=this.toSeconds(t),this.envelope.triggerAttack(t,e),this.noise.start(t),0===this.envelope.sustain&&this.noise.stop(t+this.toSeconds(this.envelope.attack)+this.toSeconds(this.envelope.decay)),this}triggerRelease(t){return t=this.toSeconds(t),this.envelope.triggerRelease(t),this.noise.stop(t+this.toSeconds(this.envelope.release)),this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",0),this._syncMethod("triggerRelease",0)),this}triggerAttackRelease(t,e,s=1){return e=this.toSeconds(e),t=this.toSeconds(t),this.triggerAttack(e,s),this.triggerRelease(e+t),this}dispose(){return super.dispose(),this.noise.dispose(),this.envelope.dispose(),this}}const Qf=new Set;function Zf(t){Qf.add(t)}function Xf(t,e){t=`registerProcessor("${t}", ${e})`;Qf.add(t)}class Yf extends A{constructor(t){super(t),this.name="ToneAudioWorklet",this.workletOptions={},this.onprocessorerror=x;const e=URL.createObjectURL(new Blob([Array.from(Qf).join("\n")],{type:"text/javascript"})),s=this._audioWorkletName();this._dummyGain=this.context.createGain(),this._dummyParam=this._dummyGain.gain,this.context.addAudioWorkletModule(e).then(()=>{this.disposed||(this._worklet=this.context.createAudioWorkletNode(s,this.workletOptions),this._worklet.onprocessorerror=this.onprocessorerror.bind(this),this.onReady(this._worklet))})}dispose(){return super.dispose(),this._dummyGain.disconnect(),this._worklet&&(this._worklet.port.postMessage("dispose"),this._worklet.disconnect()),this}}Zf('\n\t/**\n\t * The base AudioWorkletProcessor for use in Tone.js. Works with the {@link ToneAudioWorklet}. \n\t */\n\tclass ToneAudioWorkletProcessor extends AudioWorkletProcessor {\n\n\t\tconstructor(options) {\n\t\t\t\n\t\t\tsuper(options);\n\t\t\t/**\n\t\t\t * If the processor was disposed or not. Keep alive until it\'s disposed.\n\t\t\t */\n\t\t\tthis.disposed = false;\n\t\t \t/** \n\t\t\t * The number of samples in the processing block\n\t\t\t */\n\t\t\tthis.blockSize = 128;\n\t\t\t/**\n\t\t\t * the sample rate\n\t\t\t */\n\t\t\tthis.sampleRate = sampleRate;\n\n\t\t\tthis.port.onmessage = (event) => {\n\t\t\t\t// when it receives a dispose \n\t\t\t\tif (event.data === "dispose") {\n\t\t\t\t\tthis.disposed = true;\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n'),Zf("\n\t/**\n\t * Abstract class for a single input/output processor. \n\t * has a 'generate' function which processes one sample at a time\n\t */\n\tclass SingleIOProcessor extends ToneAudioWorkletProcessor {\n\n\t\tconstructor(options) {\n\t\t\tsuper(Object.assign(options, {\n\t\t\t\tnumberOfInputs: 1,\n\t\t\t\tnumberOfOutputs: 1\n\t\t\t}));\n\t\t\t/**\n\t\t\t * Holds the name of the parameter and a single value of that\n\t\t\t * parameter at the current sample\n\t\t\t * @type { [name: string]: number }\n\t\t\t */\n\t\t\tthis.params = {}\n\t\t}\n\n\t\t/**\n\t\t * Generate an output sample from the input sample and parameters\n\t\t * @abstract\n\t\t * @param input number\n\t\t * @param channel number\n\t\t * @param parameters { [name: string]: number }\n\t\t * @returns number\n\t\t */\n\t\tgenerate(){}\n\n\t\t/**\n\t\t * Update the private params object with the \n\t\t * values of the parameters at the given index\n\t\t * @param parameters { [name: string]: Float32Array },\n\t\t * @param index number\n\t\t */\n\t\tupdateParams(parameters, index) {\n\t\t\tfor (const paramName in parameters) {\n\t\t\t\tconst param = parameters[paramName];\n\t\t\t\tif (param.length > 1) {\n\t\t\t\t\tthis.params[paramName] = parameters[paramName][index];\n\t\t\t\t} else {\n\t\t\t\t\tthis.params[paramName] = parameters[paramName][0];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Process a single frame of the audio\n\t\t * @param inputs Float32Array[][]\n\t\t * @param outputs Float32Array[][]\n\t\t */\n\t\tprocess(inputs, outputs, parameters) {\n\t\t\tconst input = inputs[0];\n\t\t\tconst output = outputs[0];\n\t\t\t// get the parameter values\n\t\t\tconst channelCount = Math.max(input && input.length || 0, output.length);\n\t\t\tfor (let sample = 0; sample < this.blockSize; sample++) {\n\t\t\t\tthis.updateParams(parameters, sample);\n\t\t\t\tfor (let channel = 0; channel < channelCount; channel++) {\n\t\t\t\t\tconst inputSample = input && input.length ? input[channel][sample] : 0;\n\t\t\t\t\toutput[channel][sample] = this.generate(inputSample, channel, this.params);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn !this.disposed;\n\t\t}\n\t};\n"),Zf("\n\t/**\n\t * A multichannel buffer for use within an AudioWorkletProcessor as a delay line\n\t */\n\tclass DelayLine {\n\t\t\n\t\tconstructor(size, channels) {\n\t\t\tthis.buffer = [];\n\t\t\tthis.writeHead = []\n\t\t\tthis.size = size;\n\n\t\t\t// create the empty channels\n\t\t\tfor (let i = 0; i < channels; i++) {\n\t\t\t\tthis.buffer[i] = new Float32Array(this.size);\n\t\t\t\tthis.writeHead[i] = 0;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Push a value onto the end\n\t\t * @param channel number\n\t\t * @param value number\n\t\t */\n\t\tpush(channel, value) {\n\t\t\tthis.writeHead[channel] += 1;\n\t\t\tif (this.writeHead[channel] > this.size) {\n\t\t\t\tthis.writeHead[channel] = 0;\n\t\t\t}\n\t\t\tthis.buffer[channel][this.writeHead[channel]] = value;\n\t\t}\n\n\t\t/**\n\t\t * Get the recorded value of the channel given the delay\n\t\t * @param channel number\n\t\t * @param delay number delay samples\n\t\t */\n\t\tget(channel, delay) {\n\t\t\tlet readHead = this.writeHead[channel] - Math.floor(delay);\n\t\t\tif (readHead < 0) {\n\t\t\t\treadHead += this.size;\n\t\t\t}\n\t\t\treturn this.buffer[channel][readHead];\n\t\t}\n\t}\n");const Hf="feedback-comb-filter";Xf(Hf,'\n\tclass FeedbackCombFilterWorklet extends SingleIOProcessor {\n\n\t\tconstructor(options) {\n\t\t\tsuper(options);\n\t\t\tthis.delayLine = new DelayLine(this.sampleRate, options.channelCount || 2);\n\t\t}\n\n\t\tstatic get parameterDescriptors() {\n\t\t\treturn [{\n\t\t\t\tname: "delayTime",\n\t\t\t\tdefaultValue: 0.1,\n\t\t\t\tminValue: 0,\n\t\t\t\tmaxValue: 1,\n\t\t\t\tautomationRate: "k-rate"\n\t\t\t}, {\n\t\t\t\tname: "feedback",\n\t\t\t\tdefaultValue: 0.5,\n\t\t\t\tminValue: 0,\n\t\t\t\tmaxValue: 0.9999,\n\t\t\t\tautomationRate: "k-rate"\n\t\t\t}];\n\t\t}\n\n\t\tgenerate(input, channel, parameters) {\n\t\t\tconst delayedSample = this.delayLine.get(channel, parameters.delayTime * this.sampleRate);\n\t\t\tthis.delayLine.push(channel, input + delayedSample * parameters.feedback);\n\t\t\treturn delayedSample;\n\t\t}\n\t}\n');class $f extends Yf{constructor(){var t=g($f.getDefaults(),arguments,["delayTime","resonance"]);super(t),this.name="FeedbackCombFilter",this.input=new C({context:this.context}),this.output=new C({context:this.context}),this.delayTime=new k({context:this.context,value:t.delayTime,units:"time",minValue:0,maxValue:1,param:this._dummyParam,swappable:!0}),this.resonance=new k({context:this.context,value:t.resonance,units:"normalRange",param:this._dummyParam,swappable:!0}),y(this,["resonance","delayTime"])}_audioWorkletName(){return Hf}static getDefaults(){return Object.assign(A.getDefaults(),{delayTime:.1,resonance:.5})}onReady(t){bd(this.input,t,this.output);var e=t.parameters.get("delayTime"),e=(this.delayTime.setParam(e),t.parameters.get("feedback"));this.resonance.setParam(e)}dispose(){return super.dispose(),this.input.dispose(),this.output.dispose(),this.delayTime.dispose(),this.resonance.dispose(),this}}class Jf extends A{constructor(){var t=g(Jf.getDefaults(),arguments,["frequency","type"]);super(t),this.name="OnePoleFilter",this._frequency=t.frequency,this._type=t.type,this.input=new C({context:this.context}),this.output=new C({context:this.context}),this._createFilter()}static getDefaults(){return Object.assign(A.getDefaults(),{frequency:880,type:"lowpass"})}_createFilter(){const t=this._filter,e=this.toFrequency(this._frequency),s=1/(2*Math.PI*e);if("lowpass"===this._type){const t=1/(s*this.context.sampleRate),e=t-1;this._filter=this.context.createIIRFilter([t,0],[1,e])}else{const t=1/(s*this.context.sampleRate)-1;this._filter=this.context.createIIRFilter([1,-1],[1,t])}this.input.chain(this._filter,this.output),t&&this.context.setTimeout(()=>{this.disposed||(this.input.disconnect(t),t.disconnect())},this.blockTime)}get frequency(){return this._frequency}set frequency(t){this._frequency=t,this._createFilter()}get type(){return this._type}set type(t){this._type=t,this._createFilter()}getFrequencyResponse(e=128){const s=new Float32Array(e);for(let t=0;tthis.releaseAll(t),l(!xp(t.voice),"DEPRECATED: The polyphony count is no longer the first argument.");var e=t.voice.getDefaults(),e=(this.options=Object.assign(e,t.options),this.voice=t.voice,this.maxPolyphony=t.maxPolyphony,this._dummyVoice=this._getNextAvailableVoice(),this._voices.indexOf(this._dummyVoice));this._voices.splice(e,1),this._gcTimeout=this.context.setInterval(this._collectGarbage.bind(this),1)}static getDefaults(){return Object.assign(Mf.getDefaults(),{maxPolyphony:32,options:{},voice:qf})}get activeVoices(){return this._activeVoices.length}_makeVoiceAvailable(e){this._availableVoices.push(e);var t=this._activeVoices.findIndex(t=>t.voice===e);this._activeVoices.splice(t,1)}_getNextAvailableVoice(){if(this._availableVoices.length)return this._availableVoices.shift();if(this._voices.lengthMath.ceil(this._averageActiveVoices+1)){const t=this._availableVoices.shift(),e=this._voices.indexOf(t);this._voices.splice(e,1),this.context.isOffline||t.dispose()}}_triggerAttack(t,i,n){t.forEach(t=>{const e=new Nd(this.context,t).toMidi(),s=this._getNextAvailableVoice();s&&(s.triggerAttack(t,i,n),this._activeVoices.push({midi:e,voice:s,released:!1}),this.log("triggerAttack",t,i))})}_triggerRelease(t,i){t.forEach(t=>{const s=new Nd(this.context,t).toMidi(),e=this._activeVoices.find(({midi:t,released:e})=>t===s&&!e);e&&(e.voice.triggerRelease(i),e.released=!0,this.log("triggerRelease",t,i))})}_scheduleEvent(t,e,s,i){l(!this.disposed,"Synth was already disposed"),s<=this.now()?"attack"===t?this._triggerAttack(e,s,i):this._triggerRelease(e,s):this.context.setTimeout(()=>{this.disposed||this._scheduleEvent(t,e,s,i)},s-this.now())}triggerAttack(t,e,s){Array.isArray(t)||(t=[t]);e=this.toSeconds(e);return this._scheduleEvent("attack",t,e,s),this}triggerRelease(t,e){Array.isArray(t)||(t=[t]);e=this.toSeconds(e);return this._scheduleEvent("release",t,e),this}triggerAttackRelease(e,s,t,i){var n=this.toSeconds(t);if(this.triggerAttack(e,n,i),d(s)){l(d(e),"If the duration is an array, the notes must also be an array");for(let t=0;tt.set(e)),this._dummyVoice.set(e),this}get(){return this._dummyVoice.get()}releaseAll(t){const e=this.toSeconds(t);return this._activeVoices.forEach(({voice:t})=>{t.triggerRelease(e)}),this}dispose(){return super.dispose(),this._dummyVoice.dispose(),this._voices.forEach(t=>t.dispose()),this._activeVoices=[],this._availableVoices=[],this.context.clearInterval(this._gcTimeout),this}}class s_ extends Mf{constructor(){const s=g(s_.getDefaults(),arguments,["urls","onload","baseUrl"],"urls"),i=(super(s),this.name="Sampler",this._activeSources=new Map,{});Object.keys(s.urls).forEach(t=>{const e=parseInt(t,10);if(l(Sp(t)||xp(e)&&isFinite(e),"url key is neither a note or midi pitch: "+t),Sp(t)){const e=new vd(this.context,t).toMidi();i[e]=s.urls[t]}else xp(e)&&isFinite(e)&&(i[e]=s.urls[e])}),this._buffers=new Vd({urls:i,onload:s.onload,baseUrl:s.baseUrl,onerror:s.onerror}),this.attack=s.attack,this.release=s.release,this.curve=s.curve,this._buffers.loaded&&Promise.resolve().then(s.onload)}static getDefaults(){return Object.assign(Mf.getDefaults(),{attack:0,baseUrl:"",curve:"exponential",onload:x,onerror:x,release:.1,urls:{}})}_findClosest(t){let e=0;for(;e<96;){if(this._buffers.has(t+e))return-e;if(this._buffers.has(t-e))return e;e++}throw new Error("No available buffers for note: "+t)}triggerAttack(t,c,l=1){return this.log("triggerAttack",t,c,l),(t=Array.isArray(t)?t:[t]).forEach(t=>{const e=fd(new vd(this.context,t).toFrequency()),s=Math.round(e),i=e-s,n=this._findClosest(s),r=s-n,o=this._buffers.get(r),a=ud(n+i),h=new Xd({url:o,context:this.context,curve:this.curve,fadeIn:this.attack,fadeOut:this.release,playbackRate:a}).connect(this.output);h.start(c,0,o.duration/a,l),d(this._activeSources.get(s))||this._activeSources.set(s,[]),this._activeSources.get(s).push(h),h.onended=()=>{if(this._activeSources&&this._activeSources.has(s)){const t=this._activeSources.get(s),e=t.indexOf(h);-1!==e&&t.splice(e,1)}}}),this}triggerRelease(t,s){return this.log("triggerRelease",t,s),(t=Array.isArray(t)?t:[t]).forEach(t=>{var e=new vd(this.context,t).toMidi();if(this._activeSources.has(e)&&this._activeSources.get(e).length){const t=this._activeSources.get(e);s=this.toSeconds(s),t.forEach(t=>{t.stop(s)}),this._activeSources.set(e,[])}}),this}releaseAll(t){const e=this.toSeconds(t);return this._activeSources.forEach(t=>{for(;t.length;)t.shift().stop(e)}),this}sync(){return this._syncState()&&(this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",1)),this}triggerAttackRelease(t,s,e,i=1){const n=this.toSeconds(e);return this.triggerAttack(t,n,i),d(s)?(l(d(t),"notes must be an array when duration is array"),t.forEach((t,e)=>{e=s[Math.min(e,s.length-1)];this.triggerRelease(t,n+this.toSeconds(e))})):this.triggerRelease(t,n+this.toSeconds(s)),this}add(t,e,s){var i;return l(Sp(t)||isFinite(t),"note must be a pitch or midi: "+t),Sp(t)?(i=new vd(this.context,t).toMidi(),this._buffers.add(i,e,s)):this._buffers.add(t,e,s),this}get loaded(){return this._buffers.loaded}dispose(){return super.dispose(),this._buffers.dispose(),this._activeSources.forEach(t=>{t.forEach(t=>t.dispose())}),this._activeSources.clear(),this}}Fp([mf(0)],s_.prototype,"attack",void 0),Fp([mf(0)],s_.prototype,"release",void 0);class i_ extends S{constructor(){var t=g(i_.getDefaults(),arguments,["callback","value"]);super(t),this.name="ToneEvent",this._state=new wd("stopped"),this._startOffset=0,this._loop=t.loop,this.callback=t.callback,this.value=t.value,this._loopStart=this.toTicks(t.loopStart),this._loopEnd=this.toTicks(t.loopEnd),this._playbackRate=t.playbackRate,this._probability=t.probability,this._humanize=t.humanize,this.mute=t.mute,this._playbackRate=t.playbackRate,this._state.increasing=!0,this._rescheduleEvents()}static getDefaults(){return Object.assign(S.getDefaults(),{callback:x,humanize:!1,loop:!1,loopEnd:"1m",loopStart:0,mute:!1,playbackRate:1,probability:1,value:null})}_rescheduleEvents(t=-1){this._state.forEachFrom(t,t=>{let e;var s,i;"started"===t.state&&(-1!==t.id&&this.context.transport.clear(t.id),s=t.time+Math.round(this.startOffset/this._playbackRate),!0===this._loop||xp(this._loop)&&1{this.context.transport.clear(t.id)}),this._state.cancel(t),this}_tick(e){var t=this.context.transport.getTicksAtTime(e);if(!(this.mute||"started"!==this._state.getValueAtTime(t)||this.probability<1&&Math.random()>this.probability)){if(this.humanize){let t=.02;bp(this.humanize)||(t=this.toSeconds(this.humanize)),e+=(2*Math.random()-1)*t}this.callback(e,this.value)}}_getLoopDuration(){return(this._loopEnd-this._loopStart)/this._playbackRate}get loop(){return this._loop}set loop(t){this._loop=t,this._rescheduleEvents()}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._rescheduleEvents()}get loopEnd(){return new D(this.context,this._loopEnd).toSeconds()}set loopEnd(t){this._loopEnd=this.toTicks(t),this._loop&&this._rescheduleEvents()}get loopStart(){return new D(this.context,this._loopStart).toSeconds()}set loopStart(t){this._loopStart=this.toTicks(t),this._loop&&this._rescheduleEvents()}get progress(){var t,e,s;return this._loop?(t=this.context.transport.ticks,null!==(e=this._state.get(t))&&"started"===e.state?(s=this._getLoopDuration(),(t-e.time)%s/s):0):0}dispose(){return super.dispose(),this.cancel(),this._state.dispose(),this}}class n_ extends S{constructor(){var t=g(n_.getDefaults(),arguments,["callback","interval"]);super(t),this.name="Loop",this._event=new i_({context:this.context,callback:this._tick.bind(this),loop:!0,loopEnd:t.interval,playbackRate:t.playbackRate,probability:t.probability,humanize:t.humanize}),this.callback=t.callback,this.iterations=t.iterations}static getDefaults(){return Object.assign(S.getDefaults(),{interval:"4n",callback:x,playbackRate:1,iterations:1/0,probability:1,mute:!1,humanize:!1})}start(t){return this._event.start(t),this}stop(t){return this._event.stop(t),this}cancel(t){return this._event.cancel(t),this}_tick(t){this.callback(t)}get state(){return this._event.state}get progress(){return this._event.progress}get interval(){return this._event.loopEnd}set interval(t){this._event.loopEnd=t}get playbackRate(){return this._event.playbackRate}set playbackRate(t){this._event.playbackRate=t}get humanize(){return this._event.humanize}set humanize(t){this._event.humanize=t}get probability(){return this._event.probability}set probability(t){this._event.probability=t}get mute(){return this._event.mute}set mute(t){this._event.mute=t}get iterations(){return!0===this._event.loop?1/0:this._event.loop}set iterations(t){this._event.loop=t===1/0||t}dispose(){return super.dispose(),this._event.dispose(),this}}class r_ extends i_{constructor(){const t=g(r_.getDefaults(),arguments,["callback","events"]);super(t),this.name="Part",this._state=new wd("stopped"),this._events=new Set,this._state.increasing=!0,t.events.forEach(t=>{d(t)?this.add(t[0],t[1]):this.add(t)})}static getDefaults(){return Object.assign(i_.getDefaults(),{events:[]})}start(e,t){const s=this.toTicks(e);if("started"!==this._state.getValueAtTime(s)){t=Wp(t,this._loop?this._loopStart:0),t=this._loop?Wp(t,this._loopStart):Wp(t,0);const e=this.toTicks(t);this._state.add({id:-1,offset:e,state:"started",time:s}),this._forEach(t=>{this._startNote(t,s,e)})}return this}_startNote(t,e,s){e-=s,this._loop?t.startOffset>=this._loopStart&&t.startOffset=s&&(t.loop=!1,t.start(new D(this.context,e))):t.startOffset>=s&&t.start(new D(this.context,e))}get startOffset(){return this._startOffset}set startOffset(t){this._startOffset=t,this._forEach(t=>{t.startOffset+=this._startOffset})}stop(e){var t=this.toTicks(e);return this._state.cancel(t),this._state.setStateAtTime("stopped",t),this._forEach(t=>{t.stop(e)}),this}at(t,e){const s=new T(this.context,t).toTicks(),i=new D(this.context,1).toSeconds(),n=this._events.values();let r=n.next();for(;!r.done;){const t=r.value;if(Math.abs(s-t.startOffset){"started"===t.state?this._startNote(e,t.time,t.offset):e.stop(new D(this.context,t.time))})}remove(e,s){return wp(e)&&e.hasOwnProperty("time")&&(e=(s=e).time),e=this.toTicks(e),this._events.forEach(t=>{t.startOffset===e&&(vp(s)||o(s)&&t.value===s)&&(this._events.delete(t),t.dispose())}),this}clear(){return this._forEach(t=>t.dispose()),this._events.clear(),this}cancel(e){return this._forEach(t=>t.cancel(e)),this._state.cancel(this.toTicks(e)),this}_forEach(e){return this._events&&this._events.forEach(t=>{t instanceof r_?t._forEach(e):e(t)}),this}_setAll(e,s){this._forEach(t=>{t[e]=s})}_tick(t,e){this.mute||this.callback(t,e)}_testLoopBoundries(t){this._loop&&(t.startOffset=this._loopEnd)?t.cancel(0):"stopped"===t.state&&this._restartEvent(t)}get probability(){return this._probability}set probability(t){this._probability=t,this._setAll("probability",t)}get humanize(){return this._humanize}set humanize(t){this._humanize=t,this._setAll("humanize",t)}get loop(){return this._loop}set loop(e){this._loop=e,this._forEach(t=>{t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.loop=e,this._testLoopBoundries(t)})}get loopEnd(){return new D(this.context,this._loopEnd).toSeconds()}set loopEnd(e){this._loopEnd=this.toTicks(e),this._loop&&this._forEach(t=>{t.loopEnd=e,this._testLoopBoundries(t)})}get loopStart(){return new D(this.context,this._loopStart).toSeconds()}set loopStart(t){this._loopStart=this.toTicks(t),this._loop&&this._forEach(t=>{t.loopStart=this.loopStart,this._testLoopBoundries(t)})}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._setAll("playbackRate",t)}get length(){return this._events.size}dispose(){return super.dispose(),this.clear(),this}}function*o_(t){let e=0;for(;e=t-1&&(e=!1):--s<=0&&(e=!0)}function*l_(t){let e=0,s=0;for(;et[e],set:(t,e,s)=>(Tp(e)&&isFinite(parseInt(e,10))&&d(s)?t[e]=this._createSequence(s):t[e]=s,this._eventsUpdated(),!0)})}_eventsUpdated(){this._part.clear(),this._rescheduleSequence(this._eventsArray,this._subdivision,this.startOffset),this.loopEnd=this.loopEnd}_rescheduleSequence(t,s,i){t.forEach((t,e)=>{e=e*s+i;if(d(t))this._rescheduleSequence(t,s/t.length,e);else{const s=new D(this.context,e,"i").toSeconds();this._part.add(s,t)}})}_indexTime(t){return new D(this.context,t*this._subdivision+this.startOffset).toSeconds()}clear(){return this._part.clear(),this}dispose(){return super.dispose(),this._part.dispose(),this}get loop(){return this._part.loop}set loop(t){this._part.loop=t}get loopStart(){return this._loopStart}set loopStart(t){this._loopStart=t,this._part.loopStart=this._indexTime(t)}get loopEnd(){return this._loopEnd}set loopEnd(t){this._loopEnd=t,this._part.loopEnd=0===t?this._indexTime(this._eventsArray.length):this._indexTime(t)}get startOffset(){return this._part.startOffset}set startOffset(t){this._part.startOffset=t}get playbackRate(){return this._part.playbackRate}set playbackRate(t){this._part.playbackRate=t}get probability(){return this._part.probability}set probability(t){this._part.probability=t}get progress(){return this._part.progress}get humanize(){return this._part.humanize}set humanize(t){this._part.humanize=t}get length(){return this._part.length}}class m_ extends A{constructor(){var t=g(m_.getDefaults(),arguments,["fade"]);super(t),this.name="CrossFade",this._panner=this.context.createStereoPanner(),this._split=this.context.createChannelSplitter(2),this._g2a=new wf({context:this.context}),this.a=new C({context:this.context,gain:0}),this.b=new C({context:this.context,gain:0}),this.output=new C({context:this.context}),this._internalChannels=[this.a,this.b],this.fade=new O({context:this.context,units:"normalRange",value:t.fade}),y(this,"fade"),this.context.getConstant(1).connect(this._panner),this._panner.connect(this._split),this._panner.channelCount=1,this._panner.channelCountMode="explicit",Td(this._split,this.a.gain,0),Td(this._split,this.b.gain,1),this.fade.chain(this._g2a,this._panner.pan),this.a.connect(this.output),this.b.connect(this.output)}static getDefaults(){return Object.assign(A.getDefaults(),{fade:.5})}dispose(){return super.dispose(),this.a.dispose(),this.b.dispose(),this.output.dispose(),this.fade.dispose(),this._g2a.dispose(),this._panner.disconnect(),this._split.disconnect(),this}}class I extends A{constructor(t){super(t),this.name="Effect",this._dryWet=new m_({context:this.context}),this.wet=this._dryWet.fade,this.effectSend=new C({context:this.context}),this.effectReturn=new C({context:this.context}),this.input=new C({context:this.context}),this.output=this._dryWet,this.input.fan(this._dryWet.a,this.effectSend),this.effectReturn.connect(this._dryWet.b),this.wet.setValueAtTime(t.wet,0),this._internalChannels=[this.effectReturn,this.effectSend],y(this,"wet")}static getDefaults(){return Object.assign(A.getDefaults(),{wet:1})}connectEffect(t){return this._internalChannels.push(t),this.effectSend.chain(t,this.effectReturn),this}dispose(){return super.dispose(),this._dryWet.dispose(),this.effectSend.dispose(),this.effectReturn.dispose(),this.wet.dispose(),this}}class g_ extends I{constructor(t){super(t),this.name="LFOEffect",this._lfo=new ff({context:this.context,frequency:t.frequency,amplitude:t.depth}),this.depth=this._lfo.amplitude,this.frequency=this._lfo.frequency,this.type=t.type,y(this,["frequency","depth"])}static getDefaults(){return Object.assign(I.getDefaults(),{frequency:1,type:"sine",depth:1})}start(t){return this._lfo.start(t),this}stop(t){return this._lfo.stop(t),this}sync(){return this._lfo.sync(),this}unsync(){return this._lfo.unsync(),this}get type(){return this._lfo.type}set type(t){this._lfo.type=t}dispose(){return super.dispose(),this._lfo.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class v_ extends g_{constructor(){var t=g(v_.getDefaults(),arguments,["frequency","baseFrequency","octaves"]);super(t),this.name="AutoFilter",this.filter=new Nf(Object.assign(t.filter,{context:this.context})),this.connectEffect(this.filter),this._lfo.connect(this.filter.frequency),this.octaves=t.octaves,this.baseFrequency=t.baseFrequency}static getDefaults(){return Object.assign(g_.getDefaults(),{baseFrequency:200,octaves:2.6,filter:{type:"lowpass",rolloff:-12,Q:1}})}get baseFrequency(){return this._lfo.min}set baseFrequency(t){this._lfo.min=this.toFrequency(t),this.octaves=this._octaves}get octaves(){return this._octaves}set octaves(t){this._octaves=t,this._lfo.max=this._lfo.min*Math.pow(2,t)}dispose(){return super.dispose(),this.filter.dispose(),this}}class y_ extends A{constructor(){var t=g(y_.getDefaults(),arguments,["pan"]);super(t),this.name="Panner",this._panner=this.context.createStereoPanner(),this.input=this._panner,this.output=this._panner,this.pan=new k({context:this.context,param:this._panner.pan,value:t.pan,minValue:-1,maxValue:1}),this._panner.channelCount=t.channelCount,this._panner.channelCountMode="explicit",y(this,"pan")}static getDefaults(){return Object.assign(A.getDefaults(),{pan:0,channelCount:1})}dispose(){return super.dispose(),this._panner.disconnect(),this.pan.dispose(),this}}class x_ extends g_{constructor(){var t=g(x_.getDefaults(),arguments,["frequency"]);super(t),this.name="AutoPanner",this._panner=new y_({context:this.context,channelCount:t.channelCount}),this.connectEffect(this._panner),this._lfo.connect(this._panner.pan),this._lfo.min=-1,this._lfo.max=1}static getDefaults(){return Object.assign(g_.getDefaults(),{channelCount:1})}dispose(){return super.dispose(),this._panner.dispose(),this}}class w_ extends A{constructor(){var t=g(w_.getDefaults(),arguments,["smoothing"]);super(t),this.name="Follower",this._abs=this.input=new xf({context:this.context}),this._lowpass=this.output=new Jf({context:this.context,frequency:1/this.toSeconds(t.smoothing),type:"lowpass"}),this._abs.connect(this._lowpass),this._smoothing=t.smoothing}static getDefaults(){return Object.assign(A.getDefaults(),{smoothing:.05})}get smoothing(){return this._smoothing}set smoothing(t){this._smoothing=t,this._lowpass.frequency=1/this.toSeconds(this.smoothing)}dispose(){return super.dispose(),this._abs.dispose(),this._lowpass.dispose(),this}}class b_ extends I{constructor(){var t=g(b_.getDefaults(),arguments,["baseFrequency","octaves","sensitivity"]);super(t),this.name="AutoWah",this._follower=new w_({context:this.context,smoothing:t.follower}),this._sweepRange=new Af({context:this.context,min:0,max:1,exponent:.5}),this._baseFrequency=this.toFrequency(t.baseFrequency),this._octaves=t.octaves,this._inputBoost=new C({context:this.context}),this._bandpass=new Nf({context:this.context,rolloff:-48,frequency:0,Q:t.Q}),this._peaking=new Nf({context:this.context,type:"peaking"}),this._peaking.gain.value=t.gain,this.gain=this._peaking.gain,this.Q=this._bandpass.Q,this.effectSend.chain(this._inputBoost,this._follower,this._sweepRange),this._sweepRange.connect(this._bandpass.frequency),this._sweepRange.connect(this._peaking.frequency),this.effectSend.chain(this._bandpass,this._peaking,this.effectReturn),this._setSweepRange(),this.sensitivity=t.sensitivity,y(this,["gain","Q"])}static getDefaults(){return Object.assign(I.getDefaults(),{baseFrequency:100,octaves:6,sensitivity:0,Q:2,gain:2,follower:.2})}get octaves(){return this._octaves}set octaves(t){this._octaves=t,this._setSweepRange()}get follower(){return this._follower.smoothing}set follower(t){this._follower.smoothing=t}get baseFrequency(){return this._baseFrequency}set baseFrequency(t){this._baseFrequency=this.toFrequency(t),this._setSweepRange()}get sensitivity(){return ld(1/this._inputBoost.gain.value)}set sensitivity(t){this._inputBoost.gain.value=1/cd(t)}_setSweepRange(){this._sweepRange.min=this._baseFrequency,this._sweepRange.max=Math.min(this._baseFrequency*Math.pow(2,this._octaves),this.context.sampleRate/2)}dispose(){return super.dispose(),this._follower.dispose(),this._sweepRange.dispose(),this._bandpass.dispose(),this._peaking.dispose(),this._inputBoost.dispose(),this}}const T_="bit-crusher";Xf(T_,"\n\tclass BitCrusherWorklet extends SingleIOProcessor {\n\n\t\tstatic get parameterDescriptors() {\n\t\t\treturn [{\n\t\t\t\tname: \"bits\",\n\t\t\t\tdefaultValue: 12,\n\t\t\t\tminValue: 1,\n\t\t\t\tmaxValue: 16,\n\t\t\t\tautomationRate: 'k-rate'\n\t\t\t}];\n\t\t}\n\n\t\tgenerate(input, _channel, parameters) {\n\t\t\tconst step = Math.pow(0.5, parameters.bits - 1);\n\t\t\tconst val = step * Math.floor(input / step + 0.5);\n\t\t\treturn val;\n\t\t}\n\t}\n");class S_ extends I{constructor(){var t=g(S_.getDefaults(),arguments,["bits"]);super(t),this.name="BitCrusher",this._bitCrusherWorklet=new k_({context:this.context,bits:t.bits}),this.connectEffect(this._bitCrusherWorklet),this.bits=this._bitCrusherWorklet.bits}static getDefaults(){return Object.assign(I.getDefaults(),{bits:4})}dispose(){return super.dispose(),this._bitCrusherWorklet.dispose(),this}}class k_ extends Yf{constructor(){var t=g(k_.getDefaults(),arguments);super(t),this.name="BitCrusherWorklet",this.input=new C({context:this.context}),this.output=new C({context:this.context}),this.bits=new k({context:this.context,value:t.bits,units:"positive",minValue:1,maxValue:16,param:this._dummyParam,swappable:!0})}static getDefaults(){return Object.assign(Yf.getDefaults(),{bits:12})}_audioWorkletName(){return T_}onReady(t){bd(this.input,t,this.output);t=t.parameters.get("bits");this.bits.setParam(t)}dispose(){return super.dispose(),this.input.dispose(),this.output.dispose(),this.bits.dispose(),this}}class A_ extends I{constructor(){var t=g(A_.getDefaults(),arguments,["order"]);super(t),this.name="Chebyshev",this._shaper=new Bd({context:this.context,length:4096}),this._order=t.order,this.connectEffect(this._shaper),this.order=t.order,this.oversample=t.oversample}static getDefaults(){return Object.assign(I.getDefaults(),{order:1,oversample:"none"})}_getCoefficient(t,e,s){return s.has(e)||(0===e?s.set(e,0):1===e?s.set(e,t):s.set(e,2*t*this._getCoefficient(t,e-1,s)-this._getCoefficient(t,e-2,s))),s.get(e)}get order(){return this._order}set order(e){l(Number.isInteger(e),"'order' must be an integer"),this._order=e,this._shaper.setMap(t=>this._getCoefficient(t,e,new Map))}get oversample(){return this._shaper.oversample}set oversample(t){this._shaper.oversample=t}dispose(){return super.dispose(),this._shaper.dispose(),this}}class C_ extends A{constructor(){var t=g(C_.getDefaults(),arguments,["channels"]);super(t),this.name="Split",this._splitter=this.input=this.output=this.context.createChannelSplitter(t.channels),this._internalChannels=[this._splitter]}static getDefaults(){return Object.assign(A.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._splitter.disconnect(),this}}class O_ extends A{constructor(){var t=g(O_.getDefaults(),arguments,["channels"]);super(t),this.name="Merge",this._merger=this.output=this.input=this.context.createChannelMerger(t.channels)}static getDefaults(){return Object.assign(A.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._merger.disconnect(),this}}class D_ extends A{constructor(t){super(t),this.name="StereoEffect",this.input=new C({context:this.context}),this.input.channelCount=2,this.input.channelCountMode="explicit",this._dryWet=this.output=new m_({context:this.context,fade:t.wet}),this.wet=this._dryWet.fade,this._split=new C_({context:this.context,channels:2}),this._merge=new O_({context:this.context,channels:2}),this.input.connect(this._split),this.input.connect(this._dryWet.a),this._merge.connect(this._dryWet.b),y(this,["wet"])}connectEffectLeft(...t){this._split.connect(t[0],0,0),bd(...t),Td(t[t.length-1],this._merge,0,0)}connectEffectRight(...t){this._split.connect(t[0],1,0),bd(...t),Td(t[t.length-1],this._merge,0,1)}static getDefaults(){return Object.assign(A.getDefaults(),{wet:1})}dispose(){return super.dispose(),this._dryWet.dispose(),this._split.dispose(),this._merge.dispose(),this}}class M_ extends D_{constructor(t){super(t),this.feedback=new O({context:this.context,value:t.feedback,units:"normalRange"}),this._feedbackL=new C({context:this.context}),this._feedbackR=new C({context:this.context}),this._feedbackSplit=new C_({context:this.context,channels:2}),this._feedbackMerge=new O_({context:this.context,channels:2}),this._merge.connect(this._feedbackSplit),this._feedbackMerge.connect(this._split),this._feedbackSplit.connect(this._feedbackL,0,0),this._feedbackL.connect(this._feedbackMerge,0,0),this._feedbackSplit.connect(this._feedbackR,1,0),this._feedbackR.connect(this._feedbackMerge,0,1),this.feedback.fan(this._feedbackL.gain,this._feedbackR.gain),y(this,["feedback"])}static getDefaults(){return Object.assign(D_.getDefaults(),{feedback:.5})}dispose(){return super.dispose(),this.feedback.dispose(),this._feedbackL.dispose(),this._feedbackR.dispose(),this._feedbackSplit.dispose(),this._feedbackMerge.dispose(),this}}class E_ extends M_{constructor(){var t=g(E_.getDefaults(),arguments,["frequency","delayTime","depth"]);super(t),this.name="Chorus",this._depth=t.depth,this._delayTime=t.delayTime/1e3,this._lfoL=new ff({context:this.context,frequency:t.frequency,min:0,max:1}),this._lfoR=new ff({context:this.context,frequency:t.frequency,min:0,max:1,phase:180}),this._delayNodeL=new Rd({context:this.context}),this._delayNodeR=new Rd({context:this.context}),this.frequency=this._lfoL.frequency,y(this,["frequency"]),this._lfoL.frequency.connect(this._lfoR.frequency),this.connectEffectLeft(this._delayNodeL),this.connectEffectRight(this._delayNodeR),this._lfoL.connect(this._delayNodeL.delayTime),this._lfoR.connect(this._delayNodeR.delayTime),this.depth=this._depth,this.type=t.type,this.spread=t.spread}static getDefaults(){return Object.assign(M_.getDefaults(),{frequency:1.5,delayTime:3.5,depth:.7,type:"sine",spread:180,feedback:0,wet:.5})}get depth(){return this._depth}set depth(t){this._depth=t;t=this._delayTime*t;this._lfoL.min=Math.max(this._delayTime-t,0),this._lfoL.max=this._delayTime+t,this._lfoR.min=Math.max(this._delayTime-t,0),this._lfoR.max=this._delayTime+t}get delayTime(){return 1e3*this._delayTime}set delayTime(t){this._delayTime=t/1e3,this.depth=this._depth}get type(){return this._lfoL.type}set type(t){this._lfoL.type=t,this._lfoR.type=t}get spread(){return this._lfoR.phase-this._lfoL.phase}set spread(t){this._lfoL.phase=90-t/2,this._lfoR.phase=t/2+90}start(t){return this._lfoL.start(t),this._lfoR.start(t),this}stop(t){return this._lfoL.stop(t),this._lfoR.stop(t),this}sync(){return this._lfoL.sync(),this._lfoR.sync(),this}unsync(){return this._lfoL.unsync(),this._lfoR.unsync(),this}dispose(){return super.dispose(),this._lfoL.dispose(),this._lfoR.dispose(),this._delayNodeL.dispose(),this._delayNodeR.dispose(),this.frequency.dispose(),this}}class R_ extends I{constructor(){var t=g(R_.getDefaults(),arguments,["distortion"]);super(t),this.name="Distortion",this._shaper=new Bd({context:this.context,length:4096}),this._distortion=t.distortion,this.connectEffect(this._shaper),this.distortion=t.distortion,this.oversample=t.oversample}static getDefaults(){return Object.assign(I.getDefaults(),{distortion:.4,oversample:"none"})}get distortion(){return this._distortion}set distortion(t){const e=100*(this._distortion=t),s=Math.PI/180;this._shaper.setMap(t=>Math.abs(t)<.001?0:(3+e)*t*20*s/(Math.PI+e*Math.abs(t)))}get oversample(){return this._shaper.oversample}set oversample(t){this._shaper.oversample=t}dispose(){return super.dispose(),this._shaper.dispose(),this}}class q_ extends I{constructor(t){super(t),this.name="FeedbackEffect",this._feedbackGain=new C({context:this.context,gain:t.feedback,units:"normalRange"}),this.feedback=this._feedbackGain.gain,y(this,"feedback"),this.effectReturn.chain(this._feedbackGain,this.effectSend)}static getDefaults(){return Object.assign(I.getDefaults(),{feedback:.125})}dispose(){return super.dispose(),this._feedbackGain.dispose(),this.feedback.dispose(),this}}class I_ extends q_{constructor(){var t=g(I_.getDefaults(),arguments,["delayTime","feedback"]);super(t),this.name="FeedbackDelay",this._delayNode=new Rd({context:this.context,delayTime:t.delayTime,maxDelay:t.maxDelay}),this.delayTime=this._delayNode.delayTime,this.connectEffect(this._delayNode),y(this,"delayTime")}static getDefaults(){return Object.assign(q_.getDefaults(),{delayTime:.25,maxDelay:1})}dispose(){return super.dispose(),this._delayNode.dispose(),this.delayTime.dispose(),this}}class F_ extends A{constructor(t){super(t),this.name="PhaseShiftAllpass",this.input=new C({context:this.context}),this.output=new C({context:this.context}),this.offset90=new C({context:this.context}),this._bank0=this._createAllPassFilterBank([.6923878,.9360654322959,.988229522686,.9987488452737]),this._bank1=this._createAllPassFilterBank([.4021921162426,.856171088242,.9722909545651,.9952884791278]),this._oneSampleDelay=this.context.createIIRFilter([0,1],[1,0]),bd(this.input,...this._bank0,this._oneSampleDelay,this.output),bd(this.input,...this._bank1,this.offset90)}_createAllPassFilterBank(t){return t.map(t=>{t=[[t*t,0,-1],[1,0,-t*t]];return this.context.createIIRFilter(t[0],t[1])})}dispose(){return super.dispose(),this.input.dispose(),this.output.dispose(),this.offset90.dispose(),this._bank0.forEach(t=>t.disconnect()),this._bank1.forEach(t=>t.disconnect()),this._oneSampleDelay.disconnect(),this}}class V_ extends I{constructor(){var t=g(V_.getDefaults(),arguments,["frequency"]),t=(super(t),this.name="FrequencyShifter",this.frequency=new O({context:this.context,units:"frequency",value:t.frequency,minValue:-this.context.sampleRate/2,maxValue:this.context.sampleRate/2}),this._sine=new ef({context:this.context,type:"sine"}),this._cosine=new E({context:this.context,phase:-90,type:"sine"}),this._sineMultiply=new q({context:this.context}),this._cosineMultiply=new q({context:this.context}),this._negate=new bf({context:this.context}),this._add=new uf({context:this.context}),this._phaseShifter=new F_({context:this.context}),this.effectSend.connect(this._phaseShifter),this.frequency.fan(this._sine.frequency,this._cosine.frequency),this._phaseShifter.offset90.connect(this._cosineMultiply),this._cosine.connect(this._cosineMultiply.factor),this._phaseShifter.connect(this._sineMultiply),this._sine.connect(this._sineMultiply.factor),this._sineMultiply.connect(this._negate),this._cosineMultiply.connect(this._add),this._negate.connect(this._add.addend),this._add.connect(this.effectReturn),this.immediate());this._sine.start(t),this._cosine.start(t)}static getDefaults(){return Object.assign(I.getDefaults(),{frequency:0})}dispose(){return super.dispose(),this.frequency.dispose(),this._add.dispose(),this._cosine.dispose(),this._cosineMultiply.dispose(),this._negate.dispose(),this._phaseShifter.dispose(),this._sine.dispose(),this._sineMultiply.dispose(),this}}const N_=[1557/44100,1617/44100,1491/44100,1422/44100,1277/44100,1356/44100,1188/44100,1116/44100],P_=[225,556,441,341];class j_ extends D_{constructor(){const s=g(j_.getDefaults(),arguments,["roomSize","dampening"]);super(s),this.name="Freeverb",this._combFilters=[],this._allpassFiltersL=[],this._allpassFiltersR=[],this.roomSize=new O({context:this.context,value:s.roomSize,units:"normalRange"}),this._allpassFiltersL=P_.map(t=>{const e=this.context.createBiquadFilter();return e.type="allpass",e.frequency.value=t,e}),this._allpassFiltersR=P_.map(t=>{const e=this.context.createBiquadFilter();return e.type="allpass",e.frequency.value=t,e}),this._combFilters=N_.map((t,e)=>{t=new Kf({context:this.context,dampening:s.dampening,delayTime:t});return et.dampening=e)}dispose(){return super.dispose(),this._allpassFiltersL.forEach(t=>t.disconnect()),this._allpassFiltersR.forEach(t=>t.disconnect()),this._combFilters.forEach(t=>t.dispose()),this.roomSize.dispose(),this}}const L_=[.06748,.06404,.08212,.09004],z_=[.773,.802,.753,.733],W_=[347,113,37];class B_ extends D_{constructor(){var t=g(B_.getDefaults(),arguments,["roomSize"]);super(t),this.name="JCReverb",this._allpassFilters=[],this._feedbackCombFilters=[],this.roomSize=new O({context:this.context,value:t.roomSize,units:"normalRange"}),this._scaleRoomSize=new pf({context:this.context,min:-.733,max:.197}),this._allpassFilters=W_.map(t=>{const e=this.context.createBiquadFilter();return e.type="allpass",e.frequency.value=t,e}),this._feedbackCombFilters=L_.map((t,e)=>{const s=new $f({context:this.context,delayTime:t});return this._scaleRoomSize.connect(s.resonance),s.resonance.value=z_[e],et.disconnect()),this._feedbackCombFilters.forEach(t=>t.dispose()),this.roomSize.dispose(),this._scaleRoomSize.dispose(),this}}class U_ extends M_{constructor(t){super(t),this._feedbackL.disconnect(),this._feedbackL.connect(this._feedbackMerge,0,1),this._feedbackR.disconnect(),this._feedbackR.connect(this._feedbackMerge,0,0),y(this,["feedback"])}}class G_ extends U_{constructor(){var t=g(G_.getDefaults(),arguments,["delayTime","feedback"]);super(t),this.name="PingPongDelay",this._leftDelay=new Rd({context:this.context,maxDelay:t.maxDelay}),this._rightDelay=new Rd({context:this.context,maxDelay:t.maxDelay}),this._rightPreDelay=new Rd({context:this.context,maxDelay:t.maxDelay}),this.delayTime=new O({context:this.context,units:"time",value:t.delayTime}),this.connectEffectLeft(this._leftDelay),this.connectEffectRight(this._rightPreDelay,this._rightDelay),this.delayTime.fan(this._leftDelay.delayTime,this._rightDelay.delayTime,this._rightPreDelay.delayTime),this._feedbackL.disconnect(),this._feedbackL.connect(this._rightDelay),y(this,["delayTime"])}static getDefaults(){return Object.assign(U_.getDefaults(),{delayTime:.25,maxDelay:1})}dispose(){return super.dispose(),this._leftDelay.dispose(),this._rightDelay.dispose(),this._rightPreDelay.dispose(),this.delayTime.dispose(),this}}class Q_ extends q_{constructor(){var t=g(Q_.getDefaults(),arguments,["pitch"]),t=(super(t),this.name="PitchShift",this._frequency=new O({context:this.context}),this._delayA=new Rd({maxDelay:1,context:this.context}),this._lfoA=new ff({context:this.context,min:0,max:.1,type:"sawtooth"}).connect(this._delayA.delayTime),this._delayB=new Rd({maxDelay:1,context:this.context}),this._lfoB=new ff({context:this.context,min:0,max:.1,type:"sawtooth",phase:180}).connect(this._delayB.delayTime),this._crossFade=new m_({context:this.context}),this._crossFadeLFO=new ff({context:this.context,min:0,max:1,type:"triangle",phase:90}).connect(this._crossFade.fade),this._feedbackDelay=new Rd({delayTime:t.delayTime,context:this.context}),this.delayTime=this._feedbackDelay.delayTime,y(this,"delayTime"),this._pitch=t.pitch,this._windowSize=t.windowSize,this._delayA.connect(this._crossFade.a),this._delayB.connect(this._crossFade.b),this._frequency.fan(this._lfoA.frequency,this._lfoB.frequency,this._crossFadeLFO.frequency),this.effectSend.fan(this._delayA,this._delayB),this._crossFade.chain(this._feedbackDelay,this.effectReturn),this.now());this._lfoA.start(t),this._lfoB.start(t),this._crossFadeLFO.start(t),this.windowSize=this._windowSize}static getDefaults(){return Object.assign(q_.getDefaults(),{pitch:0,windowSize:.1,delayTime:0,feedback:0})}get pitch(){return this._pitch}set pitch(t){this._pitch=t;let e=0;e=t<0?(this._lfoA.min=0,this._lfoA.max=this._windowSize,this._lfoB.min=0,this._lfoB.max=this._windowSize,ud(t-1)+1):(this._lfoA.min=this._windowSize,this._lfoA.max=0,this._lfoB.min=this._windowSize,this._lfoB.max=0,ud(t)-1),this._frequency.value=e*(1.2/this._windowSize)}get windowSize(){return this._windowSize}set windowSize(t){this._windowSize=this.toSeconds(t),this.pitch=this._pitch}dispose(){return super.dispose(),this._frequency.dispose(),this._delayA.dispose(),this._delayB.dispose(),this._lfoA.dispose(),this._lfoB.dispose(),this._crossFade.dispose(),this._crossFadeLFO.dispose(),this._feedbackDelay.dispose(),this}}class Z_ extends D_{constructor(){var t=g(Z_.getDefaults(),arguments,["frequency","octaves","baseFrequency"]);super(t),this.name="Phaser",this._lfoL=new ff({context:this.context,frequency:t.frequency,min:0,max:1}),this._lfoR=new ff({context:this.context,frequency:t.frequency,min:0,max:1,phase:180}),this._baseFrequency=this.toFrequency(t.baseFrequency),this._octaves=t.octaves,this.Q=new O({context:this.context,value:t.Q,units:"positive"}),this._filtersL=this._makeFilters(t.stages,this._lfoL),this._filtersR=this._makeFilters(t.stages,this._lfoR),this.frequency=this._lfoL.frequency,this.frequency.value=t.frequency,this.connectEffectLeft(...this._filtersL),this.connectEffectRight(...this._filtersR),this._lfoL.frequency.connect(this._lfoR.frequency),this.baseFrequency=t.baseFrequency,this.octaves=t.octaves,this._lfoL.start(),this._lfoR.start(),y(this,["frequency","Q"])}static getDefaults(){return Object.assign(D_.getDefaults(),{frequency:.5,octaves:3,stages:10,Q:10,baseFrequency:350})}_makeFilters(e,s){const i=[];for(let t=0;tt.disconnect()),this._filtersR.forEach(t=>t.disconnect()),this.frequency.dispose(),this}}class X_ extends I{constructor(){var t=g(X_.getDefaults(),arguments,["decay"]);super(t),this.name="Reverb",this._convolver=this.context.createConvolver(),this.ready=Promise.resolve(),this._decay=t.decay,this._preDelay=t.preDelay,this.generate(),this.connectEffect(this._convolver)}static getDefaults(){return Object.assign(I.getDefaults(),{decay:1.5,preDelay:.01})}get decay(){return this._decay}set decay(t){f(t=this.toSeconds(t),.001),this._decay=t,this.generate()}get preDelay(){return this._preDelay}set preDelay(t){f(t=this.toSeconds(t),0),this._preDelay=t,this.generate()}generate(){return _(this,void 0,void 0,function*(){const t=this.ready,e=new rd(2,this._decay+this._preDelay,this.context.sampleRate),s=new Yd({context:e}),i=new Yd({context:e}),n=new O_({context:e}),r=(s.connect(n,0,0),i.connect(n,0,1),new C({context:e}).toDestination()),o=(n.connect(r),s.start(0),i.start(0),r.gain.setValueAtTime(0,0),r.gain.setValueAtTime(1,this._preDelay),r.gain.exponentialApproachValueAtTime(0,this._preDelay,this.decay),e.render());return this.ready=o.then(x),yield t,this._convolver.buffer=(yield o).get(),this})}dispose(){return super.dispose(),this._convolver.disconnect(),this}}class Y_ extends A{constructor(){super(g(Y_.getDefaults(),arguments)),this.name="MidSideSplit",this._split=this.input=new C_({channels:2,context:this.context}),this._midAdd=new uf({context:this.context}),this.mid=new q({context:this.context,value:Math.SQRT1_2}),this._sideSubtract=new Tf({context:this.context}),this.side=new q({context:this.context,value:Math.SQRT1_2}),this._split.connect(this._midAdd,0),this._split.connect(this._midAdd.addend,1),this._split.connect(this._sideSubtract,0),this._split.connect(this._sideSubtract.subtrahend,1),this._midAdd.connect(this.mid),this._sideSubtract.connect(this.side)}dispose(){return super.dispose(),this.mid.dispose(),this.side.dispose(),this._midAdd.dispose(),this._sideSubtract.dispose(),this._split.dispose(),this}}class H_ extends A{constructor(){super(g(H_.getDefaults(),arguments)),this.name="MidSideMerge",this.mid=new C({context:this.context}),this.side=new C({context:this.context}),this._left=new uf({context:this.context}),this._leftMult=new q({context:this.context,value:Math.SQRT1_2}),this._right=new Tf({context:this.context}),this._rightMult=new q({context:this.context,value:Math.SQRT1_2}),this._merge=this.output=new O_({context:this.context}),this.mid.fan(this._left),this.side.connect(this._left.addend),this.mid.connect(this._right),this.side.connect(this._right.subtrahend),this._left.connect(this._leftMult),this._right.connect(this._rightMult),this._leftMult.connect(this._merge,0,0),this._rightMult.connect(this._merge,0,1)}dispose(){return super.dispose(),this.mid.dispose(),this.side.dispose(),this._leftMult.dispose(),this._rightMult.dispose(),this._left.dispose(),this._right.dispose(),this}}class $_ extends I{constructor(t){super(t),this.name="MidSideEffect",this._midSideMerge=new H_({context:this.context}),this._midSideSplit=new Y_({context:this.context}),this._midSend=this._midSideSplit.mid,this._sideSend=this._midSideSplit.side,this._midReturn=this._midSideMerge.mid,this._sideReturn=this._midSideMerge.side,this.effectSend.connect(this._midSideSplit),this._midSideMerge.connect(this.effectReturn)}connectEffectMid(...t){this._midSend.chain(...t,this._midReturn)}connectEffectSide(...t){this._sideSend.chain(...t,this._sideReturn)}dispose(){return super.dispose(),this._midSideSplit.dispose(),this._midSideMerge.dispose(),this._midSend.dispose(),this._sideSend.dispose(),this._midReturn.dispose(),this._sideReturn.dispose(),this}}class J_ extends $_{constructor(){var t=g(J_.getDefaults(),arguments,["width"]);super(t),this.name="StereoWidener",this.width=new O({context:this.context,value:t.width,units:"normalRange"}),y(this,["width"]),this._twoTimesWidthMid=new q({context:this.context,value:2}),this._twoTimesWidthSide=new q({context:this.context,value:2}),this._midMult=new q({context:this.context}),this._twoTimesWidthMid.connect(this._midMult.factor),this.connectEffectMid(this._midMult),this._oneMinusWidth=new Tf({context:this.context}),this._oneMinusWidth.connect(this._twoTimesWidthMid),Td(this.context.getConstant(1),this._oneMinusWidth),this.width.connect(this._oneMinusWidth.subtrahend),this._sideMult=new q({context:this.context}),this.width.connect(this._twoTimesWidthSide),this._twoTimesWidthSide.connect(this._sideMult.factor),this.connectEffectSide(this._sideMult)}static getDefaults(){return Object.assign($_.getDefaults(),{width:.5})}dispose(){return super.dispose(),this.width.dispose(),this._midMult.dispose(),this._sideMult.dispose(),this._twoTimesWidthMid.dispose(),this._twoTimesWidthSide.dispose(),this._oneMinusWidth.dispose(),this}}class K_ extends D_{constructor(){var t=g(K_.getDefaults(),arguments,["frequency","depth"]);super(t),this.name="Tremolo",this._lfoL=new ff({context:this.context,type:t.type,min:1,max:0}),this._lfoR=new ff({context:this.context,type:t.type,min:1,max:0}),this._amplitudeL=new C({context:this.context}),this._amplitudeR=new C({context:this.context}),this.frequency=new O({context:this.context,value:t.frequency,units:"frequency"}),this.depth=new O({context:this.context,value:t.depth,units:"normalRange"}),y(this,["frequency","depth"]),this.connectEffectLeft(this._amplitudeL),this.connectEffectRight(this._amplitudeR),this._lfoL.connect(this._amplitudeL.gain),this._lfoR.connect(this._amplitudeR.gain),this.frequency.fan(this._lfoL.frequency,this._lfoR.frequency),this.depth.fan(this._lfoR.amplitude,this._lfoL.amplitude),this.spread=t.spread}static getDefaults(){return Object.assign(D_.getDefaults(),{frequency:10,type:"sine",depth:.5,spread:180})}start(t){return this._lfoL.start(t),this._lfoR.start(t),this}stop(t){return this._lfoL.stop(t),this._lfoR.stop(t),this}sync(){return this._lfoL.sync(),this._lfoR.sync(),this.context.transport.syncSignal(this.frequency),this}unsync(){return this._lfoL.unsync(),this._lfoR.unsync(),this.context.transport.unsyncSignal(this.frequency),this}get type(){return this._lfoL.type}set type(t){this._lfoL.type=t,this._lfoR.type=t}get spread(){return this._lfoR.phase-this._lfoL.phase}set spread(t){this._lfoL.phase=90-t/2,this._lfoR.phase=t/2+90}dispose(){return super.dispose(),this._lfoL.dispose(),this._lfoR.dispose(),this._amplitudeL.dispose(),this._amplitudeR.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class tm extends I{constructor(){var t=g(tm.getDefaults(),arguments,["frequency","depth"]);super(t),this.name="Vibrato",this._delayNode=new Rd({context:this.context,delayTime:0,maxDelay:t.maxDelay}),this._lfo=new ff({context:this.context,type:t.type,min:0,max:t.maxDelay,frequency:t.frequency,phase:-90}).start().connect(this._delayNode.delayTime),this.frequency=this._lfo.frequency,this.depth=this._lfo.amplitude,this.depth.value=t.depth,y(this,["frequency","depth"]),this.effectSend.chain(this._delayNode,this.effectReturn)}static getDefaults(){return Object.assign(I.getDefaults(),{maxDelay:.005,frequency:5,depth:.1,type:"sine"})}get type(){return this._lfo.type}set type(t){this._lfo.type=t}dispose(){return super.dispose(),this._delayNode.dispose(),this._lfo.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class em extends A{constructor(){var e=g(em.getDefaults(),arguments,["type","size"]);super(e),this.name="Analyser",this._analysers=[],this._buffers=[],this.input=this.output=this._gain=new C({context:this.context}),this._split=new C_({context:this.context,channels:e.channels}),this.input.connect(this._split),f(e.channels,1);for(let t=0;t{e=this._buffers[e];"fft"===this._type?t.getFloatFrequencyData(e):"waveform"===this._type&&t.getFloatTimeDomainData(e)}),1===this.channels?this._buffers[0]:this._buffers}get size(){return this._analysers[0].frequencyBinCount}set size(s){this._analysers.forEach((t,e)=>{t.fftSize=2*s,this._buffers[e]=new Float32Array(s)})}get channels(){return this._analysers.length}get type(){return this._type}set type(t){l("waveform"===t||"fft"===t,"Analyser: invalid type: "+t),this._type=t}get smoothing(){return this._analysers[0].smoothingTimeConstant}set smoothing(e){this._analysers.forEach(t=>t.smoothingTimeConstant=e)}dispose(){return super.dispose(),this._analysers.forEach(t=>t.disconnect()),this._split.dispose(),this._gain.dispose(),this}}class sm extends A{constructor(){super(g(sm.getDefaults(),arguments)),this.name="MeterBase",this.input=this.output=this._analyser=new em({context:this.context,size:256,type:"waveform"})}dispose(){return super.dispose(),this._analyser.dispose(),this}}class im extends sm{constructor(){var t=g(im.getDefaults(),arguments,["smoothing"]);super(t),this.name="Meter",this.input=this.output=this._analyser=new em({context:this.context,size:256,type:"waveform",channels:t.channelCount}),this.smoothing=t.smoothing,this.normalRange=t.normalRange,this._rms=new Array(t.channelCount),this._rms.fill(0)}static getDefaults(){return Object.assign(sm.getDefaults(),{smoothing:.8,normalRange:!1,channelCount:1})}getLevel(){return Rp("'getLevel' has been changed to 'getValue'"),this.getValue()}getValue(){const t=this._analyser.getValue(),e=(1===this.channels?[t]:t).map((t,e)=>{var s=t.reduce((t,e)=>t+e*e,0),s=Math.sqrt(s/t.length);return this._rms[e]=Math.max(s,this._rms[e]*this.smoothing),this.normalRange?this._rms[e]:ld(this._rms[e])});return 1===this.channels?e[0]:e}get channels(){return this._analyser.channels}dispose(){return super.dispose(),this._analyser.dispose(),this}}class nm extends sm{constructor(){var t=g(nm.getDefaults(),arguments,["size"]);super(t),this.name="FFT",this.normalRange=t.normalRange,this._analyser.type="fft",this.size=t.size}static getDefaults(){return Object.assign(A.getDefaults(),{normalRange:!1,size:1024,smoothing:.8})}getValue(){return this._analyser.getValue().map(t=>this.normalRange?cd(t):t)}get size(){return this._analyser.size}set size(t){this._analyser.size=t}get smoothing(){return this._analyser.smoothing}set smoothing(t){this._analyser.smoothing=t}getFrequencyOfIndex(t){return l(0<=t&&tt._updateSolo())}get muted(){return 0===this.input.gain.value}_addSolo(){F._soloed.has(this.context)||F._soloed.set(this.context,new Set),F._soloed.get(this.context).add(this)}_removeSolo(){F._soloed.has(this.context)&&F._soloed.get(this.context).delete(this)}_isSoloed(){return F._soloed.has(this.context)&&F._soloed.get(this.context).has(this)}_noSolos(){return!F._soloed.has(this.context)||F._soloed.has(this.context)&&0===F._soloed.get(this.context).size}_updateSolo(){this._isSoloed()||this._noSolos()?this.input.gain.value=1:this.input.gain.value=0}dispose(){return super.dispose(),F._allSolos.get(this.context).delete(this),this._removeSolo(),this}}F._allSolos=new Map,F._soloed=new Map;class am extends A{constructor(){var t=g(am.getDefaults(),arguments,["pan","volume"]);super(t),this.name="PanVol",this._panner=this.input=new y_({context:this.context,pan:t.pan,channelCount:t.channelCount}),this.pan=this._panner.pan,this._volume=this.output=new qd({context:this.context,volume:t.volume}),this.volume=this._volume.volume,this._panner.connect(this._volume),this.mute=t.mute,y(this,["pan","volume"])}static getDefaults(){return Object.assign(A.getDefaults(),{mute:!1,pan:0,volume:0,channelCount:1})}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}dispose(){return super.dispose(),this._panner.dispose(),this.pan.dispose(),this._volume.dispose(),this.volume.dispose(),this}}class hm extends A{constructor(){var t=g(hm.getDefaults(),arguments,["volume","pan"]);super(t),this.name="Channel",this._solo=this.input=new F({solo:t.solo,context:this.context}),this._panVol=this.output=new am({context:this.context,pan:t.pan,volume:t.volume,mute:t.mute,channelCount:t.channelCount}),this.pan=this._panVol.pan,this.volume=this._panVol.volume,this._solo.connect(this._panVol),y(this,["pan","volume"])}static getDefaults(){return Object.assign(A.getDefaults(),{pan:0,volume:0,mute:!1,solo:!1,channelCount:1})}get solo(){return this._solo.solo}set solo(t){this._solo.solo=t}get muted(){return this._solo.muted||this.mute}get mute(){return this._panVol.mute}set mute(t){this._panVol.mute=t}_getBus(t){return hm.buses.has(t)||hm.buses.set(t,new C({context:this.context})),hm.buses.get(t)}send(t,e=0){const s=this._getBus(t),i=new C({context:this.context,units:"decibels",gain:e});return this.connect(i),i.connect(s),i}receive(t){return this._getBus(t).connect(this),this}dispose(){return super.dispose(),this._panVol.dispose(),this.pan.dispose(),this.volume.dispose(),this._solo.dispose(),this}}hm.buses=new Map;class cm extends A{constructor(){super(g(cm.getDefaults(),arguments)),this.name="Mono",this.input=new C({context:this.context}),this._merge=this.output=new O_({channels:2,context:this.context}),this.input.connect(this._merge,0,0),this.input.connect(this._merge,0,1)}dispose(){return super.dispose(),this._merge.dispose(),this.input.dispose(),this}}class lm extends A{constructor(){var t=g(lm.getDefaults(),arguments,["lowFrequency","highFrequency"]);super(t),this.name="MultibandSplit",this.input=new C({context:this.context}),this.output=void 0,this.low=new Nf({context:this.context,frequency:0,type:"lowpass"}),this._lowMidFilter=new Nf({context:this.context,frequency:0,type:"highpass"}),this.mid=new Nf({context:this.context,frequency:0,type:"lowpass"}),this.high=new Nf({context:this.context,frequency:0,type:"highpass"}),this._internalChannels=[this.low,this.mid,this.high],this.lowFrequency=new O({context:this.context,units:"frequency",value:t.lowFrequency}),this.highFrequency=new O({context:this.context,units:"frequency",value:t.highFrequency}),this.Q=new O({context:this.context,units:"positive",value:t.Q}),this.input.fan(this.low,this.high),this.input.chain(this._lowMidFilter,this.mid),this.lowFrequency.fan(this.low.frequency,this._lowMidFilter.frequency),this.highFrequency.fan(this.mid.frequency,this.high.frequency),this.Q.connect(this.low.Q),this.Q.connect(this._lowMidFilter.Q),this.Q.connect(this.mid.Q),this.Q.connect(this.high.Q),y(this,["high","mid","low","highFrequency","lowFrequency"])}static getDefaults(){return Object.assign(A.getDefaults(),{Q:1,highFrequency:2500,lowFrequency:400})}dispose(){return super.dispose(),nd(this,["high","mid","low","highFrequency","lowFrequency"]),this.low.dispose(),this._lowMidFilter.dispose(),this.mid.dispose(),this.high.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this.Q.dispose(),this}}class um extends A{constructor(){var t=g(um.getDefaults(),arguments,["positionX","positionY","positionZ"]);super(t),this.name="Panner3D",this._panner=this.input=this.output=this.context.createPanner(),this.panningModel=t.panningModel,this.maxDistance=t.maxDistance,this.distanceModel=t.distanceModel,this.coneOuterGain=t.coneOuterGain,this.coneOuterAngle=t.coneOuterAngle,this.coneInnerAngle=t.coneInnerAngle,this.refDistance=t.refDistance,this.rolloffFactor=t.rolloffFactor,this.positionX=new k({context:this.context,param:this._panner.positionX,value:t.positionX}),this.positionY=new k({context:this.context,param:this._panner.positionY,value:t.positionY}),this.positionZ=new k({context:this.context,param:this._panner.positionZ,value:t.positionZ}),this.orientationX=new k({context:this.context,param:this._panner.orientationX,value:t.orientationX}),this.orientationY=new k({context:this.context,param:this._panner.orientationY,value:t.orientationY}),this.orientationZ=new k({context:this.context,param:this._panner.orientationZ,value:t.orientationZ})}static getDefaults(){return Object.assign(A.getDefaults(),{coneInnerAngle:360,coneOuterAngle:360,coneOuterGain:0,distanceModel:"inverse",maxDistance:1e4,orientationX:0,orientationY:0,orientationZ:0,panningModel:"equalpower",positionX:0,positionY:0,positionZ:0,refDistance:1,rolloffFactor:1})}setPosition(t,e,s){return this.positionX.value=t,this.positionY.value=e,this.positionZ.value=s,this}setOrientation(t,e,s){return this.orientationX.value=t,this.orientationY.value=e,this.orientationZ.value=s,this}get panningModel(){return this._panner.panningModel}set panningModel(t){this._panner.panningModel=t}get refDistance(){return this._panner.refDistance}set refDistance(t){this._panner.refDistance=t}get rolloffFactor(){return this._panner.rolloffFactor}set rolloffFactor(t){this._panner.rolloffFactor=t}get distanceModel(){return this._panner.distanceModel}set distanceModel(t){this._panner.distanceModel=t}get coneInnerAngle(){return this._panner.coneInnerAngle}set coneInnerAngle(t){this._panner.coneInnerAngle=t}get coneOuterAngle(){return this._panner.coneOuterAngle}set coneOuterAngle(t){this._panner.coneOuterAngle=t}get coneOuterGain(){return this._panner.coneOuterGain}set coneOuterGain(t){this._panner.coneOuterGain=t}get maxDistance(){return this._panner.maxDistance}set maxDistance(t){this._panner.maxDistance=t}dispose(){return super.dispose(),this._panner.disconnect(),this.orientationX.dispose(),this.orientationY.dispose(),this.orientationZ.dispose(),this.positionX.dispose(),this.positionY.dispose(),this.positionZ.dispose(),this}}class pm extends A{constructor(){var t=g(pm.getDefaults(),arguments);super(t),this.name="Recorder",this.input=new C({context:this.context}),l(pm.supported,"Media Recorder API is not available"),this._stream=this.context.createMediaStreamDestination(),this.input.connect(this._stream),this._recorder=new MediaRecorder(this._stream.stream,{mimeType:t.mimeType})}static getDefaults(){return A.getDefaults()}get mimeType(){return this._recorder.mimeType}static get supported(){return null!==qp&&Reflect.has(qp,"MediaRecorder")}get state(){return"inactive"===this._recorder.state?"stopped":"paused"===this._recorder.state?"paused":"started"}start(){return _(this,void 0,void 0,function*(){l("started"!==this.state,"Recorder is already started");var t=new Promise(t=>{const e=()=>{this._recorder.removeEventListener("start",e,!1),t()};this._recorder.addEventListener("start",e,!1)});return this._recorder.start(),yield t})}stop(){return _(this,void 0,void 0,function*(){l("stopped"!==this.state,"Recorder is not started");var t=new Promise(e=>{const s=t=>{this._recorder.removeEventListener("dataavailable",s,!1),e(t.data)};this._recorder.addEventListener("dataavailable",s,!1)});return this._recorder.stop(),yield t})}pause(){return l("started"===this.state,"Recorder must be started"),this._recorder.pause(),this}dispose(){return super.dispose(),this.input.dispose(),this._stream.disconnect(),this}}class dm extends A{constructor(){var t=g(dm.getDefaults(),arguments,["threshold","ratio"]);super(t),this.name="Compressor",this._compressor=this.context.createDynamicsCompressor(),this.input=this._compressor,this.output=this._compressor,this.threshold=new k({minValue:this._compressor.threshold.minValue,maxValue:this._compressor.threshold.maxValue,context:this.context,convert:!1,param:this._compressor.threshold,units:"decibels",value:t.threshold}),this.attack=new k({minValue:this._compressor.attack.minValue,maxValue:this._compressor.attack.maxValue,context:this.context,param:this._compressor.attack,units:"time",value:t.attack}),this.release=new k({minValue:this._compressor.release.minValue,maxValue:this._compressor.release.maxValue,context:this.context,param:this._compressor.release,units:"time",value:t.release}),this.knee=new k({minValue:this._compressor.knee.minValue,maxValue:this._compressor.knee.maxValue,context:this.context,convert:!1,param:this._compressor.knee,units:"decibels",value:t.knee}),this.ratio=new k({minValue:this._compressor.ratio.minValue,maxValue:this._compressor.ratio.maxValue,context:this.context,convert:!1,param:this._compressor.ratio,units:"positive",value:t.ratio}),y(this,["knee","release","attack","ratio","threshold"])}static getDefaults(){return Object.assign(A.getDefaults(),{attack:.003,knee:30,ratio:12,release:.25,threshold:-24})}get reduction(){return this._compressor.reduction}dispose(){return super.dispose(),this._compressor.disconnect(),this.attack.dispose(),this.release.dispose(),this.threshold.dispose(),this.ratio.dispose(),this.knee.dispose(),this}}class fm extends A{constructor(){var t=g(fm.getDefaults(),arguments,["threshold","smoothing"]);super(t),this.name="Gate",this._follower=new w_({context:this.context,smoothing:t.smoothing}),this._gt=new kf({context:this.context,value:cd(t.threshold)}),this.input=new C({context:this.context}),this._gate=this.output=new C({context:this.context}),this.input.connect(this._gate),this.input.chain(this._follower,this._gt,this._gate.gain)}static getDefaults(){return Object.assign(A.getDefaults(),{smoothing:.1,threshold:-40})}get threshold(){return ld(this._gt.value)}set threshold(t){this._gt.value=cd(t)}get smoothing(){return this._follower.smoothing}set smoothing(t){this._follower.smoothing=t}dispose(){return super.dispose(),this.input.dispose(),this._follower.dispose(),this._gt.dispose(),this._gate.dispose(),this}}class _m extends A{constructor(){var t=g(_m.getDefaults(),arguments,["threshold"]);super(t),this.name="Limiter",this._compressor=this.input=this.output=new dm({context:this.context,ratio:20,attack:.003,release:.01,threshold:t.threshold}),this.threshold=this._compressor.threshold,y(this,"threshold")}static getDefaults(){return Object.assign(A.getDefaults(),{threshold:-12})}get reduction(){return this._compressor.reduction}dispose(){return super.dispose(),this._compressor.dispose(),this.threshold.dispose(),this}}class mm extends A{constructor(){var t=g(mm.getDefaults(),arguments);super(t),this.name="MidSideCompressor",this._midSideSplit=this.input=new Y_({context:this.context}),this._midSideMerge=this.output=new H_({context:this.context}),this.mid=new dm(Object.assign(t.mid,{context:this.context})),this.side=new dm(Object.assign(t.side,{context:this.context})),this._midSideSplit.mid.chain(this.mid,this._midSideMerge.mid),this._midSideSplit.side.chain(this.side,this._midSideMerge.side),y(this,["mid","side"])}static getDefaults(){return Object.assign(A.getDefaults(),{mid:{ratio:3,threshold:-24,release:.03,attack:.02,knee:16},side:{ratio:6,threshold:-30,release:.25,attack:.03,knee:10}})}dispose(){return super.dispose(),this.mid.dispose(),this.side.dispose(),this._midSideSplit.dispose(),this._midSideMerge.dispose(),this}}class gm extends A{constructor(){var t=g(gm.getDefaults(),arguments);super(t),this.name="MultibandCompressor",this._splitter=this.input=new lm({context:this.context,lowFrequency:t.lowFrequency,highFrequency:t.highFrequency}),this.lowFrequency=this._splitter.lowFrequency,this.highFrequency=this._splitter.highFrequency,this.output=new C({context:this.context}),this.low=new dm(Object.assign(t.low,{context:this.context})),this.mid=new dm(Object.assign(t.mid,{context:this.context})),this.high=new dm(Object.assign(t.high,{context:this.context})),this._splitter.low.chain(this.low,this.output),this._splitter.mid.chain(this.mid,this.output),this._splitter.high.chain(this.high,this.output),y(this,["high","mid","low","highFrequency","lowFrequency"])}static getDefaults(){return Object.assign(A.getDefaults(),{lowFrequency:250,highFrequency:2e3,low:{ratio:6,threshold:-30,release:.25,attack:.03,knee:10},mid:{ratio:3,threshold:-24,release:.03,attack:.02,knee:16},high:{ratio:3,threshold:-24,release:.03,attack:.02,knee:16}})}dispose(){return super.dispose(),this._splitter.dispose(),this.low.dispose(),this.mid.dispose(),this.high.dispose(),this.output.dispose(),this}}class vm extends A{constructor(){var t=g(vm.getDefaults(),arguments,["low","mid","high"]);super(t),this.name="EQ3",this.output=new C({context:this.context}),this._internalChannels=[],this.input=this._multibandSplit=new lm({context:this.context,highFrequency:t.highFrequency,lowFrequency:t.lowFrequency}),this._lowGain=new C({context:this.context,gain:t.low,units:"decibels"}),this._midGain=new C({context:this.context,gain:t.mid,units:"decibels"}),this._highGain=new C({context:this.context,gain:t.high,units:"decibels"}),this.low=this._lowGain.gain,this.mid=this._midGain.gain,this.high=this._highGain.gain,this.Q=this._multibandSplit.Q,this.lowFrequency=this._multibandSplit.lowFrequency,this.highFrequency=this._multibandSplit.highFrequency,this._multibandSplit.low.chain(this._lowGain,this.output),this._multibandSplit.mid.chain(this._midGain,this.output),this._multibandSplit.high.chain(this._highGain,this.output),y(this,["low","mid","high","lowFrequency","highFrequency"]),this._internalChannels=[this._multibandSplit]}static getDefaults(){return Object.assign(A.getDefaults(),{high:0,highFrequency:2500,low:0,lowFrequency:400,mid:0})}dispose(){return super.dispose(),nd(this,["low","mid","high","lowFrequency","highFrequency"]),this._multibandSplit.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this._lowGain.dispose(),this._midGain.dispose(),this._highGain.dispose(),this.low.dispose(),this.mid.dispose(),this.high.dispose(),this.Q.dispose(),this}}class ym extends A{constructor(){const e=g(ym.getDefaults(),arguments,["url","onload"]);super(e),this.name="Convolver",this._convolver=this.context.createConvolver(),this._buffer=new w(e.url,t=>{this.buffer=t,e.onload()}),this.input=new C({context:this.context}),this.output=new C({context:this.context}),this._buffer.loaded&&(this.buffer=this._buffer),this.normalize=e.normalize,this.input.chain(this._convolver,this.output)}static getDefaults(){return Object.assign(A.getDefaults(),{normalize:!0,onload:x})}load(t){return _(this,void 0,void 0,function*(){this.buffer=yield this._buffer.load(t)})}get buffer(){return this._buffer.length?this._buffer:null}set buffer(t){t&&this._buffer.set(t),this._convolver.buffer&&(this.input.disconnect(),this._convolver.disconnect(),this._convolver=this.context.createConvolver(),this.input.chain(this._convolver,this.output));t=this._buffer.get();this._convolver.buffer=t||null}get normalize(){return this._convolver.normalize}set normalize(t){this._convolver.normalize=t}dispose(){return super.dispose(),this._buffer.dispose(),this._convolver.disconnect(),this}}const xm=b().transport;const wm=b().destination,bm=b().destination;const Tm=b().listener;const Sm=b().draw;const km=b();const Am=w,Cm=Vd,Om=Xd})(),Mm}); \ No newline at end of file diff --git a/js/classes.js b/js/classes.js new file mode 100644 index 0000000..ee7aca2 --- /dev/null +++ b/js/classes.js @@ -0,0 +1,117 @@ +// sounds +class Sounder { + constructor(args) { + this.soundfile = args.soundfile; + this.gain = args.gain; // (dB) + this.latitude = args.location[0]; + this.longitude = args.location[1]; + this.spread = args.spread; // (deg) + this.distmap = args.distmap; + this.volmin = args.volmin; // (dB) + this.ramptime = args.ramptime; // (seconds) + } + + async load() { + //start sound playback + this.pv = new Tone.PanVol(0, -99).toDestination(); + this.snd = await AudioImport(this.soundfile); // NOTE: url with spaces didn't work here. + // this.snd.connect(this.pv).start(); + this.snd.connect(this.pv); + this.snd.loop = true; + } + + update() { + // + //update sound pan/volume + // + // this.ang = getBearing(latitude, longitude, this.latitude, this.longitude); (deg) + this.ang = getBearing(latitude, longitude, this.latitude, this.longitude); // (deg) + this.angerr = (((this.ang - heading + 360) % 360) + 180) % 360 - 180; + this.dist = getDistance(latitude, longitude, this.latitude, this.longitude); // (km) + // + this.distvol = map(this.dist, this.distmap[0], this.distmap[1], this.distmap[2], this.distmap[3], true); //(dB) + + // (from Pure Data patch "iamyou", [eqpan2~]) + // arg #1 (inlet #3): width: + // -width*(1.5) ~ -width/2 -> left fade-in + // -width/2 ~ width/2 -> cross fading + // +width/2 ~ width*(1.5) -> right fade-out + + let panleft_start = this.spread * (-1.5); + let panleft_end = this.spread * (-0.5); + let panright_start = this.spread * (0.5); + let panright_end = this.spread * (1.5); + + //left fade-in + if (this.angerr > panleft_start && this.angerr < panleft_end) { + this.pv.pan.value = -1; //left-full + this.pv.volume.rampTo(this.distvol + this.gain + map(this.angerr, panleft_start, panleft_end, this.volmin, 0), this.ramptime)//cross fading; //(dB) + } else if (this.angerr > panleft_end && this.angerr < panright_start) { + this.pv.pan.value = map(this.angerr, panleft_end, panright_start, -1, 1); // crossfade + this.pv.volume.rampTo(this.distvol + this.gain, this.ramptime)//right fade-out; //(dB) + } else if (this.angerr > panright_start && this.angerr < panright_end) { + this.pv.pan.value = 1; //right-full + this.pv.volume.rampTo(this.distvol + this.gain + map(this.angerr, panright_start, panright_end, 0, this.volmin), this.ramptime)//slience; //(dB) + } else { + this.pv.volume.rampTo(-99, 10); //(dB) + } + } + + draw() { + //draw sound location + } +} + +// +class RadioSounder extends Sounder { + + //do nothing + async load() { + ; + } + + link(audiotag) { + //start sound playback + this.pv = new Tone.PanVol(0, -99).toDestination(); + let stream = Tone.context.createMediaElementSource(audiotag); + this.snd = Tone.context.createGain(); + stream.connect(this.snd); + console.log(stream); + console.log(this.snd); + console.log(this.pv); + // this.snd.connect(this.pv.input.input); a hack ... + this.snd.gain.value = 1; + this.snd.connect(Tone.context.destination); + } +} + +//p5 +class Compass { + constructor(size, colors) { + this.size = size; + this.colors = colors; + this.heading = 0; + } + + draw() { + push(); + // + scale(this.size); + // + translate(0.5, 0.5); + // + noStroke(); + // + fill(this.colors[0]); + circle(0, 0, 0.9); + // + fill(this.colors[1]); + rotate(this.heading); + quad(0.1, 0.2, 0, -0.4, -0.1, 0.2, 0, 0.1); + // + fill(this.colors[2]); + circle(0, 0, 0.05); + // + pop(); + } +} diff --git a/js/hls.min.js b/js/hls.min.js new file mode 100644 index 0000000..37713e1 --- /dev/null +++ b/js/hls.min.js @@ -0,0 +1,4 @@ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.Hls=e()}}(function(){return function s(e,t,r){function n(a,d){if(!t[a]){if(!e[a]){var l="function"==typeof require&&require;if(!d&&l)return l(a,!0);if(i)return i(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var o=t[a]={exports:{}};e[a][0].call(o.exports,function(t){var r=e[a][1][t];return n(r?r:t)},o,o.exports,s,e,t,r)}return t[a].exports}for(var i="function"==typeof require&&require,a=0;ae||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},e.prototype.emit=function(l){var s,e,u,a,i,o;if(this._events||(this._events={}),"error"===l&&(!this._events.error||r(this._events.error)&&!this._events.error.length)){if(s=arguments[1],s instanceof Error)throw s;throw TypeError('Uncaught, unspecified "error" event.')}if(e=this._events[l],n(e))return!1;if(t(e))switch(arguments.length){case 1:e.call(this);break;case 2:e.call(this,arguments[1]);break;case 3:e.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),e.apply(this,a)}else if(r(e))for(a=Array.prototype.slice.call(arguments,1),o=e.slice(),u=o.length,i=0;u>i;i++)o[i].apply(this,a);return!0},e.prototype.addListener=function(a,i){var s;if(!t(i))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",a,t(i.listener)?i.listener:i),this._events[a]?r(this._events[a])?this._events[a].push(i):this._events[a]=[this._events[a],i]:this._events[a]=i,r(this._events[a])&&!this._events[a].warned&&(s=n(this._maxListeners)?e.defaultMaxListeners:this._maxListeners,s&&s>0&&this._events[a].length>s&&(this._events[a].warned=!0,"function"==typeof console.trace)),this},e.prototype.on=e.prototype.addListener,e.prototype.once=function(n,e){function r(){this.removeListener(n,r),a||(a=!0,e.apply(this,arguments))}if(!t(e))throw TypeError("listener must be a function");var a=!1;return r.listener=e,this.on(n,r),this},e.prototype.removeListener=function(a,n){var e,s,o,i;if(!t(n))throw TypeError("listener must be a function");if(!this._events||!this._events[a])return this;if(e=this._events[a],o=e.length,s=-1,e===n||t(e.listener)&&e.listener===n)delete this._events[a],this._events.removeListener&&this.emit("removeListener",a,n);else if(r(e)){for(i=o;i-- >0;)if(e[i]===n||e[i].listener&&e[i].listener===n){s=i;break}if(0>s)return this;1===e.length?(e.length=0,delete this._events[a]):e.splice(s,1),this._events.removeListener&&this.emit("removeListener",a,n)}return this},e.prototype.removeAllListeners=function(r){var n,e;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[r]&&delete this._events[r],this;if(0===arguments.length){for(n in this._events)"removeListener"!==n&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events={},this}if(e=this._events[r],t(e))this.removeListener(r,e);else if(e)for(;e.length;)this.removeListener(r,e[e.length-1]);return delete this._events[r],this},e.prototype.listeners=function(e){var r;return r=this._events&&this._events[e]?t(this._events[e])?[this._events[e]]:this._events[e].slice():[]},e.prototype.listenerCount=function(r){if(this._events){var e=this._events[r];if(t(e))return 1;if(e)return e.length}return 0},e.listenerCount=function(e,t){return e.listenerCount(t)}},{}],2:[function(i,n,s){var a=arguments[3],e=arguments[4],r=arguments[5],t=JSON.stringify;n.exports=function(l){for(var n,s=Object.keys(r),i=0,d=s.length;d>i;i++){var o=s[i],u=r[o].exports;if(u===l||u.default===l){n=o;break}}if(!n){n=Math.floor(Math.pow(16,8)*Math.random()).toString(16);for(var f={},i=0,d=s.length;d>i;i++){var o=s[i];f[o]=o}e[n]=[Function(["require","module","exports"],"("+l+")(self)"),f]}var h=Math.floor(Math.pow(16,8)*Math.random()).toString(16),c={};c[n]=n,e[h]=[Function(["require"],"var f = require("+t(n)+");(f.default ? f.default : f)(self);"),c];var g="("+a+")({"+Object.keys(e).map(function(r){return t(r)+":["+e[r][0]+","+t(e[r][1])+"]"}).join(",")+"},{},["+t(h)+"])",v=window.URL||window.webkitURL||window.mozURL||window.msURL;return new Worker(v.createObjectURL(new Blob([g],{type:"text/javascript"})))}},{}],3:[function(e,h,t){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function f(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var o=function(){function e(n,r){for(var t=0;t=e;e++)if(r=e<=this.lastfetchlevel?.8*n:.7*n,ri.config.appendErrorMaxRetry)return t.logger.log("fail "+i.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),a=[],n.fatal=!0,void i.trigger(e.default.ERROR,n);n.fatal=!1,i.trigger(e.default.ERROR,n)}else a=[],n.details=r.ErrorDetails.BUFFER_FULL_ERROR,i.trigger(e.default.ERROR,n)}}}}},{key:"flushBuffer",value:function(l,s){var e,r,o,i,n,a;if(this.flushBufferCounter.5)return this.flushBufferCounter++,t.logger.log("flush "+u+" ["+n+","+a+"], of ["+o+","+i+"], pos:"+this.media.currentTime),e.remove(n,a),!1}else t.logger.warn("abort flushing too many retries");return t.logger.log("buffer flushed"),!0}}]),n}(s.default);a.default=o},{"../errors":19,"../event-handler":20,"../events":21,"../utils/logger":34}],5:[function(n,g,a){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function h(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var c=function(){function e(n,r){for(var t=0;t=0&&n1&&setTimeout(this.tick,1),this.ticks=0)}},{key:"doTick",value:function(){var c,l,i,D=this,u=this.hls,s=u.config;switch(this.state){case e.ERROR:case e.PAUSED:break;case e.STARTING:this.startLevel=u.startLevel,-1===this.startLevel&&(this.startLevel=0,this.fragBitrateTest=!0),this.level=u.nextLoadLevel=this.startLevel,this.state=e.WAITING_LEVEL,this.loadedmetadata=!1;break;case e.IDLE:if(!this.media&&(this.startFragRequested||!s.startFragPrefetch))break;c=this.loadedmetadata?this.media.currentTime:this.nextLoadPosition,l=this.startFragRequested===!1?this.startLevel:u.nextLoadLevel;var g,k=this.bufferInfo(c,s.maxBufferHole),C=k.len,h=k.end,y=this.fragPrevious;if(this.levels[l].hasOwnProperty("bitrate")?(g=Math.max(8*s.maxBufferSize/this.levels[l].bitrate,s.maxBufferLength),g=Math.min(g,s.maxMaxBufferLength)):g=s.maxBufferLength,g>C){if(u.nextLoadLevel=l,this.level=l,i=this.levels[l].details,"undefined"==typeof i||i.live&&this.levelLastLoaded!==l){this.state=e.WAITING_LEVEL;break}var d=i.fragments,v=d.length,m=d[0].start,_=d[v-1].start+d[v-1].duration,a=void 0;if(i.live){var N=void 0!==s.liveMaxLatencyDuration?s.liveMaxLatencyDuration:s.liveMaxLatencyDurationCount*i.targetduration;if(h=i.startSN&&R<=i.endSN&&(a=d[R-i.startSN],t.logger.log("live playlist, switching playlist, load frag with next SN: "+a.sn))}a||(a=d[Math.min(v-1,Math.round(v/2))],t.logger.log("live playlist, switching playlist, unknown, load middle frag : "+a.sn))}}else m>h&&(a=d[0]);if(a||!function(){var n=void 0,o=s.maxFragLookUpTolerance;_>h?(h>_-o&&(o=0),n=p.default.search(d,function(e){return e.start+e.duration-o<=h?1:e.start-o>h?-1:0})):n=d[v-1],n&&(a=n,m=n.start,y&&a.level===y.level&&a.sn===y.sn&&(a.sn1&&(a.expectedLen=Math.round(a.duration*this.levels[l].bitrate/8),a.trequest=performance.now()),void 0!==this.fragLoadIdx?this.fragLoadIdx++:this.fragLoadIdx=0,a.loadCounter){a.loadCounter++;var T=s.fragLoadingLoopThreshold;if(a.loadCounter>T&&Math.abs(this.fragLoadIdx-a.loadIdx)1){var w=performance.now()-o.trequest;if(w>500*o.duration){var P=Math.max(1,1e3*o.loaded/w);o.expectedLenE){var b=void 0,f=void 0;for(f=this.level-1;f>=0&&(b=o.duration*this.levels[f].bitrate/(6.4*P),t.logger.log("fragLoadedDelay/bufferStarvationDelay/fragLevelNextLoadedDelay["+f+"] :"+L.toFixed(1)+"/"+E.toFixed(1)+"/"+b.toFixed(1)),!(E>b));f--);L>b&&(f=Math.max(0,f),u.nextLoadLevel=f,t.logger.warn("loading too slow, abort fragment loading and switch to level "+f),o.loader.abort(),u.trigger(r.default.FRAG_LOAD_EMERGENCY_ABORTED,{frag:o}),this.state=e.IDLE)}}}break;case e.FRAG_LOADING_WAITING_RETRY:var I=performance.now(),O=this.retryDate,S=this.media,x=S&&S.seeking;(!O||I>=O||x)&&(t.logger.log("mediaController: retryDate reached, switch back to IDLE state"),this.state=e.IDLE);break;case e.PARSING:break;case e.PARSED:break;case e.ENDED:}this._checkBuffer(),this._checkFragmentChanged()}},{key:"bufferInfo",value:function(a,i){var r=this.media;if(r){var e,t=r.buffered,n=[];for(e=0;ed&&(t[u-1].end=r[e].end):t.push(r[e])}else t.push(r[e])}for(e=0,o=0,l=a=n;e=i&&f>n)l=i,a=f,o=a-n;else if(i>n+s){h=i;break}}return{len:o,start:l,end:a,nextStart:h}}},{key:"getBufferRange",value:function(n){var e,t,r=this.bufferRange;if(r)for(e=r.length-1;e>=0;e--)if(t=r[e],n>=t.start&&n<=t.end)return t;return null}},{key:"followingBufferRange",value:function(e){return e?this.getBufferRange(e.end+.5):null}},{key:"isBuffered",value:function(r){for(var n=this.media,t=n.buffered,e=0;e=t.start(e)&&r<=t.end(e))return!0;return!1}},{key:"_checkFragmentChanged",value:function(){var t,e,n=this.media;if(n&&n.seeking===!1&&(e=n.currentTime,e>n.playbackRate*this.lastCurrentTime&&(this.lastCurrentTime=e),this.isBuffered(e)?t=this.getBufferRange(e):this.isBuffered(e+.1)&&(t=this.getBufferRange(e+.1)),t)){var a=t.frag;a!==this.fragPlaying&&(this.fragPlaying=a,this.hls.trigger(r.default.FRAG_CHANGED,{frag:a}))}}},{key:"immediateLevelSwitch",value:function(){t.logger.log("immediateLevelSwitch"),this.immediateSwitch||(this.immediateSwitch=!0,this.previouslyPaused=this.media.paused,this.media.pause());var n=this.fragCurrent;n&&n.loader&&n.loader.abort(),this.fragCurrent=null,this.hls.trigger(r.default.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY}),this.state=e.PAUSED,this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold,this.tick()}},{key:"immediateLevelSwitchEnd",value:function(){this.immediateSwitch=!1,this.media.currentTime-=1e-4,this.previouslyPaused||this.media.play()}},{key:"nextLevelSwitch",value:function(){var a,n,t;if(n=this.getBufferRange(this.media.currentTime),n&&n.start>1&&(this.hls.trigger(r.default.BUFFER_FLUSHING,{startOffset:0,endOffset:n.start-1}),this.state=e.PAUSED),this.media.paused)a=0;else{var o=this.hls.nextLoadLevel,l=this.levels[o],s=this.fragLastKbps;a=s&&this.fragCurrent?this.fragCurrent.duration*l.bitrate/(1e3*s)+1:0}if(t=this.getBufferRange(this.media.currentTime+a),t&&(t=this.followingBufferRange(t))){this.hls.trigger(r.default.BUFFER_FLUSHING,{startOffset:t.start,endOffset:Number.POSITIVE_INFINITY}),this.state=e.PAUSED;var i=this.fragCurrent;i&&i.loader&&i.loader.abort(),this.fragCurrent=null,this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold}}},{key:"onMediaAttached",value:function(t){var e=this.media=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),this.onvended=this.onMediaEnded.bind(this),e.addEventListener("seeking",this.onvseeking),e.addEventListener("seeked",this.onvseeked),e.addEventListener("ended",this.onvended),this.levels&&this.config.autoStartLoad&&this.startLoad()}},{key:"onMediaDetaching",value:function(){var e=this.media;e&&e.ended&&(t.logger.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0);var r=this.levels;r&&r.forEach(function(e){e.details&&e.details.fragments.forEach(function(e){e.loadCounter=void 0})}),e&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("seeked",this.onvseeked),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvseeked=this.onvended=null),this.media=null,this.loadedmetadata=!1,this.stopLoad()}},{key:"onMediaSeeking",value:function(){if(this.state===e.FRAG_LOADING){if(0===this.bufferInfo(this.media.currentTime,this.config.maxBufferHole).len){t.logger.log("seeking outside of buffer while fragment load in progress, cancel fragment load");var r=this.fragCurrent;r&&(r.loader&&r.loader.abort(),this.fragCurrent=null),this.fragPrevious=null,this.state=e.IDLE}}else this.state===e.ENDED&&(this.state=e.IDLE);this.media&&(this.lastCurrentTime=this.media.currentTime),void 0!==this.fragLoadIdx&&(this.fragLoadIdx+=2*this.config.fragLoadingLoopThreshold),this.tick()}},{key:"onMediaSeeked",value:function(){this.tick()}},{key:"onMediaEnded",value:function(){t.logger.log("media ended"),this.startPosition=this.lastCurrentTime=0}},{key:"onManifestLoading",value:function(){t.logger.log("trigger BUFFER_RESET"),this.hls.trigger(r.default.BUFFER_RESET),this.bufferRange=[],this.stalled=!1}},{key:"onManifestParsed",value:function(r){var e,n=!1,a=!1;r.levels.forEach(function(t){e=t.audioCodec,e&&(-1!==e.indexOf("mp4a.40.2")&&(n=!0),-1!==e.indexOf("mp4a.40.5")&&(a=!0))}),this.audioCodecSwitch=n&&a,this.audioCodecSwitch&&t.logger.log("both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"), +this.levels=r.levels,this.startLevelLoaded=!1,this.startFragRequested=!1,this.config.autoStartLoad&&this.startLoad()}},{key:"onLevelLoaded",value:function(s){var n=s.details,a=s.level,o=this.levels[a],u=n.totalduration,i=0;if(t.logger.log("level "+a+" loaded ["+n.startSN+","+n.endSN+"],duration:"+u),this.levelLastLoaded=a,n.live){var d=o.details;d?(l.default.mergeDetails(d,n),i=n.fragments[0].start,n.PTSKnown?t.logger.log("live playlist sliding:"+i.toFixed(3)):t.logger.log("live playlist - outdated PTS, unknown sliding")):(n.PTSKnown=!1,t.logger.log("live playlist - first load, unknown sliding"))}else n.PTSKnown=!1;if(o.details=n,this.hls.trigger(r.default.LEVEL_UPDATED,{details:n,level:a}),this.startFragRequested===!1){if(n.live){var f=void 0!==this.config.liveSyncDuration?this.config.liveSyncDuration:this.config.liveSyncDurationCount*n.targetduration;this.startPosition=Math.max(0,i+u-f)}this.nextLoadPosition=this.startPosition}this.state===e.WAITING_LEVEL&&(this.state=e.IDLE),this.tick()}},{key:"onKeyLoaded",value:function(){this.state===e.KEY_LOADING&&(this.state=e.IDLE,this.tick())}},{key:"onFragLoaded",value:function(a){var n=this.fragCurrent;if(this.state===e.FRAG_LOADING&&n&&a.frag.level===n.level&&a.frag.sn===n.sn)if(this.fragBitrateTest===!0)this.state=e.IDLE,this.fragBitrateTest=!1,a.stats.tparsed=a.stats.tbuffered=performance.now(),this.hls.trigger(r.default.FRAG_BUFFERED,{stats:a.stats,frag:n});else{this.state=e.PARSING,this.stats=a.stats;var s=this.levels[this.level],o=s.details,d=o.totalduration,f=n.start,l=n.level,u=n.sn,i=s.audioCodec||this.config.defaultAudioCodec;this.audioCodecSwap&&(t.logger.log("swapping playlist audio codec"),void 0===i&&(i=this.lastAudioCodec),i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5")),this.pendingAppending=0,t.logger.log("Demuxing "+u+" of ["+o.startSN+" ,"+o.endSN+"],level "+l),this.demuxer.push(a.payload,i,s.videoCodec,f,n.cc,l,u,d,n.decryptdata)}this.fragLoadError=0}},{key:"onFragParsingInitSegment",value:function(l){if(this.state===e.PARSING){var o,n,a=l.tracks;if(n=a.audio){var i=this.levels[this.level].audioCodec,u=navigator.userAgent.toLowerCase();i&&this.audioCodecSwap&&(t.logger.log("swapping playlist audio codec"),i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),this.audioCodecSwitch&&1!==n.metadata.channelCount&&-1===u.indexOf("firefox")&&(i="mp4a.40.5"),-1!==u.indexOf("android")&&(i="mp4a.40.2",t.logger.log("Android: force audio codec to"+i)),n.levelCodec=i}if(n=a.video,n&&(n.levelCodec=this.levels[this.level].videoCodec),l.unique){var s={codec:"",levelCodec:""};for(o in l.tracks)n=a[o],s.container=n.container,s.codec&&(s.codec+=",",s.levelCodec+=","),n.codec&&(s.codec+=n.codec),n.levelCodec&&(s.levelCodec+=n.levelCodec);a={audiovideo:s}}this.hls.trigger(r.default.BUFFER_CODECS,a);for(o in a){n=a[o],t.logger.log("track:"+o+",container:"+n.container+",codecs[level/parsed]=["+n.levelCodec+"/"+n.codec+"]");var d=n.initSegment;d&&(this.pendingAppending++,this.hls.trigger(r.default.BUFFER_APPENDING,{type:o,data:d}))}this.tick()}}},{key:"onFragParsingData",value:function(n){var o=this;if(this.state===e.PARSING){this.tparse2=Date.now();var a=this.levels[this.level],i=this.fragCurrent;t.logger.log("parsed "+n.type+",PTS:["+n.startPTS.toFixed(3)+","+n.endPTS.toFixed(3)+"],DTS:["+n.startDTS.toFixed(3)+"/"+n.endDTS.toFixed(3)+"],nb:"+n.nb);var u=l.default.updateFragPTS(a.details,i.sn,n.startPTS,n.endPTS),s=this.hls;s.trigger(r.default.LEVEL_PTS_UPDATED,{details:a.details,level:this.level,drift:u}),[n.data1,n.data2].forEach(function(e){e&&(o.pendingAppending++,s.trigger(r.default.BUFFER_APPENDING,{type:n.type,data:e}))}),this.nextLoadPosition=n.endPTS,this.bufferRange.push({type:n.type,start:n.startPTS,end:n.endPTS,frag:i}),this.tick()}else t.logger.warn("not in PARSING state but "+this.state+", ignoring FRAG_PARSING_DATA event")}},{key:"onFragParsed",value:function(){this.state===e.PARSING&&(this.stats.tparsed=performance.now(),this.state=e.PARSED,this._checkAppendedParsed())}},{key:"onBufferAppended",value:function(){switch(this.state){case e.PARSING:case e.PARSED:this.pendingAppending--,this._checkAppendedParsed()}}},{key:"_checkAppendedParsed",value:function(){if(this.state===e.PARSED&&0===this.pendingAppending){var a=this.fragCurrent,n=this.stats;a&&(this.fragPrevious=a,n.tbuffered=performance.now(),this.fragLastKbps=Math.round(8*n.length/(n.tbuffered-n.tfirst)),this.hls.trigger(r.default.FRAG_BUFFERED,{stats:n,frag:a}),t.logger.log("media buffered : "+this.timeRangesToString(this.media.buffered)),this.state=e.IDLE),this.tick()}}},{key:"onError",value:function(a){switch(a.details){case n.ErrorDetails.FRAG_LOAD_ERROR:case n.ErrorDetails.FRAG_LOAD_TIMEOUT:if(!a.fatal){var i=this.fragLoadError;if(i?i++:i=1,i<=this.config.fragLoadingMaxRetry){this.fragLoadError=i,a.frag.loadCounter=0;var s=Math.min(Math.pow(2,i-1)*this.config.fragLoadingRetryDelay,64e3);t.logger.warn("mediaController: frag loading failed, retry in "+s+" ms"),this.retryDate=performance.now()+s,this.state=e.FRAG_LOADING_WAITING_RETRY}else t.logger.error("mediaController: "+a.details+" reaches max retry, redispatch as fatal ..."),a.fatal=!0,this.hls.trigger(r.default.ERROR,a),this.state=e.ERROR}break;case n.ErrorDetails.FRAG_LOOP_LOADING_ERROR:case n.ErrorDetails.LEVEL_LOAD_ERROR:case n.ErrorDetails.LEVEL_LOAD_TIMEOUT:case n.ErrorDetails.KEY_LOAD_ERROR:case n.ErrorDetails.KEY_LOAD_TIMEOUT:t.logger.warn("mediaController: "+a.details+" while loading frag,switch to "+(a.fatal?"ERROR":"IDLE")+" state ..."),this.state=a.fatal?e.ERROR:e.IDLE;break;case n.ErrorDetails.BUFFER_FULL_ERROR:this.config.maxMaxBufferLength/=2,t.logger.warn("reduce max buffer length to "+this.config.maxMaxBufferLength+"s and trigger a nextLevelSwitch to flush old buffer and fix QuotaExceededError"),this.nextLevelSwitch()}}},{key:"_checkBuffer",value:function(){var e=this.media;if(e){var d=e.readyState;if(d){var a,i,o=this.seekAfterBuffered;if(o)e.duration>=o&&(a=o,this.seekAfterBuffered=void 0);else{i=e.currentTime;var g=this.loadedmetadata;!g&&e.buffered.length&&(this.loadedmetadata=!0,i||i===this.startPosition||(a=this.startPosition))}a&&(i=a,t.logger.log("target seek position:"+a));var l=this.bufferInfo(i,0),c=!(e.paused||e.ended||e.seeking||2>d),u=.4,f=i>e.playbackRate*this.lastCurrentTime;if(this.stalled&&f&&(this.stalled=!1,t.logger.log("playback not stuck anymore @"+i)),l.len<=u){if(f||!c?u=0:this.stalled||(t.logger.log("playback seems stuck @"+i),this.hls.trigger(r.default.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1}),this.stalled=!0),l.len<=u){var s=l.nextStart,h=s-i;s&&h0&&!e.seeking&&(t.logger.log("adjust currentTime from "+e.currentTime+" to next buffered @ "+s),e.currentTime=s,this.hls.trigger(r.default.ERROR,{type:n.ErrorTypes.MEDIA_ERROR,details:n.ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1}))}}else a&&e.currentTime!==a&&(t.logger.log("adjust currentTime from "+e.currentTime+" to "+a),e.currentTime=a)}}}},{key:"onBufferFlushed",value:function(){var t,r,n=[];for(r=0;re;e++)r+="["+t.start(e)+","+t.end(e)+"]";return r}},{key:"currentLevel",get:function(){if(this.media){var e=this.getBufferRange(this.media.currentTime);if(e)return e.frag.level}return-1}},{key:"nextBufferRange",get:function(){return this.media?this.followingBufferRange(this.getBufferRange(this.media.currentTime)):null}},{key:"nextLevel",get:function(){var e=this.nextBufferRange;return e?e.frag.level:-1}}]),a}(s.default);o.default=b},{"../demux/demuxer":15,"../errors":19,"../event-handler":20,"../events":21,"../helper/level-helper":22,"../utils/binary-search":32,"../utils/logger":34}],7:[function(t,g,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function f(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var c=function(){function e(n,r){for(var t=0;te;e++)c[(a[e]=e<<1^283*(e>>7))^e]=e;for(n=r=0;!h[n];n^=u||1,r=c[r]||1)for(t=r^r<<1^r<<2^r<<3^r<<4,t=t>>8^255&t^99,h[n]=t,g[t]=n,d=a[f=a[u=a[n]]],l=16843009*d^65537*f^257*u^16843008*n,s=257*a[t]^16843008*t,e=0;4>e;e++)i[e][n]=s=s<<24^s>>>8,o[e][t]=l=l<<24^l>>>8;for(e=0;5>e;e++)i[e]=i[e].slice(0),o[e]=o[e].slice(0)}},{key:"decrypt",value:function(R,p,_,b,E,m){var h,v,g,i,e=this._key[1],t=R^e[0],n=b^e[1],a=_^e[2],r=p^e[3],y=e.length/4-2,s=4,o=this._tables[1],f=o[0],d=o[1],u=o[2],l=o[3],c=o[4];for(i=0;y>i;i++)h=f[t>>>24]^d[n>>16&255]^u[a>>8&255]^l[255&r]^e[s],v=f[n>>>24]^d[a>>16&255]^u[r>>8&255]^l[255&t]^e[s+1],g=f[a>>>24]^d[r>>16&255]^u[t>>8&255]^l[255&n]^e[s+2],r=f[r>>>24]^d[t>>16&255]^u[n>>8&255]^l[255&a]^e[s+3],s+=4,t=h,n=v,a=g;for(i=0;4>i;i++)E[(3&-i)+m]=c[t>>>24]<<24^c[n>>16&255]<<16^c[a>>8&255]<<8^c[255&r]^e[s++],h=t,t=n,n=a,a=r,r=h}}]),e}();e.default=n},{}],9:[function(t,l,e){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var a=function(){function e(n,r){for(var t=0;t>8|e>>>24}},{key:"doDecrypt",value:function(n,v,a){var u,h,o,f,l,c,d,i,e,r=new Int32Array(n.buffer,n.byteOffset,n.byteLength>>2),p=new s.default(Array.prototype.slice.call(v)),g=new Uint8Array(n.byteLength),t=new Int32Array(g.buffer);for(u=~~a[0],h=~~a[1],o=~~a[2],f=~~a[3],e=0;ee&&(255!==t[e]||240!==(240&t[e+1]));e++);for(r.audiosamplerate||(a=o.default.getAudioConfig(this.observer,t,e,p),r.config=a.config,r.audiosamplerate=a.samplerate,r.channelCount=a.channelCount,r.codec=a.codec,r.timescale=a.samplerate,r.duration=a.samplerate*y,l.logger.log("parsed codec:"+r.codec+",rate:"+a.samplerate+",nb channel:"+a.channelCount)),c=0,v=9216e4/r.audiosamplerate;u>e+5&&(s=1&t[e+1]?7:9,i=(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5,i-=s,i>0&&u>=e+s+i);)for(f=h+c*v,g={unit:t.subarray(e+s,e+s+i),pts:f,dts:f},r.samples.push(g),r.len+=i,e+=i+s,c++;u-1>e&&(255!==t[e]||240!==(240&t[e+1]));e++);this.remuxer.remux(this._aacTrack,{samples:[]},{samples:[{pts:h,dts:h,unit:d.payload}]},{samples:[]},m)}},{key:"destroy",value:function(){}}],[{key:"probe",value:function(t){var e,r,a=new n.default(t);if(a.hasTimeStamp)for(e=a.length,r=t.length;r-1>e;e++)if(255===t[e]&&240===(240&t[e+1]))return!0;return!1}}]),e}();t.default=s},{"../demux/id3":17,"../utils/logger":34,"./adts":12}],12:[function(e,o,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var a=function(){function e(n,r){for(var t=0;t>>6)+1,e=(60&u[l+2])>>>2,e>d.length-1?void h.trigger(Event.ERROR,{type:r.ErrorTypes.MEDIA_ERROR,details:r.ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+e}):(o=(1&u[l+2])<<2,o|=(192&u[l+3])>>>6,i.logger.log("manifest codec:"+a+",ADTS data:type:"+n+",sampleingIndex:"+e+"["+d[e]+"Hz],channelConfig:"+o),-1!==f.indexOf("firefox")?e>=6?(n=5,t=new Array(4),s=e-3):(n=2,t=new Array(2),s=e):-1!==f.indexOf("android")?(n=2,t=new Array(2),s=e):(n=5,t=new Array(4),a&&(-1!==a.indexOf("mp4a.40.29")||-1!==a.indexOf("mp4a.40.5"))||!a&&e>=6?s=e-3:((a&&-1!==a.indexOf("mp4a.40.2")&&e>=6&&1===o||!a&&1===o)&&(n=2,t=new Array(2)),s=e)),t[0]=n<<3,t[0]|=(14&e)>>1,t[1]|=(1&e)<<7,t[1]|=o<<3,5===n&&(t[1]|=(14&s)>>1,t[2]=(1&s)<<7,t[2]|=8,t[3]=0),{config:t,samplerate:d[e],channelCount:o,codec:"mp4a.40."+n})}}]),e}();t.default=s},{"../errors":19,"../utils/logger":34}],13:[function(e,y,n){"use strict";function t(e){return e&&e.__esModule?e:{default:e}}function d(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var h=function(){function e(n,r){for(var t=0;t1?r-1:0),e=1;r>e;e++)a[e-1]=arguments[e];t.emit.apply(t,[n,n].concat(a))},t.off=function(a){for(var r=arguments.length,n=Array(r>1?r-1:0),e=1;r>e;e++)n[e-1]=arguments[e];t.removeListener.apply(t,[a].concat(n))},r.addEventListener("message",function(n){var e=n.data;switch(e.cmd){case"init":r.demuxer=new u.default(t,e.typeSupported);break;case"demux":r.demuxer.push(new Uint8Array(e.data),e.audioCodec,e.videoCodec,e.timeOffset,e.cc,e.level,e.sn,e.duration)}}),t.on(e.default.FRAG_PARSING_INIT_SEGMENT,function(t,e){r.postMessage({event:t,tracks:e.tracks,unique:e.unique})}),t.on(e.default.FRAG_PARSING_DATA,function(n,e){var t={event:n,type:e.type,startPTS:e.startPTS,endPTS:e.endPTS,startDTS:e.startDTS,endDTS:e.endDTS,data1:e.data1.buffer,data2:e.data2.buffer,nb:e.nb};r.postMessage(t,[t.data1,t.data2])}),t.on(e.default.FRAG_PARSED,function(e){r.postMessage({event:e})}),t.on(e.default.ERROR,function(e,t){r.postMessage({event:e,data:t})}),t.on(e.default.FRAG_PARSING_METADATA,function(e,t){var n={event:e,samples:t.samples};r.postMessage(n)}),t.on(e.default.FRAG_PARSING_USERDATA,function(e,t){var n={event:e,samples:t.samples};r.postMessage(n)})};n.default=o},{"../demux/demuxer-inline":13,"../events":21,events:1}],15:[function(t,v,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var h=function(){function e(n,r){for(var t=0;t0&&null!=e&&null!=e.key&&"AES-128"===e.method){null==this.decrypter&&(this.decrypter=new l.default(this.hls));var d=this;this.decrypter.decrypt(t,e.key,e.iv,function(e){d.pushDecrypted(e,r,n,a,i,s,o,u)})}else this.pushDecrypted(t,r,n,a,i,s,o,u)}},{key:"onWorkerMessage",value:function(n){var t=n.data;switch(t.event){case e.default.FRAG_PARSING_INIT_SEGMENT:var r={};r.tracks=t.tracks,r.unique=t.unique,this.hls.trigger(e.default.FRAG_PARSING_INIT_SEGMENT,r);break;case e.default.FRAG_PARSING_DATA:this.hls.trigger(e.default.FRAG_PARSING_DATA,{data1:new Uint8Array(t.data1),data2:new Uint8Array(t.data2),startPTS:t.startPTS,endPTS:t.endPTS,startDTS:t.startDTS,endDTS:t.endDTS,type:t.type,nb:t.nb});break;case e.default.FRAG_PARSING_METADATA:this.hls.trigger(e.default.FRAG_PARSING_METADATA,{samples:t.samples});break;case e.default.FRAG_PARSING_USERDATA:this.hls.trigger(e.default.FRAG_PARSING_USERDATA,{samples:t.samples});break;default:this.hls.trigger(t.event,t.data)}}}]),r}();n.default=o},{"../crypt/decrypter":10,"../demux/demuxer-inline":13,"../demux/demuxer-worker":14,"../events":21,"../utils/logger":34,webworkify:2}],16:[function(t,s,e){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var n=function(){function e(n,r){for(var t=0;te?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t>>3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}},{key:"readBits",value:function(t){var e=Math.min(this.bitsAvailable,t),r=this.word>>>32-e;return t>32&&a.logger.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0?this.word<<=e:this.bytesAvailable>0&&this.loadWord(),e=t-e,e>0?r<>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}},{key:"skipUEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"skipEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"readUEG",value:function(){var e=this.skipLZ();return this.readBits(e+1)-1}},{key:"readEG",value:function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}},{key:"readBoolean",value:function(){return 1===this.readBits(1)}},{key:"readUByte",value:function(){return this.readBits(8)}},{key:"readUShort",value:function(){return this.readBits(16)}},{key:"readUInt",value:function(){return this.readBits(32)}},{key:"skipScalingList",value:function(a){var t,n,r=8,e=8;for(t=0;a>t;t++)0!==e&&(n=this.readEG(),e=(r+n+256)%256),r=0===e?r:e}},{key:"readSPS",value:function(){var t,v,p,l,a,i,n,o,r,s=0,d=0,f=0,h=0,c=1;if(this.readUByte(),t=this.readUByte(),v=this.readBits(5),this.skipBits(3),p=this.readUByte(),this.skipUEG(),100===t||110===t||122===t||244===t||44===t||83===t||86===t||118===t||128===t){var g=this.readUEG();if(3===g&&this.skipBits(1),this.skipUEG(),this.skipUEG(),this.skipBits(1),this.readBoolean())for(o=3!==g?8:12,r=0;o>r;r++)this.readBoolean()&&(6>r?this.skipScalingList(16):this.skipScalingList(64))}this.skipUEG();var u=this.readUEG();if(0===u)this.readUEG();else if(1===u)for(this.skipBits(1),this.skipEG(),this.skipEG(),l=this.readUEG(),r=0;l>r;r++)this.skipEG();if(this.skipUEG(),this.skipBits(1),a=this.readUEG(),i=this.readUEG(),n=this.readBits(1),0===n&&this.skipBits(1),this.skipBits(1),this.readBoolean()&&(s=this.readUEG(),d=this.readUEG(),f=this.readUEG(),h=this.readUEG()),this.readBoolean()&&this.readBoolean()){var e=void 0,y=this.readUByte();switch(y){case 1:e=[1,1];break;case 2:e=[12,11];break;case 3:e=[10,11];break;case 4:e=[16,11];break;case 5:e=[40,33];break;case 6:e=[24,11];break;case 7:e=[20,11];break;case 8:e=[32,11];break;case 9:e=[80,33];break;case 10:e=[18,11];break;case 11:e=[15,11];break;case 12:e=[64,33];break;case 13:e=[160,99];break;case 14:e=[4,3];break;case 15:e=[3,2];break;case 16:e=[2,1];break;case 255:e=[this.readUByte()<<8|this.readUByte(),this.readUByte()<<8|this.readUByte()]}e&&(c=e[0]/e[1])}return{width:Math.ceil((16*(a+1)-2*s-2*d)*c),height:(2-n)*(i+1)*16-(n?2:4)*(f+h)}}},{key:"readSliceType",value:function(){return this.readUByte(),this.readUEG(),this.readUEG()}}]),e}();e.default=i},{"../utils/logger":34}],17:[function(r,s,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var a=function(){function e(n,r){for(var t=0;tr);return t}},{key:"_parseID3Frames",value:function(r,t,i){for(var a,s,o,l,n;i>=t+8;)switch(a=this.readUTF(r,t,4),t+=4,s=r[t++]<<24+r[t++]<<16+r[t++]<<8+r[t++],l=r[t++]<<8+r[t++],o=t,a){case"PRIV":if("com.apple.streaming.transportStreamTimestamp"===this.readUTF(r,t,44)){t+=44,t+=4;var u=1&r[t++];this._hasTimeStamp=!0,n=((r[t++]<<23)+(r[t++]<<15)+(r[t++]<<7)+r[t++])/45,u&&(n+=47721858.84),n=Math.round(n),e.logger.trace("ID3 timestamp found: "+n),this._timeStamp=n}}}},{key:"hasTimeStamp",get:function(){return this._hasTimeStamp}},{key:"timeStamp",get:function(){return this._timeStamp}},{key:"length",get:function(){return this._length}},{key:"payload",get:function(){return this._payload}}]),t}();t.default=i},{"../utils/logger":34}],18:[function(t,g,a){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var f=function(){function e(n,r){for(var t=0;tt;t+=188)if(71===n[t]){if(d=!!(64&n[t+1]),u=((31&n[t+1])<<8)+n[t+2],y=(48&n[t+3])>>4,y>1){if(a=t+5+n[t+4],a===t+188)continue}else a=t+4;if(v)if(u===h){if(d){if(s&&(this._parseAVCPES(this._parsePES(s)),b&&this._avcTrack.codec&&(-1===f||this._aacTrack.codec)))return void this.remux(n);s={data:[],size:0}}s&&(s.data.push(n.subarray(a,t+188)),s.size+=t+188-a)}else if(u===f){if(d){if(o&&(this._parseAACPES(this._parsePES(o)),b&&this._aacTrack.codec&&(-1===h||this._avcTrack.codec)))return void this.remux(n);o={data:[],size:0}}o&&(o.data.push(n.subarray(a,t+188)),o.size+=t+188-a)}else u===g&&(d&&(l&&this._parseID3PES(this._parsePES(l)),l={data:[],size:0}),l&&(l.data.push(n.subarray(a,t+188)),l.size+=t+188-a));else d&&(a+=n[a]+1),0===u?this._parsePAT(n,a):u===this._pmtId&&(this._parsePMT(n,a),v=this.pmtParsed=!0,h=this._avcTrack.id,f=this._aacTrack.id,g=this._id3Track.id)}else this.observer.trigger(i.default.ERROR,{type:r.ErrorTypes.MEDIA_ERROR,details:r.ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});s&&this._parseAVCPES(this._parsePES(s)),o&&this._parseAACPES(this._parsePES(o)),l&&this._parseID3PES(this._parsePES(l)),this.remux(null)}},{key:"remux",value:function(e){this.remuxer.remux(this._aacTrack,this._avcTrack,this._id3Track,this._txtTrack,this.timeOffset,this.contiguous,e)}},{key:"destroy",value:function(){this.switchLevel(),this._initPTS=this._initDTS=void 0,this._duration=0}},{key:"_parsePAT",value:function(e,t){this._pmtId=(31&e[t+10])<<8|e[t+11]}},{key:"_parsePMT",value:function(r,t){var a,i,s,n;for(a=(15&r[t+1])<<8|r[t+2],i=t+3+a-4,s=(15&r[t+10])<<8|r[t+11],t+=12+s;i>t;){switch(n=(31&r[t+1])<<8|r[t+2],r[t]){case 15:this._aacTrack.id=n;break;case 21:this._id3Track.id=n;break;case 27:this._avcTrack.id=n;break;default:e.logger.log("unkown stream type:"+r[t])}t+=((15&r[t+3])<<8|r[t+4])+5}}},{key:"_parsePES",value:function(o){var e,i,h,d,u,l,n,r,t,f=0,s=o.data;if(e=s[0],h=(e[0]<<16)+(e[1]<<8)+e[2],1===h){for(d=(e[4]<<8)+e[5],i=e[7],192&i&&(n=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,n>4294967295&&(n-=8589934592),64&i?(r=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2,r>4294967295&&(r-=8589934592)):r=n),u=e[8],t=u+9,o.size-=t,l=new Uint8Array(o.size);s.length;){e=s.shift();var a=e.byteLength;if(t){if(t>a){t-=a;continue}e=e.subarray(t),a-=t,t=0}l.set(e,f),f+=a}return{data:l,pts:n,dts:r,len:d}}return null}},{key:"_parseAVCPES",value:function(n){var t,y,i,l,f=this,r=this._avcTrack,u=r.samples,m=this._parseAVCNALu(n.data),d=[],o=!1,c=!1,g=0;if(0===m.length&&u.length>0){var v=u[u.length-1],h=v.units.units[v.units.units.length-1],p=new Uint8Array(h.data.byteLength+n.data.byteLength);p.set(h.data,0),p.set(n.data,h.data.byteLength),h.data=p,v.units.length+=n.data.byteLength,r.len+=n.data.byteLength}n.data=null;var a="";m.forEach(function(e){switch(e.type){case 1:i=!0,o&&(a+="NDR ");break;case 5:i=!0,o&&(a+="IDR "),c=!0;break;case 6:i=!0,o&&(a+="SEI "),t=new s.default(e.data),t.readUByte();var E=t.readUByte();if(4===E){var p=0;do p=t.readUByte();while(255===p);var R=t.readUByte();if(181===R){var _=t.readUShort();if(49===_){var A=t.readUInt();if(1195456820===A){var k=t.readUByte();if(3===k){var v=t.readUByte(),b=t.readUByte(),S=31&v,h=[v,b];for(l=0;S>l;l++)h.push(t.readUByte()),h.push(t.readUByte()),h.push(t.readUByte());f._txtTrack.samples.push({type:3,pts:n.pts,bytes:h})}}}}}break;case 7:if(i=!0,o&&(a+="SPS "),!r.sps){t=new s.default(e.data);var y=t.readSPS();r.width=y.width,r.height=y.height,r.sps=[e.data],r.timescale=f.remuxer.timescale,r.duration=f.remuxer.timescale*f._duration;var L=e.data.subarray(1,4),m="avc1.";for(l=0;3>l;l++){var u=L[l].toString(16);u.length<2&&(u="0"+u),m+=u}r.codec=m}break;case 8:i=!0,o&&(a+="PPS "),r.pps||(r.pps=[e.data]);break;case 9:i=!1,o&&(a+="AUD ");break;default:i=!1,a+="unknown NAL "+e.type+" "}i&&(d.push(e),g+=e.data.byteLength)}),(o||a.length)&&e.logger.log(a),d.length&&(c===!0||r.sps)&&(y={units:{units:d,length:g},pts:n.pts,dts:n.dts,key:c},u.push(y),r.len+=g,r.nbNalu+=d.length)}},{key:"_parseAVCNALu",value:function(r){for(var i,n,s,p,a,l,t=0,h=r.byteLength,e=0,d=[];h>t;)switch(i=r[t++],e){case 0:0===i&&(e=1);break;case 1:e=0===i?2:0;break;case 2:case 3:if(0===i)e=3;else if(1===i&&h>t){if(p=31&r[t],a)s={data:r.subarray(a,t-e-1),type:l},d.push(s);else if(n=t-e-1){var c=this._avcTrack,f=c.samples;if(f.length){var g=f[f.length-1],v=g.units.units,o=v[v.length-1],u=new Uint8Array(o.data.byteLength+n);u.set(o.data,0),u.set(r.subarray(0,n),o.data.byteLength),o.data=u,g.units.length+=n,c.len+=n}}a=t,l=p,e=0}else e=0}return a&&(s={data:r.subarray(a,h),type:l},d.push(s)),d}},{key:"_parseAACPES",value:function(R){var s,l,p,E,t,d,h,o,_,a=this._aacTrack,n=R.data,g=R.pts,k=0,L=this._duration,A=this.audioCodec,u=this.aacOverFlow,b=this.lastAacPTS;if(u){var m=new Uint8Array(u.byteLength+n.byteLength);m.set(u,0),m.set(n,u.byteLength),n=m}for(t=k,o=n.length;o-1>t&&(255!==n[t]||240!==(240&n[t+1]));t++);if(t){var y,f;if(o-1>t?(y="AAC PES did not start with ADTS header,offset:"+t,f=!1):(y="no ADTS header found in AAC PES",f=!0),this.observer.trigger(i.default.ERROR,{type:r.ErrorTypes.MEDIA_ERROR,details:r.ErrorDetails.FRAG_PARSING_ERROR,fatal:f,reason:y}),f)return}if(a.audiosamplerate||(s=c.default.getAudioConfig(this.observer,n,t,A),a.config=s.config,a.audiosamplerate=s.samplerate,a.channelCount=s.channelCount,a.codec=s.codec,a.timescale=s.samplerate,a.duration=s.samplerate*L,e.logger.log("parsed codec:"+a.codec+",rate:"+s.samplerate+",nb channel:"+s.channelCount)),E=0,p=9216e4/a.audiosamplerate,u&&b){var v=b+p;Math.abs(v-g)>1&&(e.logger.log("AAC: align PTS for overlapping frames by "+Math.round((v-g)/90)),g=v)}for(;o>t+5&&(d=1&n[t+1]?7:9,l=(3&n[t+3])<<11|n[t+4]<<3|(224&n[t+5])>>>5,l-=d,l>0&&o>=t+d+l);)for(h=g+E*p,_={unit:n.subarray(t+d,t+d+l),pts:h,dts:h},a.samples.push(_),a.len+=l,t+=l+d,E++;o-1>t&&(255!==n[t]||240!==(240&n[t+1]));t++);u=o>t?n.subarray(t,o):null,this.aacOverFlow=u,this.lastAacPTS=h}},{key:"_parseID3PES",value:function(e){this._id3Track.samples.push(e)}}],[{key:"probe",value:function(e){return e.length>=564&&71===e[0]&&71===e[188]&&71===e[376]?!0:!1}}]),t}();a.default=o},{"../errors":19,"../events":21,"../utils/logger":34,"./adts":12,"./exp-golomb":16}],19:[function(t,r,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0});e.ErrorTypes={NETWORK_ERROR:"networkError",MEDIA_ERROR:"mediaError",OTHER_ERROR:"otherError"},e.ErrorDetails={MANIFEST_LOAD_ERROR:"manifestLoadError",MANIFEST_LOAD_TIMEOUT:"manifestLoadTimeOut",MANIFEST_PARSING_ERROR:"manifestParsingError",MANIFEST_INCOMPATIBLE_CODECS_ERROR:"manifestIncompatibleCodecsError",LEVEL_LOAD_ERROR:"levelLoadError",LEVEL_LOAD_TIMEOUT:"levelLoadTimeOut",LEVEL_SWITCH_ERROR:"levelSwitchError",FRAG_LOAD_ERROR:"fragLoadError",FRAG_LOOP_LOADING_ERROR:"fragLoopLoadingError",FRAG_LOAD_TIMEOUT:"fragLoadTimeOut",FRAG_DECRYPT_ERROR:"fragDecryptError",FRAG_PARSING_ERROR:"fragParsingError",KEY_LOAD_ERROR:"keyLoadError",KEY_LOAD_TIMEOUT:"keyLoadTimeOut",BUFFER_APPEND_ERROR:"bufferAppendError",BUFFER_APPENDING_ERROR:"bufferAppendingError",BUFFER_STALLED_ERROR:"bufferStalledError",BUFFER_FULL_ERROR:"bufferFullError",BUFFER_SEEK_OVER_HOLE:"bufferSeekOverHole"}},{}],20:[function(i,s,e){"use strict";function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},n=function(){function e(n,r){for(var t=0;t1?n-1:0),r=1;n>r;r++)a[r-1]=arguments[r];this.handledEvents=a,this.useGenericHandler=!0,this.registerListeners()}return n(e,[{key:"destroy",value:function(){this.unregisterListeners()}},{key:"isEventHandler",value:function(){return"object"===r(this.handledEvents)&&this.handledEvents.length&&"function"==typeof this.onEvent}},{key:"registerListeners",value:function(){this.isEventHandler()&&this.handledEvents.forEach(function(e){if("hlsEventGeneric"===e)throw new Error("Forbidden event name: "+e);this.hls.on(e,this.onEvent)}.bind(this))}},{key:"unregisterListeners",value:function(){this.isEventHandler()&&this.handledEvents.forEach(function(e){this.hls.off(e,this.onEvent)}.bind(this))}},{key:"onEvent",value:function(e,t){this.onEventGeneric(e,t)}},{key:"onEventGeneric",value:function(e,t){var r=function(t,r){var e="on"+t.replace("hls","");if("function"!=typeof this[e])throw new Error("Event "+t+" has no generic handler in this "+this.constructor.name+" class (tried "+e+")");return this[e].bind(this,r)};r.call(this,e,t).call()}}]),e}();e.default=a},{}],21:[function(t,e,r){"use strict";e.exports={MEDIA_ATTACHING:"hlsMediaAttaching",MEDIA_ATTACHED:"hlsMediaAttached",MEDIA_DETACHING:"hlsMediaDetaching",MEDIA_DETACHED:"hlsMediaDetached",BUFFER_RESET:"hlsBufferReset",BUFFER_CODECS:"hlsBufferCodecs",BUFFER_APPENDING:"hlsBufferAppending",BUFFER_APPENDED:"hlsBufferAppended",BUFFER_EOS:"hlsBufferEos",BUFFER_FLUSHING:"hlsBufferFlushing",BUFFER_FLUSHED:"hlsBufferFlushed",MANIFEST_LOADING:"hlsManifestLoading",MANIFEST_LOADED:"hlsManifestLoaded",MANIFEST_PARSED:"hlsManifestParsed",LEVEL_LOADING:"hlsLevelLoading",LEVEL_LOADED:"hlsLevelLoaded",LEVEL_UPDATED:"hlsLevelUpdated",LEVEL_PTS_UPDATED:"hlsLevelPtsUpdated",LEVEL_SWITCH:"hlsLevelSwitch",FRAG_LOADING:"hlsFragLoading",FRAG_LOAD_PROGRESS:"hlsFragLoadProgress",FRAG_LOAD_EMERGENCY_ABORTED:"hlsFragLoadEmergencyAborted",FRAG_LOADED:"hlsFragLoaded",FRAG_PARSING_INIT_SEGMENT:"hlsFragParsingInitSegment",FRAG_PARSING_USERDATA:"hlsFragParsingUserdata",FRAG_PARSING_METADATA:"hlsFragParsingMetadata",FRAG_PARSING_DATA:"hlsFragParsingData",FRAG_PARSED:"hlsFragParsed",FRAG_BUFFERED:"hlsFragBuffered",FRAG_CHANGED:"hlsFragChanged",FPS_DROP:"hlsFpsDrop",ERROR:"hlsError",DESTROYING:"hlsDestroying",KEY_LOADING:"hlsKeyLoading",KEY_LOADED:"hlsKeyLoaded"}},{}],22:[function(r,s,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var a=function(){function e(n,r){for(var t=0;td)return void(n.PTSKnown=!1);for(var r=c;d>=r;r++){var l=h[f+r],a=o[r];u=l.cc-a.cc,isNaN(l.startPTS)||(a.start=a.startPTS=l.startPTS,a.endPTS=l.endPTS,a.duration=l.duration,s=a)}if(u)for(e.logger.log("discontinuity sliding from playlist, take drift into account"),r=0;rn.endSN)return 0;o=l-n.startSN,i=n.fragments,r=i[o],isNaN(r.startPTS)||(a=Math.min(a,r.startPTS),s=Math.max(s,r.endPTS));var u=a-r.start;for(r.start=r.startPTS=a,r.endPTS=s,r.duration=s-a,e=o;e>0;e--)t.updatePTS(i,e,e-1);for(e=o;en?r.start=t.start+t.duration:r.start=t.start-r.duration:a>n?(t.duration=i-t.start,t.duration<0&&e.logger.error("negative duration computed for frag "+t.sn+",level "+t.level+", there should be some duration drift between playlist and fragment!")):(r.duration=t.start-i,r.duration<0&&e.logger.error("negative duration computed for frag "+r.sn+",level "+r.level+", there should be some duration drift between playlist and fragment!"))}}]),t}();t.default=i},{"../utils/logger":34}],23:[function(t,O,a){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i=function(){function e(n,r){for(var t=0;t1?t-1:0),e=1;t>e;e++)a[e-1]=arguments[e];n.emit.apply(n,[r,r].concat(a))},n.off=function(a){for(var t=arguments.length,r=Array(t>1?t-1:0),e=1;t>e;e++)r[e-1]=arguments[e];n.removeListener.apply(n,[a].concat(r))},this.on=n.on.bind(n),this.off=n.off.bind(n),this.trigger=n.trigger.bind(n),this.playlistLoader=new d.default(this),this.fragmentLoader=new h.default(this),this.levelController=new b.default(this),this.abrController=new r.abrController(this),this.bufferController=new r.bufferController(this),this.streamController=new r.streamController(this),this.timelineController=new r.timelineController(this),this.keyLoader=new v.default(this)}return i(t,null,[{key:"isSupported",value:function(){return window.MediaSource&&window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"')}},{key:"Events",get:function(){return n.default}},{key:"ErrorTypes",get:function(){return s.ErrorTypes}},{key:"ErrorDetails",get:function(){return s.ErrorDetails}},{key:"DefaultConfig",get:function(){return t.defaultConfig||(t.defaultConfig={autoStartLoad:!0,debug:!1,maxBufferLength:30,maxBufferSize:6e7,maxBufferHole:.5,maxSeekHole:2,maxFragLookUpTolerance:.2,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxMaxBufferLength:600,enableWorker:!0,enableSoftwareAES:!0,manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingLoopThreshold:3,startFragPrefetch:!1,appendErrorMaxRetry:3,loader:k.default,fLoader:void 0,pLoader:void 0,abrController:g.default,bufferController:p.default,streamController:m.default,timelineController:R.default,enableCEA708Captions:!0,enableMP2TPassThrough:!1}),t.defaultConfig},set:function(e){t.defaultConfig=e}}]),i(t,[{key:"destroy",value:function(){e.logger.log("destroy"),this.trigger(n.default.DESTROYING),this.detachMedia(),this.playlistLoader.destroy(),this.fragmentLoader.destroy(),this.levelController.destroy(),this.bufferController.destroy(),this.streamController.destroy(),this.timelineController.destroy(),this.keyLoader.destroy(),this.url=null,this.observer.removeAllListeners()}},{key:"attachMedia",value:function(t){e.logger.log("attachMedia"),this.media=t,this.trigger(n.default.MEDIA_ATTACHING,{media:t})}},{key:"detachMedia",value:function(){e.logger.log("detachMedia"),this.trigger(n.default.MEDIA_DETACHING),this.media=null}},{key:"loadSource",value:function(t){e.logger.log("loadSource:"+t),this.url=t,this.trigger(n.default.MANIFEST_LOADING,{url:t})}},{key:"startLoad",value:function(){var t=arguments.length<=0||void 0===arguments[0]?0:arguments[0];e.logger.log("startLoad"),this.levelController.startLoad(),this.streamController.startLoad(t)}},{key:"stopLoad",value:function(){e.logger.log("stopLoad"),this.levelController.stopLoad(),this.streamController.stopLoad()}},{key:"swapAudioCodec",value:function(){e.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}},{key:"recoverMediaError",value:function(){e.logger.log("recoverMediaError");var t=this.media;this.detachMedia(),this.attachMedia(t)}},{key:"levels",get:function(){return this.levelController.levels}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(t){e.logger.log("set currentLevel:"+t),this.loadLevel=t,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(t){e.logger.log("set nextLevel:"+t),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(t){e.logger.log("set loadLevel:"+t),this.levelController.manualLevel=t}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return this.levelController.firstLevel},set:function(t){e.logger.log("set firstLevel:"+t),this.levelController.firstLevel=t}},{key:"startLevel",get:function(){return this.levelController.startLevel},set:function(t){e.logger.log("set startLevel:"+t),this.levelController.startLevel=t}},{key:"autoLevelCapping",get:function(){return this.abrController.autoLevelCapping},set:function(t){e.logger.log("set autoLevelCapping:"+t),this.abrController.autoLevelCapping=t}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}}]),t}();a.default=l},{"./controller/abr-controller":3,"./controller/buffer-controller":4,"./controller/level-controller":5,"./controller/stream-controller":6,"./controller/timeline-controller":7,"./errors":19,"./events":21,"./loader/fragment-loader":25,"./loader/key-loader":26,"./loader/playlist-loader":27,"./utils/logger":34,"./utils/xhr-loader":36,events:1}],24:[function(e,t,r){"use strict";t.exports=e("./hls.js").default},{"./hls.js":23}],25:[function(r,c,n){"use strict";function a(e){return e&&e.__esModule?e:{default:e}}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function f(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var h=function(){function e(n,r){for(var t=0;t2?(e=t.shift()+".",e+=parseInt(t.shift()).toString(16),e+=("000"+parseInt(t.shift()).toString(16)).substr(-4)):e=r,e}},{key:"cloneObj",value:function(e){return JSON.parse(JSON.stringify(e))}},{key:"parseLevelPlaylist",value:function(L,l,A){var e,b,s,i,v=0,o=0,n={url:l,fragments:[],live:!0,startSN:0},r={method:null,key:null,iv:null,uri:null},E=0,f=null,t=null;for(b=/(?:#EXT-X-(MEDIA-SEQUENCE):(\d+))|(?:#EXT-X-(TARGETDURATION):(\d+))|(?:#EXT-X-(KEY):(.*))|(?:#EXT(INF):([\d\.]+)[^\r\n]*([\r\n]+[^#|\r\n]+)?)|(?:#EXT-X-(BYTERANGE):([\d]+[@[\d]*)]*[\r\n]+([^#|\r\n]+)?|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(PROGRAM-DATE-TIME):(.*))/g;null!==(e=b.exec(L));)switch(e.shift(),e=e.filter(function(e){return void 0!==e}),e[0]){case"MEDIA-SEQUENCE":v=n.startSN=parseInt(e[1]);break;case"TARGETDURATION":n.targetduration=parseFloat(e[1]);break;case"ENDLIST":n.live=!1;break;case"DIS":E++;break;case"BYTERANGE":var c=e[1].split("@");i=1===c.length?s:parseInt(c[1]),s=parseInt(c[0])+i,t&&!t.url&&(t.byteRangeStartOffset=i,t.byteRangeEndOffset=s,t.url=this.resolve(e[2],l));break;case"INF":var g=parseFloat(e[1]);if(!isNaN(g)){var u,m=v++;if(r.method&&r.uri&&!r.iv){u=this.cloneObj(r);for(var y=new Uint8Array(16),d=12;16>d;d++)y[d]=m>>8*(15-d)&255;u.iv=y}else u=r;var k=e[2]?this.resolve(e[2],l):null;t={url:k,duration:g,start:o,sn:m,level:A,cc:E,byteRangeStartOffset:i,byteRangeEndOffset:s,decryptdata:u,programDateTime:f},n.fragments.push(t),o+=g,i=null,f=null}break;case"KEY":var R=e[1],p=new a.default(R),h=p.enumeratedString("METHOD"),_=p.URI,S=p.hexadecimalInteger("IV");h&&(r={method:null,key:null,iv:null,uri:null},_&&"AES-128"===h&&(r.method=h,r.uri=this.resolve(_,l),r.key=null,r.iv=S));break;case"PROGRAM-DATE-TIME":f=new Date(Date.parse(e[1]))}return t&&!t.url&&(n.fragments.pop(),o-=t.duration),n.totalduration=o,n.endSN=v-1,n}},{key:"loadsuccess",value:function(u,n){var s,o=u.currentTarget,i=o.responseText,r=o.responseURL,l=this.id,d=this.id2,a=this.hls;if(void 0===r&&(r=this.url),n.tload=performance.now(),n.mtime=new Date(o.getResponseHeader("Last-Modified")),0===i.indexOf("#EXTM3U"))if(i.indexOf("#EXTINF:")>0)if(null===this.id)a.trigger(t.default.MANIFEST_LOADED,{levels:[{url:r}],url:r,stats:n});else{var f=this.parseLevelPlaylist(i,r,l);n.tparsed=performance.now(),a.trigger(t.default.LEVEL_LOADED,{details:f,level:l,id:d,stats:n})}else s=this.parseMasterPlaylist(i,r),s.length?a.trigger(t.default.MANIFEST_LOADED,{levels:s,url:r,stats:n}):a.trigger(t.default.ERROR,{type:e.ErrorTypes.NETWORK_ERROR,details:e.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:!0,url:r,reason:"no level found in manifest"});else a.trigger(t.default.ERROR,{type:e.ErrorTypes.NETWORK_ERROR,details:e.ErrorDetails.MANIFEST_PARSING_ERROR,fatal:!0,url:r,reason:"no EXTM3U delimiter"})}},{key:"loaderror",value:function(a){var r,n;null===this.id?(r=e.ErrorDetails.MANIFEST_LOAD_ERROR,n=!0):(r=e.ErrorDetails.LEVEL_LOAD_ERROR,n=!1),this.loader&&this.loader.abort(),this.hls.trigger(t.default.ERROR,{type:e.ErrorTypes.NETWORK_ERROR,details:r,fatal:n,url:this.url,loader:this.loader,response:a.currentTarget,level:this.id,id:this.id2})}},{key:"loadtimeout",value:function(){var r,n;null===this.id?(r=e.ErrorDetails.MANIFEST_LOAD_TIMEOUT,n=!0):(r=e.ErrorDetails.LEVEL_LOAD_TIMEOUT,n=!1),this.loader&&this.loader.abort(),this.hls.trigger(t.default.ERROR,{type:e.ErrorTypes.NETWORK_ERROR,details:r,fatal:n,url:this.url,loader:this.loader,level:this.id,id:this.id2})}}]),r}(i.default);s.default=u},{"../errors":19,"../event-handler":20,"../events":21,"../utils/attr-list":31,"../utils/url":35}],28:[function(a,i,e){"use strict";function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var r=function(){function e(n,r){for(var t=0;t>24&255,t[1]=e>>16&255,t[2]=e>>8&255,t[3]=255&e,t.set(a,4),r=0,e=8;i>r;r++)t.set(n[r],e),e+=n[r].byteLength;return t}},{key:"hdlr",value:function(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])}},{key:"mdat",value:function(t){return e.box(e.types.mdat,t)}},{key:"mdhd",value:function(t,r){return e.box(e.types.mdhd,new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}},{key:"mdia",value:function(t){return e.box(e.types.mdia,e.mdhd(t.timescale,t.duration),e.hdlr(t.type),e.minf(t))}},{key:"mfhd",value:function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}},{key:"minf",value:function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))}},{key:"moof",value:function(t,r,n){return e.box(e.types.moof,e.mfhd(t),e.traf(n,r))}},{key:"moov",value:function(t){for(var r=t.length,n=[];r--;)n[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale,t[0].duration)].concat(n).concat(e.mvex(t)))}},{key:"mvex",value:function(r){for(var t=r.length,n=[];t--;)n[t]=e.trex(r[t]);return e.box.apply(null,[e.types.mvex].concat(n))}},{key:"mvhd",value:function(t,r){var n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24&255,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(e.types.mvhd,n)}},{key:"sdtp",value:function(i){var r,t,n=i.samples||[],a=new Uint8Array(4+n.length);for(t=0;t>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(a));for(r=0;r>>8&255),s.push(255&i),s=s.concat(Array.prototype.slice.call(a));var u=e.box(e.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(s))),o=t.width,l=t.height;return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),u,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])))}},{key:"esds",value:function(t){var e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))}},{key:"mp4a",value:function(t){var r=t.audiosamplerate;return e.box(e.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),e.box(e.types.esds,e.esds(t)))}},{key:"stsd",value:function(t){return"audio"===t.type?e.box(e.types.stsd,e.STSD,e.mp4a(t)):e.box(e.types.stsd,e.STSD,e.avc1(t))}},{key:"tkhd",value:function(t){var r=t.id,n=t.duration,a=t.width,i=t.height;return e.box(e.types.tkhd,new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,a>>8&255,255&a,0,0,i>>8&255,255&i,0,0]))}},{key:"traf",value:function(n,t){var a=e.sdtp(n),r=n.id;return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),e.box(e.types.tfdt,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t])),e.trun(n,a.length+16+16+8+16+8+8),a)}},{key:"trak",value:function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))}},{key:"trex",value:function(r){var t=r.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{key:"trun",value:function(h,o){var n,a,i,s,t,l,d=h.samples||[],r=d.length,f=12+16*r,u=new Uint8Array(f);for(o+=8+f,u.set([0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,o>>>24&255,o>>>16&255,o>>>8&255,255&o],0),n=0;r>n;n++)a=d[n],i=a.duration,s=a.size,t=a.flags,l=a.cts,u.set([i>>>24&255,i>>>16&255,i>>>8&255,255&i,s>>>24&255,s>>>16&255,s>>>8&255,255&s,t.isLeading<<2|t.dependsOn,t.isDependedOn<<6|t.hasRedundancy<<4|t.paddingValue<<1|t.isNonSync,61440&t.degradPrio,15&t.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*n);return e.box(e.types.trun,u)}},{key:"initSegment",value:function(n){e.types||e.init();var t,r=e.moov(n);return t=new Uint8Array(e.FTYP.byteLength+r.byteLength),t.set(e.FTYP),t.set(r,e.FTYP.byteLength),t}}]),e}();e.default=n},{}],29:[function(n,h,a){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var l=function(){function e(n,r){for(var t=0;t=y&&(t.logger.log("invalid sample duration at PTS/DTS: "+l.pts+"/"+l.dts+":"+y),y=1),v.duration=y}else{var i,m=this.nextAvcDts;o=this._PTSNormalize(_,m),n=this._PTSNormalize(c,m),i=Math.round((n-m)/90),(T||Math.abs(i)<600)&&i&&(i>1?t.logger.log("AVC:"+i+" ms hole between fragments detected,filling it"):-1>i&&t.logger.log("AVC:"+-i+" ms overlapping between fragments detected"),n=m,o=Math.max(o-i,n),t.logger.log("Video/PTS/DTS adjusted: "+o+"/"+n+",delta:"+i)),k=Math.max(0,o),R=Math.max(0,n)}v={size:A,duration:0,cts:(o-n)/f,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0}},s=v.flags,l.key===!0?(s.dependsOn=2,s.isNonSync=0):(s.dependsOn=1,s.isNonSync=1),u.push(v),h=n}var b=0;u.length>=2&&(b=u[u.length-2].duration,v.duration=b),this.nextAvcDts=n+b*f,a.len=0,a.nbNalu=0,u.length&&navigator.userAgent.toLowerCase().indexOf("chrome")>-1&&(s=u[0].flags,s.dependsOn=2,s.isNonSync=0),a.samples=u,S=r.default.moof(a.sequenceNumber++,R/f,a),a.samples=[],this.observer.trigger(e.default.FRAG_PARSING_DATA,{data1:S,data2:d,startPTS:k/E,endPTS:(o+f*b)/E,startDTS:R/E,endDTS:this.nextAvcDts/E,type:"video",nb:u.length})}},{key:"remuxAudio",value:function(n,w,T){var k,y,i,f,o,L,A,E,l,v,_,d,a,R=8,u=this.PES_TIMESCALE,S=n.timescale,h=u/S,m=[],b=[];for(n.samples.sort(function(e,t){return e.pts-t.pts}),b=n.samples;b.length;){if(y=b.shift(),f=y.unit,v=y.pts-this._initDTS,_=y.dts-this._initDTS,void 0!==l)d=this._PTSNormalize(v,l),a=this._PTSNormalize(_,l),i.duration=(a-l)/h,Math.abs(i.duration-1024)>10&&t.logger.log("invalid AAC sample duration at PTS "+Math.round(v/90)+",should be 1024,found :"+Math.round(i.duration)),i.duration=1024,a=1024*h+l;else{var s,p=this.nextAacPts;if(d=this._PTSNormalize(v,p),a=this._PTSNormalize(_,p),s=Math.round(1e3*(d-p)/u),(T||Math.abs(s)<600)&&s){if(s>0)t.logger.log(s+" ms hole between AAC samples detected,filling it");else if(-12>s){t.logger.log(-s+" ms overlapping between AAC samples detected, drop frame"),n.len-=f.byteLength;continue}d=a=p}if(A=Math.max(0,d),E=Math.max(0,a),!(n.len>0))return;o=new Uint8Array(n.len+8),k=new DataView(o.buffer),k.setUint32(0,o.byteLength),o.set(r.default.types.mdat,4)}o.set(f,R),R+=f.byteLength,i={size:f.byteLength,cts:0,duration:0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},m.push(i),l=a}var g=0,c=m.length;c>=2&&(g=m[c-2].duration,i.duration=g),c&&(this.nextAacPts=d+h*g,n.len=0,n.samples=m,L=r.default.moof(n.sequenceNumber++,E/h,n),n.samples=[],this.observer.trigger(e.default.FRAG_PARSING_DATA,{data1:L,data2:o,startPTS:A/u,endPTS:this.nextAacPts/u,startDTS:E/u,endDTS:(a+h*g)/u,type:"audio",nb:c}))}},{key:"remuxID3",value:function(r,a){var t,i=r.samples.length;if(i){for(var n=0;i>n;n++)t=r.samples[n],t.pts=(t.pts-this._initPTS)/this.PES_TIMESCALE,t.dts=(t.dts-this._initDTS)/this.PES_TIMESCALE;this.observer.trigger(e.default.FRAG_PARSING_METADATA,{samples:r.samples})}r.samples=[],a=a}},{key:"remuxText",value:function(t,a){t.samples.sort(function(e,t){return e.pts-t.pts});var r,i=t.samples.length;if(i){for(var n=0;i>n;n++)r=t.samples[n],r.pts=(r.pts-this._initPTS)/this.PES_TIMESCALE;this.observer.trigger(e.default.FRAG_PARSING_USERDATA,{samples:t.samples})}t.samples=[],a=a}},{key:"_PTSNormalize",value:function(e,t){var r;if(void 0===t)return e;for(r=e>t?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}},{key:"passthrough",get:function(){return!1}},{key:"timescale",get:function(){return this.MP4_TIMESCALE}}]),n}();a.default=d},{"../errors":19,"../events":21,"../remux/mp4-generator":28,"../utils/logger":34}],30:[function(r,l,e){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i=function(){function e(n,r){for(var t=0;tNumber.MAX_SAFE_INTEGER?1/0:e}},{key:"hexadecimalInteger",value:function(r){if(this[r]){var e=(this[r]||"0x").slice(2);e=(1&e.length?"0":"")+e;for(var n=new Uint8Array(e.length/2),t=0;tNumber.MAX_SAFE_INTEGER?1/0:e}},{key:"decimalFloatingPoint",value:function(e){return parseFloat(this[e])}},{key:"enumeratedString",value:function(e){return this[e]}},{key:"decimalResolution",value:function(t){var e=/^(\d+)x(\d+)$/.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}}],[{key:"parseAttrList",value:function(a){for(var t,i=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,r={};null!==(t=i.exec(a));){var e=t[2],n='"';0===e.indexOf(n)&&e.lastIndexOf(n)===e.length-1&&(e=e.slice(1,-1)),r[t[1]]=e}return r}}]),e}();e.default=n},{}],32:[function(r,e,n){"use strict";var t={search:function(a,s){for(var t=0,r=a.length-1,e=null,n=null;r>=t;){e=(t+r)/2|0,n=a[e];var i=s(n);if(i>0)t=e+1;else{if(!(0>i))return n;r=e-1}}return null}};e.exports=t},{}],33:[function(a,i,e){"use strict";function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var r=function(){function e(n,r){for(var t=0;t0;)e.removeCue(e.cues[0])}},{key:"push",value:function(r,n){this.cue||this._createCue();for(var a,t,e,s,o,u=31&n[0],i=2,l=0;u>l;l++)if(a=n[i++],t=127&n[i++],e=127&n[i++],s=0===(4&a)?!1:!0,o=3&a,(0!==t||0!==e)&&s&&0===o){if(32&t||64&t)this.cue.text+=this._fromCharCode(t)+this._fromCharCode(e);else if((17===t||25===t)&&e>=48&&63>=e)switch(e){case 48:this.cue.text+="®";break;case 49:this.cue.text+="°";break;case 50:this.cue.text+="½";break;case 51:this.cue.text+="¿";break;case 52:this.cue.text+="™";break;case 53:this.cue.text+="¢";break;case 54:this.cue.text+="";break;case 55:this.cue.text+="£";break;case 56:this.cue.text+="♪";break;case 57:this.cue.text+=" ";break;case 58:this.cue.text+="è";break;case 59:this.cue.text+="â";break;case 60:this.cue.text+="ê";break;case 61:this.cue.text+="î";break;case 62:this.cue.text+="ô";break;case 63:this.cue.text+="û"}if((17===t||25===t)&&e>=32&&47>=e)switch(e){case 32:break;case 33:break;case 34:break;case 35:break;case 36:break;case 37:break;case 38:break;case 39:break;case 40:break;case 41:break;case 42:break;case 43:break;case 44:break;case 45:break;case 46:break;case 47:}if((20===t||28===t)&&e>=32&&47>=e)switch(e){case 32:this._clearActiveCues(r);break;case 33:this.cue.text=this.cue.text.substr(0,this.cue.text.length-1);break;case 34:break;case 35:break;case 36:break;case 37:break;case 38:break;case 39:break;case 40:break;case 41:this._clearActiveCues(r);break;case 42:break;case 43:break;case 44:this._clearActiveCues(r);break;case 45:break;case 46:this._text="";break;case 47:this._flipMemory(r)}if((23===t||31===t)&&e>=33&&35>=e)switch(e){case 33:break;case 34:break;case 35:}}}},{key:"_fromCharCode",value:function(e){switch(e){case 42:return"á";case 2:return"á";case 2:return"é";case 4:return"í";case 5:return"ó";case 6:return"ú";case 3:return"ç";case 4:return"÷";case 5:return"Ñ";case 6:return"ñ";case 7:return"█";default:return String.fromCharCode(e)}}},{key:"_flipMemory",value:function(e){this._clearActiveCues(e),this._flushCaptions(e)}},{key:"_flushCaptions",value:function(s){this._has708||(this._textTrack=this.media.addTextTrack("captions","English","en"),this._has708=!0);var e=!0,n=!1,a=void 0;try{for(var i,t=this.memory[Symbol.iterator]();!(e=(i=t.next()).done);e=!0){var r=i.value;r.startTime=s,this._textTrack.addCue(r),this.display.push(r)}}catch(e){n=!0,a=e}finally{try{!e&&t.return&&t.return()}finally{if(n)throw a}}this.memory=[],this.cue=null}},{key:"_clearActiveCues",value:function(i){var e=!0,r=!1,n=void 0;try{for(var a,t=this.display[Symbol.iterator]();!(e=(a=t.next()).done);e=!0){var s=a.value;s.endTime=i}}catch(e){r=!0,n=e}finally{try{!e&&t.return&&t.return()}finally{if(r)throw n}}this.display=[]}},{key:"_clearBufferedCues",value:function(){}}]),e}();e.default=n},{}],34:[function(l,u,r){"use strict";function e(){}function a(t,e){return e="["+t+"] > "+e}function i(t){var r=window.console[t];return r?function(){for(var i=arguments.length,e=Array(i),n=0;i>n;n++)e[n]=arguments[n];e[0]&&(e[0]=a(t,e[0])),r.apply(window.console,e)}:e}function s(r){for(var n=arguments.length,a=Array(n>1?n-1:0),e=1;n>e;e++)a[e-1]=arguments[e];a.forEach(function(e){t[e]=r[e]?r[e].bind(r):i(e)})}var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};Object.defineProperty(r,"__esModule",{value:!0});var n={trace:e,debug:e,log:e,warn:e,info:e,error:e},t=n;r.enableLogs=function(e){if(e===!0||"object"===("undefined"==typeof e?"undefined":o(e))){s(e,"debug","log","info","warn","error");try{t.log()}catch(e){t=n}}else t=n},r.logger=t},{}],35:[function(r,t,n){"use strict";var e={buildAbsoluteURL:function(r,t){if(t=t.trim(),/^[a-z]+:/i.test(t))return t;var o=null,a=null,i=/^([^#]*)(.*)$/.exec(t);i&&(a=i[2],t=i[1]);var s=/^([^\?]*)(.*)$/.exec(t);s&&(o=s[2],t=s[1]);var f=/^([^#]*)(.*)$/.exec(r);f&&(r=f[1]);var u=/^([^\?]*)(.*)$/.exec(r);u&&(r=u[1]);var l=/^((([a-z]+):)?\/\/[a-z0-9\.\-_~]+(:[0-9]+)?\/)(.*)$/i.exec(r),h=l[3],d=l[1],c=l[5],n=null;return n=/^\/\//.test(t)?h+"://"+e.buildAbsolutePath("",t.substring(2)):/^\//.test(t)?d+e.buildAbsolutePath("",t.substring(1)):e.buildAbsolutePath(d+c,t),o&&(n+=o),a&&(n+=a),n},buildAbsolutePath:function(i,s){for(var n,e,o=s,a="",t=i.replace(/[^\/]*$/,o.replace(/(\/|^)(?:\.?\/+)+/g,"$1")),r=0;e=t.indexOf("/../",r),e>-1;r=e+n)n=/^\/(?:\.\.\/)*/.exec(t.slice(e))[0].length,a=(a+t.substring(r,e)).replace(new RegExp("(?:\\/+[^\\/]*){0,"+(n-1)/3+"}$"),"/");return a+t.substr(r)}};t.exports=e},{}],36:[function(r,s,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var a=function(){function e(n,r){for(var t=0;t=200&&300>r?(window.clearTimeout(this.timeoutHandle),t.tload=performance.now(),this.onSuccess(n,t)):t.retry1&&(this.input=new Array(t)),this.isUndef(e)||1===e?this.output=this.context.createGain():e>1&&(this.output=new Array(t))};t.prototype.set=function(e,i,n){if(this.isObject(e))n=i;else if(this.isString(e)){var o={};o[e]=i,e=o}t:for(var r in e){i=e[r];var s=this;if(-1!==r.indexOf(".")){for(var a=r.split("."),u=0;u1)for(var t=arguments[0],e=1;e0)for(var t=this,e=0;e0)for(var t=0;tn;n++)i[n].apply(this,e)}return this},t.Emitter.mixin=function(e){var i=["on","off","emit"];e._events={};for(var n=0;n1?t.getChannelData(1):e;var s=i(e,r),a=new window.ArrayBuffer(44+2*s.length),u=new window.DataView(a);n(u,0,"RIFF"),u.setUint32(4,36+2*s.length,!0),n(u,8,"WAVE"),n(u,12,"fmt "),u.setUint32(16,16,!0),u.setUint16(20,1,!0),u.setUint16(22,2,!0),u.setUint32(24,o.audiocontext.sampleRate,!0),u.setUint32(28,4*o.audiocontext.sampleRate,!0),u.setUint16(32,4,!0),u.setUint16(34,16,!0),n(u,36,"data"),u.setUint32(40,2*s.length,!0);for(var c=s.length,p=44,h=1,l=0;c>l;l++)u.setInt16(p,s[l]*(32767*h),!0),p+=2;return u}function i(t,e){for(var i=t.length+e.length,n=new Float32Array(i),o=0,r=0;i>r;)n[r++]=t[o],n[r++]=e[o],o++;return n}function n(t,e,i){for(var n=i.length,o=0;n>o;o++)t.setUint8(e+o,i.charCodeAt(o))}var o=a;t.prototype.sampleRate=function(){return o.audiocontext.sampleRate},t.prototype.freqToMidi=function(t){var e=Math.log(t/440)/Math.log(2),i=Math.round(12*e)+69;return i};var r=t.prototype.midiToFreq=function(t){return 440*Math.pow(2,(t-69)/12)},s=function(t){if("string"!=typeof t)return t;var e={A:21,B:23,C:24,D:26,E:28,F:29,G:31},i=e[t[0].toUpperCase()],n=~~t.slice(-1);switch(i+=12*(n-1),t[1]){case"#":i+=1;break;case"b":i-=1}return r(i)};return t.prototype.soundFormats=function(){o.extensions=[];for(var t=0;t-1))throw arguments[t]+" is not a valid sound format!";o.extensions.push(arguments[t])}},t.prototype.disposeSound=function(){for(var t=0;t-1)if(t.prototype.isFileSupported(n))i=i;else for(var r=i.split("."),s=r[r.length-1],a=0;a1?(this.splitter=i.createChannelSplitter(2),this.input.connect(this.splitter),this.splitter.connect(this.left,1),this.splitter.connect(this.right,0)):(this.input.connect(this.left),this.input.connect(this.right)),this.output=i.createChannelMerger(2),this.left.connect(this.output,0,1),this.right.connect(this.output,0,0),this.output.connect(e)},t.Panner.prototype.pan=function(t,e){var n=e||0,o=i.currentTime+n,r=(t+1)/2,s=Math.cos(r*Math.PI/2),a=Math.sin(r*Math.PI/2);this.left.gain.linearRampToValueAtTime(a,o),this.right.gain.linearRampToValueAtTime(s,o)},t.Panner.prototype.inputChannels=function(t){1===t?(this.input.disconnect(),this.input.connect(this.left),this.input.connect(this.right)):2===t&&(this.splitter=i.createChannelSplitter(2),this.input.disconnect(),this.input.connect(this.splitter),this.splitter.connect(this.left,1),this.splitter.connect(this.right,0))},t.Panner.prototype.connect=function(t){this.output.connect(t)},t.Panner.prototype.disconnect=function(){this.output&&this.output.disconnect()})}(a);var h;h=function(){function e(t,e){for(var i={},n=t.length,o=0;n>o;o++){if(t[o]>e){var r=t[o],s=new v(r,o);i[o]=s,o+=6e3}o++}return i}function i(t){for(var e=[],i=Object.keys(t).sort(),n=0;no;o++){var r=t[i[n]],s=t[i[n+o]];if(r&&s){var a=r.sampleIndex,u=s.sampleIndex,c=u-a;c>0&&r.intervals.push(c);var p=e.some(function(t){return t.interval===c?(t.count++,t):void 0});p||e.push({interval:c,count:1})}}return e}function n(t,e){var i=[];return t.forEach(function(t){try{var n=Math.abs(60/(t.interval/e));n=r(n);var o=i.some(function(e){return e.tempo===n?e.count+=t.count:void 0});if(!o){if(isNaN(n))return;i.push({tempo:Math.round(n),count:t.count})}}catch(s){throw s}}),i}function o(t,e,i,n){for(var o=[],s=Object.keys(t).sort(),a=0;a.01?!0:void 0})}function r(t){if(isFinite(t)&&0!==t){for(;90>t;)t*=2;for(;t>180&&t>90;)t/=2;return t}}function s(t){var e=t.inputBuffer.getChannelData(0);this._lastPos=e[e.length-1]||0,this._onTimeUpdate(self._lastPos)}function p(t){const e=t.target,i=this;e._playing=!1,e.removeEventListener("ended",i._clearOnEnd),i._onended(i),i.bufferSourceNodes.forEach(function(t,e){t._playing===!1&&i.bufferSourceNodes.splice(e)}),0===i.bufferSourceNodes.length&&(i._playing=!1)}var h=c,l=a,f=l.audiocontext,d=u.midiToFreq,m=u.convertToWav;t.SoundFile=function(e,i,n,o){if("undefined"!=typeof e){if("string"==typeof e||"string"==typeof e[0]){var r=t.prototype._checkFileFormats(e);this.url=r}else if("object"==typeof e&&!(window.File&&window.FileReader&&window.FileList&&window.Blob))throw"Unable to load file because the File API is not supported";e.file&&(e=e.file),this.file=e}this._onended=function(){},this._looping=!1,this._playing=!1,this._paused=!1,this._pauseTime=0,this._cues=[],this._cueIDCounter=0,this._lastPos=0,this._counterNode=null,this._scopeNode=null,this.bufferSourceNodes=[],this.bufferSourceNode=null,this.buffer=null,this.playbackRate=1,this.input=l.audiocontext.createGain(),this.output=l.audiocontext.createGain(),this.reversed=!1,this.startTime=0,this.endTime=null,this.pauseTime=0,this.mode="sustain",this.startMillis=null,this.panPosition=0,this.panner=new t.Panner(this.output,l.input,2),(this.url||this.file)&&this.load(i,n),l.soundArray.push(this),"function"==typeof o?this._whileLoading=o:this._whileLoading=function(){},this._onAudioProcess=s.bind(this),this._clearOnEnd=p.bind(this)},t.prototype.registerPreloadMethod("loadSound",t.prototype),t.prototype.loadSound=function(e,i,n,o){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&window.alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS");var r=this,s=new t.SoundFile(e,function(){"function"==typeof i&&i.apply(r,arguments),"function"==typeof r._decrementPreload&&r._decrementPreload()},n,o);return s},t.SoundFile.prototype.load=function(t,e){var i=this,n=(new Error).stack;if(void 0!==this.url&&""!==this.url){var o=new XMLHttpRequest;o.addEventListener("progress",function(t){i._updateProgress(t)},!1),o.open("GET",this.url,!0),o.responseType="arraybuffer",o.onload=function(){if(200===o.status){if(!i.panner)return;f.decodeAudioData(o.response,function(e){i.panner&&(i.buffer=e,i.panner.inputChannels(e.numberOfChannels),t&&t(i))},function(){if(i.panner){var t=new h("decodeAudioData",n,i.url),o="AudioContext error at decodeAudioData for "+i.url;e?(t.msg=o,e(t)):console.error(o+"\n The error stack trace includes: \n"+t.stack)}})}else{if(!i.panner)return;var r=new h("loadSound",n,i.url),s="Unable to load "+i.url+". The request status was: "+o.status+" ("+o.statusText+")";e?(r.message=s,e(r)):console.error(s+"\n The error stack trace includes: \n"+r.stack)}},o.onerror=function(){var t=new h("loadSound",n,i.url),o="There was no response from the server at "+i.url+". Check the url and internet connectivity.";e?(t.message=o,e(t)):console.error(o+"\n The error stack trace includes: \n"+t.stack)},o.send()}else if(void 0!==this.file){var r=new FileReader;r.onload=function(){i.panner&&f.decodeAudioData(r.result,function(e){i.panner&&(i.buffer=e,i.panner.inputChannels(e.numberOfChannels),t&&t(i))})},r.onerror=function(t){i.panner&&onerror&&onerror(t)},r.readAsArrayBuffer(this.file)}},t.SoundFile.prototype._updateProgress=function(t){if(t.lengthComputable){var e=t.loaded/t.total*.99;this._whileLoading(e,t)}else this._whileLoading("size unknown")},t.SoundFile.prototype.isLoaded=function(){return this.buffer?!0:!1},t.SoundFile.prototype.play=function(t,e,i,n,o){if(!this.output)return void console.warn("SoundFile.play() called after dispose");var r,s,a=l.audiocontext.currentTime,u=t||0;if(0>u&&(u=0),u+=a,"undefined"!=typeof e&&this.rate(e),"undefined"!=typeof i&&this.setVolume(i),!this.buffer)throw"not ready to play file, buffer has yet to load. Try preload()";if(this._pauseTime=0,"restart"===this.mode&&this.buffer&&this.bufferSourceNode&&(this.bufferSourceNode.stop(u),this._counterNode.stop(u)),"untildone"!==this.mode||!this.isPlaying()){if(this.bufferSourceNode=this._initSourceNode(),delete this._counterNode,this._counterNode=this._initCounterNode(),n){if(!(n>=0&&nt&&!this.reversed?(t=Math.abs(t),e=!0):t>0&&this.reversed&&(e=!0),this.bufferSourceNode){var i=l.audiocontext.currentTime;this.bufferSourceNode.playbackRate.cancelScheduledValues(i),this.bufferSourceNode.playbackRate.linearRampToValueAtTime(Math.abs(t),i),this._counterNode.playbackRate.cancelScheduledValues(i),this._counterNode.playbackRate.linearRampToValueAtTime(Math.abs(t),i)}return e&&this.reverseBuffer(),this.playbackRate},t.SoundFile.prototype.setPitch=function(t){var e=d(t)/d(60);this.rate(e)},t.SoundFile.prototype.getPlaybackRate=function(){return this.playbackRate},t.SoundFile.prototype.duration=function(){return this.buffer?this.buffer.duration:0},t.SoundFile.prototype.currentTime=function(){return this.reversed?Math.abs(this._lastPos-this.buffer.length)/f.sampleRate:this._lastPos/f.sampleRate},t.SoundFile.prototype.jump=function(t,e){if(0>t||t>this.buffer.duration)throw"jump time out of range";if(e>this.buffer.duration-t)throw"end time out of range";var i=t||0,n=e||void 0;this.isPlaying()&&this.stop(0),this.play(0,this.playbackRate,this.output.gain.value,i,n); +},t.SoundFile.prototype.channels=function(){return this.buffer.numberOfChannels},t.SoundFile.prototype.sampleRate=function(){return this.buffer.sampleRate},t.SoundFile.prototype.frames=function(){return this.buffer.length},t.SoundFile.prototype.getPeaks=function(t){if(!this.buffer)throw"Cannot load peaks yet, buffer is not loaded";if(t||(t=5*window.width),this.buffer){for(var e=this.buffer,i=e.length/t,n=~~(i/10)||1,o=e.numberOfChannels,r=new Float32Array(Math.round(t)),s=0;o>s;s++)for(var a=e.getChannelData(s),u=0;t>u;u++){for(var c=~~(u*i),p=~~(c+i),h=0,l=c;p>l;l+=n){var f=a[l];f>h?h=f:-f>h&&(h=f)}(0===s||Math.abs(h)>r[u])&&(r[u]=h)}return r}},t.SoundFile.prototype.reverseBuffer=function(){if(!this.buffer)throw"SoundFile is not done loading";var t=this._lastPos/f.sampleRate,e=this.getVolume();this.setVolume(0,.001);const i=this.buffer.numberOfChannels;for(var n=0;i>n;n++)this.buffer.getChannelData(n).reverse();this.reversed=!this.reversed,t&&this.jump(this.duration()-t),this.setVolume(e,.001)},t.SoundFile.prototype.onended=function(t){return this._onended=t,this},t.SoundFile.prototype.add=function(){},t.SoundFile.prototype.dispose=function(){var t=l.audiocontext.currentTime,e=l.soundArray.indexOf(this);if(l.soundArray.splice(e,1),this.stop(t),this.buffer&&this.bufferSourceNode){for(var i=0;io;o++){var r=n.getChannelData(o);r.set(t[o])}this.buffer=n,this.panner.inputChannels(e)};var y=function(t){const e=t.length,i=f.createBuffer(1,t.length,f.sampleRate),n=i.getChannelData(0);for(var o=0;e>o;o++)n[o]=o;return i};t.SoundFile.prototype._initCounterNode=function(){var e=this,i=f.currentTime,n=f.createBufferSource();return e._scopeNode&&(e._scopeNode.disconnect(),e._scopeNode.removeEventListener("audioprocess",e._onAudioProcess),delete e._scopeNode),e._scopeNode=f.createScriptProcessor(256,1,1),n.buffer=y(e.buffer),n.playbackRate.setValueAtTime(e.playbackRate,i),n.connect(e._scopeNode),e._scopeNode.connect(t.soundOut._silentNode),e._scopeNode.addEventListener("audioprocess",e._onAudioProcess),n},t.SoundFile.prototype._initSourceNode=function(){var t=f.createBufferSource();return t.buffer=this.buffer,t.playbackRate.value=this.playbackRate,t.connect(this.output),t},t.SoundFile.prototype.processPeaks=function(t,r,s,a){var u=this.buffer.length,c=this.buffer.sampleRate,p=this.buffer,h=[],l=r||.9,f=l,d=s||.22,m=a||200,y=new window.OfflineAudioContext(1,u,c),v=y.createBufferSource();v.buffer=p;var g=y.createBiquadFilter();g.type="lowpass",v.connect(g),g.connect(y.destination),v.start(0),y.startRendering(),y.oncomplete=function(r){if(self.panner){var s=r.renderedBuffer,a=s.getChannelData(0);do h=e(a,f),f-=.005;while(Object.keys(h).length=d);var u=i(h),c=n(u,s.sampleRate),p=c.sort(function(t,e){return e.count-t.count}).splice(0,5);this.tempo=p[0].tempo;var l=5,y=o(h,p[0].tempo,s.sampleRate,l);t(y)}}};var v=function(t,e){this.sampleIndex=e,this.amplitude=t,this.tempos=[],this.intervals=[]},g=function(t,e,i,n){this.callback=t,this.time=e,this.id=i,this.val=n};t.SoundFile.prototype.addCue=function(t,e,i){var n=this._cueIDCounter++,o=new g(e,t,n,i);return this._cues.push(o),n},t.SoundFile.prototype.removeCue=function(t){for(var e=this._cues.length,i=0;e>i;i++){var n=this._cues[i];if(n.id===t){this._cues.splice(i,1);break}}0===this._cues.length},t.SoundFile.prototype.clearCues=function(){this._cues=[]},t.SoundFile.prototype._onTimeUpdate=function(t){for(var e=t/this.buffer.sampleRate,i=this._cues.length,n=0;i>n;n++){var o=this._cues[n],r=o.time,s=o.val;this._prevTime=r&&o.callback(s)}this._prevTime=e},t.SoundFile.prototype.save=function(e){const i=m(this.buffer);t.prototype.saveSound([i],e,"wav")},t.SoundFile.prototype.getBlob=function(){const t=m(this.buffer);return new Blob([t],{type:"audio/wav"})}}(c,a,u,u);var l;l=function(){var e=a;t.Amplitude=function(t){this.bufferSize=2048,this.audiocontext=e.audiocontext,this.processor=this.audiocontext.createScriptProcessor(this.bufferSize,2,1),this.input=this.processor,this.output=this.audiocontext.createGain(),this.smoothing=t||0,this.volume=0,this.average=0,this.stereoVol=[0,0],this.stereoAvg=[0,0],this.stereoVolNorm=[0,0],this.volMax=.001,this.normalize=!1,this.processor.onaudioprocess=this._audioProcess.bind(this),this.processor.connect(this.output),this.output.gain.value=0,this.output.connect(this.audiocontext.destination),e.meter.connect(this.processor),e.soundArray.push(this)},t.Amplitude.prototype.setInput=function(i,n){e.meter.disconnect(),n&&(this.smoothing=n),null==i?(console.log("Amplitude input source is not ready! Connecting to master output instead"),e.meter.connect(this.processor)):i instanceof t.Signal?i.output.connect(this.processor):i?(i.connect(this.processor),this.processor.disconnect(),this.processor.connect(this.output)):e.meter.connect(this.processor)},t.Amplitude.prototype.connect=function(t){t?t.hasOwnProperty("input")?this.output.connect(t.input):this.output.connect(t):this.output.connect(this.panner.connect(e.input))},t.Amplitude.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.Amplitude.prototype._audioProcess=function(t){for(var e=0;ea;a++)i=n[a],this.normalize?(r+=Math.max(Math.min(i/this.volMax,1),-1),s+=Math.max(Math.min(i/this.volMax,1),-1)*Math.max(Math.min(i/this.volMax,1),-1)):(r+=i,s+=i*i);var u=r/o,c=Math.sqrt(s/o);this.stereoVol[e]=Math.max(c,this.stereoVol[e]*this.smoothing),this.stereoAvg[e]=Math.max(u,this.stereoVol[e]*this.smoothing),this.volMax=Math.max(this.stereoVol[e],this.volMax)}var p=this,h=this.stereoVol.reduce(function(t,e,i){return p.stereoVolNorm[i-1]=Math.max(Math.min(p.stereoVol[i-1]/p.volMax,1),0),p.stereoVolNorm[i]=Math.max(Math.min(p.stereoVol[i]/p.volMax,1),0),t+e});this.volume=h/this.stereoVol.length,this.volNorm=Math.max(Math.min(this.volume/this.volMax,1),0)},t.Amplitude.prototype.getLevel=function(t){return"undefined"!=typeof t?this.normalize?this.stereoVolNorm[t]:this.stereoVol[t]:this.normalize?this.volNorm:this.volume},t.Amplitude.prototype.toggleNormalize=function(t){"boolean"==typeof t?this.normalize=t:this.normalize=!this.normalize},t.Amplitude.prototype.smooth=function(t){t>=0&&1>t?this.smoothing=t:console.log("Error: smoothing must be between 0 and 1")},t.Amplitude.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.input&&(this.input.disconnect(),delete this.input),this.output&&(this.output.disconnect(),delete this.output),delete this.processor}}(a);var f;f=function(){var e=a;t.FFT=function(t,i){this.input=this.analyser=e.audiocontext.createAnalyser(),Object.defineProperties(this,{bins:{get:function(){return this.analyser.fftSize/2},set:function(t){this.analyser.fftSize=2*t},configurable:!0,enumerable:!0},smoothing:{get:function(){return this.analyser.smoothingTimeConstant},set:function(t){this.analyser.smoothingTimeConstant=t},configurable:!0,enumerable:!0}}),this.smooth(t),this.bins=i||1024,e.fftMeter.connect(this.analyser),this.freqDomain=new Uint8Array(this.analyser.frequencyBinCount),this.timeDomain=new Uint8Array(this.analyser.frequencyBinCount),this.bass=[20,140],this.lowMid=[140,400],this.mid=[400,2600],this.highMid=[2600,5200],this.treble=[5200,14e3],e.soundArray.push(this)},t.FFT.prototype.setInput=function(t){t?(t.output?t.output.connect(this.analyser):t.connect&&t.connect(this.analyser),e.fftMeter.disconnect()):e.fftMeter.connect(this.analyser)},t.FFT.prototype.waveform=function(){for(var e,i,n,s=0;si){var o=i;i=t,t=o}for(var r=Math.round(t/n*this.freqDomain.length),s=Math.round(i/n*this.freqDomain.length),a=0,u=0,c=r;s>=c;c++)a+=this.freqDomain[c],u+=1;var p=a/u;return p}throw"invalid input for getEnergy()"}var h=Math.round(t/n*this.freqDomain.length);return this.freqDomain[h]},t.FFT.prototype.getFreq=function(t,e){console.log("getFreq() is deprecated. Please use getEnergy() instead.");var i=this.getEnergy(t,e);return i},t.FFT.prototype.getCentroid=function(){for(var t=e.audiocontext.sampleRate/2,i=0,n=0,o=0;os;s++)o[r]=void 0!==o[r]?(o[r]+e[s])/2:e[s],s%n===n-1&&r++;return o},t.FFT.prototype.logAverages=function(t){for(var i=e.audiocontext.sampleRate/2,n=this.freqDomain,o=n.length,r=new Array(t.length),s=0,a=0;o>a;a++){var u=Math.round(a*i/this.freqDomain.length);u>t[s].hi&&s++,r[s]=void 0!==r[s]?(r[s]+n[a])/2:n[a]}return r},t.FFT.prototype.getOctaveBands=function(t,i){var t=t||3,i=i||15.625,n=[],o={lo:i/Math.pow(2,1/(2*t)),ctr:i,hi:i*Math.pow(2,1/(2*t))};n.push(o);for(var r=e.audiocontext.sampleRate/2;o.hie;e++){var n=e/(i-1)*2-1;this._curve[e]=t(n,e)}return this._shaper.curve=this._curve,this},Object.defineProperty(t.WaveShaper.prototype,"curve",{get:function(){return this._shaper.curve},set:function(t){this._curve=new Float32Array(t),this._shaper.curve=this._curve}}),Object.defineProperty(t.WaveShaper.prototype,"oversample",{get:function(){return this._shaper.oversample},set:function(t){if(-1===["none","2x","4x"].indexOf(t))throw new RangeError("Tone.WaveShaper: oversampling must be either 'none', '2x', or '4x'");this._shaper.oversample=t}}),t.WaveShaper.prototype.dispose=function(){return t.prototype.dispose.call(this),this._shaper.disconnect(),this._shaper=null,this._curve=null,this},t.WaveShaper}(n);var y;y=function(t){return t.TimeBase=function(e,i){if(!(this instanceof t.TimeBase))return new t.TimeBase(e,i);if(this._expr=this._noOp,e instanceof t.TimeBase)this.copy(e);else if(!this.isUndef(i)||this.isNumber(e)){i=this.defaultArg(i,this._defaultUnits);var n=this._primaryExpressions[i].method;this._expr=n.bind(this,e)}else this.isString(e)?this.set(e):this.isUndef(e)&&(this._expr=this._defaultExpr())},t.extend(t.TimeBase),t.TimeBase.prototype.set=function(t){return this._expr=this._parseExprString(t),this},t.TimeBase.prototype.clone=function(){var t=new this.constructor;return t.copy(this),t},t.TimeBase.prototype.copy=function(t){var e=t._expr();return this.set(e)},t.TimeBase.prototype._primaryExpressions={n:{regexp:/^(\d+)n/i,method:function(t){return t=parseInt(t),1===t?this._beatsToUnits(this._timeSignature()):this._beatsToUnits(4/t)}},t:{regexp:/^(\d+)t/i,method:function(t){return t=parseInt(t),this._beatsToUnits(8/(3*parseInt(t)))}},m:{regexp:/^(\d+)m/i,method:function(t){return this._beatsToUnits(parseInt(t)*this._timeSignature())}},i:{regexp:/^(\d+)i/i,method:function(t){return this._ticksToUnits(parseInt(t))}},hz:{regexp:/^(\d+(?:\.\d+)?)hz/i,method:function(t){return this._frequencyToUnits(parseFloat(t))}},tr:{regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method:function(t,e,i){var n=0;return t&&"0"!==t&&(n+=this._beatsToUnits(this._timeSignature()*parseFloat(t))),e&&"0"!==e&&(n+=this._beatsToUnits(parseFloat(e))),i&&"0"!==i&&(n+=this._beatsToUnits(parseFloat(i)/4)),n}},s:{regexp:/^(\d+(?:\.\d+)?s)/,method:function(t){return this._secondsToUnits(parseFloat(t))}},samples:{regexp:/^(\d+)samples/,method:function(t){return parseInt(t)/this.context.sampleRate}},"default":{regexp:/^(\d+(?:\.\d+)?)/,method:function(t){return this._primaryExpressions[this._defaultUnits].method.call(this,t)}}},t.TimeBase.prototype._binaryExpressions={"+":{regexp:/^\+/,precedence:2,method:function(t,e){return t()+e()}},"-":{regexp:/^\-/,precedence:2,method:function(t,e){return t()-e()}},"*":{regexp:/^\*/,precedence:1,method:function(t,e){return t()*e()}},"/":{regexp:/^\//,precedence:1,method:function(t,e){return t()/e()}}},t.TimeBase.prototype._unaryExpressions={neg:{regexp:/^\-/,method:function(t){return-t()}}},t.TimeBase.prototype._syntaxGlue={"(":{regexp:/^\(/},")":{regexp:/^\)/}},t.TimeBase.prototype._tokenize=function(t){function e(t,e){for(var i=["_binaryExpressions","_unaryExpressions","_primaryExpressions","_syntaxGlue"],n=0;n0;){t=t.trim();var o=e(t,this);n.push(o),t=t.substr(o.value.length)}return{next:function(){return n[++i]},peek:function(){return n[i+1]}}},t.TimeBase.prototype._matchGroup=function(t,e,i){var n=!1;if(!this.isUndef(t))for(var o in e){var r=e[o];if(r.regexp.test(t.value)){if(this.isUndef(i))return r;if(r.precedence===i)return r}}return n},t.TimeBase.prototype._parseBinary=function(t,e){this.isUndef(e)&&(e=2);var i;i=0>e?this._parseUnary(t):this._parseBinary(t,e-1);for(var n=t.peek();n&&this._matchGroup(n,this._binaryExpressions,e);)n=t.next(),i=n.method.bind(this,i,this._parseBinary(t,e-1)),n=t.peek();return i},t.TimeBase.prototype._parseUnary=function(t){var e,i;e=t.peek();var n=this._matchGroup(e,this._unaryExpressions);return n?(e=t.next(),i=this._parseUnary(t),n.method.bind(this,i)):this._parsePrimary(t)},t.TimeBase.prototype._parsePrimary=function(t){var e,i;if(e=t.peek(),this.isUndef(e))throw new SyntaxError("Tone.TimeBase: Unexpected end of expression");if(this._matchGroup(e,this._primaryExpressions)){e=t.next();var n=e.value.match(e.regexp);return e.method.bind(this,n[1],n[2],n[3])}if(e&&"("===e.value){if(t.next(),i=this._parseBinary(t),e=t.next(),!e||")"!==e.value)throw new SyntaxError("Expected )");return i}throw new SyntaxError("Tone.TimeBase: Cannot process token "+e.value)},t.TimeBase.prototype._parseExprString=function(t){this.isString(t)||(t=t.toString());var e=this._tokenize(t),i=this._parseBinary(e);return i},t.TimeBase.prototype._noOp=function(){return 0},t.TimeBase.prototype._defaultExpr=function(){return this._noOp},t.TimeBase.prototype._defaultUnits="s",t.TimeBase.prototype._frequencyToUnits=function(t){return 1/t},t.TimeBase.prototype._beatsToUnits=function(e){return 60/t.Transport.bpm.value*e},t.TimeBase.prototype._secondsToUnits=function(t){return t},t.TimeBase.prototype._ticksToUnits=function(e){return e*(this._beatsToUnits(1)/t.Transport.PPQ)},t.TimeBase.prototype._timeSignature=function(){return t.Transport.timeSignature},t.TimeBase.prototype._pushExpr=function(e,i,n){return e instanceof t.TimeBase||(e=new this.constructor(e,n)),this._expr=this._binaryExpressions[i].method.bind(this,this._expr,e._expr),this},t.TimeBase.prototype.add=function(t,e){return this._pushExpr(t,"+",e)},t.TimeBase.prototype.sub=function(t,e){return this._pushExpr(t,"-",e)},t.TimeBase.prototype.mult=function(t,e){return this._pushExpr(t,"*",e)},t.TimeBase.prototype.div=function(t,e){return this._pushExpr(t,"/",e)},t.TimeBase.prototype.valueOf=function(){return this._expr()},t.TimeBase.prototype.dispose=function(){this._expr=null},t.TimeBase}(n);var v;v=function(t){return t.Time=function(e,i){return this instanceof t.Time?(this._plusNow=!1,void t.TimeBase.call(this,e,i)):new t.Time(e,i)},t.extend(t.Time,t.TimeBase),t.Time.prototype._unaryExpressions=Object.create(t.TimeBase.prototype._unaryExpressions),t.Time.prototype._unaryExpressions.quantize={regexp:/^@/,method:function(e){return t.Transport.nextSubdivision(e())}},t.Time.prototype._unaryExpressions.now={regexp:/^\+/,method:function(t){return this._plusNow=!0,t()}},t.Time.prototype.quantize=function(t,e){return e=this.defaultArg(e,1),this._expr=function(t,e,i){t=t(),e=e.toSeconds();var n=Math.round(t/e),o=n*e,r=o-t;return t+r*i}.bind(this,this._expr,new this.constructor(t),e),this},t.Time.prototype.addNow=function(){return this._plusNow=!0,this},t.Time.prototype._defaultExpr=function(){return this._plusNow=!0,this._noOp},t.Time.prototype.copy=function(e){return t.TimeBase.prototype.copy.call(this,e),this._plusNow=e._plusNow,this},t.Time.prototype.toNotation=function(){var t=this.toSeconds(),e=["1m","2n","4n","8n","16n","32n","64n","128n"],i=this._toNotationHelper(t,e),n=["1m","2n","2t","4n","4t","8n","8t","16n","16t","32n","32t","64n","64t","128n"],o=this._toNotationHelper(t,n);return o.split("+").length1-s%1&&(s+=a),s=Math.floor(s),s>0){if(n+=1===s?e[o]:s.toString()+"*"+e[o],t-=s*r,i>t)break;n+=" + "}}return""===n&&(n="0"),n},t.Time.prototype._notationToUnits=function(t){for(var e=this._primaryExpressions,i=[e.n,e.t,e.m],n=0;n3&&(n=parseFloat(n).toFixed(3));var o=[i,e,n];return o.join(":")},t.Time.prototype.toTicks=function(){var e=this._beatsToUnits(1),i=this.valueOf()/e;return Math.floor(i*t.Transport.PPQ)},t.Time.prototype.toSamples=function(){return this.toSeconds()*this.context.sampleRate},t.Time.prototype.toFrequency=function(){return 1/this.toSeconds()},t.Time.prototype.toSeconds=function(){return this.valueOf()},t.Time.prototype.toMilliseconds=function(){return 1e3*this.toSeconds()},t.Time.prototype.valueOf=function(){var t=this._expr();return t+(this._plusNow?this.now():0)},t.Time}(n);var g;g=function(t){t.Frequency=function(e,i){return this instanceof t.Frequency?void t.TimeBase.call(this,e,i):new t.Frequency(e,i)},t.extend(t.Frequency,t.TimeBase),t.Frequency.prototype._primaryExpressions=Object.create(t.TimeBase.prototype._primaryExpressions),t.Frequency.prototype._primaryExpressions.midi={regexp:/^(\d+(?:\.\d+)?midi)/,method:function(t){return this.midiToFrequency(t)}},t.Frequency.prototype._primaryExpressions.note={regexp:/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,method:function(t,i){var n=e[t.toLowerCase()],o=n+12*(parseInt(i)+1);return this.midiToFrequency(o)}},t.Frequency.prototype._primaryExpressions.tr={regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method:function(t,e,i){var n=1;return t&&"0"!==t&&(n*=this._beatsToUnits(this._timeSignature()*parseFloat(t))),e&&"0"!==e&&(n*=this._beatsToUnits(parseFloat(e))),i&&"0"!==i&&(n*=this._beatsToUnits(parseFloat(i)/4)),n}},t.Frequency.prototype.transpose=function(t){return this._expr=function(t,e){var i=t();return i*this.intervalToFrequencyRatio(e)}.bind(this,this._expr,t),this},t.Frequency.prototype.harmonize=function(t){return this._expr=function(t,e){for(var i=t(),n=[],o=0;or&&(o+=-12*r);var s=i[o%12];return s+r.toString()},t.Frequency.prototype.toSeconds=function(){return 1/this.valueOf()},t.Frequency.prototype.toFrequency=function(){return this.valueOf()},t.Frequency.prototype.toTicks=function(){var e=this._beatsToUnits(1),i=this.valueOf()/e;return Math.floor(i*t.Transport.PPQ)},t.Frequency.prototype._frequencyToUnits=function(t){return t},t.Frequency.prototype._ticksToUnits=function(e){return 1/(60*e/(t.Transport.bpm.value*t.Transport.PPQ))},t.Frequency.prototype._beatsToUnits=function(e){return 1/t.TimeBase.prototype._beatsToUnits.call(this,e)},t.Frequency.prototype._secondsToUnits=function(t){return 1/t},t.Frequency.prototype._defaultUnits="hz";var e={cbb:-2,cb:-1,c:0,"c#":1,cx:2,dbb:0,db:1,d:2,"d#":3,dx:4,ebb:2,eb:3,e:4,"e#":5,ex:6,fbb:3,fb:4,f:5,"f#":6,fx:7,gbb:5,gb:6,g:7,"g#":8,gx:9,abb:7,ab:8,a:9,"a#":10,ax:11,bbb:9,bb:10,b:11,"b#":12,bx:13},i=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];return t.Frequency.A4=440,t.Frequency.prototype.midiToFrequency=function(e){return t.Frequency.A4*Math.pow(2,(e-69)/12)},t.Frequency.prototype.frequencyToMidi=function(e){return 69+12*Math.log(e/t.Frequency.A4)/Math.LN2},t.Frequency}(n);var _;_=function(t){return t.TransportTime=function(e,i){return this instanceof t.TransportTime?void t.Time.call(this,e,i):new t.TransportTime(e,i)},t.extend(t.TransportTime,t.Time),t.TransportTime.prototype._unaryExpressions=Object.create(t.Time.prototype._unaryExpressions),t.TransportTime.prototype._unaryExpressions.quantize={regexp:/^@/,method:function(e){var i=this._secondsToTicks(e()),n=Math.ceil(t.Transport.ticks/i);return this._ticksToUnits(n*i)}},t.TransportTime.prototype._secondsToTicks=function(e){var i=this._beatsToUnits(1),n=e/i;return Math.round(n*t.Transport.PPQ)},t.TransportTime.prototype.valueOf=function(){var e=this._secondsToTicks(this._expr());return e+(this._plusNow?t.Transport.ticks:0)},t.TransportTime.prototype.toTicks=function(){return this.valueOf()},t.TransportTime.prototype.toSeconds=function(){var e=this._expr();return e+(this._plusNow?t.Transport.seconds:0)},t.TransportTime.prototype.toFrequency=function(){return 1/this.toSeconds()},t.TransportTime}(n);var T;T=function(t){return t.Type={Default:"number",Time:"time",Frequency:"frequency",TransportTime:"transportTime",Ticks:"ticks",NormalRange:"normalRange",AudioRange:"audioRange",Decibels:"db",Interval:"interval",BPM:"bpm",Positive:"positive",Cents:"cents",Degrees:"degrees",MIDI:"midi",BarsBeatsSixteenths:"barsBeatsSixteenths",Samples:"samples",Hertz:"hertz",Note:"note",Milliseconds:"milliseconds",Seconds:"seconds",Notation:"notation"},t.prototype.toSeconds=function(e){return this.isNumber(e)?e:this.isUndef(e)?this.now():this.isString(e)?new t.Time(e).toSeconds():e instanceof t.TimeBase?e.toSeconds():void 0},t.prototype.toFrequency=function(e){return this.isNumber(e)?e:this.isString(e)||this.isUndef(e)?new t.Frequency(e).valueOf():e instanceof t.TimeBase?e.toFrequency():void 0},t.prototype.toTicks=function(e){return this.isNumber(e)||this.isString(e)?new t.TransportTime(e).toTicks():this.isUndef(e)?t.Transport.ticks:e instanceof t.TimeBase?e.toTicks():void 0},t}(n,v,g,_);var b;b=function(t){"use strict";return t.Param=function(){var e=this.optionsObject(arguments,["param","units","convert"],t.Param.defaults);this._param=this.input=e.param,this.units=e.units,this.convert=e.convert,this.overridden=!1,this._lfo=null,this.isObject(e.lfo)?this.value=e.lfo:this.isUndef(e.value)||(this.value=e.value)},t.extend(t.Param),t.Param.defaults={units:t.Type.Default,convert:!0,param:void 0},Object.defineProperty(t.Param.prototype,"value",{get:function(){return this._toUnits(this._param.value)},set:function(e){if(this.isObject(e)){if(this.isUndef(t.LFO))throw new Error("Include 'Tone.LFO' to use an LFO as a Param value.");this._lfo&&this._lfo.dispose(),this._lfo=new t.LFO(e).start(),this._lfo.connect(this.input)}else{var i=this._fromUnits(e);this._param.cancelScheduledValues(0),this._param.value=i}}}),t.Param.prototype._fromUnits=function(e){if(!this.convert&&!this.isUndef(this.convert))return e;switch(this.units){case t.Type.Time:return this.toSeconds(e);case t.Type.Frequency:return this.toFrequency(e);case t.Type.Decibels:return this.dbToGain(e);case t.Type.NormalRange:return Math.min(Math.max(e,0),1);case t.Type.AudioRange:return Math.min(Math.max(e,-1),1);case t.Type.Positive:return Math.max(e,0);default:return e}},t.Param.prototype._toUnits=function(e){if(!this.convert&&!this.isUndef(this.convert))return e;switch(this.units){case t.Type.Decibels:return this.gainToDb(e);default:return e}},t.Param.prototype._minOutput=1e-5,t.Param.prototype.setValueAtTime=function(t,e){return t=this._fromUnits(t),e=this.toSeconds(e),e<=this.now()+this.blockTime?this._param.value=t:this._param.setValueAtTime(t,e),this},t.Param.prototype.setRampPoint=function(t){t=this.defaultArg(t,this.now());var e=this._param.value;return 0===e&&(e=this._minOutput),this._param.setValueAtTime(e,t),this},t.Param.prototype.linearRampToValueAtTime=function(t,e){return t=this._fromUnits(t),this._param.linearRampToValueAtTime(t,this.toSeconds(e)),this},t.Param.prototype.exponentialRampToValueAtTime=function(t,e){return t=this._fromUnits(t),t=Math.max(this._minOutput,t),this._param.exponentialRampToValueAtTime(t,this.toSeconds(e)),this},t.Param.prototype.exponentialRampToValue=function(t,e,i){return i=this.toSeconds(i),this.setRampPoint(i),this.exponentialRampToValueAtTime(t,i+this.toSeconds(e)),this},t.Param.prototype.linearRampToValue=function(t,e,i){return i=this.toSeconds(i),this.setRampPoint(i),this.linearRampToValueAtTime(t,i+this.toSeconds(e)),this},t.Param.prototype.setTargetAtTime=function(t,e,i){return t=this._fromUnits(t),t=Math.max(this._minOutput,t),i=Math.max(this._minOutput,i),this._param.setTargetAtTime(t,this.toSeconds(e),i),this},t.Param.prototype.setValueCurveAtTime=function(t,e,i){for(var n=0;n1&&(this.input=new Array(e)),1===i?this.output=new t.Gain:i>1&&(this.output=new Array(e))},t.Gain}(n,b);var S;S=function(t){"use strict";return t.Signal=function(){var e=this.optionsObject(arguments,["value","units"],t.Signal.defaults);this.output=this._gain=this.context.createGain(),e.param=this._gain.gain,t.Param.call(this,e),this.input=this._param=this._gain.gain,this.context.getConstant(1).chain(this._gain)},t.extend(t.Signal,t.Param),t.Signal.defaults={value:0,units:t.Type.Default,convert:!0},t.Signal.prototype.connect=t.SignalBase.prototype.connect,t.Signal.prototype.dispose=function(){return t.Param.prototype.dispose.call(this),this._param=null,this._gain.disconnect(),this._gain=null,this},t.Signal}(n,m,T,b);var w;w=function(t){"use strict";return t.Add=function(e){this.createInsOuts(2,0),this._sum=this.input[0]=this.input[1]=this.output=new t.Gain,this._param=this.input[1]=new t.Signal(e),this._param.connect(this._sum)},t.extend(t.Add,t.Signal),t.Add.prototype.dispose=function(){return t.prototype.dispose.call(this),this._sum.dispose(),this._sum=null,this._param.dispose(),this._param=null,this},t.Add}(n,S);var A;A=function(t){"use strict";return t.Multiply=function(e){this.createInsOuts(2,0),this._mult=this.input[0]=this.output=new t.Gain,this._param=this.input[1]=this.output.gain,this._param.value=this.defaultArg(e,0)},t.extend(t.Multiply,t.Signal),t.Multiply.prototype.dispose=function(){return t.prototype.dispose.call(this),this._mult.dispose(),this._mult=null, +this._param=null,this},t.Multiply}(n,S);var P;P=function(t){"use strict";return t.Scale=function(e,i){this._outputMin=this.defaultArg(e,0),this._outputMax=this.defaultArg(i,1),this._scale=this.input=new t.Multiply(1),this._add=this.output=new t.Add(0),this._scale.connect(this._add),this._setRange()},t.extend(t.Scale,t.SignalBase),Object.defineProperty(t.Scale.prototype,"min",{get:function(){return this._outputMin},set:function(t){this._outputMin=t,this._setRange()}}),Object.defineProperty(t.Scale.prototype,"max",{get:function(){return this._outputMax},set:function(t){this._outputMax=t,this._setRange()}}),t.Scale.prototype._setRange=function(){this._add.value=this._outputMin,this._scale.value=this._outputMax-this._outputMin},t.Scale.prototype.dispose=function(){return t.prototype.dispose.call(this),this._add.dispose(),this._add=null,this._scale.dispose(),this._scale=null,this},t.Scale}(n,w,A);var k;k=function(){var e=S,i=w,n=A,o=P;t.Signal=function(t){var i=new e(t);return i},e.prototype.fade=e.prototype.linearRampToValueAtTime,n.prototype.fade=e.prototype.fade,i.prototype.fade=e.prototype.fade,o.prototype.fade=e.prototype.fade,e.prototype.setInput=function(t){t.connect(this)},n.prototype.setInput=e.prototype.setInput,i.prototype.setInput=e.prototype.setInput,o.prototype.setInput=e.prototype.setInput,e.prototype.add=function(t){var e=new i(t);return this.connect(e),e},n.prototype.add=e.prototype.add,i.prototype.add=e.prototype.add,o.prototype.add=e.prototype.add,e.prototype.mult=function(t){var e=new n(t);return this.connect(e),e},n.prototype.mult=e.prototype.mult,i.prototype.mult=e.prototype.mult,o.prototype.mult=e.prototype.mult,e.prototype.scale=function(e,i,n,r){var s,a;4===arguments.length?(s=t.prototype.map(n,e,i,0,1)-.5,a=t.prototype.map(r,e,i,0,1)-.5):(s=arguments[0],a=arguments[1]);var u=new o(s,a);return this.connect(u),u},n.prototype.scale=e.prototype.scale,i.prototype.scale=e.prototype.scale,o.prototype.scale=e.prototype.scale}(S,w,A,P);var O;O=function(){var e=a,i=w,n=A,o=P;t.Oscillator=function(i,n){if("string"==typeof i){var o=n;n=i,i=o}if("number"==typeof n){var o=n;n=i,i=o}this.started=!1,this.phaseAmount=void 0,this.oscillator=e.audiocontext.createOscillator(),this.f=i||440,this.oscillator.type=n||"sine",this.oscillator.frequency.setValueAtTime(this.f,e.audiocontext.currentTime),this.output=e.audiocontext.createGain(),this._freqMods=[],this.output.gain.value=.5,this.output.gain.setValueAtTime(.5,e.audiocontext.currentTime),this.oscillator.connect(this.output),this.panPosition=0,this.connection=e.input,this.panner=new t.Panner(this.output,this.connection,1),this.mathOps=[this.output],e.soundArray.push(this)},t.Oscillator.prototype.start=function(t,i){if(this.started){var n=e.audiocontext.currentTime;this.stop(n)}if(!this.started){var o=i||this.f,r=this.oscillator.type;this.oscillator&&(this.oscillator.disconnect(),delete this.oscillator),this.oscillator=e.audiocontext.createOscillator(),this.oscillator.frequency.value=Math.abs(o),this.oscillator.type=r,this.oscillator.connect(this.output),t=t||0,this.oscillator.start(t+e.audiocontext.currentTime),this.freqNode=this.oscillator.frequency;for(var s in this._freqMods)"undefined"!=typeof this._freqMods[s].connect&&this._freqMods[s].connect(this.oscillator.frequency);this.started=!0}},t.Oscillator.prototype.stop=function(t){if(this.started){var i=t||0,n=e.audiocontext.currentTime;this.oscillator.stop(i+n),this.started=!1}},t.Oscillator.prototype.amp=function(t,i,n){var o=this;if("number"==typeof t){var i=i||0,n=n||0,r=e.audiocontext.currentTime;this.output.gain.linearRampToValueAtTime(t,r+n+i)}else{if(!t)return this.output.gain;t.connect(o.output.gain)}},t.Oscillator.prototype.fade=t.Oscillator.prototype.amp,t.Oscillator.prototype.getAmp=function(){return this.output.gain.value},t.Oscillator.prototype.freq=function(t,i,n){if("number"!=typeof t||isNaN(t)){if(!t)return this.oscillator.frequency;t.output&&(t=t.output),t.connect(this.oscillator.frequency),this._freqMods.push(t)}else{this.f=t;var o=e.audiocontext.currentTime,i=i||0,n=n||0;0===i?this.oscillator.frequency.setValueAtTime(t,n+o):t>0?this.oscillator.frequency.exponentialRampToValueAtTime(t,n+i+o):this.oscillator.frequency.linearRampToValueAtTime(t,n+i+o),this.phaseAmount&&this.phase(this.phaseAmount)}},t.Oscillator.prototype.getFreq=function(){return this.oscillator.frequency.value},t.Oscillator.prototype.setType=function(t){this.oscillator.type=t},t.Oscillator.prototype.getType=function(){return this.oscillator.type},t.Oscillator.prototype.connect=function(t){t?t.hasOwnProperty("input")?(this.panner.connect(t.input),this.connection=t.input):(this.panner.connect(t),this.connection=t):this.panner.connect(e.input)},t.Oscillator.prototype.disconnect=function(){this.output&&this.output.disconnect(),this.panner&&(this.panner.disconnect(),this.output&&this.output.connect(this.panner)),this.oscMods=[]},t.Oscillator.prototype.pan=function(t,e){this.panPosition=t,this.panner.pan(t,e)},t.Oscillator.prototype.getPan=function(){return this.panPosition},t.Oscillator.prototype.dispose=function(){var t=e.soundArray.indexOf(this);if(e.soundArray.splice(t,1),this.oscillator){var i=e.audiocontext.currentTime;this.stop(i),this.disconnect(),this.panner=null,this.oscillator=null}this.osc2&&this.osc2.dispose()},t.Oscillator.prototype.phase=function(i){var n=t.prototype.map(i,0,1,0,1/this.f),o=e.audiocontext.currentTime;this.phaseAmount=i,this.dNode||(this.dNode=e.audiocontext.createDelay(),this.oscillator.disconnect(),this.oscillator.connect(this.dNode),this.dNode.connect(this.output)),this.dNode.delayTime.setValueAtTime(n,o)};var r=function(t,e,i,n,o){var r=t.oscillator;for(var s in t.mathOps)t.mathOps[s]instanceof o&&(r.disconnect(),t.mathOps[s].dispose(),i=s,i0&&(r=t.mathOps[s-1]),r.disconnect(),r.connect(e),e.connect(n),t.mathOps[i]=e,t};t.Oscillator.prototype.add=function(t){var e=new i(t),n=this.mathOps.length-1,o=this.output;return r(this,e,n,o,i)},t.Oscillator.prototype.mult=function(t){var e=new n(t),i=this.mathOps.length-1,o=this.output;return r(this,e,i,o,n)},t.Oscillator.prototype.scale=function(e,i,n,s){var a,u;4===arguments.length?(a=t.prototype.map(n,e,i,0,1)-.5,u=t.prototype.map(s,e,i,0,1)-.5):(a=arguments[0],u=arguments[1]);var c=new o(a,u),p=this.mathOps.length-1,h=this.output;return r(this,c,p,h,o)},t.SinOsc=function(e){t.Oscillator.call(this,e,"sine")},t.SinOsc.prototype=Object.create(t.Oscillator.prototype),t.TriOsc=function(e){t.Oscillator.call(this,e,"triangle")},t.TriOsc.prototype=Object.create(t.Oscillator.prototype),t.SawOsc=function(e){t.Oscillator.call(this,e,"sawtooth")},t.SawOsc.prototype=Object.create(t.Oscillator.prototype),t.SqrOsc=function(e){t.Oscillator.call(this,e,"square")},t.SqrOsc.prototype=Object.create(t.Oscillator.prototype)}(a,w,A,P);var F;F=function(t){"use strict";return t.Timeline=function(){var e=this.optionsObject(arguments,["memory"],t.Timeline.defaults);this._timeline=[],this._toRemove=[],this._iterating=!1,this.memory=e.memory},t.extend(t.Timeline),t.Timeline.defaults={memory:1/0},Object.defineProperty(t.Timeline.prototype,"length",{get:function(){return this._timeline.length}}),t.Timeline.prototype.add=function(t){if(this.isUndef(t.time))throw new Error("Tone.Timeline: events must have a time attribute");if(this._timeline.length){var e=this._search(t.time);this._timeline.splice(e+1,0,t)}else this._timeline.push(t);if(this.length>this.memory){var i=this.length-this.memory;this._timeline.splice(0,i)}return this},t.Timeline.prototype.remove=function(t){if(this._iterating)this._toRemove.push(t);else{var e=this._timeline.indexOf(t);-1!==e&&this._timeline.splice(e,1)}return this},t.Timeline.prototype.get=function(t){var e=this._search(t);return-1!==e?this._timeline[e]:null},t.Timeline.prototype.peek=function(){return this._timeline[0]},t.Timeline.prototype.shift=function(){return this._timeline.shift()},t.Timeline.prototype.getAfter=function(t){var e=this._search(t);return e+10&&this._timeline[e-1].time=0?this._timeline[i-1]:null},t.Timeline.prototype.cancel=function(t){if(this._timeline.length>1){var e=this._search(t);if(e>=0)if(this._timeline[e].time===t){for(var i=e;i>=0&&this._timeline[i].time===t;i--)e=i;this._timeline=this._timeline.slice(0,e)}else this._timeline=this._timeline.slice(0,e+1);else this._timeline=[]}else 1===this._timeline.length&&this._timeline[0].time>=t&&(this._timeline=[]);return this},t.Timeline.prototype.cancelBefore=function(t){if(this._timeline.length){var e=this._search(t);e>=0&&(this._timeline=this._timeline.slice(e+1))}return this},t.Timeline.prototype._search=function(t){var e=0,i=this._timeline.length,n=i;if(i>0&&this._timeline[i-1].time<=t)return i-1;for(;n>e;){var o=Math.floor(e+(n-e)/2),r=this._timeline[o],s=this._timeline[o+1];if(r.time===t){for(var a=o;at)return o;r.time>t?n=o:r.time=n;n++)t(this._timeline[n]);if(this._iterating=!1,this._toRemove.length>0){for(var o=0;o=0&&this._timeline[i].time>=t;)i--;return this._iterate(e,i+1),this},t.Timeline.prototype.forEachAtTime=function(t,e){var i=this._search(t);return-1!==i&&this._iterate(function(i){i.time===t&&e(i)},0,i),this},t.Timeline.prototype.dispose=function(){t.prototype.dispose.call(this),this._timeline=null,this._toRemove=null},t.Timeline}(n);var q;q=function(t){"use strict";return t.TimelineSignal=function(){var e=this.optionsObject(arguments,["value","units"],t.Signal.defaults);this._events=new t.Timeline(10),t.Signal.apply(this,e),e.param=this._param,t.Param.call(this,e),this._initial=this._fromUnits(this._param.value)},t.extend(t.TimelineSignal,t.Param),t.TimelineSignal.Type={Linear:"linear",Exponential:"exponential",Target:"target",Curve:"curve",Set:"set"},Object.defineProperty(t.TimelineSignal.prototype,"value",{get:function(){var t=this.now(),e=this.getValueAtTime(t);return this._toUnits(e)},set:function(t){var e=this._fromUnits(t);this._initial=e,this.cancelScheduledValues(),this._param.value=e}}),t.TimelineSignal.prototype.setValueAtTime=function(e,i){return e=this._fromUnits(e),i=this.toSeconds(i),this._events.add({type:t.TimelineSignal.Type.Set,value:e,time:i}),this._param.setValueAtTime(e,i),this},t.TimelineSignal.prototype.linearRampToValueAtTime=function(e,i){return e=this._fromUnits(e),i=this.toSeconds(i),this._events.add({type:t.TimelineSignal.Type.Linear,value:e,time:i}),this._param.linearRampToValueAtTime(e,i),this},t.TimelineSignal.prototype.exponentialRampToValueAtTime=function(e,i){i=this.toSeconds(i);var n=this._searchBefore(i);n&&0===n.value&&this.setValueAtTime(this._minOutput,n.time),e=this._fromUnits(e);var o=Math.max(e,this._minOutput);return this._events.add({type:t.TimelineSignal.Type.Exponential,value:o,time:i}),ee)this.cancelScheduledValues(e),this.linearRampToValueAtTime(i,e);else{var o=this._searchAfter(e);o&&(this.cancelScheduledValues(e),o.type===t.TimelineSignal.Type.Linear?this.linearRampToValueAtTime(i,e):o.type===t.TimelineSignal.Type.Exponential&&this.exponentialRampToValueAtTime(i,e)),this.setValueAtTime(i,e)}return this},t.TimelineSignal.prototype.linearRampToValueBetween=function(t,e,i){return this.setRampPoint(e),this.linearRampToValueAtTime(t,i),this},t.TimelineSignal.prototype.exponentialRampToValueBetween=function(t,e,i){return this.setRampPoint(e),this.exponentialRampToValueAtTime(t,i),this},t.TimelineSignal.prototype._searchBefore=function(t){return this._events.get(t)},t.TimelineSignal.prototype._searchAfter=function(t){return this._events.getAfter(t)},t.TimelineSignal.prototype.getValueAtTime=function(e){e=this.toSeconds(e);var i=this._searchAfter(e),n=this._searchBefore(e),o=this._initial;if(null===n)o=this._initial;else if(n.type===t.TimelineSignal.Type.Target){var r,s=this._events.getBefore(n.time);r=null===s?this._initial:s.value,o=this._exponentialApproach(n.time,r,n.value,n.constant,e)}else o=n.type===t.TimelineSignal.Type.Curve?this._curveInterpolate(n.time,n.value,n.duration,e):null===i?n.value:i.type===t.TimelineSignal.Type.Linear?this._linearInterpolate(n.time,n.value,i.time,i.value,e):i.type===t.TimelineSignal.Type.Exponential?this._exponentialInterpolate(n.time,n.value,i.time,i.value,e):n.value;return o},t.TimelineSignal.prototype.connect=t.SignalBase.prototype.connect,t.TimelineSignal.prototype._exponentialApproach=function(t,e,i,n,o){return i+(e-i)*Math.exp(-(o-t)/n)},t.TimelineSignal.prototype._linearInterpolate=function(t,e,i,n,o){return e+(n-e)*((o-t)/(i-t))},t.TimelineSignal.prototype._exponentialInterpolate=function(t,e,i,n,o){return e=Math.max(this._minOutput,e),e*Math.pow(n/e,(o-t)/(i-t))},t.TimelineSignal.prototype._curveInterpolate=function(t,e,i,n){var o=e.length;if(n>=t+i)return e[o-1];if(t>=n)return e[0];var r=(n-t)/i,s=Math.floor((o-1)*r),a=Math.ceil((o-1)*r),u=e[s],c=e[a];return a===s?u:this._linearInterpolate(s,u,a,c,r*(o-1))},t.TimelineSignal.prototype.dispose=function(){t.Signal.prototype.dispose.call(this),t.Param.prototype.dispose.call(this),this._events.dispose(),this._events=null},t.TimelineSignal}(n,S);var M;M=function(){var e=a,i=w,n=A,o=P,r=q;t.Envelope=function(t,i,n,o,s,a){this.aTime=t||.1,this.aLevel=i||1,this.dTime=n||.5,this.dLevel=o||0,this.rTime=s||0,this.rLevel=a||0,this._rampHighPercentage=.98,this._rampLowPercentage=.02,this.output=e.audiocontext.createGain(),this.control=new r,this._init(),this.control.connect(this.output),this.connection=null,this.mathOps=[this.control],this.isExponential=!1,this.sourceToClear=null,this.wasTriggered=!1,e.soundArray.push(this)},t.Envelope.prototype._init=function(){var t=e.audiocontext.currentTime,i=t;this.control.setTargetAtTime(1e-5,i,.001),this._setRampAD(this.aTime,this.dTime)},t.Envelope.prototype.set=function(t,e,i,n,o,r){this.aTime=t,this.aLevel=e,this.dTime=i||0,this.dLevel=n||0,this.rTime=o||0,this.rLevel=r||0,this._setRampAD(t,i)},t.Envelope.prototype.setADSR=function(t,e,i,n){this.aTime=t,this.dTime=e||0,this.sPercent=i||0,this.dLevel="undefined"!=typeof i?i*(this.aLevel-this.rLevel)+this.rLevel:0,this.rTime=n||0,this._setRampAD(t,e)},t.Envelope.prototype.setRange=function(t,e){this.aLevel=t||1,this.rLevel=e||0},t.Envelope.prototype._setRampAD=function(t,e){this._rampAttackTime=this.checkExpInput(t),this._rampDecayTime=this.checkExpInput(e);var i=1;i=Math.log(1/this.checkExpInput(1-this._rampHighPercentage)),this._rampAttackTC=t/this.checkExpInput(i),i=Math.log(1/this._rampLowPercentage),this._rampDecayTC=e/this.checkExpInput(i)},t.Envelope.prototype.setRampPercentages=function(t,e){this._rampHighPercentage=this.checkExpInput(t),this._rampLowPercentage=this.checkExpInput(e);var i=1;i=Math.log(1/this.checkExpInput(1-this._rampHighPercentage)),this._rampAttackTC=this._rampAttackTime/this.checkExpInput(i),i=Math.log(1/this._rampLowPercentage),this._rampDecayTC=this._rampDecayTime/this.checkExpInput(i)},t.Envelope.prototype.setInput=function(){for(var t=0;t=t&&(t=1e-8),t},t.Envelope.prototype.play=function(t,e,i){var n=e||0,i=i||0;t&&this.connection!==t&&this.connect(t),this.triggerAttack(t,n),this.triggerRelease(t,n+this.aTime+this.dTime+i)},t.Envelope.prototype.triggerAttack=function(t,i){var n=e.audiocontext.currentTime,o=i||0,r=n+o;this.lastAttack=r,this.wasTriggered=!0,t&&this.connection!==t&&this.connect(t);var s=this.control.getValueAtTime(r);this.isExponential===!0?this.control.exponentialRampToValueAtTime(this.checkExpInput(s),r):this.control.linearRampToValueAtTime(s,r),r+=this.aTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.aLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.aLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r)),r+=this.dTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.dLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.dLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r))},t.Envelope.prototype.triggerRelease=function(t,i){if(this.wasTriggered){var n=e.audiocontext.currentTime,o=i||0,r=n+o;t&&this.connection!==t&&this.connect(t);var s=this.control.getValueAtTime(r);this.isExponential===!0?this.control.exponentialRampToValueAtTime(this.checkExpInput(s),r):this.control.linearRampToValueAtTime(s,r),r+=this.rTime,this.isExponential===!0?(this.control.exponentialRampToValueAtTime(this.checkExpInput(this.rLevel),r),s=this.checkExpInput(this.control.getValueAtTime(r)),this.control.cancelScheduledValues(r),this.control.exponentialRampToValueAtTime(s,r)):(this.control.linearRampToValueAtTime(this.rLevel,r),s=this.control.getValueAtTime(r),this.control.cancelScheduledValues(r),this.control.linearRampToValueAtTime(s,r)),this.wasTriggered=!1}},t.Envelope.prototype.ramp=function(t,i,n,o){var r=e.audiocontext.currentTime,s=i||0,a=r+s,u=this.checkExpInput(n),c="undefined"!=typeof o?this.checkExpInput(o):void 0;t&&this.connection!==t&&this.connect(t);var p=this.checkExpInput(this.control.getValueAtTime(a));u>p?(this.control.setTargetAtTime(u,a,this._rampAttackTC),a+=this._rampAttackTime):p>u&&(this.control.setTargetAtTime(u,a,this._rampDecayTC),a+=this._rampDecayTime),void 0!==c&&(c>u?this.control.setTargetAtTime(c,a,this._rampAttackTC):u>c&&this.control.setTargetAtTime(c,a,this._rampDecayTC))},t.Envelope.prototype.connect=function(i){this.connection=i,(i instanceof t.Oscillator||i instanceof t.SoundFile||i instanceof t.AudioIn||i instanceof t.Reverb||i instanceof t.Noise||i instanceof t.Filter||i instanceof t.Delay)&&(i=i.output.gain),i instanceof AudioParam&&i.setValueAtTime(0,e.audiocontext.currentTime),i instanceof t.Signal&&i.setValue(0),this.output.connect(i)},t.Envelope.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.Envelope.prototype.add=function(e){var n=new i(e),o=this.mathOps.length,r=this.output;return t.prototype._mathChain(this,n,o,r,i)},t.Envelope.prototype.mult=function(e){var i=new n(e),o=this.mathOps.length,r=this.output;return t.prototype._mathChain(this,i,o,r,n)},t.Envelope.prototype.scale=function(e,i,n,r){var s=new o(e,i,n,r),a=this.mathOps.length,u=this.output;return t.prototype._mathChain(this,s,a,u,o)},t.Envelope.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.disconnect(),this.control&&(this.control.dispose(),this.control=null);for(var i=1;io;o++)n[o]=1;var r=t.createBufferSource();return r.buffer=e,r.loop=!0,r}var i=a;t.Pulse=function(n,o){t.Oscillator.call(this,n,"sawtooth"),this.w=o||0,this.osc2=new t.SawOsc(n),this.dNode=i.audiocontext.createDelay(),this.dcOffset=e(),this.dcGain=i.audiocontext.createGain(),this.dcOffset.connect(this.dcGain),this.dcGain.connect(this.output),this.f=n||440;var r=this.w/this.oscillator.frequency.value;this.dNode.delayTime.value=r,this.dcGain.gain.value=1.7*(.5-this.w),this.osc2.disconnect(),this.osc2.panner.disconnect(),this.osc2.amp(-1),this.osc2.output.connect(this.dNode),this.dNode.connect(this.output),this.output.gain.value=1,this.output.connect(this.panner)},t.Pulse.prototype=Object.create(t.Oscillator.prototype),t.Pulse.prototype.width=function(e){if("number"==typeof e){if(1>=e&&e>=0){this.w=e;var i=this.w/this.oscillator.frequency.value;this.dNode.delayTime.value=i}this.dcGain.gain.value=1.7*(.5-this.w)}else{e.connect(this.dNode.delayTime);var n=new t.SignalAdd(-.5);n.setInput(e),n=n.mult(-1),n=n.mult(1.7),n.connect(this.dcGain.gain)}},t.Pulse.prototype.start=function(t,n){var o=i.audiocontext.currentTime,r=n||0;if(!this.started){var s=t||this.f,a=this.oscillator.type;this.oscillator=i.audiocontext.createOscillator(),this.oscillator.frequency.setValueAtTime(s,o),this.oscillator.type=a,this.oscillator.connect(this.output),this.oscillator.start(r+o),this.osc2.oscillator=i.audiocontext.createOscillator(),this.osc2.oscillator.frequency.setValueAtTime(s,r+o),this.osc2.oscillator.type=a,this.osc2.oscillator.connect(this.osc2.output),this.osc2.start(r+o),this.freqNode=[this.oscillator.frequency,this.osc2.oscillator.frequency],this.dcOffset=e(),this.dcOffset.connect(this.dcGain),this.dcOffset.start(r+o),void 0!==this.mods&&void 0!==this.mods.frequency&&(this.mods.frequency.connect(this.freqNode[0]),this.mods.frequency.connect(this.freqNode[1])),this.started=!0,this.osc2.started=!0}},t.Pulse.prototype.stop=function(t){if(this.started){var e=t||0,n=i.audiocontext.currentTime;this.oscillator.stop(e+n),this.osc2.oscillator&&this.osc2.oscillator.stop(e+n),this.dcOffset.stop(e+n),this.started=!1,this.osc2.started=!1}},t.Pulse.prototype.freq=function(t,e,n){if("number"==typeof t){this.f=t;var o=i.audiocontext.currentTime,e=e||0,n=n||0,r=this.oscillator.frequency.value;this.oscillator.frequency.cancelScheduledValues(o),this.oscillator.frequency.setValueAtTime(r,o+n),this.oscillator.frequency.exponentialRampToValueAtTime(t,n+e+o),this.osc2.oscillator.frequency.cancelScheduledValues(o),this.osc2.oscillator.frequency.setValueAtTime(r,o+n),this.osc2.oscillator.frequency.exponentialRampToValueAtTime(t,n+e+o),this.freqMod&&(this.freqMod.output.disconnect(),this.freqMod=null)}else t.output&&(t.output.disconnect(),t.output.connect(this.oscillator.frequency),t.output.connect(this.osc2.oscillator.frequency),this.freqMod=t)}}(a,O);var V;V=function(){var e=a;t.Noise=function(e){var r;t.Oscillator.call(this),delete this.f,delete this.freq,delete this.oscillator,r="brown"===e?o:"pink"===e?n:i,this.buffer=r},t.Noise.prototype=Object.create(t.Oscillator.prototype);var i=function(){for(var t=2*e.audiocontext.sampleRate,i=e.audiocontext.createBuffer(1,t,e.audiocontext.sampleRate),n=i.getChannelData(0),o=0;t>o;o++)n[o]=2*Math.random()-1;return i.type="white",i}(),n=function(){var t,i,n,o,r,s,a,u=2*e.audiocontext.sampleRate,c=e.audiocontext.createBuffer(1,u,e.audiocontext.sampleRate),p=c.getChannelData(0);t=i=n=o=r=s=a=0;for(var h=0;u>h;h++){var l=2*Math.random()-1;t=.99886*t+.0555179*l,i=.99332*i+.0750759*l,n=.969*n+.153852*l,o=.8665*o+.3104856*l,r=.55*r+.5329522*l,s=-.7616*s-.016898*l,p[h]=t+i+n+o+r+s+a+.5362*l,p[h]*=.11,a=.115926*l}return c.type="pink",c}(),o=function(){for(var t=2*e.audiocontext.sampleRate,i=e.audiocontext.createBuffer(1,t,e.audiocontext.sampleRate),n=i.getChannelData(0),o=0,r=0;t>r;r++){var s=2*Math.random()-1;n[r]=(o+.02*s)/1.02,o=n[r],n[r]*=3.5}return i.type="brown",i}();t.Noise.prototype.setType=function(t){switch(t){case"white":this.buffer=i;break;case"pink":this.buffer=n;break;case"brown":this.buffer=o;break;default:this.buffer=i}if(this.started){var r=e.audiocontext.currentTime;this.stop(r),this.start(r+.01)}},t.Noise.prototype.getType=function(){return this.buffer.type},t.Noise.prototype.start=function(){this.started&&this.stop(),this.noise=e.audiocontext.createBufferSource(),this.noise.buffer=this.buffer,this.noise.loop=!0,this.noise.connect(this.output);var t=e.audiocontext.currentTime;this.noise.start(t),this.started=!0},t.Noise.prototype.stop=function(){var t=e.audiocontext.currentTime;this.noise&&(this.noise.stop(t),this.started=!1)},t.Noise.prototype.dispose=function(){var t=e.audiocontext.currentTime,i=e.soundArray.indexOf(this);e.soundArray.splice(i,1),this.noise&&(this.noise.disconnect(),this.stop(t)),this.output&&this.output.disconnect(),this.panner&&this.panner.disconnect(),this.output=null,this.panner=null,this.buffer=null,this.noise=null}}(a);var R;R=function(){var e=a;e.inputSources=[],t.AudioIn=function(i){this.input=e.audiocontext.createGain(),this.output=e.audiocontext.createGain(),this.stream=null,this.mediaStream=null,this.currentSource=null,this.enabled=!1,this.amplitude=new t.Amplitude,this.output.connect(this.amplitude.input),window.MediaStreamTrack&&window.navigator.mediaDevices&&window.navigator.mediaDevices.getUserMedia||(i?i():window.alert("This browser does not support MediaStreamTrack and mediaDevices")),e.soundArray.push(this)},t.AudioIn.prototype.start=function(t,i){var n=this;this.stream&&this.stop();var o=e.inputSources[n.currentSource],r={audio:{sampleRate:e.audiocontext.sampleRate,echoCancellation:!1}};e.inputSources[this.currentSource]&&(r.audio.deviceId=o.deviceId),window.navigator.mediaDevices.getUserMedia(r).then(function(i){n.stream=i,n.enabled=!0,n.mediaStream=e.audiocontext.createMediaStreamSource(i),n.mediaStream.connect(n.output),n.amplitude.setInput(n.output),t&&t()})["catch"](function(t){i?i(t):console.error(t)})},t.AudioIn.prototype.stop=function(){this.stream&&(this.stream.getTracks().forEach(function(t){t.stop()}),this.mediaStream.disconnect(),delete this.mediaStream,delete this.stream)},t.AudioIn.prototype.connect=function(t){t?t.hasOwnProperty("input")?this.output.connect(t.input):t.hasOwnProperty("analyser")?this.output.connect(t.analyser):this.output.connect(t):this.output.connect(e.input)},t.AudioIn.prototype.disconnect=function(){this.output&&(this.output.disconnect(),this.output.connect(this.amplitude.input))},t.AudioIn.prototype.getLevel=function(t){return t&&(this.amplitude.smoothing=t),this.amplitude.getLevel()},t.AudioIn.prototype.amp=function(t,i){if(i){var n=i||0,o=this.output.gain.value;this.output.gain.cancelScheduledValues(e.audiocontext.currentTime),this.output.gain.setValueAtTime(o,e.audiocontext.currentTime),this.output.gain.linearRampToValueAtTime(t,n+e.audiocontext.currentTime)}else this.output.gain.cancelScheduledValues(e.audiocontext.currentTime),this.output.gain.setValueAtTime(t,e.audiocontext.currentTime)},t.AudioIn.prototype.getSources=function(t,i){return new Promise(function(n,o){window.navigator.mediaDevices.enumerateDevices().then(function(i){e.inputSources=i.filter(function(t){return"audioinput"===t.kind}),n(e.inputSources),t&&t(e.inputSources)})["catch"](function(t){o(t),i?i(t):console.error("This browser does not support MediaStreamTrack.getSources()")})})},t.AudioIn.prototype.setSource=function(t){e.inputSources.length>0&&t=t?0:1},127),this._scale=this.input=new t.Multiply(1e4),this._scale.connect(this._thresh)},t.extend(t.GreaterThanZero,t.SignalBase),t.GreaterThanZero.prototype.dispose=function(){return t.prototype.dispose.call(this),this._scale.dispose(),this._scale=null,this._thresh.dispose(),this._thresh=null,this},t.GreaterThanZero}(n,S,A);var B;B=function(t){"use strict";return t.GreaterThan=function(e){this.createInsOuts(2,0),this._param=this.input[0]=new t.Subtract(e),this.input[1]=this._param.input[1],this._gtz=this.output=new t.GreaterThanZero,this._param.connect(this._gtz)},t.extend(t.GreaterThan,t.Signal),t.GreaterThan.prototype.dispose=function(){return t.prototype.dispose.call(this),this._param.dispose(),this._param=null,this._gtz.dispose(),this._gtz=null,this},t.GreaterThan}(n,N,D);var U;U=function(t){"use strict";return t.Abs=function(){this._abs=this.input=this.output=new t.WaveShaper(function(t){return 0===t?0:Math.abs(t)},127)},t.extend(t.Abs,t.SignalBase),t.Abs.prototype.dispose=function(){return t.prototype.dispose.call(this),this._abs.dispose(),this._abs=null,this},t.Abs}(n,m);var I;I=function(t){"use strict";return t.Modulo=function(e){this.createInsOuts(1,0),this._shaper=new t.WaveShaper(Math.pow(2,16)),this._multiply=new t.Multiply,this._subtract=this.output=new t.Subtract,this._modSignal=new t.Signal(e),this.input.fan(this._shaper,this._subtract),this._modSignal.connect(this._multiply,0,0),this._shaper.connect(this._multiply,0,1),this._multiply.connect(this._subtract,0,1),this._setWaveShaper(e)},t.extend(t.Modulo,t.SignalBase),t.Modulo.prototype._setWaveShaper=function(t){this._shaper.setMap(function(e){var i=Math.floor((e+1e-4)/t);return i; +})},Object.defineProperty(t.Modulo.prototype,"value",{get:function(){return this._modSignal.value},set:function(t){this._modSignal.value=t,this._setWaveShaper(t)}}),t.Modulo.prototype.dispose=function(){return t.prototype.dispose.call(this),this._shaper.dispose(),this._shaper=null,this._multiply.dispose(),this._multiply=null,this._subtract.dispose(),this._subtract=null,this._modSignal.dispose(),this._modSignal=null,this},t.Modulo}(n,m,A);var G;G=function(t){"use strict";return t.Pow=function(e){this._exp=this.defaultArg(e,1),this._expScaler=this.input=this.output=new t.WaveShaper(this._expFunc(this._exp),8192)},t.extend(t.Pow,t.SignalBase),Object.defineProperty(t.Pow.prototype,"value",{get:function(){return this._exp},set:function(t){this._exp=t,this._expScaler.setMap(this._expFunc(this._exp))}}),t.Pow.prototype._expFunc=function(t){return function(e){return Math.pow(Math.abs(e),t)}},t.Pow.prototype.dispose=function(){return t.prototype.dispose.call(this),this._expScaler.dispose(),this._expScaler=null,this},t.Pow}(n);var L;L=function(t){"use strict";return t.AudioToGain=function(){this._norm=this.input=this.output=new t.WaveShaper(function(t){return(t+1)/2})},t.extend(t.AudioToGain,t.SignalBase),t.AudioToGain.prototype.dispose=function(){return t.prototype.dispose.call(this),this._norm.dispose(),this._norm=null,this},t.AudioToGain}(n,m);var j;j=function(t){"use strict";function e(t,e,i){var n=new t;return i._eval(e[0]).connect(n,0,0),i._eval(e[1]).connect(n,0,1),n}function i(t,e,i){var n=new t;return i._eval(e[0]).connect(n,0,0),n}function n(t){return t?parseFloat(t):void 0}function o(t){return t&&t.args?parseFloat(t.args):void 0}return t.Expr=function(){var t=this._replacements(Array.prototype.slice.call(arguments)),e=this._parseInputs(t);this._nodes=[],this.input=new Array(e);for(var i=0;e>i;i++)this.input[i]=this.context.createGain();var n,o=this._parseTree(t);try{n=this._eval(o)}catch(r){throw this._disposeNodes(),new Error("Tone.Expr: Could evaluate expression: "+t)}this.output=n},t.extend(t.Expr,t.SignalBase),t.Expr._Expressions={value:{signal:{regexp:/^\d+\.\d+|^\d+/,method:function(e){var i=new t.Signal(n(e));return i}},input:{regexp:/^\$\d/,method:function(t,e){return e.input[n(t.substr(1))]}}},glue:{"(":{regexp:/^\(/},")":{regexp:/^\)/},",":{regexp:/^,/}},func:{abs:{regexp:/^abs/,method:i.bind(this,t.Abs)},mod:{regexp:/^mod/,method:function(e,i){var n=o(e[1]),r=new t.Modulo(n);return i._eval(e[0]).connect(r),r}},pow:{regexp:/^pow/,method:function(e,i){var n=o(e[1]),r=new t.Pow(n);return i._eval(e[0]).connect(r),r}},a2g:{regexp:/^a2g/,method:function(e,i){var n=new t.AudioToGain;return i._eval(e[0]).connect(n),n}}},binary:{"+":{regexp:/^\+/,precedence:1,method:e.bind(this,t.Add)},"-":{regexp:/^\-/,precedence:1,method:function(n,o){return 1===n.length?i(t.Negate,n,o):e(t.Subtract,n,o)}},"*":{regexp:/^\*/,precedence:0,method:e.bind(this,t.Multiply)}},unary:{"-":{regexp:/^\-/,method:i.bind(this,t.Negate)},"!":{regexp:/^\!/,method:i.bind(this,t.NOT)}}},t.Expr.prototype._parseInputs=function(t){var e=t.match(/\$\d/g),i=0;if(null!==e)for(var n=0;n0;){e=e.trim();var r=i(e);o.push(r),e=e.substr(r.value.length)}return{next:function(){return o[++n]},peek:function(){return o[n+1]}}},t.Expr.prototype._parseTree=function(e){function i(t,e){return!p(t)&&"glue"===t.type&&t.value===e}function n(e,i,n){var o=!1,r=t.Expr._Expressions[i];if(!p(e))for(var s in r){var a=r[s];if(a.regexp.test(e.value)){if(p(n))return!0;if(a.precedence===n)return!0}}return o}function o(t){p(t)&&(t=5);var e;e=0>t?r():o(t-1);for(var i=c.peek();n(i,"binary",t);)i=c.next(),e={operator:i.value,method:i.method,args:[e,o(t-1)]},i=c.peek();return e}function r(){var t,e;return t=c.peek(),n(t,"unary")?(t=c.next(),e=r(),{operator:t.value,method:t.method,args:[e]}):s()}function s(){var t,e;if(t=c.peek(),p(t))throw new SyntaxError("Tone.Expr: Unexpected termination of expression");if("func"===t.type)return t=c.next(),a(t);if("value"===t.type)return t=c.next(),{method:t.method,args:t.value};if(i(t,"(")){if(c.next(),e=o(),t=c.next(),!i(t,")"))throw new SyntaxError("Expected )");return e}throw new SyntaxError("Tone.Expr: Parse error, cannot process token "+t.value)}function a(t){var e,n=[];if(e=c.next(),!i(e,"("))throw new SyntaxError('Tone.Expr: Expected ( in a function call "'+t.value+'"');if(e=c.peek(),i(e,")")||(n=u()),e=c.next(),!i(e,")"))throw new SyntaxError('Tone.Expr: Expected ) in a function call "'+t.value+'"');return{method:t.method,args:n,name:name}}function u(){for(var t,e,n=[];;){if(e=o(),p(e))break;if(n.push(e),t=c.peek(),!i(t,","))break;c.next()}return n}var c=this._tokenize(e),p=this.isUndef.bind(this);return o()},t.Expr.prototype._eval=function(t){if(!this.isUndef(t)){var e=t.method(t.args,this);return this._nodes.push(e),e}},t.Expr.prototype._disposeNodes=function(){for(var t=0;t0){this.connect(arguments[0]);for(var t=1;t=t&&(t=1),"number"==typeof t?(this.biquad.frequency.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.frequency.exponentialRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.frequency),this.biquad.frequency.value},t.Filter.prototype.res=function(t,e){var i=e||0;return"number"==typeof t?(this.biquad.Q.value=t,this.biquad.Q.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.Q.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.Q),this.biquad.Q.value},t.Filter.prototype.gain=function(t,e){var i=e||0;return"number"==typeof t?(this.biquad.gain.value=t,this.biquad.gain.cancelScheduledValues(this.ac.currentTime+.01+i),this.biquad.gain.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.biquad.gain),this.biquad.gain.value},t.Filter.prototype.toggle=function(){return this._on=!this._on,this._on===!0?this.biquad.type=this._untoggledType:this._on===!1&&(this.biquad.type="allpass"),this._on},t.Filter.prototype.setType=function(t){this.biquad.type=t,this._untoggledType=this.biquad.type},t.Filter.prototype.dispose=function(){e.prototype.dispose.apply(this),this.biquad&&(this.biquad.disconnect(),delete this.biquad)},t.LowPass=function(){t.Filter.call(this,"lowpass")},t.LowPass.prototype=Object.create(t.Filter.prototype),t.HighPass=function(){t.Filter.call(this,"highpass")},t.HighPass.prototype=Object.create(t.Filter.prototype),t.BandPass=function(){t.Filter.call(this,"bandpass")},t.BandPass.prototype=Object.create(t.Filter.prototype),t.Filter}(a,Y);var W;W=function(){var e=z,i=a,n=function(t,i){e.call(this,"peaking"),this.disconnect(),this.set(t,i),this.biquad.gain.value=0,delete this.input,delete this.output,delete this._drywet,delete this.wet};return n.prototype=Object.create(e.prototype),n.prototype.amp=function(){console.warn("`amp()` is not available for p5.EQ bands. Use `.gain()`")},n.prototype.drywet=function(){console.warn("`drywet()` is not available for p5.EQ bands.")},n.prototype.connect=function(e){var i=e||t.soundOut.input;this.biquad?this.biquad.connect(i.input?i.input:i):this.output.connect(i.input?i.input:i)},n.prototype.disconnect=function(){this.biquad&&this.biquad.disconnect()},n.prototype.dispose=function(){var t=i.soundArray.indexOf(this);i.soundArray.splice(t,1),this.disconnect(),delete this.biquad},n}(z,a);var Q;Q=function(){var e=Y,i=W;return t.EQ=function(t){e.call(this),t=3===t||8===t?t:3;var i;i=3===t?Math.pow(2,3):2,this.bands=[];for(var n,o,r=0;t>r;r++)r===t-1?(n=21e3,o=.01):0===r?(n=100,o=.1):1===r?(n=3===t?360*i:360,o=1):(n=this.bands[r-1].freq()*i,o=1),this.bands[r]=this._newBand(n,o),r>0?this.bands[r-1].connect(this.bands[r].biquad):this.input.connect(this.bands[r].biquad);this.bands[t-1].connect(this.output)},t.EQ.prototype=Object.create(e.prototype),t.EQ.prototype.process=function(t){t.connect(this.input)},t.EQ.prototype.set=function(){if(arguments.length===2*this.bands.length)for(var t=0;t0;)delete this.bands.pop().dispose();delete this.bands}},t.EQ}(Y,W);var H;H=function(){var e=Y;return t.Panner3D=function(){e.call(this),this.panner=this.ac.createPanner(),this.panner.panningModel="HRTF",this.panner.distanceModel="linear",this.panner.connect(this.output),this.input.connect(this.panner)},t.Panner3D.prototype=Object.create(e.prototype),t.Panner3D.prototype.process=function(t){t.connect(this.input)},t.Panner3D.prototype.set=function(t,e,i,n){return this.positionX(t,n),this.positionY(e,n),this.positionZ(i,n),[this.panner.positionX.value,this.panner.positionY.value,this.panner.positionZ.value]},t.Panner3D.prototype.positionX=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionX.value=t,this.panner.positionX.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionX),this.panner.positionX.value},t.Panner3D.prototype.positionY=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionY.value=t,this.panner.positionY.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionY),this.panner.positionY.value},t.Panner3D.prototype.positionZ=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.positionZ.value=t,this.panner.positionZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.positionZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.positionZ),this.panner.positionZ.value},t.Panner3D.prototype.orient=function(t,e,i,n){return this.orientX(t,n),this.orientY(e,n),this.orientZ(i,n),[this.panner.orientationX.value,this.panner.orientationY.value,this.panner.orientationZ.value]},t.Panner3D.prototype.orientX=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationX.value=t,this.panner.orientationX.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationX),this.panner.orientationX.value},t.Panner3D.prototype.orientY=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationY.value=t,this.panner.orientationY.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationY),this.panner.orientationY.value},t.Panner3D.prototype.orientZ=function(t,e){var i=e||0;return"number"==typeof t?(this.panner.orientationZ.value=t,this.panner.orientationZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.panner.orientationZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.panner.orientationZ),this.panner.orientationZ.value},t.Panner3D.prototype.setFalloff=function(t,e){this.maxDist(t),this.rolloff(e)},t.Panner3D.prototype.maxDist=function(t){return"number"==typeof t&&(this.panner.maxDistance=t),this.panner.maxDistance},t.Panner3D.prototype.rolloff=function(t){return"number"==typeof t&&(this.panner.rolloffFactor=t),this.panner.rolloffFactor},t.Panner3D.dispose=function(){e.prototype.dispose.apply(this),this.panner&&(this.panner.disconnect(),delete this.panner)},t.Panner3D}(a,Y);var $;$=function(){var e=a;return t.Listener3D=function(t){this.ac=e.audiocontext,this.listener=this.ac.listener},t.Listener3D.prototype.process=function(t){t.connect(this.input)},t.Listener3D.prototype.position=function(t,e,i,n){return this.positionX(t,n),this.positionY(e,n),this.positionZ(i,n),[this.listener.positionX.value,this.listener.positionY.value,this.listener.positionZ.value]},t.Listener3D.prototype.positionX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionX.value=t,this.listener.positionX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionX),this.listener.positionX.value},t.Listener3D.prototype.positionY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionY.value=t,this.listener.positionY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionY),this.listener.positionY.value},t.Listener3D.prototype.positionZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.positionZ.value=t,this.listener.positionZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.positionZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.positionZ),this.listener.positionZ.value},t.Listener3D.prototype.orient=function(t,e,i,n,o,r,s){return 3===arguments.length||4===arguments.length?(s=arguments[3],this.orientForward(t,e,i,s)):(6===arguments.length||7===arguments)&&(this.orientForward(t,e,i),this.orientUp(n,o,r,s)),[this.listener.forwardX.value,this.listener.forwardY.value,this.listener.forwardZ.value,this.listener.upX.value,this.listener.upY.value,this.listener.upZ.value]},t.Listener3D.prototype.orientForward=function(t,e,i,n){return this.forwardX(t,n),this.forwardY(e,n),this.forwardZ(i,n),[this.listener.forwardX,this.listener.forwardY,this.listener.forwardZ]},t.Listener3D.prototype.orientUp=function(t,e,i,n){return this.upX(t,n),this.upY(e,n),this.upZ(i,n),[this.listener.upX,this.listener.upY,this.listener.upZ]},t.Listener3D.prototype.forwardX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardX.value=t,this.listener.forwardX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardX),this.listener.forwardX.value},t.Listener3D.prototype.forwardY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardY.value=t,this.listener.forwardY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardY),this.listener.forwardY.value},t.Listener3D.prototype.forwardZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.forwardZ.value=t,this.listener.forwardZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.forwardZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.forwardZ),this.listener.forwardZ.value},t.Listener3D.prototype.upX=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upX.value=t,this.listener.upX.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upX.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upX),this.listener.upX.value},t.Listener3D.prototype.upY=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upY.value=t,this.listener.upY.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upY.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upY),this.listener.upY.value},t.Listener3D.prototype.upZ=function(t,e){var i=e||0;return"number"==typeof t?(this.listener.upZ.value=t,this.listener.upZ.cancelScheduledValues(this.ac.currentTime+.01+i),this.listener.upZ.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):t&&t.connect(this.listener.upZ),this.listener.upZ.value},t.Listener3D}(a,Y);var J;J=function(){var e=z,i=Y;t.Delay=function(){i.call(this),this._split=this.ac.createChannelSplitter(2),this._merge=this.ac.createChannelMerger(2),this._leftGain=this.ac.createGain(),this._rightGain=this.ac.createGain(),this.leftDelay=this.ac.createDelay(),this.rightDelay=this.ac.createDelay(),this._leftFilter=new e,this._rightFilter=new e,this._leftFilter.disconnect(),this._rightFilter.disconnect(),this._leftFilter.biquad.frequency.setValueAtTime(1200,this.ac.currentTime),this._rightFilter.biquad.frequency.setValueAtTime(1200,this.ac.currentTime),this._leftFilter.biquad.Q.setValueAtTime(.3,this.ac.currentTime),this._rightFilter.biquad.Q.setValueAtTime(.3,this.ac.currentTime),this.input.connect(this._split),this.leftDelay.connect(this._leftGain),this.rightDelay.connect(this._rightGain),this._leftGain.connect(this._leftFilter.input),this._rightGain.connect(this._rightFilter.input),this._merge.connect(this.wet),this._leftFilter.biquad.gain.setValueAtTime(1,this.ac.currentTime),this._rightFilter.biquad.gain.setValueAtTime(1,this.ac.currentTime),this.setType(0),this._maxDelay=this.leftDelay.delayTime.maxValue,this.feedback(.5)},t.Delay.prototype=Object.create(i.prototype),t.Delay.prototype.process=function(t,e,i,n){var o=i||0,r=e||0;if(o>=1)throw new Error("Feedback value will force a positive feedback loop.");if(r>=this._maxDelay)throw new Error("Delay Time exceeds maximum delay time of "+this._maxDelay+" second.");t.connect(this.input),this.leftDelay.delayTime.setValueAtTime(r,this.ac.currentTime),this.rightDelay.delayTime.setValueAtTime(r,this.ac.currentTime),this._leftGain.gain.value=o,this._rightGain.gain.value=o,n&&(this._leftFilter.freq(n),this._rightFilter.freq(n))},t.Delay.prototype.delayTime=function(t){"number"!=typeof t?(t.connect(this.leftDelay.delayTime),t.connect(this.rightDelay.delayTime)):(this.leftDelay.delayTime.cancelScheduledValues(this.ac.currentTime),this.rightDelay.delayTime.cancelScheduledValues(this.ac.currentTime),this.leftDelay.delayTime.linearRampToValueAtTime(t,this.ac.currentTime),this.rightDelay.delayTime.linearRampToValueAtTime(t,this.ac.currentTime))},t.Delay.prototype.feedback=function(t){if(t&&"number"!=typeof t)t.connect(this._leftGain.gain),t.connect(this._rightGain.gain);else{if(t>=1)throw new Error("Feedback value will force a positive feedback loop.");"number"==typeof t&&(this._leftGain.gain.value=t,this._rightGain.gain.value=t)}return this._leftGain.gain.value},t.Delay.prototype.filter=function(t,e){this._leftFilter.set(t,e),this._rightFilter.set(t,e)},t.Delay.prototype.setType=function(t){switch(1===t&&(t="pingPong"),this._split.disconnect(),this._leftFilter.disconnect(),this._rightFilter.disconnect(),this._split.connect(this.leftDelay,0),this._split.connect(this.rightDelay,1),t){case"pingPong":this._rightFilter.setType(this._leftFilter.biquad.type),this._leftFilter.output.connect(this._merge,0,0),this._rightFilter.output.connect(this._merge,0,1),this._leftFilter.output.connect(this.rightDelay),this._rightFilter.output.connect(this.leftDelay);break;default:this._leftFilter.output.connect(this._merge,0,0),this._rightFilter.output.connect(this._merge,0,1),this._leftFilter.output.connect(this.leftDelay),this._rightFilter.output.connect(this.rightDelay)}},t.Delay.prototype.dispose=function(){i.prototype.dispose.apply(this),this._split.disconnect(),this._leftFilter.dispose(),this._rightFilter.dispose(),this._merge.disconnect(),this._leftGain.disconnect(),this._rightGain.disconnect(),this.leftDelay.disconnect(),this.rightDelay.disconnect(),this._split=void 0,this._leftFilter=void 0,this._rightFilter=void 0,this._merge=void 0,this._leftGain=void 0,this._rightGain=void 0,this.leftDelay=void 0,this.rightDelay=void 0}}(z,Y);var K;K=function(){var e=c,i=Y;t.Reverb=function(){i.call(this),this._initConvolverNode(),this.input.gain.value=.5,this._seconds=3,this._decay=2,this._reverse=!1,this._buildImpulse()},t.Reverb.prototype=Object.create(i.prototype),t.Reverb.prototype._initConvolverNode=function(){this.convolverNode=this.ac.createConvolver(),this.input.connect(this.convolverNode),this.convolverNode.connect(this.wet)},t.Reverb.prototype._teardownConvolverNode=function(){this.convolverNode&&(this.convolverNode.disconnect(),delete this.convolverNode)},t.Reverb.prototype._setBuffer=function(t){this._teardownConvolverNode(),this._initConvolverNode(),this.convolverNode.buffer=t},t.Reverb.prototype.process=function(t,e,i,n){t.connect(this.input);var o=!1;e&&(this._seconds=e,o=!0),i&&(this._decay=i),n&&(this._reverse=n),o&&this._buildImpulse()},t.Reverb.prototype.set=function(t,e,i){var n=!1;t&&(this._seconds=t,n=!0),e&&(this._decay=e),i&&(this._reverse=i),n&&this._buildImpulse()},t.Reverb.prototype._buildImpulse=function(){var t,e,i=this.ac.sampleRate,n=i*this._seconds,o=this._decay,r=this.ac.createBuffer(2,n,i),s=r.getChannelData(0),a=r.getChannelData(1);for(e=0;n>e;e++)t=this._reverse?n-e:e,s[e]=(2*Math.random()-1)*Math.pow(1-t/n,o),a[e]=(2*Math.random()-1)*Math.pow(1-t/n,o);this._setBuffer(r)},t.Reverb.prototype.dispose=function(){i.prototype.dispose.apply(this),this._teardownConvolverNode()},t.Convolver=function(e,i,n){t.Reverb.call(this),this._initConvolverNode(),this.input.gain.value=.5,e?(this.impulses=[],this._loadBuffer(e,i,n)):(this._seconds=3,this._decay=2,this._reverse=!1,this._buildImpulse())},t.Convolver.prototype=Object.create(t.Reverb.prototype),t.prototype.registerPreloadMethod("createConvolver",t.prototype),t.prototype.createConvolver=function(e,i,n){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS");var o=this,r=new t.Convolver(e,function(t){"function"==typeof i&&i(t),"function"==typeof o._decrementPreload&&o._decrementPreload()},n);return r.impulses=[],r},t.Convolver.prototype._loadBuffer=function(i,n,o){var i=t.prototype._checkFileFormats(i),r=this,s=(new Error).stack,a=t.prototype.getAudioContext(),u=new XMLHttpRequest;u.open("GET",i,!0),u.responseType="arraybuffer",u.onload=function(){if(200===u.status)a.decodeAudioData(u.response,function(t){var e={},o=i.split("/");e.name=o[o.length-1],e.audioBuffer=t,r.impulses.push(e),r._setBuffer(e.audioBuffer),n&&n(e)},function(){var t=new e("decodeAudioData",s,r.url),i="AudioContext error at decodeAudioData for "+r.url;o?(t.msg=i,o(t)):console.error(i+"\n The error stack trace includes: \n"+t.stack)});else{var t=new e("loadConvolver",s,r.url),c="Unable to load "+r.url+". The request status was: "+u.status+" ("+u.statusText+")";o?(t.message=c,o(t)):console.error(c+"\n The error stack trace includes: \n"+t.stack)}},u.onerror=function(){var t=new e("loadConvolver",s,r.url),i="There was no response from the server at "+r.url+". Check the url and internet connectivity.";o?(t.message=i,o(t)):console.error(i+"\n The error stack trace includes: \n"+t.stack)},u.send()},t.Convolver.prototype.set=null,t.Convolver.prototype.process=function(t){t.connect(this.input)},t.Convolver.prototype.impulses=[],t.Convolver.prototype.addImpulse=function(t,e,i){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS"),this._loadBuffer(t,e,i)},t.Convolver.prototype.resetImpulse=function(t,e,i){window.location.origin.indexOf("file://")>-1&&"undefined"===window.cordova&&alert("This sketch may require a server to load external files. Please see http://bit.ly/1qcInwS"),this.impulses=[],this._loadBuffer(t,e,i)},t.Convolver.prototype.toggleImpulse=function(t){if("number"==typeof t&&tthis._nextTick&&this._state;){var s=this._state.getValueAtTime(this._nextTick);if(s!==this._lastState){this._lastState=s;var a=this._state.get(this._nextTick);s===t.State.Started?(this._nextTick=a.time,this.isUndef(a.offset)||(this.ticks=a.offset),this.emit("start",a.time,this.ticks)):s===t.State.Stopped?(this.ticks=0,this.emit("stop",a.time)):s===t.State.Paused&&this.emit("pause",a.time)}var u=this._nextTick;this.frequency&&(this._nextTick+=1/this.frequency.getValueAtTime(this._nextTick),s===t.State.Started&&(this.callback(u),this.ticks++))}},t.Clock.prototype.getStateAtTime=function(t){return t=this.toSeconds(t),this._state.getValueAtTime(t)},t.Clock.prototype.dispose=function(){t.Emitter.prototype.dispose.call(this),this.context.off("tick",this._boundLoop),this._writable("frequency"),this.frequency.dispose(),this.frequency=null,this._boundLoop=null,this._nextTick=1/0,this.callback=null,this._state.dispose(),this._state=null},t.Clock}(n,q,tt,o);var it;it=function(){var e=a,i=et;t.Metro=function(){this.clock=new i({callback:this.ontick.bind(this)}),this.syncedParts=[],this.bpm=120,this._init(),this.prevTick=0,this.tatumTime=0,this.tickCallback=function(){}},t.Metro.prototype.ontick=function(t){var i=t-this.prevTick,n=t-e.audiocontext.currentTime;if(!(i-this.tatumTime<=-.02)){this.prevTick=t;var o=this;this.syncedParts.forEach(function(t){t.isPlaying&&(t.incrementStep(n),t.phrases.forEach(function(t){var e=t.sequence,i=o.metroTicks%e.length;0!==e[i]&&(o.metroTicks=t.parts.length?(t.scoreStep=0,t.onended()):(t.scoreStep=0,t.parts[t.currentPart-1].stop(),t.parts[t.currentPart].start())}var i=a,n=120;t.prototype.setBPM=function(t,e){n=t;for(var o in i.parts)i.parts[o]&&i.parts[o].setBPM(t,e)},t.Phrase=function(t,e,i){this.phraseStep=0,this.name=t,this.callback=e,this.sequence=i},t.Part=function(e,o){this.length=e||0,this.partStep=0, +this.phrases=[],this.isPlaying=!1,this.noLoop(),this.tatums=o||.0625,this.metro=new t.Metro,this.metro._init(),this.metro.beatLength(this.tatums),this.metro.setBPM(n),i.parts.push(this),this.callback=function(){}},t.Part.prototype.setBPM=function(t,e){this.metro.setBPM(t,e)},t.Part.prototype.getBPM=function(){return this.metro.getBPM()},t.Part.prototype.start=function(t){if(!this.isPlaying){this.isPlaying=!0,this.metro.resetSync(this);var e=t||0;this.metro.start(e)}},t.Part.prototype.loop=function(t){this.looping=!0,this.onended=function(){this.partStep=0};var e=t||0;this.start(e)},t.Part.prototype.noLoop=function(){this.looping=!1,this.onended=function(){this.stop()}},t.Part.prototype.stop=function(t){this.partStep=0,this.pause(t)},t.Part.prototype.pause=function(t){this.isPlaying=!1;var e=t||0;this.metro.stop(e)},t.Part.prototype.addPhrase=function(e,i,n){var o;if(3===arguments.length)o=new t.Phrase(e,i,n);else{if(!(arguments[0]instanceof t.Phrase))throw"invalid input. addPhrase accepts name, callback, array or a p5.Phrase";o=arguments[0]}this.phrases.push(o),o.sequence.length>this.length&&(this.length=o.sequence.length)},t.Part.prototype.removePhrase=function(t){for(var e in this.phrases)this.phrases[e].name===t&&this.phrases.splice(e,1)},t.Part.prototype.getPhrase=function(t){for(var e in this.phrases)if(this.phrases[e].name===t)return this.phrases[e]},t.Part.prototype.replaceSequence=function(t,e){for(var i in this.phrases)this.phrases[i].name===t&&(this.phrases[i].sequence=e)},t.Part.prototype.incrementStep=function(t){this.partStep0&&o.iterations<=o.maxIterations&&o.callback(i)},frequency:this._calcFreq()})},t.SoundLoop.prototype.start=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying||(this.clock.start(n+i),this.isPlaying=!0)},t.SoundLoop.prototype.stop=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying&&(this.clock.stop(n+i),this.isPlaying=!1)},t.SoundLoop.prototype.pause=function(t){var i=t||0,n=e.audiocontext.currentTime;this.isPlaying&&(this.clock.pause(n+i),this.isPlaying=!1)},t.SoundLoop.prototype.syncedStart=function(t,i){var n=i||0,o=e.audiocontext.currentTime;if(t.isPlaying){if(t.isPlaying){var r=t.clock._nextTick-e.audiocontext.currentTime;this.clock.start(o+r),this.isPlaying=!0}}else t.clock.start(o+n),t.isPlaying=!0,this.clock.start(o+n),this.isPlaying=!0},t.SoundLoop.prototype._update=function(){this.clock.frequency.value=this._calcFreq()},t.SoundLoop.prototype._calcFreq=function(){return"number"==typeof this._interval?(this.musicalTimeMode=!1,1/this._interval):"string"==typeof this._interval?(this.musicalTimeMode=!0,this._bpm/60/this._convertNotation(this._interval)*(this._timeSignature/4)):void 0},t.SoundLoop.prototype._convertNotation=function(t){var e=t.slice(-1);switch(t=Number(t.slice(0,-1)),e){case"m":return this._measure(t);case"n":return this._note(t);default:console.warn("Specified interval is not formatted correctly. See Tone.js timing reference for more info: https://github.com/Tonejs/Tone.js/wiki/Time")}},t.SoundLoop.prototype._measure=function(t){return t*this._timeSignature},t.SoundLoop.prototype._note=function(t){return this._timeSignature/t},Object.defineProperty(t.SoundLoop.prototype,"bpm",{get:function(){return this._bpm},set:function(t){this.musicalTimeMode||console.warn('Changing the BPM in "seconds" mode has no effect. BPM is only relevant in musicalTimeMode when the interval is specified as a string ("2n", "4n", "1m"...etc)'),this._bpm=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"timeSignature",{get:function(){return this._timeSignature},set:function(t){this.musicalTimeMode||console.warn('Changing the timeSignature in "seconds" mode has no effect. BPM is only relevant in musicalTimeMode when the interval is specified as a string ("2n", "4n", "1m"...etc)'),this._timeSignature=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"interval",{get:function(){return this._interval},set:function(t){this.musicalTimeMode="Number"==typeof t?!1:!0,this._interval=t,this._update()}}),Object.defineProperty(t.SoundLoop.prototype,"iterations",{get:function(){return this.clock.ticks}}),t.SoundLoop}(a,et);var rt;rt=function(){"use strict";var e=Y;return t.Compressor=function(){e.call(this),this.compressor=this.ac.createDynamicsCompressor(),this.input.connect(this.compressor),this.compressor.connect(this.wet)},t.Compressor.prototype=Object.create(e.prototype),t.Compressor.prototype.process=function(t,e,i,n,o,r){t.connect(this.input),this.set(e,i,n,o,r)},t.Compressor.prototype.set=function(t,e,i,n,o){"undefined"!=typeof t&&this.attack(t),"undefined"!=typeof e&&this.knee(e),"undefined"!=typeof i&&this.ratio(i),"undefined"!=typeof n&&this.threshold(n),"undefined"!=typeof o&&this.release(o)},t.Compressor.prototype.attack=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.attack.value=t,this.compressor.attack.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.attack.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.attack),this.compressor.attack.value},t.Compressor.prototype.knee=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.knee.value=t,this.compressor.knee.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.knee.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.knee),this.compressor.knee.value},t.Compressor.prototype.ratio=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.ratio.value=t,this.compressor.ratio.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.ratio.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.ratio),this.compressor.ratio.value},t.Compressor.prototype.threshold=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.threshold.value=t,this.compressor.threshold.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.threshold.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof t&&t.connect(this.compressor.threshold),this.compressor.threshold.value},t.Compressor.prototype.release=function(t,e){var i=e||0;return"number"==typeof t?(this.compressor.release.value=t,this.compressor.release.cancelScheduledValues(this.ac.currentTime+.01+i),this.compressor.release.linearRampToValueAtTime(t,this.ac.currentTime+.02+i)):"undefined"!=typeof number&&t.connect(this.compressor.release),this.compressor.release.value},t.Compressor.prototype.reduction=function(){return this.compressor.reduction.value},t.Compressor.prototype.dispose=function(){e.prototype.dispose.apply(this),this.compressor&&(this.compressor.disconnect(),delete this.compressor)},t.Compressor}(a,Y,c);var st;st=function(){var e=a,i=u.convertToWav,n=e.audiocontext;t.SoundRecorder=function(){this.input=n.createGain(),this.output=n.createGain(),this.recording=!1,this.bufferSize=1024,this._channels=2,this._clear(),this._jsNode=n.createScriptProcessor(this.bufferSize,this._channels,2),this._jsNode.onaudioprocess=this._audioprocess.bind(this),this._callback=function(){},this._jsNode.connect(t.soundOut._silentNode),this.setInput(),e.soundArray.push(this)},t.SoundRecorder.prototype.setInput=function(e){this.input.disconnect(),this.input=null,this.input=n.createGain(),this.input.connect(this._jsNode),this.input.connect(this.output),e?e.connect(this.input):t.soundOut.output.connect(this.input)},t.SoundRecorder.prototype.record=function(t,e,i){this.recording=!0,e&&(this.sampleLimit=Math.round(e*n.sampleRate)),t&&i?this._callback=function(){this.buffer=this._getBuffer(),t.setBuffer(this.buffer),i()}:t&&(this._callback=function(){this.buffer=this._getBuffer(),t.setBuffer(this.buffer)})},t.SoundRecorder.prototype.stop=function(){this.recording=!1,this._callback(),this._clear()},t.SoundRecorder.prototype._clear=function(){this._leftBuffers=[],this._rightBuffers=[],this.recordedSamples=0,this.sampleLimit=null},t.SoundRecorder.prototype._audioprocess=function(t){if(this.recording!==!1&&this.recording===!0)if(this.sampleLimit&&this.recordedSamples>=this.sampleLimit)this.stop();else{var e=t.inputBuffer.getChannelData(0),i=t.inputBuffer.getChannelData(1);this._leftBuffers.push(new Float32Array(e)),this._rightBuffers.push(new Float32Array(i)),this.recordedSamples+=this.bufferSize}},t.SoundRecorder.prototype._getBuffer=function(){var t=[];return t.push(this._mergeBuffers(this._leftBuffers)),t.push(this._mergeBuffers(this._rightBuffers)),t},t.SoundRecorder.prototype._mergeBuffers=function(t){for(var e=new Float32Array(this.recordedSamples),i=0,n=t.length,o=0;n>o;o++){var r=t[o];e.set(r,i),i+=r.length}return e},t.SoundRecorder.prototype.dispose=function(){this._clear();var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this._callback=function(){},this.input&&this.input.disconnect(),this.input=null,this._jsNode=null},t.prototype.saveSound=function(e,n){const o=i(e.buffer);t.prototype.writeFile([o],n,"wav")}}(a,u);var at;at=function(){t.PeakDetect=function(t,e,i,n){this.framesPerPeak=n||20,this.framesSinceLastPeak=0,this.decayRate=.95,this.threshold=i||.35,this.cutoff=0,this.cutoffMult=1.5,this.energy=0,this.penergy=0,this.currentValue=0,this.isDetected=!1,this.f1=t||40,this.f2=e||2e4,this._onPeak=function(){}},t.PeakDetect.prototype.update=function(t){var e=this.energy=t.getEnergy(this.f1,this.f2)/255;e>this.cutoff&&e>this.threshold&&e-this.penergy>0?(this._onPeak(),this.isDetected=!0,this.cutoff=e*this.cutoffMult,this.framesSinceLastPeak=0):(this.isDetected=!1,this.framesSinceLastPeak<=this.framesPerPeak?this.framesSinceLastPeak++:(this.cutoff*=this.decayRate,this.cutoff=Math.max(this.cutoff,this.threshold))),this.currentValue=e,this.penergy=e},t.PeakDetect.prototype.onPeak=function(t,e){var i=this;i._onPeak=function(){t(i.energy,e)}}}();var ut;ut=function(){var e=a;t.Gain=function(){this.ac=e.audiocontext,this.input=this.ac.createGain(),this.output=this.ac.createGain(),this.input.gain.value=.5,this.input.connect(this.output),e.soundArray.push(this)},t.Gain.prototype.setInput=function(t){t.connect(this.input)},t.Gain.prototype.connect=function(e){var i=e||t.soundOut.input;this.output.connect(i.input?i.input:i)},t.Gain.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.Gain.prototype.amp=function(t,i,n){var i=i||0,n=n||0,o=e.audiocontext.currentTime,r=this.output.gain.value;this.output.gain.cancelScheduledValues(o),this.output.gain.linearRampToValueAtTime(r,o+n),this.output.gain.linearRampToValueAtTime(t,o+n+i)},t.Gain.prototype.dispose=function(){var t=e.soundArray.indexOf(this);e.soundArray.splice(t,1),this.output&&(this.output.disconnect(),delete this.output),this.input&&(this.input.disconnect(),delete this.input)}}(a);var ct;ct=function(){var e=a;return t.AudioVoice=function(){this.ac=e.audiocontext,this.output=this.ac.createGain(),this.connect(),e.soundArray.push(this)},t.AudioVoice.prototype.play=function(t,e,i,n){},t.AudioVoice.prototype.triggerAttack=function(t,e,i){},t.AudioVoice.prototype.triggerRelease=function(t){},t.AudioVoice.prototype.amp=function(t,e){},t.AudioVoice.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.AudioVoice.prototype.disconnect=function(){this.output.disconnect()},t.AudioVoice.prototype.dispose=function(){this.output&&(this.output.disconnect(),delete this.output)},t.AudioVoice}(a);var pt;pt=function(){var e=a,i=ct,n=u.noteToFreq,o=.15;t.MonoSynth=function(){i.call(this),this.oscillator=new t.Oscillator,this.env=new t.Envelope,this.env.setRange(1,0),this.env.setExp(!0),this.setADSR(.02,.25,.05,.35),this.oscillator.disconnect(),this.oscillator.connect(this.output),this.env.disconnect(),this.env.setInput(this.output.gain),this.oscillator.output.gain.value=1,this.oscillator.start(),this.connect(),e.soundArray.push(this)},t.MonoSynth.prototype=Object.create(t.AudioVoice.prototype),t.MonoSynth.prototype.play=function(t,e,i,n){this.triggerAttack(t,e,~~i),this.triggerRelease(~~i+(n||o))},t.MonoSynth.prototype.triggerAttack=function(t,e,i){var i=~~i,o=n(t),r=e||.1;this.oscillator.freq(o,0,i),this.env.ramp(this.output.gain,i,r)},t.MonoSynth.prototype.triggerRelease=function(t){var t=t||0;this.env.ramp(this.output.gain,t,0)},t.MonoSynth.prototype.setADSR=function(t,e,i,n){this.env.setADSR(t,e,i,n)},Object.defineProperties(t.MonoSynth.prototype,{attack:{get:function(){return this.env.aTime},set:function(t){this.env.setADSR(t,this.env.dTime,this.env.sPercent,this.env.rTime)}},decay:{get:function(){return this.env.dTime},set:function(t){this.env.setADSR(this.env.aTime,t,this.env.sPercent,this.env.rTime)}},sustain:{get:function(){return this.env.sPercent},set:function(t){this.env.setADSR(this.env.aTime,this.env.dTime,t,this.env.rTime)}},release:{get:function(){return this.env.rTime},set:function(t){this.env.setADSR(this.env.aTime,this.env.dTime,this.env.sPercent,t)}}}),t.MonoSynth.prototype.amp=function(t,e){var i=e||0;return"undefined"!=typeof t&&this.oscillator.amp(t,i),this.oscillator.amp().value},t.MonoSynth.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.MonoSynth.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.MonoSynth.prototype.dispose=function(){i.prototype.dispose.apply(this),this.env&&this.env.dispose(),this.oscillator&&this.oscillator.dispose()}}(a,ct,u);var ht;ht=function(){var e=a,i=q,n=u.noteToFreq;t.PolySynth=function(n,o){this.audiovoices=[],this.notes={},this._newest=0,this._oldest=0,this.maxVoices=o||8,this.AudioVoice=void 0===n?t.MonoSynth:n,this._voicesInUse=new i(0),this.output=e.audiocontext.createGain(),this.connect(),this._allocateVoices(),e.soundArray.push(this)},t.PolySynth.prototype._allocateVoices=function(){for(var t=0;tf?f:p}this.audiovoices[a].triggerAttack(c,p,s)},t.PolySynth.prototype._updateAfter=function(t,e){if(null!==this._voicesInUse._searchAfter(t)){this._voicesInUse._searchAfter(t).value+=e;var i=this._voicesInUse._searchAfter(t).time;this._updateAfter(i,e)}},t.PolySynth.prototype.noteRelease=function(t,i){var o=e.audiocontext.currentTime,r=i||0,s=o+r;if(t){var a=n(t);if(this.notes[a]&&null!==this.notes[a].getValueAtTime(s)){var u=Math.max(~~this._voicesInUse.getValueAtTime(s).value,1);this._voicesInUse.setValueAtTime(u-1,s),u>0&&this._updateAfter(s,-1),this.audiovoices[this.notes[a].getValueAtTime(s)].triggerRelease(r),this.notes[a].dispose(),delete this.notes[a],this._newest=0===this._newest?0:(this._newest-1)%(this.maxVoices-1)}else console.warn("Cannot release a note that is not already playing")}else{this.audiovoices.forEach(function(t){t.triggerRelease(r)}),this._voicesInUse.setValueAtTime(0,s);for(var c in this.notes)this.notes[c].dispose(),delete this.notes[c]}},t.PolySynth.prototype.connect=function(t){var i=t||e.input;this.output.connect(i.input?i.input:i)},t.PolySynth.prototype.disconnect=function(){this.output&&this.output.disconnect()},t.PolySynth.prototype.dispose=function(){this.audiovoices.forEach(function(t){t.dispose()}),this.output&&(this.output.disconnect(),delete this.output)}}(a,q,u);var lt;lt=function(){function e(t){for(var e,i="number"==typeof t?t:50,n=44100,o=new Float32Array(n),r=Math.PI/180,s=0;n>s;++s)e=2*s/n-1,o[s]=(3+i)*e*20*r/(Math.PI+i*Math.abs(e));return o}var i=Y;t.Distortion=function(n,o){if(i.call(this),"undefined"==typeof n&&(n=.25),"number"!=typeof n)throw new Error("amount must be a number");if("undefined"==typeof o&&(o="2x"),"string"!=typeof o)throw new Error("oversample must be a String");var r=t.prototype.map(n,0,1,0,2e3);this.waveShaperNode=this.ac.createWaveShaper(),this.amount=r,this.waveShaperNode.curve=e(r),this.waveShaperNode.oversample=o,this.input.connect(this.waveShaperNode),this.waveShaperNode.connect(this.wet)},t.Distortion.prototype=Object.create(i.prototype),t.Distortion.prototype.process=function(t,e,i){t.connect(this.input),this.set(e,i)},t.Distortion.prototype.set=function(i,n){if(i){var o=t.prototype.map(i,0,1,0,2e3);this.amount=o,this.waveShaperNode.curve=e(o)}n&&(this.waveShaperNode.oversample=n)},t.Distortion.prototype.getAmount=function(){return this.amount},t.Distortion.prototype.getOversample=function(){return this.waveShaperNode.oversample},t.Distortion.prototype.dispose=function(){i.prototype.dispose.apply(this),this.waveShaperNode&&(this.waveShaperNode.disconnect(),this.waveShaperNode=null)}}(Y);var ft;ft=function(){var t=a;return t}(e,s,a,u,c,p,h,l,f,k,O,M,E,V,R,z,Q,H,$,J,K,it,nt,ot,rt,st,at,ut,pt,ht,lt,ct,pt,ht)}); \ No newline at end of file diff --git a/js/p5-v1.1.9.min.js b/js/p5-v1.1.9.min.js new file mode 100644 index 0000000..275116f --- /dev/null +++ b/js/p5-v1.1.9.min.js @@ -0,0 +1,3 @@ +/*! p5.js v1.1.9 July 22, 2020 */ + +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).p5=e()}}(function(){return function o(i,s,l){function p(t,e){if(!s[t]){if(!i[t]){var r="function"==typeof require&&require;if(!e&&r)return r(t,!0);if(u)return u(t,!0);var n=new Error("Cannot find module '"+t+"'");throw n.code="MODULE_NOT_FOUND",n}var a=s[t]={exports:{}};i[t][0].call(a.exports,function(e){return p(i[t][1][e]||e)},a,a.exports,o,i,s,l)}return s[t].exports}for(var u="function"==typeof require&&require,e=0;ep5.Color object, color components,\n or CSS color

\n',type:"p5.Color|Number[]|String"}],class:"p5",module:"Color"},blue:{name:"blue",params:[{name:"color",description:'

p5.Color object, color components,\n or CSS color

\n',type:"p5.Color|Number[]|String"}],class:"p5",module:"Color"},brightness:{name:"brightness",params:[{name:"color",description:'

p5.Color object, color components,\n or CSS color

\n',type:"p5.Color|Number[]|String"}],class:"p5",module:"Color"},color:{name:"color",class:"p5",module:"Color",overloads:[{params:[{name:"gray",description:"

number specifying value between white and black.

\n",type:"Number"},{name:"alpha",description:"

alpha value relative to current color range\n (default is 0-255)

\n",type:"Number",optional:!0}]},{params:[{name:"v1",description:"

red or hue value relative to\n the current color range

\n",type:"Number"},{name:"v2",description:"

green or saturation value\n relative to the current color range

\n",type:"Number"},{name:"v3",description:"

blue or brightness value\n relative to the current color range

\n",type:"Number"},{name:"alpha",description:"",type:"Number",optional:!0}]},{params:[{name:"value",description:"

a color string

\n",type:"String"}]},{params:[{name:"values",description:"

an array containing the red,green,blue &\n and alpha components of the color

\n",type:"Number[]"}]},{params:[{name:"color",description:"",type:"p5.Color"}]}]},green:{name:"green",params:[{name:"color",description:'

p5.Color object, color components,\n or CSS color

\n',type:"p5.Color|Number[]|String"}],class:"p5",module:"Color"},hue:{name:"hue",params:[{name:"color",description:'

p5.Color object, color components,\n or CSS color

\n',type:"p5.Color|Number[]|String"}],class:"p5",module:"Color"},lerpColor:{name:"lerpColor",params:[{name:"c1",description:"

interpolate from this color

\n",type:"p5.Color"},{name:"c2",description:"

interpolate to this color

\n",type:"p5.Color"},{name:"amt",description:"

number between 0 and 1

\n",type:"Number"}],class:"p5",module:"Color"},lightness:{name:"lightness",params:[{name:"color",description:'

p5.Color object, color components,\n or CSS color

\n',type:"p5.Color|Number[]|String"}],class:"p5",module:"Color"},red:{name:"red",params:[{name:"color",description:'

p5.Color object, color components,\n or CSS color

\n',type:"p5.Color|Number[]|String"}],class:"p5",module:"Color"},saturation:{name:"saturation",params:[{name:"color",description:'

p5.Color object, color components,\n or CSS color

\n',type:"p5.Color|Number[]|String"}],class:"p5",module:"Color"},background:{name:"background",class:"p5",module:"Color",overloads:[{params:[{name:"color",description:'

any value created by the color() function

\n',type:"p5.Color"}],chainable:1},{params:[{name:"colorstring",description:"

color string, possible formats include: integer\n rgb() or rgba(), percentage rgb() or rgba(),\n 3-digit hex, 6-digit hex

\n",type:"String"},{name:"a",description:"

opacity of the background relative to current\n color range (default is 0-255)

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"gray",description:"

specifies a value between white and black

\n",type:"Number"},{name:"a",description:"",type:"Number",optional:!0}],chainable:1},{params:[{name:"v1",description:"

red or hue value (depending on the current color\n mode)

\n",type:"Number"},{name:"v2",description:"

green or saturation value (depending on the current\n color mode)

\n",type:"Number"},{name:"v3",description:"

blue or brightness value (depending on the current\n color mode)

\n",type:"Number"},{name:"a",description:"",type:"Number",optional:!0}],chainable:1},{params:[{name:"values",description:"

an array containing the red, green, blue\n and alpha components of the color

\n",type:"Number[]"}],chainable:1},{params:[{name:"image",description:'

image created with loadImage() or createImage(),\n to set as background\n (must be same size as the sketch window)

\n',type:"p5.Image"},{name:"a",description:"",type:"Number",optional:!0}],chainable:1}]},clear:{name:"clear",class:"p5",module:"Color"},colorMode:{name:"colorMode",class:"p5",module:"Color",overloads:[{params:[{name:"mode",description:"

either RGB, HSB or HSL, corresponding to\n Red/Green/Blue and Hue/Saturation/Brightness\n (or Lightness)

\n",type:"Constant"},{name:"max",description:"

range for all values

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"mode",description:"",type:"Constant"},{name:"max1",description:"

range for the red or hue depending on the\n current color mode

\n",type:"Number"},{name:"max2",description:"

range for the green or saturation depending\n on the current color mode

\n",type:"Number"},{name:"max3",description:"

range for the blue or brightness/lightness\n depending on the current color mode

\n",type:"Number"},{name:"maxA",description:"

range for the alpha

\n",type:"Number",optional:!0}],chainable:1}]},fill:{name:"fill",class:"p5",module:"Color",overloads:[{params:[{name:"v1",description:"

red or hue value relative to\n the current color range

\n",type:"Number"},{name:"v2",description:"

green or saturation value\n relative to the current color range

\n",type:"Number"},{name:"v3",description:"

blue or brightness value\n relative to the current color range

\n",type:"Number"},{name:"alpha",description:"",type:"Number",optional:!0}],chainable:1},{params:[{name:"value",description:"

a color string

\n",type:"String"}],chainable:1},{params:[{name:"gray",description:"

a gray value

\n",type:"Number"},{name:"alpha",description:"",type:"Number",optional:!0}],chainable:1},{params:[{name:"values",description:"

an array containing the red,green,blue &\n and alpha components of the color

\n",type:"Number[]"}],chainable:1},{params:[{name:"color",description:"

the fill color

\n",type:"p5.Color"}],chainable:1}]},noFill:{name:"noFill",class:"p5",module:"Color"},noStroke:{name:"noStroke",class:"p5",module:"Color"},stroke:{name:"stroke",class:"p5",module:"Color",overloads:[{params:[{name:"v1",description:"

red or hue value relative to\n the current color range

\n",type:"Number"},{name:"v2",description:"

green or saturation value\n relative to the current color range

\n",type:"Number"},{name:"v3",description:"

blue or brightness value\n relative to the current color range

\n",type:"Number"},{name:"alpha",description:"",type:"Number",optional:!0}],chainable:1},{params:[{name:"value",description:"

a color string

\n",type:"String"}],chainable:1},{params:[{name:"gray",description:"

a gray value

\n",type:"Number"},{name:"alpha",description:"",type:"Number",optional:!0}],chainable:1},{params:[{name:"values",description:"

an array containing the red,green,blue &\n and alpha components of the color

\n",type:"Number[]"}],chainable:1},{params:[{name:"color",description:"

the stroke color

\n",type:"p5.Color"}],chainable:1}]},erase:{name:"erase",params:[{name:"strengthFill",description:"

A number (0-255) for the strength of erasing for a shape's fill.\n This will default to 255 when no argument is given, which\n is full strength.

\n",type:"Number",optional:!0},{name:"strengthStroke",description:"

A number (0-255) for the strength of erasing for a shape's stroke.\n This will default to 255 when no argument is given, which\n is full strength.

\n",type:"Number",optional:!0}],class:"p5",module:"Color"},noErase:{name:"noErase",class:"p5",module:"Color"},arc:{name:"arc",params:[{name:"x",description:"

x-coordinate of the arc's ellipse

\n",type:"Number"},{name:"y",description:"

y-coordinate of the arc's ellipse

\n",type:"Number"},{name:"w",description:"

width of the arc's ellipse by default

\n",type:"Number"},{name:"h",description:"

height of the arc's ellipse by default

\n",type:"Number"},{name:"start",description:"

angle to start the arc, specified in radians

\n",type:"Number"},{name:"stop",description:"

angle to stop the arc, specified in radians

\n",type:"Number"},{name:"mode",description:"

optional parameter to determine the way of drawing\n the arc. either CHORD, PIE or OPEN

\n",type:"Constant",optional:!0},{name:"detail",description:"

optional parameter for WebGL mode only. This is to\n specify the number of vertices that makes up the\n perimeter of the arc. Default value is 25.

\n",type:"Number",optional:!0}],class:"p5",module:"Shape"},ellipse:{name:"ellipse",class:"p5",module:"Shape",overloads:[{params:[{name:"x",description:"

x-coordinate of the center of ellipse.

\n",type:"Number"},{name:"y",description:"

y-coordinate of the center of ellipse.

\n",type:"Number"},{name:"w",description:"

width of the ellipse.

\n",type:"Number"},{name:"h",description:"

height of the ellipse.

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"x",description:"",type:"Number"},{name:"y",description:"",type:"Number"},{name:"w",description:"",type:"Number"},{name:"h",description:"",type:"Number"},{name:"detail",description:"

number of radial sectors to draw (for WebGL mode)

\n",type:"Integer"}]}]},circle:{name:"circle",params:[{name:"x",description:"

x-coordinate of the centre of the circle.

\n",type:"Number"},{name:"y",description:"

y-coordinate of the centre of the circle.

\n",type:"Number"},{name:"d",description:"

diameter of the circle.

\n",type:"Number"}],class:"p5",module:"Shape"},line:{name:"line",class:"p5",module:"Shape",overloads:[{params:[{name:"x1",description:"

the x-coordinate of the first point

\n",type:"Number"},{name:"y1",description:"

the y-coordinate of the first point

\n",type:"Number"},{name:"x2",description:"

the x-coordinate of the second point

\n",type:"Number"},{name:"y2",description:"

the y-coordinate of the second point

\n",type:"Number"}],chainable:1},{params:[{name:"x1",description:"",type:"Number"},{name:"y1",description:"",type:"Number"},{name:"z1",description:"

the z-coordinate of the first point

\n",type:"Number"},{name:"x2",description:"",type:"Number"},{name:"y2",description:"",type:"Number"},{name:"z2",description:"

the z-coordinate of the second point

\n",type:"Number"}],chainable:1}]},point:{name:"point",class:"p5",module:"Shape",overloads:[{params:[{name:"x",description:"

the x-coordinate

\n",type:"Number"},{name:"y",description:"

the y-coordinate

\n",type:"Number"},{name:"z",description:"

the z-coordinate (for WebGL mode)

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"coordinate_vector",description:"

the coordinate vector

\n",type:"p5.Vector"}],chainable:1}]},quad:{name:"quad",class:"p5",module:"Shape",overloads:[{params:[{name:"x1",description:"

the x-coordinate of the first point

\n",type:"Number"},{name:"y1",description:"

the y-coordinate of the first point

\n",type:"Number"},{name:"x2",description:"

the x-coordinate of the second point

\n",type:"Number"},{name:"y2",description:"

the y-coordinate of the second point

\n",type:"Number"},{name:"x3",description:"

the x-coordinate of the third point

\n",type:"Number"},{name:"y3",description:"

the y-coordinate of the third point

\n",type:"Number"},{name:"x4",description:"

the x-coordinate of the fourth point

\n",type:"Number"},{name:"y4",description:"

the y-coordinate of the fourth point

\n",type:"Number"}],chainable:1},{params:[{name:"x1",description:"",type:"Number"},{name:"y1",description:"",type:"Number"},{name:"z1",description:"

the z-coordinate of the first point

\n",type:"Number"},{name:"x2",description:"",type:"Number"},{name:"y2",description:"",type:"Number"},{name:"z2",description:"

the z-coordinate of the second point

\n",type:"Number"},{name:"x3",description:"",type:"Number"},{name:"y3",description:"",type:"Number"},{name:"z3",description:"

the z-coordinate of the third point

\n",type:"Number"},{name:"x4",description:"",type:"Number"},{name:"y4",description:"",type:"Number"},{name:"z4",description:"

the z-coordinate of the fourth point

\n",type:"Number"}],chainable:1}]},rect:{name:"rect",class:"p5",module:"Shape",overloads:[{params:[{name:"x",description:"

x-coordinate of the rectangle.

\n",type:"Number"},{name:"y",description:"

y-coordinate of the rectangle.

\n",type:"Number"},{name:"w",description:"

width of the rectangle.

\n",type:"Number"},{name:"h",description:"

height of the rectangle.

\n",type:"Number",optional:!0},{name:"tl",description:"

optional radius of top-left corner.

\n",type:"Number",optional:!0},{name:"tr",description:"

optional radius of top-right corner.

\n",type:"Number",optional:!0},{name:"br",description:"

optional radius of bottom-right corner.

\n",type:"Number",optional:!0},{name:"bl",description:"

optional radius of bottom-left corner.

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"x",description:"",type:"Number"},{name:"y",description:"",type:"Number"},{name:"w",description:"",type:"Number"},{name:"h",description:"",type:"Number"},{name:"detailX",description:"

number of segments in the x-direction (for WebGL mode)

\n",type:"Integer",optional:!0},{name:"detailY",description:"

number of segments in the y-direction (for WebGL mode)

\n",type:"Integer",optional:!0}],chainable:1}]},square:{name:"square",params:[{name:"x",description:"

x-coordinate of the square.

\n",type:"Number"},{name:"y",description:"

y-coordinate of the square.

\n",type:"Number"},{name:"s",description:"

side size of the square.

\n",type:"Number"},{name:"tl",description:"

optional radius of top-left corner.

\n",type:"Number",optional:!0},{name:"tr",description:"

optional radius of top-right corner.

\n",type:"Number",optional:!0},{name:"br",description:"

optional radius of bottom-right corner.

\n",type:"Number",optional:!0},{name:"bl",description:"

optional radius of bottom-left corner.

\n",type:"Number",optional:!0}],class:"p5",module:"Shape"},triangle:{name:"triangle",params:[{name:"x1",description:"

x-coordinate of the first point

\n",type:"Number"},{name:"y1",description:"

y-coordinate of the first point

\n",type:"Number"},{name:"x2",description:"

x-coordinate of the second point

\n",type:"Number"},{name:"y2",description:"

y-coordinate of the second point

\n",type:"Number"},{name:"x3",description:"

x-coordinate of the third point

\n",type:"Number"},{name:"y3",description:"

y-coordinate of the third point

\n",type:"Number"}],class:"p5",module:"Shape"},ellipseMode:{name:"ellipseMode",params:[{name:"mode",description:"

either CENTER, RADIUS, CORNER, or CORNERS

\n",type:"Constant"}],class:"p5",module:"Shape"},noSmooth:{name:"noSmooth",class:"p5",module:"Shape"},rectMode:{name:"rectMode",params:[{name:"mode",description:"

either CORNER, CORNERS, CENTER, or RADIUS

\n",type:"Constant"}],class:"p5",module:"Shape"},smooth:{name:"smooth",class:"p5",module:"Shape"},strokeCap:{name:"strokeCap",params:[{name:"cap",description:"

either ROUND, SQUARE or PROJECT

\n",type:"Constant"}],class:"p5",module:"Shape"},strokeJoin:{name:"strokeJoin",params:[{name:"join",description:"

either MITER, BEVEL, ROUND

\n",type:"Constant"}],class:"p5",module:"Shape"},strokeWeight:{name:"strokeWeight",params:[{name:"weight",description:"

the weight of the stroke (in pixels)

\n",type:"Number"}],class:"p5",module:"Shape"},bezier:{name:"bezier",class:"p5",module:"Shape",overloads:[{params:[{name:"x1",description:"

x-coordinate for the first anchor point

\n",type:"Number"},{name:"y1",description:"

y-coordinate for the first anchor point

\n",type:"Number"},{name:"x2",description:"

x-coordinate for the first control point

\n",type:"Number"},{name:"y2",description:"

y-coordinate for the first control point

\n",type:"Number"},{name:"x3",description:"

x-coordinate for the second control point

\n",type:"Number"},{name:"y3",description:"

y-coordinate for the second control point

\n",type:"Number"},{name:"x4",description:"

x-coordinate for the second anchor point

\n",type:"Number"},{name:"y4",description:"

y-coordinate for the second anchor point

\n",type:"Number"}],chainable:1},{params:[{name:"x1",description:"",type:"Number"},{name:"y1",description:"",type:"Number"},{name:"z1",description:"

z-coordinate for the first anchor point

\n",type:"Number"},{name:"x2",description:"",type:"Number"},{name:"y2",description:"",type:"Number"},{name:"z2",description:"

z-coordinate for the first control point

\n",type:"Number"},{name:"x3",description:"",type:"Number"},{name:"y3",description:"",type:"Number"},{name:"z3",description:"

z-coordinate for the second control point

\n",type:"Number"},{name:"x4",description:"",type:"Number"},{name:"y4",description:"",type:"Number"},{name:"z4",description:"

z-coordinate for the second anchor point

\n",type:"Number"}],chainable:1}]},bezierDetail:{name:"bezierDetail",params:[{name:"detail",description:"

resolution of the curves

\n",type:"Number"}],class:"p5",module:"Shape"},bezierPoint:{name:"bezierPoint",params:[{name:"a",description:"

coordinate of first point on the curve

\n",type:"Number"},{name:"b",description:"

coordinate of first control point

\n",type:"Number"},{name:"c",description:"

coordinate of second control point

\n",type:"Number"},{name:"d",description:"

coordinate of second point on the curve

\n",type:"Number"},{name:"t",description:"

value between 0 and 1

\n",type:"Number"}],class:"p5",module:"Shape"},bezierTangent:{name:"bezierTangent",params:[{name:"a",description:"

coordinate of first point on the curve

\n",type:"Number"},{name:"b",description:"

coordinate of first control point

\n",type:"Number"},{name:"c",description:"

coordinate of second control point

\n",type:"Number"},{name:"d",description:"

coordinate of second point on the curve

\n",type:"Number"},{name:"t",description:"

value between 0 and 1

\n",type:"Number"}],class:"p5",module:"Shape"},curve:{name:"curve",class:"p5",module:"Shape",overloads:[{params:[{name:"x1",description:"

x-coordinate for the beginning control point

\n",type:"Number"},{name:"y1",description:"

y-coordinate for the beginning control point

\n",type:"Number"},{name:"x2",description:"

x-coordinate for the first point

\n",type:"Number"},{name:"y2",description:"

y-coordinate for the first point

\n",type:"Number"},{name:"x3",description:"

x-coordinate for the second point

\n",type:"Number"},{name:"y3",description:"

y-coordinate for the second point

\n",type:"Number"},{name:"x4",description:"

x-coordinate for the ending control point

\n",type:"Number"},{name:"y4",description:"

y-coordinate for the ending control point

\n",type:"Number"}],chainable:1},{params:[{name:"x1",description:"",type:"Number"},{name:"y1",description:"",type:"Number"},{name:"z1",description:"

z-coordinate for the beginning control point

\n",type:"Number"},{name:"x2",description:"",type:"Number"},{name:"y2",description:"",type:"Number"},{name:"z2",description:"

z-coordinate for the first point

\n",type:"Number"},{name:"x3",description:"",type:"Number"},{name:"y3",description:"",type:"Number"},{name:"z3",description:"

z-coordinate for the second point

\n",type:"Number"},{name:"x4",description:"",type:"Number"},{name:"y4",description:"",type:"Number"},{name:"z4",description:"

z-coordinate for the ending control point

\n",type:"Number"}],chainable:1}]},curveDetail:{name:"curveDetail",params:[{name:"resolution",description:"

resolution of the curves

\n",type:"Number"}],class:"p5",module:"Shape"},curveTightness:{name:"curveTightness",params:[{name:"amount",description:"

amount of deformation from the original vertices

\n",type:"Number"}],class:"p5",module:"Shape"},curvePoint:{name:"curvePoint",params:[{name:"a",description:"

coordinate of first control point of the curve

\n",type:"Number"},{name:"b",description:"

coordinate of first point

\n",type:"Number"},{name:"c",description:"

coordinate of second point

\n",type:"Number"},{name:"d",description:"

coordinate of second control point

\n",type:"Number"},{name:"t",description:"

value between 0 and 1

\n",type:"Number"}],class:"p5",module:"Shape"},curveTangent:{name:"curveTangent",params:[{name:"a",description:"

coordinate of first control point

\n",type:"Number"},{name:"b",description:"

coordinate of first point on the curve

\n",type:"Number"},{name:"c",description:"

coordinate of second point on the curve

\n",type:"Number"},{name:"d",description:"

coordinate of second conrol point

\n",type:"Number"},{name:"t",description:"

value between 0 and 1

\n",type:"Number"}],class:"p5",module:"Shape"},beginContour:{name:"beginContour",class:"p5",module:"Shape"},beginShape:{name:"beginShape",params:[{name:"kind",description:"

either POINTS, LINES, TRIANGLES, TRIANGLE_FAN\n TRIANGLE_STRIP, QUADS, QUAD_STRIP or TESS

\n",type:"Constant",optional:!0}],class:"p5",module:"Shape"},bezierVertex:{name:"bezierVertex",class:"p5",module:"Shape",overloads:[{params:[{name:"x2",description:"

x-coordinate for the first control point

\n",type:"Number"},{name:"y2",description:"

y-coordinate for the first control point

\n",type:"Number"},{name:"x3",description:"

x-coordinate for the second control point

\n",type:"Number"},{name:"y3",description:"

y-coordinate for the second control point

\n",type:"Number"},{name:"x4",description:"

x-coordinate for the anchor point

\n",type:"Number"},{name:"y4",description:"

y-coordinate for the anchor point

\n",type:"Number"}],chainable:1},{params:[{name:"x2",description:"",type:"Number"},{name:"y2",description:"",type:"Number"},{name:"z2",description:"

z-coordinate for the first control point (for WebGL mode)

\n",type:"Number"},{name:"x3",description:"",type:"Number"},{name:"y3",description:"",type:"Number"},{name:"z3",description:"

z-coordinate for the second control point (for WebGL mode)

\n",type:"Number"},{name:"x4",description:"",type:"Number"},{name:"y4",description:"",type:"Number"},{name:"z4",description:"

z-coordinate for the anchor point (for WebGL mode)

\n",type:"Number"}],chainable:1}]},curveVertex:{name:"curveVertex",class:"p5",module:"Shape",overloads:[{params:[{name:"x",description:"

x-coordinate of the vertex

\n",type:"Number"},{name:"y",description:"

y-coordinate of the vertex

\n",type:"Number"}],chainable:1},{params:[{name:"x",description:"",type:"Number"},{name:"y",description:"",type:"Number"},{name:"z",description:"

z-coordinate of the vertex (for WebGL mode)

\n",type:"Number",optional:!0}],chainable:1}]},endContour:{name:"endContour",class:"p5",module:"Shape"},endShape:{name:"endShape",params:[{name:"mode",description:"

use CLOSE to close the shape

\n",type:"Constant",optional:!0}],class:"p5",module:"Shape"},quadraticVertex:{name:"quadraticVertex",class:"p5",module:"Shape",overloads:[{params:[{name:"cx",description:"

x-coordinate for the control point

\n",type:"Number"},{name:"cy",description:"

y-coordinate for the control point

\n",type:"Number"},{name:"x3",description:"

x-coordinate for the anchor point

\n",type:"Number"},{name:"y3",description:"

y-coordinate for the anchor point

\n",type:"Number"}],chainable:1},{params:[{name:"cx",description:"",type:"Number"},{name:"cy",description:"",type:"Number"},{name:"cz",description:"

z-coordinate for the control point (for WebGL mode)

\n",type:"Number"},{name:"x3",description:"",type:"Number"},{name:"y3",description:"",type:"Number"},{name:"z3",description:"

z-coordinate for the anchor point (for WebGL mode)

\n",type:"Number"}],chainable:1}]},vertex:{name:"vertex",class:"p5",module:"Shape",overloads:[{params:[{name:"x",description:"

x-coordinate of the vertex

\n",type:"Number"},{name:"y",description:"

y-coordinate of the vertex

\n",type:"Number"}],chainable:1},{params:[{name:"x",description:"",type:"Number"},{name:"y",description:"",type:"Number"},{name:"z",description:"

z-coordinate of the vertex

\n",type:"Number"},{name:"u",description:"

the vertex's texture u-coordinate

\n",type:"Number",optional:!0},{name:"v",description:"

the vertex's texture v-coordinate

\n",type:"Number",optional:!0}],chainable:1}]},P2D:{name:"P2D",class:"p5",module:"Constants"},WEBGL:{name:"WEBGL",class:"p5",module:"Constants"},ARROW:{name:"ARROW",class:"p5",module:"Constants"},CROSS:{name:"CROSS",class:"p5",module:"Constants"},HAND:{name:"HAND",class:"p5",module:"Constants"},MOVE:{name:"MOVE",class:"p5",module:"Constants"},TEXT:{name:"TEXT",class:"p5",module:"Constants"},WAIT:{name:"WAIT",class:"p5",module:"Constants"},HALF_PI:{name:"HALF_PI",class:"p5",module:"Constants"},PI:{name:"PI",class:"p5",module:"Constants"},QUARTER_PI:{name:"QUARTER_PI",class:"p5",module:"Constants"},TAU:{name:"TAU",class:"p5",module:"Constants"},TWO_PI:{name:"TWO_PI",class:"p5",module:"Constants"},DEGREES:{name:"DEGREES",class:"p5",module:"Constants"},RADIANS:{name:"RADIANS",class:"p5",module:"Constants"},CORNER:{name:"CORNER",class:"p5",module:"Constants"},CORNERS:{name:"CORNERS",class:"p5",module:"Constants"},RADIUS:{name:"RADIUS",class:"p5",module:"Constants"},RIGHT:{name:"RIGHT",class:"p5",module:"Constants"},LEFT:{name:"LEFT",class:"p5",module:"Constants"},CENTER:{name:"CENTER",class:"p5",module:"Constants"},TOP:{name:"TOP",class:"p5",module:"Constants"},BOTTOM:{name:"BOTTOM",class:"p5",module:"Constants"},BASELINE:{name:"BASELINE",class:"p5",module:"Constants"},POINTS:{name:"POINTS",class:"p5",module:"Constants"},LINES:{name:"LINES",class:"p5",module:"Constants"},LINE_STRIP:{name:"LINE_STRIP",class:"p5",module:"Constants"},LINE_LOOP:{name:"LINE_LOOP",class:"p5",module:"Constants"},TRIANGLES:{name:"TRIANGLES",class:"p5",module:"Constants"},TRIANGLE_FAN:{name:"TRIANGLE_FAN",class:"p5",module:"Constants"},TRIANGLE_STRIP:{name:"TRIANGLE_STRIP",class:"p5",module:"Constants"},QUADS:{name:"QUADS",class:"p5",module:"Constants"},QUAD_STRIP:{name:"QUAD_STRIP",class:"p5",module:"Constants"},TESS:{name:"TESS",class:"p5",module:"Constants"},CLOSE:{name:"CLOSE",class:"p5",module:"Constants"},OPEN:{name:"OPEN",class:"p5",module:"Constants"},CHORD:{name:"CHORD",class:"p5",module:"Constants"},PIE:{name:"PIE",class:"p5",module:"Constants"},PROJECT:{name:"PROJECT",class:"p5",module:"Constants"},SQUARE:{name:"SQUARE",class:"p5",module:"Constants"},ROUND:{name:"ROUND",class:"p5",module:"Constants"},BEVEL:{name:"BEVEL",class:"p5",module:"Constants"},MITER:{name:"MITER",class:"p5",module:"Constants"},RGB:{name:"RGB",class:"p5",module:"Constants"},HSB:{name:"HSB",class:"p5",module:"Constants"},HSL:{name:"HSL",class:"p5",module:"Constants"},AUTO:{name:"AUTO",class:"p5",module:"Constants"},ALT:{name:"ALT",class:"p5",module:"Constants"},BACKSPACE:{name:"BACKSPACE",class:"p5",module:"Constants"},CONTROL:{name:"CONTROL",class:"p5",module:"Constants"},DELETE:{name:"DELETE",class:"p5",module:"Constants"},DOWN_ARROW:{name:"DOWN_ARROW",class:"p5",module:"Constants"},ENTER:{name:"ENTER",class:"p5",module:"Constants"},ESCAPE:{name:"ESCAPE",class:"p5",module:"Constants"},LEFT_ARROW:{name:"LEFT_ARROW",class:"p5",module:"Constants"},OPTION:{name:"OPTION",class:"p5",module:"Constants"},RETURN:{name:"RETURN",class:"p5",module:"Constants"},RIGHT_ARROW:{name:"RIGHT_ARROW",class:"p5",module:"Constants"},SHIFT:{name:"SHIFT",class:"p5",module:"Constants"},TAB:{name:"TAB",class:"p5",module:"Constants"},UP_ARROW:{name:"UP_ARROW",class:"p5",module:"Constants"},BLEND:{name:"BLEND",class:"p5",module:"Constants"},REMOVE:{name:"REMOVE",class:"p5",module:"Constants"},ADD:{name:"ADD",class:"p5",module:"Constants"},DARKEST:{name:"DARKEST",class:"p5",module:"Constants"},LIGHTEST:{name:"LIGHTEST",class:"p5",module:"Constants"},DIFFERENCE:{name:"DIFFERENCE",class:"p5",module:"Constants"},SUBTRACT:{name:"SUBTRACT",class:"p5",module:"Constants"},EXCLUSION:{name:"EXCLUSION",class:"p5",module:"Constants"},MULTIPLY:{name:"MULTIPLY",class:"p5",module:"Constants"},SCREEN:{name:"SCREEN",class:"p5",module:"Constants"},REPLACE:{name:"REPLACE",class:"p5",module:"Constants"},OVERLAY:{name:"OVERLAY",class:"p5",module:"Constants"},HARD_LIGHT:{name:"HARD_LIGHT",class:"p5",module:"Constants"},SOFT_LIGHT:{name:"SOFT_LIGHT",class:"p5",module:"Constants"},DODGE:{name:"DODGE",class:"p5",module:"Constants"},BURN:{name:"BURN",class:"p5",module:"Constants"},THRESHOLD:{name:"THRESHOLD",class:"p5",module:"Constants"},GRAY:{name:"GRAY",class:"p5",module:"Constants"},OPAQUE:{name:"OPAQUE",class:"p5",module:"Constants"},INVERT:{name:"INVERT",class:"p5",module:"Constants"},POSTERIZE:{name:"POSTERIZE",class:"p5",module:"Constants"},DILATE:{name:"DILATE",class:"p5",module:"Constants"},ERODE:{name:"ERODE",class:"p5",module:"Constants"},BLUR:{name:"BLUR",class:"p5",module:"Constants"},NORMAL:{name:"NORMAL",class:"p5",module:"Constants"},ITALIC:{name:"ITALIC",class:"p5",module:"Constants"},BOLD:{name:"BOLD",class:"p5",module:"Constants"},BOLDITALIC:{name:"BOLDITALIC",class:"p5",module:"Constants"},LINEAR:{name:"LINEAR",class:"p5",module:"Constants"},QUADRATIC:{name:"QUADRATIC",class:"p5",module:"Constants"},BEZIER:{name:"BEZIER",class:"p5",module:"Constants"},CURVE:{name:"CURVE",class:"p5",module:"Constants"},STROKE:{name:"STROKE",class:"p5",module:"Constants"},FILL:{name:"FILL",class:"p5",module:"Constants"},TEXTURE:{name:"TEXTURE",class:"p5",module:"Constants"},IMMEDIATE:{name:"IMMEDIATE",class:"p5",module:"Constants"},IMAGE:{name:"IMAGE",class:"p5",module:"Constants"},NEAREST:{name:"NEAREST",class:"p5",module:"Constants"},REPEAT:{name:"REPEAT",class:"p5",module:"Constants"},CLAMP:{name:"CLAMP",class:"p5",module:"Constants"},MIRROR:{name:"MIRROR",class:"p5",module:"Constants"},LANDSCAPE:{name:"LANDSCAPE",class:"p5",module:"Constants"},PORTRAIT:{name:"PORTRAIT",class:"p5",module:"Constants"},GRID:{name:"GRID",class:"p5",module:"Constants"},AXES:{name:"AXES",class:"p5",module:"Constants"},print:{name:"print",params:[{name:"contents",description:"

any combination of Number, String, Object, Boolean,\n Array to print

\n",type:"Any"}],class:"p5",module:"Environment"},frameCount:{name:"frameCount",class:"p5",module:"Environment"},deltaTime:{name:"deltaTime",class:"p5",module:"Environment"},focused:{name:"focused",class:"p5",module:"Environment"},cursor:{name:"cursor",params:[{name:"type",description:"

Built-In: either ARROW, CROSS, HAND, MOVE, TEXT and WAIT\n Native CSS properties: 'grab', 'progress', 'cell' etc.\n External: path for cursor's images\n (Allowed File extensions: .cur, .gif, .jpg, .jpeg, .png)\n For more information on Native CSS cursors and url visit:\n https://developer.mozilla.org/en-US/docs/Web/CSS/cursor

\n",type:"String|Constant"},{name:"x",description:"

the horizontal active spot of the cursor (must be less than 32)

\n",type:"Number",optional:!0},{name:"y",description:"

the vertical active spot of the cursor (must be less than 32)

\n",type:"Number",optional:!0}],class:"p5",module:"Environment"},frameRate:{name:"frameRate",class:"p5",module:"Environment",overloads:[{params:[{name:"fps",description:"

number of frames to be displayed every second

\n",type:"Number"}],chainable:1},{params:[]}]},noCursor:{name:"noCursor",class:"p5",module:"Environment"},displayWidth:{name:"displayWidth",class:"p5",module:"Environment"},displayHeight:{name:"displayHeight",class:"p5",module:"Environment"},windowWidth:{name:"windowWidth",class:"p5",module:"Environment"},windowHeight:{name:"windowHeight",class:"p5",module:"Environment"},windowResized:{name:"windowResized",class:"p5",module:"Environment"},width:{name:"width",class:"p5",module:"Environment"},height:{name:"height",class:"p5",module:"Environment"},fullscreen:{name:"fullscreen",params:[{name:"val",description:"

whether the sketch should be in fullscreen mode\nor not

\n",type:"Boolean",optional:!0}],class:"p5",module:"Environment"},pixelDensity:{name:"pixelDensity",class:"p5",module:"Environment",overloads:[{params:[{name:"val",description:"

whether or how much the sketch should scale

\n",type:"Number"}],chainable:1},{params:[]}]},displayDensity:{name:"displayDensity",class:"p5",module:"Environment"},getURL:{name:"getURL",class:"p5",module:"Environment"},getURLPath:{name:"getURLPath",class:"p5",module:"Environment"},getURLParams:{name:"getURLParams",class:"p5",module:"Environment"},preload:{name:"preload",class:"p5",module:"Structure"},setup:{name:"setup",class:"p5",module:"Structure"},draw:{name:"draw",class:"p5",module:"Structure"},remove:{name:"remove",class:"p5",module:"Structure"},disableFriendlyErrors:{name:"disableFriendlyErrors",class:"p5",module:"Structure"},let:{name:"let",class:"p5",module:"Foundation"},const:{name:"const",class:"p5",module:"Foundation"},"===":{name:"===",class:"p5",module:"Foundation"},">":{name:">",class:"p5",module:"Foundation"},">=":{name:">=",class:"p5",module:"Foundation"},"<":{name:"<",class:"p5",module:"Foundation"},"<=":{name:"<=",class:"p5",module:"Foundation"},"if-else":{name:"if-else",class:"p5",module:"Foundation"},function:{name:"function",class:"p5",module:"Foundation"},return:{name:"return",class:"p5",module:"Foundation"},boolean:{name:"boolean",params:[{name:"n",description:"

value to parse

\n",type:"String|Boolean|Number|Array"}],class:"p5",module:"Data"},string:{name:"string",class:"p5",module:"Foundation"},number:{name:"number",class:"p5",module:"Foundation"},object:{name:"object",class:"p5",module:"Foundation"},class:{name:"class",class:"p5",module:"Foundation"},for:{name:"for",class:"p5",module:"Foundation"},while:{name:"while",class:"p5",module:"Foundation"},createCanvas:{name:"createCanvas",params:[{name:"w",description:"

width of the canvas

\n",type:"Number"},{name:"h",description:"

height of the canvas

\n",type:"Number"},{name:"renderer",description:"

either P2D or WEBGL

\n",type:"Constant",optional:!0}],class:"p5",module:"Rendering"},resizeCanvas:{name:"resizeCanvas",params:[{name:"w",description:"

width of the canvas

\n",type:"Number"},{name:"h",description:"

height of the canvas

\n",type:"Number"},{name:"noRedraw",description:"

don't redraw the canvas immediately

\n",type:"Boolean",optional:!0}],class:"p5",module:"Rendering"},noCanvas:{name:"noCanvas",class:"p5",module:"Rendering"},createGraphics:{name:"createGraphics",params:[{name:"w",description:"

width of the offscreen graphics buffer

\n",type:"Number"},{name:"h",description:"

height of the offscreen graphics buffer

\n",type:"Number"},{name:"renderer",description:"

either P2D or WEBGL\n undefined defaults to p2d

\n",type:"Constant",optional:!0}],class:"p5",module:"Rendering"},blendMode:{name:"blendMode",params:[{name:"mode",description:"

blend mode to set for canvas.\n either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,\n EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD, REMOVE or SUBTRACT

\n",type:"Constant"}],class:"p5",module:"Rendering"},drawingContext:{name:"drawingContext",class:"p5",module:"Rendering"},noLoop:{name:"noLoop",class:"p5",module:"Structure"},loop:{name:"loop",class:"p5",module:"Structure"},isLooping:{name:"isLooping",class:"p5",module:"Structure"},push:{name:"push",class:"p5",module:"Structure"},pop:{name:"pop",class:"p5",module:"Structure"},redraw:{name:"redraw",params:[{name:"n",description:"

Redraw for n-times. The default value is 1.

\n",type:"Integer",optional:!0}],class:"p5",module:"Structure"},p5:{name:"p5",params:[{name:"sketch",description:"

a function containing a p5.js sketch

\n",type:"Object"},{name:"node",description:"

ID or pointer to HTML DOM node to contain sketch in

\n",type:"String|Object"}],class:"p5",module:"Structure"},applyMatrix:{name:"applyMatrix",params:[{name:"a",description:"

numbers which define the 2x3 matrix to be multiplied

\n",type:"Number"},{name:"b",description:"

numbers which define the 2x3 matrix to be multiplied

\n",type:"Number"},{name:"c",description:"

numbers which define the 2x3 matrix to be multiplied

\n",type:"Number"},{name:"d",description:"

numbers which define the 2x3 matrix to be multiplied

\n",type:"Number"},{name:"e",description:"

numbers which define the 2x3 matrix to be multiplied

\n",type:"Number"},{name:"f",description:"

numbers which define the 2x3 matrix to be multiplied

\n",type:"Number"}],class:"p5",module:"Transform"},resetMatrix:{name:"resetMatrix",class:"p5",module:"Transform"},rotate:{name:"rotate",params:[{name:"angle",description:"

the angle of rotation, specified in radians\n or degrees, depending on current angleMode

\n",type:"Number"},{name:"axis",description:"

(in 3d) the axis to rotate around

\n",type:"p5.Vector|Number[]",optional:!0}],class:"p5",module:"Transform"},rotateX:{name:"rotateX",params:[{name:"angle",description:"

the angle of rotation, specified in radians\n or degrees, depending on current angleMode

\n",type:"Number"}],class:"p5",module:"Transform"},rotateY:{name:"rotateY",params:[{name:"angle",description:"

the angle of rotation, specified in radians\n or degrees, depending on current angleMode

\n",type:"Number"}],class:"p5",module:"Transform"},rotateZ:{name:"rotateZ",params:[{name:"angle",description:"

the angle of rotation, specified in radians\n or degrees, depending on current angleMode

\n",type:"Number"}],class:"p5",module:"Transform"},scale:{name:"scale",class:"p5",module:"Transform",overloads:[{params:[{name:"s",description:"

percent to scale the object, or percentage to\n scale the object in the x-axis if multiple arguments\n are given

\n",type:"Number|p5.Vector|Number[]"},{name:"y",description:"

percent to scale the object in the y-axis

\n",type:"Number",optional:!0},{name:"z",description:"

percent to scale the object in the z-axis (webgl only)

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"scales",description:"

per-axis percents to scale the object

\n",type:"p5.Vector|Number[]"}],chainable:1}]},shearX:{name:"shearX",params:[{name:"angle",description:"

angle of shear specified in radians or degrees,\n depending on current angleMode

\n",type:"Number"}],class:"p5",module:"Transform"},shearY:{name:"shearY",params:[{name:"angle",description:"

angle of shear specified in radians or degrees,\n depending on current angleMode

\n",type:"Number"}],class:"p5",module:"Transform"},translate:{name:"translate",class:"p5",module:"Transform",overloads:[{params:[{name:"x",description:"

left/right translation

\n",type:"Number"},{name:"y",description:"

up/down translation

\n",type:"Number"},{name:"z",description:"

forward/backward translation (webgl only)

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"vector",description:"

the vector to translate by

\n",type:"p5.Vector"}],chainable:1}]},storeItem:{name:"storeItem",params:[{name:"key",description:"",type:"String"},{name:"value",description:"",type:"String|Number|Object|Boolean|p5.Color|p5.Vector"}],class:"p5",module:"Data"},getItem:{name:"getItem",params:[{name:"key",description:"

name that you wish to use to store in local storage

\n",type:"String"}],class:"p5",module:"Data"},clearStorage:{name:"clearStorage",class:"p5",module:"Data"},removeItem:{name:"removeItem",params:[{name:"key",description:"",type:"String"}],class:"p5",module:"Data"},createStringDict:{name:"createStringDict",class:"p5",module:"Data",overloads:[{params:[{name:"key",description:"",type:"String"},{name:"value",description:"",type:"String"}]},{params:[{name:"object",description:"

object

\n",type:"Object"}]}]},createNumberDict:{name:"createNumberDict",class:"p5",module:"Data",overloads:[{params:[{name:"key",description:"",type:"Number"},{name:"value",description:"",type:"Number"}]},{params:[{name:"object",description:"

object

\n",type:"Object"}]}]},select:{name:"select",params:[{name:"selectors",description:"

CSS selector string of element to search for

\n",type:"String"},{name:"container",description:'

CSS selector string, p5.Element, or\n HTML element to search within

\n',type:"String|p5.Element|HTMLElement",optional:!0}],class:"p5",module:"DOM"},selectAll:{name:"selectAll",params:[{name:"selectors",description:"

CSS selector string of elements to search for

\n",type:"String"},{name:"container",description:'

CSS selector string, p5.Element\n , or HTML element to search within

\n',type:"String|p5.Element|HTMLElement",optional:!0}],class:"p5",module:"DOM"},removeElements:{name:"removeElements",class:"p5",module:"DOM"},changed:{name:"changed",params:[{name:"fxn",description:"

function to be fired when the value of\n an element changes.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],class:"p5",module:"DOM"},input:{name:"input",params:[{name:"fxn",description:"

function to be fired when any user input is\n detected within the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],class:"p5",module:"DOM"},createDiv:{name:"createDiv",params:[{name:"html",description:"

inner HTML for element created

\n",type:"String",optional:!0}],class:"p5",module:"DOM"},createP:{name:"createP",params:[{name:"html",description:"

inner HTML for element created

\n",type:"String",optional:!0}],class:"p5",module:"DOM"},createSpan:{name:"createSpan",params:[{name:"html",description:"

inner HTML for element created

\n",type:"String",optional:!0}],class:"p5",module:"DOM"},createImg:{name:"createImg",class:"p5",module:"DOM",overloads:[{params:[{name:"src",description:"

src path or url for image

\n",type:"String"},{name:"alt",description:'

alternate text to be used if image does not load. You can use also an empty string ("") if that an image is not intended to be viewed.

\n',type:"String"}]},{params:[{name:"src",description:"",type:"String"},{name:"alt",description:"",type:"String"},{name:"crossOrigin",description:"

crossOrigin property of the img element; use either 'anonymous' or 'use-credentials' to retrieve the image with cross-origin access (for later use with canvas. if an empty string(\"\") is passed, CORS is not used

\n",type:"String"},{name:"successCallback",description:'

callback to be called once image data is loaded with the p5.Element as argument

\n',type:"Function",optional:!0}]}]},createA:{name:"createA",params:[{name:"href",description:"

url of page to link to

\n",type:"String"},{name:"html",description:"

inner html of link element to display

\n",type:"String"},{name:"target",description:"

target where new link should open,\n could be _blank, _self, _parent, _top.

\n",type:"String",optional:!0}],class:"p5",module:"DOM"},createSlider:{name:"createSlider",params:[{name:"min",description:"

minimum value of the slider

\n",type:"Number"},{name:"max",description:"

maximum value of the slider

\n",type:"Number"},{name:"value",description:"

default value of the slider

\n",type:"Number",optional:!0},{name:"step",description:"

step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value)

\n",type:"Number",optional:!0}],class:"p5",module:"DOM"},createButton:{name:"createButton",params:[{name:"label",description:"

label displayed on the button

\n",type:"String"},{name:"value",description:"

value of the button

\n",type:"String",optional:!0}],class:"p5",module:"DOM"},createCheckbox:{name:"createCheckbox",params:[{name:"label",description:"

label displayed after checkbox

\n",type:"String",optional:!0},{name:"value",description:"

value of the checkbox; checked is true, unchecked is false

\n",type:"Boolean",optional:!0}],class:"p5",module:"DOM"},createSelect:{name:"createSelect",class:"p5",module:"DOM",overloads:[{params:[{name:"multiple",description:"

true if dropdown should support multiple selections

\n",type:"Boolean",optional:!0}]},{params:[{name:"existing",description:"

DOM select element

\n",type:"Object"}]}]},createRadio:{name:"createRadio",class:"p5",module:"DOM",overloads:[{params:[{name:"containerElement",description:"

An container HTML Element either a div\nor span inside which all existing radio inputs will be considered as options.

\n",type:"Object"},{name:"name",description:"

A name parameter for each Input Element.

\n",type:"String",optional:!0}]},{params:[{name:"name",description:"",type:"String"}]},{params:[]}]},createColorPicker:{name:"createColorPicker",params:[{name:"value",description:"

default color of element

\n",type:"String|p5.Color",optional:!0}],class:"p5",module:"DOM"},createInput:{name:"createInput",class:"p5",module:"DOM",overloads:[{params:[{name:"value",description:"

default value of the input box

\n",type:"String"},{name:"type",description:"

type of text, ie text, password etc. Defaults to text.\n Needs a value to be specified first.

\n",type:"String",optional:!0}]},{params:[{name:"value",description:"",type:"String",optional:!0}]}]},createFileInput:{name:"createFileInput",params:[{name:"callback",description:"

callback function for when a file is loaded

\n",type:"Function"},{name:"multiple",description:"

optional, to allow multiple files to be selected

\n",type:"Boolean",optional:!0}],class:"p5",module:"DOM"},createVideo:{name:"createVideo",params:[{name:"src",description:"

path to a video file, or array of paths for\n supporting different browsers

\n",type:"String|String[]"},{name:"callback",description:"

callback function to be called upon\n 'canplaythrough' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content

\n",type:"Function",optional:!0}],class:"p5",module:"DOM"},createAudio:{name:"createAudio",params:[{name:"src",description:"

path to an audio file, or array of paths\n for supporting different browsers

\n",type:"String|String[]",optional:!0},{name:"callback",description:"

callback function to be called upon\n 'canplaythrough' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content

\n",type:"Function",optional:!0}],class:"p5",module:"DOM"},VIDEO:{name:"VIDEO",class:"p5",module:"DOM"},AUDIO:{name:"AUDIO",class:"p5",module:"DOM"},createCapture:{name:"createCapture",params:[{name:"type",description:"

type of capture, either VIDEO or\n AUDIO if none specified, default both,\n or a Constraints object

\n",type:"String|Constant|Object"},{name:"callback",description:"

function to be called once\n stream has loaded

\n",type:"Function",optional:!0}],class:"p5",module:"DOM"},createElement:{name:"createElement",params:[{name:"tag",description:"

tag for the new element

\n",type:"String"},{name:"content",description:"

html content to be inserted into the element

\n",type:"String",optional:!0}],class:"p5",module:"DOM"},deviceOrientation:{name:"deviceOrientation",class:"p5",module:"Events"},accelerationX:{name:"accelerationX",class:"p5",module:"Events"},accelerationY:{name:"accelerationY",class:"p5",module:"Events"},accelerationZ:{name:"accelerationZ",class:"p5",module:"Events"},pAccelerationX:{name:"pAccelerationX",class:"p5",module:"Events"},pAccelerationY:{name:"pAccelerationY",class:"p5",module:"Events"},pAccelerationZ:{name:"pAccelerationZ",class:"p5",module:"Events"},rotationX:{name:"rotationX",class:"p5",module:"Events"},rotationY:{name:"rotationY",class:"p5",module:"Events"},rotationZ:{name:"rotationZ",class:"p5",module:"Events"},pRotationX:{name:"pRotationX",class:"p5",module:"Events"},pRotationY:{name:"pRotationY",class:"p5",module:"Events"},pRotationZ:{name:"pRotationZ",class:"p5",module:"Events"},turnAxis:{name:"turnAxis",class:"p5",module:"Events"},setMoveThreshold:{name:"setMoveThreshold",params:[{name:"value",description:"

The threshold value

\n",type:"Number"}],class:"p5",module:"Events"},setShakeThreshold:{name:"setShakeThreshold",params:[{name:"value",description:"

The threshold value

\n",type:"Number"}],class:"p5",module:"Events"},deviceMoved:{name:"deviceMoved",class:"p5",module:"Events"},deviceTurned:{name:"deviceTurned",class:"p5",module:"Events"},deviceShaken:{name:"deviceShaken",class:"p5",module:"Events"},keyIsPressed:{name:"keyIsPressed",class:"p5",module:"Events"},key:{name:"key",class:"p5",module:"Events"},keyCode:{name:"keyCode",class:"p5",module:"Events"},keyPressed:{name:"keyPressed",class:"p5",module:"Events"},keyReleased:{name:"keyReleased",class:"p5",module:"Events"},keyTyped:{name:"keyTyped",class:"p5",module:"Events"},keyIsDown:{name:"keyIsDown",params:[{name:"code",description:"

The key to check for.

\n",type:"Number"}],class:"p5",module:"Events"},movedX:{name:"movedX",class:"p5",module:"Events"},movedY:{name:"movedY",class:"p5",module:"Events"},mouseX:{name:"mouseX",class:"p5",module:"Events"},mouseY:{name:"mouseY",class:"p5",module:"Events"},pmouseX:{name:"pmouseX",class:"p5",module:"Events"},pmouseY:{name:"pmouseY",class:"p5",module:"Events"},winMouseX:{name:"winMouseX",class:"p5",module:"Events"},winMouseY:{name:"winMouseY",class:"p5",module:"Events"},pwinMouseX:{name:"pwinMouseX",class:"p5",module:"Events"},pwinMouseY:{name:"pwinMouseY",class:"p5",module:"Events"},mouseButton:{name:"mouseButton",class:"p5",module:"Events"},mouseIsPressed:{name:"mouseIsPressed",class:"p5",module:"Events"},mouseMoved:{name:"mouseMoved",params:[{name:"event",description:"

optional MouseEvent callback argument.

\n",type:"Object",optional:!0}],class:"p5",module:"Events"},mouseDragged:{name:"mouseDragged",params:[{name:"event",description:"

optional MouseEvent callback argument.

\n",type:"Object",optional:!0}],class:"p5",module:"Events"},mousePressed:{name:"mousePressed",params:[{name:"event",description:"

optional MouseEvent callback argument.

\n",type:"Object",optional:!0}],class:"p5",module:"Events"},mouseReleased:{name:"mouseReleased",params:[{name:"event",description:"

optional MouseEvent callback argument.

\n",type:"Object",optional:!0}],class:"p5",module:"Events"},mouseClicked:{name:"mouseClicked",params:[{name:"event",description:"

optional MouseEvent callback argument.

\n",type:"Object",optional:!0}],class:"p5",module:"Events"},doubleClicked:{name:"doubleClicked",params:[{name:"event",description:"

optional MouseEvent callback argument.

\n",type:"Object",optional:!0}],class:"p5",module:"Events"},mouseWheel:{name:"mouseWheel",params:[{name:"event",description:"

optional WheelEvent callback argument.

\n",type:"Object",optional:!0}],class:"p5",module:"Events"},requestPointerLock:{name:"requestPointerLock",class:"p5",module:"Events"},exitPointerLock:{name:"exitPointerLock",class:"p5",module:"Events"},touches:{name:"touches",class:"p5",module:"Events"},touchStarted:{name:"touchStarted",params:[{name:"event",description:"

optional TouchEvent callback argument.

\n",type:"Object",optional:!0}],class:"p5",module:"Events"},touchMoved:{name:"touchMoved",params:[{name:"event",description:"

optional TouchEvent callback argument.

\n",type:"Object",optional:!0}],class:"p5",module:"Events"},touchEnded:{name:"touchEnded",params:[{name:"event",description:"

optional TouchEvent callback argument.

\n",type:"Object",optional:!0}],class:"p5",module:"Events"},createImage:{name:"createImage",params:[{name:"width",description:"

width in pixels

\n",type:"Integer"},{name:"height",description:"

height in pixels

\n",type:"Integer"}],class:"p5",module:"Image"},saveCanvas:{name:"saveCanvas",class:"p5",module:"Image",overloads:[{params:[{name:"selectedCanvas",description:"

a variable\n representing a specific html5 canvas (optional)

\n",type:"p5.Element|HTMLCanvasElement"},{name:"filename",description:"",type:"String",optional:!0},{name:"extension",description:"

'jpg' or 'png'

\n",type:"String",optional:!0}]},{params:[{name:"filename",description:"",type:"String",optional:!0},{name:"extension",description:"",type:"String",optional:!0}]}]},saveFrames:{name:"saveFrames",params:[{name:"filename",description:"",type:"String"},{name:"extension",description:"

'jpg' or 'png'

\n",type:"String"},{name:"duration",description:"

Duration in seconds to save the frames for.

\n",type:"Number"},{name:"framerate",description:"

Framerate to save the frames in.

\n",type:"Number"},{name:"callback",description:"

A callback function that will be executed\n to handle the image data. This function\n should accept an array as argument. The\n array will contain the specified number of\n frames of objects. Each object has three\n properties: imageData - an\n image/octet-stream, filename and extension.

\n",type:"Function(Array)",optional:!0}],class:"p5",module:"Image"},loadImage:{name:"loadImage",params:[{name:"path",description:"

Path of the image to be loaded

\n",type:"String"},{name:"successCallback",description:'

Function to be called once\n the image is loaded. Will be passed the\n p5.Image.

\n',type:"function(p5.Image)",optional:!0},{name:"failureCallback",description:"

called with event error if\n the image fails to load.

\n",type:"Function(Event)",optional:!0}],class:"p5",module:"Image"},image:{name:"image",class:"p5",module:"Image",overloads:[{params:[{name:"img",description:"

the image to display

\n",type:"p5.Image|p5.Element"},{name:"x",description:"

the x-coordinate of the top-left corner of the image

\n",type:"Number"},{name:"y",description:"

the y-coordinate of the top-left corner of the image

\n",type:"Number"},{name:"width",description:"

the width to draw the image

\n",type:"Number",optional:!0},{name:"height",description:"

the height to draw the image

\n",type:"Number",optional:!0}]},{params:[{name:"img",description:"",type:"p5.Image|p5.Element"},{name:"dx",description:"

the x-coordinate of the destination\n rectangle in which to draw the source image

\n",type:"Number"},{name:"dy",description:"

the y-coordinate of the destination\n rectangle in which to draw the source image

\n",type:"Number"},{name:"dWidth",description:"

the width of the destination rectangle

\n",type:"Number"},{name:"dHeight",description:"

the height of the destination rectangle

\n",type:"Number"},{name:"sx",description:"

the x-coordinate of the subsection of the source\nimage to draw into the destination rectangle

\n",type:"Number"},{name:"sy",description:"

the y-coordinate of the subsection of the source\nimage to draw into the destination rectangle

\n",type:"Number"},{name:"sWidth",description:"

the width of the subsection of the\n source image to draw into the destination\n rectangle

\n",type:"Number",optional:!0},{name:"sHeight",description:"

the height of the subsection of the\n source image to draw into the destination rectangle

\n",type:"Number",optional:!0}]}]},tint:{name:"tint",class:"p5",module:"Image",overloads:[{params:[{name:"v1",description:"

red or hue value relative to\n the current color range

\n",type:"Number"},{name:"v2",description:"

green or saturation value\n relative to the current color range

\n",type:"Number"},{name:"v3",description:"

blue or brightness value\n relative to the current color range

\n",type:"Number"},{name:"alpha",description:"",type:"Number",optional:!0}]},{params:[{name:"value",description:"

a color string

\n",type:"String"}]},{params:[{name:"gray",description:"

a gray value

\n",type:"Number"},{name:"alpha",description:"",type:"Number",optional:!0}]},{params:[{name:"values",description:"

an array containing the red,green,blue &\n and alpha components of the color

\n",type:"Number[]"}]},{params:[{name:"color",description:"

the tint color

\n",type:"p5.Color"}]}]},noTint:{name:"noTint",class:"p5",module:"Image"},imageMode:{name:"imageMode",params:[{name:"mode",description:"

either CORNER, CORNERS, or CENTER

\n",type:"Constant"}],class:"p5",module:"Image"},pixels:{name:"pixels",class:"p5",module:"Image"},blend:{name:"blend",class:"p5",module:"Image",overloads:[{params:[{name:"srcImage",description:"

source image

\n",type:"p5.Image"},{name:"sx",description:"

X coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sy",description:"

Y coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sw",description:"

source image width

\n",type:"Integer"},{name:"sh",description:"

source image height

\n",type:"Integer"},{name:"dx",description:"

X coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dy",description:"

Y coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dw",description:"

destination image width

\n",type:"Integer"},{name:"dh",description:"

destination image height

\n",type:"Integer"},{name:"blendMode",description:"

the blend mode. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.

\n",type:"Constant"}]},{params:[{name:"sx",description:"",type:"Integer"},{name:"sy",description:"",type:"Integer"},{name:"sw",description:"",type:"Integer"},{name:"sh",description:"",type:"Integer"},{name:"dx",description:"",type:"Integer"},{name:"dy",description:"",type:"Integer"},{name:"dw",description:"",type:"Integer"},{name:"dh",description:"",type:"Integer"},{name:"blendMode",description:"",type:"Constant"}]}]},copy:{name:"copy",class:"p5",module:"Image",overloads:[{params:[{name:"srcImage",description:"

source image

\n",type:"p5.Image|p5.Element"},{name:"sx",description:"

X coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sy",description:"

Y coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sw",description:"

source image width

\n",type:"Integer"},{name:"sh",description:"

source image height

\n",type:"Integer"},{name:"dx",description:"

X coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dy",description:"

Y coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dw",description:"

destination image width

\n",type:"Integer"},{name:"dh",description:"

destination image height

\n",type:"Integer"}]},{params:[{name:"sx",description:"",type:"Integer"},{name:"sy",description:"",type:"Integer"},{name:"sw",description:"",type:"Integer"},{name:"sh",description:"",type:"Integer"},{name:"dx",description:"",type:"Integer"},{name:"dy",description:"",type:"Integer"},{name:"dw",description:"",type:"Integer"},{name:"dh",description:"",type:"Integer"}]}]},filter:{name:"filter",params:[{name:"filterType",description:"

either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, BLUR, ERODE, DILATE or BLUR.\n See Filters.js for docs on\n each available filter

\n",type:"Constant"},{name:"filterParam",description:"

an optional parameter unique\n to each filter, see above

\n",type:"Number",optional:!0}],class:"p5",module:"Image"},get:{name:"get",class:"p5",module:"Image",overloads:[{params:[{name:"x",description:"

x-coordinate of the pixel

\n",type:"Number"},{name:"y",description:"

y-coordinate of the pixel

\n",type:"Number"},{name:"w",description:"

width

\n",type:"Number"},{name:"h",description:"

height

\n",type:"Number"}]},{params:[]},{params:[{name:"x",description:"",type:"Number"},{name:"y",description:"",type:"Number"}]}]},loadPixels:{name:"loadPixels",class:"p5",module:"Image"},set:{name:"set",params:[{name:"x",description:"

x-coordinate of the pixel

\n",type:"Number"},{name:"y",description:"

y-coordinate of the pixel

\n",type:"Number"},{name:"c",description:'

insert a grayscale value | a pixel array |\n a p5.Color object | a p5.Image to copy

\n',type:"Number|Number[]|Object"}],class:"p5",module:"Image"},updatePixels:{name:"updatePixels",params:[{name:"x",description:"

x-coordinate of the upper-left corner of region\n to update

\n",type:"Number",optional:!0},{name:"y",description:"

y-coordinate of the upper-left corner of region\n to update

\n",type:"Number",optional:!0},{name:"w",description:"

width of region to update

\n",type:"Number",optional:!0},{name:"h",description:"

height of region to update

\n",type:"Number",optional:!0}],class:"p5",module:"Image"},loadJSON:{name:"loadJSON",class:"p5",module:"IO",overloads:[{params:[{name:"path",description:"

name of the file or url to load

\n",type:"String"},{name:"jsonpOptions",description:"

options object for jsonp related settings

\n",type:"Object",optional:!0},{name:"datatype",description:'

"json" or "jsonp"

\n',type:"String",optional:!0},{name:"callback",description:'

function to be executed after\n loadJSON() completes, data is passed\n in as first argument

\n',type:"Function",optional:!0},{name:"errorCallback",description:"

function to be executed if\n there is an error, response is passed\n in as first argument

\n",type:"Function",optional:!0}]},{params:[{name:"path",description:"",type:"String"},{name:"datatype",description:"",type:"String"},{name:"callback",description:"",type:"Function",optional:!0},{name:"errorCallback",description:"",type:"Function",optional:!0}]},{params:[{name:"path",description:"",type:"String"},{name:"callback",description:"",type:"Function"},{name:"errorCallback",description:"",type:"Function",optional:!0}]}]},loadStrings:{name:"loadStrings",params:[{name:"filename",description:"

name of the file or url to load

\n",type:"String"},{name:"callback",description:'

function to be executed after loadStrings()\n completes, Array is passed in as first\n argument

\n',type:"Function",optional:!0},{name:"errorCallback",description:"

function to be executed if\n there is an error, response is passed\n in as first argument

\n",type:"Function",optional:!0}],class:"p5",module:"IO"},loadTable:{name:"loadTable",params:[{name:"filename",description:"

name of the file or URL to load

\n",type:"String"},{name:"extension",description:'

parse the table by comma-separated values "csv", semicolon-separated\n values "ssv", or tab-separated values "tsv"

\n',type:"String",optional:!0},{name:"header",description:'

"header" to indicate table has header row

\n',type:"String",optional:!0},{name:"callback",description:'

function to be executed after\n loadTable() completes. On success, the\n Table object is passed in as the\n first argument.

\n',type:"Function",optional:!0},{name:"errorCallback",description:"

function to be executed if\n there is an error, response is passed\n in as first argument

\n",type:"Function",optional:!0}],class:"p5",module:"IO"},loadXML:{name:"loadXML",params:[{name:"filename",description:"

name of the file or URL to load

\n",type:"String"},{name:"callback",description:'

function to be executed after loadXML()\n completes, XML object is passed in as\n first argument

\n',type:"Function",optional:!0},{name:"errorCallback",description:"

function to be executed if\n there is an error, response is passed\n in as first argument

\n",type:"Function",optional:!0}],class:"p5",module:"IO"},loadBytes:{name:"loadBytes",params:[{name:"file",description:"

name of the file or URL to load

\n",type:"String"},{name:"callback",description:'

function to be executed after loadBytes()\n completes

\n',type:"Function",optional:!0},{name:"errorCallback",description:"

function to be executed if there\n is an error

\n",type:"Function",optional:!0}],class:"p5",module:"IO"},httpGet:{name:"httpGet",class:"p5",module:"IO",overloads:[{params:[{name:"path",description:"

name of the file or url to load

\n",type:"String"},{name:"datatype",description:'

"json", "jsonp", "binary", "arrayBuffer",\n "xml", or "text"

\n',type:"String",optional:!0},{name:"data",description:"

param data passed sent with request

\n",type:"Object|Boolean",optional:!0},{name:"callback",description:'

function to be executed after\n httpGet() completes, data is passed in\n as first argument

\n',type:"Function",optional:!0},{name:"errorCallback",description:"

function to be executed if\n there is an error, response is passed\n in as first argument

\n",type:"Function",optional:!0}]},{params:[{name:"path",description:"",type:"String"},{name:"data",description:"",type:"Object|Boolean"},{name:"callback",description:"",type:"Function",optional:!0},{name:"errorCallback",description:"",type:"Function",optional:!0}]},{params:[{name:"path",description:"",type:"String"},{name:"callback",description:"",type:"Function"},{name:"errorCallback",description:"",type:"Function",optional:!0}]}]},httpPost:{name:"httpPost",class:"p5",module:"IO",overloads:[{params:[{name:"path",description:"

name of the file or url to load

\n",type:"String"},{name:"datatype",description:'

"json", "jsonp", "xml", or "text".\n If omitted, httpPost() will guess.

\n',type:"String",optional:!0},{name:"data",description:"

param data passed sent with request

\n",type:"Object|Boolean",optional:!0},{name:"callback",description:'

function to be executed after\n httpPost() completes, data is passed in\n as first argument

\n',type:"Function",optional:!0},{name:"errorCallback",description:"

function to be executed if\n there is an error, response is passed\n in as first argument

\n",type:"Function",optional:!0}]},{params:[{name:"path",description:"",type:"String"},{name:"data",description:"",type:"Object|Boolean"},{name:"callback",description:"",type:"Function",optional:!0},{name:"errorCallback",description:"",type:"Function",optional:!0}]},{params:[{name:"path",description:"",type:"String"},{name:"callback",description:"",type:"Function"},{name:"errorCallback",description:"",type:"Function",optional:!0}]}]},httpDo:{name:"httpDo",class:"p5",module:"IO",overloads:[{params:[{name:"path",description:"

name of the file or url to load

\n",type:"String"},{name:"method",description:'

either "GET", "POST", or "PUT",\n defaults to "GET"

\n',type:"String",optional:!0},{name:"datatype",description:'

"json", "jsonp", "xml", or "text"

\n',type:"String",optional:!0},{name:"data",description:"

param data passed sent with request

\n",type:"Object",optional:!0},{name:"callback",description:'

function to be executed after\n httpGet() completes, data is passed in\n as first argument

\n',type:"Function",optional:!0},{name:"errorCallback",description:"

function to be executed if\n there is an error, response is passed\n in as first argument

\n",type:"Function",optional:!0}]},{params:[{name:"path",description:"",type:"String"},{name:"options",description:'

Request object options as documented in the\n "fetch" API\nreference

\n',type:"Object"},{name:"callback",description:"",type:"Function",optional:!0},{name:"errorCallback",description:"",type:"Function",optional:!0}]}]},createWriter:{name:"createWriter",params:[{name:"name",description:"

name of the file to be created

\n",type:"String"},{name:"extension",description:"",type:"String",optional:!0}],class:"p5",module:"IO"},save:{name:"save",params:[{name:"objectOrFilename",description:"

If filename is provided, will\n save canvas as an image with\n either png or jpg extension\n depending on the filename.\n If object is provided, will\n save depending on the object\n and filename (see examples\n above).

\n",type:"Object|String",optional:!0},{name:"filename",description:"

If an object is provided as the first\n parameter, then the second parameter\n indicates the filename,\n and should include an appropriate\n file extension (see examples above).

\n",type:"String",optional:!0},{name:"options",description:"

Additional options depend on\n filetype. For example, when saving JSON,\n true indicates that the\n output will be optimized for filesize,\n rather than readability.

\n",type:"Boolean|String",optional:!0}],class:"p5",module:"IO"},saveJSON:{name:"saveJSON",params:[{name:"json",description:"",type:"Array|Object"},{name:"filename",description:"",type:"String"},{name:"optimize",description:"

If true, removes line breaks\n and spaces from the output\n file to optimize filesize\n (but not readability).

\n",type:"Boolean",optional:!0}],class:"p5",module:"IO"},saveStrings:{name:"saveStrings",params:[{name:"list",description:"

string array to be written

\n",type:"String[]"},{name:"filename",description:"

filename for output

\n",type:"String"},{name:"extension",description:"

the filename's extension

\n",type:"String",optional:!0},{name:"isCRLF",description:"

if true, change line-break to CRLF

\n",type:"Boolean",optional:!0}],class:"p5",module:"IO"},saveTable:{name:"saveTable",params:[{name:"Table",description:'

the Table object to save to a file

\n',type:"p5.Table"},{name:"filename",description:"

the filename to which the Table should be saved

\n",type:"String"},{name:"options",description:'

can be one of "tsv", "csv", or "html"

\n',type:"String",optional:!0}],class:"p5",module:"IO"},abs:{name:"abs",params:[{name:"n",description:"

number to compute

\n",type:"Number"}],class:"p5",module:"Math"},ceil:{name:"ceil",params:[{name:"n",description:"

number to round up

\n",type:"Number"}],class:"p5",module:"Math"},constrain:{name:"constrain",params:[{name:"n",description:"

number to constrain

\n",type:"Number"},{name:"low",description:"

minimum limit

\n",type:"Number"},{name:"high",description:"

maximum limit

\n",type:"Number"}],class:"p5",module:"Math"},dist:{name:"dist",class:"p5",module:"Math",overloads:[{params:[{name:"x1",description:"

x-coordinate of the first point

\n",type:"Number"},{name:"y1",description:"

y-coordinate of the first point

\n",type:"Number"},{name:"x2",description:"

x-coordinate of the second point

\n",type:"Number"},{name:"y2",description:"

y-coordinate of the second point

\n",type:"Number"}]},{params:[{name:"x1",description:"",type:"Number"},{name:"y1",description:"",type:"Number"},{name:"z1",description:"

z-coordinate of the first point

\n",type:"Number"},{name:"x2",description:"",type:"Number"},{name:"y2",description:"",type:"Number"},{name:"z2",description:"

z-coordinate of the second point

\n",type:"Number"}]}]},exp:{name:"exp",params:[{name:"n",description:"

exponent to raise

\n",type:"Number"}],class:"p5",module:"Math"},floor:{name:"floor",params:[{name:"n",description:"

number to round down

\n",type:"Number"}],class:"p5",module:"Math"},lerp:{name:"lerp",params:[{name:"start",description:"

first value

\n",type:"Number"},{name:"stop",description:"

second value

\n",type:"Number"},{name:"amt",description:"

number

\n",type:"Number"}],class:"p5",module:"Math"},log:{name:"log",params:[{name:"n",description:"

number greater than 0

\n",type:"Number"}],class:"p5",module:"Math"},mag:{name:"mag",params:[{name:"a",description:"

first value

\n",type:"Number"},{name:"b",description:"

second value

\n",type:"Number"}],class:"p5",module:"Math"},map:{name:"map",params:[{name:"value",description:"

the incoming value to be converted

\n",type:"Number"},{name:"start1",description:"

lower bound of the value's current range

\n",type:"Number"},{name:"stop1",description:"

upper bound of the value's current range

\n",type:"Number"},{name:"start2",description:"

lower bound of the value's target range

\n",type:"Number"},{name:"stop2",description:"

upper bound of the value's target range

\n",type:"Number"},{name:"withinBounds",description:"

constrain the value to the newly mapped range

\n",type:"Boolean",optional:!0}],class:"p5",module:"Math"},max:{name:"max",class:"p5",module:"Math",overloads:[{params:[{name:"n0",description:"

Number to compare

\n",type:"Number"},{name:"n1",description:"

Number to compare

\n",type:"Number"}]},{params:[{name:"nums",description:"

Numbers to compare

\n",type:"Number[]"}]}]},min:{name:"min",class:"p5",module:"Math",overloads:[{params:[{name:"n0",description:"

Number to compare

\n",type:"Number"},{name:"n1",description:"

Number to compare

\n",type:"Number"}]},{params:[{name:"nums",description:"

Numbers to compare

\n",type:"Number[]"}]}]},norm:{name:"norm",params:[{name:"value",description:"

incoming value to be normalized

\n",type:"Number"},{name:"start",description:"

lower bound of the value's current range

\n",type:"Number"},{name:"stop",description:"

upper bound of the value's current range

\n",type:"Number"}],class:"p5",module:"Math"},pow:{name:"pow",params:[{name:"n",description:"

base of the exponential expression

\n",type:"Number"},{name:"e",description:"

power by which to raise the base

\n",type:"Number"}],class:"p5",module:"Math"},round:{name:"round",params:[{name:"n",description:"

number to round

\n",type:"Number"},{name:"decimals",description:"

number of decimal places to round to, default is 0

\n",type:"Number",optional:!0}],class:"p5",module:"Math"},sq:{name:"sq",params:[{name:"n",description:"

number to square

\n",type:"Number"}],class:"p5",module:"Math"},sqrt:{name:"sqrt",params:[{name:"n",description:"

non-negative number to square root

\n",type:"Number"}],class:"p5",module:"Math"},fract:{name:"fract",params:[{name:"num",description:"

Number whose fractional part needs to be found out

\n",type:"Number"}],class:"p5",module:"Math"},createVector:{name:"createVector",params:[{name:"x",description:"

x component of the vector

\n",type:"Number",optional:!0},{name:"y",description:"

y component of the vector

\n",type:"Number",optional:!0},{name:"z",description:"

z component of the vector

\n",type:"Number",optional:!0}],class:"p5",module:"Math"},noise:{name:"noise",params:[{name:"x",description:"

x-coordinate in noise space

\n",type:"Number"},{name:"y",description:"

y-coordinate in noise space

\n",type:"Number",optional:!0},{name:"z",description:"

z-coordinate in noise space

\n",type:"Number",optional:!0}],class:"p5",module:"Math"},noiseDetail:{name:"noiseDetail",params:[{name:"lod",description:"

number of octaves to be used by the noise

\n",type:"Number"},{name:"falloff",description:"

falloff factor for each octave

\n",type:"Number"}],class:"p5",module:"Math"},noiseSeed:{name:"noiseSeed",params:[{name:"seed",description:"

the seed value

\n",type:"Number"}],class:"p5",module:"Math"},randomSeed:{name:"randomSeed",params:[{name:"seed",description:"

the seed value

\n",type:"Number"}],class:"p5",module:"Math"},random:{name:"random",class:"p5",module:"Math",overloads:[{params:[{name:"min",description:"

the lower bound (inclusive)

\n",type:"Number",optional:!0},{name:"max",description:"

the upper bound (exclusive)

\n",type:"Number",optional:!0}]},{params:[{name:"choices",description:"

the array to choose from

\n",type:"Array"}]}]},randomGaussian:{name:"randomGaussian",params:[{name:"mean",description:"

the mean

\n",type:"Number"},{name:"sd",description:"

the standard deviation

\n",type:"Number"}],class:"p5",module:"Math"},acos:{name:"acos",params:[{name:"value",description:"

the value whose arc cosine is to be returned

\n",type:"Number"}],class:"p5",module:"Math"},asin:{name:"asin",params:[{name:"value",description:"

the value whose arc sine is to be returned

\n",type:"Number"}],class:"p5",module:"Math"},atan:{name:"atan",params:[{name:"value",description:"

the value whose arc tangent is to be returned

\n",type:"Number"}],class:"p5",module:"Math"},atan2:{name:"atan2",params:[{name:"y",description:"

y-coordinate of the point

\n",type:"Number"},{name:"x",description:"

x-coordinate of the point

\n",type:"Number"}],class:"p5",module:"Math"},cos:{name:"cos",params:[{name:"angle",description:"

the angle

\n",type:"Number"}],class:"p5",module:"Math"},sin:{name:"sin",params:[{name:"angle",description:"

the angle

\n",type:"Number"}],class:"p5",module:"Math"},tan:{name:"tan",params:[{name:"angle",description:"

the angle

\n",type:"Number"}],class:"p5",module:"Math"},degrees:{name:"degrees",params:[{name:"radians",description:"

the radians value to convert to degrees

\n",type:"Number"}],class:"p5",module:"Math"},radians:{name:"radians",params:[{name:"degrees",description:"

the degree value to convert to radians

\n",type:"Number"}],class:"p5",module:"Math"},angleMode:{name:"angleMode",params:[{name:"mode",description:"

either RADIANS or DEGREES

\n",type:"Constant"}],class:"p5",module:"Math"},textAlign:{name:"textAlign",class:"p5",module:"Typography",overloads:[{params:[{name:"horizAlign",description:"

horizontal alignment, either LEFT,\n CENTER, or RIGHT

\n",type:"Constant"},{name:"vertAlign",description:"

vertical alignment, either TOP,\n BOTTOM, CENTER, or BASELINE

\n",type:"Constant",optional:!0}],chainable:1},{params:[]}]},textLeading:{name:"textLeading",class:"p5",module:"Typography",overloads:[{params:[{name:"leading",description:"

the size in pixels for spacing between lines

\n",type:"Number"}],chainable:1},{params:[]}]},textSize:{name:"textSize",class:"p5",module:"Typography",overloads:[{params:[{name:"theSize",description:"

the size of the letters in units of pixels

\n",type:"Number"}],chainable:1},{params:[]}]},textStyle:{name:"textStyle",class:"p5",module:"Typography",overloads:[{params:[{name:"theStyle",description:"

styling for text, either NORMAL,\n ITALIC, BOLD or BOLDITALIC

\n",type:"Constant"}],chainable:1},{params:[]}]},textWidth:{name:"textWidth",params:[{name:"theText",description:"

the String of characters to measure

\n",type:"String"}],class:"p5",module:"Typography"},textAscent:{name:"textAscent",class:"p5",module:"Typography"},textDescent:{name:"textDescent",class:"p5",module:"Typography"},loadFont:{name:"loadFont",params:[{name:"path",description:"

name of the file or url to load

\n",type:"String"},{name:"callback",description:'

function to be executed after\n loadFont() completes

\n',type:"Function",optional:!0},{name:"onError",description:"

function to be executed if\n an error occurs

\n",type:"Function",optional:!0}],class:"p5",module:"Typography"},text:{name:"text",params:[{name:"str",description:"

the alphanumeric\n symbols to be displayed

\n",type:"String|Object|Array|Number|Boolean"},{name:"x",description:"

x-coordinate of text

\n",type:"Number"},{name:"y",description:"

y-coordinate of text

\n",type:"Number"},{name:"x2",description:'

by default, the width of the text box,\n see rectMode() for more info

\n',type:"Number",optional:!0},{name:"y2",description:'

by default, the height of the text box,\n see rectMode() for more info

\n',type:"Number",optional:!0}],class:"p5",module:"Typography"},textFont:{name:"textFont",class:"p5",module:"Typography",overloads:[{params:[]},{params:[{name:"font",description:'

a font loaded via loadFont(),\nor a String representing a web safe font\n(a font that is generally available across all systems)

\n',type:"Object|String"},{name:"size",description:"

the font size to use

\n",type:"Number",optional:!0}],chainable:1}]},append:{name:"append",params:[{name:"array",description:"

Array to append

\n",type:"Array"},{name:"value",description:"

to be added to the Array

\n",type:"Any"}],class:"p5",module:"Data"},arrayCopy:{name:"arrayCopy",class:"p5",module:"Data",overloads:[{params:[{name:"src",description:"

the source Array

\n",type:"Array"},{name:"srcPosition",description:"

starting position in the source Array

\n",type:"Integer"},{name:"dst",description:"

the destination Array

\n",type:"Array"},{name:"dstPosition",description:"

starting position in the destination Array

\n",type:"Integer"},{name:"length",description:"

number of Array elements to be copied

\n",type:"Integer"}]},{params:[{name:"src",description:"",type:"Array"},{name:"dst",description:"",type:"Array"},{name:"length",description:"",type:"Integer",optional:!0}]}]},concat:{name:"concat",params:[{name:"a",description:"

first Array to concatenate

\n",type:"Array"},{name:"b",description:"

second Array to concatenate

\n",type:"Array"}],class:"p5",module:"Data"},reverse:{name:"reverse",params:[{name:"list",description:"

Array to reverse

\n",type:"Array"}],class:"p5",module:"Data"},shorten:{name:"shorten",params:[{name:"list",description:"

Array to shorten

\n",type:"Array"}],class:"p5",module:"Data"},shuffle:{name:"shuffle",params:[{name:"array",description:"

Array to shuffle

\n",type:"Array"},{name:"bool",description:"

modify passed array

\n",type:"Boolean",optional:!0}],class:"p5",module:"Data"},sort:{name:"sort",params:[{name:"list",description:"

Array to sort

\n",type:"Array"},{name:"count",description:"

number of elements to sort, starting from 0

\n",type:"Integer",optional:!0}],class:"p5",module:"Data"},splice:{name:"splice",params:[{name:"list",description:"

Array to splice into

\n",type:"Array"},{name:"value",description:"

value to be spliced in

\n",type:"Any"},{name:"position",description:"

in the array from which to insert data

\n",type:"Integer"}],class:"p5",module:"Data"},subset:{name:"subset",params:[{name:"list",description:"

Array to extract from

\n",type:"Array"},{name:"start",description:"

position to begin

\n",type:"Integer"},{name:"count",description:"

number of values to extract

\n",type:"Integer",optional:!0}],class:"p5",module:"Data"},float:{name:"float",params:[{name:"str",description:"

float string to parse

\n",type:"String"}],class:"p5",module:"Data"},int:{name:"int",class:"p5",module:"Data",overloads:[{params:[{name:"n",description:"

value to parse

\n",type:"String|Boolean|Number"},{name:"radix",description:"

the radix to convert to (default: 10)

\n",type:"Integer",optional:!0}]},{params:[{name:"ns",description:"

values to parse

\n",type:"Array"}]}]},str:{name:"str",params:[{name:"n",description:"

value to parse

\n",type:"String|Boolean|Number|Array"}],class:"p5",module:"Data"},byte:{name:"byte",class:"p5",module:"Data",overloads:[{params:[{name:"n",description:"

value to parse

\n",type:"String|Boolean|Number"}]},{params:[{name:"ns",description:"

values to parse

\n",type:"Array"}]}]},char:{name:"char",class:"p5",module:"Data",overloads:[{params:[{name:"n",description:"

value to parse

\n",type:"String|Number"}]},{params:[{name:"ns",description:"

values to parse

\n",type:"Array"}]}]},unchar:{name:"unchar",class:"p5",module:"Data",overloads:[{params:[{name:"n",description:"

value to parse

\n",type:"String"}]},{params:[{name:"ns",description:"

values to parse

\n",type:"Array"}]}]},hex:{name:"hex",class:"p5",module:"Data",overloads:[{params:[{name:"n",description:"

value to parse

\n",type:"Number"},{name:"digits",description:"",type:"Number",optional:!0}]},{params:[{name:"ns",description:"

array of values to parse

\n",type:"Number[]"},{name:"digits",description:"",type:"Number",optional:!0}]}]},unhex:{name:"unhex",class:"p5",module:"Data",overloads:[{params:[{name:"n",description:"

value to parse

\n",type:"String"}]},{params:[{name:"ns",description:"

values to parse

\n",type:"Array"}]}]},join:{name:"join",params:[{name:"list",description:"

array of Strings to be joined

\n",type:"Array"},{name:"separator",description:"

String to be placed between each item

\n",type:"String"}],class:"p5",module:"Data"},match:{name:"match",params:[{name:"str",description:"

the String to be searched

\n",type:"String"},{name:"regexp",description:"

the regexp to be used for matching

\n",type:"String"}],class:"p5",module:"Data"},matchAll:{name:"matchAll",params:[{name:"str",description:"

the String to be searched

\n",type:"String"},{name:"regexp",description:"

the regexp to be used for matching

\n",type:"String"}],class:"p5",module:"Data"},nf:{name:"nf",class:"p5",module:"Data",overloads:[{params:[{name:"num",description:"

the Number to format

\n",type:"Number|String"},{name:"left",description:"

number of digits to the left of the\n decimal point

\n",type:"Integer|String",optional:!0},{name:"right",description:"

number of digits to the right of the\n decimal point

\n",type:"Integer|String",optional:!0}]},{params:[{name:"nums",description:"

the Numbers to format

\n",type:"Array"},{name:"left",description:"",type:"Integer|String",optional:!0},{name:"right",description:"",type:"Integer|String",optional:!0}]}]},nfc:{name:"nfc",class:"p5",module:"Data",overloads:[{params:[{name:"num",description:"

the Number to format

\n",type:"Number|String"},{name:"right",description:"

number of digits to the right of the\n decimal point

\n",type:"Integer|String",optional:!0}]},{params:[{name:"nums",description:"

the Numbers to format

\n",type:"Array"},{name:"right",description:"",type:"Integer|String",optional:!0}]}]},nfp:{name:"nfp",class:"p5",module:"Data",overloads:[{params:[{name:"num",description:"

the Number to format

\n",type:"Number"},{name:"left",description:"

number of digits to the left of the decimal\n point

\n",type:"Integer",optional:!0},{name:"right",description:"

number of digits to the right of the\n decimal point

\n",type:"Integer",optional:!0}]},{params:[{name:"nums",description:"

the Numbers to format

\n",type:"Number[]"},{name:"left",description:"",type:"Integer",optional:!0},{name:"right",description:"",type:"Integer",optional:!0}]}]},nfs:{name:"nfs",class:"p5",module:"Data",overloads:[{params:[{name:"num",description:"

the Number to format

\n",type:"Number"},{name:"left",description:"

number of digits to the left of the decimal\n point

\n",type:"Integer",optional:!0},{name:"right",description:"

number of digits to the right of the\n decimal point

\n",type:"Integer",optional:!0}]},{params:[{name:"nums",description:"

the Numbers to format

\n",type:"Array"},{name:"left",description:"",type:"Integer",optional:!0},{name:"right",description:"",type:"Integer",optional:!0}]}]},split:{name:"split",params:[{name:"value",description:"

the String to be split

\n",type:"String"},{name:"delim",description:"

the String used to separate the data

\n",type:"String"}],class:"p5",module:"Data"},splitTokens:{name:"splitTokens",params:[{name:"value",description:"

the String to be split

\n",type:"String"},{name:"delim",description:"

list of individual Strings that will be used as\n separators

\n",type:"String",optional:!0}],class:"p5",module:"Data"},trim:{name:"trim",class:"p5",module:"Data",overloads:[{params:[{name:"str",description:"

a String to be trimmed

\n",type:"String"}]},{params:[{name:"strs",description:"

an Array of Strings to be trimmed

\n",type:"Array"}]}]},day:{name:"day",class:"p5",module:"IO"},hour:{name:"hour",class:"p5",module:"IO"},minute:{name:"minute",class:"p5",module:"IO"},millis:{name:"millis",class:"p5",module:"IO"},month:{name:"month",class:"p5",module:"IO"},second:{name:"second",class:"p5",module:"IO"},year:{name:"year",class:"p5",module:"IO"},plane:{name:"plane",params:[{name:"width",description:"

width of the plane

\n",type:"Number",optional:!0},{name:"height",description:"

height of the plane

\n",type:"Number",optional:!0},{name:"detailX",description:"

Optional number of triangle\n subdivisions in x-dimension

\n",type:"Integer",optional:!0},{name:"detailY",description:"

Optional number of triangle\n subdivisions in y-dimension

\n",type:"Integer",optional:!0}],class:"p5",module:"Shape"},box:{name:"box",params:[{name:"width",description:"

width of the box

\n",type:"Number",optional:!0},{name:"Height",description:"

height of the box

\n",type:"Number",optional:!0},{name:"depth",description:"

depth of the box

\n",type:"Number",optional:!0},{name:"detailX",description:"

Optional number of triangle\n subdivisions in x-dimension

\n",type:"Integer",optional:!0},{name:"detailY",description:"

Optional number of triangle\n subdivisions in y-dimension

\n",type:"Integer",optional:!0}],class:"p5",module:"Shape"},sphere:{name:"sphere",params:[{name:"radius",description:"

radius of circle

\n",type:"Number",optional:!0},{name:"detailX",description:"

optional number of subdivisions in x-dimension

\n",type:"Integer",optional:!0},{name:"detailY",description:"

optional number of subdivisions in y-dimension

\n",type:"Integer",optional:!0}],class:"p5",module:"Shape"},cylinder:{name:"cylinder",params:[{name:"radius",description:"

radius of the surface

\n",type:"Number",optional:!0},{name:"height",description:"

height of the cylinder

\n",type:"Number",optional:!0},{name:"detailX",description:"

number of subdivisions in x-dimension;\n default is 24

\n",type:"Integer",optional:!0},{name:"detailY",description:"

number of subdivisions in y-dimension;\n default is 1

\n",type:"Integer",optional:!0},{name:"bottomCap",description:"

whether to draw the bottom of the cylinder

\n",type:"Boolean",optional:!0},{name:"topCap",description:"

whether to draw the top of the cylinder

\n",type:"Boolean",optional:!0}],class:"p5",module:"Shape"},cone:{name:"cone",params:[{name:"radius",description:"

radius of the bottom surface

\n",type:"Number",optional:!0},{name:"height",description:"

height of the cone

\n",type:"Number",optional:!0},{name:"detailX",description:"

number of segments,\n the more segments the smoother geometry\n default is 24

\n",type:"Integer",optional:!0},{name:"detailY",description:"

number of segments,\n the more segments the smoother geometry\n default is 1

\n",type:"Integer",optional:!0},{name:"cap",description:"

whether to draw the base of the cone

\n",type:"Boolean",optional:!0}],class:"p5",module:"Shape"},ellipsoid:{name:"ellipsoid",params:[{name:"radiusx",description:"

x-radius of ellipsoid

\n",type:"Number",optional:!0},{name:"radiusy",description:"

y-radius of ellipsoid

\n",type:"Number",optional:!0},{name:"radiusz",description:"

z-radius of ellipsoid

\n",type:"Number",optional:!0},{name:"detailX",description:"

number of segments,\n the more segments the smoother geometry\n default is 24. Avoid detail number above\n 150, it may crash the browser.

\n",type:"Integer",optional:!0},{name:"detailY",description:"

number of segments,\n the more segments the smoother geometry\n default is 16. Avoid detail number above\n 150, it may crash the browser.

\n",type:"Integer",optional:!0}],class:"p5",module:"Shape"},torus:{name:"torus",params:[{name:"radius",description:"

radius of the whole ring

\n",type:"Number",optional:!0},{name:"tubeRadius",description:"

radius of the tube

\n",type:"Number",optional:!0},{name:"detailX",description:"

number of segments in x-dimension,\n the more segments the smoother geometry\n default is 24

\n",type:"Integer",optional:!0},{name:"detailY",description:"

number of segments in y-dimension,\n the more segments the smoother geometry\n default is 16

\n",type:"Integer",optional:!0}],class:"p5",module:"Shape"},orbitControl:{name:"orbitControl",params:[{name:"sensitivityX",description:"

sensitivity to mouse movement along X axis

\n",type:"Number",optional:!0},{name:"sensitivityY",description:"

sensitivity to mouse movement along Y axis

\n",type:"Number",optional:!0},{name:"sensitivityZ",description:"

sensitivity to scroll movement along Z axis

\n",type:"Number",optional:!0}],class:"p5",module:"Lights, Camera"},debugMode:{name:"debugMode",class:"p5",module:"Lights, Camera",overloads:[{params:[]},{params:[{name:"mode",description:"

either GRID or AXES

\n",type:"Constant"}]},{params:[{name:"mode",description:"",type:"Constant"},{name:"gridSize",description:"

size of one side of the grid

\n",type:"Number",optional:!0},{name:"gridDivisions",description:"

number of divisions in the grid

\n",type:"Number",optional:!0},{name:"xOff",description:"

X axis offset from origin (0,0,0)

\n",type:"Number",optional:!0},{name:"yOff",description:"

Y axis offset from origin (0,0,0)

\n",type:"Number",optional:!0},{name:"zOff",description:"

Z axis offset from origin (0,0,0)

\n",type:"Number",optional:!0}]},{params:[{name:"mode",description:"",type:"Constant"},{name:"axesSize",description:"

size of axes icon

\n",type:"Number",optional:!0},{name:"xOff",description:"",type:"Number",optional:!0},{name:"yOff",description:"",type:"Number",optional:!0},{name:"zOff",description:"",type:"Number",optional:!0}]},{params:[{name:"gridSize",description:"",type:"Number",optional:!0},{name:"gridDivisions",description:"",type:"Number",optional:!0},{name:"gridXOff",description:"",type:"Number",optional:!0},{name:"gridYOff",description:"",type:"Number",optional:!0},{name:"gridZOff",description:"",type:"Number",optional:!0},{name:"axesSize",description:"",type:"Number",optional:!0},{name:"axesXOff",description:"",type:"Number",optional:!0},{name:"axesYOff",description:"",type:"Number",optional:!0},{name:"axesZOff",description:"",type:"Number",optional:!0}]}]},noDebugMode:{name:"noDebugMode",class:"p5",module:"Lights, Camera"},ambientLight:{name:"ambientLight",class:"p5",module:"Lights, Camera",overloads:[{params:[{name:"v1",description:"

red or hue value relative to\n the current color range

\n",type:"Number"},{name:"v2",description:"

green or saturation value\n relative to the current color range

\n",type:"Number"},{name:"v3",description:"

blue or brightness value\n relative to the current color range

\n",type:"Number"},{name:"alpha",description:"

the alpha value

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"value",description:"

a color string

\n",type:"String"}],chainable:1},{params:[{name:"gray",description:"

a gray value

\n",type:"Number"},{name:"alpha",description:"",type:"Number",optional:!0}],chainable:1},{params:[{name:"values",description:"

an array containing the red,green,blue &\n and alpha components of the color

\n",type:"Number[]"}],chainable:1},{params:[{name:"color",description:"

the ambient light color

\n",type:"p5.Color"}],chainable:1}]},specularColor:{name:"specularColor",class:"p5",module:"Lights, Camera",overloads:[{params:[{name:"v1",description:"

red or hue value relative to\n the current color range

\n",type:"Number"},{name:"v2",description:"

green or saturation value\n relative to the current color range

\n",type:"Number"},{name:"v3",description:"

blue or brightness value\n relative to the current color range

\n",type:"Number"}],chainable:1},{params:[{name:"value",description:"

a color string

\n",type:"String"}],chainable:1},{params:[{name:"gray",description:"

a gray value

\n",type:"Number"}],chainable:1},{params:[{name:"values",description:"

an array containing the red,green,blue &\n and alpha components of the color

\n",type:"Number[]"}],chainable:1},{params:[{name:"color",description:"

the ambient light color

\n",type:"p5.Color"}],chainable:1}]},directionalLight:{name:"directionalLight",class:"p5",module:"Lights, Camera",overloads:[{params:[{name:"v1",description:"

red or hue value (depending on the current\ncolor mode),

\n",type:"Number"},{name:"v2",description:"

green or saturation value

\n",type:"Number"},{name:"v3",description:"

blue or brightness value

\n",type:"Number"},{name:"position",description:"

the direction of the light

\n",type:"p5.Vector"}],chainable:1},{params:[{name:"color",description:'

color Array, CSS color string,\n or p5.Color value

\n',type:"Number[]|String|p5.Color"},{name:"x",description:"

x axis direction

\n",type:"Number"},{name:"y",description:"

y axis direction

\n",type:"Number"},{name:"z",description:"

z axis direction

\n",type:"Number"}],chainable:1},{params:[{name:"color",description:"",type:"Number[]|String|p5.Color"},{name:"position",description:"",type:"p5.Vector"}],chainable:1},{params:[{name:"v1",description:"",type:"Number"},{name:"v2",description:"",type:"Number"},{name:"v3",description:"",type:"Number"},{name:"x",description:"",type:"Number"},{name:"y",description:"",type:"Number"},{name:"z",description:"",type:"Number"}],chainable:1}]},pointLight:{name:"pointLight",class:"p5",module:"Lights, Camera",overloads:[{params:[{name:"v1",description:"

red or hue value (depending on the current\ncolor mode),

\n",type:"Number"},{name:"v2",description:"

green or saturation value

\n",type:"Number"},{name:"v3",description:"

blue or brightness value

\n",type:"Number"},{name:"x",description:"

x axis position

\n",type:"Number"},{name:"y",description:"

y axis position

\n",type:"Number"},{name:"z",description:"

z axis position

\n",type:"Number"}],chainable:1},{params:[{name:"v1",description:"",type:"Number"},{name:"v2",description:"",type:"Number"},{name:"v3",description:"",type:"Number"},{name:"position",description:"

the position of the light

\n",type:"p5.Vector"}],chainable:1},{params:[{name:"color",description:'

color Array, CSS color string,\nor p5.Color value

\n',type:"Number[]|String|p5.Color"},{name:"x",description:"",type:"Number"},{name:"y",description:"",type:"Number"},{name:"z",description:"",type:"Number"}],chainable:1},{params:[{name:"color",description:"",type:"Number[]|String|p5.Color"},{name:"position",description:"",type:"p5.Vector"}],chainable:1}]},lights:{name:"lights",class:"p5",module:"Lights, Camera"},lightFalloff:{name:"lightFalloff",params:[{name:"constant",description:"

constant value for determining falloff

\n",type:"Number"},{name:"linear",description:"

linear value for determining falloff

\n",type:"Number"},{name:"quadratic",description:"

quadratic value for determining falloff

\n",type:"Number"}],class:"p5",module:"Lights, Camera"},spotLight:{name:"spotLight",class:"p5",module:"Lights, Camera",overloads:[{params:[{name:"v1",description:"

red or hue value (depending on the current\ncolor mode),

\n",type:"Number"},{name:"v2",description:"

green or saturation value

\n",type:"Number"},{name:"v3",description:"

blue or brightness value

\n",type:"Number"},{name:"x",description:"

x axis position

\n",type:"Number"},{name:"y",description:"

y axis position

\n",type:"Number"},{name:"z",description:"

z axis position

\n",type:"Number"},{name:"rx",description:"

x axis direction of light

\n",type:"Number"},{name:"ry",description:"

y axis direction of light

\n",type:"Number"},{name:"rz",description:"

z axis direction of light

\n",type:"Number"},{name:"angle",description:"

optional parameter for angle. Defaults to PI/3

\n",type:"Number",optional:!0},{name:"conc",description:"

optional parameter for concentration. Defaults to 100

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"color",description:'

color Array, CSS color string,\nor p5.Color value

\n',type:"Number[]|String|p5.Color"},{name:"position",description:"

the position of the light

\n",type:"p5.Vector"},{name:"direction",description:"

the direction of the light

\n",type:"p5.Vector"},{name:"angle",description:"",type:"Number",optional:!0},{name:"conc",description:"",type:"Number",optional:!0}]},{params:[{name:"v1",description:"",type:"Number"},{name:"v2",description:"",type:"Number"},{name:"v3",description:"",type:"Number"},{name:"position",description:"",type:"p5.Vector"},{name:"direction",description:"",type:"p5.Vector"},{name:"angle",description:"",type:"Number",optional:!0},{name:"conc",description:"",type:"Number",optional:!0}]},{params:[{name:"color",description:"",type:"Number[]|String|p5.Color"},{name:"x",description:"",type:"Number"},{name:"y",description:"",type:"Number"},{name:"z",description:"",type:"Number"},{name:"direction",description:"",type:"p5.Vector"},{name:"angle",description:"",type:"Number",optional:!0},{name:"conc",description:"",type:"Number",optional:!0}]},{params:[{name:"color",description:"",type:"Number[]|String|p5.Color"},{name:"position",description:"",type:"p5.Vector"},{name:"rx",description:"",type:"Number"},{name:"ry",description:"",type:"Number"},{name:"rz",description:"",type:"Number"},{name:"angle",description:"",type:"Number",optional:!0},{name:"conc",description:"",type:"Number",optional:!0}]},{params:[{name:"v1",description:"",type:"Number"},{name:"v2",description:"",type:"Number"},{name:"v3",description:"",type:"Number"},{name:"x",description:"",type:"Number"},{name:"y",description:"",type:"Number"},{name:"z",description:"",type:"Number"},{name:"direction",description:"",type:"p5.Vector"},{name:"angle",description:"",type:"Number",optional:!0},{name:"conc",description:"",type:"Number",optional:!0}]},{params:[{name:"v1",description:"",type:"Number"},{name:"v2",description:"",type:"Number"},{name:"v3",description:"",type:"Number"},{name:"position",description:"",type:"p5.Vector"},{name:"rx",description:"",type:"Number"},{name:"ry",description:"",type:"Number"},{name:"rz",description:"",type:"Number"},{name:"angle",description:"",type:"Number",optional:!0},{name:"conc",description:"",type:"Number",optional:!0}]},{params:[{name:"color",description:"",type:"Number[]|String|p5.Color"},{name:"x",description:"",type:"Number"},{name:"y",description:"",type:"Number"},{name:"z",description:"",type:"Number"},{name:"rx",description:"",type:"Number"},{name:"ry",description:"",type:"Number"},{name:"rz",description:"",type:"Number"},{name:"angle",description:"",type:"Number",optional:!0},{name:"conc",description:"",type:"Number",optional:!0}]}]},noLights:{name:"noLights",class:"p5",module:"Lights, Camera"},loadModel:{name:"loadModel",class:"p5",module:"Shape",overloads:[{params:[{name:"path",description:"

Path of the model to be loaded

\n",type:"String"},{name:"normalize",description:"

If true, scale the model to a\n standardized size when loading

\n",type:"Boolean"},{name:"successCallback",description:"

Function to be called\n once the model is loaded. Will be passed\n the 3D model object.

\n",type:"function(p5.Geometry)",optional:!0},{name:"failureCallback",description:"

called with event error if\n the model fails to load.

\n",type:"Function(Event)",optional:!0},{name:"fileType",description:"

The file extension of the model\n (.stl, .obj).

\n",type:"String",optional:!0}]},{params:[{name:"path",description:"",type:"String"},{name:"successCallback",description:"",type:"function(p5.Geometry)",optional:!0},{name:"failureCallback",description:"",type:"Function(Event)",optional:!0},{name:"fileType",description:"",type:"String",optional:!0}]}]},model:{name:"model",params:[{name:"model",description:"

Loaded 3d model to be rendered

\n",type:"p5.Geometry"}],class:"p5",module:"Shape"},loadShader:{name:"loadShader",params:[{name:"vertFilename",description:"

path to file containing vertex shader\nsource code

\n",type:"String"},{name:"fragFilename",description:"

path to file containing fragment shader\nsource code

\n",type:"String"},{name:"callback",description:"

callback to be executed after loadShader\ncompletes. On success, the Shader object is passed as the first argument.

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

callback to be executed when an error\noccurs inside loadShader. On error, the error is passed as the first\nargument.

\n",type:"Function",optional:!0}],class:"p5",module:"Lights, Camera"},createShader:{name:"createShader",params:[{name:"vertSrc",description:"

source code for the vertex shader

\n",type:"String"},{name:"fragSrc",description:"

source code for the fragment shader

\n",type:"String"}],class:"p5",module:"Lights, Camera"},shader:{name:"shader",params:[{name:"s",description:'

the desired p5.Shader to use for rendering\nshapes.

\n',type:"p5.Shader",optional:!0}],class:"p5",module:"Lights, Camera"},resetShader:{name:"resetShader",class:"p5",module:"Lights, Camera"},normalMaterial:{name:"normalMaterial",class:"p5",module:"Lights, Camera"},texture:{name:"texture",params:[{name:"tex",description:"

2-dimensional graphics\n to render as texture

\n",type:"p5.Image|p5.MediaElement|p5.Graphics"}],class:"p5",module:"Lights, Camera"},textureMode:{name:"textureMode",params:[{name:"mode",description:"

either IMAGE or NORMAL

\n",type:"Constant"}],class:"p5",module:"Lights, Camera"},textureWrap:{name:"textureWrap",params:[{name:"wrapX",description:"

either CLAMP, REPEAT, or MIRROR

\n",type:"Constant"},{name:"wrapY",description:"

either CLAMP, REPEAT, or MIRROR

\n",type:"Constant",optional:!0}],class:"p5",module:"Lights, Camera"},ambientMaterial:{name:"ambientMaterial",class:"p5",module:"Lights, Camera",overloads:[{params:[{name:"v1",description:"

gray value, red or hue value\n (depending on the current color mode),

\n",type:"Number"},{name:"v2",description:"

green or saturation value

\n",type:"Number",optional:!0},{name:"v3",description:"

blue or brightness value

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"color",description:"

color, color Array, or CSS color string

\n",type:"Number[]|String|p5.Color"}],chainable:1}]},emissiveMaterial:{name:"emissiveMaterial",class:"p5",module:"Lights, Camera",overloads:[{params:[{name:"v1",description:"

gray value, red or hue value\n (depending on the current color mode),

\n",type:"Number"},{name:"v2",description:"

green or saturation value

\n",type:"Number",optional:!0},{name:"v3",description:"

blue or brightness value

\n",type:"Number",optional:!0},{name:"a",description:"

opacity

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"color",description:"

color, color Array, or CSS color string

\n",type:"Number[]|String|p5.Color"}],chainable:1}]},specularMaterial:{name:"specularMaterial",class:"p5",module:"Lights, Camera",overloads:[{params:[{name:"gray",description:"

number specifying value between white and black.

\n",type:"Number"},{name:"alpha",description:"

alpha value relative to current color range\n (default is 0-255)

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"v1",description:"

red or hue value relative to\n the current color range

\n",type:"Number"},{name:"v2",description:"

green or saturation value\n relative to the current color range

\n",type:"Number"},{name:"v3",description:"

blue or brightness value\n relative to the current color range

\n",type:"Number"},{name:"alpha",description:"",type:"Number",optional:!0}],chainable:1},{params:[{name:"color",description:"

color Array, or CSS color string

\n",type:"Number[]|String|p5.Color"}],chainable:1}]},shininess:{name:"shininess",params:[{name:"shine",description:"

Degree of Shininess.\n Defaults to 1.

\n",type:"Number"}],class:"p5",module:"Lights, Camera"},camera:{name:"camera",params:[{name:"x",description:"

camera position value on x axis

\n",type:"Number",optional:!0},{name:"y",description:"

camera position value on y axis

\n",type:"Number",optional:!0},{name:"z",description:"

camera position value on z axis

\n",type:"Number",optional:!0},{name:"centerX",description:"

x coordinate representing center of the sketch

\n",type:"Number",optional:!0},{name:"centerY",description:"

y coordinate representing center of the sketch

\n",type:"Number",optional:!0},{name:"centerZ",description:"

z coordinate representing center of the sketch

\n",type:"Number",optional:!0},{name:"upX",description:"

x component of direction 'up' from camera

\n",type:"Number",optional:!0},{name:"upY",description:"

y component of direction 'up' from camera

\n",type:"Number",optional:!0},{name:"upZ",description:"

z component of direction 'up' from camera

\n",type:"Number",optional:!0}],class:"p5",module:"Lights, Camera"},perspective:{name:"perspective",params:[{name:"fovy",description:'

camera frustum vertical field of view,\n from bottom to top of view, in angleMode units

\n',type:"Number",optional:!0},{name:"aspect",description:"

camera frustum aspect ratio

\n",type:"Number",optional:!0},{name:"near",description:"

frustum near plane length

\n",type:"Number",optional:!0},{name:"far",description:"

frustum far plane length

\n",type:"Number",optional:!0}],class:"p5",module:"Lights, Camera"},ortho:{name:"ortho",params:[{name:"left",description:"

camera frustum left plane

\n",type:"Number",optional:!0},{name:"right",description:"

camera frustum right plane

\n",type:"Number",optional:!0},{name:"bottom",description:"

camera frustum bottom plane

\n",type:"Number",optional:!0},{name:"top",description:"

camera frustum top plane

\n",type:"Number",optional:!0},{name:"near",description:"

camera frustum near plane

\n",type:"Number",optional:!0},{name:"far",description:"

camera frustum far plane

\n",type:"Number",optional:!0}],class:"p5",module:"Lights, Camera"},frustum:{name:"frustum",params:[{name:"left",description:"

camera frustum left plane

\n",type:"Number",optional:!0},{name:"right",description:"

camera frustum right plane

\n",type:"Number",optional:!0},{name:"bottom",description:"

camera frustum bottom plane

\n",type:"Number",optional:!0},{name:"top",description:"

camera frustum top plane

\n",type:"Number",optional:!0},{name:"near",description:"

camera frustum near plane

\n",type:"Number",optional:!0},{name:"far",description:"

camera frustum far plane

\n",type:"Number",optional:!0}],class:"p5",module:"Lights, Camera"},createCamera:{name:"createCamera",class:"p5",module:"Lights, Camera"},setCamera:{name:"setCamera",params:[{name:"cam",description:"

p5.Camera object

\n",type:"p5.Camera"}],class:"p5",module:"Lights, Camera"},setAttributes:{name:"setAttributes",class:"p5",module:"Rendering",overloads:[{params:[{name:"key",description:"

Name of attribute

\n",type:"String"},{name:"value",description:"

New value of named attribute

\n",type:"Boolean"}]},{params:[{name:"obj",description:"

object with key-value pairs

\n",type:"Object"}]}]},sampleRate:{name:"sampleRate",class:"p5",module:"p5.sound"},freqToMidi:{name:"freqToMidi",params:[{name:"frequency",description:'

A freqeuncy, for example, the "A"\n above Middle C is 440Hz

\n',type:"Number"}],class:"p5",module:"p5.sound"},midiToFreq:{name:"midiToFreq",params:[{name:"midiNote",description:"

The number of a MIDI note

\n",type:"Number"}],class:"p5",module:"p5.sound"},soundFormats:{name:"soundFormats",params:[{name:"formats",description:"

i.e. 'mp3', 'wav', 'ogg'

\n",type:"String",optional:!0,multiple:!0}],class:"p5",module:"p5.sound"},getAudioContext:{name:"getAudioContext",class:"p5",module:"p5.sound"},userStartAudio:{params:[{name:"element(s)",description:"

This argument can be an Element,\n Selector String, NodeList, p5.Element,\n jQuery Element, or an Array of any of those.

\n",type:"Element|Array",optional:!0},{name:"callback",description:"

Callback to invoke when the AudioContext\n has started

\n",type:"Function",optional:!0}],name:"userStartAudio",class:"p5",module:"p5.sound"},loadSound:{name:"loadSound",params:[{name:"path",description:"

Path to the sound file, or an array with\n paths to soundfiles in multiple formats\n i.e. ['sound.ogg', 'sound.mp3'].\n Alternately, accepts an object: either\n from the HTML5 File API, or a p5.File.

\n",type:"String|Array"},{name:"successCallback",description:"

Name of a function to call once file loads

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

Name of a function to call if there is\n an error loading the file.

\n",type:"Function",optional:!0},{name:"whileLoading",description:"

Name of a function to call while file is loading.\n This function will receive the percentage loaded\n so far, from 0.0 to 1.0.

\n",type:"Function",optional:!0}],class:"p5",module:"p5.sound"},createConvolver:{name:"createConvolver",params:[{name:"path",description:"

path to a sound file

\n",type:"String"},{name:"callback",description:"

function to call if loading is successful.\n The object will be passed in as the argument\n to the callback function.

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

function to call if loading is not successful.\n A custom error will be passed in as the argument\n to the callback function.

\n",type:"Function",optional:!0}],class:"p5",module:"p5.sound"},setBPM:{name:"setBPM",params:[{name:"BPM",description:"

Beats Per Minute

\n",type:"Number"},{name:"rampTime",description:"

Seconds from now

\n",type:"Number"}],class:"p5",module:"p5.sound"},saveSound:{name:"saveSound",params:[{name:"soundFile",description:"

p5.SoundFile that you wish to save

\n",type:"p5.SoundFile"},{name:"fileName",description:"

name of the resulting .wav file.

\n",type:"String"}],class:"p5",module:"p5.sound"}},"p5.Color":{toString:{name:"toString",params:[{name:"format",description:"

How the color string will be formatted.\nLeaving this empty formats the string as rgba(r, g, b, a).\n'#rgb' '#rgba' '#rrggbb' and '#rrggbbaa' format as hexadecimal color codes.\n'rgb' 'hsb' and 'hsl' return the color formatted in the specified color mode.\n'rgba' 'hsba' and 'hsla' are the same as above but with alpha channels.\n'rgb%' 'hsb%' 'hsl%' 'rgba%' 'hsba%' and 'hsla%' format as percentages.

\n",type:"String",optional:!0}],class:"p5.Color",module:"Color"},setRed:{name:"setRed",params:[{name:"red",description:"

the new red value

\n",type:"Number"}],class:"p5.Color",module:"Color"},setGreen:{name:"setGreen",params:[{name:"green",description:"

the new green value

\n",type:"Number"}],class:"p5.Color",module:"Color"},setBlue:{name:"setBlue",params:[{name:"blue",description:"

the new blue value

\n",type:"Number"}],class:"p5.Color",module:"Color"},setAlpha:{name:"setAlpha",params:[{name:"alpha",description:"

the new alpha value

\n",type:"Number"}],class:"p5.Color",module:"Color"}},"p5.Element":{elt:{name:"elt",class:"p5.Element",module:"DOM"},parent:{name:"parent",class:"p5.Element",module:"DOM",overloads:[{params:[{name:"parent",description:'

the ID, DOM node, or p5.Element\n of desired parent element

\n',type:"String|p5.Element|Object"}],chainable:1},{params:[]}]},id:{name:"id",class:"p5.Element",module:"DOM",overloads:[{params:[{name:"id",description:"

ID of the element

\n",type:"String"}],chainable:1},{params:[]}]},class:{name:"class",class:"p5.Element",module:"DOM",overloads:[{params:[{name:"class",description:"

class to add

\n",type:"String"}],chainable:1},{params:[]}]},mousePressed:{name:"mousePressed",params:[{name:"fxn",description:"

function to be fired when mouse is\n pressed over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],class:"p5.Element",module:"DOM"},doubleClicked:{name:"doubleClicked",params:[{name:"fxn",description:"

function to be fired when mouse is\n double clicked over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],class:"p5.Element",module:"DOM"},mouseWheel:{name:"mouseWheel",params:[{name:"fxn",description:"

function to be fired when mouse is\n scrolled over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],class:"p5.Element",module:"DOM"},mouseReleased:{name:"mouseReleased",params:[{name:"fxn",description:"

function to be fired when mouse is\n released over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],class:"p5.Element",module:"DOM"},mouseClicked:{name:"mouseClicked",params:[{name:"fxn",description:"

function to be fired when mouse is\n clicked over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],class:"p5.Element",module:"DOM"},mouseMoved:{name:"mouseMoved",params:[{name:"fxn",description:"

function to be fired when a mouse moves\n over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],class:"p5.Element",module:"DOM"},mouseOver:{name:"mouseOver",params:[{name:"fxn",description:"

function to be fired when a mouse moves\n onto the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],class:"p5.Element",module:"DOM"},mouseOut:{name:"mouseOut",params:[{name:"fxn",description:"

function to be fired when a mouse\n moves off of an element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],class:"p5.Element",module:"DOM"},touchStarted:{name:"touchStarted",params:[{name:"fxn",description:"

function to be fired when a touch\n starts over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],class:"p5.Element",module:"DOM"},touchMoved:{name:"touchMoved",params:[{name:"fxn",description:"

function to be fired when a touch moves over\n the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],class:"p5.Element",module:"DOM"},touchEnded:{name:"touchEnded",params:[{name:"fxn",description:"

function to be fired when a touch ends\n over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],class:"p5.Element",module:"DOM"},dragOver:{name:"dragOver",params:[{name:"fxn",description:"

function to be fired when a file is\n dragged over the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],class:"p5.Element",module:"DOM"},dragLeave:{name:"dragLeave",params:[{name:"fxn",description:"

function to be fired when a file is\n dragged off the element.\n if false is passed instead, the previously\n firing function will no longer fire.

\n",type:"Function|Boolean"}],class:"p5.Element",module:"DOM"},addClass:{name:"addClass",params:[{name:"class",description:"

name of class to add

\n",type:"String"}],class:"p5.Element",module:"DOM"},removeClass:{name:"removeClass",params:[{name:"class",description:"

name of class to remove

\n",type:"String"}],class:"p5.Element",module:"DOM"},hasClass:{name:"hasClass",params:[{name:"c",description:"

class name of class to check

\n",type:"String"}],class:"p5.Element",module:"DOM"},toggleClass:{name:"toggleClass",params:[{name:"c",description:"

class name to toggle

\n",type:"String"}],class:"p5.Element",module:"DOM"},child:{name:"child",class:"p5.Element",module:"DOM",overloads:[{params:[]},{params:[{name:"child",description:'

the ID, DOM node, or p5.Element\n to add to the current element

\n',type:"String|p5.Element",optional:!0}],chainable:1}]},center:{name:"center",params:[{name:"align",description:"

passing 'vertical', 'horizontal' aligns element accordingly

\n",type:"String",optional:!0}],class:"p5.Element",module:"DOM"},html:{name:"html",class:"p5.Element",module:"DOM",overloads:[{params:[]},{params:[{name:"html",description:"

the HTML to be placed inside the element

\n",type:"String",optional:!0},{name:"append",description:"

whether to append HTML to existing

\n",type:"Boolean",optional:!0}],chainable:1}]},position:{name:"position",class:"p5.Element",module:"DOM",overloads:[{params:[]},{params:[{name:"x",description:"

x-position relative to upper left of window (optional)

\n",type:"Number",optional:!0},{name:"y",description:"

y-position relative to upper left of window (optional)

\n",type:"Number",optional:!0},{name:"positionType",description:"

it can be static, fixed, relative, sticky, initial or inherit (optional)

\n",type:"String"}],chainable:1}]},style:{name:"style",class:"p5.Element",module:"DOM",overloads:[{params:[{name:"property",description:"

property to be set

\n",type:"String"}]},{params:[{name:"property",description:"",type:"String"},{name:"value",description:"

value to assign to property

\n",type:"String|p5.Color"}],chainable:1}]},attribute:{name:"attribute",class:"p5.Element",module:"DOM",overloads:[{params:[]},{params:[{name:"attr",description:"

attribute to set

\n",type:"String"},{name:"value",description:"

value to assign to attribute

\n",type:"String"}],chainable:1}]},removeAttribute:{name:"removeAttribute",params:[{name:"attr",description:"

attribute to remove

\n",type:"String"}],class:"p5.Element",module:"DOM"},value:{name:"value",class:"p5.Element",module:"DOM",overloads:[{params:[]},{params:[{name:"value",description:"",type:"String|Number"}],chainable:1}]},show:{name:"show",class:"p5.Element",module:"DOM"},hide:{name:"hide",class:"p5.Element",module:"DOM"},size:{name:"size",class:"p5.Element",module:"DOM",overloads:[{params:[]},{params:[{name:"w",description:"

width of the element, either AUTO, or a number

\n",type:"Number|Constant"},{name:"h",description:"

height of the element, either AUTO, or a number

\n",type:"Number|Constant",optional:!0}],chainable:1}]},remove:{name:"remove",class:"p5.Element",module:"DOM"},drop:{name:"drop",params:[{name:"callback",description:"

callback to receive loaded file, called for each file dropped.

\n",type:"Function"},{name:"fxn",description:"

callback triggered once when files are dropped with the drop event.

\n",type:"Function",optional:!0}],class:"p5.Element",module:"DOM"}},"p5.Graphics":{reset:{name:"reset",class:"p5.Graphics",module:"Rendering"},remove:{name:"remove",class:"p5.Graphics",module:"Rendering"}},JSON:{stringify:{name:"stringify",params:[{name:"object",description:"

:Javascript object that you would like to convert to JSON

\n",type:"Object"}],class:"JSON",module:"Foundation"}},console:{log:{name:"log",params:[{name:"message",description:"

:Message that you would like to print to the console

\n",type:"String|Expression|Object"}],class:"console",module:"Foundation"}},"p5.TypedDict":{size:{name:"size",class:"p5.TypedDict",module:"Data"},hasKey:{name:"hasKey",params:[{name:"key",description:"

that you want to look up

\n",type:"Number|String"}],class:"p5.TypedDict",module:"Data"},get:{name:"get",params:[{name:"the",description:"

key you want to access

\n",type:"Number|String"}],class:"p5.TypedDict",module:"Data"},set:{name:"set",params:[{name:"key",description:"",type:"Number|String"},{name:"value",description:"",type:"Number|String"}],class:"p5.TypedDict",module:"Data"},create:{name:"create",class:"p5.TypedDict",module:"Data",overloads:[{params:[{name:"key",description:"",type:"Number|String"},{name:"value",description:"",type:"Number|String"}]},{params:[{name:"obj",description:"

key/value pair

\n",type:"Object"}]}]},clear:{name:"clear",class:"p5.TypedDict",module:"Data"},remove:{name:"remove",params:[{name:"key",description:"

for the pair to remove

\n",type:"Number|String"}],class:"p5.TypedDict",module:"Data"},print:{name:"print",class:"p5.TypedDict",module:"Data"},saveTable:{name:"saveTable",class:"p5.TypedDict",module:"Data"},saveJSON:{name:"saveJSON",class:"p5.TypedDict",module:"Data"}},"p5.NumberDict":{add:{name:"add",params:[{name:"Key",description:"

for the value you wish to add to

\n",type:"Number"},{name:"Number",description:"

to add to the value

\n",type:"Number"}],class:"p5.NumberDict",module:"Data"},sub:{name:"sub",params:[{name:"Key",description:"

for the value you wish to subtract from

\n",type:"Number"},{name:"Number",description:"

to subtract from the value

\n",type:"Number"}],class:"p5.NumberDict",module:"Data"},mult:{name:"mult",params:[{name:"Key",description:"

for value you wish to multiply

\n",type:"Number"},{name:"Amount",description:"

to multiply the value by

\n",type:"Number"}],class:"p5.NumberDict",module:"Data"},div:{name:"div",params:[{name:"Key",description:"

for value you wish to divide

\n",type:"Number"},{name:"Amount",description:"

to divide the value by

\n",type:"Number"}],class:"p5.NumberDict",module:"Data"},minValue:{name:"minValue",class:"p5.NumberDict",module:"Data"},maxValue:{name:"maxValue",class:"p5.NumberDict",module:"Data"},minKey:{name:"minKey",class:"p5.NumberDict",module:"Data"},maxKey:{name:"maxKey",class:"p5.NumberDict",module:"Data"}},"p5.MediaElement":{src:{name:"src",class:"p5.MediaElement",module:"DOM"},play:{name:"play",class:"p5.MediaElement",module:"DOM"},stop:{name:"stop",class:"p5.MediaElement",module:"DOM"},pause:{name:"pause",class:"p5.MediaElement",module:"DOM"},loop:{name:"loop",class:"p5.MediaElement",module:"DOM"},noLoop:{name:"noLoop",class:"p5.MediaElement",module:"DOM"},autoplay:{name:"autoplay",params:[{name:"shouldAutoplay",description:"

whether the element should autoplay

\n",type:"Boolean"}],class:"p5.MediaElement",module:"DOM"},volume:{name:"volume",class:"p5.MediaElement",module:"DOM",overloads:[{params:[]},{params:[{name:"val",description:"

volume between 0.0 and 1.0

\n",type:"Number"}],chainable:1}]},speed:{name:"speed",class:"p5.MediaElement",module:"DOM",overloads:[{params:[]},{params:[{name:"speed",description:"

speed multiplier for element playback

\n",type:"Number"}],chainable:1}]},time:{name:"time",class:"p5.MediaElement",module:"DOM",overloads:[{params:[]},{params:[{name:"time",description:"

time to jump to (in seconds)

\n",type:"Number"}],chainable:1}]},duration:{name:"duration",class:"p5.MediaElement",module:"DOM"},onended:{name:"onended",params:[{name:"callback",description:"

function to call when the\n soundfile has ended. The\n media element will be passed\n in as the argument to the\n callback.

\n",type:"Function"}],class:"p5.MediaElement",module:"DOM"},connect:{name:"connect",params:[{name:"audioNode",description:"

AudioNode from the Web Audio API,\nor an object from the p5.sound library

\n",type:"AudioNode|Object"}],class:"p5.MediaElement",module:"DOM"},disconnect:{name:"disconnect",class:"p5.MediaElement",module:"DOM"},showControls:{name:"showControls",class:"p5.MediaElement",module:"DOM"},hideControls:{name:"hideControls",class:"p5.MediaElement",module:"DOM"},addCue:{name:"addCue",params:[{name:"time",description:"

Time in seconds, relative to this media\n element's playback. For example, to trigger\n an event every time playback reaches two\n seconds, pass in the number 2. This will be\n passed as the first parameter to\n the callback function.

\n",type:"Number"},{name:"callback",description:"

Name of a function that will be\n called at the given time. The callback will\n receive time and (optionally) param as its\n two parameters.

\n",type:"Function"},{name:"value",description:"

An object to be passed as the\n second parameter to the\n callback function.

\n",type:"Object",optional:!0}],class:"p5.MediaElement",module:"DOM"},removeCue:{name:"removeCue",params:[{name:"id",description:"

ID of the cue, as returned by addCue

\n",type:"Number"}],class:"p5.MediaElement",module:"DOM"},clearCues:{name:"clearCues",params:[{name:"id",description:"

ID of the cue, as returned by addCue

\n",type:"Number"}],class:"p5.MediaElement",module:"DOM"}},"p5.File":{file:{name:"file",class:"p5.File",module:"DOM"},type:{name:"type",class:"p5.File",module:"DOM"},subtype:{name:"subtype",class:"p5.File",module:"DOM"},name:{name:"name",class:"p5.File",module:"DOM"},size:{name:"size",class:"p5.File",module:"DOM"},data:{name:"data",class:"p5.File",module:"DOM"}},"p5.Image":{width:{name:"width",class:"p5.Image",module:"Image"},height:{name:"height",class:"p5.Image",module:"Image"},pixels:{name:"pixels",class:"p5.Image",module:"Image"},loadPixels:{name:"loadPixels",class:"p5.Image",module:"Image"},updatePixels:{name:"updatePixels",class:"p5.Image",module:"Image",overloads:[{params:[{name:"x",description:"

x-offset of the target update area for the\n underlying canvas

\n",type:"Integer"},{name:"y",description:"

y-offset of the target update area for the\n underlying canvas

\n",type:"Integer"},{name:"w",description:"

height of the target update area for the\n underlying canvas

\n",type:"Integer"},{name:"h",description:"

height of the target update area for the\n underlying canvas

\n",type:"Integer"}]},{params:[]}]},get:{name:"get",class:"p5.Image",module:"Image",overloads:[{params:[{name:"x",description:"

x-coordinate of the pixel

\n",type:"Number"},{name:"y",description:"

y-coordinate of the pixel

\n",type:"Number"},{name:"w",description:"

width

\n",type:"Number"},{name:"h",description:"

height

\n",type:"Number"}]},{params:[]},{params:[{name:"x",description:"",type:"Number"},{name:"y",description:"",type:"Number"}]}]},set:{name:"set",params:[{name:"x",description:"

x-coordinate of the pixel

\n",type:"Number"},{name:"y",description:"

y-coordinate of the pixel

\n",type:"Number"},{name:"a",description:'

grayscale value | pixel array |\n a p5.Color | image to copy

\n',type:"Number|Number[]|Object"}],class:"p5.Image",module:"Image"},resize:{name:"resize",params:[{name:"width",description:"

the resized image width

\n",type:"Number"},{name:"height",description:"

the resized image height

\n",type:"Number"}],class:"p5.Image",module:"Image"},copy:{name:"copy",class:"p5.Image",module:"Image",overloads:[{params:[{name:"srcImage",description:"

source image

\n",type:"p5.Image|p5.Element"},{name:"sx",description:"

X coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sy",description:"

Y coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sw",description:"

source image width

\n",type:"Integer"},{name:"sh",description:"

source image height

\n",type:"Integer"},{name:"dx",description:"

X coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dy",description:"

Y coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dw",description:"

destination image width

\n",type:"Integer"},{name:"dh",description:"

destination image height

\n",type:"Integer"}]},{params:[{name:"sx",description:"",type:"Integer"},{name:"sy",description:"",type:"Integer"},{name:"sw",description:"",type:"Integer"},{name:"sh",description:"",type:"Integer"},{name:"dx",description:"",type:"Integer"},{name:"dy",description:"",type:"Integer"},{name:"dw",description:"",type:"Integer"},{name:"dh",description:"",type:"Integer"}]}]},mask:{name:"mask",params:[{name:"srcImage",description:"

source image

\n",type:"p5.Image"}],class:"p5.Image",module:"Image"},filter:{name:"filter",params:[{name:"filterType",description:"

either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, BLUR, ERODE, DILATE or BLUR.\n See Filters.js for docs on\n each available filter

\n",type:"Constant"},{name:"filterParam",description:"

an optional parameter unique\n to each filter, see above

\n",type:"Number",optional:!0}],class:"p5.Image",module:"Image"},blend:{name:"blend",class:"p5.Image",module:"Image",overloads:[{params:[{name:"srcImage",description:"

source image

\n",type:"p5.Image"},{name:"sx",description:"

X coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sy",description:"

Y coordinate of the source's upper left corner

\n",type:"Integer"},{name:"sw",description:"

source image width

\n",type:"Integer"},{name:"sh",description:"

source image height

\n",type:"Integer"},{name:"dx",description:"

X coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dy",description:"

Y coordinate of the destination's upper left corner

\n",type:"Integer"},{name:"dw",description:"

destination image width

\n",type:"Integer"},{name:"dh",description:"

destination image height

\n",type:"Integer"},{name:"blendMode",description:'

the blend mode. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.

\n

Available blend modes are: normal | multiply | screen | overlay |\n darken | lighten | color-dodge | color-burn | hard-light |\n soft-light | difference | exclusion | hue | saturation |\n color | luminosity

\n

http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/

\n',type:"Constant"}]},{params:[{name:"sx",description:"",type:"Integer"},{name:"sy",description:"",type:"Integer"},{name:"sw",description:"",type:"Integer"},{name:"sh",description:"",type:"Integer"},{name:"dx",description:"",type:"Integer"},{name:"dy",description:"",type:"Integer"},{name:"dw",description:"",type:"Integer"},{name:"dh",description:"",type:"Integer"},{name:"blendMode",description:"",type:"Constant"}]}]},save:{name:"save",params:[{name:"filename",description:"

give your file a name

\n",type:"String"},{name:"extension",description:"

'png' or 'jpg'

\n",type:"String"}],class:"p5.Image",module:"Image"},reset:{name:"reset",class:"p5.Image",module:"Image"},getCurrentFrame:{name:"getCurrentFrame",class:"p5.Image",module:"Image"},setFrame:{name:"setFrame",params:[{name:"index",description:"

the index for the frame that should be displayed

\n",type:"Number"}],class:"p5.Image",module:"Image"},numFrames:{name:"numFrames",class:"p5.Image",module:"Image"},play:{name:"play",class:"p5.Image",module:"Image"},pause:{name:"pause",class:"p5.Image",module:"Image"},delay:{name:"delay",params:[{name:"d",description:"

the amount in milliseconds to delay between switching frames

\n",type:"Number"},{name:"index",description:"

the index of the frame that should have the new delay value {optional}

\n",type:"Number",optional:!0}],class:"p5.Image",module:"Image"}},"p5.PrintWriter":{write:{name:"write",params:[{name:"data",description:"

all data to be written by the PrintWriter

\n",type:"Array"}],class:"p5.PrintWriter",module:"IO"},print:{name:"print",params:[{name:"data",description:"

all data to be printed by the PrintWriter

\n",type:"Array"}],class:"p5.PrintWriter",module:"IO"},clear:{name:"clear",class:"p5.PrintWriter",module:"IO"},close:{name:"close",class:"p5.PrintWriter",module:"IO"}},"p5.Table":{columns:{name:"columns",class:"p5.Table",module:"IO"},rows:{name:"rows",class:"p5.Table",module:"IO"},addRow:{name:"addRow",params:[{name:"row",description:"

row to be added to the table

\n",type:"p5.TableRow",optional:!0}],class:"p5.Table",module:"IO"},removeRow:{name:"removeRow",params:[{name:"id",description:"

ID number of the row to remove

\n",type:"Integer"}],class:"p5.Table",module:"IO"},getRow:{name:"getRow",params:[{name:"rowID",description:"

ID number of the row to get

\n",type:"Integer"}],class:"p5.Table",module:"IO"},getRows:{name:"getRows",class:"p5.Table",module:"IO"},findRow:{name:"findRow",params:[{name:"value",description:"

The value to match

\n",type:"String"},{name:"column",description:"

ID number or title of the\n column to search

\n",type:"Integer|String"}],class:"p5.Table",module:"IO"},findRows:{name:"findRows",params:[{name:"value",description:"

The value to match

\n",type:"String"},{name:"column",description:"

ID number or title of the\n column to search

\n",type:"Integer|String"}],class:"p5.Table",module:"IO"},matchRow:{name:"matchRow",params:[{name:"regexp",description:"

The regular expression to match

\n",type:"String|RegExp"},{name:"column",description:"

The column ID (number) or\n title (string)

\n",type:"String|Integer"}],class:"p5.Table",module:"IO"},matchRows:{name:"matchRows",params:[{name:"regexp",description:"

The regular expression to match

\n",type:"String"},{name:"column",description:"

The column ID (number) or\n title (string)

\n",type:"String|Integer",optional:!0}],class:"p5.Table",module:"IO"},getColumn:{name:"getColumn",params:[{name:"column",description:"

String or Number of the column to return

\n",type:"String|Number"}],class:"p5.Table",module:"IO"},clearRows:{name:"clearRows",class:"p5.Table",module:"IO"},addColumn:{name:"addColumn",params:[{name:"title",description:"

title of the given column

\n",type:"String",optional:!0}],class:"p5.Table",module:"IO"},getColumnCount:{name:"getColumnCount",class:"p5.Table",module:"IO"},getRowCount:{name:"getRowCount",class:"p5.Table",module:"IO"},removeTokens:{name:"removeTokens",params:[{name:"chars",description:"

String listing characters to be removed

\n",type:"String"},{name:"column",description:"

Column ID (number)\n or name (string)

\n",type:"String|Integer",optional:!0}],class:"p5.Table",module:"IO"},trim:{name:"trim",params:[{name:"column",description:"

Column ID (number)\n or name (string)

\n",type:"String|Integer",optional:!0}],class:"p5.Table",module:"IO"},removeColumn:{name:"removeColumn",params:[{name:"column",description:"

columnName (string) or ID (number)

\n",type:"String|Integer"}],class:"p5.Table",module:"IO"},set:{name:"set",params:[{name:"row",description:"

row ID

\n",type:"Integer"},{name:"column",description:"

column ID (Number)\n or title (String)

\n",type:"String|Integer"},{name:"value",description:"

value to assign

\n",type:"String|Number"}],class:"p5.Table",module:"IO"},setNum:{name:"setNum",params:[{name:"row",description:"

row ID

\n",type:"Integer"},{name:"column",description:"

column ID (Number)\n or title (String)

\n",type:"String|Integer"},{name:"value",description:"

value to assign

\n",type:"Number"}],class:"p5.Table",module:"IO"},setString:{name:"setString",params:[{name:"row",description:"

row ID

\n",type:"Integer"},{name:"column",description:"

column ID (Number)\n or title (String)

\n",type:"String|Integer"},{name:"value",description:"

value to assign

\n",type:"String"}],class:"p5.Table",module:"IO"},get:{name:"get",params:[{name:"row",description:"

row ID

\n",type:"Integer"},{name:"column",description:"

columnName (string) or\n ID (number)

\n",type:"String|Integer"}],class:"p5.Table",module:"IO"},getNum:{name:"getNum",params:[{name:"row",description:"

row ID

\n",type:"Integer"},{name:"column",description:"

columnName (string) or\n ID (number)

\n",type:"String|Integer"}],class:"p5.Table",module:"IO"},getString:{name:"getString",params:[{name:"row",description:"

row ID

\n",type:"Integer"},{name:"column",description:"

columnName (string) or\n ID (number)

\n",type:"String|Integer"}],class:"p5.Table",module:"IO"},getObject:{name:"getObject",params:[{name:"headerColumn",description:"

Name of the column which should be used to\n title each row object (optional)

\n",type:"String",optional:!0}],class:"p5.Table",module:"IO"},getArray:{name:"getArray",class:"p5.Table",module:"IO"}},"p5.TableRow":{set:{name:"set",params:[{name:"column",description:"

Column ID (Number)\n or Title (String)

\n",type:"String|Integer"},{name:"value",description:"

The value to be stored

\n",type:"String|Number"}],class:"p5.TableRow",module:"IO"},setNum:{name:"setNum",params:[{name:"column",description:"

Column ID (Number)\n or Title (String)

\n",type:"String|Integer"},{name:"value",description:"

The value to be stored\n as a Float

\n",type:"Number|String"}],class:"p5.TableRow",module:"IO"},setString:{name:"setString",params:[{name:"column",description:"

Column ID (Number)\n or Title (String)

\n",type:"String|Integer"},{name:"value",description:"

The value to be stored\n as a String

\n",type:"String|Number|Boolean|Object"}],class:"p5.TableRow",module:"IO"},get:{name:"get",params:[{name:"column",description:"

columnName (string) or\n ID (number)

\n",type:"String|Integer"}],class:"p5.TableRow",module:"IO"},getNum:{name:"getNum",params:[{name:"column",description:"

columnName (string) or\n ID (number)

\n",type:"String|Integer"}],class:"p5.TableRow",module:"IO"},getString:{name:"getString",params:[{name:"column",description:"

columnName (string) or\n ID (number)

\n",type:"String|Integer"}],class:"p5.TableRow",module:"IO"}},"p5.XML":{getParent:{name:"getParent",class:"p5.XML",module:"IO"},getName:{name:"getName",class:"p5.XML",module:"IO"},setName:{name:"setName",params:[{name:"the",description:"

new name of the node

\n",type:"String"}],class:"p5.XML",module:"IO"},hasChildren:{name:"hasChildren",class:"p5.XML",module:"IO"},listChildren:{name:"listChildren",class:"p5.XML",module:"IO"},getChildren:{name:"getChildren",params:[{name:"name",description:"

element name

\n",type:"String",optional:!0}],class:"p5.XML",module:"IO"},getChild:{name:"getChild",params:[{name:"name",description:"

element name or index

\n",type:"String|Integer"}],class:"p5.XML",module:"IO"},addChild:{name:"addChild",params:[{name:"node",description:'

a p5.XML Object which will be the child to be added

\n',type:"p5.XML"}],class:"p5.XML",module:"IO"},removeChild:{name:"removeChild",params:[{name:"name",description:"

element name or index

\n",type:"String|Integer"}],class:"p5.XML",module:"IO"},getAttributeCount:{name:"getAttributeCount",class:"p5.XML",module:"IO"},listAttributes:{name:"listAttributes",class:"p5.XML",module:"IO"},hasAttribute:{name:"hasAttribute",params:[{name:"the",description:"

attribute to be checked

\n",type:"String"}],class:"p5.XML",module:"IO"},getNum:{name:"getNum",params:[{name:"name",description:"

the non-null full name of the attribute

\n",type:"String"},{name:"defaultValue",description:"

the default value of the attribute

\n",type:"Number",optional:!0}],class:"p5.XML",module:"IO"},getString:{name:"getString",params:[{name:"name",description:"

the non-null full name of the attribute

\n",type:"String"},{name:"defaultValue",description:"

the default value of the attribute

\n",type:"Number",optional:!0}],class:"p5.XML",module:"IO"},setAttribute:{name:"setAttribute",params:[{name:"name",description:"

the full name of the attribute

\n",type:"String"},{name:"value",description:"

the value of the attribute

\n",type:"Number|String|Boolean"}],class:"p5.XML",module:"IO"},getContent:{name:"getContent",params:[{name:"defaultValue",description:"

value returned if no content is found

\n",type:"String",optional:!0}],class:"p5.XML",module:"IO"},setContent:{name:"setContent",params:[{name:"text",description:"

the new content

\n",type:"String"}],class:"p5.XML",module:"IO"},serialize:{name:"serialize",class:"p5.XML",module:"IO"}},"p5.Vector":{x:{name:"x",class:"p5.Vector",module:"Math"},y:{name:"y",class:"p5.Vector",module:"Math"},z:{name:"z",class:"p5.Vector",module:"Math"},toString:{name:"toString",class:"p5.Vector",module:"Math"},set:{name:"set",class:"p5.Vector",module:"Math",overloads:[{params:[{name:"x",description:"

the x component of the vector

\n",type:"Number",optional:!0},{name:"y",description:"

the y component of the vector

\n",type:"Number",optional:!0},{name:"z",description:"

the z component of the vector

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"value",description:"

the vector to set

\n",type:"p5.Vector|Number[]"}],chainable:1}]},copy:{name:"copy",class:"p5.Vector",module:"Math"},add:{name:"add",class:"p5.Vector",module:"Math",overloads:[{params:[{name:"x",description:"

the x component of the vector to be added

\n",type:"Number"},{name:"y",description:"

the y component of the vector to be added

\n",type:"Number",optional:!0},{name:"z",description:"

the z component of the vector to be added

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"value",description:"

the vector to add

\n",type:"p5.Vector|Number[]"}],chainable:1},{params:[{name:"v1",description:'

a p5.Vector to add

\n',type:"p5.Vector"},{name:"v2",description:'

a p5.Vector to add

\n',type:"p5.Vector"},{name:"target",description:"

the vector to receive the result (Optional)

\n",type:"p5.Vector",optional:!0}],static:1}]},rem:{name:"rem",class:"p5.Vector",module:"Math",overloads:[{params:[{name:"x",description:"

the x component of divisor vector

\n",type:"Number"},{name:"y",description:"

the y component of divisor vector

\n",type:"Number"},{name:"z",description:"

the z component of divisor vector

\n",type:"Number"}],chainable:1},{params:[{name:"value",description:"

divisor vector

\n",type:"p5.Vector | Number[]"}],chainable:1},{params:[{name:"v1",description:'

dividend p5.Vector

\n',type:"p5.Vector"},{name:"v2",description:'

divisor p5.Vector

\n',type:"p5.Vector"}],static:1},{params:[{name:"v1",description:"",type:"p5.Vector"},{name:"v2",description:"",type:"p5.Vector"}],static:1}]},sub:{name:"sub",class:"p5.Vector",module:"Math",overloads:[{params:[{name:"x",description:"

the x component of the vector to subtract

\n",type:"Number"},{name:"y",description:"

the y component of the vector to subtract

\n",type:"Number",optional:!0},{name:"z",description:"

the z component of the vector to subtract

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"value",description:"

the vector to subtract

\n",type:"p5.Vector|Number[]"}],chainable:1},{params:[{name:"v1",description:'

a p5.Vector to subtract from

\n',type:"p5.Vector"},{name:"v2",description:'

a p5.Vector to subtract

\n',type:"p5.Vector"},{name:"target",description:"

the vector to receive the result (Optional)

\n",type:"p5.Vector",optional:!0}],static:1}]},mult:{name:"mult",class:"p5.Vector",module:"Math",overloads:[{params:[{name:"n",description:"

The number to multiply with the vector

\n",type:"Number"}],chainable:1},{params:[{name:"x",description:"

The number to multiply with the x component of the vector

\n",type:"Number"},{name:"y",description:"

The number to multiply with the y component of the vector

\n",type:"Number"},{name:"z",description:"

The number to multiply with the z component of the vector

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"arr",description:"

The array to multiply with the components of the vector

\n",type:"Number[]"}],chainable:1},{params:[{name:"v",description:"

The vector to multiply with the components of the original vector

\n",type:"p5.Vector"}],chainable:1},{params:[{name:"x",description:"",type:"Number"},{name:"y",description:"",type:"Number"},{name:"z",description:"",type:"Number",optional:!0}],static:1},{params:[{name:"v",description:"",type:"p5.Vector"},{name:"n",description:"",type:"Number"},{name:"target",description:"

the vector to receive the result (Optional)

\n",type:"p5.Vector",optional:!0}],static:1},{params:[{name:"v0",description:"",type:"p5.Vector"},{name:"v1",description:"",type:"p5.Vector"},{name:"target",description:"",type:"p5.Vector",optional:!0}],static:1},{params:[{name:"v0",description:"",type:"p5.Vector"},{name:"arr",description:"",type:"Number[]"},{name:"target",description:"",type:"p5.Vector",optional:!0}],static:1}]},div:{name:"div",class:"p5.Vector",module:"Math",overloads:[{params:[{name:"n",description:"

The number to divide the vector by

\n",type:"Number"}],chainable:1},{params:[{name:"x",description:"

The number to divide with the x component of the vector

\n",type:"Number"},{name:"y",description:"

The number to divide with the y component of the vector

\n",type:"Number"},{name:"z",description:"

The number to divide with the z component of the vector

\n",type:"Number",optional:!0}],chainable:1},{params:[{name:"arr",description:"

The array to divide the components of the vector by

\n",type:"Number[]"}],chainable:1},{params:[{name:"v",description:"

The vector to divide the components of the original vector by

\n",type:"p5.Vector"}],chainable:1},{params:[{name:"x",description:"",type:"Number"},{name:"y",description:"",type:"Number"},{name:"z",description:"",type:"Number",optional:!0}],static:1},{params:[{name:"v",description:"",type:"p5.Vector"},{name:"n",description:"",type:"Number"},{name:"target",description:"

the vector to receive the result (Optional)

\n",type:"p5.Vector",optional:!0}],static:1},{params:[{name:"v0",description:"",type:"p5.Vector"},{name:"v1",description:"",type:"p5.Vector"},{name:"target",description:"",type:"p5.Vector",optional:!0}],static:1},{params:[{name:"v0",description:"",type:"p5.Vector"},{name:"arr",description:"",type:"Number[]"},{name:"target",description:"",type:"p5.Vector",optional:!0}],static:1}]},mag:{name:"mag",class:"p5.Vector",module:"Math",overloads:[{params:[]},{params:[{name:"vecT",description:"

the vector to return the magnitude of

\n",type:"p5.Vector"}],static:1}]},magSq:{name:"magSq",class:"p5.Vector",module:"Math"},dot:{name:"dot",class:"p5.Vector",module:"Math",overloads:[{params:[{name:"x",description:"

x component of the vector

\n",type:"Number"},{name:"y",description:"

y component of the vector

\n",type:"Number",optional:!0},{name:"z",description:"

z component of the vector

\n",type:"Number",optional:!0}]},{params:[{name:"value",description:'

value component of the vector or a p5.Vector

\n',type:"p5.Vector"}]},{params:[{name:"v1",description:'

the first p5.Vector

\n',type:"p5.Vector"},{name:"v2",description:'

the second p5.Vector

\n',type:"p5.Vector"}],static:1}]},cross:{name:"cross",class:"p5.Vector",module:"Math",overloads:[{params:[{name:"v",description:'

p5.Vector to be crossed

\n',type:"p5.Vector"}]},{params:[{name:"v1",description:'

the first p5.Vector

\n',type:"p5.Vector"},{name:"v2",description:'

the second p5.Vector

\n',type:"p5.Vector"}],static:1}]},dist:{name:"dist",class:"p5.Vector",module:"Math",overloads:[{params:[{name:"v",description:'

the x, y, and z coordinates of a p5.Vector

\n',type:"p5.Vector"}]},{params:[{name:"v1",description:'

the first p5.Vector

\n',type:"p5.Vector"},{name:"v2",description:'

the second p5.Vector

\n',type:"p5.Vector"}],static:1}]},normalize:{name:"normalize",class:"p5.Vector",module:"Math"},limit:{name:"limit",params:[{name:"max",description:"

the maximum magnitude for the vector

\n",type:"Number"}],class:"p5.Vector",module:"Math"},setMag:{name:"setMag",params:[{name:"len",description:"

the new length for this vector

\n",type:"Number"}],class:"p5.Vector",module:"Math"},heading:{name:"heading",class:"p5.Vector",module:"Math"},rotate:{name:"rotate",params:[{name:"angle",description:"

the angle of rotation

\n",type:"Number"}],class:"p5.Vector",module:"Math"},angleBetween:{name:"angleBetween",params:[{name:"value",description:'

the x, y, and z components of a p5.Vector

\n',type:"p5.Vector"}],class:"p5.Vector",module:"Math"},lerp:{name:"lerp",class:"p5.Vector",module:"Math",overloads:[{params:[{name:"x",description:"

the x component

\n",type:"Number"},{name:"y",description:"

the y component

\n",type:"Number"},{name:"z",description:"

the z component

\n",type:"Number"},{name:"amt",description:"

the amount of interpolation; some value between 0.0\n (old vector) and 1.0 (new vector). 0.9 is very near\n the new vector. 0.5 is halfway in between.

\n",type:"Number"}],chainable:1},{params:[{name:"v",description:'

the p5.Vector to lerp to

\n',type:"p5.Vector"},{name:"amt",description:"",type:"Number"}],chainable:1},{params:[{name:"v1",description:"",type:"p5.Vector"},{name:"v2",description:"",type:"p5.Vector"},{name:"amt",description:"",type:"Number"},{name:"target",description:"

the vector to receive the result (Optional)

\n",type:"p5.Vector",optional:!0}],static:1}]},reflect:{name:"reflect",params:[{name:"surfaceNormal",description:'

the p5.Vector to reflect about, will be normalized by this method

\n',type:"p5.Vector"}],class:"p5.Vector",module:"Math"},array:{name:"array",class:"p5.Vector",module:"Math"},equals:{name:"equals",class:"p5.Vector",module:"Math",overloads:[{params:[{name:"x",description:"

the x component of the vector

\n",type:"Number",optional:!0},{name:"y",description:"

the y component of the vector

\n",type:"Number",optional:!0},{name:"z",description:"

the z component of the vector

\n",type:"Number",optional:!0}]},{params:[{name:"value",description:"

the vector to compare

\n",type:"p5.Vector|Array"}]}]},fromAngle:{name:"fromAngle",params:[{name:"angle",description:'

the desired angle, in radians (unaffected by angleMode)

\n',type:"Number"},{name:"length",description:"

the length of the new vector (defaults to 1)

\n",type:"Number",optional:!0}],class:"p5.Vector",module:"Math"},fromAngles:{name:"fromAngles",params:[{name:"theta",description:"

the polar angle, in radians (zero is up)

\n",type:"Number"},{name:"phi",description:"

the azimuthal angle, in radians\n (zero is out of the screen)

\n",type:"Number"},{name:"length",description:"

the length of the new vector (defaults to 1)

\n",type:"Number",optional:!0}],class:"p5.Vector",module:"Math"},random2D:{name:"random2D",class:"p5.Vector",module:"Math"},random3D:{name:"random3D",class:"p5.Vector",module:"Math"}},"p5.Font":{font:{name:"font",class:"p5.Font",module:"Typography"},textBounds:{name:"textBounds",params:[{name:"line",description:"

a line of text

\n",type:"String"},{name:"x",description:"

x-position

\n",type:"Number"},{name:"y",description:"

y-position

\n",type:"Number"},{name:"fontSize",description:"

font size to use (optional) Default is 12.

\n",type:"Number",optional:!0},{name:"options",description:"

opentype options (optional)\n opentype fonts contains alignment and baseline options.\n Default is 'LEFT' and 'alphabetic'

\n",type:"Object",optional:!0}],class:"p5.Font",module:"Typography"},textToPoints:{name:"textToPoints",params:[{name:"txt",description:"

a line of text

\n",type:"String"},{name:"x",description:"

x-position

\n",type:"Number"},{name:"y",description:"

y-position

\n",type:"Number"},{name:"fontSize",description:"

font size to use (optional)

\n",type:"Number"},{name:"options",description:"

an (optional) object that can contain:

\n


sampleFactor - the ratio of path-length to number of samples\n(default=.1); higher values yield more points and are therefore\nmore precise

\n


simplifyThreshold - if set to a non-zero value, collinear points will be\nbe removed from the polygon; the value represents the threshold angle to use\nwhen determining whether two edges are collinear

\n",type:"Object",optional:!0}],class:"p5.Font",module:"Typography"}},"p5.Camera":{perspective:{name:"perspective",class:"p5.Camera",module:"Lights, Camera"},ortho:{name:"ortho",class:"p5.Camera",module:"Lights, Camera"},frustum:{name:"frustum",class:"p5.Camera",module:"Lights, Camera"},pan:{name:"pan",params:[{name:"angle",description:'

amount to rotate camera in current\nangleMode units.\nGreater than 0 values rotate counterclockwise (to the left).

\n',type:"Number"}],class:"p5.Camera",module:"Lights, Camera"},tilt:{name:"tilt",params:[{name:"angle",description:'

amount to rotate camera in current\nangleMode units.\nGreater than 0 values rotate counterclockwise (to the left).

\n',type:"Number"}],class:"p5.Camera",module:"Lights, Camera"},lookAt:{name:"lookAt",params:[{name:"x",description:"

x position of a point in world space

\n",type:"Number"},{name:"y",description:"

y position of a point in world space

\n",type:"Number"},{name:"z",description:"

z position of a point in world space

\n",type:"Number"}],class:"p5.Camera",module:"Lights, Camera"},camera:{name:"camera",class:"p5.Camera",module:"Lights, Camera"},move:{name:"move",params:[{name:"x",description:"

amount to move along camera's left-right axis

\n",type:"Number"},{name:"y",description:"

amount to move along camera's up-down axis

\n",type:"Number"},{name:"z",description:"

amount to move along camera's forward-backward axis

\n",type:"Number"}],class:"p5.Camera",module:"Lights, Camera"},setPosition:{name:"setPosition",params:[{name:"x",description:"

x position of a point in world space

\n",type:"Number"},{name:"y",description:"

y position of a point in world space

\n",type:"Number"},{name:"z",description:"

z position of a point in world space

\n",type:"Number"}],class:"p5.Camera",module:"Lights, Camera"}},"p5.Geometry":{computeFaces:{name:"computeFaces",class:"p5.Geometry",module:"Lights, Camera"},computeNormals:{name:"computeNormals",class:"p5.Geometry",module:"Lights, Camera"},averageNormals:{name:"averageNormals",class:"p5.Geometry",module:"Lights, Camera"},averagePoleNormals:{name:"averagePoleNormals",class:"p5.Geometry",module:"Lights, Camera"},normalize:{name:"normalize",class:"p5.Geometry",module:"Lights, Camera"}},"p5.Shader":{setUniform:{name:"setUniform",params:[{name:"uniformName",description:"

the name of the uniform in the\nshader program

\n",type:"String"},{name:"data",description:"

the data to be associated\nwith that uniform; type varies (could be a single numerical value, array,\nmatrix, or texture / sampler reference)

\n",type:"Object|Number|Boolean|Number[]"}],class:"p5.Shader",module:"Lights, Camera"}},"p5.sound":{getMasterVolume:{name:"getMasterVolume",class:"p5.sound",module:"p5.sound"},masterVolume:{name:"masterVolume",params:[{name:"volume",description:"

Volume (amplitude) between 0.0\n and 1.0 or modulating signal/oscillator

\n",type:"Number|Object"},{name:"rampTime",description:"

Fade for t seconds

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

Schedule this event to happen at\n t seconds in the future

\n",type:"Number",optional:!0}],class:"p5.sound",module:"p5.sound"},soundOut:{name:"soundOut",class:"p5.sound",module:"p5.sound"}},"p5.Effect":{amp:{name:"amp",params:[{name:"vol",description:"

amplitude between 0 and 1.0

\n",type:"Number",optional:!0},{name:"rampTime",description:"

create a fade that lasts until rampTime

\n",type:"Number",optional:!0},{name:"tFromNow",description:"

schedule this event to happen in tFromNow seconds

\n",type:"Number",optional:!0}],class:"p5.Effect",module:"p5.sound"},chain:{name:"chain",params:[{name:"arguments",description:"

Chain together multiple sound objects

\n",type:"Object",optional:!0}],class:"p5.Effect",module:"p5.sound"},drywet:{name:"drywet",params:[{name:"fade",description:"

The desired drywet value (0 - 1.0)

\n",type:"Number",optional:!0}],class:"p5.Effect",module:"p5.sound"},connect:{name:"connect",params:[{name:"unit",description:"",type:"Object"}],class:"p5.Effect",module:"p5.sound"},disconnect:{name:"disconnect",class:"p5.Effect",module:"p5.sound"}},"p5.Filter":{biquadFilter:{name:"biquadFilter",class:"p5.Filter",module:"p5.sound"},process:{name:"process",params:[{name:"Signal",description:"

An object that outputs audio

\n",type:"Object"},{name:"freq",description:"

Frequency in Hz, from 10 to 22050

\n",type:"Number",optional:!0},{name:"res",description:"

Resonance/Width of the filter frequency\n from 0.001 to 1000

\n",type:"Number",optional:!0}],class:"p5.Filter",module:"p5.sound"},set:{name:"set",params:[{name:"freq",description:"

Frequency in Hz, from 10 to 22050

\n",type:"Number",optional:!0},{name:"res",description:"

Resonance (Q) from 0.001 to 1000

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],class:"p5.Filter",module:"p5.sound"},freq:{name:"freq",params:[{name:"freq",description:"

Filter Frequency

\n",type:"Number"},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],class:"p5.Filter",module:"p5.sound"},res:{name:"res",params:[{name:"res",description:"

Resonance/Width of filter freq\n from 0.001 to 1000

\n",type:"Number"},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],class:"p5.Filter",module:"p5.sound"},gain:{name:"gain",params:[{name:"gain",description:"",type:"Number"}],class:"p5.Filter",module:"p5.sound"},toggle:{name:"toggle",class:"p5.Filter",module:"p5.sound"},setType:{name:"setType",params:[{name:"t",description:"",type:"String"}],class:"p5.Filter",module:"p5.sound"}},"p5.Oscillator":{start:{name:"start",params:[{name:"time",description:"

startTime in seconds from now.

\n",type:"Number",optional:!0},{name:"frequency",description:"

frequency in Hz.

\n",type:"Number",optional:!0}],class:"p5.Oscillator",module:"p5.sound"},stop:{name:"stop",params:[{name:"secondsFromNow",description:"

Time, in seconds from now.

\n",type:"Number"}],class:"p5.Oscillator",module:"p5.sound"},amp:{name:"amp",params:[{name:"vol",description:"

between 0 and 1.0\n or a modulating signal/oscillator

\n",type:"Number|Object"},{name:"rampTime",description:"

create a fade that lasts rampTime

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],class:"p5.Oscillator",module:"p5.sound"},freq:{name:"freq",params:[{name:"Frequency",description:"

Frequency in Hz\n or modulating signal/oscillator

\n",type:"Number|Object"},{name:"rampTime",description:"

Ramp time (in seconds)

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

Schedule this event to happen\n at x seconds from now

\n",type:"Number",optional:!0}],class:"p5.Oscillator",module:"p5.sound"},setType:{name:"setType",params:[{name:"type",description:"

'sine', 'triangle', 'sawtooth' or 'square'.

\n",type:"String"}],class:"p5.Oscillator",module:"p5.sound"},connect:{name:"connect",params:[{name:"unit",description:"

A p5.sound or Web Audio object

\n",type:"Object"}],class:"p5.Oscillator",module:"p5.sound"},disconnect:{name:"disconnect",class:"p5.Oscillator",module:"p5.sound"},pan:{name:"pan",params:[{name:"panning",description:"

Number between -1 and 1

\n",type:"Number"},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number"}],class:"p5.Oscillator",module:"p5.sound"},phase:{name:"phase",params:[{name:"phase",description:"

float between 0.0 and 1.0

\n",type:"Number"}],class:"p5.Oscillator",module:"p5.sound"},add:{name:"add",params:[{name:"number",description:"

Constant number to add

\n",type:"Number"}],class:"p5.Oscillator",module:"p5.sound"},mult:{name:"mult",params:[{name:"number",description:"

Constant number to multiply

\n",type:"Number"}],class:"p5.Oscillator",module:"p5.sound"},scale:{name:"scale",params:[{name:"inMin",description:"

input range minumum

\n",type:"Number"},{name:"inMax",description:"

input range maximum

\n",type:"Number"},{name:"outMin",description:"

input range minumum

\n",type:"Number"},{name:"outMax",description:"

input range maximum

\n",type:"Number"}],class:"p5.Oscillator",module:"p5.sound"}},"p5.MonoSynth":{play:{name:"play",params:[{name:"note",description:'

the note you want to play, specified as a\n frequency in Hertz (Number) or as a midi\n value in Note/Octave format ("C4", "Eb3"...etc")\n See \n Tone. Defaults to 440 hz.

\n',type:"String | Number"},{name:"velocity",description:"

velocity of the note to play (ranging from 0 to 1)

\n",type:"Number",optional:!0},{name:"secondsFromNow",description:"

time from now (in seconds) at which to play

\n",type:"Number",optional:!0},{name:"sustainTime",description:"

time to sustain before releasing the envelope. Defaults to 0.15 seconds.

\n",type:"Number",optional:!0}],class:"p5.MonoSynth",module:"p5.sound"},triggerAttack:{params:[{name:"note",description:'

the note you want to play, specified as a\n frequency in Hertz (Number) or as a midi\n value in Note/Octave format ("C4", "Eb3"...etc")\n See \n Tone. Defaults to 440 hz

\n',type:"String | Number"},{name:"velocity",description:"

velocity of the note to play (ranging from 0 to 1)

\n",type:"Number",optional:!0},{name:"secondsFromNow",description:"

time from now (in seconds) at which to play

\n",type:"Number",optional:!0}],name:"triggerAttack",class:"p5.MonoSynth",module:"p5.sound"},triggerRelease:{params:[{name:"secondsFromNow",description:"

time to trigger the release

\n",type:"Number"}],name:"triggerRelease",class:"p5.MonoSynth",module:"p5.sound"},setADSR:{name:"setADSR",params:[{name:"attackTime",description:"

Time (in seconds before envelope\n reaches Attack Level

\n",type:"Number"},{name:"decayTime",description:"

Time (in seconds) before envelope\n reaches Decay/Sustain Level

\n",type:"Number",optional:!0},{name:"susRatio",description:"

Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange),\n then decayLevel would increase proportionally, to become 0.5.

\n",type:"Number",optional:!0},{name:"releaseTime",description:"

Time in seconds from now (defaults to 0)

\n",type:"Number",optional:!0}],class:"p5.MonoSynth",module:"p5.sound"},attack:{name:"attack",class:"p5.MonoSynth",module:"p5.sound"},decay:{name:"decay",class:"p5.MonoSynth",module:"p5.sound"},sustain:{name:"sustain",class:"p5.MonoSynth",module:"p5.sound"},release:{name:"release",class:"p5.MonoSynth",module:"p5.sound"},amp:{name:"amp",params:[{name:"vol",description:"

desired volume

\n",type:"Number"},{name:"rampTime",description:"

Time to reach new volume

\n",type:"Number",optional:!0}],class:"p5.MonoSynth",module:"p5.sound"},connect:{name:"connect",params:[{name:"unit",description:"

A p5.sound or Web Audio object

\n",type:"Object"}],class:"p5.MonoSynth",module:"p5.sound"},disconnect:{name:"disconnect",class:"p5.MonoSynth",module:"p5.sound"},dispose:{name:"dispose",class:"p5.MonoSynth",module:"p5.sound"}},"p5.AudioVoice":{connect:{name:"connect",params:[{name:"unit",description:"",type:"Object"}],class:"p5.AudioVoice",module:"p5.sound"},disconnect:{name:"disconnect",class:"p5.AudioVoice",module:"p5.sound"}},"p5.PolySynth":{notes:{name:"notes",class:"p5.PolySynth",module:"p5.sound"},polyvalue:{name:"polyvalue",class:"p5.PolySynth",module:"p5.sound"},AudioVoice:{name:"AudioVoice",class:"p5.PolySynth",module:"p5.sound"},play:{name:"play",params:[{name:"note",description:"

midi note to play (ranging from 0 to 127 - 60 being a middle C)

\n",type:"Number",optional:!0},{name:"velocity",description:"

velocity of the note to play (ranging from 0 to 1)

\n",type:"Number",optional:!0},{name:"secondsFromNow",description:"

time from now (in seconds) at which to play

\n",type:"Number",optional:!0},{name:"sustainTime",description:"

time to sustain before releasing the envelope

\n",type:"Number",optional:!0}],class:"p5.PolySynth",module:"p5.sound"},noteADSR:{name:"noteADSR",params:[{name:"note",description:"

Midi note on which ADSR should be set.

\n",type:"Number",optional:!0},{name:"attackTime",description:"

Time (in seconds before envelope\n reaches Attack Level

\n",type:"Number",optional:!0},{name:"decayTime",description:"

Time (in seconds) before envelope\n reaches Decay/Sustain Level

\n",type:"Number",optional:!0},{name:"susRatio",description:"

Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange),\n then decayLevel would increase proportionally, to become 0.5.

\n",type:"Number",optional:!0},{name:"releaseTime",description:"

Time in seconds from now (defaults to 0)

\n",type:"Number",optional:!0}],class:"p5.PolySynth",module:"p5.sound"},setADSR:{name:"setADSR",params:[{name:"attackTime",description:"

Time (in seconds before envelope\n reaches Attack Level

\n",type:"Number",optional:!0},{name:"decayTime",description:"

Time (in seconds) before envelope\n reaches Decay/Sustain Level

\n",type:"Number",optional:!0},{name:"susRatio",description:"

Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange),\n then decayLevel would increase proportionally, to become 0.5.

\n",type:"Number",optional:!0},{name:"releaseTime",description:"

Time in seconds from now (defaults to 0)

\n",type:"Number",optional:!0}],class:"p5.PolySynth",module:"p5.sound"},noteAttack:{name:"noteAttack",params:[{name:"note",description:"

midi note on which attack should be triggered.

\n",type:"Number",optional:!0},{name:"velocity",description:"

velocity of the note to play (ranging from 0 to 1)/

\n",type:"Number",optional:!0},{name:"secondsFromNow",description:"

time from now (in seconds)

\n",type:"Number",optional:!0}],class:"p5.PolySynth",module:"p5.sound"},noteRelease:{name:"noteRelease",params:[{name:"note",description:"

midi note on which attack should be triggered.\n If no value is provided, all notes will be released.

\n",type:"Number",optional:!0},{name:"secondsFromNow",description:"

time to trigger the release

\n",type:"Number",optional:!0}],class:"p5.PolySynth",module:"p5.sound"},connect:{name:"connect",params:[{name:"unit",description:"

A p5.sound or Web Audio object

\n",type:"Object"}],class:"p5.PolySynth",module:"p5.sound"},disconnect:{name:"disconnect",class:"p5.PolySynth",module:"p5.sound"},dispose:{name:"dispose",class:"p5.PolySynth",module:"p5.sound"}},"p5.SoundFile":{isLoaded:{name:"isLoaded",class:"p5.SoundFile",module:"p5.sound"},play:{name:"play",params:[{name:"startTime",description:"

(optional) schedule playback to start (in seconds from now).

\n",type:"Number",optional:!0},{name:"rate",description:"

(optional) playback rate

\n",type:"Number",optional:!0},{name:"amp",description:"

(optional) amplitude (volume)\n of playback

\n",type:"Number",optional:!0},{name:"cueStart",description:"

(optional) cue start time in seconds

\n",type:"Number",optional:!0},{name:"duration",description:"

(optional) duration of playback in seconds

\n",type:"Number",optional:!0}],class:"p5.SoundFile",module:"p5.sound"},playMode:{name:"playMode",params:[{name:"str",description:"

'restart' or 'sustain' or 'untilDone'

\n",type:"String"}],class:"p5.SoundFile",module:"p5.sound"},pause:{name:"pause",params:[{name:"startTime",description:"

(optional) schedule event to occur\n seconds from now

\n",type:"Number",optional:!0}],class:"p5.SoundFile",module:"p5.sound"},loop:{name:"loop",params:[{name:"startTime",description:"

(optional) schedule event to occur\n seconds from now

\n",type:"Number",optional:!0},{name:"rate",description:"

(optional) playback rate

\n",type:"Number",optional:!0},{name:"amp",description:"

(optional) playback volume

\n",type:"Number",optional:!0},{name:"cueLoopStart",description:"

(optional) startTime in seconds

\n",type:"Number",optional:!0},{name:"duration",description:"

(optional) loop duration in seconds

\n",type:"Number",optional:!0}],class:"p5.SoundFile",module:"p5.sound"},setLoop:{name:"setLoop",params:[{name:"Boolean",description:"

set looping to true or false

\n",type:"Boolean"}],class:"p5.SoundFile",module:"p5.sound"},isLooping:{name:"isLooping",class:"p5.SoundFile",module:"p5.sound"},isPlaying:{name:"isPlaying",class:"p5.SoundFile",module:"p5.sound"},isPaused:{name:"isPaused",class:"p5.SoundFile",module:"p5.sound"},stop:{name:"stop",params:[{name:"startTime",description:"

(optional) schedule event to occur\n in seconds from now

\n",type:"Number",optional:!0}],class:"p5.SoundFile",module:"p5.sound"},setVolume:{name:"setVolume",params:[{name:"volume",description:"

Volume (amplitude) between 0.0\n and 1.0 or modulating signal/oscillator

\n",type:"Number|Object"},{name:"rampTime",description:"

Fade for t seconds

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

Schedule this event to happen at\n t seconds in the future

\n",type:"Number",optional:!0}],class:"p5.SoundFile",module:"p5.sound"},pan:{name:"pan",params:[{name:"panValue",description:"

Set the stereo panner

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],class:"p5.SoundFile",module:"p5.sound"},getPan:{name:"getPan",class:"p5.SoundFile",module:"p5.sound"},rate:{name:"rate",params:[{name:"playbackRate",description:"

Set the playback rate. 1.0 is normal,\n .5 is half-speed, 2.0 is twice as fast.\n Values less than zero play backwards.

\n",type:"Number",optional:!0}],class:"p5.SoundFile",module:"p5.sound"},duration:{name:"duration",class:"p5.SoundFile",module:"p5.sound"},currentTime:{name:"currentTime",class:"p5.SoundFile",module:"p5.sound"},jump:{name:"jump",params:[{name:"cueTime",description:"

cueTime of the soundFile in seconds.

\n",type:"Number"},{name:"duration",description:"

duration in seconds.

\n",type:"Number"}],class:"p5.SoundFile",module:"p5.sound"},channels:{name:"channels",class:"p5.SoundFile",module:"p5.sound"},sampleRate:{name:"sampleRate",class:"p5.SoundFile",module:"p5.sound"},frames:{name:"frames",class:"p5.SoundFile",module:"p5.sound"},getPeaks:{name:"getPeaks",params:[{name:"length",description:"

length is the size of the returned array.\n Larger length results in more precision.\n Defaults to 5*width of the browser window.

\n",type:"Number",optional:!0}],class:"p5.SoundFile",module:"p5.sound"},reverseBuffer:{name:"reverseBuffer",class:"p5.SoundFile",module:"p5.sound"},onended:{name:"onended",params:[{name:"callback",description:"

function to call when the\n soundfile has ended.

\n",type:"Function"}],class:"p5.SoundFile",module:"p5.sound"},connect:{name:"connect",params:[{name:"object",description:"

Audio object that accepts an input

\n",type:"Object",optional:!0}],class:"p5.SoundFile",module:"p5.sound"},disconnect:{name:"disconnect",class:"p5.SoundFile",module:"p5.sound"},setPath:{name:"setPath",params:[{name:"path",description:"

path to audio file

\n",type:"String"},{name:"callback",description:"

Callback

\n",type:"Function"}],class:"p5.SoundFile",module:"p5.sound"},setBuffer:{name:"setBuffer",params:[{name:"buf",description:"

Array of Float32 Array(s). 2 Float32 Arrays\n will create a stereo source. 1 will create\n a mono source.

\n",type:"Array"}],class:"p5.SoundFile",module:"p5.sound"},processPeaks:{name:"processPeaks",params:[{name:"callback",description:"

a function to call once this data is returned

\n",type:"Function"},{name:"initThreshold",description:"

initial threshold defaults to 0.9

\n",type:"Number",optional:!0},{name:"minThreshold",description:"

minimum threshold defaults to 0.22

\n",type:"Number",optional:!0},{name:"minPeaks",description:"

minimum number of peaks defaults to 200

\n",type:"Number",optional:!0}],class:"p5.SoundFile",module:"p5.sound"},addCue:{name:"addCue",params:[{name:"time",description:"

Time in seconds, relative to this media\n element's playback. For example, to trigger\n an event every time playback reaches two\n seconds, pass in the number 2. This will be\n passed as the first parameter to\n the callback function.

\n",type:"Number"},{name:"callback",description:"

Name of a function that will be\n called at the given time. The callback will\n receive time and (optionally) param as its\n two parameters.

\n",type:"Function"},{name:"value",description:"

An object to be passed as the\n second parameter to the\n callback function.

\n",type:"Object",optional:!0}],class:"p5.SoundFile",module:"p5.sound"},removeCue:{name:"removeCue",params:[{name:"id",description:"

ID of the cue, as returned by addCue

\n",type:"Number"}],class:"p5.SoundFile",module:"p5.sound"},clearCues:{name:"clearCues",class:"p5.SoundFile",module:"p5.sound"},save:{name:"save",params:[{name:"fileName",description:"

name of the resulting .wav file.

\n",type:"String",optional:!0}],class:"p5.SoundFile",module:"p5.sound"},getBlob:{name:"getBlob",class:"p5.SoundFile",module:"p5.sound"}},"p5.Amplitude":{setInput:{name:"setInput",params:[{name:"snd",description:"

set the sound source\n (optional, defaults to\n master output)

\n",type:"SoundObject|undefined",optional:!0},{name:"smoothing",description:"

a range between 0.0 and 1.0\n to smooth amplitude readings

\n",type:"Number|undefined",optional:!0}],class:"p5.Amplitude",module:"p5.sound"},getLevel:{name:"getLevel",params:[{name:"channel",description:"

Optionally return only channel 0 (left) or 1 (right)

\n",type:"Number",optional:!0}],class:"p5.Amplitude",module:"p5.sound"},toggleNormalize:{name:"toggleNormalize",params:[{name:"boolean",description:"

set normalize to true (1) or false (0)

\n",type:"Boolean",optional:!0}],class:"p5.Amplitude",module:"p5.sound"},smooth:{name:"smooth",params:[{name:"set",description:"

smoothing from 0.0 <= 1

\n",type:"Number"}],class:"p5.Amplitude",module:"p5.sound"}},"p5.FFT":{setInput:{name:"setInput",params:[{name:"source",description:"

p5.sound object (or web audio API source node)

\n",type:"Object",optional:!0}],class:"p5.FFT",module:"p5.sound"},waveform:{name:"waveform",params:[{name:"bins",description:"

Must be a power of two between\n 16 and 1024. Defaults to 1024.

\n",type:"Number",optional:!0},{name:"precision",description:"

If any value is provided, will return results\n in a Float32 Array which is more precise\n than a regular array.

\n",type:"String",optional:!0}],class:"p5.FFT",module:"p5.sound"},analyze:{name:"analyze",params:[{name:"bins",description:"

Must be a power of two between\n 16 and 1024. Defaults to 1024.

\n",type:"Number",optional:!0},{name:"scale",description:'

If "dB," returns decibel\n float measurements between\n -140 and 0 (max).\n Otherwise returns integers from 0-255.

\n',type:"Number",optional:!0}],class:"p5.FFT",module:"p5.sound"},getEnergy:{name:"getEnergy",params:[{name:"frequency1",description:'

Will return a value representing\n energy at this frequency. Alternately,\n the strings "bass", "lowMid" "mid",\n "highMid", and "treble" will return\n predefined frequency ranges.

\n',type:"Number|String"},{name:"frequency2",description:"

If a second frequency is given,\n will return average amount of\n energy that exists between the\n two frequencies.

\n",type:"Number",optional:!0}],class:"p5.FFT",module:"p5.sound"},getCentroid:{name:"getCentroid",class:"p5.FFT",module:"p5.sound"},smooth:{name:"smooth",params:[{name:"smoothing",description:"

0.0 < smoothing < 1.0.\n Defaults to 0.8.

\n",type:"Number"}],class:"p5.FFT",module:"p5.sound"},linAverages:{name:"linAverages",params:[{name:"N",description:"

Number of returned frequency groups

\n",type:"Number"}],class:"p5.FFT",module:"p5.sound"},logAverages:{name:"logAverages",params:[{name:"octaveBands",description:"

Array of Octave Bands objects for grouping

\n",type:"Array"}],class:"p5.FFT",module:"p5.sound"},getOctaveBands:{name:"getOctaveBands",params:[{name:"N",description:"

Specifies the 1/N type of generated octave bands

\n",type:"Number"},{name:"fCtr0",description:"

Minimum central frequency for the lowest band

\n",type:"Number"}],class:"p5.FFT",module:"p5.sound"}},"p5.Signal":{fade:{name:"fade",params:[{name:"value",description:"

Value to set this signal

\n",type:"Number"},{name:"secondsFromNow",description:"

Length of fade, in seconds from now

\n",type:"Number",optional:!0}],class:"p5.Signal",module:"p5.sound"},setInput:{name:"setInput",params:[{name:"input",description:"",type:"Object"}],class:"p5.Signal",module:"p5.sound"},add:{name:"add",params:[{name:"number",description:"",type:"Number"}],class:"p5.Signal",module:"p5.sound"},mult:{name:"mult",params:[{name:"number",description:"

to multiply

\n",type:"Number"}],class:"p5.Signal",module:"p5.sound"},scale:{name:"scale",params:[{name:"number",description:"

to multiply

\n",type:"Number"},{name:"inMin",description:"

input range minumum

\n",type:"Number"},{name:"inMax",description:"

input range maximum

\n",type:"Number"},{name:"outMin",description:"

input range minumum

\n",type:"Number"},{name:"outMax",description:"

input range maximum

\n",type:"Number"}],class:"p5.Signal",module:"p5.sound"}},"p5.Envelope":{attackTime:{name:"attackTime",class:"p5.Envelope",module:"p5.sound"},attackLevel:{name:"attackLevel",class:"p5.Envelope",module:"p5.sound"},decayTime:{name:"decayTime",class:"p5.Envelope",module:"p5.sound"},decayLevel:{name:"decayLevel",class:"p5.Envelope",module:"p5.sound"},releaseTime:{name:"releaseTime",class:"p5.Envelope",module:"p5.sound"},releaseLevel:{name:"releaseLevel",class:"p5.Envelope",module:"p5.sound"},set:{name:"set",params:[{name:"attackTime",description:"

Time (in seconds) before level\n reaches attackLevel

\n",type:"Number"},{name:"attackLevel",description:"

Typically an amplitude between\n 0.0 and 1.0

\n",type:"Number"},{name:"decayTime",description:"

Time

\n",type:"Number"},{name:"decayLevel",description:"

Amplitude (In a standard ADSR envelope,\n decayLevel = sustainLevel)

\n",type:"Number"},{name:"releaseTime",description:"

Release Time (in seconds)

\n",type:"Number"},{name:"releaseLevel",description:"

Amplitude

\n",type:"Number"}],class:"p5.Envelope",module:"p5.sound"},setADSR:{name:"setADSR",params:[{name:"attackTime",description:"

Time (in seconds before envelope\n reaches Attack Level

\n",type:"Number"},{name:"decayTime",description:"

Time (in seconds) before envelope\n reaches Decay/Sustain Level

\n",type:"Number",optional:!0},{name:"susRatio",description:"

Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange),\n then decayLevel would increase proportionally, to become 0.5.

\n",type:"Number",optional:!0},{name:"releaseTime",description:"

Time in seconds from now (defaults to 0)

\n",type:"Number",optional:!0}],class:"p5.Envelope",module:"p5.sound"},setRange:{name:"setRange",params:[{name:"aLevel",description:"

attack level (defaults to 1)

\n",type:"Number"},{name:"rLevel",description:"

release level (defaults to 0)

\n",type:"Number"}],class:"p5.Envelope",module:"p5.sound"},setInput:{name:"setInput",params:[{name:"inputs",description:"

A p5.sound object or\n Web Audio Param.

\n",type:"Object",optional:!0,multiple:!0}],class:"p5.Envelope",module:"p5.sound"},setExp:{name:"setExp",params:[{name:"isExp",description:"

true is exponential, false is linear

\n",type:"Boolean"}],class:"p5.Envelope",module:"p5.sound"},play:{name:"play",params:[{name:"unit",description:"

A p5.sound object or\n Web Audio Param.

\n",type:"Object"},{name:"startTime",description:"

time from now (in seconds) at which to play

\n",type:"Number",optional:!0},{name:"sustainTime",description:"

time to sustain before releasing the envelope

\n",type:"Number",optional:!0}],class:"p5.Envelope",module:"p5.sound"},triggerAttack:{name:"triggerAttack",params:[{name:"unit",description:"

p5.sound Object or Web Audio Param

\n",type:"Object"},{name:"secondsFromNow",description:"

time from now (in seconds)

\n",type:"Number"}],class:"p5.Envelope",module:"p5.sound"},triggerRelease:{name:"triggerRelease",params:[{name:"unit",description:"

p5.sound Object or Web Audio Param

\n",type:"Object"},{name:"secondsFromNow",description:"

time to trigger the release

\n",type:"Number"}],class:"p5.Envelope",module:"p5.sound"},ramp:{name:"ramp",params:[{name:"unit",description:"

p5.sound Object or Web Audio Param

\n",type:"Object"},{name:"secondsFromNow",description:"

When to trigger the ramp

\n",type:"Number"},{name:"v",description:"

Target value

\n",type:"Number"},{name:"v2",description:"

Second target value (optional)

\n",type:"Number",optional:!0}],class:"p5.Envelope",module:"p5.sound"},add:{name:"add",params:[{name:"number",description:"

Constant number to add

\n",type:"Number"}],class:"p5.Envelope",module:"p5.sound"},mult:{name:"mult",params:[{name:"number",description:"

Constant number to multiply

\n",type:"Number"}],class:"p5.Envelope",module:"p5.sound"},scale:{name:"scale",params:[{name:"inMin",description:"

input range minumum

\n",type:"Number"},{name:"inMax",description:"

input range maximum

\n",type:"Number"},{name:"outMin",description:"

input range minumum

\n",type:"Number"},{name:"outMax",description:"

input range maximum

\n",type:"Number"}],class:"p5.Envelope",module:"p5.sound"}},"p5.Pulse":{width:{name:"width",params:[{name:"width",description:"

Width between the pulses (0 to 1.0,\n defaults to 0)

\n",type:"Number",optional:!0}],class:"p5.Pulse",module:"p5.sound"}},"p5.Noise":{setType:{name:"setType",params:[{name:"type",description:"

'white', 'pink' or 'brown'

\n",type:"String",optional:!0}],class:"p5.Noise",module:"p5.sound"}},"p5.AudioIn":{input:{name:"input",class:"p5.AudioIn",module:"p5.sound"},output:{name:"output",class:"p5.AudioIn",module:"p5.sound"},stream:{name:"stream",class:"p5.AudioIn",module:"p5.sound"},mediaStream:{name:"mediaStream",class:"p5.AudioIn",module:"p5.sound"},currentSource:{name:"currentSource",class:"p5.AudioIn",module:"p5.sound"},enabled:{name:"enabled",class:"p5.AudioIn",module:"p5.sound"},amplitude:{name:"amplitude",class:"p5.AudioIn",module:"p5.sound"},start:{name:"start",params:[{name:"successCallback",description:"

Name of a function to call on\n success.

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

Name of a function to call if\n there was an error. For example,\n some browsers do not support\n getUserMedia.

\n",type:"Function",optional:!0}],class:"p5.AudioIn",module:"p5.sound"},stop:{name:"stop",class:"p5.AudioIn",module:"p5.sound"},connect:{name:"connect",params:[{name:"unit",description:"

An object that accepts audio input,\n such as an FFT

\n",type:"Object",optional:!0}],class:"p5.AudioIn",module:"p5.sound"},disconnect:{name:"disconnect",class:"p5.AudioIn",module:"p5.sound"},getLevel:{name:"getLevel",params:[{name:"smoothing",description:"

Smoothing is 0.0 by default.\n Smooths values based on previous values.

\n",type:"Number",optional:!0}],class:"p5.AudioIn",module:"p5.sound"},amp:{name:"amp",params:[{name:"vol",description:"

between 0 and 1.0

\n",type:"Number"},{name:"time",description:"

ramp time (optional)

\n",type:"Number",optional:!0}],class:"p5.AudioIn",module:"p5.sound"},getSources:{name:"getSources",params:[{name:"successCallback",description:"

This callback function handles the sources when they\n have been enumerated. The callback function\n receives the deviceList array as its only argument

\n",type:"Function",optional:!0},{name:"errorCallback",description:"

This optional callback receives the error\n message as its argument.

\n",type:"Function",optional:!0}],class:"p5.AudioIn",module:"p5.sound"},setSource:{name:"setSource",params:[{name:"num",description:"

position of input source in the array

\n",type:"Number"}],class:"p5.AudioIn",module:"p5.sound"}},"p5.EQ":{bands:{name:"bands",class:"p5.EQ",module:"p5.sound"},process:{name:"process",params:[{name:"src",description:"

Audio source

\n",type:"Object"}],class:"p5.EQ",module:"p5.sound"}},"p5.Panner3D":{panner:{name:"panner",class:"p5.Panner3D",module:"p5.sound"},process:{name:"process",params:[{name:"src",description:"

Input source

\n",type:"Object"}],class:"p5.Panner3D",module:"p5.sound"},set:{name:"set",params:[{name:"xVal",description:"",type:"Number"},{name:"yVal",description:"",type:"Number"},{name:"zVal",description:"",type:"Number"},{name:"time",description:"",type:"Number"}],class:"p5.Panner3D",module:"p5.sound"},positionX:{name:"positionX",class:"p5.Panner3D",module:"p5.sound"},positionY:{name:"positionY",class:"p5.Panner3D",module:"p5.sound"},positionZ:{name:"positionZ",class:"p5.Panner3D",module:"p5.sound"},orient:{name:"orient",params:[{name:"xVal",description:"",type:"Number"},{name:"yVal",description:"",type:"Number"},{name:"zVal",description:"",type:"Number"},{name:"time",description:"",type:"Number"}],class:"p5.Panner3D",module:"p5.sound"},orientX:{name:"orientX",class:"p5.Panner3D",module:"p5.sound"},orientY:{name:"orientY",class:"p5.Panner3D",module:"p5.sound"},orientZ:{name:"orientZ",class:"p5.Panner3D",module:"p5.sound"},setFalloff:{name:"setFalloff",params:[{name:"maxDistance",description:"",type:"Number",optional:!0},{name:"rolloffFactor",description:"",type:"Number",optional:!0}],class:"p5.Panner3D",module:"p5.sound"},maxDist:{name:"maxDist",params:[{name:"maxDistance",description:"",type:"Number"}],class:"p5.Panner3D",module:"p5.sound"},rollof:{name:"rollof",params:[{name:"rolloffFactor",description:"",type:"Number"}],class:"p5.Panner3D",module:"p5.sound"}},"p5.Delay":{leftDelay:{name:"leftDelay",class:"p5.Delay",module:"p5.sound"},rightDelay:{name:"rightDelay",class:"p5.Delay",module:"p5.sound"},process:{name:"process",params:[{name:"Signal",description:"

An object that outputs audio

\n",type:"Object"},{name:"delayTime",description:"

Time (in seconds) of the delay/echo.\n Some browsers limit delayTime to\n 1 second.

\n",type:"Number",optional:!0},{name:"feedback",description:"

sends the delay back through itself\n in a loop that decreases in volume\n each time.

\n",type:"Number",optional:!0},{name:"lowPass",description:"

Cutoff frequency. Only frequencies\n below the lowPass will be part of the\n delay.

\n",type:"Number",optional:!0}],class:"p5.Delay",module:"p5.sound"},delayTime:{name:"delayTime",params:[{name:"delayTime",description:"

Time (in seconds) of the delay

\n",type:"Number"}],class:"p5.Delay",module:"p5.sound"},feedback:{name:"feedback",params:[{name:"feedback",description:"

0.0 to 1.0, or an object such as an\n Oscillator that can be used to\n modulate this param

\n",type:"Number|Object"}],class:"p5.Delay",module:"p5.sound"},filter:{name:"filter",params:[{name:"cutoffFreq",description:"

A lowpass filter will cut off any\n frequencies higher than the filter frequency.

\n",type:"Number|Object"},{name:"res",description:"

Resonance of the filter frequency\n cutoff, or an object (i.e. a p5.Oscillator)\n that can be used to modulate this parameter.\n High numbers (i.e. 15) will produce a resonance,\n low numbers (i.e. .2) will produce a slope.

\n",type:"Number|Object"}],class:"p5.Delay",module:"p5.sound"},setType:{name:"setType",params:[{name:"type",description:"

'pingPong' (1) or 'default' (0)

\n",type:"String|Number"}],class:"p5.Delay",module:"p5.sound"},amp:{name:"amp",params:[{name:"volume",description:"

amplitude between 0 and 1.0

\n",type:"Number"},{name:"rampTime",description:"

create a fade that lasts rampTime

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],class:"p5.Delay",module:"p5.sound"},connect:{name:"connect",params:[{name:"unit",description:"",type:"Object"}],class:"p5.Delay",module:"p5.sound"},disconnect:{name:"disconnect",class:"p5.Delay",module:"p5.sound"}},"p5.Reverb":{process:{name:"process",params:[{name:"src",description:"

p5.sound / Web Audio object with a sound\n output.

\n",type:"Object"},{name:"seconds",description:"

Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.

\n",type:"Number",optional:!0},{name:"decayRate",description:"

Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.

\n",type:"Number",optional:!0},{name:"reverse",description:"

Play the reverb backwards or forwards.

\n",type:"Boolean",optional:!0}],class:"p5.Reverb",module:"p5.sound"},set:{name:"set",params:[{name:"seconds",description:"

Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.

\n",type:"Number",optional:!0},{name:"decayRate",description:"

Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.

\n",type:"Number",optional:!0},{name:"reverse",description:"

Play the reverb backwards or forwards.

\n",type:"Boolean",optional:!0}],class:"p5.Reverb",module:"p5.sound"},amp:{name:"amp",params:[{name:"volume",description:"

amplitude between 0 and 1.0

\n",type:"Number"},{name:"rampTime",description:"

create a fade that lasts rampTime

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],class:"p5.Reverb",module:"p5.sound"},connect:{name:"connect",params:[{name:"unit",description:"",type:"Object"}],class:"p5.Reverb",module:"p5.sound"},disconnect:{name:"disconnect",class:"p5.Reverb",module:"p5.sound"}},"p5.Convolver":{convolverNode:{name:"convolverNode",class:"p5.Convolver",module:"p5.sound"},process:{name:"process",params:[{name:"src",description:"

p5.sound / Web Audio object with a sound\n output.

\n",type:"Object"}],class:"p5.Convolver",module:"p5.sound"},impulses:{name:"impulses",class:"p5.Convolver",module:"p5.sound"},addImpulse:{name:"addImpulse",params:[{name:"path",description:"

path to a sound file

\n",type:"String"},{name:"callback",description:"

function (optional)

\n",type:"Function"},{name:"errorCallback",description:"

function (optional)

\n",type:"Function"}],class:"p5.Convolver",module:"p5.sound"},resetImpulse:{name:"resetImpulse",params:[{name:"path",description:"

path to a sound file

\n",type:"String"},{name:"callback",description:"

function (optional)

\n",type:"Function"},{name:"errorCallback",description:"

function (optional)

\n",type:"Function"}],class:"p5.Convolver",module:"p5.sound"},toggleImpulse:{name:"toggleImpulse",params:[{name:"id",description:"

Identify the impulse by its original filename\n (String), or by its position in the\n .impulses Array (Number).

\n",type:"String|Number"}],class:"p5.Convolver",module:"p5.sound"}},"p5.Phrase":{sequence:{name:"sequence",class:"p5.Phrase",module:"p5.sound"}},"p5.Part":{setBPM:{name:"setBPM",params:[{name:"BPM",description:"

Beats Per Minute

\n",type:"Number"},{name:"rampTime",description:"

Seconds from now

\n",type:"Number",optional:!0}],class:"p5.Part",module:"p5.sound"},getBPM:{name:"getBPM",class:"p5.Part",module:"p5.sound"},start:{name:"start",params:[{name:"time",description:"

seconds from now

\n",type:"Number",optional:!0}],class:"p5.Part",module:"p5.sound"},loop:{name:"loop",params:[{name:"time",description:"

seconds from now

\n",type:"Number",optional:!0}],class:"p5.Part",module:"p5.sound"},noLoop:{name:"noLoop",class:"p5.Part",module:"p5.sound"},stop:{name:"stop",params:[{name:"time",description:"

seconds from now

\n",type:"Number",optional:!0}],class:"p5.Part",module:"p5.sound"},pause:{name:"pause",params:[{name:"time",description:"

seconds from now

\n",type:"Number"}],class:"p5.Part",module:"p5.sound"},addPhrase:{name:"addPhrase",params:[{name:"phrase",description:"

reference to a p5.Phrase

\n",type:"p5.Phrase"}],class:"p5.Part",module:"p5.sound"},removePhrase:{name:"removePhrase",params:[{name:"phraseName",description:"",type:"String"}],class:"p5.Part",module:"p5.sound"},getPhrase:{name:"getPhrase",params:[{name:"phraseName",description:"",type:"String"}],class:"p5.Part",module:"p5.sound"},replaceSequence:{name:"replaceSequence",params:[{name:"phraseName",description:"",type:"String"},{name:"sequence",description:"

Array of values to pass into the callback\n at each step of the phrase.

\n",type:"Array"}],class:"p5.Part",module:"p5.sound"},onStep:{name:"onStep",params:[{name:"callback",description:"

The name of the callback\n you want to fire\n on every beat/tatum.

\n",type:"Function"}],class:"p5.Part",module:"p5.sound"}},"p5.Score":{start:{name:"start",class:"p5.Score",module:"p5.sound"},stop:{name:"stop",class:"p5.Score",module:"p5.sound"},pause:{name:"pause",class:"p5.Score",module:"p5.sound"},loop:{name:"loop",class:"p5.Score",module:"p5.sound"},noLoop:{name:"noLoop",class:"p5.Score",module:"p5.sound"},setBPM:{name:"setBPM",params:[{name:"BPM",description:"

Beats Per Minute

\n",type:"Number"},{name:"rampTime",description:"

Seconds from now

\n",type:"Number"}],class:"p5.Score",module:"p5.sound"}},"p5.SoundLoop":{musicalTimeMode:{name:"musicalTimeMode",class:"p5.SoundLoop",module:"p5.sound"},maxIterations:{name:"maxIterations",class:"p5.SoundLoop",module:"p5.sound"},start:{name:"start",params:[{name:"timeFromNow",description:"

schedule a starting time

\n",type:"Number",optional:!0}],class:"p5.SoundLoop",module:"p5.sound"},stop:{name:"stop",params:[{name:"timeFromNow",description:"

schedule a stopping time

\n",type:"Number",optional:!0}],class:"p5.SoundLoop",module:"p5.sound"},pause:{name:"pause",params:[{name:"timeFromNow",description:"

schedule a pausing time

\n",type:"Number",optional:!0}],class:"p5.SoundLoop",module:"p5.sound"},syncedStart:{name:"syncedStart",params:[{name:"otherLoop",description:"

a p5.SoundLoop to sync with

\n",type:"Object"},{name:"timeFromNow",description:"

Start the loops in sync after timeFromNow seconds

\n",type:"Number",optional:!0}],class:"p5.SoundLoop",module:"p5.sound"},bpm:{name:"bpm",class:"p5.SoundLoop",module:"p5.sound"},timeSignature:{name:"timeSignature",class:"p5.SoundLoop",module:"p5.sound"},interval:{name:"interval",class:"p5.SoundLoop",module:"p5.sound"},iterations:{name:"iterations",class:"p5.SoundLoop",module:"p5.sound"}},"p5.Compressor":{compressor:{name:"compressor",class:"p5.Compressor",module:"p5.sound"},process:{name:"process",params:[{name:"src",description:"

Sound source to be connected

\n",type:"Object"},{name:"attack",description:"

The amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1

\n",type:"Number",optional:!0},{name:"knee",description:'

A decibel value representing the range above the\n threshold where the curve smoothly transitions to the "ratio" portion.\n default = 30, range 0 - 40

\n',type:"Number",optional:!0},{name:"ratio",description:"

The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20

\n",type:"Number",optional:!0},{name:"threshold",description:"

The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0

\n",type:"Number",optional:!0},{name:"release",description:"

The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1

\n",type:"Number",optional:!0}],class:"p5.Compressor",module:"p5.sound"},set:{name:"set",params:[{name:"attack",description:"

The amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1

\n",type:"Number"},{name:"knee",description:'

A decibel value representing the range above the\n threshold where the curve smoothly transitions to the "ratio" portion.\n default = 30, range 0 - 40

\n',type:"Number"},{name:"ratio",description:"

The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20

\n",type:"Number"},{name:"threshold",description:"

The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0

\n",type:"Number"},{name:"release",description:"

The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1

\n",type:"Number"}],class:"p5.Compressor",module:"p5.sound"},attack:{name:"attack",params:[{name:"attack",description:"

Attack is the amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1

\n",type:"Number",optional:!0},{name:"time",description:"

Assign time value to schedule the change in value

\n",type:"Number",optional:!0}],class:"p5.Compressor",module:"p5.sound"},knee:{name:"knee",params:[{name:"knee",description:'

A decibel value representing the range above the\n threshold where the curve smoothly transitions to the "ratio" portion.\n default = 30, range 0 - 40

\n',type:"Number",optional:!0},{name:"time",description:"

Assign time value to schedule the change in value

\n",type:"Number",optional:!0}],class:"p5.Compressor",module:"p5.sound"},ratio:{name:"ratio",params:[{name:"ratio",description:"

The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20

\n",type:"Number",optional:!0},{name:"time",description:"

Assign time value to schedule the change in value

\n",type:"Number",optional:!0}],class:"p5.Compressor",module:"p5.sound"},threshold:{name:"threshold",params:[{name:"threshold",description:"

The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0

\n",type:"Number"},{name:"time",description:"

Assign time value to schedule the change in value

\n",type:"Number",optional:!0}],class:"p5.Compressor",module:"p5.sound"},release:{name:"release",params:[{name:"release",description:"

The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1

\n",type:"Number"},{name:"time",description:"

Assign time value to schedule the change in value

\n",type:"Number",optional:!0}],class:"p5.Compressor",module:"p5.sound"},reduction:{name:"reduction",class:"p5.Compressor",module:"p5.sound"}},"p5.SoundRecorder":{setInput:{name:"setInput",params:[{name:"unit",description:"

p5.sound object or a web audio unit\n that outputs sound

\n",type:"Object",optional:!0}],class:"p5.SoundRecorder",module:"p5.sound"},record:{name:"record",params:[{name:"soundFile",description:"

p5.SoundFile

\n",type:"p5.SoundFile"},{name:"duration",description:"

Time (in seconds)

\n",type:"Number",optional:!0},{name:"callback",description:"

The name of a function that will be\n called once the recording completes

\n",type:"Function",optional:!0}],class:"p5.SoundRecorder",module:"p5.sound"},stop:{name:"stop",class:"p5.SoundRecorder",module:"p5.sound"}},"p5.PeakDetect":{isDetected:{name:"isDetected",class:"p5.PeakDetect",module:"p5.sound"},update:{name:"update",params:[{name:"fftObject",description:"

A p5.FFT object

\n",type:"p5.FFT"}],class:"p5.PeakDetect",module:"p5.sound"},onPeak:{name:"onPeak",params:[{name:"callback",description:"

Name of a function that will\n be called when a peak is\n detected.

\n",type:"Function"},{name:"val",description:"

Optional value to pass\n into the function when\n a peak is detected.

\n",type:"Object",optional:!0}],class:"p5.PeakDetect",module:"p5.sound"}},"p5.Gain":{setInput:{name:"setInput",params:[{name:"src",description:"

p5.sound / Web Audio object with a sound\n output.

\n",type:"Object"}],class:"p5.Gain",module:"p5.sound"},connect:{name:"connect",params:[{name:"unit",description:"",type:"Object"}],class:"p5.Gain",module:"p5.sound"},disconnect:{name:"disconnect",class:"p5.Gain",module:"p5.sound"},amp:{name:"amp",params:[{name:"volume",description:"

amplitude between 0 and 1.0

\n",type:"Number"},{name:"rampTime",description:"

create a fade that lasts rampTime

\n",type:"Number",optional:!0},{name:"timeFromNow",description:"

schedule this event to happen\n seconds from now

\n",type:"Number",optional:!0}],class:"p5.Gain",module:"p5.sound"}},"p5.Distortion":{WaveShaperNode:{name:"WaveShaperNode",class:"p5.Distortion",module:"p5.sound"},process:{name:"process",params:[{name:"amount",description:"

Unbounded distortion amount.\n Normal values range from 0-1.

\n",type:"Number",optional:!0,optdefault:"0.25"},{name:"oversample",description:"

'none', '2x', or '4x'.

\n",type:"String",optional:!0,optdefault:"'none'"}],class:"p5.Distortion",module:"p5.sound"},set:{name:"set",params:[{name:"amount",description:"

Unbounded distortion amount.\n Normal values range from 0-1.

\n",type:"Number",optional:!0,optdefault:"0.25"},{name:"oversample",description:"

'none', '2x', or '4x'.

\n",type:"String",optional:!0,optdefault:"'none'"}],class:"p5.Distortion",module:"p5.sound"},getAmount:{name:"getAmount",class:"p5.Distortion",module:"p5.sound"},getOversample:{name:"getOversample",class:"p5.Distortion",module:"p5.sound"}}}},{}],2:[function(e,t,r){"use strict";r.byteLength=function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},r.toByteArray=function(e){var t,r,n=c(e),a=n[0],o=n[1],i=new u(function(e,t){return 3*(e+t)/4-t}(a,o)),s=0,l=0>16&255,i[s++]=t>>8&255,i[s++]=255&t;2===o&&(t=p[e.charCodeAt(r)]<<2|p[e.charCodeAt(r+1)]>>4,i[s++]=255&t);1===o&&(t=p[e.charCodeAt(r)]<<10|p[e.charCodeAt(r+1)]<<4|p[e.charCodeAt(r+2)]>>2,i[s++]=t>>8&255,i[s++]=255&t);return i},r.fromByteArray=function(e){for(var t,r=e.length,n=r%3,a=[],o=0,i=r-n;o>2]+s[t<<4&63]+"==")):2==n&&(t=(e[r-2]<<8)+e[r-1],a.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"="));return a.join("")};for(var s=[],p=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,o=n.length;a>18&63]+s[a>>12&63]+s[a>>6&63]+s[63&a]);return o.join("")}p["-".charCodeAt(0)]=62,p["_".charCodeAt(0)]=63},{}],3:[function(e,t,r){},{}],4:[function(e,t,r){arguments[4][3][0].apply(r,arguments)},{dup:3}],5:[function(F,e,U){(function(c){"use strict";var n=F("base64-js"),o=F("ieee754"),e="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;U.Buffer=c,U.SlowBuffer=function(e){+e!=e&&(e=0);return c.alloc(+e)},U.INSPECT_MAX_BYTES=50;var r=2147483647;function i(e){if(r>>1;case"base64":return P(e).length;default:if(a)return n?-1:I(e).length;t=(""+t).toLowerCase(),a=!0}}function h(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function m(e,t,r,n,a){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):2147483647=e.length){if(a)return-1;r=e.length-1}else if(r<0){if(!a)return-1;r=0}if("string"==typeof t&&(t=c.from(t,n)),c.isBuffer(t))return 0===t.length?-1:f(e,t,r,n,a);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):f(e,[t],r,n,a);throw new TypeError("val must be string, number or Buffer")}function f(e,t,r,n,a){var o,i=1,s=e.length,l=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s/=i=2,l/=2,r/=2}function p(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(a){var u=-1;for(o=r;o>8,a=r%256,o.push(a),o.push(n);return o}(t,e.length-r),e,r,n)}function b(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function _(e,t,r){r=Math.min(e.length,r);for(var n=[],a=t;a>>10&1023|55296),u=56320|1023&u),n.push(u),a+=c}return function(e){var t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e=e||"utf8";;)switch(e){case"hex":return M(this,t,r);case"utf8":case"utf-8":return _(this,t,r);case"ascii":return S(this,t,r);case"latin1":case"binary":return w(this,t,r);case"base64":return b(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}.apply(this,arguments)},c.prototype.equals=function(e){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===c.compare(this,e)},c.prototype.inspect=function(){var e="",t=U.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),""},e&&(c.prototype[e]=c.prototype.inspect),c.prototype.compare=function(e,t,r,n,a){if(D(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),!c.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===a&&(a=this.length),t<0||r>e.length||n<0||a>this.length)throw new RangeError("out of range index");if(a<=n&&r<=t)return 0;if(a<=n)return-1;if(r<=t)return 1;if(this===e)return 0;for(var o=(a>>>=0)-(n>>>=0),i=(r>>>=0)-(t>>>=0),s=Math.min(o,i),l=this.slice(n,a),p=e.slice(t,r),u=0;u>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var a=this.length-t;if((void 0===r||athis.length)throw new RangeError("Attempt to write outside buffer bounds");n=n||"utf8";for(var o,i,s,l,p,u,c=!1;;)switch(n){case"hex":return y(this,e,t,r);case"utf8":case"utf-8":return p=t,u=r,R(I(e,(l=this).length-p),l,p,u);case"ascii":return g(this,e,t,r);case"latin1":case"binary":return g(this,e,t,r);case"base64":return o=this,i=t,s=r,R(P(e),o,i,s);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return v(this,e,t,r);default:if(c)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),c=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var x=4096;function S(e,t,r){var n="";r=Math.min(e.length,r);for(var a=t;ae.length)throw new RangeError("Index out of range")}function N(e,t,r,n){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function O(e,t,r,n,a){return t=+t,r>>>=0,a||N(e,0,r,4),o.write(e,t,r,n,23,4),r+4}function L(e,t,r,n,a){return t=+t,r>>>=0,a||N(e,0,r,8),o.write(e,t,r,n,52,8),r+8}c.prototype.slice=function(e,t){var r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):r>>=0,t>>>=0,r||T(e,t,this.length);for(var n=this[e],a=1,o=0;++o>>=0,t>>>=0,r||T(e,t,this.length);for(var n=this[e+--t],a=1;0>>=0,t||T(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return e>>>=0,t||T(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return e>>>=0,t||T(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return e>>>=0,t||T(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return e>>>=0,t||T(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||T(e,t,this.length);for(var n=this[e],a=1,o=0;++o>>=0,t>>>=0,r||T(e,t,this.length);for(var n=t,a=1,o=this[e+--n];0>>=0,t||T(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){e>>>=0,t||T(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt16BE=function(e,t){e>>>=0,t||T(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt32LE=function(e,t){return e>>>=0,t||T(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return e>>>=0,t||T(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return e>>>=0,t||T(e,4,this.length),o.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return e>>>=0,t||T(e,4,this.length),o.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return e>>>=0,t||T(e,8,this.length),o.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return e>>>=0,t||T(e,8,this.length),o.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||C(this,e,t,r,Math.pow(2,8*r)-1,0);var a=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,n||C(this,e,t,r,Math.pow(2,8*r)-1,0);var a=r-1,o=1;for(this[t+a]=255&e;0<=--a&&(o*=256);)this[t+a]=e/o&255;return t+r},c.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,255,0),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var a=Math.pow(2,8*r-1);C(this,e,t,r,a-1,-a)}var o=0,i=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},c.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var a=Math.pow(2,8*r-1);C(this,e,t,r,a-1,-a)}var o=r-1,i=1,s=0;for(this[t+o]=255&e;0<=--o&&(i*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/i>>0)-s&255;return t+r},c.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},c.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||C(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeFloatLE=function(e,t,r){return O(this,e,t,!0,r)},c.prototype.writeFloatBE=function(e,t,r){return O(this,e,t,!1,r)},c.prototype.writeDoubleLE=function(e,t,r){return L(this,e,t,!0,r)},c.prototype.writeDoubleBE=function(e,t,r){return L(this,e,t,!1,r)},c.prototype.copy=function(e,t,r,n){if(!c.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r=r||0,n||0===n||(n=this.length),t>=e.length&&(t=e.length),t=t||0,0=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,"number"==typeof(e=e||0))for(o=t;o>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function P(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(t,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function R(e,t,r,n){for(var a=0;a=t.length||a>=e.length);++a)t[a+r]=e[a];return a}function D(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function A(e){return e!=e}var k=function(){for(var e="0123456789abcdef",t=new Array(256),r=0;r<16;++r)for(var n=16*r,a=0;a<16;++a)t[n+a]=e[r]+e[a];return t}()}).call(this,F("buffer").Buffer)},{"base64-js":2,buffer:5,ieee754:10}],6:[function(e,t,r){"use strict";t.exports=e("./").polyfill()},{"./":7}],7:[function(z,r,n){(function(j,V){var e,t;e=this,t=function(){"use strict";function l(e){return"function"==typeof e}var r=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},n=0,t=void 0,a=void 0,i=function(e,t){d[n]=e,d[n+1]=t,2===(n+=2)&&(a?a(h):v())};var e="undefined"!=typeof window?window:void 0,o=e||{},s=o.MutationObserver||o.WebKitMutationObserver,p="undefined"==typeof self&&void 0!==j&&"[object process]"==={}.toString.call(j),u="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function c(){var e=setTimeout;return function(){return e(h,1)}}var d=new Array(1e3);function h(){for(var e=0;e>1,u=-7,c=r?a-1:0,d=r?-1:1,h=e[t+c];for(c+=d,o=h&(1<<-u)-1,h>>=-u,u+=s;0>=-u,u+=n;0>1,d=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:o-1,m=n?1:-1,f=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,i=u):(i=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-i))<1&&(i--,l*=2),2<=(t+=1<=i+c?d/l:d*Math.pow(2,1-c))*l&&(i++,l/=2),u<=i+c?(s=0,i=u):1<=i+c?(s=(t*l-1)*Math.pow(2,a),i+=c):(s=t*Math.pow(2,c-1)*Math.pow(2,a),i=0));8<=a;e[r+h]=255&s,h+=m,s/=256,a-=8);for(i=i<Math.abs(e[0])&&(t=1),Math.abs(e[2])>Math.abs(e[t])&&(t=2),t}var C=4e150;function N(e,t){e.f+=t.f,e.b.f+=t.b.f}function p(e,t,r){return e=e.a,t=t.a,r=r.a,t.b.a===e?r.b.a===e?g(t.a,r.a)?b(r.b.a,t.a,r.a)<=0:0<=b(t.b.a,r.a,t.a):b(r.b.a,e,r.a)<=0:r.b.a===e?0<=b(t.b.a,e,t.a):(t=v(t.b.a,e,t.a),(e=v(r.b.a,e,r.a))<=t)}function O(e){e.a.i=null;var t=e.e;t.a.c=t.c,t.c.a=t.a,e.e=null}function u(e,t){c(e.a),e.c=!1,(e.a=t).i=e}function L(e){for(var t=e.a.a;(e=de(e)).a.a===t;);return e.c&&(u(e,t=d(ce(e).a.b,e.a.e)),e=de(e)),e}function I(e,t,r){var n=new ue;return n.a=r,n.e=W(e.f,t.e,n),r.i=n}function P(e,t){switch(e.s){case 100130:return 0!=(1&t);case 100131:return 0!==t;case 100132:return 0>1]],s[i[p]])?le(r,p):pe(r,p)),s[o]=null,l[o]=r.b,r.b=o}else for(r.c[-(o+1)]=null;0Math.max(i.a,l.a))return!1;if(g(o,i)){if(0n.f&&(n.f*=2,n.c=oe(n.c,n.f+1)),0===n.b?r=a:(r=n.b,n.b=n.c[n.b]),n.e[r]=t,n.c[r]=a,n.d[a]=r,n.h&&pe(n,a),r}return n=e.a++,e.c[n]=t,-(n+1)}function ne(e){if(0===e.a)return se(e.b);var t=e.c[e.d[e.a-1]];if(0!==e.b.a&&g(ie(e.b),t))return se(e.b);for(;--e.a,0e.a||g(n[i],n[l])){a[r[o]=i]=o;break}a[r[o]=l]=o,o=s}}function pe(e,t){for(var r=e.d,n=e.e,a=e.c,o=t,i=r[o];;){var s=o>>1,l=r[s];if(0==s||g(n[l],n[i])){a[r[o]=i]=o;break}a[r[o]=l]=o,o=s}}function ue(){this.e=this.a=null,this.f=0,this.c=this.b=this.h=this.d=!1}function ce(e){return e.e.c.b}function de(e){return e.e.a.b}(n=q.prototype).x=function(){Y(this,0)},n.B=function(e,t){switch(e){case 100142:return;case 100140:switch(t){case 100130:case 100131:case 100132:case 100133:case 100134:return void(this.s=t)}break;case 100141:return void(this.m=!!t);default:return void Z(this,100900)}Z(this,100901)},n.y=function(e){switch(e){case 100142:return 0;case 100140:return this.s;case 100141:return this.m;default:Z(this,100900)}return!1},n.A=function(e,t,r){this.j[0]=e,this.j[1]=t,this.j[2]=r},n.z=function(e,t){var r=t||null;switch(e){case 100100:case 100106:this.h=r;break;case 100104:case 100110:this.l=r;break;case 100101:case 100107:this.k=r;break;case 100102:case 100108:this.i=r;break;case 100103:case 100109:this.p=r;break;case 100105:case 100111:this.o=r;break;case 100112:this.r=r;break;default:Z(this,100900)}},n.C=function(e,t){var r=!1,n=[0,0,0];Y(this,2);for(var a=0;a<3;++a){var o=e[a];o<-1e150&&(o=-1e150,r=!0),1e150a[p]&&(a[p]=u,i[p]=l)}if(l=0,a[1]-o[1]>a[0]-o[0]&&(l=1),a[2]-o[2]>a[l]-o[l]&&(l=2),o[l]>=a[l])n[0]=0,n[1]=0,n[2]=1;else{for(a=0,o=s[l],i=i[l],s=[0,0,0],o=[o.g[0]-i.g[0],o.g[1]-i.g[1],o.g[2]-i.g[2]],p=[0,0,0],l=r.e;l!==r;l=l.e)p[0]=l.g[0]-i.g[0],p[1]=l.g[1]-i.g[1],p[2]=l.g[2]-i.g[2],s[0]=o[1]*p[2]-o[2]*p[1],s[1]=o[2]*p[0]-o[0]*p[2],s[2]=o[0]*p[1]-o[1]*p[0],a<(u=s[0]*s[0]+s[1]*s[1]+s[2]*s[2])&&(a=u,n[0]=s[0],n[1]=s[1],n[2]=s[2]);a<=0&&(n[0]=n[1]=n[2]=0,n[T(o)]=1)}r=!0}for(s=T(n),l=this.b.c,a=(s+1)%3,i=(s+2)%3,s=0>=l,u-=l,y!=o){if(y==i)break;for(var g=y>8,++v;var _=b;if(n>=8;null!==f&&s<4096&&(m[s++]=f<<8|_,p+1<=s&&l<12&&(++l,p=p<<1|1)),f=y}else s=1+i,p=(1<<(l=a+1))-1,f=null}return d!==n&&console.log("Warning, gif stream shorter than expected."),r}try{r.GifWriter=function(g,e,t,r){var v=0,n=void 0===(r=void 0===r?{}:r).loop?null:r.loop,b=void 0===r.palette?null:r.palette;if(e<=0||t<=0||65535>=1;)++a;if(i=1<>8&255,g[v++]=255&t,g[v++]=t>>8&255,g[v++]=(null!==b?128:0)|a,g[v++]=o,g[v++]=0,null!==b)for(var s=0,l=b.length;s>16&255,g[v++]=p>>8&255,g[v++]=255&p}if(null!==n){if(n<0||65535>8&255,g[v++]=0}var x=!1;this.addFrame=function(e,t,r,n,a,o){if(!0===x&&(--v,x=!1),o=void 0===o?{}:o,e<0||t<0||65535>=1;)++p;l=1<>8&255,g[v++]=h,g[v++]=0),g[v++]=44,g[v++]=255&e,g[v++]=e>>8&255,g[v++]=255&t,g[v++]=t>>8&255,g[v++]=255&r,g[v++]=r>>8&255,g[v++]=255&n,g[v++]=n>>8&255,g[v++]=!0===i?128|p-1:0,!0===i)for(var m=0,f=s.length;m>16&255,g[v++]=y>>8&255,g[v++]=255&y}return v=function(t,r,e,n){t[r++]=e;var a=r++,o=1<>=8,u-=8,r===a+256&&(t[a]=255,a=r++)}function h(e){c|=e<>=8,u-=8,r===a+256&&(t[a]=255,a=r++);4096===l?(h(o),l=1+s,p=e+1,f={}):(1<>7,a=1<<1+(7&r);x[e++],x[e++];var o=null,i=null;n&&(o=e,e+=3*(i=a));var s=!0,l=[],p=0,u=null,c=0,d=null;for(this.width=S,this.height=t;s&&e>2&7,e++;break;case 254:for(;;){if(!(0<=(C=x[e++])))throw Error("Invalid block size");if(0===C)break;e+=C}break;default:throw new Error("Unknown graphic control label: 0x"+x[e-1].toString(16))}break;case 44:var m=x[e++]|x[e++]<<8,f=x[e++]|x[e++]<<8,y=x[e++]|x[e++]<<8,g=x[e++]|x[e++]<<8,v=x[e++],b=v>>6&1,_=1<<1+(7&v),w=o,M=i,E=!1;if(v>>7){E=!0;w=e,e+=3*(M=_)}var T=e;for(e++;;){var C;if(!(0<=(C=x[e++])))throw Error("Invalid block size");if(0===C)break;e+=C}l.push({x:m,y:f,width:y,height:g,has_local_palette:E,palette_offset:w,palette_size:M,data_offset:T,data_length:e-T,transparent_index:u,interlaced:!!b,delay:p,disposal:c});break;case 59:s=!1;break;default:throw new Error("Unknown gif block: 0x"+x[e-1].toString(16))}this.numFrames=function(){return l.length},this.loopCount=function(){return d},this.frameInfo=function(e){if(e<0||e>=l.length)throw new Error("Frame index out of range.");return l[e]},this.decodeAndBlitFrameBGRA=function(e,t){var r=this.frameInfo(e),n=r.width*r.height,a=new Uint8Array(n);N(x,r.data_offset,a,n);var o=r.palette_offset,i=r.transparent_index;null===i&&(i=256);var s=r.width,l=S-s,p=s,u=4*(r.y*S+r.x),c=4*((r.y+r.height)*S+r.x),d=u,h=4*l;!0===r.interlaced&&(h+=4*S*7);for(var m=8,f=0,y=a.length;f>=1)),g===i)d+=4;else{var v=x[o+3*g],b=x[o+3*g+1],_=x[o+3*g+2];t[d++]=_,t[d++]=b,t[d++]=v,t[d++]=255}--p}},this.decodeAndBlitFrameRGBA=function(e,t){var r=this.frameInfo(e),n=r.width*r.height,a=new Uint8Array(n);N(x,r.data_offset,a,n);var o=r.palette_offset,i=r.transparent_index;null===i&&(i=256);var s=r.width,l=S-s,p=s,u=4*(r.y*S+r.x),c=4*((r.y+r.height)*S+r.x),d=u,h=4*l;!0===r.interlaced&&(h+=4*S*7);for(var m=8,f=0,y=a.length;f>=1)),g===i)d+=4;else{var v=x[o+3*g],b=x[o+3*g+1],_=x[o+3*g+2];t[d++]=v,t[d++]=b,t[d++]=_,t[d++]=255}--p}}}}catch(e){}},{}],13:[function(jr,t,r){(function(Gr){var e;e=this,function(E){"use strict";function e(e){if(null==this)throw TypeError();var t=String(this),r=t.length,n=e?Number(e):0;if(n!=n&&(n=0),!(n<0||r<=n)){var a,o=t.charCodeAt(n);return 55296<=o&&o<=56319&&n+1>>=1,t}function _(e,t,r){if(!t)return r;for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>16-t;return e.tag>>>=t,e.bitcount-=t,n+r}function x(e,t){for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>=1,++a,r+=t.table[a],0<=(n-=t.table[a]););return e.tag=o,e.bitcount-=a,t.trans[r+n]}function S(e,t,r){var n,a,o,i,s,l;for(n=_(e,5,257),a=_(e,5,1),o=_(e,4,4),i=0;i<19;++i)y[i]=0;for(i=0;ithis.x2&&(this.x2=e)),"number"==typeof t&&((isNaN(this.y1)||isNaN(this.y2))&&(this.y1=t,this.y2=t),tthis.y2&&(this.y2=t))},C.prototype.addX=function(e){this.addPoint(e,null)},C.prototype.addY=function(e){this.addPoint(null,e)},C.prototype.addBezier=function(e,t,r,n,a,o,i,s){var l=this,p=[e,t],u=[r,n],c=[a,o],d=[i,s];this.addPoint(e,t),this.addPoint(i,s);for(var h=0;h<=1;h++){var m=6*p[h]-12*u[h]+6*c[h],f=-3*p[h]+9*u[h]-9*c[h]+3*d[h],y=3*u[h]-3*p[h];if(0!=f){var g=Math.pow(m,2)-4*y*f;if(!(g<0)){var v=(-m+Math.sqrt(g))/(2*f);0>8&255,255&e]},D.USHORT=k(2),R.SHORT=function(e){return 32768<=e&&(e=-(65536-e)),[e>>8&255,255&e]},D.SHORT=k(2),R.UINT24=function(e){return[e>>16&255,e>>8&255,255&e]},D.UINT24=k(3),R.ULONG=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]},D.ULONG=k(4),R.LONG=function(e){return I<=e&&(e=-(2*I-e)),[e>>24&255,e>>16&255,e>>8&255,255&e]},D.LONG=k(4),R.FIXED=R.ULONG,D.FIXED=D.ULONG,R.FWORD=R.SHORT,D.FWORD=D.SHORT,R.UFWORD=R.USHORT,D.UFWORD=D.USHORT,R.LONGDATETIME=function(e){return[0,0,0,0,e>>24&255,e>>16&255,e>>8&255,255&e]},D.LONGDATETIME=k(8),R.TAG=function(e){return L.argument(4===e.length,"Tag should be exactly 4 ASCII characters."),[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]},D.TAG=k(4),R.Card8=R.BYTE,D.Card8=D.BYTE,R.Card16=R.USHORT,D.Card16=D.USHORT,R.OffSize=R.BYTE,D.OffSize=D.BYTE,R.SID=R.USHORT,D.SID=D.USHORT,R.NUMBER=function(e){return-107<=e&&e<=107?[e+139]:108<=e&&e<=1131?[247+((e-=108)>>8),255&e]:-1131<=e&&e<=-108?[251+((e=-e-108)>>8),255&e]:-32768<=e&&e<=32767?R.NUMBER16(e):R.NUMBER32(e)},D.NUMBER=function(e){return R.NUMBER(e).length},R.NUMBER16=function(e){return[28,e>>8&255,255&e]},D.NUMBER16=k(3),R.NUMBER32=function(e){return[29,e>>24&255,e>>16&255,e>>8&255,255&e]},D.NUMBER32=k(5),R.REAL=function(e){var t=e.toString(),r=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(t);if(r){var n=parseFloat("1e"+((r[2]?+r[2]:0)+r[1].length));t=(Math.round(e*n)/n).toString()}for(var a="",o=0,i=t.length;o>8&255,t[t.length]=255&n}return t},D.UTF16=function(e){return 2*e.length};var F={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};P.MACSTRING=function(e,t,r,n){var a=F[n];if(void 0!==a){for(var o="",i=0;i>8&255,l+256&255)}return o}R.MACSTRING=function(e,t){var r=function(e){if(!U)for(var t in U={},F)U[t]=new String(t);var r=U[e];if(void 0!==r){if(B){var n=B.get(r);if(void 0!==n)return n}var a=F[e];if(void 0!==a){for(var o={},i=0;i>8,t[c+1]=255&d,t=t.concat(n[u])}return t},D.TABLE=function(e){for(var t=0,r=e.fields.length,n=0;n>1,t.skip("uShort",3),e.glyphIndexMap={};for(var i=new se.Parser(r,n+a+14),s=new se.Parser(r,n+a+16+2*o),l=new se.Parser(r,n+a+16+4*o),p=new se.Parser(r,n+a+16+6*o),u=n+a+16+8*o,c=0;c>4,o=15&n;if(15==a)break;if(t+=r[a],15==o)break;t+=r[o]}return parseFloat(t)}(e);if(32<=t&&t<=246)return t-139;if(247<=t&&t<=250)return 256*(t-247)+e.parseByte()+108;if(251<=t&&t<=254)return 256*-(t-251)-e.parseByte()-108;throw new Error("Invalid b0 "+t)}function Te(e,t,r){t=void 0!==t?t:0;var n=new se.Parser(e,t),a=[],o=[];for(r=void 0!==r?r:e.length;n.relativeOffset>1,T.length=0,N=!0}return function e(t){for(var r,n,a,o,i,s,l,p,u,c,d,h,m=0;mMath.abs(h-I)?L=d+T.shift():I=h+T.shift(),E.curveTo(v,b,_,x,l,p),E.curveTo(u,c,d,h,L,I);break;default:console.log("Glyph "+g.index+": unknown operator 1200"+f),T.length=0}break;case 14:0>3;break;case 21:2>16),m+=2;break;case 29:i=T.pop()+y.gsubrsBias,(s=y.gsubrs[i])&&e(s);break;case 30:for(;0=r.begin&&e=de.length){var i=n.parseChar();r.names.push(n.parseString(i))}break;case 2.5:r.numberOfGlyphs=n.parseUShort(),r.offset=new Array(r.numberOfGlyphs);for(var s=0;st.value.tag?1:-1}),t.fields=t.fields.concat(n),t.fields=t.fields.concat(a),t}function yt(e,t,r){for(var n=0;n 123 are reserved for internal usage");h|=1<>>1,o=e[a].tag;if(o===t)return a;o>>1,o=e[a];if(o===t)return a;o>>1,i=(r=e[o]).start;if(i===t)return r;i(r=e[n-1]).end?0:r}function xt(e,t){this.font=e,this.tableName=t}function St(e){xt.call(this,e,"gpos")}function wt(e){xt.call(this,e,"gsub")}function Mt(e,t){var r=e.length;if(r!==t.length)return!1;for(var n=0;nt.points.length-1||n.matchedPoints[1]>a.points.length-1)throw Error("Matched points out of range in "+t.name);var i=t.points[n.matchedPoints[0]],s=a.points[n.matchedPoints[1]],l={xScale:n.xScale,scale01:n.scale01,scale10:n.scale10,yScale:n.yScale,dx:0,dy:0};s=Lt([s],l)[0],l.dx=i.x-s.x,l.dy=i.y-s.y,o=Lt(a.points,l)}t.points=t.points.concat(o)}}return It(t.points)}(St.prototype=xt.prototype={searchTag:vt,binSearch:bt,getTable:function(e){var t=this.font.tables[this.tableName];return!t&&e&&(t=this.font.tables[this.tableName]=this.createDefaultTable()),t},getScriptNames:function(){var e=this.getTable();return e?e.scripts.map(function(e){return e.tag}):[]},getDefaultScriptName:function(){var e=this.getTable();if(e){for(var t=!1,r=0;r=s[p-1].tag,"Features must be added in alphabetical order."),o={tag:r,feature:{params:0,lookupListIndexes:[]}},s.push(o),i.push(p),o.feature}}},getLookupTables:function(e,t,r,n,a){var o=this.getFeatureTable(e,t,r,a),i=[];if(o){for(var s,l=o.lookupListIndexes,p=this.font.tables[this.tableName].lookups,u=0;u",s),t.stack.push(Math.round(64*s))}function gr(e,t){var r=t.stack,n=r.pop(),a=t.fv,o=t.pv,i=t.ppem,s=t.deltaBase+16*(e-1),l=t.deltaShift,p=t.z0;E.DEBUG&&console.log(t.step,"DELTAP["+e+"]",n,r);for(var u=0;u>4)===i){var h=(15&d)-8;0<=h&&h++,E.DEBUG&&console.log(t.step,"DELTAPFIX",c,"by",h*l);var m=p[c];a.setRelative(m,m,h*l,o)}}}function vr(e,t){var r=t.stack,n=r.pop();E.DEBUG&&console.log(t.step,"ROUND[]"),r.push(64*t.round(n/64))}function br(e,t){var r=t.stack,n=r.pop(),a=t.ppem,o=t.deltaBase+16*(e-1),i=t.deltaShift;E.DEBUG&&console.log(t.step,"DELTAC["+e+"]",n,r);for(var s=0;s>4)===a){var u=(15&p)-8;0<=u&&u++;var c=u*i;E.DEBUG&&console.log(t.step,"DELTACFIX",l,"by",c),t.cvt[l]+=c}}}function _r(e,t){var r,n,a=t.stack,o=a.pop(),i=a.pop(),s=t.z2[o],l=t.z1[i];E.DEBUG&&console.log(t.step,"SDPVTL["+e+"]",o,i),n=e?(r=s.y-l.y,l.x-s.x):(r=l.x-s.x,l.y-s.y),t.dpv=Zt(r,n)}function xr(e,t){var r=t.stack,n=t.prog,a=t.ip;E.DEBUG&&console.log(t.step,"PUSHB["+e+"]");for(var o=0;o":"_")+(n?"R":"_")+(0===a?"Gr":1===a?"Bl":2===a?"Wh":"")+"]",e?c+"("+o.cvt[c]+","+p+")":"",d,"(d =",i,"->",l*s,")"),o.rp1=o.rp0,o.rp2=d,t&&(o.rp0=d)}Ut.prototype.exec=function(e,t){if("number"!=typeof t)throw new Error("Point size is not a number!");if(!(2",n),s.interpolate(c,o,i,l),s.touch(c)}e.loop=1},hr.bind(void 0,0),hr.bind(void 0,1),function(e){for(var t=e.stack,r=e.rp0,n=e.z0[r],a=e.loop,o=e.fv,i=e.pv,s=e.z1;a--;){var l=t.pop(),p=s[l];E.DEBUG&&console.log(e.step,(1"].indexOf(a[0])?void 0:a[0],lineNumber:a[1],columnNumber:a[2],source:e}},this)},parseFFOrSafari:function(e){return e.stack.split("\n").filter(function(e){return!e.match(n)},this).map(function(e){if(-1 eval")&&(e=e.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),-1===e.indexOf("@")&&-1===e.indexOf(":"))return{functionName:e};var t=/((.*".+"[^@]*)?[^@]*)(?:@)/,r=e.match(t),n=r&&r[1]?r[1]:void 0,a=this.extractLocation(e.replace(t,""));return{functionName:n,fileName:a[0],lineNumber:a[1],columnNumber:a[2],source:e}},this)},parseOpera:function(e){return!e.stacktrace||-1e.stacktrace.split("\n").length?this.parseOpera9(e):e.stack?this.parseOpera11(e):this.parseOpera10(e)},parseOpera9:function(e){for(var t=/Line (\d+).*script (?:in )?(\S+)/i,r=e.message.split("\n"),n=[],a=2,o=r.length;a/,"$2").replace(/\([^)]*\)/g,"")||void 0;return a.match(/\(([^)]*)\)/)&&(t=a.replace(/^[^(]+\(([^)]*)\)$/,"$1")),{functionName:o,args:void 0===t||"[arguments not available]"===t?void 0:t.split(","),fileName:n[0],lineNumber:n[1],columnNumber:n[2],source:e}},this)}}}a.default._getErrorStackParser=function(){return new o};var i=a.default;r.default=i},{"../main":32}],27:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n,a=(n=e("../main"))&&n.__esModule?n:{default:n};(function(e){if(e&&e.__esModule)return;if(null===e||"object"!==s(e)&&"function"!=typeof e)return;var t=i();if(t&&t.has(e))return t.get(e);var r={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)){var o=n?Object.getOwnPropertyDescriptor(e,a):null;o&&(o.get||o.set)?Object.defineProperty(r,a,o):r[a]=e[a]}r.default=e,t&&t.set(e,r)})(e("../constants")),e("../internationalization");function i(){if("function"!=typeof WeakMap)return null;var e=new WeakMap;return i=function(){return e},e}function s(e){return(s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}a.default._validateParameters=a.default._clearValidateParamsCache=function(){};var o=a.default;r.default=o},{"../../../docs/parameterData.json":1,"../constants":22,"../internationalization":30,"../main":32}],28:[function(e,t,r){"use strict";function i(e){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var o=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==i(e)&&"function"!=typeof e)return{default:e};var t=s();if(t&&t.has(e))return t.get(e);var r={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)){var o=n?Object.getOwnPropertyDescriptor(e,a):null;o&&(o.get||o.set)?Object.defineProperty(r,a,o):r[a]=e[a]}r.default=e,t&&t.set(e,r);return r}(e("./constants"));function s(){if("function"!=typeof WeakMap)return null;var e=new WeakMap;return s=function(){return e},e}var n={modeAdjust:function(e,t,r,n,a){return a===o.CORNER?{x:e,y:t,w:r,h:n}:a===o.CORNERS?{x:e,y:t,w:r-e,h:n-t}:a===o.RADIUS?{x:e-r,y:t-n,w:2*r,h:2*n}:a===o.CENTER?{x:e-.5*r,y:t-.5*n,w:r,h:n}:void 0}};r.default=n},{"./constants":22}],29:[function(e,t,r){"use strict";var n,a=(n=e("../core/main"))&&n.__esModule?n:{default:n};e("./internationalization");var o=Promise.resolve();Promise.all([new Promise(function(e,t){"complete"===document.readyState?e():window.addEventListener("load",e,!1)}),o]).then(function(){void 0===window._setupDone?window.mocha||(window.setup&&"function"==typeof window.setup||window.draw&&"function"==typeof window.draw)&&!a.default.instance&&new a.default:console.warn("p5.js seems to have been imported multiple times. Please remove the duplicate import")})},{"../core/main":32,"./internationalization":30}],30:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.initialize=n.translator=void 0;var a,o=r(e("i18next")),i=r(e("i18next-browser-languagedetector"));function r(e){return e&&e.__esModule?e:{default:e}}var s=function(){return console.debug("p5.js translator called before translations were loaded"),""};n.translator=s;n.initialize=function(){return new Promise(function(t,r){o.default.use(i.default).init({fallbackLng:"en",nestingPrefix:"$tr(",nestingSuffix:")",defaultNS:"translation",returnEmptyString:!1,interpolation:{escapeValue:!1},detection:{checkWhitelist:!1},resources:a}).then(function(e){n.translator=s=e,t()},function(e){return r("Translations failed to load (".concat(e,")"))})})}},{"../../translations":void 0,i18next:4,"i18next-browser-languagedetector":4}],31:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n,a=(n=e("./main"))&&n.__esModule?n:{default:n};a.default.prototype.pushStyle=function(){throw new Error("pushStyle() not used, see push()")},a.default.prototype.popStyle=function(){throw new Error("popStyle() not used, see pop()")},a.default.prototype.popMatrix=function(){throw new Error("popMatrix() not used, see pop()")},a.default.prototype.pushMatrix=function(){throw new Error("pushMatrix() not used, see push()")};var o=a.default;r.default=o},{"./main":32}],32:[function(e,t,r){"use strict";function i(e){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0,e("./shim");var n=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==i(e)&&"function"!=typeof e)return{default:e};var t=s();if(t&&t.has(e))return t.get(e);var r={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)){var o=n?Object.getOwnPropertyDescriptor(e,a):null;o&&(o.get||o.set)?Object.defineProperty(r,a,o):r[a]=e[a]}r.default=e,t&&t.set(e,r);return r}(e("./constants"));function s(){if("function"!=typeof WeakMap)return null;var e=new WeakMap;return s=function(){return e},e}function a(e,t){for(var r=0;r=i.width||t>=i.height?[0,0,0,0]:this._getPixel(e,t);var s=new l.default.Image(r,n);return s.canvas.getContext("2d").drawImage(i,e,t,r*o,n*o,0,0,r,n),s},l.default.Renderer.prototype.textLeading=function(e){return"number"==typeof e?(this._setProperty("_textLeading",e),this._pInst):this._textLeading},l.default.Renderer.prototype.textSize=function(e){return"number"==typeof e?(this._setProperty("_textSize",e),this._setProperty("_textLeading",e*b._DEFAULT_LEADMULT),this._applyTextProperties()):this._textSize},l.default.Renderer.prototype.textStyle=function(e){return e?(e!==b.NORMAL&&e!==b.ITALIC&&e!==b.BOLD&&e!==b.BOLDITALIC||this._setProperty("_textStyle",e),this._applyTextProperties()):this._textStyle},l.default.Renderer.prototype.textAscent=function(){return null===this._textAscent&&this._updateTextMetrics(),this._textAscent},l.default.Renderer.prototype.textDescent=function(){return null===this._textDescent&&this._updateTextMetrics(),this._textDescent},l.default.Renderer.prototype.textAlign=function(e,t){return void 0!==e?(this._setProperty("_textAlign",e),void 0!==t&&this._setProperty("_textBaseline",t),this._applyTextProperties()):{horizontal:this._textAlign,vertical:this._textBaseline}},l.default.Renderer.prototype.text=function(e,t,r,n,a){var o,i,s,l,p,u,c,d,h,m=this._pInst,f=Number.MAX_VALUE;if((this._doFill||this._doStroke)&&void 0!==e){if("string"!=typeof e&&(e=e.toString()),o=(e=e.replace(/(\t)/g," ")).split("\n"),void 0!==n){for(c=1,s=h=0;ss.HALF_PI&&e<=3*s.HALF_PI?Math.atan(r/n*Math.tan(e))+s.PI:Math.atan(r/n*Math.tan(e))+s.TWO_PI,t=t<=s.HALF_PI?Math.atan(r/n*Math.tan(t)):t>s.HALF_PI&&t<=3*s.HALF_PI?Math.atan(r/n*Math.tan(t))+s.PI:Math.atan(r/n*Math.tan(t))+s.TWO_PI),tg||Math.abs(this.accelerationY-this.pAccelerationY)>g||Math.abs(this.accelerationZ-this.pAccelerationZ)>g)&&e();var t=this.deviceTurned||window.deviceTurned;if("function"==typeof t){var r=this.rotationX+180,n=this.pRotationX+180,a=c+180;0>>24],n+=x[(16711680&C)>>16],a+=x[(65280&C)>>8],o+=x[255&C],r+=L[_],s++}S[l=T+v]=i/r,w[l]=n/r,M[l]=a/r,E[l]=o/r}T+=h}for(u=(p=-N)*h,b=T=0;b>>16,e[r+1]=(65280&t[n])>>>8,e[r+2]=255&t[n],e[r+3]=(4278190080&t[n])>>>24},P._toImageData=function(e){return e instanceof ImageData?e:e.getContext("2d").getImageData(0,0,e.width,e.height)},P._createImageData=function(e,t){return P._tmpCanvas=document.createElement("canvas"),P._tmpCtx=P._tmpCanvas.getContext("2d"),this._tmpCtx.createImageData(e,t)},P.apply=function(e,t,r){var n=e.getContext("2d"),a=n.getImageData(0,0,e.width,e.height),o=t(a,r);o instanceof ImageData?n.putImageData(o,0,0,0,0,e.width,e.height):n.putImageData(a,0,0,0,0,e.width,e.height)},P.threshold=function(e,t){var r=P._toPixels(e);void 0===t&&(t=.5);for(var n=Math.floor(255*t),a=0;a>8)/n,r[a+1]=255*(i*t>>8)/n,r[a+2]=255*(s*t>>8)/n}},P.dilate=function(e){for(var t,r,n,a,o,i,s,l,p,u,c,d,h,m,f,y,g,v=P._toPixels(e),b=0,_=v.length?v.length/4:0,x=new Int32Array(_);b<_;)for(r=(t=b)+e.width;b>16&255)+151*(n>>8&255)+28*(255&n))<(f=77*(c>>16&255)+151*(c>>8&255)+28*(255&c))&&(a=c,o=f),o<(m=77*((u=P._getARGB(v,i))>>16&255)+151*(u>>8&255)+28*(255&u))&&(a=u,o=m),o<(y=77*(d>>16&255)+151*(d>>8&255)+28*(255&d))&&(a=d,o=y),o<(g=77*(h>>16&255)+151*(h>>8&255)+28*(255&h))&&(a=h,o=g),x[b++]=a;P._setPixels(v,x)},P.erode=function(e){for(var t,r,n,a,o,i,s,l,p,u,c,d,h,m,f,y,g,v=P._toPixels(e),b=0,_=v.length?v.length/4:0,x=new Int32Array(_);b<_;)for(r=(t=b)+e.width;b>16&255)+151*(c>>8&255)+28*(255&c))<(o=77*(n>>16&255)+151*(n>>8&255)+28*(255&n))&&(a=c,o=f),(m=77*((u=P._getARGB(v,i))>>16&255)+151*(u>>8&255)+28*(255&u))>16&255)+151*(d>>8&255)+28*(255&d))>16&255)+151*(h>>8&255)+28*(255&h))=r){var n=Math.floor(t.timeDisplayed/r);if(t.timeDisplayed=0,t.displayIndex+=n,t.loopCount=Math.floor(t.displayIndex/t.numFrames),null!==t.loopLimit&&t.loopCount>=t.loopLimit)t.playing=!1;else{var a=t.displayIndex%t.numFrames;this.drawingContext.putImageData(t.frames[a].image,0,0),t.displayIndex=a,this.setModified(!0)}}}},a.default.Image.prototype._setProperty=function(e,t){this[e]=t,this.setModified(!0)},a.default.Image.prototype.loadPixels=function(){a.default.Renderer2D.prototype.loadPixels.call(this),this.setModified(!0)},a.default.Image.prototype.updatePixels=function(e,t,r,n){a.default.Renderer2D.prototype.updatePixels.call(this,e,t,r,n),this.setModified(!0)},a.default.Image.prototype.get=function(e,t,r,n){return a.default._validateParameters("p5.Image.get",arguments),a.default.Renderer2D.prototype.get.apply(this,arguments)},a.default.Image.prototype._getPixel=a.default.Renderer2D.prototype._getPixel,a.default.Image.prototype.set=function(e,t,r){a.default.Renderer2D.prototype.set.call(this,e,t,r),this.setModified(!0)},a.default.Image.prototype.resize=function(e,t){0===e&&0===t?(e=this.canvas.width,t=this.canvas.height):0===e?e=this.canvas.width*t/this.canvas.height:0===t&&(t=this.canvas.height*e/this.canvas.width),e=Math.floor(e),t=Math.floor(t);var r=document.createElement("canvas");if(r.width=e,r.height=t,this.gifProperties)for(var n=this.gifProperties,a=function(e,t){for(var r=0,n=0;n/g,">").replace(/"/g,""").replace(/'/g,"'")}function l(e,t){t&&!0!==t&&"true"!==t||(t="");var r="";return(e=e||"untitled")&&e.includes(".")&&(r=e.split(".").pop()),t&&r!==t&&(r=t,e="".concat(e,".").concat(r)),[e,r]}e("../core/friendly_errors/validate_params"),e("../core/friendly_errors/file_errors"),e("../core/friendly_errors/fes_core"),g.default.prototype.loadJSON=function(){for(var e=arguments.length,t=new Array(e),r=0;r"),a.print("");if(a.print(' '),a.print(""),a.print(""),a.print(" "),"0"!==o[0]){a.print(" ");for(var u=0;u".concat(c)),a.print(" ")}a.print(" ")}for(var d=0;d");for(var h=0;h".concat(m)),a.print(" ")}a.print(" ")}a.print("
"),a.print(""),a.print("")}a.close(),a.clear()},g.default.prototype.writeFile=function(e,t,r){var n="application/octet-stream";g.default.prototype._isSafari()&&(n="text/plain");var a=new Blob(e,{type:n});g.default.prototype.downloadFile(a,t,r)},g.default.prototype.downloadFile=function(e,t,r){var n=l(t,r),a=n[0];if(e instanceof Blob)s.default.saveAs(e,a);else{var o=document.createElement("a");if(o.href=e,o.download=a,o.onclick=function(e){var t;t=e,document.body.removeChild(t.target),e.stopPropagation()},o.style.display="none",document.body.appendChild(o),g.default.prototype._isSafari()){var i="Hello, Safari user! To download this file...\n";i+="1. Go to File --\x3e Save As.\n",i+='2. Choose "Page Source" as the Format.\n',i+='3. Name it with this extension: ."'.concat(n[1],'"'),alert(i)}o.click()}},g.default.prototype._checkFileExtension=l,g.default.prototype._isSafari=function(){return 0>>0},getSeed:function(){return t},rand:function(){return(r=(1664525*r+1013904223)%n)/n}});a.setSeed(e),_=new Array(4096);for(var o=0;o<4096;o++)_[o]=a.rand()};var o=a.default;r.default=o},{"../core/main":32}],65:[function(e,t,r){"use strict";function i(e){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n,l=(n=e("../core/main"))&&n.__esModule?n:{default:n},o=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==i(e)&&"function"!=typeof e)return{default:e};var t=s();if(t&&t.has(e))return t.get(e);var r={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)){var o=n?Object.getOwnPropertyDescriptor(e,a):null;o&&(o.get||o.set)?Object.defineProperty(r,a,o):r[a]=e[a]}r.default=e,t&&t.set(e,r);return r}(e("../core/constants"));function s(){if("function"!=typeof WeakMap)return null;var e=new WeakMap;return s=function(){return e},e}l.default.Vector=function(e,t,r){var n,a,o;o=e instanceof l.default?(this.p5=e,n=t[0]||0,a=t[1]||0,t[2]||0):(n=e||0,a=t||0,r||0),this.x=n,this.y=a,this.z=o},l.default.Vector.prototype.toString=function(){return"p5.Vector Object : [".concat(this.x,", ").concat(this.y,", ").concat(this.z,"]")},l.default.Vector.prototype.set=function(e,t,r){return e instanceof l.default.Vector?(this.x=e.x||0,this.y=e.y||0,this.z=e.z||0):e instanceof Array?(this.x=e[0]||0,this.y=e[1]||0,this.z=e[2]||0):(this.x=e||0,this.y=t||0,this.z=r||0),this},l.default.Vector.prototype.copy=function(){return this.p5?new l.default.Vector(this.p5,[this.x,this.y,this.z]):new l.default.Vector(this.x,this.y,this.z)},l.default.Vector.prototype.add=function(e,t,r){return e instanceof l.default.Vector?(this.x+=e.x||0,this.y+=e.y||0,this.z+=e.z||0):e instanceof Array?(this.x+=e[0]||0,this.y+=e[1]||0,this.z+=e[2]||0):(this.x+=e||0,this.y+=t||0,this.z+=r||0),this};function p(e,t){return 0!==e&&(this.x=this.x%e),0!==t&&(this.y=this.y%t),this}function u(e,t,r){return 0!==e&&(this.x=this.x%e),0!==t&&(this.y=this.y%t),0!==r&&(this.z=this.z%r),this}l.default.Vector.prototype.rem=function(e,t,r){if(e instanceof l.default.Vector){if(Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.z)){var n=parseFloat(e.x),a=parseFloat(e.y),o=parseFloat(e.z);u.call(this,n,a,o)}}else if(e instanceof Array)e.every(function(e){return Number.isFinite(e)})&&(2===e.length&&p.call(this,e[0],e[1]),3===e.length&&u.call(this,e[0],e[1],e[2]));else if(1===arguments.length){if(Number.isFinite(e)&&0!==e)return this.x=this.x%e,this.y=this.y%e,this.z=this.z%e,this}else if(2===arguments.length){var i=Array.prototype.slice.call(arguments);i.every(function(e){return Number.isFinite(e)})&&2===i.length&&p.call(this,i[0],i[1])}else if(3===arguments.length){var s=Array.prototype.slice.call(arguments);s.every(function(e){return Number.isFinite(e)})&&3===s.length&&u.call(this,s[0],s[1],s[2])}},l.default.Vector.prototype.sub=function(e,t,r){return e instanceof l.default.Vector?(this.x-=e.x||0,this.y-=e.y||0,this.z-=e.z||0):e instanceof Array?(this.x-=e[0]||0,this.y-=e[1]||0,this.z-=e[2]||0):(this.x-=e||0,this.y-=t||0,this.z-=r||0),this},l.default.Vector.prototype.mult=function(e,t,r){if(e instanceof l.default.Vector)return Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.z)&&"number"==typeof e.x&&"number"==typeof e.y&&"number"==typeof e.z?(this.x*=e.x,this.y*=e.y,this.z*=e.z):console.warn("p5.Vector.prototype.mult:","x contains components that are either undefined or not finite numbers"),this;if(e instanceof Array)return e.every(function(e){return Number.isFinite(e)})&&e.every(function(e){return"number"==typeof e})?1===e.length?(this.x*=e[0],this.y*=e[0],this.z*=e[0]):2===e.length?(this.x*=e[0],this.y*=e[1]):3===e.length&&(this.x*=e[0],this.y*=e[1],this.z*=e[2]):console.warn("p5.Vector.prototype.mult:","x contains elements that are either undefined or not finite numbers"),this;var n=Array.prototype.slice.call(arguments);return n.every(function(e){return Number.isFinite(e)})&&n.every(function(e){return"number"==typeof e})?(1===arguments.length&&(this.x*=e,this.y*=e,this.z*=e),2===arguments.length&&(this.x*=e,this.y*=t),3===arguments.length&&(this.x*=e,this.y*=t,this.z*=r)):console.warn("p5.Vector.prototype.mult:","x, y, or z arguments are either undefined or not a finite number"),this},l.default.Vector.prototype.div=function(e,t,r){if(e instanceof l.default.Vector){if(Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.z)&&"number"==typeof e.x&&"number"==typeof e.y&&"number"==typeof e.z){if(0===e.x||0===e.y||0===e.z)return console.warn("p5.Vector.prototype.div:","divide by 0"),this;this.x/=e.x,this.y/=e.y,this.z/=e.z}else console.warn("p5.Vector.prototype.div:","x contains components that are either undefined or not finite numbers");return this}if(e instanceof Array){if(e.every(function(e){return Number.isFinite(e)})&&e.every(function(e){return"number"==typeof e})){if(e.some(function(e){return 0===e}))return console.warn("p5.Vector.prototype.div:","divide by 0"),this;1===e.length?(this.x/=e[0],this.y/=e[0],this.z/=e[0]):2===e.length?(this.x/=e[0],this.y/=e[1]):3===e.length&&(this.x/=e[0],this.y/=e[1],this.z/=e[2])}else console.warn("p5.Vector.prototype.div:","x contains components that are either undefined or not finite numbers");return this}var n=Array.prototype.slice.call(arguments);if(n.every(function(e){return Number.isFinite(e)})&&n.every(function(e){return"number"==typeof e})){if(n.some(function(e){return 0===e}))return console.warn("p5.Vector.prototype.div:","divide by 0"),this;1===arguments.length&&(this.x/=e,this.y/=e,this.z/=e),2===arguments.length&&(this.x/=e,this.y/=t),3===arguments.length&&(this.x/=e,this.y/=t,this.z/=r)}else console.warn("p5.Vector.prototype.div:","x, y, or z arguments are either undefined or not a finite number");return this},l.default.Vector.prototype.mag=function(){return Math.sqrt(this.magSq())},l.default.Vector.prototype.magSq=function(){var e=this.x,t=this.y,r=this.z;return e*e+t*t+r*r},l.default.Vector.prototype.dot=function(e,t,r){return e instanceof l.default.Vector?this.dot(e.x,e.y,e.z):this.x*(e||0)+this.y*(t||0)+this.z*(r||0)},l.default.Vector.prototype.cross=function(e){var t=this.y*e.z-this.z*e.y,r=this.z*e.x-this.x*e.z,n=this.x*e.y-this.y*e.x;return this.p5?new l.default.Vector(this.p5,[t,r,n]):new l.default.Vector(t,r,n)},l.default.Vector.prototype.dist=function(e){return e.copy().sub(this).mag()},l.default.Vector.prototype.normalize=function(){var e=this.mag();return 0!==e&&this.mult(1/e),this},l.default.Vector.prototype.limit=function(e){var t=this.magSq();return e*e>>0},a.default.prototype.randomSeed=function(e){this._lcgSetSeed(o,e),this._gaussian_previous=!1},a.default.prototype.random=function(e,t){var r;if(a.default._validateParameters("random",arguments),r=null!=this[o]?this._lcg(o):Math.random(),void 0===e)return r;if(void 0===t)return e instanceof Array?e[Math.floor(r*e.length)]:r*e;if(td){var N=m,O=l,L=p;m=h+d*(s&&h=t&&(r=r.substring(r.length-t,r.length)),r}},a.default.prototype.unhex=function(e){return e instanceof Array?e.map(a.default.prototype.unhex):parseInt("0x".concat(e),16)};var o=a.default;r.default=o},{"../core/main":32}],73:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n,i=(n=e("../core/main"))&&n.__esModule?n:{default:n};function a(e,t,r){var n=e<0,a=n?e.toString().substring(1):e.toString(),o=a.indexOf("."),i=-1!==o?a.substring(0,o):a,s=-1!==o?a.substring(o+1):"",l=n?"-":"";if(void 0!==r){var p="";(-1!==o||0r&&(s=s.substring(0,r));for(var u=0;un.length)for(var o=t-(n+=-1===r?".":"").length+1,i=0;i=h.TWO_PI?"".concat("ellipse","|").concat(p,"|"):"".concat("arc","|").concat(i,"|").concat(s,"|").concat(l,"|").concat(p,"|"),!this.geometryInHash(t)){var u=new T.default.Geometry(p,1,function(){if(this.strokeIndices=[],i.toFixed(10)!==s.toFixed(10)){l!==h.PIE&&void 0!==l||(this.vertices.push(new T.default.Vector(.5,.5,0)),this.uvs.push([.5,.5]));for(var e=0;e<=p;e++){var t=(s-i)*(e/p)+i,r=.5+Math.cos(t)/2,n=.5+Math.sin(t)/2;this.vertices.push(new T.default.Vector(r,n,0)),this.uvs.push([r,n]),e>5&31)/31,(v>>10&31)/31):(r=i,n=s,l)}for(var b=new w.default.Vector(f,y,g),_=1;_<=3;_++){var x=m+12*_,S=new w.default.Vector(p.getFloat32(x,!0),p.getFloat32(4+x,!0),p.getFloat32(8+x,!0));e.vertices.push(S),e.vertexNormals.push(b),c&&o.push(r,n,a)}e.faces.push([3*h,3*h+1,3*h+2]),e.uvs.push([0,0],[0,0],[0,0])}}(e,t);else{var r=new DataView(t);if(!("TextDecoder"in window))return console.warn("Sorry, ASCII STL loading only works in browsers that support TextDecoder (https://caniuse.com/#feat=textencoder)");var n=new TextDecoder("utf-8").decode(r).split("\n");!function(e,t){for(var r,n,a="",o=[],i=0;iMath.PI?l=Math.PI:l<=0&&(l=.001);var p=Math.sin(l)*i*Math.sin(s),u=Math.cos(l)*i,c=Math.sin(l)*i*Math.cos(s);this.camera(p+this.centerX,u+this.centerY,c+this.centerZ,this.centerX,this.centerY,this.centerZ,0,1,0)},f.default.Camera.prototype._isActive=function(){return this===this._renderer._curCamera},f.default.prototype.setCamera=function(e){this._renderer._curCamera=e,this._renderer.uPMatrix.set(e.projMatrix.mat4[0],e.projMatrix.mat4[1],e.projMatrix.mat4[2],e.projMatrix.mat4[3],e.projMatrix.mat4[4],e.projMatrix.mat4[5],e.projMatrix.mat4[6],e.projMatrix.mat4[7],e.projMatrix.mat4[8],e.projMatrix.mat4[9],e.projMatrix.mat4[10],e.projMatrix.mat4[11],e.projMatrix.mat4[12],e.projMatrix.mat4[13],e.projMatrix.mat4[14],e.projMatrix.mat4[15])};var a=f.default.Camera;r.default=a},{"../core/main":32}],81:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n,u=(n=e("../core/main"))&&n.__esModule?n:{default:n};u.default.Geometry=function(e,t,r){return this.vertices=[],this.lineVertices=[],this.lineNormals=[],this.vertexNormals=[],this.faces=[],this.uvs=[],this.edges=[],this.vertexColors=[],this.detailX=void 0!==e?e:1,this.detailY=void 0!==t?t:1,this.dirtyFlags={},r instanceof Function&&r.call(this),this},u.default.Geometry.prototype.reset=function(){this.lineVertices.length=0,this.lineNormals.length=0,this.vertices.length=0,this.edges.length=0,this.vertexColors.length=0,this.vertexNormals.length=0,this.uvs.length=0,this.dirtyFlags={}},u.default.Geometry.prototype.computeFaces=function(){this.faces.length=0;for(var e,t,r,n,a=this.detailX+1,o=0;othis.vertices.length-1-this.detailX;n--)e.add(this.vertexNormals[n]);e=u.default.Vector.div(e,this.detailX);for(var a=this.vertices.length-1;a>this.vertices.length-1-this.detailX;a--)this.vertexNormals[a]=e;return this},u.default.Geometry.prototype._makeTriangleEdges=function(){if(this.edges.length=0,Array.isArray(this.strokeIndices))for(var e=0,t=this.strokeIndices.length;e vTexCoord.y;\n bool y1 = p1.y > vTexCoord.y;\n bool y2 = p2.y > vTexCoord.y;\n\n // could web be under the curve (after t1)?\n if (y1 ? !y2 : y0) {\n // add the coverage for t1\n coverage.x += saturate(C1.x + 0.5);\n // calculate the anti-aliasing for t1\n weight.x = min(weight.x, abs(C1.x));\n }\n\n // are we outside the curve (after t2)?\n if (y1 ? !y0 : y2) {\n // subtract the coverage for t2\n coverage.x -= saturate(C2.x + 0.5);\n // calculate the anti-aliasing for t2\n weight.x = min(weight.x, abs(C2.x));\n }\n}\n\n// this is essentially the same as coverageX, but with the axes swapped\nvoid coverageY(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n bool x0 = p0.x > vTexCoord.x;\n bool x1 = p1.x > vTexCoord.x;\n bool x2 = p2.x > vTexCoord.x;\n\n if (x1 ? !x2 : x0) {\n coverage.y -= saturate(C1.y + 0.5);\n weight.y = min(weight.y, abs(C1.y));\n }\n\n if (x1 ? !x0 : x2) {\n coverage.y += saturate(C2.y + 0.5);\n weight.y = min(weight.y, abs(C2.y));\n }\n}\n\nvoid main() {\n\n // calculate the pixel scale based on screen-coordinates\n pixelScale = hardness / fwidth(vTexCoord);\n\n // which grid cell is this pixel in?\n ivec2 gridCoord = ifloor(vTexCoord * vec2(uGridSize));\n\n // intersect curves in this row\n {\n // the index into the row info bitmap\n int rowIndex = gridCoord.y + uGridOffset.y;\n // fetch the info texel\n vec4 rowInfo = getTexel(uSamplerRows, rowIndex, uGridImageSize);\n // unpack the rowInfo\n int rowStrokeIndex = getInt16(rowInfo.xy);\n int rowStrokeCount = getInt16(rowInfo.zw);\n\n for (int iRowStroke = INT(0); iRowStroke < N; iRowStroke++) {\n if (iRowStroke >= rowStrokeCount)\n break;\n\n // each stroke is made up of 3 points: the start and control point\n // and the start of the next curve.\n // fetch the indices of this pair of strokes:\n vec4 strokeIndices = getTexel(uSamplerRowStrokes, rowStrokeIndex++, uCellsImageSize);\n\n // unpack the stroke index\n int strokePos = getInt16(strokeIndices.xy);\n\n // fetch the two strokes\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n\n // calculate the coverage\n coverageX(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n // intersect curves in this column\n {\n int colIndex = gridCoord.x + uGridOffset.x;\n vec4 colInfo = getTexel(uSamplerCols, colIndex, uGridImageSize);\n int colStrokeIndex = getInt16(colInfo.xy);\n int colStrokeCount = getInt16(colInfo.zw);\n \n for (int iColStroke = INT(0); iColStroke < N; iColStroke++) {\n if (iColStroke >= colStrokeCount)\n break;\n\n vec4 strokeIndices = getTexel(uSamplerColStrokes, colStrokeIndex++, uCellsImageSize);\n\n int strokePos = getInt16(strokeIndices.xy);\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n coverageY(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n weight = saturate(1.0 - weight * 2.0);\n float distance = max(weight.x + weight.y, minDistance); // manhattan approx.\n float antialias = abs(dot(coverage, weight) / distance);\n float cover = min(abs(coverage.x), abs(coverage.y));\n gl_FragColor = uMaterialColor;\n gl_FragColor.a *= saturate(max(antialias, cover));\n}",lineVert:"/*\n Part of the Processing project - http://processing.org\n Copyright (c) 2012-15 The Processing Foundation\n Copyright (c) 2004-12 Ben Fry and Casey Reas\n Copyright (c) 2001-04 Massachusetts Institute of Technology\n This library is free software; you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation, version 2.1.\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n You should have received a copy of the GNU Lesser General\n Public License along with this library; if not, write to the\n Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n Boston, MA 02111-1307 USA\n*/\n\n#define PROCESSING_LINE_SHADER\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uStrokeWeight;\n\nuniform vec4 uViewport;\nuniform int uPerspective;\n\nattribute vec4 aPosition;\nattribute vec4 aDirection;\n \nvoid main() {\n // using a scale <1 moves the lines towards the camera\n // in order to prevent popping effects due to half of\n // the line disappearing behind the geometry faces.\n vec3 scale = vec3(0.9995);\n\n vec4 posp = uModelViewMatrix * aPosition;\n vec4 posq = uModelViewMatrix * (aPosition + vec4(aDirection.xyz, 0));\n\n // Moving vertices slightly toward the camera\n // to avoid depth-fighting with the fill triangles.\n // Discussed here:\n // http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=252848 \n posp.xyz = posp.xyz * scale;\n posq.xyz = posq.xyz * scale;\n\n vec4 p = uProjectionMatrix * posp;\n vec4 q = uProjectionMatrix * posq;\n\n // formula to convert from clip space (range -1..1) to screen space (range 0..[width or height])\n // screen_p = (p.xy/p.w + <1,1>) * 0.5 * uViewport.zw\n\n // prevent division by W by transforming the tangent formula (div by 0 causes\n // the line to disappear, see https://github.com/processing/processing/issues/5183)\n // t = screen_q - screen_p\n //\n // tangent is normalized and we don't care which aDirection it points to (+-)\n // t = +- normalize( screen_q - screen_p )\n // t = +- normalize( (q.xy/q.w+<1,1>)*0.5*uViewport.zw - (p.xy/p.w+<1,1>)*0.5*uViewport.zw )\n //\n // extract common factor, <1,1> - <1,1> cancels out\n // t = +- normalize( (q.xy/q.w - p.xy/p.w) * 0.5 * uViewport.zw )\n //\n // convert to common divisor\n // t = +- normalize( ((q.xy*p.w - p.xy*q.w) / (p.w*q.w)) * 0.5 * uViewport.zw )\n //\n // remove the common scalar divisor/factor, not needed due to normalize and +-\n // (keep uViewport - can't remove because it has different components for x and y\n // and corrects for aspect ratio, see https://github.com/processing/processing/issues/5181)\n // t = +- normalize( (q.xy*p.w - p.xy*q.w) * uViewport.zw )\n\n vec2 tangent = normalize((q.xy*p.w - p.xy*q.w) * uViewport.zw);\n\n // flip tangent to normal (it's already normalized)\n vec2 normal = vec2(-tangent.y, tangent.x);\n\n float thickness = aDirection.w * uStrokeWeight;\n vec2 offset = normal * thickness / 2.0;\n\n vec2 curPerspScale;\n\n if(uPerspective == 1) {\n // Perspective ---\n // convert from world to clip by multiplying with projection scaling factor\n // to get the right thickness (see https://github.com/processing/processing/issues/5182)\n // invert Y, projections in Processing invert Y\n curPerspScale = (uProjectionMatrix * vec4(1, -1, 0, 0)).xy;\n } else {\n // No Perspective ---\n // multiply by W (to cancel out division by W later in the pipeline) and\n // convert from screen to clip (derived from clip to screen above)\n curPerspScale = p.w / (0.5 * uViewport.zw);\n }\n\n gl_Position.xy = p.xy + offset.xy * curPerspScale;\n gl_Position.zw = p.zw;\n}\n",lineFrag:"precision mediump float;\nprecision mediump int;\n\nuniform vec4 uMaterialColor;\n\nvoid main() {\n gl_FragColor = uMaterialColor;\n}",pointVert:"attribute vec3 aPosition;\nuniform float uPointSize;\nvarying float vStrokeWeight;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nvoid main() {\n\tvec4 positionVec4 = vec4(aPosition, 1.0);\n\tgl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n\tgl_PointSize = uPointSize;\n\tvStrokeWeight = uPointSize;\n}",pointFrag:"precision mediump float;\nprecision mediump int;\nuniform vec4 uMaterialColor;\nvarying float vStrokeWeight;\n\nvoid main(){\n\tfloat mask = 0.0;\n\n\t// make a circular mask using the gl_PointCoord (goes from 0 - 1 on a point)\n // might be able to get a nicer edge on big strokeweights with smoothstep but slightly less performant\n\n\tmask = step(0.98, length(gl_PointCoord * 2.0 - 1.0));\n\n\t// if strokeWeight is 1 or less lets just draw a square\n\t// this prevents weird artifacting from carving circles when our points are really small\n\t// if strokeWeight is larger than 1, we just use it as is\n\n\tmask = mix(0.0, mask, clamp(floor(vStrokeWeight - 0.5),0.0,1.0));\n\n\t// throw away the borders of the mask\n // otherwise we get weird alpha blending issues\n\n\tif(mask > 0.98){\n discard;\n \t}\n\n \tgl_FragColor = vec4(uMaterialColor.rgb * (1.0 - mask), uMaterialColor.a) ;\n}"};p.default.RendererGL=function(e,t,r,n){return p.default.Renderer.call(this,e,t,r),this._setAttributeDefaults(t),this._initContext(),this.isP3D=!0,this.GL=this.drawingContext,this._pInst._setProperty("drawingContext",this.drawingContext),this._isErasing=!1,this._enableLighting=!1,this.ambientLightColors=[],this.specularColors=[1,1,1],this.directionalLightDirections=[],this.directionalLightDiffuseColors=[],this.directionalLightSpecularColors=[],this.pointLightPositions=[],this.pointLightDiffuseColors=[],this.pointLightSpecularColors=[],this.spotLightPositions=[],this.spotLightDirections=[],this.spotLightDiffuseColors=[],this.spotLightSpecularColors=[],this.spotLightAngle=[],this.spotLightConc=[],this.drawMode=o.FILL,this.curFillColor=this._cachedFillStyle=[1,1,1,1],this.curStrokeColor=this._cachedStrokeStyle=[0,0,0,1],this.curBlendMode=o.BLEND,this._cachedBlendMode=void 0,this.blendExt=this.GL.getExtension("EXT_blend_minmax"),this._isBlending=!1,this._useSpecularMaterial=!1,this._useEmissiveMaterial=!1,this._useNormalMaterial=!1,this._useShininess=1,this._tint=[255,255,255,255],this.constantAttenuation=1,this.linearAttenuation=0,this.quadraticAttenuation=0,this.uMVMatrix=new p.default.Matrix,this.uPMatrix=new p.default.Matrix,this.uNMatrix=new p.default.Matrix("mat3"),this._curCamera=new p.default.Camera(this),this._curCamera._computeCameraDefaultSettings(),this._curCamera._setDefaultCamera(),this._defaultLightShader=void 0,this._defaultImmediateModeShader=void 0,this._defaultNormalShader=void 0,this._defaultColorShader=void 0,this._defaultPointShader=void 0,this.userFillShader=void 0,this.userStrokeShader=void 0,this.userPointShader=void 0,this.retainedMode={geometry:{},buffers:{stroke:[new p.default.RenderBuffer(3,"lineVertices","lineVertexBuffer","aPosition",this,this._flatten),new p.default.RenderBuffer(4,"lineNormals","lineNormalBuffer","aDirection",this,this._flatten)],fill:[new p.default.RenderBuffer(3,"vertices","vertexBuffer","aPosition",this,this._vToNArray),new p.default.RenderBuffer(3,"vertexNormals","normalBuffer","aNormal",this,this._vToNArray),new p.default.RenderBuffer(4,"vertexColors","colorBuffer","aMaterialColor",this),new p.default.RenderBuffer(3,"vertexAmbients","ambientBuffer","aAmbientColor",this),new p.default.RenderBuffer(2,"uvs","uvBuffer","aTexCoord",this,this._flatten)],text:[new p.default.RenderBuffer(3,"vertices","vertexBuffer","aPosition",this,this._vToNArray),new p.default.RenderBuffer(2,"uvs","uvBuffer","aTexCoord",this,this._flatten)]}},this.immediateMode={geometry:new p.default.Geometry,shapeMode:o.TRIANGLE_FAN,_bezierVertex:[],_quadraticVertex:[],_curveVertex:[],buffers:{fill:[new p.default.RenderBuffer(3,"vertices","vertexBuffer","aPosition",this,this._vToNArray),new p.default.RenderBuffer(3,"vertexNormals","normalBuffer","aNormal",this,this._vToNArray),new p.default.RenderBuffer(4,"vertexColors","colorBuffer","aVertexColor",this),new p.default.RenderBuffer(3,"vertexAmbients","ambientBuffer","aAmbientColor",this),new p.default.RenderBuffer(2,"uvs","uvBuffer","aTexCoord",this,this._flatten)],stroke:[new p.default.RenderBuffer(3,"lineVertices","lineVertexBuffer","aPosition",this,this._flatten),new p.default.RenderBuffer(4,"lineNormals","lineNormalBuffer","aDirection",this,this._flatten)],point:this.GL.createBuffer()}},this.pointSize=5,this.curStrokeWeight=1,this.textures=[],this.textureMode=o.IMAGE,this.textureWrapX=o.CLAMP,this.textureWrapY=o.CLAMP,this._tex=null,this._curveTightness=6,this._lookUpTableBezier=[],this._lookUpTableQuadratic=[],this._lutBezierDetail=0,this._lutQuadraticDetail=0,this._tessy=this._initTessy(),this.fontInfos={},this._curShader=void 0,this},p.default.RendererGL.prototype=Object.create(p.default.Renderer.prototype),p.default.RendererGL.prototype._setAttributeDefaults=function(e){var t={alpha:!0,depth:!0,stencil:!0,antialias:navigator.userAgent.toLowerCase().includes("safari"),premultipliedAlpha:!1,preserveDrawingBuffer:!0,perPixelLighting:!0};null===e._glAttributes?e._glAttributes=t:e._glAttributes=Object.assign(t,e._glAttributes)},p.default.RendererGL.prototype._initContext=function(){try{if(this.drawingContext=this.canvas.getContext("webgl",this._pInst._glAttributes)||this.canvas.getContext("experimental-webgl",this._pInst._glAttributes),null===this.drawingContext)throw new Error("Error creating webgl context");var e=this.drawingContext;e.enable(e.DEPTH_TEST),e.depthFunc(e.LEQUAL),e.viewport(0,0,e.drawingBufferWidth,e.drawingBufferHeight),this._viewport=this.drawingContext.getParameter(this.drawingContext.VIEWPORT)}catch(e){throw e}},p.default.RendererGL.prototype._resetContext=function(e,t){var r=this.width,n=this.height,a=this.canvas.id,o=this._pInst instanceof p.default.Graphics;if(o){var i=this._pInst;i.canvas.parentNode.removeChild(i.canvas),i.canvas=document.createElement("canvas"),(i._pInst._userNode||document.body).appendChild(i.canvas),p.default.Element.call(i,i.canvas,i._pInst),i.width=r,i.height=n}else{var s=this.canvas;s&&s.parentNode.removeChild(s),(s=document.createElement("canvas")).id=a,this._pInst._userNode?this._pInst._userNode.appendChild(s):document.body.appendChild(s),this._pInst.canvas=s}var l=new p.default.RendererGL(this._pInst.canvas,this._pInst,!o);this._pInst._setProperty("_renderer",l),l.resize(r,n),l._applyDefaults(),o||this._pInst._elements.push(l),"function"==typeof t&&setTimeout(function(){t.apply(window._renderer,e)},0)},p.default.prototype.setAttributes=function(e,t){if(void 0!==this._glAttributes){var r=!0;if(void 0!==t?(null===this._glAttributes&&(this._glAttributes={}),this._glAttributes[e]!==t&&(this._glAttributes[e]=t,r=!1)):e instanceof Object&&this._glAttributes!==e&&(this._glAttributes=e,r=!1),this._renderer.isP3D&&!r){if(!this._setupDone)for(var n in this._renderer.retainedMode.geometry)if(this._renderer.retainedMode.geometry.hasOwnProperty(n))return void console.error("Sorry, Could not set the attributes, you need to call setAttributes() before calling the other drawing methods in setup()");this.push(),this._renderer._resetContext(),this.pop(),this._renderer._curCamera&&(this._renderer._curCamera._renderer=this._renderer)}}else console.log("You are trying to use setAttributes on a p5.Graphics object that does not use a WEBGL renderer.")},p.default.RendererGL.prototype._update=function(){this.uMVMatrix.set(this._curCamera.cameraMatrix.mat4[0],this._curCamera.cameraMatrix.mat4[1],this._curCamera.cameraMatrix.mat4[2],this._curCamera.cameraMatrix.mat4[3],this._curCamera.cameraMatrix.mat4[4],this._curCamera.cameraMatrix.mat4[5],this._curCamera.cameraMatrix.mat4[6],this._curCamera.cameraMatrix.mat4[7],this._curCamera.cameraMatrix.mat4[8],this._curCamera.cameraMatrix.mat4[9],this._curCamera.cameraMatrix.mat4[10],this._curCamera.cameraMatrix.mat4[11],this._curCamera.cameraMatrix.mat4[12],this._curCamera.cameraMatrix.mat4[13],this._curCamera.cameraMatrix.mat4[14],this._curCamera.cameraMatrix.mat4[15]),this.ambientLightColors.length=0,this.specularColors=[1,1,1],this.directionalLightDirections.length=0,this.directionalLightDiffuseColors.length=0,this.directionalLightSpecularColors.length=0,this.pointLightPositions.length=0,this.pointLightDiffuseColors.length=0,this.pointLightSpecularColors.length=0,this.spotLightPositions.length=0,this.spotLightDirections.length=0,this.spotLightDiffuseColors.length=0,this.spotLightSpecularColors.length=0,this.spotLightAngle.length=0,this.spotLightConc.length=0,this._enableLighting=!1,this._tint=[255,255,255,255],this.GL.clear(this.GL.DEPTH_BUFFER_BIT)},p.default.RendererGL.prototype.background=function(){var e,t=(e=this._pInst).color.apply(e,arguments),r=t.levels[0]/255,n=t.levels[1]/255,a=t.levels[2]/255,o=t.levels[3]/255;this.GL.clearColor(r,n,a,o),this.GL.clear(this.GL.COLOR_BUFFER_BIT)},p.default.RendererGL.prototype.fill=function(e,t,r,n){var a=p.default.prototype.color.apply(this._pInst,arguments);this.curFillColor=a._array,this.drawMode=o.FILL,this._useNormalMaterial=!1,this._tex=null},p.default.RendererGL.prototype.stroke=function(e,t,r,n){arguments[3]=255;var a=p.default.prototype.color.apply(this._pInst,arguments);this.curStrokeColor=a._array},p.default.RendererGL.prototype.strokeCap=function(e){console.error("Sorry, strokeCap() is not yet implemented in WEBGL mode")},p.default.RendererGL.prototype.strokeJoin=function(e){console.error("Sorry, strokeJoin() is not yet implemented in WEBGL mode")},p.default.RendererGL.prototype.filter=function(e){console.error("filter() does not work in WEBGL mode")},p.default.RendererGL.prototype.blendMode=function(e){e===o.DARKEST||e===o.LIGHTEST||e===o.ADD||e===o.BLEND||e===o.SUBTRACT||e===o.SCREEN||e===o.EXCLUSION||e===o.REPLACE||e===o.MULTIPLY||e===o.REMOVE?this.curBlendMode=e:e!==o.BURN&&e!==o.OVERLAY&&e!==o.HARD_LIGHT&&e!==o.SOFT_LIGHT&&e!==o.DODGE||console.warn("BURN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, and DODGE only work for blendMode in 2D mode.")},p.default.RendererGL.prototype.erase=function(e,t){this._isErasing||(this._applyBlendMode(o.REMOVE),this._isErasing=!0,this._cachedFillStyle=this.curFillColor.slice(),this.curFillColor=[1,1,1,e/255],this._cachedStrokeStyle=this.curStrokeColor.slice(),this.curStrokeColor=[1,1,1,t/255])},p.default.RendererGL.prototype.noErase=function(){this._isErasing&&(this._isErasing=!1,this.curFillColor=this._cachedFillStyle.slice(),this.curStrokeColor=this._cachedStrokeStyle.slice(),this.blendMode(this._cachedBlendMode))},p.default.RendererGL.prototype.strokeWeight=function(e){this.curStrokeWeight!==e&&(this.pointSize=e,this.curStrokeWeight=e)},p.default.RendererGL.prototype._getPixel=function(e,t){var r;return r=new Uint8Array(4),this.drawingContext.readPixels(e,t,1,1,this.drawingContext.RGBA,this.drawingContext.UNSIGNED_BYTE,r),[r[0],r[1],r[2],r[3]]},p.default.RendererGL.prototype.loadPixels=function(){var e=this._pixelsState;if(!0===this._pInst._glAttributes.preserveDrawingBuffer){var t=e.pixels,r=this.GL.drawingBufferWidth*this.GL.drawingBufferHeight*4;t instanceof Uint8Array&&t.length===r||(t=new Uint8Array(r),this._pixelsState._setProperty("pixels",t));var n=this._pInst._pixelDensity;this.GL.readPixels(0,0,this.width*n,this.height*n,this.GL.RGBA,this.GL.UNSIGNED_BYTE,t)}else console.log("loadPixels only works in WebGL when preserveDrawingBuffer is true.")},p.default.RendererGL.prototype.geometryInHash=function(e){return void 0!==this.retainedMode.geometry[e]},p.default.RendererGL.prototype.resize=function(e,t){p.default.Renderer.prototype.resize.call(this,e,t),this.GL.viewport(0,0,this.GL.drawingBufferWidth,this.GL.drawingBufferHeight),this._viewport=this.GL.getParameter(this.GL.VIEWPORT),this._curCamera._resize();var r=this._pixelsState;void 0!==r.pixels&&r._setProperty("pixels",new Uint8Array(this.GL.drawingBufferWidth*this.GL.drawingBufferHeight*4))},p.default.RendererGL.prototype.clear=function(){var e=(arguments.length<=0?void 0:arguments[0])||0,t=(arguments.length<=1?void 0:arguments[1])||0,r=(arguments.length<=2?void 0:arguments[2])||0,n=(arguments.length<=3?void 0:arguments[3])||0;this.GL.clearColor(e,t,r,n),this.GL.clear(this.GL.COLOR_BUFFER_BIT|this.GL.DEPTH_BUFFER_BIT)},p.default.RendererGL.prototype.applyMatrix=function(e,t,r,n,a,o){16===arguments.length?p.default.Matrix.prototype.apply.apply(this.uMVMatrix,arguments):this.uMVMatrix.apply([e,t,0,0,r,n,0,0,0,0,1,0,a,o,0,1])},p.default.RendererGL.prototype.translate=function(e,t,r){return e instanceof p.default.Vector&&(r=e.z,t=e.y,e=e.x),this.uMVMatrix.translate([e,t,r]),this},p.default.RendererGL.prototype.scale=function(e,t,r){return this.uMVMatrix.scale(e,t,r),this},p.default.RendererGL.prototype.rotate=function(e,t){return void 0===t?this.rotateZ(e):(p.default.Matrix.prototype.rotate.apply(this.uMVMatrix,arguments),this)},p.default.RendererGL.prototype.rotateX=function(e){return this.rotate(e,1,0,0),this},p.default.RendererGL.prototype.rotateY=function(e){return this.rotate(e,0,1,0),this},p.default.RendererGL.prototype.rotateZ=function(e){return this.rotate(e,0,0,1),this},p.default.RendererGL.prototype.push=function(){var e=p.default.Renderer.prototype.push.apply(this),t=e.properties;return t.uMVMatrix=this.uMVMatrix.copy(),t.uPMatrix=this.uPMatrix.copy(),t._curCamera=this._curCamera,this._curCamera=this._curCamera.copy(),t.ambientLightColors=this.ambientLightColors.slice(),t.specularColors=this.specularColors.slice(),t.directionalLightDirections=this.directionalLightDirections.slice(),t.directionalLightDiffuseColors=this.directionalLightDiffuseColors.slice(),t.directionalLightSpecularColors=this.directionalLightSpecularColors.slice(),t.pointLightPositions=this.pointLightPositions.slice(),t.pointLightDiffuseColors=this.pointLightDiffuseColors.slice(),t.pointLightSpecularColors=this.pointLightSpecularColors.slice(),t.spotLightPositions=this.spotLightPositions.slice(),t.spotLightDirections=this.spotLightDirections.slice(),t.spotLightDiffuseColors=this.spotLightDiffuseColors.slice(),t.spotLightSpecularColors=this.spotLightSpecularColors.slice(),t.spotLightAngle=this.spotLightAngle.slice(),t.spotLightConc=this.spotLightConc.slice(),t.userFillShader=this.userFillShader,t.userStrokeShader=this.userStrokeShader,t.userPointShader=this.userPointShader,t.pointSize=this.pointSize,t.curStrokeWeight=this.curStrokeWeight,t.curStrokeColor=this.curStrokeColor,t.curFillColor=this.curFillColor,t._useSpecularMaterial=this._useSpecularMaterial,t._useEmissiveMaterial=this._useEmissiveMaterial,t._useShininess=this._useShininess,t.constantAttenuation=this.constantAttenuation,t.linearAttenuation=this.linearAttenuation,t.quadraticAttenuation=this.quadraticAttenuation,t._enableLighting=this._enableLighting,t._useNormalMaterial=this._useNormalMaterial,t._tex=this._tex,t.drawMode=this.drawMode,e},p.default.RendererGL.prototype.resetMatrix=function(){return this.uMVMatrix=p.default.Matrix.identity(this._pInst),this},p.default.RendererGL.prototype._getImmediateStrokeShader=function(){var e=this.userStrokeShader;return e&&e.isStrokeShader()?e:this._getLineShader()},p.default.RendererGL.prototype._getRetainedStrokeShader=p.default.RendererGL.prototype._getImmediateStrokeShader,p.default.RendererGL.prototype._getImmediateFillShader=function(){var e=this.userFillShader;if(this._useNormalMaterial&&(!e||!e.isNormalShader()))return this._getNormalShader();if(this._enableLighting){if(!e||!e.isLightShader())return this._getLightShader()}else if(this._tex){if(!e||!e.isTextureShader())return this._getLightShader()}else if(!e)return this._getImmediateModeShader();return e},p.default.RendererGL.prototype._getRetainedFillShader=function(){if(this._useNormalMaterial)return this._getNormalShader();var e=this.userFillShader;if(this._enableLighting){if(!e||!e.isLightShader())return this._getLightShader()}else if(this._tex){if(!e||!e.isTextureShader())return this._getLightShader()}else if(!e)return this._getColorShader();return e},p.default.RendererGL.prototype._getImmediatePointShader=function(){var e=this.userPointShader;return e&&e.isPointShader()?e:this._getPointShader()},p.default.RendererGL.prototype._getRetainedLineShader=p.default.RendererGL.prototype._getImmediateLineShader,p.default.RendererGL.prototype._getLightShader=function(){return this._defaultLightShader||(this._pInst._glAttributes.perPixelLighting?this._defaultLightShader=new p.default.Shader(this,c.phongVert,c.phongFrag):this._defaultLightShader=new p.default.Shader(this,c.lightVert,c.lightTextureFrag)),this._defaultLightShader},p.default.RendererGL.prototype._getImmediateModeShader=function(){return this._defaultImmediateModeShader||(this._defaultImmediateModeShader=new p.default.Shader(this,c.immediateVert,c.vertexColorFrag)),this._defaultImmediateModeShader},p.default.RendererGL.prototype._getNormalShader=function(){return this._defaultNormalShader||(this._defaultNormalShader=new p.default.Shader(this,c.normalVert,c.normalFrag)),this._defaultNormalShader},p.default.RendererGL.prototype._getColorShader=function(){return this._defaultColorShader||(this._defaultColorShader=new p.default.Shader(this,c.normalVert,c.basicFrag)),this._defaultColorShader},p.default.RendererGL.prototype._getPointShader=function(){return this._defaultPointShader||(this._defaultPointShader=new p.default.Shader(this,c.pointVert,c.pointFrag)),this._defaultPointShader},p.default.RendererGL.prototype._getLineShader=function(){return this._defaultLineShader||(this._defaultLineShader=new p.default.Shader(this,c.lineVert,c.lineFrag)),this._defaultLineShader},p.default.RendererGL.prototype._getFontShader=function(){return this._defaultFontShader||(this.GL.getExtension("OES_standard_derivatives"),this._defaultFontShader=new p.default.Shader(this,c.fontVert,c.fontFrag)),this._defaultFontShader},p.default.RendererGL.prototype._getEmptyTexture=function(){if(!this._emptyTexture){var e=new p.default.Image(1,1);e.set(0,0,255),this._emptyTexture=new p.default.Texture(this,e)}return this._emptyTexture},p.default.RendererGL.prototype.getTexture=function(e){var t=this.textures,r=!0,n=!1,a=void 0;try{for(var o,i=t[Symbol.iterator]();!(r=(o=i.next()).done);r=!0){var s=o.value;if(s.src===e)return s}}catch(e){n=!0,a=e}finally{try{r||null==i.return||i.return()}finally{if(n)throw a}}var l=new p.default.Texture(this,e);return t.push(l),l},p.default.RendererGL.prototype._setStrokeUniforms=function(e){e.bindShader(),e.setUniform("uMaterialColor",this.curStrokeColor),e.setUniform("uStrokeWeight",this.curStrokeWeight)},p.default.RendererGL.prototype._setFillUniforms=function(e){e.bindShader(),e.setUniform("uMaterialColor",this.curFillColor),e.setUniform("isTexture",!!this._tex),this._tex&&e.setUniform("uSampler",this._tex),e.setUniform("uTint",this._tint),e.setUniform("uSpecular",this._useSpecularMaterial),e.setUniform("uEmissive",this._useEmissiveMaterial),e.setUniform("uShininess",this._useShininess),e.setUniform("uUseLighting",this._enableLighting);var t=this.pointLightDiffuseColors.length/3;e.setUniform("uPointLightCount",t),e.setUniform("uPointLightLocation",this.pointLightPositions),e.setUniform("uPointLightDiffuseColors",this.pointLightDiffuseColors),e.setUniform("uPointLightSpecularColors",this.pointLightSpecularColors);var r=this.directionalLightDiffuseColors.length/3;e.setUniform("uDirectionalLightCount",r),e.setUniform("uLightingDirection",this.directionalLightDirections),e.setUniform("uDirectionalDiffuseColors",this.directionalLightDiffuseColors),e.setUniform("uDirectionalSpecularColors",this.directionalLightSpecularColors);var n=this.ambientLightColors.length/3;e.setUniform("uAmbientLightCount",n),e.setUniform("uAmbientColor",this.ambientLightColors);var a=this.spotLightDiffuseColors.length/3;e.setUniform("uSpotLightCount",a),e.setUniform("uSpotLightAngle",this.spotLightAngle),e.setUniform("uSpotLightConc",this.spotLightConc),e.setUniform("uSpotLightDiffuseColors",this.spotLightDiffuseColors),e.setUniform("uSpotLightSpecularColors",this.spotLightSpecularColors),e.setUniform("uSpotLightLocation",this.spotLightPositions),e.setUniform("uSpotLightDirection",this.spotLightDirections),e.setUniform("uConstantAttenuation",this.constantAttenuation),e.setUniform("uLinearAttenuation",this.linearAttenuation),e.setUniform("uQuadraticAttenuation",this.quadraticAttenuation),e.bindTextures()},p.default.RendererGL.prototype._setPointUniforms=function(e){e.bindShader(),e.setUniform("uMaterialColor",this.curStrokeColor),e.setUniform("uPointSize",this.pointSize)},p.default.RendererGL.prototype._bindBuffer=function(e,t,r,n,a){if(t=t||this.GL.ARRAY_BUFFER,this.GL.bindBuffer(t,e),void 0!==r){var o=new(n||Float32Array)(r);this.GL.bufferData(t,o,a||this.GL.STATIC_DRAW)}},p.default.RendererGL.prototype._arraysEqual=function(e,t){var r=e.length;if(r!==t.length)return!1;for(var n=0;n>7,127&d,c>>7,127&c);for(var h=0;h>7,127&m,0,0)}}return{cellImageInfo:l,dimOffset:o,dimImageInfo:a}}return(t=this.glyphInfos[e.index]={glyph:e,uGlyphRect:[n.x1,-n.y1,n.x2,-n.y2],strokeImageInfo:k,strokes:h,colInfo:G(f,this.colDimImageInfos,this.colCellImageInfos),rowInfo:G(m,this.rowDimImageInfos,this.rowCellImageInfos)}).uGridOffset=[t.colInfo.dimOffset,t.rowInfo.dimOffset],t}}var z=Math.sqrt(3);j.default.RendererGL.prototype._renderText=function(e,t,r,n,a){if(this._textFont&&"string"!=typeof this._textFont){if(!(a<=n)&&this._doFill){if(!this._isOpenType())return console.log("WEBGL: only Opentype (.otf) and Truetype (.ttf) fonts are supported"),e;e.push();var o=this._doStroke,i=this.drawMode;this._doStroke=!1,this.drawMode=R.TEXTURE;var s=this._textFont.font,l=this._textFont._fontInfo;l=l||(this._textFont._fontInfo=new D(s));var p=this._textFont._handleAlignment(this,t,r,n),u=this._textSize/s.unitsPerEm;this.translate(p.x,p.y,0),this.scale(u,u,1);var c=this.GL,d=!this._defaultFontShader,h=this._getFontShader();h.init(),h.bindShader(),d&&(h.setUniform("uGridImageSize",[64,64]),h.setUniform("uCellsImageSize",[64,64]),h.setUniform("uStrokeImageSize",[64,64]),h.setUniform("uGridSize",[9,9])),this._applyColorBlend(this.curFillColor);var m=this.retainedMode.geometry.glyph;if(!m){var f=this._textGeom=new j.default.Geometry(1,1,function(){for(var e=0;e<=1;e++)for(var t=0;t<=1;t++)this.vertices.push(new j.default.Vector(t,e,0)),this.uvs.push(t,e)});f.computeFaces().computeNormals(),m=this.createBuffers("glyph",f)}var y=!0,g=!1,v=void 0;try{for(var b,_=this.retainedMode.buffers.text[Symbol.iterator]();!(y=(b=_.next()).done);y=!0){b.value._prepareBuffer(m,h)}}catch(e){g=!0,v=e}finally{try{y||null==_.return||_.return()}finally{if(g)throw v}}this._bindBuffer(m.indexBuffer,c.ELEMENT_ARRAY_BUFFER),h.setUniform("uMaterialColor",this.curFillColor);try{var x=0,S=null,w=s.stringToGlyphs(t),M=!0,E=!1,T=void 0;try{for(var C,N=w[Symbol.iterator]();!(M=(C=N.next()).done);M=!0){var O=C.value;S&&(x+=s.getKerningValue(S,O));var L=l.getGlyphInfo(O);if(L.uGlyphRect){var I=L.rowInfo,P=L.colInfo;h.setUniform("uSamplerStrokes",L.strokeImageInfo.imageData),h.setUniform("uSamplerRowStrokes",I.cellImageInfo.imageData),h.setUniform("uSamplerRows",I.dimImageInfo.imageData),h.setUniform("uSamplerColStrokes",P.cellImageInfo.imageData),h.setUniform("uSamplerCols",P.dimImageInfo.imageData),h.setUniform("uGridOffset",L.uGridOffset),h.setUniform("uGlyphRect",L.uGlyphRect),h.setUniform("uGlyphOffset",x),h.bindTextures(),c.drawElements(c.TRIANGLES,6,this.GL.UNSIGNED_SHORT,0)}x+=O.advanceWidth,S=O}}catch(e){E=!0,T=e}finally{try{M||null==N.return||N.return()}finally{if(E)throw T}}}finally{h.unbindShader(),this._doStroke=o,this.drawMode=i,e.pop()}return e}}else console.log("WEBGL: you must load and set a font before drawing text. See `loadFont` and `textFont` for more details.")}},{"../core/constants":22,"../core/main":32,"./p5.RendererGL.Retained":85,"./p5.Shader":87}]},{},[17])(17)}); \ No newline at end of file diff --git a/js/p5.min.js b/js/p5.min.js new file mode 100644 index 0000000..d14c00d --- /dev/null +++ b/js/p5.min.js @@ -0,0 +1,2 @@ +/*! p5.js v1.10.0 July 31, 2024 */ +!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).p5=e()}(function(){var s,t,r;return function o(n,s,i){function a(t,e){if(!s[t]){if(!n[t]){var r="function"==typeof require&&require;if(!e&&r)return r(t,!0);if(l)return l(t,!0);throw(e=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",e}r=s[t]={exports:{}},n[t][0].call(r.exports,function(e){return a(n[t][1][e]||e)},r,r.exports,o,n,s,i)}return s[t].exports}for(var l="function"==typeof require&&require,e=0;e>16&255,s[i++]=t>>8&255,s[i++]=255&t;2===o&&(t=l[e.charCodeAt(r)]<<2|l[e.charCodeAt(r+1)]>>4,s[i++]=255&t);1===o&&(t=l[e.charCodeAt(r)]<<10|l[e.charCodeAt(r+1)]<<4|l[e.charCodeAt(r+2)]>>2,s[i++]=t>>8&255,s[i++]=255&t);return s},r.fromByteArray=function(e){for(var t,r=e.length,o=r%3,n=[],s=0,i=r-o;s>18&63]+a[e>>12&63]+a[e>>6&63]+a[63&e]}(o));return n.join("")}(e,s,i>2]+a[t<<4&63]+"==")):2==o&&(t=(e[r-2]<<8)+e[r-1],n.push(a[t>>10]+a[t>>4&63]+a[t<<2&63]+"="));return n.join("")};for(var a=[],l=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=0,s=o.length;n>>1;case"base64":return M(e).length;default:if(n)return o?-1:E(e).length;t=(""+t).toLowerCase(),n=!0}}function r(e,t,r){var o,n=!1;if((t=void 0===t||t<0?0:t)>this.length)return"";if((r=void 0===r||r>this.length?this.length:r)<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e=e||"utf8";;)switch(e){case"hex":var s=this,i=t,a=r,l=s.length;(!a||a<0||l=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=d.from(t,o)),d.isBuffer(t))return 0===t.length?-1:p(e,t,r,o,n);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?(n?Uint8Array.prototype.indexOf:Uint8Array.prototype.lastIndexOf).call(e,t,r):p(e,[t],r,o,n);throw new TypeError("val must be string, number or Buffer")}function p(e,t,r,o,n){var s=1,i=e.length,a=t.length;if(void 0!==o&&("ucs2"===(o=String(o).toLowerCase())||"ucs-2"===o||"utf16le"===o||"utf-16le"===o)){if(e.length<2||t.length<2)return-1;i/=s=2,a/=2,r/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(n)for(var u=-1,c=r;c>8,o=o%256,n.push(o),n.push(r);return n}(t,e.length-r),e,r,o)}function T(e,t,r){r=Math.min(e.length,r);for(var o=[],n=t;n>>10&1023|55296),c=56320|1023&c),o.push(c),n+=d}var h=o,f=h.length;if(f<=v)return String.fromCharCode.apply(String,h);for(var p="",m=0;mt&&(e+=" ... "),""},e&&(d.prototype[e]=d.prototype.inspect),d.prototype.compare=function(e,t,r,o,n){if(O(e,Uint8Array)&&(e=d.from(e,e.offset,e.byteLength)),!d.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===r&&(r=e?e.length:0),void 0===o&&(o=0),void 0===n&&(n=this.length),(t=void 0===t?0:t)<0||r>e.length||o<0||n>this.length)throw new RangeError("out of range index");if(n<=o&&r<=t)return 0;if(n<=o)return-1;if(r<=t)return 1;if(this===e)return 0;for(var s=(n>>>=0)-(o>>>=0),i=(r>>>=0)-(t>>>=0),a=Math.min(s,i),l=this.slice(o,n),u=e.slice(t,r),c=0;c>>=0,isFinite(r)?(r>>>=0,void 0===o&&(o="utf8")):(o=r,r=void 0)}var n=this.length-t;if((void 0===r||nthis.length)throw new RangeError("Attempt to write outside buffer bounds");o=o||"utf8";for(var s,i,a,l=!1;;)switch(o){case"hex":var u=this,c=e,d=t,h=r,f=(d=Number(d)||0,u.length-d);(!h||f<(h=Number(h)))&&(h=f),(f=c.length)/2e.length)throw new RangeError("Index out of range")}function j(e,t,r,o){if(r+o>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function _(e,t,r,o,n){return t=+t,r>>>=0,n||j(e,0,r,4),s.write(e,t,r,o,23,4),r+4}function x(e,t,r,o,n){return t=+t,r>>>=0,n||j(e,0,r,8),s.write(e,t,r,o,52,8),r+8}d.prototype.slice=function(e,t){var r=this.length,r=((e=~~e)<0?(e+=r)<0&&(e=0):r>>=0,t>>>=0,r||m(e,t,this.length);for(var o=this[e],n=1,s=0;++s>>=0,t>>>=0,r||m(e,t,this.length);for(var o=this[e+--t],n=1;0>>=0,t||m(e,1,this.length),this[e]},d.prototype.readUInt16LE=function(e,t){return e>>>=0,t||m(e,2,this.length),this[e]|this[e+1]<<8},d.prototype.readUInt16BE=function(e,t){return e>>>=0,t||m(e,2,this.length),this[e]<<8|this[e+1]},d.prototype.readUInt32LE=function(e,t){return e>>>=0,t||m(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},d.prototype.readUInt32BE=function(e,t){return e>>>=0,t||m(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},d.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||m(e,t,this.length);for(var o=this[e],n=1,s=0;++s>>=0,t>>>=0,r||m(e,t,this.length);for(var o=t,n=1,s=this[e+--o];0>>=0,t||m(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},d.prototype.readInt16LE=function(e,t){e>>>=0,t||m(e,2,this.length);t=this[e]|this[e+1]<<8;return 32768&t?4294901760|t:t},d.prototype.readInt16BE=function(e,t){e>>>=0,t||m(e,2,this.length);t=this[e+1]|this[e]<<8;return 32768&t?4294901760|t:t},d.prototype.readInt32LE=function(e,t){return e>>>=0,t||m(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},d.prototype.readInt32BE=function(e,t){return e>>>=0,t||m(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},d.prototype.readFloatLE=function(e,t){return e>>>=0,t||m(e,4,this.length),s.read(this,e,!0,23,4)},d.prototype.readFloatBE=function(e,t){return e>>>=0,t||m(e,4,this.length),s.read(this,e,!1,23,4)},d.prototype.readDoubleLE=function(e,t){return e>>>=0,t||m(e,8,this.length),s.read(this,e,!0,52,8)},d.prototype.readDoubleBE=function(e,t){return e>>>=0,t||m(e,8,this.length),s.read(this,e,!1,52,8)},d.prototype.writeUIntLE=function(e,t,r,o){e=+e,t>>>=0,r>>>=0,o||b(this,e,t,r,Math.pow(2,8*r)-1,0);var n=1,s=0;for(this[t]=255&e;++s>>=0,r>>>=0,o||b(this,e,t,r,Math.pow(2,8*r)-1,0);var n=r-1,s=1;for(this[t+n]=255&e;0<=--n&&(s*=256);)this[t+n]=e/s&255;return t+r},d.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,1,255,0),this[t]=255&e,t+1},d.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},d.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},d.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},d.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},d.prototype.writeIntLE=function(e,t,r,o){e=+e,t>>>=0,o||b(this,e,t,r,(o=Math.pow(2,8*r-1))-1,-o);var n=0,s=1,i=0;for(this[t]=255&e;++n>0)-i&255;return t+r},d.prototype.writeIntBE=function(e,t,r,o){e=+e,t>>>=0,o||b(this,e,t,r,(o=Math.pow(2,8*r-1))-1,-o);var n=r-1,s=1,i=0;for(this[t+n]=255&e;0<=--n&&(s*=256);)e<0&&0===i&&0!==this[t+n+1]&&(i=1),this[t+n]=(e/s>>0)-i&255;return t+r},d.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,1,127,-128),this[t]=255&(e=e<0?255+e+1:e),t+1},d.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},d.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},d.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},d.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||b(this,e,t,4,2147483647,-2147483648),this[t]=(e=e<0?4294967295+e+1:e)>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},d.prototype.writeFloatLE=function(e,t,r){return _(this,e,t,!0,r)},d.prototype.writeFloatBE=function(e,t,r){return _(this,e,t,!1,r)},d.prototype.writeDoubleLE=function(e,t,r){return x(this,e,t,!0,r)},d.prototype.writeDoubleBE=function(e,t,r){return x(this,e,t,!1,r)},d.prototype.copy=function(e,t,r,o){if(!d.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r=r||0,o||0===o||(o=this.length),t>=e.length&&(t=e.length),(o=0=this.length)throw new RangeError("Index out of range");if(o<0)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length);var n=(o=e.length-t>>=0,r=void 0===r?this.length:r>>>0,"number"==typeof(e=e||0))for(s=t;s>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function M(e){return S.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(w,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function k(e,t,r,o){for(var n=0;n=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function O(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function C(e){return e!=e}var A=function(){for(var e="0123456789abcdef",t=new Array(256),r=0;r<16;++r)for(var o=16*r,n=0;n<16;++n)t[o+n]=e[r]+e[n];return t}()}.call(this,P("buffer").Buffer)},{"base64-js":1,buffer:4,ieee754:254}],5:[function(e,t,r){t.exports=function(e){if("function"!=typeof e)throw TypeError(String(e)+" is not a function");return e}},{}],6:[function(e,t,r){var o=e("../internals/is-object");t.exports=function(e){if(o(e)||null===e)return e;throw TypeError("Can't set "+String(e)+" as a prototype")}},{"../internals/is-object":75}],7:[function(e,t,r){var o=e("../internals/well-known-symbol"),n=e("../internals/object-create"),e=e("../internals/object-define-property"),s=o("unscopables"),i=Array.prototype;null==i[s]&&e.f(i,s,{configurable:!0,value:n(null)}),t.exports=function(e){i[s][e]=!0}},{"../internals/object-create":91,"../internals/object-define-property":93,"../internals/well-known-symbol":150}],8:[function(e,t,r){"use strict";var o=e("../internals/string-multibyte").charAt;t.exports=function(e,t,r){return t+(r?o(e,t).length:1)}},{"../internals/string-multibyte":125}],9:[function(e,t,r){t.exports=function(e,t,r){if(e instanceof t)return e;throw TypeError("Incorrect "+(r?r+" ":"")+"invocation")}},{}],10:[function(e,t,r){var o=e("../internals/is-object");t.exports=function(e){if(o(e))return e;throw TypeError(String(e)+" is not an object")}},{"../internals/is-object":75}],11:[function(e,t,r){t.exports="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView},{}],12:[function(e,t,r){"use strict";function o(e){return l(e)&&u(E,c(e))}var n,s=e("../internals/array-buffer-native"),i=e("../internals/descriptors"),a=e("../internals/global"),l=e("../internals/is-object"),u=e("../internals/has"),c=e("../internals/classof"),d=e("../internals/create-non-enumerable-property"),h=e("../internals/redefine"),f=e("../internals/object-define-property").f,p=e("../internals/object-get-prototype-of"),m=e("../internals/object-set-prototype-of"),y=e("../internals/well-known-symbol"),e=e("../internals/uid"),g=a.Int8Array,v=g&&g.prototype,b=a.Uint8ClampedArray,b=b&&b.prototype,j=g&&p(g),_=v&&p(v),x=Object.prototype,w=x.isPrototypeOf,y=y("toStringTag"),S=e("TYPED_ARRAY_TAG"),T=s&&!!m&&"Opera"!==c(a.opera),e=!1,E={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8};for(n in E)a[n]||(T=!1);if((!T||"function"!=typeof j||j===Function.prototype)&&(j=function(){throw TypeError("Incorrect invocation")},T))for(n in E)a[n]&&m(a[n],j);if((!T||!_||_===x)&&(_=j.prototype,T))for(n in E)a[n]&&m(a[n].prototype,_);if(T&&p(b)!==_&&m(b,_),i&&!u(_,y))for(n in e=!0,f(_,y,{get:function(){return l(this)?this[S]:void 0}}),E)a[n]&&d(a[n],S,n);t.exports={NATIVE_ARRAY_BUFFER_VIEWS:T,TYPED_ARRAY_TAG:e&&S,aTypedArray:function(e){if(o(e))return e;throw TypeError("Target is not a typed array")},aTypedArrayConstructor:function(e){if(m){if(w.call(j,e))return e}else for(var t in E)if(u(E,n)){t=a[t];if(t&&(e===t||w.call(t,e)))return e}throw TypeError("Target is not a typed array constructor")},exportTypedArrayMethod:function(e,t,r){if(i){if(r)for(var o in E){o=a[o];o&&u(o.prototype,e)&&delete o.prototype[e]}_[e]&&!r||h(_,e,!r&&T&&v[e]||t)}},exportTypedArrayStaticMethod:function(e,t,r){var o,n;if(i){if(m){if(r)for(o in E)(n=a[o])&&u(n,e)&&delete n[e];if(j[e]&&!r)return;try{return h(j,e,!r&&T&&g[e]||t)}catch(e){}}for(o in E)!(n=a[o])||n[e]&&!r||h(n,e,t)}},isView:function(e){e=c(e);return"DataView"===e||u(E,e)},isTypedArray:o,TypedArray:j,TypedArrayPrototype:_}},{"../internals/array-buffer-native":11,"../internals/classof":29,"../internals/create-non-enumerable-property":38,"../internals/descriptors":43,"../internals/global":60,"../internals/has":61,"../internals/is-object":75,"../internals/object-define-property":93,"../internals/object-get-prototype-of":98,"../internals/object-set-prototype-of":102,"../internals/redefine":110,"../internals/uid":147,"../internals/well-known-symbol":150}],13:[function(e,t,D){"use strict";function r(e){return[255&e]}function o(e){return[255&e,e>>8&255]}function n(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]}function s(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]}function i(e){return C(e,23,4)}function F(e){return C(e,52,8)}function a(e,t){H(e[w],t,{get:function(){return b(this)[t]}})}function l(e,t,r,o){if(r=m(r),e=b(e),r+t>e.byteLength)throw O(S);var n=b(e.buffer).bytes,r=r+e.byteOffset,e=n.slice(r,r+t);return o?e:e.reverse()}function u(e,t,r,o,n,s){if(r=m(r),e=b(e),r+t>e.byteLength)throw O(S);for(var i=b(e.buffer).bytes,a=r+e.byteOffset,l=o(+n),u=0;uR;)(P=L[R++])in E||N(E,P,T[P]);c.constructor=E}g&&V(e)!==k&&g(e,k);var y=new M(new E(2)),I=e.setInt8;y.setInt8(0,2147483648),y.setInt8(1,2147483649),!y.getInt8(0)&&y.getInt8(1)||h(e,{setInt8:function(e,t){I.call(this,e,t<<24>>24)},setUint8:function(e,t){I.call(this,e,t<<24>>24)}},{unsafe:!0})}else E=function(e){p(this,E,_);e=m(e);j(this,{bytes:W.call(new Array(e),0),byteLength:e}),d||(this.byteLength=e)},M=function(e,t,r){p(this,M,x),p(e,E,x);var o=b(e).byteLength,t=B(t);if(t<0||o>24},getUint8:function(e){return l(this,1,e)[0]},getInt16:function(e){e=l(this,2,e,1>16},getUint16:function(e){e=l(this,2,e,1>>0},getFloat32:function(e){return A(l(this,4,e,1"+e+""}},{"../internals/require-object-coercible":115}],37:[function(e,t,r){"use strict";function o(){return this}var n=e("../internals/iterators-core").IteratorPrototype,s=e("../internals/object-create"),i=e("../internals/create-property-descriptor"),a=e("../internals/set-to-string-tag"),l=e("../internals/iterators");t.exports=function(e,t,r){t+=" Iterator";return e.prototype=s(n,{next:i(1,r)}),a(e,t,!1,!0),l[t]=o,e}},{"../internals/create-property-descriptor":39,"../internals/iterators":80,"../internals/iterators-core":79,"../internals/object-create":91,"../internals/set-to-string-tag":119}],38:[function(e,t,r){var o=e("../internals/descriptors"),n=e("../internals/object-define-property"),s=e("../internals/create-property-descriptor");t.exports=o?function(e,t,r){return n.f(e,t,s(1,r))}:function(e,t,r){return e[t]=r,e}},{"../internals/create-property-descriptor":39,"../internals/descriptors":43,"../internals/object-define-property":93}],39:[function(e,t,r){t.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},{}],40:[function(e,t,r){"use strict";var o=e("../internals/to-primitive"),n=e("../internals/object-define-property"),s=e("../internals/create-property-descriptor");t.exports=function(e,t,r){t=o(t);t in e?n.f(e,t,s(0,r)):e[t]=r}},{"../internals/create-property-descriptor":39,"../internals/object-define-property":93,"../internals/to-primitive":142}],41:[function(e,t,r){"use strict";function m(){return this}var y=e("../internals/export"),g=e("../internals/create-iterator-constructor"),v=e("../internals/object-get-prototype-of"),b=e("../internals/object-set-prototype-of"),j=e("../internals/set-to-string-tag"),_=e("../internals/create-non-enumerable-property"),x=e("../internals/redefine"),o=e("../internals/well-known-symbol"),w=e("../internals/is-pure"),S=e("../internals/iterators"),e=e("../internals/iterators-core"),T=e.IteratorPrototype,E=e.BUGGY_SAFARI_ITERATORS,M=o("iterator"),k="values",O="entries";t.exports=function(e,t,r,o,n,s,i){g(r,t,o);function a(e){if(e===n&&f)return f;if(!E&&e in d)return d[e];switch(e){case"keys":case k:case O:return function(){return new r(this,e)}}return function(){return new r(this)}}var l,u,o=t+" Iterator",c=!1,d=e.prototype,h=d[M]||d["@@iterator"]||n&&d[n],f=!E&&h||a(n),p="Array"==t&&d.entries||h;if(p&&(p=v(p.call(new e)),T!==Object.prototype&&p.next&&(w||v(p)===T||(b?b(p,T):"function"!=typeof p[M]&&_(p,M,m)),j(p,o,!0,!0),w&&(S[o]=m))),n==k&&h&&h.name!==k&&(c=!0,f=function(){return h.call(this)}),w&&!i||d[M]===f||_(d,M,f),S[t]=f,n)if(l={values:a(k),keys:s?f:a("keys"),entries:a(O)},i)for(u in l)!E&&!c&&u in d||x(d,u,l[u]);else y({target:t,proto:!0,forced:E||c},l);return l}},{"../internals/create-iterator-constructor":37,"../internals/create-non-enumerable-property":38,"../internals/export":50,"../internals/is-pure":76,"../internals/iterators":80,"../internals/iterators-core":79,"../internals/object-get-prototype-of":98,"../internals/object-set-prototype-of":102,"../internals/redefine":110,"../internals/set-to-string-tag":119,"../internals/well-known-symbol":150}],42:[function(e,t,r){var o=e("../internals/path"),n=e("../internals/has"),s=e("../internals/well-known-symbol-wrapped"),i=e("../internals/object-define-property").f;t.exports=function(e){var t=o.Symbol||(o.Symbol={});n(t,e)||i(t,e,{value:s.f(e)})}},{"../internals/has":61,"../internals/object-define-property":93,"../internals/path":106,"../internals/well-known-symbol-wrapped":149}],43:[function(e,t,r){e=e("../internals/fails");t.exports=!e(function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})},{"../internals/fails":51}],44:[function(e,t,r){var o=e("../internals/global"),e=e("../internals/is-object"),n=o.document,s=e(n)&&e(n.createElement);t.exports=function(e){return s?n.createElement(e):{}}},{"../internals/global":60,"../internals/is-object":75}],45:[function(e,t,r){t.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},{}],46:[function(e,t,r){e=e("../internals/engine-user-agent");t.exports=/(iphone|ipod|ipad).*applewebkit/i.test(e)},{"../internals/engine-user-agent":47}],47:[function(e,t,r){e=e("../internals/get-built-in");t.exports=e("navigator","userAgent")||""},{"../internals/get-built-in":57}],48:[function(e,t,r){var o,n,s=e("../internals/global"),e=e("../internals/engine-user-agent"),s=s.process,s=s&&s.versions,s=s&&s.v8;s?n=(o=s.split("."))[0]+o[1]:e&&(!(o=e.match(/Edge\/(\d+)/))||74<=o[1])&&(o=e.match(/Chrome\/(\d+)/))&&(n=o[1]),t.exports=n&&+n},{"../internals/engine-user-agent":47,"../internals/global":60}],49:[function(e,t,r){t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},{}],50:[function(e,t,r){var u=e("../internals/global"),c=e("../internals/object-get-own-property-descriptor").f,d=e("../internals/create-non-enumerable-property"),h=e("../internals/redefine"),f=e("../internals/set-global"),p=e("../internals/copy-constructor-properties"),m=e("../internals/is-forced");t.exports=function(e,t){var r,o,n,s=e.target,i=e.global,a=e.stat,l=i?u:a?u[s]||f(s,{}):(u[s]||{}).prototype;if(l)for(r in t){if(o=t[r],n=e.noTargetGet?(n=c(l,r))&&n.value:l[r],!m(i?r:s+(a?".":"#")+r,e.forced)&&void 0!==n){if(typeof o==typeof n)continue;p(o,n)}(e.sham||n&&n.sham)&&d(o,"sham",!0),h(l,r,o,e)}}},{"../internals/copy-constructor-properties":33,"../internals/create-non-enumerable-property":38,"../internals/global":60,"../internals/is-forced":74,"../internals/object-get-own-property-descriptor":94,"../internals/redefine":110,"../internals/set-global":117}],51:[function(e,t,r){t.exports=function(e){try{return!!e()}catch(e){return!0}}},{}],52:[function(e,t,r){"use strict";e("../modules/es.regexp.exec");var u=e("../internals/redefine"),c=e("../internals/fails"),d=e("../internals/well-known-symbol"),h=e("../internals/regexp-exec"),f=e("../internals/create-non-enumerable-property"),p=d("species"),m=!c(function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$")}),y="$0"==="a".replace(/./,"$0"),e=d("replace"),g=!!/./[e]&&""===/./[e]("a","$0"),v=!c(function(){var e=/(?:)/,t=e.exec,e=(e.exec=function(){return t.apply(this,arguments)},"ab".split(e));return 2!==e.length||"a"!==e[0]||"b"!==e[1]});t.exports=function(r,e,t,o){var s,n,i=d(r),a=!c(function(){var e={};return e[i]=function(){return 7},7!=""[r](e)}),l=a&&!c(function(){var e=!1,t=/a/;return"split"===r&&((t={constructor:{}}).constructor[p]=function(){return t},t.flags="",t[i]=/./[i]),t.exec=function(){return e=!0,null},t[i](""),!e});a&&l&&("replace"!==r||m&&y&&!g)&&("split"!==r||v)||(s=/./[i],t=(l=t(i,""[r],function(e,t,r,o,n){return t.exec===h?a&&!n?{done:!0,value:s.call(t,r,o)}:{done:!0,value:e.call(r,t,o)}:{done:!1}},{REPLACE_KEEPS_$0:y,REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE:g}))[0],n=l[1],u(String.prototype,r,t),u(RegExp.prototype,i,2==e?function(e,t){return n.call(e,this,t)}:function(e){return n.call(e,this)})),o&&f(RegExp.prototype[i],"sham",!0)}},{"../internals/create-non-enumerable-property":38,"../internals/fails":51,"../internals/redefine":110,"../internals/regexp-exec":112,"../internals/well-known-symbol":150,"../modules/es.regexp.exec":195}],53:[function(e,t,r){"use strict";function h(e,t,r,o,n,s,i,a){for(var l,u=n,c=0,d=!!i&&m(i,a,3);c>1,u=23===t?f(2,-24)-f(2,-77):0,c=e<0||0===e&&1/e<0?1:0,d=0;for((e=h(e))!=e||e===1/0?(n=e!=e?1:0,o=r):(o=p(m(e)/y),e*(s=f(2,-o))<1&&(o--,s*=2),2<=(e+=1<=o+l?u/s:u*f(2,1-l))*s&&(o++,s/=2),r<=o+l?(n=0,o=r):1<=o+l?(n=(e*s-1)*f(2,t),o+=l):(n=e*f(2,l-1)*f(2,t),o=0));8<=t;i[d++]=255&n,n/=256,t-=8);for(o=o<>1,a=n-7,l=o-1,n=e[l--],u=127&n;for(n>>=7;0>=-a,a+=t;0"+e+""},m=function(){try{n=document.domain&&new ActiveXObject("htmlfile")}catch(e){}m=n?((e=n).write(p("")),e.close(),t=e.parentWindow.Object,e=null,t):(e=c("iframe"),t="java"+h+":",e.style.display="none",u.appendChild(e),e.src=String(t),(t=e.contentWindow.document).open(),t.write(p("document.F=Object")),t.close(),t.F);for(var e,t,r=a.length;r--;)delete m[d][a[r]];return m()};l[f]=!0,t.exports=Object.create||function(e,t){var r;return null!==e?(o[d]=s(e),r=new o,o[d]=null,r[f]=e):r=m(),void 0===t?r:i(r,t)}},{"../internals/an-object":10,"../internals/document-create-element":44,"../internals/enum-bug-keys":49,"../internals/hidden-keys":62,"../internals/html":64,"../internals/object-define-properties":92,"../internals/shared-key":120}],92:[function(e,t,r){var o=e("../internals/descriptors"),i=e("../internals/object-define-property"),a=e("../internals/an-object"),l=e("../internals/object-keys");t.exports=o?Object.defineProperties:function(e,t){a(e);for(var r,o=l(t),n=o.length,s=0;sn;)!i(o,r=t[n++])||~l(s,r)||s.push(r);return s}},{"../internals/array-includes":18,"../internals/has":61,"../internals/hidden-keys":62,"../internals/to-indexed-object":136}],100:[function(e,t,r){var o=e("../internals/object-keys-internal"),n=e("../internals/enum-bug-keys");t.exports=Object.keys||function(e){return o(e,n)}},{"../internals/enum-bug-keys":49,"../internals/object-keys-internal":99}],101:[function(e,t,r){"use strict";var o={}.propertyIsEnumerable,n=Object.getOwnPropertyDescriptor,s=n&&!o.call({1:2},1);r.f=s?function(e){e=n(this,e);return!!e&&e.enumerable}:o},{}],102:[function(e,t,r){var n=e("../internals/an-object"),s=e("../internals/a-possible-prototype");t.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var r,o=!1,e={};try{(r=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(e,[]),o=e instanceof Array}catch(e){}return function(e,t){return n(e),s(t),o?r.call(e,t):e.__proto__=t,e}}():void 0)},{"../internals/a-possible-prototype":6,"../internals/an-object":10}],103:[function(e,t,r){function o(a){return function(e){for(var t,r=c(e),o=u(r),n=o.length,s=0,i=[];st&&(o=o.slice(0,t)),n?e+o:o+e)}}var s=e("../internals/to-length"),i=e("../internals/string-repeat"),a=e("../internals/require-object-coercible"),l=Math.ceil;t.exports={start:o(!1),end:o(!0)}},{"../internals/require-object-coercible":115,"../internals/string-repeat":129,"../internals/to-length":138}],128:[function(e,t,r){"use strict";function g(e){return e+22+75*(e<26)}function s(e){var t,r=[],o=(e=function(e){for(var t=[],r=0,o=e.length;rT((v-s)/d))throw RangeError(w);for(s+=(u-n)*d,n=u,c=0;cv)throw RangeError(w);if(t==n){for(var h=s,f=b;;f+=b){var p=f<=i?1:i+j<=f?j:f-i;if(h>1,e+=T(e/t);S*j>>1>>=1)&&(t+=t))1&o&&(r+=t);return r}},{"../internals/require-object-coercible":115,"../internals/to-integer":137}],130:[function(e,t,r){var o=e("../internals/fails"),n=e("../internals/whitespaces");t.exports=function(e){return o(function(){return!!n[e]()||"​…᠎"!="​…᠎"[e]()||n[e].name!==e})}},{"../internals/fails":51,"../internals/whitespaces":151}],131:[function(e,t,r){function o(t){return function(e){e=String(n(e));return 1&t&&(e=e.replace(s,"")),e=2&t?e.replace(i,""):e}}var n=e("../internals/require-object-coercible"),e="["+e("../internals/whitespaces")+"]",s=RegExp("^"+e+e+"*"),i=RegExp(e+e+"*$");t.exports={start:o(1),end:o(2),trim:o(3)}},{"../internals/require-object-coercible":115,"../internals/whitespaces":151}],132:[function(e,t,r){function o(e){return function(){x(e)}}function n(e){x(e.data)}function s(e){a.postMessage(e+"",f.protocol+"//"+f.host)}var i,a=e("../internals/global"),l=e("../internals/fails"),u=e("../internals/classof-raw"),c=e("../internals/function-bind-context"),d=e("../internals/html"),h=e("../internals/document-create-element"),e=e("../internals/engine-is-ios"),f=a.location,p=a.setImmediate,m=a.clearImmediate,y=a.process,g=a.MessageChannel,v=a.Dispatch,b=0,j={},_="onreadystatechange",x=function(e){var t;j.hasOwnProperty(e)&&(t=j[e],delete j[e],t())};p&&m||(p=function(e){for(var t=[],r=1;r=t.length?{value:e.target=void 0,done:!0}:"keys"==r?{value:o,done:!1}:"values"==r?{value:t[o],done:!1}:{value:[o,t[o]],done:!1}},"values"),s.Arguments=s.Array,n("keys"),n("values"),n("entries")},{"../internals/add-to-unscopables":7,"../internals/define-iterator":41,"../internals/internal-state":71,"../internals/iterators":80,"../internals/to-indexed-object":136}],166:[function(e,t,r){"use strict";var o=e("../internals/export"),n=e("../internals/indexed-object"),s=e("../internals/to-indexed-object"),e=e("../internals/array-method-is-strict"),i=[].join,n=n!=Object,e=e("join",",");o({target:"Array",proto:!0,forced:n||!e},{join:function(e){return i.call(s(this),void 0===e?",":e)}})},{"../internals/array-method-is-strict":22,"../internals/export":50,"../internals/indexed-object":67,"../internals/to-indexed-object":136}],167:[function(e,t,r){var o=e("../internals/export"),e=e("../internals/array-last-index-of");o({target:"Array",proto:!0,forced:e!==[].lastIndexOf},{lastIndexOf:e})},{"../internals/array-last-index-of":20,"../internals/export":50}],168:[function(e,t,r){"use strict";var o=e("../internals/export"),n=e("../internals/array-iteration").map,s=e("../internals/array-method-has-species-support"),e=e("../internals/array-method-uses-to-length"),s=s("map"),e=e("map");o({target:"Array",proto:!0,forced:!s||!e},{map:function(e){return n(this,e,1T;T++)l(b,x=S[T])&&!l(w,x)&&y(w,x,m(b,x));(w.prototype=j).constructor=w,a(s,v,w)}},{"../internals/classof-raw":28,"../internals/descriptors":43,"../internals/fails":51,"../internals/global":60,"../internals/has":61,"../internals/inherit-if-required":68,"../internals/is-forced":74,"../internals/object-create":91,"../internals/object-define-property":93,"../internals/object-get-own-property-descriptor":94,"../internals/object-get-own-property-names":96,"../internals/redefine":110,"../internals/string-trim":131,"../internals/to-primitive":142}],180:[function(e,t,r){e("../internals/export")({target:"Number",stat:!0},{EPSILON:Math.pow(2,-52)})},{"../internals/export":50}],181:[function(e,t,r){e("../internals/export")({target:"Number",stat:!0},{isFinite:e("../internals/number-is-finite")})},{"../internals/export":50,"../internals/number-is-finite":89}],182:[function(e,t,r){"use strict";function c(e,t,r){return 0===t?r:t%2==1?c(e,t-1,r*e):c(e*e,t/2,r)}var o=e("../internals/export"),d=e("../internals/to-integer"),h=e("../internals/this-number-value"),f=e("../internals/string-repeat"),e=e("../internals/fails"),n=1..toFixed,p=Math.floor;o({target:"Number",proto:!0,forced:n&&("0.000"!==8e-5.toFixed(3)||"1"!==.9.toFixed(0)||"1.25"!==1.255.toFixed(2)||"1000000000000000128"!==0xde0b6b3a7640080.toFixed(0))||!e(function(){n.call({})})},{toFixed:function(e){function t(e,t){for(var r=-1,o=t;++r<6;)o+=e*a[r],a[r]=o%1e7,o=p(o/1e7)}function r(e){for(var t=6,r=0;0<=--t;)r+=a[t],a[t]=p(r/e),r=r%e*1e7}function o(){for(var e,t=6,r="";0<=--t;)""===r&&0!==t&&0===a[t]||(e=String(a[t]),r=""===r?e:r+f.call("0",7-e.length)+e);return r}var n,s,i=h(this),e=d(e),a=[0,0,0,0,0,0],l="",u="0";if(e<0||20n;){var s,i,a,l=y[n++],u=t?l.ok:l.fail,c=l.resolve,d=l.reject,h=l.domain;try{u?(t||(p.rejection===oe&&function(e,t){v.call(g,function(){if(k)T.emit("rejectionHandled",e);else se(te,e,t.value)})}(f,p),p.rejection=A),!0===u?s=e:(h&&h.enter(),s=u(e),h&&(h.exit(),a=!0)),s===l.promise?d(w("Promise-chain cycle")):(i=ne(s))?i.call(s,c,d):c(s)):d(e)}catch(e){h&&!a&&h.exit(),d(e)}}p.reactions=[],p.notified=!1,m&&!p.rejection&&(r=f,o=p,v.call(g,function(){var e=o.value,t=ie(o);if(t&&(t=b(function(){k?T.emit("unhandledRejection",e,r):se(O,r,e)}),o.rejection=k||ie(o)?oe:A,t.error))throw t.value}))}))},se=function(e,t,r){var o;ee?((o=S.createEvent("Event")).promise=t,o.reason=r,o.initEvent(e,!1,!0),g.dispatchEvent(o)):o={promise:t,reason:r},(t=g["on"+e])?t(o):e===O&&Y("Unhandled promise rejection",r)},ie=function(e){return e.rejection!==A&&!e.parent},L=function(t,r,o,n){return function(e){t(r,o,e,n)}},R=function(e,t,r,o){t.done||(t.done=!0,(t=o?o:t).value=r,t.state=re,P(e,t,!0))},I=function(r,o,e,t){if(!o.done){o.done=!0,t&&(o=t);try{if(r===e)throw w("Promise can't be resolved itself");var n=ne(e);n?u(function(){var t={done:!1};try{n.call(e,L(I,r,t,o),L(R,r,t,o))}catch(e){R(r,t,e,o)}}):(o.value=e,o.state=C,P(r,o,!1))}catch(e){R(r,{done:!1},e,o)}}};e&&(x=function(e){z(this,x,j),c(e),r.call(this);var t=_(this);try{e(L(I,this,t),L(R,this,t))}catch(e){R(this,t,e)}},(r=function(e){K(this,{type:j,done:!1,notified:!1,parent:!1,reactions:[],rejection:!1,state:0,value:void 0})}).prototype=N(x.prototype,{then:function(e,t){var r=J(this),o=M(X(this,x));return o.ok="function"!=typeof e||e,o.fail="function"==typeof t&&t,o.domain=k?T.domain:void 0,r.parent=!0,r.reactions.push(o),0!=r.state&&P(this,r,!1),o.promise},catch:function(e){return this.then(void 0,e)}}),t=function(){var e=new r,t=_(e);this.promise=e,this.resolve=L(I,e,t),this.reject=L(R,e,t)},f.f=M=function(e){return e===x||e===o?new t:$(e)},i||"function"!=typeof l||(n=l.prototype.then,U(l.prototype,"then",function(e,t){var r=this;return new x(function(e,t){n.call(r,e,t)}).then(e,t)},{unsafe:!0}),"function"==typeof E&&s({global:!0,enumerable:!0,forced:!0},{fetch:function(e){return h(x,E.apply(g,arguments))}}))),s({global:!0,wrap:!0,forced:e},{Promise:x}),B(x,j,!1,!0),G(j),o=a(j),s({target:j,stat:!0,forced:e},{reject:function(e){var t=M(this);return t.reject.call(void 0,e),t.promise}}),s({target:j,stat:!0,forced:i||e},{resolve:function(e){return h(i&&this===o?x:this,e)}}),s({target:j,stat:!0,forced:m},{all:function(e){var a=this,t=M(a),l=t.resolve,u=t.reject,r=b(function(){var o=c(a.resolve),n=[],s=0,i=1;d(e,function(e){var t=s++,r=!1;n.push(void 0),i++,o.call(a,e).then(function(e){r||(r=!0,n[t]=e,--i||l(n))},u)}),--i||l(n)});return r.error&&u(r.value),t.promise},race:function(e){var r=this,o=M(r),n=o.reject,t=b(function(){var t=c(r.resolve);d(e,function(e){t.call(r,e).then(o.resolve,n)})});return t.error&&n(t.value),o.promise}})},{"../internals/a-function":5,"../internals/an-instance":9,"../internals/check-correctness-of-iteration":27,"../internals/classof-raw":28,"../internals/engine-v8-version":48,"../internals/export":50,"../internals/get-built-in":57,"../internals/global":60,"../internals/host-report-errors":63,"../internals/inspect-source":69,"../internals/internal-state":71,"../internals/is-forced":74,"../internals/is-object":75,"../internals/is-pure":76,"../internals/iterate":78,"../internals/microtask":82,"../internals/native-promise-constructor":83,"../internals/new-promise-capability":87,"../internals/perform":107,"../internals/promise-resolve":108,"../internals/redefine":110,"../internals/redefine-all":109,"../internals/set-species":118,"../internals/set-to-string-tag":119,"../internals/species-constructor":123,"../internals/task":132,"../internals/well-known-symbol":150}],192:[function(e,t,r){var o=e("../internals/export"),n=e("../internals/get-built-in"),s=e("../internals/a-function"),i=e("../internals/an-object"),a=e("../internals/is-object"),l=e("../internals/object-create"),u=e("../internals/function-bind"),e=e("../internals/fails"),c=n("Reflect","construct"),d=e(function(){function e(){}return!(c(function(){},[],e)instanceof e)}),h=!e(function(){c(function(){})}),n=d||h;o({target:"Reflect",stat:!0,forced:n,sham:n},{construct:function(e,t){s(e),i(t);var r=arguments.length<3?e:s(arguments[2]);if(h&&!d)return c(e,t,r);if(e==r){switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3])}var o=[null];return o.push.apply(o,t),new(u.apply(e,o))}o=r.prototype,r=l(a(o)?o:Object.prototype),o=Function.apply.call(e,r,t);return a(o)?o:r}})},{"../internals/a-function":5,"../internals/an-object":10,"../internals/export":50,"../internals/fails":51,"../internals/function-bind":56,"../internals/get-built-in":57,"../internals/is-object":75,"../internals/object-create":91}],193:[function(e,t,r){var o=e("../internals/export"),s=e("../internals/is-object"),i=e("../internals/an-object"),a=e("../internals/has"),l=e("../internals/object-get-own-property-descriptor"),u=e("../internals/object-get-prototype-of");o({target:"Reflect",stat:!0},{get:function e(t,r){var o,n=arguments.length<3?t:arguments[2];return i(t)===n?t[r]:(o=l.f(t,r))?a(o,"value")?o.value:void 0===o.get?void 0:o.get.call(n):s(o=u(t))?e(o,r,n):void 0}})},{"../internals/an-object":10,"../internals/export":50,"../internals/has":61,"../internals/is-object":75,"../internals/object-get-own-property-descriptor":94,"../internals/object-get-prototype-of":98}],194:[function(e,t,r){var o=e("../internals/descriptors"),n=e("../internals/global"),s=e("../internals/is-forced"),i=e("../internals/inherit-if-required"),a=e("../internals/object-define-property").f,l=e("../internals/object-get-own-property-names").f,u=e("../internals/is-regexp"),c=e("../internals/regexp-flags"),d=e("../internals/regexp-sticky-helpers"),h=e("../internals/redefine"),f=e("../internals/fails"),p=e("../internals/internal-state").set,m=e("../internals/set-species"),y=e("../internals/well-known-symbol")("match"),g=n.RegExp,v=g.prototype,b=/a/g,j=/a/g,_=new g(b)!==b,x=d.UNSUPPORTED_Y;if(o&&s("RegExp",!_||x||f(function(){return j[y]=!1,g(b)!=b||g(j)==j||"/a/i"!=g(b,"i")}))){for(var w=function(e,t){var r,o=this instanceof w,n=u(e),s=void 0===t;if(!o&&n&&e.constructor===w&&s)return e;_?n&&!s&&(e=e.source):e instanceof w&&(s&&(t=c.call(e)),e=e.source),x&&(r=!!t&&-1T;)!function(t){t in w||a(w,t,{configurable:!0,get:function(){return g[t]},set:function(e){g[t]=e}})}(S[T++]);(v.constructor=w).prototype=v,h(n,"RegExp",w)}m("RegExp")},{"../internals/descriptors":43,"../internals/fails":51,"../internals/global":60,"../internals/inherit-if-required":68,"../internals/internal-state":71,"../internals/is-forced":74,"../internals/is-regexp":77,"../internals/object-define-property":93,"../internals/object-get-own-property-names":96,"../internals/redefine":110,"../internals/regexp-flags":113,"../internals/regexp-sticky-helpers":114,"../internals/set-species":118,"../internals/well-known-symbol":150}],195:[function(e,t,r){"use strict";var o=e("../internals/export"),e=e("../internals/regexp-exec");o({target:"RegExp",proto:!0,forced:/./.exec!==e},{exec:e})},{"../internals/export":50,"../internals/regexp-exec":112}],196:[function(e,t,r){"use strict";var o=e("../internals/redefine"),n=e("../internals/an-object"),s=e("../internals/fails"),i=e("../internals/regexp-flags"),e="toString",a=RegExp.prototype,l=a[e],s=s(function(){return"/a/b"!=l.call({source:"a",flags:"b"})}),u=l.name!=e;(s||u)&&o(RegExp.prototype,e,function(){var e=n(this),t=String(e.source),r=e.flags;return"/"+t+"/"+String(void 0===r&&e instanceof RegExp&&!("flags"in a)?i.call(e):r)},{unsafe:!0})},{"../internals/an-object":10,"../internals/fails":51,"../internals/redefine":110,"../internals/regexp-flags":113}],197:[function(e,t,r){"use strict";var o=e("../internals/collection"),e=e("../internals/collection-strong");t.exports=o("Set",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},e)},{"../internals/collection":32,"../internals/collection-strong":30}],198:[function(e,t,r){"use strict";var o=e("../internals/export"),n=e("../internals/object-get-own-property-descriptor").f,s=e("../internals/to-length"),i=e("../internals/not-a-regexp"),a=e("../internals/require-object-coercible"),l=e("../internals/correct-is-regexp-logic"),e=e("../internals/is-pure"),u="".endsWith,c=Math.min,l=l("endsWith");o({target:"String",proto:!0,forced:!!(e||l||(!(o=n(String.prototype,"endsWith"))||o.writable))&&!l},{endsWith:function(e){var t=String(a(this)),r=(i(e),1=t.length?{value:void 0,done:!0}:(t=o(t,r),e.index+=t.length,{value:t,done:!1})})},{"../internals/define-iterator":41,"../internals/internal-state":71,"../internals/string-multibyte":125}],201:[function(e,t,r){"use strict";var o=e("../internals/fix-regexp-well-known-symbol-logic"),c=e("../internals/an-object"),d=e("../internals/to-length"),n=e("../internals/require-object-coercible"),h=e("../internals/advance-string-index"),f=e("../internals/regexp-exec-abstract");o("match",1,function(o,l,u){return[function(e){var t=n(this),r=null==e?void 0:e[o];return void 0!==r?r.call(e,t):new RegExp(e)[o](String(t))},function(e){var t=u(l,e,this);if(t.done)return t.value;var r=c(e),o=String(this);if(!r.global)return f(r,o);for(var n=r.unicode,s=[],i=r.lastIndex=0;null!==(a=f(r,o));){var a=String(a[0]);""===(s[i]=a)&&(r.lastIndex=h(o,d(r.lastIndex),n)),i++}return 0===i?null:s}]})},{"../internals/advance-string-index":8,"../internals/an-object":10,"../internals/fix-regexp-well-known-symbol-logic":52,"../internals/regexp-exec-abstract":111,"../internals/require-object-coercible":115,"../internals/to-length":138}],202:[function(e,t,r){"use strict";var o=e("../internals/export"),n=e("../internals/string-pad").start;o({target:"String",proto:!0,forced:e("../internals/string-pad-webkit-bug")},{padStart:function(e){return n(this,e,1]*>)/g,I=/\$([$&'`]|\d\d?)/g;o("replace",2,function(n,j,_,e){var x=e.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE,w=e.REPLACE_KEEPS_$0,S=x?"$":"$0";return[function(e,t){var r=s(this),o=null==e?void 0:e[n];return void 0!==o?o.call(e,r,t):j.call(String(r),e,t)},function(e,t){if(!x&&w||"string"==typeof t&&-1===t.indexOf(S)){var r=_(j,e,this,t);if(r.done)return r.value}for(var o,n=T(e),s=String(this),i="function"==typeof t,a=(i||(t=String(t)),n.global),l=(a&&(o=n.unicode,n.lastIndex=0),[]);null!==(f=C(n,s))&&(l.push(f),a);)""===String(f[0])&&(n.lastIndex=O(s,M(n.lastIndex),o));for(var u,c="",d=0,h=0;h>>0;if(0==o)return[];if(void 0===e)return[r];if(!c(e))return p.call(r,e,o);for(var n,s,i,a=[],t=(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.unicode?"u":"")+(e.sticky?"y":""),l=0,u=new RegExp(e.source,t+"g");(n=h.call(u,r))&&!(l<(s=u.lastIndex)&&(a.push(r.slice(l,n.index)),1=o));)u.lastIndex===n.index&&u.lastIndex++;return l===r.length?!i&&u.test("")||a.push(""):a.push(r.slice(l)),a.length>o?a.slice(0,o):a}:"0".split(void 0,0).length?function(e,t){return void 0===e&&0===t?[]:p.call(this,e,t)}:p;return[function(e,t){var r=d(this),o=null==e?void 0:e[n];return void 0!==o?o.call(e,r,t):y.call(String(r),e,t)},function(e,t){var r=m(y,e,this,t,y!==p);if(r.done)return r.value;var r=g(e),o=String(this),e=v(r,RegExp),n=r.unicode,s=(r.ignoreCase?"i":"")+(r.multiline?"m":"")+(r.unicode?"u":"")+(S?"y":"g"),i=new e(S?r:"^(?:"+r.source+")",s),a=void 0===t?w:t>>>0;if(0==a)return[];if(0===o.length)return null===_(i,o)?[o]:[];for(var l=0,u=0,c=[];ue.key){o.splice(t,0,e);break}t===s&&o.push(e)}r.updateURL()},forEach:function(e){for(var t,r=A(this).entries,o=v(e,16)return;a=0;while(h()){l=null;if(a>0)if(h()=="."&&a<4)n++;else return;if(!x.test(h()))return;while(x.test(h())){u=parseInt(h(),10);if(l===null)l=u;else if(l==0)return;else l=l*10+u;if(l>255)return;n++}t[r]=t[r]*256+l;a++;if(a==2||a==4)r++}if(a!=4)return;break}else if(h()==":"){n++;if(!h())return}else if(h())return;t[r++]=s}if(o!==null){c=r-o;r=7;while(r!=0&&c>0){d=t[r];t[r--]=t[o+c-1];t[o+--c]=d}}else if(r!=8)return;return t}(t.slice(1,-1)))?void(e.host=r):_;if(k(e))return t=z(t),ne.test(t)||null===(r=function(e){var t=e.split("."),r,o,n,s,i,a,l;if(t.length&&t[t.length-1]=="")t.pop();if((r=t.length)>4)return e;for(o=[],n=0;n1&&s.charAt(0)=="0"){i=ee.test(s)?16:8;s=s.slice(i==8?1:2)}if(s==="")a=0;else{if(!(i==10?re:i==8?te:oe).test(s))return e;a=parseInt(s,i)}o.push(a)}for(n=0;n=Z(256,5-r))return null}else if(a>255)return null}for(l=o.pop(),n=0;n":1,"`":1}),ce=d({},ue,{"#":1,"?":1,"{":1,"}":1}),T=d({},ce,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),E=function(e,t){var r=V(e,0);return 32h,applyPalette:()=>function(e,t,r="rgb565"){if(!e||!e.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(e instanceof Uint8Array||e instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");if(256>24&255,c=l>>16&255,d=l>>8&255,l=255&l,h=A(l,d,c,u),h=h in a?a[h]:a[h]=function(t,r,o,n,s){let i=0,a=1e100;for(let e=0;ea||(l=u[0],(c+=v(l-t))>a||(l=u[1],(c+=v(l-r))>a||(l=u[2],(c+=v(l-o))>a||(a=c,i=e))))}return i}(l,d,c,u,t);i[e]=h}else{const g="rgb444"===r?P:C;for(let e=0;e>16&255,m=f>>8&255,f=255&f,y=g(f,m,p),y=y in a?a[y]:a[y]=function(t,r,o,n){let s=0,i=1e100;for(let e=0;ei||(a=l[1],(u+=v(a-r))>i||(a=l[2],(u+=v(a-o))>i||(i=u,s=e)))}return s}(f,m,p,t);i[e]=y}}return i},default:()=>f,nearestColor:()=>function(e,t,r=u){return e[l(e,t,r)]},nearestColorIndex:()=>l,nearestColorIndexWithDistance:()=>d,prequantize:()=>function(e,{roundRGB:r=5,roundAlpha:o=10,oneBitAlpha:n=null}={}){const s=new Uint32Array(e.buffer);for(let t=0;t>24&255;var a,l=i>>16&255,u=i>>8&255,i=255&i;e=c(e,o),n&&(a="number"==typeof n?n:127,e=e<=a?0:255),i=c(i,r),u=c(u,r),l=c(l,r),s[t]=e<<24|l<<16|u<<8|i<<0}},quantize:()=>function(e,t,r={}){var{format:o="rgb565",clearAlpha:n=!0,clearAlphaColor:s=0,clearAlphaThreshold:i=0,oneBitAlpha:a=!1}=r;if(!e||!e.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(e instanceof Uint8Array||e instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");e=new Uint32Array(e.buffer);let l=!1!==r.useSqrt;const u="rgba4444"===o,c=function(r,e){const t="rgb444"===e?4096:65536,o=new Array(t),n=r.length;if("rgba4444"===e)for(let t=0;t>24&255,a=s>>16&255,l=s>>8&255,s=255&s,u=A(s,l,a,i);let e=u in o?o[u]:o[u]=D();e.rc+=s,e.gc+=l,e.bc+=a,e.ac+=i,e.cnt++}else if("rgb444"===e)for(let t=0;t>16&255,h=c>>8&255,c=255&c,f=P(c,h,d);let e=f in o?o[f]:o[f]=D();e.rc+=c,e.gc+=h,e.bc+=d,e.cnt++}else for(let t=0;t>16&255,y=p>>8&255,p=255&p,g=C(p,y,m);let e=g in o?o[g]:o[g]=D();e.rc+=p,e.gc+=y,e.bc+=m,e.cnt++}return o}(e,o),d=c.length,h=d-1,f=new Uint32Array(d+1);for(var p=0,m=0;m>1,!(c[y=f[v]].err<=b));g=v)f[g]=y;f[g]=m}var j,_=p-t;for(m=0;m<_;){for(;;){var x=f[1];if((j=c[x]).tm>=j.mtm&&c[j.nn].mtm<=j.tm)break;j.mtm==h?x=f[1]=f[f[0]--]:(I(c,x,!1),j.tm=m);b=c[x].err;for(g=1;(v=g+g)<=f[0]&&(vc[f[v+1]].err&&v++,!(b<=c[y=f[v]].err));g=v)f[g]=y;f[g]=x}var w=c[j.nn],S=j.cnt,T=w.cnt,E=1/(S+T);u&&(j.ac=E*(S*j.ac+T*w.ac)),j.rc=E*(S*j.rc+T*w.rc),j.gc=E*(S*j.gc+T*w.gc),j.bc=E*(S*j.bc+T*w.bc),j.cnt+=w.cnt,j.mtm=++m,c[w.bk].fw=w.fw,c[w.fw].bk=w.bk,w.mtm=h}let M=[];for(m=0;;0){let e=L(Math.round(c[m].rc),0,255),t=L(Math.round(c[m].gc),0,255),r=L(Math.round(c[m].bc),0,255),o=255;u&&(o=L(Math.round(c[m].ac),0,255),a&&(k="number"==typeof a?a:127,o=o<=k?0:255),n&&o<=i&&(e=t=r=s,o=0));var k=u?[e,t,r,o]:[e,t,r];if(function(t,r){for(let e=0;efunction(r,o,e=5){if(r.length&&o.length){var n=r.map(e=>e.slice(0,3)),s=e*e,i=r[0].length;for(let t=0;ti?e.slice(0,3):e.slice();var a=d(n,e.slice(0,3),u),l=a[0],a=a[1];0>>0),0!=t&&(e=Math.max(e,256));const r=s;s=new Uint8Array(e),0>=8,c-=8;if((v>m||f)&&(f?(p=h,m=(1<>=8,c-=8;0>3}function A(e,t,r,o){return e>>4|240&t|(240&r)<<4|(240&o)<<8}function P(e,t,r){return e>>4<<8|240&t|r>>4}function L(e,t,r){return e>8&255)}function O(e,t){for(var r=0;r>1,c=-7,d=r?n-1:0,h=r?-1:1,n=e[t+d];for(d+=h,s=n&(1<<-c)-1,n>>=-c,c+=a;0>=-c,c+=o;0>1,d=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,h=o?0:s-1,f=o?1:-1,s=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,i=u):(i=Math.floor(Math.log(t)/Math.LN2),t*(o=Math.pow(2,-i))<1&&(i--,o*=2),2<=(t+=1<=i+c?d/o:d*Math.pow(2,1-c))*o&&(i++,o/=2),u<=i+c?(a=0,i=u):1<=i+c?(a=(t*o-1)*Math.pow(2,n),i+=c):(a=t*Math.pow(2,c-1)*Math.pow(2,n),i=0));8<=n;e[r+h]=255&a,h+=f,a/=256,n-=8);for(i=i<Math.abs(e[0])&&(t=1),t=Math.abs(e[2])>Math.abs(e[t])?2:t}function M(e,t){e.f+=t.f,e.b.f+=t.b.f}function h(e,t,r){return e=e.a,t=t.a,r=r.a,t.b.a===e?r.b.a===e?g(t.a,r.a)?b(r.b.a,t.a,r.a)<=0:0<=b(t.b.a,r.a,t.a):b(r.b.a,e,r.a)<=0:r.b.a===e?0<=b(t.b.a,e,t.a):(t=v(t.b.a,e,t.a),(e=v(r.b.a,e,r.a))<=t)}function k(e){e.a.i=null;var t=e.e;t.a.c=t.c,t.c.a=t.a,e.e=null}function O(e,t){m(e.a),e.c=!1,(e.a=t).i=e}function C(e){for(var t=e.a.a;(e=G(e)).a.a===t;);return e.c&&(O(e,t=S(B(e).a.b,e.a.e)),e=G(e)),e}function q(e,t,r){var o=new N;return o.a=r,o.e=p(e.f,t.e,o),r.i=o}function X(e,t){switch(e.s){case 100130:return 0!=(1&t);case 100131:return 0!==t;case 100132:return 0>1]],a[i[u]])?U:ue)(r,u),a[s]=null,l[s]=r.b,r.b=s}else for(r.c[-(s+1)]=null;0Math.max(i.a,l.a))){if(g(s,i)){if(0r.f&&(r.f*=2,r.c=ae(r.c,r.f+1)),0===r.b?n=o:(n=r.b,r.b=r.c[r.b]),r.e[n]=t,r.c[n]=o,r.d[o]=n,r.h&&ue(r,o),n):(r=e.a++,e.c[r]=t,-(r+1))}function se(e){if(0===e.a)return le(e.b);var t=e.c[e.d[e.a-1]];if(0!==e.b.a&&g(F(e.b),t))return le(e.b);for(;--e.a,0e.a||g(o[i],o[l])){n[r[s]=i]=s;break}n[r[s]=l]=s,s=a}}function ue(e,t){for(var r=e.d,o=e.e,n=e.c,s=t,i=r[s];;){var a=s>>1,l=r[a];if(0==a||g(o[l],o[i])){n[r[s]=i]=s;break}n[r[s]=l]=s,s=a}}function N(){this.e=this.a=null,this.f=0,this.c=this.b=this.h=this.d=!1}function B(e){return e.e.c.b}function G(e){return e.e.a.b}(t=r.prototype).x=function(){I(this,0)},t.B=function(e,t){switch(e){case 100142:return;case 100140:switch(t){case 100130:case 100131:case 100132:case 100133:case 100134:return void(this.s=t)}break;case 100141:return void(this.m=!!t);default:return void l(this,100900)}l(this,100901)},t.y=function(e){switch(e){case 100142:return 0;case 100140:return this.s;case 100141:return this.m;default:l(this,100900)}return!1},t.A=function(e,t,r){this.j[0]=e,this.j[1]=t,this.j[2]=r},t.z=function(e,t){var r=t||null;switch(e){case 100100:case 100106:this.h=r;break;case 100104:case 100110:this.l=r;break;case 100101:case 100107:this.k=r;break;case 100102:case 100108:this.i=r;break;case 100103:case 100109:this.p=r;break;case 100105:case 100111:this.o=r;break;case 100112:this.r=r;break;default:l(this,100900)}},t.C=function(e,t){var r=!1,o=[0,0,0];I(this,2);for(var n=0;n<3;++n){var s=e[n];s<-1e150&&(s=-1e150,r=!0),1e150o[u]&&(o[u]=c,n[u]=r)}if(o[1]-a[1]>o[r=0]-a[0]&&(r=1),a[r=o[2]-a[2]>o[r]-a[r]?2:r]>=o[r])i[0]=0,i[1]=0,i[2]=1;else{for(a=l[r],n=n[r],l=[o=0,0,0],a=[a.g[0]-n.g[0],a.g[1]-n.g[1],a.g[2]-n.g[2]],u=[0,0,0],r=s.e;r!==s;r=r.e)u[0]=r.g[0]-n.g[0],u[1]=r.g[1]-n.g[1],u[2]=r.g[2]-n.g[2],l[0]=a[1]*u[2]-a[2]*u[1],l[1]=a[2]*u[0]-a[0]*u[2],l[2]=a[0]*u[1]-a[1]*u[0],o<(c=l[0]*l[0]+l[1]*l[1]+l[2]*l[2])&&(o=c,i[0]=l[0],i[1]=l[1],i[2]=l[2]);o<=0&&(i[0]=i[1]=i[2]=0,i[W(a)]=1)}s=!0}for(l=W(i),r=this.b.c,o=(l+1)%3,n=(l+2)%3,l=0>=1;)++n;if(i=1<>8&255,g[v++]=255&t,g[v++]=t>>8&255,g[v++]=(null!==b?128:0)|n,g[v++]=s,g[v++]=0,null!==b)for(var a=0,l=b.length;a>16&255,g[v++]=u>>8&255,g[v++]=255&u}if(null!==o){if(o<0||65535>8&255,g[v++]=0}var _=!1;this.addFrame=function(e,t,r,o,n,s){if(!0===_&&(--v,_=!1),s=void 0===s?{}:s,e<0||t<0||65535>=1;)++u;var l=1<>8&255,g[v++]=f,g[v++]=0),g[v++]=44,g[v++]=255&e,g[v++]=e>>8&255,g[v++]=255&t,g[v++]=t>>8&255,g[v++]=255&r,g[v++]=r>>8&255,g[v++]=255&o,g[v++]=o>>8&255,g[v++]=!0===i?128|u-1:0,!0===i)for(var p=0,m=a.length;p>16&255,g[v++]=y>>8&255,g[v++]=255&y}return v=function(t,r,e,o){t[r++]=e;var n=r++,s=1<>=8,c-=8,r===n+256&&(t[n]=255,n=r++)}function f(e){d|=e<>=8,c-=8,r===n+256&&(t[n]=255,n=r++);4096===l?(f(s),l=1+a,u=e+1,m={}):(1<>=l,c-=l,y==s)a=1+i,u=(1<<(l=n+1))-1,m=null;else{if(y==i)break;for(var g=y>8,++v;var j=b;if(o>=8;null!==m&&a<4096&&(p[a++]=m<<8|j,u+1<=a&&l<12&&(++l,u=u<<1|1)),m=y}}h!==o&&console.log("Warning, gif stream shorter than expected.")}try{r.GifWriter=o,r.GifReader=function(b){var e=0;if(71!==b[e++]||73!==b[e++]||70!==b[e++]||56!==b[e++]||56!=(b[e++]+1&253)||97!==b[e++])throw new Error("Invalid GIF 87a/89a header.");var j=b[e++]|b[e++]<<8,t=b[e++]|b[e++]<<8,r=b[e++],o=1<<1+(7&r),n=(b[e++],b[e++],null),s=null,i=(r>>7&&(n=e,e+=3*(s=o)),!0),a=[],l=0,u=null,c=0,d=null;for(this.width=j,this.height=t;i&&e>2&7,e++;break;case 254:for(;;){if(!(0<=(f=b[e++])))throw Error("Invalid block size");if(0===f)break;e+=f}break;default:throw new Error("Unknown graphic control label: 0x"+b[e-1].toString(16))}break;case 44:var f,p=b[e++]|b[e++]<<8,m=b[e++]|b[e++]<<8,y=b[e++]|b[e++]<<8,g=b[e++]|b[e++]<<8,v=b[e++],_=v>>6&1,x=1<<1+(7&v),w=n,S=s,T=!1,v=(v>>7&&(T=!0,w=e,e+=3*(S=x)),e);for(e++;;){if(!(0<=(f=b[e++])))throw Error("Invalid block size");if(0===f)break;e+=f}a.push({x:p,y:m,width:y,height:g,has_local_palette:T,palette_offset:w,palette_size:S,data_offset:v,data_length:e-v,transparent_index:u,interlaced:!!_,delay:l,disposal:c});break;case 59:i=!1;break;default:throw new Error("Unknown gif block: 0x"+b[e-1].toString(16))}this.numFrames=function(){return a.length},this.loopCount=function(){return d},this.frameInfo=function(e){if(e<0||e>=a.length)throw new Error("Frame index out of range.");return a[e]},this.decodeAndBlitFrameBGRA=function(e,t){for(var e=this.frameInfo(e),r=e.width*e.height,o=new Uint8Array(r),n=(E(b,e.data_offset,o,r),e.palette_offset),s=e.transparent_index,i=(null===s&&(s=256),e.width),a=j-i,l=i,u=4*(e.y*j+e.x),c=4*((e.y+e.height)*j+e.x),d=u,h=4*a,f=(!0===e.interlaced&&(h+=4*j*7),8),p=0,m=o.length;p>=1)),v===s?d+=4:(y=b[n+3*v],g=b[n+3*v+1],v=b[n+3*v+2],t[d++]=v,t[d++]=g,t[d++]=y,t[d++]=255),--l}},this.decodeAndBlitFrameRGBA=function(e,t){for(var e=this.frameInfo(e),r=e.width*e.height,o=new Uint8Array(r),n=(E(b,e.data_offset,o,r),e.palette_offset),s=e.transparent_index,i=(null===s&&(s=256),e.width),a=j-i,l=i,u=4*(e.y*j+e.x),c=4*((e.y+e.height)*j+e.x),d=u,h=4*a,f=(!0===e.interlaced&&(h+=4*j*7),8),p=0,m=o.length;p>=1)),v===s?d+=4:(y=b[n+3*v],g=b[n+3*v+1],v=b[n+3*v+2],t[d++]=y,t[d++]=g,t[d++]=v,t[d++]=255),--l}}}}catch(e){}},{}],257:[function(Pr,r,o){!function(Ar){var e,t;e=this,t=function(j){"use strict";function D(e){if(null==this)throw TypeError();var t,r=String(this),o=r.length,e=e?Number(e):0;if(!((e=e!=e?0:e)<0||o<=e))return 55296<=(t=r.charCodeAt(e))&&t<=56319&&e+1>>16-t;return e.tag>>>=t,e.bitcount-=t,o+r}function $(e,t){for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>=1,r+=t.table[++n],0<=(o-=t.table[n]););return e.tag=s,e.bitcount-=n,t.trans[r+o]}function ee(e,t,r){for(;;){var o=$(e,t);if(256===o)return U;if(o<256)e.dest[e.destLen++]=o;else for(var n,s=b(e,H[o-=257],W[o]),o=$(e,r),i=n=e.destLen-b(e,q[o],X[o]);i>>=1,o=n,b(s,2,0)){case 0:r=function(e){for(var t,r;8this.x2&&(this.x2=e)),"number"==typeof t&&((isNaN(this.y1)||isNaN(this.y2))&&(this.y1=t,this.y2=t),tthis.y2&&(this.y2=t))},a.prototype.addX=function(e){this.addPoint(e,null)},a.prototype.addY=function(e){this.addPoint(null,e)},a.prototype.addBezier=function(e,t,r,o,n,s,i,a){var l=[e,t],u=[r,o],c=[n,s],d=[i,a];this.addPoint(e,t),this.addPoint(i,a);for(var h=0;h<=1;h++){var f,p=6*l[h]-12*u[h]+6*c[h],m=-3*l[h]+9*u[h]-9*c[h]+3*d[h],y=3*u[h]-3*l[h];0==m?0==p||0<(f=-y/p)&&f<1&&(0===h&&this.addX(g(l[h],u[h],c[h],d[h],f)),1===h&&this.addY(g(l[h],u[h],c[h],d[h],f))):(f=Math.pow(p,2)-4*y*m)<0||(0<(y=(-p+Math.sqrt(f))/(2*m))&&y<1&&(0===h&&this.addX(g(l[h],u[h],c[h],d[h],y)),1===h&&this.addY(g(l[h],u[h],c[h],d[h],y))),0<(y=(-p-Math.sqrt(f))/(2*m))&&y<1&&(0===h&&this.addX(g(l[h],u[h],c[h],d[h],y)),1===h&&this.addY(g(l[h],u[h],c[h],d[h],y))))}},a.prototype.addQuad=function(e,t,r,o,n,s){r=e+2/3*(r-e),o=t+2/3*(o-t);this.addBezier(e,t,r,o,r+1/3*(n-e),o+1/3*(s-t),n,s)},h.prototype.moveTo=function(e,t){this.commands.push({type:"M",x:e,y:t})},h.prototype.lineTo=function(e,t){this.commands.push({type:"L",x:e,y:t})},h.prototype.curveTo=h.prototype.bezierCurveTo=function(e,t,r,o,n,s){this.commands.push({type:"C",x1:e,y1:t,x2:r,y2:o,x:n,y:s})},h.prototype.quadTo=h.prototype.quadraticCurveTo=function(e,t,r,o){this.commands.push({type:"Q",x1:e,y1:t,x:r,y:o})},h.prototype.close=h.prototype.closePath=function(){this.commands.push({type:"Z"})},h.prototype.extend=function(e){var t;if(e.commands)e=e.commands;else if(e instanceof a)return t=e,this.moveTo(t.x1,t.y1),this.lineTo(t.x2,t.y1),this.lineTo(t.x2,t.y2),this.lineTo(t.x1,t.y2),void this.close();Array.prototype.push.apply(this.commands,e)},h.prototype.getBoundingBox=function(){for(var e=new a,t=0,r=0,o=0,n=0,s=0;s>8&255,255&e]},l.USHORT=r(2),w.SHORT=function(e){return[(e=32768<=e?-(65536-e):e)>>8&255,255&e]},l.SHORT=r(2),w.UINT24=function(e){return[e>>16&255,e>>8&255,255&e]},l.UINT24=r(3),w.ULONG=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]},l.ULONG=r(4),w.LONG=function(e){return[(e=2147483648<=e?-(4294967296-e):e)>>24&255,e>>16&255,e>>8&255,255&e]},l.LONG=r(4),w.FIXED=w.ULONG,l.FIXED=l.ULONG,w.FWORD=w.SHORT,l.FWORD=l.SHORT,w.UFWORD=w.USHORT,l.UFWORD=l.USHORT,w.LONGDATETIME=function(e){return[0,0,0,0,e>>24&255,e>>16&255,e>>8&255,255&e]},l.LONGDATETIME=r(8),w.TAG=function(e){return L.argument(4===e.length,"Tag should be exactly 4 ASCII characters."),[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]},l.TAG=r(4),w.Card8=w.BYTE,l.Card8=l.BYTE,w.Card16=w.USHORT,l.Card16=l.USHORT,w.OffSize=w.BYTE,l.OffSize=l.BYTE,w.SID=w.USHORT,l.SID=l.USHORT,w.NUMBER=function(e){return-107<=e&&e<=107?[e+139]:108<=e&&e<=1131?[247+((e-=108)>>8),255&e]:-1131<=e&&e<=-108?[251+((e=-e-108)>>8),255&e]:-32768<=e&&e<=32767?w.NUMBER16(e):w.NUMBER32(e)},l.NUMBER=function(e){return w.NUMBER(e).length},w.NUMBER16=function(e){return[28,e>>8&255,255&e]},l.NUMBER16=r(3),w.NUMBER32=function(e){return[29,e>>24&255,e>>16&255,e>>8&255,255&e]},l.NUMBER32=r(5),w.REAL=function(e){for(var t=e.toString(),r=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(t),o=(r&&(r=parseFloat("1e"+((r[2]?+r[2]:0)+r[1].length)),t=(Math.round(e*r)/r).toString()),""),n=0,s=t.length;n>8&255,t[t.length]=255&o}return t},l.UTF16=function(e){return 2*e.length};var se,ie={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"},ae=(m.MACSTRING=function(e,t,r,o){var n=ie[o];if(void 0!==n){for(var s="",i=0;i>8&255,l+256&255)}return s})(e,t,r);return r},w.INDEX=function(e){for(var t=1,r=[t],o=[],n=0;n>8,t[c+1]=255&d,t=t.concat(o[u])}return t},l.TABLE=function(e){for(var t=0,r=e.fields.length,o=0;o>1,a.skip("uShort",3),y.glyphIndexMap={};for(var j,_=new R.Parser(g,v+b+14),x=new R.Parser(g,v+b+16+2*j),w=new R.Parser(g,v+b+16+4*j),S=new R.Parser(g,v+b+16+6*j),T=v+b+16+8*j,E=0;E>4,s=15&s;if(15==i)break;if(o+=n[i],15==s)break;o+=n[s]}return parseFloat(o)}if(32<=t&&t<=246)return t-139;if(247<=t&&t<=250)return 256*(t-247)+e.parseByte()+108;if(251<=t&&t<=254)return 256*-(t-251)-e.parseByte()-108;throw new Error("Invalid b0 "+t)}function Ie(e,t,r){var o=new R.Parser(e,t=void 0!==t?t:0),n=[],s=[];for(r=void 0!==r?r:e.length;o.relativeOffset>1,E.length=0,k=!0}return function e(t){for(var r,o,n,s,i,a,l,u,c,d,h,f,p=0;pMath.abs(f-A)?C=h+E.shift():A=f+E.shift(),T.curveTo(v,b,j,_,l,u),T.curveTo(c,d,h,f,C,A);break;default:console.log("Glyph "+g.index+": unknown operator 1200"+m),E.length=0}break;case 14:0>3;break;case 21:2>16),p+=2;break;case 29:i=E.pop()+y.gsubrsBias,(a=y.gsubrs[i])&&e(a);break;case 30:for(;0=r.begin&&e=c.length&&(s=o.parseChar(),r.names.push(o.parseString(s)));break;case 2.5:r.numberOfGlyphs=o.parseUShort(),r.offset=new Array(r.numberOfGlyphs);for(var a=0;at.value.tag?1:-1}),t.fields=t.fields.concat(o),t.fields=t.fields.concat(n),t}function xt(e,t,r){for(var o=0;o 123 are reserved for internal usage");f|=1<>>1,s=e[n].tag;if(s===t)return n;s>>1,s=e[n];if(s===t)return n;s>>1,i=(n=e[s]).start;if(i===t)return n;i(n=e[r-1]).end?0:n}function Mt(e,t){this.font=e,this.tableName=t}function kt(e){Mt.call(this,e,"gpos")}function i(e){Mt.call(this,e,"gsub")}function Ot(e,t,r){for(var o=e.subtables,n=0;nt.points.length-1||o.matchedPoints[1]>n.points.length-1)throw Error("Matched points out of range in "+t.name);var i=t.points[o.matchedPoints[0]],a=n.points[o.matchedPoints[1]],o={xScale:o.xScale,scale01:o.scale01,scale10:o.scale10,yScale:o.yScale,dx:0,dy:0},a=Lt([a],o)[0];o.dx=i.x-a.x,o.dy=i.y-a.y,s=Lt(n.points,o)}t.points=t.points.concat(s)}}return Rt(t.points)}(kt.prototype=Mt.prototype={searchTag:St,binSearch:Tt,getTable:function(e){var t=this.font.tables[this.tableName];return t=!t&&e?this.font.tables[this.tableName]=this.createDefaultTable():t},getScriptNames:function(){var e=this.getTable();return e?e.scripts.map(function(e){return e.tag}):[]},getDefaultScriptName:function(){var e=this.getTable();if(e){for(var t=!1,r=0;r=i[t-1].tag,"Features must be added in alphabetical order."),i.push(n={tag:r,feature:{params:0,lookupListIndexes:[]}}),s.push(t),n.feature}},getLookupTables:function(e,t,r,o,n){var e=this.getFeatureTable(e,t,r,n),s=[];if(e){for(var i,a=e.lookupListIndexes,l=this.font.tables[this.tableName].lookups,u=0;u",s),t.stack.push(Math.round(64*s))}function hr(e,t){var r=t.stack,o=r.pop(),n=t.fv,s=t.pv,i=t.ppem,a=t.deltaBase+16*(e-1),l=t.deltaShift,u=t.z0;j.DEBUG&&console.log(t.step,"DELTAP["+e+"]",o,r);for(var c=0;c>4)===i&&(0<=(h=(15&h)-8)&&h++,j.DEBUG&&console.log(t.step,"DELTAPFIX",d,"by",h*l),d=u[d],n.setRelative(d,d,h*l,s))}}function fr(e,t){var r=t.stack,o=r.pop();j.DEBUG&&console.log(t.step,"ROUND[]"),r.push(64*t.round(o/64))}function pr(e,t){var r=t.stack,o=r.pop(),n=t.ppem,s=t.deltaBase+16*(e-1),i=t.deltaShift;j.DEBUG&&console.log(t.step,"DELTAC["+e+"]",o,r);for(var a=0;a>4)===n&&(0<=(u=(15&u)-8)&&u++,u=u*i,j.DEBUG&&console.log(t.step,"DELTACFIX",l,"by",u),t.cvt[l]+=u)}}function mr(e,t){var r,o=t.stack,n=o.pop(),o=o.pop(),s=t.z2[n],i=t.z1[o];j.DEBUG&&console.log(t.step,"SDPVTL["+e+"]",n,o),n=e?(r=s.y-i.y,i.x-s.x):(r=i.x-s.x,i.y-s.y),t.dpv=qt(r,n)}function k(e,t){var r=t.stack,o=t.prog,n=t.ip;j.DEBUG&&console.log(t.step,"PUSHB["+e+"]");for(var s=0;s":"_")+(o?"R":"_")+(0===n?"Gr":1===n?"Bl":2===n?"Wh":"")+"]",e?u+"("+s.cvt[u]+","+a+")":"",l,"(d =",i,"->",y*m,")"),s.rp1=s.rp0,s.rp2=l,t&&(s.rp0=l)}Ft.prototype.exec=function(e,t){if("number"!=typeof t)throw new Error("Point size is not a number!");if(!(2",o),a.interpolate(d,s,i,l),a.touch(d)}e.loop=1},lr.bind(void 0,0),lr.bind(void 0,1),function(e){for(var t=e.stack,r=e.rp0,o=e.z0[r],n=e.loop,s=e.fv,i=e.pv,a=e.z1;n--;){var l=t.pop(),u=a[l];j.DEBUG&&console.log(e.step,(1'.concat(n,"").concat(t,""),this.dummyDOM||(this.dummyDOM=document.getElementById(o).parentNode),this.descriptions?this.descriptions.fallbackElements||(this.descriptions.fallbackElements={}):this.descriptions={fallbackElements:{}},this.descriptions.fallbackElements[e]?this.descriptions.fallbackElements[e].innerHTML!==n&&(this.descriptions.fallbackElements[e].innerHTML=n):this._describeElementHTML("fallback",e,n),r===this.LABEL&&(this.descriptions.labelElements||(this.descriptions.labelElements={}),this.descriptions.labelElements[e]?this.descriptions.labelElements[e].innerHTML!==n&&(this.descriptions.labelElements[e].innerHTML=n):this._describeElementHTML("label",e,n)))},s.default.prototype._describeHTML=function(e,t){var r,o=this.canvas.id;"fallback"===e?(this.dummyDOM.querySelector("#".concat(o+i))?this.dummyDOM.querySelector("#"+o+l).insertAdjacentHTML("beforebegin",'

')):(r='

'),this.dummyDOM.querySelector("#".concat(o,"accessibleOutput"))?this.dummyDOM.querySelector("#".concat(o,"accessibleOutput")).insertAdjacentHTML("beforebegin",r):this.dummyDOM.querySelector("#".concat(o)).innerHTML=r),this.descriptions.fallback=this.dummyDOM.querySelector("#".concat(o).concat(a)),this.descriptions.fallback.innerHTML=t):"label"===e&&(this.dummyDOM.querySelector("#".concat(o+u))?this.dummyDOM.querySelector("#".concat(o+d))&&this.dummyDOM.querySelector("#".concat(o+d)).insertAdjacentHTML("beforebegin",'

')):(r='

'),this.dummyDOM.querySelector("#".concat(o,"accessibleOutputLabel"))?this.dummyDOM.querySelector("#".concat(o,"accessibleOutputLabel")).insertAdjacentHTML("beforebegin",r):this.dummyDOM.querySelector("#"+o).insertAdjacentHTML("afterend",r)),this.descriptions.label=this.dummyDOM.querySelector("#"+o+c),this.descriptions.label.innerHTML=t)},s.default.prototype._describeElementHTML=function(e,t,r){var o,n=this.canvas.id;"fallback"===e?(this.dummyDOM.querySelector("#".concat(n+i))?this.dummyDOM.querySelector("#"+n+l)||this.dummyDOM.querySelector("#"+n+a).insertAdjacentHTML("afterend",'
Canvas elements and their descriptions
')):(o='
Canvas elements and their descriptions
'),this.dummyDOM.querySelector("#".concat(n,"accessibleOutput"))?this.dummyDOM.querySelector("#".concat(n,"accessibleOutput")).insertAdjacentHTML("beforebegin",o):this.dummyDOM.querySelector("#"+n).innerHTML=o),(o=document.createElement("tr")).id=n+"_fte_"+t,this.dummyDOM.querySelector("#"+n+l).appendChild(o),this.descriptions.fallbackElements[t]=this.dummyDOM.querySelector("#".concat(n).concat("_fte_").concat(t)),this.descriptions.fallbackElements[t].innerHTML=r):"label"===e&&(this.dummyDOM.querySelector("#".concat(n+u))?this.dummyDOM.querySelector("#".concat(n+d))||this.dummyDOM.querySelector("#"+n+c).insertAdjacentHTML("afterend",'
')):(o='
'),this.dummyDOM.querySelector("#".concat(n,"accessibleOutputLabel"))?this.dummyDOM.querySelector("#".concat(n,"accessibleOutputLabel")).insertAdjacentHTML("beforebegin",o):this.dummyDOM.querySelector("#"+n).insertAdjacentHTML("afterend",o)),(e=document.createElement("tr")).id=n+"_lte_"+t,this.dummyDOM.querySelector("#"+n+d).appendChild(e),this.descriptions.labelElements[t]=this.dummyDOM.querySelector("#".concat(n).concat("_lte_").concat(t)),this.descriptions.labelElements[t].innerHTML=r)};e=s.default;r.default=e},{"../core/main":283,"core-js/modules/es.array.concat":153,"core-js/modules/es.regexp.exec":195,"core-js/modules/es.string.ends-with":198,"core-js/modules/es.string.replace":204}],264:[function(e,t,r){"use strict";e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.from"),e("core-js/modules/es.array.map"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.from"),e("core-js/modules/es.array.map"),e("core-js/modules/es.string.iterator"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;e=(e=e("../core/main"))&&e.__esModule?e:{default:e};e.default.prototype._updateGridOutput=function(e){var t,r,o,n;this.dummyDOM.querySelector("#".concat(e,"_summary"))&&(t=this._accessibleOutputs[e],o=function(e,t,r,o){t="".concat(t," canvas, ").concat(r," by ").concat(o," pixels, contains ").concat(e[0]);t=(1===e[0]?"".concat(t," shape: "):"".concat(t," shapes: ")).concat(e[1]);return t}((r=function(e,t){var r,o="",n="",s=0;for(r in t){var i,a=0;for(i in t[r]){var l='
  • ').concat(t[r][i].color," ").concat(r,",");"line"===r?l+=" location = ".concat(t[r][i].pos,", length = ").concat(t[r][i].length," pixels"):(l+=" location = ".concat(t[r][i].pos),"point"!==r&&(l+=", area = ".concat(t[r][i].area," %")),l+="
  • "),o+=l,a++,s++}n=1').concat(t[r][a].color," ").concat(r,"
    "):'').concat(t[r][a].color," ").concat(r," midpoint"),t[r][a].loc.locY";s=s+c+""}return s}(e,this.ingredients.shapes),o!==t.summary.innerHTML&&(t.summary.innerHTML=o),n!==t.map.innerHTML&&(t.map.innerHTML=n),r.details!==t.shapeDetails.innerHTML&&(t.shapeDetails.innerHTML=r.details),this._accessibleOutputs[e]=t)};e=e.default;r.default=e},{"../core/main":283,"core-js/modules/es.array.concat":153,"core-js/modules/es.array.from":162,"core-js/modules/es.array.map":168,"core-js/modules/es.string.iterator":200}],265:[function(e,t,r){"use strict";e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.fill"),e("core-js/modules/es.array.from"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.map"),e("core-js/modules/es.number.to-fixed"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.string.iterator"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.fill"),e("core-js/modules/es.array.map"),e("core-js/modules/es.number.to-fixed"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var o=(e=e("../core/main"))&&e.__esModule?e:{default:e};function l(e){return function(e){if(Array.isArray(e)){for(var t=0,r=new Array(e.length);t')):this.dummyDOM.querySelector("#".concat(s)).innerHTML='
    '))):"Label"===t&&(r=s+e+(i=t),this.dummyDOM.querySelector("#".concat(o=s+"accessibleOutput"+t))||(this.dummyDOM.querySelector("#".concat(s,"_Label"))?this.dummyDOM.querySelector("#".concat(s,"_Label")):this.dummyDOM.querySelector("#".concat(s))).insertAdjacentHTML("afterend",'
    '))),this._accessibleOutputs[r]={},"textOutput"===e?(i="#".concat(s,"gridOutput").concat(i),n='
    Text Output

      '),this.dummyDOM.querySelector(i)?this.dummyDOM.querySelector(i).insertAdjacentHTML("beforebegin",n):this.dummyDOM.querySelector("#".concat(o)).innerHTML=n,this._accessibleOutputs[r].list=this.dummyDOM.querySelector("#".concat(r,"_list"))):"gridOutput"===e&&(i="#".concat(s,"textOutput").concat(i),n='
      Grid Output

        '),this.dummyDOM.querySelector(i)?this.dummyDOM.querySelector(i).insertAdjacentHTML("afterend",n):this.dummyDOM.querySelector("#".concat(o)).innerHTML=n,this._accessibleOutputs[r].map=this.dummyDOM.querySelector("#".concat(r,"_map"))),this._accessibleOutputs[r].shapeDetails=this.dummyDOM.querySelector("#".concat(r,"_shapeDetails")),this._accessibleOutputs[r].summary=this.dummyDOM.querySelector("#".concat(r,"_summary"))},o.default.prototype._updateAccsOutput=function(){var e=this.canvas.id;JSON.stringify(this.ingredients.shapes)===this.ingredients.pShapes&&this.ingredients.colors.background===this.ingredients.pBackground||(this.ingredients.pShapes=JSON.stringify(this.ingredients.shapes),this._accessibleOutputs.text&&this._updateTextOutput(e+"textOutput"),this._accessibleOutputs.grid&&this._updateGridOutput(e+"gridOutput"),this._accessibleOutputs.textLabel&&this._updateTextOutput(e+"textOutputLabel"),this._accessibleOutputs.gridLabel&&this._updateGridOutput(e+"gridOutputLabel"))},o.default.prototype._accsBackground=function(e){this.ingredients.pShapes=JSON.stringify(this.ingredients.shapes),this.ingredients.pBackground=this.ingredients.colors.background,this.ingredients.shapes={},this.ingredients.colors.backgroundRGBA!==e&&(this.ingredients.colors.backgroundRGBA=e,this.ingredients.colors.background=this._rgbColorName(e))},o.default.prototype._accsCanvasColors=function(e,t){"fill"===e?this.ingredients.colors.fillRGBA!==t&&(this.ingredients.colors.fillRGBA=t,this.ingredients.colors.fill=this._rgbColorName(t)):"stroke"===e&&this.ingredients.colors.strokeRGBA!==t&&(this.ingredients.colors.strokeRGBA=t,this.ingredients.colors.stroke=this._rgbColorName(t))},o.default.prototype._accsOutput=function(e,t){"ellipse"===e&&t[2]===t[3]?e="circle":"rectangle"===e&&t[2]===t[3]&&(e="square");var r,o,n={},s=!0,i=function(e,t){var r;e="rectangle"===e||"ellipse"===e||"arc"===e||"circle"===e||"square"===e?(r=Math.round(t[0]+t[2]/2),Math.round(t[1]+t[3]/2)):"triangle"===e?(r=(t[0]+t[2]+t[4])/3,(t[1]+t[3]+t[5])/3):"quadrilateral"===e?(r=(t[0]+t[2]+t[4]+t[6])/4,(t[1]+t[3]+t[5]+t[7])/4):"line"===e?(r=(t[0]+t[2])/2,(t[1]+t[3])/2):(r=t[0],t[1]);return[r,e]}(e,t);if("line"===e?(n.color=this.ingredients.colors.stroke,n.length=Math.round(this.dist(t[0],t[1],t[2],t[3])),r=this._getPos(t[0],[1]),o=this._getPos(t[2],[3]),n.loc=u(i,this.width,this.height),n.pos=r===o?"at ".concat(r):"from ".concat(r," to ").concat(o)):("point"===e?n.color=this.ingredients.colors.stroke:(n.color=this.ingredients.colors.fill,n.area=this._getArea(e,t)),n.pos=this._getPos.apply(this,l(i)),n.loc=u(i,this.width,this.height)),this.ingredients.shapes[e]){if(this.ingredients.shapes[e]!==[n]){for(var a in this.ingredients.shapes[e])JSON.stringify(this.ingredients.shapes[e][a])===JSON.stringify(n)&&(s=!1);!0===s&&this.ingredients.shapes[e].push(n)}}else this.ingredients.shapes[e]=[n]},o.default.prototype._getPos=function(e,t){var e=new DOMPointReadOnly(e,t),t=this._renderer.isP3D?new DOMMatrix(this._renderer.uMVMatrix.mat4):this.drawingContext.getTransform(),e=e.matrixTransform(t),t=e.x,e=e.y,r=this.width*this._pixelDensity,o=this.height*this._pixelDensity;return t<.4*r?e<.4*o?"top left":.6*oMath.PI?n+=o:n-=o)):"ellipse"===e||"circle"===e?n=3.14*t[2]/2*t[3]/2:"line"===e||"point"===e?n=0:"quadrilateral"===e?n=Math.abs((t[6]+t[0])*(t[7]-t[1])+(t[0]+t[2])*(t[1]-t[3])+(t[2]+t[4])*(t[3]-t[5])+(t[4]+t[6])*(t[5]-t[7]))/2:"rectangle"===e||"square"===e?n=t[2]*t[3]:"triangle"===e&&(n=Math.abs(t[0]*(t[3]-t[5])+t[2]*(t[5]-t[1])+t[4]*(t[1]-t[3]))/2),this.width*this._pixelDensity),i=this.height*this._pixelDensity,a=[new DOMPoint(0,0),new DOMPoint(s,0),new DOMPoint(s,i),new DOMPoint(0,i)],l=(this._renderer.isP3D?new DOMMatrix(this._renderer.uMVMatrix.mat4):this.drawingContext.getTransform()).inverse(),u=a.map(function(e){return e.matrixTransform(l)}),c=Math.abs((u[3].x+u[0].x)*(u[3].y-u[0].y)+(u[0].x+u[1].x)*(u[0].y-u[1].y)+(u[1].x+u[2].x)*(u[1].y-u[2].y)+(u[2].x+u[3].x)*(u[2].y-u[3].y))/2;return Math.round(100*n/c)};e=o.default;r.default=e},{"../core/main":283,"core-js/modules/es.array.concat":153,"core-js/modules/es.array.fill":156,"core-js/modules/es.array.from":162,"core-js/modules/es.array.iterator":165,"core-js/modules/es.array.map":168,"core-js/modules/es.number.to-fixed":182,"core-js/modules/es.object.to-string":190,"core-js/modules/es.regexp.to-string":196,"core-js/modules/es.string.iterator":200,"core-js/modules/es.symbol":212,"core-js/modules/es.symbol.description":210,"core-js/modules/es.symbol.iterator":211,"core-js/modules/web.dom-collections.iterator":246}],266:[function(e,t,r){"use strict";e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.concat"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;e=(e=e("../core/main"))&&e.__esModule?e:{default:e};e.default.prototype._updateTextOutput=function(e){var t,r,o,n;this.dummyDOM.querySelector("#".concat(e,"_summary"))&&(t=this._accessibleOutputs[e],o=function(e,t,r,o){r="Your output is a, ".concat(r," by ").concat(o," pixels, ").concat(t," canvas containing the following");r=1===e?"".concat(r," shape:"):"".concat(r," ").concat(e," shapes:");return r}((r=function(e,t){var r,o="",n=0;for(r in t)for(var s in t[r]){var i='
      • ').concat(t[r][s].color," ").concat(r,"");"line"===r?i+=", ".concat(t[r][s].pos,", ").concat(t[r][s].length," pixels long.
      • "):(i+=", at ".concat(t[r][s].pos),"point"!==r&&(i+=", covering ".concat(t[r][s].area,"% of the canvas")),i+="."),o+=i,n++}return{numShapes:n,listShapes:o}}(e,this.ingredients.shapes)).numShapes,this.ingredients.colors.background,this.width,this.height),n=function(e,t){var r,o="",n=0;for(r in t)for(var s in t[r]){var i='').concat(t[r][s].color," ").concat(r,"");"line"===r?i+="location = ".concat(t[r][s].pos,"length = ").concat(t[r][s].length," pixels"):(i+="location = ".concat(t[r][s].pos,""),"point"!==r&&(i+=" area = ".concat(t[r][s].area,"%")),i+=""),o+=i,n++}return o}(e,this.ingredients.shapes),o!==t.summary.innerHTML&&(t.summary.innerHTML=o),r.listShapes!==t.list.innerHTML&&(t.list.innerHTML=r.listShapes),n!==t.shapeDetails.innerHTML&&(t.shapeDetails.innerHTML=n),this._accessibleOutputs[e]=t)};e=e.default;r.default=e},{"../core/main":283,"core-js/modules/es.array.concat":153}],267:[function(e,t,r){"use strict";var o=(o=e("./core/main"))&&o.__esModule?o:{default:o};e("./core/constants"),e("./core/environment"),e("./core/friendly_errors/stacktrace"),e("./core/friendly_errors/validate_params"),e("./core/friendly_errors/file_errors"),e("./core/friendly_errors/fes_core"),e("./core/friendly_errors/sketch_reader"),e("./core/helpers"),e("./core/legacy"),e("./core/preload"),e("./core/p5.Element"),e("./core/p5.Graphics"),e("./core/p5.Renderer"),e("./core/p5.Renderer2D"),e("./core/rendering"),e("./core/shim"),e("./core/structure"),e("./core/transform"),e("./core/shape/2d_primitives"),e("./core/shape/attributes"),e("./core/shape/curves"),e("./core/shape/vertex"),e("./accessibility/outputs"),e("./accessibility/textOutput"),e("./accessibility/gridOutput"),e("./accessibility/color_namer"),e("./color/color_conversion"),e("./color/creating_reading"),e("./color/p5.Color"),e("./color/setting"),e("./data/p5.TypedDict"),e("./data/local_storage.js"),e("./dom/dom"),e("./accessibility/describe"),e("./events/acceleration"),e("./events/keyboard"),e("./events/mouse"),e("./events/touch"),e("./image/filters"),e("./image/image"),e("./image/loading_displaying"),e("./image/p5.Image"),e("./image/pixels"),e("./io/files"),e("./io/p5.Table"),e("./io/p5.TableRow"),e("./io/p5.XML"),e("./math/calculation"),e("./math/math"),e("./math/noise"),e("./math/p5.Vector"),e("./math/random"),e("./math/trigonometry"),e("./typography/attributes"),e("./typography/loading_displaying"),e("./typography/p5.Font"),e("./utilities/array_functions"),e("./utilities/conversion"),e("./utilities/string_functions"),e("./utilities/time_date"),e("./webgl/3d_primitives"),e("./webgl/interaction"),e("./webgl/light"),e("./webgl/loading"),e("./webgl/material"),e("./webgl/p5.Camera"),e("./webgl/p5.DataArray"),e("./webgl/p5.Geometry"),e("./webgl/p5.Matrix"),e("./webgl/p5.Quat"),e("./webgl/p5.RendererGL.Immediate"),e("./webgl/p5.RendererGL"),e("./webgl/p5.RendererGL.Retained"),e("./webgl/p5.Framebuffer"),e("./webgl/p5.Shader"),e("./webgl/p5.RenderBuffer"),e("./webgl/p5.Texture"),e("./webgl/text"),e("./core/init"),t.exports=o.default},{"./accessibility/color_namer":262,"./accessibility/describe":263,"./accessibility/gridOutput":264,"./accessibility/outputs":265,"./accessibility/textOutput":266,"./color/color_conversion":268,"./color/creating_reading":269,"./color/p5.Color":270,"./color/setting":271,"./core/constants":272,"./core/environment":273,"./core/friendly_errors/fes_core":274,"./core/friendly_errors/file_errors":275,"./core/friendly_errors/sketch_reader":276,"./core/friendly_errors/stacktrace":277,"./core/friendly_errors/validate_params":278,"./core/helpers":279,"./core/init":280,"./core/legacy":282,"./core/main":283,"./core/p5.Element":284,"./core/p5.Graphics":285,"./core/p5.Renderer":286,"./core/p5.Renderer2D":287,"./core/preload":288,"./core/rendering":289,"./core/shape/2d_primitives":290,"./core/shape/attributes":291,"./core/shape/curves":292,"./core/shape/vertex":293,"./core/shim":294,"./core/structure":295,"./core/transform":296,"./data/local_storage.js":297,"./data/p5.TypedDict":298,"./dom/dom":299,"./events/acceleration":300,"./events/keyboard":301,"./events/mouse":302,"./events/touch":303,"./image/filters":304,"./image/image":305,"./image/loading_displaying":306,"./image/p5.Image":307,"./image/pixels":308,"./io/files":309,"./io/p5.Table":310,"./io/p5.TableRow":311,"./io/p5.XML":312,"./math/calculation":313,"./math/math":314,"./math/noise":315,"./math/p5.Vector":316,"./math/random":317,"./math/trigonometry":318,"./typography/attributes":319,"./typography/loading_displaying":320,"./typography/p5.Font":321,"./utilities/array_functions":322,"./utilities/conversion":323,"./utilities/string_functions":324,"./utilities/time_date":325,"./webgl/3d_primitives":326,"./webgl/interaction":328,"./webgl/light":329,"./webgl/loading":330,"./webgl/material":331,"./webgl/p5.Camera":332,"./webgl/p5.DataArray":333,"./webgl/p5.Framebuffer":334,"./webgl/p5.Geometry":335,"./webgl/p5.Matrix":336,"./webgl/p5.Quat":337,"./webgl/p5.RenderBuffer":338,"./webgl/p5.RendererGL":341,"./webgl/p5.RendererGL.Immediate":339,"./webgl/p5.RendererGL.Retained":340,"./webgl/p5.Shader":342,"./webgl/p5.Texture":343,"./webgl/text":344}],268:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;e=(e=e("../core/main"))&&e.__esModule?e:{default:e};e.default.ColorConversion={_hsbaToHSLA:function(e){var t=e[0],r=e[1],o=e[2],n=(2-r)*o/2;return 0!=n&&(1==n?r=0:n<.5?r/=2-r:r=r*o/(2-2*n)),[t,r,n,e[3]]},_hsbaToRGBA:function(e){var t,r,o,n,s,i=6*e[0],a=e[1],l=e[2];return 0===a?[l,l,l,e[3]]:(r=l*(1-a),o=l*(1-a*(i-(t=Math.floor(i)))),a=l*(1-a*(1+t-i)),i=1===t?(n=o,s=l,r):2===t?(n=r,s=l,a):3===t?(n=r,s=o,l):4===t?(n=a,s=r,l):5===t?(n=l,s=r,o):(n=l,s=a,r),[n,s,i,e[3]])},_hslaToHSBA:function(e){var t=e[0],r=e[1],o=e[2],n=o<.5?(1+r)*o:o+r-o*r;return[t,r=2*(n-o)/n,n,e[3]]},_hslaToRGBA:function(e){var t,r=6*e[0],o=e[1],n=e[2];return 0===o?[n,n,n,e[3]]:[(t=function(e,t,r){return e<0?e+=6:6<=e&&(e-=6),e<1?t+(r-t)*e:e<3?r:e<4?t+(r-t)*(4-e):t})(2+r,o=2*n-(n=n<.5?(1+o)*n:n+o-n*o),n),t(r,o,n),t(r-2,o,n),e[3]]},_rgbaToHSBA:function(e){var t,r,o=e[0],n=e[1],s=e[2],i=Math.max(o,n,s),a=i-Math.min(o,n,s);return 0==a?r=t=0:(r=a/i,o===i?t=(n-s)/a:n===i?t=2+(s-o)/a:s===i&&(t=4+(o-n)/a),t<0?t+=6:6<=t&&(t-=6)),[t/6,r,i,e[3]]},_rgbaToHSLA:function(e){var t,r,o=e[0],n=e[1],s=e[2],i=Math.max(o,n,s),a=Math.min(o,n,s),l=i+a,a=i-a;return 0==a?r=t=0:(r=l<1?a/l:a/(2-l),o===i?t=(n-s)/a:n===i?t=2+(s-o)/a:s===i&&(t=4+(o-n)/a),t<0?t+=6:6<=t&&(t-=6)),[t/6,r,l/2,e[3]]}};e=e.default.ColorConversion;r.default=e},{"../core/main":283}],269:[function(e,t,r){"use strict";function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e){return(i="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":o(e)})(e)}e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.map"),e("core-js/modules/es.object.get-own-property-descriptor"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.weak-map"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.array.map"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var l=(n=e("../core/main"))&&n.__esModule?n:{default:n},u=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==i(e)&&"function"!=typeof e)return{default:e};var t=a();if(t&&t.has(e))return t.get(e);var r,o={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(r in e){var s;Object.prototype.hasOwnProperty.call(e,r)&&((s=n?Object.getOwnPropertyDescriptor(e,r):null)&&(s.get||s.set)?Object.defineProperty(o,r,s):o[r]=e[r])}o.default=e,t&&t.set(e,o);return o}(e("../core/constants"));function a(){var e;return"function"!=typeof WeakMap?null:(e=new WeakMap,a=function(){return e},e)}e("./p5.Color"),e("../core/friendly_errors/validate_params"),e("../core/friendly_errors/file_errors"),e("../core/friendly_errors/fes_core"),l.default.prototype.alpha=function(e){return l.default._validateParameters("alpha",arguments),this.color(e)._getAlpha()},l.default.prototype.blue=function(e){return l.default._validateParameters("blue",arguments),this.color(e)._getBlue()},l.default.prototype.brightness=function(e){return l.default._validateParameters("brightness",arguments),this.color(e)._getBrightness()},l.default.prototype.color=function(){for(var e,t=arguments.length,r=new Array(t),o=0;os[0]?s[0]+=1:n[0]+=1),1<=(o=this.lerp(n[0],s[0],r))&&--o),e=this.lerp(n[1],s[1],r),t=this.lerp(n[2],s[2],r),n=this.lerp(n[3],s[3],r),o*=a[i][0],e*=a[i][1],t*=a[i][2],n*=a[i][3],this.color(o,e,t,n)},l.default.prototype.lightness=function(e){return l.default._validateParameters("lightness",arguments),this.color(e)._getLightness()},l.default.prototype.red=function(e){return l.default._validateParameters("red",arguments),this.color(e)._getRed()},l.default.prototype.saturation=function(e){return l.default._validateParameters("saturation",arguments),this.color(e)._getSaturation()};var n=l.default;r.default=n},{"../core/constants":272,"../core/friendly_errors/fes_core":274,"../core/friendly_errors/file_errors":275,"../core/friendly_errors/validate_params":278,"../core/main":283,"./p5.Color":270,"core-js/modules/es.array.iterator":165,"core-js/modules/es.array.map":168,"core-js/modules/es.object.get-own-property-descriptor":186,"core-js/modules/es.object.to-string":190,"core-js/modules/es.string.iterator":200,"core-js/modules/es.symbol":212,"core-js/modules/es.symbol.description":210,"core-js/modules/es.symbol.iterator":211,"core-js/modules/es.weak-map":244,"core-js/modules/web.dom-collections.iterator":246}],270:[function(e,t,r){"use strict";function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e){return(i="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":o(e)})(e)}e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.includes"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.map"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.object.get-own-property-descriptor"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.regexp.constructor"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.string.includes"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.string.trim"),e("core-js/modules/es.weak-map"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.array.includes"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.map"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.regexp.constructor"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.string.includes"),e("core-js/modules/es.string.trim"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n=s(e("../core/main")),d=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==i(e)&&"function"!=typeof e)return{default:e};var t=a();if(t&&t.has(e))return t.get(e);var r,o={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(r in e){var s;Object.prototype.hasOwnProperty.call(e,r)&&((s=n?Object.getOwnPropertyDescriptor(e,r):null)&&(s.get||s.set)?Object.defineProperty(o,r,s):o[r]=e[r])}o.default=e,t&&t.set(e,o);return o}(e("../core/constants")),h=s(e("./color_conversion"));function a(){var e;return"function"!=typeof WeakMap?null:(e=new WeakMap,a=function(){return e},e)}function s(e){return e&&e.__esModule?e:{default:e}}function l(e,t){for(var r=0;r"].indexOf(r[0])?void 0:r[0],lineNumber:r[1],columnNumber:r[2],source:e}},this)},parseFFOrSafari:function(e){return e.stack.split("\n").filter(function(e){return!e.match(o)},this).map(function(e){var t,r;return-1===(e=-1 eval")?e.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1"):e).indexOf("@")&&-1===e.indexOf(":")?{functionName:e}:{functionName:(r=e.match(t=/((.*".+"[^@]*)?[^@]*)(?:@)/))&&r[1]?r[1]:void 0,fileName:(r=this.extractLocation(e.replace(t,"")))[0],lineNumber:r[1],columnNumber:r[2],source:e}},this)},parseOpera:function(e){return!e.stacktrace||-1e.stacktrace.split("\n").length?this.parseOpera9(e):e.stack?this.parseOpera11(e):this.parseOpera10(e)},parseOpera9:function(e){for(var t=/Line (\d+).*script (?:in )?(\S+)/i,r=e.message.split("\n"),o=[],n=2,s=r.length;n/,"$2").replace(/\([^)]*\)/g,"")||void 0,args:void 0===(t=r.match(/\(([^)]*)\)/)?r.replace(/^[^(]+\(([^)]*)\)$/,"$1"):t)||"[arguments not available]"===t?void 0:t.split(","),fileName:o[0],lineNumber:o[1],columnNumber:o[2],source:e}},this)}}}e.default._getErrorStackParser=function(){return new o};e=e.default;r.default=e},{"../main":283,"core-js/modules/es.array.filter":157,"core-js/modules/es.array.index-of":164,"core-js/modules/es.array.join":166,"core-js/modules/es.array.map":168,"core-js/modules/es.array.slice":169,"core-js/modules/es.regexp.exec":195,"core-js/modules/es.string.match":201,"core-js/modules/es.string.replace":204,"core-js/modules/es.string.split":206}],278:[function(e,t,r){"use strict";function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.for-each"),e("core-js/modules/es.array.includes"),e("core-js/modules/es.array.index-of"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.last-index-of"),e("core-js/modules/es.array.map"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.function.name"),e("core-js/modules/es.map"),e("core-js/modules/es.number.constructor"),e("core-js/modules/es.object.get-own-property-descriptor"),e("core-js/modules/es.object.get-prototype-of"),e("core-js/modules/es.object.keys"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.reflect.construct"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.set"),e("core-js/modules/es.string.includes"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.string.split"),e("core-js/modules/es.weak-map"),e("core-js/modules/web.dom-collections.for-each"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.for-each"),e("core-js/modules/es.array.includes"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.last-index-of"),e("core-js/modules/es.array.map"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.function.name"),e("core-js/modules/es.number.constructor"),e("core-js/modules/es.object.keys"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.set"),e("core-js/modules/es.string.includes"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.string.split"),e("core-js/modules/web.dom-collections.for-each"),e("core-js/modules/web.dom-collections.iterator"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n=(n=e("../main"))&&n.__esModule?n:{default:n};(function(e){if(e&&e.__esModule)return;if(null===e||"object"!==a(e)&&"function"!=typeof e)return;var t=i();if(t&&t.has(e))return t.get(e);var r,o={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(r in e){var s;Object.prototype.hasOwnProperty.call(e,r)&&((s=n?Object.getOwnPropertyDescriptor(e,r):null)&&(s.get||s.set)?Object.defineProperty(o,r,s):o[r]=e[r])}o.default=e,t&&t.set(e,o)})(e("../constants")),e("../internationalization");function i(){var e;return"function"!=typeof WeakMap?null:(e=new WeakMap,i=function(){return e},e)}function a(e){return(a="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":o(e)})(e)}n.default._validateParameters=n.default._clearValidateParamsCache=function(){};e=n.default;r.default=e},{"../../../docs/parameterData.json":void 0,"../constants":272,"../internationalization":281,"../main":283,"core-js/modules/es.array.concat":153,"core-js/modules/es.array.for-each":161,"core-js/modules/es.array.includes":163,"core-js/modules/es.array.index-of":164,"core-js/modules/es.array.iterator":165,"core-js/modules/es.array.join":166,"core-js/modules/es.array.last-index-of":167,"core-js/modules/es.array.map":168,"core-js/modules/es.array.slice":169,"core-js/modules/es.function.name":174,"core-js/modules/es.map":175,"core-js/modules/es.number.constructor":179,"core-js/modules/es.object.get-own-property-descriptor":186,"core-js/modules/es.object.get-prototype-of":188,"core-js/modules/es.object.keys":189,"core-js/modules/es.object.to-string":190,"core-js/modules/es.reflect.construct":192,"core-js/modules/es.regexp.exec":195,"core-js/modules/es.regexp.to-string":196,"core-js/modules/es.set":197,"core-js/modules/es.string.includes":199,"core-js/modules/es.string.iterator":200,"core-js/modules/es.string.split":206,"core-js/modules/es.symbol":212,"core-js/modules/es.symbol.description":210,"core-js/modules/es.symbol.iterator":211,"core-js/modules/es.weak-map":244,"core-js/modules/web.dom-collections.for-each":245,"core-js/modules/web.dom-collections.iterator":246}],279:[function(e,t,r){"use strict";function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e){return(i="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":o(e)})(e)}e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.object.get-own-property-descriptor"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.weak-map"),e("core-js/modules/web.dom-collections.iterator"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var s=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==i(e)&&"function"!=typeof e)return{default:e};var t=a();if(t&&t.has(e))return t.get(e);var r,o={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(r in e){var s;Object.prototype.hasOwnProperty.call(e,r)&&((s=n?Object.getOwnPropertyDescriptor(e,r):null)&&(s.get||s.set)?Object.defineProperty(o,r,s):o[r]=e[r])}o.default=e,t&&t.set(e,o);return o}(e("./constants"));function a(){var e;return"function"!=typeof WeakMap?null:(e=new WeakMap,a=function(){return e},e)}r.default={modeAdjust:function(e,t,r,o,n){return n===s.CORNER?{x:e,y:t,w:r,h:o}:n===s.CORNERS?{x:e,y:t,w:r-e,h:o-t}:n===s.RADIUS?{x:e-r,y:t-o,w:2*r,h:2*o}:n===s.CENTER?{x:e-.5*r,y:t-.5*o,w:r,h:o}:void 0}}},{"./constants":272,"core-js/modules/es.array.iterator":165,"core-js/modules/es.object.get-own-property-descriptor":186,"core-js/modules/es.object.to-string":190,"core-js/modules/es.string.iterator":200,"core-js/modules/es.symbol":212,"core-js/modules/es.symbol.description":210,"core-js/modules/es.symbol.iterator":211,"core-js/modules/es.weak-map":244,"core-js/modules/web.dom-collections.iterator":246}],280:[function(e,t,r){"use strict";e("core-js/modules/es.array.iterator"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.promise"),e("core-js/modules/es.string.iterator"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.promise"),e("core-js/modules/es.string.iterator"),e("core-js/modules/web.dom-collections.iterator");var o=(n=e("../core/main"))&&n.__esModule?n:{default:n};e("./internationalization");var n=Promise.resolve();Promise.all([new Promise(function(e,t){"complete"===document.readyState?e():window.addEventListener("load",e,!1)}),n]).then(function(){void 0!==window._setupDone?console.warn("p5.js seems to have been imported multiple times. Please remove the duplicate import"):window.mocha||(window.setup&&"function"==typeof window.setup||window.draw&&"function"==typeof window.draw)&&!o.default.instance&&new o.default})},{"../core/main":283,"./internationalization":281,"core-js/modules/es.array.iterator":165,"core-js/modules/es.object.to-string":190,"core-js/modules/es.promise":191,"core-js/modules/es.string.iterator":200,"core-js/modules/web.dom-collections.iterator":246}],281:[function(e,t,r){"use strict";e("core-js/modules/es.array.includes"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.object.keys"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.promise"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.string.includes"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.string.split"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.array.includes"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.object.keys"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.promise"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.string.includes"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.string.split"),e("core-js/modules/web.dom-collections.iterator"),Object.defineProperty(r,"__esModule",{value:!0}),r.setTranslatorLanguage=r.currentTranslatorLanguage=r.availableTranslatorLanguages=r.initialize=r.translator=void 0;var n,s,o=a(e("i18next")),i=a(e("i18next-browser-languagedetector"));function a(e){return e&&e.__esModule?e:{default:e}}function l(e,t){for(var r=0;r=i.width||t>=i.height?[0,0,0,0]:this._getPixel(e,t);n=new a.default.Image(r*s,o*s);return n.pixelDensity(s),n.canvas.getContext("2d").drawImage(i,e,t,r*s,o*s,0,0,r*s,o*s),n}},{key:"textLeading",value:function(e){return"number"==typeof e?(this._setProperty("_leadingSet",!0),this._setProperty("_textLeading",e),this._pInst):this._textLeading}},{key:"textStyle",value:function(e){return e?(e!==A.NORMAL&&e!==A.ITALIC&&e!==A.BOLD&&e!==A.BOLDITALIC||this._setProperty("_textStyle",e),this._applyTextProperties()):this._textStyle}},{key:"textAscent",value:function(){return null===this._textAscent&&this._updateTextMetrics(),this._textAscent}},{key:"textDescent",value:function(){return null===this._textDescent&&this._updateTextMetrics(),this._textDescent}},{key:"textAlign",value:function(e,t){return void 0!==e?(this._setProperty("_textAlign",e),void 0!==t&&this._setProperty("_textBaseline",t),this._applyTextProperties()):{horizontal:this._textAlign,vertical:this._textBaseline}}},{key:"textWrap",value:function(e){return this._setProperty("_textWrap",e),this._textWrap}},{key:"text",value:function(e,t,r,o,n){var s,i,a,l,u=this._pInst,c=this._textWrap,d=Number.MAX_VALUE,h=r;if((this._doFill||this._doStroke)&&void 0!==e){if(s=(e=(e="string"!=typeof e?e.toString():e).replace(/(\t)/g," ")).split("\n"),void 0!==o){switch(this._rectMode===A.CENTER&&(t-=o/2),this._textAlign){case A.CENTER:t+=o/2;break;case A.RIGHT:t+=o}if(void 0!==n){this._rectMode===A.CENTER&&(r-=n/2,h-=n/2);var e=r,f=u.textAscent();switch(this._textBaseline){case A.BOTTOM:l=r+n,r=Math.max(l,r),h+=f;break;case A.CENTER:l=r+n/2,r=Math.max(l,r),h+=f/2}d=r+n-f,this._textBaseline===A.CENTER&&(d=e+n-f/2)}else this._textBaseline!==A.BOTTOM&&this._textBaseline!==A.CENTER||(h=r-(e=u.textSize()*this._textLeading)/2,d=r+e/2);if(c===A.WORD){for(var p=[],m=0;ma.HALF_PI&&e<=3*a.HALF_PI?Math.atan(r/o*Math.tan(e))+a.PI:Math.atan(r/o*Math.tan(e))+a.TWO_PI,t=t<=a.HALF_PI?Math.atan(r/o*Math.tan(t)):t>a.HALF_PI&&t<=3*a.HALF_PI?Math.atan(r/o*Math.tan(t))+a.PI:Math.atan(r/o*Math.tan(t))+a.TWO_PI),th||Math.abs(this.accelerationY-this.pAccelerationY)>h||Math.abs(this.accelerationZ-this.pAccelerationZ)>h)&&s.deviceMoved(),"function"==typeof s.deviceTurned&&(t=this._toDegrees(this.rotationX)+180,r=this._toDegrees(this.pRotationX)+180,e=i+180,0>>16,e[1+r]=(65280&t[o])>>>8,e[2+r]=255&t[o],e[3+r]=(4278190080&t[o])>>>24},_toImageData:function(e){return e instanceof ImageData?e:e.getContext("2d").getImageData(0,0,e.width,e.height)},_createImageData:function(e,t){return V._tmpCanvas=document.createElement("canvas"),V._tmpCtx=V._tmpCanvas.getContext("2d"),this._tmpCtx.createImageData(e,t)},apply:function(e,t,r){var o=e.getContext("2d"),n=o.getImageData(0,0,e.width,e.height),t=t(n,r);t instanceof ImageData?o.putImageData(t,0,0,0,0,e.width,e.height):o.putImageData(n,0,0,0,0,e.width,e.height)},threshold:function(e){for(var t=1>8)/o,r[n+1]=255*(i*t>>8)/o,r[n+2]=255*(a*t>>8)/o}},dilate:function(e){for(var t,r,o,n,s,i,a,l,u,c=V._toPixels(e),d=0,h=c.length?c.length/4:0,f=new Int32Array(h);d>16&255)+151*(n>>8&255)+28*(255&n))<(a=77*(u>>16&255)+151*(u>>8&255)+28*(255&u))&&(o=u,n=a),n<(a=77*((u=V._getARGB(c,l))>>16&255)+151*(u>>8&255)+28*(255&u))&&(o=u,n=a),n<(l=77*(s>>16&255)+151*(s>>8&255)+28*(255&s))&&(o=s,n=l),n<(u=77*(i>>16&255)+151*(i>>8&255)+28*(255&i))&&(o=i,n=u),f[d++]=o;V._setPixels(c,f)},erode:function(e){for(var t,r,o,n,s,i,a,l,u,c=V._toPixels(e),d=0,h=c.length?c.length/4:0,f=new Int32Array(h);d>16&255)+151*(u>>8&255)+28*(255&u))<(n=77*(n>>16&255)+151*(n>>8&255)+28*(255&n))&&(o=u,n=a),(a=77*((u=V._getARGB(c,l))>>16&255)+151*(u>>8&255)+28*(255&u))>16&255)+151*(s>>8&255)+28*(255&s))>16&255)+151*(i>>8&255)+28*(255&i))>>24],r+=j[(16711680&I)>>16],o+=j[(65280&I)>>8],n+=j[255&I],t+=B[b],i++}T[a=k+g]=s/t,E[a]=r/t,M[a]=o/t,F[a]=n/t}k+=h}for(u=(l=-U)*h,v=k=0;v"+p.length.toString()+" out of "+c.toString()),e.next=48,new Promise(function(e){return setTimeout(e,0)});e.next=50;break;case 48:e.next=39;break;case 50:i||m.html("Frames processed, generating color palette..."),this.loop(),this.pixelDensity(f),v=(0,A.GIFEncoder)(),b=function(e){for(var t=new Uint8Array(e.length*e[0].length),r=0;r"+S.toString()+" out of "+c.toString()),e.next=68,new Promise(function(e){return setTimeout(e,0)});case 68:S++,e.next=60;break;case 71:v.finish(),k=v.bytesView(),k=new Blob([k],{type:"image/gif"}),p=[],this._recording=!1,this.loop(),i||(m.html("Done. Downloading your gif!🌸"),0=t&&(t=Math.floor(r.timeDisplayed/t),r.timeDisplayed=0,r.lastChangeTime=e,r.displayIndex+=t,r.loopCount=Math.floor(r.displayIndex/r.numFrames),null!==r.loopLimit&&r.loopCount>=r.loopLimit?r.playing=!1:(e=r.displayIndex%r.numFrames,this.drawingContext.putImageData(r.frames[e].image,0,0),r.displayIndex=e,this.setModified(!0))))}},{key:"_setProperty",value:function(e,t){this[e]=t,this.setModified(!0)}},{key:"loadPixels",value:function(){i.default.Renderer2D.prototype.loadPixels.call(this),this.setModified(!0)}},{key:"updatePixels",value:function(e,t,r,o){i.default.Renderer2D.prototype.updatePixels.call(this,e,t,r,o),this.setModified(!0)}},{key:"get",value:function(e,t,r,o){return i.default._validateParameters("p5.Image.get",arguments),i.default.Renderer2D.prototype.get.apply(this,arguments)}},{key:"_getPixel",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r/g,">").replace(/"/g,""").replace(/'/g,"'")}function i(e,t){t&&!0!==t&&"true"!==t||(t="");var r="";return(e=e||"untitled")&&e.includes(".")&&(r=e.split(".").pop()),t&&r!==t&&(r=t,e="".concat(e,".").concat(r)),[e,r]}e("../core/friendly_errors/validate_params"),e("../core/friendly_errors/file_errors"),e("../core/friendly_errors/fes_core"),v.default.prototype.loadJSON=function(){for(var e=arguments.length,t=new Array(e),r=0;r"),n.print("");if(n.print(' '),n.print(""),n.print(""),n.print(" "),"0"!==s[0]){n.print(" ");for(var c=0;c".concat(d)),n.print(" ")}n.print(" ")}for(var h=0;h");for(var f=0;f".concat(p)),n.print(" ")}n.print(" ")}n.print("
        "),n.print(""),n.print("")}n.close(),n.clear()},v.default.prototype.writeFile=function(e,t,r){var o="application/octet-stream",e=(v.default.prototype._isSafari()&&(o="text/plain"),new Blob(e,{type:o}));v.default.prototype.downloadFile(e,t,r)},v.default.prototype.downloadFile=function(e,t,r){var o,t=i(t,r),r=t[0];e instanceof Blob?n.default.saveAs(e,r):((o=document.createElement("a")).href=e,o.download=r,o.onclick=function(e){document.body.removeChild(e.target),e.stopPropagation()},o.style.display="none",document.body.appendChild(o),v.default.prototype._isSafari()&&(e=(e='Hello, Safari user! To download this file...\n1. Go to File --\x3e Save As.\n2. Choose "Page Source" as the Format.\n')+'3. Name it with this extension: ."'.concat(t[1],'"'),alert(e)),o.click())},v.default.prototype._checkFileExtension=i,v.default.prototype._isSafari=function(){return window.HTMLElement.toString().includes("Constructor")};e=v.default;r.default=e},{"../core/friendly_errors/fes_core":274,"../core/friendly_errors/file_errors":275,"../core/friendly_errors/validate_params":278,"../core/main":283,"core-js/modules/es.array.concat":153,"core-js/modules/es.array.includes":163,"core-js/modules/es.array.iterator":165,"core-js/modules/es.array.last-index-of":167,"core-js/modules/es.array.map":168,"core-js/modules/es.array.slice":169,"core-js/modules/es.array.splice":171,"core-js/modules/es.function.name":174,"core-js/modules/es.object.from-entries":185,"core-js/modules/es.object.to-string":190,"core-js/modules/es.promise":191,"core-js/modules/es.regexp.exec":195,"core-js/modules/es.regexp.to-string":196,"core-js/modules/es.string.includes":199,"core-js/modules/es.string.iterator":200,"core-js/modules/es.string.replace":204,"core-js/modules/es.string.split":206,"core-js/modules/es.symbol":212,"core-js/modules/es.symbol.description":210,"core-js/modules/es.symbol.iterator":211,"core-js/modules/es.typed-array.copy-within":213,"core-js/modules/es.typed-array.every":214,"core-js/modules/es.typed-array.fill":215,"core-js/modules/es.typed-array.filter":216,"core-js/modules/es.typed-array.find":218,"core-js/modules/es.typed-array.find-index":217,"core-js/modules/es.typed-array.for-each":221,"core-js/modules/es.typed-array.includes":222,"core-js/modules/es.typed-array.index-of":223,"core-js/modules/es.typed-array.iterator":226,"core-js/modules/es.typed-array.join":227,"core-js/modules/es.typed-array.last-index-of":228,"core-js/modules/es.typed-array.map":229,"core-js/modules/es.typed-array.reduce":231,"core-js/modules/es.typed-array.reduce-right":230,"core-js/modules/es.typed-array.reverse":232,"core-js/modules/es.typed-array.set":233,"core-js/modules/es.typed-array.slice":234,"core-js/modules/es.typed-array.some":235,"core-js/modules/es.typed-array.sort":236,"core-js/modules/es.typed-array.subarray":237,"core-js/modules/es.typed-array.to-locale-string":238,"core-js/modules/es.typed-array.to-string":239,"core-js/modules/es.typed-array.uint8-array":242,"core-js/modules/web.dom-collections.iterator":246,"core-js/modules/web.url":248,"es6-promise/auto":249,"fetch-jsonp":251,"file-saver":252,"whatwg-fetch":261}],310:[function(e,t,r){"use strict";e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.index-of"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.splice"),e("core-js/modules/es.regexp.constructor"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.string.match"),e("core-js/modules/es.string.replace"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.index-of"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.splice"),e("core-js/modules/es.regexp.constructor"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.string.match"),e("core-js/modules/es.string.replace"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var n=(e=e("../core/main"))&&e.__esModule?e:{default:e};function s(e,t){for(var r=0;r>>0},getSeed:function(){return t},rand:function(){return(r=(1664525*r+1013904223)%o)/o}};n.setSeed(e),j=new Array(4096);for(var s=0;s<4096;s++)j[s]=n.rand()},e.default);r.default=e},{"../core/main":283}],316:[function(e,t,r){"use strict";function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e){return(i="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":o(e)})(e)}e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.every"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.some"),e("core-js/modules/es.math.sign"),e("core-js/modules/es.number.constructor"),e("core-js/modules/es.number.epsilon"),e("core-js/modules/es.number.is-finite"),e("core-js/modules/es.object.get-own-property-descriptor"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.string.sub"),e("core-js/modules/es.weak-map"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.every"),e("core-js/modules/es.array.some"),e("core-js/modules/es.math.sign"),e("core-js/modules/es.number.constructor"),e("core-js/modules/es.number.epsilon"),e("core-js/modules/es.number.is-finite"),e("core-js/modules/es.string.sub"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var u=(n=e("../core/main"))&&n.__esModule?n:{default:n},s=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==i(e)&&"function"!=typeof e)return{default:e};var t=a();if(t&&t.has(e))return t.get(e);var r,o={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(r in e){var s;Object.prototype.hasOwnProperty.call(e,r)&&((s=n?Object.getOwnPropertyDescriptor(e,r):null)&&(s.get||s.set)?Object.defineProperty(o,r,s):o[r]=e[r])}o.default=e,t&&t.set(e,o);return o}(e("../core/constants"));function a(){var e;return"function"!=typeof WeakMap?null:(e=new WeakMap,a=function(){return e},e)}function l(e,t){for(var r=0;r>>0},n.default.prototype.randomSeed=function(e){this._lcgSetSeed(s,e),this._gaussian_previous=!1},n.default.prototype.random=function(e,t){var r,o;return n.default._validateParameters("random",arguments),r=null!=this[s]?this._lcg(s):Math.random(),void 0===e?r:void 0===t?Array.isArray(e)?e[Math.floor(r*e.length)]:r*e:(tf&&(b=d,v=a,s=l,d=x+f*(i&&x=t?r.substring(r.length-t,r.length):r}},o.default.prototype.unhex=function(e){return e instanceof Array?e.map(o.default.prototype.unhex):parseInt("0x".concat(e),16)};e=o.default;r.default=e},{"../core/main":283,"core-js/modules/es.array.map":168,"core-js/modules/es.number.constructor":179,"core-js/modules/es.object.to-string":190,"core-js/modules/es.regexp.to-string":196,"core-js/modules/es.string.repeat":203}],324:[function(e,t,r){"use strict";e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.filter"),e("core-js/modules/es.array.index-of"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.map"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.number.to-fixed"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.regexp.constructor"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.string.match"),e("core-js/modules/es.string.pad-start"),e("core-js/modules/es.string.replace"),e("core-js/modules/es.string.split"),e("core-js/modules/es.string.trim"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.array.filter"),e("core-js/modules/es.array.index-of"),e("core-js/modules/es.array.join"),e("core-js/modules/es.array.map"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.number.to-fixed"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.regexp.constructor"),e("core-js/modules/es.regexp.exec"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.string.match"),e("core-js/modules/es.string.pad-start"),e("core-js/modules/es.string.replace"),e("core-js/modules/es.string.split"),e("core-js/modules/es.string.trim"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;var s=(u=e("../core/main"))&&u.__esModule?u:{default:u};function i(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)){var r=[],o=!0,n=!1,s=void 0;try{for(var i,a=e[Symbol.iterator]();!(o=(i=a.next()).done)&&(r.push(i.value),!t||r.length!==t);o=!0);}catch(e){n=!0,s=e}finally{try{o||null==a.return||a.return()}finally{if(n)throw s}}return r}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function o(e,t,r){var o=i(e.toString().split("."),2),n=o[0],o=o[1];return void 0===r?(n=n.padStart(t,"0"),o?n+"."+o:n):(n=(e=i(e.toFixed(r).toString().split("."),2))[0],o=e[1],n=n.padStart(t,"0"),void 0===o?n:n+"."+o)}function n(e,t){var r=(e=e.toString()).indexOf("."),o=-1!==r?e.substring(r):"",e=(e=-1!==r?e.substring(0,r):e).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",");if(0===t)o="";else if(void 0!==t)if(t>o.length)for(var n=t-(o+=-1===r?".":"").length+1,s=0;s=_.TWO_PI?"".concat(c="ellipse","|"):"".concat(c="arc","|").concat(s,"|").concat(i,"|").concat(a,"|")).concat(l,"|"),c=(this.geometryInHash(u)||((e=new S.default.Geometry(l,1,function(){if(s.toFixed(10)!==i.toFixed(10)){a!==_.PIE&&void 0!==a||(this.vertices.push(new S.default.Vector(.5,.5,0)),this.uvs.push([.5,.5]));for(var e=0;e<=l;e++){var t=(i-s)*(e/l)+s,r=.5+Math.cos(t)/2,t=.5+Math.sin(t)/2;this.vertices.push(new S.default.Vector(r,t,0)),this.uvs.push([r,t]),e>5&31)/31,(p>>10&31)/31):(r=i,o=a,l)),new x.default.Vector(y,g,v)),j=1;j<=3;j++){var _=m+12*j,_=new x.default.Vector(u.getFloat32(_,!0),u.getFloat32(4+_,!0),u.getFloat32(8+_,!0));e.vertices.push(_),e.vertexNormals.push(b),d&&s.push(r,o,n)}e.faces.push([3*f,3*f+1,3*f+2]),e.uvs.push([0,0],[0,0],[0,0])}}(e,t);else{t=new DataView(t);if(!("TextDecoder"in window))return console.warn("Sorry, ASCII STL loading only works in browsers that support TextDecoder (https://caniuse.com/#feat=textencoder)");t=new TextDecoder("utf-8").decode(t).split("\n");!function(e,t){for(var r,o,n="",s=[],i=0;ithis.cameraFar&&(i=this.cameraFar),Math.acos(Math.max(-1,Math.min(1,_.default.Vector.dot(o,n))))+t),t=e;(r<=0||r>=Math.PI)&&(this.upX*=-1,this.upY*=-1,this.upZ*=-1),n.mult(Math.cos(r)),a.mult(Math.cos(t)*Math.sin(r)),s.mult(Math.sin(t)*Math.sin(r)),o.set(n).add(a).add(s),this.eyeX=i*o.x+this.centerX,this.eyeY=i*o.y+this.centerY,this.eyeZ=i*o.z+this.centerZ,this.camera(this.eyeX,this.eyeY,this.eyeZ,this.centerX,this.centerY,this.centerZ,this.upX,this.upY,this.upZ)}},{key:"_orbitFree",value:function(e,t,r){var o=this.eyeX-this.centerX,n=this.eyeY-this.centerY,s=this.eyeZ-this.centerZ,i=Math.hypot(o,n,s),o=new _.default.Vector(o,n,s).normalize(),n=new _.default.Vector(this.upX,this.upY,this.upZ),s=_.default.Vector.cross(n,o).normalize(),a=_.default.Vector.cross(o,s),l=Math.atan2(t,e),l=(a.mult(Math.sin(l)),s.mult(Math.cos(l)).add(a),Math.sqrt(e*e+t*t)),a=_.default.Vector.cross(o,s),e=((i=(i*=Math.pow(10,r))this.cameraFar&&(i=this.cameraFar),Math.cos(l)),t=Math.sin(l),r=n.dot(o),l=n.dot(s),u=r*e+l*t,r=-r*t+l*e,l=n.dot(a);n.x=u*o.x+r*s.x+l*a.x,n.y=u*o.y+r*s.y+l*a.y,n.z=u*o.z+r*s.z+l*a.z,s.mult(-t),o.mult(e).add(s).mult(i),this.camera(o.x+this.centerX,o.y+this.centerY,o.z+this.centerZ,this.centerX,this.centerY,this.centerZ,n.x,n.y,n.z)}},{key:"_isActive",value:function(){return this===this._renderer._curCamera}}])&&n(e.prototype,r),o&&n(e,o),t}(),_.default.prototype.setCamera=function(e){this._renderer._curCamera=e,this._renderer.uPMatrix.set(e.projMatrix),this._renderer.uViewMatrix.set(e.cameraMatrix)};e=_.default.Camera;r.default=e},{"../core/main":283,"core-js/modules/es.array.slice":169,"core-js/modules/es.math.hypot":176,"core-js/modules/es.string.sub":208}],333:[function(e,t,r){"use strict";e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.math.log2"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.typed-array.float32-array"),e("core-js/modules/es.typed-array.copy-within"),e("core-js/modules/es.typed-array.every"),e("core-js/modules/es.typed-array.fill"),e("core-js/modules/es.typed-array.filter"),e("core-js/modules/es.typed-array.find"),e("core-js/modules/es.typed-array.find-index"),e("core-js/modules/es.typed-array.for-each"),e("core-js/modules/es.typed-array.includes"),e("core-js/modules/es.typed-array.index-of"),e("core-js/modules/es.typed-array.iterator"),e("core-js/modules/es.typed-array.join"),e("core-js/modules/es.typed-array.last-index-of"),e("core-js/modules/es.typed-array.map"),e("core-js/modules/es.typed-array.reduce"),e("core-js/modules/es.typed-array.reduce-right"),e("core-js/modules/es.typed-array.reverse"),e("core-js/modules/es.typed-array.set"),e("core-js/modules/es.typed-array.slice"),e("core-js/modules/es.typed-array.some"),e("core-js/modules/es.typed-array.sort"),e("core-js/modules/es.typed-array.subarray"),e("core-js/modules/es.typed-array.to-locale-string"),e("core-js/modules/es.typed-array.to-string"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.math.log2"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.typed-array.float32-array"),e("core-js/modules/es.typed-array.copy-within"),e("core-js/modules/es.typed-array.every"),e("core-js/modules/es.typed-array.fill"),e("core-js/modules/es.typed-array.filter"),e("core-js/modules/es.typed-array.find"),e("core-js/modules/es.typed-array.find-index"),e("core-js/modules/es.typed-array.for-each"),e("core-js/modules/es.typed-array.includes"),e("core-js/modules/es.typed-array.index-of"),e("core-js/modules/es.typed-array.iterator"),e("core-js/modules/es.typed-array.join"),e("core-js/modules/es.typed-array.last-index-of"),e("core-js/modules/es.typed-array.map"),e("core-js/modules/es.typed-array.reduce"),e("core-js/modules/es.typed-array.reduce-right"),e("core-js/modules/es.typed-array.reverse"),e("core-js/modules/es.typed-array.set"),e("core-js/modules/es.typed-array.slice"),e("core-js/modules/es.typed-array.some"),e("core-js/modules/es.typed-array.sort"),e("core-js/modules/es.typed-array.subarray"),e("core-js/modules/es.typed-array.to-locale-string"),e("core-js/modules/es.typed-array.to-string"),Object.defineProperty(r,"__esModule",{value:!0}),r.default=void 0;e=(e=e("../core/main"))&&e.__esModule?e:{default:e};function n(e,t){for(var r=0;r=this.width||t>=this.height)&&(console.warn("The x and y values passed to p5.Framebuffer.get are outside of its range and will be clamped."),e=this.target.constrain(e,0,this.width-1),t=this.target.constrain(t,0,this.height-1)),(0,p.readPixelWebGL)(this.gl,this.framebuffer,e*this.density,t*this.density,n.format,n.type);e=this.target.constrain(e,0,this.width-1),t=this.target.constrain(t,0,this.height-1),r=this.target.constrain(r,1,this.width-e),o=this.target.constrain(o,1,this.height-t);for(var s=(0,p.readPixelsWebGL)(void 0,this.gl,this.framebuffer,e*this.density,t*this.density,r*this.density,o*this.density,n.format,n.type),i=new Uint8ClampedArray(r*o*this.density*this.density*4),a=(i.fill(255),n.type===this.gl.RGB?3:4),l=0;lthis.vertices.length-1-this.detailX;o--)e.add(this.vertexNormals[o]);e=F.default.Vector.div(e,this.detailX);for(var n=this.vertices.length-1;n>this.vertices.length-1-this.detailX;n--)this.vertexNormals[n]=e;return this}},{key:"_makeTriangleEdges",value:function(){for(var e=this.edges.length=0;e 65535 triangles. Your web browser does not support the WebGL Extension OES_element_index_uint.");r.drawElements(r.TRIANGLES,t.vertexCount,t.indexBufferType,0)}else r.drawArrays(e||r.TRIANGLES,0,t.vertexCount)},a.default.RendererGL.prototype._drawPoints=function(e,t){var r=this.GL,o=this._getImmediatePointShader();this._setPointUniforms(o),this._bindBuffer(t,r.ARRAY_BUFFER,this._vToNArray(e),Float32Array,r.STATIC_DRAW),o.enableAttrib(o.attributes.aPosition,3),this._applyColorBlend(this.curStrokeColor),r.drawArrays(r.Points,0,e.length),o.unbindShader()};var s=a.default.RendererGL;r.default=s},{"../core/constants":272,"../core/main":283,"./p5.RenderBuffer":338,"./p5.RendererGL":341,"core-js/modules/es.array.fill":156,"core-js/modules/es.array.iterator":165,"core-js/modules/es.array.some":170,"core-js/modules/es.object.get-own-property-descriptor":186,"core-js/modules/es.object.keys":189,"core-js/modules/es.object.to-string":190,"core-js/modules/es.string.iterator":200,"core-js/modules/es.symbol":212,"core-js/modules/es.symbol.description":210,"core-js/modules/es.symbol.iterator":211,"core-js/modules/es.typed-array.copy-within":213,"core-js/modules/es.typed-array.every":214,"core-js/modules/es.typed-array.fill":215,"core-js/modules/es.typed-array.filter":216,"core-js/modules/es.typed-array.find":218,"core-js/modules/es.typed-array.find-index":217,"core-js/modules/es.typed-array.float32-array":219,"core-js/modules/es.typed-array.for-each":221,"core-js/modules/es.typed-array.includes":222,"core-js/modules/es.typed-array.index-of":223,"core-js/modules/es.typed-array.iterator":226,"core-js/modules/es.typed-array.join":227,"core-js/modules/es.typed-array.last-index-of":228,"core-js/modules/es.typed-array.map":229,"core-js/modules/es.typed-array.reduce":231,"core-js/modules/es.typed-array.reduce-right":230,"core-js/modules/es.typed-array.reverse":232,"core-js/modules/es.typed-array.set":233,"core-js/modules/es.typed-array.slice":234,"core-js/modules/es.typed-array.some":235,"core-js/modules/es.typed-array.sort":236,"core-js/modules/es.typed-array.subarray":237,"core-js/modules/es.typed-array.to-locale-string":238,"core-js/modules/es.typed-array.to-string":239,"core-js/modules/es.typed-array.uint16-array":240,"core-js/modules/es.typed-array.uint32-array":241,"core-js/modules/es.weak-map":244,"core-js/modules/web.dom-collections.iterator":246}],341:[function(e,t,r){"use strict";function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e){return(i="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":o(e)})(e)}e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.copy-within"),e("core-js/modules/es.array.every"),e("core-js/modules/es.array.fill"),e("core-js/modules/es.array.flat"),e("core-js/modules/es.array.flat-map"),e("core-js/modules/es.array.from"),e("core-js/modules/es.array.includes"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.map"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.array.some"),e("core-js/modules/es.array.unscopables.flat"),e("core-js/modules/es.array.unscopables.flat-map"),e("core-js/modules/es.map"),e("core-js/modules/es.object.assign"),e("core-js/modules/es.object.get-own-property-descriptor"),e("core-js/modules/es.object.get-prototype-of"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.reflect.construct"),e("core-js/modules/es.reflect.get"),e("core-js/modules/es.regexp.to-string"),e("core-js/modules/es.set"),e("core-js/modules/es.string.includes"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.typed-array.float32-array"),e("core-js/modules/es.typed-array.float64-array"),e("core-js/modules/es.typed-array.int16-array"),e("core-js/modules/es.typed-array.uint8-array"),e("core-js/modules/es.typed-array.uint16-array"),e("core-js/modules/es.typed-array.uint32-array"),e("core-js/modules/es.typed-array.copy-within"),e("core-js/modules/es.typed-array.every"),e("core-js/modules/es.typed-array.fill"),e("core-js/modules/es.typed-array.filter"),e("core-js/modules/es.typed-array.find"),e("core-js/modules/es.typed-array.find-index"),e("core-js/modules/es.typed-array.for-each"),e("core-js/modules/es.typed-array.includes"),e("core-js/modules/es.typed-array.index-of"),e("core-js/modules/es.typed-array.iterator"),e("core-js/modules/es.typed-array.join"),e("core-js/modules/es.typed-array.last-index-of"),e("core-js/modules/es.typed-array.map"),e("core-js/modules/es.typed-array.reduce"),e("core-js/modules/es.typed-array.reduce-right"),e("core-js/modules/es.typed-array.reverse"),e("core-js/modules/es.typed-array.set"),e("core-js/modules/es.typed-array.slice"),e("core-js/modules/es.typed-array.some"),e("core-js/modules/es.typed-array.sort"),e("core-js/modules/es.typed-array.subarray"),e("core-js/modules/es.typed-array.to-locale-string"),e("core-js/modules/es.typed-array.to-string"),e("core-js/modules/es.weak-map"),e("core-js/modules/web.dom-collections.iterator"),e("core-js/modules/es.symbol"),e("core-js/modules/es.symbol.description"),e("core-js/modules/es.symbol.iterator"),e("core-js/modules/es.array.concat"),e("core-js/modules/es.array.copy-within"),e("core-js/modules/es.array.every"),e("core-js/modules/es.array.fill"),e("core-js/modules/es.array.flat"),e("core-js/modules/es.array.flat-map"),e("core-js/modules/es.array.from"),e("core-js/modules/es.array.includes"),e("core-js/modules/es.array.iterator"),e("core-js/modules/es.array.map"),e("core-js/modules/es.array.slice"),e("core-js/modules/es.array.some"),e("core-js/modules/es.array.unscopables.flat"),e("core-js/modules/es.array.unscopables.flat-map"),e("core-js/modules/es.map"),e("core-js/modules/es.object.assign"),e("core-js/modules/es.object.to-string"),e("core-js/modules/es.set"),e("core-js/modules/es.string.includes"),e("core-js/modules/es.string.iterator"),e("core-js/modules/es.typed-array.float32-array"),e("core-js/modules/es.typed-array.float64-array"),e("core-js/modules/es.typed-array.int16-array"),e("core-js/modules/es.typed-array.uint8-array"),e("core-js/modules/es.typed-array.uint16-array"),e("core-js/modules/es.typed-array.uint32-array"),e("core-js/modules/es.typed-array.copy-within"),e("core-js/modules/es.typed-array.every"),e("core-js/modules/es.typed-array.fill"),e("core-js/modules/es.typed-array.filter"),e("core-js/modules/es.typed-array.find"),e("core-js/modules/es.typed-array.find-index"),e("core-js/modules/es.typed-array.for-each"),e("core-js/modules/es.typed-array.includes"),e("core-js/modules/es.typed-array.index-of"),e("core-js/modules/es.typed-array.iterator"),e("core-js/modules/es.typed-array.join"),e("core-js/modules/es.typed-array.last-index-of"),e("core-js/modules/es.typed-array.map"),e("core-js/modules/es.typed-array.reduce"),e("core-js/modules/es.typed-array.reduce-right"),e("core-js/modules/es.typed-array.reverse"),e("core-js/modules/es.typed-array.set"),e("core-js/modules/es.typed-array.slice"),e("core-js/modules/es.typed-array.some"),e("core-js/modules/es.typed-array.sort"),e("core-js/modules/es.typed-array.subarray"),e("core-js/modules/es.typed-array.to-locale-string"),e("core-js/modules/es.typed-array.to-string"),e("core-js/modules/web.dom-collections.iterator"),Object.defineProperty(r,"__esModule",{value:!0}),r.readPixelsWebGL=O,r.readPixelWebGL=C,r.default=void 0;var g=n(e("../core/main")),l=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==i(e)&&"function"!=typeof e)return{default:e};var t=d();if(t&&t.has(e))return t.get(e);var r,o={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(r in e){var s;Object.prototype.hasOwnProperty.call(e,r)&&((s=n?Object.getOwnPropertyDescriptor(e,r):null)&&(s.get||s.set)?Object.defineProperty(o,r,s):o[r]=e[r])}o.default=e,t&&t.set(e,o);return o}(e("../core/constants")),a=n(e("./GeometryBuilder")),u=n(e("libtess")),c=(e("./p5.Shader"),e("./p5.Camera"),e("../core/p5.Renderer"),e("./p5.Matrix"),e("./p5.Framebuffer"),e("path"),e("./p5.Texture"));function d(){var e;return"function"!=typeof WeakMap?null:(e=new WeakMap,d=function(){return e},e)}function n(e){return e&&e.__esModule?e:{default:e}}function h(e){return function(e){if(Array.isArray(e)){for(var t=0,r=new Array(e.length);t vTexCoord.y;\n bool y1 = p1.y > vTexCoord.y;\n bool y2 = p2.y > vTexCoord.y;\n\n // could web be under the curve (after t1)?\n if (y1 ? !y2 : y0) {\n // add the coverage for t1\n coverage.x += saturate(C1.x + 0.5);\n // calculate the anti-aliasing for t1\n weight.x = min(weight.x, abs(C1.x));\n }\n\n // are we outside the curve (after t2)?\n if (y1 ? !y0 : y2) {\n // subtract the coverage for t2\n coverage.x -= saturate(C2.x + 0.5);\n // calculate the anti-aliasing for t2\n weight.x = min(weight.x, abs(C2.x));\n }\n}\n\n// this is essentially the same as coverageX, but with the axes swapped\nvoid coverageY(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n bool x0 = p0.x > vTexCoord.x;\n bool x1 = p1.x > vTexCoord.x;\n bool x2 = p2.x > vTexCoord.x;\n\n if (x1 ? !x2 : x0) {\n coverage.y -= saturate(C1.y + 0.5);\n weight.y = min(weight.y, abs(C1.y));\n }\n\n if (x1 ? !x0 : x2) {\n coverage.y += saturate(C2.y + 0.5);\n weight.y = min(weight.y, abs(C2.y));\n }\n}\n\nvoid main() {\n\n // calculate the pixel scale based on screen-coordinates\n pixelScale = hardness / fwidth(vTexCoord);\n\n // which grid cell is this pixel in?\n ivec2 gridCoord = ifloor(vTexCoord * vec2(uGridSize));\n\n // intersect curves in this row\n {\n // the index into the row info bitmap\n int rowIndex = gridCoord.y + uGridOffset.y;\n // fetch the info texel\n vec4 rowInfo = getTexel(uSamplerRows, rowIndex, uGridImageSize);\n // unpack the rowInfo\n int rowStrokeIndex = getInt16(rowInfo.xy);\n int rowStrokeCount = getInt16(rowInfo.zw);\n\n for (int iRowStroke = INT(0); iRowStroke < N; iRowStroke++) {\n if (iRowStroke >= rowStrokeCount)\n break;\n\n // each stroke is made up of 3 points: the start and control point\n // and the start of the next curve.\n // fetch the indices of this pair of strokes:\n vec4 strokeIndices = getTexel(uSamplerRowStrokes, rowStrokeIndex++, uCellsImageSize);\n\n // unpack the stroke index\n int strokePos = getInt16(strokeIndices.xy);\n\n // fetch the two strokes\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n\n // calculate the coverage\n coverageX(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n // intersect curves in this column\n {\n int colIndex = gridCoord.x + uGridOffset.x;\n vec4 colInfo = getTexel(uSamplerCols, colIndex, uGridImageSize);\n int colStrokeIndex = getInt16(colInfo.xy);\n int colStrokeCount = getInt16(colInfo.zw);\n \n for (int iColStroke = INT(0); iColStroke < N; iColStroke++) {\n if (iColStroke >= colStrokeCount)\n break;\n\n vec4 strokeIndices = getTexel(uSamplerColStrokes, colStrokeIndex++, uCellsImageSize);\n\n int strokePos = getInt16(strokeIndices.xy);\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n coverageY(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n weight = saturate(1.0 - weight * 2.0);\n float distance = max(weight.x + weight.y, minDistance); // manhattan approx.\n float antialias = abs(dot(coverage, weight) / distance);\n float cover = min(abs(coverage.x), abs(coverage.y));\n OUT_COLOR = vec4(uMaterialColor.rgb, 1.) * uMaterialColor.a;\n OUT_COLOR *= saturate(max(antialias, cover));\n}\n",lineVert:T+"/*\n Part of the Processing project - http://processing.org\n Copyright (c) 2012-15 The Processing Foundation\n Copyright (c) 2004-12 Ben Fry and Casey Reas\n Copyright (c) 2001-04 Massachusetts Institute of Technology\n This library is free software; you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation, version 2.1.\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n You should have received a copy of the GNU Lesser General\n Public License along with this library; if not, write to the\n Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n Boston, MA 02111-1307 USA\n*/\n\n#define PROCESSING_LINE_SHADER\n\nprecision mediump int;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uStrokeWeight;\n\nuniform bool uUseLineColor;\nuniform vec4 uMaterialColor;\n\nuniform vec4 uViewport;\nuniform int uPerspective;\nuniform int uStrokeJoin;\n\nIN vec4 aPosition;\nIN vec3 aTangentIn;\nIN vec3 aTangentOut;\nIN float aSide;\nIN vec4 aVertexColor;\n\nOUT vec4 vColor;\nOUT vec2 vTangent;\nOUT vec2 vCenter;\nOUT vec2 vPosition;\nOUT float vMaxDist;\nOUT float vCap;\nOUT float vJoin;\n\nvec2 lineIntersection(vec2 aPoint, vec2 aDir, vec2 bPoint, vec2 bDir) {\n // Rotate and translate so a starts at the origin and goes out to the right\n bPoint -= aPoint;\n vec2 rotatedBFrom = vec2(\n bPoint.x*aDir.x + bPoint.y*aDir.y,\n bPoint.y*aDir.x - bPoint.x*aDir.y\n );\n vec2 bTo = bPoint + bDir;\n vec2 rotatedBTo = vec2(\n bTo.x*aDir.x + bTo.y*aDir.y,\n bTo.y*aDir.x - bTo.x*aDir.y\n );\n float intersectionDistance =\n rotatedBTo.x + (rotatedBFrom.x - rotatedBTo.x) * rotatedBTo.y /\n (rotatedBTo.y - rotatedBFrom.y);\n return aPoint + aDir * intersectionDistance;\n}\n\nvoid main() {\n // Caps have one of either the in or out tangent set to 0\n vCap = (aTangentIn == vec3(0.)) != (aTangentOut == (vec3(0.)))\n ? 1. : 0.;\n\n // Joins have two unique, defined tangents\n vJoin = (\n aTangentIn != vec3(0.) &&\n aTangentOut != vec3(0.) &&\n aTangentIn != aTangentOut\n ) ? 1. : 0.;\n\n vec4 posp = uModelViewMatrix * aPosition;\n vec4 posqIn = uModelViewMatrix * (aPosition + vec4(aTangentIn, 0));\n vec4 posqOut = uModelViewMatrix * (aPosition + vec4(aTangentOut, 0));\n\n float facingCamera = pow(\n // The word space tangent's z value is 0 if it's facing the camera\n abs(normalize(posqIn-posp).z),\n\n // Using pow() here to ramp `facingCamera` up from 0 to 1 really quickly\n // so most lines get scaled and don't get clipped\n 0.25\n );\n\n // Moving vertices slightly toward the camera\n // to avoid depth-fighting with the fill triangles.\n // This prevents popping effects due to half of\n // the line disappearing behind the geometry faces.\n \n float zOffset = mix(-0.00045, -1., facingCamera);\n posp.z -= zOffset;\n posqIn.z -= zOffset;\n posqOut.z -= zOffset;\n \n vec4 p = uProjectionMatrix * posp;\n vec4 qIn = uProjectionMatrix * posqIn;\n vec4 qOut = uProjectionMatrix * posqOut;\n vCenter = p.xy;\n\n // formula to convert from clip space (range -1..1) to screen space (range 0..[width or height])\n // screen_p = (p.xy/p.w + <1,1>) * 0.5 * uViewport.zw\n\n // prevent division by W by transforming the tangent formula (div by 0 causes\n // the line to disappear, see https://github.com/processing/processing/issues/5183)\n // t = screen_q - screen_p\n //\n // tangent is normalized and we don't care which aDirection it points to (+-)\n // t = +- normalize( screen_q - screen_p )\n // t = +- normalize( (q.xy/q.w+<1,1>)*0.5*uViewport.zw - (p.xy/p.w+<1,1>)*0.5*uViewport.zw )\n //\n // extract common factor, <1,1> - <1,1> cancels out\n // t = +- normalize( (q.xy/q.w - p.xy/p.w) * 0.5 * uViewport.zw )\n //\n // convert to common divisor\n // t = +- normalize( ((q.xy*p.w - p.xy*q.w) / (p.w*q.w)) * 0.5 * uViewport.zw )\n //\n // remove the common scalar divisor/factor, not needed due to normalize and +-\n // (keep uViewport - can't remove because it has different components for x and y\n // and corrects for aspect ratio, see https://github.com/processing/processing/issues/5181)\n // t = +- normalize( (q.xy*p.w - p.xy*q.w) * uViewport.zw )\n\n vec2 tangentIn = normalize((qIn.xy*p.w - p.xy*qIn.w) * uViewport.zw);\n vec2 tangentOut = normalize((qOut.xy*p.w - p.xy*qOut.w) * uViewport.zw);\n\n vec2 curPerspScale;\n if(uPerspective == 1) {\n // Perspective ---\n // convert from world to clip by multiplying with projection scaling factor\n // to get the right thickness (see https://github.com/processing/processing/issues/5182)\n\n // The y value of the projection matrix may be flipped if rendering to a Framebuffer.\n // Multiplying again by its sign here negates the flip to get just the scale.\n curPerspScale = (uProjectionMatrix * vec4(1, sign(uProjectionMatrix[1][1]), 0, 0)).xy;\n } else {\n // No Perspective ---\n // multiply by W (to cancel out division by W later in the pipeline) and\n // convert from screen to clip (derived from clip to screen above)\n curPerspScale = p.w / (0.5 * uViewport.zw);\n }\n\n vec2 offset;\n if (vJoin == 1.) {\n vTangent = normalize(tangentIn + tangentOut);\n vec2 normalIn = vec2(-tangentIn.y, tangentIn.x);\n vec2 normalOut = vec2(-tangentOut.y, tangentOut.x);\n float side = sign(aSide);\n float sideEnum = abs(aSide);\n\n // We generate vertices for joins on either side of the centerline, but\n // the \"elbow\" side is the only one needing a join. By not setting the\n // offset for the other side, all its vertices will end up in the same\n // spot and not render, effectively discarding it.\n if (sign(dot(tangentOut, vec2(-tangentIn.y, tangentIn.x))) != side) {\n // Side enums:\n // 1: the side going into the join\n // 2: the middle of the join\n // 3: the side going out of the join\n if (sideEnum == 2.) {\n // Calculate the position + tangent on either side of the join, and\n // find where the lines intersect to find the elbow of the join\n vec2 c = (posp.xy/posp.w + vec2(1.,1.)) * 0.5 * uViewport.zw;\n vec2 intersection = lineIntersection(\n c + (side * normalIn * uStrokeWeight / 2.),\n tangentIn,\n c + (side * normalOut * uStrokeWeight / 2.),\n tangentOut\n );\n offset = (intersection - c);\n\n // When lines are thick and the angle of the join approaches 180, the\n // elbow might be really far from the center. We'll apply a limit to\n // the magnitude to avoid lines going across the whole screen when this\n // happens.\n float mag = length(offset);\n float maxMag = 3. * uStrokeWeight;\n if (mag > maxMag) {\n offset *= maxMag / mag;\n }\n } else if (sideEnum == 1.) {\n offset = side * normalIn * uStrokeWeight / 2.;\n } else if (sideEnum == 3.) {\n offset = side * normalOut * uStrokeWeight / 2.;\n }\n }\n if (uStrokeJoin == STROKE_JOIN_BEVEL) {\n vec2 avgNormal = vec2(-vTangent.y, vTangent.x);\n vMaxDist = abs(dot(avgNormal, normalIn * uStrokeWeight / 2.));\n } else {\n vMaxDist = uStrokeWeight / 2.;\n }\n } else {\n vec2 tangent = aTangentIn == vec3(0.) ? tangentOut : tangentIn;\n vTangent = tangent;\n vec2 normal = vec2(-tangent.y, tangent.x);\n\n float normalOffset = sign(aSide);\n // Caps will have side values of -2 or 2 on the edge of the cap that\n // extends out from the line\n float tangentOffset = abs(aSide) - 1.;\n offset = (normal * normalOffset + tangent * tangentOffset) *\n uStrokeWeight * 0.5;\n vMaxDist = uStrokeWeight / 2.;\n }\n vPosition = vCenter + offset;\n\n gl_Position.xy = p.xy + offset.xy * curPerspScale;\n gl_Position.zw = p.zw;\n \n vColor = (uUseLineColor ? aVertexColor : uMaterialColor);\n}\n",lineFrag:T+"precision mediump int;\n\nuniform vec4 uMaterialColor;\nuniform int uStrokeCap;\nuniform int uStrokeJoin;\nuniform float uStrokeWeight;\n\nIN vec4 vColor;\nIN vec2 vTangent;\nIN vec2 vCenter;\nIN vec2 vPosition;\nIN float vMaxDist;\nIN float vCap;\nIN float vJoin;\n\nfloat distSquared(vec2 a, vec2 b) {\n vec2 aToB = b - a;\n return dot(aToB, aToB);\n}\n\nvoid main() {\n if (vCap > 0.) {\n if (\n uStrokeCap == STROKE_CAP_ROUND &&\n distSquared(vPosition, vCenter) > uStrokeWeight * uStrokeWeight * 0.25\n ) {\n discard;\n } else if (\n uStrokeCap == STROKE_CAP_SQUARE &&\n dot(vPosition - vCenter, vTangent) > 0.\n ) {\n discard;\n }\n // Use full area for PROJECT\n } else if (vJoin > 0.) {\n if (\n uStrokeJoin == STROKE_JOIN_ROUND &&\n distSquared(vPosition, vCenter) > uStrokeWeight * uStrokeWeight * 0.25\n ) {\n discard;\n } else if (uStrokeJoin == STROKE_JOIN_BEVEL) {\n vec2 normal = vec2(-vTangent.y, vTangent.x);\n if (abs(dot(vPosition - vCenter, normal)) > vMaxDist) {\n discard;\n }\n }\n // Use full area for MITER\n }\n OUT_COLOR = vec4(vColor.rgb, 1.) * vColor.a;\n}\n",pointVert:"IN vec3 aPosition;\nuniform float uPointSize;\nOUT float vStrokeWeight;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nvoid main() {\n\tvec4 positionVec4 = vec4(aPosition, 1.0);\n\tgl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n\tgl_PointSize = uPointSize;\n\tvStrokeWeight = uPointSize;\n}\n",pointFrag:"precision mediump int;\nuniform vec4 uMaterialColor;\nIN float vStrokeWeight;\n\nvoid main(){\n float mask = 0.0;\n\n // make a circular mask using the gl_PointCoord (goes from 0 - 1 on a point)\n // might be able to get a nicer edge on big strokeweights with smoothstep but slightly less performant\n\n mask = step(0.98, length(gl_PointCoord * 2.0 - 1.0));\n\n // if strokeWeight is 1 or less lets just draw a square\n // this prevents weird artifacting from carving circles when our points are really small\n // if strokeWeight is larger than 1, we just use it as is\n\n mask = mix(0.0, mask, clamp(floor(vStrokeWeight - 0.5),0.0,1.0));\n\n // throw away the borders of the mask\n // otherwise we get weird alpha blending issues\n\n if(mask > 0.98){\n discard;\n }\n\n OUT_COLOR = vec4(uMaterialColor.rgb, 1.) * uMaterialColor.a;\n}\n",imageLightVert:"precision highp float;\nattribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nvarying vec3 localPos;\nvarying vec3 vWorldNormal;\nvarying vec3 vWorldPosition;\nvarying vec2 vTexCoord;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nvoid main() {\n // Multiply the position by the matrix.\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * viewModelPosition; \n \n // orient the normals and pass to the fragment shader\n vWorldNormal = uNormalMatrix * aNormal;\n \n // send the view position to the fragment shader\n vWorldPosition = (uModelViewMatrix * vec4(aPosition, 1.0)).xyz;\n \n localPos = vWorldPosition;\n vTexCoord = aTexCoord;\n}\n\n\n/*\nin the vertex shader we'll compute the world position and world oriented normal of the vertices and pass those to the fragment shader as varyings.\n*/\n",imageLightDiffusedFrag:"precision highp float;\nvarying vec3 localPos;\n\n// the HDR cubemap converted (can be from an equirectangular environment map.)\nuniform sampler2D environmentMap;\nvarying vec2 vTexCoord;\n\nconst float PI = 3.14159265359;\n\nvec2 nTOE( vec3 v ){\n // x = r sin(phi) cos(theta) \n // y = r cos(phi) \n // z = r sin(phi) sin(theta)\n float phi = acos( v.y );\n // if phi is 0, then there are no x, z components\n float theta = 0.0;\n // else \n theta = acos(v.x / sin(phi));\n float sinTheta = v.z / sin(phi);\n if (sinTheta < 0.0) {\n // Turn it into -theta, but in the 0-2PI range\n theta = 2.0 * PI - theta;\n }\n theta = theta / (2.0 * 3.14159);\n phi = phi / 3.14159 ;\n \n vec2 angles = vec2( phi, theta );\n return angles;\n}\n\nfloat random(vec2 p) {\n vec3 p3 = fract(vec3(p.xyx) * .1031);\n p3 += dot(p3, p3.yzx + 33.33);\n return fract((p3.x + p3.y) * p3.z);\n}\n\nvoid main()\n{ \t \n\t// the sample direction equals the hemisphere's orientation\n float phi = vTexCoord.x * 2.0 * PI;\n float theta = vTexCoord.y * PI;\n float x = sin(theta) * cos(phi);\n float y = sin(theta) * sin(phi);\n float z = cos(theta);\n vec3 normal = vec3( x, y, z);\n\n\t// Discretely sampling the hemisphere given the integral's\n // spherical coordinates translates to the following fragment code:\n\tvec3 irradiance = vec3(0.0); \n\tvec3 up\t= vec3(0.0, 1.0, 0.0);\n\tvec3 right = normalize(cross(up, normal));\n\tup = normalize(cross(normal, right));\n\n\t// We specify a fixed sampleDelta delta value to traverse\n // the hemisphere; decreasing or increasing the sample delta\n // will increase or decrease the accuracy respectively.\n\tconst float sampleDelta = 0.100;\n\tfloat nrSamples = 0.0;\n float randomOffset = random(gl_FragCoord.xy) * sampleDelta;\n\tfor(float rawPhi = 0.0; rawPhi < 2.0 * PI; rawPhi += sampleDelta)\n\t{\n float phi = rawPhi + randomOffset;\n for(float rawTheta = 0.0; rawTheta < ( 0.5 ) * PI; rawTheta += sampleDelta)\n {\n float theta = rawTheta + randomOffset;\n // spherical to cartesian (in tangent space) // tangent space to world // add each sample result to irradiance\n float x = sin(theta) * cos(phi);\n float y = sin(theta) * sin(phi);\n float z = cos(theta);\n vec3 tangentSample = vec3( x, y, z);\n \n vec3 sampleVec = tangentSample.x * right + tangentSample.y * up + tangentSample.z * normal;\n irradiance += (texture2D(environmentMap, nTOE(sampleVec)).xyz) * cos(theta) * sin(theta);\n nrSamples++;\n }\n\t}\n\t// divide by the total number of samples taken, giving us the average sampled irradiance.\n\tirradiance = PI * irradiance * (1.0 / float(nrSamples )) ;\n \n \n\tgl_FragColor = vec4(irradiance, 1.0);\n}",imageLightSpecularFrag:"precision highp float;\r\nvarying vec3 localPos;\r\nvarying vec2 vTexCoord;\r\n\r\n// our texture\r\nuniform sampler2D environmentMap;\r\nuniform float roughness;\r\n\r\nconst float PI = 3.14159265359;\r\n\r\nfloat VanDerCorput(int bits);\r\nvec2 HammersleyNoBitOps(int i, int N);\r\nvec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness);\r\n\r\n\r\nvec2 nTOE( vec3 v ){\r\n // x = r sin(phi) cos(theta) \r\n // y = r cos(phi) \r\n // z = r sin(phi) sin(theta)\r\n float phi = acos( v.y );\r\n // if phi is 0, then there are no x, z components\r\n float theta = 0.0;\r\n // else \r\n theta = acos(v.x / sin(phi));\r\n float sinTheta = v.z / sin(phi);\r\n if (sinTheta < 0.0) {\r\n // Turn it into -theta, but in the 0-2PI range\r\n theta = 2.0 * PI - theta;\r\n }\r\n theta = theta / (2.0 * 3.14159);\r\n phi = phi / 3.14159 ;\r\n \r\n vec2 angles = vec2( phi, theta );\r\n return angles;\r\n}\r\n\r\n\r\nvoid main(){\r\n const int SAMPLE_COUNT = 400; // 4096\r\n int lowRoughnessLimit = int(pow(2.0,(roughness+0.1)*20.0));\r\n float totalWeight = 0.0;\r\n vec3 prefilteredColor = vec3(0.0);\r\n float phi = vTexCoord.x * 2.0 * PI;\r\n float theta = vTexCoord.y * PI;\r\n float x = sin(theta) * cos(phi);\r\n float y = sin(theta) * sin(phi);\r\n float z = cos(theta);\r\n vec3 N = vec3(x,y,z);\r\n vec3 V = N;\r\n for (int i = 0; i < SAMPLE_COUNT; ++i)\r\n {\r\n // break at smaller sample numbers for low roughness levels\r\n if(i == lowRoughnessLimit)\r\n {\r\n break;\r\n }\r\n vec2 Xi = HammersleyNoBitOps(i, SAMPLE_COUNT);\r\n vec3 H = ImportanceSampleGGX(Xi, N, roughness);\r\n vec3 L = normalize(2.0 * dot(V, H) * H - V);\r\n\r\n float NdotL = max(dot(N, L), 0.0);\r\n if (NdotL > 0.0)\r\n {\r\n prefilteredColor += texture2D(environmentMap, nTOE(L)).xyz * NdotL;\r\n totalWeight += NdotL;\r\n }\r\n }\r\n prefilteredColor = prefilteredColor / totalWeight;\r\n\r\n gl_FragColor = vec4(prefilteredColor, 1.0);\r\n}\r\n\r\nvec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness){\r\n float a = roughness * roughness;\r\n\r\n float phi = 2.0 * PI * Xi.x;\r\n float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a * a - 1.0) * Xi.y));\r\n float sinTheta = sqrt(1.0 - cosTheta * cosTheta);\r\n // from spherical coordinates to cartesian coordinates\r\n vec3 H;\r\n H.x = cos(phi) * sinTheta;\r\n H.y = sin(phi) * sinTheta;\r\n H.z = cosTheta;\r\n\r\n // from tangent-space vector to world-space sample vector\r\n vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);\r\n vec3 tangent = normalize(cross(up, N));\r\n vec3 bitangent = cross(N, tangent);\r\n\r\n vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z;\r\n return normalize(sampleVec);\r\n}\r\n\r\n\r\nfloat VanDerCorput(int n, int base)\r\n{\r\n#ifdef WEBGL2\r\n\r\n uint bits = uint(n);\r\n bits = (bits << 16u) | (bits >> 16u);\r\n bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);\r\n bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);\r\n bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);\r\n bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);\r\n return float(bits) * 2.3283064365386963e-10; // / 0x100000000\r\n\r\n#else\r\n\r\n float invBase = 1.0 / float(base);\r\n float denom = 1.0;\r\n float result = 0.0;\r\n\r\n\r\n for (int i = 0; i < 32; ++i)\r\n {\r\n if (n > 0)\r\n {\r\n denom = mod(float(n), 2.0);\r\n result += denom * invBase;\r\n invBase = invBase / 2.0;\r\n n = int(float(n) / 2.0);\r\n }\r\n }\r\n\r\n\r\n return result;\r\n\r\n#endif\r\n}\r\n\r\nvec2 HammersleyNoBitOps(int i, int N)\r\n{\r\n return vec2(float(i) / float(N), VanDerCorput(i, 2));\r\n}\r\n"},M=E.sphereMappingFrag;for(x in E)E[x]="#ifdef WEBGL2\n\n#define IN in\n#define OUT out\n\n#ifdef FRAGMENT_SHADER\nout vec4 outColor;\n#define OUT_COLOR outColor\n#endif\n#define TEXTURE texture\n\n#else\n\n#ifdef FRAGMENT_SHADER\n#define IN varying\n#else\n#define IN attribute\n#endif\n#define OUT varying\n#define TEXTURE texture2D\n\n#ifdef FRAGMENT_SHADER\n#define OUT_COLOR gl_FragColor\n#endif\n\n#endif\n"+E[x];j(e={},l.GRAY,"precision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\n\nfloat luma(vec3 color) {\n // weighted grayscale with luminance values\n return dot(color, vec3(0.2126, 0.7152, 0.0722));\n}\n\nvoid main() {\n vec4 tex = texture2D(tex0, vTexCoord);\n float gray = luma(tex.rgb);\n gl_FragColor = vec4(gray, gray, gray, tex.a);\n}\n"),j(e,l.ERODE,"// Reduces the bright areas in an image\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\nuniform vec2 texelSize;\n\nfloat luma(vec3 color) {\n // weighted grayscale with luminance values\n // weights 77, 151, 28 taken from src/image/filters.js\n return dot(color, vec3(0.300781, 0.589844, 0.109375));\n}\n\nvoid main() {\n vec4 color = texture2D(tex0, vTexCoord);\n float lum = luma(color.rgb);\n\n // set current color as the darkest neighbor color\n\n vec4 neighbors[4];\n neighbors[0] = texture2D(tex0, vTexCoord + vec2( texelSize.x, 0.0));\n neighbors[1] = texture2D(tex0, vTexCoord + vec2(-texelSize.x, 0.0));\n neighbors[2] = texture2D(tex0, vTexCoord + vec2(0.0, texelSize.y));\n neighbors[3] = texture2D(tex0, vTexCoord + vec2(0.0, -texelSize.y));\n\n for (int i = 0; i < 4; i++) {\n vec4 neighborColor = neighbors[i];\n float neighborLum = luma(neighborColor.rgb);\n\n if (neighborLum < lum) {\n color = neighborColor;\n lum = neighborLum;\n }\n }\n\n gl_FragColor = color;\n}\n"),j(e,l.DILATE,"// Increase the bright areas in an image\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\nuniform vec2 texelSize;\n\nfloat luma(vec3 color) {\n // weighted grayscale with luminance values\n // weights 77, 151, 28 taken from src/image/filters.js\n return dot(color, vec3(0.300781, 0.589844, 0.109375));\n}\n\nvoid main() {\n vec4 color = texture2D(tex0, vTexCoord);\n float lum = luma(color.rgb);\n\n // set current color as the brightest neighbor color\n\n vec4 neighbors[4];\n neighbors[0] = texture2D(tex0, vTexCoord + vec2( texelSize.x, 0.0));\n neighbors[1] = texture2D(tex0, vTexCoord + vec2(-texelSize.x, 0.0));\n neighbors[2] = texture2D(tex0, vTexCoord + vec2(0.0, texelSize.y));\n neighbors[3] = texture2D(tex0, vTexCoord + vec2(0.0, -texelSize.y));\n\n for (int i = 0; i < 4; i++) {\n vec4 neighborColor = neighbors[i];\n float neighborLum = luma(neighborColor.rgb);\n\n if (neighborLum > lum) {\n color = neighborColor;\n lum = neighborLum;\n }\n }\n\n gl_FragColor = color;\n}\n"),j(e,l.BLUR,"precision highp float;\n\n// Two-pass blur filter, unweighted kernel.\n// See also a similar blur at Adam Ferriss' repo of shader examples:\n// https://github.com/aferriss/p5jsShaderExamples/blob/gh-pages/4_image-effects/4-9_single-pass-blur/effect.frag\n\n\nuniform sampler2D tex0;\nvarying vec2 vTexCoord;\nuniform vec2 direction;\nuniform vec2 canvasSize;\nuniform float radius;\n\nfloat random(vec2 p) {\n vec3 p3 = fract(vec3(p.xyx) * .1031);\n p3 += dot(p3, p3.yzx + 33.33);\n return fract((p3.x + p3.y) * p3.z);\n}\n\n// This isn't a real Gaussian weight, it's a quadratic weight. It's what the\n// CPU mode's blur uses though, so we also use it here to match.\nfloat quadWeight(float x, float e) {\n return pow(e-abs(x), 2.);\n}\n\nvoid main(){\n vec2 uv = vTexCoord;\n\n // A reasonable maximum number of samples\n const float maxSamples = 64.0;\n\n float numSamples = floor(7. * radius);\n if (fract(numSamples / 2.) == 0.) {\n numSamples++;\n }\n vec4 avg = vec4(0.0);\n float total = 0.0;\n\n // Calculate the spacing to avoid skewing if numSamples > maxSamples\n float spacing = 1.0;\n if (numSamples > maxSamples) {\n spacing = numSamples / maxSamples;\n numSamples = maxSamples;\n }\n\n float randomOffset = (spacing - 1.0) * mix(-0.5, 0.5, random(gl_FragCoord.xy));\n for (float i = 0.0; i < maxSamples; i++) {\n if (i >= numSamples) break;\n\n float sample = i * spacing - (numSamples - 1.0) * 0.5 * spacing + randomOffset;\n vec2 sampleCoord = uv + vec2(sample, sample) / canvasSize * direction;\n float weight = quadWeight(sample, (numSamples - 1.0) * 0.5 * spacing);\n\n avg += weight * texture2D(tex0, sampleCoord);\n total += weight;\n }\n\n avg /= total;\n gl_FragColor = avg;\n}\n"),j(e,l.POSTERIZE,"// Limit color space for a stylized cartoon / poster effect\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\nuniform float filterParameter;\n\nvec3 quantize(vec3 color, float n) {\n // restrict values to N options/bins\n // and floor each channel to nearest value\n //\n // eg. when N = 5, values = 0.0, 0.25, 0.50, 0.75, 1.0\n // then quantize (0.1, 0.7, 0.9) -> (0.0, 0.5, 1.0)\n\n color = color * n;\n color = floor(color);\n color = color / (n - 1.0);\n return color;\n}\n\nvoid main() {\n vec4 color = texture2D(tex0, vTexCoord);\n\n vec3 restrictedColor = quantize(color.rgb / color.a, filterParameter);\n\n gl_FragColor = vec4(restrictedColor.rgb * color.a, color.a);\n}\n"),j(e,l.OPAQUE,"// Set alpha channel to entirely opaque\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\n\nvoid main() {\n vec4 color = texture2D(tex0, vTexCoord);\n gl_FragColor = vec4(color.rgb / color.a, 1.0);\n}\n"),j(e,l.INVERT,"// Set each pixel to inverse value\n// Note that original INVERT does not change the opacity, so this follows suit\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\n\nvoid main() {\nvec4 color = texture2D(tex0, vTexCoord);\nvec3 origColor = color.rgb / color.a;\nvec3 invertedColor = vec3(1.0) - origColor;\ngl_FragColor = vec4(invertedColor * color.a, color.a);\n}\n"),j(e,l.THRESHOLD,"// Convert pixels to either white or black, \n// depending on if their luma is above or below filterParameter\n\nprecision highp float;\n\nvarying vec2 vTexCoord;\n\nuniform sampler2D tex0;\nuniform float filterParameter;\n\nfloat luma(vec3 color) {\n // weighted grayscale with luminance values\n return dot(color, vec3(0.2126, 0.7152, 0.0722));\n}\n\nvoid main() {\n vec4 color = texture2D(tex0, vTexCoord);\n float gray = luma(color.rgb / color.a);\n // floor() used to match src/image/filters.js\n float threshold = floor(filterParameter * 255.0) / 255.0;\n float blackOrWhite = step(threshold, gray);\n gl_FragColor = vec4(vec3(blackOrWhite) * color.a, color.a);\n}\n");var k=e;function O(e,t,r,o,n,s,i,a,l,u){var c=t.getParameter(t.FRAMEBUFFER_BINDING),r=(t.bindFramebuffer(t.FRAMEBUFFER,r),a===t.RGBA?4:3),d=s*i*r,h=l===t.UNSIGNED_BYTE?Uint8Array:Float32Array;if(e instanceof h&&e.length===d||(e=new h(d)),t.readPixels(o,u?u-n-i:n,s,i,a,l,e),t.bindFramebuffer(t.FRAMEBUFFER,c),u)for(var f=Math.floor(i/2),p=new h(s*r),m=0;m>7,127&d,c>>7,127&c);for(var h=0;h>7,127&f,0,0)}}return{cellImageInfo:a,dimOffset:t,dimImageInfo:n}}}}]),t}();B.default.RendererGL.prototype._renderText=function(e,t,r,o,n){if(this._textFont&&"string"!=typeof this._textFont){if(!(n<=o)&&this._doFill){if(this._isOpenType()){e.push();var n=this._doStroke,s=this.drawMode,i=(this._doStroke=!1,this.drawMode=E.TEXTURE,this._textFont.font),a=(a=this._textFont._fontInfo)||(this._textFont._fontInfo=new M(i)),r=this._textFont._handleAlignment(this,t,r,o),o=this._textSize/i.unitsPerEm,l=(this.translate(r.x,r.y,0),this.scale(o,o,1),this.GL),r=!this._defaultFontShader,u=this._getFontShader(),c=(u.init(),u.bindShader(),r&&(u.setUniform("uGridImageSize",[64,64]),u.setUniform("uCellsImageSize",[64,64]),u.setUniform("uStrokeImageSize",[64,64]),u.setUniform("uGridSize",[9,9])),this._applyColorBlend(this.curFillColor),this.retainedMode.geometry.glyph),d=(c||((o=this._textGeom=new B.default.Geometry(1,1,function(){for(var e=0;e<=1;e++)for(var t=0;t<=1;t++)this.vertices.push(new B.default.Vector(t,e,0)),this.uvs.push(t,e)})).computeFaces().computeNormals(),c=this.createBuffers("glyph",o)),!0),r=!1,o=void 0;try{for(var h,f=this.retainedMode.buffers.text[Symbol.iterator]();!(d=(h=f.next()).done);d=!0)h.value._prepareBuffer(c,u)}catch(e){r=!0,o=e}finally{try{d||null==f.return||f.return()}finally{if(r)throw o}}this._bindBuffer(c.indexBuffer,l.ELEMENT_ARRAY_BUFFER),u.setUniform("uMaterialColor",this.curFillColor),l.pixelStorei(l.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1);try{var p=0,m=null,y=i.stringToGlyphs(t),g=!0,v=!1,b=void 0;try{for(var j,_=y[Symbol.iterator]();!(g=(j=_.next()).done);g=!0){var x,w,S=j.value,T=(m&&(p+=i.getKerningValue(m,S)),a.getGlyphInfo(S));T.uGlyphRect&&(x=T.rowInfo,w=T.colInfo,u.setUniform("uSamplerStrokes",T.strokeImageInfo.imageData),u.setUniform("uSamplerRowStrokes",x.cellImageInfo.imageData),u.setUniform("uSamplerRows",x.dimImageInfo.imageData),u.setUniform("uSamplerColStrokes",w.cellImageInfo.imageData),u.setUniform("uSamplerCols",w.dimImageInfo.imageData),u.setUniform("uGridOffset",T.uGridOffset),u.setUniform("uGlyphRect",T.uGlyphRect),u.setUniform("uGlyphOffset",p),u.bindTextures(),l.drawElements(l.TRIANGLES,6,this.GL.UNSIGNED_SHORT,0)),p+=S.advanceWidth,m=S}}catch(e){v=!0,b=e}finally{try{g||null==_.return||_.return()}finally{if(v)throw b}}}finally{u.unbindShader(),this._doStroke=n,this.drawMode=s,l.pixelStorei(l.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),e.pop()}}else console.log("WEBGL: only Opentype (.otf) and Truetype (.ttf) fonts are supported");return e}}else console.log("WEBGL: you must load and set a font before drawing text. See `loadFont` and `textFont` for more details.")}},{"../core/constants":272,"../core/main":283,"./p5.RendererGL.Retained":340,"./p5.Shader":342,"core-js/modules/es.array.iterator":165,"core-js/modules/es.object.get-own-property-descriptor":186,"core-js/modules/es.object.to-string":190,"core-js/modules/es.regexp.exec":195,"core-js/modules/es.string.iterator":200,"core-js/modules/es.string.split":206,"core-js/modules/es.string.sub":208,"core-js/modules/es.symbol":212,"core-js/modules/es.symbol.description":210,"core-js/modules/es.symbol.iterator":211,"core-js/modules/es.weak-map":244,"core-js/modules/web.dom-collections.iterator":246}]},{},[267])(267)}); \ No newline at end of file diff --git a/js/socket-v2.3.0.io.slim.js b/js/socket-v2.3.0.io.slim.js new file mode 100644 index 0000000..2d89d90 --- /dev/null +++ b/js/socket-v2.3.0.io.slim.js @@ -0,0 +1,9 @@ +/*! + * Socket.IO v2.3.0 + * (c) 2014-2019 Guillermo Rauch + * Released under the MIT License. + */ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.io=e():t.io=e()}(this,function(){return function(t){function e(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return t[n].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var r={};return e.m=t,e.c=r,e.p="",e(0)}([function(t,e,r){"use strict";function n(t,e){"object"===("undefined"==typeof t?"undefined":o(t))&&(e=t,t=void 0),e=e||{};var r,n=i(t),s=n.source,p=n.id,h=n.path,u=c[p]&&h in c[p].nsps,f=e.forceNew||e["force new connection"]||!1===e.multiplex||u;return f?r=a(s,e):(c[p]||(c[p]=a(s,e)),r=c[p]),n.query&&!e.query&&(e.query=n.query),r.socket(n.path,e)}var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(1),s=r(4),a=r(9);r(3)("socket.io-client");t.exports=e=n;var c=e.managers={};e.protocol=s.protocol,e.connect=n,e.Manager=r(9),e.Socket=r(33)},function(t,e,r){"use strict";function n(t,e){var r=t;e=e||"undefined"!=typeof location&&location,null==t&&(t=e.protocol+"//"+e.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?e.protocol+t:e.host+t),/^(https?|wss?):\/\//.test(t)||(t="undefined"!=typeof e?e.protocol+"//"+t:"https://"+t),r=o(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";var n=r.host.indexOf(":")!==-1,i=n?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port,r.href=r.protocol+"://"+i+(e&&e.port===r.port?"":":"+r.port),r}var o=r(2);r(3)("socket.io-client:url");t.exports=n},function(t,e){var r=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,n=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.exports=function(t){var e=t,o=t.indexOf("["),i=t.indexOf("]");o!=-1&&i!=-1&&(t=t.substring(0,o)+t.substring(o,i).replace(/:/g,";")+t.substring(i,t.length));for(var s=r.exec(t||""),a={},c=14;c--;)a[n[c]]=s[c]||"";return o!=-1&&i!=-1&&(a.source=e,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a}},function(t,e){"use strict";t.exports=function(){return function(){}}},function(t,e,r){function n(){}function o(t){var r=""+t.type;if(e.BINARY_EVENT!==t.type&&e.BINARY_ACK!==t.type||(r+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(r+=t.nsp+","),null!=t.id&&(r+=t.id),null!=t.data){var n=i(t.data);if(n===!1)return m;r+=n}return r}function i(t){try{return JSON.stringify(t)}catch(t){return!1}}function s(t,e){function r(t){var r=l.deconstructPacket(t),n=o(r.packet),i=r.buffers;i.unshift(n),e(i)}l.removeBlobs(t,r)}function a(){this.reconstructor=null}function c(t){var r=0,n={type:Number(t.charAt(0))};if(null==e.types[n.type])return u("unknown packet type "+n.type);if(e.BINARY_EVENT===n.type||e.BINARY_ACK===n.type){for(var o="";"-"!==t.charAt(++r)&&(o+=t.charAt(r),r!=t.length););if(o!=Number(o)||"-"!==t.charAt(r))throw new Error("Illegal attachments");n.attachments=Number(o)}if("/"===t.charAt(r+1))for(n.nsp="";++r;){var i=t.charAt(r);if(","===i)break;if(n.nsp+=i,r===t.length)break}else n.nsp="/";var s=t.charAt(r+1);if(""!==s&&Number(s)==s){for(n.id="";++r;){var i=t.charAt(r);if(null==i||Number(i)!=i){--r;break}if(n.id+=t.charAt(r),r===t.length)break}n.id=Number(n.id)}if(t.charAt(++r)){var a=p(t.substr(r)),c=a!==!1&&(n.type===e.ERROR||d(a));if(!c)return u("invalid payload");n.data=a}return n}function p(t){try{return JSON.parse(t)}catch(t){return!1}}function h(t){this.reconPack=t,this.buffers=[]}function u(t){return{type:e.ERROR,data:"parser error: "+t}}var f=(r(3)("socket.io-parser"),r(5)),l=r(6),d=r(7),y=r(8);e.protocol=4,e.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],e.CONNECT=0,e.DISCONNECT=1,e.EVENT=2,e.ACK=3,e.ERROR=4,e.BINARY_EVENT=5,e.BINARY_ACK=6,e.Encoder=n,e.Decoder=a;var m=e.ERROR+'"encode error"';n.prototype.encode=function(t,r){if(e.BINARY_EVENT===t.type||e.BINARY_ACK===t.type)s(t,r);else{var n=o(t);r([n])}},f(a.prototype),a.prototype.add=function(t){var r;if("string"==typeof t)r=c(t),e.BINARY_EVENT===r.type||e.BINARY_ACK===r.type?(this.reconstructor=new h(r),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",r)):this.emit("decoded",r);else{if(!y(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");r=this.reconstructor.takeBinaryData(t),r&&(this.reconstructor=null,this.emit("decoded",r))}},a.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},h.prototype.takeBinaryData=function(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){var e=l.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null},h.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]}},function(t,e,r){function n(t){if(t)return o(t)}function o(t){for(var e in n.prototype)t[e]=n.prototype[e];return t}t.exports=n,n.prototype.on=n.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},n.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var n,o=0;o0&&!this.encoding){var t=this.packetBuffer.shift();this.packet(t)}},n.prototype.cleanup=function(){for(var t=this.subs.length,e=0;e=this._reconnectionAttempts)this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var e=this.backoff.duration();this.reconnecting=!0;var r=setTimeout(function(){t.skipReconnect||(t.emitAll("reconnect_attempt",t.backoff.attempts),t.emitAll("reconnecting",t.backoff.attempts),t.skipReconnect||t.open(function(e){e?(t.reconnecting=!1,t.reconnect(),t.emitAll("reconnect_error",e.data)):t.onreconnect()}))},e);this.subs.push({destroy:function(){clearTimeout(r)}})}},n.prototype.onreconnect=function(){var t=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",t)}},function(t,e,r){t.exports=r(11),t.exports.parser=r(18)},function(t,e,r){function n(t,e){return this instanceof n?(e=e||{},t&&"object"==typeof t&&(e=t,t=null),t?(t=p(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=p(e.host).host),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.agent=e.agent||!1,this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?443:80),this.query=e.query||{},"string"==typeof this.query&&(this.query=h.decode(this.query)),this.upgrade=!1!==e.upgrade,this.path=(e.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!e.forceJSONP,this.jsonp=!1!==e.jsonp,this.forceBase64=!!e.forceBase64,this.enablesXDR=!!e.enablesXDR,this.withCredentials=!1!==e.withCredentials,this.timestampParam=e.timestampParam||"t",this.timestampRequests=e.timestampRequests,this.transports=e.transports||["polling","websocket"],this.transportOptions=e.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=e.policyPort||843,this.rememberUpgrade=e.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=e.onlyBinaryUpgrades,this.perMessageDeflate=!1!==e.perMessageDeflate&&(e.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=e.pfx||null,this.key=e.key||null,this.passphrase=e.passphrase||null,this.cert=e.cert||null,this.ca=e.ca||null,this.ciphers=e.ciphers||null,this.rejectUnauthorized=void 0===e.rejectUnauthorized||e.rejectUnauthorized,this.forceNode=!!e.forceNode,this.isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),("undefined"==typeof self||this.isReactNative)&&(e.extraHeaders&&Object.keys(e.extraHeaders).length>0&&(this.extraHeaders=e.extraHeaders),e.localAddress&&(this.localAddress=e.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,void this.open()):new n(t,e)}function o(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);return e}var i=r(12),s=r(5),a=(r(3)("engine.io-client:socket"),r(32)),c=r(18),p=r(2),h=r(26);t.exports=n,n.priorWebsocketSuccess=!1,s(n.prototype),n.protocol=c.protocol,n.Socket=n,n.Transport=r(17),n.transports=r(12),n.parser=r(18),n.prototype.createTransport=function(t){var e=o(this.query);e.EIO=c.protocol,e.transport=t;var r=this.transportOptions[t]||{};this.id&&(e.sid=this.id);var n=new i[t]({query:e,socket:this,agent:r.agent||this.agent,hostname:r.hostname||this.hostname,port:r.port||this.port,secure:r.secure||this.secure,path:r.path||this.path,forceJSONP:r.forceJSONP||this.forceJSONP,jsonp:r.jsonp||this.jsonp,forceBase64:r.forceBase64||this.forceBase64,enablesXDR:r.enablesXDR||this.enablesXDR,withCredentials:r.withCredentials||this.withCredentials,timestampRequests:r.timestampRequests||this.timestampRequests,timestampParam:r.timestampParam||this.timestampParam,policyPort:r.policyPort||this.policyPort,pfx:r.pfx||this.pfx,key:r.key||this.key,passphrase:r.passphrase||this.passphrase,cert:r.cert||this.cert,ca:r.ca||this.ca,ciphers:r.ciphers||this.ciphers,rejectUnauthorized:r.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:r.perMessageDeflate||this.perMessageDeflate,extraHeaders:r.extraHeaders||this.extraHeaders,forceNode:r.forceNode||this.forceNode,localAddress:r.localAddress||this.localAddress,requestTimeout:r.requestTimeout||this.requestTimeout,protocols:r.protocols||void 0,isReactNative:this.isReactNative});return n},n.prototype.open=function(){var t;if(this.rememberUpgrade&&n.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else{if(0===this.transports.length){var e=this;return void setTimeout(function(){e.emit("error","No transports available")},0)}t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)},n.prototype.setTransport=function(t){var e=this;this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",function(){e.onDrain()}).on("packet",function(t){e.onPacket(t)}).on("error",function(t){e.onError(t)}).on("close",function(){e.onClose("transport close")})},n.prototype.probe=function(t){function e(){if(u.onlyBinaryUpgrades){var t=!this.supportsBinary&&u.transport.supportsBinary;h=h||t}h||(p.send([{type:"ping",data:"probe"}]),p.once("packet",function(t){if(!h)if("pong"===t.type&&"probe"===t.data){if(u.upgrading=!0,u.emit("upgrading",p),!p)return;n.priorWebsocketSuccess="websocket"===p.name,u.transport.pause(function(){h||"closed"!==u.readyState&&(c(),u.setTransport(p),p.send([{type:"upgrade"}]),u.emit("upgrade",p),p=null,u.upgrading=!1,u.flush())})}else{var e=new Error("probe error");e.transport=p.name,u.emit("upgradeError",e)}}))}function r(){h||(h=!0,c(),p.close(),p=null)}function o(t){var e=new Error("probe error: "+t);e.transport=p.name,r(),u.emit("upgradeError",e)}function i(){o("transport closed")}function s(){o("socket closed")}function a(t){p&&t.name!==p.name&&r()}function c(){p.removeListener("open",e),p.removeListener("error",o),p.removeListener("close",i),u.removeListener("close",s),u.removeListener("upgrading",a)}var p=this.createTransport(t,{probe:1}),h=!1,u=this;n.priorWebsocketSuccess=!1,p.once("open",e),p.once("error",o),p.once("close",i),this.once("close",s),this.once("upgrading",a),p.open()},n.prototype.onOpen=function(){if(this.readyState="open",n.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause)for(var t=0,e=this.upgrades.length;t1?{type:b[o],data:t.substring(1)}:{type:b[o]}:k}var i=new Uint8Array(t),o=i[0],s=f(t,1);return w&&"blob"===r&&(s=new w([s])),{type:b[o],data:s}},e.decodeBase64Packet=function(t,e){var r=b[t.charAt(0)];if(!p)return{type:r,data:{base64:!0,data:t.substr(1)}};var n=p.decode(t.substr(1));return"blob"===e&&w&&(n=new w([n])),{type:r,data:n}},e.encodePayload=function(t,r,n){function o(t){return t.length+":"+t}function i(t,n){e.encodePacket(t,!!s&&r,!1,function(t){n(null,o(t))})}"function"==typeof r&&(n=r,r=null);var s=u(t);return r&&s?w&&!g?e.encodePayloadAsBlob(t,n):e.encodePayloadAsArrayBuffer(t,n):t.length?void c(t,i,function(t,e){return n(e.join(""))}):n("0:")},e.decodePayload=function(t,r,n){if("string"!=typeof t)return e.decodePayloadAsBinary(t,r,n);"function"==typeof r&&(n=r,r=null);var o;if(""===t)return n(k,0,1);for(var i,s,a="",c=0,p=t.length;c0;){for(var s=new Uint8Array(o),a=0===s[0],c="",p=1;255!==s[p];p++){if(c.length>310)return n(k,0,1);c+=s[p]}o=f(o,2+c.length),c=parseInt(c);var h=f(o,0,c);if(a)try{h=String.fromCharCode.apply(null,new Uint8Array(h))}catch(t){var u=new Uint8Array(h);h="";for(var p=0;pn&&(r=n),e>=n||e>=r||0===n)return new ArrayBuffer(0);for(var o=new Uint8Array(t),i=new Uint8Array(r-e),s=e,a=0;s=55296&&e<=56319&&o65535&&(e-=65536,o+=d(e>>>10&1023|55296),e=56320|1023&e),o+=d(e);return o}function o(t,e){if(t>=55296&&t<=57343){if(e)throw Error("Lone surrogate U+"+t.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function i(t,e){return d(t>>e&63|128)}function s(t,e){if(0==(4294967168&t))return d(t);var r="";return 0==(4294965248&t)?r=d(t>>6&31|192):0==(4294901760&t)?(o(t,e)||(t=65533),r=d(t>>12&15|224),r+=i(t,6)):0==(4292870144&t)&&(r=d(t>>18&7|240),r+=i(t,12),r+=i(t,6)),r+=d(63&t|128)}function a(t,e){e=e||{};for(var n,o=!1!==e.strict,i=r(t),a=i.length,c=-1,p="";++c=f)throw Error("Invalid byte index");var t=255&u[l];if(l++,128==(192&t))return 63&t;throw Error("Invalid continuation byte")}function p(t){var e,r,n,i,s;if(l>f)throw Error("Invalid byte index");if(l==f)return!1;if(e=255&u[l],l++,0==(128&e))return e;if(192==(224&e)){if(r=c(),s=(31&e)<<6|r,s>=128)return s;throw Error("Invalid continuation byte")}if(224==(240&e)){if(r=c(),n=c(),s=(15&e)<<12|r<<6|n,s>=2048)return o(s,t)?s:65533;throw Error("Invalid continuation byte")}if(240==(248&e)&&(r=c(),n=c(),i=c(),s=(7&e)<<18|r<<12|n<<6|i,s>=65536&&s<=1114111))return s;throw Error("Invalid UTF-8 detected")}function h(t,e){e=e||{};var o=!1!==e.strict;u=r(t),f=u.length,l=0;for(var i,s=[];(i=p(o))!==!1;)s.push(i);return n(s)}/*! https://mths.be/utf8js v2.1.2 by @mathias */ +var u,f,l,d=String.fromCharCode;t.exports={version:"2.1.2",encode:a,decode:h}},function(t,e){!function(){"use strict";for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=new Uint8Array(256),n=0;n>2],i+=t[(3&n[r])<<4|n[r+1]>>4],i+=t[(15&n[r+1])<<2|n[r+2]>>6],i+=t[63&n[r+2]];return o%3===2?i=i.substring(0,i.length-1)+"=":o%3===1&&(i=i.substring(0,i.length-2)+"=="),i},e.decode=function(t){var e,n,o,i,s,a=.75*t.length,c=t.length,p=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);var h=new ArrayBuffer(a),u=new Uint8Array(h);for(e=0;e>4,u[p++]=(15&o)<<4|i>>2,u[p++]=(3&i)<<6|63&s;return h}}()},function(t,e){function r(t){return t.map(function(t){if(t.buffer instanceof ArrayBuffer){var e=t.buffer;if(t.byteLength!==e.byteLength){var r=new Uint8Array(t.byteLength);r.set(new Uint8Array(e,t.byteOffset,t.byteLength)),e=r.buffer}return e}return t})}function n(t,e){e=e||{};var n=new i;return r(t).forEach(function(t){n.append(t)}),e.type?n.getBlob(e.type):n.getBlob()}function o(t,e){return new Blob(r(t),e||{})}var i="undefined"!=typeof i?i:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,s=function(){try{var t=new Blob(["hi"]);return 2===t.size}catch(t){return!1}}(),a=s&&function(){try{var t=new Blob([new Uint8Array([1,2])]);return 2===t.size}catch(t){return!1}}(),c=i&&i.prototype.append&&i.prototype.getBlob;"undefined"!=typeof Blob&&(n.prototype=Blob.prototype,o.prototype=Blob.prototype),t.exports=function(){return s?a?Blob:o:c?n:void 0}()},function(t,e){e.encode=function(t){var e="";for(var r in t)t.hasOwnProperty(r)&&(e.length&&(e+="&"),e+=encodeURIComponent(r)+"="+encodeURIComponent(t[r]));return e},e.decode=function(t){for(var e={},r=t.split("&"),n=0,o=r.length;n0);return e}function n(t){var e=0;for(h=0;h';i=document.createElement(t)}catch(t){i=document.createElement("iframe"),i.name=o.iframeId,i.src="javascript:0"}i.id=o.iframeId,o.form.appendChild(i),o.iframe=i}var o=this;if(!this.form){var i,s=document.createElement("form"),a=document.createElement("textarea"),c=this.iframeId="eio_iframe_"+this.index;s.className="socketio",s.style.position="absolute",s.style.top="-1000px",s.style.left="-1000px",s.target=c,s.method="POST",s.setAttribute("accept-charset","utf-8"),a.name="d",s.appendChild(a),document.body.appendChild(s),this.form=s,this.area=a}this.form.action=this.uri(),n(),t=t.replace(h,"\\\n"),this.area.value=t.replace(p,"\\n");try{this.form.submit()}catch(t){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===o.iframe.readyState&&r()}:this.iframe.onload=r}}).call(e,function(){return this}())},function(t,e,r){function n(t){var e=t&&t.forceBase64;e&&(this.supportsBinary=!1),this.perMessageDeflate=t.perMessageDeflate,this.usingBrowserWebSocket=o&&!t.forceNode,this.protocols=t.protocols,this.usingBrowserWebSocket||(u=i),s.call(this,t)}var o,i,s=r(17),a=r(18),c=r(26),p=r(27),h=r(28);r(3)("engine.io-client:websocket");if("undefined"!=typeof WebSocket?o=WebSocket:"undefined"!=typeof self&&(o=self.WebSocket||self.MozWebSocket),"undefined"==typeof window)try{i=r(31)}catch(t){}var u=o||i;t.exports=n,p(n,s),n.prototype.name="websocket",n.prototype.supportsBinary=!0,n.prototype.doOpen=function(){if(this.check()){var t=this.uri(),e=this.protocols,r={agent:this.agent,perMessageDeflate:this.perMessageDeflate};r.pfx=this.pfx,r.key=this.key,r.passphrase=this.passphrase,r.cert=this.cert,r.ca=this.ca,r.ciphers=this.ciphers,r.rejectUnauthorized=this.rejectUnauthorized,this.extraHeaders&&(r.headers=this.extraHeaders),this.localAddress&&(r.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket&&!this.isReactNative?e?new u(t,e):new u(t):new u(t,e,r)}catch(t){return this.emit("error",t)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},n.prototype.addEventListeners=function(){var t=this;this.ws.onopen=function(){t.onOpen()},this.ws.onclose=function(){t.onClose()},this.ws.onmessage=function(e){t.onData(e.data)},this.ws.onerror=function(e){t.onError("websocket error",e)}},n.prototype.write=function(t){function e(){r.emit("flush"),setTimeout(function(){r.writable=!0,r.emit("drain")},0)}var r=this;this.writable=!1;for(var n=t.length,o=0,i=n;o0&&t.jitter<=1?t.jitter:0,this.attempts=0}t.exports=r,r.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),r=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-r:t+r}return 0|Math.min(t,this.max)},r.prototype.reset=function(){this.attempts=0},r.prototype.setMin=function(t){this.ms=t},r.prototype.setMax=function(t){this.max=t},r.prototype.setJitter=function(t){this.jitter=t}}])}); +//# sourceMappingURL=socket.io.slim.js.map \ No newline at end of file diff --git a/js/standardized-audio-context.js b/js/standardized-audio-context.js new file mode 100644 index 0000000..7423fde --- /dev/null +++ b/js/standardized-audio-context.js @@ -0,0 +1,10204 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('automation-events'), require('@babel/runtime/helpers/slicedToArray'), require('@babel/runtime/helpers/createClass'), require('@babel/runtime/helpers/classCallCheck'), require('@babel/runtime/helpers/typeof'), require('@babel/runtime/helpers/defineProperty'), require('@babel/runtime/helpers/possibleConstructorReturn'), require('@babel/runtime/helpers/getPrototypeOf'), require('@babel/runtime/helpers/inherits'), require('@babel/runtime/helpers/asyncToGenerator'), require('@babel/runtime/regenerator'), require('@babel/runtime/helpers/toConsumableArray'), require('@babel/runtime/helpers/objectWithoutProperties')) : + typeof define === 'function' && define.amd ? define(['exports', 'automation-events', '@babel/runtime/helpers/slicedToArray', '@babel/runtime/helpers/createClass', '@babel/runtime/helpers/classCallCheck', '@babel/runtime/helpers/typeof', '@babel/runtime/helpers/defineProperty', '@babel/runtime/helpers/possibleConstructorReturn', '@babel/runtime/helpers/getPrototypeOf', '@babel/runtime/helpers/inherits', '@babel/runtime/helpers/asyncToGenerator', '@babel/runtime/regenerator', '@babel/runtime/helpers/toConsumableArray', '@babel/runtime/helpers/objectWithoutProperties'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.standardizedAudioContext = {}, global.automationEvents, global._slicedToArray, global._createClass, global._classCallCheck, global._typeof, global._defineProperty, global._possibleConstructorReturn, global._getPrototypeOf, global._inherits, global._asyncToGenerator, global._regeneratorRuntime, global._toConsumableArray, global._objectWithoutProperties)); +})(this, (function (exports, automationEvents, _slicedToArray, _createClass, _classCallCheck, _typeof, _defineProperty, _possibleConstructorReturn, _getPrototypeOf, _inherits, _asyncToGenerator, _regeneratorRuntime, _toConsumableArray, _objectWithoutProperties) { 'use strict'; + + var createAbortError = function createAbortError() { + return new DOMException('', 'AbortError'); + }; + + var createAddActiveInputConnectionToAudioNode = function createAddActiveInputConnectionToAudioNode(insertElementInSet) { + return function (activeInputs, source, _ref, ignoreDuplicates) { + var _ref2 = _slicedToArray(_ref, 3), + output = _ref2[0], + input = _ref2[1], + eventListener = _ref2[2]; + insertElementInSet(activeInputs[input], [source, output, eventListener], function (activeInputConnection) { + return activeInputConnection[0] === source && activeInputConnection[1] === output; + }, ignoreDuplicates); + }; + }; + + var createAddAudioNodeConnections = function createAddAudioNodeConnections(audioNodeConnectionsStore) { + return function (audioNode, audioNodeRenderer, nativeAudioNode) { + var activeInputs = []; + for (var i = 0; i < nativeAudioNode.numberOfInputs; i += 1) { + activeInputs.push(new Set()); + } + audioNodeConnectionsStore.set(audioNode, { + activeInputs: activeInputs, + outputs: new Set(), + passiveInputs: new WeakMap(), + renderer: audioNodeRenderer + }); + }; + }; + + var createAddAudioParamConnections = function createAddAudioParamConnections(audioParamConnectionsStore) { + return function (audioParam, audioParamRenderer) { + audioParamConnectionsStore.set(audioParam, { + activeInputs: new Set(), + passiveInputs: new WeakMap(), + renderer: audioParamRenderer + }); + }; + }; + + var ACTIVE_AUDIO_NODE_STORE = new WeakSet(); + var AUDIO_NODE_CONNECTIONS_STORE = new WeakMap(); + var AUDIO_NODE_STORE = new WeakMap(); + var AUDIO_PARAM_CONNECTIONS_STORE = new WeakMap(); + var AUDIO_PARAM_STORE = new WeakMap(); + var CONTEXT_STORE = new WeakMap(); + var EVENT_LISTENERS = new WeakMap(); + var CYCLE_COUNTERS = new WeakMap(); + // This clunky name is borrowed from the spec. :-) + var NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS = new WeakMap(); + var NODE_TO_PROCESSOR_MAPS = new WeakMap(); + + var handler = { + construct: function construct() { + return handler; + } + }; + var isConstructible = function isConstructible(constructible) { + try { + var proxy = new Proxy(constructible, handler); + new proxy(); // tslint:disable-line:no-unused-expression + } catch (_unused) { + return false; + } + return true; + }; + + /* + * This massive regex tries to cover all the following cases. + * + * import './path'; + * import defaultImport from './path'; + * import { namedImport } from './path'; + * import { namedImport as renamendImport } from './path'; + * import * as namespaceImport from './path'; + * import defaultImport, { namedImport } from './path'; + * import defaultImport, { namedImport as renamendImport } from './path'; + * import defaultImport, * as namespaceImport from './path'; + */ + var IMPORT_STATEMENT_REGEX = /^import(?:(?:[\s]+[\w]+|(?:[\s]+[\w]+[\s]*,)?[\s]*\{[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?(?:[\s]*,[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?)*[\s]*}|(?:[\s]+[\w]+[\s]*,)?[\s]*\*[\s]+as[\s]+[\w]+)[\s]+from)?(?:[\s]*)("([^"\\]|\\.)+"|'([^'\\]|\\.)+')(?:[\s]*);?/; // tslint:disable-line:max-line-length + var splitImportStatements = function splitImportStatements(source, url) { + var importStatements = []; + var sourceWithoutImportStatements = source.replace(/^[\s]+/, ''); + var result = sourceWithoutImportStatements.match(IMPORT_STATEMENT_REGEX); + while (result !== null) { + var unresolvedUrl = result[1].slice(1, -1); + var importStatementWithResolvedUrl = result[0].replace(/([\s]+)?;?$/, '').replace(unresolvedUrl, new URL(unresolvedUrl, url).toString()); + importStatements.push(importStatementWithResolvedUrl); + sourceWithoutImportStatements = sourceWithoutImportStatements.slice(result[0].length).replace(/^[\s]+/, ''); + result = sourceWithoutImportStatements.match(IMPORT_STATEMENT_REGEX); + } + return [importStatements.join(';'), sourceWithoutImportStatements]; + }; + + var verifyParameterDescriptors = function verifyParameterDescriptors(parameterDescriptors) { + if (parameterDescriptors !== undefined && !Array.isArray(parameterDescriptors)) { + throw new TypeError('The parameterDescriptors property of given value for processorCtor is not an array.'); + } + }; + var verifyProcessorCtor = function verifyProcessorCtor(processorCtor) { + if (!isConstructible(processorCtor)) { + throw new TypeError('The given value for processorCtor should be a constructor.'); + } + if (processorCtor.prototype === null || _typeof(processorCtor.prototype) !== 'object') { + throw new TypeError('The given value for processorCtor should have a prototype.'); + } + }; + var createAddAudioWorkletModule = function createAddAudioWorkletModule(cacheTestResult, createNotSupportedError, evaluateSource, exposeCurrentFrameAndCurrentTime, fetchSource, getNativeContext, getOrCreateBackupOfflineAudioContext, isNativeOfflineAudioContext, nativeAudioWorkletNodeConstructor, ongoingRequests, resolvedRequests, testAudioWorkletProcessorPostMessageSupport, window) { + var index = 0; + return function (context, moduleURL) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + credentials: 'omit' + }; + var resolvedRequestsOfContext = resolvedRequests.get(context); + if (resolvedRequestsOfContext !== undefined && resolvedRequestsOfContext.has(moduleURL)) { + return Promise.resolve(); + } + var ongoingRequestsOfContext = ongoingRequests.get(context); + if (ongoingRequestsOfContext !== undefined) { + var promiseOfOngoingRequest = ongoingRequestsOfContext.get(moduleURL); + if (promiseOfOngoingRequest !== undefined) { + return promiseOfOngoingRequest; + } + } + var nativeContext = getNativeContext(context); + // Bug #59: Safari does not implement the audioWorklet property. + var promise = nativeContext.audioWorklet === undefined ? fetchSource(moduleURL).then(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + source = _ref2[0], + absoluteUrl = _ref2[1]; + var _splitImportStatement = splitImportStatements(source, absoluteUrl), + _splitImportStatement2 = _slicedToArray(_splitImportStatement, 2), + importStatements = _splitImportStatement2[0], + sourceWithoutImportStatements = _splitImportStatement2[1]; + /* + * This is the unminified version of the code used below: + * + * ```js + * ${ importStatements }; + * ((a, b) => { + * (a[b] = a[b] || [ ]).push( + * (AudioWorkletProcessor, global, registerProcessor, sampleRate, self, window) => { + * ${ sourceWithoutImportStatements } + * } + * ); + * })(window, '_AWGS'); + * ``` + */ + // tslint:disable-next-line:max-line-length + var wrappedSource = "".concat(importStatements, ";((a,b)=>{(a[b]=a[b]||[]).push((AudioWorkletProcessor,global,registerProcessor,sampleRate,self,window)=>{").concat(sourceWithoutImportStatements, "\n})})(window,'_AWGS')"); + // @todo Evaluating the given source code is a possible security problem. + return evaluateSource(wrappedSource); + }).then(function () { + var evaluateAudioWorkletGlobalScope = window._AWGS.pop(); + if (evaluateAudioWorkletGlobalScope === undefined) { + // Bug #182 Chrome and Edge do throw an instance of a SyntaxError instead of a DOMException. + throw new SyntaxError(); + } + exposeCurrentFrameAndCurrentTime(nativeContext.currentTime, nativeContext.sampleRate, function () { + return evaluateAudioWorkletGlobalScope(/*#__PURE__*/_createClass(function AudioWorkletProcessor() { + _classCallCheck(this, AudioWorkletProcessor); + }), undefined, function (name, processorCtor) { + if (name.trim() === '') { + throw createNotSupportedError(); + } + var nodeNameToProcessorConstructorMap = NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS.get(nativeContext); + if (nodeNameToProcessorConstructorMap !== undefined) { + if (nodeNameToProcessorConstructorMap.has(name)) { + throw createNotSupportedError(); + } + verifyProcessorCtor(processorCtor); + verifyParameterDescriptors(processorCtor.parameterDescriptors); + nodeNameToProcessorConstructorMap.set(name, processorCtor); + } else { + verifyProcessorCtor(processorCtor); + verifyParameterDescriptors(processorCtor.parameterDescriptors); + NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS.set(nativeContext, new Map([[name, processorCtor]])); + } + }, nativeContext.sampleRate, undefined, undefined); + }); + }) : Promise.all([fetchSource(moduleURL), Promise.resolve(cacheTestResult(testAudioWorkletProcessorPostMessageSupport, testAudioWorkletProcessorPostMessageSupport))]).then(function (_ref3) { + var _ref4 = _slicedToArray(_ref3, 2), + _ref4$ = _slicedToArray(_ref4[0], 2), + source = _ref4$[0], + absoluteUrl = _ref4$[1], + isSupportingPostMessage = _ref4[1]; + var currentIndex = index + 1; + index = currentIndex; + var _splitImportStatement3 = splitImportStatements(source, absoluteUrl), + _splitImportStatement4 = _slicedToArray(_splitImportStatement3, 2), + importStatements = _splitImportStatement4[0], + sourceWithoutImportStatements = _splitImportStatement4[1]; + /* + * Bug #179: Firefox does not allow to transfer any buffer which has been passed to the process() method as an argument. + * + * This is the unminified version of the code used below. + * + * ```js + * class extends AudioWorkletProcessor { + * + * __buffers = new WeakSet(); + * + * constructor () { + * super(); + * + * this.port.postMessage = ((postMessage) => { + * return (message, transferables) => { + * const filteredTransferables = (transferables) + * ? transferables.filter((transferable) => !this.__buffers.has(transferable)) + * : transferables; + * + * return postMessage.call(this.port, message, filteredTransferables); + * }; + * })(this.port.postMessage); + * } + * } + * ``` + */ + var patchedAudioWorkletProcessor = isSupportingPostMessage ? 'AudioWorkletProcessor' : 'class extends AudioWorkletProcessor {__b=new WeakSet();constructor(){super();(p=>p.postMessage=(q=>(m,t)=>q.call(p,m,t?t.filter(u=>!this.__b.has(u)):t))(p.postMessage))(this.port)}}'; + /* + * Bug #170: Chrome and Edge do call process() with an array with empty channelData for each input if no input is connected. + * + * Bug #179: Firefox does not allow to transfer any buffer which has been passed to the process() method as an argument. + * + * Bug #190: Safari doesn't throw an error when loading an unparsable module. + * + * This is the unminified version of the code used below: + * + * ```js + * `${ importStatements }; + * ((AudioWorkletProcessor, registerProcessor) => {${ sourceWithoutImportStatements } + * })( + * ${ patchedAudioWorkletProcessor }, + * (name, processorCtor) => registerProcessor(name, class extends processorCtor { + * + * __collectBuffers = (array) => { + * array.forEach((element) => this.__buffers.add(element.buffer)); + * }; + * + * process (inputs, outputs, parameters) { + * inputs.forEach(this.__collectBuffers); + * outputs.forEach(this.__collectBuffers); + * this.__collectBuffers(Object.values(parameters)); + * + * return super.process( + * (inputs.map((input) => input.some((channelData) => channelData.length === 0)) ? [ ] : input), + * outputs, + * parameters + * ); + * } + * + * }) + * ); + * + * registerProcessor(`__sac${currentIndex}`, class extends AudioWorkletProcessor{ + * + * process () { + * return false; + * } + * + * })` + * ``` + */ + var memberDefinition = isSupportingPostMessage ? '' : '__c = (a) => a.forEach(e=>this.__b.add(e.buffer));'; + var bufferRegistration = isSupportingPostMessage ? '' : 'i.forEach(this.__c);o.forEach(this.__c);this.__c(Object.values(p));'; + var wrappedSource = "".concat(importStatements, ";((AudioWorkletProcessor,registerProcessor)=>{").concat(sourceWithoutImportStatements, "\n})(").concat(patchedAudioWorkletProcessor, ",(n,p)=>registerProcessor(n,class extends p{").concat(memberDefinition, "process(i,o,p){").concat(bufferRegistration, "return super.process(i.map(j=>j.some(k=>k.length===0)?[]:j),o,p)}}));registerProcessor('__sac").concat(currentIndex, "',class extends AudioWorkletProcessor{process(){return !1}})"); + var blob = new Blob([wrappedSource], { + type: 'application/javascript; charset=utf-8' + }); + var url = URL.createObjectURL(blob); + return nativeContext.audioWorklet.addModule(url, options).then(function () { + if (isNativeOfflineAudioContext(nativeContext)) { + return nativeContext; + } + // Bug #186: Chrome and Edge do not allow to create an AudioWorkletNode on a closed AudioContext. + var backupOfflineAudioContext = getOrCreateBackupOfflineAudioContext(nativeContext); + return backupOfflineAudioContext.audioWorklet.addModule(url, options).then(function () { + return backupOfflineAudioContext; + }); + }).then(function (nativeContextOrBackupOfflineAudioContext) { + if (nativeAudioWorkletNodeConstructor === null) { + throw new SyntaxError(); + } + try { + // Bug #190: Safari doesn't throw an error when loading an unparsable module. + new nativeAudioWorkletNodeConstructor(nativeContextOrBackupOfflineAudioContext, "__sac".concat(currentIndex)); // tslint:disable-line:no-unused-expression + } catch (_unused) { + throw new SyntaxError(); + } + })["finally"](function () { + return URL.revokeObjectURL(url); + }); + }); + if (ongoingRequestsOfContext === undefined) { + ongoingRequests.set(context, new Map([[moduleURL, promise]])); + } else { + ongoingRequestsOfContext.set(moduleURL, promise); + } + promise.then(function () { + var updatedResolvedRequestsOfContext = resolvedRequests.get(context); + if (updatedResolvedRequestsOfContext === undefined) { + resolvedRequests.set(context, new Set([moduleURL])); + } else { + updatedResolvedRequestsOfContext.add(moduleURL); + } + })["finally"](function () { + var updatedOngoingRequestsOfContext = ongoingRequests.get(context); + if (updatedOngoingRequestsOfContext !== undefined) { + updatedOngoingRequestsOfContext["delete"](moduleURL); + } + }); + return promise; + }; + }; + + var getValueForKey = function getValueForKey(map, key) { + var value = map.get(key); + if (value === undefined) { + throw new Error('A value with the given key could not be found.'); + } + return value; + }; + + var pickElementFromSet = function pickElementFromSet(set, predicate) { + var matchingElements = Array.from(set).filter(predicate); + if (matchingElements.length > 1) { + throw Error('More than one element was found.'); + } + if (matchingElements.length === 0) { + throw Error('No element was found.'); + } + var _matchingElements = _slicedToArray(matchingElements, 1), + matchingElement = _matchingElements[0]; + set["delete"](matchingElement); + return matchingElement; + }; + + var deletePassiveInputConnectionToAudioNode = function deletePassiveInputConnectionToAudioNode(passiveInputs, source, output, input) { + var passiveInputConnections = getValueForKey(passiveInputs, source); + var matchingConnection = pickElementFromSet(passiveInputConnections, function (passiveInputConnection) { + return passiveInputConnection[0] === output && passiveInputConnection[1] === input; + }); + if (passiveInputConnections.size === 0) { + passiveInputs["delete"](source); + } + return matchingConnection; + }; + + var getEventListenersOfAudioNode = function getEventListenersOfAudioNode(audioNode) { + return getValueForKey(EVENT_LISTENERS, audioNode); + }; + + var setInternalStateToActive = function setInternalStateToActive(audioNode) { + if (ACTIVE_AUDIO_NODE_STORE.has(audioNode)) { + throw new Error('The AudioNode is already stored.'); + } + ACTIVE_AUDIO_NODE_STORE.add(audioNode); + getEventListenersOfAudioNode(audioNode).forEach(function (eventListener) { + return eventListener(true); + }); + }; + + var isAudioWorkletNode = function isAudioWorkletNode(audioNode) { + return 'port' in audioNode; + }; + + var setInternalStateToPassive = function setInternalStateToPassive(audioNode) { + if (!ACTIVE_AUDIO_NODE_STORE.has(audioNode)) { + throw new Error('The AudioNode is not stored.'); + } + ACTIVE_AUDIO_NODE_STORE["delete"](audioNode); + getEventListenersOfAudioNode(audioNode).forEach(function (eventListener) { + return eventListener(false); + }); + }; + + // Set the internalState of the audioNode to 'passive' if it is not an AudioWorkletNode and if it has no 'active' input connections. + var setInternalStateToPassiveWhenNecessary = function setInternalStateToPassiveWhenNecessary(audioNode, activeInputs) { + if (!isAudioWorkletNode(audioNode) && activeInputs.every(function (connections) { + return connections.size === 0; + })) { + setInternalStateToPassive(audioNode); + } + }; + + var createAddConnectionToAudioNode = function createAddConnectionToAudioNode(addActiveInputConnectionToAudioNode, addPassiveInputConnectionToAudioNode, connectNativeAudioNodeToNativeAudioNode, deleteActiveInputConnectionToAudioNode, disconnectNativeAudioNodeFromNativeAudioNode, getAudioNodeConnections, getAudioNodeTailTime, getEventListenersOfAudioNode, getNativeAudioNode, insertElementInSet, isActiveAudioNode, isPartOfACycle, isPassiveAudioNode) { + var tailTimeTimeoutIds = new WeakMap(); + return function (source, destination, output, input, isOffline) { + var _getAudioNodeConnecti = getAudioNodeConnections(destination), + activeInputs = _getAudioNodeConnecti.activeInputs, + passiveInputs = _getAudioNodeConnecti.passiveInputs; + var _getAudioNodeConnecti2 = getAudioNodeConnections(source), + outputs = _getAudioNodeConnecti2.outputs; + var eventListeners = getEventListenersOfAudioNode(source); + var eventListener = function eventListener(isActive) { + var nativeDestinationAudioNode = getNativeAudioNode(destination); + var nativeSourceAudioNode = getNativeAudioNode(source); + if (isActive) { + var partialConnection = deletePassiveInputConnectionToAudioNode(passiveInputs, source, output, input); + addActiveInputConnectionToAudioNode(activeInputs, source, partialConnection, false); + if (!isOffline && !isPartOfACycle(source)) { + connectNativeAudioNodeToNativeAudioNode(nativeSourceAudioNode, nativeDestinationAudioNode, output, input); + } + if (isPassiveAudioNode(destination)) { + setInternalStateToActive(destination); + } + } else { + var _partialConnection = deleteActiveInputConnectionToAudioNode(activeInputs, source, output, input); + addPassiveInputConnectionToAudioNode(passiveInputs, input, _partialConnection, false); + if (!isOffline && !isPartOfACycle(source)) { + disconnectNativeAudioNodeFromNativeAudioNode(nativeSourceAudioNode, nativeDestinationAudioNode, output, input); + } + var tailTime = getAudioNodeTailTime(destination); + if (tailTime === 0) { + if (isActiveAudioNode(destination)) { + setInternalStateToPassiveWhenNecessary(destination, activeInputs); + } + } else { + var tailTimeTimeoutId = tailTimeTimeoutIds.get(destination); + if (tailTimeTimeoutId !== undefined) { + clearTimeout(tailTimeTimeoutId); + } + tailTimeTimeoutIds.set(destination, setTimeout(function () { + if (isActiveAudioNode(destination)) { + setInternalStateToPassiveWhenNecessary(destination, activeInputs); + } + }, tailTime * 1000)); + } + } + }; + if (insertElementInSet(outputs, [destination, output, input], function (outputConnection) { + return outputConnection[0] === destination && outputConnection[1] === output && outputConnection[2] === input; + }, true)) { + eventListeners.add(eventListener); + if (isActiveAudioNode(source)) { + addActiveInputConnectionToAudioNode(activeInputs, source, [output, input, eventListener], true); + } else { + addPassiveInputConnectionToAudioNode(passiveInputs, input, [source, output, eventListener], true); + } + return true; + } + return false; + }; + }; + + var createAddPassiveInputConnectionToAudioNode = function createAddPassiveInputConnectionToAudioNode(insertElementInSet) { + return function (passiveInputs, input, _ref, ignoreDuplicates) { + var _ref2 = _slicedToArray(_ref, 3), + source = _ref2[0], + output = _ref2[1], + eventListener = _ref2[2]; + var passiveInputConnections = passiveInputs.get(source); + if (passiveInputConnections === undefined) { + passiveInputs.set(source, new Set([[output, input, eventListener]])); + } else { + insertElementInSet(passiveInputConnections, [output, input, eventListener], function (passiveInputConnection) { + return passiveInputConnection[0] === output && passiveInputConnection[1] === input; + }, ignoreDuplicates); + } + }; + }; + + var createAddSilentConnection = function createAddSilentConnection(createNativeGainNode) { + return function (nativeContext, nativeAudioScheduledSourceNode) { + var nativeGainNode = createNativeGainNode(nativeContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + gain: 0 + }); + nativeAudioScheduledSourceNode.connect(nativeGainNode).connect(nativeContext.destination); + var _disconnect = function disconnect() { + nativeAudioScheduledSourceNode.removeEventListener('ended', _disconnect); + nativeAudioScheduledSourceNode.disconnect(nativeGainNode); + nativeGainNode.disconnect(); + }; + nativeAudioScheduledSourceNode.addEventListener('ended', _disconnect); + }; + }; + + var createAddUnrenderedAudioWorkletNode = function createAddUnrenderedAudioWorkletNode(getUnrenderedAudioWorkletNodes) { + return function (nativeContext, audioWorkletNode) { + getUnrenderedAudioWorkletNodes(nativeContext).add(audioWorkletNode); + }; + }; + + function ownKeys$w(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$w(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$w(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$w(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$r(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$r() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$r() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$r = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$k = { + channelCount: 2, + channelCountMode: 'max', + channelInterpretation: 'speakers', + fftSize: 2048, + maxDecibels: -30, + minDecibels: -100, + smoothingTimeConstant: 0.8 + }; + var createAnalyserNodeConstructor = function createAnalyserNodeConstructor(audionNodeConstructor, createAnalyserNodeRenderer, createIndexSizeError, createNativeAnalyserNode, getNativeContext, isNativeOfflineAudioContext) { + return /*#__PURE__*/function (_audionNodeConstructo) { + function AnalyserNode(context, options) { + var _this; + _classCallCheck(this, AnalyserNode); + var nativeContext = getNativeContext(context); + var mergedOptions = _objectSpread$w(_objectSpread$w({}, DEFAULT_OPTIONS$k), options); + var nativeAnalyserNode = createNativeAnalyserNode(nativeContext, mergedOptions); + var analyserNodeRenderer = isNativeOfflineAudioContext(nativeContext) ? createAnalyserNodeRenderer() : null; + _this = _callSuper$r(this, AnalyserNode, [context, false, nativeAnalyserNode, analyserNodeRenderer]); + _this._nativeAnalyserNode = nativeAnalyserNode; + return _this; + } + _inherits(AnalyserNode, _audionNodeConstructo); + return _createClass(AnalyserNode, [{ + key: "fftSize", + get: function get() { + return this._nativeAnalyserNode.fftSize; + }, + set: function set(value) { + this._nativeAnalyserNode.fftSize = value; + } + }, { + key: "frequencyBinCount", + get: function get() { + return this._nativeAnalyserNode.frequencyBinCount; + } + }, { + key: "maxDecibels", + get: function get() { + return this._nativeAnalyserNode.maxDecibels; + }, + set: function set(value) { + // Bug #118: Safari does not throw an error if maxDecibels is not more than minDecibels. + var maxDecibels = this._nativeAnalyserNode.maxDecibels; + this._nativeAnalyserNode.maxDecibels = value; + if (!(value > this._nativeAnalyserNode.minDecibels)) { + this._nativeAnalyserNode.maxDecibels = maxDecibels; + throw createIndexSizeError(); + } + } + }, { + key: "minDecibels", + get: function get() { + return this._nativeAnalyserNode.minDecibels; + }, + set: function set(value) { + // Bug #118: Safari does not throw an error if maxDecibels is not more than minDecibels. + var minDecibels = this._nativeAnalyserNode.minDecibels; + this._nativeAnalyserNode.minDecibels = value; + if (!(this._nativeAnalyserNode.maxDecibels > value)) { + this._nativeAnalyserNode.minDecibels = minDecibels; + throw createIndexSizeError(); + } + } + }, { + key: "smoothingTimeConstant", + get: function get() { + return this._nativeAnalyserNode.smoothingTimeConstant; + }, + set: function set(value) { + this._nativeAnalyserNode.smoothingTimeConstant = value; + } + }, { + key: "getByteFrequencyData", + value: function getByteFrequencyData(array) { + this._nativeAnalyserNode.getByteFrequencyData(array); + } + }, { + key: "getByteTimeDomainData", + value: function getByteTimeDomainData(array) { + this._nativeAnalyserNode.getByteTimeDomainData(array); + } + }, { + key: "getFloatFrequencyData", + value: function getFloatFrequencyData(array) { + this._nativeAnalyserNode.getFloatFrequencyData(array); + } + }, { + key: "getFloatTimeDomainData", + value: function getFloatTimeDomainData(array) { + this._nativeAnalyserNode.getFloatTimeDomainData(array); + } + }]); + }(audionNodeConstructor); + }; + + var isOwnedByContext = function isOwnedByContext(nativeAudioNode, nativeContext) { + return nativeAudioNode.context === nativeContext; + }; + + var createAnalyserNodeRendererFactory = function createAnalyserNodeRendererFactory(createNativeAnalyserNode, getNativeAudioNode, renderInputsOfAudioNode) { + return function () { + var renderedNativeAnalyserNodes = new WeakMap(); + var createAnalyserNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(proxy, nativeOfflineAudioContext) { + var nativeAnalyserNode, nativeAnalyserNodeIsOwnedByContext, options; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + nativeAnalyserNode = getNativeAudioNode(proxy); // If the initially used nativeAnalyserNode was not constructed on the same OfflineAudioContext it needs to be created again. + nativeAnalyserNodeIsOwnedByContext = isOwnedByContext(nativeAnalyserNode, nativeOfflineAudioContext); + if (!nativeAnalyserNodeIsOwnedByContext) { + options = { + channelCount: nativeAnalyserNode.channelCount, + channelCountMode: nativeAnalyserNode.channelCountMode, + channelInterpretation: nativeAnalyserNode.channelInterpretation, + fftSize: nativeAnalyserNode.fftSize, + maxDecibels: nativeAnalyserNode.maxDecibels, + minDecibels: nativeAnalyserNode.minDecibels, + smoothingTimeConstant: nativeAnalyserNode.smoothingTimeConstant + }; + nativeAnalyserNode = createNativeAnalyserNode(nativeOfflineAudioContext, options); + } + renderedNativeAnalyserNodes.set(nativeOfflineAudioContext, nativeAnalyserNode); + _context.next = 6; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAnalyserNode); + case 6: + return _context.abrupt("return", nativeAnalyserNode); + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createAnalyserNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeAnalyserNode = renderedNativeAnalyserNodes.get(nativeOfflineAudioContext); + if (renderedNativeAnalyserNode !== undefined) { + return Promise.resolve(renderedNativeAnalyserNode); + } + return createAnalyserNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + var testAudioBufferCopyChannelMethodsOutOfBoundsSupport = function testAudioBufferCopyChannelMethodsOutOfBoundsSupport(nativeAudioBuffer) { + try { + nativeAudioBuffer.copyToChannel(new Float32Array(1), 0, -1); + } catch (_unused) { + return false; + } + return true; + }; + + var createIndexSizeError = function createIndexSizeError() { + return new DOMException('', 'IndexSizeError'); + }; + + var wrapAudioBufferGetChannelDataMethod = function wrapAudioBufferGetChannelDataMethod(audioBuffer) { + audioBuffer.getChannelData = function (getChannelData) { + return function (channel) { + try { + return getChannelData.call(audioBuffer, channel); + } catch (err) { + if (err.code === 12) { + throw createIndexSizeError(); + } + throw err; + } + }; + }(audioBuffer.getChannelData); + }; + + function ownKeys$v(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$v(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$v(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$v(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + var DEFAULT_OPTIONS$j = { + numberOfChannels: 1 + }; + var createAudioBufferConstructor = function createAudioBufferConstructor(audioBufferStore, cacheTestResult, createNotSupportedError, nativeAudioBufferConstructor, nativeOfflineAudioContextConstructor, testNativeAudioBufferConstructorSupport, wrapAudioBufferCopyChannelMethods, wrapAudioBufferCopyChannelMethodsOutOfBounds) { + var nativeOfflineAudioContext = null; + return /*#__PURE__*/function () { + function AudioBuffer(options) { + _classCallCheck(this, AudioBuffer); + if (nativeOfflineAudioContextConstructor === null) { + throw new Error('Missing the native OfflineAudioContext constructor.'); + } + var _DEFAULT_OPTIONS$opti = _objectSpread$v(_objectSpread$v({}, DEFAULT_OPTIONS$j), options), + length = _DEFAULT_OPTIONS$opti.length, + numberOfChannels = _DEFAULT_OPTIONS$opti.numberOfChannels, + sampleRate = _DEFAULT_OPTIONS$opti.sampleRate; + if (nativeOfflineAudioContext === null) { + nativeOfflineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100); + } + /* + * Bug #99: Firefox does not throw a NotSupportedError when the numberOfChannels is zero. But it only does it when using the + * factory function. But since Firefox also supports the constructor everything should be fine. + */ + var audioBuffer = nativeAudioBufferConstructor !== null && cacheTestResult(testNativeAudioBufferConstructorSupport, testNativeAudioBufferConstructorSupport) ? new nativeAudioBufferConstructor({ + length: length, + numberOfChannels: numberOfChannels, + sampleRate: sampleRate + }) : nativeOfflineAudioContext.createBuffer(numberOfChannels, length, sampleRate); + // Bug #99: Safari does not throw an error when the numberOfChannels is zero. + if (audioBuffer.numberOfChannels === 0) { + throw createNotSupportedError(); + } + // Bug #5: Safari does not support copyFromChannel() and copyToChannel(). + // Bug #100: Safari does throw a wrong error when calling getChannelData() with an out-of-bounds value. + if (typeof audioBuffer.copyFromChannel !== 'function') { + wrapAudioBufferCopyChannelMethods(audioBuffer); + wrapAudioBufferGetChannelDataMethod(audioBuffer); + // Bug #157: Firefox does not allow the bufferOffset to be out-of-bounds. + } else if (!cacheTestResult(testAudioBufferCopyChannelMethodsOutOfBoundsSupport, function () { + return testAudioBufferCopyChannelMethodsOutOfBoundsSupport(audioBuffer); + })) { + wrapAudioBufferCopyChannelMethodsOutOfBounds(audioBuffer); + } + audioBufferStore.add(audioBuffer); + /* + * This does violate all good pratices but it is necessary to allow this AudioBuffer to be used with native + * (Offline)AudioContexts. + */ + return audioBuffer; + } + return _createClass(AudioBuffer, null, [{ + key: Symbol.hasInstance, + value: function value(instance) { + return instance !== null && _typeof(instance) === 'object' && Object.getPrototypeOf(instance) === AudioBuffer.prototype || audioBufferStore.has(instance); + } + }]); + }(); + }; + + var MOST_NEGATIVE_SINGLE_FLOAT = -3.4028234663852886e38; + var MOST_POSITIVE_SINGLE_FLOAT = -MOST_NEGATIVE_SINGLE_FLOAT; + + var isActiveAudioNode = function isActiveAudioNode(audioNode) { + return ACTIVE_AUDIO_NODE_STORE.has(audioNode); + }; + + function ownKeys$u(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$u(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$u(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$u(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$q(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$q() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$q() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$q = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$i = { + buffer: null, + channelCount: 2, + channelCountMode: 'max', + channelInterpretation: 'speakers', + // Bug #149: Safari does not yet support the detune AudioParam. + loop: false, + loopEnd: 0, + loopStart: 0, + playbackRate: 1 + }; + var createAudioBufferSourceNodeConstructor = function createAudioBufferSourceNodeConstructor(audioNodeConstructor, createAudioBufferSourceNodeRenderer, createAudioParam, createInvalidStateError, createNativeAudioBufferSourceNode, getNativeContext, isNativeOfflineAudioContext, wrapEventListener) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function AudioBufferSourceNode(context, options) { + var _this; + _classCallCheck(this, AudioBufferSourceNode); + var nativeContext = getNativeContext(context); + var mergedOptions = _objectSpread$u(_objectSpread$u({}, DEFAULT_OPTIONS$i), options); + var nativeAudioBufferSourceNode = createNativeAudioBufferSourceNode(nativeContext, mergedOptions); + var isOffline = isNativeOfflineAudioContext(nativeContext); + var audioBufferSourceNodeRenderer = isOffline ? createAudioBufferSourceNodeRenderer() : null; + _this = _callSuper$q(this, AudioBufferSourceNode, [context, false, nativeAudioBufferSourceNode, audioBufferSourceNodeRenderer]); + _this._audioBufferSourceNodeRenderer = audioBufferSourceNodeRenderer; + _this._isBufferNullified = false; + _this._isBufferSet = mergedOptions.buffer !== null; + _this._nativeAudioBufferSourceNode = nativeAudioBufferSourceNode; + _this._onended = null; + // Bug #73: Safari does not export the correct values for maxValue and minValue. + _this._playbackRate = createAudioParam(_this, isOffline, nativeAudioBufferSourceNode.playbackRate, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT); + return _this; + } + _inherits(AudioBufferSourceNode, _audioNodeConstructor); + return _createClass(AudioBufferSourceNode, [{ + key: "buffer", + get: function get() { + if (this._isBufferNullified) { + return null; + } + return this._nativeAudioBufferSourceNode.buffer; + }, + set: function set(value) { + this._nativeAudioBufferSourceNode.buffer = value; + // Bug #72: Only Chrome & Edge do not allow to reassign the buffer yet. + if (value !== null) { + if (this._isBufferSet) { + throw createInvalidStateError(); + } + this._isBufferSet = true; + } + } + }, { + key: "loop", + get: function get() { + return this._nativeAudioBufferSourceNode.loop; + }, + set: function set(value) { + this._nativeAudioBufferSourceNode.loop = value; + } + }, { + key: "loopEnd", + get: function get() { + return this._nativeAudioBufferSourceNode.loopEnd; + }, + set: function set(value) { + this._nativeAudioBufferSourceNode.loopEnd = value; + } + }, { + key: "loopStart", + get: function get() { + return this._nativeAudioBufferSourceNode.loopStart; + }, + set: function set(value) { + this._nativeAudioBufferSourceNode.loopStart = value; + } + }, { + key: "onended", + get: function get() { + return this._onended; + }, + set: function set(value) { + var wrappedListener = typeof value === 'function' ? wrapEventListener(this, value) : null; + this._nativeAudioBufferSourceNode.onended = wrappedListener; + var nativeOnEnded = this._nativeAudioBufferSourceNode.onended; + this._onended = nativeOnEnded !== null && nativeOnEnded === wrappedListener ? value : nativeOnEnded; + } + }, { + key: "playbackRate", + get: function get() { + return this._playbackRate; + } + }, { + key: "start", + value: function start() { + var _this2 = this; + var when = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var duration = arguments.length > 2 ? arguments[2] : undefined; + this._nativeAudioBufferSourceNode.start(when, offset, duration); + if (this._audioBufferSourceNodeRenderer !== null) { + this._audioBufferSourceNodeRenderer.start = duration === undefined ? [when, offset] : [when, offset, duration]; + } + if (this.context.state !== 'closed') { + setInternalStateToActive(this); + var _resetInternalStateToPassive = function resetInternalStateToPassive() { + _this2._nativeAudioBufferSourceNode.removeEventListener('ended', _resetInternalStateToPassive); + if (isActiveAudioNode(_this2)) { + setInternalStateToPassive(_this2); + } + }; + this._nativeAudioBufferSourceNode.addEventListener('ended', _resetInternalStateToPassive); + } + } + }, { + key: "stop", + value: function stop() { + var when = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + this._nativeAudioBufferSourceNode.stop(when); + if (this._audioBufferSourceNodeRenderer !== null) { + this._audioBufferSourceNodeRenderer.stop = when; + } + } + }]); + }(audioNodeConstructor); + }; + + var createAudioBufferSourceNodeRendererFactory = function createAudioBufferSourceNodeRendererFactory(connectAudioParam, createNativeAudioBufferSourceNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) { + return function () { + var renderedNativeAudioBufferSourceNodes = new WeakMap(); + var start = null; + var stop = null; + var createAudioBufferSourceNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(proxy, nativeOfflineAudioContext) { + var nativeAudioBufferSourceNode, nativeAudioBufferSourceNodeIsOwnedByContext, options, _nativeAudioBufferSou; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + nativeAudioBufferSourceNode = getNativeAudioNode(proxy); + /* + * If the initially used nativeAudioBufferSourceNode was not constructed on the same OfflineAudioContext it needs to be created + * again. + */ + nativeAudioBufferSourceNodeIsOwnedByContext = isOwnedByContext(nativeAudioBufferSourceNode, nativeOfflineAudioContext); + if (!nativeAudioBufferSourceNodeIsOwnedByContext) { + options = { + buffer: nativeAudioBufferSourceNode.buffer, + channelCount: nativeAudioBufferSourceNode.channelCount, + channelCountMode: nativeAudioBufferSourceNode.channelCountMode, + channelInterpretation: nativeAudioBufferSourceNode.channelInterpretation, + // Bug #149: Safari does not yet support the detune AudioParam. + loop: nativeAudioBufferSourceNode.loop, + loopEnd: nativeAudioBufferSourceNode.loopEnd, + loopStart: nativeAudioBufferSourceNode.loopStart, + playbackRate: nativeAudioBufferSourceNode.playbackRate.value + }; + nativeAudioBufferSourceNode = createNativeAudioBufferSourceNode(nativeOfflineAudioContext, options); + if (start !== null) { + (_nativeAudioBufferSou = nativeAudioBufferSourceNode).start.apply(_nativeAudioBufferSou, _toConsumableArray(start)); + } + if (stop !== null) { + nativeAudioBufferSourceNode.stop(stop); + } + } + renderedNativeAudioBufferSourceNodes.set(nativeOfflineAudioContext, nativeAudioBufferSourceNode); + if (nativeAudioBufferSourceNodeIsOwnedByContext) { + _context.next = 9; + break; + } + _context.next = 7; + return renderAutomation(nativeOfflineAudioContext, proxy.playbackRate, nativeAudioBufferSourceNode.playbackRate); + case 7: + _context.next = 11; + break; + case 9: + _context.next = 11; + return connectAudioParam(nativeOfflineAudioContext, proxy.playbackRate, nativeAudioBufferSourceNode.playbackRate); + case 11: + _context.next = 13; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAudioBufferSourceNode); + case 13: + return _context.abrupt("return", nativeAudioBufferSourceNode); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createAudioBufferSourceNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + set start(value) { + start = value; + }, + set stop(value) { + stop = value; + }, + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeAudioBufferSourceNode = renderedNativeAudioBufferSourceNodes.get(nativeOfflineAudioContext); + if (renderedNativeAudioBufferSourceNode !== undefined) { + return Promise.resolve(renderedNativeAudioBufferSourceNode); + } + return createAudioBufferSourceNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + var isAudioBufferSourceNode = function isAudioBufferSourceNode(audioNode) { + return 'playbackRate' in audioNode; + }; + + var isBiquadFilterNode = function isBiquadFilterNode(audioNode) { + return 'frequency' in audioNode && 'gain' in audioNode; + }; + + var isConstantSourceNode = function isConstantSourceNode(audioNode) { + return 'offset' in audioNode; + }; + + var isGainNode = function isGainNode(audioNode) { + return !('frequency' in audioNode) && 'gain' in audioNode; + }; + + var isOscillatorNode = function isOscillatorNode(audioNode) { + return 'detune' in audioNode && 'frequency' in audioNode && !('gain' in audioNode); + }; + + var isStereoPannerNode = function isStereoPannerNode(audioNode) { + return 'pan' in audioNode; + }; + + var getAudioNodeConnections = function getAudioNodeConnections(audioNode) { + return getValueForKey(AUDIO_NODE_CONNECTIONS_STORE, audioNode); + }; + + var getAudioParamConnections = function getAudioParamConnections(audioParam) { + return getValueForKey(AUDIO_PARAM_CONNECTIONS_STORE, audioParam); + }; + + function _createForOfIteratorHelper$b(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$b(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } + function _unsupportedIterableToArray$b(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$b(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$b(r, a) : void 0; } } + function _arrayLikeToArray$b(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } + var _deactivateActiveAudioNodeInputConnections = function deactivateActiveAudioNodeInputConnections(audioNode, trace) { + var _getAudioNodeConnecti = getAudioNodeConnections(audioNode), + activeInputs = _getAudioNodeConnecti.activeInputs; + activeInputs.forEach(function (connections) { + return connections.forEach(function (_ref) { + var _ref2 = _slicedToArray(_ref, 1), + source = _ref2[0]; + if (!trace.includes(audioNode)) { + _deactivateActiveAudioNodeInputConnections(source, [].concat(_toConsumableArray(trace), [audioNode])); + } + }); + }); + var audioParams = isAudioBufferSourceNode(audioNode) ? [ + // Bug #149: Safari does not yet support the detune AudioParam. + audioNode.playbackRate] : isAudioWorkletNode(audioNode) ? Array.from(audioNode.parameters.values()) : isBiquadFilterNode(audioNode) ? [audioNode.Q, audioNode.detune, audioNode.frequency, audioNode.gain] : isConstantSourceNode(audioNode) ? [audioNode.offset] : isGainNode(audioNode) ? [audioNode.gain] : isOscillatorNode(audioNode) ? [audioNode.detune, audioNode.frequency] : isStereoPannerNode(audioNode) ? [audioNode.pan] : []; + var _iterator = _createForOfIteratorHelper$b(audioParams), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var audioParam = _step.value; + var audioParamConnections = getAudioParamConnections(audioParam); + if (audioParamConnections !== undefined) { + audioParamConnections.activeInputs.forEach(function (_ref3) { + var _ref4 = _slicedToArray(_ref3, 1), + source = _ref4[0]; + return _deactivateActiveAudioNodeInputConnections(source, trace); + }); + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + if (isActiveAudioNode(audioNode)) { + setInternalStateToPassive(audioNode); + } + }; + + var deactivateAudioGraph = function deactivateAudioGraph(context) { + _deactivateActiveAudioNodeInputConnections(context.destination, []); + }; + + var isValidLatencyHint = function isValidLatencyHint(latencyHint) { + return latencyHint === undefined || typeof latencyHint === 'number' || typeof latencyHint === 'string' && (latencyHint === 'balanced' || latencyHint === 'interactive' || latencyHint === 'playback'); + }; + + function _callSuper$p(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$p() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$p() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$p = function _isNativeReflectConstruct() { return !!t; })(); } + var createAudioContextConstructor = function createAudioContextConstructor(baseAudioContextConstructor, createInvalidStateError, createNotSupportedError, createUnknownError, mediaElementAudioSourceNodeConstructor, mediaStreamAudioDestinationNodeConstructor, mediaStreamAudioSourceNodeConstructor, mediaStreamTrackAudioSourceNodeConstructor, nativeAudioContextConstructor) { + return /*#__PURE__*/function (_baseAudioContextCons) { + function AudioContext() { + var _this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + _classCallCheck(this, AudioContext); + if (nativeAudioContextConstructor === null) { + throw new Error('Missing the native AudioContext constructor.'); + } + var nativeAudioContext; + try { + nativeAudioContext = new nativeAudioContextConstructor(options); + } catch (err) { + // Bug #192 Safari does throw a SyntaxError if the sampleRate is not supported. + if (err.code === 12 && err.message === 'sampleRate is not in range') { + throw createNotSupportedError(); + } + throw err; + } + // Bug #131 Safari returns null when there are four other AudioContexts running already. + if (nativeAudioContext === null) { + throw createUnknownError(); + } + // Bug #51 Only Chrome and Edge throw an error if the given latencyHint is invalid. + if (!isValidLatencyHint(options.latencyHint)) { + throw new TypeError("The provided value '".concat(options.latencyHint, "' is not a valid enum value of type AudioContextLatencyCategory.")); + } + // Bug #150 Safari does not support setting the sampleRate. + if (options.sampleRate !== undefined && nativeAudioContext.sampleRate !== options.sampleRate) { + throw createNotSupportedError(); + } + _this = _callSuper$p(this, AudioContext, [nativeAudioContext, 2]); + var latencyHint = options.latencyHint; + var _nativeAudioContext = nativeAudioContext, + sampleRate = _nativeAudioContext.sampleRate; + // @todo The values for 'balanced', 'interactive' and 'playback' are just copied from Chrome's implementation. + _this._baseLatency = typeof nativeAudioContext.baseLatency === 'number' ? nativeAudioContext.baseLatency : latencyHint === 'balanced' ? 512 / sampleRate : latencyHint === 'interactive' || latencyHint === undefined ? 256 / sampleRate : latencyHint === 'playback' ? 1024 / sampleRate : + /* + * @todo The min (256) and max (16384) values are taken from the allowed bufferSize values of a + * ScriptProcessorNode. + */ + Math.max(2, Math.min(128, Math.round(latencyHint * sampleRate / 128))) * 128 / sampleRate; + _this._nativeAudioContext = nativeAudioContext; + // Bug #188: Safari will set the context's state to 'interrupted' in case the user switches tabs. + if (nativeAudioContextConstructor.name === 'webkitAudioContext') { + _this._nativeGainNode = nativeAudioContext.createGain(); + _this._nativeOscillatorNode = nativeAudioContext.createOscillator(); + _this._nativeGainNode.gain.value = 1e-37; + _this._nativeOscillatorNode.connect(_this._nativeGainNode).connect(nativeAudioContext.destination); + _this._nativeOscillatorNode.start(); + } else { + _this._nativeGainNode = null; + _this._nativeOscillatorNode = null; + } + _this._state = null; + /* + * Bug #34: Chrome and Edge pretend to be running right away, but fire an onstatechange event when the state actually changes + * to 'running'. + */ + if (nativeAudioContext.state === 'running') { + _this._state = 'suspended'; + var _revokeState = function revokeState() { + if (_this._state === 'suspended') { + _this._state = null; + } + nativeAudioContext.removeEventListener('statechange', _revokeState); + }; + nativeAudioContext.addEventListener('statechange', _revokeState); + } + return _this; + } + _inherits(AudioContext, _baseAudioContextCons); + return _createClass(AudioContext, [{ + key: "baseLatency", + get: function get() { + return this._baseLatency; + } + }, { + key: "state", + get: function get() { + return this._state !== null ? this._state : this._nativeAudioContext.state; + } + }, { + key: "close", + value: function close() { + var _this2 = this; + // Bug #35: Firefox does not throw an error if the AudioContext was closed before. + if (this.state === 'closed') { + return this._nativeAudioContext.close().then(function () { + throw createInvalidStateError(); + }); + } + // Bug #34: If the state was set to suspended before it should be revoked now. + if (this._state === 'suspended') { + this._state = null; + } + return this._nativeAudioContext.close().then(function () { + if (_this2._nativeGainNode !== null && _this2._nativeOscillatorNode !== null) { + _this2._nativeOscillatorNode.stop(); + _this2._nativeGainNode.disconnect(); + _this2._nativeOscillatorNode.disconnect(); + } + deactivateAudioGraph(_this2); + }); + } + }, { + key: "createMediaElementSource", + value: function createMediaElementSource(mediaElement) { + return new mediaElementAudioSourceNodeConstructor(this, { + mediaElement: mediaElement + }); + } + }, { + key: "createMediaStreamDestination", + value: function createMediaStreamDestination() { + return new mediaStreamAudioDestinationNodeConstructor(this); + } + }, { + key: "createMediaStreamSource", + value: function createMediaStreamSource(mediaStream) { + return new mediaStreamAudioSourceNodeConstructor(this, { + mediaStream: mediaStream + }); + } + }, { + key: "createMediaStreamTrackSource", + value: function createMediaStreamTrackSource(mediaStreamTrack) { + return new mediaStreamTrackAudioSourceNodeConstructor(this, { + mediaStreamTrack: mediaStreamTrack + }); + } + }, { + key: "resume", + value: function resume() { + var _this3 = this; + if (this._state === 'suspended') { + return new Promise(function (resolve, reject) { + var _resolvePromise = function resolvePromise() { + _this3._nativeAudioContext.removeEventListener('statechange', _resolvePromise); + if (_this3._nativeAudioContext.state === 'running') { + resolve(); + } else { + _this3.resume().then(resolve, reject); + } + }; + _this3._nativeAudioContext.addEventListener('statechange', _resolvePromise); + }); + } + return this._nativeAudioContext.resume()["catch"](function (err) { + // Bug #55: Chrome and Edge do throw an InvalidAccessError instead of an InvalidStateError. + // Bug #56: Safari invokes the catch handler but without an error. + if (err === undefined || err.code === 15) { + throw createInvalidStateError(); + } + throw err; + }); + } + }, { + key: "suspend", + value: function suspend() { + return this._nativeAudioContext.suspend()["catch"](function (err) { + // Bug #56: Safari invokes the catch handler but without an error. + if (err === undefined) { + throw createInvalidStateError(); + } + throw err; + }); + } + }]); + }(baseAudioContextConstructor); + }; + + function _callSuper$o(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$o() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$o() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$o = function _isNativeReflectConstruct() { return !!t; })(); } + var createAudioDestinationNodeConstructor = function createAudioDestinationNodeConstructor(audioNodeConstructor, createAudioDestinationNodeRenderer, createIndexSizeError, createInvalidStateError, createNativeAudioDestinationNode, getNativeContext, isNativeOfflineAudioContext, renderInputsOfAudioNode) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function AudioDestinationNode(context, channelCount) { + var _this; + _classCallCheck(this, AudioDestinationNode); + var nativeContext = getNativeContext(context); + var isOffline = isNativeOfflineAudioContext(nativeContext); + var nativeAudioDestinationNode = createNativeAudioDestinationNode(nativeContext, channelCount, isOffline); + var audioDestinationNodeRenderer = isOffline ? createAudioDestinationNodeRenderer(renderInputsOfAudioNode) : null; + _this = _callSuper$o(this, AudioDestinationNode, [context, false, nativeAudioDestinationNode, audioDestinationNodeRenderer]); + _this._isNodeOfNativeOfflineAudioContext = isOffline; + _this._nativeAudioDestinationNode = nativeAudioDestinationNode; + return _this; + } + _inherits(AudioDestinationNode, _audioNodeConstructor); + return _createClass(AudioDestinationNode, [{ + key: "channelCount", + get: function get() { + return this._nativeAudioDestinationNode.channelCount; + }, + set: function set(value) { + // Bug #52: Chrome, Edge & Safari do not throw an exception at all. + // Bug #54: Firefox does throw an IndexSizeError. + if (this._isNodeOfNativeOfflineAudioContext) { + throw createInvalidStateError(); + } + // Bug #47: The AudioDestinationNode in Safari does not initialize the maxChannelCount property correctly. + if (value > this._nativeAudioDestinationNode.maxChannelCount) { + throw createIndexSizeError(); + } + this._nativeAudioDestinationNode.channelCount = value; + } + }, { + key: "channelCountMode", + get: function get() { + return this._nativeAudioDestinationNode.channelCountMode; + }, + set: function set(value) { + // Bug #53: No browser does throw an exception yet. + if (this._isNodeOfNativeOfflineAudioContext) { + throw createInvalidStateError(); + } + this._nativeAudioDestinationNode.channelCountMode = value; + } + }, { + key: "maxChannelCount", + get: function get() { + return this._nativeAudioDestinationNode.maxChannelCount; + } + }]); + }(audioNodeConstructor); + }; + + var createAudioDestinationNodeRenderer = function createAudioDestinationNodeRenderer(renderInputsOfAudioNode) { + var renderedNativeAudioDestinationNodes = new WeakMap(); + var createAudioDestinationNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(proxy, nativeOfflineAudioContext) { + var nativeAudioDestinationNode; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + nativeAudioDestinationNode = nativeOfflineAudioContext.destination; + renderedNativeAudioDestinationNodes.set(nativeOfflineAudioContext, nativeAudioDestinationNode); + _context.next = 4; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAudioDestinationNode); + case 4: + return _context.abrupt("return", nativeAudioDestinationNode); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createAudioDestinationNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeAudioDestinationNode = renderedNativeAudioDestinationNodes.get(nativeOfflineAudioContext); + if (renderedNativeAudioDestinationNode !== undefined) { + return Promise.resolve(renderedNativeAudioDestinationNode); + } + return createAudioDestinationNode(proxy, nativeOfflineAudioContext); + } + }; + }; + + var createAudioListenerFactory = function createAudioListenerFactory(createAudioParam, createNativeChannelMergerNode, createNativeConstantSourceNode, createNativeScriptProcessorNode, createNotSupportedError, getFirstSample, isNativeOfflineAudioContext, overwriteAccessors) { + return function (context, nativeContext) { + var nativeListener = nativeContext.listener; + // Bug #117: Only Chrome & Edge support the new interface already. + var createFakeAudioParams = function createFakeAudioParams() { + var buffer = new Float32Array(1); + var channelMergerNode = createNativeChannelMergerNode(nativeContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'speakers', + numberOfInputs: 9 + }); + var isOffline = isNativeOfflineAudioContext(nativeContext); + var isScriptProcessorNodeCreated = false; + var lastOrientation = [0, 0, -1, 0, 1, 0]; + var lastPosition = [0, 0, 0]; + var createScriptProcessorNode = function createScriptProcessorNode() { + if (isScriptProcessorNodeCreated) { + return; + } + isScriptProcessorNodeCreated = true; + var scriptProcessorNode = createNativeScriptProcessorNode(nativeContext, 256, 9, 0); + // tslint:disable-next-line:deprecation + scriptProcessorNode.onaudioprocess = function (_ref) { + var inputBuffer = _ref.inputBuffer; + var orientation = [getFirstSample(inputBuffer, buffer, 0), getFirstSample(inputBuffer, buffer, 1), getFirstSample(inputBuffer, buffer, 2), getFirstSample(inputBuffer, buffer, 3), getFirstSample(inputBuffer, buffer, 4), getFirstSample(inputBuffer, buffer, 5)]; + if (orientation.some(function (value, index) { + return value !== lastOrientation[index]; + })) { + nativeListener.setOrientation.apply(nativeListener, orientation); // tslint:disable-line:deprecation + lastOrientation = orientation; + } + var positon = [getFirstSample(inputBuffer, buffer, 6), getFirstSample(inputBuffer, buffer, 7), getFirstSample(inputBuffer, buffer, 8)]; + if (positon.some(function (value, index) { + return value !== lastPosition[index]; + })) { + nativeListener.setPosition.apply(nativeListener, positon); // tslint:disable-line:deprecation + lastPosition = positon; + } + }; + channelMergerNode.connect(scriptProcessorNode); + }; + var createSetOrientation = function createSetOrientation(index) { + return function (value) { + if (value !== lastOrientation[index]) { + lastOrientation[index] = value; + nativeListener.setOrientation.apply(nativeListener, _toConsumableArray(lastOrientation)); // tslint:disable-line:deprecation + } + }; + }; + var createSetPosition = function createSetPosition(index) { + return function (value) { + if (value !== lastPosition[index]) { + lastPosition[index] = value; + nativeListener.setPosition.apply(nativeListener, _toConsumableArray(lastPosition)); // tslint:disable-line:deprecation + } + }; + }; + var createFakeAudioParam = function createFakeAudioParam(input, initialValue, setValue) { + var constantSourceNode = createNativeConstantSourceNode(nativeContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + offset: initialValue + }); + constantSourceNode.connect(channelMergerNode, 0, input); + // @todo This should be stopped when the context is closed. + constantSourceNode.start(); + Object.defineProperty(constantSourceNode.offset, 'defaultValue', { + get: function get() { + return initialValue; + } + }); + /* + * Bug #62 & #74: Safari does not support ConstantSourceNodes and does not export the correct values for maxValue and + * minValue for GainNodes. + */ + var audioParam = createAudioParam({ + context: context + }, isOffline, constantSourceNode.offset, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT); + overwriteAccessors(audioParam, 'value', function (get) { + return function () { + return get.call(audioParam); + }; + }, function (set) { + return function (value) { + try { + set.call(audioParam, value); + } catch (err) { + if (err.code !== 9) { + throw err; + } + } + createScriptProcessorNode(); + if (isOffline) { + // Bug #117: Using setOrientation() and setPosition() doesn't work with an OfflineAudioContext. + setValue(value); + } + }; + }); + audioParam.cancelAndHoldAtTime = function (cancelAndHoldAtTime) { + if (isOffline) { + return function () { + throw createNotSupportedError(); + }; + } + return function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + var value = cancelAndHoldAtTime.apply(audioParam, args); + createScriptProcessorNode(); + return value; + }; + }(audioParam.cancelAndHoldAtTime); + audioParam.cancelScheduledValues = function (cancelScheduledValues) { + if (isOffline) { + return function () { + throw createNotSupportedError(); + }; + } + return function () { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + var value = cancelScheduledValues.apply(audioParam, args); + createScriptProcessorNode(); + return value; + }; + }(audioParam.cancelScheduledValues); + audioParam.exponentialRampToValueAtTime = function (exponentialRampToValueAtTime) { + if (isOffline) { + return function () { + throw createNotSupportedError(); + }; + } + return function () { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + var value = exponentialRampToValueAtTime.apply(audioParam, args); + createScriptProcessorNode(); + return value; + }; + }(audioParam.exponentialRampToValueAtTime); + audioParam.linearRampToValueAtTime = function (linearRampToValueAtTime) { + if (isOffline) { + return function () { + throw createNotSupportedError(); + }; + } + return function () { + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + var value = linearRampToValueAtTime.apply(audioParam, args); + createScriptProcessorNode(); + return value; + }; + }(audioParam.linearRampToValueAtTime); + audioParam.setTargetAtTime = function (setTargetAtTime) { + if (isOffline) { + return function () { + throw createNotSupportedError(); + }; + } + return function () { + for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } + var value = setTargetAtTime.apply(audioParam, args); + createScriptProcessorNode(); + return value; + }; + }(audioParam.setTargetAtTime); + audioParam.setValueAtTime = function (setValueAtTime) { + if (isOffline) { + return function () { + throw createNotSupportedError(); + }; + } + return function () { + for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { + args[_key6] = arguments[_key6]; + } + var value = setValueAtTime.apply(audioParam, args); + createScriptProcessorNode(); + return value; + }; + }(audioParam.setValueAtTime); + audioParam.setValueCurveAtTime = function (setValueCurveAtTime) { + if (isOffline) { + return function () { + throw createNotSupportedError(); + }; + } + return function () { + for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { + args[_key7] = arguments[_key7]; + } + var value = setValueCurveAtTime.apply(audioParam, args); + createScriptProcessorNode(); + return value; + }; + }(audioParam.setValueCurveAtTime); + return audioParam; + }; + return { + forwardX: createFakeAudioParam(0, 0, createSetOrientation(0)), + forwardY: createFakeAudioParam(1, 0, createSetOrientation(1)), + forwardZ: createFakeAudioParam(2, -1, createSetOrientation(2)), + positionX: createFakeAudioParam(6, 0, createSetPosition(0)), + positionY: createFakeAudioParam(7, 0, createSetPosition(1)), + positionZ: createFakeAudioParam(8, 0, createSetPosition(2)), + upX: createFakeAudioParam(3, 0, createSetOrientation(3)), + upY: createFakeAudioParam(4, 1, createSetOrientation(4)), + upZ: createFakeAudioParam(5, 0, createSetOrientation(5)) + }; + }; + var _ref2 = nativeListener.forwardX === undefined ? createFakeAudioParams() : nativeListener, + forwardX = _ref2.forwardX, + forwardY = _ref2.forwardY, + forwardZ = _ref2.forwardZ, + positionX = _ref2.positionX, + positionY = _ref2.positionY, + positionZ = _ref2.positionZ, + upX = _ref2.upX, + upY = _ref2.upY, + upZ = _ref2.upZ; + return { + get forwardX() { + return forwardX; + }, + get forwardY() { + return forwardY; + }, + get forwardZ() { + return forwardZ; + }, + get positionX() { + return positionX; + }, + get positionY() { + return positionY; + }, + get positionZ() { + return positionZ; + }, + get upX() { + return upX; + }, + get upY() { + return upY; + }, + get upZ() { + return upZ; + } + }; + }; + }; + + var isAudioNode = function isAudioNode(audioNodeOrAudioParam) { + return 'context' in audioNodeOrAudioParam; + }; + + var isAudioNodeOutputConnection = function isAudioNodeOutputConnection(outputConnection) { + return isAudioNode(outputConnection[0]); + }; + + function _createForOfIteratorHelper$a(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$a(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } + function _unsupportedIterableToArray$a(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$a(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$a(r, a) : void 0; } } + function _arrayLikeToArray$a(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } + var insertElementInSet = function insertElementInSet(set, element, predicate, ignoreDuplicates) { + var _iterator = _createForOfIteratorHelper$a(set), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var lmnt = _step.value; + if (predicate(lmnt)) { + if (ignoreDuplicates) { + return false; + } + throw Error('The set contains at least one similar element.'); + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + set.add(element); + return true; + }; + + var addActiveInputConnectionToAudioParam = function addActiveInputConnectionToAudioParam(activeInputs, source, _ref, ignoreDuplicates) { + var _ref2 = _slicedToArray(_ref, 2), + output = _ref2[0], + eventListener = _ref2[1]; + insertElementInSet(activeInputs, [source, output, eventListener], function (activeInputConnection) { + return activeInputConnection[0] === source && activeInputConnection[1] === output; + }, ignoreDuplicates); + }; + + var addPassiveInputConnectionToAudioParam = function addPassiveInputConnectionToAudioParam(passiveInputs, _ref, ignoreDuplicates) { + var _ref2 = _slicedToArray(_ref, 3), + source = _ref2[0], + output = _ref2[1], + eventListener = _ref2[2]; + var passiveInputConnections = passiveInputs.get(source); + if (passiveInputConnections === undefined) { + passiveInputs.set(source, new Set([[output, eventListener]])); + } else { + insertElementInSet(passiveInputConnections, [output, eventListener], function (passiveInputConnection) { + return passiveInputConnection[0] === output; + }, ignoreDuplicates); + } + }; + + var isNativeAudioNodeFaker = function isNativeAudioNodeFaker(nativeAudioNodeOrNativeAudioNodeFaker) { + return 'inputs' in nativeAudioNodeOrNativeAudioNodeFaker; + }; + + var connectNativeAudioNodeToNativeAudioNode = function connectNativeAudioNodeToNativeAudioNode(nativeSourceAudioNode, nativeDestinationAudioNode, output, input) { + if (isNativeAudioNodeFaker(nativeDestinationAudioNode)) { + var fakeNativeDestinationAudioNode = nativeDestinationAudioNode.inputs[input]; + nativeSourceAudioNode.connect(fakeNativeDestinationAudioNode, output, 0); + return [fakeNativeDestinationAudioNode, output, 0]; + } + nativeSourceAudioNode.connect(nativeDestinationAudioNode, output, input); + return [nativeDestinationAudioNode, output, input]; + }; + + function _createForOfIteratorHelper$9(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$9(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } + function _unsupportedIterableToArray$9(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$9(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$9(r, a) : void 0; } } + function _arrayLikeToArray$9(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } + var deleteActiveInputConnection = function deleteActiveInputConnection(activeInputConnections, source, output) { + var _iterator = _createForOfIteratorHelper$9(activeInputConnections), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var activeInputConnection = _step.value; + if (activeInputConnection[0] === source && activeInputConnection[1] === output) { + activeInputConnections["delete"](activeInputConnection); + return activeInputConnection; + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + return null; + }; + + var deleteActiveInputConnectionToAudioParam = function deleteActiveInputConnectionToAudioParam(activeInputs, source, output) { + return pickElementFromSet(activeInputs, function (activeInputConnection) { + return activeInputConnection[0] === source && activeInputConnection[1] === output; + }); + }; + + var deleteEventListenerOfAudioNode = function deleteEventListenerOfAudioNode(audioNode, eventListener) { + var eventListeners = getEventListenersOfAudioNode(audioNode); + if (!eventListeners["delete"](eventListener)) { + throw new Error('Missing the expected event listener.'); + } + }; + + var deletePassiveInputConnectionToAudioParam = function deletePassiveInputConnectionToAudioParam(passiveInputs, source, output) { + var passiveInputConnections = getValueForKey(passiveInputs, source); + var matchingConnection = pickElementFromSet(passiveInputConnections, function (passiveInputConnection) { + return passiveInputConnection[0] === output; + }); + if (passiveInputConnections.size === 0) { + passiveInputs["delete"](source); + } + return matchingConnection; + }; + + var disconnectNativeAudioNodeFromNativeAudioNode = function disconnectNativeAudioNodeFromNativeAudioNode(nativeSourceAudioNode, nativeDestinationAudioNode, output, input) { + if (isNativeAudioNodeFaker(nativeDestinationAudioNode)) { + nativeSourceAudioNode.disconnect(nativeDestinationAudioNode.inputs[input], output, 0); + } else { + nativeSourceAudioNode.disconnect(nativeDestinationAudioNode, output, input); + } + }; + + var getNativeAudioNode = function getNativeAudioNode(audioNode) { + return getValueForKey(AUDIO_NODE_STORE, audioNode); + }; + + var getNativeAudioParam = function getNativeAudioParam(audioParam) { + return getValueForKey(AUDIO_PARAM_STORE, audioParam); + }; + + var isPartOfACycle = function isPartOfACycle(audioNode) { + return CYCLE_COUNTERS.has(audioNode); + }; + + var isPassiveAudioNode = function isPassiveAudioNode(audioNode) { + return !ACTIVE_AUDIO_NODE_STORE.has(audioNode); + }; + + var testAudioNodeDisconnectMethodSupport = function testAudioNodeDisconnectMethodSupport(nativeAudioContext, nativeAudioWorkletNodeConstructor) { + return new Promise(function (resolve) { + /* + * This bug existed in Safari up until v14.0.2. Since AudioWorklets were not supported in Safari until v14.1 the presence of the + * constructor for an AudioWorkletNode can be used here to skip the test. + */ + if (nativeAudioWorkletNodeConstructor !== null) { + resolve(true); + } else { + var analyzer = nativeAudioContext.createScriptProcessor(256, 1, 1); // tslint:disable-line deprecation + var dummy = nativeAudioContext.createGain(); + // Bug #95: Safari does not play one sample buffers. + var ones = nativeAudioContext.createBuffer(1, 2, 44100); + var channelData = ones.getChannelData(0); + channelData[0] = 1; + channelData[1] = 1; + var source = nativeAudioContext.createBufferSource(); + source.buffer = ones; + source.loop = true; + source.connect(analyzer).connect(nativeAudioContext.destination); + source.connect(dummy); + source.disconnect(dummy); + // tslint:disable-next-line:deprecation + analyzer.onaudioprocess = function (event) { + var chnnlDt = event.inputBuffer.getChannelData(0); // tslint:disable-line deprecation + if (Array.prototype.some.call(chnnlDt, function (sample) { + return sample === 1; + })) { + resolve(true); + } else { + resolve(false); + } + source.stop(); + analyzer.onaudioprocess = null; // tslint:disable-line:deprecation + source.disconnect(analyzer); + analyzer.disconnect(nativeAudioContext.destination); + }; + source.start(); + } + }); + }; + + function _createForOfIteratorHelper$8(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$8(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } + function _unsupportedIterableToArray$8(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$8(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$8(r, a) : void 0; } } + function _arrayLikeToArray$8(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } + var visitEachAudioNodeOnce = function visitEachAudioNodeOnce(cycles, visitor) { + var counts = new Map(); + var _iterator = _createForOfIteratorHelper$8(cycles), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var cycle = _step.value; + var _iterator2 = _createForOfIteratorHelper$8(cycle), + _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + var audioNode = _step2.value; + var count = counts.get(audioNode); + counts.set(audioNode, count === undefined ? 1 : count + 1); + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + counts.forEach(function (count, audioNode) { + return visitor(audioNode, count); + }); + }; + + var isNativeAudioNode$1 = function isNativeAudioNode(nativeAudioNodeOrAudioParam) { + return 'context' in nativeAudioNodeOrAudioParam; + }; + + function _createForOfIteratorHelper$7(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$7(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } + function _unsupportedIterableToArray$7(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$7(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$7(r, a) : void 0; } } + function _arrayLikeToArray$7(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } + var wrapAudioNodeDisconnectMethod = function wrapAudioNodeDisconnectMethod(nativeAudioNode) { + var connections = new Map(); + nativeAudioNode.connect = function (connect) { + // tslint:disable-next-line:invalid-void no-inferrable-types + return function (destination) { + var output = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var input = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var returnValue = isNativeAudioNode$1(destination) ? connect(destination, output, input) : connect(destination, output); + // Save the new connection only if the calls to connect above didn't throw an error. + var connectionsToDestination = connections.get(destination); + if (connectionsToDestination === undefined) { + connections.set(destination, [{ + input: input, + output: output + }]); + } else { + if (connectionsToDestination.every(function (connection) { + return connection.input !== input || connection.output !== output; + })) { + connectionsToDestination.push({ + input: input, + output: output + }); + } + } + return returnValue; + }; + }(nativeAudioNode.connect.bind(nativeAudioNode)); + nativeAudioNode.disconnect = function (disconnect) { + return function (destinationOrOutput, output, input) { + disconnect.apply(nativeAudioNode); + if (destinationOrOutput === undefined) { + connections.clear(); + } else if (typeof destinationOrOutput === 'number') { + var _iterator = _createForOfIteratorHelper$7(connections), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var _step$value = _slicedToArray(_step.value, 2), + destination = _step$value[0], + connectionsToDestination = _step$value[1]; + var filteredConnections = connectionsToDestination.filter(function (connection) { + return connection.output !== destinationOrOutput; + }); + if (filteredConnections.length === 0) { + connections["delete"](destination); + } else { + connections.set(destination, filteredConnections); + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + } else if (connections.has(destinationOrOutput)) { + if (output === undefined) { + connections["delete"](destinationOrOutput); + } else { + var _connectionsToDestination = connections.get(destinationOrOutput); + if (_connectionsToDestination !== undefined) { + var _filteredConnections = _connectionsToDestination.filter(function (connection) { + return connection.output !== output && (connection.input !== input || input === undefined); + }); + if (_filteredConnections.length === 0) { + connections["delete"](destinationOrOutput); + } else { + connections.set(destinationOrOutput, _filteredConnections); + } + } + } + } + var _iterator2 = _createForOfIteratorHelper$7(connections), + _step2; + try { + var _loop = function _loop() { + var _step2$value = _slicedToArray(_step2.value, 2), + destination = _step2$value[0], + connectionsToDestination = _step2$value[1]; + connectionsToDestination.forEach(function (connection) { + if (isNativeAudioNode$1(destination)) { + nativeAudioNode.connect(destination, connection.output, connection.input); + } else { + nativeAudioNode.connect(destination, connection.output); + } + }); + }; + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + _loop(); + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + }; + }(nativeAudioNode.disconnect); + }; + + function _callSuper$n(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$n() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$n() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$n = function _isNativeReflectConstruct() { return !!t; })(); } + function _createForOfIteratorHelper$6(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$6(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } + function _unsupportedIterableToArray$6(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$6(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$6(r, a) : void 0; } } + function _arrayLikeToArray$6(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } + var addConnectionToAudioParamOfAudioContext = function addConnectionToAudioParamOfAudioContext(source, destination, output, isOffline) { + var _getAudioParamConnect = getAudioParamConnections(destination), + activeInputs = _getAudioParamConnect.activeInputs, + passiveInputs = _getAudioParamConnect.passiveInputs; + var _getAudioNodeConnecti = getAudioNodeConnections(source), + outputs = _getAudioNodeConnecti.outputs; + var eventListeners = getEventListenersOfAudioNode(source); + var eventListener = function eventListener(isActive) { + var nativeAudioNode = getNativeAudioNode(source); + var nativeAudioParam = getNativeAudioParam(destination); + if (isActive) { + var partialConnection = deletePassiveInputConnectionToAudioParam(passiveInputs, source, output); + addActiveInputConnectionToAudioParam(activeInputs, source, partialConnection, false); + if (!isOffline && !isPartOfACycle(source)) { + nativeAudioNode.connect(nativeAudioParam, output); + } + } else { + var _partialConnection = deleteActiveInputConnectionToAudioParam(activeInputs, source, output); + addPassiveInputConnectionToAudioParam(passiveInputs, _partialConnection, false); + if (!isOffline && !isPartOfACycle(source)) { + nativeAudioNode.disconnect(nativeAudioParam, output); + } + } + }; + if (insertElementInSet(outputs, [destination, output], function (outputConnection) { + return outputConnection[0] === destination && outputConnection[1] === output; + }, true)) { + eventListeners.add(eventListener); + if (isActiveAudioNode(source)) { + addActiveInputConnectionToAudioParam(activeInputs, source, [output, eventListener], true); + } else { + addPassiveInputConnectionToAudioParam(passiveInputs, [source, output, eventListener], true); + } + return true; + } + return false; + }; + var deleteInputConnectionOfAudioNode = function deleteInputConnectionOfAudioNode(source, destination, output, input) { + var _getAudioNodeConnecti2 = getAudioNodeConnections(destination), + activeInputs = _getAudioNodeConnecti2.activeInputs, + passiveInputs = _getAudioNodeConnecti2.passiveInputs; + var activeInputConnection = deleteActiveInputConnection(activeInputs[input], source, output); + if (activeInputConnection === null) { + var passiveInputConnection = deletePassiveInputConnectionToAudioNode(passiveInputs, source, output, input); + return [passiveInputConnection[2], false]; + } + return [activeInputConnection[2], true]; + }; + var deleteInputConnectionOfAudioParam = function deleteInputConnectionOfAudioParam(source, destination, output) { + var _getAudioParamConnect2 = getAudioParamConnections(destination), + activeInputs = _getAudioParamConnect2.activeInputs, + passiveInputs = _getAudioParamConnect2.passiveInputs; + var activeInputConnection = deleteActiveInputConnection(activeInputs, source, output); + if (activeInputConnection === null) { + var passiveInputConnection = deletePassiveInputConnectionToAudioParam(passiveInputs, source, output); + return [passiveInputConnection[1], false]; + } + return [activeInputConnection[2], true]; + }; + var deleteInputsOfAudioNode = function deleteInputsOfAudioNode(source, isOffline, destination, output, input) { + var _deleteInputConnectio = deleteInputConnectionOfAudioNode(source, destination, output, input), + _deleteInputConnectio2 = _slicedToArray(_deleteInputConnectio, 2), + listener = _deleteInputConnectio2[0], + isActive = _deleteInputConnectio2[1]; + if (listener !== null) { + deleteEventListenerOfAudioNode(source, listener); + if (isActive && !isOffline && !isPartOfACycle(source)) { + disconnectNativeAudioNodeFromNativeAudioNode(getNativeAudioNode(source), getNativeAudioNode(destination), output, input); + } + } + if (isActiveAudioNode(destination)) { + var _getAudioNodeConnecti3 = getAudioNodeConnections(destination), + activeInputs = _getAudioNodeConnecti3.activeInputs; + setInternalStateToPassiveWhenNecessary(destination, activeInputs); + } + }; + var deleteInputsOfAudioParam = function deleteInputsOfAudioParam(source, isOffline, destination, output) { + var _deleteInputConnectio3 = deleteInputConnectionOfAudioParam(source, destination, output), + _deleteInputConnectio4 = _slicedToArray(_deleteInputConnectio3, 2), + listener = _deleteInputConnectio4[0], + isActive = _deleteInputConnectio4[1]; + if (listener !== null) { + deleteEventListenerOfAudioNode(source, listener); + if (isActive && !isOffline && !isPartOfACycle(source)) { + getNativeAudioNode(source).disconnect(getNativeAudioParam(destination), output); + } + } + }; + var deleteAnyConnection = function deleteAnyConnection(source, isOffline) { + var audioNodeConnectionsOfSource = getAudioNodeConnections(source); + var destinations = []; + var _iterator = _createForOfIteratorHelper$6(audioNodeConnectionsOfSource.outputs), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var outputConnection = _step.value; + if (isAudioNodeOutputConnection(outputConnection)) { + deleteInputsOfAudioNode.apply(void 0, [source, isOffline].concat(_toConsumableArray(outputConnection))); + } else { + deleteInputsOfAudioParam.apply(void 0, [source, isOffline].concat(_toConsumableArray(outputConnection))); + } + destinations.push(outputConnection[0]); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + audioNodeConnectionsOfSource.outputs.clear(); + return destinations; + }; + var deleteConnectionAtOutput = function deleteConnectionAtOutput(source, isOffline, output) { + var audioNodeConnectionsOfSource = getAudioNodeConnections(source); + var destinations = []; + var _iterator2 = _createForOfIteratorHelper$6(audioNodeConnectionsOfSource.outputs), + _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + var outputConnection = _step2.value; + if (outputConnection[1] === output) { + if (isAudioNodeOutputConnection(outputConnection)) { + deleteInputsOfAudioNode.apply(void 0, [source, isOffline].concat(_toConsumableArray(outputConnection))); + } else { + deleteInputsOfAudioParam.apply(void 0, [source, isOffline].concat(_toConsumableArray(outputConnection))); + } + destinations.push(outputConnection[0]); + audioNodeConnectionsOfSource.outputs["delete"](outputConnection); + } + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + return destinations; + }; + var deleteConnectionToDestination = function deleteConnectionToDestination(source, isOffline, destination, output, input) { + var audioNodeConnectionsOfSource = getAudioNodeConnections(source); + return Array.from(audioNodeConnectionsOfSource.outputs).filter(function (outputConnection) { + return outputConnection[0] === destination && (output === undefined || outputConnection[1] === output) && (input === undefined || outputConnection[2] === input); + }).map(function (outputConnection) { + if (isAudioNodeOutputConnection(outputConnection)) { + deleteInputsOfAudioNode.apply(void 0, [source, isOffline].concat(_toConsumableArray(outputConnection))); + } else { + deleteInputsOfAudioParam.apply(void 0, [source, isOffline].concat(_toConsumableArray(outputConnection))); + } + audioNodeConnectionsOfSource.outputs["delete"](outputConnection); + return outputConnection[0]; + }); + }; + var createAudioNodeConstructor = function createAudioNodeConstructor(addAudioNodeConnections, addConnectionToAudioNode, cacheTestResult, createIncrementCycleCounter, createIndexSizeError, createInvalidAccessError, createNotSupportedError, decrementCycleCounter, detectCycles, eventTargetConstructor, getNativeContext, isNativeAudioContext, isNativeAudioNode, isNativeAudioParam, isNativeOfflineAudioContext, nativeAudioWorkletNodeConstructor) { + return /*#__PURE__*/function (_eventTargetConstruct) { + function AudioNode(context, isActive, nativeAudioNode, audioNodeRenderer) { + var _this; + _classCallCheck(this, AudioNode); + _this = _callSuper$n(this, AudioNode, [nativeAudioNode]); + _this._context = context; + _this._nativeAudioNode = nativeAudioNode; + var nativeContext = getNativeContext(context); + // Bug #12: Safari does not support to disconnect a specific destination. + if (isNativeAudioContext(nativeContext) && true !== cacheTestResult(testAudioNodeDisconnectMethodSupport, function () { + return testAudioNodeDisconnectMethodSupport(nativeContext, nativeAudioWorkletNodeConstructor); + })) { + wrapAudioNodeDisconnectMethod(nativeAudioNode); + } + AUDIO_NODE_STORE.set(_this, nativeAudioNode); + EVENT_LISTENERS.set(_this, new Set()); + if (context.state !== 'closed' && isActive) { + setInternalStateToActive(_this); + } + addAudioNodeConnections(_this, audioNodeRenderer, nativeAudioNode); + return _this; + } + _inherits(AudioNode, _eventTargetConstruct); + return _createClass(AudioNode, [{ + key: "channelCount", + get: function get() { + return this._nativeAudioNode.channelCount; + }, + set: function set(value) { + this._nativeAudioNode.channelCount = value; + } + }, { + key: "channelCountMode", + get: function get() { + return this._nativeAudioNode.channelCountMode; + }, + set: function set(value) { + this._nativeAudioNode.channelCountMode = value; + } + }, { + key: "channelInterpretation", + get: function get() { + return this._nativeAudioNode.channelInterpretation; + }, + set: function set(value) { + this._nativeAudioNode.channelInterpretation = value; + } + }, { + key: "context", + get: function get() { + return this._context; + } + }, { + key: "numberOfInputs", + get: function get() { + return this._nativeAudioNode.numberOfInputs; + } + }, { + key: "numberOfOutputs", + get: function get() { + return this._nativeAudioNode.numberOfOutputs; + } + // tslint:disable-next-line:invalid-void + }, { + key: "connect", + value: function connect(destination) { + var output = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var input = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + // Bug #174: Safari does expose a wrong numberOfOutputs for MediaStreamAudioDestinationNodes. + if (output < 0 || output >= this._nativeAudioNode.numberOfOutputs) { + throw createIndexSizeError(); + } + var nativeContext = getNativeContext(this._context); + var isOffline = isNativeOfflineAudioContext(nativeContext); + if (isNativeAudioNode(destination) || isNativeAudioParam(destination)) { + throw createInvalidAccessError(); + } + if (isAudioNode(destination)) { + var nativeDestinationAudioNode = getNativeAudioNode(destination); + try { + var connection = connectNativeAudioNodeToNativeAudioNode(this._nativeAudioNode, nativeDestinationAudioNode, output, input); + var isPassive = isPassiveAudioNode(this); + if (isOffline || isPassive) { + var _this$_nativeAudioNod; + (_this$_nativeAudioNod = this._nativeAudioNode).disconnect.apply(_this$_nativeAudioNod, _toConsumableArray(connection)); + } + if (this.context.state !== 'closed' && !isPassive && isPassiveAudioNode(destination)) { + setInternalStateToActive(destination); + } + } catch (err) { + // Bug #41: Safari does not throw the correct exception so far. + if (err.code === 12) { + throw createInvalidAccessError(); + } + throw err; + } + var isNewConnectionToAudioNode = addConnectionToAudioNode(this, destination, output, input, isOffline); + // Bug #164: Only Firefox detects cycles so far. + if (isNewConnectionToAudioNode) { + var cycles = detectCycles([this], destination); + visitEachAudioNodeOnce(cycles, createIncrementCycleCounter(isOffline)); + } + return destination; + } + var nativeAudioParam = getNativeAudioParam(destination); + /* + * Bug #73, #147 & #153: Safari does not support to connect an input signal to the playbackRate AudioParam of an + * AudioBufferSourceNode. This can't be easily detected and that's why the outdated name property is used here to identify + * Safari. In addition to that the maxValue property is used to only detect the affected versions below v14.0.2. + */ + if (nativeAudioParam.name === 'playbackRate' && nativeAudioParam.maxValue === 1024) { + throw createNotSupportedError(); + } + try { + this._nativeAudioNode.connect(nativeAudioParam, output); + if (isOffline || isPassiveAudioNode(this)) { + this._nativeAudioNode.disconnect(nativeAudioParam, output); + } + } catch (err) { + // Bug #58: Safari doesn't throw an InvalidAccessError yet. + if (err.code === 12) { + throw createInvalidAccessError(); + } + throw err; + } + var isNewConnectionToAudioParam = addConnectionToAudioParamOfAudioContext(this, destination, output, isOffline); + // Bug #164: Only Firefox detects cycles so far. + if (isNewConnectionToAudioParam) { + var _cycles = detectCycles([this], destination); + visitEachAudioNodeOnce(_cycles, createIncrementCycleCounter(isOffline)); + } + } + }, { + key: "disconnect", + value: function disconnect(destinationOrOutput, output, input) { + var destinations; + var nativeContext = getNativeContext(this._context); + var isOffline = isNativeOfflineAudioContext(nativeContext); + if (destinationOrOutput === undefined) { + destinations = deleteAnyConnection(this, isOffline); + } else if (typeof destinationOrOutput === 'number') { + if (destinationOrOutput < 0 || destinationOrOutput >= this.numberOfOutputs) { + throw createIndexSizeError(); + } + destinations = deleteConnectionAtOutput(this, isOffline, destinationOrOutput); + } else { + if (output !== undefined && (output < 0 || output >= this.numberOfOutputs)) { + throw createIndexSizeError(); + } + if (isAudioNode(destinationOrOutput) && input !== undefined && (input < 0 || input >= destinationOrOutput.numberOfInputs)) { + throw createIndexSizeError(); + } + destinations = deleteConnectionToDestination(this, isOffline, destinationOrOutput, output, input); + if (destinations.length === 0) { + throw createInvalidAccessError(); + } + } + // Bug #164: Only Firefox detects cycles so far. + var _iterator3 = _createForOfIteratorHelper$6(destinations), + _step3; + try { + for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { + var destination = _step3.value; + var cycles = detectCycles([this], destination); + visitEachAudioNodeOnce(cycles, decrementCycleCounter); + } + } catch (err) { + _iterator3.e(err); + } finally { + _iterator3.f(); + } + } + }]); + }(eventTargetConstructor); + }; + + var createAudioParamFactory = function createAudioParamFactory(addAudioParamConnections, audioParamAudioNodeStore, audioParamStore, createAudioParamRenderer, createCancelAndHoldAutomationEvent, createCancelScheduledValuesAutomationEvent, createExponentialRampToValueAutomationEvent, createLinearRampToValueAutomationEvent, createSetTargetAutomationEvent, createSetValueAutomationEvent, createSetValueCurveAutomationEvent, nativeAudioContextConstructor, setValueAtTimeUntilPossible) { + return function (audioNode, isAudioParamOfOfflineAudioContext, nativeAudioParam) { + var maxValue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var minValue = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; + // Bug #196 Only Safari sets the defaultValue to the initial value. + var defaultValue = nativeAudioParam.value; + var automationEventList = new automationEvents.AutomationEventList(defaultValue); + var audioParamRenderer = isAudioParamOfOfflineAudioContext ? createAudioParamRenderer(automationEventList) : null; + var audioParam = { + get defaultValue() { + return defaultValue; + }, + get maxValue() { + return maxValue === null ? nativeAudioParam.maxValue : maxValue; + }, + get minValue() { + return minValue === null ? nativeAudioParam.minValue : minValue; + }, + get value() { + return nativeAudioParam.value; + }, + set value(value) { + nativeAudioParam.value = value; + // Bug #98: Firefox & Safari do not yet treat the value setter like a call to setValueAtTime(). + audioParam.setValueAtTime(value, audioNode.context.currentTime); + }, + cancelAndHoldAtTime: function cancelAndHoldAtTime(cancelTime) { + // Bug #28: Firefox & Safari do not yet implement cancelAndHoldAtTime(). + if (typeof nativeAudioParam.cancelAndHoldAtTime === 'function') { + if (audioParamRenderer === null) { + automationEventList.flush(audioNode.context.currentTime); + } + automationEventList.add(createCancelAndHoldAutomationEvent(cancelTime)); + nativeAudioParam.cancelAndHoldAtTime(cancelTime); + } else { + var previousLastEvent = Array.from(automationEventList).pop(); + if (audioParamRenderer === null) { + automationEventList.flush(audioNode.context.currentTime); + } + automationEventList.add(createCancelAndHoldAutomationEvent(cancelTime)); + var currentLastEvent = Array.from(automationEventList).pop(); + nativeAudioParam.cancelScheduledValues(cancelTime); + if (previousLastEvent !== currentLastEvent && currentLastEvent !== undefined) { + if (currentLastEvent.type === 'exponentialRampToValue') { + nativeAudioParam.exponentialRampToValueAtTime(currentLastEvent.value, currentLastEvent.endTime); + } else if (currentLastEvent.type === 'linearRampToValue') { + nativeAudioParam.linearRampToValueAtTime(currentLastEvent.value, currentLastEvent.endTime); + } else if (currentLastEvent.type === 'setValue') { + nativeAudioParam.setValueAtTime(currentLastEvent.value, currentLastEvent.startTime); + } else if (currentLastEvent.type === 'setValueCurve') { + nativeAudioParam.setValueCurveAtTime(currentLastEvent.values, currentLastEvent.startTime, currentLastEvent.duration); + } + } + } + return audioParam; + }, + cancelScheduledValues: function cancelScheduledValues(cancelTime) { + if (audioParamRenderer === null) { + automationEventList.flush(audioNode.context.currentTime); + } + automationEventList.add(createCancelScheduledValuesAutomationEvent(cancelTime)); + nativeAudioParam.cancelScheduledValues(cancelTime); + return audioParam; + }, + exponentialRampToValueAtTime: function exponentialRampToValueAtTime(value, endTime) { + // Bug #45: Safari does not throw an error yet. + if (value === 0) { + throw new RangeError(); + } + // Bug #187: Safari does not throw an error yet. + if (!Number.isFinite(endTime) || endTime < 0) { + throw new RangeError(); + } + var currentTime = audioNode.context.currentTime; + if (audioParamRenderer === null) { + automationEventList.flush(currentTime); + } + // Bug #194: Firefox does not implicitly call setValueAtTime() if there is no previous event. + if (Array.from(automationEventList).length === 0) { + automationEventList.add(createSetValueAutomationEvent(defaultValue, currentTime)); + nativeAudioParam.setValueAtTime(defaultValue, currentTime); + } + automationEventList.add(createExponentialRampToValueAutomationEvent(value, endTime)); + nativeAudioParam.exponentialRampToValueAtTime(value, endTime); + return audioParam; + }, + linearRampToValueAtTime: function linearRampToValueAtTime(value, endTime) { + var currentTime = audioNode.context.currentTime; + if (audioParamRenderer === null) { + automationEventList.flush(currentTime); + } + // Bug #195: Firefox does not implicitly call setValueAtTime() if there is no previous event. + if (Array.from(automationEventList).length === 0) { + automationEventList.add(createSetValueAutomationEvent(defaultValue, currentTime)); + nativeAudioParam.setValueAtTime(defaultValue, currentTime); + } + automationEventList.add(createLinearRampToValueAutomationEvent(value, endTime)); + nativeAudioParam.linearRampToValueAtTime(value, endTime); + return audioParam; + }, + setTargetAtTime: function setTargetAtTime(target, startTime, timeConstant) { + if (audioParamRenderer === null) { + automationEventList.flush(audioNode.context.currentTime); + } + automationEventList.add(createSetTargetAutomationEvent(target, startTime, timeConstant)); + nativeAudioParam.setTargetAtTime(target, startTime, timeConstant); + return audioParam; + }, + setValueAtTime: function setValueAtTime(value, startTime) { + if (audioParamRenderer === null) { + automationEventList.flush(audioNode.context.currentTime); + } + automationEventList.add(createSetValueAutomationEvent(value, startTime)); + nativeAudioParam.setValueAtTime(value, startTime); + return audioParam; + }, + setValueCurveAtTime: function setValueCurveAtTime(values, startTime, duration) { + // Bug 183: Safari only accepts a Float32Array. + var convertedValues = values instanceof Float32Array ? values : new Float32Array(values); + /* + * Bug #152: Safari does not correctly interpolate the values of the curve. + * @todo Unfortunately there is no way to test for this behavior in a synchronous fashion which is why testing for the + * existence of the webkitAudioContext is used as a workaround here. + */ + if (nativeAudioContextConstructor !== null && nativeAudioContextConstructor.name === 'webkitAudioContext') { + var endTime = startTime + duration; + var sampleRate = audioNode.context.sampleRate; + var firstSample = Math.ceil(startTime * sampleRate); + var lastSample = Math.floor(endTime * sampleRate); + var numberOfInterpolatedValues = lastSample - firstSample; + var interpolatedValues = new Float32Array(numberOfInterpolatedValues); + for (var i = 0; i < numberOfInterpolatedValues; i += 1) { + var theoreticIndex = (convertedValues.length - 1) / duration * ((firstSample + i) / sampleRate - startTime); + var lowerIndex = Math.floor(theoreticIndex); + var upperIndex = Math.ceil(theoreticIndex); + interpolatedValues[i] = lowerIndex === upperIndex ? convertedValues[lowerIndex] : (1 - (theoreticIndex - lowerIndex)) * convertedValues[lowerIndex] + (1 - (upperIndex - theoreticIndex)) * convertedValues[upperIndex]; + } + if (audioParamRenderer === null) { + automationEventList.flush(audioNode.context.currentTime); + } + automationEventList.add(createSetValueCurveAutomationEvent(interpolatedValues, startTime, duration)); + nativeAudioParam.setValueCurveAtTime(interpolatedValues, startTime, duration); + var timeOfLastSample = lastSample / sampleRate; + if (timeOfLastSample < endTime) { + setValueAtTimeUntilPossible(audioParam, interpolatedValues[interpolatedValues.length - 1], timeOfLastSample); + } + setValueAtTimeUntilPossible(audioParam, convertedValues[convertedValues.length - 1], endTime); + } else { + if (audioParamRenderer === null) { + automationEventList.flush(audioNode.context.currentTime); + } + automationEventList.add(createSetValueCurveAutomationEvent(convertedValues, startTime, duration)); + nativeAudioParam.setValueCurveAtTime(convertedValues, startTime, duration); + } + return audioParam; + } + }; + audioParamStore.set(audioParam, nativeAudioParam); + audioParamAudioNodeStore.set(audioParam, audioNode); + addAudioParamConnections(audioParam, audioParamRenderer); + return audioParam; + }; + }; + + function _createForOfIteratorHelper$5(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$5(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } + function _unsupportedIterableToArray$5(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$5(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$5(r, a) : void 0; } } + function _arrayLikeToArray$5(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } + var createAudioParamRenderer = function createAudioParamRenderer(automationEventList) { + return { + replay: function replay(audioParam) { + var _iterator = _createForOfIteratorHelper$5(automationEventList), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var automationEvent = _step.value; + if (automationEvent.type === 'exponentialRampToValue') { + var endTime = automationEvent.endTime, + value = automationEvent.value; + audioParam.exponentialRampToValueAtTime(value, endTime); + } else if (automationEvent.type === 'linearRampToValue') { + var _endTime = automationEvent.endTime, + _value = automationEvent.value; + audioParam.linearRampToValueAtTime(_value, _endTime); + } else if (automationEvent.type === 'setTarget') { + var startTime = automationEvent.startTime, + target = automationEvent.target, + timeConstant = automationEvent.timeConstant; + audioParam.setTargetAtTime(target, startTime, timeConstant); + } else if (automationEvent.type === 'setValue') { + var _startTime = automationEvent.startTime, + _value2 = automationEvent.value; + audioParam.setValueAtTime(_value2, _startTime); + } else if (automationEvent.type === 'setValueCurve') { + var duration = automationEvent.duration, + _startTime2 = automationEvent.startTime, + values = automationEvent.values; + audioParam.setValueCurveAtTime(values, _startTime2, duration); + } else { + throw new Error("Can't apply an unknown automation."); + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + } + }; + }; + + var ReadOnlyMap = /*#__PURE__*/function () { + function ReadOnlyMap(parameters) { + _classCallCheck(this, ReadOnlyMap); + this._map = new Map(parameters); + } + return _createClass(ReadOnlyMap, [{ + key: "size", + get: function get() { + return this._map.size; + } + }, { + key: "entries", + value: function entries() { + return this._map.entries(); + } + }, { + key: "forEach", + value: function forEach(callback) { + var _this = this; + var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + return this._map.forEach(function (value, key) { + return callback.call(thisArg, value, key, _this); + }); + } + }, { + key: "get", + value: function get(name) { + return this._map.get(name); + } + }, { + key: "has", + value: function has(name) { + return this._map.has(name); + } + }, { + key: "keys", + value: function keys() { + return this._map.keys(); + } + }, { + key: "values", + value: function values() { + return this._map.values(); + } + }]); + }(); + + function ownKeys$t(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$t(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$t(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$t(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$m(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$m() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$m() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$m = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$h = { + channelCount: 2, + // Bug #61: The channelCountMode should be 'max' according to the spec but is set to 'explicit' to achieve consistent behavior. + channelCountMode: 'explicit', + channelInterpretation: 'speakers', + numberOfInputs: 1, + numberOfOutputs: 1, + parameterData: {}, + processorOptions: {} + }; + var createAudioWorkletNodeConstructor = function createAudioWorkletNodeConstructor(addUnrenderedAudioWorkletNode, audioNodeConstructor, createAudioParam, createAudioWorkletNodeRenderer, createNativeAudioWorkletNode, getAudioNodeConnections, getBackupOfflineAudioContext, getNativeContext, isNativeOfflineAudioContext, nativeAudioWorkletNodeConstructor, sanitizeAudioWorkletNodeOptions, setActiveAudioWorkletNodeInputs, testAudioWorkletNodeOptionsClonability, wrapEventListener) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function AudioWorkletNode(context, name, options) { + var _this; + _classCallCheck(this, AudioWorkletNode); + var _a; + var nativeContext = getNativeContext(context); + var isOffline = isNativeOfflineAudioContext(nativeContext); + var mergedOptions = sanitizeAudioWorkletNodeOptions(_objectSpread$t(_objectSpread$t({}, DEFAULT_OPTIONS$h), options)); + // Bug #191: Safari doesn't throw an error if the options aren't clonable. + testAudioWorkletNodeOptionsClonability(mergedOptions); + var nodeNameToProcessorConstructorMap = NODE_NAME_TO_PROCESSOR_CONSTRUCTOR_MAPS.get(nativeContext); + var processorConstructor = nodeNameToProcessorConstructorMap === null || nodeNameToProcessorConstructorMap === void 0 ? void 0 : nodeNameToProcessorConstructorMap.get(name); + // Bug #186: Chrome and Edge do not allow to create an AudioWorkletNode on a closed AudioContext. + var nativeContextOrBackupOfflineAudioContext = isOffline || nativeContext.state !== 'closed' ? nativeContext : (_a = getBackupOfflineAudioContext(nativeContext)) !== null && _a !== void 0 ? _a : nativeContext; + var nativeAudioWorkletNode = createNativeAudioWorkletNode(nativeContextOrBackupOfflineAudioContext, isOffline ? null : context.baseLatency, nativeAudioWorkletNodeConstructor, name, processorConstructor, mergedOptions); + var audioWorkletNodeRenderer = isOffline ? createAudioWorkletNodeRenderer(name, mergedOptions, processorConstructor) : null; + /* + * @todo Add a mechanism to switch an AudioWorkletNode to passive once the process() function of the AudioWorkletProcessor + * returns false. + */ + _this = _callSuper$m(this, AudioWorkletNode, [context, true, nativeAudioWorkletNode, audioWorkletNodeRenderer]); + var parameters = []; + nativeAudioWorkletNode.parameters.forEach(function (nativeAudioParam, nm) { + var audioParam = createAudioParam(_this, isOffline, nativeAudioParam); + parameters.push([nm, audioParam]); + }); + _this._nativeAudioWorkletNode = nativeAudioWorkletNode; + _this._onprocessorerror = null; + _this._parameters = new ReadOnlyMap(parameters); + /* + * Bug #86 & #87: Invoking the renderer of an AudioWorkletNode might be necessary if it has no direct or indirect connection to + * the destination. + */ + if (isOffline) { + addUnrenderedAudioWorkletNode(nativeContext, _this); + } + var _getAudioNodeConnecti = getAudioNodeConnections(_this), + activeInputs = _getAudioNodeConnecti.activeInputs; + setActiveAudioWorkletNodeInputs(nativeAudioWorkletNode, activeInputs); + return _this; + } + _inherits(AudioWorkletNode, _audioNodeConstructor); + return _createClass(AudioWorkletNode, [{ + key: "onprocessorerror", + get: function get() { + return this._onprocessorerror; + }, + set: function set(value) { + var wrappedListener = typeof value === 'function' ? wrapEventListener(this, value) : null; + this._nativeAudioWorkletNode.onprocessorerror = wrappedListener; + var nativeOnProcessorError = this._nativeAudioWorkletNode.onprocessorerror; + this._onprocessorerror = nativeOnProcessorError !== null && nativeOnProcessorError === wrappedListener ? value : nativeOnProcessorError; + } + }, { + key: "parameters", + get: function get() { + if (this._parameters === null) { + // @todo The definition that TypeScript uses of the AudioParamMap is lacking many methods. + return this._nativeAudioWorkletNode.parameters; + } + return this._parameters; + } + }, { + key: "port", + get: function get() { + return this._nativeAudioWorkletNode.port; + } + }]); + }(audioNodeConstructor); + }; + + function copyFromChannel(audioBuffer, + // @todo There is currently no way to define something like { [ key: number | string ]: Float32Array } + parent, key, channelNumber, bufferOffset) { + if (typeof audioBuffer.copyFromChannel === 'function') { + // The byteLength will be 0 when the ArrayBuffer was transferred. + if (parent[key].byteLength === 0) { + parent[key] = new Float32Array(128); + } + audioBuffer.copyFromChannel(parent[key], channelNumber, bufferOffset); + // Bug #5: Safari does not support copyFromChannel(). + } else { + var channelData = audioBuffer.getChannelData(channelNumber); + // The byteLength will be 0 when the ArrayBuffer was transferred. + if (parent[key].byteLength === 0) { + parent[key] = channelData.slice(bufferOffset, bufferOffset + 128); + } else { + var slicedInput = new Float32Array(channelData.buffer, bufferOffset * Float32Array.BYTES_PER_ELEMENT, 128); + parent[key].set(slicedInput); + } + } + } + + var copyToChannel = function copyToChannel(audioBuffer, parent, key, channelNumber, bufferOffset) { + if (typeof audioBuffer.copyToChannel === 'function') { + // The byteLength will be 0 when the ArrayBuffer was transferred. + if (parent[key].byteLength !== 0) { + audioBuffer.copyToChannel(parent[key], channelNumber, bufferOffset); + } + // Bug #5: Safari does not support copyToChannel(). + } else { + // The byteLength will be 0 when the ArrayBuffer was transferred. + if (parent[key].byteLength !== 0) { + audioBuffer.getChannelData(channelNumber).set(parent[key], bufferOffset); + } + } + }; + + var createNestedArrays = function createNestedArrays(x, y) { + var arrays = []; + for (var i = 0; i < x; i += 1) { + var array = []; + var length = typeof y === 'number' ? y : y[i]; + for (var j = 0; j < length; j += 1) { + array.push(new Float32Array(128)); + } + arrays.push(array); + } + return arrays; + }; + + var getAudioWorkletProcessor = function getAudioWorkletProcessor(nativeOfflineAudioContext, proxy) { + var nodeToProcessorMap = getValueForKey(NODE_TO_PROCESSOR_MAPS, nativeOfflineAudioContext); + var nativeAudioWorkletNode = getNativeAudioNode(proxy); + return getValueForKey(nodeToProcessorMap, nativeAudioWorkletNode); + }; + + function _createForOfIteratorHelper$4(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$4(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } + function _unsupportedIterableToArray$4(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$4(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$4(r, a) : void 0; } } + function _arrayLikeToArray$4(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } + function ownKeys$s(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$s(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$s(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$s(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + var processBuffer = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(proxy, renderedBuffer, nativeOfflineAudioContext, options, outputChannelCount, processorConstructor, exposeCurrentFrameAndCurrentTime) { + var length, numberOfInputChannels, numberOfOutputChannels, processedBuffer, audioNodeConnections, audioWorkletProcessor, inputs, outputs, parameters, _loop, _ret, i; + return _regeneratorRuntime.wrap(function _callee$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + // Ceil the length to the next full render quantum. + // Bug #17: Safari does not yet expose the length. + length = renderedBuffer === null ? Math.ceil(proxy.context.length / 128) * 128 : renderedBuffer.length; + numberOfInputChannels = options.channelCount * options.numberOfInputs; + numberOfOutputChannels = outputChannelCount.reduce(function (sum, value) { + return sum + value; + }, 0); + processedBuffer = numberOfOutputChannels === 0 ? null : nativeOfflineAudioContext.createBuffer(numberOfOutputChannels, length, nativeOfflineAudioContext.sampleRate); + if (!(processorConstructor === undefined)) { + _context2.next = 6; + break; + } + throw new Error('Missing the processor constructor.'); + case 6: + audioNodeConnections = getAudioNodeConnections(proxy); + _context2.next = 9; + return getAudioWorkletProcessor(nativeOfflineAudioContext, proxy); + case 9: + audioWorkletProcessor = _context2.sent; + inputs = createNestedArrays(options.numberOfInputs, options.channelCount); + outputs = createNestedArrays(options.numberOfOutputs, outputChannelCount); + parameters = Array.from(proxy.parameters.keys()).reduce(function (prmtrs, name) { + return _objectSpread$s(_objectSpread$s({}, prmtrs), {}, _defineProperty({}, name, new Float32Array(128))); + }, {}); + _loop = /*#__PURE__*/_regeneratorRuntime.mark(function _loop(i) { + var j, k, _j, _k, potentiallyEmptyInputs, activeSourceFlag, _j2, outputChannelSplitterNodeOutput, _k2; + return _regeneratorRuntime.wrap(function _loop$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (options.numberOfInputs > 0 && renderedBuffer !== null) { + for (j = 0; j < options.numberOfInputs; j += 1) { + for (k = 0; k < options.channelCount; k += 1) { + copyFromChannel(renderedBuffer, inputs[j], k, k, i); + } + } + } + if (processorConstructor.parameterDescriptors !== undefined && renderedBuffer !== null) { + processorConstructor.parameterDescriptors.forEach(function (_ref2, index) { + var name = _ref2.name; + copyFromChannel(renderedBuffer, parameters, name, numberOfInputChannels + index, i); + }); + } + for (_j = 0; _j < options.numberOfInputs; _j += 1) { + for (_k = 0; _k < outputChannelCount[_j]; _k += 1) { + // The byteLength will be 0 when the ArrayBuffer was transferred. + if (outputs[_j][_k].byteLength === 0) { + outputs[_j][_k] = new Float32Array(128); + } + } + } + _context.prev = 3; + potentiallyEmptyInputs = inputs.map(function (input, index) { + if (audioNodeConnections.activeInputs[index].size === 0) { + return []; + } + return input; + }); + activeSourceFlag = exposeCurrentFrameAndCurrentTime(i / nativeOfflineAudioContext.sampleRate, nativeOfflineAudioContext.sampleRate, function () { + return audioWorkletProcessor.process(potentiallyEmptyInputs, outputs, parameters); + }); + if (processedBuffer !== null) { + for (_j2 = 0, outputChannelSplitterNodeOutput = 0; _j2 < options.numberOfOutputs; _j2 += 1) { + for (_k2 = 0; _k2 < outputChannelCount[_j2]; _k2 += 1) { + copyToChannel(processedBuffer, outputs[_j2], _k2, outputChannelSplitterNodeOutput + _k2, i); + } + outputChannelSplitterNodeOutput += outputChannelCount[_j2]; + } + } + if (activeSourceFlag) { + _context.next = 9; + break; + } + return _context.abrupt("return", 0); + case 9: + _context.next = 15; + break; + case 11: + _context.prev = 11; + _context.t0 = _context["catch"](3); + proxy.dispatchEvent(new ErrorEvent('processorerror', { + colno: _context.t0.colno, + filename: _context.t0.filename, + lineno: _context.t0.lineno, + message: _context.t0.message + })); + return _context.abrupt("return", 0); + case 15: + case "end": + return _context.stop(); + } + }, _loop, null, [[3, 11]]); + }); + i = 0; + case 15: + if (!(i < length)) { + _context2.next = 23; + break; + } + return _context2.delegateYield(_loop(i), "t0", 17); + case 17: + _ret = _context2.t0; + if (!(_ret === 0)) { + _context2.next = 20; + break; + } + return _context2.abrupt("break", 23); + case 20: + i += 128; + _context2.next = 15; + break; + case 23: + return _context2.abrupt("return", processedBuffer); + case 24: + case "end": + return _context2.stop(); + } + }, _callee); + })); + return function processBuffer(_x, _x2, _x3, _x4, _x5, _x6, _x7) { + return _ref.apply(this, arguments); + }; + }(); + var createAudioWorkletNodeRendererFactory = function createAudioWorkletNodeRendererFactory(connectAudioParam, connectMultipleOutputs, createNativeAudioBufferSourceNode, createNativeChannelMergerNode, createNativeChannelSplitterNode, createNativeConstantSourceNode, createNativeGainNode, deleteUnrenderedAudioWorkletNode, disconnectMultipleOutputs, exposeCurrentFrameAndCurrentTime, getNativeAudioNode, nativeAudioWorkletNodeConstructor, nativeOfflineAudioContextConstructor, renderAutomation, renderInputsOfAudioNode, renderNativeOfflineAudioContext) { + return function (name, options, processorConstructor) { + var renderedNativeAudioNodes = new WeakMap(); + var processedBufferPromise = null; + var createAudioNode = /*#__PURE__*/function () { + var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(proxy, nativeOfflineAudioContext) { + var nativeAudioWorkletNode, nativeOutputNodes, nativeAudioWorkletNodeIsOwnedByContext, outputChannelCount, numberOfOutputChannels, outputChannelSplitterNode, outputChannelMergerNodes, i, outputGainNode, numberOfInputChannels, numberOfParameters, numberOfChannels, renderBuffer, processedBuffer, audioBufferSourceNode, _nativeOutputNodes, _nativeOutputNodes2, _outputChannelSplitterNode, _outputChannelMergerNodes, _outputGainNode, _i3, outputChannelSplitterNodeOutput, outputChannelMergerNode, j, _iterator2, _step2, _step2$value, nm, audioParam, _iterator3, _step3, _step3$value, _nm, _audioParam; + return _regeneratorRuntime.wrap(function _callee4$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + nativeAudioWorkletNode = getNativeAudioNode(proxy); + nativeOutputNodes = null; + nativeAudioWorkletNodeIsOwnedByContext = isOwnedByContext(nativeAudioWorkletNode, nativeOfflineAudioContext); + outputChannelCount = Array.isArray(options.outputChannelCount) ? options.outputChannelCount : Array.from(options.outputChannelCount); // Bug #61: Only Chrome, Edge & Firefox have an implementation of the AudioWorkletNode yet. + if (nativeAudioWorkletNodeConstructor === null) { + numberOfOutputChannels = outputChannelCount.reduce(function (sum, value) { + return sum + value; + }, 0); + outputChannelSplitterNode = createNativeChannelSplitterNode(nativeOfflineAudioContext, { + channelCount: Math.max(1, numberOfOutputChannels), + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + numberOfOutputs: Math.max(1, numberOfOutputChannels) + }); + outputChannelMergerNodes = []; + for (i = 0; i < proxy.numberOfOutputs; i += 1) { + outputChannelMergerNodes.push(createNativeChannelMergerNode(nativeOfflineAudioContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'speakers', + numberOfInputs: outputChannelCount[i] + })); + } + outputGainNode = createNativeGainNode(nativeOfflineAudioContext, { + channelCount: options.channelCount, + channelCountMode: options.channelCountMode, + channelInterpretation: options.channelInterpretation, + gain: 1 + }); + outputGainNode.connect = connectMultipleOutputs.bind(null, outputChannelMergerNodes); + outputGainNode.disconnect = disconnectMultipleOutputs.bind(null, outputChannelMergerNodes); + nativeOutputNodes = [outputChannelSplitterNode, outputChannelMergerNodes, outputGainNode]; + } else if (!nativeAudioWorkletNodeIsOwnedByContext) { + nativeAudioWorkletNode = new nativeAudioWorkletNodeConstructor(nativeOfflineAudioContext, name); + } + renderedNativeAudioNodes.set(nativeOfflineAudioContext, nativeOutputNodes === null ? nativeAudioWorkletNode : nativeOutputNodes[2]); + if (!(nativeOutputNodes !== null)) { + _context5.next = 41; + break; + } + if (!(processedBufferPromise === null)) { + _context5.next = 32; + break; + } + if (!(processorConstructor === undefined)) { + _context5.next = 10; + break; + } + throw new Error('Missing the processor constructor.'); + case 10: + if (!(nativeOfflineAudioContextConstructor === null)) { + _context5.next = 12; + break; + } + throw new Error('Missing the native OfflineAudioContext constructor.'); + case 12: + // Bug #47: The AudioDestinationNode in Safari gets not initialized correctly. + numberOfInputChannels = proxy.channelCount * proxy.numberOfInputs; + numberOfParameters = processorConstructor.parameterDescriptors === undefined ? 0 : processorConstructor.parameterDescriptors.length; + numberOfChannels = numberOfInputChannels + numberOfParameters; + renderBuffer = /*#__PURE__*/function () { + var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { + var partialOfflineAudioContext, gainNodes, inputChannelSplitterNodes, _i, constantSourceNodes, inputChannelMergerNode, _i2, j, _iterator, _step, _step$value, index, constantSourceNode; + return _regeneratorRuntime.wrap(function _callee3$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + partialOfflineAudioContext = new nativeOfflineAudioContextConstructor(numberOfChannels, + // Ceil the length to the next full render quantum. + // Bug #17: Safari does not yet expose the length. + Math.ceil(proxy.context.length / 128) * 128, nativeOfflineAudioContext.sampleRate); + gainNodes = []; + inputChannelSplitterNodes = []; + for (_i = 0; _i < options.numberOfInputs; _i += 1) { + gainNodes.push(createNativeGainNode(partialOfflineAudioContext, { + channelCount: options.channelCount, + channelCountMode: options.channelCountMode, + channelInterpretation: options.channelInterpretation, + gain: 1 + })); + inputChannelSplitterNodes.push(createNativeChannelSplitterNode(partialOfflineAudioContext, { + channelCount: options.channelCount, + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + numberOfOutputs: options.channelCount + })); + } + _context4.next = 6; + return Promise.all(Array.from(proxy.parameters.values()).map(/*#__PURE__*/function () { + var _ref5 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(audioParam) { + var constantSourceNode; + return _regeneratorRuntime.wrap(function _callee2$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + constantSourceNode = createNativeConstantSourceNode(partialOfflineAudioContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + offset: audioParam.value + }); + _context3.next = 3; + return renderAutomation(partialOfflineAudioContext, audioParam, constantSourceNode.offset); + case 3: + return _context3.abrupt("return", constantSourceNode); + case 4: + case "end": + return _context3.stop(); + } + }, _callee2); + })); + return function (_x10) { + return _ref5.apply(this, arguments); + }; + }())); + case 6: + constantSourceNodes = _context4.sent; + inputChannelMergerNode = createNativeChannelMergerNode(partialOfflineAudioContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'speakers', + numberOfInputs: Math.max(1, numberOfInputChannels + numberOfParameters) + }); + for (_i2 = 0; _i2 < options.numberOfInputs; _i2 += 1) { + gainNodes[_i2].connect(inputChannelSplitterNodes[_i2]); + for (j = 0; j < options.channelCount; j += 1) { + inputChannelSplitterNodes[_i2].connect(inputChannelMergerNode, j, _i2 * options.channelCount + j); + } + } + _iterator = _createForOfIteratorHelper$4(constantSourceNodes.entries()); + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + _step$value = _slicedToArray(_step.value, 2), index = _step$value[0], constantSourceNode = _step$value[1]; + constantSourceNode.connect(inputChannelMergerNode, 0, numberOfInputChannels + index); + constantSourceNode.start(0); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + inputChannelMergerNode.connect(partialOfflineAudioContext.destination); + _context4.next = 14; + return Promise.all(gainNodes.map(function (gainNode) { + return renderInputsOfAudioNode(proxy, partialOfflineAudioContext, gainNode); + })); + case 14: + return _context4.abrupt("return", renderNativeOfflineAudioContext(partialOfflineAudioContext)); + case 15: + case "end": + return _context4.stop(); + } + }, _callee3); + })); + return function renderBuffer() { + return _ref4.apply(this, arguments); + }; + }(); + _context5.t0 = processBuffer; + _context5.t1 = proxy; + if (!(numberOfChannels === 0)) { + _context5.next = 22; + break; + } + _context5.t2 = null; + _context5.next = 25; + break; + case 22: + _context5.next = 24; + return renderBuffer(); + case 24: + _context5.t2 = _context5.sent; + case 25: + _context5.t3 = _context5.t2; + _context5.t4 = nativeOfflineAudioContext; + _context5.t5 = options; + _context5.t6 = outputChannelCount; + _context5.t7 = processorConstructor; + _context5.t8 = exposeCurrentFrameAndCurrentTime; + processedBufferPromise = (0, _context5.t0)(_context5.t1, _context5.t3, _context5.t4, _context5.t5, _context5.t6, _context5.t7, _context5.t8); + case 32: + _context5.next = 34; + return processedBufferPromise; + case 34: + processedBuffer = _context5.sent; + audioBufferSourceNode = createNativeAudioBufferSourceNode(nativeOfflineAudioContext, { + buffer: null, + channelCount: 2, + channelCountMode: 'max', + channelInterpretation: 'speakers', + loop: false, + loopEnd: 0, + loopStart: 0, + playbackRate: 1 + }); + _nativeOutputNodes = nativeOutputNodes, _nativeOutputNodes2 = _slicedToArray(_nativeOutputNodes, 3), _outputChannelSplitterNode = _nativeOutputNodes2[0], _outputChannelMergerNodes = _nativeOutputNodes2[1], _outputGainNode = _nativeOutputNodes2[2]; + if (processedBuffer !== null) { + audioBufferSourceNode.buffer = processedBuffer; + audioBufferSourceNode.start(0); + } + audioBufferSourceNode.connect(_outputChannelSplitterNode); + for (_i3 = 0, outputChannelSplitterNodeOutput = 0; _i3 < proxy.numberOfOutputs; _i3 += 1) { + outputChannelMergerNode = _outputChannelMergerNodes[_i3]; + for (j = 0; j < outputChannelCount[_i3]; j += 1) { + _outputChannelSplitterNode.connect(outputChannelMergerNode, outputChannelSplitterNodeOutput + j, j); + } + outputChannelSplitterNodeOutput += outputChannelCount[_i3]; + } + return _context5.abrupt("return", _outputGainNode); + case 41: + if (nativeAudioWorkletNodeIsOwnedByContext) { + _context5.next = 61; + break; + } + _iterator2 = _createForOfIteratorHelper$4(proxy.parameters.entries()); + _context5.prev = 43; + _iterator2.s(); + case 45: + if ((_step2 = _iterator2.n()).done) { + _context5.next = 51; + break; + } + _step2$value = _slicedToArray(_step2.value, 2), nm = _step2$value[0], audioParam = _step2$value[1]; + _context5.next = 49; + return renderAutomation(nativeOfflineAudioContext, audioParam, + // @todo The definition that TypeScript uses of the AudioParamMap is lacking many methods. + nativeAudioWorkletNode.parameters.get(nm)); + case 49: + _context5.next = 45; + break; + case 51: + _context5.next = 56; + break; + case 53: + _context5.prev = 53; + _context5.t9 = _context5["catch"](43); + _iterator2.e(_context5.t9); + case 56: + _context5.prev = 56; + _iterator2.f(); + return _context5.finish(56); + case 59: + _context5.next = 78; + break; + case 61: + _iterator3 = _createForOfIteratorHelper$4(proxy.parameters.entries()); + _context5.prev = 62; + _iterator3.s(); + case 64: + if ((_step3 = _iterator3.n()).done) { + _context5.next = 70; + break; + } + _step3$value = _slicedToArray(_step3.value, 2), _nm = _step3$value[0], _audioParam = _step3$value[1]; + _context5.next = 68; + return connectAudioParam(nativeOfflineAudioContext, _audioParam, + // @todo The definition that TypeScript uses of the AudioParamMap is lacking many methods. + nativeAudioWorkletNode.parameters.get(_nm)); + case 68: + _context5.next = 64; + break; + case 70: + _context5.next = 75; + break; + case 72: + _context5.prev = 72; + _context5.t10 = _context5["catch"](62); + _iterator3.e(_context5.t10); + case 75: + _context5.prev = 75; + _iterator3.f(); + return _context5.finish(75); + case 78: + _context5.next = 80; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAudioWorkletNode); + case 80: + return _context5.abrupt("return", nativeAudioWorkletNode); + case 81: + case "end": + return _context5.stop(); + } + }, _callee4, null, [[43, 53, 56, 59], [62, 72, 75, 78]]); + })); + return function createAudioNode(_x8, _x9) { + return _ref3.apply(this, arguments); + }; + }(); + return { + render: function render(proxy, nativeOfflineAudioContext) { + deleteUnrenderedAudioWorkletNode(nativeOfflineAudioContext, proxy); + var renderedNativeAudioWorkletNodeOrGainNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext); + if (renderedNativeAudioWorkletNodeOrGainNode !== undefined) { + return Promise.resolve(renderedNativeAudioWorkletNodeOrGainNode); + } + return createAudioNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + function ownKeys$r(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$r(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$r(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$r(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$l(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$l() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$l() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$l = function _isNativeReflectConstruct() { return !!t; })(); } + var createBaseAudioContextConstructor = function createBaseAudioContextConstructor(addAudioWorkletModule, analyserNodeConstructor, audioBufferConstructor, audioBufferSourceNodeConstructor, biquadFilterNodeConstructor, channelMergerNodeConstructor, channelSplitterNodeConstructor, constantSourceNodeConstructor, convolverNodeConstructor, _decodeAudioData, delayNodeConstructor, dynamicsCompressorNodeConstructor, gainNodeConstructor, iIRFilterNodeConstructor, minimalBaseAudioContextConstructor, oscillatorNodeConstructor, pannerNodeConstructor, periodicWaveConstructor, stereoPannerNodeConstructor, waveShaperNodeConstructor) { + return /*#__PURE__*/function (_minimalBaseAudioCont) { + function BaseAudioContext(_nativeContext, numberOfChannels) { + var _this; + _classCallCheck(this, BaseAudioContext); + _this = _callSuper$l(this, BaseAudioContext, [_nativeContext, numberOfChannels]); + _this._nativeContext = _nativeContext; + _this._audioWorklet = addAudioWorkletModule === undefined ? undefined : { + addModule: function addModule(moduleURL, options) { + return addAudioWorkletModule(_this, moduleURL, options); + } + }; + return _this; + } + _inherits(BaseAudioContext, _minimalBaseAudioCont); + return _createClass(BaseAudioContext, [{ + key: "audioWorklet", + get: function get() { + return this._audioWorklet; + } + }, { + key: "createAnalyser", + value: function createAnalyser() { + return new analyserNodeConstructor(this); + } + }, { + key: "createBiquadFilter", + value: function createBiquadFilter() { + return new biquadFilterNodeConstructor(this); + } + }, { + key: "createBuffer", + value: function createBuffer(numberOfChannels, length, sampleRate) { + return new audioBufferConstructor({ + length: length, + numberOfChannels: numberOfChannels, + sampleRate: sampleRate + }); + } + }, { + key: "createBufferSource", + value: function createBufferSource() { + return new audioBufferSourceNodeConstructor(this); + } + }, { + key: "createChannelMerger", + value: function createChannelMerger() { + var numberOfInputs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 6; + return new channelMergerNodeConstructor(this, { + numberOfInputs: numberOfInputs + }); + } + }, { + key: "createChannelSplitter", + value: function createChannelSplitter() { + var numberOfOutputs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 6; + return new channelSplitterNodeConstructor(this, { + numberOfOutputs: numberOfOutputs + }); + } + }, { + key: "createConstantSource", + value: function createConstantSource() { + return new constantSourceNodeConstructor(this); + } + }, { + key: "createConvolver", + value: function createConvolver() { + return new convolverNodeConstructor(this); + } + }, { + key: "createDelay", + value: function createDelay() { + var maxDelayTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + return new delayNodeConstructor(this, { + maxDelayTime: maxDelayTime + }); + } + }, { + key: "createDynamicsCompressor", + value: function createDynamicsCompressor() { + return new dynamicsCompressorNodeConstructor(this); + } + }, { + key: "createGain", + value: function createGain() { + return new gainNodeConstructor(this); + } + }, { + key: "createIIRFilter", + value: function createIIRFilter(feedforward, feedback) { + return new iIRFilterNodeConstructor(this, { + feedback: feedback, + feedforward: feedforward + }); + } + }, { + key: "createOscillator", + value: function createOscillator() { + return new oscillatorNodeConstructor(this); + } + }, { + key: "createPanner", + value: function createPanner() { + return new pannerNodeConstructor(this); + } + }, { + key: "createPeriodicWave", + value: function createPeriodicWave(real, imag) { + var constraints = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + disableNormalization: false + }; + return new periodicWaveConstructor(this, _objectSpread$r(_objectSpread$r({}, constraints), {}, { + imag: imag, + real: real + })); + } + }, { + key: "createStereoPanner", + value: function createStereoPanner() { + return new stereoPannerNodeConstructor(this); + } + }, { + key: "createWaveShaper", + value: function createWaveShaper() { + return new waveShaperNodeConstructor(this); + } + }, { + key: "decodeAudioData", + value: function decodeAudioData(audioData, successCallback, errorCallback) { + return _decodeAudioData(this._nativeContext, audioData).then(function (audioBuffer) { + if (typeof successCallback === 'function') { + successCallback(audioBuffer); + } + return audioBuffer; + }, function (err) { + if (typeof errorCallback === 'function') { + errorCallback(err); + } + throw err; + }); + } + }]); + }(minimalBaseAudioContextConstructor); + }; + + function ownKeys$q(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$q(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$q(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$q(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$k(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$k() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$k() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$k = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$g = { + Q: 1, + channelCount: 2, + channelCountMode: 'max', + channelInterpretation: 'speakers', + detune: 0, + frequency: 350, + gain: 0, + type: 'lowpass' + }; + var createBiquadFilterNodeConstructor = function createBiquadFilterNodeConstructor(audioNodeConstructor, createAudioParam, createBiquadFilterNodeRenderer, createInvalidAccessError, createNativeBiquadFilterNode, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function BiquadFilterNode(context, options) { + var _this; + _classCallCheck(this, BiquadFilterNode); + var nativeContext = getNativeContext(context); + var mergedOptions = _objectSpread$q(_objectSpread$q({}, DEFAULT_OPTIONS$g), options); + var nativeBiquadFilterNode = createNativeBiquadFilterNode(nativeContext, mergedOptions); + var isOffline = isNativeOfflineAudioContext(nativeContext); + var biquadFilterNodeRenderer = isOffline ? createBiquadFilterNodeRenderer() : null; + _this = _callSuper$k(this, BiquadFilterNode, [context, false, nativeBiquadFilterNode, biquadFilterNodeRenderer]); + // Bug #80: Safari does not export the correct values for maxValue and minValue. + _this._Q = createAudioParam(_this, isOffline, nativeBiquadFilterNode.Q, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT); + // Bug #78: Firefox & Safari do not export the correct values for maxValue and minValue. + _this._detune = createAudioParam(_this, isOffline, nativeBiquadFilterNode.detune, 1200 * Math.log2(MOST_POSITIVE_SINGLE_FLOAT), -1200 * Math.log2(MOST_POSITIVE_SINGLE_FLOAT)); + // Bug #77: Firefox & Safari do not export the correct value for minValue. + _this._frequency = createAudioParam(_this, isOffline, nativeBiquadFilterNode.frequency, context.sampleRate / 2, 0); + // Bug #79: Firefox & Safari do not export the correct values for maxValue and minValue. + _this._gain = createAudioParam(_this, isOffline, nativeBiquadFilterNode.gain, 40 * Math.log10(MOST_POSITIVE_SINGLE_FLOAT), MOST_NEGATIVE_SINGLE_FLOAT); + _this._nativeBiquadFilterNode = nativeBiquadFilterNode; + // @todo Determine a meaningful tail-time instead of just using one second. + setAudioNodeTailTime(_this, 1); + return _this; + } + _inherits(BiquadFilterNode, _audioNodeConstructor); + return _createClass(BiquadFilterNode, [{ + key: "detune", + get: function get() { + return this._detune; + } + }, { + key: "frequency", + get: function get() { + return this._frequency; + } + }, { + key: "gain", + get: function get() { + return this._gain; + } + }, { + key: "Q", + get: function get() { + return this._Q; + } + }, { + key: "type", + get: function get() { + return this._nativeBiquadFilterNode.type; + }, + set: function set(value) { + this._nativeBiquadFilterNode.type = value; + } + }, { + key: "getFrequencyResponse", + value: function getFrequencyResponse(frequencyHz, magResponse, phaseResponse) { + // Bug #189: Safari does throw an InvalidStateError. + try { + this._nativeBiquadFilterNode.getFrequencyResponse(frequencyHz, magResponse, phaseResponse); + } catch (err) { + if (err.code === 11) { + throw createInvalidAccessError(); + } + throw err; + } + // Bug #68: Safari does not throw an error if the parameters differ in their length. + if (frequencyHz.length !== magResponse.length || magResponse.length !== phaseResponse.length) { + throw createInvalidAccessError(); + } + } + }]); + }(audioNodeConstructor); + }; + + var createBiquadFilterNodeRendererFactory = function createBiquadFilterNodeRendererFactory(connectAudioParam, createNativeBiquadFilterNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) { + return function () { + var renderedNativeBiquadFilterNodes = new WeakMap(); + var createBiquadFilterNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(proxy, nativeOfflineAudioContext) { + var nativeBiquadFilterNode, nativeBiquadFilterNodeIsOwnedByContext, options; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + nativeBiquadFilterNode = getNativeAudioNode(proxy); + /* + * If the initially used nativeBiquadFilterNode was not constructed on the same OfflineAudioContext it needs to be created + * again. + */ + nativeBiquadFilterNodeIsOwnedByContext = isOwnedByContext(nativeBiquadFilterNode, nativeOfflineAudioContext); + if (!nativeBiquadFilterNodeIsOwnedByContext) { + options = { + Q: nativeBiquadFilterNode.Q.value, + channelCount: nativeBiquadFilterNode.channelCount, + channelCountMode: nativeBiquadFilterNode.channelCountMode, + channelInterpretation: nativeBiquadFilterNode.channelInterpretation, + detune: nativeBiquadFilterNode.detune.value, + frequency: nativeBiquadFilterNode.frequency.value, + gain: nativeBiquadFilterNode.gain.value, + type: nativeBiquadFilterNode.type + }; + nativeBiquadFilterNode = createNativeBiquadFilterNode(nativeOfflineAudioContext, options); + } + renderedNativeBiquadFilterNodes.set(nativeOfflineAudioContext, nativeBiquadFilterNode); + if (nativeBiquadFilterNodeIsOwnedByContext) { + _context.next = 15; + break; + } + _context.next = 7; + return renderAutomation(nativeOfflineAudioContext, proxy.Q, nativeBiquadFilterNode.Q); + case 7: + _context.next = 9; + return renderAutomation(nativeOfflineAudioContext, proxy.detune, nativeBiquadFilterNode.detune); + case 9: + _context.next = 11; + return renderAutomation(nativeOfflineAudioContext, proxy.frequency, nativeBiquadFilterNode.frequency); + case 11: + _context.next = 13; + return renderAutomation(nativeOfflineAudioContext, proxy.gain, nativeBiquadFilterNode.gain); + case 13: + _context.next = 23; + break; + case 15: + _context.next = 17; + return connectAudioParam(nativeOfflineAudioContext, proxy.Q, nativeBiquadFilterNode.Q); + case 17: + _context.next = 19; + return connectAudioParam(nativeOfflineAudioContext, proxy.detune, nativeBiquadFilterNode.detune); + case 19: + _context.next = 21; + return connectAudioParam(nativeOfflineAudioContext, proxy.frequency, nativeBiquadFilterNode.frequency); + case 21: + _context.next = 23; + return connectAudioParam(nativeOfflineAudioContext, proxy.gain, nativeBiquadFilterNode.gain); + case 23: + _context.next = 25; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeBiquadFilterNode); + case 25: + return _context.abrupt("return", nativeBiquadFilterNode); + case 26: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createBiquadFilterNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeBiquadFilterNode = renderedNativeBiquadFilterNodes.get(nativeOfflineAudioContext); + if (renderedNativeBiquadFilterNode !== undefined) { + return Promise.resolve(renderedNativeBiquadFilterNode); + } + return createBiquadFilterNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + var createCacheTestResult = function createCacheTestResult(ongoingTests, testResults) { + return function (tester, test) { + var cachedTestResult = testResults.get(tester); + if (cachedTestResult !== undefined) { + return cachedTestResult; + } + var ongoingTest = ongoingTests.get(tester); + if (ongoingTest !== undefined) { + return ongoingTest; + } + try { + var synchronousTestResult = test(); + if (synchronousTestResult instanceof Promise) { + ongoingTests.set(tester, synchronousTestResult); + return synchronousTestResult["catch"](function () { + return false; + }).then(function (finalTestResult) { + ongoingTests["delete"](tester); + testResults.set(tester, finalTestResult); + return finalTestResult; + }); + } + testResults.set(tester, synchronousTestResult); + return synchronousTestResult; + } catch (_unused) { + testResults.set(tester, false); + return false; + } + }; + }; + + function ownKeys$p(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$p(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$p(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$p(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$j(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$j() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$j() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$j = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$f = { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'speakers', + numberOfInputs: 6 + }; + var createChannelMergerNodeConstructor = function createChannelMergerNodeConstructor(audioNodeConstructor, createChannelMergerNodeRenderer, createNativeChannelMergerNode, getNativeContext, isNativeOfflineAudioContext) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function ChannelMergerNode(context, options) { + _classCallCheck(this, ChannelMergerNode); + var nativeContext = getNativeContext(context); + var mergedOptions = _objectSpread$p(_objectSpread$p({}, DEFAULT_OPTIONS$f), options); + var nativeChannelMergerNode = createNativeChannelMergerNode(nativeContext, mergedOptions); + var channelMergerNodeRenderer = isNativeOfflineAudioContext(nativeContext) ? createChannelMergerNodeRenderer() : null; + return _callSuper$j(this, ChannelMergerNode, [context, false, nativeChannelMergerNode, channelMergerNodeRenderer]); + } + _inherits(ChannelMergerNode, _audioNodeConstructor); + return _createClass(ChannelMergerNode); + }(audioNodeConstructor); + }; + + var createChannelMergerNodeRendererFactory = function createChannelMergerNodeRendererFactory(createNativeChannelMergerNode, getNativeAudioNode, renderInputsOfAudioNode) { + return function () { + var renderedNativeAudioNodes = new WeakMap(); + var createAudioNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(proxy, nativeOfflineAudioContext) { + var nativeAudioNode, nativeAudioNodeIsOwnedByContext, options; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + nativeAudioNode = getNativeAudioNode(proxy); // If the initially used nativeAudioNode was not constructed on the same OfflineAudioContext it needs to be created again. + nativeAudioNodeIsOwnedByContext = isOwnedByContext(nativeAudioNode, nativeOfflineAudioContext); + if (!nativeAudioNodeIsOwnedByContext) { + options = { + channelCount: nativeAudioNode.channelCount, + channelCountMode: nativeAudioNode.channelCountMode, + channelInterpretation: nativeAudioNode.channelInterpretation, + numberOfInputs: nativeAudioNode.numberOfInputs + }; + nativeAudioNode = createNativeChannelMergerNode(nativeOfflineAudioContext, options); + } + renderedNativeAudioNodes.set(nativeOfflineAudioContext, nativeAudioNode); + _context.next = 6; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAudioNode); + case 6: + return _context.abrupt("return", nativeAudioNode); + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createAudioNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeAudioNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext); + if (renderedNativeAudioNode !== undefined) { + return Promise.resolve(renderedNativeAudioNode); + } + return createAudioNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + function ownKeys$o(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$o(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$o(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$o(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$i(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$i() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$i() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$i = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$e = { + channelCount: 6, + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + numberOfOutputs: 6 + }; + var createChannelSplitterNodeConstructor = function createChannelSplitterNodeConstructor(audioNodeConstructor, createChannelSplitterNodeRenderer, createNativeChannelSplitterNode, getNativeContext, isNativeOfflineAudioContext, sanitizeChannelSplitterOptions) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function ChannelSplitterNode(context, options) { + _classCallCheck(this, ChannelSplitterNode); + var nativeContext = getNativeContext(context); + var mergedOptions = sanitizeChannelSplitterOptions(_objectSpread$o(_objectSpread$o({}, DEFAULT_OPTIONS$e), options)); + var nativeChannelSplitterNode = createNativeChannelSplitterNode(nativeContext, mergedOptions); + var channelSplitterNodeRenderer = isNativeOfflineAudioContext(nativeContext) ? createChannelSplitterNodeRenderer() : null; + return _callSuper$i(this, ChannelSplitterNode, [context, false, nativeChannelSplitterNode, channelSplitterNodeRenderer]); + } + _inherits(ChannelSplitterNode, _audioNodeConstructor); + return _createClass(ChannelSplitterNode); + }(audioNodeConstructor); + }; + + var createChannelSplitterNodeRendererFactory = function createChannelSplitterNodeRendererFactory(createNativeChannelSplitterNode, getNativeAudioNode, renderInputsOfAudioNode) { + return function () { + var renderedNativeAudioNodes = new WeakMap(); + var createAudioNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(proxy, nativeOfflineAudioContext) { + var nativeAudioNode, nativeAudioNodeIsOwnedByContext, options; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + nativeAudioNode = getNativeAudioNode(proxy); // If the initially used nativeAudioNode was not constructed on the same OfflineAudioContext it needs to be created again. + nativeAudioNodeIsOwnedByContext = isOwnedByContext(nativeAudioNode, nativeOfflineAudioContext); + if (!nativeAudioNodeIsOwnedByContext) { + options = { + channelCount: nativeAudioNode.channelCount, + channelCountMode: nativeAudioNode.channelCountMode, + channelInterpretation: nativeAudioNode.channelInterpretation, + numberOfOutputs: nativeAudioNode.numberOfOutputs + }; + nativeAudioNode = createNativeChannelSplitterNode(nativeOfflineAudioContext, options); + } + renderedNativeAudioNodes.set(nativeOfflineAudioContext, nativeAudioNode); + _context.next = 6; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeAudioNode); + case 6: + return _context.abrupt("return", nativeAudioNode); + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createAudioNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeAudioNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext); + if (renderedNativeAudioNode !== undefined) { + return Promise.resolve(renderedNativeAudioNode); + } + return createAudioNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + var createConnectAudioParam = function createConnectAudioParam(renderInputsOfAudioParam) { + return function (nativeOfflineAudioContext, audioParam, nativeAudioParam) { + return renderInputsOfAudioParam(audioParam, nativeOfflineAudioContext, nativeAudioParam); + }; + }; + + var createConnectMultipleOutputs = function createConnectMultipleOutputs(createIndexSizeError) { + return function (outputAudioNodes, destination) { + var output = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var input = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var outputAudioNode = outputAudioNodes[output]; + if (outputAudioNode === undefined) { + throw createIndexSizeError(); + } + if (isNativeAudioNode$1(destination)) { + return outputAudioNode.connect(destination, 0, input); + } + return outputAudioNode.connect(destination, 0); + }; + }; + + var createConnectedNativeAudioBufferSourceNodeFactory = function createConnectedNativeAudioBufferSourceNodeFactory(createNativeAudioBufferSourceNode) { + return function (nativeContext, nativeAudioNode) { + var nativeAudioBufferSourceNode = createNativeAudioBufferSourceNode(nativeContext, { + buffer: null, + channelCount: 2, + channelCountMode: 'max', + channelInterpretation: 'speakers', + loop: false, + loopEnd: 0, + loopStart: 0, + playbackRate: 1 + }); + var nativeAudioBuffer = nativeContext.createBuffer(1, 2, 44100); + nativeAudioBufferSourceNode.buffer = nativeAudioBuffer; + nativeAudioBufferSourceNode.loop = true; + nativeAudioBufferSourceNode.connect(nativeAudioNode); + nativeAudioBufferSourceNode.start(); + return function () { + nativeAudioBufferSourceNode.stop(); + nativeAudioBufferSourceNode.disconnect(nativeAudioNode); + }; + }; + }; + + function ownKeys$n(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$n(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$n(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$n(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$h(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$h() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$h() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$h = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$d = { + channelCount: 2, + channelCountMode: 'max', + channelInterpretation: 'speakers', + offset: 1 + }; + var createConstantSourceNodeConstructor = function createConstantSourceNodeConstructor(audioNodeConstructor, createAudioParam, createConstantSourceNodeRendererFactory, createNativeConstantSourceNode, getNativeContext, isNativeOfflineAudioContext, wrapEventListener) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function ConstantSourceNode(context, options) { + var _this; + _classCallCheck(this, ConstantSourceNode); + var nativeContext = getNativeContext(context); + var mergedOptions = _objectSpread$n(_objectSpread$n({}, DEFAULT_OPTIONS$d), options); + var nativeConstantSourceNode = createNativeConstantSourceNode(nativeContext, mergedOptions); + var isOffline = isNativeOfflineAudioContext(nativeContext); + var constantSourceNodeRenderer = isOffline ? createConstantSourceNodeRendererFactory() : null; + _this = _callSuper$h(this, ConstantSourceNode, [context, false, nativeConstantSourceNode, constantSourceNodeRenderer]); + _this._constantSourceNodeRenderer = constantSourceNodeRenderer; + _this._nativeConstantSourceNode = nativeConstantSourceNode; + /* + * Bug #62 & #74: Safari does not support ConstantSourceNodes and does not export the correct values for maxValue and minValue + * for GainNodes. + */ + _this._offset = createAudioParam(_this, isOffline, nativeConstantSourceNode.offset, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT); + _this._onended = null; + return _this; + } + _inherits(ConstantSourceNode, _audioNodeConstructor); + return _createClass(ConstantSourceNode, [{ + key: "offset", + get: function get() { + return this._offset; + } + }, { + key: "onended", + get: function get() { + return this._onended; + }, + set: function set(value) { + var wrappedListener = typeof value === 'function' ? wrapEventListener(this, value) : null; + this._nativeConstantSourceNode.onended = wrappedListener; + var nativeOnEnded = this._nativeConstantSourceNode.onended; + this._onended = nativeOnEnded !== null && nativeOnEnded === wrappedListener ? value : nativeOnEnded; + } + }, { + key: "start", + value: function start() { + var _this2 = this; + var when = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + this._nativeConstantSourceNode.start(when); + if (this._constantSourceNodeRenderer !== null) { + this._constantSourceNodeRenderer.start = when; + } + if (this.context.state !== 'closed') { + setInternalStateToActive(this); + var _resetInternalStateToPassive = function resetInternalStateToPassive() { + _this2._nativeConstantSourceNode.removeEventListener('ended', _resetInternalStateToPassive); + if (isActiveAudioNode(_this2)) { + setInternalStateToPassive(_this2); + } + }; + this._nativeConstantSourceNode.addEventListener('ended', _resetInternalStateToPassive); + } + } + }, { + key: "stop", + value: function stop() { + var when = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + this._nativeConstantSourceNode.stop(when); + if (this._constantSourceNodeRenderer !== null) { + this._constantSourceNodeRenderer.stop = when; + } + } + }]); + }(audioNodeConstructor); + }; + + var createConstantSourceNodeRendererFactory = function createConstantSourceNodeRendererFactory(connectAudioParam, createNativeConstantSourceNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) { + return function () { + var renderedNativeConstantSourceNodes = new WeakMap(); + var start = null; + var stop = null; + var createConstantSourceNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(proxy, nativeOfflineAudioContext) { + var nativeConstantSourceNode, nativeConstantSourceNodeIsOwnedByContext, options; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + nativeConstantSourceNode = getNativeAudioNode(proxy); + /* + * If the initially used nativeConstantSourceNode was not constructed on the same OfflineAudioContext it needs to be created + * again. + */ + nativeConstantSourceNodeIsOwnedByContext = isOwnedByContext(nativeConstantSourceNode, nativeOfflineAudioContext); + if (!nativeConstantSourceNodeIsOwnedByContext) { + options = { + channelCount: nativeConstantSourceNode.channelCount, + channelCountMode: nativeConstantSourceNode.channelCountMode, + channelInterpretation: nativeConstantSourceNode.channelInterpretation, + offset: nativeConstantSourceNode.offset.value + }; + nativeConstantSourceNode = createNativeConstantSourceNode(nativeOfflineAudioContext, options); + if (start !== null) { + nativeConstantSourceNode.start(start); + } + if (stop !== null) { + nativeConstantSourceNode.stop(stop); + } + } + renderedNativeConstantSourceNodes.set(nativeOfflineAudioContext, nativeConstantSourceNode); + if (nativeConstantSourceNodeIsOwnedByContext) { + _context.next = 9; + break; + } + _context.next = 7; + return renderAutomation(nativeOfflineAudioContext, proxy.offset, nativeConstantSourceNode.offset); + case 7: + _context.next = 11; + break; + case 9: + _context.next = 11; + return connectAudioParam(nativeOfflineAudioContext, proxy.offset, nativeConstantSourceNode.offset); + case 11: + _context.next = 13; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeConstantSourceNode); + case 13: + return _context.abrupt("return", nativeConstantSourceNode); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createConstantSourceNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + set start(value) { + start = value; + }, + set stop(value) { + stop = value; + }, + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeConstantSourceNode = renderedNativeConstantSourceNodes.get(nativeOfflineAudioContext); + if (renderedNativeConstantSourceNode !== undefined) { + return Promise.resolve(renderedNativeConstantSourceNode); + } + return createConstantSourceNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + var createConvertNumberToUnsignedLong = function createConvertNumberToUnsignedLong(unit32Array) { + return function (value) { + unit32Array[0] = value; + return unit32Array[0]; + }; + }; + + function ownKeys$m(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$m(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$m(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$m(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$g(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$g() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$g() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$g = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$c = { + buffer: null, + channelCount: 2, + channelCountMode: 'clamped-max', + channelInterpretation: 'speakers', + disableNormalization: false + }; + var createConvolverNodeConstructor = function createConvolverNodeConstructor(audioNodeConstructor, createConvolverNodeRenderer, createNativeConvolverNode, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function ConvolverNode(context, options) { + var _this; + _classCallCheck(this, ConvolverNode); + var nativeContext = getNativeContext(context); + var mergedOptions = _objectSpread$m(_objectSpread$m({}, DEFAULT_OPTIONS$c), options); + var nativeConvolverNode = createNativeConvolverNode(nativeContext, mergedOptions); + var isOffline = isNativeOfflineAudioContext(nativeContext); + var convolverNodeRenderer = isOffline ? createConvolverNodeRenderer() : null; + _this = _callSuper$g(this, ConvolverNode, [context, false, nativeConvolverNode, convolverNodeRenderer]); + _this._isBufferNullified = false; + _this._nativeConvolverNode = nativeConvolverNode; + if (mergedOptions.buffer !== null) { + setAudioNodeTailTime(_this, mergedOptions.buffer.duration); + } + return _this; + } + _inherits(ConvolverNode, _audioNodeConstructor); + return _createClass(ConvolverNode, [{ + key: "buffer", + get: function get() { + if (this._isBufferNullified) { + return null; + } + return this._nativeConvolverNode.buffer; + }, + set: function set(value) { + this._nativeConvolverNode.buffer = value; + // Bug #115: Safari does not allow to set the buffer to null. + if (value === null && this._nativeConvolverNode.buffer !== null) { + var nativeContext = this._nativeConvolverNode.context; + this._nativeConvolverNode.buffer = nativeContext.createBuffer(1, 1, nativeContext.sampleRate); + this._isBufferNullified = true; + setAudioNodeTailTime(this, 0); + } else { + this._isBufferNullified = false; + setAudioNodeTailTime(this, this._nativeConvolverNode.buffer === null ? 0 : this._nativeConvolverNode.buffer.duration); + } + } + }, { + key: "normalize", + get: function get() { + return this._nativeConvolverNode.normalize; + }, + set: function set(value) { + this._nativeConvolverNode.normalize = value; + } + }]); + }(audioNodeConstructor); + }; + + var createConvolverNodeRendererFactory = function createConvolverNodeRendererFactory(createNativeConvolverNode, getNativeAudioNode, renderInputsOfAudioNode) { + return function () { + var renderedNativeConvolverNodes = new WeakMap(); + var createConvolverNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(proxy, nativeOfflineAudioContext) { + var nativeConvolverNode, nativeConvolverNodeIsOwnedByContext, options; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + nativeConvolverNode = getNativeAudioNode(proxy); // If the initially used nativeConvolverNode was not constructed on the same OfflineAudioContext it needs to be created again. + nativeConvolverNodeIsOwnedByContext = isOwnedByContext(nativeConvolverNode, nativeOfflineAudioContext); + if (!nativeConvolverNodeIsOwnedByContext) { + options = { + buffer: nativeConvolverNode.buffer, + channelCount: nativeConvolverNode.channelCount, + channelCountMode: nativeConvolverNode.channelCountMode, + channelInterpretation: nativeConvolverNode.channelInterpretation, + disableNormalization: !nativeConvolverNode.normalize + }; + nativeConvolverNode = createNativeConvolverNode(nativeOfflineAudioContext, options); + } + renderedNativeConvolverNodes.set(nativeOfflineAudioContext, nativeConvolverNode); + if (!isNativeAudioNodeFaker(nativeConvolverNode)) { + _context.next = 9; + break; + } + _context.next = 7; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeConvolverNode.inputs[0]); + case 7: + _context.next = 11; + break; + case 9: + _context.next = 11; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeConvolverNode); + case 11: + return _context.abrupt("return", nativeConvolverNode); + case 12: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createConvolverNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeConvolverNode = renderedNativeConvolverNodes.get(nativeOfflineAudioContext); + if (renderedNativeConvolverNode !== undefined) { + return Promise.resolve(renderedNativeConvolverNode); + } + return createConvolverNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + var createCreateNativeOfflineAudioContext = function createCreateNativeOfflineAudioContext(createNotSupportedError, nativeOfflineAudioContextConstructor) { + return function (numberOfChannels, length, sampleRate) { + if (nativeOfflineAudioContextConstructor === null) { + throw new Error('Missing the native OfflineAudioContext constructor.'); + } + try { + return new nativeOfflineAudioContextConstructor(numberOfChannels, length, sampleRate); + } catch (err) { + // Bug #143, #144 & #146: Safari throws a SyntaxError when numberOfChannels, length or sampleRate are invalid. + if (err.name === 'SyntaxError') { + throw createNotSupportedError(); + } + throw err; + } + }; + }; + + var createDataCloneError = function createDataCloneError() { + return new DOMException('', 'DataCloneError'); + }; + + var detachArrayBuffer = function detachArrayBuffer(arrayBuffer) { + var _MessageChannel = new MessageChannel(), + port1 = _MessageChannel.port1, + port2 = _MessageChannel.port2; + return new Promise(function (resolve) { + var closeAndResolve = function closeAndResolve() { + port2.onmessage = null; + port1.close(); + port2.close(); + resolve(); + }; + port2.onmessage = function () { + return closeAndResolve(); + }; + try { + port1.postMessage(arrayBuffer, [arrayBuffer]); + } catch (_unused) { + // Ignore errors. + } finally { + closeAndResolve(); + } + }); + }; + + var createDecodeAudioData = function createDecodeAudioData(audioBufferStore, cacheTestResult, createDataCloneError, createEncodingError, detachedArrayBuffers, getNativeContext, isNativeContext, testAudioBufferCopyChannelMethodsOutOfBoundsSupport, testPromiseSupport, wrapAudioBufferCopyChannelMethods, wrapAudioBufferCopyChannelMethodsOutOfBounds) { + return function (anyContext, audioData) { + var nativeContext = isNativeContext(anyContext) ? anyContext : getNativeContext(anyContext); + // Bug #43: Only Chrome and Edge do throw a DataCloneError. + if (detachedArrayBuffers.has(audioData)) { + var err = createDataCloneError(); + return Promise.reject(err); + } + // The audioData parameter maybe of a type which can't be added to a WeakSet. + try { + detachedArrayBuffers.add(audioData); + } catch (_unused) { + // Ignore errors. + } + // Bug #21: Safari does not support promises yet. + if (cacheTestResult(testPromiseSupport, function () { + return testPromiseSupport(nativeContext); + })) { + return nativeContext.decodeAudioData(audioData).then(function (audioBuffer) { + // Bug #133: Safari does neuter the ArrayBuffer. + detachArrayBuffer(audioData)["catch"](function () { + // Ignore errors. + }); + // Bug #157: Firefox does not allow the bufferOffset to be out-of-bounds. + if (!cacheTestResult(testAudioBufferCopyChannelMethodsOutOfBoundsSupport, function () { + return testAudioBufferCopyChannelMethodsOutOfBoundsSupport(audioBuffer); + })) { + wrapAudioBufferCopyChannelMethodsOutOfBounds(audioBuffer); + } + audioBufferStore.add(audioBuffer); + return audioBuffer; + }); + } + // Bug #21: Safari does not return a Promise yet. + return new Promise(function (resolve, reject) { + var complete = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return detachArrayBuffer(audioData); + case 3: + _context.next = 7; + break; + case 5: + _context.prev = 5; + _context.t0 = _context["catch"](0); + case 7: + case "end": + return _context.stop(); + } + }, _callee, null, [[0, 5]]); + })); + return function complete() { + return _ref.apply(this, arguments); + }; + }(); + var fail = function fail(err) { + reject(err); + complete(); + }; + // Bug #26: Safari throws a synchronous error. + try { + // Bug #1: Safari requires a successCallback. + nativeContext.decodeAudioData(audioData, function (audioBuffer) { + // Bug #5: Safari does not support copyFromChannel() and copyToChannel(). + // Bug #100: Safari does throw a wrong error when calling getChannelData() with an out-of-bounds value. + if (typeof audioBuffer.copyFromChannel !== 'function') { + wrapAudioBufferCopyChannelMethods(audioBuffer); + wrapAudioBufferGetChannelDataMethod(audioBuffer); + } + audioBufferStore.add(audioBuffer); + complete().then(function () { + return resolve(audioBuffer); + }); + }, function (err) { + // Bug #4: Safari returns null instead of an error. + if (err === null) { + fail(createEncodingError()); + } else { + fail(err); + } + }); + } catch (err) { + fail(err); + } + }); + }; + }; + + function _createForOfIteratorHelper$3(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$3(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } + function _unsupportedIterableToArray$3(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$3(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$3(r, a) : void 0; } } + function _arrayLikeToArray$3(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } + var createDecrementCycleCounter = function createDecrementCycleCounter(connectNativeAudioNodeToNativeAudioNode, cycleCounters, getAudioNodeConnections, getNativeAudioNode, getNativeAudioParam, getNativeContext, isActiveAudioNode, isNativeOfflineAudioContext) { + return function (audioNode, count) { + var cycleCounter = cycleCounters.get(audioNode); + if (cycleCounter === undefined) { + throw new Error('Missing the expected cycle count.'); + } + var nativeContext = getNativeContext(audioNode.context); + var isOffline = isNativeOfflineAudioContext(nativeContext); + if (cycleCounter === count) { + cycleCounters["delete"](audioNode); + if (!isOffline && isActiveAudioNode(audioNode)) { + var nativeSourceAudioNode = getNativeAudioNode(audioNode); + var _getAudioNodeConnecti = getAudioNodeConnections(audioNode), + outputs = _getAudioNodeConnecti.outputs; + var _iterator = _createForOfIteratorHelper$3(outputs), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var output = _step.value; + if (isAudioNodeOutputConnection(output)) { + var nativeDestinationAudioNode = getNativeAudioNode(output[0]); + connectNativeAudioNodeToNativeAudioNode(nativeSourceAudioNode, nativeDestinationAudioNode, output[1], output[2]); + } else { + var nativeDestinationAudioParam = getNativeAudioParam(output[0]); + nativeSourceAudioNode.connect(nativeDestinationAudioParam, output[1]); + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + } + } else { + cycleCounters.set(audioNode, cycleCounter - count); + } + }; + }; + + function ownKeys$l(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$l(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$l(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$l(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$f(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$f() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$f() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$f = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$b = { + channelCount: 2, + channelCountMode: 'max', + channelInterpretation: 'speakers', + delayTime: 0, + maxDelayTime: 1 + }; + var createDelayNodeConstructor = function createDelayNodeConstructor(audioNodeConstructor, createAudioParam, createDelayNodeRenderer, createNativeDelayNode, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function DelayNode(context, options) { + var _this; + _classCallCheck(this, DelayNode); + var nativeContext = getNativeContext(context); + var mergedOptions = _objectSpread$l(_objectSpread$l({}, DEFAULT_OPTIONS$b), options); + var nativeDelayNode = createNativeDelayNode(nativeContext, mergedOptions); + var isOffline = isNativeOfflineAudioContext(nativeContext); + var delayNodeRenderer = isOffline ? createDelayNodeRenderer(mergedOptions.maxDelayTime) : null; + _this = _callSuper$f(this, DelayNode, [context, false, nativeDelayNode, delayNodeRenderer]); + _this._delayTime = createAudioParam(_this, isOffline, nativeDelayNode.delayTime); + setAudioNodeTailTime(_this, mergedOptions.maxDelayTime); + return _this; + } + _inherits(DelayNode, _audioNodeConstructor); + return _createClass(DelayNode, [{ + key: "delayTime", + get: function get() { + return this._delayTime; + } + }]); + }(audioNodeConstructor); + }; + + var createDelayNodeRendererFactory = function createDelayNodeRendererFactory(connectAudioParam, createNativeDelayNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) { + return function (maxDelayTime) { + var renderedNativeDelayNodes = new WeakMap(); + var createDelayNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(proxy, nativeOfflineAudioContext) { + var nativeDelayNode, nativeDelayNodeIsOwnedByContext, options; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + nativeDelayNode = getNativeAudioNode(proxy); // If the initially used nativeDelayNode was not constructed on the same OfflineAudioContext it needs to be created again. + nativeDelayNodeIsOwnedByContext = isOwnedByContext(nativeDelayNode, nativeOfflineAudioContext); + if (!nativeDelayNodeIsOwnedByContext) { + options = { + channelCount: nativeDelayNode.channelCount, + channelCountMode: nativeDelayNode.channelCountMode, + channelInterpretation: nativeDelayNode.channelInterpretation, + delayTime: nativeDelayNode.delayTime.value, + maxDelayTime: maxDelayTime + }; + nativeDelayNode = createNativeDelayNode(nativeOfflineAudioContext, options); + } + renderedNativeDelayNodes.set(nativeOfflineAudioContext, nativeDelayNode); + if (nativeDelayNodeIsOwnedByContext) { + _context.next = 9; + break; + } + _context.next = 7; + return renderAutomation(nativeOfflineAudioContext, proxy.delayTime, nativeDelayNode.delayTime); + case 7: + _context.next = 11; + break; + case 9: + _context.next = 11; + return connectAudioParam(nativeOfflineAudioContext, proxy.delayTime, nativeDelayNode.delayTime); + case 11: + _context.next = 13; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeDelayNode); + case 13: + return _context.abrupt("return", nativeDelayNode); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createDelayNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeDelayNode = renderedNativeDelayNodes.get(nativeOfflineAudioContext); + if (renderedNativeDelayNode !== undefined) { + return Promise.resolve(renderedNativeDelayNode); + } + return createDelayNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + var createDeleteActiveInputConnectionToAudioNode = function createDeleteActiveInputConnectionToAudioNode(pickElementFromSet) { + return function (activeInputs, source, output, input) { + return pickElementFromSet(activeInputs[input], function (activeInputConnection) { + return activeInputConnection[0] === source && activeInputConnection[1] === output; + }); + }; + }; + + var createDeleteUnrenderedAudioWorkletNode = function createDeleteUnrenderedAudioWorkletNode(getUnrenderedAudioWorkletNodes) { + return function (nativeContext, audioWorkletNode) { + getUnrenderedAudioWorkletNodes(nativeContext)["delete"](audioWorkletNode); + }; + }; + + var isDelayNode = function isDelayNode(audioNode) { + return 'delayTime' in audioNode; + }; + + var createDetectCycles = function createDetectCycles(audioParamAudioNodeStore, getAudioNodeConnections, getValueForKey) { + return function detectCycles(chain, nextLink) { + var audioNode = isAudioNode(nextLink) ? nextLink : getValueForKey(audioParamAudioNodeStore, nextLink); + if (isDelayNode(audioNode)) { + return []; + } + if (chain[0] === audioNode) { + return [chain]; + } + if (chain.includes(audioNode)) { + return []; + } + var _getAudioNodeConnecti = getAudioNodeConnections(audioNode), + outputs = _getAudioNodeConnecti.outputs; + return Array.from(outputs).map(function (outputConnection) { + return detectCycles([].concat(_toConsumableArray(chain), [audioNode]), outputConnection[0]); + }).reduce(function (mergedCycles, nestedCycles) { + return mergedCycles.concat(nestedCycles); + }, []); + }; + }; + + var getOutputAudioNodeAtIndex = function getOutputAudioNodeAtIndex(createIndexSizeError, outputAudioNodes, output) { + var outputAudioNode = outputAudioNodes[output]; + if (outputAudioNode === undefined) { + throw createIndexSizeError(); + } + return outputAudioNode; + }; + var createDisconnectMultipleOutputs = function createDisconnectMultipleOutputs(createIndexSizeError) { + return function (outputAudioNodes) { + var destinationOrOutput = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + var output = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; + var input = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + if (destinationOrOutput === undefined) { + return outputAudioNodes.forEach(function (outputAudioNode) { + return outputAudioNode.disconnect(); + }); + } + if (typeof destinationOrOutput === 'number') { + return getOutputAudioNodeAtIndex(createIndexSizeError, outputAudioNodes, destinationOrOutput).disconnect(); + } + if (isNativeAudioNode$1(destinationOrOutput)) { + if (output === undefined) { + return outputAudioNodes.forEach(function (outputAudioNode) { + return outputAudioNode.disconnect(destinationOrOutput); + }); + } + if (input === undefined) { + return getOutputAudioNodeAtIndex(createIndexSizeError, outputAudioNodes, output).disconnect(destinationOrOutput, 0); + } + return getOutputAudioNodeAtIndex(createIndexSizeError, outputAudioNodes, output).disconnect(destinationOrOutput, 0, input); + } + if (output === undefined) { + return outputAudioNodes.forEach(function (outputAudioNode) { + return outputAudioNode.disconnect(destinationOrOutput); + }); + } + return getOutputAudioNodeAtIndex(createIndexSizeError, outputAudioNodes, output).disconnect(destinationOrOutput, 0); + }; + }; + + function ownKeys$k(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$k(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$k(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$k(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$e(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$e() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$e() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$e = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$a = { + attack: 0.003, + channelCount: 2, + channelCountMode: 'clamped-max', + channelInterpretation: 'speakers', + knee: 30, + ratio: 12, + release: 0.25, + threshold: -24 + }; + var createDynamicsCompressorNodeConstructor = function createDynamicsCompressorNodeConstructor(audioNodeConstructor, createAudioParam, createDynamicsCompressorNodeRenderer, createNativeDynamicsCompressorNode, createNotSupportedError, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function DynamicsCompressorNode(context, options) { + var _this; + _classCallCheck(this, DynamicsCompressorNode); + var nativeContext = getNativeContext(context); + var mergedOptions = _objectSpread$k(_objectSpread$k({}, DEFAULT_OPTIONS$a), options); + var nativeDynamicsCompressorNode = createNativeDynamicsCompressorNode(nativeContext, mergedOptions); + var isOffline = isNativeOfflineAudioContext(nativeContext); + var dynamicsCompressorNodeRenderer = isOffline ? createDynamicsCompressorNodeRenderer() : null; + _this = _callSuper$e(this, DynamicsCompressorNode, [context, false, nativeDynamicsCompressorNode, dynamicsCompressorNodeRenderer]); + _this._attack = createAudioParam(_this, isOffline, nativeDynamicsCompressorNode.attack); + _this._knee = createAudioParam(_this, isOffline, nativeDynamicsCompressorNode.knee); + _this._nativeDynamicsCompressorNode = nativeDynamicsCompressorNode; + _this._ratio = createAudioParam(_this, isOffline, nativeDynamicsCompressorNode.ratio); + _this._release = createAudioParam(_this, isOffline, nativeDynamicsCompressorNode.release); + _this._threshold = createAudioParam(_this, isOffline, nativeDynamicsCompressorNode.threshold); + setAudioNodeTailTime(_this, 0.006); + return _this; + } + _inherits(DynamicsCompressorNode, _audioNodeConstructor); + return _createClass(DynamicsCompressorNode, [{ + key: "attack", + get: function get() { + return this._attack; + } + // Bug #108: Safari allows a channelCount of three and above which is why the getter and setter needs to be overwritten here. + }, { + key: "channelCount", + get: function get() { + return this._nativeDynamicsCompressorNode.channelCount; + }, + set: function set(value) { + var previousChannelCount = this._nativeDynamicsCompressorNode.channelCount; + this._nativeDynamicsCompressorNode.channelCount = value; + if (value > 2) { + this._nativeDynamicsCompressorNode.channelCount = previousChannelCount; + throw createNotSupportedError(); + } + } + /* + * Bug #109: Only Chrome and Firefox disallow a channelCountMode of 'max' yet which is why the getter and setter needs to be + * overwritten here. + */ + }, { + key: "channelCountMode", + get: function get() { + return this._nativeDynamicsCompressorNode.channelCountMode; + }, + set: function set(value) { + var previousChannelCount = this._nativeDynamicsCompressorNode.channelCountMode; + this._nativeDynamicsCompressorNode.channelCountMode = value; + if (value === 'max') { + this._nativeDynamicsCompressorNode.channelCountMode = previousChannelCount; + throw createNotSupportedError(); + } + } + }, { + key: "knee", + get: function get() { + return this._knee; + } + }, { + key: "ratio", + get: function get() { + return this._ratio; + } + }, { + key: "reduction", + get: function get() { + // Bug #111: Safari returns an AudioParam instead of a number. + if (typeof this._nativeDynamicsCompressorNode.reduction.value === 'number') { + return this._nativeDynamicsCompressorNode.reduction.value; + } + return this._nativeDynamicsCompressorNode.reduction; + } + }, { + key: "release", + get: function get() { + return this._release; + } + }, { + key: "threshold", + get: function get() { + return this._threshold; + } + }]); + }(audioNodeConstructor); + }; + + var createDynamicsCompressorNodeRendererFactory = function createDynamicsCompressorNodeRendererFactory(connectAudioParam, createNativeDynamicsCompressorNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) { + return function () { + var renderedNativeDynamicsCompressorNodes = new WeakMap(); + var createDynamicsCompressorNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(proxy, nativeOfflineAudioContext) { + var nativeDynamicsCompressorNode, nativeDynamicsCompressorNodeIsOwnedByContext, options; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + nativeDynamicsCompressorNode = getNativeAudioNode(proxy); + /* + * If the initially used nativeDynamicsCompressorNode was not constructed on the same OfflineAudioContext it needs to be + * created again. + */ + nativeDynamicsCompressorNodeIsOwnedByContext = isOwnedByContext(nativeDynamicsCompressorNode, nativeOfflineAudioContext); + if (!nativeDynamicsCompressorNodeIsOwnedByContext) { + options = { + attack: nativeDynamicsCompressorNode.attack.value, + channelCount: nativeDynamicsCompressorNode.channelCount, + channelCountMode: nativeDynamicsCompressorNode.channelCountMode, + channelInterpretation: nativeDynamicsCompressorNode.channelInterpretation, + knee: nativeDynamicsCompressorNode.knee.value, + ratio: nativeDynamicsCompressorNode.ratio.value, + release: nativeDynamicsCompressorNode.release.value, + threshold: nativeDynamicsCompressorNode.threshold.value + }; + nativeDynamicsCompressorNode = createNativeDynamicsCompressorNode(nativeOfflineAudioContext, options); + } + renderedNativeDynamicsCompressorNodes.set(nativeOfflineAudioContext, nativeDynamicsCompressorNode); + if (nativeDynamicsCompressorNodeIsOwnedByContext) { + _context.next = 17; + break; + } + _context.next = 7; + return renderAutomation(nativeOfflineAudioContext, proxy.attack, nativeDynamicsCompressorNode.attack); + case 7: + _context.next = 9; + return renderAutomation(nativeOfflineAudioContext, proxy.knee, nativeDynamicsCompressorNode.knee); + case 9: + _context.next = 11; + return renderAutomation(nativeOfflineAudioContext, proxy.ratio, nativeDynamicsCompressorNode.ratio); + case 11: + _context.next = 13; + return renderAutomation(nativeOfflineAudioContext, proxy.release, nativeDynamicsCompressorNode.release); + case 13: + _context.next = 15; + return renderAutomation(nativeOfflineAudioContext, proxy.threshold, nativeDynamicsCompressorNode.threshold); + case 15: + _context.next = 27; + break; + case 17: + _context.next = 19; + return connectAudioParam(nativeOfflineAudioContext, proxy.attack, nativeDynamicsCompressorNode.attack); + case 19: + _context.next = 21; + return connectAudioParam(nativeOfflineAudioContext, proxy.knee, nativeDynamicsCompressorNode.knee); + case 21: + _context.next = 23; + return connectAudioParam(nativeOfflineAudioContext, proxy.ratio, nativeDynamicsCompressorNode.ratio); + case 23: + _context.next = 25; + return connectAudioParam(nativeOfflineAudioContext, proxy.release, nativeDynamicsCompressorNode.release); + case 25: + _context.next = 27; + return connectAudioParam(nativeOfflineAudioContext, proxy.threshold, nativeDynamicsCompressorNode.threshold); + case 27: + _context.next = 29; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeDynamicsCompressorNode); + case 29: + return _context.abrupt("return", nativeDynamicsCompressorNode); + case 30: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createDynamicsCompressorNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeDynamicsCompressorNode = renderedNativeDynamicsCompressorNodes.get(nativeOfflineAudioContext); + if (renderedNativeDynamicsCompressorNode !== undefined) { + return Promise.resolve(renderedNativeDynamicsCompressorNode); + } + return createDynamicsCompressorNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + var createEncodingError = function createEncodingError() { + return new DOMException('', 'EncodingError'); + }; + + var createEvaluateSource = function createEvaluateSource(window) { + return function (source) { + return new Promise(function (resolve, reject) { + if (window === null) { + // Bug #182 Chrome and Edge do throw an instance of a SyntaxError instead of a DOMException. + reject(new SyntaxError()); + return; + } + var head = window.document.head; + if (head === null) { + // Bug #182 Chrome and Edge do throw an instance of a SyntaxError instead of a DOMException. + reject(new SyntaxError()); + } else { + var script = window.document.createElement('script'); + // @todo Safari doesn't like URLs with a type of 'application/javascript; charset=utf-8'. + var blob = new Blob([source], { + type: 'application/javascript' + }); + var url = URL.createObjectURL(blob); + var originalOnErrorHandler = window.onerror; + var removeErrorEventListenerAndRevokeUrl = function removeErrorEventListenerAndRevokeUrl() { + window.onerror = originalOnErrorHandler; + URL.revokeObjectURL(url); + }; + window.onerror = function (message, src, lineno, colno, error) { + // @todo Edge thinks the source is the one of the html document. + if (src === url || src === window.location.href && lineno === 1 && colno === 1) { + removeErrorEventListenerAndRevokeUrl(); + reject(error); + return false; + } + if (originalOnErrorHandler !== null) { + return originalOnErrorHandler(message, src, lineno, colno, error); + } + }; + script.onerror = function () { + removeErrorEventListenerAndRevokeUrl(); + // Bug #182 Chrome and Edge do throw an instance of a SyntaxError instead of a DOMException. + reject(new SyntaxError()); + }; + script.onload = function () { + removeErrorEventListenerAndRevokeUrl(); + resolve(); + }; + script.src = url; + script.type = 'module'; + head.appendChild(script); + } + }); + }; + }; + + var createEventTargetConstructor = function createEventTargetConstructor(wrapEventListener) { + return /*#__PURE__*/function () { + function EventTarget(_nativeEventTarget) { + _classCallCheck(this, EventTarget); + this._nativeEventTarget = _nativeEventTarget; + this._listeners = new WeakMap(); + } + return _createClass(EventTarget, [{ + key: "addEventListener", + value: function addEventListener(type, listener, options) { + if (listener !== null) { + var wrappedEventListener = this._listeners.get(listener); + if (wrappedEventListener === undefined) { + wrappedEventListener = wrapEventListener(this, listener); + if (typeof listener === 'function') { + this._listeners.set(listener, wrappedEventListener); + } + } + this._nativeEventTarget.addEventListener(type, wrappedEventListener, options); + } + } + }, { + key: "dispatchEvent", + value: function dispatchEvent(event) { + return this._nativeEventTarget.dispatchEvent(event); + } + }, { + key: "removeEventListener", + value: function removeEventListener(type, listener, options) { + var wrappedEventListener = listener === null ? undefined : this._listeners.get(listener); + this._nativeEventTarget.removeEventListener(type, wrappedEventListener === undefined ? null : wrappedEventListener, options); + } + }]); + }(); + }; + + var createExposeCurrentFrameAndCurrentTime = function createExposeCurrentFrameAndCurrentTime(window) { + return function (currentTime, sampleRate, fn) { + Object.defineProperties(window, { + currentFrame: { + configurable: true, + get: function get() { + return Math.round(currentTime * sampleRate); + } + }, + currentTime: { + configurable: true, + get: function get() { + return currentTime; + } + } + }); + try { + return fn(); + } finally { + if (window !== null) { + delete window.currentFrame; + delete window.currentTime; + } + } + }; + }; + + var createFetchSource = function createFetchSource(createAbortError) { + return /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(url) { + var response; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return fetch(url); + case 3: + response = _context.sent; + if (!response.ok) { + _context.next = 10; + break; + } + _context.next = 7; + return response.text(); + case 7: + _context.t0 = _context.sent; + _context.t1 = response.url; + return _context.abrupt("return", [_context.t0, _context.t1]); + case 10: + _context.next = 14; + break; + case 12: + _context.prev = 12; + _context.t2 = _context["catch"](0); + case 14: + throw createAbortError(); + case 15: + case "end": + return _context.stop(); + } + }, _callee, null, [[0, 12]]); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }(); + }; + + function ownKeys$j(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$j(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$j(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$j(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$d(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$d() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$d() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$d = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$9 = { + channelCount: 2, + channelCountMode: 'max', + channelInterpretation: 'speakers', + gain: 1 + }; + var createGainNodeConstructor = function createGainNodeConstructor(audioNodeConstructor, createAudioParam, createGainNodeRenderer, createNativeGainNode, getNativeContext, isNativeOfflineAudioContext) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function GainNode(context, options) { + var _this; + _classCallCheck(this, GainNode); + var nativeContext = getNativeContext(context); + var mergedOptions = _objectSpread$j(_objectSpread$j({}, DEFAULT_OPTIONS$9), options); + var nativeGainNode = createNativeGainNode(nativeContext, mergedOptions); + var isOffline = isNativeOfflineAudioContext(nativeContext); + var gainNodeRenderer = isOffline ? createGainNodeRenderer() : null; + _this = _callSuper$d(this, GainNode, [context, false, nativeGainNode, gainNodeRenderer]); + // Bug #74: Safari does not export the correct values for maxValue and minValue. + _this._gain = createAudioParam(_this, isOffline, nativeGainNode.gain, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT); + return _this; + } + _inherits(GainNode, _audioNodeConstructor); + return _createClass(GainNode, [{ + key: "gain", + get: function get() { + return this._gain; + } + }]); + }(audioNodeConstructor); + }; + + var createGainNodeRendererFactory = function createGainNodeRendererFactory(connectAudioParam, createNativeGainNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) { + return function () { + var renderedNativeGainNodes = new WeakMap(); + var createGainNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(proxy, nativeOfflineAudioContext) { + var nativeGainNode, nativeGainNodeIsOwnedByContext, options; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + nativeGainNode = getNativeAudioNode(proxy); // If the initially used nativeGainNode was not constructed on the same OfflineAudioContext it needs to be created again. + nativeGainNodeIsOwnedByContext = isOwnedByContext(nativeGainNode, nativeOfflineAudioContext); + if (!nativeGainNodeIsOwnedByContext) { + options = { + channelCount: nativeGainNode.channelCount, + channelCountMode: nativeGainNode.channelCountMode, + channelInterpretation: nativeGainNode.channelInterpretation, + gain: nativeGainNode.gain.value + }; + nativeGainNode = createNativeGainNode(nativeOfflineAudioContext, options); + } + renderedNativeGainNodes.set(nativeOfflineAudioContext, nativeGainNode); + if (nativeGainNodeIsOwnedByContext) { + _context.next = 9; + break; + } + _context.next = 7; + return renderAutomation(nativeOfflineAudioContext, proxy.gain, nativeGainNode.gain); + case 7: + _context.next = 11; + break; + case 9: + _context.next = 11; + return connectAudioParam(nativeOfflineAudioContext, proxy.gain, nativeGainNode.gain); + case 11: + _context.next = 13; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeGainNode); + case 13: + return _context.abrupt("return", nativeGainNode); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createGainNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeGainNode = renderedNativeGainNodes.get(nativeOfflineAudioContext); + if (renderedNativeGainNode !== undefined) { + return Promise.resolve(renderedNativeGainNode); + } + return createGainNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + var createGetActiveAudioWorkletNodeInputs = function createGetActiveAudioWorkletNodeInputs(activeAudioWorkletNodeInputsStore, getValueForKey) { + return function (nativeAudioWorkletNode) { + return getValueForKey(activeAudioWorkletNodeInputsStore, nativeAudioWorkletNode); + }; + }; + + var createGetAudioNodeRenderer = function createGetAudioNodeRenderer(getAudioNodeConnections) { + return function (audioNode) { + var audioNodeConnections = getAudioNodeConnections(audioNode); + if (audioNodeConnections.renderer === null) { + throw new Error('Missing the renderer of the given AudioNode in the audio graph.'); + } + return audioNodeConnections.renderer; + }; + }; + + var createGetAudioNodeTailTime = function createGetAudioNodeTailTime(audioNodeTailTimeStore) { + return function (audioNode) { + var _a; + return (_a = audioNodeTailTimeStore.get(audioNode)) !== null && _a !== void 0 ? _a : 0; + }; + }; + + var createGetAudioParamRenderer = function createGetAudioParamRenderer(getAudioParamConnections) { + return function (audioParam) { + var audioParamConnections = getAudioParamConnections(audioParam); + if (audioParamConnections.renderer === null) { + throw new Error('Missing the renderer of the given AudioParam in the audio graph.'); + } + return audioParamConnections.renderer; + }; + }; + + var createGetBackupOfflineAudioContext = function createGetBackupOfflineAudioContext(backupOfflineAudioContextStore) { + return function (nativeContext) { + return backupOfflineAudioContextStore.get(nativeContext); + }; + }; + + var createInvalidStateError = function createInvalidStateError() { + return new DOMException('', 'InvalidStateError'); + }; + + var createGetNativeContext = function createGetNativeContext(contextStore) { + return function (context) { + var nativeContext = contextStore.get(context); + if (nativeContext === undefined) { + throw createInvalidStateError(); + } + return nativeContext; + }; + }; + + var createGetOrCreateBackupOfflineAudioContext = function createGetOrCreateBackupOfflineAudioContext(backupOfflineAudioContextStore, nativeOfflineAudioContextConstructor) { + return function (nativeContext) { + var backupOfflineAudioContext = backupOfflineAudioContextStore.get(nativeContext); + if (backupOfflineAudioContext !== undefined) { + return backupOfflineAudioContext; + } + if (nativeOfflineAudioContextConstructor === null) { + throw new Error('Missing the native OfflineAudioContext constructor.'); + } + // Bug #141: Safari does not support creating an OfflineAudioContext with less than 44100 Hz. + backupOfflineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100); + backupOfflineAudioContextStore.set(nativeContext, backupOfflineAudioContext); + return backupOfflineAudioContext; + }; + }; + + var createGetUnrenderedAudioWorkletNodes = function createGetUnrenderedAudioWorkletNodes(unrenderedAudioWorkletNodeStore) { + return function (nativeContext) { + var unrenderedAudioWorkletNodes = unrenderedAudioWorkletNodeStore.get(nativeContext); + if (unrenderedAudioWorkletNodes === undefined) { + throw new Error('The context has no set of AudioWorkletNodes.'); + } + return unrenderedAudioWorkletNodes; + }; + }; + + var createInvalidAccessError = function createInvalidAccessError() { + return new DOMException('', 'InvalidAccessError'); + }; + + var wrapIIRFilterNodeGetFrequencyResponseMethod = function wrapIIRFilterNodeGetFrequencyResponseMethod(nativeIIRFilterNode) { + nativeIIRFilterNode.getFrequencyResponse = function (getFrequencyResponse) { + return function (frequencyHz, magResponse, phaseResponse) { + if (frequencyHz.length !== magResponse.length || magResponse.length !== phaseResponse.length) { + throw createInvalidAccessError(); + } + return getFrequencyResponse.call(nativeIIRFilterNode, frequencyHz, magResponse, phaseResponse); + }; + }(nativeIIRFilterNode.getFrequencyResponse); + }; + + function ownKeys$i(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$i(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$i(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$i(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$c(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$c() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$c() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$c = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$8 = { + channelCount: 2, + channelCountMode: 'max', + channelInterpretation: 'speakers' + }; + var createIIRFilterNodeConstructor = function createIIRFilterNodeConstructor(audioNodeConstructor, createNativeIIRFilterNode, createIIRFilterNodeRenderer, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function IIRFilterNode(context, options) { + var _this; + _classCallCheck(this, IIRFilterNode); + var nativeContext = getNativeContext(context); + var isOffline = isNativeOfflineAudioContext(nativeContext); + var mergedOptions = _objectSpread$i(_objectSpread$i({}, DEFAULT_OPTIONS$8), options); + var nativeIIRFilterNode = createNativeIIRFilterNode(nativeContext, isOffline ? null : context.baseLatency, mergedOptions); + var iirFilterNodeRenderer = isOffline ? createIIRFilterNodeRenderer(mergedOptions.feedback, mergedOptions.feedforward) : null; + _this = _callSuper$c(this, IIRFilterNode, [context, false, nativeIIRFilterNode, iirFilterNodeRenderer]); + // Bug #23 & #24: FirefoxDeveloper does not throw an InvalidAccessError. + // @todo Write a test which allows other browsers to remain unpatched. + wrapIIRFilterNodeGetFrequencyResponseMethod(nativeIIRFilterNode); + _this._nativeIIRFilterNode = nativeIIRFilterNode; + // @todo Determine a meaningful tail-time instead of just using one second. + setAudioNodeTailTime(_this, 1); + return _this; + } + _inherits(IIRFilterNode, _audioNodeConstructor); + return _createClass(IIRFilterNode, [{ + key: "getFrequencyResponse", + value: function getFrequencyResponse(frequencyHz, magResponse, phaseResponse) { + return this._nativeIIRFilterNode.getFrequencyResponse(frequencyHz, magResponse, phaseResponse); + } + }]); + }(audioNodeConstructor); + }; + + // This implementation as shamelessly inspired by source code of + // tslint:disable-next-line:max-line-length + // {@link https://chromium.googlesource.com/chromium/src.git/+/master/third_party/WebKit/Source/platform/audio/IIRFilter.cpp|Chromium's IIRFilter}. + var filterBuffer = function filterBuffer(feedback, feedbackLength, feedforward, feedforwardLength, minLength, xBuffer, yBuffer, bufferIndex, bufferLength, input, output) { + var inputLength = input.length; + var i = bufferIndex; + for (var j = 0; j < inputLength; j += 1) { + var y = feedforward[0] * input[j]; + for (var k = 1; k < minLength; k += 1) { + var x = i - k & bufferLength - 1; // tslint:disable-line:no-bitwise + y += feedforward[k] * xBuffer[x]; + y -= feedback[k] * yBuffer[x]; + } + for (var _k = minLength; _k < feedforwardLength; _k += 1) { + y += feedforward[_k] * xBuffer[i - _k & bufferLength - 1]; // tslint:disable-line:no-bitwise + } + for (var _k2 = minLength; _k2 < feedbackLength; _k2 += 1) { + y -= feedback[_k2] * yBuffer[i - _k2 & bufferLength - 1]; // tslint:disable-line:no-bitwise + } + xBuffer[i] = input[j]; + yBuffer[i] = y; + i = i + 1 & bufferLength - 1; // tslint:disable-line:no-bitwise + output[j] = y; + } + return i; + }; + + var filterFullBuffer = function filterFullBuffer(renderedBuffer, nativeOfflineAudioContext, feedback, feedforward) { + var convertedFeedback = feedback instanceof Float64Array ? feedback : new Float64Array(feedback); + var convertedFeedforward = feedforward instanceof Float64Array ? feedforward : new Float64Array(feedforward); + var feedbackLength = convertedFeedback.length; + var feedforwardLength = convertedFeedforward.length; + var minLength = Math.min(feedbackLength, feedforwardLength); + if (convertedFeedback[0] !== 1) { + for (var i = 0; i < feedbackLength; i += 1) { + convertedFeedforward[i] /= convertedFeedback[0]; + } + for (var _i = 1; _i < feedforwardLength; _i += 1) { + convertedFeedback[_i] /= convertedFeedback[0]; + } + } + var bufferLength = 32; + var xBuffer = new Float32Array(bufferLength); + var yBuffer = new Float32Array(bufferLength); + var filteredBuffer = nativeOfflineAudioContext.createBuffer(renderedBuffer.numberOfChannels, renderedBuffer.length, renderedBuffer.sampleRate); + var numberOfChannels = renderedBuffer.numberOfChannels; + for (var _i2 = 0; _i2 < numberOfChannels; _i2 += 1) { + var input = renderedBuffer.getChannelData(_i2); + var output = filteredBuffer.getChannelData(_i2); + xBuffer.fill(0); + yBuffer.fill(0); + filterBuffer(convertedFeedback, feedbackLength, convertedFeedforward, feedforwardLength, minLength, xBuffer, yBuffer, 0, bufferLength, input, output); + } + return filteredBuffer; + }; + var createIIRFilterNodeRendererFactory = function createIIRFilterNodeRendererFactory(createNativeAudioBufferSourceNode, getNativeAudioNode, nativeOfflineAudioContextConstructor, renderInputsOfAudioNode, renderNativeOfflineAudioContext) { + return function (feedback, feedforward) { + var renderedNativeAudioNodes = new WeakMap(); + var filteredBufferPromise = null; + var createAudioNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(proxy, nativeOfflineAudioContext) { + var nativeAudioBufferSourceNode, nativeIIRFilterNode, nativeIIRFilterNodeIsOwnedByContext, partialOfflineAudioContext, filteredBuffer; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + nativeAudioBufferSourceNode = null; + nativeIIRFilterNode = getNativeAudioNode(proxy); // If the initially used nativeIIRFilterNode was not constructed on the same OfflineAudioContext it needs to be created again. + nativeIIRFilterNodeIsOwnedByContext = isOwnedByContext(nativeIIRFilterNode, nativeOfflineAudioContext); // Bug #9: Safari does not support IIRFilterNodes. + if (nativeOfflineAudioContext.createIIRFilter === undefined) { + nativeAudioBufferSourceNode = createNativeAudioBufferSourceNode(nativeOfflineAudioContext, { + buffer: null, + channelCount: 2, + channelCountMode: 'max', + channelInterpretation: 'speakers', + loop: false, + loopEnd: 0, + loopStart: 0, + playbackRate: 1 + }); + } else if (!nativeIIRFilterNodeIsOwnedByContext) { + // @todo TypeScript defines the parameters of createIIRFilter() as arrays of numbers. + nativeIIRFilterNode = nativeOfflineAudioContext.createIIRFilter(feedforward, feedback); + } + renderedNativeAudioNodes.set(nativeOfflineAudioContext, nativeAudioBufferSourceNode === null ? nativeIIRFilterNode : nativeAudioBufferSourceNode); + if (!(nativeAudioBufferSourceNode !== null)) { + _context2.next = 17; + break; + } + if (!(filteredBufferPromise === null)) { + _context2.next = 11; + break; + } + if (!(nativeOfflineAudioContextConstructor === null)) { + _context2.next = 9; + break; + } + throw new Error('Missing the native OfflineAudioContext constructor.'); + case 9: + partialOfflineAudioContext = new nativeOfflineAudioContextConstructor( + // Bug #47: The AudioDestinationNode in Safari gets not initialized correctly. + proxy.context.destination.channelCount, + // Bug #17: Safari does not yet expose the length. + proxy.context.length, nativeOfflineAudioContext.sampleRate); + filteredBufferPromise = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var renderedBuffer; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return renderInputsOfAudioNode(proxy, partialOfflineAudioContext, partialOfflineAudioContext.destination); + case 2: + _context.next = 4; + return renderNativeOfflineAudioContext(partialOfflineAudioContext); + case 4: + renderedBuffer = _context.sent; + return _context.abrupt("return", filterFullBuffer(renderedBuffer, nativeOfflineAudioContext, feedback, feedforward)); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + }))(); + case 11: + _context2.next = 13; + return filteredBufferPromise; + case 13: + filteredBuffer = _context2.sent; + nativeAudioBufferSourceNode.buffer = filteredBuffer; + nativeAudioBufferSourceNode.start(0); + return _context2.abrupt("return", nativeAudioBufferSourceNode); + case 17: + _context2.next = 19; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeIIRFilterNode); + case 19: + return _context2.abrupt("return", nativeIIRFilterNode); + case 20: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function createAudioNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeAudioNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext); + if (renderedNativeAudioNode !== undefined) { + return Promise.resolve(renderedNativeAudioNode); + } + return createAudioNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + function _createForOfIteratorHelper$2(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$2(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } + function _unsupportedIterableToArray$2(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$2(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$2(r, a) : void 0; } } + function _arrayLikeToArray$2(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } + var createIncrementCycleCounterFactory = function createIncrementCycleCounterFactory(cycleCounters, disconnectNativeAudioNodeFromNativeAudioNode, getAudioNodeConnections, getNativeAudioNode, getNativeAudioParam, isActiveAudioNode) { + return function (isOffline) { + return function (audioNode, count) { + var cycleCounter = cycleCounters.get(audioNode); + if (cycleCounter === undefined) { + if (!isOffline && isActiveAudioNode(audioNode)) { + var nativeSourceAudioNode = getNativeAudioNode(audioNode); + var _getAudioNodeConnecti = getAudioNodeConnections(audioNode), + outputs = _getAudioNodeConnecti.outputs; + var _iterator = _createForOfIteratorHelper$2(outputs), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var output = _step.value; + if (isAudioNodeOutputConnection(output)) { + var nativeDestinationAudioNode = getNativeAudioNode(output[0]); + disconnectNativeAudioNodeFromNativeAudioNode(nativeSourceAudioNode, nativeDestinationAudioNode, output[1], output[2]); + } else { + var nativeDestinationAudioParam = getNativeAudioParam(output[0]); + nativeSourceAudioNode.disconnect(nativeDestinationAudioParam, output[1]); + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + } + cycleCounters.set(audioNode, count); + } else { + cycleCounters.set(audioNode, cycleCounter + count); + } + }; + }; + }; + + var createIsAnyAudioContext = function createIsAnyAudioContext(contextStore, isNativeAudioContext) { + return function (anything) { + var nativeContext = contextStore.get(anything); + return isNativeAudioContext(nativeContext) || isNativeAudioContext(anything); + }; + }; + + var createIsAnyAudioNode = function createIsAnyAudioNode(audioNodeStore, isNativeAudioNode) { + return function (anything) { + return audioNodeStore.has(anything) || isNativeAudioNode(anything); + }; + }; + + var createIsAnyAudioParam = function createIsAnyAudioParam(audioParamStore, isNativeAudioParam) { + return function (anything) { + return audioParamStore.has(anything) || isNativeAudioParam(anything); + }; + }; + + var createIsAnyOfflineAudioContext = function createIsAnyOfflineAudioContext(contextStore, isNativeOfflineAudioContext) { + return function (anything) { + var nativeContext = contextStore.get(anything); + return isNativeOfflineAudioContext(nativeContext) || isNativeOfflineAudioContext(anything); + }; + }; + + var createIsNativeAudioContext = function createIsNativeAudioContext(nativeAudioContextConstructor) { + return function (anything) { + return nativeAudioContextConstructor !== null && anything instanceof nativeAudioContextConstructor; + }; + }; + + var createIsNativeAudioNode = function createIsNativeAudioNode(window) { + return function (anything) { + return window !== null && typeof window.AudioNode === 'function' && anything instanceof window.AudioNode; + }; + }; + + var createIsNativeAudioParam = function createIsNativeAudioParam(window) { + return function (anything) { + return window !== null && typeof window.AudioParam === 'function' && anything instanceof window.AudioParam; + }; + }; + + var createIsNativeContext = function createIsNativeContext(isNativeAudioContext, isNativeOfflineAudioContext) { + return function (anything) { + return isNativeAudioContext(anything) || isNativeOfflineAudioContext(anything); + }; + }; + + var createIsNativeOfflineAudioContext = function createIsNativeOfflineAudioContext(nativeOfflineAudioContextConstructor) { + return function (anything) { + return nativeOfflineAudioContextConstructor !== null && anything instanceof nativeOfflineAudioContextConstructor; + }; + }; + + var createIsSecureContext = function createIsSecureContext(window) { + return window !== null && window.isSecureContext; + }; + + var createIsSupportedPromise = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(cacheTestResult, testAudioBufferCopyChannelMethodsSubarraySupport, testAudioContextCloseMethodSupport, testAudioContextDecodeAudioDataMethodTypeErrorSupport, testAudioContextOptionsSupport, testAudioNodeConnectMethodSupport, testAudioWorkletProcessorNoOutputsSupport, testChannelMergerNodeChannelCountSupport, testConstantSourceNodeAccurateSchedulingSupport, testConvolverNodeBufferReassignabilitySupport, testConvolverNodeChannelCountSupport, testDomExceptionContrucorSupport, testIsSecureContextSupport, testMediaStreamAudioSourceNodeMediaStreamWithoutAudioTrackSupport, testStereoPannerNodeDefaultValueSupport, testTransferablesSupport) { + var results; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!(cacheTestResult(testAudioBufferCopyChannelMethodsSubarraySupport, testAudioBufferCopyChannelMethodsSubarraySupport) && cacheTestResult(testAudioContextCloseMethodSupport, testAudioContextCloseMethodSupport) && cacheTestResult(testAudioContextOptionsSupport, testAudioContextOptionsSupport) && cacheTestResult(testAudioNodeConnectMethodSupport, testAudioNodeConnectMethodSupport) && cacheTestResult(testChannelMergerNodeChannelCountSupport, testChannelMergerNodeChannelCountSupport) && cacheTestResult(testConstantSourceNodeAccurateSchedulingSupport, testConstantSourceNodeAccurateSchedulingSupport) && cacheTestResult(testConvolverNodeBufferReassignabilitySupport, testConvolverNodeBufferReassignabilitySupport) && cacheTestResult(testConvolverNodeChannelCountSupport, testConvolverNodeChannelCountSupport) && cacheTestResult(testDomExceptionContrucorSupport, testDomExceptionContrucorSupport) && cacheTestResult(testIsSecureContextSupport, testIsSecureContextSupport) && cacheTestResult(testMediaStreamAudioSourceNodeMediaStreamWithoutAudioTrackSupport, testMediaStreamAudioSourceNodeMediaStreamWithoutAudioTrackSupport))) { + _context.next = 5; + break; + } + _context.next = 3; + return Promise.all([cacheTestResult(testAudioContextDecodeAudioDataMethodTypeErrorSupport, testAudioContextDecodeAudioDataMethodTypeErrorSupport), cacheTestResult(testAudioWorkletProcessorNoOutputsSupport, testAudioWorkletProcessorNoOutputsSupport), cacheTestResult(testStereoPannerNodeDefaultValueSupport, testStereoPannerNodeDefaultValueSupport), cacheTestResult(testTransferablesSupport, testTransferablesSupport)]); + case 3: + results = _context.sent; + return _context.abrupt("return", results.every(function (result) { + return result; + })); + case 5: + return _context.abrupt("return", false); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createIsSupportedPromise(_x, _x2, _x3, _x4, _x5, _x6, _x7, _x8, _x9, _x10, _x11, _x12, _x13, _x14, _x15, _x16) { + return _ref.apply(this, arguments); + }; + }(); + + function _callSuper$b(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$b() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$b() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$b = function _isNativeReflectConstruct() { return !!t; })(); } + var createMediaElementAudioSourceNodeConstructor = function createMediaElementAudioSourceNodeConstructor(audioNodeConstructor, createNativeMediaElementAudioSourceNode, getNativeContext, isNativeOfflineAudioContext) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function MediaElementAudioSourceNode(context, options) { + var _this; + _classCallCheck(this, MediaElementAudioSourceNode); + var nativeContext = getNativeContext(context); + var nativeMediaElementAudioSourceNode = createNativeMediaElementAudioSourceNode(nativeContext, options); + // Bug #171: Safari allows to create a MediaElementAudioSourceNode with an OfflineAudioContext. + if (isNativeOfflineAudioContext(nativeContext)) { + throw TypeError(); + } + _this = _callSuper$b(this, MediaElementAudioSourceNode, [context, true, nativeMediaElementAudioSourceNode, null]); + _this._nativeMediaElementAudioSourceNode = nativeMediaElementAudioSourceNode; + return _this; + } + _inherits(MediaElementAudioSourceNode, _audioNodeConstructor); + return _createClass(MediaElementAudioSourceNode, [{ + key: "mediaElement", + get: function get() { + return this._nativeMediaElementAudioSourceNode.mediaElement; + } + }]); + }(audioNodeConstructor); + }; + + function ownKeys$h(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$h(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$h(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$h(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$a(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$a() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$a() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$a = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$7 = { + channelCount: 2, + channelCountMode: 'explicit', + channelInterpretation: 'speakers' + }; + var createMediaStreamAudioDestinationNodeConstructor = function createMediaStreamAudioDestinationNodeConstructor(audioNodeConstructor, createNativeMediaStreamAudioDestinationNode, getNativeContext, isNativeOfflineAudioContext) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function MediaStreamAudioDestinationNode(context, options) { + var _this; + _classCallCheck(this, MediaStreamAudioDestinationNode); + var nativeContext = getNativeContext(context); + // Bug #173: Safari allows to create a MediaStreamAudioDestinationNode with an OfflineAudioContext. + if (isNativeOfflineAudioContext(nativeContext)) { + throw new TypeError(); + } + var mergedOptions = _objectSpread$h(_objectSpread$h({}, DEFAULT_OPTIONS$7), options); + var nativeMediaStreamAudioDestinationNode = createNativeMediaStreamAudioDestinationNode(nativeContext, mergedOptions); + _this = _callSuper$a(this, MediaStreamAudioDestinationNode, [context, false, nativeMediaStreamAudioDestinationNode, null]); + _this._nativeMediaStreamAudioDestinationNode = nativeMediaStreamAudioDestinationNode; + return _this; + } + _inherits(MediaStreamAudioDestinationNode, _audioNodeConstructor); + return _createClass(MediaStreamAudioDestinationNode, [{ + key: "stream", + get: function get() { + return this._nativeMediaStreamAudioDestinationNode.stream; + } + }]); + }(audioNodeConstructor); + }; + + function _callSuper$9(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$9() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$9() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$9 = function _isNativeReflectConstruct() { return !!t; })(); } + var createMediaStreamAudioSourceNodeConstructor = function createMediaStreamAudioSourceNodeConstructor(audioNodeConstructor, createNativeMediaStreamAudioSourceNode, getNativeContext, isNativeOfflineAudioContext) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function MediaStreamAudioSourceNode(context, options) { + var _this; + _classCallCheck(this, MediaStreamAudioSourceNode); + var nativeContext = getNativeContext(context); + var nativeMediaStreamAudioSourceNode = createNativeMediaStreamAudioSourceNode(nativeContext, options); + // Bug #172: Safari allows to create a MediaStreamAudioSourceNode with an OfflineAudioContext. + if (isNativeOfflineAudioContext(nativeContext)) { + throw new TypeError(); + } + _this = _callSuper$9(this, MediaStreamAudioSourceNode, [context, true, nativeMediaStreamAudioSourceNode, null]); + _this._nativeMediaStreamAudioSourceNode = nativeMediaStreamAudioSourceNode; + return _this; + } + _inherits(MediaStreamAudioSourceNode, _audioNodeConstructor); + return _createClass(MediaStreamAudioSourceNode, [{ + key: "mediaStream", + get: function get() { + return this._nativeMediaStreamAudioSourceNode.mediaStream; + } + }]); + }(audioNodeConstructor); + }; + + function _callSuper$8(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$8() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$8() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$8 = function _isNativeReflectConstruct() { return !!t; })(); } + var createMediaStreamTrackAudioSourceNodeConstructor = function createMediaStreamTrackAudioSourceNodeConstructor(audioNodeConstructor, createNativeMediaStreamTrackAudioSourceNode, getNativeContext) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function MediaStreamTrackAudioSourceNode(context, options) { + _classCallCheck(this, MediaStreamTrackAudioSourceNode); + var nativeContext = getNativeContext(context); + var nativeMediaStreamTrackAudioSourceNode = createNativeMediaStreamTrackAudioSourceNode(nativeContext, options); + return _callSuper$8(this, MediaStreamTrackAudioSourceNode, [context, true, nativeMediaStreamTrackAudioSourceNode, null]); + } + _inherits(MediaStreamTrackAudioSourceNode, _audioNodeConstructor); + return _createClass(MediaStreamTrackAudioSourceNode); + }(audioNodeConstructor); + }; + + function _callSuper$7(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$7() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$7() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$7 = function _isNativeReflectConstruct() { return !!t; })(); } + var createMinimalAudioContextConstructor = function createMinimalAudioContextConstructor(createInvalidStateError, createNotSupportedError, createUnknownError, minimalBaseAudioContextConstructor, nativeAudioContextConstructor) { + return /*#__PURE__*/function (_minimalBaseAudioCont) { + function MinimalAudioContext() { + var _this; + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + _classCallCheck(this, MinimalAudioContext); + if (nativeAudioContextConstructor === null) { + throw new Error('Missing the native AudioContext constructor.'); + } + var nativeAudioContext; + try { + nativeAudioContext = new nativeAudioContextConstructor(options); + } catch (err) { + // Bug #192 Safari does throw a SyntaxError if the sampleRate is not supported. + if (err.code === 12 && err.message === 'sampleRate is not in range') { + throw createNotSupportedError(); + } + throw err; + } + // Bug #131 Safari returns null when there are four other AudioContexts running already. + if (nativeAudioContext === null) { + throw createUnknownError(); + } + // Bug #51 Only Chrome and Edge throw an error if the given latencyHint is invalid. + if (!isValidLatencyHint(options.latencyHint)) { + throw new TypeError("The provided value '".concat(options.latencyHint, "' is not a valid enum value of type AudioContextLatencyCategory.")); + } + // Bug #150 Safari does not support setting the sampleRate. + if (options.sampleRate !== undefined && nativeAudioContext.sampleRate !== options.sampleRate) { + throw createNotSupportedError(); + } + _this = _callSuper$7(this, MinimalAudioContext, [nativeAudioContext, 2]); + var latencyHint = options.latencyHint; + var _nativeAudioContext = nativeAudioContext, + sampleRate = _nativeAudioContext.sampleRate; + // @todo The values for 'balanced', 'interactive' and 'playback' are just copied from Chrome's implementation. + _this._baseLatency = typeof nativeAudioContext.baseLatency === 'number' ? nativeAudioContext.baseLatency : latencyHint === 'balanced' ? 512 / sampleRate : latencyHint === 'interactive' || latencyHint === undefined ? 256 / sampleRate : latencyHint === 'playback' ? 1024 / sampleRate : + /* + * @todo The min (256) and max (16384) values are taken from the allowed bufferSize values of a + * ScriptProcessorNode. + */ + Math.max(2, Math.min(128, Math.round(latencyHint * sampleRate / 128))) * 128 / sampleRate; + _this._nativeAudioContext = nativeAudioContext; + // Bug #188: Safari will set the context's state to 'interrupted' in case the user switches tabs. + if (nativeAudioContextConstructor.name === 'webkitAudioContext') { + _this._nativeGainNode = nativeAudioContext.createGain(); + _this._nativeOscillatorNode = nativeAudioContext.createOscillator(); + _this._nativeGainNode.gain.value = 1e-37; + _this._nativeOscillatorNode.connect(_this._nativeGainNode).connect(nativeAudioContext.destination); + _this._nativeOscillatorNode.start(); + } else { + _this._nativeGainNode = null; + _this._nativeOscillatorNode = null; + } + _this._state = null; + /* + * Bug #34: Chrome and Edge pretend to be running right away, but fire an onstatechange event when the state actually changes + * to 'running'. + */ + if (nativeAudioContext.state === 'running') { + _this._state = 'suspended'; + var _revokeState = function revokeState() { + if (_this._state === 'suspended') { + _this._state = null; + } + nativeAudioContext.removeEventListener('statechange', _revokeState); + }; + nativeAudioContext.addEventListener('statechange', _revokeState); + } + return _this; + } + _inherits(MinimalAudioContext, _minimalBaseAudioCont); + return _createClass(MinimalAudioContext, [{ + key: "baseLatency", + get: function get() { + return this._baseLatency; + } + }, { + key: "state", + get: function get() { + return this._state !== null ? this._state : this._nativeAudioContext.state; + } + }, { + key: "close", + value: function close() { + var _this2 = this; + // Bug #35: Firefox does not throw an error if the AudioContext was closed before. + if (this.state === 'closed') { + return this._nativeAudioContext.close().then(function () { + throw createInvalidStateError(); + }); + } + // Bug #34: If the state was set to suspended before it should be revoked now. + if (this._state === 'suspended') { + this._state = null; + } + return this._nativeAudioContext.close().then(function () { + if (_this2._nativeGainNode !== null && _this2._nativeOscillatorNode !== null) { + _this2._nativeOscillatorNode.stop(); + _this2._nativeGainNode.disconnect(); + _this2._nativeOscillatorNode.disconnect(); + } + deactivateAudioGraph(_this2); + }); + } + }, { + key: "resume", + value: function resume() { + var _this3 = this; + if (this._state === 'suspended') { + return new Promise(function (resolve, reject) { + var _resolvePromise = function resolvePromise() { + _this3._nativeAudioContext.removeEventListener('statechange', _resolvePromise); + if (_this3._nativeAudioContext.state === 'running') { + resolve(); + } else { + _this3.resume().then(resolve, reject); + } + }; + _this3._nativeAudioContext.addEventListener('statechange', _resolvePromise); + }); + } + return this._nativeAudioContext.resume()["catch"](function (err) { + // Bug #55: Chrome and Edge do throw an InvalidAccessError instead of an InvalidStateError. + // Bug #56: Safari invokes the catch handler but without an error. + if (err === undefined || err.code === 15) { + throw createInvalidStateError(); + } + throw err; + }); + } + }, { + key: "suspend", + value: function suspend() { + return this._nativeAudioContext.suspend()["catch"](function (err) { + // Bug #56: Safari invokes the catch handler but without an error. + if (err === undefined) { + throw createInvalidStateError(); + } + throw err; + }); + } + }]); + }(minimalBaseAudioContextConstructor); + }; + + function _callSuper$6(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$6() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$6() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$6 = function _isNativeReflectConstruct() { return !!t; })(); } + var createMinimalBaseAudioContextConstructor = function createMinimalBaseAudioContextConstructor(audioDestinationNodeConstructor, createAudioListener, eventTargetConstructor, isNativeOfflineAudioContext, unrenderedAudioWorkletNodeStore, wrapEventListener) { + return /*#__PURE__*/function (_eventTargetConstruct) { + function MinimalBaseAudioContext(_nativeContext, numberOfChannels) { + var _this; + _classCallCheck(this, MinimalBaseAudioContext); + _this = _callSuper$6(this, MinimalBaseAudioContext, [_nativeContext]); + _this._nativeContext = _nativeContext; + CONTEXT_STORE.set(_this, _nativeContext); + if (isNativeOfflineAudioContext(_nativeContext)) { + unrenderedAudioWorkletNodeStore.set(_nativeContext, new Set()); + } + _this._destination = new audioDestinationNodeConstructor(_this, numberOfChannels); + _this._listener = createAudioListener(_this, _nativeContext); + _this._onstatechange = null; + return _this; + } + _inherits(MinimalBaseAudioContext, _eventTargetConstruct); + return _createClass(MinimalBaseAudioContext, [{ + key: "currentTime", + get: function get() { + return this._nativeContext.currentTime; + } + }, { + key: "destination", + get: function get() { + return this._destination; + } + }, { + key: "listener", + get: function get() { + return this._listener; + } + }, { + key: "onstatechange", + get: function get() { + return this._onstatechange; + }, + set: function set(value) { + var wrappedListener = typeof value === 'function' ? wrapEventListener(this, value) : null; + this._nativeContext.onstatechange = wrappedListener; + var nativeOnStateChange = this._nativeContext.onstatechange; + this._onstatechange = nativeOnStateChange !== null && nativeOnStateChange === wrappedListener ? value : nativeOnStateChange; + } + }, { + key: "sampleRate", + get: function get() { + return this._nativeContext.sampleRate; + } + }, { + key: "state", + get: function get() { + return this._nativeContext.state; + } + }]); + }(eventTargetConstructor); + }; + + var testPromiseSupport = function testPromiseSupport(nativeContext) { + // This 12 numbers represent the 48 bytes of an empty WAVE file with a single sample. + var uint32Array = new Uint32Array([1179011410, 40, 1163280727, 544501094, 16, 131073, 44100, 176400, 1048580, 1635017060, 4, 0]); + try { + // Bug #1: Safari requires a successCallback. + var promise = nativeContext.decodeAudioData(uint32Array.buffer, function () { + // Ignore the success callback. + }); + if (promise === undefined) { + return false; + } + promise["catch"](function () { + // Ignore rejected errors. + }); + return true; + } catch (_unused) { + // Ignore errors. + } + return false; + }; + + function ownKeys$g(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$g(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$g(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$g(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$5(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$5() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$5() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$5 = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$6 = { + numberOfChannels: 1 + }; + var createMinimalOfflineAudioContextConstructor = function createMinimalOfflineAudioContextConstructor(cacheTestResult, createInvalidStateError, createNativeOfflineAudioContext, minimalBaseAudioContextConstructor, _startRendering) { + return /*#__PURE__*/function (_minimalBaseAudioCont) { + function MinimalOfflineAudioContext(options) { + var _this; + _classCallCheck(this, MinimalOfflineAudioContext); + var _DEFAULT_OPTIONS$opti = _objectSpread$g(_objectSpread$g({}, DEFAULT_OPTIONS$6), options), + length = _DEFAULT_OPTIONS$opti.length, + numberOfChannels = _DEFAULT_OPTIONS$opti.numberOfChannels, + sampleRate = _DEFAULT_OPTIONS$opti.sampleRate; + var nativeOfflineAudioContext = createNativeOfflineAudioContext(numberOfChannels, length, sampleRate); + // #21 Safari does not support promises and therefore would fire the statechange event before the promise can be resolved. + if (!cacheTestResult(testPromiseSupport, function () { + return testPromiseSupport(nativeOfflineAudioContext); + })) { + nativeOfflineAudioContext.addEventListener('statechange', function () { + var i = 0; + var _delayStateChangeEvent = function delayStateChangeEvent(event) { + if (_this._state === 'running') { + if (i > 0) { + nativeOfflineAudioContext.removeEventListener('statechange', _delayStateChangeEvent); + event.stopImmediatePropagation(); + _this._waitForThePromiseToSettle(event); + } else { + i += 1; + } + } + }; + return _delayStateChangeEvent; + }()); + } + _this = _callSuper$5(this, MinimalOfflineAudioContext, [nativeOfflineAudioContext, numberOfChannels]); + _this._length = length; + _this._nativeOfflineAudioContext = nativeOfflineAudioContext; + _this._state = null; + return _this; + } + _inherits(MinimalOfflineAudioContext, _minimalBaseAudioCont); + return _createClass(MinimalOfflineAudioContext, [{ + key: "length", + get: function get() { + // Bug #17: Safari does not yet expose the length. + if (this._nativeOfflineAudioContext.length === undefined) { + return this._length; + } + return this._nativeOfflineAudioContext.length; + } + }, { + key: "state", + get: function get() { + return this._state === null ? this._nativeOfflineAudioContext.state : this._state; + } + }, { + key: "startRendering", + value: function startRendering() { + var _this2 = this; + /* + * Bug #9 & #59: It is theoretically possible that startRendering() will first render a partialOfflineAudioContext. Therefore + * the state of the nativeOfflineAudioContext might no transition to running immediately. + */ + if (this._state === 'running') { + return Promise.reject(createInvalidStateError()); + } + this._state = 'running'; + return _startRendering(this.destination, this._nativeOfflineAudioContext)["finally"](function () { + _this2._state = null; + deactivateAudioGraph(_this2); + }); + } + }, { + key: "_waitForThePromiseToSettle", + value: function _waitForThePromiseToSettle(event) { + var _this3 = this; + if (this._state === null) { + this._nativeOfflineAudioContext.dispatchEvent(event); + } else { + setTimeout(function () { + return _this3._waitForThePromiseToSettle(event); + }); + } + } + }]); + }(minimalBaseAudioContextConstructor); + }; + + function _createForOfIteratorHelper$1(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$1(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } + function _unsupportedIterableToArray$1(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$1(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$1(r, a) : void 0; } } + function _arrayLikeToArray$1(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } + var createMonitorConnections = function createMonitorConnections(insertElementInSet, isNativeAudioNode) { + return function (nativeAudioNode, whenConnected, whenDisconnected) { + var connections = new Set(); + nativeAudioNode.connect = function (connect) { + // tslint:disable-next-line:invalid-void no-inferrable-types + return function (destination) { + var output = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var input = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var wasDisconnected = connections.size === 0; + if (isNativeAudioNode(destination)) { + // @todo TypeScript cannot infer the overloaded signature with 3 arguments yet. + connect.call(nativeAudioNode, destination, output, input); + insertElementInSet(connections, [destination, output, input], function (connection) { + return connection[0] === destination && connection[1] === output && connection[2] === input; + }, true); + if (wasDisconnected) { + whenConnected(); + } + return destination; + } + connect.call(nativeAudioNode, destination, output); + insertElementInSet(connections, [destination, output], function (connection) { + return connection[0] === destination && connection[1] === output; + }, true); + if (wasDisconnected) { + whenConnected(); + } + return; + }; + }(nativeAudioNode.connect); + nativeAudioNode.disconnect = function (disconnect) { + return function (destinationOrOutput, output, input) { + var wasConnected = connections.size > 0; + if (destinationOrOutput === undefined) { + disconnect.apply(nativeAudioNode); + connections.clear(); + } else if (typeof destinationOrOutput === 'number') { + // @todo TypeScript cannot infer the overloaded signature with 1 argument yet. + disconnect.call(nativeAudioNode, destinationOrOutput); + var _iterator = _createForOfIteratorHelper$1(connections), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var connection = _step.value; + if (connection[1] === destinationOrOutput) { + connections["delete"](connection); + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + } else { + if (isNativeAudioNode(destinationOrOutput)) { + // @todo TypeScript cannot infer the overloaded signature with 3 arguments yet. + disconnect.call(nativeAudioNode, destinationOrOutput, output, input); + } else { + // @todo TypeScript cannot infer the overloaded signature with 2 arguments yet. + disconnect.call(nativeAudioNode, destinationOrOutput, output); + } + var _iterator2 = _createForOfIteratorHelper$1(connections), + _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + var _connection = _step2.value; + if (_connection[0] === destinationOrOutput && (output === undefined || _connection[1] === output) && (input === undefined || _connection[2] === input)) { + connections["delete"](_connection); + } + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + } + var isDisconnected = connections.size === 0; + if (wasConnected && isDisconnected) { + whenDisconnected(); + } + }; + }(nativeAudioNode.disconnect); + return nativeAudioNode; + }; + }; + + var assignNativeAudioNodeOption = function assignNativeAudioNodeOption(nativeAudioNode, options, option) { + var value = options[option]; + if (value !== undefined && value !== nativeAudioNode[option]) { + nativeAudioNode[option] = value; + } + }; + + var assignNativeAudioNodeOptions = function assignNativeAudioNodeOptions(nativeAudioNode, options) { + assignNativeAudioNodeOption(nativeAudioNode, options, 'channelCount'); + assignNativeAudioNodeOption(nativeAudioNode, options, 'channelCountMode'); + assignNativeAudioNodeOption(nativeAudioNode, options, 'channelInterpretation'); + }; + + var testAnalyserNodeGetFloatTimeDomainDataMethodSupport = function testAnalyserNodeGetFloatTimeDomainDataMethodSupport(nativeAnalyserNode) { + return typeof nativeAnalyserNode.getFloatTimeDomainData === 'function'; + }; + + var wrapAnalyserNodeGetFloatTimeDomainDataMethod = function wrapAnalyserNodeGetFloatTimeDomainDataMethod(nativeAnalyserNode) { + nativeAnalyserNode.getFloatTimeDomainData = function (array) { + var byteTimeDomainData = new Uint8Array(array.length); + nativeAnalyserNode.getByteTimeDomainData(byteTimeDomainData); + var length = Math.max(byteTimeDomainData.length, nativeAnalyserNode.fftSize); + for (var i = 0; i < length; i += 1) { + array[i] = (byteTimeDomainData[i] - 128) * 0.0078125; + } + return array; + }; + }; + + var createNativeAnalyserNodeFactory = function createNativeAnalyserNodeFactory(cacheTestResult, createIndexSizeError) { + return function (nativeContext, options) { + var nativeAnalyserNode = nativeContext.createAnalyser(); + // Bug #37: Firefox does not create an AnalyserNode with the default properties. + assignNativeAudioNodeOptions(nativeAnalyserNode, options); + // Bug #118: Safari does not throw an error if maxDecibels is not more than minDecibels. + if (!(options.maxDecibels > options.minDecibels)) { + throw createIndexSizeError(); + } + assignNativeAudioNodeOption(nativeAnalyserNode, options, 'fftSize'); + assignNativeAudioNodeOption(nativeAnalyserNode, options, 'maxDecibels'); + assignNativeAudioNodeOption(nativeAnalyserNode, options, 'minDecibels'); + assignNativeAudioNodeOption(nativeAnalyserNode, options, 'smoothingTimeConstant'); + // Bug #36: Safari does not support getFloatTimeDomainData() yet. + if (!cacheTestResult(testAnalyserNodeGetFloatTimeDomainDataMethodSupport, function () { + return testAnalyserNodeGetFloatTimeDomainDataMethodSupport(nativeAnalyserNode); + })) { + wrapAnalyserNodeGetFloatTimeDomainDataMethod(nativeAnalyserNode); + } + return nativeAnalyserNode; + }; + }; + + var createNativeAudioBufferConstructor = function createNativeAudioBufferConstructor(window) { + if (window === null) { + return null; + } + if (window.hasOwnProperty('AudioBuffer')) { + return window.AudioBuffer; + } + return null; + }; + + var assignNativeAudioNodeAudioParamValue = function assignNativeAudioNodeAudioParamValue(nativeAudioNode, options, audioParam) { + var value = options[audioParam]; + if (value !== undefined && value !== nativeAudioNode[audioParam].value) { + nativeAudioNode[audioParam].value = value; + } + }; + + var wrapAudioBufferSourceNodeStartMethodConsecutiveCalls = function wrapAudioBufferSourceNodeStartMethodConsecutiveCalls(nativeAudioBufferSourceNode) { + nativeAudioBufferSourceNode.start = function (start) { + var isScheduled = false; + return function () { + var when = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var duration = arguments.length > 2 ? arguments[2] : undefined; + if (isScheduled) { + throw createInvalidStateError(); + } + start.call(nativeAudioBufferSourceNode, when, offset, duration); + isScheduled = true; + }; + }(nativeAudioBufferSourceNode.start); + }; + + var wrapAudioScheduledSourceNodeStartMethodNegativeParameters = function wrapAudioScheduledSourceNodeStartMethodNegativeParameters(nativeAudioScheduledSourceNode) { + nativeAudioScheduledSourceNode.start = function (start) { + return function () { + var when = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var duration = arguments.length > 2 ? arguments[2] : undefined; + if (typeof duration === 'number' && duration < 0 || offset < 0 || when < 0) { + throw new RangeError("The parameters can't be negative."); + } + // @todo TypeScript cannot infer the overloaded signature with 3 arguments yet. + start.call(nativeAudioScheduledSourceNode, when, offset, duration); + }; + }(nativeAudioScheduledSourceNode.start); + }; + + var wrapAudioScheduledSourceNodeStopMethodNegativeParameters = function wrapAudioScheduledSourceNodeStopMethodNegativeParameters(nativeAudioScheduledSourceNode) { + nativeAudioScheduledSourceNode.stop = function (stop) { + return function () { + var when = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + if (when < 0) { + throw new RangeError("The parameter can't be negative."); + } + stop.call(nativeAudioScheduledSourceNode, when); + }; + }(nativeAudioScheduledSourceNode.stop); + }; + + var createNativeAudioBufferSourceNodeFactory = function createNativeAudioBufferSourceNodeFactory(addSilentConnection, cacheTestResult, testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport, testAudioBufferSourceNodeStartMethodOffsetClampingSupport, testAudioBufferSourceNodeStopMethodNullifiedBufferSupport, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, wrapAudioBufferSourceNodeStartMethodOffsetClampling, wrapAudioBufferSourceNodeStopMethodNullifiedBuffer, wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls) { + return function (nativeContext, options) { + var nativeAudioBufferSourceNode = nativeContext.createBufferSource(); + assignNativeAudioNodeOptions(nativeAudioBufferSourceNode, options); + assignNativeAudioNodeAudioParamValue(nativeAudioBufferSourceNode, options, 'playbackRate'); + assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, 'buffer'); + // Bug #149: Safari does not yet support the detune AudioParam. + assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, 'loop'); + assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, 'loopEnd'); + assignNativeAudioNodeOption(nativeAudioBufferSourceNode, options, 'loopStart'); + // Bug #69: Safari does allow calls to start() of an already scheduled AudioBufferSourceNode. + if (!cacheTestResult(testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport, function () { + return testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport(nativeContext); + })) { + wrapAudioBufferSourceNodeStartMethodConsecutiveCalls(nativeAudioBufferSourceNode); + } + // Bug #154 & #155: Safari does not handle offsets which are equal to or greater than the duration of the buffer. + if (!cacheTestResult(testAudioBufferSourceNodeStartMethodOffsetClampingSupport, function () { + return testAudioBufferSourceNodeStartMethodOffsetClampingSupport(nativeContext); + })) { + wrapAudioBufferSourceNodeStartMethodOffsetClampling(nativeAudioBufferSourceNode); + } + // Bug #162: Safari does throw an error when stop() is called on an AudioBufferSourceNode which has no buffer assigned to it. + if (!cacheTestResult(testAudioBufferSourceNodeStopMethodNullifiedBufferSupport, function () { + return testAudioBufferSourceNodeStopMethodNullifiedBufferSupport(nativeContext); + })) { + wrapAudioBufferSourceNodeStopMethodNullifiedBuffer(nativeAudioBufferSourceNode, nativeContext); + } + // Bug #44: Safari does not throw a RangeError yet. + if (!cacheTestResult(testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, function () { + return testAudioScheduledSourceNodeStartMethodNegativeParametersSupport(nativeContext); + })) { + wrapAudioScheduledSourceNodeStartMethodNegativeParameters(nativeAudioBufferSourceNode); + } + // Bug #19: Safari does not ignore calls to stop() of an already stopped AudioBufferSourceNode. + if (!cacheTestResult(testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport, function () { + return testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport(nativeContext); + })) { + wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls(nativeAudioBufferSourceNode, nativeContext); + } + // Bug #44: Only Firefox does not throw a RangeError yet. + if (!cacheTestResult(testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, function () { + return testAudioScheduledSourceNodeStopMethodNegativeParametersSupport(nativeContext); + })) { + wrapAudioScheduledSourceNodeStopMethodNegativeParameters(nativeAudioBufferSourceNode); + } + // Bug #175: Safari will not fire an ended event if the AudioBufferSourceNode is unconnected. + addSilentConnection(nativeContext, nativeAudioBufferSourceNode); + return nativeAudioBufferSourceNode; + }; + }; + + var createNativeAudioContextConstructor = function createNativeAudioContextConstructor(window) { + if (window === null) { + return null; + } + if (window.hasOwnProperty('AudioContext')) { + return window.AudioContext; + } + return window.hasOwnProperty('webkitAudioContext') ? window.webkitAudioContext : null; + }; + + var createNativeAudioDestinationNodeFactory = function createNativeAudioDestinationNodeFactory(createNativeGainNode, overwriteAccessors) { + return function (nativeContext, channelCount, isNodeOfNativeOfflineAudioContext) { + var nativeAudioDestinationNode = nativeContext.destination; + // Bug #132: Safari does not have the correct channelCount. + if (nativeAudioDestinationNode.channelCount !== channelCount) { + try { + nativeAudioDestinationNode.channelCount = channelCount; + } catch (_unused) { + // Bug #169: Safari throws an error on each attempt to change the channelCount. + } + } + // Bug #83: Safari does not have the correct channelCountMode. + if (isNodeOfNativeOfflineAudioContext && nativeAudioDestinationNode.channelCountMode !== 'explicit') { + nativeAudioDestinationNode.channelCountMode = 'explicit'; + } + // Bug #47: The AudioDestinationNode in Safari does not initialize the maxChannelCount property correctly. + if (nativeAudioDestinationNode.maxChannelCount === 0) { + Object.defineProperty(nativeAudioDestinationNode, 'maxChannelCount', { + value: channelCount + }); + } + // Bug #168: No browser does yet have an AudioDestinationNode with an output. + var gainNode = createNativeGainNode(nativeContext, { + channelCount: channelCount, + channelCountMode: nativeAudioDestinationNode.channelCountMode, + channelInterpretation: nativeAudioDestinationNode.channelInterpretation, + gain: 1 + }); + overwriteAccessors(gainNode, 'channelCount', function (get) { + return function () { + return get.call(gainNode); + }; + }, function (set) { + return function (value) { + set.call(gainNode, value); + try { + nativeAudioDestinationNode.channelCount = value; + } catch (err) { + // Bug #169: Safari throws an error on each attempt to change the channelCount. + if (value > nativeAudioDestinationNode.maxChannelCount) { + throw err; + } + } + }; + }); + overwriteAccessors(gainNode, 'channelCountMode', function (get) { + return function () { + return get.call(gainNode); + }; + }, function (set) { + return function (value) { + set.call(gainNode, value); + nativeAudioDestinationNode.channelCountMode = value; + }; + }); + overwriteAccessors(gainNode, 'channelInterpretation', function (get) { + return function () { + return get.call(gainNode); + }; + }, function (set) { + return function (value) { + set.call(gainNode, value); + nativeAudioDestinationNode.channelInterpretation = value; + }; + }); + Object.defineProperty(gainNode, 'maxChannelCount', { + get: function get() { + return nativeAudioDestinationNode.maxChannelCount; + } + }); + // @todo This should be disconnected when the context is closed. + gainNode.connect(nativeAudioDestinationNode); + return gainNode; + }; + }; + + var createNativeAudioWorkletNodeConstructor = function createNativeAudioWorkletNodeConstructor(window) { + if (window === null) { + return null; + } + return window.hasOwnProperty('AudioWorkletNode') ? window.AudioWorkletNode : null; + }; + + var testClonabilityOfAudioWorkletNodeOptions = function testClonabilityOfAudioWorkletNodeOptions(audioWorkletNodeOptions) { + var _MessageChannel = new MessageChannel(), + port1 = _MessageChannel.port1; + try { + // This will throw an error if the audioWorkletNodeOptions are not clonable. + port1.postMessage(audioWorkletNodeOptions); + } finally { + port1.close(); + } + }; + + function ownKeys$f(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$f(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$f(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$f(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + var createNativeAudioWorkletNodeFactory = function createNativeAudioWorkletNodeFactory(createInvalidStateError, createNativeAudioWorkletNodeFaker, createNativeGainNode, createNotSupportedError, monitorConnections) { + return function (nativeContext, baseLatency, nativeAudioWorkletNodeConstructor, name, processorConstructor, options) { + if (nativeAudioWorkletNodeConstructor !== null) { + try { + var nativeAudioWorkletNode = new nativeAudioWorkletNodeConstructor(nativeContext, name, options); + var patchedEventListeners = new Map(); + var onprocessorerror = null; + Object.defineProperties(nativeAudioWorkletNode, { + /* + * Bug #61: Overwriting the property accessors for channelCount and channelCountMode is necessary as long as some + * browsers have no native implementation to achieve a consistent behavior. + */ + channelCount: { + get: function get() { + return options.channelCount; + }, + set: function set() { + throw createInvalidStateError(); + } + }, + channelCountMode: { + get: function get() { + return 'explicit'; + }, + set: function set() { + throw createInvalidStateError(); + } + }, + // Bug #156: Chrome and Edge do not yet fire an ErrorEvent. + onprocessorerror: { + get: function get() { + return onprocessorerror; + }, + set: function set(value) { + if (typeof onprocessorerror === 'function') { + nativeAudioWorkletNode.removeEventListener('processorerror', onprocessorerror); + } + onprocessorerror = typeof value === 'function' ? value : null; + if (typeof onprocessorerror === 'function') { + nativeAudioWorkletNode.addEventListener('processorerror', onprocessorerror); + } + } + } + }); + nativeAudioWorkletNode.addEventListener = function (addEventListener) { + return function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (args[0] === 'processorerror') { + var unpatchedEventListener = typeof args[1] === 'function' ? args[1] : _typeof(args[1]) === 'object' && args[1] !== null && typeof args[1].handleEvent === 'function' ? args[1].handleEvent : null; + if (unpatchedEventListener !== null) { + var patchedEventListener = patchedEventListeners.get(args[1]); + if (patchedEventListener !== undefined) { + args[1] = patchedEventListener; + } else { + args[1] = function (event) { + // Bug #178: Chrome and Edge do fire an event of type error. + if (event.type === 'error') { + Object.defineProperties(event, { + type: { + value: 'processorerror' + } + }); + unpatchedEventListener(event); + } else { + unpatchedEventListener(new ErrorEvent(args[0], _objectSpread$f({}, event))); + } + }; + patchedEventListeners.set(unpatchedEventListener, args[1]); + } + } + } + // Bug #178: Chrome and Edge do fire an event of type error. + addEventListener.call(nativeAudioWorkletNode, 'error', args[1], args[2]); + return addEventListener.call.apply(addEventListener, [nativeAudioWorkletNode].concat(args)); + }; + }(nativeAudioWorkletNode.addEventListener); + nativeAudioWorkletNode.removeEventListener = function (removeEventListener) { + return function () { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + if (args[0] === 'processorerror') { + var patchedEventListener = patchedEventListeners.get(args[1]); + if (patchedEventListener !== undefined) { + patchedEventListeners["delete"](args[1]); + args[1] = patchedEventListener; + } + } + // Bug #178: Chrome and Edge do fire an event of type error. + removeEventListener.call(nativeAudioWorkletNode, 'error', args[1], args[2]); + return removeEventListener.call(nativeAudioWorkletNode, args[0], args[1], args[2]); + }; + }(nativeAudioWorkletNode.removeEventListener); + /* + * Bug #86: Chrome and Edge do not invoke the process() function if the corresponding AudioWorkletNode is unconnected but + * has an output. + */ + if (options.numberOfOutputs !== 0) { + var nativeGainNode = createNativeGainNode(nativeContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + gain: 0 + }); + nativeAudioWorkletNode.connect(nativeGainNode).connect(nativeContext.destination); + var whenConnected = function whenConnected() { + return nativeGainNode.disconnect(); + }; + var whenDisconnected = function whenDisconnected() { + return nativeGainNode.connect(nativeContext.destination); + }; + // @todo Disconnect the connection when the process() function of the AudioWorkletNode returns false. + return monitorConnections(nativeAudioWorkletNode, whenConnected, whenDisconnected); + } + return nativeAudioWorkletNode; + } catch (err) { + // Bug #60: Chrome & Edge throw an InvalidStateError instead of a NotSupportedError. + if (err.code === 11) { + throw createNotSupportedError(); + } + throw err; + } + } + // Bug #61: Only Chrome & Edge have an implementation of the AudioWorkletNode yet. + if (processorConstructor === undefined) { + throw createNotSupportedError(); + } + testClonabilityOfAudioWorkletNodeOptions(options); + return createNativeAudioWorkletNodeFaker(nativeContext, baseLatency, processorConstructor, options); + }; + }; + + var computeBufferSize = function computeBufferSize(baseLatency, sampleRate) { + if (baseLatency === null) { + return 512; + } + return Math.max(512, Math.min(16384, Math.pow(2, Math.round(Math.log2(baseLatency * sampleRate))))); + }; + + var cloneAudioWorkletNodeOptions = function cloneAudioWorkletNodeOptions(audioWorkletNodeOptions) { + return new Promise(function (resolve, reject) { + var _MessageChannel = new MessageChannel(), + port1 = _MessageChannel.port1, + port2 = _MessageChannel.port2; + port1.onmessage = function (_ref) { + var data = _ref.data; + port1.close(); + port2.close(); + resolve(data); + }; + port1.onmessageerror = function (_ref2) { + var data = _ref2.data; + port1.close(); + port2.close(); + reject(data); + }; + // This will throw an error if the audioWorkletNodeOptions are not clonable. + port2.postMessage(audioWorkletNodeOptions); + }); + }; + + var createAudioWorkletProcessorPromise = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(processorConstructor, audioWorkletNodeOptions) { + var clonedAudioWorkletNodeOptions; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return cloneAudioWorkletNodeOptions(audioWorkletNodeOptions); + case 2: + clonedAudioWorkletNodeOptions = _context.sent; + return _context.abrupt("return", new processorConstructor(clonedAudioWorkletNodeOptions)); + case 4: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createAudioWorkletProcessorPromise(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + + var createAudioWorkletProcessor = function createAudioWorkletProcessor(nativeContext, nativeAudioWorkletNode, processorConstructor, audioWorkletNodeOptions) { + var nodeToProcessorMap = NODE_TO_PROCESSOR_MAPS.get(nativeContext); + if (nodeToProcessorMap === undefined) { + nodeToProcessorMap = new WeakMap(); + NODE_TO_PROCESSOR_MAPS.set(nativeContext, nodeToProcessorMap); + } + var audioWorkletProcessorPromise = createAudioWorkletProcessorPromise(processorConstructor, audioWorkletNodeOptions); + nodeToProcessorMap.set(nativeAudioWorkletNode, audioWorkletProcessorPromise); + return audioWorkletProcessorPromise; + }; + + function ownKeys$e(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$e(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$e(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$e(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } + function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } + function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } + var createNativeAudioWorkletNodeFakerFactory = function createNativeAudioWorkletNodeFakerFactory(connectMultipleOutputs, createIndexSizeError, createInvalidStateError, createNativeChannelMergerNode, createNativeChannelSplitterNode, createNativeConstantSourceNode, createNativeGainNode, createNativeScriptProcessorNode, createNotSupportedError, disconnectMultipleOutputs, exposeCurrentFrameAndCurrentTime, getActiveAudioWorkletNodeInputs, monitorConnections) { + return function (nativeContext, baseLatency, processorConstructor, options) { + if (options.numberOfInputs === 0 && options.numberOfOutputs === 0) { + throw createNotSupportedError(); + } + var outputChannelCount = Array.isArray(options.outputChannelCount) ? options.outputChannelCount : Array.from(options.outputChannelCount); + // @todo Check if any of the channelCount values is greater than the implementation's maximum number of channels. + if (outputChannelCount.some(function (channelCount) { + return channelCount < 1; + })) { + throw createNotSupportedError(); + } + if (outputChannelCount.length !== options.numberOfOutputs) { + throw createIndexSizeError(); + } + // Bug #61: This is not part of the standard but required for the faker to work. + if (options.channelCountMode !== 'explicit') { + throw createNotSupportedError(); + } + var numberOfInputChannels = options.channelCount * options.numberOfInputs; + var numberOfOutputChannels = outputChannelCount.reduce(function (sum, value) { + return sum + value; + }, 0); + var numberOfParameters = processorConstructor.parameterDescriptors === undefined ? 0 : processorConstructor.parameterDescriptors.length; + // Bug #61: This is not part of the standard but required for the faker to work. + if (numberOfInputChannels + numberOfParameters > 6 || numberOfOutputChannels > 6) { + throw createNotSupportedError(); + } + var messageChannel = new MessageChannel(); + var gainNodes = []; + var inputChannelSplitterNodes = []; + for (var i = 0; i < options.numberOfInputs; i += 1) { + gainNodes.push(createNativeGainNode(nativeContext, { + channelCount: options.channelCount, + channelCountMode: options.channelCountMode, + channelInterpretation: options.channelInterpretation, + gain: 1 + })); + inputChannelSplitterNodes.push(createNativeChannelSplitterNode(nativeContext, { + channelCount: options.channelCount, + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + numberOfOutputs: options.channelCount + })); + } + var constantSourceNodes = []; + if (processorConstructor.parameterDescriptors !== undefined) { + var _iterator = _createForOfIteratorHelper(processorConstructor.parameterDescriptors), + _step; + try { + var _loop = function _loop() { + var _step$value = _step.value, + defaultValue = _step$value.defaultValue, + maxValue = _step$value.maxValue, + minValue = _step$value.minValue, + name = _step$value.name; + var constantSourceNode = createNativeConstantSourceNode(nativeContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + offset: options.parameterData[name] !== undefined ? options.parameterData[name] : defaultValue === undefined ? 0 : defaultValue + }); + Object.defineProperties(constantSourceNode.offset, { + defaultValue: { + get: function get() { + return defaultValue === undefined ? 0 : defaultValue; + } + }, + maxValue: { + get: function get() { + return maxValue === undefined ? MOST_POSITIVE_SINGLE_FLOAT : maxValue; + } + }, + minValue: { + get: function get() { + return minValue === undefined ? MOST_NEGATIVE_SINGLE_FLOAT : minValue; + } + } + }); + constantSourceNodes.push(constantSourceNode); + }; + for (_iterator.s(); !(_step = _iterator.n()).done;) { + _loop(); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + } + var inputChannelMergerNode = createNativeChannelMergerNode(nativeContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'speakers', + numberOfInputs: Math.max(1, numberOfInputChannels + numberOfParameters) + }); + var bufferSize = computeBufferSize(baseLatency, nativeContext.sampleRate); + var scriptProcessorNode = createNativeScriptProcessorNode(nativeContext, bufferSize, numberOfInputChannels + numberOfParameters, + // Bug #87: Only Firefox will fire an AudioProcessingEvent if there is no connected output. + Math.max(1, numberOfOutputChannels)); + var outputChannelSplitterNode = createNativeChannelSplitterNode(nativeContext, { + channelCount: Math.max(1, numberOfOutputChannels), + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + numberOfOutputs: Math.max(1, numberOfOutputChannels) + }); + var outputChannelMergerNodes = []; + for (var _i = 0; _i < options.numberOfOutputs; _i += 1) { + outputChannelMergerNodes.push(createNativeChannelMergerNode(nativeContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'speakers', + numberOfInputs: outputChannelCount[_i] + })); + } + for (var _i2 = 0; _i2 < options.numberOfInputs; _i2 += 1) { + gainNodes[_i2].connect(inputChannelSplitterNodes[_i2]); + for (var j = 0; j < options.channelCount; j += 1) { + inputChannelSplitterNodes[_i2].connect(inputChannelMergerNode, j, _i2 * options.channelCount + j); + } + } + var parameterMap = new ReadOnlyMap(processorConstructor.parameterDescriptors === undefined ? [] : processorConstructor.parameterDescriptors.map(function (_ref, index) { + var name = _ref.name; + var constantSourceNode = constantSourceNodes[index]; + constantSourceNode.connect(inputChannelMergerNode, 0, numberOfInputChannels + index); + constantSourceNode.start(0); + return [name, constantSourceNode.offset]; + })); + inputChannelMergerNode.connect(scriptProcessorNode); + var channelInterpretation = options.channelInterpretation; + var onprocessorerror = null; + // Bug #87: Expose at least one output to make this node connectable. + var outputAudioNodes = options.numberOfOutputs === 0 ? [scriptProcessorNode] : outputChannelMergerNodes; + var nativeAudioWorkletNodeFaker = { + get bufferSize() { + return bufferSize; + }, + get channelCount() { + return options.channelCount; + }, + set channelCount(_) { + // Bug #61: This is not part of the standard but required for the faker to work. + throw createInvalidStateError(); + }, + get channelCountMode() { + return options.channelCountMode; + }, + set channelCountMode(_) { + // Bug #61: This is not part of the standard but required for the faker to work. + throw createInvalidStateError(); + }, + get channelInterpretation() { + return channelInterpretation; + }, + set channelInterpretation(value) { + for (var _i3 = 0, _gainNodes = gainNodes; _i3 < _gainNodes.length; _i3++) { + var gainNode = _gainNodes[_i3]; + gainNode.channelInterpretation = value; + } + channelInterpretation = value; + }, + get context() { + return scriptProcessorNode.context; + }, + get inputs() { + return gainNodes; + }, + get numberOfInputs() { + return options.numberOfInputs; + }, + get numberOfOutputs() { + return options.numberOfOutputs; + }, + get onprocessorerror() { + return onprocessorerror; + }, + set onprocessorerror(value) { + if (typeof onprocessorerror === 'function') { + nativeAudioWorkletNodeFaker.removeEventListener('processorerror', onprocessorerror); + } + onprocessorerror = typeof value === 'function' ? value : null; + if (typeof onprocessorerror === 'function') { + nativeAudioWorkletNodeFaker.addEventListener('processorerror', onprocessorerror); + } + }, + get parameters() { + return parameterMap; + }, + get port() { + return messageChannel.port2; + }, + addEventListener: function addEventListener() { + return scriptProcessorNode.addEventListener(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1], arguments.length <= 2 ? undefined : arguments[2]); + }, + connect: connectMultipleOutputs.bind(null, outputAudioNodes), + disconnect: disconnectMultipleOutputs.bind(null, outputAudioNodes), + dispatchEvent: function dispatchEvent() { + return scriptProcessorNode.dispatchEvent(arguments.length <= 0 ? undefined : arguments[0]); + }, + removeEventListener: function removeEventListener() { + return scriptProcessorNode.removeEventListener(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1], arguments.length <= 2 ? undefined : arguments[2]); + } + }; + var patchedEventListeners = new Map(); + messageChannel.port1.addEventListener = function (addEventListener) { + return function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (args[0] === 'message') { + var unpatchedEventListener = typeof args[1] === 'function' ? args[1] : _typeof(args[1]) === 'object' && args[1] !== null && typeof args[1].handleEvent === 'function' ? args[1].handleEvent : null; + if (unpatchedEventListener !== null) { + var patchedEventListener = patchedEventListeners.get(args[1]); + if (patchedEventListener !== undefined) { + args[1] = patchedEventListener; + } else { + args[1] = function (event) { + exposeCurrentFrameAndCurrentTime(nativeContext.currentTime, nativeContext.sampleRate, function () { + return unpatchedEventListener(event); + }); + }; + patchedEventListeners.set(unpatchedEventListener, args[1]); + } + } + } + return addEventListener.call(messageChannel.port1, args[0], args[1], args[2]); + }; + }(messageChannel.port1.addEventListener); + messageChannel.port1.removeEventListener = function (removeEventListener) { + return function () { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + if (args[0] === 'message') { + var patchedEventListener = patchedEventListeners.get(args[1]); + if (patchedEventListener !== undefined) { + patchedEventListeners["delete"](args[1]); + args[1] = patchedEventListener; + } + } + return removeEventListener.call(messageChannel.port1, args[0], args[1], args[2]); + }; + }(messageChannel.port1.removeEventListener); + var onmessage = null; + Object.defineProperty(messageChannel.port1, 'onmessage', { + get: function get() { + return onmessage; + }, + set: function set(value) { + if (typeof onmessage === 'function') { + messageChannel.port1.removeEventListener('message', onmessage); + } + onmessage = typeof value === 'function' ? value : null; + if (typeof onmessage === 'function') { + messageChannel.port1.addEventListener('message', onmessage); + messageChannel.port1.start(); + } + } + }); + processorConstructor.prototype.port = messageChannel.port1; + var audioWorkletProcessor = null; + var audioWorkletProcessorPromise = createAudioWorkletProcessor(nativeContext, nativeAudioWorkletNodeFaker, processorConstructor, options); + audioWorkletProcessorPromise.then(function (dWrkltPrcssr) { + return audioWorkletProcessor = dWrkltPrcssr; + }); + var inputs = createNestedArrays(options.numberOfInputs, options.channelCount); + var outputs = createNestedArrays(options.numberOfOutputs, outputChannelCount); + var parameters = processorConstructor.parameterDescriptors === undefined ? [] : processorConstructor.parameterDescriptors.reduce(function (prmtrs, _ref2) { + var name = _ref2.name; + return _objectSpread$e(_objectSpread$e({}, prmtrs), {}, _defineProperty({}, name, new Float32Array(128))); + }, {}); + var isActive = true; + var disconnectOutputsGraph = function disconnectOutputsGraph() { + if (options.numberOfOutputs > 0) { + scriptProcessorNode.disconnect(outputChannelSplitterNode); + } + for (var _i4 = 0, outputChannelSplitterNodeOutput = 0; _i4 < options.numberOfOutputs; _i4 += 1) { + var outputChannelMergerNode = outputChannelMergerNodes[_i4]; + for (var _j = 0; _j < outputChannelCount[_i4]; _j += 1) { + outputChannelSplitterNode.disconnect(outputChannelMergerNode, outputChannelSplitterNodeOutput + _j, _j); + } + outputChannelSplitterNodeOutput += outputChannelCount[_i4]; + } + }; + var activeInputIndexes = new Map(); + // tslint:disable-next-line:deprecation + scriptProcessorNode.onaudioprocess = function (_ref3) { + var inputBuffer = _ref3.inputBuffer, + outputBuffer = _ref3.outputBuffer; + if (audioWorkletProcessor !== null) { + var activeInputs = getActiveAudioWorkletNodeInputs(nativeAudioWorkletNodeFaker); + var _loop2 = function _loop2(_i5) { + for (var _j2 = 0; _j2 < options.numberOfInputs; _j2 += 1) { + for (var k = 0; k < options.channelCount; k += 1) { + copyFromChannel(inputBuffer, inputs[_j2], k, k, _i5); + } + } + if (processorConstructor.parameterDescriptors !== undefined) { + processorConstructor.parameterDescriptors.forEach(function (_ref4, index) { + var name = _ref4.name; + copyFromChannel(inputBuffer, parameters, name, numberOfInputChannels + index, _i5); + }); + } + for (var _j3 = 0; _j3 < options.numberOfInputs; _j3 += 1) { + for (var _k = 0; _k < outputChannelCount[_j3]; _k += 1) { + // The byteLength will be 0 when the ArrayBuffer was transferred. + if (outputs[_j3][_k].byteLength === 0) { + outputs[_j3][_k] = new Float32Array(128); + } + } + } + try { + var potentiallyEmptyInputs = inputs.map(function (input, index) { + var activeInput = activeInputs[index]; + if (activeInput.size > 0) { + activeInputIndexes.set(index, bufferSize / 128); + return input; + } + var count = activeInputIndexes.get(index); + if (count === undefined) { + return []; + } + if (input.every(function (channelData) { + return channelData.every(function (sample) { + return sample === 0; + }); + })) { + if (count === 1) { + activeInputIndexes["delete"](index); + } else { + activeInputIndexes.set(index, count - 1); + } + } + return input; + }); + var activeSourceFlag = exposeCurrentFrameAndCurrentTime(nativeContext.currentTime + _i5 / nativeContext.sampleRate, nativeContext.sampleRate, function () { + return audioWorkletProcessor.process(potentiallyEmptyInputs, outputs, parameters); + }); + isActive = activeSourceFlag; + for (var _j4 = 0, outputChannelSplitterNodeOutput = 0; _j4 < options.numberOfOutputs; _j4 += 1) { + for (var _k2 = 0; _k2 < outputChannelCount[_j4]; _k2 += 1) { + copyToChannel(outputBuffer, outputs[_j4], _k2, outputChannelSplitterNodeOutput + _k2, _i5); + } + outputChannelSplitterNodeOutput += outputChannelCount[_j4]; + } + } catch (error) { + isActive = false; + nativeAudioWorkletNodeFaker.dispatchEvent(new ErrorEvent('processorerror', { + colno: error.colno, + filename: error.filename, + lineno: error.lineno, + message: error.message + })); + } + if (!isActive) { + for (var _j5 = 0; _j5 < options.numberOfInputs; _j5 += 1) { + gainNodes[_j5].disconnect(inputChannelSplitterNodes[_j5]); + for (var _k3 = 0; _k3 < options.channelCount; _k3 += 1) { + inputChannelSplitterNodes[_i5].disconnect(inputChannelMergerNode, _k3, _j5 * options.channelCount + _k3); + } + } + if (processorConstructor.parameterDescriptors !== undefined) { + var length = processorConstructor.parameterDescriptors.length; + for (var _j6 = 0; _j6 < length; _j6 += 1) { + var constantSourceNode = constantSourceNodes[_j6]; + constantSourceNode.disconnect(inputChannelMergerNode, 0, numberOfInputChannels + _j6); + constantSourceNode.stop(); + } + } + inputChannelMergerNode.disconnect(scriptProcessorNode); + scriptProcessorNode.onaudioprocess = null; // tslint:disable-line:deprecation + if (isConnected) { + disconnectOutputsGraph(); + } else { + disconnectFakeGraph(); + } + return 1; // break + } + }; + for (var _i5 = 0; _i5 < bufferSize; _i5 += 128) { + if (_loop2(_i5)) break; + } + } + }; + var isConnected = false; + // Bug #87: Only Firefox will fire an AudioProcessingEvent if there is no connected output. + var nativeGainNode = createNativeGainNode(nativeContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + gain: 0 + }); + var connectFakeGraph = function connectFakeGraph() { + return scriptProcessorNode.connect(nativeGainNode).connect(nativeContext.destination); + }; + var disconnectFakeGraph = function disconnectFakeGraph() { + scriptProcessorNode.disconnect(nativeGainNode); + nativeGainNode.disconnect(); + }; + var whenConnected = function whenConnected() { + if (isActive) { + disconnectFakeGraph(); + if (options.numberOfOutputs > 0) { + scriptProcessorNode.connect(outputChannelSplitterNode); + } + for (var _i6 = 0, outputChannelSplitterNodeOutput = 0; _i6 < options.numberOfOutputs; _i6 += 1) { + var outputChannelMergerNode = outputChannelMergerNodes[_i6]; + for (var _j7 = 0; _j7 < outputChannelCount[_i6]; _j7 += 1) { + outputChannelSplitterNode.connect(outputChannelMergerNode, outputChannelSplitterNodeOutput + _j7, _j7); + } + outputChannelSplitterNodeOutput += outputChannelCount[_i6]; + } + } + isConnected = true; + }; + var whenDisconnected = function whenDisconnected() { + if (isActive) { + connectFakeGraph(); + disconnectOutputsGraph(); + } + isConnected = false; + }; + connectFakeGraph(); + return monitorConnections(nativeAudioWorkletNodeFaker, whenConnected, whenDisconnected); + }; + }; + + var createNativeBiquadFilterNode = function createNativeBiquadFilterNode(nativeContext, options) { + var nativeBiquadFilterNode = nativeContext.createBiquadFilter(); + assignNativeAudioNodeOptions(nativeBiquadFilterNode, options); + assignNativeAudioNodeAudioParamValue(nativeBiquadFilterNode, options, 'Q'); + assignNativeAudioNodeAudioParamValue(nativeBiquadFilterNode, options, 'detune'); + assignNativeAudioNodeAudioParamValue(nativeBiquadFilterNode, options, 'frequency'); + assignNativeAudioNodeAudioParamValue(nativeBiquadFilterNode, options, 'gain'); + assignNativeAudioNodeOption(nativeBiquadFilterNode, options, 'type'); + return nativeBiquadFilterNode; + }; + + var createNativeChannelMergerNodeFactory = function createNativeChannelMergerNodeFactory(nativeAudioContextConstructor, wrapChannelMergerNode) { + return function (nativeContext, options) { + var nativeChannelMergerNode = nativeContext.createChannelMerger(options.numberOfInputs); + /* + * Bug #20: Safari requires a connection of any kind to treat the input signal correctly. + * @todo Unfortunately there is no way to test for this behavior in a synchronous fashion which is why testing for the existence of + * the webkitAudioContext is used as a workaround here. + */ + if (nativeAudioContextConstructor !== null && nativeAudioContextConstructor.name === 'webkitAudioContext') { + wrapChannelMergerNode(nativeContext, nativeChannelMergerNode); + } + assignNativeAudioNodeOptions(nativeChannelMergerNode, options); + return nativeChannelMergerNode; + }; + }; + + var wrapChannelSplitterNode = function wrapChannelSplitterNode(channelSplitterNode) { + var channelCount = channelSplitterNode.numberOfOutputs; + // Bug #97: Safari does not throw an error when attempting to change the channelCount to something other than its initial value. + Object.defineProperty(channelSplitterNode, 'channelCount', { + get: function get() { + return channelCount; + }, + set: function set(value) { + if (value !== channelCount) { + throw createInvalidStateError(); + } + } + }); + // Bug #30: Safari does not throw an error when attempting to change the channelCountMode to something other than explicit. + Object.defineProperty(channelSplitterNode, 'channelCountMode', { + get: function get() { + return 'explicit'; + }, + set: function set(value) { + if (value !== 'explicit') { + throw createInvalidStateError(); + } + } + }); + // Bug #32: Safari does not throw an error when attempting to change the channelInterpretation to something other than discrete. + Object.defineProperty(channelSplitterNode, 'channelInterpretation', { + get: function get() { + return 'discrete'; + }, + set: function set(value) { + if (value !== 'discrete') { + throw createInvalidStateError(); + } + } + }); + }; + + var createNativeChannelSplitterNode = function createNativeChannelSplitterNode(nativeContext, options) { + var nativeChannelSplitterNode = nativeContext.createChannelSplitter(options.numberOfOutputs); + // Bug #96: Safari does not have the correct channelCount. + // Bug #29: Safari does not have the correct channelCountMode. + // Bug #31: Safari does not have the correct channelInterpretation. + assignNativeAudioNodeOptions(nativeChannelSplitterNode, options); + // Bug #29, #30, #31, #32, #96 & #97: Only Chrome, Edge & Firefox partially support the spec yet. + wrapChannelSplitterNode(nativeChannelSplitterNode); + return nativeChannelSplitterNode; + }; + + var createNativeConstantSourceNodeFactory = function createNativeConstantSourceNodeFactory(addSilentConnection, cacheTestResult, createNativeConstantSourceNodeFaker, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport) { + return function (nativeContext, options) { + // Bug #62: Safari does not support ConstantSourceNodes. + if (nativeContext.createConstantSource === undefined) { + return createNativeConstantSourceNodeFaker(nativeContext, options); + } + var nativeConstantSourceNode = nativeContext.createConstantSource(); + assignNativeAudioNodeOptions(nativeConstantSourceNode, options); + assignNativeAudioNodeAudioParamValue(nativeConstantSourceNode, options, 'offset'); + // Bug #44: Safari does not throw a RangeError yet. + if (!cacheTestResult(testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, function () { + return testAudioScheduledSourceNodeStartMethodNegativeParametersSupport(nativeContext); + })) { + wrapAudioScheduledSourceNodeStartMethodNegativeParameters(nativeConstantSourceNode); + } + // Bug #44: Only Firefox does not throw a RangeError yet. + if (!cacheTestResult(testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, function () { + return testAudioScheduledSourceNodeStopMethodNegativeParametersSupport(nativeContext); + })) { + wrapAudioScheduledSourceNodeStopMethodNegativeParameters(nativeConstantSourceNode); + } + // Bug #175: Safari will not fire an ended event if the ConstantSourceNode is unconnected. + addSilentConnection(nativeContext, nativeConstantSourceNode); + return nativeConstantSourceNode; + }; + }; + + var interceptConnections = function interceptConnections(original, interceptor) { + original.connect = interceptor.connect.bind(interceptor); + original.disconnect = interceptor.disconnect.bind(interceptor); + return original; + }; + + var _excluded$3 = ["offset"]; + function ownKeys$d(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$d(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$d(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$d(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + var createNativeConstantSourceNodeFakerFactory = function createNativeConstantSourceNodeFakerFactory(addSilentConnection, createNativeAudioBufferSourceNode, createNativeGainNode, monitorConnections) { + return function (nativeContext, _ref) { + var offset = _ref.offset, + audioNodeOptions = _objectWithoutProperties(_ref, _excluded$3); + var audioBuffer = nativeContext.createBuffer(1, 2, 44100); + var audioBufferSourceNode = createNativeAudioBufferSourceNode(nativeContext, { + buffer: null, + channelCount: 2, + channelCountMode: 'max', + channelInterpretation: 'speakers', + loop: false, + loopEnd: 0, + loopStart: 0, + playbackRate: 1 + }); + var gainNode = createNativeGainNode(nativeContext, _objectSpread$d(_objectSpread$d({}, audioNodeOptions), {}, { + gain: offset + })); + // Bug #5: Safari does not support copyFromChannel() and copyToChannel(). + var channelData = audioBuffer.getChannelData(0); + // Bug #95: Safari does not play or loop one sample buffers. + channelData[0] = 1; + channelData[1] = 1; + audioBufferSourceNode.buffer = audioBuffer; + audioBufferSourceNode.loop = true; + var nativeConstantSourceNodeFaker = { + get bufferSize() { + return undefined; + }, + get channelCount() { + return gainNode.channelCount; + }, + set channelCount(value) { + gainNode.channelCount = value; + }, + get channelCountMode() { + return gainNode.channelCountMode; + }, + set channelCountMode(value) { + gainNode.channelCountMode = value; + }, + get channelInterpretation() { + return gainNode.channelInterpretation; + }, + set channelInterpretation(value) { + gainNode.channelInterpretation = value; + }, + get context() { + return gainNode.context; + }, + get inputs() { + return []; + }, + get numberOfInputs() { + return audioBufferSourceNode.numberOfInputs; + }, + get numberOfOutputs() { + return gainNode.numberOfOutputs; + }, + get offset() { + return gainNode.gain; + }, + get onended() { + return audioBufferSourceNode.onended; + }, + set onended(value) { + audioBufferSourceNode.onended = value; + }, + addEventListener: function addEventListener() { + return audioBufferSourceNode.addEventListener(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1], arguments.length <= 2 ? undefined : arguments[2]); + }, + dispatchEvent: function dispatchEvent() { + return audioBufferSourceNode.dispatchEvent(arguments.length <= 0 ? undefined : arguments[0]); + }, + removeEventListener: function removeEventListener() { + return audioBufferSourceNode.removeEventListener(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1], arguments.length <= 2 ? undefined : arguments[2]); + }, + start: function start() { + var when = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + audioBufferSourceNode.start.call(audioBufferSourceNode, when); + }, + stop: function stop() { + var when = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + audioBufferSourceNode.stop.call(audioBufferSourceNode, when); + } + }; + var whenConnected = function whenConnected() { + return audioBufferSourceNode.connect(gainNode); + }; + var whenDisconnected = function whenDisconnected() { + return audioBufferSourceNode.disconnect(gainNode); + }; + // Bug #175: Safari will not fire an ended event if the AudioBufferSourceNode is unconnected. + addSilentConnection(nativeContext, audioBufferSourceNode); + return monitorConnections(interceptConnections(nativeConstantSourceNodeFaker, gainNode), whenConnected, whenDisconnected); + }; + }; + + var createNativeConvolverNodeFactory = function createNativeConvolverNodeFactory(createNotSupportedError, overwriteAccessors) { + return function (nativeContext, options) { + var nativeConvolverNode = nativeContext.createConvolver(); + assignNativeAudioNodeOptions(nativeConvolverNode, options); + // The normalize property needs to be set before setting the buffer. + if (options.disableNormalization === nativeConvolverNode.normalize) { + nativeConvolverNode.normalize = !options.disableNormalization; + } + assignNativeAudioNodeOption(nativeConvolverNode, options, 'buffer'); + // Bug #113: Safari does allow to set the channelCount to a value larger than 2. + if (options.channelCount > 2) { + throw createNotSupportedError(); + } + overwriteAccessors(nativeConvolverNode, 'channelCount', function (get) { + return function () { + return get.call(nativeConvolverNode); + }; + }, function (set) { + return function (value) { + if (value > 2) { + throw createNotSupportedError(); + } + return set.call(nativeConvolverNode, value); + }; + }); + // Bug #114: Safari allows to set the channelCountMode to 'max'. + if (options.channelCountMode === 'max') { + throw createNotSupportedError(); + } + overwriteAccessors(nativeConvolverNode, 'channelCountMode', function (get) { + return function () { + return get.call(nativeConvolverNode); + }; + }, function (set) { + return function (value) { + if (value === 'max') { + throw createNotSupportedError(); + } + return set.call(nativeConvolverNode, value); + }; + }); + return nativeConvolverNode; + }; + }; + + var createNativeDelayNode = function createNativeDelayNode(nativeContext, options) { + var nativeDelayNode = nativeContext.createDelay(options.maxDelayTime); + assignNativeAudioNodeOptions(nativeDelayNode, options); + assignNativeAudioNodeAudioParamValue(nativeDelayNode, options, 'delayTime'); + return nativeDelayNode; + }; + + var createNativeDynamicsCompressorNodeFactory = function createNativeDynamicsCompressorNodeFactory(createNotSupportedError) { + return function (nativeContext, options) { + var nativeDynamicsCompressorNode = nativeContext.createDynamicsCompressor(); + assignNativeAudioNodeOptions(nativeDynamicsCompressorNode, options); + // Bug #108: Safari allows a channelCount of three and above. + if (options.channelCount > 2) { + throw createNotSupportedError(); + } + // Bug #109: Only Chrome and Firefox disallow a channelCountMode of 'max'. + if (options.channelCountMode === 'max') { + throw createNotSupportedError(); + } + assignNativeAudioNodeAudioParamValue(nativeDynamicsCompressorNode, options, 'attack'); + assignNativeAudioNodeAudioParamValue(nativeDynamicsCompressorNode, options, 'knee'); + assignNativeAudioNodeAudioParamValue(nativeDynamicsCompressorNode, options, 'ratio'); + assignNativeAudioNodeAudioParamValue(nativeDynamicsCompressorNode, options, 'release'); + assignNativeAudioNodeAudioParamValue(nativeDynamicsCompressorNode, options, 'threshold'); + return nativeDynamicsCompressorNode; + }; + }; + + var createNativeGainNode = function createNativeGainNode(nativeContext, options) { + var nativeGainNode = nativeContext.createGain(); + assignNativeAudioNodeOptions(nativeGainNode, options); + assignNativeAudioNodeAudioParamValue(nativeGainNode, options, 'gain'); + return nativeGainNode; + }; + + var createNativeIIRFilterNodeFactory = function createNativeIIRFilterNodeFactory(createNativeIIRFilterNodeFaker) { + return function (nativeContext, baseLatency, options) { + // Bug #9: Safari does not support IIRFilterNodes. + if (nativeContext.createIIRFilter === undefined) { + return createNativeIIRFilterNodeFaker(nativeContext, baseLatency, options); + } + // @todo TypeScript defines the parameters of createIIRFilter() as arrays of numbers. + var nativeIIRFilterNode = nativeContext.createIIRFilter(options.feedforward, options.feedback); + assignNativeAudioNodeOptions(nativeIIRFilterNode, options); + return nativeIIRFilterNode; + }; + }; + + function divide(a, b) { + var denominator = b[0] * b[0] + b[1] * b[1]; + return [(a[0] * b[0] + a[1] * b[1]) / denominator, (a[1] * b[0] - a[0] * b[1]) / denominator]; + } + function multiply(a, b) { + return [a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0]]; + } + function evaluatePolynomial(coefficient, z) { + var result = [0, 0]; + for (var i = coefficient.length - 1; i >= 0; i -= 1) { + result = multiply(result, z); + result[0] += coefficient[i]; + } + return result; + } + var createNativeIIRFilterNodeFakerFactory = function createNativeIIRFilterNodeFakerFactory(createInvalidAccessError, createInvalidStateError, createNativeScriptProcessorNode, createNotSupportedError) { + return function (nativeContext, baseLatency, _ref) { + var channelCount = _ref.channelCount, + channelCountMode = _ref.channelCountMode, + channelInterpretation = _ref.channelInterpretation, + feedback = _ref.feedback, + feedforward = _ref.feedforward; + var bufferSize = computeBufferSize(baseLatency, nativeContext.sampleRate); + var convertedFeedback = feedback instanceof Float64Array ? feedback : new Float64Array(feedback); + var convertedFeedforward = feedforward instanceof Float64Array ? feedforward : new Float64Array(feedforward); + var feedbackLength = convertedFeedback.length; + var feedforwardLength = convertedFeedforward.length; + var minLength = Math.min(feedbackLength, feedforwardLength); + if (feedbackLength === 0 || feedbackLength > 20) { + throw createNotSupportedError(); + } + if (convertedFeedback[0] === 0) { + throw createInvalidStateError(); + } + if (feedforwardLength === 0 || feedforwardLength > 20) { + throw createNotSupportedError(); + } + if (convertedFeedforward[0] === 0) { + throw createInvalidStateError(); + } + if (convertedFeedback[0] !== 1) { + for (var i = 0; i < feedforwardLength; i += 1) { + convertedFeedforward[i] /= convertedFeedback[0]; + } + for (var _i = 1; _i < feedbackLength; _i += 1) { + convertedFeedback[_i] /= convertedFeedback[0]; + } + } + var scriptProcessorNode = createNativeScriptProcessorNode(nativeContext, bufferSize, channelCount, channelCount); + scriptProcessorNode.channelCount = channelCount; + scriptProcessorNode.channelCountMode = channelCountMode; + scriptProcessorNode.channelInterpretation = channelInterpretation; + var bufferLength = 32; + var bufferIndexes = []; + var xBuffers = []; + var yBuffers = []; + for (var _i2 = 0; _i2 < channelCount; _i2 += 1) { + bufferIndexes.push(0); + var xBuffer = new Float32Array(bufferLength); + var yBuffer = new Float32Array(bufferLength); + xBuffer.fill(0); + yBuffer.fill(0); + xBuffers.push(xBuffer); + yBuffers.push(yBuffer); + } + // tslint:disable-next-line:deprecation + scriptProcessorNode.onaudioprocess = function (event) { + var inputBuffer = event.inputBuffer; + var outputBuffer = event.outputBuffer; + var numberOfChannels = inputBuffer.numberOfChannels; + for (var _i3 = 0; _i3 < numberOfChannels; _i3 += 1) { + var input = inputBuffer.getChannelData(_i3); + var output = outputBuffer.getChannelData(_i3); + bufferIndexes[_i3] = filterBuffer(convertedFeedback, feedbackLength, convertedFeedforward, feedforwardLength, minLength, xBuffers[_i3], yBuffers[_i3], bufferIndexes[_i3], bufferLength, input, output); + } + }; + var nyquist = nativeContext.sampleRate / 2; + var nativeIIRFilterNodeFaker = { + get bufferSize() { + return bufferSize; + }, + get channelCount() { + return scriptProcessorNode.channelCount; + }, + set channelCount(value) { + scriptProcessorNode.channelCount = value; + }, + get channelCountMode() { + return scriptProcessorNode.channelCountMode; + }, + set channelCountMode(value) { + scriptProcessorNode.channelCountMode = value; + }, + get channelInterpretation() { + return scriptProcessorNode.channelInterpretation; + }, + set channelInterpretation(value) { + scriptProcessorNode.channelInterpretation = value; + }, + get context() { + return scriptProcessorNode.context; + }, + get inputs() { + return [scriptProcessorNode]; + }, + get numberOfInputs() { + return scriptProcessorNode.numberOfInputs; + }, + get numberOfOutputs() { + return scriptProcessorNode.numberOfOutputs; + }, + addEventListener: function addEventListener() { + // @todo Dissallow adding an audioprocess listener. + return scriptProcessorNode.addEventListener(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1], arguments.length <= 2 ? undefined : arguments[2]); + }, + dispatchEvent: function dispatchEvent() { + return scriptProcessorNode.dispatchEvent(arguments.length <= 0 ? undefined : arguments[0]); + }, + getFrequencyResponse: function getFrequencyResponse(frequencyHz, magResponse, phaseResponse) { + if (frequencyHz.length !== magResponse.length || magResponse.length !== phaseResponse.length) { + throw createInvalidAccessError(); + } + var length = frequencyHz.length; + for (var _i4 = 0; _i4 < length; _i4 += 1) { + var omega = -Math.PI * (frequencyHz[_i4] / nyquist); + var z = [Math.cos(omega), Math.sin(omega)]; + var numerator = evaluatePolynomial(convertedFeedforward, z); + var denominator = evaluatePolynomial(convertedFeedback, z); + var response = divide(numerator, denominator); + magResponse[_i4] = Math.sqrt(response[0] * response[0] + response[1] * response[1]); + phaseResponse[_i4] = Math.atan2(response[1], response[0]); + } + }, + removeEventListener: function removeEventListener() { + return scriptProcessorNode.removeEventListener(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1], arguments.length <= 2 ? undefined : arguments[2]); + } + }; + return interceptConnections(nativeIIRFilterNodeFaker, scriptProcessorNode); + }; + }; + + var createNativeMediaElementAudioSourceNode = function createNativeMediaElementAudioSourceNode(nativeAudioContext, options) { + return nativeAudioContext.createMediaElementSource(options.mediaElement); + }; + + var createNativeMediaStreamAudioDestinationNode = function createNativeMediaStreamAudioDestinationNode(nativeAudioContext, options) { + var nativeMediaStreamAudioDestinationNode = nativeAudioContext.createMediaStreamDestination(); + assignNativeAudioNodeOptions(nativeMediaStreamAudioDestinationNode, options); + // Bug #174: Safari does expose a wrong numberOfOutputs. + if (nativeMediaStreamAudioDestinationNode.numberOfOutputs === 1) { + Object.defineProperty(nativeMediaStreamAudioDestinationNode, 'numberOfOutputs', { + get: function get() { + return 0; + } + }); + } + return nativeMediaStreamAudioDestinationNode; + }; + + var createNativeMediaStreamAudioSourceNode = function createNativeMediaStreamAudioSourceNode(nativeAudioContext, _ref) { + var mediaStream = _ref.mediaStream; + var audioStreamTracks = mediaStream.getAudioTracks(); + /* + * Bug #151: Safari does not use the audio track as input anymore if it gets removed from the mediaStream after construction. + * Bug #159: Safari picks the first audio track if the MediaStream has more than one audio track. + */ + audioStreamTracks.sort(function (a, b) { + return a.id < b.id ? -1 : a.id > b.id ? 1 : 0; + }); + var filteredAudioStreamTracks = audioStreamTracks.slice(0, 1); + var nativeMediaStreamAudioSourceNode = nativeAudioContext.createMediaStreamSource(new MediaStream(filteredAudioStreamTracks)); + /* + * Bug #151 & #159: The given mediaStream gets reconstructed before it gets passed to the native node which is why the accessor needs + * to be overwritten as it would otherwise expose the reconstructed version. + */ + Object.defineProperty(nativeMediaStreamAudioSourceNode, 'mediaStream', { + value: mediaStream + }); + return nativeMediaStreamAudioSourceNode; + }; + + var createNativeMediaStreamTrackAudioSourceNodeFactory = function createNativeMediaStreamTrackAudioSourceNodeFactory(createInvalidStateError, isNativeOfflineAudioContext) { + return function (nativeAudioContext, _ref) { + var mediaStreamTrack = _ref.mediaStreamTrack; + // Bug #121: Only Firefox does yet support the MediaStreamTrackAudioSourceNode. + if (typeof nativeAudioContext.createMediaStreamTrackSource === 'function') { + return nativeAudioContext.createMediaStreamTrackSource(mediaStreamTrack); + } + var mediaStream = new MediaStream([mediaStreamTrack]); + var nativeMediaStreamAudioSourceNode = nativeAudioContext.createMediaStreamSource(mediaStream); + // Bug #120: Firefox does not throw an error if the mediaStream has no audio track. + if (mediaStreamTrack.kind !== 'audio') { + throw createInvalidStateError(); + } + // Bug #172: Safari allows to create a MediaStreamAudioSourceNode with an OfflineAudioContext. + if (isNativeOfflineAudioContext(nativeAudioContext)) { + throw new TypeError(); + } + return nativeMediaStreamAudioSourceNode; + }; + }; + + var createNativeOfflineAudioContextConstructor = function createNativeOfflineAudioContextConstructor(window) { + if (window === null) { + return null; + } + if (window.hasOwnProperty('OfflineAudioContext')) { + return window.OfflineAudioContext; + } + return window.hasOwnProperty('webkitOfflineAudioContext') ? window.webkitOfflineAudioContext : null; + }; + + var createNativeOscillatorNodeFactory = function createNativeOscillatorNodeFactory(addSilentConnection, cacheTestResult, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls) { + return function (nativeContext, options) { + var nativeOscillatorNode = nativeContext.createOscillator(); + assignNativeAudioNodeOptions(nativeOscillatorNode, options); + assignNativeAudioNodeAudioParamValue(nativeOscillatorNode, options, 'detune'); + assignNativeAudioNodeAudioParamValue(nativeOscillatorNode, options, 'frequency'); + if (options.periodicWave !== undefined) { + nativeOscillatorNode.setPeriodicWave(options.periodicWave); + } else { + assignNativeAudioNodeOption(nativeOscillatorNode, options, 'type'); + } + // Bug #44: Only Chrome & Edge throw a RangeError yet. + if (!cacheTestResult(testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, function () { + return testAudioScheduledSourceNodeStartMethodNegativeParametersSupport(nativeContext); + })) { + wrapAudioScheduledSourceNodeStartMethodNegativeParameters(nativeOscillatorNode); + } + // Bug #19: Safari does not ignore calls to stop() of an already stopped AudioBufferSourceNode. + if (!cacheTestResult(testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport, function () { + return testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport(nativeContext); + })) { + wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls(nativeOscillatorNode, nativeContext); + } + // Bug #44: Only Firefox does not throw a RangeError yet. + if (!cacheTestResult(testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, function () { + return testAudioScheduledSourceNodeStopMethodNegativeParametersSupport(nativeContext); + })) { + wrapAudioScheduledSourceNodeStopMethodNegativeParameters(nativeOscillatorNode); + } + // Bug #175: Safari will not fire an ended event if the OscillatorNode is unconnected. + addSilentConnection(nativeContext, nativeOscillatorNode); + return nativeOscillatorNode; + }; + }; + + var createNativePannerNodeFactory = function createNativePannerNodeFactory(createNativePannerNodeFaker) { + return function (nativeContext, options) { + var nativePannerNode = nativeContext.createPanner(); + // Bug #124: Safari does not support modifying the orientation and the position with AudioParams. + if (nativePannerNode.orientationX === undefined) { + return createNativePannerNodeFaker(nativeContext, options); + } + assignNativeAudioNodeOptions(nativePannerNode, options); + assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'orientationX'); + assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'orientationY'); + assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'orientationZ'); + assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'positionX'); + assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'positionY'); + assignNativeAudioNodeAudioParamValue(nativePannerNode, options, 'positionZ'); + assignNativeAudioNodeOption(nativePannerNode, options, 'coneInnerAngle'); + assignNativeAudioNodeOption(nativePannerNode, options, 'coneOuterAngle'); + assignNativeAudioNodeOption(nativePannerNode, options, 'coneOuterGain'); + assignNativeAudioNodeOption(nativePannerNode, options, 'distanceModel'); + assignNativeAudioNodeOption(nativePannerNode, options, 'maxDistance'); + assignNativeAudioNodeOption(nativePannerNode, options, 'panningModel'); + assignNativeAudioNodeOption(nativePannerNode, options, 'refDistance'); + assignNativeAudioNodeOption(nativePannerNode, options, 'rolloffFactor'); + return nativePannerNode; + }; + }; + + var _excluded$2 = ["coneInnerAngle", "coneOuterAngle", "coneOuterGain", "distanceModel", "maxDistance", "orientationX", "orientationY", "orientationZ", "panningModel", "positionX", "positionY", "positionZ", "refDistance", "rolloffFactor"]; + function ownKeys$c(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$c(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$c(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$c(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + var createNativePannerNodeFakerFactory = function createNativePannerNodeFakerFactory(connectNativeAudioNodeToNativeAudioNode, createInvalidStateError, createNativeChannelMergerNode, createNativeGainNode, createNativeScriptProcessorNode, createNativeWaveShaperNode, createNotSupportedError, disconnectNativeAudioNodeFromNativeAudioNode, getFirstSample, monitorConnections) { + return function (nativeContext, _ref) { + var coneInnerAngle = _ref.coneInnerAngle, + coneOuterAngle = _ref.coneOuterAngle, + coneOuterGain = _ref.coneOuterGain, + distanceModel = _ref.distanceModel, + maxDistance = _ref.maxDistance, + orientationX = _ref.orientationX, + orientationY = _ref.orientationY, + orientationZ = _ref.orientationZ, + panningModel = _ref.panningModel, + positionX = _ref.positionX, + positionY = _ref.positionY, + positionZ = _ref.positionZ, + refDistance = _ref.refDistance, + rolloffFactor = _ref.rolloffFactor, + audioNodeOptions = _objectWithoutProperties(_ref, _excluded$2); + var pannerNode = nativeContext.createPanner(); + // Bug #125: Safari does not throw an error yet. + if (audioNodeOptions.channelCount > 2) { + throw createNotSupportedError(); + } + // Bug #126: Safari does not throw an error yet. + if (audioNodeOptions.channelCountMode === 'max') { + throw createNotSupportedError(); + } + assignNativeAudioNodeOptions(pannerNode, audioNodeOptions); + var SINGLE_CHANNEL_OPTIONS = { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'discrete' + }; + var channelMergerNode = createNativeChannelMergerNode(nativeContext, _objectSpread$c(_objectSpread$c({}, SINGLE_CHANNEL_OPTIONS), {}, { + channelInterpretation: 'speakers', + numberOfInputs: 6 + })); + var inputGainNode = createNativeGainNode(nativeContext, _objectSpread$c(_objectSpread$c({}, audioNodeOptions), {}, { + gain: 1 + })); + var orientationXGainNode = createNativeGainNode(nativeContext, _objectSpread$c(_objectSpread$c({}, SINGLE_CHANNEL_OPTIONS), {}, { + gain: 1 + })); + var orientationYGainNode = createNativeGainNode(nativeContext, _objectSpread$c(_objectSpread$c({}, SINGLE_CHANNEL_OPTIONS), {}, { + gain: 0 + })); + var orientationZGainNode = createNativeGainNode(nativeContext, _objectSpread$c(_objectSpread$c({}, SINGLE_CHANNEL_OPTIONS), {}, { + gain: 0 + })); + var positionXGainNode = createNativeGainNode(nativeContext, _objectSpread$c(_objectSpread$c({}, SINGLE_CHANNEL_OPTIONS), {}, { + gain: 0 + })); + var positionYGainNode = createNativeGainNode(nativeContext, _objectSpread$c(_objectSpread$c({}, SINGLE_CHANNEL_OPTIONS), {}, { + gain: 0 + })); + var positionZGainNode = createNativeGainNode(nativeContext, _objectSpread$c(_objectSpread$c({}, SINGLE_CHANNEL_OPTIONS), {}, { + gain: 0 + })); + var scriptProcessorNode = createNativeScriptProcessorNode(nativeContext, 256, 6, 1); + var waveShaperNode = createNativeWaveShaperNode(nativeContext, _objectSpread$c(_objectSpread$c({}, SINGLE_CHANNEL_OPTIONS), {}, { + curve: new Float32Array([1, 1]), + oversample: 'none' + })); + var lastOrientation = [orientationX, orientationY, orientationZ]; + var lastPosition = [positionX, positionY, positionZ]; + var buffer = new Float32Array(1); + // tslint:disable-next-line:deprecation + scriptProcessorNode.onaudioprocess = function (_ref2) { + var inputBuffer = _ref2.inputBuffer; + var orientation = [getFirstSample(inputBuffer, buffer, 0), getFirstSample(inputBuffer, buffer, 1), getFirstSample(inputBuffer, buffer, 2)]; + if (orientation.some(function (value, index) { + return value !== lastOrientation[index]; + })) { + pannerNode.setOrientation.apply(pannerNode, orientation); // tslint:disable-line:deprecation + lastOrientation = orientation; + } + var positon = [getFirstSample(inputBuffer, buffer, 3), getFirstSample(inputBuffer, buffer, 4), getFirstSample(inputBuffer, buffer, 5)]; + if (positon.some(function (value, index) { + return value !== lastPosition[index]; + })) { + pannerNode.setPosition.apply(pannerNode, positon); // tslint:disable-line:deprecation + lastPosition = positon; + } + }; + Object.defineProperty(orientationYGainNode.gain, 'defaultValue', { + get: function get() { + return 0; + } + }); + Object.defineProperty(orientationZGainNode.gain, 'defaultValue', { + get: function get() { + return 0; + } + }); + Object.defineProperty(positionXGainNode.gain, 'defaultValue', { + get: function get() { + return 0; + } + }); + Object.defineProperty(positionYGainNode.gain, 'defaultValue', { + get: function get() { + return 0; + } + }); + Object.defineProperty(positionZGainNode.gain, 'defaultValue', { + get: function get() { + return 0; + } + }); + var nativePannerNodeFaker = { + get bufferSize() { + return undefined; + }, + get channelCount() { + return pannerNode.channelCount; + }, + set channelCount(value) { + // Bug #125: Safari does not throw an error yet. + if (value > 2) { + throw createNotSupportedError(); + } + inputGainNode.channelCount = value; + pannerNode.channelCount = value; + }, + get channelCountMode() { + return pannerNode.channelCountMode; + }, + set channelCountMode(value) { + // Bug #126: Safari does not throw an error yet. + if (value === 'max') { + throw createNotSupportedError(); + } + inputGainNode.channelCountMode = value; + pannerNode.channelCountMode = value; + }, + get channelInterpretation() { + return pannerNode.channelInterpretation; + }, + set channelInterpretation(value) { + inputGainNode.channelInterpretation = value; + pannerNode.channelInterpretation = value; + }, + get coneInnerAngle() { + return pannerNode.coneInnerAngle; + }, + set coneInnerAngle(value) { + pannerNode.coneInnerAngle = value; + }, + get coneOuterAngle() { + return pannerNode.coneOuterAngle; + }, + set coneOuterAngle(value) { + pannerNode.coneOuterAngle = value; + }, + get coneOuterGain() { + return pannerNode.coneOuterGain; + }, + set coneOuterGain(value) { + // Bug #127: Safari does not throw an InvalidStateError yet. + if (value < 0 || value > 1) { + throw createInvalidStateError(); + } + pannerNode.coneOuterGain = value; + }, + get context() { + return pannerNode.context; + }, + get distanceModel() { + return pannerNode.distanceModel; + }, + set distanceModel(value) { + pannerNode.distanceModel = value; + }, + get inputs() { + return [inputGainNode]; + }, + get maxDistance() { + return pannerNode.maxDistance; + }, + set maxDistance(value) { + // Bug #128: Safari does not throw an error yet. + if (value < 0) { + throw new RangeError(); + } + pannerNode.maxDistance = value; + }, + get numberOfInputs() { + return pannerNode.numberOfInputs; + }, + get numberOfOutputs() { + return pannerNode.numberOfOutputs; + }, + get orientationX() { + return orientationXGainNode.gain; + }, + get orientationY() { + return orientationYGainNode.gain; + }, + get orientationZ() { + return orientationZGainNode.gain; + }, + get panningModel() { + return pannerNode.panningModel; + }, + set panningModel(value) { + pannerNode.panningModel = value; + }, + get positionX() { + return positionXGainNode.gain; + }, + get positionY() { + return positionYGainNode.gain; + }, + get positionZ() { + return positionZGainNode.gain; + }, + get refDistance() { + return pannerNode.refDistance; + }, + set refDistance(value) { + // Bug #129: Safari does not throw an error yet. + if (value < 0) { + throw new RangeError(); + } + pannerNode.refDistance = value; + }, + get rolloffFactor() { + return pannerNode.rolloffFactor; + }, + set rolloffFactor(value) { + // Bug #130: Safari does not throw an error yet. + if (value < 0) { + throw new RangeError(); + } + pannerNode.rolloffFactor = value; + }, + addEventListener: function addEventListener() { + return inputGainNode.addEventListener(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1], arguments.length <= 2 ? undefined : arguments[2]); + }, + dispatchEvent: function dispatchEvent() { + return inputGainNode.dispatchEvent(arguments.length <= 0 ? undefined : arguments[0]); + }, + removeEventListener: function removeEventListener() { + return inputGainNode.removeEventListener(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1], arguments.length <= 2 ? undefined : arguments[2]); + } + }; + if (coneInnerAngle !== nativePannerNodeFaker.coneInnerAngle) { + nativePannerNodeFaker.coneInnerAngle = coneInnerAngle; + } + if (coneOuterAngle !== nativePannerNodeFaker.coneOuterAngle) { + nativePannerNodeFaker.coneOuterAngle = coneOuterAngle; + } + if (coneOuterGain !== nativePannerNodeFaker.coneOuterGain) { + nativePannerNodeFaker.coneOuterGain = coneOuterGain; + } + if (distanceModel !== nativePannerNodeFaker.distanceModel) { + nativePannerNodeFaker.distanceModel = distanceModel; + } + if (maxDistance !== nativePannerNodeFaker.maxDistance) { + nativePannerNodeFaker.maxDistance = maxDistance; + } + if (orientationX !== nativePannerNodeFaker.orientationX.value) { + nativePannerNodeFaker.orientationX.value = orientationX; + } + if (orientationY !== nativePannerNodeFaker.orientationY.value) { + nativePannerNodeFaker.orientationY.value = orientationY; + } + if (orientationZ !== nativePannerNodeFaker.orientationZ.value) { + nativePannerNodeFaker.orientationZ.value = orientationZ; + } + if (panningModel !== nativePannerNodeFaker.panningModel) { + nativePannerNodeFaker.panningModel = panningModel; + } + if (positionX !== nativePannerNodeFaker.positionX.value) { + nativePannerNodeFaker.positionX.value = positionX; + } + if (positionY !== nativePannerNodeFaker.positionY.value) { + nativePannerNodeFaker.positionY.value = positionY; + } + if (positionZ !== nativePannerNodeFaker.positionZ.value) { + nativePannerNodeFaker.positionZ.value = positionZ; + } + if (refDistance !== nativePannerNodeFaker.refDistance) { + nativePannerNodeFaker.refDistance = refDistance; + } + if (rolloffFactor !== nativePannerNodeFaker.rolloffFactor) { + nativePannerNodeFaker.rolloffFactor = rolloffFactor; + } + if (lastOrientation[0] !== 1 || lastOrientation[1] !== 0 || lastOrientation[2] !== 0) { + pannerNode.setOrientation.apply(pannerNode, _toConsumableArray(lastOrientation)); // tslint:disable-line:deprecation + } + if (lastPosition[0] !== 0 || lastPosition[1] !== 0 || lastPosition[2] !== 0) { + pannerNode.setPosition.apply(pannerNode, _toConsumableArray(lastPosition)); // tslint:disable-line:deprecation + } + var whenConnected = function whenConnected() { + inputGainNode.connect(pannerNode); + // Bug #119: Safari does not fully support the WaveShaperNode. + connectNativeAudioNodeToNativeAudioNode(inputGainNode, waveShaperNode, 0, 0); + waveShaperNode.connect(orientationXGainNode).connect(channelMergerNode, 0, 0); + waveShaperNode.connect(orientationYGainNode).connect(channelMergerNode, 0, 1); + waveShaperNode.connect(orientationZGainNode).connect(channelMergerNode, 0, 2); + waveShaperNode.connect(positionXGainNode).connect(channelMergerNode, 0, 3); + waveShaperNode.connect(positionYGainNode).connect(channelMergerNode, 0, 4); + waveShaperNode.connect(positionZGainNode).connect(channelMergerNode, 0, 5); + channelMergerNode.connect(scriptProcessorNode).connect(nativeContext.destination); + }; + var whenDisconnected = function whenDisconnected() { + inputGainNode.disconnect(pannerNode); + // Bug #119: Safari does not fully support the WaveShaperNode. + disconnectNativeAudioNodeFromNativeAudioNode(inputGainNode, waveShaperNode, 0, 0); + waveShaperNode.disconnect(orientationXGainNode); + orientationXGainNode.disconnect(channelMergerNode); + waveShaperNode.disconnect(orientationYGainNode); + orientationYGainNode.disconnect(channelMergerNode); + waveShaperNode.disconnect(orientationZGainNode); + orientationZGainNode.disconnect(channelMergerNode); + waveShaperNode.disconnect(positionXGainNode); + positionXGainNode.disconnect(channelMergerNode); + waveShaperNode.disconnect(positionYGainNode); + positionYGainNode.disconnect(channelMergerNode); + waveShaperNode.disconnect(positionZGainNode); + positionZGainNode.disconnect(channelMergerNode); + channelMergerNode.disconnect(scriptProcessorNode); + scriptProcessorNode.disconnect(nativeContext.destination); + }; + return monitorConnections(interceptConnections(nativePannerNodeFaker, pannerNode), whenConnected, whenDisconnected); + }; + }; + + var createNativePeriodicWaveFactory = function createNativePeriodicWaveFactory(createIndexSizeError) { + return function (nativeContext, _ref) { + var disableNormalization = _ref.disableNormalization, + imag = _ref.imag, + real = _ref.real; + // Bug #180: Safari does not allow to use ordinary arrays. + var convertedImag = imag instanceof Float32Array ? imag : new Float32Array(imag); + var convertedReal = real instanceof Float32Array ? real : new Float32Array(real); + var nativePeriodicWave = nativeContext.createPeriodicWave(convertedReal, convertedImag, { + disableNormalization: disableNormalization + }); + // Bug #181: Safari does not throw an IndexSizeError so far if the given arrays have less than two values. + if (Array.from(imag).length < 2) { + throw createIndexSizeError(); + } + return nativePeriodicWave; + }; + }; + + var createNativeScriptProcessorNode = function createNativeScriptProcessorNode(nativeContext, bufferSize, numberOfInputChannels, numberOfOutputChannels) { + return nativeContext.createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels); // tslint:disable-line deprecation + }; + + var createNativeStereoPannerNodeFactory = function createNativeStereoPannerNodeFactory(createNativeStereoPannerNodeFaker, createNotSupportedError) { + return function (nativeContext, options) { + var channelCountMode = options.channelCountMode; + /* + * Bug #105: The channelCountMode of 'clamped-max' should be supported. However it is not possible to write a polyfill for Safari + * which supports it and therefore it can't be supported at all. + */ + if (channelCountMode === 'clamped-max') { + throw createNotSupportedError(); + } + // Bug #105: Safari does not support the StereoPannerNode. + if (nativeContext.createStereoPanner === undefined) { + return createNativeStereoPannerNodeFaker(nativeContext, options); + } + var nativeStereoPannerNode = nativeContext.createStereoPanner(); + assignNativeAudioNodeOptions(nativeStereoPannerNode, options); + assignNativeAudioNodeAudioParamValue(nativeStereoPannerNode, options, 'pan'); + /* + * Bug #105: The channelCountMode of 'clamped-max' should be supported. However it is not possible to write a polyfill for Safari + * which supports it and therefore it can't be supported at all. + */ + Object.defineProperty(nativeStereoPannerNode, 'channelCountMode', { + get: function get() { + return channelCountMode; + }, + set: function set(value) { + if (value !== channelCountMode) { + throw createNotSupportedError(); + } + } + }); + return nativeStereoPannerNode; + }; + }; + + var _excluded$1 = ["channelCount", "channelCountMode", "pan"]; + function ownKeys$b(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$b(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$b(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$b(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + var createNativeStereoPannerNodeFakerFactory = function createNativeStereoPannerNodeFakerFactory(createNativeChannelMergerNode, createNativeChannelSplitterNode, createNativeGainNode, createNativeWaveShaperNode, createNotSupportedError, monitorConnections) { + // The curve has a size of 14bit plus 1 value to have an exact representation for zero. This value has been determined experimentally. + var CURVE_SIZE = 16385; + var DC_CURVE = new Float32Array([1, 1]); + var HALF_PI = Math.PI / 2; + var SINGLE_CHANNEL_OPTIONS = { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'discrete' + }; + var SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS = _objectSpread$b(_objectSpread$b({}, SINGLE_CHANNEL_OPTIONS), {}, { + oversample: 'none' + }); + var buildInternalGraphForMono = function buildInternalGraphForMono(nativeContext, inputGainNode, panGainNode, channelMergerNode) { + var leftWaveShaperCurve = new Float32Array(CURVE_SIZE); + var rightWaveShaperCurve = new Float32Array(CURVE_SIZE); + for (var i = 0; i < CURVE_SIZE; i += 1) { + var x = i / (CURVE_SIZE - 1) * HALF_PI; + leftWaveShaperCurve[i] = Math.cos(x); + rightWaveShaperCurve[i] = Math.sin(x); + } + var leftGainNode = createNativeGainNode(nativeContext, _objectSpread$b(_objectSpread$b({}, SINGLE_CHANNEL_OPTIONS), {}, { + gain: 0 + })); + // Bug #119: Safari does not fully support the WaveShaperNode. + var leftWaveShaperNode = createNativeWaveShaperNode(nativeContext, _objectSpread$b(_objectSpread$b({}, SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS), {}, { + curve: leftWaveShaperCurve + })); + // Bug #119: Safari does not fully support the WaveShaperNode. + var panWaveShaperNode = createNativeWaveShaperNode(nativeContext, _objectSpread$b(_objectSpread$b({}, SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS), {}, { + curve: DC_CURVE + })); + var rightGainNode = createNativeGainNode(nativeContext, _objectSpread$b(_objectSpread$b({}, SINGLE_CHANNEL_OPTIONS), {}, { + gain: 0 + })); + // Bug #119: Safari does not fully support the WaveShaperNode. + var rightWaveShaperNode = createNativeWaveShaperNode(nativeContext, _objectSpread$b(_objectSpread$b({}, SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS), {}, { + curve: rightWaveShaperCurve + })); + return { + connectGraph: function connectGraph() { + inputGainNode.connect(leftGainNode); + inputGainNode.connect(panWaveShaperNode.inputs === undefined ? panWaveShaperNode : panWaveShaperNode.inputs[0]); + inputGainNode.connect(rightGainNode); + panWaveShaperNode.connect(panGainNode); + panGainNode.connect(leftWaveShaperNode.inputs === undefined ? leftWaveShaperNode : leftWaveShaperNode.inputs[0]); + panGainNode.connect(rightWaveShaperNode.inputs === undefined ? rightWaveShaperNode : rightWaveShaperNode.inputs[0]); + leftWaveShaperNode.connect(leftGainNode.gain); + rightWaveShaperNode.connect(rightGainNode.gain); + leftGainNode.connect(channelMergerNode, 0, 0); + rightGainNode.connect(channelMergerNode, 0, 1); + }, + disconnectGraph: function disconnectGraph() { + inputGainNode.disconnect(leftGainNode); + inputGainNode.disconnect(panWaveShaperNode.inputs === undefined ? panWaveShaperNode : panWaveShaperNode.inputs[0]); + inputGainNode.disconnect(rightGainNode); + panWaveShaperNode.disconnect(panGainNode); + panGainNode.disconnect(leftWaveShaperNode.inputs === undefined ? leftWaveShaperNode : leftWaveShaperNode.inputs[0]); + panGainNode.disconnect(rightWaveShaperNode.inputs === undefined ? rightWaveShaperNode : rightWaveShaperNode.inputs[0]); + leftWaveShaperNode.disconnect(leftGainNode.gain); + rightWaveShaperNode.disconnect(rightGainNode.gain); + leftGainNode.disconnect(channelMergerNode, 0, 0); + rightGainNode.disconnect(channelMergerNode, 0, 1); + } + }; + }; + var buildInternalGraphForStereo = function buildInternalGraphForStereo(nativeContext, inputGainNode, panGainNode, channelMergerNode) { + var leftInputForLeftOutputWaveShaperCurve = new Float32Array(CURVE_SIZE); + var leftInputForRightOutputWaveShaperCurve = new Float32Array(CURVE_SIZE); + var rightInputForLeftOutputWaveShaperCurve = new Float32Array(CURVE_SIZE); + var rightInputForRightOutputWaveShaperCurve = new Float32Array(CURVE_SIZE); + var centerIndex = Math.floor(CURVE_SIZE / 2); + for (var i = 0; i < CURVE_SIZE; i += 1) { + if (i > centerIndex) { + var x = (i - centerIndex) / (CURVE_SIZE - 1 - centerIndex) * HALF_PI; + leftInputForLeftOutputWaveShaperCurve[i] = Math.cos(x); + leftInputForRightOutputWaveShaperCurve[i] = Math.sin(x); + rightInputForLeftOutputWaveShaperCurve[i] = 0; + rightInputForRightOutputWaveShaperCurve[i] = 1; + } else { + var _x = i / (CURVE_SIZE - 1 - centerIndex) * HALF_PI; + leftInputForLeftOutputWaveShaperCurve[i] = 1; + leftInputForRightOutputWaveShaperCurve[i] = 0; + rightInputForLeftOutputWaveShaperCurve[i] = Math.cos(_x); + rightInputForRightOutputWaveShaperCurve[i] = Math.sin(_x); + } + } + var channelSplitterNode = createNativeChannelSplitterNode(nativeContext, { + channelCount: 2, + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + numberOfOutputs: 2 + }); + var leftInputForLeftOutputGainNode = createNativeGainNode(nativeContext, _objectSpread$b(_objectSpread$b({}, SINGLE_CHANNEL_OPTIONS), {}, { + gain: 0 + })); + // Bug #119: Safari does not fully support the WaveShaperNode. + var leftInputForLeftOutputWaveShaperNode = createNativeWaveShaperNode(nativeContext, _objectSpread$b(_objectSpread$b({}, SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS), {}, { + curve: leftInputForLeftOutputWaveShaperCurve + })); + var leftInputForRightOutputGainNode = createNativeGainNode(nativeContext, _objectSpread$b(_objectSpread$b({}, SINGLE_CHANNEL_OPTIONS), {}, { + gain: 0 + })); + // Bug #119: Safari does not fully support the WaveShaperNode. + var leftInputForRightOutputWaveShaperNode = createNativeWaveShaperNode(nativeContext, _objectSpread$b(_objectSpread$b({}, SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS), {}, { + curve: leftInputForRightOutputWaveShaperCurve + })); + // Bug #119: Safari does not fully support the WaveShaperNode. + var panWaveShaperNode = createNativeWaveShaperNode(nativeContext, _objectSpread$b(_objectSpread$b({}, SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS), {}, { + curve: DC_CURVE + })); + var rightInputForLeftOutputGainNode = createNativeGainNode(nativeContext, _objectSpread$b(_objectSpread$b({}, SINGLE_CHANNEL_OPTIONS), {}, { + gain: 0 + })); + // Bug #119: Safari does not fully support the WaveShaperNode. + var rightInputForLeftOutputWaveShaperNode = createNativeWaveShaperNode(nativeContext, _objectSpread$b(_objectSpread$b({}, SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS), {}, { + curve: rightInputForLeftOutputWaveShaperCurve + })); + var rightInputForRightOutputGainNode = createNativeGainNode(nativeContext, _objectSpread$b(_objectSpread$b({}, SINGLE_CHANNEL_OPTIONS), {}, { + gain: 0 + })); + // Bug #119: Safari does not fully support the WaveShaperNode. + var rightInputForRightOutputWaveShaperNode = createNativeWaveShaperNode(nativeContext, _objectSpread$b(_objectSpread$b({}, SINGLE_CHANNEL_WAVE_SHAPER_OPTIONS), {}, { + curve: rightInputForRightOutputWaveShaperCurve + })); + return { + connectGraph: function connectGraph() { + inputGainNode.connect(channelSplitterNode); + inputGainNode.connect(panWaveShaperNode.inputs === undefined ? panWaveShaperNode : panWaveShaperNode.inputs[0]); + channelSplitterNode.connect(leftInputForLeftOutputGainNode, 0); + channelSplitterNode.connect(leftInputForRightOutputGainNode, 0); + channelSplitterNode.connect(rightInputForLeftOutputGainNode, 1); + channelSplitterNode.connect(rightInputForRightOutputGainNode, 1); + panWaveShaperNode.connect(panGainNode); + panGainNode.connect(leftInputForLeftOutputWaveShaperNode.inputs === undefined ? leftInputForLeftOutputWaveShaperNode : leftInputForLeftOutputWaveShaperNode.inputs[0]); + panGainNode.connect(leftInputForRightOutputWaveShaperNode.inputs === undefined ? leftInputForRightOutputWaveShaperNode : leftInputForRightOutputWaveShaperNode.inputs[0]); + panGainNode.connect(rightInputForLeftOutputWaveShaperNode.inputs === undefined ? rightInputForLeftOutputWaveShaperNode : rightInputForLeftOutputWaveShaperNode.inputs[0]); + panGainNode.connect(rightInputForRightOutputWaveShaperNode.inputs === undefined ? rightInputForRightOutputWaveShaperNode : rightInputForRightOutputWaveShaperNode.inputs[0]); + leftInputForLeftOutputWaveShaperNode.connect(leftInputForLeftOutputGainNode.gain); + leftInputForRightOutputWaveShaperNode.connect(leftInputForRightOutputGainNode.gain); + rightInputForLeftOutputWaveShaperNode.connect(rightInputForLeftOutputGainNode.gain); + rightInputForRightOutputWaveShaperNode.connect(rightInputForRightOutputGainNode.gain); + leftInputForLeftOutputGainNode.connect(channelMergerNode, 0, 0); + rightInputForLeftOutputGainNode.connect(channelMergerNode, 0, 0); + leftInputForRightOutputGainNode.connect(channelMergerNode, 0, 1); + rightInputForRightOutputGainNode.connect(channelMergerNode, 0, 1); + }, + disconnectGraph: function disconnectGraph() { + inputGainNode.disconnect(channelSplitterNode); + inputGainNode.disconnect(panWaveShaperNode.inputs === undefined ? panWaveShaperNode : panWaveShaperNode.inputs[0]); + channelSplitterNode.disconnect(leftInputForLeftOutputGainNode, 0); + channelSplitterNode.disconnect(leftInputForRightOutputGainNode, 0); + channelSplitterNode.disconnect(rightInputForLeftOutputGainNode, 1); + channelSplitterNode.disconnect(rightInputForRightOutputGainNode, 1); + panWaveShaperNode.disconnect(panGainNode); + panGainNode.disconnect(leftInputForLeftOutputWaveShaperNode.inputs === undefined ? leftInputForLeftOutputWaveShaperNode : leftInputForLeftOutputWaveShaperNode.inputs[0]); + panGainNode.disconnect(leftInputForRightOutputWaveShaperNode.inputs === undefined ? leftInputForRightOutputWaveShaperNode : leftInputForRightOutputWaveShaperNode.inputs[0]); + panGainNode.disconnect(rightInputForLeftOutputWaveShaperNode.inputs === undefined ? rightInputForLeftOutputWaveShaperNode : rightInputForLeftOutputWaveShaperNode.inputs[0]); + panGainNode.disconnect(rightInputForRightOutputWaveShaperNode.inputs === undefined ? rightInputForRightOutputWaveShaperNode : rightInputForRightOutputWaveShaperNode.inputs[0]); + leftInputForLeftOutputWaveShaperNode.disconnect(leftInputForLeftOutputGainNode.gain); + leftInputForRightOutputWaveShaperNode.disconnect(leftInputForRightOutputGainNode.gain); + rightInputForLeftOutputWaveShaperNode.disconnect(rightInputForLeftOutputGainNode.gain); + rightInputForRightOutputWaveShaperNode.disconnect(rightInputForRightOutputGainNode.gain); + leftInputForLeftOutputGainNode.disconnect(channelMergerNode, 0, 0); + rightInputForLeftOutputGainNode.disconnect(channelMergerNode, 0, 0); + leftInputForRightOutputGainNode.disconnect(channelMergerNode, 0, 1); + rightInputForRightOutputGainNode.disconnect(channelMergerNode, 0, 1); + } + }; + }; + var buildInternalGraph = function buildInternalGraph(nativeContext, channelCount, inputGainNode, panGainNode, channelMergerNode) { + if (channelCount === 1) { + return buildInternalGraphForMono(nativeContext, inputGainNode, panGainNode, channelMergerNode); + } + if (channelCount === 2) { + return buildInternalGraphForStereo(nativeContext, inputGainNode, panGainNode, channelMergerNode); + } + throw createNotSupportedError(); + }; + return function (nativeContext, _ref) { + var channelCount = _ref.channelCount, + channelCountMode = _ref.channelCountMode, + pan = _ref.pan, + audioNodeOptions = _objectWithoutProperties(_ref, _excluded$1); + if (channelCountMode === 'max') { + throw createNotSupportedError(); + } + var channelMergerNode = createNativeChannelMergerNode(nativeContext, _objectSpread$b(_objectSpread$b({}, audioNodeOptions), {}, { + channelCount: 1, + channelCountMode: channelCountMode, + numberOfInputs: 2 + })); + var inputGainNode = createNativeGainNode(nativeContext, _objectSpread$b(_objectSpread$b({}, audioNodeOptions), {}, { + channelCount: channelCount, + channelCountMode: channelCountMode, + gain: 1 + })); + var panGainNode = createNativeGainNode(nativeContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + gain: pan + }); + var _buildInternalGraph = buildInternalGraph(nativeContext, channelCount, inputGainNode, panGainNode, channelMergerNode), + connectGraph = _buildInternalGraph.connectGraph, + disconnectGraph = _buildInternalGraph.disconnectGraph; + Object.defineProperty(panGainNode.gain, 'defaultValue', { + get: function get() { + return 0; + } + }); + Object.defineProperty(panGainNode.gain, 'maxValue', { + get: function get() { + return 1; + } + }); + Object.defineProperty(panGainNode.gain, 'minValue', { + get: function get() { + return -1; + } + }); + var nativeStereoPannerNodeFakerFactory = { + get bufferSize() { + return undefined; + }, + get channelCount() { + return inputGainNode.channelCount; + }, + set channelCount(value) { + if (inputGainNode.channelCount !== value) { + if (isConnected) { + disconnectGraph(); + } + var _buildInternalGraph2 = buildInternalGraph(nativeContext, value, inputGainNode, panGainNode, channelMergerNode); + connectGraph = _buildInternalGraph2.connectGraph; + disconnectGraph = _buildInternalGraph2.disconnectGraph; + if (isConnected) { + connectGraph(); + } + } + inputGainNode.channelCount = value; + }, + get channelCountMode() { + return inputGainNode.channelCountMode; + }, + set channelCountMode(value) { + if (value === 'clamped-max' || value === 'max') { + throw createNotSupportedError(); + } + inputGainNode.channelCountMode = value; + }, + get channelInterpretation() { + return inputGainNode.channelInterpretation; + }, + set channelInterpretation(value) { + inputGainNode.channelInterpretation = value; + }, + get context() { + return inputGainNode.context; + }, + get inputs() { + return [inputGainNode]; + }, + get numberOfInputs() { + return inputGainNode.numberOfInputs; + }, + get numberOfOutputs() { + return inputGainNode.numberOfOutputs; + }, + get pan() { + return panGainNode.gain; + }, + addEventListener: function addEventListener() { + return inputGainNode.addEventListener(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1], arguments.length <= 2 ? undefined : arguments[2]); + }, + dispatchEvent: function dispatchEvent() { + return inputGainNode.dispatchEvent(arguments.length <= 0 ? undefined : arguments[0]); + }, + removeEventListener: function removeEventListener() { + return inputGainNode.removeEventListener(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1], arguments.length <= 2 ? undefined : arguments[2]); + } + }; + var isConnected = false; + var whenConnected = function whenConnected() { + connectGraph(); + isConnected = true; + }; + var whenDisconnected = function whenDisconnected() { + disconnectGraph(); + isConnected = false; + }; + return monitorConnections(interceptConnections(nativeStereoPannerNodeFakerFactory, channelMergerNode), whenConnected, whenDisconnected); + }; + }; + + var createNativeWaveShaperNodeFactory = function createNativeWaveShaperNodeFactory(createConnectedNativeAudioBufferSourceNode, createInvalidStateError, createNativeWaveShaperNodeFaker, isDCCurve, monitorConnections, nativeAudioContextConstructor, overwriteAccessors) { + return function (nativeContext, options) { + var nativeWaveShaperNode = nativeContext.createWaveShaper(); + /* + * Bug #119: Safari does not correctly map the values. + * @todo Unfortunately there is no way to test for this behavior in a synchronous fashion which is why testing for the existence of + * the webkitAudioContext is used as a workaround here. Testing for the automationRate property is necessary because this workaround + * isn't necessary anymore since v14.0.2 of Safari. + */ + if (nativeAudioContextConstructor !== null && nativeAudioContextConstructor.name === 'webkitAudioContext' && nativeContext.createGain().gain.automationRate === undefined) { + return createNativeWaveShaperNodeFaker(nativeContext, options); + } + assignNativeAudioNodeOptions(nativeWaveShaperNode, options); + var curve = options.curve === null || options.curve instanceof Float32Array ? options.curve : new Float32Array(options.curve); + // Bug #104: Chrome and Edge will throw an InvalidAccessError when the curve has less than two samples. + if (curve !== null && curve.length < 2) { + throw createInvalidStateError(); + } + // Only values of type Float32Array can be assigned to the curve property. + assignNativeAudioNodeOption(nativeWaveShaperNode, { + curve: curve + }, 'curve'); + assignNativeAudioNodeOption(nativeWaveShaperNode, options, 'oversample'); + var disconnectNativeAudioBufferSourceNode = null; + var isConnected = false; + overwriteAccessors(nativeWaveShaperNode, 'curve', function (get) { + return function () { + return get.call(nativeWaveShaperNode); + }; + }, function (set) { + return function (value) { + set.call(nativeWaveShaperNode, value); + if (isConnected) { + if (isDCCurve(value) && disconnectNativeAudioBufferSourceNode === null) { + disconnectNativeAudioBufferSourceNode = createConnectedNativeAudioBufferSourceNode(nativeContext, nativeWaveShaperNode); + } else if (!isDCCurve(value) && disconnectNativeAudioBufferSourceNode !== null) { + disconnectNativeAudioBufferSourceNode(); + disconnectNativeAudioBufferSourceNode = null; + } + } + return value; + }; + }); + var whenConnected = function whenConnected() { + isConnected = true; + if (isDCCurve(nativeWaveShaperNode.curve)) { + disconnectNativeAudioBufferSourceNode = createConnectedNativeAudioBufferSourceNode(nativeContext, nativeWaveShaperNode); + } + }; + var whenDisconnected = function whenDisconnected() { + isConnected = false; + if (disconnectNativeAudioBufferSourceNode !== null) { + disconnectNativeAudioBufferSourceNode(); + disconnectNativeAudioBufferSourceNode = null; + } + }; + return monitorConnections(nativeWaveShaperNode, whenConnected, whenDisconnected); + }; + }; + + var _excluded = ["curve", "oversample"]; + function ownKeys$a(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$a(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$a(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$a(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + var createNativeWaveShaperNodeFakerFactory = function createNativeWaveShaperNodeFakerFactory(createConnectedNativeAudioBufferSourceNode, createInvalidStateError, createNativeGainNode, isDCCurve, monitorConnections) { + return function (nativeContext, _ref) { + var curve = _ref.curve, + oversample = _ref.oversample, + audioNodeOptions = _objectWithoutProperties(_ref, _excluded); + var negativeWaveShaperNode = nativeContext.createWaveShaper(); + var positiveWaveShaperNode = nativeContext.createWaveShaper(); + assignNativeAudioNodeOptions(negativeWaveShaperNode, audioNodeOptions); + assignNativeAudioNodeOptions(positiveWaveShaperNode, audioNodeOptions); + var inputGainNode = createNativeGainNode(nativeContext, _objectSpread$a(_objectSpread$a({}, audioNodeOptions), {}, { + gain: 1 + })); + var invertGainNode = createNativeGainNode(nativeContext, _objectSpread$a(_objectSpread$a({}, audioNodeOptions), {}, { + gain: -1 + })); + var outputGainNode = createNativeGainNode(nativeContext, _objectSpread$a(_objectSpread$a({}, audioNodeOptions), {}, { + gain: 1 + })); + var revertGainNode = createNativeGainNode(nativeContext, _objectSpread$a(_objectSpread$a({}, audioNodeOptions), {}, { + gain: -1 + })); + var disconnectNativeAudioBufferSourceNode = null; + var isConnected = false; + var unmodifiedCurve = null; + var nativeWaveShaperNodeFaker = { + get bufferSize() { + return undefined; + }, + get channelCount() { + return negativeWaveShaperNode.channelCount; + }, + set channelCount(value) { + inputGainNode.channelCount = value; + invertGainNode.channelCount = value; + negativeWaveShaperNode.channelCount = value; + outputGainNode.channelCount = value; + positiveWaveShaperNode.channelCount = value; + revertGainNode.channelCount = value; + }, + get channelCountMode() { + return negativeWaveShaperNode.channelCountMode; + }, + set channelCountMode(value) { + inputGainNode.channelCountMode = value; + invertGainNode.channelCountMode = value; + negativeWaveShaperNode.channelCountMode = value; + outputGainNode.channelCountMode = value; + positiveWaveShaperNode.channelCountMode = value; + revertGainNode.channelCountMode = value; + }, + get channelInterpretation() { + return negativeWaveShaperNode.channelInterpretation; + }, + set channelInterpretation(value) { + inputGainNode.channelInterpretation = value; + invertGainNode.channelInterpretation = value; + negativeWaveShaperNode.channelInterpretation = value; + outputGainNode.channelInterpretation = value; + positiveWaveShaperNode.channelInterpretation = value; + revertGainNode.channelInterpretation = value; + }, + get context() { + return negativeWaveShaperNode.context; + }, + get curve() { + return unmodifiedCurve; + }, + set curve(value) { + // Bug #102: Safari does not throw an InvalidStateError when the curve has less than two samples. + if (value !== null && value.length < 2) { + throw createInvalidStateError(); + } + if (value === null) { + negativeWaveShaperNode.curve = value; + positiveWaveShaperNode.curve = value; + } else { + var curveLength = value.length; + var negativeCurve = new Float32Array(curveLength + 2 - curveLength % 2); + var positiveCurve = new Float32Array(curveLength + 2 - curveLength % 2); + negativeCurve[0] = value[0]; + positiveCurve[0] = -value[curveLength - 1]; + var length = Math.ceil((curveLength + 1) / 2); + var centerIndex = (curveLength + 1) / 2 - 1; + for (var i = 1; i < length; i += 1) { + var theoreticIndex = i / length * centerIndex; + var lowerIndex = Math.floor(theoreticIndex); + var upperIndex = Math.ceil(theoreticIndex); + negativeCurve[i] = lowerIndex === upperIndex ? value[lowerIndex] : (1 - (theoreticIndex - lowerIndex)) * value[lowerIndex] + (1 - (upperIndex - theoreticIndex)) * value[upperIndex]; + positiveCurve[i] = lowerIndex === upperIndex ? -value[curveLength - 1 - lowerIndex] : -((1 - (theoreticIndex - lowerIndex)) * value[curveLength - 1 - lowerIndex]) - (1 - (upperIndex - theoreticIndex)) * value[curveLength - 1 - upperIndex]; + } + negativeCurve[length] = curveLength % 2 === 1 ? value[length - 1] : (value[length - 2] + value[length - 1]) / 2; + negativeWaveShaperNode.curve = negativeCurve; + positiveWaveShaperNode.curve = positiveCurve; + } + unmodifiedCurve = value; + if (isConnected) { + if (isDCCurve(unmodifiedCurve) && disconnectNativeAudioBufferSourceNode === null) { + disconnectNativeAudioBufferSourceNode = createConnectedNativeAudioBufferSourceNode(nativeContext, inputGainNode); + } else if (disconnectNativeAudioBufferSourceNode !== null) { + disconnectNativeAudioBufferSourceNode(); + disconnectNativeAudioBufferSourceNode = null; + } + } + }, + get inputs() { + return [inputGainNode]; + }, + get numberOfInputs() { + return negativeWaveShaperNode.numberOfInputs; + }, + get numberOfOutputs() { + return negativeWaveShaperNode.numberOfOutputs; + }, + get oversample() { + return negativeWaveShaperNode.oversample; + }, + set oversample(value) { + negativeWaveShaperNode.oversample = value; + positiveWaveShaperNode.oversample = value; + }, + addEventListener: function addEventListener() { + return inputGainNode.addEventListener(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1], arguments.length <= 2 ? undefined : arguments[2]); + }, + dispatchEvent: function dispatchEvent() { + return inputGainNode.dispatchEvent(arguments.length <= 0 ? undefined : arguments[0]); + }, + removeEventListener: function removeEventListener() { + return inputGainNode.removeEventListener(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1], arguments.length <= 2 ? undefined : arguments[2]); + } + }; + if (curve !== null) { + // Only values of type Float32Array can be assigned to the curve property. + nativeWaveShaperNodeFaker.curve = curve instanceof Float32Array ? curve : new Float32Array(curve); + } + if (oversample !== nativeWaveShaperNodeFaker.oversample) { + nativeWaveShaperNodeFaker.oversample = oversample; + } + var whenConnected = function whenConnected() { + inputGainNode.connect(negativeWaveShaperNode).connect(outputGainNode); + inputGainNode.connect(invertGainNode).connect(positiveWaveShaperNode).connect(revertGainNode).connect(outputGainNode); + isConnected = true; + if (isDCCurve(unmodifiedCurve)) { + disconnectNativeAudioBufferSourceNode = createConnectedNativeAudioBufferSourceNode(nativeContext, inputGainNode); + } + }; + var whenDisconnected = function whenDisconnected() { + inputGainNode.disconnect(negativeWaveShaperNode); + negativeWaveShaperNode.disconnect(outputGainNode); + inputGainNode.disconnect(invertGainNode); + invertGainNode.disconnect(positiveWaveShaperNode); + positiveWaveShaperNode.disconnect(revertGainNode); + revertGainNode.disconnect(outputGainNode); + isConnected = false; + if (disconnectNativeAudioBufferSourceNode !== null) { + disconnectNativeAudioBufferSourceNode(); + disconnectNativeAudioBufferSourceNode = null; + } + }; + return monitorConnections(interceptConnections(nativeWaveShaperNodeFaker, outputGainNode), whenConnected, whenDisconnected); + }; + }; + + var createNotSupportedError = function createNotSupportedError() { + return new DOMException('', 'NotSupportedError'); + }; + + function ownKeys$9(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$9(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$9(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$9(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$4(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$4() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$4() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$4 = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$5 = { + numberOfChannels: 1 + }; + var createOfflineAudioContextConstructor = function createOfflineAudioContextConstructor(baseAudioContextConstructor, cacheTestResult, createInvalidStateError, createNativeOfflineAudioContext, _startRendering) { + return /*#__PURE__*/function (_baseAudioContextCons) { + function OfflineAudioContext(a, b, c) { + var _this; + _classCallCheck(this, OfflineAudioContext); + var options; + if (typeof a === 'number' && b !== undefined && c !== undefined) { + options = { + length: b, + numberOfChannels: a, + sampleRate: c + }; + } else if (_typeof(a) === 'object') { + options = a; + } else { + throw new Error('The given parameters are not valid.'); + } + var _DEFAULT_OPTIONS$opti = _objectSpread$9(_objectSpread$9({}, DEFAULT_OPTIONS$5), options), + length = _DEFAULT_OPTIONS$opti.length, + numberOfChannels = _DEFAULT_OPTIONS$opti.numberOfChannels, + sampleRate = _DEFAULT_OPTIONS$opti.sampleRate; + var nativeOfflineAudioContext = createNativeOfflineAudioContext(numberOfChannels, length, sampleRate); + // #21 Safari does not support promises and therefore would fire the statechange event before the promise can be resolved. + if (!cacheTestResult(testPromiseSupport, function () { + return testPromiseSupport(nativeOfflineAudioContext); + })) { + nativeOfflineAudioContext.addEventListener('statechange', function () { + var i = 0; + var _delayStateChangeEvent = function delayStateChangeEvent(event) { + if (_this._state === 'running') { + if (i > 0) { + nativeOfflineAudioContext.removeEventListener('statechange', _delayStateChangeEvent); + event.stopImmediatePropagation(); + _this._waitForThePromiseToSettle(event); + } else { + i += 1; + } + } + }; + return _delayStateChangeEvent; + }()); + } + _this = _callSuper$4(this, OfflineAudioContext, [nativeOfflineAudioContext, numberOfChannels]); + _this._length = length; + _this._nativeOfflineAudioContext = nativeOfflineAudioContext; + _this._state = null; + return _this; + } + _inherits(OfflineAudioContext, _baseAudioContextCons); + return _createClass(OfflineAudioContext, [{ + key: "length", + get: function get() { + // Bug #17: Safari does not yet expose the length. + if (this._nativeOfflineAudioContext.length === undefined) { + return this._length; + } + return this._nativeOfflineAudioContext.length; + } + }, { + key: "state", + get: function get() { + return this._state === null ? this._nativeOfflineAudioContext.state : this._state; + } + }, { + key: "startRendering", + value: function startRendering() { + var _this2 = this; + /* + * Bug #9 & #59: It is theoretically possible that startRendering() will first render a partialOfflineAudioContext. Therefore + * the state of the nativeOfflineAudioContext might no transition to running immediately. + */ + if (this._state === 'running') { + return Promise.reject(createInvalidStateError()); + } + this._state = 'running'; + return _startRendering(this.destination, this._nativeOfflineAudioContext)["finally"](function () { + _this2._state = null; + deactivateAudioGraph(_this2); + }); + } + }, { + key: "_waitForThePromiseToSettle", + value: function _waitForThePromiseToSettle(event) { + var _this3 = this; + if (this._state === null) { + this._nativeOfflineAudioContext.dispatchEvent(event); + } else { + setTimeout(function () { + return _this3._waitForThePromiseToSettle(event); + }); + } + } + }]); + }(baseAudioContextConstructor); + }; + + function ownKeys$8(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$8(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$8(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$8(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$3(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$3() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$3() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$3 = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$4 = { + channelCount: 2, + channelCountMode: 'max', + // This attribute has no effect for nodes with no inputs. + channelInterpretation: 'speakers', + // This attribute has no effect for nodes with no inputs. + detune: 0, + frequency: 440, + periodicWave: undefined, + type: 'sine' + }; + var createOscillatorNodeConstructor = function createOscillatorNodeConstructor(audioNodeConstructor, createAudioParam, createNativeOscillatorNode, createOscillatorNodeRenderer, getNativeContext, isNativeOfflineAudioContext, wrapEventListener) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function OscillatorNode(context, options) { + var _this; + _classCallCheck(this, OscillatorNode); + var nativeContext = getNativeContext(context); + var mergedOptions = _objectSpread$8(_objectSpread$8({}, DEFAULT_OPTIONS$4), options); + var nativeOscillatorNode = createNativeOscillatorNode(nativeContext, mergedOptions); + var isOffline = isNativeOfflineAudioContext(nativeContext); + var oscillatorNodeRenderer = isOffline ? createOscillatorNodeRenderer() : null; + var nyquist = context.sampleRate / 2; + _this = _callSuper$3(this, OscillatorNode, [context, false, nativeOscillatorNode, oscillatorNodeRenderer]); + // Bug #81: Firefox & Safari do not export the correct values for maxValue and minValue. + _this._detune = createAudioParam(_this, isOffline, nativeOscillatorNode.detune, 153600, -153600); + // Bug #76: Safari does not export the correct values for maxValue and minValue. + _this._frequency = createAudioParam(_this, isOffline, nativeOscillatorNode.frequency, nyquist, -nyquist); + _this._nativeOscillatorNode = nativeOscillatorNode; + _this._onended = null; + _this._oscillatorNodeRenderer = oscillatorNodeRenderer; + if (_this._oscillatorNodeRenderer !== null && mergedOptions.periodicWave !== undefined) { + _this._oscillatorNodeRenderer.periodicWave = mergedOptions.periodicWave; + } + return _this; + } + _inherits(OscillatorNode, _audioNodeConstructor); + return _createClass(OscillatorNode, [{ + key: "detune", + get: function get() { + return this._detune; + } + }, { + key: "frequency", + get: function get() { + return this._frequency; + } + }, { + key: "onended", + get: function get() { + return this._onended; + }, + set: function set(value) { + var wrappedListener = typeof value === 'function' ? wrapEventListener(this, value) : null; + this._nativeOscillatorNode.onended = wrappedListener; + var nativeOnEnded = this._nativeOscillatorNode.onended; + this._onended = nativeOnEnded !== null && nativeOnEnded === wrappedListener ? value : nativeOnEnded; + } + }, { + key: "type", + get: function get() { + return this._nativeOscillatorNode.type; + }, + set: function set(value) { + this._nativeOscillatorNode.type = value; + if (this._oscillatorNodeRenderer !== null) { + this._oscillatorNodeRenderer.periodicWave = null; + } + } + }, { + key: "setPeriodicWave", + value: function setPeriodicWave(periodicWave) { + this._nativeOscillatorNode.setPeriodicWave(periodicWave); + if (this._oscillatorNodeRenderer !== null) { + this._oscillatorNodeRenderer.periodicWave = periodicWave; + } + } + }, { + key: "start", + value: function start() { + var _this2 = this; + var when = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + this._nativeOscillatorNode.start(when); + if (this._oscillatorNodeRenderer !== null) { + this._oscillatorNodeRenderer.start = when; + } + if (this.context.state !== 'closed') { + setInternalStateToActive(this); + var _resetInternalStateToPassive = function resetInternalStateToPassive() { + _this2._nativeOscillatorNode.removeEventListener('ended', _resetInternalStateToPassive); + if (isActiveAudioNode(_this2)) { + setInternalStateToPassive(_this2); + } + }; + this._nativeOscillatorNode.addEventListener('ended', _resetInternalStateToPassive); + } + } + }, { + key: "stop", + value: function stop() { + var when = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + this._nativeOscillatorNode.stop(when); + if (this._oscillatorNodeRenderer !== null) { + this._oscillatorNodeRenderer.stop = when; + } + } + }]); + }(audioNodeConstructor); + }; + + var createOscillatorNodeRendererFactory = function createOscillatorNodeRendererFactory(connectAudioParam, createNativeOscillatorNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) { + return function () { + var renderedNativeOscillatorNodes = new WeakMap(); + var periodicWave = null; + var start = null; + var stop = null; + var createOscillatorNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(proxy, nativeOfflineAudioContext) { + var nativeOscillatorNode, nativeOscillatorNodeIsOwnedByContext, options; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + nativeOscillatorNode = getNativeAudioNode(proxy); // If the initially used nativeOscillatorNode was not constructed on the same OfflineAudioContext it needs to be created again. + nativeOscillatorNodeIsOwnedByContext = isOwnedByContext(nativeOscillatorNode, nativeOfflineAudioContext); + if (!nativeOscillatorNodeIsOwnedByContext) { + options = { + channelCount: nativeOscillatorNode.channelCount, + channelCountMode: nativeOscillatorNode.channelCountMode, + channelInterpretation: nativeOscillatorNode.channelInterpretation, + detune: nativeOscillatorNode.detune.value, + frequency: nativeOscillatorNode.frequency.value, + periodicWave: periodicWave === null ? undefined : periodicWave, + type: nativeOscillatorNode.type + }; + nativeOscillatorNode = createNativeOscillatorNode(nativeOfflineAudioContext, options); + if (start !== null) { + nativeOscillatorNode.start(start); + } + if (stop !== null) { + nativeOscillatorNode.stop(stop); + } + } + renderedNativeOscillatorNodes.set(nativeOfflineAudioContext, nativeOscillatorNode); + if (nativeOscillatorNodeIsOwnedByContext) { + _context.next = 11; + break; + } + _context.next = 7; + return renderAutomation(nativeOfflineAudioContext, proxy.detune, nativeOscillatorNode.detune); + case 7: + _context.next = 9; + return renderAutomation(nativeOfflineAudioContext, proxy.frequency, nativeOscillatorNode.frequency); + case 9: + _context.next = 15; + break; + case 11: + _context.next = 13; + return connectAudioParam(nativeOfflineAudioContext, proxy.detune, nativeOscillatorNode.detune); + case 13: + _context.next = 15; + return connectAudioParam(nativeOfflineAudioContext, proxy.frequency, nativeOscillatorNode.frequency); + case 15: + _context.next = 17; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeOscillatorNode); + case 17: + return _context.abrupt("return", nativeOscillatorNode); + case 18: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createOscillatorNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + set periodicWave(value) { + periodicWave = value; + }, + set start(value) { + start = value; + }, + set stop(value) { + stop = value; + }, + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeOscillatorNode = renderedNativeOscillatorNodes.get(nativeOfflineAudioContext); + if (renderedNativeOscillatorNode !== undefined) { + return Promise.resolve(renderedNativeOscillatorNode); + } + return createOscillatorNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + function ownKeys$7(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$7(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$7(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$7(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$2(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$2() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$2() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$2 = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$3 = { + channelCount: 2, + channelCountMode: 'clamped-max', + channelInterpretation: 'speakers', + coneInnerAngle: 360, + coneOuterAngle: 360, + coneOuterGain: 0, + distanceModel: 'inverse', + maxDistance: 10000, + orientationX: 1, + orientationY: 0, + orientationZ: 0, + panningModel: 'equalpower', + positionX: 0, + positionY: 0, + positionZ: 0, + refDistance: 1, + rolloffFactor: 1 + }; + var createPannerNodeConstructor = function createPannerNodeConstructor(audioNodeConstructor, createAudioParam, createNativePannerNode, createPannerNodeRenderer, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function PannerNode(context, options) { + var _this; + _classCallCheck(this, PannerNode); + var nativeContext = getNativeContext(context); + var mergedOptions = _objectSpread$7(_objectSpread$7({}, DEFAULT_OPTIONS$3), options); + var nativePannerNode = createNativePannerNode(nativeContext, mergedOptions); + var isOffline = isNativeOfflineAudioContext(nativeContext); + var pannerNodeRenderer = isOffline ? createPannerNodeRenderer() : null; + _this = _callSuper$2(this, PannerNode, [context, false, nativePannerNode, pannerNodeRenderer]); + _this._nativePannerNode = nativePannerNode; + // Bug #74: Safari does not export the correct values for maxValue and minValue. + _this._orientationX = createAudioParam(_this, isOffline, nativePannerNode.orientationX, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT); + _this._orientationY = createAudioParam(_this, isOffline, nativePannerNode.orientationY, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT); + _this._orientationZ = createAudioParam(_this, isOffline, nativePannerNode.orientationZ, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT); + _this._positionX = createAudioParam(_this, isOffline, nativePannerNode.positionX, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT); + _this._positionY = createAudioParam(_this, isOffline, nativePannerNode.positionY, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT); + _this._positionZ = createAudioParam(_this, isOffline, nativePannerNode.positionZ, MOST_POSITIVE_SINGLE_FLOAT, MOST_NEGATIVE_SINGLE_FLOAT); + // @todo Determine a meaningful tail-time instead of just using one second. + setAudioNodeTailTime(_this, 1); + return _this; + } + _inherits(PannerNode, _audioNodeConstructor); + return _createClass(PannerNode, [{ + key: "coneInnerAngle", + get: function get() { + return this._nativePannerNode.coneInnerAngle; + }, + set: function set(value) { + this._nativePannerNode.coneInnerAngle = value; + } + }, { + key: "coneOuterAngle", + get: function get() { + return this._nativePannerNode.coneOuterAngle; + }, + set: function set(value) { + this._nativePannerNode.coneOuterAngle = value; + } + }, { + key: "coneOuterGain", + get: function get() { + return this._nativePannerNode.coneOuterGain; + }, + set: function set(value) { + this._nativePannerNode.coneOuterGain = value; + } + }, { + key: "distanceModel", + get: function get() { + return this._nativePannerNode.distanceModel; + }, + set: function set(value) { + this._nativePannerNode.distanceModel = value; + } + }, { + key: "maxDistance", + get: function get() { + return this._nativePannerNode.maxDistance; + }, + set: function set(value) { + this._nativePannerNode.maxDistance = value; + } + }, { + key: "orientationX", + get: function get() { + return this._orientationX; + } + }, { + key: "orientationY", + get: function get() { + return this._orientationY; + } + }, { + key: "orientationZ", + get: function get() { + return this._orientationZ; + } + }, { + key: "panningModel", + get: function get() { + return this._nativePannerNode.panningModel; + }, + set: function set(value) { + this._nativePannerNode.panningModel = value; + } + }, { + key: "positionX", + get: function get() { + return this._positionX; + } + }, { + key: "positionY", + get: function get() { + return this._positionY; + } + }, { + key: "positionZ", + get: function get() { + return this._positionZ; + } + }, { + key: "refDistance", + get: function get() { + return this._nativePannerNode.refDistance; + }, + set: function set(value) { + this._nativePannerNode.refDistance = value; + } + }, { + key: "rolloffFactor", + get: function get() { + return this._nativePannerNode.rolloffFactor; + }, + set: function set(value) { + this._nativePannerNode.rolloffFactor = value; + } + }]); + }(audioNodeConstructor); + }; + + function ownKeys$6(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$6(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$6(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$6(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + var createPannerNodeRendererFactory = function createPannerNodeRendererFactory(connectAudioParam, createNativeChannelMergerNode, createNativeConstantSourceNode, createNativeGainNode, createNativePannerNode, getNativeAudioNode, nativeOfflineAudioContextConstructor, renderAutomation, renderInputsOfAudioNode, renderNativeOfflineAudioContext) { + return function () { + var renderedNativeAudioNodes = new WeakMap(); + var renderedBufferPromise = null; + var createAudioNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(proxy, nativeOfflineAudioContext) { + var nativeGainNode, nativePannerNode, commonAudioNodeOptions, commonNativePannerNodeOptions, nativePannerNodeIsOwnedByContext, options, partialOfflineAudioContext, nativeChannelMergerNode, renderedBuffer, inputGainNode, channelDatas, i, lastOrientation, lastPosition, gateGainNode, partialPannerNode, _i, orientation, positon, currentTime; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + nativeGainNode = null; + nativePannerNode = getNativeAudioNode(proxy); + commonAudioNodeOptions = { + channelCount: nativePannerNode.channelCount, + channelCountMode: nativePannerNode.channelCountMode, + channelInterpretation: nativePannerNode.channelInterpretation + }; + commonNativePannerNodeOptions = _objectSpread$6(_objectSpread$6({}, commonAudioNodeOptions), {}, { + coneInnerAngle: nativePannerNode.coneInnerAngle, + coneOuterAngle: nativePannerNode.coneOuterAngle, + coneOuterGain: nativePannerNode.coneOuterGain, + distanceModel: nativePannerNode.distanceModel, + maxDistance: nativePannerNode.maxDistance, + panningModel: nativePannerNode.panningModel, + refDistance: nativePannerNode.refDistance, + rolloffFactor: nativePannerNode.rolloffFactor + }); // If the initially used nativePannerNode was not constructed on the same OfflineAudioContext it needs to be created again. + nativePannerNodeIsOwnedByContext = isOwnedByContext(nativePannerNode, nativeOfflineAudioContext); // Bug #124: Safari does not support modifying the orientation and the position with AudioParams. + if ('bufferSize' in nativePannerNode) { + nativeGainNode = createNativeGainNode(nativeOfflineAudioContext, _objectSpread$6(_objectSpread$6({}, commonAudioNodeOptions), {}, { + gain: 1 + })); + } else if (!nativePannerNodeIsOwnedByContext) { + options = _objectSpread$6(_objectSpread$6({}, commonNativePannerNodeOptions), {}, { + orientationX: nativePannerNode.orientationX.value, + orientationY: nativePannerNode.orientationY.value, + orientationZ: nativePannerNode.orientationZ.value, + positionX: nativePannerNode.positionX.value, + positionY: nativePannerNode.positionY.value, + positionZ: nativePannerNode.positionZ.value + }); + nativePannerNode = createNativePannerNode(nativeOfflineAudioContext, options); + } + renderedNativeAudioNodes.set(nativeOfflineAudioContext, nativeGainNode === null ? nativePannerNode : nativeGainNode); + if (!(nativeGainNode !== null)) { + _context3.next = 31; + break; + } + if (!(renderedBufferPromise === null)) { + _context3.next = 15; + break; + } + if (!(nativeOfflineAudioContextConstructor === null)) { + _context3.next = 11; + break; + } + throw new Error('Missing the native OfflineAudioContext constructor.'); + case 11: + partialOfflineAudioContext = new nativeOfflineAudioContextConstructor(6, + // Bug #17: Safari does not yet expose the length. + proxy.context.length, nativeOfflineAudioContext.sampleRate); + nativeChannelMergerNode = createNativeChannelMergerNode(partialOfflineAudioContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'speakers', + numberOfInputs: 6 + }); + nativeChannelMergerNode.connect(partialOfflineAudioContext.destination); + renderedBufferPromise = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { + var nativeConstantSourceNodes, i; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return Promise.all([proxy.orientationX, proxy.orientationY, proxy.orientationZ, proxy.positionX, proxy.positionY, proxy.positionZ].map(/*#__PURE__*/function () { + var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(audioParam, index) { + var nativeConstantSourceNode; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + nativeConstantSourceNode = createNativeConstantSourceNode(partialOfflineAudioContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + offset: index === 0 ? 1 : 0 + }); + _context.next = 3; + return renderAutomation(partialOfflineAudioContext, audioParam, nativeConstantSourceNode.offset); + case 3: + return _context.abrupt("return", nativeConstantSourceNode); + case 4: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x3, _x4) { + return _ref3.apply(this, arguments); + }; + }())); + case 2: + nativeConstantSourceNodes = _context2.sent; + for (i = 0; i < 6; i += 1) { + nativeConstantSourceNodes[i].connect(nativeChannelMergerNode, 0, i); + nativeConstantSourceNodes[i].start(0); + } + return _context2.abrupt("return", renderNativeOfflineAudioContext(partialOfflineAudioContext)); + case 5: + case "end": + return _context2.stop(); + } + }, _callee2); + }))(); + case 15: + _context3.next = 17; + return renderedBufferPromise; + case 17: + renderedBuffer = _context3.sent; + inputGainNode = createNativeGainNode(nativeOfflineAudioContext, _objectSpread$6(_objectSpread$6({}, commonAudioNodeOptions), {}, { + gain: 1 + })); + _context3.next = 21; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, inputGainNode); + case 21: + channelDatas = []; + for (i = 0; i < renderedBuffer.numberOfChannels; i += 1) { + channelDatas.push(renderedBuffer.getChannelData(i)); + } + lastOrientation = [channelDatas[0][0], channelDatas[1][0], channelDatas[2][0]]; + lastPosition = [channelDatas[3][0], channelDatas[4][0], channelDatas[5][0]]; + gateGainNode = createNativeGainNode(nativeOfflineAudioContext, _objectSpread$6(_objectSpread$6({}, commonAudioNodeOptions), {}, { + gain: 1 + })); + partialPannerNode = createNativePannerNode(nativeOfflineAudioContext, _objectSpread$6(_objectSpread$6({}, commonNativePannerNodeOptions), {}, { + orientationX: lastOrientation[0], + orientationY: lastOrientation[1], + orientationZ: lastOrientation[2], + positionX: lastPosition[0], + positionY: lastPosition[1], + positionZ: lastPosition[2] + })); + inputGainNode.connect(gateGainNode).connect(partialPannerNode.inputs[0]); + partialPannerNode.connect(nativeGainNode); + for (_i = 128; _i < renderedBuffer.length; _i += 128) { + orientation = [channelDatas[0][_i], channelDatas[1][_i], channelDatas[2][_i]]; + positon = [channelDatas[3][_i], channelDatas[4][_i], channelDatas[5][_i]]; + if (orientation.some(function (value, index) { + return value !== lastOrientation[index]; + }) || positon.some(function (value, index) { + return value !== lastPosition[index]; + })) { + lastOrientation = orientation; + lastPosition = positon; + currentTime = _i / nativeOfflineAudioContext.sampleRate; + gateGainNode.gain.setValueAtTime(0, currentTime); + gateGainNode = createNativeGainNode(nativeOfflineAudioContext, _objectSpread$6(_objectSpread$6({}, commonAudioNodeOptions), {}, { + gain: 0 + })); + partialPannerNode = createNativePannerNode(nativeOfflineAudioContext, _objectSpread$6(_objectSpread$6({}, commonNativePannerNodeOptions), {}, { + orientationX: lastOrientation[0], + orientationY: lastOrientation[1], + orientationZ: lastOrientation[2], + positionX: lastPosition[0], + positionY: lastPosition[1], + positionZ: lastPosition[2] + })); + gateGainNode.gain.setValueAtTime(1, currentTime); + inputGainNode.connect(gateGainNode).connect(partialPannerNode.inputs[0]); + partialPannerNode.connect(nativeGainNode); + } + } + return _context3.abrupt("return", nativeGainNode); + case 31: + if (nativePannerNodeIsOwnedByContext) { + _context3.next = 46; + break; + } + _context3.next = 34; + return renderAutomation(nativeOfflineAudioContext, proxy.orientationX, nativePannerNode.orientationX); + case 34: + _context3.next = 36; + return renderAutomation(nativeOfflineAudioContext, proxy.orientationY, nativePannerNode.orientationY); + case 36: + _context3.next = 38; + return renderAutomation(nativeOfflineAudioContext, proxy.orientationZ, nativePannerNode.orientationZ); + case 38: + _context3.next = 40; + return renderAutomation(nativeOfflineAudioContext, proxy.positionX, nativePannerNode.positionX); + case 40: + _context3.next = 42; + return renderAutomation(nativeOfflineAudioContext, proxy.positionY, nativePannerNode.positionY); + case 42: + _context3.next = 44; + return renderAutomation(nativeOfflineAudioContext, proxy.positionZ, nativePannerNode.positionZ); + case 44: + _context3.next = 58; + break; + case 46: + _context3.next = 48; + return connectAudioParam(nativeOfflineAudioContext, proxy.orientationX, nativePannerNode.orientationX); + case 48: + _context3.next = 50; + return connectAudioParam(nativeOfflineAudioContext, proxy.orientationY, nativePannerNode.orientationY); + case 50: + _context3.next = 52; + return connectAudioParam(nativeOfflineAudioContext, proxy.orientationZ, nativePannerNode.orientationZ); + case 52: + _context3.next = 54; + return connectAudioParam(nativeOfflineAudioContext, proxy.positionX, nativePannerNode.positionX); + case 54: + _context3.next = 56; + return connectAudioParam(nativeOfflineAudioContext, proxy.positionY, nativePannerNode.positionY); + case 56: + _context3.next = 58; + return connectAudioParam(nativeOfflineAudioContext, proxy.positionZ, nativePannerNode.positionZ); + case 58: + if (!isNativeAudioNodeFaker(nativePannerNode)) { + _context3.next = 63; + break; + } + _context3.next = 61; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativePannerNode.inputs[0]); + case 61: + _context3.next = 65; + break; + case 63: + _context3.next = 65; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativePannerNode); + case 65: + return _context3.abrupt("return", nativePannerNode); + case 66: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return function createAudioNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeGainNodeOrNativePannerNode = renderedNativeAudioNodes.get(nativeOfflineAudioContext); + if (renderedNativeGainNodeOrNativePannerNode !== undefined) { + return Promise.resolve(renderedNativeGainNodeOrNativePannerNode); + } + return createAudioNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + function ownKeys$5(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$5(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$5(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$5(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + var DEFAULT_OPTIONS$2 = { + disableNormalization: false + }; + var createPeriodicWaveConstructor = function createPeriodicWaveConstructor(createNativePeriodicWave, getNativeContext, periodicWaveStore, sanitizePeriodicWaveOptions) { + return /*#__PURE__*/function () { + function PeriodicWave(context, options) { + _classCallCheck(this, PeriodicWave); + var nativeContext = getNativeContext(context); + var mergedOptions = sanitizePeriodicWaveOptions(_objectSpread$5(_objectSpread$5({}, DEFAULT_OPTIONS$2), options)); + var periodicWave = createNativePeriodicWave(nativeContext, mergedOptions); + periodicWaveStore.add(periodicWave); + // This does violate all good pratices but it is used here to simplify the handling of periodic waves. + return periodicWave; + } + return _createClass(PeriodicWave, null, [{ + key: Symbol.hasInstance, + value: function value(instance) { + return instance !== null && _typeof(instance) === 'object' && Object.getPrototypeOf(instance) === PeriodicWave.prototype || periodicWaveStore.has(instance); + } + }]); + }(); + }; + + var createRenderAutomation = function createRenderAutomation(getAudioParamRenderer, renderInputsOfAudioParam) { + return function (nativeOfflineAudioContext, audioParam, nativeAudioParam) { + var audioParamRenderer = getAudioParamRenderer(audioParam); + audioParamRenderer.replay(nativeAudioParam); + return renderInputsOfAudioParam(audioParam, nativeOfflineAudioContext, nativeAudioParam); + }; + }; + + var createRenderInputsOfAudioNode = function createRenderInputsOfAudioNode(getAudioNodeConnections, getAudioNodeRenderer, isPartOfACycle) { + return /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(audioNode, nativeOfflineAudioContext, nativeAudioNode) { + var audioNodeConnections; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + audioNodeConnections = getAudioNodeConnections(audioNode); + _context2.next = 3; + return Promise.all(audioNodeConnections.activeInputs.map(function (connections, input) { + return Array.from(connections).map(/*#__PURE__*/function () { + var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref2) { + var _ref4, source, output, audioNodeRenderer, renderedNativeAudioNode, destination; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _ref4 = _slicedToArray(_ref2, 2), source = _ref4[0], output = _ref4[1]; + audioNodeRenderer = getAudioNodeRenderer(source); + _context.next = 4; + return audioNodeRenderer.render(source, nativeOfflineAudioContext); + case 4: + renderedNativeAudioNode = _context.sent; + destination = audioNode.context.destination; + if (!isPartOfACycle(source) && (audioNode !== destination || !isPartOfACycle(audioNode))) { + renderedNativeAudioNode.connect(nativeAudioNode, output, input); + } + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x4) { + return _ref3.apply(this, arguments); + }; + }()); + }).reduce(function (allRenderingPromises, renderingPromises) { + return [].concat(_toConsumableArray(allRenderingPromises), _toConsumableArray(renderingPromises)); + }, [])); + case 3: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x, _x2, _x3) { + return _ref.apply(this, arguments); + }; + }(); + }; + + var createRenderInputsOfAudioParam = function createRenderInputsOfAudioParam(getAudioNodeRenderer, getAudioParamConnections, isPartOfACycle) { + return /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(audioParam, nativeOfflineAudioContext, nativeAudioParam) { + var audioParamConnections; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + audioParamConnections = getAudioParamConnections(audioParam); + _context2.next = 3; + return Promise.all(Array.from(audioParamConnections.activeInputs).map(/*#__PURE__*/function () { + var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref2) { + var _ref4, source, output, audioNodeRenderer, renderedNativeAudioNode; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _ref4 = _slicedToArray(_ref2, 2), source = _ref4[0], output = _ref4[1]; + audioNodeRenderer = getAudioNodeRenderer(source); + _context.next = 4; + return audioNodeRenderer.render(source, nativeOfflineAudioContext); + case 4: + renderedNativeAudioNode = _context.sent; + if (!isPartOfACycle(source)) { + renderedNativeAudioNode.connect(nativeAudioParam, output); + } + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x4) { + return _ref3.apply(this, arguments); + }; + }())); + case 3: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x, _x2, _x3) { + return _ref.apply(this, arguments); + }; + }(); + }; + + var createRenderNativeOfflineAudioContext = function createRenderNativeOfflineAudioContext(cacheTestResult, createNativeGainNode, createNativeScriptProcessorNode, testOfflineAudioContextCurrentTimeSupport) { + return function (nativeOfflineAudioContext) { + // Bug #21: Safari does not support promises yet. + if (cacheTestResult(testPromiseSupport, function () { + return testPromiseSupport(nativeOfflineAudioContext); + })) { + // Bug #158: Chrome and Edge do not advance currentTime if it is not accessed while rendering the audio. + return Promise.resolve(cacheTestResult(testOfflineAudioContextCurrentTimeSupport, testOfflineAudioContextCurrentTimeSupport)).then(function (isOfflineAudioContextCurrentTimeSupported) { + if (!isOfflineAudioContextCurrentTimeSupported) { + var scriptProcessorNode = createNativeScriptProcessorNode(nativeOfflineAudioContext, 512, 0, 1); + nativeOfflineAudioContext.oncomplete = function () { + scriptProcessorNode.onaudioprocess = null; // tslint:disable-line:deprecation + scriptProcessorNode.disconnect(); + }; + scriptProcessorNode.onaudioprocess = function () { + return nativeOfflineAudioContext.currentTime; + }; // tslint:disable-line:deprecation + scriptProcessorNode.connect(nativeOfflineAudioContext.destination); + } + return nativeOfflineAudioContext.startRendering(); + }); + } + return new Promise(function (resolve) { + // Bug #48: Safari does not render an OfflineAudioContext without any connected node. + var gainNode = createNativeGainNode(nativeOfflineAudioContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + gain: 0 + }); + nativeOfflineAudioContext.oncomplete = function (event) { + gainNode.disconnect(); + resolve(event.renderedBuffer); + }; + gainNode.connect(nativeOfflineAudioContext.destination); + nativeOfflineAudioContext.startRendering(); + }); + }; + }; + + var createSetActiveAudioWorkletNodeInputs = function createSetActiveAudioWorkletNodeInputs(activeAudioWorkletNodeInputsStore) { + return function (nativeAudioWorkletNode, activeInputs) { + activeAudioWorkletNodeInputsStore.set(nativeAudioWorkletNode, activeInputs); + }; + }; + + var createSetAudioNodeTailTime = function createSetAudioNodeTailTime(audioNodeTailTimeStore) { + return function (audioNode, tailTime) { + return audioNodeTailTimeStore.set(audioNode, tailTime); + }; + }; + + var createStartRendering = function createStartRendering(audioBufferStore, cacheTestResult, getAudioNodeRenderer, getUnrenderedAudioWorkletNodes, renderNativeOfflineAudioContext, testAudioBufferCopyChannelMethodsOutOfBoundsSupport, wrapAudioBufferCopyChannelMethods, wrapAudioBufferCopyChannelMethodsOutOfBounds) { + return function (destination, nativeOfflineAudioContext) { + return getAudioNodeRenderer(destination).render(destination, nativeOfflineAudioContext) + /* + * Bug #86 & #87: Invoking the renderer of an AudioWorkletNode might be necessary if it has no direct or indirect connection to the + * destination. + */.then(function () { + return Promise.all(Array.from(getUnrenderedAudioWorkletNodes(nativeOfflineAudioContext)).map(function (audioWorkletNode) { + return getAudioNodeRenderer(audioWorkletNode).render(audioWorkletNode, nativeOfflineAudioContext); + })); + }).then(function () { + return renderNativeOfflineAudioContext(nativeOfflineAudioContext); + }).then(function (audioBuffer) { + // Bug #5: Safari does not support copyFromChannel() and copyToChannel(). + // Bug #100: Safari does throw a wrong error when calling getChannelData() with an out-of-bounds value. + if (typeof audioBuffer.copyFromChannel !== 'function') { + wrapAudioBufferCopyChannelMethods(audioBuffer); + wrapAudioBufferGetChannelDataMethod(audioBuffer); + // Bug #157: Firefox does not allow the bufferOffset to be out-of-bounds. + } else if (!cacheTestResult(testAudioBufferCopyChannelMethodsOutOfBoundsSupport, function () { + return testAudioBufferCopyChannelMethodsOutOfBoundsSupport(audioBuffer); + })) { + wrapAudioBufferCopyChannelMethodsOutOfBounds(audioBuffer); + } + audioBufferStore.add(audioBuffer); + return audioBuffer; + }); + }; + }; + + function ownKeys$4(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$4(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$4(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper$1(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$1() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct$1() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$1 = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS$1 = { + channelCount: 2, + /* + * Bug #105: The channelCountMode should be 'clamped-max' according to the spec but is set to 'explicit' to achieve consistent + * behavior. + */ + channelCountMode: 'explicit', + channelInterpretation: 'speakers', + pan: 0 + }; + var createStereoPannerNodeConstructor = function createStereoPannerNodeConstructor(audioNodeConstructor, createAudioParam, createNativeStereoPannerNode, createStereoPannerNodeRenderer, getNativeContext, isNativeOfflineAudioContext) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function StereoPannerNode(context, options) { + var _this; + _classCallCheck(this, StereoPannerNode); + var nativeContext = getNativeContext(context); + var mergedOptions = _objectSpread$4(_objectSpread$4({}, DEFAULT_OPTIONS$1), options); + var nativeStereoPannerNode = createNativeStereoPannerNode(nativeContext, mergedOptions); + var isOffline = isNativeOfflineAudioContext(nativeContext); + var stereoPannerNodeRenderer = isOffline ? createStereoPannerNodeRenderer() : null; + _this = _callSuper$1(this, StereoPannerNode, [context, false, nativeStereoPannerNode, stereoPannerNodeRenderer]); + _this._pan = createAudioParam(_this, isOffline, nativeStereoPannerNode.pan); + return _this; + } + _inherits(StereoPannerNode, _audioNodeConstructor); + return _createClass(StereoPannerNode, [{ + key: "pan", + get: function get() { + return this._pan; + } + }]); + }(audioNodeConstructor); + }; + + var createStereoPannerNodeRendererFactory = function createStereoPannerNodeRendererFactory(connectAudioParam, createNativeStereoPannerNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode) { + return function () { + var renderedNativeStereoPannerNodes = new WeakMap(); + var createStereoPannerNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(proxy, nativeOfflineAudioContext) { + var nativeStereoPannerNode, nativeStereoPannerNodeIsOwnedByContext, options; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + nativeStereoPannerNode = getNativeAudioNode(proxy); + /* + * If the initially used nativeStereoPannerNode was not constructed on the same OfflineAudioContext it needs to be created + * again. + */ + nativeStereoPannerNodeIsOwnedByContext = isOwnedByContext(nativeStereoPannerNode, nativeOfflineAudioContext); + if (!nativeStereoPannerNodeIsOwnedByContext) { + options = { + channelCount: nativeStereoPannerNode.channelCount, + channelCountMode: nativeStereoPannerNode.channelCountMode, + channelInterpretation: nativeStereoPannerNode.channelInterpretation, + pan: nativeStereoPannerNode.pan.value + }; + nativeStereoPannerNode = createNativeStereoPannerNode(nativeOfflineAudioContext, options); + } + renderedNativeStereoPannerNodes.set(nativeOfflineAudioContext, nativeStereoPannerNode); + if (nativeStereoPannerNodeIsOwnedByContext) { + _context.next = 9; + break; + } + _context.next = 7; + return renderAutomation(nativeOfflineAudioContext, proxy.pan, nativeStereoPannerNode.pan); + case 7: + _context.next = 11; + break; + case 9: + _context.next = 11; + return connectAudioParam(nativeOfflineAudioContext, proxy.pan, nativeStereoPannerNode.pan); + case 11: + if (!isNativeAudioNodeFaker(nativeStereoPannerNode)) { + _context.next = 16; + break; + } + _context.next = 14; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeStereoPannerNode.inputs[0]); + case 14: + _context.next = 18; + break; + case 16: + _context.next = 18; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeStereoPannerNode); + case 18: + return _context.abrupt("return", nativeStereoPannerNode); + case 19: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createStereoPannerNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeStereoPannerNode = renderedNativeStereoPannerNodes.get(nativeOfflineAudioContext); + if (renderedNativeStereoPannerNode !== undefined) { + return Promise.resolve(renderedNativeStereoPannerNode); + } + return createStereoPannerNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + // Bug #33: Safari exposes an AudioBuffer but it can't be used as a constructor. + var createTestAudioBufferConstructorSupport = function createTestAudioBufferConstructorSupport(nativeAudioBufferConstructor) { + return function () { + if (nativeAudioBufferConstructor === null) { + return false; + } + try { + new nativeAudioBufferConstructor({ + length: 1, + sampleRate: 44100 + }); // tslint:disable-line:no-unused-expression + } catch (_unused) { + return false; + } + return true; + }; + }; + + /* + * Firefox up to version 67 didn't fully support the copyFromChannel() and copyToChannel() methods. Therefore testing one of those methods + * is enough to know if the other one is supported as well. + */ + var createTestAudioBufferCopyChannelMethodsSubarraySupport = function createTestAudioBufferCopyChannelMethodsSubarraySupport(nativeOfflineAudioContextConstructor) { + return function () { + if (nativeOfflineAudioContextConstructor === null) { + return false; + } + var nativeOfflineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100); + var nativeAudioBuffer = nativeOfflineAudioContext.createBuffer(1, 1, 44100); + // Bug #5: Safari does not support copyFromChannel() and copyToChannel(). + if (nativeAudioBuffer.copyToChannel === undefined) { + return true; + } + var source = new Float32Array(2); + try { + nativeAudioBuffer.copyFromChannel(source, 0, 0); + } catch (_unused) { + return false; + } + return true; + }; + }; + + var createTestAudioContextCloseMethodSupport = function createTestAudioContextCloseMethodSupport(nativeAudioContextConstructor) { + return function () { + if (nativeAudioContextConstructor === null) { + return false; + } + // Try to check the prototype before constructing the AudioContext. + if (nativeAudioContextConstructor.prototype !== undefined && nativeAudioContextConstructor.prototype.close !== undefined) { + return true; + } + var audioContext = new nativeAudioContextConstructor(); + var isAudioContextClosable = audioContext.close !== undefined; + try { + audioContext.close(); + } catch (_unused) { + // Ignore errors. + } + return isAudioContextClosable; + }; + }; + + /** + * Edge up to version 14, Firefox up to version 52, Safari up to version 9 and maybe other browsers + * did not refuse to decode invalid parameters with a TypeError. + */ + var createTestAudioContextDecodeAudioDataMethodTypeErrorSupport = function createTestAudioContextDecodeAudioDataMethodTypeErrorSupport(nativeOfflineAudioContextConstructor) { + return function () { + if (nativeOfflineAudioContextConstructor === null) { + return Promise.resolve(false); + } + var offlineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100); + // Bug #21: Safari does not support promises yet. + return new Promise(function (resolve) { + var isPending = true; + var resolvePromise = function resolvePromise(err) { + if (isPending) { + isPending = false; + offlineAudioContext.startRendering(); + resolve(err instanceof TypeError); + } + }; + var promise; + // Bug #26: Safari throws a synchronous error. + try { + promise = offlineAudioContext + // Bug #1: Safari requires a successCallback. + .decodeAudioData(null, function () { + // Ignore the success callback. + }, resolvePromise); + } catch (err) { + resolvePromise(err); + } + // Bug #21: Safari does not support promises yet. + if (promise !== undefined) { + // Bug #6: Chrome, Edge and Firefox do not call the errorCallback. + promise["catch"](resolvePromise); + } + }); + }; + }; + + var createTestAudioContextOptionsSupport = function createTestAudioContextOptionsSupport(nativeAudioContextConstructor) { + return function () { + if (nativeAudioContextConstructor === null) { + return false; + } + var audioContext; + try { + audioContext = new nativeAudioContextConstructor({ + latencyHint: 'balanced' + }); + } catch (_unused) { + return false; + } + audioContext.close(); + return true; + }; + }; + + // Safari up to version 12.0 (but not v12.1) didn't return the destination in case it was an AudioNode. + var createTestAudioNodeConnectMethodSupport = function createTestAudioNodeConnectMethodSupport(nativeOfflineAudioContextConstructor) { + return function () { + if (nativeOfflineAudioContextConstructor === null) { + return false; + } + var nativeOfflineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100); + var nativeGainNode = nativeOfflineAudioContext.createGain(); + var isSupported = nativeGainNode.connect(nativeGainNode) === nativeGainNode; + nativeGainNode.disconnect(nativeGainNode); + return isSupported; + }; + }; + + /** + * Chrome version 66 and 67 did not call the process() function of an AudioWorkletProcessor if it had no outputs. AudioWorklet support was + * enabled by default in version 66. + */ + var createTestAudioWorkletProcessorNoOutputsSupport = function createTestAudioWorkletProcessorNoOutputsSupport(nativeAudioWorkletNodeConstructor, nativeOfflineAudioContextConstructor) { + return /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var blob, messageChannel, offlineAudioContext, url, isCallingProcess, audioWorkletNode, oscillator; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!(nativeAudioWorkletNodeConstructor === null)) { + _context.next = 2; + break; + } + return _context.abrupt("return", true); + case 2: + if (!(nativeOfflineAudioContextConstructor === null)) { + _context.next = 4; + break; + } + return _context.abrupt("return", false); + case 4: + blob = new Blob(['let c,p;class A extends AudioWorkletProcessor{constructor(){super();this.port.onmessage=(e)=>{p=e.data;p.onmessage=()=>{p.postMessage(c);p.close()};this.port.postMessage(0)}}process(){c=1}}registerProcessor("a",A)'], { + type: 'application/javascript; charset=utf-8' + }); + messageChannel = new MessageChannel(); // Bug #141: Safari does not support creating an OfflineAudioContext with less than 44100 Hz. + offlineAudioContext = new nativeOfflineAudioContextConstructor(1, 128, 44100); + url = URL.createObjectURL(blob); + isCallingProcess = false; + _context.prev = 9; + _context.next = 12; + return offlineAudioContext.audioWorklet.addModule(url); + case 12: + audioWorkletNode = new nativeAudioWorkletNodeConstructor(offlineAudioContext, 'a', { + numberOfOutputs: 0 + }); + oscillator = offlineAudioContext.createOscillator(); + _context.next = 16; + return new Promise(function (resolve) { + audioWorkletNode.port.onmessage = function () { + return resolve(); + }; + audioWorkletNode.port.postMessage(messageChannel.port2, [messageChannel.port2]); + }); + case 16: + audioWorkletNode.port.onmessage = function () { + return isCallingProcess = true; + }; + oscillator.connect(audioWorkletNode); + oscillator.start(0); + _context.next = 21; + return offlineAudioContext.startRendering(); + case 21: + _context.next = 23; + return new Promise(function (resolve) { + messageChannel.port1.onmessage = function (_ref2) { + var data = _ref2.data; + return resolve(data === 1); + }; + messageChannel.port1.postMessage(0); + }); + case 23: + isCallingProcess = _context.sent; + _context.next = 28; + break; + case 26: + _context.prev = 26; + _context.t0 = _context["catch"](9); + case 28: + _context.prev = 28; + messageChannel.port1.close(); + URL.revokeObjectURL(url); + return _context.finish(28); + case 32: + return _context.abrupt("return", isCallingProcess); + case 33: + case "end": + return _context.stop(); + } + }, _callee, null, [[9, 26, 28, 32]]); + })); + }; + + // Bug #179: Firefox does not allow to transfer any buffer which has been passed to the process() method as an argument. + var createTestAudioWorkletProcessorPostMessageSupport = function createTestAudioWorkletProcessorPostMessageSupport(nativeAudioWorkletNodeConstructor, nativeOfflineAudioContextConstructor) { + return /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var blob, offlineAudioContext, url, isEmittingMessageEvents, isEmittingProcessorErrorEvents, audioWorkletNode, oscillator; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!(nativeAudioWorkletNodeConstructor === null)) { + _context.next = 2; + break; + } + return _context.abrupt("return", true); + case 2: + if (!(nativeOfflineAudioContextConstructor === null)) { + _context.next = 4; + break; + } + return _context.abrupt("return", false); + case 4: + blob = new Blob(['class A extends AudioWorkletProcessor{process(i){this.port.postMessage(i,[i[0][0].buffer])}}registerProcessor("a",A)'], { + type: 'application/javascript; charset=utf-8' + }); // Bug #141: Safari does not support creating an OfflineAudioContext with less than 44100 Hz. + offlineAudioContext = new nativeOfflineAudioContextConstructor(1, 128, 44100); + url = URL.createObjectURL(blob); + isEmittingMessageEvents = false; + isEmittingProcessorErrorEvents = false; + _context.prev = 9; + _context.next = 12; + return offlineAudioContext.audioWorklet.addModule(url); + case 12: + audioWorkletNode = new nativeAudioWorkletNodeConstructor(offlineAudioContext, 'a', { + numberOfOutputs: 0 + }); + oscillator = offlineAudioContext.createOscillator(); + audioWorkletNode.port.onmessage = function () { + return isEmittingMessageEvents = true; + }; + audioWorkletNode.onprocessorerror = function () { + return isEmittingProcessorErrorEvents = true; + }; + oscillator.connect(audioWorkletNode); + oscillator.start(0); + _context.next = 20; + return offlineAudioContext.startRendering(); + case 20: + _context.next = 22; + return new Promise(function (resolve) { + return setTimeout(resolve); + }); + case 22: + _context.next = 26; + break; + case 24: + _context.prev = 24; + _context.t0 = _context["catch"](9); + case 26: + _context.prev = 26; + URL.revokeObjectURL(url); + return _context.finish(26); + case 29: + return _context.abrupt("return", isEmittingMessageEvents && !isEmittingProcessorErrorEvents); + case 30: + case "end": + return _context.stop(); + } + }, _callee, null, [[9, 24, 26, 29]]); + })); + }; + + /** + * Firefox up to version 69 did not throw an error when setting a different channelCount or channelCountMode. + */ + var createTestChannelMergerNodeChannelCountSupport = function createTestChannelMergerNodeChannelCountSupport(nativeOfflineAudioContextConstructor) { + return function () { + if (nativeOfflineAudioContextConstructor === null) { + return false; + } + var offlineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100); + var nativeChannelMergerNode = offlineAudioContext.createChannelMerger(); + /** + * Bug #15: Safari does not return the default properties. It still needs to be patched. This test is supposed to test the support + * in other browsers. + */ + if (nativeChannelMergerNode.channelCountMode === 'max') { + return true; + } + try { + nativeChannelMergerNode.channelCount = 2; + } catch (_unused) { + return true; + } + return false; + }; + }; + + var createTestConstantSourceNodeAccurateSchedulingSupport = function createTestConstantSourceNodeAccurateSchedulingSupport(nativeOfflineAudioContextConstructor) { + return function () { + if (nativeOfflineAudioContextConstructor === null) { + return false; + } + var nativeOfflineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100); + // Bug #62: Safari does not support ConstantSourceNodes. + if (nativeOfflineAudioContext.createConstantSource === undefined) { + return true; + } + var nativeConstantSourceNode = nativeOfflineAudioContext.createConstantSource(); + /* + * @todo This is using bug #75 to detect bug #70. That works because both bugs were unique to + * the implementation of Firefox right now, but it could probably be done in a better way. + */ + return nativeConstantSourceNode.offset.maxValue !== Number.POSITIVE_INFINITY; + }; + }; + + // Opera up to version 57 did not allow to reassign the buffer of a ConvolverNode. + var createTestConvolverNodeBufferReassignabilitySupport = function createTestConvolverNodeBufferReassignabilitySupport(nativeOfflineAudioContextConstructor) { + return function () { + if (nativeOfflineAudioContextConstructor === null) { + return false; + } + var offlineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100); + var nativeConvolverNode = offlineAudioContext.createConvolver(); + nativeConvolverNode.buffer = offlineAudioContext.createBuffer(1, 1, offlineAudioContext.sampleRate); + try { + nativeConvolverNode.buffer = offlineAudioContext.createBuffer(1, 1, offlineAudioContext.sampleRate); + } catch (_unused) { + return false; + } + return true; + }; + }; + + // Chrome up to version v80, Edge up to version v80 and Opera up to version v67 did not allow to set the channelCount property of a ConvolverNode to 1. They also did not allow to set the channelCountMode to 'explicit'. + var createTestConvolverNodeChannelCountSupport = function createTestConvolverNodeChannelCountSupport(nativeOfflineAudioContextConstructor) { + return function () { + if (nativeOfflineAudioContextConstructor === null) { + return false; + } + var offlineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100); + var nativeConvolverNode = offlineAudioContext.createConvolver(); + try { + nativeConvolverNode.channelCount = 1; + } catch (_unused) { + return false; + } + return true; + }; + }; + + var createTestIsSecureContextSupport = function createTestIsSecureContextSupport(window) { + return function () { + return window !== null && window.hasOwnProperty('isSecureContext'); + }; + }; + + // Firefox up to version 68 did not throw an error when creating a MediaStreamAudioSourceNode with a mediaStream that had no audio track. + var createTestMediaStreamAudioSourceNodeMediaStreamWithoutAudioTrackSupport = function createTestMediaStreamAudioSourceNodeMediaStreamWithoutAudioTrackSupport(nativeAudioContextConstructor) { + return function () { + if (nativeAudioContextConstructor === null) { + return false; + } + var audioContext = new nativeAudioContextConstructor(); + try { + audioContext.createMediaStreamSource(new MediaStream()); + return false; + } catch (err) { + return true; + } finally { + audioContext.close(); + } + }; + }; + + var createTestOfflineAudioContextCurrentTimeSupport = function createTestOfflineAudioContextCurrentTimeSupport(createNativeGainNode, nativeOfflineAudioContextConstructor) { + return function () { + if (nativeOfflineAudioContextConstructor === null) { + return Promise.resolve(false); + } + var nativeOfflineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100); + // Bug #48: Safari does not render an OfflineAudioContext without any connected node. + var gainNode = createNativeGainNode(nativeOfflineAudioContext, { + channelCount: 1, + channelCountMode: 'explicit', + channelInterpretation: 'discrete', + gain: 0 + }); + // Bug #21: Safari does not support promises yet. + return new Promise(function (resolve) { + nativeOfflineAudioContext.oncomplete = function () { + gainNode.disconnect(); + resolve(nativeOfflineAudioContext.currentTime !== 0); + }; + nativeOfflineAudioContext.startRendering(); + }); + }; + }; + + /** + * Firefox up to version 62 did not kick off the processing of the StereoPannerNode if the value of pan was zero. + */ + var createTestStereoPannerNodeDefaultValueSupport = function createTestStereoPannerNodeDefaultValueSupport(nativeOfflineAudioContextConstructor) { + return function () { + if (nativeOfflineAudioContextConstructor === null) { + return Promise.resolve(false); + } + var nativeOfflineAudioContext = new nativeOfflineAudioContextConstructor(1, 1, 44100); + /* + * Bug #105: Safari does not support the StereoPannerNode. Therefore the returned value should normally be false but the faker does + * support the tested behaviour. + */ + if (nativeOfflineAudioContext.createStereoPanner === undefined) { + return Promise.resolve(true); + } + // Bug #62: Safari does not support ConstantSourceNodes. + if (nativeOfflineAudioContext.createConstantSource === undefined) { + return Promise.resolve(true); + } + var constantSourceNode = nativeOfflineAudioContext.createConstantSource(); + var stereoPanner = nativeOfflineAudioContext.createStereoPanner(); + constantSourceNode.channelCount = 1; + constantSourceNode.offset.value = 1; + stereoPanner.channelCount = 1; + constantSourceNode.start(); + constantSourceNode.connect(stereoPanner).connect(nativeOfflineAudioContext.destination); + return nativeOfflineAudioContext.startRendering().then(function (buffer) { + return buffer.getChannelData(0)[0] !== 1; + }); + }; + }; + + var createUnknownError = function createUnknownError() { + return new DOMException('', 'UnknownError'); + }; + + function ownKeys$3(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$3(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$3(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } + function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } + var DEFAULT_OPTIONS = { + channelCount: 2, + channelCountMode: 'max', + channelInterpretation: 'speakers', + curve: null, + oversample: 'none' + }; + var createWaveShaperNodeConstructor = function createWaveShaperNodeConstructor(audioNodeConstructor, createInvalidStateError, createNativeWaveShaperNode, createWaveShaperNodeRenderer, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime) { + return /*#__PURE__*/function (_audioNodeConstructor) { + function WaveShaperNode(context, options) { + var _this; + _classCallCheck(this, WaveShaperNode); + var nativeContext = getNativeContext(context); + var mergedOptions = _objectSpread$3(_objectSpread$3({}, DEFAULT_OPTIONS), options); + var nativeWaveShaperNode = createNativeWaveShaperNode(nativeContext, mergedOptions); + var isOffline = isNativeOfflineAudioContext(nativeContext); + var waveShaperNodeRenderer = isOffline ? createWaveShaperNodeRenderer() : null; + // @todo Add a mechanism to only switch a WaveShaperNode to active while it is connected. + _this = _callSuper(this, WaveShaperNode, [context, true, nativeWaveShaperNode, waveShaperNodeRenderer]); + _this._isCurveNullified = false; + _this._nativeWaveShaperNode = nativeWaveShaperNode; + // @todo Determine a meaningful tail-time instead of just using one second. + setAudioNodeTailTime(_this, 1); + return _this; + } + _inherits(WaveShaperNode, _audioNodeConstructor); + return _createClass(WaveShaperNode, [{ + key: "curve", + get: function get() { + if (this._isCurveNullified) { + return null; + } + return this._nativeWaveShaperNode.curve; + }, + set: function set(value) { + // Bug #103: Safari does not allow to set the curve to null. + if (value === null) { + this._isCurveNullified = true; + this._nativeWaveShaperNode.curve = new Float32Array([0, 0]); + } else { + // Bug #102: Safari does not throw an InvalidStateError when the curve has less than two samples. + // Bug #104: Chrome and Edge will throw an InvalidAccessError when the curve has less than two samples. + if (value.length < 2) { + throw createInvalidStateError(); + } + this._isCurveNullified = false; + this._nativeWaveShaperNode.curve = value; + } + } + }, { + key: "oversample", + get: function get() { + return this._nativeWaveShaperNode.oversample; + }, + set: function set(value) { + this._nativeWaveShaperNode.oversample = value; + } + }]); + }(audioNodeConstructor); + }; + + var createWaveShaperNodeRendererFactory = function createWaveShaperNodeRendererFactory(createNativeWaveShaperNode, getNativeAudioNode, renderInputsOfAudioNode) { + return function () { + var renderedNativeWaveShaperNodes = new WeakMap(); + var createWaveShaperNode = /*#__PURE__*/function () { + var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(proxy, nativeOfflineAudioContext) { + var nativeWaveShaperNode, nativeWaveShaperNodeIsOwnedByContext, options; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + nativeWaveShaperNode = getNativeAudioNode(proxy); // If the initially used nativeWaveShaperNode was not constructed on the same OfflineAudioContext it needs to be created again. + nativeWaveShaperNodeIsOwnedByContext = isOwnedByContext(nativeWaveShaperNode, nativeOfflineAudioContext); + if (!nativeWaveShaperNodeIsOwnedByContext) { + options = { + channelCount: nativeWaveShaperNode.channelCount, + channelCountMode: nativeWaveShaperNode.channelCountMode, + channelInterpretation: nativeWaveShaperNode.channelInterpretation, + curve: nativeWaveShaperNode.curve, + oversample: nativeWaveShaperNode.oversample + }; + nativeWaveShaperNode = createNativeWaveShaperNode(nativeOfflineAudioContext, options); + } + renderedNativeWaveShaperNodes.set(nativeOfflineAudioContext, nativeWaveShaperNode); + if (!isNativeAudioNodeFaker(nativeWaveShaperNode)) { + _context.next = 9; + break; + } + _context.next = 7; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeWaveShaperNode.inputs[0]); + case 7: + _context.next = 11; + break; + case 9: + _context.next = 11; + return renderInputsOfAudioNode(proxy, nativeOfflineAudioContext, nativeWaveShaperNode); + case 11: + return _context.abrupt("return", nativeWaveShaperNode); + case 12: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function createWaveShaperNode(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); + return { + render: function render(proxy, nativeOfflineAudioContext) { + var renderedNativeWaveShaperNode = renderedNativeWaveShaperNodes.get(nativeOfflineAudioContext); + if (renderedNativeWaveShaperNode !== undefined) { + return Promise.resolve(renderedNativeWaveShaperNode); + } + return createWaveShaperNode(proxy, nativeOfflineAudioContext); + } + }; + }; + }; + + var createWindow = function createWindow() { + return typeof window === 'undefined' ? null : window; + }; + + var createWrapAudioBufferCopyChannelMethods = function createWrapAudioBufferCopyChannelMethods(convertNumberToUnsignedLong, createIndexSizeError) { + return function (audioBuffer) { + audioBuffer.copyFromChannel = function (destination, channelNumberAsNumber) { + var bufferOffsetAsNumber = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var bufferOffset = convertNumberToUnsignedLong(bufferOffsetAsNumber); + var channelNumber = convertNumberToUnsignedLong(channelNumberAsNumber); + if (channelNumber >= audioBuffer.numberOfChannels) { + throw createIndexSizeError(); + } + var audioBufferLength = audioBuffer.length; + var channelData = audioBuffer.getChannelData(channelNumber); + var destinationLength = destination.length; + for (var i = bufferOffset < 0 ? -bufferOffset : 0; i + bufferOffset < audioBufferLength && i < destinationLength; i += 1) { + destination[i] = channelData[i + bufferOffset]; + } + }; + audioBuffer.copyToChannel = function (source, channelNumberAsNumber) { + var bufferOffsetAsNumber = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var bufferOffset = convertNumberToUnsignedLong(bufferOffsetAsNumber); + var channelNumber = convertNumberToUnsignedLong(channelNumberAsNumber); + if (channelNumber >= audioBuffer.numberOfChannels) { + throw createIndexSizeError(); + } + var audioBufferLength = audioBuffer.length; + var channelData = audioBuffer.getChannelData(channelNumber); + var sourceLength = source.length; + for (var i = bufferOffset < 0 ? -bufferOffset : 0; i + bufferOffset < audioBufferLength && i < sourceLength; i += 1) { + channelData[i + bufferOffset] = source[i]; + } + }; + }; + }; + + var createWrapAudioBufferCopyChannelMethodsOutOfBounds = function createWrapAudioBufferCopyChannelMethodsOutOfBounds(convertNumberToUnsignedLong) { + return function (audioBuffer) { + audioBuffer.copyFromChannel = function (copyFromChannel) { + return function (destination, channelNumberAsNumber) { + var bufferOffsetAsNumber = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var bufferOffset = convertNumberToUnsignedLong(bufferOffsetAsNumber); + var channelNumber = convertNumberToUnsignedLong(channelNumberAsNumber); + if (bufferOffset < audioBuffer.length) { + return copyFromChannel.call(audioBuffer, destination, channelNumber, bufferOffset); + } + }; + }(audioBuffer.copyFromChannel); + audioBuffer.copyToChannel = function (copyToChannel) { + return function (source, channelNumberAsNumber) { + var bufferOffsetAsNumber = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var bufferOffset = convertNumberToUnsignedLong(bufferOffsetAsNumber); + var channelNumber = convertNumberToUnsignedLong(channelNumberAsNumber); + if (bufferOffset < audioBuffer.length) { + return copyToChannel.call(audioBuffer, source, channelNumber, bufferOffset); + } + }; + }(audioBuffer.copyToChannel); + }; + }; + + var createWrapAudioBufferSourceNodeStopMethodNullifiedBuffer = function createWrapAudioBufferSourceNodeStopMethodNullifiedBuffer(overwriteAccessors) { + return function (nativeAudioBufferSourceNode, nativeContext) { + var nullifiedBuffer = nativeContext.createBuffer(1, 1, 44100); + if (nativeAudioBufferSourceNode.buffer === null) { + nativeAudioBufferSourceNode.buffer = nullifiedBuffer; + } + overwriteAccessors(nativeAudioBufferSourceNode, 'buffer', function (get) { + return function () { + var value = get.call(nativeAudioBufferSourceNode); + return value === nullifiedBuffer ? null : value; + }; + }, function (set) { + return function (value) { + return set.call(nativeAudioBufferSourceNode, value === null ? nullifiedBuffer : value); + }; + }); + }; + }; + + var createWrapChannelMergerNode = function createWrapChannelMergerNode(createInvalidStateError, monitorConnections) { + return function (nativeContext, channelMergerNode) { + // Bug #15: Safari does not return the default properties. + channelMergerNode.channelCount = 1; + channelMergerNode.channelCountMode = 'explicit'; + // Bug #16: Safari does not throw an error when setting a different channelCount or channelCountMode. + Object.defineProperty(channelMergerNode, 'channelCount', { + get: function get() { + return 1; + }, + set: function set() { + throw createInvalidStateError(); + } + }); + Object.defineProperty(channelMergerNode, 'channelCountMode', { + get: function get() { + return 'explicit'; + }, + set: function set() { + throw createInvalidStateError(); + } + }); + // Bug #20: Safari requires a connection of any kind to treat the input signal correctly. + var audioBufferSourceNode = nativeContext.createBufferSource(); + var whenConnected = function whenConnected() { + var length = channelMergerNode.numberOfInputs; + for (var i = 0; i < length; i += 1) { + audioBufferSourceNode.connect(channelMergerNode, 0, i); + } + }; + var whenDisconnected = function whenDisconnected() { + return audioBufferSourceNode.disconnect(channelMergerNode); + }; + monitorConnections(channelMergerNode, whenConnected, whenDisconnected); + }; + }; + + var getFirstSample = function getFirstSample(audioBuffer, buffer, channelNumber) { + // Bug #5: Safari does not support copyFromChannel() and copyToChannel(). + if (audioBuffer.copyFromChannel === undefined) { + return audioBuffer.getChannelData(channelNumber)[0]; + } + audioBuffer.copyFromChannel(buffer, channelNumber); + return buffer[0]; + }; + + var isDCCurve = function isDCCurve(curve) { + if (curve === null) { + return false; + } + var length = curve.length; + if (length % 2 !== 0) { + return curve[Math.floor(length / 2)] !== 0; + } + return curve[length / 2 - 1] + curve[length / 2] !== 0; + }; + + var overwriteAccessors = function overwriteAccessors(object, property, createGetter, createSetter) { + var prototype = object; + while (!prototype.hasOwnProperty(property)) { + prototype = Object.getPrototypeOf(prototype); + } + var _Object$getOwnPropert = Object.getOwnPropertyDescriptor(prototype, property), + get = _Object$getOwnPropert.get, + set = _Object$getOwnPropert.set; + Object.defineProperty(object, property, { + get: createGetter(get), + set: createSetter(set) + }); + }; + + function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + var sanitizeAudioWorkletNodeOptions = function sanitizeAudioWorkletNodeOptions(options) { + return _objectSpread$2(_objectSpread$2({}, options), {}, { + outputChannelCount: options.outputChannelCount !== undefined ? options.outputChannelCount : options.numberOfInputs === 1 && options.numberOfOutputs === 1 ? + /* + * Bug #61: This should be the computedNumberOfChannels, but unfortunately that is almost impossible to fake. That's why + * the channelCountMode is required to be 'explicit' as long as there is not a native implementation in every browser. That + * makes sure the computedNumberOfChannels is equivilant to the channelCount which makes it much easier to compute. + */ + [options.channelCount] : Array.from({ + length: options.numberOfOutputs + }, function () { + return 1; + }) + }); + }; + + function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + var sanitizeChannelSplitterOptions = function sanitizeChannelSplitterOptions(options) { + return _objectSpread$1(_objectSpread$1({}, options), {}, { + channelCount: options.numberOfOutputs + }); + }; + + function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } + function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } + var sanitizePeriodicWaveOptions = function sanitizePeriodicWaveOptions(options) { + var imag = options.imag, + real = options.real; + if (imag === undefined) { + if (real === undefined) { + return _objectSpread(_objectSpread({}, options), {}, { + imag: [0, 0], + real: [0, 0] + }); + } + return _objectSpread(_objectSpread({}, options), {}, { + imag: Array.from(real, function () { + return 0; + }), + real: real + }); + } + if (real === undefined) { + return _objectSpread(_objectSpread({}, options), {}, { + imag: imag, + real: Array.from(imag, function () { + return 0; + }) + }); + } + return _objectSpread(_objectSpread({}, options), {}, { + imag: imag, + real: real + }); + }; + + var _setValueAtTimeUntilPossible = function setValueAtTimeUntilPossible(audioParam, value, startTime) { + try { + audioParam.setValueAtTime(value, startTime); + } catch (err) { + if (err.code !== 9) { + throw err; + } + _setValueAtTimeUntilPossible(audioParam, value, startTime + 1e-7); + } + }; + + var testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport = function testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport(nativeContext) { + var nativeAudioBufferSourceNode = nativeContext.createBufferSource(); + nativeAudioBufferSourceNode.start(); + try { + nativeAudioBufferSourceNode.start(); + } catch (_unused) { + return true; + } + return false; + }; + + var testAudioBufferSourceNodeStartMethodOffsetClampingSupport = function testAudioBufferSourceNodeStartMethodOffsetClampingSupport(nativeContext) { + var nativeAudioBufferSourceNode = nativeContext.createBufferSource(); + var nativeAudioBuffer = nativeContext.createBuffer(1, 1, 44100); + nativeAudioBufferSourceNode.buffer = nativeAudioBuffer; + try { + nativeAudioBufferSourceNode.start(0, 1); + } catch (_unused) { + return false; + } + return true; + }; + + var testAudioBufferSourceNodeStopMethodNullifiedBufferSupport = function testAudioBufferSourceNodeStopMethodNullifiedBufferSupport(nativeContext) { + var nativeAudioBufferSourceNode = nativeContext.createBufferSource(); + nativeAudioBufferSourceNode.start(); + try { + nativeAudioBufferSourceNode.stop(); + } catch (_unused) { + return false; + } + return true; + }; + + var testAudioScheduledSourceNodeStartMethodNegativeParametersSupport = function testAudioScheduledSourceNodeStartMethodNegativeParametersSupport(nativeContext) { + var nativeAudioBufferSourceNode = nativeContext.createOscillator(); + try { + nativeAudioBufferSourceNode.start(-1); + } catch (err) { + return err instanceof RangeError; + } + return false; + }; + + var testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport = function testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport(nativeContext) { + var nativeAudioBuffer = nativeContext.createBuffer(1, 1, 44100); + var nativeAudioBufferSourceNode = nativeContext.createBufferSource(); + nativeAudioBufferSourceNode.buffer = nativeAudioBuffer; + nativeAudioBufferSourceNode.start(); + nativeAudioBufferSourceNode.stop(); + try { + nativeAudioBufferSourceNode.stop(); + return true; + } catch (_unused) { + return false; + } + }; + + var testAudioScheduledSourceNodeStopMethodNegativeParametersSupport = function testAudioScheduledSourceNodeStopMethodNegativeParametersSupport(nativeContext) { + var nativeAudioBufferSourceNode = nativeContext.createOscillator(); + try { + nativeAudioBufferSourceNode.stop(-1); + } catch (err) { + return err instanceof RangeError; + } + return false; + }; + + var testAudioWorkletNodeOptionsClonability = function testAudioWorkletNodeOptionsClonability(audioWorkletNodeOptions) { + var _MessageChannel = new MessageChannel(), + port1 = _MessageChannel.port1, + port2 = _MessageChannel.port2; + try { + // This will throw an error if the audioWorkletNodeOptions are not clonable. + port1.postMessage(audioWorkletNodeOptions); + } finally { + port1.close(); + port2.close(); + } + }; + + /* + * Bug #122: Edge up to version v18 did not allow to construct a DOMException'. It also had a couple more bugs but since this is easy to + * test it's used here as a placeholder. + * + * Bug #27: Edge up to version v18 did reject an invalid arrayBuffer passed to decodeAudioData() with a DOMException. + * + * Bug #50: Edge up to version v18 did not allow to create AudioNodes on a closed context. + * + * Bug #57: Edge up to version v18 did not throw an error when assigning the type of an OscillatorNode to 'custom'. + * + * Bug #63: Edge up to version v18 did not expose the mediaElement property of a MediaElementAudioSourceNode. + * + * Bug #64: Edge up to version v18 did not support the MediaStreamAudioDestinationNode. + * + * Bug #71: Edge up to version v18 did not allow to set the buffer of an AudioBufferSourceNode to null. + * + * Bug #93: Edge up to version v18 did set the sampleRate of an AudioContext to zero when it was closed. + * + * Bug #101: Edge up to version v18 refused to execute decodeAudioData() on a closed context. + * + * Bug #106: Edge up to version v18 did not expose the maxValue and minValue properties of the pan AudioParam of a StereoPannerNode. + * + * Bug #110: Edge up to version v18 did not expose the maxValue and minValue properties of the attack, knee, ratio, release and threshold AudioParams of a DynamicsCompressorNode. + * + * Bug #123: Edge up to version v18 did not support HRTF as the panningModel for a PannerNode. + * + * Bug #145: Edge up to version v18 did throw an IndexSizeError when an OfflineAudioContext was created with a sampleRate of zero. + * + * Bug #161: Edge up to version v18 did not expose the maxValue and minValue properties of the delayTime AudioParam of a DelayNode. + */ + var testDomExceptionConstructorSupport = function testDomExceptionConstructorSupport() { + try { + new DOMException(); // tslint:disable-line:no-unused-expression + } catch (_unused) { + return false; + } + return true; + }; + + // Safari at version 11 did not support transferables. + var testTransferablesSupport = function testTransferablesSupport() { + return new Promise(function (resolve) { + var arrayBuffer = new ArrayBuffer(0); + var _MessageChannel = new MessageChannel(), + port1 = _MessageChannel.port1, + port2 = _MessageChannel.port2; + port1.onmessage = function (_ref) { + var data = _ref.data; + return resolve(data !== null); + }; + port2.postMessage(arrayBuffer, [arrayBuffer]); + }); + }; + + var wrapAudioBufferSourceNodeStartMethodOffsetClamping = function wrapAudioBufferSourceNodeStartMethodOffsetClamping(nativeAudioBufferSourceNode) { + nativeAudioBufferSourceNode.start = function (start) { + return function () { + var when = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var duration = arguments.length > 2 ? arguments[2] : undefined; + var buffer = nativeAudioBufferSourceNode.buffer; + // Bug #154: Safari does not clamp the offset if it is equal to or greater than the duration of the buffer. + var clampedOffset = buffer === null ? offset : Math.min(buffer.duration, offset); + // Bug #155: Safari does not handle the offset correctly if it would cause the buffer to be not be played at all. + if (buffer !== null && clampedOffset > buffer.duration - 0.5 / nativeAudioBufferSourceNode.context.sampleRate) { + start.call(nativeAudioBufferSourceNode, when, 0, 0); + } else { + start.call(nativeAudioBufferSourceNode, when, clampedOffset, duration); + } + }; + }(nativeAudioBufferSourceNode.start); + }; + + var wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls = function wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls(nativeAudioScheduledSourceNode, nativeContext) { + var nativeGainNode = nativeContext.createGain(); + nativeAudioScheduledSourceNode.connect(nativeGainNode); + var disconnectGainNode = function (disconnect) { + return function () { + // @todo TypeScript cannot infer the overloaded signature with 1 argument yet. + disconnect.call(nativeAudioScheduledSourceNode, nativeGainNode); + nativeAudioScheduledSourceNode.removeEventListener('ended', disconnectGainNode); + }; + }(nativeAudioScheduledSourceNode.disconnect); + nativeAudioScheduledSourceNode.addEventListener('ended', disconnectGainNode); + interceptConnections(nativeAudioScheduledSourceNode, nativeGainNode); + nativeAudioScheduledSourceNode.stop = function (stop) { + var isStopped = false; + return function () { + var when = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + if (isStopped) { + try { + stop.call(nativeAudioScheduledSourceNode, when); + } catch (_unused) { + nativeGainNode.gain.setValueAtTime(0, when); + } + } else { + stop.call(nativeAudioScheduledSourceNode, when); + isStopped = true; + } + }; + }(nativeAudioScheduledSourceNode.stop); + }; + + var wrapEventListener = function wrapEventListener(target, eventListener) { + return function (event) { + var descriptor = { + value: target + }; + Object.defineProperties(event, { + currentTarget: descriptor, + target: descriptor + }); + if (typeof eventListener === 'function') { + return eventListener.call(target, event); + } + return eventListener.handleEvent.call(target, event); + }; + }; + + var addActiveInputConnectionToAudioNode = createAddActiveInputConnectionToAudioNode(insertElementInSet); + var addPassiveInputConnectionToAudioNode = createAddPassiveInputConnectionToAudioNode(insertElementInSet); + var deleteActiveInputConnectionToAudioNode = createDeleteActiveInputConnectionToAudioNode(pickElementFromSet); + var audioNodeTailTimeStore = new WeakMap(); + var getAudioNodeTailTime = createGetAudioNodeTailTime(audioNodeTailTimeStore); + var cacheTestResult = createCacheTestResult(new Map(), new WeakMap()); + var window$1 = createWindow(); + var createNativeAnalyserNode = createNativeAnalyserNodeFactory(cacheTestResult, createIndexSizeError); + var getAudioNodeRenderer = createGetAudioNodeRenderer(getAudioNodeConnections); + var renderInputsOfAudioNode = createRenderInputsOfAudioNode(getAudioNodeConnections, getAudioNodeRenderer, isPartOfACycle); + var createAnalyserNodeRenderer = createAnalyserNodeRendererFactory(createNativeAnalyserNode, getNativeAudioNode, renderInputsOfAudioNode); + var getNativeContext = createGetNativeContext(CONTEXT_STORE); + var nativeOfflineAudioContextConstructor = createNativeOfflineAudioContextConstructor(window$1); + var isNativeOfflineAudioContext = createIsNativeOfflineAudioContext(nativeOfflineAudioContextConstructor); + var audioParamAudioNodeStore = new WeakMap(); + var eventTargetConstructor = createEventTargetConstructor(wrapEventListener); + var nativeAudioContextConstructor = createNativeAudioContextConstructor(window$1); + var isNativeAudioContext = createIsNativeAudioContext(nativeAudioContextConstructor); + var isNativeAudioNode = createIsNativeAudioNode(window$1); + var isNativeAudioParam = createIsNativeAudioParam(window$1); + var nativeAudioWorkletNodeConstructor = createNativeAudioWorkletNodeConstructor(window$1); + var audioNodeConstructor = createAudioNodeConstructor(createAddAudioNodeConnections(AUDIO_NODE_CONNECTIONS_STORE), createAddConnectionToAudioNode(addActiveInputConnectionToAudioNode, addPassiveInputConnectionToAudioNode, connectNativeAudioNodeToNativeAudioNode, deleteActiveInputConnectionToAudioNode, disconnectNativeAudioNodeFromNativeAudioNode, getAudioNodeConnections, getAudioNodeTailTime, getEventListenersOfAudioNode, getNativeAudioNode, insertElementInSet, isActiveAudioNode, isPartOfACycle, isPassiveAudioNode), cacheTestResult, createIncrementCycleCounterFactory(CYCLE_COUNTERS, disconnectNativeAudioNodeFromNativeAudioNode, getAudioNodeConnections, getNativeAudioNode, getNativeAudioParam, isActiveAudioNode), createIndexSizeError, createInvalidAccessError, createNotSupportedError, createDecrementCycleCounter(connectNativeAudioNodeToNativeAudioNode, CYCLE_COUNTERS, getAudioNodeConnections, getNativeAudioNode, getNativeAudioParam, getNativeContext, isActiveAudioNode, isNativeOfflineAudioContext), createDetectCycles(audioParamAudioNodeStore, getAudioNodeConnections, getValueForKey), eventTargetConstructor, getNativeContext, isNativeAudioContext, isNativeAudioNode, isNativeAudioParam, isNativeOfflineAudioContext, nativeAudioWorkletNodeConstructor); + var analyserNodeConstructor = createAnalyserNodeConstructor(audioNodeConstructor, createAnalyserNodeRenderer, createIndexSizeError, createNativeAnalyserNode, getNativeContext, isNativeOfflineAudioContext); + var audioBufferStore = new WeakSet(); + var nativeAudioBufferConstructor = createNativeAudioBufferConstructor(window$1); + var convertNumberToUnsignedLong = createConvertNumberToUnsignedLong(new Uint32Array(1)); + var wrapAudioBufferCopyChannelMethods = createWrapAudioBufferCopyChannelMethods(convertNumberToUnsignedLong, createIndexSizeError); + var wrapAudioBufferCopyChannelMethodsOutOfBounds = createWrapAudioBufferCopyChannelMethodsOutOfBounds(convertNumberToUnsignedLong); + var audioBufferConstructor = createAudioBufferConstructor(audioBufferStore, cacheTestResult, createNotSupportedError, nativeAudioBufferConstructor, nativeOfflineAudioContextConstructor, createTestAudioBufferConstructorSupport(nativeAudioBufferConstructor), wrapAudioBufferCopyChannelMethods, wrapAudioBufferCopyChannelMethodsOutOfBounds); + var addSilentConnection = createAddSilentConnection(createNativeGainNode); + var renderInputsOfAudioParam = createRenderInputsOfAudioParam(getAudioNodeRenderer, getAudioParamConnections, isPartOfACycle); + var connectAudioParam = createConnectAudioParam(renderInputsOfAudioParam); + var createNativeAudioBufferSourceNode = createNativeAudioBufferSourceNodeFactory(addSilentConnection, cacheTestResult, testAudioBufferSourceNodeStartMethodConsecutiveCallsSupport, testAudioBufferSourceNodeStartMethodOffsetClampingSupport, testAudioBufferSourceNodeStopMethodNullifiedBufferSupport, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, wrapAudioBufferSourceNodeStartMethodOffsetClamping, createWrapAudioBufferSourceNodeStopMethodNullifiedBuffer(overwriteAccessors), wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls); + var renderAutomation = createRenderAutomation(createGetAudioParamRenderer(getAudioParamConnections), renderInputsOfAudioParam); + var createAudioBufferSourceNodeRenderer = createAudioBufferSourceNodeRendererFactory(connectAudioParam, createNativeAudioBufferSourceNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode); + var createAudioParam = createAudioParamFactory(createAddAudioParamConnections(AUDIO_PARAM_CONNECTIONS_STORE), audioParamAudioNodeStore, AUDIO_PARAM_STORE, createAudioParamRenderer, automationEvents.createCancelAndHoldAutomationEvent, automationEvents.createCancelScheduledValuesAutomationEvent, automationEvents.createExponentialRampToValueAutomationEvent, automationEvents.createLinearRampToValueAutomationEvent, automationEvents.createSetTargetAutomationEvent, automationEvents.createSetValueAutomationEvent, automationEvents.createSetValueCurveAutomationEvent, nativeAudioContextConstructor, _setValueAtTimeUntilPossible); + var audioBufferSourceNodeConstructor = createAudioBufferSourceNodeConstructor(audioNodeConstructor, createAudioBufferSourceNodeRenderer, createAudioParam, createInvalidStateError, createNativeAudioBufferSourceNode, getNativeContext, isNativeOfflineAudioContext, wrapEventListener); + var audioDestinationNodeConstructor = createAudioDestinationNodeConstructor(audioNodeConstructor, createAudioDestinationNodeRenderer, createIndexSizeError, createInvalidStateError, createNativeAudioDestinationNodeFactory(createNativeGainNode, overwriteAccessors), getNativeContext, isNativeOfflineAudioContext, renderInputsOfAudioNode); + var createBiquadFilterNodeRenderer = createBiquadFilterNodeRendererFactory(connectAudioParam, createNativeBiquadFilterNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode); + var setAudioNodeTailTime = createSetAudioNodeTailTime(audioNodeTailTimeStore); + var biquadFilterNodeConstructor = createBiquadFilterNodeConstructor(audioNodeConstructor, createAudioParam, createBiquadFilterNodeRenderer, createInvalidAccessError, createNativeBiquadFilterNode, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime); + var monitorConnections = createMonitorConnections(insertElementInSet, isNativeAudioNode); + var wrapChannelMergerNode = createWrapChannelMergerNode(createInvalidStateError, monitorConnections); + var createNativeChannelMergerNode = createNativeChannelMergerNodeFactory(nativeAudioContextConstructor, wrapChannelMergerNode); + var createChannelMergerNodeRenderer = createChannelMergerNodeRendererFactory(createNativeChannelMergerNode, getNativeAudioNode, renderInputsOfAudioNode); + var channelMergerNodeConstructor = createChannelMergerNodeConstructor(audioNodeConstructor, createChannelMergerNodeRenderer, createNativeChannelMergerNode, getNativeContext, isNativeOfflineAudioContext); + var createChannelSplitterNodeRenderer = createChannelSplitterNodeRendererFactory(createNativeChannelSplitterNode, getNativeAudioNode, renderInputsOfAudioNode); + var channelSplitterNodeConstructor = createChannelSplitterNodeConstructor(audioNodeConstructor, createChannelSplitterNodeRenderer, createNativeChannelSplitterNode, getNativeContext, isNativeOfflineAudioContext, sanitizeChannelSplitterOptions); + var createNativeConstantSourceNodeFaker = createNativeConstantSourceNodeFakerFactory(addSilentConnection, createNativeAudioBufferSourceNode, createNativeGainNode, monitorConnections); + var createNativeConstantSourceNode = createNativeConstantSourceNodeFactory(addSilentConnection, cacheTestResult, createNativeConstantSourceNodeFaker, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport); + var createConstantSourceNodeRenderer = createConstantSourceNodeRendererFactory(connectAudioParam, createNativeConstantSourceNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode); + var constantSourceNodeConstructor = createConstantSourceNodeConstructor(audioNodeConstructor, createAudioParam, createConstantSourceNodeRenderer, createNativeConstantSourceNode, getNativeContext, isNativeOfflineAudioContext, wrapEventListener); + var createNativeConvolverNode = createNativeConvolverNodeFactory(createNotSupportedError, overwriteAccessors); + var createConvolverNodeRenderer = createConvolverNodeRendererFactory(createNativeConvolverNode, getNativeAudioNode, renderInputsOfAudioNode); + var convolverNodeConstructor = createConvolverNodeConstructor(audioNodeConstructor, createConvolverNodeRenderer, createNativeConvolverNode, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime); + var createDelayNodeRenderer = createDelayNodeRendererFactory(connectAudioParam, createNativeDelayNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode); + var delayNodeConstructor = createDelayNodeConstructor(audioNodeConstructor, createAudioParam, createDelayNodeRenderer, createNativeDelayNode, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime); + var createNativeDynamicsCompressorNode = createNativeDynamicsCompressorNodeFactory(createNotSupportedError); + var createDynamicsCompressorNodeRenderer = createDynamicsCompressorNodeRendererFactory(connectAudioParam, createNativeDynamicsCompressorNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode); + var dynamicsCompressorNodeConstructor = createDynamicsCompressorNodeConstructor(audioNodeConstructor, createAudioParam, createDynamicsCompressorNodeRenderer, createNativeDynamicsCompressorNode, createNotSupportedError, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime); + var createGainNodeRenderer = createGainNodeRendererFactory(connectAudioParam, createNativeGainNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode); + var gainNodeConstructor = createGainNodeConstructor(audioNodeConstructor, createAudioParam, createGainNodeRenderer, createNativeGainNode, getNativeContext, isNativeOfflineAudioContext); + var createNativeIIRFilterNodeFaker = createNativeIIRFilterNodeFakerFactory(createInvalidAccessError, createInvalidStateError, createNativeScriptProcessorNode, createNotSupportedError); + var renderNativeOfflineAudioContext = createRenderNativeOfflineAudioContext(cacheTestResult, createNativeGainNode, createNativeScriptProcessorNode, createTestOfflineAudioContextCurrentTimeSupport(createNativeGainNode, nativeOfflineAudioContextConstructor)); + var createIIRFilterNodeRenderer = createIIRFilterNodeRendererFactory(createNativeAudioBufferSourceNode, getNativeAudioNode, nativeOfflineAudioContextConstructor, renderInputsOfAudioNode, renderNativeOfflineAudioContext); + var createNativeIIRFilterNode = createNativeIIRFilterNodeFactory(createNativeIIRFilterNodeFaker); + var iIRFilterNodeConstructor = createIIRFilterNodeConstructor(audioNodeConstructor, createNativeIIRFilterNode, createIIRFilterNodeRenderer, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime); + var createAudioListener = createAudioListenerFactory(createAudioParam, createNativeChannelMergerNode, createNativeConstantSourceNode, createNativeScriptProcessorNode, createNotSupportedError, getFirstSample, isNativeOfflineAudioContext, overwriteAccessors); + var unrenderedAudioWorkletNodeStore = new WeakMap(); + var minimalBaseAudioContextConstructor = createMinimalBaseAudioContextConstructor(audioDestinationNodeConstructor, createAudioListener, eventTargetConstructor, isNativeOfflineAudioContext, unrenderedAudioWorkletNodeStore, wrapEventListener); + var createNativeOscillatorNode = createNativeOscillatorNodeFactory(addSilentConnection, cacheTestResult, testAudioScheduledSourceNodeStartMethodNegativeParametersSupport, testAudioScheduledSourceNodeStopMethodConsecutiveCallsSupport, testAudioScheduledSourceNodeStopMethodNegativeParametersSupport, wrapAudioScheduledSourceNodeStopMethodConsecutiveCalls); + var createOscillatorNodeRenderer = createOscillatorNodeRendererFactory(connectAudioParam, createNativeOscillatorNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode); + var oscillatorNodeConstructor = createOscillatorNodeConstructor(audioNodeConstructor, createAudioParam, createNativeOscillatorNode, createOscillatorNodeRenderer, getNativeContext, isNativeOfflineAudioContext, wrapEventListener); + var createConnectedNativeAudioBufferSourceNode = createConnectedNativeAudioBufferSourceNodeFactory(createNativeAudioBufferSourceNode); + var createNativeWaveShaperNodeFaker = createNativeWaveShaperNodeFakerFactory(createConnectedNativeAudioBufferSourceNode, createInvalidStateError, createNativeGainNode, isDCCurve, monitorConnections); + var createNativeWaveShaperNode = createNativeWaveShaperNodeFactory(createConnectedNativeAudioBufferSourceNode, createInvalidStateError, createNativeWaveShaperNodeFaker, isDCCurve, monitorConnections, nativeAudioContextConstructor, overwriteAccessors); + var createNativePannerNodeFaker = createNativePannerNodeFakerFactory(connectNativeAudioNodeToNativeAudioNode, createInvalidStateError, createNativeChannelMergerNode, createNativeGainNode, createNativeScriptProcessorNode, createNativeWaveShaperNode, createNotSupportedError, disconnectNativeAudioNodeFromNativeAudioNode, getFirstSample, monitorConnections); + var createNativePannerNode = createNativePannerNodeFactory(createNativePannerNodeFaker); + var createPannerNodeRenderer = createPannerNodeRendererFactory(connectAudioParam, createNativeChannelMergerNode, createNativeConstantSourceNode, createNativeGainNode, createNativePannerNode, getNativeAudioNode, nativeOfflineAudioContextConstructor, renderAutomation, renderInputsOfAudioNode, renderNativeOfflineAudioContext); + var pannerNodeConstructor = createPannerNodeConstructor(audioNodeConstructor, createAudioParam, createNativePannerNode, createPannerNodeRenderer, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime); + var createNativePeriodicWave = createNativePeriodicWaveFactory(createIndexSizeError); + var periodicWaveConstructor = createPeriodicWaveConstructor(createNativePeriodicWave, getNativeContext, new WeakSet(), sanitizePeriodicWaveOptions); + var nativeStereoPannerNodeFakerFactory = createNativeStereoPannerNodeFakerFactory(createNativeChannelMergerNode, createNativeChannelSplitterNode, createNativeGainNode, createNativeWaveShaperNode, createNotSupportedError, monitorConnections); + var createNativeStereoPannerNode = createNativeStereoPannerNodeFactory(nativeStereoPannerNodeFakerFactory, createNotSupportedError); + var createStereoPannerNodeRenderer = createStereoPannerNodeRendererFactory(connectAudioParam, createNativeStereoPannerNode, getNativeAudioNode, renderAutomation, renderInputsOfAudioNode); + var stereoPannerNodeConstructor = createStereoPannerNodeConstructor(audioNodeConstructor, createAudioParam, createNativeStereoPannerNode, createStereoPannerNodeRenderer, getNativeContext, isNativeOfflineAudioContext); + var createWaveShaperNodeRenderer = createWaveShaperNodeRendererFactory(createNativeWaveShaperNode, getNativeAudioNode, renderInputsOfAudioNode); + var waveShaperNodeConstructor = createWaveShaperNodeConstructor(audioNodeConstructor, createInvalidStateError, createNativeWaveShaperNode, createWaveShaperNodeRenderer, getNativeContext, isNativeOfflineAudioContext, setAudioNodeTailTime); + var isSecureContext = createIsSecureContext(window$1); + var exposeCurrentFrameAndCurrentTime = createExposeCurrentFrameAndCurrentTime(window$1); + var backupOfflineAudioContextStore = new WeakMap(); + var getOrCreateBackupOfflineAudioContext = createGetOrCreateBackupOfflineAudioContext(backupOfflineAudioContextStore, nativeOfflineAudioContextConstructor); + // The addAudioWorkletModule() function is only available in a SecureContext. + var addAudioWorkletModule = isSecureContext ? createAddAudioWorkletModule(cacheTestResult, createNotSupportedError, createEvaluateSource(window$1), exposeCurrentFrameAndCurrentTime, createFetchSource(createAbortError), getNativeContext, getOrCreateBackupOfflineAudioContext, isNativeOfflineAudioContext, nativeAudioWorkletNodeConstructor, new WeakMap(), new WeakMap(), createTestAudioWorkletProcessorPostMessageSupport(nativeAudioWorkletNodeConstructor, nativeOfflineAudioContextConstructor), + // @todo window is guaranteed to be defined because isSecureContext checks that as well. + window$1) : undefined; + var isNativeContext = createIsNativeContext(isNativeAudioContext, isNativeOfflineAudioContext); + var decodeAudioData = createDecodeAudioData(audioBufferStore, cacheTestResult, createDataCloneError, createEncodingError, new WeakSet(), getNativeContext, isNativeContext, testAudioBufferCopyChannelMethodsOutOfBoundsSupport, testPromiseSupport, wrapAudioBufferCopyChannelMethods, wrapAudioBufferCopyChannelMethodsOutOfBounds); + var baseAudioContextConstructor = createBaseAudioContextConstructor(addAudioWorkletModule, analyserNodeConstructor, audioBufferConstructor, audioBufferSourceNodeConstructor, biquadFilterNodeConstructor, channelMergerNodeConstructor, channelSplitterNodeConstructor, constantSourceNodeConstructor, convolverNodeConstructor, decodeAudioData, delayNodeConstructor, dynamicsCompressorNodeConstructor, gainNodeConstructor, iIRFilterNodeConstructor, minimalBaseAudioContextConstructor, oscillatorNodeConstructor, pannerNodeConstructor, periodicWaveConstructor, stereoPannerNodeConstructor, waveShaperNodeConstructor); + var mediaElementAudioSourceNodeConstructor = createMediaElementAudioSourceNodeConstructor(audioNodeConstructor, createNativeMediaElementAudioSourceNode, getNativeContext, isNativeOfflineAudioContext); + var mediaStreamAudioDestinationNodeConstructor = createMediaStreamAudioDestinationNodeConstructor(audioNodeConstructor, createNativeMediaStreamAudioDestinationNode, getNativeContext, isNativeOfflineAudioContext); + var mediaStreamAudioSourceNodeConstructor = createMediaStreamAudioSourceNodeConstructor(audioNodeConstructor, createNativeMediaStreamAudioSourceNode, getNativeContext, isNativeOfflineAudioContext); + var createNativeMediaStreamTrackAudioSourceNode = createNativeMediaStreamTrackAudioSourceNodeFactory(createInvalidStateError, isNativeOfflineAudioContext); + var mediaStreamTrackAudioSourceNodeConstructor = createMediaStreamTrackAudioSourceNodeConstructor(audioNodeConstructor, createNativeMediaStreamTrackAudioSourceNode, getNativeContext); + var audioContextConstructor = createAudioContextConstructor(baseAudioContextConstructor, createInvalidStateError, createNotSupportedError, createUnknownError, mediaElementAudioSourceNodeConstructor, mediaStreamAudioDestinationNodeConstructor, mediaStreamAudioSourceNodeConstructor, mediaStreamTrackAudioSourceNodeConstructor, nativeAudioContextConstructor); + var getUnrenderedAudioWorkletNodes = createGetUnrenderedAudioWorkletNodes(unrenderedAudioWorkletNodeStore); + var addUnrenderedAudioWorkletNode = createAddUnrenderedAudioWorkletNode(getUnrenderedAudioWorkletNodes); + var connectMultipleOutputs = createConnectMultipleOutputs(createIndexSizeError); + var deleteUnrenderedAudioWorkletNode = createDeleteUnrenderedAudioWorkletNode(getUnrenderedAudioWorkletNodes); + var disconnectMultipleOutputs = createDisconnectMultipleOutputs(createIndexSizeError); + var activeAudioWorkletNodeInputsStore = new WeakMap(); + var getActiveAudioWorkletNodeInputs = createGetActiveAudioWorkletNodeInputs(activeAudioWorkletNodeInputsStore, getValueForKey); + var createNativeAudioWorkletNodeFaker = createNativeAudioWorkletNodeFakerFactory(connectMultipleOutputs, createIndexSizeError, createInvalidStateError, createNativeChannelMergerNode, createNativeChannelSplitterNode, createNativeConstantSourceNode, createNativeGainNode, createNativeScriptProcessorNode, createNotSupportedError, disconnectMultipleOutputs, exposeCurrentFrameAndCurrentTime, getActiveAudioWorkletNodeInputs, monitorConnections); + var createNativeAudioWorkletNode = createNativeAudioWorkletNodeFactory(createInvalidStateError, createNativeAudioWorkletNodeFaker, createNativeGainNode, createNotSupportedError, monitorConnections); + var createAudioWorkletNodeRenderer = createAudioWorkletNodeRendererFactory(connectAudioParam, connectMultipleOutputs, createNativeAudioBufferSourceNode, createNativeChannelMergerNode, createNativeChannelSplitterNode, createNativeConstantSourceNode, createNativeGainNode, deleteUnrenderedAudioWorkletNode, disconnectMultipleOutputs, exposeCurrentFrameAndCurrentTime, getNativeAudioNode, nativeAudioWorkletNodeConstructor, nativeOfflineAudioContextConstructor, renderAutomation, renderInputsOfAudioNode, renderNativeOfflineAudioContext); + var getBackupOfflineAudioContext = createGetBackupOfflineAudioContext(backupOfflineAudioContextStore); + var setActiveAudioWorkletNodeInputs = createSetActiveAudioWorkletNodeInputs(activeAudioWorkletNodeInputsStore); + // The AudioWorkletNode constructor is only available in a SecureContext. + var audioWorkletNodeConstructor = isSecureContext ? createAudioWorkletNodeConstructor(addUnrenderedAudioWorkletNode, audioNodeConstructor, createAudioParam, createAudioWorkletNodeRenderer, createNativeAudioWorkletNode, getAudioNodeConnections, getBackupOfflineAudioContext, getNativeContext, isNativeOfflineAudioContext, nativeAudioWorkletNodeConstructor, sanitizeAudioWorkletNodeOptions, setActiveAudioWorkletNodeInputs, testAudioWorkletNodeOptionsClonability, wrapEventListener) : undefined; + var minimalAudioContextConstructor = createMinimalAudioContextConstructor(createInvalidStateError, createNotSupportedError, createUnknownError, minimalBaseAudioContextConstructor, nativeAudioContextConstructor); + var createNativeOfflineAudioContext = createCreateNativeOfflineAudioContext(createNotSupportedError, nativeOfflineAudioContextConstructor); + var startRendering = createStartRendering(audioBufferStore, cacheTestResult, getAudioNodeRenderer, getUnrenderedAudioWorkletNodes, renderNativeOfflineAudioContext, testAudioBufferCopyChannelMethodsOutOfBoundsSupport, wrapAudioBufferCopyChannelMethods, wrapAudioBufferCopyChannelMethodsOutOfBounds); + var minimalOfflineAudioContextConstructor = createMinimalOfflineAudioContextConstructor(cacheTestResult, createInvalidStateError, createNativeOfflineAudioContext, minimalBaseAudioContextConstructor, startRendering); + var offlineAudioContextConstructor = createOfflineAudioContextConstructor(baseAudioContextConstructor, cacheTestResult, createInvalidStateError, createNativeOfflineAudioContext, startRendering); + var isAnyAudioContext = createIsAnyAudioContext(CONTEXT_STORE, isNativeAudioContext); + var isAnyAudioNode = createIsAnyAudioNode(AUDIO_NODE_STORE, isNativeAudioNode); + var isAnyAudioParam = createIsAnyAudioParam(AUDIO_PARAM_STORE, isNativeAudioParam); + var isAnyOfflineAudioContext = createIsAnyOfflineAudioContext(CONTEXT_STORE, isNativeOfflineAudioContext); + var isSupported = function isSupported() { + return createIsSupportedPromise(cacheTestResult, createTestAudioBufferCopyChannelMethodsSubarraySupport(nativeOfflineAudioContextConstructor), createTestAudioContextCloseMethodSupport(nativeAudioContextConstructor), createTestAudioContextDecodeAudioDataMethodTypeErrorSupport(nativeOfflineAudioContextConstructor), createTestAudioContextOptionsSupport(nativeAudioContextConstructor), createTestAudioNodeConnectMethodSupport(nativeOfflineAudioContextConstructor), createTestAudioWorkletProcessorNoOutputsSupport(nativeAudioWorkletNodeConstructor, nativeOfflineAudioContextConstructor), createTestChannelMergerNodeChannelCountSupport(nativeOfflineAudioContextConstructor), createTestConstantSourceNodeAccurateSchedulingSupport(nativeOfflineAudioContextConstructor), createTestConvolverNodeBufferReassignabilitySupport(nativeOfflineAudioContextConstructor), createTestConvolverNodeChannelCountSupport(nativeOfflineAudioContextConstructor), testDomExceptionConstructorSupport, createTestIsSecureContextSupport(window$1), createTestMediaStreamAudioSourceNodeMediaStreamWithoutAudioTrackSupport(nativeAudioContextConstructor), createTestStereoPannerNodeDefaultValueSupport(nativeOfflineAudioContextConstructor), testTransferablesSupport); + }; + + exports.AnalyserNode = analyserNodeConstructor; + exports.AudioBuffer = audioBufferConstructor; + exports.AudioBufferSourceNode = audioBufferSourceNodeConstructor; + exports.AudioContext = audioContextConstructor; + exports.AudioWorkletNode = audioWorkletNodeConstructor; + exports.BiquadFilterNode = biquadFilterNodeConstructor; + exports.ChannelMergerNode = channelMergerNodeConstructor; + exports.ChannelSplitterNode = channelSplitterNodeConstructor; + exports.ConstantSourceNode = constantSourceNodeConstructor; + exports.ConvolverNode = convolverNodeConstructor; + exports.DelayNode = delayNodeConstructor; + exports.DynamicsCompressorNode = dynamicsCompressorNodeConstructor; + exports.GainNode = gainNodeConstructor; + exports.IIRFilterNode = iIRFilterNodeConstructor; + exports.MediaElementAudioSourceNode = mediaElementAudioSourceNodeConstructor; + exports.MediaStreamAudioDestinationNode = mediaStreamAudioDestinationNodeConstructor; + exports.MediaStreamAudioSourceNode = mediaStreamAudioSourceNodeConstructor; + exports.MediaStreamTrackAudioSourceNode = mediaStreamTrackAudioSourceNodeConstructor; + exports.MinimalAudioContext = minimalAudioContextConstructor; + exports.MinimalOfflineAudioContext = minimalOfflineAudioContextConstructor; + exports.OfflineAudioContext = offlineAudioContextConstructor; + exports.OscillatorNode = oscillatorNodeConstructor; + exports.PannerNode = pannerNodeConstructor; + exports.PeriodicWave = periodicWaveConstructor; + exports.StereoPannerNode = stereoPannerNodeConstructor; + exports.WaveShaperNode = waveShaperNodeConstructor; + exports.addAudioWorkletModule = addAudioWorkletModule; + exports.decodeAudioData = decodeAudioData; + exports.isAnyAudioContext = isAnyAudioContext; + exports.isAnyAudioNode = isAnyAudioNode; + exports.isAnyAudioParam = isAnyAudioParam; + exports.isAnyOfflineAudioContext = isAnyOfflineAudioContext; + exports.isSupported = isSupported; + +})); diff --git a/js/two-v0.8.1.min.js b/js/two-v0.8.1.min.js new file mode 100644 index 0000000..bd9fc49 --- /dev/null +++ b/js/two-v0.8.1.min.js @@ -0,0 +1,87 @@ +/* +MIT License + +Copyright (c) 2012 - 2021 @jonobr1 / http://jono.fyi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ +var Two=(()=>{var ge=Object.defineProperty;var Gi=Object.getOwnPropertyDescriptor;var qi=Object.getOwnPropertyNames;var Ki=Object.prototype.hasOwnProperty;var Ji=(i,t,e)=>t in i?ge(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var $i=i=>ge(i,"__esModule",{value:!0});var Ce=(i,t)=>{for(var e in t)ge(i,e,{get:t[e],enumerable:!0})},Zi=(i,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of qi(t))!Ki.call(i,r)&&(e||r!=="default")&&ge(i,r,{get:()=>t[r],enumerable:!(s=Gi(t,r))||s.enumerable});return i};var Qi=(i=>(t,e)=>i&&i.get(t)||(e=Zi($i({}),t,1),i&&i.set(t,e),e))(typeof WeakMap!="undefined"?new WeakMap:0);var w=(i,t,e)=>(Ji(i,typeof t!="symbol"?t+"":t,e),e);var Js={};Ce(Js,{default:()=>I});var v={move:"M",line:"L",curve:"C",arc:"A",close:"Z"};var Ie={};Ce(Ie,{HALF_PI:()=>$,NumArray:()=>xt,TWO_PI:()=>J,decomposeMatrix:()=>Lt,getComputedMatrix:()=>pt,getPoT:()=>Pe,lerp:()=>nt,mod:()=>it,setMatrix:()=>Le,toFixed:()=>K});var H;typeof window!="undefined"?H=window:typeof global!="undefined"?H=global:typeof self!="undefined"&&(H=self);var oi,J=Math.PI*2,$=Math.PI*.5;function Lt(i,t,e,s,r,n){let a;return arguments.length<=1?(a=i.a,t=i.b,e=i.c,s=i.d,r=i.e,n=i.f):a=i,{translateX:r,translateY:n,scaleX:Math.sqrt(a*a+t*t),scaleY:Math.sqrt(e*e+s*s),rotation:180*Math.atan2(t,a)/Math.PI}}function Le(i){oi=i}function pt(i,t){t=t&&t.identity()||new oi;let e=i,s=[];for(;e&&e._matrix;)s.push(e._matrix),e=e.parent;s.reverse();for(let r=0;rjt,getAnchorsFromArcData:()=>is,getComponentOnCubicBezier:()=>Dt,getControlPoints:()=>ci,getCurveBoundingBox:()=>je,getCurveFromPoints:()=>Ne,getCurveLength:()=>Be,getReflection:()=>pe,integrate:()=>fi,subdivide:()=>te});var m=class{_events={};_bound=!1;constructor(){}addEventListener(t,e){return(this._events[t]||(this._events[t]=[])).push(e),this._bound=!0,this}on(){return this.addEventListener.apply(this,arguments)}bind(){return this.addEventListener.apply(this,arguments)}removeEventListener(t,e){if(!this._events)return this;if(!t&&!e)return this._events={},this._bound=!1,this;let s=t?[t]:Object.keys(this._events);for(let r=0,n=s.length;r=4){let n=arguments[0]-arguments[2],a=arguments[1]-arguments[3];return Math.atan2(a,n)}let s=t.x-e.x,r=t.y-e.y;return Math.atan2(r,s)}static distanceBetween(t,e){return Math.sqrt(Ot.distanceBetweenSquared(t,e))}static distanceBetweenSquared(t,e){let s=t.x-e.x,r=t.y-e.y;return s*s+r*r}set(t,e){return this.x=t,this.y=e,this}copy(t){return this.x=t.x,this.y=t.y,this}clear(){return this.x=0,this.y=0,this}clone(){return new Ot(this.x,this.y)}add(t,e){return arguments.length<=0?this:(arguments.length<=1?typeof t=="number"?(this.x+=t,this.y+=t):t&&typeof t.x=="number"&&typeof t.y=="number"&&(this.x+=t.x,this.y+=t.y):(this.x+=t,this.y+=e),this)}addSelf(t){return this.add.apply(this,arguments)}sub(t,e){return arguments.length<=0?this:(arguments.length<=1?typeof t=="number"?(this.x-=t,this.y-=t):t&&typeof t.x=="number"&&typeof t.y=="number"&&(this.x-=t.x,this.y-=t.y):(this.x-=t,this.y-=e),this)}subtract(){return this.sub.apply(this,arguments)}subSelf(t){return this.sub.apply(this,arguments)}subtractSelf(t){return this.sub.apply(this,arguments)}multiply(t,e){return arguments.length<=0?this:(arguments.length<=1?typeof t=="number"?(this.x*=t,this.y*=t):t&&typeof t.x=="number"&&typeof t.y=="number"&&(this.x*=t.x,this.y*=t.y):(this.x*=t,this.y*=e),this)}multiplySelf(t){return this.multiply.apply(this,arguments)}multiplyScalar(t){return this.multiply(t)}divide(t,e){return arguments.length<=0?this:(arguments.length<=1?typeof t=="number"?(this.x/=t,this.y/=t):t&&typeof t.x=="number"&&typeof t.y=="number"&&(this.x/=t.x,this.y/=t.y):(this.x/=t,this.y/=e),isNaN(this.x)&&(this.x=0),isNaN(this.y)&&(this.y=0),this)}divideSelf(t){return this.divide.apply(this,arguments)}divideScalar(t){return this.divide(t)}negate(){return this.multiply(-1)}dot(t){return this.x*t.x+this.y*t.y}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.divideScalar(this.length())}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){let e=this.x-t.x,s=this.y-t.y;return e*e+s*s}setLength(t){return this.normalize().multiplyScalar(t)}equals(t,e){return e=typeof e=="undefined"?1e-4:e,this.distanceTo(t)>1,f=s&1?n[h++]*i(o):0;for(;h=0&&t<4294967296}var S={isNaN:function(i){return typeof i=="number"&&i!==+i},isElement:function(i){return!!(i&&i.nodeType===1)},isObject:function(i){let t=typeof i;return t==="function"||t==="object"&&!!i},extend:function(i){let t=ui.call(arguments,1);for(let e=0;e=0&&this.classList.splice(n,1)}this.classList=this.classList.concat(e)}this._className=i}}};var as=Math.cos,os=Math.sin,_i=Math.tan,ze=[],mt=class extends m{elements=new xt(9);manual=!1;constructor(t,e,s,r,n,a){super();let o=t;Array.isArray(o)||(o=Array.prototype.slice.call(arguments)),this.identity(),o.length>0&&this.set(o)}static Multiply(t,e,s){if(e.length<=3){let E=t,C,j,M,T=e[0]||0,N=e[1]||0,z=e[2]||0;return C=E[0]*T+E[1]*N+E[2]*z,j=E[3]*T+E[4]*N+E[5]*z,M=E[6]*T+E[7]*N+E[8]*z,{x:C,y:j,z:M}}let r=t[0],n=t[1],a=t[2],o=t[3],h=t[4],l=t[5],f=t[6],u=t[7],_=t[8],d=e[0],c=e[1],p=e[2],b=e[3],g=e[4],y=e[5],x=e[6],R=e[7],A=e[8];return s=s||new xt(9),s[0]=r*d+n*b+a*x,s[1]=r*c+n*g+a*R,s[2]=r*p+n*y+a*A,s[3]=o*d+h*b+l*x,s[4]=o*c+h*g+l*R,s[5]=o*p+h*y+l*A,s[6]=f*d+u*b+_*x,s[7]=f*c+u*g+_*R,s[8]=f*p+u*y+_*A,s}set(t,e,s,r,n,a,o,h,l){if(typeof e=="undefined"){let f=t;t=f[0],e=f[1],s=f[2],r=f[3],n=f[4],a=f[5],o=f[6],h=f[7],l=f[8]}return this.elements[0]=t,this.elements[1]=e,this.elements[2]=s,this.elements[3]=r,this.elements[4]=n,this.elements[5]=a,this.elements[6]=o,this.elements[7]=h,this.elements[8]=l,this.trigger(m.Types.change)}copy(t){return this.elements[0]=t.elements[0],this.elements[1]=t.elements[1],this.elements[2]=t.elements[2],this.elements[3]=t.elements[3],this.elements[4]=t.elements[4],this.elements[5]=t.elements[5],this.elements[6]=t.elements[6],this.elements[7]=t.elements[7],this.elements[8]=t.elements[8],this.manual=t.manual,this.trigger(m.Types.change)}identity(){return this.elements[0]=mt.Identity[0],this.elements[1]=mt.Identity[1],this.elements[2]=mt.Identity[2],this.elements[3]=mt.Identity[3],this.elements[4]=mt.Identity[4],this.elements[5]=mt.Identity[5],this.elements[6]=mt.Identity[6],this.elements[7]=mt.Identity[7],this.elements[8]=mt.Identity[8],this.trigger(m.Types.change)}multiply(t,e,s,r,n,a,o,h,l){if(typeof e=="undefined")return this.elements[0]*=t,this.elements[1]*=t,this.elements[2]*=t,this.elements[3]*=t,this.elements[4]*=t,this.elements[5]*=t,this.elements[6]*=t,this.elements[7]*=t,this.elements[8]*=t,this.trigger(m.Types.change);if(typeof r=="undefined"){t=t||0,e=e||0,s=s||0,n=this.elements;let V=n[0]*t+n[1]*e+n[2]*s,ft=n[3]*t+n[4]*e+n[5]*s,ct=n[6]*t+n[7]*e+n[8]*s;return{x:V,y:ft,z:ct}}let f=this.elements,u=[t,e,s,r,n,a,o,h,l],_=f[0],d=f[1],c=f[2],p=f[3],b=f[4],g=f[5],y=f[6],x=f[7],R=f[8],A=u[0],E=u[1],C=u[2],j=u[3],M=u[4],T=u[5],N=u[6],z=u[7],W=u[8];return this.elements[0]=_*A+d*j+c*N,this.elements[1]=_*E+d*M+c*z,this.elements[2]=_*C+d*T+c*W,this.elements[3]=p*A+b*j+g*N,this.elements[4]=p*E+b*M+g*z,this.elements[5]=p*C+b*T+g*W,this.elements[6]=y*A+x*j+R*N,this.elements[7]=y*E+x*M+R*z,this.elements[8]=y*C+x*T+R*W,this.trigger(m.Types.change)}inverse(t){let e=this.elements;t=t||new mt;let s=e[0],r=e[1],n=e[2],a=e[3],o=e[4],h=e[5],l=e[6],f=e[7],u=e[8],_=u*o-h*f,d=-u*a+h*l,c=f*a-o*l,p=s*_+r*d+n*c;return p?(p=1/p,t.elements[0]=_*p,t.elements[1]=(-u*r+n*f)*p,t.elements[2]=(h*r-n*o)*p,t.elements[3]=d*p,t.elements[4]=(u*s-n*l)*p,t.elements[5]=(-h*s+n*a)*p,t.elements[6]=c*p,t.elements[7]=(-f*s+r*l)*p,t.elements[8]=(o*s-r*a)*p,t):null}scale(t,e){return arguments.length<=1&&(e=t),this.multiply(t,0,0,0,e,0,0,0,1)}rotate(t){let e=as(t),s=os(t);return this.multiply(e,-s,0,s,e,0,0,0,1)}translate(t,e){return this.multiply(1,0,t,0,1,e,0,0,1)}skewX(t){let e=_i(t);return this.multiply(1,e,0,0,1,0,0,0,1)}skewY(t){let e=_i(t);return this.multiply(1,0,0,e,1,0,0,0,1)}toString(t){return ze.length=0,this.toTransformArray(t,ze),ze.map(K).join(" ")}toTransformArray(t,e){let s=this.elements,r=!!e,n=s[0],a=s[1],o=s[2],h=s[3],l=s[4],f=s[5];if(t){let u=s[6],_=s[7],d=s[8];if(r){e[0]=n,e[1]=h,e[2]=u,e[3]=a,e[4]=l,e[5]=_,e[6]=o,e[7]=f,e[8]=d;return}return[n,h,u,a,l,_,o,f,d]}if(r){e[0]=n,e[1]=h,e[2]=a,e[3]=l,e[4]=o,e[5]=f;return}return[n,h,a,l,o,f]}toArray(t,e){let s=this.elements,r=!!e,n=s[0],a=s[1],o=s[2],h=s[3],l=s[4],f=s[5];if(t){let u=s[6],_=s[7],d=s[8];if(r){e[0]=n,e[1]=a,e[2]=o,e[3]=h,e[4]=l,e[5]=f,e[6]=u,e[7]=_,e[8]=d;return}return[n,a,o,h,l,f,u,_,d]}if(r){e[0]=n,e[1]=a,e[2]=o,e[3]=h,e[4]=l,e[5]=f;return}return[n,a,o,h,l,f]}toObject(){return{elements:this.toArray(!0),manual:!!this.manual}}clone(){return new mt().copy(this)}},at=mt;w(at,"Identity",[1,0,0,0,1,0,0,0,1]);Le(at);var ot=class extends Et{_flagMatrix=!0;_flagScale=!1;_matrix=null;_worldMatrix=null;_position=null;_rotation=0;_scale=1;_skewX=0;_skewY=0;constructor(){super();for(let t in me)Object.defineProperty(this,t,me[t]);this._renderer.flagMatrix=gi.bind(this),this.isShape=!0,this.id=X.Identifier+X.uniqueId(),this.matrix=new at,this.worldMatrix=new at,this.position=new k,this.rotation=0,this.scale=1,this.skewX=0,this.skewY=0}get renderer(){return this._renderer}set renderer(t){this._renderer=t}get translation(){return me.position.get.apply(this,arguments)}set translation(t){me.position.set.apply(this,arguments)}addTo(t){return t.add(this),this}remove(){return this.parent?(this.parent.remove(this),this):this}clone(t){let e=new ot;return e.position.copy(this.position),e.rotation=this.rotation,e.scale=this.scale,e.skewX=this.skewX,e.skewY=this.skewY,this.matrix.manual&&e.matrix.copy(this.matrix),t&&t.add(e),e._update()}_update(t){return!this._matrix.manual&&this._flagMatrix&&(this._matrix.identity().translate(this.position.x,this.position.y),this._scale instanceof k?this._matrix.scale(this._scale.x,this._scale.y):this._matrix.scale(this._scale),this._matrix.rotate(this.rotation),this._matrix.skewX(this.skewX),this._matrix.skewY(this.skewY)),t&&this.parent&&this.parent._update&&this.parent._update(),this}flagReset(){return this._flagMatrix=this._flagScale=!1,super.flagReset.call(this),this}},me={position:{enumerable:!0,get:function(){return this._position},set:function(i){this._position&&this._position.unbind(m.Types.change,this._renderer.flagMatrix),this._position=i,this._position.bind(m.Types.change,this._renderer.flagMatrix),gi.call(this)}},rotation:{enumerable:!0,get:function(){return this._rotation},set:function(i){this._rotation=i,this._flagMatrix=!0}},scale:{enumerable:!0,get:function(){return this._scale},set:function(i){this._scale instanceof k&&this._scale.unbind(m.Types.change,this._renderer.flagMatrix),this._scale=i,this._scale instanceof k&&this._scale.bind(m.Types.change,this._renderer.flagMatrix),this._flagMatrix=!0,this._flagScale=!0}},skewX:{enumerable:!0,get:function(){return this._skewX},set:function(i){this._skewX=i,this._flagMatrix=!0}},skewY:{enumerable:!0,get:function(){return this._skewY},set:function(i){this._skewY=i,this._flagMatrix=!0}},matrix:{enumerable:!0,get:function(){return this._matrix},set:function(i){this._matrix=i,this._flagMatrix=!0}},worldMatrix:{enumerable:!0,get:function(){return pt(this,this._worldMatrix),this._worldMatrix},set:function(i){this._worldMatrix=i}}};function gi(){this._flagMatrix=!0}var lt=class extends Array{_events=new m;get _bound(){return this._events._bound}set _bound(t){this._events._bound=t}addEventListener(){return this._events.addEventListener.apply(this,arguments)}on(){return this._events.on.apply(this,arguments)}bind(){return this._events.bind.apply(this,arguments)}removeEventListener(){return this._events.removeEventListener.apply(this,arguments)}off(){return this._events.off.apply(this,arguments)}unbind(){return this._events.unbind.apply(this,arguments)}dispatchEvent(){return this._events.dispatchEvent.apply(this,arguments)}trigger(){return this._events.trigger.apply(this,arguments)}listen(){return this._events.listen.apply(this,arguments)}ignore(){return this._events.ignore.apply(this,arguments)}constructor(){super();arguments[0]&&Array.isArray(arguments[0])?arguments[0].length>0&&this.push.apply(this,arguments[0]):arguments.length>0&&this.push.apply(this,arguments)}pop(){let t=super.pop.apply(this,arguments);return this.trigger(m.Types.remove,[t]),t}shift(){let t=super.shift.apply(this,arguments);return this.trigger(m.Types.remove,[t]),t}push(){let t=super.push.apply(this,arguments);return this.trigger(m.Types.insert,arguments),t}unshift(){let t=super.unshift.apply(this,arguments);return this.trigger(m.Types.insert,arguments),t}splice(){let t=super.splice.apply(this,arguments);if(this.trigger(m.Types.remove,t),arguments.length>2){let e=this.slice(arguments[0],arguments[0]+arguments.length-2);this.trigger(m.Types.insert,e),this.trigger(m.Types.order)}return t}sort(){return super.sort.apply(this,arguments),this.trigger(m.Types.order),this}reverse(){return super.reverse.apply(this,arguments),this.trigger(m.Types.order),this}indexOf(){return super.indexOf.apply(this,arguments)}};var ye=class extends lt{ids={};constructor(t){t=Array.isArray(t)?t:Array.prototype.slice.call(arguments);super(t);this.attach(t),this.on(m.Types.insert,this.attach),this.on(m.Types.remove,this.detach)}attach(t){for(let e=0;e=0&&e.push(r),r.children)for(let n=0;n=0&&this.children.splice(r,1),this.children.push(s)}return this}remove(t){let e=arguments.length,s=this.parent;if(e<=0&&s)return s.remove(this),this;t instanceof Array?t=t.slice():t=Array.prototype.slice.call(arguments);for(let r=0;r=0&&this.children.splice(a,1)}return this}getBoundingClientRect(t){let e,s,r,n,a,o,h,l,f,u;this._update(!0);let _=1/0,d=-1/0,c=1/0,p=-1/0,b=/texture|gradient/i;s=t?this._matrix:pt(this);for(let g=0;go+e?(s.beginning=1,s.ending=1):lo&&ho&&l0&&e(this._children)),this._children=new ye(i),this._children.bind(m.Types.insert,t),this._children.bind(m.Types.remove,e),this._children.bind(m.Types.order,s),i.length>0&&t(i)}},mask:{enumerable:!0,get:function(){return this._mask},set:function(i){this._mask=i,this._flagMask=!0,S.isObject(i)&&!i.clip&&(i.clip=!0)}}};function mi(i,t){let e=i.parent,s;if(e===t){r();return}if(e&&e.children.ids[i.id]&&(s=Array.prototype.indexOf.call(e.children,i),e.children.splice(s,1),n()),t){r();return}n(),e._flagAdditions&&e.additions.length===0&&(e._flagAdditions=!1),e._flagSubtractions&&e.subtractions.length===0&&(e._flagSubtractions=!1),delete i.parent;function r(){t.subtractions.length>0&&(s=Array.prototype.indexOf.call(t.subtractions,i),s>=0&&t.subtractions.splice(s,1)),t.additions.length>0&&(s=Array.prototype.indexOf.call(t.additions,i),s>=0&&t.additions.splice(s,1)),i.parent=t,t.additions.push(i),t._flagAdditions=!0}function n(){s=Array.prototype.indexOf.call(e.additions,i),s>=0&&e.additions.splice(s,1),s=Array.prototype.indexOf.call(e.subtractions,i),s<0&&(e.subtractions.push(i),e._flagSubtractions=!0)}}var yi=new at,De=[],He=Math.max,ls=Math.min,xi=Math.abs,ve=Math.sin,we=Math.cos,hs=Math.acos,ke=Math.sqrt,tt={isHidden:/(undefined|none|transparent)/i,alignments:{left:"start",middle:"center",right:"end"},shim:function(i,t){return i.tagName=i.nodeName=t||"canvas",i.nodeType=1,i.getAttribute=function(e){return this[e]},i.setAttribute=function(e,s){return this[e]=s,this},i},group:{renderChild:function(i){tt[i._renderer.type].render.call(i,this.ctx,!0,this.clip)},render:function(i){if(!this._visible)return this;this._update();let t=this._matrix.elements,e=this.parent;this._renderer.opacity=this._opacity*(e&&e._renderer?e._renderer.opacity:1);let s=this._mask,r=Ae(t),n=!r||!!s;if(this._renderer.context||(this._renderer.context={}),this._renderer.context.ctx=i,n&&(i.save(),r||i.transform(t[0],t[3],t[1],t[4],t[2],t[5])),s&&tt[s._renderer.type].render.call(s,i,!0),this._opacity>0&&this._scale!==0)for(let a=0;a0&&(i.lineDashOffset=rt.offset||0,i.setLineDash(rt)),i.beginPath();let Mt,$t,Zt,Qt,wt,Q,ai;for(let Ct=0;Ct=p&&_&&(x=R,N=y.controls&&y.controls.right||k.zero,z=x.controls&&x.controls.left||k.zero,y._relative?(C=N.x+y.x,j=N.y+y.y):(C=N.x,j=N.y),x._relative?(A=z.x+x.x,E=z.y+x.y):(A=z.x,E=z.y),W=x.x,V=x.y,i.bezierCurveTo(C,j,A,E,W,V));break;case v.line:i.lineTo(W,V);break;case v.move:R=y,i.moveTo(W,V);break}return _&&i.closePath(),!ct&&!e&&(tt.isHidden.test(a)||(ut=a._renderer&&a._renderer.offset,ut&&(i.save(),i.translate(-a._renderer.offset.x,-a._renderer.offset.y),i.scale(a._renderer.scale.x,a._renderer.scale.y)),i.fill(),ut&&i.restore()),tt.isHidden.test(r)||(ut=r._renderer&&r._renderer.offset,ut&&(i.save(),i.translate(-r._renderer.offset.x,-r._renderer.offset.y),i.scale(r._renderer.scale.x,r._renderer.scale.y),i.lineWidth=n/r._renderer.scale.x),i.stroke(),ut&&i.restore())),Z||i.restore(),ct&&!e&&i.clip(),rt&&rt.length>0&&i.setLineDash(De),this.flagReset()}},points:{render:function(i,t,e){let s,r,n,a,o,h,l,f,u,_,d,c,p,b,g,y;if(y=this.parent&&this.parent._renderer?this.parent._renderer.opacity:1,o=this._opacity*(y||1),h=this._visible,!t&&(!h||o===0))return this;this._update(),s=this._matrix.elements,r=this._stroke,n=this._linewidth,a=this._fill,f=this._renderer.collection,u=f.length,p=Ae(s),g=this.dashes,l=this._size,p||(i.save(),i.transform(s[0],s[3],s[1],s[4],s[2],s[5])),a&&(typeof a=="string"?i.fillStyle=a:(tt[a._renderer.type].render.call(a,i,this),i.fillStyle=a._renderer.effect)),r&&(typeof r=="string"?i.strokeStyle=r:(tt[r._renderer.type].render.call(r,i,this),i.strokeStyle=r._renderer.effect),n&&(i.lineWidth=n)),typeof o=="number"&&(i.globalAlpha=o),g&&g.length>0&&(i.lineDashOffset=g.offset||0,i.setLineDash(g)),i.beginPath();let x=l*.5,R;this._sizeAttenuation||(pt(this,yi),R=yi.elements,R=Lt(R[0],R[3],R[1],R[4],R[2],R[5]),x/=Math.max(R.scaleX,R.scaleY));for(let A=0;A0&&i.setLineDash(De),this.flagReset()}},text:{render:function(i,t,e){let s=this.parent&&this.parent._renderer?this.parent._renderer.opacity:1,r=this._opacity*s,n=this._visible,a=this._mask,o=this._clip;if(!t&&(!n||o||r===0))return this;this._update();let h=this._matrix.elements,l=this._stroke,f=this._linewidth,u=this._fill,_=this._decoration,d=Ae(h),c=u._renderer&&u._renderer.offset&&l._renderer&&l._renderer.offset,p=this.dashes,b=tt.alignments[this._alignment]||this._alignment,g=this._baseline,y,x,R,A,E,C,j,M,T,N,z;if(d||(i.save(),i.transform(h[0],h[3],h[1],h[4],h[2],h[5])),a&&tt[a._renderer.type].render.call(a,i,!0),c||(i.font=[this._style,this._weight,this._size+"px/"+this._leading+"px",this._family].join(" ")),i.textAlign=b,i.textBaseline=g,u&&(typeof u=="string"?i.fillStyle=u:(tt[u._renderer.type].render.call(u,i,this),i.fillStyle=u._renderer.effect)),l&&(typeof l=="string"?i.strokeStyle=l:(tt[l._renderer.type].render.call(l,i,this),i.strokeStyle=l._renderer.effect),f&&(i.lineWidth=f)),typeof r=="number"&&(i.globalAlpha=r),p&&p.length>0&&(i.lineDashOffset=p.offset||0,i.setLineDash(p)),!o&&!e&&(tt.isHidden.test(u)||(u._renderer&&u._renderer.offset?(C=u._renderer.scale.x,j=u._renderer.scale.y,i.save(),i.translate(-u._renderer.offset.x,-u._renderer.offset.y),i.scale(C,j),y=this._size/u._renderer.scale.y,x=this._leading/u._renderer.scale.y,i.font=[this._style,this._weight,y+"px/",x+"px",this._family].join(" "),R=u._renderer.offset.x/u._renderer.scale.x,A=u._renderer.offset.y/u._renderer.scale.y,i.fillText(this.value,R,A),i.restore()):i.fillText(this.value,0,0)),tt.isHidden.test(l)||(l._renderer&&l._renderer.offset?(C=l._renderer.scale.x,j=l._renderer.scale.y,i.save(),i.translate(-l._renderer.offset.x,-l._renderer.offset.y),i.scale(C,j),y=this._size/l._renderer.scale.y,x=this._leading/l._renderer.scale.y,i.font=[this._style,this._weight,y+"px/",x+"px",this._family].join(" "),R=l._renderer.offset.x/l._renderer.scale.x,A=l._renderer.offset.y/l._renderer.scale.y,E=f/l._renderer.scale.x,i.lineWidth=E,i.strokeText(this.value,R,A),i.restore()):i.strokeText(this.value,0,0))),/(underline|strikethrough)/i.test(_)){let W=i.measureText(this.value),V=1;switch(_){case"underline":T=W.actualBoundingBoxAscent,z=W.actualBoundingBoxAscent;break;case"strikethrough":T=0,z=0,V=.5;break}switch(g){case"top":T+=this._size*V,z+=this._size*V;break;case"baseline":case"bottom":T-=this._size*V,z-=this._size*V;break}switch(b){case"left":case"start":M=0,N=W.width;break;case"right":case"end":M=-W.width,N=0;break;default:M=-W.width/2,N=W.width/2}i.lineWidth=Math.max(Math.floor(this._size/15),1),i.strokeStyle=i.fillStyle,i.beginPath(),i.moveTo(M,T),i.lineTo(N,z),i.stroke()}return d||i.restore(),o&&!e&&i.clip(),p&&p.length>0&&i.setLineDash(De),this.flagReset()}},"linear-gradient":{render:function(i,t){if(!!t){if(this._update(),!this._renderer.effect||this._flagEndPoints||this._flagStops||this._flagUnits){let e,s=this.left._x,r=this.left._y,n=this.right._x,a=this.right._y;/objectBoundingBox/i.test(this._units)&&(e=t.getBoundingClientRect(!0),s=(s-.5)*e.width,r=(r-.5)*e.height,n=(n-.5)*e.width,a=(a-.5)*e.height),this._renderer.effect=i.createLinearGradient(s,r,n,a);for(let o=0;o1){let V=ke(y);s=V*s,r=V*r,b=s*s,g=r*r}let x=b*p+g*c,R=(b*g-x)/x,A=ke(He(0,R));n===a&&(A=-A);let E=A*s*d/r,C=-A*r*_/s,j=we(o)*E-ve(o)*C+(t+h)/2,M=ve(o)*E+we(o)*C+(e+l)/2,T=bi(1,0,(_-E)/s,(d-C)/r),N=bi((_-E)/s,(d-C)/r,(-_-E)/s,(-d-C)/r)%J,z=T+N;fs(i,j,M,s,r,T,z,a===0,o)}},kt=class extends m{constructor(t){super();let e=t.smoothing!==!1;this.domElement=t.domElement||document.createElement("canvas"),this.ctx=this.domElement.getContext("2d"),this.overdraw=t.overdraw||!1,typeof this.ctx.imageSmoothingEnabled!="undefined"&&(this.ctx.imageSmoothingEnabled=e),this.scene=new G,this.scene.parent=this}setSize(t,e,s){return this.width=t,this.height=e,this.ratio=typeof s=="undefined"?Ht(this.ctx):s,this.domElement.width=t*this.ratio,this.domElement.height=e*this.ratio,this.domElement.style&&S.extend(this.domElement.style,{width:t+"px",height:e+"px"}),this.trigger(m.Types.resize,t,e,s)}render(){let t=this.ratio===1;return t||(this.ctx.save(),this.ctx.scale(this.ratio,this.ratio)),this.overdraw||this.ctx.clearRect(0,0,this.width,this.height),tt.group.render.call(this.scene,this.ctx),t||this.ctx.restore(),this}};w(kt,"Utils",tt);function fs(i,t,e,s,r,n,a,o,h){let l=a-n,f=jt.Tolerance.epsilon,u=Math.abs(l)=s)return s-r>=0;r+=a}return!1}function Xt(i,t){let e=i._length;if(t<=0)return 0;if(t>=e)return i._lengths.length-1;for(let s=0,r=0;s=t)return t-=r,Math.max(s-1,0)+t/i._lengths[s];r+=i._lengths[s]}return-1}function Re(i,t,e){let s,r,n,a,o,h,l,f,u=t.controls&&t.controls.right,_=i.controls&&i.controls.left;return s=t.x,o=t.y,r=(u||t).x,h=(u||t).y,n=(_||i).x,l=(_||i).y,a=i.x,f=i.y,u&&t._relative&&(r+=t.x,h+=t.y),_&&i._relative&&(n+=i.x,l+=i.y),Be(s,o,r,h,n,l,a,f,e)}function Xe(i,t,e){let s,r,n,a,o,h,l,f,u=t.controls&&t.controls.right,_=i.controls&&i.controls.left;return s=t.x,o=t.y,r=(u||t).x,h=(u||t).y,n=(_||i).x,l=(_||i).y,a=i.x,f=i.y,u&&t._relative&&(r+=t.x,h+=t.y),_&&i._relative&&(n+=i.x,l+=i.y),te(s,o,r,h,n,l,a,f,e)}var Tt=class extends Et{_flagOffset=!0;_flagOpacity=!0;_flagColor=!0;_offset=0;_opacity=1;_color="#fff";constructor(t,e,s){super();for(let r in vi)Object.defineProperty(this,r,vi[r]);this._renderer.type="stop",this.offset=typeof t=="number"?t:Tt.Index<=0?0:1,this.opacity=typeof s=="number"?s:1,this.color=typeof e=="string"?e:Tt.Index<=0?"#fff":"#000",Tt.Index=(Tt.Index+1)%2}clone(){let t=new Tt;return S.each(Tt.Properties,function(e){t[e]=this[e]},this),t}toObject(){let t={};return S.each(Tt.Properties,function(e){t[e]=this[e]},this),t}flagReset(){return this._flagOffset=this._flagColor=this._flagOpacity=!1,super.flagReset.call(this),this}},_t=Tt;w(_t,"Index",0),w(_t,"Properties",["offset","opacity","color"]);var vi={offset:{enumerable:!0,get:function(){return this._offset},set:function(i){this._offset=i,this._flagOffset=!0,this.parent&&(this.parent._flagStops=!0)}},opacity:{enumerable:!0,get:function(){return this._opacity},set:function(i){this._opacity=i,this._flagOpacity=!0,this.parent&&(this.parent._flagStops=!0)}},color:{enumerable:!0,get:function(){return this._color},set:function(i){this._color=i,this._flagColor=!0,this.parent&&(this.parent._flagStops=!0)}}};var ee=class extends Et{_flagStops=!1;_flagSpread=!1;_flagUnits=!1;_spread="";_units="";constructor(t){super();for(let e in wi)Object.defineProperty(this,e,wi[e]);this._renderer.type="gradient",this.id=X.Identifier+X.uniqueId(),this.classList=[],this._renderer.flagStops=cs.bind(this),this._renderer.bindStops=us.bind(this),this._renderer.unbindStops=ds.bind(this),this.spread="pad",this.units="objectBoundingBox",t&&(this.stops=t)}clone(t){let e=this.stops.map(function(r){return r.clone()}),s=new ee(e);return S.each(ee.Properties,function(r){s[r]=this[r]},this),t&&t.add(s),s}toObject(){let t={stops:this.stops.map(function(e){return e.toObject()})};return S.each(ee.Properties,function(e){t[e]=this[e]},this),t}_update(){return(this._flagSpread||this._flagStops)&&this.trigger(m.Types.change),this}flagReset(){return this._flagSpread=this._flagUnits=this._flagStops=!1,super.flagReset.call(this),this}},Y=ee;w(Y,"Stop",_t),w(Y,"Properties",["spread","stops","renderer","id","units"]);var wi={spread:{enumerable:!0,get:function(){return this._spread},set:function(i){this._spread=i,this._flagSpread=!0}},units:{enumerable:!0,get:function(){return this._units},set:function(i){this._units=i,this._flagUnits=!0}},stops:{enumerable:!0,get:function(){return this._stops},set:function(i){let t=this._renderer.bindStops,e=this._renderer.unbindStops;this._stops&&this._stops.unbind(m.Types.insert,t).unbind(m.Types.remove,e),this._stops=new lt((i||[]).slice(0)),this._stops.bind(m.Types.insert,t).bind(m.Types.remove,e),t(this._stops)}}};function cs(){this._flagStops=!0}function us(i){let t=i.length;for(;t--;)i[t].bind(m.Types.change,this._renderer.flagStops),i[t].parent=this;this._renderer.flagStops()}function ds(i){let t=i.length;for(;t--;)i[t].unbind(m.Types.change,this._renderer.flagStops),delete i[t].parent;this._renderer.flagStops()}var Ye=class extends Y{_flagEndPoints=!1;_left=null;_right=null;constructor(t,e,s,r,n){super(n);for(let a in ki)Object.defineProperty(this,a,ki[a]);this._renderer.type="linear-gradient",this._renderer.flagEndPoints=_s.bind(this),this.left=new k,this.right=new k,typeof t=="number"&&(this.left.x=t),typeof e=="number"&&(this.left.y=e),typeof s=="number"&&(this.right.x=s),typeof r=="number"&&(this.right.y=r)}clone(t){let e=this.stops.map(function(r){return r.clone()}),s=new Ye(this.left._x,this.left._y,this.right._x,this.right._y,e);return S.each(Y.Properties,function(r){s[r]=this[r]},this),t&&t.add(s),s}toObject(){let t=super.toObject.call(this);return t.left=this.left.toObject(),t.right=this.right.toObject(),t}_update(){return(this._flagEndPoints||this._flagSpread||this._flagStops)&&this.trigger(m.Types.change),this}flagReset(){return this._flagEndPoints=!1,super.flagReset.call(this),this}},U=Ye;w(U,"Properties",["left","right"]),w(U,"Stop",_t);var ki={left:{enumerable:!0,get:function(){return this._left},set:function(i){this._left instanceof k&&this._left.unbind(m.Types.change,this._renderer.flagEndPoints),this._left=i,this._left.bind(m.Types.change,this._renderer.flagEndPoints),this._flagEndPoints=!0}},right:{enumerable:!0,get:function(){return this._right},set:function(i){this._right instanceof k&&this._right.unbind(m.Types.change,this._renderer.flagEndPoints),this._right=i,this._right.bind(m.Types.change,this._renderer.flagEndPoints),this._flagEndPoints=!0}}};function _s(){this._flagEndPoints=!0}var ie=class extends Y{_flagRadius=!1;_flagCenter=!1;_flagFocal=!1;_radius=0;_center=null;_focal=null;constructor(t,e,s,r,n,a){super(r);for(let o in Ai)Object.defineProperty(this,o,Ai[o]);this._renderer.type="radial-gradient",this._renderer.flagCenter=gs.bind(this),this._renderer.flagFocal=ps.bind(this),this.center=new k,this.radius=typeof s=="number"?s:20,this.focal=new k,typeof t=="number"&&(this.center.x=t),typeof e=="number"&&(this.center.y=e),this.focal.copy(this.center),typeof n=="number"&&(this.focal.x=n),typeof a=="number"&&(this.focal.y=a)}clone(t){let e=this.stops.map(function(r){return r.clone()}),s=new ie(this.center._x,this.center._y,this._radius,e,this.focal._x,this.focal._y);return S.each(Y.Properties.concat(ie.Properties),function(r){s[r]=this[r]},this),t&&t.add(s),s}toObject(){let t=super.toObject.call(this);return S.each(ie.Properties,function(e){t[e]=this[e]},this),t.center=this.center.toObject(),t.focal=this.focal.toObject(),t}_update(){return(this._flagRadius||this._flatCenter||this._flagFocal||this._flagSpread||this._flagStops)&&this.trigger(m.Types.change),this}flagReset(){return this._flagRadius=this._flagCenter=this._flagFocal=!1,super.flagReset.call(this),this}},D=ie;w(D,"Stop",_t),w(D,"Properties",["center","radius","focal"]);var Ai={radius:{enumerable:!0,get:function(){return this._radius},set:function(i){this._radius=i,this._flagRadius=!0}},center:{enumerable:!0,get:function(){return this._center},set:function(i){this._center&&this._center.unbind(m.Types.change,this._renderer.flagCenter),this._center=i,this._center.bind(m.Types.change,this._renderer.flagCenter),this._flagCenter=!0}},focal:{enumerable:!0,get:function(){return this._focal},set:function(i){this._focal&&this._focal.unbind(m.Types.change,this._renderer.flagFocal),this._focal=i,this._focal.bind(m.Types.change,this._renderer.flagFocal),this._flagFocal=!0}}};function gs(){this._flagCenter=!0}function ps(){this._flagFocal=!0}var Se,Ri={video:/\.(mp4|webm|ogg)$/i,image:/\.(jpe?g|png|gif|tiff|webp)$/i,effect:/texture|gradient/i};H.document&&(Se=document.createElement("a"));var st=class extends Et{_flagSrc=!1;_flagImage=!1;_flagVideo=!1;_flagLoaded=!1;_flagRepeat=!1;_flagOffset=!1;_flagScale=!1;_src="";_image=null;_loaded=!1;_repeat="no-repeat";_scale=1;_offset=null;constructor(t,e){super();this._renderer={};for(let s in Si)Object.defineProperty(this,s,Si[s]);if(this._renderer.type="texture",this._renderer.flagOffset=ms.bind(this),this._renderer.flagScale=ys.bind(this),this.id=X.Identifier+X.uniqueId(),this.classList=[],this.loaded=!1,this.repeat="no-repeat",this.offset=new k,typeof e=="function"){let s=function(){this.unbind(m.Types.load,s),typeof e=="function"&&e()}.bind(this);this.bind(m.Types.load,s)}if(typeof t=="string")this.src=t;else if(typeof t=="object"){let s=Object.prototype.toString.call(t);(s==="[object HTMLImageElement]"||s==="[object HTMLCanvasElement]"||s==="[object HTMLVideoElement]"||s==="[object Image]")&&(this.image=t)}this._update()}static getAbsoluteURL(t){return Se?(Se.href=t,Se.href):t}static loadHeadlessBuffer(t,e){t.image.onload=e,t.image.src=t.src}static getTag(t){return t&&t.nodeName&&t.nodeName.toLowerCase()||"img"}static getImage(t){let e=st.getAbsoluteURL(t);if(st.ImageRegistry.contains(e))return st.ImageRegistry.get(e);let s;return ht.Image?(s=new ht.Image,kt.Utils.shim(s,"img")):H.document?Ri.video.test(e)?s=document.createElement("video"):s=document.createElement("img"):console.warn("Two.js: no prototypical image defined for Two.Texture"),s.crossOrigin="anonymous",s}static load(t,e){let s=t.image,r=st.getTag(s);t._flagImage&&(/canvas/i.test(r)?st.Register.canvas(t,e):(t._src=!ht.isHeadless&&s.getAttribute("two-src")||s.src,st.Register[r](t,e))),t._flagSrc&&(s||(s=st.getImage(t.src),t.image=s),r=st.getTag(s),st.Register[r](t,e))}clone(){let t=new st(this.src);return t.repeat=this.repeat,t.offset.copy(this.origin),t.scale=this.scale,t}toObject(){return{src:this.src,repeat:this.repeat,origin:this.origin.toObject(),scale:typeof this.scale=="number"?this.scale:this.scale.toObject()}}_update(){return(this._flagSrc||this._flagImage)&&(this.trigger(m.Types.change),(this._flagSrc||this._flagImage)&&(this.loaded=!1,st.load(this,function(){this.loaded=!0,this.trigger(m.Types.change).trigger(m.Types.load)}.bind(this)))),this._image&&this._image.readyState>=4&&(this._flagVideo=!0),this}flagReset(){return this._flagSrc=this._flagImage=this._flagLoaded=this._flagRepeat=this._flagVideo=this._flagScale=this._flagOffset=!1,super.flagReset.call(this),this}},B=st;w(B,"Properties",["id","className","src","loaded","repeat","scale","offset","image"]),w(B,"RegularExpressions",Ri),w(B,"ImageRegistry",new Ft),w(B,"Register",{canvas:function(t,e){t._src="#"+t.id,st.ImageRegistry.add(t.src,t.image),typeof e=="function"&&e()},img:function(t,e){let s=t.image,r=function(a){!ht.isHeadless&&s.removeEventListener&&typeof s.removeEventListener=="function"&&(s.removeEventListener("load",r,!1),s.removeEventListener("error",n,!1)),typeof e=="function"&&e()},n=function(a){throw!ht.isHeadless&&typeof s.removeEventListener=="function"&&(s.removeEventListener("load",r,!1),s.removeEventListener("error",n,!1)),new et("unable to load "+t.src)};typeof s.width=="number"&&s.width>0&&typeof s.height=="number"&&s.height>0?r():!ht.isHeadless&&typeof s.addEventListener=="function"&&(s.addEventListener("load",r,!1),s.addEventListener("error",n,!1)),t._src=st.getAbsoluteURL(t._src),!(!ht.isHeadless&&s&&s.getAttribute("two-src"))&&(ht.isHeadless||s.setAttribute("two-src",t.src),st.ImageRegistry.add(t.src,s),ht.isHeadless?st.loadHeadlessBuffer(t,r):t.image.src=t.src)},video:function(t,e){if(ht.isHeadless)throw new et("video textures are not implemented in headless environments.");let s=function(n){t.image.removeEventListener("canplaythrough",s,!1),t.image.removeEventListener("error",r,!1),t.image.width=t.image.videoWidth,t.image.height=t.image.videoHeight,typeof e=="function"&&e()},r=function(n){throw t.image.removeEventListener("canplaythrough",s,!1),t.image.removeEventListener("error",r,!1),new et("unable to load "+t.src)};t._src=st.getAbsoluteURL(t._src),t.image.getAttribute("two-src")||(t.image.setAttribute("two-src",t.src),st.ImageRegistry.add(t.src,t.image)),t.image.readyState>=4?s():(t.image.addEventListener("canplaythrough",s,!1),t.image.addEventListener("error",r,!1),t.image.src=t.src,t.image.load())}});var Si={src:{enumerable:!0,get:function(){return this._src},set:function(i){this._src=i,this._flagSrc=!0}},loaded:{enumerable:!0,get:function(){return this._loaded},set:function(i){this._loaded=i,this._flagLoaded=!0}},repeat:{enumerable:!0,get:function(){return this._repeat},set:function(i){this._repeat=i,this._flagRepeat=!0}},image:{enumerable:!0,get:function(){return this._image},set:function(i){let t=B.getTag(i),e;switch(t){case"canvas":e="#"+i.id;break;default:e=i.src}B.ImageRegistry.contains(e)?this._image=B.ImageRegistry.get(i.src):this._image=i,this._flagImage=!0}},offset:{enumerable:!0,get:function(){return this._offset},set:function(i){this._offset&&this._offset.unbind(m.Types.change,this._renderer.flagOffset),this._offset=i,this._offset.bind(m.Types.change,this._renderer.flagOffset),this._flagOffset=!0}},scale:{enumerable:!0,get:function(){return this._scale},set:function(i){this._scale instanceof k&&this._scale.unbind(m.Types.change,this._renderer.flagScale),this._scale=i,this._scale instanceof k&&this._scale.bind(m.Types.change,this._renderer.flagScale),this._flagScale=!0}}};function ms(){this._flagOffset=!0}function ys(){this._flagScale=!0}var Pt=Math.min,It=Math.max,xs=Math.ceil,bs=Math.floor,vs=new k,Yt=class extends ot{_flagVertices=!0;_flagLength=!0;_flagFill=!0;_flagStroke=!0;_flagLinewidth=!0;_flagOpacity=!0;_flagVisible=!0;_flagCap=!0;_flagJoin=!0;_flagMiter=!0;_flagMask=!1;_flagClip=!1;_length=0;_fill="#fff";_stroke="#000";_linewidth=1;_opacity=1;_visible=!0;_cap="round";_join="round";_miter=4;_closed=!0;_curved=!1;_automatic=!0;_beginning=0;_ending=1;_mask=null;_clip=!1;_dashes=null;constructor(t,e,s,r){super();for(let n in Ei)Object.defineProperty(this,n,Ei[n]);this._renderer.type="path",this._renderer.flagVertices=Ge.bind(this),this._renderer.bindVertices=qe.bind(this),this._renderer.unbindVertices=Ke.bind(this),this._renderer.flagFill=Je.bind(this),this._renderer.flagStroke=$e.bind(this),this._renderer.vertices=[],this._renderer.collection=[],this._closed=!!e,this._curved=!!s,this.beginning=0,this.ending=1,this.fill="#fff",this.stroke="#000",this.linewidth=1,this.opacity=1,this.className="",this.visible=!0,this.cap="butt",this.join="miter",this.miter=4,this.vertices=t,this.automatic=!r,this.dashes=[],this.dashes.offset=0}clone(t){let e=new Yt;for(let s=0;s=y){this._closed?(s=it(Z,x),r=it(Z-1,x),Z===0&&(s=r,r=Z)):(s=Z,r=Math.min(Math.max(Z-1,0),R)),A=this.vertices[s],E=this.vertices[r],y-=rt,this._lengths[Z]!==0?t=y/this._lengths[Z]:t=0;break}rt+=this._lengths[Z]}if(A===null||E===null)return null;if(A){if(!E)return A}else return E;g=E.controls&&E.controls.right,b=A.controls&&A.controls.left,o=E.x,_=E.y,h=(g||E).x,d=(g||E).y,l=(b||A).x,c=(b||A).y,f=A.x,p=A.y,g&&E.relative&&(h+=E.x,d+=E.y),b&&A.relative&&(l+=A.x,c+=A.y),a=Dt(t,o,h,l,f),u=Dt(t,_,d,c,p);let C=nt(o,h,t),j=nt(_,d,t),M=nt(h,l,t),T=nt(d,c,t),N=nt(l,f,t),z=nt(c,p,t),W=nt(C,M,t),V=nt(j,T,t),ft=nt(M,N,t),ct=nt(T,z,t);return S.isObject(e)?(e.x=a,e.y=u,e instanceof F&&(e.controls.left.x=W,e.controls.left.y=V,e.controls.right.x=ft,e.controls.right.y=ct,(typeof e.relative!="boolean"||e.relative)&&(e.controls.left.x-=a,e.controls.left.y-=u,e.controls.right.x-=a,e.controls.right.y-=u)),e.t=t,e):(n=new F(a,u,W-a,V-u,ft-a,ct-u,this._curved?v.curve:v.line),n.t=t,n)}plot(){if(this.curved)return Ne(this._collection,this.closed),this;for(let t=0;t0&&(n[n.length-1].command=v.line),r=o;return}a=Xe(o,r,t),n=n.concat(a),S.each(a,function(l,f){f<=0&&r.command===v.move?l.command=v.move:l.command=v.line}),h>=e&&(this._closed&&this._automatic?(r=o,a=Xe(o,r,t),n=n.concat(a),S.each(a,function(l,f){f<=0&&r.command===v.move?l.command=v.move:l.command=v.line})):s&&n.push(new F(o.x,o.y)),n[n.length-1].command=s?v.close:v.line),r=o},this),this._automatic=!1,this._curved=!1,this.vertices=n,this}_updateLength(t,e){e||this._update();let s=this.vertices.length,r=s-1,n=!1,a=this.vertices[r],o=0;return typeof this._lengths=="undefined"&&(this._lengths=[]),S.each(this.vertices,function(h,l){if(l<=0&&!n||h.command===v.move){a=h,this._lengths[l]=0;return}this._lengths[l]=Re(h,a,t),o+=this._lengths[l],l>=r&&n&&(a=this.vertices[(l+1)%s],this._lengths[l+1]=Re(h,a,t),o+=this._lengths[l+1]),a=h},this),this._length=o,this._flagLength=!1,this}_update(){if(this._flagVertices){this._automatic&&this.plot(),this._flagLength&&this._updateLength(void 0,!0);let t=this._collection.length,e=this._closed,s=Math.min(this._beginning,this._ending),r=Math.max(this._beginning,this._ending),n=Xt(this,s*this._length),a=Xt(this,r*this._length),o=xs(n),h=bs(a),l,f,u,_,d,c;for(this._renderer.vertices.length=0,c=0;ch&&!f?(d=this._renderer.collection[c].copy(this._collection[c]),this.getPointAt(r,d),d.command=this._renderer.collection[c].command,this._renderer.vertices.push(d),f=d,u=this._collection[c-1],u&&u.controls&&(d.controls.relative?d.controls.right.clear():d.controls.right.copy(d),this._renderer.collection[c-1].controls.right.copy(u).lerp(u.controls.right,d.t))):c>=o&&c<=h&&(d=this._renderer.collection[c].copy(this._collection[c]),this._renderer.vertices.push(d),c===h&&We(this,r)?(f=d,!e&&f.controls&&(f.relative?f.controls.right.clear():f.controls.right.copy(f))):c===o&&We(this,s)&&(l=d,l.command=v.move,!e&&l.controls&&(l.relative?l.controls.left.clear():l.controls.left.copy(l))));o>0&&!l&&(c=o-1,d=this._renderer.collection[c].copy(this._collection[c]),this.getPointAt(s,d),d.command=v.move,this._renderer.vertices.unshift(d),_=this._collection[c+1],_&&_.controls&&(d.controls.left.clear(),_.relative?this._renderer.collection[c+1].controls.left.copy(_.controls.left).lerp(k.zero,d.t):(vs.copy(_),this._renderer.collection[c+1].controls.left.copy(_.controls.left).lerp(_,d.t))))}return ot.prototype._update.apply(this,arguments),this}flagReset(){return this._flagVertices=this._flagLength=this._flagFill=this._flagStroke=this._flagLinewidth=this._flagOpacity=this._flagVisible=this._flagCap=this._flagJoin=this._flagMiter=this._flagClip=!1,ot.prototype.flagReset.call(this),this}},L=Yt;w(L,"Properties",["fill","stroke","linewidth","opacity","visible","cap","join","miter","closed","curved","automatic","beginning","ending"]),w(L,"Utils",{getCurveLength:Re});var Ei={linewidth:{enumerable:!0,get:function(){return this._linewidth},set:function(i){this._linewidth=i,this._flagLinewidth=!0}},opacity:{enumerable:!0,get:function(){return this._opacity},set:function(i){this._opacity=i,this._flagOpacity=!0}},visible:{enumerable:!0,get:function(){return this._visible},set:function(i){this._visible=i,this._flagVisible=!0}},cap:{enumerable:!0,get:function(){return this._cap},set:function(i){this._cap=i,this._flagCap=!0}},join:{enumerable:!0,get:function(){return this._join},set:function(i){this._join=i,this._flagJoin=!0}},miter:{enumerable:!0,get:function(){return this._miter},set:function(i){this._miter=i,this._flagMiter=!0}},fill:{enumerable:!0,get:function(){return this._fill},set:function(i){(this._fill instanceof Y||this._fill instanceof U||this._fill instanceof D||this._fill instanceof B)&&this._fill.unbind(m.Types.change,this._renderer.flagFill),this._fill=i,this._flagFill=!0,(this._fill instanceof Y||this._fill instanceof U||this._fill instanceof D||this._fill instanceof B)&&this._fill.bind(m.Types.change,this._renderer.flagFill)}},stroke:{enumerable:!0,get:function(){return this._stroke},set:function(i){(this._stroke instanceof Y||this._stroke instanceof U||this._stroke instanceof D||this._stroke instanceof B)&&this._stroke.unbind(m.Types.change,this._renderer.flagStroke),this._stroke=i,this._flagStroke=!0,(this._stroke instanceof Y||this._stroke instanceof U||this._stroke instanceof D||this._stroke instanceof B)&&this._stroke.bind(m.Types.change,this._renderer.flagStroke)}},length:{get:function(){return this._flagLength&&this._updateLength(),this._length}},closed:{enumerable:!0,get:function(){return this._closed},set:function(i){this._closed=!!i,this._flagVertices=!0}},curved:{enumerable:!0,get:function(){return this._curved},set:function(i){this._curved=!!i,this._flagVertices=!0}},automatic:{enumerable:!0,get:function(){return this._automatic},set:function(i){if(i===this._automatic)return;this._automatic=!!i;let t=this._automatic?"ignore":"listen";S.each(this.vertices,function(e){e[t]()})}},beginning:{enumerable:!0,get:function(){return this._beginning},set:function(i){this._beginning=i,this._flagVertices=!0}},ending:{enumerable:!0,get:function(){return this._ending},set:function(i){this._ending=i,this._flagVertices=!0}},vertices:{enumerable:!0,get:function(){return this._collection},set:function(i){let t=this._renderer.bindVertices,e=this._renderer.unbindVertices;this._collection&&this._collection.unbind(m.Types.insert,t).unbind(m.Types.remove,e),i instanceof lt?this._collection=i:this._collection=new lt(i||[]),this._collection.bind(m.Types.insert,t).bind(m.Types.remove,e),t(this._collection)}},mask:{enumerable:!0,get:function(){return this._mask},set:function(i){this._mask=i,this._flagMask=!0,S.isObject(i)&&!i.clip&&(i.clip=!0)}},clip:{enumerable:!0,get:function(){return this._clip},set:function(i){this._clip=i,this._flagClip=!0}},dashes:{enumerable:!0,get:function(){return this._dashes},set:function(i){typeof i.offset!="number"&&(i.offset=this.dashes&&this._dashes.offset||0),this._dashes=i}}};function Ge(){this._flagVertices=!0,this._flagLength=!0,this.parent&&(this.parent._flagLength=!0)}function qe(i){let t=i.length;for(;t--;)i[t].bind(m.Types.change,this._renderer.flagVertices);this._renderer.flagVertices()}function Ke(i){let t=i.length;for(;t--;)i[t].unbind(m.Types.change,this._renderer.flagVertices);this._renderer.flagVertices()}function Je(){this._flagFill=!0}function $e(){this._flagStroke=!0}var Ze=class extends L{constructor(t,e,s,r){let n=[new F,new F,new F,new F];super(n,!0,!1,!0);for(let a in Fi)Object.defineProperty(this,a,Fi[a]);this.width=s,this.height=r,this.origin=new k,this.translation.set(t,e),this._update()}_flagWidth=0;_flagHeight=0;_width=0;_height=0;_origin=null;_update(){if(this._flagVertices||this._flagWidth||this._flagHeight){let t=this._width/2,e=this._height/2;!this._closed&&this.vertices.length===4&&this.vertices.push(new F),this.vertices[0].set(-t,-e).sub(this._origin).command=v.move,this.vertices[1].set(t,-e).sub(this._origin).command=v.line,this.vertices[2].set(t,e).sub(this._origin).command=v.line,this.vertices[3].set(-t,e).sub(this._origin).command=v.line,this.vertices[4]&&(this.vertices[4].set(-t,-e).sub(this._origin).command=v.line)}return super._update.call(this),this}flagReset(){return this._flagWidth=this._flagHeight=!1,super.flagReset.call(this),this}clone(t){let e=new Ze(0,0,this.width,this.height);e.translation.copy(this.translation),e.rotation=this.rotation,e.scale=this.scale,e.skewX=this.skewX,e.skewY=this.skewY,this.matrix.manual&&e.matrix.copy(this.matrix);for(let s=0;s0&&(S.isNaN(this._lastFrame)&&(this._lastFrame=o-1),a=S.performance.now()-this._startTime,_=this._lastFrame+1,h=1e3*(_-this._firstFrame)/this._frameRate,this._loop?a=a%h:a=Math.min(a,h),l=nt(this._firstFrame,_,a/h),l=Math.floor(l),l!==this._index&&(this._index=l,l>=this._lastFrame-1&&this._onLastFrame&&this._onLastFrame()));let d=this._index%e,c=Math.floor(this._index/e),p=-r*d+(f-r)/2,b=-n*c+(u-n)/2;p!==t.offset.x&&(t.offset.x=p),b!==t.offset.y&&(t.offset.y=b)}return super._update.call(this),this}flagReset(){return this._flagTexture=this._flagColumns=this._flagRows=this._flagFrameRate=!1,super.flagReset.call(this),this}},Nt=Qe;w(Nt,"Properties",["texture","columns","rows","frameRate","index"]);var Ti={texture:{enumerable:!0,get:function(){return this._texture},set:function(i){this._texture=i,this._flagTexture=!0}},columns:{enumerable:!0,get:function(){return this._columns},set:function(i){this._columns=i,this._flagColumns=!0}},rows:{enumerable:!0,get:function(){return this._rows},set:function(i){this._rows=i,this._flagRows=!0}},frameRate:{enumerable:!0,get:function(){return this._frameRate},set:function(i){this._frameRate=i,this._flagFrameRate=!0}},index:{enumerable:!0,get:function(){return this._index},set:function(i){this._index=i,this._flagIndex=!0}}};var ti=Math.cos,ei=Math.sin,se=class extends L{_flagRadius=!1;_radius=0;constructor(t,e,s,r){let n=r?Math.max(r,2):4,a=[];for(let o=0;o2&&(t-=1);let e=4/3*Math.tan(Math.PI/(t*2)),s=this._radius,r=s*e;for(let n=0;n2&&(t-=1);let e=4/3*Math.tan(Math.PI/(this.vertices.length*2)),s=this._width/2,r=this._height/2;for(let n=0;n=0&&t.splice(r,1)}return t}function Ls(i,t){let e=t.split(/[\s,]/),s=-parseFloat(e[0]),r=-parseFloat(e[1]),n=parseFloat(e[2]),a=parseFloat(e[3]);if(s&&r)for(let u=0;u0?i.gradientTransform.baseVal[0].matrix:i.getCTM?i.getCTM():null,o===null))break;switch(_=Lt(o),t._renderer.type){case"linear-gradient":Ni(_,t.left),Ni(_,t.right);break;case"radial-gradient":t.center.x+=_.translateX,t.center.y+=_.translateY,t.focal.x+=_.translateX,t.focal.y+=_.translateY,t.radius*=Math.max(_.scaleX,_.scaleY);break}break;case"transform":if(/none/i.test(l)||(o=i.transform&&i.transform.baseVal&&i.transform.baseVal.length>0?i.transform.baseVal[0].matrix:i.getCTM?i.getCTM():null,o===null))break;X.AutoCalculateImportedMatrices?(_=Lt(o),t.translation.set(_.translateX,_.translateY),t.rotation=Math.PI*(_.rotation/180),t.scale=new k(_.scaleX,_.scaleY),d=parseFloat((s.x+"").replace("px")),c=parseFloat((s.y+"").replace("px")),d&&(t.translation.x=d),c&&(t.translation.y=c)):(o=i.getCTM(),t._matrix.manual=!0,t._matrix.set(o.a,o.b,o.c,o.d,o.e,o.f));break;case"visible":if(t instanceof G){t._visible=l;break}t.visible=l;break;case"stroke-linecap":if(t instanceof G){t._cap=l;break}t.cap=l;break;case"stroke-linejoin":if(t instanceof G){t._join=l;break}t.join=l;break;case"stroke-miterlimit":if(t instanceof G){t._miter=l;break}t.miter=l;break;case"stroke-width":if(t instanceof G){t._linewidth=parseFloat(l);break}t.linewidth=parseFloat(l);break;case"opacity":case"stroke-opacity":case"fill-opacity":if(t instanceof G){t._opacity=parseFloat(l);break}t.opacity=parseFloat(l);break;case"clip-path":if(Rt.cssBackgroundImage.test(l)&&(p=l.replace(Rt.cssBackgroundImage,"$1"),q.defs.current&&q.defs.current.contains(p)&&(g=q.defs.current.get(p),g&&g.childNodes.length>0)))switch(g=g.childNodes[0],y=ae(g.nodeName),t.mask=q[y].call(this,g,{}),t._renderer.type){case"text":case"path":t.position.add(t.mask.position),t.mask.position.clear();break}break;case"fill":case"stroke":f=(t instanceof G?"_":"")+h,Rt.cssBackgroundImage.test(l)?(p=l.replace(Rt.cssBackgroundImage,"$1"),q.defs.current&&q.defs.current.contains(p)?(g=q.defs.current.get(p),g.object||(y=ae(g.nodeName),g.object=q[y].call(this,g,{})),g=g.object):(b=Ps(this),g=b.getById(p)),t[f]=g):t[f]=/none/i.test(l)?"transparent":l;break;case"id":t.id=l;break;case"class":case"className":t.classList=l.split(" "),t._flagClassName=!0;break;case"x":case"y":if(x=t instanceof Y,R=t instanceof U,A=t instanceof D,x||R||A)break;l.match("[a-z%]$")&&!l.endsWith("px")&&(E=new et("only pixel values are supported with the "+h+" attribute."),console.warn(E.name,E.message)),t.translation[h]=parseFloat(l);break;case"font-family":t instanceof gt&&(t.family=l);break;case"font-size":t instanceof gt&&(t.size=l);break;case"font-weight":t instanceof gt&&(t.weight=l);break;case"font-style":t instanceof gt&&(t.style=l);break;case"text-decoration":t instanceof gt&&(t.decoration=l);break;case"line-height":t instanceof gt&&(t.leading=l);break}return Object.keys(i.dataset).length&&(t.dataset=i.dataset),s}function Os(i,t){for(let e=0,s=i.childNodes.length;e with no href."),console.warn(e.name,e.message),null;let r=s.slice(1);if(!q.defs.current.contains(r))return e=new et("unable to find element for reference "+s+"."),console.warn(e.name,e.message),null;let a=q.defs.current.get(r).cloneNode(!0);for(let h=0;h1&&(g=1);break;case"m":case"l":case"t":c.length>2&&(g=2);break;case"s":case"q":c.length>4&&(g=4);break;case"c":c.length>6&&(g=6);break;case"a":c.length>7&&(g=7);break}if(g){for(y=0,x=c.length,A=0;y0)switch(p){case"m":R="l";break;case"M":R="L";break}E.push(R+c.slice(y,y+g).join(" ")),A++}f=Array.prototype.concat.apply(f,E)}else f.push(_)}),S.each(f,function(_,d){let c,p,b,g=_[0],y=g.toLowerCase();l=_.slice(1).trim().match(Rt.path),n=g===y;let x,R,A,E,C,j,M,T,N,z,W,V,ft,ct,Z,ut,rt;switch(y){case"z":if(d>=u)r=!0;else{p=o.x,b=o.y,c=new F(p,b,void 0,void 0,void 0,void 0,v.close);for(let St=s.length-1;St>=0;St--){let Mt=s[St];if(/m/i.test(Mt.command)){o=Mt;break}}}break;case"m":case"l":h=void 0,p=parseFloat(l[0]),b=parseFloat(l[1]),c=new F(p,b,void 0,void 0,void 0,void 0,/m/i.test(y)?v.move:v.line),n&&c.addSelf(o),o=c;break;case"h":case"v":z=/h/i.test(y)?"x":"y",W=/x/i.test(z)?"y":"x",c=new F(void 0,void 0,void 0,void 0,void 0,void 0,v.line),c[z]=parseFloat(l[0]),c[W]=o[W],n&&(c[z]+=o[z]),o=c;break;case"c":case"s":x=o.x,R=o.y,h||(h=new k),/c/i.test(y)?(A=parseFloat(l[0]),E=parseFloat(l[1]),C=parseFloat(l[2]),j=parseFloat(l[3]),M=parseFloat(l[4]),T=parseFloat(l[5])):(N=pe(o,h,n),A=N.x,E=N.y,C=parseFloat(l[0]),j=parseFloat(l[1]),M=parseFloat(l[2]),T=parseFloat(l[3])),n&&(A+=x,E+=R,C+=x,j+=R,M+=x,T+=R),o.controls.right.set(A-o.x,E-o.y),c=new F(M,T,C-M,j-T,void 0,void 0,v.curve),o=c,h=c.controls.left;break;case"t":case"q":x=o.x,R=o.y,h||(h=new k),/q/i.test(y)?(A=parseFloat(l[0]),E=parseFloat(l[1]),C=parseFloat(l[0]),j=parseFloat(l[1]),M=parseFloat(l[2]),T=parseFloat(l[3])):(N=pe(o,h,n),A=N.x,E=N.y,C=N.x,j=N.y,M=parseFloat(l[0]),T=parseFloat(l[1])),n&&(A+=x,E+=R,C+=x,j+=R,M+=x,T+=R),o.controls.right.set((A-o.x)*.33,(E-o.y)*.33),c=new F(M,T,C-M,j-T,void 0,void 0,v.curve),o=c,h=c.controls.left;break;case"a":x=o.x,R=o.y,ft=parseFloat(l[0]),ct=parseFloat(l[1]),Z=parseFloat(l[2]),ut=parseFloat(l[3]),rt=parseFloat(l[4]),M=parseFloat(l[5]),T=parseFloat(l[6]),n&&(M+=x,T+=R),V=new F(M,T),V.command=v.arc,V.rx=ft,V.ry=ct,V.xAxisRotation=Z,V.largeArcFlag=ut,V.sweepFlag=rt,c=V,o=V,h=void 0;break}c&&(Array.isArray(c)?s=s.concat(c):s.push(c))})}e=new L(s,r,void 0,!0).noStroke(),e.fill="black";let a=e.getBoundingClientRect(!0);return a.centroid={x:a.left+a.width/2,y:a.top+a.height/2},S.each(e.vertices,function(o){o.subSelf(a.centroid)}),vt.call(this,i,e,t),e.translation.addSelf(a.centroid),e},circle:function(i,t){let e=parseFloat(i.getAttribute("cx")),s=parseFloat(i.getAttribute("cy")),r=parseFloat(i.getAttribute("r")),n=new Vt(0,0,r).noStroke();return n.fill="black",vt.call(this,i,n,t),n.translation.x=e,n.translation.y=s,n},ellipse:function(i,t){let e=parseFloat(i.getAttribute("cx")),s=parseFloat(i.getAttribute("cy")),r=parseFloat(i.getAttribute("rx")),n=parseFloat(i.getAttribute("ry")),a=new zt(0,0,r,n).noStroke();return a.fill="black",vt.call(this,i,a,t),a.translation.x=e,a.translation.y=s,a},rect:function(i,t){let e=parseFloat(i.getAttribute("rx")),s=parseFloat(i.getAttribute("ry"));if(!S.isNaN(e)||!S.isNaN(s))return q["rounded-rect"](i);let r=parseFloat(i.getAttribute("width")),n=parseFloat(i.getAttribute("height")),a=r/2,o=n/2,h=new bt(0,0,r,n).noStroke();return h.fill="black",vt.call(this,i,h,t),h.translation.x+=a,h.translation.y+=o,h},"rounded-rect":function(i,t){let e=parseFloat(i.getAttribute("rx"))||0,s=parseFloat(i.getAttribute("ry"))||0,r=parseFloat(i.getAttribute("width")),n=parseFloat(i.getAttribute("height")),a=r/2,o=n/2,h=new k(e,s),l=new Ut(0,0,r,n,h).noStroke();return l.fill="black",vt.call(this,i,l,t),l.translation.x+=a,l.translation.y+=o,l},line:function(i,t){let e=parseFloat(i.getAttribute("x1")),s=parseFloat(i.getAttribute("y1")),r=parseFloat(i.getAttribute("x2")),n=parseFloat(i.getAttribute("y2")),a=new Gt(e,s,r,n).noFill();return vt.call(this,i,a,t),a},lineargradient:function(i,t){let e=i.getAttribute("gradientUnits"),s=i.getAttribute("spreadMethod");e||(e="objectBoundingBox"),s||(s="pad");let r=parseFloat(i.getAttribute("x1")||0),n=parseFloat(i.getAttribute("y1")||0),a=parseFloat(i.getAttribute("x2")||0),o=parseFloat(i.getAttribute("y2")||0),h=(a+r)/2,l=(o+n)/2;/userSpaceOnUse/i.test(e)&&(r-=h,n-=l,a-=h,o-=l);let f=[];for(let _=0;_1?y[1]:void 0),b===null?(y=g?g.match(/stop-opacity:\s?([0-9.-]*)/):!1,b=y&&y.length>1?parseFloat(y[1]):1):b=parseFloat(b),f.push(new _t(c,p,b))}let u=new U(r,n,a,o,f);return u.spread=s,u.units=e,vt.call(this,i,u,t),u},radialgradient:function(i,t){let e=i.getAttribute("gradientUnits"),s=i.getAttribute("spreadMethod");e||(e="objectBoundingBox"),s||(s="pad");let r=parseFloat(i.getAttribute("cx"))||0,n=parseFloat(i.getAttribute("cy"))||0,a=parseFloat(i.getAttribute("r")),o=parseFloat(i.getAttribute("fx")),h=parseFloat(i.getAttribute("fy"));S.isNaN(o)&&(o=r),S.isNaN(h)&&(h=n);let l=Math.abs(r+o)/2,f=Math.abs(n+h)/2;/userSpaceOnUse/i.test(e)&&(r-=l,n-=f,o-=l,h-=f);let u=[];for(let d=0;d1?x[1]:void 0),g===null?(x=y?y.match(/stop-opacity:\s?([0-9.-]*)/):!1,g=x&&x.length>1?parseFloat(x[1]):1):g=parseFloat(g),u.push(new _t(p,b,g))}let _=new D(r,n,a,u,o,h);return _.spread=s,_.units=e,vt.call(this,i,_,t),_},text:function(i,t){let e=Es(i.getAttribute("text-anchor"))||"left",s=Fs(i)||"baseline",r=i.textContent,n=new gt(r);return vt.call(this,i,n,t),n.alignment=e,n.baseline=s,n},clippath:function(i,t){return q.defs.current&&!q.defs.current.contains(i.id)&&q.defs.current.add(i.id,i),null},image:function(i,t){let e,s=i.getAttribute("href")||i.getAttribute("xlink:href");if(!s)return e=new et("encountered with no href."),console.warn(e.name,e.message),null;let r=parseFloat(i.getAttribute("x"))||0,n=parseFloat(i.getAttribute("y"))||0,a=parseFloat(i.getAttribute("width")),o=parseFloat(i.getAttribute("height")),h=new Nt(s,r,n);return S.isNaN(a)||(h.width=a),S.isNaN(o)||(h.height=o),vt.call(this,i,h,t),h}};function ri(i,t){let e=new XMLHttpRequest;return e.open("GET",i),e.onreadystatechange=function(){e.readyState===4&&e.status===200&&t(e.responseText)},e.send(),e}var Ee=class extends bt{_flagTextures=!1;_flagFrameRate=!1;_flagIndex=!1;_amount=1;_duration=0;_index=0;_startTime=0;_playing=!1;_firstFrame=0;_lastFrame=0;_loop=!0;_textures=null;_frameRate=0;_origin=null;constructor(t,e,s,r){super(e,s,0,0);for(let n in Vi)Object.defineProperty(this,n,Vi[n]);this._renderer.flagTextures=Is.bind(this),this._renderer.bindTextures=Bs.bind(this),this._renderer.unbindTextures=js.bind(this),this.noStroke(),this.noFill(),Array.isArray(t)?this.textures=t.map(zi.bind(this)):this.textures=[zi(t)],this.origin=new k,this._update(),typeof r=="number"?this.frameRate=r:this.frameRate=Ee.DefaultFrameRate,this.index=0}play(t,e,s){return this._playing=!0,this._firstFrame=0,this._lastFrame=this.amount-1,this._startTime=S.performance.now(),typeof t=="number"&&(this._firstFrame=t),typeof e=="number"&&(this._lastFrame=e),typeof s=="function"?this._onLastFrame=s:delete this._onLastFrame,this._index!==this._firstFrame&&(this._startTime-=1e3*Math.abs(this._index-this._firstFrame)/this._frameRate),this}pause(){return this._playing=!1,this}stop(){return this._playing=!1,this._index=this._firstFrame,this}clone(t){let e=new Ee(this.textures,this.translation.x,this.translation.y,this.frameRate);return e._loop=this._loop,this._playing&&e.play(),t&&t.add(e),e}toObject(){let t=super.toObject.call(this);return t.textures=this.textures.map(function(e){return e.toObject()}),t.frameRate=this.frameRate,t.index=this.index,t._firstFrame=this._firstFrame,t._lastFrame=this._lastFrame,t._loop=this._loop,t}_update(){let t=this._textures,e,s,r,n,a,o,h,l;return t&&(this._flagTextures&&(this._amount=t.length),this._flagFrameRate&&(this._duration=1e3*this._amount/this._frameRate),this._playing&&this._frameRate>0?(n=this._amount,S.isNaN(this._lastFrame)&&(this._lastFrame=n-1),r=S.performance.now()-this._startTime,l=this._lastFrame+1,a=1e3*(l-this._firstFrame)/this._frameRate,this._loop?r=r%a:r=Math.min(r,a),h=nt(this._firstFrame,l,r/a),h=Math.floor(h),h!==this._index&&(this._index=h,o=t[this._index],o.loaded&&(e=o.image.width,s=o.image.height,this.width!==e&&(this.width=e),this.height!==s&&(this.height=s),this.fill=o,h>=this._lastFrame-1&&this._onLastFrame&&this._onLastFrame()))):(this._flagIndex||!(this.fill instanceof B))&&(o=t[this._index],o.loaded&&(e=o.image.width,s=o.image.height,this.width!==e&&(this.width=e),this.height!==s&&(this.height=s)),this.fill=o)),super._update.call(this),this}flagReset(){return this._flagTextures=this._flagFrameRate=!1,super.flagReset.call(this),this}},qt=Ee;w(qt,"Properties",["textures","frameRate","index"]),w(qt,"DefaultFrameRate",30);var Vi={frameRate:{enumerable:!0,get:function(){return this._frameRate},set:function(i){this._frameRate=i,this._flagFrameRate=!0}},index:{enumerable:!0,get:function(){return this._index},set:function(i){this._index=i,this._flagIndex=!0}},textures:{enumerable:!0,get:function(){return this._textures},set:function(i){let t=this._renderer.bindTextures,e=this._renderer.unbindTextures;this._textures&&this._textures.unbind(m.Types.insert,t).unbind(m.Types.remove,e),this._textures=new lt((i||[]).slice(0)),this._textures.bind(m.Types.insert,t).bind(m.Types.remove,e),t(this._textures)}}};function Is(){this._flagTextures=!0}function Bs(i){let t=i.length;for(;t--;)i[t].bind(m.Types.change,this._renderer.flagTextures);this._renderer.flagTextures()}function js(i){let t=i.length;for(;t--;)i[t].unbind(m.Types.change,this._renderer.flagTextures);this._renderer.flagTextures()}function zi(i){if(i instanceof B)return i;if(typeof i=="string")return new B(i)}var le=class extends L{_flagStartAngle=!1;_flagEndAngle=!1;_flagInnerRadius=!1;_flagOuterRadius=!1;_startAngle=0;_endAngle=J;_innerRadius=0;_outerRadius=0;constructor(t,e,s,r,n,a,o){let h=o||X.Resolution*3,l=[];for(let f=0;f0,o=this.vertices,h=a?o.length/2:o.length,l,f=0,u,_,d,c,p,b,g,y,x;for(n?h--:a||(h-=2),u=0,_=h-1;u=n&&l<=a&&(h=this._collection[l],this._renderer.collection.push(h),this._renderer.vertices[o*2+0]=h.x,this._renderer.vertices[o*2+1]=h.y,o++)}return super._update.apply(this,arguments),this}flagReset(){return this._flagVertices=this._flagLength=this._flagFill=this._flagStroke=this._flagLinewidth=this._flagOpacity=this._flagVisible=this._flagSize=this._flagSizeAttenuation=!1,super.flagReset.call(this),this}},he=Kt;w(he,"Properties",["fill","stroke","linewidth","opacity","visible","size","sizeAttenuation","beginning","ending"]);var Di={linewidth:{enumerable:!0,get:function(){return this._linewidth},set:function(i){this._linewidth=i,this._flagLinewidth=!0}},opacity:{enumerable:!0,get:function(){return this._opacity},set:function(i){this._opacity=i,this._flagOpacity=!0}},visible:{enumerable:!0,get:function(){return this._visible},set:function(i){this._visible=i,this._flagVisible=!0}},size:{enumerable:!0,get:function(){return this._size},set:function(i){this._size=i,this._flagSize=!0}},sizeAttenuation:{enumerable:!0,get:function(){return this._sizeAttenuation},set:function(i){this._sizeAttenuation=i,this._flagSizeAttenuation=!0}},fill:{enumerable:!0,get:function(){return this._fill},set:function(i){(this._fill instanceof Y||this._fill instanceof U||this._fill instanceof D||this._fill instanceof B)&&this._fill.unbind(m.Types.change,this._renderer.flagFill),this._fill=i,this._flagFill=!0,(this._fill instanceof Y||this._fill instanceof U||this._fill instanceof D||this._fill instanceof B)&&this._fill.bind(m.Types.change,this._renderer.flagFill)}},stroke:{enumerable:!0,get:function(){return this._stroke},set:function(i){(this._stroke instanceof Y||this._stroke instanceof U||this._stroke instanceof D||this._stroke instanceof B)&&this._stroke.unbind(m.Types.change,this._renderer.flagStroke),this._stroke=i,this._flagStroke=!0,(this._stroke instanceof Y||this._stroke instanceof U||this._stroke instanceof D||this._stroke instanceof B)&&this._stroke.bind(m.Types.change,this._renderer.flagStroke)}},length:{get:function(){return this._flagLength&&this._updateLength(),this._length}},beginning:{enumerable:!0,get:function(){return this._beginning},set:function(i){this._beginning=i,this._flagVertices=!0}},ending:{enumerable:!0,get:function(){return this._ending},set:function(i){this._ending=i,this._flagVertices=!0}},vertices:{enumerable:!0,get:function(){return this._collection},set:function(i){let t=this._renderer.bindVertices,e=this._renderer.unbindVertices;this._collection&&this._collection.unbind(m.Types.insert,t).unbind(m.Types.remove,e),i instanceof lt?this._collection=i:this._collection=new lt(i||[]),this._collection.bind(m.Types.insert,t).bind(m.Types.remove,e),t(this._collection)}},dashes:{enumerable:!0,get:function(){return this._dashes},set:function(i){typeof i.offset!="number"&&(i.offset=this.dashes&&this._dashes.offset||0),this._dashes=i}}};var zs=Math.cos,Us=Math.sin,ce=class extends L{_flagWidth=!1;_flagHeight=!1;_flagSides=!1;_width=0;_height=0;_sides=0;constructor(t,e,s,r){r=Math.max(r||0,3);super();for(let n in Hi)Object.defineProperty(this,n,Hi[n]);this.closed=!0,this.automatic=!1,typeof s=="number"&&(this.width=s*2),typeof s=="number"&&(this.height=s*2),typeof r=="number"&&(this.sides=r),this._update(),typeof t=="number"&&(this.translation.x=t),typeof e=="number"&&(this.translation.y=e)}_update(){if(this._flagVertices||this._flagWidth||this._flagHeight||this._flagSides){let t=this._sides,e=t+1,s=this.vertices.length;s>t&&(this.vertices.splice(t-1,s-t),s=t);for(let r=0;r=s?this.vertices.push(new F(o,h)):this.vertices[r].set(o,h),this.vertices[r].command=r===0?v.move:v.line}}return super._update.call(this),this}flagReset(){return this._flagWidth=this._flagHeight=this._flagSides=!1,super.flagReset.call(this),this}clone(t){let e=new ce(0,0,this.radius,this.sides);e.translation.copy(this.translation),e.rotation=this.rotation,e.scale=this.scale,e.skewX=this.skewX,e.skewY=this.skewY,this.matrix.manual&&e.matrix.copy(this.matrix);for(let s=0;st&&(this.vertices.splice(t-1,s-t),s=t);for(let r=0;r=s?this.vertices.push(new F(h,l)):this.vertices[r].set(h,l),this.vertices[r].command=r===0?v.move:v.line}}return super._update.call(this),this}flagReset(){return this._flagInnerRadius=this._flagOuterRadius=this._flagSides=!1,super.flagReset.call(this),this}clone(t){let e=this.innerRadius,s=this.outerRadius,r=this.sides,n=new de(0,0,e,s,r);n.translation.copy(this.translation),n.rotation=this.rotation,n.scale=this.scale,n.skewX=this.skewX,n.skewY=this.skewY,this.matrix.manual&&n.matrix.copy(this.matrix);for(let a=0;a0&&O.setAttributes(s,t),s},setAttributes:function(i,t){let e=Object.keys(t);for(let s=0;s=s&&t&&(o.command===v.curve&&(u=r,y=o.controls&&o.controls.right||o,x=u.controls&&u.controls.left||u,o.relative?(_=K(y.x+o.x),d=K(y.y+o.y)):(_=K(y.x),d=K(y.y)),u.relative?(c=K(x.x+u.x),p=K(x.y+u.y)):(c=K(x.x),p=K(x.y)),M=K(u.x),T=K(u.y),f+=" C "+_+" "+d+" "+c+" "+p+" "+M+" "+T),o.command!==v.close&&(f+=" Z")),n+=f+" "}return n},pointsToString:function(i,t){let e="",s=t*.5;for(let r=0;r0&&(t["stroke-dasharray"]=this.dashes.join(" "),t["stroke-dashoffset"]=this.dashes.offset||0),this._renderer.elem?O.setAttributes(this._renderer.elem,t):(t.id=this._id,this._renderer.elem=O.createElement("path",t),i.appendChild(this._renderer.elem)),this._flagClip){let s=O.getClip(this,i),r=this._renderer.elem;this._clip?(r.removeAttribute("id"),s.setAttribute("id",this.id),s.appendChild(r)):(s.removeAttribute("id"),r.setAttribute("id",this.id),this.parent._renderer.elem.appendChild(r))}return this._flagMask&&(this._mask?(O[this._mask._renderer.type].render.call(this._mask,i),this._renderer.elem.setAttribute("clip-path","url(#"+this._mask.id+")")):this._renderer.elem.removeAttribute("clip-path")),this.flagReset()}},points:{render:function(i){if(this._opacity===0&&!this._flagOpacity)return this;this._update();let t={};if((this._matrix.manual||this._flagMatrix)&&(t.transform="matrix("+this._matrix.toString()+")"),this._flagId&&(t.id=this._id),this._flagVertices||this._flagSize||this._flagSizeAttenuation){let s=this._size;if(!this._sizeAttenuation){pt(this,Xi);let n=Xi.elements,a=Lt(n[0],n[3],n[1],n[4],n[2],n[5]);s/=Math.max(a.scaleX,a.scaleY)}let r=O.pointsToString(this._renderer.collection,s);t.d=r}return this._fill&&this._fill._renderer&&(this._fill._update(),O[this._fill._renderer.type].render.call(this._fill,i,!0)),this._flagFill&&(t.fill=this._fill&&this._fill.id?"url(#"+this._fill.id+")":this._fill),this._stroke&&this._stroke._renderer&&(this._stroke._update(),O[this._stroke._renderer.type].render.call(this._stroke,i,!0)),this._flagStroke&&(t.stroke=this._stroke&&this._stroke.id?"url(#"+this._stroke.id+")":this._stroke),this._flagLinewidth&&(t["stroke-width"]=this._linewidth),this._flagOpacity&&(t["stroke-opacity"]=this._opacity,t["fill-opacity"]=this._opacity),this._flagClassName&&(t.class=this.classList.join(" ")),this._flagVisible&&(t.visibility=this._visible?"visible":"hidden"),this.dashes&&this.dashes.length>0&&(t["stroke-dasharray"]=this.dashes.join(" "),t["stroke-dashoffset"]=this.dashes.offset||0),this._renderer.elem?O.setAttributes(this._renderer.elem,t):(t.id=this._id,this._renderer.elem=O.createElement("path",t),i.appendChild(this._renderer.elem)),this.flagReset()}},text:{render:function(i){this._update();let t={};if((this._matrix.manual||this._flagMatrix)&&(t.transform="matrix("+this._matrix.toString()+")"),this._flagId&&(t.id=this._id),this._flagFamily&&(t["font-family"]=this._family),this._flagSize&&(t["font-size"]=this._size),this._flagLeading&&(t["line-height"]=this._leading),this._flagAlignment&&(t["text-anchor"]=O.alignments[this._alignment]||this._alignment),this._flagBaseline&&(t["alignment-baseline"]=t["dominant-baseline"]=this._baseline),this._flagStyle&&(t["font-style"]=this._style),this._flagWeight&&(t["font-weight"]=this._weight),this._flagDecoration&&(t["text-decoration"]=this._decoration),this._fill&&this._fill._renderer&&(this._fill._update(),O[this._fill._renderer.type].render.call(this._fill,i,!0)),this._flagFill&&(t.fill=this._fill&&this._fill.id?"url(#"+this._fill.id+")":this._fill),this._stroke&&this._stroke._renderer&&(this._stroke._update(),O[this._stroke._renderer.type].render.call(this._stroke,i,!0)),this._flagStroke&&(t.stroke=this._stroke&&this._stroke.id?"url(#"+this._stroke.id+")":this._stroke),this._flagLinewidth&&(t["stroke-width"]=this._linewidth),this._flagOpacity&&(t.opacity=this._opacity),this._flagClassName&&(t.class=this.classList.join(" ")),this._flagVisible&&(t.visibility=this._visible?"visible":"hidden"),this.dashes&&this.dashes.length>0&&(t["stroke-dasharray"]=this.dashes.join(" "),t["stroke-dashoffset"]=this.dashes.offset||0),this._renderer.elem?O.setAttributes(this._renderer.elem,t):(t.id=this._id,this._renderer.elem=O.createElement("text",t),i.defs.appendChild(this._renderer.elem)),this._flagClip){let s=O.getClip(this,i),r=this._renderer.elem;this._clip?(r.removeAttribute("id"),s.setAttribute("id",this.id),s.appendChild(r)):(s.removeAttribute("id"),r.setAttribute("id",this.id),this.parent._renderer.elem.appendChild(r))}return this._flagMask&&(this._mask?(O[this._mask._renderer.type].render.call(this._mask,i),this._renderer.elem.setAttribute("clip-path","url(#"+this._mask.id+")")):this._renderer.elem.removeAttribute("clip-path")),this._flagValue&&(this._renderer.elem.textContent=this._value),this.flagReset()}},"linear-gradient":{render:function(i,t){t||this._update();let e={};if(this._flagId&&(e.id=this._id),this._flagEndPoints&&(e.x1=this.left._x,e.y1=this.left._y,e.x2=this.right._x,e.y2=this.right._y),this._flagSpread&&(e.spreadMethod=this._spread),this._flagUnits&&(e.gradientUnits=this._units),this._renderer.elem?O.setAttributes(this._renderer.elem,e):(e.id=this._id,this._renderer.elem=O.createElement("linearGradient",e),i.defs.appendChild(this._renderer.elem)),this._flagStops){let s=this._renderer.elem.childNodes.length!==this.stops.length;if(s)for(;this._renderer.elem.lastChild;)this._renderer.elem.removeChild(this._renderer.elem.lastChild);for(let r=0;r0&&(e.x*=-1),e.y>0&&(e.y*=-1)),(this._flagScale||this._flagLoaded||this._flagRepeat)&&(e.width=0,e.height=0,r)){switch(s.width=e.width=r.width,s.height=e.height=r.height,this._repeat){case"no-repeat":e.width+=1,e.height+=1;break}this._scale instanceof k?(e.width*=this._scale.x,e.height*=this._scale.y):(e.width*=this._scale,e.height*=this._scale)}return(this._flagScale||this._flagLoaded)&&(this._renderer.image?O.setAttributes(this._renderer.image,s):this._renderer.image=O.createElement("image",s)),this._renderer.elem?Object.keys(e).length!==0&&O.setAttributes(this._renderer.elem,e):(e.id=this._id,e.patternUnits="userSpaceOnUse",this._renderer.elem=O.createElement("pattern",e),i.defs.appendChild(this._renderer.elem)),this._renderer.elem&&this._renderer.image&&!this._renderer.appended&&(this._renderer.elem.appendChild(this._renderer.image),this._renderer.appended=!0),this.flagReset()}}},Fe=class extends m{constructor(t){super();this.domElement=t.domElement||O.createElement("svg"),this.scene=new G,this.scene.parent=this,this.defs=O.createElement("defs"),this.domElement.appendChild(this.defs),this.domElement.defs=this.defs,this.domElement.style.overflow="hidden"}setSize(t,e){return this.width=t,this.height=e,O.setAttributes(this.domElement,{width:t,height:e}),this.trigger(m.Types.resize,t,e)}render(){return O.group.render.call(this.scene,this.domElement),this}};w(Fe,"Utils",O);var yt={create:function(i,t,e){let s=i.createShader(i[e]);if(i.shaderSource(s,t),i.compileShader(s),!i.getShaderParameter(s,i.COMPILE_STATUS)){let n=i.getShaderInfoLog(s);throw i.deleteShader(s),new et("unable to compile shader "+s+": "+n)}return s},types:{vertex:"VERTEX_SHADER",fragment:"FRAGMENT_SHADER"},path:{vertex:` + precision mediump float; + attribute vec2 a_position; + + uniform mat3 u_matrix; + uniform vec2 u_resolution; + uniform vec4 u_rect; + + varying vec2 v_textureCoords; + + void main() { + vec2 rectCoords = (a_position * (u_rect.zw - u_rect.xy)) + u_rect.xy; + vec2 projected = (u_matrix * vec3(rectCoords, 1.0)).xy; + vec2 normal = projected / u_resolution; + vec2 clipspace = (normal * 2.0) - 1.0; + + gl_Position = vec4(clipspace * vec2(1.0, -1.0), 0.0, 1.0); + v_textureCoords = a_position; + } + `,fragment:` + precision mediump float; + + uniform sampler2D u_image; + varying vec2 v_textureCoords; + + void main() { + vec4 texel = texture2D(u_image, v_textureCoords); + if (texel.a == 0.0) { + discard; + } + gl_FragColor = texel; + } + `},points:{vertex:` + precision mediump float; + attribute vec2 a_position; + + uniform float u_size; + uniform mat3 u_matrix; + uniform vec2 u_resolution; + + varying vec2 v_textureCoords; + + void main() { + vec2 projected = (u_matrix * vec3(a_position, 1.0)).xy; + vec2 normal = projected / u_resolution; + vec2 clipspace = (normal * 2.0) - 1.0; + + gl_PointSize = u_size; + gl_Position = vec4(clipspace * vec2(1.0, -1.0), 0.0, 1.0); + v_textureCoords = a_position; + } + `,fragment:` + precision mediump float; + + uniform sampler2D u_image; + + void main() { + vec4 texel = texture2D(u_image, gl_PointCoord); + if (texel.a == 0.0) { + discard; + } + gl_FragColor = texel; + } + `}};var Te=at.Multiply,Ws=[1,0,0,0,1,0,0,0,1],Bt=new xt(9),Xs=kt.Utils,ni=new xt([0,0,1,0,0,1,0,1,1,0,1,1]),P={precision:.9,isHidden:/(undefined|none|transparent)/i,canvas:H.document?H.document.createElement("canvas"):{getContext:function(){}},alignments:{left:"start",middle:"center",right:"end"},matrix:new at,group:{removeChild:function(i,t){if(i.children)for(let e=0;e0&&(g.lineDashOffset=N.offset||0,g.setLineDash(N));let Z,ut,rt,St,Mt,$t,Zt,Qt;g.save(),g.scale(y.x,y.y),g.translate(ft,ct),g.beginPath();for(let wt=0;wt=W&&T&&(s=Z,f=Q.controls&&Q.controls.right||k.zero,u=s.controls&&s.controls.left||k.zero,Q._relative?(a=f.x+Q.x,o=f.y+Q.y):(a=f.x,o=f.y),s._relative?(r=u.x+s.x,n=u.y+s.y):(r=u.x,n=u.y),_=s.x,d=s.y,g.bezierCurveTo(a,o,r,n,_,d));break;case v.line:g.lineTo(_,d);break;case v.move:Z=Q,g.moveTo(_,d);break}}T&&g.closePath(),P.isHidden.test(A)||(c=A._renderer&&A._renderer.offset,c&&(g.save(),g.translate(-A._renderer.offset.x,-A._renderer.offset.y),g.scale(A._renderer.scale.x,A._renderer.scale.y)),g.fill(),c&&g.restore()),P.isHidden.test(x)||(c=x._renderer&&x._renderer.offset,c&&(g.save(),g.translate(-x._renderer.offset.x,-x._renderer.offset.y),g.scale(x._renderer.scale.x,x._renderer.scale.y),g.lineWidth=R/x._renderer.scale.x),g.stroke(),c&&g.restore()),g.restore()},getBoundingClientRect:function(i,t,e){let s=1/0,r=-1/0,n=1/0,a=-1/0,o,h;i.forEach(function(l){let f=l.x,u=l.y,_=l.controls,d,c,p,b,g,y;n=Math.min(u,n),s=Math.min(f,s),r=Math.max(f,r),a=Math.max(u,a),!!l.controls&&(g=_.left,y=_.right,!(!g||!y)&&(d=l._relative?g.x+f:g.x,c=l._relative?g.y+u:g.y,p=l._relative?y.x+f:y.x,b=l._relative?y.y+u:y.y,!(!d||!c||!p||!b)&&(n=Math.min(c,b,n),s=Math.min(d,p,s),r=Math.max(d,p,r),a=Math.max(c,b,a))))}),typeof t=="number"&&(n-=t,s-=t,r+=t,a+=t),o=r-s,h=a-n,e.top=n,e.left=s,e.right=r,e.bottom=a,e.width=o,e.height=h,e.centroid||(e.centroid={}),e.centroid.x=-s,e.centroid.y=-n},render:function(i,t,e){if(!this._visible||!this._opacity)return this;this._update();let s=e||this.parent,r=t[this._renderer.type],n=s._matrix.manual||s._flagMatrix,a=this._matrix.manual||this._flagMatrix,o=this._renderer.parent!==s,h=this._flagVertices||this._flagFill||this._fill instanceof U&&(this._fill._flagSpread||this._fill._flagStops||this._fill._flagEndPoints)||this._fill instanceof D&&(this._fill._flagSpread||this._fill._flagStops||this._fill._flagRadius||this._fill._flagCenter||this._fill._flagFocal)||this._fill instanceof B&&(this._fill._flagLoaded&&this._fill.loaded||this._fill._flagImage||this._fill._flagVideo||this._fill._flagRepeat||this._fill._flagOffset||this._fill._flagScale)||this._stroke instanceof U&&(this._stroke._flagSpread||this._stroke._flagStops||this._stroke._flagEndPoints)||this._stroke instanceof D&&(this._stroke._flagSpread||this._stroke._flagStops||this._stroke._flagRadius||this._stroke._flagCenter||this._stroke._flagFocal)||this._stroke instanceof B&&(this._stroke._flagLoaded&&this._stroke.loaded||this._stroke._flagImage||this._stroke._flagVideo||this._stroke._flagRepeat||this._stroke._flagOffset||this._fill._flagScale)||this._flagStroke||this._flagLinewidth||this._flagOpacity||s._flagOpacity||this._flagVisible||this._flagCap||this._flagJoin||this._flagMiter||this._flagScale||this.dashes&&this.dashes.length>0||!this._renderer.texture;if((n||a||o)&&(this._renderer.matrix||(this._renderer.matrix=new xt(9)),this._matrix.toTransformArray(!0,Bt),Te(Bt,s._renderer.matrix,this._renderer.matrix),this._renderer.scale instanceof k||(this._renderer.scale=new k),this._scale instanceof k?(this._renderer.scale.x=this._scale.x*s._renderer.scale.x,this._renderer.scale.y=this._scale.y*s._renderer.scale.y):(this._renderer.scale.x=this._scale*s._renderer.scale.x,this._renderer.scale.y=this._scale*s._renderer.scale.y),o&&(this._renderer.parent=s)),this._mask&&(i.clear(i.STENCIL_BUFFER_BIT),i.enable(i.STENCIL_TEST),i.stencilFunc(i.ALWAYS,1,0),i.stencilOp(i.KEEP,i.KEEP,i.REPLACE),i.colorMask(!1,!1,!1,!1),P[this._mask._renderer.type].render.call(this._mask,i,t,this),i.stencilFunc(i.EQUAL,1,255),i.stencilOp(i.KEEP,i.KEEP,i.KEEP),i.colorMask(!0,!0,!0,!0)),h?(this._renderer.rect||(this._renderer.rect={}),this._renderer.opacity=this._opacity*s._renderer.opacity,P.path.getBoundingClientRect(this._renderer.vertices,this._linewidth,this._renderer.rect),P.updateTexture.call(P,i,this)):(this._fill&&this._fill._update&&this._fill._update(),this._stroke&&this._stroke._update&&this._stroke._update()),this._clip&&!e||!this._renderer.texture)return this;t.current!==r&&(i.useProgram(r),i.bindBuffer(i.ARRAY_BUFFER,t.buffers.position),i.vertexAttribPointer(r.position,2,i.FLOAT,!1,0,0),i.enableVertexAttribArray(r.position),i.bufferData(i.ARRAY_BUFFER,ni,i.STATIC_DRAW),t.resolution.flagged||i.uniform2f(i.getUniformLocation(r,"u_resolution"),t.resolution.width,t.resolution.height),t.current=r),t.resolution.flagged&&i.uniform2f(i.getUniformLocation(r,"u_resolution"),t.resolution.width,t.resolution.height),i.bindTexture(i.TEXTURE_2D,this._renderer.texture);let l=this._renderer.rect;return i.uniformMatrix3fv(r.matrix,!1,this._renderer.matrix),i.uniform4f(r.rect,l.left,l.top,l.right,l.bottom),i.drawArrays(i.TRIANGLES,0,6),this._mask&&i.disable(i.STENCIL_TEST),this.flagReset()}},points:{updateCanvas:function(i){let t,e=this.canvas,s=this.ctx,r=i._stroke,n=i._linewidth,a=i._fill,o=i._renderer.opacity||i._opacity,h=i.dashes,l=i._size,f=l;P.isHidden.test(r)||(f+=n),e.width=Pe(f),e.height=e.width;let u=f/e.width,_=e.width/2,d=e.height/2;s.clearRect(0,0,e.width,e.height),a&&(typeof a=="string"?s.fillStyle=a:(P[a._renderer.type].render.call(a,s,i),s.fillStyle=a._renderer.effect)),r&&(typeof r=="string"?s.strokeStyle=r:(P[r._renderer.type].render.call(r,s,i),s.strokeStyle=r._renderer.effect),n&&(s.lineWidth=n/u)),typeof o=="number"&&(s.globalAlpha=o),h&&h.length>0&&(s.lineDashOffset=h.offset||0,s.setLineDash(h)),s.save(),s.translate(_,d),s.scale(P.precision,P.precision),s.beginPath(),s.arc(0,0,l/u*.5,0,J),s.restore(),closed&&s.closePath(),P.isHidden.test(a)||(t=a._renderer&&a._renderer.offset,t&&(s.save(),s.translate(-a._renderer.offset.x,-a._renderer.offset.y),s.scale(a._renderer.scale.x,a._renderer.scale.y)),s.fill(),t&&s.restore()),P.isHidden.test(r)||(t=r._renderer&&r._renderer.offset,t&&(s.save(),s.translate(-r._renderer.offset.x,-r._renderer.offset.y),s.scale(r._renderer.scale.x,r._renderer.scale.y),s.lineWidth=n/r._renderer.scale.x),s.stroke(),t&&s.restore())},render:function(i,t,e){if(!this._visible||!this._opacity)return this;this._update();let s=this._size,r=e||this.parent,n=t[this._renderer.type],a=this._sizeAttenuation,o=this._stroke,h=this._linewidth,l=r._matrix.manual||r._flagMatrix,f=this._matrix.manual||this._flagMatrix,u=this._renderer.parent!==r,_=this._renderer.vertices,d=this._renderer.collection.length,c=this._flagVertices,p=this._flagFill||this._fill instanceof U&&(this._fill._flagSpread||this._fill._flagStops||this._fill._flagEndPoints)||this._fill instanceof D&&(this._fill._flagSpread||this._fill._flagStops||this._fill._flagRadius||this._fill._flagCenter||this._fill._flagFocal)||this._fill instanceof B&&(this._fill._flagLoaded&&this._fill.loaded||this._fill._flagImage||this._fill._flagVideo||this._fill._flagRepeat||this._fill._flagOffset||this._fill._flagScale)||this._stroke instanceof U&&(this._stroke._flagSpread||this._stroke._flagStops||this._stroke._flagEndPoints)||this._stroke instanceof D&&(this._stroke._flagSpread||this._stroke._flagStops||this._stroke._flagRadius||this._stroke._flagCenter||this._stroke._flagFocal)||this._stroke instanceof B&&(this._stroke._flagLoaded&&this._stroke.loaded||this._stroke._flagImage||this._stroke._flagVideo||this._stroke._flagRepeat||this._stroke._flagOffset||this._fill._flagScale)||this._flagStroke||this._flagLinewidth||this._flagOpacity||r._flagOpacity||this._flagVisible||this._flagScale||this.dashes&&this.dashes.length>0||!this._renderer.texture;if((l||f||u)&&(this._renderer.matrix||(this._renderer.matrix=new xt(9)),this._matrix.toTransformArray(!0,Bt),Te(Bt,r._renderer.matrix,this._renderer.matrix),this._renderer.scale instanceof k||(this._renderer.scale=new k),this._scale instanceof k?(this._renderer.scale.x=this._scale.x*r._renderer.scale.x,this._renderer.scale.y=this._scale.y*r._renderer.scale.y):(this._renderer.scale.x=this._scale*r._renderer.scale.x,this._renderer.scale.y=this._scale*r._renderer.scale.y),u&&(this._renderer.parent=r)),c){let b=this._renderer.positionBuffer;b&&i.deleteBuffer(b),this._renderer.positionBuffer=i.createBuffer(),i.bindBuffer(i.ARRAY_BUFFER,this._renderer.positionBuffer),i.vertexAttribPointer(n.position,2,i.FLOAT,!1,0,0),i.enableVertexAttribArray(n.position),i.bufferData(i.ARRAY_BUFFER,_,i.STATIC_DRAW)}return p?(this._renderer.opacity=this._opacity*r._renderer.opacity,P.updateTexture.call(P,i,this)):(this._fill&&this._fill._update&&this._fill._update(),this._stroke&&this._stroke._update&&this._stroke._update()),this._clip&&!e||!this._renderer.texture?this:(P.isHidden.test(o)||(s+=h),s/=P.precision,a&&(s*=Math.max(this._renderer.scale.x,this._renderer.scale.y)),t.current!==n&&(i.useProgram(n),t.resolution.flagged||i.uniform2f(i.getUniformLocation(n,"u_resolution"),t.resolution.width,t.resolution.height),t.current=n),t.resolution.flagged&&i.uniform2f(i.getUniformLocation(n,"u_resolution"),t.resolution.width,t.resolution.height),i.bindTexture(i.TEXTURE_2D,this._renderer.texture),i.uniformMatrix3fv(n.matrix,!1,this._renderer.matrix),i.uniform1f(n.size,s*t.resolution.ratio),i.drawArrays(i.POINTS,0,d),this.flagReset())}},text:{updateCanvas:function(i){let t=this.canvas,e=this.ctx,s=i._renderer.scale,r=i._stroke,n=i._linewidth*s,a=i._fill,o=i._renderer.opacity||i._opacity,h=i.dashes,l=i._decoration;t.width=Math.max(Math.ceil(i._renderer.rect.width*s.x),1),t.height=Math.max(Math.ceil(i._renderer.rect.height*s.y),1);let f=i._renderer.rect.centroid,u=f.x,_=f.y,d,c,p,b,g,y,x,R,A,E,C,j=a._renderer&&a._renderer.offset&&r._renderer&&r._renderer.offset;if(e.clearRect(0,0,t.width,t.height),j||(e.font=[i._style,i._weight,i._size+"px/"+i._leading+"px",i._family].join(" ")),e.textAlign="center",e.textBaseline="middle",a&&(typeof a=="string"?e.fillStyle=a:(P[a._renderer.type].render.call(a,e,i),e.fillStyle=a._renderer.effect)),r&&(typeof r=="string"?e.strokeStyle=r:(P[r._renderer.type].render.call(r,e,i),e.strokeStyle=r._renderer.effect),n&&(e.lineWidth=n)),typeof o=="number"&&(e.globalAlpha=o),h&&h.length>0&&(e.lineDashOffset=h.offset||0,e.setLineDash(h)),e.save(),e.scale(s.x,s.y),e.translate(u,_),P.isHidden.test(a)||(a._renderer&&a._renderer.offset?(y=a._renderer.scale.x,x=a._renderer.scale.y,e.save(),e.translate(-a._renderer.offset.x,-a._renderer.offset.y),e.scale(y,x),d=i._size/a._renderer.scale.y,c=i._leading/a._renderer.scale.y,e.font=[i._style,i._weight,d+"px/",c+"px",i._family].join(" "),p=a._renderer.offset.x/a._renderer.scale.x,b=a._renderer.offset.y/a._renderer.scale.y,e.fillText(i.value,p,b),e.restore()):e.fillText(i.value,0,0)),P.isHidden.test(r)||(r._renderer&&r._renderer.offset?(y=r._renderer.scale.x,x=r._renderer.scale.y,e.save(),e.translate(-r._renderer.offset.x,-r._renderer.offset.y),e.scale(y,x),d=i._size/r._renderer.scale.y,c=i._leading/r._renderer.scale.y,e.font=[i._style,i._weight,d+"px/",c+"px",i._family].join(" "),p=r._renderer.offset.x/r._renderer.scale.x,b=r._renderer.offset.y/r._renderer.scale.y,g=n/r._renderer.scale.x,e.lineWidth=g,e.strokeText(i.value,p,b),e.restore()):e.strokeText(i.value,0,0)),/(underline|strikethrough)/i.test(l)){let M=e.measureText(i.value);switch(l){case"underline":A=M.actualBoundingBoxAscent,C=M.actualBoundingBoxAscent;break;case"strikethrough":A=0,C=0;break}R=-M.width/2,E=M.width/2,e.lineWidth=Math.max(Math.floor(i._size/15),1),e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(R,A),e.lineTo(E,C),e.stroke()}e.restore()},getBoundingClientRect:function(i,t){let e=P.ctx;e.font=[i._style,i._weight,i._size+"px/"+i._leading+"px",i._family].join(" "),e.textAlign="center",e.textBaseline=i._baseline;let s=e.measureText(i._value).width*1.25,r=Math.max(i._size,i._leading)*1.25;this._linewidth&&!P.isHidden.test(this._stroke)&&(s+=this._linewidth*2,r+=this._linewidth*2);let n=s/2,a=r/2;switch(P.alignments[i._alignment]||i._alignment){case P.alignments.left:t.left=0,t.right=s;break;case P.alignments.right:t.left=-s,t.right=0;break;default:t.left=-n,t.right=n}switch(i._baseline){case"bottom":t.top=-r,t.bottom=0;break;case"top":t.top=0,t.bottom=r;break;default:t.top=-a,t.bottom=a}t.width=s,t.height=r,t.centroid||(t.centroid={}),t.centroid.x=n,t.centroid.y=a},render:function(i,t,e){if(!this._visible||!this._opacity)return this;this._update();let s=e||this.parent,r=t[this._renderer.type],n=s._matrix.manual||s._flagMatrix,a=this._matrix.manual||this._flagMatrix,o=this._renderer.parent!==s,h=this._flagVertices||this._flagFill||this._fill instanceof U&&(this._fill._flagSpread||this._fill._flagStops||this._fill._flagEndPoints)||this._fill instanceof D&&(this._fill._flagSpread||this._fill._flagStops||this._fill._flagRadius||this._fill._flagCenter||this._fill._flagFocal)||this._fill instanceof B&&(this._fill._flagLoaded&&this._fill.loaded||this._fill._flagImage||this._fill._flagVideo||this._fill._flagRepeat||this._fill._flagOffset||this._fill._flagScale)||this._stroke instanceof U&&(this._stroke._flagSpread||this._stroke._flagStops||this._stroke._flagEndPoints)||this._stroke instanceof D&&(this._stroke._flagSpread||this._stroke._flagStops||this._stroke._flagRadius||this._stroke._flagCenter||this._stroke._flagFocal)||this._stroke instanceof B&&(this._stroke._flagLoaded&&this._stroke.loaded||this._stroke._flagImage||this._stroke._flagVideo||this._stroke._flagRepeat||this._stroke._flagOffset||this._fill._flagScale)||this._flagStroke||this._flagLinewidth||this._flagOpacity||s._flagOpacity||this._flagVisible||this._flagScale||this._flagValue||this._flagFamily||this._flagSize||this._flagLeading||this._flagAlignment||this._flagBaseline||this._flagStyle||this._flagWeight||this._flagDecoration||this.dashes&&this.dashes.length>0||!this._renderer.texture;if((n||a||o)&&(this._renderer.matrix||(this._renderer.matrix=new xt(9)),this._matrix.toTransformArray(!0,Bt),Te(Bt,s._renderer.matrix,this._renderer.matrix),this._renderer.scale instanceof k||(this._renderer.scale=new k),this._scale instanceof k?(this._renderer.scale.x=this._scale.x*s._renderer.scale.x,this._renderer.scale.y=this._scale.y*s._renderer.scale.y):(this._renderer.scale.x=this._scale*s._renderer.scale.x,this._renderer.scale.y=this._scale*s._renderer.scale.y),o&&(this._renderer.parent=s)),this._mask&&(i.clear(i.STENCIL_BUFFER_BIT),i.enable(i.STENCIL_TEST),i.stencilFunc(i.ALWAYS,1,0),i.stencilOp(i.KEEP,i.KEEP,i.REPLACE),i.colorMask(!1,!1,!1,!1),P[this._mask._renderer.type].render.call(this._mask,i,t,this),i.stencilFunc(i.EQUAL,1,255),i.stencilOp(i.KEEP,i.KEEP,i.KEEP),i.colorMask(!0,!0,!0,!0)),h?(this._renderer.rect||(this._renderer.rect={}),this._renderer.opacity=this._opacity*s._renderer.opacity,P.text.getBoundingClientRect(this,this._renderer.rect),P.updateTexture.call(P,i,this)):(this._fill&&this._fill._update&&this._fill._update(),this._stroke&&this._stroke._update&&this._stroke._update()),this._clip&&!e||!this._renderer.texture)return this;t.current!==r&&(i.useProgram(r),i.bindBuffer(i.ARRAY_BUFFER,t.buffers.position),i.vertexAttribPointer(r.position,2,i.FLOAT,!1,0,0),i.enableVertexAttribArray(r.position),i.bufferData(i.ARRAY_BUFFER,ni,i.STATIC_DRAW),t.resolution.flagged||i.uniform2f(i.getUniformLocation(r,"u_resolution"),t.resolution.width,t.resolution.height),t.current=r),t.resolution.flagged&&i.uniform2f(i.getUniformLocation(r,"u_resolution"),t.resolution.width,t.resolution.height),i.bindTexture(i.TEXTURE_2D,this._renderer.texture);let l=this._renderer.rect;return i.uniformMatrix3fv(r.matrix,!1,this._renderer.matrix),i.uniform4f(r.rect,l.left,l.top,l.right,l.bottom),i.drawArrays(i.TRIANGLES,0,6),this._mask&&i.disable(i.STENCIL_TEST),this.flagReset()}},"linear-gradient":{render:function(i,t){if(!(!i.canvas.getContext("2d")||!t)){if(this._update(),!this._renderer.effect||this._flagEndPoints||this._flagStops||this._flagUnits){let e,s=this.left._x,r=this.left._y,n=this.right._x,a=this.right._y;/objectBoundingBox/i.test(this._units)&&(e=t.getBoundingClientRect(!0),s=(s-.5)*e.width,r=(r-.5)*e.height,n=(n-.5)*e.width,a=(a-.5)*e.height),this._renderer.effect=i.createLinearGradient(s,r,n,a);for(let o=0;o { + if (response == 'granted') { + window.addEventListener("deviceorientation", (event) => { + if (event.webkitCompassHeading) { + heading = event.webkitCompassHeading; + } + }, true); + } + }) + .catch(console.error) + } +} else { + window.addEventListener("deviceorientationabsolute", (event) => { + heading = event.alpha * -1; + }, true); +} + +const watchID = navigator.geolocation.watchPosition( + (position) => { + latitude = position.coords.latitude; + longitude = position.coords.longitude; + }, + (error) => {}, { + enableHighAccuracy: true, + maximumAge: 30000, + timeout: 27000, + } +); + +//distance between 2 locations (lat/lon) +function getDistance(lat1, lon1, lat2, lon2) { + var R = 6371; // Radius of the earth in km + var dLat = deg2rad(lat2 - lat1); // deg2rad below + var dLon = deg2rad(lon2 - lon1); + var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); + var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); + var d = R * c; // Distance in km + return d; +} + +function deg2rad(deg) { + return deg * (Math.PI / 180) +} + +//bearing between 2 locations (lat/lon) + +// Converts from degrees to radians. +function toRadians(degrees) { + return degrees * Math.PI / 180; +}; + +// Converts from radians to degrees. +function toDegrees(radians) { + return radians * 180 / Math.PI; +} + +// const y = Math.sin(λ2-λ1) * Math.cos(φ2); +// const x = Math.cos(φ1)*Math.sin(φ2) - +// Math.sin(φ1)*Math.cos(φ2)*Math.cos(λ2-λ1); +// const θ = Math.atan2(y, x); +// const brng = (θ*180/Math.PI + 360) % 360; in degrees + +function getBearing(startLat, startLng, destLat, destLng) { + startLat = toRadians(startLat); + startLng = toRadians(startLng); + destLat = toRadians(destLat); + destLng = toRadians(destLng); + + y = Math.sin(destLng - startLng) * Math.cos(destLat); + x = Math.cos(startLat) * Math.sin(destLat) - Math.sin(startLat) * Math.cos(destLat) * Math.cos(destLng - startLng); + brng = Math.atan2(y, x); + brng = toDegrees(brng); + return (brng + 360) % 360; +} + +//promisify -> new Tone.Player +function AudioImport(url) { + return new Promise((resolve, reject) => { + var audio = new Tone.Player(url, () => resolve(audio)); + }); +} + +// some p5 tools +class Textline { + static #lines = 0; + static #linestep = 20; + static restart() { + Textline.#lines = 0; + } + static put(t) { + Textline.#lines = Textline.#lines + 1; + text(t, 0, Textline.#linestep * Textline.#lines); + } +}