diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..f3c97dcc9f7b7d9932010772b9cf6efe24a7818f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +source/docs/assets/choir_bwv407.wav filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md index 6e30675d92ba8f3f01bf5391d714279b2b8feeca..06a66e3b04ea59826947f58ba27711bfb58a4679 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,64 @@ --- title: Hendrix -emoji: 📚 -colorFrom: yellow +emoji: 🎹 +colorFrom: purple colorTo: pink sdk: static -pinned: false +app_file: index.html +fullWidth: true +short_description: Music to MIDI on your device. Your audio stays local. +tags: + - music + - automatic-music-transcription + - audio-to-midi + - onnx + - webgpu +custom_headers: + cross-origin-embedder-policy: require-corp + cross-origin-opener-policy: same-origin + cross-origin-resource-policy: cross-origin --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# Hendrix + +Choose an audio file, record with your microphone, or try the short Bach +example. Hendrix predicts notes and instrument families, draws a piano roll, +plays the result, and lets you download a MIDI file. + +Audio decoding and model inference run on your device. The app does not upload +your recording. It downloads the checked 195.3 MB FP32 D26 model on first use. +WebGPU is preferred; WebAssembly supplies a CPU fallback. Start with two +seconds: speed and memory use depend on your browser and device. + +If the embedded app runs slowly, [open the app directly](https://jackboyla-hendrix.hf.space/) +to enable browser isolation and up to four CPU threads. Microphone access also +depends on browser permissions. Predictions are a research result and may +miss notes, assign the wrong instrument, or give poor note endings. MIDI +playback uses a simple browser synth. + +The example is a two-second excerpt of our synthetic Bach BWV 407 chorale +rendering, made from a public-domain score. We do not redistribute the local +YouTube diagnostic audio. + +Model: 46.5M-parameter D26, derived from YPTF-MoE+Multi. `models/fp32/manifest.json` +records the source checkpoint and graph hashes. `deployment.json` records the +app build and file hashes. This Space includes only the checked FP32 release. + +[Source, methods, results, and deployment commands](https://github.com/jackboyla/hendrix) + +This is a static Space: hosting requires no server-side inference or GPU. + +The `source/` directory contains the app source used for this deployment. +To rebuild and publish from that snapshot: + +```bash +cd source +npx --yes pnpm@10.20.0 --dir demo/web install --frozen-lockfile +hf auth login +uv run --no-project --with huggingface_hub==0.36.2 python \ + scripts/deploy_huggingface_space.py --graph-dir ../models/fp32 --upload +``` + +Omit `--upload` to build and check a local package. Each run prints the staging +directory. The script keeps the model hashes fixed and refuses to change an +existing Space's visibility or SDK. diff --git a/assets/PianoRollCanvas-xSq9nagc.js b/assets/PianoRollCanvas-xSq9nagc.js new file mode 100644 index 0000000000000000000000000000000000000000..d6a6090cc6e197cc0e2abb99a0859c6fa13fdb78 --- /dev/null +++ b/assets/PianoRollCanvas-xSq9nagc.js @@ -0,0 +1 @@ +import{o as e,r as t,t as n}from"./style-CdJLhYve.js";var r=e(),i=t();function a(e){let{rollRef:t,audio:a,setUserScrolled:o}=e,s=(0,r.useRef)(null);return(0,r.useEffect)(()=>{let e=s.current,r=new n(e);t.current=r;let i=t=>{t.preventDefault();let n=e.getBoundingClientRect(),i=Math.exp(-t.deltaY*.01);if(t.altKey){r.zoomPitch(i,t.clientY-n.top),o(!0);return}if(t.ctrlKey||t.metaKey){r.zoomTime(i,t.clientX-n.left),o(!0);return}if(t.shiftKey){let e=t.deltaX===0?t.deltaY:t.deltaX;e!==0&&r.scrollBy(e/r.pxPerSec)}else t.deltaX!==0&&r.scrollBy(t.deltaX/r.pxPerSec),t.deltaY!==0&&r.scrollPitchBy(-t.deltaY);o(!0)},c=null,l=t=>{let n=e.getBoundingClientRect(),i=t{let n=e.getBoundingClientRect(),r=t.clientX-n.left;r>=56?(c={wasPlaying:a.state===`started`},c.wasPlaying&&a.pause(),l(t.clientX)):u={x:r,y:t.clientY-n.top},t.preventDefault()},f=t=>{if(c){l(t.clientX);return}let n=e.getBoundingClientRect();if(u){let e=t.clientX-n.left,i=t.clientY-n.top,a=e-u.x,s=i-u.y;a!==0&&r.zoomPitch(Math.exp(a*.01),i),s!==0&&r.scrollPitchBy(s),u={x:e,y:i},o(!0);return}e.style.cursor=t.clientX-n.left<56?`ew-resize`:`default`},p=()=>{c&&=(a.seek(a.seconds),c.wasPlaying&&a.play(),null),u=null},m=null,h=null,g=e=>({dx:Math.abs(e[0].clientX-e[1].clientX),dy:Math.abs(e[0].clientY-e[1].clientY)}),_=e=>{e.touches.length===2?(h=g(e.touches),m=null,e.preventDefault()):e.touches.length===1&&(m={x:e.touches[0].clientX,y:e.touches[0].clientY})},v=t=>{let n=e.getBoundingClientRect();if(h&&t.touches.length===2){t.preventDefault();let e=g(t.touches),i=(t.touches[0].clientX+t.touches[1].clientX)/2-n.left,a=(t.touches[0].clientY+t.touches[1].clientY)/2-n.top;h.dx>12&&e.dx>12&&r.zoomTime(e.dx/h.dx,i),h.dy>12&&e.dy>12&&r.zoomPitch(e.dy/h.dy,a),h=e,o(!0)}else if(m&&t.touches.length===1){t.preventDefault();let e=t.touches[0];r.scrollBy(-(e.clientX-m.x)/r.pxPerSec),r.scrollPitchBy(e.clientY-m.y),m={x:e.clientX,y:e.clientY},o(!0)}},y=e=>{e.touches.length<2&&(h=null),e.touches.length===0&&(m=null)};return e.addEventListener(`wheel`,i,{passive:!1}),e.addEventListener(`touchstart`,_,{passive:!1}),e.addEventListener(`touchmove`,v,{passive:!1}),e.addEventListener(`touchend`,y,{passive:!1}),e.addEventListener(`mousedown`,d),window.addEventListener(`mousemove`,f),window.addEventListener(`mouseup`,p),()=>{e.removeEventListener(`wheel`,i),e.removeEventListener(`touchstart`,_),e.removeEventListener(`touchmove`,v),e.removeEventListener(`touchend`,y),e.removeEventListener(`mousedown`,d),window.removeEventListener(`mousemove`,f),window.removeEventListener(`mouseup`,p)}},[a,t,o]),(0,i.jsx)(`section`,{className:`relative col-start-1 overflow-hidden rounded-card border border-line bg-[linear-gradient(180deg,rgba(255,255,255,0.02),transparent_60px),#0a0b0e] p-0 shadow-[0_1px_0_rgba(255,255,255,0.04)_inset,0_18px_40px_-28px_rgba(0,0,0,0.9)] animate-rise [animation-delay:0.12s]`,children:(0,i.jsx)(`canvas`,{className:`block h-[420px] w-full`,width:1200,height:400,ref:s})})}export{a as t}; \ No newline at end of file diff --git a/assets/local-56CJnE36.css b/assets/local-56CJnE36.css new file mode 100644 index 0000000000000000000000000000000000000000..c9a4b1f7cd5a7d2df5eb7bb20c424a1b9b9480c4 --- /dev/null +++ b/assets/local-56CJnE36.css @@ -0,0 +1 @@ +:root{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark}body{color:#f2f0e9;background:#090a0d;margin:0}.local-shell{width:min(1120px,100% - 28px);padding:max(24px, env(safe-area-inset-top)) 0 56px;gap:18px;margin:0 auto;font-family:Inter,ui-sans-serif,system-ui,sans-serif;display:grid}.local-hero{border-bottom:1px solid #30323a;padding:clamp(24px,6vw,72px) 4px 20px}.local-kicker{color:#ff627d;letter-spacing:.18em;font-size:12px;font-weight:800;text-decoration:none}.local-hero h1{letter-spacing:-.06em;max-width:850px;margin:14px 0;font-family:Georgia,serif;font-size:clamp(54px,11vw,124px);font-weight:500;line-height:.82}.local-hero p{color:#b7bac4;max-width:700px;margin:26px 0 0;font-size:clamp(16px,2vw,21px);line-height:1.5}.local-card{background:#111319;border:1px solid #2d3038;border-radius:16px;box-shadow:inset 0 1px #ffffff0a}.capability-card{color:#c7cad2;align-items:center;gap:10px;padding:14px 18px;font-size:13px;display:flex}.status-dot{background:#ff627d;border-radius:50%;width:9px;height:9px;box-shadow:0 0 14px #ff627d88}.status-dot.ready{background:#70e09b;box-shadow:0 0 14px #70e09b88}.input-card{padding:clamp(18px,4vw,34px)}.file-row,.action-row,.result-bar{flex-wrap:wrap;align-items:center;gap:10px;display:flex}.primary-button,.secondary-button,.record-button{appearance:none;font:inherit;cursor:pointer;border:1px solid #0000;border-radius:999px;padding:12px 18px;font-weight:750;text-decoration:none}.primary-button{color:#090a0d;background:#f2f0e9}.secondary-button{color:#f2f0e9;background:#1b1e25;border-color:#3a3e48}.record-button{color:#fff;background:#d83455;animation:1.3s infinite pulse-record}button:disabled{cursor:not-allowed;opacity:.38}.primary-button:has(input:disabled){cursor:not-allowed;opacity:.38}.limit-label{color:#9da1ac;align-items:center;gap:8px;margin-left:auto;font-size:13px;display:flex}.limit-label select{color:#fff;background:#171920;border:1px solid #3a3e48;border-radius:8px;padding:8px}.chosen-file{color:#f2f0e9;text-overflow:ellipsis;white-space:nowrap;margin:22px 0;font-family:ui-monospace,monospace;overflow:hidden}.progress-track{background:#262933;border-radius:9px;height:5px;margin-top:22px;overflow:hidden}.progress-track>div{background:linear-gradient(90deg,#f57,#f3b65c);height:100%;transition:width .2s}.run-status{color:#aeb1bb;min-height:1.5em;margin:12px 0 0;font-size:14px}.run-status.error{color:#ff8ca0}.diagnostic-output{overflow-wrap:anywhere;color:#858994;margin:10px 0 0;font:11px/1.5 ui-monospace,monospace}.result-bar{background:#111319;border:1px solid #2d3038;border-radius:16px;padding:16px 18px}.result-bar>div{min-width:80px}.result-bar strong{font-family:Georgia,serif;font-size:30px;font-weight:500;display:block}.result-bar span{color:#8f939e;letter-spacing:.12em;text-transform:uppercase;font-size:11px}.result-bar button{margin-left:auto}.roll-stage{position:relative}.roll-empty{color:#b7bac4;pointer-events:none;background:#111319e8;border:1px solid #3a3e48;border-radius:999px;width:max-content;max-width:80%;padding:11px 16px;font-size:13px;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)}.local-footer{color:#858994;grid-template-columns:minmax(0,1fr) auto;align-items:start;gap:16px 36px;padding:8px 4px 0;font-size:12px;line-height:1.5;display:grid}.local-footer p{max-width:650px;margin:0}.local-footer-links{flex-wrap:wrap;justify-content:flex-end;gap:8px 16px;max-width:380px;display:flex}.local-footer a{color:#d9dce5;text-underline-offset:3px;text-decoration-color:#626670}@keyframes pulse-record{50%{box-shadow:0 0 0 7px #d8345522}}@media (width<=640px){.local-shell{width:min(100% - 20px,1120px)}.local-hero h1{font-size:58px}.limit-label{width:100%;margin:8px 0 0}.result-bar button{margin-left:0}.local-footer{grid-template-columns:1fr}.local-footer-links{justify-content:flex-start}}.run-hint{color:#aeb1bb;margin:16px 0 0;font-size:13px;line-height:1.5}.run-diagnostics{color:#aeb1bb;margin-top:12px;font-size:12px}.run-diagnostics summary{cursor:pointer}.primary-button:focus-within,button:focus-visible,a:focus-visible,select:focus-visible{outline-offset:4px;outline:2px solid #ff627d} diff --git a/assets/local-DblFrGk8.js b/assets/local-DblFrGk8.js new file mode 100644 index 0000000000000000000000000000000000000000..a7bd666e3176281b374a7265e8595511f13d521c --- /dev/null +++ b/assets/local-DblFrGk8.js @@ -0,0 +1,4 @@ +import{a as e,i as t,o as n,r,s as i}from"./style-CdJLhYve.js";import{t as a}from"./PianoRollCanvas-xSq9nagc.js";var o=n(),s=e(),c=[[`acoustic_piano`,[0,1,3,6,7]],[`electric_piano`,[2,4,5]],[`chromatic_percussion`,l(8,16)],[`organ`,l(16,24)],[`acoustic_guitar`,[24,25]],[`clean_electric_guitar`,[26,27,28]],[`distorted_electric_guitar`,[29,30,31]],[`acoustic_bass`,[32,35]],[`electric_bass`,[33,34,36,37,38,39]],[`violin`,[40]],[`viola`,[41]],[`cello`,[42]],[`contrabass`,[43]],[`orchestral_harp`,[46]],[`timpani`,[47]],[`string_ensemble`,[48,49,44,45]],[`synth_strings`,[50,51]],[`voice`,[52,53,54,100,101]],[`orchestra_hit`,[55]],[`trumpet`,[56,59]],[`trombone`,[57]],[`tuba`,[58]],[`french_horn`,[60]],[`brass_section`,[61,62,63]],[`soprano_and_alto_sax`,[64,65]],[`tenor_sax`,[66]],[`baritone_sax`,[67]],[`oboe`,[68]],[`english_horn`,[69]],[`bassoon`,[70]],[`clarinet`,[71]],[`flutes`,l(72,80)],[`synth_lead`,l(80,88)],[`synth_pad`,l(88,96)]];function l(e,t){return Array.from({length:t-e},(t,n)=>e+n)}var u=new Map;for(let[e,t]of c)for(let n of t)u.set(n,e);function d(e){return e.isDrum?`drums`:u.get(e.program)??`program_${e.program}`}function f(e){if(e===0)return{type:`PAD`,value:0};if(e===1)return{type:`EOS`,value:0};if(e===2)return{type:`UNK`,value:0};if(e<=208)return{type:`shift`,value:e-3};if(e<=336)return{type:`pitch`,value:e-209};if(e<=338)return{type:`velocity`,value:e-337};if(e===339)return{type:`tie`,value:0};if(e<=467)return{type:`program`,value:e-340};if(e<=595)return{type:`drum`,value:e-468};throw Error(`unknown token ${e}`)}function p(e,t){let n=e.map(f),r=null,i=[],a=[],o=-1;for(let e=0;e0&&(l=c+e.value);else if(e.type===`drum`)s.push({isDrum:!0,program:128,time:l/100,velocity:1,pitch:e.value});else if(e.type===`program`)r=e.value;else if(e.type===`velocity`)u=e.value;else if(e.type===`pitch`&&r!==null&&u!==null){let t=`${r}:${e.value}`;if(u>0)a.push([r,e.value]);else{let e=a.findIndex(([e,n])=>`${e}:${n}`===t);if(e<0)continue;a.splice(e,1)}s.push({isDrum:!1,program:r,time:l/100,velocity:u,pitch:e.value})}else if(e.type===`EOS`)break;return s.sort((e,t)=>(e.time??0)-(t.time??0)||Number(e.isDrum)-Number(t.isDrum)||e.program-t.program||e.velocity-t.velocity||e.pitch-t.pitch),i.sort((e,t)=>Number(e.isDrum)-Number(t.isDrum)||e.program-t.program||e.pitch-t.pitch),{notes:s,ties:i,lastActivity:a,start:t}}function m(e){let t=new Map,n=[];e.sort((e,t)=>(e.time??0)-(t.time??0)||Number(e.isDrum)-Number(t.isDrum)||e.pitch-t.pitch||e.velocity-t.velocity||e.program-t.program);for(let r of e){if(r.time===null)continue;if(r.isDrum){n.push({onset:r.time,offset:r.time+.01,pitch:r.pitch,program:128,isDrum:!0,velocity:1});continue}let e=`${r.pitch}:${r.program}`;if(r.velocity===1){let i=t.get(e);i!==void 0&&i.time!==null&&n.push({onset:i.time,offset:r.time,pitch:r.pitch,program:r.program,isDrum:!1,velocity:i.velocity}),t.set(e,r)}else{let i=t.get(e);t.delete(e),i!==void 0&&i.time!==null&&n.push({onset:i.time,offset:r.time,pitch:r.pitch,program:r.program,isDrum:!1,velocity:i.velocity})}}for(let e of t.values())e.time!==null&&n.push({onset:e.time,offset:e.time+.01,pitch:e.pitch,program:e.program,isDrum:!1,velocity:1});return n}function h(e){let t=new Map;for(let n of e){let e=`${n.pitch}:${n.program}:${Number(n.isDrum)}`,r=t.get(e)??[];r.push(n),t.set(e,r)}let n=[];for(let e of t.values()){e.sort((e,t)=>e.onset-t.onset);for(let t=1;te[t].onset&&(e[t-1].offset=e[t].onset);n.push(...e.filter(e=>e.onsete.onset-t.onset||Number(e.isDrum)-Number(t.isDrum)||e.program-t.program||e.velocity-t.velocity||e.pitch-t.pitch)}function g(e,t,n){let r=[];for(let n=0;n<13;n++){let i=e.map((e,r)=>p(e[n],r*t)),a=[],o=null;for(let e of i){if(o!==null){let t=new Set(e.ties.map(e=>`${e.program}:${e.pitch}`));for(let[n,r]of o)t.has(`${n}:${r}`)||a.push({isDrum:!1,program:n,time:e.start,velocity:0,pitch:r})}a.push(...e.notes),o=e.lastActivity}r.push(m(a))}return h(r.flat()).filter(e=>e.onset({...e,offset:Math.min(n,Math.max(e.offset,e.onset+.01))}))}var _=16e3,v=32767,y=2048,b=1024;async function ee(e,t){let n=new AudioContext;try{let r=await n.decodeAudioData(await e.arrayBuffer()),i=t===void 0?r.duration:Math.min(r.duration,t),a=Math.max(1,Math.ceil(i*_)),o=new OfflineAudioContext(1,a,_),s=o.createBuffer(1,r.length,r.sampleRate),c=s.getChannelData(0);for(let e=0;e>=1;this.reversed[t]=r}}magnitude(e,t,n){for(let t=0;t.5-.5*Math.cos(2*Math.PI*t/y));function S(e,t){let n=e;for(;n<0||n>=t;)n=n<0?-n:2*t-2-n;return n}function C(e){if(e.length!==32767)throw Error(`expected ${v} samples, got ${e.length}`);let t=new Float32Array(y),n=new Float32Array(110*b),r=y/2;for(let i=0;i<110;i++){let a=i*300-r;for(let n=0;n>=7)>0;)t=t<<8|e&127|128;for(;n.push(t&255),t&128;)t>>=8;return n}function T(e){return[e>>8&255,e&255]}function E(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}function D(e,t){return[...Array.from(e).map(e=>e.charCodeAt(0)),...E(t.length),...t]}function re(e){let t=new Map;for(let n of e){let e=n.isDrum?`drums`:String(n.program),r=t.get(e)??[];r.push(n),t.set(e,r)}let n=[];n.push(D(`MTrk`,[0,255,81,3,7,161,32,0,255,47,0]));let r=0;for(let[e,i]of t){let t=e===`drums`;for(;r===9;)r++;let a=t?9:r++%16,o=t?0:Number(e),s=[];t||s.push({tick:0,order:0,bytes:[192|a,o&127]});for(let e of i){let t=Math.max(0,Math.round(e.onset*960)),n=Math.max(t+1,Math.round(e.offset*960));s.push({tick:t,order:1,bytes:[144|a,e.pitch&127,100]}),s.push({tick:n,order:0,bytes:[128|a,e.pitch&127,0]})}s.sort((e,t)=>e.tick-t.tick||e.order-t.order);let c=[],l=0;for(let e of s)c.push(...w(e.tick-l),...e.bytes),l=e.tick;c.push(0,255,47,0),n.push(D(`MTrk`,c))}let i=D(`MThd`,[...T(1),...T(n.length),...T(480)]);return new Blob([new Uint8Array([...i,...n.flat()])],{type:`audio/midi`})}var ie=`modulepreload`,O=function(e){return`/`+e},ae={},oe=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=O(t,n),t in ae)return;ae[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:ie,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},se=Object.defineProperty,ce=Object.getOwnPropertyDescriptor,le=Object.getOwnPropertyNames,ue=Object.prototype.hasOwnProperty,de=(e=>typeof i<`u`?i:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof i<`u`?i:e)[t]}):e)(function(e){if(typeof i<`u`)return i.apply(this,arguments);throw Error(`Dynamic require of "`+e+`" is not supported`)}),k=(e,t)=>()=>(e&&(t=e(e=0)),t),fe=(e,t)=>{for(var n in t)se(e,n,{get:t[n],enumerable:!0})},pe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of le(t))!ue.call(e,i)&&i!==n&&se(e,i,{get:()=>t[i],enumerable:!(r=ce(t,i))||r.enumerable});return e},me=e=>pe(se({},`__esModule`,{value:!0}),e),he,A,ge,j,M,_e=k(()=>{he=new Map,A=[],ge=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=he.get(e);if(r===void 0)he.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=A.indexOf(e);t!==-1&&A.splice(t,1);for(let t=0;t{let t=he.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},M=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?A:n,i,a=[],o=new Set;for(let e of r){let t=await j(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),ve=k(()=>{_e()}),ye,be=k(()=>{ye=`1.27.0`}),xe,N,Se=k(()=>{be(),xe=`warning`,N={wasm:{},webgl:{},webgpu:{},versions:{common:ye},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);xe=e}},get logLevel(){return xe}},Object.defineProperty(N,"logLevel",{enumerable:!0})}),P,Ce=k(()=>{Se(),P=N}),we,Te,Ee=k(()=>{we=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t{Ve(),De=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,De(o,s)}else throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(De(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return De(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},ke=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new I({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},F=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new I({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},Ae=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new I({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},je=(e,t,n)=>new I({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),Ne,Pe,Fe,Ie,Le=k(()=>{Ne=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),Pe=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),Fe=!1,Ie=()=>{if(!Fe){Fe=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(Ne.set(`int64`,BigInt64Array),Pe.set(BigInt64Array,`int64`)),t&&(Ne.set(`uint64`,BigUint64Array),Pe.set(BigUint64Array,`uint64`)),r?(Ne.set(`float16`,n),Pe.set(n,`float16`)):Ne.set(`float16`,Uint16Array)}}}),Re,ze,Be=k(()=>{Ve(),Re=e=>{let t=1;for(let n=0;n{switch(e.location){case`cpu`:return new I(e.type,e.data,t);case`cpu-pinned`:return new I({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new I({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new I({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new I({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),I,Ve=k(()=>{Ee(),Me(),Le(),Be(),I=class{constructor(e,t,n){Ie();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=Ne.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`)if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=Ne.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray)if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`);else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=Pe.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=Re(i);if(this.cpuData&&a!==this.cpuData.length&&!((r===`uint4`||r===`int4`)&&Math.ceil(a/2)===this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return Oe(e,t)}static fromTexture(e,t){return ke(e,t)}static fromGpuBuffer(e,t){return F(e,t)}static fromMLTensor(e,t){return Ae(e,t)}static fromPinnedBuffer(e,t,n){return je(e,t,n)}toDataURL(e){return we(this,e)}toImageData(e){return Te(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return ze(this,e)}}}),L,He=k(()=>{Ve(),L=I}),Ue,We,Ge,Ke,qe,Je,Ye=k(()=>{Se(),Ue=(e,t)=>{(typeof N.trace>`u`?!N.wasm.trace:!N.trace)||console.timeStamp(`${e}::ORT::${t}`)},We=(e,t)=>{let n=Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i{(typeof N.trace>`u`?!N.wasm.trace:!N.trace)||We(`BEGIN`,e)},Ke=e=>{(typeof N.trace>`u`?!N.wasm.trace:!N.trace)||We(`END`,e)},qe=e=>{(typeof N.trace>`u`?!N.wasm.trace:!N.trace)||console.time(`ORT::${e}`)},Je=e=>{(typeof N.trace>`u`?!N.wasm.trace:!N.trace)||console.timeEnd(`ORT::${e}`)}}),Xe,Ze=k(()=>{_e(),He(),Ye(),Xe=class e{constructor(e){this.handler=e}async run(e,t,n){Ge(),qe(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof L||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof L)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof L)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];t instanceof L?s[e]=t:s[e]=new L(t.type,t.data,t.dims)}return Je(`InferenceSession.run`),Ke(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){Ge(),qe(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await M(o),l=await s.createInferenceSessionHandler(a,c);return Je(`InferenceSession.create`),Ke(),new e(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Qe,$e=k(()=>{Ze(),Qe=Xe}),et=k(()=>{}),tt=k(()=>{}),nt=k(()=>{}),rt=k(()=>{});fe({},{InferenceSession:()=>Qe,TRACE:()=>Ue,TRACE_EVENT_BEGIN:()=>qe,TRACE_EVENT_END:()=>Je,TRACE_FUNC_BEGIN:()=>Ge,TRACE_FUNC_END:()=>Ke,Tensor:()=>L,env:()=>P,registerBackend:()=>ge});var it=k(()=>{ve(),Ce(),$e(),He(),et(),tt(),Ye(),nt(),rt()}),at=k(()=>{}),ot={};fe(ot,{default:()=>lt});var st,ct,lt,ut=k(()=>{Wn(),It(),Dt(),st=`ort-wasm-proxy-worker`,ct=globalThis.self?.name===st,ct&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:Ft(n.wasm).then(()=>{Mn(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;Nn(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=Ln(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;Rn(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:zn(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;Vn(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},Un([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:Hn(n),postMessage({type:t});break;default:}}catch(e){postMessage({type:t,err:e})}}),lt=ct?null:e=>new Worker(e??R,{type:`module`,name:st})}),dt={};fe(dt,{default:()=>pt});async function ft(e={}){var t=e,n=!!globalThis.window,r=!!globalThis.WorkerGlobalScope,i=r&&self.name?.startsWith(`em-pthread`);t.mountExternalData=(e,n)=>{e.startsWith(`./`)&&(e=e.substring(2)),(t.Vc||=new Map).set(e,n)},t.unmountExternalData=()=>{delete t.Vc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let a=()=>{let e=e=>(...t)=>{let n=G;return t=e(...t),G==n?t:new Promise((e,t)=>{en={resolve:e,reject:t}})};(()=>{for(let n of[`_OrtAppendExecutionProvider`,`_OrtCreateSession`,`_OrtRun`,`_OrtRunWithBinding`,`_OrtBindInput`])t[n]=e(t[n])})(),typeof jsepRunAsync<`u`&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a?.()};var o,s,c=(e,t)=>{throw t},l=import.meta.url,u=``;if(n||r){try{u=new URL(`.`,l).href}catch{}r&&(s=e=>{var t=new XMLHttpRequest;return t.open(`GET`,e,!1),t.responseType=`arraybuffer`,t.send(null),new Uint8Array(t.response)}),o=async e=>{if(te(e))return new Promise((t,n)=>{var r=new XMLHttpRequest;r.open(`GET`,e,!0),r.responseType=`arraybuffer`,r.onload=()=>{r.status==200||r.status==0&&r.response?t(r.response):n(r.status)},r.onerror=n,r.send(null)});var t=await fetch(e,{credentials:`same-origin`});if(t.ok)return t.arrayBuffer();throw Error(t.status+` : `+t.url)}}var d,f,p,m,h,g,_=console.log.bind(console),v=console.error.bind(console),y=_,b=v,ee=!1,te=e=>e.startsWith(`file://`);function x(){Ee.buffer!=S.buffer&&ce()}if(i){let e=function(n){try{var r=n.data,i=r.Pc;if(i===`load`){let n=[];self.onmessage=e=>n.push(e),g=()=>{postMessage({Pc:`loaded`});for(let t of n)e(t);self.onmessage=e};for(let e of r.ee)t[e]&&!t[e].proxy||(t[e]=(...t)=>{postMessage({Pc:`callHandler`,de:e,args:t})},e==`print`&&(y=t[e]),e==`printErr`&&(b=t[e]));Ee=r.ke,ce(),f=r.le,k(),Co()}else if(i===`run`){(function(e){var t=(x(),D)[e+52>>>2>>>0];e=(x(),D)[e+56>>>2>>>0],Ui(t,t-e),Q(t)})(r.Oc),Pi(r.Oc,0,0,1,0,0),Ce(),Lt(r.Oc),ne||=(di(),!0);try{De(r.ie,r.Xc)}catch(e){if(e!=`unwind`)throw e}}else r.target!==`setimmediate`&&(i===`checkMailbox`?ne&&Rt():i&&(b(`worker: received unknown command ${i}`),b(r)))}catch(e){throw Fi(),e}};var ne=!1;self.onunhandledrejection=e=>{throw e.reason||e},self.onmessage=e}var S,C,w,T,E,D,re,ie,O,ae,oe,se=!1;function ce(){var e=Ee.buffer;t.HEAP8=S=new Int8Array(e),w=new Int16Array(e),t.HEAPU8=C=new Uint8Array(e),T=new Uint16Array(e),t.HEAP32=E=new Int32Array(e),t.HEAPU32=D=new Uint32Array(e),re=new Float32Array(e),ie=new Float64Array(e),O=new BigInt64Array(e),ae=new BigUint64Array(e)}function le(){se=!0,i?g():Ia.$b()}function ue(e){throw b(e=`Aborted(`+e+`)`),ee=!0,e=new WebAssembly.RuntimeError(e+`. Build with -sASSERTIONS for more info.`),h?.(e),e}function de(){return{a:{f:Ae,J:Me,k:Le,p:Re,l:ze,sa:Be,b:I,ca:Ve,Ja:He,q:Ue,da:Je,Za:Ye,Fa:Xe,Ha:Ze,_a:Qe,Xa:$e,Qa:et,Wa:tt,oa:nt,Ga:rt,Yb:it,Ya:at,Zb:ot,db:st,Da:ht,Tb:gt,Rb:xt,Ca:Ct,M:wt,I:Tt,Sb:Ot,ja:V,Ub:It,Ta:H,Wb:zt,Ka:Vt,Pb:Ht,ka:Ut,Sa:Lt,ab:Wt,U:rn,n:dn,c:R,rb:fn,w:K,L:pn,z:mn,j:hn,o:gn,sb:_n,G:vn,T:yn,h:bn,u:xn,m:Sn,i:Cn,Na:wn,Oa:On,Pa:kn,La:An,Ma:jn,Qb:Pn,eb:Fn,cb:Rn,Y:Vn,qb:Hn,la:Un,bb:In,fb:Wn,$a:Gn,Xb:q,N:Nn,gb:Kn,X:qn,Vb:Jn,nb:mr,C:hr,ra:gr,qa:_r,pb:vr,W:yr,v:br,mb:xr,lb:Sr,kb:Cr,ob:wr,jb:Tr,ib:Er,hb:Dr,Ua:Ar,Va:jr,Ia:ye,V:Mr,na:Nr,Ra:Pr,ma:Ir,Cb:xo,xa:ho,Db:bo,ya:mo,F:no,e:Ha,s:Ba,x:za,B:Qa,Fb:uo,ba:lo,D:Ga,za:fo,$:go,ga:co,Gb:so,Hb:oo,Ba:ro,Aa:ao,Ib:io,wa:yo,aa:po,d:Va,A:Wa,r:Ua,Bb:So,t:qa,y:eo,H:Ka,E:Ja,K:to,R:_o,ia:Za,_:vo,Kb:Xa,Lb:Ya,Jb:$a,g:Lr,a:Ee,Ob:_e,Eb:Rr,ha:zr,O:Br,pa:Vr,Mb:Hr,ta:Ur,Q:Wr,yb:Gr,zb:Kr,ua:qr,ea:Jr,P:Yr,Ea:Xr,va:Zr,Z:Qr,wb:$r,_b:ei,S:ti,Ab:ni,tb:ri,ub:ai,vb:oi,fa:si,xb:ci,Nb:li}}}async function k(){function e(e,n){var r=Ia=e.exports;e={};for(let[t,n]of Object.entries(r))typeof n==`function`?(r=Kt(n),e[t]=r):e[t]=n;return Ia=e,Ia=(function(){var e=Ia,t=e=>t=>e(t)>>>0,n=e=>()=>e()>>>0;return(e=Object.assign({},e)).ac=t(e.ac),e.Dc=n(e.Dc),e.Fc=t(e.Fc),e.sd=(e=>(t,n)=>e(t,n)>>>0)(e.sd),e.xd=t(e.xd),e.yd=n(e.yd),e.Cd=t(e.Cd),e})(),N.push(Ia.jd),ui=(e=Ia).ac,di=e.bc,t._OrtInit=e.cc,t._OrtGetLastError=e.dc,t._OrtCreateSessionOptions=e.ec,t._OrtAppendExecutionProvider=e.fc,t._OrtAddFreeDimensionOverride=e.gc,t._OrtAddSessionConfigEntry=e.hc,t._OrtReleaseSessionOptions=e.ic,t._OrtCreateSession=e.jc,t._OrtReleaseSession=e.kc,t._OrtGetInputOutputCount=e.lc,t._OrtGetInputOutputMetadata=e.mc,t._OrtFree=e.nc,t._OrtCreateTensor=e.oc,t._OrtGetTensorData=e.pc,t._OrtReleaseTensor=e.qc,t._OrtCreateRunOptions=e.rc,t._OrtAddRunConfigEntry=e.sc,t._OrtReleaseRunOptions=e.tc,t._OrtCreateBinding=e.uc,t._OrtBindInput=e.vc,t._OrtBindOutput=e.wc,t._OrtClearBoundOutputs=e.xc,t._OrtReleaseBinding=e.yc,t._OrtRunWithBinding=e.zc,t._OrtRun=e.Ac,t._OrtEndProfiling=e.Bc,fi=t._OrtGetWebGpuDevice=e.Cc,pi=e.Dc,mi=t._free=e.Ec,hi=t._malloc=e.Fc,gi=t._wgpuBufferRelease=e.Gc,_i=t._wgpuCreateInstance=e.Hc,vi=e.Ic,yi=e.Jc,bi=e.Kc,xi=e.Lc,Si=e.Mc,Ci=e.Qc,wi=e._c,Ti=e.$c,Ei=e.ad,Di=e.cd,Oi=e.dd,ki=e.ed,Ai=e.fd,ji=e.gd,Mi=e.hd,Ni=e.id,Pi=e.ld,Fi=e.md,Ii=e.nd,Li=e.od,Ri=e.pd,zi=e.qd,Bi=e.rd,Vi=e.sd,Z=e.td,Hi=e.ud,Ui=e.vd,Q=e.wd,Wi=e.xd,$=e.yd,Gi=e.zd,Ki=e.Ad,qi=e.Bd,Ji=e.Cd,Yi=e.Dd,Xi=e.Ed,Zi=e.Fd,Qi=e.Gd,$i=e.Hd,ea=e.Id,ta=e.Jd,na=e.Kd,ra=e.Ld,ia=e.Md,aa=e.Nd,oa=e.Od,sa=e.Pd,ca=e.Qd,la=e.Rd,ua=e.Sd,da=e.Ud,fa=e.Vd,pa=e.Wd,ma=e.Xd,ha=e.Zd,ga=e._d,_a=e.$d,va=e.ae,ya=e.be,ba=e.ce,xa=e.qe,Sa=e.re,Ca=e.se,wa=e.te,Ta=e.ue,Ea=e.ve,Da=e.we,Oa=e.xe,ka=e.ye,Aa=e.ze,ja=e.Ae,Ma=e.$e,Na=e.af,Pa=e.bf,Fa=e.cf,f=n,Ia}var n,r=de();return t.instantiateWasm?new Promise(n=>{t.instantiateWasm(r,(t,r)=>{n(e(t,r))})}):i?e(new WebAssembly.Instance(f,de()),f):(oe??=t.locateFile?t.locateFile?t.locateFile(`ort-wasm-simd-threaded.asyncify.wasm`,u):u+`ort-wasm-simd-threaded.asyncify.wasm`:new URL(`/assets/ort-wasm-simd-threaded.asyncify-CvvOzbbq.wasm`,``+import.meta.url).href,n=await(async function(e){var t=oe;if(!d&&!te(t))try{var n=fetch(t,{credentials:`same-origin`});return await WebAssembly.instantiateStreaming(n,e)}catch(e){b(`wasm streaming compile failed: ${e}`),b(`falling back to ArrayBuffer instantiation`)}return(async function(e,t){try{var n=await(async function(e){if(!d)try{var t=await o(e);return new Uint8Array(t)}catch{}if(e==oe&&d)e=new Uint8Array(d);else{if(!s)throw`both async and sync fetching of the wasm failed`;e=s(e)}return e})(e);return await WebAssembly.instantiate(n,t)}catch(e){b(`failed to asynchronously prepare wasm: ${e}`),ue(e)}})(t,e)})(r),e(n.instance,n.module))}class fe{name=`ExitStatus`;constructor(e){this.message=`Program terminated with exit(${e})`,this.status=e}}var pe=e=>{e.terminate(),e.onmessage=()=>{}},me=[],he=0,A=null,ge=e=>{be.length==0&&(Te(),we(be[0]));var t=be.pop();if(!t)return 6;xe.push(t),Se[e.Oc]=t,t.Oc=e.Oc;var n={Pc:`run`,ie:e.he,Xc:e.Xc,Oc:e.Oc};return t.postMessage(n,e.Zc),0},j=0,M=(e,t,...n)=>{var r,i=16*n.length,a=$(),o=Wi(i),s=o>>>3;for(r of n)typeof r==`bigint`?((x(),O)[s++>>>0]=1n,(x(),O)[s++>>>0]=r):((x(),O)[s++>>>0]=0n,(x(),ie)[s++>>>0]=r);return e=Ii(e,0,i,o,t),Q(a),e};function _e(e){if(i)return M(0,1,e);if(p=e,!(0{if(p=e,i)throw ve(e),`unwind`;_e(e)},be=[],xe=[],N=[],Se={},P=e=>{var t=e.Oc;delete Se[t],be.push(e),xe.splice(xe.indexOf(e),1),e.Oc=0,Li(t)};function Ce(){N.forEach(e=>e())}var we=e=>new Promise(n=>{e.onmessage=r=>{var i=r.data;if(r=i.Pc,i.Wc&&i.Wc!=pi()){var a=Se[i.Wc];a?a.postMessage(i,i.Zc):b(`Internal error! Worker sent a message "${r}" to target pthread ${i.Wc}, but that thread no longer exists!`)}else r===`checkMailbox`?Rt():r===`spawnThread`?ge(i):r===`cleanupThread`?U(()=>{P(Se[i.je])}):r===`loaded`?(e.loaded=!0,n(e)):i.target===`setimmediate`?e.postMessage(i):r===`uncaughtException`?e.onerror(i.error):r===`callHandler`?t[i.de](...i.args):r&&b(`worker sent an unknown command ${r}`)},e.onerror=e=>{throw b(`worker sent an error! ${e.filename}:${e.lineno}: ${e.message}`),e};var r,i=[];for(r of[])t.propertyIsEnumerable(r)&&i.push(r);e.postMessage({Pc:`load`,ee:i,ke:Ee,le:f})});function Te(){var e=new Worker((()=>{let e=URL;return import.meta.url>`file:`&&import.meta.url<`file;`?new e(`ort.webgpu.bundle.min.mjs`,import.meta.url):new URL(import.meta.url)})(),{type:`module`,workerData:`em-pthread`,name:`em-pthread`});be.push(e)}var Ee,De=(e,t)=>{j=0,e=Xi(e,t),0-9007199254740992>e||9007199254740992>>=0);return(x(),S)[t.Rc+12>>>0]==0&&(Ne(t,!0),ke--),Pe(t,!1),Oe.push(t),Ji(e)}var je=0,Me=()=>{Z(0,0);var e=Oe.pop();Gi(e.Yc),je=0};function Ne(e,t){t=+!!t,(x(),S)[e.Rc+12>>>0]=t}function Pe(e,t){t=+!!t,(x(),S)[e.Rc+13>>>0]=t}class Fe{constructor(e){this.Yc=e,this.Rc=e-24}}var Ie=e=>{var t=je;if(!t)return Hi(0),0;var n=new Fe(t);(x(),D)[n.Rc+16>>>2>>>0]=t;var r=(x(),D)[n.Rc+4>>>2>>>0];if(!r)return Hi(0),t;for(var i of e){if(i===0||i===r)break;if(qi(i,r,n.Rc+16))return Hi(i),t}return Hi(r),t};function Le(){return Ie([])}function Re(e){return Ie([e>>>0])}function ze(e,t,n,r){return Ie([e>>>0,t>>>0,n>>>0,r>>>0])}var Be=()=>{var e=Oe.pop();e||ue(`no exception to throw`);var t=e.Yc;throw(x(),S)[e.Rc+13>>>0]==0&&(Oe.push(e),Pe(e,!0),Ne(e,!1),ke++),Ki(t),je=t};function I(e,t,n){var r=new Fe(e>>>=0);throw t>>>=0,n>>>=0,(x(),D)[r.Rc+16>>>2>>>0]=0,(x(),D)[r.Rc+4>>>2>>>0]=t,(x(),D)[r.Rc+8>>>2>>>0]=n,Ki(e),ke++,je=e}var Ve=()=>ke;function L(e,t,n,r){return i?M(2,1,e,t,n,r):He(e,t,n,r)}function He(e,t,n,r){if(e>>>=0,t>>>=0,n>>>=0,r>>>=0,!globalThis.SharedArrayBuffer)return 6;var a=[];return i&&a.length===0?L(e,t,n,r):(e={he:n,Oc:e,Xc:r,Zc:a},i?(e.Pc=`spawnThread`,postMessage(e,a),0):ge(e))}function Ue(e){throw je||=e>>>0,je}var We=globalThis.TextDecoder&&new TextDecoder,Ge=(e,t,n,r)=>{if(n=t+n,r)return n;for(;e[t]&&!(t>=n);)++t;return t},Ke=(e,t=0,n,r)=>{if(16<(n=Ge(e,t>>>=0,n,r))-t&&e.buffer&&We)return We.decode(e.buffer instanceof ArrayBuffer?e.subarray(t,n):e.slice(t,n));for(r=``;t(i=(240&i)==224?(15&i)<<12|a<<6|o:(7&i)<<18|a<<12|o<<6|63&e[t++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r},qe=(e,t,n)=>(e>>>=0)?Ke((x(),C),e,t,n):``;function Je(e,t,n){return i?M(3,1,e,t,n):0}function Ye(e,t){if(i)return M(4,1,e,t)}function Xe(e,t){if(i)return M(5,1,e,t)}function Ze(e,t,n){if(i)return M(6,1,e,t,n)}function Qe(e,t,n){return i?M(7,1,e,t,n):0}function $e(e,t){if(i)return M(8,1,e,t)}function et(e,t,n){if(i)return M(9,1,e,t,n)}function tt(e,t,n,r){if(i)return M(10,1,e,t,n,r)}function nt(e,t,n,r){if(i)return M(11,1,e,t,n,r)}function rt(e,t,n,r){if(i)return M(12,1,e,t,n,r)}function it(e){if(i)return M(13,1,e)}function at(e,t){if(i)return M(14,1,e,t)}function ot(e,t,n){if(i)return M(15,1,e,t,n)}var st=()=>ue(``),ct=e=>{e>>>=0;for(var t=``;;){var n=(x(),C)[e++>>>0];if(!n)return t;t+=String.fromCharCode(n)}},lt={},ut={},dt={},ft=class extends Error{constructor(e){super(e),this.name=`BindingError`}};function pt(e,t,n={}){return(function(e,t,n={}){var r=t.name;if(!e)throw new ft(`type "${r}" must have a positive integer typeid pointer`);if(ut.hasOwnProperty(e)){if(n.fe)return;throw new ft(`Cannot register type '${r}' twice`)}ut[e]=t,delete dt[e],lt.hasOwnProperty(e)&&(t=lt[e],delete lt[e],t.forEach(e=>e()))})(e,t,n)}var mt=(e,t,n)=>{switch(t){case 1:return n?e=>(x(),S)[e>>>0]:e=>(x(),C)[e>>>0];case 2:return n?e=>(x(),w)[e>>>1>>>0]:e=>(x(),T)[e>>>1>>>0];case 4:return n?e=>(x(),E)[e>>>2>>>0]:e=>(x(),D)[e>>>2>>>0];case 8:return n?e=>(x(),O)[e>>>3>>>0]:e=>(x(),ae)[e>>>3>>>0];default:throw TypeError(`invalid integer width (${t}): ${e}`)}};function ht(e,t,n,r,i){e>>>=0,n>>>=0,t=ct(t>>>0);let a=e=>e;if(r=r===0n){let e=8*n;a=t=>BigInt.asUintN(e,t),i=a(i)}pt(e,{name:t,Nc:a,Tc:(e,t)=>(typeof t==`number`&&(t=BigInt(t)),t),Sc:mt(t,n,!r),Uc:null})}function gt(e,t,n,r){pt(e>>>=0,{name:t=ct(t>>>0),Nc:function(e){return!!e},Tc:function(e,t){return t?n:r},Sc:function(e){return this.Nc((x(),C)[e>>>0])},Uc:null})}var _t=[],vt=[0,1,,1,null,1,!0,1,!1,1];function R(e){9<(e>>>=0)&&--vt[e+1]===0&&(vt[e]=void 0,_t.push(e))}var z=e=>{if(!e)throw new ft(`Cannot use deleted val. handle = ${e}`);return vt[e]},B=e=>{switch(e){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let t=_t.pop()||vt.length;return vt[t]=e,vt[t+1]=1,t}};function yt(e){return this.Nc((x(),D)[e>>>2>>>0])}var bt={name:`emscripten::val`,Nc:e=>{var t=z(e);return R(e),t},Tc:(e,t)=>B(t),Sc:yt,Uc:null};function xt(e){return pt(e>>>0,bt)}var St=(e,t)=>{switch(t){case 4:return function(e){return this.Nc((x(),re)[e>>>2>>>0])};case 8:return function(e){return this.Nc((x(),ie)[e>>>3>>>0])};default:throw TypeError(`invalid float width (${t}): ${e}`)}};function Ct(e,t,n){n>>>=0,pt(e>>>=0,{name:t=ct(t>>>0),Nc:e=>e,Tc:(e,t)=>t,Sc:St(t,n),Uc:null})}function wt(e,t,n,r,i){e>>>=0,n>>>=0,t=ct(t>>>0);let a=e=>e;if(r===0){var o=32-8*n;a=e=>e<>>o,i=a(i)}pt(e,{name:t,Nc:a,Tc:(e,t)=>t,Sc:mt(t,n,r!==0),Uc:null})}function Tt(e,t,n){function r(e){var t=(x(),D)[e>>>2>>>0];return e=(x(),D)[e+4>>>2>>>0],new i((x(),S).buffer,e,t)}var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][t];pt(e>>>=0,{name:n=ct(n>>>0),Nc:r,Sc:r},{fe:!0})}var Et=(e,t,n)=>{var r=(x(),C);if(t>>>=0,0=o){if(t>=n)break;r[t++>>>0]=o}else if(2047>=o){if(t+1>=n)break;r[t++>>>0]=192|o>>6,r[t++>>>0]=128|63&o}else if(65535>=o){if(t+2>=n)break;r[t++>>>0]=224|o>>12,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o}else{if(t+3>=n)break;r[t++>>>0]=240|o>>18,r[t++>>>0]=128|o>>12&63,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o,a++}}r[t>>>0]=0,e=t-i}else e=0;return e},Dt=e=>{for(var t=0,n=0;n=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t};function Ot(e,t){pt(e>>>=0,{name:t=ct(t>>>0),Nc(e){var t=(x(),D)[e>>>2>>>0];return t=qe(e+4,t,!0),mi(e),t},Tc(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var n=typeof t==`string`;if(!(n||ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT==1))throw new ft(`Cannot pass non-string to std::string`);var r=n?Dt(t):t.length,i=hi(4+r+1),a=i+4;return(x(),D)[i>>>2>>>0]=r,n?Et(t,a,r+1):(x(),C).set(t,a>>>0),e!==null&&e.push(mi,i),i},Sc:yt,Uc(e){mi(e)}})}var kt=globalThis.TextDecoder?new TextDecoder(`utf-16le`):void 0,At=(e,t,n)=>{if(e>>>=1,16<(t=Ge((x(),T),e,t/2,n))-e&&kt)return kt.decode((x(),T).slice(e,t));for(n=``;e>>0];n+=String.fromCharCode(r)}return n},jt=(e,t,n)=>{if(n??=2147483647,2>n)return 0;var r=t;n=(n-=2)<2*e.length?n/2:e.length;for(var i=0;i>>1>>>0]=a,t+=2}return(x(),w)[t>>>1>>>0]=0,t-r},Mt=e=>2*e.length,Nt=(e,t,n)=>{var r=``;e>>>=2;for(var i=0;!(i>=t/4);i++){var a=(x(),D)[e+i>>>0];if(!a&&!n)break;r+=String.fromCodePoint(a)}return r},Pt=(e,t,n)=>{if(t>>>=0,n??=2147483647,4>n)return 0;var r=t;n=r+n-4;for(var i=0;i>>2>>>0]=a,(t+=4)+4>n)break}return(x(),E)[t>>>2>>>0]=0,t-r},Ft=e=>{for(var t=0,n=0;n>>=0,t>>>=0,n=ct(n>>>=0),t===2)var r=At,i=jt,a=Mt;else r=Nt,i=Pt,a=Ft;pt(e,{name:n,Nc:e=>{var n=(x(),D)[e>>>2>>>0];return n=r(e+4,n*t,!0),mi(e),n},Tc:(e,r)=>{if(typeof r!=`string`)throw new ft(`Cannot pass non-string to C++ string type ${n}`);var o=a(r),s=hi(4+o+t);return(x(),D)[s>>>2>>>0]=o/t,i(r,s+4,o+t),e!==null&&e.push(mi,s),s},Sc:yt,Uc(e){mi(e)}})}function It(e,t){pt(e>>>=0,{ge:!0,name:t=ct(t>>>0),Nc:()=>{},Tc:()=>{}})}function H(e){Pi(e>>>0,!r,1,!n,131072,!1),Ce()}var U=e=>{if(!ee)try{if(e(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Lt(e){e>>>=0,W||(Atomics.waitAsync((x(),E),e>>>2,e).value.then(Rt),e+=128,Atomics.store((x(),E),e>>>2,1))}var Rt=()=>U(()=>{var e=pi();e&&(Lt(e),Bi())});function zt(e,t){(e>>>=0)==t>>>0?setTimeout(Rt):i?postMessage({Wc:e,Pc:`checkMailbox`}):(e=Se[e])&&e.postMessage({Pc:`checkMailbox`})}var Bt=[];function Vt(e,t,n,r,i){for(t>>>=0,i>>>=0,Bt.length=0,n=i>>>3,r=i+r>>>3;n>>0]?(x(),O)[n++>>>0]:(x(),ie)[n++>>>0];Bt.push(a)}return(t?Ra[t]:La[e])(...Bt)}var Ht=()=>{j=0};function Ut(e){e>>>=0,i?postMessage({Pc:`cleanupThread`,je:e}):P(Se[e])}function Wt(e){}var Gt=e=>{try{e()}catch(e){ue(e)}};function Kt(e){var t=(...t)=>{Yt.push(e);try{return e(...t)}finally{ee||(Yt.pop(),G&&qt===1&&Yt.length===0&&(qt=0,j+=1,Gt(Na),typeof Fibers<`u`&&Fibers.De()))}};return Qt.set(e,t),t}var qt=0,G=null,Jt=0,Yt=[],Xt=new Map,Zt=new Map,Qt=new Map,$t=0,en=null,tn=[],nn=e=>(function(e){if(!ee){if(qt===0){var t=!1,n=!1;e((e=0)=>{if(!ee&&(Jt=e,t=!0,n)){qt=2,Gt(()=>Pa(G)),typeof MainLoop<`u`&&MainLoop.Yd&&MainLoop.resume(),e=!1;try{var r=(function(){var e=(x(),E)[G+8>>>2>>>0];return e=Zt.get(e),e=Qt.get(e),--j,e()})()}catch(t){r=t,e=!0}var i=!1;if(!G){var a=en;a&&(en=null,(e?a.reject:a.resolve)(r),i=!0)}if(e&&!i)throw r}}),n=!0,t||(qt=1,G=(function(){var e=hi(65548),t=e+12;if((x(),D)[e>>>2>>>0]=t,(x(),D)[e+4>>>2>>>0]=t+65536,t=Yt[0],!Xt.has(t)){var n=$t++;Xt.set(t,n),Zt.set(n,t)}return t=Xt.get(t),(x(),E)[e+8>>>2>>>0]=t,e})(),typeof MainLoop<`u`&&MainLoop.Yd&&MainLoop.pause(),Gt(()=>Ma(G)))}else qt===2?(qt=0,Gt(Fa),mi(G),G=null,tn.forEach(U)):ue(`invalid state: ${qt}`);return Jt}})(t=>{e().then(t)});function rn(e){return e>>>=0,nn(async()=>B(await z(e)))}var an=[],on=e=>{var t=an.length;return an.push(e),t},sn=(e,t)=>{for(var n=Array(e),r=0;r>>2>>>0],o=ut[a];if(o===void 0)throw e=`parameter ${r}`,a=ui(a),t=ct(a),mi(a),new ft(`${e} has unknown type ${t}`);n[i]=o}return n},cn=(e,t,n)=>{var r=[];return e=e(r,n),r.length&&((x(),D)[t>>>2>>>0]=B(r)),e},ln={},un=e=>{var t=ln[e];return t===void 0?ct(e):t};function dn(e,t,n){var[r,...i]=sn(e,t>>>0);t=r.Tc.bind(r);var a=i.map(e=>e.Sc.bind(e));e--;var o={toValue:z};switch(e=a.map((e,t)=>{var n=`argFromPtr${t}`;return o[n]=e,`${n}(args${t?`+`+8*t:``})`}),n){case 0:var s=`toValue(handle)`;break;case 2:s=`new (toValue(handle))`;break;case 3:s=``;break;case 1:o.getStringOrSymbol=un,s=`toValue(handle)[getStringOrSymbol(methodName)]`}return s+=`(${e})`,r.ge||(o.toReturnWire=t,o.emval_returnValue=cn,s=`return emval_returnValue(toReturnWire, destructorsRef, ${s})`),s=`return function (handle, methodName, destructorsRef, args) { + ${s} + }`,n=Function(Object.keys(o),s)(...Object.values(o)),s=`methodCaller<(${i.map(e=>e.name)}) => ${r.name}>`,on(Object.defineProperty(n,"name",{value:s}))}function fn(e,t){return t>>>=0,(e=z(e>>>0))==z(t)}function K(e){return(e>>>=0)?(e=un(e),B(globalThis[e])):B(globalThis)}function pn(e){return e=un(e>>>0),B(t[e])}function mn(e,t){return t>>>=0,e=z(e>>>0),t=z(t),B(e[t])}function hn(e){9<(e>>>=0)&&(vt[e+1]+=1)}function gn(e,t,n,r,i){return an[e>>>0](t>>>0,n>>>0,r>>>0,i>>>0)}function _n(e,t,n,r,i){return gn(e>>>0,t>>>0,n>>>0,r>>>0,i>>>0)}function vn(){return B([])}function yn(e){e=z(e>>>0);for(var t=Array(e.length),n=0;n>>0))}function xn(){return B({})}function Sn(e){for(var t=z(e>>>=0);t.length;){var n=t.pop();t.pop()(n)}R(e)}function Cn(e,t,n){t>>>=0,n>>>=0,e=z(e>>>0),t=z(t),n=z(n),e[t]=n}function wn(e,t){e=F(e),t>>>=0,e=new Date(1e3*e),(x(),E)[t>>>2>>>0]=e.getUTCSeconds(),(x(),E)[t+4>>>2>>>0]=e.getUTCMinutes(),(x(),E)[t+8>>>2>>>0]=e.getUTCHours(),(x(),E)[t+12>>>2>>>0]=e.getUTCDate(),(x(),E)[t+16>>>2>>>0]=e.getUTCMonth(),(x(),E)[t+20>>>2>>>0]=e.getUTCFullYear()-1900,(x(),E)[t+24>>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(x(),E)[t+28>>>2>>>0]=e}var Tn=e=>e%4==0&&(e%100!=0||e%400==0),En=[0,31,60,91,121,152,182,213,244,274,305,335],Dn=[0,31,59,90,120,151,181,212,243,273,304,334];function On(e,t){e=F(e),t>>>=0,e=new Date(1e3*e),(x(),E)[t>>>2>>>0]=e.getSeconds(),(x(),E)[t+4>>>2>>>0]=e.getMinutes(),(x(),E)[t+8>>>2>>>0]=e.getHours(),(x(),E)[t+12>>>2>>>0]=e.getDate(),(x(),E)[t+16>>>2>>>0]=e.getMonth(),(x(),E)[t+20>>>2>>>0]=e.getFullYear()-1900,(x(),E)[t+24>>>2>>>0]=e.getDay();var n=(Tn(e.getFullYear())?En:Dn)[e.getMonth()]+e.getDate()-1|0;(x(),E)[t+28>>>2>>>0]=n,(x(),E)[t+36>>>2>>>0]=-60*e.getTimezoneOffset(),n=new Date(e.getFullYear(),6,1).getTimezoneOffset();var r=new Date(e.getFullYear(),0,1).getTimezoneOffset();e=0|(n!=r&&e.getTimezoneOffset()==Math.min(r,n)),(x(),E)[t+32>>>2>>>0]=e}function kn(e){e>>>=0;var t=new Date((x(),E)[e+20>>>2>>>0]+1900,(x(),E)[e+16>>>2>>>0],(x(),E)[e+12>>>2>>>0],(x(),E)[e+8>>>2>>>0],(x(),E)[e+4>>>2>>>0],(x(),E)[e>>>2>>>0],0),n=(x(),E)[e+32>>>2>>>0],r=t.getTimezoneOffset(),i=new Date(t.getFullYear(),6,1).getTimezoneOffset(),a=new Date(t.getFullYear(),0,1).getTimezoneOffset(),o=Math.min(a,i);return 0>n?(x(),E)[e+32>>>2>>>0]=+(i!=a&&o==r):0>>2>>>0]=t.getDay(),n=(Tn(t.getFullYear())?En:Dn)[t.getMonth()]+t.getDate()-1|0,(x(),E)[e+28>>>2>>>0]=n,(x(),E)[e>>>2>>>0]=t.getSeconds(),(x(),E)[e+4>>>2>>>0]=t.getMinutes(),(x(),E)[e+8>>>2>>>0]=t.getHours(),(x(),E)[e+12>>>2>>>0]=t.getDate(),(x(),E)[e+16>>>2>>>0]=t.getMonth(),(x(),E)[e+20>>>2>>>0]=t.getYear(),e=t.getTime(),BigInt(isNaN(e)?-1:e/1e3)}function An(e,t,n,r,a,o,s){return i?M(16,1,e,t,n,r,a,o,s):-52}function jn(e,t,n,r,a,o){if(i)return M(17,1,e,t,n,r,a,o)}var Mn={},Nn=()=>performance.timeOrigin+performance.now();function Pn(e,t){return i?M(18,1,e,t):(Mn[e]&&(clearTimeout(Mn[e].id),delete Mn[e]),t&&(Mn[e]={id:setTimeout(()=>{delete Mn[e],U(()=>zi(e,performance.timeOrigin+performance.now()))},t),Ce:t}),0)}function Fn(e,t,n,r){e>>>=0,t>>>=0,n>>>=0,r>>>=0;var i=new Date().getFullYear(),a=new Date(i,0,1).getTimezoneOffset();i=new Date(i,6,1).getTimezoneOffset();var o=Math.max(a,i);(x(),D)[e>>>2>>>0]=60*o,(x(),E)[t>>>2>>>0]=+(a!=i),e=(t=e=>{var t=Math.abs(e);return`UTC${0<=e?`-`:`+`}${String(Math.floor(t/60)).padStart(2,`0`)}${String(t%60).padStart(2,`0`)}`})(a),t=t(i),iDate.now(),Ln=1;function Rn(e,t,n){if(n>>>=0,!(0<=e&&3>=e))return 28;if(e===0)e=Date.now();else{if(!Ln)return 52;e=performance.timeOrigin+performance.now()}return e=Math.round(1e6*e),(x(),O)[n>>>3>>>0]=BigInt(e),0}var zn=[],Bn=(e,t)=>{zn.length=0;for(var n;n=(x(),C)[e++>>>0];){var r=n!=105;t+=(r&=n!=112)&&t%8?4:0,zn.push(n==112?(x(),D)[t>>>2>>>0]:n==106?(x(),O)[t>>>3>>>0]:n==105?(x(),E)[t>>>2>>>0]:(x(),ie)[t>>>3>>>0]),t+=r?8:4}return zn};function Vn(e,t,n){return e>>>=0,t=Bn(t>>>0,n>>>0),Ra[e](...t)}function Hn(e,t,n){return e>>>=0,t=Bn(t>>>0,n>>>0),Ra[e](...t)}var Un=()=>{};function Wn(e,t){return b(qe(e>>>0,t>>>0))}var Gn=()=>{throw j+=1,`unwind`};function q(){return 4294901760}var Kn=()=>1,qn=()=>navigator.hardwareConcurrency;function Jn(e){e>>>=0;var t=(x(),C).length;if(e<=t||4294901760=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);e:{r=(Math.min(4294901760,65536*Math.ceil(Math.max(e,r)/65536))-Ee.buffer.byteLength+65535)/65536|0;try{Ee.grow(r),ce();var i=1;break e}catch{}i=void 0}if(i)return!0}return!1}var Yn=e=>{var t=Dt(e)+1,n=Wi(t);return Et(e,n,t),n},Xn=(e,t)=>{(x(),D)[e>>>2>>>0]=t;var n=(x(),D)[e>>>2>>>0];(x(),D)[e+4>>>2>>>0]=(t-n)/4294967296},Zn=e=>(x(),D)[e>>>2>>>0]+4294967296*(x(),E)[e+4>>>2>>>0],J=[],Qn=(e,t)=>{J[e>>>0]=t},$n=[],er=[],tr=(e,t)=>{er[e]=new Promise(n=>t.finally(()=>n(e)))},Y=e=>{if(e)return J[e>>>0]},nr=(e,t)=>{for(e=(x(),D)[e>>>2>>>0];e;e=(x(),D)[e>>>2>>>0])t[(x(),E)[e+4>>>2>>>0]](e)},rr=(e,t,n)=>{(x(),D)[e>>>2>>>0]=t,(x(),D)[e+4>>>2>>>0]=n},ir=e=>{var t=(x(),D)[e>>>2>>>0];return e=(x(),D)[e+4>>>2>>>0],qe(t,e)},ar=e=>{var t=(x(),D)[e>>>2>>>0];return e=(x(),D)[e+4>>>2>>>0],t?qe(t,e):e===0?``:void 0},or=e=>{var t=ar(e+4),n=(n=(x(),D)[e+12>>>2>>>0])?Y(n):`auto`;if(e+=16){var r=Y((x(),D)[e+4>>>2>>>0]),i=(x(),D)[e+16>>>2>>>0],a=(x(),D)[e+20>>>2>>>0];if(i){for(var o={},s=0;s>>3>>>0]}i=o}else i=void 0;e={module:r,constants:i,entryPoint:ar(e+8)}}else e=void 0;return{label:t,layout:n,compute:e}},sr=(e,t)=>{function n(n,r){n=e[n],(x(),D)[t+r>>>2>>>0]=n}n(`maxTextureDimension1D`,4),n(`maxTextureDimension2D`,8),n(`maxTextureDimension3D`,12),n(`maxTextureArrayLayers`,16),n(`maxBindGroups`,20),n(`maxBindGroupsPlusVertexBuffers`,24),n(`maxBindingsPerBindGroup`,28),n(`maxDynamicUniformBuffersPerPipelineLayout`,32),n(`maxDynamicStorageBuffersPerPipelineLayout`,36),n(`maxSampledTexturesPerShaderStage`,40),n(`maxSamplersPerShaderStage`,44),n(`maxStorageBuffersPerShaderStage`,48),n(`maxStorageTexturesPerShaderStage`,52),n(`maxUniformBuffersPerShaderStage`,56),n(`minUniformBufferOffsetAlignment`,80),n(`minStorageBufferOffsetAlignment`,84),Xn(t+64,e.maxUniformBufferBindingSize),Xn(t+72,e.maxStorageBufferBindingSize),n(`maxVertexBuffers`,88),Xn(t+96,e.maxBufferSize),n(`maxVertexAttributes`,104),n(`maxVertexBufferArrayStride`,108),n(`maxInterStageShaderVariables`,112),n(`maxColorAttachments`,116),n(`maxColorAttachmentBytesPerSample`,120),n(`maxComputeWorkgroupStorageSize`,124),n(`maxComputeInvocationsPerWorkgroup`,128),n(`maxComputeWorkgroupSizeX`,132),n(`maxComputeWorkgroupSizeY`,136),n(`maxComputeWorkgroupSizeZ`,140),n(`maxComputeWorkgroupsPerDimension`,144),e.Be!==void 0&&n(`maxImmediateSize`,148)},cr=[,`validation`,`out-of-memory`,`internal`],lr=[,`compatibility`,`core`],ur={1:`core-features-and-limits`,2:`depth-clip-control`,3:`depth32float-stencil8`,4:`texture-compression-bc`,5:`texture-compression-bc-sliced-3d`,6:`texture-compression-etc2`,7:`texture-compression-astc`,8:`texture-compression-astc-sliced-3d`,9:`timestamp-query`,10:`indirect-first-instance`,11:`shader-f16`,12:`rg11b10ufloat-renderable`,13:`bgra8unorm-storage`,14:`float32-filterable`,15:`float32-blendable`,16:`clip-distances`,17:`dual-source-blending`,18:`subgroups`,19:`texture-formats-tier1`,20:`texture-formats-tier2`,21:`primitive-index`,22:`texture-component-swizzle`,327692:`chromium-experimental-unorm16-texture-formats`,327729:`chromium-experimental-multi-draw-indirect`},dr=[,`low-power`,`high-performance`],fr=[,`occlusion`,`timestamp`],pr={undefined:1,unknown:1,destroyed:2};function mr(e,t,n,r,i,a){t=F(t),n=F(n),r>>>=0,i>>>=0,a>>>=0;var o=Y(e>>>0);if(e={},a){var s=(x(),D)[a+12>>>2>>>0];if(s){var c=(x(),D)[a+16>>>2>>>0];e.requiredFeatures=Array.from((x(),D).subarray(c>>>2>>>0,c+4*s>>>2>>>0),e=>ur[e])}var l=(x(),D)[a+20>>>2>>>0];if(l){let t=function(e,t,n=!1){t=l+t,(t=(x(),D)[t>>>2>>>0])==4294967295||n&&t==0||(u[e]=t)},n=function(e,t){t=l+t;var n=(x(),D)[t>>>2>>>0],r=(x(),D)[t+4>>>2>>>0];n==4294967295&&r==4294967295||(u[e]=Zn(t))};var u={};t(`maxTextureDimension1D`,4),t(`maxTextureDimension2D`,8),t(`maxTextureDimension3D`,12),t(`maxTextureArrayLayers`,16),t(`maxBindGroups`,20),t(`maxBindGroupsPlusVertexBuffers`,24),t(`maxDynamicUniformBuffersPerPipelineLayout`,32),t(`maxDynamicStorageBuffersPerPipelineLayout`,36),t(`maxSampledTexturesPerShaderStage`,40),t(`maxSamplersPerShaderStage`,44),t(`maxStorageBuffersPerShaderStage`,48),t(`maxStorageTexturesPerShaderStage`,52),t(`maxUniformBuffersPerShaderStage`,56),t(`minUniformBufferOffsetAlignment`,80),t(`minStorageBufferOffsetAlignment`,84),n(`maxUniformBufferBindingSize`,64),n(`maxStorageBufferBindingSize`,72),t(`maxVertexBuffers`,88),n(`maxBufferSize`,96),t(`maxVertexAttributes`,104),t(`maxVertexBufferArrayStride`,108),t(`maxInterStageShaderVariables`,112),t(`maxColorAttachments`,116),t(`maxColorAttachmentBytesPerSample`,120),t(`maxComputeWorkgroupStorageSize`,124),t(`maxComputeInvocationsPerWorkgroup`,128),t(`maxComputeWorkgroupSizeX`,132),t(`maxComputeWorkgroupSizeY`,136),t(`maxComputeWorkgroupSizeZ`,140),t(`maxComputeWorkgroupsPerDimension`,144),t(`maxImmediateSize`,148,!0),e.requiredLimits=u}(s=(x(),D)[a+24>>>2>>>0])&&(s={label:ar(s+4)},e.defaultQueue=s),e.label=ar(a+4)}j+=1,tr(t,o.requestDevice(e).then(e=>{--j,U(()=>{J[i>>>0]=e.queue,J[r>>>0]=e,j+=1,tr(n,e.lost.then(t=>{U(()=>{e.onuncapturederror=()=>{};var r=$(),i=Yn(t.message);Oi(n,pr[t.reason],i),Q(r)}),--j})),e.onuncapturederror=e=>{var t=5;e.error instanceof GPUValidationError?t=2:e.error instanceof GPUOutOfMemoryError?t=3:e.error instanceof GPUInternalError&&(t=4);var n=$();e=Yn(e.error.message),Ni(r,t,e),Q(n)},`adapterInfo`in e||(e.adapterInfo=o.info),Mi(t,1,r,0)})},e=>{--j,U(()=>{var i=$(),a=Yn(e.message);Mi(t,3,r,a),n&&Oi(n,4,a),Q(i)})}))}function hr(e){var t=Y(e>>>=0),n=$n[e];if(n){for(var r=0;r>>=0;var r=Y(e>>>=0);n==4294967295&&(n=void 0);try{var i=r.getMappedRange(t>>>0,n)}catch{return 0}var a=Vi(16,i.byteLength);return(x(),C).set(new Uint8Array(i),a>>>0),$n[e].push(()=>mi(a)),a}function _r(e,t,n){n>>>=0;var r=Y(e>>>=0);n==4294967295&&(n=void 0);try{var i=r.getMappedRange(t>>>0,n)}catch{return 0}var a=Vi(16,i.byteLength);return(x(),C).fill(0,a,i.byteLength),$n[e].push(()=>{new Uint8Array(i).set((x(),C).subarray(a>>>0,a+i.byteLength>>>0)),mi(a)}),a}function vr(e,t,n,r,i){e>>>=0,t=F(t),n=F(n),i>>>=0;var a=Y(e);$n[e]=[],i==4294967295&&(i=void 0),j+=1,tr(t,a.mapAsync(n,r>>>0,i).then(()=>{--j,U(()=>{ki(t,1,0)})},n=>{--j,U(()=>{$();var r=Yn(n.message);ki(t,n.name===`AbortError`?4:n.name===`OperationError`?3:0,r),delete $n[e]})}))}function yr(e){var t=Y(e>>>=0),n=$n[e];if(n){for(var r=0;r>>0]}function xr(e,t,n){e>>>=0,t>>>=0,n>>>=0;var r=!!(x(),D)[t+32>>>2>>>0];t={label:ar(t+4),usage:(x(),D)[t+16>>>2>>>0],size:Zn(t+24),mappedAtCreation:r},e=Y(e);try{var i=e.createBuffer(t)}catch{return!1}return J[n>>>0]=i,r&&($n[n]=[]),!0}function Sr(e,t,n,r){e>>>=0,t=F(t),r>>>=0,n=or(n>>>0),e=Y(e),j+=1,tr(t,e.createComputePipelineAsync(n).then(e=>{--j,U(()=>{J[r>>>0]=e,Di(t,1,r,0)})},e=>{--j,U(()=>{var n=$(),i=Yn(e.message);Di(t,e.reason===`validation`?3:e.reason===`internal`?4:0,r,i),Q(n)})}))}function Cr(e,t,n){e>>>=0,t>>>=0,n>>>=0;var r=(x(),D)[t>>>2>>>0],i=(x(),E)[r+4>>>2>>>0];t={label:ar(t+4),code:``},i===2&&(t.code=ir(r+8)),e=Y(e).createShaderModule(t),J[n>>>0]=e}var wr=e=>{(e=Y(e)).onuncapturederror=null,e.destroy()};function Tr(e,t){t=F(t),e=Y(e>>>0),j+=1,tr(t,e.popErrorScope().then(e=>{--j,U(()=>{var n=5;e?e instanceof GPUValidationError?n=2:e instanceof GPUOutOfMemoryError?n=3:e instanceof GPUInternalError&&(n=4):n=1;var r=$(),i=e?Yn(e.message):0;Ai(t,1,n,i),Q(r)})},e=>{--j,U(()=>{var n=$(),r=Yn(e.message);Ai(t,1,5,r),Q(n)})}))}function Er(e,t,n,r){if(t=F(t),r>>>=0,n>>>=0){var i={featureLevel:lr[(x(),E)[n+4>>>2>>>0]],powerPreference:dr[(x(),E)[n+8>>>2>>>0]],forceFallbackAdapter:!!(x(),D)[n+12>>>2>>>0]};(e=(x(),D)[n>>>2>>>0])!==0&&(x(),i.Fe=!!(x(),D)[e+8>>>2>>>0])}`gpu`in navigator?(j+=1,tr(t,navigator.gpu.requestAdapter(i).then(e=>{--j,U(()=>{if(e)J[r>>>0]=e,ji(t,1,r,0);else{var n=$(),i=Yn(`WebGPU not available on this browser (requestAdapter returned null)`);ji(t,3,r,i),Q(n)}})},e=>{--j,U(()=>{var n=$(),i=Yn(e.message);ji(t,4,r,i),Q(n)})}))):(i=$(),e=Yn(`WebGPU not available on this browser (navigator.gpu is not available)`),ji(t,3,r,e),Q(i))}function Dr(e,t,n){return e>>>=0,t>>>=0,n>>>=0,nn(async()=>{var r=[];if(n){var i=(x(),E)[n>>>2>>>0];r.length=t+1,r[t]=new Promise(e=>setTimeout(e,i,0))}else r.length=t;for(var a=0;a{if(!Or){var e,t={USER:`web_user`,LOGNAME:`web_user`,PATH:`/`,PWD:`/`,HOME:`/home/web_user`,LANG:(globalThis.navigator?.language??`C`).replace(`-`,`_`)+`.UTF-8`,_:`./this.program`};for(e in X)X[e]===void 0?delete t[e]:t[e]=X[e];var n=[];for(e in t)n.push(`${e}=${t[e]}`);Or=n}return Or};function Ar(e,t){if(i)return M(19,1,e,t);e>>>=0,t>>>=0;var n,r=0,a=0;for(n of kr()){var o=t+r;(x(),D)[e+a>>>2>>>0]=o,r+=Et(n,o,1/0)+1,a+=4}return 0}function jr(e,t){if(i)return M(20,1,e,t);e>>>=0,t>>>=0;var n=kr();for(var r of((x(),D)[e>>>2>>>0]=n.length,e=0,n))e+=Dt(r)+1;return(x(),D)[t>>>2>>>0]=e,0}function Mr(e){return i?M(21,1,e):52}function Nr(e,t,n,r){return i?M(22,1,e,t,n,r):52}function Pr(e,t,n,r){return i?M(23,1,e,t,n,r):70}var Fr=[null,[],[]];function Ir(e,t,n,r){if(i)return M(24,1,e,t,n,r);t>>>=0,n>>>=0,r>>>=0;for(var a=0,o=0;o>>2>>>0],c=(x(),D)[t+4>>>2>>>0];t+=8;for(var l=0;l>>0],f=Fr[u];d===0||d===10?((u===1?y:b)(Ke(f)),f.length=0):f.push(d)}a+=c}return(x(),D)[r>>>2>>>0]=a,0}function Lr(e){return e>>>0}function Rr(e,t){return sr(Y(e>>>0).limits,t>>>0),1}function zr(e,t){return Y(e>>>0).features.has(ur[t])}function Br(e){return BigInt(Y(e>>>0).size)}function Vr(e){return BigInt(Y(e>>>0).usage)}function Hr(e,t){if(e>>>=0,t>>>=0){var n=ar(t+4);n={label:n,timestampWrites:t=(t=(x(),D)[t+12>>>2>>>0])===0?void 0:{querySet:Y((x(),D)[t+4>>>2>>>0]),beginningOfPassWriteIndex:(x(),D)[t+8>>>2>>>0],endOfPassWriteIndex:(x(),D)[t+12>>>2>>>0]}}}return t=Y(e),e=Si(0),n=t.beginComputePass(n),J[e>>>0]=n,e}function Ur(e,t,n,r){n=F(n),(r=F(r))==-1&&(r=void 0),(e=Y(e>>>0)).clearBuffer(Y(t>>>0),n,r)}function Wr(e,t,n,r,i,a){n=F(n),i=F(i),a=F(a),Y(e>>>0).copyBufferToBuffer(Y(t>>>0),n,Y(r>>>0),i,a)}function Gr(e){var t=Y(e>>>0);return e=bi(0),t=t.finish(),J[e>>>0]=t,e}function Kr(e,t,n,r,i,a){a=F(a),Y(e>>>0).resolveQuerySet(Y(t>>>0),n,r,Y(i>>>0),a)}function qr(e,t,n,r){Y(e>>>0).dispatchWorkgroups(t,n,r)}function Jr(e,t,n){n=F(n),Y(e>>>0).dispatchWorkgroupsIndirect(Y(t>>>0),n)}function Yr(e){Y(e>>>0).end()}function Xr(e,t,n,r,i){r>>>=0,i>>>=0,e=Y(e>>>0),n=Y(n>>>0),r==0?e.setBindGroup(t,n):e.setBindGroup(t,n,(x(),D),i>>>2,r)}function Zr(e,t){Y(e>>>0).setPipeline(Y(t>>>0))}function Qr(e,t,n){Y(e>>>0).Ee(Y(t>>>0),n)}function $r(e,t){var n=Y(e>>>0);return e=yi(0),t=n.getBindGroupLayout(t),J[e>>>0]=t,e}function ei(e,t){function n(e){var t=(x(),D)[e+8>>>2>>>0],n=(x(),D)[e+32>>>2>>>0],r=(x(),D)[e+36>>>2>>>0],i=0;return nr(e,{327681:e=>{i=(x(),D)[e+8>>>2>>>0]}}),t?((n=Zn(e+24))==-1&&(n=void 0),t={buffer:Y(t),offset:Zn(e+16),size:n}):t=Y(n||r||i),{binding:(x(),D)[e+4>>>2>>>0],resource:t}}e>>>=0,t={label:ar((t>>>=0)+4),layout:Y((x(),D)[t+12>>>2>>>0]),entries:(function(e,t){for(var r=[],i=0;i>>2>>>0],(x(),D)[t+20>>>2>>>0])},e=Y(e);var r=vi(0);return Qn(r,e.createBindGroup(t)),r}function ti(e,t){var n;return e>>>=0,(t>>>=0)&&(n={label:ar(t+4)}),t=Y(e),e=xi(0),n=t.createCommandEncoder(n),J[e>>>0]=n,e}function ni(e,t){e>>>=0,t>>>=0,t={type:fr[(x(),E)[t+12>>>2>>>0]],count:(x(),D)[t+16>>>2>>>0]};var n=Y(e);return e=Ci(0),t=n.createQuerySet(t),J[e>>>0]=t,e}function ri(e,t){e=Y(e>>>0).adapterInfo,t>>>=0,(x(),D)[t+52>>>2>>>0]=e.subgroupMinSize,(x(),D)[t+56>>>2>>>0]=e.subgroupMaxSize;var n=e.vendor+e.architecture+e.device+e.description,r=Dt(n)+1,i=hi(r);return i&&Et(n,i,r),n=i,r=Dt(e.vendor),rr(t+4,n,r),n+=r,r=Dt(e.architecture),rr(t+12,n,r),n+=r,r=Dt(e.device),rr(t+20,n,r),rr(t+28,n+r,Dt(e.description)),(x(),E)[t+36>>>2>>>0]=2,e=e.isFallbackAdapter?3:4,(x(),E)[t+40>>>2>>>0]=e,(x(),D)[t+44>>>2>>>0]=0,(x(),D)[t+48>>>2>>>0]=0,1}var ii={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function ai(e,t){t>>>=0;var n=Y(e>>>0);e=hi(4*n.features.size);var r=0,i=0;for(let t of n.features)0<=(n=ii[t])&&((x(),E)[e+r>>>2>>>0]=n,r+=4,i++);(x(),D)[t+4>>>2>>>0]=e,(x(),D)[t>>>2>>>0]=i}function oi(e,t){return sr(Y(e>>>0).limits,t>>>0),1}function si(e,t){Y(e>>>0).pushErrorScope(cr[t])}function ci(e,t,n){t>>>=0,n>>>=0,e=Y(e>>>0),t=Array.from((x(),E).subarray(n>>>2>>>0,n+4*t>>>2>>>0),e=>Y(e)),e.submit(t)}function li(e,t,n,r,i){n=F(n),r>>>=0,i>>>=0,e=Y(e>>>0),t=Y(t>>>0),r=(x(),C).subarray(r>>>0,r+i>>>0),e.writeBuffer(t,n,r,0,i)}i||(function(){for(var e=t.numThreads-1;e--;)Te();me.push(async()=>{var e=(async function(){if(!i)return Promise.all(be.map(we))})();he++,await e,--he==0&&A&&(e=A,A=null,e())})})(),i||(Ee=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),ce()),t.wasmBinary&&(d=t.wasmBinary),t.stackSave=()=>$(),t.stackRestore=e=>Q(e),t.stackAlloc=e=>Wi(e),t.setValue=function(e,t,n=`i8`){switch(n.endsWith(`*`)&&(n=`*`),n){case`i1`:case`i8`:(x(),S)[e>>>0]=t;break;case`i16`:(x(),w)[e>>>1>>>0]=t;break;case`i32`:(x(),E)[e>>>2>>>0]=t;break;case`i64`:(x(),O)[e>>>3>>>0]=BigInt(t);break;case`float`:(x(),re)[e>>>2>>>0]=t;break;case`double`:(x(),ie)[e>>>3>>>0]=t;break;case`*`:(x(),D)[e>>>2>>>0]=t;break;default:ue(`invalid type for setValue: ${n}`)}},t.getValue=function(e,t=`i8`){switch(t.endsWith(`*`)&&(t=`*`),t){case`i1`:case`i8`:return(x(),S)[e>>>0];case`i16`:return(x(),w)[e>>>1>>>0];case`i32`:return(x(),E)[e>>>2>>>0];case`i64`:return(x(),O)[e>>>3>>>0];case`float`:return(x(),re)[e>>>2>>>0];case`double`:return(x(),ie)[e>>>3>>>0];case`*`:return(x(),D)[e>>>2>>>0];default:ue(`invalid type for getValue: ${t}`)}},t.UTF8ToString=qe,t.stringToUTF8=Et,t.lengthBytesUTF8=Dt;var ui,di,fi,pi,mi,hi,gi,_i,vi,yi,bi,xi,Si,Ci,wi,Ti,Ei,Di,Oi,ki,Ai,ji,Mi,Ni,Pi,Fi,Ii,Li,Ri,zi,Bi,Vi,Z,Hi,Ui,Q,Wi,$,Gi,Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,ea,ta,na,ra,ia,aa,oa,sa,ca,la,ua,da,fa,pa,ma,ha,ga,_a,va,ya,ba,xa,Sa,Ca,wa,Ta,Ea,Da,Oa,ka,Aa,ja,Ma,Na,Pa,Fa,Ia,La=[_e,ve,L,Je,Ye,Xe,Ze,Qe,$e,et,tt,nt,rt,it,at,ot,An,jn,Pn,Ar,jr,Mr,Nr,Pr,Ir],Ra={1028716:(e,n,r,i,a)=>{if(t===void 0||!t.Vc)return 1;if((e=qe(Number(e>>>0))).startsWith(`./`)&&(e=e.substring(2)),!(e=t.Vc.get(e)))return 2;if(n=Number(n>>>0),r=Number(r>>>0),i=Number(i>>>0),n+r>e.byteLength)return 3;try{let o=e.subarray(n,n+r);switch(a){case 0:(x(),C).set(o,i>>>0);break;case 1:t.bd?t.bd(i,o):t.pe(i,o);break;default:return 4}return 0}catch{return 4}},1029540:(e,n,r)=>{t.Td(e,(x(),C).subarray(n>>>0,n+r>>>0))},1029604:()=>t.ne(),1029646:e=>{t.kd(e)},1029683:()=>typeof wasmOffsetConverter<`u`};function za(e,t,n,r){var i=$();try{return ia(e,t,n,r)}catch(e){if(Q(i),e!==e+0)throw e;Z(1,0)}}function Ba(e,t,n){var r=$();try{return ta(e,t,n)}catch(e){if(Q(r),e!==e+0)throw e;Z(1,0)}}function Va(e){var t=$();try{Zi(e)}catch(e){if(Q(t),e!==e+0)throw e;Z(1,0)}}function Ha(e,t){var n=$();try{return Xi(e,t)}catch(e){if(Q(n),e!==e+0)throw e;Z(1,0)}}function Ua(e,t,n){var r=$();try{Yi(e,t,n)}catch(e){if(Q(r),e!==e+0)throw e;Z(1,0)}}function Wa(e,t){var n=$();try{aa(e,t)}catch(e){if(Q(n),e!==e+0)throw e;Z(1,0)}}function Ga(e,t,n,r,i,a,o){var s=$();try{return ea(e,t,n,r,i,a,o)}catch(e){if(Q(s),e!==e+0)throw e;Z(1,0)}}function Ka(e,t,n,r,i,a){var o=$();try{Qi(e,t,n,r,i,a)}catch(e){if(Q(o),e!==e+0)throw e;Z(1,0)}}function qa(e,t,n,r){var i=$();try{ra(e,t,n,r)}catch(e){if(Q(i),e!==e+0)throw e;Z(1,0)}}function Ja(e,t,n,r,i,a,o){var s=$();try{sa(e,t,n,r,i,a,o)}catch(e){if(Q(s),e!==e+0)throw e;Z(1,0)}}function Ya(e,t,n,r,i,a,o){var s=$();try{ca(e,t,n,r,i,a,o)}catch(e){if(Q(s),e!==e+0)throw e;Z(1,0)}}function Xa(e,t,n,r,i,a,o,s){var c=$();try{_a(e,t,n,r,i,a,o,s)}catch(e){if(Q(c),e!==e+0)throw e;Z(1,0)}}function Za(e,t,n,r,i,a,o,s,c,l,u,d){var f=$();try{la(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(Q(f),e!==e+0)throw e;Z(1,0)}}function Qa(e,t,n,r,i){var a=$();try{return oa(e,t,n,r,i)}catch(e){if(Q(a),e!==e+0)throw e;Z(1,0)}}function $a(e,t,n,r,i,a){var o=$();try{va(e,t,n,r,i,a)}catch(e){if(Q(o),e!==e+0)throw e;Z(1,0)}}function eo(e,t,n,r,i){var a=$();try{$i(e,t,n,r,i)}catch(e){if(Q(a),e!==e+0)throw e;Z(1,0)}}function to(e,t,n,r,i,a,o,s){var c=$();try{na(e,t,n,r,i,a,o,s)}catch(e){if(Q(c),e!==e+0)throw e;Z(1,0)}}function no(e){var t=$();try{return ya(e)}catch(e){if(Q(t),e!==e+0)throw e;Z(1,0)}}function ro(e,t,n){var r=$();try{return ba(e,t,n)}catch(e){if(Q(r),e!==e+0)throw e;Z(1,0)}}function io(e,t){var n=$();try{return ja(e,t)}catch(e){if(Q(n),e!==e+0)throw e;return Z(1,0),0n}}function ao(e){var t=$();try{return ua(e)}catch(e){if(Q(t),e!==e+0)throw e;return Z(1,0),0n}}function oo(e,t,n,r){var i=$();try{return xa(e,t,n,r)}catch(e){if(Q(i),e!==e+0)throw e;Z(1,0)}}function so(e,t,n,r,i){var a=$();try{return Sa(e,t,n,r,i)}catch(e){if(Q(a),e!==e+0)throw e;Z(1,0)}}function co(e,t,n,r,i,a){var o=$();try{return Ca(e,t,n,r,i,a)}catch(e){if(Q(o),e!==e+0)throw e;Z(1,0)}}function lo(e,t,n,r,i,a){var o=$();try{return ha(e,t,n,r,i,a)}catch(e){if(Q(o),e!==e+0)throw e;Z(1,0)}}function uo(e,t,n,r,i,a){var o=$();try{return wa(e,t,n,r,i,a)}catch(e){if(Q(o),e!==e+0)throw e;Z(1,0)}}function fo(e,t,n,r,i,a,o,s){var c=$();try{return ga(e,t,n,r,i,a,o,s)}catch(e){if(Q(c),e!==e+0)throw e;Z(1,0)}}function po(e,t,n,r,i){var a=$();try{return Ta(e,t,n,r,i)}catch(e){if(Q(a),e!==e+0)throw e;return Z(1,0),0n}}function mo(e,t,n,r){var i=$();try{return Ea(e,t,n,r)}catch(e){if(Q(i),e!==e+0)throw e;Z(1,0)}}function ho(e,t,n,r){var i=$();try{return Da(e,t,n,r)}catch(e){if(Q(i),e!==e+0)throw e;Z(1,0)}}function go(e,t,n,r,i,a,o,s,c,l,u,d){var f=$();try{return Oa(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(Q(f),e!==e+0)throw e;Z(1,0)}}function _o(e,t,n,r,i,a,o,s,c,l,u){var d=$();try{ka(e,t,n,r,i,a,o,s,c,l,u)}catch(e){if(Q(d),e!==e+0)throw e;Z(1,0)}}function vo(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){var g=$();try{Aa(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}catch(e){if(Q(g),e!==e+0)throw e;Z(1,0)}}function yo(e,t,n){var r=$();try{return fa(e,t,n)}catch(e){if(Q(r),e!==e+0)throw e;return Z(1,0),0n}}function bo(e,t,n){var r=$();try{return da(e,t,n)}catch(e){if(Q(r),e!==e+0)throw e;Z(1,0)}}function xo(e,t,n){var r=$();try{return pa(e,t,n)}catch(e){if(Q(r),e!==e+0)throw e;Z(1,0)}}function So(e,t,n,r){var i=$();try{ma(e,t,n,r)}catch(e){if(Q(i),e!==e+0)throw e;Z(1,0)}}function Co(){if(0{let n=new WeakMap,r,i,a=1;t.webgpuRegisterDevice=e=>{if(i!==void 0)throw Error(`another WebGPU EP inference session is being created.`);if(e){var t=n.get(e);if(!t){let r=((e,t=0)=>{var n=Ei(t);return t=Ti(t,n),J[n>>>0]=e.queue,J[t>>>0]=e,t})(e,t=_i(0));t=[a++,t,r],n.set(e,t)}return r=e,i=t[0],t}r=void 0,i=0};let o=new Map;t.webgpuOnCreateSession=t=>{if(i!==void 0){var n=i;if(i=void 0,t){let i=fi(n);o.set(t,i),n===0&&e(r??Y(i))}r=void 0}},t.webgpuOnReleaseSession=e=>{o.delete(e)};let s=Symbol(`gpuBufferMetadata`);t.webgpuRegisterBuffer=(e,t,n)=>{if(n)return e[s]=[n,NaN],n;if(n=e[s])return n[1]++,n[0];if((t=o.get(t))===void 0)throw Error(`Invalid session handle passed to webgpuRegisterBuffer`);return t=((e,t=0)=>(e.mapState===`unmapped`||ue(),t=wi(t),J[t>>>0]=e,t))(e,t),e[s]=[t,1],t},t.webgpuUnregisterBuffer=e=>{let t=e[s];if(!t)throw Error(`Buffer is not registered`);t[1]--,t[1]===0&&(gi(t[0]),delete e[s])},t.webgpuGetBuffer=e=>Y(e),t.webgpuCreateDownloader=(e,t,n)=>{if((n=o.get(n))===void 0)throw Error(`Invalid session handle passed to webgpuRegisterBuffer`);let r=Y(n),i=16*Math.ceil(Number(t)/16);return async()=>{let n=r.createBuffer({size:i,usage:9});try{let a=r.createCommandEncoder();return a.copyBufferToBuffer(e,0,n,0,i),r.queue.submit([a.finish()]),await n.mapAsync(GPUMapMode.READ),n.getMappedRange().slice(0,t)}finally{n.destroy()}}},t.bd=(e,t)=>{var n=t.buffer;let a=t.byteOffset,o=t.byteLength;if(t=16*Math.ceil(Number(o)/16),e=Y(e),!r){var s=fi(i);r=Y(s)}let c=(s=r.createBuffer({mappedAtCreation:!0,size:t,usage:6})).getMappedRange();new Uint8Array(c).set(new Uint8Array(n,a,o)),s.unmap(),(n=r.createCommandEncoder()).copyBufferToBuffer(s,0,e,0,t),r.queue.submit([n.finish()]),s.destroy()}},t.webnnInit=e=>{let n=e[0];[t.ne,t.kd,t.webnnEnsureTensor,t.Td,t.webnnDownloadTensor,t.me,t.webnnEnableTraceEvent]=e.slice(1),t.webnnReleaseTensorId=t.kd,t.webnnUploadTensor=t.Td,t.webnnRegisterMLContext=t.me,t.webnnOnRunStart=e=>n.onRunStart(e),t.webnnOnRunEnd=n.onRunEnd.bind(n),t.webnnOnReleaseSession=e=>{n.onReleaseSession(e)},t.webnnCreateMLTensorDownloader=(e,t)=>n.createMLTensorDownloader(e,t),t.webnnRegisterMLTensor=(e,t,r,i)=>n.registerMLTensor(e,t,r,i),t.webnnCreateMLContext=e=>n.createMLContext(e),t.webnnRegisterMLConstant=(e,r,i,a,o,s)=>n.registerMLConstant(e,r,i,a,o,t.Vc,s),t.webnnRegisterGraphInput=n.registerGraphInput.bind(n),t.webnnIsGraphInput=n.isGraphInput.bind(n),t.webnnRegisterGraphOutput=n.registerGraphOutput.bind(n),t.webnnIsGraphOutput=n.isGraphOutput.bind(n),t.webnnCreateTemporaryTensor=n.createTemporaryTensor.bind(n),t.webnnIsGraphInputOutputTypeSupported=n.isGraphInputOutputTypeSupported.bind(n)},se?t:new Promise((e,t)=>{m=e,h=t})}var pt,mt,ht=k(()=>{pt=ft,mt=globalThis.self?.name?.startsWith(`em-pthread`),mt&&ft()}),gt,_t,vt,R,z,B,yt,bt,xt,St,Ct,wt,Tt,Et,Dt=k(()=>{at(),gt=typeof location>`u`?void 0:location.origin,_t=import.meta.url>`file:`&&import.meta.url<`file;`,vt=()=>_t?new URL(new URL(`ort.webgpu.bundle.min.mjs`,import.meta.url).href,gt).href:import.meta.url,R=vt(),z=()=>{if(R&&!R.startsWith(`blob:`))return R.substring(0,R.lastIndexOf(`/`)+1)},B=(e,t)=>{try{let n=t??R;return(n?new URL(e,n):new URL(e)).origin===gt}catch{return!1}},yt=(e,t)=>{let n=t??R;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},bt=(e,t)=>`${t??`./`}${e}`,xt=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},St=async e=>(await oe(async()=>{let{default:t}=await import(e);return{default:t}},[])).default,Ct=(ut(),me(ot)).default,wt=async()=>{if(!R)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(B(R))return[void 0,Ct()];let e=await xt(R);return[e,Ct(e)]},Tt=(ht(),me(dt)).default,Et=async(e,t,n,r)=>{let i=Tt&&!(e||t);if(i)if(R)i=B(R)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`);if(i)return[void 0,Tt];{let r=`ort-wasm-simd-threaded.asyncify.mjs`,i=e??yt(r,t),a=n&&i&&!B(i,t),o=a?await xt(i):i??bt(r,t);return[a?o:void 0,await St(o)]}}}),Ot,kt,At,jt,Mt,Nt,Pt,Ft,V,It=k(()=>{Dt(),kt=!1,At=!1,jt=!1,Mt=()=>{if(typeof SharedArrayBuffer>`u`)return!1;try{return typeof MessageChannel<`u`&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Nt=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Pt=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Ft=async e=>{if(kt)return Promise.resolve();if(At)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(jt)throw Error(`previous call to 'initializeWebAssembly()' failed.`);At=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!Pt())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!Nt())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=Mt();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.`),console.warn(`WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.`),e.numThreads=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await Et(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=z();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{At=!1,kt=!0,Ot=t,e(),d&&URL.revokeObjectURL(d)},e=>{At=!1,jt=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},V=()=>{if(kt&&Ot)return Ot;throw Error(`WebAssembly is not initialized yet.`)}}),H,U,W,Lt=k(()=>{It(),H=(e,t)=>{let n=V(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},U=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)U(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},W=e=>{let t=V(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),Rt,zt=k(()=>{It(),Lt(),Rt=e=>{let t=V(),n=0,r=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=H(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&W(`Can't create run options.`),e?.extra!==void 0&&U(e.extra,``,new WeakSet,(e,i)=>{let a=H(e,r),o=H(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&W(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt=k(()=>{It(),Lt(),Bt=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},Vt=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},Ht=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},Ut=(e,t,n,r)=>{let i=H(t,r),a=H(n,r);V()._OrtAddSessionConfigEntry(e,i,a)!==0&&W(`Can't set a session config entry: ${t} - ${n}.`)},Wt=(e,t,n,r)=>{let i=H(t,r),a=H(n,r);e.push([i,a])},Gt=async(e,t,n)=>{let r=t.executionProviders;for(let i of r){let r=typeof i==`string`?i:i.name,a=[];switch(r){case`webnn`:if(r=`WEBNN`,Ut(e,`session.disable_quant_qdq`,`1`,n),Ut(e,`session.disable_qdq_constant_folding`,`1`,n),typeof i!=`string`){let t=i?.deviceType;t&&Ut(e,`deviceType`,t,n)}break;case`webgpu`:{r=`WebGPU`;let e;if(typeof i!=`string`){let r=i;if(r.device)if(typeof GPUDevice<`u`&&r.device instanceof GPUDevice)e=r.device;else throw Error(`Invalid GPU device set in WebGPU EP options.`);let{enableGraphCapture:o}=t;if(typeof o==`boolean`&&o&&Wt(a,`enableGraphCapture`,`1`,n),typeof r.preferredLayout==`string`&&Wt(a,`preferredLayout`,r.preferredLayout,n),r.forceCpuNodeNames){let e=Array.isArray(r.forceCpuNodeNames)?r.forceCpuNodeNames:[r.forceCpuNodeNames];Wt(a,`forceCpuNodeNames`,e.join(` +`),n)}r.validationMode&&Wt(a,`validationMode`,r.validationMode,n)}let o=V().webgpuRegisterDevice(e);if(o){let[e,t,r]=o;Wt(a,`deviceId`,e.toString(),n),Wt(a,`webgpuInstance`,t.toString(),n),Wt(a,`webgpuDevice`,r.toString(),n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let o=H(r,n),s=a.length,c=0,l=0;if(s>0){c=V()._malloc(s*V().PTR_SIZE),n.push(c),l=V()._malloc(s*V().PTR_SIZE),n.push(l);for(let e=0;e{let t=V(),n=0,r=[],i=e||{};Ht(i);try{let e=Bt(i.graphOptimizationLevel??`all`),a=Vt(i.executionMode??`sequential`),o=typeof i.logId==`string`?H(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?H(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&W(`Can't create session options.`),i.executionProviders&&await Gt(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);Ut(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=H(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&W(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&U(i.extra,``,new WeakSet,(e,t)=>{Ut(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&W(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),G,Jt,Yt,Xt,Zt,Qt,$t,en,tn=k(()=>{G=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},Jt=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},Yt=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},Xt=e=>{switch(e){case`float16`:return typeof Float16Array<`u`?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},Zt=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},Qt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,$t=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,en=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),nn,rn=k(()=>{at(),nn=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),an,on=k(()=>{tn(),an=(e,t)=>new(Xt(t))(e)}),sn,cn,ln,un,dn,fn,K,pn=k(()=>{tn(),sn=[`V`,`I`,`W`,`E`,`F`],cn=(e,t)=>{console.log(`[${sn[e]},${new Date().toISOString()}]${t}`)},dn=(e,t)=>{ln=e,un=t},fn=(e,t)=>{let n=Zt(e);n>=Zt(ln)&&cn(n,typeof t==`function`?t():t)},K=(...e)=>{un&&fn(...e)}}),mn,hn,gn,_n,vn,yn,bn,xn,Sn,Cn,wn,Tn=k(()=>{tn(),pn(),mn=new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),hn=(e,t)=>{if(t===`int32`)return e;let n=mn.get(t);if(!n)throw Error(`WebNN backend does not support data type: ${t}`);let r=n/8;if(e.byteLength%r!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${r}.`);let i=e.byteLength/r,a=new(Xt(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t2147483647n||n<-2147483648n)throw Error(`Can not convert int64 data to int32 - value out of range.`);e[t]=Number(n)}return new Uint8Array(e.buffer)}case`int8`:case`uint8`:case`uint32`:{if(t===`uint32`&&a.some(e=>e>2147483647))throw Error(`Can not convert uint32 data to int32 - value out of range.`);let e=Int32Array.from(a,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from ${t} to 'int32'`)}},gn=(e,t)=>{if(t===`int32`)return e;if(e.byteLength%4!=0)throw Error(`Invalid Uint8Array length - must be a multiple of 4 (int32).`);let n=e.byteLength/4,r=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case`int64`:{let e=BigInt64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`uint64`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uin64 - negative value found.`);let e=BigUint64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`int8`:{if(r.some(e=>e<-128||e>127))throw Error(`Can not convert int32 data to int8 - value out of range.`);let e=Int8Array.from(r,Number);return new Uint8Array(e.buffer)}case`uint8`:if(r.some(e=>e<0||e>255))throw Error(`Can not convert int32 data to uint8 - value out of range.`);return Uint8Array.from(r,Number);case`uint32`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uint32 - negative value found.`);let e=Uint32Array.from(r,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${t}`)}},_n=1,vn=()=>_n++,yn=new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),bn=(e,t)=>{let n=mn.get(e);if(!n)throw Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((e,t)=>e*t)*n/8):0},xn=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:r,dataType:i,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=r,this.dataType=i,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return bn(this.dataType,this.tensorShape)}destroy(){K(`verbose`,()=>`[WebNN] TensorWrapper.destroy`),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=gn(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}else return new Uint8Array(n).buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((e,t)=>e===n[t])}setIsDataConverted(e){this.isDataConverted=e}},Sn=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,r){let i=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=yn.get(t),!o||a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);K(`verbose`,()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(i,t,n))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==bn(t,n))throw Error(`Unable to copy data to tensor with different size.`);this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let s=typeof MLTensorUsage>`u`?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,s,!0,!0,o),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType===`int32`)t=hn(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else K(`verbose`,()=>`Data size does not match tensor size. Releasing tensor.`),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?gn(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw Error(`Tensor has not been created.`);return e?this.wrapper.read(e):this.wrapper.read()}},Cn=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw Error(`MLContext not found for session.`);return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=vn();return this.tensorTrackersById.set(e,new Sn(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,r,i){K(`verbose`,()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${r}, copyOld: ${i}}`);let a=this.tensorTrackersById.get(t);if(!a)throw Error(`Tensor not found.`);return a.ensureTensor(e,n,r,i)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);n.upload(t)}async download(e,t){K(`verbose`,()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,r){let i=this.getMLContext(e),a=vn(),o=new xn({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new Sn(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,n,r,i,a,o){let s=this.getMLContext(e);for(let[r,i]of this.freeTensors.entries())if(i.canReuseTensor(s,t,n)){K(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}K(`verbose`,()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}}`);let c=await s.createTensor({dataType:o??t,shape:n,dimensions:n,usage:r,writable:i,readable:a});return new xn({sessionId:e,context:s,tensor:c,dataType:t,shape:n,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},wn=(...e)=>new Cn(...e)}),En={};fe(En,{WebNNBackend:()=>kn});var Dn,On,kn,An=k(()=>{tn(),It(),on(),Tn(),pn(),Dn=new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),On=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((n,i)=>n===r[i]&&e[n]===t[n])},kn=class{constructor(e){this.tensorManager=wn(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,dn(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){K(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){K(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)K(`verbose`,()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(t=>t.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}else if(e===void 0){let e=this.mlContextCache.findIndex(e=>e.options===void 0&&e.gpuDevice===void 0);if(e!==-1)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex(t=>On(t.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex(e=>e.mlContext===t);e!==-1&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){K(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=Dn.get(n);if(!a)throw Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,r,i)}async createTemporaryTensor(e,t,n){K(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=Dn.get(t);if(!r)throw Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,r,n,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,t){if(!V().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);K(`verbose`,()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return an(n,t)}}registerMLTensor(e,t,n,r){let i=Dn.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return K(`verbose`,()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,n,r,i,a,o=!1){if(!a)throw Error(`External mounted files are not available.`);let s=e;e.startsWith(`./`)&&(s=e.substring(2));let c=a.get(s);if(!c)throw Error(`File with name ${s} not found in preloaded files.`);if(t+n>c.byteLength)throw Error(`Out of bounds: data offset and length exceed the external file data size.`);let l=c.slice(t,t+n).buffer,u;switch(i.dataType){case`float32`:u=new Float32Array(l);break;case`float16`:u=typeof Float16Array<`u`?new Float16Array(l):new Uint16Array(l);break;case`int32`:u=new Int32Array(l);break;case`uint32`:u=new Uint32Array(l);break;case`int64`:if(o){let e=hn(new Uint8Array(l),`int64`);u=new Int32Array(e.buffer),i.dataType=`int32`}else u=new BigInt64Array(l);break;case`uint64`:u=new BigUint64Array(l);break;case`int8`:u=new Int8Array(l);break;case`int4`:case`uint4`:case`uint8`:u=new Uint8Array(l);break;default:throw Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return K(`verbose`,()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}} ${o?`(Note: it was int64 data type and registered to int32 as workaround)`:``}`),r.constant(i,u)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let r=Dn.get(G(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),jn,Mn,Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn,Hn,Un,Wn=k(()=>{it(),zt(),qt(),tn(),It(),Lt(),rn(),jn=(e,t)=>{V()._OrtInit(e,t)!==0&&W(`Can't initialize onnxruntime.`)},Mn=async e=>{jn(e.wasm.numThreads,Zt(e.logLevel))},Nn=async(e,t)=>{V().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);if(t===`webgpu`&&V().webgpuInit(t=>{e.webgpu.device=t}),t===`webnn`){let t=new(An(),me(En)).WebNNBackend(e);V().webnnInit([t,()=>t.reserveTensorId(),e=>t.releaseTensorId(e),async(e,n,r,i,a)=>t.ensureTensor(e,n,r,i,a),(e,n)=>{t.uploadTensor(e,n)},async(e,n)=>t.downloadTensor(e,n),(e,n)=>t.registerMLContext(e,n),!!e.trace])}},Pn=new Map,Fn=e=>{let t=V(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&W(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},In=(e,t)=>{let n=V(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&W(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e{let t=V(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},Rn=async(e,t)=>{let n,r,i=V();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=Ln(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await Kt(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path;e.push(nn(typeof n==`string`?n:n.data).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;n?i.currentContext=n:r?i.currentContext=await i.webnnCreateMLContext(r):i.currentContext=await i.webnnCreateMLContext({deviceType:a,powerPreference:o})}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&W(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=Fn(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;te===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&W(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>en(e))}),Pn.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&W(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&W(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&W(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},zn=e=>{let t=V(),n=Pn.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&W(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&W(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&W(`Can't release session.`),Pn.delete(e)},Bn=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=V(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=Yt(G(l),u);{let e=s.webgpuRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(t,r)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=Yt(G(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,G(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;es.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(G(l),p,m,g,u.length,en(f));e===0&&W(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},Vn=async(e,t,n,r,i,a)=>{let o=V(),s=o.PTR_SIZE,c=Pn.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4],m=c[5],h=t.length,g=r.length,_=0,v=[],y=[],b=[],ee=[],te=[],x=o.stackSave(),ne=o.stackAlloc(h*s),S=o.stackAlloc(h*s),C=o.stackAlloc(g*s),w=o.stackAlloc(g*s);try{[_,v]=Rt(a),qe(`wasm prepareInputOutputTensor`);for(let r=0;re*t,1);u=Jt(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t0){let t=o.webgpuGetBuffer;if(!t)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let r=t(d),i=Yt(a,g);if(i===void 0||!Qt(u))throw Error(`Unsupported data type: ${u}`);l=!0;{o.webgpuRegisterBuffer(r,e,d);let t=o.webgpuCreateDownloader(r,i,e);x.push([u,h,{gpuBuffer:r,download:async()=>{let e=await t();return new(Xt(u))(e)},dispose:()=>{o._OrtReleaseTensor(n)!==0&&W(`Can't release tensor.`)}},`gpu-buffer`])}}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(Yt(a,g)===void 0||!$t(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,x.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=x.length;l=!0,T.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),x.push([u,h,[],`cpu`])}else{let e=new(Xt(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),x.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&W(`Can't clear bound outputs.`),Pn.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(T))x[e][2]=t;return Je(`wasm ProcessOutputTensor`),x}finally{o.webnnOnRunEnd?.(l),o.stackRestore(x),n.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),i.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._OrtReleaseTensor(e)),ee.forEach(e=>o._free(e)),_!==0&&o._OrtReleaseRunOptions(_),v.forEach(e=>o._free(e))}},Hn=e=>{let t=V(),n=Pn.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&W(`Can't get an profile file name.`),t._OrtFree(i)},Un=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),Gn,q,Kn,qn,Jn,Yn,Xn,Zn,J,Qn,$n,er,tr,Y,nr,rr,ir,ar,or=k(()=>{it(),Wn(),It(),Dt(),Gn=()=>!!P.wasm.proxy&&typeof document<`u`,Kn=!1,qn=!1,Jn=!1,Zn=new Map,J=(e,t)=>{let n=Zn.get(e);n?n.push(t):Zn.set(e,[t])},Qn=()=>{if(Kn||!qn||Jn||!q)throw Error(`worker not ready`)},$n=e=>{switch(e.data.type){case`init-wasm`:Kn=!1,e.data.err?(Jn=!0,Xn[1](e.data.err)):(qn=!0,Xn[0]()),Yn&&=(URL.revokeObjectURL(Yn),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=Zn.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},er=async()=>{if(!qn){if(Kn)throw Error(`multiple calls to 'initWasm()' detected.`);if(Jn)throw Error(`previous call to 'initWasm()' failed.`);if(Kn=!0,Gn())return new Promise((e,t)=>{q?.terminate(),wt().then(([n,r])=>{try{q=r,q.onerror=e=>t(e),q.onmessage=$n,Xn=[e,t];let i={type:`init-wasm`,in:P};!i.in.wasm.wasmPaths&&(n||_t)&&(i.in.wasm.wasmPaths={wasm:new URL(`/assets/ort-wasm-simd-threaded.asyncify-CvvOzbbq.wasm`,``+import.meta.url).href}),q.postMessage(i),Yn=n}catch(e){t(e)}},t)});try{await Ft(P.wasm),await Mn(P),qn=!0}catch(e){throw Jn=!0,e}finally{Kn=!1}}},tr=async e=>{if(Gn())return Qn(),new Promise((t,n)=>{J(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:P}};q.postMessage(r)});await Nn(P,e)},Y=async e=>Gn()?(Qn(),new Promise((t,n)=>{J(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};q.postMessage(r,[e.buffer])})):Ln(e),nr=async(e,t)=>{if(Gn()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return Qn(),new Promise((n,r)=>{J(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),q.postMessage(i,a)})}else return Rn(e,t)},rr=async e=>{if(Gn())return Qn(),new Promise((t,n)=>{J(`release`,[t,n]);let r={type:`release`,in:e};q.postMessage(r)});zn(e)},ir=async(e,t,n,r,i,a)=>{if(Gn()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return Qn(),new Promise((i,o)=>{J(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};q.postMessage(c,Un(s))})}else return Vn(e,t,n,r,i,a)},ar=async e=>{if(Gn())return Qn(),new Promise((t,n)=>{J(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};q.postMessage(r)});Hn(e)}}),sr,cr,lr,ur=k(()=>{it(),or(),tn(),at(),rn(),sr=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},cr=e=>{switch(e[3]){case`cpu`:return new L(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!Qt(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return L.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!$t(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return L.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},lr=class{async fetchModelAndCopyToWasmMemory(e){return Y(await nn(e))}async loadModel(e,t){Ge();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await nr(n,t),Ke()}async dispose(){return rr(this.sessionId)}async run(e,t,n){Ge();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>sr(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?sr(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await ir(this.sessionId,i,s,o,c,n),u={};for(let e=0;epr,initializeFlags:()=>fr,wasmBackend:()=>mr});var fr,pr,mr,hr=k(()=>{it(),or(),ur(),fr=()=>{(typeof P.wasm.initTimeout!=`number`||P.wasm.initTimeout<0)&&(P.wasm.initTimeout=0);let e=P.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),P.wasm.simd=!1),typeof P.wasm.proxy!=`boolean`&&(P.wasm.proxy=!1),typeof P.wasm.trace!=`boolean`&&(P.wasm.trace=!1),typeof P.wasm.numThreads!=`number`||!Number.isInteger(P.wasm.numThreads)||P.wasm.numThreads<=0)if(typeof self<`u`&&!self.crossOriginIsolated)P.wasm.numThreads=1;else{let e=typeof navigator>`u`?de(`node:os`).cpus().length:navigator.hardwareConcurrency;P.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},pr=class{async init(e){fr(),await er(),await tr(e)}async createInferenceSessionHandler(e,t){let n=new lr;return await n.loadModel(e,t),n}},mr=new pr});it(),it(),it();var gr=`1.27.0`;{let e=(hr(),me(dr)).wasmBackend;ge(`webgpu`,e,5),ge(`webnn`,e,5),ge(`cpu`,e,10),ge(`wasm`,e,10)}Object.defineProperty(P.versions,"web",{value:gr,enumerable:!0});function _r(e,t){let n=e[t];if(!(e instanceof Uint16Array))return Number(n);let r=n&32768?-1:1,i=n>>10&31,a=n&1023;return i===0?r*2**-14*(a/1024):i===31?a?NaN:r*(1/0):r*2**(i-15)*(1+a/1024)}function vr(e){let t=e.info;return[t.vendor,t.architecture,t.device,t.description].filter(Boolean).join(` · `)||`WebGPU adapter`}function yr(){if(!globalThis.crossOriginIsolated)return 1;let e=navigator.hardwareConcurrency||1;return Math.min(4,Math.ceil(e/2))}function br(){let e=yr();return`WebAssembly CPU · ${e} ${e===1?`thread`:`threads`}`}async function xr(e){if(e===`wasm`||!globalThis.isSecureContext||!navigator.gpu)return{supported:!0,adapter:br(),shaderF16:!1,backend:`wasm`};let t=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});return t?{supported:!0,adapter:vr(t),shaderF16:t.features.has(`shader-f16`),backend:`webgpu`}:{supported:!0,adapter:br(),shaderF16:!1,backend:`wasm`}}var Sr=new Float32Array(1),Cr=new Uint32Array(Sr.buffer);function wr(e){Sr[0]=e;let t=Cr[0],n=t>>16&32768,r=(t>>23&255)-127+15,i=t&8388607;return r<=0?r<-10?n:(i=(i|8388608)>>1-r,n|i+4096>>13):r>=31?n|(i?32256:31744):(i+=4096,i&8388608&&(i=0,r+=1,r>=31)?n|31744:n|r<<10|i>>13)}function Tr(e,t){if(t===`fp32`)return e;let n=new Uint16Array(e.length);for(let t=0;to&&(o=r,a=e)}r.push(a)}return{tokens:r,arrayType:n.constructor?.name||`unknown`,finiteValues:i,totalValues:n.length}}var Or=class e{cacheLocation;encoder;crossCache;decoder;manifest;precision;adapter;backend;constructor(e,t,n,r,i,a,o){this.cacheLocation=r,this.encoder=i,this.crossCache=a,this.decoder=o,this.manifest=e,this.precision=e.precision,this.adapter=t,this.backend=n}static async create(t=`/models`,n=()=>{},r,i=!0,a=`webgpu`){P.logLevel=`error`,P.wasm.wasmPaths=`/ort/`;let o;if(a===`webgpu`){if(!globalThis.isSecureContext||!navigator.gpu)throw Error(`WebGPU needs Safari or Chrome over HTTPS (localhost also works). `);n(`Checking WebGPU…`);let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`No WebGPU adapter is available.`);P.webgpu.adapter=e,o=vr(e)}else n(`Starting the local CPU runtime…`),P.wasm.numThreads=yr(),o=br(),i=!1;let s=r??`fp32`;if(a===`wasm`&&s===`fp16`)throw Error(`The CPU browser path uses the verified FP32 model.`);if(a===`webgpu`&&s===`fp16`&&!P.webgpu.adapter?.features.has(`shader-f16`))throw Error(`This WebGPU adapter cannot run the FP16 model.`);let c=`${t}/${s}`;n(`Loading the ${s.toUpperCase()} model…`);let l=await fetch(`${c}/manifest.json`,{cache:`no-cache`});if(!l.ok)throw Error(`${s.toUpperCase()} model manifest: HTTP ${l.status}`);let u=await l.json();if(u.precision!==s)throw Error(`Model precision does not match this GPU.`);let d={executionProviders:[a],graphOptimizationLevel:`all`,logSeverityLevel:3};n(`Compiling the encoder…`);let f=await Qe.create(`${c}/encoder.onnx`,{...d,...i?{preferredOutputLocation:`gpu-buffer`}:{}});n(`Compiling the attention cache…`);let p=await Qe.create(`${c}/cross_cache.onnx`,{...d,...i?{preferredOutputLocation:`gpu-buffer`}:{}});n(`Compiling the note decoder…`);let m={logits:`cpu`};for(let e=0;e<8;e++)m[`layer_${e}_present_self_key`]=`gpu-buffer`,m[`layer_${e}_present_self_value`]=`gpu-buffer`;let h=await Qe.create(`${c}/decoder_step.onnx`,{...d,...i?{preferredOutputLocation:m}:{}});return new e(u,o,a,i?`gpu`:`cpu`,f,p,h)}async transcribeSegment(e,t){if(t?.aborted)throw new DOMException(`Cancelled`,`AbortError`);let n=this.precision===`fp16`?`float16`:`float32`,r=new L(n,Tr(e,this.precision),[1,110,b]),i=performance.now(),a=await this.encoder.run({spectrogram:r}),o=performance.now()-i;r.dispose();let s=a.encoder_hidden_states,c=performance.now(),l=await this.crossCache.run({encoder_hidden_states:s}),u=performance.now()-c;s.dispose();let d=this.crossCache.outputNames.map(e=>l[e]),f=Array.from({length:16},()=>new L(n,this.precision===`fp16`?new Uint16Array:new Float32Array,[13,6,0,64])),p=Array(13).fill(0),m=Array(13).fill(!0),h=Array.from({length:13},()=>[]),g=`unknown`,_=0,v=0,y=[],ee=0,te=0;try{for(let e=0;eo[e]);for(let e of f)e.dispose();f=l,p=c;for(let e=0;e<13;e++){let t=m[e]?c[e]:0;h[e].push(t),t===1&&(m[e]=!1)}if(m.every(e=>!e))break;e%8==7&&await new Promise(e=>requestAnimationFrame(()=>e()))}return{channels:h,diagnostics:{precision:this.precision,backend:this.backend,cacheLocation:this.cacheLocation,logitsArray:g,steps:ee,endedChannels:m.filter(e=>!e).length,finiteLogits:_,totalLogits:v,firstTokens:y,channelPreviews:h.slice(0,3).map(e=>e.slice(0,12)),encoderMs:o,crossCacheMs:u,decoderMs:te}}}finally{for(let e of f)e.dispose();for(let e of d)e.dispose()}}async dispose(){await Promise.all([this.encoder.release(),this.crossCache.release(),this.decoder.release()])}},X=r(),kr=new URLSearchParams(window.location.search).get(`precision`),Ar=kr===`fp32`||kr===`fp16`?kr:void 0,jr=new URLSearchParams(window.location.search).get(`cache`)!==`cpu`,Mr=new URLSearchParams(window.location.search).get(`backend`),Nr=Mr===`wasm`||Mr===`webgpu`?Mr:void 0;function Pr(){let e=(0,o.useRef)(null),n=e.current??=new t({forceFallback:!0}),r=(0,o.useRef)(null),i=(0,o.useRef)(null),s=(0,o.useRef)(null),c=(0,o.useRef)(null),[l,u]=(0,o.useState)(null),[f,p]=(0,o.useState)(null),[m,h]=(0,o.useState)(`idle`),[v,y]=(0,o.useState)(`Choose a recording or make one here.`),[b,x]=(0,o.useState)(0),[ne,S]=(0,o.useState)([]),[w,T]=(0,o.useState)(null),[E,D]=(0,o.useState)(2.05),[ie,O]=(0,o.useState)(!1),[ae,oe]=(0,o.useState)(!1),[se,ce]=(0,o.useState)(``),[,le]=(0,o.useState)(!1);(0,o.useEffect)(()=>{xr(Nr).then(u).catch(e=>u({supported:!1,adapter:``,shaderF16:!1,backend:`wasm`,reason:String(e)}))},[]),(0,o.useEffect)(()=>{let e=0,t=()=>{r.current?.setPlayhead(n.seconds),r.current?.render(),e=requestAnimationFrame(t)};return e=requestAnimationFrame(t),()=>cancelAnimationFrame(e)},[n]),(0,o.useEffect)(()=>()=>{s.current?.abort(),c.current?.stream.getTracks().forEach(e=>e.stop())},[]),(0,o.useEffect)(()=>()=>{w&&URL.revokeObjectURL(w)},[w]);function ue(e){s.current?.abort(),n.reset(),r.current?.clear(),p(e),S([]),x(0),h(`idle`),ce(``),y(`${e.name} stays on this device.`),T(null)}async function de(){if(!navigator.mediaDevices?.getUserMedia||typeof MediaRecorder>`u`)throw Error(`Recording is unavailable in this browser. Choose an audio file instead.`);let e=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!1,noiseSuppression:!1}}),t;try{t=new MediaRecorder(e)}catch(t){throw e.getTracks().forEach(e=>e.stop()),t}let n={recorder:t,stream:e,chunks:[]};c.current=n,t.ondataavailable=e=>{e.data.size&&n.chunks.push(e.data)},t.onstop=()=>{let r=new Blob(n.chunks,{type:t.mimeType||`audio/mp4`});e.getTracks().forEach(e=>e.stop()),ue(new File([r],`hendrix-recording-${Date.now()}.${r.type.includes(`webm`)?`webm`:r.type.includes(`ogg`)?`ogg`:`m4a`}`,{type:r.type})),c.current=null,O(!1)};try{t.start(250)}catch(t){throw e.getTracks().forEach(e=>e.stop()),c.current=null,t}O(!0),y(`Recording locally… tap Stop when you have enough audio.`)}function k(){c.current?.recorder.stop()}async function fe(){y(`Loading the known two-second check clip…`);let e=await fetch(`/diagnostic.wav`,{cache:`no-cache`});if(!e.ok)throw Error(`Diagnostic clip: HTTP ${e.status}`);ue(new File([await e.blob()],`hendrix-known-check.wav`,{type:`audio/wav`})),D(2.05)}async function pe(e){oe(!0);try{await e()}catch(e){h(`error`),y(e instanceof Error?e.message:String(e))}finally{oe(!1)}}async function me(){if(!f||!l?.supported)return;let e=new AbortController;s.current?.abort(),s.current=e,h(`loading`),x(0),ce(``),S([]),T(null),n.reset(),r.current?.clear(),await n.unlock().catch(()=>{});let t=n.loadWav(f).catch(()=>{}),a=performance.now();try{y(`Decoding and resampling audio on this device…`);let[o]=await Promise.all([ee(f,E),t]);e.signal.throwIfAborted();let s=o.subarray(0,Math.min(o.length,Math.round(E*_))),c=s.length/_,u=te(s);i.current||=await Or.create(`/models`,t=>{e.signal.aborted||y(t)},Ar,jr,l.backend),e.signal.throwIfAborted();let p=i.current;h(`running`);let m=[],v=[];for(let t=0;t0&&n.scheduleStop(c+.3);let ne=re(b);T(URL.createObjectURL(ne));let w=(performance.now()-a)/1e3;ce(v.join(` | `)),y(`${b.length} notes from ${c.toFixed(1)} s of audio in ${w.toFixed(1)} s. Audio never left this device.`),h(`done`)}catch(t){e.signal.aborted?(h(`idle`),y(`Cancelled.`)):(console.error(t),h(`error`),y(t instanceof Error?t.message:String(t)))}finally{s.current===e&&(s.current=null)}}function he(){s.current?.abort(),y(`Cancelling… waiting for the current browser operation to finish.`)}let A=Array.from(new Set(ne.map(d))).sort(),ge=m===`loading`||m===`running`,j=ge||ie||ae;return(0,X.jsxs)(`main`,{className:`local-shell`,children:[(0,X.jsxs)(`header`,{className:`local-hero`,children:[(0,X.jsx)(`a`,{href:`/`,className:`local-kicker`,children:`HENDRIX / AUDIO TO MIDI`}),(0,X.jsx)(`h1`,{children:(0,X.jsxs)(X.Fragment,{children:[`Audio to MIDI.`,(0,X.jsx)(`br`,{}),`On your device.`]})}),(0,X.jsxs)(`p`,{children:[(0,X.jsx)(`strong`,{children:`29× fewer learned parameters than MuScriptor-large.`}),` The D26 research checkpoint runs here with WebGPU or a CPU fallback. Pick a file or record here; the page turns it into notes without an upload.`]})]}),(0,X.jsxs)(`section`,{className:`local-card capability-card`,children:[(0,X.jsx)(`span`,{className:l?.supported?`status-dot ready`:`status-dot`}),l===null?`Checking this browser…`:l.supported?`${l.adapter} · ${Ar===`fp16`?`FP16 diagnostic · 100.1 MB`:`FP32 verified · 195.3 MB`}`:l.reason]}),(0,X.jsxs)(`section`,{className:`local-card input-card`,children:[(0,X.jsxs)(`div`,{className:`file-row`,children:[(0,X.jsxs)(`label`,{className:`primary-button`,children:[`Choose audio`,(0,X.jsx)(`input`,{type:`file`,accept:`audio/*`,disabled:j,hidden:!0,onChange:e=>{let t=e.target.files?.[0];t&&ue(t)}})]}),(0,X.jsx)(`button`,{className:`secondary-button`,disabled:j,onClick:()=>pe(fe),children:`Try Bach example`}),ie?(0,X.jsx)(`button`,{className:`record-button`,onClick:k,children:`Stop recording`}):(0,X.jsx)(`button`,{className:`secondary-button`,onClick:()=>pe(de),disabled:!l?.supported||j,children:`Record here`}),(0,X.jsxs)(`label`,{className:`limit-label`,children:[`Use first`,(0,X.jsxs)(`select`,{disabled:j,value:E,onChange:e=>D(Number(e.target.value)),children:[(0,X.jsx)(`option`,{value:2.05,children:`2 seconds`}),(0,X.jsx)(`option`,{value:6,children:`6 seconds`}),(0,X.jsx)(`option`,{value:10,children:`10 seconds`}),(0,X.jsx)(`option`,{value:30,children:`30 seconds`}),(0,X.jsx)(`option`,{value:60,children:`60 seconds`})]})]})]}),(0,X.jsx)(`div`,{className:`chosen-file`,children:f?f.name:`No recording chosen`}),(0,X.jsxs)(`div`,{className:`action-row`,children:[(0,X.jsx)(`button`,{className:`primary-button`,onClick:me,disabled:!f||!l?.supported||j,children:`Run on this device`}),ge&&(0,X.jsx)(`button`,{className:`secondary-button`,onClick:he,children:`Cancel`})]}),(0,X.jsx)(`p`,{className:`run-hint`,children:`Start with two seconds. The first run downloads a 195.3 MB model and prepares it; speed varies by device.`}),(0,X.jsx)(`div`,{className:`progress-track`,role:`progressbar`,"aria-label":`Transcription progress`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(b*100),children:(0,X.jsx)(`div`,{style:{width:`${b*100}%`}})}),(0,X.jsx)(`p`,{role:`status`,"aria-live":`polite`,className:m===`error`?`run-status error`:`run-status`,children:v}),se&&(0,X.jsxs)(`details`,{className:`run-diagnostics`,children:[(0,X.jsx)(`summary`,{children:`Run details`}),(0,X.jsx)(`p`,{className:`diagnostic-output`,children:se})]})]}),ne.length>0&&(0,X.jsxs)(`section`,{className:`result-bar`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`strong`,{children:ne.length}),(0,X.jsx)(`span`,{children:`notes`})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`strong`,{children:A.length}),(0,X.jsx)(`span`,{children:`families`})]}),(0,X.jsx)(`button`,{onClick:()=>n.state===`started`?n.pause():n.play(),className:`secondary-button`,children:`Play / pause`}),w&&(0,X.jsx)(`a`,{className:`primary-button`,href:w,download:`${f?.name.replace(/\.[^/.]+$/,``)??`hendrix`}.mid`,children:`Download MIDI`})]}),(0,X.jsxs)(`div`,{className:`roll-stage`,children:[(0,X.jsx)(a,{rollRef:r,audio:n,setUserScrolled:le}),ne.length===0&&(0,X.jsx)(`div`,{className:`roll-empty`,children:`Your notes will appear here`})]}),(0,X.jsxs)(`footer`,{className:`local-footer`,children:[(0,X.jsx)(`p`,{children:`The D26 research build uses the 195.3 MB FP32 graph. WebGPU is preferred; WebAssembly runs the same graph on the CPU when no GPU is available. Later visits use the browser cache.`}),(0,X.jsxs)(`nav`,{"aria-label":`Other demo modes`,className:`local-footer-links`,children:[(0,X.jsx)(`a`,{href:`https://github.com/jackboyla/hendrix`,children:`Source and research`}),(0,X.jsx)(`a`,{href:`/local.html?backend=wasm`,children:`Force CPU WebAssembly`}),!1,!1]})]})]})}(0,s.createRoot)(document.getElementById(`root`)).render((0,X.jsx)(Pr,{})); \ No newline at end of file diff --git a/assets/ort-wasm-simd-threaded.asyncify-CvvOzbbq.wasm b/assets/ort-wasm-simd-threaded.asyncify-CvvOzbbq.wasm new file mode 100644 index 0000000000000000000000000000000000000000..1df09ff7c52fb0ba86836a7a18ed7362969aeabb --- /dev/null +++ b/assets/ort-wasm-simd-threaded.asyncify-CvvOzbbq.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e83cd6cee77e478bc96a7e91b198144fb5e4126287daf1f9b54bb195ebcd55a +size 24254953 diff --git a/assets/spessasynth_processor.min-tdOdhV7p.js b/assets/spessasynth_processor.min-tdOdhV7p.js new file mode 100644 index 0000000000000000000000000000000000000000..f9fcd304a8bdc3b540feb00efd55db7decc0286e --- /dev/null +++ b/assets/spessasynth_processor.min-tdOdhV7p.js @@ -0,0 +1,18 @@ +function Ht(t,e,A=0){let s=0;for(let a=0;a>>0}function Nt(t,e){let A=Ht(t,e,t.currentIndex);return t.currentIndex+=e,A}function aA(t,e){let A=new Array(e).fill(0);for(let s=e-1;s>=0;s--)A[s]=t&255,t>>=8;return A}function Xn(t,e){let A=Zn(t,e,t.currentIndex);return t.currentIndex+=e,A}function Zn(t,e,A=0){let s=0n;for(let a=0;a>>0}function ls(t,e,A){for(let s=0;s>s*8&255}function se(t,e){t[t.currentIndex++]=e&255,t[t.currentIndex++]=e>>8}function ge(t,e){ls(t,e,4)}function xA(t,e){let A=BigInt(e);for(let s=0n;s<8n;s++)t[t.currentIndex++]=Number(A>>s*8n&255n)}function Cs(t,e){let A=e<<8|t;return A>32767?A-65536:A}function Wn(t){return t>127?t-256:t}var te=class extends Uint8Array{currentIndex=0;slice(t,e){let A=super.slice(t,e);return A.currentIndex=0,A}};function We(t,e=t.length,A=0){let s="";for(let a=0;a0&&e.length>A&&(e=e.slice(0,A));for(let s=0;se.length)for(let s=0;s>7!==1)break}return e}function HA(t){let e=[t&127];for(t>>=7;t>0;)e.unshift(t&127|128),t>>=7;return e}function _A(t){t=Math.floor(t);let e=Math.floor(t/60),A=Math.round(t-e*60);return{minutes:e,seconds:A,time:`${e.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`}}function en(t){let e="";for(let A=0;A{var t=Uint8Array,e=Uint16Array,A=Int32Array,s=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),a=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),n=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),r=function(U,T){for(var Q=new e(31),b=0;b<31;++b)Q[b]=T+=1<>1|(D&21845)<<1,g=(g&52428)>>2|(g&13107)<<2,g=(g&61680)>>4|(g&3855)<<4,B[D]=((g&65280)>>8|(g&255)<<8)>>1;var g,D,E=function(U,T,Q){for(var b=U.length,L=0,z=new e(T);L>V]=ee}else for(W=new e(b),L=0;L>15-U[L]);return W},p=new t(288);for(D=0;D<144;++D)p[D]=8;var D;for(D=144;D<256;++D)p[D]=9;var D;for(D=256;D<280;++D)p[D]=7;var D;for(D=280;D<288;++D)p[D]=8;var D,y=new t(32);for(D=0;D<32;++D)y[D]=5;var D,R=E(p,9,1),S=E(y,5,1),w=function(U){for(var T=U[0],Q=1;QT&&(T=U[Q]);return T},F=function(U,T,Q){var b=T/8|0;return(U[b]|U[b+1]<<8)>>(T&7)&Q},H=function(U,T){var Q=T/8|0;return(U[Q]|U[Q+1]<<8|U[Q+2]<<16)>>(T&7)},k=function(U){return(U+7)/8|0},u=function(U,T,Q){return(T==null||T<0)&&(T=0),(Q==null||Q>U.length)&&(Q=U.length),new t(U.subarray(T,Q))},m=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],J=function(U,T,Q){var b=new Error(T||m[U]);if(b.code=U,Error.captureStackTrace&&Error.captureStackTrace(b,J),!Q)throw b;return b},O=function(U,T,Q,b){var L=U.length,z=b?b.length:0;if(!L||T.f&&!T.l)return Q||new t(0);var $=!Q,W=$||T.i!=2,V=T.i;$&&(Q=new t(L*3));var ee=function(Be){var he=Q.length;if(Be>he){var xe=new t(Math.max(he*2,Be));xe.set(Q),Q=xe}},Ae=T.f||0,Y=T.p||0,re=T.b||0,ue=T.l,Le=T.d,Ee=T.m,Re=T.n,Oe=L*8;do{if(!ue){Ae=F(U,Y,1);var Bt=F(U,Y+1,3);if(Y+=3,Bt)if(Bt==1)ue=R,Le=S,Ee=9,Re=5;else if(Bt==2){var Et=F(U,Y,31)+257,tA=F(U,Y+10,15)+4,AA=Et+F(U,Y+5,31)+1;Y+=14;for(var Je=new t(AA),Qt=new t(19),Fe=0;Fe>4;if(_e<16)Je[Fe++]=_e;else{var It=0,dt=0;for(_e==16?(dt=3+F(U,Y,3),Y+=2,It=Je[Fe-1]):_e==17?(dt=3+F(U,Y,7),Y+=3):_e==18&&(dt=11+F(U,Y,127),Y+=7);dt--;)Je[Fe++]=It}}var Rt=Je.subarray(0,Et),Ke=Je.subarray(Et);Ee=w(Rt),Re=w(Ke),ue=E(Rt,Ee,1),Le=E(Ke,Re,1)}else J(1);else{var _e=k(Y)+4,ut=U[_e-4]|U[_e-3]<<8,tt=_e+ut;if(tt>L){V&&J(0);break}W&&ee(re+ut),Q.set(U.subarray(_e,tt),re),T.b=re+=ut,T.p=Y=tt*8,T.f=Ae;continue}if(Y>Oe){V&&J(0);break}}W&&ee(re+131072);for(var v=(1<>4;if(Y+=It&15,Y>Oe){V&&J(0);break}if(It||J(2),_<256)Q[re++]=_;else if(_==256){P=Y,ue=null;break}else{var ie=_-254;if(_>264){var Fe=_-257,ce=s[Fe];ie=F(U,Y,(1<>4;fe||J(3),Y+=fe&15;var Ke=C[j];if(j>3){var ce=a[j];Ke+=H(U,Y)&(1<Oe){V&&J(0);break}W&&ee(re+131072);var Te=re+ie;if(reh.length+I,0);a&&(r+=4,n="LIST");let i;s?(i=new te(8),xA(i,r)):(i=new te(4),ge(i,r));let o=[et(n),i];return a&&o.push(et(e)),o.push(...A),r%2!==0&&o.push(new Uint8Array(1)),o}static writeParts(e,A,s=!1,a=!1){let n=s?12:8,r=e,i=A.reduce((C,B)=>B.length+C,0),o=i;a&&(n+=4,o+=4,r="LIST");let I=n+i;I%2!==0&&I++;let h=new te(I);Ne(h,r),s?xA(h,o):ge(h,o),a&&Ne(h,e);for(let C of A)h.set(C,n),n+=C.length;return h}static findListType(e,A){return e.find(s=>s.header!=="LIST"?!1:(s.data.currentIndex=4,We(s.data,4)===A))}};function $t(t,e){return{...e,...t}}var l=class $A{static infoEnabled=!1;static warnEnabled=!0;static groupEnabled=!1;static setLogLevel(e,A,s){this.infoEnabled=e,this.warnEnabled=A,this.groupEnabled=s}static info(...e){this.infoEnabled&&console.info(...e)}static warn(...e){this.warnEnabled&&console.warn(...e)}static group(...e){this.groupEnabled&&console.group(...e)}static groupCollapsed(...e){this.groupEnabled&&console.groupCollapsed(...e)}static groupEnd(){this.groupEnabled&&console.groupEnd()}static unsupported(e,A,s=""){this.infoEnabled&&this.info(`%cUnsupported %c${e}%c message: %c${en(A)}%c. ${s}`,d.warn,d.recognized,d.warn,d.unrecognized,d.warn)}static gmInfo(e,A,s=""){this.infoEnabled&&this.coolInfo(`General MIDI ${e}`,A,s)}static gmFail(e,A){this.infoEnabled&&this.unsupported(`General MIDI ${e}`,A)}static gsInfo(e,A,s=""){this.infoEnabled&&this.coolInfo(`Roland GS ${e}`,A,s)}static gsFail(e,A,s=""){this.infoEnabled&&this.unsupported(`Roland GS ${e}`,A,s)}static xgInfo(e,A,s=""){this.infoEnabled&&this.coolInfo(`Yamaha XG ${e}`,A,s)}static xgFail(e,A,s=""){this.infoEnabled&&this.unsupported(`Yamaha XG ${e}`,A,s)}static coolInfo(e,A,s=""){this.infoEnabled&&(s?$A.info(`%c${e}%c is now set to %c${A}%c ${s}.`,d.recognized,d.info,d.value,d.info):$A.info(`%c${e}%c is now set to %c${A}%c.`,d.recognized,d.info,d.value,d.info))}},nn={ConsoleColors:d,readBigEndian:Ht,readLittleEndian:hs,readLittleEndianIndexed:X,readBinaryString:We,readBinaryStringIndexed:de,readVariableLengthQuantity:pe,inflateSync:An},G={noteOff:128,noteOn:144,polyPressure:160,controllerChange:176,programChange:192,channelPressure:208,pitchWheel:224,systemExclusive:240,timecode:241,songPosition:242,songSelect:243,tuneRequest:246,clock:248,start:250,continue:251,stop:252,activeSensing:254,reset:255,sequenceNumber:0,text:1,copyright:2,trackName:3,instrumentName:4,lyric:5,marker:6,cuePoint:7,programName:8,midiChannelPrefix:32,midiPort:33,endOfTrack:47,setTempo:81,smpteOffset:84,timeSignature:88,keySignature:89,sequenceSpecific:127},f={bankSelect:0,modulationWheel:1,breathController:2,undefinedCC3:3,footController:4,portamentoTime:5,dataEntryMSB:6,mainVolume:7,balance:8,undefinedCC9:9,pan:10,expression:11,effectControl1:12,effectControl2:13,undefinedCC14:14,undefinedCC15:15,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,undefinedCC20:20,undefinedCC21:21,undefinedCC22:22,undefinedCC23:23,undefinedCC24:24,undefinedCC25:25,undefinedCC26:26,undefinedCC27:27,undefinedCC28:28,undefinedCC29:29,undefinedCC30:30,undefinedCC31:31,bankSelectLSB:32,modulationWheelLSB:33,breathControllerLSB:34,undefinedCC3LSB:35,footControllerLSB:36,portamentoTimeLSB:37,dataEntryLSB:38,mainVolumeLSB:39,balanceLSB:40,undefinedCC9LSB:41,panLSB:42,expressionLSB:43,effectControl1LSB:44,effectControl2LSB:45,undefinedCC14LSB:46,undefinedCC15LSB:47,undefinedCC16LSB:48,undefinedCC17LSB:49,undefinedCC18LSB:50,undefinedCC19LSB:51,undefinedCC20LSB:52,undefinedCC21LSB:53,undefinedCC22LSB:54,undefinedCC23LSB:55,undefinedCC24LSB:56,undefinedCC25LSB:57,undefinedCC26LSB:58,undefinedCC27LSB:59,undefinedCC28LSB:60,undefinedCC29LSB:61,undefinedCC30LSB:62,undefinedCC31LSB:63,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,filterResonance:71,releaseTime:72,attackTime:73,brightness:74,decayTime:75,vibratoRate:76,vibratoDepth:77,vibratoDelay:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,undefinedCC85:85,undefinedCC86:86,undefinedCC87:87,undefinedCC88:88,undefinedCC89:89,undefinedCC90:90,reverbDepth:91,tremoloDepth:92,chorusDepth:93,variationDepth:94,phaserDepth:95,dataIncrement:96,dataDecrement:97,nonRegisteredParameterLSB:98,nonRegisteredParameterMSB:99,registeredParameterLSB:100,registeredParameterMSB:101,undefinedCC102LSB:102,undefinedCC103LSB:103,undefinedCC104LSB:104,undefinedCC105LSB:105,undefinedCC106LSB:106,undefinedCC107LSB:107,undefinedCC108LSB:108,undefinedCC109LSB:109,undefinedCC110LSB:110,undefinedCC111LSB:111,undefinedCC112LSB:112,undefinedCC113LSB:113,undefinedCC114LSB:114,undefinedCC115LSB:115,undefinedCC116LSB:116,undefinedCC117LSB:117,undefinedCC118LSB:118,undefinedCC119LSB:119,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127},Ze={pitchWheelRange:0,fineTuning:1,coarseTuning:2,modulationDepth:5,resetParameters:16383},ke={partParameter:1,drumPitch:24,drumPitchFine:25,drumLevel:26,drumPan:28,drumReverb:29,drumChorus:30,drumDelay:31,awe32:127,SF2:120},Ue={vibratoRate:8,vibratoDepth:9,vibratoDelay:10,tvfCutoffFrequency:32,tvfResonance:33,envelopeAttackTime:99,envelopeDecayTime:100,envelopeReleaseTime:102},Qe=class it{ticks;statusByte;data;constructor(e,A,s){this.ticks=e,this.statusByte=A,this.data=s}static pitchWheel(e,A,s){return new it(e,G.pitchWheel|A%16,new Uint8Array([s&127,s>>7&127]))}static channelPressure(e,A,s){return new it(e,G.channelPressure|A%16,new Uint8Array([s]))}static programChange(e,A,s){return new it(e,G.programChange|A%16,new Uint8Array([s]))}static controllerChange(e,A,s,a){return new it(e,G.controllerChange|A%16,new Uint8Array([s,a]))}static systemExclusive(e,A){return new it(e,G.systemExclusive,new Uint8Array(A))}static registeredParameter(e,A,s,a){if(s>16383||s<0||a>16383||a<0)throw new Error("Parameter and value must be between 0 and 16383.");return[it.controllerChange(e,A,f.registeredParameterMSB,s>>7),it.controllerChange(e,A,f.registeredParameterLSB,s&127),it.controllerChange(e,A,f.dataEntryMSB,a>>7),it.controllerChange(e,A,f.dataEntryLSB,a&127)]}},Ms=(t,e)=>{for(let A=0;A3||A.length<2)throw new Error(`Invalid MIDI string: ${e}`);return e.startsWith("DRUM")?{bankMSB:0,bankLSB:0,program:Number.parseInt(A[1]),isGMGSDrum:!0}:{bankLSB:Number.parseInt(A[0]),bankMSB:Number.parseInt(A[1]),program:Number.parseInt(A[2]),isGMGSDrum:!1}}static toFullMIDIString(e){return`${this.toMIDIString(e)} ${e.isDrum?"D":"M"} ${e.name}`}static fromFullMIDIString(e){let A=e.indexOf(" "),s=e.indexOf(" ",A+1);if(A===-1||s===-1)throw new Error(`Invalid named MIDI string: ${e}`);let a=e.slice(0,Math.max(0,A)),n=e.slice(A+1,s),r=e.slice(Math.max(0,s+1));return{...jA.fromMIDIString(a),isDrum:n==="D",name:r}}static matches(e,A){return e.isGMGSDrum||A.isGMGSDrum?e.isGMGSDrum===A.isGMGSDrum&&e.program===A.program:e.program===A.program&&e.bankLSB===A.bankLSB&&e.bankMSB===A.bankMSB}static compare(e,A){return e.isGMGSDrum&&!A.isGMGSDrum?1:!e.isGMGSDrum&&A.isGMGSDrum?-1:e.program!==A.program?e.program-A.program:e.bankMSB!==A.bankMSB?e.bankMSB-A.bankMSB:e.bankLSB-A.bankLSB}static isXGDrum(e){return e.isDrum&&!e.isGMGSDrum}static selectPatch(e,A,s){if(e.length===0)throw new Error("No presets!");A.isGMGSDrum&&De.isSystemXG(s)&&(A={...A,isGMGSDrum:!1,bankLSB:0,bankMSB:De.getDrumBank(s)});let{isGMGSDrum:a,bankLSB:n,bankMSB:r,program:i}=A,o=De.isSystemXG(s),I=De.isXGDrum(r)&&o,h=e.find(g=>this.matches(g,A));if(h&&(!I||I&&this.isXGDrum(h)))return h;let C=g=>{l.info(`%cPreset %c${jA.toMIDIString(A)}%c not found. (${s}) Replaced with %c${this.toFullMIDIString(g)}`,d.warn,d.unrecognized,d.warn,d.value)};if(a){let g=e.find(E=>E.isGMGSDrum&&E.program===i);return g||(g=e.find(E=>E.isDrum&&E.program===i),g)?(C(g),g):(g=this.getAnyDrums(e,!1),C(g),g)}if(I){let g=e.find(E=>E.program===i&&E.isDrum&&!E.isGMGSDrum);return g||(g=e.find(E=>E.isDrum&&E.program===i),g&&g.program<49)?(C(g),g):(g=this.getAnyDrums(e,!0),C(g),g)}let B=e.filter(g=>g.program===i&&!g.isDrum);if(B.length===0)return C(e[0]),e[0];if(h=o?B.find(g=>g.bankLSB===n):B.find(g=>g.bankMSB===r),h)return C(h),h;if(n!==64||!o){let g=Math.max(r,n);if(h=B.find(E=>E.bankLSB===g||E.bankMSB===g),h)return C(h),h}return C(B[0]),B[0]}static getAnyDrums(e,A){let s=A?e.find(a=>this.isXGDrum(a)):e.find(a=>a.isGMGSDrum);return s||(e.find(a=>a.isDrum)??e[0])}},me=Object.freeze({type:"Other"}),ne=class le{static analyzeSysEx(e){if(e.length<3)return me;switch(e[0]){default:return me;case 126:case 127:return this.analyzeGM(e);case 65:return this.analyzeGS(e);case 67:return this.analyzeXG(e)}}static analyzeRPN(e,A,s){switch(A){default:return me;case Ze.pitchWheelRange:return{type:"Channel MIDI Param",channel:e,parameter:"pitchWheelRange",value:s/128};case Ze.fineTuning:return{type:"Channel MIDI Param",channel:e,parameter:"fineTune",value:(s-8192)/81.92};case Ze.coarseTuning:return{type:"Channel MIDI Param",channel:e,parameter:"keyShift",value:(s>>7)-64};case Ze.modulationDepth:return{type:"Channel MIDI Param",channel:e,parameter:"modulationDepth",value:s/1.28}}}static analyzeNRPN(e,A,s){let a=A>>7,n=A&127;switch(a){default:return me;case ke.partParameter:switch(n){default:return me;case Ue.vibratoRate:return{type:"Controller Change",channel:e,controller:f.vibratoRate,value:s>>7};case Ue.vibratoDepth:return{type:"Controller Change",channel:e,controller:f.vibratoDepth,value:s>>7};case Ue.vibratoDelay:return{type:"Controller Change",channel:e,controller:f.vibratoDelay,value:s>>7};case Ue.tvfCutoffFrequency:return{type:"Controller Change",channel:e,controller:f.brightness,value:s>>7};case Ue.tvfResonance:return{type:"Controller Change",channel:e,controller:f.filterResonance,value:s>>7};case Ue.envelopeAttackTime:return{type:"Controller Change",channel:e,controller:f.attackTime,value:s>>7};case Ue.envelopeDecayTime:return{type:"Controller Change",channel:e,controller:f.decayTime,value:s>>7};case Ue.envelopeReleaseTime:return{type:"Controller Change",channel:e,controller:f.releaseTime,value:s>>7}}case ke.drumPitch:case ke.drumPitchFine:case ke.drumLevel:case ke.drumPan:case ke.drumReverb:case ke.drumChorus:case ke.drumDelay:return{type:"Drum Setup"}}}static setGlobalMIDIParameter(e,A,s,a){switch(s){case"system":return[le.reset(e,a)];case"keyShift":switch(A){default:return[le.deviceControlMessage(e,4,[0,a+64])];case"xg":return[le.xgMessage(e,0,0,6,[a+64])];case"gs":return[le.gsMessage(e,64,0,5,[a+64])]}case"fineTune":switch(A){default:{let n=Math.floor(a*81.92+8192);return[le.deviceControlMessage(e,3,[n&127,n>>7&127])]}case"xg":{let n=Math.floor(a*10+1024);return[le.xgMessage(e,0,0,0,[n>>12&15,n>>8&15,n>>4&15,n&15])]}case"gs":{let n=Math.floor(a*10+1024);return[le.gsMessage(e,64,0,0,[n>>12&15,n>>8&15,n>>4&15,n&15])]}}case"volume":switch(A){default:{let n=Math.floor(a*16383);return[le.deviceControlMessage(e,1,[n&127,n>>7&127])]}case"xg":{let n=Math.floor(a*127);return[le.xgMessage(e,0,0,4,[n])]}case"gs":{let n=Math.floor(a*127);return[le.gsMessage(e,64,0,4,[n])]}}case"pan":if(A==="gs"){let n=Math.floor(a*63)+64;return[le.gsMessage(e,64,0,6,[n])]}else{let n=Math.floor(a*8192)+8192;return[le.deviceControlMessage(e,2,[n&127,n>>7&127])]}}}static setChannelMIDIParameter(e,A,s,a,n){A%=16;let r=le.channelToSyx(A);switch(a){case"pressure":return[Qe.channelPressure(e,A,n)];case"pitchWheel":return[Qe.pitchWheel(e,A,n)];case"pitchWheelRange":return Qe.registeredParameter(e,A,Ze.pitchWheelRange,Math.floor(n*128));case"modulationDepth":return Qe.registeredParameter(e,A,Ze.modulationDepth,Math.floor(n*1.28));case"rxChannel":return s==="xg"?[le.xgMessage(e,8,A,4,[n])]:[le.gsMessage(e,64,16|r,2,[n])];case"polyMode":return n?[Qe.controllerChange(e,A,f.polyModeOn,0)]:[Qe.controllerChange(e,A,f.monoModeOn,0)];case"keyShift":return Qe.registeredParameter(e,A,Ze.coarseTuning,n+64<<7);case"fineTune":return Qe.registeredParameter(e,A,Ze.fineTuning,Math.floor(n*81.92+8192));case"randomPan":return s==="xg"?[le.xgMessage(e,8,A,14,[0])]:[le.gsMessage(e,64,16|r,28,[0])];case"assignMode":switch(s){default:case"gs":return[le.gsMessage(e,64,16|r,20,[n])];case"xg":return[le.xgMessage(e,8,A,6,[n])]}case"efxAssign":return[le.gsMessage(e,64,16|r,34,[n])];case"cc1":return[le.gsMessage(e,64,16|r,31,[n])];case"cc2":return[le.gsMessage(e,64,16|r,32,[n])];case"drumMap":return[le.gsMessage(e,64,16|r,21,[n])];case"velocitySenseDepth":return s==="xg"?[le.xgMessage(e,8,A,12,[n])]:[le.gsMessage(e,64,16|r,26,[n])];case"velocitySenseOffset":return s==="xg"?[le.xgMessage(e,8,A,13,[n])]:[le.gsMessage(e,64,16|r,27,[n])]}}static syxToChannel(e){return[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][e%16]}static channelToSyx(e){return[1,2,3,4,5,6,7,8,9,0,10,11,12,13,14,15][e%16]}static gs(e,A,s,a){let n=128-(e+A+s+a.reduce((r,i)=>r+i,0))%128&127;return[65,16,66,18,e,A,s,...a,n,247]}static gsMessage(e,A,s,a,n){return Qe.systemExclusive(e,this.gs(A,s,a,n))}static xg(e,A,s,a){return[67,16,76,e,A,s,...a,247]}static xgMessage(e,A,s,a,n){return Qe.systemExclusive(e,this.xg(A,s,a,n))}static deviceControl(e,A){return[127,127,4,e,...A,247]}static deviceControlMessage(e,A,s){return Qe.systemExclusive(e,this.deviceControl(A,s))}static reset(e,A){switch(A){case"gs":return this.gsMessage(e,64,0,127,[0]);case"xg":return this.xgMessage(e,0,0,126,[0]);case"gm":return Qe.systemExclusive(e,[126,127,9,1,127]);case"gm2":return Qe.systemExclusive(e,[126,127,9,3,127])}}static analyzeGM(e){if(e.length<4)return me;if(e[2]===4)switch(e[3]){default:return me;case 1:{let A=(e[5]<<7|e[4])/16383;return{type:"Global MIDI Param",parameter:"volume",value:Math.pow(A,2)}}case 2:return{type:"Global MIDI Param",parameter:"pan",value:((e[5]<<7|e[4])-8192)/8192};case 3:return{type:"Global MIDI Param",parameter:"fineTune",value:((e[5]<<7|e[4])-8192)/81.92};case 4:return{type:"Global MIDI Param",parameter:"keyShift",value:e[5]-64};case 5:if(e[4]!==1||e[5]!==1||e[6]!==1||e[7]!==1)return me;switch(e[8]){default:return me;case 1:switch(e[9]){default:return me;case 0:case 1:return{type:"Reverb Param"}}case 2:switch(e[9]){default:return me;case 0:case 1:case 2:case 3:case 4:return{type:"Chorus Param"}}}}if(e[2]!==9)return me;switch(e[3]){default:return me;case 1:return{type:"Global MIDI Param",parameter:"system",value:"gm"};case 2:return{type:"Global MIDI Param",parameter:"system",value:"gm"};case 3:return{type:"Global MIDI Param",parameter:"system",value:"gm2"}}}static analyzeXG(e){if(e[2]!==76||e.length<7)return me;let A=e[3],s=e[4],a=e[5],n=e[6];if(A===6||A===7)return{type:"Display Data"};if(A===0&&s===0)switch(a){default:return me;case 0:return{type:"Global MIDI Param",parameter:"fineTune",value:(((e[6]&15)<<12|(e[7]&15)<<8|(e[8]&15)<<4|e[9]&15)-1024)/10};case 6:return{type:"Global MIDI Param",parameter:"keyShift",value:n-64};case 126:case 127:return{type:"Global MIDI Param",parameter:"system",value:"xg"}}if(A===2&&s===1)return a<=21?{type:"Reverb Param"}:a<=53?{type:"Chorus Param"}:{type:"Variation Param"};if(A===3&&s===0)return{type:"Variation Param"};if(A===8){let r=s;switch(a){default:return me;case 1:return{type:"Controller Change",channel:r,controller:f.bankSelect,value:n};case 2:return{type:"Controller Change",channel:r,controller:f.bankSelectLSB,value:n};case 3:return{type:"Program Change",channel:r,value:n};case 5:return{type:"Controller Change",channel:r,controller:n===1?f.polyModeOn:f.monoModeOn,value:0};case 6:return{type:"Channel MIDI Param",channel:r,parameter:"assignMode",value:n};case 7:return{type:"Drums On",channel:r,isDrum:n>0};case 8:return{type:"Channel MIDI Param",channel:r,parameter:"keyShift",value:n-64};case 11:return{type:"Controller Change",channel:r,controller:f.mainVolume,value:n};case 14:return{type:"Controller Change",channel:r,controller:f.pan,value:n};case 18:return{type:"Controller Change",channel:r,controller:f.chorusDepth,value:n};case 19:return{type:"Controller Change",channel:r,controller:f.reverbDepth,value:n};case 21:return{type:"Controller Change",channel:r,controller:f.vibratoRate,value:n};case 22:return{type:"Controller Change",channel:r,controller:f.vibratoDepth,value:n};case 23:return{type:"Controller Change",channel:r,controller:f.vibratoDelay,value:n};case 24:return{type:"Controller Change",channel:r,controller:f.brightness,value:n};case 25:return{type:"Controller Change",channel:r,controller:f.filterResonance,value:n};case 26:return{type:"Controller Change",channel:r,controller:f.attackTime,value:n};case 27:return{type:"Controller Change",channel:r,controller:f.decayTime,value:n};case 12:return{type:"Controller Change",channel:r,controller:f.releaseTime,value:n}}}return A>>4===3?{type:"Drum Setup"}:me}static analyzeGS(e){if(e.length<10||e[3]!==18)return me;if(e[2]===69)return{type:"Display Data"};if(e[2]!==66)return me;let A=e[4],s=e[5],a=e[6],n=e[7];if((A===0||A===64)&&s===0)switch(a){case 0:return{type:"Global MIDI Param",parameter:"fineTune",value:((n<<12|e[8]<<8|e[9]<<4|e[10])-1024)/10};case 4:return{type:"Global MIDI Param",parameter:"volume",value:n/127};case 5:return{type:"Global MIDI Param",parameter:"keyShift",value:n-64};case 6:return{type:"Global MIDI Param",parameter:"pan",value:(n-64)/63};case 127:switch(n){case 0:case 1:return{type:"Global MIDI Param",parameter:"system",value:"gs"};case 127:return{type:"Global MIDI Param",parameter:"system",value:"gm"}}return me}if(A===65)return{type:"Drum Setup"};if(A!==64&&A!==80)return me;let r=A===80?16:0;if(s===1){if(a>=48&&a<=55)return{type:"Reverb Param"};if(a>=56&&a<=64)return{type:"Chorus Param"};if(a>=80&&a<=90)return{type:"Delay Param"}}if(s===3&&a>=0&&a<=127)return{type:"Insertion Param"};if(s>>4===1){let i=le.syxToChannel(s&15)+r;switch(a){default:return me;case 0:return{type:"Program Change",channel:i,value:n};case 19:return{type:"Channel MIDI Param",channel:i,parameter:"polyMode",value:n===1};case 20:return{type:"Channel MIDI Param",channel:i,parameter:"assignMode",value:n};case 21:return{type:"Drums On",channel:i,isDrum:n>0};case 22:return{type:"Channel MIDI Param",channel:i,parameter:"keyShift",value:n-64};case 25:return{type:"Controller Change",channel:i,controller:f.mainVolume,value:n};case 26:return{type:"Channel MIDI Param",channel:i,parameter:"velocitySenseDepth",value:n};case 27:return{type:"Channel MIDI Param",channel:i,parameter:"velocitySenseOffset",value:n};case 28:return{type:"Controller Change",channel:i,controller:f.pan,value:n};case 31:return{type:"Channel MIDI Param",channel:i,parameter:"cc1",value:n};case 32:return{type:"Channel MIDI Param",channel:i,parameter:"cc2",value:n};case 33:return{type:"Controller Change",channel:i,controller:f.chorusDepth,value:n};case 34:return{type:"Controller Change",channel:i,controller:f.reverbDepth,value:n};case 42:return{type:"Channel MIDI Param",channel:i,parameter:"fineTune",value:((n<<7|e[8])-8192)/81.92};case 44:return{type:"Controller Change",channel:i,controller:f.variationDepth,value:n};case 48:return{type:"Controller Change",channel:i,controller:f.vibratoRate,value:n};case 49:return{type:"Controller Change",channel:i,controller:f.vibratoDepth,value:n};case 50:return{type:"Controller Change",channel:i,controller:f.brightness,value:n};case 51:return{type:"Controller Change",channel:i,controller:f.filterResonance,value:n};case 52:return{type:"Controller Change",channel:i,controller:f.attackTime,value:n};case 53:return{type:"Controller Change",channel:i,controller:f.decayTime,value:n};case 54:return{type:"Controller Change",channel:i,controller:f.releaseTime,value:n};case 55:return{type:"Controller Change",channel:i,controller:f.vibratoDelay,value:n}}}if(s>>4===4){let i=le.syxToChannel(s&15)+r;switch(a){default:return me;case 0:case 1:return{type:"Controller Change",channel:i,controller:f.bankSelectLSB,value:n};case 34:return{type:"Channel MIDI Param",channel:i,parameter:"efxAssign",value:n===1}}}return me}},Aa="Created using SpessaSynth";function sa(t,e,A){let s="gm",a=[],n=new Array(t.tracks.length).fill(0),r=16+Math.max(...t.portChannelOffsetMap),i=[];for(let o=0;o{let C=t.portChannelOffsetMap[n[I]];if(o.statusByte===G.midiPort){n[I]=o.data[0];return}let B=o.statusByte&240;if(B!==G.controllerChange&&B!==G.programChange&&B!==G.systemExclusive)return;if(B===G.systemExclusive){let y=ne.analyzeSysEx(o.data);switch(y.type){default:return;case"Drums On":{let D=y.channel+C;if(!i[D])return;i[D].isDrum=y.isDrum;return}case"Global MIDI Param":y.parameter==="system"&&(s=y.value,y.value==="gm"&&a.push({tNum:I,e:o}));break;case"Controller Change":{let D=t.tracks[I];if(y.channel>=16)return;let R=Qe.controllerChange(o.ticks,y.channel,y.controller,y.value);D.events[h[I]]=R,o=R,l.info("%cReplaced a system exclusive with controller change!",d.info);break}case"Program Change":{if(y.channel>=16)return;let D=t.tracks[I],R=Qe.programChange(o.ticks,y.channel,y.value);D.events[h[I]]=R,o=R,l.info("%cReplaced a system exclusive with program change!",d.info);break}}}let g=(o.statusByte&15)+C,E=i[g];if(B===G.programChange){let y={program:o.data[0],bankLSB:E.lastBankLSB?.data?.[1]??0,bankMSB:De.subtractBankOffset(E.lastBank?.data?.[1]??0,t.bankOffset,s==="xg"),isGMGSDrum:E.isDrum},D=A.getPreset(y,s);if(l.info(`%cInput patch: %c${je.toMIDIString(y)}%c. Channel %c${g}%c. Changing patch to ${D.toString()}.`,d.info,d.unrecognized,d.info,d.recognized,d.info),o.data[0]=D.program,D.isGMGSDrum&&De.isSystemXG(s)||E.lastBank===void 0||(E.lastBank.data[1]=De.addBankOffset(D.bankMSB,e,s==="xg"),E.lastBankLSB===void 0))return;E.lastBankLSB.data[1]=D.bankLSB;return}let p=o.data[0]===f.bankSelectLSB;o.data[0]!==f.bankSelect&&!p||(E.hasBankSelect=!0,p?E.lastBankLSB=o:E.lastBank=o)});for(let o=0;oS.port===g&&S.channels.has(h));if(E===void 0)continue;let p=E.events.findIndex(S=>S.statusByte===C);if(p===-1){let S=E.events.findIndex(H=>H.statusByte>128&&H.statusByte<240&&(H.statusByte&15)===h);if(S===-1)continue;let w=E.events[S].ticks,F=A.getPreset({bankMSB:0,bankLSB:0,program:0,isGMGSDrum:!1},s).program;E.addEvents(S,Qe.programChange(w,h,F)),p=S}l.info(`%cAdding bank select for %c${o}`,d.info,d.recognized);let y=E.events[p].ticks,D=A.getPreset({bankLSB:0,bankMSB:0,program:I.program,isGMGSDrum:I.isDrum},s),R=De.addBankOffset(D.bankMSB,e,s==="xg");E.addEvents(p,Qe.controllerChange(y,h,f.bankSelect,R))}if(s==="gm"&&!De.isSystemXG(s)){for(let I of a){let h=t.tracks[I.tNum];h.deleteEvent(h.events.indexOf(I.e))}let o=0;t.tracks[0].events[0].statusByte===G.trackName&&o++,t.tracks[0].addEvents(o,ne.reset(0,"gs"))}t.flush()}var Rs={bankOffset:0,metadata:{},correctBankOffset:!0,soundBank:void 0};function na(t,e,A){let s=A.metadata;if(l.group("%cWriting the RMIDI File...",d.info),l.info("metadata",s),l.info("Initial bank offset",t.bankOffset),A.correctBankOffset){if(!A.soundBank)throw new Error("Sound bank must be provided if correcting bank offset.");sa(t,A.bankOffset,A.soundBank)}let a=new te(t.writeMIDI());s.name??=t.getName(),s.creationDate??=new Date,s.copyright??=Aa,s.software??="SpessaSynth",Object.entries(s).forEach(o=>{let I=o;I[1]&&t.setRMIDInfo(I[0],I[1])});let n=[],r=(o,I)=>{n.push(x.write(o,I))};for(let o of Object.entries(t.rmidiInfo)){let I=o[0],h=o[1];switch(I){case"album":r("IALB",h),r("IPRD",h);break;case"software":r("ISFT",h);break;case"infoEncoding":r("IENC",h);break;case"creationDate":r("ICRD",h);break;case"picture":r("IPIC",h);break;case"name":r("INAM",h);break;case"artist":r("IART",h);break;case"genre":r("IGNR",h);break;case"copyright":r("ICOP",h);break;case"comment":r("ICMT",h);break;case"engineer":r("IENG",h);break;case"subject":r("ISBJ",h);break;case"midiEncoding":r("MENC",h);break}}let i=new te(2);return ls(i,A.bankOffset,2),n.push(x.write("DBNK",i)),l.info("%cFinished!",d.info),l.groupEnd(),x.writeParts("RIFF",[et("RMID"),x.write("data",a),x.writeParts("INFO",n,!1,!0),new te(e)]).buffer}var mA=class{rpnMSB={v:127,track:0,event:0};rpnLSB={v:127,track:0,event:0};nrpnMSB={v:0,track:0,event:0};nrpnLSB={v:0,track:0,event:0};dataMSB={v:0,track:0,event:0};dataLSB={v:0,track:0,event:0};channel;isRegistered=!0;constructor(t){this.channel=t}get paramMSB(){return this.isRegistered?this.rpnMSB:this.nrpnMSB}get paramLSB(){return this.isRegistered?this.rpnLSB:this.nrpnLSB}reset(){this.isRegistered=!0,this.rpnLSB.v=127,this.rpnMSB.v=127,this.nrpnMSB.v=0,this.nrpnLSB.v=0,this.resetData()}controllerChange(t,e,A,s){switch(t){case f.registeredParameterMSB:this.resetData(),this.isRegistered=!0,this.rpnMSB={v:e,track:A,event:s};break;case f.registeredParameterLSB:this.resetData(),this.isRegistered=!0,this.rpnLSB={v:e,track:A,event:s};break;case f.nonRegisteredParameterMSB:this.resetData(),this.isRegistered=!1,this.nrpnMSB={v:e,track:A,event:s};break;case f.nonRegisteredParameterLSB:this.resetData(),this.isRegistered=!1,this.nrpnLSB={v:e,track:A,event:s};break;case f.dataEntryMSB:return this.dataMSB={v:e,track:A,event:s},this.analyze();case f.dataEntryLSB:return this.dataLSB={v:e,track:A,event:s},this.analyze()}}resetData(){this.dataLSB.v=0,this.dataMSB.v=0}analyze(){let t=this.dataMSB.v<<7|this.dataLSB.v;return this.isRegistered?ne.analyzeRPN(this.channel,this.rpnMSB.v<<7|this.rpnLSB.v,t):ne.analyzeNRPN(this.channel,this.nrpnMSB.v<<7|this.nrpnLSB.v,t)}};function aa(t,e){l.groupCollapsed("%cSearching for all used programs and keys...",d.info);let A=16+Math.max(...t.portChannelOffsetMap),s=[],a="gs",n=0,r=B=>{a=B,n=0;for(let g=0;gB.port),I=t.portChannelOffsetMap,{timeline:h,tracks:C}=t;for(let B of h){let g=B.tr,E=B.ev,p=C[g].events[E];if(p.statusByte===G.midiPort&&t.tracks[g].channels.size>0){let R=p.data[0];I[R]===void 0&&(l.warn(`Invalid port ${R} on track ${g}. (No offset found in the MIDI map.`),R=0),o[g]=R;continue}let y=p.statusByte&240;if(y!==G.noteOn&&y!==G.controllerChange&&y!==G.programChange&&y!==G.systemExclusive)continue;let D=I[o[g]]||0;switch(y){case G.programChange:{let R=s[(p.statusByte&15)+D];R.preset=e.getPreset({bankMSB:R.bankMSB,bankLSB:R.bankLSB,program:p.data[0],isGMGSDrum:R.isDrum},a);break}case G.controllerChange:{let R=s[(p.statusByte&15)+D],S=p.data[0],w=p.data[1];switch(S){case f.registeredParameterMSB:case f.registeredParameterLSB:case f.nonRegisteredParameterLSB:case f.nonRegisteredParameterMSB:R.param.controllerChange(S,w,g,E);break;case f.dataEntryMSB:case f.dataEntryLSB:{let F=R.param.controllerChange(S,w,g,E);F?.type==="Channel MIDI Param"&&F.parameter==="keyShift"&&(R.keyShift=R.isDrum?0:F.value);break}case f.resetAllControllers:R.param.reset();break;case f.bankSelect:R.bankMSB=w;break;case f.bankSelectLSB:R.bankLSB=w;break}break}case G.noteOn:{let R=s[(p.statusByte&15)+D];if(p.data[1]===0||!R.preset)continue;let S=i.get(R.preset);S||(S=new Map,i.set(R.preset,S));let w=p.data[0]+(R.isDrum?0:n)+R.keyShift,F=S.get(w);F||(F=new Set,S.set(w,F)),F.add(p.data[1]);break}case G.systemExclusive:{let R=ne.analyzeSysEx(p.data);switch(R.type){default:break;case"Global MIDI Param":R.parameter==="keyShift"?n=R.value:R.parameter==="system"&&(r(R.value),l.info(`%c${R.value.toUpperCase()} on detected!`,d.recognized));break;case"Channel MIDI Param":if(R.parameter==="keyShift"){let S=s[R.channel];if(!S)break;S.keyShift=S.isDrum?0:R.value}break;case"Drums On":{let S=R.channel+D;if(!s[S])break;s[S].isDrum=R.isDrum;break}case"Program Change":{let S=s[R.channel+D];if(!S)break;S.preset=e.getPreset({bankMSB:S.bankMSB,bankLSB:S.bankLSB,program:R.value,isGMGSDrum:S.isDrum},a);break}case"Controller Change":{let S=s[R.channel+D];if(!S)break;R.controller===f.bankSelectLSB?S.bankLSB=R.value:R.controller===f.bankSelect&&(S.bankMSB=R.value)}}}}}for(let[B,g]of i.entries())g.size===0&&(l.info(`%cDetected change but no keys for %c${B.name}`,d.info,d.value),i.delete(B));return l.groupEnd(),i}var ra=t=>(t.data=new te(t.data.buffer),6e7/Ht(t.data,3));function ia(t,e=0){let A=[];for(let C=0;C<16;C++)A.push([]);let s=0,a=60/(120*t.timeDivision),n=0,r=0,i=[];for(let C=0;C<16;C++)i.push(new Map);let o=(C,B)=>{let g=i[B].get(C);if(g===void 0)return;let E=g.shift();if(E===void 0)return;let p=A[B][E],y=s-p.start;p.length=B===9?Math.max(y,e):y,r--},{timeline:I,tracks:h}=t;for(;n>4,E=B.statusByte&15;if(g===8)o(B.data[0],E);else if(g===9){let y=B.data[0],D=B.data[1];if(D===0)o(y,E);else{let R={midiNote:y,start:s,length:-1,velocity:D},S=A[E];S.push(R);let w=i[E];w.has(y)||w.set(y,[]),i[E].get(y)?.push(S.length-1),r++}}else B.statusByte===81&&(a=60/(ra(B)*t.timeDivision));if(++n>=I.length)break;let p=I[n];s+=a*(h[p.tr].events[p.ev].ticks-B.ticks)}if(r>0)for(let C=0;Ck.port),p={},y=0,D=(k,u)=>{t.tracks[k].channels.size!==0&&(y===0&&(y+=16,p[u]=0),p[u]===void 0&&(p[u]=y,y+=16),E[k]=u)};for(let[k,u]of t.tracks.entries())D(k,u.port);let R=y,S=[];for(let k=0;k{let J=t.tracks[u],O=m[u],q=()=>{J.deleteEvent(O),m[u]--},K=W=>{let V=S[W],ee=V.param,Ae=ee.paramMSB,Y=ee.paramLSB;l.info(`%cClearing Non/Registered Parameter on ${W}. Clear MSB: %c${V.clearedParams.pMSB}%c, clear LSB: %c${V.clearedParams.pLSB}%c, clear data: %c${V.clearedParams.data}.`,d.info,d.recognized,d.info,d.recognized,d.info,d.recognized),V.clearedParams.data||(q(),u===Ae.track&&O{J.addEvents(O,W),m[u]++},U=(...W)=>{for(let V=W.length-1;V>=0;V--)ae(W[V])},T=p[E[u]]||0;if(k.statusByte===G.midiPort){D(u,k.data[0]);return}if(k.statusByteG.systemExclusive)return;let Q=k.statusByte&240,b=k.statusByte&15,L=b+T;if(k.statusByte!==G.systemExclusive&&o.has(L)){q();return}let z=S[L],$=I.get(L);switch(Q){case G.noteOn:if(!$)break;if(z.isFirstNoteOn){if(z.isFirstNoteOn=!1,$.controllers)for(let[V,ee]of $.controllers)ee!=="clear"&&ae(Qe.controllerChange(k.ticks,b,V,ee));if($.midiParams?.fineTune!==void 0&&$.midiParams.fineTune!=="clear"){let V=z.fineTune+$.midiParams.fineTune;z.currentKeyShift=Math.trunc(V/100),$.midiParams.fineTune=V%100}else{let V=z.fineTune+z.currentFineTune;z.currentKeyShift=Math.trunc(V/100),$.midiParams??={},$.midiParams.fineTune=V%100}let W=$.patch;if(W&&W!=="clear"){l.info(`%cSetting %c${L}%c to %c${je.toMIDIString(W)}%c. Track num: %c${u}`,d.info,d.recognized,d.info,d.recognized,d.info,d.recognized);let V=W.bankMSB,ee=W.bankLSB,Ae=W.program;ae(Qe.programChange(k.ticks,b,Ae));let Y=(re,ue)=>{ae(Qe.controllerChange(k.ticks,b,re?f.bankSelectLSB:f.bankSelect,ue))};if(De.isSystemXG(h)&&W.isGMGSDrum&&(l.info(`%cAdding XG Drum change on track %c${u}`,d.recognized,d.value),V=De.getDrumBank(h),ee=0),Y(!1,V),Y(!0,ee),W.isGMGSDrum&&!De.isSystemXG(h)&&b!==9){l.info(`%cAdding GS Drum change on track %c${u}`,d.recognized,d.value);let re=16|ne.channelToSyx(b);ae(ne.gsMessage(k.ticks,40,re,21,[1]))}}if($.midiParams)for(let[V,ee]of Object.entries($.midiParams))ee!=="clear"&&U(...ne.setChannelMIDIParameter(k.ticks,b,h,V,ee))}k.data[0]+=z.keyShift+z.currentKeyShift;break;case G.noteOff:if(!$)break;k.data[0]+=z.keyShift+z.currentKeyShift;break;case G.programChange:if($?.patch){q();return}break;case G.pitchWheel:$?.midiParams?.pitchWheel&&q();break;case G.channelPressure:$?.midiParams?.pressure&&q();break;case G.controllerChange:{let W=k.data[0],V=k.data[1];if($?.controllers?.get(W)){q();return}switch(W){case f.bankSelect:case f.bankSelectLSB:$?.patch&&q();return;case f.registeredParameterLSB:case f.registeredParameterMSB:case f.nonRegisteredParameterMSB:case f.nonRegisteredParameterLSB:W===f.nonRegisteredParameterLSB||W===f.registeredParameterLSB?z.clearedParams.pLSB=!1:z.clearedParams.pMSB=!1,z.param.controllerChange(W,V,u,O);return;case f.dataEntryMSB:case f.dataEntryLSB:{z.clearedParams.data=!1;let ee=z.param.controllerChange(W,V,u,O);if(!ee)return;switch(ee.type){case"Drum Setup":i&&K(L);return;case"Controller Change":{let Ae=ee.controller,Y=ee.channel;if($?.controllers?.get(Ae)){K(Y);return}(Ae===f.bankSelect||Ae===f.bankSelectLSB)&&$?.patch&&K(Y);break}case"Channel MIDI Param":if(ee.parameter==="fineTune"&&z.fineTune){z.currentFineTune=ee.value;let Ae=z.fineTune+ee.value;z.currentKeyShift=Math.trunc(Ae/100);let Y=Ae%100;l.info(`%cFine tuning already present on ${L}%c (${ee.value})%c, new relative tune: %c${Ae}%c cents. Key shift: %c${z.currentKeyShift}%c semitones. Actual RPN value to set: %c${Y} cents.`,d.info,d.recognized,d.info,d.value,d.info,d.value,d.info,d.value);let re=Math.floor(Y*81.92)+8192;k.data[1]=W===f.dataEntryMSB?re>>7:re&127}else $?.midiParams?.[ee.parameter]&&K(L);break}z.clearedParams.pLSB=!0,z.clearedParams.pMSB=!0;return}default:return}}case G.systemExclusive:{let W=ne.analyzeSysEx(k.data);switch(W.type){default:return;case"Drum Setup":i&&q();return;case"Reverb Param":s&&q();return;case"Chorus Param":a&&q();return;case"Delay Param":n&&q();return;case"Insertion Param":r&&q();return;case"Program Change":I.get(W.channel+T)?.patch&&q();return;case"Global MIDI Param":if(e.midiParams?.[W.parameter]){q();return}if(W.parameter==="system")switch(W.value){case"xg":l.info("%cXG system on detected",d.info),h="xg",C=!0,B=u,g=O;for(let V of S)V.param.reset(),V.clearedParams={pLSB:!0,pMSB:!0,data:!0};return;case"gm2":l.info("%cGM2 system on detected",d.info),h="gm2",C=!0,B=u,g=O;for(let V of S)V.param.reset(),V.clearedParams={pLSB:!0,pMSB:!0,data:!0};return;case"gs":l.info("%cGS on detected!",d.recognized),C=!0,B=u,g=O;for(let V of S)V.param.reset(),V.clearedParams={pLSB:!0,pMSB:!0,data:!0};return;case"gm":l.info("%cGM on detected, removing!",d.info),q(),C=!1;return}break;case"Channel MIDI Param":{let V=I.get(W.channel+T);if(V?.midiParams?.[W.parameter]){q();return}if(W.parameter==="fineTune"){let ee=S[W.channel+T];if(ee&&ee.isFirstNoteOn&&V){let Ae=ee.fineTune+W.value;ee.currentKeyShift=Math.trunc(Ae/100),ee.fineTune=Ae%100,l.info(`%cFine tuning already present on ${W.channel+T}, new relative tune: %c${Ae} cents`,d.info,d.recognized),q()}break}break}case"Controller Change":{let V=W.controller,ee=I.get(W.channel+T);if(ee?.controllers?.get(V)!==void 0){q();return}(V===f.bankSelect||V===f.bankSelectLSB)&&ee?.patch&&q();return}}}}}),!C&&[...I.values()].some(k=>k.patch&&k.patch!=="clear")){let k=0;t.tracks[0].events[0].statusByte===G.trackName&&k++;let u=(e.midiParams?.system==="clear"?void 0:e.midiParams?.system)??"gs";t.tracks[0].addEvents(k,ne.reset(0,u)),B=0,g=k,h=u,l.info(`%c${u} reset on not detected. Adding it.`,d.info)}let w=Math.max(0,t.firstNoteOn),F=t.tracks[B],H=g+1;for(let k of Object.keys(e.midiParams??{})){if(k==="system")continue;let u=e.midiParams?.[k];!u||u==="clear"||F.addEvents(H,...ne.setGlobalMIDIParameter(w,h,k,u))}if(s&&s!=="clear"){let k=oa,u=s;F.addEvents(H,ne.gsMessage(w,64,1,k.level,[u.level]),ne.gsMessage(w,64,1,k.preLowpass,[u.preLowpass]),ne.gsMessage(w,64,1,k.character,[u.character]),ne.gsMessage(w,64,1,k.time,[u.time]),ne.gsMessage(w,64,1,k.delayFeedback,[u.delayFeedback]),ne.gsMessage(w,64,1,k.preDelayTime,[u.preDelayTime]))}if(a&&a!=="clear"){let k=ga,u=a;F.addEvents(H,ne.gsMessage(w,64,1,k.level,[u.level]),ne.gsMessage(w,64,1,k.preLowpass,[u.preLowpass]),ne.gsMessage(w,64,1,k.feedback,[u.feedback]),ne.gsMessage(w,64,1,k.delay,[u.delay]),ne.gsMessage(w,64,1,k.rate,[u.rate]),ne.gsMessage(w,64,1,k.depth,[u.depth]),ne.gsMessage(w,64,1,k.sendLevelToReverb,[u.sendLevelToReverb]),ne.gsMessage(w,64,1,k.sendLevelToDelay,[u.sendLevelToDelay]))}if(n&&n!=="clear"){let k=Ia,u=n;F.addEvents(H,ne.gsMessage(w,64,1,k.level,[u.level]),ne.gsMessage(w,64,1,k.preLowpass,[u.preLowpass]),ne.gsMessage(w,64,1,k.timeCenter,[u.timeCenter]),ne.gsMessage(w,64,1,k.timeRatioLeft,[u.timeRatioLeft]),ne.gsMessage(w,64,1,k.timeRatioRight,[u.timeRatioRight]),ne.gsMessage(w,64,1,k.levelCenter,[u.levelCenter]),ne.gsMessage(w,64,1,k.levelLeft,[u.levelLeft]),ne.gsMessage(w,64,1,k.levelRight,[u.levelRight]),ne.gsMessage(w,64,1,k.feedback,[u.feedback]),ne.gsMessage(w,64,1,k.sendLevelToReverb,[u.sendLevelToReverb]))}if(r&&r!=="clear"){let k=r;for(let u=0;u>8,k.type&127]))}t.flush(),l.groupEnd()}var RA=class an{name="";port=0;channels=new Set;events=[];static copyFrom(e){let A=new an;return A.copyFrom(e),A}copyFrom(e){this.name=e.name,this.port=e.port,this.channels=new Set(e.channels),this.events=e.events.map(A=>new Qe(A.ticks,A.statusByte,new te(A.data)))}addEvent(e,A){this.events.splice(A,0,e)}addEvents(e,...A){this.events.splice(e,0,...A)}deleteEvent(e){this.events.splice(e,1)}pushEvent(e){this.events.push(e)}},ha={8:2,9:2,10:2,11:2,12:1,13:1,14:2};function Bs(t,e,A){l.groupCollapsed("%cParsing MIDI File...",d.info),t.fileName=A;let s=r=>{let i=de(r,4),o=Nt(r,4),I={type:i,size:o,data:new te(o)},h=r.slice(r.currentIndex,r.currentIndex+I.size);return I.data.set(h,0),r.currentIndex+=I.size,I},a=s(e);if(a.type!=="MThd")throw l.groupEnd(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${a.type}"`);if(a.size!==6)throw l.groupEnd(),new RangeError(`Invalid MIDI header chunk size! Expected 6, got ${a.size}`);t.format=Nt(a.data,2);let n=Nt(a.data,2);t.timeDivision=Nt(a.data,2);for(let r=0;r0&&(h+=t.tracks[r-1].events[t.tracks[r-1].events.length-1].ticks);let C=o.data;for(;C.currentIndex=G.noteOff&&g>4],I=g):g===G.systemExclusive?E=pe(C):g===255?(g=C[C.currentIndex++],E=pe(C)):E=0;let p=new te(E);p.set(C.slice(C.currentIndex,C.currentIndex+E)),i.pushEvent(new Qe(h,g,p)),C.currentIndex+=E}t.tracks.push(i),l.info(`%cParsed %c${t.tracks.length}%c / %c${t.tracks.length}`,d.info,d.value,d.info,d.value)}l.info("%cAll tracks parsed correctly!",d.recognized),t.flush(!1),l.groupEnd()}function Es(t){return t.toISOString().split(".")[0]+"Z"}var la=[new Map([["domingo","Sunday"],["segunda-feira","Monday"],["ter\xE7a-feira","Tuesday"],["quarta-feira","Wednesday"],["quinta-feira","Thursday"],["sexta-feira","Friday"],["s\xE1bado","Saturday"],["janeiro","January"],["fevereiro","February"],["mar\xE7o","March"],["abril","April"],["maio","May"],["junho","June"],["julho","July"],["agosto","August"],["setembro","September"],["outubro","October"],["novembro","November"],["dezembro","December"]])];function Ca(t){for(let e of la){let A=t;for(let[a,n]of e.entries()){let r=new RegExp(a,"gi");A=A.replace(r,n)}let s=new Date(A);if(!Number.isNaN(s.getTime()))return s}}function Ba(t){let e=/^(\d{2})\.(\d{2})\.(\d{4})$/.exec(t);if(e){let A=Number.parseInt(e[1]),s=Number.parseInt(e[2])-1,a=Number.parseInt(e[3]),n=new Date(a,s,A);if(!Number.isNaN(n.getTime()))return n}}function Ea(t){let e=/^(\d{1,2})\s{1,2}(\d{1,2})\s{1,2}(\d{2})$/.exec(t);if(e){let A=e[1],s=(Number.parseInt(e[2])+1).toString(),a=e[3],n=new Date(`${s}/${A}/${a}`);if(!Number.isNaN(n.getTime()))return n}}function da(t){let e=/\b\d{4}\b/.exec(t);return e?new Date(e[0]):void 0}function ds(t){if(t=t.trim(),t.length===0)return new Date;let e=t.replaceAll(/\b(\d+)(st|nd|rd|th)\b/g,"$1").replace(/\s+at\s+/i," "),A=new Date(e);if(Number.isNaN(A.getTime())){let s=Ca(t);if(s)return s;let a=Ba(t);if(a)return a;let n=Ea(t);if(n)return n;let r=da(t);return r||(l.warn(`Invalid date: "${t}". Replacing with the current date!`),new Date)}return A}function fa(t,e,A){e.currentIndex+=8;let s=de(e,4);if(s!=="RMID")throw l.groupEnd(),new SyntaxError(`Invalid RMIDI Header! Expected "RMID", got "${s}"`);let a=x.read(e);if(a.header!=="data")throw l.groupEnd(),new SyntaxError(`Invalid RMIDI Chunk header! Expected "data", got "${a.header}"`);let n=a.data,r=!1,i=!1;for(;e.currentIndexOA[g]===i)??"":(l.info(`Unknown field specifier: ${i}`),o=`unknown_${i}`)):(i=de(r,pe(r)),o=i);let B=pe(r);if(B===0){let g=pe(r),E=r.slice(r.currentIndex,r.currentIndex+g);r.currentIndex+=g;let p=pe(E);this.metadata[o]=p<4?de(E,g-1):E.slice(E.currentIndex)}else l.info(`International content: ${B}`),r.currentIndex+=pe(r)}let I=n.currentIndex,h=pe(n),C=n.slice(n.currentIndex,I+h);if(n.currentIndex=I+h,h>0)for(this.packedContent=!0;C.currentIndexYA[E]===g):l.info(`Unrecognized resource format: ${g}`)}}else for(this.resourceFormat="folder";this.nodeData.currentIndex{let h=(C,B)=>{I.metadata[C]!==void 0&&typeof I.metadata[C]=="string"&&(t.rmidiInfo[B]=et(I.metadata[C]))};if(h("nodeName","name"),h("title","name"),h("copyrightNotice","copyright"),h("comment","comment"),I.isFile)switch(I.resourceFormat){default:return;case"DLS1":case"DLS2":case"DLS22":case"mobileDLS":l.info("%cFound embedded DLS!",d.recognized),t.embeddedSoundBank=I.nodeData.buffer;break;case"StandardMIDIFile":case"StandardMIDIFileType1":l.info("%cFound embedded MIDI!",d.recognized),i=I.nodeData;break}else for(let C of I.innerNodes)o(C)};if(o(r),l.groupEnd(),!i)throw new Error("No MIDI data in the XMF file!");Bs(t,i,A)}function pa(t,e){let A=new Map,s=e.systemParameters.keyShift,a=e.systemParameters.fineTune;for(let r=0;r>7;C.set(g,E)}let B={};for(let[g,E]of Object.entries(i.midiParameters))i.lockedMIDIParameters[g]&&(B[g]=E);A.set(r,{keyShift:o,fineTune:I,patch:h,controllers:C,midiParams:B})}let n={};for(let[r,i]of Object.entries(e.midiParameters))e.lockedMIDIParameters[r]&&(n[r]=i);t.modify({channels:A,drumSetupParams:e.systemParameters.drumLock?"clear":void 0,reverbParams:e.systemParameters.reverbLock?e.reverbProcessor:void 0,chorusParams:e.systemParameters.chorusLock?e.chorusProcessor:void 0,delayParams:e.systemParameters.delayLock?e.delayProcessor:void 0,insertionParams:e.systemParameters.insertionEffectLock?e.insertionProcessor:void 0,midiParams:n})}var Mt=class es{tracks=[];timeline=[];timeDivision=480;duration=0;tempoChanges=[{ticks:0,tempo:120}];extraMetadata=[];lyrics=[];firstNoteOn=0;keyRange={min:0,max:127};lastVoiceEventTick=0;portChannelOffsetMap=[0];loop={start:0,end:0,type:"hard"};fileName;format=0;rmidiInfo={};bankOffset=0;isKaraokeFile=!1;isMultiPort=!1;isDLSRMIDI=!1;embeddedSoundBank;binaryName;get infoEncoding(){let e=this.rmidiInfo.infoEncoding;if(!e)return;let A=e.byteLength;return e[e.byteLength-1]===0&&A--,We(e,A)}static fromArrayBuffer(e,A=""){let s=new es,a=new te(e);switch(We(a,4)){case"RIFF":fa(s,a,A);break;case"XMF_":ma(s,a,A);break;default:Bs(s,a,A);break}return s}static async fromFile(e){return this.fromArrayBuffer(await e.arrayBuffer(),e.name)}static copyFrom(e){let A=new es;return A.copyFrom(e),A}copyFrom(e){this.copyMetadataFrom(e),this.embeddedSoundBank=e?.embeddedSoundBank?.slice(0)??void 0,this.tracks=e.tracks.map(A=>RA.copyFrom(A)),this.timeline=e.timeline.map(A=>({...A}))}midiTicksToSeconds(e){if(e=Math.max(e,0),this.tempoChanges.length===0)throw new Error("There are no tempo changes in the sequence. At least one is needed.");if(this.tempoChanges[this.tempoChanges.length-1].ticks!==0)throw new Error(`The last tempo change is not at 0 ticks. Got ${this.tempoChanges[this.tempoChanges.length-1].ticks} ticks.`);let A=this.tempoChanges.findIndex(a=>a.ticks<=e),s=0;for(;A=0;a--){let n=this.tempoChanges[a],r=this.tempoChanges[a-1],i=r?r.ticks-n.ticks:1/0,o=60/(n.tempo*this.timeDivision),I=i*o;if(A<=I)return s+=Math.round(A/o),s;s+=i,A-=I}return s}getUsedProgramsAndKeys(e){return aa(this,e)}preloadSynth(e){l.groupCollapsed("%cPreloading samples...",d.info);let A=this.getUsedProgramsAndKeys(e.soundBankManager);for(let[s,a]of A.entries()){l.info(`%cPreloading used samples on %c${s.name}%c...`,d.info,d.recognized,d.info);for(let[n,r]of a.entries())for(let i of r)e.getVoicesForPreset(s,n,i)}l.groupEnd()}flush(e=!0){if(e)for(let A of this.tracks)A.events.sort((s,a)=>s.ticks-a.ticks);this.parseInternal()}getNoteTimes(e=0){return ia(this,e)}writeMIDI(){return zn(this)}writeRMIDI(e,A=Rs){return na(this,e,$t(A,Rs))}modify(e){ca(this,e)}applySnapshot(e){pa(this,e)}getName(e="Shift_JIS"){let A="",s=this.getRMIDInfo("name");if(s)return s.trim();if(this.binaryName){e=this.getRMIDInfo("midiEncoding")??e;try{A=new TextDecoder(e).decode(this.binaryName).trim()}catch(a){l.warn(`Failed to decode MIDI name: ${a}`)}}return A||this.fileName}getExtraMetadata(e="Shift_JIS"){e=this.infoEncoding??e;let A=new TextDecoder(e);return this.extraMetadata.map(s=>A.decode(s.data).replaceAll(/@T|@A/g,"").trim())}setRMIDInfo(e,A){if(this.rmidiInfo.infoEncoding=et("utf-8",!0),e==="picture")this.rmidiInfo.picture=new Uint8Array(A);else if(e==="creationDate")this.rmidiInfo.creationDate=et(Es(A),!0);else{let s=new TextEncoder().encode(A);this.rmidiInfo[e]=new Uint8Array([...s,0])}}getRMIDInfo(e){if(!this.rmidiInfo[e])return;let A=this.infoEncoding??"UTF-8";if(e==="picture")return this.rmidiInfo[e].buffer;if(e==="creationDate")return ds(We(this.rmidiInfo[e]));try{let s=new TextDecoder(A),a=this.rmidiInfo[e];return a[a.length-1]===0&&(a=a?.slice(0,-1)),s.decode(a.buffer).trim()}catch(s){l.warn(`Failed to decode ${e} name: ${s}`);return}}iterate(e){let A=new Array(this.tracks.length).fill(0),s=this.tracks.length;for(;s>0;){let a=0,n=1/0;for(let o=0;o=I.length||I[A[o]].ticks=r.length){s--;continue}let i=A[a];e(r[i],a,A),A[a]++}}copyMetadataFrom(e){this.fileName=e.fileName,this.timeDivision=e.timeDivision,this.duration=e.duration,this.firstNoteOn=e.firstNoteOn,this.lastVoiceEventTick=e.lastVoiceEventTick,this.format=e.format,this.bankOffset=e.bankOffset,this.isKaraokeFile=e.isKaraokeFile,this.isMultiPort=e.isMultiPort,this.isDLSRMIDI=e.isDLSRMIDI,this.isDLSRMIDI=e.isDLSRMIDI,this.tempoChanges=[...e.tempoChanges],this.extraMetadata=e.extraMetadata.map(A=>new Qe(A.ticks,A.statusByte,new te(A.data))),this.lyrics=e.lyrics.map(A=>new Qe(A.ticks,A.statusByte,new te(A.data))),this.portChannelOffsetMap=[...e.portChannelOffsetMap],this.binaryName=e?.binaryName?.slice(),this.loop={...e.loop},this.keyRange={...e.keyRange},this.rmidiInfo={};for(let A of Object.entries(e.rmidiInfo)){let s=A[0],a=A[1];this.rmidiInfo[s]=new Uint8Array(a)}}parseInternal(){l.group("%cInterpreting MIDI events...",d.info);let e=!1;this.tempoChanges=[{ticks:0,tempo:120}],this.extraMetadata=[],this.lyrics=[],this.firstNoteOn=0,this.keyRange={max:0,min:127},this.lastVoiceEventTick=0,this.portChannelOffsetMap=[0],this.loop={start:0,end:0,type:"hard"},this.isKaraokeFile=!1,this.isMultiPort=!1;let A=!1;this.rmidiInfo.name!==void 0&&(A=!0);let s=null,a=null,n="hard";for(let I of this.tracks){let h=new Set,C=!1;for(let g=0;g=128&&E.statusByte<240)switch(C=!0,E.ticks>this.lastVoiceEventTick&&(this.lastVoiceEventTick=E.ticks),E.statusByte&240){case G.controllerChange:switch(E.data[0]){case f.breathController:case f.undefinedCC111LSB:E.data[1]===0&&(s=E.ticks);break;case f.undefinedCC116LSB:s=E.ticks;break;case f.footController:case f.undefinedCC117LSB:a===null&&(E.data[0]!==4||E.data[0]===4&&E.data[1]===0)?(n="soft",a=E.ticks):(a=0,n="hard");break;case f.bankSelect:this.isDLSRMIDI&&E.data[1]!==0&&E.data[1]!==127&&(l.info("%cDLS RMIDI with offset 1 detected!",d.recognized),this.bankOffset=1)}break;case G.noteOn:{h.add(E.statusByte&15);let y=E.data[0];this.keyRange.min=Math.min(this.keyRange.min,y),this.keyRange.max=Math.max(this.keyRange.max,y);break}}let p=We(E.data);switch(E.statusByte){case G.endOfTrack:g!==I.events.length-1&&(I.deleteEvent(g),g--,l.warn("Unexpected EndOfTrack. Removing!"));break;case G.setTempo:this.tempoChanges.push({ticks:E.ticks,tempo:6e7/Ht(E.data,3)});break;case G.marker:switch(p.trim().toLowerCase()){default:break;case"start":case"loopstart":s=E.ticks;break;case"loopend":a=E.ticks}break;case G.copyright:this.extraMetadata.push(E);break;case G.lyric:p.trim().startsWith("@KMIDI KARAOKE FILE")&&(this.isKaraokeFile=!0,l.info("%cKaraoke MIDI detected!",d.recognized)),this.isKaraokeFile?E.statusByte=G.text:this.lyrics.push(E);case G.text:{let y=p.trim();y.startsWith("@KMIDI KARAOKE FILE")?(this.isKaraokeFile=!0,l.info("%cKaraoke MIDI detected!",d.recognized)):this.isKaraokeFile&&(y.startsWith("@T")||y.startsWith("@A")?e?this.extraMetadata.push(E):(this.binaryName=E.data.slice(2),e=!0,A=!0):y.startsWith("@")||this.lyrics.push(E));break}}}I.channels=h,I.name="";let B=I.events.find(g=>g.statusByte===G.trackName);B&&this.tracks.indexOf(I)>0&&(I.name=We(B.data),!C&&!I.name.toLowerCase().includes("setup")&&this.extraMetadata.push(B))}this.tempoChanges.reverse(),l.info("%cCorrecting loops, ports and detecting notes...",d.info);let r=[];for(let I of this.tracks){let h=I.events.find(C=>(C.statusByte&240)===G.noteOn);h&&r.push(h.ticks)}this.firstNoteOn=Math.min(...r),l.info(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,d.info,d.recognized,d.info),s??=this.firstNoteOn,(a===null||a===0)&&(a=this.lastVoiceEventTick),this.loop={start:s,end:a,type:n},this.lastVoiceEventTick=Math.max(this.lastVoiceEventTick,this.loop.end),l.info(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,d.info,d.recognized,d.info,d.recognized);let i=0;this.portChannelOffsetMap=[];for(let I of this.tracks)if(I.port=-1,I.channels.size!==0)for(let h of I.events){if(h.statusByte!==G.midiPort)continue;let C=h.data[0];I.port=C,this.portChannelOffsetMap[C]===void 0&&(this.portChannelOffsetMap[C]=i,i+=16)}this.portChannelOffsetMap=[...this.portChannelOffsetMap].map(I=>I??0);let o=1/0;for(let I of this.tracks)I.port!==-1&&o>I.port&&(o=I.port);o===1/0&&(o=0);for(let I of this.tracks)(I.port===-1||I.port===void 0)&&(I.port=o);if(this.portChannelOffsetMap.length===0&&(this.portChannelOffsetMap=[0]),this.portChannelOffsetMap.length<2?l.info("%cNo additional MIDI Ports detected.",d.info):(this.isMultiPort=!0,l.info("%cMIDI Ports detected!",d.recognized)),!A)if(this.tracks.length>1){if(!this.tracks[0].events.some(I=>I.statusByte>=G.noteOn&&I.statusByteh.statusByte===G.trackName);I&&(this.binaryName=I.data)}}else{let I=this.tracks[0].events.find(h=>h.statusByte===G.trackName);I&&(this.binaryName=I.data)}if(this.extraMetadata=this.extraMetadata.filter(I=>I.data.length>0),this.lyrics.sort((I,h)=>I.ticks-h.ticks),!this.tracks.some(I=>I.events[0].ticks===0)){let I=this.tracks[0],h=this?.binaryName?.buffer;h||(h=new Uint8Array(0).buffer),I.addEvents(0,new Qe(0,G.trackName,new te(h)))}this.duration=this.midiTicksToSeconds(this.lastVoiceEventTick),this.timeline.length=0,this.iterate((I,h,C)=>{this.timeline.push(Object.freeze({ev:C[h],tr:h}))}),this.binaryName?.length===0&&(this.binaryName=void 0),l.info(`%cMIDI file parsed. Total tick time: %c${this.lastVoiceEventTick}%c, total seconds time: %c${_A(Math.ceil(this.duration)).time}`,d.info,d.recognized,d.info,d.recognized),l.groupEnd()}};function ya(t,e){if(this.externalMIDIPlayback&&t.statusByte>=128){this.sendMIDIMessage([t.statusByte,...t.data]);return}let A=this._midiData.tracks[e],s,a=0;t.statusByte>=128&&t.statusByte<240?(s=t.statusByte&240,a=t.statusByte&15):s=t.statusByte;let n=this.midiPortChannelOffsets[this.currentMIDIPorts[e]]||0;switch(a+=n,s){case G.noteOn:{let r=this.playingNotes[a];if(!r){for(;this.playingNotes.length<=a;)this.playingNotes.push(new Map);r=this.playingNotes[a]}let i=t.data[1];i>0?(this.synth.noteOn(a,t.data[0],i),r.set(t.data[0],i)):(this.synth.noteOff(a,t.data[0]),r.delete(t.data[0]));break}case G.noteOff:{let r=this.playingNotes[a];if(!r){for(;this.playingNotes.length<=a;)this.playingNotes.push(new Map);r=this.playingNotes[a]}this.synth.noteOff(a,t.data[0]),r.delete(t.data[0]);break}case G.pitchWheel:this.synth.pitchWheel(a,t.data[1]<<7|t.data[0]);break;case G.controllerChange:if(this._midiData.isMultiPort&&A.channels.size===0)return;this.synth.controllerChange(a,t.data[0],t.data[1]);break;case G.programChange:if(this._midiData.isMultiPort&&A.channels.size===0)return;this.synth.programChange(a,t.data[0]);break;case G.polyPressure:this.synth.polyPressure(a,t.data[0],t.data[1]);break;case G.channelPressure:this.synth.channelPressure(a,t.data[0]);break;case G.systemExclusive:this.synth.systemExclusive(t.data,n);break;case G.setTempo:{let r=6e7/Ht(t.data,3);this.oneTickToSeconds=60/(r*this._midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this._midiData.timeDivision),l.info("invalid tempo! falling back to 120 BPM"));break}case G.timeSignature:case G.endOfTrack:case G.midiChannelPrefix:case G.songPosition:case G.activeSensing:case G.keySignature:case G.sequenceNumber:case G.sequenceSpecific:case G.text:case G.lyric:case G.copyright:case G.trackName:case G.marker:case G.cuePoint:case G.instrumentName:case G.programName:break;case G.midiPort:this.assignMIDIPort(e,t.data[0]);break;case G.reset:this.synth.stopAllChannels(),this.synth.reset();break;default:l.info(`%cUnrecognized Event: %c${t.statusByte}%c status byte: %c${Object.keys(G).find(r=>G[r]===s)}`,d.warn,d.unrecognized,d.warn,d.value);break}s>=0&&s<128&&this.callEvent("metaEvent",{event:t,trackIndex:e})}function Sa(){if(this.paused||!this._midiData)return;let t=this.currentTime;for(;this.playedTime0&&a.end<=r.ticks){this.loopCount!==1/0&&(this.loopCount--,this.callEvent("loopCountChange",{newCount:this.loopCount})),a.type==="soft"?this.jumpToTick(a.start):this.setTimeTicks(a.start);return}if(this.index>=e.length||r.ticks>=s){this.songIsFinished();return}let i=e[this.index],o=A[i.tr].events[i.ev];this.playedTime+=this.oneTickToSeconds*(o.ticks-r.ticks)}}function ka(t,e){this._midiData.tracks[t].channels.size!==0&&(this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[e]=0),this.midiPortChannelOffsets[e]===void 0&&(this.synth.midiChannels.lengthe.port),this.midiPortChannelOffset=0,this.midiPortChannelOffsets={};for(let[e,A]of this._midiData.tracks.entries())this.assignMIDIPort(e,A.port);this.firstNoteTime=this._midiData.midiTicksToSeconds(this._midiData.firstNoteOn),l.info(`%cTotal song time: ${_A(Math.ceil(this._midiData.duration)).time}`,d.recognized),this.callEvent("songChange",{songIndex:this._songIndex}),this._midiData.duration<=.2&&(l.warn(`%cVery short song: (${_A(Math.round(this._midiData.duration)).time}). Disabling loop!`,d.warn),this.loopCount=0),this.currentTime=0}var yt=new Int16Array(128).fill(0),Ge=(t,e)=>yt[t]=e<<7;Ge(f.mainVolume,100);Ge(f.balance,64);Ge(f.expression,127);Ge(f.pan,64);Ge(f.filterResonance,64);Ge(f.releaseTime,64);Ge(f.attackTime,64);Ge(f.brightness,64);Ge(f.decayTime,64);Ge(f.vibratoRate,64);Ge(f.vibratoDepth,64);Ge(f.vibratoDelay,64);Ge(f.generalPurposeController6,64);Ge(f.generalPurposeController8,64);Ge(f.registeredParameterLSB,127);Ge(f.registeredParameterMSB,127);Ge(f.nonRegisteredParameterLSB,0);Ge(f.nonRegisteredParameterMSB,0);var pA=new Int8Array(128).fill(127);pA[35]=0;pA[36]=0;function wa(t=!0){for(let e=0;e<128;e++){if(this.lockedControllers[e]){this.synthCore.callEvent("controllerChange",{channel:this.channel,controller:e,value:this._midiControllers[e]>>7});continue}let A=yt[e];this._midiControllers[e]!==A&&e!==f.portamentoControl&&e!==f.dataEntryMSB&&e!==f.registeredParameterMSB&&e!==f.registeredParameterLSB&&e!==f.nonRegisteredParameterMSB&&e!==f.nonRegisteredParameterLSB&&this.controllerChange(e,A>>7,t)}this.setMIDIParameter("pressure",0),this.setMIDIParameter("pitchWheelRange",2),this.setMIDIParameter("modulationDepth",50),this.setMIDIParameter("rxChannel",this.channel),this.setMIDIParameter("efxAssign",!1),this.setMIDIParameter("polyMode",!0),this.setMIDIParameter("keyShift",0),this.setMIDIParameter("fineTune",0),this.setMIDIParameter("assignMode",2),this.setMIDIParameter("randomPan",!1),this.setMIDIParameter("cc1",16),this.setMIDIParameter("cc2",17),this.setMIDIParameter("drumMap",this.channel%16===9?1:0),this.setMIDIParameter("velocitySenseOffset",64),this.setMIDIParameter("velocitySenseDepth",64),this.pitchWheel(8192),this.octaveTuning.fill(0),this.lastPortamentoNote=this.channelSystem==="xg"?60:-1,this.resetDrumParams(),this.resetGeneratorOverrides(),this.resetGeneratorOffsets(),this.dynamicModulators.resetModulators(),this.sf2NRPNGeneratorLSB=0,this.playingNotes.fill(!1),this.lastParameterIsRegistered=!0,this._midiControllers[f.nonRegisteredParameterLSB]=0,this._midiControllers[f.nonRegisteredParameterMSB]=0,this._midiControllers[f.registeredParameterLSB]=16256,this._midiControllers[f.registeredParameterMSB]=16256,this._midiControllers[f.dataEntryMSB]=0,this._midiControllers[f.dataEntryLSB]=0,this.setBankMSB(De.getDefaultBank(this.channelSystem)),this.setBankLSB(0),this.setGSDrums(!1),this.setDrums(this.channel%16===9),this.programChange(0)}var on=[f.modulationWheel,f.expression,f.sustainPedal,f.portamentoOnOff,f.sostenutoPedal,f.softPedal,f.registeredParameterMSB,f.registeredParameterLSB];function Ma(){this.pitchWheel(8192),this.setMIDIParameter("pressure",0);for(let t of on){let e=yt[t];e!==this._midiControllers[t]&&this.controllerChange(t,e>>7)}}var oA=new Set([f.dataDecrement,f.dataIncrement,f.dataEntryMSB,f.dataEntryLSB,f.registeredParameterLSB,f.registeredParameterMSB,f.nonRegisteredParameterLSB,f.nonRegisteredParameterMSB,f.bankSelect,f.bankSelectLSB,f.resetAllControllers,f.monoModeOn,f.polyModeOn]);function ba(t,e=void 0){if(!this._midiData)return!1;this.oneTickToSeconds=60/(120*this._midiData.timeDivision),this.sendMIDIReset(),this.playedTime=0,this.index=0;let A=this.synth.midiChannels.length,s=[];for(let I=0;I=t)break}else if(B.ticks>=e)break;let g,E=0;B.statusByte>=128&&B.statusByte<240?(g=B.statusByte&240,E=B.statusByte&15):g=B.statusByte;let p=E+(this.midiPortChannelOffsets[C.port]||0);s[p]??={pitchWheel:8192,controllers:new Int16Array(yt),param:new mA(p),portamentoNote:-1};let y=s[p];switch(g){case G.noteOn:y.portamentoNote=B.data[0];break;case G.noteOff:break;case G.pitchWheel:y.pitchWheel=B.data[1]<<7|B.data[0];break;case G.systemExclusive:{let S=ne.analyzeSysEx(B.data);switch(S.type){default:this.processEvent(B,h);break;case"Controller Change":{let{controller:w,value:F,channel:H}=S;if(H>=A||this._midiData.isMultiPort&&C.channels.size===0)break;if(w===f.resetAllControllers){r(H);break}oA.has(w)?this.sendMIDICC(H,w,F):s[H].controllers[w]=F<<7}}break}case G.controllerChange:{if(this._midiData.isMultiPort&&C.channels.size===0)break;let S=B.data[0],w=B.data[1];switch(S){default:if(S===f.resetAllControllers){r(p);break}oA.has(S)?this.sendMIDICC(p,S,w):y.controllers[S]=w<<7;break;case f.registeredParameterMSB:case f.registeredParameterLSB:case f.nonRegisteredParameterLSB:case f.nonRegisteredParameterMSB:y.param.controllerChange(S,w,0,0),this.sendMIDICC(p,S,w);break;case f.dataEntryMSB:case f.dataEntryLSB:{let F=y.param.controllerChange(S,w,0,0);this.sendMIDICC(p,S,w),F.type==="Controller Change"&&(oA.has(F.controller)?this.sendMIDICC(p,F.controller,F.value):y.controllers[F.controller]=F.value<<7);break}}break}case G.setTempo:{let S=6e7/Ht(B.data,3);this.oneTickToSeconds=60/(S*this._midiData.timeDivision),a=B,n=h;break}default:this.processEvent(B,h);break}let D=i[++this.index],R=o[D.tr].events[D.ev];if(R===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(R.ticks-B.ticks)}for(let I=0;I=0&&(this.externalMIDIPlayback?this.sendMIDICC(I,f.portamentoControl,h.portamentoNote):this.synth.midiChannels[I].setLastNote(h.portamentoNote));for(let C=0;C<128;C++){let B=h.controllers[C]>>7;B!==yt[C]&&!oA.has(C)&&this.sendMIDICC(I,C,B)}}return a&&this.callEvent("metaEvent",{event:a,trackIndex:n}),this.paused&&(this.pausedTime=this.playedTime),!0}var gn=class{songs=[];shuffledSongIndexes=[];synth;externalMIDIPlayback=!1;retriggerPausedNotes=!0;loopCount=0;skipToFirstNoteOn=!0;isFinished=!1;preload=!0;onEventCall;processTick=Sa.bind(this);firstNoteTime=0;oneTickToSeconds=0;index=0;playedTime=0;pausedTime=-1;absoluteStartTime=0;playingNotes=[];currentMIDIPorts=[];midiPortChannelOffset=0;midiPortChannelOffsets={};assignMIDIPort=ka.bind(this);loadNewSequence=Da.bind(this);processEvent=ya.bind(this);setTimeTo=ba.bind(this);constructor(t){this.synth=t,this.absoluteStartTime=this.synth.currentTime,this.playingNotes=this.synth.midiChannels.map(()=>new Map)}_midiData;get midiData(){return this._midiData}get duration(){return this._midiData?.duration??0}_songIndex=0;get songIndex(){return this._songIndex}set songIndex(t){this._songIndex=t,this._songIndex=Math.max(0,t%this.songs.length),this.loadCurrentSong()}_shuffleMode=!1;get shuffleMode(){return this._shuffleMode}set shuffleMode(t){this._shuffleMode=t}_playbackRate=1;get playbackRate(){return this._playbackRate}set playbackRate(t){let e=this.currentTime;this._playbackRate=t,this.recalculateStartTime(e)}get currentTime(){return this.pausedTime!==void 0?this.pausedTime:(this.synth.currentTime-this.absoluteStartTime)*this._playbackRate}set currentTime(t){if(this._midiData)if(this.paused&&(this.pausedTime=t),t>this._midiData.duration||t<0)this.skipToFirstNoteOn?this.setTimeTicks(this._midiData.firstNoteOn-1):this.setTimeTicks(0);else if(this.skipToFirstNoteOn&&t=this._midiData.duration&&(this.currentTime=0),this.paused&&this.recalculateStartTime(this.pausedTime??0),this.retriggerPausedNotes&&!this.externalMIDIPlayback)for(let t=0;tA);for(this.shuffledSongIndexes.length=0;t.length>0;){let e=t[Math.floor(Math.random()*t.length)];this.shuffledSongIndexes.push(e),t.splice(t.indexOf(e),1)}}setTimeTicks(t){if(!this._midiData)return;for(let s of this.playingNotes)s.clear();let e=this._midiData.midiTicksToSeconds(t);this.callEvent("timeChange",{newTime:e});let A=this.setTimeTo(0,t);this.recalculateStartTime(this.playedTime)}recalculateStartTime(t){this.absoluteStartTime=this.synth.currentTime-t/this._playbackRate}jumpToTick(t){if(!this._midiData)return;this.sendMIDIAllOff();let e=this._midiData,A=e.midiTicksToSeconds(t);this.callEvent("timeChange",{newTime:A}),this.recalculateStartTime(A),this.playedTime=A;let s=e.timeline.findIndex(n=>e.tracks[n.tr].events[n.ev].ticks>=t);this.index=s===-1?e.timeline.length:s;let a=e.tempoChanges.find(n=>n.ticks<=t);this.oneTickToSeconds=60/(a.tempo*e.timeDivision)}sendMIDINoteOn(t,e,A){if(!this.externalMIDIPlayback){this.synth.noteOn(t,e,A);return}t%=16,this.sendMIDIMessage([G.noteOn|t,e,A])}sendMIDINoteOff(t,e){if(!this.externalMIDIPlayback){this.synth.noteOff(t,e);return}t%=16,this.sendMIDIMessage([G.noteOff|t,e,64])}sendMIDICC(t,e,A){if(!this.externalMIDIPlayback){this.synth.controllerChange(t,e,A);return}t%=16,this.sendMIDIMessage([G.controllerChange|t,e,A])}sendMIDISysEx(t){if(!this.externalMIDIPlayback){this.synth.systemExclusive(t);return}this.sendMIDIMessage([G.systemExclusive,...t])}sendMIDIPitchWheel(t,e){if(!this.externalMIDIPlayback){this.synth.pitchWheel(t,e);return}t%=16,this.sendMIDIMessage([G.pitchWheel|t,e&127,e>>7])}},Ra={linear:0,nearestNeighbor:1,hermite:2},Wt=Wt!==void 0?Wt:{},Fs=!1,In;Wt.isInitialized=new Promise(t=>In=t);var Fa=function(t){var e,A,s,a,n,r,i,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",I="",h=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do a=o.indexOf(t.charAt(h++)),n=o.indexOf(t.charAt(h++)),r=o.indexOf(t.charAt(h++)),i=o.indexOf(t.charAt(h++)),e=a<<2|n>>4,A=(15&n)<<4|r>>2,s=(3&r)<<6|i,I+=String.fromCharCode(e),r!==64&&(I+=String.fromCharCode(A)),i!==64&&(I+=String.fromCharCode(s));while(h1&&(g.thisProgram=process.argv[1].replace(/\\/g,"/")),g.arguments=process.argv.slice(2),process.on("uncaughtException",function(v){if(!(v instanceof Ke))throw v}),process.on("unhandledRejection",function(v,M){process.exit(1)}),g.quit=function(v){process.exit(v)},g.inspect=function(){return"[Emscripten Module object]"}):R?(typeof read<"u"&&(g.read=function(M){return read(M)}),g.readBinary=function(M){var P;return typeof readbuffer=="function"?new Uint8Array(readbuffer(M)):(q(typeof(P=read(M,"binary"))=="object"),P)},typeof scriptArgs<"u"?g.arguments=scriptArgs:typeof arguments<"u"&&(g.arguments=arguments),typeof quit=="function"&&(g.quit=function(v){quit(v)})):(p||y)&&(p?document.currentScript&&(S=document.currentScript.src):S=self.location.href,S=S.indexOf("blob:")!==0?S.split("/").slice(0,-1).join("/")+"/":"",g.read=function(M){var P=new XMLHttpRequest;return P.open("GET",M,!1),P.send(null),P.responseText},y&&(g.readBinary=function(M){var P=new XMLHttpRequest;return P.open("GET",M,!1),P.responseType="arraybuffer",P.send(null),new Uint8Array(P.response)}),g.readAsync=function(M,P,_){var ie=new XMLHttpRequest;ie.open("GET",M,!0),ie.responseType="arraybuffer",ie.onload=function(){if(ie.status==200||ie.status==0&&ie.response){P(ie.response);return}_()},ie.onerror=_,ie.send(null)},g.setWindowTitle=function(v){document.title=v});var F=g.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),H=g.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||F);for(t in E)E.hasOwnProperty(t)&&(g[t]=E[t]);function k(v){var M=o;return o=o+v+15&-16,M}function u(v,M){return M||(M=16),v=Math.ceil(v/M)*M}function m(v){m.shown||(m.shown={}),m.shown[v]||(m.shown[v]=1,H(v))}E=void 0;var J={"f64-rem":function(v,M){return v%M},debugger:function(){}},O=0;function q(v,M){v||tt("Assertion failed: "+M)}function K(v){var M=g["_"+v];return q(M,"Cannot call unknown function "+v+", make sure it is exported"),M}var ae={stackSave:function(){Rt()},stackRestore:function(){dt()},arrayToC:function(v){var M,P,_=It(v.length);return M=v,P=_,a.set(M,P),_},stringToC:function(v){var M=0;if(v!=null&&v!==0){var P=(v.length<<2)+1;M=It(P),z(v,M,P)}return M}},U={string:ae.stringToC,array:ae.arrayToC};function T(v,M,P,_,ie){var ce=K(v),fe=[],j=0;if(_)for(var Te=0;Te<_.length;Te++){var Me=U[P[Te]];Me?(j===0&&(j=Rt()),fe[Te]=Me(_[Te])):fe[Te]=_[Te]}var oe,Be=ce.apply(null,fe);return Be=(oe=Be,M==="string"?Q(oe):M==="boolean"?!!oe:oe),j!==0&&dt(j),Be}function Q(v,M){if(M===0||!v)return"";for(var P,_,ie,ce=0,fe=0;ce|=_=n[v+fe>>0],(_!=0||M)&&(fe++,!M||fe!=M););M||(M=fe);var j="";if(ce<128){for(;M>0;)ie=String.fromCharCode.apply(String,n.subarray(v,v+Math.min(M,1024))),j=j?j+ie:ie,v+=1024,M-=1024;return j}return P=v,(function(Me,oe){for(var Be=oe;Me[Be];)++Be;if(Be-oe>16&&Me.subarray&&b)return b.decode(Me.subarray(oe,Be));for(var he,xe,He,At,mt,ct="";;){if(!(he=Me[oe++]))return ct;if(!(128&he)){ct+=String.fromCharCode(he);continue}if(xe=63&Me[oe++],(224&he)==192){ct+=String.fromCharCode((31&he)<<6|xe);continue}if(He=63&Me[oe++],(240&he)==224?he=(15&he)<<12|xe<<6|He:(At=63&Me[oe++],(248&he)==240?he=(7&he)<<18|xe<<12|He<<6|At:(mt=63&Me[oe++],he=(252&he)==248?(3&he)<<24|xe<<18|He<<12|At<<6|mt:(1&he)<<30|xe<<24|He<<18|At<<12|mt<<6|63&Me[oe++])),he<65536)ct+=String.fromCharCode(he);else{var st=he-65536;ct+=String.fromCharCode(55296|st>>10,56320|1023&st)}}})(n,P)}var b=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function L(v,M,P,_){if(!(_>0))return 0;for(var ie=P,ce=P+_-1,fe=0;fe=55296&&j<=57343&&(j=65536+((1023&j)<<10)|1023&v.charCodeAt(++fe)),j<=127){if(P>=ce)break;M[P++]=j}else if(j<=2047){if(P+1>=ce)break;M[P++]=192|j>>6,M[P++]=128|63&j}else if(j<=65535){if(P+2>=ce)break;M[P++]=224|j>>12,M[P++]=128|j>>6&63,M[P++]=128|63&j}else if(j<=2097151){if(P+3>=ce)break;M[P++]=240|j>>18,M[P++]=128|j>>12&63,M[P++]=128|j>>6&63,M[P++]=128|63&j}else if(j<=67108863){if(P+4>=ce)break;M[P++]=248|j>>24,M[P++]=128|j>>18&63,M[P++]=128|j>>12&63,M[P++]=128|j>>6&63,M[P++]=128|63&j}else{if(P+5>=ce)break;M[P++]=252|j>>30,M[P++]=128|j>>24&63,M[P++]=128|j>>18&63,M[P++]=128|j>>12&63,M[P++]=128|j>>6&63,M[P++]=128|63&j}}return M[P]=0,P-ie}function z(v,M,P){return L(v,n,M,P)}typeof TextDecoder<"u"&&new TextDecoder("utf-16le");function $(v,M){return v%M>0&&(v+=M-v%M),v}function W(v){g.buffer=s=v}function V(){g.HEAP8=a=new Int8Array(s),g.HEAP16=new Int16Array(s),g.HEAP32=r=new Int32Array(s),g.HEAPU8=n=new Uint8Array(s),g.HEAPU16=new Uint16Array(s),g.HEAPU32=new Uint32Array(s),g.HEAPF32=new Float32Array(s),g.HEAPF64=new Float64Array(s)}function ee(){var v=g.usingWasm?65536:16777216,M=2147483648-v;if(r[B>>2]>M)return!1;var P=Y;for(Y=Math.max(Y,16777216);Y>2];)Y=Y<=536870912?$(2*Y,v):Math.min($((3*Y+2147483648)/4,v),M);var _=g.reallocBuffer(Y);return _&&_.byteLength==Y?(W(_),V(),!0):(Y=P,!1)}i=o=I=h=C=B=0,g.reallocBuffer||(g.reallocBuffer=function(v){try{if(ArrayBuffer.transfer)M=ArrayBuffer.transfer(s,v);else{var M,P=a;M=new ArrayBuffer(v),new Int8Array(M).set(P)}}catch{return!1}return!!_e(M)&&M});try{Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get)(new ArrayBuffer(4))}catch{}var Ae=g.TOTAL_STACK||5242880,Y=g.TOTAL_MEMORY||16777216;function re(){return Y}function ue(v){for(;v.length>0;){var M=v.shift();if(typeof M=="function"){M();continue}var P=M.func;typeof P=="number"?M.arg===void 0?g.dynCall_v(P):g.dynCall_vi(P,M.arg):P(M.arg===void 0?null:M.arg)}}Y>2]=C,g.wasmTableSize=4,g.wasmMaxTableSize=4,g.asmGlobalArg={},g.asmLibraryArg={abort:tt,assert:q,enlargeMemory:ee,getTotalMemory:re,abortOnCannotGrowMemory:function(){tt("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+Y+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ")},invoke_iii:function(M,P,_){var ie=Rt();try{return g.dynCall_iii(M,P,_)}catch(ce){if(dt(ie),typeof ce!="number"&&ce!=="longjmp")throw ce;g.setThrew(1,0)}},___assert_fail:function(M,P,_,ie){tt("Assertion failed: "+Q(M)+", at: "+[P?Q(P):"unknown filename",_,ie?Q(ie):"unknown function"])},___setErrNo:function(M){return g.___errno_location&&(r[g.___errno_location()>>2]=M),M},_abort:function(){g.abort()},_emscripten_memcpy_big:function(M,P,_){return n.set(n.subarray(P,P+_),M),M},_llvm_floor_f64:AA,DYNAMICTOP_PTR:B,tempDoublePtr:UA,ABORT:O,STACKTOP:I,STACK_MAX:h};var qt=g.asm(g.asmGlobalArg,g.asmLibraryArg,s);g.asm=qt,g.___errno_location=function(){return g.asm.___errno_location.apply(null,arguments)};var _e=g._emscripten_replace_memory=function(){return g.asm._emscripten_replace_memory.apply(null,arguments)};g._free=function(){return g.asm._free.apply(null,arguments)},g._malloc=function(){return g.asm._malloc.apply(null,arguments)},g._memcpy=function(){return g.asm._memcpy.apply(null,arguments)},g._memset=function(){return g.asm._memset.apply(null,arguments)},g._sbrk=function(){return g.asm._sbrk.apply(null,arguments)},g._stb_vorbis_js_channels=function(){return g.asm._stb_vorbis_js_channels.apply(null,arguments)},g._stb_vorbis_js_close=function(){return g.asm._stb_vorbis_js_close.apply(null,arguments)},g._stb_vorbis_js_decode=function(){return g.asm._stb_vorbis_js_decode.apply(null,arguments)},g._stb_vorbis_js_open=function(){return g.asm._stb_vorbis_js_open.apply(null,arguments)},g._stb_vorbis_js_sample_rate=function(){return g.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},g.establishStackSpace=function(){return g.asm.establishStackSpace.apply(null,arguments)},g.getTempRet0=function(){return g.asm.getTempRet0.apply(null,arguments)},g.runPostSets=function(){return g.asm.runPostSets.apply(null,arguments)},g.setTempRet0=function(){return g.asm.setTempRet0.apply(null,arguments)},g.setThrew=function(){return g.asm.setThrew.apply(null,arguments)};var It=g.stackAlloc=function(){return g.asm.stackAlloc.apply(null,arguments)},dt=g.stackRestore=function(){return g.asm.stackRestore.apply(null,arguments)},Rt=g.stackSave=function(){return g.asm.stackSave.apply(null,arguments)};function Ke(v){this.name="ExitStatus",this.message="Program terminated with exit("+v+")",this.status=v}function ut(v){v=v||g.arguments,!(Je>0)&&((function(){if(g.preRun)for(typeof g.preRun=="function"&&(g.preRun=[g.preRun]);g.preRun.length;)Et(g.preRun.shift());ue(Le)})(),!(Je>0)&&(g.calledRun||(g.setStatus?(g.setStatus("Running..."),setTimeout(function(){setTimeout(function(){g.setStatus("")},1),M()},1)):M())));function M(){!g.calledRun&&(g.calledRun=!0,O||(Bt||(Bt=!0,ue(Ee)),ue(Re),g.onRuntimeInitialized&&g.onRuntimeInitialized(),(function(){if(g.postRun)for(typeof g.postRun=="function"&&(g.postRun=[g.postRun]);g.postRun.length;)tA(g.postRun.shift());ue(Oe)})()))}}function tt(v){throw g.onAbort&&g.onAbort(v),v!==void 0?(F(v),H(v),v=JSON.stringify(v)):v="",O=!0,"abort("+v+"). Build with -s ASSERTIONS=1 for more info."}if(g.dynCall_iii=function(){return g.asm.dynCall_iii.apply(null,arguments)},g.asm=qt,g.ccall=T,g.cwrap=function(M,P,_,ie){var ce=(_=_||[]).every(function(fe){return fe==="number"});return P!=="string"&&ce&&!ie?K(M):function(){return T(M,P,_,arguments,ie)}},Ke.prototype=Error(),Ke.prototype.constructor=Ke,Fe=function v(){g.calledRun||ut(),g.calledRun||(Fe=v)},g.run=ut,g.abort=tt,g.preInit)for(typeof g.preInit=="function"&&(g.preInit=[g.preInit]);g.preInit.length>0;)g.preInit.pop()();g.noExitRuntime=!0,ut(),g.onRuntimeInitialized=()=>{Fs=!0,In()},Wt.decode=function(v){return(function(P){if(!Fs)throw Error("SF3 decoder has not been initialized yet. Did you await synth.isReady?");var _={};function ie(Ft){return new Int32Array(g.HEAPU8.buffer,Ft,1)[0]}function ce(Ft,vt){var sA=new ArrayBuffer(vt*Float32Array.BYTES_PER_ELEMENT),Ve=new Float32Array(sA);return Ve.set(new Float32Array(g.HEAPU8.buffer,Ft,vt)),Ve}_.open=g.cwrap("stb_vorbis_js_open","number",[]),_.close=g.cwrap("stb_vorbis_js_close","void",["number"]),_.channels=g.cwrap("stb_vorbis_js_channels","number",["number"]),_.sampleRate=g.cwrap("stb_vorbis_js_sample_rate","number",["number"]),_.decode=g.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var fe,j,Te,Me,oe=_.open(),Be=(fe=P,j=P.byteLength,Te=g._malloc(j),(Me=new Uint8Array(g.HEAPU8.buffer,Te,j)).set(new Uint8Array(fe,0,j)),Me),he=g._malloc(4),xe=g._malloc(4),He=_.decode(oe,Be.byteOffset,Be.byteLength,he,xe);if(g._free(Be.byteOffset),He<0)throw _.close(oe),g._free(he),Error("stbvorbis decode failed: "+He);for(var At=_.channels(oe),mt=Array(At),ct=new Int32Array(g.HEAPU32.buffer,ie(he),At),st=0;st=0}getPatch(t,e){let A=this.keyMappings[t]?.[e];if(A)return A.patch;throw new Error("No modifier.")}};function La(t){for(this.keyModifierManager.setMappings(t.keyMappings);this.midiChannels.length>8,e.type&127]));for(let A=0;At.getSnapshot()),keyMappings:this.keyModifierManager.getMappings(),reverbProcessor:this.reverbProcessor.getSnapshot(),chorusProcessor:this.chorusProcessor.getSnapshot(),delayProcessor:this.delayProcessor.getSnapshot(),insertionProcessor:this.getInsertionSnapshot()}}var cn={effectsEnabled:!0,eventsEnabled:!0,voiceCap:350,autoAllocateVoices:!1,reverbGain:1,reverbLock:!1,chorusGain:1,chorusLock:!1,delayGain:1,delayLock:!1,insertionEffectLock:!1,drumLock:!1,blackMIDIMode:!1,deviceID:-1,gain:1,pan:0,keyShift:0,fineTune:0,interpolationType:Ra.hermite,nrpnParamLock:!1,monophonicRetrigger:!1};function Na(t,e){if(this.systemParameters[t]===e)return;let A=this.systemParameters[t];this.systemParameters[t]=e;for(let s of this.midiChannels)s.updateInternalParams();switch(t){default:break;case"voiceCap":{let s=Math.min(e,1e6);this.systemParameters.voiceCap=s;for(let a=s;athis.voices.length&&(l.warn(`Allocating ${s-this.voices.length} new voices!`),this.allocateNewVoices(s-this.voices.length));break}case"keyShift":A!==e&&this.stopAllChannels(!0)}}var fs=-15e3,ts=new Float32Array(15e3-fs+1);for(let t=0;thn?440*Math.pow(2,(t-6900)/1200):As[t-SA|0]}var Tt=-16600,Ut=new Float32Array(16e3-Tt+1);for(let t=0;t=gA&&(t.isActive=!1)}init(t){this.enteredRelease=!1,this.state=0,this.sampleTime=0,this.outputGain=0,this.canEndOnSilentSustain=t.modulatedGenerators[c.sustainVolEnv]>=gA,this.sustainCb=Math.min(Xe,t.modulatedGenerators[c.sustainVolEnv]),this.attackDuration=this.timecentsToSamples(t.modulatedGenerators[c.attackVolEnv]);let e=(60-t.targetKey)*t.modulatedGenerators[c.keyNumToVolEnvDecay],A=this.sustainCb/Xe;this.decayDuration=this.timecentsToSamples(t.modulatedGenerators[c.decayVolEnv]+e)*A,this.delayEnd=this.timecentsToSamples(t.modulatedGenerators[c.delayVolEnv]),this.attackEnd=this.attackDuration+this.delayEnd;let s=(60-t.targetKey)*t.modulatedGenerators[c.keyNumToVolEnvHold];this.holdEnd=this.timecentsToSamples(t.modulatedGenerators[c.holdVolEnv]+s)+this.attackEnd,this.decayEnd=this.decayDuration+this.holdEnd,this.attackEnd<=this.updateInterval&&(this.state=2)}process(t,e){let{releaseStartTimeSamples:A,releaseStartCb:s,releaseDuration:a,delayEnd:n,attackEnd:r,attackDuration:i,holdEnd:o,decayEnd:I,decayDuration:h,sustainCb:C}=this,B=this.sampleTime+=t;if(this.enteredRelease){let g=B-A,E=Xe-s;return this.attenuationCb=g/a*E+s,this.outputGain=Ut[this.attenuationCb-Tt|0]*e,this.attenuationCb=gA?(this.attenuationCb=Xe,this.outputGain=0,!1):(this.attenuationCb=C,this.outputGain=e*Ut[C-Tt|0],!0)}}timecentsToSamples(t){return Math.max(0,Math.floor(yA(t)*this.sampleRate))}},ve={monoSample:1,rightSample:2,leftSample:4,linkedSample:8,romMonoSample:32769,romRightSample:32770,romLeftSample:32772,romLinkedSample:32776},Ie={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},Ce={linear:0,concave:1,convex:2,switch:3};var Ye=16384,DA=Object.keys(Ce).length,lt=new Float32Array(Ye+1),kt=new Float32Array(Ye+1);lt[0]=0;lt[lt.length-1]=1;kt[0]=0;kt[kt.length-1]=1;for(let t=1;t.5?1:0,s?A*2-1:A;case Ce.concave:return s?(A=A*2-1,A<0?-lt[Math.trunc(A*-Ye)]:lt[Math.trunc(A*Ye)]):lt[Math.trunc(A*Ye)];case Ce.convex:return s?(A=A*2-1,A<0?-kt[Math.trunc(A*-Ye)]:kt[Math.trunc(A*Ye)]):kt[Math.trunc(A*Ye)]}}var qA=1,ns=new Float32Array(1e3);for(let t=0;t=n;)o-=r;let h=o|0,C=h+1;C>=n&&(C-=r);let B=o-h,g=a[C],E=a[h];A[I]=E+(g-E)*B,o+=s}else for(let I=0;I=i)return A.fill(0,I,t),!1;let B=o-h,g=a[C],E=a[h];A[I]=E+(g-E)*B,o+=s}return this.cursor=o,!0}},Oa=class extends us{process(t,e,A){let s=e*this.playbackStep,a=this.sampleData,{loopEnd:n,loopLength:r,end:i}=this,o=this.cursor;if(this.isLooping)for(let I=0;I=n;)o-=r;A[I]=a[o|0],o+=s}else for(let I=0;I=i)return A.fill(0,I,t),!1;A[I]=a[o|0],o+=s}return this.cursor=o,!0}},Ya=class extends us{process(t,e,A){let s=e*this.playbackStep,a=this.sampleData,{loopEnd:n,loopLength:r,end:i}=this,o=this.cursor;if(this.isLooping)for(let I=0;I=n;)o-=r;let h=o|0,C=h+1,B=h+2,g=h+3,E=o-h;C>=n&&(C-=r),B>=n&&(B-=r),g>=n&&(g-=r);let p=a[h],y=a[C],D=a[B],R=a[g],S=(D-p)*.5,w=y-D,F=S+w,H=F+w+(R-y)*.5,k=F+H;A[I]=((H*E-k)*E+S)*E+y,o+=s}else for(let I=0;I=i)return A.fill(0,I,t),!1;let p=a[h],y=a[C],D=a[B],R=a[g],S=(D-p)*.5,w=y-D,F=S+w,H=F+w+(R-y)*.5,k=F+H;A[I]=((H*E-k)*E+S)*E+y,o+=s}return this.cursor=o,!0}},qa=-2320,Ja=class{oscillators=[new Ha,new Oa,new Ya];wavetable=this.oscillators[cn.interpolationType];filter;generators=new Int16Array(Dt);modulatedGenerators=new Int16Array(Dt);modulators=new Array;modulatorValues=new Int16Array(64);modEnv=new xa;volEnv;resonanceOffset=0;priority=0;isActive=!1;hasRendered=!1;isInRelease=!1;isHeld=!1;channel=0;noteID=0;midiNote=0;targetKey=0;velocity=0;rootKey=0;pressure=0;gainModifier=1;loopingMode=0;startTime=0;releaseStartTime=1/0;tuningCents=0;tuningRatio=1;currentPan=0;portamentoFromKey=-1;portamentoDuration=0;overridePan=0;pitchOffset=0;reverbSend=1;chorusSend=1;delaySend=1;exclusiveClass=0;overrideReleaseVolEnv=0;vibLfoPhase=0;vibLfoStartTime=0;modLfoPhase=0;modLfoStartTime=0;constructor(t,e){this.volEnv=new Ua(t,e),this.filter=new Qs(t)}exclusiveRelease(t,e=ea){this.overrideReleaseVolEnv=qa,this.isInRelease=!1,this.releaseVoice(t,e)}releaseVoice(t,e=jn){this.releaseStartTime=t,this.releaseStartTime-this.startTime>e&1)>0}function JA(t){return t?1:0}var at=class as{isBipolar;isNegative;index;isCC;curveType;constructor(e=Ie.noController,A=Ce.linear,s=!1,a=!1,n=!1){this.isBipolar=a,this.isNegative=n,this.index=e,this.isCC=s,this.curveType=A}get sourceName(){return this.isCC?Object.keys(f).find(e=>f[e]===this.index)??this.index.toString():Object.keys(Ie).find(e=>Ie[e]===this.index)??this.index.toString()}get curveTypeName(){return Object.keys(Ce).find(e=>Ce[e]===this.curveType)??this.curveType.toString()}static fromSourceEnum(e){let A=St(e,9),s=St(e,8),a=St(e,7);return new as(e&127,e>>10&3,a,A,s)}static copyFrom(e){return new as(e.index,e.curveType,e.isCC,e.isBipolar,e.isNegative)}toString(){return`${this.sourceName} ${this.curveTypeName} ${this.isBipolar?"bipolar":"unipolar"} ${this.isNegative?"negative":"positive"}`}toSourceEnum(){return this.curveType<<10|JA(this.isBipolar)<<9|JA(this.isNegative)<<8|JA(this.isCC)<<7|this.index}isIdentical(e){return this.index===e.index&&this.isNegative===e.isNegative&&this.isCC===e.isCC&&this.isBipolar===e.isBipolar&&this.curveType===e.curveType}getValue(e,A,s){let a;if(this.isCC)a=e.midiControllers[this.index];else switch(this.index){default:case Ie.noController:a=16383;break;case Ie.noteOnVelocity:a=s.velocity<<7;break;case Ie.noteOnKeyNum:a=s.targetKey<<7;break;case Ie.polyPressure:a=s.pressure<<7;break;case Ie.channelPressure:a=e.midiParameters.pressure<<7;break;case Ie.pitchWheel:a=A;break;case Ie.pitchWheelRange:a=Math.floor(e.midiParameters.pitchWheelRange*128)}let n=(this.isBipolar?2:0)|(this.isNegative?1:0);return Bn[Ye*(this.curveType*DA+n)+a]}},Bn=new Float32Array(Ye*4*DA);for(let t=0;tc[e]===this.destination)}static isIdentical(e,A,s=!1){return e.primarySource.isIdentical(A.primarySource)&&e.secondarySource.isIdentical(A.secondarySource)&&e.destination===A.destination&&e.transformType===A.transformType&&(!s||e.transformAmount===A.transformAmount)}static copyFrom(e){return new rs(at.copyFrom(e.primarySource),at.copyFrom(e.secondarySource),e.destination,e.transformAmount,e.transformType)}toString(){return`Source: ${this.primarySource.toString()} +Secondary source: ${this.secondarySource.toString()} +to: ${this.destinationName} +amount: ${this.transformAmount}`+(this.transformType===2?"absolute value":"")}write(e,A){se(e,this.primarySource.toSourceEnum()),se(e,this.destination),se(e,this.transformAmount),se(e,this.secondarySource.toSourceEnum()),se(e,this.transformType),A&&A.mod++}sumTransform(e){let A=rs.copyFrom(this);return A.transformAmount+=e.transformAmount,A}},ye=class extends we{constructor(t,e,A,s,a){super(at.fromSourceEnum(t),at.fromSourceEnum(e),A,s,a),this.destination>ln&&(this.destination=c.invalid)}},Ka=[new ye($e(Ce.concave,!1,!0,!1,Ie.noteOnVelocity),0,c.initialAttenuation,960,0),new ye(129,0,c.vibLfoToPitch,50,0),new ye($e(Ce.concave,!1,!0,!0,f.mainVolume),0,c.initialAttenuation,960,0),new ye(13,0,c.vibLfoToPitch,50,0),new ye(526,16,c.fineTune,12700,0),new ye(650,0,c.pan,500,0),new ye($e(Ce.concave,!1,!0,!0,f.expression),0,c.initialAttenuation,960,0),new ye(219,0,c.reverbEffectsSend,200,0),new ye(221,0,c.chorusEffectsSend,200,0)],Va=[new ye($e(Ce.convex,!0,!1,!0,f.attackTime),0,c.attackVolEnv,6e3,0),new ye($e(Ce.linear,!0,!1,!0,f.releaseTime),0,c.releaseVolEnv,3600,0),new ye($e(Ce.linear,!0,!1,!0,f.decayTime),0,c.decayVolEnv,3600,0),new ye($e(Ce.linear,!0,!1,!0,f.brightness),0,c.initialFilterFc,9600,0),new ye(En,0,c.initialFilterQ,250,0),new ye($e(Ce.switch,!1,!1,!0,f.softPedal),0,c.initialAttenuation,50,0),new ye($e(Ce.switch,!1,!1,!0,f.softPedal),0,c.initialFilterFc,-2400,0),new ye($e(Ce.linear,!0,!1,!0,f.balance),0,c.pan,500,0)],dn=[...Ka,...Va],Pe=class{type;value=0;constructor(t,e,A=!0){if(this.type=t,e===void 0)throw new Error("No value provided.");if(this.value=Math.round(e),A){let s=ze[t];s!==void 0&&(this.value=Math.max(s.min,Math.min(s.max,this.value)))}}write(t){se(t,this.type),se(t,this.value)}toString(){return`${Object.keys(c).find(t=>c[t]===this.type)}: ${this.value}`}},jt=class{velRange={min:-1,max:127};keyRange={min:-1,max:127};generators=[];modulators=[];get hasKeyRange(){return this.keyRange.min!==-1}get hasVelRange(){return this.velRange.min!==-1}get fineTuning(){let t=this.getGenerator(c.coarseTune,0),e=this.getGenerator(c.fineTune,0);return t*100+e}set fineTuning(t){let e=Math.trunc(t/100),A=t%100;this.setGenerator(c.coarseTune,e),this.setGenerator(c.fineTune,A)}addToGenerator(t,e,A=!0){let s=this.getGenerator(t,ze[t].def);this.setGenerator(t,e+s,A)}setGenerator(t,e,A=!0){switch(t){case c.sampleID:throw new Error("Use setSample()");case c.instrument:throw new Error("Use setInstrument()");case c.velRange:case c.keyRange:throw new Error("Set the range manually")}if(e===null){this.generators=this.generators.filter(a=>a.type!==t);return}let s=this.generators.findIndex(a=>a.type===t);s===-1?this.addGenerators(new Pe(t,e,A)):this.generators[s]=new Pe(t,e,A)}addGenerators(...t){for(let e of t)switch(e.type){default:this.generators.push(e);break;case c.sampleID:case c.instrument:break;case c.velRange:this.velRange.min=e.value&127,this.velRange.max=e.value>>8&127;break;case c.keyRange:this.keyRange.min=e.value&127,this.keyRange.max=e.value>>8&127}}addModulators(...t){this.modulators.push(...t)}getGenerator(t,e){return this.generators.find(A=>A.type===t)?.value??e}copyFrom(t){this.generators=t.generators.map(e=>new Pe(e.type,e.value,!1)),this.modulators=t.modulators.map(we.copyFrom.bind(we)),this.velRange={...t.velRange},this.keyRange={...t.keyRange}}getWriteGenerators(t){let e=this.generators.filter(A=>A.type!==c.sampleID&&A.type!==c.instrument&&A.type!==c.keyRange&&A.type!==c.velRange);if(!t)throw new Error("No bank provided! ");return this.hasVelRange&&e.unshift(new Pe(c.velRange,this.velRange.max<<8|Math.max(this.velRange.min,0),!1)),this.hasKeyRange&&e.unshift(new Pe(c.keyRange,this.keyRange.max<<8|Math.max(this.keyRange.min,0),!1)),e}},Xa=48e3,vA=class{name;sampleRate;originalKey;pitchCorrection;linkedSample;sampleType;loopStart;loopEnd;linkedTo=[];dataOverridden=!0;compressedData;audioData;constructor(t,e,A,s,a,n,r){this.name=t,this.sampleRate=e,this.originalKey=A,this.pitchCorrection=s,this.loopStart=n,this.loopEnd=r,this.sampleType=a}get isCompressed(){return this.compressedData!==void 0}get isLinked(){return this.sampleType===ve.rightSample||this.sampleType===ve.leftSample||this.sampleType===ve.linkedSample}get useCount(){return this.linkedTo.length}getRawData(t){return this.compressedData&&t&&!this.dataOverridden?this.compressedData:this.encodeS16LE()}resampleData(t){let e=this.getAudioData(),A=t/this.sampleRate,s=new Float32Array(Math.floor(e.length*A));for(let a=0;a96e3)&&(this.resampleData(Xa),e=this.getAudioData());let A=await t(e,this.sampleRate);this.setCompressedData(A)}catch(e){l.warn(`Failed to compress ${this.name}. Leaving as uncompressed!`,e),this.compressedData=void 0}}setSampleType(t){if(this.sampleType=t,this.isLinked||(this.linkedSample&&(this.linkedSample.linkedSample=void 0,this.linkedSample.sampleType=t),this.linkedSample=void 0),(t&32768)>0)throw new Error("ROM samples are not supported.")}unlinkSample(){this.setSampleType(ve.monoSample)}setLinkedSample(t,e){if(t.linkedSample)throw new Error(`${t.name} is linked tp ${t.linkedSample.name}. Unlink it first.`);switch(this.linkedSample=t,t.linkedSample=this,e){case ve.leftSample:this.setSampleType(ve.leftSample),t.setSampleType(ve.rightSample);break;case ve.rightSample:this.setSampleType(ve.rightSample),t.setSampleType(ve.leftSample);break;case ve.linkedSample:this.setSampleType(ve.linkedSample),t.setSampleType(ve.linkedSample);break;default:throw new Error("Invalid sample type: "+e)}}linkTo(t){this.linkedTo.push(t)}unlinkFrom(t){let e=this.linkedTo.indexOf(t);if(e===-1){l.warn(`Cannot unlink ${t.name} from ${this.name}: not linked.`);return}this.linkedTo.splice(e,1)}getAudioData(){if(this.audioData)return this.audioData;if(this.isCompressed)return this.audioData=this.decodeVorbis(),this.audioData;throw new Error("Sample data is undefined for a BasicSample instance.")}setAudioData(t,e){this.audioData=t,this.sampleRate=e,this.dataOverridden=!0,this.compressedData=void 0}setCompressedData(t){this.audioData=void 0,this.compressedData=t,this.dataOverridden=!1}encodeS16LE(){let t=this.getAudioData(),e=new Int16Array(t.length),A=t.length;for(let s=0;s32767?a=32767:a<-32768&&(a=-32768),e[s]=a}return new te(e.buffer)}decodeVorbis(){if(this.audioData)return this.audioData;if(!this.compressedData)throw new Error("Compressed data is missing.");try{let t=FA.decode(this.compressedData).data[0];if(t===void 0)return l.warn(`Error decoding sample ${this.name}: Vorbis decode returned undefined.`),new Float32Array(0);for(let e=0;e=e.min&&A<=e.max}static addUniqueModulators(e,A){for(let s of A)e.some(a=>we.isIdentical(s,a))||e.push(s)}static subtractRanges(e,A){return{min:Math.max(e.min,A.min),max:Math.min(e.max,A.max)}}delete(){for(let e of this.zones)e.instrument?.unlinkFrom(this)}deleteZone(e){this.zones[e]?.instrument?.unlinkFrom(this),this.zones.splice(e,1)}createZone(e){let A=new Qn(this,e);return this.zones.push(A),A}preload(e,A){for(let s=e;swe.isIdentical(C,g));B===-1?I.push(C):I[B]=I[B].sumTransform(C)}let h=new Int16Array(is);for(let C of n.globalZone.generators)h[C.type]=C.value;for(let C of o.generators)h[C.type]=C.value;for(let C=0;C{I.push(...h.filter(C=>!I.some(B=>B.type===C.type)))},A=(I,h)=>{I.push(...h.filter(C=>!I.some(B=>we.isIdentical(C,B))))},s=new _t;s.name=this.name;let a=[],n=[],r=this.globalZone;a.push(...r.generators),n.push(...r.modulators);let i=r.keyRange,o=r.velRange;for(let I of this.zones){if(!I.instrument)throw new Error("No instrument in a preset zone.");let h=I.keyRange;I.hasKeyRange||(h=i);let C=I.velRange;I.hasVelRange||(C=o);let B=I.generators.map(F=>new Pe(F.type,F.value));e(B,a);let g=[...I.modulators];A(g,n);let E=I.instrument,p=E.zones,y=[],D=[],R=E.globalZone;y.push(...R.generators),D.push(...R.modulators);let S=R.keyRange,w=R.velRange;for(let F of p){if(!F.sample)throw new Error("No sample in an instrument zone.");let H=F.keyRange;F.hasKeyRange||(H=S);let k=F.velRange;if(F.hasVelRange||(k=w),H=ot.subtractRanges(H,h),k=ot.subtractRanges(k,C),H.maxnew Pe(K.type,K.value));e(u,y);let m=[...F.modulators];A(m,D);let J=[...m];for(let K of g){let ae=J.findIndex(U=>we.isIdentical(K,U));ae===-1?J.push(K):J[ae]=J[ae].sumTransform(K)}let O=u.map(K=>new Pe(K.type,K.value));for(let K of B){if(K.type===c.velRange||K.type===c.keyRange||K.type===c.instrument||K.type===c.endOper||K.type===c.sampleModes)continue;let ae=u.findIndex(U=>U.type===K.type);if(ae===-1){let U=ze[K.type].def+K.value;O.push(new Pe(K.type,U))}else{let U=O[ae].value+K.value;O[ae]=new Pe(K.type,U)}}O=O.filter(K=>K.type!==c.sampleID&&K.type!==c.keyRange&&K.type!==c.velRange&&K.type!==c.endOper&&K.type!==c.instrument&&(!(K.type in ze)||K.value!==ze[K.type].def));let q=s.createZone(F.sample);q.keyRange=H,q.velRange=k,q.keyRange.min===0&&q.keyRange.max===127&&(q.keyRange.min=-1),q.velRange.min===0&&q.velRange.max===127&&(q.velRange.min=-1),q.addGenerators(...O),q.addModulators(...J)}}return s}write(e,A,s){l.info(`%cWriting ${this.name}...`,d.info),Ne(e.pdta,this.name.slice(0,20),20),Ne(e.xdta,this.name.slice(20),20),se(e.pdta,this.program);let a=this.bankMSB;s?(a=this.bankMSB&127|(this.bankLSB&127)<<8,this.isGMGSDrum&&(a|=128)):this.isGMGSDrum?a=128:this.bankMSB===0&&(a=this.bankLSB),se(e.pdta,a),e.xdta.currentIndex+=4,se(e.pdta,A&65535),se(e.xdta,A>>16),ge(e.pdta,this.library),ge(e.pdta,this.genre),ge(e.pdta,this.morphology),e.xdta.currentIndex+=12}},Wa=new Set([c.velRange,c.keyRange,c.instrument,c.sampleID,c.exclusiveClass,c.endOper,c.sampleModes,c.startloopAddrsOffset,c.startloopAddrsCoarseOffset,c.endloopAddrsOffset,c.endloopAddrsCoarseOffset,c.startAddrsOffset,c.startAddrsCoarseOffset,c.endAddrOffset,c.endAddrsCoarseOffset,c.initialAttenuation,c.fineTune,c.coarseTune,c.keyNumToVolEnvHold,c.keyNumToVolEnvDecay,c.keyNumToModEnvHold,c.keyNumToModEnvDecay]),_t=class{name="";zones=[];globalZone=new jt;linkedTo=[];get useCount(){return this.linkedTo.length}createZone(t){let e=new fn(this,t);return this.zones.push(e),e}linkTo(t){this.linkedTo.push(t);for(let e of this.zones)e.useCount++}unlinkFrom(t){let e=this.linkedTo.indexOf(t);if(e===-1){l.warn(`Cannot unlink ${t.name} from ${this.name}: not linked.`);return}this.linkedTo.splice(e,1);for(let A of this.zones)A.useCount--}deleteUnusedZones(){this.zones=this.zones.filter(t=>{let e=t.useCount>0;return e||t.sample.unlinkFrom(this),e})}delete(){if(this.useCount>0)throw new Error(`Cannot delete an instrument that is used by: ${this.linkedTo.map(t=>t.name).toString()}.`);for(let t of this.zones)t.sample.unlinkFrom(this)}deleteZone(t,e=!1){let A=this.zones[t];return A.useCount-=1,A.useCount<1||e?(A.sample.unlinkFrom(this),this.zones.splice(t,1),!0):!1}globalize(){let t=this.globalZone;for(let A=0;A<58;A++){if(Wa.has(A))continue;A=A;let s={},a=ze[A]?.def||0;s[a]=0;for(let n of this.zones){let r=n.getGenerator(A,void 0);r===void 0?s[a]++:s[r]===void 0?s[r]=1:s[r]++;let i;switch(A){default:continue;case c.decayVolEnv:i=c.keyNumToVolEnvDecay;break;case c.holdVolEnv:i=c.keyNumToVolEnvHold;break;case c.decayModEnv:i=c.keyNumToModEnvDecay;break;case c.holdModEnv:i=c.keyNumToModEnvHold}if(n.getGenerator(i,void 0)!==void 0){s={};break}}if(Object.keys(s).length>0){let n=["0",0];for(let[i,o]of Object.entries(s))o>n[1]&&(n=[i,o]);let r=Number.parseInt(n[0]);r!==a&&t.setGenerator(A,r,!1);for(let i of this.zones){let o=i.getGenerator(A,void 0);o===void 0?r!==a&&i.setGenerator(A,a):o===r&&i.setGenerator(A,null)}}}let e=this.zones.length===0?[]:this.zones[0].modulators.map(A=>we.copyFrom(A));for(let A of e){let s=!0;for(let a of this.zones)s&&(a.modulators.find(n=>we.isIdentical(n,A))||(s=!1));if(s){t.addModulators(we.copyFrom(A));for(let a of this.zones){let n=a.modulators.find(r=>we.isIdentical(r,A));n&&n.transformAmount===A.transformAmount&&a.modulators.splice(a.modulators.indexOf(n),1)}}}}write(t,e){l.info(`%cWriting ${this.name}...`,d.info),Ne(t.pdta,this.name.slice(0,20),20),Ne(t.xdta,this.name.slice(20),20),se(t.pdta,e&65535),se(t.xdta,e>>>16)}};function za(t,e,A,s,a){let n=0,r=[],i=[];for(let C of t.samples){let B=C.getRawData(!0);n++,a?.(n/t.samples.length),l.info(`%cWrote sample %c${n}. ${C.name}%c of %c${t.samples.length}.`,d.info,d.recognized,d.info,d.recognized),r.push(B),i.push(B.length),C.isCompressed||r.push(new Uint8Array(92))}let o=x.getParts("smpl",r,s),I=x.getParts("sdta",o,s,!0),h=0;for(let[C,B]of t.samples.entries()){let g=i[C],E,p;B.isCompressed?(E=h,p=E+g):(E=h/2,p=E+g/2,h+=92),h+=g,e.push(E),A.push(p)}return I}var _a=class extends vA{linkedSampleIndex;s16leData;startByteOffset;endByteOffset;sampleID;constructor(t,e,A,s,a,n,r,i,o,I,h,C){let B=(I&16)>0;I&=-17,super(t,n,r,i,I,s-e/2,a-e/2),this.dataOverridden=!1,this.name=t,this.startByteOffset=e,this.endByteOffset=A,this.sampleID=C;let g=h instanceof te?h.currentIndex:0;h instanceof te?B?(this.loopStart+=this.startByteOffset/2,this.loopEnd+=this.startByteOffset/2,this.setCompressedData(h.slice(this.startByteOffset/2+g,this.endByteOffset/2+g))):this.s16leData=h.slice(g+this.startByteOffset,g+this.endByteOffset):this.setAudioData(h.slice(this.startByteOffset/2,this.endByteOffset/2),n),this.linkedSampleIndex=o}getLinkedSample(t){if(this.linkedSample||!this.isLinked)return;let e=t[this.linkedSampleIndex];e?e.linkedSample?(l.info(`%cInvalid linked sample for ${this.name}: ${e.name} is already linked to ${e.linkedSample.name}`,d.warn),this.unlinkSample()):this.setLinkedSample(e,this.sampleType):(l.info(`%cInvalid linked sample for ${this.name}. Setting to mono.`,d.warn),this.unlinkSample())}getAudioData(){if(this.audioData)return this.audioData;if(this.isCompressed)return super.getAudioData();if(!this.s16leData)throw console.error(this),new Error("Unexpected lack of audio data.");let t=this.endByteOffset-this.startByteOffset;if(t<1)return l.warn(`Invalid sample ${this.name}! Invalid length: ${t}`),new Float32Array(1);let e=new Float32Array(t/2),A=new Int16Array(this.s16leData.buffer),s=A.length;for(let a=0;at.data.currentIndex;){let n=$a(a,t.data,e);s.push(n),a++}if(s.pop(),A)for(let n of s)n.getLinkedSample(s);return s}function $a(t,e,A){let s=de(e,20),a=X(e,4)*2,n=X(e,4)*2,r=X(e,4),i=X(e,4),o=X(e,4),I=e[e.currentIndex++];I>127&&(I=60);let h=Wn(e[e.currentIndex++]),C=X(e,2),B=X(e,2);return new _a(s,a,n,r,i,o,I,h,C,B,A,t)}function ja(t,e,A,s){let n=46*(t.samples.length+1),r=new te(n),i=new te(n),o=0;for(let[I,h]of t.samples.entries()){Ne(r,h.name.slice(0,20),20),Ne(i,h.name.slice(20),20);let C=e[I];ge(r,C),i.currentIndex+=4;let B=A[I];ge(r,B),i.currentIndex+=4;let g=h.loopStart+C,E=h.loopEnd+C;h.isCompressed&&(g-=C,E-=C),ge(r,g),ge(r,E),ge(r,h.sampleRate),r[r.currentIndex++]=h.originalKey,r[r.currentIndex++]=h.pitchCorrection,i.currentIndex+=14;let p=h.linkedSample?t.samples.indexOf(h.linkedSample):0;se(r,Math.max(0,p)&65535),se(i,Math.max(0,p)>>16),o=Math.max(o,p);let y=h.sampleType;h.isCompressed&&(y|=16),se(r,y),i.currentIndex+=2}return Ne(r,"EOS",46),Ne(i,"EOS",46),{pdta:x.write("shdr",r,s),xdta:x.write("shdr",i,s)}}function Gs(t,e,A,s=!1){let a=A?t.presets:t.instruments,n=A?"pgen":"igen",r=A?"pmod":"imod",i=A?"pbag":"ibag",o=A?"phdr":"inst",I=A?38:22,h=0,C=new Array,B=0,g=new Array,E=new Array,p=new Array,y=0,D=new Array,R=m=>{C.push(h);let J=m.getWriteGenerators(t);h+=J.length,E.push(...J),g.push(B);let O=m.modulators;B+=O.length,p.push(...O)};for(let m of a){D.push(y),R(m.globalZone);for(let J of m.zones)R(J);y+=m.zones.length+1}E.push(new Pe(0,0,!1)),p.push(new ye(0,0,0,0,0)),C.push(h),g.push(B),D.push(y);let S=new te(E.length*4);for(let m of E)m.write(S);let w=new te(p.length*10);for(let m of p)m.write(w);let F=g.length*4,H={pdta:new te(F),xdta:new te(F)};for(let[m,J]of g.entries()){let O=C[m];se(H.pdta,O&65535),se(H.pdta,J&65535),se(H.xdta,O>>16),se(H.xdta,J>>16)}let k=(a.length+1)*I,u={pdta:new te(k),xdta:new te(k)};for(let[m,J]of a.entries())J.write(u,D[m],s);return A?(Ne(u.pdta,"EOP",20),u.pdta.currentIndex+=4,se(u.pdta,y&65535),u.pdta.currentIndex+=12,Ne(u.xdta,"",20),u.xdta.currentIndex+=4,se(u.xdta,y>>16),u.xdta.currentIndex+=12):(Ne(u.pdta,"EOI",20),se(u.pdta,y&65535),Ne(u.xdta,"",20),se(u.xdta,y>>16)),{writeXdta:Math.max(h,B,y)>65535,gen:{pdta:x.write(n,S,e),xdta:x.write(r,new te(4),e)},mod:{pdta:x.write(r,w,e),xdta:x.write(r,new te(10),e)},bag:{pdta:x.write(i,H.pdta,e),xdta:x.write(i,H.xdta,e)},hdr:{pdta:x.write(o,u.pdta,e),xdta:x.write(o,u.xdta,e)}}}var un={writeDefaultModulators:!0,writeExtendedLimits:!0,software:"SpessaSynth"},mn={rf64:!0,software:"SpessaSynth"};function er(t,e){let A=$t(e,un);return pn(t,A.software,A.writeDefaultModulators,A.writeExtendedLimits,!1,!1)}function tr(t,e){return pn(t,$t(e,mn).software,!0,!0,!0,!0)}function pn(t,e,A,s,a,n){l.groupCollapsed("%cSaving soundbank...",d.info),l.group("%cWriting INFO...",d.info);let r=[],i=(S,w)=>{w&&r.push(...x.getParts(S,[et(w,!0,!0)],n))},o=t.soundBankInfo;{let S=new te(4);se(S,o.version.major),se(S,o.version.minor),r.push(x.write("ifil",S,n))}if(i("isng",o.soundEngine),i("INAM",o.name),i("irom",o.romInfo),o.romVersion){let S=new te(4);se(S,o.romVersion.major),se(S,o.romVersion.minor),r.push(x.write("iver",S,n))}if(i("ICRD",Es(o.creationDate)),i("IENG",o.engineer),i("IPRD",o.product),i("ICOP",o.copyright),i("ICMT",o?.subject?(o?.comment?o.comment+` +`:"")+o.subject:o?.comment),i("ISFT",e),t.defaultModulators.some(S=>!dn.some(w=>we.isIdentical(w,S,!0)))&&A){let S=t.defaultModulators;l.info(`%cWriting %c${S.length}%c default modulators...`,d.info,d.recognized,d.info);let w=new te(10+S.length*10);for(let F of S)F.write(w);ls(w,0,10),r.push(...x.getParts("DMOD",[w],n))}l.groupEnd(),l.info("%cWriting SDTA...",d.info);let I=[],h=[],C=za(t,I,h,n);l.info("%cWriting PDTA...",d.info),l.info("%cWriting SHDR...",d.info);let B=ja(t,I,h,n);l.group("%cWriting instruments...",d.info);let g=Gs(t,n,!1);l.groupEnd(),l.group("%cWriting presets...",d.info);let E=Gs(t,n,!0,a);l.groupEnd();let p=[E.hdr,E.bag,E.mod,E.gen,g.hdr,g.bag,g.mod,g.gen,B],y=x.getParts("pdta",p.map(S=>S.pdta),n,!0);s&&(g.writeXdta||E.writeXdta||t.presets.some(S=>S.name.length>20)||t.instruments.some(S=>S.name.length>20)||t.samples.some(S=>S.name.length>20))&&(l.info("%cWriting the xdta chunk as writeExtendedLimits is enabled and at least one condition was met.",d.info,d.value),r.push(...x.getParts("xdta",p.map(S=>S.xdta),n,!0)));let D=x.getParts("INFO",r,n,!0);l.info("%cWriting the output file...",d.info);let R=x.writeParts(n?"RIFS":"RIFF",[et(a?"sfen":"sfbk"),...D,...C,...y],n);return l.info(`%cSaved successfully! Final file size: %c${R.length}`,d.info,d.recognized),l.groupEnd(),R.buffer}var Ot=class{static verifyHeader(t,...e){for(let A of e)if(t.header.toLowerCase()===A.toLowerCase())return;this.parsingError(`Invalid DLS chunk header! Expected "${e.join(", or ")}" got "${t.header.toLowerCase()}"`)}static verifyText(t,...e){for(let A of e)if(t.toLowerCase()===A.toLowerCase())return;this.parsingError(`FourCC error: Expected "${e.join(", or ")}" got "${t.toLowerCase()}"`)}static parsingError(t){throw l.groupEnd(),new Error(`DLS parse error: ${t} The file may be corrupted.`)}static verifyAndReadList(t,...e){this.verifyHeader(t,"LIST"),t.data.currentIndex=0,this.verifyText(de(t.data,4),...e);let A=[];for(;t.data.length>t.data.currentIndex;)A.push(x.read(t.data));return A}},Z={none:0,modLfo:1,velocity:2,keyNum:3,volEnv:4,modEnv:5,pitchWheel:6,polyPressure:7,channelPressure:8,vibratoLfo:9,modulationWheel:129,volume:135,pan:138,expression:139,chorus:221,reverb:219,pitchWheelRange:256,fineTune:257,coarseTune:258},N={none:0,gain:1,reserved:2,pitch:3,pan:4,keyNum:5,chorusSend:128,reverbSend:129,modLfoFreq:260,modLfoDelay:261,vibLfoFreq:276,vibLfoDelay:277,volEnvAttack:518,volEnvDecay:519,reservedEG1:520,volEnvRelease:521,volEnvSustain:522,volEnvDelay:523,volEnvHold:524,modEnvAttack:778,modEnvDecay:779,reservedEG2:780,modEnvRelease:781,modEnvSustain:782,modEnvDelay:783,modEnvHold:784,filterCutoff:1280,filterQ:1281},Ls={forward:0,loopAndRelease:1},IA=20,cA=16,xt=class Xt extends Ot{gain=0;unityNote=60;fineTune=0;loops=new Array;fulOptions=2;static copyFrom(e){let A=new Xt;return A.unityNote=e.unityNote,A.gain=e.gain,A.fineTune=e.fineTune,A.loops=e.loops.map(s=>({...s})),A.fulOptions=e.fulOptions,A}static read(e){this.verifyHeader(e,"wsmp");let A=new Xt,s=X(e.data,4);if(s!==IA&&l.warn(`Wsmp cbSize mismatch: got ${s}, expected ${IA}.`),A.unityNote=X(e.data,2),A.fineTune=Cs(e.data[e.data.currentIndex++],e.data[e.data.currentIndex++]),A.gain=X(e.data,4)|0,A.fulOptions=X(e.data,4),X(e.data,4)!==0){let a=X(e.data,4);a!==cA&&l.warn(`CbSize for loop in wsmp mismatch. Expected ${cA}, got ${a}.`);let n=X(e.data,4),r=X(e.data,4),i=X(e.data,4);A.loops.push({loopStart:r,loopLength:i,loopType:n})}return A}static fromSFSample(e){let A=new Xt;return A.unityNote=e.originalKey,A.fineTune=e.pitchCorrection,(e.loopEnd!==0||e.loopStart!==0)&&A.loops.push({loopStart:e.loopStart,loopLength:e.loopEnd-e.loopStart,loopType:Ls.forward}),A}static fromSFZone(e){let A=new Xt;A.unityNote=e.getGenerator(c.overridingRootKey,e.sample.originalKey),e.getGenerator(c.scaleTuning,100)===0&&e.keyRange.max-e.keyRange.min===0&&(A.unityNote=e.keyRange.min),A.fineTune=e.fineTuning+e.sample.pitchCorrection,A.gain=-(e.getGenerator(c.initialAttenuation,0)*.4)<<16;let s=e.getGenerator(c.sampleModes,0);if(s!==0){let a=e.sample.loopStart+e.getGenerator(c.startloopAddrsOffset,0)+e.getGenerator(c.startloopAddrsCoarseOffset,0)*32768,n=e.sample.loopEnd+e.getGenerator(c.endloopAddrsOffset,0)+e.getGenerator(c.endloopAddrsCoarseOffset,0)*32768,r;switch(s){case 1:default:r=0;break;case 3:r=1}A.loops.push({loopType:r,loopStart:a,loopLength:n-a})}return A}toSFZone(e,A){let s=0,a=this.loops[0];a&&(s=a.loopType===Ls.loopAndRelease?3:1),s!==0&&e.setGenerator(c.sampleModes,s);let n=-(this.gain>>16)/.4;if(n!==0&&e.setGenerator(c.initialAttenuation,n),e.fineTuning=this.fineTune-A.pitchCorrection,this.unityNote!==A.originalKey&&e.setGenerator(c.overridingRootKey,this.unityNote),a){let r=a.loopStart-A.loopStart,i=a.loopStart+a.loopLength-A.loopEnd;if(r!==0){let o=r%32768;e.setGenerator(c.startloopAddrsOffset,o);let I=Math.trunc(r/32768);I!==0&&e.setGenerator(c.startloopAddrsCoarseOffset,I)}if(i!==0){let o=i%32768;e.setGenerator(c.endloopAddrsOffset,o);let I=Math.trunc(i/32768);I!==0&&e.setGenerator(c.endloopAddrsCoarseOffset,I)}}}write(){let e=new te(IA+this.loops.length*cA);ge(e,IA),se(e,this.unityNote),se(e,this.fineTune),ge(e,this.gain),ge(e,this.fulOptions),ge(e,this.loops.length);for(let A of this.loops)ge(e,cA),ge(e,A.loopType),ge(e,A.loopStart),ge(e,A.loopLength);return x.write("wsmp",e)}},KA={PCM:1,ALAW:6};function Ar(t,e){let A=Math.pow(2,e*8-1),s=Math.pow(2,e*8),a,n=!1;e===1?(a=255,n=!0):a=A;let r=t.length/e,i=new Float32Array(r);if(e===2){let o=new Int16Array(t.buffer),I=o.length;for(let h=0;h=A&&(I-=s),i[o]=I/a)}return i}function sr(t,e){let A=t.length/e,s=new Float32Array(A);for(let a=0;a>4,o=r&15;i>0&&(o+=16),o=(o<<4)+8,i>1&&(o=o<127?o:-o)/32768}return s}var nr=class extends vA{wFormatTag;bytesPerSample;rawData;constructor(t,e,A,s,a,n,r,i,o){super(t,e,A,s,ve.monoSample,a,n),this.dataOverridden=!1,this.rawData=r.data,this.wFormatTag=i,this.bytesPerSample=o}getAudioData(){if(!this.rawData)return new Float32Array(0);if(!this.audioData){let t;switch(this.wFormatTag){default:l.warn(`Failed to decode sample. Unknown wFormatTag: ${this.wFormatTag}`),t=new Float32Array(this.rawData.length/this.bytesPerSample);break;case KA.PCM:t=Ar(this.rawData,this.bytesPerSample);break;case KA.ALAW:t=sr(this.rawData,this.bytesPerSample);break}this.setAudioData(t,this.sampleRate)}return this.audioData??new Float32Array(0)}getRawData(t){return this.dataOverridden||this.isCompressed?super.getRawData(t):this.wFormatTag===KA.PCM&&this.bytesPerSample===2?this.rawData:this.encodeS16LE()}},Ps=class os extends Ot{waveSample=new xt;wFormatTag;bytesPerSample;sampleRate;dataChunk;name="Unnamed sample";constructor(e,A,s,a){super(),this.wFormatTag=e,this.bytesPerSample=A,this.sampleRate=s,this.dataChunk=a}static read(e){let A=this.verifyAndReadList(e,"wave"),s=A.find(B=>B.header==="fmt ");if(!s)throw new Error("No fmt chunk in the wave file!");let a=X(s.data,2),n=X(s.data,2);if(n!==1)throw new Error(`Only mono samples are supported. Fmt reports ${n} channels.`);let r=X(s.data,4);X(s.data,4),X(s.data,2);let i=X(s.data,2)/8,o=A.find(B=>B.header==="data");if(!o)throw new Error("No data chunk in the WAVE chunk!");let I=new os(a,i,r,o),h=x.findListType(A,"INFO");if(h){let B=x.read(h.data);for(;B.header!=="INAM"&&h.data.currentIndexB.header==="wsmp");return C&&(I.waveSample=xt.read(C)),I}static fromSFSample(e){let A=e.getRawData(!1),s=new os(1,2,e.sampleRate,new x("data",A.length,new te(A.buffer)));return s.name=e.name,s.waveSample=xt.fromSFSample(e),s}toSFSample(e){let A=this.waveSample.unityNote,s=this.waveSample.fineTune,a=Math.trunc(s/100);A+=a,s-=a*100;let n=0,r=0,i=this.waveSample.loops?.[0];i&&(n=i.loopStart,r=i.loopStart+i.loopLength);let o=new nr(this.name,this.sampleRate,A,s,n,r,this.dataChunk,this.wFormatTag,this.bytesPerSample);e.addSamples(o)}write(){let e=this.writeFmt(),A=this.waveSample.write(),s=x.getParts("data",[this.dataChunk.data]),a=x.write("INAM",et(this.name,!0)),n=x.write("INFO",a,!1,!0);return l.info(`%cSaved %c${this.name}%c successfully!`,d.recognized,d.value,d.recognized),x.getParts("wave",[e,A,...s,n],!1,!0)}writeFmt(){let e=new te(18);return se(e,this.wFormatTag),se(e,1),ge(e,this.sampleRate),ge(e,this.sampleRate*2),se(e,2),se(e,this.bytesPerSample*8),x.write("fmt ",e)}},nt=class gs{source;transform;bipolar;invert;constructor(e=Z.none,A=Ce.linear,s=!1,a=!1){this.source=e,this.transform=A,this.bipolar=s,this.invert=a}get sourceName(){return Object.keys(Z).find(e=>Z[e]===this.source)??this.source.toString()}get transformName(){return Object.keys(Ce).find(e=>Ce[e]===this.transform)??this.transform.toString()}static copyFrom(e){return new gs(e.source,e.transform,e.bipolar,e.invert)}static fromSFSource(e){let A;if(e.isCC)switch(e.index){case f.modulationWheel:A=Z.modulationWheel;break;case f.mainVolume:A=Z.volume;break;case f.pan:A=Z.pan;break;case f.expression:A=Z.expression;break;case f.chorusDepth:A=Z.chorus;break;case f.reverbDepth:A=Z.reverb;break}else switch(e.index){case Ie.noController:A=Z.none;break;case Ie.noteOnKeyNum:A=Z.keyNum;break;case Ie.noteOnVelocity:A=Z.velocity;break;case Ie.pitchWheel:A=Z.pitchWheel;break;case Ie.pitchWheelRange:A=Z.pitchWheelRange;break;case Ie.polyPressure:A=Z.polyPressure;break;case Ie.channelPressure:A=Z.channelPressure}if(A!==void 0)return new gs(A,e.curveType,e.isBipolar,e.isNegative)}toString(){return`${this.sourceName} ${this.transformName} ${this.bipolar?"bipolar":"unipolar"} ${this.invert?"inverted":"positive"}`}toTransformFlag(){return this.transform|(this.bipolar?1:0)<<4|(this.invert?1:0)<<5}toSFSource(){let e,A=!1;switch(this.source){default:case Z.modLfo:case Z.vibratoLfo:case Z.coarseTune:case Z.fineTune:case Z.modEnv:return;case Z.keyNum:e=Ie.noteOnKeyNum;break;case Z.none:e=Ie.noController;break;case Z.modulationWheel:e=f.modulationWheel,A=!0;break;case Z.pan:e=f.pan,A=!0;break;case Z.reverb:e=f.reverbDepth,A=!0;break;case Z.chorus:e=f.chorusDepth,A=!0;break;case Z.expression:e=f.expression,A=!0;break;case Z.volume:e=f.mainVolume,A=!0;break;case Z.velocity:e=Ie.noteOnVelocity;break;case Z.polyPressure:e=Ie.polyPressure;break;case Z.channelPressure:e=Ie.channelPressure;break;case Z.pitchWheel:e=Ie.pitchWheel;break;case Z.pitchWheelRange:e=Ie.pitchWheelRange;break}if(e!==void 0)return new at(e,this.transform,A,this.bipolar,this.invert)}},yn=new ye(219,0,c.reverbEffectsSend,1e3,0),Sn=new ye(221,0,c.chorusEffectsSend,1e3,0);new ye(129,0,c.vibLfoToPitch,0,0);new ye(13,0,c.vibLfoToPitch,0,0);var ar=new Set([c.sampleModes,c.initialAttenuation,c.keyRange,c.velRange,c.sampleID,c.fineTune,c.coarseTune,c.startAddrsOffset,c.startAddrsCoarseOffset,c.endAddrOffset,c.endAddrsCoarseOffset,c.startloopAddrsOffset,c.startloopAddrsCoarseOffset,c.endloopAddrsOffset,c.endloopAddrsCoarseOffset,c.overridingRootKey,c.exclusiveClass]),Jt=class pt{source;control;destination;scale;transform;constructor(e=new nt,A=new nt,s,a,n){this.source=e,this.control=A,this.destination=s,this.transform=a,this.scale=n}get isStaticParameter(){return this.source.source===Z.none&&this.control.source===Z.none}get shortScale(){return this.scale>>16}get transformName(){return Object.keys(Ce).find(e=>Ce[e]===this.transform)??this.transform.toString()}get destinationName(){return Object.keys(N).find(e=>N[e]===this.destination)??this.destination.toString()}static read(e){let A=X(e,2),s=X(e,2),a=X(e,2),n=X(e,2),r=X(e,4)|0,i=n&15,o=new nt(s,n>>4&15,St(n,8),St(n,9));return new pt(new nt(A,n>>10&15,St(n,14),St(n,15)),o,a,i,r)}static fromSFModulator(e,A){let s=h=>{l.warn(`Failed converting SF modulator into DLS: + ${e.toString()} +(${h})`)};if(e.transformType!==0){s("Absolute transform type is not supported");return}if(we.isIdentical(e,Sn,!0)||we.isIdentical(e,yn,!0))return;let a=nt.fromSFSource(e.primarySource);if(!a){s("Invalid primary source");return}let n=nt.fromSFSource(e.secondarySource);if(!n){s("Invalid secondary source");return}let r=pt.fromSFDestination(e.destination,e.transformAmount);if(r===void 0){s("Invalid destination");return}let i=e.transformAmount,o;if(typeof r=="number")o=r;else if(o=r.destination,i=r.amount,r.source!==Z.none){if(n.source!==Z.none&&a.source!==Z.none){s("Articulation generators with secondary source are not supported");return}a.source!==Z.none&&(n=a),a=new nt(r.source,Ce.linear,r.isBipolar)}let I=new pt(a,n,o,0,i<<16);A.connectionBlocks.push(I)}static copyFrom(e){return new pt(nt.copyFrom(e.source),nt.copyFrom(e.control),e.destination,e.transform,e.scale)}static fromSFGenerator(e,A){if(ar.has(e.type))return;let s=o=>{l.warn(`Failed converting SF2 generator into DLS: + ${e.toString()} +(${o})`)},a=pt.fromSFDestination(e.type,e.value);if(a===void 0){s("Invalid type");return}let n=new nt,r,i=e.value;typeof a=="number"?r=a:(r=a.destination,i=a.amount,n.source=a.source,n.bipolar=a.isBipolar),A.connectionBlocks.push(new pt(n,new nt,r,0,i<<16))}static fromSFDestination(e,A){switch(e){default:return;case c.initialAttenuation:return{destination:N.gain,amount:-A,isBipolar:!1,source:Z.none};case c.fineTune:return N.pitch;case c.pan:return N.pan;case c.keyNum:return N.keyNum;case c.reverbEffectsSend:return N.reverbSend;case c.chorusEffectsSend:return N.chorusSend;case c.freqModLFO:return N.modLfoFreq;case c.delayModLFO:return N.modLfoDelay;case c.delayVibLFO:return N.vibLfoDelay;case c.freqVibLFO:return N.vibLfoFreq;case c.delayVolEnv:return N.volEnvDelay;case c.attackVolEnv:return N.volEnvAttack;case c.holdVolEnv:return N.volEnvHold;case c.decayVolEnv:return N.volEnvDecay;case c.sustainVolEnv:return{destination:N.volEnvSustain,amount:1e3-A,isBipolar:!1,source:Z.none};case c.releaseVolEnv:return N.volEnvRelease;case c.delayModEnv:return N.modEnvDelay;case c.attackModEnv:return N.modEnvAttack;case c.holdModEnv:return N.modEnvHold;case c.decayModEnv:return N.modEnvDecay;case c.sustainModEnv:return{destination:N.modEnvSustain,amount:1e3-A,isBipolar:!1,source:Z.none};case c.releaseModEnv:return N.modEnvRelease;case c.initialFilterFc:return N.filterCutoff;case c.initialFilterQ:return N.filterQ;case c.modEnvToFilterFc:return{source:Z.modEnv,destination:N.filterCutoff,amount:A,isBipolar:!1};case c.modEnvToPitch:return{source:Z.modEnv,destination:N.pitch,amount:A,isBipolar:!1};case c.modLfoToFilterFc:return{source:Z.modLfo,destination:N.filterCutoff,amount:A,isBipolar:!0};case c.modLfoToVolume:return{source:Z.modLfo,destination:N.gain,amount:A,isBipolar:!0};case c.modLfoToPitch:return{source:Z.modLfo,destination:N.pitch,amount:A,isBipolar:!0};case c.vibLfoToPitch:return{source:Z.vibratoLfo,destination:N.pitch,amount:A,isBipolar:!0};case c.keyNumToVolEnvHold:return{source:Z.keyNum,destination:N.volEnvHold,amount:A,isBipolar:!0};case c.keyNumToVolEnvDecay:return{source:Z.keyNum,destination:N.volEnvDecay,amount:A,isBipolar:!0};case c.keyNumToModEnvHold:return{source:Z.keyNum,destination:N.modEnvHold,amount:A,isBipolar:!0};case c.keyNumToModEnvDecay:return{source:Z.keyNum,destination:N.modEnvDecay,amount:A,isBipolar:!0};case c.scaleTuning:return{source:Z.keyNum,destination:N.pitch,amount:A*128,isBipolar:!1}}}toString(){return`Source: ${this.source.toString()}, +Control: ${this.control.toString()}, +Scale: ${this.scale} >> 16 = ${this.shortScale}, +Output transform: ${this.transformName} +Destination: ${this.destinationName}`}write(){let e=new te(12);return se(e,this.source.source),se(e,this.control.source),se(e,this.destination),se(e,this.transform|this.control.toTransformFlag()<<4|this.source.toTransformFlag()<<10),ge(e,this.scale),e}toSFGenerator(e){let A=this.destination,s=this.shortScale;switch(A){default:l.info(`%cFailed converting DLS articulator into SF generator: %c${this.toString()}%c +(invalid destination)`,d.warn,d.value,d.unrecognized);return;case N.pan:e.setGenerator(c.pan,s);break;case N.gain:e.addToGenerator(c.initialAttenuation,-s/.4);break;case N.filterCutoff:e.setGenerator(c.initialFilterFc,s);break;case N.filterQ:e.setGenerator(c.initialFilterQ,s);break;case N.modLfoFreq:e.setGenerator(c.freqModLFO,s);break;case N.modLfoDelay:e.setGenerator(c.delayModLFO,s);break;case N.vibLfoFreq:e.setGenerator(c.freqVibLFO,s);break;case N.vibLfoDelay:e.setGenerator(c.delayVibLFO,s);break;case N.volEnvDelay:e.setGenerator(c.delayVolEnv,s);break;case N.volEnvAttack:e.setGenerator(c.attackVolEnv,s);break;case N.volEnvHold:e.setGenerator(c.holdVolEnv,s);break;case N.volEnvDecay:e.setGenerator(c.decayVolEnv,s);break;case N.volEnvRelease:e.setGenerator(c.releaseVolEnv,s);break;case N.volEnvSustain:e.setGenerator(c.sustainVolEnv,1e3-s);break;case N.modEnvDelay:e.setGenerator(c.delayModEnv,s);break;case N.modEnvAttack:e.setGenerator(c.attackModEnv,s);break;case N.modEnvHold:e.setGenerator(c.holdModEnv,s);break;case N.modEnvDecay:e.setGenerator(c.decayModEnv,s);break;case N.modEnvRelease:e.setGenerator(c.releaseModEnv,s);break;case N.modEnvSustain:e.setGenerator(c.sustainModEnv,1e3-s);break;case N.reverbSend:e.setGenerator(c.reverbEffectsSend,s);break;case N.chorusSend:e.setGenerator(c.chorusEffectsSend,s);break;case N.pitch:e.fineTuning+=s;break}}toSFModulator(e){let A=this.shortScale,s,a,n=new at,r=this.toCombinedSFDestination();if(r){s=r;let o=this.control.toSFSource();if(!o){this.failedConversion("Invalid control");return}a=o}else{let o=this.toSFDestination();if(!o){this.failedConversion("Invalid destination");return}typeof o=="object"?(A=o.newAmount,s=o.gen):s=o;let I=this.source.toSFSource();if(!I){this.failedConversion("Invalid source");return}a=I;let h=this.control.toSFSource();if(!h){this.failedConversion("Invalid control");return}n=h}this.transform!==Ce.linear&&a.curveType===Ce.linear&&(a.curveType=this.transform),s===c.initialAttenuation&&((this.source.source===Z.velocity||this.source.source===Z.volume||this.source.source===Z.expression)&&(a.isNegative=!0),A=Math.min(960,Math.max(0,A)));let i=new we(a,n,s,A,0);e.addModulators(i)}toCombinedSFDestination(){let e=this.source.source,A=this.destination;return e===Z.vibratoLfo&&A===N.pitch?c.vibLfoToPitch:e===Z.modLfo&&A===N.pitch?c.modLfoToPitch:e===Z.modLfo&&A===N.filterCutoff?c.modLfoToFilterFc:e===Z.modLfo&&A===N.gain?c.modLfoToVolume:e===Z.modEnv&&A===N.filterCutoff?c.modEnvToFilterFc:e===Z.modEnv&&A===N.pitch?c.modEnvToPitch:void 0}failedConversion(e){l.info(`%cFailed converting DLS articulator into SF2: + %c${this.toString()}%c +(${e})`,d.warn,d.value,d.unrecognized)}toSFDestination(){let e=this.shortScale;switch(this.destination){default:case N.none:return;case N.pan:return c.pan;case N.gain:return{gen:c.initialAttenuation,newAmount:-e};case N.pitch:return c.fineTune;case N.keyNum:return c.overridingRootKey;case N.volEnvDelay:return c.delayVolEnv;case N.volEnvAttack:return c.attackVolEnv;case N.volEnvHold:return c.holdVolEnv;case N.volEnvDecay:return c.decayVolEnv;case N.volEnvSustain:return{gen:c.sustainVolEnv,newAmount:1e3-e};case N.volEnvRelease:return c.releaseVolEnv;case N.modEnvDelay:return c.delayModEnv;case N.modEnvAttack:return c.attackModEnv;case N.modEnvHold:return c.holdModEnv;case N.modEnvDecay:return c.decayModEnv;case N.modEnvSustain:return{gen:c.sustainModEnv,newAmount:1e3-e};case N.modEnvRelease:return c.releaseModEnv;case N.filterCutoff:return c.initialFilterFc;case N.filterQ:return c.initialFilterQ;case N.chorusSend:return c.chorusEffectsSend;case N.reverbSend:return c.reverbEffectsSend;case N.modLfoFreq:return c.freqModLFO;case N.modLfoDelay:return c.delayModLFO;case N.vibLfoFreq:return c.freqVibLFO;case N.vibLfoDelay:return c.delayVibLFO}}},kn=class extends Ot{connectionBlocks=new Array;mode="dls2";get length(){return this.connectionBlocks.length}copyFrom(t){this.mode=t.mode;for(let e of t.connectionBlocks)this.connectionBlocks.push(Jt.copyFrom(e))}fromSFZone(t){this.mode="dls2";let e=new jt;e.copyFrom(t);for(let A of e.generators){let s;switch(A.type){default:continue;case c.keyNumToVolEnvDecay:s=c.decayVolEnv;break;case c.keyNumToVolEnvHold:s=c.holdVolEnv;break;case c.keyNumToModEnvDecay:s=c.decayModEnv;break;case c.keyNumToModEnvHold:s=c.holdModEnv}let a=e.getGenerator(s,void 0),n=A.value*-128;if(a===void 0)continue;let r=a-60/128*n;e.setGenerator(A.type,n,!1),e.setGenerator(s,r,!1)}for(let A of e.generators)Jt.fromSFGenerator(A,this);for(let A of e.modulators)Jt.fromSFModulator(A,this)}read(t){let e=x.findListType(t,"lart"),A=x.findListType(t,"lar2");if(e)for(this.mode="dls1";e.data.currentIndexs.write()),A=x.getParts(this.mode==="dls2"?"art2":"art1",[t,...e]);return x.getParts(this.mode==="dls2"?"lar2":"lart",A,!0)}toSFZone(t){let e=(A,s,a,n)=>{let r=A/-128;if(t.setGenerator(s,r),r<=120){let i=Math.round(.46875*A),o=this.connectionBlocks.find(I=>I.isStaticParameter&&I.destination===n);o&&t.setGenerator(a,i+o.shortScale)}};for(let A of this.connectionBlocks){let s=A.shortScale,a=A.source.source,n=A.control.source,r=A.destination;if(A.isStaticParameter){A.toSFGenerator(t);continue}if(n===Z.none)if(a===Z.keyNum){if(r===N.pitch){t.setGenerator(c.scaleTuning,s/128);continue}if(r===N.modEnvHold||r===N.modEnvDecay||r===N.volEnvHold||r===N.volEnvDecay)continue}else{let i=A.toCombinedSFDestination();if(i){t.setGenerator(i,s);continue}}A.toSFModulator(t)}for(let A of this.connectionBlocks){if(A.source.source!==Z.keyNum)continue;let s=A.shortScale;switch(A.destination){default:case N.volEnvHold:e(s,c.keyNumToVolEnvHold,c.holdVolEnv,N.volEnvHold);break;case N.volEnvDecay:e(s,c.keyNumToVolEnvDecay,c.decayVolEnv,N.volEnvDecay);break;case N.modEnvHold:e(s,c.keyNumToModEnvHold,c.holdModEnv,N.modEnvHold);break;case N.modEnvDecay:e(s,c.keyNumToModEnvDecay,c.decayModEnv,N.modEnvDecay);break}}if(this.mode==="dls1"){t.setGenerator(c.delayVibLFO,t.getGenerator(c.delayModLFO,null)),t.setGenerator(c.freqVibLFO,t.getGenerator(c.freqModLFO,null)),t.setGenerator(c.vibLfoToPitch,t.getGenerator(c.modLfoToPitch,null)),t.setGenerator(c.modLfoToPitch,null);for(let A of t.modulators)A.destination===c.modLfoToPitch&&(A.destination=c.vibLfoToPitch)}}},VA=class BA{channel=1;tableIndex;fusOptions=0;phaseGroup=0;constructor(e){this.tableIndex=e}static copyFrom(e){let A=new BA(e.tableIndex);return A.channel=e.channel,A.phaseGroup=e.phaseGroup,A.fusOptions=e.fusOptions,A}static read(e){let A=X(e.data,2),s=X(e.data,2),a=X(e.data,4),n=new BA(X(e.data,4));return n.channel=a,n.fusOptions=A,n.phaseGroup=s,n}static fromSFZone(e,A){let s=e.indexOf(A.sample);if(s===-1)throw new Error(`Wave link error: Sample ${A.sample.name} does not exist in the sample list.`);let a=new BA(s);switch(A.sample.sampleType){default:case ve.leftSample:case ve.monoSample:a.channel=Math.trunc(1);break;case ve.rightSample:a.channel=2}return a}write(){let e=new te(12);return se(e,this.fusOptions),se(e,this.phaseGroup),ge(e,this.channel),ge(e,this.tableIndex),x.write("wlnk",e)}},EA=class Pt extends Ot{articulation=new kn;keyRange={min:0,max:127};velRange={min:0,max:127};keyGroup=0;fusOptions=0;usLayer=0;waveSample;waveLink;constructor(e,A){super(),this.waveSample=A,this.waveLink=e}static copyFrom(e){let A=new Pt(VA.copyFrom(e.waveLink),xt.copyFrom(e.waveSample));return A.keyGroup=e.keyGroup,A.keyRange={...e.keyRange},A.velRange={...e.velRange},A.usLayer=e.usLayer,A.fusOptions=e.fusOptions,A.articulation.copyFrom(e.articulation),A}static read(e,A){let s=this.verifyAndReadList(A,"rgn ","rgn2"),a=s.find(p=>p.header==="wsmp"),n=a?xt.read(a):void 0,r=s.find(p=>p.header==="wlnk");if(!r){l.warn("Invalid DLS region: missing 'wlnk' chunk! Discarding...");return}let i=VA.read(r),o=s.find(p=>p.header==="rgnh");if(!o){l.warn("Invalid DLS region: missing 'rgnh' chunk! Discarding...");return}let I=e[i.tableIndex];I||Pt.parsingError(`Invalid sample index: ${i.tableIndex}. Samples available: ${e.length}`),n??=I.waveSample;let h=new Pt(i,n),C=X(o.data,2),B=X(o.data,2),g=X(o.data,2),E=X(o.data,2);return g===0&&E===0&&(E=127,g=0),h.keyRange.max=B,h.keyRange.min=C,h.velRange.max=E,h.velRange.min=g,h.fusOptions=X(o.data,2),h.keyGroup=X(o.data,2),o.data.length-o.data.currentIndex>=2&&(h.usLayer=X(o.data,2)),h.articulation.read(s),h}static fromSFZone(e,A){let s=xt.fromSFZone(e),a=new Pt(VA.fromSFZone(A,e),s);return a.keyRange.min=Math.max(e.keyRange.min,0),a.keyRange.max=e.keyRange.max,a.velRange.min=Math.max(e.velRange.min,0),a.velRange.max=e.velRange.max,a.keyGroup=e.getGenerator(c.exclusiveClass,0),a.articulation.fromSFZone(e),a}write(){let e=[this.writeHeader(),this.waveSample.write(),this.waveLink.write(),...this.articulation.write()];return x.getParts("rgn2",e,!1,!0)}toSFZone(e,A){let s=A[this.waveLink.tableIndex];s||Pt.parsingError(`Invalid sample index: ${this.waveLink.tableIndex}`);let a=e.createZone(s);return a.keyRange=this.keyRange,a.velRange=this.velRange,this.keyRange.max===127&&this.keyRange.min===0&&(a.keyRange.min=-1),this.velRange.max===127&&this.velRange.min===0&&(a.velRange.min=-1),this.keyGroup!==0&&a.setGenerator(c.exclusiveClass,this.keyGroup),this.waveSample.toSFZone(a,s),this.articulation.toSFZone(a),a.generators=a.generators.filter(n=>n.value!==ze[n.type].def),a}writeHeader(){let e=new te(14);return se(e,Math.max(this.keyRange.min,0)),se(e,this.keyRange.max),se(e,Math.max(this.velRange.min,0)),se(e,this.velRange.max),se(e,this.fusOptions),se(e,this.keyGroup),se(e,this.usLayer),x.write("rgnh",e)}},XA=class dA extends Ot{articulation=new kn;regions=new Array;name="Unnamed";bankLSB=0;bankMSB=0;isGMGSDrum=!1;program=0;static copyFrom(e){let A=new dA;A.name=e.name,A.isGMGSDrum=e.isGMGSDrum,A.bankMSB=e.bankMSB,A.bankLSB=e.bankLSB,A.program=e.program,A.articulation.copyFrom(e.articulation);for(let s of e.regions)A.regions.push(EA.copyFrom(s));return A}static read(e,A){let s=this.verifyAndReadList(A,"ins "),a=s.find(C=>C.header==="insh");if(!a)throw l.groupEnd(),new Error("No instrument header!");let n="",r=x.findListType(s,"INFO");if(r){let C=x.read(r.data);for(;C.header!=="INAM";)C=x.read(r.data);n=de(C.data,C.data.length).trim()}n.length===0&&(n="Unnamed Instrument");let i=new dA;i.name=n;let o=X(a.data,4),I=X(a.data,4);i.program=X(a.data,4)&127,i.bankMSB=I>>>8&127,i.bankLSB=I&127,i.isGMGSDrum=I>>>31>0,l.groupCollapsed(`%cParsing %c"${n}"%c...`,d.info,d.recognized,d.info);let h=x.findListType(s,"lrgn");if(!h)throw l.groupEnd(),new Error("No region list!");i.articulation.read(s);for(let C=0;Ca.write());e.push(...x.getParts("lrgn",A,!1,!0)),this.articulation.length>0&&e.push(...this.articulation.write());let s=x.write("INAM",et(this.name,!0));return e.push(x.write("INFO",s,!1,!0)),l.groupEnd(),x.writeParts("ins ",e,!1,!0)}toSFPreset(e){let A=new zt(e);A.name=this.name,A.bankMSB=this.bankMSB,A.bankLSB=this.bankLSB,A.isGMGSDrum=this.isGMGSDrum,A.program=this.program;let s=new _t;s.name=this.name,A.createZone(s),this.articulation.toSFZone(s.globalZone);for(let a of this.regions)a.toSFZone(s,e.samples);s.globalize(),s.globalZone.modulators.some(a=>a.destination===c.reverbEffectsSend)||s.globalZone.addModulators(we.copyFrom(yn)),s.globalZone.modulators.some(a=>a.destination===c.chorusEffectsSend)||s.globalZone.addModulators(we.copyFrom(Sn)),s.globalZone.generators=s.globalZone.generators.filter(a=>a.value!==ze[a.type].def),e.addPresets(A),e.addInstruments(s)}writeHeader(){let e=new te(12);ge(e,this.regions.length);let A=(this.bankMSB&127)<<8|this.bankLSB&127;return this.isGMGSDrum&&(A|=1<<31),ge(e,A),ge(e,this.program&127),x.write("insh",e)}},Is={software:"SpessaSynth"},Dn=class cs extends Ot{samples=new Array;instruments=new Array;soundBankInfo={name:"Unnamed DLS sound bank",creationDate:new Date,software:"SpessaSynth",soundEngine:"DLS Level 2.2",product:"SpessaSynth DLS",version:{major:2,minor:4}};static read(e){if(!e)throw new Error("No data provided!");let A=new te(e);l.group("%cParsing DLS file...",d.info);let s=x.read(A,!1,!1);this.verifyHeader(s,"RIFF"),this.verifyText(de(A,4).toLowerCase(),"dls ");let a=[];for(;A.currentIndexE.header==="colh");if(!i)return this.parsingError("No colh chunk!"),5;let o=X(i.data,4);l.info(`%cInstruments amount: %c${o}`,d.info,d.recognized);let I=x.findListType(a,"wvpl");if(!I)return this.parsingError("No wvpl chunk!"),5;let h=this.verifyAndReadList(I,"wvpl");for(let E of h)n.samples.push(Ps.read(E));let C=x.findListType(a,"lins");if(!C)return this.parsingError("No lins chunk!"),5;let B=this.verifyAndReadList(C,"lins");l.groupCollapsed("%cLoading instruments...",d.info),B.length!==o&&l.warn(`Colh reported invalid amount of instruments. Detected ${B.length}, expected ${o}`);for(let E of B)n.instruments.push(XA.read(n.samples,E));l.groupEnd();let g=a.find(E=>E.header==="pgal");if(g){l.info("%cFound the instrument aliasing chunk!",d.recognized);let E=g.data;(E[0]!==0||E[1]!==1||E[2]!==2||E[3]!==3)&&(E.currentIndex+=4);let p=n.instruments.find(D=>De.isXGDrum(D.bankMSB)||D.isGMGSDrum);if(!p)return l.warn("MobileBAE aliasing chunk without a drum preset. Aborting!"),n;let y=E.slice(E.currentIndex,E.currentIndex+128);E.currentIndex+=128;for(let D=0;D<128;D++){let R=y[D];if(R===D)continue;let S=p.regions.find(F=>F.keyRange.max===R&&F.keyRange.min===R);if(!S){l.warn(`Invalid drum alias ${D} to ${R}: region does not exist.`);continue}let w=EA.copyFrom(S);w.keyRange.max=D,w.keyRange.min=D,p.regions.push(w)}for(E.currentIndex+=4;E.currentIndex>7&127,w=E[E.currentIndex++],F=E[E.currentIndex++];F!==0&&l.warn(`Invalid alias byte. Expected 0, got ${F}`);let H=X(E,2),k=H&127,u=H>>7&127,m=E[E.currentIndex++];F=E[E.currentIndex++],F!==0&&l.warn(`Invalid alias header. Expected 0, got ${F}`);let J=n.instruments.find(q=>q.bankLSB===k&&q.bankMSB===u&&q.program===m&&!q.isGMGSDrum);if(!J){l.warn(`Invalid alias. Missing instrument: ${k}:${u}:${m}`);continue}let O=XA.copyFrom(J);O.bankMSB=S,O.bankLSB=R,O.program=w,n.instruments.push(O)}}return l.info(`%cParsing finished! %c"${n.soundBankInfo.name||"UNNAMED"}"%c has %c${n.instruments.length}%c instruments and %c${n.samples.length}%c samples.`,d.info,d.recognized,d.info,d.recognized,d.info,d.recognized,d.info),l.groupEnd(),n}static fromSF(e,A){l.groupCollapsed("%cSaving SF2 to DLS level 2...",d.info);let s=new cs;s.soundBankInfo={...e.soundBankInfo};for(let a=0;aD.write()),!1,!0);l.info("%cSuccess!",d.recognized),l.groupEnd(),l.groupCollapsed("%cWriting WAVE samples...",d.info);let r=0,i=[],o=[],I=0;for(let D of this.samples){let R=D.write();A.progressFunction?.(I/this.samples.length),l.info(`%cWrote sample %c${I}. ${D.name}%c of %c${this.samples.length}.`,d.info,d.recognized,d.info,d.recognized),i.push(r),r+=R.reduce((S,w)=>S+w.length,0),o.push(...R),I++}let h=x.getParts("wvpl",o,!1,!0);l.info("%cSucceeded!",d.recognized);let C=new te(8+4*i.length);ge(C,8),ge(C,i.length);for(let D of i)ge(C,D);let B=x.write("ptbl",C);this.soundBankInfo.software=A.software;let g=[],E=this.soundBankInfo,p=(D,R)=>{R&&g.push(...x.getParts(D,[et(R,!0)]))};p("INAM",E.name),p("ICMT",E.comment),p("ICOP",E.copyright),p("ICRD",Es(E.creationDate)),p("IENG",E.engineer),p("IPRD",E.product),p("ISFT",A.software),p("ISBJ",E.subject),l.info("%cCombining everything...");let y=x.writeParts("RIFF",[et("DLS "),a,...n,B,...h,...x.getParts("INFO",g,!1,!0)]);return l.info("%cSaved successfully!",d.recognized),l.groupEnd(),y.buffer}toSF(){l.group("%cConverting DLS to SF2...",d.info);let e=new wn("dls");e.soundBankInfo.version.minor=4,e.soundBankInfo.version.major=2,e.soundBankInfo={...this.soundBankInfo};for(let A of this.samples)A.toSFSample(e);for(let A of this.instruments)A.toSFPreset(e);return e.flush(),l.info("%cConversion complete!",d.recognized),l.groupEnd(),e}},wn=class fA{static isSF3DecoderReady=FA.isInitialized;type;soundBankInfo={name:"Unnamed",creationDate:new Date,software:"SpessaSynth",soundEngine:"E-mu 10K2",version:{major:2,minor:4}};presets=[];samples=[];instruments=[];defaultModulators=dn.map(we.copyFrom.bind(we));customDefaultModulators=!1;constructor(e="sf2"){this.type=e}_isXGBank=!1;get isXGBank(){return this._isXGBank}static mergeSoundBanks(...e){let A=e.shift();if(!A)throw new Error("No sound banks provided!");let s=A.presets;for(;e.length>0;){let n=e?.shift()?.presets;if(n)for(let r of n)s.some(i=>r.matches(i))||s.push(r)}let a=new fA;return a.addCompletePresets(s),a.soundBankInfo={...A.soundBankInfo},a}static getSampleSoundBankFile(){let e=new fA,A=new Float32Array(128);for(let r=0;r<128;r++)A[r]=r/128*2-1;let s=new Za;s.name="Saw",s.originalKey=65,s.pitchCorrection=20,s.loopEnd=128,s.setAudioData(A,44100),e.addSamples(s);let a=new _t;a.name="Saw Wave",a.globalZone.addGenerators(new Pe(c.initialAttenuation,375),new Pe(c.releaseVolEnv,-1e3),new Pe(c.sampleModes,1)),a.createZone(s),a.createZone(s).setGenerator(c.fineTune,-9),e.addInstruments(a);let n=new zt(e);return n.name="Saw Wave",n.createZone(a),e.addPresets(n),e.soundBankInfo.name="SpessaSynth Sample Sound Bank",e.flush(),e.writeSF2()}static copyFrom(e){let A=new fA;for(let s of e.presets)A.clonePreset(s);return A.soundBankInfo={...e.soundBankInfo},A}addCompletePresets(e){this.addPresets(...e);let A=[];for(let a of e)for(let n of a.zones)n.instrument&&!A.includes(n.instrument)&&A.push(n.instrument);this.addInstruments(...A);let s=[];for(let a of A)for(let n of a.zones)n.sample&&!s.includes(n.sample)&&s.push(n.sample);this.addSamples(...s)}async setSampleFormat(e){let A=0,s=e.format,a=e.progressFunction;for(let n of this.samples){switch(s){default:case"pcm":n.setAudioData(n.getAudioData(),n.sampleRate);break;case"compressed":{let r=e.compressionFunction;if(!r)throw new Error(`No compression function supplied but '${s}' was requested.`);await n.compressSample(r)}}A++,a?.(A/this.samples.length),l.info(`%cEncoded sample %c${A}. ${n.name}%c of %c${this.samples.length}%c. Compressed: %c${n.isCompressed}%c.`,d.info,d.recognized,d.info,d.recognized,d.info,n.isCompressed?d.recognized:d.unrecognized,d.info)}switch(s){default:case"pcm":this.soundBankInfo.version.major=2,this.soundBankInfo.version.minor=4;break;case"compressed":this.soundBankInfo.version.major=3,this.soundBankInfo.version.minor=0}}writeDLS(e=Is){let A=e.progressFunction;return Dn.fromSF(this,A?s=>A(s/2):void 0).write({...e,progressFunction:A?s=>A(.5+s/2):void 0})}writeSF2(e=un){return er(this,e)}writeSFE(e=mn){return tr(this,e)}addPresets(...e){this.presets.push(...e)}addInstruments(...e){this.instruments.push(...e)}addSamples(...e){this.samples.push(...e)}cloneSample(e){let A=this.samples.find(a=>a.name===e.name);if(A)return A;let s=new vA(e.name,e.sampleRate,e.originalKey,e.pitchCorrection,e.sampleType,e.loopStart,e.loopEnd);if(e.isCompressed?s.setCompressedData(e.getRawData(!0)):s.setAudioData(e.getAudioData(),e.sampleRate),this.addSamples(s),e.linkedSample){let a=this.cloneSample(e.linkedSample);a.linkedSample||s.setLinkedSample(a,s.sampleType)}return s}cloneInstrument(e){let A=this.instruments.find(a=>a.name===e.name);if(A)return A;let s=new _t;s.name=e.name,s.globalZone.copyFrom(e.globalZone);for(let a of e.zones)s.createZone(this.cloneSample(a.sample)).copyFrom(a);return this.addInstruments(s),s}clonePreset(e){let A=this.presets.find(a=>a.name===e.name);if(A)return A;let s=new zt(this);s.name=e.name,s.bankMSB=e.bankMSB,s.bankLSB=e.bankLSB,s.isGMGSDrum=e.isGMGSDrum,s.program=e.program,s.library=e.library,s.genre=e.genre,s.morphology=e.morphology,s.globalZone.copyFrom(e.globalZone);for(let a of e.zones)s.createZone(this.cloneInstrument(a.instrument)).copyFrom(a);return this.addPresets(s),s}flush(){this.presets.sort(je.compare.bind(je)),this.parseInternal()}trim(e){let A=(s,a)=>{let n=0;for(let r=0;r=o.min&&C<=o.max&&[...B].some(g=>g>=I.min&&g<=I.max)){h=!0;break}h||(l.info(`%c${i.sample.name}%c removed from %c${s.name}%c.`,d.recognized,d.info,d.recognized,d.info),s.deleteZone(r)&&(n++,r--,l.info(`%c${i.sample.name}%c deleted`,d.recognized,d.info)),i.sample.useCount<1&&this.deleteSample(i.sample))}return n};l.groupCollapsed("%cTrimming sound bank...",d.info),l.info("Combinations to trim for:",e);for(let s=0;s=I.min&&B<=I.max&&[...g].some(E=>E>=h.min&&E<=h.max)){C=!0;let E=A(o.instrument,n);l.info(`%cTrimmed off %c${E}%c instrument zones from %c${o.instrument.name}`,d.info,d.recognized,d.info,d.recognized);break}C||(r++,a.deleteZone(i),o.instrument.useCount<1&&this.deleteInstrument(o.instrument),i--)}l.info(`%cTrimmed off %c${r}%c preset zones from %c${a.name}`,d.info,d.recognized,d.info,d.recognized),l.groupEnd()}}this.removeUnusedElements(),l.info("%cSound bank modified!",d.recognized),l.groupEnd()}removeUnusedElements(){this.instruments=this.instruments.filter(e=>{e.deleteUnusedZones();let A=e.useCount<1;return A&&e.delete(),!A}),this.samples=this.samples.filter(e=>{let A=e.useCount<1;return A&&e.unlinkSample(),!A})}deleteInstrument(e){e.delete(),this.instruments.splice(this.instruments.indexOf(e),1)}deletePreset(e){e.delete(),this.presets.splice(this.presets.indexOf(e),1)}deleteSample(e){e.unlinkSample(),this.samples.splice(this.samples.indexOf(e),1)}getPreset(e,A){return je.selectPatch(this.presets,e,A)}destroySoundBank(){this.presets.length=0,this.instruments.length=0,this.samples.length=0}parsingError(e){throw new Error(`SF parsing error: ${e} The file may be corrupted.`)}parseInternal(){this._isXGBank=!1;let e=new Set([0,1,2,3,4,5,6,7,8,9,16,17,24,25,26,27,28,29,30,31,32,33,40,41,48,56,57,58,64,65,66,126,127]);for(let A of this.presets)if(De.isXGDrum(A.bankMSB)&&(this._isXGBank=!0,!e.has(A.program))){this._isXGBank=!1,l.info(`%cThis bank is not valid XG. Preset %c${A.toString()}%c is not a valid XG drum. XG mode will use presets on bank 128.`,d.info,d.value,d.info);break}}printInfo(){for(let[e,A]of Object.entries(this.soundBankInfo))if(typeof A=="object"&&"major"in A){let s=A;l.info(`%c${e}: %c"${s.major}.${s.minor}"`,d.info,d.recognized)}else l.info(`%c${e}: %c${A.toLocaleString()}`,d.info,d.recognized)}},rr=class extends Pe{constructor(t){let e=t.currentIndex,A=t[e+1]<<8|t[e],s=Cs(t[e+2],t[e+3]);t.currentIndex+=4,super(A,s,!1)}};function Ns(t){let e=[];for(;t.data.length>t.data.currentIndex;)e.push(new rr(t.data));return e.pop(),e}function ir(t,e,A,s,a){let n=t.gen,r=t.mod,i=0,o=0;for(let I of a)for(let h=0;hD.type===c.instrument)?I.createSoundFontZone(y,g,s):(I.globalZone.addGenerators(...g),I.globalZone.addModulators(...y))}}var or=class extends zt{zoneStartIndex;zonesCount=0;constructor(t,e){super(e),this.name=de(t.data,20),this.program=X(t.data,2);let A=X(t.data,2);this.bankMSB=A&127,this.isGMGSDrum=(A&128)>0,this.bankLSB=A>>8,this.zoneStartIndex=X(t.data,2),this.library=X(t.data,4),this.genre=X(t.data,4),this.morphology=X(t.data,4)}createSoundFontZone(t,e,A){let s=e.find(r=>r.type===c.instrument),a;if(s)a=A[s.value];else throw new Error("No instrument ID found in preset zone.");if(!a)throw new Error(`Invalid instrument ID: ${s.value}, available instruments: ${A.length}`);let n=new Qn(this,a);return n.addGenerators(...e),n.addModulators(...t),this.zones.push(n),n}};function Ts(t,e){let A=[];for(;t.data.length>t.data.currentIndex;){let s=new or(t,e);if(A.length>0){let a=A[A.length-1];a.zonesCount=s.zoneStartIndex-a.zoneStartIndex}A.push(s)}return A.pop(),A}var gr=class extends _t{zoneStartIndex;zonesCount=0;constructor(t){super(),this.name=de(t.data,20),this.zoneStartIndex=X(t.data,2)}createSoundFontZone(t,e,A){let s=e.find(r=>r.type===c.sampleID),a;if(s)a=A[s.value];else throw new Error("No sample ID found in instrument zone.");if(!a)throw new Error(`Invalid sample ID: ${s.value}, available samples: ${A.length}`);let n=new fn(this,a);return n.addGenerators(...e),n.addModulators(...t),this.zones.push(n),n}};function Us(t){let e=[];for(;t.data.length>t.data.currentIndex;){let A=new gr(t);if(e.length>0){let s=e[e.length-1];s.zonesCount=A.zoneStartIndex-s.zoneStartIndex}e.push(A)}return e.pop(),e}function ZA(t){let e=[];for(;t.data.length>t.data.currentIndex;){let A=t.data,s=X(A,2),a=X(A,2),n=Cs(A[A.currentIndex++],A[A.currentIndex++]),r=X(A,2),i=X(A,2);e.push(new ye(s,r,a,n,i))}return e.pop(),e}function Ir(t,e,A,s,a){let n=t.gen,r=t.mod,i=0,o=0;for(let I of a)for(let h=0;hD.type===c.sampleID)?I.createSoundFontZone(y,g,s):(I.globalZone.addGenerators(...g),I.globalZone.addModulators(...y))}}function hA(t){let e=[],A=[];for(;t.data.length>t.data.currentIndex;)A.push(X(t.data,2)),e.push(X(t.data,2));return{mod:e,gen:A}}var cr=class extends wn{sampleDataStartIndex=0;constructor(t,e){super(e?"sfe":"sf2");let A=new te(t);l.group("%cParsing a SoundFont2 file...",d.info);let s=We(A,4).toLowerCase();this.verifyTexts(s,["riff","rifs"]);let a=s==="rifs";a&&l.info("%cRIFF64 Detected!",d.recognized),x.read(A,a,!1);let n=de(A,4).toLowerCase();this.verifyTexts(n,["sfbk","sfpk","sfen"]);let r=n==="sfpk",i=x.read(A,a);this.verifyHeader(i,"list");let o=de(i.data,4);this.verifyText(o,"info");let I;for(;i.data.length>i.data.currentIndex;){let Q=x.read(i.data,a),b=We(Q.data,Q.data.length),L=Q.header;switch(L){case"ifil":case"iver":{let z=X(Q.data,2),$=X(Q.data,2);L==="ifil"?this.soundBankInfo.version={major:z,minor:$}:this.soundBankInfo.romVersion={major:z,minor:$};break}case"DMOD":this.defaultModulators=ZA(Q),this.customDefaultModulators=!0;break;case"LIST":de(Q.data,4)==="xdta"&&(l.info("%cExtended SF2 found!",d.recognized),I=Q);break;case"ICRD":this.soundBankInfo.creationDate=ds(de(Q.data,Q.data.length));break;case"ISFT":this.soundBankInfo.software=b;break;case"IPRD":this.soundBankInfo.product=b;break;case"IENG":this.soundBankInfo.engineer=b;break;case"ICOP":this.soundBankInfo.copyright=b;break;case"INAM":this.soundBankInfo.name=b;break;case"ICMT":this.soundBankInfo.comment=b;break;case"irom":this.soundBankInfo.romInfo=b;break;case"isng":this.soundBankInfo.soundEngine=b}}this.printInfo();let h={};I!==void 0&&(h.phdr=x.read(I.data,a),h.pbag=x.read(I.data,a),h.pmod=x.read(I.data,a),h.pgen=x.read(I.data,a),h.inst=x.read(I.data,a),h.ibag=x.read(I.data,a),h.imod=x.read(I.data,a),h.igen=x.read(I.data,a),h.shdr=x.read(I.data,a));let C=x.read(A,a,!1);this.verifyHeader(C,"list"),this.verifyText(de(A,4),"sdta"),l.info("%cVerifying smpl chunk...",d.warn);let B=x.read(A,a,!1);this.verifyHeader(B,"smpl");let g;if(r){l.info("%cSF2Pack detected, attempting to decode the smpl chunk...",d.info);try{g=FA.decode(A.buffer.slice(A.currentIndex,A.currentIndex+C.size-4-C.headerSize)).data[0]}catch(Q){throw l.groupEnd(),new Error(`SF2Pack Ogg Vorbis decode error: ${Q}`,{cause:Q})}l.info(`%cDecoded the smpl chunk! Length: %c${g.length}`,d.info,d.value)}else g=A,this.sampleDataStartIndex=A.currentIndex;l.info(`%cSkipping sample chunk, length: %c${C.size-4-C.headerSize}`,d.info,d.value),A.currentIndex+=C.size-4-C.headerSize,l.info("%cLoading preset data chunk...",d.warn);let E=x.read(A,a);this.verifyHeader(E,"list"),de(E.data,4);let p=x.read(E.data,a);this.verifyHeader(p,"phdr");let y=x.read(E.data,a);this.verifyHeader(y,"pbag");let D=x.read(E.data,a);this.verifyHeader(D,"pmod");let R=x.read(E.data,a);this.verifyHeader(R,"pgen");let S=x.read(E.data,a);this.verifyHeader(S,"inst");let w=x.read(E.data,a);this.verifyHeader(w,"ibag");let F=x.read(E.data,a);this.verifyHeader(F,"imod");let H=x.read(E.data,a);this.verifyHeader(H,"igen");let k=x.read(E.data,a);this.verifyHeader(k,"shdr"),l.info("%cParsing samples...",d.info),A.currentIndex=this.sampleDataStartIndex;let u=vs(k,g,I===void 0);if(I&&h.shdr){let Q=vs(h.shdr,new Float32Array(1),!1);if(Q.length===u.length)for(let[b,L]of u.entries())L.name+=Q[b].name,L.linkedSampleIndex|=Q[b].linkedSampleIndex<<16}for(let Q of u)Q.name=Q.name.trim();this.samples.push(...u);let m=Ns(H),J=ZA(F),O=Us(S);if(I&&h.inst){let Q=Us(h.inst);if(Q.length===O.length){for(let[b,L]of O.entries())L.name+=Q[b].name,L.zoneStartIndex|=Q[b].zoneStartIndex<<16;for(let[b,L]of O.entries())b`"${A}"`).join(", ")} but got "${t.toLowerCase()}"`))}},eA=class{static fromArrayBuffer(t){let e=de(new te(t.slice(0,4)),4);if(e!=="RIFF"&&e!=="RIFS")throw new Error(`Expected 'RIFF' or 'RIFS' header, got '${e}'`);let A=de(new te(e==="RIFS"?t.slice(12,16):t.slice(8,12)),4).toLowerCase();return A==="dls "?this.loadDLS(t):new cr(t,A==="sfen")}static loadDLS(t){return Dn.read(t).toSF()}},wA=class Mn extends we{isEffectModulator;isDefaultResonantModulator;isModWheelModulator;constructor(e,A,s,a,n,r,i,o){super(e,A,s,a,n),this.isEffectModulator=r,this.isDefaultResonantModulator=i,this.isModWheelModulator=o}static fromData(e,A,s,a,n){let r=e.toSourceEnum(),i=A.toSourceEnum();return new Mn(e,A,s,a,n,(r===219||r===221)&&i===0&&(s===c.reverbEffectsSend||s===c.chorusEffectsSend),r===En&&i===0&&s===c.initialFilterQ,(e.isCC&&e.index===f.modulationWheel||A.isCC&&A.index===f.modulationWheel)&&(s===c.modLfoToPitch||s===c.vibLfoToPitch))}static fromModulator(e){return this.fromData(e.primarySource,e.secondarySource,e.destination,e.transformAmount,e.transformType)}},hr=class{sampleData;generators;modulators;exclusiveClass;targetKey;velocity;rootKey;loopStart;loopEnd;playbackStep;loopingMode;constructor(t,e,A,s){let a=t.sample,n=t.generators;this.modulators=t.modulators.map(wA.fromModulator.bind(wA)),this.generators=n,this.rootKey=a.originalKey,n[c.overridingRootKey]>-1&&(this.rootKey=n[c.overridingRootKey]),this.targetKey=e,n[c.keyNum]>-1&&(this.targetKey=n[c.keyNum]),this.velocity=A,n[c.velocity]>-1&&(this.velocity=n[c.velocity]),this.exclusiveClass=n[c.exclusiveClass],this.loopStart=a.loopStart,this.loopEnd=a.loopEnd,this.sampleData=a.getAudioData(),this.playbackStep=a.sampleRate/s*Math.pow(2,a.pitchCorrection/1200),this.loopingMode=n[c.sampleModes]}},xs=Math.PI/2,QA=-500,bn=500,ms=bn-QA,Rn=new Float32Array(ms+1),Fn=new Float32Array(ms+1);for(let t=QA;t<=bn;t++){let e=(t-QA)/ms,A=t-QA;Rn[A]=Math.cos(xs*e),Fn[A]=Math.sin(xs*e)}function lr(t,e,A,s,a,n){if(!t.isInRelease&&e>=t.releaseStartTime&&(t.isInRelease=!0,t.volEnv.startRelease(t),t.modEnv.startRelease(t),t.loopingMode===3&&(t.wavetable.isLooping=!1)),t.hasRendered=!0,!t.isActive)return;let r=this.synthCore,i=r.sampleRate,o=t.modulatedGenerators,I=t.targetKey,h=t.pitchOffset+o[c.fineTune]+this.octaveTuning[I]+this.currentTuning,C=o[c.coarseTune],B=r.tunings[this.preset.program*128+t.midiNote];if(B!==-1&&(I=Math.trunc(B),C+=B-I),t.portamentoFromKey>-1){let Q=Math.min((e-t.startTime)/t.portamentoDuration,1),b=I-t.portamentoFromKey;C-=b*(1-Q)}h+=(I-t.rootKey)*o[c.scaleTuning];let g=0,E=0,p=t.gainModifier*(1+o[c.amplitude]/1e3);if(e>=t.vibLfoStartTime){let Q=o[c.vibLfoToPitch],b=o[c.vibLfoToFilterFc],L=o[c.vibLfoAmplitudeDepth];if(Q!==0||b!==0||L!==0){let z=Math.max(0,ss(o[c.freqVibLFO])+o[c.vibLfoRate]/100)*n/i,$=1-4*Math.abs(t.vibLfoPhase-.5);(t.vibLfoPhase+=z)>=1&&(t.vibLfoPhase-=1),h+=$*Q,g+=$*b,p*=1-($+1)/2*(L/1e3)}}if(e>=t.modLfoStartTime){let Q=o[c.modLfoToPitch],b=o[c.modLfoToVolume],L=o[c.modLfoToFilterFc],z=o[c.modLfoAmplitudeDepth];if(Q!==0||L!==0||b!==0||z!==0){let $=Math.max(0,ss(o[c.freqModLFO])+o[c.modLfoRate]/100)*n/i,W=1-4*Math.abs(t.modLfoPhase-.5);(t.modLfoPhase+=$)>=1&&(t.modLfoPhase-=1),h+=W*Q,E+=-W*b,g+=W*L,p*=1-(W+1)/2*(z/1e3)}}let y=o[c.modEnvToPitch],D=o[c.modEnvToFilterFc];if(D!==0||y!==0){let Q=t.modEnv.process(t,e);g+=Q*D,h+=Q*y}E-=t.resonanceOffset;let R=h+C*100,S=R|0;S!==t.tuningCents&&(t.tuningCents=S,t.tuningRatio=Math.pow(2,R/1200));let w=kA(o[c.initialAttenuation])*kA(E);if(t.loopingMode===2&&!t.isInRelease){t.isActive=t.volEnv.process(n,w);return}let F=r.voiceBuffer;t.isActive=t.wavetable.process(n,t.tuningRatio,F);let H=t.volEnv.outputGain,k=t.volEnv.process(n,w),u=(t.volEnv.outputGain-H)/n;{let Q=t.filter,b=o[c.initialFilterFc];Q.initialized?Q.currentInitialFc+=(b-Q.currentInitialFc)*Qs.smoothingConstant:(Q.initialized=!0,Q.currentInitialFc=b);let L=Q.currentInitialFc+g,z=o[c.initialFilterQ];if(Q.currentInitialFc>13499&&L>13499&&z===0){Q.currentInitialFc=13500;for(let $=0;$1||Q.resonanceCb!==z)&&(Q.lastTargetCutoff=L,Q.resonanceCb=z,Q.calculateCoefficients(L));let{a0:$,a1:W,a2:V,a3:ee,a4:Ae}=Q,{x1:Y,x2:re,y1:ue,y2:Le}=Q;for(let Ee=0;Ee0){let Q=J.reverbGain*O*(U/1e3),b=r.reverbInput;for(let L=0;L0){let Q=J.chorusGain*(T/1e3)*O,b=r.chorusInput;for(let L=0;L0){let b=O*J.delayGain*((Q>>7)/127),L=r.delayInput;for(let z=0;z127||e<0)throw new Error("Invalid MIDI Controller.");if(t>=f.modulationWheelLSB&&t<=f.effectControl2LSB){let s=t-32;if(this.lockedControllers[s])return;this._midiControllers[s]=this._midiControllers[s]&16256|e&127,this.computeModulatorsAll(1,s)}if(!this.lockedControllers[t]){switch(this._midiControllers[t]=e<<7|this._midiControllers[t]&127,t){case f.omniModeOff:case f.omniModeOn:case f.allNotesOff:this.stopAllNotes();break;case f.allSoundOff:this.stopAllNotes(!0);break;case f.polyModeOn:this.stopAllNotes(!0),this.setMIDIParameter("polyMode",!0);break;case f.monoModeOn:this.stopAllNotes(!0),this.setMIDIParameter("polyMode",!1);break;case f.bankSelect:this.setBankMSB(e),this.channel%16===9&&De.isSystemXG(this.channelSystem)&&this.setBankMSB(127);break;case f.bankSelectLSB:this.setBankLSB(e);break;case f.variationDepth:this.synthCore.delayActive=!0;break;case f.registeredParameterLSB:case f.registeredParameterMSB:this._midiControllers[f.dataEntryMSB]=0,this.lastParameterIsRegistered=!0;break;case f.nonRegisteredParameterMSB:this.sf2NRPNGeneratorLSB=0,this._midiControllers[f.dataEntryMSB]=0,this.lastParameterIsRegistered=!1;break;case f.nonRegisteredParameterLSB:if(this._midiControllers[f.nonRegisteredParameterMSB]>>7===ke.SF2)switch(this.sf2NRPNGeneratorLSB%100!==0&&(this.sf2NRPNGeneratorLSB=0),e){case 100:this.sf2NRPNGeneratorLSB+=100;break;case 101:this.sf2NRPNGeneratorLSB+=1e3;break;case 102:this.sf2NRPNGeneratorLSB+=1e4;break;default:e<100&&(this.sf2NRPNGeneratorLSB+=e)}this._midiControllers[f.dataEntryMSB]=0,this.lastParameterIsRegistered=!1;break;case f.dataEntryMSB:case f.dataEntryLSB:this.dataEntry();break;case f.resetAllControllers:this.resetRP15();break;case f.sustainPedal:if(e<64){let s=0;if(this._voiceCount>0){for(let a of this.synthCore.voices)if(a.channel===this.channel&&a.isActive&&a.isHeld&&(a.isHeld=!1,a.releaseVoice(this.synthCore.currentTime),++s>=this._voiceCount))break}}break;case f.portamentoControl:this.lastPortamentoNote=e,this.portamentoForce=!0;break;default:this.computeModulatorsAll(1,t);break}A&&this.synthCore.callEvent("controllerChange",{channel:this.channel,controller:t,value:e})}}var Br=[c.delayModLFO,c.freqModLFO,c.delayVibLFO,c.freqVibLFO,c.delayModEnv,c.attackModEnv,c.holdModEnv,c.decayModEnv,c.sustainModEnv,c.releaseModEnv,c.delayVolEnv,c.attackVolEnv,c.holdVolEnv,c.decayVolEnv,c.sustainVolEnv,c.releaseVolEnv,c.fineTune,c.modLfoToPitch,c.vibLfoToPitch,c.modEnvToPitch,c.modLfoToVolume,c.initialFilterFc,c.initialFilterQ,c.modLfoToFilterFc,c.modEnvToFilterFc,c.chorusEffectsSend,c.reverbEffectsSend],ht=(t,e,A)=>Math.max(e,Math.min(A,t)),lA=t=>Math.max(-32768,1200*Math.log2(t/1e3)),Er=t=>6900+1200*Math.log2(t/440);function dr(t,e){let A=e&127;e-=8192;let s=Br[t];s||l.unsupported(`AWE32 LSB for ${this.channel}`,[t],"Invalid Generator Number");let a,n,r,i;switch(s){default:break;case c.delayModLFO:case c.delayVibLFO:case c.delayVolEnv:case c.delayModEnv:a=4*ht(e,0,5900),this.setGeneratorOverride(s,lA(a));break;case c.attackVolEnv:case c.attackModEnv:a=ht(e,0,5940),this.setGeneratorOverride(s,lA(a));break;case c.holdVolEnv:case c.holdModEnv:a=ht(e,0,8191),this.setGeneratorOverride(s,lA(a));break;case c.decayModEnv:case c.decayVolEnv:case c.releaseVolEnv:case c.releaseModEnv:a=4*ht(e,0,5940),this.setGeneratorOverride(s,lA(a));break;case c.freqVibLFO:case c.freqModLFO:n=.084*A,this.setGeneratorOverride(s,Er(n),!0);break;case c.sustainVolEnv:case c.sustainModEnv:r=A*7.5,this.setGeneratorOverride(s,r);break;case c.fineTune:this.setGeneratorOverride(s,e,!0);break;case c.modLfoToPitch:case c.vibLfoToPitch:i=ht(e,-127,127)*9.375,this.setGeneratorOverride(s,i,!0);break;case c.modEnvToPitch:i=ht(e,-127,127)*9.375,this.setGeneratorOverride(s,i);break;case c.modLfoToVolume:r=1.875*A,this.setGeneratorOverride(s,r,!0);break;case c.initialFilterFc:{let o=4335+59*A;this.setGeneratorOverride(s,o,!0);break}case c.initialFilterQ:r=215*(A/127),this.setGeneratorOverride(s,r,!0);break;case c.modLfoToFilterFc:i=ht(e,-64,63)*56.25,this.setGeneratorOverride(s,i,!0);break;case c.modEnvToFilterFc:i=ht(e,-64,63)*56.25,this.setGeneratorOverride(s,i);break;case c.chorusEffectsSend:case c.reverbEffectsSend:this.setGeneratorOverride(s,ht(e,0,255)*(1e3/255));break}}function fr(){let t=this._midiControllers[f.dataEntryMSB];if(this.lastParameterIsRegistered){let a=this._midiControllers[f.registeredParameterMSB]|this._midiControllers[f.registeredParameterLSB]>>7;switch(a){default:l.info(`%cUnrecognized RPN for %c${this.channel}%c: %c(0x${a.toString(16)})%c data value: %c${t}`,d.warn,d.recognized,d.warn,d.unrecognized,d.warn,d.value);break;case Ze.pitchWheelRange:{let n=t/128;this.setMIDIParameter("pitchWheelRange",n),l.coolInfo(`Pitch Wheel Range for ${this.channel}`,n,"semitones");break}case Ze.coarseTuning:{let n=(t>>7)-64;this.setMIDIParameter("keyShift",n),l.coolInfo(`Key shift for ${this.channel}`,n);break}case Ze.fineTuning:{let n=(t-8192)/81.92;this.setMIDIParameter("fineTune",n),l.coolInfo(`Fine tuning for ${this.channel}`,Math.round(n),"cents");break}case Ze.modulationDepth:{let n=t/1.28;this.setMIDIParameter("modulationDepth",n),l.coolInfo(`Modulation depth for ${this.channel}`,Math.round(n),"cents");break}case Ze.resetParameters:break}return}let e=this._midiControllers[f.nonRegisteredParameterMSB]>>7,A=this._midiControllers[f.nonRegisteredParameterLSB]>>7,s=t>>7;if(!(this.synthCore.systemParameters.drumLock&&e>=ke.drumPitch&&e<=ke.drumDelay))switch(e){default:l.info(`%cUnrecognized NRPN for %c${this.channel}%c: %c(0x${e.toString(16).toUpperCase()} 0x${A.toString(16).toUpperCase()})%c data value: %c${s}`,d.warn,d.recognized,d.warn,d.unrecognized,d.warn,d.value);break;case ke.partParameter:{let a=this._systemParameters.nrpnParamLock??this.synthCore.systemParameters.nrpnParamLock;switch(A){default:l.info(`%cUnrecognized NRPN for %c${this.channel}%c: %c(0x${e.toString(16)} 0x${A.toString(16)})%c data value: %c${s}`,d.warn,d.recognized,d.warn,d.unrecognized,d.warn,d.value);break;case Ue.vibratoRate:this.controllerChange(f.vibratoRate,s);break;case Ue.vibratoDepth:this.controllerChange(f.vibratoDepth,s);break;case Ue.vibratoDelay:this.controllerChange(f.vibratoDelay,s);break;case Ue.tvfCutoffFrequency:if(a)return;this.controllerChange(f.brightness,s),l.coolInfo(`Filter cutoff for ${this.channel}`,s.toString(),"");break;case Ue.tvfResonance:if(a)return;this.controllerChange(f.filterResonance,s),l.coolInfo(`Filter resonance for ${this.channel}`,s.toString(),"");break;case Ue.envelopeAttackTime:if(a)return;this.controllerChange(f.attackTime,s),l.coolInfo(`EG attack time for ${this.channel}`,s.toString(),"");break;case Ue.envelopeDecayTime:if(a)return;this.controllerChange(f.decayTime,s),l.coolInfo(`EG decay time for ${this.channel}`,s.toString(),"");break;case Ue.envelopeReleaseTime:if(a)return;this.controllerChange(f.releaseTime,s),l.coolInfo(`EG release time for ${this.channel}`,s.toString(),"");break}break}case ke.drumPitch:{let a=this.channelSystem==="xg"||this.patch.bankLSB===1?(s-64)*100:(s-64)*50;this.drumParams[A].pitch=a,l.coolInfo(`Drum ${A} pitch for ${this.channel}`,a,"cents");break}case ke.drumPitchFine:{let a=s-64;this.drumParams[A].pitch+=a,l.coolInfo(`Drum ${A} pitch fine for ${this.channel}`,this.drumParams[A].pitch,"cents");break}case ke.drumLevel:this.drumParams[A].gain=s/120,l.coolInfo(`Drum ${A} level for ${this.channel}`,s,"");break;case ke.drumPan:this.drumParams[A].pan=s,l.coolInfo(`Drum ${A} pan for ${this.channel}`,s,"");break;case ke.drumReverb:this.drumParams[A].reverbGain=s/127,l.coolInfo(`Drum ${A} reverb level for ${this.channel}`,s,"");break;case ke.drumChorus:this.drumParams[A].chorusGain=s/127,l.coolInfo(`Drum ${A} chorus level for ${this.channel}`,s,"");break;case ke.drumDelay:this.drumParams[A].delayGain=s/127,l.coolInfo(`Drum ${A} delay level for ${this.channel}`,t,"");break;case ke.awe32:dr.call(this,A,t);break;case ke.SF2:{if(A>100)break;let a=this.sf2NRPNGeneratorLSB,n=t-8192;this.setGeneratorOffset(a,n);break}}}var Qr=40;function ur(t){if(t<1)return 0;{let e=[1,2,4,8,16,32,64,80,96,112,120,124],A=[1,.5,.25,.125,.0625,.03125,.0625,.0625,.0625,.125,.25,1/3],s=[-.16653127382501215,.11863875218299408,.029479047361245264,-.005442312089231738,.1451520875973037,-.005056281449558275,-.005095486882876532,.03334009551111544,-.09361368678020432,.14132569702451822,-.15805565301011382,-.09918856955881927],a=[.028212773333433472,-.3388502064992847,-.15839529890929713,-.12398131766775483,-.2874848552685111,.012254866302537692,.005957797193345771,-.03745899330347374,.12911781869810196,-.15867193224162568,.504406322732748,.3786845131875458],n=[.7218950861255283,.5574536226347168,.47133893237025826,.48597095327079914,.44336276333518854,.6076986311801551,.30851975971827794,.30514889345633955,.3302511933827384,.153822885219165,.1302280559047337,.49865530675491687],r=[-2.2218487496163566,-1.6382721639824072,-1.3010299956639813,-.958607314841775,-.6020599913279624,-.3010299956639812,.31386722036915343,.6232492903979004,.9242792860618817,1.290034611362518,1.4265112613645752,1.9030899869919435],i=[2,4,8,16,32,64,80,96,112,120,124],o=-1;for(let h=i.length-1;h>=0;h--)if(i[h]Math.max(e,Math.min(A,t));function pr(t,e,A=!0){if(e<1){this.noteOff(t);return}let s=this.synthCore.systemParameters.blackMIDIMode;if(s&&this.synthCore.voiceCount>200&&e<40||s&&e<10||this._systemParameters.isMuted||!this.preset)return;let a=Kt(Math.floor(e*(this._midiParameters.velocitySenseDepth/64)+(this._midiParameters.velocitySenseOffset-64)*2),0,127),n=t+this.currentKeyShift;if(t>127||t<0)return;let r=this.preset.program,i=this.synthCore.tunings[r*128+t];i>=0&&(n=Math.trunc(i)),((this._systemParameters.monophonicRetrigger??this.synthCore.systemParameters.monophonicRetrigger)||this._midiParameters.assignMode===0)&&this.killNote(t);let o=this.synthCore.keyModifierManager.getVelocity(this.channel,t);o>-1&&(a=o);let I=this.synthCore.keyModifierManager.getGain(this.channel,t),h=this.lastPortamentoNote,C=this.portamentoForce||this._midiControllers[f.portamentoOnOff]>=8192,B=this._midiControllers[f.portamentoTime]>>7,g=C&&!this._drumChannel&&h>=0&&h!==t&&B>0,E=-1,p=0;if(g){let u=Math.abs(t-h);E=h,p=mr(B,u),this.portamentoForce=!1}this.lastPortamentoNote=t,this.playingNotes[t]=!0,this._midiParameters.polyMode||(this.lastMonoNote>=0&&this.lastMonoNote!==t&&this.killNote(this.lastMonoNote),this.lastMonoNote=t,this.lastMonoVelocity=e);let y=this.synthCore.getVoices(this.channel,n,a),D=0,R=0,S=0,w=1,F=1,H=1;if(this._midiParameters.randomPan&&(D=Math.round(Math.random()*1e3-500)),this._drumChannel){let u=this.drumParams[t];if(!u.rxNoteOn)return;let m=u.pan-64;if(m!==0)if(m===-64)D=Math.round(Math.random()*1e3-500);else{let J=(this._midiControllers[f.pan]>>7)-64;D=Math.max(-63,Math.min(m+J,63))/63*500||1}S=u.pitch,R=u.exclusiveClass,w=u.reverbGain,F=u.chorusGain,H=u.delayGain,I===1&&(I=u.gain)}let k=A?this.noteOnID[t]++:this.noteOnID[t];for(let u of y){let m=this.synthCore.assignVoice(),J=this.synthCore.currentTime;if(m.setup(J,this.channel,t,k),m.wavetable=m.oscillators[this._systemParameters.interpolationType??this.synthCore.systemParameters.interpolationType],m.targetKey=u.targetKey,m.velocity=u.velocity,m.generators.set(u.generators),m.exclusiveClass=R||u.exclusiveClass,m.rootKey=u.rootKey,m.loopingMode=u.loopingMode,m.wavetable.sampleData=u.sampleData,m.wavetable.playbackStep=u.playbackStep,this.dynamicModulators.active){m.modulators=[...u.modulators];for(let T of this.dynamicModulators.modulatorList){let Q=m.modulators.findIndex(b=>we.isIdentical(b,T.mod));Q===-1?m.modulators.push(T.mod):m.modulators[Q]=T.mod}}else m.modulators=u.modulators;if(m.modulators.length>m.modulatorValues.length&&(l.warn(`${m.modulators.length} modulators! Increasing modulatorValues table.`),m.modulatorValues=new Int16Array(m.modulators.length)),this.generators.overridesEnabled){let T=this.generators.overrides;for(let Q=0;Q0){for(let Q of this.synthCore.voices)if(Q.isActive&&Q.channel===this.channel&&Q.exclusiveClass===m.exclusiveClass&&Q.hasRendered&&(Q.exclusiveRelease(this.synthCore.currentTime),++T>=this._voiceCount))break}}this.computeModulators(m),m.volEnv.init(m),m.modEnv.init(m),m.filter.init(),m.vibLfoStartTime=J+yA(m.modulatedGenerators[c.delayVibLFO]),m.modLfoStartTime=J+yA(m.modulatedGenerators[c.delayModLFO]);let O=m.modulatedGenerators[c.startAddrsOffset]+m.modulatedGenerators[c.startAddrsCoarseOffset]*32768,q=m.modulatedGenerators[c.endAddrOffset]+m.modulatedGenerators[c.endAddrsCoarseOffset]*32768,K=m.modulatedGenerators[c.startloopAddrsOffset]+m.modulatedGenerators[c.startloopAddrsCoarseOffset]*32768,ae=m.modulatedGenerators[c.endloopAddrsOffset]+m.modulatedGenerators[c.endloopAddrsCoarseOffset]*32768,U=u.sampleData.length;if(m.wavetable.cursor=Kt(O,0,U-1),m.wavetable.end=Kt(U+q,0,U),m.wavetable.loopStart=Kt(u.loopStart+K,0,U),m.wavetable.loopEnd=Kt(u.loopEnd+ae,0,U),m.wavetable.loopEnd127||t<0)return;if(this.synthCore.systemParameters.blackMIDIMode&&!this._drumChannel||this._drumChannel&&this.drumParams[t].rxNoteOff){this.killNote(t),this.synthCore.callEvent("noteOff",{midiNote:t,channel:this.channel});return}this.playingNotes[t]=!1;let e=!this._midiParameters.polyMode,A=this._midiControllers[f.sustainPedal]>=8192&&!e,s=0,a=this.noteOffID[t];if(a0){for(let n of this.synthCore.voices)if(n.channel===this.channel&&n.isActive&&n.midiNote===t&&n.noteID===a&&!n.isInRelease&&(A?n.isHeld=!0:n.releaseVoice(this.synthCore.currentTime),++s>=this._voiceCount))break}if(this.synthCore.callEvent("noteOff",{midiNote:t,channel:this.channel}),e){let n=this.playingNotes.lastIndexOf(!0);n===-1?this.lastMonoNote=-1:this.lastMonoNote===t&&this.noteOn(n,this.lastMonoVelocity,!1)}}function Sr(t){if(this._systemParameters.presetLock)return;this.patch.program=t;let e=this.synthCore.soundBankManager.getPreset(this.patch,this.channelSystem);!e&&(e=this.synthCore.missingPresetHandler(this.patch,this.channelSystem),!e)||(this.preset=e,e.isDrum!==this._drumChannel&&this.setDrumFlag(e.isDrum),this.resetDrumParams(),this.synthCore.callEvent("programChange",{channel:this.channel,bankLSB:this.preset.bankLSB,bankMSB:this.preset.bankMSB,program:this.preset.program,name:this.preset.name,isGMGSDrum:this.preset.isGMGSDrum,isDrum:this.preset.isDrum}))}var kr=[wA.fromModulator(new ye($e(Ce.linear,!0,!1,!0,f.vibratoRate),0,c.vibLfoRate,1e3,0))],Dr=class{modulatorList=[];active=!1;channel;constructor(t){this.channel=t}resetModulators(){this.modulatorList=kr.map(t=>({mod:t,id:this.getModulatorID(t.primarySource.toSourceEnum(),t.destination,t.primarySource.isBipolar,t.primarySource.isNegative)})),this.active=!1}setupReceiver(t,e,A,s,a,n=!1){this.active=!0;let r=e-64,i=r/64,o=e/127;switch(t&15){case 0:{let I=Math.min(24,Math.max(-24,r));this.setModulator(A,s,c.fineTune,I*100,n),l.coolInfo(`Channel ${this.channel} ${a} pitch control`,I,"semitones");break}case 1:this.setModulator(A,s,c.initialFilterFc,i*9600,n),l.coolInfo(`Channel ${this.channel} ${a} filter control`,i*9600,"cents");break;case 2:this.setModulator(A,s,c.amplitude,i*1e3,n),l.coolInfo(`Channel ${this.channel} ${a} amplitude control`,i*100,"%");break;case 3:this.setModulator(A,s,c.vibLfoRate,i*1e3,n),l.coolInfo(`Channel ${this.channel} ${a} LFO1 rate control`,i*10,"Hz");break;case 4:this.setModulator(A,s,c.vibLfoToPitch,o*600,n),l.coolInfo(`Channel ${this.channel} ${a} LFO1 pitch depth control`,o*600,"cents");break;case 5:this.setModulator(A,s,c.vibLfoToFilterFc,o*2400,n),l.coolInfo(`Channel ${this.channel} ${a} LFO1 filter depth control`,o*2400,"cents");break;case 6:this.setModulator(A,s,c.vibLfoAmplitudeDepth,o*1e3,n),l.coolInfo(`Channel ${this.channel} ${a} LFO1 amplitude depth control`,o*100,"%");break;case 7:this.setModulator(A,s,c.modLfoRate,i*1e3,n),l.coolInfo(`Channel ${this.channel} ${a} LFO2 rate control`,i*10,"Hz");break;case 8:this.setModulator(A,s,c.modLfoToPitch,o*600,n),l.coolInfo(`Channel ${this.channel} ${a} LFO2 pitch depth control`,o*600,"cents");break;case 9:this.setModulator(A,s,c.modLfoToFilterFc,o*2400,n),l.coolInfo(`Channel ${this.channel} ${a} LFO2 filter depth control`,o*2400,"cents");break;case 10:this.setModulator(A,s,c.modLfoAmplitudeDepth,o*1e3,n),l.coolInfo(`Channel ${this.channel} ${a} LFO2 amplitude depth control`,o*100,"%");break}}setModulator(t,e,A,s,a=!1,n=!1){let r=this.getModulatorID(t,A,a,n);s===0&&this.deleteModulator(r);let i=this.modulatorList.find(o=>o.id===r);if(i)i.mod.transformAmount=s;else{let o=wA.fromData(new at(t,Ce.linear,e,a),new at,A,s,0);this.modulatorList.push({mod:o,id:r})}}getModulatorID(t,e,A,s){return`${t}-${e}-${A}-${s}`}deleteModulator(t){this.modulatorList=this.modulatorList.filter(e=>e.id!==t)}},wr=1e3/200;function Mr(t,e,A){let s=t.modulators[A];if(s.transformAmount===0)return t.modulatorValues[A]=0,0;let a=s.primarySource.getValue(this,e,t),n=s.secondarySource.getValue(this,e,t),r=s.transformAmount;s.isEffectModulator&&r<=1e3&&(r*=wr,r=Math.min(r,1e3));let i=a*n*r;return s.transformType===2&&(i=Math.abs(i)),s.isDefaultResonantModulator&&(t.resonanceOffset=Math.max(0,i/2)),s.isModWheelModulator&&(i*=this._midiParameters.modulationDepth/50),t.modulatorValues[A]=i,i}function br(t,e=-1,A=0){let s=t.modulators,a=t.generators;if(this.generators.offsetsEnabled){let o=this.generators.offsets;a=new Int16Array(a);for(let I=0;I({...t})),drumChannel:this._drumChannel,channel:this.channel}}function Fr(t){this.setDrums(t.drumChannel),this._midiControllers.set(t.midiControllers);for(let e=0;e<128;e++)this.lockController(e,t.lockedControllers[e]);this.pitchWheels.set(t.pitchWheels),this.octaveTuning.set(t.octaveTuning),this.perNotePitch=t.perNotePitch,this.generators.offsets.set(t.generators.offsets),this.generators.overrides.set(t.generators.overrides),this.generators.offsetsEnabled=t.generators.offsetsEnabled,this.generators.overridesEnabled=t.generators.overridesEnabled;for(let e=0;e<128;e++)this.drumParams[e]=vn.copyFrom(t.drumParams[e]);this.setSystemParameter("presetLock",!1),t.patch&&this.setPatch(t.patch),this.lockedSystem=t.lockedSystem;for(let[e,A]of Object.entries(t.midiParameters))this.setMIDIParameter(e,A);for(let[e,A]of Object.entries(t.lockedMIDIParameters))this.lockMIDIParameter(e,A);for(let[e,A]of Object.entries(t.systemParameters))this.setSystemParameter(e,A)}var Hs={pitchWheel:8192,pitchWheelRange:2,pressure:0,modulationDepth:50,rxChannel:0,polyMode:!0,keyShift:0,fineTune:0,randomPan:!1,assignMode:2,efxAssign:!1,cc1:16,cc2:17,drumMap:0,velocitySenseDepth:64,velocitySenseOffset:64};function vr(t,e){if(!this.lockedMIDIParameters[t]){switch(this._midiParameters[t]=e,t){case"pitchWheel":this.computeModulatorsAll(0,Ie.pitchWheel);break;case"pressure":this.computeModulatorsAll(0,Ie.channelPressure);break}this.updateInternalParams(),this.synthCore.callEvent("channelParamChange",{channel:this.channel,parameter:t,value:e})}}function Gr(t,e){this.lockedMIDIParameters[t]=e}var Lr={presetLock:!1,isMuted:!1,gain:1,pan:0,keyShift:0,fineTune:0,interpolationType:null,nrpnParamLock:null,monophonicRetrigger:null};function Pr(t,e){if(this._systemParameters[t]===e)return;let A=this._systemParameters[t];switch(this._systemParameters[t]=e,this.updateInternalParams(),t){default:break;case"presetLock":e&&(this.lockedSystem=this.synthCore.midiParameters.system);break;case"isMuted":e&&this.stopAllNotes(!0);break;case"keyShift":!this._drumChannel&&A!==e&&this.stopAllNotes(!0)}}var Nr=class{pitchWheels=new Int16Array(128).fill(8192);drumParams=[];dynamicModulators;sf2NRPNGeneratorLSB=0;patch={bankMSB:0,bankLSB:0,program:0,isGMGSDrum:!1};preset;lockedSystem="gs";channel;synthCore;setSystemParameter=Pr.bind(this);lockMIDIParameter=Gr.bind(this);noteOn=pr.bind(this);noteOff=yr.bind(this);programChange=Sr.bind(this);controllerChange=Cr.bind(this);reset=wa.bind(this);renderVoice=lr.bind(this);setMIDIParameter=vr.bind(this);lockedControllers=new Array(128).fill(!1);_midiControllers=new Int16Array(128);octaveTuning=new Int8Array(128);resetRP15=Ma.bind(this);dataEntry=fr.bind(this);lockedMIDIParameters=Object.fromEntries(Object.keys(Hs).map(t=>[t,!1]));_midiParameters={...Hs};_systemParameters={...Lr};noteOnID=new Array(128).fill(0);noteOffID=new Array(128).fill(0);lastParameterIsRegistered=!0;perNotePitch=!1;currentPan=0;currentTuning=0;currentKeyShift=0;currentGain=0;lastPortamentoNote=-1;portamentoForce=!1;lastMonoNote=-1;lastMonoVelocity=0;playingNotes=new Array(128).fill(!1);generators={offsets:new Int16Array(Dt),offsetsEnabled:!1,overrides:new Int16Array(Dt),overridesEnabled:!1};computeModulator=Mr.bind(this);computeModulators=br.bind(this);constructor(t,e,A){this.synthCore=t,this.preset=e,this.channel=A,this._midiParameters.rxChannel=A,this.dynamicModulators=new Dr(A),this.resetGeneratorOverrides(),this.resetGeneratorOffsets();for(let s=0;s<128;s++)this.drumParams.push(new vn);this.resetDrumParams()}_voiceCount=0;get voiceCount(){return this._voiceCount}set voiceCount(t){this._voiceCount=t}_drumChannel=!1;get drumChannel(){return this._drumChannel}get midiControllers(){return this._midiControllers}get systemParameters(){return this._systemParameters}get midiParameters(){return this._midiParameters}get channelSystem(){return this._systemParameters.presetLock?this.lockedSystem:this.synthCore.midiParameters.system}lockController(t,e){this.lockedControllers[t]=e}setDrums(t){if(De.isSystemXG(this.channelSystem))if(t)this.setBankMSB(De.getDrumBank(this.channelSystem)),this.setBankLSB(0);else{if(this.channel%16===9)throw new Error(`Cannot disable drums on channel ${this.channel} for XG.`);this.setBankMSB(0),this.setBankLSB(0)}else this.setGSDrums(t);this.setDrumFlag(t),this.programChange(this.patch.program)}stopAllNotes(t=!1){if(this.noteOnID.fill(0),this.noteOffID.fill(0),this.playingNotes.fill(!1),t){let e=0;if(this._voiceCount>0){for(let A of this.synthCore.voices)if(A.channel===this.channel&&A.isActive&&(A.isActive=!1,++e>=this._voiceCount))break}this.clearVoiceCount()}else{let e=0;if(this._voiceCount>0){for(let A of this.synthCore.voices)if(A.channel===this.channel&&A.isActive&&(A.releaseVoice(this.synthCore.currentTime),++e>=this._voiceCount))break}}this.synthCore.callEvent("stopAll",{channel:this.channel,force:t})}clearVoiceCount(){this._voiceCount=0}setOctaveTuning(t){if(t.length!==12)throw new Error("Tuning is not the length of 12.");for(let e=0;e<128;e++)this.octaveTuning[e]=t[e%12]}pitchWheel(t,e=-1){e===-1?(this.perNotePitch=!1,this.setMIDIParameter("pitchWheel",t)):(this.perNotePitch||this.pitchWheels.fill(this._midiParameters.pitchWheel),this.perNotePitch=!0,this.pitchWheels[e]=t,this.computeModulatorsAll(0,Ie.pitchWheel))}polyPressure(t,e){let A=0;if(this._voiceCount>0){for(let s of this.synthCore.voices)if(s.isActive&&s.channel===this.channel&&s.midiNote===t&&(s.pressure=e,this.computeModulators(s,0,Ie.polyPressure),++A>=this._voiceCount))break}this.synthCore.callEvent("polyPressure",{channel:this.channel,midiNote:t,pressure:e})}updateInternalParams(){let t=this.synthCore.systemParameters,e=this._systemParameters,A=this.synthCore.midiParameters,s=this._midiParameters,a=this._drumChannel?e.keyShift:t.keyShift+A.keyShift+e.keyShift+s.keyShift;this.currentKeyShift=Math.trunc(a),this.currentTuning=this._drumChannel?e.fineTune:t.fineTune+A.fineTune+e.fineTune+s.fineTune;let n=t.pan+A.pan+e.pan;this.currentPan=n*500,this.currentGain=ta*t.gain*Math.pow(A.volume,2)*e.gain}setPatch(t){this.setBankMSB(t.bankMSB),this.setBankLSB(t.bankLSB),this.setGSDrums(t.isGMGSDrum),this.programChange(t.program)}setGSDrums(t){t!==this.patch.isGMGSDrum&&(this.setBankLSB(0),this.setBankMSB(0),this.patch.isGMGSDrum=t)}killNote(t,e=-12e3){let A=0;if(this.noteOffID[t]=0,this.noteOnID[t]=0,this._voiceCount>0){for(let s of this.synthCore.voices)if(s.channel===this.channel&&s.isActive&&s.midiNote===t&&(s.overrideReleaseVolEnv=e,s.isInRelease=!1,s.releaseVoice(this.synthCore.currentTime),++A>=this._voiceCount))break}}applySnapshot(t){Fr.call(this,t)}getSnapshot(){return Rr.call(this)}setLastNote(t){this.lastPortamentoNote=t}destroy(){this.preset=void 0,this.lockedControllers=void 0,this._systemParameters=void 0,this._midiControllers=void 0,this._midiParameters=void 0}resetGeneratorOverrides(){this.generators.overrides.fill(_n),this.generators.overridesEnabled=!1}setGeneratorOverride(t,e,A=!1){if(this.generators.overrides[t]=e,this.generators.overridesEnabled=!0,A){let s=0;if(this._voiceCount>0){for(let a of this.synthCore.voices)if(a.channel===this.channel&&a.isActive&&(a.generators[t]=e,this.computeModulators(a),++s>=this._voiceCount))break}}}resetGeneratorOffsets(){this.generators.offsets.fill(0),this.generators.offsetsEnabled=!1}setGeneratorOffset(t,e){this.generators.offsets[t]=e*ze[t].nrpn,this.generators.offsetsEnabled=!0;let A=0;if(this._voiceCount>0){for(let s of this.synthCore.voices)if(s.channel===this.channel&&s.isActive&&(this.computeModulators(s),++A>=this._voiceCount))break}}resetDrumParams(){if(!(this.synthCore.systemParameters.drumLock||!this._drumChannel))for(let t=0;t<128;t++){let e=this.drumParams[t];e.pitch=0,e.gain=1,e.exclusiveClass=0,e.pan=64,e.reverbGain=pA[t]/127,e.chorusGain=this.channelSystem==="xg"?pA[t]/127:0,e.delayGain=0,e.rxNoteOn=!0,e.rxNoteOff=!1}}computeModulatorsAll(t,e){let A=0;if(this._voiceCount>0){for(let s of this.synthCore.voices)if(s.channel===this.channel&&s.isActive&&(this.computeModulators(s,t,e),++A>=this._voiceCount))break}}setBankMSB(t){this._systemParameters.presetLock||(this.patch.bankMSB=t)}setBankLSB(t){this._systemParameters.presetLock||(this.patch.bankLSB=t)}setDrumFlag(t){this._systemParameters.presetLock||!this.preset||this._drumChannel===t||(this._drumChannel=t,this.updateInternalParams())}},Tr=class extends zt{constructor(t,e){super(t.parentSoundBank,t.globalZone),this.bankMSB=De.addBankOffset(t.bankMSB,e,!0),this.name=t.name,this.bankLSB=t.bankLSB,this.isGMGSDrum=t.isGMGSDrum,this.program=t.program,this.genre=t.genre,this.morphology=t.morphology,this.library=t.library,this.zones=t.zones}},Ur=class{soundBankList=[];presetListChangeCallback;selectablePresetList=[];constructor(t){this.presetListChangeCallback=t}_presetList=[];get presetList(){return[...this._presetList]}get priorityOrder(){return this.soundBankList.map(t=>t.id)}set priorityOrder(t){this.soundBankList.sort((e,A)=>t.indexOf(e.id)-t.indexOf(A.id)),this.generatePresetList()}deleteSoundBank(t){if(this.soundBankList.length===0){l.warn("1 soundbank left. Aborting!");return}let e=this.soundBankList.findIndex(A=>A.id===t);if(e===-1)throw new Error(`No sound bank with id "${t}"`);this.soundBankList.splice(e,1),this.generatePresetList()}addSoundBank(t,e,A=0){let s=this.soundBankList.find(a=>a.id===e);s===void 0?this.soundBankList.push({id:e,soundBank:t,bankOffset:A}):(s.soundBank=t,s.bankOffset=A),this.generatePresetList()}getPreset(t,e){if(!(this.soundBankList.length===0||this.selectablePresetList.length===0))return je.selectPatch(this.selectablePresetList,t,e)}destroy(){for(let t of this.soundBankList)t.soundBank.destroySoundBank();this.soundBankList=[]}generatePresetList(){let t=new Array,e=new Set;for(let A of this.soundBankList){let s=A.soundBank,a=A.bankOffset;for(let n of s.presets){let r=new Tr(n,a);e.has(r.toMIDIString())||(e.add(r.toMIDIString()),t.push(r))}}t.sort(je.compare.bind(je)),this.selectablePresetList=t,this._presetList=t.map(A=>({bankMSB:A.bankMSB,bankLSB:A.bankLSB,program:A.program,isGMGSDrum:A.isGMGSDrum,name:A.name,isDrum:A.isDrum})),this.presetListChangeCallback()}};function Os(t,e,A){let s=t,a=e<<7|A;return t===127&&e===127&&A===127?-1:s+a*61e-6}function xr(t,e=0){switch(t[2]){case 4:switch(t[3]){default:l.gmFail("Device Control",t);break;case 1:{let A=t[5]<<7|t[4];this.setMIDIParameter("volume",A/16383),l.gmInfo("Master Volume",A);break}case 2:{let A=((t[5]<<7|t[4])-8192)/8192;this.setMIDIParameter("pan",A),l.gmInfo("Master Balance",A);break}case 3:{let A=((t[5]<<7|t[4])-8192)/81.92;this.setMIDIParameter("fineTune",A),l.gmInfo("Master Fine Tuning",A,"cents");break}case 4:{let A=t[5]-64;this.setMIDIParameter("keyShift",A),l.gmInfo("Master Coarse Tuning",A,"keys");break}case 5:if(t[4]!==1||t[5]!==1||t[6]!==1||t[7]!==1){l.gmFail("Global Parameter Control",t);break}switch(t[8]){default:l.gmFail("Global Parameter Control",t);break;case 1:{let A=t[10];switch(t[9]){default:l.gmFail("Reverb Parameter Control",t);break;case 0:{let s=A===8?5:A;this.setReverbMacro(s),l.gmInfo("Reverb Type",s);break}case 1:this.reverbProcessor.time=A,l.gmInfo("Reverb Time",A)}break}case 2:{let A=t[10];switch(t[9]){default:l.gmFail("Chorus Parameter Control",t);break;case 0:this.setChorusMacro(A),l.gmInfo("Chorus Type",A);break;case 1:this.chorusProcessor.rate=A,l.gmInfo("Chorus Mod Rate",A);break;case 2:this.chorusProcessor.depth=A,l.gmInfo("Chorus Mod Depth",A);break;case 3:this.chorusProcessor.feedback=A,l.gmInfo("Chorus Mod Feedback",A);break;case 4:this.chorusProcessor.sendLevelToReverb=A,l.gmInfo("Chorus Send to Reverb",A);break}}}}break;case 9:switch(t[3]){default:l.gmFail("System Exclusive",t);break;case 1:l.coolInfo("MIDI System","General MIDI 1"),this.reset("gm");break;case 2:l.coolInfo("MIDI System","Roland GS"),this.reset("gs");break;case 3:l.coolInfo("MIDI System","General MIDI 2"),this.reset("gm2");break}break;case 8:{let A=4;switch(t[3]){case 1:{let s=t[A++],a=We(t,16,A);if(A+=16,t.length<384){l.warn(`The Bulk Tuning Dump is too short! (${t.length} bytes, at least 384 are expected)`);return}for(let n=0;n<128;n++)this.tunings[s*128+n]=Os(t[A++],t[A++],t[A++]);l.gmInfo("Bulk Tuning Dump",`${a}, program ${s}`);break}case 2:case 7:{t[3]===7&&A++;let s=t[A++],a=t[A++];for(let n=0;n>1&1)===1&&this.midiChannels[15+e].setOctaveTuning(s);for(let a=0;a<7;a++)(t[5]>>a&1)===1&&this.midiChannels[7+a+e].setOctaveTuning(s);for(let a=0;a<7;a++)(t[6]>>a&1)===1&&this.midiChannels[a+e].setOctaveTuning(s);l.gmInfo("Octave Scale Tuning",s.join(" "));break}default:l.gmFail("MIDI Tuning Standard",t);break}break}default:l.gmFail("Universal System Exclusive",t)}}function Hr(t,e=0){if(t[3]===18)switch(t[2]){case 66:{let A=t[4],s=t[5],a=t[6],n=Math.min(t[7],127);if(A===0&&s===0&&a===127&&(n===0||n===1)){if(n===1)for(l.gsInfo("Mode","Double Module");this.midiChannels.length<32;)this.createMIDIChannel(!0);l.coolInfo("MIDI System","Roland GS"),this.reset("gs");return}if(A===64||A===80){if(A===80&&(e+=16),s===0){switch(a){case 0:{let r=((n<<12|t[8]<<8|t[9]<<4|t[10])-1024)/10;this.setMIDIParameter("fineTune",r),l.gsInfo("Master Tune",r,"cents");break}case 4:l.gsInfo("Master Volume",n),this.setMIDIParameter("volume",n/127);break;case 5:{let r=n-64;l.gsInfo("Master Key-Shift",r,"keys"),this.setMIDIParameter("keyShift",r);break}case 6:{let r=(n-64)/63;l.gsInfo("Master Pan",r),this.setMIDIParameter("pan",r);break}case 127:n===0?(l.coolInfo("MIDI System","Roland GS"),this.reset("gs")):n===127&&(l.coolInfo("MIDI System","General MIDI 1"),this.reset("gm"));break;default:l.gsFail("System Parameter",t);break}return}if(s===1){let r=a>=48&&a<=55,i=a>=56&&a<=64,o=a>=80&&a<=90;if(r&&this.systemParameters.reverbLock||i&&this.systemParameters.chorusLock||o&&this.systemParameters.delayLock)return;switch(this.delayActive||=a===64||o,a){default:l.gsFail("Patch Common Parameter",[a]);break;case 0:{let I=We(t,16,7);l.gsInfo("Patch name",I),this.callEvent("displayMessage",[...t]);break}case 48:this.setReverbMacro(n),l.gsInfo("Reverb Macro",n);break;case 49:this.reverbProcessor.character=n,l.gsInfo("Reverb Character",n),this.callEvent("effectChange",{effect:"reverb",parameter:"character",value:n});break;case 50:this.reverbProcessor.preLowpass=n,l.gsInfo("Reverb Pre-LPF",n),this.callEvent("effectChange",{effect:"reverb",parameter:"preLowpass",value:n});break;case 51:this.reverbProcessor.level=n,l.gsInfo("Reverb Level",n),this.callEvent("effectChange",{effect:"reverb",parameter:"level",value:n});break;case 52:this.reverbProcessor.time=n,l.gsInfo("Reverb Time",n),this.callEvent("effectChange",{effect:"reverb",parameter:"time",value:n});break;case 53:this.reverbProcessor.delayFeedback=n,l.gsInfo("Reverb Delay Feedback",n),this.callEvent("effectChange",{effect:"reverb",parameter:"delayFeedback",value:n});break;case 54:break;case 55:this.reverbProcessor.preDelayTime=n,l.gsInfo("Reverb Predelay Time",n),this.callEvent("effectChange",{effect:"reverb",parameter:"preDelayTime",value:n});break;case 56:this.setChorusMacro(n),l.gsInfo("Chorus Macro",n);break;case 57:this.chorusProcessor.preLowpass=n,l.gsInfo("Chorus Pre-LPF",n),this.callEvent("effectChange",{effect:"chorus",parameter:"preLowpass",value:n});break;case 58:this.chorusProcessor.level=n,l.gsInfo("Chorus Level",n),this.callEvent("effectChange",{effect:"chorus",parameter:"level",value:n});break;case 59:this.chorusProcessor.feedback=n,l.gsInfo("Chorus Feedback",n),this.callEvent("effectChange",{effect:"chorus",parameter:"feedback",value:n});break;case 60:this.chorusProcessor.delay=n,l.gsInfo("Chorus Delay",n),this.callEvent("effectChange",{effect:"chorus",parameter:"delay",value:n});break;case 61:this.chorusProcessor.rate=n,l.gsInfo("Chorus Rate",n),this.callEvent("effectChange",{effect:"chorus",parameter:"rate",value:n});break;case 62:this.chorusProcessor.depth=n,l.gsInfo("Chorus Depth",n),this.callEvent("effectChange",{effect:"chorus",parameter:"depth",value:n});break;case 63:this.chorusProcessor.sendLevelToReverb=n,l.gsInfo("Chorus Send Level To Reverb",n),this.callEvent("effectChange",{effect:"chorus",parameter:"sendLevelToReverb",value:n});break;case 64:this.chorusProcessor.sendLevelToDelay=n,l.gsInfo("Chorus Send Level To Delay",n),this.callEvent("effectChange",{effect:"chorus",parameter:"sendLevelToDelay",value:n});break;case 80:this.setDelayMacro(n),l.gsInfo("Delay Macro",n);break;case 81:this.delayProcessor.preLowpass=n,l.gsInfo("Delay Pre-LPF",n),this.callEvent("effectChange",{effect:"delay",parameter:"preLowpass",value:n});break;case 82:this.delayProcessor.timeCenter=n,l.gsInfo("Delay Time Center",n),this.callEvent("effectChange",{effect:"delay",parameter:"timeCenter",value:n});break;case 83:this.delayProcessor.timeRatioLeft=n,l.gsInfo("Delay Time Ratio Left",n),this.callEvent("effectChange",{effect:"delay",parameter:"timeRatioLeft",value:n});break;case 84:this.delayProcessor.timeRatioRight=n,l.gsInfo("Delay Time Ratio Right",n),this.callEvent("effectChange",{effect:"delay",parameter:"timeRatioRight",value:n});break;case 85:this.delayProcessor.levelCenter=n,l.gsInfo("Delay Level Center",n),this.callEvent("effectChange",{effect:"delay",parameter:"levelCenter",value:n});break;case 86:this.delayProcessor.levelLeft=n,l.gsInfo("Delay Level Left",n),this.callEvent("effectChange",{effect:"delay",parameter:"levelLeft",value:n});break;case 87:this.delayProcessor.levelRight=n,l.gsInfo("Delay Level Right",n),this.callEvent("effectChange",{effect:"delay",parameter:"levelRight",value:n});break;case 88:this.delayProcessor.level=n,l.gsInfo("Delay Level",n),this.callEvent("effectChange",{effect:"delay",parameter:"level",value:n});break;case 89:this.delayProcessor.feedback=n,l.gsInfo("Delay Feedback",n),this.callEvent("effectChange",{effect:"delay",parameter:"feedback",value:n});break;case 90:this.delayProcessor.sendLevelToReverb=n,l.gsInfo("Delay Send Level To Reverb",n),this.callEvent("effectChange",{effect:"delay",parameter:"sendLevelToReverb",value:n});break}break}if(s===3){if(this.systemParameters.insertionEffectLock)return;if(a>=3&&a<=25&&(this.insertionParams[a-3]=n),a>=3&&a<=22){this.insertionProcessor.setParameter(a,n),l.gsInfo(`EFX Parameter ${a-2}`,n),this.callEvent("effectChange",{effect:"insertion",parameter:a,value:n});return}switch(a){default:l.gsFail("Insertion Effect",[a]);return;case 0:{let r=n<<8|t[8],i=this.insertionEffects.get(r);i?(l.gsInfo("EFX Type",r.toString(16)),this.insertionProcessor=i):(this.insertionProcessor=this.insertionFallback,l.gsFail("EFX Processor",[r],"Using Thru.")),this.resetInsertionParams(),this.insertionProcessor.reset(),this.callEvent("effectChange",{effect:"insertion",parameter:0,value:r});return}case 23:this.insertionProcessor.sendLevelToReverb=n/127*CA,l.gsInfo("EFX Send Level to Reverb",n),this.callEvent("effectChange",{effect:"insertion",parameter:a,value:n});return;case 24:this.insertionProcessor.sendLevelToChorus=n/127*CA,l.gsInfo("EFX Send Level to Chorus",n),this.callEvent("effectChange",{effect:"insertion",parameter:a,value:n});return;case 25:this.insertionProcessor.sendLevelToDelay=n/127*CA,this.delayActive=!0,l.gsInfo("EFX Send Level to Delay",n),this.callEvent("effectChange",{effect:"insertion",parameter:a,value:n});return}}if(s>>4===1){let r=ne.syxToChannel(s&15)+e,i=this.midiChannels[r];switch(i||l.gsFail(`Patch Parameter for ${r}`,t,"Invalid channel number"),a){default:l.gsFail(`Patch Part Parameter for ${r}`,[a]);return;case 0:i.controllerChange(f.bankSelect,n),i.programChange(t[8]);break;case 2:{let o=n===16?-1:n+e;i.setMIDIParameter("rxChannel",o),this.customChannelNumbers||=o!==i.channel,l.gsInfo(`Rx. Channel on ${r}`,o);break}case 19:i.setMIDIParameter("polyMode",n===1),l.gsInfo(`Mono/poly on ${r}`,i.midiParameters.polyMode?"POLY":"MONO");break;case 20:i.setMIDIParameter("assignMode",n),l.gsInfo(`Assign mode on ${r}`,n);break;case 21:{i.setMIDIParameter("drumMap",n);let o=n>0;i.setGSDrums(o),l.gsInfo(`Drums on ${r}`,o.toString());return}case 22:{let o=n-64;i.setMIDIParameter("keyShift",o),l.gsInfo(`Key Shift for ${r}`,o);return}case 25:i.controllerChange(f.mainVolume,n);return;case 26:i.setMIDIParameter("velocitySenseDepth",n),l.gsInfo(`Velocity Sense Depth for ${r}`,n);return;case 27:i.setMIDIParameter("velocitySenseOffset",n),l.gsInfo(`Velocity Sense Offset for ${r}`,n);return;case 28:{let o=n,I=o===0;i.setMIDIParameter("randomPan",I),I?l.gsInfo(`Random pan on ${r}`,"ON"):i.controllerChange(f.pan,o);break}case 31:i.setMIDIParameter("cc1",n),l.gsInfo(`CC1 Controller Number for ${r}`,n);break;case 32:i.setMIDIParameter("cc2",n),l.gsInfo(`CC2 Controller Number for ${r}`,n);break;case 33:i.controllerChange(f.chorusDepth,n);break;case 34:i.controllerChange(f.reverbDepth,n);break;case 42:{let o=((n<<7|t[8])-8192)/81.92;i.setMIDIParameter("fineTune",o),l.gsInfo(`Fine tuning for ${r}`,Math.round(o),"cents");break}case 44:i.controllerChange(f.variationDepth,n);break;case 48:i.controllerChange(f.vibratoRate,n);break;case 49:i.controllerChange(f.vibratoDepth,n);break;case 50:i.controllerChange(f.brightness,n);break;case 51:i.controllerChange(f.filterResonance,n);break;case 52:i.controllerChange(f.attackTime,n);break;case 53:i.controllerChange(f.decayTime,n);break;case 54:i.controllerChange(f.releaseTime,n);break;case 55:i.controllerChange(f.vibratoDelay,n);break;case 64:{let o=t.length-9,I=new Int8Array(12);for(let h=0;h>4===2){let r=ne.syxToChannel(s&15)+e,i=this.midiChannels[r];switch(a&240){default:l.gsFail(`Patch Parameter Controller for ${r}`,[a&240]);break;case 0:if((a&15)===4){let o=n/127*600;i.setMIDIParameter("modulationDepth",o),l.gsInfo(`Modulation depth for ${r}`,Math.round(o),"cents");break}i.dynamicModulators.setupReceiver(a,n,f.modulationWheel,!0,"mod wheel");break;case 16:if((a&15)===0){let o=n-64;i.setMIDIParameter("pitchWheelRange",o),l.gsInfo(`Pitch Wheel Range for ${r}`,o,"semitones");break}i.dynamicModulators.setupReceiver(a,n,Ie.pitchWheel,!1,"pitch wheel",!0);break;case 32:i.dynamicModulators.setupReceiver(a,n,Ie.channelPressure,!1,"channel pressure");break;case 48:i.dynamicModulators.setupReceiver(a,n,Ie.polyPressure,!1,"poly pressure");break;case 64:i.dynamicModulators.setupReceiver(a,n,i.midiParameters.cc1,!0,"CC1");break;case 80:i.dynamicModulators.setupReceiver(a,n,i.midiParameters.cc2,!0,"CC2")}return}if(s>>4===4){let r=ne.syxToChannel(s&15)+e,i=this.midiChannels[r];switch(a){default:l.gsFail("Patch Part Parameter",[a]);break;case 0:case 1:i.controllerChange(f.bankSelectLSB,n);break;case 34:{let o=n===1;i.setMIDIParameter("efxAssign",o),this.insertionActive||=o,l.gsInfo(`EFX assign for ${r}`,o?"EFX":"BYPASS")}}return}l.gsFail("Patch Parameter",t);return}if(A===65||A===81){if(this.systemParameters.drumLock)return;let r=(s>>4)+1,i=a,o=s&15;switch(o){default:l.gsFail("Drum Setup",[o]);return;case 0:{let I=We(t,12,7);l.gsInfo(`Drum Map Name for MAP${r}`,I),this.callEvent("displayMessage",[...t]);break}case 1:{let I=n-60;for(let h of this.midiChannels)h.midiParameters.drumMap===r&&(h.drumParams[i].pitch=I*(h.patch.bankLSB===1?100:50));l.gsInfo(`Drum Pitch for MAP${r}, key ${i}`,I);break}case 2:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].gain=n/120);l.gsInfo(`Drum Level for MAP${r}, key ${i}`,n);break;case 3:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].exclusiveClass=n);l.gsInfo(`Drum Assign Group for MAP${r}, key ${i}`,n);break;case 4:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].pan=n);l.gsInfo(`Drum Pan for MAP${r}, key ${i}`,n);break;case 5:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].reverbGain=n/127);l.gsInfo(`Drum Reverb for MAP${r}, key ${i}`,n);break;case 6:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].chorusGain=n/127);l.gsInfo(`Drum Chorus for MAP${r}, key ${i}`,n);break;case 7:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].rxNoteOff=n===1);l.gsInfo(`Drum Note Off for MAP${r}, key ${i}`,n===1?"ON":"OFF");break;case 8:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].rxNoteOn=n===1);l.gsInfo(`Drum Note On for MAP${r}, key ${i}`,n===1?"ON":"OFF");break;case 9:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].delayGain=n/127);l.gsInfo(`Drum Delay for MAP${r}, key ${i}`,n);break}return}l.gsFail("System Exclusive",t);return}case 69:t[4]===16&&this.callEvent("displayMessage",[...t]);return;case 22:if(t[4]===16){this.setMIDIParameter("volume",t[7]/100),l.coolInfo("Roland Master Volume Control",t[7]);return}else l.unsupported("Roland",t)}else{l.unsupported("Roland",t);return}}function Or(t,e=0){if(t[2]===76){let A=t[3],s=t[4],a=t[5],n=t[6];if(A===0&&s===0){switch(a){case 0:{let r=(((t[6]&15)<<12|(t[7]&15)<<8|(t[8]&15)<<4|t[9]&15)-1024)/10;this.setMIDIParameter("fineTune",r),l.xgInfo("Master Tune",r,"cents")}break;case 4:this.setMIDIParameter("volume",n/127),l.xgInfo("Master Volume",n);break;case 5:{let r=127-n;this.setMIDIParameter("volume",r/127),l.xgInfo("Master Attenuation",n);break}case 6:{let r=n-64;this.setMIDIParameter("keyShift",r),l.xgInfo("Master Transpose",n);break}case 127:case 126:l.coolInfo("MIDI System","Yamaha XG"),this.reset("xg");break}return}if(A===2&&s===1){let r,i=a;i<=21?r="Reverb":i<=53?r="Chorus":r="Variation",l.xgFail(`${r} parameter`,[i]);return}if(A===8){let r=s+e;if(r>=this.midiChannels.length){l.xgFail("Part Setup",t,`Invalid part number: ${r}`);return}let i=this.midiChannels[r];switch(a){default:l.xgFail("Part Setup",[t[5]]);break;case 1:i.controllerChange(f.bankSelect,n);break;case 2:i.controllerChange(f.bankSelectLSB,n);break;case 3:i.programChange(n);break;case 4:{let o=n+e;i.setMIDIParameter("rxChannel",o),this.customChannelNumbers||=o!==i.channel,l.xgInfo(`Rev. Channel on ${r}`,o);break}case 5:{let o=n===1;i.setMIDIParameter("polyMode",o),l.xgInfo(`Mono/poly on ${r}`,o?"POLY":"MONO");break}case 6:i.setMIDIParameter("assignMode",n),l.xgInfo(`Same Note Number Key On Assign on ${r}`,n);break;case 7:{let o=n!==0;i.setDrums(o),l.xgInfo(`Part Mode on ${r}`,o?"DRUM":"MELODIC");break}case 8:{let o=n-64;i.setMIDIParameter("keyShift",o),l.xgInfo(`Key Shift on ${r}`,o);break}case 11:i.controllerChange(f.mainVolume,n);break;case 12:i.setMIDIParameter("velocitySenseDepth",n),l.xgInfo(`Velocity Sense Depth on ${r}`,n);return;case 13:i.setMIDIParameter("velocitySenseOffset",n),l.xgInfo(`Velocity Sense Offset on ${r}`,n);return;case 14:{let o=n,I=o===0;i.setMIDIParameter("randomPan",I),I?l.xgInfo(`Random Pan for ${r}`,"ON"):i.controllerChange(f.pan,o);break}case 18:i.controllerChange(f.chorusDepth,n);break;case 19:i.controllerChange(f.reverbDepth,n);break;case 21:i.controllerChange(f.vibratoRate,n);break;case 22:i.controllerChange(f.vibratoDepth,n);break;case 23:i.controllerChange(f.vibratoDelay,n);break;case 24:i.controllerChange(f.brightness,n);break;case 25:i.controllerChange(f.filterResonance,n);break;case 26:i.controllerChange(f.attackTime,n);break;case 27:i.controllerChange(f.decayTime,n);break;case 28:i.controllerChange(f.releaseTime,n);break;case 35:{let o=n-64;i.setMIDIParameter("pitchWheelRange",o),l.xgInfo(`Pitch Wheel Range for ${r}`,o,"semitones")}}return}if(A>>4===3){if(this.systemParameters.drumLock)return;let r=s;switch(a){default:l.xgFail("Drum Setup",[a]);return;case 0:{let i=(n-64)*100;for(let o of this.midiChannels)o.drumChannel&&(o.drumParams[r].pitch=i);l.xgInfo(`Drum Pitch for key ${r}`,i,"semitones");break}case 1:{let i=n-64;for(let o of this.midiChannels)o.drumChannel&&(o.drumParams[r].pitch+=i,l.xgInfo(`Drum Pitch for key ${r}`,o.drumParams[r].pitch,"semitones"));break}case 2:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].gain=n/120);l.xgInfo(`Drum Level for key ${r}`,n);break;case 3:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].exclusiveClass=n);l.xgInfo(`Drum Alternate Group for key ${r}`,n);break;case 4:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].pan=n);l.xgInfo(`Drum Pan for key ${r}`,n);break;case 5:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].reverbGain=n/127);l.xgInfo(`Drum Reverb for key ${r}`,n);break;case 6:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].chorusGain=n/127);l.xgInfo(`Drum Chorus for key ${r}`,n);break;case 9:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].rxNoteOff=n===1);l.xgInfo(`Drum Note Off for key ${r}`,n===1?"ON":"OFF");break;case 10:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].rxNoteOn=n===1);l.xgInfo(`Drum Note On for key ${r}`,n===1?"ON":"OFF");break}return}if(A===6||A===7){this.callEvent("displayMessage",[...t]);return}l.xgFail("System Exclusive",t,"Unknown address")}else l.xgFail("System Exclusive",t)}function Yr(t,e=0){e+=this.portSelectChannelOffset;let A=t[0];if(!(this.systemParameters.deviceID!==-1&&t[1]!==127&&this.systemParameters.deviceID!==t[1]))switch(A){default:l.unsupported("System Exclusive",t,`Unknown manufacturer: ${A}`);break;case 126:case 127:xr.call(this,t,e);break;case 65:Hr.call(this,t,e);break;case 67:Or.call(this,t,e);break;case 245:if(t.length<2)return;for(this.portSelectChannelOffset=(t[1]-1)*16;this.midiChannels.length<=this.portSelectChannelOffset;){l.info(`%cPort select, channel offset %c${this.portSelectChannelOffset}%c. Creating a new port!`,d.info,d.value,d.info);for(let s=0;s<16;s++)this.createMIDIChannel(!0)}break}}var Ln=class{sendLevelToReverb=40/127;sendLevelToChorus=0;sendLevelToDelay=0;type=0;reset(){}process(t,e,A,s,a,n,r,i,o){let{sendLevelToReverb:I,sendLevelToChorus:h,sendLevelToDelay:C}=this;for(let B=0;B=1&&(ae-=1);let $=E+g*(1-O*z),W=Math.tan(Math.PI*$/J),V=Math.max(-.9999,Math.min(.9999,(1-W)/(1+W))),ee=b+T*q,Ae=L+T*K;for(let Ee=0;Ee1e3?(this.manualOffset=zA*1.5*Js,this.manual=t):(this.manualOffset=zA,this.manual=t*Js)}clearAllPass(){this.prevR=0,this.prevL=0;for(let t=0;t.5?-1:-Math.cos((k-.75)*Vs);break;case 2:q=Math.sin(Vs*k);break;case 3:q=1-2*k;break;case 4:q=2*k-1;break}(k+=H)>=1&&(k-=1),u+=(q-u)*Wr;let K=u*w,ae=(1-K)*.5*F,U=(1+K)*.5*F,T=J*B*ae,Q=O*B*U,b=i+m;A[b]+=T,s[b]+=Q;let L=(T+Q)*.5;a[m]+=L*I,n[m]+=L*h,r[m]+=L*C}this.currentPan=u,this.phase=k}setParameter(t,e){switch(t){default:break;case 3:this.modWave=e;break;case 4:this.modRate=Ct.rate1(e);break;case 5:this.modDepth=e;break;case 19:this.lowGain=e-64;break;case 20:this.hiGain=e-64;break;case 22:this.level=e/127;break}this.updateShelves()}updateShelves(){ft(this.lsCoeffs,this.lowGain,200,this.sampleRate,!0),ft(this.hsCoeffs,this.hiGain,4e3,this.sampleRate,!1)}},Zs=96,_r=.1,$r=.1,jr=27,ei=28,ti=-28,Ai=400,si=.62,ni=.005,Un=5,Ws=Un*.5,xn=class{sendLevelToReverb=40/127;sendLevelToChorus=0;sendLevelToDelay=0;type=289;filType=1;sens=0;manual=68;peak=62;rate=2.05;depth=72;polarity=1;pan=0;lowGain=0;hiGain=0;level=Zs/127;coeffs={...qe};state={...be};hpCoeffs={...qe};hpState={...be};phase=0;lsCoeffs={...qe};hsCoeffs={...qe};lsState={...be};hsState={...be};sampleRate;lastFc=this.manual;attackCoeff;releaseCoeff;envelope=0;constructor(t){this.sampleRate=t,this.attackCoeff=Math.exp(-1/(_r*t)),this.releaseCoeff=Math.exp(-1/($r*t)),this.reset()}reset(){this.filType=1,this.sens=0,this.setManual(68),this.peak=62,this.rate=2.05,this.depth=72,this.polarity=1,this.lowGain=0,this.hiGain=0,this.pan=0,this.level=Zs/127,this.phase=.2,this.lastFc=this.manual,Se(this.hsState),Se(this.lsState),Se(this.state),Se(this.hpState),this.updateShelves()}process(t,e,A,s,a,n,r,i,o){let{sendLevelToReverb:I,sendLevelToChorus:h,sendLevelToDelay:C,level:B,lsCoeffs:g,lsState:E,hsCoeffs:p,hsState:y,coeffs:D,state:R,sampleRate:S,filType:w,manual:F,pan:H,attackCoeff:k,releaseCoeff:u,hpState:m,hpCoeffs:J}=this,{phase:O,lastFc:q,envelope:K}=this,ae=this.rate/this.sampleRate,U=Math.pow(10,this.peak/127*ei/20),T=Math.pow(10,this.peak/127*ti/20),Q=this.polarity===0?-1:Un,b=this.depth/127*Q,L=this.sens/127,z=H+64|0,$=MA[z],W=bA[z];for(let V=0;VK?k*K+(1-k)*Ae:u*K+(1-u)*Ae;let Y=2*Math.abs(O-.5)*b;(O+=ae)>=1&&(O-=1);let re=Y>=Ws||Q<0?1:Math.sin(Y*Math.PI/(2*Ws)),ue=F*(1+L*K*jr),Le=Math.max(20,ue*(1+re*Y));q+=(Math.max(10,Le)-q)*ni,ai(D,q,U,S);let Ee=ee;w===1&&(ri(J,Ai,T,S),Ee=gt(Ee,J,m));let Re=gt(Ee,D,R)*B,Oe=Re*$,Bt=Re*W,Et=i+V;A[Et]+=Oe,s[Et]+=Bt,a[V]+=Re*I,n[V]+=Re*h,r[V]+=Re*C}this.phase=O,this.lastFc=q,this.envelope=K}setParameter(t,e){switch(t){default:break;case 3:this.filType=e;break;case 4:this.sens=e;break;case 5:this.setManual(e);break;case 6:this.peak=e;break;case 7:this.rate=Ct.rate1(e);break;case 8:this.depth=e;break;case 9:this.polarity=e;break;case 19:this.lowGain=e-64;break;case 20:this.hiGain=e-64;break;case 21:this.pan=e-64;break;case 22:this.level=e/127;break}this.updateShelves()}setManual(t){let e=t*si,A=Ct.manual(Math.floor(e)),s=Ct.manual(Math.ceil(e)),a=e-Math.floor(e);this.manual=A+(s-A)*a}updateShelves(){ft(this.lsCoeffs,this.lowGain,200,this.sampleRate,!0),ft(this.hsCoeffs,this.hiGain,4e3,this.sampleRate,!1)}};function ai(t,e,A,s){let a=2*Math.PI*e/s,n=Math.cos(a),r=Math.sin(a)/(2*A),i=1-n,o=i/2,I=o,h=1+r,C=-2*n,B=1-r;t.a0=1,t.a1=C/h,t.a2=B/h,t.b0=o/h,t.b1=i/h,t.b2=I/h}function ri(t,e,A,s){let a=2*Math.PI*e/s,n=Math.cos(a),r=Math.sin(a)/(2*A),i=(1+n)/2,o=-(1+n),I=i,h=1+r,C=-2*n,B=1-r;t.a0=1,t.a1=C/h,t.a2=B/h,t.b0=i/h,t.b1=o/h,t.b2=I/h}var zs=127,ii=class{sendLevelToReverb=40/127;sendLevelToChorus=0;sendLevelToDelay=0;type=4360;phPan=0;awPan=127;level=zs/127;phaser;autoWah;bufferPh;bufferAw;constructor(t,e){this.phaser=new Tn(t),this.autoWah=new xn(t),this.bufferAw=new Float32Array(e),this.bufferPh=new Float32Array(e),this.phaser.sendLevelToReverb=0,this.phaser.sendLevelToChorus=0,this.phaser.sendLevelToDelay=0,this.autoWah.sendLevelToReverb=0,this.autoWah.sendLevelToChorus=0,this.autoWah.sendLevelToDelay=0,this.reset()}reset(){this.phPan=0,this.awPan=127,this.level=zs/127,this.phaser.reset(),this.autoWah.reset(),this.phaser.setParameter(22,127),this.autoWah.setParameter(22,127)}process(t,e,A,s,a,n,r,i,o){let{sendLevelToReverb:I,sendLevelToChorus:h,sendLevelToDelay:C,level:B}=this,{bufferPh:g,bufferAw:E}=this;this.bufferPh.fill(0),this.phaser.process(t,t,g,g,g,g,g,0,o),this.bufferAw.fill(0),this.autoWah.process(e,e,E,E,E,E,E,0,o);let p=this.phPan|0,y=MA[p],D=bA[p],R=this.awPan|0,S=MA[R],w=bA[R];for(let F=0;F=3&&t<=7){this.phaser.setParameter(t,e);return}if(t>=8&&t<=14){this.autoWah.setParameter(t-5,e);return}switch(t){default:break;case 18:this.phPan=e;break;case 19:this.phaser.setParameter(22,e);break;case 20:this.awPan=e;break;case 21:this.autoWah.setParameter(22,e);break;case 22:this.level=e/127;break}}},_s=127,$s=Math.PI*2,oi=.01,gi=class{sendLevelToReverb=40/127;sendLevelToChorus=0;sendLevelToDelay=0;type=293;modWave=1;modRate=3.05;modDepth=96;lowGain=0;hiGain=0;level=_s/127;phase=0;currentGain=1;lsCoeffs={...qe};hsCoeffs={...qe};lsStateR={...be};lsStateL={...be};hsStateR={...be};hsStateL={...be};sampleRate;constructor(t){this.sampleRate=t,this.reset()}reset(){this.modWave=1,this.modRate=3.05,this.modDepth=96,this.lowGain=0,this.hiGain=0,this.level=_s/127,this.phase=0,this.currentGain=1,Se(this.hsStateR),Se(this.hsStateL),Se(this.lsStateR),Se(this.lsStateL),this.updateShelves()}process(t,e,A,s,a,n,r,i,o){let{sendLevelToReverb:I,sendLevelToChorus:h,sendLevelToDelay:C,level:B,lsCoeffs:g,lsStateL:E,lsStateR:p,hsCoeffs:y,hsStateR:D,hsStateL:R,modDepth:S,modWave:w}=this,F=this.modRate/this.sampleRate,{currentGain:H,phase:k}=this;for(let u=0;u.5?-1:-Math.cos((k-.75)*$s);break;case 2:O=Math.sin($s*k);break;case 3:O=1-2*k;break;case 4:O=2*k-1;break}(k+=F)>=1&&(k-=1);let q=1-(O/2+.5)*(S/127);H+=(q-H)*oi;let K=m*B*H,ae=J*B*H,U=i+u;A[U]+=K,s[U]+=ae;let T=(K+ae)*.5;a[u]+=T*I,n[u]+=T*h,r[u]+=T*C}this.phase=k,this.currentGain=H}setParameter(t,e){switch(t){default:break;case 3:this.modWave=e;break;case 4:this.modRate=Ct.rate1(e);break;case 5:this.modDepth=e;break;case 19:this.lowGain=e-64;break;case 20:this.hiGain=e-64;break;case 22:this.level=e/127;break}this.updateShelves()}updateShelves(){ft(this.lsCoeffs,this.lowGain,200,this.sampleRate,!0),ft(this.hsCoeffs,this.hiGain,4e3,this.sampleRate,!1)}},Ii=[Ln,qr,Tn,zr,xn,ii,gi],ci=class{preDelay=0;preLPF=.5;inputDiffusion1=.75;inputDiffusion2=.625;decay=.5;decayDiffusion1=.7;decayDiffusion2=.5;damping=.005;excursionRate=.1;excursionDepth=.2;gain=1;sampleRate;lp1=0;lp2=0;lp3=0;excPhase=0;pDWrite=0;taps;pDelay;pDLength;delays=new Array;constructor(t){this.sampleRate=t,this.pDLength=t,this.pDelay=new Float32Array(this.pDLength);for(let e of[.004771345,.003595309,.012734787,.009307483,.022579886,.149625349,.060481839,.1249958,.030509727,.141695508,.089244313,.106280031])this.makeDelayLine(e);this.taps=Int16Array.from([.008937872,.099929438,.064278754,.067067639,.066866033,.006283391,.035818689,.011861161,.121870905,.041262054,.08981553,.070931756,.011256342,.004065724],e=>Math.round(e*this.sampleRate))}process(t,e,A,s,a){let n=this.preDelay|0,r=this.inputDiffusion1,i=this.inputDiffusion2,o=this.decay,I=this.decayDiffusion1,h=this.decayDiffusion2,C=1-this.damping,B=this.excursionRate/this.sampleRate,g=this.excursionDepth*this.sampleRate/1e3,E=this.pDWrite;for(let p=0;p=r&&(s=0)}this.writeIndex=s}},hi=1.5,li=class{dattorro;delayLeft;delayRight;delayLeftOutput;delayRightOutput;delayLeftInput;delayPreLPF;sampleRate;preLPFfc=8e3;preLPFa=0;preLPFz=0;characterTimeCoefficient=1;characterGainCoefficient=1;characterLPFCoefficient=0;delayGain=1;panDelayFeedback=0;constructor(t,e){this.sampleRate=t,this.delayLeftOutput=new Float32Array(e),this.delayRightOutput=new Float32Array(e),this.delayLeftInput=new Float32Array(e),this.delayPreLPF=new Float32Array(e),this.dattorro=new ci(t),this.delayLeft=new Zt(t),this.delayRight=new Zt(t)}_delayFeedback=0;get delayFeedback(){return this._delayFeedback}set delayFeedback(t){this._delayFeedback=t,this.updateFeedback()}_character=0;get character(){return this._character}set character(t){switch(this._character=t,this.dattorro.damping=.005,this.characterTimeCoefficient=1,this.characterGainCoefficient=1,this.characterLPFCoefficient=0,this.dattorro.inputDiffusion1=.75,this.dattorro.inputDiffusion2=.625,this.dattorro.decayDiffusion1=.7,this.dattorro.decayDiffusion2=.5,this.dattorro.excursionRate=.5,this.dattorro.excursionDepth=.7,t){case 0:this.dattorro.damping=.85,this.characterTimeCoefficient=.9,this.characterGainCoefficient=.9,this.characterLPFCoefficient=.2;break;case 1:this.dattorro.damping=.2,this.characterGainCoefficient=.7,this.characterTimeCoefficient=1,this.dattorro.decayDiffusion2=.64,this.dattorro.decayDiffusion1=.6,this.characterLPFCoefficient=.2;break;case 2:this.dattorro.damping=.56,this.characterGainCoefficient=.75,this.characterTimeCoefficient=1,this.dattorro.decayDiffusion2=.64,this.dattorro.decayDiffusion1=.6,this.characterLPFCoefficient=.1;break;case 3:this.dattorro.damping=.3,this.characterGainCoefficient=1.25,this.characterTimeCoefficient=1.3,this.characterLPFCoefficient=0,this.dattorro.decayDiffusion2=.7,this.dattorro.decayDiffusion1=.66;break;case 4:this.characterGainCoefficient=1,this.characterTimeCoefficient=1.2,this.characterLPFCoefficient=.1,this.dattorro.damping=.1,this.dattorro.decayDiffusion2=.69,this.dattorro.decayDiffusion1=.67;break;case 5:this.characterGainCoefficient=.75,this.dattorro.damping=.65,this.characterTimeCoefficient=.5;break}this.updateTime(),this.updateGain(),this.updateLowpass(),this.updateFeedback(),this.delayLeft.clear(),this.delayRight.clear()}_time=0;get time(){return this._time}set time(t){this._time=t,this.updateTime()}_preDelayTime=0;get preDelayTime(){return this._preDelayTime}set preDelayTime(t){this._preDelayTime=t,this.dattorro.preDelay=t/1e3*this.sampleRate}_level=0;get level(){return this._level}set level(t){this._level=t,this.updateGain()}_preLowpass=0;get preLowpass(){return this._preLowpass}set preLowpass(t){this._preLowpass=t,this.preLPFfc=8e3*.63**this._preLowpass;let e=Math.exp(-2*Math.PI*this.preLPFfc/this.sampleRate);this.preLPFa=1-e,this.updateLowpass()}process(t,e,A,s,a){switch(this._character){default:this.dattorro.process(t,e,A,s,a);return;case 6:{let n;if(this._preLowpass>0){let o=this.delayPreLPF,I=this.preLPFz,h=this.preLPFa;for(let C=0;C0){let C=this.delayPreLPF,B=this.preLPFz,g=this.preLPFa;for(let E=0;E0,R=this.phase,S=this.write,w=this.preLPFz,F=this.preLPFa;for(let H=0;H=h&&(q-=h);let K=J-O,ae=i[O]*(1-K)+i[q]*K;i[S]=k+ae*y;let U=Math.max(1,Math.min(B+(1-u)*C,h)),T=S-U;T<0&&(T+=h),O=T|0,q=O+1,q>=h&&(q-=h),K=T-O;let Q=o[O]*(1-K)+o[q]*K,b=H+n;e[b]+=ae*g,A[b]+=Q*g;let L=(ae+Q)/2;s[H]+=L*E,a[H]+=L*p,o[S]=k+Q*y,++S>=h&&(S=0),(R+=I)>=1&&(R-=1)}this.write=S,this.phase=R,this.preLPFz=w}getSnapshot(){return{preLowpass:this._preLowpass,depth:this._depth,delay:this._delay,sendLevelToDelay:this._sendLevelToDelay,sendLevelToReverb:this._sendLevelToReverb,rate:this._rate,feedback:this._feedback,level:this._level}}},Ei=[{start:1,end:20,timeStart:.1,resolution:.1},{start:20,end:35,timeStart:2,resolution:.2},{start:35,end:45,timeStart:5,resolution:.5},{start:45,end:55,timeStart:10,resolution:1},{start:55,end:70,timeStart:20,resolution:2},{start:70,end:80,timeStart:50,resolution:5},{start:80,end:90,timeStart:100,resolution:10},{start:90,end:105,timeStart:200,resolution:20},{start:105,end:116,timeStart:500,resolution:50}],di=1.66,fi=class{preLPFfc=8e3;preLPFa=0;preLPFz=0;delayLeft;delayRight;delayCenter;sampleRate;delayCenterOutput;delayPreLPF;delayCenterTime;delayLeftMultiplier=.04;delayRightMultiplier=.04;gain=0;reverbGain=0;constructor(t,e){this.sampleRate=t,this.delayCenterOutput=new Float32Array(e),this.delayPreLPF=new Float32Array(e),this.delayCenterTime=.34*t,this.delayCenter=new Zt(t),this.delayLeft=new Zt(t),this.delayRight=new Zt(t)}_sendLevelToReverb=0;get sendLevelToReverb(){return this._sendLevelToReverb}set sendLevelToReverb(t){this._sendLevelToReverb=t,this.reverbGain=t/127}_preLowpass=0;get preLowpass(){return this._preLowpass}set preLowpass(t){this._preLowpass=t,this.preLPFfc=8e3*.63**this._preLowpass;let e=Math.exp(-2*Math.PI*this.preLPFfc/this.sampleRate);this.preLPFa=1-e}_levelRight=0;get levelRight(){return this._levelRight}set levelRight(t){this._levelRight=t,this.updateGain()}_level=64;get level(){return this._level}set level(t){this._level=t,this.gain=t/127*di}_levelCenter=127;get levelCenter(){return this._levelCenter}set levelCenter(t){this._levelCenter=t,this.updateGain()}_levelLeft=0;get levelLeft(){return this._levelLeft}set levelLeft(t){this._levelLeft=t,this.updateGain()}_feedback=16;get feedback(){return this._feedback}set feedback(t){this._feedback=t,this.delayLeft.feedback=this.delayRight.feedback=0,this.delayCenter.feedback=(t-64)/66}_timeRatioRight=0;get timeRatioRight(){return this._timeRatioRight}set timeRatioRight(t){this._timeRatioRight=t,this.delayRightMultiplier=t*(100/2400),this.delayRight.time=this.delayCenterTime*this.delayRightMultiplier}_timeRatioLeft=0;get timeRatioLeft(){return this._timeRatioLeft}set timeRatioLeft(t){this._timeRatioLeft=t,this.delayLeftMultiplier=t*(100/2400),this.delayLeft.time=this.delayCenterTime*this.delayLeftMultiplier}_timeCenter=12;get timeCenter(){return this._timeCenter}set timeCenter(t){this._timeCenter=t;let e=.1;for(let A of Ei)if(t>=A.start&&t0){let C=this.delayPreLPF,B=this.preLPFz,g=this.preLPFa;for(let E=0;E[t,!1]));midiParameters={...js};systemParameters={...cn};currentTime=0;defaultPreset;drumPreset;gainSmoothingFactor;panSmoothingFactor;eventCallbackHandler;missingPresetHandler;cachedVoices=new Map;lockMIDIParameter=ui.bind(this);setSystemParameter=Na.bind(this);systemExclusive=Yr.bind(this);reverbProcessor;chorusProcessor;delayProcessor;customChannelNumbers=!1;setMIDIParameter=Qi.bind(this);insertionFallback=new Ln;insertionProcessor=this.insertionFallback;insertionEffects=new Map;insertionActive=!1;portSelectChannelOffset=0;insertionParams=new Uint8Array(23).fill(255);lastPriorityAssignmentTime=0;eventQueue=[];sampleTime;constructor(t,e,A,s){this.eventCallbackHandler=t,this.missingPresetHandler=e,this.sampleRate=A,this.sampleTime=1/A,this.currentTime=s.initialTime,this.setSystemParameter("effectsEnabled",s.effectsEnabled),this.setSystemParameter("eventsEnabled",s.eventsEnabled),this.maxBufferSize=s.maxBufferSize,this.gainSmoothingFactor=mi*(44100/A),this.panSmoothingFactor=pi*(44100/A),Qs.initCache(this.sampleRate);let a=this.maxBufferSize;this.reverbProcessor=s.reverbProcessor??new li(A,a),this.chorusProcessor=s.chorusProcessor??new Bi(A,a),this.delayProcessor=s.delayProcessor??new fi(A,a),this.voiceBuffer=new Float32Array(a),this.insertionInputL=new Float32Array(a),this.insertionInputR=new Float32Array(a),this.reverbInput=new Float32Array(a),this.chorusInput=new Float32Array(a),this.delayInput=new Float32Array(a);for(let n of Ii)this.registerInsertionProcessor(n);this.resetInsertionParams(),this.allocateNewVoices(this.systemParameters.voiceCap)}_voiceCount=0;get voiceCount(){return this._voiceCount}controllerChange(t,e,A){if(this.customChannelNumbers){for(let s of this.midiChannels)s.midiParameters.rxChannel===t&&s.controllerChange(e,A);return}this.midiChannels[t+this.portSelectChannelOffset].controllerChange(e,A)}noteOn(t,e,A){if(this.customChannelNumbers){for(let s of this.midiChannels)s.midiParameters.rxChannel===t&&s.noteOn(e,A);return}this.midiChannels[t+this.portSelectChannelOffset].noteOn(e,A)}noteOff(t,e){if(this.customChannelNumbers){for(let A of this.midiChannels)A.midiParameters.rxChannel===t&&A.noteOff(e);return}this.midiChannels[t+this.portSelectChannelOffset].noteOff(e)}polyPressure(t,e,A){if(this.customChannelNumbers){for(let s of this.midiChannels)s.midiParameters.rxChannel===t&&s.polyPressure(e,A);return}this.midiChannels[t+this.portSelectChannelOffset].polyPressure(e,A)}channelPressure(t,e){if(this.customChannelNumbers){for(let A of this.midiChannels)A.midiParameters.rxChannel===t&&A.setMIDIParameter("pressure",e);return}this.midiChannels[t+this.portSelectChannelOffset].setMIDIParameter("pressure",e)}pitchWheel(t,e,A=-1){if(this.customChannelNumbers){for(let s of this.midiChannels)s.midiParameters.rxChannel===t&&s.pitchWheel(e,A);return}this.midiChannels[t+this.portSelectChannelOffset].pitchWheel(e,A)}programChange(t,e){if(this.customChannelNumbers){for(let A of this.midiChannels)A.midiParameters.rxChannel===t&&A.programChange(e);return}this.midiChannels[t+this.portSelectChannelOffset].programChange(e)}assignVoice(){for(let e=0;ethis.currentTime?(this.eventQueue.push({message:t,channelOffset:e,time:s}),this.eventQueue.sort((a,n)=>a.time-n.time)):this.processMessageInternal(t,e)}destroySynthProcessor(){this.voices.length=0;for(let t of this.midiChannels)t.destroy();this.clearCache(),this.midiChannels.length=0,this.soundBankManager.destroy()}getVoices(t,e,A){let s=this.midiChannels[t],a=this.keyModifierManager.hasOverridePatch(t,e),n=s.preset;if(a){let r=this.keyModifierManager.getPatch(t,e);n=this.soundBankManager.getPreset(r,this.midiParameters.system)}return n?this.getVoicesForPreset(n,e,A):[]}createMIDIChannel(t){let e=new Nr(this,this.defaultPreset,this.midiChannels.length);this.midiChannels.push(e),t&&(this.callEvent("channelAdded",void 0),e.setDrums(!0))}reset(t="gs"){if(this.callEvent("reset",t),this.setMIDIParameter("system",t),this.setMIDIParameter("volume",1),this.setMIDIParameter("pan",0),this.setMIDIParameter("keyShift",0),this.setMIDIParameter("fineTune",0),this.tunings.fill(-1),this.portSelectChannelOffset=0,this.customChannelNumbers=!1,this.setReverbMacro(4),this.setChorusMacro(2),this.setDelayMacro(0),this.systemParameters.delayLock||(this.delayActive=!1),this.resetInsertion(),!(!this.drumPreset||!this.defaultPreset))for(let e of this.midiChannels)e.reset(!1)}process(t,e,A=0,s=0){this.processSplit([[t,e]],t,e,A,s)}processSplit(t,e,A,s=0,a=0){if(this.eventQueue.length>0){let o=this.currentTime;for(;this.eventQueue[0]?.time<=o;){let I=this.eventQueue.shift();I&&this.processMessageInternal(I.message,I.channelOffset)}}s=Math.max(s,0);let n=a||t[0][0].length-s;if(n>this.maxBufferSize)throw new Error(`Requested ${n} samples, but maxBufferSize is ${this.maxBufferSize}`);this.reverbInput.fill(0),this.chorusInput.fill(0),this.delayActive&&this.delayInput.fill(0),this.insertionActive&&(this.insertionInputL.fill(0),this.insertionInputR.fill(0));for(let o of this.midiChannels)o.clearVoiceCount();this._voiceCount=0;let r=this.systemParameters.voiceCap,i=t.length;for(let o=0;o=128&&A<240?(s=A&240,a=A&15):s=A,a+=e,s){case G.noteOn:{let n=t[2];n>0?this.noteOn(a,t[1],n):this.noteOff(a,t[1]);break}case G.noteOff:this.noteOff(a,t[1]);break;case G.pitchWheel:this.pitchWheel(a,t[2]<<7|t[1]);break;case G.controllerChange:this.controllerChange(a,t[1],t[2]);break;case G.programChange:this.programChange(a,t[1]);break;case G.polyPressure:this.polyPressure(a,t[1],t[2]);break;case G.channelPressure:this.channelPressure(a,t[1]);break;case G.systemExclusive:this.systemExclusive(new te(t.slice(1)),e);break;case G.reset:this.stopAllChannels(!1),this.reset();break;default:break}}assignVoicePriorities(){if(this.lastPriorityAssignmentTime===this.currentTime)return;l.info("%cPolyphony exceeded, stealing voices",d.warn),this.lastPriorityAssignmentTime=this.currentTime;let t=this.systemParameters.voiceCap;for(let e=0;e{l.info("%cSpessaSynth is ready!",d.recognized)})}get midiChannels(){return this.synthCore.midiChannels}get midiParameters(){return this.synthCore.midiParameters}get systemParameters(){return this.synthCore.systemParameters}get voiceCount(){return this.synthCore.voiceCount}get currentTime(){return this.synthCore.currentTime}get reverbProcessor(){return this.synthCore.reverbProcessor}get chorusProcessor(){return this.synthCore.chorusProcessor}get delayProcessor(){return this.synthCore.delayProcessor}get soundBankManager(){return this.synthCore.soundBankManager}get keyModifierManager(){return this.synthCore.keyModifierManager}onMissingPreset=(t,e)=>{l.warn(`No preset found for ${je.toMIDIString(t)}! Did you forget to add a sound bank?`)};lockMIDIParameter(t,e){this.synthCore.lockMIDIParameter(t,e)}setSystemParameter(t,e){this.synthCore.setSystemParameter(t,e)}reset(){this.synthCore.reset()}applySnapshot(t){this.savedSnapshot=t,La.call(this.synthCore,t)}getSnapshot(){return Pa.call(this.synthCore)}setEmbeddedSoundBank(t,e){let A=eA.fromArrayBuffer(t);this.synthCore.soundBankManager.addSoundBank(A,rA,e);let s=this.synthCore.soundBankManager.priorityOrder;s.pop(),s.unshift(rA),this.synthCore.soundBankManager.priorityOrder=s,this.savedSnapshot!==void 0&&this.applySnapshot(this.savedSnapshot),l.info(`%cEmbedded sound bank set at offset %c${e}`,d.recognized,d.value)}clearEmbeddedSoundBank(){this.synthCore.soundBankManager.soundBankList.some(t=>t.id===rA)&&this.synthCore.soundBankManager.deleteSoundBank(rA)}createMIDIChannel(){this.synthCore.createMIDIChannel(!0)}stopAllChannels(t=!1){this.synthCore.stopAllChannels(t)}destroySynthProcessor(){this.synthCore.destroySynthProcessor()}clearCache(){this.synthCore.clearCache()}getVoicesForPreset(t,e,A){return this.synthCore.getVoicesForPreset(t,e,A)}callEvent(t,e){this.onEventCall?.({type:t,data:e})}missingPreset(t,e){return this.onMissingPreset(t,e)}};var GA=nn.ConsoleColors;var On="spessasynth-worklet-processor";function Yn(t,e){return{...e,...t}}var qn={skipToFirstNoteOn:!0,initialPlaybackRate:1};var ys=class extends RA{events=[];constructor(e){super(),super.copyFrom(e),this.events=[]}},LA=class t extends Mt{tracks;timeline=[];embeddedSoundBank=void 0;embeddedSoundBankSize;constructor(e){super(),super.copyMetadataFrom(e),this.tracks=e.tracks.map(A=>new ys(A)),this.embeddedSoundBankSize=e instanceof t?e.embeddedSoundBankSize:e?.embeddedSoundBank?.byteLength}};var PA={shuffleOn:1,shuffleOff:2,index:3};var Jn=-1;var Kn=1,NA=class{synthesizer;sequencers=new Array;post;lastSequencerSync=0;voiceCounts=new Array(16).fill(0);alive=!1;eventsEnabled;constructor(e,A,s){this.synthesizer=new Hn(e,A),this.eventsEnabled=A.eventsEnabled??!1,this.post=s,this.synthesizer.onEventCall=a=>{if(a.type==="channelAdded"){let n=this.synthesizer.midiChannels.length;for(let r=this.voiceCounts.length;r{if(this.eventsEnabled){if(s.type==="songListChange"){let n=s.data.newSongList.map(r=>new LA(r));this.post({type:"sequencerReturn",data:{type:s.type,data:{newSongList:n,shuffledSongIndexes:e.shuffledSongIndexes},id:A},currentTime:this.synthesizer.currentTime});return}this.post({type:"sequencerReturn",data:{...s,id:A},currentTime:this.synthesizer.currentTime})}}}postReady(e,A,s=[]){this.post({type:"isFullyInitialized",data:{type:e,data:A},currentTime:this.synthesizer.currentTime},s)}postProgress(e,A){this.post({type:"renderingProgress",data:{type:e,data:A},currentTime:this.synthesizer.currentTime})}destroy(){this.synthesizer.destroySynthProcessor(),delete this.synthesizer,delete this.sequencers}handleMessage(e){let A=e.channelNumber,s;if(A>=0&&(s=this.synthesizer.midiChannels[A],s===void 0)){l.warn(`Trying to access channel ${A} which does not exist... ignoring!`);return}switch(e.type){case"midiMessage":{this.synthesizer.processMessage(e.data.messageData,e.data.channelOffset,e.data.options);break}case"ccReset":{this.synthesizer.reset();break}case"stopAll":{A===Jn?this.synthesizer.stopAllChannels(e.data===1):s?.stopAllNotes(e.data===1);break}case"addNewChannel":{this.synthesizer.createMIDIChannel();break}case"lockGlobalMIDIParameter":{this.synthesizer.lockMIDIParameter(e.data.parameter,e.data.isLocked);break}case"setGlobalSystemParameter":{this.synthesizer.setSystemParameter(e.data.parameter,e.data.value);break}case"lockChannelMIDIParameter":{s?.lockMIDIParameter(e.data.parameter,e.data.isLocked);break}case"setChannelSystemParameter":{s?.setSystemParameter(e.data.parameter,e.data.value);break}case"setDrums":{s?.setDrums(e.data);break}case"lockController":{s?.lockController(e.data.controller,e.data.isLocked);break}case"sequencerSpecific":{let a=this.sequencers[e.data.id];if(!a)return;let n=e.data;switch(n.type){default:break;case"loadNewSongList":{try{let i=n.data.map(o=>"duration"in o?Mt.copyFrom(o):Mt.fromArrayBuffer(o.binary,o.fileName));a.loadNewSongList(i)}catch(r){console.error(r),this.post({type:"sequencerReturn",data:{type:"midiError",data:r,id:e.data.id},currentTime:this.synthesizer.currentTime})}break}case"pause":{a.pause();break}case"play":{a.play();break}case"setTime":{a.currentTime=n.data;break}case"changeMIDIMessageSending":{a.externalMIDIPlayback=n.data;break}case"setPlaybackRate":{a.playbackRate=n.data;break}case"setLoopCount":{a.loopCount=n.data;break}case"changeSong":{switch(n.data.changeType){case PA.shuffleOff:{a.shuffleMode=!1;break}case PA.shuffleOn:{a.shuffleMode=!0;break}case PA.index:{n.data.data!==void 0&&(a.songIndex=n.data.data);break}}break}case"getMIDI":{if(!a.midiData)throw new Error("No MIDI is loaded!");this.post({type:"sequencerReturn",data:{type:"getMIDI",data:a.midiData,id:e.data.id},currentTime:this.synthesizer.currentTime});break}case"setSkipToFirstNote":{a.skipToFirstNoteOn=n.data;break}}break}case"soundBankManager":{try{let a=this.synthesizer.soundBankManager,n=e.data,r;switch(n.type){case"addSoundBank":{r=eA.fromArrayBuffer(n.data.soundBankBuffer),a.addSoundBank(r,n.data.id,n.data.bankOffset),this.postReady("soundBankManager",null);break}case"deleteSoundBank":{a.deleteSoundBank(n.data),this.postReady("soundBankManager",null);break}case"rearrangeSoundBanks":a.priorityOrder=n.data,this.postReady("soundBankManager",null)}}catch(a){this.post({type:"soundBankError",data:a,currentTime:this.synthesizer.currentTime})}break}case"keyModifierManager":{let a=e.data,n=this.synthesizer.keyModifierManager;switch(a.type){default:return;case"addMapping":{n.addMapping(a.data.channel,a.data.midiNote,a.data.mapping);break}case"clearMappings":{n.clearMappings();break}case"deleteMapping":n.deleteMapping(a.data.channel,a.data.midiNote)}break}case"requestSynthesizerSnapshot":{let a=this.synthesizer.getSnapshot();this.postReady("synthesizerSnapshot",a);break}case"requestNewSequencer":{this.createNewSequencer();break}case"setLogLevel":{l.setLogLevel(e.data.enableInfo,e.data.enableWarning,e.data.enableGroup);break}case"destroyWorklet":{this.alive=!1,this.synthesizer.destroySynthProcessor(),this.destroy();break}default:{l.warn("Unrecognized event!",e);break}}}};var TA=class extends NA{alive=!0;oneOutputMode;port;constructor(e,A,s,a){super(e,{effectsEnabled:!a.oneOutput,eventsEnabled:a?.eventsEnabled,initialTime:A},(n,r)=>{s.postMessage(n,r)}),this.port=s,this.oneOutputMode=a.oneOutput,this.synthesizer.processorInitialized.then(()=>{this.port.onmessage=n=>this.handleMessage(n.data),this.postReady("sf3Decoder",null)})}process(e,A){if(!this.alive)return!1;for(let i of this.sequencers)i.processTick();if(this.oneOutputMode){let i=A[0],o=[];for(let I=0;I<32;I+=2)o.push([i[I],i[I+1]]);this.synthesizer.setSystemParameter("effectsEnabled",!1),this.synthesizer.processSplit(o,i[0],i[0])}else this.synthesizer.processSplit(A.slice(1),A[0][0],A[0][1]);let s=this.synthesizer.currentTime;if(this.eventsEnabled&&s-this.lastSequencerSync>Kn){for(let i=0;i=760px){.max-\[760px\]\:col-start-1{grid-column-start:1}.max-\[760px\]\:ml-0{margin-left:0}.max-\[760px\]\:grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.max-\[760px\]\:flex-col{flex-direction:column}.max-\[760px\]\:items-start{align-items:flex-start}.max-\[760px\]\:pt-8{padding-top:calc(var(--spacing) * 8)}}@media (width>=40rem){.sm\:gap-5{gap:calc(var(--spacing) * 5)}}}.grain{pointer-events:none;z-index:100;opacity:.035;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");position:fixed;inset:0}body[data-state=transcribing] .status-dot{background:var(--color-accent);animation:ping 1.3s var(--ease-fluid) infinite}body[data-state=done] .status-dot{background:var(--color-ok)}body[data-state=error] .status-dot{background:var(--color-accent)}body.drag .drop-overlay{opacity:1}.mix-slider{appearance:none;background:linear-gradient(90deg, var(--color-muted), var(--color-accent));cursor:pointer;border-radius:999px;width:170px;height:4px}.mix-slider:disabled{cursor:not-allowed;filter:grayscale()}.mix-slider::-webkit-slider-thumb{appearance:none;border:2px solid var(--color-accent);width:16px;height:16px;transition:transform .1s var(--ease-fluid);background:#fff;border-radius:50%;box-shadow:0 2px 8px #00000080}.mix-slider::-webkit-slider-thumb:hover{transform:scale(1.15)}.mix-slider::-moz-range-thumb{border:2px solid var(--color-accent);background:#fff;border-radius:50%;width:16px;height:16px;box-shadow:0 2px 8px #00000080}@media (prefers-reduced-motion:reduce){*,:before,:after{transition:none!important;animation:none!important}}.compare-body{--lab-paper:#f1eee3;--lab-paper-deep:#e3dfd1;--lab-ink:#171714;--lab-ink-soft:#292925;--lab-muted:#6d6b62;--lab-rule:#17171447;--lab-rule-light:#f1eee333;--lab-signal:#ff573c;--lab-acid:#d9ef4a;--lab-blue:#55c4cf;--lab-focus:#116fdb;--lab-success:#88a829;--lab-warning:#d08a12;--lab-danger:#dc3f2d;--lab-display:"Bodoni Moda", Baskerville, "Times New Roman", serif;--lab-body:"Manrope", "Avenir Next", "Helvetica Neue", sans-serif;--lab-mono:"IBM Plex Mono", "Courier New", monospace;--lab-xs:.68rem;--lab-sm:.78rem;--lab-base:.96rem;--lab-lg:1.2rem;--lab-xl:clamp(2rem, 4vw, 4.4rem);--lab-2xl:clamp(3.8rem, 9vw, 9.5rem);--lab-1:.3rem;--lab-2:.6rem;--lab-3:.9rem;--lab-4:1.2rem;--lab-6:1.8rem;--lab-8:2.4rem;--lab-12:3.6rem;--lab-radius-sm:2px;--lab-radius-md:8px;--lab-shadow:8px 8px 0 #17171426;--lab-fast:.12s;--lab-base-duration:.24s;--lab-slow:.62s;--lab-ease:cubic-bezier(.22, 1, .36, 1);min-width:320px;color:var(--lab-ink);background-color:var(--lab-paper);font-family:var(--lab-body);background-image:linear-gradient(#17171406 1px,#0000 1px),linear-gradient(90deg,#17171405 1px,#0000 1px);background-size:28px 28px;background-attachment:fixed}.compare-body *,.compare-body :before,.compare-body :after{box-sizing:border-box}.compare-body button,.compare-body input{font:inherit}.compare-body button{min-height:44px;color:inherit;background:0 0;border:0;border-radius:0;padding:0}.compare-body button:hover{background:0 0;border-color:#0000}.compare-body button:focus-visible,.compare-body a:focus-visible,.compare-body input:focus-visible{outline:3px solid var(--lab-focus);outline-offset:3px}.compare-body button:active:not(:disabled){transform:translateY(1px)}.compare-body button:disabled,.compare-body input:disabled{opacity:.38;cursor:not-allowed}.compare-body a{color:inherit}.compare-app{isolation:isolate;min-height:100vh;position:relative}.compare-grain{z-index:100;pointer-events:none;opacity:.055;mix-blend-mode:multiply;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='180' height='180'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.82' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='.65'/%3E%3C/svg%3E");position:fixed;inset:0}@keyframes lab-enter{0%{opacity:0;transform:translateY(18px)}to{opacity:1;transform:translateY(0)}}@keyframes signal-travel{0%{opacity:0;transform:translate(-16px)}40%,80%{opacity:1}to{opacity:0;transform:translate(16px)}}@keyframes signal-pulse{0%,to{box-shadow:0 0 0 0 color-mix(in srgb, var(--node-accent) 65%, transparent)}50%{box-shadow:0 0 0 7px #0000}}.compare-masthead{gap:var(--lab-8);border-bottom:2px solid var(--lab-ink);width:min(100% - 48px,1880px);min-height:430px;animation:lab-enter var(--lab-slow) var(--lab-ease) both;grid-template-columns:minmax(160px,.55fr) minmax(520px,2fr) minmax(190px,.65fr);align-items:start;margin:0 auto;padding:34px 0 42px;display:grid}.compare-wordmark{flex-direction:column;align-items:flex-start;width:fit-content;text-decoration:none;display:inline-flex}.compare-wordmark>span{font:700 clamp(1.35rem, 2.4vw, 2.4rem)/.9 var(--lab-body);letter-spacing:-.075em}.compare-wordmark>small,.compare-kicker,.section-index,.preset-label{font:600 var(--lab-xs)/1.2 var(--lab-mono);letter-spacing:.12em;text-transform:uppercase}.compare-wordmark>small{border-top:1px solid var(--lab-ink);margin-top:10px;padding-top:8px}.compare-intro{max-width:1040px;padding-top:46px}.compare-kicker{margin:0 0 var(--lab-4);color:var(--lab-danger)}.compare-intro h1{max-width:960px;font:600 var(--lab-2xl)/.78 var(--lab-display);letter-spacing:-.065em;text-wrap:balance;margin:0}.compare-intro h1 em{color:var(--lab-signal);font-weight:600}.compare-intro>p:last-child{border-left:7px solid var(--lab-acid);width:min(610px,75%);font-size:var(--lab-base);text-wrap:pretty;margin:40px 0 0 auto;padding-left:18px;line-height:1.65}.compare-config-button{text-align:left;width:100%;max-width:240px;transition:padding var(--lab-base-duration) var(--lab-ease), color var(--lab-fast);grid-template-columns:auto 1fr auto;justify-self:end;align-items:center;gap:10px;display:grid;border-top:1px solid var(--lab-ink)!important;border-bottom:1px solid var(--lab-ink)!important;font-size:var(--lab-sm)!important;padding:12px 0!important}.compare-config-button:hover{color:var(--lab-danger);padding-left:8px!important;padding-right:8px!important}.compare-config-button>.config-button-count{width:27px;height:27px;color:var(--lab-paper);background:var(--lab-ink);font:500 var(--lab-xs)/1 var(--lab-mono);place-items:center;display:grid}.compare-main{width:min(100% - 48px,1880px);margin:0 auto}.preset-strip{border-bottom:1px solid var(--lab-ink);contain:inline-size;max-width:100%;min-height:66px;animation:lab-enter var(--lab-slow) var(--lab-ease) 80ms both;align-items:stretch;display:flex}.preset-label{color:var(--lab-muted);align-items:center;padding-right:28px;display:flex}.preset-button{min-width:132px;position:relative;border-left:1px solid var(--lab-rule)!important;font-size:var(--lab-sm)!important;transition:color var(--lab-fast), background var(--lab-fast)!important;padding:0 20px!important;font-weight:600!important}.preset-button:hover,.preset-button.is-active{color:var(--lab-paper)!important;background:var(--lab-ink)!important}.preset-button.is-active:after{content:"";background:var(--lab-acid);width:7px;height:7px;position:absolute;top:8px;right:8px}.signal-rail{min-height:132px;color:var(--lab-paper);background:var(--lab-ink);border-bottom:1px solid var(--lab-ink);animation:lab-enter var(--lab-slow) var(--lab-ease) .13s both;grid-template-columns:115px 1fr 100px;align-items:stretch;display:grid;overflow:hidden}.signal-origin,.signal-output{font-family:var(--lab-mono);flex-direction:column;justify-content:center;gap:5px;padding:18px;display:flex}.signal-origin{border-right:1px solid var(--lab-rule-light)}.signal-output{border-left:1px solid var(--lab-rule-light);text-align:right}.signal-origin span,.signal-output span{color:#f1eee38c;letter-spacing:.16em;font-size:.6rem}.signal-origin strong,.signal-output strong{font-size:.88rem}.signal-track{grid-template-columns:repeat(var(--rail-count), minmax(125px, 1fr));align-items:center;gap:10px;padding:18px 32px;display:grid;position:relative;overflow-x:auto}.signal-track:before{content:"";background:#f1eee373;height:1px;position:absolute;top:50%;left:0;right:0}.signal-track:after{content:"";background:var(--lab-acid);width:24px;height:7px;animation:1.8s linear infinite signal-travel;position:absolute;top:calc(50% - 3px);left:12px}.signal-node{--node-accent:var(--lab-signal);z-index:1;min-width:128px;color:var(--lab-paper);background:var(--lab-ink-soft);animation:lab-enter .4s var(--lab-ease) var(--node-delay) both;border:1px solid #f1eee34d;grid-template-rows:auto auto;grid-template-columns:auto 1fr;align-items:center;column-gap:9px;padding:11px 12px;display:grid;position:relative;box-shadow:4px 4px #00000052}.signal-node strong{font-size:.78rem;line-height:1.2}.signal-node small{color:#f1eee38c;font:400 .6rem/1.2 var(--lab-mono);text-transform:uppercase;grid-column:2}.signal-light{border:2px solid var(--lab-ink-soft);background:#575751;outline:1px solid #f1eee359;grid-row:1/3;width:10px;height:10px}.signal-light.is-transcribing{background:var(--node-accent);animation:1.2s ease-out infinite signal-pulse}.signal-light.is-done{background:var(--lab-acid)}.signal-light.is-error,.signal-light.is-offline{background:var(--lab-danger)}.signal-empty{z-index:1;justify-self:center;position:relative;color:var(--lab-paper)!important;background:var(--lab-ink)!important;border:1px solid var(--lab-rule-light)!important;font-size:var(--lab-sm)!important;padding:0 18px!important}.source-console,.outputs-section{border-bottom:2px solid var(--lab-ink);padding:76px 0 80px}.source-console-head,.outputs-heading{grid-template-columns:minmax(280px,1fr) minmax(240px,.7fr);align-items:end;gap:40px;margin-bottom:28px;display:grid}.section-index{color:var(--lab-danger);margin-bottom:10px;display:block}.source-console-head h2,.outputs-heading h2{font:600 var(--lab-xl)/.95 var(--lab-display);letter-spacing:-.045em;margin:0}.source-console-head>p,.outputs-heading>p{max-width:430px;color:var(--lab-muted);font-size:var(--lab-sm);justify-self:end;margin:0;line-height:1.55}.source-actions{border:2px solid var(--lab-ink);box-shadow:var(--lab-shadow);grid-template-columns:minmax(210px,.75fr) minmax(300px,1.6fr) minmax(220px,.8fr);display:grid}.upload-plate,.run-button{flex-direction:column;justify-content:center;align-items:flex-start;min-height:136px;display:flex;transition:background var(--lab-fast), color var(--lab-fast)!important;padding:22px 24px!important}.upload-plate{border-right:1px solid var(--lab-ink)!important}.upload-plate svg{margin-bottom:15px}.upload-plate>span,.run-button>span{font-size:var(--lab-base);font-weight:700}.upload-plate>small,.run-button>small{color:var(--lab-muted);font:400 .62rem/1.4 var(--lab-mono);margin-top:6px}.upload-plate:hover{color:var(--lab-paper)!important;background:var(--lab-ink)!important}.upload-plate:hover small{color:#f1eee399}.selected-source{background:#ffffff3d;flex-direction:column;justify-content:center;min-width:0;padding:22px 30px;display:flex}.selected-source>span{color:var(--lab-muted);font:600 .62rem/1.2 var(--lab-mono);letter-spacing:.14em;margin-bottom:10px}.selected-source>strong{text-overflow:ellipsis;white-space:nowrap;max-width:100%;font:600 clamp(1.25rem, 2.5vw, 2.5rem)/1 var(--lab-display);letter-spacing:-.035em;overflow:hidden}.selected-source>small{color:var(--lab-muted);font-size:var(--lab-sm);margin-top:10px}.selected-source.has-file{background:var(--lab-acid)}.selected-source.has-file>span,.selected-source.has-file>small{color:#171714ad}.run-button{color:var(--lab-paper)!important;background:var(--lab-signal)!important;border-left:1px solid var(--lab-ink)!important}.run-button small{color:#1717149e}.run-button:hover:not(:disabled){background:var(--lab-ink)!important}.run-button:hover:not(:disabled) small{color:#f1eee399}.source-error{color:var(--lab-paper);background:var(--lab-danger);border-left:8px solid var(--lab-ink);font-size:var(--lab-sm);margin-top:18px;padding:14px 18px}.record-crate{margin-top:42px}.crate-heading{border-bottom:1px solid var(--lab-ink);justify-content:space-between;align-items:end;gap:20px;padding-bottom:13px;display:flex}.crate-heading>div{align-items:baseline;gap:18px;display:flex}.crate-heading span{color:var(--lab-danger);font:600 var(--lab-xs)/1.2 var(--lab-mono);letter-spacing:.12em}.crate-heading strong{font:600 var(--lab-lg)/1 var(--lab-display)}.crate-heading>small{max-width:520px;color:var(--lab-muted);font-size:var(--lab-xs);text-align:right}.crate-scroll{scrollbar-color:var(--lab-ink) var(--lab-paper-deep);grid-auto-columns:minmax(230px,1fr);grid-auto-flow:column;gap:1px;padding:1px 0 14px;display:grid;overflow-x:auto}.record-sleeve{text-align:left;flex-direction:column;align-items:flex-start;min-height:235px;display:flex;position:relative;overflow:hidden;border:1px solid var(--lab-ink)!important;transition:transform var(--lab-base-duration) var(--lab-ease), box-shadow var(--lab-base-duration) var(--lab-ease)!important;background:#dcd7c7!important;padding:18px!important}.record-sleeve:nth-child(4n+1){background:#e65a41!important}.record-sleeve:nth-child(4n+2){background:#67bdc8!important}.record-sleeve:nth-child(4n+3){background:#d5e45a!important}.record-sleeve:nth-child(4n+4){background:#e3b64a!important}.record-sleeve:after{content:"";border:28px solid #1717141f;border-radius:50%;width:150px;height:150px;position:absolute;bottom:-54px;right:-54px}.record-sleeve:hover:not(:disabled){z-index:2;box-shadow:7px 8px 0 var(--lab-ink);transform:translateY(-7px)rotate(-.4deg)}.record-sleeve:active:not(:disabled){transform:translateY(-2px)}.record-sleeve.is-loading{color:var(--lab-paper);background:var(--lab-ink)!important}.sleeve-number{font:500 .66rem/1 var(--lab-mono);margin-left:auto}.sleeve-genre{font:600 .62rem/1 var(--lab-mono);letter-spacing:.1em;text-transform:uppercase;margin-top:46px}.record-sleeve strong{z-index:1;max-width:94%;font:600 1.25rem/1.05 var(--lab-display);letter-spacing:-.025em;margin-top:9px;position:relative}.record-sleeve small{z-index:1;margin-top:auto;padding-top:18px;font-size:.66rem;line-height:1.35;position:relative}.crate-state{min-height:120px;color:var(--lab-muted);border-bottom:1px solid var(--lab-rule);font-size:var(--lab-sm);text-align:center;place-items:center;padding:20px;display:grid}.crate-state.is-error{color:var(--lab-danger)}.crate-state code{color:var(--lab-ink);background:var(--lab-paper-deep);font-family:var(--lab-mono);padding:2px 5px}.transport-console{z-index:20;min-height:78px;color:var(--lab-paper);border:1px solid var(--lab-ink);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);background:#171714f7;grid-template-columns:58px 112px minmax(140px,1fr) minmax(235px,auto) minmax(260px,auto);align-items:center;gap:18px;margin:26px 0;padding:10px 16px 10px 10px;display:grid;position:sticky;top:10px;box-shadow:6px 7px #1717142b}.transport-play{place-items:center;width:56px;height:56px;display:grid;min-height:56px!important;color:var(--lab-ink)!important;background:var(--lab-acid)!important}.transport-play:hover:not(:disabled){background:var(--lab-signal)!important}.transport-play svg{width:20px;height:20px}.transport-clock{font:500 .72rem/1 var(--lab-mono);font-variant-numeric:tabular-nums}.transport-seek,.transport-mix input{appearance:none;cursor:pointer;background:#f1eee352;height:3px}.transport-seek{width:100%}.transport-seek::-webkit-slider-thumb{appearance:none;background:var(--lab-signal);border:2px solid var(--lab-ink);outline:1px solid var(--lab-paper);border-radius:0;width:15px;height:15px}.transport-mix input::-webkit-slider-thumb{appearance:none;background:var(--lab-signal);border:2px solid var(--lab-ink);outline:1px solid var(--lab-paper);border-radius:0;width:15px;height:15px}.transport-seek::-moz-range-thumb{background:var(--lab-signal);border:2px solid var(--lab-paper);border-radius:0;width:12px;height:12px}.transport-mix input::-moz-range-thumb{background:var(--lab-signal);border:2px solid var(--lab-paper);border-radius:0;width:12px;height:12px}.transport-mix{color:#f1eee39e;font:500 .59rem/1 var(--lab-mono);text-transform:uppercase;grid-template-columns:auto minmax(90px,1fr) auto;align-items:center;gap:8px;display:grid}.listen-switch{justify-content:flex-end;align-items:center;gap:4px;display:flex;overflow-x:auto}.listen-switch>span{color:#f1eee37a;font:500 .58rem/1 var(--lab-mono);text-transform:uppercase;flex:none;margin-right:5px}.listen-switch button{flex:none;color:#f1eee3a6!important;border:1px solid var(--lab-rule-light)!important;min-height:36px!important;padding:0 10px!important;font-size:.68rem!important}.listen-switch button:hover:not(:disabled),.listen-switch button.is-active{color:var(--lab-ink)!important;background:var(--model-accent)!important;border-color:var(--model-accent)!important}.outputs-section{padding-top:56px}.model-grid{grid-template-columns:repeat(auto-fit,minmax(min(100%,540px),1fr));align-items:start;gap:22px;display:grid}.model-panel{--model-accent:var(--lab-signal);background:var(--lab-ink);border:2px solid var(--lab-ink);min-width:0;animation:lab-enter var(--lab-slow) var(--lab-ease) calc(var(--panel-order) * 65ms) both;box-shadow:7px 7px #17171424}.model-panel.status-transcribing{box-shadow:7px 7px 0 var(--model-accent)}.model-panel.status-error{border-color:var(--lab-danger)}.model-panel-head{min-height:114px;color:var(--lab-paper);border-bottom:1px solid var(--lab-rule-light);justify-content:space-between;align-items:flex-start;gap:18px;padding:18px 20px;display:flex}.model-panel-head>div:first-child>span{color:var(--model-accent);font:600 .59rem/1 var(--lab-mono);letter-spacing:.12em;text-transform:uppercase}.model-panel h3{font:600 2.1rem/.95 var(--lab-display);letter-spacing:-.035em;margin:5px 0 3px}.model-panel-head>div:first-child>small{color:#f1eee380;font-size:.66rem}.model-metrics{text-align:right;grid-template-columns:repeat(2,auto);gap:8px 18px;display:grid}.model-state{color:#f1eee39e;font:500 .58rem/1 var(--lab-mono);text-transform:uppercase;grid-column:1/-1;justify-content:flex-end;align-items:center;gap:7px;display:flex}.model-state i{background:#5f5f58;width:8px;height:8px}.status-transcribing .model-state i{background:var(--model-accent);animation:1.2s ease-out infinite signal-pulse}.status-done .model-state i{background:var(--lab-acid)}.status-error .model-state i{background:var(--lab-danger)}.model-metrics>strong{font:500 .75rem/1.2 var(--lab-mono)}.model-metrics>strong>small{color:#f1eee361;text-transform:uppercase;margin-top:3px;font-size:.53rem;font-weight:400;display:block}.roll-frame{background:#0b0c10;min-height:390px;position:relative;overflow:hidden}.roll-frame canvas{width:100%;height:390px;display:block}.roll-state{color:#f1eee394;text-align:center;background:#0b0c10e6;flex-direction:column;justify-content:center;align-items:center;gap:6px;padding:35px;display:flex;position:absolute;inset:0}.roll-state>span{font:600 1.55rem/1 var(--lab-display);color:var(--lab-paper)}.roll-state>small{max-width:410px;font-size:.72rem;line-height:1.5}.roll-state.is-error{background:var(--lab-danger)}@supports (color:color-mix(in lab, red, red)){.roll-state.is-error{background:color-mix(in srgb, var(--lab-danger) 18%, #0b0c10f5)}}.roll-state button{margin-top:10px;color:var(--lab-paper)!important;border:1px solid #f1eee380!important;padding:0 14px!important;font-size:.7rem!important}.roll-state button:hover{color:var(--lab-ink)!important;background:var(--lab-paper)!important}.panel-progress{background:var(--model-accent);height:4px;transition:width .36s var(--lab-ease);position:absolute;bottom:0;left:0}.model-panel-foot{min-height:57px;color:var(--lab-paper);border-top:1px solid var(--lab-rule-light);align-items:center;gap:12px;padding:10px 14px;display:flex}.instrument-tape{scrollbar-width:thin;flex:1;align-items:center;gap:8px 12px;min-width:0;display:flex;overflow-x:auto}.instrument-tape>span{color:#f1eee394;flex:none;align-items:center;gap:5px;font-size:.61rem;display:inline-flex}.instrument-tape>span>i{width:8px;height:8px}.midi-download{background:var(--lab-acid);min-height:34px;font:600 .61rem/34px var(--lab-mono);flex:none;align-items:center;gap:5px;padding:0 10px;text-decoration:none;display:inline-flex;color:var(--lab-ink)!important}.midi-download:hover{background:var(--model-accent)}.outputs-empty{flex-direction:column;justify-content:center;align-items:center;gap:8px;width:100%;display:flex;border:2px dashed var(--lab-rule)!important;min-height:240px!important}.outputs-empty strong{font:600 1.8rem/1 var(--lab-display)}.outputs-empty span{color:var(--lab-muted);font-size:var(--lab-sm)}.outputs-empty:hover{color:var(--lab-paper)!important;background:var(--lab-ink)!important;border-color:var(--lab-ink)!important}.compare-footer{width:min(100% - 48px,1880px);min-height:180px;font-size:var(--lab-xs);grid-template-columns:1fr minmax(280px,1fr) auto;align-items:center;gap:30px;margin:0 auto;display:grid}.compare-footer>span{font:600 var(--lab-xs)/1.4 var(--lab-mono);letter-spacing:.1em}.compare-footer p{color:var(--lab-muted);line-height:1.5}.compare-footer a{border-bottom:1px solid var(--lab-ink);padding:10px 0;font-weight:700;text-decoration:none}.compare-footer a:hover{color:var(--lab-danger)}.drop-field{z-index:80;color:var(--lab-paper);border:4px solid var(--lab-acid);pointer-events:none;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);background:#171714f0;flex-direction:column;justify-content:center;align-items:center;display:flex;position:fixed;inset:18px}.drop-field span{color:var(--lab-acid);font:600 var(--lab-xs)/1 var(--lab-mono);letter-spacing:.16em}.drop-field strong{font:600 clamp(2rem, 6vw, 5rem)/.95 var(--lab-display);margin-top:12px}.config-backdrop{z-index:120;-webkit-backdrop-filter:blur(5px);backdrop-filter:blur(5px);background:#1717149e;justify-content:flex-end;display:flex;position:fixed;inset:0}.config-drawer{width:min(680px,100%);height:100%;color:var(--lab-ink);background:var(--lab-paper);border-left:2px solid var(--lab-ink);animation:lab-enter .34s var(--lab-ease) both;padding:34px;overflow-y:auto;box-shadow:-16px 0 #17171421}.config-drawer>header{border-bottom:2px solid var(--lab-ink);justify-content:space-between;align-items:flex-start;gap:20px;padding-bottom:22px;display:flex}.config-drawer>header span{color:var(--lab-danger);font:600 var(--lab-xs)/1 var(--lab-mono);letter-spacing:.12em}.config-drawer h2{font:600 clamp(2.4rem, 7vw, 4.4rem)/.9 var(--lab-display);letter-spacing:-.05em;margin:8px 0 0}.config-close{place-items:center;width:48px;display:grid;border:1px solid var(--lab-ink)!important;min-height:48px!important}.config-close:hover{color:var(--lab-paper)!important;background:var(--lab-ink)!important}.config-lede{max-width:530px;color:var(--lab-muted);font-size:var(--lab-sm);margin:22px 0;line-height:1.6}.config-presets{flex-wrap:wrap;gap:5px;margin-bottom:24px;display:flex}.config-presets button{border:1px solid var(--lab-rule)!important;min-height:36px!important;padding:0 12px!important;font-size:.68rem!important}.config-presets button:hover{color:var(--lab-paper)!important;background:var(--lab-ink)!important}.config-models{gap:10px;display:grid}.config-model{--model-accent:var(--lab-signal);border:1px solid var(--lab-rule);background:#ffffff42;grid-template-columns:1fr auto;gap:15px;padding:16px;display:grid;position:relative}.config-model:before{content:"";background:0 0;width:5px;position:absolute;inset:0 auto 0 0}.config-model.is-enabled:before{background:var(--model-accent)}.config-toggle{cursor:pointer;grid-column:1/-1;grid-template-columns:auto auto 1fr auto;align-items:center;gap:10px;display:grid}.config-toggle input{opacity:0;pointer-events:none;position:absolute}.config-toggle>span{border:1px solid var(--lab-ink);background:#bbb7a9;width:38px;height:21px;position:relative}.config-toggle>span:after{content:"";background:var(--lab-paper);border:1px solid var(--lab-ink);width:13px;height:13px;transition:transform var(--lab-fast);position:absolute;top:3px;left:3px}.config-toggle input:checked+span{background:var(--model-accent)}.config-toggle input:checked+span:after{transform:translate(17px)}.config-toggle input:focus-visible+span{outline:3px solid var(--lab-focus);outline-offset:3px}.config-toggle strong{font:600 1.18rem/1 var(--lab-display)}.config-toggle small{color:var(--lab-muted);font:500 .57rem/1 var(--lab-mono);text-transform:uppercase}.endpoint-field{gap:5px;min-width:0;display:grid}.endpoint-field>span{color:var(--lab-muted);font:500 .55rem/1 var(--lab-mono);text-transform:uppercase}.endpoint-field input{width:100%;min-width:0;height:37px;color:var(--lab-ink);background:var(--lab-paper);border:1px solid var(--lab-rule);font:400 .68rem/1 var(--lab-mono);border-radius:0;padding:0 9px}.endpoint-health{min-width:72px;height:37px;color:var(--lab-muted);font:500 .56rem/1 var(--lab-mono);text-transform:uppercase;align-self:end;align-items:center;gap:6px;display:flex}.endpoint-health i{background:var(--lab-warning);width:7px;height:7px}.endpoint-health.is-online i{background:var(--lab-success)}.endpoint-health.is-offline i{background:var(--lab-danger)}.config-note{border-top:1px solid var(--lab-rule);border-bottom:1px solid var(--lab-rule);font-size:var(--lab-xs);grid-template-columns:130px 1fr;gap:14px;margin:22px 0;padding:15px 0;line-height:1.5;display:grid}.config-note span{color:var(--lab-muted)}.config-note code{color:var(--lab-ink);font-family:var(--lab-mono)}.config-done{width:100%;min-height:58px!important;color:var(--lab-paper)!important;background:var(--lab-ink)!important;font-weight:700!important}.config-done:hover:not(:disabled){color:var(--lab-ink)!important;background:var(--lab-acid)!important}@media (width>=1600px){.model-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.source-actions{grid-template-columns:.65fr 1.8fr .7fr}}@media (width<=1180px){.compare-masthead{grid-template-columns:160px 1fr;min-height:390px}.compare-config-button{grid-area:2/1;place-self:end start}.compare-intro{grid-area:1/2/3}.signal-rail{grid-template-columns:90px 1fr 80px}.signal-track{padding-left:20px;padding-right:20px}.source-actions{grid-template-columns:.8fr 1.4fr}.run-button{grid-column:1/-1;min-height:88px;border-top:1px solid var(--lab-ink)!important;border-left:0!important}.transport-console{grid-template-columns:58px 105px 1fr minmax(220px,auto)}.listen-switch{grid-column:1/-1;justify-content:flex-start;padding:4px 0}}@media (width<=760px){.compare-masthead,.compare-main,.compare-footer{width:min(100% - 28px,1880px)}.compare-masthead{grid-template-columns:1fr auto;gap:24px;min-height:auto;padding:22px 0 32px}.compare-wordmark{grid-column:1}.compare-config-button{grid-area:1/2;place-items:center;width:48px;height:48px;min-height:48px;display:grid;border:1px solid var(--lab-ink)!important;padding:0!important}.compare-config-button:hover{padding:0!important}.compare-config-button>.config-button-label{display:none}.compare-config-button>svg{width:19px;height:19px}.compare-config-button>.config-button-count{width:21px;height:21px;margin:-34px 0 0 36px;font-size:.58rem;position:absolute}.compare-intro{grid-area:2/1/auto/-1;padding-top:22px}.compare-intro h1{font-size:clamp(3.5rem,18vw,6.8rem);line-height:.82}.compare-intro>p:last-child{width:100%;margin-top:30px}.preset-strip{overflow-x:auto}.preset-label{z-index:1;background:var(--lab-paper);padding:0 14px;position:sticky;left:0}.preset-button{min-width:126px}.signal-rail{grid-template-columns:68px minmax(0,1fr);min-height:118px}.signal-output{display:none}.signal-origin{padding:10px}.signal-track{grid-template-columns:none;grid-auto-columns:145px;grid-auto-flow:column;padding:15px}.source-console,.outputs-section{padding:54px 0}.source-console-head,.outputs-heading{grid-template-columns:1fr;gap:16px}.source-console-head>p,.outputs-heading>p{justify-self:start}.source-actions{grid-template-columns:1fr;box-shadow:5px 5px #17171426}.upload-plate{min-height:104px;border-right:0!important;border-bottom:1px solid var(--lab-ink)!important}.selected-source{min-height:112px;padding:22px}.run-button{grid-column:auto;min-height:86px}.crate-heading{flex-direction:column;align-items:flex-start}.crate-heading>small{text-align:left}.crate-scroll{grid-auto-columns:minmax(205px,78vw)}.record-sleeve{min-height:220px}.transport-console{grid-template-columns:52px 1fr;gap:11px;padding:8px;top:6px}.transport-play{width:50px;height:50px;min-height:50px!important}.transport-clock{text-align:right}.transport-seek,.transport-mix,.listen-switch{grid-column:1/-1}.transport-mix{padding:5px}.listen-switch{justify-content:flex-start}.model-grid{grid-template-columns:1fr}.model-panel-head{min-height:130px}.model-panel h3{font-size:1.8rem}.roll-frame,.roll-frame canvas{height:340px;min-height:340px}.compare-footer{grid-template-columns:1fr;gap:14px;padding:38px 0}.compare-footer p{margin:0}.compare-footer a{width:fit-content}.config-drawer{padding:22px 16px 32px}}@media (width<=460px){.compare-masthead,.compare-main,.compare-footer{width:min(100% - 20px,1880px)}.compare-intro h1{font-size:clamp(3rem,17vw,4.9rem)}.compare-intro>p:last-child{font-size:.86rem}.signal-origin{display:none}.signal-rail{grid-template-columns:1fr}.source-console-head h2,.outputs-heading h2{font-size:2.6rem}.selected-source>strong{font-size:1.5rem}.model-panel-head{flex-direction:column}.model-metrics{text-align:left;grid-template-columns:1fr auto auto;width:100%}.model-state{grid-column:auto;justify-content:flex-start}.model-metrics>strong{text-align:right}.roll-frame,.roll-frame canvas{height:300px;min-height:300px}.config-model{grid-template-columns:1fr}.endpoint-health{align-self:start;height:auto}.config-note{grid-template-columns:1fr}}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@keyframes ping{0%{box-shadow:0 0 0 0 var(--color-accent-glow)}70%{box-shadow:0 0 0 7px #0000}to{box-shadow:0 0 #0000}}@keyframes drag-glow{0%,to{box-shadow:0 0 0 1px var(--color-accent-soft), 0 0 14px -2px var(--color-accent-glow)}50%{box-shadow:0 0 0 1px var(--color-accent), 0 0 40px 2px var(--color-accent-glow)}}@keyframes rise{0%{opacity:0;transform:translateY(14px)}to{opacity:1;transform:none}} diff --git a/assets/style-CdJLhYve.js b/assets/style-CdJLhYve.js new file mode 100644 index 0000000000000000000000000000000000000000..69830573db4aeb956590f4fb0a201796dee062c2 --- /dev/null +++ b/assets/style-CdJLhYve.js @@ -0,0 +1,220 @@ +var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),t=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")});(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var n=e((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,S||(S=!0,O());else{var t=n(l);t!==null&&ne(x,t.startTime-e)}}var S=!1,C=-1,w=5,T=-1;function E(){return g?!0:!(e.unstable_now()-Tt&&E());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&ne(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var ee=new MessageChannel,te=ee.port2;ee.port1.onmessage=D,O=function(){te.postMessage(null)}}else O=function(){_(D,0)};function ne(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,ne(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,O()))),r},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),r=e(((e,t)=>{t.exports=n()})),i=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function D(e,t){return E(e.type,t,e.props)}function O(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function ee(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var te=/\/+/g;function ne(e,t){return typeof e==`object`&&e&&e.key!=null?ee(``+e.key):t.toString(36)}function re(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function ie(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,ie(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+ne(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(te,`$&/`)+`/`),ie(o,r,i,``,function(e){return e})):o!=null&&(O(o)&&(o=D(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(te,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{t.exports=i()})),o=e((e=>{var t=a();function n(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=o()})),c=e((e=>{var t=r(),n=a(),i=s();function o(e){var t=`https://react.dev/errors/`+e;if(1le||(e.current=ce[le],ce[le]=null,le--)}function N(e,t){le++,ce[le]=e.current,e.current=t}var P=j(null),ue=j(null),de=j(null),fe=j(null);function pe(e,t){switch(N(de,t),N(ue,e),N(P,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Vd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Vd(t),e=Hd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}M(P),N(P,e)}function me(){M(P),M(ue),M(de)}function he(e){e.memoizedState!==null&&N(fe,e);var t=P.current,n=Hd(t,e.type);t!==n&&(N(ue,e),N(P,n))}function ge(e){ue.current===e&&(M(P),M(ue)),fe.current===e&&(M(fe),Qf._currentValue=se)}var _e,ve;function ye(e){if(_e===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);_e=t&&t[1]||``,ve=-1)`:-1i||c[r]!==l[i]){var u=` +`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{be=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?ye(n):``}function Se(e,t){switch(e.tag){case 26:case 27:case 5:return ye(e.type);case 16:return ye(`Lazy`);case 13:return e.child!==t&&t!==null?ye(`Suspense Fallback`):ye(`Suspense`);case 19:return ye(`SuspenseList`);case 0:case 15:return xe(e.type,!1);case 11:return xe(e.type.render,!1);case 1:return xe(e.type,!0);case 31:return ye(`Activity`);default:return``}}function Ce(e){try{var t=``,n=null;do t+=Se(e,n),n=e,e=e.return;while(e);return t}catch(e){return` +Error generating stack: `+e.message+` +`+e.stack}}var we=Object.prototype.hasOwnProperty,Te=t.unstable_scheduleCallback,Ee=t.unstable_cancelCallback,De=t.unstable_shouldYield,Oe=t.unstable_requestPaint,ke=t.unstable_now,Ae=t.unstable_getCurrentPriorityLevel,je=t.unstable_ImmediatePriority,Me=t.unstable_UserBlockingPriority,Ne=t.unstable_NormalPriority,Pe=t.unstable_LowPriority,Fe=t.unstable_IdlePriority,Ie=t.log,Le=t.unstable_setDisableYieldValue,Re=null,ze=null;function Be(e){if(typeof Ie==`function`&&Le(e),ze&&typeof ze.setStrictMode==`function`)try{ze.setStrictMode(Re,e)}catch{}}var Ve=Math.clz32?Math.clz32:We,He=Math.log,Ue=Math.LN2;function We(e){return e>>>=0,e===0?32:31-(He(e)/Ue|0)|0}var Ge=256,Ke=262144,qe=4194304;function Je(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Ye(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=Je(n))):i=Je(o):i=Je(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=Je(n))):i=Je(o)):i=Je(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function Xe(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Ze(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Qe(){var e=qe;return qe<<=1,!(qe&62914560)&&(qe=4194304),e}function $e(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function et(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function tt(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),mn=!1;if(pn)try{var hn={};Object.defineProperty(hn,"passive",{get:function(){mn=!0}}),window.addEventListener(`test`,hn,hn),window.removeEventListener(`test`,hn,hn)}catch{mn=!1}var gn=null,_n=null,vn=null;function yn(){if(vn)return vn;var e,t=_n,n=t.length,r,i=`value`in gn?gn.value:gn.textContent,a=i.length;for(e=0;e=Zn),er=` `,tr=!1;function nr(e,t){switch(e){case`keyup`:return Yn.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function rr(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var ir=!1;function ar(e,t){switch(e){case`compositionend`:return rr(t);case`keypress`:return t.which===32?(tr=!0,er):null;case`textInput`:return e=t.data,e===er&&tr?null:e;default:return null}}function or(e,t){if(ir)return e===`compositionend`||!Xn&&nr(e,t)?(e=yn(),vn=_n=gn=null,ir=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=Or(n)}}function Ar(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Ar(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function jr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Bt(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Bt(e.document)}return t}function Mr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var Nr=pn&&`documentMode`in document&&11>=document.documentMode,Pr=null,Fr=null,Ir=null,Lr=!1;function Rr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Lr||Pr==null||Pr!==Bt(r)||(r=Pr,`selectionStart`in r&&Mr(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ir&&Dr(Ir,r)||(Ir=r,r=Td(Fr,`onSelect`),0>=o,i-=o,Ai=1<<32-Ve(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),o=a(_,o,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),F&&Mi(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(i,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(i,h),s=a(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(i,h),F&&Mi(i,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(i,v.value,l),v!==null&&(s=a(v,s,g),d===null?u=v:d.sibling=v,d=v);return F&&Mi(i,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,i,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=a(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(i,e)}),F&&Mi(i,g),u}function b(e,r,a,c){if(typeof a==`object`&&a&&a.type===y&&a.key===null&&(a=a.props.children),typeof a==`object`&&a){switch(a.$$typeof){case _:a:{for(var l=a.key;r!==null;){if(r.key===l){if(l=a.type,l===y){if(r.tag===7){n(e,r.sibling),c=i(r,a.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===O&&ja(l)===r.type){n(e,r.sibling),c=i(r,a.props),Ra(c,a),c.return=e,e=c;break a}n(e,r);break}else t(e,r);r=r.sibling}a.type===y?(c=_i(a.props.children,e.mode,c,a.key),c.return=e,e=c):(c=gi(a.type,a.key,a.props,null,e.mode,c),Ra(c,a),c.return=e,e=c)}return s(e);case v:a:{for(l=a.key;r!==null;){if(r.key===l)if(r.tag===4&&r.stateNode.containerInfo===a.containerInfo&&r.stateNode.implementation===a.implementation){n(e,r.sibling),c=i(r,a.children||[]),c.return=e,e=c;break a}else{n(e,r);break}else t(e,r);r=r.sibling}c=bi(a,e.mode,c),c.return=e,e=c}return s(e);case O:return a=ja(a),b(e,r,a,c)}if(oe(a))return h(e,r,a,c);if(re(a)){if(l=re(a),typeof l!=`function`)throw Error(o(150));return a=l.call(a),g(e,r,a,c)}if(typeof a.then==`function`)return b(e,r,La(a),c);if(a.$$typeof===C)return b(e,r,oa(e,a),c);za(e,a)}return typeof a==`string`&&a!==``||typeof a==`number`||typeof a==`bigint`?(a=``+a,r!==null&&r.tag===6?(n(e,r.sibling),c=i(r,a),c.return=e,e=c):(n(e,r),c=vi(a,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Ia=0;var i=b(e,t,n,r);return Fa=null,i}catch(t){if(t===Ta||t===Da)throw t;var a=fi(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Va=Ba(!0),Ha=Ba(!1),Ua=!1;function Wa(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ga(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function Ka(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function qa(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,zl&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=li(e),ci(e,null,n),t}return ai(e,r,t,n),li(e)}function Ja(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,rt(e,n)}}function Ya(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Xa=!1;function Za(){if(Xa){var e=ga;if(e!==null)throw e}}function Qa(e,t,n,r){Xa=!1;var i=e.updateQueue;Ua=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(q&f)===f:(r&f)===f){f!==0&&f===I&&(Xa=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(m=g.payload,typeof m==`function`){d=m.call(_,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=g.payload,f=typeof m==`function`?m.call(_,d,f):m,f==null)break a;d=h({},d,f);break a;case 2:Ua=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),Kl|=o,e.lanes=o,e.memoizedState=d}}function $a(e,t){if(typeof e!=`function`)throw Error(o(191,e));e.call(t)}function eo(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=k.T,s={};k.T=s,Ls(e,!1,t,n);try{var c=i(),l=k.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Is(e,t,ya(c,r),mu(e)):Is(e,t,r,mu(e))}catch(n){Is(e,t,{then:function(){},status:`rejected`,reason:n},mu())}finally{A.p=a,o!==null&&s.types!==null&&(o.types=s.types),k.T=o}}function Es(){}function Ds(e,t,n,r){if(e.tag!==5)throw Error(o(476));var i=Os(e).queue;Ts(e,i,t,se,n===null?Es:function(){return ks(e),n(r)})}function Os(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:se,baseState:se,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Vo,lastRenderedState:se},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Vo,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function ks(e){var t=Os(e);t.next===null&&(t=e.alternate.memoizedState),Is(e,t.next.queue,{},mu())}function As(){return aa(Qf)}function js(){return Io().memoizedState}function Ms(){return Io().memoizedState}function Ns(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=mu();e=Ka(n);var r=qa(t,e,n);r!==null&&(X(r,t,n),Ja(r,t,n)),t={cache:fa()},e.payload=t;return}t=t.return}}function Ps(e,t,n){var r=mu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Rs(e)?zs(t,n):(n=oi(e,t,n,r),n!==null&&(X(n,e,r),Bs(n,t,r)))}function Fs(e,t,n){Is(e,t,n,mu())}function Is(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Rs(e))zs(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,Er(s,o))return ai(e,t,i,0),Bl===null&&ii(),!1}catch{}if(n=oi(e,t,i,r),n!==null)return X(n,e,r),Bs(n,t,r),!0}return!1}function Ls(e,t,n,r){if(r={lane:2,revertLane:ud(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Rs(e)){if(t)throw Error(o(479))}else t=oi(e,n,r,2),t!==null&&X(t,e,2)}function Rs(e){var t=e.alternate;return e===L||t!==null&&t===L}function zs(e,t){bo=yo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Bs(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,rt(e,n)}}var Vs={readContext:aa,use:zo,useCallback:Eo,useContext:Eo,useEffect:Eo,useImperativeHandle:Eo,useLayoutEffect:Eo,useInsertionEffect:Eo,useMemo:Eo,useReducer:Eo,useRef:Eo,useState:Eo,useDebugValue:Eo,useDeferredValue:Eo,useTransition:Eo,useSyncExternalStore:Eo,useId:Eo,useHostTransitionStatus:Eo,useFormState:Eo,useActionState:Eo,useOptimistic:Eo,useMemoCache:Eo,useCacheRefresh:Eo};Vs.useEffectEvent=Eo;var Hs={readContext:aa,use:zo,useCallback:function(e,t){return Fo().memoizedState=[e,t===void 0?null:t],e},useContext:aa,useEffect:ps,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),ds(4194308,4,ys.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ds(4194308,4,e,t)},useInsertionEffect:function(e,t){ds(4,2,e,t)},useMemo:function(e,t){var n=Fo();t=t===void 0?null:t;var r=e();if(xo){Be(!0);try{e()}finally{Be(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=Fo();if(n!==void 0){var i=n(t);if(xo){Be(!0);try{n(t)}finally{Be(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=Ps.bind(null,L,e),[r.memoizedState,e]},useRef:function(e){var t=Fo();return e={current:e},t.memoizedState=e},useState:function(e){e=z(e);var t=e.queue,n=Fs.bind(null,L,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:B,useDeferredValue:function(e,t){return Cs(Fo(),e,t)},useTransition:function(){var e=z(!1);return e=Ts.bind(null,L,e.queue,!0,!1),Fo().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=L,i=Fo();if(F){if(n===void 0)throw Error(o(407));n=n()}else{if(n=t(),Bl===null)throw Error(o(349));q&127||Go(r,t,n)}i.memoizedState=n;var a={value:n,getSnapshot:t};return i.queue=a,ps(qo.bind(null,r,a,e),[e]),r.flags|=2048,ls(9,{destroy:void 0},Ko.bind(null,r,a,n,t),null),n},useId:function(){var e=Fo(),t=Bl.identifierPrefix;if(F){var n=ji,r=Ai;n=(r&~(1<<32-Ve(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=So++,0<\/script>`,a=a.removeChild(a.firstChild);break;case`select`:a=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?a.multiple=!0:r.size&&(a.size=r.size);break;default:a=typeof r.is==`string`?s.createElement(i,{is:r.is}):s.createElement(i)}}a[ut]=t,a[dt]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)a.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=a;a:switch(Pd(a,i,r),i){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&Fc(t)}}return Bc(t),Ic(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Fc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(o(166));if(e=de.current,Gi(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,i=Li,i!==null)switch(i.tag){case 27:case 5:r=i.memoizedProps}e[ut]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||jd(e.nodeValue,n)),e||Hi(t,!0)}else e=Bd(e).createTextNode(r),e[ut]=t,t.stateNode=e}return Bc(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Gi(t),n!==null){if(e===null){if(!r)throw Error(o(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(o(557));e[ut]=t}else Ki(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Bc(t),e=!1}else n=qi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(po(t),t):(po(t),null);if(t.flags&128)throw Error(o(558))}return Bc(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(i=Gi(t),r!==null&&r.dehydrated!==null){if(e===null){if(!i)throw Error(o(318));if(i=t.memoizedState,i=i===null?null:i.dehydrated,!i)throw Error(o(317));i[ut]=t}else Ki(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Bc(t),i=!1}else i=qi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),i=!0;if(!i)return t.flags&256?(po(t),t):(po(t),null)}return po(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,i=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(i=r.alternate.memoizedState.cachePool.pool),a=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(a=r.memoizedState.cachePool.pool),a!==i&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Rc(t,t.updateQueue),Bc(t),null);case 4:return me(),e===null&&xd(t.stateNode.containerInfo),Bc(t),null;case 10:return $i(t.type),Bc(t),null;case 19:if(M(mo),r=t.memoizedState,r===null)return Bc(t),null;if(i=(t.flags&128)!=0,a=r.rendering,a===null)if(i)zc(r,!1);else{if(Gl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(a=ho(e),a!==null){for(t.flags|=128,zc(r,!1),e=a.updateQueue,t.updateQueue=e,Rc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)hi(n,e),n=n.sibling;return N(mo,mo.current&1|2),F&&Mi(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&ke()>nu&&(t.flags|=128,i=!0,zc(r,!1),t.lanes=4194304)}else{if(!i)if(e=ho(a),e!==null){if(t.flags|=128,i=!0,e=e.updateQueue,t.updateQueue=e,Rc(t,e),zc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!a.alternate&&!F)return Bc(t),null}else 2*ke()-r.renderingStartTime>nu&&n!==536870912&&(t.flags|=128,i=!0,zc(r,!1),t.lanes=4194304);r.isBackwards?(a.sibling=t.child,t.child=a):(e=r.last,e===null?t.child=a:e.sibling=a,r.last=a)}return r.tail===null?(Bc(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=ke(),e.sibling=null,n=mo.current,N(mo,i?n&1|2:n&1),F&&Mi(t,r.treeForkCount),e);case 22:case 23:return po(t),ao(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Bc(t),t.subtreeFlags&6&&(t.flags|=8192)):Bc(t),n=t.updateQueue,n!==null&&Rc(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&M(xa),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),$i(da),Bc(t),null;case 25:return null;case 30:return null}throw Error(o(156,t.tag))}function Hc(e,t){switch(Fi(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return $i(da),me(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return ge(t),null;case 31:if(t.memoizedState!==null){if(po(t),t.alternate===null)throw Error(o(340));Ki()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(po(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(o(340));Ki()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return M(mo),null;case 4:return me(),null;case 10:return $i(t.type),null;case 22:case 23:return po(t),ao(),e!==null&&M(xa),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return $i(da),null;case 25:return null;default:return null}}function Uc(e,t){switch(Fi(t),t.tag){case 3:$i(da),me();break;case 26:case 27:case 5:ge(t);break;case 4:me();break;case 31:t.memoizedState!==null&&po(t);break;case 13:po(t);break;case 19:M(mo);break;case 10:$i(t.type);break;case 22:case 23:po(t),ao(),e!==null&&M(xa);break;case 24:$i(da)}}function Wc(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){Gu(t,t.return,e)}}function Gc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){Gu(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Gu(t,t.return,e)}}function Kc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{eo(t,n)}catch(t){Gu(e,e.return,t)}}}function qc(e,t,n){n.props=Ys(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Gu(e,t,n)}}function Jc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){Gu(e,t,n)}}function Yc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null)if(typeof r==`function`)try{r()}catch(n){Gu(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){Gu(e,t,n)}else n.current=null}function Xc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){Gu(e,e.return,t)}}function Zc(e,t,n){try{var r=e.stateNode;Fd(r,e.type,n,t),r[dt]=t}catch(t){Gu(e,e.return,t)}}function Qc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Zd(e.type)||e.tag===4}function $c(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Qc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&Zd(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function el(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=rn));else if(r!==4&&(r===27&&Zd(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(el(e,t,n),e=e.sibling;e!==null;)el(e,t,n),e=e.sibling}function tl(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&Zd(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(tl(e,t,n),e=e.sibling;e!==null;)tl(e,t,n),e=e.sibling}function nl(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Pd(t,r,n),t[ut]=e,t[dt]=n}catch(t){Gu(e,e.return,t)}}var rl=!1,il=!1,al=!1,ol=typeof WeakSet==`function`?WeakSet:Set,sl=null;function cl(e,t){if(e=e.containerInfo,Rd=sp,e=jr(e),Mr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,a=r.focusNode;r=r.focusOffset;try{n.nodeType,a.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||i!==0&&f.nodeType!==3||(c=s+i),f!==a||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===i&&(c=s),p===a&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(zd={focusedElem:e,selectionRange:n},sp=!1,sl=t;sl!==null;)if(t=sl,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,sl=e;else for(;sl!==null;){switch(t=sl,a=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),Pd(a,r,n),a[ut]=e,Ct(a),r=a;break a;case`link`:var s=Vf(`link`,`href`,i).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=kr(s,h),v=kr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,k.T=null,n=uu,uu=null;var a=ou,s=cu;if(au=0,su=ou=null,cu=0,zl&6)throw Error(o(331));var c=zl;if(zl|=4,Fl(a.current),kl(a,a.current,s,n),zl=c,Z(0,!1),ze&&typeof ze.onPostCommitFiberRoot==`function`)try{ze.onPostCommitFiberRoot(Re,a)}catch{}return!0}finally{A.p=i,k.T=r,Vu(e,t)}}function Wu(e,t,n){t=Si(n,t),t=tc(e.stateNode,t,2),e=qa(e,t,2),e!==null&&(et(e,2),id(e))}function Gu(e,t,n){if(e.tag===3)Wu(e,e,n);else for(;t!==null;){if(t.tag===3){Wu(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(iu===null||!iu.has(r))){e=Si(n,e),n=nc(2),r=qa(t,n,2),r!==null&&(rc(n,r,t,e),et(r,2),id(r));break}}t=t.return}}function Ku(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new G;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(Ul=!0,i.add(n),e=qu.bind(null,e,t,n),t.then(e,e))}function qu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Bl===e&&(q&n)===n&&(Gl===4||Gl===3&&(q&62914560)===q&&300>ke()-eu?!(zl&2)&&Su(e,0):Jl|=n,Xl===q&&(Xl=0)),id(e)}function Ju(e,t){t===0&&(t=Qe()),e=si(e,t),e!==null&&(et(e,t),id(e))}function Yu(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Ju(e,n)}function Xu(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(o(314))}r!==null&&r.delete(t),Ju(e,n)}function Zu(e,t){return Te(e,t)}var Qu=null,$u=null,ed=!1,td=!1,nd=!1,rd=0;function id(e){e!==$u&&e.next===null&&($u===null?Qu=$u=e:$u=$u.next=e),td=!0,ed||(ed=!0,ld())}function Z(e,t){if(!nd&&td){nd=!0;do for(var n=!1,r=Qu;r!==null;){if(!t)if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Ve(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,cd(r,a))}else a=q,a=Ye(r,r===Bl?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||Xe(r,a)||(n=!0,cd(r,a));r=r.next}while(n);nd=!1}}function Q(){ad()}function ad(){td=ed=!1;var e=0;rd!==0&&Gd()&&(e=rd);for(var t=ke(),n=null,r=Qu;r!==null;){var i=r.next,a=od(r,t);a===0?(r.next=null,n===null?Qu=i:n.next=i,i===null&&($u=n)):(n=r,(e!==0||a&3)&&(td=!0)),r=i}au!==0&&au!==5||Z(e,!1),rd!==0&&(rd=0)}function od(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Id(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function xf(e,t,n){var r=bf;if(r&&typeof t==`string`&&t){var i=Ht(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),hf.has(i)||(hf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Pd(t,`link`,e),Ct(t),r.head.appendChild(t)))}}function Sf(e){_f.D(e),xf(`dns-prefetch`,e,null)}function Cf(e,t){_f.C(e,t),xf(`preconnect`,e,t)}function wf(e,t,n){_f.L(e,t,n);var r=bf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Ht(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Ht(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Ht(n.imageSizes)+`"]`)):i+=`[href="`+Ht(e)+`"]`;var a=i;switch(t){case`style`:a=Af(e);break;case`script`:a=Pf(e)}mf.has(a)||(e=h({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),mf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(jf(a))||t===`script`&&r.querySelector(Ff(a))||(t=r.createElement(`link`),Pd(t,`link`,e),Ct(t),r.head.appendChild(t)))}}function Tf(e,t){_f.m(e,t);var n=bf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Ht(r)+`"][href="`+Ht(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Pf(e)}if(!mf.has(a)&&(e=h({rel:`modulepreload`,href:e},t),mf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(Ff(a)))return}r=n.createElement(`link`),Pd(r,`link`,e),Ct(r),n.head.appendChild(r)}}}function Ef(e,t,n){_f.S(e,t,n);var r=bf;if(r&&e){var i=St(r).hoistableStyles,a=Af(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(jf(a)))s.loading=5;else{e=h({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=mf.get(a))&&Rf(e,n);var c=o=r.createElement(`link`);Ct(c),Pd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Lf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Df(e,t){_f.X(e,t);var n=bf;if(n&&e){var r=St(n).hoistableScripts,i=Pf(e),a=r.get(i);a||(a=n.querySelector(Ff(i)),a||(e=h({src:e,async:!0},t),(t=mf.get(i))&&zf(e,t),a=n.createElement(`script`),Ct(a),Pd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Of(e,t){_f.M(e,t);var n=bf;if(n&&e){var r=St(n).hoistableScripts,i=Pf(e),a=r.get(i);a||(a=n.querySelector(Ff(i)),a||(e=h({src:e,async:!0,type:`module`},t),(t=mf.get(i))&&zf(e,t),a=n.createElement(`script`),Ct(a),Pd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function kf(e,t,n,r){var i=(i=de.current)?gf(i):null;if(!i)throw Error(o(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=Af(n.href),n=St(i).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Af(n.href);var a=St(i).hoistableStyles,s=a.get(e);if(s||(i=i.ownerDocument||i,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},a.set(e,s),(a=i.querySelector(jf(e)))&&!a._p&&(s.instance=a,s.state.loading=5),mf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},mf.set(e,n),a||Nf(i,e,n,s.state))),t&&r===null)throw Error(o(528,``));return s}if(t&&r!==null)throw Error(o(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Pf(n),n=St(i).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(o(444,e))}}function Af(e){return`href="`+Ht(e)+`"`}function jf(e){return`link[rel="stylesheet"][`+e+`]`}function Mf(e){return h({},e,{"data-precedence":e.precedence,precedence:null})}function Nf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),Pd(t,`link`,n),Ct(t),e.head.appendChild(t))}function Pf(e){return`[src="`+Ht(e)+`"]`}function Ff(e){return`script[async]`+e}function If(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Ht(n.href)+`"]`);if(r)return t.instance=r,Ct(r),r;var i=h({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),Ct(r),Pd(r,`style`,i),Lf(r,n.precedence,e),t.instance=r;case`stylesheet`:i=Af(n.href);var a=e.querySelector(jf(i));if(a)return t.state.loading|=4,t.instance=a,Ct(a),a;r=Mf(n),(i=mf.get(i))&&Rf(r,i),a=(e.ownerDocument||e).createElement(`link`),Ct(a);var s=a;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Pd(a,`link`,r),t.state.loading|=4,Lf(a,n.precedence,e),t.instance=a;case`script`:return a=Pf(n.src),(i=e.querySelector(Ff(a)))?(t.instance=i,Ct(i),i):(r=n,(i=mf.get(a))&&(r=h({},n),zf(r,i)),e=e.ownerDocument||e,i=e.createElement(`script`),Ct(i),Pd(i,`link`,r),e.head.appendChild(i),t.instance=i);case`void`:return null;default:throw Error(o(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Lf(r,n.precedence,e));return t.instance}function Lf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function Uf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Wf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Gf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Af(r.href),a=t.querySelector(jf(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Jf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,Ct(a);return}a=t.ownerDocument||t,r=Mf(r),(i=mf.get(i))&&Rf(r,i),a=a.createElement(`link`),Ct(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Pd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=Jf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Kf=0;function qf(e,t){return e.stylesheets&&e.count===0&&Xf(e,e.stylesheets),0Kf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Jf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Xf(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Yf=null;function Xf(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Yf=new Map,t.forEach(Zf,e),Yf=null,Jf.call(e))}function Zf(e,t){if(!(t.state.loading&4)){var n=Yf.get(e);if(n)var r=n.get(null);else{n=new Map,Yf.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=c()})),u=`15.1.22`,d=e(((e,t)=>{function n(e){if(Array.isArray(e))return e}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),f=e(((e,t)=>{function n(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),p=e(((e,t)=>{function n(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var n=p();function r(e,t){if(e){if(typeof e==`string`)return n(e,t);var r={}.toString.call(e).slice(8,-1);return r===`Object`&&e.constructor&&(r=e.constructor.name),r===`Map`||r===`Set`?Array.from(e):r===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}}t.exports=r,t.exports.__esModule=!0,t.exports.default=t.exports})),h=e(((e,t)=>{function n(){throw TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),g=e(((e,t)=>{var n=d(),r=f(),i=m(),a=h();function o(e,t){return n(e)||r(e,t)||i(e,t)||a()}t.exports=o,t.exports.__esModule=!0,t.exports.default=t.exports})),_=e(((e,t)=>{function n(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),v=e(((e,t)=>{function n(e){"@babel/helpers - typeof";return t.exports=n=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},t.exports.__esModule=!0,t.exports.default=t.exports,n(e)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),y=e(((e,t)=>{var n=v().default;function r(e,t){if(n(e)!=`object`||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,t||`default`);if(n(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}t.exports=r,t.exports.__esModule=!0,t.exports.default=t.exports})),b=e(((e,t)=>{var n=v().default,r=y();function i(e){var t=r(e,`string`);return n(t)==`symbol`?t:t+``}t.exports=i,t.exports.__esModule=!0,t.exports.default=t.exports})),x=e(((e,t)=>{var n=b();function r(e,t){for(var r=0;r{(function(n,r){typeof e==`object`&&t!==void 0?r(e,g(),_(),x()):typeof define==`function`&&define.amd?define([`exports`,`@babel/runtime/helpers/slicedToArray`,`@babel/runtime/helpers/classCallCheck`,`@babel/runtime/helpers/createClass`],r):(n=typeof globalThis<`u`?globalThis:n||self,r(n.automationEvents={},n._slicedToArray,n._classCallCheck,n._createClass))})(e,(function(e,t,n,r){var i=function(e,t,n){return{endTime:t,insertTime:n,type:`exponentialRampToValue`,value:e}},a=function(e,t,n){return{endTime:t,insertTime:n,type:`linearRampToValue`,value:e}},o=function(e,t){return{startTime:t,type:`setValue`,value:e}},s=function(e,t,n){return{duration:n,startTime:t,type:`setValueCurve`,values:e}},c=function(e,t,n){var r=n.startTime,i=n.target,a=n.timeConstant;return i+(t-i)*Math.exp((r-e)/a)},l=function(e){return e.type===`exponentialRampToValue`},u=function(e){return e.type===`linearRampToValue`},d=function(e){return l(e)||u(e)},f=function(e){return e.type===`setValue`},p=function(e){return e.type===`setValueCurve`},m=function(e,t,n,r){var i=e[t];return i===void 0?r:d(i)||f(i)?i.value:p(i)?i.values[i.values.length-1]:c(n,m(e,t-1,i.startTime,r),i)},h=function(e,t,n,r,i){return n===void 0?[r.insertTime,i]:d(n)?[n.endTime,n.value]:f(n)?[n.startTime,n.value]:p(n)?[n.startTime+n.duration,n.values[n.values.length-1]]:[n.startTime,m(e,t-1,n.startTime,i)]},g=function(e){return e.type===`cancelAndHold`},_=function(e){return e.type===`cancelScheduledValues`},v=function(e){return g(e)||_(e)?e.cancelTime:l(e)||u(e)?e.endTime:e.startTime},y=function(e,t,n,r){var i=r.endTime,a=r.value;return n===a?a:0=t:v(n)>=t}),r=this._automationEvents[n];if(n!==-1&&(this._automationEvents=this._automationEvents.slice(0,n)),g(e)){var c=this._automationEvents[this._automationEvents.length-1];if(r!==void 0&&d(r)){if(c!==void 0&&w(c))throw Error(`The internal list is malformed.`);var f=c===void 0?r.insertTime:p(c)?c.startTime+c.duration:v(c),m=c===void 0?this._defaultValue:p(c)?c.values[c.values.length-1]:c.value,h=l(r)?y(t,f,m,r):b(t,f,m,r),x=l(r)?i(h,t,this._currenTime):a(h,t,this._currenTime);this._automationEvents.push(x)}if(c!==void 0&&w(c)&&this._automationEvents.push(o(this.getValue(t),t)),c!==void 0&&p(c)&&c.startTime+c.duration>t){var S=t-c.startTime;this._automationEvents[this._automationEvents.length-1]=s(C(c.values,c.duration,S),c.startTime,S)}}}else{var T=this._automationEvents.findIndex(function(e){return v(e)>t}),E=T===-1?this._automationEvents[this._automationEvents.length-1]:this._automationEvents[T-1];if(E!==void 0&&p(E)&&v(E)+E.duration>t)return!1;var D=l(e)?i(e.value,e.endTime,this._currenTime):u(e)?a(e.value,t,this._currenTime):e;if(T===-1)this._automationEvents.push(D);else{if(p(e)&&t+e.duration>v(this._automationEvents[T]))return!1;this._automationEvents.splice(T,0,D)}}return!0}},{key:`flush`,value:function(e){var t=this._automationEvents.findIndex(function(t){return v(t)>e});if(t>1){var n=this._automationEvents.slice(t-1),r=n[0];w(r)&&n.unshift(o(m(this._automationEvents,t-2,r.startTime,this._defaultValue),r.startTime)),this._automationEvents=n}}},{key:`getValue`,value:function(e){if(this._automationEvents.length===0)return this._defaultValue;var n=this._automationEvents.findIndex(function(t){return v(t)>e}),r=this._automationEvents[n],i=(n===-1?this._automationEvents.length:n)-1,a=this._automationEvents[i];if(a!==void 0&&w(a)&&(r===void 0||!d(r)||r.insertTime>e))return c(e,m(this._automationEvents,i-1,a.startTime,this._defaultValue),a);if(a!==void 0&&f(a)&&(r===void 0||!d(r)))return a.value;if(a!==void 0&&p(a)&&(r===void 0||!d(r)||a.startTime+a.duration>e))return enew DOMException(``,`AbortError`),w=e=>(t,n,[r,i,a],o)=>{e(t[i],[n,r,a],e=>e[0]===n&&e[1]===r,o)},T=e=>(t,n,r)=>{let i=[];for(let e=0;e(t,n)=>{e.set(t,{activeInputs:new Set,passiveInputs:new WeakMap,renderer:n})},D=new WeakSet,O=new WeakMap,ee=new WeakMap,te=new WeakMap,ne=new WeakMap,re=new WeakMap,ie=new WeakMap,ae=new WeakMap,oe=new WeakMap,k=new WeakMap,A={construct(){return A}},se=e=>{try{new new Proxy(e,A)}catch{return!1}return!0},ce=/^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]*);?/,le=(e,t)=>{let n=[],r=e.replace(/^[\s]+/,``),i=r.match(ce);for(;i!==null;){let e=i[1].slice(1,-1),a=i[0].replace(/([\s]+)?;?$/,``).replace(e,new URL(e,t).toString());n.push(a),r=r.slice(i[0].length).replace(/^[\s]+/,``),i=r.match(ce)}return[n.join(`;`),r]},j=e=>{if(e!==void 0&&!Array.isArray(e))throw TypeError(`The parameterDescriptors property of given value for processorCtor is not an array.`)},M=e=>{if(!se(e))throw TypeError(`The given value for processorCtor should be a constructor.`);if(e.prototype===null||typeof e.prototype!=`object`)throw TypeError(`The given value for processorCtor should have a prototype.`)},N=(e,t,n,r,i,a,o,s,c,l,u,d,f)=>{let p=0;return(m,h,g={credentials:`omit`})=>{let _=u.get(m);if(_!==void 0&&_.has(h))return Promise.resolve();let v=l.get(m);if(v!==void 0){let e=v.get(h);if(e!==void 0)return e}let y=a(m),b=y.audioWorklet===void 0?i(h).then(([e,t])=>{let[r,i]=le(e,t);return n(`${r};((a,b)=>{(a[b]=a[b]||[]).push((AudioWorkletProcessor,global,registerProcessor,sampleRate,self,window)=>{${i} +})})(window,'_AWGS')`)}).then(()=>{let e=f._AWGS.pop();if(e===void 0)throw SyntaxError();r(y.currentTime,y.sampleRate,()=>e(class{},void 0,(e,n)=>{if(e.trim()===``)throw t();let r=oe.get(y);if(r!==void 0){if(r.has(e))throw t();M(n),j(n.parameterDescriptors),r.set(e,n)}else M(n),j(n.parameterDescriptors),oe.set(y,new Map([[e,n]]))},y.sampleRate,void 0,void 0))}):Promise.all([i(h),Promise.resolve(e(d,d))]).then(([[e,t],n])=>{let r=p+1;p=r;let[i,a]=le(e,t),l=`${i};((AudioWorkletProcessor,registerProcessor)=>{${a} +})(${n?`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{${n?``:`__c = (a) => a.forEach(e=>this.__b.add(e.buffer));`}process(i,o,p){${n?``:`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${r}',class extends AudioWorkletProcessor{process(){return !1}})`,u=new Blob([l],{type:`application/javascript; charset=utf-8`}),d=URL.createObjectURL(u);return y.audioWorklet.addModule(d,g).then(()=>{if(s(y))return y;let e=o(y);return e.audioWorklet.addModule(d,g).then(()=>e)}).then(e=>{if(c===null)throw SyntaxError();try{new c(e,`__sac${r}`)}catch{throw SyntaxError()}}).finally(()=>URL.revokeObjectURL(d))});return v===void 0?l.set(m,new Map([[h,b]])):v.set(h,b),b.then(()=>{let e=u.get(m);e===void 0?u.set(m,new Set([h])):e.add(h)}).finally(()=>{let e=l.get(m);e!==void 0&&e.delete(h)}),b}},P=(e,t)=>{let n=e.get(t);if(n===void 0)throw Error(`A value with the given key could not be found.`);return n},ue=(e,t)=>{let n=Array.from(e).filter(t);if(n.length>1)throw Error(`More than one element was found.`);if(n.length===0)throw Error(`No element was found.`);let[r]=n;return e.delete(r),r},de=(e,t,n,r)=>{let i=P(e,t),a=ue(i,e=>e[0]===n&&e[1]===r);return i.size===0&&e.delete(t),a},fe=e=>P(ie,e),pe=e=>{if(D.has(e))throw Error(`The AudioNode is already stored.`);D.add(e),fe(e).forEach(e=>e(!0))},me=e=>`port`in e,he=e=>{if(!D.has(e))throw Error(`The AudioNode is not stored.`);D.delete(e),fe(e).forEach(e=>e(!1))},ge=(e,t)=>{!me(e)&&t.every(e=>e.size===0)&&he(e)},_e=(e,t,n,r,i,a,o,s,c,l,u,d,f)=>{let p=new WeakMap;return(m,h,g,_,v)=>{let{activeInputs:y,passiveInputs:b}=a(h),{outputs:x}=a(m),S=s(m),C=a=>{let s=c(h),l=c(m);if(a)e(y,m,de(b,m,g,_),!1),!v&&!d(m)&&n(l,s,g,_),f(h)&&pe(h);else{t(b,_,r(y,m,g,_),!1),!v&&!d(m)&&i(l,s,g,_);let e=o(h);if(e===0)u(h)&&ge(h,y);else{let t=p.get(h);t!==void 0&&clearTimeout(t),p.set(h,setTimeout(()=>{u(h)&&ge(h,y)},e*1e3))}}};return l(x,[h,g,_],e=>e[0]===h&&e[1]===g&&e[2]===_,!0)?(S.add(C),u(m)?e(y,m,[g,_,C],!0):t(b,_,[m,g,C],!0),!0):!1}},ve=e=>(t,n,[r,i,a],o)=>{let s=t.get(r);s===void 0?t.set(r,new Set([[i,n,a]])):e(s,[i,n,a],e=>e[0]===i&&e[1]===n,o)},ye=e=>(t,n)=>{let r=e(t,{channelCount:1,channelCountMode:`explicit`,channelInterpretation:`discrete`,gain:0});n.connect(r).connect(t.destination);let i=()=>{n.removeEventListener(`ended`,i),n.disconnect(r),r.disconnect()};n.addEventListener(`ended`,i)},be=e=>(t,n)=>{e(t).add(n)},xe={channelCount:2,channelCountMode:`max`,channelInterpretation:`speakers`,fftSize:2048,maxDecibels:-30,minDecibels:-100,smoothingTimeConstant:.8},Se=(e,t,n,r,i,a)=>class extends e{constructor(e,n){let o=i(e),s=r(o,{...xe,...n}),c=a(o)?t():null;super(e,!1,s,c),this._nativeAnalyserNode=s}get fftSize(){return this._nativeAnalyserNode.fftSize}set fftSize(e){this._nativeAnalyserNode.fftSize=e}get frequencyBinCount(){return this._nativeAnalyserNode.frequencyBinCount}get maxDecibels(){return this._nativeAnalyserNode.maxDecibels}set maxDecibels(e){let t=this._nativeAnalyserNode.maxDecibels;if(this._nativeAnalyserNode.maxDecibels=e,!(e>this._nativeAnalyserNode.minDecibels))throw this._nativeAnalyserNode.maxDecibels=t,n()}get minDecibels(){return this._nativeAnalyserNode.minDecibels}set minDecibels(e){let t=this._nativeAnalyserNode.minDecibels;if(this._nativeAnalyserNode.minDecibels=e,!(this._nativeAnalyserNode.maxDecibels>e))throw this._nativeAnalyserNode.minDecibels=t,n()}get smoothingTimeConstant(){return this._nativeAnalyserNode.smoothingTimeConstant}set smoothingTimeConstant(e){this._nativeAnalyserNode.smoothingTimeConstant=e}getByteFrequencyData(e){this._nativeAnalyserNode.getByteFrequencyData(e)}getByteTimeDomainData(e){this._nativeAnalyserNode.getByteTimeDomainData(e)}getFloatFrequencyData(e){this._nativeAnalyserNode.getFloatFrequencyData(e)}getFloatTimeDomainData(e){this._nativeAnalyserNode.getFloatTimeDomainData(e)}},Ce=(e,t)=>e.context===t,we=(e,t,n)=>()=>{let r=new WeakMap,i=async(i,a)=>{let o=t(i);return Ce(o,a)||(o=e(a,{channelCount:o.channelCount,channelCountMode:o.channelCountMode,channelInterpretation:o.channelInterpretation,fftSize:o.fftSize,maxDecibels:o.maxDecibels,minDecibels:o.minDecibels,smoothingTimeConstant:o.smoothingTimeConstant})),r.set(a,o),await n(i,a,o),o};return{render(e,t){let n=r.get(t);return n===void 0?i(e,t):Promise.resolve(n)}}},Te=e=>{try{e.copyToChannel(new Float32Array(1),0,-1)}catch{return!1}return!0},Ee=()=>new DOMException(``,`IndexSizeError`),De=e=>{e.getChannelData=(t=>n=>{try{return t.call(e,n)}catch(e){throw e.code===12?Ee():e}})(e.getChannelData)},Oe={numberOfChannels:1},ke=(e,t,n,r,i,a,o,s)=>{let c=null;return class l{constructor(l){if(i===null)throw Error(`Missing the native OfflineAudioContext constructor.`);let{length:u,numberOfChannels:d,sampleRate:f}={...Oe,...l};c===null&&(c=new i(1,1,44100));let p=r!==null&&t(a,a)?new r({length:u,numberOfChannels:d,sampleRate:f}):c.createBuffer(d,u,f);if(p.numberOfChannels===0)throw n();return typeof p.copyFromChannel==`function`?t(Te,()=>Te(p))||s(p):(o(p),De(p)),e.add(p),p}static[Symbol.hasInstance](t){return typeof t==`object`&&!!t&&Object.getPrototypeOf(t)===l.prototype||e.has(t)}}},Ae=-34028234663852886e22,je=34028234663852886e22,Me=e=>D.has(e),Ne={buffer:null,channelCount:2,channelCountMode:`max`,channelInterpretation:`speakers`,loop:!1,loopEnd:0,loopStart:0,playbackRate:1},Pe=(e,t,n,r,i,a,o,s)=>class extends e{constructor(e,r){let s=a(e),c={...Ne,...r},l=i(s,c),u=o(s),d=u?t():null;super(e,!1,l,d),this._audioBufferSourceNodeRenderer=d,this._isBufferNullified=!1,this._isBufferSet=c.buffer!==null,this._nativeAudioBufferSourceNode=l,this._onended=null,this._playbackRate=n(this,u,l.playbackRate,je,Ae)}get buffer(){return this._isBufferNullified?null:this._nativeAudioBufferSourceNode.buffer}set buffer(e){if(this._nativeAudioBufferSourceNode.buffer=e,e!==null){if(this._isBufferSet)throw r();this._isBufferSet=!0}}get loop(){return this._nativeAudioBufferSourceNode.loop}set loop(e){this._nativeAudioBufferSourceNode.loop=e}get loopEnd(){return this._nativeAudioBufferSourceNode.loopEnd}set loopEnd(e){this._nativeAudioBufferSourceNode.loopEnd=e}get loopStart(){return this._nativeAudioBufferSourceNode.loopStart}set loopStart(e){this._nativeAudioBufferSourceNode.loopStart=e}get onended(){return this._onended}set onended(e){let t=typeof e==`function`?s(this,e):null;this._nativeAudioBufferSourceNode.onended=t;let n=this._nativeAudioBufferSourceNode.onended;this._onended=n!==null&&n===t?e:n}get playbackRate(){return this._playbackRate}start(e=0,t=0,n){if(this._nativeAudioBufferSourceNode.start(e,t,n),this._audioBufferSourceNodeRenderer!==null&&(this._audioBufferSourceNodeRenderer.start=n===void 0?[e,t]:[e,t,n]),this.context.state!==`closed`){pe(this);let e=()=>{this._nativeAudioBufferSourceNode.removeEventListener(`ended`,e),Me(this)&&he(this)};this._nativeAudioBufferSourceNode.addEventListener(`ended`,e)}}stop(e=0){this._nativeAudioBufferSourceNode.stop(e),this._audioBufferSourceNodeRenderer!==null&&(this._audioBufferSourceNodeRenderer.stop=e)}},Fe=(e,t,n,r,i)=>()=>{let a=new WeakMap,o=null,s=null,c=async(c,l)=>{let u=n(c),d=Ce(u,l);return d||(u=t(l,{buffer:u.buffer,channelCount:u.channelCount,channelCountMode:u.channelCountMode,channelInterpretation:u.channelInterpretation,loop:u.loop,loopEnd:u.loopEnd,loopStart:u.loopStart,playbackRate:u.playbackRate.value}),o!==null&&u.start(...o),s!==null&&u.stop(s)),a.set(l,u),d?await e(l,c.playbackRate,u.playbackRate):await r(l,c.playbackRate,u.playbackRate),await i(c,l,u),u};return{set start(e){o=e},set stop(e){s=e},render(e,t){let n=a.get(t);return n===void 0?c(e,t):Promise.resolve(n)}}},Ie=e=>`playbackRate`in e,Le=e=>`frequency`in e&&`gain`in e,Re=e=>`offset`in e,ze=e=>!(`frequency`in e)&&`gain`in e,Be=e=>`detune`in e&&`frequency`in e&&!(`gain`in e),Ve=e=>`pan`in e,He=e=>P(O,e),Ue=e=>P(te,e),We=(e,t)=>{let{activeInputs:n}=He(e);n.forEach(n=>n.forEach(([n])=>{t.includes(e)||We(n,[...t,e])}));let r=Ie(e)?[e.playbackRate]:me(e)?Array.from(e.parameters.values()):Le(e)?[e.Q,e.detune,e.frequency,e.gain]:Re(e)?[e.offset]:ze(e)?[e.gain]:Be(e)?[e.detune,e.frequency]:Ve(e)?[e.pan]:[];for(let e of r){let n=Ue(e);n!==void 0&&n.activeInputs.forEach(([e])=>We(e,t))}Me(e)&&he(e)},Ge=e=>{We(e.destination,[])},Ke=e=>e===void 0||typeof e==`number`||typeof e==`string`&&(e===`balanced`||e===`interactive`||e===`playback`),qe=(e,t,n,r,i,a,o,s,c)=>class extends e{constructor(e={}){if(c===null)throw Error(`Missing the native AudioContext constructor.`);let t;try{t=new c(e)}catch(e){throw e.code===12&&e.message===`sampleRate is not in range`?n():e}if(t===null)throw r();if(!Ke(e.latencyHint))throw TypeError(`The provided value '${e.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);if(e.sampleRate!==void 0&&t.sampleRate!==e.sampleRate)throw n();super(t,2);let{latencyHint:i}=e,{sampleRate:a}=t;if(this._baseLatency=typeof t.baseLatency==`number`?t.baseLatency:i===`balanced`?512/a:i===`interactive`||i===void 0?256/a:i===`playback`?1024/a:Math.max(2,Math.min(128,Math.round(i*a/128)))*128/a,this._nativeAudioContext=t,c.name===`webkitAudioContext`?(this._nativeGainNode=t.createGain(),this._nativeOscillatorNode=t.createOscillator(),this._nativeGainNode.gain.value=1e-37,this._nativeOscillatorNode.connect(this._nativeGainNode).connect(t.destination),this._nativeOscillatorNode.start()):(this._nativeGainNode=null,this._nativeOscillatorNode=null),this._state=null,t.state===`running`){this._state=`suspended`;let e=()=>{this._state===`suspended`&&(this._state=null),t.removeEventListener(`statechange`,e)};t.addEventListener(`statechange`,e)}}get baseLatency(){return this._baseLatency}get state(){return this._state===null?this._nativeAudioContext.state:this._state}close(){return this.state===`closed`?this._nativeAudioContext.close().then(()=>{throw t()}):(this._state===`suspended`&&(this._state=null),this._nativeAudioContext.close().then(()=>{this._nativeGainNode!==null&&this._nativeOscillatorNode!==null&&(this._nativeOscillatorNode.stop(),this._nativeGainNode.disconnect(),this._nativeOscillatorNode.disconnect()),Ge(this)}))}createMediaElementSource(e){return new i(this,{mediaElement:e})}createMediaStreamDestination(){return new a(this)}createMediaStreamSource(e){return new o(this,{mediaStream:e})}createMediaStreamTrackSource(e){return new s(this,{mediaStreamTrack:e})}resume(){return this._state===`suspended`?new Promise((e,t)=>{let n=()=>{this._nativeAudioContext.removeEventListener(`statechange`,n),this._nativeAudioContext.state===`running`?e():this.resume().then(e,t)};this._nativeAudioContext.addEventListener(`statechange`,n)}):this._nativeAudioContext.resume().catch(e=>{throw e===void 0||e.code===15?t():e})}suspend(){return this._nativeAudioContext.suspend().catch(e=>{throw e===void 0?t():e})}},Je=(e,t,n,r,i,a,o,s)=>class extends e{constructor(e,n){let r=a(e),c=o(r),l=i(r,n,c),u=c?t(s):null;super(e,!1,l,u),this._isNodeOfNativeOfflineAudioContext=c,this._nativeAudioDestinationNode=l}get channelCount(){return this._nativeAudioDestinationNode.channelCount}set channelCount(e){if(this._isNodeOfNativeOfflineAudioContext)throw r();if(e>this._nativeAudioDestinationNode.maxChannelCount)throw n();this._nativeAudioDestinationNode.channelCount=e}get channelCountMode(){return this._nativeAudioDestinationNode.channelCountMode}set channelCountMode(e){if(this._isNodeOfNativeOfflineAudioContext)throw r();this._nativeAudioDestinationNode.channelCountMode=e}get maxChannelCount(){return this._nativeAudioDestinationNode.maxChannelCount}},Ye=e=>{let t=new WeakMap,n=async(n,r)=>{let i=r.destination;return t.set(r,i),await e(n,r,i),i};return{render(e,r){let i=t.get(r);return i===void 0?n(e,r):Promise.resolve(i)}}},Xe=(e,t,n,r,i,a,o,s)=>(c,l)=>{let u=l.listener,{forwardX:d,forwardY:f,forwardZ:p,positionX:m,positionY:h,positionZ:g,upX:_,upY:v,upZ:y}=u.forwardX===void 0?(()=>{let d=new Float32Array(1),f=t(l,{channelCount:1,channelCountMode:`explicit`,channelInterpretation:`speakers`,numberOfInputs:9}),p=o(l),m=!1,h=[0,0,-1,0,1,0],g=[0,0,0],_=()=>{if(m)return;m=!0;let e=r(l,256,9,0);e.onaudioprocess=({inputBuffer:e})=>{let t=[a(e,d,0),a(e,d,1),a(e,d,2),a(e,d,3),a(e,d,4),a(e,d,5)];t.some((e,t)=>e!==h[t])&&(u.setOrientation(...t),h=t);let n=[a(e,d,6),a(e,d,7),a(e,d,8)];n.some((e,t)=>e!==g[t])&&(u.setPosition(...n),g=n)},f.connect(e)},v=e=>t=>{t!==h[e]&&(h[e]=t,u.setOrientation(...h))},y=e=>t=>{t!==g[e]&&(g[e]=t,u.setPosition(...g))},b=(t,r,a)=>{let o=n(l,{channelCount:1,channelCountMode:`explicit`,channelInterpretation:`discrete`,offset:r});o.connect(f,0,t),o.start(),Object.defineProperty(o.offset,"defaultValue",{get(){return r}});let u=e({context:c},p,o.offset,je,Ae);return s(u,`value`,e=>()=>e.call(u),e=>t=>{try{e.call(u,t)}catch(e){if(e.code!==9)throw e}_(),p&&a(t)}),u.cancelAndHoldAtTime=(e=>p?()=>{throw i()}:(...t)=>{let n=e.apply(u,t);return _(),n})(u.cancelAndHoldAtTime),u.cancelScheduledValues=(e=>p?()=>{throw i()}:(...t)=>{let n=e.apply(u,t);return _(),n})(u.cancelScheduledValues),u.exponentialRampToValueAtTime=(e=>p?()=>{throw i()}:(...t)=>{let n=e.apply(u,t);return _(),n})(u.exponentialRampToValueAtTime),u.linearRampToValueAtTime=(e=>p?()=>{throw i()}:(...t)=>{let n=e.apply(u,t);return _(),n})(u.linearRampToValueAtTime),u.setTargetAtTime=(e=>p?()=>{throw i()}:(...t)=>{let n=e.apply(u,t);return _(),n})(u.setTargetAtTime),u.setValueAtTime=(e=>p?()=>{throw i()}:(...t)=>{let n=e.apply(u,t);return _(),n})(u.setValueAtTime),u.setValueCurveAtTime=(e=>p?()=>{throw i()}:(...t)=>{let n=e.apply(u,t);return _(),n})(u.setValueCurveAtTime),u};return{forwardX:b(0,0,v(0)),forwardY:b(1,0,v(1)),forwardZ:b(2,-1,v(2)),positionX:b(6,0,y(0)),positionY:b(7,0,y(1)),positionZ:b(8,0,y(2)),upX:b(3,0,v(3)),upY:b(4,1,v(4)),upZ:b(5,0,v(5))}})():u;return{get forwardX(){return d},get forwardY(){return f},get forwardZ(){return p},get positionX(){return m},get positionY(){return h},get positionZ(){return g},get upX(){return _},get upY(){return v},get upZ(){return y}}},Ze=e=>`context`in e,Qe=e=>Ze(e[0]),$e=(e,t,n,r)=>{for(let t of e)if(n(t)){if(r)return!1;throw Error(`The set contains at least one similar element.`)}return e.add(t),!0},et=(e,t,[n,r],i)=>{$e(e,[t,n,r],e=>e[0]===t&&e[1]===n,i)},tt=(e,[t,n,r],i)=>{let a=e.get(t);a===void 0?e.set(t,new Set([[n,r]])):$e(a,[n,r],e=>e[0]===n,i)},nt=e=>`inputs`in e,rt=(e,t,n,r)=>{if(nt(t)){let i=t.inputs[r];return e.connect(i,n,0),[i,n,0]}return e.connect(t,n,r),[t,n,r]},it=(e,t,n)=>{for(let r of e)if(r[0]===t&&r[1]===n)return e.delete(r),r;return null},at=(e,t,n)=>ue(e,e=>e[0]===t&&e[1]===n),ot=(e,t)=>{if(!fe(e).delete(t))throw Error(`Missing the expected event listener.`)},st=(e,t,n)=>{let r=P(e,t),i=ue(r,e=>e[0]===n);return r.size===0&&e.delete(t),i},ct=(e,t,n,r)=>{nt(t)?e.disconnect(t.inputs[r],n,0):e.disconnect(t,n,r)},lt=e=>P(ee,e),ut=e=>P(ne,e),dt=e=>ae.has(e),ft=e=>!D.has(e),pt=(e,t)=>new Promise(n=>{if(t!==null)n(!0);else{let t=e.createScriptProcessor(256,1,1),r=e.createGain(),i=e.createBuffer(1,2,44100),a=i.getChannelData(0);a[0]=1,a[1]=1;let o=e.createBufferSource();o.buffer=i,o.loop=!0,o.connect(t).connect(e.destination),o.connect(r),o.disconnect(r),t.onaudioprocess=r=>{let i=r.inputBuffer.getChannelData(0);Array.prototype.some.call(i,e=>e===1)?n(!0):n(!1),o.stop(),t.onaudioprocess=null,o.disconnect(t),t.disconnect(e.destination)},o.start()}}),mt=(e,t)=>{let n=new Map;for(let t of e)for(let e of t){let t=n.get(e);n.set(e,t===void 0?1:t+1)}n.forEach((e,n)=>t(n,e))},ht=e=>`context`in e,gt=e=>{let t=new Map;e.connect=(e=>(n,r=0,i=0)=>{let a=ht(n)?e(n,r,i):e(n,r),o=t.get(n);return o===void 0?t.set(n,[{input:i,output:r}]):o.every(e=>e.input!==i||e.output!==r)&&o.push({input:i,output:r}),a})(e.connect.bind(e)),e.disconnect=(n=>(r,i,a)=>{if(n.apply(e),r===void 0)t.clear();else if(typeof r==`number`)for(let[e,n]of t){let i=n.filter(e=>e.output!==r);i.length===0?t.delete(e):t.set(e,i)}else if(t.has(r))if(i===void 0)t.delete(r);else{let e=t.get(r);if(e!==void 0){let n=e.filter(e=>e.output!==i&&(e.input!==a||a===void 0));n.length===0?t.delete(r):t.set(r,n)}}for(let[n,r]of t)r.forEach(t=>{ht(n)?e.connect(n,t.output,t.input):e.connect(n,t.output)})})(e.disconnect)},_t=(e,t,n,r)=>{let{activeInputs:i,passiveInputs:a}=Ue(t),{outputs:o}=He(e),s=fe(e),c=o=>{let s=lt(e),c=ut(t);o?(et(i,e,st(a,e,n),!1),!r&&!dt(e)&&s.connect(c,n)):(tt(a,at(i,e,n),!1),!r&&!dt(e)&&s.disconnect(c,n))};return $e(o,[t,n],e=>e[0]===t&&e[1]===n,!0)?(s.add(c),Me(e)?et(i,e,[n,c],!0):tt(a,[e,n,c],!0),!0):!1},vt=(e,t,n,r)=>{let{activeInputs:i,passiveInputs:a}=He(t),o=it(i[r],e,n);return o===null?[de(a,e,n,r)[2],!1]:[o[2],!0]},yt=(e,t,n)=>{let{activeInputs:r,passiveInputs:i}=Ue(t),a=it(r,e,n);return a===null?[st(i,e,n)[1],!1]:[a[2],!0]},bt=(e,t,n,r,i)=>{let[a,o]=vt(e,n,r,i);if(a!==null&&(ot(e,a),o&&!t&&!dt(e)&&ct(lt(e),lt(n),r,i)),Me(n)){let{activeInputs:e}=He(n);ge(n,e)}},xt=(e,t,n,r)=>{let[i,a]=yt(e,n,r);i!==null&&(ot(e,i),a&&!t&&!dt(e)&<(e).disconnect(ut(n),r))},St=(e,t)=>{let n=He(e),r=[];for(let i of n.outputs)Qe(i)?bt(e,t,...i):xt(e,t,...i),r.push(i[0]);return n.outputs.clear(),r},Ct=(e,t,n)=>{let r=He(e),i=[];for(let a of r.outputs)a[1]===n&&(Qe(a)?bt(e,t,...a):xt(e,t,...a),i.push(a[0]),r.outputs.delete(a));return i},wt=(e,t,n,r,i)=>{let a=He(e);return Array.from(a.outputs).filter(e=>e[0]===n&&(r===void 0||e[1]===r)&&(i===void 0||e[2]===i)).map(n=>(Qe(n)?bt(e,t,...n):xt(e,t,...n),a.outputs.delete(n),n[0]))},Tt=(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)=>class extends l{constructor(t,r,i,a){super(i),this._context=t,this._nativeAudioNode=i;let o=u(t);d(o)&&!0!==n(pt,()=>pt(o,h))&>(i),ee.set(this,i),ie.set(this,new Set),t.state!==`closed`&&r&&pe(this),e(this,a,i)}get channelCount(){return this._nativeAudioNode.channelCount}set channelCount(e){this._nativeAudioNode.channelCount=e}get channelCountMode(){return this._nativeAudioNode.channelCountMode}set channelCountMode(e){this._nativeAudioNode.channelCountMode=e}get channelInterpretation(){return this._nativeAudioNode.channelInterpretation}set channelInterpretation(e){this._nativeAudioNode.channelInterpretation=e}get context(){return this._context}get numberOfInputs(){return this._nativeAudioNode.numberOfInputs}get numberOfOutputs(){return this._nativeAudioNode.numberOfOutputs}connect(e,n=0,s=0){if(n<0||n>=this._nativeAudioNode.numberOfOutputs)throw i();let l=m(u(this._context));if(f(e)||p(e))throw a();if(Ze(e)){let i=lt(e);try{let t=rt(this._nativeAudioNode,i,n,s),r=ft(this);(l||r)&&this._nativeAudioNode.disconnect(...t),this.context.state!==`closed`&&!r&&ft(e)&&pe(e)}catch(e){throw e.code===12?a():e}return t(this,e,n,s,l)&&mt(c([this],e),r(l)),e}let d=ut(e);if(d.name===`playbackRate`&&d.maxValue===1024)throw o();try{this._nativeAudioNode.connect(d,n),(l||ft(this))&&this._nativeAudioNode.disconnect(d,n)}catch(e){throw e.code===12?a():e}_t(this,e,n,l)&&mt(c([this],e),r(l))}disconnect(e,t,n){let r,o=m(u(this._context));if(e===void 0)r=St(this,o);else if(typeof e==`number`){if(e<0||e>=this.numberOfOutputs)throw i();r=Ct(this,o,e)}else{if(t!==void 0&&(t<0||t>=this.numberOfOutputs)||Ze(e)&&n!==void 0&&(n<0||n>=e.numberOfInputs))throw i();if(r=wt(this,o,e,t,n),r.length===0)throw a()}for(let e of r)mt(c([this],e),s)}},Et=(e,t,n,r,i,a,o,s,c,l,u,d,f)=>(p,m,h,g=null,_=null)=>{let v=h.value,y=new S.AutomationEventList(v),b=m?r(y):null,x={get defaultValue(){return v},get maxValue(){return g===null?h.maxValue:g},get minValue(){return _===null?h.minValue:_},get value(){return h.value},set value(e){h.value=e,x.setValueAtTime(e,p.context.currentTime)},cancelAndHoldAtTime(e){if(typeof h.cancelAndHoldAtTime==`function`)b===null&&y.flush(p.context.currentTime),y.add(i(e)),h.cancelAndHoldAtTime(e);else{let t=Array.from(y).pop();b===null&&y.flush(p.context.currentTime),y.add(i(e));let n=Array.from(y).pop();h.cancelScheduledValues(e),t!==n&&n!==void 0&&(n.type===`exponentialRampToValue`?h.exponentialRampToValueAtTime(n.value,n.endTime):n.type===`linearRampToValue`?h.linearRampToValueAtTime(n.value,n.endTime):n.type===`setValue`?h.setValueAtTime(n.value,n.startTime):n.type===`setValueCurve`&&h.setValueCurveAtTime(n.values,n.startTime,n.duration))}return x},cancelScheduledValues(e){return b===null&&y.flush(p.context.currentTime),y.add(a(e)),h.cancelScheduledValues(e),x},exponentialRampToValueAtTime(e,t){if(e===0||!Number.isFinite(t)||t<0)throw RangeError();let n=p.context.currentTime;return b===null&&y.flush(n),Array.from(y).length===0&&(y.add(l(v,n)),h.setValueAtTime(v,n)),y.add(o(e,t)),h.exponentialRampToValueAtTime(e,t),x},linearRampToValueAtTime(e,t){let n=p.context.currentTime;return b===null&&y.flush(n),Array.from(y).length===0&&(y.add(l(v,n)),h.setValueAtTime(v,n)),y.add(s(e,t)),h.linearRampToValueAtTime(e,t),x},setTargetAtTime(e,t,n){return b===null&&y.flush(p.context.currentTime),y.add(c(e,t,n)),h.setTargetAtTime(e,t,n),x},setValueAtTime(e,t){return b===null&&y.flush(p.context.currentTime),y.add(l(e,t)),h.setValueAtTime(e,t),x},setValueCurveAtTime(e,t,n){let r=e instanceof Float32Array?e:new Float32Array(e);if(d!==null&&d.name===`webkitAudioContext`){let e=t+n,i=p.context.sampleRate,a=Math.ceil(t*i),o=Math.floor(e*i),s=o-a,c=new Float32Array(s);for(let e=0;e({replay(t){for(let n of e)if(n.type===`exponentialRampToValue`){let{endTime:e,value:r}=n;t.exponentialRampToValueAtTime(r,e)}else if(n.type===`linearRampToValue`){let{endTime:e,value:r}=n;t.linearRampToValueAtTime(r,e)}else if(n.type===`setTarget`){let{startTime:e,target:r,timeConstant:i}=n;t.setTargetAtTime(r,e,i)}else if(n.type===`setValue`){let{startTime:e,value:r}=n;t.setValueAtTime(r,e)}else if(n.type===`setValueCurve`){let{duration:e,startTime:r,values:i}=n;t.setValueCurveAtTime(i,r,e)}else throw Error(`Can't apply an unknown automation.`)}}),Ot=class{constructor(e){this._map=new Map(e)}get size(){return this._map.size}entries(){return this._map.entries()}forEach(e,t=null){return this._map.forEach((n,r)=>e.call(t,n,r,this))}get(e){return this._map.get(e)}has(e){return this._map.has(e)}keys(){return this._map.keys()}values(){return this._map.values()}},kt={channelCount:2,channelCountMode:`explicit`,channelInterpretation:`speakers`,numberOfInputs:1,numberOfOutputs:1,parameterData:{},processorOptions:{}},At=(e,t,n,r,i,a,o,s,c,l,u,d,f,p)=>class extends t{constructor(t,p,m){let h=s(t),g=c(h),_=u({...kt,...m});f(_);let v=oe.get(h)?.get(p),y=i(g||h.state!==`closed`?h:o(h)??h,g?null:t.baseLatency,l,p,v,_),b=g?r(p,_,v):null;super(t,!0,y,b);let x=[];y.parameters.forEach((e,t)=>{let r=n(this,g,e);x.push([t,r])}),this._nativeAudioWorkletNode=y,this._onprocessorerror=null,this._parameters=new Ot(x),g&&e(h,this);let{activeInputs:S}=a(this);d(y,S)}get onprocessorerror(){return this._onprocessorerror}set onprocessorerror(e){let t=typeof e==`function`?p(this,e):null;this._nativeAudioWorkletNode.onprocessorerror=t;let n=this._nativeAudioWorkletNode.onprocessorerror;this._onprocessorerror=n!==null&&n===t?e:n}get parameters(){return this._parameters===null?this._nativeAudioWorkletNode.parameters:this._parameters}get port(){return this._nativeAudioWorkletNode.port}};function jt(e,t,n,r,i){if(typeof e.copyFromChannel==`function`)t[n].byteLength===0&&(t[n]=new Float32Array(128)),e.copyFromChannel(t[n],r,i);else{let a=e.getChannelData(r);if(t[n].byteLength===0)t[n]=a.slice(i,i+128);else{let e=new Float32Array(a.buffer,i*Float32Array.BYTES_PER_ELEMENT,128);t[n].set(e)}}}var Mt=(e,t,n,r,i)=>{typeof e.copyToChannel==`function`?t[n].byteLength!==0&&e.copyToChannel(t[n],r,i):t[n].byteLength!==0&&e.getChannelData(r).set(t[n],i)},Nt=(e,t)=>{let n=[];for(let r=0;rP(P(k,e),lt(t)),Ft=async(e,t,n,r,i,a,o)=>{let s=t===null?Math.ceil(e.context.length/128)*128:t.length,c=r.channelCount*r.numberOfInputs,l=i.reduce((e,t)=>e+t,0),u=l===0?null:n.createBuffer(l,s,n.sampleRate);if(a===void 0)throw Error(`Missing the processor constructor.`);let d=He(e),f=await Pt(n,e),p=Nt(r.numberOfInputs,r.channelCount),m=Nt(r.numberOfOutputs,i),h=Array.from(e.parameters.keys()).reduce((e,t)=>({...e,[t]:new Float32Array(128)}),{});for(let l=0;l0&&t!==null)for(let e=0;e{jt(t,h,e,c+n,l)});for(let e=0;ed.activeInputs[t].size===0?[]:e),t=o(l/n.sampleRate,n.sampleRate,()=>f.process(e,m,h));if(u!==null)for(let e=0,t=0;e(g,_,v)=>{let y=new WeakMap,b=null,x=async(s,x)=>{let S=u(s),C=null,w=Ce(S,x),T=Array.isArray(_.outputChannelCount)?_.outputChannelCount:Array.from(_.outputChannelCount);if(d===null){let e=T.reduce((e,t)=>e+t,0),n=i(x,{channelCount:Math.max(1,e),channelCountMode:`explicit`,channelInterpretation:`discrete`,numberOfOutputs:Math.max(1,e)}),a=[];for(let e=0;e{let c=new f(n,Math.ceil(s.context.length/128)*128,x.sampleRate),l=[],u=[];for(let e=0;e<_.numberOfInputs;e+=1)l.push(o(c,{channelCount:_.channelCount,channelCountMode:_.channelCountMode,channelInterpretation:_.channelInterpretation,gain:1})),u.push(i(c,{channelCount:_.channelCount,channelCountMode:`explicit`,channelInterpretation:`discrete`,numberOfOutputs:_.channelCount}));let d=await Promise.all(Array.from(s.parameters.values()).map(async e=>{let t=a(c,{channelCount:1,channelCountMode:`explicit`,channelInterpretation:`discrete`,offset:e.value});return await p(c,e,t.offset),t})),g=r(c,{channelCount:1,channelCountMode:`explicit`,channelInterpretation:`speakers`,numberOfInputs:Math.max(1,e+t)});for(let e=0;e<_.numberOfInputs;e+=1){l[e].connect(u[e]);for(let t=0;t<_.channelCount;t+=1)u[e].connect(g,t,e*_.channelCount+t)}for(let[t,n]of d.entries())n.connect(g,0,e+t),n.start(0);return g.connect(c.destination),await Promise.all(l.map(e=>m(s,c,e))),h(c)})(),x,_,T,v,l)}let e=await b,t=n(x,{buffer:null,channelCount:2,channelCountMode:`max`,channelInterpretation:`speakers`,loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),[c,u,d]=C;e!==null&&(t.buffer=e,t.start(0)),t.connect(c);for(let e=0,t=0;eclass extends m{constructor(t,n){super(t,n),this._nativeContext=t,this._audioWorklet=e===void 0?void 0:{addModule:(t,n)=>e(this,t,n)}}get audioWorklet(){return this._audioWorklet}createAnalyser(){return new t(this)}createBiquadFilter(){return new i(this)}createBuffer(e,t,r){return new n({length:t,numberOfChannels:e,sampleRate:r})}createBufferSource(){return new r(this)}createChannelMerger(e=6){return new a(this,{numberOfInputs:e})}createChannelSplitter(e=6){return new o(this,{numberOfOutputs:e})}createConstantSource(){return new s(this)}createConvolver(){return new c(this)}createDelay(e=1){return new u(this,{maxDelayTime:e})}createDynamicsCompressor(){return new d(this)}createGain(){return new f(this)}createIIRFilter(e,t){return new p(this,{feedback:t,feedforward:e})}createOscillator(){return new h(this)}createPanner(){return new g(this)}createPeriodicWave(e,t,n={disableNormalization:!1}){return new _(this,{...n,imag:t,real:e})}createStereoPanner(){return new v(this)}createWaveShaper(){return new y(this)}decodeAudioData(e,t,n){return l(this._nativeContext,e).then(e=>(typeof t==`function`&&t(e),e),e=>{throw typeof n==`function`&&n(e),e})}},Rt={Q:1,channelCount:2,channelCountMode:`max`,channelInterpretation:`speakers`,detune:0,frequency:350,gain:0,type:`lowpass`},zt=(e,t,n,r,i,a,o,s)=>class extends e{constructor(e,r){let c=a(e),l=i(c,{...Rt,...r}),u=o(c),d=u?n():null;super(e,!1,l,d),this._Q=t(this,u,l.Q,je,Ae),this._detune=t(this,u,l.detune,1200*Math.log2(je),-1200*Math.log2(je)),this._frequency=t(this,u,l.frequency,e.sampleRate/2,0),this._gain=t(this,u,l.gain,40*Math.log10(je),Ae),this._nativeBiquadFilterNode=l,s(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(e){this._nativeBiquadFilterNode.type=e}getFrequencyResponse(e,t,n){try{this._nativeBiquadFilterNode.getFrequencyResponse(e,t,n)}catch(e){throw e.code===11?r():e}if(e.length!==t.length||t.length!==n.length)throw r()}},Bt=(e,t,n,r,i)=>()=>{let a=new WeakMap,o=async(o,s)=>{let c=n(o),l=Ce(c,s);return l||(c=t(s,{Q:c.Q.value,channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,detune:c.detune.value,frequency:c.frequency.value,gain:c.gain.value,type:c.type})),a.set(s,c),l?(await e(s,o.Q,c.Q),await e(s,o.detune,c.detune),await e(s,o.frequency,c.frequency),await e(s,o.gain,c.gain)):(await r(s,o.Q,c.Q),await r(s,o.detune,c.detune),await r(s,o.frequency,c.frequency),await r(s,o.gain,c.gain)),await i(o,s,c),c};return{render(e,t){let n=a.get(t);return n===void 0?o(e,t):Promise.resolve(n)}}},Vt=(e,t)=>(n,r)=>{let i=t.get(n);if(i!==void 0)return i;let a=e.get(n);if(a!==void 0)return a;try{let i=r();return i instanceof Promise?(e.set(n,i),i.catch(()=>!1).then(r=>(e.delete(n),t.set(n,r),r))):(t.set(n,i),i)}catch{return t.set(n,!1),!1}},Ht={channelCount:1,channelCountMode:`explicit`,channelInterpretation:`speakers`,numberOfInputs:6},Ut=(e,t,n,r,i)=>class extends e{constructor(e,a){let o=r(e),s=n(o,{...Ht,...a}),c=i(o)?t():null;super(e,!1,s,c)}},Wt=(e,t,n)=>()=>{let r=new WeakMap,i=async(i,a)=>{let o=t(i);return Ce(o,a)||(o=e(a,{channelCount:o.channelCount,channelCountMode:o.channelCountMode,channelInterpretation:o.channelInterpretation,numberOfInputs:o.numberOfInputs})),r.set(a,o),await n(i,a,o),o};return{render(e,t){let n=r.get(t);return n===void 0?i(e,t):Promise.resolve(n)}}},Gt={channelCount:6,channelCountMode:`explicit`,channelInterpretation:`discrete`,numberOfOutputs:6},Kt=(e,t,n,r,i,a)=>class extends e{constructor(e,o){let s=r(e),c=n(s,a({...Gt,...o})),l=i(s)?t():null;super(e,!1,c,l)}},qt=(e,t,n)=>()=>{let r=new WeakMap,i=async(i,a)=>{let o=t(i);return Ce(o,a)||(o=e(a,{channelCount:o.channelCount,channelCountMode:o.channelCountMode,channelInterpretation:o.channelInterpretation,numberOfOutputs:o.numberOfOutputs})),r.set(a,o),await n(i,a,o),o};return{render(e,t){let n=r.get(t);return n===void 0?i(e,t):Promise.resolve(n)}}},Jt=e=>(t,n,r)=>e(n,t,r),Yt=e=>(t,n,r=0,i=0)=>{let a=t[r];if(a===void 0)throw e();return ht(n)?a.connect(n,0,i):a.connect(n,0)},Xt=e=>(t,n)=>{let r=e(t,{buffer:null,channelCount:2,channelCountMode:`max`,channelInterpretation:`speakers`,loop:!1,loopEnd:0,loopStart:0,playbackRate:1});return r.buffer=t.createBuffer(1,2,44100),r.loop=!0,r.connect(n),r.start(),()=>{r.stop(),r.disconnect(n)}},Zt={channelCount:2,channelCountMode:`max`,channelInterpretation:`speakers`,offset:1},Qt=(e,t,n,r,i,a,o)=>class extends e{constructor(e,o){let s=i(e),c=r(s,{...Zt,...o}),l=a(s),u=l?n():null;super(e,!1,c,u),this._constantSourceNodeRenderer=u,this._nativeConstantSourceNode=c,this._offset=t(this,l,c.offset,je,Ae),this._onended=null}get offset(){return this._offset}get onended(){return this._onended}set onended(e){let t=typeof e==`function`?o(this,e):null;this._nativeConstantSourceNode.onended=t;let n=this._nativeConstantSourceNode.onended;this._onended=n!==null&&n===t?e:n}start(e=0){if(this._nativeConstantSourceNode.start(e),this._constantSourceNodeRenderer!==null&&(this._constantSourceNodeRenderer.start=e),this.context.state!==`closed`){pe(this);let e=()=>{this._nativeConstantSourceNode.removeEventListener(`ended`,e),Me(this)&&he(this)};this._nativeConstantSourceNode.addEventListener(`ended`,e)}}stop(e=0){this._nativeConstantSourceNode.stop(e),this._constantSourceNodeRenderer!==null&&(this._constantSourceNodeRenderer.stop=e)}},$t=(e,t,n,r,i)=>()=>{let a=new WeakMap,o=null,s=null,c=async(c,l)=>{let u=n(c),d=Ce(u,l);return d||(u=t(l,{channelCount:u.channelCount,channelCountMode:u.channelCountMode,channelInterpretation:u.channelInterpretation,offset:u.offset.value}),o!==null&&u.start(o),s!==null&&u.stop(s)),a.set(l,u),d?await e(l,c.offset,u.offset):await r(l,c.offset,u.offset),await i(c,l,u),u};return{set start(e){o=e},set stop(e){s=e},render(e,t){let n=a.get(t);return n===void 0?c(e,t):Promise.resolve(n)}}},en=e=>t=>(e[0]=t,e[0]),tn={buffer:null,channelCount:2,channelCountMode:`clamped-max`,channelInterpretation:`speakers`,disableNormalization:!1},nn=(e,t,n,r,i,a)=>class extends e{constructor(e,o){let s=r(e),c={...tn,...o},l=n(s,c),u=i(s)?t():null;super(e,!1,l,u),this._isBufferNullified=!1,this._nativeConvolverNode=l,c.buffer!==null&&a(this,c.buffer.duration)}get buffer(){return this._isBufferNullified?null:this._nativeConvolverNode.buffer}set buffer(e){if(this._nativeConvolverNode.buffer=e,e===null&&this._nativeConvolverNode.buffer!==null){let e=this._nativeConvolverNode.context;this._nativeConvolverNode.buffer=e.createBuffer(1,1,e.sampleRate),this._isBufferNullified=!0,a(this,0)}else this._isBufferNullified=!1,a(this,this._nativeConvolverNode.buffer===null?0:this._nativeConvolverNode.buffer.duration)}get normalize(){return this._nativeConvolverNode.normalize}set normalize(e){this._nativeConvolverNode.normalize=e}},rn=(e,t,n)=>()=>{let r=new WeakMap,i=async(i,a)=>{let o=t(i);return Ce(o,a)||(o=e(a,{buffer:o.buffer,channelCount:o.channelCount,channelCountMode:o.channelCountMode,channelInterpretation:o.channelInterpretation,disableNormalization:!o.normalize})),r.set(a,o),nt(o)?await n(i,a,o.inputs[0]):await n(i,a,o),o};return{render(e,t){let n=r.get(t);return n===void 0?i(e,t):Promise.resolve(n)}}},an=(e,t)=>(n,r,i)=>{if(t===null)throw Error(`Missing the native OfflineAudioContext constructor.`);try{return new t(n,r,i)}catch(t){throw t.name===`SyntaxError`?e():t}},on=()=>new DOMException(``,`DataCloneError`),sn=e=>{let{port1:t,port2:n}=new MessageChannel;return new Promise(r=>{let i=()=>{n.onmessage=null,t.close(),n.close(),r()};n.onmessage=()=>i();try{t.postMessage(e,[e])}catch{}finally{i()}})},cn=(e,t,n,r,i,a,o,s,c,l,u)=>(d,f)=>{let p=o(d)?d:a(d);if(i.has(f)){let e=n();return Promise.reject(e)}try{i.add(f)}catch{}return t(c,()=>c(p))?p.decodeAudioData(f).then(n=>(sn(f).catch(()=>{}),t(s,()=>s(n))||u(n),e.add(n),n)):new Promise((t,n)=>{let i=async()=>{try{await sn(f)}catch{}},a=e=>{n(e),i()};try{p.decodeAudioData(f,n=>{typeof n.copyFromChannel!=`function`&&(l(n),De(n)),e.add(n),i().then(()=>t(n))},e=>{a(e===null?r():e)})}catch(e){a(e)}})},ln=(e,t,n,r,i,a,o,s)=>(c,l)=>{let u=t.get(c);if(u===void 0)throw Error(`Missing the expected cycle count.`);let d=s(a(c.context));if(u===l){if(t.delete(c),!d&&o(c)){let t=r(c),{outputs:a}=n(c);for(let n of a)if(Qe(n))e(t,r(n[0]),n[1],n[2]);else{let e=i(n[0]);t.connect(e,n[1])}}}else t.set(c,u-l)},un={channelCount:2,channelCountMode:`max`,channelInterpretation:`speakers`,delayTime:0,maxDelayTime:1},dn=(e,t,n,r,i,a,o)=>class extends e{constructor(e,s){let c=i(e),l={...un,...s},u=r(c,l),d=a(c),f=d?n(l.maxDelayTime):null;super(e,!1,u,f),this._delayTime=t(this,d,u.delayTime),o(this,l.maxDelayTime)}get delayTime(){return this._delayTime}},fn=(e,t,n,r,i)=>a=>{let o=new WeakMap,s=async(s,c)=>{let l=n(s),u=Ce(l,c);return u||(l=t(c,{channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,delayTime:l.delayTime.value,maxDelayTime:a})),o.set(c,l),u?await e(c,s.delayTime,l.delayTime):await r(c,s.delayTime,l.delayTime),await i(s,c,l),l};return{render(e,t){let n=o.get(t);return n===void 0?s(e,t):Promise.resolve(n)}}},pn=e=>(t,n,r,i)=>e(t[i],e=>e[0]===n&&e[1]===r),mn=e=>(t,n)=>{e(t).delete(n)},hn=e=>`delayTime`in e,gn=(e,t,n)=>function r(i,a){let o=Ze(a)?a:n(e,a);if(hn(o))return[];if(i[0]===o)return[i];if(i.includes(o))return[];let{outputs:s}=t(o);return Array.from(s).map(e=>r([...i,o],e[0])).reduce((e,t)=>e.concat(t),[])},_n=(e,t,n)=>{let r=t[n];if(r===void 0)throw e();return r},vn=e=>(t,n=void 0,r=void 0,i=0)=>n===void 0?t.forEach(e=>e.disconnect()):typeof n==`number`?_n(e,t,n).disconnect():ht(n)?r===void 0?t.forEach(e=>e.disconnect(n)):i===void 0?_n(e,t,r).disconnect(n,0):_n(e,t,r).disconnect(n,0,i):r===void 0?t.forEach(e=>e.disconnect(n)):_n(e,t,r).disconnect(n,0),yn={attack:.003,channelCount:2,channelCountMode:`clamped-max`,channelInterpretation:`speakers`,knee:30,ratio:12,release:.25,threshold:-24},bn=(e,t,n,r,i,a,o,s)=>class extends e{constructor(e,i){let c=a(e),l=r(c,{...yn,...i}),u=o(c),d=u?n():null;super(e,!1,l,d),this._attack=t(this,u,l.attack),this._knee=t(this,u,l.knee),this._nativeDynamicsCompressorNode=l,this._ratio=t(this,u,l.ratio),this._release=t(this,u,l.release),this._threshold=t(this,u,l.threshold),s(this,.006)}get attack(){return this._attack}get channelCount(){return this._nativeDynamicsCompressorNode.channelCount}set channelCount(e){let t=this._nativeDynamicsCompressorNode.channelCount;if(this._nativeDynamicsCompressorNode.channelCount=e,e>2)throw this._nativeDynamicsCompressorNode.channelCount=t,i()}get channelCountMode(){return this._nativeDynamicsCompressorNode.channelCountMode}set channelCountMode(e){let t=this._nativeDynamicsCompressorNode.channelCountMode;if(this._nativeDynamicsCompressorNode.channelCountMode=e,e===`max`)throw this._nativeDynamicsCompressorNode.channelCountMode=t,i()}get knee(){return this._knee}get ratio(){return this._ratio}get reduction(){return typeof this._nativeDynamicsCompressorNode.reduction.value==`number`?this._nativeDynamicsCompressorNode.reduction.value:this._nativeDynamicsCompressorNode.reduction}get release(){return this._release}get threshold(){return this._threshold}},xn=(e,t,n,r,i)=>()=>{let a=new WeakMap,o=async(o,s)=>{let c=n(o),l=Ce(c,s);return l||(c=t(s,{attack:c.attack.value,channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,knee:c.knee.value,ratio:c.ratio.value,release:c.release.value,threshold:c.threshold.value})),a.set(s,c),l?(await e(s,o.attack,c.attack),await e(s,o.knee,c.knee),await e(s,o.ratio,c.ratio),await e(s,o.release,c.release),await e(s,o.threshold,c.threshold)):(await r(s,o.attack,c.attack),await r(s,o.knee,c.knee),await r(s,o.ratio,c.ratio),await r(s,o.release,c.release),await r(s,o.threshold,c.threshold)),await i(o,s,c),c};return{render(e,t){let n=a.get(t);return n===void 0?o(e,t):Promise.resolve(n)}}},Sn=()=>new DOMException(``,`EncodingError`),Cn=e=>t=>new Promise((n,r)=>{if(e===null){r(SyntaxError());return}let i=e.document.head;if(i===null)r(SyntaxError());else{let a=e.document.createElement(`script`),o=new Blob([t],{type:`application/javascript`}),s=URL.createObjectURL(o),c=e.onerror,l=()=>{e.onerror=c,URL.revokeObjectURL(s)};e.onerror=(t,n,i,a,o)=>{if(n===s||n===e.location.href&&i===1&&a===1)return l(),r(o),!1;if(c!==null)return c(t,n,i,a,o)},a.onerror=()=>{l(),r(SyntaxError())},a.onload=()=>{l(),n()},a.src=s,a.type=`module`,i.appendChild(a)}}),wn=e=>class{constructor(e){this._nativeEventTarget=e,this._listeners=new WeakMap}addEventListener(t,n,r){if(n!==null){let i=this._listeners.get(n);i===void 0&&(i=e(this,n),typeof n==`function`&&this._listeners.set(n,i)),this._nativeEventTarget.addEventListener(t,i,r)}}dispatchEvent(e){return this._nativeEventTarget.dispatchEvent(e)}removeEventListener(e,t,n){let r=t===null?void 0:this._listeners.get(t);this._nativeEventTarget.removeEventListener(e,r===void 0?null:r,n)}},Tn=e=>(t,n,r)=>{Object.defineProperties(e,{currentFrame:{configurable:!0,get(){return Math.round(t*n)}},currentTime:{configurable:!0,get(){return t}}});try{return r()}finally{e!==null&&(delete e.currentFrame,delete e.currentTime)}},En=e=>async t=>{try{let e=await fetch(t);if(e.ok)return[await e.text(),e.url]}catch{}throw e()},Dn={channelCount:2,channelCountMode:`max`,channelInterpretation:`speakers`,gain:1},On=(e,t,n,r,i,a)=>class extends e{constructor(e,o){let s=i(e),c=r(s,{...Dn,...o}),l=a(s),u=l?n():null;super(e,!1,c,u),this._gain=t(this,l,c.gain,je,Ae)}get gain(){return this._gain}},kn=(e,t,n,r,i)=>()=>{let a=new WeakMap,o=async(o,s)=>{let c=n(o),l=Ce(c,s);return l||(c=t(s,{channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,gain:c.gain.value})),a.set(s,c),l?await e(s,o.gain,c.gain):await r(s,o.gain,c.gain),await i(o,s,c),c};return{render(e,t){let n=a.get(t);return n===void 0?o(e,t):Promise.resolve(n)}}},An=(e,t)=>n=>t(e,n),jn=e=>t=>{let n=e(t);if(n.renderer===null)throw Error(`Missing the renderer of the given AudioNode in the audio graph.`);return n.renderer},Mn=e=>t=>e.get(t)??0,Nn=e=>t=>{let n=e(t);if(n.renderer===null)throw Error(`Missing the renderer of the given AudioParam in the audio graph.`);return n.renderer},Pn=e=>t=>e.get(t),Fn=()=>new DOMException(``,`InvalidStateError`),In=e=>t=>{let n=e.get(t);if(n===void 0)throw Fn();return n},Ln=(e,t)=>n=>{let r=e.get(n);if(r!==void 0)return r;if(t===null)throw Error(`Missing the native OfflineAudioContext constructor.`);return r=new t(1,1,44100),e.set(n,r),r},Rn=e=>t=>{let n=e.get(t);if(n===void 0)throw Error(`The context has no set of AudioWorkletNodes.`);return n},zn=()=>new DOMException(``,`InvalidAccessError`),Bn=e=>{e.getFrequencyResponse=(t=>(n,r,i)=>{if(n.length!==r.length||r.length!==i.length)throw zn();return t.call(e,n,r,i)})(e.getFrequencyResponse)},Vn={channelCount:2,channelCountMode:`max`,channelInterpretation:`speakers`},Hn=(e,t,n,r,i,a)=>class extends e{constructor(e,o){let s=r(e),c=i(s),l={...Vn,...o},u=t(s,c?null:e.baseLatency,l),d=c?n(l.feedback,l.feedforward):null;super(e,!1,u,d),Bn(u),this._nativeIIRFilterNode=u,a(this,1)}getFrequencyResponse(e,t,n){return this._nativeIIRFilterNode.getFrequencyResponse(e,t,n)}},Un=(e,t,n,r,i,a,o,s,c,l,u)=>{let d=l.length,f=s;for(let s=0;s{let i=n instanceof Float64Array?n:new Float64Array(n),a=r instanceof Float64Array?r:new Float64Array(r),o=i.length,s=a.length,c=Math.min(o,s);if(i[0]!==1){for(let e=0;e(a,o)=>{let s=new WeakMap,c=null,l=async(l,u)=>{let d=null,f=t(l),p=Ce(f,u);if(u.createIIRFilter===void 0?d=e(u,{buffer:null,channelCount:2,channelCountMode:`max`,channelInterpretation:`speakers`,loop:!1,loopEnd:0,loopStart:0,playbackRate:1}):p||(f=u.createIIRFilter(o,a)),s.set(u,d===null?f:d),d!==null){if(c===null){if(n===null)throw Error(`Missing the native OfflineAudioContext constructor.`);let e=new n(l.context.destination.channelCount,l.context.length,u.sampleRate);c=(async()=>(await r(l,e,e.destination),Wn(await i(e),u,a,o)))()}let e=await c;return d.buffer=e,d.start(0),d}return await r(l,u,f),f};return{render(e,t){let n=s.get(t);return n===void 0?l(e,t):Promise.resolve(n)}}},Kn=(e,t,n,r,i,a)=>o=>(s,c)=>{let l=e.get(s);if(l===void 0){if(!o&&a(s)){let e=r(s),{outputs:a}=n(s);for(let n of a)if(Qe(n))t(e,r(n[0]),n[1],n[2]);else{let t=i(n[0]);e.disconnect(t,n[1])}}e.set(s,c)}else e.set(s,l+c)},qn=(e,t)=>n=>t(e.get(n))||t(n),Jn=(e,t)=>n=>e.has(n)||t(n),Yn=(e,t)=>n=>e.has(n)||t(n),Xn=(e,t)=>n=>t(e.get(n))||t(n),Zn=e=>t=>e!==null&&t instanceof e,Qn=e=>t=>e!==null&&typeof e.AudioNode==`function`&&t instanceof e.AudioNode,$n=e=>t=>e!==null&&typeof e.AudioParam==`function`&&t instanceof e.AudioParam,er=(e,t)=>n=>e(n)||t(n),tr=e=>t=>e!==null&&t instanceof e,nr=e=>e!==null&&e.isSecureContext,rr=(e,t,n,r)=>class extends e{constructor(e,i){let a=n(e),o=t(a,i);if(r(a))throw TypeError();super(e,!0,o,null),this._nativeMediaElementAudioSourceNode=o}get mediaElement(){return this._nativeMediaElementAudioSourceNode.mediaElement}},ir={channelCount:2,channelCountMode:`explicit`,channelInterpretation:`speakers`},ar=(e,t,n,r)=>class extends e{constructor(e,i){let a=n(e);if(r(a))throw TypeError();let o=t(a,{...ir,...i});super(e,!1,o,null),this._nativeMediaStreamAudioDestinationNode=o}get stream(){return this._nativeMediaStreamAudioDestinationNode.stream}},or=(e,t,n,r)=>class extends e{constructor(e,i){let a=n(e),o=t(a,i);if(r(a))throw TypeError();super(e,!0,o,null),this._nativeMediaStreamAudioSourceNode=o}get mediaStream(){return this._nativeMediaStreamAudioSourceNode.mediaStream}},sr=(e,t,n)=>class extends e{constructor(e,r){let i=t(n(e),r);super(e,!0,i,null)}},cr=(e,t,n,r,i,a)=>class extends n{constructor(n,a){super(n),this._nativeContext=n,re.set(this,n),r(n)&&i.set(n,new Set),this._destination=new e(this,a),this._listener=t(this,n),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(e){let t=typeof e==`function`?a(this,e):null;this._nativeContext.onstatechange=t;let n=this._nativeContext.onstatechange;this._onstatechange=n!==null&&n===t?e:n}get sampleRate(){return this._nativeContext.sampleRate}get state(){return this._nativeContext.state}},lr=e=>{let t=new Uint32Array([1179011410,40,1163280727,544501094,16,131073,44100,176400,1048580,1635017060,4,0]);try{let n=e.decodeAudioData(t.buffer,()=>{});return n===void 0?!1:(n.catch(()=>{}),!0)}catch{}return!1},ur=(e,t)=>(n,r,i)=>{let a=new Set;return n.connect=(i=>(o,s=0,c=0)=>{let l=a.size===0;if(t(o))return i.call(n,o,s,c),e(a,[o,s,c],e=>e[0]===o&&e[1]===s&&e[2]===c,!0),l&&r(),o;i.call(n,o,s),e(a,[o,s],e=>e[0]===o&&e[1]===s,!0),l&&r()})(n.connect),n.disconnect=(e=>(r,o,s)=>{let c=a.size>0;if(r===void 0)e.apply(n),a.clear();else if(typeof r==`number`){e.call(n,r);for(let e of a)e[1]===r&&a.delete(e)}else{t(r)?e.call(n,r,o,s):e.call(n,r,o);for(let e of a)e[0]===r&&(o===void 0||e[1]===o)&&(s===void 0||e[2]===s)&&a.delete(e)}let l=a.size===0;c&&l&&i()})(n.disconnect),n},dr=(e,t,n)=>{let r=t[n];r!==void 0&&r!==e[n]&&(e[n]=r)},fr=(e,t)=>{dr(e,t,`channelCount`),dr(e,t,`channelCountMode`),dr(e,t,`channelInterpretation`)},pr=e=>typeof e.getFloatTimeDomainData==`function`,mr=e=>{e.getFloatTimeDomainData=t=>{let n=new Uint8Array(t.length);e.getByteTimeDomainData(n);let r=Math.max(n.length,e.fftSize);for(let e=0;e(n,r)=>{let i=n.createAnalyser();if(fr(i,r),!(r.maxDecibels>r.minDecibels))throw t();return dr(i,r,`fftSize`),dr(i,r,`maxDecibels`),dr(i,r,`minDecibels`),dr(i,r,`smoothingTimeConstant`),e(pr,()=>pr(i))||mr(i),i},gr=e=>e===null?null:e.hasOwnProperty(`AudioBuffer`)?e.AudioBuffer:null,_r=(e,t,n)=>{let r=t[n];r!==void 0&&r!==e[n].value&&(e[n].value=r)},vr=e=>{e.start=(t=>{let n=!1;return(r=0,i=0,a)=>{if(n)throw Fn();t.call(e,r,i,a),n=!0}})(e.start)},yr=e=>{e.start=(t=>(n=0,r=0,i)=>{if(typeof i==`number`&&i<0||r<0||n<0)throw RangeError(`The parameters can't be negative.`);t.call(e,n,r,i)})(e.start)},br=e=>{e.stop=(t=>(n=0)=>{if(n<0)throw RangeError(`The parameter can't be negative.`);t.call(e,n)})(e.stop)},xr=(e,t,n,r,i,a,o,s,c,l,u)=>(d,f)=>{let p=d.createBufferSource();return fr(p,f),_r(p,f,`playbackRate`),dr(p,f,`buffer`),dr(p,f,`loop`),dr(p,f,`loopEnd`),dr(p,f,`loopStart`),t(n,()=>n(d))||vr(p),t(r,()=>r(d))||c(p),t(i,()=>i(d))||l(p,d),t(a,()=>a(d))||yr(p),t(o,()=>o(d))||u(p,d),t(s,()=>s(d))||br(p),e(d,p),p},Sr=e=>e===null?null:e.hasOwnProperty(`AudioContext`)?e.AudioContext:e.hasOwnProperty(`webkitAudioContext`)?e.webkitAudioContext:null,Cr=(e,t)=>(n,r,i)=>{let a=n.destination;if(a.channelCount!==r)try{a.channelCount=r}catch{}i&&a.channelCountMode!==`explicit`&&(a.channelCountMode=`explicit`),a.maxChannelCount===0&&Object.defineProperty(a,"maxChannelCount",{value:r});let o=e(n,{channelCount:r,channelCountMode:a.channelCountMode,channelInterpretation:a.channelInterpretation,gain:1});return t(o,`channelCount`,e=>()=>e.call(o),e=>t=>{e.call(o,t);try{a.channelCount=t}catch(e){if(t>a.maxChannelCount)throw e}}),t(o,`channelCountMode`,e=>()=>e.call(o),e=>t=>{e.call(o,t),a.channelCountMode=t}),t(o,`channelInterpretation`,e=>()=>e.call(o),e=>t=>{e.call(o,t),a.channelInterpretation=t}),Object.defineProperty(o,"maxChannelCount",{get:()=>a.maxChannelCount}),o.connect(a),o},wr=e=>e===null?null:e.hasOwnProperty(`AudioWorkletNode`)?e.AudioWorkletNode:null,Tr=e=>{let{port1:t}=new MessageChannel;try{t.postMessage(e)}finally{t.close()}},Er=(e,t,n,r,i)=>(a,o,s,c,l,u)=>{if(s!==null)try{let t=new s(a,c,u),r=new Map,o=null;if(Object.defineProperties(t,{channelCount:{get:()=>u.channelCount,set:()=>{throw e()}},channelCountMode:{get:()=>`explicit`,set:()=>{throw e()}},onprocessorerror:{get:()=>o,set:e=>{typeof o==`function`&&t.removeEventListener(`processorerror`,o),o=typeof e==`function`?e:null,typeof o==`function`&&t.addEventListener(`processorerror`,o)}}}),t.addEventListener=(e=>(...n)=>{if(n[0]===`processorerror`){let e=typeof n[1]==`function`?n[1]:typeof n[1]==`object`&&n[1]!==null&&typeof n[1].handleEvent==`function`?n[1].handleEvent:null;if(e!==null){let t=r.get(n[1]);t===void 0?(n[1]=t=>{t.type===`error`?(Object.defineProperties(t,{type:{value:`processorerror`}}),e(t)):e(new ErrorEvent(n[0],{...t}))},r.set(e,n[1])):n[1]=t}}return e.call(t,`error`,n[1],n[2]),e.call(t,...n)})(t.addEventListener),t.removeEventListener=(e=>(...n)=>{if(n[0]===`processorerror`){let e=r.get(n[1]);e!==void 0&&(r.delete(n[1]),n[1]=e)}return e.call(t,`error`,n[1],n[2]),e.call(t,n[0],n[1],n[2])})(t.removeEventListener),u.numberOfOutputs!==0){let e=n(a,{channelCount:1,channelCountMode:`explicit`,channelInterpretation:`discrete`,gain:0});return t.connect(e).connect(a.destination),i(t,()=>e.disconnect(),()=>e.connect(a.destination))}return t}catch(e){throw e.code===11?r():e}if(l===void 0)throw r();return Tr(u),t(a,o,l,u)},Dr=(e,t)=>e===null?512:Math.max(512,Math.min(16384,2**Math.round(Math.log2(e*t)))),Or=e=>new Promise((t,n)=>{let{port1:r,port2:i}=new MessageChannel;r.onmessage=({data:e})=>{r.close(),i.close(),t(e)},r.onmessageerror=({data:e})=>{r.close(),i.close(),n(e)},i.postMessage(e)}),kr=async(e,t)=>new e(await Or(t)),Ar=(e,t,n,r)=>{let i=k.get(e);i===void 0&&(i=new WeakMap,k.set(e,i));let a=kr(n,r);return i.set(t,a),a},jr=(e,t,n,r,i,a,o,s,c,l,u,d,f)=>(p,m,h,g)=>{if(g.numberOfInputs===0&&g.numberOfOutputs===0)throw c();let _=Array.isArray(g.outputChannelCount)?g.outputChannelCount:Array.from(g.outputChannelCount);if(_.some(e=>e<1))throw c();if(_.length!==g.numberOfOutputs)throw t();if(g.channelCountMode!==`explicit`)throw c();let v=g.channelCount*g.numberOfInputs,y=_.reduce((e,t)=>e+t,0),b=h.parameterDescriptors===void 0?0:h.parameterDescriptors.length;if(v+b>6||y>6)throw c();let x=new MessageChannel,S=[],C=[];for(let e=0;ee===void 0?0:e},maxValue:{get:()=>t===void 0?je:t},minValue:{get:()=>n===void 0?Ae:n}}),w.push(i)}let T=r(p,{channelCount:1,channelCountMode:`explicit`,channelInterpretation:`speakers`,numberOfInputs:Math.max(1,v+b)}),E=Dr(m,p.sampleRate),D=s(p,E,v+b,Math.max(1,y)),O=i(p,{channelCount:Math.max(1,y),channelCountMode:`explicit`,channelInterpretation:`discrete`,numberOfOutputs:Math.max(1,y)}),ee=[];for(let e=0;e{let n=w[t];return n.connect(T,0,v+t),n.start(0),[e,n.offset]}));T.connect(D);let ne=g.channelInterpretation,re=null,ie=g.numberOfOutputs===0?[D]:ee,ae={get bufferSize(){return E},get channelCount(){return g.channelCount},set channelCount(e){throw n()},get channelCountMode(){return g.channelCountMode},set channelCountMode(e){throw n()},get channelInterpretation(){return ne},set channelInterpretation(e){for(let t of S)t.channelInterpretation=e;ne=e},get context(){return D.context},get inputs(){return S},get numberOfInputs(){return g.numberOfInputs},get numberOfOutputs(){return g.numberOfOutputs},get onprocessorerror(){return re},set onprocessorerror(e){typeof re==`function`&&ae.removeEventListener(`processorerror`,re),re=typeof e==`function`?e:null,typeof re==`function`&&ae.addEventListener(`processorerror`,re)},get parameters(){return te},get port(){return x.port2},addEventListener(...e){return D.addEventListener(e[0],e[1],e[2])},connect:e.bind(null,ie),disconnect:l.bind(null,ie),dispatchEvent(...e){return D.dispatchEvent(e[0])},removeEventListener(...e){return D.removeEventListener(e[0],e[1],e[2])}},oe=new Map;x.port1.addEventListener=(e=>(...t)=>{if(t[0]===`message`){let e=typeof t[1]==`function`?t[1]:typeof t[1]==`object`&&t[1]!==null&&typeof t[1].handleEvent==`function`?t[1].handleEvent:null;if(e!==null){let n=oe.get(t[1]);n===void 0?(t[1]=t=>{u(p.currentTime,p.sampleRate,()=>e(t))},oe.set(e,t[1])):t[1]=n}}return e.call(x.port1,t[0],t[1],t[2])})(x.port1.addEventListener),x.port1.removeEventListener=(e=>(...t)=>{if(t[0]===`message`){let e=oe.get(t[1]);e!==void 0&&(oe.delete(t[1]),t[1]=e)}return e.call(x.port1,t[0],t[1],t[2])})(x.port1.removeEventListener);let k=null;Object.defineProperty(x.port1,"onmessage",{get:()=>k,set:e=>{typeof k==`function`&&x.port1.removeEventListener(`message`,k),k=typeof e==`function`?e:null,typeof k==`function`&&(x.port1.addEventListener(`message`,k),x.port1.start())}}),h.prototype.port=x.port1;let A=null;Ar(p,ae,h,g).then(e=>A=e);let se=Nt(g.numberOfInputs,g.channelCount),ce=Nt(g.numberOfOutputs,_),le=h.parameterDescriptors===void 0?[]:h.parameterDescriptors.reduce((e,{name:t})=>({...e,[t]:new Float32Array(128)}),{}),j=!0,M=()=>{g.numberOfOutputs>0&&D.disconnect(O);for(let e=0,t=0;e{if(A!==null){let n=d(ae);for(let r=0;r{jt(e,le,t,v+n,r)});for(let e=0;e{if(n[t].size>0)return N.set(t,E/128),e;let r=N.get(t);return r===void 0?[]:(e.every(e=>e.every(e=>e===0))&&(r===1?N.delete(t):N.set(t,r-1)),e)});j=u(p.currentTime+r/p.sampleRate,p.sampleRate,()=>A.process(e,ce,le));for(let e=0,n=0;eD.connect(ue).connect(p.destination),fe=()=>{D.disconnect(ue),ue.disconnect()};return de(),f(ae,()=>{if(j){fe(),g.numberOfOutputs>0&&D.connect(O);for(let e=0,t=0;e{j&&(de(),M()),P=!1})},Mr=(e,t)=>{let n=e.createBiquadFilter();return fr(n,t),_r(n,t,`Q`),_r(n,t,`detune`),_r(n,t,`frequency`),_r(n,t,`gain`),dr(n,t,`type`),n},Nr=(e,t)=>(n,r)=>{let i=n.createChannelMerger(r.numberOfInputs);return e!==null&&e.name===`webkitAudioContext`&&t(n,i),fr(i,r),i},Pr=e=>{let t=e.numberOfOutputs;Object.defineProperty(e,"channelCount",{get:()=>t,set:e=>{if(e!==t)throw Fn()}}),Object.defineProperty(e,"channelCountMode",{get:()=>`explicit`,set:e=>{if(e!==`explicit`)throw Fn()}}),Object.defineProperty(e,"channelInterpretation",{get:()=>`discrete`,set:e=>{if(e!==`discrete`)throw Fn()}})},Fr=(e,t)=>{let n=e.createChannelSplitter(t.numberOfOutputs);return fr(n,t),Pr(n),n},Ir=(e,t,n,r,i)=>(a,o)=>{if(a.createConstantSource===void 0)return n(a,o);let s=a.createConstantSource();return fr(s,o),_r(s,o,`offset`),t(r,()=>r(a))||yr(s),t(i,()=>i(a))||br(s),e(a,s),s},Lr=(e,t)=>(e.connect=t.connect.bind(t),e.disconnect=t.disconnect.bind(t),e),Rr=(e,t,n,r)=>(i,{offset:a,...o})=>{let s=i.createBuffer(1,2,44100),c=t(i,{buffer:null,channelCount:2,channelCountMode:`max`,channelInterpretation:`speakers`,loop:!1,loopEnd:0,loopStart:0,playbackRate:1}),l=n(i,{...o,gain:a}),u=s.getChannelData(0);return u[0]=1,u[1]=1,c.buffer=s,c.loop=!0,e(i,c),r(Lr({get bufferSize(){},get channelCount(){return l.channelCount},set channelCount(e){l.channelCount=e},get channelCountMode(){return l.channelCountMode},set channelCountMode(e){l.channelCountMode=e},get channelInterpretation(){return l.channelInterpretation},set channelInterpretation(e){l.channelInterpretation=e},get context(){return l.context},get inputs(){return[]},get numberOfInputs(){return c.numberOfInputs},get numberOfOutputs(){return l.numberOfOutputs},get offset(){return l.gain},get onended(){return c.onended},set onended(e){c.onended=e},addEventListener(...e){return c.addEventListener(e[0],e[1],e[2])},dispatchEvent(...e){return c.dispatchEvent(e[0])},removeEventListener(...e){return c.removeEventListener(e[0],e[1],e[2])},start(e=0){c.start.call(c,e)},stop(e=0){c.stop.call(c,e)}},l),()=>c.connect(l),()=>c.disconnect(l))},zr=(e,t)=>(n,r)=>{let i=n.createConvolver();if(fr(i,r),r.disableNormalization===i.normalize&&(i.normalize=!r.disableNormalization),dr(i,r,`buffer`),r.channelCount>2||(t(i,`channelCount`,e=>()=>e.call(i),t=>n=>{if(n>2)throw e();return t.call(i,n)}),r.channelCountMode===`max`))throw e();return t(i,`channelCountMode`,e=>()=>e.call(i),t=>n=>{if(n===`max`)throw e();return t.call(i,n)}),i},Br=(e,t)=>{let n=e.createDelay(t.maxDelayTime);return fr(n,t),_r(n,t,`delayTime`),n},Vr=e=>(t,n)=>{let r=t.createDynamicsCompressor();if(fr(r,n),n.channelCount>2||n.channelCountMode===`max`)throw e();return _r(r,n,`attack`),_r(r,n,`knee`),_r(r,n,`ratio`),_r(r,n,`release`),_r(r,n,`threshold`),r},Hr=(e,t)=>{let n=e.createGain();return fr(n,t),_r(n,t,`gain`),n},Ur=e=>(t,n,r)=>{if(t.createIIRFilter===void 0)return e(t,n,r);let i=t.createIIRFilter(r.feedforward,r.feedback);return fr(i,r),i};function Wr(e,t){let n=t[0]*t[0]+t[1]*t[1];return[(e[0]*t[0]+e[1]*t[1])/n,(e[1]*t[0]-e[0]*t[1])/n]}function Gr(e,t){return[e[0]*t[0]-e[1]*t[1],e[0]*t[1]+e[1]*t[0]]}function Kr(e,t){let n=[0,0];for(let r=e.length-1;r>=0;--r)n=Gr(n,t),n[0]+=e[r];return n}var qr=(e,t,n,r)=>(i,a,{channelCount:o,channelCountMode:s,channelInterpretation:c,feedback:l,feedforward:u})=>{let d=Dr(a,i.sampleRate),f=l instanceof Float64Array?l:new Float64Array(l),p=u instanceof Float64Array?u:new Float64Array(u),m=f.length,h=p.length,g=Math.min(m,h);if(m===0||m>20)throw r();if(f[0]===0)throw t();if(h===0||h>20)throw r();if(p[0]===0)throw t();if(f[0]!==1){for(let e=0;e{let t=e.inputBuffer,n=e.outputBuffer,r=t.numberOfChannels;for(let e=0;ee.createMediaElementSource(t.mediaElement),Yr=(e,t)=>{let n=e.createMediaStreamDestination();return fr(n,t),n.numberOfOutputs===1&&Object.defineProperty(n,"numberOfOutputs",{get:()=>0}),n},Xr=(e,{mediaStream:t})=>{let n=t.getAudioTracks();n.sort((e,t)=>e.idt.id));let r=n.slice(0,1),i=e.createMediaStreamSource(new MediaStream(r));return Object.defineProperty(i,"mediaStream",{value:t}),i},Zr=(e,t)=>(n,{mediaStreamTrack:r})=>{if(typeof n.createMediaStreamTrackSource==`function`)return n.createMediaStreamTrackSource(r);let i=new MediaStream([r]),a=n.createMediaStreamSource(i);if(r.kind!==`audio`)throw e();if(t(n))throw TypeError();return a},Qr=e=>e===null?null:e.hasOwnProperty(`OfflineAudioContext`)?e.OfflineAudioContext:e.hasOwnProperty(`webkitOfflineAudioContext`)?e.webkitOfflineAudioContext:null,$r=(e,t,n,r,i,a)=>(o,s)=>{let c=o.createOscillator();return fr(c,s),_r(c,s,`detune`),_r(c,s,`frequency`),s.periodicWave===void 0?dr(c,s,`type`):c.setPeriodicWave(s.periodicWave),t(n,()=>n(o))||yr(c),t(r,()=>r(o))||a(c,o),t(i,()=>i(o))||br(c),e(o,c),c},ei=e=>(t,n)=>{let r=t.createPanner();return r.orientationX===void 0?e(t,n):(fr(r,n),_r(r,n,`orientationX`),_r(r,n,`orientationY`),_r(r,n,`orientationZ`),_r(r,n,`positionX`),_r(r,n,`positionY`),_r(r,n,`positionZ`),dr(r,n,`coneInnerAngle`),dr(r,n,`coneOuterAngle`),dr(r,n,`coneOuterGain`),dr(r,n,`distanceModel`),dr(r,n,`maxDistance`),dr(r,n,`panningModel`),dr(r,n,`refDistance`),dr(r,n,`rolloffFactor`),r)},ti=(e,t,n,r,i,a,o,s,c,l)=>(u,{coneInnerAngle:d,coneOuterAngle:f,coneOuterGain:p,distanceModel:m,maxDistance:h,orientationX:g,orientationY:_,orientationZ:v,panningModel:y,positionX:b,positionY:x,positionZ:S,refDistance:C,rolloffFactor:w,...T})=>{let E=u.createPanner();if(T.channelCount>2||T.channelCountMode===`max`)throw o();fr(E,T);let D={channelCount:1,channelCountMode:`explicit`,channelInterpretation:`discrete`},O=n(u,{...D,channelInterpretation:`speakers`,numberOfInputs:6}),ee=r(u,{...T,gain:1}),te=r(u,{...D,gain:1}),ne=r(u,{...D,gain:0}),re=r(u,{...D,gain:0}),ie=r(u,{...D,gain:0}),ae=r(u,{...D,gain:0}),oe=r(u,{...D,gain:0}),k=i(u,256,6,1),A=a(u,{...D,curve:new Float32Array([1,1]),oversample:`none`}),se=[g,_,v],ce=[b,x,S],le=new Float32Array(1);k.onaudioprocess=({inputBuffer:e})=>{let t=[c(e,le,0),c(e,le,1),c(e,le,2)];t.some((e,t)=>e!==se[t])&&(E.setOrientation(...t),se=t);let n=[c(e,le,3),c(e,le,4),c(e,le,5)];n.some((e,t)=>e!==ce[t])&&(E.setPosition(...n),ce=n)},Object.defineProperty(ne.gain,"defaultValue",{get:()=>0}),Object.defineProperty(re.gain,"defaultValue",{get:()=>0}),Object.defineProperty(ie.gain,"defaultValue",{get:()=>0}),Object.defineProperty(ae.gain,"defaultValue",{get:()=>0}),Object.defineProperty(oe.gain,"defaultValue",{get:()=>0});let j={get bufferSize(){},get channelCount(){return E.channelCount},set channelCount(e){if(e>2)throw o();ee.channelCount=e,E.channelCount=e},get channelCountMode(){return E.channelCountMode},set channelCountMode(e){if(e===`max`)throw o();ee.channelCountMode=e,E.channelCountMode=e},get channelInterpretation(){return E.channelInterpretation},set channelInterpretation(e){ee.channelInterpretation=e,E.channelInterpretation=e},get coneInnerAngle(){return E.coneInnerAngle},set coneInnerAngle(e){E.coneInnerAngle=e},get coneOuterAngle(){return E.coneOuterAngle},set coneOuterAngle(e){E.coneOuterAngle=e},get coneOuterGain(){return E.coneOuterGain},set coneOuterGain(e){if(e<0||e>1)throw t();E.coneOuterGain=e},get context(){return E.context},get distanceModel(){return E.distanceModel},set distanceModel(e){E.distanceModel=e},get inputs(){return[ee]},get maxDistance(){return E.maxDistance},set maxDistance(e){if(e<0)throw RangeError();E.maxDistance=e},get numberOfInputs(){return E.numberOfInputs},get numberOfOutputs(){return E.numberOfOutputs},get orientationX(){return te.gain},get orientationY(){return ne.gain},get orientationZ(){return re.gain},get panningModel(){return E.panningModel},set panningModel(e){E.panningModel=e},get positionX(){return ie.gain},get positionY(){return ae.gain},get positionZ(){return oe.gain},get refDistance(){return E.refDistance},set refDistance(e){if(e<0)throw RangeError();E.refDistance=e},get rolloffFactor(){return E.rolloffFactor},set rolloffFactor(e){if(e<0)throw RangeError();E.rolloffFactor=e},addEventListener(...e){return ee.addEventListener(e[0],e[1],e[2])},dispatchEvent(...e){return ee.dispatchEvent(e[0])},removeEventListener(...e){return ee.removeEventListener(e[0],e[1],e[2])}};return d!==j.coneInnerAngle&&(j.coneInnerAngle=d),f!==j.coneOuterAngle&&(j.coneOuterAngle=f),p!==j.coneOuterGain&&(j.coneOuterGain=p),m!==j.distanceModel&&(j.distanceModel=m),h!==j.maxDistance&&(j.maxDistance=h),g!==j.orientationX.value&&(j.orientationX.value=g),_!==j.orientationY.value&&(j.orientationY.value=_),v!==j.orientationZ.value&&(j.orientationZ.value=v),y!==j.panningModel&&(j.panningModel=y),b!==j.positionX.value&&(j.positionX.value=b),x!==j.positionY.value&&(j.positionY.value=x),S!==j.positionZ.value&&(j.positionZ.value=S),C!==j.refDistance&&(j.refDistance=C),w!==j.rolloffFactor&&(j.rolloffFactor=w),(se[0]!==1||se[1]!==0||se[2]!==0)&&E.setOrientation(...se),(ce[0]!==0||ce[1]!==0||ce[2]!==0)&&E.setPosition(...ce),l(Lr(j,E),()=>{ee.connect(E),e(ee,A,0,0),A.connect(te).connect(O,0,0),A.connect(ne).connect(O,0,1),A.connect(re).connect(O,0,2),A.connect(ie).connect(O,0,3),A.connect(ae).connect(O,0,4),A.connect(oe).connect(O,0,5),O.connect(k).connect(u.destination)},()=>{ee.disconnect(E),s(ee,A,0,0),A.disconnect(te),te.disconnect(O),A.disconnect(ne),ne.disconnect(O),A.disconnect(re),re.disconnect(O),A.disconnect(ie),ie.disconnect(O),A.disconnect(ae),ae.disconnect(O),A.disconnect(oe),oe.disconnect(O),O.disconnect(k),k.disconnect(u.destination)})},ni=e=>(t,{disableNormalization:n,imag:r,real:i})=>{let a=r instanceof Float32Array?r:new Float32Array(r),o=i instanceof Float32Array?i:new Float32Array(i),s=t.createPeriodicWave(o,a,{disableNormalization:n});if(Array.from(r).length<2)throw e();return s},ri=(e,t,n,r)=>e.createScriptProcessor(t,n,r),ii=(e,t)=>(n,r)=>{let i=r.channelCountMode;if(i===`clamped-max`)throw t();if(n.createStereoPanner===void 0)return e(n,r);let a=n.createStereoPanner();return fr(a,r),_r(a,r,`pan`),Object.defineProperty(a,"channelCountMode",{get:()=>i,set:e=>{if(e!==i)throw t()}}),a},ai=(e,t,n,r,i,a)=>{let o=16385,s=new Float32Array([1,1]),c=Math.PI/2,l={channelCount:1,channelCountMode:`explicit`,channelInterpretation:`discrete`},u={...l,oversample:`none`},d=(e,t,i,a)=>{let d=new Float32Array(o),f=new Float32Array(o);for(let e=0;e{let f=new Float32Array(o),p=new Float32Array(o),m=new Float32Array(o),h=new Float32Array(o),g=8192;for(let e=0;eg){let t=(e-g)/(o-1-g)*c;f[e]=Math.cos(t),p[e]=Math.sin(t),m[e]=0,h[e]=1}else{let t=e/(o-1-g)*c;f[e]=1,p[e]=0,m[e]=Math.cos(t),h[e]=Math.sin(t)}let _=t(e,{channelCount:2,channelCountMode:`explicit`,channelInterpretation:`discrete`,numberOfOutputs:2}),v=n(e,{...l,gain:0}),y=r(e,{...u,curve:f}),b=n(e,{...l,gain:0}),x=r(e,{...u,curve:p}),S=r(e,{...u,curve:s}),C=n(e,{...l,gain:0}),w=r(e,{...u,curve:m}),T=n(e,{...l,gain:0}),E=r(e,{...u,curve:h});return{connectGraph(){i.connect(_),i.connect(S.inputs===void 0?S:S.inputs[0]),_.connect(v,0),_.connect(b,0),_.connect(C,1),_.connect(T,1),S.connect(a),a.connect(y.inputs===void 0?y:y.inputs[0]),a.connect(x.inputs===void 0?x:x.inputs[0]),a.connect(w.inputs===void 0?w:w.inputs[0]),a.connect(E.inputs===void 0?E:E.inputs[0]),y.connect(v.gain),x.connect(b.gain),w.connect(C.gain),E.connect(T.gain),v.connect(d,0,0),C.connect(d,0,0),b.connect(d,0,1),T.connect(d,0,1)},disconnectGraph(){i.disconnect(_),i.disconnect(S.inputs===void 0?S:S.inputs[0]),_.disconnect(v,0),_.disconnect(b,0),_.disconnect(C,1),_.disconnect(T,1),S.disconnect(a),a.disconnect(y.inputs===void 0?y:y.inputs[0]),a.disconnect(x.inputs===void 0?x:x.inputs[0]),a.disconnect(w.inputs===void 0?w:w.inputs[0]),a.disconnect(E.inputs===void 0?E:E.inputs[0]),y.disconnect(v.gain),x.disconnect(b.gain),w.disconnect(C.gain),E.disconnect(T.gain),v.disconnect(d,0,0),C.disconnect(d,0,0),b.disconnect(d,0,1),T.disconnect(d,0,1)}}},p=(e,t,n,r,a)=>{if(t===1)return d(e,n,r,a);if(t===2)return f(e,n,r,a);throw i()};return(t,{channelCount:r,channelCountMode:o,pan:s,...c})=>{if(o===`max`)throw i();let l=e(t,{...c,channelCount:1,channelCountMode:o,numberOfInputs:2}),u=n(t,{...c,channelCount:r,channelCountMode:o,gain:1}),d=n(t,{channelCount:1,channelCountMode:`explicit`,channelInterpretation:`discrete`,gain:s}),{connectGraph:f,disconnectGraph:m}=p(t,r,u,d,l);Object.defineProperty(d.gain,"defaultValue",{get:()=>0}),Object.defineProperty(d.gain,"maxValue",{get:()=>1}),Object.defineProperty(d.gain,"minValue",{get:()=>-1});let h={get bufferSize(){},get channelCount(){return u.channelCount},set channelCount(e){u.channelCount!==e&&(g&&m(),{connectGraph:f,disconnectGraph:m}=p(t,e,u,d,l),g&&f()),u.channelCount=e},get channelCountMode(){return u.channelCountMode},set channelCountMode(e){if(e===`clamped-max`||e===`max`)throw i();u.channelCountMode=e},get channelInterpretation(){return u.channelInterpretation},set channelInterpretation(e){u.channelInterpretation=e},get context(){return u.context},get inputs(){return[u]},get numberOfInputs(){return u.numberOfInputs},get numberOfOutputs(){return u.numberOfOutputs},get pan(){return d.gain},addEventListener(...e){return u.addEventListener(e[0],e[1],e[2])},dispatchEvent(...e){return u.dispatchEvent(e[0])},removeEventListener(...e){return u.removeEventListener(e[0],e[1],e[2])}},g=!1;return a(Lr(h,l),()=>{f(),g=!0},()=>{m(),g=!1})}},oi=(e,t,n,r,i,a,o)=>(s,c)=>{let l=s.createWaveShaper();if(a!==null&&a.name===`webkitAudioContext`&&s.createGain().gain.automationRate===void 0)return n(s,c);fr(l,c);let u=c.curve===null||c.curve instanceof Float32Array?c.curve:new Float32Array(c.curve);if(u!==null&&u.length<2)throw t();dr(l,{curve:u},`curve`),dr(l,c,`oversample`);let d=null,f=!1;return o(l,`curve`,e=>()=>e.call(l),t=>n=>(t.call(l,n),f&&(r(n)&&d===null?d=e(s,l):!r(n)&&d!==null&&(d(),d=null)),n)),i(l,()=>{f=!0,r(l.curve)&&(d=e(s,l))},()=>{f=!1,d!==null&&(d(),d=null)})},si=(e,t,n,r,i)=>(a,{curve:o,oversample:s,...c})=>{let l=a.createWaveShaper(),u=a.createWaveShaper();fr(l,c),fr(u,c);let d=n(a,{...c,gain:1}),f=n(a,{...c,gain:-1}),p=n(a,{...c,gain:1}),m=n(a,{...c,gain:-1}),h=null,g=!1,_=null,v={get bufferSize(){},get channelCount(){return l.channelCount},set channelCount(e){d.channelCount=e,f.channelCount=e,l.channelCount=e,p.channelCount=e,u.channelCount=e,m.channelCount=e},get channelCountMode(){return l.channelCountMode},set channelCountMode(e){d.channelCountMode=e,f.channelCountMode=e,l.channelCountMode=e,p.channelCountMode=e,u.channelCountMode=e,m.channelCountMode=e},get channelInterpretation(){return l.channelInterpretation},set channelInterpretation(e){d.channelInterpretation=e,f.channelInterpretation=e,l.channelInterpretation=e,p.channelInterpretation=e,u.channelInterpretation=e,m.channelInterpretation=e},get context(){return l.context},get curve(){return _},set curve(n){if(n!==null&&n.length<2)throw t();if(n===null)l.curve=n,u.curve=n;else{let e=n.length,t=new Float32Array(e+2-e%2),r=new Float32Array(e+2-e%2);t[0]=n[0],r[0]=-n[e-1];let i=Math.ceil((e+1)/2),a=(e+1)/2-1;for(let o=1;o{d.connect(l).connect(p),d.connect(f).connect(u).connect(m).connect(p),g=!0,r(_)&&(h=e(a,d))},()=>{d.disconnect(l),l.disconnect(p),d.disconnect(f),f.disconnect(u),u.disconnect(m),m.disconnect(p),g=!1,h!==null&&(h(),h=null)})},ci=()=>new DOMException(``,`NotSupportedError`),li={numberOfChannels:1},ui=(e,t,n,r,i)=>class extends e{constructor(e,n,i){let a;if(typeof e==`number`&&n!==void 0&&i!==void 0)a={length:n,numberOfChannels:e,sampleRate:i};else if(typeof e==`object`)a=e;else throw Error(`The given parameters are not valid.`);let{length:o,numberOfChannels:s,sampleRate:c}={...li,...a},l=r(s,o,c);t(lr,()=>lr(l))||l.addEventListener(`statechange`,(()=>{let e=0,t=n=>{this._state===`running`&&(e>0?(l.removeEventListener(`statechange`,t),n.stopImmediatePropagation(),this._waitForThePromiseToSettle(n)):e+=1)};return t})()),super(l,s),this._length=o,this._nativeOfflineAudioContext=l,this._state=null}get length(){return this._nativeOfflineAudioContext.length===void 0?this._length:this._nativeOfflineAudioContext.length}get state(){return this._state===null?this._nativeOfflineAudioContext.state:this._state}startRendering(){return this._state===`running`?Promise.reject(n()):(this._state=`running`,i(this.destination,this._nativeOfflineAudioContext).finally(()=>{this._state=null,Ge(this)}))}_waitForThePromiseToSettle(e){this._state===null?this._nativeOfflineAudioContext.dispatchEvent(e):setTimeout(()=>this._waitForThePromiseToSettle(e))}},di={channelCount:2,channelCountMode:`max`,channelInterpretation:`speakers`,detune:0,frequency:440,periodicWave:void 0,type:`sine`},fi=(e,t,n,r,i,a,o)=>class extends e{constructor(e,o){let s=i(e),c={...di,...o},l=n(s,c),u=a(s),d=u?r():null,f=e.sampleRate/2;super(e,!1,l,d),this._detune=t(this,u,l.detune,153600,-153600),this._frequency=t(this,u,l.frequency,f,-f),this._nativeOscillatorNode=l,this._onended=null,this._oscillatorNodeRenderer=d,this._oscillatorNodeRenderer!==null&&c.periodicWave!==void 0&&(this._oscillatorNodeRenderer.periodicWave=c.periodicWave)}get detune(){return this._detune}get frequency(){return this._frequency}get onended(){return this._onended}set onended(e){let t=typeof e==`function`?o(this,e):null;this._nativeOscillatorNode.onended=t;let n=this._nativeOscillatorNode.onended;this._onended=n!==null&&n===t?e:n}get type(){return this._nativeOscillatorNode.type}set type(e){this._nativeOscillatorNode.type=e,this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.periodicWave=null)}setPeriodicWave(e){this._nativeOscillatorNode.setPeriodicWave(e),this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.periodicWave=e)}start(e=0){if(this._nativeOscillatorNode.start(e),this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.start=e),this.context.state!==`closed`){pe(this);let e=()=>{this._nativeOscillatorNode.removeEventListener(`ended`,e),Me(this)&&he(this)};this._nativeOscillatorNode.addEventListener(`ended`,e)}}stop(e=0){this._nativeOscillatorNode.stop(e),this._oscillatorNodeRenderer!==null&&(this._oscillatorNodeRenderer.stop=e)}},pi=(e,t,n,r,i)=>()=>{let a=new WeakMap,o=null,s=null,c=null,l=async(l,u)=>{let d=n(l),f=Ce(d,u);return f||(d=t(u,{channelCount:d.channelCount,channelCountMode:d.channelCountMode,channelInterpretation:d.channelInterpretation,detune:d.detune.value,frequency:d.frequency.value,periodicWave:o===null?void 0:o,type:d.type}),s!==null&&d.start(s),c!==null&&d.stop(c)),a.set(u,d),f?(await e(u,l.detune,d.detune),await e(u,l.frequency,d.frequency)):(await r(u,l.detune,d.detune),await r(u,l.frequency,d.frequency)),await i(l,u,d),d};return{set periodicWave(e){o=e},set start(e){s=e},set stop(e){c=e},render(e,t){let n=a.get(t);return n===void 0?l(e,t):Promise.resolve(n)}}},mi={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},hi=(e,t,n,r,i,a,o)=>class extends e{constructor(e,s){let c=i(e),l=n(c,{...mi,...s}),u=a(c),d=u?r():null;super(e,!1,l,d),this._nativePannerNode=l,this._orientationX=t(this,u,l.orientationX,je,Ae),this._orientationY=t(this,u,l.orientationY,je,Ae),this._orientationZ=t(this,u,l.orientationZ,je,Ae),this._positionX=t(this,u,l.positionX,je,Ae),this._positionY=t(this,u,l.positionY,je,Ae),this._positionZ=t(this,u,l.positionZ,je,Ae),o(this,1)}get coneInnerAngle(){return this._nativePannerNode.coneInnerAngle}set coneInnerAngle(e){this._nativePannerNode.coneInnerAngle=e}get coneOuterAngle(){return this._nativePannerNode.coneOuterAngle}set coneOuterAngle(e){this._nativePannerNode.coneOuterAngle=e}get coneOuterGain(){return this._nativePannerNode.coneOuterGain}set coneOuterGain(e){this._nativePannerNode.coneOuterGain=e}get distanceModel(){return this._nativePannerNode.distanceModel}set distanceModel(e){this._nativePannerNode.distanceModel=e}get maxDistance(){return this._nativePannerNode.maxDistance}set maxDistance(e){this._nativePannerNode.maxDistance=e}get orientationX(){return this._orientationX}get orientationY(){return this._orientationY}get orientationZ(){return this._orientationZ}get panningModel(){return this._nativePannerNode.panningModel}set panningModel(e){this._nativePannerNode.panningModel=e}get positionX(){return this._positionX}get positionY(){return this._positionY}get positionZ(){return this._positionZ}get refDistance(){return this._nativePannerNode.refDistance}set refDistance(e){this._nativePannerNode.refDistance=e}get rolloffFactor(){return this._nativePannerNode.rolloffFactor}set rolloffFactor(e){this._nativePannerNode.rolloffFactor=e}},gi=(e,t,n,r,i,a,o,s,c,l)=>()=>{let u=new WeakMap,d=null,f=async(f,p)=>{let m=null,h=a(f),g={channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation},_={...g,coneInnerAngle:h.coneInnerAngle,coneOuterAngle:h.coneOuterAngle,coneOuterGain:h.coneOuterGain,distanceModel:h.distanceModel,maxDistance:h.maxDistance,panningModel:h.panningModel,refDistance:h.refDistance,rolloffFactor:h.rolloffFactor},v=Ce(h,p);if(`bufferSize`in h?m=r(p,{...g,gain:1}):v||(h=i(p,{..._,orientationX:h.orientationX.value,orientationY:h.orientationY.value,orientationZ:h.orientationZ.value,positionX:h.positionX.value,positionY:h.positionY.value,positionZ:h.positionZ.value})),u.set(p,m===null?h:m),m!==null){if(d===null){if(o===null)throw Error(`Missing the native OfflineAudioContext constructor.`);let e=new o(6,f.context.length,p.sampleRate),r=t(e,{channelCount:1,channelCountMode:`explicit`,channelInterpretation:`speakers`,numberOfInputs:6});r.connect(e.destination),d=(async()=>{let t=await Promise.all([f.orientationX,f.orientationY,f.orientationZ,f.positionX,f.positionY,f.positionZ].map(async(t,r)=>{let i=n(e,{channelCount:1,channelCountMode:`explicit`,channelInterpretation:`discrete`,offset:+(r===0)});return await s(e,t,i.offset),i}));for(let e=0;e<6;e+=1)t[e].connect(r,0,e),t[e].start(0);return l(e)})()}let e=await d,a=r(p,{...g,gain:1});await c(f,p,a);let u=[];for(let t=0;te!==h[t])||n.some((e,t)=>e!==v[t])){h=e,v=n;let o=t/p.sampleRate;y.gain.setValueAtTime(0,o),y=r(p,{...g,gain:0}),b=i(p,{..._,orientationX:h[0],orientationY:h[1],orientationZ:h[2],positionX:v[0],positionY:v[1],positionZ:v[2]}),y.gain.setValueAtTime(1,o),a.connect(y).connect(b.inputs[0]),b.connect(m)}}return m}return v?(await e(p,f.orientationX,h.orientationX),await e(p,f.orientationY,h.orientationY),await e(p,f.orientationZ,h.orientationZ),await e(p,f.positionX,h.positionX),await e(p,f.positionY,h.positionY),await e(p,f.positionZ,h.positionZ)):(await s(p,f.orientationX,h.orientationX),await s(p,f.orientationY,h.orientationY),await s(p,f.orientationZ,h.orientationZ),await s(p,f.positionX,h.positionX),await s(p,f.positionY,h.positionY),await s(p,f.positionZ,h.positionZ)),nt(h)?await c(f,p,h.inputs[0]):await c(f,p,h),h};return{render(e,t){let n=u.get(t);return n===void 0?f(e,t):Promise.resolve(n)}}},_i={disableNormalization:!1},vi=(e,t,n,r)=>class i{constructor(i,a){let o=e(t(i),r({..._i,...a}));return n.add(o),o}static[Symbol.hasInstance](e){return typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===i.prototype||n.has(e)}},yi=(e,t)=>(n,r,i)=>(e(r).replay(i),t(r,n,i)),bi=(e,t,n)=>async(r,i,a)=>{let o=e(r);await Promise.all(o.activeInputs.map((e,o)=>Array.from(e).map(async([e,s])=>{let c=await t(e).render(e,i),l=r.context.destination;!n(e)&&(r!==l||!n(r))&&c.connect(a,s,o)})).reduce((e,t)=>[...e,...t],[]))},xi=(e,t,n)=>async(r,i,a)=>{let o=t(r);await Promise.all(Array.from(o.activeInputs).map(async([t,r])=>{let o=await e(t).render(t,i);n(t)||o.connect(a,r)}))},Si=(e,t,n,r)=>i=>e(lr,()=>lr(i))?Promise.resolve(e(r,r)).then(e=>{if(!e){let e=n(i,512,0,1);i.oncomplete=()=>{e.onaudioprocess=null,e.disconnect()},e.onaudioprocess=()=>i.currentTime,e.connect(i.destination)}return i.startRendering()}):new Promise(e=>{let n=t(i,{channelCount:1,channelCountMode:`explicit`,channelInterpretation:`discrete`,gain:0});i.oncomplete=t=>{n.disconnect(),e(t.renderedBuffer)},n.connect(i.destination),i.startRendering()}),Ci=e=>(t,n)=>{e.set(t,n)},wi=e=>(t,n)=>e.set(t,n),Ti=(e,t,n,r,i,a,o,s)=>(c,l)=>n(c).render(c,l).then(()=>Promise.all(Array.from(r(l)).map(e=>n(e).render(e,l)))).then(()=>i(l)).then(n=>(typeof n.copyFromChannel==`function`?t(a,()=>a(n))||s(n):(o(n),De(n)),e.add(n),n)),Ei={channelCount:2,channelCountMode:`explicit`,channelInterpretation:`speakers`,pan:0},Di=(e,t,n,r,i,a)=>class extends e{constructor(e,o){let s=i(e),c=n(s,{...Ei,...o}),l=a(s),u=l?r():null;super(e,!1,c,u),this._pan=t(this,l,c.pan)}get pan(){return this._pan}},Oi=(e,t,n,r,i)=>()=>{let a=new WeakMap,o=async(o,s)=>{let c=n(o),l=Ce(c,s);return l||(c=t(s,{channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,pan:c.pan.value})),a.set(s,c),l?await e(s,o.pan,c.pan):await r(s,o.pan,c.pan),nt(c)?await i(o,s,c.inputs[0]):await i(o,s,c),c};return{render(e,t){let n=a.get(t);return n===void 0?o(e,t):Promise.resolve(n)}}},ki=e=>()=>{if(e===null)return!1;try{new e({length:1,sampleRate:44100})}catch{return!1}return!0},Ai=(e,t)=>async()=>{if(e===null)return!0;if(t===null)return!1;let n=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`}),r=new t(1,128,44100),i=URL.createObjectURL(n),a=!1,o=!1;try{await r.audioWorklet.addModule(i);let t=new e(r,`a`,{numberOfOutputs:0}),n=r.createOscillator();t.port.onmessage=()=>a=!0,t.onprocessorerror=()=>o=!0,n.connect(t),n.start(0),await r.startRendering(),await new Promise(e=>setTimeout(e))}catch{}finally{URL.revokeObjectURL(i)}return a&&!o},ji=(e,t)=>()=>{if(t===null)return Promise.resolve(!1);let n=new t(1,1,44100),r=e(n,{channelCount:1,channelCountMode:`explicit`,channelInterpretation:`discrete`,gain:0});return new Promise(e=>{n.oncomplete=()=>{r.disconnect(),e(n.currentTime!==0)},n.startRendering()})},Mi=()=>new DOMException(``,`UnknownError`),Ni={channelCount:2,channelCountMode:`max`,channelInterpretation:`speakers`,curve:null,oversample:`none`},Pi=(e,t,n,r,i,a,o)=>class extends e{constructor(e,t){let s=i(e),c=n(s,{...Ni,...t}),l=a(s)?r():null;super(e,!0,c,l),this._isCurveNullified=!1,this._nativeWaveShaperNode=c,o(this,1)}get curve(){return this._isCurveNullified?null:this._nativeWaveShaperNode.curve}set curve(e){if(e===null)this._isCurveNullified=!0,this._nativeWaveShaperNode.curve=new Float32Array([0,0]);else{if(e.length<2)throw t();this._isCurveNullified=!1,this._nativeWaveShaperNode.curve=e}}get oversample(){return this._nativeWaveShaperNode.oversample}set oversample(e){this._nativeWaveShaperNode.oversample=e}},Fi=(e,t,n)=>()=>{let r=new WeakMap,i=async(i,a)=>{let o=t(i);return Ce(o,a)||(o=e(a,{channelCount:o.channelCount,channelCountMode:o.channelCountMode,channelInterpretation:o.channelInterpretation,curve:o.curve,oversample:o.oversample})),r.set(a,o),nt(o)?await n(i,a,o.inputs[0]):await n(i,a,o),o};return{render(e,t){let n=r.get(t);return n===void 0?i(e,t):Promise.resolve(n)}}},Ii=()=>typeof window>`u`?null:window,Li=(e,t)=>n=>{n.copyFromChannel=(r,i,a=0)=>{let o=e(a),s=e(i);if(s>=n.numberOfChannels)throw t();let c=n.length,l=n.getChannelData(s),u=r.length;for(let e=o<0?-o:0;e+o{let o=e(a),s=e(i);if(s>=n.numberOfChannels)throw t();let c=n.length,l=n.getChannelData(s),u=r.length;for(let e=o<0?-o:0;e+ot=>{t.copyFromChannel=(n=>(r,i,a=0)=>{let o=e(a),s=e(i);if(o(r,i,a=0)=>{let o=e(a),s=e(i);if(o(t,n)=>{let r=n.createBuffer(1,1,44100);t.buffer===null&&(t.buffer=r),e(t,`buffer`,e=>()=>{let n=e.call(t);return n===r?null:n},e=>n=>e.call(t,n===null?r:n))},zi=(e,t)=>(n,r)=>{r.channelCount=1,r.channelCountMode=`explicit`,Object.defineProperty(r,"channelCount",{get:()=>1,set:()=>{throw e()}}),Object.defineProperty(r,"channelCountMode",{get:()=>`explicit`,set:()=>{throw e()}});let i=n.createBufferSource();t(r,()=>{let e=r.numberOfInputs;for(let t=0;ti.disconnect(r))},Bi=(e,t,n)=>e.copyFromChannel===void 0?e.getChannelData(n)[0]:(e.copyFromChannel(t,n),t[0]),Vi=e=>{if(e===null)return!1;let t=e.length;return t%2==0?e[t/2-1]+e[t/2]!==0:e[Math.floor(t/2)]!==0},Hi=(e,t,n,r)=>{let i=e;for(;!i.hasOwnProperty(t);)i=Object.getPrototypeOf(i);let{get:a,set:o}=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,{get:n(a),set:r(o)})},Ui=e=>({...e,outputChannelCount:e.outputChannelCount===void 0?e.numberOfInputs===1&&e.numberOfOutputs===1?[e.channelCount]:Array.from({length:e.numberOfOutputs},()=>1):e.outputChannelCount}),Wi=e=>({...e,channelCount:e.numberOfOutputs}),Gi=e=>{let{imag:t,real:n}=e;return t===void 0?n===void 0?{...e,imag:[0,0],real:[0,0]}:{...e,imag:Array.from(n,()=>0),real:n}:n===void 0?{...e,imag:t,real:Array.from(t,()=>0)}:{...e,imag:t,real:n}},Ki=(e,t,n)=>{try{e.setValueAtTime(t,n)}catch(r){if(r.code!==9)throw r;Ki(e,t,n+1e-7)}},qi=e=>{let t=e.createBufferSource();t.start();try{t.start()}catch{return!0}return!1},Ji=e=>{let t=e.createBufferSource();t.buffer=e.createBuffer(1,1,44100);try{t.start(0,1)}catch{return!1}return!0},Yi=e=>{let t=e.createBufferSource();t.start();try{t.stop()}catch{return!1}return!0},Xi=e=>{let t=e.createOscillator();try{t.start(-1)}catch(e){return e instanceof RangeError}return!1},Zi=e=>{let t=e.createBuffer(1,1,44100),n=e.createBufferSource();n.buffer=t,n.start(),n.stop();try{return n.stop(),!0}catch{return!1}},Qi=e=>{let t=e.createOscillator();try{t.stop(-1)}catch(e){return e instanceof RangeError}return!1},$i=e=>{let{port1:t,port2:n}=new MessageChannel;try{t.postMessage(e)}finally{t.close(),n.close()}},ea=e=>{e.start=(t=>(n=0,r=0,i)=>{let a=e.buffer,o=a===null?r:Math.min(a.duration,r);a!==null&&o>a.duration-.5/e.context.sampleRate?t.call(e,n,0,0):t.call(e,n,o,i)})(e.start)},ta=(e,t)=>{let n=t.createGain();e.connect(n);let r=(t=>()=>{t.call(e,n),e.removeEventListener(`ended`,r)})(e.disconnect);e.addEventListener(`ended`,r),Lr(e,n),e.stop=(t=>{let r=!1;return(i=0)=>{if(r)try{t.call(e,i)}catch{n.gain.setValueAtTime(0,i)}else t.call(e,i),r=!0}})(e.stop)},na=(e,t)=>n=>{let r={value:e};return Object.defineProperties(n,{currentTarget:r,target:r}),typeof t==`function`?t.call(e,n):t.handleEvent.call(e,n)},ra=w($e),ia=ve($e),aa=pn(ue),oa=new WeakMap,sa=Mn(oa),ca=Vt(new Map,new WeakMap),la=Ii(),ua=hr(ca,Ee),da=jn(He),fa=bi(He,da,dt),pa=we(ua,lt,fa),ma=In(re),ha=Qr(la),I=tr(ha),ga=new WeakMap,_a=wn(na),va=Sr(la),ya=Zn(va),ba=Qn(la),xa=$n(la),Sa=wr(la),Ca=Tt(T(O),_e(ra,ia,rt,aa,ct,He,sa,fe,lt,$e,Me,dt,ft),ca,Kn(ae,ct,He,lt,ut,Me),Ee,zn,ci,ln(rt,ae,He,lt,ut,ma,Me,I),gn(ga,He,P),_a,ma,ya,ba,xa,I,Sa),wa=Se(Ca,pa,Ee,ua,ma,I),Ta=new WeakSet,Ea=gr(la),Da=en(new Uint32Array(1)),Oa=Li(Da,Ee),ka=Ri(Da),Aa=ke(Ta,ca,ci,Ea,ha,ki(Ea),Oa,ka),ja=ye(Hr),Ma=xi(da,Ue,dt),Na=Jt(Ma),Pa=xr(ja,ca,qi,Ji,Yi,Xi,Zi,Qi,ea,F(Hi),ta),Fa=yi(Nn(Ue),Ma),Ia=Fe(Na,Pa,lt,Fa,fa),La=Et(E(te),ga,ne,Dt,S.createCancelAndHoldAutomationEvent,S.createCancelScheduledValuesAutomationEvent,S.createExponentialRampToValueAutomationEvent,S.createLinearRampToValueAutomationEvent,S.createSetTargetAutomationEvent,S.createSetValueAutomationEvent,S.createSetValueCurveAutomationEvent,va,Ki),Ra=Pe(Ca,Ia,La,Fn,Pa,ma,I,na),za=Je(Ca,Ye,Ee,Fn,Cr(Hr,Hi),ma,I,fa),Ba=Bt(Na,Mr,lt,Fa,fa),Va=wi(oa),Ha=zt(Ca,La,Ba,zn,Mr,ma,I,Va),Ua=ur($e,ba),Wa=Nr(va,zi(Fn,Ua)),Ga=Ut(Ca,Wt(Wa,lt,fa),Wa,ma,I),Ka=Kt(Ca,qt(Fr,lt,fa),Fr,ma,I,Wi),qa=Ir(ja,ca,Rr(ja,Pa,Hr,Ua),Xi,Qi),Ja=Qt(Ca,La,$t(Na,qa,lt,Fa,fa),qa,ma,I,na),Ya=zr(ci,Hi),Xa=nn(Ca,rn(Ya,lt,fa),Ya,ma,I,Va),Za=dn(Ca,La,fn(Na,Br,lt,Fa,fa),Br,ma,I,Va),Qa=Vr(ci),$a=bn(Ca,La,xn(Na,Qa,lt,Fa,fa),Qa,ci,ma,I,Va),eo=On(Ca,La,kn(Na,Hr,lt,Fa,fa),Hr,ma,I),to=qr(zn,Fn,ri,ci),no=Si(ca,Hr,ri,ji(Hr,ha)),ro=Gn(Pa,lt,ha,fa,no),io=Hn(Ca,Ur(to),ro,ma,I,Va),ao=Xe(La,Wa,qa,ri,ci,Bi,I,Hi),oo=new WeakMap,so=cr(za,ao,_a,I,oo,na),co=$r(ja,ca,Xi,Zi,Qi,ta),lo=fi(Ca,La,co,pi(Na,co,lt,Fa,fa),ma,I,na),uo=Xt(Pa),fo=oi(uo,Fn,si(uo,Fn,Hr,Vi,Ua),Vi,Ua,va,Hi),po=ei(ti(rt,Fn,Wa,Hr,ri,fo,ci,ct,Bi,Ua)),mo=hi(Ca,La,po,gi(Na,Wa,qa,Hr,po,lt,ha,Fa,fa,no),ma,I,Va),ho=vi(ni(Ee),ma,new WeakSet,Gi),go=ii(ai(Wa,Fr,Hr,fo,ci,Ua),ci),L=Di(Ca,La,go,Oi(Na,go,lt,Fa,fa),ma,I),_o=Pi(Ca,Fn,fo,Fi(fo,lt,fa),ma,I,Va),vo=nr(la),yo=Tn(la),bo=new WeakMap,xo=Ln(bo,ha),So=vo?N(ca,ci,Cn(la),yo,En(C),ma,xo,I,Sa,new WeakMap,new WeakMap,Ai(Sa,ha),la):void 0,Co=er(ya,I),wo=Lt(So,wa,Aa,Ra,Ha,Ga,Ka,Ja,Xa,cn(Ta,ca,on,Sn,new WeakSet,ma,Co,Te,lr,Oa,ka),Za,$a,eo,io,so,lo,mo,ho,L,_o),To=qe(wo,Fn,ci,Mi,rr(Ca,Jr,ma,I),ar(Ca,Yr,ma,I),or(Ca,Xr,ma,I),sr(Ca,Zr(Fn,I),ma),va),Eo=Rn(oo),Do=be(Eo),Oo=Yt(Ee),ko=mn(Eo),Ao=vn(Ee),jo=new WeakMap,Mo=Er(Fn,jr(Oo,Ee,Fn,Wa,Fr,qa,Hr,ri,ci,Ao,yo,An(jo,P),Ua),Hr,ci,Ua),No=It(Na,Oo,Pa,Wa,Fr,qa,Hr,ko,Ao,yo,lt,Sa,ha,Fa,fa,no),Po=Pn(bo),Fo=Ci(jo),Io=vo?At(Do,Ca,La,No,Mo,He,Po,ma,I,Sa,Ui,Fo,$i,na):void 0,Lo=ui(wo,ca,Fn,an(ci,ha),Ti(Ta,ca,da,Eo,no,Te,Oa,ka)),Ro=qn(re,ya),zo=Jn(ee,ba),Bo=Yn(ne,xa),Vo=Xn(re,I);function Ho(e){return e===void 0}function R(e){return e!==void 0}function Uo(e){return typeof e==`function`}function Wo(e){return typeof e==`number`}function Go(e){return Object.prototype.toString.call(e)===`[object Object]`&&e.constructor===Object}function Ko(e){return typeof e==`boolean`}function qo(e){return Array.isArray(e)}function Jo(e){return typeof e==`string`}function Yo(e){return Jo(e)&&/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i.test(e)}function z(e,t){if(!e)throw Error(t)}function Xo(e,t,n=1/0){if(!(t<=e&&e<=n))throw RangeError(`Value must be within [${t}, ${n}], got: ${e}`)}function Zo(e){!e.isOffline&&e.state!==`running`&&is(`The AudioContext is "suspended". Invoke Tone.start() from a user action to start the audio.`)}var Qo=!1,$o=!1;function es(e){Qo=e}function ts(e){Ho(e)&&Qo&&!$o&&($o=!0,is(`Events scheduled inside of scheduled callbacks should use the passed in scheduling time. See https://github.com/Tonejs/Tone.js/wiki/Accurate-Timing`))}var ns=console;function rs(...e){ns.log(...e)}function is(...e){ns.warn(...e)}function as(e){return new To(e)}function os(e,t,n){return new Lo(e,t,n)}var ss=typeof self==`object`?self:null,cs=ss&&(ss.hasOwnProperty(`AudioContext`)||ss.hasOwnProperty(`webkitAudioContext`));function ls(e,t,n){return z(R(Io),`AudioWorkletNode only works in a secure context (https or localhost)`),new(e instanceof ss?.BaseAudioContext?ss?.AudioWorkletNode:Io)(e,t,n)}function us(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function ds(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}var fs=class{constructor(e,t,n,r){this._callback=e,this._type=t,this._minimumUpdateInterval=Math.max(128/(r||44100),.001),this.updateInterval=n,this._createClock()}_createWorker(){let e=new Blob([` + // the initial timeout time + let timeoutTime = ${(this._updateInterval*1e3).toFixed(1)}; + // onmessage callback + self.onmessage = function(msg){ + timeoutTime = parseInt(msg.data); + }; + // the tick function which posts a message + // and schedules a new tick + function tick(){ + setTimeout(tick, timeoutTime); + self.postMessage('tick'); + } + // call tick initially + tick(); + `],{type:`text/javascript`}),t=URL.createObjectURL(e),n=new Worker(t);n.onmessage=this._callback.bind(this),this._worker=n}_createTimeout(){this._timeout=setTimeout(()=>{this._createTimeout(),this._callback()},this._updateInterval*1e3)}_createClock(){if(this._type===`worker`)try{this._createWorker()}catch{this._type=`timeout`,this._createClock()}else this._type===`timeout`&&this._createTimeout()}_disposeClock(){this._timeout&&clearTimeout(this._timeout),this._worker&&(this._worker.terminate(),this._worker.onmessage=null)}get updateInterval(){return this._updateInterval}set updateInterval(e){var t;this._updateInterval=Math.max(e,this._minimumUpdateInterval),this._type===`worker`&&((t=this._worker)==null||t.postMessage(this._updateInterval*1e3))}get type(){return this._type}set type(e){this._disposeClock(),this._type=e,this._createClock()}dispose(){this._disposeClock()}};function ps(e){return Bo(e)}function ms(e){return zo(e)}function hs(e){return Vo(e)}function gs(e){return Ro(e)}function _s(e){return e instanceof Aa}function vs(e,t){return e===`value`||ps(t)||ms(t)||_s(t)}function ys(e,...t){if(!t.length)return e;let n=t.shift();if(Go(e)&&Go(n))for(let t in n)vs(t,n[t])?e[t]=n[t]:Go(n[t])?(e[t]||Object.assign(e,{[t]:{}}),ys(e[t],n[t])):Object.assign(e,{[t]:n[t]});return ys(e,...t)}function bs(e,t){return e.length===t.length&&e.every((e,n)=>t[n]===e)}function B(e,t,n=[],r){let i={},a=Array.from(t);if(Go(a[0])&&r&&!Reflect.has(a[0],r)&&(Object.keys(a[0]).some(t=>Reflect.has(e,t))||(ys(i,{[r]:a[0]}),n.splice(n.indexOf(r),1),a.shift())),a.length===1&&Go(a[0]))ys(i,a[0]);else for(let e=0;e{Reflect.has(e,t)&&delete e[t]}),e}var ws=class{constructor(){this.debug=!1,this._wasDisposed=!1}static getDefaults(){return{}}log(...e){(this.debug||ss&&this.toString()===ss.TONE_DEBUG_CLASS)&&rs(this,...e)}dispose(){return this._wasDisposed=!0,this}get disposed(){return this._wasDisposed}toString(){return this.name}};ws.version=u;var Ts=1e-6;function Es(e,t){return e>t+Ts}function Ds(e,t){return Es(e,t)||ks(e,t)}function Os(e,t){return e+Tsthis.memory){let e=this.length-this.memory;this._timeline.splice(0,e)}return this}remove(e){let t=this._timeline.indexOf(e);return t!==-1&&this._timeline.splice(t,1),this}get(e,t=`time`){let n=this._search(e,t);return n===-1?null:this._timeline[n]}peek(){return this._timeline[0]}shift(){return this._timeline.shift()}getAfter(e,t=`time`){let n=this._search(e,t);return n+10&&this._timeline[t-1].time=0?this._timeline[n-1]:null}cancel(e){if(this._timeline.length>1){let t=this._search(e);if(t>=0)if(ks(this._timeline[t].time,e)){for(let n=t;n>=0&&ks(this._timeline[n].time,e);n--)t=n;this._timeline=this._timeline.slice(0,t)}else this._timeline=this._timeline.slice(0,t+1);else this._timeline=[]}else this._timeline.length===1&&Ds(this._timeline[0].time,e)&&(this._timeline=[]);return this}cancelBefore(e){let t=this._search(e);return t>=0&&(this._timeline=this._timeline.slice(t+1)),this}previousEvent(e){let t=this._timeline.indexOf(e);return t>0?this._timeline[t-1]:null}_search(e,t=`time`){if(this._timeline.length===0)return-1;let n=0,r=this._timeline.length,i=r;if(r>0&&this._timeline[r-1][t]<=e)return r-1;for(;n=0&&this._timeline[n].time>=e;)n--;return this._iterate(t,n+1),this}forEachAtTime(e,t){let n=this._search(e);if(n!==-1&&ks(this._timeline[n].time,e)){let r=n;for(let t=n;t>=0&&ks(this._timeline[t].time,e);t--)r=t;this._iterate(e=>{t(e)},r,n)}return this}dispose(){return super.dispose(),this._timeline=[],this}},Ms=[];function Ns(e){Ms.push(e)}function Ps(e){Ms.forEach(t=>t(e))}var Fs=[];function Is(e){Fs.push(e)}function Ls(e){Fs.forEach(t=>t(e))}var Rs=class e extends ws{constructor(){super(...arguments),this.name=`Emitter`}on(e,t){return e.split(/\W+/).forEach(e=>{Ho(this._events)&&(this._events={}),this._events.hasOwnProperty(e)||(this._events[e]=[]),this._events[e].push(t)}),this}once(e,t){let n=(...r)=>{t(...r),this.off(e,n)};return this.on(e,n),this}off(e,t){return e.split(/\W+/).forEach(e=>{if(Ho(this._events)&&(this._events={}),this._events.hasOwnProperty(e))if(Ho(t))this._events[e]=[];else{let n=this._events[e];for(let e=n.length-1;e>=0;e--)n[e]===t&&n.splice(e,1)}}),this}emit(e,...t){if(this._events&&this._events.hasOwnProperty(e)){let n=this._events[e].slice(0);for(let e=0,r=n.length;e{let r=Object.getOwnPropertyDescriptor(e.prototype,n);Object.defineProperty(t.prototype,n,r)})}dispose(){return super.dispose(),this._events=void 0,this}},zs=class extends Rs{constructor(){super(...arguments),this.isOffline=!1}toJSON(){return{}}},Bs=class e extends zs{constructor(){super(),this.name=`Context`,this._constants=new Map,this._timeouts=new js,this._timeoutIds=0,this._initialized=!1,this._closeStarted=!1,this.isOffline=!1,this._workletPromise=null;let t=B(e.getDefaults(),arguments,[`context`]);t.context?(this._context=t.context,this._latencyHint=arguments[0]?.latencyHint||``):(this._context=as({latencyHint:t.latencyHint}),this._latencyHint=t.latencyHint),this._ticker=new fs(this.emit.bind(this,`tick`),t.clockSource,t.updateInterval,this._context.sampleRate),this.on(`tick`,this._timeoutLoop.bind(this)),this._context.onstatechange=()=>{this.emit(`statechange`,this.state)},this[arguments[0]?.hasOwnProperty(`updateInterval`)?`_lookAhead`:`lookAhead`]=t.lookAhead}static getDefaults(){return{clockSource:`worker`,latencyHint:`interactive`,lookAhead:.1,updateInterval:.05}}initialize(){return this._initialized||=(Ps(this),!0),this}createAnalyser(){return this._context.createAnalyser()}createOscillator(){return this._context.createOscillator()}createBufferSource(){return this._context.createBufferSource()}createBiquadFilter(){return this._context.createBiquadFilter()}createBuffer(e,t,n){return this._context.createBuffer(e,t,n)}createChannelMerger(e){return this._context.createChannelMerger(e)}createChannelSplitter(e){return this._context.createChannelSplitter(e)}createConstantSource(){return this._context.createConstantSource()}createConvolver(){return this._context.createConvolver()}createDelay(e){return this._context.createDelay(e)}createDynamicsCompressor(){return this._context.createDynamicsCompressor()}createGain(){return this._context.createGain()}createIIRFilter(e,t){return this._context.createIIRFilter(e,t)}createPanner(){return this._context.createPanner()}createPeriodicWave(e,t,n){return this._context.createPeriodicWave(e,t,n)}createStereoPanner(){return this._context.createStereoPanner()}createWaveShaper(){return this._context.createWaveShaper()}createMediaStreamSource(e){return z(gs(this._context),`Not available if OfflineAudioContext`),this._context.createMediaStreamSource(e)}createMediaElementSource(e){return z(gs(this._context),`Not available if OfflineAudioContext`),this._context.createMediaElementSource(e)}createMediaStreamDestination(){return z(gs(this._context),`Not available if OfflineAudioContext`),this._context.createMediaStreamDestination()}decodeAudioData(e){return this._context.decodeAudioData(e)}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(e){z(!this._initialized,`The listener cannot be set after initialization.`),this._listener=e}get transport(){return this.initialize(),this._transport}set transport(e){z(!this._initialized,`The transport cannot be set after initialization.`),this._transport=e}get draw(){return this.initialize(),this._draw}set draw(e){z(!this._initialized,`Draw cannot be set after initialization.`),this._draw=e}get destination(){return this.initialize(),this._destination}set destination(e){z(!this._initialized,`The destination cannot be set after initialization.`),this._destination=e}createAudioWorkletNode(e,t){return ls(this.rawContext,e,t)}addAudioWorkletModule(e){return ds(this,void 0,void 0,function*(){z(R(this.rawContext.audioWorklet),`AudioWorkletNode is only available in a secure context (https or localhost)`),this._workletPromise||=this.rawContext.audioWorklet.addModule(e),yield this._workletPromise})}workletsAreReady(){return ds(this,void 0,void 0,function*(){(yield this._workletPromise)?this._workletPromise:Promise.resolve()})}get updateInterval(){return this._ticker.updateInterval}set updateInterval(e){this._ticker.updateInterval=e}get clockSource(){return this._ticker.type}set clockSource(e){this._ticker.type=e}get lookAhead(){return this._lookAhead}set lookAhead(e){this._lookAhead=e,this.updateInterval=e?e/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 gs(this._context)?this._context.resume():Promise.resolve()}close(){return ds(this,void 0,void 0,function*(){gs(this._context)&&this.state!==`closed`&&!this._closeStarted&&(this._closeStarted=!0,yield this._context.close()),this._initialized&&Ls(this)})}getConstant(e){if(this._constants.has(e))return this._constants.get(e);{let t=this._context.createBuffer(1,128,this._context.sampleRate),n=t.getChannelData(0);for(let t=0;tthis._constants[e].disconnect()),this.close(),this}_timeoutLoop(){let e=this.now();this._timeouts.forEachBefore(e,e=>{e.callback(),this._timeouts.remove(e)})}setTimeout(e,t){this._timeoutIds++;let n=this.now();return this._timeouts.add({callback:e,id:this._timeoutIds,time:n+t}),this._timeoutIds}clearTimeout(e){return this._timeouts.forEach(t=>{t.id===e&&this._timeouts.remove(t)}),this}clearInterval(e){return this.clearTimeout(e)}setInterval(e,t){let n=++this._timeoutIds,r=()=>{let i=this.now();this._timeouts.add({callback:()=>{e(),r()},id:n,time:i+t})};return r(),n}},Vs=class extends zs{constructor(){super(...arguments),this.lookAhead=0,this.latencyHint=0,this.isOffline=!1}createAnalyser(){return{}}createOscillator(){return{}}createBufferSource(){return{}}createBiquadFilter(){return{}}createBuffer(e,t,n){return{}}createChannelMerger(e){return{}}createChannelSplitter(e){return{}}createConstantSource(){return{}}createConvolver(){return{}}createDelay(e){return{}}createDynamicsCompressor(){return{}}createGain(){return{}}createIIRFilter(e,t){return{}}createPanner(){return{}}createPeriodicWave(e,t,n){return{}}createStereoPanner(){return{}}createWaveShaper(){return{}}createMediaStreamSource(e){return{}}createMediaElementSource(e){return{}}createMediaStreamDestination(){return{}}decodeAudioData(e){return Promise.resolve({})}createAudioWorkletNode(e,t){return{}}get rawContext(){return{}}addAudioWorkletModule(e){return ds(this,void 0,void 0,function*(){return Promise.resolve()})}resume(){return Promise.resolve()}setTimeout(e,t){return 0}clearTimeout(e){return this}setInterval(e,t){return 0}clearInterval(e){return this}getConstant(e){return{}}get currentTime(){return 0}get state(){return{}}get sampleRate(){return 0}get listener(){return{}}get transport(){return{}}get draw(){return{}}set draw(e){}get destination(){return{}}set destination(e){}now(){return 0}immediate(){return 0}};function Hs(e,t){qo(t)?t.forEach(t=>Hs(e,t)):Object.defineProperty(e,t,{enumerable:!0,writable:!1})}function Us(e,t){qo(t)?t.forEach(t=>Us(e,t)):Object.defineProperty(e,t,{writable:!0})}var Ws=()=>{},Gs=class e extends ws{constructor(){super(),this.name=`ToneAudioBuffer`,this.onload=Ws;let t=B(e.getDefaults(),arguments,[`url`,`onload`,`onerror`]);this.reverse=t.reverse,this.onload=t.onload,Jo(t.url)?this.load(t.url).catch(t.onerror):t.url&&this.set(t.url)}static getDefaults(){return{onerror:Ws,onload:Ws,reverse:!1}}get sampleRate(){return this._buffer?this._buffer.sampleRate:Ys().sampleRate}set(t){return t instanceof e?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(t){return ds(this,void 0,void 0,function*(){let n=e.load(t).then(e=>{this.set(e),this.onload(this)});e.downloads.push(n);try{yield n}finally{let t=e.downloads.indexOf(n);e.downloads.splice(t,1)}return this})}dispose(){return super.dispose(),this._buffer=void 0,this}fromArray(e){let t=qo(e)&&e[0].length>0,n=t?e.length:1,r=t?e[0].length:e.length,i=Ys(),a=i.createBuffer(n,r,i.sampleRate),o=!t&&n===1?[e]:e;for(let e=0;ee/t),this.fromArray(e)}return this}toArray(e){if(Wo(e))return this.getChannelData(e);if(this.numberOfChannels===1)return this.toArray(0);{let e=[];for(let t=0;t0}get duration(){return this._buffer?this._buffer.duration:0}get length(){return this._buffer?this._buffer.length:0}get numberOfChannels(){return this._buffer?this._buffer.numberOfChannels:0}get reverse(){return this._reversed}set reverse(e){this._reversed!==e&&(this._reversed=e,this._reverse())}static fromArray(t){return new e().fromArray(t)}static fromUrl(t){return ds(this,void 0,void 0,function*(){return yield new e().load(t)})}static load(t){return ds(this,void 0,void 0,function*(){let n=e.baseUrl===``||e.baseUrl.endsWith(`/`)?e.baseUrl:e.baseUrl+`/`,r=yield fetch(n+t);if(!r.ok)throw Error(`could not load url: ${t}`);let i=yield r.arrayBuffer();return yield Ys().decodeAudioData(i)})}static supportsType(e){let t=e.split(`.`),n=t[t.length-1];return document.createElement(`audio`).canPlayType(`audio/`+n)!==``}static loaded(){return ds(this,void 0,void 0,function*(){for(yield Promise.resolve();e.downloads.length;)yield e.downloads[0]})}};Gs.baseUrl=``,Gs.downloads=[];var Ks=class extends Bs{constructor(){super({clockSource:`offline`,context:hs(arguments[0])?arguments[0]:os(arguments[0],arguments[1]*arguments[2],arguments[2]),lookAhead:0,updateInterval:hs(arguments[0])?128/arguments[0].sampleRate:128/arguments[2]}),this.name=`OfflineContext`,this._currentTime=0,this.isOffline=!0,this._duration=hs(arguments[0])?arguments[0].length/arguments[0].sampleRate:arguments[1]}now(){return this._currentTime}get currentTime(){return this._currentTime}_renderClock(e){return ds(this,void 0,void 0,function*(){let t=0;for(;this._duration-this._currentTime>=0;){this.emit(`tick`),this._currentTime+=128/this.sampleRate,t++;let n=Math.floor(this.sampleRate/128);e&&t%n===0&&(yield new Promise(e=>setTimeout(e,1)))}})}render(){return ds(this,arguments,void 0,function*(e=!0){return yield this.workletsAreReady(),yield this._renderClock(e),new Gs(yield this._context.startRendering())})}close(){return Promise.resolve()}},qs=new Vs,Js=qs;function Ys(){return Js===qs&&cs&&Xs(new Bs),Js}function Xs(e,t=!1){t&&Js.dispose(),Js=gs(e)?new Bs(e):hs(e)?new Ks(e):e}function Zs(){return Js.resume()}if(ss&&!ss.TONE_SILENCE_LOGGING){let e=` * Tone.js v${u} * `;console.log(`%c${e}`,`background: #000; color: #fff`)}function Qs(e){return 10**(e/20)}function $s(e){return Math.log(e)/Math.LN10*20}function ec(e){return 2**(e/12)}var tc=440;function nc(){return tc}function rc(e){tc=e}function ic(e){return Math.round(ac(e))}function ac(e){return 69+12*Math.log2(e/tc)}function oc(e){return tc*2**((e-69)/12)}var sc=class e extends ws{constructor(e,t,n){super(),this.defaultUnits=`s`,this._val=t,this._units=n,this.context=e,this._expressions=this._getExpressions()}_getExpressions(){return{hz:{method:e=>this._frequencyToUnits(parseFloat(e)),regexp:/^(\d+(?:\.\d+)?)hz$/i},i:{method:e=>this._ticksToUnits(parseInt(e,10)),regexp:/^(\d+)i$/i},m:{method:e=>this._beatsToUnits(parseInt(e,10)*this._getTimeSignature()),regexp:/^(\d+)m$/i},n:{method:(e,t)=>{let n=parseInt(e,10),r=t===`.`?1.5:1;return n===1?this._beatsToUnits(this._getTimeSignature())*r:this._beatsToUnits(4/n)*r},regexp:/^(\d+)n(\.?)$/i},number:{method:e=>this._expressions[this.defaultUnits].method.call(this,e),regexp:/^(\d+(?:\.\d+)?)$/},s:{method:e=>this._secondsToUnits(parseFloat(e)),regexp:/^(\d+(?:\.\d+)?)s$/},samples:{method:e=>parseInt(e,10)/this.context.sampleRate,regexp:/^(\d+)samples$/},t:{method:e=>{let t=parseInt(e,10);return this._beatsToUnits(8/(Math.floor(t)*3))},regexp:/^(\d+)t$/i},tr:{method:(e,t,n)=>{let r=0;return e&&e!==`0`&&(r+=this._beatsToUnits(this._getTimeSignature()*parseFloat(e))),t&&t!==`0`&&(r+=this._beatsToUnits(parseFloat(t))),n&&n!==`0`&&(r+=this._beatsToUnits(parseFloat(n)/4)),r},regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?$/}}}valueOf(){if(this._val instanceof e&&this.fromType(this._val),Ho(this._val))return this._noArg();if(Jo(this._val)&&Ho(this._units)){for(let e in this._expressions)if(this._expressions[e].regexp.test(this._val.trim())){this._units=e;break}}else if(Go(this._val)){let e=0;for(let t in this._val)if(R(this._val[t])){let n=this._val[t],r=new this.constructor(this.context,t).valueOf()*n;e+=r}return e}if(R(this._units)){let e=this._expressions[this._units],t=this._val.toString().trim().match(e.regexp);return t?e.method.apply(this,t.slice(1)):e.method.call(this,this._val)}else if(Jo(this._val))return parseFloat(this._val);else return this._val}_frequencyToUnits(e){return 1/e}_beatsToUnits(e){return 60/this._getBpm()*e}_secondsToUnits(e){return e}_ticksToUnits(e){return e*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(e){switch(this._units=void 0,this.defaultUnits){case`s`:this._val=e.toSeconds();break;case`i`:this._val=e.toTicks();break;case`hz`:this._val=e.toFrequency();break;case`midi`:this._val=e.toMidi();break}return this}toFrequency(){return 1/this.toSeconds()}toSamples(){return this.toSeconds()*this.context.sampleRate}toMilliseconds(){return this.toSeconds()*1e3}},cc=class e extends sc{constructor(){super(...arguments),this.name=`TimeClass`}_getExpressions(){return Object.assign(super._getExpressions(),{now:{method:e=>this._now()+new this.constructor(this.context,e).valueOf(),regexp:/^\+(.+)/},quantize:{method:t=>{let n=new e(this.context,t).valueOf();return this._secondsToUnits(this.context.transport.nextSubdivision(n))},regexp:/^@(.+)/}})}quantize(e,t=1){let n=new this.constructor(this.context,e).valueOf(),r=this.valueOf();return r+(Math.round(r/n)*n-r)*t}toNotation(){let t=this.toSeconds(),n=[`1m`];for(let e=1;e<9;e++){let t=2**e;n.push(t+`n.`),n.push(t+`n`),n.push(t+`t`)}n.push(`0`);let r=n[0],i=new e(this.context,n[0]).toSeconds();return n.forEach(n=>{let a=new e(this.context,n).toSeconds();Math.abs(a-t)3&&(r=parseFloat(parseFloat(i).toFixed(3))),[n,t,r].join(`:`)}toTicks(){let e=this._beatsToUnits(1);return this.valueOf()/e*this._getPPQ()}toSeconds(){return this.valueOf()}toMidi(){return ic(this.toFrequency())}_now(){return this.context.now()}},lc=class e extends cc{constructor(){super(...arguments),this.name=`Frequency`,this.defaultUnits=`hz`}static get A4(){return nc()}static set A4(e){rc(e)}_getExpressions(){return Object.assign({},super._getExpressions(),{midi:{regexp:/^(\d+(?:\.\d+)?midi)/,method(t){return this.defaultUnits===`midi`?t:e.mtof(t)}},note:{regexp:/^([a-g]{1}(?:b|#|##|x|bb|###|#x|x#|bbb)?)(-?[0-9]+)/i,method(t,n){let r=uc[t.toLowerCase()]+(parseInt(n,10)+1)*12;return this.defaultUnits===`midi`?r:e.mtof(r)}},tr:{regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method(e,t,n){let r=1;return e&&e!==`0`&&(r*=this._beatsToUnits(this._getTimeSignature()*parseFloat(e))),t&&t!==`0`&&(r*=this._beatsToUnits(parseFloat(t))),n&&n!==`0`&&(r*=this._beatsToUnits(parseFloat(n)/4)),r}}})}transpose(t){return new e(this.context,this.valueOf()*ec(t))}harmonize(e){return e.map(e=>this.transpose(e))}toMidi(){return ic(this.valueOf())}toNote(){let t=this.toFrequency(),n=Math.log2(t/e.A4),r=Math.round(12*n)+57,i=Math.floor(r/12);return i<0&&(r+=-12*i),dc[r%12]+i.toString()}toSeconds(){return 1/super.toSeconds()}toTicks(){let e=this._beatsToUnits(1),t=this.valueOf()/e;return Math.floor(t*this._getPPQ())}_noArg(){return 0}_frequencyToUnits(e){return e}_ticksToUnits(e){return 1/(e*60/(this._getBpm()*this._getPPQ()))}_beatsToUnits(e){return 1/super._beatsToUnits(e)}_secondsToUnits(e){return 1/e}static mtof(e){return oc(e)}static ftom(e){return ic(e)}},uc={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},dc=[`C`,`C#`,`D`,`D#`,`E`,`F`,`F#`,`G`,`G#`,`A`,`A#`,`B`];function fc(e,t){return new lc(Ys(),e,t)}var pc=class extends cc{constructor(){super(...arguments),this.name=`TransportTime`}_now(){return this.context.transport.seconds}},mc=class e extends ws{constructor(){super();let t=B(e.getDefaults(),arguments,[`context`]);this.defaultContext?this.context=this.defaultContext:this.context=t.context}static getDefaults(){return{context:Ys()}}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(e){return ts(e),new cc(this.context,e).toSeconds()}toFrequency(e){return new lc(this.context,e).toFrequency()}toTicks(e){return new pc(this.context,e).toTicks()}_getPartialProperties(e){let t=this.get();return Object.keys(t).forEach(n=>{Ho(e[n])&&delete t[n]}),t}get(){let t=xs(this);return Object.keys(t).forEach(n=>{if(Reflect.has(this,n)){let r=this[n];R(r)&&R(r.value)&&R(r.setValueAtTime)?t[n]=r.value:r instanceof e?t[n]=r._getPartialProperties(t[n]):qo(r)||Wo(r)||Jo(r)||Ko(r)?t[n]=r:delete t[n]}}),t}set(t){return Object.keys(t).forEach(n=>{Reflect.has(this,n)&&R(this[n])&&(this[n]&&R(this[n].value)&&R(this[n].setValueAtTime)?this[n].value!==t[n]&&(this[n].value=t[n]):this[n]instanceof e?this[n].set(t[n]):this[n]=t[n])}),this}},hc=class extends js{constructor(e=`stopped`){super(),this.name=`StateTimeline`,this._initial=e,this.setStateAtTime(this._initial,0)}getValueAtTime(e){let t=this.get(e);return t===null?this._initial:t.state}setStateAtTime(e,t,n){return Xo(t,0),this.add(Object.assign({},n,{state:e,time:t})),this}getLastState(e,t){let n=this._search(t);for(let t=n;t>=0;t--){let n=this._timeline[t];if(n.state===e)return n}}getNextState(e,t){let n=this._search(t);if(n!==-1)for(let t=n;t0,`timeConstant must be a number greater than 0`);let i=this.toSeconds(t);return this._assertRange(r),z(isFinite(r)&&isFinite(i),`Invalid argument(s) to setTargetAtTime: ${JSON.stringify(e)}, ${JSON.stringify(t)}`),this._events.add({constant:n,time:i,type:`setTargetAtTime`,value:r}),this.log(this.units,`setTargetAtTime`,e,i,n),this._param.setTargetAtTime(r,i,n),this}setValueCurveAtTime(e,t,n,r=1){n=this.toSeconds(n),t=this.toSeconds(t);let i=this._fromType(e[0])*r;this.setValueAtTime(this._toType(i),t);let a=n/(e.length-1);for(let n=1;n{t.type===`cancelScheduledValues`?e.cancelScheduledValues(t.time):t.type===`setTargetAtTime`?e.setTargetAtTime(t.value,t.time,t.constant):e[t.type](t.value,t.time)}),this}setParam(e){z(this._swappable,`The Param must be assigned as 'swappable' in the constructor`);let t=this.input;return t.disconnect(this._param),this.apply(e),this._param=e,t.connect(this._param),this}dispose(){return super.dispose(),this._events.dispose(),this}get defaultValue(){return this._toType(this._param.defaultValue)}_exponentialApproach(e,t,n,r,i){return n+(t-n)*Math.exp(-(i-e)/r)}_linearInterpolate(e,t,n,r,i){return t+(r-t)*((i-e)/(n-e))}_exponentialInterpolate(e,t,n,r,i){return t*(r/t)**+((i-e)/(n-e))}},V=class e extends mc{constructor(){super(...arguments),this._internalChannels=[]}get numberOfInputs(){return R(this.input)?ps(this.input)||this.input instanceof gc?1:this.input.numberOfInputs:0}get numberOfOutputs(){return R(this.output)?this.output.numberOfOutputs:0}_isAudioNode(t){return R(t)&&(t instanceof e||ms(t))}_getInternalNodes(){let e=this._internalChannels.slice(0);return this._isAudioNode(this.input)&&e.push(this.input),this._isAudioNode(this.output)&&this.input!==this.output&&e.push(this.output),e}_setChannelProperties(e){this._getInternalNodes().forEach(t=>{t.channelCount=e.channelCount,t.channelCountMode=e.channelCountMode,t.channelInterpretation=e.channelInterpretation})}_getChannelProperties(){let e=this._getInternalNodes();z(e.length>0,`ToneAudioNode does not have any internal nodes`);let t=e[0];return{channelCount:t.channelCount,channelCountMode:t.channelCountMode,channelInterpretation:t.channelInterpretation}}get channelCount(){return this._getChannelProperties().channelCount}set channelCount(e){let t=this._getChannelProperties();this._setChannelProperties(Object.assign(t,{channelCount:e}))}get channelCountMode(){return this._getChannelProperties().channelCountMode}set channelCountMode(e){let t=this._getChannelProperties();this._setChannelProperties(Object.assign(t,{channelCountMode:e}))}get channelInterpretation(){return this._getChannelProperties().channelInterpretation}set channelInterpretation(e){let t=this._getChannelProperties();this._setChannelProperties(Object.assign(t,{channelInterpretation:e}))}connect(e,t=0,n=0){return vc(this,e,t,n),this}toDestination(){return this.connect(this.context.destination),this}toMaster(){return is(`toMaster() has been renamed toDestination()`),this.toDestination()}disconnect(e,t=0,n=0){return yc(this,e,t,n),this}chain(...e){return _c(this,...e),this}fan(...e){return e.forEach(e=>this.connect(e)),this}dispose(){return super.dispose(),R(this.input)&&(this.input instanceof e?this.input.dispose():ms(this.input)&&this.input.disconnect()),R(this.output)&&(this.output instanceof e?this.output.dispose():ms(this.output)&&this.output.disconnect()),this._internalChannels=[],this}};function _c(...e){let t=e.shift();e.reduce((e,t)=>(e instanceof V?e.connect(t):ms(e)&&vc(e,t),t),t)}function vc(e,t,n=0,r=0){for(z(R(e),`Cannot connect from undefined node`),z(R(t),`Cannot connect to undefined node`),(t instanceof V||ms(t))&&z(t.numberOfInputs>0,`Cannot connect to node with no inputs`),z(e.numberOfOutputs>0,`Cannot connect from node with no outputs`);t instanceof V||t instanceof gc;)R(t.input)&&(t=t.input);for(;e instanceof V;)R(e.output)&&(e=e.output);ps(t)?e.connect(t,n):e.connect(t,n,r)}function yc(e,t,n=0,r=0){if(R(t))for(;t instanceof V;)t=t.input;for(;!ms(e);)R(e.output)&&(e=e.output);ps(t)?e.disconnect(t,n):ms(t)?e.disconnect(t,n,r):e.disconnect()}var bc=class e extends V{constructor(){let t=B(e.getDefaults(),arguments,[`gain`,`units`]);super(t),this.name=`Gain`,this._gainNode=this.context.createGain(),this.input=this._gainNode,this.output=this._gainNode,this.gain=new gc({context:this.context,convert:t.convert,param:this._gainNode.gain,units:t.units,value:t.gain,minValue:t.minValue,maxValue:t.maxValue}),Hs(this,`gain`)}static getDefaults(){return Object.assign(V.getDefaults(),{convert:!0,gain:1,units:`gain`})}dispose(){return super.dispose(),this._gainNode.disconnect(),this.gain.dispose(),this}},xc=class extends V{constructor(e){super(e),this.onended=Ws,this._startTime=-1,this._stopTime=-1,this._timeout=-1,this.output=new bc({context:this.context,gain:0}),this._gainNode=this.output,this.getStateAtTime=function(e){let t=this.toSeconds(e);return this._startTime!==-1&&t>=this._startTime&&(this._stopTime===-1||t<=this._stopTime)?`started`:`stopped`},this._fadeIn=e.fadeIn,this._fadeOut=e.fadeOut,this._curve=e.curve,this.onended=e.onended}static getDefaults(){return Object.assign(V.getDefaults(),{curve:`linear`,fadeIn:0,fadeOut:0,onended:Ws})}_startGain(e,t=1){z(this._startTime===-1,`Source cannot be started more than once`);let n=this.toSeconds(this._fadeIn);return this._startTime=e+n,this._startTime=Math.max(this._startTime,this.context.currentTime),n>0?(this._gainNode.gain.setValueAtTime(0,e),this._curve===`linear`?this._gainNode.gain.linearRampToValueAtTime(t,e+n):this._gainNode.gain.exponentialApproachValueAtTime(t,e,n)):this._gainNode.gain.setValueAtTime(t,e),this}stop(e){return this.log(`stop`,e),this._stopGain(this.toSeconds(e)),this}_stopGain(e){z(this._startTime!==-1,`'start' must be called before 'stop'`),this.cancelStop();let t=this.toSeconds(this._fadeOut);return this._stopTime=this.toSeconds(e)+t,this._stopTime=Math.max(this._stopTime,this.now()),t>0?this._curve===`linear`?this._gainNode.gain.linearRampTo(0,t,e):this._gainNode.gain.targetRampTo(0,t,e):(this._gainNode.gain.cancelAndHoldAtTime(e),this._gainNode.gain.setValueAtTime(0,e)),this.context.clearTimeout(this._timeout),this._timeout=this.context.setTimeout(()=>{let e=this._curve===`exponential`?t*2:0;this._stopSource(this.now()+e),this._onended()},this._stopTime-this.context.currentTime),this}_onended(){if(this.onended!==Ws&&(this.onended(this),this.onended=Ws,!this.context.isOffline)){let e=()=>this.dispose();typeof requestIdleCallback<`u`?requestIdleCallback(e):setTimeout(e,10)}}get state(){return this.getStateAtTime(this.now())}cancelStop(){return this.log(`cancelStop`),z(this._startTime!==-1,`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=Ws,this}},Sc=class e extends xc{constructor(){let t=B(e.getDefaults(),arguments,[`offset`]);super(t),this.name=`ToneConstantSource`,this._source=this.context.createConstantSource(),vc(this._source,this._gainNode),this.offset=new gc({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(xc.getDefaults(),{convert:!0,offset:1,units:`number`})}start(e){let t=this.toSeconds(e);return this.log(`start`,t),this._startGain(t),this._source.start(t),this}_stopSource(e){this._source.stop(e)}dispose(){return super.dispose(),this.state===`started`&&this.stop(),this._source.disconnect(),this.offset.dispose(),this}},Cc=class e extends V{constructor(){let t=B(e.getDefaults(),arguments,[`value`,`units`]);super(t),this.name=`Signal`,this.override=!0,this.output=this._constantSource=new Sc({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(V.getDefaults(),{convert:!0,units:`number`,value:0})}connect(e,t=0,n=0){return wc(this,e,t,n),this}dispose(){return super.dispose(),this._param.dispose(),this._constantSource.dispose(),this}setValueAtTime(e,t){return this._param.setValueAtTime(e,t),this}getValueAtTime(e){return this._param.getValueAtTime(e)}setRampPoint(e){return this._param.setRampPoint(e),this}linearRampToValueAtTime(e,t){return this._param.linearRampToValueAtTime(e,t),this}exponentialRampToValueAtTime(e,t){return this._param.exponentialRampToValueAtTime(e,t),this}exponentialRampTo(e,t,n){return this._param.exponentialRampTo(e,t,n),this}linearRampTo(e,t,n){return this._param.linearRampTo(e,t,n),this}targetRampTo(e,t,n){return this._param.targetRampTo(e,t,n),this}exponentialApproachValueAtTime(e,t,n){return this._param.exponentialApproachValueAtTime(e,t,n),this}setTargetAtTime(e,t,n){return this._param.setTargetAtTime(e,t,n),this}setValueCurveAtTime(e,t,n,r){return this._param.setValueCurveAtTime(e,t,n,r),this}cancelScheduledValues(e){return this._param.cancelScheduledValues(e),this}cancelAndHoldAtTime(e){return this._param.cancelAndHoldAtTime(e),this}rampTo(e,t,n){return this._param.rampTo(e,t,n),this}get value(){return this._param.value}set value(e){this._param.value=e}get convert(){return this._param.convert}set convert(e){this._param.convert=e}get units(){return this._param.units}get overridden(){return this._param.overridden}set overridden(e){this._param.overridden=e}get maxValue(){return this._param.maxValue}get minValue(){return this._param.minValue}apply(e){return this._param.apply(e),this}};function wc(e,t,n,r){(t instanceof gc||ps(t)||t instanceof Cc&&t.override)&&(t.cancelScheduledValues(0),t.setValueAtTime(0,0),t instanceof Cc&&(t.overridden=!0)),vc(e,t,n,r)}var Tc=class e extends gc{constructor(){let t=B(e.getDefaults(),arguments,[`value`]);super(t),this.name=`TickParam`,this._events=new js(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(gc.getDefaults(),{multiplier:1,units:`hertz`,value:1})}setTargetAtTime(e,t,n){t=this.toSeconds(t),this.setRampPoint(t);let r=this._fromType(e),i=this._events.get(t),a=Math.round(Math.max(1/n,1));for(let e=0;e<=a;e++){let a=n*e+t,o=this._exponentialApproach(i.time,i.value,r,n,a);this.linearRampToValueAtTime(this._toType(o),a)}return this}setValueAtTime(e,t){let n=this.toSeconds(t);super.setValueAtTime(e,t);let r=this._events.get(n),i=this._events.previousEvent(r),a=this._getTicksUntilEvent(i,n);return r.ticks=Math.max(a,0),this}linearRampToValueAtTime(e,t){let n=this.toSeconds(t);super.linearRampToValueAtTime(e,t);let r=this._events.get(n),i=this._events.previousEvent(r),a=this._getTicksUntilEvent(i,n);return r.ticks=Math.max(a,0),this}exponentialRampToValueAtTime(e,t){t=this.toSeconds(t);let n=this._fromType(e),r=this._events.get(t),i=Math.round(Math.max((t-r.time)*10,1)),a=(t-r.time)/i;for(let e=0;e<=i;e++){let i=a*e+r.time,o=this._exponentialInterpolate(r.time,r.value,t,n,i);this.linearRampToValueAtTime(this._toType(o),i)}return this}_getTicksUntilEvent(e,t){if(e===null)e={ticks:0,time:0,type:`setValueAtTime`,value:0};else if(Ho(e.ticks)){let t=this._events.previousEvent(e);e.ticks=this._getTicksUntilEvent(t,e.time)}let n=this._fromType(this.getValueAtTime(e.time)),r=this._fromType(this.getValueAtTime(t)),i=this._events.get(t);return i&&i.time===t&&i.type===`setValueAtTime`&&(r=this._fromType(this.getValueAtTime(t-this.sampleTime))),.5*(t-e.time)*(n+r)+e.ticks}getTicksAtTime(e){let t=this.toSeconds(e),n=this._events.get(t);return Math.max(this._getTicksUntilEvent(n,t),0)}getDurationOfTicks(e,t){let n=this.toSeconds(t),r=this.getTicksAtTime(t);return this.getTimeOfTick(r+e)-n}getTimeOfTick(e){let t=this._events.get(e,`ticks`),n=this._events.getAfter(e,`ticks`);if(t&&t.ticks===e)return t.time;if(t&&n&&n.type===`linearRampToValueAtTime`&&t.value!==n.value){let r=this._fromType(this.getValueAtTime(t.time)),i=(this._fromType(this.getValueAtTime(n.time))-r)/(n.time-t.time),a=Math.sqrt(r**2-2*i*(t.ticks-e)),o=(-r+a)/i,s=(-r-a)/i;return(o>0?o:s)+t.time}else if(t)return t.value===0?1/0:t.time+(e-t.ticks)/t.value;else return e/this._initialValue}ticksToTime(e,t){return this.getDurationOfTicks(e,t)}timeToTicks(e,t){let n=this.toSeconds(t),r=this.toSeconds(e),i=this.getTicksAtTime(n);return this.getTicksAtTime(n+r)-i}_fromType(e){return this.units===`bpm`&&this.multiplier?1/(60/e/this.multiplier):super._fromType(e)}_toType(e){return this.units===`bpm`&&this.multiplier?e/this.multiplier*60:super._toType(e)}get multiplier(){return this._multiplier}set multiplier(e){let t=this.value;this._multiplier=e,this.cancelScheduledValues(0),this.setValueAtTime(t,0)}},Ec=class e extends Cc{constructor(){let t=B(e.getDefaults(),arguments,[`value`]);super(t),this.name=`TickSignal`,this.input=this._param=new Tc({context:this.context,convert:t.convert,multiplier:t.multiplier,param:this._constantSource.offset,units:t.units,value:t.value})}static getDefaults(){return Object.assign(Cc.getDefaults(),{multiplier:1,units:`hertz`,value:1})}ticksToTime(e,t){return this._param.ticksToTime(e,t)}timeToTicks(e,t){return this._param.timeToTicks(e,t)}getTimeOfTick(e){return this._param.getTimeOfTick(e)}getDurationOfTicks(e,t){return this._param.getDurationOfTicks(e,t)}getTicksAtTime(e){return this._param.getTicksAtTime(e)}get multiplier(){return this._param.multiplier}set multiplier(e){this._param.multiplier=e}dispose(){return super.dispose(),this._param.dispose(),this}},Dc=class e extends mc{constructor(){let t=B(e.getDefaults(),arguments,[`frequency`]);super(t),this.name=`TickSource`,this._state=new hc,this._tickOffset=new js,this._ticksAtTime=new js,this._secondsAtTime=new js,this.frequency=new Ec({context:this.context,units:t.units,value:t.frequency}),Hs(this,`frequency`),this._state.setStateAtTime(`stopped`,0),this.setTicksAtTime(0,0)}static getDefaults(){return Object.assign({frequency:1,units:`hertz`},mc.getDefaults())}get state(){return this.getStateAtTime(this.now())}start(e,t){let n=this.toSeconds(e);return this._state.getValueAtTime(n)!==`started`&&(this._state.setStateAtTime(`started`,n),R(t)&&this.setTicksAtTime(t,n),this._ticksAtTime.cancel(n),this._secondsAtTime.cancel(n)),this}stop(e){let t=this.toSeconds(e);if(this._state.getValueAtTime(t)===`stopped`){let e=this._state.get(t);e&&e.time>0&&(this._tickOffset.cancel(e.time),this._state.cancel(e.time))}return this._state.cancel(t),this._state.setStateAtTime(`stopped`,t),this.setTicksAtTime(0,t),this._ticksAtTime.cancel(t),this._secondsAtTime.cancel(t),this}pause(e){let t=this.toSeconds(e);return this._state.getValueAtTime(t)===`started`&&(this._state.setStateAtTime(`paused`,t),this._ticksAtTime.cancel(t),this._secondsAtTime.cancel(t)),this}cancel(e){return e=this.toSeconds(e),this._state.cancel(e),this._tickOffset.cancel(e),this._ticksAtTime.cancel(e),this._secondsAtTime.cancel(e),this}getTicksAtTime(e){let t=this.toSeconds(e),n=this._state.getLastState(`stopped`,t),r=this._ticksAtTime.get(t),i={state:`paused`,time:t};this._state.add(i);let a=r||n,o=r?r.ticks:0,s=null;return this._state.forEachBetween(a.time,t+this.sampleTime,e=>{let t=a.time,n=this._tickOffset.get(e.time);n&&n.time>=a.time&&(o=n.ticks,t=n.time),a.state===`started`&&e.state!==`started`&&(o+=this.frequency.getTicksAtTime(e.time)-this.frequency.getTicksAtTime(t),e.time!==i.time&&(s={state:e.state,time:e.time,ticks:o})),a=e}),this._state.remove(i),s&&this._ticksAtTime.add(s),o}get ticks(){return this.getTicksAtTime(this.now())}set ticks(e){this.setTicksAtTime(e,this.now())}get seconds(){return this.getSecondsAtTime(this.now())}set seconds(e){let t=this.now(),n=this.frequency.timeToTicks(e,t);this.setTicksAtTime(n,t)}getSecondsAtTime(e){e=this.toSeconds(e);let t=this._state.getLastState(`stopped`,e),n={state:`paused`,time:e};this._state.add(n);let r=this._secondsAtTime.get(e),i=r||t,a=r?r.seconds:0,o=null;return this._state.forEachBetween(i.time,e+this.sampleTime,e=>{let t=i.time,r=this._tickOffset.get(e.time);r&&r.time>=i.time&&(a=r.seconds,t=r.time),i.state===`started`&&e.state!==`started`&&(a+=e.time-t,e.time!==n.time&&(o={state:e.state,time:e.time,seconds:a})),i=e}),this._state.remove(n),o&&this._secondsAtTime.add(o),a}setTicksAtTime(e,t){return t=this.toSeconds(t),this._tickOffset.cancel(t),this._tickOffset.add({seconds:this.frequency.getDurationOfTicks(e,t),ticks:e,time:t}),this._ticksAtTime.cancel(t),this._secondsAtTime.cancel(t),this}getStateAtTime(e){return e=this.toSeconds(e),this._state.getValueAtTime(e)}getTimeOfTick(e,t=this.now()){let n=this._tickOffset.get(t),r=this._state.get(t),i=Math.max(n.time,r.time),a=this.frequency.getTicksAtTime(i)+e-n.ticks;return this.frequency.getTimeOfTick(a)}forEachTickBetween(e,t,n){let r=this._state.get(e);this._state.forEachBetween(e,t,t=>{r&&r.state===`started`&&t.state!==`started`&&this.forEachTickBetween(Math.max(r.time,e),t.time-this.sampleTime,n),r=t});let i=null;if(r&&r.state===`started`){let a=Math.max(r.time,e),o=this.frequency.getTicksAtTime(a),s=o-this.frequency.getTicksAtTime(r.time),c=Math.ceil(s)-s;c=ks(c,1)?0:c;let l=this.frequency.getTimeOfTick(o+c);for(;l{switch(e.state){case`started`:let t=this._tickSource.getTicksAtTime(e.time);this.emit(`start`,e.time,t);break;case`stopped`:e.time!==0&&this.emit(`stop`,e.time);break;case`paused`:this.emit(`pause`,e.time);break}}),this._tickSource.forEachTickBetween(e,t,(e,t)=>{this.callback(e,t)}))}getStateAtTime(e){let t=this.toSeconds(e);return this._state.getValueAtTime(t)}dispose(){return super.dispose(),this.context.off(`tick`,this._boundLoop),this._tickSource.dispose(),this._state.dispose(),this}};Rs.mixin(Oc);var kc=class e extends V{constructor(){let t=B(e.getDefaults(),arguments,[`volume`]);super(t),this.name=`Volume`,this.input=this.output=new bc({context:this.context,gain:t.volume,units:`decibels`}),this.volume=this.output.gain,Hs(this,`volume`),this._unmutedVolume=t.volume,this.mute=t.mute}static getDefaults(){return Object.assign(V.getDefaults(),{mute:!1,volume:0})}get mute(){return this.volume.value===-1/0}set mute(e){!this.mute&&e?(this._unmutedVolume=this.volume.value,this.volume.value=-1/0):this.mute&&!e&&(this.volume.value=this._unmutedVolume)}dispose(){return super.dispose(),this.input.dispose(),this.volume.dispose(),this}},Ac=class e extends V{constructor(){let t=B(e.getDefaults(),arguments);super(t),this.name=`Destination`,this.input=new kc({context:this.context}),this.output=new bc({context:this.context}),this.volume=this.input.volume,_c(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(V.getDefaults(),{mute:!1,volume:0})}get mute(){return this.input.mute}set mute(e){this.input.mute=e}chain(...e){return this.input.disconnect(),e.unshift(this.input),e.push(this.output),_c(...e),this}get maxChannelCount(){return this.context.rawContext.destination.maxChannelCount}dispose(){return super.dispose(),this.volume.dispose(),this}};Ns(e=>{e.destination=new Ac({context:e})}),Is(e=>{e.destination.dispose()});var jc=class extends V{constructor(){super(...arguments),this.name=`Listener`,this.positionX=new gc({context:this.context,param:this.context.rawContext.listener.positionX}),this.positionY=new gc({context:this.context,param:this.context.rawContext.listener.positionY}),this.positionZ=new gc({context:this.context,param:this.context.rawContext.listener.positionZ}),this.forwardX=new gc({context:this.context,param:this.context.rawContext.listener.forwardX}),this.forwardY=new gc({context:this.context,param:this.context.rawContext.listener.forwardY}),this.forwardZ=new gc({context:this.context,param:this.context.rawContext.listener.forwardZ}),this.upX=new gc({context:this.context,param:this.context.rawContext.listener.upX}),this.upY=new gc({context:this.context,param:this.context.rawContext.listener.upY}),this.upZ=new gc({context:this.context,param:this.context.rawContext.listener.upZ})}static getDefaults(){return Object.assign(V.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}};Ns(e=>{e.listener=new jc({context:e})}),Is(e=>{e.listener.dispose()});var Mc=class e extends ws{constructor(){super(),this.name=`ToneAudioBuffers`,this._buffers=new Map,this._loadingCount=0;let t=B(e.getDefaults(),arguments,[`urls`,`onload`,`baseUrl`],`urls`);this.baseUrl=t.baseUrl,Object.keys(t.urls).forEach(e=>{this._loadingCount++;let n=t.urls[e];this.add(e,n,this._bufferLoaded.bind(this,t.onload),t.onerror)})}static getDefaults(){return{baseUrl:``,onerror:Ws,onload:Ws,urls:{}}}has(e){return this._buffers.has(e.toString())}get(e){return z(this.has(e),`ToneAudioBuffers has no buffer named: ${e}`),this._buffers.get(e.toString())}_bufferLoaded(e){this._loadingCount--,this._loadingCount===0&&e&&e()}get loaded(){return Array.from(this._buffers).every(([e,t])=>t.loaded)}add(e,t,n=Ws,r=Ws){return Jo(t)?(this.baseUrl&&t.trim().substring(0,11).toLowerCase()===`data:audio/`&&(this.baseUrl=``),this._buffers.set(e.toString(),new Gs(this.baseUrl+t,n,r))):this._buffers.set(e.toString(),new Gs(t,n,r)),this}dispose(){return super.dispose(),this._buffers.forEach(e=>e.dispose()),this._buffers.clear(),this}},Nc=class e extends lc{constructor(){super(...arguments),this.name=`MidiClass`,this.defaultUnits=`midi`}_frequencyToUnits(e){return ic(super._frequencyToUnits(e))}_ticksToUnits(e){return ic(super._ticksToUnits(e))}_beatsToUnits(e){return ic(super._beatsToUnits(e))}_secondsToUnits(e){return ic(super._secondsToUnits(e))}toMidi(){return this.valueOf()}toFrequency(){return oc(this.toMidi())}transpose(t){return new e(this.context,this.toMidi()+t)}},Pc=class extends pc{constructor(){super(...arguments),this.name=`Ticks`,this.defaultUnits=`i`}_now(){return this.context.transport.ticks}_beatsToUnits(e){return this._getPPQ()*e}_secondsToUnits(e){return Math.floor(e/(60/this._getBpm())*this._getPPQ())}_ticksToUnits(e){return e}toTicks(){return this.valueOf()}toSeconds(){return this.valueOf()/this._getPPQ()*(60/this._getBpm())}},Fc=class extends mc{constructor(){super(...arguments),this.name=`Draw`,this.expiration=.25,this.anticipation=.008,this._events=new js,this._boundDrawLoop=this._drawLoop.bind(this),this._animationFrame=-1}schedule(e,t){return this._events.add({callback:e,time:this.toSeconds(t)}),this._events.length===1&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop)),this}cancel(e){return this._events.cancel(this.toSeconds(e)),this}_drawLoop(){let e=this.context.currentTime;this._events.forEachBefore(e+this.anticipation,t=>{e-t.time<=this.expiration&&t.callback(),this._events.remove(t)}),this._events.length>0&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop))}dispose(){return super.dispose(),this._events.dispose(),cancelAnimationFrame(this._animationFrame),this}};Ns(e=>{e.draw=new Fc({context:e})}),Is(e=>{e.draw.dispose()});var Ic=class extends ws{constructor(){super(...arguments),this.name=`IntervalTimeline`,this._root=null,this._length=0}add(e){z(R(e.time),`Events must have a time property`),z(R(e.duration),`Events must have a duration parameter`),e.time=e.time.valueOf();let t=new Lc(e.time,e.time+e.duration,e);for(this._root===null?this._root=t:this._root.insert(t),this._length++;t!==null;)t.updateHeight(),t.updateMax(),this._rebalance(t),t=t.parent;return this}remove(e){if(this._root!==null){let t=[];this._root.search(e.time,t);for(let n of t)if(n.event===e){this._removeNode(n),this._length--;break}}return this}get length(){return this._length}cancel(e){return this.forEachFrom(e,e=>this.remove(e)),this}_setRoot(e){this._root=e,this._root!==null&&(this._root.parent=null)}_replaceNodeInParent(e,t){e.parent===null?this._setRoot(t):(e.isLeftChild()?e.parent.left=t:e.parent.right=t,this._rebalance(e.parent))}_removeNode(e){if(e.left===null&&e.right===null)this._replaceNodeInParent(e,null);else if(e.right===null)this._replaceNodeInParent(e,e.left);else if(e.left===null)this._replaceNodeInParent(e,e.right);else{let t=e.getBalance(),n,r=null;if(t>0)if(e.left.right===null)n=e.left,n.right=e.right,r=n;else{for(n=e.left.right;n.right!==null;)n=n.right;n.parent&&(n.parent.right=n.left,r=n.parent,n.left=e.left,n.right=e.right)}else if(e.right.left===null)n=e.right,n.left=e.left,r=n;else{for(n=e.right.left;n.left!==null;)n=n.left;n.parent&&(n.parent.left=n.right,r=n.parent,n.left=e.left,n.right=e.right)}e.parent===null?this._setRoot(n):e.isLeftChild()?e.parent.left=n:e.parent.right=n,r&&this._rebalance(r)}e.dispose()}_rotateLeft(e){let t=e.parent,n=e.isLeftChild(),r=e.right;r&&(e.right=r.left,r.left=e),t===null?this._setRoot(r):n?t.left=r:t.right=r}_rotateRight(e){let t=e.parent,n=e.isLeftChild(),r=e.left;r&&(e.left=r.right,r.right=e),t===null?this._setRoot(r):n?t.left=r:t.right=r}_rebalance(e){let t=e.getBalance();t>1&&e.left?e.left.getBalance()<0?this._rotateLeft(e.left):this._rotateRight(e):t<-1&&e.right&&(e.right.getBalance()>0?this._rotateRight(e.right):this._rotateLeft(e))}get(e){if(this._root!==null){let t=[];if(this._root.search(e,t),t.length>0){let e=t[0];for(let n=1;ne.low&&(e=t[n]);return e.event}}return null}forEach(e){if(this._root!==null){let t=[];this._root.traverse(e=>t.push(e)),t.forEach(t=>{t.event&&e(t.event)})}return this}forEachAtTime(e,t){if(this._root!==null){let n=[];this._root.search(e,n),n.forEach(e=>{e.event&&t(e.event)})}return this}forEachFrom(e,t){if(this._root!==null){let n=[];this._root.searchAfter(e,n),n.forEach(e=>{e.event&&t(e.event)})}return this}dispose(){return super.dispose(),this._root!==null&&this._root.traverse(e=>e.dispose()),this._root=null,this}},Lc=class{constructor(e,t,n){this._left=null,this._right=null,this.parent=null,this.height=0,this.event=n,this.low=e,this.high=t,this.max=this.high}insert(e){e.low<=this.low?this.left===null?this.left=e:this.left.insert(e):this.right===null?this.right=e:this.right.insert(e)}search(e,t){e>this.max||(this.left!==null&&this.left.search(e,t),this.low<=e&&this.high>e&&t.push(this),!(this.low>e)&&this.right!==null&&this.right.search(e,t))}searchAfter(e,t){this.low>=e&&(t.push(this),this.left!==null&&this.left.searchAfter(e,t)),this.right!==null&&this.right.searchAfter(e,t)}traverse(e){e(this),this.left!==null&&this.left.traverse(e),this.right!==null&&this.right.traverse(e)}updateHeight(){this.left!==null&&this.right!==null?this.height=Math.max(this.left.height,this.right.height)+1:this.right===null?this.left===null?this.height=0:this.height=this.left.height+1:this.height=this.right.height+1}updateMax(){this.max=this.high,this.left!==null&&(this.max=Math.max(this.max,this.left.max)),this.right!==null&&(this.max=Math.max(this.max,this.right.max))}getBalance(){let e=0;return this.left!==null&&this.right!==null?e=this.left.height-this.right.height:this.left===null?this.right!==null&&(e=-(this.right.height+1)):e=this.left.height+1,e}isLeftChild(){return this.parent!==null&&this.parent.left===this}get left(){return this._left}set left(e){this._left=e,e!==null&&(e.parent=this),this.updateHeight(),this.updateMax()}get right(){return this._right}set right(e){this._right=e,e!==null&&(e.parent=this),this.updateHeight(),this.updateMax()}dispose(){this.parent=null,this._left=null,this._right=null,this.event=null}},Rc=class extends ws{constructor(e){super(),this.name=`TimelineValue`,this._timeline=new js({memory:10}),this._initialValue=e}set(e,t){return this._timeline.add({value:e,time:t}),this}get(e){let t=this._timeline.get(e);return t?t.value:this._initialValue}},zc=class e extends V{constructor(){super(B(e.getDefaults(),arguments,[`context`]))}connect(e,t=0,n=0){return wc(this,e,t,n),this}},Bc=class e extends zc{constructor(){let t=B(e.getDefaults(),arguments,[`mapping`,`length`]);super(t),this.name=`WaveShaper`,this._shaper=this.context.createWaveShaper(),this.input=this._shaper,this.output=this._shaper,qo(t.mapping)||t.mapping instanceof Float32Array?this.curve=Float32Array.from(t.mapping):Uo(t.mapping)&&this.setMap(t.mapping,t.length)}static getDefaults(){return Object.assign(Cc.getDefaults(),{length:1024})}setMap(e,t=1024){let n=new Float32Array(t);for(let r=0,i=t;rt.includes(e)),`oversampling must be either 'none', '2x', or '4x'`),this._shaper.oversample=e}dispose(){return super.dispose(),this._shaper.disconnect(),this}},Vc=class e extends zc{constructor(){let t=B(e.getDefaults(),arguments,[`value`]);super(t),this.name=`Pow`,this._exponentScaler=this.input=this.output=new Bc({context:this.context,mapping:this._expFunc(t.value),length:8192}),this._exponent=t.value}static getDefaults(){return Object.assign(zc.getDefaults(),{value:1})}_expFunc(e){return t=>Math.abs(t)**+e}get value(){return this._exponent}set value(e){this._exponent=e,this._exponentScaler.setMap(this._expFunc(this._exponent))}dispose(){return super.dispose(),this._exponentScaler.dispose(),this}},Hc=class e{constructor(t,n){this.id=e._eventId++,this._remainderTime=0;let r=Object.assign(e.getDefaults(),n);this.transport=t,this.callback=r.callback,this._once=r.once,this.time=Math.floor(r.time),this._remainderTime=r.time-this.time}static getDefaults(){return{callback:Ws,once:!1,time:0}}get floatTime(){return this.time+this._remainderTime}invoke(e){if(this.callback){let t=this.transport.bpm.getDurationOfTicks(1,e);this.callback(e+this._remainderTime*t),this._once&&this.transport.clear(this.id)}}dispose(){return this.callback=void 0,this}};Hc._eventId=0;var Uc=class e extends Hc{constructor(t,n){super(t,n),this._currentId=-1,this._nextId=-1,this._nextTick=this.time,this._boundRestart=this._restart.bind(this);let r=Object.assign(e.getDefaults(),n);this.duration=r.duration,this._interval=r.interval,this._nextTick=r.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({},Hc.getDefaults(),{duration:1/0,interval:1,once:!1})}invoke(e){this._createEvents(e),super.invoke(e)}_createEvent(){return Os(this._nextTick,this.floatTime+this.duration)?this.transport.scheduleOnce(this.invoke.bind(this),new Pc(this.context,this._nextTick).toSeconds()):-1}_createEvents(e){Os(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 Pc(this.context,this._nextTick).toSeconds()))}_restart(e){this.transport.clear(this._currentId),this.transport.clear(this._nextId),this._nextTick=this.floatTime;let t=this.transport.getTicksAtTime(e);Es(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}},Wc=class e extends mc{constructor(){let t=B(e.getDefaults(),arguments);super(t),this.name=`Transport`,this._loop=new Rc(!1),this._loopStart=0,this._loopEnd=0,this._scheduledEvents={},this._timeline=new js,this._repeatedEvents=new Ic,this._syncedSignals=[],this._swingAmount=0,this._ppq=t.ppq,this._clock=new Oc({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),Hs(this,`bpm`),this._timeSignature=t.timeSignature,this._swingTicks=t.ppq/2}static getDefaults(){return Object.assign(mc.getDefaults(),{bpm:120,loopEnd:`4m`,loopStart:0,ppq:192,swing:0,swingSubdivision:`8n`,timeSignature:4})}_processTick(e,t){if(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)),this._swingAmount>0&&t%this._ppq!==0&&t%(this._swingTicks*2)!=0){let n=t%(this._swingTicks*2)/(this._swingTicks*2),r=Math.sin(n*Math.PI)*this._swingAmount;e+=new Pc(this.context,this._swingTicks*2/3).toSeconds()*r}es(!0),this._timeline.forEachAtTime(t,t=>t.invoke(e)),es(!1)}schedule(e,t){let n=new Hc(this,{callback:e,time:new pc(this.context,t).toTicks()});return this._addEvent(n,this._timeline)}scheduleRepeat(e,t,n,r=1/0){let i=new Uc(this,{callback:e,duration:new cc(this.context,r).toTicks(),interval:new cc(this.context,t).toTicks(),time:new pc(this.context,n).toTicks()});return this._addEvent(i,this._repeatedEvents)}scheduleOnce(e,t){let n=new Hc(this,{callback:e,once:!0,time:new pc(this.context,t).toTicks()});return this._addEvent(n,this._timeline)}clear(e){if(this._scheduledEvents.hasOwnProperty(e)){let t=this._scheduledEvents[e.toString()];t.timeline.remove(t.event),t.event.dispose(),delete this._scheduledEvents[e.toString()]}return this}_addEvent(e,t){return this._scheduledEvents[e.id.toString()]={event:e,timeline:t},t.add(e),e.id}cancel(e=0){let t=this.toTicks(e);return this._timeline.forEachFrom(t,e=>this.clear(e.id)),this._repeatedEvents.forEachFrom(t,e=>this.clear(e.id)),this}_bindClockEvents(){this._clock.on(`start`,(e,t)=>{t=new Pc(this.context,t).toSeconds(),this.emit(`start`,e,t)}),this._clock.on(`stop`,e=>{this.emit(`stop`,e)}),this._clock.on(`pause`,e=>{this.emit(`pause`,e)})}get state(){return this._clock.getStateAtTime(this.now())}start(e,t){this.context.resume();let n;return R(t)&&(n=this.toTicks(t)),this._clock.start(e,n),this}stop(e){return this._clock.stop(e),this}pause(e){return this._clock.pause(e),this}toggle(e){return e=this.toSeconds(e),this._clock.getStateAtTime(e)===`started`?this.stop(e):this.start(e),this}get timeSignature(){return this._timeSignature}set timeSignature(e){qo(e)&&(e=e[0]/e[1]*4),this._timeSignature=e}get loopStart(){return new cc(this.context,this._loopStart,`i`).toSeconds()}set loopStart(e){this._loopStart=this.toTicks(e)}get loopEnd(){return new cc(this.context,this._loopEnd,`i`).toSeconds()}set loopEnd(e){this._loopEnd=this.toTicks(e)}get loop(){return this._loop.get(this.now())}set loop(e){this._loop.set(e,this.now())}setLoopPoints(e,t){return this.loopStart=e,this.loopEnd=t,this}get swing(){return this._swingAmount}set swing(e){this._swingAmount=e}get swingSubdivision(){return new Pc(this.context,this._swingTicks).toNotation()}set swingSubdivision(e){this._swingTicks=this.toTicks(e)}get position(){let e=this.now(),t=this._clock.getTicksAtTime(e);return new Pc(this.context,t).toBarsBeatsSixteenths()}set position(e){let t=this.toTicks(e);this.ticks=t}get seconds(){return this._clock.seconds}set seconds(e){let t=this.now(),n=this._clock.frequency.timeToTicks(e,t);this.ticks=n}get progress(){if(this.loop){let e=this.now();return(this._clock.getTicksAtTime(e)-this._loopStart)/(this._loopEnd-this._loopStart)}else return 0}get ticks(){return this._clock.ticks}set ticks(e){if(this._clock.ticks!==e){let t=this.now();if(this.state===`started`){let n=this._clock.getTicksAtTime(t),r=t+this._clock.frequency.getDurationOfTicks(Math.ceil(n)-n,t);this.emit(`stop`,r),this._clock.setTicksAtTime(e,r),this.emit(`start`,r,this._clock.getSecondsAtTime(r))}else this.emit(`ticks`,t),this._clock.setTicksAtTime(e,t)}}getTicksAtTime(e){return this._clock.getTicksAtTime(e)}getSecondsAtTime(e){return this._clock.getSecondsAtTime(e)}get PPQ(){return this._clock.frequency.multiplier}set PPQ(e){this._clock.frequency.multiplier=e}nextSubdivision(e){if(e=this.toTicks(e),this.state!==`started`)return 0;{let t=this.now(),n=this.getTicksAtTime(t),r=e-n%e;return this._clock.nextTickTime(r,t)}}syncSignal(e,t){let n=this.now(),r=this.bpm,i=1/(60/r.getValueAtTime(n)/this.PPQ),a=[];if(e.units===`time`){let e=1/64/i,t=new bc(e),n=new Vc(-1),o=new bc(e);r.chain(t,n,o),r=o,i=1/i,a=[t,n,o]}t||=e.getValueAtTime(n)===0?0:e.getValueAtTime(n)/i;let o=new bc(t);return r.connect(o),o.connect(e._param),a.push(o),this._syncedSignals.push({initial:e.value,nodes:a,signal:e}),e.value=0,this}unsyncSignal(e){for(let t=this._syncedSignals.length-1;t>=0;t--){let n=this._syncedSignals[t];n.signal===e&&(n.nodes.forEach(e=>e.dispose()),n.signal.value=n.initial,this._syncedSignals.splice(t,1))}return this}dispose(){return super.dispose(),this._clock.dispose(),Us(this,`bpm`),this._timeline.dispose(),this._repeatedEvents.dispose(),this}};Rs.mixin(Wc),Ns(e=>{e.transport=new Wc({context:e})}),Is(e=>{e.transport.dispose()});var Gc=class extends V{constructor(e){super(e),this.input=void 0,this._state=new hc(`stopped`),this._synced=!1,this._scheduled=[],this._syncedStart=Ws,this._syncedStop=Ws,this._state.memory=100,this._state.increasing=!0,this._volume=this.output=new kc({context:this.context,mute:e.mute,volume:e.volume}),this.volume=this._volume.volume,Hs(this,`volume`),this.onstop=e.onstop}static getDefaults(){return Object.assign(V.getDefaults(),{mute:!1,onstop:Ws,volume:0})}get state(){return this._synced?this.context.transport.state===`started`?this._state.getValueAtTime(this.context.transport.seconds):`stopped`:this._state.getValueAtTime(this.now())}get mute(){return this._volume.mute}set mute(e){this._volume.mute=e}_clampToCurrentTime(e){return this._synced?e:Math.max(e,this.context.currentTime)}start(e,t,n){let r=Ho(e)&&this._synced?this.context.transport.seconds:this.toSeconds(e);if(r=this._clampToCurrentTime(r),!this._synced&&this._state.getValueAtTime(r)===`started`)z(Es(r,this._state.get(r).time),`Start time must be strictly greater than previous start time`),this._state.cancel(r),this._state.setStateAtTime(`started`,r),this.log(`restart`,r),this.restart(r,t,n);else if(this.log(`start`,r),this._state.setStateAtTime(`started`,r),this._synced){let e=this._state.get(r);e&&(e.offset=this.toSeconds(Ss(t,0)),e.duration=n?this.toSeconds(n):void 0);let i=this.context.transport.schedule(e=>{this._start(e,t,n)},r);this._scheduled.push(i),this.context.transport.state===`started`&&this.context.transport.getSecondsAtTime(this.immediate())>r&&this._syncedStart(this.now(),this.context.transport.seconds)}else Zo(this.context),this._start(r,t,n);return this}stop(e){let t=Ho(e)&&this._synced?this.context.transport.seconds:this.toSeconds(e);if(t=this._clampToCurrentTime(t),this._state.getValueAtTime(t)===`started`||R(this._state.getNextState(`started`,t))){if(this.log(`stop`,t),!this._synced)this._stop(t);else{let e=this.context.transport.schedule(this._stop.bind(this),t);this._scheduled.push(e)}this._state.cancel(t),this._state.setStateAtTime(`stopped`,t)}return this}restart(e,t,n){return e=this.toSeconds(e),this._state.getValueAtTime(e)===`started`&&(this._state.cancel(e),this._restart(e,t,n)),this}sync(){return this._synced||(this._synced=!0,this._syncedStart=(e,t)=>{if(Es(t,0)){let n=this._state.get(t);if(n&&n.state===`started`&&n.time!==t){let r=t-this.toSeconds(n.time),i;n.duration&&(i=this.toSeconds(n.duration)-r),this._start(e,this.toSeconds(n.offset)+r,i)}}},this._syncedStop=e=>{let t=this.context.transport.getSecondsAtTime(Math.max(e-this.sampleTime,0));this._state.getValueAtTime(t)===`started`&&this._stop(e)},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(e=>this.context.transport.clear(e)),this._scheduled=[],this._state.cancel(0),this._stop(0),this}dispose(){return super.dispose(),this.onstop=Ws,this.unsync(),this._volume.dispose(),this._state.dispose(),this}},Kc=class e extends xc{constructor(){let t=B(e.getDefaults(),arguments,[`url`,`onload`]);super(t),this.name=`ToneBufferSource`,this._source=this.context.createBufferSource(),this._internalChannels=[this._source],this._sourceStarted=!1,this._sourceStopped=!1,vc(this._source,this._gainNode),this._source.onended=()=>this._stopSource(),this.playbackRate=new gc({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 Gs(t.url,t.onload,t.onerror),this._internalChannels.push(this._source)}static getDefaults(){return Object.assign(xc.getDefaults(),{url:new Gs,loop:!1,loopEnd:0,loopStart:0,onload:Ws,onerror:Ws,playbackRate:1})}get fadeIn(){return this._fadeIn}set fadeIn(e){this._fadeIn=e}get fadeOut(){return this._fadeOut}set fadeOut(e){this._fadeOut=e}get curve(){return this._curve}set curve(e){this._curve=e}start(e,t,n,r=1){z(this.buffer.loaded,`buffer is either not set or not loaded`);let i=this.toSeconds(e);this._startGain(i,r),t=this.loop?Ss(t,this.loopStart):Ss(t,0);let a=Math.max(this.toSeconds(t),0);if(this.loop){let e=this.toSeconds(this.loopEnd)||this.buffer.duration,t=this.toSeconds(this.loopStart),n=e-t;Ds(a,e)&&(a=(a-t)%n+t),ks(a,this.buffer.duration)&&(a=0)}if(this._source.buffer=this.buffer.get(),this._source.loopEnd=this.toSeconds(this.loopEnd)||this.buffer.duration,Os(a,this.buffer.duration)&&(this._sourceStarted=!0,this._source.start(i,a)),R(n)){let e=this.toSeconds(n);e=Math.max(e,0),this.stop(i+e)}return this}_stopSource(e){!this._sourceStopped&&this._sourceStarted&&(this._sourceStopped=!0,this._source.stop(this.toSeconds(e)),this._onended())}get loopStart(){return this._source.loopStart}set loopStart(e){this._source.loopStart=this.toSeconds(e)}get loopEnd(){return this._source.loopEnd}set loopEnd(e){this._source.loopEnd=this.toSeconds(e)}get buffer(){return this._buffer}set buffer(e){this._buffer.set(e)}get loop(){return this._source.loop}set loop(e){this._source.loop=e,this._sourceStarted&&this.cancelStop()}dispose(){return super.dispose(),this._source.onended=null,this._source.disconnect(),this._buffer.dispose(),this.playbackRate.dispose(),this}};function qc(e,t){return ds(this,void 0,void 0,function*(){let n=t/e.context.sampleRate,r=new Ks(1,n,e.context.sampleRate);return new e.constructor(Object.assign(e.get(),{frequency:2/n,detune:0,context:r})).toDestination().start(0),(yield r.render()).getChannelData(0)})}var Jc=class e extends xc{constructor(){let t=B(e.getDefaults(),arguments,[`frequency`,`type`]);super(t),this.name=`ToneOscillatorNode`,this._oscillator=this.context.createOscillator(),this._internalChannels=[this._oscillator],vc(this._oscillator,this._gainNode),this.type=t.type,this.frequency=new gc({context:this.context,param:this._oscillator.frequency,units:`frequency`,value:t.frequency}),this.detune=new gc({context:this.context,param:this._oscillator.detune,units:`cents`,value:t.detune}),Hs(this,[`frequency`,`detune`])}static getDefaults(){return Object.assign(xc.getDefaults(),{detune:0,frequency:440,type:`sine`})}start(e){let t=this.toSeconds(e);return this.log(`start`,t),this._startGain(t),this._oscillator.start(t),this}_stopSource(e){this._oscillator.stop(e)}setPeriodicWave(e){return this._oscillator.setPeriodicWave(e),this}get type(){return this._oscillator.type}set type(e){this._oscillator.type=e}dispose(){return super.dispose(),this.state===`started`&&this.stop(),this._oscillator.disconnect(),this.frequency.dispose(),this.detune.dispose(),this}},Yc=class e extends Gc{constructor(){let t=B(e.getDefaults(),arguments,[`frequency`,`type`]);super(t),this.name=`Oscillator`,this._oscillator=null,this.frequency=new Cc({context:this.context,units:`frequency`,value:t.frequency}),Hs(this,`frequency`),this.detune=new Cc({context:this.context,units:`cents`,value:t.detune}),Hs(this,`detune`),this._partials=t.partials,this._partialCount=t.partialCount,this._type=t.type,t.partialCount&&t.type!==`custom`&&(this._type=this.baseType+t.partialCount.toString()),this.phase=t.phase}static getDefaults(){return Object.assign(Gc.getDefaults(),{detune:0,frequency:440,partialCount:0,partials:[],phase:0,type:`sine`})}_start(e){let t=this.toSeconds(e),n=new Jc({context:this.context,onended:()=>this.onstop(this)});this._oscillator=n,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(e){let t=this.toSeconds(e);this._oscillator&&this._oscillator.stop(t)}_restart(e){let t=this.toSeconds(e);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(this._type===`custom`)return e._periodicWaveCache.find(e=>e.phase===this._phase&&bs(e.partials,this._partials));{let t=e._periodicWaveCache.find(e=>e.type===this._type&&e.phase===this._phase);return this._partialCount=t?t.partialCount:this._partialCount,t}}get type(){return this._type}set type(t){this._type=t;let n=[`sine`,`square`,`sawtooth`,`triangle`].indexOf(t)!==-1;if(this._phase===0&&n)this._wave=void 0,this._partialCount=0,this._oscillator!==null&&(this._oscillator.type=t);else{let n=this._getCachedPeriodicWave();if(R(n)){let{partials:e,wave:t}=n;this._wave=t,this._partials=e,this._oscillator!==null&&this._oscillator.setPeriodicWave(this._wave)}else{let[n,r]=this._getRealImaginary(t,this._phase),i=this.context.createPeriodicWave(n,r);this._wave=i,this._oscillator!==null&&this._oscillator.setPeriodicWave(this._wave),e._periodicWaveCache.push({imag:r,partialCount:this._partialCount,partials:this._partials,phase:this._phase,real:n,type:this._type,wave:this._wave}),e._periodicWaveCache.length>100&&e._periodicWaveCache.shift()}}}get baseType(){return this._type.replace(this.partialCount.toString(),``)}set baseType(e){this.partialCount&&this._type!==`custom`&&e!==`custom`?this.type=e+this.partialCount:this.type=e}get partialCount(){return this._partialCount}set partialCount(e){Xo(e,0);let t=this._type,n=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(this._type);if(n&&(t=n[1]),this._type!==`custom`)e===0?this.type=t:this.type=t+e.toString();else{let t=new Float32Array(e);this._partials.forEach((e,n)=>t[n]=e),this._partials=Array.from(t),this.type=this._type}}_getRealImaginary(e,t){let n=4096/2,r=new Float32Array(n),i=new Float32Array(n),a=1;if(e===`custom`){if(a=this._partials.length+1,this._partialCount=this._partials.length,n=a,this._partials.length===0)return[r,i]}else{let t=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(e);t?(a=parseInt(t[2],10)+1,this._partialCount=parseInt(t[2],10),e=t[1],a=Math.max(a,2),n=a):this._partialCount=0,this._partials=[]}for(let o=1;o>1&1?-1:1):0,this._partials[o-1]=s;break;case`custom`:s=this._partials[o-1];break;default:throw TypeError(`Oscillator: invalid type: `+e)}s===0?(r[o]=0,i[o]=0):(r[o]=-s*Math.sin(t*o),i[o]=s*Math.cos(t*o))}return[r,i]}_inverseFFT(e,t,n){let r=0,i=e.length;for(let a=0;a(e+1)/2}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}},Zc=class e extends Cc{constructor(){let t=B(e.getDefaults(),arguments,[`value`]);super(t),this.name=`Multiply`,this.override=!1,this._mult=this.input=this.output=new bc({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(Cc.getDefaults(),{value:0})}dispose(){return super.dispose(),this._mult.dispose(),this}},Qc=class e extends Gc{constructor(){let t=B(e.getDefaults(),arguments,[`frequency`,`type`,`modulationType`]);super(t),this.name=`AMOscillator`,this._modulationScale=new Xc({context:this.context}),this._modulationNode=new bc({context:this.context}),this._carrier=new Yc({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 Yc({context:this.context,phase:t.phase,type:t.modulationType}),this.harmonicity=new Zc({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),Hs(this,[`frequency`,`detune`,`harmonicity`])}static getDefaults(){return Object.assign(Yc.getDefaults(),{harmonicity:1,modulationType:`square`})}_start(e){this._modulator.start(e),this._carrier.start(e)}_stop(e){this._modulator.stop(e),this._carrier.stop(e)}_restart(e){this._modulator.restart(e),this._carrier.restart(e)}get type(){return this._carrier.type}set type(e){this._carrier.type=e}get baseType(){return this._carrier.baseType}set baseType(e){this._carrier.baseType=e}get partialCount(){return this._carrier.partialCount}set partialCount(e){this._carrier.partialCount=e}get modulationType(){return this._modulator.type}set modulationType(e){this._modulator.type=e}get phase(){return this._carrier.phase}set phase(e){this._carrier.phase=e,this._modulator.phase=e}get partials(){return this._carrier.partials}set partials(e){this._carrier.partials=e}asArray(){return ds(this,arguments,void 0,function*(e=1024){return qc(this,e)})}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}},$c=class e extends Gc{constructor(){let t=B(e.getDefaults(),arguments,[`frequency`,`type`,`modulationType`]);super(t),this.name=`FMOscillator`,this._modulationNode=new bc({context:this.context,gain:0}),this._carrier=new Yc({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 Cc({context:this.context,units:`frequency`,value:t.frequency}),this._modulator=new Yc({context:this.context,phase:t.phase,type:t.modulationType}),this.harmonicity=new Zc({context:this.context,units:`positive`,value:t.harmonicity}),this.modulationIndex=new Zc({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),Hs(this,[`modulationIndex`,`frequency`,`detune`,`harmonicity`])}static getDefaults(){return Object.assign(Yc.getDefaults(),{harmonicity:1,modulationIndex:2,modulationType:`square`})}_start(e){this._modulator.start(e),this._carrier.start(e)}_stop(e){this._modulator.stop(e),this._carrier.stop(e)}_restart(e){return this._modulator.restart(e),this._carrier.restart(e),this}get type(){return this._carrier.type}set type(e){this._carrier.type=e}get baseType(){return this._carrier.baseType}set baseType(e){this._carrier.baseType=e}get partialCount(){return this._carrier.partialCount}set partialCount(e){this._carrier.partialCount=e}get modulationType(){return this._modulator.type}set modulationType(e){this._modulator.type=e}get phase(){return this._carrier.phase}set phase(e){this._carrier.phase=e,this._modulator.phase=e}get partials(){return this._carrier.partials}set partials(e){this._carrier.partials=e}asArray(){return ds(this,arguments,void 0,function*(e=1024){return qc(this,e)})}dispose(){return super.dispose(),this.frequency.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this.modulationIndex.dispose(),this}},el=class e extends Gc{constructor(){let t=B(e.getDefaults(),arguments,[`frequency`,`width`]);super(t),this.name=`PulseOscillator`,this._widthGate=new bc({context:this.context,gain:0}),this._thresh=new Bc({context:this.context,mapping:e=>e<=0?-1:1}),this.width=new Cc({context:this.context,units:`audioRange`,value:t.width}),this._triangle=new Yc({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),Hs(this,[`width`,`frequency`,`detune`])}static getDefaults(){return Object.assign(Gc.getDefaults(),{detune:0,frequency:440,phase:0,type:`pulse`,width:.2})}_start(e){e=this.toSeconds(e),this._triangle.start(e),this._widthGate.gain.setValueAtTime(1,e)}_stop(e){e=this.toSeconds(e),this._triangle.stop(e),this._widthGate.gain.cancelScheduledValues(e),this._widthGate.gain.setValueAtTime(0,e)}_restart(e){this._triangle.restart(e),this._widthGate.gain.cancelScheduledValues(e),this._widthGate.gain.setValueAtTime(1,e)}get phase(){return this._triangle.phase}set phase(e){this._triangle.phase=e}get type(){return`pulse`}get baseType(){return`pulse`}get partials(){return[]}get partialCount(){return 0}set carrierType(e){this._triangle.type=e}asArray(){return ds(this,arguments,void 0,function*(e=1024){return qc(this,e)})}dispose(){return super.dispose(),this._triangle.dispose(),this.width.dispose(),this._widthGate.dispose(),this._thresh.dispose(),this}},tl=class e extends Gc{constructor(){let t=B(e.getDefaults(),arguments,[`frequency`,`type`,`spread`]);super(t),this.name=`FatOscillator`,this._oscillators=[],this.frequency=new Cc({context:this.context,units:`frequency`,value:t.frequency}),this.detune=new Cc({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,Hs(this,[`frequency`,`detune`])}static getDefaults(){return Object.assign(Yc.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(e){if(this._spread=e,this._oscillators.length>1){let t=-e/2,n=e/(this._oscillators.length-1);this._forEach((e,r)=>e.detune.value=t+n*r)}}get count(){return this._oscillators.length}set count(e){if(Xo(e,1),this._oscillators.length!==e){this._forEach(e=>e.dispose()),this._oscillators=[];for(let t=0;tthis.onstop(this):Ws});this.type===`custom`&&(n.partials=this._partials),this.frequency.connect(n.frequency),this.detune.connect(n.detune),n.detune.overridden=!1,n.connect(this.output),this._oscillators[t]=n}this.spread=this._spread,this.state===`started`&&this._forEach(e=>e.start())}}get phase(){return this._phase}set phase(e){this._phase=e,this._forEach((e,t)=>e.phase=this._phase+t/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 ds(this,arguments,void 0,function*(e=1024){return qc(this,e)})}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this._forEach(e=>e.dispose()),this}},nl=class e extends Gc{constructor(){let t=B(e.getDefaults(),arguments,[`frequency`,`modulationFrequency`]);super(t),this.name=`PWMOscillator`,this.sourceType=`pwm`,this._scale=new Zc({context:this.context,value:2}),this._pulse=new el({context:this.context,frequency:t.modulationFrequency}),this._pulse.carrierType=`sine`,this.modulationFrequency=this._pulse.frequency,this._modulator=new Yc({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),Hs(this,[`modulationFrequency`,`frequency`,`detune`])}static getDefaults(){return Object.assign(Gc.getDefaults(),{detune:0,frequency:440,modulationFrequency:.4,phase:0,type:`pwm`})}_start(e){e=this.toSeconds(e),this._modulator.start(e),this._pulse.start(e)}_stop(e){e=this.toSeconds(e),this._modulator.stop(e),this._pulse.stop(e)}_restart(e){this._modulator.restart(e),this._pulse.restart(e)}get type(){return`pwm`}get baseType(){return`pwm`}get partials(){return[]}get partialCount(){return 0}get phase(){return this._modulator.phase}set phase(e){this._modulator.phase=e}asArray(){return ds(this,arguments,void 0,function*(e=1024){return qc(this,e)})}dispose(){return super.dispose(),this._pulse.dispose(),this._scale.dispose(),this._modulator.dispose(),this}},rl={am:Qc,fat:tl,fm:$c,oscillator:Yc,pulse:el,pwm:nl},il=class e extends Gc{constructor(){let t=B(e.getDefaults(),arguments,[`frequency`,`type`]);super(t),this.name=`OmniOscillator`,this.frequency=new Cc({context:this.context,units:`frequency`,value:t.frequency}),this.detune=new Cc({context:this.context,units:`cents`,value:t.detune}),Hs(this,[`frequency`,`detune`]),this.set(t)}static getDefaults(){return Object.assign(Yc.getDefaults(),$c.getDefaults(),Qc.getDefaults(),tl.getDefaults(),el.getDefaults(),nl.getDefaults())}_start(e){this._oscillator.start(e)}_stop(e){this._oscillator.stop(e)}_restart(e){return this._oscillator.restart(e),this}get type(){let e=``;return[`am`,`fm`,`fat`].some(e=>this._sourceType===e)&&(e=this._sourceType),e+this._oscillator.type}set type(e){e.substr(0,2)===`fm`?(this._createNewOscillator(`fm`),this._oscillator=this._oscillator,this._oscillator.type=e.substr(2)):e.substr(0,2)===`am`?(this._createNewOscillator(`am`),this._oscillator=this._oscillator,this._oscillator.type=e.substr(2)):e.substr(0,3)===`fat`?(this._createNewOscillator(`fat`),this._oscillator=this._oscillator,this._oscillator.type=e.substr(3)):e===`pwm`?(this._createNewOscillator(`pwm`),this._oscillator=this._oscillator):e===`pulse`?this._createNewOscillator(`pulse`):(this._createNewOscillator(`oscillator`),this._oscillator=this._oscillator,this._oscillator.type=e)}get partials(){return this._oscillator.partials}set partials(e){!this._getOscType(this._oscillator,`pulse`)&&!this._getOscType(this._oscillator,`pwm`)&&(this._oscillator.partials=e)}get partialCount(){return this._oscillator.partialCount}set partialCount(e){!this._getOscType(this._oscillator,`pulse`)&&!this._getOscType(this._oscillator,`pwm`)&&(this._oscillator.partialCount=e)}set(e){return Reflect.has(e,`type`)&&e.type&&(this.type=e.type),super.set(e),this}_createNewOscillator(e){if(e!==this._sourceType){this._sourceType=e;let t=rl[e],n=this.now();if(this._oscillator){let e=this._oscillator;e.stop(n),this.context.setTimeout(()=>e.dispose(),this.blockTime)}this._oscillator=new t({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),this.state===`started`&&this._oscillator.start(n)}}get phase(){return this._oscillator.phase}set phase(e){this._oscillator.phase=e}get sourceType(){return this._sourceType}set sourceType(e){let t=`sine`;this._oscillator.type!==`pwm`&&this._oscillator.type!==`pulse`&&(t=this._oscillator.type),e===`fm`?this.type=`fm`+t:e===`am`?this.type=`am`+t:e===`fat`?this.type=`fat`+t:e===`oscillator`?this.type=t:e===`pulse`?this.type=`pulse`:e===`pwm`&&(this.type=`pwm`)}_getOscType(e,t){return e instanceof rl[t]}get baseType(){return this._oscillator.baseType}set baseType(e){!this._getOscType(this._oscillator,`pulse`)&&!this._getOscType(this._oscillator,`pwm`)&&e!==`pulse`&&e!==`pwm`&&(this._oscillator.baseType=e)}get width(){if(this._getOscType(this._oscillator,`pulse`))return this._oscillator.width}get count(){if(this._getOscType(this._oscillator,`fat`))return this._oscillator.count}set count(e){this._getOscType(this._oscillator,`fat`)&&Wo(e)&&(this._oscillator.count=e)}get spread(){if(this._getOscType(this._oscillator,`fat`))return this._oscillator.spread}set spread(e){this._getOscType(this._oscillator,`fat`)&&Wo(e)&&(this._oscillator.spread=e)}get modulationType(){if(this._getOscType(this._oscillator,`fm`)||this._getOscType(this._oscillator,`am`))return this._oscillator.modulationType}set modulationType(e){(this._getOscType(this._oscillator,`fm`)||this._getOscType(this._oscillator,`am`))&&Jo(e)&&(this._oscillator.modulationType=e)}get modulationIndex(){if(this._getOscType(this._oscillator,`fm`))return this._oscillator.modulationIndex}get harmonicity(){if(this._getOscType(this._oscillator,`fm`)||this._getOscType(this._oscillator,`am`))return this._oscillator.harmonicity}get modulationFrequency(){if(this._getOscType(this._oscillator,`pwm`))return this._oscillator.modulationFrequency}asArray(){return ds(this,arguments,void 0,function*(e=1024){return qc(this,e)})}dispose(){return super.dispose(),this.detune.dispose(),this.frequency.dispose(),this._oscillator.dispose(),this}};function al(e,t=1/0){let n=new WeakMap;return function(r,i){Reflect.defineProperty(r,i,{configurable:!0,enumerable:!0,get:function(){return n.get(this)},set:function(r){Xo(r,e,t),n.set(this,r)}})}}function ol(e,t=1/0){let n=new WeakMap;return function(r,i){Reflect.defineProperty(r,i,{configurable:!0,enumerable:!0,get:function(){return n.get(this)},set:function(r){Xo(this.toSeconds(r),e,t),n.set(this,r)}})}}var sl=class e extends Gc{constructor(){let t=B(e.getDefaults(),arguments,[`url`,`onload`]);super(t),this.name=`Player`,this._activeSources=new Set,this._buffer=new Gs({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(Gc.getDefaults(),{autostart:!1,fadeIn:0,fadeOut:0,loop:!1,loopEnd:0,loopStart:0,onload:Ws,onerror:Ws,playbackRate:1,reverse:!1})}load(e){return ds(this,void 0,void 0,function*(){return yield this._buffer.load(e),this._onload(),this})}_onload(e=Ws){e(),this.autostart&&this.start()}_onSourceEnd(e){this.onstop(this),this._activeSources.delete(e),this._activeSources.size===0&&!this._synced&&this._state.getValueAtTime(this.now())===`started`&&(this._state.cancel(this.now()),this._state.setStateAtTime(`stopped`,this.now()))}start(e,t,n){return super.start(e,t,n),this}_start(e,t,n){t=this._loop?Ss(t,this._loopStart):Ss(t,0);let r=this.toSeconds(t),i=n;n=Ss(n,Math.max(this._buffer.duration-r,0));let a=this.toSeconds(n);a/=this._playbackRate,e=this.toSeconds(e);let o=new Kc({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(e+a),this._state.setStateAtTime(`stopped`,e+a,{implicitEnd:!0})),this._activeSources.add(o),this._loop&&Ho(i)?o.start(e,r):o.start(e,r,a-this.toSeconds(this.fadeOut))}_stop(e){let t=this.toSeconds(e);this._activeSources.forEach(e=>e.stop(t))}restart(e,t,n){return super.restart(e,t,n),this}_restart(e,t,n){var r;(r=[...this._activeSources].pop())==null||r.stop(e),this._start(e,t,n)}seek(e,t){let n=this.toSeconds(t);if(this._state.getValueAtTime(n)===`started`){let t=this.toSeconds(e);this._stop(n),this._start(n,t)}return this}setLoopPoints(e,t){return this.loopStart=e,this.loopEnd=t,this}get loopStart(){return this._loopStart}set loopStart(e){this._loopStart=e,this.buffer.loaded&&Xo(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&&Xo(this.toSeconds(e),0,this.buffer.duration),this._activeSources.forEach(t=>{t.loopEnd=e})}get buffer(){return this._buffer}set buffer(e){this._buffer.set(e)}get loop(){return this._loop}set loop(e){if(this._loop!==e&&(this._loop=e,this._activeSources.forEach(t=>{t.loop=e}),e)){let e=this._state.getNextState(`stopped`,this.now());e&&this._state.cancel(e.time)}}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e;let t=this.now(),n=this._state.getNextState(`stopped`,t);n&&n.implicitEnd&&(this._state.cancel(n.time),this._activeSources.forEach(e=>e.cancelStop())),this._activeSources.forEach(n=>{n.playbackRate.setValueAtTime(e,t)})}get reverse(){return this._buffer.reverse}set reverse(e){this._buffer.reverse=e}get loaded(){return this._buffer.loaded}dispose(){return super.dispose(),this._activeSources.forEach(e=>e.dispose()),this._activeSources.clear(),this._buffer.dispose(),this}};us([ol(0)],sl.prototype,`fadeIn`,void 0),us([ol(0)],sl.prototype,`fadeOut`,void 0);var cl=class e extends V{constructor(){let t=B(e.getDefaults(),arguments,[`attack`,`decay`,`sustain`,`release`]);super(t),this.name=`Envelope`,this._sig=new Cc({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(V.getDefaults(),{attack:.01,attackCurve:`linear`,decay:.1,decayCurve:`exponential`,release:1,releaseCurve:`exponential`,sustain:.5})}get value(){return this.getValueAtTime(this.now())}_getCurve(e,t){if(Jo(e))return e;{let n;for(n in ll)if(ll[n][t]===e)return n;return e}}_setCurve(e,t,n){if(Jo(n)&&Reflect.has(ll,n)){let r=ll[n];Go(r)?e!==`_decayCurve`&&(this[e]=r[t]):this[e]=r}else if(qo(n)&&e!==`_decayCurve`)this[e]=n;else throw Error(`Envelope: invalid curve: `+n)}get attackCurve(){return this._getCurve(this._attackCurve,`In`)}set attackCurve(e){this._setCurve(`_attackCurve`,`In`,e)}get releaseCurve(){return this._getCurve(this._releaseCurve,`Out`)}set releaseCurve(e){this._setCurve(`_releaseCurve`,`Out`,e)}get decayCurve(){return this._getCurve(this._decayCurve,`Out`)}set decayCurve(e){this._setCurve(`_decayCurve`,`Out`,e)}triggerAttack(e,t=1){this.log(`triggerAttack`,e,t),e=this.toSeconds(e);let n=this.toSeconds(this.attack),r=this.toSeconds(this.decay),i=this.getValueAtTime(e);if(i>0){let e=1/n;n=(1-i)/e}if(n0){let n=this.toSeconds(this.release);n{let e,t,n=[];for(e=0;e<128;e++)n[e]=Math.sin(e/127*(Math.PI/2));let r=[];for(e=0;e<127;e++)t=e/127,r[e]=(Math.sin(Math.PI*2*t*6.4-Math.PI/2)+1)/10+t*.83;r[127]=1;let i=[];for(e=0;e<128;e++)i[e]=Math.ceil(e/127*5)/5;let a=[];for(e=0;e<128;e++)t=e/127,a[e]=.5*(1-Math.cos(Math.PI*t));let o=[];for(e=0;e<128;e++){t=e/127;let n=t**3*4+.2,r=Math.cos(n*Math.PI*2*t);o[e]=Math.abs(r*(1-t))}function s(e){let t=Array(e.length);for(let n=0;nthis._original_triggerRelease(e),this._volume=this.output=new kc({context:this.context,volume:t.volume}),this.volume=this._volume.volume,Hs(this,`volume`)}static getDefaults(){return Object.assign(V.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 e=!1;return this._synced||(this._synced=!0,e=!0),e}_syncMethod(e,t){let n=this[`_original_`+e]=this[e];this[e]=(...e)=>{let r=e[t],i=this.context.transport.schedule(r=>{e[t]=r,n.apply(this,e)},r);this._scheduledEvents.push(i)}}unsync(){return this._scheduledEvents.forEach(e=>this.context.transport.clear(e)),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(e,t,n,r){let i=this.toSeconds(n),a=this.toSeconds(t);return this.triggerAttack(e,i,r),this.triggerRelease(i+a),this}dispose(){return super.dispose(),this._volume.dispose(),this.unsync(),this._scheduledEvents=[],this}},dl=class e extends ul{constructor(){let t=B(e.getDefaults(),arguments);super(t),this.portamento=t.portamento,this.onsilence=t.onsilence}static getDefaults(){return Object.assign(ul.getDefaults(),{detune:0,onsilence:Ws,portamento:0})}triggerAttack(e,t,n=1){this.log(`triggerAttack`,e,t,n);let r=this.toSeconds(t);return this._triggerEnvelopeAttack(r,n),this.setNote(e,r),this}triggerRelease(e){this.log(`triggerRelease`,e);let t=this.toSeconds(e);return this._triggerEnvelopeRelease(t),this}setNote(e,t){let n=this.toSeconds(t),r=e instanceof lc?e.toFrequency():e;if(this.portamento>0&&this.getLevelAtTime(n)>.05){let e=this.toSeconds(this.portamento);this.frequency.exponentialRampTo(r,e,n)}else this.frequency.setValueAtTime(r,n);return this}};us([ol(0)],dl.prototype,`portamento`,void 0);var fl=class e extends cl{constructor(){super(B(e.getDefaults(),arguments,[`attack`,`decay`,`sustain`,`release`])),this.name=`AmplitudeEnvelope`,this._gainNode=new bc({context:this.context,gain:0}),this.output=this._gainNode,this.input=this._gainNode,this._sig.connect(this._gainNode.gain),this.output=this._gainNode,this.input=this._gainNode}dispose(){return super.dispose(),this._gainNode.dispose(),this}},pl=class e extends dl{constructor(){let t=B(e.getDefaults(),arguments);super(t),this.name=`Synth`,this.oscillator=new il(Object.assign({context:this.context,detune:t.detune,onstop:()=>this.onsilence(this)},t.oscillator)),this.frequency=this.oscillator.frequency,this.detune=this.oscillator.detune,this.envelope=new fl(Object.assign({context:this.context},t.envelope)),this.oscillator.chain(this.envelope,this.output),Hs(this,[`oscillator`,`frequency`,`detune`,`envelope`])}static getDefaults(){return Object.assign(dl.getDefaults(),{envelope:Object.assign(Cs(cl.getDefaults(),Object.keys(V.getDefaults())),{attack:.005,decay:.1,release:1,sustain:.3}),oscillator:Object.assign(Cs(il.getDefaults(),[...Object.keys(Gc.getDefaults()),`frequency`,`detune`]),{type:`triangle`})})}_triggerEnvelopeAttack(e,t){if(this.envelope.triggerAttack(e,t),this.oscillator.start(e),this.envelope.sustain===0){let t=this.toSeconds(this.envelope.attack),n=this.toSeconds(this.envelope.decay);this.oscillator.stop(e+t+n)}}_triggerEnvelopeRelease(e){this.envelope.triggerRelease(e),this.oscillator.stop(e+this.toSeconds(this.envelope.release))}getLevelAtTime(e){return e=this.toSeconds(e),this.envelope.getValueAtTime(e)}dispose(){return super.dispose(),this.oscillator.dispose(),this.envelope.dispose(),this}},ml=class e extends pl{constructor(){let t=B(e.getDefaults(),arguments);super(t),this.name=`MembraneSynth`,this.portamento=0,this.pitchDecay=t.pitchDecay,this.octaves=t.octaves,Hs(this,[`oscillator`,`envelope`])}static getDefaults(){return ys(dl.getDefaults(),pl.getDefaults(),{envelope:{attack:.001,attackCurve:`exponential`,decay:.4,release:1.4,sustain:.01},octaves:10,oscillator:{type:`sine`},pitchDecay:.05})}setNote(e,t){let n=this.toSeconds(t),r=this.toFrequency(e instanceof lc?e.toFrequency():e),i=r*this.octaves;return this.oscillator.frequency.setValueAtTime(i,n),this.oscillator.frequency.exponentialRampToValueAtTime(r,n+this.toSeconds(this.pitchDecay)),this}dispose(){return super.dispose(),this}};us([al(0)],ml.prototype,`octaves`,void 0),us([ol(0)],ml.prototype,`pitchDecay`,void 0);var hl=new Set;function gl(e){hl.add(e)}function _l(e,t){let n=`registerProcessor("${e}", ${t})`;hl.add(n)}gl(` + /** + * The base AudioWorkletProcessor for use in Tone.js. Works with the {@link ToneAudioWorklet}. + */ + class ToneAudioWorkletProcessor extends AudioWorkletProcessor { + + constructor(options) { + + super(options); + /** + * If the processor was disposed or not. Keep alive until it's disposed. + */ + this.disposed = false; + /** + * The number of samples in the processing block + */ + this.blockSize = 128; + /** + * the sample rate + */ + this.sampleRate = sampleRate; + + this.port.onmessage = (event) => { + // when it receives a dispose + if (event.data === "dispose") { + this.disposed = true; + } + }; + } + } +`),gl(` + /** + * Abstract class for a single input/output processor. + * has a 'generate' function which processes one sample at a time + */ + class SingleIOProcessor extends ToneAudioWorkletProcessor { + + constructor(options) { + super(Object.assign(options, { + numberOfInputs: 1, + numberOfOutputs: 1 + })); + /** + * Holds the name of the parameter and a single value of that + * parameter at the current sample + * @type { [name: string]: number } + */ + this.params = {} + } + + /** + * Generate an output sample from the input sample and parameters + * @abstract + * @param input number + * @param channel number + * @param parameters { [name: string]: number } + * @returns number + */ + generate(){} + + /** + * Update the private params object with the + * values of the parameters at the given index + * @param parameters { [name: string]: Float32Array }, + * @param index number + */ + updateParams(parameters, index) { + for (const paramName in parameters) { + const param = parameters[paramName]; + if (param.length > 1) { + this.params[paramName] = parameters[paramName][index]; + } else { + this.params[paramName] = parameters[paramName][0]; + } + } + } + + /** + * Process a single frame of the audio + * @param inputs Float32Array[][] + * @param outputs Float32Array[][] + */ + process(inputs, outputs, parameters) { + const input = inputs[0]; + const output = outputs[0]; + // get the parameter values + const channelCount = Math.max(input && input.length || 0, output.length); + for (let sample = 0; sample < this.blockSize; sample++) { + this.updateParams(parameters, sample); + for (let channel = 0; channel < channelCount; channel++) { + const inputSample = input && input.length ? input[channel][sample] : 0; + output[channel][sample] = this.generate(inputSample, channel, this.params); + } + } + return !this.disposed; + } + }; +`),gl(` + /** + * A multichannel buffer for use within an AudioWorkletProcessor as a delay line + */ + class DelayLine { + + constructor(size, channels) { + this.buffer = []; + this.writeHead = [] + this.size = size; + + // create the empty channels + for (let i = 0; i < channels; i++) { + this.buffer[i] = new Float32Array(this.size); + this.writeHead[i] = 0; + } + } + + /** + * Push a value onto the end + * @param channel number + * @param value number + */ + push(channel, value) { + this.writeHead[channel] += 1; + if (this.writeHead[channel] > this.size) { + this.writeHead[channel] = 0; + } + this.buffer[channel][this.writeHead[channel]] = value; + } + + /** + * Get the recorded value of the channel given the delay + * @param channel number + * @param delay number delay samples + */ + get(channel, delay) { + let readHead = this.writeHead[channel] - Math.floor(delay); + if (readHead < 0) { + readHead += this.size; + } + return this.buffer[channel][readHead]; + } + } +`),_l(`feedback-comb-filter`,` + class FeedbackCombFilterWorklet extends SingleIOProcessor { + + constructor(options) { + super(options); + this.delayLine = new DelayLine(this.sampleRate, options.channelCount || 2); + } + + static get parameterDescriptors() { + return [{ + name: "delayTime", + defaultValue: 0.1, + minValue: 0, + maxValue: 1, + automationRate: "k-rate" + }, { + name: "feedback", + defaultValue: 0.5, + minValue: 0, + maxValue: 0.9999, + automationRate: "k-rate" + }]; + } + + generate(input, channel, parameters) { + const delayedSample = this.delayLine.get(channel, parameters.delayTime * this.sampleRate); + this.delayLine.push(channel, input + delayedSample * parameters.feedback); + return delayedSample; + } + } +`);var vl=class e extends ul{constructor(){let t=B(e.getDefaults(),arguments,[`voice`,`options`]);super(t),this.name=`PolySynth`,this._availableVoices=[],this._activeVoices=[],this._voices=[],this._gcTimeout=-1,this._averageActiveVoices=0,this._syncedRelease=e=>this.releaseAll(e),z(!Wo(t.voice),`DEPRECATED: The polyphony count is no longer the first argument.`);let n=t.voice.getDefaults();this.options=Object.assign(n,t.options),this.voice=t.voice,this.maxPolyphony=t.maxPolyphony,this._dummyVoice=this._getNextAvailableVoice();let r=this._voices.indexOf(this._dummyVoice);this._voices.splice(r,1),this._gcTimeout=this.context.setInterval(this._collectGarbage.bind(this),1)}static getDefaults(){return Object.assign(ul.getDefaults(),{maxPolyphony:32,options:{},voice:pl})}get activeVoices(){return this._activeVoices.length}_makeVoiceAvailable(e){this._availableVoices.push(e);let 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)){let e=this._availableVoices.shift(),t=this._voices.indexOf(e);this._voices.splice(t,1),this.context.isOffline||e.dispose()}}_triggerAttack(e,t,n){e.forEach(e=>{let r=new Nc(this.context,e).toMidi(),i=this._getNextAvailableVoice();i&&(i.triggerAttack(e,t,n),this._activeVoices.push({midi:r,voice:i,released:!1}),this.log(`triggerAttack`,e,t))})}_triggerRelease(e,t){e.forEach(e=>{let n=new Nc(this.context,e).toMidi(),r=this._activeVoices.find(({midi:e,released:t})=>e===n&&!t);r&&(r.voice.triggerRelease(t),r.released=!0,this.log(`triggerRelease`,e,t))})}_scheduleEvent(e,t,n,r){z(!this.disposed,`Synth was already disposed`),n<=this.now()?e===`attack`?this._triggerAttack(t,n,r):this._triggerRelease(t,n):this.context.setTimeout(()=>{this.disposed||this._scheduleEvent(e,t,n,r)},n-this.now())}triggerAttack(e,t,n){Array.isArray(e)||(e=[e]);let r=this.toSeconds(t);return this._scheduleEvent(`attack`,e,r,n),this}triggerRelease(e,t){Array.isArray(e)||(e=[e]);let n=this.toSeconds(t);return this._scheduleEvent(`release`,e,n),this}triggerAttackRelease(e,t,n,r){let i=this.toSeconds(n);if(this.triggerAttack(e,i,r),qo(t)){z(qo(e),`If the duration is an array, the notes must also be an array`),e=e;for(let n=0;n0,`The duration must be greater than 0`),this.triggerRelease(e[n],i+a)}}else{let n=this.toSeconds(t);z(n>0,`The duration must be greater than 0`),this.triggerRelease(e,i+n)}return this}sync(){return this._syncState()&&(this._syncMethod(`triggerAttack`,1),this._syncMethod(`triggerRelease`,1),this.context.transport.on(`stop`,this._syncedRelease),this.context.transport.on(`pause`,this._syncedRelease),this.context.transport.on(`loopEnd`,this._syncedRelease)),this}set(e){let t=Cs(e,[`onsilence`,`context`]);return this.options=ys(this.options,t),this._voices.forEach(e=>e.set(t)),this._dummyVoice.set(t),this}get(){return this._dummyVoice.get()}releaseAll(e){let t=this.toSeconds(e);return this._activeVoices.forEach(({voice:e})=>{e.triggerRelease(t)}),this}dispose(){return super.dispose(),this._dummyVoice.dispose(),this._voices.forEach(e=>e.dispose()),this._activeVoices=[],this._availableVoices=[],this.context.clearInterval(this._gcTimeout),this}},yl=class e extends ul{constructor(){let t=B(e.getDefaults(),arguments,[`urls`,`onload`,`baseUrl`],`urls`);super(t),this.name=`Sampler`,this._activeSources=new Map;let n={};Object.keys(t.urls).forEach(e=>{let r=parseInt(e,10);if(z(Yo(e)||Wo(r)&&isFinite(r),`url key is neither a note or midi pitch: ${e}`),Yo(e)){let r=new lc(this.context,e).toMidi();n[r]=t.urls[e]}else Wo(r)&&isFinite(r)&&(n[r]=t.urls[r])}),this._buffers=new Mc({urls:n,onload:t.onload,baseUrl:t.baseUrl,onerror:t.onerror}),this.attack=t.attack,this.release=t.release,this.curve=t.curve,this._buffers.loaded&&Promise.resolve().then(t.onload)}static getDefaults(){return Object.assign(ul.getDefaults(),{attack:0,baseUrl:``,curve:`exponential`,onload:Ws,onerror:Ws,release:.1,urls:{}})}_findClosest(e){let t=0;for(;t<96;){if(this._buffers.has(e+t))return-t;if(this._buffers.has(e-t))return t;t++}throw Error(`No available buffers for note: ${e}`)}triggerAttack(e,t,n=1){return this.log(`triggerAttack`,e,t,n),Array.isArray(e)||(e=[e]),e.forEach(e=>{let r=ac(new lc(this.context,e).toFrequency()),i=Math.round(r),a=r-i,o=this._findClosest(i),s=i-o,c=this._buffers.get(s),l=ec(o+a),u=new Kc({url:c,context:this.context,curve:this.curve,fadeIn:this.attack,fadeOut:this.release,playbackRate:l}).connect(this.output);u.start(t,0,c.duration/l,n),qo(this._activeSources.get(i))||this._activeSources.set(i,[]),this._activeSources.get(i).push(u),u.onended=()=>{if(this._activeSources&&this._activeSources.has(i)){let e=this._activeSources.get(i),t=e.indexOf(u);t!==-1&&e.splice(t,1)}}}),this}triggerRelease(e,t){return this.log(`triggerRelease`,e,t),Array.isArray(e)||(e=[e]),e.forEach(e=>{let n=new lc(this.context,e).toMidi();if(this._activeSources.has(n)&&this._activeSources.get(n).length){let e=this._activeSources.get(n);t=this.toSeconds(t),e.forEach(e=>{e.stop(t)}),this._activeSources.set(n,[])}}),this}releaseAll(e){let t=this.toSeconds(e);return this._activeSources.forEach(e=>{for(;e.length;)e.shift().stop(t)}),this}sync(){return this._syncState()&&(this._syncMethod(`triggerAttack`,1),this._syncMethod(`triggerRelease`,1)),this}triggerAttackRelease(e,t,n,r=1){let i=this.toSeconds(n);return this.triggerAttack(e,i,r),qo(t)?(z(qo(e),`notes must be an array when duration is array`),e.forEach((e,n)=>{let r=t[Math.min(n,t.length-1)];this.triggerRelease(e,i+this.toSeconds(r))})):this.triggerRelease(e,i+this.toSeconds(t)),this}add(e,t,n){if(z(Yo(e)||isFinite(e),`note must be a pitch or midi: ${e}`),Yo(e)){let r=new lc(this.context,e).toMidi();this._buffers.add(r,t,n)}else this._buffers.add(e,t,n);return this}get loaded(){return this._buffers.loaded}dispose(){return super.dispose(),this._buffers.dispose(),this._activeSources.forEach(e=>{e.forEach(e=>e.dispose())}),this._activeSources.clear(),this}};us([ol(0)],yl.prototype,`attack`,void 0),us([ol(0)],yl.prototype,`release`,void 0);var bl=class e extends V{constructor(){let t=B(e.getDefaults(),arguments,[`pan`]);super(t),this.name=`Panner`,this._panner=this.context.createStereoPanner(),this.input=this._panner,this.output=this._panner,this.pan=new gc({context:this.context,param:this._panner.pan,value:t.pan,minValue:-1,maxValue:1}),this._panner.channelCount=t.channelCount,this._panner.channelCountMode=`explicit`,Hs(this,`pan`)}static getDefaults(){return Object.assign(V.getDefaults(),{pan:0,channelCount:1})}dispose(){return super.dispose(),this._panner.disconnect(),this.pan.dispose(),this}};_l(`bit-crusher`,` + class BitCrusherWorklet extends SingleIOProcessor { + + static get parameterDescriptors() { + return [{ + name: "bits", + defaultValue: 12, + minValue: 1, + maxValue: 16, + automationRate: 'k-rate' + }]; + } + + generate(input, _channel, parameters) { + const step = Math.pow(0.5, parameters.bits - 1); + const val = step * Math.floor(input / step + 0.5); + return val; + } + } +`);var xl=class e extends V{constructor(){let t=B(e.getDefaults(),arguments,[`solo`]);super(t),this.name=`Solo`,this.input=this.output=new bc({context:this.context}),e._allSolos.has(this.context)||e._allSolos.set(this.context,new Set),e._allSolos.get(this.context).add(this),this.solo=t.solo}static getDefaults(){return Object.assign(V.getDefaults(),{solo:!1})}get solo(){return this._isSoloed()}set solo(t){t?this._addSolo():this._removeSolo(),e._allSolos.get(this.context).forEach(e=>e._updateSolo())}get muted(){return this.input.gain.value===0}_addSolo(){e._soloed.has(this.context)||e._soloed.set(this.context,new Set),e._soloed.get(this.context).add(this)}_removeSolo(){e._soloed.has(this.context)&&e._soloed.get(this.context).delete(this)}_isSoloed(){return e._soloed.has(this.context)&&e._soloed.get(this.context).has(this)}_noSolos(){return!e._soloed.has(this.context)||e._soloed.has(this.context)&&e._soloed.get(this.context).size===0}_updateSolo(){this._isSoloed()||this._noSolos()?this.input.gain.value=1:this.input.gain.value=0}dispose(){return super.dispose(),e._allSolos.get(this.context).delete(this),this._removeSolo(),this}};xl._allSolos=new Map,xl._soloed=new Map;var Sl=class e extends V{constructor(){let t=B(e.getDefaults(),arguments,[`pan`,`volume`]);super(t),this.name=`PanVol`,this._panner=this.input=new bl({context:this.context,pan:t.pan,channelCount:t.channelCount}),this.pan=this._panner.pan,this._volume=this.output=new kc({context:this.context,volume:t.volume}),this.volume=this._volume.volume,this._panner.connect(this._volume),this.mute=t.mute,Hs(this,[`pan`,`volume`])}static getDefaults(){return Object.assign(V.getDefaults(),{mute:!1,pan:0,volume:0,channelCount:1})}get mute(){return this._volume.mute}set mute(e){this._volume.mute=e}dispose(){return super.dispose(),this._panner.dispose(),this.pan.dispose(),this._volume.dispose(),this.volume.dispose(),this}},Cl=class e extends V{constructor(){let t=B(e.getDefaults(),arguments,[`volume`,`pan`]);super(t),this.name=`Channel`,this._solo=this.input=new xl({solo:t.solo,context:this.context}),this._panVol=this.output=new Sl({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),Hs(this,[`pan`,`volume`])}static getDefaults(){return Object.assign(V.getDefaults(),{pan:0,volume:0,mute:!1,solo:!1,channelCount:1})}get solo(){return this._solo.solo}set solo(e){this._solo.solo=e}get muted(){return this._solo.muted||this.mute}get mute(){return this._panVol.mute}set mute(e){this._panVol.mute=e}_getBus(t){return e.buses.has(t)||e.buses.set(t,new bc({context:this.context})),e.buses.get(t)}send(e,t=0){let n=this._getBus(e),r=new bc({context:this.context,units:`decibels`,gain:t});return this.connect(r),r.connect(n),r}receive(e){return this._getBus(e).connect(this),this}dispose(){return super.dispose(),this._panVol.dispose(),this.pan.dispose(),this.volume.dispose(),this._solo.dispose(),this}};Cl.buses=new Map,Ys().transport;function wl(){return Ys().transport}Ys().destination,Ys().destination,Ys().listener,Ys().draw,Ys();function Tl(e,t,n=0){let r=0;for(let i=0;i>>0}function El(e,t){let n=Dl(e,t,e.currentIndex);return e.currentIndex+=t,n}function Dl(e,t,n=0){let r=0n;for(let i=0;i>>0}function kl(e,t,n){for(let r=0;r>r*8&255}function U(e,t){e[e.currentIndex++]=t&255,e[e.currentIndex++]=t>>8}function W(e,t){kl(e,t,4)}function Al(e,t){let n=BigInt(t);for(let t=0n;t<8n;t++)e[e.currentIndex++]=Number(n>>t*8n&255n)}function jl(e,t){let n=t<<8|e;return n>32767?n-65536:n}var Ml=class extends Uint8Array{currentIndex=0;slice(e,t){let n=super.slice(e,t);return n.currentIndex=0,n}};function Nl(e,t=e.length,n=0){let r=``;for(let i=0;i0&&t.length>n&&(t=t.slice(0,n));for(let n=0;nt.length)for(let r=0;r>7!=1)break}return t}function Rl(e){let t=``;for(let n=0;n{var e=Uint8Array,t=Uint16Array,n=Int32Array,r=new e([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new e([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new e([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),o=function(e,r){for(var i=new t(31),a=0;a<31;++a)i[a]=r+=1<>1|(m&21845)<<1,p=(p&52428)>>2|(p&13107)<<2,p=(p&61680)>>4|(p&3855)<<4,f[m]=((p&65280)>>8|(p&255)<<8)>>1;var p,m,h=function(e,n,r){for(var i=e.length,a=0,o=new t(n);a>l]=u}else for(c=new t(i),a=0;a>15-e[a]);return c},g=new e(288);for(m=0;m<144;++m)g[m]=8;var m;for(m=144;m<256;++m)g[m]=9;var m;for(m=256;m<280;++m)g[m]=7;var m;for(m=280;m<288;++m)g[m]=8;var m,_=new e(32);for(m=0;m<32;++m)_[m]=5;var m,v=h(g,9,1),y=h(_,5,1),b=function(e){for(var t=e[0],n=1;nt&&(t=e[n]);return t},x=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},S=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},C=function(e){return(e+7)/8|0},w=function(t,n,r){return(n==null||n<0)&&(n=0),(r==null||r>t.length)&&(r=t.length),new e(t.subarray(n,r))},T=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],E=function(e,t,n){var r=Error(t||T[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,E),!n)throw r;return r},D=function(t,n,o,s){var l=t.length,u=s?s.length:0;if(!l||n.f&&!n.l)return o||new e(0);var f=!o,p=f||n.i!=2,m=n.i;f&&(o=new e(l*3));var g=function(t){var n=o.length;if(t>n){var r=new e(Math.max(n*2,t));r.set(o),o=r}},_=n.f||0,T=n.p||0,D=n.b||0,O=n.l,ee=n.d,te=n.m,ne=n.n,re=l*8;do{if(!O){_=x(t,T,1);var ie=x(t,T+1,3);if(T+=3,ie)if(ie==1)O=v,ee=y,te=9,ne=5;else if(ie==2){var ae=x(t,T,31)+257,oe=x(t,T+10,15)+4,k=ae+x(t,T+5,31)+1;T+=14;for(var A=new e(k),se=new e(19),ce=0;ce>4;if(P<16)A[ce++]=P;else{var ue=0,de=0;for(P==16?(de=3+x(t,T,3),T+=2,ue=A[ce-1]):P==17?(de=3+x(t,T,7),T+=3):P==18&&(de=11+x(t,T,127),T+=7);de--;)A[ce++]=ue}}var fe=A.subarray(0,ae),pe=A.subarray(ae);te=b(fe),ne=b(pe),O=h(fe,te,1),ee=h(pe,ne,1)}else E(1);else{var P=C(T)+4,me=t[P-4]|t[P-3]<<8,he=P+me;if(he>l){m&&E(0);break}p&&g(D+me),o.set(t.subarray(P,he),D),n.b=D+=me,n.p=T=he*8,n.f=_;continue}if(T>re){m&&E(0);break}}p&&g(D+131072);for(var ge=(1<>4;if(T+=ue&15,T>re){m&&E(0);break}if(ue||E(2),ye<256)o[D++]=ye;else if(ye==256){ve=T,O=null;break}else{var be=ye-254;if(ye>264){var ce=ye-257,xe=r[ce];be=x(t,T,(1<>4;Se||E(3),T+=Se&15;var pe=d[Ce];if(Ce>3){var xe=i[Ce];pe+=S(t,T)&(1<re){m&&E(0);break}p&&g(D+131072);var we=D+be;if(Dt.length+e,0);r&&(a+=4,i=`LIST`);let o;n?(o=new Ml(8),Al(o,a)):(o=new Ml(4),W(o,a));let s=[Fl(i),o];return r&&s.push(Fl(e)),s.push(...t),a%2!=0&&s.push(new Uint8Array(1)),s}static writeParts(e,t,n=!1,r=!1){let i=n?12:8,a=e,o=t.reduce((e,t)=>t.length+e,0),s=o;r&&(i+=4,s+=4,a=`LIST`);let c=i+o;c%2!=0&&c++;let l=new Ml(c);Il(l,a),n?Al(l,s):W(l,s),r&&Il(l,e);for(let e of t)l.set(e,i),i+=e.length;return l}static findListType(e,t){return e.find(e=>e.header===`LIST`?(e.data.currentIndex=4,Nl(e.data,4)===t):!1)}};function q(e,t){return{...t,...e}}var J=class e{static infoEnabled=!1;static warnEnabled=!0;static groupEnabled=!1;static setLogLevel(e,t,n){this.infoEnabled=e,this.warnEnabled=t,this.groupEnabled=n}static info(...e){this.infoEnabled&&console.info(...e)}static warn(...e){this.warnEnabled&&console.warn(...e)}static group(...e){this.groupEnabled&&console.group(...e)}static groupCollapsed(...e){this.groupEnabled&&console.groupCollapsed(...e)}static groupEnd(){this.groupEnabled&&console.groupEnd()}static unsupported(e,t,n=``){this.infoEnabled&&this.info(`%cUnsupported %c${e}%c message: %c${Rl(t)}%c. ${n}`,G.warn,G.recognized,G.warn,G.unrecognized,G.warn)}static gmInfo(e,t,n=``){this.infoEnabled&&this.coolInfo(`General MIDI ${e}`,t,n)}static gmFail(e,t){this.infoEnabled&&this.unsupported(`General MIDI ${e}`,t)}static gsInfo(e,t,n=``){this.infoEnabled&&this.coolInfo(`Roland GS ${e}`,t,n)}static gsFail(e,t,n=``){this.infoEnabled&&this.unsupported(`Roland GS ${e}`,t,n)}static xgInfo(e,t,n=``){this.infoEnabled&&this.coolInfo(`Yamaha XG ${e}`,t,n)}static xgFail(e,t,n=``){this.infoEnabled&&this.unsupported(`Yamaha XG ${e}`,t,n)}static coolInfo(t,n,r=``){this.infoEnabled&&(r?e.info(`%c${t}%c is now set to %c${n}%c ${r}.`,G.recognized,G.info,G.value,G.info):e.info(`%c${t}%c is now set to %c${n}%c.`,G.recognized,G.info,G.value,G.info))}},Vl={ConsoleColors:G,readBigEndian:Tl,readLittleEndian:Ol,readLittleEndianIndexed:H,readBinaryString:Nl,readBinaryStringIndexed:Pl,readVariableLengthQuantity:Ll,inflateSync:Bl},Hl={noteOff:128,noteOn:144,polyPressure:160,controllerChange:176,programChange:192,channelPressure:208,pitchWheel:224,systemExclusive:240,timecode:241,songPosition:242,songSelect:243,tuneRequest:246,clock:248,start:250,continue:251,stop:252,activeSensing:254,reset:255,sequenceNumber:0,text:1,copyright:2,trackName:3,instrumentName:4,lyric:5,marker:6,cuePoint:7,programName:8,midiChannelPrefix:32,midiPort:33,endOfTrack:47,setTempo:81,smpteOffset:84,timeSignature:88,keySignature:89,sequenceSpecific:127},Y={bankSelect:0,modulationWheel:1,breathController:2,undefinedCC3:3,footController:4,portamentoTime:5,dataEntryMSB:6,mainVolume:7,balance:8,undefinedCC9:9,pan:10,expression:11,effectControl1:12,effectControl2:13,undefinedCC14:14,undefinedCC15:15,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,undefinedCC20:20,undefinedCC21:21,undefinedCC22:22,undefinedCC23:23,undefinedCC24:24,undefinedCC25:25,undefinedCC26:26,undefinedCC27:27,undefinedCC28:28,undefinedCC29:29,undefinedCC30:30,undefinedCC31:31,bankSelectLSB:32,modulationWheelLSB:33,breathControllerLSB:34,undefinedCC3LSB:35,footControllerLSB:36,portamentoTimeLSB:37,dataEntryLSB:38,mainVolumeLSB:39,balanceLSB:40,undefinedCC9LSB:41,panLSB:42,expressionLSB:43,effectControl1LSB:44,effectControl2LSB:45,undefinedCC14LSB:46,undefinedCC15LSB:47,undefinedCC16LSB:48,undefinedCC17LSB:49,undefinedCC18LSB:50,undefinedCC19LSB:51,undefinedCC20LSB:52,undefinedCC21LSB:53,undefinedCC22LSB:54,undefinedCC23LSB:55,undefinedCC24LSB:56,undefinedCC25LSB:57,undefinedCC26LSB:58,undefinedCC27LSB:59,undefinedCC28LSB:60,undefinedCC29LSB:61,undefinedCC30LSB:62,undefinedCC31LSB:63,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,filterResonance:71,releaseTime:72,attackTime:73,brightness:74,decayTime:75,vibratoRate:76,vibratoDepth:77,vibratoDelay:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,undefinedCC85:85,undefinedCC86:86,undefinedCC87:87,undefinedCC88:88,undefinedCC89:89,undefinedCC90:90,reverbDepth:91,tremoloDepth:92,chorusDepth:93,variationDepth:94,phaserDepth:95,dataIncrement:96,dataDecrement:97,nonRegisteredParameterLSB:98,nonRegisteredParameterMSB:99,registeredParameterLSB:100,registeredParameterMSB:101,undefinedCC102LSB:102,undefinedCC103LSB:103,undefinedCC104LSB:104,undefinedCC105LSB:105,undefinedCC106LSB:106,undefinedCC107LSB:107,undefinedCC108LSB:108,undefinedCC109LSB:109,undefinedCC110LSB:110,undefinedCC111LSB:111,undefinedCC112LSB:112,undefinedCC113LSB:113,undefinedCC114LSB:114,undefinedCC115LSB:115,undefinedCC116LSB:116,undefinedCC117LSB:117,undefinedCC118LSB:118,undefinedCC119LSB:119,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127};`${Math.random()}`,1/Math.cos(Math.PI/4)**2;var Ul=121,Wl=class{static getDefaultBank(e){return e===`gm2`?Ul:0}static getDrumBank(e){switch(e){default:throw Error(`${e} doesn't have a bank MSB for drums.`);case`gm2`:return 120;case`xg`:return 127}}static isXGDrum(e){return e===120||e===127}static isValidXGMSB(e){return this.isXGDrum(e)||e===64||e===Ul}static isSystemXG(e){return e===`gm2`||e===`xg`}static addBankOffset(e,t,n){return this.isXGDrum(e)&&n?e:Math.min(e+t,127)}static subtractBankOffset(e,t,n){return this.isXGDrum(e)&&n?e:Math.max(0,e-t)}},Gl=class e{static toMIDIString(e){return e.isGMGSDrum?`DRUM:${e.program}`:`${e.bankLSB}:${e.bankMSB}:${e.program}`}static fromMIDIString(e){let t=e.split(`:`);if(t.length>3||t.length<2)throw Error(`Invalid MIDI string: ${e}`);return e.startsWith(`DRUM`)?{bankMSB:0,bankLSB:0,program:Number.parseInt(t[1]),isGMGSDrum:!0}:{bankLSB:Number.parseInt(t[0]),bankMSB:Number.parseInt(t[1]),program:Number.parseInt(t[2]),isGMGSDrum:!1}}static toFullMIDIString(e){return`${this.toMIDIString(e)} ${e.isDrum?`D`:`M`} ${e.name}`}static fromFullMIDIString(t){let n=t.indexOf(` `),r=t.indexOf(` `,n+1);if(n===-1||r===-1)throw Error(`Invalid named MIDI string: ${t}`);let i=t.slice(0,Math.max(0,n)),a=t.slice(n+1,r),o=t.slice(Math.max(0,r+1));return{...e.fromMIDIString(i),isDrum:a===`D`,name:o}}static matches(e,t){return e.isGMGSDrum||t.isGMGSDrum?e.isGMGSDrum===t.isGMGSDrum&&e.program===t.program:e.program===t.program&&e.bankLSB===t.bankLSB&&e.bankMSB===t.bankMSB}static compare(e,t){return e.isGMGSDrum&&!t.isGMGSDrum?1:!e.isGMGSDrum&&t.isGMGSDrum?-1:e.program===t.program?e.bankMSB===t.bankMSB?e.bankLSB-t.bankLSB:e.bankMSB-t.bankMSB:e.program-t.program}static isXGDrum(e){return e.isDrum&&!e.isGMGSDrum}static selectPatch(t,n,r){if(t.length===0)throw Error(`No presets!`);n.isGMGSDrum&&Wl.isSystemXG(r)&&(n={...n,isGMGSDrum:!1,bankLSB:0,bankMSB:Wl.getDrumBank(r)});let{isGMGSDrum:i,bankLSB:a,bankMSB:o,program:s}=n,c=Wl.isSystemXG(r),l=Wl.isXGDrum(o)&&c,u=t.find(e=>this.matches(e,n));if(u&&(!l||l&&this.isXGDrum(u)))return u;let d=t=>{J.info(`%cPreset %c${e.toMIDIString(n)}%c not found. (${r}) Replaced with %c${this.toFullMIDIString(t)}`,G.warn,G.unrecognized,G.warn,G.value)};if(i){let e=t.find(e=>e.isGMGSDrum&&e.program===s);return e||(e=t.find(e=>e.isDrum&&e.program===s),e)?(d(e),e):(e=this.getAnyDrums(t,!1),d(e),e)}if(l){let e=t.find(e=>e.program===s&&e.isDrum&&!e.isGMGSDrum);return e||(e=t.find(e=>e.isDrum&&e.program===s),e&&e.program<49)?(d(e),e):(e=this.getAnyDrums(t,!0),d(e),e)}let f=t.filter(e=>e.program===s&&!e.isDrum);if(f.length===0)return d(t[0]),t[0];if(u=c?f.find(e=>e.bankLSB===a):f.find(e=>e.bankMSB===o),u)return d(u),u;if(a!==64||!c){let e=Math.max(o,a);if(u=f.find(t=>t.bankLSB===e||t.bankMSB===e),u)return d(u),u}return d(f[0]),f[0]}static getAnyDrums(e,t){return(t?e.find(e=>this.isXGDrum(e)):e.find(e=>e.isGMGSDrum))||(e.find(e=>e.isDrum)??e[0])}};Object.freeze({type:`Other`});function Kl(e){return e.toISOString().split(`.`)[0]+`Z`}var ql=[new Map([[`domingo`,`Sunday`],[`segunda-feira`,`Monday`],[`terça-feira`,`Tuesday`],[`quarta-feira`,`Wednesday`],[`quinta-feira`,`Thursday`],[`sexta-feira`,`Friday`],[`sábado`,`Saturday`],[`janeiro`,`January`],[`fevereiro`,`February`],[`março`,`March`],[`abril`,`April`],[`maio`,`May`],[`junho`,`June`],[`julho`,`July`],[`agosto`,`August`],[`setembro`,`September`],[`outubro`,`October`],[`novembro`,`November`],[`dezembro`,`December`]])];function Jl(e){for(let t of ql){let n=e;for(let[e,r]of t.entries()){let t=new RegExp(e,`gi`);n=n.replace(t,r)}let r=new Date(n);if(!Number.isNaN(r.getTime()))return r}}function Yl(e){let t=/^(\d{2})\.(\d{2})\.(\d{4})$/.exec(e);if(t){let e=Number.parseInt(t[1]),n=Number.parseInt(t[2])-1,r=Number.parseInt(t[3]),i=new Date(r,n,e);if(!Number.isNaN(i.getTime()))return i}}function Xl(e){let t=/^(\d{1,2})\s{1,2}(\d{1,2})\s{1,2}(\d{2})$/.exec(e);if(t){let e=t[1],n=(Number.parseInt(t[2])+1).toString(),r=t[3],i=new Date(`${n}/${e}/${r}`);if(!Number.isNaN(i.getTime()))return i}}function Zl(e){let t=/\b\d{4}\b/.exec(e);return t?new Date(t[0]):void 0}function Ql(e){if(e=e.trim(),e.length===0)return new Date;let t=e.replaceAll(/\b(\d+)(st|nd|rd|th)\b/g,`$1`).replace(/\s+at\s+/i,` `),n=new Date(t);return Number.isNaN(n.getTime())?Jl(e)||Yl(e)||Xl(e)||Zl(e)||(J.warn(`Invalid date: "${e}". Replacing with the current date!`),new Date):n}var $l=new Int16Array(128).fill(0),eu=(e,t)=>$l[e]=t<<7;eu(Y.mainVolume,100),eu(Y.balance,64),eu(Y.expression,127),eu(Y.pan,64),eu(Y.filterResonance,64),eu(Y.releaseTime,64),eu(Y.attackTime,64),eu(Y.brightness,64),eu(Y.decayTime,64),eu(Y.vibratoRate,64),eu(Y.vibratoDepth,64),eu(Y.vibratoDelay,64),eu(Y.generalPurposeController6,64),eu(Y.generalPurposeController8,64),eu(Y.registeredParameterLSB,127),eu(Y.registeredParameterMSB,127),eu(Y.nonRegisteredParameterLSB,0),eu(Y.nonRegisteredParameterMSB,0);var tu=new Int8Array(128).fill(127);tu[35]=0,tu[36]=0,Y.modulationWheel,Y.expression,Y.sustainPedal,Y.portamentoOnOff,Y.sostenutoPedal,Y.softPedal,Y.registeredParameterMSB,Y.registeredParameterLSB,new Set([Y.dataDecrement,Y.dataIncrement,Y.dataEntryMSB,Y.dataEntryLSB,Y.registeredParameterLSB,Y.registeredParameterMSB,Y.nonRegisteredParameterLSB,Y.nonRegisteredParameterMSB,Y.bankSelect,Y.bankSelectLSB,Y.resetAllControllers,Y.monoModeOn,Y.polyModeOn]);var nu={linear:0,nearestNeighbor:1,hermite:2},ru=ru===void 0?{}:ru,iu=!1,au;ru.isInitialized=new Promise(e=>au=e);var ou=function(e){var t,n,r,i,a,o,s,c=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=`,l=``,u=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,``);do i=c.indexOf(e.charAt(u++)),a=c.indexOf(e.charAt(u++)),o=c.indexOf(e.charAt(u++)),s=c.indexOf(e.charAt(u++)),t=i<<2|a>>4,n=(15&a)<<4|o>>2,r=(3&o)<<6|s,l+=String.fromCharCode(t),o!==64&&(l+=String.fromCharCode(n)),s!==64&&(l+=String.fromCharCode(r));while(u1&&(p.thisProgram=process.argv[1].replace(/\\/g,`/`)),p.arguments=process.argv.slice(2),process.on(`uncaughtException`,function(e){if(!(e instanceof ke))throw e}),process.on(`unhandledRejection`,function(e,t){process.exit(1)}),p.quit=function(e){process.exit(e)},p.inspect=function(){return`[Emscripten Module object]`}):v?(typeof read<`u`&&(p.read=function(e){return read(e)}),p.readBinary=function(e){var t;return typeof readbuffer==`function`?new Uint8Array(readbuffer(e)):(O(typeof(t=read(e,`binary`))==`object`),t)},typeof scriptArgs<`u`?p.arguments=scriptArgs:typeof arguments<`u`&&(p.arguments=arguments),typeof quit==`function`&&(p.quit=function(e){quit(e)})):(h||g)&&(h?document.currentScript&&(y=document.currentScript.src):y=self.location.href,y=y.indexOf(`blob:`)===0?``:y.split(`/`).slice(0,-1).join(`/`)+`/`,p.read=function(e){var t=new XMLHttpRequest;return t.open(`GET`,e,!1),t.send(null),t.responseText},g&&(p.readBinary=function(e){var t=new XMLHttpRequest;return t.open(`GET`,e,!1),t.responseType=`arraybuffer`,t.send(null),new Uint8Array(t.response)}),p.readAsync=function(e,t,n){var r=new XMLHttpRequest;r.open(`GET`,e,!0),r.responseType=`arraybuffer`,r.onload=function(){if(r.status==200||r.status==0&&r.response){t(r.response);return}n()},r.onerror=n,r.send(null)},p.setWindowTitle=function(e){document.title=e});var x=p.print||(typeof console<`u`?console.log.bind(console):typeof print<`u`?print:null),S=p.printErr||(typeof printErr<`u`?printErr:typeof console<`u`&&console.warn.bind(console)||x);for(e in m)m.hasOwnProperty(e)&&(p[e]=m[e]);function C(e){var t=c;return c=c+e+15&-16,t}function w(e,t){return t||=16,e=Math.ceil(e/t)*t}function T(e){T.shown||={},T.shown[e]||(T.shown[e]=1,S(e))}m=void 0;var E={"f64-rem":function(e,t){return e%t},debugger:function(){}},D=0;function O(e,t){e||je(`Assertion failed: `+t)}function ee(e){var t=p[`_`+e];return O(t,`Cannot call unknown function `+e+`, make sure it is exported`),t}var te={stackSave:function(){Oe()},stackRestore:function(){De()},arrayToC:function(e){var t,n,r=Ee(e.length);return t=e,n=r,i.set(t,n),r},stringToC:function(e){var t=0;if(e!=null&&e!==0){var n=(e.length<<2)+1;t=Ee(n),k(e,t,n)}return t}},ne={string:te.stringToC,array:te.arrayToC};function re(e,t,n,r,i){var a=ee(e),o=[],s=0;if(r)for(var c=0;c>0],(r!=0||t)&&(s++,!t||s!=t););t||=s;var c=``;if(o<128){for(;t>0;)i=String.fromCharCode.apply(String,a.subarray(e,e+Math.min(t,1024))),c=c?c+i:i,e+=1024,t-=1024;return c}return n=e,function(e,t){for(var n=t;e[n];)++n;if(n-t>16&&e.subarray&&ae)return ae.decode(e.subarray(t,n));for(var r,i,a,o,s,c=``;;){if(!(r=e[t++]))return c;if(!(128&r)){c+=String.fromCharCode(r);continue}if(i=63&e[t++],(224&r)==192){c+=String.fromCharCode((31&r)<<6|i);continue}if(a=63&e[t++],(240&r)==224?r=(15&r)<<12|i<<6|a:(o=63&e[t++],(248&r)==240?r=(7&r)<<18|i<<12|a<<6|o:(s=63&e[t++],r=(252&r)==248?(3&r)<<24|i<<18|a<<12|o<<6|s:(1&r)<<30|i<<24|a<<18|o<<12|s<<6|63&e[t++])),r<65536)c+=String.fromCharCode(r);else{var l=r-65536;c+=String.fromCharCode(55296|l>>10,56320|1023&l)}}}(a,n)}var ae=typeof TextDecoder<`u`?new TextDecoder(`utf8`):void 0;function oe(e,t,n,r){if(!(r>0))return 0;for(var i=n,a=n+r-1,o=0;o=55296&&s<=57343&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++o)),s<=127){if(n>=a)break;t[n++]=s}else if(s<=2047){if(n+1>=a)break;t[n++]=192|s>>6,t[n++]=128|63&s}else if(s<=65535){if(n+2>=a)break;t[n++]=224|s>>12,t[n++]=128|s>>6&63,t[n++]=128|63&s}else if(s<=2097151){if(n+3>=a)break;t[n++]=240|s>>18,t[n++]=128|s>>12&63,t[n++]=128|s>>6&63,t[n++]=128|63&s}else if(s<=67108863){if(n+4>=a)break;t[n++]=248|s>>24,t[n++]=128|s>>18&63,t[n++]=128|s>>12&63,t[n++]=128|s>>6&63,t[n++]=128|63&s}else{if(n+5>=a)break;t[n++]=252|s>>30,t[n++]=128|s>>24&63,t[n++]=128|s>>18&63,t[n++]=128|s>>12&63,t[n++]=128|s>>6&63,t[n++]=128|63&s}}return t[n]=0,n-i}function k(e,t,n){return oe(e,a,t,n)}typeof TextDecoder<`u`&&new TextDecoder(`utf-16le`);function A(e,t){return e%t>0&&(e+=t-e%t),e}function se(e){p.buffer=r=e}function ce(){p.HEAP8=i=new Int8Array(r),p.HEAP16=new Int16Array(r),p.HEAP32=o=new Int32Array(r),p.HEAPU8=a=new Uint8Array(r),p.HEAPU16=new Uint16Array(r),p.HEAPU32=new Uint32Array(r),p.HEAPF32=new Float32Array(r),p.HEAPF64=new Float64Array(r)}function le(){var e=p.usingWasm?65536:16777216,t=2147483648-e;if(o[f>>2]>t)return!1;var n=M;for(M=Math.max(M,16777216);M>2];)M=M<=536870912?A(2*M,e):Math.min(A((3*M+2147483648)/4,e),t);var r=p.reallocBuffer(M);return r&&r.byteLength==M?(se(r),ce(),!0):(M=n,!1)}s=c=l=u=d=f=0,p.reallocBuffer||=function(e){try{if(ArrayBuffer.transfer)t=ArrayBuffer.transfer(r,e);else{var t,n=i;t=new ArrayBuffer(e),new Int8Array(t).set(n)}}catch{return!1}return!!Te(t)&&t};try{Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,`byteLength`).get)(new ArrayBuffer(4))}catch{}var j=p.TOTAL_STACK||5242880,M=p.TOTAL_MEMORY||16777216;function N(){return M}function P(e){for(;e.length>0;){var t=e.shift();if(typeof t==`function`){t();continue}var n=t.func;typeof n==`number`?t.arg===void 0?p.dynCall_v(n):p.dynCall_vi(n,t.arg):n(t.arg===void 0?null:t.arg)}}M>2]=d,p.wasmTableSize=4,p.wasmMaxTableSize=4,p.asmGlobalArg={},p.asmLibraryArg={abort:je,assert:O,enlargeMemory:le,getTotalMemory:N,abortOnCannotGrowMemory:function(){je(`Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value `+M+`, (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 `)},invoke_iii:function(e,t,n){var r=Oe();try{return p.dynCall_iii(e,t,n)}catch(e){if(De(r),typeof e!=`number`&&e!==`longjmp`)throw e;p.setThrew(1,0)}},___assert_fail:function(e,t,n,r){je(`Assertion failed: `+ie(e)+`, at: `+[t?ie(t):`unknown filename`,n,r?ie(r):`unknown function`])},___setErrNo:function(e){return p.___errno_location&&(o[p.___errno_location()>>2]=e),e},_abort:function(){p.abort()},_emscripten_memcpy_big:function(e,t,n){return a.set(a.subarray(t,t+n),e),e},_llvm_floor_f64:_e,DYNAMICTOP_PTR:f,tempDoublePtr:Ce,ABORT:D,STACKTOP:l,STACK_MAX:u};var we=p.asm(p.asmGlobalArg,p.asmLibraryArg,r);p.asm=we,p.___errno_location=function(){return p.asm.___errno_location.apply(null,arguments)};var Te=p._emscripten_replace_memory=function(){return p.asm._emscripten_replace_memory.apply(null,arguments)};p._free=function(){return p.asm._free.apply(null,arguments)},p._malloc=function(){return p.asm._malloc.apply(null,arguments)},p._memcpy=function(){return p.asm._memcpy.apply(null,arguments)},p._memset=function(){return p.asm._memset.apply(null,arguments)},p._sbrk=function(){return p.asm._sbrk.apply(null,arguments)},p._stb_vorbis_js_channels=function(){return p.asm._stb_vorbis_js_channels.apply(null,arguments)},p._stb_vorbis_js_close=function(){return p.asm._stb_vorbis_js_close.apply(null,arguments)},p._stb_vorbis_js_decode=function(){return p.asm._stb_vorbis_js_decode.apply(null,arguments)},p._stb_vorbis_js_open=function(){return p.asm._stb_vorbis_js_open.apply(null,arguments)},p._stb_vorbis_js_sample_rate=function(){return p.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},p.establishStackSpace=function(){return p.asm.establishStackSpace.apply(null,arguments)},p.getTempRet0=function(){return p.asm.getTempRet0.apply(null,arguments)},p.runPostSets=function(){return p.asm.runPostSets.apply(null,arguments)},p.setTempRet0=function(){return p.asm.setTempRet0.apply(null,arguments)},p.setThrew=function(){return p.asm.setThrew.apply(null,arguments)};var Ee=p.stackAlloc=function(){return p.asm.stackAlloc.apply(null,arguments)},De=p.stackRestore=function(){return p.asm.stackRestore.apply(null,arguments)},Oe=p.stackSave=function(){return p.asm.stackSave.apply(null,arguments)};function ke(e){this.name=`ExitStatus`,this.message=`Program terminated with exit(`+e+`)`,this.status=e}function Ae(e){e||=p.arguments,!(ve>0)&&((function(){if(p.preRun)for(typeof p.preRun==`function`&&(p.preRun=[p.preRun]);p.preRun.length;)he(p.preRun.shift());P(ue)})(),!(ve>0)&&(p.calledRun||(p.setStatus?(p.setStatus(`Running...`),setTimeout(function(){setTimeout(function(){p.setStatus(``)},1),t()},1)):t())));function t(){!p.calledRun&&(p.calledRun=!0,D||(me||(me=!0,P(de)),P(fe),p.onRuntimeInitialized&&p.onRuntimeInitialized(),function(){if(p.postRun)for(typeof p.postRun==`function`&&(p.postRun=[p.postRun]);p.postRun.length;)ge(p.postRun.shift());P(pe)}()))}}function je(e){throw p.onAbort&&p.onAbort(e),e===void 0?e=``:(x(e),S(e),e=JSON.stringify(e)),D=!0,`abort(`+e+`). Build with -s ASSERTIONS=1 for more info.`}if(p.dynCall_iii=function(){return p.asm.dynCall_iii.apply(null,arguments)},p.asm=we,p.ccall=re,p.cwrap=function(e,t,n,r){var i=(n||=[]).every(function(e){return e===`number`});return t!==`string`&&i&&!r?ee(e):function(){return re(e,t,n,arguments,r)}},ke.prototype=Error(),ke.prototype.constructor=ke,be=function e(){p.calledRun||Ae(),p.calledRun||(be=e)},p.run=Ae,p.abort=je,p.preInit)for(typeof p.preInit==`function`&&(p.preInit=[p.preInit]);p.preInit.length>0;)p.preInit.pop()();p.noExitRuntime=!0,Ae(),p.onRuntimeInitialized=()=>{iu=!0,au()},ru.decode=function(e){return function(e){if(!iu)throw Error(`SF3 decoder has not been initialized yet. Did you await synth.isReady?`);var t={};function n(e){return new Int32Array(p.HEAPU8.buffer,e,1)[0]}function r(e,t){var n=new ArrayBuffer(t*Float32Array.BYTES_PER_ELEMENT),r=new Float32Array(n);return r.set(new Float32Array(p.HEAPU8.buffer,e,t)),r}t.open=p.cwrap(`stb_vorbis_js_open`,`number`,[]),t.close=p.cwrap(`stb_vorbis_js_close`,`void`,[`number`]),t.channels=p.cwrap(`stb_vorbis_js_channels`,`number`,[`number`]),t.sampleRate=p.cwrap(`stb_vorbis_js_sample_rate`,`number`,[`number`]),t.decode=p.cwrap(`stb_vorbis_js_decode`,`number`,[`number`,`number`,`number`,`number`,`number`]);var i,a,o,s,c=t.open(),l=(i=e,a=e.byteLength,o=p._malloc(a),(s=new Uint8Array(p.HEAPU8.buffer,o,a)).set(new Uint8Array(i,0,a)),s),u=p._malloc(4),d=p._malloc(4),f=t.decode(c,l.byteOffset,l.byteLength,u,d);if(p._free(l.byteOffset),f<0)throw t.close(c),p._free(u),Error(`stbvorbis decode failed: `+f);for(var m=t.channels(c),h=Array(m),g=new Int32Array(p.HEAPU32.buffer,n(u),m),_=0;_.5),r?n*2-1:n;case xu.concave:return r?(n=n*2-1,n<0?-wu[Math.trunc(n*-16384)]:wu[Math.trunc(n*Su)]):wu[Math.trunc(n*Su)];case xu.convex:return r?(n=n*2-1,n<0?-Tu[Math.trunc(n*-16384)]:Tu[Math.trunc(n*Su)]):Tu[Math.trunc(n*Su)]}}var Du=new Float32Array(1e3);for(let e=0;e>t&1)>0}function ku(e){return+!!e}var Au=class e{isBipolar;isNegative;index;isCC;curveType;constructor(e=bu.noController,t=xu.linear,n=!1,r=!1,i=!1){this.isBipolar=r,this.isNegative=i,this.index=e,this.isCC=n,this.curveType=t}get sourceName(){return this.isCC?Object.keys(Y).find(e=>Y[e]===this.index)??this.index.toString():Object.keys(bu).find(e=>bu[e]===this.index)??this.index.toString()}get curveTypeName(){return Object.keys(xu).find(e=>xu[e]===this.curveType)??this.curveType.toString()}static fromSourceEnum(t){let n=Ou(t,9),r=Ou(t,8),i=Ou(t,7);return new e(t&127,t>>10&3,i,n,r)}static copyFrom(t){return new e(t.index,t.curveType,t.isCC,t.isBipolar,t.isNegative)}toString(){return`${this.sourceName} ${this.curveTypeName} ${this.isBipolar?`bipolar`:`unipolar`} ${this.isNegative?`negative`:`positive`}`}toSourceEnum(){return this.curveType<<10|ku(this.isBipolar)<<9|ku(this.isNegative)<<8|ku(this.isCC)<<7|this.index}isIdentical(e){return this.index===e.index&&this.isNegative===e.isNegative&&this.isCC===e.isCC&&this.isBipolar===e.isBipolar&&this.curveType===e.curveType}getValue(e,t,n){let r;if(this.isCC)r=e.midiControllers[this.index];else switch(this.index){default:case bu.noController:r=16383;break;case bu.noteOnVelocity:r=n.velocity<<7;break;case bu.noteOnKeyNum:r=n.targetKey<<7;break;case bu.polyPressure:r=n.pressure<<7;break;case bu.channelPressure:r=e.midiParameters.pressure<<7;break;case bu.pitchWheel:r=t;break;case bu.pitchWheelRange:r=Math.floor(e.midiParameters.pitchWheelRange*128)}let i=(this.isBipolar?2:0)|!!this.isNegative;return ju[Su*(this.curveType*Cu+i)+r]}},ju=new Float32Array(Su*4*Cu);for(let e=0;eX[e]===this.destination)}static isIdentical(e,t,n=!1){return e.primarySource.isIdentical(t.primarySource)&&e.secondarySource.isIdentical(t.secondarySource)&&e.destination===t.destination&&e.transformType===t.transformType&&(!n||e.transformAmount===t.transformAmount)}static copyFrom(t){return new e(Au.copyFrom(t.primarySource),Au.copyFrom(t.secondarySource),t.destination,t.transformAmount,t.transformType)}toString(){return`Source: ${this.primarySource.toString()}\nSecondary source: ${this.secondarySource.toString()}\nto: ${this.destinationName}\namount: ${this.transformAmount}`+(this.transformType===2?`absolute value`:``)}write(e,t){U(e,this.primarySource.toSourceEnum()),U(e,this.destination),U(e,this.transformAmount),U(e,this.secondarySource.toSourceEnum()),U(e,this.transformType),t&&t.mod++}sumTransform(t){let n=e.copyFrom(this);return n.transformAmount+=t.transformAmount,n}},Fu=class extends Pu{constructor(e,t,n,r,i){super(Au.fromSourceEnum(e),Au.fromSourceEnum(t),n,r,i),this.destination>gu&&(this.destination=X.invalid)}},Iu=[new Fu(Mu(xu.concave,!1,!0,!1,bu.noteOnVelocity),0,X.initialAttenuation,960,0),new Fu(129,0,X.vibLfoToPitch,50,0),new Fu(Mu(xu.concave,!1,!0,!0,Y.mainVolume),0,X.initialAttenuation,960,0),new Fu(13,0,X.vibLfoToPitch,50,0),new Fu(526,16,X.fineTune,12700,0),new Fu(650,0,X.pan,500,0),new Fu(Mu(xu.concave,!1,!0,!0,Y.expression),0,X.initialAttenuation,960,0),new Fu(219,0,X.reverbEffectsSend,200,0),new Fu(221,0,X.chorusEffectsSend,200,0)],Lu=[new Fu(Mu(xu.convex,!0,!1,!0,Y.attackTime),0,X.attackVolEnv,6e3,0),new Fu(Mu(xu.linear,!0,!1,!0,Y.releaseTime),0,X.releaseVolEnv,3600,0),new Fu(Mu(xu.linear,!0,!1,!0,Y.decayTime),0,X.decayVolEnv,3600,0),new Fu(Mu(xu.linear,!0,!1,!0,Y.brightness),0,X.initialFilterFc,9600,0),new Fu(Nu,0,X.initialFilterQ,250,0),new Fu(Mu(xu.switch,!1,!1,!0,Y.softPedal),0,X.initialFilterFc,-1200,0)],Ru=[...Iu,...Lu],zu=class{type;value=0;constructor(e,t,n=!0){if(this.type=e,t===void 0)throw Error(`No value provided.`);if(this.value=Math.round(t),n){let t=vu[e];t!==void 0&&(this.value=Math.max(t.min,Math.min(t.max,this.value)))}}write(e){U(e,this.type),U(e,this.value)}toString(){return`${Object.keys(X).find(e=>X[e]===this.type)}: ${this.value}`}},Bu=class{velRange={min:-1,max:127};keyRange={min:-1,max:127};generators=[];modulators=[];get hasKeyRange(){return this.keyRange.min!==-1}get hasVelRange(){return this.velRange.min!==-1}get fineTuning(){let e=this.getGenerator(X.coarseTune,0),t=this.getGenerator(X.fineTune,0);return e*100+t}set fineTuning(e){let t=Math.trunc(e/100),n=e%100;this.setGenerator(X.coarseTune,t),this.setGenerator(X.fineTune,n)}addToGenerator(e,t,n=!0){let r=this.getGenerator(e,vu[e].def);this.setGenerator(e,t+r,n)}setGenerator(e,t,n=!0){switch(e){case X.sampleID:throw Error(`Use setSample()`);case X.instrument:throw Error(`Use setInstrument()`);case X.velRange:case X.keyRange:throw Error(`Set the range manually`)}if(t===null){this.generators=this.generators.filter(t=>t.type!==e);return}let r=this.generators.findIndex(t=>t.type===e);r===-1?this.addGenerators(new zu(e,t,n)):this.generators[r]=new zu(e,t,n)}addGenerators(...e){for(let t of e)switch(t.type){default:this.generators.push(t);break;case X.sampleID:case X.instrument:break;case X.velRange:this.velRange.min=t.value&127,this.velRange.max=t.value>>8&127;break;case X.keyRange:this.keyRange.min=t.value&127,this.keyRange.max=t.value>>8&127}}addModulators(...e){this.modulators.push(...e)}getGenerator(e,t){return this.generators.find(t=>t.type===e)?.value??t}copyFrom(e){this.generators=e.generators.map(e=>new zu(e.type,e.value,!1)),this.modulators=e.modulators.map(Pu.copyFrom.bind(Pu)),this.velRange={...e.velRange},this.keyRange={...e.keyRange}}getWriteGenerators(e){let t=this.generators.filter(e=>e.type!==X.sampleID&&e.type!==X.instrument&&e.type!==X.keyRange&&e.type!==X.velRange);if(!e)throw Error(`No bank provided! `);return this.hasVelRange&&t.unshift(new zu(X.velRange,this.velRange.max<<8|Math.max(this.velRange.min,0),!1)),this.hasKeyRange&&t.unshift(new zu(X.keyRange,this.keyRange.max<<8|Math.max(this.keyRange.min,0),!1)),t}},Vu=48e3,Hu=class{name;sampleRate;originalKey;pitchCorrection;linkedSample;sampleType;loopStart;loopEnd;linkedTo=[];dataOverridden=!0;compressedData;audioData;constructor(e,t,n,r,i,a,o){this.name=e,this.sampleRate=t,this.originalKey=n,this.pitchCorrection=r,this.loopStart=a,this.loopEnd=o,this.sampleType=i}get isCompressed(){return this.compressedData!==void 0}get isLinked(){return this.sampleType===yu.rightSample||this.sampleType===yu.leftSample||this.sampleType===yu.linkedSample}get useCount(){return this.linkedTo.length}getRawData(e){return this.compressedData&&e&&!this.dataOverridden?this.compressedData:this.encodeS16LE()}resampleData(e){let t=this.getAudioData(),n=e/this.sampleRate,r=new Float32Array(Math.floor(t.length*n));for(let e=0;e96e3)&&(this.resampleData(Vu),t=this.getAudioData());let n=await e(t,this.sampleRate);this.setCompressedData(n)}catch(e){J.warn(`Failed to compress ${this.name}. Leaving as uncompressed!`,e),this.compressedData=void 0}}setSampleType(e){if(this.sampleType=e,this.isLinked||(this.linkedSample&&(this.linkedSample.linkedSample=void 0,this.linkedSample.sampleType=e),this.linkedSample=void 0),(e&32768)>0)throw Error(`ROM samples are not supported.`)}unlinkSample(){this.setSampleType(yu.monoSample)}setLinkedSample(e,t){if(e.linkedSample)throw Error(`${e.name} is linked tp ${e.linkedSample.name}. Unlink it first.`);if(this===e)throw Error(`${e.name} cannot be linked to itself.`);switch(this.linkedSample=e,e.linkedSample=this,t){case yu.leftSample:this.setSampleType(yu.leftSample),e.setSampleType(yu.rightSample);break;case yu.rightSample:this.setSampleType(yu.rightSample),e.setSampleType(yu.leftSample);break;case yu.linkedSample:this.setSampleType(yu.linkedSample),e.setSampleType(yu.linkedSample);break;default:throw Error(`Invalid sample type: `+t)}}linkTo(e){this.linkedTo.push(e)}unlinkFrom(e){let t=this.linkedTo.indexOf(e);if(t===-1){J.warn(`Cannot unlink ${e.name} from ${this.name}: not linked.`);return}this.linkedTo.splice(t,1)}getAudioData(){if(this.audioData)return this.audioData;if(this.isCompressed)return this.audioData=this.decodeVorbis(),this.audioData;throw Error(`Sample data is undefined for a BasicSample instance.`)}setAudioData(e,t){this.audioData=e,this.sampleRate=t,this.dataOverridden=!0,this.compressedData=void 0}setCompressedData(e){this.audioData=void 0,this.compressedData=e,this.dataOverridden=!1}encodeS16LE(){let e=this.getAudioData(),t=new Int16Array(e.length),n=e.length;for(let r=0;r32767?n=32767:n<-32768&&(n=-32768),t[r]=n}return new Ml(t.buffer)}decodeVorbis(){if(this.audioData)return this.audioData;if(!this.compressedData)throw Error(`Compressed data is missing.`);try{let e=su.decode(this.compressedData).data[0];if(e===void 0)return J.warn(`Error decoding sample ${this.name}: Vorbis decode returned undefined.`),new Float32Array;for(let t=0;t=e.min&&t<=e.max}static addUniqueModulators(e,t){for(let n of t)e.some(e=>Pu.isIdentical(n,e))||e.push(n)}static subtractRanges(e,t){return{min:Math.max(e.min,t.min),max:Math.min(e.max,t.max)}}delete(){for(let e of this.zones)e.instrument?.unlinkFrom(this)}deleteZone(e){this.zones[e]?.instrument?.unlinkFrom(this),this.zones.splice(e,1)}createZone(e){let t=new Gu(this,e);return this.zones.push(t),t}preload(e,t){for(let n=e;nPu.isIdentical(e,t));t===-1?c.push(e):c[t]=c[t].sumTransform(e)}let l=new Int16Array(Ku);for(let e of a.globalZone.generators)l[e.type]=e.value;for(let e of i.generators)l[e.type]=e.value;for(let e=0;e{e.push(...t.filter(t=>!e.some(e=>e.type===t.type)))},n=(e,t)=>{e.push(...t.filter(t=>!e.some(e=>Pu.isIdentical(t,e))))},r=new Yu;r.name=this.name;let i=[],a=[],o=this.globalZone;i.push(...o.generators),a.push(...o.modulators);let s=o.keyRange,c=o.velRange;for(let o of this.zones){if(!o.instrument)throw Error(`No instrument in a preset zone.`);let l=o.keyRange;o.hasKeyRange||(l=s);let u=o.velRange;o.hasVelRange||(u=c);let d=o.generators.map(e=>new zu(e.type,e.value));t(d,i);let f=[...o.modulators];n(f,a);let p=o.instrument,m=p.zones,h=[],g=[],_=p.globalZone;h.push(..._.generators),g.push(..._.modulators);let v=_.keyRange,y=_.velRange;for(let i of m){if(!i.sample)throw Error(`No sample in an instrument zone.`);let a=i.keyRange;i.hasKeyRange||(a=v);let o=i.velRange;if(i.hasVelRange||(o=y),a=e.subtractRanges(a,l),o=e.subtractRanges(o,u),a.maxnew zu(e.type,e.value));t(s,h);let c=[...i.modulators];n(c,g);let p=[...c];for(let e of f){let t=p.findIndex(t=>Pu.isIdentical(e,t));t===-1?p.push(e):p[t]=p[t].sumTransform(e)}let m=s.map(e=>new zu(e.type,e.value));for(let e of d){if(e.type===X.velRange||e.type===X.keyRange||e.type===X.instrument||e.type===X.endOper||e.type===X.sampleModes)continue;let t=s.findIndex(t=>t.type===e.type);if(t===-1){let t=vu[e.type].def+e.value;m.push(new zu(e.type,t))}else{let n=m[t].value+e.value;m[t]=new zu(e.type,n)}}m=m.filter(e=>e.type!==X.sampleID&&e.type!==X.keyRange&&e.type!==X.velRange&&e.type!==X.endOper&&e.type!==X.instrument&&(!(e.type in vu)||e.value!==vu[e.type].def));let _=r.createZone(i.sample);_.keyRange=a,_.velRange=o,_.keyRange.min===0&&_.keyRange.max===127&&(_.keyRange.min=-1),_.velRange.min===0&&_.velRange.max===127&&(_.velRange.min=-1),_.addGenerators(...m),_.addModulators(...p)}}return r}write(e,t,n){J.info(`%cWriting ${this.name}...`,G.info),Il(e.pdta,this.name.slice(0,20),20),Il(e.xdta,this.name.slice(20),20),U(e.pdta,this.program);let r=this.bankMSB;n?(r=this.bankMSB&127|(this.bankLSB&127)<<8,this.isGMGSDrum&&(r|=128)):this.isGMGSDrum?r=128:this.bankMSB===0&&(r=this.bankLSB),U(e.pdta,r),e.xdta.currentIndex+=4,U(e.pdta,t&65535),U(e.xdta,t>>16),W(e.pdta,this.library),W(e.pdta,this.genre),W(e.pdta,this.morphology),e.xdta.currentIndex+=12}},Ju=new Set([X.velRange,X.keyRange,X.instrument,X.sampleID,X.exclusiveClass,X.endOper,X.sampleModes,X.startloopAddrsOffset,X.startloopAddrsCoarseOffset,X.endloopAddrsOffset,X.endloopAddrsCoarseOffset,X.startAddrsOffset,X.startAddrsCoarseOffset,X.endAddrOffset,X.endAddrsCoarseOffset,X.initialAttenuation,X.fineTune,X.coarseTune,X.keyNumToVolEnvHold,X.keyNumToVolEnvDecay,X.keyNumToModEnvHold,X.keyNumToModEnvDecay]),Yu=class{name=``;zones=[];globalZone=new Bu;linkedTo=[];get useCount(){return this.linkedTo.length}createZone(e){let t=new Wu(this,e);return this.zones.push(t),t}linkTo(e){this.linkedTo.push(e);for(let e of this.zones)e.useCount++}unlinkFrom(e){let t=this.linkedTo.indexOf(e);if(t===-1){J.warn(`Cannot unlink ${e.name} from ${this.name}: not linked.`);return}this.linkedTo.splice(t,1);for(let e of this.zones)e.useCount--}deleteUnusedZones(){this.zones=this.zones.filter(e=>{let t=e.useCount>0;return t||e.sample.unlinkFrom(this),t})}delete(){if(this.useCount>0)throw Error(`Cannot delete an instrument that is used by: ${this.linkedTo.map(e=>e.name).toString()}.`);for(let e of this.zones)e.sample.unlinkFrom(this)}deleteZone(e,t=!1){let n=this.zones[e];return--n.useCount,n.useCount<1||t?(n.sample.unlinkFrom(this),this.zones.splice(e,1),!0):!1}globalize(){let e=this.globalZone;for(let t=0;t<58;t++){if(Ju.has(t))continue;t=t;let n={},r=vu[t]?.def||0;n[r]=0;for(let e of this.zones){let i=e.getGenerator(t,void 0);i===void 0?n[r]++:n[i]===void 0?n[i]=1:n[i]++;let a;switch(t){default:continue;case X.decayVolEnv:a=X.keyNumToVolEnvDecay;break;case X.holdVolEnv:a=X.keyNumToVolEnvHold;break;case X.decayModEnv:a=X.keyNumToModEnvDecay;break;case X.holdModEnv:a=X.keyNumToModEnvHold}if(e.getGenerator(a,void 0)!==void 0){n={};break}}if(Object.keys(n).length>0){let i=[`0`,0];for(let[e,t]of Object.entries(n))t>i[1]&&(i=[e,t]);let a=Number.parseInt(i[0]);a!==r&&e.setGenerator(t,a,!1);for(let e of this.zones){let n=e.getGenerator(t,void 0);n===void 0?a!==r&&e.setGenerator(t,r):n===a&&e.setGenerator(t,null)}}}let t=this.zones.length===0?[]:this.zones[0].modulators.map(e=>Pu.copyFrom(e));for(let n of t){let t=!0;for(let e of this.zones)t&&(e.modulators.find(e=>Pu.isIdentical(e,n))||(t=!1));if(t){e.addModulators(Pu.copyFrom(n));for(let e of this.zones){let t=e.modulators.find(e=>Pu.isIdentical(e,n));t&&t.transformAmount===n.transformAmount&&e.modulators.splice(e.modulators.indexOf(t),1)}}}}write(e,t){J.info(`%cWriting ${this.name}...`,G.info),Il(e.pdta,this.name.slice(0,20),20),Il(e.xdta,this.name.slice(20),20),U(e.pdta,t&65535),U(e.xdta,t>>>16)}};function Xu(e,t,n,r,i){let a=0,o=[],s=[];for(let t of e.samples){let n=t.getRawData(!0);a++,i?.(a/e.samples.length),J.info(`%cWrote sample %c${a}. ${t.name}%c of %c${e.samples.length}.`,G.info,G.recognized,G.info,G.recognized),o.push(n),s.push(n.length),t.isCompressed||o.push(new Uint8Array(92))}let c=K.getParts(`smpl`,o,r),l=K.getParts(`sdta`,c,r,!0),u=0;for(let[r,i]of e.samples.entries()){let e=s[r],a,o;i.isCompressed?(a=u,o=a+e):(a=u/2,o=a+e/2,u+=92),u+=e,t.push(a),n.push(o)}return l}function Zu(e,t,n,r){let i=46*(e.samples.length+1),a=new Ml(i),o=new Ml(i),s=0;for(let[r,i]of e.samples.entries()){Il(a,i.name.slice(0,20),20),Il(o,i.name.slice(20),20);let c=t[r];W(a,c),o.currentIndex+=4;let l=n[r];W(a,l),o.currentIndex+=4;let u=i.loopStart+c,d=i.loopEnd+c;i.isCompressed&&(u-=c,d-=c),W(a,u),W(a,d),W(a,i.sampleRate),a[a.currentIndex++]=i.originalKey,a[a.currentIndex++]=i.pitchCorrection,o.currentIndex+=14;let f=i.linkedSample?e.samples.indexOf(i.linkedSample):0;U(a,Math.max(0,f)&65535),U(o,Math.max(0,f)>>16),s=Math.max(s,f);let p=i.sampleType;i.isCompressed&&(p|=16),U(a,p),o.currentIndex+=2}return Il(a,`EOS`,46),Il(o,`EOS`,46),{pdta:K.write(`shdr`,a,r),xdta:K.write(`shdr`,o,r)}}function Qu(e,t,n,r=!1){let i=n?e.presets:e.instruments,a=n?`pgen`:`igen`,o=n?`pmod`:`imod`,s=n?`pbag`:`ibag`,c=n?`phdr`:`inst`,l=n?38:22,u=0,d=[],f=0,p=[],m=[],h=[],g=0,_=[],v=t=>{d.push(u);let n=t.getWriteGenerators(e);u+=n.length,m.push(...n),p.push(f);let r=t.modulators;f+=r.length,h.push(...r)};for(let e of i){_.push(g),v(e.globalZone);for(let t of e.zones)v(t);g+=e.zones.length+1}m.push(new zu(0,0,!1)),h.push(new Fu(0,0,0,0,0)),d.push(u),p.push(f),_.push(g);let y=new Ml(m.length*4);for(let e of m)e.write(y);let b=new Ml(h.length*10);for(let e of h)e.write(b);let x=p.length*4,S={pdta:new Ml(x),xdta:new Ml(x)};for(let[e,t]of p.entries()){let n=d[e];U(S.pdta,n&65535),U(S.pdta,t&65535),U(S.xdta,n>>16),U(S.xdta,t>>16)}let C=(i.length+1)*l,w={pdta:new Ml(C),xdta:new Ml(C)};for(let[e,t]of i.entries())t.write(w,_[e],r);return n?(Il(w.pdta,`EOP`,20),w.pdta.currentIndex+=4,U(w.pdta,g&65535),w.pdta.currentIndex+=12,Il(w.xdta,``,20),w.xdta.currentIndex+=4,U(w.xdta,g>>16),w.xdta.currentIndex+=12):(Il(w.pdta,`EOI`,20),U(w.pdta,g&65535),Il(w.xdta,``,20),U(w.xdta,g>>16)),{writeXdta:Math.max(u,f,g)>65535,gen:{pdta:K.write(a,y,t),xdta:K.write(o,new Ml(4),t)},mod:{pdta:K.write(o,b,t),xdta:K.write(o,new Ml(10),t)},bag:{pdta:K.write(s,S.pdta,t),xdta:K.write(s,S.xdta,t)},hdr:{pdta:K.write(c,w.pdta,t),xdta:K.write(c,w.xdta,t)}}}var $u={writeDefaultModulators:!0,writeExtendedLimits:!0,software:`SpessaSynth`},ed={rf64:!0,software:`SpessaSynth`};function td(e,t){let n=q(t,$u);return rd(e,n.software,n.writeDefaultModulators,n.writeExtendedLimits,!1,!1)}function nd(e,t){return rd(e,q(t,ed).software,!0,!0,!0,!0)}function rd(e,t,n,r,i,a){J.groupCollapsed(`%cSaving soundbank...`,G.info),J.group(`%cWriting INFO...`,G.info);let o=[],s=(e,t)=>{t&&o.push(...K.getParts(e,[Fl(t,!0,!0)],a))},c=e.soundBankInfo;{let e=new Ml(4);U(e,c.version.major),U(e,c.version.minor),o.push(K.write(`ifil`,e,a))}if(s(`isng`,c.soundEngine),s(`INAM`,c.name),s(`irom`,c.romInfo),c.romVersion){let e=new Ml(4);U(e,c.romVersion.major),U(e,c.romVersion.minor),o.push(K.write(`iver`,e,a))}if(s(`ICRD`,Kl(c.creationDate)),s(`IENG`,c.engineer),s(`IPRD`,c.product),s(`ICOP`,c.copyright),s(`ICMT`,c?.subject?(c?.comment?c.comment+` +`:``)+c.subject:c?.comment),s(`ISFT`,t),e.defaultModulators.some(e=>!Ru.some(t=>Pu.isIdentical(t,e,!0)))&&n){let t=e.defaultModulators;J.info(`%cWriting %c${t.length}%c default modulators...`,G.info,G.recognized,G.info);let n=new Ml(10+t.length*10);for(let e of t)e.write(n);kl(n,0,10),o.push(...K.getParts(`DMOD`,[n],a))}J.groupEnd(),J.info(`%cWriting SDTA...`,G.info);let l=[],u=[],d=Xu(e,l,u,a);J.info(`%cWriting PDTA...`,G.info),J.info(`%cWriting SHDR...`,G.info);let f=Zu(e,l,u,a);J.group(`%cWriting instruments...`,G.info);let p=Qu(e,a,!1);J.groupEnd(),J.group(`%cWriting presets...`,G.info);let m=Qu(e,a,!0,i);J.groupEnd();let h=[m.hdr,m.bag,m.mod,m.gen,p.hdr,p.bag,p.mod,p.gen,f],g=K.getParts(`pdta`,h.map(e=>e.pdta),a,!0);r&&(p.writeXdta||m.writeXdta||e.presets.some(e=>e.name.length>20)||e.instruments.some(e=>e.name.length>20)||e.samples.some(e=>e.name.length>20))&&(J.info(`%cWriting the xdta chunk as writeExtendedLimits is enabled and at least one condition was met.`,G.info,G.value),o.push(...K.getParts(`xdta`,h.map(e=>e.xdta),a,!0)));let _=K.getParts(`INFO`,o,a,!0);J.info(`%cWriting the output file...`,G.info);let v=K.writeParts(a?`RIFS`:`RIFF`,[Fl(i?`sfen`:`sfbk`),..._,...d,...g],a);return J.info(`%cSaved successfully! Final file size: %c${v.length}`,G.info,G.recognized),J.groupEnd(),v.buffer}var id=class{static verifyHeader(e,...t){for(let n of t)if(e.header.toLowerCase()===n.toLowerCase())return;this.parsingError(`Invalid DLS chunk header! Expected "${t.join(`, or `)}" got "${e.header.toLowerCase()}"`)}static verifyText(e,...t){for(let n of t)if(e.toLowerCase()===n.toLowerCase())return;this.parsingError(`FourCC error: Expected "${t.join(`, or `)}" got "${e.toLowerCase()}"`)}static parsingError(e){throw J.groupEnd(),Error(`DLS parse error: ${e} The file may be corrupted.`)}static verifyAndReadList(e,...t){this.verifyHeader(e,`LIST`),e.data.currentIndex=0,this.verifyText(Pl(e.data,4),...t);let n=[];for(;e.data.length>e.data.currentIndex;)n.push(K.read(e.data));return n}},Z={none:0,modLfo:1,velocity:2,keyNum:3,volEnv:4,modEnv:5,pitchWheel:6,polyPressure:7,channelPressure:8,vibratoLfo:9,modulationWheel:129,volume:135,pan:138,expression:139,chorus:221,reverb:219,pitchWheelRange:256,fineTune:257,coarseTune:258},Q={none:0,gain:1,reserved:2,pitch:3,pan:4,keyNum:5,chorusSend:128,reverbSend:129,modLfoFreq:260,modLfoDelay:261,vibLfoFreq:276,vibLfoDelay:277,volEnvAttack:518,volEnvDecay:519,reservedEG1:520,volEnvRelease:521,volEnvSustain:522,volEnvDelay:523,volEnvHold:524,modEnvAttack:778,modEnvDecay:779,reservedEG2:780,modEnvRelease:781,modEnvSustain:782,modEnvDelay:783,modEnvHold:784,filterCutoff:1280,filterQ:1281},ad={forward:0,loopAndRelease:1},od=20,sd=16,cd=class e extends id{gain=0;unityNote=60;fineTune=0;loops=[];fulOptions=2;static copyFrom(t){let n=new e;return n.unityNote=t.unityNote,n.gain=t.gain,n.fineTune=t.fineTune,n.loops=t.loops.map(e=>({...e})),n.fulOptions=t.fulOptions,n}static read(t){this.verifyHeader(t,`wsmp`);let n=new e,r=H(t.data,4);if(r!==od&&J.warn(`Wsmp cbSize mismatch: got ${r}, expected ${od}.`),n.unityNote=H(t.data,2),n.fineTune=jl(t.data[t.data.currentIndex++],t.data[t.data.currentIndex++]),n.gain=H(t.data,4)|0,n.fulOptions=H(t.data,4),H(t.data,4)!==0){let e=H(t.data,4);e!==sd&&J.warn(`CbSize for loop in wsmp mismatch. Expected ${sd}, got ${e}.`);let r=H(t.data,4),i=H(t.data,4),a=H(t.data,4);n.loops.push({loopStart:i,loopLength:a,loopType:r})}return n}static fromSFSample(t){let n=new e;return n.unityNote=t.originalKey,n.fineTune=t.pitchCorrection,(t.loopEnd!==0||t.loopStart!==0)&&n.loops.push({loopStart:t.loopStart,loopLength:t.loopEnd-t.loopStart,loopType:ad.forward}),n}static fromSFZone(t){let n=new e;n.unityNote=t.getGenerator(X.overridingRootKey,t.sample.originalKey),t.getGenerator(X.scaleTuning,100)===0&&t.keyRange.max-t.keyRange.min===0&&(n.unityNote=t.keyRange.min),n.fineTune=t.fineTuning+t.sample.pitchCorrection,n.gain=-(t.getGenerator(X.initialAttenuation,0)*.4)<<16;let r=t.getGenerator(X.sampleModes,0);if(r!==0){let e=t.sample.loopStart+t.getGenerator(X.startloopAddrsOffset,0)+t.getGenerator(X.startloopAddrsCoarseOffset,0)*32768,i=t.sample.loopEnd+t.getGenerator(X.endloopAddrsOffset,0)+t.getGenerator(X.endloopAddrsCoarseOffset,0)*32768,a;switch(r){case 1:default:a=0;break;case 3:a=1}n.loops.push({loopType:a,loopStart:e,loopLength:i-e})}return n}toSFZone(e,t){let n=0,r=this.loops[0];r&&(n=r.loopType===ad.loopAndRelease?3:1),n!==0&&e.setGenerator(X.sampleModes,n);let i=-(this.gain>>16)/.4;if(i!==0&&e.setGenerator(X.initialAttenuation,i),e.fineTuning=this.fineTune-t.pitchCorrection,this.unityNote!==t.originalKey&&e.setGenerator(X.overridingRootKey,this.unityNote),r){let n=r.loopStart-t.loopStart,i=r.loopStart+r.loopLength-t.loopEnd;if(n!==0){let t=n%32768;e.setGenerator(X.startloopAddrsOffset,t);let r=Math.trunc(n/32768);r!==0&&e.setGenerator(X.startloopAddrsCoarseOffset,r)}if(i!==0){let t=i%32768;e.setGenerator(X.endloopAddrsOffset,t);let n=Math.trunc(i/32768);n!==0&&e.setGenerator(X.endloopAddrsCoarseOffset,n)}}}write(){let e=new Ml(od+this.loops.length*sd);W(e,od),U(e,this.unityNote),U(e,this.fineTune),W(e,this.gain),W(e,this.fulOptions),W(e,this.loops.length);for(let t of this.loops)W(e,sd),W(e,t.loopType),W(e,t.loopStart),W(e,t.loopLength);return K.write(`wsmp`,e)}},ld={PCM:1,ALAW:6};function ud(e,t){let n=2**(t*8-1),r=2**(t*8),i,a=!1;t===1?(i=255,a=!0):i=n;let o=e.length/t,s=new Float32Array(o);if(t===2){let t=new Int16Array(e.buffer),n=t.length;for(let e=0;e=n&&(c-=r),s[o]=c/i)}return s}function dd(e,t){let n=e.length/t,r=new Float32Array(n);for(let n=0;n>4,s=a&15;o>0&&(s+=16),s=(s<<4)+8,o>1&&(s<<=o-1),r[n]=(i>127?s:-s)/32768}return r}var fd=class extends Hu{wFormatTag;bytesPerSample;rawData;constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r,yu.monoSample,i,a),this.dataOverridden=!1,this.rawData=o.data,this.wFormatTag=s,this.bytesPerSample=c}getAudioData(){if(!this.rawData)return new Float32Array;if(!this.audioData){let e;switch(this.wFormatTag){default:J.warn(`Failed to decode sample. Unknown wFormatTag: ${this.wFormatTag}`),e=new Float32Array(this.rawData.length/this.bytesPerSample);break;case ld.PCM:e=ud(this.rawData,this.bytesPerSample);break;case ld.ALAW:e=dd(this.rawData,this.bytesPerSample);break}this.setAudioData(e,this.sampleRate)}return this.audioData??new Float32Array}getRawData(e){return this.dataOverridden||this.isCompressed?super.getRawData(e):this.wFormatTag===ld.PCM&&this.bytesPerSample===2?this.rawData:this.encodeS16LE()}},pd=class e extends id{waveSample=new cd;wFormatTag;bytesPerSample;sampleRate;dataChunk;name=`Unnamed sample`;constructor(e,t,n,r){super(),this.wFormatTag=e,this.bytesPerSample=t,this.sampleRate=n,this.dataChunk=r}static read(t){let n=this.verifyAndReadList(t,`wave`),r=n.find(e=>e.header===`fmt `);if(!r)throw Error(`No fmt chunk in the wave file!`);let i=H(r.data,2),a=H(r.data,2);if(a!==1)throw Error(`Only mono samples are supported. Fmt reports ${a} channels.`);let o=H(r.data,4);H(r.data,4),H(r.data,2);let s=H(r.data,2)/8,c=n.find(e=>e.header===`data`);if(!c)throw Error(`No data chunk in the WAVE chunk!`);let l=new e(i,s,o,c),u=K.findListType(n,`INFO`);if(u){let e=K.read(u.data);for(;e.header!==`INAM`&&u.data.currentIndexe.header===`wsmp`);return d&&(l.waveSample=cd.read(d)),l}static fromSFSample(t){let n=t.getRawData(!1),r=new e(1,2,t.sampleRate,new K(`data`,n.length,new Ml(n.buffer)));return r.name=t.name,r.waveSample=cd.fromSFSample(t),r}toSFSample(e){let t=this.waveSample.unityNote,n=this.waveSample.fineTune,r=Math.trunc(n/100);t+=r,n-=r*100;let i=0,a=0,o=this.waveSample.loops?.[0];o&&(i=o.loopStart,a=o.loopStart+o.loopLength);let s=new fd(this.name,this.sampleRate,t,n,i,a,this.dataChunk,this.wFormatTag,this.bytesPerSample);e.addSamples(s)}write(){let e=this.writeFmt(),t=this.waveSample.write(),n=K.getParts(`data`,[this.dataChunk.data]),r=K.write(`INAM`,Fl(this.name,!0)),i=K.write(`INFO`,r,!1,!0);return J.info(`%cSaved %c${this.name}%c successfully!`,G.recognized,G.value,G.recognized),K.getParts(`wave`,[e,t,...n,i],!1,!0)}writeFmt(){let e=new Ml(18);return U(e,this.wFormatTag),U(e,1),W(e,this.sampleRate),W(e,this.sampleRate*2),U(e,2),U(e,this.bytesPerSample*8),K.write(`fmt `,e)}},md=class e{source;transform;bipolar;invert;constructor(e=Z.none,t=xu.linear,n=!1,r=!1){this.source=e,this.transform=t,this.bipolar=n,this.invert=r}get sourceName(){return Object.keys(Z).find(e=>Z[e]===this.source)??this.source.toString()}get transformName(){return Object.keys(xu).find(e=>xu[e]===this.transform)??this.transform.toString()}static copyFrom(t){return new e(t.source,t.transform,t.bipolar,t.invert)}static fromSFSource(t){let n;if(t.isCC)switch(t.index){case Y.modulationWheel:n=Z.modulationWheel;break;case Y.mainVolume:n=Z.volume;break;case Y.pan:n=Z.pan;break;case Y.expression:n=Z.expression;break;case Y.chorusDepth:n=Z.chorus;break;case Y.reverbDepth:n=Z.reverb;break}else switch(t.index){case bu.noController:n=Z.none;break;case bu.noteOnKeyNum:n=Z.keyNum;break;case bu.noteOnVelocity:n=Z.velocity;break;case bu.pitchWheel:n=Z.pitchWheel;break;case bu.pitchWheelRange:n=Z.pitchWheelRange;break;case bu.polyPressure:n=Z.polyPressure;break;case bu.channelPressure:n=Z.channelPressure}if(n!==void 0)return new e(n,t.curveType,t.isBipolar,t.isNegative)}toString(){return`${this.sourceName} ${this.transformName} ${this.bipolar?`bipolar`:`unipolar`} ${this.invert?`inverted`:`positive`}`}toTransformFlag(){return this.transform|!!this.bipolar<<4|!!this.invert<<5}toSFSource(){let e,t=!1;switch(this.source){default:case Z.modLfo:case Z.vibratoLfo:case Z.coarseTune:case Z.fineTune:case Z.modEnv:return;case Z.keyNum:e=bu.noteOnKeyNum;break;case Z.none:e=bu.noController;break;case Z.modulationWheel:e=Y.modulationWheel,t=!0;break;case Z.pan:e=Y.pan,t=!0;break;case Z.reverb:e=Y.reverbDepth,t=!0;break;case Z.chorus:e=Y.chorusDepth,t=!0;break;case Z.expression:e=Y.expression,t=!0;break;case Z.volume:e=Y.mainVolume,t=!0;break;case Z.velocity:e=bu.noteOnVelocity;break;case Z.polyPressure:e=bu.polyPressure;break;case Z.channelPressure:e=bu.channelPressure;break;case Z.pitchWheel:e=bu.pitchWheel;break;case Z.pitchWheelRange:e=bu.pitchWheelRange;break}if(e!==void 0)return new Au(e,this.transform,t,this.bipolar,this.invert)}},hd=new Fu(219,0,X.reverbEffectsSend,1e3,0),gd=new Fu(221,0,X.chorusEffectsSend,1e3,0);new Fu(129,0,X.vibLfoToPitch,0,0),new Fu(13,0,X.vibLfoToPitch,0,0);var _d=new Set([X.sampleModes,X.initialAttenuation,X.keyRange,X.velRange,X.sampleID,X.fineTune,X.coarseTune,X.startAddrsOffset,X.startAddrsCoarseOffset,X.endAddrOffset,X.endAddrsCoarseOffset,X.startloopAddrsOffset,X.startloopAddrsCoarseOffset,X.endloopAddrsOffset,X.endloopAddrsCoarseOffset,X.overridingRootKey,X.exclusiveClass]),vd=class e{source;control;destination;scale;transform;constructor(e=new md,t=new md,n,r,i){this.source=e,this.control=t,this.destination=n,this.transform=r,this.scale=i}get isStaticParameter(){return this.source.source===Z.none&&this.control.source===Z.none}get shortScale(){return this.scale>>16}get transformName(){return Object.keys(xu).find(e=>xu[e]===this.transform)??this.transform.toString()}get destinationName(){return Object.keys(Q).find(e=>Q[e]===this.destination)??this.destination.toString()}static read(t){let n=H(t,2),r=H(t,2),i=H(t,2),a=H(t,2),o=H(t,4)|0,s=a&15,c=new md(r,a>>4&15,Ou(a,8),Ou(a,9));return new e(new md(n,a>>10&15,Ou(a,14),Ou(a,15)),c,i,s,o)}static fromSFModulator(t,n){let r=e=>{J.warn(`Failed converting SF modulator into DLS:\n ${t.toString()} \n(${e})`)};if(t.transformType!==0){r(`Absolute transform type is not supported`);return}if(Pu.isIdentical(t,gd,!0)||Pu.isIdentical(t,hd,!0))return;let i=md.fromSFSource(t.primarySource);if(!i){r(`Invalid primary source`);return}let a=md.fromSFSource(t.secondarySource);if(!a){r(`Invalid secondary source`);return}let o=e.fromSFDestination(t.destination,t.transformAmount);if(o===void 0){r(`Invalid destination`);return}let s=t.transformAmount,c;if(typeof o==`number`)c=o;else if(c=o.destination,s=o.amount,o.source!==Z.none){if(a.source!==Z.none&&i.source!==Z.none){r(`Articulation generators with secondary source are not supported`);return}i.source!==Z.none&&(a=i),i=new md(o.source,xu.linear,o.isBipolar)}let l=new e(i,a,c,0,s<<16);n.connectionBlocks.push(l)}static copyFrom(t){return new e(md.copyFrom(t.source),md.copyFrom(t.control),t.destination,t.transform,t.scale)}static fromSFGenerator(t,n){if(_d.has(t.type))return;let r=e=>{J.warn(`Failed converting SF2 generator into DLS:\n ${t.toString()} \n(${e})`)},i=e.fromSFDestination(t.type,t.value);if(i===void 0){r(`Invalid type`);return}let a=new md,o,s=t.value;typeof i==`number`?o=i:(o=i.destination,s=i.amount,a.source=i.source,a.bipolar=i.isBipolar),n.connectionBlocks.push(new e(a,new md,o,0,s<<16))}static fromSFDestination(e,t){switch(e){default:return;case X.initialAttenuation:return{destination:Q.gain,amount:-t,isBipolar:!1,source:Z.none};case X.fineTune:return Q.pitch;case X.pan:return Q.pan;case X.keyNum:return Q.keyNum;case X.reverbEffectsSend:return Q.reverbSend;case X.chorusEffectsSend:return Q.chorusSend;case X.freqModLFO:return Q.modLfoFreq;case X.delayModLFO:return Q.modLfoDelay;case X.delayVibLFO:return Q.vibLfoDelay;case X.freqVibLFO:return Q.vibLfoFreq;case X.delayVolEnv:return Q.volEnvDelay;case X.attackVolEnv:return Q.volEnvAttack;case X.holdVolEnv:return Q.volEnvHold;case X.decayVolEnv:return Q.volEnvDecay;case X.sustainVolEnv:return{destination:Q.volEnvSustain,amount:1e3-t,isBipolar:!1,source:Z.none};case X.releaseVolEnv:return Q.volEnvRelease;case X.delayModEnv:return Q.modEnvDelay;case X.attackModEnv:return Q.modEnvAttack;case X.holdModEnv:return Q.modEnvHold;case X.decayModEnv:return Q.modEnvDecay;case X.sustainModEnv:return{destination:Q.modEnvSustain,amount:1e3-t,isBipolar:!1,source:Z.none};case X.releaseModEnv:return Q.modEnvRelease;case X.initialFilterFc:return Q.filterCutoff;case X.initialFilterQ:return Q.filterQ;case X.modEnvToFilterFc:return{source:Z.modEnv,destination:Q.filterCutoff,amount:t,isBipolar:!1};case X.modEnvToPitch:return{source:Z.modEnv,destination:Q.pitch,amount:t,isBipolar:!1};case X.modLfoToFilterFc:return{source:Z.modLfo,destination:Q.filterCutoff,amount:t,isBipolar:!0};case X.modLfoToVolume:return{source:Z.modLfo,destination:Q.gain,amount:t,isBipolar:!0};case X.modLfoToPitch:return{source:Z.modLfo,destination:Q.pitch,amount:t,isBipolar:!0};case X.vibLfoToPitch:return{source:Z.vibratoLfo,destination:Q.pitch,amount:t,isBipolar:!0};case X.keyNumToVolEnvHold:return{source:Z.keyNum,destination:Q.volEnvHold,amount:t,isBipolar:!0};case X.keyNumToVolEnvDecay:return{source:Z.keyNum,destination:Q.volEnvDecay,amount:t,isBipolar:!0};case X.keyNumToModEnvHold:return{source:Z.keyNum,destination:Q.modEnvHold,amount:t,isBipolar:!0};case X.keyNumToModEnvDecay:return{source:Z.keyNum,destination:Q.modEnvDecay,amount:t,isBipolar:!0};case X.scaleTuning:return{source:Z.keyNum,destination:Q.pitch,amount:t*128,isBipolar:!1}}}toString(){return`Source: ${this.source.toString()},\nControl: ${this.control.toString()},\nScale: ${this.scale} >> 16 = ${this.shortScale},\nOutput transform: ${this.transformName}\nDestination: ${this.destinationName}`}write(){let e=new Ml(12);return U(e,this.source.source),U(e,this.control.source),U(e,this.destination),U(e,this.transform|this.control.toTransformFlag()<<4|this.source.toTransformFlag()<<10),W(e,this.scale),e}toSFGenerator(e){let t=this.destination,n=this.shortScale;switch(t){default:J.info(`%cFailed converting DLS articulator into SF generator: %c${this.toString()}%c\n(invalid destination)`,G.warn,G.value,G.unrecognized);return;case Q.pan:e.setGenerator(X.pan,n);break;case Q.gain:e.addToGenerator(X.initialAttenuation,-n/.4);break;case Q.filterCutoff:e.setGenerator(X.initialFilterFc,n);break;case Q.filterQ:e.setGenerator(X.initialFilterQ,n);break;case Q.modLfoFreq:e.setGenerator(X.freqModLFO,n);break;case Q.modLfoDelay:e.setGenerator(X.delayModLFO,n);break;case Q.vibLfoFreq:e.setGenerator(X.freqVibLFO,n);break;case Q.vibLfoDelay:e.setGenerator(X.delayVibLFO,n);break;case Q.volEnvDelay:e.setGenerator(X.delayVolEnv,n);break;case Q.volEnvAttack:e.setGenerator(X.attackVolEnv,n);break;case Q.volEnvHold:e.setGenerator(X.holdVolEnv,n);break;case Q.volEnvDecay:e.setGenerator(X.decayVolEnv,n);break;case Q.volEnvRelease:e.setGenerator(X.releaseVolEnv,n);break;case Q.volEnvSustain:e.setGenerator(X.sustainVolEnv,1e3-n);break;case Q.modEnvDelay:e.setGenerator(X.delayModEnv,n);break;case Q.modEnvAttack:e.setGenerator(X.attackModEnv,n);break;case Q.modEnvHold:e.setGenerator(X.holdModEnv,n);break;case Q.modEnvDecay:e.setGenerator(X.decayModEnv,n);break;case Q.modEnvRelease:e.setGenerator(X.releaseModEnv,n);break;case Q.modEnvSustain:e.setGenerator(X.sustainModEnv,1e3-n);break;case Q.reverbSend:e.setGenerator(X.reverbEffectsSend,n);break;case Q.chorusSend:e.setGenerator(X.chorusEffectsSend,n);break;case Q.pitch:e.fineTuning+=n;break}}toSFModulator(e){let t=this.shortScale,n,r,i=new Au,a=this.toCombinedSFDestination();if(a){n=a;let e=this.control.toSFSource();if(!e){this.failedConversion(`Invalid control`);return}r=e}else{let e=this.toSFDestination();if(!e){this.failedConversion(`Invalid destination`);return}typeof e==`object`?(t=e.newAmount,n=e.gen):n=e;let a=this.source.toSFSource();if(!a){this.failedConversion(`Invalid source`);return}r=a;let o=this.control.toSFSource();if(!o){this.failedConversion(`Invalid control`);return}i=o}this.transform!==xu.linear&&r.curveType===xu.linear&&(r.curveType=this.transform),n===X.initialAttenuation&&((this.source.source===Z.velocity||this.source.source===Z.volume||this.source.source===Z.expression)&&(r.isNegative=!0),t=Math.min(960,Math.max(0,t)));let o=new Pu(r,i,n,t,0);e.addModulators(o)}toCombinedSFDestination(){let e=this.source.source,t=this.destination;if(e===Z.vibratoLfo&&t===Q.pitch)return X.vibLfoToPitch;if(e===Z.modLfo&&t===Q.pitch)return X.modLfoToPitch;if(e===Z.modLfo&&t===Q.filterCutoff)return X.modLfoToFilterFc;if(e===Z.modLfo&&t===Q.gain)return X.modLfoToVolume;if(e===Z.modEnv&&t===Q.filterCutoff)return X.modEnvToFilterFc;if(e===Z.modEnv&&t===Q.pitch)return X.modEnvToPitch}failedConversion(e){J.info(`%cFailed converting DLS articulator into SF2:\n %c${this.toString()}%c\n(${e})`,G.warn,G.value,G.unrecognized)}toSFDestination(){let e=this.shortScale;switch(this.destination){default:case Q.none:return;case Q.pan:return X.pan;case Q.gain:return{gen:X.initialAttenuation,newAmount:-e};case Q.pitch:return X.fineTune;case Q.keyNum:return X.overridingRootKey;case Q.volEnvDelay:return X.delayVolEnv;case Q.volEnvAttack:return X.attackVolEnv;case Q.volEnvHold:return X.holdVolEnv;case Q.volEnvDecay:return X.decayVolEnv;case Q.volEnvSustain:return{gen:X.sustainVolEnv,newAmount:1e3-e};case Q.volEnvRelease:return X.releaseVolEnv;case Q.modEnvDelay:return X.delayModEnv;case Q.modEnvAttack:return X.attackModEnv;case Q.modEnvHold:return X.holdModEnv;case Q.modEnvDecay:return X.decayModEnv;case Q.modEnvSustain:return{gen:X.sustainModEnv,newAmount:1e3-e};case Q.modEnvRelease:return X.releaseModEnv;case Q.filterCutoff:return X.initialFilterFc;case Q.filterQ:return X.initialFilterQ;case Q.chorusSend:return X.chorusEffectsSend;case Q.reverbSend:return X.reverbEffectsSend;case Q.modLfoFreq:return X.freqModLFO;case Q.modLfoDelay:return X.delayModLFO;case Q.vibLfoFreq:return X.freqVibLFO;case Q.vibLfoDelay:return X.delayVibLFO}}},$=class extends id{connectionBlocks=[];mode=`dls2`;get length(){return this.connectionBlocks.length}copyFrom(e){this.mode=e.mode;for(let t of e.connectionBlocks)this.connectionBlocks.push(vd.copyFrom(t))}fromSFZone(e){this.mode=`dls2`;let t=new Bu;t.copyFrom(e);for(let e of t.generators){let n;switch(e.type){default:continue;case X.keyNumToVolEnvDecay:n=X.decayVolEnv;break;case X.keyNumToVolEnvHold:n=X.holdVolEnv;break;case X.keyNumToModEnvDecay:n=X.decayModEnv;break;case X.keyNumToModEnvHold:n=X.holdModEnv}let r=t.getGenerator(n,void 0),i=e.value*-128;if(r===void 0)continue;let a=r-60/128*i;t.setGenerator(e.type,i,!1),t.setGenerator(n,a,!1)}for(let e of t.generators)vd.fromSFGenerator(e,this);for(let e of t.modulators)vd.fromSFModulator(e,this)}read(e){let t=K.findListType(e,`lart`),n=K.findListType(e,`lar2`);if(t)for(this.mode=`dls1`;t.data.currentIndexe.write()),n=K.getParts(this.mode===`dls2`?`art2`:`art1`,[e,...t]);return K.getParts(this.mode===`dls2`?`lar2`:`lart`,n,!0)}toSFZone(e){let t=(t,n,r,i)=>{let a=t/-128;if(e.setGenerator(n,a),a<=120){let n=Math.round(60/128*t),a=this.connectionBlocks.find(e=>e.isStaticParameter&&e.destination===i);a&&e.setGenerator(r,n+a.shortScale)}};for(let t of this.connectionBlocks){let n=t.shortScale,r=t.source.source,i=t.control.source,a=t.destination;if(t.isStaticParameter){t.toSFGenerator(e);continue}if(i===Z.none)if(r===Z.keyNum){if(a===Q.pitch){e.setGenerator(X.scaleTuning,n/128);continue}if(a===Q.modEnvHold||a===Q.modEnvDecay||a===Q.volEnvHold||a===Q.volEnvDecay)continue}else{let r=t.toCombinedSFDestination();if(r){e.setGenerator(r,n);continue}}t.toSFModulator(e)}for(let e of this.connectionBlocks){if(e.source.source!==Z.keyNum)continue;let n=e.shortScale;switch(e.destination){default:case Q.volEnvHold:t(n,X.keyNumToVolEnvHold,X.holdVolEnv,Q.volEnvHold);break;case Q.volEnvDecay:t(n,X.keyNumToVolEnvDecay,X.decayVolEnv,Q.volEnvDecay);break;case Q.modEnvHold:t(n,X.keyNumToModEnvHold,X.holdModEnv,Q.modEnvHold);break;case Q.modEnvDecay:t(n,X.keyNumToModEnvDecay,X.decayModEnv,Q.modEnvDecay);break}}if(this.mode===`dls1`){e.setGenerator(X.delayVibLFO,e.getGenerator(X.delayModLFO,null)),e.setGenerator(X.freqVibLFO,e.getGenerator(X.freqModLFO,null)),e.setGenerator(X.vibLfoToPitch,e.getGenerator(X.modLfoToPitch,null)),e.setGenerator(X.modLfoToPitch,null);for(let t of e.modulators)t.destination===X.modLfoToPitch&&(t.destination=X.vibLfoToPitch)}}},yd=class e{channel=1;tableIndex;fusOptions=0;phaseGroup=0;constructor(e){this.tableIndex=e}static copyFrom(t){let n=new e(t.tableIndex);return n.channel=t.channel,n.phaseGroup=t.phaseGroup,n.fusOptions=t.fusOptions,n}static read(t){let n=H(t.data,2),r=H(t.data,2),i=H(t.data,4),a=new e(H(t.data,4));return a.channel=i,a.fusOptions=n,a.phaseGroup=r,a}static fromSFZone(t,n){let r=t.indexOf(n.sample);if(r===-1)throw Error(`Wave link error: Sample ${n.sample.name} does not exist in the sample list.`);let i=new e(r);switch(n.sample.sampleType){default:case yu.leftSample:case yu.monoSample:i.channel=1;break;case yu.rightSample:i.channel=2}return i}write(){let e=new Ml(12);return U(e,this.fusOptions),U(e,this.phaseGroup),W(e,this.channel),W(e,this.tableIndex),K.write(`wlnk`,e)}},bd=class e extends id{articulation=new $;keyRange={min:0,max:127};velRange={min:0,max:127};keyGroup=0;fusOptions=0;usLayer=0;waveSample;waveLink;constructor(e,t){super(),this.waveSample=t,this.waveLink=e}static copyFrom(t){let n=new e(yd.copyFrom(t.waveLink),cd.copyFrom(t.waveSample));return n.keyGroup=t.keyGroup,n.keyRange={...t.keyRange},n.velRange={...t.velRange},n.usLayer=t.usLayer,n.fusOptions=t.fusOptions,n.articulation.copyFrom(t.articulation),n}static read(t,n){let r=this.verifyAndReadList(n,`rgn `,`rgn2`),i=r.find(e=>e.header===`wsmp`),a=i?cd.read(i):void 0,o=r.find(e=>e.header===`wlnk`);if(!o){J.warn(`Invalid DLS region: missing 'wlnk' chunk! Discarding...`);return}let s=yd.read(o),c=r.find(e=>e.header===`rgnh`);if(!c){J.warn(`Invalid DLS region: missing 'rgnh' chunk! Discarding...`);return}let l=t[s.tableIndex];l||e.parsingError(`Invalid sample index: ${s.tableIndex}. Samples available: ${t.length}`),a??=l.waveSample;let u=new e(s,a),d=H(c.data,2),f=H(c.data,2),p=H(c.data,2),m=H(c.data,2);return p===0&&m===0&&(m=127,p=0),u.keyRange.max=f,u.keyRange.min=d,u.velRange.max=m,u.velRange.min=p,u.fusOptions=H(c.data,2),u.keyGroup=H(c.data,2),c.data.length-c.data.currentIndex>=2&&(u.usLayer=H(c.data,2)),u.articulation.read(r),u}static fromSFZone(t,n){let r=cd.fromSFZone(t),i=new e(yd.fromSFZone(n,t),r);return i.keyRange.min=Math.max(t.keyRange.min,0),i.keyRange.max=t.keyRange.max,i.velRange.min=Math.max(t.velRange.min,0),i.velRange.max=t.velRange.max,i.keyGroup=t.getGenerator(X.exclusiveClass,0),i.articulation.fromSFZone(t),i}write(){let e=[this.writeHeader(),this.waveSample.write(),this.waveLink.write(),...this.articulation.write()];return K.getParts(`rgn2`,e,!1,!0)}toSFZone(t,n){let r=n[this.waveLink.tableIndex];r||e.parsingError(`Invalid sample index: ${this.waveLink.tableIndex}`);let i=t.createZone(r);return i.keyRange=this.keyRange,i.velRange=this.velRange,this.keyRange.max===127&&this.keyRange.min===0&&(i.keyRange.min=-1),this.velRange.max===127&&this.velRange.min===0&&(i.velRange.min=-1),this.keyGroup!==0&&i.setGenerator(X.exclusiveClass,this.keyGroup),this.waveSample.toSFZone(i,r),this.articulation.toSFZone(i),i.generators=i.generators.filter(e=>e.value!==vu[e.type].def),i}writeHeader(){let e=new Ml(14);return U(e,Math.max(this.keyRange.min,0)),U(e,this.keyRange.max),U(e,Math.max(this.velRange.min,0)),U(e,this.velRange.max),U(e,this.fusOptions),U(e,this.keyGroup),U(e,this.usLayer),K.write(`rgnh`,e)}},xd=class e extends id{articulation=new $;regions=[];name=`Unnamed`;bankLSB=0;bankMSB=0;isGMGSDrum=!1;program=0;static copyFrom(t){let n=new e;n.name=t.name,n.isGMGSDrum=t.isGMGSDrum,n.bankMSB=t.bankMSB,n.bankLSB=t.bankLSB,n.program=t.program,n.articulation.copyFrom(t.articulation);for(let e of t.regions)n.regions.push(bd.copyFrom(e));return n}static read(t,n){let r=this.verifyAndReadList(n,`ins `),i=r.find(e=>e.header===`insh`);if(!i)throw J.groupEnd(),Error(`No instrument header!`);let a=``,o=K.findListType(r,`INFO`);if(o){let e=K.read(o.data);for(;e.header!==`INAM`;)e=K.read(o.data);a=Pl(e.data,e.data.length).trim()}a.length===0&&(a=`Unnamed Instrument`);let s=new e;s.name=a;let c=H(i.data,4),l=H(i.data,4);s.program=H(i.data,4)&127,s.bankMSB=l>>>8&127,s.bankLSB=l&127,s.isGMGSDrum=l>>>31>0,J.groupCollapsed(`%cParsing %c"${a}"%c...`,G.info,G.recognized,G.info);let u=K.findListType(r,`lrgn`);if(!u)throw J.groupEnd(),Error(`No region list!`);s.articulation.read(r);for(let e=0;ee.write());e.push(...K.getParts(`lrgn`,t,!1,!0)),this.articulation.length>0&&e.push(...this.articulation.write());let n=K.write(`INAM`,Fl(this.name,!0));return e.push(K.write(`INFO`,n,!1,!0)),J.groupEnd(),K.writeParts(`ins `,e,!1,!0)}toSFPreset(e){let t=new qu(e);t.name=this.name,t.bankMSB=this.bankMSB,t.bankLSB=this.bankLSB,t.isGMGSDrum=this.isGMGSDrum,t.program=this.program;let n=new Yu;n.name=this.name,t.createZone(n),this.articulation.toSFZone(n.globalZone);for(let t of this.regions)t.toSFZone(n,e.samples);n.globalize(),n.globalZone.modulators.some(e=>e.destination===X.reverbEffectsSend)||n.globalZone.addModulators(Pu.copyFrom(hd)),n.globalZone.modulators.some(e=>e.destination===X.chorusEffectsSend)||n.globalZone.addModulators(Pu.copyFrom(gd)),n.globalZone.generators=n.globalZone.generators.filter(e=>e.value!==vu[e.type].def),e.addPresets(t),e.addInstruments(n)}writeHeader(){let e=new Ml(12);W(e,this.regions.length);let t=(this.bankMSB&127)<<8|this.bankLSB&127;return this.isGMGSDrum&&(t|=1<<31),W(e,t),W(e,this.program&127),K.write(`insh`,e)}},Sd={software:`SpessaSynth`},Cd=class e extends id{samples=[];instruments=[];soundBankInfo={name:`Unnamed DLS sound bank`,creationDate:new Date,software:`SpessaSynth`,soundEngine:`DLS Level 2.2`,product:`SpessaSynth DLS`,version:{major:2,minor:4}};static read(t){if(!t)throw Error(`No data provided!`);let n=new Ml(t);J.group(`%cParsing DLS file...`,G.info);let r=K.read(n,!1,!1);this.verifyHeader(r,`RIFF`),this.verifyText(Pl(n,4).toLowerCase(),`dls `);let i=[];for(;n.currentIndexe.header===`colh`);if(!s)return this.parsingError(`No colh chunk!`),5;let c=H(s.data,4);J.info(`%cInstruments amount: %c${c}`,G.info,G.recognized);let l=K.findListType(i,`wvpl`);if(!l)return this.parsingError(`No wvpl chunk!`),5;let u=this.verifyAndReadList(l,`wvpl`);for(let e of u)a.samples.push(pd.read(e));let d=K.findListType(i,`lins`);if(!d)return this.parsingError(`No lins chunk!`),5;let f=this.verifyAndReadList(d,`lins`);J.groupCollapsed(`%cLoading instruments...`,G.info),f.length!==c&&J.warn(`Colh reported invalid amount of instruments. Detected ${f.length}, expected ${c}`);for(let e of f)a.instruments.push(xd.read(a.samples,e));J.groupEnd();let p=i.find(e=>e.header===`pgal`);if(p){J.info(`%cFound the instrument aliasing chunk!`,G.recognized);let e=p.data;(e[0]!==0||e[1]!==1||e[2]!==2||e[3]!==3)&&(e.currentIndex+=4);let t=a.instruments.find(e=>Wl.isXGDrum(e.bankMSB)||e.isGMGSDrum);if(!t)return J.warn(`MobileBAE aliasing chunk without a drum preset. Aborting!`),a;let n=e.slice(e.currentIndex,e.currentIndex+128);e.currentIndex+=128;for(let e=0;e<128;e++){let r=n[e];if(r===e)continue;let i=t.regions.find(e=>e.keyRange.max===r&&e.keyRange.min===r);if(!i){J.warn(`Invalid drum alias ${e} to ${r}: region does not exist.`);continue}let a=bd.copyFrom(i);a.keyRange.max=e,a.keyRange.min=e,t.regions.push(a)}for(e.currentIndex+=4;e.currentIndex>7&127,i=e[e.currentIndex++],o=e[e.currentIndex++];o!==0&&J.warn(`Invalid alias byte. Expected 0, got ${o}`);let s=H(e,2),c=s&127,l=s>>7&127,u=e[e.currentIndex++];o=e[e.currentIndex++],o!==0&&J.warn(`Invalid alias header. Expected 0, got ${o}`);let d=a.instruments.find(e=>e.bankLSB===c&&e.bankMSB===l&&e.program===u&&!e.isGMGSDrum);if(!d){J.warn(`Invalid alias. Missing instrument: ${c}:${l}:${u}`);continue}let f=xd.copyFrom(d);f.bankMSB=r,f.bankLSB=n,f.program=i,a.instruments.push(f)}}return J.info(`%cParsing finished! %c"${a.soundBankInfo.name||`UNNAMED`}"%c has %c${a.instruments.length}%c instruments and %c${a.samples.length}%c samples.`,G.info,G.recognized,G.info,G.recognized,G.info,G.recognized,G.info),J.groupEnd(),a}static fromSF(t,n){J.groupCollapsed(`%cSaving SF2 to DLS level 2...`,G.info);let r=new e;r.soundBankInfo={...t.soundBankInfo};for(let e=0;ee.write()),!1,!0);J.info(`%cSuccess!`,G.recognized),J.groupEnd(),J.groupCollapsed(`%cWriting WAVE samples...`,G.info);let a=0,o=[],s=[],c=0;for(let e of this.samples){let n=e.write();t.progressFunction?.(c/this.samples.length),J.info(`%cWrote sample %c${c}. ${e.name}%c of %c${this.samples.length}.`,G.info,G.recognized,G.info,G.recognized),o.push(a),a+=n.reduce((e,t)=>e+t.length,0),s.push(...n),c++}let l=K.getParts(`wvpl`,s,!1,!0);J.info(`%cSucceeded!`,G.recognized);let u=new Ml(8+4*o.length);W(u,8),W(u,o.length);for(let e of o)W(u,e);let d=K.write(`ptbl`,u);this.soundBankInfo.software=t.software;let f=[],p=this.soundBankInfo,m=(e,t)=>{t&&f.push(...K.getParts(e,[Fl(t,!0)]))};m(`INAM`,p.name),m(`ICMT`,p.comment),m(`ICOP`,p.copyright),m(`ICRD`,Kl(p.creationDate)),m(`IENG`,p.engineer),m(`IPRD`,p.product),m(`ISFT`,t.software),m(`ISBJ`,p.subject),J.info(`%cCombining everything...`);let h=K.writeParts(`RIFF`,[Fl(`DLS `),r,...i,d,...l,...K.getParts(`INFO`,f,!1,!0)]);return J.info(`%cSaved successfully!`,G.recognized),J.groupEnd(),h.buffer}toSF(){J.group(`%cConverting DLS to SF2...`,G.info);let e=new wd(`dls`);e.soundBankInfo.version.minor=4,e.soundBankInfo.version.major=2,e.soundBankInfo={...this.soundBankInfo};for(let t of this.samples)t.toSFSample(e);for(let t of this.instruments)t.toSFPreset(e);return e.flush(),J.info(`%cConversion complete!`,G.recognized),J.groupEnd(),e}},wd=class e{static isSF3DecoderReady=su.isInitialized;type;soundBankInfo={name:`Unnamed`,creationDate:new Date,software:`SpessaSynth`,soundEngine:`E-mu 10K2`,version:{major:2,minor:4}};presets=[];samples=[];instruments=[];defaultModulators=Ru.map(Pu.copyFrom.bind(Pu));customDefaultModulators=!1;constructor(e=`sf2`){this.type=e}_isXGBank=!1;get isXGBank(){return this._isXGBank}static mergeSoundBanks(...t){let n=t.shift();if(!n)throw Error(`No sound banks provided!`);let r=n.presets;for(;t.length>0;){let e=t?.shift()?.presets;if(e)for(let t of e)r.some(e=>t.matches(e))||r.push(t)}let i=new e;return i.addCompletePresets(r),i.soundBankInfo={...n.soundBankInfo},i}static getSampleSoundBankFile(){let t=new e,n=new Float32Array(128);for(let e=0;e<128;e++)n[e]=e/128*2-1;let r=new Uu;r.name=`Saw`,r.originalKey=65,r.pitchCorrection=20,r.loopEnd=128,r.setAudioData(n,44100),t.addSamples(r);let i=new Yu;i.name=`Saw Wave`,i.globalZone.addGenerators(new zu(X.initialAttenuation,375),new zu(X.releaseVolEnv,-1e3),new zu(X.sampleModes,1)),i.createZone(r),i.createZone(r).setGenerator(X.fineTune,-9),t.addInstruments(i);let a=new qu(t);return a.name=`Saw Wave`,a.createZone(i),t.addPresets(a),t.soundBankInfo.name=`SpessaSynth Sample Sound Bank`,t.flush(),t.writeSF2()}static copyFrom(t){let n=new e;for(let e of t.presets)n.clonePreset(e);return n.soundBankInfo={...t.soundBankInfo},n}addCompletePresets(e){this.addPresets(...e);let t=[];for(let n of e)for(let e of n.zones)e.instrument&&!t.includes(e.instrument)&&t.push(e.instrument);this.addInstruments(...t);let n=[];for(let e of t)for(let t of e.zones)t.sample&&!n.includes(t.sample)&&n.push(t.sample);this.addSamples(...n)}async setSampleFormat(e){let t=0,n=e.format,r=e.progressFunction;for(let i of this.samples){switch(n){default:case`pcm`:i.setAudioData(i.getAudioData(),i.sampleRate);break;case`compressed`:{let t=e.compressionFunction;if(!t)throw Error(`No compression function supplied but '${n}' was requested.`);await i.compressSample(t)}}t++,r?.(t/this.samples.length),J.info(`%cEncoded sample %c${t}. ${i.name}%c of %c${this.samples.length}%c. Compressed: %c${i.isCompressed}%c.`,G.info,G.recognized,G.info,G.recognized,G.info,i.isCompressed?G.recognized:G.unrecognized,G.info)}switch(n){default:case`pcm`:this.soundBankInfo.version.major=2,this.soundBankInfo.version.minor=4;break;case`compressed`:this.soundBankInfo.version.major=3,this.soundBankInfo.version.minor=0}}writeDLS(e=Sd){let t=e.progressFunction;return Cd.fromSF(this,t?e=>t(e/2):void 0).write({...e,progressFunction:t?e=>t(.5+e/2):void 0})}writeSF2(e=$u){return td(this,e)}writeSFE(e=ed){return nd(this,e)}addPresets(...e){this.presets.push(...e)}addInstruments(...e){this.instruments.push(...e)}addSamples(...e){this.samples.push(...e)}cloneSample(e){let t=this.samples.find(t=>t.name===e.name);if(t)return t;let n=new Hu(e.name,e.sampleRate,e.originalKey,e.pitchCorrection,e.sampleType,e.loopStart,e.loopEnd);if(e.isCompressed?n.setCompressedData(e.getRawData(!0)):n.setAudioData(e.getAudioData(),e.sampleRate),this.addSamples(n),e.linkedSample){let t=this.cloneSample(e.linkedSample);t.linkedSample||n.setLinkedSample(t,n.sampleType)}return n}cloneInstrument(e){let t=this.instruments.find(t=>t.name===e.name);if(t)return t;let n=new Yu;n.name=e.name,n.globalZone.copyFrom(e.globalZone);for(let t of e.zones)n.createZone(this.cloneSample(t.sample)).copyFrom(t);return this.addInstruments(n),n}clonePreset(e){let t=this.presets.find(t=>t.name===e.name);if(t)return t;let n=new qu(this);n.name=e.name,n.bankMSB=e.bankMSB,n.bankLSB=e.bankLSB,n.isGMGSDrum=e.isGMGSDrum,n.program=e.program,n.library=e.library,n.genre=e.genre,n.morphology=e.morphology,n.globalZone.copyFrom(e.globalZone);for(let t of e.zones)n.createZone(this.cloneInstrument(t.instrument)).copyFrom(t);return this.addPresets(n),n}flush(){this.presets.sort(Gl.compare.bind(Gl)),this.parseInternal()}trim(e){let t=(e,t)=>{let n=0;for(let r=0;r=a.min&&e<=a.max&&[...n].some(e=>e>=o.min&&e<=o.max)){s=!0;break}s||(J.info(`%c${i.sample.name}%c removed from %c${e.name}%c.`,G.recognized,G.info,G.recognized,G.info),e.deleteZone(r)&&(n++,r--,J.info(`%c${i.sample.name}%c deleted`,G.recognized,G.info)),i.sample.useCount<1&&this.deleteSample(i.sample))}return n};J.groupCollapsed(`%cTrimming sound bank...`,G.info),J.info(`Combinations to trim for:`,e);for(let n=0;n=o.min&&e<=o.max&&[...n].some(e=>e>=s.min&&e<=s.max)){c=!0;let e=t(a.instrument,i);J.info(`%cTrimmed off %c${e}%c instrument zones from %c${a.instrument.name}`,G.info,G.recognized,G.info,G.recognized);break}c||(e++,r.deleteZone(n),a.instrument.useCount<1&&this.deleteInstrument(a.instrument),n--)}J.info(`%cTrimmed off %c${e}%c preset zones from %c${r.name}`,G.info,G.recognized,G.info,G.recognized),J.groupEnd()}}this.removeUnusedElements(),J.info(`%cSound bank modified!`,G.recognized),J.groupEnd()}removeUnusedElements(){this.instruments=this.instruments.filter(e=>{e.deleteUnusedZones();let t=e.useCount<1;return t&&e.delete(),!t}),this.samples=this.samples.filter(e=>{let t=e.useCount<1;return t&&e.unlinkSample(),!t})}deleteInstrument(e){e.delete(),this.instruments.splice(this.instruments.indexOf(e),1)}deletePreset(e){e.delete(),this.presets.splice(this.presets.indexOf(e),1)}deleteSample(e){e.unlinkSample(),this.samples.splice(this.samples.indexOf(e),1)}getPreset(e,t){return Gl.selectPatch(this.presets,e,t)}destroySoundBank(){this.presets.length=0,this.instruments.length=0,this.samples.length=0}parsingError(e){throw Error(`SF parsing error: ${e} The file may be corrupted.`)}parseInternal(){this._isXGBank=!1;let e=new Set([0,1,2,3,4,5,6,7,8,9,16,17,24,25,26,27,28,29,30,31,32,33,40,41,48,56,57,58,64,65,66,126,127]);for(let t of this.presets)if(Wl.isXGDrum(t.bankMSB)&&(this._isXGBank=!0,!e.has(t.program))){this._isXGBank=!1,J.info(`%cThis bank is not valid XG. Preset %c${t.toString()}%c is not a valid XG drum. XG mode will use presets on bank 128.`,G.info,G.value,G.info);break}}printInfo(){for(let[e,t]of Object.entries(this.soundBankInfo))if(typeof t==`object`&&`major`in t){let n=t;J.info(`%c${e}: %c"${n.major}.${n.minor}"`,G.info,G.recognized)}else J.info(`%c${e}: %c${t.toLocaleString()}`,G.info,G.recognized)}},Td=class e extends Pu{isEffectModulator;isDefaultResonantModulator;isModWheelModulator;constructor(e,t,n,r,i,a,o,s){super(e,t,n,r,i),this.isEffectModulator=a,this.isDefaultResonantModulator=o,this.isModWheelModulator=s}static fromData(t,n,r,i,a){let o=t.toSourceEnum(),s=n.toSourceEnum();return new e(t,n,r,i,a,(o===219||o===221)&&s===0&&(r===X.reverbEffectsSend||r===X.chorusEffectsSend),o===Nu&&s===0&&r===X.initialFilterQ,(t.isCC&&t.index===Y.modulationWheel||n.isCC&&n.index===Y.modulationWheel)&&(r===X.modLfoToPitch||r===X.vibLfoToPitch))}static fromModulator(e){return this.fromData(e.primarySource,e.secondarySource,e.destination,e.transformAmount,e.transformType)}},Ed=Math.PI/2,Dd=-500,Od=500,kd=Od-Dd,Ad=new Float32Array(1001),jd=new Float32Array(1001);for(let e=Dd;e<=Od;e++){let t=(e-Dd)/kd,n=e-Dd;Ad[n]=Math.cos(Ed*t),jd[n]=Math.sin(Ed*t)}X.delayModLFO,X.freqModLFO,X.delayVibLFO,X.freqVibLFO,X.delayModEnv,X.attackModEnv,X.holdModEnv,X.decayModEnv,X.sustainModEnv,X.releaseModEnv,X.delayVolEnv,X.attackVolEnv,X.holdVolEnv,X.decayVolEnv,X.sustainVolEnv,X.releaseVolEnv,X.fineTune,X.modLfoToPitch,X.vibLfoToPitch,X.modEnvToPitch,X.modLfoToVolume,X.initialFilterFc,X.initialFilterQ,X.modLfoToFilterFc,X.modEnvToFilterFc,X.chorusEffectsSend,X.reverbEffectsSend,Td.fromModulator(new Fu(Mu(xu.linear,!0,!1,!0,Y.vibratoRate),0,X.vibLfoRate,1e3,0));var Md={pitchWheel:8192,pitchWheelRange:2,pressure:0,modulationDepth:50,rxChannel:0,polyMode:!0,keyShift:0,fineTune:0,randomPan:!1,assignMode:2,efxAssign:!1,cc1:16,cc2:17,drumMap:0,velocitySenseDepth:64,velocitySenseOffset:64},Nd={presetLock:!1,isMuted:!1,gain:1,pan:0,keyShift:0,fineTune:0,interpolationType:null,nrpnParamLock:null,monophonicRetrigger:null},Pd=Math.PI/2,Fd=-64,Id=63,Ld=Id-Fd,Rd=new Float32Array(128),zd=new Float32Array(128);for(let e=Fd;e<=Id;e++){let t=(e-Fd)/Ld,n=e-Fd;Rd[n]=Math.cos(Pd*t),zd[n]=Math.sin(Pd*t)}Math.PI*2,Math.PI*2;var Bd={volume:1,pan:0,keyShift:0,fineTune:0,system:`gs`},Vd={eventsEnabled:!0,oneOutput:!1,audioNodeCreators:void 0},Hd=`spessasynth-worklet-processor`;function Ud(e,t){return{...t,...e}}var Wd=class{keyModifiers=[];synth;constructor(e){this.synth=e}addModifier(e,t,n){let r=new cu;r.gain=n?.gain??1,r.velocity=n?.velocity??-1,r.patch=Ud(n.patch??{},{isGMGSDrum:!1,bankLSB:-1,bankMSB:-1,program:-1}),this.keyModifiers[e]??=[],this.keyModifiers[e][t]=r,this.sendToWorklet(`addMapping`,{channel:e,midiNote:t,mapping:r})}getModifier(e,t){return this.keyModifiers?.[e]?.[t]}deleteModifier(e,t){this.sendToWorklet(`deleteMapping`,{channel:e,midiNote:t}),this.keyModifiers[e]?.[t]!==void 0&&(this.keyModifiers[e][t]=void 0)}clearModifiers(){this.sendToWorklet(`clearMappings`,null),this.keyModifiers=[]}sendToWorklet(e,t){let n={type:e,data:t};this.synth.post({type:`keyModifierManager`,channelNumber:-1,data:n})}},Gd=class{soundBankList;synth;constructor(e){this.soundBankList=[],this.synth=e}get priorityOrder(){return this.soundBankList.map(e=>e.id)}set priorityOrder(e){this.sendToWorklet(`rearrangeSoundBanks`,e),this.soundBankList.sort((t,n)=>e.indexOf(t.id)-e.indexOf(n.id))}async addSoundBank(e,t,n=0){this.sendToWorklet(`addSoundBank`,{soundBankBuffer:e,bankOffset:n,id:t},[e]),await this.awaitResponse();let r=this.soundBankList.find(e=>e.id===t);r===void 0?this.soundBankList.push({id:t,bankOffset:n}):r.bankOffset=n}async deleteSoundBank(e){if(this.soundBankList.length<2){J.warn(`1 sound bank left. Aborting!`);return}if(!this.soundBankList.some(t=>t.id===e)){J.warn(`No sound banks with id of "${e}" found. Aborting!`);return}this.sendToWorklet(`deleteSoundBank`,e),this.soundBankList=this.soundBankList.filter(t=>t.id!==e),await this.awaitResponse()}async awaitResponse(){return new Promise(e=>this.synth.awaitWorkerResponse(`soundBankManager`,e))}sendToWorklet(e,t,n=[]){let r={type:`soundBankManager`,channelNumber:-1,data:{type:e,data:t}};this.synth.post(r,n)}},Kd=class{timeDelay=0;events={noteOff:new Map,noteOn:new Map,controllerChange:new Map,programChange:new Map,polyPressure:new Map,stopAll:new Map,channelAdded:new Map,presetListChange:new Map,reset:new Map,soundBankError:new Map,displayMessage:new Map,globalParamChange:new Map,channelParamChange:new Map,effectChange:new Map};addEvent(e,t,n){this.events[e].set(t,n)}removeEvent(e,t){this.events[e].delete(t)}callEventInternal(e,t){let n=this.events[e],r=()=>{for(let r of n.values())try{r(t)}catch(t){console.error(`Error while executing an event callback for ${e}:`,t)}};this.timeDelay>0?setTimeout(r.bind(this),this.timeDelay*1e3):r()}},qd=Vl.ConsoleColors,Jd=class{channel;synth;_systemParameters={...Nd};constructor(e,t){this.channel=e,this.synth=t}_patch={bankMSB:0,bankLSB:0,program:0,isDrum:!1,isGMGSDrum:!1,name:``};get patch(){return this._patch}set patch(e){this._patch=e}_midiParameters={...Md};get midiParameters(){return this._midiParameters}get systemParameters(){return this._systemParameters}_voiceCount=0;get voiceCount(){return this._voiceCount}set voiceCount(e){this._voiceCount=e}lockMIDIParameter(e,t){this.synth.post({type:`lockChannelMIDIParameter`,channelNumber:this.channel,data:{parameter:e,isLocked:t}})}setSystemParameter(e,t){this._systemParameters[e]=t,this.synth.post({type:`setChannelSystemParameter`,channelNumber:this.channel,data:{parameter:e,value:t}})}lockController(e,t){this.synth.post({channelNumber:this.channel,type:`lockController`,data:{controller:e,isLocked:t}})}setDrums(e){this.synth.post({channelNumber:this.channel,type:`setDrums`,data:e})}setMIDIParameter(e,t){this._midiParameters[e]=t}reset(){this._midiParameters={...Md}}},Yd={time:0},Xd=e=>`SPESSASYNTH_LIB_HANDLE_${e}_${Math.random()}`,Zd=class{soundBankManager=new Gd(this);keyModifierManager=new Wd(this);eventHandler=new Kd;context;midiChannels=[];presetList=[];sequencers=[];isReady;post;worklet;_outputCount=16;_systemParameters={...lu};resolveMap=new Map;renderingProgressTracker=new Map;constructor(e,t,n){J.info(`%cInitializing SpessaSynth synthesizer...`,qd.info),this.context=e.context,this.worklet=e,this.post=t,this.isReady=new Promise(e=>this.awaitWorkerResponse(`sf3Decoder`,e)),this.worklet.port.onmessage=e=>this.handleMessage(e.data);for(let e=0;e<16;e++)this.addNewChannelInternal(!1);this.registerInternalEvent(`channelAdded`,()=>{this.addNewChannelInternal(!1)}),this.registerInternalEvent(`presetListChange`,e=>this.presetList=[...e]),this.registerInternalEvent(`globalParamChange`,e=>this._midiParameters[e.parameter]=e.value),this.registerInternalEvent(`channelParamChange`,e=>this.midiChannels[e.channel].setMIDIParameter(e.parameter,e.value)),this.registerInternalEvent(`programChange`,e=>this.midiChannels[e.channel].patch={...e}),this.registerInternalEvent(`reset`,()=>{for(let e of this.midiChannels)e.reset();this._midiParameters={...Bd}})}_midiParameters={...Bd};get midiParameters(){return this._midiParameters}get channelCount(){return this.midiChannels.length}_voiceCount=0;get voiceCount(){return this._voiceCount}get currentTime(){return this.context.currentTime}get systemParameters(){return this._systemParameters}connect(e){for(let t=0;t<17;t++)this.worklet.connect(e,t);return e}disconnect(e){if(!e){this.worklet.disconnect();return}for(let t=0;t<17;t++)this.worklet.disconnect(e,t);return e}setLogLevel(e,t,n){this.post({channelNumber:-1,type:`setLogLevel`,data:{enableInfo:e,enableWarning:t,enableGroup:n}})}lockMIDIParameter(e,t){this.post({type:`lockGlobalMIDIParameter`,data:{parameter:e,isLocked:t},channelNumber:-1})}setSystemParameter(e,t){this._systemParameters[e]=t,this.post({type:`setGlobalSystemParameter`,channelNumber:-1,data:{parameter:e,value:t}})}async getSnapshot(){return new Promise(e=>{this.awaitWorkerResponse(`synthesizerSnapshot`,t=>{e(t)}),this.post({type:`requestSynthesizerSnapshot`,data:null,channelNumber:-1})})}addNewChannel(){this.addNewChannelInternal(!0)}connectChannel(e,t){return this.worklet.connect(e,t%16+1),e}disconnectChannel(e,t){this.worklet.disconnect(e,t%16+1)}connectIndividualOutputs(e){if(e.length!==this._outputCount)throw Error(`input nodes amount differs from the system's outputs amount! + Expected ${this._outputCount} got ${e.length}`);for(let t=0;t127||t<0)throw Error(`Invalid controller number: ${t}`);n=Math.floor(n)%128,t=Math.floor(t)%128;let i=e%16,a=e-i;this._sendInternal([Hl.controllerChange|i,t,n],a,r)}reset(){this.post({channelNumber:-1,type:`ccReset`,data:null})}channelPressure(e,t,n=Yd){let r=e%16,i=e-r;t%=128,this.sendMessage([Hl.channelPressure|r,t],i,n)}polyPressure(e,t,n,r=Yd){let i=e%16,a=e-i;t%=128,n%=128,this.sendMessage([Hl.polyPressure|i,t,n],a,r)}pitchWheel(e,t,n=Yd){let r=e%16,i=e-r;this.sendMessage([Hl.pitchWheel|r,t&127,t>>7],i,n)}pitchWheelRange(e,t,n=Yd){this.controllerChange(e,Y.registeredParameterMSB,0,n),this.controllerChange(e,Y.registeredParameterLSB,0,n),this.controllerChange(e,Y.dataEntryMSB,t),this.controllerChange(e,Y.registeredParameterMSB,127,n),this.controllerChange(e,Y.registeredParameterLSB,127,n),this.controllerChange(e,Y.dataEntryMSB,0,n)}programChange(e,t,n=Yd){let r=e%16,i=e-r;t%=128,this.sendMessage([Hl.programChange|r,t],i,n)}systemExclusive(e,t=0,n=Yd){this._sendInternal([Hl.systemExclusive,...Array.from(e)],t,n)}tuneKeys(e,t){if(t.length>127)throw Error(`Too many tunings. Maximum allowed is 127.`);let n=[127,16,8,2,e,t.length];for(let e of t)if(n.push(e.sourceKey),e.targetPitch===-1)n.push(127,127,127);else{let t=Math.floor(e.targetPitch),r=Math.floor((e.targetPitch-t)/61e-6);n.push(t,r>>7&127,r&127)}n.push(247),this.systemExclusive(n)}reverbateEverythingBecauseWhyNot(){for(let e=0;ee+t,0);break;case`isFullyInitialized`:this.workletResponds(e.data.type,e.data.data);break;case`soundBankError`:J.warn(e.data),this.eventHandler.callEventInternal(`soundBankError`,e.data);break;case`renderingProgress`:this.renderingProgressTracker.get(e.data.type)?.(e.data.data)}}addNewChannelInternal(e){this.midiChannels.push(new Jd(this.midiChannels.length,this)),e&&this.post({channelNumber:0,type:`addNewChannel`,data:null})}workletResponds(e,t){this.resolveMap.get(e)?.(t),this.resolveMap.delete(e)}registerInternalEvent(e,t){this.eventHandler.addEvent(e,Xd(e),t)}},Qd=class extends Zd{constructor(e,t=Vd){let n=Ud(t,Vd),r=Array(17).fill(2),i=17;n.oneOutput&&(r=[34],i=1);let a;try{a=(n?.audioNodeCreators?.worklet??((e,t,n)=>new AudioWorkletNode(e,t,n)))(e,Hd,{outputChannelCount:r,numberOfOutputs:i,processorOptions:{oneOutput:n.oneOutput,eventsEnabled:n.eventsEnabled}})}catch(e){throw console.error(e),Error(`Could not create the AudioWorkletNode. Did you forget to addModule()?`,{cause:e})}super(a,(e,t=[])=>{a.port.postMessage(e,t)},n)}async startOfflineRender(e){this.post({type:`startOfflineRender`,data:e,channelNumber:-1},e.soundBankList.map(e=>e.soundBankBuffer)),await new Promise(e=>this.awaitWorkerResponse(`startOfflineRender`,e))}destroy(){this.post({channelNumber:0,type:`destroyWorklet`,data:null}),this.worklet.disconnect(),delete this.worklet}},$d={trim:!0,bankID:``,writeEmbeddedSoundBank:!0,sequencerID:0},ef={...$d,writeDefaultModulators:!0,writeExtendedLimits:!0,compressionAction:`keep`,compressionQuality:1,software:`SpessaSynth`};({...$d}),{...ef},{...$d};var tf=`/assets/spessasynth_processor.min-tdOdhV7p.js`,nf=`/soundfonts/MuseScore_General.sf3`,rf=9,af={acoustic_piano:0,electric_piano:4,chromatic_percussion:9,organ:19,acoustic_guitar:24,clean_electric_guitar:27,distorted_electric_guitar:30,acoustic_bass:32,electric_bass:33,violin:40,viola:41,cello:42,contrabass:43,orchestral_harp:46,timpani:47,string_ensemble:48,synth_strings:50,voice:52,orchestra_hit:55,trumpet:56,trombone:57,tuba:58,french_horn:60,brass_section:61,soprano_and_alto_sax:65,tenor_sax:66,baritone_sax:67,oboe:68,english_horn:69,bassoon:70,clarinet:71,flutes:73,synth_lead:80,synth_pad:89},of=100;function sf(e){return e===`drums`||e===`timpani`?`square`:e.includes(`guitar`)||e.includes(`bass`)||e.includes(`sax`)||e.includes(`brass`)?`sawtooth`:e===`voice`||e.includes(`flute`)?`sine`:`triangle`}var cf=class{ctx;synth=null;synthMode=`loading`;fallbackSynths=new Map;pendingNotes=[];channels=new Map;warmChannels=new Map;warmedNotes=new Set;nextChannel=0;allNotes=[];autoStopAt=null;wavBuffer=null;wavSource=null;wavGain;midiGain;wavPanner;midiPanner;mutedInstruments=new Set;mix=.75;stereo=!1;constructor(e={}){this.ctx=Ys().rawContext,this.midiPanner=this.ctx.createStereoPanner(),this.midiPanner.connect(this.ctx.destination),this.midiGain=this.ctx.createGain(),this.midiGain.connect(this.midiPanner),this.wavPanner=this.ctx.createStereoPanner(),this.wavPanner.connect(this.ctx.destination),this.wavGain=this.ctx.createGain(),this.wavGain.connect(this.wavPanner),!e.forceFallback&&globalThis.isSecureContext&&this.ctx.audioWorklet?this.initSynth().catch(e=>this.initFallback(e)):this.initFallback(Error(`AudioWorklet requires HTTPS or localhost`)),this.applyMix(),wl().on(`start`,e=>this.startWavSource(e)),wl().on(`stop`,()=>this.stopWavSource()),wl().on(`pause`,()=>this.stopWavSource())}async initSynth(){let e=fetch(nf).then(e=>{if(!e.ok)throw Error(`${nf}: HTTP ${e.status}`);return e.arrayBuffer()}),t=Ys();await t.addAudioWorkletModule(tf);let n=new Qd(this.ctx,{audioNodeCreators:{worklet:(e,n,r)=>t.createAudioWorkletNode(n,r)}});n.connect(this.midiGain),await n.isReady,await n.soundBankManager.addSoundBank(await e,`MuseScore_General`),this.synth=n,this.synthMode=`soundfont`,this.flushPendingNotes()}initFallback(e){this.synthMode===`loading`&&(console.warn(`SoundFont synthesis is unavailable; using the basic browser synth instead.`,e),this.synthMode=`fallback`,this.flushPendingNotes())}flushPendingNotes(){let e=this.pendingNotes;this.pendingNotes=[];for(let t of e)this.scheduleNoteRaw(t)}fallbackSynthFor(e){let t=this.fallbackSynths.get(e);if(t)return t;let n=e===`drums`||e===`timpani`;return t=new vl(pl,{oscillator:{type:sf(e)},envelope:n?{attack:.001,decay:.08,sustain:.05,release:.05}:{attack:.01,decay:.1,sustain:.55,release:.12}}),t.maxPolyphony=32,t.volume.value=this.mutedInstruments.has(e)?-1/0:-10,t.connect(this.midiGain),this.fallbackSynths.set(e,t),t}stopSynthVoices(){this.synth?.stopAll();for(let e of this.fallbackSynths.values())e.releaseAll()}async loadWav(e){this.stopWavSource(),this.wavBuffer=null;let t=await e.arrayBuffer();try{this.wavBuffer=await this.ctx.decodeAudioData(t)}catch{this.wavBuffer=null}this.applyMix()}setMix(e){this.mix=Math.max(0,Math.min(1,e)),this.applyMix()}setStereo(e){this.stereo=e,this.applyMix()}applyMix(){let e=this.ctx.currentTime;if(this.stereo){let t=this.wavBuffer?.numberOfChannels===1?1:.5;this.wavGain.gain.setTargetAtTime(t,e,.01),this.midiGain.gain.setTargetAtTime(.5,e,.01),this.wavPanner.pan.setTargetAtTime(-1,e,.01),this.midiPanner.pan.setTargetAtTime(1,e,.01)}else this.wavGain.gain.setTargetAtTime(1-this.mix,e,.01),this.midiGain.gain.setTargetAtTime(this.mix,e,.01),this.wavPanner.pan.setTargetAtTime(0,e,.01),this.midiPanner.pan.setTargetAtTime(0,e,.01)}channelFor(e){let t=this.channels.get(e);if(t!==void 0)return t;let n=this.synth;if(e===`drums`)t=rf;else{for(t=this.nextChannel++,this.nextChannel===rf&&this.nextChannel++;t>=n.channelCount;)n.addNewChannel();n.programChange(t,af[e]??0)}return this.mutedInstruments.has(e)&&n.midiChannels[t]?.setSystemParameter(`isMuted`,!0),this.channels.set(e,t),t}warmChannelFor(e){let t=this.warmChannels.get(e);if(t!==void 0)return t;let n=this.synth;for(t=this.nextChannel++,this.nextChannel===rf&&this.nextChannel++;t>=n.channelCount;)n.addNewChannel();return e===`drums`?n.midiChannels[t]?.setDrums(!0):n.programChange(t,af[e]??0),n.midiChannels[t]?.setSystemParameter(`gain`,0),this.warmChannels.set(e,t),t}warmNote(e,t){let n=`${e}:${t}`;if(this.warmedNotes.has(n))return;this.warmedNotes.add(n);let r=this.synth,i=this.warmChannelFor(e);r.noteOn(i,t,of),r.noteOff(i,t)}setInstrumentMuted(e,t){t?this.mutedInstruments.add(e):this.mutedInstruments.delete(e);let n=this.channels.get(e);n!==void 0&&this.synth?.midiChannels[n]?.setSystemParameter(`isMuted`,t);let r=this.fallbackSynths.get(e);r&&(r.volume.value=t?-1/0:-10)}startWavSource(e){if(this.stopWavSource(),!this.wavBuffer)return;let t=wl().seconds;if(t>=this.wavBuffer.duration)return;let n=this.ctx.createBufferSource();n.buffer=this.wavBuffer,n.connect(this.wavGain),n.start(e,t),this.wavSource=n}stopWavSource(){if(this.wavSource){try{this.wavSource.stop()}catch{}this.wavSource.disconnect(),this.wavSource=null}}scheduleNote(e){this.allNotes.push({...e}),this.scheduleNoteRaw(e)}scheduleNoteRaw(e){if(this.synthMode===`loading`){this.pendingNotes.push(e);return}let t=Math.max(.05,e.end-e.start);if(this.synthMode===`fallback`){let n=this.fallbackSynthFor(e.instrument);wl().scheduleOnce(r=>{n.triggerAttackRelease(fc(e.pitch,`midi`).toFrequency(),t,r,of/127)},e.start);return}let n=this.synth,r=this.channelFor(e.instrument);this.warmNote(e.instrument,e.pitch),wl().scheduleOnce(i=>{n.noteOn(r,e.pitch,of,{time:i}),n.noteOff(r,e.pitch,{time:i+t})},e.start)}async unlock(){await Zs()}async play(){await Zs();let e=wl();if(e.seconds<.001){e.cancel();for(let e of this.allNotes)this.scheduleNoteRaw(e);this.autoStopAt!==null&&this.scheduleStopRaw(this.autoStopAt)}e.start()}pause(){wl().pause(),this.stopSynthVoices()}seek(e){let t=wl(),n=Math.max(0,e),r=t.state===`started`;r&&t.pause(),this.stopSynthVoices(),t.cancel(),t.seconds=n;for(let e of this.allNotes)e.start>=n&&this.scheduleNoteRaw(e);this.autoStopAt!==null&&this.autoStopAt>n&&this.scheduleStopRaw(this.autoStopAt),r&&t.start()}scrubTo(e){wl().seconds=Math.max(0,e)}stop(){let e=wl();e.stop(),e.cancel(),e.seconds=0,this.stopSynthVoices()}loadNotes(e){let t=wl(),n=t.seconds;t.cancel(),this.stopSynthVoices(),this.allNotes=e.map(e=>({...e})),this.pendingNotes=[];for(let e of this.allNotes)e.start>=n&&this.scheduleNoteRaw(e);let r=this.allNotes.reduce((e,t)=>Math.max(e,t.end),0);this.autoStopAt=r>0?r+.3:null,this.autoStopAt!==null&&this.autoStopAt>n&&this.scheduleStopRaw(this.autoStopAt)}reset(){this.stop(),this.allNotes=[],this.pendingNotes=[],this.autoStopAt=null,this.stopWavSource(),this.wavBuffer=null,this.mutedInstruments.clear();for(let e of this.channels.values())this.synth?.midiChannels[e]?.setSystemParameter(`isMuted`,!1);for(let e of this.fallbackSynths.values())e.volume.value=-10}scheduleStop(e){this.autoStopAt=e,this.scheduleStopRaw(e)}scheduleStopRaw(e){wl().scheduleOnce(()=>{wl().stop(),wl().seconds=0,this.stopSynthVoices()},e)}get seconds(){return wl().seconds}get duration(){return this.wavBuffer?.duration??0}get state(){return wl().state}},lf=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),uf=e(((e,t)=>{t.exports=lf()})),df=280,ff=1.5,pf=1.5;function mf(e){let t=1-e;return 1-t*t*t}var hf=80,gf=10,_f=2e3,vf=160,yf=21,bf=108,xf=84,Sf=64;function Cf(e){let t=(e%12+12)%12;return t===1||t===3||t===6||t===8||t===10}var wf=137.508,Tf=new Map;function Ef(e){let t=Tf.get(e);return t===void 0&&(t=Tf.size,Tf.set(e,t)),`hsl(${t*wf%360}, 70%, 55%)`}var Df=class{canvas;ctx;notes=[];hiddenInstruments=new Set;mutedInstruments=new Set;highlightedInstrument=null;playhead=0;chunkFrontier=null;latestNoteStart=0;transcribedSmooth=0;userOffset=null;lastOffset=0;_pxPerSec=hf;pxPerPitch=null;pitchTop=xf;contentDuration=0;get pxPerSec(){return this._pxPerSec}constructor(e){this.canvas=e,this.ctx=e.getContext(`2d`),this.resize(),window.addEventListener(`resize`,()=>this.resize())}resize(){let e=window.devicePixelRatio||1,t=this.canvas.getBoundingClientRect();this.canvas.width=t.width*e,this.canvas.height=t.height*e,this.ctx.setTransform(e,0,0,e,0,0)}addNote(e){this.notes.push(e),e.start>this.latestNoteStart&&(this.latestNoteStart=e.start)}setNoteEnd(e,t){e.end=t,e.spawn=performance.now();let n=!0;for(let t of this.notes){if(t===e){n=!1;continue}t.spawn===void 0||t.pitch!==e.pitch||t.starte&&(e=t.end);return e}contentEnd(){return Math.max(this.contentDuration,this.maxEnd())}clampOffset(e,t){let n=(this.canvas.getBoundingClientRect().width-56)/t,r=Math.max(0,this.contentEnd()-n);return Math.max(0,Math.min(e,r))}render(){let e=this.ctx,t=this.canvas.getBoundingClientRect(),n=t.width,r=t.height;e.clearRect(0,0,n,r);let i=n-56,a=Math.max(this.maxEnd(),this.playhead+1),o=i/this._pxPerSec,s;this.userOffset===null?(s=this.lastOffset,this.playhead>s+o*.66?s=this.playhead-o*.66:this.playheadbf||this.hiddenInstruments.has(t.instrument))continue;let i=56+(t.start-s)*c,a=Math.max(2,(t.end-t.start)*c-ff)*(t.spawn===void 0?1:mf(Math.min(1,(p-t.spawn)/df)));if(i+a<56||i>n)continue;let o=Math.min((t.stackOffset??0)*pf,h),d=(u-t.pitch)*l-o;if(d+l<0||d>r)continue;let f=this.mutedInstruments.has(t.instrument)?.2:1;this.highlightedInstrument!==null&&t.instrument!==this.highlightedInstrument&&(f=Math.min(f,.15)),e.globalAlpha=f,e.fillStyle=Ef(t.instrument),e.fillRect(i,d,a,Math.max(2,l-m))}e.globalAlpha=1;let g=56+(this.playhead-s)*c;e.strokeStyle=`#ff5577`,e.lineWidth=2,e.beginPath(),e.moveTo(g,0),e.lineTo(g,r),e.stroke(),e.restore(),this.drawKeyboard(e,r,l,u)}drawKeyboard(e,t,n,r){let i=n>=8;i&&(e.font=`10px sans-serif`,e.textBaseline=`middle`);for(let a=yf;a<=bf;a++){let o=(r-a)*n;o+n<0||o>t||(e.fillStyle=Cf(a)?`#23232b`:`#cfd2dc`,e.fillRect(0,o,56,n),e.strokeStyle=`#16161c`,e.lineWidth=1,e.beginPath(),e.moveTo(0,o+.5),e.lineTo(56,o+.5),e.stroke(),i&&a%12==0&&(e.fillStyle=`#16161c`,e.fillText(`C${a/12-1}`,4,o+n/2)))}e.strokeStyle=`#000`,e.lineWidth=1,e.beginPath(),e.moveTo(56.5,0),e.lineTo(56.5,t),e.stroke()}};export{l as a,cf as i,Ef as n,a as o,uf as r,t as s,Df as t}; \ No newline at end of file diff --git a/deployment.json b/deployment.json new file mode 100644 index 0000000000000000000000000000000000000000..34ea3461beb735d044ed46b7762797f40cd937f6 --- /dev/null +++ b/deployment.json @@ -0,0 +1,242 @@ +{ + "schema_version": 1, + "source_commit": "0ce98baefa7de35b185a66974c3f512ee6b7b4f5", + "source_branch": "main", + "source_dirty": true, + "build_command": "VITE_HENDRIX_SPACE=1 npx --yes pnpm@10.20.0 --dir demo/web build --manifest", + "checkpoint_sha256": "3df08bb38dce7ae30be23090524b63755c565d1a3242860aef6c9401fc125bbe", + "files": { + "README.md": { + "bytes": 2428, + "sha256": "1340d543066c6b908957e39a6e13d9c3f1d05372857fdeaee368d992d583bbb6" + }, + "assets/PianoRollCanvas-xSq9nagc.js": { + "bytes": 3055, + "sha256": "05090a468a79f356f2603f7105b26205be5703f5fffcb37bb2502317d4f9836f" + }, + "assets/local-56CJnE36.css": { + "bytes": 4149, + "sha256": "dfab143da9fda372f21e3513d3882baffdc7c40f4df51ad86f7ad3c01b34ef3d" + }, + "assets/local-DblFrGk8.js": { + "bytes": 133988, + "sha256": "215ca24985995907cf196d12e0d63ba585fc25e4fd0ff5893629ba63f7be3d17" + }, + "assets/ort-wasm-simd-threaded.asyncify-CvvOzbbq.wasm": { + "bytes": 24254953, + "sha256": "7e83cd6cee77e478bc96a7e91b198144fb5e4126287daf1f9b54bb195ebcd55a" + }, + "assets/spessasynth_processor.min-tdOdhV7p.js": { + "bytes": 396249, + "sha256": "fd3e25623e191efc4068e6cc44c7b0f4e3b508404c9088a77b6beedc7dbf861f" + }, + "assets/style-BAFoxh21.css": { + "bytes": 56584, + "sha256": "ba1247f859311f3b533b28aada5a316bf1edef2dd01be3216eecb0f1318f1205" + }, + "assets/style-CdJLhYve.js": { + "bytes": 644106, + "sha256": "1be18fcb99a202c31bfe5ab4154afda3aaeb95af45706ae534653910c0b914dc" + }, + "diagnostic.wav": { + "bytes": 65644, + "sha256": "1d2f1b3974848ea5a714c393b53e85a0d5c9d0d34cac846040ef293dbc961b8a" + }, + "favicon.png": { + "bytes": 4671, + "sha256": "5ff57d04a630614e38703856834d410bc3df02e7d6656c09d017406c63c1925d" + }, + "index.html": { + "bytes": 770, + "sha256": "ae09e25f5a38cb3af09085e6a4fd3379d8ed4b66d372289be41707ea40495f57" + }, + "local.html": { + "bytes": 770, + "sha256": "ae09e25f5a38cb3af09085e6a4fd3379d8ed4b66d372289be41707ea40495f57" + }, + "models/fp32/cross_cache.onnx": { + "bytes": 12648891, + "sha256": "cbfb5da1057eee995d5572c478705a5defb6c00d9fdcd96125cbe89072f24d53" + }, + "models/fp32/decoder_step.onnx": { + "bytes": 93343733, + "sha256": "6367704e25f718c962686b719537b43b1f7c4bdbaa84c3b36bd307323ccf72ca" + }, + "models/fp32/encoder.onnx": { + "bytes": 89354488, + "sha256": "786b70a7424531349f259cd867761b3eeb4c27696a0e5c7d03082678962bd912" + }, + "models/fp32/manifest.json": { + "bytes": 2921, + "sha256": "af943495d8272d7729f73face746c5f15be7e1f251fccc74a0e8244fc4a81d77" + }, + "ort/ort-wasm-simd-threaded.jsep.mjs": { + "bytes": 46614, + "sha256": "3ee381d20a80f51a788a1c4a5872f6f1d047538dd4342f4af00062de5f9ea4c6" + }, + "ort/ort-wasm-simd-threaded.jsep.wasm": { + "bytes": 26827543, + "sha256": "78feeeb3d08f6bcee94d938ed322f69073bb8076b5f9d34697a574ffba8deb48" + }, + "source/demo/web/compare.html": { + "bytes": 1141, + "sha256": "17aa0c9a8b01152b1c49057d30c80cc267373ce1f20744862e2f34335cfc5a62" + }, + "source/demo/web/index.html": { + "bytes": 1207, + "sha256": "f08c8bef6f294e96ca88802160e0ec70564cf886719b6d208693fac6216f718b" + }, + "source/demo/web/local.html": { + "bytes": 437, + "sha256": "7bff5d6d1f50e5a44aef947af1cefeb83abf244dd1b6360b0846225ca4afdd5d" + }, + "source/demo/web/package.json": { + "bytes": 948, + "sha256": "2d31d01dedf4556b6ca4907fdbbb287df932e9720d43629cee6068925b6e4be8" + }, + "source/demo/web/pnpm-lock.yaml": { + "bytes": 33463, + "sha256": "ddb399c0980adef3d3c4e33bb60787b4f9c5d9a072b9bbe95a9c4864e142dc5b" + }, + "source/demo/web/public/favicon.png": { + "bytes": 4671, + "sha256": "5ff57d04a630614e38703856834d410bc3df02e7d6656c09d017406c63c1925d" + }, + "source/demo/web/src/App.tsx": { + "bytes": 15167, + "sha256": "a7368c93040a5e59b8889ee94a8c2e2693f0fd6f0c19dcc8d94a0a24d20317ad" + }, + "source/demo/web/src/audio.ts": { + "bytes": 19304, + "sha256": "8e9d876bbeef997e5d5fe740cee5b6d219f815aa2b821a02fd0c718b00dc6174" + }, + "source/demo/web/src/compare.tsx": { + "bytes": 33406, + "sha256": "fbd9765e7dda9c2154a28d43e80a4224d37ef265ec110e2e919c095603545c96" + }, + "source/demo/web/src/components/ConditioningPanel.tsx": { + "bytes": 7009, + "sha256": "2b94c6c9abf11a06e65f33048c37d2d23524d58ce3640daea0468914c1252df5" + }, + "source/demo/web/src/components/Controls.tsx": { + "bytes": 4477, + "sha256": "3750944349448f2a5db019bae4545bf5133f3c355d7027dc8e776dcd3d3a9f58" + }, + "source/demo/web/src/components/DropOverlay.tsx": { + "bytes": 1156, + "sha256": "cb35ddc8606134742af66760684ebda67aed1965e285ed8b60925bc5c9b78b6d" + }, + "source/demo/web/src/components/Footer.tsx": { + "bytes": 1544, + "sha256": "e8c1200535086ed7cf702fee4efd33021f4514a31d93fd113ff874a68b81ed8c" + }, + "source/demo/web/src/components/InstrumentList.tsx": { + "bytes": 7707, + "sha256": "abea54518c2130241aabf8123a02485add70d178db3cd0a1aebaa5e57588fe7e" + }, + "source/demo/web/src/components/OutputBar.tsx": { + "bytes": 6629, + "sha256": "619254150609f6362acd9b43c9ad694c52a07511c9b9efbf42e7a8f1d322c3b9" + }, + "source/demo/web/src/components/PianoRollCanvas.tsx": { + "bytes": 7960, + "sha256": "fc67a13f6d5f13102702c33b7707a9d10f171fc7e95ddfb748a56224ab5d11cd" + }, + "source/demo/web/src/components/WelcomeScreen.tsx": { + "bytes": 6592, + "sha256": "d2677506ae098d98eae41b3ced56d3a88ba4b1a7b4947e22a6fbdef324cc490b" + }, + "source/demo/web/src/components/icons.tsx": { + "bytes": 1913, + "sha256": "c09441e24c6ccf79b466852ec2ed72709dc6205820438c01638586222882ae2f" + }, + "source/demo/web/src/hooks/useAudioEngine.ts": { + "bytes": 732, + "sha256": "c70379f29702324446ead26ba5308d21c307c6c59611b3ece6dfdf2fbd85b1d6" + }, + "source/demo/web/src/hooks/useTranscription.ts": { + "bytes": 8771, + "sha256": "65c1604cdff77546e694222d5f72dfdc19b19269c62481a230c515bc6efbb37f" + }, + "source/demo/web/src/instruments.ts": { + "bytes": 6027, + "sha256": "bbfe086dabe0e270ae70be6e3302818dff1d49e619a87370f06d40d066e415cf" + }, + "source/demo/web/src/local/codec.ts": { + "bytes": 8414, + "sha256": "37c5bdc987216cb7b042f6b79ad61e2a592bd7ff98bc58702b505dc3a629d027" + }, + "source/demo/web/src/local/dsp.ts": { + "bytes": 5633, + "sha256": "017ca4ab6ce2e3bc40307cdada62ce9597ea816df805ff93ff1710d93664c9d1" + }, + "source/demo/web/src/local/float16.ts": { + "bytes": 787, + "sha256": "2124afe19c0654456ffe22a2ad247c7948d01dbdc0b0e4022556e0aeb25024dc" + }, + "source/demo/web/src/local/local.css": { + "bytes": 4682, + "sha256": "d7060987283fc6b6d102e2e35077a74a46d6274db1a4a2e2b34ef4ec8c1591c4" + }, + "source/demo/web/src/local/midi.ts": { + "bytes": 2445, + "sha256": "fffabd0db926f7a44541f50524f642931c88fe2aeb44953743524723f106c767" + }, + "source/demo/web/src/local/model.ts": { + "bytes": 13379, + "sha256": "461a7c37240940c440694d7a65cc18c47090b8429bbeb1daa5a6175440c75c99" + }, + "source/demo/web/src/local.tsx": { + "bytes": 15344, + "sha256": "e0ad3fe81c9272536e3f0dd0eea05365b10cdc49329d5f8f50646933d18446cb" + }, + "source/demo/web/src/main.tsx": { + "bytes": 381, + "sha256": "76e1cac7b31bfb00a1f3582616a43fd669114adaa9110284481c2933277080af" + }, + "source/demo/web/src/pianoroll.ts": { + "bytes": 19132, + "sha256": "e44be0447e0fe1f5923b9d815485855b0ec1bfa56adfa7de24cc9242d53ca295" + }, + "source/demo/web/src/progress.ts": { + "bytes": 3563, + "sha256": "2a66fd30476dff84ce70772e57cbd92c53f1a6dec7f3a7077b57c8a648a9394b" + }, + "source/demo/web/src/sse.ts": { + "bytes": 2194, + "sha256": "348773394753d61bfb89d900cbede71330b5943898041c115e94b1ba5e1b42ea" + }, + "source/demo/web/src/style.css": { + "bytes": 39145, + "sha256": "0f2624ee4074d57ba3794980d22ebd6e2bd45e42877cfb4cc47acacf261cfd75" + }, + "source/demo/web/src/vite-env.d.ts": { + "bytes": 38, + "sha256": "65996936fbb042915f7b74a200fcdde7e410f32a669b1ab9597cfaa4b0faddb5" + }, + "source/demo/web/tsconfig.json": { + "bytes": 389, + "sha256": "6091edf460498911c41bafc771226fc718b17ae792f3dbaab24555ba40a56d07" + }, + "source/demo/web/vite.config.ts": { + "bytes": 1158, + "sha256": "2e3e6765cca9de53a0f23e42a52f4f152b9789b36e630345c9e2e6fb3f1b8475" + }, + "source/deploy/huggingface/README.md": { + "bytes": 2428, + "sha256": "1340d543066c6b908957e39a6e13d9c3f1d05372857fdeaee368d992d583bbb6" + }, + "source/docs/assets/choir_bwv407.wav": { + "bytes": 960044, + "sha256": "2640f4fe1b68b6d5f8392c688d5a919ac0e89a6b017d3c3f41ebad5bb72d6e0f" + }, + "source/scripts/check_huggingface_space.mjs": { + "bytes": 4632, + "sha256": "142f3dac4055c333601d21b741dc2cc26fd1518cf4e98e8842bbdbd7edc012de" + }, + "source/scripts/deploy_huggingface_space.py": { + "bytes": 7745, + "sha256": "329be2f93c6eee411202c70a79f8cb3329fc48c937811c74d02a703f16f80562" + } + } +} diff --git a/diagnostic.wav b/diagnostic.wav new file mode 100644 index 0000000000000000000000000000000000000000..3c0fd49ab9a97a05313f61ff3a519b1335f91ddf Binary files /dev/null and b/diagnostic.wav differ diff --git a/favicon.png b/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..7c8790cdc9d8aacda6f8cd34623eb9944be327bb Binary files /dev/null and b/favicon.png differ diff --git a/index.html b/index.html index b0c4b3666032a737f3903db53e6a8a9272483e28..bdd056b7555cd86cd0a4889c3f87272a24e34696 100644 --- a/index.html +++ b/index.html @@ -1,19 +1,18 @@ - - - - - My static Space - - - -
-

Welcome to your static Space!

-

You can modify this app directly by editing index.html in the Files and versions tab.

-

- Also don't forget to check the - Spaces documentation. -

-
- + + + + + + + Hendrix — on-device transcription + + + + + + + +
+ diff --git a/local.html b/local.html new file mode 100644 index 0000000000000000000000000000000000000000..bdd056b7555cd86cd0a4889c3f87272a24e34696 --- /dev/null +++ b/local.html @@ -0,0 +1,18 @@ + + + + + + + + Hendrix — on-device transcription + + + + + + + +
+ + diff --git a/models/fp32/cross_cache.onnx b/models/fp32/cross_cache.onnx new file mode 100644 index 0000000000000000000000000000000000000000..5298ade8caa51e1abf3874ee1cdfe2903c4c8083 --- /dev/null +++ b/models/fp32/cross_cache.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbfb5da1057eee995d5572c478705a5defb6c00d9fdcd96125cbe89072f24d53 +size 12648891 diff --git a/models/fp32/decoder_step.onnx b/models/fp32/decoder_step.onnx new file mode 100644 index 0000000000000000000000000000000000000000..bf0aa14408fa588f0c5913623d01ec50c9d85225 --- /dev/null +++ b/models/fp32/decoder_step.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6367704e25f718c962686b719537b43b1f7c4bdbaa84c3b36bd307323ccf72ca +size 93343733 diff --git a/models/fp32/encoder.onnx b/models/fp32/encoder.onnx new file mode 100644 index 0000000000000000000000000000000000000000..7d31a71e75f1a4f8a465f0167f0d6da09d3a0e41 --- /dev/null +++ b/models/fp32/encoder.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:786b70a7424531349f259cd867761b3eeb4c27696a0e5c7d03082678962bd912 +size 89354488 diff --git a/models/fp32/manifest.json b/models/fp32/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..5aab9c44543153408f44088a387ccd12448eb2b1 --- /dev/null +++ b/models/fp32/manifest.json @@ -0,0 +1,111 @@ +{ + "schema_version": 1, + "checkpoint": { + "path": "yptf_allmetric_rwc_pg_support2_d26.pt", + "sha256": "3df08bb38dce7ae30be23090524b63755c565d1a3242860aef6c9401fc125bbe", + "file_bytes": 189496364 + }, + "source_revision": "5e66c1ea173a8186e0d20432b841d3180cc015b5", + "precision": "fp32", + "export_math_replacements": { + "rotary": 3, + "moe": 12 + }, + "runtime_contract": { + "sample_rate": 16000, + "input_frames": 32767, + "segment_seconds": 2.0479375, + "stft_shape": [ + 1, + 110, + 1024 + ], + "channels": 13, + "max_tokens": 256, + "decoder": "greedy cached autoregressive" + }, + "graphs": { + "encoder": { + "path": "encoder.onnx", + "sha256": "786b70a7424531349f259cd867761b3eeb4c27696a0e5c7d03082678962bd912", + "bytes": 89354488, + "nodes": 1783, + "operators": { + "Add": 201, + "AveragePool": 3, + "Concat": 30, + "Conv": 7, + "Div": 27, + "Equal": 96, + "Expand": 2, + "Gemm": 300, + "LayerNormalization": 30, + "MatMul": 91, + "Mul": 318, + "Neg": 15, + "ReduceSum": 108, + "Relu": 6, + "Reshape": 130, + "Sigmoid": 96, + "Slice": 60, + "Softmax": 27, + "Squeeze": 30, + "TopK": 12, + "Transpose": 68, + "Unsqueeze": 30, + "Where": 96 + }, + "export_sec": 6.482101709989365, + "precision_conversion_sec": 0.0, + "ort_cpu_sec": 0.20406562398420647, + "max_abs_error": 3.552436828613281e-05, + "mean_abs_error": 8.357006322512461e-07 + }, + "cross_cache": { + "path": "cross_cache.onnx", + "sha256": "cbfb5da1057eee995d5572c478705a5defb6c00d9fdcd96125cbe89072f24d53", + "bytes": 12648891, + "nodes": 49, + "operators": { + "MatMul": 16, + "Reshape": 17, + "Transpose": 16 + }, + "export_sec": 0.6789736609789543, + "precision_conversion_sec": 0.0, + "ort_cpu_sec": 0.007953249965794384, + "worst_output_max_abs_error": 2.288818359375e-05 + }, + "decoder_step": { + "path": "decoder_step.onnx", + "sha256": "6367704e25f718c962686b719537b43b1f7c4bdbaa84c3b36bd307323ccf72ca", + "bytes": 93343733, + "nodes": 528, + "operators": { + "Add": 66, + "Concat": 16, + "Gather": 2, + "MatMul": 105, + "Mul": 91, + "Pow": 33, + "Reciprocal": 25, + "ReduceMean": 25, + "Reshape": 52, + "Softmax": 16, + "Sqrt": 25, + "Tanh": 8, + "Transpose": 64 + }, + "export_sec": 2.754342700005509, + "precision_conversion_sec": 0.0, + "ort_cpu_sec": 0.01502414100104943, + "logits": { + "max_abs_error": 0.000213623046875, + "mean_abs_error": 2.1228790501481853e-05 + }, + "argmax_equal": true, + "worst_cache_max_abs_error": 2.0265579223632812e-06 + } + }, + "total_graph_bytes": 195347112 +} diff --git a/ort/ort-wasm-simd-threaded.jsep.mjs b/ort/ort-wasm-simd-threaded.jsep.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0c3f883eff71ab2be163de744cb1f40f4d8e380a --- /dev/null +++ b/ort/ort-wasm-simd-threaded.jsep.mjs @@ -0,0 +1,106 @@ +async function ortWasmThreaded(moduleArg={}){var moduleRtn;var f=moduleArg,aa=!!globalThis.window,ba=!!globalThis.WorkerGlobalScope,h=globalThis.process?.versions?.node&&"renderer"!=globalThis.process?.type,m=ba&&self.name?.startsWith("em-pthread");if(h){const {createRequire:a}=await import("module");var require=a(import.meta.url),ca=require("worker_threads");global.Worker=ca.Worker;m=(ba=!ca.Xd)&&"em-pthread"==ca.workerData}f.mountExternalData=(a,b)=>{a.startsWith("./")&&(a=a.substring(2));(f.Xc||(f.Xc=new Map)).set(a,b)}; +f.unmountExternalData=()=>{delete f.Xc};var SharedArrayBuffer=globalThis.SharedArrayBuffer??(new WebAssembly.Memory({initial:0,maximum:0,shared:!0})).buffer.constructor;const da=a=>async(...b)=>{try{if(f.Yc)throw Error("Session already started");const d=f.Yc={Kd:b[0],errors:[]},c=await a(...b);if(f.Yc!==d)throw Error("Session mismatch");f.dd?.flush();const e=d.errors;if(0k);if(0{if("webgpu"===a){[f.dd,f.Ad,f.Ed,f.ed,f.Dd,f.$b,f.Fd,f.Hd,f.Bd,f.Cd,f.Gd]=b;const d=f.dd;f.jsepRegisterBuffer=(c,e,g,k)=>d.registerBuffer(c,e,g,k);f.jsepGetBuffer=c=>d.getBuffer(c);f.jsepCreateDownloader=(c,e,g)=>d.createDownloader(c,e,g);f.jsepOnCreateSession=c=>{d.onCreateSession(c)};f.jsepOnReleaseSession=c=>{d.onReleaseSession(c)};f.jsepOnRunStart=c=>d.onRunStart(c);f.Id=(c,e)=>{d.upload(c,e)}}else if("webnn"===a){const d=b[0];[f.Sd,f.sd,f.webnnEnsureTensor,f.td,f.webnnDownloadTensor, +f.Rd,f.webnnEnableTraceEvent]=b.slice(1);f.webnnReleaseTensorId=f.sd;f.webnnUploadTensor=f.td;f.webnnRegisterMLContext=f.Rd;f.webnnOnRunStart=c=>d.onRunStart(c);f.webnnOnRunEnd=d.onRunEnd.bind(d);f.webnnOnReleaseSession=c=>{d.onReleaseSession(c)};f.webnnCreateMLTensorDownloader=(c,e)=>d.createMLTensorDownloader(c,e);f.webnnRegisterMLTensor=(c,e,g,k)=>d.registerMLTensor(c,e,g,k);f.webnnCreateMLContext=c=>d.createMLContext(c);f.webnnRegisterMLConstant=(c,e,g,k,l,n)=>d.registerMLConstant(c,e,g,k,l,f.Xc, +n);f.webnnRegisterGraphInput=d.registerGraphInput.bind(d);f.webnnIsGraphInput=d.isGraphInput.bind(d);f.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d);f.webnnIsGraphOutput=d.isGraphOutput.bind(d);f.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d);f.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)}}; +let fa=()=>{const a=b=>(...d)=>{const c=q;d=b(...d);return q!=c?ea():d};(b=>{for(const d of b)f[d]=a(f[d])})(["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"]);"undefined"!==typeof da&&(f._OrtRun=da(f._OrtRun),f._OrtRunWithBinding=da(f._OrtRunWithBinding));fa=void 0};f.asyncInit=()=>{fa?.()};var ha="./this.program",ia=(a,b)=>{throw b;},ja=import.meta.url,ka="",la,ma; +if(h){var fs=require("fs");ja.startsWith("file:")&&(ka=require("path").dirname(require("url").fileURLToPath(ja))+"/");ma=a=>{a=na(a)?new URL(a):a;return fs.readFileSync(a)};la=async a=>{a=na(a)?new URL(a):a;return fs.readFileSync(a,void 0)};1{process.exitCode=a;throw b;}}else if(aa||ba){try{ka=(new URL(".",ja)).href}catch{}h||(ba&&(ma=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer"; +b.send(null);return new Uint8Array(b.response)}),la=async a=>{if(na(a))return new Promise((d,c)=>{var e=new XMLHttpRequest;e.open("GET",a,!0);e.responseType="arraybuffer";e.onload=()=>{200==e.status||0==e.status&&e.response?d(e.response):c(e.status)};e.onerror=c;e.send(null)});var b=await fetch(a,{credentials:"same-origin"});if(b.ok)return b.arrayBuffer();throw Error(b.status+" : "+b.url);})}var oa=console.log.bind(console),pa=console.error.bind(console); +if(h){var qa=require("util"),ra=a=>"object"==typeof a?qa.inspect(a):a;oa=(...a)=>fs.writeSync(1,a.map(ra).join(" ")+"\n");pa=(...a)=>fs.writeSync(2,a.map(ra).join(" ")+"\n")}var sa=oa,r=pa,ta,ua,t=!1,va,na=a=>a.startsWith("file://");function v(){x.buffer!=A.buffer&&wa()}var xa,ya; +if(h&&m){var za=ca.parentPort;za.on("message",a=>global.onmessage?.({data:a}));Object.assign(globalThis,{self:global,postMessage:a=>za.postMessage(a)});process.on("uncaughtException",a=>{postMessage({Sc:"uncaughtException",error:a});process.exit(1)})}var Aa; +if(m){var Ba=!1;self.onunhandledrejection=b=>{throw b.reason||b;};function a(b){try{var d=b.data,c=d.Sc;if("load"===c){let e=[];self.onmessage=g=>e.push(g);Aa=()=>{postMessage({Sc:"loaded"});for(let g of e)a(g);self.onmessage=a};for(const g of d.xd)if(!f[g]||f[g].proxy)f[g]=(...k)=>{postMessage({Sc:"callHandler",wd:g,args:k})},"print"==g&&(sa=f[g]),"printErr"==g&&(r=f[g]);x=d.Od;wa();ua=d.Pd;Ca();Da()}else if("run"===c){Ea(d.Rc);Fa(d.Rc,0,0,1,0,0);Ga();Ha(d.Rc);Ba||(Ia(),Ba=!0);try{Ja(d.Md,d.bd)}catch(e){if("unwind"!= +e)throw e;}}else"setimmediate"!==d.target&&("checkMailbox"===c?Ba&&Ka():c&&(r(`worker: received unknown command ${c}`),r(d)))}catch(e){throw La(),e;}}self.onmessage=a}var A,B,Ma,Na,C,D,Oa,E,F,Pa,Qa=!1;function wa(){var a=x.buffer;f.HEAP8=A=new Int8Array(a);Ma=new Int16Array(a);f.HEAPU8=B=new Uint8Array(a);Na=new Uint16Array(a);f.HEAP32=C=new Int32Array(a);f.HEAPU32=D=new Uint32Array(a);Oa=new Float32Array(a);E=new Float64Array(a);F=new BigInt64Array(a);Pa=new BigUint64Array(a)} +function Ra(){Qa=!0;m?Aa():G.sb()}function H(a){a="Aborted("+a+")";r(a);t=!0;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");ya?.(a);throw a;}var Sa;async function Ta(a){if(!ta)try{var b=await la(a);return new Uint8Array(b)}catch{}if(a==Sa&&ta)a=new Uint8Array(ta);else if(ma)a=ma(a);else throw"both async and sync fetching of the wasm failed";return a} +async function Ua(a,b){try{var d=await Ta(a);return await WebAssembly.instantiate(d,b)}catch(c){r(`failed to asynchronously prepare wasm: ${c}`),H(c)}}async function Va(a){var b=Sa;if(!ta&&!na(b)&&!h)try{var d=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(d,a)}catch(c){r(`wasm streaming compile failed: ${c}`),r("falling back to ArrayBuffer instantiation")}return Ua(b,a)} +function Wa(){Xa={ma:Ya,gb:Za,g:$a,J:ab,f:bb,o:cb,h:db,ha:eb,b:fb,T:gb,Ha:hb,n:ib,$:jb,Xa:mb,Da:nb,Fa:ob,Ya:pb,Va:qb,Oa:rb,Ua:sb,ka:tb,Ea:ub,Ba:vb,Wa:wb,Ca:xb,bb:yb,ea:zb,wa:Ab,ua:Bb,da:Cb,O:Db,H:Eb,va:Fb,_:Gb,xa:Hb,Ra:Ib,za:Jb,Ia:Kb,sa:Lb,fa:Mb,Qa:Ha,_a:Nb,R:Ob,r:Pb,c:Qb,hb:Rb,y:Sb,M:Tb,D:Ub,l:Vb,s:Wb,ib:Xb,I:Yb,S:Zb,j:$b,u:ac,q:bc,k:cc,La:dc,Ma:ec,Na:fc,Ja:gc,Ka:hc,ta:ic,db:jc,ab:kc,v:lc,aa:mc,ga:nc,$a:oc,W:pc,Za:qc,Aa:rc,F:sc,U:tc,la:uc,ya:vc,fb:wc,eb:xc,Sa:yc,Ta:zc,Ga:Ac,V:Bc,ja:Cc,Pa:Dc,ia:Ec, +kb:Fc,na:Gc,lb:Hc,oa:Ic,G:Jc,e:Kc,t:Lc,w:Mc,B:Nc,mb:Oc,K:Pc,x:Qc,pa:Rc,Y:Sc,ba:Tc,nb:Uc,ob:Vc,P:Wc,qa:Xc,pb:Yc,N:Zc,Z:$c,d:ad,A:bd,m:cd,jb:dd,p:ed,z:fd,C:gd,E:hd,L:jd,qb:kd,Q:ld,ca:md,X:nd,rb:od,ra:pd,i:qd,a:x,cb:rd};return{a:Xa}} +async function Ca(){function a(c,e){var g=G=c.exports;c={};for(let [k,l]of Object.entries(g))"function"==typeof l?(g=sd(l),c[k]=g):c[k]=l;G=c;G=td();ud.push(G._b);c=G;vd=c.tb;Ia=c.ub;f._OrtInit=c.vb;f._OrtGetLastError=c.wb;f._OrtCreateSessionOptions=c.xb;f._OrtAppendExecutionProvider=c.yb;f._OrtAddFreeDimensionOverride=c.zb;f._OrtAddSessionConfigEntry=c.Ab;f._OrtReleaseSessionOptions=c.Bb;f._OrtCreateSession=c.Cb;f._OrtReleaseSession=c.Db;f._OrtGetInputOutputCount=c.Eb;f._OrtGetInputOutputMetadata= +c.Fb;f._OrtFree=c.Gb;f._OrtCreateTensor=c.Hb;f._OrtGetTensorData=c.Ib;f._OrtReleaseTensor=c.Jb;f._OrtCreateRunOptions=c.Kb;f._OrtAddRunConfigEntry=c.Lb;f._OrtReleaseRunOptions=c.Mb;f._OrtCreateBinding=c.Nb;f._OrtBindInput=c.Ob;f._OrtBindOutput=c.Pb;f._OrtClearBoundOutputs=c.Qb;f._OrtReleaseBinding=c.Rb;f._OrtRunWithBinding=c.Sb;f._OrtRun=c.Tb;f._OrtEndProfiling=c.Ub;f._JsepOutput=c.Vb;f._JsepGetNodeName=c.Wb;wd=c.Xb;I=f._free=c.Yb;xd=f._malloc=c.Zb;Fa=c.ac;La=c.bc;yd=c.cc;zd=c.dc;Ad=c.ec;Bd=c.fc; +Cd=c.gc;J=c.hc;Dd=c.ic;Ed=c.jc;K=c.kc;Fd=c.lc;L=c.mc;Gd=c.nc;Hd=c.oc;Id=c.pc;Jd=c.qc;dynCall_vii=c.rc;Kd=c.sc;dynCall_v=c.tc;Ld=c.uc;Md=c.vc;dynCall_iii=c.wc;Nd=c.xc;Od=c.yc;Pd=c.zc;Qd=c.Ac;dynCall_vi=c.Bc;Rd=c.Cc;Sd=c.Dc;Td=c.Ec;Ud=c.Fc;Vd=c.Gc;Wd=c.Hc;Xd=c.Ic;Yd=c.Jc;Zd=c.Kc;$d=c.Lc;ae=c.Mc;be=c.Nc;ce=c.Pc;de=c.Qc;ee=c.$c;fe=c.ad;ge=c.fd;he=c.jd;ie=c.kd;je=c.ld;ke=c.md;le=c.nd;me=c.od;ne=c.pd;oe=c.qd;pe=c.vd;qe=c.Td;re=c.Ud;se=c.Vd;te=c.Wd;ua=e;return G}var b=Wa();if(f.instantiateWasm)return new Promise(c=> +{f.instantiateWasm(b,(e,g)=>{c(a(e,g))})});if(m){var d=new WebAssembly.Instance(ua,Wa());return a(d,ua)}Sa??=f.locateFile?f.locateFile?f.locateFile("ort-wasm-simd-threaded.jsep.wasm",ka):ka+"ort-wasm-simd-threaded.jsep.wasm":(new URL("ort-wasm-simd-threaded.jsep.wasm",import.meta.url)).href;return function(c){return a(c.instance,c.module)}(await Va(b))}class ue{name="ExitStatus";constructor(a){this.message=`Program terminated with exit(${a})`;this.status=a}} +var ve=a=>{a.terminate();a.onmessage=()=>{}},we=[],xe=0,ye=null,Ce=a=>{0==M.length&&(ze(),Ae(M[0]));var b=M.pop();if(!b)return 6;Be.push(b);N[a.Rc]=b;b.Rc=a.Rc;var d={Sc:"run",Md:a.Ld,bd:a.bd,Rc:a.Rc};h&&b.unref();b.postMessage(d,a.rd);return 0},O=0,P=(a,b,...d)=>{var c=16*d.length,e=L(),g=Fd(c),k=g>>>3,l;for(l of d)"bigint"==typeof l?((v(),F)[k++>>>0]=1n,(v(),F)[k++>>>0]=l):((v(),F)[k++>>>0]=0n,(v(),E)[k++>>>0]=l);a=yd(a,0,c,g,b);K(e);return a}; +function rd(a){if(m)return P(0,1,a);va=a;if(!(0{va=a;if(m)throw De(a),"unwind";rd(a)},M=[],Be=[],ud=[],N={};function Ee(){for(var a=f.numThreads-1;a--;)ze();we.push(async()=>{var b=Fe();xe++;await b;xe--;0==xe&&ye&&(b=ye,ye=null,b())})}var Ge=a=>{var b=a.Rc;delete N[b];M.push(a);Be.splice(Be.indexOf(a),1);a.Rc=0;zd(b)};function Ga(){ud.forEach(a=>a())} +var Ae=a=>new Promise(b=>{a.onmessage=g=>{var k=g.data;g=k.Sc;if(k.Zc&&k.Zc!=wd()){var l=N[k.Zc];l?l.postMessage(k,k.rd):r(`Internal error! Worker sent a message "${g}" to target pthread ${k.Zc}, but that thread no longer exists!`)}else if("checkMailbox"===g)Ka();else if("spawnThread"===g)Ce(k);else if("cleanupThread"===g)He(()=>{Ge(N[k.Nd])});else if("loaded"===g)a.loaded=!0,h&&!a.Rc&&a.unref(),b(a);else if("setimmediate"===k.target)a.postMessage(k);else if("uncaughtException"===g)a.onerror(k.error); +else if("callHandler"===g)f[k.wd](...k.args);else g&&r(`worker sent an unknown command ${g}`)};a.onerror=g=>{r(`${"worker sent an error!"} ${g.filename}:${g.lineno}: ${g.message}`);throw g;};h&&(a.on("message",g=>a.onmessage({data:g})),a.on("error",g=>a.onerror(g)));var d=[],c=[],e;for(e of c)f.propertyIsEnumerable(e)&&d.push(e);a.postMessage({Sc:"load",xd:d,Od:x,Pd:ua})});async function Fe(){if(!m)return Promise.all(M.map(Ae))} +function ze(){var a=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});M.push(a)}function Ea(a){var b=(v(),D)[a+52>>>2>>>0];a=(v(),D)[a+56>>>2>>>0];Ed(b,b-a);K(b)}var Ja=(a,b)=>{O=0;a=Kd(a,b);0>>=0;var b=new Ke(a);0==(v(),A)[b.Tc+12>>>0]&&(Le(b,!0),Je--);Me(b,!1);Ie.push(b);return Jd(a)}var Q=0,ab=()=>{J(0,0);var a=Ie.pop();Gd(a.cd);Q=0}; +function Le(a,b){b=b?1:0;(v(),A)[a.Tc+12>>>0]=b}function Me(a,b){b=b?1:0;(v(),A)[a.Tc+13>>>0]=b}class Ke{constructor(a){this.cd=a;this.Tc=a-24}}var Ne=a=>{var b=Q;if(!b)return Dd(0),0;var d=new Ke(b);(v(),D)[d.Tc+16>>>2>>>0]=b;var c=(v(),D)[d.Tc+4>>>2>>>0];if(!c)return Dd(0),b;for(var e of a){if(0===e||e===c)break;if(Id(e,c,d.Tc+16))return Dd(e),b}Dd(c);return b};function bb(){return Ne([])}function cb(a){return Ne([a>>>0])}function db(a,b,d,c){return Ne([a>>>0,b>>>0,d>>>0,c>>>0])} +var eb=()=>{var a=Ie.pop();a||H("no exception to throw");var b=a.cd;0==(v(),A)[a.Tc+13>>>0]&&(Ie.push(a),Me(a,!0),Le(a,!1),Je++);Hd(b);Q=b;throw Q;};function fb(a,b,d){a>>>=0;var c=new Ke(a);b>>>=0;d>>>=0;(v(),D)[c.Tc+16>>>2>>>0]=0;(v(),D)[c.Tc+4>>>2>>>0]=b;(v(),D)[c.Tc+8>>>2>>>0]=d;Hd(a);Q=a;Je++;throw Q;}var gb=()=>Je;function Oe(a,b,d,c){return m?P(2,1,a,b,d,c):hb(a,b,d,c)} +function hb(a,b,d,c){a>>>=0;b>>>=0;d>>>=0;c>>>=0;if(!globalThis.SharedArrayBuffer)return 6;var e=[];if(m&&0===e.length)return Oe(a,b,d,c);a={Ld:d,Rc:a,bd:c,rd:e};return m?(a.Sc="spawnThread",postMessage(a,e),0):Ce(a)}function ib(a){Q||=a>>>0;throw Q;} +var Pe=globalThis.TextDecoder&&new TextDecoder,Qe=(a,b,d,c)=>{d=b+d;if(c)return d;for(;a[b]&&!(b>=d);)++b;return b},Re=(a,b=0,d,c)=>{b>>>=0;d=Qe(a,b,d,c);if(16e?c+=String.fromCharCode(e):(e-=65536,c+=String.fromCharCode(55296| +e>>10,56320|e&1023))}}else c+=String.fromCharCode(e)}return c},R=(a,b,d)=>(a>>>=0)?Re((v(),B),a,b,d):"";function jb(a,b,d){return m?P(3,1,a,b,d):0}function mb(a,b){if(m)return P(4,1,a,b)}function nb(a,b){if(m)return P(5,1,a,b)}function ob(a,b,d){if(m)return P(6,1,a,b,d)}function pb(a,b,d){return m?P(7,1,a,b,d):0}function qb(a,b){if(m)return P(8,1,a,b)}function rb(a,b,d){if(m)return P(9,1,a,b,d)}function sb(a,b,d,c){if(m)return P(10,1,a,b,d,c)}function tb(a,b,d,c){if(m)return P(11,1,a,b,d,c)} +function ub(a,b,d,c){if(m)return P(12,1,a,b,d,c)}function vb(a){if(m)return P(13,1,a)}function wb(a,b){if(m)return P(14,1,a,b)}function xb(a,b,d){if(m)return P(15,1,a,b,d)}var yb=()=>H(""),S=a=>{a>>>=0;for(var b="";;){var d=(v(),B)[a++>>>0];if(!d)return b;b+=String.fromCharCode(d)}},Se={},Te={},Ue={},Ve=class extends Error{constructor(a){super(a);this.name="BindingError"}}; +function We(a,b,d={}){var c=b.name;if(!a)throw new Ve(`type "${c}" must have a positive integer typeid pointer`);if(Te.hasOwnProperty(a)){if(d.yd)return;throw new Ve(`Cannot register type '${c}' twice`);}Te[a]=b;delete Ue[a];Se.hasOwnProperty(a)&&(b=Se[a],delete Se[a],b.forEach(e=>e()))}function T(a,b,d={}){return We(a,b,d)} +var Xe=(a,b,d)=>{switch(b){case 1:return d?c=>(v(),A)[c>>>0]:c=>(v(),B)[c>>>0];case 2:return d?c=>(v(),Ma)[c>>>1>>>0]:c=>(v(),Na)[c>>>1>>>0];case 4:return d?c=>(v(),C)[c>>>2>>>0]:c=>(v(),D)[c>>>2>>>0];case 8:return d?c=>(v(),F)[c>>>3>>>0]:c=>(v(),Pa)[c>>>3>>>0];default:throw new TypeError(`invalid integer width (${b}): ${a}`);}}; +function zb(a,b,d,c,e){a>>>=0;d>>>=0;b=S(b>>>0);c=0n===c;let g=k=>k;if(c){const k=8*d;g=l=>BigInt.asUintN(k,l);e=g(e)}T(a,{name:b,Oc:g,Vc:(k,l)=>{"number"==typeof l&&(l=BigInt(l));return l},Uc:Xe(b,d,!c),Wc:null})}function Ab(a,b,d,c){a>>>=0;b=S(b>>>0);T(a,{name:b,Oc:function(e){return!!e},Vc:function(e,g){return g?d:c},Uc:function(e){return this.Oc((v(),B)[e>>>0])},Wc:null})}var Ye=[],U=[0,1,,1,null,1,!0,1,!1,1];function Qb(a){a>>>=0;9{if(!a)throw new Ve(`Cannot use deleted val. handle = ${a}`);return U[a]},X=a=>{switch(a){case void 0:return 2;case null:return 4;case !0:return 6;case !1:return 8;default:const b=Ye.pop()||U.length;U[b]=a;U[b+1]=1;return b}};function Ze(a){return this.Oc((v(),D)[a>>>2>>>0])}var $e={name:"emscripten::val",Oc:a=>{var b=V(a);Qb(a);return b},Vc:(a,b)=>X(b),Uc:Ze,Wc:null};function Bb(a){return T(a>>>0,$e)} +var af=(a,b)=>{switch(b){case 4:return function(d){return this.Oc((v(),Oa)[d>>>2>>>0])};case 8:return function(d){return this.Oc((v(),E)[d>>>3>>>0])};default:throw new TypeError(`invalid float width (${b}): ${a}`);}};function Cb(a,b,d){a>>>=0;d>>>=0;b=S(b>>>0);T(a,{name:b,Oc:c=>c,Vc:(c,e)=>e,Uc:af(b,d),Wc:null})}function Db(a,b,d,c,e){a>>>=0;d>>>=0;b=S(b>>>0);let g=l=>l;if(0===c){var k=32-8*d;g=l=>l<>>k;e=g(e)}T(a,{name:b,Oc:g,Vc:(l,n)=>n,Uc:Xe(b,d,0!==c),Wc:null})} +function Eb(a,b,d){function c(g){var k=(v(),D)[g>>>2>>>0];g=(v(),D)[g+4>>>2>>>0];return new e((v(),A).buffer,g,k)}a>>>=0;var e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][b];d=S(d>>>0);T(a,{name:d,Oc:c,Uc:c},{yd:!0})} +var Y=(a,b,d)=>{var c=(v(),B);b>>>=0;if(0=k){if(b>=d)break;c[b++>>>0]=k}else if(2047>=k){if(b+1>=d)break;c[b++>>>0]=192|k>>6;c[b++>>>0]=128|k&63}else if(65535>=k){if(b+2>=d)break;c[b++>>>0]=224|k>>12;c[b++>>>0]=128|k>>6&63;c[b++>>>0]=128|k&63}else{if(b+3>=d)break;c[b++>>>0]=240|k>>18;c[b++>>>0]=128|k>>12&63;c[b++>>>0]=128|k>>6&63;c[b++>>>0]=128|k&63;g++}}c[b>>>0]=0;a=b-e}else a=0;return a},bf=a=>{for(var b=0,d=0;d=c?b++:2047>=c?b+=2:55296<=c&&57343>=c?(b+=4,++d):b+=3}return b}; +function Fb(a,b){a>>>=0;b=S(b>>>0);T(a,{name:b,Oc(d){var c=(v(),D)[d>>>2>>>0];c=R(d+4,c,!0);I(d);return c},Vc(d,c){c instanceof ArrayBuffer&&(c=new Uint8Array(c));var e="string"==typeof c;if(!(e||ArrayBuffer.isView(c)&&1==c.BYTES_PER_ELEMENT))throw new Ve("Cannot pass non-string to std::string");var g=e?bf(c):c.length;var k=xd(4+g+1),l=k+4;(v(),D)[k>>>2>>>0]=g;e?Y(c,l,g+1):(v(),B).set(c,l>>>0);null!==d&&d.push(I,k);return k},Uc:Ze,Wc(d){I(d)}})} +var cf=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,df=(a,b,d)=>{a>>>=1;b=Qe((v(),Na),a,b/2,d);if(16>>0];d+=String.fromCharCode(c)}return d},ef=(a,b,d)=>{d??=2147483647;if(2>d)return 0;d-=2;var c=b;d=d<2*a.length?d/2:a.length;for(var e=0;e>>1>>>0]=g;b+=2}(v(),Ma)[b>>>1>>>0]=0;return b-c},ff=a=>2*a.length,gf=(a,b,d)=>{var c="";a>>>=2;for(var e=0;!(e>=b/4);e++){var g= +(v(),D)[a+e>>>0];if(!g&&!d)break;c+=String.fromCodePoint(g)}return c},hf=(a,b,d)=>{b>>>=0;d??=2147483647;if(4>d)return 0;var c=b;d=c+d-4;for(var e=0;e>>2>>>0]=g;b+=4;if(b+4>d)break}(v(),C)[b>>>2>>>0]=0;return b-c},jf=a=>{for(var b=0,d=0;d>>=0;b>>>=0;d>>>=0;d=S(d);if(2===b){var c=df;var e=ef;var g=ff}else c=gf,e=hf,g=jf;T(a,{name:d,Oc:k=>{var l=(v(),D)[k>>>2>>>0];l=c(k+4,l*b,!0);I(k);return l},Vc:(k,l)=>{if("string"!=typeof l)throw new Ve(`Cannot pass non-string to C++ string type ${d}`);var n=g(l),p=xd(4+n+b);(v(),D)[p>>>2>>>0]=n/b;e(l,p+4,n+b);null!==k&&k.push(I,p);return p},Uc:Ze,Wc(k){I(k)}})}function Hb(a,b){a>>>=0;b=S(b>>>0);T(a,{zd:!0,name:b,Oc:()=>{},Vc:()=>{}})} +function Ib(a){Fa(a>>>0,!ba,1,!aa,131072,!1);Ga()}var He=a=>{if(!t)try{if(a(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ha(a){a>>>=0;kf||(Atomics.waitAsync((v(),C),a>>>2,a).value.then(Ka),a+=128,Atomics.store((v(),C),a>>>2,1))}var Ka=()=>He(()=>{var a=wd();a&&(Ha(a),Cd())}); +function Jb(a,b){a>>>=0;a==b>>>0?setTimeout(Ka):m?postMessage({Zc:a,Sc:"checkMailbox"}):(a=N[a])&&a.postMessage({Sc:"checkMailbox"})}var lf=[];function Kb(a,b,d,c,e){b>>>=0;e>>>=0;lf.length=0;d=e>>>3;for(c=e+c>>>3;d>>0]?g=(v(),F)[d++>>>0]:g=(v(),E)[d++>>>0];lf.push(g)}return(b?mf[b]:nf[a])(...lf)}var Lb=()=>{O=0};function Mb(a){a>>>=0;m?postMessage({Sc:"cleanupThread",Nd:a}):Ge(N[a])}function Nb(a){h&&N[a>>>0].ref()}var of=a=>{try{a()}catch(b){H(b)}}; +function sd(a){var b=(...d)=>{pf.push(a);try{return a(...d)}finally{t||(pf.pop(),q&&1===Z&&0===pf.length&&(Z=0,O+=1,of(re),"undefined"!=typeof Fibers&&Fibers.Zd()))}};qf.set(a,b);return b}var Z=0,q=null,rf=0,pf=[],sf=new Map,tf=new Map,qf=new Map,uf=0,vf=null,wf=[];function ea(){return new Promise((a,b)=>{vf={resolve:a,reject:b}})} +function xf(){var a=xd(65548),b=a+12;(v(),D)[a>>>2>>>0]=b;(v(),D)[a+4>>>2>>>0]=b+65536;b=pf[0];if(!sf.has(b)){var d=uf++;sf.set(b,d);tf.set(d,b)}b=sf.get(b);(v(),C)[a+8>>>2>>>0]=b;return a}function yf(){var a=(v(),C)[q+8>>>2>>>0];a=tf.get(a);a=qf.get(a);--O;return a()} +function zf(a){if(!t){if(0===Z){var b=!1,d=!1;a((c=0)=>{if(!t&&(rf=c,b=!0,d)){Z=2;of(()=>se(q));"undefined"!=typeof MainLoop&&MainLoop.ud&&MainLoop.resume();c=!1;try{var e=yf()}catch(l){e=l,c=!0}var g=!1;if(!q){var k=vf;k&&(vf=null,(c?k.reject:k.resolve)(e),g=!0)}if(c&&!g)throw e;}});d=!0;b||(Z=1,q=xf(),"undefined"!=typeof MainLoop&&MainLoop.ud&&MainLoop.pause(),of(()=>qe(q)))}else 2===Z?(Z=0,of(te),I(q),q=null,wf.forEach(He)):H(`invalid state: ${Z}`);return rf}}var Af=a=>zf(b=>{a().then(b)}); +function Ob(a){a>>>=0;return Af(async()=>{var b=await V(a);return X(b)})}var Bf=[],Cf=a=>{var b=Bf.length;Bf.push(a);return b},Df=(a,b)=>{for(var d=Array(a),c=0;c>>2>>>0],k=Te[g];if(void 0===k)throw a=`parameter ${c}`,g=vd(g),b=S(g),I(g),new Ve(`${a} has unknown type ${b}`);d[e]=k}return d},Ef=(a,b,d)=>{var c=[];a=a(c,d);c.length&&((v(),D)[b>>>2>>>0]=X(c));return a},Ff={},Gf=a=>{var b=Ff[a];return void 0===b?S(a):b}; +function Pb(a,b,d){var [c,...e]=Df(a,b>>>0);b=c.Vc.bind(c);var g=e.map(n=>n.Uc.bind(n));a--;var k={toValue:V};a=g.map((n,p)=>{var u=`argFromPtr${p}`;k[u]=n;return`${u}(args${p?"+"+8*p:""})`});switch(d){case 0:var l="toValue(handle)";break;case 2:l="new (toValue(handle))";break;case 3:l="";break;case 1:k.getStringOrSymbol=Gf,l="toValue(handle)[getStringOrSymbol(methodName)]"}l+=`(${a})`;c.zd||(k.toReturnWire=b,k.emval_returnValue=Ef,l=`return emval_returnValue(toReturnWire, destructorsRef, ${l})`); +l=`return function (handle, methodName, destructorsRef, args) {\n ${l}\n }`;d=(new Function(Object.keys(k),l))(...Object.values(k));l=`methodCaller<(${e.map(n=>n.name)}) => ${c.name}>`;return Cf(Object.defineProperty(d,"name",{value:l}))}function Rb(a,b){b>>>=0;a=V(a>>>0);b=V(b);return a==b}function Sb(a){a>>>=0;if(!a)return X(globalThis);a=Gf(a);return X(globalThis[a])}function Tb(a){a=Gf(a>>>0);return X(f[a])}function Ub(a,b){b>>>=0;a=V(a>>>0);b=V(b);return X(a[b])} +function Vb(a){a>>>=0;9>>0](b>>>0,d>>>0,c>>>0,e>>>0)}function Xb(a,b,d,c,e){return Wb(a>>>0,b>>>0,d>>>0,c>>>0,e>>>0)}function Yb(){return X([])}function Zb(a){a=V(a>>>0);for(var b=Array(a.length),d=0;d>>0))}function ac(){return X({})}function bc(a){a>>>=0;for(var b=V(a);b.length;){var d=b.pop();b.pop()(d)}Qb(a)}function cc(a,b,d){b>>>=0;d>>>=0;a=V(a>>>0);b=V(b);d=V(d);a[b]=d} +function dc(a,b){a=-9007199254740992>a||9007199254740992>>=0;a=new Date(1E3*a);(v(),C)[b>>>2>>>0]=a.getUTCSeconds();(v(),C)[b+4>>>2>>>0]=a.getUTCMinutes();(v(),C)[b+8>>>2>>>0]=a.getUTCHours();(v(),C)[b+12>>>2>>>0]=a.getUTCDate();(v(),C)[b+16>>>2>>>0]=a.getUTCMonth();(v(),C)[b+20>>>2>>>0]=a.getUTCFullYear()-1900;(v(),C)[b+24>>>2>>>0]=a.getUTCDay();a=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0;(v(),C)[b+28>>>2>>>0]=a} +var Hf=a=>0===a%4&&(0!==a%100||0===a%400),If=[0,31,60,91,121,152,182,213,244,274,305,335],Jf=[0,31,59,90,120,151,181,212,243,273,304,334]; +function ec(a,b){a=-9007199254740992>a||9007199254740992>>=0;a=new Date(1E3*a);(v(),C)[b>>>2>>>0]=a.getSeconds();(v(),C)[b+4>>>2>>>0]=a.getMinutes();(v(),C)[b+8>>>2>>>0]=a.getHours();(v(),C)[b+12>>>2>>>0]=a.getDate();(v(),C)[b+16>>>2>>>0]=a.getMonth();(v(),C)[b+20>>>2>>>0]=a.getFullYear()-1900;(v(),C)[b+24>>>2>>>0]=a.getDay();var d=(Hf(a.getFullYear())?If:Jf)[a.getMonth()]+a.getDate()-1|0;(v(),C)[b+28>>>2>>>0]=d;(v(),C)[b+36>>>2>>>0]=-(60*a.getTimezoneOffset());d=(new Date(a.getFullYear(), +6,1)).getTimezoneOffset();var c=(new Date(a.getFullYear(),0,1)).getTimezoneOffset();a=(d!=c&&a.getTimezoneOffset()==Math.min(c,d))|0;(v(),C)[b+32>>>2>>>0]=a} +function fc(a){a>>>=0;var b=new Date((v(),C)[a+20>>>2>>>0]+1900,(v(),C)[a+16>>>2>>>0],(v(),C)[a+12>>>2>>>0],(v(),C)[a+8>>>2>>>0],(v(),C)[a+4>>>2>>>0],(v(),C)[a>>>2>>>0],0),d=(v(),C)[a+32>>>2>>>0],c=b.getTimezoneOffset(),e=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),g=(new Date(b.getFullYear(),0,1)).getTimezoneOffset(),k=Math.min(g,e);0>d?(v(),C)[a+32>>>2>>>0]=Number(e!=g&&k==c):0>>2>>>0]=b.getDay();d=(Hf(b.getFullYear())? +If:Jf)[b.getMonth()]+b.getDate()-1|0;(v(),C)[a+28>>>2>>>0]=d;(v(),C)[a>>>2>>>0]=b.getSeconds();(v(),C)[a+4>>>2>>>0]=b.getMinutes();(v(),C)[a+8>>>2>>>0]=b.getHours();(v(),C)[a+12>>>2>>>0]=b.getDate();(v(),C)[a+16>>>2>>>0]=b.getMonth();(v(),C)[a+20>>>2>>>0]=b.getYear();a=b.getTime();return BigInt(isNaN(a)?-1:a/1E3)}function gc(a,b,d,c,e,g,k){return m?P(16,1,a,b,d,c,e,g,k):-52}function hc(a,b,d,c,e,g){if(m)return P(17,1,a,b,d,c,e,g)}var Kf={},sc=()=>performance.timeOrigin+performance.now(); +function ic(a,b){if(m)return P(18,1,a,b);Kf[a]&&(clearTimeout(Kf[a].id),delete Kf[a]);if(!b)return 0;var d=setTimeout(()=>{delete Kf[a];He(()=>Bd(a,performance.timeOrigin+performance.now()))},b);Kf[a]={id:d,Yd:b};return 0} +function jc(a,b,d,c){a>>>=0;b>>>=0;d>>>=0;c>>>=0;var e=(new Date).getFullYear(),g=(new Date(e,0,1)).getTimezoneOffset();e=(new Date(e,6,1)).getTimezoneOffset();var k=Math.max(g,e);(v(),D)[a>>>2>>>0]=60*k;(v(),C)[b>>>2>>>0]=Number(g!=e);b=l=>{var n=Math.abs(l);return`UTC${0<=l?"-":"+"}${String(Math.floor(n/60)).padStart(2,"0")}${String(n%60).padStart(2,"0")}`};a=b(g);b=b(e);eDate.now(),Lf=1; +function kc(a,b,d){d>>>=0;if(!(0<=a&&3>=a))return 28;if(0===a)a=Date.now();else if(Lf)a=performance.timeOrigin+performance.now();else return 52;a=Math.round(1E6*a);(v(),F)[d>>>3>>>0]=BigInt(a);return 0}var Mf=[],Nf=(a,b)=>{Mf.length=0;for(var d;d=(v(),B)[a++>>>0];){var c=105!=d;c&=112!=d;b+=c&&b%8?4:0;Mf.push(112==d?(v(),D)[b>>>2>>>0]:106==d?(v(),F)[b>>>3>>>0]:105==d?(v(),C)[b>>>2>>>0]:(v(),E)[b>>>3>>>0]);b+=c?8:4}return Mf};function lc(a,b,d){a>>>=0;b=Nf(b>>>0,d>>>0);return mf[a](...b)} +function mc(a,b,d){a>>>=0;b=Nf(b>>>0,d>>>0);return mf[a](...b)}var nc=()=>{};function pc(a,b){return r(R(a>>>0,b>>>0))}var qc=()=>{O+=1;throw"unwind";};function rc(){return 4294901760}var tc=()=>h?require("os").cpus().length:navigator.hardwareConcurrency,Of={},Pf=a=>{var b;return(b=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(a))?+b[1]:(b=/:(\d+):\d+(?:\)|$)/.exec(a))?2147483648|+b[1]:0},Qf=a=>{for(var b of a)(a=Pf(b))&&(Of[a]=b)}; +function wc(){var a=Error().stack.toString().split("\n");"Error"==a[0]&&a.shift();Qf(a);Of.gd=Pf(a[3]);Of.Jd=a;return Of.gd}function uc(a){a=Of[a>>>0];if(!a)return 0;var b;if(b=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(a))a=b[1];else if(b=/^\s+at (.*) \(.*\)$/.exec(a))a=b[1];else if(b=/^(.+?)@/.exec(a))a=b[1];else return 0;I(uc.hd??0);b=bf(a)+1;var d=xd(b);d&&Y(a,d,b);uc.hd=d;return uc.hd} +function vc(a){a>>>=0;var b=(v(),B).length;if(a<=b||4294901760=d;d*=2){var c=b*(1+.2/d);c=Math.min(c,a+100663296);a:{c=(Math.min(4294901760,65536*Math.ceil(Math.max(a,c)/65536))-x.buffer.byteLength+65535)/65536|0;try{x.grow(c);wa();var e=1;break a}catch(g){}e=void 0}if(e)return!0}return!1} +function xc(a,b,d){a>>>=0;b>>>=0;if(Of.gd==a)var c=Of.Jd;else c=Error().stack.toString().split("\n"),"Error"==c[0]&&c.shift(),Qf(c);for(var e=3;c[e]&&Pf(c[e])!=a;)++e;for(a=0;a>>2>>>0]=Pf(c[a+e]);return a} +var Rf={},Tf=()=>{if(!Sf){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:ha||"./this.program"},b;for(b in Rf)void 0===Rf[b]?delete a[b]:a[b]=Rf[b];var d=[];for(b in a)d.push(`${b}=${a[b]}`);Sf=d}return Sf},Sf;function yc(a,b){if(m)return P(19,1,a,b);a>>>=0;b>>>=0;var d=0,c=0,e;for(e of Tf()){var g=b+d;(v(),D)[a+c>>>2>>>0]=g;d+=Y(e,g,Infinity)+1;c+=4}return 0} +function zc(a,b){if(m)return P(20,1,a,b);a>>>=0;b>>>=0;var d=Tf();(v(),D)[a>>>2>>>0]=d.length;a=0;for(var c of d)a+=bf(c)+1;(v(),D)[b>>>2>>>0]=a;return 0}function Bc(a){return m?P(21,1,a):52}function Cc(a,b,d,c){return m?P(22,1,a,b,d,c):52}function Dc(a,b,d,c){return m?P(23,1,a,b,d,c):70}var Uf=[null,[],[]]; +function Ec(a,b,d,c){if(m)return P(24,1,a,b,d,c);b>>>=0;d>>>=0;c>>>=0;for(var e=0,g=0;g>>2>>>0],l=(v(),D)[b+4>>>2>>>0];b+=8;for(var n=0;n>>0],w=Uf[p];0===u||10===u?((1===p?sa:r)(Re(w)),w.length=0):w.push(u)}e+=l}(v(),D)[c>>>2>>>0]=e;return 0}function qd(a){return a>>>0}m||Ee();m||(x=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),wa());f.wasmBinary&&(ta=f.wasmBinary);f.stackSave=()=>L();f.stackRestore=a=>K(a);f.stackAlloc=a=>Fd(a); +f.setValue=function(a,b,d="i8"){d.endsWith("*")&&(d="*");switch(d){case "i1":(v(),A)[a>>>0]=b;break;case "i8":(v(),A)[a>>>0]=b;break;case "i16":(v(),Ma)[a>>>1>>>0]=b;break;case "i32":(v(),C)[a>>>2>>>0]=b;break;case "i64":(v(),F)[a>>>3>>>0]=BigInt(b);break;case "float":(v(),Oa)[a>>>2>>>0]=b;break;case "double":(v(),E)[a>>>3>>>0]=b;break;case "*":(v(),D)[a>>>2>>>0]=b;break;default:H(`invalid type for setValue: ${d}`)}}; +f.getValue=function(a,b="i8"){b.endsWith("*")&&(b="*");switch(b){case "i1":return(v(),A)[a>>>0];case "i8":return(v(),A)[a>>>0];case "i16":return(v(),Ma)[a>>>1>>>0];case "i32":return(v(),C)[a>>>2>>>0];case "i64":return(v(),F)[a>>>3>>>0];case "float":return(v(),Oa)[a>>>2>>>0];case "double":return(v(),E)[a>>>3>>>0];case "*":return(v(),D)[a>>>2>>>0];default:H(`invalid type for getValue: ${b}`)}};f.UTF8ToString=R;f.stringToUTF8=Y;f.lengthBytesUTF8=bf; +var nf=[rd,De,Oe,jb,mb,nb,ob,pb,qb,rb,sb,tb,ub,vb,wb,xb,gc,hc,ic,yc,zc,Bc,Cc,Dc,Ec],mf={1003524:(a,b,d,c,e)=>{if("undefined"==typeof f||!f.Xc)return 1;a=R(Number(a>>>0));a.startsWith("./")&&(a=a.substring(2));a=f.Xc.get(a);if(!a)return 2;b=Number(b>>>0);d=Number(d>>>0);c=Number(c>>>0);if(b+d>a.byteLength)return 3;try{const g=a.subarray(b,b+d);switch(e){case 0:(v(),B).set(g,c>>>0);break;case 1:f.Qd?f.Qd(c,g):f.Id(c,g);break;default:return 4}return 0}catch{return 4}},1004348:(a,b,d)=>{f.td(a,(v(),B).subarray(b>>> +0,b+d>>>0))},1004412:()=>f.Sd(),1004454:a=>{f.sd(a)},1004491:()=>{f.Bd()},1004522:()=>{f.Cd()},1004551:()=>{f.Gd()},1004576:a=>f.Ad(a),1004609:a=>f.Ed(a),1004641:(a,b,d)=>{f.ed(Number(a),Number(b),Number(d),!0)},1004704:(a,b,d)=>{f.ed(Number(a),Number(b),Number(d))},1004761:()=>"undefined"!==typeof wasmOffsetConverter,1004818:a=>{f.$b("Abs",a,void 0)},1004869:a=>{f.$b("Neg",a,void 0)},1004920:a=>{f.$b("Floor",a,void 0)},1004973:a=>{f.$b("Ceil",a,void 0)},1005025:a=>{f.$b("Reciprocal",a,void 0)},1005083:a=> +{f.$b("Sqrt",a,void 0)},1005135:a=>{f.$b("Exp",a,void 0)},1005186:a=>{f.$b("Erf",a,void 0)},1005237:a=>{f.$b("Sigmoid",a,void 0)},1005292:(a,b,d)=>{f.$b("HardSigmoid",a,{alpha:b,beta:d})},1005371:a=>{f.$b("Log",a,void 0)},1005422:a=>{f.$b("Sin",a,void 0)},1005473:a=>{f.$b("Cos",a,void 0)},1005524:a=>{f.$b("Tan",a,void 0)},1005575:a=>{f.$b("Asin",a,void 0)},1005627:a=>{f.$b("Acos",a,void 0)},1005679:a=>{f.$b("Atan",a,void 0)},1005731:a=>{f.$b("Sinh",a,void 0)},1005783:a=>{f.$b("Cosh",a,void 0)},1005835:a=> +{f.$b("Asinh",a,void 0)},1005888:a=>{f.$b("Acosh",a,void 0)},1005941:a=>{f.$b("Atanh",a,void 0)},1005994:a=>{f.$b("Tanh",a,void 0)},1006046:a=>{f.$b("Not",a,void 0)},1006097:(a,b,d)=>{f.$b("Clip",a,{min:b,max:d})},1006166:a=>{f.$b("Clip",a,void 0)},1006218:(a,b)=>{f.$b("Elu",a,{alpha:b})},1006276:a=>{f.$b("Gelu",a,void 0)},1006328:a=>{f.$b("Relu",a,void 0)},1006380:(a,b)=>{f.$b("LeakyRelu",a,{alpha:b})},1006444:(a,b)=>{f.$b("ThresholdedRelu",a,{alpha:b})},1006514:(a,b)=>{f.$b("Cast",a,{to:b})},1006572:a=> +{f.$b("Add",a,void 0)},1006623:a=>{f.$b("Sub",a,void 0)},1006674:a=>{f.$b("Mul",a,void 0)},1006725:a=>{f.$b("Div",a,void 0)},1006776:a=>{f.$b("Pow",a,void 0)},1006827:a=>{f.$b("Equal",a,void 0)},1006880:a=>{f.$b("Greater",a,void 0)},1006935:a=>{f.$b("GreaterOrEqual",a,void 0)},1006997:a=>{f.$b("Less",a,void 0)},1007049:a=>{f.$b("LessOrEqual",a,void 0)},1007108:(a,b,d,c,e)=>{f.$b("ReduceMean",a,{keepDims:!!b,noopWithEmptyAxes:!!d,axes:c?Array.from((v(),C).subarray(Number(c)>>>0,Number(e)>>>0)):[]})}, +1007283:(a,b,d,c,e)=>{f.$b("ReduceMax",a,{keepDims:!!b,noopWithEmptyAxes:!!d,axes:c?Array.from((v(),C).subarray(Number(c)>>>0,Number(e)>>>0)):[]})},1007457:(a,b,d,c,e)=>{f.$b("ReduceMin",a,{keepDims:!!b,noopWithEmptyAxes:!!d,axes:c?Array.from((v(),C).subarray(Number(c)>>>0,Number(e)>>>0)):[]})},1007631:(a,b,d,c,e)=>{f.$b("ReduceProd",a,{keepDims:!!b,noopWithEmptyAxes:!!d,axes:c?Array.from((v(),C).subarray(Number(c)>>>0,Number(e)>>>0)):[]})},1007806:(a,b,d,c,e)=>{f.$b("ReduceSum",a,{keepDims:!!b,noopWithEmptyAxes:!!d, +axes:c?Array.from((v(),C).subarray(Number(c)>>>0,Number(e)>>>0)):[]})},1007980:(a,b,d,c,e)=>{f.$b("ReduceL1",a,{keepDims:!!b,noopWithEmptyAxes:!!d,axes:c?Array.from((v(),C).subarray(Number(c)>>>0,Number(e)>>>0)):[]})},1008153:(a,b,d,c,e)=>{f.$b("ReduceL2",a,{keepDims:!!b,noopWithEmptyAxes:!!d,axes:c?Array.from((v(),C).subarray(Number(c)>>>0,Number(e)>>>0)):[]})},1008326:(a,b,d,c,e)=>{f.$b("ReduceLogSum",a,{keepDims:!!b,noopWithEmptyAxes:!!d,axes:c?Array.from((v(),C).subarray(Number(c)>>>0,Number(e)>>> +0)):[]})},1008503:(a,b,d,c,e)=>{f.$b("ReduceSumSquare",a,{keepDims:!!b,noopWithEmptyAxes:!!d,axes:c?Array.from((v(),C).subarray(Number(c)>>>0,Number(e)>>>0)):[]})},1008683:(a,b,d,c,e)=>{f.$b("ReduceLogSumExp",a,{keepDims:!!b,noopWithEmptyAxes:!!d,axes:c?Array.from((v(),C).subarray(Number(c)>>>0,Number(e)>>>0)):[]})},1008863:a=>{f.$b("Where",a,void 0)},1008916:(a,b,d)=>{f.$b("Transpose",a,{perm:b?Array.from((v(),C).subarray(Number(b)>>>0,Number(d)>>>0)):[]})},1009040:(a,b,d,c)=>{f.$b("DepthToSpace", +a,{blocksize:b,mode:R(d),format:c?"NHWC":"NCHW"})},1009173:(a,b,d,c)=>{f.$b("DepthToSpace",a,{blocksize:b,mode:R(d),format:c?"NHWC":"NCHW"})},1009306:(a,b,d,c,e,g,k,l,n,p,u,w,y,z,W)=>{f.$b("ConvTranspose",a,{format:n?"NHWC":"NCHW",autoPad:b,dilations:[d],group:c,kernelShape:[e],pads:[g,k],strides:[l],wIsConst:()=>!!(v(),A)[p>>>0],outputPadding:u?Array.from((v(),C).subarray(Number(u)>>>0,Number(w)>>>0)):[],outputShape:y?Array.from((v(),C).subarray(Number(y)>>>0,Number(z)>>>0)):[],activation:R(W)})}, +1009739:(a,b,d,c,e,g,k,l,n,p,u,w,y,z)=>{f.$b("ConvTranspose",a,{format:l?"NHWC":"NCHW",autoPad:b,dilations:Array.from((v(),C).subarray(Number(d)>>>0,(Number(d)>>>0)+2>>>0)),group:c,kernelShape:Array.from((v(),C).subarray(Number(e)>>>0,(Number(e)>>>0)+2>>>0)),pads:Array.from((v(),C).subarray(Number(g)>>>0,(Number(g)>>>0)+4>>>0)),strides:Array.from((v(),C).subarray(Number(k)>>>0,(Number(k)>>>0)+2>>>0)),wIsConst:()=>!!(v(),A)[n>>>0],outputPadding:p?Array.from((v(),C).subarray(Number(p)>>>0,Number(u)>>> +0)):[],outputShape:w?Array.from((v(),C).subarray(Number(w)>>>0,Number(y)>>>0)):[],activation:R(z)})},1010400:(a,b,d,c,e,g,k,l,n,p,u,w,y,z,W)=>{f.$b("ConvTranspose",a,{format:n?"NHWC":"NCHW",autoPad:b,dilations:[d],group:c,kernelShape:[e],pads:[g,k],strides:[l],wIsConst:()=>!!(v(),A)[p>>>0],outputPadding:u?Array.from((v(),C).subarray(Number(u)>>>0,Number(w)>>>0)):[],outputShape:y?Array.from((v(),C).subarray(Number(y)>>>0,Number(z)>>>0)):[],activation:R(W)})},1010833:(a,b,d,c,e,g,k,l,n,p,u,w,y,z)=> +{f.$b("ConvTranspose",a,{format:l?"NHWC":"NCHW",autoPad:b,dilations:Array.from((v(),C).subarray(Number(d)>>>0,(Number(d)>>>0)+2>>>0)),group:c,kernelShape:Array.from((v(),C).subarray(Number(e)>>>0,(Number(e)>>>0)+2>>>0)),pads:Array.from((v(),C).subarray(Number(g)>>>0,(Number(g)>>>0)+4>>>0)),strides:Array.from((v(),C).subarray(Number(k)>>>0,(Number(k)>>>0)+2>>>0)),wIsConst:()=>!!(v(),A)[n>>>0],outputPadding:p?Array.from((v(),C).subarray(Number(p)>>>0,Number(u)>>>0)):[],outputShape:w?Array.from((v(), +C).subarray(Number(w)>>>0,Number(y)>>>0)):[],activation:R(z)})},1011494:(a,b)=>{f.$b("GlobalAveragePool",a,{format:b?"NHWC":"NCHW"})},1011585:(a,b,d,c,e,g,k,l,n,p,u,w,y,z)=>{f.$b("AveragePool",a,{format:z?"NHWC":"NCHW",auto_pad:b,ceil_mode:d,count_include_pad:c,storage_order:e,dilations:g?Array.from((v(),C).subarray(Number(g)>>>0,Number(k)>>>0)):[],kernel_shape:l?Array.from((v(),C).subarray(Number(l)>>>0,Number(n)>>>0)):[],pads:p?Array.from((v(),C).subarray(Number(p)>>>0,Number(u)>>>0)):[],strides:w? +Array.from((v(),C).subarray(Number(w)>>>0,Number(y)>>>0)):[]})},1012064:(a,b)=>{f.$b("GlobalAveragePool",a,{format:b?"NHWC":"NCHW"})},1012155:(a,b,d,c,e,g,k,l,n,p,u,w,y,z)=>{f.$b("AveragePool",a,{format:z?"NHWC":"NCHW",auto_pad:b,ceil_mode:d,count_include_pad:c,storage_order:e,dilations:g?Array.from((v(),C).subarray(Number(g)>>>0,Number(k)>>>0)):[],kernel_shape:l?Array.from((v(),C).subarray(Number(l)>>>0,Number(n)>>>0)):[],pads:p?Array.from((v(),C).subarray(Number(p)>>>0,Number(u)>>>0)):[],strides:w? +Array.from((v(),C).subarray(Number(w)>>>0,Number(y)>>>0)):[]})},1012634:(a,b)=>{f.$b("GlobalMaxPool",a,{format:b?"NHWC":"NCHW"})},1012721:(a,b,d,c,e,g,k,l,n,p,u,w,y,z)=>{f.$b("MaxPool",a,{format:z?"NHWC":"NCHW",auto_pad:b,ceil_mode:d,count_include_pad:c,storage_order:e,dilations:g?Array.from((v(),C).subarray(Number(g)>>>0,Number(k)>>>0)):[],kernel_shape:l?Array.from((v(),C).subarray(Number(l)>>>0,Number(n)>>>0)):[],pads:p?Array.from((v(),C).subarray(Number(p)>>>0,Number(u)>>>0)):[],strides:w?Array.from((v(), +C).subarray(Number(w)>>>0,Number(y)>>>0)):[]})},1013196:(a,b)=>{f.$b("GlobalMaxPool",a,{format:b?"NHWC":"NCHW"})},1013283:(a,b,d,c,e,g,k,l,n,p,u,w,y,z)=>{f.$b("MaxPool",a,{format:z?"NHWC":"NCHW",auto_pad:b,ceil_mode:d,count_include_pad:c,storage_order:e,dilations:g?Array.from((v(),C).subarray(Number(g)>>>0,Number(k)>>>0)):[],kernel_shape:l?Array.from((v(),C).subarray(Number(l)>>>0,Number(n)>>>0)):[],pads:p?Array.from((v(),C).subarray(Number(p)>>>0,Number(u)>>>0)):[],strides:w?Array.from((v(),C).subarray(Number(w)>>> +0,Number(y)>>>0)):[]})},1013758:(a,b,d,c,e)=>{f.$b("Gemm",a,{alpha:b,beta:d,transA:c,transB:e})},1013862:a=>{f.$b("MatMul",a,void 0)},1013916:(a,b,d,c)=>{f.$b("ArgMax",a,{keepDims:!!b,selectLastIndex:!!d,axis:c})},1014024:(a,b,d,c)=>{f.$b("ArgMin",a,{keepDims:!!b,selectLastIndex:!!d,axis:c})},1014132:(a,b)=>{f.$b("Softmax",a,{axis:b})},1014195:(a,b)=>{f.$b("Concat",a,{axis:b})},1014255:(a,b,d,c,e)=>{f.$b("Split",a,{axis:b,numOutputs:d,splitSizes:c?Array.from((v(),C).subarray(Number(c)>>>0,Number(e)>>> +0)):[]})},1014411:a=>{f.$b("Expand",a,void 0)},1014465:(a,b)=>{f.$b("Gather",a,{axis:Number(b)})},1014536:(a,b)=>{f.$b("GatherElements",a,{axis:Number(b)})},1014615:(a,b)=>{f.$b("GatherND",a,{batch_dims:Number(b)})},1014694:(a,b,d,c,e,g,k,l,n,p,u)=>{f.$b("Resize",a,{antialias:b,axes:d?Array.from((v(),C).subarray(Number(d)>>>0,Number(c)>>>0)):[],coordinateTransformMode:R(e),cubicCoeffA:g,excludeOutside:k,extrapolationValue:l,keepAspectRatioPolicy:R(n),mode:R(p),nearestMode:R(u)})},1015056:(a,b,d,c, +e,g,k)=>{f.$b("Slice",a,{starts:b?Array.from((v(),C).subarray(Number(b)>>>0,Number(d)>>>0)):[],ends:c?Array.from((v(),C).subarray(Number(c)>>>0,Number(e)>>>0)):[],axes:g?Array.from((v(),C).subarray(Number(g)>>>0,Number(k)>>>0)):[]})},1015320:a=>{f.$b("Tile",a,void 0)},1015372:(a,b,d)=>{f.$b("InstanceNormalization",a,{epsilon:b,format:d?"NHWC":"NCHW"})},1015486:(a,b,d)=>{f.$b("InstanceNormalization",a,{epsilon:b,format:d?"NHWC":"NCHW"})},1015600:a=>{f.$b("Range",a,void 0)},1015653:(a,b)=>{f.$b("Einsum", +a,{equation:R(b)})},1015734:(a,b,d,c,e)=>{f.$b("Pad",a,{mode:b,value:d,pads:c?Array.from((v(),C).subarray(Number(c)>>>0,Number(e)>>>0)):[]})},1015877:(a,b,d,c,e,g)=>{f.$b("BatchNormalization",a,{epsilon:b,momentum:d,spatial:!!e,trainingMode:!!c,format:g?"NHWC":"NCHW"})},1016046:(a,b,d,c,e,g)=>{f.$b("BatchNormalization",a,{epsilon:b,momentum:d,spatial:!!e,trainingMode:!!c,format:g?"NHWC":"NCHW"})},1016215:(a,b,d)=>{f.$b("CumSum",a,{exclusive:Number(b),reverse:Number(d)})},1016312:(a,b,d)=>{f.$b("DequantizeLinear", +a,{axis:b,blockSize:d})},1016402:(a,b,d,c,e)=>{f.$b("GridSample",a,{align_corners:b,mode:R(d),padding_mode:R(c),format:e?"NHWC":"NCHW"})},1016572:(a,b,d,c,e)=>{f.$b("GridSample",a,{align_corners:b,mode:R(d),padding_mode:R(c),format:e?"NHWC":"NCHW"})},1016742:(a,b)=>{f.$b("ScatterND",a,{reduction:R(b)})},1016827:(a,b,d,c,e,g,k,l,n)=>{f.$b("Attention",a,{numHeads:b,isUnidirectional:d,maskFilterValue:c,scale:e,doRotary:g,qkvHiddenSizes:k?Array.from((v(),C).subarray(Number(l)>>>0,Number(l)+k>>>0)):[], +pastPresentShareBuffer:!!n})},1017099:a=>{f.$b("BiasAdd",a,void 0)},1017154:a=>{f.$b("BiasSplitGelu",a,void 0)},1017215:a=>{f.$b("FastGelu",a,void 0)},1017271:(a,b,d,c,e,g,k,l,n,p,u,w,y,z,W,kb)=>{f.$b("Conv",a,{format:w?"NHWC":"NCHW",auto_pad:b,dilations:d?Array.from((v(),C).subarray(Number(d)>>>0,Number(c)>>>0)):[],group:e,kernel_shape:g?Array.from((v(),C).subarray(Number(g)>>>0,Number(k)>>>0)):[],pads:l?Array.from((v(),C).subarray(Number(l)>>>0,Number(n)>>>0)):[],strides:p?Array.from((v(),C).subarray(Number(p)>>> +0,Number(u)>>>0)):[],w_is_const:()=>!!(v(),A)[Number(y)>>>0],activation:R(z),activation_params:W?Array.from((v(),Oa).subarray(Number(W)>>>0,Number(kb)>>>0)):[]})},1017855:a=>{f.$b("Gelu",a,void 0)},1017907:(a,b,d,c,e,g,k,l,n)=>{f.$b("GroupQueryAttention",a,{numHeads:b,kvNumHeads:d,scale:c,softcap:e,doRotary:g,rotaryInterleaved:k,smoothSoftmax:l,localWindowSize:n})},1018124:(a,b,d,c)=>{f.$b("LayerNormalization",a,{axis:b,epsilon:d,simplified:!!c})},1018235:(a,b,d,c)=>{f.$b("LayerNormalization",a,{axis:b, +epsilon:d,simplified:!!c})},1018346:(a,b,d,c,e,g)=>{f.$b("MatMulNBits",a,{k:b,n:d,accuracyLevel:c,bits:e,blockSize:g})},1018473:(a,b,d,c,e,g)=>{f.$b("MultiHeadAttention",a,{numHeads:b,isUnidirectional:d,maskFilterValue:c,scale:e,doRotary:g})},1018632:(a,b)=>{f.$b("QuickGelu",a,{alpha:b})},1018696:(a,b,d,c,e)=>{f.$b("RotaryEmbedding",a,{interleaved:!!b,numHeads:d,rotaryEmbeddingDim:c,scale:e})},1018835:(a,b,d)=>{f.$b("SkipLayerNormalization",a,{epsilon:b,simplified:!!d})},1018937:(a,b,d)=>{f.$b("SkipLayerNormalization", +a,{epsilon:b,simplified:!!d})},1019039:(a,b,d,c)=>{f.$b("GatherBlockQuantized",a,{gatherAxis:b,quantizeAxis:d,blockSize:c})},1019160:a=>{f.Fd(a)},1019194:(a,b)=>f.Hd(Number(a),Number(b),f.Yc.Kd,f.Yc.errors)};function Za(a,b,d){return Af(async()=>{await f.Dd(Number(a),Number(b),Number(d))})}function Ya(){return"undefined"!==typeof wasmOffsetConverter} +var vd,Ia,wd,I,xd,Fa,La,yd,zd,Ad,Bd,Cd,J,Dd,Ed,K,Fd,L,Gd,Hd,Id,Jd,dynCall_vii,Kd,dynCall_v,Ld,Md,dynCall_iii,Nd,Od,Pd,Qd,dynCall_vi,Rd,Sd,Td,Ud,Vd,Wd,Xd,Yd,Zd,$d,ae,be,ce,de,ee,fe,ge,he,ie,je,ke,le,me,ne,oe,pe,qe,re,se,te,Xa;function Mc(a,b,d,c){var e=L();try{return Qd(a,b,d,c)}catch(g){K(e);if(g!==g+0)throw g;J(1,0)}}function Lc(a,b,d){var c=L();try{return dynCall_iii(a,b,d)}catch(e){K(c);if(e!==e+0)throw e;J(1,0)}} +function ad(a){var b=L();try{dynCall_v(a)}catch(d){K(b);if(d!==d+0)throw d;J(1,0)}}function Kc(a,b){var d=L();try{return Kd(a,b)}catch(c){K(d);if(c!==c+0)throw c;J(1,0)}}function cd(a,b,d){var c=L();try{dynCall_vii(a,b,d)}catch(e){K(c);if(e!==e+0)throw e;J(1,0)}}function bd(a,b){var d=L();try{dynCall_vi(a,b)}catch(c){K(d);if(c!==c+0)throw c;J(1,0)}}function Qc(a,b,d,c,e,g,k){var l=L();try{return Od(a,b,d,c,e,g,k)}catch(n){K(l);if(n!==n+0)throw n;J(1,0)}} +function gd(a,b,d,c,e,g){var k=L();try{Ld(a,b,d,c,e,g)}catch(l){K(k);if(l!==l+0)throw l;J(1,0)}}function ed(a,b,d,c){var e=L();try{Pd(a,b,d,c)}catch(g){K(e);if(g!==g+0)throw g;J(1,0)}}function fd(a,b,d,c,e){var g=L();try{Md(a,b,d,c,e)}catch(k){K(g);if(k!==k+0)throw k;J(1,0)}}function hd(a,b,d,c,e,g,k){var l=L();try{Sd(a,b,d,c,e,g,k)}catch(n){K(l);if(n!==n+0)throw n;J(1,0)}}function pd(a,b,d,c,e,g,k){var l=L();try{Td(a,b,d,c,e,g,k)}catch(n){K(l);if(n!==n+0)throw n;J(1,0)}} +function od(a,b,d,c,e,g,k,l){var n=L();try{Xd(a,b,d,c,e,g,k,l)}catch(p){K(n);if(p!==p+0)throw p;J(1,0)}}function Nc(a,b,d,c,e){var g=L();try{return Rd(a,b,d,c,e)}catch(k){K(g);if(k!==k+0)throw k;J(1,0)}}function Wc(a,b,d){var c=L();try{return Yd(a,b,d)}catch(e){K(c);if(e!==e+0)throw e;J(1,0)}}function jd(a,b,d,c,e,g,k,l){var n=L();try{Zd(a,b,d,c,e,g,k,l)}catch(p){K(n);if(p!==p+0)throw p;J(1,0)}} +function md(a,b,d,c,e,g,k,l,n,p,u,w){var y=L();try{Ud(a,b,d,c,e,g,k,l,n,p,u,w)}catch(z){K(y);if(z!==z+0)throw z;J(1,0)}}function Pc(a,b,d,c,e,g){var k=L();try{return Vd(a,b,d,c,e,g)}catch(l){K(k);if(l!==l+0)throw l;J(1,0)}}function Zc(a,b,d){var c=L();try{return $d(a,b,d)}catch(e){K(c);if(e!==e+0)throw e;J(1,0);return 0n}}function kd(a,b,d,c,e,g,k,l,n){var p=L();try{Nd(a,b,d,c,e,g,k,l,n)}catch(u){K(p);if(u!==u+0)throw u;J(1,0)}} +function Jc(a){var b=L();try{return ae(a)}catch(d){K(b);if(d!==d+0)throw d;J(1,0)}}function Yc(a,b){var d=L();try{return pe(a,b)}catch(c){K(d);if(c!==c+0)throw c;J(1,0);return 0n}}function Xc(a){var b=L();try{return be(a)}catch(d){K(b);if(d!==d+0)throw d;J(1,0);return 0n}}function Vc(a,b,d,c){var e=L();try{return he(a,b,d,c)}catch(g){K(e);if(g!==g+0)throw g;J(1,0)}}function Uc(a,b,d,c,e){var g=L();try{return ie(a,b,d,c,e)}catch(k){K(g);if(k!==k+0)throw k;J(1,0)}} +function Tc(a,b,d,c,e,g){var k=L();try{return je(a,b,d,c,e,g)}catch(l){K(k);if(l!==l+0)throw l;J(1,0)}}function Oc(a,b,d,c,e,g){var k=L();try{return ke(a,b,d,c,e,g)}catch(l){K(k);if(l!==l+0)throw l;J(1,0)}}function Rc(a,b,d,c,e,g,k,l){var n=L();try{return Wd(a,b,d,c,e,g,k,l)}catch(p){K(n);if(p!==p+0)throw p;J(1,0)}}function $c(a,b,d,c,e){var g=L();try{return le(a,b,d,c,e)}catch(k){K(g);if(k!==k+0)throw k;J(1,0);return 0n}} +function Ic(a,b,d,c){var e=L();try{return me(a,b,d,c)}catch(g){K(e);if(g!==g+0)throw g;J(1,0)}}function Gc(a,b,d,c){var e=L();try{return ne(a,b,d,c)}catch(g){K(e);if(g!==g+0)throw g;J(1,0)}}function Sc(a,b,d,c,e,g,k,l,n,p,u,w){var y=L();try{return oe(a,b,d,c,e,g,k,l,n,p,u,w)}catch(z){K(y);if(z!==z+0)throw z;J(1,0)}}function ld(a,b,d,c,e,g,k,l,n,p,u){var w=L();try{fe(a,b,d,c,e,g,k,l,n,p,u)}catch(y){K(w);if(y!==y+0)throw y;J(1,0)}} +function nd(a,b,d,c,e,g,k,l,n,p,u,w,y,z,W,kb){var Vf=L();try{ge(a,b,d,c,e,g,k,l,n,p,u,w,y,z,W,kb)}catch(lb){K(Vf);if(lb!==lb+0)throw lb;J(1,0)}}function Hc(a,b,d){var c=L();try{return ce(a,b,d)}catch(e){K(c);if(e!==e+0)throw e;J(1,0)}}function Fc(a,b,d){var c=L();try{return de(a,b,d)}catch(e){K(c);if(e!==e+0)throw e;J(1,0)}}function dd(a,b,d,c){var e=L();try{ee(a,b,d,c)}catch(g){K(e);if(g!==g+0)throw g;J(1,0)}} +function td(){var a=G;a=Object.assign({},a);var b=c=>e=>c(e)>>>0,d=c=>()=>c()>>>0;a.tb=b(a.tb);a.Xb=d(a.Xb);a.Zb=b(a.Zb);a.lc=b(a.lc);a.mc=d(a.mc);a.qc=b(a.qc);return a}function Da(){if(0{xa=a;ya=b}); +;return moduleRtn}export default ortWasmThreaded;var isPthread=globalThis.self?.name?.startsWith("em-pthread");var isNode=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(isNode)isPthread=(await import("worker_threads")).workerData==="em-pthread";isPthread&&ortWasmThreaded(); diff --git a/ort/ort-wasm-simd-threaded.jsep.wasm b/ort/ort-wasm-simd-threaded.jsep.wasm new file mode 100644 index 0000000000000000000000000000000000000000..922fb1f0c8564d2fb148ca6beaa7bbc9fa212019 --- /dev/null +++ b/ort/ort-wasm-simd-threaded.jsep.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78feeeb3d08f6bcee94d938ed322f69073bb8076b5f9d34697a574ffba8deb48 +size 26827543 diff --git a/source/demo/web/compare.html b/source/demo/web/compare.html new file mode 100644 index 0000000000000000000000000000000000000000..1b3b583fee2f358307c75c7a1348a78f31376267 --- /dev/null +++ b/source/demo/web/compare.html @@ -0,0 +1,27 @@ + + + + + + Hendrix Listening Lab — compare transcription systems + + + + + + + +
+ + + diff --git a/source/demo/web/index.html b/source/demo/web/index.html new file mode 100644 index 0000000000000000000000000000000000000000..8469c12c9e68a3db48d02abd8018bd4aa3895ab7 --- /dev/null +++ b/source/demo/web/index.html @@ -0,0 +1,29 @@ + + + + + + muscriptor + + + + + + + + +
+ + + diff --git a/source/demo/web/local.html b/source/demo/web/local.html new file mode 100644 index 0000000000000000000000000000000000000000..a1d190cae625935b89da3795b7a0c92e6e294705 --- /dev/null +++ b/source/demo/web/local.html @@ -0,0 +1,14 @@ + + + + + + + + Hendrix — on-device transcription + + +
+ + + diff --git a/source/demo/web/package.json b/source/demo/web/package.json new file mode 100644 index 0000000000000000000000000000000000000000..61d0d19c847bc2b863d509962b4446b6078f1ae5 --- /dev/null +++ b/source/demo/web/package.json @@ -0,0 +1,34 @@ +{ + "name": "muscriptor-web", + "version": "0.1.0", + "private": true, + "type": "module", + "packageManager": "pnpm@10.20.0", + "scripts": { + "dev": "vite", + "dev:proxy": "BACKEND_URL=https://muscriptor.kyutai.org vite", + "build": "tsc --noEmit && vite build", + "preview": "vite preview", + "test:local:e2e": "node --test ../../tests/browser_local_e2e.mjs", + "test:local:wasm": "node --test ../../tests/browser_local_wasm_e2e.mjs" + }, + "devDependencies": { + "@tailwindcss/vite": "^4.3.2", + "@types/node": "^25.9.1", + "@types/react": "^19.2.17", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^6.0.3", + "playwright": "1.61.1", + "tailwindcss": "^4.3.2", + "typescript": "^6.0.3", + "vite": "^8.0.14" + }, + "dependencies": { + "clsx": "^2.1.1", + "onnxruntime-web": "1.27.0", + "react": "^19.2.7", + "react-dom": "^19.2.7", + "spessasynth_lib": "^4.3.8", + "tone": "^15.1.22" + } +} diff --git a/source/demo/web/pnpm-lock.yaml b/source/demo/web/pnpm-lock.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e844551ebcf1eafd1eab83882f45191eb6b86778 --- /dev/null +++ b/source/demo/web/pnpm-lock.yaml @@ -0,0 +1,1025 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + clsx: + specifier: ^2.1.1 + version: 2.1.1 + onnxruntime-web: + specifier: 1.27.0 + version: 1.27.0 + react: + specifier: ^19.2.7 + version: 19.2.7 + react-dom: + specifier: ^19.2.7 + version: 19.2.7(react@19.2.7) + spessasynth_lib: + specifier: ^4.3.8 + version: 4.3.8 + tone: + specifier: ^15.1.22 + version: 15.1.22 + devDependencies: + '@tailwindcss/vite': + specifier: ^4.3.2 + version: 4.3.2(vite@8.0.16(@types/node@25.9.2)(jiti@2.7.0)) + '@types/node': + specifier: ^25.9.1 + version: 25.9.2 + '@types/react': + specifier: ^19.2.17 + version: 19.2.17 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.17) + '@vitejs/plugin-react': + specifier: ^6.0.3 + version: 6.0.3(vite@8.0.16(@types/node@25.9.2)(jiti@2.7.0)) + playwright: + specifier: 1.61.1 + version: 1.61.1 + tailwindcss: + specifier: ^4.3.2 + version: 4.3.2 + typescript: + specifier: ^6.0.3 + version: 6.0.3 + vite: + specifier: ^8.0.14 + version: 8.0.16(@types/node@25.9.2)(jiti@2.7.0) + +packages: + + '@babel/runtime@7.29.7': + resolution: {integrity: sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==} + engines: {node: '>=6.9.0'} + + '@emnapi/core@1.10.0': + resolution: {integrity: sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==} + + '@emnapi/runtime@1.10.0': + resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==} + + '@emnapi/wasi-threads@1.2.1': + resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==} + + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/remapping@2.3.5': + resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.5.5': + resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@napi-rs/wasm-runtime@1.1.4': + resolution: {integrity: sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==} + peerDependencies: + '@emnapi/core': ^1.7.1 + '@emnapi/runtime': ^1.7.1 + + '@oxc-project/types@0.133.0': + resolution: {integrity: sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==} + + '@protobufjs/aspromise@1.1.2': + resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==} + + '@protobufjs/base64@1.1.2': + resolution: {integrity: sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==} + + '@protobufjs/codegen@2.0.5': + resolution: {integrity: sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==} + + '@protobufjs/eventemitter@1.1.1': + resolution: {integrity: sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==} + + '@protobufjs/fetch@1.1.1': + resolution: {integrity: sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==} + + '@protobufjs/float@1.0.2': + resolution: {integrity: sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==} + + '@protobufjs/path@1.1.2': + resolution: {integrity: sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==} + + '@protobufjs/pool@1.1.0': + resolution: {integrity: sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==} + + '@protobufjs/utf8@1.1.2': + resolution: {integrity: sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==} + + '@rolldown/binding-android-arm64@1.0.3': + resolution: {integrity: sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.0.3': + resolution: {integrity: sha512-PcAhP+ynjURNyy8SKGl5DQP94aGuB/7JrXJb/t7P+hanXvQVMWzUvRRhBAcg/lNRadBhoUPqSoP4xw5tR/KBEA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.0.3': + resolution: {integrity: sha512-9YpfeUvSE2RS7wysJ81uOZkXJz7f7Q55H2Gvp3VEw/EsahqDtrphrZ0EwDLK5vvKOzaCrBsjF8JmnMLcUt78Gg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.0.3': + resolution: {integrity: sha512-yB1IlAsSNHncV6SCTL27/MVGR5htvQsoGxIv5KMGXALp+Ll1wYsn+x98M9MW7qa+NdSbvrrY7ANI4wLJ0n1e6g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.0.3': + resolution: {integrity: sha512-Yi30IVAAfLUCy2MseFjbB1jAMDl1VMCAas5StnYp8da9+CKvMd2H2cbEjWcw5NPaPqzvYkVIaF1nNUG+b7u/sw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.0.3': + resolution: {integrity: sha512-jsO7R8To+AdlYgUmN5sHSCZbfhtMBkO0WUx8iORQnPcMMdgr7qM2DQmMwgabs3GhNztdmoKkMKQFHD6DTMCIQw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + + '@rolldown/binding-linux-arm64-musl@1.0.3': + resolution: {integrity: sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + + '@rolldown/binding-linux-ppc64-gnu@1.0.3': + resolution: {integrity: sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + + '@rolldown/binding-linux-s390x-gnu@1.0.3': + resolution: {integrity: sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + + '@rolldown/binding-linux-x64-gnu@1.0.3': + resolution: {integrity: sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + + '@rolldown/binding-linux-x64-musl@1.0.3': + resolution: {integrity: sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + + '@rolldown/binding-openharmony-arm64@1.0.3': + resolution: {integrity: sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-wasm32-wasi@1.0.3': + resolution: {integrity: sha512-JTtb8BWFynicNSoPrehsCzBtOKjZ6jhMiPFEmOiuXg1Fl8dn2KHQob+GuPSGR0dryQa1PQJbzjF3dqO/whhjLg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [wasm32] + + '@rolldown/binding-win32-arm64-msvc@1.0.3': + resolution: {integrity: sha512-gEdFFEN70A/jxb2svrWsN3aDL7OUtmvlOy+6fa2jxG8K0wQ1ZbdeLGnidov6Yu5/733dI5ySfzFlQ/cb0bSz1g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.0.3': + resolution: {integrity: sha512-eXB7CHuaQdqmJcc3koCNtNPmT/bj2gc999kUFgBxG8Ac0NdgXc4rkCHhqrgrhN3zddvvvrgzj1e90SuSfmyIXA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@tailwindcss/node@4.3.2': + resolution: {integrity: sha512-yWP/sqEcBLaD8JuA6zNwxoYKr75qxTioYwlRwekj5Jr/I5GXnoJfjetH/psLUIv74cYTH2lBUEzBkinthoYcBg==} + + '@tailwindcss/oxide-android-arm64@4.3.2': + resolution: {integrity: sha512-WHxqIuHpvZ5VtdX6GTl1Ik/Vp2YuN42Et+0CdeaVd/frQ9jAvGmvR8vLT+jk3e8/Q3x8kECB9+R17pgpp2BulA==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [android] + + '@tailwindcss/oxide-darwin-arm64@4.3.2': + resolution: {integrity: sha512-GZypeUY/IDJW3877KeM+O67vbXr3MBnbtEL4aYhNErv/JWZhye2vGSWWG9tB6iiqR2MqRNkY8IOUy4NdSZV26w==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [darwin] + + '@tailwindcss/oxide-darwin-x64@4.3.2': + resolution: {integrity: sha512-UIIzmefR6KO1sDU7MzRqAxC8iBpft/VhkGjTjnhoS6k7Z3rQ9wEgA1ODSiyH/tcSYssulNm4Ci3hOeK1jH7ccQ==} + engines: {node: '>= 20'} + cpu: [x64] + os: [darwin] + + '@tailwindcss/oxide-freebsd-x64@4.3.2': + resolution: {integrity: sha512-GN+uAmcI6DNspnCDwtOAZrTz6oukJnp337qZvxqCGLd3BHBzJpO0ZbTLRvJNdztOeAmTzewewGIMPb0tk2R4WA==} + engines: {node: '>= 20'} + cpu: [x64] + os: [freebsd] + + '@tailwindcss/oxide-linux-arm-gnueabihf@4.3.2': + resolution: {integrity: sha512-4ABn7qSbdHRwTiDiuWNegCyb5+2FJ4vKIKc3DmKrvAFw7MU1Lm11dIkTPwUaFdTzc7IsOpDbqBrlh0x6y36U/w==} + engines: {node: '>= 20'} + cpu: [arm] + os: [linux] + + '@tailwindcss/oxide-linux-arm64-gnu@4.3.2': + resolution: {integrity: sha512-wDgEIGwoM8w8pufh9LVt1PahDgNdKXrLC2qfAnV3vAmococ9RWbxeAw4pxPttd/TsJfwjyLf90Dg1y9y8I6Emw==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [linux] + + '@tailwindcss/oxide-linux-arm64-musl@4.3.2': + resolution: {integrity: sha512-J5Nuk0uZQIiMTJj3LEx4sAA9tMFUoXQZFv1J6An+QGYe53HKRJuFDi0rpq/tuouCZeAbOBY3kQ6g8qeD4TUjtA==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [linux] + + '@tailwindcss/oxide-linux-x64-gnu@4.3.2': + resolution: {integrity: sha512-kqCZpSKOBEJO4mz7OqWoofBZeXTAwaVGPj0ErAj7CojmhKpWVWVOnrt9dE8odoIraZq4oj3ausM37kXi+Tow8w==} + engines: {node: '>= 20'} + cpu: [x64] + os: [linux] + + '@tailwindcss/oxide-linux-x64-musl@4.3.2': + resolution: {integrity: sha512-cixpqbh2toJDmkuCRI68nXA8ZxNmdK9Y+9v5h3MC3ZQKy/0BO8AWzlkWyRM7JAFSGBlfig4YVTPsK6MVgqz1uw==} + engines: {node: '>= 20'} + cpu: [x64] + os: [linux] + + '@tailwindcss/oxide-wasm32-wasi@4.3.2': + resolution: {integrity: sha512-4ec2Z/LOmRsAgU23CS4xeJfcJlmRg94A/XrbGRCF1gyU/zdDfRLYDVsS+ynSZCmGNxQ1jQriQOKMQeQxBA3Isw==} + engines: {node: '>=14.0.0'} + cpu: [wasm32] + bundledDependencies: + - '@napi-rs/wasm-runtime' + - '@emnapi/core' + - '@emnapi/runtime' + - '@tybys/wasm-util' + - '@emnapi/wasi-threads' + - tslib + + '@tailwindcss/oxide-win32-arm64-msvc@4.3.2': + resolution: {integrity: sha512-Zyr/M0+XcYZu3bZrUytc7TXvrk0ftWfl8gN2MwekNDzhqhKRUucMPSeOzM0o0wH5AWOU49BsKRrfKxI2atCPMQ==} + engines: {node: '>= 20'} + cpu: [arm64] + os: [win32] + + '@tailwindcss/oxide-win32-x64-msvc@4.3.2': + resolution: {integrity: sha512-QI9BO7KlNZsp2GuO0jwAAj5jCDABOKXRkCk2XuKTSaNEFSdfzqswYVTtCHBNKHLsqyjFyFkqlDiwkNbTYSssMQ==} + engines: {node: '>= 20'} + cpu: [x64] + os: [win32] + + '@tailwindcss/oxide@4.3.2': + resolution: {integrity: sha512-z8ZgnzX8gdNoWLBLqBPoh/sjnxkwvf9ZuWjnO0l0yIzbLa5/9S+eC5QxGZKRobVHIC3/1BoMWjHblqWjcgFgag==} + engines: {node: '>= 20'} + + '@tailwindcss/vite@4.3.2': + resolution: {integrity: sha512-eHpMeX4JXfVNJDEcsouTeCBubJBTcTLigeaw/NTUW6PB5ATKKXdyonnXgTBX2VuRbjz1hjfz6C5XAhr52ImQXA==} + peerDependencies: + vite: ^5.2.0 || ^6 || ^7 || ^8 + + '@tybys/wasm-util@0.10.2': + resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==} + + '@types/node@25.9.2': + resolution: {integrity: sha512-G05zqtJhcDLb8uslf5EjCxXg9G1KQxiV8OS0R26IC//Eoyitzqe8z37I7cqvnZlrlSfgocQRfSn/AHBZJJFyGw==} + + '@types/react-dom@19.2.3': + resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==} + peerDependencies: + '@types/react': ^19.2.0 + + '@types/react@19.2.17': + resolution: {integrity: sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==} + + '@vitejs/plugin-react@6.0.3': + resolution: {integrity: sha512-vmFvco5/QuC2f9Oj+wTk0+9XeDFkHxSamwZKYc7MxYwKICfvUvlMhqKI0VuICPltGqh1neqBKDvO4kes1ya8vg==} + engines: {node: ^20.19.0 || >=22.12.0} + peerDependencies: + '@rolldown/plugin-babel': ^0.1.7 || ^0.2.0 + babel-plugin-react-compiler: ^1.0.0 + vite: ^8.0.0 + peerDependenciesMeta: + '@rolldown/plugin-babel': + optional: true + babel-plugin-react-compiler: + optional: true + + automation-events@7.1.19: + resolution: {integrity: sha512-cD+TLhJTI0q4AI3ktd353lrGZiVa9AchowSDzQzzGjSoYe22js4vlS32VUtWuaulghi1Yq0KYNWKk9wWuGymPA==} + engines: {node: '>=18.2.0'} + + clsx@2.1.1: + resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} + engines: {node: '>=6'} + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + enhanced-resolve@5.21.6: + resolution: {integrity: sha512-aNnGCvbJ/RIyWo1IuhNdVjnNF+EjH9wpzpNHt+ci/m9He9LJvUN8wrCcXjp9cWsGNAuvSpVFTx/vraAFQ8qGjQ==} + engines: {node: '>=10.13.0'} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + flatbuffers@25.9.23: + resolution: {integrity: sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==} + + fsevents@2.3.2: + resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + graceful-fs@4.2.11: + resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + + guid-typescript@1.0.9: + resolution: {integrity: sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==} + + jiti@2.7.0: + resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} + hasBin: true + + lightningcss-android-arm64@1.32.0: + resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.32.0: + resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.32.0: + resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.32.0: + resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.32.0: + resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.32.0: + resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + + lightningcss-linux-arm64-musl@1.32.0: + resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + + lightningcss-linux-x64-gnu@1.32.0: + resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + + lightningcss-linux-x64-musl@1.32.0: + resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + + lightningcss-win32-arm64-msvc@1.32.0: + resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.32.0: + resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.32.0: + resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==} + engines: {node: '>= 12.0.0'} + + long@5.3.2: + resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + nanoid@3.3.12: + resolution: {integrity: sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + onnxruntime-common@1.27.0: + resolution: {integrity: sha512-3KxL5wIVqa8Ex08jxSzncm9CMgw8CjOFyOQ7SxvG9o0cVLlhTNKXyIQuTbtX4tGPJEf73OER2xrjt4HJSBL4ow==} + + onnxruntime-web@1.27.0: + resolution: {integrity: sha512-ogDLsqIozHZwifPuN37OproAo0byX6t43/bP8GzeZWBWD6MOGExswFAx3up4NS/vvWBOg2u2PXomDt3rMmdQSg==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.4: + resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} + engines: {node: '>=12'} + + platform@1.3.6: + resolution: {integrity: sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==} + + playwright-core@1.61.1: + resolution: {integrity: sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==} + engines: {node: '>=18'} + hasBin: true + + playwright@1.61.1: + resolution: {integrity: sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==} + engines: {node: '>=18'} + hasBin: true + + postcss@8.5.15: + resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==} + engines: {node: ^10 || ^12 || >=14} + + protobufjs@7.6.5: + resolution: {integrity: sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==} + engines: {node: '>=12.0.0'} + + react-dom@19.2.7: + resolution: {integrity: sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ==} + peerDependencies: + react: ^19.2.7 + + react@19.2.7: + resolution: {integrity: sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==} + engines: {node: '>=0.10.0'} + + rolldown@1.0.3: + resolution: {integrity: sha512-i00lAJ2ks1BYr7rjNjKC7BcqAS7nVfiT3QX1SI5aY+AFHblCmaUf9OE9dbdzDvW6dJxbi2ZCZiy9v3CcwOiX3g==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + scheduler@0.27.0: + resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + spessasynth_core@4.3.20: + resolution: {integrity: sha512-RcYCXemGESRKIRbGEAGOwFgNSXcsuLMptjk3BmRTJJWtF6RH4KLRXKkUs6rzREUh3ooInfsJla/sRmWvwZzjhw==} + + spessasynth_lib@4.3.8: + resolution: {integrity: sha512-v5D/XF9DH34FNwVSaoR51URsVxfGTuGSH577ZnmFwHOCo1mWq7b545oliIHxPFkP1OKoAjcp82oQFoqBv5i8pQ==} + deprecated: Only the latest version of spessasynth_lib is supported. + + standardized-audio-context@25.3.77: + resolution: {integrity: sha512-Ki9zNz6pKcC5Pi+QPjPyVsD9GwJIJWgryji0XL9cAJXMGyn+dPOf6Qik1AHei0+UNVcc4BOCa0hWLBzlwqsW/A==} + + stb-vorbis@0.0.6: + resolution: {integrity: sha512-CyvjJEGROIdnuZknwFvdOfMIO1ssUxO2OawsXCR3IlbJ8z2IMBjDe8FDxFJqBfLgf1ZOdqvoHAYx3Xk8q9rbbg==} + + tailwindcss@4.3.2: + resolution: {integrity: sha512-WtctNNSH8A9jlMIqxzuYumOHU5uGZyRv0Q5svQl+oEPy5w84YpBxdb7MdqyiSPQge5jTJ6zFQLq0PFygdccSBA==} + + tapable@2.3.3: + resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==} + engines: {node: '>=6'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tone@15.1.22: + resolution: {integrity: sha512-TCScAGD4sLsama5DjvTUXlLDXSqPealhL64nsdV1hhr6frPWve0DeSo63AKnSJwgfg55fhvxj0iPPRwPN5o0ag==} + + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + + typescript@6.0.3: + resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@7.24.6: + resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} + + vite@8.0.16: + resolution: {integrity: sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.1.18 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + +snapshots: + + '@babel/runtime@7.29.7': {} + + '@emnapi/core@1.10.0': + dependencies: + '@emnapi/wasi-threads': 1.2.1 + tslib: 2.8.1 + optional: true + + '@emnapi/runtime@1.10.0': + dependencies: + tslib: 2.8.1 + optional: true + + '@emnapi/wasi-threads@1.2.1': + dependencies: + tslib: 2.8.1 + optional: true + + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/remapping@2.3.5': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.5.5': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.5.5 + + '@napi-rs/wasm-runtime@1.1.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': + dependencies: + '@emnapi/core': 1.10.0 + '@emnapi/runtime': 1.10.0 + '@tybys/wasm-util': 0.10.2 + optional: true + + '@oxc-project/types@0.133.0': {} + + '@protobufjs/aspromise@1.1.2': {} + + '@protobufjs/base64@1.1.2': {} + + '@protobufjs/codegen@2.0.5': {} + + '@protobufjs/eventemitter@1.1.1': {} + + '@protobufjs/fetch@1.1.1': + dependencies: + '@protobufjs/aspromise': 1.1.2 + + '@protobufjs/float@1.0.2': {} + + '@protobufjs/path@1.1.2': {} + + '@protobufjs/pool@1.1.0': {} + + '@protobufjs/utf8@1.1.2': {} + + '@rolldown/binding-android-arm64@1.0.3': + optional: true + + '@rolldown/binding-darwin-arm64@1.0.3': + optional: true + + '@rolldown/binding-darwin-x64@1.0.3': + optional: true + + '@rolldown/binding-freebsd-x64@1.0.3': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.0.3': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.0.3': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.0.3': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.0.3': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.0.3': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.0.3': + optional: true + + '@rolldown/binding-linux-x64-musl@1.0.3': + optional: true + + '@rolldown/binding-openharmony-arm64@1.0.3': + optional: true + + '@rolldown/binding-wasm32-wasi@1.0.3': + dependencies: + '@emnapi/core': 1.10.0 + '@emnapi/runtime': 1.10.0 + '@napi-rs/wasm-runtime': 1.1.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.0.3': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.0.3': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@tailwindcss/node@4.3.2': + dependencies: + '@jridgewell/remapping': 2.3.5 + enhanced-resolve: 5.21.6 + jiti: 2.7.0 + lightningcss: 1.32.0 + magic-string: 0.30.21 + source-map-js: 1.2.1 + tailwindcss: 4.3.2 + + '@tailwindcss/oxide-android-arm64@4.3.2': + optional: true + + '@tailwindcss/oxide-darwin-arm64@4.3.2': + optional: true + + '@tailwindcss/oxide-darwin-x64@4.3.2': + optional: true + + '@tailwindcss/oxide-freebsd-x64@4.3.2': + optional: true + + '@tailwindcss/oxide-linux-arm-gnueabihf@4.3.2': + optional: true + + '@tailwindcss/oxide-linux-arm64-gnu@4.3.2': + optional: true + + '@tailwindcss/oxide-linux-arm64-musl@4.3.2': + optional: true + + '@tailwindcss/oxide-linux-x64-gnu@4.3.2': + optional: true + + '@tailwindcss/oxide-linux-x64-musl@4.3.2': + optional: true + + '@tailwindcss/oxide-wasm32-wasi@4.3.2': + optional: true + + '@tailwindcss/oxide-win32-arm64-msvc@4.3.2': + optional: true + + '@tailwindcss/oxide-win32-x64-msvc@4.3.2': + optional: true + + '@tailwindcss/oxide@4.3.2': + optionalDependencies: + '@tailwindcss/oxide-android-arm64': 4.3.2 + '@tailwindcss/oxide-darwin-arm64': 4.3.2 + '@tailwindcss/oxide-darwin-x64': 4.3.2 + '@tailwindcss/oxide-freebsd-x64': 4.3.2 + '@tailwindcss/oxide-linux-arm-gnueabihf': 4.3.2 + '@tailwindcss/oxide-linux-arm64-gnu': 4.3.2 + '@tailwindcss/oxide-linux-arm64-musl': 4.3.2 + '@tailwindcss/oxide-linux-x64-gnu': 4.3.2 + '@tailwindcss/oxide-linux-x64-musl': 4.3.2 + '@tailwindcss/oxide-wasm32-wasi': 4.3.2 + '@tailwindcss/oxide-win32-arm64-msvc': 4.3.2 + '@tailwindcss/oxide-win32-x64-msvc': 4.3.2 + + '@tailwindcss/vite@4.3.2(vite@8.0.16(@types/node@25.9.2)(jiti@2.7.0))': + dependencies: + '@tailwindcss/node': 4.3.2 + '@tailwindcss/oxide': 4.3.2 + tailwindcss: 4.3.2 + vite: 8.0.16(@types/node@25.9.2)(jiti@2.7.0) + + '@tybys/wasm-util@0.10.2': + dependencies: + tslib: 2.8.1 + optional: true + + '@types/node@25.9.2': + dependencies: + undici-types: 7.24.6 + + '@types/react-dom@19.2.3(@types/react@19.2.17)': + dependencies: + '@types/react': 19.2.17 + + '@types/react@19.2.17': + dependencies: + csstype: 3.2.3 + + '@vitejs/plugin-react@6.0.3(vite@8.0.16(@types/node@25.9.2)(jiti@2.7.0))': + dependencies: + '@rolldown/pluginutils': 1.0.1 + vite: 8.0.16(@types/node@25.9.2)(jiti@2.7.0) + + automation-events@7.1.19: + dependencies: + '@babel/runtime': 7.29.7 + tslib: 2.8.1 + + clsx@2.1.1: {} + + csstype@3.2.3: {} + + detect-libc@2.1.2: {} + + enhanced-resolve@5.21.6: + dependencies: + graceful-fs: 4.2.11 + tapable: 2.3.3 + + fdir@6.5.0(picomatch@4.0.4): + optionalDependencies: + picomatch: 4.0.4 + + flatbuffers@25.9.23: {} + + fsevents@2.3.2: + optional: true + + fsevents@2.3.3: + optional: true + + graceful-fs@4.2.11: {} + + guid-typescript@1.0.9: {} + + jiti@2.7.0: {} + + lightningcss-android-arm64@1.32.0: + optional: true + + lightningcss-darwin-arm64@1.32.0: + optional: true + + lightningcss-darwin-x64@1.32.0: + optional: true + + lightningcss-freebsd-x64@1.32.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.32.0: + optional: true + + lightningcss-linux-arm64-gnu@1.32.0: + optional: true + + lightningcss-linux-arm64-musl@1.32.0: + optional: true + + lightningcss-linux-x64-gnu@1.32.0: + optional: true + + lightningcss-linux-x64-musl@1.32.0: + optional: true + + lightningcss-win32-arm64-msvc@1.32.0: + optional: true + + lightningcss-win32-x64-msvc@1.32.0: + optional: true + + lightningcss@1.32.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.32.0 + lightningcss-darwin-arm64: 1.32.0 + lightningcss-darwin-x64: 1.32.0 + lightningcss-freebsd-x64: 1.32.0 + lightningcss-linux-arm-gnueabihf: 1.32.0 + lightningcss-linux-arm64-gnu: 1.32.0 + lightningcss-linux-arm64-musl: 1.32.0 + lightningcss-linux-x64-gnu: 1.32.0 + lightningcss-linux-x64-musl: 1.32.0 + lightningcss-win32-arm64-msvc: 1.32.0 + lightningcss-win32-x64-msvc: 1.32.0 + + long@5.3.2: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + + nanoid@3.3.12: {} + + onnxruntime-common@1.27.0: {} + + onnxruntime-web@1.27.0: + dependencies: + flatbuffers: 25.9.23 + guid-typescript: 1.0.9 + long: 5.3.2 + onnxruntime-common: 1.27.0 + platform: 1.3.6 + protobufjs: 7.6.5 + + picocolors@1.1.1: {} + + picomatch@4.0.4: {} + + platform@1.3.6: {} + + playwright-core@1.61.1: {} + + playwright@1.61.1: + dependencies: + playwright-core: 1.61.1 + optionalDependencies: + fsevents: 2.3.2 + + postcss@8.5.15: + dependencies: + nanoid: 3.3.12 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + protobufjs@7.6.5: + dependencies: + '@protobufjs/aspromise': 1.1.2 + '@protobufjs/base64': 1.1.2 + '@protobufjs/codegen': 2.0.5 + '@protobufjs/eventemitter': 1.1.1 + '@protobufjs/fetch': 1.1.1 + '@protobufjs/float': 1.0.2 + '@protobufjs/path': 1.1.2 + '@protobufjs/pool': 1.1.0 + '@protobufjs/utf8': 1.1.2 + '@types/node': 25.9.2 + long: 5.3.2 + + react-dom@19.2.7(react@19.2.7): + dependencies: + react: 19.2.7 + scheduler: 0.27.0 + + react@19.2.7: {} + + rolldown@1.0.3: + dependencies: + '@oxc-project/types': 0.133.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm64': 1.0.3 + '@rolldown/binding-darwin-arm64': 1.0.3 + '@rolldown/binding-darwin-x64': 1.0.3 + '@rolldown/binding-freebsd-x64': 1.0.3 + '@rolldown/binding-linux-arm-gnueabihf': 1.0.3 + '@rolldown/binding-linux-arm64-gnu': 1.0.3 + '@rolldown/binding-linux-arm64-musl': 1.0.3 + '@rolldown/binding-linux-ppc64-gnu': 1.0.3 + '@rolldown/binding-linux-s390x-gnu': 1.0.3 + '@rolldown/binding-linux-x64-gnu': 1.0.3 + '@rolldown/binding-linux-x64-musl': 1.0.3 + '@rolldown/binding-openharmony-arm64': 1.0.3 + '@rolldown/binding-wasm32-wasi': 1.0.3 + '@rolldown/binding-win32-arm64-msvc': 1.0.3 + '@rolldown/binding-win32-x64-msvc': 1.0.3 + + scheduler@0.27.0: {} + + source-map-js@1.2.1: {} + + spessasynth_core@4.3.20: + dependencies: + stb-vorbis: 0.0.6 + + spessasynth_lib@4.3.8: + dependencies: + spessasynth_core: 4.3.20 + + standardized-audio-context@25.3.77: + dependencies: + '@babel/runtime': 7.29.7 + automation-events: 7.1.19 + tslib: 2.8.1 + + stb-vorbis@0.0.6: {} + + tailwindcss@4.3.2: {} + + tapable@2.3.3: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.4) + picomatch: 4.0.4 + + tone@15.1.22: + dependencies: + standardized-audio-context: 25.3.77 + tslib: 2.8.1 + + tslib@2.8.1: {} + + typescript@6.0.3: {} + + undici-types@7.24.6: {} + + vite@8.0.16(@types/node@25.9.2)(jiti@2.7.0): + dependencies: + lightningcss: 1.32.0 + picomatch: 4.0.4 + postcss: 8.5.15 + rolldown: 1.0.3 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 25.9.2 + fsevents: 2.3.3 + jiti: 2.7.0 diff --git a/source/demo/web/public/favicon.png b/source/demo/web/public/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..7c8790cdc9d8aacda6f8cd34623eb9944be327bb Binary files /dev/null and b/source/demo/web/public/favicon.png differ diff --git a/source/demo/web/src/App.tsx b/source/demo/web/src/App.tsx new file mode 100644 index 0000000000000000000000000000000000000000..14a4222f5c85bc8cd21353e8131facca649a0629 --- /dev/null +++ b/source/demo/web/src/App.tsx @@ -0,0 +1,385 @@ +import { useEffect, useRef, useState } from "react"; +import clsx from "clsx"; +import type { PianoRoll } from "./pianoroll"; +import { useAudioEngine } from "./hooks/useAudioEngine"; +import { useTranscription, type AppState } from "./hooks/useTranscription"; +import { Controls } from "./components/Controls"; +import { OutputBar } from "./components/OutputBar"; +import { PianoRollCanvas } from "./components/PianoRollCanvas"; +import { InstrumentList } from "./components/InstrumentList"; +import { DropOverlay } from "./components/DropOverlay"; +import { Footer } from "./components/Footer"; +import { WelcomeScreen } from "./components/WelcomeScreen"; + +/** + * A failure surfaced on the welcome screen. `server` means the backend is + * unreachable (health probe / network) and replaces the file picker entirely; + * `file` is a per-upload problem (e.g. an undecodable audio file) shown + * alongside the picker so the user can choose a different file. + */ +export type AppError = { kind: "server" | "file"; message: string }; +import { ProgressEstimator, formatClock } from "./progress"; + +type Screen = "welcome" | "transcribe"; + +// The song is Headache by Lost Deposit. ig: @lostdeposit +const EXAMPLE = { + url: "/headache_by_lost_deposit_1min.mp3", + filename: "Lost Deposit - Headache (example track)", + conditioning: [ + "drums", + "electric_bass", + "distorted_electric_guitar", + "clean_electric_guitar", + "voice", + ], +}; + +export function App() { + const audio = useAudioEngine(); + const rollRef = useRef(null); + const clockRef = useRef(null); + // Progress estimator (stable across renders) + the DOM nodes its smoothed + // fraction/ETA are written into each frame. + const progressRef = useRef(null); + const progress = (progressRef.current ??= new ProgressEstimator()); + const progressFillRef = useRef(null); + const progressLabelRef = useRef(null); + + const [screen, setScreen] = useState("welcome"); + const [selectedFile, setSelectedFile] = useState(null); + const [appState, setAppState] = useState("idle"); + // Shown on the welcome screen: a server-down notice (set when the /health + // check fails) or a per-file error (set when a transcription is rejected). + // null = healthy and no file error. + const [error, setError] = useState(null); + const [instruments, setInstruments] = useState([]); + const [midiUrl, setMidiUrl] = useState(null); + const [midiBlob, setMidiBlob] = useState(null); + const [currentFile, setCurrentFile] = useState(null); + const [mix, setMix] = useState(0.75); + const [stereo, setStereo] = useState(false); + const [userScrolled, setUserScrolled] = useState(false); + const [condSelected, setCondSelected] = useState>(() => new Set()); + // True while a file is being dragged over the window. On the welcome screen + // this swaps the panel's prompt in place instead of showing the overlay. + const [dragging, setDragging] = useState(false); + + const midiFilenameRef = useRef("transcription.mid"); + // Mirror of the selected conditioning set, read at submit time without + // re-creating `transcribe` whenever the selection changes. + const condRef = useRef(condSelected); + condRef.current = condSelected; + // Read inside the per-frame loop (which only re-subscribes on `audio`) so the + // transcribed-so-far tint is only drawn while a transcription is running. + const appStateRef = useRef(appState); + appStateRef.current = appState; + + const { transcribe, abort } = useTranscription({ + audio, + rollRef, + getConditioning: () => Array.from(condRef.current), + progress, + // A failed transcription bounces back to the welcome screen with a message. + onError: (message) => { + setError({ kind: "file", message }); + setScreen("welcome"); + }, + setAppState, + setInstruments, + setMidiUrl, + setMidiBlob, + setCurrentFile, + setUserScrolled, + midiFilenameRef, + }); + // Start transcribing the file picked on the welcome screen and switch views. + // Called from a button click, so the AudioContext unlock inside `transcribe` + // still happens under a user gesture. + function startTranscription() { + if (selectedFile === null) return; + // Drop any leftover file error from a previous failed attempt. + setError(null); + setScreen("transcribe"); + transcribe(selectedFile); + } + + // Tear down the current transcription (in-flight or finished) and return to + // the welcome screen. The previously chosen conditioning is kept so it's easy + // to re-run with the same settings. + function resetToWelcome() { + // Stop the in-flight run right away (not just when the next one starts): + // otherwise it keeps streaming notes into the torn-down UI and keeps the + // server transcribing — and the server lock held — while the user picks + // the next file. + abort(); + audio.reset(); + rollRef.current?.clear(); + setInstruments([]); + setMidiUrl(null); + setMidiBlob(null); + setUserScrolled(false); + setAppState("idle"); + setScreen("welcome"); + } + + // "Transcribe another file" (also the wordmark, on the transcribe screen): + // confirm (the work is about to be discarded), then tear down and go back. + function transcribeAnother() { + if (!window.confirm("Discard this transcription and start over?")) return; + setSelectedFile(null); + resetToWelcome(); + } + + // Load the bundled demo track and pre-fill conditioning with a reasonable + // guess for it (a rock track). The user still reviews and hits "Transcribe". + async function useExample() { + const resp = await fetch(EXAMPLE.url); + if (!resp.ok) throw new Error(`HTTP ${resp.status}`); + const blob = await resp.blob(); + const file = new File([blob], EXAMPLE.filename, { type: "audio/mpeg" }); + setCondSelected(new Set(EXAMPLE.conditioning)); + setSelectedFile(file); + } + + // A file dropped anywhere on the page selects it on the welcome screen, from + // either screen — dropping while a transcription is showing returns you to the + // welcome screen with the new file picked, so you can choose conditioning + // before hitting "Transcribe". It does not auto-start. Routed through a ref so + // the window-level handler (installed once) always calls the latest closure. + function onDropFile(file: File) { + // Dropping onto the transcribe screen abandons the current run — confirm + // first, then tear everything down (stop playback, clear the roll) so the + // music doesn't keep playing behind the welcome screen. + if (screen === "transcribe") { + if (!window.confirm("Discard this transcription and start over with the dropped file?")) + return; + resetToWelcome(); + } + setSelectedFile(file); + } + const dropRef = useRef(onDropFile); + dropRef.current = onDropFile; + + // Drive the body's data-state (it lives outside the React root) from state. + useEffect(() => { + document.body.dataset.state = appState; + }, [appState]); + + // Drag & drop works anywhere on the page; a fullscreen overlay (CSS, keyed off + // `body.drag`) shows while a file is being dragged. dragenter/dragleave fire + // on every child element, so keep a depth counter to know when the drag truly + // left the window. + useEffect(() => { + let dragDepth = 0; + const onEnter = (e: DragEvent) => { + e.preventDefault(); + dragDepth++; + document.body.classList.add("drag"); + setDragging(true); + }; + const onOver = (e: DragEvent) => e.preventDefault(); + const onLeave = () => { + dragDepth = Math.max(0, dragDepth - 1); + if (dragDepth === 0) { + document.body.classList.remove("drag"); + setDragging(false); + } + }; + const onDrop = (e: DragEvent) => { + e.preventDefault(); + dragDepth = 0; + document.body.classList.remove("drag"); + setDragging(false); + const f = e.dataTransfer?.files?.[0]; + if (f) dropRef.current(f); + }; + window.addEventListener("dragenter", onEnter); + window.addEventListener("dragover", onOver); + window.addEventListener("dragleave", onLeave); + window.addEventListener("drop", onDrop); + return () => { + window.removeEventListener("dragenter", onEnter); + window.removeEventListener("dragover", onOver); + window.removeEventListener("dragleave", onLeave); + window.removeEventListener("drop", onDrop); + }; + }, []); + + // Space toggles play/pause on the transcribe screen. Ignored while focus is + // on a form control (slider, checkbox, button) so its native space behavior + // is preserved. + useEffect(() => { + if (screen !== "transcribe") return; + const onKey = (e: KeyboardEvent) => { + if (e.code !== "Space" && e.key !== " ") return; + const tag = (e.target as HTMLElement | null)?.tagName; + if (tag === "INPUT" || tag === "BUTTON" || tag === "SELECT" || tag === "TEXTAREA") + return; + e.preventDefault(); + if (audio.state === "started") audio.pause(); + else audio.play(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [screen, audio]); + + // Per-frame: advance the playhead, redraw the canvas, and tick the clock. + // Kept off React state so it doesn't trigger ~60fps re-renders. + useEffect(() => { + let raf = 0; + const frame = () => { + const roll = rollRef.current; + if (roll) { + roll.setPlayhead(audio.seconds); + // Feed the chunk-completion estimate of the transcribed span (completed + // fraction × audio length). The roll combines it with the latest note + // onset and eases the frontier itself; null while not transcribing + // disables the tint (once done the whole roll is covered). + const dur = audio.duration; + roll.setDuration(dur); + roll.setTranscribedUntil( + appStateRef.current === "transcribing" && dur > 0 + ? progress.completedFraction() * dur + : null, + ); + roll.render(); + } + if (clockRef.current) clockRef.current.textContent = `${audio.seconds.toFixed(1)}s`; + // Drive the progress bar straight to the DOM (only mounted while + // transcribing) so the smoothing doesn't re-render the app each frame. + if (progressFillRef.current) { + const now = performance.now(); + const frac = progress.fraction(now); + progressFillRef.current.style.width = `${(frac * 100).toFixed(1)}%`; + // Estimated time transcribed (smoothed fraction × audio length) out of + // the file's total length, plus the ETA once a pace estimate exists. + if (progressLabelRef.current) { + const dur = audio.duration; + if (dur > 0) { + let text = `${formatClock(frac * dur)}/${formatClock(dur)}`; + const eta = progress.etaMs(now); + if (eta != null) text += ` · done in ${formatClock(eta / 1000)}`; + progressLabelRef.current.textContent = text; + } else { + progressLabelRef.current.textContent = ""; + } + } + } + raf = requestAnimationFrame(frame); + }; + raf = requestAnimationFrame(frame); + return () => cancelAnimationFrame(raf); + }, [audio]); + + // Expose for browser-devtools debugging. + useEffect(() => { + (window as unknown as { __mu: unknown }).__mu = { audio, rollRef }; + }, [audio]); + + return ( + <> +