supersonic-scsynth 0.44.0 → 0.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/metrics-dark.css +86 -0
- package/dist/metrics-light.css +86 -0
- package/dist/metrics_component.js +1 -0
- package/dist/osc_channel.js +1 -1
- package/dist/supersonic.js +5 -5
- package/package.json +8 -2
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/* supersonic-metrics dark theme
|
|
2
|
+
* Styles for the <supersonic-metrics> web component (ssm- namespace).
|
|
3
|
+
* Load this file to get a dark-themed metrics panel with a responsive grid layout.
|
|
4
|
+
* Override grid-template-columns on supersonic-metrics to control column count. */
|
|
5
|
+
|
|
6
|
+
/* Default responsive layout — auto-fit collapses empty tracks so the last row fills fully */
|
|
7
|
+
supersonic-metrics {
|
|
8
|
+
display: grid;
|
|
9
|
+
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
|
|
10
|
+
gap: 4px;
|
|
11
|
+
background: #111;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/* Panel */
|
|
15
|
+
.ssm-panel {
|
|
16
|
+
background: #111;
|
|
17
|
+
border: 1px solid #333;
|
|
18
|
+
border-radius: 4px;
|
|
19
|
+
padding: 8px 10px 10px;
|
|
20
|
+
font-family: inherit;
|
|
21
|
+
font-size: 12px;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
.ssm-panel--wide { padding-right: 16px; }
|
|
25
|
+
|
|
26
|
+
/* Title */
|
|
27
|
+
.ssm-title {
|
|
28
|
+
color: #666;
|
|
29
|
+
font-size: 10px;
|
|
30
|
+
text-transform: uppercase;
|
|
31
|
+
letter-spacing: 0.5px;
|
|
32
|
+
margin-bottom: 6px;
|
|
33
|
+
padding-bottom: 4px;
|
|
34
|
+
border-bottom: 1px solid #282828;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/* Value row */
|
|
38
|
+
.ssm-row {
|
|
39
|
+
display: flex;
|
|
40
|
+
justify-content: space-between;
|
|
41
|
+
color: #888;
|
|
42
|
+
padding: 1px 0;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
.ssm-label { color: #888; }
|
|
46
|
+
|
|
47
|
+
/* Value kinds */
|
|
48
|
+
.ssm-value { color: #7ee787; font-variant-numeric: tabular-nums; }
|
|
49
|
+
.ssm-value[data-kind="green"] { color: #7ee787; }
|
|
50
|
+
.ssm-value[data-kind="error"] { color: #f85149; }
|
|
51
|
+
.ssm-value[data-kind="purple"] { color: #d8b4fe; }
|
|
52
|
+
.ssm-value[data-kind="dim"] { color: #444; }
|
|
53
|
+
.ssm-value[data-kind="muted"] { color: #888; }
|
|
54
|
+
|
|
55
|
+
.ssm-sep { color: #444; }
|
|
56
|
+
|
|
57
|
+
/* Bar chart */
|
|
58
|
+
.ssm-bar {
|
|
59
|
+
display: flex;
|
|
60
|
+
align-items: center;
|
|
61
|
+
gap: 6px;
|
|
62
|
+
padding: 2px 0;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
.ssm-bar-label { color: #888; width: 20px; font-size: 11px; }
|
|
66
|
+
|
|
67
|
+
.ssm-bar-track {
|
|
68
|
+
flex: 1;
|
|
69
|
+
height: 4px;
|
|
70
|
+
background: #1a1a1a;
|
|
71
|
+
border-radius: 2px;
|
|
72
|
+
overflow: hidden;
|
|
73
|
+
position: relative;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
.ssm-bar-fill { height: 100%; transition: width 0.3s; }
|
|
77
|
+
.ssm-bar-fill--blue { background: #3b82f6; }
|
|
78
|
+
.ssm-bar-fill--green { background: #4ade80; }
|
|
79
|
+
.ssm-bar-fill--purple { background: #c084fc; }
|
|
80
|
+
|
|
81
|
+
.ssm-bar-peak { position: absolute; top: 0; width: 2px; height: 100%; left: 0; }
|
|
82
|
+
.ssm-bar-peak--blue { background: #93c5fd; }
|
|
83
|
+
.ssm-bar-peak--green { background: #bbf7d0; }
|
|
84
|
+
.ssm-bar-peak--purple { background: #e9d5ff; }
|
|
85
|
+
|
|
86
|
+
.ssm-bar-value { width: 28px; text-align: right; color: #888; font-size: 11px; }
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/* supersonic-metrics light theme
|
|
2
|
+
* Styles for the <supersonic-metrics> web component (ssm- namespace).
|
|
3
|
+
* Load this file to get a light-themed metrics panel with a responsive grid layout.
|
|
4
|
+
* Override grid-template-columns on supersonic-metrics to control column count. */
|
|
5
|
+
|
|
6
|
+
/* Default responsive layout — auto-fit collapses empty tracks so the last row fills fully */
|
|
7
|
+
supersonic-metrics {
|
|
8
|
+
display: grid;
|
|
9
|
+
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
|
|
10
|
+
gap: 4px;
|
|
11
|
+
background: #f8f8fa;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/* Panel */
|
|
15
|
+
.ssm-panel {
|
|
16
|
+
background: #f8f8fa;
|
|
17
|
+
border: 1px solid #ddd;
|
|
18
|
+
border-radius: 4px;
|
|
19
|
+
padding: 8px 10px 10px;
|
|
20
|
+
font-family: inherit;
|
|
21
|
+
font-size: 12px;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
.ssm-panel--wide { padding-right: 16px; }
|
|
25
|
+
|
|
26
|
+
/* Title */
|
|
27
|
+
.ssm-title {
|
|
28
|
+
color: #888;
|
|
29
|
+
font-size: 10px;
|
|
30
|
+
text-transform: uppercase;
|
|
31
|
+
letter-spacing: 0.5px;
|
|
32
|
+
margin-bottom: 6px;
|
|
33
|
+
padding-bottom: 4px;
|
|
34
|
+
border-bottom: 1px solid #e8e8e8;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/* Value row */
|
|
38
|
+
.ssm-row {
|
|
39
|
+
display: flex;
|
|
40
|
+
justify-content: space-between;
|
|
41
|
+
color: #666;
|
|
42
|
+
padding: 1px 0;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
.ssm-label { color: #666; }
|
|
46
|
+
|
|
47
|
+
/* Value kinds */
|
|
48
|
+
.ssm-value { color: #16a34a; font-variant-numeric: tabular-nums; }
|
|
49
|
+
.ssm-value[data-kind="green"] { color: #16a34a; }
|
|
50
|
+
.ssm-value[data-kind="error"] { color: #dc2626; }
|
|
51
|
+
.ssm-value[data-kind="purple"] { color: #9333ea; }
|
|
52
|
+
.ssm-value[data-kind="dim"] { color: #aaa; }
|
|
53
|
+
.ssm-value[data-kind="muted"] { color: #999; }
|
|
54
|
+
|
|
55
|
+
.ssm-sep { color: #bbb; }
|
|
56
|
+
|
|
57
|
+
/* Bar chart */
|
|
58
|
+
.ssm-bar {
|
|
59
|
+
display: flex;
|
|
60
|
+
align-items: center;
|
|
61
|
+
gap: 6px;
|
|
62
|
+
padding: 2px 0;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
.ssm-bar-label { color: #666; width: 20px; font-size: 11px; }
|
|
66
|
+
|
|
67
|
+
.ssm-bar-track {
|
|
68
|
+
flex: 1;
|
|
69
|
+
height: 4px;
|
|
70
|
+
background: #e5e5e5;
|
|
71
|
+
border-radius: 2px;
|
|
72
|
+
overflow: hidden;
|
|
73
|
+
position: relative;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
.ssm-bar-fill { height: 100%; transition: width 0.3s; }
|
|
77
|
+
.ssm-bar-fill--blue { background: #3b82f6; }
|
|
78
|
+
.ssm-bar-fill--green { background: #22c55e; }
|
|
79
|
+
.ssm-bar-fill--purple { background: #a855f7; }
|
|
80
|
+
|
|
81
|
+
.ssm-bar-peak { position: absolute; top: 0; width: 2px; height: 100%; left: 0; }
|
|
82
|
+
.ssm-bar-peak--blue { background: #60a5fa; }
|
|
83
|
+
.ssm-bar-peak--green { background: #4ade80; }
|
|
84
|
+
.ssm-bar-peak--purple { background: #c084fc; }
|
|
85
|
+
|
|
86
|
+
.ssm-bar-value { width: 28px; text-align: right; color: #888; font-size: 11px; }
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function u(a){if(!Number.isFinite(a)||a<=0)return"0 B";let l=["B","KB","MB","GB"],e=0;for(;a>=1024&&e<l.length-1;)a/=1024,e++;return`${a.toFixed(e>0?1:0)} ${l[e]}`}function h(a){return a===4294967295?"-":String(a)}function E(a,l){return l[a]??String(a)}function v(a){return String(a|0)}function C(a,l){if(a.format==="bytes")return e=>u(e);if(a.format==="headroom")return e=>h(e);if(a.format==="signed")return e=>v(e);if(a.format==="enum"&&l?.values){let e=l.values;return t=>E(t,e)}return e=>String(e)}var m=class extends HTMLElement{#e=null;#t=null;#s=[];#n=[];#l=!1;buildFromSchema(l){let e=l.getMetricsSchema(),t=e.metrics,n=e.layout;this.innerHTML="",this.#s=[],this.#n=[];for(let o of n.panels){let i=document.createElement("div");i.className="ssm-panel"+(o.class?` ssm-panel--${o.class}`:"");let r=document.createElement("div");r.className="ssm-title",r.textContent=o.title,i.appendChild(r);for(let s of o.rows)s.type==="bar"?this.#i(i,s,t):this.#a(i,s,t);this.appendChild(i)}this.#l=!0}connect(l,e={}){this.disconnect(),this.#e=l,this.#l||this.buildFromSchema(l.constructor);let t=e.refreshRate??10;this.#t=setInterval(()=>this.#c(),1e3/t)}disconnect(){this.#t!==null&&(clearInterval(this.#t),this.#t=null),this.#e=null}disconnectedCallback(){this.disconnect()}#a(l,e,t){let n=document.createElement("div");n.className="ssm-row";let o=e.cells?.find(s=>s.key);if(o){let s=t[o.key];s?.description&&(n.title=s.description)}let i=document.createElement("span");i.className="ssm-label",i.textContent=e.label,n.appendChild(i);let r=document.createElement("span");for(let s of e.cells||[])if(s.sep!==void 0){let c=document.createElement("span");c.className="ssm-sep",c.textContent=s.sep,r.appendChild(c)}else if(s.text!==void 0){let c=document.createElement("span");c.className="ssm-value",s.kind&&c.setAttribute("data-kind",s.kind),c.textContent=s.text,r.appendChild(c)}else if(s.key){let c=t[s.key];if(!c)continue;let d=document.createElement("span");d.className="ssm-value",s.kind&&d.setAttribute("data-kind",s.kind),d.textContent="-",r.appendChild(d),this.#s.push({offset:c.offset,format:C(s,c),el:d,prev:-1})}n.appendChild(r),l.appendChild(n)}#i(l,e,t){let n=document.createElement("div");n.className="ssm-bar";let o=t[e.usedKey],i=t[e.peakKey],r=t[e.capacityKey];o?.description&&(n.title=o.description);let s=document.createElement("span");s.className="ssm-bar-label",s.textContent=e.label,n.appendChild(s);let c=document.createElement("div");c.className="ssm-bar-track";let d=document.createElement("div");d.className=`ssm-bar-fill ssm-bar-fill--${e.color}`,c.appendChild(d);let p=document.createElement("div");p.className=`ssm-bar-peak ssm-bar-peak--${e.color}`,c.appendChild(p),n.appendChild(c);let f=document.createElement("span");f.className="ssm-bar-value ssm-value",e.color==="green"?f.setAttribute("data-kind","green"):e.color==="purple"&&f.setAttribute("data-kind","purple"),f.textContent="-",n.appendChild(f),l.appendChild(n),this.#n.push({usedOffset:o?.offset??0,peakOffset:i?.offset??0,capacityOffset:r?.offset??0,fillEl:d,peakEl:p,labelEl:f,prevUsed:-1,prevPeak:-1,prevCap:-1})}#c(){if(!this.#e)return;let l=this.#e.getMetricsArray();for(let e=0;e<this.#s.length;e++){let t=this.#s[e],n=l[t.offset];n!==t.prev&&(t.el.textContent=t.format(n),t.prev=n)}for(let e=0;e<this.#n.length;e++){let t=this.#n[e],n=l[t.usedOffset],o=l[t.peakOffset],i=l[t.capacityOffset];if(n!==t.prevUsed||i!==t.prevCap){if(i>0){let r=n/i*100;t.fillEl.style.width=r+"%",t.labelEl.textContent=r.toFixed(1)+"%"}else t.fillEl.style.width="0%",t.labelEl.textContent="N/A";t.prevUsed=n,t.prevCap=i}if(o!==t.prevPeak&&i>0){let r=o/i*100;t.peakEl.style.left=`calc(${r}% - 1px)`,t.prevPeak=o}}}};typeof customElements<"u"&&!customElements.get("supersonic-metrics")&&customElements.define("supersonic-metrics",m);export{m as SupersonicMetrics};
|
package/dist/osc_channel.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function B(e,t,s){return(s-1-e+t)%s}function L({uint8View:e,dataView:t,bufferStart:s,bufferSize:r,head:n,payload:o,sequence:i,messageMagic:c,headerSize:_,sourceId:S=0,headerScratch:p=null,headerScratchView:l=null}){let f=o.length,T=_+f+3&-4,u=r-n;if(T>u){let E=p||new Uint8Array(_),A=l||new DataView(E.buffer);A.setUint32(0,c,!0),A.setUint32(4,T,!0),A.setUint32(8,i,!0),A.setUint32(12,S,!0);let I=s+n,U=s;if(u>=_){e.set(E,I);let a=u-_;a>0&&e.set(o.subarray(0,a),I+_),e.set(o.subarray(a),U)}else{e.set(E.subarray(0,u),I),e.set(E.subarray(u),U);let a=_-u;e.set(o,U+a)}}else{let E=s+n;t.setUint32(E,c,!0),t.setUint32(E+4,T,!0),t.setUint32(E+8,i,!0),t.setUint32(E+12,S,!0),e.set(o,E+_)}return(n+T)%r}function Y(e,t,s=0,r=!1){for(let n=0;n<=s;n++)if(Atomics.compareExchange(e,t,0,1)===0)return!0;if(r){for(let o=0;o<100;o++)if(Atomics.wait(e,t,1,100),Atomics.compareExchange(e,t,0,1)===0)return!0;return console.error("[RingBuffer] Lock acquisition timeout after 10s - possible deadlock"),!1}return!1}function b(e,t){Atomics.store(e,t,0),Atomics.notify(e,t,1)}function N({atomicView:e,dataView:t,uint8View:s,bufferConstants:r,ringBufferBase:n,controlIndices:o,oscMessage:i,sourceId:c=0,maxSpins:_=0,useWait:S=!1}){let p=i.length,l=r.MESSAGE_HEADER_SIZE+p;if(l>r.IN_BUFFER_SIZE-r.MESSAGE_HEADER_SIZE||!Y(e,o.IN_WRITE_LOCK,_,S))return!1;try{let f=Atomics.load(e,o.IN_HEAD),R=Atomics.load(e,o.IN_TAIL),T=l+3&-4;if(B(f,R,r.IN_BUFFER_SIZE)<T)return!1;let E=Atomics.add(e,o.IN_SEQUENCE,1),A=L({uint8View:s,dataView:t,bufferStart:n+r.IN_BUFFER_START,bufferSize:r.IN_BUFFER_SIZE,head:f,payload:i,sequence:E,messageMagic:r.MESSAGE_MAGIC,headerSize:r.MESSAGE_HEADER_SIZE,sourceId:c});return Atomics.load(e,o.IN_HEAD),Atomics.store(e,o.IN_HEAD,A),Atomics.notify(e,o.IN_HEAD,1),!0}finally{b(e,o.IN_WRITE_LOCK)}}function d(e,t){let s=e+t;return{IN_HEAD:(s+0)/4,IN_TAIL:(s+4)/4,IN_SEQUENCE:(s+24)/4,IN_WRITE_LOCK:(s+40)/4,IN_LOG_TAIL:(s+44)/4}}function y(e){return e.length>=8&&e[0]===35&&e[1]===98&&e[2]===117&&e[3]===110&&e[4]===100&&e[5]===108&&e[6]===101&&e[7]===0}function k(e){if(e.length<16)return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{ntpSeconds:t.getUint32(8,!1),ntpFraction:t.getUint32(12,!1)}}function C(){return(performance.timeOrigin+performance.now())/1e3+2208988800}function D(e,t={}){let{getCurrentNTP:s=C,bypassLookaheadS:r=.5}=t;if(!y(e))return"nonBundle";let n=k(e);if(!n)return"nonBundle";let{ntpSeconds:o,ntpFraction:i}=n;if(o===0&&i<=1)return"immediate";let c=s();if(c===null||c===0)return"immediate";let S=o+i/4294967296-c;return S<0?"late":S<r?"nearFuture":"farFuture"}function O(e){return e!=="farFuture"}var h=class e{#s;#r;#o;#_;#e;#t;#i;#E;#c;#S;#n={messagesSent:0,bytesSent:0,nonBundle:0,immediate:0,nearFuture:0,late:0,bypassed:0};constructor(t,s){if(this.#s=t,this.#e=s.preschedulerPort||null,this.#i=s.bypassLookaheadS??.5,this.#E=s.sourceId??0,this.#c=s.blocking??this.#E!==0,this.#S=s.getCurrentNTP??C,t==="postMessage")this.#r=s.port;else if(this.#o={sharedBuffer:s.sharedBuffer,ringBufferBase:s.ringBufferBase,bufferConstants:s.bufferConstants,controlIndices:s.controlIndices},this.#a(),s.sharedBuffer&&s.bufferConstants){let r=s.ringBufferBase+s.bufferConstants.METRICS_START;this.#t=new Int32Array(s.sharedBuffer,r,s.bufferConstants.METRICS_SIZE/4)}}#a(){let t=this.#o.sharedBuffer;this.#_={atomicView:new Int32Array(t),dataView:new DataView(t),uint8View:new Uint8Array(t)}}classify(t){return D(t,{getCurrentNTP:this.#S,bypassLookaheadS:this.#i})}#T(t,s=null){if(this.#s==="sab"&&this.#t){if(Atomics.add(this.#t,24,1),Atomics.add(this.#t,25,t),s){let n={nonBundle:38,immediate:39,nearFuture:40,late:41}[s];n!==void 0&&(Atomics.add(this.#t,n,1),Atomics.add(this.#t,22,1))}}else this.#n.messagesSent++,this.#n.bytesSent+=t,s&&s in this.#n&&(this.#n[s]++,this.#n.bypassed++)}getAndResetMetrics(){let t={...this.#n};return this.#n={messagesSent:0,bytesSent:0,nonBundle:0,immediate:0,nearFuture:0,late:0,bypassed:0},t}getMetrics(){return this.#s==="sab"&&this.#t?{messagesSent:Atomics.load(this.#t,24),bytesSent:Atomics.load(this.#t,25),nonBundle:Atomics.load(this.#t,38),immediate:Atomics.load(this.#t,39),nearFuture:Atomics.load(this.#t,40),late:Atomics.load(this.#t,41),bypassed:Atomics.load(this.#t,22)}:{...this.#n}}#u(t,s=null,r=!0){if(this.#s==="postMessage")return this.#r?(this.#r.postMessage({type:"osc",oscData:t,bypassCategory:s,sourceId:this.#E}),!0):!1;{let n=this.#c,o=N({atomicView:this.#_.atomicView,dataView:this.#_.dataView,uint8View:this.#_.uint8View,bufferConstants:this.#o.bufferConstants,ringBufferBase:this.#o.ringBufferBase,controlIndices:this.#o.controlIndices,oscMessage:t,sourceId:this.#E,maxSpins:n?10:0,useWait:n});return!o&&!n&&r&&this.#e?(this.#t&&Atomics.add(this.#t,45,1),this.#e.postMessage({type:"directDispatch",oscData:t,sourceId:this.#E}),!0):o}}#A(t){return this.#e?(this.#e.postMessage({type:"osc",oscData:t,sourceId:this.#E}),!0):(console.error("[OscChannel] No prescheduler port, sending direct"),this.#u(t))}send(t){let s=this.classify(t);if(O(s)){let r=this.#u(t,s);return r&&this.#T(t.length,s),r}else{let r=this.#A(t);return r&&this.#T(t.length,null),r}}sendDirect(t){return this.#u(t)}sendToPrescheduler(t){return this.#A(t)}set getCurrentNTP(t){this.#S=t}get mode(){return this.#s}get transferable(){let t={mode:this.#s,preschedulerPort:this.#e,bypassLookaheadS:this.#i,sourceId:this.#E,blocking:this.#c};return this.#s==="postMessage"?{...t,port:this.#r}:{...t,sharedBuffer:this.#o.sharedBuffer,ringBufferBase:this.#o.ringBufferBase,bufferConstants:this.#o.bufferConstants,controlIndices:this.#o.controlIndices}}get transferList(){let t=[];return this.#s==="postMessage"&&this.#r&&t.push(this.#r),this.#e&&t.push(this.#e),t}close(){this.#s==="postMessage"&&this.#r&&(this.#r.close(),this.#r=null),this.#e&&(this.#e.close(),this.#e=null)}static createPostMessage(t){return t instanceof MessagePort?new e("postMessage",{port:t}):new e("postMessage",t)}static createSAB(t){let s=t.controlIndices;return s||(s=d(t.ringBufferBase,t.bufferConstants.CONTROL_START)),new e("sab",{sharedBuffer:t.sharedBuffer,ringBufferBase:t.ringBufferBase,bufferConstants:t.bufferConstants,controlIndices:s,preschedulerPort:t.preschedulerPort,bypassLookaheadS:t.bypassLookaheadS,sourceId:t.sourceId,blocking:t.blocking})}static fromTransferable(t){return t.mode==="postMessage"?new e("postMessage",{port:t.port,preschedulerPort:t.preschedulerPort,bypassLookaheadS:t.bypassLookaheadS,sourceId:t.sourceId,blocking:t.blocking}):new e("sab",{sharedBuffer:t.sharedBuffer,ringBufferBase:t.ringBufferBase,bufferConstants:t.bufferConstants,controlIndices:t.controlIndices,preschedulerPort:t.preschedulerPort,bypassLookaheadS:t.bypassLookaheadS,sourceId:t.sourceId,blocking:t.blocking})}};export{h as OscChannel};
|
package/dist/supersonic.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var xt=Object.defineProperty;var Pt=(i,e)=>{for(var t in e)xt(i,t,{get:e[t],enumerable:!0})};var U=class i{constructor(e){if(new.target===i)throw new Error("Transport is abstract - use SABTransport or PostMessageTransport");this._config=e,this._disposed=!1}get mode(){return this._config.mode}send(e,t){throw new Error("Abstract method - implement in subclass")}onReply(e){throw new Error("Abstract method - implement in subclass")}onDebug(e){throw new Error("Abstract method - implement in subclass")}onError(e){throw new Error("Abstract method - implement in subclass")}getMetrics(){throw new Error("Abstract method - implement in subclass")}async initialize(){throw new Error("Abstract method - implement in subclass")}createOscChannel(){throw new Error("Abstract method - implement in subclass")}dispose(){this._disposed=!0}get ready(){throw new Error("Abstract method - implement in subclass")}};var de=new Map;function ve(i){try{return new URL(i,window.location.href).origin!==window.location.origin}catch{return!1}}async function He(i){if(de.has(i))return de.get(i);let e=await fetch(i);if(!e.ok)throw new Error(`Failed to fetch ${i}: ${e.status} ${e.statusText}`);let t=await e.text(),s=new Blob([t],{type:"application/javascript"}),r=URL.createObjectURL(s);return de.set(i,r),r}async function R(i,e={}){let t=i;return ve(i)&&(t=await He(i)),new Worker(t,e)}async function ze(i,e){let t=e;ve(e)&&(t=await He(e)),await i.addModule(t)}function Ge(i,e,t){return(t-1-i+e)%t}function $e({uint8View:i,dataView:e,bufferStart:t,bufferSize:s,head:r,payload:n,sequence:o,messageMagic:a,headerSize:c,sourceId:u=0,headerScratch:f=null,headerScratchView:l=null}){let d=n.length,p=c+d+3&-4,E=s-r;if(p>E){let g=f||new Uint8Array(c),y=l||new DataView(g.buffer);y.setUint32(0,a,!0),y.setUint32(4,p,!0),y.setUint32(8,o,!0),y.setUint32(12,u,!0);let _=t+r,h=t;if(E>=c){i.set(g,_);let T=E-c;T>0&&i.set(n.subarray(0,T),_+c),i.set(n.subarray(T),h)}else{i.set(g.subarray(0,E),_),i.set(g.subarray(E),h);let T=c-E;i.set(n,h+T)}}else{let g=t+r;e.setUint32(g,a,!0),e.setUint32(g+4,p,!0),e.setUint32(g+8,o,!0),e.setUint32(g+12,u,!0),i.set(n,g+c)}return(r+p)%s}function Ft(i,e,t=0,s=!1){for(let r=0;r<=t;r++)if(Atomics.compareExchange(i,e,0,1)===0)return!0;if(s){for(let n=0;n<100;n++)if(Atomics.wait(i,e,1,100),Atomics.compareExchange(i,e,0,1)===0)return!0;return console.error("[RingBuffer] Lock acquisition timeout after 10s - possible deadlock"),!1}return!1}function Nt(i,e){Atomics.store(i,e,0),Atomics.notify(i,e,1)}function We({atomicView:i,dataView:e,uint8View:t,bufferConstants:s,ringBufferBase:r,controlIndices:n,oscMessage:o,sourceId:a=0,maxSpins:c=0,useWait:u=!1}){let f=o.length,l=s.MESSAGE_HEADER_SIZE+f;if(l>s.IN_BUFFER_SIZE-s.MESSAGE_HEADER_SIZE||!Ft(i,n.IN_WRITE_LOCK,c,u))return!1;try{let d=Atomics.load(i,n.IN_HEAD),m=Atomics.load(i,n.IN_TAIL),p=l+3&-4;if(Ge(d,m,s.IN_BUFFER_SIZE)<p)return!1;let g=Atomics.add(i,n.IN_SEQUENCE,1),y=$e({uint8View:t,dataView:e,bufferStart:r+s.IN_BUFFER_START,bufferSize:s.IN_BUFFER_SIZE,head:d,payload:o,sequence:g,messageMagic:s.MESSAGE_MAGIC,headerSize:s.MESSAGE_HEADER_SIZE,sourceId:a});return Atomics.load(i,n.IN_HEAD),Atomics.store(i,n.IN_HEAD,y),Atomics.notify(i,n.IN_HEAD,1),!0}finally{Nt(i,n.IN_WRITE_LOCK)}}function j(i,e){let t=i+e;return{IN_HEAD:(t+0)/4,IN_TAIL:(t+4)/4,IN_SEQUENCE:(t+24)/4,IN_WRITE_LOCK:(t+40)/4,IN_LOG_TAIL:(t+44)/4}}function kt(i){return i.length>=8&&i[0]===35&&i[1]===98&&i[2]===117&&i[3]===110&&i[4]===100&&i[5]===108&&i[6]===101&&i[7]===0}function me(i){if(i.length<16)return null;let e=new DataView(i.buffer,i.byteOffset,i.byteLength);return{ntpSeconds:e.getUint32(8,!1),ntpFraction:e.getUint32(12,!1)}}function L(){return(performance.timeOrigin+performance.now())/1e3+2208988800}function Ye(i,e={}){let{getCurrentNTP:t=L,bypassLookaheadS:s=.5}=e;if(!kt(i))return"nonBundle";let r=me(i);if(!r)return"nonBundle";let{ntpSeconds:n,ntpFraction:o}=r;if(n===0&&o<=1)return"immediate";let a=t();if(a===null||a===0)return"immediate";let u=n+o/4294967296-a;return u<0?"late":u<s?"nearFuture":"farFuture"}function Q(i){return i!=="farFuture"}var B=class i{#t;#e;#n;#i;#f;#s;#h;#o;#c;#a;#u={messagesSent:0,bytesSent:0,nonBundle:0,immediate:0,nearFuture:0,late:0,bypassed:0};constructor(e,t){if(this.#t=e,this.#f=t.preschedulerPort||null,this.#h=t.bypassLookaheadS??.5,this.#o=t.sourceId??0,this.#c=t.blocking??this.#o!==0,this.#a=t.getCurrentNTP??L,e==="postMessage")this.#e=t.port;else if(this.#n={sharedBuffer:t.sharedBuffer,ringBufferBase:t.ringBufferBase,bufferConstants:t.bufferConstants,controlIndices:t.controlIndices},this.#p(),t.sharedBuffer&&t.bufferConstants){let s=t.ringBufferBase+t.bufferConstants.METRICS_START;this.#s=new Int32Array(t.sharedBuffer,s,t.bufferConstants.METRICS_SIZE/4)}}#p(){let e=this.#n.sharedBuffer;this.#i={atomicView:new Int32Array(e),dataView:new DataView(e),uint8View:new Uint8Array(e)}}classify(e){return Ye(e,{getCurrentNTP:this.#a,bypassLookaheadS:this.#h})}#m(e,t=null){if(this.#t==="sab"&&this.#s){if(Atomics.add(this.#s,24,1),Atomics.add(this.#s,25,e),t){let r={nonBundle:38,immediate:39,nearFuture:40,late:41}[t];r!==void 0&&(Atomics.add(this.#s,r,1),Atomics.add(this.#s,22,1))}}else this.#u.messagesSent++,this.#u.bytesSent+=e,t&&t in this.#u&&(this.#u[t]++,this.#u.bypassed++)}getAndResetMetrics(){let e={...this.#u};return this.#u={messagesSent:0,bytesSent:0,nonBundle:0,immediate:0,nearFuture:0,late:0,bypassed:0},e}getMetrics(){return this.#t==="sab"&&this.#s?{messagesSent:Atomics.load(this.#s,24),bytesSent:Atomics.load(this.#s,25),nonBundle:Atomics.load(this.#s,38),immediate:Atomics.load(this.#s,39),nearFuture:Atomics.load(this.#s,40),late:Atomics.load(this.#s,41),bypassed:Atomics.load(this.#s,22)}:{...this.#u}}#y(e,t=null,s=!0){if(this.#t==="postMessage")return this.#e?(this.#e.postMessage({type:"osc",oscData:e,bypassCategory:t,sourceId:this.#o}),!0):!1;{let r=this.#c,n=We({atomicView:this.#i.atomicView,dataView:this.#i.dataView,uint8View:this.#i.uint8View,bufferConstants:this.#n.bufferConstants,ringBufferBase:this.#n.ringBufferBase,controlIndices:this.#n.controlIndices,oscMessage:e,sourceId:this.#o,maxSpins:r?10:0,useWait:r});return!n&&!r&&s&&this.#f?(this.#s&&Atomics.add(this.#s,45,1),this.#f.postMessage({type:"directDispatch",oscData:e,sourceId:this.#o}),!0):n}}#d(e){return this.#f?(this.#f.postMessage({type:"osc",oscData:e,sourceId:this.#o}),!0):(console.error("[OscChannel] No prescheduler port, sending direct"),this.#y(e))}send(e){let t=this.classify(e);if(Q(t)){let s=this.#y(e,t);return s&&this.#m(e.length,t),s}else{let s=this.#d(e);return s&&this.#m(e.length,null),s}}sendDirect(e){return this.#y(e)}sendToPrescheduler(e){return this.#d(e)}set getCurrentNTP(e){this.#a=e}get mode(){return this.#t}get transferable(){let e={mode:this.#t,preschedulerPort:this.#f,bypassLookaheadS:this.#h,sourceId:this.#o,blocking:this.#c};return this.#t==="postMessage"?{...e,port:this.#e}:{...e,sharedBuffer:this.#n.sharedBuffer,ringBufferBase:this.#n.ringBufferBase,bufferConstants:this.#n.bufferConstants,controlIndices:this.#n.controlIndices}}get transferList(){let e=[];return this.#t==="postMessage"&&this.#e&&e.push(this.#e),this.#f&&e.push(this.#f),e}close(){this.#t==="postMessage"&&this.#e&&(this.#e.close(),this.#e=null),this.#f&&(this.#f.close(),this.#f=null)}static createPostMessage(e){return e instanceof MessagePort?new i("postMessage",{port:e}):new i("postMessage",e)}static createSAB(e){let t=e.controlIndices;return t||(t=j(e.ringBufferBase,e.bufferConstants.CONTROL_START)),new i("sab",{sharedBuffer:e.sharedBuffer,ringBufferBase:e.ringBufferBase,bufferConstants:e.bufferConstants,controlIndices:t,preschedulerPort:e.preschedulerPort,bypassLookaheadS:e.bypassLookaheadS,sourceId:e.sourceId,blocking:e.blocking})}static fromTransferable(e){return e.mode==="postMessage"?new i("postMessage",{port:e.port,preschedulerPort:e.preschedulerPort,bypassLookaheadS:e.bypassLookaheadS,sourceId:e.sourceId,blocking:e.blocking}):new i("sab",{sharedBuffer:e.sharedBuffer,ringBufferBase:e.ringBufferBase,bufferConstants:e.bufferConstants,controlIndices:e.controlIndices,preschedulerPort:e.preschedulerPort,bypassLookaheadS:e.bypassLookaheadS,sourceId:e.sourceId,blocking:e.blocking})}};var z=class extends U{#t;#e;#n;#i;#f;#s;#h;#o;#c;#a;#u;#p;#m;#y;#d;#S;#b=1;#r=!1;#l;#g=0;#E=0;#T=0;#w=null;constructor(e){if(super({...e,mode:"sab"}),this.#t=e.sharedBuffer,this.#e=e.ringBufferBase,this.#n=e.bufferConstants,this.#p=e.workerBaseURL,this.#l=e.preschedulerCapacity||65536,!(this.#t instanceof SharedArrayBuffer))throw new Error("SABTransport requires a SharedArrayBuffer");this.#M()}async initialize(){if(this.#r)return;let[e,t,s,r]=await Promise.all([R(this.#p+"osc_out_prescheduler_worker.js",{type:"module"}),R(this.#p+"osc_in_worker.js",{type:"module"}),R(this.#p+"debug_worker.js",{type:"module"}),R(this.#p+"osc_out_log_sab_worker.js",{type:"module"})]);this.#o=e,this.#c=t,this.#a=s,this.#u=r,this.#B(),await Promise.all([this.#A(this.#o,"OSC OUT",{maxPendingMessages:this.#l,bypassLookaheadS:this._config.bypassLookaheadS}),this.#A(this.#c,"OSC IN"),this.#A(this.#a,"DEBUG"),this.#A(this.#u,"OSC OUT LOG")]),this.#c.postMessage({type:"start"}),this.#a.postMessage({type:"start"}),this.#u.postMessage({type:"start"}),this.#r=!0}send(e,t){return!this.#r||this._disposed?!1:(this.#o.postMessage({type:"send",oscData:e,sessionId:0,runTag:"",audioTimeS:null,currentTimeS:null}),this.#g++,this.#T+=e.length,!0)}sendWithOptions(e,t={}){if(!this.#r||this._disposed)return!1;let{sessionId:s=0,runTag:r="",audioTimeS:n=null,currentTimeS:o=null}=t;return this.#o.postMessage({type:"send",oscData:e,sessionId:s,runTag:r,audioTimeS:n,currentTimeS:o}),this.#g++,this.#T+=e.length,!0}sendImmediate(e){return!this.#r||this._disposed?!1:(this.#o.postMessage({type:"sendImmediate",oscData:e}),this.#g++,this.#T+=e.length,!0)}createOscChannel(e={}){if(!this.#r)throw new Error("Transport not initialized");let t=e.sourceId??this.#b++,s=new MessageChannel;return this.#o.postMessage({type:"addOscSource"},[s.port1]),B.createSAB({sharedBuffer:this.#t,ringBufferBase:this.#e,bufferConstants:this.#n,controlIndices:this.#h,preschedulerPort:s.port2,bypassLookaheadS:this._config.bypassLookaheadS,sourceId:t,blocking:e.blocking})}cancelSessionTag(e,t){this.#r&&this.#o.postMessage({type:"cancelSessionTag",sessionId:e,runTag:t})}cancelSession(e){this.#r&&this.#o.postMessage({type:"cancelSession",sessionId:e})}cancelTag(e){this.#r&&this.#o.postMessage({type:"cancelTag",runTag:e})}cancelAll(){this.#r&&this.#o.postMessage({type:"cancelAll"})}cancelAllWithAck(){return this.#r?new Promise(e=>{let t=s=>{s.data.type==="cancelAllAck"&&(this.#o.removeEventListener("message",t),e())};this.#o.addEventListener("message",t),this.#o.postMessage({type:"cancelAll",ack:!0})}):Promise.resolve()}onReply(e){this.#m=e}onDebug(e){this.#y=e}onError(e){this.#d=e}onOscLog(e){this.#S=e}handleOscLog(e){this.#S&&this.#S(e)}getMetrics(){return{oscOutMessagesSent:this.#g,oscOutMessagesDropped:this.#E,oscOutBytesSent:this.#T}}get ready(){return this.#r&&!this._disposed}dispose(){this._disposed||(this.#o&&(this.#o.postMessage({type:"stop"}),this.#o.terminate(),this.#o=null),this.#c&&(this.#c.postMessage({type:"stop"}),this.#c.terminate(),this.#c=null),this.#a&&(this.#a.postMessage({type:"stop"}),this.#a.terminate(),this.#a=null),this.#u&&(this.#u.postMessage({type:"stop"}),this.#u.terminate(),this.#u=null),this.#r=!1,super.dispose())}#M(){this.#i=new Int32Array(this.#t),this.#f=new DataView(this.#t),this.#s=new Uint8Array(this.#t),this.#h=j(this.#e,this.#n.CONTROL_START)}#A(e,t,s={}){return new Promise((r,n)=>{let o=setTimeout(()=>{n(new Error(`${t} worker initialization timeout`))},5e3),a=c=>{c.data.type==="initialized"&&(clearTimeout(o),e.removeEventListener("message",a),r())};e.addEventListener("message",a),e.postMessage({type:"init",sharedBuffer:this.#t,ringBufferBase:this.#e,bufferConstants:this.#n,...s})})}#B(){this.#c.onmessage=e=>{let t=e.data;t.type==="messages"&&this.#m?t.messages.forEach(s=>{s.oscData&&this.#m(s.oscData,s.sequence)}):t.type==="error"&&(console.error("[SABTransport] OSC IN error:",t.error),this.#d&&this.#d(t.error,"oscIn"))},this.#a.onmessage=e=>{let t=e.data;t.type==="debug"&&this.#y?t.messages.forEach(s=>{this.#y(s)}):t.type==="error"&&(console.error("[SABTransport] DEBUG error:",t.error),this.#d&&this.#d(t.error,"debug"))},this.#o.onmessage=e=>{let t=e.data;t.type==="preschedulerMetrics"?this.#w=t.metrics:t.type==="error"&&(console.error("[SABTransport] OSC OUT error:",t.error),this.#E++,this.#d&&this.#d(t.error,"oscOut"))},this.#u.onmessage=e=>{let t=e.data;t.type==="oscLog"&&this.#S?this.#S(t.entries):t.type==="error"&&(console.error("[SABTransport] OSC OUT LOG error:",t.error),this.#d&&this.#d(t.error,"oscOutLog"))}}getPreschedulerMetrics(){return this.#w}};var G=class extends U{#t;#e;#n;#i;#f;#s;#h;#o=1;#c=null;#a=!1;#u;#p;#m=null;#y=0;#d=0;#S=0;#b=0;#r=0;#l=-1;#g=0;#E=0;#T;#w;constructor(e){super({...e,mode:"postMessage"}),this.#n=e.workerBaseURL,this.#u=e.preschedulerCapacity||65536,this.#p=e.snapshotIntervalMs,this.#T=e.getAudioContextTime,this.#w=e.getNTPStartTime}async initialize(e){if(this.#a)return;if(!e)throw new Error("PostMessageTransport requires workletPort");this.#t=e,this.#t.onmessage=s=>{this.#A(s.data)};let t=new MessageChannel;this.#t.postMessage({type:"addOscPort"},[t.port1]),this.#e=await R(this.#n+"osc_out_prescheduler_worker.js",{type:"module"}),this.#e.onmessage=s=>{this.#B(s.data)},await this.#M(t.port2),this.#a=!0}setBufferConstants(e){this.#m=e}send(e,t){return!this.#a||this._disposed?!1:(this.#e.postMessage({type:"send",oscData:e,sessionId:0,runTag:"",audioTimeS:null,currentTimeS:null}),this.#y++,this.#S+=e.length,!0)}sendWithOptions(e,t={}){if(!this.#a||this._disposed)return!1;let{sessionId:s=0,runTag:r="",audioTimeS:n=null,currentTimeS:o=null}=t;return this.#e.postMessage({type:"send",oscData:e,sessionId:s,runTag:r,audioTimeS:n,currentTimeS:o}),this.#y++,this.#S+=e.length,!0}sendImmediate(e,t){return!this.#a||this._disposed?!1:(this.#t.postMessage({type:"osc",oscData:e,bypassCategory:t}),this.#y++,this.#S+=e.length,!0)}createOscChannel(e={}){if(!this.#a)throw new Error("Transport not initialized");let t=e.sourceId??this.#o++,s=new MessageChannel;this.#t.postMessage({type:"addOscPort",sourceId:t},[s.port1]);let r=new MessageChannel;return this.#e.postMessage({type:"addOscSource"},[r.port1]),B.createPostMessage({port:s.port2,preschedulerPort:r.port2,bypassLookaheadS:this._config.bypassLookaheadS,sourceId:t,blocking:e.blocking})}cancelSessionTag(e,t){this.#a&&this.#e.postMessage({type:"cancelSessionTag",sessionId:e,runTag:t})}cancelSession(e){this.#a&&this.#e.postMessage({type:"cancelSession",sessionId:e})}cancelTag(e){this.#a&&this.#e.postMessage({type:"cancelTag",runTag:e})}cancelAll(){this.#a&&this.#e.postMessage({type:"cancelAll"})}cancelAllWithAck(){return this.#a?new Promise(e=>{let t=s=>{s.data.type==="cancelAllAck"&&(this.#e.removeEventListener("message",t),e())};this.#e.addEventListener("message",t),this.#e.postMessage({type:"cancelAll",ack:!0})}):Promise.resolve()}onReply(e){this.#i=e}onDebug(e){this.#f=e}onError(e){this.#s=e}onOscLog(e){this.#h=e}handleDebugRaw(e){if(e.messages&&e.count>0&&e.buffer){let t=new TextDecoder("utf-8"),s=new Uint8Array(e.buffer);for(let r=0;r<e.count;r++){let n=e.messages[r];try{let o=s.subarray(n.offset,n.offset+n.length),a=t.decode(o);a.endsWith(`
|
|
2
|
-
`)&&(a=a.slice(0,-1)),this.#g++,this.#E+=n.length,this.#f&&this.#f({text:a,timestamp:performance.now(),sequence:n.sequence})}catch(o){console.error("[PostMessageTransport] Failed to decode debug message:",o)}}}}getPreschedulerMetrics(){return this.#c}getMetrics(){return{oscInMessagesReceived:this.#b,oscInBytesReceived:this.#r,oscInMessagesDropped:this.#d,debugMessagesReceived:this.#g,debugBytesReceived:this.#E}}get ready(){return this.#a&&!this._disposed}dispose(){this._disposed||(this.#e&&(this.#e.postMessage({type:"stop"}),this.#e.terminate(),this.#e=null),this.#t=null,this.#a=!1,super.dispose())}#M(e){return new Promise((t,s)=>{let r=setTimeout(()=>{s(new Error("Prescheduler worker initialization timeout"))},5e3),n=o=>{o.data.type==="initialized"&&(clearTimeout(r),this.#e.removeEventListener("message",n),t())};this.#e.addEventListener("message",n),this.#e.postMessage({type:"init",mode:"postMessage",maxPendingMessages:this.#u,snapshotIntervalMs:this.#p,bypassLookaheadS:this._config.bypassLookaheadS,workletPort:e},[e])})}#A(e){switch(e.type){case"oscReplies":if(e.messages&&e.count>0&&e.buffer){let t=new Uint8Array(e.buffer);for(let s=0;s<e.count;s++){let r=e.messages[s],n=t.subarray(r.offset,r.offset+r.length);if(r.sequence!==void 0&&this.#l>=0){let o=this.#l+1&4294967295;if(r.sequence!==o){let a=r.sequence-o+4294967296&4294967295;a<1e3&&(this.#d+=a)}}r.sequence!==void 0&&(this.#l=r.sequence),this.#b++,this.#r+=r.length,this.#i&&this.#i(n,r.sequence)}}break;case"metrics":break;case"bufferLoaded":break;case"debugRawBatch":this.handleDebugRaw(e);break;case"oscLog":if(this.#h&&e.count>0&&e.buffer&&e.entries){let t=new Uint8Array(e.buffer),s=[];for(let r=0;r<e.count;r++){let n=e.entries[r],o=t.subarray(n.offset,n.offset+n.length);s.push({oscData:o,sourceId:n.sourceId,sequence:n.sequence,truncated:n.length<n.originalLength,originalLength:n.originalLength})}this.#h(s)}break;case"error":console.error("[PostMessageTransport] Worklet error:",e.error),this.#d++,this.#s&&this.#s(e.error,"worklet");break;case"debug":break}}#B(e){switch(e.type){case"preschedulerMetrics":this.#c=e.metrics;break;case"error":console.error("[PostMessageTransport] Prescheduler error:",e.error),this.#d++,this.#s&&this.#s(e.error,"oscOut");break}}};function Ve(i,e){if(i==="sab")return new z(e);if(i==="postMessage")return new G(e);throw new Error(`Unknown transport mode: ${i}. Use 'sab' or 'postMessage'`)}var Ht={5120:"i8",5121:"u8",5122:"i16",5123:"u16",5124:"i32",5125:"u32",5126:"f32"};var qe={u8:1,u8c:1,i8:1,u16:2,i16:2,u32:4,i32:4,i64:8,u64:8,f32:4,f64:8};var zt={f32:Float32Array,f64:Float64Array},Gt={i8:Int8Array,i16:Int16Array,i32:Int32Array},$t={u8:Uint8Array,u8c:Uint8ClampedArray,u16:Uint16Array,u32:Uint32Array},Wt={i64:BigInt64Array,u64:BigUint64Array},Yt={...zt,...Gt,...$t},Vt=i=>{let e=Ht[i];return e!==void 0?e:i};function Ze(i,...e){let t=Wt[i];return new(t||Yt[Vt(i)])(...e)}var $=(i,e)=>(e--,i+e&~e);var Ke=i=>typeof i=="number";var X=(i,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(i(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var qt=X(()=>"Assertion failed"),Ee=(typeof process<"u"&&process.env!==void 0?process.env.UMBRELLA_ASSERTS:!import.meta.env||import.meta.env.MODE!=="production"||import.meta.env.UMBRELLA_ASSERTS||import.meta.env.VITE_UMBRELLA_ASSERTS)?(i,e)=>{if(typeof i=="function"&&!i()||!i)throw new qt(typeof e=="function"?e():e)}:()=>{};var Zt=X(()=>"illegal argument(s)"),je=i=>{throw new Zt(i)};var Qe=0,Xe=1,Je=2,et=3,tt=4,I=5,st=6,ye=1,Se=2,rt=7*4,_e=0,be=1,M=2*4,Y=class{buf;start;u8;u32;state;constructor(e={}){if(this.buf=e.buf?e.buf:new ArrayBuffer(e.size||4096),this.start=e.start!=null?$(Math.max(e.start,0),4):0,this.u8=new Uint8Array(this.buf),this.u32=new Uint32Array(this.buf),this.state=new Uint32Array(this.buf,this.start,rt/4),!e.skipInitialization){let t=e.align||8;Ee(t>=8,`invalid alignment: ${t}, must be a pow2 and >= 8`);let s=this.initialTop(t),r=e.end!=null?Math.min(e.end,this.buf.byteLength):this.buf.byteLength;s>=r&&je(`insufficient address range (0x${this.start.toString(16)} - 0x${r.toString(16)})`),this.align=t,this.doCompact=e.compact!==!1,this.doSplit=e.split!==!1,this.minSplit=e.minSplit||16,this.end=r,this.top=s,this._free=0,this._used=0}}stats(){let e=s=>{let r=0,n=0;for(;s;)r++,n+=this.blockSize(s),s=this.blockNext(s);return{count:r,size:n}},t=e(this._free);return{free:t,used:e(this._used),top:this.top,available:this.end-this.top+t.size,total:this.buf.byteLength}}callocAs(e,t,s=0){let r=this.mallocAs(e,t);return r?.fill(s),r}mallocAs(e,t){let s=this.malloc(t*qe[e]);return s?Ze(e,this.buf,s,t):void 0}calloc(e,t=0){let s=this.malloc(e);return s&&this.u8.fill(t,s,s+e),s}malloc(e){if(e<=0)return 0;let t=$(e+M,this.align),s=this.end,r=this.top,n=this._free,o=0;for(;n;){let a=this.blockSize(n),c=n+a>=r;if(c||a>=t)return this.mallocTop(n,o,a,t,c);o=n,n=this.blockNext(n)}return n=r,r=n+t,r<=s?(this.initBlock(n,t,this._used),this._used=n,this.top=r,W(n)):0}mallocTop(e,t,s,r,n){if(n&&e+r>this.end)return 0;if(t?this.unlinkBlock(t,e):this._free=this.blockNext(e),this.setBlockNext(e,this._used),this._used=e,n)this.top=e+this.setBlockSize(e,r);else if(this.doSplit){let o=s-r;o>=this.minSplit&&this.splitBlock(e,r,o)}return W(e)}realloc(e,t){if(t<=0)return 0;let s=Te(e),r=0,n=this._used,o=0;for(;n;){if(n===s){[r,o]=this.reallocBlock(n,t);break}n=this.blockNext(n)}return r&&r!==s&&this.u8.copyWithin(W(r),W(s),o),W(r)}reallocBlock(e,t){let s=this.blockSize(e),r=e+s,n=r>=this.top,o=$(t+M,this.align);if(o<=s){if(this.doSplit){let a=s-o;a>=this.minSplit?this.splitBlock(e,o,a):n&&(this.top=e+o)}else n&&(this.top=e+o);return[e,r]}return n&&e+o<this.end?(this.top=e+this.setBlockSize(e,o),[e,r]):(this.free(e),[Te(this.malloc(t)),r])}reallocArray(e,t){if(e.buffer!==this.buf)return;let s=this.realloc(e.byteOffset,t*e.BYTES_PER_ELEMENT);return s?new e.constructor(this.buf,s,t):void 0}free(e){let t;if(Ke(e))t=e;else{if(e.buffer!==this.buf)return!1;t=e.byteOffset}t=Te(t);let s=this._used,r=0;for(;s;){if(s===t)return r?this.unlinkBlock(r,s):this._used=this.blockNext(s),this.insert(s),this.doCompact&&this.compact(),!0;r=s,s=this.blockNext(s)}return!1}freeAll(){this._free=0,this._used=0,this.top=this.initialTop()}release(){return delete this.u8,delete this.u32,delete this.state,delete this.buf,!0}get align(){return this.state[tt]}set align(e){this.state[tt]=e}get end(){return this.state[et]}set end(e){this.state[et]=e}get top(){return this.state[Je]}set top(e){this.state[Je]=e}get _free(){return this.state[Qe]}set _free(e){this.state[Qe]=e}get _used(){return this.state[Xe]}set _used(e){this.state[Xe]=e}get doCompact(){return!!(this.state[I]&ye)}set doCompact(e){e?this.state[I]|=1<<ye-1:this.state[I]&=~ye}get doSplit(){return!!(this.state[I]&Se)}set doSplit(e){e?this.state[I]|=1<<Se-1:this.state[I]&=~Se}get minSplit(){return this.state[st]}set minSplit(e){Ee(e>M,`illegal min split threshold: ${e}, require at least ${M+1}`),this.state[st]=e}blockSize(e){return this.u32[(e>>2)+_e]}setBlockSize(e,t){return this.u32[(e>>2)+_e]=t,t}blockNext(e){return this.u32[(e>>2)+be]}setBlockNext(e,t){this.u32[(e>>2)+be]=t}initBlock(e,t,s){let r=e>>>2;return this.u32[r+_e]=t,this.u32[r+be]=s,e}unlinkBlock(e,t){this.setBlockNext(e,this.blockNext(t))}splitBlock(e,t,s){this.insert(this.initBlock(e+this.setBlockSize(e,t),s,0)),this.doCompact&&this.compact()}initialTop(e=this.align){return $(this.start+rt+M,e)-M}compact(){let e=this._free,t=0,s=0,r,n=!1;for(;e;){for(r=e,s=this.blockNext(e);s&&r+this.blockSize(r)===s;)r=s,s=this.blockNext(s);if(r!==e){let o=r-e+this.blockSize(r);this.setBlockSize(e,o);let a=this.blockNext(r),c=this.blockNext(e);for(;c&&c!==a;){let u=this.blockNext(c);this.setBlockNext(c,0),c=u}this.setBlockNext(e,a),n=!0}e+this.blockSize(e)>=this.top&&(this.top=e,t?this.unlinkBlock(t,e):this._free=this.blockNext(e)),t=e,e=this.blockNext(e)}return n}insert(e){let t=this._free,s=0;for(;t&&!(e<=t);)s=t,t=this.blockNext(t);s?this.setBlockNext(s,e):this._free=e,this.setBlockNext(e,t)}},W=i=>i>0?i+M:0,Te=i=>i>0?i-M:0;function it(i){if(i.byteLength<12)return!1;let e=new Uint8Array(i,0,12),t=String.fromCharCode(e[0],e[1],e[2],e[3]),s=String.fromCharCode(e[8],e[9],e[10],e[11]);return t==="FORM"&&(s==="AIFF"||s==="AIFC")}function Kt(i){let e=i[0]>>7&1,t=(i[0]&127)<<8|i[1],s=0;for(let n=2;n<10;n++)s=s*256+i[n];if(t===0)return 0;let r=s*Math.pow(2,t-16383-63);return e?-r:r}function Ae(i,e){let t=12;for(;t<i.byteLength-8;){let s=String.fromCharCode(i.getUint8(t),i.getUint8(t+1),i.getUint8(t+2),i.getUint8(t+3)),r=i.getUint32(t+4,!1);if(s===e)return{offset:t+8,size:r};t+=8+r+r%2}return null}function nt(i){let e=new DataView(i),t=String.fromCharCode(e.getUint8(8),e.getUint8(9),e.getUint8(10),e.getUint8(11)),s=Ae(e,"COMM");if(!s)throw new Error("AIFF file missing COMM chunk");let r=e.getUint16(s.offset,!1),n=e.getUint32(s.offset+2,!1),o=e.getUint16(s.offset+6,!1),a=new Uint8Array(i,s.offset+8,10),c=Kt(a);if(t==="AIFC"&&s.size>=22){let h=String.fromCharCode(e.getUint8(s.offset+18),e.getUint8(s.offset+19),e.getUint8(s.offset+20),e.getUint8(s.offset+21));if(h!=="NONE"&&h!=="sowt")throw new Error(`AIFC compression type '${h}' is not supported. Only uncompressed AIFF/AIFC files are supported.`);if(h==="sowt")return jt(i,r,n,o,c)}let u=Ae(e,"SSND");if(!u)throw new Error("AIFF file missing SSND chunk");let f=e.getUint32(u.offset,!1),l=u.offset+8+f,d=o/8,m=n*r*d;if(l+m>i.byteLength)throw new Error("AIFF file truncated: not enough audio data");let p=44,E=new ArrayBuffer(p+m),g=new DataView(E),y=new Uint8Array(E);ot(g,{numChannels:r,sampleRate:Math.round(c),bitsPerSample:o,dataSize:m});let _=new Uint8Array(i,l,m);if(d===1)for(let h=0;h<m;h++)y[p+h]=_[h]+128;else if(d===2)for(let h=0;h<m;h+=2)y[p+h]=_[h+1],y[p+h+1]=_[h];else if(d===3)for(let h=0;h<m;h+=3)y[p+h]=_[h+2],y[p+h+1]=_[h+1],y[p+h+2]=_[h];else if(d===4)for(let h=0;h<m;h+=4)y[p+h]=_[h+3],y[p+h+1]=_[h+2],y[p+h+2]=_[h+1],y[p+h+3]=_[h];else throw new Error(`Unsupported bit depth: ${o}`);return E}function jt(i,e,t,s,r){let n=new DataView(i),o=Ae(n,"SSND");if(!o)throw new Error("AIFF file missing SSND chunk");let a=n.getUint32(o.offset,!1),c=o.offset+8+a,u=s/8,f=t*e*u;if(c+f>i.byteLength)throw new Error("AIFF file truncated: not enough audio data");let l=44,d=new ArrayBuffer(l+f),m=new DataView(d),p=new Uint8Array(d);ot(m,{numChannels:e,sampleRate:Math.round(r),bitsPerSample:s,dataSize:f});let E=new Uint8Array(i,c,f);if(u===1)for(let g=0;g<f;g++)p[l+g]=E[g]+128;else p.set(E,l);return d}function ot(i,{numChannels:e,sampleRate:t,bitsPerSample:s,dataSize:r}){let n=t*e*(s/8),o=e*(s/8);i.setUint8(0,82),i.setUint8(1,73),i.setUint8(2,70),i.setUint8(3,70),i.setUint32(4,36+r,!0),i.setUint8(8,87),i.setUint8(9,65),i.setUint8(10,86),i.setUint8(11,69),i.setUint8(12,102),i.setUint8(13,109),i.setUint8(14,116),i.setUint8(15,32),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,e,!0),i.setUint32(24,t,!0),i.setUint32(28,n,!0),i.setUint16(32,o,!0),i.setUint16(34,s,!0),i.setUint8(36,100),i.setUint8(37,97),i.setUint8(38,116),i.setUint8(39,97),i.setUint32(40,r,!0)}var at=8,J=class{#t;#e;#n;#i;#f;#s;#h;#o;#c;#a;#u;#p;constructor(e){let{mode:t="sab",audioContext:s,sharedBuffer:r,bufferPoolConfig:n,sampleBaseURL:o,maxBuffers:a=1024,assetLoader:c=null,workletPort:u=null}=e;if(this.#t=t,!s)throw new Error("BufferManager requires audioContext");if(t==="sab"){if(!r||!(r instanceof SharedArrayBuffer))throw new Error("BufferManager requires sharedBuffer (SharedArrayBuffer) in SAB mode");if(!n||typeof n!="object")throw new Error("BufferManager requires bufferPoolConfig (object with start, size, align)");if(!Number.isFinite(n.start)||n.start<0)throw new Error("bufferPoolConfig.start must be a non-negative number");if(!Number.isFinite(n.size)||n.size<=0)throw new Error("bufferPoolConfig.size must be a positive number")}if(t==="postMessage"&&(!n||typeof n!="object"))throw new Error("BufferManager requires bufferPoolConfig in postMessage mode");if(!Number.isInteger(a)||a<=0)throw new Error("maxBuffers must be a positive integer");if(this.#i=s,this.#f=r,this.#e=o,this.#n=c,this.#p=u,t==="sab")this.#s=new Y({buf:r,start:n.start,size:n.size,align:at}),this.#h=n.size,this.#o=n.start;else{let d=new ArrayBuffer(n.start+n.size);this.#s=new Y({buf:d,start:n.start,size:n.size,align:at}),this.#h=n.size,this.#o=n.start}this.#c=new Map,this.#a=new Map,this.#u=new Map,this.GUARD_BEFORE=3,this.GUARD_AFTER=1,this.MAX_BUFFERS=a;let f=(n.size/(1024*1024)).toFixed(0),l=(n.start/(1024*1024)).toFixed(0)}async#m(e){return it(e)&&(e=nt(e)),this.#i.decodeAudioData(e)}setWorkletPort(e){if(this.#t==="postMessage"){if(!e)throw new Error("BufferManager.setWorkletPort() requires a valid port");this.#p=e}}#y(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid audio path: must be a non-empty string");if(e.includes(".."))throw new Error(`Invalid audio path: path cannot contain '..' (got: ${e})`);if(e.includes("%2e")||e.includes("%2E"))throw new Error(`Invalid audio path: path cannot contain URL-encoded characters (got: ${e})`);if(e.includes("\\"))throw new Error(`Invalid audio path: use forward slashes only (got: ${e})`);if(e.includes("://")||e.startsWith("/")||e.startsWith("./"))return e;if(!this.#e)throw new Error(`sampleBaseURL not configured. Please set it in SuperSonic constructor options.
|
|
1
|
+
var Pt=Object.defineProperty;var Ft=(i,e)=>{for(var t in e)Pt(i,t,{get:e[t],enumerable:!0})};var C=class i{constructor(e){if(new.target===i)throw new Error("Transport is abstract - use SABTransport or PostMessageTransport");this._config=e,this._disposed=!1}get mode(){return this._config.mode}send(e,t){throw new Error("Abstract method - implement in subclass")}onReply(e){throw new Error("Abstract method - implement in subclass")}onDebug(e){throw new Error("Abstract method - implement in subclass")}onError(e){throw new Error("Abstract method - implement in subclass")}getMetrics(){throw new Error("Abstract method - implement in subclass")}async initialize(){throw new Error("Abstract method - implement in subclass")}createOscChannel(){throw new Error("Abstract method - implement in subclass")}dispose(){this._disposed=!0}get ready(){throw new Error("Abstract method - implement in subclass")}};var de=new Map;function ve(i){try{return new URL(i,window.location.href).origin!==window.location.origin}catch{return!1}}async function He(i){if(de.has(i))return de.get(i);let e=await fetch(i);if(!e.ok)throw new Error(`Failed to fetch ${i}: ${e.status} ${e.statusText}`);let t=await e.text(),s=new Blob([t],{type:"application/javascript"}),r=URL.createObjectURL(s);return de.set(i,r),r}async function O(i,e={}){let t=i;return ve(i)&&(t=await He(i)),new Worker(t,e)}async function ze(i,e){let t=e;ve(e)&&(t=await He(e)),await i.addModule(t)}function Ge(i,e,t){return(t-1-i+e)%t}function Ye({uint8View:i,dataView:e,bufferStart:t,bufferSize:s,head:r,payload:n,sequence:o,messageMagic:a,headerSize:c,sourceId:l=0,headerScratch:f=null,headerScratchView:u=null}){let d=n.length,p=c+d+3&-4,E=s-r;if(p>E){let y=f||new Uint8Array(c),S=u||new DataView(y.buffer);S.setUint32(0,a,!0),S.setUint32(4,p,!0),S.setUint32(8,o,!0),S.setUint32(12,l,!0);let _=t+r,h=t;if(E>=c){i.set(y,_);let T=E-c;T>0&&i.set(n.subarray(0,T),_+c),i.set(n.subarray(T),h)}else{i.set(y.subarray(0,E),_),i.set(y.subarray(E),h);let T=c-E;i.set(n,h+T)}}else{let y=t+r;e.setUint32(y,a,!0),e.setUint32(y+4,p,!0),e.setUint32(y+8,o,!0),e.setUint32(y+12,l,!0),i.set(n,y+c)}return(r+p)%s}function kt(i,e,t=0,s=!1){for(let r=0;r<=t;r++)if(Atomics.compareExchange(i,e,0,1)===0)return!0;if(s){for(let n=0;n<100;n++)if(Atomics.wait(i,e,1,100),Atomics.compareExchange(i,e,0,1)===0)return!0;return console.error("[RingBuffer] Lock acquisition timeout after 10s - possible deadlock"),!1}return!1}function xt(i,e){Atomics.store(i,e,0),Atomics.notify(i,e,1)}function $e({atomicView:i,dataView:e,uint8View:t,bufferConstants:s,ringBufferBase:r,controlIndices:n,oscMessage:o,sourceId:a=0,maxSpins:c=0,useWait:l=!1}){let f=o.length,u=s.MESSAGE_HEADER_SIZE+f;if(u>s.IN_BUFFER_SIZE-s.MESSAGE_HEADER_SIZE||!kt(i,n.IN_WRITE_LOCK,c,l))return!1;try{let d=Atomics.load(i,n.IN_HEAD),m=Atomics.load(i,n.IN_TAIL),p=u+3&-4;if(Ge(d,m,s.IN_BUFFER_SIZE)<p)return!1;let y=Atomics.add(i,n.IN_SEQUENCE,1),S=Ye({uint8View:t,dataView:e,bufferStart:r+s.IN_BUFFER_START,bufferSize:s.IN_BUFFER_SIZE,head:d,payload:o,sequence:y,messageMagic:s.MESSAGE_MAGIC,headerSize:s.MESSAGE_HEADER_SIZE,sourceId:a});return Atomics.load(i,n.IN_HEAD),Atomics.store(i,n.IN_HEAD,S),Atomics.notify(i,n.IN_HEAD,1),!0}finally{xt(i,n.IN_WRITE_LOCK)}}function K(i,e){let t=i+e;return{IN_HEAD:(t+0)/4,IN_TAIL:(t+4)/4,IN_SEQUENCE:(t+24)/4,IN_WRITE_LOCK:(t+40)/4,IN_LOG_TAIL:(t+44)/4}}function Nt(i){return i.length>=8&&i[0]===35&&i[1]===98&&i[2]===117&&i[3]===110&&i[4]===100&&i[5]===108&&i[6]===101&&i[7]===0}function me(i){if(i.length<16)return null;let e=new DataView(i.buffer,i.byteOffset,i.byteLength);return{ntpSeconds:e.getUint32(8,!1),ntpFraction:e.getUint32(12,!1)}}function H(){return(performance.timeOrigin+performance.now())/1e3+2208988800}function We(i,e={}){let{getCurrentNTP:t=H,bypassLookaheadS:s=.5}=e;if(!Nt(i))return"nonBundle";let r=me(i);if(!r)return"nonBundle";let{ntpSeconds:n,ntpFraction:o}=r;if(n===0&&o<=1)return"immediate";let a=t();if(a===null||a===0)return"immediate";let l=n+o/4294967296-a;return l<0?"late":l<s?"nearFuture":"farFuture"}function Q(i){return i!=="farFuture"}var w=class i{#r;#e;#t;#h;#n;#s;#c;#a;#o;#l;#u={messagesSent:0,bytesSent:0,nonBundle:0,immediate:0,nearFuture:0,late:0,bypassed:0};constructor(e,t){if(this.#r=e,this.#n=t.preschedulerPort||null,this.#c=t.bypassLookaheadS??.5,this.#a=t.sourceId??0,this.#o=t.blocking??this.#a!==0,this.#l=t.getCurrentNTP??H,e==="postMessage")this.#e=t.port;else if(this.#t={sharedBuffer:t.sharedBuffer,ringBufferBase:t.ringBufferBase,bufferConstants:t.bufferConstants,controlIndices:t.controlIndices},this.#p(),t.sharedBuffer&&t.bufferConstants){let s=t.ringBufferBase+t.bufferConstants.METRICS_START;this.#s=new Int32Array(t.sharedBuffer,s,t.bufferConstants.METRICS_SIZE/4)}}#p(){let e=this.#t.sharedBuffer;this.#h={atomicView:new Int32Array(e),dataView:new DataView(e),uint8View:new Uint8Array(e)}}classify(e){return We(e,{getCurrentNTP:this.#l,bypassLookaheadS:this.#c})}#_(e,t=null){if(this.#r==="sab"&&this.#s){if(Atomics.add(this.#s,24,1),Atomics.add(this.#s,25,e),t){let r={nonBundle:38,immediate:39,nearFuture:40,late:41}[t];r!==void 0&&(Atomics.add(this.#s,r,1),Atomics.add(this.#s,22,1))}}else this.#u.messagesSent++,this.#u.bytesSent+=e,t&&t in this.#u&&(this.#u[t]++,this.#u.bypassed++)}getAndResetMetrics(){let e={...this.#u};return this.#u={messagesSent:0,bytesSent:0,nonBundle:0,immediate:0,nearFuture:0,late:0,bypassed:0},e}getMetrics(){return this.#r==="sab"&&this.#s?{messagesSent:Atomics.load(this.#s,24),bytesSent:Atomics.load(this.#s,25),nonBundle:Atomics.load(this.#s,38),immediate:Atomics.load(this.#s,39),nearFuture:Atomics.load(this.#s,40),late:Atomics.load(this.#s,41),bypassed:Atomics.load(this.#s,22)}:{...this.#u}}#m(e,t=null,s=!0){if(this.#r==="postMessage")return this.#e?(this.#e.postMessage({type:"osc",oscData:e,bypassCategory:t,sourceId:this.#a}),!0):!1;{let r=this.#o,n=$e({atomicView:this.#h.atomicView,dataView:this.#h.dataView,uint8View:this.#h.uint8View,bufferConstants:this.#t.bufferConstants,ringBufferBase:this.#t.ringBufferBase,controlIndices:this.#t.controlIndices,oscMessage:e,sourceId:this.#a,maxSpins:r?10:0,useWait:r});return!n&&!r&&s&&this.#n?(this.#s&&Atomics.add(this.#s,45,1),this.#n.postMessage({type:"directDispatch",oscData:e,sourceId:this.#a}),!0):n}}#d(e){return this.#n?(this.#n.postMessage({type:"osc",oscData:e,sourceId:this.#a}),!0):(console.error("[OscChannel] No prescheduler port, sending direct"),this.#m(e))}send(e){let t=this.classify(e);if(Q(t)){let s=this.#m(e,t);return s&&this.#_(e.length,t),s}else{let s=this.#d(e);return s&&this.#_(e.length,null),s}}sendDirect(e){return this.#m(e)}sendToPrescheduler(e){return this.#d(e)}set getCurrentNTP(e){this.#l=e}get mode(){return this.#r}get transferable(){let e={mode:this.#r,preschedulerPort:this.#n,bypassLookaheadS:this.#c,sourceId:this.#a,blocking:this.#o};return this.#r==="postMessage"?{...e,port:this.#e}:{...e,sharedBuffer:this.#t.sharedBuffer,ringBufferBase:this.#t.ringBufferBase,bufferConstants:this.#t.bufferConstants,controlIndices:this.#t.controlIndices}}get transferList(){let e=[];return this.#r==="postMessage"&&this.#e&&e.push(this.#e),this.#n&&e.push(this.#n),e}close(){this.#r==="postMessage"&&this.#e&&(this.#e.close(),this.#e=null),this.#n&&(this.#n.close(),this.#n=null)}static createPostMessage(e){return e instanceof MessagePort?new i("postMessage",{port:e}):new i("postMessage",e)}static createSAB(e){let t=e.controlIndices;return t||(t=K(e.ringBufferBase,e.bufferConstants.CONTROL_START)),new i("sab",{sharedBuffer:e.sharedBuffer,ringBufferBase:e.ringBufferBase,bufferConstants:e.bufferConstants,controlIndices:t,preschedulerPort:e.preschedulerPort,bypassLookaheadS:e.bypassLookaheadS,sourceId:e.sourceId,blocking:e.blocking})}static fromTransferable(e){return e.mode==="postMessage"?new i("postMessage",{port:e.port,preschedulerPort:e.preschedulerPort,bypassLookaheadS:e.bypassLookaheadS,sourceId:e.sourceId,blocking:e.blocking}):new i("sab",{sharedBuffer:e.sharedBuffer,ringBufferBase:e.ringBufferBase,bufferConstants:e.bufferConstants,controlIndices:e.controlIndices,preschedulerPort:e.preschedulerPort,bypassLookaheadS:e.bypassLookaheadS,sourceId:e.sourceId,blocking:e.blocking})}};var z=class extends C{#r;#e;#t;#h;#n;#s;#c;#a;#o;#l;#u;#p;#_;#m;#d;#E;#b=1;#g=!1;#i;#f=0;#y=0;#S=0;#A=null;constructor(e){if(super({...e,mode:"sab"}),this.#r=e.sharedBuffer,this.#e=e.ringBufferBase,this.#t=e.bufferConstants,this.#p=e.workerBaseURL,this.#i=e.preschedulerCapacity||65536,!(this.#r instanceof SharedArrayBuffer))throw new Error("SABTransport requires a SharedArrayBuffer");this.#w()}async initialize(){if(this.#g)return;let[e,t,s,r]=await Promise.all([O(this.#p+"osc_out_prescheduler_worker.js",{type:"module"}),O(this.#p+"osc_in_worker.js",{type:"module"}),O(this.#p+"debug_worker.js",{type:"module"}),O(this.#p+"osc_out_log_sab_worker.js",{type:"module"})]);this.#a=e,this.#o=t,this.#l=s,this.#u=r,this.#B(),await Promise.all([this.#M(this.#a,"OSC OUT",{maxPendingMessages:this.#i,bypassLookaheadS:this._config.bypassLookaheadS}),this.#M(this.#o,"OSC IN"),this.#M(this.#l,"DEBUG"),this.#M(this.#u,"OSC OUT LOG")]),this.#o.postMessage({type:"start"}),this.#l.postMessage({type:"start"}),this.#u.postMessage({type:"start"}),this.#g=!0}send(e,t){return!this.#g||this._disposed?!1:(this.#a.postMessage({type:"send",oscData:e,sessionId:0,runTag:"",audioTimeS:null,currentTimeS:null}),this.#f++,this.#S+=e.length,!0)}sendWithOptions(e,t={}){if(!this.#g||this._disposed)return!1;let{sessionId:s=0,runTag:r="",audioTimeS:n=null,currentTimeS:o=null}=t;return this.#a.postMessage({type:"send",oscData:e,sessionId:s,runTag:r,audioTimeS:n,currentTimeS:o}),this.#f++,this.#S+=e.length,!0}sendImmediate(e){return!this.#g||this._disposed?!1:(this.#a.postMessage({type:"sendImmediate",oscData:e}),this.#f++,this.#S+=e.length,!0)}createOscChannel(e={}){if(!this.#g)throw new Error("Transport not initialized");let t=e.sourceId??this.#b++,s=new MessageChannel;return this.#a.postMessage({type:"addOscSource"},[s.port1]),w.createSAB({sharedBuffer:this.#r,ringBufferBase:this.#e,bufferConstants:this.#t,controlIndices:this.#c,preschedulerPort:s.port2,bypassLookaheadS:this._config.bypassLookaheadS,sourceId:t,blocking:e.blocking})}cancelSessionTag(e,t){this.#g&&this.#a.postMessage({type:"cancelSessionTag",sessionId:e,runTag:t})}cancelSession(e){this.#g&&this.#a.postMessage({type:"cancelSession",sessionId:e})}cancelTag(e){this.#g&&this.#a.postMessage({type:"cancelTag",runTag:e})}cancelAll(){this.#g&&this.#a.postMessage({type:"cancelAll"})}cancelAllWithAck(){return this.#g?new Promise(e=>{let t=s=>{s.data.type==="cancelAllAck"&&(this.#a.removeEventListener("message",t),e())};this.#a.addEventListener("message",t),this.#a.postMessage({type:"cancelAll",ack:!0})}):Promise.resolve()}onReply(e){this.#_=e}onDebug(e){this.#m=e}onError(e){this.#d=e}onOscLog(e){this.#E=e}handleOscLog(e){this.#E&&this.#E(e)}getMetrics(){return{oscOutMessagesSent:this.#f,oscOutMessagesDropped:this.#y,oscOutBytesSent:this.#S}}get ready(){return this.#g&&!this._disposed}dispose(){this._disposed||(this.#a&&(this.#a.postMessage({type:"stop"}),this.#a.terminate(),this.#a=null),this.#o&&(this.#o.postMessage({type:"stop"}),this.#o.terminate(),this.#o=null),this.#l&&(this.#l.postMessage({type:"stop"}),this.#l.terminate(),this.#l=null),this.#u&&(this.#u.postMessage({type:"stop"}),this.#u.terminate(),this.#u=null),this.#g=!1,super.dispose())}#w(){this.#h=new Int32Array(this.#r),this.#n=new DataView(this.#r),this.#s=new Uint8Array(this.#r),this.#c=K(this.#e,this.#t.CONTROL_START)}#M(e,t,s={}){return new Promise((r,n)=>{let o=setTimeout(()=>{n(new Error(`${t} worker initialization timeout`))},5e3),a=c=>{c.data.type==="initialized"&&(clearTimeout(o),e.removeEventListener("message",a),r())};e.addEventListener("message",a),e.postMessage({type:"init",sharedBuffer:this.#r,ringBufferBase:this.#e,bufferConstants:this.#t,...s})})}#B(){this.#o.onmessage=e=>{let t=e.data;t.type==="messages"&&this.#_?t.messages.forEach(s=>{s.oscData&&this.#_(s.oscData,s.sequence)}):t.type==="error"&&(console.error("[SABTransport] OSC IN error:",t.error),this.#d&&this.#d(t.error,"oscIn"))},this.#l.onmessage=e=>{let t=e.data;t.type==="debug"&&this.#m?t.messages.forEach(s=>{this.#m(s)}):t.type==="error"&&(console.error("[SABTransport] DEBUG error:",t.error),this.#d&&this.#d(t.error,"debug"))},this.#a.onmessage=e=>{let t=e.data;t.type==="preschedulerMetrics"?this.#A=t.metrics:t.type==="error"&&(console.error("[SABTransport] OSC OUT error:",t.error),this.#y++,this.#d&&this.#d(t.error,"oscOut"))},this.#u.onmessage=e=>{let t=e.data;t.type==="oscLog"&&this.#E?this.#E(t.entries):t.type==="error"&&(console.error("[SABTransport] OSC OUT LOG error:",t.error),this.#d&&this.#d(t.error,"oscOutLog"))}}getPreschedulerMetrics(){return this.#A}};var G=class extends C{#r;#e;#t;#h;#n;#s;#c;#a=1;#o=null;#l=!1;#u;#p;#_=null;#m=0;#d=0;#E=0;#b=0;#g=0;#i=-1;#f=0;#y=0;#S;#A;constructor(e){super({...e,mode:"postMessage"}),this.#t=e.workerBaseURL,this.#u=e.preschedulerCapacity||65536,this.#p=e.snapshotIntervalMs,this.#S=e.getAudioContextTime,this.#A=e.getNTPStartTime}async initialize(e){if(this.#l)return;if(!e)throw new Error("PostMessageTransport requires workletPort");this.#r=e,this.#r.onmessage=s=>{this.#M(s.data)};let t=new MessageChannel;this.#r.postMessage({type:"addOscPort"},[t.port1]),this.#e=await O(this.#t+"osc_out_prescheduler_worker.js",{type:"module"}),this.#e.onmessage=s=>{this.#B(s.data)},await this.#w(t.port2),this.#l=!0}setBufferConstants(e){this.#_=e}send(e,t){return!this.#l||this._disposed?!1:(this.#e.postMessage({type:"send",oscData:e,sessionId:0,runTag:"",audioTimeS:null,currentTimeS:null}),this.#m++,this.#E+=e.length,!0)}sendWithOptions(e,t={}){if(!this.#l||this._disposed)return!1;let{sessionId:s=0,runTag:r="",audioTimeS:n=null,currentTimeS:o=null}=t;return this.#e.postMessage({type:"send",oscData:e,sessionId:s,runTag:r,audioTimeS:n,currentTimeS:o}),this.#m++,this.#E+=e.length,!0}sendImmediate(e,t){return!this.#l||this._disposed?!1:(this.#r.postMessage({type:"osc",oscData:e,bypassCategory:t}),this.#m++,this.#E+=e.length,!0)}createOscChannel(e={}){if(!this.#l)throw new Error("Transport not initialized");let t=e.sourceId??this.#a++,s=new MessageChannel;this.#r.postMessage({type:"addOscPort",sourceId:t},[s.port1]);let r=new MessageChannel;return this.#e.postMessage({type:"addOscSource"},[r.port1]),w.createPostMessage({port:s.port2,preschedulerPort:r.port2,bypassLookaheadS:this._config.bypassLookaheadS,sourceId:t,blocking:e.blocking})}cancelSessionTag(e,t){this.#l&&this.#e.postMessage({type:"cancelSessionTag",sessionId:e,runTag:t})}cancelSession(e){this.#l&&this.#e.postMessage({type:"cancelSession",sessionId:e})}cancelTag(e){this.#l&&this.#e.postMessage({type:"cancelTag",runTag:e})}cancelAll(){this.#l&&this.#e.postMessage({type:"cancelAll"})}cancelAllWithAck(){return this.#l?new Promise(e=>{let t=s=>{s.data.type==="cancelAllAck"&&(this.#e.removeEventListener("message",t),e())};this.#e.addEventListener("message",t),this.#e.postMessage({type:"cancelAll",ack:!0})}):Promise.resolve()}onReply(e){this.#h=e}onDebug(e){this.#n=e}onError(e){this.#s=e}onOscLog(e){this.#c=e}handleDebugRaw(e){if(e.messages&&e.count>0&&e.buffer){let t=new TextDecoder("utf-8"),s=new Uint8Array(e.buffer);for(let r=0;r<e.count;r++){let n=e.messages[r];try{let o=s.subarray(n.offset,n.offset+n.length),a=t.decode(o);a.endsWith(`
|
|
2
|
+
`)&&(a=a.slice(0,-1)),this.#f++,this.#y+=n.length,this.#n&&this.#n({text:a,timestamp:performance.now(),sequence:n.sequence})}catch(o){console.error("[PostMessageTransport] Failed to decode debug message:",o)}}}}getPreschedulerMetrics(){return this.#o}getMetrics(){return{oscInMessagesReceived:this.#b,oscInBytesReceived:this.#g,oscInMessagesDropped:this.#d,debugMessagesReceived:this.#f,debugBytesReceived:this.#y}}get ready(){return this.#l&&!this._disposed}dispose(){this._disposed||(this.#e&&(this.#e.postMessage({type:"stop"}),this.#e.terminate(),this.#e=null),this.#r=null,this.#l=!1,super.dispose())}#w(e){return new Promise((t,s)=>{let r=setTimeout(()=>{s(new Error("Prescheduler worker initialization timeout"))},5e3),n=o=>{o.data.type==="initialized"&&(clearTimeout(r),this.#e.removeEventListener("message",n),t())};this.#e.addEventListener("message",n),this.#e.postMessage({type:"init",mode:"postMessage",maxPendingMessages:this.#u,snapshotIntervalMs:this.#p,bypassLookaheadS:this._config.bypassLookaheadS,workletPort:e},[e])})}#M(e){switch(e.type){case"oscReplies":if(e.messages&&e.count>0&&e.buffer){let t=new Uint8Array(e.buffer);for(let s=0;s<e.count;s++){let r=e.messages[s],n=t.subarray(r.offset,r.offset+r.length);if(r.sequence!==void 0&&this.#i>=0){let o=this.#i+1&4294967295;if(r.sequence!==o){let a=r.sequence-o+4294967296&4294967295;a<1e3&&(this.#d+=a)}}r.sequence!==void 0&&(this.#i=r.sequence),this.#b++,this.#g+=r.length,this.#h&&this.#h(n,r.sequence)}}break;case"metrics":break;case"bufferLoaded":break;case"debugRawBatch":this.handleDebugRaw(e);break;case"oscLog":if(this.#c&&e.count>0&&e.buffer&&e.entries){let t=new Uint8Array(e.buffer),s=[];for(let r=0;r<e.count;r++){let n=e.entries[r],o=t.subarray(n.offset,n.offset+n.length);s.push({oscData:o,sourceId:n.sourceId,sequence:n.sequence,truncated:n.length<n.originalLength,originalLength:n.originalLength})}this.#c(s)}break;case"error":console.error("[PostMessageTransport] Worklet error:",e.error),this.#d++,this.#s&&this.#s(e.error,"worklet");break;case"debug":break}}#B(e){switch(e.type){case"preschedulerMetrics":this.#o=e.metrics;break;case"error":console.error("[PostMessageTransport] Prescheduler error:",e.error),this.#d++,this.#s&&this.#s(e.error,"oscOut");break}}};function Ve(i,e){if(i==="sab")return new z(e);if(i==="postMessage")return new G(e);throw new Error(`Unknown transport mode: ${i}. Use 'sab' or 'postMessage'`)}var Ht={5120:"i8",5121:"u8",5122:"i16",5123:"u16",5124:"i32",5125:"u32",5126:"f32"};var qe={u8:1,u8c:1,i8:1,u16:2,i16:2,u32:4,i32:4,i64:8,u64:8,f32:4,f64:8};var zt={f32:Float32Array,f64:Float64Array},Gt={i8:Int8Array,i16:Int16Array,i32:Int32Array},Yt={u8:Uint8Array,u8c:Uint8ClampedArray,u16:Uint16Array,u32:Uint32Array},$t={i64:BigInt64Array,u64:BigUint64Array},Wt={...zt,...Gt,...Yt},Vt=i=>{let e=Ht[i];return e!==void 0?e:i};function Ze(i,...e){let t=$t[i];return new(t||Wt[Vt(i)])(...e)}var Y=(i,e)=>(e--,i+e&~e);var Xe=i=>typeof i=="number";var j=(i,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(i(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var qt=j(()=>"Assertion failed"),Ee=(typeof process<"u"&&process.env!==void 0?process.env.UMBRELLA_ASSERTS:!import.meta.env||import.meta.env.MODE!=="production"||import.meta.env.UMBRELLA_ASSERTS||import.meta.env.VITE_UMBRELLA_ASSERTS)?(i,e)=>{if(typeof i=="function"&&!i()||!i)throw new qt(typeof e=="function"?e():e)}:()=>{};var Zt=j(()=>"illegal argument(s)"),Ke=i=>{throw new Zt(i)};var Qe=0,je=1,Je=2,et=3,tt=4,N=5,st=6,Se=1,ge=2,rt=7*4,_e=0,be=1,M=2*4,W=class{buf;start;u8;u32;state;constructor(e={}){if(this.buf=e.buf?e.buf:new ArrayBuffer(e.size||4096),this.start=e.start!=null?Y(Math.max(e.start,0),4):0,this.u8=new Uint8Array(this.buf),this.u32=new Uint32Array(this.buf),this.state=new Uint32Array(this.buf,this.start,rt/4),!e.skipInitialization){let t=e.align||8;Ee(t>=8,`invalid alignment: ${t}, must be a pow2 and >= 8`);let s=this.initialTop(t),r=e.end!=null?Math.min(e.end,this.buf.byteLength):this.buf.byteLength;s>=r&&Ke(`insufficient address range (0x${this.start.toString(16)} - 0x${r.toString(16)})`),this.align=t,this.doCompact=e.compact!==!1,this.doSplit=e.split!==!1,this.minSplit=e.minSplit||16,this.end=r,this.top=s,this._free=0,this._used=0}}stats(){let e=s=>{let r=0,n=0;for(;s;)r++,n+=this.blockSize(s),s=this.blockNext(s);return{count:r,size:n}},t=e(this._free);return{free:t,used:e(this._used),top:this.top,available:this.end-this.top+t.size,total:this.buf.byteLength}}callocAs(e,t,s=0){let r=this.mallocAs(e,t);return r?.fill(s),r}mallocAs(e,t){let s=this.malloc(t*qe[e]);return s?Ze(e,this.buf,s,t):void 0}calloc(e,t=0){let s=this.malloc(e);return s&&this.u8.fill(t,s,s+e),s}malloc(e){if(e<=0)return 0;let t=Y(e+M,this.align),s=this.end,r=this.top,n=this._free,o=0;for(;n;){let a=this.blockSize(n),c=n+a>=r;if(c||a>=t)return this.mallocTop(n,o,a,t,c);o=n,n=this.blockNext(n)}return n=r,r=n+t,r<=s?(this.initBlock(n,t,this._used),this._used=n,this.top=r,$(n)):0}mallocTop(e,t,s,r,n){if(n&&e+r>this.end)return 0;if(t?this.unlinkBlock(t,e):this._free=this.blockNext(e),this.setBlockNext(e,this._used),this._used=e,n)this.top=e+this.setBlockSize(e,r);else if(this.doSplit){let o=s-r;o>=this.minSplit&&this.splitBlock(e,r,o)}return $(e)}realloc(e,t){if(t<=0)return 0;let s=Te(e),r=0,n=this._used,o=0;for(;n;){if(n===s){[r,o]=this.reallocBlock(n,t);break}n=this.blockNext(n)}return r&&r!==s&&this.u8.copyWithin($(r),$(s),o),$(r)}reallocBlock(e,t){let s=this.blockSize(e),r=e+s,n=r>=this.top,o=Y(t+M,this.align);if(o<=s){if(this.doSplit){let a=s-o;a>=this.minSplit?this.splitBlock(e,o,a):n&&(this.top=e+o)}else n&&(this.top=e+o);return[e,r]}return n&&e+o<this.end?(this.top=e+this.setBlockSize(e,o),[e,r]):(this.free(e),[Te(this.malloc(t)),r])}reallocArray(e,t){if(e.buffer!==this.buf)return;let s=this.realloc(e.byteOffset,t*e.BYTES_PER_ELEMENT);return s?new e.constructor(this.buf,s,t):void 0}free(e){let t;if(Xe(e))t=e;else{if(e.buffer!==this.buf)return!1;t=e.byteOffset}t=Te(t);let s=this._used,r=0;for(;s;){if(s===t)return r?this.unlinkBlock(r,s):this._used=this.blockNext(s),this.insert(s),this.doCompact&&this.compact(),!0;r=s,s=this.blockNext(s)}return!1}freeAll(){this._free=0,this._used=0,this.top=this.initialTop()}release(){return delete this.u8,delete this.u32,delete this.state,delete this.buf,!0}get align(){return this.state[tt]}set align(e){this.state[tt]=e}get end(){return this.state[et]}set end(e){this.state[et]=e}get top(){return this.state[Je]}set top(e){this.state[Je]=e}get _free(){return this.state[Qe]}set _free(e){this.state[Qe]=e}get _used(){return this.state[je]}set _used(e){this.state[je]=e}get doCompact(){return!!(this.state[N]&Se)}set doCompact(e){e?this.state[N]|=1<<Se-1:this.state[N]&=~Se}get doSplit(){return!!(this.state[N]&ge)}set doSplit(e){e?this.state[N]|=1<<ge-1:this.state[N]&=~ge}get minSplit(){return this.state[st]}set minSplit(e){Ee(e>M,`illegal min split threshold: ${e}, require at least ${M+1}`),this.state[st]=e}blockSize(e){return this.u32[(e>>2)+_e]}setBlockSize(e,t){return this.u32[(e>>2)+_e]=t,t}blockNext(e){return this.u32[(e>>2)+be]}setBlockNext(e,t){this.u32[(e>>2)+be]=t}initBlock(e,t,s){let r=e>>>2;return this.u32[r+_e]=t,this.u32[r+be]=s,e}unlinkBlock(e,t){this.setBlockNext(e,this.blockNext(t))}splitBlock(e,t,s){this.insert(this.initBlock(e+this.setBlockSize(e,t),s,0)),this.doCompact&&this.compact()}initialTop(e=this.align){return Y(this.start+rt+M,e)-M}compact(){let e=this._free,t=0,s=0,r,n=!1;for(;e;){for(r=e,s=this.blockNext(e);s&&r+this.blockSize(r)===s;)r=s,s=this.blockNext(s);if(r!==e){let o=r-e+this.blockSize(r);this.setBlockSize(e,o);let a=this.blockNext(r),c=this.blockNext(e);for(;c&&c!==a;){let l=this.blockNext(c);this.setBlockNext(c,0),c=l}this.setBlockNext(e,a),n=!0}e+this.blockSize(e)>=this.top&&(this.top=e,t?this.unlinkBlock(t,e):this._free=this.blockNext(e)),t=e,e=this.blockNext(e)}return n}insert(e){let t=this._free,s=0;for(;t&&!(e<=t);)s=t,t=this.blockNext(t);s?this.setBlockNext(s,e):this._free=e,this.setBlockNext(e,t)}},$=i=>i>0?i+M:0,Te=i=>i>0?i-M:0;function it(i){if(i.byteLength<12)return!1;let e=new Uint8Array(i,0,12),t=String.fromCharCode(e[0],e[1],e[2],e[3]),s=String.fromCharCode(e[8],e[9],e[10],e[11]);return t==="FORM"&&(s==="AIFF"||s==="AIFC")}function Xt(i){let e=i[0]>>7&1,t=(i[0]&127)<<8|i[1],s=0;for(let n=2;n<10;n++)s=s*256+i[n];if(t===0)return 0;let r=s*Math.pow(2,t-16383-63);return e?-r:r}function Ae(i,e){let t=12;for(;t<i.byteLength-8;){let s=String.fromCharCode(i.getUint8(t),i.getUint8(t+1),i.getUint8(t+2),i.getUint8(t+3)),r=i.getUint32(t+4,!1);if(s===e)return{offset:t+8,size:r};t+=8+r+r%2}return null}function nt(i){let e=new DataView(i),t=String.fromCharCode(e.getUint8(8),e.getUint8(9),e.getUint8(10),e.getUint8(11)),s=Ae(e,"COMM");if(!s)throw new Error("AIFF file missing COMM chunk");let r=e.getUint16(s.offset,!1),n=e.getUint32(s.offset+2,!1),o=e.getUint16(s.offset+6,!1),a=new Uint8Array(i,s.offset+8,10),c=Xt(a);if(t==="AIFC"&&s.size>=22){let h=String.fromCharCode(e.getUint8(s.offset+18),e.getUint8(s.offset+19),e.getUint8(s.offset+20),e.getUint8(s.offset+21));if(h!=="NONE"&&h!=="sowt")throw new Error(`AIFC compression type '${h}' is not supported. Only uncompressed AIFF/AIFC files are supported.`);if(h==="sowt")return Kt(i,r,n,o,c)}let l=Ae(e,"SSND");if(!l)throw new Error("AIFF file missing SSND chunk");let f=e.getUint32(l.offset,!1),u=l.offset+8+f,d=o/8,m=n*r*d;if(u+m>i.byteLength)throw new Error("AIFF file truncated: not enough audio data");let p=44,E=new ArrayBuffer(p+m),y=new DataView(E),S=new Uint8Array(E);ot(y,{numChannels:r,sampleRate:Math.round(c),bitsPerSample:o,dataSize:m});let _=new Uint8Array(i,u,m);if(d===1)for(let h=0;h<m;h++)S[p+h]=_[h]+128;else if(d===2)for(let h=0;h<m;h+=2)S[p+h]=_[h+1],S[p+h+1]=_[h];else if(d===3)for(let h=0;h<m;h+=3)S[p+h]=_[h+2],S[p+h+1]=_[h+1],S[p+h+2]=_[h];else if(d===4)for(let h=0;h<m;h+=4)S[p+h]=_[h+3],S[p+h+1]=_[h+2],S[p+h+2]=_[h+1],S[p+h+3]=_[h];else throw new Error(`Unsupported bit depth: ${o}`);return E}function Kt(i,e,t,s,r){let n=new DataView(i),o=Ae(n,"SSND");if(!o)throw new Error("AIFF file missing SSND chunk");let a=n.getUint32(o.offset,!1),c=o.offset+8+a,l=s/8,f=t*e*l;if(c+f>i.byteLength)throw new Error("AIFF file truncated: not enough audio data");let u=44,d=new ArrayBuffer(u+f),m=new DataView(d),p=new Uint8Array(d);ot(m,{numChannels:e,sampleRate:Math.round(r),bitsPerSample:s,dataSize:f});let E=new Uint8Array(i,c,f);if(l===1)for(let y=0;y<f;y++)p[u+y]=E[y]+128;else p.set(E,u);return d}function ot(i,{numChannels:e,sampleRate:t,bitsPerSample:s,dataSize:r}){let n=t*e*(s/8),o=e*(s/8);i.setUint8(0,82),i.setUint8(1,73),i.setUint8(2,70),i.setUint8(3,70),i.setUint32(4,36+r,!0),i.setUint8(8,87),i.setUint8(9,65),i.setUint8(10,86),i.setUint8(11,69),i.setUint8(12,102),i.setUint8(13,109),i.setUint8(14,116),i.setUint8(15,32),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,e,!0),i.setUint32(24,t,!0),i.setUint32(28,n,!0),i.setUint16(32,o,!0),i.setUint16(34,s,!0),i.setUint8(36,100),i.setUint8(37,97),i.setUint8(38,116),i.setUint8(39,97),i.setUint32(40,r,!0)}var at=8,J=class{#r;#e;#t;#h;#n;#s;#c;#a;#o;#l;#u;#p;constructor(e){let{mode:t="sab",audioContext:s,sharedBuffer:r,bufferPoolConfig:n,sampleBaseURL:o,maxBuffers:a=1024,assetLoader:c=null,workletPort:l=null}=e;if(this.#r=t,!s)throw new Error("BufferManager requires audioContext");if(t==="sab"){if(!r||!(r instanceof SharedArrayBuffer))throw new Error("BufferManager requires sharedBuffer (SharedArrayBuffer) in SAB mode");if(!n||typeof n!="object")throw new Error("BufferManager requires bufferPoolConfig (object with start, size, align)");if(!Number.isFinite(n.start)||n.start<0)throw new Error("bufferPoolConfig.start must be a non-negative number");if(!Number.isFinite(n.size)||n.size<=0)throw new Error("bufferPoolConfig.size must be a positive number")}if(t==="postMessage"&&(!n||typeof n!="object"))throw new Error("BufferManager requires bufferPoolConfig in postMessage mode");if(!Number.isInteger(a)||a<=0)throw new Error("maxBuffers must be a positive integer");if(this.#h=s,this.#n=r,this.#e=o,this.#t=c,this.#p=l,t==="sab")this.#s=new W({buf:r,start:n.start,size:n.size,align:at}),this.#c=n.size,this.#a=n.start;else{let d=new ArrayBuffer(n.start+n.size);this.#s=new W({buf:d,start:n.start,size:n.size,align:at}),this.#c=n.size,this.#a=n.start}this.#o=new Map,this.#l=new Map,this.#u=new Map,this.GUARD_BEFORE=3,this.GUARD_AFTER=1,this.MAX_BUFFERS=a;let f=(n.size/(1024*1024)).toFixed(0),u=(n.start/(1024*1024)).toFixed(0)}async#_(e){return it(e)&&(e=nt(e)),this.#h.decodeAudioData(e)}setWorkletPort(e){if(this.#r==="postMessage"){if(!e)throw new Error("BufferManager.setWorkletPort() requires a valid port");this.#p=e}}#m(e){if(typeof e!="string"||e.length===0)throw new Error("Invalid audio path: must be a non-empty string");if(e.includes(".."))throw new Error(`Invalid audio path: path cannot contain '..' (got: ${e})`);if(e.includes("%2e")||e.includes("%2E"))throw new Error(`Invalid audio path: path cannot contain URL-encoded characters (got: ${e})`);if(e.includes("\\"))throw new Error(`Invalid audio path: use forward slashes only (got: ${e})`);if(e.includes("://")||e.startsWith("/")||e.startsWith("./"))return e;if(!this.#e)throw new Error(`sampleBaseURL not configured. Please set it in SuperSonic constructor options.
|
|
3
3
|
Example: new SuperSonic({ sampleBaseURL: "./dist/samples/" })
|
|
4
4
|
Or use CDN: new SuperSonic({ sampleBaseURL: "https://unpkg.com/supersonic-scsynth-samples@latest/samples/" })
|
|
5
|
-
Or install: npm install supersonic-scsynth-samples`);return this.#e+e}#d(e){if(!Number.isInteger(e)||e<0||e>=this.MAX_BUFFERS)throw new Error(`Invalid buffer number ${e} (must be 0-${this.MAX_BUFFERS-1})`)}async#S(e,t,s){let r=null,n=null,o=!1,a=await this.#T(e),c=!1;try{await this.#M(e);let{ptr:u,sizeBytes:f,numFrames:l,numChannels:d,sampleRate:m,source:p,...E}=await s();r=u;let{uuid:g,allocationComplete:y}=this.#E(e,t);n=g,this.#w(e,r,f,g,y,{numFrames:l,numChannels:d,sampleRate:m,source:p}),o=!0;let _=this.#A(e,g,y);return a(),c=!0,{ptr:r,uuid:g,allocationComplete:_,numFrames:l,numChannels:d,sampleRate:m,...E}}catch(u){throw o&&n?this.#B(e,n,!1):r&&this.#s.free(r),u}finally{c||a()}}async prepareFromBlob(e){let{bufnum:t,blob:s,startFrame:r=0,numFrames:n=0,channels:o=null}=e;if(this.#d(t),!s||!(s instanceof ArrayBuffer||ArrayBuffer.isView(s)))throw new Error("/b_allocFile requires audio data as ArrayBuffer or typed array");let a=s instanceof ArrayBuffer?s:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);return this.#S(t,3e4,async()=>{let c=await this.#m(a),u=Math.max(0,Math.floor(r||0)),f=c.length-u,l=n&&n>0?Math.min(Math.floor(n),f):f;if(l<=0)throw new Error(`No audio frames available for buffer ${t}`);let d=this.#b(o,c.numberOfChannels),m=d.length,p=l*m+(this.GUARD_BEFORE+this.GUARD_AFTER)*m,E=this.#r(p),g=new Float32Array(p),y=this.GUARD_BEFORE*m;for(let h=0;h<l;h++)for(let T=0;T<m;T++){let A=d[T],w=c.getChannelData(A);g[y+h*m+T]=w[u+h]}await this.#l(E,g);let _=g.length*4;return{ptr:E,sizeBytes:_,numFrames:l,numChannels:m,sampleRate:c.sampleRate}})}async prepareFromFile(e){let{bufnum:t,path:s,startFrame:r=0,numFrames:n=0,channels:o=null}=e;return this.#d(t),this.#S(t,6e4,async()=>{let a=this.#y(s),c=s.split("/").pop(),u=await this.#n.fetch(a,{type:"sample",name:c}),f=await this.#m(u),l=Math.max(0,Math.floor(r||0)),d=f.length-l,m=n&&n>0?Math.min(Math.floor(n),d):d;if(m<=0)throw new Error(`No audio frames available for buffer ${t} from ${s}`);let p=this.#b(o,f.numberOfChannels),E=p.length,g=m*E+(this.GUARD_BEFORE+this.GUARD_AFTER)*E,y=this.#r(g),_=new Float32Array(g),h=this.GUARD_BEFORE*E;for(let A=0;A<m;A++)for(let w=0;w<E;w++){let he=p[w],Lt=f.getChannelData(he);_[h+A*E+w]=Lt[l+A]}await this.#l(y,_);let T=_.length*4;return{ptr:y,sizeBytes:T,numFrames:m,numChannels:E,sampleRate:f.sampleRate,source:{type:"file",path:s,startFrame:r,numFrames:n,channels:o}}})}async prepareEmpty(e){let{bufnum:t,numFrames:s,numChannels:r=1,sampleRate:n=null}=e;if(this.#d(t),!Number.isFinite(s)||s<=0)throw new Error(`/b_alloc requires a positive number of frames (got ${s})`);if(!Number.isFinite(r)||r<=0)throw new Error(`/b_alloc requires a positive channel count (got ${r})`);let o=Math.floor(s),a=Math.floor(r);return this.#S(t,5e3,async()=>{let c=o*a+(this.GUARD_BEFORE+this.GUARD_AFTER)*a,u=this.#r(c),f=new Float32Array(c);await this.#l(u,f);let l=f.length*4;return{ptr:u,sizeBytes:l,numFrames:o,numChannels:a,sampleRate:n||this.#i.sampleRate}})}#b(e,t){return!e||e.length===0?Array.from({length:t},(s,r)=>r):(e.forEach(s=>{if(!Number.isInteger(s)||s<0||s>=t)throw new Error(`Channel ${s} is out of range (file has ${t} channels)`)}),e)}#r(e){let t=e*4,s=this.#s.malloc(t);if(s===0){let r=this.#s.stats(),n=((r.available||0)/(1024*1024)).toFixed(2),o=((r.total||0)/(1024*1024)).toFixed(2),a=(t/(1024*1024)).toFixed(2);throw new Error(`Buffer pool allocation failed: requested ${a}MB, available ${n}MB of ${o}MB total`)}return s}async#l(e,t){if(this.#t==="sab")new Float32Array(this.#f,e,t.length).set(t);else{let s=crypto.randomUUID(),r=new Promise((o,a)=>{let c=setTimeout(()=>{a(new Error("Buffer copy to WASM memory timed out"))},1e4),u=f=>{let l=f.data;l.type==="bufferCopied"&&l.copyId===s&&(this.#p.removeEventListener("message",u),clearTimeout(c),l.success?o():a(new Error(l.error||"Buffer copy failed")))};this.#p.addEventListener("message",u)}),n=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);this.#p.postMessage({type:"copyBufferData",copyId:s,ptr:e,data:n},[n]),await r}}#g(e,t,s){return new Promise((r,n)=>{let o=setTimeout(()=>{this.#a.delete(e),n(new Error(`Buffer ${t} allocation timeout (${s}ms)`))},s);this.#a.set(e,{resolve:r,reject:n,timeout:o})})}#E(e,t){let s=crypto.randomUUID(),r=this.#g(s,e,t);return{uuid:s,allocationComplete:r}}async#T(e){let t=this.#u.get(e)||Promise.resolve(),s,r=new Promise(n=>{s=n});return this.#u.set(e,t.then(()=>r)),await t,()=>{s&&(s(),s=null),this.#u.get(e)===r&&this.#u.delete(e)}}#w(e,t,s,r,n,o={}){let a=this.#c.get(e),c={ptr:t,size:s,numFrames:o.numFrames||0,numChannels:o.numChannels||1,sampleRate:o.sampleRate||48e3,pendingToken:r,pendingPromise:n,previousAllocation:a?{ptr:a.ptr,size:a.size}:null,source:o.source||null};return this.#c.set(e,c),c}async#M(e){let t=this.#c.get(e);if(t&&t.pendingToken&&t.pendingPromise)try{await t.pendingPromise}catch{}}#A(e,t,s){return!s||typeof s.then!="function"?(this.#B(e,t,!0),Promise.resolve()):s.then(r=>(this.#B(e,t,!0),r)).catch(r=>{throw this.#B(e,t,!1),r})}#B(e,t,s){let r=this.#c.get(e);if(!r||r.pendingToken!==t)return;let n=r.previousAllocation;if(s){r.pendingToken=null,r.pendingPromise=null,r.previousAllocation=null,n?.ptr&&this.#s.free(n.ptr);return}r.ptr&&this.#s.free(r.ptr),r.pendingPromise=null,n?.ptr?this.#c.set(e,{ptr:n.ptr,size:n.size,pendingToken:null,previousAllocation:null}):this.#c.delete(e)}handleBufferFreed(e){let t=e[0],s=e[1],r=this.#c.get(t);if(!r){typeof s=="number"&&s!==0&&this.#s.free(s);return}if(typeof s=="number"&&s===r.ptr){this.#s.free(r.ptr),this.#c.delete(t);return}if(typeof s=="number"&&r.previousAllocation&&r.previousAllocation.ptr===s){this.#s.free(s),r.previousAllocation=null;return}this.#s.free(r.ptr),this.#c.delete(t)}handleBufferAllocated(e){let t=e[0],s=e[1],r=this.#a.get(t);r&&(clearTimeout(r.timeout),r.resolve({bufnum:s}),this.#a.delete(t))}allocate(e){let t=e*4,s=this.#s.malloc(t);if(s===0){let r=this.#s.stats(),n=((r.available||0)/(1024*1024)).toFixed(2),o=((r.total||0)/(1024*1024)).toFixed(2),a=(t/(1024*1024)).toFixed(2);console.error(`[BufferManager] Allocation failed: requested ${a}MB, available ${n}MB of ${o}MB total`)}return s}free(e){return this.#s.free(e)}getView(e,t){return new Float32Array(this.#f,e,t)}getStats(){return this.#s?this.#s.stats():{total:0,available:0,used:0,allocations:0}}getAllocatedBuffers(){let e=[];for(let[t,s]of this.#c.entries())!s||!s.ptr||e.push({bufnum:t,ptr:s.ptr,numFrames:s.numFrames,numChannels:s.numChannels,sampleRate:s.sampleRate,source:s.source||null});return e}updateAudioContext(e){if(!e)throw new Error("BufferManager.updateAudioContext requires audioContext");this.#i=e}getDiagnostics(){let e=this.#s.stats(),t=0,s=0;for(let r of this.#c.values())r&&(t+=r.size||0,r.pendingToken&&s++);return{active:this.#c.size,pending:s,bytesActive:t,pool:{total:this.#h,available:e.available||0,freeBytes:e.free?.size||0,freeBlocks:e.free?.count||0,usedBytes:e.used?.size||0,usedBlocks:e.used?.count||0}}}destroy(){for(let[e,t]of this.#a.entries())clearTimeout(t.timeout),t.reject(new Error("BufferManager destroyed"));this.#a.clear();for(let[e,t]of this.#c.entries())t.ptr&&this.#s.free(t.ptr);this.#c.clear(),this.#u.clear()}};var ee=class{#t;#e;#n;constructor(e={}){let{onLoadingEvent:t=null,maxRetries:s=3,baseDelay:r=1e3}=e;this.#t=t,this.#e=s,this.#n=r}async fetch(e,{type:t,name:s}){let r=this.#i(e),n=this.#f(e),o=await r;this.#t?.("loading:start",{type:t,name:s,...o!=null&&{size:o}});let c=await(await n).arrayBuffer();return this.#t?.("loading:complete",{type:t,name:s,size:c.byteLength}),c}async#i(e){try{let t=await fetch(e,{method:"HEAD"});if(t.ok){let s=t.headers.get("Content-Length");return s?parseInt(s,10):null}return null}catch{return null}}async#f(e){let t;for(let s=0;s<=this.#e;s++)try{let r=await fetch(e);if(r.status>=400&&r.status<500)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);if(!r.ok)throw new Error(`Server error fetching ${e}: ${r.status} ${r.statusText}`);return r}catch(r){if(t=r,r.message.includes("Failed to fetch")&&r.message.includes("4"))throw r;if(s<this.#e){let n=this.#n*Math.pow(2,s);await this.#s(n)}}throw t}#s(e){return new Promise(t=>setTimeout(t,e))}};var te=class{#t;#e;constructor({bufferManager:e,getDefaultSampleRate:t}){if(!e)throw new Error("OSCRewriter requires bufferManager");if(typeof t!="function")throw new Error("OSCRewriter requires getDefaultSampleRate callback");this.#t=e,this.#e=t}async rewritePacket(e){if(Array.isArray(e)){let{message:t,changed:s}=await this.#n(e);return{packet:t,changed:s}}if(this.#c(e)){let t=await Promise.all(e.packets.map(n=>this.rewritePacket(n)));if(!t.some(n=>n.changed))return{packet:e,changed:!1};let r=t.map(n=>n.packet);return{packet:{timeTag:e.timeTag,packets:r},changed:!0}}return{packet:e,changed:!1}}async#n(e){let t=e[0],s=e.slice(1);switch(t){case"/b_alloc":return{message:await this.#i(s),changed:!0};case"/b_allocRead":return{message:await this.#f(s),changed:!0};case"/b_allocReadChannel":return{message:await this.#s(s),changed:!0};case"/b_allocFile":return{message:await this.#h(s),changed:!0};default:return{message:e,changed:!1}}}async#i(e){let t=this.#p(e,0,"/b_alloc requires a buffer number"),s=this.#p(e,1,"/b_alloc requires a frame count"),r=2,n=1,o=this.#e();this.#S(this.#a(e,r))&&(n=Math.max(1,this.#m(e,r,1)),r++),this.#a(e,r)?.type==="b"&&r++,this.#S(this.#a(e,r))&&(o=this.#u(this.#a(e,r)));let a=await this.#t.prepareEmpty({bufnum:t,numFrames:s,numChannels:n,sampleRate:o});return this.#b(a.allocationComplete,`/b_alloc ${t}`),this.#o(t,a)}async#f(e){let t=this.#p(e,0,"/b_allocRead requires a buffer number"),s=this.#y(e,1,"/b_allocRead requires a file path"),r=this.#m(e,2,0),n=this.#m(e,3,0),o=await this.#t.prepareFromFile({bufnum:t,path:s,startFrame:r,numFrames:n});return this.#b(o.allocationComplete,`/b_allocRead ${t}`),this.#o(t,o)}async#s(e){let t=this.#p(e,0,"/b_allocReadChannel requires a buffer number"),s=this.#y(e,1,"/b_allocReadChannel requires a file path"),r=this.#m(e,2,0),n=this.#m(e,3,0),o=[];for(let c=4;c<(e?.length||0)&&this.#S(e[c]);c++)o.push(Math.floor(this.#u(e[c])));let a=await this.#t.prepareFromFile({bufnum:t,path:s,startFrame:r,numFrames:n,channels:o.length>0?o:null});return this.#b(a.allocationComplete,`/b_allocReadChannel ${t}`),this.#o(t,a)}async#h(e){let t=this.#p(e,0,"/b_allocFile requires a buffer number"),s=this.#d(e,1,"/b_allocFile requires audio file data as blob"),r=await this.#t.prepareFromBlob({bufnum:t,blob:s});return this.#b(r.allocationComplete,`/b_allocFile ${t}`),this.#o(t,r)}#o(e,t){return["/b_allocPtr",Math.floor(e),Math.floor(t.ptr),Math.floor(t.numFrames),Math.floor(t.numChannels),t.sampleRate,String(t.uuid)]}#c(e){return e&&e.timeTag!==void 0&&Array.isArray(e.packets)}#a(e,t){if(Array.isArray(e))return e[t]}#u(e){if(e!=null)return typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"value")?e.value:e}#p(e,t,s){let r=this.#u(this.#a(e,t));if(!Number.isFinite(r))throw new Error(s);return Math.floor(r)}#m(e,t,s=0){let r=this.#u(this.#a(e,t));return Number.isFinite(r)?Math.floor(r):s}#y(e,t,s){let r=this.#u(this.#a(e,t));if(typeof r!="string")throw new Error(s);return r}#d(e,t,s){let r=this.#u(this.#a(e,t));if(!(r instanceof Uint8Array||r instanceof ArrayBuffer))throw new Error(s);return r}#S(e){if(!e)return!1;let t=this.#u(e);return Number.isFinite(t)}#b(e,t){!e||typeof e.catch!="function"||e.catch(s=>{console.error(`[OSCRewriter] ${t} allocation failed:`,s)})}};function D(i){if(!i)return null;if(typeof i=="string")return(i.split("/").filter(Boolean).pop()||i).replace(/\.scsyndef$/i,"");let e=i instanceof ArrayBuffer?new Uint8Array(i):i;if(!(e instanceof Uint8Array)||e.length<11||e[0]!==83||e[1]!==67||e[2]!==103||e[3]!==102)return null;let t=e[10];if(t===0||11+t>e.length)return null;try{return new TextDecoder().decode(e.slice(11,11+t))}catch{return null}}var se=class{#t=new Map;on(e,t){if(typeof t!="function")throw new Error("Callback must be a function");return this.#t.has(e)||this.#t.set(e,new Set),this.#t.get(e).add(t),()=>this.off(e,t)}off(e,t){let s=this.#t.get(e);return s&&s.delete(t),this}once(e,t){let s=(...r)=>{this.off(e,s),t(...r)};return this.on(e,s)}removeAllListeners(e){return e===void 0?this.#t.clear():this.#t.delete(e),this}hasListeners(e){let t=this.#t.get(e);return t?t.size>0:!1}emit(e,...t){let s=this.#t.get(e);if(s)for(let r of s)try{r(...t)}catch(n){console.error(`[EventEmitter] Error in ${e} listener:`,n)}}async emitAsync(e,...t){let s=this.#t.get(e);if(s)for(let r of s)try{await r(...t)}catch(n){console.error(`[EventEmitter] Error in ${e} listener:`,n)}}clearAllListeners(){this.#t.clear()}};var re=class{#t;#e;#n;#i;#f;#s;#h=null;constructor(e={}){this.#i=e.mode||"sab",this.#t=e.sharedBuffer||null,this.#e=e.ringBufferBase||0,this.#n=e.bufferConstants||null}initSharedViews(e,t,s){if(this.#t=e,this.#e=t,this.#n=s,this.#i==="sab"&&e&&s){this.#f=new Int32Array(e);let r=t+s.METRICS_START;this.#s=new Uint32Array(e,r,s.METRICS_SIZE/4)}}updateSnapshot(e){this.#h=e}getSnapshotBuffer(){return this.#h}getMetricsView(){return this.#s}addMetric(e,t=1){if(!this.#s)return;let r={oscOutMessagesSent:24,oscOutBytesSent:25,preschedulerBypassed:22,bypassNonBundle:38,bypassImmediate:39,bypassNearFuture:40,bypassLate:41}[e];r!==void 0&&Atomics.add(this.#s,r,t)}parseMetricsBuffer(e){return{scsynthProcessCount:e[0],scsynthMessagesProcessed:e[1],scsynthMessagesDropped:e[2],scsynthSchedulerDepth:e[3],scsynthSchedulerPeakDepth:e[4],scsynthSchedulerDropped:e[5],scsynthSequenceGaps:e[6],scsynthSchedulerLates:e[8],scsynthSchedulerMaxLateMs:e[42],scsynthSchedulerLastLateMs:e[43],scsynthSchedulerLastLateTick:e[44],preschedulerPending:e[9],preschedulerPendingPeak:e[10],preschedulerDispatched:e[12],preschedulerRetriesSucceeded:e[16],preschedulerRetriesFailed:e[17],preschedulerBundlesScheduled:e[11],preschedulerEventsCancelled:e[13],preschedulerTotalDispatches:e[21],preschedulerMessagesRetried:e[20],preschedulerRetryQueueSize:e[18],preschedulerRetryQueuePeak:e[19],preschedulerBypassed:e[22],oscInMessagesReceived:e[26],oscInMessagesDropped:e[28],oscInBytesReceived:e[27],debugMessagesReceived:e[30],debugBytesReceived:e[31],oscOutMessagesSent:e[24],oscOutBytesSent:e[25],preschedulerMinHeadroomMs:e[14],preschedulerLates:e[15],preschedulerMaxLateMs:e[23],scsynthWasmErrors:e[7],oscInCorrupted:e[29],ringBufferDirectWriteFails:e[45],inBufferUsedBytes:e[32],outBufferUsedBytes:e[33],debugBufferUsedBytes:e[34],inBufferPeakBytes:e[35],outBufferPeakBytes:e[36],debugBufferPeakBytes:e[37],bypassNonBundle:e[38],bypassImmediate:e[39],bypassNearFuture:e[40],bypassLate:e[41]}}getSABMetrics(){return this.#s?this.parseMetricsBuffer(this.#s):null}getBufferUsage(){if(!this.#f||!this.#n||!this.#e)return null;let e=this.#e+this.#n.CONTROL_START,t=this.#n,s=this.#f,r=Atomics.load(s,(e+0)/4),n=Atomics.load(s,(e+4)/4),o=Atomics.load(s,(e+8)/4),a=Atomics.load(s,(e+12)/4),c=Atomics.load(s,(e+16)/4),u=Atomics.load(s,(e+20)/4),f=(r-n+t.IN_BUFFER_SIZE)%t.IN_BUFFER_SIZE,l=(o-a+t.OUT_BUFFER_SIZE)%t.OUT_BUFFER_SIZE,d=(c-u+t.DEBUG_BUFFER_SIZE)%t.DEBUG_BUFFER_SIZE;return{inBufferUsed:{bytes:f,percentage:f/t.IN_BUFFER_SIZE*100,capacity:t.IN_BUFFER_SIZE},outBufferUsed:{bytes:l,percentage:l/t.OUT_BUFFER_SIZE*100,capacity:t.OUT_BUFFER_SIZE},debugBufferUsed:{bytes:d,percentage:d/t.DEBUG_BUFFER_SIZE*100,capacity:t.DEBUG_BUFFER_SIZE}}}overlayPreschedulerMetrics(e){if(!this.#h||!e)return;let t=new Uint32Array(this.#h,0,46),s=9,r=13;t.set(e.subarray(s,s+r),s),t[23]=e[23]}gatherMetrics(e={}){let t;if(this.#i==="postMessage")if(e.preschedulerMetrics&&this.overlayPreschedulerMetrics(e.preschedulerMetrics),this.#h){let s=new Uint32Array(this.#h,0,46);t=this.parseMetricsBuffer(s)}else t={};else t=this.getSABMetrics()||{};if(t.inBufferUsedBytes!==void 0&&this.#n){let s=this.#n;t.inBufferUsed={bytes:t.inBufferUsedBytes,percentage:t.inBufferUsedBytes/s.IN_BUFFER_SIZE*100,peakBytes:t.inBufferPeakBytes,peakPercentage:t.inBufferPeakBytes/s.IN_BUFFER_SIZE*100,capacity:s.IN_BUFFER_SIZE},t.outBufferUsed={bytes:t.outBufferUsedBytes,percentage:t.outBufferUsedBytes/s.OUT_BUFFER_SIZE*100,peakBytes:t.outBufferPeakBytes,peakPercentage:t.outBufferPeakBytes/s.OUT_BUFFER_SIZE*100,capacity:s.OUT_BUFFER_SIZE},t.debugBufferUsed={bytes:t.debugBufferUsedBytes,percentage:t.debugBufferUsedBytes/s.DEBUG_BUFFER_SIZE*100,peakBytes:t.debugBufferPeakBytes,peakPercentage:t.debugBufferPeakBytes/s.DEBUG_BUFFER_SIZE*100,capacity:s.DEBUG_BUFFER_SIZE},delete t.inBufferUsedBytes,delete t.outBufferUsedBytes,delete t.debugBufferUsedBytes,delete t.inBufferPeakBytes,delete t.outBufferPeakBytes,delete t.debugBufferPeakBytes}return t.mode=this.#i,this.#n?.scheduler_slot_count!==void 0&&(t.scsynthSchedulerCapacity=this.#n.scheduler_slot_count),e.driftOffsetMs!==void 0&&(t.driftOffsetMs=e.driftOffsetMs),e.ntpStartTime!==void 0&&(t.ntpStartTime=e.ntpStartTime),e.globalOffsetMs!==void 0&&(t.globalOffsetMs=e.globalOffsetMs),e.audioContextState&&(t.audioContextState=e.audioContextState),e.bufferPoolStats&&(t.bufferPoolUsedBytes=e.bufferPoolStats.used.size,t.bufferPoolAvailableBytes=e.bufferPoolStats.available,t.bufferPoolAllocations=e.bufferPoolStats.used.count),e.loadedSynthDefsCount!==void 0&&(t.loadedSynthDefs=e.loadedSynthDefsCount),e.preschedulerCapacity!==void 0&&(t.preschedulerCapacity=e.preschedulerCapacity),this.#i==="postMessage"&&e.transportMetrics&&Object.assign(t,e.transportMetrics),t}get bufferConstants(){return this.#n}get ringBufferBase(){return this.#e}get sharedBuffer(){return this.#t}};function ie(i){return i/1e3+2208988800}function Ie(i,e){return i-e}function ct(i,e){let t=i-e;return Math.round(t*1e3)}var ne=class{#t;#e;#n;#i;#f;#s;#h;#o;#c;#a=0;#u=0;#p=null;constructor(e={}){this.#t=e.mode||"sab",this.#e=e.audioContext,this.#n=e.workletPort||null}initSharedViews(e,t,s){this.#f=t,this.#i=s,this.#t==="sab"&&e&&s&&(this.#s=new Float64Array(e,t+s.NTP_START_TIME_START,1),this.#h=new Int32Array(e,t+s.DRIFT_OFFSET_START,1),this.#o=new Int32Array(e,t+s.GLOBAL_OFFSET_START,1))}setWorkletPort(e){this.#n=e}updateAudioContext(e){this.#e=e}async initialize(){if(!this.#e)return;let e;for(;e=this.#e.getOutputTimestamp(),!(e.contextTime>0);)await new Promise(o=>setTimeout(o,50));e=this.#e.getOutputTimestamp();let t=performance.timeOrigin+e.performanceTime,s=ie(t),r=e.contextTime,n=Ie(s,r);this.#t==="sab"&&this.#s?this.#s[0]=n:this.#n&&this.#n.postMessage({type:"setNTPStartTime",ntpStartTime:n}),this.#c=n,await new Promise(o=>setTimeout(o,500)),this.updateDriftOffset()}updateDriftOffset(){if(!this.#e||this.#c===void 0)return;let e=this.#e.getOutputTimestamp(),t=performance.timeOrigin+e.performanceTime,r=ie(t)-this.#c,n=ct(r,e.contextTime);this.#a=n,this.#t==="sab"&&this.#h?Atomics.store(this.#h,0,n):this.#n&&this.#n.postMessage({type:"setDriftOffset",driftOffsetMs:n})}resync(){if(!this.#e)return;let e=this.#e.getOutputTimestamp();if(!e||e.contextTime<=0)return;let t=performance.timeOrigin+e.performanceTime,s=ie(t),r=Ie(s,e.contextTime);this.#t==="sab"&&this.#s?this.#s[0]=r:this.#n&&this.#n.postMessage({type:"setNTPStartTime",ntpStartTime:r}),this.#c=r,this.updateDriftOffset()}startDriftTimer(){this.stopDriftTimer(),this.#p=setInterval(()=>{this.updateDriftOffset()},1e3)}stopDriftTimer(){this.#p&&(clearInterval(this.#p),this.#p=null)}getDriftOffset(){return this.#h?Atomics.load(this.#h,0):this.#a}getNTPStartTime(){return this.#s?this.#s[0]:this.#c??0}getGlobalOffset(){return this.#o?Atomics.load(this.#o,0):this.#u}setGlobalOffset(e){this.#u=e,this.#t==="sab"&&this.#o?Atomics.store(this.#o,0,e):this.#n&&this.#n.postMessage({type:"setGlobalOffset",globalOffsetMs:e})}calculateBundleWait(e){if(e.length<16||String.fromCharCode.apply(null,e.slice(0,8))!=="#bundle\0")return null;let s=this.getNTPStartTime();if(s===0)return console.warn("[NTPTiming] NTP start time not yet initialized"),null;let n=this.getDriftOffset()/1e3,a=this.getGlobalOffset()/1e3,c=s+n+a,u=new DataView(e.buffer,e.byteOffset),f=u.getUint32(8,!1),l=u.getUint32(12,!1);if(f===0&&(l===0||l===1))return null;let m=f+l/4294967296-c,p=this.#e?.currentTime??0;return{audioTimeS:m,currentTimeS:p}}reset(){this.stopDriftTimer(),this.#c=void 0,this.#a=0,this.#u=0,this.#s=null,this.#h=null,this.#o=null}};var oe=class{#t;#e;#n;constructor(e={}){this.#t=e.sharedBuffer||null,this.#e=e.bufferConstants||null,this.#n=e.ringBufferBase||0}update(e,t,s){this.#t=e,this.#n=t,this.#e=s}isAvailable(){return!!(this.#t&&this.#e)}start(){if(!this.isAvailable())throw new Error("AudioCapture not initialized");let e=this.#e,t=this.#n+e.AUDIO_CAPTURE_START,s=new Uint32Array(this.#t,t,4);Atomics.store(s,1,0),Atomics.store(s,0,1)}stop(){if(!this.isAvailable())throw new Error("AudioCapture not initialized");let e=this.#e,t=this.#n+e.AUDIO_CAPTURE_START,s=new Uint32Array(this.#t,t,4);Atomics.store(s,0,0);let r=Atomics.load(s,1),n=s[2],o=s[3],a=t+e.AUDIO_CAPTURE_HEADER_SIZE,c=new Float32Array(this.#t,a,r*o),u=new Float32Array(r),f=o>1?new Float32Array(r):null;for(let l=0;l<r;l++)u[l]=c[l*o],f&&(f[l]=c[l*o+1]);return{sampleRate:n,channels:o,frames:r,left:u,right:f}}isEnabled(){if(!this.isAvailable())return!1;let e=this.#e,t=this.#n+e.AUDIO_CAPTURE_START,s=new Uint32Array(this.#t,t,1);return Atomics.load(s,0)===1}getFrameCount(){if(!this.isAvailable())return 0;let e=this.#e,t=this.#n+e.AUDIO_CAPTURE_START,s=new Uint32Array(this.#t,t,2);return Atomics.load(s,1)}getMaxDuration(){if(!this.#e)return 0;let e=this.#e;return e.AUDIO_CAPTURE_FRAMES/(e.AUDIO_CAPTURE_SAMPLE_RATE||48e3)}};function ut(i){let e,t,s;if(i&&typeof i.sharedBuffer<"u"&&typeof i.ringBufferBase<"u")e=i.sharedBuffer,t=i.ringBufferBase,s=i.bufferConstants;else if(i&&i.sab)e=i.sab,t=i.ringBufferBase??0,s=i.layout;else throw new Error("inspect() requires an instance or {sab, ringBufferBase, layout}");if(!e||!s)return{error:"Not initialized - sab or layout missing"};let r=new Int32Array(e),n=t+s.CONTROL_START,o={inHead:Atomics.load(r,(n+0)/4),inTail:Atomics.load(r,(n+4)/4),outHead:Atomics.load(r,(n+8)/4),outTail:Atomics.load(r,(n+12)/4),debugHead:Atomics.load(r,(n+16)/4),debugTail:Atomics.load(r,(n+20)/4),inSequence:Atomics.load(r,(n+24)/4),outSequence:Atomics.load(r,(n+28)/4),debugSequence:Atomics.load(r,(n+32)/4),statusFlags:Atomics.load(r,(n+36)/4),inWriteLock:Atomics.load(r,(n+40)/4)},a=new Float64Array(e,t+s.NTP_START_TIME_START,1),c=new Int32Array(e,t+s.DRIFT_OFFSET_START,1),u=new Int32Array(e,t+s.GLOBAL_OFFSET_START,1),f={ntpStartTime:a[0],driftOffsetMs:Atomics.load(c,0),globalOffsetMs:Atomics.load(u,0)},l=(o.inHead-o.inTail+s.IN_BUFFER_SIZE)%s.IN_BUFFER_SIZE,d=(o.outHead-o.outTail+s.OUT_BUFFER_SIZE)%s.OUT_BUFFER_SIZE,m=(o.debugHead-o.debugTail+s.DEBUG_BUFFER_SIZE)%s.DEBUG_BUFFER_SIZE,p={in:{bytes:l,percent:l/s.IN_BUFFER_SIZE*100},out:{bytes:d,percent:d/s.OUT_BUFFER_SIZE*100},debug:{bytes:m,percent:m/s.DEBUG_BUFFER_SIZE*100}},E=new Uint32Array(e,t+s.METRICS_START,s.METRICS_SIZE/4),g={processCount:E[0],messagesProcessed:E[1],messagesDropped:E[2],schedulerQueueDepth:E[3],schedulerQueueMax:E[4],schedulerQueueDropped:E[5]};return{layout:s,ringBufferBase:t,control:o,timing:f,bufferUsage:p,metrics:g,sabByteLength:e.byteLength}}function lt(i,e,t){let s=t,r=new Uint32Array(i,e,3),n=r[0],o=r[1],a=r[2],c=e+s.NODE_TREE_HEADER_SIZE,u=s.NODE_TREE_MIRROR_MAX_NODES,f=s.NODE_TREE_ENTRY_SIZE,l=s.NODE_TREE_DEF_NAME_SIZE,d=new DataView(i,c,u*f),m=new TextDecoder("utf-8"),p=[],E=0;for(let g=0;g<u&&E<n;g++){let y=g*f,_=d.getInt32(y,!0);if(_===-1)continue;E++;let h=c+y+24,T=new Uint8Array(i,h,l),A=new Uint8Array(l);A.set(T);let w=A.indexOf(0);w===-1&&(w=l);let he=m.decode(A.subarray(0,w));p.push({id:_,parentId:d.getInt32(y+4,!0),isGroup:d.getInt32(y+8,!0)===1,prevId:d.getInt32(y+12,!0),nextId:d.getInt32(y+16,!0),headId:d.getInt32(y+20,!0),defName:he})}return{nodeCount:n,version:o,droppedCount:a,nodes:p}}var Ct={};Pt(Ct,{NTP_EPOCH_OFFSET:()=>ue,TWO_POW_32:()=>C,clearCache:()=>Fs,copyEncoded:()=>O,decodeBundle:()=>Ut,decodeMessage:()=>Mt,decodePacket:()=>K,encodeBundle:()=>Z,encodeBundleIntoBuffer:()=>Ps,encodeMessage:()=>q,encodeMessageIntoBuffer:()=>xs,encodeSingleBundle:()=>Fe,getBundleTimeTag:()=>ks,getCacheStats:()=>Ns,isBundle:()=>Rt});var Le=new Uint8Array(2097152),ft=new DataView(Le.buffer),S=Le,b=ft,V=new Map,ht=1e3,Ls=new TextDecoder,ue=2208988800,C=4294967296,xe=new Uint8Array([35,98,117,110,100,108,101,0]),dt=44,pt=105,mt=102,gt=115,Et=98,yt=84,St=70,_t=104,bt=100,Tt=116;function ae(i,e){let t=i.length+4;t+=e.length+4;for(let s of e)s instanceof Uint8Array?t+=4+s.length+3:s instanceof ArrayBuffer?t+=4+s.byteLength+3:typeof s=="string"?t+=s.length*3+4:t+=8;return t}function At(i){let e=16;for(let t of i)e+=4,Array.isArray(t)?e+=ae(t[0],t.slice(1)):t.packets!==void 0?e+=At(t.packets):e+=ae(t.address,t.args||[]);return e}function Pe(i){if(i<=2097152){S=Le,b=ft;return}S=new Uint8Array(i),b=new DataView(S.buffer)}function q(i,e=[]){let t=ae(i,e);Pe(t);let s=0;s=Ne(i,s),s=ke(e,s);for(let r=0;r<e.length;r++)s=le(e[r],s);return S.subarray(0,s)}function Z(i,e){let t=At(e);Pe(t);let s=0;S.set(xe,s),s+=8,s=fe(i,s);for(let r=0;r<e.length;r++){let n=e[r],o=s;s+=4;let a=s;Array.isArray(n)?s=ce(n[0],n.slice(1),s):n.packets!==void 0?s=wt(n.timeTag,n.packets,s):s=ce(n.address,n.args||[],s);let c=s-a;b.setUint32(o,c,!1)}return S.subarray(0,s)}function Fe(i,e,t=[]){let s=20+ae(e,t);Pe(s);let r=0;S.set(xe,r),r+=8,r=fe(i,r);let n=r;r+=4;let o=r;r=Ne(e,r),r=ke(t,r);for(let a=0;a<t.length;a++)r=le(t[a],r);return b.setUint32(n,r-o,!1),S.subarray(0,r)}function ce(i,e,t){t=Ne(i,t),t=ke(e,t);for(let s=0;s<e.length;s++)t=le(e[s],t);return t}function wt(i,e,t){S.set(xe,t),t+=8,t=fe(i,t);for(let s=0;s<e.length;s++){let r=e[s],n=t;t+=4;let o=t;Array.isArray(r)?t=ce(r[0],r.slice(1),t):r.packets!==void 0?t=wt(r.timeTag,r.packets,t):t=ce(r.address,r.args||[],t),b.setUint32(n,t-o,!1)}return t}function Ne(i,e){let t=V.get(i);if(t)return S.set(t,e),e+t.length;let s=e;if(e=Bt(i,e),V.size<ht){let r=S.slice(s,e);V.set(i,r)}return e}function Bt(i,e){for(let t=0;t<i.length;t++)S[e++]=i.charCodeAt(t);for(S[e++]=0;e&3;)S[e++]=0;return e}function ke(i,e){S[e++]=dt;for(let t=0;t<i.length;t++){let s=i[t],r=typeof s;if(r==="number")S[e++]=Number.isInteger(s)?pt:mt;else if(r==="string")S[e++]=gt;else if(r==="boolean")S[e++]=s?yt:St;else if(s instanceof Uint8Array||s instanceof ArrayBuffer)S[e++]=Et;else if(s&&s.type==="int64")S[e++]=_t;else if(s&&s.type==="double")S[e++]=bt;else if(s&&s.type==="timetag")S[e++]=Tt;else throw s==null?new Error(`OSC argument at index ${t} is ${s}`):new Error(`Unknown OSC argument type at index ${t}: ${r}`)}for(S[e++]=0;e&3;)S[e++]=0;return e}function le(i,e){let t=typeof i;if(t==="number")return Number.isInteger(i)?(b.setInt32(e,i,!1),e+4):(b.setFloat32(e,i,!1),e+4);if(t==="string")return Bt(i,e);if(t==="boolean")return e;if(i instanceof Uint8Array){let s=i.length;for(b.setUint32(e,s,!1),e+=4,S.set(i,e),e+=s;e&3;)S[e++]=0;return e}return i instanceof ArrayBuffer?le(new Uint8Array(i),e):i&&i.type==="int64"?(b.setBigInt64(e,BigInt(i.value),!1),e+8):i&&i.type==="double"?(b.setFloat64(e,i.value,!1),e+8):i&&i.type==="timetag"?fe(i.value,e):e}function fe(i,e){if(i===1||i===null||i===void 0)return b.setUint32(e,0,!1),b.setUint32(e+4,1,!1),e+8;if(Array.isArray(i)){if(i.length!==2)throw new Error(`TimeTag array must have exactly 2 elements [seconds, fraction], got ${i.length}`);return b.setUint32(e,i[0]>>>0,!1),b.setUint32(e+4,i[1]>>>0,!1),e+8}if(typeof i!="number")throw new TypeError(`TimeTag must be a number, array, null, or undefined, got ${typeof i}`);i>1&&i<ue&&console.warn(`TimeTag ${i} looks like a Unix timestamp (< NTP_EPOCH_OFFSET). Did you mean to add NTP_EPOCH_OFFSET (2208988800)?`);let t=i>>>0,s=(i-Math.floor(i))*C>>>0;return b.setUint32(e,t,!1),b.setUint32(e+4,s,!1),e+8}function K(i){return i instanceof Uint8Array||(i=new Uint8Array(i)),i[0]===35&&i[1]===98?Ut(i):Mt(i)}function Mt(i){i instanceof Uint8Array||(i=new Uint8Array(i));let e=new DataView(i.buffer,i.byteOffset,i.byteLength),t=0,[s,r]=De(i,t);if(t=r,t>=i.length||i[t]!==dt)return[s];let[n,o]=De(i,t);t=o;let a=[s];for(let c=1;c<n.length;c++)switch(n.charCodeAt(c)){case pt:a.push(e.getInt32(t,!1)),t+=4;break;case mt:a.push(e.getFloat32(t,!1)),t+=4;break;case gt:let[f,l]=De(i,t);a.push(f),t=l;break;case Et:let d=e.getUint32(t,!1);t+=4,a.push(i.slice(t,t+d)),t+=d,t=t+3&-4;break;case _t:a.push(e.getBigInt64(t,!1)),t+=8;break;case bt:a.push(e.getFloat64(t,!1)),t+=8;break;case yt:a.push(!0);break;case St:a.push(!1);break;case Tt:let m=e.getUint32(t,!1),p=e.getUint32(t+4,!1);a.push(m+p/C),t+=8;break}return a}function Ut(i){i instanceof Uint8Array||(i=new Uint8Array(i));let e=new DataView(i.buffer,i.byteOffset,i.byteLength),t=8,s=e.getUint32(t,!1),r=e.getUint32(t+4,!1),n=s+r/C;t+=8;let o=[];for(;t<i.length;){let a=e.getUint32(t,!1);if(t+=4,a>0&&t+a<=i.length){let c=i.subarray(t,t+a);o.push(K(c))}t+=a}return{timeTag:n,packets:o}}function De(i,e){let t=e;for(;t<i.length&&i[t]!==0;)t++;let s=Ls.decode(i.subarray(e,t));return t++,t=t+3&-4,[s,t]}function O(i){return i.slice()}function xs(i,e,t,s){let r=q(i,e);return t.set(r,s),r.length}function Ps(i,e,t,s){let r=Z(i,e);return t.set(r,s),r.length}function Fs(){V.clear()}function Ns(){return{stringCacheSize:V.size,maxSize:ht}}function Rt(i){return!i||i.length<8?!1:i[0]===35&&i[1]===98}function ks(i){if(!Rt(i))return null;let e=new DataView(i.buffer,i.byteOffset,i.byteLength),t=e.getUint32(8,!1),s=e.getUint32(12,!1);return t+s/C}var Ot={totalPages:1280,ringBufferReserved:3145728,bufferPoolOffset:19922944,bufferPoolSize:63963136,get totalMemory(){return this.bufferPoolOffset+this.bufferPoolSize},get wasmHeapSize(){return this.bufferPoolOffset-this.ringBufferReserved}};var It={numBuffers:1024,maxNodes:1024,maxGraphDefs:1024,maxWireBufs:64,numAudioBusChannels:128,numInputBusChannels:2,numOutputBusChannels:2,numControlBusChannels:4096,bufLength:128,realTimeMemorySize:8192,numRGens:64,realTime:!1,memoryLocking:!1,loadGraphDefs:0,preferredSampleRate:0,verbosity:0};var Dt=class i{static osc={encodeMessage:(e,t)=>O(q(e,t)),encodeBundle:(e,t)=>O(Z(e,t)),decode:e=>K(e),encodeSingleBundle:(e,t,s)=>O(Fe(e,t,s)),readTimetag:e=>me(e),ntpNow:()=>L(),NTP_EPOCH_OFFSET:ue,encode:e=>{if(e.timeTag!==void 0){let t;if(e.timeTag.raw){let[r,n]=e.timeTag.raw;t=r+n/C}else typeof e.timeTag=="number"?t=e.timeTag:t=1;let s=e.packets.map(r=>{let n=(r.args||[]).map(o=>o&&typeof o=="object"&&"value"in o?o.value:o);return[r.address,...n]});return O(Z(t,s))}else{let t=(e.args||[]).map(s=>s&&typeof s=="object"&&"value"in s?s.value:s);return O(q(e.address,t))}}};static inspect(e){return ut(e)}static getMetricsSchema(){return{mode:{type:"string",values:["sab","postMessage"],description:"Transport mode"},scsynthProcessCount:{type:"counter",unit:"count",description:"Audio process() calls"},scsynthMessagesProcessed:{type:"counter",unit:"count",description:"OSC messages processed by scsynth"},scsynthMessagesDropped:{type:"counter",unit:"count",description:"Messages dropped (ring buffer full)"},scsynthSchedulerDepth:{type:"gauge",unit:"count",description:"Current scheduler queue depth"},scsynthSchedulerPeakDepth:{type:"gauge",unit:"count",description:"Peak scheduler queue depth (high water mark)"},scsynthSchedulerCapacity:{type:"constant",unit:"count",description:"Maximum scheduler queue size"},scsynthSchedulerDropped:{type:"counter",unit:"count",description:"Scheduled events dropped"},scsynthSequenceGaps:{type:"counter",unit:"count",description:"Messages lost in transit from JS to scsynth"},scsynthSchedulerLates:{type:"counter",unit:"count",description:"Bundles executed after their scheduled time"},scsynthSchedulerMaxLateMs:{type:"gauge",unit:"ms",description:"Maximum lateness observed in scsynth scheduler (ms)"},scsynthSchedulerLastLateMs:{type:"gauge",unit:"ms",description:"Most recent late magnitude in scsynth scheduler (ms)"},scsynthSchedulerLastLateTick:{type:"gauge",unit:"count",description:"Process count when last scsynth late occurred"},preschedulerPending:{type:"gauge",unit:"count",description:"Events waiting to be scheduled"},preschedulerPendingPeak:{type:"gauge",unit:"count",description:"Peak pending events"},preschedulerDispatched:{type:"counter",unit:"count",description:"Events sent to worklet"},preschedulerRetriesSucceeded:{type:"counter",unit:"count",description:"Retries that succeeded"},preschedulerRetriesFailed:{type:"counter",unit:"count",description:"Retries that failed"},preschedulerBundlesScheduled:{type:"counter",unit:"count",description:"Bundles scheduled"},preschedulerEventsCancelled:{type:"counter",unit:"count",description:"Events cancelled"},preschedulerTotalDispatches:{type:"counter",unit:"count",description:"Total dispatch attempts"},preschedulerMessagesRetried:{type:"counter",unit:"count",description:"Messages that needed retry"},preschedulerRetryQueueSize:{type:"gauge",unit:"count",description:"Current retry queue size"},preschedulerRetryQueuePeak:{type:"gauge",unit:"count",description:"Peak retry queue size"},preschedulerBypassed:{type:"counter",unit:"count",description:"Messages sent directly from JS to scsynth, bypassing prescheduler (aggregate)"},bypassNonBundle:{type:"counter",unit:"count",description:"Plain OSC messages (not bundles) that bypassed prescheduler"},bypassImmediate:{type:"counter",unit:"count",description:"Bundles with timetag 0 or 1 that bypassed prescheduler"},bypassNearFuture:{type:"counter",unit:"count",description:"Bundles within bypass lookahead threshold that bypassed prescheduler"},bypassLate:{type:"counter",unit:"count",description:"Timestamped OSC bundles arriving late into SuperSonic bypassing prescheduler"},preschedulerCapacity:{type:"constant",unit:"count",description:"Maximum pending events in prescheduler"},preschedulerMinHeadroomMs:{type:"gauge",unit:"ms",description:"Smallest time gap between JS prescheduler dispatch and scsynth scheduler execution"},preschedulerLates:{type:"counter",unit:"count",description:"Bundles dispatched after their scheduled execution time"},preschedulerMaxLateMs:{type:"gauge",unit:"ms",description:"Maximum lateness at prescheduler (ms)"},oscInMessagesReceived:{type:"counter",unit:"count",description:"OSC replies received from scsynth to JS"},oscInMessagesDropped:{type:"counter",unit:"count",description:"Replies lost in transit from scsynth to JS"},oscInBytesReceived:{type:"counter",unit:"bytes",description:"Total bytes received from scsynth to JS"},debugMessagesReceived:{type:"counter",unit:"count",description:"Debug messages from scsynth"},debugBytesReceived:{type:"counter",unit:"bytes",description:"Debug bytes received"},oscOutMessagesSent:{type:"counter",unit:"count",description:"OSC messages sent from JS to scsynth"},oscOutBytesSent:{type:"counter",unit:"bytes",description:"Total bytes sent from JS to scsynth"},inBufferUsed:{type:"object",description:"Input ring buffer usage",properties:{bytes:{type:"gauge",unit:"bytes",description:"Bytes used"},percentage:{type:"gauge",unit:"percentage",description:"Percentage full"},capacity:{type:"constant",unit:"bytes",description:"Total buffer capacity"}}},outBufferUsed:{type:"object",description:"Output ring buffer usage",properties:{bytes:{type:"gauge",unit:"bytes",description:"Bytes used"},percentage:{type:"gauge",unit:"percentage",description:"Percentage full"},capacity:{type:"constant",unit:"bytes",description:"Total buffer capacity"}}},debugBufferUsed:{type:"object",description:"Debug ring buffer usage",properties:{bytes:{type:"gauge",unit:"bytes",description:"Bytes used"},percentage:{type:"gauge",unit:"percentage",description:"Percentage full"},capacity:{type:"constant",unit:"bytes",description:"Total buffer capacity"}}},driftOffsetMs:{type:"gauge",unit:"ms",description:"Clock drift between AudioContext and wall clock"},ntpStartTime:{type:"gauge",unit:"seconds",description:"NTP time when AudioContext started"},globalOffsetMs:{type:"gauge",unit:"ms",description:"Global timing offset for multi-system sync"},audioContextState:{type:"string",values:["running","suspended","closed","interrupted"],description:"AudioContext state"},bufferPoolUsedBytes:{type:"gauge",unit:"bytes",description:"Buffer pool bytes used"},bufferPoolAvailableBytes:{type:"gauge",unit:"bytes",description:"Buffer pool bytes available"},bufferPoolAllocations:{type:"counter",unit:"count",description:"Total buffer allocations"},loadedSynthDefs:{type:"gauge",unit:"count",description:"Number of loaded synthdefs"},scsynthWasmErrors:{type:"counter",unit:"count",description:"WASM execution errors in audio worklet"},oscInCorrupted:{type:"counter",unit:"count",description:"Corrupted messages detected from scsynth to JS"},ringBufferDirectWriteFails:{type:"counter",unit:"count",description:"SAB mode only: optimistic direct writes attempted but failed due to ring buffer lock not being available (delivered via prescheduler instead)"}}}static getTreeSchema(){return{nodeCount:{type:"number",description:"Total nodes in tree"},version:{type:"number",description:"Increments on any tree change, useful for detecting updates"},droppedCount:{type:"number",description:"Nodes that exceeded mirror capacity (tree may be incomplete)"},root:{type:"object",description:"Root node of the tree (always a group with id 0)",schema:{id:{type:"number",description:"Unique node ID"},type:{type:"string",values:["group","synth"],description:"Node type"},defName:{type:"string",description:"Synthdef name (synths only, empty for groups)"},children:{type:"array",description:"Child nodes (recursive)",itemSchema:"(self)"}}}}}static getRawTreeSchema(){return{nodeCount:{type:"number",description:"Total nodes in tree"},version:{type:"number",description:"Increments on any tree change, useful for detecting updates"},droppedCount:{type:"number",description:"Nodes that exceeded mirror capacity (tree may be incomplete)"},nodes:{type:"array",description:"Flat array of all nodes with internal linkage pointers",itemSchema:{id:{type:"number",description:"Unique node ID"},parentId:{type:"number",description:"Parent node ID (-1 for root)"},isGroup:{type:"boolean",description:"True if group, false if synth"},prevId:{type:"number",description:"Previous sibling node ID (-1 if none)"},nextId:{type:"number",description:"Next sibling node ID (-1 if none)"},headId:{type:"number",description:"First child node ID (groups only, -1 if empty)"},defName:{type:"string",description:"Synthdef name (synths only, empty for groups)"}}}}}#t;#e;#n=null;#i;#f;#s;#h;#o;#c;#a;#u;#p;#m;#y;#d;#S;#b;#r;#l;#g;#E;#T;#w;#M=null;#A=null;#B=0;#U=[];#R=null;#N(e){let t=(s,r,{min:n,max:o,allowZero:a=!0}={})=>{if(typeof r!="number"||!Number.isFinite(r))throw new Error(`scsynthOptions.${s} must be a finite number, got: ${r}`);if(!a&&r===0)throw new Error(`scsynthOptions.${s} must be non-zero, got: ${r}`);if(n!==void 0&&r<n)throw new Error(`scsynthOptions.${s} must be >= ${n}, got: ${r}`);if(o!==void 0&&r>o)throw new Error(`scsynthOptions.${s} must be <= ${o}, got: ${r}`)};if(t("numBuffers",e.numBuffers,{min:1,max:65535}),t("maxNodes",e.maxNodes,{min:1}),t("maxGraphDefs",e.maxGraphDefs,{min:1}),t("maxWireBufs",e.maxWireBufs,{min:1}),t("numAudioBusChannels",e.numAudioBusChannels,{min:1}),t("numInputBusChannels",e.numInputBusChannels,{min:0}),t("numOutputBusChannels",e.numOutputBusChannels,{min:1}),t("numControlBusChannels",e.numControlBusChannels,{min:1}),e.bufLength!==128)throw new Error(`scsynthOptions.bufLength must be 128 (WebAudio API constraint), got: ${e.bufLength}`);if(t("realTimeMemorySize",e.realTimeMemorySize,{min:1}),t("numRGens",e.numRGens,{min:1}),typeof e.realTime!="boolean")throw new Error(`scsynthOptions.realTime must be a boolean, got: ${typeof e.realTime}`);if(typeof e.memoryLocking!="boolean")throw new Error(`scsynthOptions.memoryLocking must be a boolean, got: ${typeof e.memoryLocking}`);if(e.loadGraphDefs!==0&&e.loadGraphDefs!==1)throw new Error(`scsynthOptions.loadGraphDefs must be 0 or 1, got: ${e.loadGraphDefs}`);if(t("preferredSampleRate",e.preferredSampleRate,{min:0,max:384e3}),e.preferredSampleRate!==0&&e.preferredSampleRate<8e3)throw new Error(`scsynthOptions.preferredSampleRate must be 0 (auto) or >= 8000, got: ${e.preferredSampleRate}`);t("verbosity",e.verbosity,{min:0,max:4})}constructor(e={}){this.#m=!1,this.#y=!1,this.#d=null,this.#S={},this.#b=null,this.#l=new se,this.#g=new re({mode:e.mode||"postMessage"}),this.#T=new oe({}),this.#t=null,this.#e=null,this.#i=null,this.#s=null,this.loadedSynthDefs=new Map;let t=e.baseURL||null,s=e.coreBaseURL||t,r=e.workerBaseURL||(s?`${s}workers/`:null),n=e.wasmBaseURL||(s?`${s}wasm/`:null);if(!r||!n)throw new Error(`SuperSonic requires explicit URL configuration.
|
|
5
|
+
Or install: npm install supersonic-scsynth-samples`);return this.#e+e}#d(e){if(!Number.isInteger(e)||e<0||e>=this.MAX_BUFFERS)throw new Error(`Invalid buffer number ${e} (must be 0-${this.MAX_BUFFERS-1})`)}async#E(e,t,s){let r=null,n=null,o=!1,a=await this.#S(e),c=!1;try{await this.#w(e);let{ptr:l,sizeBytes:f,numFrames:u,numChannels:d,sampleRate:m,source:p,...E}=await s();r=l;let{uuid:y,allocationComplete:S}=this.#y(e,t);n=y,this.#A(e,r,f,y,S,{numFrames:u,numChannels:d,sampleRate:m,source:p}),o=!0;let _=this.#M(e,y,S);return a(),c=!0,{ptr:r,uuid:y,allocationComplete:_,numFrames:u,numChannels:d,sampleRate:m,...E}}catch(l){throw o&&n?this.#B(e,n,!1):r&&this.#s.free(r),l}finally{c||a()}}async prepareFromBlob(e){let{bufnum:t,blob:s,startFrame:r=0,numFrames:n=0,channels:o=null}=e;if(this.#d(t),!s||!(s instanceof ArrayBuffer||ArrayBuffer.isView(s)))throw new Error("/b_allocFile requires audio data as ArrayBuffer or typed array");let a=s instanceof ArrayBuffer?s:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);return this.#E(t,3e4,async()=>{let c=await this.#_(a),l=Math.max(0,Math.floor(r||0)),f=c.length-l,u=n&&n>0?Math.min(Math.floor(n),f):f;if(u<=0)throw new Error(`No audio frames available for buffer ${t}`);let d=this.#b(o,c.numberOfChannels),m=d.length,p=u*m+(this.GUARD_BEFORE+this.GUARD_AFTER)*m,E=this.#g(p),y=new Float32Array(p),S=this.GUARD_BEFORE*m;for(let h=0;h<u;h++)for(let T=0;T<m;T++){let A=d[T],B=c.getChannelData(A);y[S+h*m+T]=B[l+h]}await this.#i(E,y);let _=y.length*4;return{ptr:E,sizeBytes:_,numFrames:u,numChannels:m,sampleRate:c.sampleRate}})}async prepareFromFile(e){let{bufnum:t,path:s,startFrame:r=0,numFrames:n=0,channels:o=null}=e;return this.#d(t),this.#E(t,6e4,async()=>{let a=this.#m(s),c=s.split("/").pop(),l=await this.#t.fetch(a,{type:"sample",name:c}),f=await this.#_(l),u=Math.max(0,Math.floor(r||0)),d=f.length-u,m=n&&n>0?Math.min(Math.floor(n),d):d;if(m<=0)throw new Error(`No audio frames available for buffer ${t} from ${s}`);let p=this.#b(o,f.numberOfChannels),E=p.length,y=m*E+(this.GUARD_BEFORE+this.GUARD_AFTER)*E,S=this.#g(y),_=new Float32Array(y),h=this.GUARD_BEFORE*E;for(let A=0;A<m;A++)for(let B=0;B<E;B++){let he=p[B],Lt=f.getChannelData(he);_[h+A*E+B]=Lt[u+A]}await this.#i(S,_);let T=_.length*4;return{ptr:S,sizeBytes:T,numFrames:m,numChannels:E,sampleRate:f.sampleRate,source:{type:"file",path:s,startFrame:r,numFrames:n,channels:o}}})}async prepareEmpty(e){let{bufnum:t,numFrames:s,numChannels:r=1,sampleRate:n=null}=e;if(this.#d(t),!Number.isFinite(s)||s<=0)throw new Error(`/b_alloc requires a positive number of frames (got ${s})`);if(!Number.isFinite(r)||r<=0)throw new Error(`/b_alloc requires a positive channel count (got ${r})`);let o=Math.floor(s),a=Math.floor(r);return this.#E(t,5e3,async()=>{let c=o*a+(this.GUARD_BEFORE+this.GUARD_AFTER)*a,l=this.#g(c),f=new Float32Array(c);await this.#i(l,f);let u=f.length*4;return{ptr:l,sizeBytes:u,numFrames:o,numChannels:a,sampleRate:n||this.#h.sampleRate}})}#b(e,t){return!e||e.length===0?Array.from({length:t},(s,r)=>r):(e.forEach(s=>{if(!Number.isInteger(s)||s<0||s>=t)throw new Error(`Channel ${s} is out of range (file has ${t} channels)`)}),e)}#g(e){let t=e*4,s=this.#s.malloc(t);if(s===0){let r=this.#s.stats(),n=((r.available||0)/(1024*1024)).toFixed(2),o=((r.total||0)/(1024*1024)).toFixed(2),a=(t/(1024*1024)).toFixed(2);throw new Error(`Buffer pool allocation failed: requested ${a}MB, available ${n}MB of ${o}MB total`)}return s}async#i(e,t){if(this.#r==="sab")new Float32Array(this.#n,e,t.length).set(t);else{let s=crypto.randomUUID(),r=new Promise((o,a)=>{let c=setTimeout(()=>{a(new Error("Buffer copy to WASM memory timed out"))},1e4),l=f=>{let u=f.data;u.type==="bufferCopied"&&u.copyId===s&&(this.#p.removeEventListener("message",l),clearTimeout(c),u.success?o():a(new Error(u.error||"Buffer copy failed")))};this.#p.addEventListener("message",l)}),n=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);this.#p.postMessage({type:"copyBufferData",copyId:s,ptr:e,data:n},[n]),await r}}#f(e,t,s){return new Promise((r,n)=>{let o=setTimeout(()=>{this.#l.delete(e),n(new Error(`Buffer ${t} allocation timeout (${s}ms)`))},s);this.#l.set(e,{resolve:r,reject:n,timeout:o})})}#y(e,t){let s=crypto.randomUUID(),r=this.#f(s,e,t);return{uuid:s,allocationComplete:r}}async#S(e){let t=this.#u.get(e)||Promise.resolve(),s,r=new Promise(n=>{s=n});return this.#u.set(e,t.then(()=>r)),await t,()=>{s&&(s(),s=null),this.#u.get(e)===r&&this.#u.delete(e)}}#A(e,t,s,r,n,o={}){let a=this.#o.get(e),c={ptr:t,size:s,numFrames:o.numFrames||0,numChannels:o.numChannels||1,sampleRate:o.sampleRate||48e3,pendingToken:r,pendingPromise:n,previousAllocation:a?{ptr:a.ptr,size:a.size}:null,source:o.source||null};return this.#o.set(e,c),c}async#w(e){let t=this.#o.get(e);if(t&&t.pendingToken&&t.pendingPromise)try{await t.pendingPromise}catch{}}#M(e,t,s){return!s||typeof s.then!="function"?(this.#B(e,t,!0),Promise.resolve()):s.then(r=>(this.#B(e,t,!0),r)).catch(r=>{throw this.#B(e,t,!1),r})}#B(e,t,s){let r=this.#o.get(e);if(!r||r.pendingToken!==t)return;let n=r.previousAllocation;if(s){r.pendingToken=null,r.pendingPromise=null,r.previousAllocation=null,n?.ptr&&this.#s.free(n.ptr);return}r.ptr&&this.#s.free(r.ptr),r.pendingPromise=null,n?.ptr?this.#o.set(e,{ptr:n.ptr,size:n.size,pendingToken:null,previousAllocation:null}):this.#o.delete(e)}handleBufferFreed(e){let t=e[0],s=e[1],r=this.#o.get(t);if(!r){typeof s=="number"&&s!==0&&this.#s.free(s);return}if(typeof s=="number"&&s===r.ptr){this.#s.free(r.ptr),this.#o.delete(t);return}if(typeof s=="number"&&r.previousAllocation&&r.previousAllocation.ptr===s){this.#s.free(s),r.previousAllocation=null;return}this.#s.free(r.ptr),this.#o.delete(t)}handleBufferAllocated(e){let t=e[0],s=e[1],r=this.#l.get(t);r&&(clearTimeout(r.timeout),r.resolve({bufnum:s}),this.#l.delete(t))}allocate(e){let t=e*4,s=this.#s.malloc(t);if(s===0){let r=this.#s.stats(),n=((r.available||0)/(1024*1024)).toFixed(2),o=((r.total||0)/(1024*1024)).toFixed(2),a=(t/(1024*1024)).toFixed(2);console.error(`[BufferManager] Allocation failed: requested ${a}MB, available ${n}MB of ${o}MB total`)}return s}free(e){return this.#s.free(e)}getView(e,t){return new Float32Array(this.#n,e,t)}getStats(){return this.#s?this.#s.stats():{total:0,available:0,used:0,allocations:0}}getAllocatedBuffers(){let e=[];for(let[t,s]of this.#o.entries())!s||!s.ptr||e.push({bufnum:t,ptr:s.ptr,numFrames:s.numFrames,numChannels:s.numChannels,sampleRate:s.sampleRate,source:s.source||null});return e}updateAudioContext(e){if(!e)throw new Error("BufferManager.updateAudioContext requires audioContext");this.#h=e}getDiagnostics(){let e=this.#s.stats(),t=0,s=0;for(let r of this.#o.values())r&&(t+=r.size||0,r.pendingToken&&s++);return{active:this.#o.size,pending:s,bytesActive:t,pool:{total:this.#c,available:e.available||0,freeBytes:e.free?.size||0,freeBlocks:e.free?.count||0,usedBytes:e.used?.size||0,usedBlocks:e.used?.count||0}}}destroy(){for(let[e,t]of this.#l.entries())clearTimeout(t.timeout),t.reject(new Error("BufferManager destroyed"));this.#l.clear();for(let[e,t]of this.#o.entries())t.ptr&&this.#s.free(t.ptr);this.#o.clear(),this.#u.clear()}};var ee=class{#r;#e;#t;constructor(e={}){let{onLoadingEvent:t=null,maxRetries:s=3,baseDelay:r=1e3}=e;this.#r=t,this.#e=s,this.#t=r}async fetch(e,{type:t,name:s}){let r=this.#h(e),n=this.#n(e),o=await r;this.#r?.("loading:start",{type:t,name:s,...o!=null&&{size:o}});let c=await(await n).arrayBuffer();return this.#r?.("loading:complete",{type:t,name:s,size:c.byteLength}),c}async#h(e){try{let t=await fetch(e,{method:"HEAD"});if(t.ok){let s=t.headers.get("Content-Length");return s?parseInt(s,10):null}return null}catch{return null}}async#n(e){let t;for(let s=0;s<=this.#e;s++)try{let r=await fetch(e);if(r.status>=400&&r.status<500)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);if(!r.ok)throw new Error(`Server error fetching ${e}: ${r.status} ${r.statusText}`);return r}catch(r){if(t=r,r.message.includes("Failed to fetch")&&r.message.includes("4"))throw r;if(s<this.#e){let n=this.#t*Math.pow(2,s);await this.#s(n)}}throw t}#s(e){return new Promise(t=>setTimeout(t,e))}};var te=class{#r;#e;constructor({bufferManager:e,getDefaultSampleRate:t}){if(!e)throw new Error("OSCRewriter requires bufferManager");if(typeof t!="function")throw new Error("OSCRewriter requires getDefaultSampleRate callback");this.#r=e,this.#e=t}async rewritePacket(e){if(Array.isArray(e)){let{message:t,changed:s}=await this.#t(e);return{packet:t,changed:s}}if(this.#o(e)){let t=await Promise.all(e.packets.map(n=>this.rewritePacket(n)));if(!t.some(n=>n.changed))return{packet:e,changed:!1};let r=t.map(n=>n.packet);return{packet:{timeTag:e.timeTag,packets:r},changed:!0}}return{packet:e,changed:!1}}async#t(e){let t=e[0],s=e.slice(1);switch(t){case"/b_alloc":return{message:await this.#h(s),changed:!0};case"/b_allocRead":return{message:await this.#n(s),changed:!0};case"/b_allocReadChannel":return{message:await this.#s(s),changed:!0};case"/b_allocFile":return{message:await this.#c(s),changed:!0};default:return{message:e,changed:!1}}}async#h(e){let t=this.#p(e,0,"/b_alloc requires a buffer number"),s=this.#p(e,1,"/b_alloc requires a frame count"),r=2,n=1,o=this.#e();this.#E(this.#l(e,r))&&(n=Math.max(1,this.#_(e,r,1)),r++),this.#l(e,r)?.type==="b"&&r++,this.#E(this.#l(e,r))&&(o=this.#u(this.#l(e,r)));let a=await this.#r.prepareEmpty({bufnum:t,numFrames:s,numChannels:n,sampleRate:o});return this.#b(a.allocationComplete,`/b_alloc ${t}`),this.#a(t,a)}async#n(e){let t=this.#p(e,0,"/b_allocRead requires a buffer number"),s=this.#m(e,1,"/b_allocRead requires a file path"),r=this.#_(e,2,0),n=this.#_(e,3,0),o=await this.#r.prepareFromFile({bufnum:t,path:s,startFrame:r,numFrames:n});return this.#b(o.allocationComplete,`/b_allocRead ${t}`),this.#a(t,o)}async#s(e){let t=this.#p(e,0,"/b_allocReadChannel requires a buffer number"),s=this.#m(e,1,"/b_allocReadChannel requires a file path"),r=this.#_(e,2,0),n=this.#_(e,3,0),o=[];for(let c=4;c<(e?.length||0)&&this.#E(e[c]);c++)o.push(Math.floor(this.#u(e[c])));let a=await this.#r.prepareFromFile({bufnum:t,path:s,startFrame:r,numFrames:n,channels:o.length>0?o:null});return this.#b(a.allocationComplete,`/b_allocReadChannel ${t}`),this.#a(t,a)}async#c(e){let t=this.#p(e,0,"/b_allocFile requires a buffer number"),s=this.#d(e,1,"/b_allocFile requires audio file data as blob"),r=await this.#r.prepareFromBlob({bufnum:t,blob:s});return this.#b(r.allocationComplete,`/b_allocFile ${t}`),this.#a(t,r)}#a(e,t){return["/b_allocPtr",Math.floor(e),Math.floor(t.ptr),Math.floor(t.numFrames),Math.floor(t.numChannels),t.sampleRate,String(t.uuid)]}#o(e){return e&&e.timeTag!==void 0&&Array.isArray(e.packets)}#l(e,t){if(Array.isArray(e))return e[t]}#u(e){if(e!=null)return typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"value")?e.value:e}#p(e,t,s){let r=this.#u(this.#l(e,t));if(!Number.isFinite(r))throw new Error(s);return Math.floor(r)}#_(e,t,s=0){let r=this.#u(this.#l(e,t));return Number.isFinite(r)?Math.floor(r):s}#m(e,t,s){let r=this.#u(this.#l(e,t));if(typeof r!="string")throw new Error(s);return r}#d(e,t,s){let r=this.#u(this.#l(e,t));if(!(r instanceof Uint8Array||r instanceof ArrayBuffer))throw new Error(s);return r}#E(e){if(!e)return!1;let t=this.#u(e);return Number.isFinite(t)}#b(e,t){!e||typeof e.catch!="function"||e.catch(s=>{console.error(`[OSCRewriter] ${t} allocation failed:`,s)})}};function v(i){if(!i)return null;if(typeof i=="string")return(i.split("/").filter(Boolean).pop()||i).replace(/\.scsyndef$/i,"");let e=i instanceof ArrayBuffer?new Uint8Array(i):i;if(!(e instanceof Uint8Array)||e.length<11||e[0]!==83||e[1]!==67||e[2]!==103||e[3]!==102)return null;let t=e[10];if(t===0||11+t>e.length)return null;try{return new TextDecoder().decode(e.slice(11,11+t))}catch{return null}}var se=class{#r=new Map;on(e,t){if(typeof t!="function")throw new Error("Callback must be a function");return this.#r.has(e)||this.#r.set(e,new Set),this.#r.get(e).add(t),()=>this.off(e,t)}off(e,t){let s=this.#r.get(e);return s&&s.delete(t),this}once(e,t){let s=(...r)=>{this.off(e,s),t(...r)};return this.on(e,s)}removeAllListeners(e){return e===void 0?this.#r.clear():this.#r.delete(e),this}hasListeners(e){let t=this.#r.get(e);return t?t.size>0:!1}emit(e,...t){let s=this.#r.get(e);if(s)for(let r of s)try{r(...t)}catch(n){console.error(`[EventEmitter] Error in ${e} listener:`,n)}}async emitAsync(e,...t){let s=this.#r.get(e);if(s)for(let r of s)try{await r(...t)}catch(n){console.error(`[EventEmitter] Error in ${e} listener:`,n)}}clearAllListeners(){this.#r.clear()}};var re=class{#r;#e;#t;#h;#n;#s;#c=null;#a=new Uint32Array(64);#o=new DataView(this.#a.buffer);constructor(e={}){this.#h=e.mode||"sab",this.#r=e.sharedBuffer||null,this.#e=e.ringBufferBase||0,this.#t=e.bufferConstants||null}initSharedViews(e,t,s){if(this.#r=e,this.#e=t,this.#t=s,this.#h==="sab"&&e&&s){this.#n=new Int32Array(e);let r=t+s.METRICS_START;this.#s=new Uint32Array(e,r,s.METRICS_SIZE/4)}}updateSnapshot(e){this.#c=e}getSnapshotBuffer(){return this.#c}getMetricsView(){return this.#s}addMetric(e,t=1){if(!this.#s)return;let r={oscOutMessagesSent:24,oscOutBytesSent:25,preschedulerBypassed:22,bypassNonBundle:38,bypassImmediate:39,bypassNearFuture:40,bypassLate:41}[e];r!==void 0&&Atomics.add(this.#s,r,t)}parseMetricsBuffer(e){return{scsynthProcessCount:e[0],scsynthMessagesProcessed:e[1],scsynthMessagesDropped:e[2],scsynthSchedulerDepth:e[3],scsynthSchedulerPeakDepth:e[4],scsynthSchedulerDropped:e[5],scsynthSequenceGaps:e[6],scsynthSchedulerLates:e[8],scsynthSchedulerMaxLateMs:e[42],scsynthSchedulerLastLateMs:e[43],scsynthSchedulerLastLateTick:e[44],preschedulerPending:e[9],preschedulerPendingPeak:e[10],preschedulerDispatched:e[12],preschedulerRetriesSucceeded:e[16],preschedulerRetriesFailed:e[17],preschedulerBundlesScheduled:e[11],preschedulerEventsCancelled:e[13],preschedulerTotalDispatches:e[21],preschedulerMessagesRetried:e[20],preschedulerRetryQueueSize:e[18],preschedulerRetryQueuePeak:e[19],preschedulerBypassed:e[22],oscInMessagesReceived:e[26],oscInMessagesDropped:e[28],oscInBytesReceived:e[27],debugMessagesReceived:e[30],debugBytesReceived:e[31],oscOutMessagesSent:e[24],oscOutBytesSent:e[25],preschedulerMinHeadroomMs:e[14],preschedulerLates:e[15],preschedulerMaxLateMs:e[23],scsynthWasmErrors:e[7],oscInCorrupted:e[29],ringBufferDirectWriteFails:e[45],inBufferUsedBytes:e[32],outBufferUsedBytes:e[33],debugBufferUsedBytes:e[34],inBufferPeakBytes:e[35],outBufferPeakBytes:e[36],debugBufferPeakBytes:e[37],bypassNonBundle:e[38],bypassImmediate:e[39],bypassNearFuture:e[40],bypassLate:e[41]}}getSABMetrics(){return this.#s?this.parseMetricsBuffer(this.#s):null}getBufferUsage(){if(!this.#n||!this.#t||!this.#e)return null;let e=this.#e+this.#t.CONTROL_START,t=this.#t,s=this.#n,r=Atomics.load(s,(e+0)/4),n=Atomics.load(s,(e+4)/4),o=Atomics.load(s,(e+8)/4),a=Atomics.load(s,(e+12)/4),c=Atomics.load(s,(e+16)/4),l=Atomics.load(s,(e+20)/4),f=(r-n+t.IN_BUFFER_SIZE)%t.IN_BUFFER_SIZE,u=(o-a+t.OUT_BUFFER_SIZE)%t.OUT_BUFFER_SIZE,d=(c-l+t.DEBUG_BUFFER_SIZE)%t.DEBUG_BUFFER_SIZE;return{inBufferUsed:{bytes:f,percentage:f/t.IN_BUFFER_SIZE*100,capacity:t.IN_BUFFER_SIZE},outBufferUsed:{bytes:u,percentage:u/t.OUT_BUFFER_SIZE*100,capacity:t.OUT_BUFFER_SIZE},debugBufferUsed:{bytes:d,percentage:d/t.DEBUG_BUFFER_SIZE*100,capacity:t.DEBUG_BUFFER_SIZE}}}overlayPreschedulerMetrics(e){if(!this.#c||!e)return;let t=new Uint32Array(this.#c,0,46),s=9,r=13;t.set(e.subarray(s,s+r),s),t[23]=e[23]}gatherMetrics(e={}){let t;if(this.#h==="postMessage")if(e.preschedulerMetrics&&this.overlayPreschedulerMetrics(e.preschedulerMetrics),this.#c){let s=new Uint32Array(this.#c,0,46);t=this.parseMetricsBuffer(s)}else t={};else t=this.getSABMetrics()||{};if(t.inBufferUsedBytes!==void 0&&this.#t){let s=this.#t;t.inBufferUsed={bytes:t.inBufferUsedBytes,percentage:t.inBufferUsedBytes/s.IN_BUFFER_SIZE*100,peakBytes:t.inBufferPeakBytes,peakPercentage:t.inBufferPeakBytes/s.IN_BUFFER_SIZE*100,capacity:s.IN_BUFFER_SIZE},t.outBufferUsed={bytes:t.outBufferUsedBytes,percentage:t.outBufferUsedBytes/s.OUT_BUFFER_SIZE*100,peakBytes:t.outBufferPeakBytes,peakPercentage:t.outBufferPeakBytes/s.OUT_BUFFER_SIZE*100,capacity:s.OUT_BUFFER_SIZE},t.debugBufferUsed={bytes:t.debugBufferUsedBytes,percentage:t.debugBufferUsedBytes/s.DEBUG_BUFFER_SIZE*100,peakBytes:t.debugBufferPeakBytes,peakPercentage:t.debugBufferPeakBytes/s.DEBUG_BUFFER_SIZE*100,capacity:s.DEBUG_BUFFER_SIZE},delete t.inBufferUsedBytes,delete t.outBufferUsedBytes,delete t.debugBufferUsedBytes,delete t.inBufferPeakBytes,delete t.outBufferPeakBytes,delete t.debugBufferPeakBytes}return t.mode=this.#h,this.#t?.scheduler_slot_count!==void 0&&(t.scsynthSchedulerCapacity=this.#t.scheduler_slot_count),e.driftOffsetMs!==void 0&&(t.driftOffsetMs=e.driftOffsetMs),e.ntpStartTime!==void 0&&(t.ntpStartTime=e.ntpStartTime),e.globalOffsetMs!==void 0&&(t.globalOffsetMs=e.globalOffsetMs),e.audioContextState&&(t.audioContextState=e.audioContextState),e.bufferPoolStats&&(t.bufferPoolUsedBytes=e.bufferPoolStats.used.size,t.bufferPoolAvailableBytes=e.bufferPoolStats.available,t.bufferPoolAllocations=e.bufferPoolStats.used.count),e.loadedSynthDefsCount!==void 0&&(t.loadedSynthDefs=e.loadedSynthDefsCount),e.preschedulerCapacity!==void 0&&(t.preschedulerCapacity=e.preschedulerCapacity),this.#h==="postMessage"&&e.transportMetrics&&Object.assign(t,e.transportMetrics),t}updateMergedArray(e={}){let t=this.#a;if(this.#h==="postMessage"){if(e.preschedulerMetrics&&this.overlayPreschedulerMetrics(e.preschedulerMetrics),this.#c){let a=new Uint32Array(this.#c,0,46);t.set(a)}e.transportMetrics&&(e.transportMetrics.oscOutMessagesSent!==void 0&&(t[24]=e.transportMetrics.oscOutMessagesSent),e.transportMetrics.oscOutBytesSent!==void 0&&(t[25]=e.transportMetrics.oscOutBytesSent),e.transportMetrics.preschedulerBypassed!==void 0&&(t[22]=e.transportMetrics.preschedulerBypassed),e.transportMetrics.bypassNonBundle!==void 0&&(t[38]=e.transportMetrics.bypassNonBundle),e.transportMetrics.bypassImmediate!==void 0&&(t[39]=e.transportMetrics.bypassImmediate),e.transportMetrics.bypassNearFuture!==void 0&&(t[40]=e.transportMetrics.bypassNearFuture),e.transportMetrics.bypassLate!==void 0&&(t[41]=e.transportMetrics.bypassLate))}else this.#s&&t.set(this.#s);let s=this.#o;s.setInt32(46*4,e.driftOffsetMs??0,!0),s.setInt32(47*4,e.globalOffsetMs??0,!0);let r=e.audioContextState||"unknown",n={unknown:0,running:1,suspended:2,closed:3,interrupted:4};t[48]=n[r]??0,e.bufferPoolStats&&(t[49]=e.bufferPoolStats.used?.size??0,t[50]=e.bufferPoolStats.available??0,t[51]=e.bufferPoolStats.used?.count??0),t[52]=e.loadedSynthDefsCount??0;let o=this.#t;t[53]=o?.scheduler_slot_count??0,t[54]=e.preschedulerCapacity??0,t[55]=o?.IN_BUFFER_SIZE??0,t[56]=o?.OUT_BUFFER_SIZE??0,t[57]=o?.DEBUG_BUFFER_SIZE??0,t[58]=this.#h==="sab"?0:1}getMergedArray(){return this.#a}get bufferConstants(){return this.#t}get ringBufferBase(){return this.#e}get sharedBuffer(){return this.#r}};function ie(i){return i/1e3+2208988800}function Ie(i,e){return i-e}function ct(i,e){let t=i-e;return Math.round(t*1e3)}var ne=class{#r;#e;#t;#h;#n;#s;#c;#a;#o;#l=0;#u=0;#p=null;constructor(e={}){this.#r=e.mode||"sab",this.#e=e.audioContext,this.#t=e.workletPort||null}initSharedViews(e,t,s){this.#n=t,this.#h=s,this.#r==="sab"&&e&&s&&(this.#s=new Float64Array(e,t+s.NTP_START_TIME_START,1),this.#c=new Int32Array(e,t+s.DRIFT_OFFSET_START,1),this.#a=new Int32Array(e,t+s.GLOBAL_OFFSET_START,1))}setWorkletPort(e){this.#t=e}updateAudioContext(e){this.#e=e}async initialize(){if(!this.#e)return;let e;for(;e=this.#e.getOutputTimestamp(),!(e.contextTime>0);)await new Promise(o=>setTimeout(o,50));e=this.#e.getOutputTimestamp();let t=performance.timeOrigin+e.performanceTime,s=ie(t),r=e.contextTime,n=Ie(s,r);this.#r==="sab"&&this.#s?this.#s[0]=n:this.#t&&this.#t.postMessage({type:"setNTPStartTime",ntpStartTime:n}),this.#o=n,await new Promise(o=>setTimeout(o,500)),this.updateDriftOffset()}updateDriftOffset(){if(!this.#e||this.#o===void 0)return;let e=this.#e.getOutputTimestamp(),t=performance.timeOrigin+e.performanceTime,r=ie(t)-this.#o,n=ct(r,e.contextTime);this.#l=n,this.#r==="sab"&&this.#c?Atomics.store(this.#c,0,n):this.#t&&this.#t.postMessage({type:"setDriftOffset",driftOffsetMs:n})}resync(){if(!this.#e)return;let e=this.#e.getOutputTimestamp();if(!e||e.contextTime<=0)return;let t=performance.timeOrigin+e.performanceTime,s=ie(t),r=Ie(s,e.contextTime);this.#r==="sab"&&this.#s?this.#s[0]=r:this.#t&&this.#t.postMessage({type:"setNTPStartTime",ntpStartTime:r}),this.#o=r,this.updateDriftOffset()}startDriftTimer(){this.stopDriftTimer(),this.#p=setInterval(()=>{this.updateDriftOffset()},1e3)}stopDriftTimer(){this.#p&&(clearInterval(this.#p),this.#p=null)}getDriftOffset(){return this.#c?Atomics.load(this.#c,0):this.#l}getNTPStartTime(){return this.#s?this.#s[0]:this.#o??0}getGlobalOffset(){return this.#a?Atomics.load(this.#a,0):this.#u}setGlobalOffset(e){this.#u=e,this.#r==="sab"&&this.#a?Atomics.store(this.#a,0,e):this.#t&&this.#t.postMessage({type:"setGlobalOffset",globalOffsetMs:e})}calculateBundleWait(e){if(e.length<16||String.fromCharCode.apply(null,e.slice(0,8))!=="#bundle\0")return null;let s=this.getNTPStartTime();if(s===0)return console.warn("[NTPTiming] NTP start time not yet initialized"),null;let n=this.getDriftOffset()/1e3,a=this.getGlobalOffset()/1e3,c=s+n+a,l=new DataView(e.buffer,e.byteOffset),f=l.getUint32(8,!1),u=l.getUint32(12,!1);if(f===0&&(u===0||u===1))return null;let m=f+u/4294967296-c,p=this.#e?.currentTime??0;return{audioTimeS:m,currentTimeS:p}}reset(){this.stopDriftTimer(),this.#o=void 0,this.#l=0,this.#u=0,this.#s=null,this.#c=null,this.#a=null}};var oe=class{#r;#e;#t;constructor(e={}){this.#r=e.sharedBuffer||null,this.#e=e.bufferConstants||null,this.#t=e.ringBufferBase||0}update(e,t,s){this.#r=e,this.#t=t,this.#e=s}isAvailable(){return!!(this.#r&&this.#e)}start(){if(!this.isAvailable())throw new Error("AudioCapture not initialized");let e=this.#e,t=this.#t+e.AUDIO_CAPTURE_START,s=new Uint32Array(this.#r,t,4);Atomics.store(s,1,0),Atomics.store(s,0,1)}stop(){if(!this.isAvailable())throw new Error("AudioCapture not initialized");let e=this.#e,t=this.#t+e.AUDIO_CAPTURE_START,s=new Uint32Array(this.#r,t,4);Atomics.store(s,0,0);let r=Atomics.load(s,1),n=s[2],o=s[3],a=t+e.AUDIO_CAPTURE_HEADER_SIZE,c=new Float32Array(this.#r,a,r*o),l=new Float32Array(r),f=o>1?new Float32Array(r):null;for(let u=0;u<r;u++)l[u]=c[u*o],f&&(f[u]=c[u*o+1]);return{sampleRate:n,channels:o,frames:r,left:l,right:f}}isEnabled(){if(!this.isAvailable())return!1;let e=this.#e,t=this.#t+e.AUDIO_CAPTURE_START,s=new Uint32Array(this.#r,t,1);return Atomics.load(s,0)===1}getFrameCount(){if(!this.isAvailable())return 0;let e=this.#e,t=this.#t+e.AUDIO_CAPTURE_START,s=new Uint32Array(this.#r,t,2);return Atomics.load(s,1)}getMaxDuration(){if(!this.#e)return 0;let e=this.#e;return e.AUDIO_CAPTURE_FRAMES/(e.AUDIO_CAPTURE_SAMPLE_RATE||48e3)}};function lt(i){let e,t,s;if(i&&typeof i.sharedBuffer<"u"&&typeof i.ringBufferBase<"u")e=i.sharedBuffer,t=i.ringBufferBase,s=i.bufferConstants;else if(i&&i.sab)e=i.sab,t=i.ringBufferBase??0,s=i.layout;else throw new Error("inspect() requires an instance or {sab, ringBufferBase, layout}");if(!e||!s)return{error:"Not initialized - sab or layout missing"};let r=new Int32Array(e),n=t+s.CONTROL_START,o={inHead:Atomics.load(r,(n+0)/4),inTail:Atomics.load(r,(n+4)/4),outHead:Atomics.load(r,(n+8)/4),outTail:Atomics.load(r,(n+12)/4),debugHead:Atomics.load(r,(n+16)/4),debugTail:Atomics.load(r,(n+20)/4),inSequence:Atomics.load(r,(n+24)/4),outSequence:Atomics.load(r,(n+28)/4),debugSequence:Atomics.load(r,(n+32)/4),statusFlags:Atomics.load(r,(n+36)/4),inWriteLock:Atomics.load(r,(n+40)/4)},a=new Float64Array(e,t+s.NTP_START_TIME_START,1),c=new Int32Array(e,t+s.DRIFT_OFFSET_START,1),l=new Int32Array(e,t+s.GLOBAL_OFFSET_START,1),f={ntpStartTime:a[0],driftOffsetMs:Atomics.load(c,0),globalOffsetMs:Atomics.load(l,0)},u=(o.inHead-o.inTail+s.IN_BUFFER_SIZE)%s.IN_BUFFER_SIZE,d=(o.outHead-o.outTail+s.OUT_BUFFER_SIZE)%s.OUT_BUFFER_SIZE,m=(o.debugHead-o.debugTail+s.DEBUG_BUFFER_SIZE)%s.DEBUG_BUFFER_SIZE,p={in:{bytes:u,percent:u/s.IN_BUFFER_SIZE*100},out:{bytes:d,percent:d/s.OUT_BUFFER_SIZE*100},debug:{bytes:m,percent:m/s.DEBUG_BUFFER_SIZE*100}},E=new Uint32Array(e,t+s.METRICS_START,s.METRICS_SIZE/4),y={processCount:E[0],messagesProcessed:E[1],messagesDropped:E[2],schedulerQueueDepth:E[3],schedulerQueueMax:E[4],schedulerQueueDropped:E[5]};return{layout:s,ringBufferBase:t,control:o,timing:f,bufferUsage:p,metrics:y,sabByteLength:e.byteLength}}function ut(i,e,t){let s=t,r=new Uint32Array(i,e,3),n=r[0],o=r[1],a=r[2],c=e+s.NODE_TREE_HEADER_SIZE,l=s.NODE_TREE_MIRROR_MAX_NODES,f=s.NODE_TREE_ENTRY_SIZE,u=s.NODE_TREE_DEF_NAME_SIZE,d=new DataView(i,c,l*f),m=new TextDecoder("utf-8"),p=[],E=0;for(let y=0;y<l&&E<n;y++){let S=y*f,_=d.getInt32(S,!0);if(_===-1)continue;E++;let h=c+S+24,T=new Uint8Array(i,h,u),A=new Uint8Array(u);A.set(T);let B=A.indexOf(0);B===-1&&(B=u);let he=m.decode(A.subarray(0,B));p.push({id:_,parentId:d.getInt32(S+4,!0),isGroup:d.getInt32(S+8,!0)===1,prevId:d.getInt32(S+12,!0),nextId:d.getInt32(S+16,!0),headId:d.getInt32(S+20,!0),defName:he})}return{nodeCount:n,version:o,droppedCount:a,nodes:p}}var Ut={};Ft(Ut,{NTP_EPOCH_OFFSET:()=>le,TWO_POW_32:()=>U,clearCache:()=>Ks,copyEncoded:()=>R,decodeBundle:()=>Ct,decodeMessage:()=>Mt,decodePacket:()=>X,encodeBundle:()=>Z,encodeBundleIntoBuffer:()=>Xs,encodeMessage:()=>q,encodeMessageIntoBuffer:()=>Zs,encodeSingleBundle:()=>ke,getBundleTimeTag:()=>js,getCacheStats:()=>Qs,isBundle:()=>Ot});var Le=new Uint8Array(2097152),ft=new DataView(Le.buffer),g=Le,b=ft,V=new Map,ht=1e3,qs=new TextDecoder,le=2208988800,U=4294967296,Pe=new Uint8Array([35,98,117,110,100,108,101,0]),dt=44,pt=105,mt=102,yt=115,Et=98,St=84,gt=70,_t=104,bt=100,Tt=116;function ae(i,e){let t=i.length+4;t+=e.length+4;for(let s of e)s instanceof Uint8Array?t+=4+s.length+3:s instanceof ArrayBuffer?t+=4+s.byteLength+3:typeof s=="string"?t+=s.length*3+4:t+=8;return t}function At(i){let e=16;for(let t of i)e+=4,Array.isArray(t)?e+=ae(t[0],t.slice(1)):t.packets!==void 0?e+=At(t.packets):e+=ae(t.address,t.args||[]);return e}function Fe(i){if(i<=2097152){g=Le,b=ft;return}g=new Uint8Array(i),b=new DataView(g.buffer)}function q(i,e=[]){let t=ae(i,e);Fe(t);let s=0;s=xe(i,s),s=Ne(e,s);for(let r=0;r<e.length;r++)s=ue(e[r],s);return g.subarray(0,s)}function Z(i,e){let t=At(e);Fe(t);let s=0;g.set(Pe,s),s+=8,s=fe(i,s);for(let r=0;r<e.length;r++){let n=e[r],o=s;s+=4;let a=s;Array.isArray(n)?s=ce(n[0],n.slice(1),s):n.packets!==void 0?s=Bt(n.timeTag,n.packets,s):s=ce(n.address,n.args||[],s);let c=s-a;b.setUint32(o,c,!1)}return g.subarray(0,s)}function ke(i,e,t=[]){let s=20+ae(e,t);Fe(s);let r=0;g.set(Pe,r),r+=8,r=fe(i,r);let n=r;r+=4;let o=r;r=xe(e,r),r=Ne(t,r);for(let a=0;a<t.length;a++)r=ue(t[a],r);return b.setUint32(n,r-o,!1),g.subarray(0,r)}function ce(i,e,t){t=xe(i,t),t=Ne(e,t);for(let s=0;s<e.length;s++)t=ue(e[s],t);return t}function Bt(i,e,t){g.set(Pe,t),t+=8,t=fe(i,t);for(let s=0;s<e.length;s++){let r=e[s],n=t;t+=4;let o=t;Array.isArray(r)?t=ce(r[0],r.slice(1),t):r.packets!==void 0?t=Bt(r.timeTag,r.packets,t):t=ce(r.address,r.args||[],t),b.setUint32(n,t-o,!1)}return t}function xe(i,e){let t=V.get(i);if(t)return g.set(t,e),e+t.length;let s=e;if(e=wt(i,e),V.size<ht){let r=g.slice(s,e);V.set(i,r)}return e}function wt(i,e){for(let t=0;t<i.length;t++)g[e++]=i.charCodeAt(t);for(g[e++]=0;e&3;)g[e++]=0;return e}function Ne(i,e){g[e++]=dt;for(let t=0;t<i.length;t++){let s=i[t],r=typeof s;if(r==="number")g[e++]=Number.isInteger(s)?pt:mt;else if(r==="string")g[e++]=yt;else if(r==="boolean")g[e++]=s?St:gt;else if(s instanceof Uint8Array||s instanceof ArrayBuffer)g[e++]=Et;else if(s&&s.type==="int64")g[e++]=_t;else if(s&&s.type==="double")g[e++]=bt;else if(s&&s.type==="timetag")g[e++]=Tt;else throw s==null?new Error(`OSC argument at index ${t} is ${s}`):new Error(`Unknown OSC argument type at index ${t}: ${r}`)}for(g[e++]=0;e&3;)g[e++]=0;return e}function ue(i,e){let t=typeof i;if(t==="number")return Number.isInteger(i)?(b.setInt32(e,i,!1),e+4):(b.setFloat32(e,i,!1),e+4);if(t==="string")return wt(i,e);if(t==="boolean")return e;if(i instanceof Uint8Array){let s=i.length;for(b.setUint32(e,s,!1),e+=4,g.set(i,e),e+=s;e&3;)g[e++]=0;return e}return i instanceof ArrayBuffer?ue(new Uint8Array(i),e):i&&i.type==="int64"?(b.setBigInt64(e,BigInt(i.value),!1),e+8):i&&i.type==="double"?(b.setFloat64(e,i.value,!1),e+8):i&&i.type==="timetag"?fe(i.value,e):e}function fe(i,e){if(i===1||i===null||i===void 0)return b.setUint32(e,0,!1),b.setUint32(e+4,1,!1),e+8;if(Array.isArray(i)){if(i.length!==2)throw new Error(`TimeTag array must have exactly 2 elements [seconds, fraction], got ${i.length}`);return b.setUint32(e,i[0]>>>0,!1),b.setUint32(e+4,i[1]>>>0,!1),e+8}if(typeof i!="number")throw new TypeError(`TimeTag must be a number, array, null, or undefined, got ${typeof i}`);i>1&&i<le&&console.warn(`TimeTag ${i} looks like a Unix timestamp (< NTP_EPOCH_OFFSET). Did you mean to add NTP_EPOCH_OFFSET (2208988800)?`);let t=i>>>0,s=(i-Math.floor(i))*U>>>0;return b.setUint32(e,t,!1),b.setUint32(e+4,s,!1),e+8}function X(i){return i instanceof Uint8Array||(i=new Uint8Array(i)),i[0]===35&&i[1]===98?Ct(i):Mt(i)}function Mt(i){i instanceof Uint8Array||(i=new Uint8Array(i));let e=new DataView(i.buffer,i.byteOffset,i.byteLength),t=0,[s,r]=De(i,t);if(t=r,t>=i.length||i[t]!==dt)return[s];let[n,o]=De(i,t);t=o;let a=[s];for(let c=1;c<n.length;c++)switch(n.charCodeAt(c)){case pt:a.push(e.getInt32(t,!1)),t+=4;break;case mt:a.push(e.getFloat32(t,!1)),t+=4;break;case yt:let[f,u]=De(i,t);a.push(f),t=u;break;case Et:let d=e.getUint32(t,!1);t+=4,a.push(i.slice(t,t+d)),t+=d,t=t+3&-4;break;case _t:a.push(e.getBigInt64(t,!1)),t+=8;break;case bt:a.push(e.getFloat64(t,!1)),t+=8;break;case St:a.push(!0);break;case gt:a.push(!1);break;case Tt:let m=e.getUint32(t,!1),p=e.getUint32(t+4,!1);a.push(m+p/U),t+=8;break}return a}function Ct(i){i instanceof Uint8Array||(i=new Uint8Array(i));let e=new DataView(i.buffer,i.byteOffset,i.byteLength),t=8,s=e.getUint32(t,!1),r=e.getUint32(t+4,!1),n=s+r/U;t+=8;let o=[];for(;t<i.length;){let a=e.getUint32(t,!1);if(t+=4,a>0&&t+a<=i.length){let c=i.subarray(t,t+a);o.push(X(c))}t+=a}return{timeTag:n,packets:o}}function De(i,e){let t=e;for(;t<i.length&&i[t]!==0;)t++;let s=qs.decode(i.subarray(e,t));return t++,t=t+3&-4,[s,t]}function R(i){return i.slice()}function Zs(i,e,t,s){let r=q(i,e);return t.set(r,s),r.length}function Xs(i,e,t,s){let r=Z(i,e);return t.set(r,s),r.length}function Ks(){V.clear()}function Qs(){return{stringCacheSize:V.size,maxSize:ht}}function Ot(i){return!i||i.length<8?!1:i[0]===35&&i[1]===98}function js(i){if(!Ot(i))return null;let e=new DataView(i.buffer,i.byteOffset,i.byteLength),t=e.getUint32(8,!1),s=e.getUint32(12,!1);return t+s/U}var Rt={totalPages:1280,ringBufferReserved:3145728,bufferPoolOffset:19922944,bufferPoolSize:63963136,get totalMemory(){return this.bufferPoolOffset+this.bufferPoolSize},get wasmHeapSize(){return this.bufferPoolOffset-this.ringBufferReserved}};var It={numBuffers:1024,maxNodes:1024,maxGraphDefs:1024,maxWireBufs:64,numAudioBusChannels:128,numInputBusChannels:2,numOutputBusChannels:2,numControlBusChannels:4096,bufLength:128,realTimeMemorySize:8192,numRGens:64,realTime:!1,memoryLocking:!1,loadGraphDefs:0,preferredSampleRate:0,verbosity:0};var Dt=class i{static osc={encodeMessage:(e,t)=>R(q(e,t)),encodeBundle:(e,t)=>R(Z(e,t)),decode:e=>X(e),encodeSingleBundle:(e,t,s)=>R(ke(e,t,s)),readTimetag:e=>me(e),ntpNow:()=>H(),NTP_EPOCH_OFFSET:le,encode:e=>{if(e.timeTag!==void 0){let t;if(e.timeTag.raw){let[r,n]=e.timeTag.raw;t=r+n/U}else typeof e.timeTag=="number"?t=e.timeTag:t=1;let s=e.packets.map(r=>{let n=(r.args||[]).map(o=>o&&typeof o=="object"&&"value"in o?o.value:o);return[r.address,...n]});return R(Z(t,s))}else{let t=(e.args||[]).map(s=>s&&typeof s=="object"&&"value"in s?s.value:s);return R(q(e.address,t))}}};static inspect(e){return lt(e)}static#r=null;static getMetricsSchema(){return this.#r??={metrics:{scsynthProcessCount:{offset:0,type:"counter",unit:"count",description:"Audio process() calls"},scsynthMessagesProcessed:{offset:1,type:"counter",unit:"count",description:"OSC messages processed by scsynth"},scsynthMessagesDropped:{offset:2,type:"counter",unit:"count",description:"Messages dropped (ring buffer full)"},scsynthSchedulerDepth:{offset:3,type:"gauge",unit:"count",description:"Current scheduler queue depth"},scsynthSchedulerPeakDepth:{offset:4,type:"gauge",unit:"count",description:"Peak scheduler queue depth (high water mark)"},scsynthSchedulerDropped:{offset:5,type:"counter",unit:"count",description:"Scheduled events dropped"},scsynthSequenceGaps:{offset:6,type:"counter",unit:"count",description:"Messages lost in transit from JS to scsynth"},scsynthWasmErrors:{offset:7,type:"counter",unit:"count",description:"WASM execution errors in audio worklet"},scsynthSchedulerLates:{offset:8,type:"counter",unit:"count",description:"Bundles executed after their scheduled time"},preschedulerPending:{offset:9,type:"gauge",unit:"count",description:"Events waiting to be scheduled"},preschedulerPendingPeak:{offset:10,type:"gauge",unit:"count",description:"Peak pending events"},preschedulerBundlesScheduled:{offset:11,type:"counter",unit:"count",description:"Bundles scheduled"},preschedulerDispatched:{offset:12,type:"counter",unit:"count",description:"Events sent to worklet"},preschedulerEventsCancelled:{offset:13,type:"counter",unit:"count",description:"Events cancelled"},preschedulerMinHeadroomMs:{offset:14,type:"gauge",unit:"ms",description:"Smallest time gap between JS prescheduler dispatch and scsynth scheduler execution"},preschedulerLates:{offset:15,type:"counter",unit:"count",description:"Bundles dispatched after their scheduled execution time"},preschedulerRetriesSucceeded:{offset:16,type:"counter",unit:"count",description:"Retries that succeeded"},preschedulerRetriesFailed:{offset:17,type:"counter",unit:"count",description:"Retries that failed"},preschedulerRetryQueueSize:{offset:18,type:"gauge",unit:"count",description:"Current retry queue size"},preschedulerRetryQueuePeak:{offset:19,type:"gauge",unit:"count",description:"Peak retry queue size"},preschedulerMessagesRetried:{offset:20,type:"counter",unit:"count",description:"Messages that needed retry"},preschedulerTotalDispatches:{offset:21,type:"counter",unit:"count",description:"Total dispatch attempts"},preschedulerBypassed:{offset:22,type:"counter",unit:"count",description:"Messages sent directly from JS to scsynth, bypassing prescheduler (aggregate)"},preschedulerMaxLateMs:{offset:23,type:"gauge",unit:"ms",description:"Maximum lateness at prescheduler (ms)"},oscOutMessagesSent:{offset:24,type:"counter",unit:"count",description:"OSC messages sent from JS to scsynth"},oscOutBytesSent:{offset:25,type:"counter",unit:"bytes",description:"Total bytes sent from JS to scsynth"},oscInMessagesReceived:{offset:26,type:"counter",unit:"count",description:"OSC replies received from scsynth to JS"},oscInBytesReceived:{offset:27,type:"counter",unit:"bytes",description:"Total bytes received from scsynth to JS"},oscInMessagesDropped:{offset:28,type:"counter",unit:"count",description:"Replies lost in transit from scsynth to JS"},oscInCorrupted:{offset:29,type:"counter",unit:"count",description:"Corrupted messages detected from scsynth to JS"},debugMessagesReceived:{offset:30,type:"counter",unit:"count",description:"Debug messages from scsynth"},debugBytesReceived:{offset:31,type:"counter",unit:"bytes",description:"Debug bytes received"},inBufferUsedBytes:{offset:32,type:"gauge",unit:"bytes",description:"Bytes used in IN ring buffer"},outBufferUsedBytes:{offset:33,type:"gauge",unit:"bytes",description:"Bytes used in OUT ring buffer"},debugBufferUsedBytes:{offset:34,type:"gauge",unit:"bytes",description:"Bytes used in DEBUG ring buffer"},inBufferPeakBytes:{offset:35,type:"gauge",unit:"bytes",description:"Peak bytes used in IN ring buffer"},outBufferPeakBytes:{offset:36,type:"gauge",unit:"bytes",description:"Peak bytes used in OUT ring buffer"},debugBufferPeakBytes:{offset:37,type:"gauge",unit:"bytes",description:"Peak bytes used in DEBUG ring buffer"},bypassNonBundle:{offset:38,type:"counter",unit:"count",description:"Plain OSC messages (not bundles) that bypassed prescheduler"},bypassImmediate:{offset:39,type:"counter",unit:"count",description:"Bundles with timetag 0 or 1 that bypassed prescheduler"},bypassNearFuture:{offset:40,type:"counter",unit:"count",description:"Bundles within bypass lookahead threshold that bypassed prescheduler"},bypassLate:{offset:41,type:"counter",unit:"count",description:"Timestamped OSC bundles arriving late into SuperSonic bypassing prescheduler"},scsynthSchedulerMaxLateMs:{offset:42,type:"gauge",unit:"ms",description:"Maximum lateness observed in scsynth scheduler (ms)"},scsynthSchedulerLastLateMs:{offset:43,type:"gauge",unit:"ms",description:"Most recent late magnitude in scsynth scheduler (ms)"},scsynthSchedulerLastLateTick:{offset:44,type:"gauge",unit:"count",description:"Process count when last scsynth late occurred"},ringBufferDirectWriteFails:{offset:45,type:"counter",unit:"count",description:"SAB mode only: optimistic direct writes attempted but failed due to ring buffer lock not being available (delivered via prescheduler instead)"},driftOffsetMs:{offset:46,type:"gauge",unit:"ms",signed:!0,description:"Clock drift between AudioContext and wall clock"},globalOffsetMs:{offset:47,type:"gauge",unit:"ms",signed:!0,description:"Global timing offset for multi-system sync"},audioContextState:{offset:48,type:"enum",values:["unknown","running","suspended","closed","interrupted"],description:"AudioContext state"},bufferPoolUsedBytes:{offset:49,type:"gauge",unit:"bytes",description:"Buffer pool bytes used"},bufferPoolAvailableBytes:{offset:50,type:"gauge",unit:"bytes",description:"Buffer pool bytes available"},bufferPoolAllocations:{offset:51,type:"counter",unit:"count",description:"Total buffer allocations"},loadedSynthDefs:{offset:52,type:"gauge",unit:"count",description:"Number of loaded synthdefs"},scsynthSchedulerCapacity:{offset:53,type:"constant",unit:"count",description:"Maximum scheduler queue size"},preschedulerCapacity:{offset:54,type:"constant",unit:"count",description:"Maximum pending events in prescheduler"},inBufferCapacity:{offset:55,type:"constant",unit:"bytes",description:"IN ring buffer capacity"},outBufferCapacity:{offset:56,type:"constant",unit:"bytes",description:"OUT ring buffer capacity"},debugBufferCapacity:{offset:57,type:"constant",unit:"bytes",description:"DEBUG ring buffer capacity"},mode:{offset:58,type:"enum",values:["sab","postMessage"],description:"Transport mode"}},layout:{panels:[{title:"OSC Out",rows:[{label:"sent",cells:[{key:"oscOutMessagesSent"}]},{label:"bytes",cells:[{key:"oscOutBytesSent",kind:"muted",format:"bytes"}]},{label:"bypass",cells:[{key:"preschedulerBypassed",kind:"green"}]},{label:"lost",cells:[{key:"scsynthSequenceGaps",kind:"error"}]}]},{title:"Bypass",rows:[{label:"msg",cells:[{key:"bypassNonBundle",kind:"muted"}]},{label:"imm",cells:[{key:"bypassImmediate",kind:"muted"}]},{label:"near",cells:[{key:"bypassNearFuture",kind:"muted"}]},{label:"late",cells:[{key:"bypassLate",kind:"muted"}]}]},{title:"OSC In",rows:[{label:"received",cells:[{key:"oscInMessagesReceived"}]},{label:"bytes",cells:[{key:"oscInBytesReceived",kind:"muted",format:"bytes"}]},{label:"dropped",cells:[{key:"oscInMessagesDropped",kind:"error"}]},{label:"corrupted",cells:[{key:"oscInCorrupted",kind:"error"}]}]},{title:"Presched Flow",rows:[{label:"pending",cells:[{key:"preschedulerPending"},{sep:" | "},{key:"preschedulerPendingPeak",kind:"muted"}]},{label:"scheduled",cells:[{key:"preschedulerBundlesScheduled"}]},{label:"dispatched",cells:[{key:"preschedulerDispatched",kind:"dim"}]},{label:"min slack",cells:[{key:"preschedulerMinHeadroomMs",kind:"dim",format:"headroom"},{text:" ms",kind:"muted"}]}]},{title:"Presched Health",rows:[{label:"lates",cells:[{key:"preschedulerLates",kind:"error"},{sep:" ("},{key:"preschedulerMaxLateMs",kind:"dim"},{text:"ms max)",kind:"muted"}]},{label:"cancelled",cells:[{key:"preschedulerEventsCancelled",kind:"error"}]},{label:"retried",cells:[{key:"preschedulerMessagesRetried",kind:"dim"},{sep:" | "},{key:"preschedulerRetriesSucceeded",kind:"green"},{sep:" | "},{key:"preschedulerRetriesFailed",kind:"error"}]},{label:"retry queue",cells:[{key:"preschedulerRetryQueueSize"},{sep:" | "},{key:"preschedulerRetryQueuePeak",kind:"muted"}]}]},{title:"scsynth Scheduler",rows:[{label:"queue",cells:[{key:"scsynthSchedulerDepth"},{sep:" | "},{key:"scsynthSchedulerPeakDepth",kind:"muted"}]},{label:"dropped",cells:[{key:"scsynthSchedulerDropped",kind:"error"}]},{label:"lates",cells:[{key:"scsynthSchedulerLates",kind:"error"}]},{label:"max | last",cells:[{key:"scsynthSchedulerMaxLateMs",kind:"error"},{sep:" | "},{key:"scsynthSchedulerLastLateMs",kind:"dim"},{text:" ms",kind:"muted"}]}]},{title:"scsynth",rows:[{label:"processed",cells:[{key:"scsynthMessagesProcessed"}]},{label:"dropped",cells:[{key:"scsynthMessagesDropped",kind:"error"}]},{label:"synthdefs",cells:[{key:"loadedSynthDefs"}]},{label:"clock drift",cells:[{key:"driftOffsetMs",format:"signed"},{text:"ms",kind:"muted"}]}]},{title:"Ring Buffer Level",class:"wide",rows:[{type:"bar",label:"in",usedKey:"inBufferUsedBytes",peakKey:"inBufferPeakBytes",capacityKey:"inBufferCapacity",color:"blue"},{type:"bar",label:"out",usedKey:"outBufferUsedBytes",peakKey:"outBufferPeakBytes",capacityKey:"outBufferCapacity",color:"green"},{type:"bar",label:"dbg",usedKey:"debugBufferUsedBytes",peakKey:"debugBufferPeakBytes",capacityKey:"debugBufferCapacity",color:"purple"},{label:"direct write fails",cells:[{key:"ringBufferDirectWriteFails",kind:"error"}]}]},{title:"AudioWorklet",rows:[{label:"audio",cells:[{key:"audioContextState",kind:"green",format:"enum"}]},{label:"ticks",cells:[{key:"scsynthProcessCount",kind:"dim"}]},{label:"WASM errors",cells:[{key:"scsynthWasmErrors",kind:"error"}]},{label:"debug",cells:[{key:"debugMessagesReceived",kind:"muted"},{text:" ("},{key:"debugBytesReceived",kind:"muted",format:"bytes"},{text:")"}]}]},{title:"Audio Buffers",rows:[{label:"used",cells:[{key:"bufferPoolUsedBytes",format:"bytes"}]},{label:"free",cells:[{key:"bufferPoolAvailableBytes",kind:"green",format:"bytes"}]},{label:"allocs",cells:[{key:"bufferPoolAllocations",kind:"dim"}]}]}]},sentinels:{HEADROOM_UNSET:4294967295}}}static getTreeSchema(){return{nodeCount:{type:"number",description:"Total nodes in tree"},version:{type:"number",description:"Increments on any tree change, useful for detecting updates"},droppedCount:{type:"number",description:"Nodes that exceeded mirror capacity (tree may be incomplete)"},root:{type:"object",description:"Root node of the tree (always a group with id 0)",schema:{id:{type:"number",description:"Unique node ID"},type:{type:"string",values:["group","synth"],description:"Node type"},defName:{type:"string",description:"Synthdef name (synths only, empty for groups)"},children:{type:"array",description:"Child nodes (recursive)",itemSchema:"(self)"}}}}}static getRawTreeSchema(){return{nodeCount:{type:"number",description:"Total nodes in tree"},version:{type:"number",description:"Increments on any tree change, useful for detecting updates"},droppedCount:{type:"number",description:"Nodes that exceeded mirror capacity (tree may be incomplete)"},nodes:{type:"array",description:"Flat array of all nodes with internal linkage pointers",itemSchema:{id:{type:"number",description:"Unique node ID"},parentId:{type:"number",description:"Parent node ID (-1 for root)"},isGroup:{type:"boolean",description:"True if group, false if synth"},prevId:{type:"number",description:"Previous sibling node ID (-1 if none)"},nextId:{type:"number",description:"Next sibling node ID (-1 if none)"},headId:{type:"number",description:"First child node ID (groups only, -1 if empty)"},defName:{type:"string",description:"Synthdef name (synths only, empty for groups)"}}}}}#e;#t;#h=null;#n;#s;#c;#a;#o;#l;#u;#p;#_;#m;#d;#E;#b;#g;#i;#f;#y;#S;#A;#w;#M=null;#B=null;#N=0;#C=[];#O=null;#v(e){let t=(s,r,{min:n,max:o,allowZero:a=!0}={})=>{if(typeof r!="number"||!Number.isFinite(r))throw new Error(`scsynthOptions.${s} must be a finite number, got: ${r}`);if(!a&&r===0)throw new Error(`scsynthOptions.${s} must be non-zero, got: ${r}`);if(n!==void 0&&r<n)throw new Error(`scsynthOptions.${s} must be >= ${n}, got: ${r}`);if(o!==void 0&&r>o)throw new Error(`scsynthOptions.${s} must be <= ${o}, got: ${r}`)};if(t("numBuffers",e.numBuffers,{min:1,max:65535}),t("maxNodes",e.maxNodes,{min:1}),t("maxGraphDefs",e.maxGraphDefs,{min:1}),t("maxWireBufs",e.maxWireBufs,{min:1}),t("numAudioBusChannels",e.numAudioBusChannels,{min:1}),t("numInputBusChannels",e.numInputBusChannels,{min:0}),t("numOutputBusChannels",e.numOutputBusChannels,{min:1}),t("numControlBusChannels",e.numControlBusChannels,{min:1}),e.bufLength!==128)throw new Error(`scsynthOptions.bufLength must be 128 (WebAudio API constraint), got: ${e.bufLength}`);if(t("realTimeMemorySize",e.realTimeMemorySize,{min:1}),t("numRGens",e.numRGens,{min:1}),typeof e.realTime!="boolean")throw new Error(`scsynthOptions.realTime must be a boolean, got: ${typeof e.realTime}`);if(typeof e.memoryLocking!="boolean")throw new Error(`scsynthOptions.memoryLocking must be a boolean, got: ${typeof e.memoryLocking}`);if(e.loadGraphDefs!==0&&e.loadGraphDefs!==1)throw new Error(`scsynthOptions.loadGraphDefs must be 0 or 1, got: ${e.loadGraphDefs}`);if(t("preferredSampleRate",e.preferredSampleRate,{min:0,max:384e3}),e.preferredSampleRate!==0&&e.preferredSampleRate<8e3)throw new Error(`scsynthOptions.preferredSampleRate must be 0 (auto) or >= 8000, got: ${e.preferredSampleRate}`);t("verbosity",e.verbosity,{min:0,max:4})}constructor(e={}){this.#m=!1,this.#d=!1,this.#E=null,this.#b={},this.#g=null,this.#f=new se,this.#y=new re({mode:e.mode||"postMessage"}),this.#A=new oe({}),this.#e=null,this.#t=null,this.#n=null,this.#c=null,this.loadedSynthDefs=new Map;let t=e.baseURL||null,s=e.coreBaseURL||t,r=e.workerBaseURL||(s?`${s}workers/`:null),n=e.wasmBaseURL||(s?`${s}wasm/`:null);if(!r||!n)throw new Error(`SuperSonic requires explicit URL configuration.
|
|
6
6
|
|
|
7
7
|
For CDN usage:
|
|
8
8
|
import { SuperSonic } from 'https://unpkg.com/supersonic-scsynth@VERSION/dist/supersonic.js';
|
|
@@ -11,6 +11,6 @@ For CDN usage:
|
|
|
11
11
|
For local usage:
|
|
12
12
|
new SuperSonic({ baseURL: '/path/to/supersonic/dist/' })
|
|
13
13
|
|
|
14
|
-
See: https://github.com/samaaron/supersonic#configuration`);let o={...It,...e.scsynthOptions};this.#N(o);let a=e.mode||"postMessage";this.#r={mode:a,snapshotIntervalMs:e.snapshotIntervalMs??150,wasmUrl:e.wasmUrl||n+"scsynth-nrt.wasm",wasmBaseURL:n,workletUrl:e.workletUrl||r+"scsynth_audio_worklet.js",workerBaseURL:r,audioContext:e.audioContext||null,autoConnect:e.autoConnect!==!1,audioContextOptions:{latencyHint:"interactive",sampleRate:48e3,...e.audioContextOptions},memory:Ot,worldOptions:o,preschedulerCapacity:e.preschedulerCapacity||65536,bypassLookaheadMs:e.bypassLookaheadMs??500,activityEvent:{maxLineLength:e.activityEvent?.maxLineLength??200,scsynthMaxLineLength:e.activityEvent?.scsynthMaxLineLength??null,oscInMaxLineLength:e.activityEvent?.oscInMaxLineLength??null,oscOutMaxLineLength:e.activityEvent?.oscOutMaxLineLength??null},debug:e.debug??!1,debugScsynth:e.debugScsynth??!1,debugOscIn:e.debugOscIn??!1,debugOscOut:e.debugOscOut??!1,activityConsoleLog:{maxLineLength:e.activityConsoleLog?.maxLineLength??200,scsynthMaxLineLength:e.activityConsoleLog?.scsynthMaxLineLength??null,oscInMaxLineLength:e.activityConsoleLog?.oscInMaxLineLength??null,oscOutMaxLineLength:e.activityConsoleLog?.oscOutMaxLineLength??null}},this.#c=e.sampleBaseURL||(t?`${t}samples/`:null),this.#a=e.synthdefBaseURL||(t?`${t}synthdefs/`:null),this.#u={maxRetries:e.fetchMaxRetries??3,baseDelay:e.fetchRetryDelay??1e3},this.#p=new ee({onLoadingEvent:(c,u)=>this.#l.emit(c,u),maxRetries:this.#u.maxRetries,baseDelay:this.#u.baseDelay}),this.bootStats={initStartTime:null,initDuration:null}}get initialized(){return this.#m}get initializing(){return this.#y}get mode(){return this.#r.mode}get bufferConstants(){return this.#g.bufferConstants}get ringBufferBase(){return this.#g.ringBufferBase}get sharedBuffer(){return this.#g.sharedBuffer}get node(){return this.#n}get osc(){return this.#i}on(e,t){return this.#l.on(e,t)}off(e,t){return this.#l.off(e,t),this}once(e,t){return this.#l.once(e,t),this}removeAllListeners(e){return this.#l.removeAllListeners(e),this}async init(){if(!this.#m)return this.#d?this.#d:(this.#d=this.#k(),this.#d)}async#k(){this.#y=!0,this.bootStats.initStartTime=performance.now();try{this.#z(),this.#G(),this.#C(),this.#$(),this.#O();let e=await this.#I();await this.#D(e),await this.#L(),await this.#x()}catch(e){throw this.#y=!1,this.#d=null,console.error("[SuperSonic] Initialization failed:",e),this.#l.emit("error",e),e}}getMetrics(){return this.#P()}getSnapshot(){let e=this.#P(),t=i.getMetricsSchema()||{},s={};for(let[n,o]of Object.entries(e)){let a=t[n];a?.description?s[n]={value:o,description:a.description}:s[n]={value:o}}let r=null;return typeof performance<"u"&&performance.memory&&(r={usedJSHeapSize:performance.memory.usedJSHeapSize,totalJSHeapSize:performance.memory.totalJSHeapSize,jsHeapSizeLimit:performance.memory.jsHeapSizeLimit}),{timestamp:new Date().toISOString(),metrics:s,nodeTree:this.getRawTree(),memory:r}}setGlobalOffset(e){this.#_("set global offset"),this.#E?.setGlobalOffset(e)}async recover(){return this.#m?await this.resume()?!0:await this.reload():!1}async resume(){if(!this.#m||!this.#t)return!1;await this.purge();try{await this.#t.resume()}catch{}this.#E?.startDriftTimer();let e=this.#F();if(e===null){let r=this.#t.state==="running";return r&&(this.#E?.resync(),this.#l.emit("resumed")),r}await new Promise(r=>setTimeout(r,200));let t=this.#F(),s=t!==null&&t>e;return s&&(this.#E?.resync(),this.#l.emit("resumed")),s}async suspend(){if(this.#m){this.#E?.stopDriftTimer();try{await this.#t?.suspend()}catch{}}}async reload(){if(!this.#m)return!1;this.#l.emit("reload:start");let e=new Map(this.loadedSynthDefs),t=this.#s?.getAllocatedBuffers()||[];await this.#v(),await this.#H();for(let[s,r]of e)try{await this.send("/d_recv",r)}catch(n){console.error(`[SuperSonic] Failed to restore synthdef ${s}:`,n)}for(let s of t)try{if(this.#r.mode==="postMessage"&&s.source)s.source.type==="file"&&await this.loadSample(s.bufnum,s.source.path,s.source.startFrame||0,s.source.numFrames||0);else{let r=crypto.randomUUID();await this.send("/b_allocPtr",s.bufnum,s.ptr,s.numFrames,s.numChannels,s.sampleRate,r)}}catch(r){console.error(`[SuperSonic] Failed to restore buffer ${s.bufnum}:`,r)}return(e.size>0||t.length>0)&&await this.sync(),this.#l.emit("reload:complete",{success:!0}),!0}async#v(){this.#E?.stopDriftTimer(),this.#o?.clear(),this.#o=null,this.#i&&(this.#i.cancelAll(),this.#i.dispose(),this.#i=null),this.#e&&(this.#e.disconnect(),this.#e=null),this.#t&&(await this.#t.close(),this.#t=null),this.#m=!1,this.loadedSynthDefs.clear(),this.#d=null,this.#w=null,this.#E?.reset()}async#H(){this.#y=!0,this.bootStats.initStartTime=performance.now();try{this.#C(),this.#s&&this.#s.updateAudioContext(this.#t),this.#O();let e=await this.#I();await this.#D(e),await this.#L(),await this.#x()}catch(e){throw this.#y=!1,this.#d=null,console.error("[SuperSonic] Partial init failed:",e),this.#l.emit("error",e),e}}getRawTree(){if(!this.#m)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};let e=this.#g.bufferConstants;if(!e)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};let t,s;if(this.#r.mode==="postMessage"){let r=this.#g.getSnapshotBuffer();if(!r)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};t=r,s=e.METRICS_SIZE}else{let r=this.#g.sharedBuffer;if(!r)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};t=r,s=this.#g.ringBufferBase+e.NODE_TREE_START}return lt(t,s,e)}getTree(){let e=this.getRawTree(),t=n=>({id:n.id,type:n.isGroup?"group":"synth",defName:n.defName,children:[]}),s=new Map;for(let n of e.nodes)s.set(n.id,t(n));let r=null;for(let n of e.nodes){let o=s.get(n.id);if(n.parentId===-1||n.parentId===0&&n.id===0)r=o;else{let a=s.get(n.parentId);a&&a.children.push(o)}}return{nodeCount:e.nodeCount,version:e.version,droppedCount:e.droppedCount,root:r||{id:0,type:"group",defName:"",children:[]}}}startCapture(){this.#_("start capture"),this.#T.start()}stopCapture(){return this.#_("stop capture"),this.#T.stop()}isCaptureEnabled(){return this.#T.isEnabled()}getCaptureFrames(){return this.#T.getFrameCount()}getMaxCaptureDuration(){return this.#T.getMaxDuration()}async send(e,...t){this.#_("send OSC messages");let s={"/d_load":"Use loadSynthDef() or send /d_recv with synthdef bytes instead.","/d_loadDir":"Use loadSynthDef() or send /d_recv with synthdef bytes instead.","/b_read":"Use loadSample() to load audio into a buffer.","/b_readChannel":"Use loadSample() to load audio into a buffer.","/b_write":"Writing audio files is not available in the browser.","/b_close":"Writing audio files is not available in the browser.","/clearSched":"Use purge() to clear both the JS prescheduler and WASM scheduler.","/error":"SuperSonic always enables error notifications so you never miss a /fail message."};if(s[e])throw new Error(`${e} is not supported in SuperSonic. ${s[e]}`);if(e==="/d_recv"){let o=t[0];if(o instanceof Uint8Array||o instanceof ArrayBuffer){let a=o instanceof ArrayBuffer?new Uint8Array(o):o,c=D(a)||"unknown";this.loadedSynthDefs.set(c,a)}}if(e==="/d_free")for(let o of t)typeof o=="string"&&this.loadedSynthDefs.delete(o);else e==="/d_freeAll"&&this.loadedSynthDefs.clear();let r=t.map(o=>o instanceof ArrayBuffer?new Uint8Array(o):o),n=i.osc.encodeMessage(e,r);if(this.#r.debug||this.#r.debugOscOut){let o=this.#r.activityConsoleLog.oscOutMaxLineLength??this.#r.activityConsoleLog.maxLineLength,a=t.map(c=>{if(c instanceof Uint8Array||c instanceof ArrayBuffer)return`<${c.byteLength||c.length} bytes>`;let u=JSON.stringify(c);return u.length>o?u.slice(0,o)+"...":u}).join(", ");console.log(`[OSC \u2192] ${e}${a?" "+a:""}`)}return this.sendOSC(n)}async sendOSC(e,t={}){this.#_("send OSC data");let s=this.#Z(e),r=await this.#K(s),n=this.#w.classify(r);if(Q(n))this.#r.mode==="sab"?this.#w.send(r):this.#i.sendImmediate(r,n);else{let o=this.#g.bufferConstants?.scheduler_slot_size;if(o&&r.length>o)throw new Error(`OSC bundle too large to schedule (${r.length} > ${o} bytes). Use immediate timestamp (0 or 1) for large messages, or reduce bundle size.`);this.#i.sendWithOptions(r,t)}}cancelTag(e){this.#_("cancel by tag"),this.#i.cancelTag(e)}cancelSession(e){this.#_("cancel by session"),this.#i.cancelSession(e)}cancelSessionTag(e,t){this.#_("cancel by session and tag"),this.#i.cancelSessionTag(e,t)}cancelAll(){this.#_("cancel all scheduled"),this.#i.cancelAll()}async purge(){this.#_("purge");let e=this.#i.cancelAllWithAck(),t=new Promise(s=>{let r=n=>{n.data.type==="clearSchedAck"&&(this.#e.port.removeEventListener("message",r),s())};this.#e.port.addEventListener("message",r),this.#e.port.postMessage({type:"clearSched",ack:!0})});await Promise.all([e,t])}createOscChannel(){return this.#_("create OSC channel"),this.#i.createOscChannel()}async loadSynthDef(e){this.#_("load synthdef");let t,s;if(typeof e=="string"){let r;if(this.#q(e))r=e;else{if(!this.#a)throw new Error("synthdefBaseURL not configured.");r=`${this.#a}${e}.scsyndef`}let n=D(r),o=await this.#p.fetch(r,{type:"synthdef",name:n});t=new Uint8Array(o),s=D(t)||n}else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){if(t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=D(t),!s)throw new Error("Could not extract synthdef name from binary data. Make sure it's a valid .scsyndef file.")}else if(e instanceof Blob){let r=await e.arrayBuffer();if(t=new Uint8Array(r),s=D(t),!s)throw new Error("Could not extract synthdef name from file. Make sure it's a valid .scsyndef file.")}else throw new Error("loadSynthDef source must be a name, path/URL string, ArrayBuffer, Uint8Array, or File/Blob");return await this.send("/d_recv",t),{name:s,size:t.length}}async loadSynthDefs(e){this.#_("load synthdefs");let t={};return await Promise.all(e.map(async s=>{try{await this.loadSynthDef(s),t[s]={success:!0}}catch(r){t[s]={success:!1,error:r.message}}})),t}async loadSample(e,t,s=0,r=0){this.#_("load samples");let n;if(typeof t=="string")n=await this.#s.prepareFromFile({bufnum:e,path:t,startFrame:s,numFrames:r});else if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))n=await this.#s.prepareFromBlob({bufnum:e,blob:t,startFrame:s,numFrames:r});else if(t instanceof Blob){let o=await t.arrayBuffer();n=await this.#s.prepareFromBlob({bufnum:e,blob:o,startFrame:s,numFrames:r})}else throw new Error("loadSample source must be a path/URL string, ArrayBuffer, TypedArray, or File/Blob");return await this.send("/b_allocPtr",e,n.ptr,n.numFrames,n.numChannels,n.sampleRate,n.uuid),n.allocationComplete}getLoadedBuffers(){return this.#_("get loaded buffers"),(this.#s?.getAllocatedBuffers()||[]).map(({bufnum:t,numFrames:s,numChannels:r,sampleRate:n,source:o})=>({bufnum:t,numFrames:s,numChannels:r,sampleRate:n,source:o?.path||o?.name||null,duration:n>0?s/n:0}))}async sync(e=Math.floor(Math.random()*2147483647)){this.#_("sync");let t=new Promise((s,r)=>{let n=setTimeout(()=>{this.#o?.delete(e),r(new Error("Timeout waiting for /synced response"))},1e4),o=()=>{clearTimeout(n),this.#o.delete(e),s()};this.#o||(this.#o=new Map),this.#o.set(e,o)});await this.send("/sync",e),await t,this.#r.mode==="postMessage"&&await new Promise(s=>setTimeout(s,this.#r.snapshotIntervalMs*2))}getInfo(){return this.#_("get info"),{sampleRate:this.#t.sampleRate,numBuffers:this.#r.worldOptions.numBuffers,totalMemory:this.#r.memory.totalMemory,wasmHeapSize:this.#r.memory.wasmHeapSize,bufferPoolSize:this.#r.memory.bufferPoolSize,bootTimeMs:this.bootStats.initDuration,capabilities:{...this.#S},version:this.#b}}async shutdown(){!this.#m&&!this.#y||(this.#l.emit("shutdown"),this.#E?.stopDriftTimer(),this.#o?.clear(),this.#o=null,this.#i&&(this.#i.cancelAll(),this.#i.dispose(),this.#i=null),this.#e&&(this.#e.disconnect(),this.#e=null),this.#t&&(await this.#t.close(),this.#t=null),this.#s&&(this.#s.destroy(),this.#s=null),this.#h=null,this.#w=null,this.#m=!1,this.loadedSynthDefs.clear(),this.#d=null,this.#f=null,this.#E?.reset(),this.bootStats={initStartTime:null,initDuration:null})}async destroy(){this.#l.emit("destroy"),await this.shutdown(),this.#A=null,this.#l.clearAllListeners()}async reset(e={}){await this.shutdown(),await this.init(e)}#z(){this.#S={audioWorklet:typeof AudioWorklet<"u",sharedArrayBuffer:typeof SharedArrayBuffer<"u",crossOriginIsolated:window.crossOriginIsolated===!0,atomics:typeof Atomics<"u",webWorker:typeof Worker<"u"};let e=this.#r.mode,t=["audioWorklet","webWorker"];e==="sab"&&t.push("sharedArrayBuffer","crossOriginIsolated","atomics");let s=t.filter(r=>!this.#S[r]);if(s.length>0){let r=new Error(`Missing required features for ${e} mode: ${s.join(", ")}`);throw e==="sab"&&!this.#S.crossOriginIsolated&&(r.message+=`
|
|
14
|
+
See: https://github.com/samaaron/supersonic#configuration`);let o={...It,...e.scsynthOptions};this.#v(o);let a=e.mode||"postMessage";this.#i={mode:a,snapshotIntervalMs:e.snapshotIntervalMs??150,wasmUrl:e.wasmUrl||n+"scsynth-nrt.wasm",wasmBaseURL:n,workletUrl:e.workletUrl||r+"scsynth_audio_worklet.js",workerBaseURL:r,audioContext:e.audioContext||null,autoConnect:e.autoConnect!==!1,audioContextOptions:{latencyHint:"interactive",sampleRate:48e3,...e.audioContextOptions},memory:Rt,worldOptions:o,preschedulerCapacity:e.preschedulerCapacity||65536,bypassLookaheadMs:e.bypassLookaheadMs??500,activityEvent:{maxLineLength:e.activityEvent?.maxLineLength??200,scsynthMaxLineLength:e.activityEvent?.scsynthMaxLineLength??null,oscInMaxLineLength:e.activityEvent?.oscInMaxLineLength??null,oscOutMaxLineLength:e.activityEvent?.oscOutMaxLineLength??null},debug:e.debug??!1,debugScsynth:e.debugScsynth??!1,debugOscIn:e.debugOscIn??!1,debugOscOut:e.debugOscOut??!1,activityConsoleLog:{maxLineLength:e.activityConsoleLog?.maxLineLength??200,scsynthMaxLineLength:e.activityConsoleLog?.scsynthMaxLineLength??null,oscInMaxLineLength:e.activityConsoleLog?.oscInMaxLineLength??null,oscOutMaxLineLength:e.activityConsoleLog?.oscOutMaxLineLength??null}},this.#l=e.sampleBaseURL||(t?`${t}samples/`:null),this.#u=e.synthdefBaseURL||(t?`${t}synthdefs/`:null),this.#p={maxRetries:e.fetchMaxRetries??3,baseDelay:e.fetchRetryDelay??1e3},this.#_=new ee({onLoadingEvent:(c,l)=>this.#f.emit(c,l),maxRetries:this.#p.maxRetries,baseDelay:this.#p.baseDelay}),this.bootStats={initStartTime:null,initDuration:null}}get initialized(){return this.#m}get initializing(){return this.#d}get mode(){return this.#i.mode}get bufferConstants(){return this.#y.bufferConstants}get ringBufferBase(){return this.#y.ringBufferBase}get sharedBuffer(){return this.#y.sharedBuffer}get node(){return this.#h}get osc(){return this.#n}on(e,t){return this.#f.on(e,t)}off(e,t){return this.#f.off(e,t),this}once(e,t){return this.#f.once(e,t),this}removeAllListeners(e){return this.#f.removeAllListeners(e),this}async init(){if(!this.#m)return this.#E?this.#E:(this.#E=this.#H(),this.#E)}async#H(){this.#d=!0,this.bootStats.initStartTime=performance.now();try{this.#Y(),this.#$(),this.#U(),this.#W(),this.#R();let e=await this.#I();await this.#D(e),await this.#L(),await this.#P()}catch(e){throw this.#d=!1,this.#E=null,console.error("[SuperSonic] Initialization failed:",e),this.#f.emit("error",e),e}}getMetrics(){return this.#k()}getMetricsArray(){return this.#X(),this.#y.getMergedArray()}getSnapshot(){let e=this.#k(),t=i.getMetricsSchema()?.metrics||{},s={};for(let[n,o]of Object.entries(e)){let a=t[n];a?.description?s[n]={value:o,description:a.description}:s[n]={value:o}}let r=null;return typeof performance<"u"&&performance.memory&&(r={usedJSHeapSize:performance.memory.usedJSHeapSize,totalJSHeapSize:performance.memory.totalJSHeapSize,jsHeapSizeLimit:performance.memory.jsHeapSizeLimit}),{timestamp:new Date().toISOString(),metrics:s,nodeTree:this.getRawTree(),memory:r}}setGlobalOffset(e){this.#T("set global offset"),this.#S?.setGlobalOffset(e)}async recover(){return this.#m?await this.resume()?!0:await this.reload():!1}async resume(){if(!this.#m||!this.#e)return!1;await this.purge();try{await this.#e.resume()}catch{}this.#S?.startDriftTimer();let e=this.#x();if(e===null){let r=this.#e.state==="running";return r&&(this.#S?.resync(),this.#f.emit("resumed")),r}await new Promise(r=>setTimeout(r,200));let t=this.#x(),s=t!==null&&t>e;return s&&(this.#S?.resync(),this.#f.emit("resumed")),s}async suspend(){if(this.#m){this.#S?.stopDriftTimer();try{await this.#e?.suspend()}catch{}}}async reload(){if(!this.#m)return!1;this.#f.emit("reload:start");let e=new Map(this.loadedSynthDefs),t=this.#c?.getAllocatedBuffers()||[];await this.#z(),await this.#G();for(let[s,r]of e)try{await this.send("/d_recv",r)}catch(n){console.error(`[SuperSonic] Failed to restore synthdef ${s}:`,n)}for(let s of t)try{if(this.#i.mode==="postMessage"&&s.source)s.source.type==="file"&&await this.loadSample(s.bufnum,s.source.path,s.source.startFrame||0,s.source.numFrames||0);else{let r=crypto.randomUUID();await this.send("/b_allocPtr",s.bufnum,s.ptr,s.numFrames,s.numChannels,s.sampleRate,r)}}catch(r){console.error(`[SuperSonic] Failed to restore buffer ${s.bufnum}:`,r)}return(e.size>0||t.length>0)&&await this.sync(),this.#f.emit("reload:complete",{success:!0}),!0}async#z(){this.#S?.stopDriftTimer(),this.#o?.clear(),this.#o=null,this.#n&&(this.#n.cancelAll(),this.#n.dispose(),this.#n=null),this.#t&&(this.#t.disconnect(),this.#t=null),this.#e&&(await this.#e.close(),this.#e=null),this.#m=!1,this.loadedSynthDefs.clear(),this.#E=null,this.#w=null,this.#S?.reset()}async#G(){this.#d=!0,this.bootStats.initStartTime=performance.now();try{this.#U(),this.#c&&this.#c.updateAudioContext(this.#e),this.#R();let e=await this.#I();await this.#D(e),await this.#L(),await this.#P()}catch(e){throw this.#d=!1,this.#E=null,console.error("[SuperSonic] Partial init failed:",e),this.#f.emit("error",e),e}}getRawTree(){if(!this.#m)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};let e=this.#y.bufferConstants;if(!e)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};let t,s;if(this.#i.mode==="postMessage"){let r=this.#y.getSnapshotBuffer();if(!r)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};t=r,s=e.METRICS_SIZE}else{let r=this.#y.sharedBuffer;if(!r)return{nodeCount:0,version:0,droppedCount:0,nodes:[]};t=r,s=this.#y.ringBufferBase+e.NODE_TREE_START}return ut(t,s,e)}getTree(){let e=this.getRawTree(),t=n=>({id:n.id,type:n.isGroup?"group":"synth",defName:n.defName,children:[]}),s=new Map;for(let n of e.nodes)s.set(n.id,t(n));let r=null;for(let n of e.nodes){let o=s.get(n.id);if(n.parentId===-1||n.parentId===0&&n.id===0)r=o;else{let a=s.get(n.parentId);a&&a.children.push(o)}}return{nodeCount:e.nodeCount,version:e.version,droppedCount:e.droppedCount,root:r||{id:0,type:"group",defName:"",children:[]}}}startCapture(){this.#T("start capture"),this.#A.start()}stopCapture(){return this.#T("stop capture"),this.#A.stop()}isCaptureEnabled(){return this.#A.isEnabled()}getCaptureFrames(){return this.#A.getFrameCount()}getMaxCaptureDuration(){return this.#A.getMaxDuration()}async send(e,...t){this.#T("send OSC messages");let s={"/d_load":"Use loadSynthDef() or send /d_recv with synthdef bytes instead.","/d_loadDir":"Use loadSynthDef() or send /d_recv with synthdef bytes instead.","/b_read":"Use loadSample() to load audio into a buffer.","/b_readChannel":"Use loadSample() to load audio into a buffer.","/b_write":"Writing audio files is not available in the browser.","/b_close":"Writing audio files is not available in the browser.","/clearSched":"Use purge() to clear both the JS prescheduler and WASM scheduler.","/error":"SuperSonic always enables error notifications so you never miss a /fail message."};if(s[e])throw new Error(`${e} is not supported in SuperSonic. ${s[e]}`);if(e==="/d_recv"){let o=t[0];if(o instanceof Uint8Array||o instanceof ArrayBuffer){let a=o instanceof ArrayBuffer?new Uint8Array(o):o,c=v(a)||"unknown";this.loadedSynthDefs.set(c,a)}}if(e==="/d_free")for(let o of t)typeof o=="string"&&this.loadedSynthDefs.delete(o);else e==="/d_freeAll"&&this.loadedSynthDefs.clear();let r=t.map(o=>o instanceof ArrayBuffer?new Uint8Array(o):o),n=i.osc.encodeMessage(e,r);if(this.#i.debug||this.#i.debugOscOut){let o=this.#i.activityConsoleLog.oscOutMaxLineLength??this.#i.activityConsoleLog.maxLineLength,a=t.map(c=>{if(c instanceof Uint8Array||c instanceof ArrayBuffer)return`<${c.byteLength||c.length} bytes>`;let l=JSON.stringify(c);return l.length>o?l.slice(0,o)+"...":l}).join(", ");console.log(`[OSC \u2192] ${e}${a?" "+a:""}`)}return this.sendOSC(n)}async sendOSC(e,t={}){this.#T("send OSC data");let s=this.#Q(e),r=await this.#j(s),n=this.#w.classify(r);if(Q(n))this.#i.mode==="sab"?this.#w.send(r):this.#n.sendImmediate(r,n);else{let o=this.#y.bufferConstants?.scheduler_slot_size;if(o&&r.length>o)throw new Error(`OSC bundle too large to schedule (${r.length} > ${o} bytes). Use immediate timestamp (0 or 1) for large messages, or reduce bundle size.`);this.#n.sendWithOptions(r,t)}}cancelTag(e){this.#T("cancel by tag"),this.#n.cancelTag(e)}cancelSession(e){this.#T("cancel by session"),this.#n.cancelSession(e)}cancelSessionTag(e,t){this.#T("cancel by session and tag"),this.#n.cancelSessionTag(e,t)}cancelAll(){this.#T("cancel all scheduled"),this.#n.cancelAll()}async purge(){this.#T("purge");let e=this.#n.cancelAllWithAck(),t=new Promise(s=>{let r=n=>{n.data.type==="clearSchedAck"&&(this.#t.port.removeEventListener("message",r),s())};this.#t.port.addEventListener("message",r),this.#t.port.postMessage({type:"clearSched",ack:!0})});await Promise.all([e,t])}createOscChannel(){return this.#T("create OSC channel"),this.#n.createOscChannel()}async loadSynthDef(e){this.#T("load synthdef");let t,s;if(typeof e=="string"){let r;if(this.#K(e))r=e;else{if(!this.#u)throw new Error("synthdefBaseURL not configured.");r=`${this.#u}${e}.scsyndef`}let n=v(r),o=await this.#_.fetch(r,{type:"synthdef",name:n});t=new Uint8Array(o),s=v(t)||n}else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){if(t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=v(t),!s)throw new Error("Could not extract synthdef name from binary data. Make sure it's a valid .scsyndef file.")}else if(e instanceof Blob){let r=await e.arrayBuffer();if(t=new Uint8Array(r),s=v(t),!s)throw new Error("Could not extract synthdef name from file. Make sure it's a valid .scsyndef file.")}else throw new Error("loadSynthDef source must be a name, path/URL string, ArrayBuffer, Uint8Array, or File/Blob");return await this.send("/d_recv",t),{name:s,size:t.length}}async loadSynthDefs(e){this.#T("load synthdefs");let t={};return await Promise.all(e.map(async s=>{try{await this.loadSynthDef(s),t[s]={success:!0}}catch(r){t[s]={success:!1,error:r.message}}})),t}async loadSample(e,t,s=0,r=0){this.#T("load samples");let n;if(typeof t=="string")n=await this.#c.prepareFromFile({bufnum:e,path:t,startFrame:s,numFrames:r});else if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))n=await this.#c.prepareFromBlob({bufnum:e,blob:t,startFrame:s,numFrames:r});else if(t instanceof Blob){let o=await t.arrayBuffer();n=await this.#c.prepareFromBlob({bufnum:e,blob:o,startFrame:s,numFrames:r})}else throw new Error("loadSample source must be a path/URL string, ArrayBuffer, TypedArray, or File/Blob");return await this.send("/b_allocPtr",e,n.ptr,n.numFrames,n.numChannels,n.sampleRate,n.uuid),n.allocationComplete}getLoadedBuffers(){return this.#T("get loaded buffers"),(this.#c?.getAllocatedBuffers()||[]).map(({bufnum:t,numFrames:s,numChannels:r,sampleRate:n,source:o})=>({bufnum:t,numFrames:s,numChannels:r,sampleRate:n,source:o?.path||o?.name||null,duration:n>0?s/n:0}))}async sync(e=Math.floor(Math.random()*2147483647)){this.#T("sync");let t=new Promise((s,r)=>{let n=setTimeout(()=>{this.#o?.delete(e),r(new Error("Timeout waiting for /synced response"))},1e4),o=()=>{clearTimeout(n),this.#o.delete(e),s()};this.#o||(this.#o=new Map),this.#o.set(e,o)});await this.send("/sync",e),await t,this.#i.mode==="postMessage"&&await new Promise(s=>setTimeout(s,this.#i.snapshotIntervalMs*2))}getInfo(){return this.#T("get info"),{sampleRate:this.#e.sampleRate,numBuffers:this.#i.worldOptions.numBuffers,totalMemory:this.#i.memory.totalMemory,wasmHeapSize:this.#i.memory.wasmHeapSize,bufferPoolSize:this.#i.memory.bufferPoolSize,bootTimeMs:this.bootStats.initDuration,capabilities:{...this.#b},version:this.#g}}async shutdown(){!this.#m&&!this.#d||(this.#f.emit("shutdown"),this.#S?.stopDriftTimer(),this.#o?.clear(),this.#o=null,this.#n&&(this.#n.cancelAll(),this.#n.dispose(),this.#n=null),this.#t&&(this.#t.disconnect(),this.#t=null),this.#e&&(await this.#e.close(),this.#e=null),this.#c&&(this.#c.destroy(),this.#c=null),this.#a=null,this.#w=null,this.#m=!1,this.loadedSynthDefs.clear(),this.#E=null,this.#s=null,this.#S?.reset(),this.bootStats={initStartTime:null,initDuration:null})}async destroy(){this.#f.emit("destroy"),await this.shutdown(),this.#B=null,this.#f.clearAllListeners()}async reset(e={}){await this.shutdown(),await this.init(e)}#Y(){this.#b={audioWorklet:typeof AudioWorklet<"u",sharedArrayBuffer:typeof SharedArrayBuffer<"u",crossOriginIsolated:window.crossOriginIsolated===!0,atomics:typeof Atomics<"u",webWorker:typeof Worker<"u"};let e=this.#i.mode,t=["audioWorklet","webWorker"];e==="sab"&&t.push("sharedArrayBuffer","crossOriginIsolated","atomics");let s=t.filter(r=>!this.#b[r]);if(s.length>0){let r=new Error(`Missing required features for ${e} mode: ${s.join(", ")}`);throw e==="sab"&&!this.#b.crossOriginIsolated&&(r.message+=`
|
|
15
15
|
|
|
16
|
-
Consider using mode: 'postMessage' which doesn't require COOP/COEP headers.`),r}if(e!=="sab"&&e!=="postMessage")throw new Error(`Invalid mode: '${e}'. Use 'sab' or 'postMessage'.`)}
|
|
16
|
+
Consider using mode: 'postMessage' which doesn't require COOP/COEP headers.`),r}if(e!=="sab"&&e!=="postMessage")throw new Error(`Invalid mode: '${e}'. Use 'sab' or 'postMessage'.`)}#$(){let e=this.#i.memory;this.#i.mode==="sab"?this.#s=new WebAssembly.Memory({initial:e.totalPages,maximum:e.totalPages,shared:!0}):this.#s=null}#U(){this.#i.audioContext?this.#e=this.#i.audioContext:this.#e=new AudioContext(this.#i.audioContextOptions),this.#e.addEventListener("statechange",()=>{let e=this.#e?.state;if(!e)return;let t=this.#M;this.#M=e,e==="running"&&(t==="suspended"||t==="interrupted")&&this.#S?.resync(),this.#f.emit("audiocontext:statechange",{state:e}),e==="suspended"?this.#f.emit("audiocontext:suspended"):e==="running"?this.#f.emit("audiocontext:resumed"):e==="interrupted"&&this.#f.emit("audiocontext:interrupted")})}#W(){let e=this.#i.mode==="sab"?this.#s.buffer:null;this.#c=new J({mode:this.#i.mode,audioContext:this.#e,sharedBuffer:e,bufferPoolConfig:{start:this.#i.memory.bufferPoolOffset,size:this.#i.memory.bufferPoolSize},sampleBaseURL:this.#l,maxBuffers:this.#i.worldOptions.numBuffers,assetLoader:this.#_})}#R(){this.#a=new te({bufferManager:this.#c,getDefaultSampleRate:()=>this.#e?.sampleRate||44100})}async#I(){if(this.#B)return this.#B;let e=this.#i.wasmUrl.split("/").pop();this.#f.emit("loading:start",{type:"wasm",name:e});let t=await fetch(this.#i.wasmUrl);if(!t.ok)throw new Error(`Failed to load WASM: ${t.status} ${t.statusText}`);let s=await t.arrayBuffer();return this.#f.emit("loading:complete",{type:"wasm",name:e,size:s.byteLength}),this.#B=s,s}async#D(e){await ze(this.#e.audioWorklet,this.#i.workletUrl),this.#t=new AudioWorkletNode(this.#e,"scsynth-processor",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2]}),this.#i.autoConnect&&this.#t.connect(this.#e.destination),this.#h=this.#V(),this.#t.port.start(),this.#Z();let t=this.#i.mode,s=t==="sab"?this.#s.buffer:null;this.#t.port.postMessage({type:"init",mode:t,sharedBuffer:s,snapshotIntervalMs:this.#i.snapshotIntervalMs});let r={type:"loadWasm",wasmBytes:e,worldOptions:this.#i.worldOptions,sampleRate:this.#e.sampleRate};t==="sab"?r.wasmMemory=this.#s:r.memoryPages=this.#i.memoryPages||1280,this.#t.port.postMessage(r),await this.#q(),this.#c.setWorkletPort(this.#t.port)}#V(){let e=this.#t;return Object.freeze({connect:(...t)=>e.connect(...t),disconnect:(...t)=>e.disconnect(...t),get context(){return e.context},get numberOfOutputs(){return e.numberOfOutputs},get numberOfInputs(){return e.numberOfInputs},get channelCount(){return e.channelCount},get input(){return e}})}async#L(){let e=this.#i.mode,t=this.#y.bufferConstants,s=this.#y.ringBufferBase,r=this.#y.sharedBuffer,n={workerBaseURL:this.#i.workerBaseURL,preschedulerCapacity:this.#i.preschedulerCapacity,snapshotIntervalMs:this.#i.snapshotIntervalMs,bypassLookaheadS:this.#i.bypassLookaheadMs/1e3,getAudioContextTime:()=>this.#e?.currentTime??0,getNTPStartTime:()=>this.#S?.getNTPStartTime()??0};if(e==="sab"&&(n.sharedBuffer=r,n.ringBufferBase=s,n.bufferConstants=t),this.#n=Ve(e,n),this.#n.onReply((o,a)=>{this.#f.emit("message:raw",{oscData:o,sequence:a});try{let c=X(o),l=c[0],f=c.slice(1);if(l==="/supersonic/buffer/freed")this.#c?.handleBufferFreed(f);else if(l==="/supersonic/buffer/allocated")this.#c?.handleBufferAllocated(f);else if(l==="/synced"&&f.length>0){let u=f[0];this.#o?.has(u)&&this.#o.get(u)(c)}if(this.#f.emit("message",c),this.#i.debug||this.#i.debugOscIn){let u=this.#i.activityConsoleLog.oscInMaxLineLength??this.#i.activityConsoleLog.maxLineLength,d=f.map(m=>{let p=JSON.stringify(m);return p.length>u?p.slice(0,u)+"...":p}).join(", ")||"";console.log(`[\u2190 OSC] ${l}${d?" "+d:""}`)}}catch(c){console.error("[SuperSonic] Failed to decode OSC message:",c)}}),this.#n.onDebug(o=>{let a=this.#i.activityEvent.scsynthMaxLineLength??this.#i.activityEvent.maxLineLength;if(a>0&&o.text?.length>a&&(o={...o,text:o.text.slice(0,a)+"..."}),this.#f.emit("debug",o),this.#i.debug||this.#i.debugScsynth){let c=this.#i.activityConsoleLog.scsynthMaxLineLength??this.#i.activityConsoleLog.maxLineLength,l=o.text.length>c?o.text.slice(0,c)+"...":o.text;console.log(`[synth] ${l}`)}}),this.#n.onError((o,a)=>{console.error(`[SuperSonic] ${a} error:`,o),this.#f.emit("error",new Error(`${a}: ${o}`))}),this.#n.onOscLog(o=>{for(let a of o)this.#f.emit("message:sent",a.oscData,a.sourceId,a.sequence)}),e==="sab")await this.#n.initialize();else{if(await this.#n.initialize(this.#t.port),this.#n.setBufferConstants(t),this.#C?.length>0)for(let o of this.#C)this.#n.handleDebugRaw(o);this.#O=o=>this.#n.handleDebugRaw(o),this.#C=[]}this.#w=this.#n.createOscChannel({sourceId:0})}async#P(){this.#m=!0,this.#d=!1,this.bootStats.initDuration=performance.now()-this.bootStats.initStartTime,await this.#f.emitAsync("setup"),this.#f.emit("ready",{capabilities:this.#b,bootStats:this.bootStats})}#q(){return new Promise((e,t)=>{let s=setTimeout(()=>{t(new Error("AudioWorklet initialization timeout"))},5e3),r=async n=>{if(n.data.type==="error"){clearTimeout(s),this.#t.port.removeEventListener("message",r),t(new Error(n.data.error||"AudioWorklet error"));return}if(n.data.type==="initialized")if(clearTimeout(s),this.#t.port.removeEventListener("message",r),n.data.success){let o=n.data.ringBufferBase??0,a=n.data.bufferConstants,c=this.#i.mode==="sab"?this.#s.buffer:null;this.#y.initSharedViews(c,o,a);let l=this.#i.worldOptions?.maxNodes??1024,f=a?.NODE_TREE_MIRROR_MAX_NODES??1024;l>f&&console.warn(`SuperSonic: maxNodes (${l}) exceeds NODE_TREE_MIRROR_MAX_NODES (${f}). The node tree mirror will not show all nodes. Rebuild with NODE_TREE_MIRROR_MAX_NODES=${l} to fix.`),this.#S=new ne({mode:this.#i.mode,audioContext:this.#e,workletPort:this.#t.port}),this.#S.initSharedViews(c,o,a),await this.#S.initialize(),this.#S.startDriftTimer(),this.#i.mode==="sab"&&this.#A.update(c,o,a),this.#i.mode==="postMessage"&&n.data.initialSnapshot&&this.#y.updateSnapshot(n.data.initialSnapshot),e()}else t(new Error(n.data.error||"AudioWorklet initialization failed"))};this.#t.port.addEventListener("message",r),this.#t.port.start()})}#Z(){this.#t.port.addEventListener("message",e=>{let{data:t}=e;switch(t.type){case"error":console.error("[Worklet] Error:",t.error),this.#f.emit("error",new Error(t.error));break;case"version":this.#g=t.version;break;case"snapshot":t.buffer&&(this.#y.updateSnapshot(t.buffer),this.#N=t.snapshotsSent);break;case"debugRawBatch":this.#O?this.#O(t):this.#C.push(t);break;case"oscLog":t.entries&&this.#n?.handleOscLog&&this.#n.handleOscLog(t.entries);break}})}#F(){return{preschedulerMetrics:this.#n?.getPreschedulerMetrics(),transportMetrics:this.#n?.getMetrics(),driftOffsetMs:this.#S?.getDriftOffset()??0,ntpStartTime:this.#S?.getNTPStartTime()??0,globalOffsetMs:this.#S?.getGlobalOffset()??0,audioContextState:this.#e?.state||"unknown",bufferPoolStats:this.#c?.getStats(),loadedSynthDefsCount:this.loadedSynthDefs?.size||0,preschedulerCapacity:this.#i.preschedulerCapacity}}#k(){return this.#y.gatherMetrics(this.#F())}#X(){this.#y.updateMergedArray(this.#F())}#x(){if(this.#i.mode==="sab"){let t=this.#y.getMetricsView();return t?t[0]:null}let e=this.#y.getSnapshotBuffer();return e?new Uint32Array(e,0,1)[0]:null}#T(e="perform this operation"){if(!this.#m)throw new Error(`SuperSonic not initialized. Call init() before attempting to ${e}.`)}#J(e){let s={nonBundle:"bypassNonBundle",immediate:"bypassImmediate",nearFuture:"bypassNearFuture",late:"bypassLate"}[e];s&&this.#y.addMetric(s)}#K(e){return e.includes("/")||e.includes("://")}#Q(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new Error("oscData must be ArrayBuffer or Uint8Array")}async#j(e){try{let t=i.osc.decode(e),{packet:s,changed:r}=await this.#a.rewritePacket(t);return r?s.timeTag!==void 0?i.osc.encodeBundle(s.timeTag,s.packets):i.osc.encodeMessage(s[0],s.slice(1)):e}catch(t){throw console.error("[SuperSonic] Failed to prepare OSC packet:",t),t}}};export{w as OscChannel,Dt as SuperSonic,Ut as oscFast};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "supersonic-scsynth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.45.0",
|
|
4
4
|
"description": "SuperCollider scsynth WebAssembly port for AudioWorklet - Run SuperCollider synthesis in the browser",
|
|
5
5
|
"main": "dist/supersonic.js",
|
|
6
6
|
"unpkg": "dist/supersonic.js",
|
|
@@ -38,11 +38,17 @@
|
|
|
38
38
|
"homepage": "https://github.com/samaaron/supersonic#readme",
|
|
39
39
|
"exports": {
|
|
40
40
|
".": "./dist/supersonic.js",
|
|
41
|
-
"./osc-channel": "./dist/osc_channel.js"
|
|
41
|
+
"./osc-channel": "./dist/osc_channel.js",
|
|
42
|
+
"./metrics": "./dist/metrics_component.js",
|
|
43
|
+
"./metrics-dark.css": "./dist/metrics-dark.css",
|
|
44
|
+
"./metrics-light.css": "./dist/metrics-light.css"
|
|
42
45
|
},
|
|
43
46
|
"files": [
|
|
44
47
|
"dist/supersonic.js",
|
|
45
48
|
"dist/osc_channel.js",
|
|
49
|
+
"dist/metrics_component.js",
|
|
50
|
+
"dist/metrics-dark.css",
|
|
51
|
+
"dist/metrics-light.css",
|
|
46
52
|
"README.md",
|
|
47
53
|
"LICENSE"
|
|
48
54
|
],
|