@4players/odin-plugin-web 1.7.1 → 1.8.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.
@@ -1,4 +1,4 @@
1
- var iA=Object.defineProperty;var p=(C,j)=>()=>(C&&(j=C(C=0)),j);var Px=(C,j)=>{for(var e in j)iA(C,e,{get:j[e],enumerable:!0})};var b={};Px(b,{AdditionalCaptureBlocks:()=>oA,AdditionalPlaybackBlocks:()=>bA,ClockJumpCheckInterval:()=>pA,ClockJumpThreshold:()=>hA,ConnectInterval:()=>yA,ConnectTimeout:()=>IA,DefaultRefreshRate:()=>lA,HealthCheckTimeout:()=>dA,MainConnectionPingInterval:()=>qA,MaxNumberOfDecoders:()=>kA,MinDBFs:()=>Ox,MinTokenLifetime:()=>$A,MinTokenRefreshInterval:()=>gA,PlaybackPreload:()=>aA,RenderQuantumSize:()=>cA,VadPreload:()=>uA,WebRtcIceTimeout:()=>mA,WebRtcTimeout:()=>GA});var bA,oA,aA,lA,uA,kA,cA,Ox,dA,pA,hA,qA,mA,GA,IA,$A,gA,yA,Mx=p(()=>{"use strict";bA=3,oA=3,aA=3,lA=250,uA=3,kA=512,cA=128,Ox=-758.596,dA=1e4,pA=1e3,hA=1e4,qA=3e3,mA=3e3,GA=1e4,IA=5e3,$A=6e4,gA=5e3,yA=[0,100,200,200,500]});function jx(C){return typeof C!="symbol"}function l(C){return typeof C=="symbol"}var m,s,P,G,ex=p(()=>{"use strict";m=Symbol("Unencrypted"),s=Symbol("Invalid"),P=Symbol("Retry"),G=Symbol("UnexpectedEof")});function c(C,j,e){return C.postMessage(j,e)}function W(C,j){return new Promise(e=>{let B=v=>{let[E,f]=v.data;E===j&&(e(v.data[1]),C.removeEventListener("message",B))};C.addEventListener("message",B)})}var B0=p(()=>{"use strict"});function Tx(C,j){C.values[0]=j[0],C.values[1]=j[1]}function v0(C,j){return C.values[2+j*5]}function C0(C,j,e){let B=2+j*5+1;C.values[B+0]=e[0],C.values[B+1]=e[1]}function E0(C){return C.values[0]!==0}function f0(C){return C.values[1]}function n0(C){return C.values[2]}function s0(C,j){return C.values[3]=j}var i0=p(()=>{"use strict"});function b0(C,j){let e=new O(C);e.position=j;let B=e.readObjects(1);return jx(B)?e.position:B}var O,o0=p(()=>{"use strict";ex();O=class{constructor(j,e=0){this.bytes=j;this.position=e}readArrayLength(){let j=this.readTag();return l(j)?j:(j&240)===144?j&15:j===220?this.readUint16():j===221?this.readUint32():s}readNumber(){let j=this.readTag();return l(j)||(j&128)===0?j:(j&224)===224?j-256:j===202?this.readFloat32():j===203?this.readFloat64():j===204?this.readUint8():j===205?this.readUint16():j===206?this.readUint32():j===207?this.readUint64():j===208?this.readInt8():j===209?this.readInt16():j===210?this.readInt32():j===211?this.readInt64():s}readBytes(){let j=this.readTag();if(l(j))return j;let e;if(j===196)e=this.readUint8();else if(j===197)e=this.readUint16();else if(j===198)e=this.readUint32();else return s;if(l(e))return e;let B=this.consume(e);return B!==G?this.bytes.subarray(B,B+e):G}readObjects(j){for(;j>0;j-=1){let e=this.readTag();if(l(e))return e;let B,v=0,E=0;switch(e){case 192:break;case 194:break;case 195:break;case 196:v=this.readUint8();break;case 197:v=this.readUint16();break;case 198:v=this.readUint32();break;case 199:v=this.readUint8(),E=1;break;case 200:v=this.readUint8(),E=1;break;case 201:v=this.readUint32(),E=1;break;case 202:v=4;break;case 203:v=8;break;case 204:v=1;break;case 205:v=2;break;case 206:v=4;break;case 207:v=8;break;case 208:v=1;break;case 209:v=2;break;case 210:v=4;break;case 211:v=8;break;case 212:v=2;break;case 213:v=3;break;case 214:v=5;break;case 215:v=9;break;case 216:v=17;break;case 217:v=this.readUint8();break;case 218:v=this.readUint16();break;case 219:v=this.readUint32();break;case 220:if(B=this.readUint16(),l(B))return B;j+=B;break;case 221:if(B=this.readUint32(),l(B))return B;j+=B;break;case 222:if(B=this.readUint16(),l(B))return B;j+=B*2;break;case 223:if(B=this.readUint32(),l(B))return B;j+=B*2;break;default:if((e&128)!==0){if((e&240)===128)j+=(e&15)*2;else if((e&240)===144)j+=e&15;else if((e&224)===160)v=e&31;else if((e&224)!==224)return s}}if(v===G)return G;if(this.consume(v+E)===G)return G}}consume(j){if(j===G||this.position+j>this.bytes.length)return G;let e=this.position;return this.position=e+j,e}readTag(){let j=this.consume(1);return jx(j)?this.bytes[j]:j}readUint8(){let j=this.consume(1);return jx(j)?this.bytes[j]:j}readUint16(){let j=this.consume(2);return l(j)?j:this.bytes[j]<<8|this.bytes[j+1]}readUint32(){let j=this.consume(4);return l(j)?j:this.bytes[j]<<24|this.bytes[j+1]<<16|this.bytes[j+2]<<8|this.bytes[j+3]}readUint64(){let j=this.readUint32();if(l(j))return j;if(j>=2097152)return s;let e=this.readUint32();return l(e)?e:j<<32|e}readInt8(){let j=this.readUint8();return l(j)||j>=128&&(j=j-256),j}readInt16(){let j=this.readUint16();return l(j)||j>=32768&&(j=j-65536),j}readInt32(){let j=this.readUint32();return l(j)||j>=2147483648&&(j=j-4294967296),j}readInt64(){let j=this.readUint32();if(l(j))return j;if(j>=2097152||j<-2097152)return s;let e=this.readUint32();return l(e)?e:j<<32|e}readFloat32(){let j=this.consume(4);return l(j)?j:new Float32Array(this.bytes.subarray(j,j+4))[0]}readFloat64(){let j=this.consume(8);return l(j)?j:new Float64Array(this.bytes.subarray(j,j+8))[0]}}});var a0,l0=p(()=>{"use strict";a0="1.7.1"});import{error as _A,warn as LA,info as HA,debug as NA,Logger as KA,LogLevel as wA,CallbackSink as JA,Formatter as PA}from"@4players/odin-common";function u0(C,j){I||(I=C??new KA(wA.DEBUG,"odin-plugin-web",[]),j&&I.sinks.push(new JA(j,PA.structured)))}function d(C,...j){let e=Bx(j);I?I?.error(C,e):_A(C,e)}function q(C,...j){let e=Bx(j);I?I?.warn(C,e):LA(C,e)}function o(C,...j){let e=Bx(j);I?I?.info(C,e):HA(C,e)}function a(C,...j){let e=Bx(j);I?I?.debug(C,e):NA(C,e)}function Bx(...C){if(C.length===1&&typeof C[0]=="object"&&C[0]!==null)return{...C[0]};if(C.length>0)return{args:C}}var I,k0=p(()=>{"use strict"});function h(C){return C.connectionId*4294967296+C.mediaId}var _,S,k=p(()=>{"use strict";Mx();ex();Mx();B0();i0();o0();l0();k0();ex();_={isSilent:!0,rmsDBFS:-758.596};S=class{constructor(){this.inFlight=null}run(j){return this.inFlight||(this.inFlight=j().finally(()=>{this.inFlight=null})),this.inFlight}}});function Y(C,j,e,B,v){return Promise.all([VA(C),UA(e,j,B,v)])}async function VA(C){let j=URL.createObjectURL(new Blob([C],{type:"text/javascript"})),e=new Worker(j,{type:"module",name:"odin worker"});return h0.push(e),e}async function UA(C,j,e,B){try{let f=new AudioWorkletNode(C,e,B);return Sx.push(f),f}catch{}let v=URL.createObjectURL(new Blob([j],{type:"text/javascript"}));await C.audioWorklet.addModule(v);let E=new AudioWorkletNode(C,e,B);return Sx.push(E),E}async function q0(){return{workers:await Promise.all(h0.map(Q)),worklets:await Promise.all(Sx.map(C=>Q(C.port)))}}function Q(C){let{port1:j,port2:e}=new MessageChannel,{promise:B,resolve:v}=Promise.withResolvers();return e.onmessage=E=>v(E.data),setTimeout(()=>v("timeout"),100),c(C,["dump",{result:j}],[j]),B}var h0,Sx,z,X,Cx=p(()=>{"use strict";k();h0=[],Sx=[],z=class{constructor(j,e,B){this.audioContext=j;this.worklet=e;this.worker=B;this.availableIndexes=[];this.medias=new Map;B.addEventListener("message",this._OnMessages.bind(this))}receivePacket(j,e){c(this.worker,["playbackReceivePacket",{connectionId:j,packet:e}],[e.buffer])}addMedias(j,e,B=[1,1]){let v=[];for(let E of e){let f=this._GetFreeIndex();f!==void 0&&(this.medias.set(h({connectionId:j,mediaId:E}),{index:f}),v.push({connectionId:j,mediaId:E,index:f,volume:B}))}c(this.worker,["playbackUpdateMedias",{added:v,removed:[]}])}removeMedias(j,e){let B=[];for(let v of e){let E=h({connectionId:j,mediaId:v}),f=this.medias.get(E);f!==void 0&&(this.medias.delete(E),this.availableIndexes.push(f.index),B.push({connectionId:j,mediaId:v,index:f.index}))}c(this.worker,["playbackUpdateMedias",{added:[],removed:B}])}close(){c(this.worker,["close",void 0]),c(this.worklet.port,["close",void 0])}async dump(){return{playbackWorker:await Q(this.worker),playbackWorklet:await Q(this.worklet.port)}}_GetFreeIndex(){return this.availableIndexes.pop()}_OnMessages(j){}},X=class C{constructor(j,e,B,v,E){this.worklet=j;this.worker=e;this.sink=(f,n)=>{E.deref()!==void 0?B(f,n):(d("capture worker was left abandoned, aborting capture worker"),C.shutdown(j,e))},this.monitorSink=(f,n)=>{E.deref()!==void 0?v(f,n):(d("capture worker was left abandoned, aborting capture worker"),C.shutdown(j,e))},e.addEventListener("message",this._OnMessages.bind(this))}get context(){return this.worklet.context}setMedias(j){c(this.worker,["captureSetMedias",{connections:j}])}setVad(j){c(this.worker,["captureSetVad",j])}close(){C.shutdown(this.worklet,this.worker)}static shutdown(j,e){c(j.port,["close",void 0]),c(e,["close",void 0])}async dump(){return{captureWorker:await Q(this.worker),captureWorklet:await Q(this.worklet.port)}}_OnMessages(j){let[e,B]=j.data;e==="sendPacket"&&(B.connectionId===0?this.monitorSink(B.connectionId,B.packet):this.sink(B.connectionId,B.packet))}}});var Rx,m0=p(()=>{Rx=`"use strict";(()=>{var pn=Object.create;var kr=Object.defineProperty;var hn=Object.getOwnPropertyDescriptor;var mn=Object.getOwnPropertyNames;var En=Object.getPrototypeOf,In=Object.prototype.hasOwnProperty;var $n=(n,A)=>()=>(A||n((A={exports:{}}).exports,A),A.exports),Fn=(n,A)=>{for(var t in A)kr(n,t,{get:A[t],enumerable:!0})},vn=(n,A,t,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of mn(A))!In.call(n,i)&&i!==t&&kr(n,i,{get:()=>A[i],enumerable:!(e=hn(A,i))||e.enumerable});return n};var Ln=(n,A,t)=>(t=n!=null?pn(En(n)):{},vn(A||!n||!n.__esModule?kr(t,"default",{value:n,enumerable:!0}):t,n));var vt=$n((Ft,UA)=>{"use strict";var TA=(()=>{var n=globalThis.document?.currentScript?.src;return async function(A={}){var t,e=A,i=!!globalThis.window,d=!!globalThis.WorkerGlobalScope,q=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",C=d&&globalThis.name=="em-pthread",v=[],B="./this.program",pA=(r,j)=>{throw j};d&&(n=self.location.href);var P="",yt,xt;if(i||d){try{P=new URL(".",n).href}catch{}d&&(xt=r=>{var j=new XMLHttpRequest;return j.open("GET",r,!1),j.responseType="arraybuffer",j.send(null),new Uint8Array(j.response)}),yt=async r=>{var j=await fetch(r,{credentials:"same-origin"});if(j.ok)return j.arrayBuffer();throw new Error(j.status+" : "+j.url)}}var SA=console.log.bind(console),N=console.error.bind(console),_r,nA,hA=!1,z;function Dt(r){for(var j=0,s=r.length,l=new Uint8Array(s),o;j<s;++j)o=r.charCodeAt(j),l[j]=~o>>8&o;return l}var VA,Hr,yr;if(C){let r=function(j){try{var s=j.data,l=s.cmd;if(l==="load"){let o=[];self.onmessage=k=>o.push(k),yr=()=>{postMessage({cmd:"loaded"});for(let k of o)r(k);self.onmessage=r};for(let k of s.handlers)(!e[k]||e[k].proxy)&&(e[k]=(...a)=>{postMessage({cmd:"callHandler",handler:k,args:a})},k=="print"&&(SA=e[k]),k=="printErr"&&(N=e[k]));Y=s.wasmMemory,Nr(),nA=s.wasmModule,Or(),Nj()}else if(l==="run"){Wt(s.pthread_ptr),lr(s.pthread_ptr,0,0,1,0,0),h.threadInitTLS(),nr(s.pthread_ptr),WA||(Ij(),WA=!0);try{Rt(s.start_routine,s.arg)}catch(o){if(o!="unwind")throw o}}else s.target==="setimmediate"||(l==="checkMailbox"?WA&&yA():l&&(N(\`worker: received unknown command \${l}\`),N(s)))}catch(o){throw $j(),o}};var ys=r,WA=!1;self.onunhandledrejection=j=>{throw j.reason||j},self.onmessage=r}var V,x,mA,sA,Q,I,xr,EA,W,Dr,Br=!1;function Nr(){var r=Y.buffer;V=new Int8Array(r),mA=new Int16Array(r),e.HEAPU8=x=new Uint8Array(r),sA=new Uint16Array(r),e.HEAP32=Q=new Int32Array(r),e.HEAPU32=I=new Uint32Array(r),e.HEAPF32=xr=new Float32Array(r),EA=new Float64Array(r),W=new BigInt64Array(r),Dr=new BigUint64Array(r)}function Bt(){if(!C){if(e.wasmMemory)Y=e.wasmMemory;else{var r=e.INITIAL_MEMORY||16777216;Y=new WebAssembly.Memory({initial:r/65536,maximum:r/65536,shared:!0})}Nr()}}function Nt(){if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)Pt(e.preRun.shift());Tr(Ur)}function Kr(){if(Br=!0,C)return yr();tA.F()}function Kt(){if(!C){if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)Vt(e.postRun.shift());Tr(Rr)}}function RA(r){e.onAbort?.(r),r="Aborted("+r+")",N(r),hA=!0,r+=". Build with -sASSERTIONS for more info.";var j=new WebAssembly.RuntimeError(r);throw Hr?.(j),j}var Jr;function Jt(){return Dt(\`\\0asm\\0\\0\\0\\xB2>\\\`\\x7F\\0\\\`\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\\`\\0\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`||\\\`\\x7F}\\\`}}\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\0\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F~\\\`\\x7F\\x7F}\\\`\\x7F}}\\\`\\x7F\\x7F}}\\0\\\`
1
+ var iA=Object.defineProperty;var d=(v,t)=>()=>(v&&(t=v(v=0)),t);var Ox=(v,t)=>{for(var j in t)iA(v,j,{get:t[j],enumerable:!0})};var i={};Ox(i,{AdditionalCaptureBlocks:()=>oA,AdditionalPlaybackBlocks:()=>bA,ClockJumpCheckInterval:()=>pA,ClockJumpThreshold:()=>hA,ConnectInterval:()=>_A,ConnectTimeout:()=>$A,DefaultRefreshRate:()=>lA,DefaultVideoCodec:()=>LA,HealthCheckTimeout:()=>dA,MainConnectionPingInterval:()=>qA,MaxNumberOfDecoders:()=>kA,MinDBFs:()=>Mx,MinTokenLifetime:()=>gA,MinTokenRefreshInterval:()=>yA,PlaybackPreload:()=>aA,RenderQuantumSize:()=>cA,VadPreload:()=>uA,WebRtcIceTimeout:()=>GA,WebRtcStatsSnapshotInterval:()=>mA,WebRtcTimeout:()=>IA});var bA,oA,aA,lA,uA,kA,cA,Mx,dA,pA,hA,qA,mA,GA,IA,$A,gA,yA,_A,LA,Tx=d(()=>{"use strict";bA=3,oA=3,aA=3,lA=250,uA=3,kA=512,cA=128,Mx=-758.596,dA=1e4,pA=1e3,hA=1e4,qA=3e3,mA=1e3,GA=3e3,IA=1e4,$A=5e3,gA=6e4,yA=5e3,_A=[0,100,200,200,500],LA="H264"});function ex(v){return typeof v!="symbol"}function l(v){return typeof v=="symbol"}var m,n,P,G,Bx=d(()=>{"use strict";m=Symbol("Unencrypted"),n=Symbol("Invalid"),P=Symbol("Retry"),G=Symbol("UnexpectedEof")});function k(v,t,j){return v.postMessage(t,j)}function W(v,t){return new Promise(j=>{let e=B=>{let[C,E]=B.data;C===t&&(j(B.data[1]),v.removeEventListener("message",e))};v.addEventListener("message",e)})}var B0=d(()=>{"use strict"});function Sx(v,t){v.values[0]=t[0],v.values[1]=t[1]}function v0(v,t){return v.values[2+t*5]}function C0(v,t,j){let e=2+t*5+1;v.values[e+0]=j[0],v.values[e+1]=j[1]}function E0(v){return v.values[0]!==0}function f0(v){return v.values[1]}function n0(v){return v.values[2]}function s0(v,t){return v.values[3]=t}var i0=d(()=>{"use strict"});function b0(v,t){let j=new O(v);j.position=t;let e=j.readObjects(1);return ex(e)?j.position:e}var O,o0=d(()=>{"use strict";Bx();O=class{constructor(t,j=0){this.bytes=t;this.position=j}readArrayLength(){let t=this.readTag();return l(t)?t:(t&240)===144?t&15:t===220?this.readUint16():t===221?this.readUint32():n}readNumber(){let t=this.readTag();return l(t)||(t&128)===0?t:(t&224)===224?t-256:t===202?this.readFloat32():t===203?this.readFloat64():t===204?this.readUint8():t===205?this.readUint16():t===206?this.readUint32():t===207?this.readUint64():t===208?this.readInt8():t===209?this.readInt16():t===210?this.readInt32():t===211?this.readInt64():n}readBytes(){let t=this.readTag();if(l(t))return t;let j;if(t===196)j=this.readUint8();else if(t===197)j=this.readUint16();else if(t===198)j=this.readUint32();else return n;if(l(j))return j;let e=this.consume(j);return e!==G?this.bytes.subarray(e,e+j):G}readObjects(t){for(;t>0;t-=1){let j=this.readTag();if(l(j))return j;let e,B=0,C=0;switch(j){case 192:break;case 194:break;case 195:break;case 196:B=this.readUint8();break;case 197:B=this.readUint16();break;case 198:B=this.readUint32();break;case 199:B=this.readUint8(),C=1;break;case 200:B=this.readUint8(),C=1;break;case 201:B=this.readUint32(),C=1;break;case 202:B=4;break;case 203:B=8;break;case 204:B=1;break;case 205:B=2;break;case 206:B=4;break;case 207:B=8;break;case 208:B=1;break;case 209:B=2;break;case 210:B=4;break;case 211:B=8;break;case 212:B=2;break;case 213:B=3;break;case 214:B=5;break;case 215:B=9;break;case 216:B=17;break;case 217:B=this.readUint8();break;case 218:B=this.readUint16();break;case 219:B=this.readUint32();break;case 220:if(e=this.readUint16(),l(e))return e;t+=e;break;case 221:if(e=this.readUint32(),l(e))return e;t+=e;break;case 222:if(e=this.readUint16(),l(e))return e;t+=e*2;break;case 223:if(e=this.readUint32(),l(e))return e;t+=e*2;break;default:if((j&128)!==0){if((j&240)===128)t+=(j&15)*2;else if((j&240)===144)t+=j&15;else if((j&224)===160)B=j&31;else if((j&224)!==224)return n}}if(B===G)return G;if(this.consume(B+C)===G)return G}}consume(t){if(t===G||this.position+t>this.bytes.length)return G;let j=this.position;return this.position=j+t,j}readTag(){let t=this.consume(1);return ex(t)?this.bytes[t]:t}readUint8(){let t=this.consume(1);return ex(t)?this.bytes[t]:t}readUint16(){let t=this.consume(2);return l(t)?t:this.bytes[t]<<8|this.bytes[t+1]}readUint32(){let t=this.consume(4);return l(t)?t:this.bytes[t]<<24|this.bytes[t+1]<<16|this.bytes[t+2]<<8|this.bytes[t+3]}readUint64(){let t=this.readUint32();if(l(t))return t;if(t>=2097152)return n;let j=this.readUint32();return l(j)?j:t<<32|j}readInt8(){let t=this.readUint8();return l(t)||t>=128&&(t=t-256),t}readInt16(){let t=this.readUint16();return l(t)||t>=32768&&(t=t-65536),t}readInt32(){let t=this.readUint32();return l(t)||t>=2147483648&&(t=t-4294967296),t}readInt64(){let t=this.readUint32();if(l(t))return t;if(t>=2097152||t<-2097152)return n;let j=this.readUint32();return l(j)?j:t<<32|j}readFloat32(){let t=this.consume(4);return l(t)?t:new Float32Array(this.bytes.subarray(t,t+4))[0]}readFloat64(){let t=this.consume(8);return l(t)?t:new Float64Array(this.bytes.subarray(t,t+8))[0]}}});var a0,l0=d(()=>{"use strict";a0="1.8.0"});import{error as HA,warn as NA,info as KA,debug as wA,Logger as JA,LogLevel as PA,CallbackSink as OA,Formatter as MA}from"@4players/odin-common";function u0(v,t){I||(I=v??new JA(PA.DEBUG,"odin-plugin-web",[]),t&&I.sinks.push(new OA(t,MA.structured)))}function c(v,...t){let j=vx(t);I?I?.error(v,j):HA(v,j)}function h(v,...t){let j=vx(t);I?I?.warn(v,j):NA(v,j)}function b(v,...t){let j=vx(t);I?I?.info(v,j):KA(v,j)}function o(v,...t){let j=vx(t);I?I?.debug(v,j):wA(v,j)}function vx(...v){if(v.length===1&&typeof v[0]=="object"&&v[0]!==null)return{...v[0]};if(v.length>0)return{args:v}}var I,k0=d(()=>{"use strict"});function p(v){return v.connectionId*4294967296+v.mediaId}var y,S,u=d(()=>{"use strict";Tx();Bx();Tx();B0();i0();o0();l0();k0();Bx();y={isSilent:!0,rmsDBFS:-758.596};S=class{constructor(){this.inFlight=null}run(t){return this.inFlight||(this.inFlight=t().finally(()=>{this.inFlight=null})),this.inFlight}}});function Z(v,t,j,e,B){return Promise.all([WA(v),zA(j,t,e,B)])}async function WA(v){let t=URL.createObjectURL(new Blob([v],{type:"text/javascript"})),j=new Worker(t,{type:"module",name:"odin worker"});return z.push(j),j}async function zA(v,t,j,e){try{let E=new AudioWorkletNode(v,j,e);return V.push(E),E}catch{}let B=URL.createObjectURL(new Blob([t],{type:"text/javascript"}));await v.audioWorklet.addModule(B);let C=new AudioWorkletNode(v,j,e);return V.push(C),C}async function h0(){return{workers:await Promise.all(z.map(Y)),worklets:await Promise.all(V.map(v=>Y(v.port)))}}function Y(v){let{port1:t,port2:j}=new MessageChannel,{promise:e,resolve:B}=Promise.withResolvers();return j.onmessage=C=>B(C.data),setTimeout(()=>B("timeout"),100),k(v,["dump",{result:t}],[t]),e}var z,V,X,Q,Ex=d(()=>{"use strict";u();z=[],V=[],X=class{constructor(t,j,e){this.audioContext=t;this.worklet=j;this.worker=e;this.availableIndexes=[];this.medias=new Map;e.addEventListener("message",this._OnMessages.bind(this))}receivePacket(t,j){k(this.worker,["playbackReceivePacket",{connectionId:t,packet:j}],[j.buffer])}addMedias(t,j,e=[1,1]){let B=[];for(let C of j){let E=this._GetFreeIndex();E!==void 0&&(this.medias.set(p({connectionId:t,mediaId:C}),{index:E}),B.push({connectionId:t,mediaId:C,index:E,volume:e}))}k(this.worker,["playbackUpdateMedias",{added:B,removed:[]}])}removeMedias(t,j){let e=[];for(let B of j){let C=p({connectionId:t,mediaId:B}),E=this.medias.get(C);E!==void 0&&(this.medias.delete(C),this.availableIndexes.push(E.index),e.push({connectionId:t,mediaId:B,index:E.index}))}k(this.worker,["playbackUpdateMedias",{added:[],removed:e}])}close(){k(this.worker,["close",void 0]),k(this.worklet.port,["close",void 0]);let t=z.indexOf(this.worker);t>=0&&z.splice(t,1);let j=V.indexOf(this.worklet);j>=0&&V.splice(j,1)}async dump(){return{playbackWorker:await Y(this.worker),playbackWorklet:await Y(this.worklet.port)}}_GetFreeIndex(){return this.availableIndexes.pop()}_OnMessages(t){}},Q=class v{constructor(t,j,e,B,C){this.worklet=t;this.worker=j;this.sink=(E,f)=>{C.deref()!==void 0?e(E,f):(c("capture worker was left abandoned, aborting capture worker"),v.shutdown(t,j))},this.monitorSink=(E,f)=>{C.deref()!==void 0?B(E,f):(c("capture worker was left abandoned, aborting capture worker"),v.shutdown(t,j))},j.addEventListener("message",this._OnMessages.bind(this))}get context(){return this.worklet.context}setMedias(t){k(this.worker,["captureSetMedias",{connections:t}])}setVad(t){k(this.worker,["captureSetVad",t])}close(){v.shutdown(this.worklet,this.worker)}static shutdown(t,j){k(t.port,["close",void 0]),k(j,["close",void 0]);let e=z.indexOf(j);e>=0&&z.splice(e,1);let B=V.indexOf(t);B>=0&&V.splice(B,1)}async dump(){return{captureWorker:await Y(this.worker),captureWorklet:await Y(this.worklet.port)}}_OnMessages(t){let[j,e]=t.data;j==="sendPacket"&&(e.connectionId===0?this.monitorSink(e.connectionId,e.packet):this.sink(e.connectionId,e.packet))}}});var Rx,q0=d(()=>{Rx=`"use strict";(()=>{var pn=Object.create;var kr=Object.defineProperty;var hn=Object.getOwnPropertyDescriptor;var mn=Object.getOwnPropertyNames;var En=Object.getPrototypeOf,In=Object.prototype.hasOwnProperty;var $n=(n,A)=>()=>(A||n((A={exports:{}}).exports,A),A.exports),Fn=(n,A)=>{for(var t in A)kr(n,t,{get:A[t],enumerable:!0})},vn=(n,A,t,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of mn(A))!In.call(n,i)&&i!==t&&kr(n,i,{get:()=>A[i],enumerable:!(e=hn(A,i))||e.enumerable});return n};var Ln=(n,A,t)=>(t=n!=null?pn(En(n)):{},vn(A||!n||!n.__esModule?kr(t,"default",{value:n,enumerable:!0}):t,n));var vt=$n((Ft,UA)=>{"use strict";var TA=(()=>{var n=globalThis.document?.currentScript?.src;return async function(A={}){var t,e=A,i=!!globalThis.window,d=!!globalThis.WorkerGlobalScope,q=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",C=d&&globalThis.name=="em-pthread",v=[],B="./this.program",pA=(r,j)=>{throw j};d&&(n=self.location.href);var P="",yt,xt;if(i||d){try{P=new URL(".",n).href}catch{}d&&(xt=r=>{var j=new XMLHttpRequest;return j.open("GET",r,!1),j.responseType="arraybuffer",j.send(null),new Uint8Array(j.response)}),yt=async r=>{var j=await fetch(r,{credentials:"same-origin"});if(j.ok)return j.arrayBuffer();throw new Error(j.status+" : "+j.url)}}var SA=console.log.bind(console),N=console.error.bind(console),_r,nA,hA=!1,z;function Dt(r){for(var j=0,s=r.length,l=new Uint8Array(s),o;j<s;++j)o=r.charCodeAt(j),l[j]=~o>>8&o;return l}var VA,Hr,yr;if(C){let r=function(j){try{var s=j.data,l=s.cmd;if(l==="load"){let o=[];self.onmessage=k=>o.push(k),yr=()=>{postMessage({cmd:"loaded"});for(let k of o)r(k);self.onmessage=r};for(let k of s.handlers)(!e[k]||e[k].proxy)&&(e[k]=(...a)=>{postMessage({cmd:"callHandler",handler:k,args:a})},k=="print"&&(SA=e[k]),k=="printErr"&&(N=e[k]));Y=s.wasmMemory,Nr(),nA=s.wasmModule,Or(),Nj()}else if(l==="run"){Wt(s.pthread_ptr),lr(s.pthread_ptr,0,0,1,0,0),h.threadInitTLS(),nr(s.pthread_ptr),WA||(Ij(),WA=!0);try{Rt(s.start_routine,s.arg)}catch(o){if(o!="unwind")throw o}}else s.target==="setimmediate"||(l==="checkMailbox"?WA&&yA():l&&(N(\`worker: received unknown command \${l}\`),N(s)))}catch(o){throw $j(),o}};var Ds=r,WA=!1;self.onunhandledrejection=j=>{throw j.reason||j},self.onmessage=r}var V,x,mA,sA,Q,I,xr,EA,W,Dr,Br=!1;function Nr(){var r=Y.buffer;V=new Int8Array(r),mA=new Int16Array(r),e.HEAPU8=x=new Uint8Array(r),sA=new Uint16Array(r),e.HEAP32=Q=new Int32Array(r),e.HEAPU32=I=new Uint32Array(r),e.HEAPF32=xr=new Float32Array(r),EA=new Float64Array(r),W=new BigInt64Array(r),Dr=new BigUint64Array(r)}function Bt(){if(!C){if(e.wasmMemory)Y=e.wasmMemory;else{var r=e.INITIAL_MEMORY||16777216;Y=new WebAssembly.Memory({initial:r/65536,maximum:r/65536,shared:!0})}Nr()}}function Nt(){if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)Pt(e.preRun.shift());Tr(Ur)}function Kr(){if(Br=!0,C)return yr();tA.F()}function Kt(){if(!C){if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)Vt(e.postRun.shift());Tr(Rr)}}function RA(r){e.onAbort?.(r),r="Aborted("+r+")",N(r),hA=!0,r+=". Build with -sASSERTIONS for more info.";var j=new WebAssembly.RuntimeError(r);throw Hr?.(j),j}var Jr;function Jt(){return Dt(\`\\0asm\\0\\0\\0\\xB2>\\\`\\x7F\\0\\\`\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\\`\\0\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`||\\\`\\x7F}\\\`}}\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\0\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F~\\\`\\x7F\\x7F}\\\`\\x7F}}\\\`\\x7F\\x7F}}\\0\\\`
2
2
  \\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`|}\\\`|\\x7F|\\\`\\x7F\\x7F}\\0\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\` \\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\f\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F|\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F|}\\\`\\0|\\\`\\x7F\\x7F\\x7F~~\\0\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F|\\\`\\r\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F\\x7F\\x7F\\\`\\x7F\\x7F|\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\x7F\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F}}\\x7F\\x7F\\x7F\\x7F\\0\\\`~\\x7F\\x7F\\\` \\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\\`\\x7F\\x7F|\\x7F\\\`||\\x7F|\\\`|||\\\`\\x7F\\x7F\\x7F|\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\\`\\f\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`}\\x7F\\x7F\\\`|\\x7F\\x7F\\\`\\x7F\\x7F\\x7F}\\\`\\x7F}\\x7F\\0\\\`\\x7F\\x7F}\\x7F\\x7F\\x7F}\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F}}\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F|\\\`\\x7F\\x7F|\\0\\xBFab\\0ac\\0ad\\0ae\\0af\\0!ag\\0ah\\0"ai\\0aj\\0
3
3
  ak\\0#al\\0am\\0 an\\0$ao\\0ap\\0aq\\0ar\\0\\0as\\0\\0at\\0au\\0av\\0%aw\\0ax\\0\\bay\\0\\0az\\0\\0aA\\0\\baB\\0\\0aC\\0\\baD\\0\\0aE\\0aa\\x80\\x80\\xFB\\xF9\\0\\x07\\f&\\0\\f\\x07\\f\\f\\0\\x07\\0\\x07'(
4
4
  \\b\\v)\\x07*\\0\\f+,-.\\v\\0\\0\\x07\\0\\b\\b\\x1B
@@ -3209,7 +3209,7 @@ K\\xE08\\xDF\\0}\\xBC\\x8A\\x1B\\f\\xE5\\xFF\\xCF\\xE8?\\x9F\\xFFFq\\0\\x88\\xB
3209
3209
 
3210
3210
  
3211
3211
  \\x07\\0\\0 \\v\\0\\0 \\v\\0\\0\\v\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\v\\r\\0\\r\\0\\0\\0 \\0\\0\\0 \\0\\0\\0!\\f\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\f\\0\\0\\0\\0\\0\\f\\0\\0\\f!\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0*\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 !\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\xC0 \\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\x000123456789ABCDEF\\xA0\\0\\xF8\\0NSt3__214__shared_countE\\0\\0\\0\\0$\\0,\\0\\0\\0\\0\\0\\0\\0\\0\\xF0\\0\\0\\0\\0\\0NSt3__219__shared_weak_countE\\0\\0\\0\\xC8\\0X\\0h\\0N10__cxxabiv116__shim_type_infoE\\0\\0\\0\\0\\xC8\\0\\x88\\0L\\0N10__cxxabiv117__class_type_infoE\\0\\0\\0\\xC8\\0\\xB8\\0L\\0N10__cxxabiv117__pbase_type_infoE\\0\\0\\0\\xC8\\0\\xE8\\0\\xAC\\0N10__cxxabiv119__pointer_type_infoE\\0\\xC8\\0\\0L\\0N10__cxxabiv120__function_type_infoE\\0\\0\\0\\0\\xC8\\0L\\0\\xAC\\0N10__cxxabiv129__pointer_to_member_type_infoE\\0\\0\\0\\0\\0\\0\\0\\x98\\0n\\0\\0\\0o\\0\\0\\0p\\0\\0\\0q\\0\\0\\0r\\0\\0\\0\\xC8\\0\\xA4\\0L\\0N10__cxxabiv123__fundamental_type_infoE\\0\\x84\\0\\xD4\\0v\\0Dn\\0\\0\\0\\0\\x84\\0\\xE4\\0b\\0\\0\\0\\x84\\0\\xF0\\0c\\0\\0\\0\\x84\\0\\xFC\\0h\\0\\0\\0\\x84\\0\\b\\0a\\0\\0\\0\\x84\\0\\0s\\0\\0\\0\\x84\\0 \\0t\\0\\0\\0\\x84\\0,\\0i\\0\\0\\0\\x84\\x008\\0j\\0\\0\\0\\x84\\0D\\0l\\0\\0\\0\\x84\\0P\\0m\\0\\0\\0\\x84\\0\\\\\\0x\\0\\0\\0\\x84\\0h\\0y\\0\\0\\0\\x84\\0t\\0f\\0\\0\\0\\x80\\0\\x88\\0\\0\\0\\0\\0l\\0Pf\\0\\0\\x84\\0\\x94\\0d\\0\\0\\0\\0\\0\\0\\0|\\0n\\0\\0\\0s\\0\\0\\0p\\0\\0\\0q\\0\\0\\0t\\0\\0\\0u\\0\\0\\0v\\0\\0\\0w\\0\\0\\0\\0\\0\\0\\0\\xE8\\0n\\0\\0\\0x\\0\\0\\0p\\0\\0\\0q\\0\\0\\0t\\0\\0\\0y\\0\\0\\0z\\0\\0\\0{\\0\\0\\0\\xC8\\0\\xF4\\0|\\0N10__cxxabiv120__si_class_type_infoE\\0\\0\\0\\0\\0\\0\\0\\0D\\0n\\0\\0\\0|\\0\\0\\0p\\0\\0\\0q\\0\\0\\0t\\0\\0\\0}\\0\\0\\0~\\0\\0\\0\\x7F\\0\\0\\0\\xC8\\0P\\0|\\0N10__cxxabiv121__vmi_class_type_infoE\\0\\0\\0\\0\\0\\0\\0\\xDC\\0n\\0\\0\\0\\x80\\0\\0\\0p\\0\\0\\0q\\0\\0\\0\\x81\\0\\0\\0\\0\\0\\0\\0\\xDC\\0F\\0\\0\\0\\x82\\0\\0\\0\\x83\\0\\0\\0\\xA0\\0\\xB0\\0St9exception\\0\\0\\0\\0\\xC8\\0\\xCC\\0\\xA8\\0St9bad_alloc\\0\\0\\0\\0\\xC8\\0\\xE8\\0\\xC0\\0St20bad_array_new_length\\0\\0\\0\\0\\0\\0\\0\\0\\0H\\0\\0\\0\\x84\\0\\0\\0\\x85\\0\\0\\0\\xC8\\0$\\0\\xA8\\0St11logic_error\\0\\0\\0\\0\\0H\\0H\\0\\0\\0\\x86\\0\\0\\0\\x85\\0\\0\\0\\xC8\\0T\\0\\0St12length_error\\0\\0\\0\\0\\xA0\\0p\\0St9type_info\\0\\\`\\x80\\0\\x80\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0f\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0g\\0\\0\\0h\\0\\0\\0P\\x1B\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFFY\\xC0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0i\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0g\\0\\0\\0j\\0\\0\\0X\\x1B\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\xFF\\xFF\\xFF\\xFF
3212
- \\fX\\0\\x90!\\0\\0\\0\\0\`)}function Hs(r){return r}async function bt(r){return r}async function Ot(r,j){try{var s=await bt(r),l=await WebAssembly.instantiate(s,j);return l}catch(o){N(\`failed to asynchronously prepare wasm: \${o}\`),RA(o)}}async function wt(r,j,s){return Ot(j,s)}function br(){Cn();var r={a:Bj};return r}async function Or(){function r(a,u){return tA=a.exports,Xt(tA.M),fn(tA),nA=u,tA}function j(a){return r(a.instance,a.module)}var s=br();if(e.instantiateWasm)return new Promise((a,u)=>{e.instantiateWasm(s,(c,f)=>{a(r(c,f))})});if(C){var l=new WebAssembly.Instance(nA,br());return r(l,nA)}Jr??=Jt();var o=await wt(_r,Jr,s),k=j(o);return k}class wr{name="ExitStatus";constructor(j){this.message=\`Program terminated with exit(\${j})\`,this.status=j}}var Pr=r=>{r.terminate(),r.onmessage=j=>{}},Mr=r=>{var j=h.pthreads[r];h.returnWorkerToPool(j)},Tr=r=>{for(;r.length>0;)r.shift()(e)},Ur=[],Pt=r=>Ur.push(r),Mt=r=>{var j=h.getNewWorker();if(!j)return 6;h.runningWorkers.push(j),h.pthreads[r.pthread_ptr]=j,j.pthread_ptr=r.pthread_ptr;var s={cmd:"run",start_routine:r.startRoutine,arg:r.arg,pthread_ptr:r.pthread_ptr};return j.postMessage(s,r.transferList),0},XA=0,zA=()=>YA||XA>0,Tt=()=>xj(),Sr=r=>Hj(r),Ut=r=>yj(r),iA=(r,j,s,...l)=>{var o=8*l.length*2,k=Tt(),a=Ut(o),u=a>>3;for(var c of l)typeof c=="bigint"?(W[u++]=1n,W[u++]=c):(W[u++]=0n,EA[u++]=c);var f=vj(r,j,o,a,s);return Sr(k),f};function Vr(r){if(C)return iA(0,0,1,r);z=r,zA()||(h.terminateAllThreads(),e.onExit?.(r),hA=!0),pA(r,new wr(r))}function Wr(r){if(C)return iA(1,0,0,r);QA(r)}var St=(r,j)=>{if(z=r,C)throw Wr(r),"unwind";Vr(r)},QA=St,h={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init(){C||h.initMainThread()},initMainThread(){},terminateAllThreads:()=>{for(var r of h.runningWorkers)Pr(r);for(var r of h.unusedWorkers)Pr(r);h.unusedWorkers=[],h.runningWorkers=[],h.pthreads={}},returnWorkerToPool:r=>{var j=r.pthread_ptr;delete h.pthreads[j],h.unusedWorkers.push(r),h.runningWorkers.splice(h.runningWorkers.indexOf(r),1),r.pthread_ptr=0,Lj(j)},threadInitTLS(){h.tlsInitFunctions.forEach(r=>r())},loadWasmModuleToWorker:r=>new Promise(j=>{r.onmessage=k=>{var a=k.data,u=a.cmd;if(a.targetThread&&a.targetThread!=xA()){var c=h.pthreads[a.targetThread];c?c.postMessage(a,a.transferList):N(\`Internal error! Worker sent a message "\${u}" to target pthread \${a.targetThread}, but that thread no longer exists!\`);return}u==="checkMailbox"?yA():u==="spawnThread"?Mt(a):u==="cleanupThread"?Gj(()=>Mr(a.thread)):u==="loaded"?(r.loaded=!0,j(r)):a.target==="setimmediate"?r.postMessage(a):u==="callHandler"?e[a.handler](...a.args):u&&N(\`worker sent an unknown command \${u}\`)},r.onerror=k=>{var a="worker sent an error!";throw N(\`\${a} \${k.filename}:\${k.lineno}: \${k.message}\`),k};var s=[],l=["onExit","onAbort","print","printErr"];for(var o of l)e.propertyIsEnumerable(o)&&s.push(o);r.postMessage({cmd:"load",handlers:s,wasmMemory:Y,wasmModule:nA})}),allocateUnusedWorker(){var r,j=n;e.mainScriptUrlOrBlob&&(j=e.mainScriptUrlOrBlob,typeof j!="string"&&(j=URL.createObjectURL(j))),r=new Worker(j,{name:"em-pthread"}),h.unusedWorkers.push(r)},getNewWorker(){return h.unusedWorkers.length==0&&(h.allocateUnusedWorker(),h.loadWasmModuleToWorker(h.unusedWorkers[0])),h.unusedWorkers.pop()}},Rr=[],Vt=r=>Rr.push(r);function Wt(r){var j=I[r+52>>2],s=I[r+56>>2],l=j-s;_j(j,l),Sr(j)}var Xr=[],zr=r=>{var j=Xr[r];return j||(Xr[r]=j=Dj.get(r)),j},Rt=(r,j)=>{XA=0,YA=0;var s=zr(r)(j);function l(o){if(zA()){z=o;return}or(o)}l(s)},YA=!0,Xt=r=>h.tlsInitFunctions.push(r),Y;class zt{constructor(j){this.excPtr=j,this.ptr=j-24}set_type(j){I[this.ptr+4>>2]=j}get_type(){return I[this.ptr+4>>2]}set_destructor(j){I[this.ptr+8>>2]=j}get_destructor(){return I[this.ptr+8>>2]}set_caught(j){j=j?1:0,V[this.ptr+12]=j}get_caught(){return V[this.ptr+12]!=0}set_rethrown(j){j=j?1:0,V[this.ptr+13]=j}get_rethrown(){return V[this.ptr+13]!=0}init(j,s){this.set_adjusted_ptr(0),this.set_type(j),this.set_destructor(s)}set_adjusted_ptr(j){I[this.ptr+16>>2]=j}get_adjusted_ptr(){return I[this.ptr+16>>2]}}var Qr=0,Qt=0,Yt=(r,j,s)=>{var l=new zt(r);throw l.init(j,s),Qr=r,Qt++,Qr},Zt=()=>RA(""),L=r=>{for(var j="";;){var s=x[r++];if(!s)return j;j+=String.fromCharCode(s)}},Z={},AA={},IA={},lA=class extends Error{constructor(j){super(j),this.name="BindingError"}},p=r=>{throw new lA(r)};function Ae(r,j,s={}){var l=j.name;if(r||p(\`type "\${l}" must have a positive integer typeid pointer\`),AA.hasOwnProperty(r)){if(s.ignoreDuplicateRegistrations)return;p(\`Cannot register type '\${l}' twice\`)}if(AA[r]=j,delete IA[r],Z.hasOwnProperty(r)){var o=Z[r];delete Z[r],o.forEach(k=>k())}}function K(r,j,s={}){return Ae(r,j,s)}var Yr=(r,j,s)=>{switch(j){case 1:return s?l=>V[l]:l=>x[l];case 2:return s?l=>mA[l>>1]:l=>sA[l>>1];case 4:return s?l=>Q[l>>2]:l=>I[l>>2];case 8:return s?l=>W[l>>3]:l=>Dr[l>>3];default:throw new TypeError(\`invalid integer width (\${j}): \${r}\`)}},re=(r,j,s,l,o)=>{j=L(j);let k=l===0n,a=u=>u;if(k){let u=s*8;a=c=>BigInt.asUintN(u,c),o=a(o)}K(r,{name:j,fromWireType:a,toWireType:(u,c)=>(typeof c=="number"&&(c=BigInt(c)),c),readValueFromPointer:Yr(j,s,!k),destructorFunction:null})},je=(r,j,s,l)=>{j=L(j),K(r,{name:j,fromWireType:function(o){return!!o},toWireType:function(o,k){return k?s:l},readValueFromPointer:function(o){return this.fromWireType(x[o])},destructorFunction:null})},te=r=>({count:r.count,deleteScheduled:r.deleteScheduled,preservePointerOnDelete:r.preservePointerOnDelete,ptr:r.ptr,ptrType:r.ptrType,smartPtr:r.smartPtr,smartPtrType:r.smartPtrType}),ZA=r=>{function j(s){return s.$$.ptrType.registeredClass.name}p(j(r)+" instance already deleted")},Ar=!1,Zr=r=>{},ee=r=>{r.smartPtr?r.smartPtrType.rawDestructor(r.smartPtr):r.ptrType.registeredClass.rawDestructor(r.ptr)},Aj=r=>{r.count.value-=1;var j=r.count.value===0;j&&ee(r)},oA=r=>globalThis.FinalizationRegistry?(Ar=new FinalizationRegistry(j=>{Aj(j.$$)}),oA=j=>{var s=j.$$,l=!!s.smartPtr;if(l){var o={$$:s};Ar.register(j,o,j)}return j},Zr=j=>Ar.unregister(j),oA(r)):(oA=j=>j,r),$A=[],ne=()=>{for(;$A.length;){var r=$A.pop();r.$$.deleteScheduled=!1,r.delete()}},rj,se=()=>{let r=FA.prototype;Object.assign(r,{isAliasOf(s){if(!(this instanceof FA)||!(s instanceof FA))return!1;var l=this.$$.ptrType.registeredClass,o=this.$$.ptr;s.$$=s.$$;for(var k=s.$$.ptrType.registeredClass,a=s.$$.ptr;l.baseClass;)o=l.upcast(o),l=l.baseClass;for(;k.baseClass;)a=k.upcast(a),k=k.baseClass;return l===k&&o===a},clone(){if(this.$$.ptr||ZA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var s=oA(Object.create(Object.getPrototypeOf(this),{$$:{value:te(this.$$)}}));return s.$$.count.value+=1,s.$$.deleteScheduled=!1,s},delete(){this.$$.ptr||ZA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&p("Object already scheduled for deletion"),Zr(this),Aj(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||ZA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&p("Object already scheduled for deletion"),$A.push(this),$A.length===1&&rj&&rj(ne),this.$$.deleteScheduled=!0,this}});let j=Symbol.dispose;j&&(r[j]=r.delete)};function FA(){}var jj=(r,j)=>Object.defineProperty(j,"name",{value:r}),tj={},ej=(r,j,s)=>{if(r[j].overloadTable===void 0){var l=r[j];r[j]=function(...o){return r[j].overloadTable.hasOwnProperty(o.length)||p(\`Function '\${s}' called with an invalid number of arguments (\${o.length}) - expects one of (\${r[j].overloadTable})!\`),r[j].overloadTable[o.length].apply(this,o)},r[j].overloadTable=[],r[j].overloadTable[l.argCount]=l}},nj=(r,j,s)=>{e.hasOwnProperty(r)?((s===void 0||e[r].overloadTable!==void 0&&e[r].overloadTable[s]!==void 0)&&p(\`Cannot register public name '\${r}' twice\`),ej(e,r,r),e[r].overloadTable.hasOwnProperty(s)&&p(\`Cannot register multiple overloads of a function with the same number of arguments (\${s})!\`),e[r].overloadTable[s]=j):(e[r]=j,e[r].argCount=s)},ie=48,le=57,oe=r=>{r=r.replace(/[^a-zA-Z0-9_]/g,"$");var j=r.charCodeAt(0);return j>=ie&&j<=le?\`_\${r}\`:r};function ae(r,j,s,l,o,k,a,u){this.name=r,this.constructor=j,this.instancePrototype=s,this.rawDestructor=l,this.baseClass=o,this.getActualType=k,this.upcast=a,this.downcast=u,this.pureVirtualFunctions=[]}var vA=(r,j,s)=>{for(;j!==s;)j.upcast||p(\`Expected null or instance of \${s.name}, got an instance of \${j.name}\`),r=j.upcast(r),j=j.baseClass;return r},rr=r=>{if(r===null)return"null";var j=typeof r;return j==="object"||j==="array"||j==="function"?r.toString():""+r};function ke(r,j){if(j===null)return this.isReference&&p(\`null is not a valid \${this.name}\`),0;j.$$||p(\`Cannot pass "\${rr(j)}" as a \${this.name}\`),j.$$.ptr||p(\`Cannot pass deleted object as a pointer of type \${this.name}\`);var s=j.$$.ptrType.registeredClass,l=vA(j.$$.ptr,s,this.registeredClass);return l}function ue(r,j){var s;if(j===null)return this.isReference&&p(\`null is not a valid \${this.name}\`),this.isSmartPointer?(s=this.rawConstructor(),r!==null&&r.push(this.rawDestructor,s),s):0;(!j||!j.$$)&&p(\`Cannot pass "\${rr(j)}" as a \${this.name}\`),j.$$.ptr||p(\`Cannot pass deleted object as a pointer of type \${this.name}\`),!this.isConst&&j.$$.ptrType.isConst&&p(\`Cannot convert argument of type \${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type \${this.name}\`);var l=j.$$.ptrType.registeredClass;if(s=vA(j.$$.ptr,l,this.registeredClass),this.isSmartPointer)switch(j.$$.smartPtr===void 0&&p("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:j.$$.smartPtrType===this?s=j.$$.smartPtr:p(\`Cannot convert argument of type \${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type \${this.name}\`);break;case 1:s=j.$$.smartPtr;break;case 2:if(j.$$.smartPtrType===this)s=j.$$.smartPtr;else{var o=j.clone();s=this.rawShare(s,er.toHandle(()=>o.delete())),r!==null&&r.push(this.rawDestructor,s)}break;default:p("Unsupported sharing policy")}return s}function ce(r,j){if(j===null)return this.isReference&&p(\`null is not a valid \${this.name}\`),0;j.$$||p(\`Cannot pass "\${rr(j)}" as a \${this.name}\`),j.$$.ptr||p(\`Cannot pass deleted object as a pointer of type \${this.name}\`),j.$$.ptrType.isConst&&p(\`Cannot convert argument of type \${j.$$.ptrType.name} to parameter type \${this.name}\`);var s=j.$$.ptrType.registeredClass,l=vA(j.$$.ptr,s,this.registeredClass);return l}function LA(r){return this.fromWireType(I[r>>2])}var sj=(r,j,s)=>{if(j===s)return r;if(s.baseClass===void 0)return null;var l=sj(r,j,s.baseClass);return l===null?null:s.downcast(l)},de={},qe=(r,j)=>{for(j===void 0&&p("ptr should not be undefined");r.baseClass;)j=r.upcast(j),r=r.baseClass;return j},fe=(r,j)=>(j=qe(r,j),de[j]),Ce=class extends Error{constructor(j){super(j),this.name="InternalError"}},gA=r=>{throw new Ce(r)},_A=(r,j)=>{(!j.ptrType||!j.ptr)&&gA("makeClassHandle requires ptr and ptrType");var s=!!j.smartPtrType,l=!!j.smartPtr;return s!==l&&gA("Both smartPtrType and smartPtr must be specified"),j.count={value:1},oA(Object.create(r,{$$:{value:j,writable:!0}}))};function Ge(r){var j=this.getPointee(r);if(!j)return this.destructor(r),null;var s=fe(this.registeredClass,j);if(s!==void 0){if(s.$$.count.value===0)return s.$$.ptr=j,s.$$.smartPtr=r,s.clone();var l=s.clone();return this.destructor(r),l}function o(){return this.isSmartPointer?_A(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:j,smartPtrType:this,smartPtr:r}):_A(this.registeredClass.instancePrototype,{ptrType:this,ptr:r})}var k=this.registeredClass.getActualType(j),a=tj[k];if(!a)return o.call(this);var u;this.isConst?u=a.constPointerType:u=a.pointerType;var c=sj(j,this.registeredClass,u.registeredClass);return c===null?o.call(this):this.isSmartPointer?_A(u.registeredClass.instancePrototype,{ptrType:u,ptr:c,smartPtrType:this,smartPtr:r}):_A(u.registeredClass.instancePrototype,{ptrType:u,ptr:c})}var pe=()=>{Object.assign(HA.prototype,{getPointee(r){return this.rawGetPointee&&(r=this.rawGetPointee(r)),r},destructor(r){this.rawDestructor?.(r)},readValueFromPointer:LA,fromWireType:Ge})};function HA(r,j,s,l,o,k,a,u,c,f,G){this.name=r,this.registeredClass=j,this.isReference=s,this.isConst=l,this.isSmartPointer=o,this.pointeeType=k,this.sharingPolicy=a,this.rawGetPointee=u,this.rawConstructor=c,this.rawShare=f,this.rawDestructor=G,!o&&j.baseClass===void 0?l?(this.toWireType=ke,this.destructorFunction=null):(this.toWireType=ce,this.destructorFunction=null):this.toWireType=ue}var ij=(r,j,s)=>{e.hasOwnProperty(r)||gA("Replacing nonexistent public symbol"),e[r].overloadTable!==void 0&&s!==void 0?e[r].overloadTable[s]=j:(e[r]=j,e[r].argCount=s)},b=(r,j,s=!1)=>{r=L(r);function l(){var k=zr(j);return k}var o=l();return typeof o!="function"&&p(\`unknown function pointer with signature \${r}: \${j}\`),o};class he extends Error{}var me=r=>{var j=Ej(r),s=L(j);return O(j),s},rA=(r,j)=>{var s=[],l={};function o(k){if(!l[k]&&!AA[k]){if(IA[k]){IA[k].forEach(o);return}s.push(k),l[k]=!0}}throw j.forEach(o),new he(\`\${r}: \`+s.map(me).join([", "]))},M=(r,j,s)=>{r.forEach(u=>IA[u]=j);function l(u){var c=s(u);c.length!==r.length&&gA("Mismatched type converter count");for(var f=0;f<r.length;++f)K(r[f],c[f])}var o=new Array(j.length),k=[],a=0;for(let[u,c]of j.entries())AA.hasOwnProperty(c)?o[u]=AA[c]:(k.push(c),Z.hasOwnProperty(c)||(Z[c]=[]),Z[c].push(()=>{o[u]=AA[c],++a,a===k.length&&l(o)}));k.length===0&&l(o)},Ee=(r,j,s,l,o,k,a,u,c,f,G,m,$)=>{G=L(G),k=b(o,k),u&&=b(a,u),f&&=b(c,f),$=b(m,$);var E=oe(G);nj(E,function(){rA(\`Cannot construct \${G} due to unbound types\`,[l])}),M([r,j,s],l?[l]:[],F=>{F=F[0];var H,w;l?(H=F.registeredClass,w=H.instancePrototype):w=FA.prototype;var y=jj(G,function(...ar){if(Object.getPrototypeOf(this)!==kA)throw new lA(\`Use 'new' to construct \${G}\`);if(_.constructor_body===void 0)throw new lA(\`\${G} has no accessible constructor\`);var bj=_.constructor_body[ar.length];if(bj===void 0)throw new lA(\`Tried to invoke ctor of \${G} with invalid number of parameters (\${ar.length}) - expected (\${Object.keys(_.constructor_body).toString()}) parameters instead!\`);return bj.apply(this,ar)}),kA=Object.create(w,{constructor:{value:y}});y.prototype=kA;var _=new ae(G,y,kA,$,H,k,u,f);_.baseClass&&(_.baseClass.__derivedClasses??=[],_.baseClass.__derivedClasses.push(_));var Gn=new HA(G,_,!0,!1,!1),Kj=new HA(G+"*",_,!1,!1,!1),Jj=new HA(G+" const*",_,!1,!0,!1);return tj[r]={pointerType:Kj,constPointerType:Jj},ij(E,y),[Gn,Kj,Jj]})},jr=(r,j)=>{for(var s=[],l=0;l<r;l++)s.push(I[j+l*4>>2]);return s},lj=r=>{for(;r.length;){var j=r.pop(),s=r.pop();s(j)}};function oj(r){for(var j=1;j<r.length;++j)if(r[j]!==null&&r[j].destructorFunction===void 0)return!0;return!1}function Ie(r,j,s,l){var o=oj(r),k=r.length-2,a=[],u=["fn"];j&&u.push("thisWired");for(var c=0;c<k;++c)a.push(\`arg\${c}\`),u.push(\`arg\${c}Wired\`);a=a.join(","),u=u.join(",");var f=\`return function (\${a}) {
3212
+ \\fX\\0\\x90!\\0\\0\\0\\0\`)}function xs(r){return r}async function bt(r){return r}async function Ot(r,j){try{var s=await bt(r),l=await WebAssembly.instantiate(s,j);return l}catch(o){N(\`failed to asynchronously prepare wasm: \${o}\`),RA(o)}}async function wt(r,j,s){return Ot(j,s)}function br(){Cn();var r={a:Bj};return r}async function Or(){function r(a,u){return tA=a.exports,Xt(tA.M),fn(tA),nA=u,tA}function j(a){return r(a.instance,a.module)}var s=br();if(e.instantiateWasm)return new Promise((a,u)=>{e.instantiateWasm(s,(c,f)=>{a(r(c,f))})});if(C){var l=new WebAssembly.Instance(nA,br());return r(l,nA)}Jr??=Jt();var o=await wt(_r,Jr,s),k=j(o);return k}class wr{name="ExitStatus";constructor(j){this.message=\`Program terminated with exit(\${j})\`,this.status=j}}var Pr=r=>{r.terminate(),r.onmessage=j=>{}},Mr=r=>{var j=h.pthreads[r];h.returnWorkerToPool(j)},Tr=r=>{for(;r.length>0;)r.shift()(e)},Ur=[],Pt=r=>Ur.push(r),Mt=r=>{var j=h.getNewWorker();if(!j)return 6;h.runningWorkers.push(j),h.pthreads[r.pthread_ptr]=j,j.pthread_ptr=r.pthread_ptr;var s={cmd:"run",start_routine:r.startRoutine,arg:r.arg,pthread_ptr:r.pthread_ptr};return j.postMessage(s,r.transferList),0},XA=0,zA=()=>YA||XA>0,Tt=()=>xj(),Sr=r=>Hj(r),Ut=r=>yj(r),iA=(r,j,s,...l)=>{var o=8*l.length*2,k=Tt(),a=Ut(o),u=a>>3;for(var c of l)typeof c=="bigint"?(W[u++]=1n,W[u++]=c):(W[u++]=0n,EA[u++]=c);var f=vj(r,j,o,a,s);return Sr(k),f};function Vr(r){if(C)return iA(0,0,1,r);z=r,zA()||(h.terminateAllThreads(),e.onExit?.(r),hA=!0),pA(r,new wr(r))}function Wr(r){if(C)return iA(1,0,0,r);QA(r)}var St=(r,j)=>{if(z=r,C)throw Wr(r),"unwind";Vr(r)},QA=St,h={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init(){C||h.initMainThread()},initMainThread(){},terminateAllThreads:()=>{for(var r of h.runningWorkers)Pr(r);for(var r of h.unusedWorkers)Pr(r);h.unusedWorkers=[],h.runningWorkers=[],h.pthreads={}},returnWorkerToPool:r=>{var j=r.pthread_ptr;delete h.pthreads[j],h.unusedWorkers.push(r),h.runningWorkers.splice(h.runningWorkers.indexOf(r),1),r.pthread_ptr=0,Lj(j)},threadInitTLS(){h.tlsInitFunctions.forEach(r=>r())},loadWasmModuleToWorker:r=>new Promise(j=>{r.onmessage=k=>{var a=k.data,u=a.cmd;if(a.targetThread&&a.targetThread!=xA()){var c=h.pthreads[a.targetThread];c?c.postMessage(a,a.transferList):N(\`Internal error! Worker sent a message "\${u}" to target pthread \${a.targetThread}, but that thread no longer exists!\`);return}u==="checkMailbox"?yA():u==="spawnThread"?Mt(a):u==="cleanupThread"?Gj(()=>Mr(a.thread)):u==="loaded"?(r.loaded=!0,j(r)):a.target==="setimmediate"?r.postMessage(a):u==="callHandler"?e[a.handler](...a.args):u&&N(\`worker sent an unknown command \${u}\`)},r.onerror=k=>{var a="worker sent an error!";throw N(\`\${a} \${k.filename}:\${k.lineno}: \${k.message}\`),k};var s=[],l=["onExit","onAbort","print","printErr"];for(var o of l)e.propertyIsEnumerable(o)&&s.push(o);r.postMessage({cmd:"load",handlers:s,wasmMemory:Y,wasmModule:nA})}),allocateUnusedWorker(){var r,j=n;e.mainScriptUrlOrBlob&&(j=e.mainScriptUrlOrBlob,typeof j!="string"&&(j=URL.createObjectURL(j))),r=new Worker(j,{name:"em-pthread"}),h.unusedWorkers.push(r)},getNewWorker(){return h.unusedWorkers.length==0&&(h.allocateUnusedWorker(),h.loadWasmModuleToWorker(h.unusedWorkers[0])),h.unusedWorkers.pop()}},Rr=[],Vt=r=>Rr.push(r);function Wt(r){var j=I[r+52>>2],s=I[r+56>>2],l=j-s;_j(j,l),Sr(j)}var Xr=[],zr=r=>{var j=Xr[r];return j||(Xr[r]=j=Dj.get(r)),j},Rt=(r,j)=>{XA=0,YA=0;var s=zr(r)(j);function l(o){if(zA()){z=o;return}or(o)}l(s)},YA=!0,Xt=r=>h.tlsInitFunctions.push(r),Y;class zt{constructor(j){this.excPtr=j,this.ptr=j-24}set_type(j){I[this.ptr+4>>2]=j}get_type(){return I[this.ptr+4>>2]}set_destructor(j){I[this.ptr+8>>2]=j}get_destructor(){return I[this.ptr+8>>2]}set_caught(j){j=j?1:0,V[this.ptr+12]=j}get_caught(){return V[this.ptr+12]!=0}set_rethrown(j){j=j?1:0,V[this.ptr+13]=j}get_rethrown(){return V[this.ptr+13]!=0}init(j,s){this.set_adjusted_ptr(0),this.set_type(j),this.set_destructor(s)}set_adjusted_ptr(j){I[this.ptr+16>>2]=j}get_adjusted_ptr(){return I[this.ptr+16>>2]}}var Qr=0,Qt=0,Yt=(r,j,s)=>{var l=new zt(r);throw l.init(j,s),Qr=r,Qt++,Qr},Zt=()=>RA(""),L=r=>{for(var j="";;){var s=x[r++];if(!s)return j;j+=String.fromCharCode(s)}},Z={},AA={},IA={},lA=class extends Error{constructor(j){super(j),this.name="BindingError"}},p=r=>{throw new lA(r)};function Ae(r,j,s={}){var l=j.name;if(r||p(\`type "\${l}" must have a positive integer typeid pointer\`),AA.hasOwnProperty(r)){if(s.ignoreDuplicateRegistrations)return;p(\`Cannot register type '\${l}' twice\`)}if(AA[r]=j,delete IA[r],Z.hasOwnProperty(r)){var o=Z[r];delete Z[r],o.forEach(k=>k())}}function K(r,j,s={}){return Ae(r,j,s)}var Yr=(r,j,s)=>{switch(j){case 1:return s?l=>V[l]:l=>x[l];case 2:return s?l=>mA[l>>1]:l=>sA[l>>1];case 4:return s?l=>Q[l>>2]:l=>I[l>>2];case 8:return s?l=>W[l>>3]:l=>Dr[l>>3];default:throw new TypeError(\`invalid integer width (\${j}): \${r}\`)}},re=(r,j,s,l,o)=>{j=L(j);let k=l===0n,a=u=>u;if(k){let u=s*8;a=c=>BigInt.asUintN(u,c),o=a(o)}K(r,{name:j,fromWireType:a,toWireType:(u,c)=>(typeof c=="number"&&(c=BigInt(c)),c),readValueFromPointer:Yr(j,s,!k),destructorFunction:null})},je=(r,j,s,l)=>{j=L(j),K(r,{name:j,fromWireType:function(o){return!!o},toWireType:function(o,k){return k?s:l},readValueFromPointer:function(o){return this.fromWireType(x[o])},destructorFunction:null})},te=r=>({count:r.count,deleteScheduled:r.deleteScheduled,preservePointerOnDelete:r.preservePointerOnDelete,ptr:r.ptr,ptrType:r.ptrType,smartPtr:r.smartPtr,smartPtrType:r.smartPtrType}),ZA=r=>{function j(s){return s.$$.ptrType.registeredClass.name}p(j(r)+" instance already deleted")},Ar=!1,Zr=r=>{},ee=r=>{r.smartPtr?r.smartPtrType.rawDestructor(r.smartPtr):r.ptrType.registeredClass.rawDestructor(r.ptr)},Aj=r=>{r.count.value-=1;var j=r.count.value===0;j&&ee(r)},oA=r=>globalThis.FinalizationRegistry?(Ar=new FinalizationRegistry(j=>{Aj(j.$$)}),oA=j=>{var s=j.$$,l=!!s.smartPtr;if(l){var o={$$:s};Ar.register(j,o,j)}return j},Zr=j=>Ar.unregister(j),oA(r)):(oA=j=>j,r),$A=[],ne=()=>{for(;$A.length;){var r=$A.pop();r.$$.deleteScheduled=!1,r.delete()}},rj,se=()=>{let r=FA.prototype;Object.assign(r,{isAliasOf(s){if(!(this instanceof FA)||!(s instanceof FA))return!1;var l=this.$$.ptrType.registeredClass,o=this.$$.ptr;s.$$=s.$$;for(var k=s.$$.ptrType.registeredClass,a=s.$$.ptr;l.baseClass;)o=l.upcast(o),l=l.baseClass;for(;k.baseClass;)a=k.upcast(a),k=k.baseClass;return l===k&&o===a},clone(){if(this.$$.ptr||ZA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var s=oA(Object.create(Object.getPrototypeOf(this),{$$:{value:te(this.$$)}}));return s.$$.count.value+=1,s.$$.deleteScheduled=!1,s},delete(){this.$$.ptr||ZA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&p("Object already scheduled for deletion"),Zr(this),Aj(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||ZA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&p("Object already scheduled for deletion"),$A.push(this),$A.length===1&&rj&&rj(ne),this.$$.deleteScheduled=!0,this}});let j=Symbol.dispose;j&&(r[j]=r.delete)};function FA(){}var jj=(r,j)=>Object.defineProperty(j,"name",{value:r}),tj={},ej=(r,j,s)=>{if(r[j].overloadTable===void 0){var l=r[j];r[j]=function(...o){return r[j].overloadTable.hasOwnProperty(o.length)||p(\`Function '\${s}' called with an invalid number of arguments (\${o.length}) - expects one of (\${r[j].overloadTable})!\`),r[j].overloadTable[o.length].apply(this,o)},r[j].overloadTable=[],r[j].overloadTable[l.argCount]=l}},nj=(r,j,s)=>{e.hasOwnProperty(r)?((s===void 0||e[r].overloadTable!==void 0&&e[r].overloadTable[s]!==void 0)&&p(\`Cannot register public name '\${r}' twice\`),ej(e,r,r),e[r].overloadTable.hasOwnProperty(s)&&p(\`Cannot register multiple overloads of a function with the same number of arguments (\${s})!\`),e[r].overloadTable[s]=j):(e[r]=j,e[r].argCount=s)},ie=48,le=57,oe=r=>{r=r.replace(/[^a-zA-Z0-9_]/g,"$");var j=r.charCodeAt(0);return j>=ie&&j<=le?\`_\${r}\`:r};function ae(r,j,s,l,o,k,a,u){this.name=r,this.constructor=j,this.instancePrototype=s,this.rawDestructor=l,this.baseClass=o,this.getActualType=k,this.upcast=a,this.downcast=u,this.pureVirtualFunctions=[]}var vA=(r,j,s)=>{for(;j!==s;)j.upcast||p(\`Expected null or instance of \${s.name}, got an instance of \${j.name}\`),r=j.upcast(r),j=j.baseClass;return r},rr=r=>{if(r===null)return"null";var j=typeof r;return j==="object"||j==="array"||j==="function"?r.toString():""+r};function ke(r,j){if(j===null)return this.isReference&&p(\`null is not a valid \${this.name}\`),0;j.$$||p(\`Cannot pass "\${rr(j)}" as a \${this.name}\`),j.$$.ptr||p(\`Cannot pass deleted object as a pointer of type \${this.name}\`);var s=j.$$.ptrType.registeredClass,l=vA(j.$$.ptr,s,this.registeredClass);return l}function ue(r,j){var s;if(j===null)return this.isReference&&p(\`null is not a valid \${this.name}\`),this.isSmartPointer?(s=this.rawConstructor(),r!==null&&r.push(this.rawDestructor,s),s):0;(!j||!j.$$)&&p(\`Cannot pass "\${rr(j)}" as a \${this.name}\`),j.$$.ptr||p(\`Cannot pass deleted object as a pointer of type \${this.name}\`),!this.isConst&&j.$$.ptrType.isConst&&p(\`Cannot convert argument of type \${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type \${this.name}\`);var l=j.$$.ptrType.registeredClass;if(s=vA(j.$$.ptr,l,this.registeredClass),this.isSmartPointer)switch(j.$$.smartPtr===void 0&&p("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:j.$$.smartPtrType===this?s=j.$$.smartPtr:p(\`Cannot convert argument of type \${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type \${this.name}\`);break;case 1:s=j.$$.smartPtr;break;case 2:if(j.$$.smartPtrType===this)s=j.$$.smartPtr;else{var o=j.clone();s=this.rawShare(s,er.toHandle(()=>o.delete())),r!==null&&r.push(this.rawDestructor,s)}break;default:p("Unsupported sharing policy")}return s}function ce(r,j){if(j===null)return this.isReference&&p(\`null is not a valid \${this.name}\`),0;j.$$||p(\`Cannot pass "\${rr(j)}" as a \${this.name}\`),j.$$.ptr||p(\`Cannot pass deleted object as a pointer of type \${this.name}\`),j.$$.ptrType.isConst&&p(\`Cannot convert argument of type \${j.$$.ptrType.name} to parameter type \${this.name}\`);var s=j.$$.ptrType.registeredClass,l=vA(j.$$.ptr,s,this.registeredClass);return l}function LA(r){return this.fromWireType(I[r>>2])}var sj=(r,j,s)=>{if(j===s)return r;if(s.baseClass===void 0)return null;var l=sj(r,j,s.baseClass);return l===null?null:s.downcast(l)},de={},qe=(r,j)=>{for(j===void 0&&p("ptr should not be undefined");r.baseClass;)j=r.upcast(j),r=r.baseClass;return j},fe=(r,j)=>(j=qe(r,j),de[j]),Ce=class extends Error{constructor(j){super(j),this.name="InternalError"}},gA=r=>{throw new Ce(r)},_A=(r,j)=>{(!j.ptrType||!j.ptr)&&gA("makeClassHandle requires ptr and ptrType");var s=!!j.smartPtrType,l=!!j.smartPtr;return s!==l&&gA("Both smartPtrType and smartPtr must be specified"),j.count={value:1},oA(Object.create(r,{$$:{value:j,writable:!0}}))};function Ge(r){var j=this.getPointee(r);if(!j)return this.destructor(r),null;var s=fe(this.registeredClass,j);if(s!==void 0){if(s.$$.count.value===0)return s.$$.ptr=j,s.$$.smartPtr=r,s.clone();var l=s.clone();return this.destructor(r),l}function o(){return this.isSmartPointer?_A(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:j,smartPtrType:this,smartPtr:r}):_A(this.registeredClass.instancePrototype,{ptrType:this,ptr:r})}var k=this.registeredClass.getActualType(j),a=tj[k];if(!a)return o.call(this);var u;this.isConst?u=a.constPointerType:u=a.pointerType;var c=sj(j,this.registeredClass,u.registeredClass);return c===null?o.call(this):this.isSmartPointer?_A(u.registeredClass.instancePrototype,{ptrType:u,ptr:c,smartPtrType:this,smartPtr:r}):_A(u.registeredClass.instancePrototype,{ptrType:u,ptr:c})}var pe=()=>{Object.assign(HA.prototype,{getPointee(r){return this.rawGetPointee&&(r=this.rawGetPointee(r)),r},destructor(r){this.rawDestructor?.(r)},readValueFromPointer:LA,fromWireType:Ge})};function HA(r,j,s,l,o,k,a,u,c,f,G){this.name=r,this.registeredClass=j,this.isReference=s,this.isConst=l,this.isSmartPointer=o,this.pointeeType=k,this.sharingPolicy=a,this.rawGetPointee=u,this.rawConstructor=c,this.rawShare=f,this.rawDestructor=G,!o&&j.baseClass===void 0?l?(this.toWireType=ke,this.destructorFunction=null):(this.toWireType=ce,this.destructorFunction=null):this.toWireType=ue}var ij=(r,j,s)=>{e.hasOwnProperty(r)||gA("Replacing nonexistent public symbol"),e[r].overloadTable!==void 0&&s!==void 0?e[r].overloadTable[s]=j:(e[r]=j,e[r].argCount=s)},b=(r,j,s=!1)=>{r=L(r);function l(){var k=zr(j);return k}var o=l();return typeof o!="function"&&p(\`unknown function pointer with signature \${r}: \${j}\`),o};class he extends Error{}var me=r=>{var j=Ej(r),s=L(j);return O(j),s},rA=(r,j)=>{var s=[],l={};function o(k){if(!l[k]&&!AA[k]){if(IA[k]){IA[k].forEach(o);return}s.push(k),l[k]=!0}}throw j.forEach(o),new he(\`\${r}: \`+s.map(me).join([", "]))},M=(r,j,s)=>{r.forEach(u=>IA[u]=j);function l(u){var c=s(u);c.length!==r.length&&gA("Mismatched type converter count");for(var f=0;f<r.length;++f)K(r[f],c[f])}var o=new Array(j.length),k=[],a=0;for(let[u,c]of j.entries())AA.hasOwnProperty(c)?o[u]=AA[c]:(k.push(c),Z.hasOwnProperty(c)||(Z[c]=[]),Z[c].push(()=>{o[u]=AA[c],++a,a===k.length&&l(o)}));k.length===0&&l(o)},Ee=(r,j,s,l,o,k,a,u,c,f,G,m,$)=>{G=L(G),k=b(o,k),u&&=b(a,u),f&&=b(c,f),$=b(m,$);var E=oe(G);nj(E,function(){rA(\`Cannot construct \${G} due to unbound types\`,[l])}),M([r,j,s],l?[l]:[],F=>{F=F[0];var H,w;l?(H=F.registeredClass,w=H.instancePrototype):w=FA.prototype;var y=jj(G,function(...ar){if(Object.getPrototypeOf(this)!==kA)throw new lA(\`Use 'new' to construct \${G}\`);if(_.constructor_body===void 0)throw new lA(\`\${G} has no accessible constructor\`);var bj=_.constructor_body[ar.length];if(bj===void 0)throw new lA(\`Tried to invoke ctor of \${G} with invalid number of parameters (\${ar.length}) - expected (\${Object.keys(_.constructor_body).toString()}) parameters instead!\`);return bj.apply(this,ar)}),kA=Object.create(w,{constructor:{value:y}});y.prototype=kA;var _=new ae(G,y,kA,$,H,k,u,f);_.baseClass&&(_.baseClass.__derivedClasses??=[],_.baseClass.__derivedClasses.push(_));var Gn=new HA(G,_,!0,!1,!1),Kj=new HA(G+"*",_,!1,!1,!1),Jj=new HA(G+" const*",_,!1,!0,!1);return tj[r]={pointerType:Kj,constPointerType:Jj},ij(E,y),[Gn,Kj,Jj]})},jr=(r,j)=>{for(var s=[],l=0;l<r;l++)s.push(I[j+l*4>>2]);return s},lj=r=>{for(;r.length;){var j=r.pop(),s=r.pop();s(j)}};function oj(r){for(var j=1;j<r.length;++j)if(r[j]!==null&&r[j].destructorFunction===void 0)return!0;return!1}function Ie(r,j,s,l){var o=oj(r),k=r.length-2,a=[],u=["fn"];j&&u.push("thisWired");for(var c=0;c<k;++c)a.push(\`arg\${c}\`),u.push(\`arg\${c}Wired\`);a=a.join(","),u=u.join(",");var f=\`return function (\${a}) {
3213
3213
  \`;o&&(f+=\`var destructors = [];
3214
3214
  \`);var G=o?"destructors":"null",m=["humanName","throwBindingError","invoker","fn","runDestructors","fromRetWire","toClassParamWire"];j&&(f+=\`var thisWired = toClassParamWire(\${G}, this);
3215
3215
  \`);for(var c=0;c<k;++c){var $=\`toArg\${c}Wire\`;f+=\`var arg\${c}Wired = \${$}(\${G}, arg\${c});
@@ -3219,8 +3219,8 @@ K\\xE08\\xDF\\0}\\xBC\\x8A\\x1B\\f\\xE5\\xFF\\xCF\\xE8?\\x9F\\xFFFq\\0\\x88\\xB
3219
3219
  \`,m.push(\`\${E}_dtor\`))}return s&&(f+=\`var ret = fromRetWire(rv);
3220
3220
  return ret;
3221
3221
  \`),f+=\`}
3222
- \`,new Function(m,f)}function tr(r,j,s,l,o,k){var a=j.length;a<2&&p("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var u=j[1]!==null&&s!==null,c=oj(j),f=!j[0].isVoid,G=j[0],m=j[1],$=[r,p,l,o,lj,G.fromWireType.bind(G),m?.toWireType.bind(m)],E=2;E<a;++E){var F=j[E];$.push(F.toWireType.bind(F))}if(!c)for(var E=u?1:2;E<j.length;++E)j[E].destructorFunction!==null&&$.push(j[E].destructorFunction);var w=Ie(j,u,f,k)(...$);return jj(r,w)}var $e=(r,j,s,l,o,k)=>{var a=jr(j,s);o=b(l,o),M([],[r],u=>{u=u[0];var c=\`constructor \${u.name}\`;if(u.registeredClass.constructor_body===void 0&&(u.registeredClass.constructor_body=[]),u.registeredClass.constructor_body[j-1]!==void 0)throw new lA(\`Cannot register multiple constructors with identical number of parameters (\${j-1}) for class '\${u.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!\`);return u.registeredClass.constructor_body[j-1]=()=>{rA(\`Cannot construct \${u.name} due to unbound types\`,a)},M([],a,f=>(f.splice(1,0,null),u.registeredClass.constructor_body[j-1]=tr(c,f,null,o,k),[])),[]})},aj=r=>{r=r.trim();let j=r.indexOf("(");return j===-1?r:r.slice(0,j)},Fe=(r,j,s,l,o,k,a,u,c,f)=>{var G=jr(s,l);j=L(j),j=aj(j),k=b(o,k,c),M([],[r],m=>{m=m[0];var $=\`\${m.name}.\${j}\`;j.startsWith("@@")&&(j=Symbol[j.substring(2)]),u&&m.registeredClass.pureVirtualFunctions.push(j);function E(){rA(\`Cannot call \${$} due to unbound types\`,G)}var F=m.registeredClass.instancePrototype,H=F[j];return H===void 0||H.overloadTable===void 0&&H.className!==m.name&&H.argCount===s-2?(E.argCount=s-2,E.className=m.name,F[j]=E):(ej(F,j,$),F[j].overloadTable[s-2]=E),M([],G,w=>{var y=tr($,w,m,k,a,c);return F[j].overloadTable===void 0?(y.argCount=s-2,F[j]=y):F[j].overloadTable[s-2]=y,[]}),[]})},kj=(r,j,s)=>(r instanceof Object||p(\`\${s} with invalid "this": \${r}\`),r instanceof j.registeredClass.constructor||p(\`\${s} incompatible with "this" of type \${r.constructor.name}\`),r.$$.ptr||p(\`cannot call emscripten binding method \${s} on deleted object\`),vA(r.$$.ptr,r.$$.ptrType.registeredClass,j.registeredClass)),ve=(r,j,s,l,o,k,a,u,c,f)=>{j=L(j),o=b(l,o),M([],[r],G=>{G=G[0];var m=\`\${G.name}.\${j}\`,$={get(){rA(\`Cannot access \${m} due to unbound types\`,[s,a])},enumerable:!0,configurable:!0};return c?$.set=()=>rA(\`Cannot access \${m} due to unbound types\`,[s,a]):$.set=E=>p(m+" is a read-only property"),Object.defineProperty(G.registeredClass.instancePrototype,j,$),M([],c?[s,a]:[s],E=>{var F=E[0],H={get(){var y=kj(this,G,m+" getter");return F.fromWireType(o(k,y))},enumerable:!0};if(c){c=b(u,c);var w=E[1];H.set=function(y){var kA=kj(this,G,m+" setter"),_=[];c(f,kA,w.toWireType(_,y)),lj(_)}}return Object.defineProperty(G.registeredClass.instancePrototype,j,H),[]}),[]})},uj=[],jA=[0,1,,1,null,1,!0,1,!1,1],Le=r=>{r>9&&--jA[r+1]===0&&(jA[r]=void 0,uj.push(r))},er={toValue:r=>(r||p(\`Cannot use deleted val. handle = \${r}\`),jA[r]),toHandle:r=>{switch(r){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:{let j=uj.pop()||jA.length;return jA[j]=r,jA[j+1]=1,j}}}},ge={name:"emscripten::val",fromWireType:r=>{var j=er.toValue(r);return Le(r),j},toWireType:(r,j)=>er.toHandle(j),readValueFromPointer:LA,destructorFunction:null},_e=r=>K(r,ge),He=(r,j)=>{switch(j){case 4:return function(s){return this.fromWireType(xr[s>>2])};case 8:return function(s){return this.fromWireType(EA[s>>3])};default:throw new TypeError(\`invalid float width (\${j}): \${r}\`)}},ye=(r,j,s)=>{j=L(j),K(r,{name:j,fromWireType:l=>l,toWireType:(l,o)=>o,readValueFromPointer:He(j,s),destructorFunction:null})},xe=(r,j,s,l,o,k,a,u)=>{var c=jr(j,s);r=L(r),r=aj(r),o=b(l,o,a),nj(r,function(){rA(\`Cannot call \${r} due to unbound types\`,c)},j-1),M([],c,f=>{var G=[f[0],null].concat(f.slice(1));return ij(r,tr(r,G,null,o,k,a),j-1),[]})},De=(r,j,s,l,o)=>{j=L(j);let k=l===0,a=c=>c;if(k){var u=32-8*s;a=c=>c<<u>>>u,o=a(o)}K(r,{name:j,fromWireType:a,toWireType:(c,f)=>f,readValueFromPointer:Yr(j,s,l!==0),destructorFunction:null})},Be=(r,j,s)=>{var l=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=l[j];function k(a){var u=I[a>>2],c=I[a+4>>2];return new o(V.buffer,c,u)}s=L(s),K(r,{name:s,fromWireType:k,readValueFromPointer:k},{ignoreDuplicateRegistrations:!0})},Ne=(r,j,s,l)=>{if(!(l>0))return 0;for(var o=s,k=s+l-1,a=0;a<r.length;++a){var u=r.codePointAt(a);if(u<=127){if(s>=k)break;j[s++]=u}else if(u<=2047){if(s+1>=k)break;j[s++]=192|u>>6,j[s++]=128|u&63}else if(u<=65535){if(s+2>=k)break;j[s++]=224|u>>12,j[s++]=128|u>>6&63,j[s++]=128|u&63}else{if(s+3>=k)break;j[s++]=240|u>>18,j[s++]=128|u>>12&63,j[s++]=128|u>>6&63,j[s++]=128|u&63,a++}}return j[s]=0,s-o},Ke=(r,j,s)=>Ne(r,x,j,s),Je=r=>{for(var j=0,s=0;s<r.length;++s){var l=r.charCodeAt(s);l<=127?j++:l<=2047?j+=2:l>=55296&&l<=57343?(j+=4,++s):j+=3}return j},cj=globalThis.TextDecoder&&new TextDecoder,dj=(r,j,s,l)=>{var o=j+s;if(l)return o;for(;r[j]&&!(j>=o);)++j;return j},qj=(r,j=0,s,l)=>{var o=dj(r,j,s,l);if(o-j>16&&r.buffer&&cj)return cj.decode(r.buffer instanceof ArrayBuffer?r.subarray(j,o):r.slice(j,o));for(var k="";j<o;){var a=r[j++];if(!(a&128)){k+=String.fromCharCode(a);continue}var u=r[j++]&63;if((a&224)==192){k+=String.fromCharCode((a&31)<<6|u);continue}var c=r[j++]&63;if((a&240)==224?a=(a&15)<<12|u<<6|c:a=(a&7)<<18|u<<12|c<<6|r[j++]&63,a<65536)k+=String.fromCharCode(a);else{var f=a-65536;k+=String.fromCharCode(55296|f>>10,56320|f&1023)}}return k},be=(r,j,s)=>r?qj(x,r,j,s):"",Oe=(r,j)=>{j=L(j);var s=!0;K(r,{name:j,fromWireType(l){var o=I[l>>2],k=l+4,a;if(s)a=be(k,o,!0);else{a="";for(var u=0;u<o;++u)a+=String.fromCharCode(x[k+u])}return O(l),a},toWireType(l,o){o instanceof ArrayBuffer&&(o=new Uint8Array(o));var k,a=typeof o=="string";a||ArrayBuffer.isView(o)&&o.BYTES_PER_ELEMENT==1||p("Cannot pass non-string to std::string"),s&&a?k=Je(o):k=o.length;var u=ir(4+k+1),c=u+4;if(I[u>>2]=k,a)if(s)Ke(o,c,k+1);else for(var f=0;f<k;++f){var G=o.charCodeAt(f);G>255&&(O(u),p("String has UTF-16 code units that do not fit in 8 bits")),x[c+f]=G}else x.set(o,c);return l!==null&&l.push(O,u),u},readValueFromPointer:LA,destructorFunction(l){O(l)}})},fj=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,we=(r,j,s)=>{var l=r>>1,o=dj(sA,l,j/2,s);if(o-l>16&&fj)return fj.decode(sA.slice(l,o));for(var k="",a=l;a<o;++a){var u=sA[a];k+=String.fromCharCode(u)}return k},Pe=(r,j,s)=>{if(s??=2147483647,s<2)return 0;s-=2;for(var l=j,o=s<r.length*2?s/2:r.length,k=0;k<o;++k){var a=r.charCodeAt(k);mA[j>>1]=a,j+=2}return mA[j>>1]=0,j-l},Me=r=>r.length*2,Te=(r,j,s)=>{for(var l="",o=r>>2,k=0;!(k>=j/4);k++){var a=I[o+k];if(!a&&!s)break;l+=String.fromCodePoint(a)}return l},Ue=(r,j,s)=>{if(s??=2147483647,s<4)return 0;for(var l=j,o=l+s-4,k=0;k<r.length;++k){var a=r.codePointAt(k);if(a>65535&&k++,Q[j>>2]=a,j+=4,j+4>o)break}return Q[j>>2]=0,j-l},Se=r=>{for(var j=0,s=0;s<r.length;++s){var l=r.codePointAt(s);l>65535&&s++,j+=4}return j},Ve=(r,j,s)=>{s=L(s);var l,o,k;j===2?(l=we,o=Pe,k=Me):(l=Te,o=Ue,k=Se),K(r,{name:s,fromWireType:a=>{var u=I[a>>2],c=l(a+4,u*j,!0);return O(a),c},toWireType:(a,u)=>{typeof u!="string"&&p(\`Cannot pass non-string to C++ string type \${s}\`);var c=k(u),f=ir(4+c+j);return I[f>>2]=c/j,o(u,f+4,c+j),a!==null&&a.push(O,f),f},readValueFromPointer:LA,destructorFunction(a){O(a)}})},We=(r,j)=>{j=L(j),K(r,{isVoid:!0,name:j,fromWireType:()=>{},toWireType:(s,l)=>{}})},Re=r=>{lr(r,!d,1,!i,65536,!1),h.threadInitTLS()},Cj=r=>{if(r instanceof wr||r=="unwind")return z;pA(1,r)},Xe=()=>{if(!zA())try{if(C){xA()&&or(z);return}QA(z)}catch(r){Cj(r)}},Gj=r=>{if(!hA)try{return r()}catch(j){Cj(j)}finally{Xe()}},ze=!Atomics.waitAsync||globalThis.navigator?.userAgent&&Number((navigator.userAgent.match(/Chrom(e|ium)\\/([0-9]+)\\./)||[])[2])<91,nr=r=>{if(!ze){var j=Atomics.waitAsync(Q,r>>2,r);j.value.then(yA);var s=r+128;Atomics.store(Q,s>>2,1)}},yA=()=>Gj(()=>{var r=xA();r&&(nr(r),gj())}),Qe=(r,j)=>{if(r==j)setTimeout(yA);else if(C)postMessage({targetThread:r,cmd:"checkMailbox"});else{var s=h.pthreads[r];if(!s)return;s.postMessage({cmd:"checkMailbox"})}},sr=[],Ye=(r,j,s,l,o,k,a)=>{sr.length=0;for(var u=o>>3,c=o+l>>3;u<c;){var f;W[u++]?f=W[u++]:f=EA[u++],sr.push(f)}var G=cn[r];h.currentProxiedOperationCallerThread=s;var m=G(...sr);if(h.currentProxiedOperationCallerThread=0,k){m.then($=>Fj(k,a,$));return}return m},Ze=r=>{C?postMessage({cmd:"cleanupThread",thread:r}):Mr(r)},An=r=>{},rn=()=>performance.timeOrigin+performance.now(),jn=9007199254740992,tn=-9007199254740992,en=r=>r<tn||r>jn?NaN:Number(r),nn=()=>{},sn=()=>{XA+=1},ln=()=>{throw sn(),"unwind"},on=r=>{RA("OOM")},an=r=>{var j=x.length;r>>>=0,on(r)};function pj(r){return C?iA(2,0,1,r):52}function hj(r,j,s,l){return C?iA(3,0,1,r,j,s,l):(j=en(j),70)}var kn=[null,[],[]],un=(r,j)=>{var s=kn[r];j===0||j===10?((r===1?SA:N)(qj(s)),s.length=0):s.push(j)};function mj(r,j,s,l){if(C)return iA(4,0,1,r,j,s,l);for(var o=0,k=0;k<s;k++){var a=I[j>>2],u=I[j+4>>2];j+=8;for(var c=0;c<u;c++)un(r,x[a+c]);o+=u}return I[l>>2]=o,0}h.init();for(var aA=new Uint8Array(123),T=25;T>=0;--T)aA[48+T]=52+T,aA[65+T]=T,aA[97+T]=26+T;if(aA[43]=62,aA[47]=63,se(),pe(),Bt(),e.noExitRuntime&&(YA=e.noExitRuntime),e.print&&(SA=e.print),e.printErr&&(N=e.printErr),e.wasmBinary&&(_r=e.wasmBinary),e.arguments&&(v=e.arguments),e.thisProgram&&(B=e.thisProgram),e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.shift()();var cn=[Vr,Wr,pj,hj,mj],Ej,Ij,xA,ir,O,dn,lr,$j,Fj,vj,Lj,or,gj,_j,Hj,yj,xj,qn,Dj;function fn(r){Ej=r.G,Ij=r.H,xA=r.J,ir=e._malloc=r.K,O=e._free=r.L,dn=r.M,lr=r.N,$j=r.O,Fj=r.P,vj=r.Q,Lj=r.R,or=r.S,gj=r.T,_j=r.U,Hj=r.V,yj=r.W,xj=r.X,qn=Dj=r.I}var Bj;function Cn(){Bj={i:Yt,C:Zt,h:re,o:je,n:Ee,m:$e,e:Fe,b:ve,D:_e,l:ye,q:xe,d:De,c:Be,E:Oe,g:Ve,p:We,z:Re,u:Qe,k:Ye,s:Ze,y:nr,B:An,x:nn,A:ln,f:rn,t:an,r:QA,w:pj,v:hj,j:mj,a:Y}}function Nj(){if(C){VA?.(e),Kr();return}Nt();function r(){e.calledRun=!0,!hA&&(Kr(),VA?.(e),e.onRuntimeInitialized?.(),Kt())}e.setStatus?(e.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>e.setStatus(""),1),r()},1)):r()}var tA;return C||(tA=await Or(),Nj()),Br?t=e:t=new Promise((r,j)=>{VA=r,Hr=j}),t}})();typeof Ft=="object"&&typeof UA=="object"?(UA.exports=TA,UA.exports.default=TA):typeof define=="function"&&define.amd&&define([],()=>TA);var _s=globalThis.name=="em-pthread";_s&&TA()});var J={};Fn(J,{AdditionalCaptureBlocks:()=>_n,AdditionalPlaybackBlocks:()=>gn,ClockJumpCheckInterval:()=>Kn,ClockJumpThreshold:()=>Jn,ConnectInterval:()=>Un,ConnectTimeout:()=>Pn,DefaultRefreshRate:()=>yn,HealthCheckTimeout:()=>Nn,MainConnectionPingInterval:()=>bn,MaxNumberOfDecoders:()=>Dn,MinDBFs:()=>Oj,MinTokenLifetime:()=>Mn,MinTokenRefreshInterval:()=>Tn,PlaybackPreload:()=>Hn,RenderQuantumSize:()=>Bn,VadPreload:()=>xn,WebRtcIceTimeout:()=>On,WebRtcTimeout:()=>wn});var gn=3,_n=3,Hn=3,yn=250,xn=3,Dn=512,Bn=128,Oj=-758.596,Nn=1e4,Kn=1e3,Jn=1e4,bn=3e3,On=3e3,wn=1e4,Pn=5e3,Mn=6e4,Tn=5e3,Un=[0,100,200,200,500];function uA(n,A,t){return n.postMessage(A,t)}function ur(n){return n.sampleRate*.02*(n.stereo?2:1)}function cr(n,A){let t=ur(n),e=t*A,i=e+t;return n.samples.subarray(e,i)}function dr(n,A,t){n.headers[A]=t.id}function wj(n){return[n.values[0],n.values[1]]}function Pj(n,A){n.values[0]=A[0],n.values[1]=A[1]}function Mj(n,A){return n.values[2+A*5]}function Tj(n,A,t){n.values[2+A*5]=t}function Uj(n,A){let t=2+A*5+1;return[n.values[t+0],n.values[t+1]]}function Sj(n,A,t){let e=2+A*5+1;n.values[e+0]=t[0],n.values[e+1]=t[1]}function Vj(n,A){return n.values[2+A*5+3]}function Wj(n,A,t){n.values[2+A*5+3]=t}function Rj(n,A){return n.values[2+A*5+4]}function Xj(n,A,t){n.values[2+A*5+4]=t}function zj(n){return n.values[0]!==0}function Qj(n){return n.values[1]}function Yj(n){return n.values[2]}function Zj(n){return n.values[3]}function At(n,A){return n.values[3]=A}function rt(n){return n?Array.from(n).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var Sn;(n=>{let A;(t=>(t[t.InvalidPassword=-1]="InvalidPassword",t[t.Unknown=0]="Unknown",t[t.Unencrypted=1]="Unencrypted",t[t.Encrypted=2]="Encrypted"))(A=n.PeerCipherStatus||={})})(Sn||={});function st(n){return{type:"Success",value:n}}function D(n){return{type:"Failure",reason:n}}var{Deno:jt}=globalThis,Vn=typeof jt?.noColor=="boolean"?jt.noColor:!1,Wn=!Vn;function fr(n,A){return{open:\`\\x1B[\${n.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function Cr(n,A){return Wn?\`\${A.open}\${n.replace(A.regexp,A.open)}\${A.close}\`:n}function qr(n){return Cr(n,fr([0],0))}function tt(n){return Cr(n,fr([1],22))}function Rn(n){return Cr(n,fr([2],22))}var Ts=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),Xn=new Date,DA=(n=>(n[n.CRITICAL=0]="CRITICAL",n[n.ERROR=1]="ERROR",n[n.WARN=2]="WARN",n[n.INFO=3]="INFO",n[n.DEBUG=4]="DEBUG",n))(DA||{}),it={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},zn={4:Rn,3:qr,2:qr,1:tt,0:tt};function Qn({message:n}){return String(n)}function et(n){return JSON.stringify({timestamp:n.date.toISOString(),level:DA[n.level],message:n.message,extra:n.extra})}function nt(n){function A(q,C){return[Math.floor(q/C),q%C]}function t(){let q,C=n.date.valueOf()-Xn.valueOf();[C,q]=A(C,1e3);let[v,B]=A(C,60);return\`\${v.toString().padStart(4,"0")}:\${B.toString().padStart(2,"0")}.\${q.toString().padStart(4,"0")}\`}function e(){return n.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(n.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(n.extra)}let i=it[n.level],d=n.logger.name!==void 0?\`@\${n.logger}\`:"";return\`\${qr(t())}\${d} \${i} \${zn[n.level](String(n.message))}\${e()}\`}function Yn(n){let A=\`[\${n.date.toISOString()}]\`,t=\`[\${DA[n.level]}]\`,e=n.logger.name!==void 0?\`[\${n.logger.name}] \`:"",i=it[n.level];return\`\${A} \${i} \${t.padEnd(7," ")} \${e}\${n.message}\`}function Zn(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var lt={sparse:Qn,json:et,pretty:nt,structured:Yn,default:Zn()?nt:et},As=class{formatter;consoleObject;filter;constructor(n=lt.default,A=4,t=console){this.filter=A,this.formatter=n,this.consoleObject=t}handle(n){let A=this.formatter(n);switch(n.level){case 1:this.consoleObject.error(A);break;case 2:this.consoleObject.warn(A);break;case 3:this.consoleObject.info(A);break;case 4:this.consoleObject.debug(A);break}}};var R=class{#A;sinks;filter;parent;get name(){return this.#A}constructor(n,A=void 0,t=[],e=void 0){this.#A=A,this.sinks=t,this.filter=n,this.parent=e}log(n,A,t=void 0){let e={date:new Date,level:n,logger:this,message:A,extra:t};this.filter<n||this.insert(e)}insert(n){if(!(this.filter<n.level)){for(let A of this.sinks)A.filter>=n.level&&A.handle(n);this.parent!==void 0&&this.parent.insert(n)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},cA=new R(3,void 0,[new As]),rs=R.prototype.log.bind(cA,1),js=R.prototype.log.bind(cA,2),ot=R.prototype.log.bind(cA,3),ts=R.prototype.log.bind(cA,4),Us=R.prototype.log.bind(cA);var at;function kt(n,...A){let t=es(A);at?at?.info(n,t):ot(n,t)}function es(...n){if(n.length===1&&typeof n[0]=="object"&&n[0]!==null)return{...n[0]};if(n.length>0)return{args:n}}function BA(n){return n.connectionId*4294967296+n.mediaId}function ut(n){return{mediaId:n%4294967296,connectionId:Math.floor(n/4294967296)}}function U(n,A,t){let e;switch(A){case"f32":e=n.HEAPF32;break;case"u32":e=n.HEAPU32;break;case"i32":e=n.HEAP32;break;case"u8":e=n.HEAPU8;break;default:throw new Error(\`allocating \${A} is not supported\`)}let i=n._malloc(t*e.BYTES_PER_ELEMENT);if(i===0||i%e.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${t} \${A} array\`);let d=i/e.BYTES_PER_ELEMENT;return e.subarray(d,d+t)}function eA(n,A){n._free(A.byteOffset)}function Gr(n,A,t,e){return{headers:U(n,"i32",t),samples:U(n,"f32",t*ur({sampleRate:A,stereo:e})),length:t,sampleRate:A,stereo:e}}function pr(n,A){eA(n,A.headers),eA(n,A.samples)}function ct(n,A){return{values:U(n,"f32",2+A*5),length:A}}function dt(n,A){eA(n,A.values)}function qt(n){return{values:U(n,"f32",4)}}function ft(n,A){eA(n,A.values)}function Ct(n){let A=n.length,t=0,e=0;for(;e<A;){let i=n.charCodeAt(e++);if((i&4294967168)===0){t++;continue}else if((i&4294965248)===0)t+=2;else{if(i>=55296&&i<=56319&&e<A){let d=n.charCodeAt(e);(d&64512)===56320&&(++e,i=((i&1023)<<10)+(d&1023)+65536)}(i&4294901760)===0?t+=3:t+=4}}return t}function ns(n,A,t){let e=n.length,i=t,d=0;for(;d<e;){let q=n.charCodeAt(d++);if((q&4294967168)===0){A[i++]=q;continue}else if((q&4294965248)===0)A[i++]=q>>6&31|192;else{if(q>=55296&&q<=56319&&d<e){let C=n.charCodeAt(d);(C&64512)===56320&&(++d,q=((q&1023)<<10)+(C&1023)+65536)}(q&4294901760)===0?(A[i++]=q>>12&15|224,A[i++]=q>>6&63|128):(A[i++]=q>>18&7|240,A[i++]=q>>12&63|128,A[i++]=q>>6&63|128)}A[i++]=q&63|128}}var ss=new TextEncoder,is=50;function ls(n,A,t){ss.encodeInto(n,A.subarray(t))}function Gt(n,A,t){n.length>is?ls(n,A,t):ns(n,A,t)}var os=4096;function hr(n,A,t){let e=A,i=e+t,d=[],q="";for(;e<i;){let C=n[e++];if((C&128)===0)d.push(C);else if((C&224)===192){let v=n[e++]&63;d.push((C&31)<<6|v)}else if((C&240)===224){let v=n[e++]&63,B=n[e++]&63;d.push((C&31)<<12|v<<6|B)}else if((C&248)===240){let v=n[e++]&63,B=n[e++]&63,pA=n[e++]&63,P=(C&7)<<18|v<<12|B<<6|pA;P>65535&&(P-=65536,d.push(P>>>10&1023|55296),P=56320|P&1023),d.push(P)}else d.push(C);d.length>=os&&(q+=String.fromCharCode(...d),d.length=0)}return d.length>0&&(q+=String.fromCharCode(...d)),q}var as=new TextDecoder,ks=200;function us(n,A,t){let e=n.subarray(A,A+t);return as.decode(e)}function pt(n,A,t){return t>ks?us(n,A,t):hr(n,A,t)}var X=class{constructor(A,t){this.type=A,this.data=t}};var g=class n extends Error{constructor(A){super(A);let t=Object.create(n.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:n.name})}};function ht(n,A,t){let e=t/4294967296,i=t;n.setUint32(A,e),n.setUint32(A+4,i)}function NA(n,A,t){let e=Math.floor(t/4294967296),i=t;n.setUint32(A,e),n.setUint32(A+4,i)}function KA(n,A){let t=n.getInt32(A),e=n.getUint32(A+4);return t*4294967296+e}function mt(n,A){let t=n.getUint32(A),e=n.getUint32(A+4);return t*4294967296+e}var cs=-1,ds=4294967296-1,qs=17179869184-1;function fs({sec:n,nsec:A}){if(n>=0&&A>=0&&n<=qs)if(A===0&&n<=ds){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{let t=n/4294967296,e=n&4294967295,i=new Uint8Array(8),d=new DataView(i.buffer);return d.setUint32(0,A<<2|t&3),d.setUint32(4,e),i}else{let t=new Uint8Array(12),e=new DataView(t.buffer);return e.setUint32(0,A),NA(e,4,n),t}}function Cs(n){let A=n.getTime(),t=Math.floor(A/1e3),e=(A-t*1e3)*1e6,i=Math.floor(e/1e9);return{sec:t+i,nsec:e-i*1e9}}function Gs(n){if(n instanceof Date){let A=Cs(n);return fs(A)}else return null}function ps(n){let A=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:A.getUint32(0),nsec:0};case 8:{let t=A.getUint32(0),e=A.getUint32(4),i=(t&3)*4294967296+e,d=t>>>2;return{sec:i,nsec:d}}case 12:{let t=KA(A,4),e=A.getUint32(0);return{sec:t,nsec:e}}default:throw new g(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${n.length}\`)}}function hs(n){let A=ps(n);return new Date(A.sec*1e3+A.nsec/1e6)}var Et={type:cs,encode:Gs,decode:hs};var S=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Et)}register({type:A,encode:t,decode:e}){if(A>=0)this.encoders[A]=t,this.decoders[A]=e;else{let i=-1-A;this.builtInEncoders[i]=t,this.builtInDecoders[i]=e}}tryToEncode(A,t){for(let e=0;e<this.builtInEncoders.length;e++){let i=this.builtInEncoders[e];if(i!=null){let d=i(A,t);if(d!=null){let q=-1-e;return new X(q,d)}}}for(let e=0;e<this.encoders.length;e++){let i=this.encoders[e];if(i!=null){let d=i(A,t);if(d!=null){let q=e;return new X(q,d)}}}return A instanceof X?A:null}decode(A,t,e){let i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(A,t,e):new X(t,A)}};S.defaultCodec=new S;function ms(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function dA(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):ms(n)?new Uint8Array(n):Uint8Array.from(n)}var Es=100,Is=2048,JA=class n{constructor(A){this.entered=!1,this.extensionCodec=A?.extensionCodec??S.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??Es,this.initialBufferSize=A?.initialBufferSize??Is,this.sortKeys=A?.sortKeys??!1,this.forceFloat32=A?.forceFloat32??!1,this.ignoreUndefined=A?.ignoreUndefined??!1,this.forceIntegerToFloat=A?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(A){if(this.entered)return this.clone().encodeSharedRef(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(A){if(this.entered)return this.clone().encode(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(A,t){if(t>this.maxDepth)throw new Error(\`Too deep objects in depth \${t}\`);A==null?this.encodeNil():typeof A=="boolean"?this.encodeBoolean(A):typeof A=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(A):this.encodeNumber(A):typeof A=="string"?this.encodeString(A):this.useBigInt64&&typeof A=="bigint"?this.encodeBigInt64(A):this.encodeObject(A,t)}ensureBufferSizeToWrite(A){let t=this.pos+A;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(A){let t=new ArrayBuffer(A),e=new Uint8Array(t),i=new DataView(t);e.set(this.bytes),this.view=i,this.bytes=e}encodeNil(){this.writeU8(192)}encodeBoolean(A){A===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(A){!this.forceIntegerToFloat&&Number.isSafeInteger(A)?A>=0?A<128?this.writeU8(A):A<256?(this.writeU8(204),this.writeU8(A)):A<65536?(this.writeU8(205),this.writeU16(A)):A<4294967296?(this.writeU8(206),this.writeU32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(207),this.writeU64(A)):A>=-32?this.writeU8(224|A+32):A>=-128?(this.writeU8(208),this.writeI8(A)):A>=-32768?(this.writeU8(209),this.writeI16(A)):A>=-2147483648?(this.writeU8(210),this.writeI32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(211),this.writeI64(A)):this.encodeNumberAsFloat(A)}encodeNumberAsFloat(A){this.forceFloat32?(this.writeU8(202),this.writeF32(A)):(this.writeU8(203),this.writeF64(A))}encodeBigInt64(A){A>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(A)):(this.writeU8(211),this.writeBigInt64(A))}writeStringHeader(A){if(A<32)this.writeU8(160+A);else if(A<256)this.writeU8(217),this.writeU8(A);else if(A<65536)this.writeU8(218),this.writeU16(A);else if(A<4294967296)this.writeU8(219),this.writeU32(A);else throw new Error(\`Too long string: \${A} bytes in UTF-8\`)}encodeString(A){let e=Ct(A);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),Gt(A,this.bytes,this.pos),this.pos+=e}encodeObject(A,t){let e=this.extensionCodec.tryToEncode(A,this.context);if(e!=null)this.encodeExtension(e);else if(Array.isArray(A))this.encodeArray(A,t);else if(ArrayBuffer.isView(A))this.encodeBinary(A);else if(typeof A=="object")this.encodeMap(A,t);else throw new Error(\`Unrecognized object: \${Object.prototype.toString.apply(A)}\`)}encodeBinary(A){let t=A.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(\`Too large binary: \${t}\`);let e=dA(A);this.writeU8a(e)}encodeArray(A,t){let e=A.length;if(e<16)this.writeU8(144+e);else if(e<65536)this.writeU8(220),this.writeU16(e);else if(e<4294967296)this.writeU8(221),this.writeU32(e);else throw new Error(\`Too large array: \${e}\`);for(let i of A)this.doEncode(i,t+1)}countWithoutUndefined(A,t){let e=0;for(let i of t)A[i]!==void 0&&e++;return e}encodeMap(A,t){let e=Object.keys(A);this.sortKeys&&e.sort();let i=this.ignoreUndefined?this.countWithoutUndefined(A,e):e.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(\`Too large map object: \${i}\`);for(let d of e){let q=A[d];this.ignoreUndefined&&q===void 0||(this.encodeString(d),this.doEncode(q,t+1))}}encodeExtension(A){if(typeof A.data=="function"){let e=A.data(this.pos+6),i=e.length;if(i>=4294967296)throw new Error(\`Too large extension object: \${i}\`);this.writeU8(201),this.writeU32(i),this.writeI8(A.type),this.writeU8a(e);return}let t=A.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(\`Too large extension object: \${t}\`);this.writeI8(A.type),this.writeU8a(A.data)}writeU8(A){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,A),this.pos++}writeU8a(A){let t=A.length;this.ensureBufferSizeToWrite(t),this.bytes.set(A,this.pos),this.pos+=t}writeI8(A){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,A),this.pos++}writeU16(A){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,A),this.pos+=2}writeI16(A){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,A),this.pos+=2}writeU32(A){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,A),this.pos+=4}writeI32(A){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,A),this.pos+=4}writeF32(A){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,A),this.pos+=4}writeF64(A){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,A),this.pos+=8}writeU64(A){this.ensureBufferSizeToWrite(8),ht(this.view,this.pos,A),this.pos+=8}writeI64(A){this.ensureBufferSizeToWrite(8),NA(this.view,this.pos,A),this.pos+=8}writeBigUint64(A){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,A),this.pos+=8}writeBigInt64(A){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,A),this.pos+=8}};function mr(n,A){return new JA(A).encodeSharedRef(n)}function bA(n){return\`\${n<0?"-":""}0x\${Math.abs(n).toString(16).padStart(2,"0")}\`}var $s=16,Fs=16,OA=class{constructor(A=$s,t=Fs){this.hit=0,this.miss=0,this.maxKeyLength=A,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,t,e){let i=this.caches[e-1];A:for(let d of i){let q=d.bytes;for(let C=0;C<e;C++)if(q[C]!==A[t+C])continue A;return d.str}return null}store(A,t){let e=this.caches[A.length-1],i={bytes:A,str:t};e.length>=this.maxLengthPerKey?e[Math.random()*e.length|0]=i:e.push(i)}decode(A,t,e){let i=this.find(A,t,e);if(i!=null)return this.hit++,i;this.miss++;let d=hr(A,t,e),q=Uint8Array.prototype.slice.call(A,t,t+e);return this.store(q,d),d}};var Er="array",CA="map_key",$t="map_value",vs=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new g("The type of key must be string or number but "+typeof n)},Ir=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let t=this.getUninitializedStateFromPool();t.type=Er,t.position=0,t.size=A,t.array=new Array(A)}pushMapState(A){let t=this.getUninitializedStateFromPool();t.type=CA,t.readCount=0,t.size=A,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let A={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(A)}return this.stack[this.stackHeadPosition]}release(A){if(this.stack[this.stackHeadPosition]!==A)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(A.type===Er){let e=A;e.size=0,e.array=void 0,e.position=0,e.type=void 0}if(A.type===CA||A.type===$t){let e=A;e.size=0,e.map=void 0,e.readCount=0,e.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},fA=-1,$r=new DataView(new ArrayBuffer(0)),Ls=new Uint8Array($r.buffer);try{$r.getInt8(0)}catch(n){if(!(n instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var It=new RangeError("Insufficient data"),gs=new OA,wA=class n{constructor(A){this.totalPos=0,this.pos=0,this.view=$r,this.bytes=Ls,this.headByte=fA,this.stack=new Ir,this.entered=!1,this.extensionCodec=A?.extensionCodec??S.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.rawStrings=A?.rawStrings??!1,this.maxStrLength=A?.maxStrLength??4294967295,this.maxBinLength=A?.maxBinLength??4294967295,this.maxArrayLength=A?.maxArrayLength??4294967295,this.maxMapLength=A?.maxMapLength??4294967295,this.maxExtLength=A?.maxExtLength??4294967295,this.keyDecoder=A?.keyDecoder!==void 0?A.keyDecoder:gs,this.mapKeyConverter=A?.mapKeyConverter??vs}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=fA,this.stack.reset()}setBuffer(A){let t=dA(A);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(A){if(this.headByte===fA&&!this.hasRemaining(1))this.setBuffer(A);else{let t=this.bytes.subarray(this.pos),e=dA(A),i=new Uint8Array(t.length+e.length);i.set(t),i.set(e,t.length),this.setBuffer(i)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:t,pos:e}=this;return new RangeError(\`Extra \${t.byteLength-e} of \${t.byteLength} byte(s) found at buffer[\${A}]\`)}decode(A){if(this.entered)return this.clone().decode(A);try{this.entered=!0,this.reinitializeState(),this.setBuffer(A);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(A){if(this.entered){yield*this.clone().decodeMulti(A);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(A);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(A){if(this.entered)return this.clone().decodeAsync(A);try{this.entered=!0;let t=!1,e;for await(let C of A){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(C);try{e=this.doDecodeSync(),t=!0}catch(v){if(!(v instanceof RangeError))throw v}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return e}let{headByte:i,pos:d,totalPos:q}=this;throw new RangeError(\`Insufficient data in parsing \${bA(i)} at \${q} (\${d} in the current buffer)\`)}finally{this.entered=!1}}decodeArrayStream(A){return this.decodeMultiAsync(A,!0)}decodeStream(A){return this.decodeMultiAsync(A,!1)}async*decodeMultiAsync(A,t){if(this.entered){yield*this.clone().decodeMultiAsync(A,t);return}try{this.entered=!0;let e=t,i=-1;for await(let d of A){if(t&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(d),e&&(i=this.readArraySize(),e=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(q){if(!(q instanceof RangeError))throw q}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){A:for(;;){let A=this.readHeadByte(),t;if(A>=224)t=A-256;else if(A<192)if(A<128)t=A;else if(A<144){let i=A-128;if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A<160){let i=A-144;if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else{let i=A-160;t=this.decodeString(i,0)}else if(A===192)t=null;else if(A===194)t=!1;else if(A===195)t=!0;else if(A===202)t=this.readF32();else if(A===203)t=this.readF64();else if(A===204)t=this.readU8();else if(A===205)t=this.readU16();else if(A===206)t=this.readU32();else if(A===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(A===208)t=this.readI8();else if(A===209)t=this.readI16();else if(A===210)t=this.readI32();else if(A===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(A===217){let i=this.lookU8();t=this.decodeString(i,1)}else if(A===218){let i=this.lookU16();t=this.decodeString(i,2)}else if(A===219){let i=this.lookU32();t=this.decodeString(i,4)}else if(A===220){let i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===221){let i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===222){let i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===223){let i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===196){let i=this.lookU8();t=this.decodeBinary(i,1)}else if(A===197){let i=this.lookU16();t=this.decodeBinary(i,2)}else if(A===198){let i=this.lookU32();t=this.decodeBinary(i,4)}else if(A===212)t=this.decodeExtension(1,0);else if(A===213)t=this.decodeExtension(2,0);else if(A===214)t=this.decodeExtension(4,0);else if(A===215)t=this.decodeExtension(8,0);else if(A===216)t=this.decodeExtension(16,0);else if(A===199){let i=this.lookU8();t=this.decodeExtension(i,1)}else if(A===200){let i=this.lookU16();t=this.decodeExtension(i,2)}else if(A===201){let i=this.lookU32();t=this.decodeExtension(i,4)}else throw new g(\`Unrecognized type byte: \${bA(A)}\`);this.complete();let e=this.stack;for(;e.length>0;){let i=e.top();if(i.type===Er)if(i.array[i.position]=t,i.position++,i.position===i.size)t=i.array,e.release(i);else continue A;else if(i.type===CA){if(t==="__proto__")throw new g("The key __proto__ is not allowed");i.key=this.mapKeyConverter(t),i.type=$t;continue A}else if(i.map[i.key]=t,i.readCount++,i.readCount===i.size)t=i.map,e.release(i);else{i.key=null,i.type=CA;continue A}}return t}}readHeadByte(){return this.headByte===fA&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=fA}readArraySize(){let A=this.readHeadByte();switch(A){case 220:return this.readU16();case 221:return this.readU32();default:{if(A<160)return A-144;throw new g(\`Unrecognized array type byte: \${bA(A)}\`)}}}pushMapState(A){if(A>this.maxMapLength)throw new g(\`Max length exceeded: map length (\${A}) > maxMapLengthLength (\${this.maxMapLength})\`);this.stack.pushMapState(A)}pushArrayState(A){if(A>this.maxArrayLength)throw new g(\`Max length exceeded: array length (\${A}) > maxArrayLength (\${this.maxArrayLength})\`);this.stack.pushArrayState(A)}decodeString(A,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(A,t):this.decodeBinary(A,t)}decodeUtf8String(A,t){if(A>this.maxStrLength)throw new g(\`Max length exceeded: UTF-8 byte length (\${A}) > maxStrLength (\${this.maxStrLength})\`);if(this.bytes.byteLength<this.pos+t+A)throw It;let e=this.pos+t,i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?i=this.keyDecoder.decode(this.bytes,e,A):i=pt(this.bytes,e,A),this.pos+=t+A,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===CA:!1}decodeBinary(A,t){if(A>this.maxBinLength)throw new g(\`Max length exceeded: bin length (\${A}) > maxBinLength (\${this.maxBinLength})\`);if(!this.hasRemaining(A+t))throw It;let e=this.pos+t,i=this.bytes.subarray(e,e+A);return this.pos+=t+A,i}decodeExtension(A,t){if(A>this.maxExtLength)throw new g(\`Max length exceeded: ext length (\${A}) > maxExtLength (\${this.maxExtLength})\`);let e=this.view.getInt8(this.pos+t),i=this.decodeBinary(A,t+1);return this.extensionCodec.decode(i,e,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let A=this.view.getUint8(this.pos);return this.pos++,A}readI8(){let A=this.view.getInt8(this.pos);return this.pos++,A}readU16(){let A=this.view.getUint16(this.pos);return this.pos+=2,A}readI16(){let A=this.view.getInt16(this.pos);return this.pos+=2,A}readU32(){let A=this.view.getUint32(this.pos);return this.pos+=4,A}readI32(){let A=this.view.getInt32(this.pos);return this.pos+=4,A}readU64(){let A=mt(this.view,this.pos);return this.pos+=8,A}readI64(){let A=KA(this.view,this.pos);return this.pos+=8,A}readU64AsBigInt(){let A=this.view.getBigUint64(this.pos);return this.pos+=8,A}readI64AsBigInt(){let A=this.view.getBigInt64(this.pos);return this.pos+=8,A}readF32(){let A=this.view.getFloat32(this.pos);return this.pos+=4,A}readF64(){let A=this.view.getFloat64(this.pos);return this.pos+=8,A}};function Fr(n,A){return new wA(A).decode(n)}var GA=class n{constructor(A,t,e,i,d){this.mediaIds=A;this.sequenceNumber=t;this.timeStamp=e;this.isEndOfSpurt=i;this.payload=d}static parse(A){let t;try{t=Fr(A)}catch{return D("not valid msgpack")}if(!Array.isArray(t))return D("container must be an array");if(t.length<6)return D("missing fields");if(t[0]!==1)return D("unknown type");if(!Array.isArray(t[1]))return D("media ids must be an array");if(!t[1].every(B=>typeof B=="number"))return D("media ids must be numbers");if(typeof t[2]!="number")return D("sequence number must be a number");if(typeof t[3]!="number")return D("timestamp must be a number");if(typeof t[4]!="number")return D("flags must be a number");let e=t[1],i=t[2]>>>0,d=t[3]>>>0,C=(t[4]&1)!==0,v=t[t.length-1];return v instanceof Uint8Array?st(new n(e,i,d,C,v)):D("payload must be bytes")}toBytes(){let A=Number(this.isEndOfSpurt),t=[1,this.mediaIds,this.sequenceNumber>>>0,this.timeStamp>>>0,A,this.payload];return new Uint8Array(mr(t,{forceFloat32:!0,ignoreUndefined:!0}))}};var PA=class{constructor(A,t){this.sampleRate=A;this.wasm=t;this.sequenceNumber=Math.random()*Math.pow(2,32)>>0;this.timestamp=Math.random()*Math.pow(2,32)>>0;this.connections=[];this.monitoring=!1;this.active=!1;this.stats={numberPackets:0,numberTicks:0,numberPacketError:0,numberPacketsMediaNotFound:0};this.encoder=new t.Encoder(A,15,!0,J.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=qt(this.wasm),this.outBuffer=U(this.wasm,"u8",1270),At(this.information,1)}setVad(A){this.encoder.set_volume_gate(A.volumeGate!==void 0,A.volumeGate?.attackThreshold??0,A.volumeGate?.releaseThreshold??0),this.encoder.set_speech_detection(A.voiceActivity!==void 0,A.voiceActivity?.attackThreshold??0,A.voiceActivity?.releaseThreshold??0)}setMedias(A){this.connections=A.filter(({mediaIds:t})=>t.length>0)}close(){ft(this.wasm,this.information),eA(this.wasm,this.outBuffer),this.encoder.delete()}encode(A){for(this.encoder.push(A.byteOffset,this.information.values.byteOffset);;){let t=this.encoder.pop(this.connections.length===0?0:this.outBuffer.byteOffset,this.outBuffer.length);if(t===0)break;if(t<0){kt(\`failed encoding packet: \${t}\`);return}if(this.timestamp=this.timestamp+1800>>0,t===1)continue;this.sequenceNumber=this.sequenceNumber+1>>0;let e=this.active&&!this.encoder.active;this.active=this.encoder.active,this.monitoring=this.connections.some(i=>i.id===0);for(let i of this.connections){if(this.monitoring&&i.id!==0)continue;let d=new GA(i.mediaIds,this.sequenceNumber,this.timestamp,e,this.outBuffer.subarray(0,t));uA(globalThis,["sendPacket",{connectionId:i.id,packet:d.toBytes()}])}}}onMessage(A){let[t,e]=A;switch(t){case"captureSetVad":this?.setVad(e);break;case"captureSetMedias":this?.setMedias(e.connections);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){return{sequenceNumber:this.sequenceNumber,timestamp:this.timestamp,connections:this.connections.map(A=>\`\${A.id} => \${A.mediaIds.join(",")}\`),active:this.active,monitoring:this.monitoring,information:{active:zj(this.information),speechProbability:Qj(this.information),rmsDBFS:Yj(this.information),volume:Zj(this.information)},encoder:{sample_rate:this.encoder.sample_rate,fec_packet_loss:this.encoder.fec_packet_loss,voip:this.encoder.voip,vad_preload:this.encoder.vad_preload,complexity:this.encoder.complexity,speech_probability:this.encoder.speech_probability,rms_dbfs:this.encoder.rms_dbfs,active:this.encoder.active,speech_detection_enabled:this.encoder.speech_detection_enabled,speech_detection_going_active:this.encoder.speech_detection_going_active,speech_detection_going_inactive:this.encoder.speech_detection_going_inactive,volume_gate_enabled:this.encoder.volume_gate_enabled,volume_gate_going_active:this.encoder.volume_gate_going_active,volume_gate_going_inactive:this.encoder.volume_gate_going_inactive}}}},MA=class{constructor(A){this.wasm=A;this.medias=new Map;this.stats={numberPackets:0,numberTicks:0,numberPacketError:0,numberPacketsMediaNotFound:0,numberTicksWithAudio:0};this.largestIndex=-1;this.decoders=U(this.wasm,"u32",J.MaxNumberOfDecoders),this.information=ct(this.wasm,J.MaxNumberOfDecoders),Pj(this.information,[1,1])}close(){dt(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,t){this.stats.numberPackets++;let e=GA.parse(t);if(e.type==="Failure"){this.stats.numberPacketError++;let i=Array.from(t).map(d=>d.toString(16).padStart(2,"0")).join("");console.error(\`failed decoding audio packet; reason: \${e.reason}, connection: \${A}, dump: \${i}\`);return}for(let i of e.value.mediaIds){let d=this.medias.get(BA({connectionId:A,mediaId:i}));if(d===void 0){this.stats.numberPacketsMediaNotFound++;continue}d.lastPacket=t;let q=U(this.wasm,"u8",e.value.payload.length);q.set(e.value.payload),d.decoder.push(e.value.sequenceNumber,e.value.timeStamp,e.value.isEndOfSpurt,q.byteOffset,q.length)}}insertMedia(A,t,e,i=[1,1]){let d=BA({connectionId:t,mediaId:e}),q=new this.wasm.Decoder;this.medias.set(d,{index:A,decoder:q,lastPacket:void 0}),this.decoders[A]=q.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),Sj(this.information,A,i),Xj(this.information,A,0),Wj(this.information,A,0)}removeMedia(A,t,e){let i=BA({connectionId:t,mediaId:e}),d=this.medias.get(i);if(!(d===void 0||d.index!==A)&&(this.medias.delete(i),Tj(this.information,A,0),this.decoders[A]=0,d.decoder.delete(),A===this.largestIndex)){for(A=A-1;A>=0&&this.decoders[A]===0;A--);this.largestIndex=A}}decode(A){return{hasAudio:this.wasm.pop_many(this.decoders.byteOffset,this.information.values.byteOffset,this.largestIndex+1,A.byteOffset)}}onMessage(A){let[t,e]=A;switch(t){case"playbackReceivePacket":this.receivePacket(e.connectionId,e.packet);break;case"playbackUpdateMedias":for(let{index:i,connectionId:d,mediaId:q}of e.removed)this.removeMedia(i,d,q);for(let{index:i,connectionId:d,mediaId:q,volume:C}of e.added)this.insertMedia(i,d,q,C);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){let A=[];for(let[t,e]of this.medias){let i=ut(t);A.push({index:e.index,connectionId:i.connectionId,mediaId:i.mediaId,rmsDBFS:Mj(this.information,e.index),volume:Uj(this.information,e.index),voicedBlocks:Rj(this.information,e.index),silentBlocks:Vj(this.information,e.index),time:e.decoder.time,consecutive_silence:e.decoder.consecutive_silence,last_voiced_time_point:e.decoder.last_voiced_time_point,sequence_number:e.decoder.sequence_number,packetsSeen:e.decoder.packets_seen,packetsInvalid:e.decoder.packets_invalid,packetsTooLate:e.decoder.packets_too_late,packetsTooEarly:e.decoder.packets_too_early,packetsRepeated:e.decoder.packets_repeated,packetsProcessed:e.decoder.packets_processed,packetsLost:e.decoder.packets_lost,rewinds:e.decoder.rewinds,cacheLength:e.decoder.cache_length,lastPacket:rt(e.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:wj(this.information),decoders:A}}};var Ht=Ln(vt()),Lt=(0,Ht.default)(),gt,_t;globalThis.addEventListener("message",vr);async function vr(n){let A=n.data,[t,e]=A;switch(t){case"captureInit":e.workletPort.onmessage=vr,gt=new Lr(e.sampleRate,await Lt);break;case"playbackInit":e.workletPort.onmessage=vr,_t=new gr(await Lt);break;case"close":globalThis.close();break}gt?.onMessage(A),_t?.onMessage(A)}var Lr=class extends PA{constructor(t,e){super(t,e);this.id=-1;this.samples=Gr(this.wasm,t,2+J.VadPreload+J.AdditionalCaptureBlocks,!1),uA(globalThis,["captureReady",{sampleBuffer:this.samples,informationBuffer:this.information}])}close(){super.close(),pr(this.wasm,this.samples)}onMessage(t){super.onMessage(t);let[e,i]=t;e==="captureTick"&&this.tick(i.id)}tick(t){for(;this.id<t;this.id+=1)this.encode(cr(this.samples,this.id%this.samples.length))}dump(){return{type:"shared capture worker",id:this.id,sampleRate:this.samples.sampleRate,stereo:this.samples.stereo,length:this.samples.length,...super.dump()}}},gr=class extends MA{constructor(A){super(A);let t=2+J.AdditionalPlaybackBlocks;this.sampleBuffer=Gr(A,48e3,t,!0),this.sampleBuffer.samples.fill(0),this.prefill=t-2;for(let e=0;e<this.prefill;e++)dr(this.sampleBuffer,e,{id:e});this.id=this.prefill,uA(globalThis,["playbackReady",{sampleBuffer:this.sampleBuffer,informationBuffer:this.information}])}close(){super.close(),pr(this.wasm,this.sampleBuffer)}onMessage(A){super.onMessage(A);let[t,e]=A;t==="playbackTick"&&this.tick(e.id)}tick(A){for(this.stats.numberTicks++;this.id<A+this.prefill;this.id++){let t=this.id%this.sampleBuffer.length,{hasAudio:e}=this.decode(cr(this.sampleBuffer,t));e&&(this.stats.numberTicksWithAudio++,dr(this.sampleBuffer,t,{id:this.id}))}}dump(){return{type:"shared playback worker",id:this.id,prefill:this.prefill,sampleRate:this.sampleBuffer.sampleRate,stereo:this.sampleBuffer.stereo,...super.dump()}}};})();
3223
- `});var Vx,G0=p(()=>{Vx='"use strict";(()=>{var R=Object.defineProperty;var F=(e,t)=>{for(var r in t)R(e,r,{get:t[r],enumerable:!0})};var l={};F(l,{AdditionalCaptureBlocks:()=>C,AdditionalPlaybackBlocks:()=>D,ClockJumpCheckInterval:()=>$,ClockJumpThreshold:()=>j,ConnectInterval:()=>Q,ConnectTimeout:()=>G,DefaultRefreshRate:()=>V,HealthCheckTimeout:()=>W,MainConnectionPingInterval:()=>H,MaxNumberOfDecoders:()=>_,MinDBFs:()=>k,MinTokenLifetime:()=>Z,MinTokenRefreshInterval:()=>q,PlaybackPreload:()=>L,RenderQuantumSize:()=>N,VadPreload:()=>O,WebRtcIceTimeout:()=>J,WebRtcTimeout:()=>z});var D=3,C=3,L=3,V=250,O=3,_=512,N=128,k=-758.596,W=1e4,$=1e3,j=1e4,H=3e3,J=3e3,z=1e4,G=5e3,Z=6e4,q=5e3,Q=[0,100,200,200,500];function p(e,t,r){return e.postMessage(t,r)}function K(e){return e.sampleRate*.02*(e.stereo?2:1)}function f(e,t){let r=K(e),n=r*t,s=n+r;return e.samples.subarray(n,s)}function S(e,t){return{id:e.headers[t]}}function U(e,t,r){e.headers[t]=r.id}var X;(e=>{let t;(r=>(r[r.InvalidPassword=-1]="InvalidPassword",r[r.Unknown=0]="Unknown",r[r.Unencrypted=1]="Unencrypted",r[r.Encrypted=2]="Encrypted"))(t=e.PeerCipherStatus||={})})(X||={});var{Deno:I}=globalThis,Y=typeof I?.noColor=="boolean"?I.noColor:!1,ee=!Y;function h(e,t){return{open:`\\x1B[${e.join(";")}m`,close:`\\x1B[${t}m`,regexp:new RegExp(`\\\\x1b\\\\[${t}m`,"g")}}function b(e,t){return ee?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}function m(e){return b(e,h([0],0))}function T(e){return b(e,h([1],22))}function te(e){return b(e,h([2],22))}var Ue=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),re=new Date,d=(e=>(e[e.CRITICAL=0]="CRITICAL",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(d||{}),P={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},ne={4:te,3:m,2:m,1:T,0:T};function se({message:e}){return String(e)}function B(e){return JSON.stringify({timestamp:e.date.toISOString(),level:d[e.level],message:e.message,extra:e.extra})}function w(e){function t(c,i){return[Math.floor(c/i),c%i]}function r(){let c,i=e.date.valueOf()-re.valueOf();[i,c]=t(i,1e3);let[M,E]=t(i,60);return`${M.toString().padStart(4,"0")}:${E.toString().padStart(2,"0")}.${c.toString().padStart(4,"0")}`}function n(){return e.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(e.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(e.extra)}let s=P[e.level],a=e.logger.name!==void 0?`@${e.logger}`:"";return`${m(r())}${a} ${s} ${ne[e.level](String(e.message))}${n()}`}function oe(e){let t=`[${e.date.toISOString()}]`,r=`[${d[e.level]}]`,n=e.logger.name!==void 0?`[${e.logger.name}] `:"",s=P[e.level];return`${t} ${s} ${r.padEnd(7," ")} ${n}${e.message}`}function ae(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var A={sparse:se,json:B,pretty:w,structured:oe,default:ae()?w:B},ie=class{formatter;consoleObject;filter;constructor(e=A.default,t=4,r=console){this.filter=t,this.formatter=e,this.consoleObject=r}handle(e){let t=this.formatter(e);switch(e.level){case 1:this.consoleObject.error(t);break;case 2:this.consoleObject.warn(t);break;case 3:this.consoleObject.info(t);break;case 4:this.consoleObject.debug(t);break}}};var o=class{#e;sinks;filter;parent;get name(){return this.#e}constructor(e,t=void 0,r=[],n=void 0){this.#e=t,this.sinks=r,this.filter=e,this.parent=n}log(e,t,r=void 0){let n={date:new Date,level:e,logger:this,message:t,extra:r};this.filter<e||this.insert(n)}insert(e){if(!(this.filter<e.level)){for(let t of this.sinks)t.filter>=e.level&&t.handle(e);this.parent!==void 0&&this.parent.insert(e)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},u=new o(3,void 0,[new ie]),ce=o.prototype.log.bind(u,1),le=o.prototype.log.bind(u,2),ue=o.prototype.log.bind(u,3),fe=o.prototype.log.bind(u,4),Ie=o.prototype.log.bind(u);var x=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.blocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"init":this.state=new g(s.sampleBuffer,s.workerPort,sampleRate*.02);break;case"close":this.alive=!1;break;case"dump":s.result.postMessage(this.dump());break}}process(r,n,s){if(this.state===void 0||r.length<1||r[0].length<1)return this.alive;let a=this.state.fill(0,r[0][0]);return this.state.offset===this.state.length&&(this.blocks+=1,this.state.flush(),this.state.fill(a,r[0][0])),this.alive}dump(){return{type:"shared capture worklet",alive:this.alive,sampleRate,id:this.state?.id||null,offset:this.state?.offset||null,length:this.state?.length||null,blocks:this.blocks}}},y=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.silenceBlocks=0;this.voiceBlocks=0;this.totalBlocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"close":this.alive=!1;break;case"init":this.state=new v(s.workerPort,s.sampleBuffer,sampleRate*.02);break;case"dump":s.result.postMessage(this.dump());break}n==="close"&&(this.alive=!1)}process(r,n,s){if(this.state===void 0||n.length<1||n[0].length<2)return this.alive;let a=this.state.fill(0,n[0][0],n[0][1]);return a<l.RenderQuantumSize&&(this.totalBlocks+=1,this.state.next(),this.state.hasVoice?this.voiceBlocks+=1:this.silenceBlocks+=1,this.state.fill(a,n[0][0],n[0][1])),this.alive}dump(){return{type:"shared playback worklet",alive:this.alive,sampleRate,id:this.state?.id||null,offset:this.state?.offset||null,length:this.state?.length||null,hasVoice:this.state?.hasVoice??!1,silenceBlocks:this.silenceBlocks,voiceBlocks:this.voiceBlocks,totalBlocks:this.totalBlocks}}},g=class{constructor(t,r,n){this.samples=t;this.port=r;this.length=n;this.id=0,this.offset=0,this.entry=f(this.samples,0)}fill(t,r){let n=Math.min(r.length-t,this.length-this.offset);return this.entry.set(r.subarray(t,t+n),this.offset),this.offset+=n,t+n}flush(){this.id+=1,p(this.port,["captureTick",{id:this.id}]);let t=this.id%this.samples.length;this.entry=f(this.samples,t),U(this.samples,t,{id:this.id}),this.offset=0}},v=class{constructor(t,r,n){this.port=t;this.samples=r;this.length=n;this.id=-1,this.offset=0,this.entry=void 0,this.next()}get hasVoice(){return this.entry!==void 0}fill(t,r,n){let s=Math.min(l.RenderQuantumSize-t,this.length-this.offset);return this.entry!==void 0&&(r.set(this.entry.subarray(this.offset,this.offset+s),t),n.set(this.entry.subarray(this.offset+this.length,this.offset+this.length+s),t)),this.offset+=s,t+s}next(){this.id+=1;let t=this.id%this.samples.length,{id:r}=S(this.samples,t);this.entry=this.id===r?f(this.samples,t):void 0,this.offset=0,p(this.port,["playbackTick",{id:this.id}])}};registerProcessor("OdinCaptureProcessor",x);registerProcessor("OdinPlaybackProcessor",y);})();\n'});var I0={};Px(I0,{createCaptureWorker:()=>YA,createPlaybackWorker:()=>ZA});import{Strand as XA}from"@4players/odin-common";function YA(C,j,e,B,v=b.DefaultRefreshRate){return QA.enqueue(async()=>{let[E,f]=await Y(Rx,Vx,C,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return Wx.create(C,j,e,E,f,B)})}async function ZA(C,j=b.DefaultRefreshRate){if(C.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[e,B]=await Y(Rx,Vx,C,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return Ux.create(C,e,B)}var QA,Ux,Wx,$0=p(()=>{"use strict";k();Cx();m0();G0();QA=new XA;Ux=class C extends z{constructor(e,B,v,E){super(e,B,v);this.information=E}static async create(e,B,v){let{port1:E,port2:f}=new MessageChannel;c(B,["playbackInit",{workletPort:E}],[E]);let{informationBuffer:n,sampleBuffer:i}=await W(B,"playbackReady");return Tx(n,[1,1]),c(v.port,["init",{sampleBuffer:i,workerPort:f}],[f]),v.connect(e.destination),new C(e,v,B,n)}getActivity(e){let B=this.medias.get(h(e));if(B===void 0)return;let v=v0(this.information,B.index);return v===0?_:{isSilent:!1,rmsDBFS:v}}getJitterStats(e){}setGlobalVolume(e){Tx(this.information,e)}setVolume(e,B){let v=this.medias.get(h(e));v!==void 0&&C0(this.information,v.index,B)}_GetFreeIndex(){let e=super._GetFreeIndex();if(e!==void 0)return e;if(this.information.length>this.medias.size)return this.medias.size}},Wx=class C extends X{constructor(e,B,v,E,f,n){super(e,B,v,E,n);this.information=f}static async create(e,B,v,E,f,n){let{port1:i,port2:u}=new MessageChannel;c(E,["captureInit",{sampleRate:e.sampleRate,workletPort:i}],[i]);let{sampleBuffer:y,informationBuffer:U}=await W(E,"captureReady");return c(f.port,["init",{workerPort:u,sampleBuffer:y}],[u]),new C(f,E,B,v,U,n)}get activity(){return{isSilent:!E0(this.information),rmsDBFS:n0(this.information)}}get speechProbability(){return f0(this.information)}setVolume(e){s0(this.information,e)}}});var zx,g0=p(()=>{zx=`"use strict";(()=>{var ke=Object.create;var XA=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var ce=Object.getOwnPropertyNames;var de=Object.getPrototypeOf,qe=Object.prototype.hasOwnProperty;var Ce=(n,A)=>()=>(A||n((A={exports:{}}).exports,A),A.exports),fe=(n,A)=>{for(var t in A)XA(n,t,{get:A[t],enumerable:!0})},Ge=(n,A,t,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of ce(A))!qe.call(n,i)&&i!==t&&XA(n,i,{get:()=>A[i],enumerable:!(e=ue(A,i))||e.enumerable});return n};var pe=(n,A,t)=>(t=n!=null?ke(de(n)):{},Ge(A||!n||!n.__esModule?XA(t,"default",{value:n,enumerable:!0}):t,n));var _j=Ce((yj,OA)=>{"use strict";var sr=(()=>{var n=globalThis.document?.currentScript?.src;return async function(A={}){var t,e=A,i=!!globalThis.window,d=!!globalThis.WorkerGlobalScope,q=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",p=[],F="./this.program";d&&(n=self.location.href);var x="",wA,O;if(i||d){try{x=new URL(".",n).href}catch{}d&&(O=j=>{var r=new XMLHttpRequest;return r.open("GET",j,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),wA=async j=>{var r=await fetch(j,{credentials:"same-origin"});if(r.ok)return r.arrayBuffer();throw new Error(r.status+" : "+r.url)}}var ar=console.log.bind(console),kA=console.error.bind(console),kr,ur=!1;function Bj(j){for(var r=0,s=j.length,l=new Uint8Array(s),o;r<s;++r)o=j.charCodeAt(r),l[r]=~o>>8&o;return l}var cr,dr,V,_,uA,Z,cA,I,qr,Cr,fr,Gr,pr=!1;function Jj(){var j=Sr.buffer;V=new Int8Array(j),uA=new Int16Array(j),e.HEAPU8=_=new Uint8Array(j),Z=new Uint16Array(j),e.HEAP32=cA=new Int32Array(j),e.HEAPU32=I=new Uint32Array(j),e.HEAPF32=qr=new Float32Array(j),Cr=new Float64Array(j),fr=new BigInt64Array(j),Gr=new BigUint64Array(j)}function bj(){if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)Rj(e.preRun.shift());mr(Er)}function Oj(){pr=!0,tA.v()}function wj(){if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)Wj(e.postRun.shift());mr(Ir)}function PA(j){e.onAbort?.(j),j="Aborted("+j+")",kA(j),ur=!0,j+=". Build with -sASSERTIONS for more info.";var r=new WebAssembly.RuntimeError(j);throw dr?.(r),r}var hr;function Pj(){return Bj(\`\\0asm\\0\\0\\0\\x8D9\\\`\\x7F\\x7F\\\`\\x7F\\0\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\0\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`||\\\`\\x7F}\\\`}}\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F~\\\`\\x7F\\x7F}\\\`\\x7F}}\\\`\\x7F\\x7F}}\\0\\\`
3222
+ \`,new Function(m,f)}function tr(r,j,s,l,o,k){var a=j.length;a<2&&p("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var u=j[1]!==null&&s!==null,c=oj(j),f=!j[0].isVoid,G=j[0],m=j[1],$=[r,p,l,o,lj,G.fromWireType.bind(G),m?.toWireType.bind(m)],E=2;E<a;++E){var F=j[E];$.push(F.toWireType.bind(F))}if(!c)for(var E=u?1:2;E<j.length;++E)j[E].destructorFunction!==null&&$.push(j[E].destructorFunction);var w=Ie(j,u,f,k)(...$);return jj(r,w)}var $e=(r,j,s,l,o,k)=>{var a=jr(j,s);o=b(l,o),M([],[r],u=>{u=u[0];var c=\`constructor \${u.name}\`;if(u.registeredClass.constructor_body===void 0&&(u.registeredClass.constructor_body=[]),u.registeredClass.constructor_body[j-1]!==void 0)throw new lA(\`Cannot register multiple constructors with identical number of parameters (\${j-1}) for class '\${u.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!\`);return u.registeredClass.constructor_body[j-1]=()=>{rA(\`Cannot construct \${u.name} due to unbound types\`,a)},M([],a,f=>(f.splice(1,0,null),u.registeredClass.constructor_body[j-1]=tr(c,f,null,o,k),[])),[]})},aj=r=>{r=r.trim();let j=r.indexOf("(");return j===-1?r:r.slice(0,j)},Fe=(r,j,s,l,o,k,a,u,c,f)=>{var G=jr(s,l);j=L(j),j=aj(j),k=b(o,k,c),M([],[r],m=>{m=m[0];var $=\`\${m.name}.\${j}\`;j.startsWith("@@")&&(j=Symbol[j.substring(2)]),u&&m.registeredClass.pureVirtualFunctions.push(j);function E(){rA(\`Cannot call \${$} due to unbound types\`,G)}var F=m.registeredClass.instancePrototype,H=F[j];return H===void 0||H.overloadTable===void 0&&H.className!==m.name&&H.argCount===s-2?(E.argCount=s-2,E.className=m.name,F[j]=E):(ej(F,j,$),F[j].overloadTable[s-2]=E),M([],G,w=>{var y=tr($,w,m,k,a,c);return F[j].overloadTable===void 0?(y.argCount=s-2,F[j]=y):F[j].overloadTable[s-2]=y,[]}),[]})},kj=(r,j,s)=>(r instanceof Object||p(\`\${s} with invalid "this": \${r}\`),r instanceof j.registeredClass.constructor||p(\`\${s} incompatible with "this" of type \${r.constructor.name}\`),r.$$.ptr||p(\`cannot call emscripten binding method \${s} on deleted object\`),vA(r.$$.ptr,r.$$.ptrType.registeredClass,j.registeredClass)),ve=(r,j,s,l,o,k,a,u,c,f)=>{j=L(j),o=b(l,o),M([],[r],G=>{G=G[0];var m=\`\${G.name}.\${j}\`,$={get(){rA(\`Cannot access \${m} due to unbound types\`,[s,a])},enumerable:!0,configurable:!0};return c?$.set=()=>rA(\`Cannot access \${m} due to unbound types\`,[s,a]):$.set=E=>p(m+" is a read-only property"),Object.defineProperty(G.registeredClass.instancePrototype,j,$),M([],c?[s,a]:[s],E=>{var F=E[0],H={get(){var y=kj(this,G,m+" getter");return F.fromWireType(o(k,y))},enumerable:!0};if(c){c=b(u,c);var w=E[1];H.set=function(y){var kA=kj(this,G,m+" setter"),_=[];c(f,kA,w.toWireType(_,y)),lj(_)}}return Object.defineProperty(G.registeredClass.instancePrototype,j,H),[]}),[]})},uj=[],jA=[0,1,,1,null,1,!0,1,!1,1],Le=r=>{r>9&&--jA[r+1]===0&&(jA[r]=void 0,uj.push(r))},er={toValue:r=>(r||p(\`Cannot use deleted val. handle = \${r}\`),jA[r]),toHandle:r=>{switch(r){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:{let j=uj.pop()||jA.length;return jA[j]=r,jA[j+1]=1,j}}}},ge={name:"emscripten::val",fromWireType:r=>{var j=er.toValue(r);return Le(r),j},toWireType:(r,j)=>er.toHandle(j),readValueFromPointer:LA,destructorFunction:null},_e=r=>K(r,ge),He=(r,j)=>{switch(j){case 4:return function(s){return this.fromWireType(xr[s>>2])};case 8:return function(s){return this.fromWireType(EA[s>>3])};default:throw new TypeError(\`invalid float width (\${j}): \${r}\`)}},ye=(r,j,s)=>{j=L(j),K(r,{name:j,fromWireType:l=>l,toWireType:(l,o)=>o,readValueFromPointer:He(j,s),destructorFunction:null})},xe=(r,j,s,l,o,k,a,u)=>{var c=jr(j,s);r=L(r),r=aj(r),o=b(l,o,a),nj(r,function(){rA(\`Cannot call \${r} due to unbound types\`,c)},j-1),M([],c,f=>{var G=[f[0],null].concat(f.slice(1));return ij(r,tr(r,G,null,o,k,a),j-1),[]})},De=(r,j,s,l,o)=>{j=L(j);let k=l===0,a=c=>c;if(k){var u=32-8*s;a=c=>c<<u>>>u,o=a(o)}K(r,{name:j,fromWireType:a,toWireType:(c,f)=>f,readValueFromPointer:Yr(j,s,l!==0),destructorFunction:null})},Be=(r,j,s)=>{var l=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=l[j];function k(a){var u=I[a>>2],c=I[a+4>>2];return new o(V.buffer,c,u)}s=L(s),K(r,{name:s,fromWireType:k,readValueFromPointer:k},{ignoreDuplicateRegistrations:!0})},Ne=(r,j,s,l)=>{if(!(l>0))return 0;for(var o=s,k=s+l-1,a=0;a<r.length;++a){var u=r.codePointAt(a);if(u<=127){if(s>=k)break;j[s++]=u}else if(u<=2047){if(s+1>=k)break;j[s++]=192|u>>6,j[s++]=128|u&63}else if(u<=65535){if(s+2>=k)break;j[s++]=224|u>>12,j[s++]=128|u>>6&63,j[s++]=128|u&63}else{if(s+3>=k)break;j[s++]=240|u>>18,j[s++]=128|u>>12&63,j[s++]=128|u>>6&63,j[s++]=128|u&63,a++}}return j[s]=0,s-o},Ke=(r,j,s)=>Ne(r,x,j,s),Je=r=>{for(var j=0,s=0;s<r.length;++s){var l=r.charCodeAt(s);l<=127?j++:l<=2047?j+=2:l>=55296&&l<=57343?(j+=4,++s):j+=3}return j},cj=globalThis.TextDecoder&&new TextDecoder,dj=(r,j,s,l)=>{var o=j+s;if(l)return o;for(;r[j]&&!(j>=o);)++j;return j},qj=(r,j=0,s,l)=>{var o=dj(r,j,s,l);if(o-j>16&&r.buffer&&cj)return cj.decode(r.buffer instanceof ArrayBuffer?r.subarray(j,o):r.slice(j,o));for(var k="";j<o;){var a=r[j++];if(!(a&128)){k+=String.fromCharCode(a);continue}var u=r[j++]&63;if((a&224)==192){k+=String.fromCharCode((a&31)<<6|u);continue}var c=r[j++]&63;if((a&240)==224?a=(a&15)<<12|u<<6|c:a=(a&7)<<18|u<<12|c<<6|r[j++]&63,a<65536)k+=String.fromCharCode(a);else{var f=a-65536;k+=String.fromCharCode(55296|f>>10,56320|f&1023)}}return k},be=(r,j,s)=>r?qj(x,r,j,s):"",Oe=(r,j)=>{j=L(j);var s=!0;K(r,{name:j,fromWireType(l){var o=I[l>>2],k=l+4,a;if(s)a=be(k,o,!0);else{a="";for(var u=0;u<o;++u)a+=String.fromCharCode(x[k+u])}return O(l),a},toWireType(l,o){o instanceof ArrayBuffer&&(o=new Uint8Array(o));var k,a=typeof o=="string";a||ArrayBuffer.isView(o)&&o.BYTES_PER_ELEMENT==1||p("Cannot pass non-string to std::string"),s&&a?k=Je(o):k=o.length;var u=ir(4+k+1),c=u+4;if(I[u>>2]=k,a)if(s)Ke(o,c,k+1);else for(var f=0;f<k;++f){var G=o.charCodeAt(f);G>255&&(O(u),p("String has UTF-16 code units that do not fit in 8 bits")),x[c+f]=G}else x.set(o,c);return l!==null&&l.push(O,u),u},readValueFromPointer:LA,destructorFunction(l){O(l)}})},fj=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,we=(r,j,s)=>{var l=r>>1,o=dj(sA,l,j/2,s);if(o-l>16&&fj)return fj.decode(sA.slice(l,o));for(var k="",a=l;a<o;++a){var u=sA[a];k+=String.fromCharCode(u)}return k},Pe=(r,j,s)=>{if(s??=2147483647,s<2)return 0;s-=2;for(var l=j,o=s<r.length*2?s/2:r.length,k=0;k<o;++k){var a=r.charCodeAt(k);mA[j>>1]=a,j+=2}return mA[j>>1]=0,j-l},Me=r=>r.length*2,Te=(r,j,s)=>{for(var l="",o=r>>2,k=0;!(k>=j/4);k++){var a=I[o+k];if(!a&&!s)break;l+=String.fromCodePoint(a)}return l},Ue=(r,j,s)=>{if(s??=2147483647,s<4)return 0;for(var l=j,o=l+s-4,k=0;k<r.length;++k){var a=r.codePointAt(k);if(a>65535&&k++,Q[j>>2]=a,j+=4,j+4>o)break}return Q[j>>2]=0,j-l},Se=r=>{for(var j=0,s=0;s<r.length;++s){var l=r.codePointAt(s);l>65535&&s++,j+=4}return j},Ve=(r,j,s)=>{s=L(s);var l,o,k;j===2?(l=we,o=Pe,k=Me):(l=Te,o=Ue,k=Se),K(r,{name:s,fromWireType:a=>{var u=I[a>>2],c=l(a+4,u*j,!0);return O(a),c},toWireType:(a,u)=>{typeof u!="string"&&p(\`Cannot pass non-string to C++ string type \${s}\`);var c=k(u),f=ir(4+c+j);return I[f>>2]=c/j,o(u,f+4,c+j),a!==null&&a.push(O,f),f},readValueFromPointer:LA,destructorFunction(a){O(a)}})},We=(r,j)=>{j=L(j),K(r,{isVoid:!0,name:j,fromWireType:()=>{},toWireType:(s,l)=>{}})},Re=r=>{lr(r,!d,1,!i,65536,!1),h.threadInitTLS()},Cj=r=>{if(r instanceof wr||r=="unwind")return z;pA(1,r)},Xe=()=>{if(!zA())try{if(C){xA()&&or(z);return}QA(z)}catch(r){Cj(r)}},Gj=r=>{if(!hA)try{return r()}catch(j){Cj(j)}finally{Xe()}},ze=!Atomics.waitAsync||globalThis.navigator?.userAgent&&Number((navigator.userAgent.match(/Chrom(e|ium)\\/([0-9]+)\\./)||[])[2])<91,nr=r=>{if(!ze){var j=Atomics.waitAsync(Q,r>>2,r);j.value.then(yA);var s=r+128;Atomics.store(Q,s>>2,1)}},yA=()=>Gj(()=>{var r=xA();r&&(nr(r),gj())}),Qe=(r,j)=>{if(r==j)setTimeout(yA);else if(C)postMessage({targetThread:r,cmd:"checkMailbox"});else{var s=h.pthreads[r];if(!s)return;s.postMessage({cmd:"checkMailbox"})}},sr=[],Ye=(r,j,s,l,o,k,a)=>{sr.length=0;for(var u=o>>3,c=o+l>>3;u<c;){var f;W[u++]?f=W[u++]:f=EA[u++],sr.push(f)}var G=cn[r];h.currentProxiedOperationCallerThread=s;var m=G(...sr);if(h.currentProxiedOperationCallerThread=0,k){m.then($=>Fj(k,a,$));return}return m},Ze=r=>{C?postMessage({cmd:"cleanupThread",thread:r}):Mr(r)},An=r=>{},rn=()=>performance.timeOrigin+performance.now(),jn=9007199254740992,tn=-9007199254740992,en=r=>r<tn||r>jn?NaN:Number(r),nn=()=>{},sn=()=>{XA+=1},ln=()=>{throw sn(),"unwind"},on=r=>{RA("OOM")},an=r=>{var j=x.length;r>>>=0,on(r)};function pj(r){return C?iA(2,0,1,r):52}function hj(r,j,s,l){return C?iA(3,0,1,r,j,s,l):(j=en(j),70)}var kn=[null,[],[]],un=(r,j)=>{var s=kn[r];j===0||j===10?((r===1?SA:N)(qj(s)),s.length=0):s.push(j)};function mj(r,j,s,l){if(C)return iA(4,0,1,r,j,s,l);for(var o=0,k=0;k<s;k++){var a=I[j>>2],u=I[j+4>>2];j+=8;for(var c=0;c<u;c++)un(r,x[a+c]);o+=u}return I[l>>2]=o,0}h.init();for(var aA=new Uint8Array(123),T=25;T>=0;--T)aA[48+T]=52+T,aA[65+T]=T,aA[97+T]=26+T;if(aA[43]=62,aA[47]=63,se(),pe(),Bt(),e.noExitRuntime&&(YA=e.noExitRuntime),e.print&&(SA=e.print),e.printErr&&(N=e.printErr),e.wasmBinary&&(_r=e.wasmBinary),e.arguments&&(v=e.arguments),e.thisProgram&&(B=e.thisProgram),e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.shift()();var cn=[Vr,Wr,pj,hj,mj],Ej,Ij,xA,ir,O,dn,lr,$j,Fj,vj,Lj,or,gj,_j,Hj,yj,xj,qn,Dj;function fn(r){Ej=r.G,Ij=r.H,xA=r.J,ir=e._malloc=r.K,O=e._free=r.L,dn=r.M,lr=r.N,$j=r.O,Fj=r.P,vj=r.Q,Lj=r.R,or=r.S,gj=r.T,_j=r.U,Hj=r.V,yj=r.W,xj=r.X,qn=Dj=r.I}var Bj;function Cn(){Bj={i:Yt,C:Zt,h:re,o:je,n:Ee,m:$e,e:Fe,b:ve,D:_e,l:ye,q:xe,d:De,c:Be,E:Oe,g:Ve,p:We,z:Re,u:Qe,k:Ye,s:Ze,y:nr,B:An,x:nn,A:ln,f:rn,t:an,r:QA,w:pj,v:hj,j:mj,a:Y}}function Nj(){if(C){VA?.(e),Kr();return}Nt();function r(){e.calledRun=!0,!hA&&(Kr(),VA?.(e),e.onRuntimeInitialized?.(),Kt())}e.setStatus?(e.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>e.setStatus(""),1),r()},1)):r()}var tA;return C||(tA=await Or(),Nj()),Br?t=e:t=new Promise((r,j)=>{VA=r,Hr=j}),t}})();typeof Ft=="object"&&typeof UA=="object"?(UA.exports=TA,UA.exports.default=TA):typeof define=="function"&&define.amd&&define([],()=>TA);var ys=globalThis.name=="em-pthread";ys&&TA()});var J={};Fn(J,{AdditionalCaptureBlocks:()=>_n,AdditionalPlaybackBlocks:()=>gn,ClockJumpCheckInterval:()=>Kn,ClockJumpThreshold:()=>Jn,ConnectInterval:()=>Sn,ConnectTimeout:()=>Mn,DefaultRefreshRate:()=>yn,DefaultVideoCodec:()=>Vn,HealthCheckTimeout:()=>Nn,MainConnectionPingInterval:()=>bn,MaxNumberOfDecoders:()=>Dn,MinDBFs:()=>Oj,MinTokenLifetime:()=>Tn,MinTokenRefreshInterval:()=>Un,PlaybackPreload:()=>Hn,RenderQuantumSize:()=>Bn,VadPreload:()=>xn,WebRtcIceTimeout:()=>wn,WebRtcStatsSnapshotInterval:()=>On,WebRtcTimeout:()=>Pn});var gn=3,_n=3,Hn=3,yn=250,xn=3,Dn=512,Bn=128,Oj=-758.596,Nn=1e4,Kn=1e3,Jn=1e4,bn=3e3,On=1e3,wn=3e3,Pn=1e4,Mn=5e3,Tn=6e4,Un=5e3,Sn=[0,100,200,200,500],Vn="H264";function uA(n,A,t){return n.postMessage(A,t)}function ur(n){return n.sampleRate*.02*(n.stereo?2:1)}function cr(n,A){let t=ur(n),e=t*A,i=e+t;return n.samples.subarray(e,i)}function dr(n,A,t){n.headers[A]=t.id}function wj(n){return[n.values[0],n.values[1]]}function Pj(n,A){n.values[0]=A[0],n.values[1]=A[1]}function Mj(n,A){return n.values[2+A*5]}function Tj(n,A,t){n.values[2+A*5]=t}function Uj(n,A){let t=2+A*5+1;return[n.values[t+0],n.values[t+1]]}function Sj(n,A,t){let e=2+A*5+1;n.values[e+0]=t[0],n.values[e+1]=t[1]}function Vj(n,A){return n.values[2+A*5+3]}function Wj(n,A,t){n.values[2+A*5+3]=t}function Rj(n,A){return n.values[2+A*5+4]}function Xj(n,A,t){n.values[2+A*5+4]=t}function zj(n){return n.values[0]!==0}function Qj(n){return n.values[1]}function Yj(n){return n.values[2]}function Zj(n){return n.values[3]}function At(n,A){return n.values[3]=A}function rt(n){return n?Array.from(n).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var Wn;(n=>{let A;(t=>(t[t.InvalidPassword=-1]="InvalidPassword",t[t.Unknown=0]="Unknown",t[t.Unencrypted=1]="Unencrypted",t[t.Encrypted=2]="Encrypted"))(A=n.PeerCipherStatus||={})})(Wn||={});function st(n){return{type:"Success",value:n}}function D(n){return{type:"Failure",reason:n}}var{Deno:jt}=globalThis,Rn=typeof jt?.noColor=="boolean"?jt.noColor:!1,Xn=!Rn;function fr(n,A){return{open:\`\\x1B[\${n.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function Cr(n,A){return Xn?\`\${A.open}\${n.replace(A.regexp,A.open)}\${A.close}\`:n}function qr(n){return Cr(n,fr([0],0))}function tt(n){return Cr(n,fr([1],22))}function zn(n){return Cr(n,fr([2],22))}var Ss=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),Qn=new Date,DA=(n=>(n[n.CRITICAL=0]="CRITICAL",n[n.ERROR=1]="ERROR",n[n.WARN=2]="WARN",n[n.INFO=3]="INFO",n[n.DEBUG=4]="DEBUG",n))(DA||{}),it={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},Yn={4:zn,3:qr,2:qr,1:tt,0:tt};function Zn({message:n}){return String(n)}function et(n){return JSON.stringify({timestamp:n.date.toISOString(),level:DA[n.level],message:n.message,extra:n.extra})}function nt(n){function A(q,C){return[Math.floor(q/C),q%C]}function t(){let q,C=n.date.valueOf()-Qn.valueOf();[C,q]=A(C,1e3);let[v,B]=A(C,60);return\`\${v.toString().padStart(4,"0")}:\${B.toString().padStart(2,"0")}.\${q.toString().padStart(4,"0")}\`}function e(){return n.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(n.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(n.extra)}let i=it[n.level],d=n.logger.name!==void 0?\`@\${n.logger}\`:"";return\`\${qr(t())}\${d} \${i} \${Yn[n.level](String(n.message))}\${e()}\`}function As(n){let A=\`[\${n.date.toISOString()}]\`,t=\`[\${DA[n.level]}]\`,e=n.logger.name!==void 0?\`[\${n.logger.name}] \`:"",i=it[n.level];return\`\${A} \${i} \${t.padEnd(7," ")} \${e}\${n.message}\`}function rs(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var lt=class{static sparse=Zn;static json=et;static pretty=nt;static structured=As;static default=rs()?nt:et;constructor(){}},js=class{formatter;consoleObject;filter;constructor(n=lt.default,A=4,t=console){this.filter=A,this.formatter=n,this.consoleObject=t}handle(n){let A=this.formatter(n);switch(n.level){case 1:this.consoleObject.error(A);break;case 2:this.consoleObject.warn(A);break;case 3:this.consoleObject.info(A);break;case 4:this.consoleObject.debug(A);break}}};var R=class{#A;sinks;filter;parent;get name(){return this.#A}constructor(n,A=void 0,t=[],e=void 0){this.#A=A,this.sinks=t,this.filter=n,this.parent=e}log(n,A,t=void 0){let e={date:new Date,level:n,logger:this,message:A,extra:t};this.filter<n||this.insert(e)}insert(n){if(!(this.filter<n.level)){for(let A of this.sinks)A.filter>=n.level&&A.handle(n);this.parent!==void 0&&this.parent.insert(n)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},cA=new R(3,void 0,[new js]),ts=R.prototype.log.bind(cA,1),es=R.prototype.log.bind(cA,2),ot=R.prototype.log.bind(cA,3),ns=R.prototype.log.bind(cA,4),Vs=R.prototype.log.bind(cA);var at;function kt(n,...A){let t=ss(A);at?at?.info(n,t):ot(n,t)}function ss(...n){if(n.length===1&&typeof n[0]=="object"&&n[0]!==null)return{...n[0]};if(n.length>0)return{args:n}}function BA(n){return n.connectionId*4294967296+n.mediaId}function ut(n){return{mediaId:n%4294967296,connectionId:Math.floor(n/4294967296)}}function U(n,A,t){let e;switch(A){case"f32":e=n.HEAPF32;break;case"u32":e=n.HEAPU32;break;case"i32":e=n.HEAP32;break;case"u8":e=n.HEAPU8;break;default:throw new Error(\`allocating \${A} is not supported\`)}let i=n._malloc(t*e.BYTES_PER_ELEMENT);if(i===0||i%e.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${t} \${A} array\`);let d=i/e.BYTES_PER_ELEMENT;return e.subarray(d,d+t)}function eA(n,A){n._free(A.byteOffset)}function Gr(n,A,t,e){return{headers:U(n,"i32",t),samples:U(n,"f32",t*ur({sampleRate:A,stereo:e})),length:t,sampleRate:A,stereo:e}}function pr(n,A){eA(n,A.headers),eA(n,A.samples)}function ct(n,A){return{values:U(n,"f32",2+A*5),length:A}}function dt(n,A){eA(n,A.values)}function qt(n){return{values:U(n,"f32",4)}}function ft(n,A){eA(n,A.values)}function Ct(n){let A=n.length,t=0,e=0;for(;e<A;){let i=n.charCodeAt(e++);if((i&4294967168)===0){t++;continue}else if((i&4294965248)===0)t+=2;else{if(i>=55296&&i<=56319&&e<A){let d=n.charCodeAt(e);(d&64512)===56320&&(++e,i=((i&1023)<<10)+(d&1023)+65536)}(i&4294901760)===0?t+=3:t+=4}}return t}function is(n,A,t){let e=n.length,i=t,d=0;for(;d<e;){let q=n.charCodeAt(d++);if((q&4294967168)===0){A[i++]=q;continue}else if((q&4294965248)===0)A[i++]=q>>6&31|192;else{if(q>=55296&&q<=56319&&d<e){let C=n.charCodeAt(d);(C&64512)===56320&&(++d,q=((q&1023)<<10)+(C&1023)+65536)}(q&4294901760)===0?(A[i++]=q>>12&15|224,A[i++]=q>>6&63|128):(A[i++]=q>>18&7|240,A[i++]=q>>12&63|128,A[i++]=q>>6&63|128)}A[i++]=q&63|128}}var ls=new TextEncoder,os=50;function as(n,A,t){ls.encodeInto(n,A.subarray(t))}function Gt(n,A,t){n.length>os?as(n,A,t):is(n,A,t)}var ks=4096;function hr(n,A,t){let e=A,i=e+t,d=[],q="";for(;e<i;){let C=n[e++];if((C&128)===0)d.push(C);else if((C&224)===192){let v=n[e++]&63;d.push((C&31)<<6|v)}else if((C&240)===224){let v=n[e++]&63,B=n[e++]&63;d.push((C&31)<<12|v<<6|B)}else if((C&248)===240){let v=n[e++]&63,B=n[e++]&63,pA=n[e++]&63,P=(C&7)<<18|v<<12|B<<6|pA;P>65535&&(P-=65536,d.push(P>>>10&1023|55296),P=56320|P&1023),d.push(P)}else d.push(C);d.length>=ks&&(q+=String.fromCharCode(...d),d.length=0)}return d.length>0&&(q+=String.fromCharCode(...d)),q}var us=new TextDecoder,cs=200;function ds(n,A,t){let e=n.subarray(A,A+t);return us.decode(e)}function pt(n,A,t){return t>cs?ds(n,A,t):hr(n,A,t)}var X=class{constructor(A,t){this.type=A,this.data=t}};var g=class n extends Error{constructor(A){super(A);let t=Object.create(n.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:n.name})}};function ht(n,A,t){let e=t/4294967296,i=t;n.setUint32(A,e),n.setUint32(A+4,i)}function NA(n,A,t){let e=Math.floor(t/4294967296),i=t;n.setUint32(A,e),n.setUint32(A+4,i)}function KA(n,A){let t=n.getInt32(A),e=n.getUint32(A+4);return t*4294967296+e}function mt(n,A){let t=n.getUint32(A),e=n.getUint32(A+4);return t*4294967296+e}var qs=-1,fs=4294967296-1,Cs=17179869184-1;function Gs({sec:n,nsec:A}){if(n>=0&&A>=0&&n<=Cs)if(A===0&&n<=fs){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{let t=n/4294967296,e=n&4294967295,i=new Uint8Array(8),d=new DataView(i.buffer);return d.setUint32(0,A<<2|t&3),d.setUint32(4,e),i}else{let t=new Uint8Array(12),e=new DataView(t.buffer);return e.setUint32(0,A),NA(e,4,n),t}}function ps(n){let A=n.getTime(),t=Math.floor(A/1e3),e=(A-t*1e3)*1e6,i=Math.floor(e/1e9);return{sec:t+i,nsec:e-i*1e9}}function hs(n){if(n instanceof Date){let A=ps(n);return Gs(A)}else return null}function ms(n){let A=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:A.getUint32(0),nsec:0};case 8:{let t=A.getUint32(0),e=A.getUint32(4),i=(t&3)*4294967296+e,d=t>>>2;return{sec:i,nsec:d}}case 12:{let t=KA(A,4),e=A.getUint32(0);return{sec:t,nsec:e}}default:throw new g(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${n.length}\`)}}function Es(n){let A=ms(n);return new Date(A.sec*1e3+A.nsec/1e6)}var Et={type:qs,encode:hs,decode:Es};var S=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Et)}register({type:A,encode:t,decode:e}){if(A>=0)this.encoders[A]=t,this.decoders[A]=e;else{let i=-1-A;this.builtInEncoders[i]=t,this.builtInDecoders[i]=e}}tryToEncode(A,t){for(let e=0;e<this.builtInEncoders.length;e++){let i=this.builtInEncoders[e];if(i!=null){let d=i(A,t);if(d!=null){let q=-1-e;return new X(q,d)}}}for(let e=0;e<this.encoders.length;e++){let i=this.encoders[e];if(i!=null){let d=i(A,t);if(d!=null){let q=e;return new X(q,d)}}}return A instanceof X?A:null}decode(A,t,e){let i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(A,t,e):new X(t,A)}};S.defaultCodec=new S;function Is(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function dA(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):Is(n)?new Uint8Array(n):Uint8Array.from(n)}var $s=100,Fs=2048,JA=class n{constructor(A){this.entered=!1,this.extensionCodec=A?.extensionCodec??S.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??$s,this.initialBufferSize=A?.initialBufferSize??Fs,this.sortKeys=A?.sortKeys??!1,this.forceFloat32=A?.forceFloat32??!1,this.ignoreUndefined=A?.ignoreUndefined??!1,this.forceIntegerToFloat=A?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(A){if(this.entered)return this.clone().encodeSharedRef(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(A){if(this.entered)return this.clone().encode(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(A,t){if(t>this.maxDepth)throw new Error(\`Too deep objects in depth \${t}\`);A==null?this.encodeNil():typeof A=="boolean"?this.encodeBoolean(A):typeof A=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(A):this.encodeNumber(A):typeof A=="string"?this.encodeString(A):this.useBigInt64&&typeof A=="bigint"?this.encodeBigInt64(A):this.encodeObject(A,t)}ensureBufferSizeToWrite(A){let t=this.pos+A;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(A){let t=new ArrayBuffer(A),e=new Uint8Array(t),i=new DataView(t);e.set(this.bytes),this.view=i,this.bytes=e}encodeNil(){this.writeU8(192)}encodeBoolean(A){A===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(A){!this.forceIntegerToFloat&&Number.isSafeInteger(A)?A>=0?A<128?this.writeU8(A):A<256?(this.writeU8(204),this.writeU8(A)):A<65536?(this.writeU8(205),this.writeU16(A)):A<4294967296?(this.writeU8(206),this.writeU32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(207),this.writeU64(A)):A>=-32?this.writeU8(224|A+32):A>=-128?(this.writeU8(208),this.writeI8(A)):A>=-32768?(this.writeU8(209),this.writeI16(A)):A>=-2147483648?(this.writeU8(210),this.writeI32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(211),this.writeI64(A)):this.encodeNumberAsFloat(A)}encodeNumberAsFloat(A){this.forceFloat32?(this.writeU8(202),this.writeF32(A)):(this.writeU8(203),this.writeF64(A))}encodeBigInt64(A){A>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(A)):(this.writeU8(211),this.writeBigInt64(A))}writeStringHeader(A){if(A<32)this.writeU8(160+A);else if(A<256)this.writeU8(217),this.writeU8(A);else if(A<65536)this.writeU8(218),this.writeU16(A);else if(A<4294967296)this.writeU8(219),this.writeU32(A);else throw new Error(\`Too long string: \${A} bytes in UTF-8\`)}encodeString(A){let e=Ct(A);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),Gt(A,this.bytes,this.pos),this.pos+=e}encodeObject(A,t){let e=this.extensionCodec.tryToEncode(A,this.context);if(e!=null)this.encodeExtension(e);else if(Array.isArray(A))this.encodeArray(A,t);else if(ArrayBuffer.isView(A))this.encodeBinary(A);else if(typeof A=="object")this.encodeMap(A,t);else throw new Error(\`Unrecognized object: \${Object.prototype.toString.apply(A)}\`)}encodeBinary(A){let t=A.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(\`Too large binary: \${t}\`);let e=dA(A);this.writeU8a(e)}encodeArray(A,t){let e=A.length;if(e<16)this.writeU8(144+e);else if(e<65536)this.writeU8(220),this.writeU16(e);else if(e<4294967296)this.writeU8(221),this.writeU32(e);else throw new Error(\`Too large array: \${e}\`);for(let i of A)this.doEncode(i,t+1)}countWithoutUndefined(A,t){let e=0;for(let i of t)A[i]!==void 0&&e++;return e}encodeMap(A,t){let e=Object.keys(A);this.sortKeys&&e.sort();let i=this.ignoreUndefined?this.countWithoutUndefined(A,e):e.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(\`Too large map object: \${i}\`);for(let d of e){let q=A[d];this.ignoreUndefined&&q===void 0||(this.encodeString(d),this.doEncode(q,t+1))}}encodeExtension(A){if(typeof A.data=="function"){let e=A.data(this.pos+6),i=e.length;if(i>=4294967296)throw new Error(\`Too large extension object: \${i}\`);this.writeU8(201),this.writeU32(i),this.writeI8(A.type),this.writeU8a(e);return}let t=A.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(\`Too large extension object: \${t}\`);this.writeI8(A.type),this.writeU8a(A.data)}writeU8(A){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,A),this.pos++}writeU8a(A){let t=A.length;this.ensureBufferSizeToWrite(t),this.bytes.set(A,this.pos),this.pos+=t}writeI8(A){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,A),this.pos++}writeU16(A){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,A),this.pos+=2}writeI16(A){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,A),this.pos+=2}writeU32(A){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,A),this.pos+=4}writeI32(A){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,A),this.pos+=4}writeF32(A){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,A),this.pos+=4}writeF64(A){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,A),this.pos+=8}writeU64(A){this.ensureBufferSizeToWrite(8),ht(this.view,this.pos,A),this.pos+=8}writeI64(A){this.ensureBufferSizeToWrite(8),NA(this.view,this.pos,A),this.pos+=8}writeBigUint64(A){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,A),this.pos+=8}writeBigInt64(A){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,A),this.pos+=8}};function mr(n,A){return new JA(A).encodeSharedRef(n)}function bA(n){return\`\${n<0?"-":""}0x\${Math.abs(n).toString(16).padStart(2,"0")}\`}var vs=16,Ls=16,OA=class{constructor(A=vs,t=Ls){this.hit=0,this.miss=0,this.maxKeyLength=A,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,t,e){let i=this.caches[e-1];A:for(let d of i){let q=d.bytes;for(let C=0;C<e;C++)if(q[C]!==A[t+C])continue A;return d.str}return null}store(A,t){let e=this.caches[A.length-1],i={bytes:A,str:t};e.length>=this.maxLengthPerKey?e[Math.random()*e.length|0]=i:e.push(i)}decode(A,t,e){let i=this.find(A,t,e);if(i!=null)return this.hit++,i;this.miss++;let d=hr(A,t,e),q=Uint8Array.prototype.slice.call(A,t,t+e);return this.store(q,d),d}};var Er="array",CA="map_key",$t="map_value",gs=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new g("The type of key must be string or number but "+typeof n)},Ir=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let t=this.getUninitializedStateFromPool();t.type=Er,t.position=0,t.size=A,t.array=new Array(A)}pushMapState(A){let t=this.getUninitializedStateFromPool();t.type=CA,t.readCount=0,t.size=A,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let A={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(A)}return this.stack[this.stackHeadPosition]}release(A){if(this.stack[this.stackHeadPosition]!==A)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(A.type===Er){let e=A;e.size=0,e.array=void 0,e.position=0,e.type=void 0}if(A.type===CA||A.type===$t){let e=A;e.size=0,e.map=void 0,e.readCount=0,e.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},fA=-1,$r=new DataView(new ArrayBuffer(0)),_s=new Uint8Array($r.buffer);try{$r.getInt8(0)}catch(n){if(!(n instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var It=new RangeError("Insufficient data"),Hs=new OA,wA=class n{constructor(A){this.totalPos=0,this.pos=0,this.view=$r,this.bytes=_s,this.headByte=fA,this.stack=new Ir,this.entered=!1,this.extensionCodec=A?.extensionCodec??S.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.rawStrings=A?.rawStrings??!1,this.maxStrLength=A?.maxStrLength??4294967295,this.maxBinLength=A?.maxBinLength??4294967295,this.maxArrayLength=A?.maxArrayLength??4294967295,this.maxMapLength=A?.maxMapLength??4294967295,this.maxExtLength=A?.maxExtLength??4294967295,this.keyDecoder=A?.keyDecoder!==void 0?A.keyDecoder:Hs,this.mapKeyConverter=A?.mapKeyConverter??gs}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=fA,this.stack.reset()}setBuffer(A){let t=dA(A);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(A){if(this.headByte===fA&&!this.hasRemaining(1))this.setBuffer(A);else{let t=this.bytes.subarray(this.pos),e=dA(A),i=new Uint8Array(t.length+e.length);i.set(t),i.set(e,t.length),this.setBuffer(i)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:t,pos:e}=this;return new RangeError(\`Extra \${t.byteLength-e} of \${t.byteLength} byte(s) found at buffer[\${A}]\`)}decode(A){if(this.entered)return this.clone().decode(A);try{this.entered=!0,this.reinitializeState(),this.setBuffer(A);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(A){if(this.entered){yield*this.clone().decodeMulti(A);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(A);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(A){if(this.entered)return this.clone().decodeAsync(A);try{this.entered=!0;let t=!1,e;for await(let C of A){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(C);try{e=this.doDecodeSync(),t=!0}catch(v){if(!(v instanceof RangeError))throw v}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return e}let{headByte:i,pos:d,totalPos:q}=this;throw new RangeError(\`Insufficient data in parsing \${bA(i)} at \${q} (\${d} in the current buffer)\`)}finally{this.entered=!1}}decodeArrayStream(A){return this.decodeMultiAsync(A,!0)}decodeStream(A){return this.decodeMultiAsync(A,!1)}async*decodeMultiAsync(A,t){if(this.entered){yield*this.clone().decodeMultiAsync(A,t);return}try{this.entered=!0;let e=t,i=-1;for await(let d of A){if(t&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(d),e&&(i=this.readArraySize(),e=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(q){if(!(q instanceof RangeError))throw q}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){A:for(;;){let A=this.readHeadByte(),t;if(A>=224)t=A-256;else if(A<192)if(A<128)t=A;else if(A<144){let i=A-128;if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A<160){let i=A-144;if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else{let i=A-160;t=this.decodeString(i,0)}else if(A===192)t=null;else if(A===194)t=!1;else if(A===195)t=!0;else if(A===202)t=this.readF32();else if(A===203)t=this.readF64();else if(A===204)t=this.readU8();else if(A===205)t=this.readU16();else if(A===206)t=this.readU32();else if(A===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(A===208)t=this.readI8();else if(A===209)t=this.readI16();else if(A===210)t=this.readI32();else if(A===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(A===217){let i=this.lookU8();t=this.decodeString(i,1)}else if(A===218){let i=this.lookU16();t=this.decodeString(i,2)}else if(A===219){let i=this.lookU32();t=this.decodeString(i,4)}else if(A===220){let i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===221){let i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===222){let i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===223){let i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===196){let i=this.lookU8();t=this.decodeBinary(i,1)}else if(A===197){let i=this.lookU16();t=this.decodeBinary(i,2)}else if(A===198){let i=this.lookU32();t=this.decodeBinary(i,4)}else if(A===212)t=this.decodeExtension(1,0);else if(A===213)t=this.decodeExtension(2,0);else if(A===214)t=this.decodeExtension(4,0);else if(A===215)t=this.decodeExtension(8,0);else if(A===216)t=this.decodeExtension(16,0);else if(A===199){let i=this.lookU8();t=this.decodeExtension(i,1)}else if(A===200){let i=this.lookU16();t=this.decodeExtension(i,2)}else if(A===201){let i=this.lookU32();t=this.decodeExtension(i,4)}else throw new g(\`Unrecognized type byte: \${bA(A)}\`);this.complete();let e=this.stack;for(;e.length>0;){let i=e.top();if(i.type===Er)if(i.array[i.position]=t,i.position++,i.position===i.size)t=i.array,e.release(i);else continue A;else if(i.type===CA){if(t==="__proto__")throw new g("The key __proto__ is not allowed");i.key=this.mapKeyConverter(t),i.type=$t;continue A}else if(i.map[i.key]=t,i.readCount++,i.readCount===i.size)t=i.map,e.release(i);else{i.key=null,i.type=CA;continue A}}return t}}readHeadByte(){return this.headByte===fA&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=fA}readArraySize(){let A=this.readHeadByte();switch(A){case 220:return this.readU16();case 221:return this.readU32();default:{if(A<160)return A-144;throw new g(\`Unrecognized array type byte: \${bA(A)}\`)}}}pushMapState(A){if(A>this.maxMapLength)throw new g(\`Max length exceeded: map length (\${A}) > maxMapLengthLength (\${this.maxMapLength})\`);this.stack.pushMapState(A)}pushArrayState(A){if(A>this.maxArrayLength)throw new g(\`Max length exceeded: array length (\${A}) > maxArrayLength (\${this.maxArrayLength})\`);this.stack.pushArrayState(A)}decodeString(A,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(A,t):this.decodeBinary(A,t)}decodeUtf8String(A,t){if(A>this.maxStrLength)throw new g(\`Max length exceeded: UTF-8 byte length (\${A}) > maxStrLength (\${this.maxStrLength})\`);if(this.bytes.byteLength<this.pos+t+A)throw It;let e=this.pos+t,i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?i=this.keyDecoder.decode(this.bytes,e,A):i=pt(this.bytes,e,A),this.pos+=t+A,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===CA:!1}decodeBinary(A,t){if(A>this.maxBinLength)throw new g(\`Max length exceeded: bin length (\${A}) > maxBinLength (\${this.maxBinLength})\`);if(!this.hasRemaining(A+t))throw It;let e=this.pos+t,i=this.bytes.subarray(e,e+A);return this.pos+=t+A,i}decodeExtension(A,t){if(A>this.maxExtLength)throw new g(\`Max length exceeded: ext length (\${A}) > maxExtLength (\${this.maxExtLength})\`);let e=this.view.getInt8(this.pos+t),i=this.decodeBinary(A,t+1);return this.extensionCodec.decode(i,e,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let A=this.view.getUint8(this.pos);return this.pos++,A}readI8(){let A=this.view.getInt8(this.pos);return this.pos++,A}readU16(){let A=this.view.getUint16(this.pos);return this.pos+=2,A}readI16(){let A=this.view.getInt16(this.pos);return this.pos+=2,A}readU32(){let A=this.view.getUint32(this.pos);return this.pos+=4,A}readI32(){let A=this.view.getInt32(this.pos);return this.pos+=4,A}readU64(){let A=mt(this.view,this.pos);return this.pos+=8,A}readI64(){let A=KA(this.view,this.pos);return this.pos+=8,A}readU64AsBigInt(){let A=this.view.getBigUint64(this.pos);return this.pos+=8,A}readI64AsBigInt(){let A=this.view.getBigInt64(this.pos);return this.pos+=8,A}readF32(){let A=this.view.getFloat32(this.pos);return this.pos+=4,A}readF64(){let A=this.view.getFloat64(this.pos);return this.pos+=8,A}};function Fr(n,A){return new wA(A).decode(n)}var GA=class n{constructor(A,t,e,i,d){this.mediaIds=A;this.sequenceNumber=t;this.timeStamp=e;this.isEndOfSpurt=i;this.payload=d}static parse(A){let t;try{t=Fr(A)}catch{return D("not valid msgpack")}if(!Array.isArray(t))return D("container must be an array");if(t.length<6)return D("missing fields");if(t[0]!==1)return D("unknown type");if(!Array.isArray(t[1]))return D("media ids must be an array");if(!t[1].every(B=>typeof B=="number"))return D("media ids must be numbers");if(typeof t[2]!="number")return D("sequence number must be a number");if(typeof t[3]!="number")return D("timestamp must be a number");if(typeof t[4]!="number")return D("flags must be a number");let e=t[1],i=t[2]>>>0,d=t[3]>>>0,C=(t[4]&1)!==0,v=t[t.length-1];return v instanceof Uint8Array?st(new n(e,i,d,C,v)):D("payload must be bytes")}toBytes(){let A=Number(this.isEndOfSpurt),t=[1,this.mediaIds,this.sequenceNumber>>>0,this.timeStamp>>>0,A,this.payload];return new Uint8Array(mr(t,{forceFloat32:!0,ignoreUndefined:!0}))}};var PA=class{constructor(A,t){this.sampleRate=A;this.wasm=t;this.sequenceNumber=Math.random()*Math.pow(2,32)>>0;this.timestamp=Math.random()*Math.pow(2,32)>>0;this.connections=[];this.monitoring=!1;this.active=!1;this.stats={numberPackets:0,numberTicks:0,numberPacketError:0,numberPacketsMediaNotFound:0};this.encoder=new t.Encoder(A,15,!0,J.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=qt(this.wasm),this.outBuffer=U(this.wasm,"u8",1270),At(this.information,1)}setVad(A){this.encoder.set_volume_gate(A.volumeGate!==void 0,A.volumeGate?.attackThreshold??0,A.volumeGate?.releaseThreshold??0),this.encoder.set_speech_detection(A.voiceActivity!==void 0,A.voiceActivity?.attackThreshold??0,A.voiceActivity?.releaseThreshold??0)}setMedias(A){this.connections=A.filter(({mediaIds:t})=>t.length>0)}close(){ft(this.wasm,this.information),eA(this.wasm,this.outBuffer),this.encoder.delete()}encode(A){for(this.encoder.push(A.byteOffset,this.information.values.byteOffset);;){let t=this.encoder.pop(this.connections.length===0?0:this.outBuffer.byteOffset,this.outBuffer.length);if(t===0)break;if(t<0){kt(\`failed encoding packet: \${t}\`);return}if(this.timestamp=this.timestamp+1800>>0,t===1)continue;this.sequenceNumber=this.sequenceNumber+1>>0;let e=this.active&&!this.encoder.active;this.active=this.encoder.active,this.monitoring=this.connections.some(i=>i.id===0);for(let i of this.connections){if(this.monitoring&&i.id!==0)continue;let d=new GA(i.mediaIds,this.sequenceNumber,this.timestamp,e,this.outBuffer.subarray(0,t));uA(globalThis,["sendPacket",{connectionId:i.id,packet:d.toBytes()}])}}}onMessage(A){let[t,e]=A;switch(t){case"captureSetVad":this?.setVad(e);break;case"captureSetMedias":this?.setMedias(e.connections);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){return{sequenceNumber:this.sequenceNumber,timestamp:this.timestamp,connections:this.connections.map(A=>\`\${A.id} => \${A.mediaIds.join(",")}\`),active:this.active,monitoring:this.monitoring,information:{active:zj(this.information),speechProbability:Qj(this.information),rmsDBFS:Yj(this.information),volume:Zj(this.information)},encoder:{sample_rate:this.encoder.sample_rate,fec_packet_loss:this.encoder.fec_packet_loss,voip:this.encoder.voip,vad_preload:this.encoder.vad_preload,complexity:this.encoder.complexity,speech_probability:this.encoder.speech_probability,rms_dbfs:this.encoder.rms_dbfs,active:this.encoder.active,speech_detection_enabled:this.encoder.speech_detection_enabled,speech_detection_going_active:this.encoder.speech_detection_going_active,speech_detection_going_inactive:this.encoder.speech_detection_going_inactive,volume_gate_enabled:this.encoder.volume_gate_enabled,volume_gate_going_active:this.encoder.volume_gate_going_active,volume_gate_going_inactive:this.encoder.volume_gate_going_inactive}}}},MA=class{constructor(A){this.wasm=A;this.medias=new Map;this.stats={numberPackets:0,numberTicks:0,numberPacketError:0,numberPacketsMediaNotFound:0,numberTicksWithAudio:0};this.largestIndex=-1;this.decoders=U(this.wasm,"u32",J.MaxNumberOfDecoders),this.information=ct(this.wasm,J.MaxNumberOfDecoders),Pj(this.information,[1,1])}close(){dt(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,t){this.stats.numberPackets++;let e=GA.parse(t);if(e.type==="Failure"){this.stats.numberPacketError++;let i=Array.from(t).map(d=>d.toString(16).padStart(2,"0")).join("");console.error(\`failed decoding audio packet; reason: \${e.reason}, connection: \${A}, dump: \${i}\`);return}for(let i of e.value.mediaIds){let d=this.medias.get(BA({connectionId:A,mediaId:i}));if(d===void 0){this.stats.numberPacketsMediaNotFound++;continue}d.lastPacket=t;let q=U(this.wasm,"u8",e.value.payload.length);q.set(e.value.payload),d.decoder.push(e.value.sequenceNumber,e.value.timeStamp,e.value.isEndOfSpurt,q.byteOffset,q.length)}}insertMedia(A,t,e,i=[1,1]){let d=BA({connectionId:t,mediaId:e}),q=new this.wasm.Decoder;this.medias.set(d,{index:A,decoder:q,lastPacket:void 0}),this.decoders[A]=q.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),Sj(this.information,A,i),Xj(this.information,A,0),Wj(this.information,A,0)}removeMedia(A,t,e){let i=BA({connectionId:t,mediaId:e}),d=this.medias.get(i);if(!(d===void 0||d.index!==A)&&(this.medias.delete(i),Tj(this.information,A,0),this.decoders[A]=0,d.decoder.delete(),A===this.largestIndex)){for(A=A-1;A>=0&&this.decoders[A]===0;A--);this.largestIndex=A}}decode(A){return{hasAudio:this.wasm.pop_many(this.decoders.byteOffset,this.information.values.byteOffset,this.largestIndex+1,A.byteOffset)}}onMessage(A){let[t,e]=A;switch(t){case"playbackReceivePacket":this.receivePacket(e.connectionId,e.packet);break;case"playbackUpdateMedias":for(let{index:i,connectionId:d,mediaId:q}of e.removed)this.removeMedia(i,d,q);for(let{index:i,connectionId:d,mediaId:q,volume:C}of e.added)this.insertMedia(i,d,q,C);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){let A=[];for(let[t,e]of this.medias){let i=ut(t);A.push({index:e.index,connectionId:i.connectionId,mediaId:i.mediaId,rmsDBFS:Mj(this.information,e.index),volume:Uj(this.information,e.index),voicedBlocks:Rj(this.information,e.index),silentBlocks:Vj(this.information,e.index),time:e.decoder.time,consecutive_silence:e.decoder.consecutive_silence,last_voiced_time_point:e.decoder.last_voiced_time_point,sequence_number:e.decoder.sequence_number,packetsSeen:e.decoder.packets_seen,packetsInvalid:e.decoder.packets_invalid,packetsTooLate:e.decoder.packets_too_late,packetsTooEarly:e.decoder.packets_too_early,packetsRepeated:e.decoder.packets_repeated,packetsProcessed:e.decoder.packets_processed,packetsLost:e.decoder.packets_lost,rewinds:e.decoder.rewinds,cacheLength:e.decoder.cache_length,lastPacket:rt(e.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:wj(this.information),decoders:A}}};var Ht=Ln(vt()),Lt=(0,Ht.default)(),gt,_t;globalThis.addEventListener("message",vr);async function vr(n){let A=n.data,[t,e]=A;switch(t){case"captureInit":e.workletPort.onmessage=vr,gt=new Lr(e.sampleRate,await Lt);break;case"playbackInit":e.workletPort.onmessage=vr,_t=new gr(await Lt);break;case"close":globalThis.close();break}gt?.onMessage(A),_t?.onMessage(A)}var Lr=class extends PA{constructor(t,e){super(t,e);this.id=-1;this.samples=Gr(this.wasm,t,2+J.VadPreload+J.AdditionalCaptureBlocks,!1),uA(globalThis,["captureReady",{sampleBuffer:this.samples,informationBuffer:this.information}])}close(){super.close(),pr(this.wasm,this.samples)}onMessage(t){super.onMessage(t);let[e,i]=t;e==="captureTick"&&this.tick(i.id)}tick(t){for(;this.id<t;this.id+=1)this.encode(cr(this.samples,this.id%this.samples.length))}dump(){return{type:"shared capture worker",id:this.id,sampleRate:this.samples.sampleRate,stereo:this.samples.stereo,length:this.samples.length,...super.dump()}}},gr=class extends MA{constructor(A){super(A);let t=2+J.AdditionalPlaybackBlocks;this.sampleBuffer=Gr(A,48e3,t,!0),this.sampleBuffer.samples.fill(0),this.prefill=t-2;for(let e=0;e<this.prefill;e++)dr(this.sampleBuffer,e,{id:e});this.id=this.prefill,uA(globalThis,["playbackReady",{sampleBuffer:this.sampleBuffer,informationBuffer:this.information}])}close(){super.close(),pr(this.wasm,this.sampleBuffer)}onMessage(A){super.onMessage(A);let[t,e]=A;t==="playbackTick"&&this.tick(e.id)}tick(A){for(this.stats.numberTicks++;this.id<A+this.prefill;this.id++){let t=this.id%this.sampleBuffer.length,{hasAudio:e}=this.decode(cr(this.sampleBuffer,t));e&&(this.stats.numberTicksWithAudio++,dr(this.sampleBuffer,t,{id:this.id}))}}dump(){return{type:"shared playback worker",id:this.id,prefill:this.prefill,sampleRate:this.sampleBuffer.sampleRate,stereo:this.sampleBuffer.stereo,...super.dump()}}};})();
3223
+ `});var Vx,m0=d(()=>{Vx='"use strict";(()=>{var R=Object.defineProperty;var F=(e,t)=>{for(var r in t)R(e,r,{get:t[r],enumerable:!0})};var l={};F(l,{AdditionalCaptureBlocks:()=>C,AdditionalPlaybackBlocks:()=>D,ClockJumpCheckInterval:()=>$,ClockJumpThreshold:()=>j,ConnectInterval:()=>K,ConnectTimeout:()=>Z,DefaultRefreshRate:()=>V,DefaultVideoCodec:()=>X,HealthCheckTimeout:()=>W,MainConnectionPingInterval:()=>H,MaxNumberOfDecoders:()=>_,MinDBFs:()=>k,MinTokenLifetime:()=>q,MinTokenRefreshInterval:()=>Q,PlaybackPreload:()=>L,RenderQuantumSize:()=>N,VadPreload:()=>O,WebRtcIceTimeout:()=>z,WebRtcStatsSnapshotInterval:()=>J,WebRtcTimeout:()=>G});var D=3,C=3,L=3,V=250,O=3,_=512,N=128,k=-758.596,W=1e4,$=1e3,j=1e4,H=3e3,J=1e3,z=3e3,G=1e4,Z=5e3,q=6e4,Q=5e3,K=[0,100,200,200,500],X="H264";function p(e,t,r){return e.postMessage(t,r)}function Y(e){return e.sampleRate*.02*(e.stereo?2:1)}function f(e,t){let r=Y(e),n=r*t,s=n+r;return e.samples.subarray(n,s)}function S(e,t){return{id:e.headers[t]}}function I(e,t,r){e.headers[t]=r.id}var ee;(e=>{let t;(r=>(r[r.InvalidPassword=-1]="InvalidPassword",r[r.Unknown=0]="Unknown",r[r.Unencrypted=1]="Unencrypted",r[r.Encrypted=2]="Encrypted"))(t=e.PeerCipherStatus||={})})(ee||={});var{Deno:U}=globalThis,te=typeof U?.noColor=="boolean"?U.noColor:!1,re=!te;function h(e,t){return{open:`\\x1B[${e.join(";")}m`,close:`\\x1B[${t}m`,regexp:new RegExp(`\\\\x1b\\\\[${t}m`,"g")}}function b(e,t){return re?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}function m(e){return b(e,h([0],0))}function T(e){return b(e,h([1],22))}function ne(e){return b(e,h([2],22))}var Te=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),se=new Date,d=(e=>(e[e.CRITICAL=0]="CRITICAL",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(d||{}),P={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},oe={4:ne,3:m,2:m,1:T,0:T};function ae({message:e}){return String(e)}function B(e){return JSON.stringify({timestamp:e.date.toISOString(),level:d[e.level],message:e.message,extra:e.extra})}function w(e){function t(c,i){return[Math.floor(c/i),c%i]}function r(){let c,i=e.date.valueOf()-se.valueOf();[i,c]=t(i,1e3);let[M,E]=t(i,60);return`${M.toString().padStart(4,"0")}:${E.toString().padStart(2,"0")}.${c.toString().padStart(4,"0")}`}function n(){return e.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(e.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(e.extra)}let s=P[e.level],a=e.logger.name!==void 0?`@${e.logger}`:"";return`${m(r())}${a} ${s} ${oe[e.level](String(e.message))}${n()}`}function ie(e){let t=`[${e.date.toISOString()}]`,r=`[${d[e.level]}]`,n=e.logger.name!==void 0?`[${e.logger.name}] `:"",s=P[e.level];return`${t} ${s} ${r.padEnd(7," ")} ${n}${e.message}`}function ce(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var A=class{static sparse=ae;static json=B;static pretty=w;static structured=ie;static default=ce()?w:B;constructor(){}},le=class{formatter;consoleObject;filter;constructor(e=A.default,t=4,r=console){this.filter=t,this.formatter=e,this.consoleObject=r}handle(e){let t=this.formatter(e);switch(e.level){case 1:this.consoleObject.error(t);break;case 2:this.consoleObject.warn(t);break;case 3:this.consoleObject.info(t);break;case 4:this.consoleObject.debug(t);break}}};var o=class{#e;sinks;filter;parent;get name(){return this.#e}constructor(e,t=void 0,r=[],n=void 0){this.#e=t,this.sinks=r,this.filter=e,this.parent=n}log(e,t,r=void 0){let n={date:new Date,level:e,logger:this,message:t,extra:r};this.filter<e||this.insert(n)}insert(e){if(!(this.filter<e.level)){for(let t of this.sinks)t.filter>=e.level&&t.handle(e);this.parent!==void 0&&this.parent.insert(e)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},u=new o(3,void 0,[new le]),ue=o.prototype.log.bind(u,1),fe=o.prototype.log.bind(u,2),de=o.prototype.log.bind(u,3),pe=o.prototype.log.bind(u,4),Be=o.prototype.log.bind(u);var x=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.blocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"init":this.state=new g(s.sampleBuffer,s.workerPort,sampleRate*.02);break;case"close":this.alive=!1;break;case"dump":s.result.postMessage(this.dump());break}}process(r,n,s){if(this.state===void 0||r.length<1||r[0].length<1)return this.alive;let a=this.state.fill(0,r[0][0]);return this.state.offset===this.state.length&&(this.blocks+=1,this.state.flush(),this.state.fill(a,r[0][0])),this.alive}dump(){return{type:"shared capture worklet",alive:this.alive,sampleRate,id:this.state?.id||null,offset:this.state?.offset||null,length:this.state?.length||null,blocks:this.blocks}}},y=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.silenceBlocks=0;this.voiceBlocks=0;this.totalBlocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"close":this.alive=!1;break;case"init":this.state=new v(s.workerPort,s.sampleBuffer,sampleRate*.02);break;case"dump":s.result.postMessage(this.dump());break}n==="close"&&(this.alive=!1)}process(r,n,s){if(this.state===void 0||n.length<1||n[0].length<2)return this.alive;let a=this.state.fill(0,n[0][0],n[0][1]);return a<l.RenderQuantumSize&&(this.totalBlocks+=1,this.state.next(),this.state.hasVoice?this.voiceBlocks+=1:this.silenceBlocks+=1,this.state.fill(a,n[0][0],n[0][1])),this.alive}dump(){return{type:"shared playback worklet",alive:this.alive,sampleRate,id:this.state?.id||null,offset:this.state?.offset||null,length:this.state?.length||null,hasVoice:this.state?.hasVoice??!1,silenceBlocks:this.silenceBlocks,voiceBlocks:this.voiceBlocks,totalBlocks:this.totalBlocks}}},g=class{constructor(t,r,n){this.samples=t;this.port=r;this.length=n;this.id=0,this.offset=0,this.entry=f(this.samples,0)}fill(t,r){let n=Math.min(r.length-t,this.length-this.offset);return this.entry.set(r.subarray(t,t+n),this.offset),this.offset+=n,t+n}flush(){this.id+=1,p(this.port,["captureTick",{id:this.id}]);let t=this.id%this.samples.length;this.entry=f(this.samples,t),I(this.samples,t,{id:this.id}),this.offset=0}},v=class{constructor(t,r,n){this.port=t;this.samples=r;this.length=n;this.id=-1,this.offset=0,this.entry=void 0,this.next()}get hasVoice(){return this.entry!==void 0}fill(t,r,n){let s=Math.min(l.RenderQuantumSize-t,this.length-this.offset);return this.entry!==void 0&&(r.set(this.entry.subarray(this.offset,this.offset+s),t),n.set(this.entry.subarray(this.offset+this.length,this.offset+this.length+s),t)),this.offset+=s,t+s}next(){this.id+=1;let t=this.id%this.samples.length,{id:r}=S(this.samples,t);this.entry=this.id===r?f(this.samples,t):void 0,this.offset=0,p(this.port,["playbackTick",{id:this.id}])}};registerProcessor("OdinCaptureProcessor",x);registerProcessor("OdinPlaybackProcessor",y);})();\n'});var G0={};Ox(G0,{createCaptureWorker:()=>xF,createPlaybackWorker:()=>AF});import{Strand as YA}from"@4players/odin-common";function xF(v,t,j,e,B=i.DefaultRefreshRate){return ZA.enqueue(async()=>{let[C,E]=await Z(Rx,Vx,v,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return Wx.create(v,t,j,C,E,e)})}async function AF(v,t=i.DefaultRefreshRate){if(v.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[j,e]=await Z(Rx,Vx,v,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return Ux.create(v,j,e)}var ZA,Ux,Wx,I0=d(()=>{"use strict";u();Ex();q0();m0();ZA=new YA;Ux=class v extends X{constructor(j,e,B,C){super(j,e,B);this.information=C}static async create(j,e,B){let{port1:C,port2:E}=new MessageChannel;k(e,["playbackInit",{workletPort:C}],[C]);let{informationBuffer:f,sampleBuffer:s}=await W(e,"playbackReady");return Sx(f,[1,1]),k(B.port,["init",{sampleBuffer:s,workerPort:E}],[E]),B.connect(j.destination),new v(j,B,e,f)}getActivity(j){let e=this.medias.get(p(j));if(e===void 0)return;let B=v0(this.information,e.index);return B===0?y:{isSilent:!1,rmsDBFS:B}}getJitterStats(j){}setGlobalVolume(j){Sx(this.information,j)}setVolume(j,e){let B=this.medias.get(p(j));B!==void 0&&C0(this.information,B.index,e)}_GetFreeIndex(){let j=super._GetFreeIndex();if(j!==void 0)return j;if(this.information.length>this.medias.size)return this.medias.size}},Wx=class v extends Q{constructor(j,e,B,C,E,f){super(j,e,B,C,f);this.information=E}static async create(j,e,B,C,E,f){let{port1:s,port2:a}=new MessageChannel;k(C,["captureInit",{sampleRate:j.sampleRate,workletPort:s}],[s]);let{sampleBuffer:q,informationBuffer:N}=await W(C,"captureReady");return k(E.port,["init",{workerPort:a,sampleBuffer:q}],[a]),new v(E,C,e,B,N,f)}get activity(){return{isSilent:!E0(this.information),rmsDBFS:n0(this.information)}}get speechProbability(){return f0(this.information)}setVolume(j){s0(this.information,j)}}});var zx,$0=d(()=>{zx=`"use strict";(()=>{var ke=Object.create;var XA=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var ce=Object.getOwnPropertyNames;var de=Object.getPrototypeOf,qe=Object.prototype.hasOwnProperty;var Ce=(n,A)=>()=>(A||n((A={exports:{}}).exports,A),A.exports),fe=(n,A)=>{for(var t in A)XA(n,t,{get:A[t],enumerable:!0})},Ge=(n,A,t,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of ce(A))!qe.call(n,i)&&i!==t&&XA(n,i,{get:()=>A[i],enumerable:!(e=ue(A,i))||e.enumerable});return n};var pe=(n,A,t)=>(t=n!=null?ke(de(n)):{},Ge(A||!n||!n.__esModule?XA(t,"default",{value:n,enumerable:!0}):t,n));var _j=Ce((yj,OA)=>{"use strict";var sr=(()=>{var n=globalThis.document?.currentScript?.src;return async function(A={}){var t,e=A,i=!!globalThis.window,d=!!globalThis.WorkerGlobalScope,q=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",p=[],F="./this.program";d&&(n=self.location.href);var x="",wA,O;if(i||d){try{x=new URL(".",n).href}catch{}d&&(O=j=>{var r=new XMLHttpRequest;return r.open("GET",j,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),wA=async j=>{var r=await fetch(j,{credentials:"same-origin"});if(r.ok)return r.arrayBuffer();throw new Error(r.status+" : "+r.url)}}var ar=console.log.bind(console),kA=console.error.bind(console),kr,ur=!1;function Bj(j){for(var r=0,s=j.length,l=new Uint8Array(s),o;r<s;++r)o=j.charCodeAt(r),l[r]=~o>>8&o;return l}var cr,dr,V,_,uA,Z,cA,I,qr,Cr,fr,Gr,pr=!1;function Jj(){var j=Sr.buffer;V=new Int8Array(j),uA=new Int16Array(j),e.HEAPU8=_=new Uint8Array(j),Z=new Uint16Array(j),e.HEAP32=cA=new Int32Array(j),e.HEAPU32=I=new Uint32Array(j),e.HEAPF32=qr=new Float32Array(j),Cr=new Float64Array(j),fr=new BigInt64Array(j),Gr=new BigUint64Array(j)}function bj(){if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)Rj(e.preRun.shift());mr(Er)}function Oj(){pr=!0,tA.v()}function wj(){if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)Wj(e.postRun.shift());mr(Ir)}function PA(j){e.onAbort?.(j),j="Aborted("+j+")",kA(j),ur=!0,j+=". Build with -sASSERTIONS for more info.";var r=new WebAssembly.RuntimeError(j);throw dr?.(r),r}var hr;function Pj(){return Bj(\`\\0asm\\0\\0\\0\\x8D9\\\`\\x7F\\x7F\\\`\\x7F\\0\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\0\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`||\\\`\\x7F}\\\`}}\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F~\\\`\\x7F\\x7F}\\\`\\x7F}}\\\`\\x7F\\x7F}}\\0\\\`
3224
3224
  \\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`|}\\\`|\\x7F|\\\`\\x7F\\x7F}\\0\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\` \\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\f\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F|\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F|}\\\`\\0\\x7F\\\`\\x7F\\x7F\\x7F~~\\0\\\`\\r\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F\\x7F\\x7F\\\`\\x7F\\x7F|\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\x7F\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F}}\\x7F\\x7F\\x7F\\x7F\\0\\\`~\\x7F\\x7F\\\` \\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\\`||\\x7F|\\\`|||\\\`\\x7F\\x7F\\x7F|\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\\`\\f\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`}\\x7F\\x7F\\\`|\\x7F\\x7F\\\`\\x7F\\x7F\\x7F}\\\`\\x7F}\\x7F\\0\\\`\\x7F\\x7F}\\x7F\\x7F\\x7F}\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F}}\\0yaa\\0ab\\0ac\\0ad\\0ae\\0af\\0!ag\\0ah\\0 ai\\0aj\\0\\bak\\0"al\\0am\\0an\\0ao\\0\\0ap\\0#aq\\0\\0ar\\0
3225
3225
  as\\0at\\0\\xBB\\xB9\\0\\0\\f$\\f\\x07\\0\\f\\x07\\f\\x07\\0%& \\0
3226
3226
  \\0\\x07\\v\\0'\\0\\0(\\0\\f\\0)*+\\x07\\v\\x07\\0
@@ -6399,7 +6399,7 @@ K\\xE08\\xDF\\0}\\xBC\\x8A\\x1B\\f\\xE5\\xFF\\xCF\\xE8?\\x9F\\xFFFq\\0\\x88\\xB
6399
6399
 
6400
6400
  
6401
6401
  \\x07\\0\\0 \\v\\0\\0 \\v\\0\\0\\v\\0\\0\\0\\0\\0A\\xC1\\x9D\\v!\\0\\0\\0\\0\\0\\0\\0\\0\\0\\v\\r\\0\\r\\0\\0\\0 \\0\\0\\0 \\0\\0\\0\\0A\\xFB\\x9D\\v\\f\\0A\\x87\\x9E\\v\\0\\0\\0\\0\\0\\0\\0\\0 \\f\\0\\0\\0\\0\\0\\f\\0\\0\\f\\0A\\xB5\\x9E\\v\\0A\\xC1\\x9E\\v\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0A\\xEF\\x9E\\v\\0A\\xFB\\x9E\\v\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0A\\xB2\\x9F\\v\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0A\\xE3\\x9F\\v\\0A\\xEF\\x9F\\v\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0A\\x9D\\xA0\\v\\0A\\xA9\\xA0\\v\\xB3 \\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\x000123456789ABCDEF\\0\\0X\\0NSt3__214__shared_countE\\0\\0\\0\\0\\x84\\0\\x8C\\0\\0\\0\\0\\0\\0\\0\\0P\\0\\0\\0\\0\\0NSt3__219__shared_weak_countE\\0\\0\\0(\\0\\xB8\\0\\xC8\\0N10__cxxabiv116__shim_type_infoE\\0\\0\\0\\0(\\0\\xE8\\0\\xAC\\0N10__cxxabiv117__class_type_infoE\\0\\0\\0(\\0\\0\\xAC\\0N10__cxxabiv117__pbase_type_infoE\\0\\0\\0(\\0H\\0\\f\\0N10__cxxabiv119__pointer_type_infoE\\0(\\0x\\0\\xAC\\0N10__cxxabiv120__function_type_infoE\\0\\0\\0\\0(\\0\\xAC\\0\\f\\0N10__cxxabiv129__pointer_to_member_type_infoE\\0\\0\\0\\0\\0\\0\\0\\xF8\\0\\\`\\0\\0\\0a\\0\\0\\0b\\0\\0\\0c\\0\\0\\0d\\0\\0\\0(\\0\\0\\xAC\\0N10__cxxabiv123__fundamental_type_infoE\\0\\xE4\\x004\\0v\\0Dn\\0\\0\\0\\0\\xE4\\0D\\0b\\0\\0\\0\\xE4\\0P\\0c\\0\\0\\0\\xE4\\0\\\\\\0h\\0\\0\\0\\xE4\\0h\\0a\\0\\0\\0\\xE4\\0t\\0s\\0\\0\\0\\xE4\\0\\x80\\0t\\0\\0\\0\\xE4\\0\\x8C\\0i\\0\\0\\0\\xE4\\0\\x98\\0j\\0\\0\\0\\xE4\\0\\xA4\\0l\\0\\0\\0\\xE4\\0\\xB0\\0m\\0\\0\\0\\xE4\\0\\xBC\\0x\\0\\0\\0\\xE4\\0\\xC8\\0y\\0\\0\\0\\xE4\\0\\xD4\\0f\\0\\0\\0\\xE0\\0\\xE8\\0\\0\\0\\0\\0\\xCC\\0Pf\\0\\0\\xE4\\0\\xF4\\0d\\0\\0\\0\\0\\0\\0\\0\\xDC\\0\\\`\\0\\0\\0e\\0\\0\\0b\\0\\0\\0c\\0\\0\\0f\\0\\0\\0g\\0\\0\\0h\\0\\0\\0i\\0\\0\\0\\0\\0\\0\\0H\\0\\\`\\0\\0\\0j\\0\\0\\0b\\0\\0\\0c\\0\\0\\0f\\0\\0\\0k\\0\\0\\0l\\0\\0\\0m\\0\\0\\0(\\0T\\0\\xDC\\0N10__cxxabiv120__si_class_type_infoE\\0\\0\\0\\0\\0\\0\\0\\0\\xA4\\0\\\`\\0\\0\\0n\\0\\0\\0b\\0\\0\\0c\\0\\0\\0f\\0\\0\\0o\\0\\0\\0p\\0\\0\\0q\\0\\0\\0(\\0\\xB0\\0\\xDC\\0N10__cxxabiv121__vmi_class_type_infoE\\0\\0\\0\\0\\0\\0\\0<\\0\\\`\\0\\0\\0r\\0\\0\\0b\\0\\0\\0c\\0\\0\\0s\\0\\0\\0\\0\\0\\0\\0<\\0F\\0\\0\\0t\\0\\0\\0u\\0\\0\\0\\0\\0\\0St9exception\\0\\0\\0\\0(\\0,\\0\\b\\0St9bad_alloc\\0\\0\\0\\0(\\0H\\0 \\0St20bad_array_new_length\\0\\0\\0\\0\\0\\0\\0\\0x\\0H\\0\\0\\0v\\0\\0\\0w\\0\\0\\0(\\0\\x84\\0\\b\\0St11logic_error\\0\\0\\0\\0\\0\\xA8\\0H\\0\\0\\0x\\0\\0\\0w\\0\\0\\0(\\0\\xB4\\0x\\0St12length_error\\0\\0\\0\\0\\0\\0\\xD0\\0St9type_info\\0A\\xE1\\xA9\\v\\b \\0\\0\\0\\0\\0\\0\\0A\\xF4\\xA9\\vX\\0A\\x8C\\xAA\\v\\vY\\0\\0\\0Z\\0\\0\\0\\0A\\xA4\\xAA\\v\\0A\\xB4\\xAA\\v\\b\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\0A\\xF8\\xAA\\v \\xE8\\0\\0\\0\\0\\0\\0A\\x8C\\xAB\\v[\\0A\\xA4\\xAB\\vY\\0\\0\\0\\\\\\0\\0\\0\\0\\0\\0A\\xBC\\xAB\\v\\0A\\xCC\\xAB\\v\\xFF\\xFF\\xFF\\xFF
6402
- \\0A\\x90\\xAC\\v\\x07\\x80\\0\`)}function In(j){return j}async function Mj(j){return j}async function Tj(j,r){try{var s=await Mj(j),l=await WebAssembly.instantiate(s,r);return l}catch(o){kA(\`failed to asynchronously prepare wasm: \${o}\`),PA(o)}}async function Uj(j,r,s){return Tj(r,s)}function Vj(){var j={a:le};return j}async function Sj(){function j(a,k){return tA=a.exports,ie(tA),Jj(),tA}function r(a){return j(a.instance)}var s=Vj();if(e.instantiateWasm)return new Promise((a,k)=>{e.instantiateWasm(s,(u,c)=>{a(j(u,c))})});hr??=Pj();var l=await Uj(kr,hr,s),o=r(l);return o}class En{name="ExitStatus";constructor(r){this.message=\`Program terminated with exit(\${r})\`,this.status=r}}var mr=j=>{for(;j.length>0;)j.shift()(e)},Ir=[],Wj=j=>Ir.push(j),Er=[],Rj=j=>Er.push(j),zj=!0;class Xj{constructor(r){this.excPtr=r,this.ptr=r-24}set_type(r){I[this.ptr+4>>2]=r}get_type(){return I[this.ptr+4>>2]}set_destructor(r){I[this.ptr+8>>2]=r}get_destructor(){return I[this.ptr+8>>2]}set_caught(r){r=r?1:0,V[this.ptr+12]=r}get_caught(){return V[this.ptr+12]!=0}set_rethrown(r){r=r?1:0,V[this.ptr+13]=r}get_rethrown(){return V[this.ptr+13]!=0}init(r,s){this.set_adjusted_ptr(0),this.set_type(r),this.set_destructor(s)}set_adjusted_ptr(r){I[this.ptr+16>>2]=r}get_adjusted_ptr(){return I[this.ptr+16>>2]}}var $r=0,Qj=0,Yj=(j,r,s)=>{var l=new Xj(j);throw l.init(r,s),$r=j,Qj++,$r},Zj=()=>PA(""),v=j=>{for(var r="";;){var s=_[j++];if(!s)return r;r+=String.fromCharCode(s)}},z={},X={},dA={},AA=class extends Error{constructor(r){super(r),this.name="BindingError"}},G=j=>{throw new AA(j)};function At(j,r,s={}){var l=r.name;if(j||G(\`type "\${l}" must have a positive integer typeid pointer\`),X.hasOwnProperty(j)){if(s.ignoreDuplicateRegistrations)return;G(\`Cannot register type '\${l}' twice\`)}if(X[j]=r,delete dA[j],z.hasOwnProperty(j)){var o=z[j];delete z[j],o.forEach(a=>a())}}function K(j,r,s={}){return At(j,r,s)}var Fr=(j,r,s)=>{switch(r){case 1:return s?l=>V[l]:l=>_[l];case 2:return s?l=>uA[l>>1]:l=>Z[l>>1];case 4:return s?l=>cA[l>>2]:l=>I[l>>2];case 8:return s?l=>fr[l>>3]:l=>Gr[l>>3];default:throw new TypeError(\`invalid integer width (\${r}): \${j}\`)}},rt=(j,r,s,l,o)=>{r=v(r);let a=l===0n,k=u=>u;if(a){let u=s*8;k=c=>BigInt.asUintN(u,c),o=k(o)}K(j,{name:r,fromWireType:k,toWireType:(u,c)=>(typeof c=="number"&&(c=BigInt(c)),c),readValueFromPointer:Fr(r,s,!a),destructorFunction:null})},jt=(j,r,s,l)=>{r=v(r),K(j,{name:r,fromWireType:function(o){return!!o},toWireType:function(o,a){return a?s:l},readValueFromPointer:function(o){return this.fromWireType(_[o])},destructorFunction:null})},tt=j=>({count:j.count,deleteScheduled:j.deleteScheduled,preservePointerOnDelete:j.preservePointerOnDelete,ptr:j.ptr,ptrType:j.ptrType,smartPtr:j.smartPtr,smartPtrType:j.smartPtrType}),MA=j=>{function r(s){return s.$$.ptrType.registeredClass.name}G(r(j)+" instance already deleted")},TA=!1,vr=j=>{},et=j=>{j.smartPtr?j.smartPtrType.rawDestructor(j.smartPtr):j.ptrType.registeredClass.rawDestructor(j.ptr)},Lr=j=>{j.count.value-=1;var r=j.count.value===0;r&&et(j)},rA=j=>globalThis.FinalizationRegistry?(TA=new FinalizationRegistry(r=>{Lr(r.$$)}),rA=r=>{var s=r.$$,l=!!s.smartPtr;if(l){var o={$$:s};TA.register(r,o,r)}return r},vr=r=>TA.unregister(r),rA(j)):(rA=r=>r,j),qA=[],nt=()=>{for(;qA.length;){var j=qA.pop();j.$$.deleteScheduled=!1,j.delete()}},gr,st=()=>{let j=CA.prototype;Object.assign(j,{isAliasOf(s){if(!(this instanceof CA)||!(s instanceof CA))return!1;var l=this.$$.ptrType.registeredClass,o=this.$$.ptr;s.$$=s.$$;for(var a=s.$$.ptrType.registeredClass,k=s.$$.ptr;l.baseClass;)o=l.upcast(o),l=l.baseClass;for(;a.baseClass;)k=a.upcast(k),a=a.baseClass;return l===a&&o===k},clone(){if(this.$$.ptr||MA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var s=rA(Object.create(Object.getPrototypeOf(this),{$$:{value:tt(this.$$)}}));return s.$$.count.value+=1,s.$$.deleteScheduled=!1,s},delete(){this.$$.ptr||MA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),vr(this),Lr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||MA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),qA.push(this),qA.length===1&&gr&&gr(nt),this.$$.deleteScheduled=!0,this}});let r=Symbol.dispose;r&&(j[r]=j.delete)};function CA(){}var Hr=(j,r)=>Object.defineProperty(r,"name",{value:j}),yr={},_r=(j,r,s)=>{if(j[r].overloadTable===void 0){var l=j[r];j[r]=function(...o){return j[r].overloadTable.hasOwnProperty(o.length)||G(\`Function '\${s}' called with an invalid number of arguments (\${o.length}) - expects one of (\${j[r].overloadTable})!\`),j[r].overloadTable[o.length].apply(this,o)},j[r].overloadTable=[],j[r].overloadTable[l.argCount]=l}},Dr=(j,r,s)=>{e.hasOwnProperty(j)?((s===void 0||e[j].overloadTable!==void 0&&e[j].overloadTable[s]!==void 0)&&G(\`Cannot register public name '\${j}' twice\`),_r(e,j,j),e[j].overloadTable.hasOwnProperty(s)&&G(\`Cannot register multiple overloads of a function with the same number of arguments (\${s})!\`),e[j].overloadTable[s]=r):(e[j]=r,e[j].argCount=s)},it=48,lt=57,ot=j=>{j=j.replace(/[^a-zA-Z0-9_]/g,"$");var r=j.charCodeAt(0);return r>=it&&r<=lt?\`_\${j}\`:j};function at(j,r,s,l,o,a,k,u){this.name=j,this.constructor=r,this.instancePrototype=s,this.rawDestructor=l,this.baseClass=o,this.getActualType=a,this.upcast=k,this.downcast=u,this.pureVirtualFunctions=[]}var fA=(j,r,s)=>{for(;r!==s;)r.upcast||G(\`Expected null or instance of \${s.name}, got an instance of \${r.name}\`),j=r.upcast(j),r=r.baseClass;return j},UA=j=>{if(j===null)return"null";var r=typeof j;return r==="object"||r==="array"||r==="function"?j.toString():""+j};function kt(j,r){if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;r.$$||G(\`Cannot pass "\${UA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`);var s=r.$$.ptrType.registeredClass,l=fA(r.$$.ptr,s,this.registeredClass);return l}function ut(j,r){var s;if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),this.isSmartPointer?(s=this.rawConstructor(),j!==null&&j.push(this.rawDestructor,s),s):0;(!r||!r.$$)&&G(\`Cannot pass "\${UA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),!this.isConst&&r.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name} to parameter type \${this.name}\`);var l=r.$$.ptrType.registeredClass;if(s=fA(r.$$.ptr,l,this.registeredClass),this.isSmartPointer)switch(r.$$.smartPtr===void 0&&G("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:r.$$.smartPtrType===this?s=r.$$.smartPtr:G(\`Cannot convert argument of type \${r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name} to parameter type \${this.name}\`);break;case 1:s=r.$$.smartPtr;break;case 2:if(r.$$.smartPtrType===this)s=r.$$.smartPtr;else{var o=r.clone();s=this.rawShare(s,WA.toHandle(()=>o.delete())),j!==null&&j.push(this.rawDestructor,s)}break;default:G("Unsupported sharing policy")}return s}function ct(j,r){if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;r.$$||G(\`Cannot pass "\${UA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),r.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${r.$$.ptrType.name} to parameter type \${this.name}\`);var s=r.$$.ptrType.registeredClass,l=fA(r.$$.ptr,s,this.registeredClass);return l}function GA(j){return this.fromWireType(I[j>>2])}var xr=(j,r,s)=>{if(r===s)return j;if(s.baseClass===void 0)return null;var l=xr(j,r,s.baseClass);return l===null?null:s.downcast(l)},dt={},qt=(j,r)=>{for(r===void 0&&G("ptr should not be undefined");j.baseClass;)r=j.upcast(r),j=j.baseClass;return r},Ct=(j,r)=>(r=qt(j,r),dt[r]),ft=class extends Error{constructor(r){super(r),this.name="InternalError"}},pA=j=>{throw new ft(j)},hA=(j,r)=>{(!r.ptrType||!r.ptr)&&pA("makeClassHandle requires ptr and ptrType");var s=!!r.smartPtrType,l=!!r.smartPtr;return s!==l&&pA("Both smartPtrType and smartPtr must be specified"),r.count={value:1},rA(Object.create(j,{$$:{value:r,writable:!0}}))};function Gt(j){var r=this.getPointee(j);if(!r)return this.destructor(j),null;var s=Ct(this.registeredClass,r);if(s!==void 0){if(s.$$.count.value===0)return s.$$.ptr=r,s.$$.smartPtr=j,s.clone();var l=s.clone();return this.destructor(j),l}function o(){return this.isSmartPointer?hA(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:r,smartPtrType:this,smartPtr:j}):hA(this.registeredClass.instancePrototype,{ptrType:this,ptr:j})}var a=this.registeredClass.getActualType(r),k=yr[a];if(!k)return o.call(this);var u;this.isConst?u=k.constPointerType:u=k.pointerType;var c=xr(r,this.registeredClass,u.registeredClass);return c===null?o.call(this):this.isSmartPointer?hA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c,smartPtrType:this,smartPtr:j}):hA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c})}var pt=()=>{Object.assign(mA.prototype,{getPointee(j){return this.rawGetPointee&&(j=this.rawGetPointee(j)),j},destructor(j){this.rawDestructor?.(j)},readValueFromPointer:GA,fromWireType:Gt})};function mA(j,r,s,l,o,a,k,u,c,C,f){this.name=j,this.registeredClass=r,this.isReference=s,this.isConst=l,this.isSmartPointer=o,this.pointeeType=a,this.sharingPolicy=k,this.rawGetPointee=u,this.rawConstructor=c,this.rawShare=C,this.rawDestructor=f,!o&&r.baseClass===void 0?l?(this.toWireType=kt,this.destructorFunction=null):(this.toWireType=ct,this.destructorFunction=null):this.toWireType=ut}var Kr=(j,r,s)=>{e.hasOwnProperty(j)||pA("Replacing nonexistent public symbol"),e[j].overloadTable!==void 0&&s!==void 0?e[j].overloadTable[s]=r:(e[j]=r,e[j].argCount=s)},Nr=[],ht=j=>{var r=Nr[j];return r||(Nr[j]=r=Wr.get(j)),r},N=(j,r,s=!1)=>{j=v(j);function l(){var a=ht(r);return a}var o=l();return typeof o!="function"&&G(\`unknown function pointer with signature \${j}: \${r}\`),o};class mt extends Error{}var It=j=>{var r=Vr(j),s=v(r);return B(r),s},Q=(j,r)=>{var s=[],l={};function o(a){if(!l[a]&&!X[a]){if(dA[a]){dA[a].forEach(o);return}s.push(a),l[a]=!0}}throw r.forEach(o),new mt(\`\${j}: \`+s.map(It).join([", "]))},w=(j,r,s)=>{j.forEach(u=>dA[u]=r);function l(u){var c=s(u);c.length!==j.length&&pA("Mismatched type converter count");for(var C=0;C<j.length;++C)K(j[C],c[C])}var o=new Array(r.length),a=[],k=0;for(let[u,c]of r.entries())X.hasOwnProperty(c)?o[u]=X[c]:(a.push(c),z.hasOwnProperty(c)||(z[c]=[]),z[c].push(()=>{o[u]=X[c],++k,k===a.length&&l(o)}));a.length===0&&l(o)},Et=(j,r,s,l,o,a,k,u,c,C,f,m,E)=>{f=v(f),a=N(o,a),u&&=N(k,u),C&&=N(c,C),E=N(m,E);var h=ot(f);Dr(h,function(){Q(\`Cannot construct \${f} due to unbound types\`,[l])}),w([j,r,s],l?[l]:[],$=>{$=$[0];var H,J;l?(H=$.registeredClass,J=H.instancePrototype):J=CA.prototype;var y=Hr(f,function(...zA){if(Object.getPrototypeOf(this)!==eA)throw new AA(\`Use 'new' to construct \${f}\`);if(g.constructor_body===void 0)throw new AA(\`\${f} has no accessible constructor\`);var Xr=g.constructor_body[zA.length];if(Xr===void 0)throw new AA(\`Tried to invoke ctor of \${f} with invalid number of parameters (\${zA.length}) - expected (\${Object.keys(g.constructor_body).toString()}) parameters instead!\`);return Xr.apply(this,zA)}),eA=Object.create(J,{constructor:{value:y}});y.prototype=eA;var g=new at(f,y,eA,E,H,a,u,C);g.baseClass&&(g.baseClass.__derivedClasses??=[],g.baseClass.__derivedClasses.push(g));var ae=new mA(f,g,!0,!1,!1),Rr=new mA(f+"*",g,!1,!1,!1),zr=new mA(f+" const*",g,!1,!0,!1);return yr[j]={pointerType:Rr,constPointerType:zr},Kr(h,y),[ae,Rr,zr]})},VA=(j,r)=>{for(var s=[],l=0;l<j;l++)s.push(I[r+l*4>>2]);return s},Br=j=>{for(;j.length;){var r=j.pop(),s=j.pop();s(r)}};function Jr(j){for(var r=1;r<j.length;++r)if(j[r]!==null&&j[r].destructorFunction===void 0)return!0;return!1}function $t(j,r,s,l){var o=Jr(j),a=j.length-2,k=[],u=["fn"];r&&u.push("thisWired");for(var c=0;c<a;++c)k.push(\`arg\${c}\`),u.push(\`arg\${c}Wired\`);k=k.join(","),u=u.join(",");var C=\`return function (\${k}) {
6402
+ \\0A\\x90\\xAC\\v\\x07\\x80\\0\`)}function $n(j){return j}async function Mj(j){return j}async function Tj(j,r){try{var s=await Mj(j),l=await WebAssembly.instantiate(s,r);return l}catch(o){kA(\`failed to asynchronously prepare wasm: \${o}\`),PA(o)}}async function Uj(j,r,s){return Tj(r,s)}function Vj(){var j={a:le};return j}async function Sj(){function j(a,k){return tA=a.exports,ie(tA),Jj(),tA}function r(a){return j(a.instance)}var s=Vj();if(e.instantiateWasm)return new Promise((a,k)=>{e.instantiateWasm(s,(u,c)=>{a(j(u,c))})});hr??=Pj();var l=await Uj(kr,hr,s),o=r(l);return o}class Fn{name="ExitStatus";constructor(r){this.message=\`Program terminated with exit(\${r})\`,this.status=r}}var mr=j=>{for(;j.length>0;)j.shift()(e)},Ir=[],Wj=j=>Ir.push(j),Er=[],Rj=j=>Er.push(j),zj=!0;class Xj{constructor(r){this.excPtr=r,this.ptr=r-24}set_type(r){I[this.ptr+4>>2]=r}get_type(){return I[this.ptr+4>>2]}set_destructor(r){I[this.ptr+8>>2]=r}get_destructor(){return I[this.ptr+8>>2]}set_caught(r){r=r?1:0,V[this.ptr+12]=r}get_caught(){return V[this.ptr+12]!=0}set_rethrown(r){r=r?1:0,V[this.ptr+13]=r}get_rethrown(){return V[this.ptr+13]!=0}init(r,s){this.set_adjusted_ptr(0),this.set_type(r),this.set_destructor(s)}set_adjusted_ptr(r){I[this.ptr+16>>2]=r}get_adjusted_ptr(){return I[this.ptr+16>>2]}}var $r=0,Qj=0,Yj=(j,r,s)=>{var l=new Xj(j);throw l.init(r,s),$r=j,Qj++,$r},Zj=()=>PA(""),v=j=>{for(var r="";;){var s=_[j++];if(!s)return r;r+=String.fromCharCode(s)}},z={},X={},dA={},AA=class extends Error{constructor(r){super(r),this.name="BindingError"}},G=j=>{throw new AA(j)};function At(j,r,s={}){var l=r.name;if(j||G(\`type "\${l}" must have a positive integer typeid pointer\`),X.hasOwnProperty(j)){if(s.ignoreDuplicateRegistrations)return;G(\`Cannot register type '\${l}' twice\`)}if(X[j]=r,delete dA[j],z.hasOwnProperty(j)){var o=z[j];delete z[j],o.forEach(a=>a())}}function K(j,r,s={}){return At(j,r,s)}var Fr=(j,r,s)=>{switch(r){case 1:return s?l=>V[l]:l=>_[l];case 2:return s?l=>uA[l>>1]:l=>Z[l>>1];case 4:return s?l=>cA[l>>2]:l=>I[l>>2];case 8:return s?l=>fr[l>>3]:l=>Gr[l>>3];default:throw new TypeError(\`invalid integer width (\${r}): \${j}\`)}},rt=(j,r,s,l,o)=>{r=v(r);let a=l===0n,k=u=>u;if(a){let u=s*8;k=c=>BigInt.asUintN(u,c),o=k(o)}K(j,{name:r,fromWireType:k,toWireType:(u,c)=>(typeof c=="number"&&(c=BigInt(c)),c),readValueFromPointer:Fr(r,s,!a),destructorFunction:null})},jt=(j,r,s,l)=>{r=v(r),K(j,{name:r,fromWireType:function(o){return!!o},toWireType:function(o,a){return a?s:l},readValueFromPointer:function(o){return this.fromWireType(_[o])},destructorFunction:null})},tt=j=>({count:j.count,deleteScheduled:j.deleteScheduled,preservePointerOnDelete:j.preservePointerOnDelete,ptr:j.ptr,ptrType:j.ptrType,smartPtr:j.smartPtr,smartPtrType:j.smartPtrType}),MA=j=>{function r(s){return s.$$.ptrType.registeredClass.name}G(r(j)+" instance already deleted")},TA=!1,vr=j=>{},et=j=>{j.smartPtr?j.smartPtrType.rawDestructor(j.smartPtr):j.ptrType.registeredClass.rawDestructor(j.ptr)},Lr=j=>{j.count.value-=1;var r=j.count.value===0;r&&et(j)},rA=j=>globalThis.FinalizationRegistry?(TA=new FinalizationRegistry(r=>{Lr(r.$$)}),rA=r=>{var s=r.$$,l=!!s.smartPtr;if(l){var o={$$:s};TA.register(r,o,r)}return r},vr=r=>TA.unregister(r),rA(j)):(rA=r=>r,j),qA=[],nt=()=>{for(;qA.length;){var j=qA.pop();j.$$.deleteScheduled=!1,j.delete()}},gr,st=()=>{let j=CA.prototype;Object.assign(j,{isAliasOf(s){if(!(this instanceof CA)||!(s instanceof CA))return!1;var l=this.$$.ptrType.registeredClass,o=this.$$.ptr;s.$$=s.$$;for(var a=s.$$.ptrType.registeredClass,k=s.$$.ptr;l.baseClass;)o=l.upcast(o),l=l.baseClass;for(;a.baseClass;)k=a.upcast(k),a=a.baseClass;return l===a&&o===k},clone(){if(this.$$.ptr||MA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var s=rA(Object.create(Object.getPrototypeOf(this),{$$:{value:tt(this.$$)}}));return s.$$.count.value+=1,s.$$.deleteScheduled=!1,s},delete(){this.$$.ptr||MA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),vr(this),Lr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||MA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),qA.push(this),qA.length===1&&gr&&gr(nt),this.$$.deleteScheduled=!0,this}});let r=Symbol.dispose;r&&(j[r]=j.delete)};function CA(){}var Hr=(j,r)=>Object.defineProperty(r,"name",{value:j}),yr={},_r=(j,r,s)=>{if(j[r].overloadTable===void 0){var l=j[r];j[r]=function(...o){return j[r].overloadTable.hasOwnProperty(o.length)||G(\`Function '\${s}' called with an invalid number of arguments (\${o.length}) - expects one of (\${j[r].overloadTable})!\`),j[r].overloadTable[o.length].apply(this,o)},j[r].overloadTable=[],j[r].overloadTable[l.argCount]=l}},Dr=(j,r,s)=>{e.hasOwnProperty(j)?((s===void 0||e[j].overloadTable!==void 0&&e[j].overloadTable[s]!==void 0)&&G(\`Cannot register public name '\${j}' twice\`),_r(e,j,j),e[j].overloadTable.hasOwnProperty(s)&&G(\`Cannot register multiple overloads of a function with the same number of arguments (\${s})!\`),e[j].overloadTable[s]=r):(e[j]=r,e[j].argCount=s)},it=48,lt=57,ot=j=>{j=j.replace(/[^a-zA-Z0-9_]/g,"$");var r=j.charCodeAt(0);return r>=it&&r<=lt?\`_\${j}\`:j};function at(j,r,s,l,o,a,k,u){this.name=j,this.constructor=r,this.instancePrototype=s,this.rawDestructor=l,this.baseClass=o,this.getActualType=a,this.upcast=k,this.downcast=u,this.pureVirtualFunctions=[]}var fA=(j,r,s)=>{for(;r!==s;)r.upcast||G(\`Expected null or instance of \${s.name}, got an instance of \${r.name}\`),j=r.upcast(j),r=r.baseClass;return j},UA=j=>{if(j===null)return"null";var r=typeof j;return r==="object"||r==="array"||r==="function"?j.toString():""+j};function kt(j,r){if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;r.$$||G(\`Cannot pass "\${UA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`);var s=r.$$.ptrType.registeredClass,l=fA(r.$$.ptr,s,this.registeredClass);return l}function ut(j,r){var s;if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),this.isSmartPointer?(s=this.rawConstructor(),j!==null&&j.push(this.rawDestructor,s),s):0;(!r||!r.$$)&&G(\`Cannot pass "\${UA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),!this.isConst&&r.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name} to parameter type \${this.name}\`);var l=r.$$.ptrType.registeredClass;if(s=fA(r.$$.ptr,l,this.registeredClass),this.isSmartPointer)switch(r.$$.smartPtr===void 0&&G("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:r.$$.smartPtrType===this?s=r.$$.smartPtr:G(\`Cannot convert argument of type \${r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name} to parameter type \${this.name}\`);break;case 1:s=r.$$.smartPtr;break;case 2:if(r.$$.smartPtrType===this)s=r.$$.smartPtr;else{var o=r.clone();s=this.rawShare(s,WA.toHandle(()=>o.delete())),j!==null&&j.push(this.rawDestructor,s)}break;default:G("Unsupported sharing policy")}return s}function ct(j,r){if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;r.$$||G(\`Cannot pass "\${UA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),r.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${r.$$.ptrType.name} to parameter type \${this.name}\`);var s=r.$$.ptrType.registeredClass,l=fA(r.$$.ptr,s,this.registeredClass);return l}function GA(j){return this.fromWireType(I[j>>2])}var xr=(j,r,s)=>{if(r===s)return j;if(s.baseClass===void 0)return null;var l=xr(j,r,s.baseClass);return l===null?null:s.downcast(l)},dt={},qt=(j,r)=>{for(r===void 0&&G("ptr should not be undefined");j.baseClass;)r=j.upcast(r),j=j.baseClass;return r},Ct=(j,r)=>(r=qt(j,r),dt[r]),ft=class extends Error{constructor(r){super(r),this.name="InternalError"}},pA=j=>{throw new ft(j)},hA=(j,r)=>{(!r.ptrType||!r.ptr)&&pA("makeClassHandle requires ptr and ptrType");var s=!!r.smartPtrType,l=!!r.smartPtr;return s!==l&&pA("Both smartPtrType and smartPtr must be specified"),r.count={value:1},rA(Object.create(j,{$$:{value:r,writable:!0}}))};function Gt(j){var r=this.getPointee(j);if(!r)return this.destructor(j),null;var s=Ct(this.registeredClass,r);if(s!==void 0){if(s.$$.count.value===0)return s.$$.ptr=r,s.$$.smartPtr=j,s.clone();var l=s.clone();return this.destructor(j),l}function o(){return this.isSmartPointer?hA(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:r,smartPtrType:this,smartPtr:j}):hA(this.registeredClass.instancePrototype,{ptrType:this,ptr:j})}var a=this.registeredClass.getActualType(r),k=yr[a];if(!k)return o.call(this);var u;this.isConst?u=k.constPointerType:u=k.pointerType;var c=xr(r,this.registeredClass,u.registeredClass);return c===null?o.call(this):this.isSmartPointer?hA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c,smartPtrType:this,smartPtr:j}):hA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c})}var pt=()=>{Object.assign(mA.prototype,{getPointee(j){return this.rawGetPointee&&(j=this.rawGetPointee(j)),j},destructor(j){this.rawDestructor?.(j)},readValueFromPointer:GA,fromWireType:Gt})};function mA(j,r,s,l,o,a,k,u,c,C,f){this.name=j,this.registeredClass=r,this.isReference=s,this.isConst=l,this.isSmartPointer=o,this.pointeeType=a,this.sharingPolicy=k,this.rawGetPointee=u,this.rawConstructor=c,this.rawShare=C,this.rawDestructor=f,!o&&r.baseClass===void 0?l?(this.toWireType=kt,this.destructorFunction=null):(this.toWireType=ct,this.destructorFunction=null):this.toWireType=ut}var Kr=(j,r,s)=>{e.hasOwnProperty(j)||pA("Replacing nonexistent public symbol"),e[j].overloadTable!==void 0&&s!==void 0?e[j].overloadTable[s]=r:(e[j]=r,e[j].argCount=s)},Nr=[],ht=j=>{var r=Nr[j];return r||(Nr[j]=r=Wr.get(j)),r},N=(j,r,s=!1)=>{j=v(j);function l(){var a=ht(r);return a}var o=l();return typeof o!="function"&&G(\`unknown function pointer with signature \${j}: \${r}\`),o};class mt extends Error{}var It=j=>{var r=Vr(j),s=v(r);return B(r),s},Q=(j,r)=>{var s=[],l={};function o(a){if(!l[a]&&!X[a]){if(dA[a]){dA[a].forEach(o);return}s.push(a),l[a]=!0}}throw r.forEach(o),new mt(\`\${j}: \`+s.map(It).join([", "]))},w=(j,r,s)=>{j.forEach(u=>dA[u]=r);function l(u){var c=s(u);c.length!==j.length&&pA("Mismatched type converter count");for(var C=0;C<j.length;++C)K(j[C],c[C])}var o=new Array(r.length),a=[],k=0;for(let[u,c]of r.entries())X.hasOwnProperty(c)?o[u]=X[c]:(a.push(c),z.hasOwnProperty(c)||(z[c]=[]),z[c].push(()=>{o[u]=X[c],++k,k===a.length&&l(o)}));a.length===0&&l(o)},Et=(j,r,s,l,o,a,k,u,c,C,f,m,E)=>{f=v(f),a=N(o,a),u&&=N(k,u),C&&=N(c,C),E=N(m,E);var h=ot(f);Dr(h,function(){Q(\`Cannot construct \${f} due to unbound types\`,[l])}),w([j,r,s],l?[l]:[],$=>{$=$[0];var H,J;l?(H=$.registeredClass,J=H.instancePrototype):J=CA.prototype;var y=Hr(f,function(...zA){if(Object.getPrototypeOf(this)!==eA)throw new AA(\`Use 'new' to construct \${f}\`);if(g.constructor_body===void 0)throw new AA(\`\${f} has no accessible constructor\`);var Xr=g.constructor_body[zA.length];if(Xr===void 0)throw new AA(\`Tried to invoke ctor of \${f} with invalid number of parameters (\${zA.length}) - expected (\${Object.keys(g.constructor_body).toString()}) parameters instead!\`);return Xr.apply(this,zA)}),eA=Object.create(J,{constructor:{value:y}});y.prototype=eA;var g=new at(f,y,eA,E,H,a,u,C);g.baseClass&&(g.baseClass.__derivedClasses??=[],g.baseClass.__derivedClasses.push(g));var ae=new mA(f,g,!0,!1,!1),Rr=new mA(f+"*",g,!1,!1,!1),zr=new mA(f+" const*",g,!1,!0,!1);return yr[j]={pointerType:Rr,constPointerType:zr},Kr(h,y),[ae,Rr,zr]})},VA=(j,r)=>{for(var s=[],l=0;l<j;l++)s.push(I[r+l*4>>2]);return s},Br=j=>{for(;j.length;){var r=j.pop(),s=j.pop();s(r)}};function Jr(j){for(var r=1;r<j.length;++r)if(j[r]!==null&&j[r].destructorFunction===void 0)return!0;return!1}function $t(j,r,s,l){var o=Jr(j),a=j.length-2,k=[],u=["fn"];r&&u.push("thisWired");for(var c=0;c<a;++c)k.push(\`arg\${c}\`),u.push(\`arg\${c}Wired\`);k=k.join(","),u=u.join(",");var C=\`return function (\${k}) {
6403
6403
  \`;o&&(C+=\`var destructors = [];
6404
6404
  \`);var f=o?"destructors":"null",m=["humanName","throwBindingError","invoker","fn","runDestructors","fromRetWire","toClassParamWire"];r&&(C+=\`var thisWired = toClassParamWire(\${f}, this);
6405
6405
  \`);for(var c=0;c<a;++c){var E=\`toArg\${c}Wire\`;C+=\`var arg\${c}Wired = \${E}(\${f}, arg\${c});
@@ -6409,5 +6409,5 @@ K\\xE08\\xDF\\0}\\xBC\\x8A\\x1B\\f\\xE5\\xFF\\xCF\\xE8?\\x9F\\xFFFq\\0\\x88\\xB
6409
6409
  \`,m.push(\`\${h}_dtor\`))}return s&&(C+=\`var ret = fromRetWire(rv);
6410
6410
  return ret;
6411
6411
  \`),C+=\`}
6412
- \`,new Function(m,C)}function SA(j,r,s,l,o,a){var k=r.length;k<2&&G("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var u=r[1]!==null&&s!==null,c=Jr(r),C=!r[0].isVoid,f=r[0],m=r[1],E=[j,G,l,o,Br,f.fromWireType.bind(f),m?.toWireType.bind(m)],h=2;h<k;++h){var $=r[h];E.push($.toWireType.bind($))}if(!c)for(var h=u?1:2;h<r.length;++h)r[h].destructorFunction!==null&&E.push(r[h].destructorFunction);var J=$t(r,u,C,a)(...E);return Hr(j,J)}var Ft=(j,r,s,l,o,a)=>{var k=VA(r,s);o=N(l,o),w([],[j],u=>{u=u[0];var c=\`constructor \${u.name}\`;if(u.registeredClass.constructor_body===void 0&&(u.registeredClass.constructor_body=[]),u.registeredClass.constructor_body[r-1]!==void 0)throw new AA(\`Cannot register multiple constructors with identical number of parameters (\${r-1}) for class '\${u.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!\`);return u.registeredClass.constructor_body[r-1]=()=>{Q(\`Cannot construct \${u.name} due to unbound types\`,k)},w([],k,C=>(C.splice(1,0,null),u.registeredClass.constructor_body[r-1]=SA(c,C,null,o,a),[])),[]})},br=j=>{j=j.trim();let r=j.indexOf("(");return r===-1?j:j.slice(0,r)},vt=(j,r,s,l,o,a,k,u,c,C)=>{var f=VA(s,l);r=v(r),r=br(r),a=N(o,a,c),w([],[j],m=>{m=m[0];var E=\`\${m.name}.\${r}\`;r.startsWith("@@")&&(r=Symbol[r.substring(2)]),u&&m.registeredClass.pureVirtualFunctions.push(r);function h(){Q(\`Cannot call \${E} due to unbound types\`,f)}var $=m.registeredClass.instancePrototype,H=$[r];return H===void 0||H.overloadTable===void 0&&H.className!==m.name&&H.argCount===s-2?(h.argCount=s-2,h.className=m.name,$[r]=h):(_r($,r,E),$[r].overloadTable[s-2]=h),w([],f,J=>{var y=SA(E,J,m,a,k,c);return $[r].overloadTable===void 0?(y.argCount=s-2,$[r]=y):$[r].overloadTable[s-2]=y,[]}),[]})},Or=(j,r,s)=>(j instanceof Object||G(\`\${s} with invalid "this": \${j}\`),j instanceof r.registeredClass.constructor||G(\`\${s} incompatible with "this" of type \${j.constructor.name}\`),j.$$.ptr||G(\`cannot call emscripten binding method \${s} on deleted object\`),fA(j.$$.ptr,j.$$.ptrType.registeredClass,r.registeredClass)),Lt=(j,r,s,l,o,a,k,u,c,C)=>{r=v(r),o=N(l,o),w([],[j],f=>{f=f[0];var m=\`\${f.name}.\${r}\`,E={get(){Q(\`Cannot access \${m} due to unbound types\`,[s,k])},enumerable:!0,configurable:!0};return c?E.set=()=>Q(\`Cannot access \${m} due to unbound types\`,[s,k]):E.set=h=>G(m+" is a read-only property"),Object.defineProperty(f.registeredClass.instancePrototype,r,E),w([],c?[s,k]:[s],h=>{var $=h[0],H={get(){var y=Or(this,f,m+" getter");return $.fromWireType(o(a,y))},enumerable:!0};if(c){c=N(u,c);var J=h[1];H.set=function(y){var eA=Or(this,f,m+" setter"),g=[];c(C,eA,J.toWireType(g,y)),Br(g)}}return Object.defineProperty(f.registeredClass.instancePrototype,r,H),[]}),[]})},wr=[],Y=[0,1,,1,null,1,!0,1,!1,1],gt=j=>{j>9&&--Y[j+1]===0&&(Y[j]=void 0,wr.push(j))},WA={toValue:j=>(j||G(\`Cannot use deleted val. handle = \${j}\`),Y[j]),toHandle:j=>{switch(j){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:{let r=wr.pop()||Y.length;return Y[r]=j,Y[r+1]=1,r}}}},Ht={name:"emscripten::val",fromWireType:j=>{var r=WA.toValue(j);return gt(j),r},toWireType:(j,r)=>WA.toHandle(r),readValueFromPointer:GA,destructorFunction:null},yt=j=>K(j,Ht),_t=(j,r)=>{switch(r){case 4:return function(s){return this.fromWireType(qr[s>>2])};case 8:return function(s){return this.fromWireType(Cr[s>>3])};default:throw new TypeError(\`invalid float width (\${r}): \${j}\`)}},Dt=(j,r,s)=>{r=v(r),K(j,{name:r,fromWireType:l=>l,toWireType:(l,o)=>o,readValueFromPointer:_t(r,s),destructorFunction:null})},xt=(j,r,s,l,o,a,k,u)=>{var c=VA(r,s);j=v(j),j=br(j),o=N(l,o,k),Dr(j,function(){Q(\`Cannot call \${j} due to unbound types\`,c)},r-1),w([],c,C=>{var f=[C[0],null].concat(C.slice(1));return Kr(j,SA(j,f,null,o,a,k),r-1),[]})},Kt=(j,r,s,l,o)=>{r=v(r);let a=l===0,k=c=>c;if(a){var u=32-8*s;k=c=>c<<u>>>u,o=k(o)}K(j,{name:r,fromWireType:k,toWireType:(c,C)=>C,readValueFromPointer:Fr(r,s,l!==0),destructorFunction:null})},Nt=(j,r,s)=>{var l=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=l[r];function a(k){var u=I[k>>2],c=I[k+4>>2];return new o(V.buffer,c,u)}s=v(s),K(j,{name:s,fromWireType:a,readValueFromPointer:a},{ignoreDuplicateRegistrations:!0})},Bt=(j,r,s,l)=>{if(!(l>0))return 0;for(var o=s,a=s+l-1,k=0;k<j.length;++k){var u=j.codePointAt(k);if(u<=127){if(s>=a)break;r[s++]=u}else if(u<=2047){if(s+1>=a)break;r[s++]=192|u>>6,r[s++]=128|u&63}else if(u<=65535){if(s+2>=a)break;r[s++]=224|u>>12,r[s++]=128|u>>6&63,r[s++]=128|u&63}else{if(s+3>=a)break;r[s++]=240|u>>18,r[s++]=128|u>>12&63,r[s++]=128|u>>6&63,r[s++]=128|u&63,k++}}return r[s]=0,s-o},Jt=(j,r,s)=>Bt(j,_,r,s),bt=j=>{for(var r=0,s=0;s<j.length;++s){var l=j.charCodeAt(s);l<=127?r++:l<=2047?r+=2:l>=55296&&l<=57343?(r+=4,++s):r+=3}return r},Pr=globalThis.TextDecoder&&new TextDecoder,Mr=(j,r,s,l)=>{var o=r+s;if(l)return o;for(;j[r]&&!(r>=o);)++r;return r},Tr=(j,r=0,s,l)=>{var o=Mr(j,r,s,l);if(o-r>16&&j.buffer&&Pr)return Pr.decode(j.subarray(r,o));for(var a="";r<o;){var k=j[r++];if(!(k&128)){a+=String.fromCharCode(k);continue}var u=j[r++]&63;if((k&224)==192){a+=String.fromCharCode((k&31)<<6|u);continue}var c=j[r++]&63;if((k&240)==224?k=(k&15)<<12|u<<6|c:k=(k&7)<<18|u<<12|c<<6|j[r++]&63,k<65536)a+=String.fromCharCode(k);else{var C=k-65536;a+=String.fromCharCode(55296|C>>10,56320|C&1023)}}return a},Ot=(j,r,s)=>j?Tr(_,j,r,s):"",wt=(j,r)=>{r=v(r);var s=!0;K(j,{name:r,fromWireType(l){var o=I[l>>2],a=l+4,k;if(s)k=Ot(a,o,!0);else{k="";for(var u=0;u<o;++u)k+=String.fromCharCode(_[a+u])}return B(l),k},toWireType(l,o){o instanceof ArrayBuffer&&(o=new Uint8Array(o));var a,k=typeof o=="string";k||ArrayBuffer.isView(o)&&o.BYTES_PER_ELEMENT==1||G("Cannot pass non-string to std::string"),s&&k?a=bt(o):a=o.length;var u=RA(4+a+1),c=u+4;if(I[u>>2]=a,k)if(s)Jt(o,c,a+1);else for(var C=0;C<a;++C){var f=o.charCodeAt(C);f>255&&(B(u),G("String has UTF-16 code units that do not fit in 8 bits")),_[c+C]=f}else _.set(o,c);return l!==null&&l.push(B,u),u},readValueFromPointer:GA,destructorFunction(l){B(l)}})},Ur=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Pt=(j,r,s)=>{var l=j>>1,o=Mr(Z,l,r/2,s);if(o-l>16&&Ur)return Ur.decode(Z.subarray(l,o));for(var a="",k=l;k<o;++k){var u=Z[k];a+=String.fromCharCode(u)}return a},Mt=(j,r,s)=>{if(s??=2147483647,s<2)return 0;s-=2;for(var l=r,o=s<j.length*2?s/2:j.length,a=0;a<o;++a){var k=j.charCodeAt(a);uA[r>>1]=k,r+=2}return uA[r>>1]=0,r-l},Tt=j=>j.length*2,Ut=(j,r,s)=>{for(var l="",o=j>>2,a=0;!(a>=r/4);a++){var k=I[o+a];if(!k&&!s)break;l+=String.fromCodePoint(k)}return l},Vt=(j,r,s)=>{if(s??=2147483647,s<4)return 0;for(var l=r,o=l+s-4,a=0;a<j.length;++a){var k=j.codePointAt(a);if(k>65535&&a++,cA[r>>2]=k,r+=4,r+4>o)break}return cA[r>>2]=0,r-l},St=j=>{for(var r=0,s=0;s<j.length;++s){var l=j.codePointAt(s);l>65535&&s++,r+=4}return r},Wt=(j,r,s)=>{s=v(s);var l,o,a;r===2?(l=Pt,o=Mt,a=Tt):(l=Ut,o=Vt,a=St),K(j,{name:s,fromWireType:k=>{var u=I[k>>2],c=l(k+4,u*r,!0);return B(k),c},toWireType:(k,u)=>{typeof u!="string"&&G(\`Cannot pass non-string to C++ string type \${s}\`);var c=a(u),C=RA(4+c+r);return I[C>>2]=c/r,o(u,C+4,c+r),k!==null&&k.push(B,C),C},readValueFromPointer:GA,destructorFunction(k){B(k)}})},Rt=(j,r)=>{r=v(r),K(j,{isVoid:!0,name:r,fromWireType:()=>{},toWireType:(s,l)=>{}})},zt=j=>{PA("OOM")},Xt=j=>{var r=_.length;j>>>=0,zt(j)},Qt=j=>52,Yt=9007199254740992,Zt=-9007199254740992,Ae=j=>j<Zt||j>Yt?NaN:Number(j);function re(j,r,s,l){return r=Ae(r),70}for(var je=[null,[],[]],te=(j,r)=>{var s=je[j];r===0||r===10?((j===1?ar:kA)(Tr(s)),s.length=0):s.push(r)},ee=(j,r,s,l)=>{for(var o=0,a=0;a<s;a++){var k=I[r>>2],u=I[r+4>>2];r+=8;for(var c=0;c<u;c++)te(j,_[k+c]);o+=u}return I[l>>2]=o,0},jA=new Uint8Array(123),P=25;P>=0;--P)jA[48+P]=52+P,jA[65+P]=P,jA[97+P]=26+P;if(jA[43]=62,jA[47]=63,st(),pt(),e.noExitRuntime&&(zj=e.noExitRuntime),e.print&&(ar=e.print),e.printErr&&(kA=e.printErr),e.wasmBinary&&(kr=e.wasmBinary),e.arguments&&(p=e.arguments),e.thisProgram&&(F=e.thisProgram),e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.shift()();var Vr,RA,B,ne,se,Sr,Wr;function ie(j){Vr=j.w,RA=e._malloc=j.y,B=e._free=j.z,ne=Sr=j.u,se=Wr=j.x}var le={g:Yj,r:Zj,f:rt,l:jt,k:Et,j:Ft,d:vt,a:Lt,s:yt,i:Dt,n:xt,c:Kt,b:Nt,t:wt,e:Wt,m:Rt,o:Xt,q:Qt,p:re,h:ee};function oe(){bj();function j(){e.calledRun=!0,!ur&&(Oj(),cr?.(e),e.onRuntimeInitialized?.(),wj())}e.setStatus?(e.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>e.setStatus(""),1),j()},1)):j()}var tA;return tA=await Sj(),oe(),pr?t=e:t=new Promise((j,r)=>{cr=j,dr=r}),t}})();typeof yj=="object"&&typeof OA=="object"?(OA.exports=sr,OA.exports.default=sr):typeof define=="function"&&define.amd&&define([],()=>sr)});var M={};fe(M,{AdditionalCaptureBlocks:()=>me,AdditionalPlaybackBlocks:()=>he,ClockJumpCheckInterval:()=>ge,ClockJumpThreshold:()=>He,ConnectInterval:()=>Be,ConnectTimeout:()=>xe,DefaultRefreshRate:()=>Ee,HealthCheckTimeout:()=>Le,MainConnectionPingInterval:()=>ye,MaxNumberOfDecoders:()=>Fe,MinDBFs:()=>Qr,MinTokenLifetime:()=>Ke,MinTokenRefreshInterval:()=>Ne,PlaybackPreload:()=>Ie,RenderQuantumSize:()=>ve,VadPreload:()=>$e,WebRtcIceTimeout:()=>_e,WebRtcTimeout:()=>De});var he=3,me=3,Ie=3,Ee=250,$e=3,Fe=512,ve=128,Qr=-758.596,Le=1e4,ge=1e3,He=1e4,ye=3e3,_e=3e3,De=1e4,xe=5e3,Ke=6e4,Ne=5e3,Be=[0,100,200,200,500];function T(n,A,t){return n.postMessage(A,t)}function Yr(n){return[n.values[0],n.values[1]]}function IA(n,A){n.values[0]=A[0],n.values[1]=A[1]}function EA(n,A){return n.values[2+A*5]}function Zr(n,A,t){n.values[2+A*5]=t}function Aj(n,A){let t=2+A*5+1;return[n.values[t+0],n.values[t+1]]}function $A(n,A,t){let e=2+A*5+1;n.values[e+0]=t[0],n.values[e+1]=t[1]}function rj(n,A){return n.values[2+A*5+3]}function jj(n,A,t){n.values[2+A*5+3]=t}function tj(n,A){return n.values[2+A*5+4]}function ej(n,A,t){n.values[2+A*5+4]=t}function FA(n){return n.values[0]!==0}function vA(n){return n.values[1]}function LA(n){return n.values[2]}function nj(n){return n.values[3]}function gA(n,A){return n.values[3]=A}function sj(n){return n?Array.from(n).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var Je;(n=>{let A;(t=>(t[t.InvalidPassword=-1]="InvalidPassword",t[t.Unknown=0]="Unknown",t[t.Unencrypted=1]="Unencrypted",t[t.Encrypted=2]="Encrypted"))(A=n.PeerCipherStatus||={})})(Je||={});function kj(n){return{type:"Success",value:n}}function D(n){return{type:"Failure",reason:n}}var{Deno:ij}=globalThis,be=typeof ij?.noColor=="boolean"?ij.noColor:!1,Oe=!be;function YA(n,A){return{open:\`\\x1B[\${n.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function ZA(n,A){return Oe?\`\${A.open}\${n.replace(A.regexp,A.open)}\${A.close}\`:n}function QA(n){return ZA(n,YA([0],0))}function lj(n){return ZA(n,YA([1],22))}function we(n){return ZA(n,YA([2],22))}var Nn=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),Pe=new Date,HA=(n=>(n[n.CRITICAL=0]="CRITICAL",n[n.ERROR=1]="ERROR",n[n.WARN=2]="WARN",n[n.INFO=3]="INFO",n[n.DEBUG=4]="DEBUG",n))(HA||{}),uj={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},Me={4:we,3:QA,2:QA,1:lj,0:lj};function Te({message:n}){return String(n)}function oj(n){return JSON.stringify({timestamp:n.date.toISOString(),level:HA[n.level],message:n.message,extra:n.extra})}function aj(n){function A(q,p){return[Math.floor(q/p),q%p]}function t(){let q,p=n.date.valueOf()-Pe.valueOf();[p,q]=A(p,1e3);let[F,x]=A(p,60);return\`\${F.toString().padStart(4,"0")}:\${x.toString().padStart(2,"0")}.\${q.toString().padStart(4,"0")}\`}function e(){return n.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(n.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(n.extra)}let i=uj[n.level],d=n.logger.name!==void 0?\`@\${n.logger}\`:"";return\`\${QA(t())}\${d} \${i} \${Me[n.level](String(n.message))}\${e()}\`}function Ue(n){let A=\`[\${n.date.toISOString()}]\`,t=\`[\${HA[n.level]}]\`,e=n.logger.name!==void 0?\`[\${n.logger.name}] \`:"",i=uj[n.level];return\`\${A} \${i} \${t.padEnd(7," ")} \${e}\${n.message}\`}function Ve(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var cj={sparse:Te,json:oj,pretty:aj,structured:Ue,default:Ve()?aj:oj},Se=class{formatter;consoleObject;filter;constructor(n=cj.default,A=4,t=console){this.filter=A,this.formatter=n,this.consoleObject=t}handle(n){let A=this.formatter(n);switch(n.level){case 1:this.consoleObject.error(A);break;case 2:this.consoleObject.warn(A);break;case 3:this.consoleObject.info(A);break;case 4:this.consoleObject.debug(A);break}}};var S=class{#A;sinks;filter;parent;get name(){return this.#A}constructor(n,A=void 0,t=[],e=void 0){this.#A=A,this.sinks=t,this.filter=n,this.parent=e}log(n,A,t=void 0){let e={date:new Date,level:n,logger:this,message:A,extra:t};this.filter<n||this.insert(e)}insert(n){if(!(this.filter<n.level)){for(let A of this.sinks)A.filter>=n.level&&A.handle(n);this.parent!==void 0&&this.parent.insert(n)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},nA=new S(3,void 0,[new Se]),We=S.prototype.log.bind(nA,1),Re=S.prototype.log.bind(nA,2),dj=S.prototype.log.bind(nA,3),ze=S.prototype.log.bind(nA,4),Bn=S.prototype.log.bind(nA);var qj;function Cj(n,...A){let t=Xe(A);qj?qj?.info(n,t):dj(n,t)}function Xe(...n){if(n.length===1&&typeof n[0]=="object"&&n[0]!==null)return{...n[0]};if(n.length>0)return{args:n}}function yA(n){return n.connectionId*4294967296+n.mediaId}function fj(n){return{mediaId:n%4294967296,connectionId:Math.floor(n/4294967296)}}function b(n,A,t){let e;switch(A){case"f32":e=n.HEAPF32;break;case"u32":e=n.HEAPU32;break;case"i32":e=n.HEAP32;break;case"u8":e=n.HEAPU8;break;default:throw new Error(\`allocating \${A} is not supported\`)}let i=n._malloc(t*e.BYTES_PER_ELEMENT);if(i===0||i%e.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${t} \${A} array\`);let d=i/e.BYTES_PER_ELEMENT;return e.subarray(d,d+t)}function W(n,A){n._free(A.byteOffset)}function Gj(n,A){return{values:b(n,"f32",2+A*5),length:A}}function pj(n,A){W(n,A.values)}function hj(n){return{values:b(n,"f32",4)}}function mj(n,A){W(n,A.values)}function Ij(n){let A=n.length,t=0,e=0;for(;e<A;){let i=n.charCodeAt(e++);if((i&4294967168)===0){t++;continue}else if((i&4294965248)===0)t+=2;else{if(i>=55296&&i<=56319&&e<A){let d=n.charCodeAt(e);(d&64512)===56320&&(++e,i=((i&1023)<<10)+(d&1023)+65536)}(i&4294901760)===0?t+=3:t+=4}}return t}function Qe(n,A,t){let e=n.length,i=t,d=0;for(;d<e;){let q=n.charCodeAt(d++);if((q&4294967168)===0){A[i++]=q;continue}else if((q&4294965248)===0)A[i++]=q>>6&31|192;else{if(q>=55296&&q<=56319&&d<e){let p=n.charCodeAt(d);(p&64512)===56320&&(++d,q=((q&1023)<<10)+(p&1023)+65536)}(q&4294901760)===0?(A[i++]=q>>12&15|224,A[i++]=q>>6&63|128):(A[i++]=q>>18&7|240,A[i++]=q>>12&63|128,A[i++]=q>>6&63|128)}A[i++]=q&63|128}}var Ye=new TextEncoder,Ze=50;function An(n,A,t){Ye.encodeInto(n,A.subarray(t))}function Ej(n,A,t){n.length>Ze?An(n,A,t):Qe(n,A,t)}var rn=4096;function Ar(n,A,t){let e=A,i=e+t,d=[],q="";for(;e<i;){let p=n[e++];if((p&128)===0)d.push(p);else if((p&224)===192){let F=n[e++]&63;d.push((p&31)<<6|F)}else if((p&240)===224){let F=n[e++]&63,x=n[e++]&63;d.push((p&31)<<12|F<<6|x)}else if((p&248)===240){let F=n[e++]&63,x=n[e++]&63,wA=n[e++]&63,O=(p&7)<<18|F<<12|x<<6|wA;O>65535&&(O-=65536,d.push(O>>>10&1023|55296),O=56320|O&1023),d.push(O)}else d.push(p);d.length>=rn&&(q+=String.fromCharCode(...d),d.length=0)}return d.length>0&&(q+=String.fromCharCode(...d)),q}var jn=new TextDecoder,tn=200;function en(n,A,t){let e=n.subarray(A,A+t);return jn.decode(e)}function $j(n,A,t){return t>tn?en(n,A,t):Ar(n,A,t)}var R=class{constructor(A,t){this.type=A,this.data=t}};var L=class n extends Error{constructor(A){super(A);let t=Object.create(n.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:n.name})}};function Fj(n,A,t){let e=t/4294967296,i=t;n.setUint32(A,e),n.setUint32(A+4,i)}function _A(n,A,t){let e=Math.floor(t/4294967296),i=t;n.setUint32(A,e),n.setUint32(A+4,i)}function DA(n,A){let t=n.getInt32(A),e=n.getUint32(A+4);return t*4294967296+e}function vj(n,A){let t=n.getUint32(A),e=n.getUint32(A+4);return t*4294967296+e}var nn=-1,sn=4294967296-1,ln=17179869184-1;function on({sec:n,nsec:A}){if(n>=0&&A>=0&&n<=ln)if(A===0&&n<=sn){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{let t=n/4294967296,e=n&4294967295,i=new Uint8Array(8),d=new DataView(i.buffer);return d.setUint32(0,A<<2|t&3),d.setUint32(4,e),i}else{let t=new Uint8Array(12),e=new DataView(t.buffer);return e.setUint32(0,A),_A(e,4,n),t}}function an(n){let A=n.getTime(),t=Math.floor(A/1e3),e=(A-t*1e3)*1e6,i=Math.floor(e/1e9);return{sec:t+i,nsec:e-i*1e9}}function kn(n){if(n instanceof Date){let A=an(n);return on(A)}else return null}function un(n){let A=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:A.getUint32(0),nsec:0};case 8:{let t=A.getUint32(0),e=A.getUint32(4),i=(t&3)*4294967296+e,d=t>>>2;return{sec:i,nsec:d}}case 12:{let t=DA(A,4),e=A.getUint32(0);return{sec:t,nsec:e}}default:throw new L(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${n.length}\`)}}function cn(n){let A=un(n);return new Date(A.sec*1e3+A.nsec/1e6)}var Lj={type:nn,encode:kn,decode:cn};var U=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Lj)}register({type:A,encode:t,decode:e}){if(A>=0)this.encoders[A]=t,this.decoders[A]=e;else{let i=-1-A;this.builtInEncoders[i]=t,this.builtInDecoders[i]=e}}tryToEncode(A,t){for(let e=0;e<this.builtInEncoders.length;e++){let i=this.builtInEncoders[e];if(i!=null){let d=i(A,t);if(d!=null){let q=-1-e;return new R(q,d)}}}for(let e=0;e<this.encoders.length;e++){let i=this.encoders[e];if(i!=null){let d=i(A,t);if(d!=null){let q=e;return new R(q,d)}}}return A instanceof R?A:null}decode(A,t,e){let i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(A,t,e):new R(t,A)}};U.defaultCodec=new U;function dn(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function sA(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):dn(n)?new Uint8Array(n):Uint8Array.from(n)}var qn=100,Cn=2048,xA=class n{constructor(A){this.entered=!1,this.extensionCodec=A?.extensionCodec??U.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??qn,this.initialBufferSize=A?.initialBufferSize??Cn,this.sortKeys=A?.sortKeys??!1,this.forceFloat32=A?.forceFloat32??!1,this.ignoreUndefined=A?.ignoreUndefined??!1,this.forceIntegerToFloat=A?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(A){if(this.entered)return this.clone().encodeSharedRef(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(A){if(this.entered)return this.clone().encode(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(A,t){if(t>this.maxDepth)throw new Error(\`Too deep objects in depth \${t}\`);A==null?this.encodeNil():typeof A=="boolean"?this.encodeBoolean(A):typeof A=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(A):this.encodeNumber(A):typeof A=="string"?this.encodeString(A):this.useBigInt64&&typeof A=="bigint"?this.encodeBigInt64(A):this.encodeObject(A,t)}ensureBufferSizeToWrite(A){let t=this.pos+A;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(A){let t=new ArrayBuffer(A),e=new Uint8Array(t),i=new DataView(t);e.set(this.bytes),this.view=i,this.bytes=e}encodeNil(){this.writeU8(192)}encodeBoolean(A){A===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(A){!this.forceIntegerToFloat&&Number.isSafeInteger(A)?A>=0?A<128?this.writeU8(A):A<256?(this.writeU8(204),this.writeU8(A)):A<65536?(this.writeU8(205),this.writeU16(A)):A<4294967296?(this.writeU8(206),this.writeU32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(207),this.writeU64(A)):A>=-32?this.writeU8(224|A+32):A>=-128?(this.writeU8(208),this.writeI8(A)):A>=-32768?(this.writeU8(209),this.writeI16(A)):A>=-2147483648?(this.writeU8(210),this.writeI32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(211),this.writeI64(A)):this.encodeNumberAsFloat(A)}encodeNumberAsFloat(A){this.forceFloat32?(this.writeU8(202),this.writeF32(A)):(this.writeU8(203),this.writeF64(A))}encodeBigInt64(A){A>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(A)):(this.writeU8(211),this.writeBigInt64(A))}writeStringHeader(A){if(A<32)this.writeU8(160+A);else if(A<256)this.writeU8(217),this.writeU8(A);else if(A<65536)this.writeU8(218),this.writeU16(A);else if(A<4294967296)this.writeU8(219),this.writeU32(A);else throw new Error(\`Too long string: \${A} bytes in UTF-8\`)}encodeString(A){let e=Ij(A);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),Ej(A,this.bytes,this.pos),this.pos+=e}encodeObject(A,t){let e=this.extensionCodec.tryToEncode(A,this.context);if(e!=null)this.encodeExtension(e);else if(Array.isArray(A))this.encodeArray(A,t);else if(ArrayBuffer.isView(A))this.encodeBinary(A);else if(typeof A=="object")this.encodeMap(A,t);else throw new Error(\`Unrecognized object: \${Object.prototype.toString.apply(A)}\`)}encodeBinary(A){let t=A.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(\`Too large binary: \${t}\`);let e=sA(A);this.writeU8a(e)}encodeArray(A,t){let e=A.length;if(e<16)this.writeU8(144+e);else if(e<65536)this.writeU8(220),this.writeU16(e);else if(e<4294967296)this.writeU8(221),this.writeU32(e);else throw new Error(\`Too large array: \${e}\`);for(let i of A)this.doEncode(i,t+1)}countWithoutUndefined(A,t){let e=0;for(let i of t)A[i]!==void 0&&e++;return e}encodeMap(A,t){let e=Object.keys(A);this.sortKeys&&e.sort();let i=this.ignoreUndefined?this.countWithoutUndefined(A,e):e.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(\`Too large map object: \${i}\`);for(let d of e){let q=A[d];this.ignoreUndefined&&q===void 0||(this.encodeString(d),this.doEncode(q,t+1))}}encodeExtension(A){if(typeof A.data=="function"){let e=A.data(this.pos+6),i=e.length;if(i>=4294967296)throw new Error(\`Too large extension object: \${i}\`);this.writeU8(201),this.writeU32(i),this.writeI8(A.type),this.writeU8a(e);return}let t=A.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(\`Too large extension object: \${t}\`);this.writeI8(A.type),this.writeU8a(A.data)}writeU8(A){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,A),this.pos++}writeU8a(A){let t=A.length;this.ensureBufferSizeToWrite(t),this.bytes.set(A,this.pos),this.pos+=t}writeI8(A){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,A),this.pos++}writeU16(A){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,A),this.pos+=2}writeI16(A){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,A),this.pos+=2}writeU32(A){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,A),this.pos+=4}writeI32(A){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,A),this.pos+=4}writeF32(A){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,A),this.pos+=4}writeF64(A){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,A),this.pos+=8}writeU64(A){this.ensureBufferSizeToWrite(8),Fj(this.view,this.pos,A),this.pos+=8}writeI64(A){this.ensureBufferSizeToWrite(8),_A(this.view,this.pos,A),this.pos+=8}writeBigUint64(A){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,A),this.pos+=8}writeBigInt64(A){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,A),this.pos+=8}};function rr(n,A){return new xA(A).encodeSharedRef(n)}function KA(n){return\`\${n<0?"-":""}0x\${Math.abs(n).toString(16).padStart(2,"0")}\`}var fn=16,Gn=16,NA=class{constructor(A=fn,t=Gn){this.hit=0,this.miss=0,this.maxKeyLength=A,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,t,e){let i=this.caches[e-1];A:for(let d of i){let q=d.bytes;for(let p=0;p<e;p++)if(q[p]!==A[t+p])continue A;return d.str}return null}store(A,t){let e=this.caches[A.length-1],i={bytes:A,str:t};e.length>=this.maxLengthPerKey?e[Math.random()*e.length|0]=i:e.push(i)}decode(A,t,e){let i=this.find(A,t,e);if(i!=null)return this.hit++,i;this.miss++;let d=Ar(A,t,e),q=Uint8Array.prototype.slice.call(A,t,t+e);return this.store(q,d),d}};var jr="array",oA="map_key",Hj="map_value",pn=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new L("The type of key must be string or number but "+typeof n)},tr=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let t=this.getUninitializedStateFromPool();t.type=jr,t.position=0,t.size=A,t.array=new Array(A)}pushMapState(A){let t=this.getUninitializedStateFromPool();t.type=oA,t.readCount=0,t.size=A,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let A={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(A)}return this.stack[this.stackHeadPosition]}release(A){if(this.stack[this.stackHeadPosition]!==A)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(A.type===jr){let e=A;e.size=0,e.array=void 0,e.position=0,e.type=void 0}if(A.type===oA||A.type===Hj){let e=A;e.size=0,e.map=void 0,e.readCount=0,e.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},lA=-1,er=new DataView(new ArrayBuffer(0)),hn=new Uint8Array(er.buffer);try{er.getInt8(0)}catch(n){if(!(n instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var gj=new RangeError("Insufficient data"),mn=new NA,BA=class n{constructor(A){this.totalPos=0,this.pos=0,this.view=er,this.bytes=hn,this.headByte=lA,this.stack=new tr,this.entered=!1,this.extensionCodec=A?.extensionCodec??U.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.rawStrings=A?.rawStrings??!1,this.maxStrLength=A?.maxStrLength??4294967295,this.maxBinLength=A?.maxBinLength??4294967295,this.maxArrayLength=A?.maxArrayLength??4294967295,this.maxMapLength=A?.maxMapLength??4294967295,this.maxExtLength=A?.maxExtLength??4294967295,this.keyDecoder=A?.keyDecoder!==void 0?A.keyDecoder:mn,this.mapKeyConverter=A?.mapKeyConverter??pn}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=lA,this.stack.reset()}setBuffer(A){let t=sA(A);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(A){if(this.headByte===lA&&!this.hasRemaining(1))this.setBuffer(A);else{let t=this.bytes.subarray(this.pos),e=sA(A),i=new Uint8Array(t.length+e.length);i.set(t),i.set(e,t.length),this.setBuffer(i)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:t,pos:e}=this;return new RangeError(\`Extra \${t.byteLength-e} of \${t.byteLength} byte(s) found at buffer[\${A}]\`)}decode(A){if(this.entered)return this.clone().decode(A);try{this.entered=!0,this.reinitializeState(),this.setBuffer(A);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(A){if(this.entered){yield*this.clone().decodeMulti(A);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(A);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(A){if(this.entered)return this.clone().decodeAsync(A);try{this.entered=!0;let t=!1,e;for await(let p of A){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(p);try{e=this.doDecodeSync(),t=!0}catch(F){if(!(F instanceof RangeError))throw F}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return e}let{headByte:i,pos:d,totalPos:q}=this;throw new RangeError(\`Insufficient data in parsing \${KA(i)} at \${q} (\${d} in the current buffer)\`)}finally{this.entered=!1}}decodeArrayStream(A){return this.decodeMultiAsync(A,!0)}decodeStream(A){return this.decodeMultiAsync(A,!1)}async*decodeMultiAsync(A,t){if(this.entered){yield*this.clone().decodeMultiAsync(A,t);return}try{this.entered=!0;let e=t,i=-1;for await(let d of A){if(t&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(d),e&&(i=this.readArraySize(),e=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(q){if(!(q instanceof RangeError))throw q}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){A:for(;;){let A=this.readHeadByte(),t;if(A>=224)t=A-256;else if(A<192)if(A<128)t=A;else if(A<144){let i=A-128;if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A<160){let i=A-144;if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else{let i=A-160;t=this.decodeString(i,0)}else if(A===192)t=null;else if(A===194)t=!1;else if(A===195)t=!0;else if(A===202)t=this.readF32();else if(A===203)t=this.readF64();else if(A===204)t=this.readU8();else if(A===205)t=this.readU16();else if(A===206)t=this.readU32();else if(A===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(A===208)t=this.readI8();else if(A===209)t=this.readI16();else if(A===210)t=this.readI32();else if(A===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(A===217){let i=this.lookU8();t=this.decodeString(i,1)}else if(A===218){let i=this.lookU16();t=this.decodeString(i,2)}else if(A===219){let i=this.lookU32();t=this.decodeString(i,4)}else if(A===220){let i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===221){let i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===222){let i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===223){let i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===196){let i=this.lookU8();t=this.decodeBinary(i,1)}else if(A===197){let i=this.lookU16();t=this.decodeBinary(i,2)}else if(A===198){let i=this.lookU32();t=this.decodeBinary(i,4)}else if(A===212)t=this.decodeExtension(1,0);else if(A===213)t=this.decodeExtension(2,0);else if(A===214)t=this.decodeExtension(4,0);else if(A===215)t=this.decodeExtension(8,0);else if(A===216)t=this.decodeExtension(16,0);else if(A===199){let i=this.lookU8();t=this.decodeExtension(i,1)}else if(A===200){let i=this.lookU16();t=this.decodeExtension(i,2)}else if(A===201){let i=this.lookU32();t=this.decodeExtension(i,4)}else throw new L(\`Unrecognized type byte: \${KA(A)}\`);this.complete();let e=this.stack;for(;e.length>0;){let i=e.top();if(i.type===jr)if(i.array[i.position]=t,i.position++,i.position===i.size)t=i.array,e.release(i);else continue A;else if(i.type===oA){if(t==="__proto__")throw new L("The key __proto__ is not allowed");i.key=this.mapKeyConverter(t),i.type=Hj;continue A}else if(i.map[i.key]=t,i.readCount++,i.readCount===i.size)t=i.map,e.release(i);else{i.key=null,i.type=oA;continue A}}return t}}readHeadByte(){return this.headByte===lA&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=lA}readArraySize(){let A=this.readHeadByte();switch(A){case 220:return this.readU16();case 221:return this.readU32();default:{if(A<160)return A-144;throw new L(\`Unrecognized array type byte: \${KA(A)}\`)}}}pushMapState(A){if(A>this.maxMapLength)throw new L(\`Max length exceeded: map length (\${A}) > maxMapLengthLength (\${this.maxMapLength})\`);this.stack.pushMapState(A)}pushArrayState(A){if(A>this.maxArrayLength)throw new L(\`Max length exceeded: array length (\${A}) > maxArrayLength (\${this.maxArrayLength})\`);this.stack.pushArrayState(A)}decodeString(A,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(A,t):this.decodeBinary(A,t)}decodeUtf8String(A,t){if(A>this.maxStrLength)throw new L(\`Max length exceeded: UTF-8 byte length (\${A}) > maxStrLength (\${this.maxStrLength})\`);if(this.bytes.byteLength<this.pos+t+A)throw gj;let e=this.pos+t,i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?i=this.keyDecoder.decode(this.bytes,e,A):i=$j(this.bytes,e,A),this.pos+=t+A,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===oA:!1}decodeBinary(A,t){if(A>this.maxBinLength)throw new L(\`Max length exceeded: bin length (\${A}) > maxBinLength (\${this.maxBinLength})\`);if(!this.hasRemaining(A+t))throw gj;let e=this.pos+t,i=this.bytes.subarray(e,e+A);return this.pos+=t+A,i}decodeExtension(A,t){if(A>this.maxExtLength)throw new L(\`Max length exceeded: ext length (\${A}) > maxExtLength (\${this.maxExtLength})\`);let e=this.view.getInt8(this.pos+t),i=this.decodeBinary(A,t+1);return this.extensionCodec.decode(i,e,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let A=this.view.getUint8(this.pos);return this.pos++,A}readI8(){let A=this.view.getInt8(this.pos);return this.pos++,A}readU16(){let A=this.view.getUint16(this.pos);return this.pos+=2,A}readI16(){let A=this.view.getInt16(this.pos);return this.pos+=2,A}readU32(){let A=this.view.getUint32(this.pos);return this.pos+=4,A}readI32(){let A=this.view.getInt32(this.pos);return this.pos+=4,A}readU64(){let A=vj(this.view,this.pos);return this.pos+=8,A}readI64(){let A=DA(this.view,this.pos);return this.pos+=8,A}readU64AsBigInt(){let A=this.view.getBigUint64(this.pos);return this.pos+=8,A}readI64AsBigInt(){let A=this.view.getBigInt64(this.pos);return this.pos+=8,A}readF32(){let A=this.view.getFloat32(this.pos);return this.pos+=4,A}readF64(){let A=this.view.getFloat64(this.pos);return this.pos+=8,A}};function nr(n,A){return new BA(A).decode(n)}var aA=class n{constructor(A,t,e,i,d){this.mediaIds=A;this.sequenceNumber=t;this.timeStamp=e;this.isEndOfSpurt=i;this.payload=d}static parse(A){let t;try{t=nr(A)}catch{return D("not valid msgpack")}if(!Array.isArray(t))return D("container must be an array");if(t.length<6)return D("missing fields");if(t[0]!==1)return D("unknown type");if(!Array.isArray(t[1]))return D("media ids must be an array");if(!t[1].every(x=>typeof x=="number"))return D("media ids must be numbers");if(typeof t[2]!="number")return D("sequence number must be a number");if(typeof t[3]!="number")return D("timestamp must be a number");if(typeof t[4]!="number")return D("flags must be a number");let e=t[1],i=t[2]>>>0,d=t[3]>>>0,p=(t[4]&1)!==0,F=t[t.length-1];return F instanceof Uint8Array?kj(new n(e,i,d,p,F)):D("payload must be bytes")}toBytes(){let A=Number(this.isEndOfSpurt),t=[1,this.mediaIds,this.sequenceNumber>>>0,this.timeStamp>>>0,A,this.payload];return new Uint8Array(rr(t,{forceFloat32:!0,ignoreUndefined:!0}))}};var JA=class{constructor(A,t){this.sampleRate=A;this.wasm=t;this.sequenceNumber=Math.random()*Math.pow(2,32)>>0;this.timestamp=Math.random()*Math.pow(2,32)>>0;this.connections=[];this.monitoring=!1;this.active=!1;this.stats={numberPackets:0,numberTicks:0,numberPacketError:0,numberPacketsMediaNotFound:0};this.encoder=new t.Encoder(A,15,!0,M.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=hj(this.wasm),this.outBuffer=b(this.wasm,"u8",1270),gA(this.information,1)}setVad(A){this.encoder.set_volume_gate(A.volumeGate!==void 0,A.volumeGate?.attackThreshold??0,A.volumeGate?.releaseThreshold??0),this.encoder.set_speech_detection(A.voiceActivity!==void 0,A.voiceActivity?.attackThreshold??0,A.voiceActivity?.releaseThreshold??0)}setMedias(A){this.connections=A.filter(({mediaIds:t})=>t.length>0)}close(){mj(this.wasm,this.information),W(this.wasm,this.outBuffer),this.encoder.delete()}encode(A){for(this.encoder.push(A.byteOffset,this.information.values.byteOffset);;){let t=this.encoder.pop(this.connections.length===0?0:this.outBuffer.byteOffset,this.outBuffer.length);if(t===0)break;if(t<0){Cj(\`failed encoding packet: \${t}\`);return}if(this.timestamp=this.timestamp+1800>>0,t===1)continue;this.sequenceNumber=this.sequenceNumber+1>>0;let e=this.active&&!this.encoder.active;this.active=this.encoder.active,this.monitoring=this.connections.some(i=>i.id===0);for(let i of this.connections){if(this.monitoring&&i.id!==0)continue;let d=new aA(i.mediaIds,this.sequenceNumber,this.timestamp,e,this.outBuffer.subarray(0,t));T(globalThis,["sendPacket",{connectionId:i.id,packet:d.toBytes()}])}}}onMessage(A){let[t,e]=A;switch(t){case"captureSetVad":this?.setVad(e);break;case"captureSetMedias":this?.setMedias(e.connections);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){return{sequenceNumber:this.sequenceNumber,timestamp:this.timestamp,connections:this.connections.map(A=>\`\${A.id} => \${A.mediaIds.join(",")}\`),active:this.active,monitoring:this.monitoring,information:{active:FA(this.information),speechProbability:vA(this.information),rmsDBFS:LA(this.information),volume:nj(this.information)},encoder:{sample_rate:this.encoder.sample_rate,fec_packet_loss:this.encoder.fec_packet_loss,voip:this.encoder.voip,vad_preload:this.encoder.vad_preload,complexity:this.encoder.complexity,speech_probability:this.encoder.speech_probability,rms_dbfs:this.encoder.rms_dbfs,active:this.encoder.active,speech_detection_enabled:this.encoder.speech_detection_enabled,speech_detection_going_active:this.encoder.speech_detection_going_active,speech_detection_going_inactive:this.encoder.speech_detection_going_inactive,volume_gate_enabled:this.encoder.volume_gate_enabled,volume_gate_going_active:this.encoder.volume_gate_going_active,volume_gate_going_inactive:this.encoder.volume_gate_going_inactive}}}},bA=class{constructor(A){this.wasm=A;this.medias=new Map;this.stats={numberPackets:0,numberTicks:0,numberPacketError:0,numberPacketsMediaNotFound:0,numberTicksWithAudio:0};this.largestIndex=-1;this.decoders=b(this.wasm,"u32",M.MaxNumberOfDecoders),this.information=Gj(this.wasm,M.MaxNumberOfDecoders),IA(this.information,[1,1])}close(){pj(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,t){this.stats.numberPackets++;let e=aA.parse(t);if(e.type==="Failure"){this.stats.numberPacketError++;let i=Array.from(t).map(d=>d.toString(16).padStart(2,"0")).join("");console.error(\`failed decoding audio packet; reason: \${e.reason}, connection: \${A}, dump: \${i}\`);return}for(let i of e.value.mediaIds){let d=this.medias.get(yA({connectionId:A,mediaId:i}));if(d===void 0){this.stats.numberPacketsMediaNotFound++;continue}d.lastPacket=t;let q=b(this.wasm,"u8",e.value.payload.length);q.set(e.value.payload),d.decoder.push(e.value.sequenceNumber,e.value.timeStamp,e.value.isEndOfSpurt,q.byteOffset,q.length)}}insertMedia(A,t,e,i=[1,1]){let d=yA({connectionId:t,mediaId:e}),q=new this.wasm.Decoder;this.medias.set(d,{index:A,decoder:q,lastPacket:void 0}),this.decoders[A]=q.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),$A(this.information,A,i),ej(this.information,A,0),jj(this.information,A,0)}removeMedia(A,t,e){let i=yA({connectionId:t,mediaId:e}),d=this.medias.get(i);if(!(d===void 0||d.index!==A)&&(this.medias.delete(i),Zr(this.information,A,0),this.decoders[A]=0,d.decoder.delete(),A===this.largestIndex)){for(A=A-1;A>=0&&this.decoders[A]===0;A--);this.largestIndex=A}}decode(A){return{hasAudio:this.wasm.pop_many(this.decoders.byteOffset,this.information.values.byteOffset,this.largestIndex+1,A.byteOffset)}}onMessage(A){let[t,e]=A;switch(t){case"playbackReceivePacket":this.receivePacket(e.connectionId,e.packet);break;case"playbackUpdateMedias":for(let{index:i,connectionId:d,mediaId:q}of e.removed)this.removeMedia(i,d,q);for(let{index:i,connectionId:d,mediaId:q,volume:p}of e.added)this.insertMedia(i,d,q,p);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){let A=[];for(let[t,e]of this.medias){let i=fj(t);A.push({index:e.index,connectionId:i.connectionId,mediaId:i.mediaId,rmsDBFS:EA(this.information,e.index),volume:Aj(this.information,e.index),voicedBlocks:tj(this.information,e.index),silentBlocks:rj(this.information,e.index),time:e.decoder.time,consecutive_silence:e.decoder.consecutive_silence,last_voiced_time_point:e.decoder.last_voiced_time_point,sequence_number:e.decoder.sequence_number,packetsSeen:e.decoder.packets_seen,packetsInvalid:e.decoder.packets_invalid,packetsTooLate:e.decoder.packets_too_late,packetsTooEarly:e.decoder.packets_too_early,packetsRepeated:e.decoder.packets_repeated,packetsProcessed:e.decoder.packets_processed,packetsLost:e.decoder.packets_lost,rewinds:e.decoder.rewinds,cacheLength:e.decoder.cache_length,lastPacket:sj(e.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:Yr(this.information),decoders:A}}};var Nj=pe(_j()),Dj=(0,Nj.default)(),xj,Kj;globalThis.addEventListener("message",ir);async function ir(n){let A=n.data,[t,e]=A;switch(t){case"captureInit":e.workletPort.onmessage=ir,xj=new lr(e.sampleRate,await Dj,e.refreshRate);break;case"playbackInit":e.workletPort.onmessage=ir,Kj=new or(await Dj,e.workletPort,e.refreshRate);break;case"close":globalThis.close();break}xj?.onMessage(A),Kj?.onMessage(A)}var lr=class extends JA{constructor(t,e,i){super(t,e);this.sampleRate=t;this.inBuffer=b(this.wasm,"f32",t*.02),this.updateHandle=setInterval(()=>this.update(),i),T(globalThis,["captureReady",{}])}close(){super.close(),W(this.wasm,this.inBuffer),clearInterval(this.updateHandle)}onMessage(t){super.onMessage(t);let[e,i]=t;switch(e){case"captureSetVolume":this.setVolume(i.value);break;case"captureTick":this.tick(i.buffer);break}}setVolume(t){gA(this.information,t)}tick(t){this.inBuffer.set(t,0),this.encode(this.inBuffer)}update(){T(globalThis,["captureUpdate",{active:FA(this.information),rmsDBFs:LA(this.information),speechProbability:vA(this.information)}])}dump(){return{type:"unshared capture worker",sampleRate:this.sampleRate,...super.dump()}}},or=class extends bA{constructor(t,e,i){super(t);this.workletPort=e;this.id=M.PlaybackPreload,this.outBuffer=b(this.wasm,"f32",48e3*.02*2),this.updateHandle=setInterval(()=>this.update(),i),T(globalThis,["playbackReady",{}])}close(){super.close(),W(this.wasm,this.outBuffer),clearInterval(this.updateHandle)}onMessage(t){super.onMessage(t);let[e,i]=t;switch(e){case"playbackSetVolume":this.setVolume(i.index,i.value);break;case"playbackTick":this.tick();break}}setVolume(t,e){t==="global"?IA(this.information,e):$A(this.information,t,e)}tick(){this.stats.numberTicks++,this.id+=1;let{hasAudio:t}=this.decode(this.outBuffer);if(t){let e=this.outBuffer.slice();T(this.workletPort,["samples",{id:this.id,buffer:e}],[e.buffer])}}update(){let t=new Float32Array(this.information.length*2);for(let i=0;i<=this.largestIndex;i++)t[i]=EA(this.information,i);let e=[];for(let[i,d]of this.medias)e[d.index]={packetsBuffered:d.decoder.cache_length,packetsSeen:d.decoder.packets_seen,packetsProcessed:d.decoder.packets_processed,packetsTooEarly:d.decoder.packets_too_early,packetsTooLate:d.decoder.packets_too_late,packetsDropped:0,packetsInvalid:d.decoder.packets_invalid,packetsRepeated:d.decoder.packets_repeated,packetsLost:d.decoder.packets_lost};T(globalThis,["playbackUpdate",{activities:t,jitterStats:e}],[t.buffer])}dump(){return{type:"unshared playback worker",id:this.id,...super.dump()}}};})();
6413
- `});var Xx,y0=p(()=>{Xx='"use strict";(()=>{var P=Object.defineProperty;var M=(e,t)=>{for(var r in t)P(e,r,{get:t[r],enumerable:!0})};var u={};M(u,{AdditionalCaptureBlocks:()=>R,AdditionalPlaybackBlocks:()=>E,ClockJumpCheckInterval:()=>_,ClockJumpThreshold:()=>N,ConnectInterval:()=>H,ConnectTimeout:()=>J,DefaultRefreshRate:()=>D,HealthCheckTimeout:()=>O,MainConnectionPingInterval:()=>W,MaxNumberOfDecoders:()=>L,MinDBFs:()=>v,MinTokenLifetime:()=>z,MinTokenRefreshInterval:()=>G,PlaybackPreload:()=>F,RenderQuantumSize:()=>V,VadPreload:()=>C,WebRtcIceTimeout:()=>$,WebRtcTimeout:()=>j});var E=3,R=3,F=3,D=250,C=3,L=512,V=128,v=-758.596,O=1e4,_=1e3,N=1e4,W=3e3,$=3e3,j=1e4,J=5e3,z=6e4,G=5e3,H=[0,100,200,200,500];function d(e,t,r){return e.postMessage(t,r)}var Z;(e=>{let t;(r=>(r[r.InvalidPassword=-1]="InvalidPassword",r[r.Unknown=0]="Unknown",r[r.Unencrypted=1]="Unencrypted",r[r.Encrypted=2]="Encrypted"))(t=e.PeerCipherStatus||={})})(Z||={});var{Deno:k}=globalThis,q=typeof k?.noColor=="boolean"?k.noColor:!1,Q=!q;function m(e,t){return{open:`\\x1B[${e.join(";")}m`,close:`\\x1B[${t}m`,regexp:new RegExp(`\\\\x1b\\\\[${t}m`,"g")}}function h(e,t){return Q?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}function p(e){return h(e,m([0],0))}function U(e){return h(e,m([1],22))}function K(e){return h(e,m([2],22))}var ge=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),X=new Date,f=(e=>(e[e.CRITICAL=0]="CRITICAL",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(f||{}),T={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},Y={4:K,3:p,2:p,1:U,0:U};function ee({message:e}){return String(e)}function S(e){return JSON.stringify({timestamp:e.date.toISOString(),level:f[e.level],message:e.message,extra:e.extra})}function I(e){function t(c,i){return[Math.floor(c/i),c%i]}function r(){let c,i=e.date.valueOf()-X.valueOf();[i,c]=t(i,1e3);let[B,A]=t(i,60);return`${B.toString().padStart(4,"0")}:${A.toString().padStart(2,"0")}.${c.toString().padStart(4,"0")}`}function n(){return e.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(e.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(e.extra)}let s=T[e.level],a=e.logger.name!==void 0?`@${e.logger}`:"";return`${p(r())}${a} ${s} ${Y[e.level](String(e.message))}${n()}`}function te(e){let t=`[${e.date.toISOString()}]`,r=`[${f[e.level]}]`,n=e.logger.name!==void 0?`[${e.logger.name}] `:"",s=T[e.level];return`${t} ${s} ${r.padEnd(7," ")} ${n}${e.message}`}function re(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var w={sparse:ee,json:S,pretty:I,structured:te,default:re()?I:S},ne=class{formatter;consoleObject;filter;constructor(e=w.default,t=4,r=console){this.filter=t,this.formatter=e,this.consoleObject=r}handle(e){let t=this.formatter(e);switch(e.level){case 1:this.consoleObject.error(t);break;case 2:this.consoleObject.warn(t);break;case 3:this.consoleObject.info(t);break;case 4:this.consoleObject.debug(t);break}}};var o=class{#e;sinks;filter;parent;get name(){return this.#e}constructor(e,t=void 0,r=[],n=void 0){this.#e=t,this.sinks=r,this.filter=e,this.parent=n}log(e,t,r=void 0){let n={date:new Date,level:e,logger:this,message:t,extra:r};this.filter<e||this.insert(n)}insert(e){if(!(this.filter<e.level)){for(let t of this.sinks)t.filter>=e.level&&t.handle(e);this.parent!==void 0&&this.parent.insert(e)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},l=new o(3,void 0,[new ne]),se=o.prototype.log.bind(l,1),oe=o.prototype.log.bind(l,2),ae=o.prototype.log.bind(l,3),ie=o.prototype.log.bind(l,4),ve=o.prototype.log.bind(l);var b=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.blocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"init":this.state=new y(s.workerPort,sampleRate*.02);break;case"close":this.alive=!1;break;case"dump":s.result.postMessage(this.dump());break}}process(r,n,s){if(this.state===void 0||r.length<1||r[0].length<1)return this.alive;let a=this.state.fill(0,r[0][0]);return this.state.offset===this.state.length&&(this.state.flush(),this.state.fill(a,r[0][0])),this.alive}dump(){return{type:"unshared capture worklet",alive:this.alive,sampleRate,offset:this.state?.offset||null,length:this.state?.length||null,blocks:this.blocks}}},x=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.silenceBlocks=0;this.voiceBlocks=0;this.totalBlocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"close":this.alive=!1;break;case"init":this.state=new g(s.workerPort,sampleRate*.02),s.workerPort.onmessage=this.onMessage.bind(this);break;case"samples":this.state?.add(s.id,s.buffer);break;case"dump":s.result.postMessage(this.dump());break}n==="close"&&(this.alive=!1)}process(r,n,s){if(this.state===void 0||n.length<1||n[0].length<2)return this.alive;let a=this.state.fill(0,n[0][0],n[0][1]);return a<u.RenderQuantumSize&&(this.totalBlocks+=1,this.state.next(),this.state.hasVoice?this.voiceBlocks+=1:this.silenceBlocks+=1,this.state.fill(a,n[0][0],n[0][1])),this.alive}dump(){return{type:"unshared playback worklet",alive:this.alive,sampleRate,id:this.state?.id||null,offset:this.state?.offset||null,length:this.state?.length||null,hasVoice:this.state?.hasVoice??!1,silenceBlocks:this.silenceBlocks,voiceBlocks:this.voiceBlocks,totalBlocks:this.totalBlocks}}},y=class{constructor(t,r){this.port=t;this.length=r;this.offset=0,this.buffer=new Float32Array(r)}fill(t,r){let n=Math.min(r.length-t,this.length-this.offset);return this.buffer.set(r.subarray(t,t+n),this.offset),this.offset+=n,t+n}flush(){d(this.port,["captureTick",{buffer:this.buffer}],[this.buffer.buffer]),this.offset=0,this.buffer=new Float32Array(this.length)}},g=class{constructor(t,r){this.port=t;this.length=r;this.cache=[];this.id=-1,this.offset=0,this.buffer=void 0,this.next()}get hasVoice(){return this.buffer!==void 0}fill(t,r,n){let s=Math.min(u.RenderQuantumSize-t,this.length-this.offset);return this.buffer!==void 0&&(r.set(this.buffer.subarray(this.offset,this.offset+s),t),n.set(this.buffer.subarray(this.offset+this.length,this.offset+this.length+s),t)),this.offset+=s,t+s}add(t,r){this.cache.push({id:t,buffer:r})}next(){for(this.id+=1;this.cache[0]?.id<this.id;)this.cache.shift();this.cache[0]?.id===this.id?(this.buffer=this.cache[0].buffer,this.cache.shift()):this.buffer=void 0,this.offset=0,d(this.port,["playbackTick",{}])}};registerProcessor("OdinCaptureProcessor",b);registerProcessor("OdinPlaybackProcessor",x);})();\n'});var _0={};Px(_0,{UnsharedCaptureWorker:()=>Ex,UnsharedPlaybackWorker:()=>fx,createCaptureWorker:()=>DF,createPlaybackWorker:()=>tF});import{Strand as FF}from"@4players/odin-common";function DF(C,j,e,B,v=b.DefaultRefreshRate){return rF.enqueue(async()=>{let[E,f]=await Y(zx,Xx,C,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return console.warn("SharedArrayBuffer is not available; creating ODIN CaptureWorker in fallback mode"),Ex.create(C,j,e,v,E,f,B)})}async function tF(C,j=b.DefaultRefreshRate){if(C.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[e,B]=await Y(zx,Xx,C,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return fx.create(C,j,e,B)}var rF,Ex,fx,L0=p(()=>{"use strict";k();Cx();g0();y0();rF=new FF;Ex=class C extends X{constructor(e,B,v,E,f){super(e,B,v,E,f);this._Activity=_;this._SpeechProbability=0;B.addEventListener("message",this._OnMessages.bind(this))}static async create(e,B,v,E,f,n,i){let{port1:u,port2:y}=new MessageChannel;return c(f,["captureInit",{sampleRate:e.sampleRate,refreshRate:E,workletPort:u}],[u]),await W(f,"captureReady"),c(n.port,["init",{workerPort:y}],[y]),new C(n,f,B,v,i)}get activity(){return this._Activity}get speechProbability(){return this._SpeechProbability}setVolume(e){c(this.worker,["captureSetVolume",{value:e}])}_OnMessages(e){super._OnMessages(e);let[B,v]=e.data;B==="captureUpdate"&&(this._Activity={isSilent:!v.active,rmsDBFS:v.rmsDBFs},this._SpeechProbability=v.speechProbability)}},fx=class C extends z{constructor(e,B,v){super(e,B,v);this.activities=new Float32Array;this.jitterStats=[]}static async create(e,B,v,E){let{port1:f,port2:n}=new MessageChannel;return c(v,["playbackInit",{workletPort:f,refreshRate:B}],[f]),await W(v,"playbackReady"),c(E.port,["init",{workerPort:n}],[n]),E.connect(e.destination),new C(e,E,v)}getActivity(e){let B=this.medias.get(h(e));if(B===void 0)return;let v=this.activities.at(B.index);if(v!==void 0)return v===0?_:{isSilent:!1,rmsDBFS:v}}getJitterStats(e){let B=this.medias.get(h(e));if(B===void 0)return;let v=this.jitterStats.at(B.index);if(v!==void 0)return v}setGlobalVolume(e){c(this.worker,["playbackSetVolume",{index:"global",value:e}])}setVolume(e,B){let v=this.medias.get(h(e));v!==void 0&&c(this.worker,["playbackSetVolume",{index:v.index,value:B}])}_GetFreeIndex(){let e=super._GetFreeIndex();if(e!==void 0)return e;if(this.medias.size<b.MaxNumberOfDecoders)return this.medias.size}_OnMessages(e){super._OnMessages(e);let[B,v]=e.data;B==="playbackUpdate"&&(this.activities=v.activities,this.jitterStats=v.jitterStats)}}});k();import{Backend as t,generateUUID as sr}from"@4players/odin-common";k();import{Backend as F,JITTER_STATS_INITIAL as w0,Strand as fF,assert as nF}from"@4players/odin-common";k();import{APM_DEFAULTS as BF,Backend as iB,generateUUID as vF,VAD_DEFAULTS as CF}from"@4players/odin-common";import{failure as c0,isFirefoxBrowser as OA,sleep as MA,success as TA}from"@4players/odin-common";async function d0(C,j,e){let B;if(j.device?.device.kind==="track"&&j.device?.device.audioTrack)B=new MediaStream([j.device.device.audioTrack]);else{let f=j.device?{exact:j.device.device.deviceId==="default"?void 0:j.device.device.deviceId}:void 0;try{let n=await Promise.race([navigator.mediaDevices.getUserMedia({audio:{echoCancellation:e.echoCanceller,noiseSuppression:e.noiseSuppression!=="None",autoGainControl:e.gainController,echoCancellationType:"system",deviceId:f}}),MA(3e4,"timeout")]);if(n==="timeout")return c0("getUserMedia; timeout");B=n}catch(n){return c0(`getUserMedia; ${n}`)}}let v=B.getAudioTracks()[0].getSettings().sampleRate,E=await C.audioContexts.acquire(v);return TA(E.createMediaStreamSource(B))}function R(C){C.getTracks().forEach(j=>{j.stop(),C.removeTrack(j)})}async function p0(C){return new L({deviceId:C.id,kind:"track",name:C.label??"MediaStreamTrack",audioTrack:C},!1)}async function vx(){if(OA()){let v=await SA("microphone");(v==="granted"||v===!1)&&await RA("audio")}let C=(await navigator.mediaDevices.enumerateDevices()).filter(v=>!!v.label),j=[],e=new L({deviceId:"default",name:"Default",kind:"audioinput"},!0),B=new L({deviceId:"default",name:"Default",kind:"audiooutput"},!0);j.push(e),j.push(B);for(let v of C){if(v.deviceId==="default"){v.kind==="audioinput"&&(e=new L({deviceId:"default",name:v.label,kind:"audioinput"},!0),j[0]=e),v.kind==="audiooutput"&&(B=new L({deviceId:"default",name:v.label,kind:"audiooutput"},!0),j[1]=B);continue}v.kind==="audioinput"&&j.push(new L({deviceId:v.deviceId,name:v.label,kind:"audioinput"},!1)),v.kind==="audiooutput"&&j.push(new L({deviceId:v.deviceId,name:v.label,kind:"audiooutput"},!1))}return j}async function SA(C){try{return(await navigator.permissions.query({name:C})).state}catch{return!1}}async function RA(C){try{let j=await navigator.mediaDevices.getUserMedia({[C]:!0});return j?.getTracks().forEach(e=>{e.stop(),j.removeTrack(e)}),!0}catch{return!1}}k();import{isSafariBrowser as jF,isSharedArrayBufferCapable as eF}from"@4players/odin-common";var H0=eF()&&!jF()?Promise.resolve().then(()=>($0(),I0)):Promise.resolve().then(()=>(L0(),_0));async function N0(C,j,e,B){return H0.then(v=>v.createCaptureWorker(C,j,e,B,b.DefaultRefreshRate))}async function K0(C){return H0.then(j=>j.createPlaybackWorker(C,b.DefaultRefreshRate))}var K=class{constructor(j,e){this.controller=j;this._Medias=new Map;this._Vad={...CF};this._Apm={...BF};this._Volume=1;this._ProcessingDevice=!1;this._DeviceCb=async()=>{(await vx()).some(B=>B.device.deviceId===this._DeviceParameters?.device?.device.deviceId)||(this._DeviceParameters?.onStatusChanged?.("stopped"),navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._DeviceParameters=void 0,this._Capture!==void 0&&(R(this._Capture.source.mediaStream),this._Capture.source.disconnect(this._Capture.worker.worklet)))};e.apm&&this.setApm(e.apm).catch(console.error),e.vad&&this.setVad(e.vad),typeof e.volume<"u"&&this.setVolume(e.volume).catch(console.error),this.uid=vF(),this.#x=e.customType,this.#A=e.ref}#x;#A;get vad(){return this._Vad}get apm(){return this._Apm}get volume(){return this._Volume}get activity(){return this._Capture?.worker.activity??_}get speechProbability(){return this._Capture?.worker.speechProbability??0}get deviceId(){return this._DeviceParameters?.device?.device.deviceId}async start(j,e){let B=this._Medias.get(e.connectionId);B===void 0&&this._Medias.set(e.connectionId,B=new Set),o(`starting audio capture media ${e.mediaId} on connection ${e.connectionId}`),!B.has(e.mediaId)&&(B.add(e.mediaId),j.mainConnection?.id===e.connectionId&&await j.request("StartMedia",{media_id:e.mediaId,properties:{kind:"audio",uid:this.uid,ref:this.#A,customType:this.#x}}).catch(v=>d(`StartMedia got rejected; ${v}`)),this._UpdateMedias())}async stop(j,e){let B=this._Medias.get(e.connectionId);o(`stopping audio capture media ${e.mediaId} on connection ${e.connectionId}`),B?.delete(e.mediaId)&&(j.mainConnection?.id===e.connectionId&&await j.request("StopMedia",{media_id:e.mediaId}).catch(v=>d(`StopMedia got rejected; ${v}`)),this._UpdateMedias())}setVad(j){a("updating vad config",j),this._Vad=j,this._Capture&&this._Capture.worker.setVad(j)}async setApm(j){a("updating apm config",j),this._Apm=j,this._DeviceParameters&&await this.setDevice(this._DeviceParameters)}async setDevice(j){if(a("updating capture device parameters",j),this._ProcessingDevice)return;this._ProcessingDevice=!0;let e=this._DeviceParameters;if(this._DeviceParameters=j,this._Volume==="muted"){this._ProcessingDevice=!1;return}try{let B=await d0(this.controller,j,{...this._Apm,echoCanceller:this._Monitor?!1:this._Apm.echoCanceller});if(B.type!=="Success"){d(`unable to open capture device; ${B.reason}`),this._DeviceParameters=e,this._ProcessingDevice=!1;return}this._DeviceParameters.onStatusChanged&&navigator.mediaDevices.addEventListener("devicechange",this._DeviceCb),this._Capture!==void 0&&(R(this._Capture.source.mediaStream),this._Capture.source.disconnect(this._Capture.worker.worklet)),this._Capture===void 0||this._Capture.worker.worklet.context!==B.value.context?(this._Capture?.worker.close(),this._Capture={worker:await N0(B.value.context,this.controller.sink,this.controller.receiveMonitoredPacket.bind(this.controller),new WeakRef(this)),source:B.value},await this._UpdateMedias(),await this.setVolume(this._Volume),this.setVad(this.vad)):this._Capture.source=B.value,this._Capture.source.connect(this._Capture.worker.worklet)}catch(B){throw this._ProcessingDevice=!1,new Error(`Error in setDevice(); ${B}`)}this._ProcessingDevice=!1}async setVolume(j){a(`updating capture volume to ${j}`),this._Volume=j,j==="muted"?await this.close():(!this._Capture&&this._DeviceParameters&&await this.setDevice(this._DeviceParameters),this._Capture?.worker.setVolume(j)),j!==this._Volume&&await this.setVolume(this._Volume)}async close(){if(a("closing audio capture"),this._Capture!==void 0){this._Capture.worker.close(),R(this._Capture.source.mediaStream);try{this._Capture.source.disconnect(this._Capture.worker.worklet)}catch(j){q("failed to disconnect audio node",j)}await this.controller.audioContexts.release(this._Capture.source.context)}navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._Capture=void 0}async dump(){let j=[];for(let[e,B]of this._Medias)j.push(`${e} => ${Array.from(B.values()).join(",")}`);return{uid:this.uid,ref:this.#A??null,customType:this.#x??null,worker:await this._Capture?.worker.dump()??null,vad:this._Vad,apm:this._Apm,volume:this._Volume,processingSetDevice:this._ProcessingDevice,medias:j}}async _UpdateMedias(){if(this._Capture!==void 0){let j=Array.from(this._Medias).map(([e,B])=>({id:e,mediaIds:Array.from(B)}));this._Capture.worker.setMedias(j)}}async startLoopback(){this._Monitor===void 0&&(a("starting audio capture loopback"),this.setApm(this._Apm),this._Monitor=await this.controller.createAudioPlayback({uid:"loopback"}),this._Monitor.start({connectionId:0,mediaId:0}),this._Medias.set(0,new Set([0])),await this._UpdateMedias())}async stopLoopback(){this._Monitor!==void 0&&(a("stopping audio capture loopback"),this._Monitor.close(),this._Monitor=void 0,this.setApm(this._Apm),this._Medias.delete(0),await this._UpdateMedias())}};import{assert as nx,Backend as A,generateUUID as EF}from"@4players/odin-common";k();var $=class{constructor(j,e){this.controller=j;this.options=e;this.uid=EF()}#x;#A=new Map;#F;get customType(){return this.options?.customType}get mediaStream(){return this.#x}get audioCapture(){return this.#F}get volume(){return nx(this.audioCapture,"getting the volume failed, this video has no Audio"),this.audioCapture.volume}async setVolume(j){nx(this.audioCapture,"setVolume() failed, this video has no Audio"),await this.audioCapture.setVolume(j)}get vad(){return nx(this.audioCapture,"getting the vad config failed, this video has no Audio"),this.audioCapture.vad}setVad(j){nx(this.audioCapture,"setVad() failed, this video has no Audio"),this.audioCapture.setVad(j)}async setDevice(j,e={voiceActivity:void 0,volumeGate:void 0}){if(this.#x)throw new Error("This VideoCapture already has a MediaStream.");if(!j.getVideoTracks()[0])throw new Error("Error when calling setDevice(), MediaStream does not contain a VideoStreamTrack!");if(this.#x=j,j.getAudioTracks()[0]){let v={device:await p0(j.getAudioTracks()[0]),vad:e,ref:this.uid};this.#F=await this.controller.createAudioCapture(v)}}async start(j,e){let B=this.#A.get(e.connectionId);if(B===void 0&&this.#A.set(e.connectionId,B=new Set),!B.has(e.mediaId)&&(B.add(e.mediaId),j.mainConnection?.id===e.connectionId)){let v={kind:"video",codec:this.options?.codec??"H264",ref:this.#F?.uid,uid:this.uid};this.options?.customType&&(v.customType=this.options.customType),await j.request("StartMedia",{media_id:e.mediaId,properties:v}).catch(E=>d(`StartMedia got rejected; ${E}`))}}async stop(j,e){this.#x&&R(this.#x),this.#A.get(e.connectionId)?.delete(e.mediaId)&&j.mainConnection?.id===e.connectionId&&await j.request("StopMedia",{media_id:e.mediaId}).catch(v=>d(`StopMedia got rejected; ${v}`))}async dump(){let j=[];for(let[e,B]of this.#A)j.push(`${e} => ${Array.from(B.values()).join(",")}`);return{uid:this.uid,ref:this.#F?.uid??null,customType:this.customType??null,tracks:this.#x?.getVideoTracks().map(e=>({id:e.id,kind:e.kind,label:e.label,ready:e.readyState,muted:e.muted,settings:{...e.getSettings()}}))??[],volume:this.#F?.volume??0,medias:j}}close(){this.#x&&R(this.#x),this.audioCapture?.close(),this.#F=void 0}};k();import{Backend as bB}from"@4players/odin-common";var H=class{constructor(j,e,B){this.controller=j;this.uid=e;this.customType=B}get volume(){return this.controller.playbackGetVolume(this.uid)}get activity(){return this.controller.playbackGetActivity(this.uid)}get jitterStats(){return this.controller.playbackGetJitterStats(this.uid)}start(j){o(`starting audio playback media ${j.mediaId} on connection ${j.connectionId}`),this.controller.playbackStart(this.uid,j)}stop(j){o(`stopping audio playback media ${j.mediaId} on connection ${j.connectionId}`),this.controller.playbackStop(this.uid,j)}setVolume(j){a(`updating audio playback media '${this.uid}' volume to ${j}`),this.controller.playbackSetVolume(this.uid,j)}close(){a(`closing audio playback media '${this.uid}'`),this.controller.closePlayback(this.uid)}};var sx=class{constructor(j){this.audioContextFactory=j;this.entries=[]}async acquire(j){for(let B of this.entries){if(B.sampleRate===j)return B.references+=1,B.audioContext;if(B.sampleRate===void 0&&B.audioContext.sampleRate===j)return B.references+=1,B.audioContext}let e={sampleRate:j,audioContext:await this.audioContextFactory(j),references:1};return this.entries.push(e),e.audioContext}async release(j){let e=this.entries.findIndex(B=>B.audioContext===j);if(!(e<0)&&(this.entries[e].references-=1,this.entries[e].references<=0)){let B=this.entries[e].audioContext;this.entries.splice(e,1),await B.close()}}close(){for(let j of this.entries)j.audioContext.close()}},ix=class C{constructor(j,e){this.audioContexts=j;this.sink=e;this.audioCaptures=[];this.videoCaptures=[];this.globalVolume=[1,1];this.playbacks=new Map;this.setPlaybackStrand=new fF}async create(j,e){return new C(j,e)}receivePacket(j,e){this.playbackWorker?.receivePacket(j,e)}receiveMonitoredPacket(j,e){let B=e.slice();this.receivePacket(j,B)}async createAudioPlayback(j){let e=this.playbacks.get(j.uid),B=j.volume;if(e===void 0){B=B??[1,1];let v=new H(this,j.uid,j.customType);e={id:void 0,volume:B,playback:v},this.playbacks.set(j.uid,e)}return B!==void 0&&e.playback.setVolume(B),e.playback}async createAudioCapture(j){let e=new K(this,j);return await e.setDevice(j),this.audioCaptures.push(new WeakRef(e)),e}async createVideoCapture(j,e){let B=new $(this,e);return await B.setDevice(j),this.videoCaptures.push(new WeakRef(B)),B}playbackSetDevice(j){return this.setPlaybackStrand.enqueue(async()=>{let e=j?.device.deviceId??"";e==="default"&&(e="");let B;if(this.playbackWorker===void 0){B=await this.audioContexts.acquire(48e3),this.playbackWorker=await K0(B),this.playbackWorker.setGlobalVolume(this.globalVolume);for(let[,v]of this.playbacks)v.id!==void 0&&this.playbackWorker.addMedias(v.id.connectionId,[v.id.mediaId],v.volume)}else B=this.playbackWorker.audioContext;B?.setSinkId!==void 0&&j&&B?.state==="running"&&await B.setSinkId(e)})}playbackSetGlobalVolume(j){this.globalVolume=j,this.playbackWorker?.setGlobalVolume(this.globalVolume)}playbackStart(j,e){let B=this.playbacks.get(j);B!==void 0&&(B.id!==void 0&&this.playbackStop(j,B.id),B.id=e,this.playbackWorker?.addMedias(e.connectionId,[e.mediaId],B.volume))}playbackStop(j,e){let B=this.playbacks.get(j);B!==void 0&&(B.id!==e&&q(`playback media ${e.mediaId} on connection ${e.connectionId} is out of sync`,B.id,e),B.id=void 0,this.playbackWorker?.removeMedias(e.connectionId,[e.mediaId]))}playbackGetActivity(j){let e=this.playbacks.get(j);return e?.id===void 0?_:this.playbackWorker?.getActivity(e.id)??_}playbackGetJitterStats(j){let e=this.playbacks.get(j);return e?.id===void 0?w0:this.playbackWorker?.getJitterStats(e.id)??w0}playbackSetVolume(j,e){let B=this.playbacks.get(j);B!==void 0&&(B.volume=e,B.id!==void 0&&this.playbackWorker?.setVolume(B.id,B.volume))}playbackGetVolume(j){return this.playbacks.get(j)?.volume??[1,1]}closePlayback(j){let e=this.playbacks.get(j);e!==void 0&&(e.id!==void 0&&this.playbackStop(j,e.id),this.playbacks.delete(j))}close(){this.playbackWorker?.close(),this.audioContexts.close()}async dump(){let j=[];for(let v of this.audioCaptures){let E=v.deref();E!==void 0&&j.push(await E.dump())}let e=[];for(let v of this.videoCaptures){let E=v.deref();E!==void 0&&e.push(await E.dump())}let B=[];for(let[v,E]of this.playbacks)B.push({uid:v,id:E.id||null,volume:E.volume});return{globalVolume:this.globalVolume,playbackWorker:await this.playbackWorker?.dump()||null,audioCaptures:j,videoCaptures:e,playbacks:B}}},L=class{constructor(j,e=!1){this.device=j;this.isDefault=e}get type(){switch(this.device.kind){case"audioinput":return"AudioCapture";case"audiooutput":return"AudioPlayback";default:nF(!1,"not supported device")}}get id(){return this.device.deviceId}get name(){return this.device.name}};k();import{nextTick as PF,success as Z0}from"@4players/odin-common";import{decode as OF}from"@msgpack/msgpack";k();import{Backend as x}from"@4players/odin-common";k();import{Backend as r,failure as x0,success as R0,CONNECTION_STATS_INITIAL as pF}from"@4players/odin-common";k();import{failure as Qx,success as Yx}from"@4players/odin-common";import{MessagePackRpcSchema as sF,parseRequest as J0,parseResponse as iF}from"@4players/odin-common/api";import{encode as bF,decode as oF}from"@msgpack/msgpack";var M=class{constructor(j){this.stream=j;this._SendQueue=[];this._RecvQueue=[];this._EventQueue=[];this._Requests=new Map;this._Close=new AbortController;this._NextId=1;j instanceof WebSocket?(j.addEventListener("open",this._OnWebSocketOpen.bind(this)),j.addEventListener("close",this.close.bind(this)),j.addEventListener("message",e=>this._OnRpcMessage(e.data)),j.binaryType="arraybuffer"):(lF(j.readable.getReader(),this._OnRpcMessage.bind(this)).finally(this.close.bind(this)),this._Writer=j.writable.getWriter()),this._Close.signal.addEventListener("abort",this._Cleanup.bind(this),{once:!0})}get closed(){return this._Close.signal.aborted}get closeSignal(){return this._Close.signal}async request(j,e,B){if(this.closed)return Promise.resolve("closed");let v=this._NextId,E=B===void 0?void 0:setTimeout(()=>this._TimeoutRequest(v),B);return this._Send([0,v,j,e]),new Promise(f=>{this._Requests.set(v,{accept:f,timeoutId:E}),this._NextId+=1})}notify(j,e){this.closed||this._Send([2,j,e])}recv(){if(this.closed)return Promise.resolve("closed");let j=this._EventQueue.shift();return j!==void 0?Promise.resolve(j):new Promise(e=>this._RecvQueue.push(e))}close(){this._Close.abort()}_TimeoutRequest(j){let e=this._Requests.get(j);e!==void 0&&(this._Requests.delete(j),clearTimeout(e.timeoutId),e.accept("timeout"))}_Send(j){let e;j instanceof Uint8Array?e=j:e=new Uint8Array(bF(j,{ignoreUndefined:!0,forceFloat32:!0})),this.stream instanceof WebSocket?this.stream.send(e):this._Writer.write(e)}_OnWebSocketOpen(j){for(let e of this._SendQueue)this._Send(e);this._SendQueue.length=0}_OnRpcMessage(j){let e=aF(j);if(e.type!=="Success"){this.close();return}switch(e.value[0]){case 0:this._Send([1,e.value[1],"not supported",null]);break;case 1:this._OnResponse(e.value[1],e.value[2],e.value[3]);break;case 2:this._OnEvent(e.value[1],e.value[2]);break}}_OnResponse(j,e,B){let v=this._Requests.get(j);v!==void 0&&(clearTimeout(v.timeoutId),v.accept(e===null?Yx(B):Qx(e)))}_OnEvent(j,e){let B=this._RecvQueue.shift();B!==void 0?B({name:j,properties:e}):this._EventQueue.push({name:j,properties:e})}_Cleanup(){for(let j of this._Requests.values())clearTimeout(j.timeoutId),j.accept("closed");this._Requests.clear();for(let j of this._RecvQueue)j("closed");this._RecvQueue.length=0,this._SendQueue.length=0,this.stream instanceof WebSocket?this.stream.close():this._Writer?.close().catch(()=>{})}},V=class{constructor(j,e,B){this.rpc=j;this._Commands=e;this._Events=B}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(j,e,B){e=J0(j,e,this._Commands);let v=await this.rpc.request(j,e,B);if(v==="closed"||v==="timeout"||v.type==="Failure")return v;let E=iF(j,v.value,this._Commands);return E!==void 0?Yx(E):Qx("response schema failed validation")}notify(j,e){e=J0(j,e,this._Commands),this.rpc.notify(j,e)}async recv(){let j=await this.rpc.recv();if(j==="closed")return j;let e=Zx(this._Events,j);return e!==void 0?e:(P0(this._Events,j.name)?(d(`schema validation for ${j.name} failed; closing connection`),this.rpc.close()):q(`dropping unknown event ${j.name}`),"closed")}close(){this.rpc.close()}};function aF(C){try{return Yx(sF.parse(oF(new Uint8Array(C))))}catch(j){return Qx(String(j))}}function Zx(C,j){if(!P0(C,j.name))return;let e=C[j.name].safeParse(j.properties);if(e.success)return{name:j.name,properties:e.data}}function P0(C,j){return j in C}async function lF(C,j){let e=new Uint8Array;for(;;){let B=b0(e,0);if(B===s){C.cancel("protocol violation");break}if(B!==G&&B<=e.length){j(e.subarray(0,B)),e=e.subarray(B);continue}let v;try{v=await C.read()}catch{break}if(v.done)break;e=uF(e,v.value)}e.length>0&&q("unprocessed bytes left in rpc stream",e)}function uF(C,j){if(C.length===0)return j;if(j.length===0)return C;let e=new Uint8Array(C.length+j.length);return e.set(C,0),e.set(j,C.length),e}k();import{failure as bx,fromBase64Url as kF,success as cF}from"@4players/odin-common";import{TokenClaimsSchema as dF}from"@4players/odin-common/api";var g=class C{constructor(j,e){this.text=j;this.claims=e;if(e.ups!==void 0){let B=C.parse(e.ups);B.type==="Success"?this._Upstream=B.value:d(`upstream in token can not be parsed; ${B.reason}`)}}static parse(j){let e=j.split(".");if(e.length!==3)return bx("expected three segments");let B=kF(e[1]);if(B.type==="Failure")return bx(`invalid token; ${B.reason}`);let v;try{v=JSON.parse(B.value)}catch(f){return bx(`invalid token; ${f}`)}let E=dF.safeParse(v);return E.success===!1?bx(`invalid token; ${E.error}`):cF(new C(j,E.data))}get timeLeft(){return this.claims.exp===void 0?1/0:this.claims.exp*1e3-Date.now()}get upstream(){return this._Upstream}get defaultRoomId(){return Array.isArray(this.claims.rid)?this.claims.rid.length===1?this.claims.rid[0]:void 0:this.claims.rid}hasAudience(j){return this.claims.aud===void 0&&j==="gateway"?!0:Array.isArray(this.claims.aud)?this.claims.aud.includes(j):this.claims.aud===j}toString(){return this.text}};k();import{VideoCodec as O0,assert as ox,Backend as oB}from"@4players/odin-common";function M0(C){typeof globalThis.rtcDataChannels>"u"&&(globalThis.rtcDataChannels=[]),Array.isArray(globalThis.rtcDataChannels)&&globalThis.rtcDataChannels.length<=100&&globalThis.rtcDataChannels.push(C)}function T0(C){let j=globalThis.rtcDataChannels?.indexOf(C);j!==void 0&&j>=0&&globalThis.rtcDataChannels.splice(j,1),C.readyState!=="closed"&&C.close()}function ax(C){typeof globalThis.rtcPeerConnections>"u"&&(globalThis.rtcPeerConnections=[]),Array.isArray(globalThis.rtcPeerConnections)&&globalThis.rtcPeerConnections.length<=100&&globalThis.rtcPeerConnections.push(C)}function S0(C){let j=globalThis.rtcPeerConnections?.indexOf(C);j!==void 0&&j>=0&&globalThis.rtcPeerConnections.splice(j,1),C.connectionState!=="closed"&&C.close()}var Z=class{constructor(j,e){this._localVideos=new Map;this._remoteVideos=new Map;this._negotiation={requested:!1,running:!1,waitForAnswer:!1};this._peerConnection=j,this._signaling=e,this._peerConnection.ontrack=this._onTrack.bind(this),this._peerConnection.onconnectionstatechange=()=>this._onStatusChanged.bind(this),this._peerConnection.onicecandidate=async B=>{B.candidate?await this._signaling.sendIceCandidate(B.candidate):await this._signaling.sendIceComplete()}}requestNegotiation(j){this._negotiation.requested=!0,j&&(this._negotiation.waitForAnswer=!0),!this._negotiation.running&&(this._negotiation.running=!0,setTimeout(async()=>{let e=this._negotiation.waitForAnswer;this._negotiation.requested=!1,this._negotiation.waitForAnswer=!1;try{let B;e&&(B=new Promise(v=>{this._resolveOffer=v})),await this._sendOffer(),B&&await B}catch(B){d("negotiation failed during sdp offer/answer exchange",B)}finally{this._resolveOffer=void 0,this._negotiation.running=!1,this._negotiation.requested&&this.requestNegotiation(this._negotiation.waitForAnswer)}}))}async startLocalVideo(j,e,B="H264"){if(this._localVideos.has(j))return;o(`starting local video for media ${j}`);let v=this._peerConnection.getTransceivers().find(n=>n.sender.track===e);if(v)await v.sender.replaceTrack(e);else{let n=this._peerConnection.addTrack(e);v=this._peerConnection.getTransceivers().find(i=>i.sender===n),ox(v,"failed to create transceiver for local video")}let f=new O0(B).isSupported();f&&v.setCodecPreferences([f]),this._localVideos.set(j,{transceiver:v}),this.requestNegotiation(!0)}stopLocalVideo(j){let e=this._localVideos.get(j);e&&(o(`stopping local video for media ${j}`),this._localVideos.delete(j),e.transceiver.sender.track&&(e.transceiver.sender.track.enabled=!1),e.transceiver.direction="inactive",this.requestNegotiation(!1))}startRemoteVideo(j,e="H264"){o(`starting remote video for media ${j}`);let B=this._peerConnection.addTransceiver("video"),E=new O0(e).isSupported();E&&B.setCodecPreferences([E]);let f=new Promise((n,i)=>{this._remoteVideos.set(j,{state:"Requested",transceiver:B,promise:{resolve:n,reject:i}})});return this.requestNegotiation(!0),f}stopRemoteVideo(j){let e=this._remoteVideos.get(j);e&&(o(`stopping remote video for media ${j}`),this._remoteVideos.delete(j),e.state!=="Active"&&e.promise.reject(new Error("video stopped")),this.requestNegotiation(!1))}async handleWebRtcUpdate(j){switch(j.kind){case"Sdp":await this._updateRemoteSdp(j.type==="Answer"?"answer":"offer",j.sdp,j.media_map);break;case"Trickle":this._addIceCandidate({candidate:j.candidate,sdpMid:j.spd_mid??void 0,sdpMLineIndex:j.spd_mline_index??void 0,usernameFragment:j.username_fragment??void 0});break;case"TrickleFinished":this._addIceCandidate(void 0);break}}async startup(){if(this._peerConnection.connectionState==="new")try{let j=await this._peerConnection.createOffer();ox(j.type==="offer"&&j.sdp,"generated broken webrtc offer"),await this._peerConnection.setLocalDescription(j),await this._signaling.sendOffer(j.sdp,[])}catch{d("failed to create initial sdp offer")}}cleanup(){for(let[,j]of this._remoteVideos)j.state!=="Active"&&j.promise.reject(new Error("connection closed"));clearTimeout(this._WebRtcIceTimeout),clearTimeout(this._WebRtcTimeout),this._localVideos.clear(),this._remoteVideos.clear()}get peerConnection(){return this._peerConnection}get localVideos(){return this._localVideos}get remoteVideos(){return this._remoteVideos}get isNegotiating(){return this._negotiation.running}_addIceCandidate(j){j&&(j.sdpMid===void 0&&j.sdpMLineIndex===void 0&&(j={...j,sdpMid:"0"}),a(`adding new ice ${j.candidate}`,j)),this._peerConnection.addIceCandidate(j)}async _sendOffer(){try{let j=await this._peerConnection.createOffer();ox(j.type==="offer"&&j.sdp,"generated broken payload"),await this._peerConnection.setLocalDescription(j);let e=[];for(let[B,{transceiver:v}]of this._localVideos)v.mid&&e.push([B,v.mid]);for(let[B,v]of this._remoteVideos)v.state!=="Active"&&v.transceiver.mid&&e.push([B,v.transceiver.mid]);await this._signaling.sendOffer(j.sdp,e)}catch(j){throw d("failed to send sdp offer",j),j}}async _updateRemoteSdp(j,e,B){for(let[v,E]of B){let f=this._remoteVideos.get(v);f?.state==="Requested"&&(this._remoteVideos.set(v,{state:"Mapped",transceiver:f.transceiver,mid:E,promise:f.promise}),a(`updated remote video list with media ${v}`,f,this._remoteVideos))}await this._peerConnection.setRemoteDescription({type:j,sdp:e}),this._resolveOffer?.(!0)}async _onStatusChanged(){switch(a(`peer connection state changed to ${this._peerConnection.connectionState}`),this._peerConnection.connectionState){case"closed":case"failed":await this._signaling.closeConnection();break;case"connected":clearTimeout(this._WebRtcIceTimeout),this._WebRtcIceTimeout=void 0,clearTimeout(this._WebRtcTimeout),this._WebRtcTimeout=void 0;break;case"disconnected":b.MainConnectionPingInterval!==void 0&&await this._signaling.checkConnection();default:this._WebRtcIceTimeout===void 0&&(this._WebRtcIceTimeout=setTimeout(()=>{a("ice connection timeout was reached"),this._peerConnection.restartIce(),this._WebRtcIceTimeout=void 0},b.WebRtcIceTimeout)),this._WebRtcTimeout===void 0&&(this._WebRtcTimeout=setTimeout(async()=>{a("peer connection timeout was reached"),await this._signaling.closeConnection()},b.WebRtcTimeout));break}}_onTrack(j){let e=Array.from(this._remoteVideos).find(([,E])=>E.state==="Mapped"&&E.mid===j.transceiver.mid);if(!e){q(`unexpected track with mid: ${j.transceiver.mid}`);return}let[B,v]=e;ox(v.state==="Mapped","expected video state to be Mapped"),this._remoteVideos.set(B,{state:"Active",transceiver:j.transceiver}),a(`updated local video list with media ${B}`,e,j.transceiver,this._localVideos),j.track.onended=()=>{a(`video track with mid ${j.transceiver.mid} ended`,e)},v.promise.resolve(j.track)}};import{MainCommandsRpc as hF,MainNotificationsRpc as qF,RoomCommandsRpc as mF,RoomNotificationsRpc as GF}from"@4players/odin-common/api";var lx=class C{constructor(j,e,B,v,E,f){this.id=j;this.address=e;this.connection=v;this.rpc=E;this.closeController=f;this._ConnectionStats={...pF};this._WebRtcSessionFlight=new S;this._PingFlight=new S;this.status=0;this._ClosePromise=(async()=>{try{await this.connection.closed}catch{}return"closed"})(),b.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(b.HealthCheckTimeout)},b.MainConnectionPingInterval)),f.signal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this.datagramWriter=v.datagrams.writable.getWriter(),this.connection.closed.then(()=>{this.status=2}).catch(()=>{}),this.connection.ready.then(()=>{this.status=1}).catch(()=>{}),this.readDatagrams(this.connection,this.id,(n,i)=>{this._ConnectionStats.packetsReceived+=1,B(n,i)})}static async create(j,e,B,v){try{let E=new URL(`https://${e}?version=${a0}&uid=${ux}`),f=new AbortController;v.addEventListener("abort",()=>f.abort(),{once:!0});let n=new WebTransport(E);f.signal.addEventListener("abort",()=>{try{n.close()}catch{}},{once:!0}),await n.ready;let i=await n.createBidirectionalStream(),u=new V(new M(i),hF,qF);return f.signal.addEventListener("abort",()=>u.close(),{once:!0}),u.notify("Hello",{stream:"main"}),R0(new C(j,e,B,n,u,f))}catch(E){return x0(`connecting to ${e} failed with ${E}`)}}get connectionStats(){return this._ConnectionStats}get transport(){return"H3"}get closePromise(){return this._ClosePromise}get closeSignal(){return this.closeController.signal}get closed(){return this.closeSignal.aborted}waitForConnected(){return Promise.race([this.connection.ready,this.connection.closed.then(()=>{throw new Error("connection closed")})])}close(){o(`closing connection to '${this.address}' with id ${this.id}`),this.closeController.abort("request")}async joinRoom(j,e,B,v){try{if(this.closed)return"closed";let E=await this.connection.createBidirectionalStream().catch(()=>"closed");if(E==="closed")return"closed";let f=new V(new M(E),mF,GF),n=await f.request("Hello",{stream:"room",token:String(j),room_id:e,user_data:B,position:v});return n==="closed"||n.type==="Failure"?n:R0(f.rpc)}catch(E){return x0(`JoinRoom failed; ${E}`)}}async getReconnectToken(j){let e=await this._Request("RequestReconnectToken",{peer_id:j});return e.type==="Failure"?e:g.parse(e.value)}async healthCheck(){let j=await this._RequestPing(b.HealthCheckTimeout);return j||this.close(),j}async ping(j=3e4){let e=Date.now();return await this._RequestPing(j)?Date.now()-e:0}sendDatagram(j){try{this.datagramWriter.write(j),this._ConnectionStats.packetsSent+=1;let e=j.byteLength;this.connectionStats.bytesSent+=e}catch{}}async readDatagrams(j,e,B){try{let v=j.datagrams.readable.getReader();for(;;){let E=await v.read();if(E.done)break;let f=E.value.byteLength;this.connectionStats.bytesReceived+=f,B(e,E.value)}}catch{}}_CleanUp(){a(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId)}async _EnsureWebRtcSession(){return this._WebRtcSession?this._WebRtcSession:this._WebRtcSessionFlight.run(async()=>(this._PeerConnection=new RTCPeerConnection,ax(this._PeerConnection),this._WebRtcSession=new Z(this._PeerConnection,{sendOffer:async(j,e)=>{await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:j,media_map:e})},sendIceCandidate:async j=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:j.candidate,spd_mid:j.sdpMid??void 0,spd_mline_index:j.sdpMLineIndex??void 0,username_fragment:j.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async()=>{this.close()},checkConnection:async()=>{this.healthCheck().then()}}),this._HandleWebRtcUpdates(),this._WebRtcSession))}async _HandleWebRtcUpdates(){for(;;){let j=await this.rpc.recv();if(j==="closed")break;j.name==="WebRtcUpdate"&&this._WebRtcSession?.handleWebRtcUpdate(j.properties)}this.close()}async _Request(j,e,B){let v=Date.now(),E=await(B===void 0?this.rpc.request(j,e):this.rpc.request(j,e,B)),f=(Date.now()-v)/1e3;return j!=="Ping"&&a(`sent main rpc '${j}'; took: ${f}s`,{properties:e,timeout:B,result:E}),E==="closed"?x0("connection lost"):E}_RequestPing(j=3e4){return this._PingFlight.run(async()=>{let e=await this._Request("Ping",{},j);return e!=="timeout"&&e.type==="Success"})}async startLocalVideo(j,e,B="H264"){await(await this._EnsureWebRtcSession()).startLocalVideo(j,e,B)}stopLocalVideo(j){this._WebRtcSession?.stopLocalVideo(j)}async startRemoteVideo(j,e="H264"){return(await this._EnsureWebRtcSession()).startRemoteVideo(j,e)}stopRemoteVideo(j){this._WebRtcSession?.stopRemoteVideo(j)}async dump(){return{type:"H3",id:this.id,address:this.address,closed:this.closed,status:this.status,datagrams:{sent:this._ConnectionStats.packetsSent,received:this._ConnectionStats.packetsReceived}}}};k();import{Backend as D,extendUrl as U0,failure as kx,success as W0,fail as _F,CONNECTION_STATS_INITIAL as LF}from"@4players/odin-common";k();import{abortableSleep as IF,failure as rx,success as $F}from"@4players/odin-common";async function A0(C,j){let e=performance.now(),B=rx("no connection was attempted");for(let v=0;v<b.ConnectInterval.length&&!j.aborted;v++){let E=e+yF(v);if(await IF(E-performance.now(),j)==="aborted")return rx("aborted");if(B=await gF(C,j),B.type==="Success")return B}return B}async function gF(C,j){let e;try{e=new WebSocket(C)}catch(i){return rx(`unable to create websocket; ${i}`)}let B=new AbortController,v=new Promise(i=>e.addEventListener("open",()=>i($F(e)),{signal:B.signal})),E=new Promise(i=>e.addEventListener("close",u=>i(rx(u.reason!==""?u.reason:"unable to establish websocket connection")),{signal:B.signal})),f=new Promise(i=>j.addEventListener("abort",()=>i(rx("aborted")),{signal:B.signal})),n=await Promise.race([v,E,f]);return B.abort(),n}function yF(C){let j=b.ConnectInterval.slice(0,C).reduce((B,v)=>B+v,0),e=b.ConnectInterval[C]*Math.random();return j+e}import{MainCommandsRpc as HF,MainNotificationsRpc as NF}from"@4players/odin-common/api";var cx=class C{constructor(j,e,B,v,E,f){this.id=j;this.address=e;this.url=B;this.onDatagram=v;this.connection=E;this.webRtc=f;this._PeerIdMap=new WeakMap;this._ConnectionStats={...LF};this._PingFlight=new S;o(`creating new webrtc connection to '${this.address}' with id ${this.id}`),this.closeSignal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this._ClosePromise=new Promise(n=>{this.closeSignal.addEventListener("abort",()=>{n("closed")},{once:!0})}),ax(f),this._AudioChannel=this.webRtc.createDataChannel("audio",{id:2,negotiated:!0,ordered:!1,maxRetransmits:0}),this._AudioChannel.binaryType="arraybuffer",this._AudioChannel.onmessage=n=>{this._ConnectionStats.packetsReceived++;let i=new Uint8Array(n.data);this._ConnectionStats.bytesReceived+=i.byteLength,this.onDatagram(this.id,i)},this._AudioChannel.onerror=n=>q(`webrtc audio data channel for connection with id ${j} raised an error`,n),this._AudioChannel.onclosing=n=>o(`webrtc audio data channel for connection with id ${j} begins shutting down`,n),this._AudioChannel.onclose=n=>o(`webrtc audio data channel for connection with id ${j} has closed`,n),M0(this._AudioChannel),this._WebRtcSession=new Z(this.webRtc,{sendOffer:async(n,i)=>{await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:n,media_map:i})},sendIceCandidate:async n=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:n.candidate,spd_mid:n.sdpMid??void 0,spd_mline_index:n.sdpMLineIndex??void 0,username_fragment:n.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async()=>{this.close()},checkConnection:async()=>{this.healthCheck().then()}}),this._WebRtcSession.startup(),b.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(b.HealthCheckTimeout)},b.MainConnectionPingInterval)),this._HandleWebRtcUpdates()}static async create(j,e,B,v){if(v.aborted)return kx("aborted");let E;try{E=new URL(`wss://${e}`)}catch(u){return _F(`address in token(${e}) can not be parsed; ${u}`)}let f=U0(E,`main?uid=${ux}`);if(f.type!=="Success")return f;let n=await A0(f.value,v);if(n.type!=="Success")return n;let i=new V(new M(n.value),HF,NF);try{return W0(new C(j,e,E,B,i,new RTCPeerConnection))}catch(u){return i.close(),kx(`unable to create webrtc connection; ${u}`)}}get status(){switch(this.webRtc.connectionState){case"connected":return 1;case"failed":case"closed":return 2;default:return 0}}get connectionStats(){return this._ConnectionStats}get transport(){return"WebRTC"}get closePromise(){return this._ClosePromise}get closeSignal(){return this.connection.closeSignal}get closed(){return this.connection.closed}async waitForConnected(){return new Promise((j,e)=>{let B=()=>{let v=this.status;v!==0&&(this.webRtc.removeEventListener("connectionstatechange",B),v===1?j():e(new Error("connection closed")))};this.webRtc.addEventListener("connectionstatechange",B),B(),this.closePromise.then(()=>{e(new Error("connection closed"))})})}close(){o(`closing ${this.transport} connection to '${this.address}' with id ${this.id}`),this.connection.close()}async joinRoom(j,e,B,v){let E=await this.connection.request("JoinRoom",{token:String(j),room_id:e,user_data:B,position:v});if(E==="closed"||E.type==="Failure")return E;let f=E.value;if(!("token"in f))return kx("JoinRoom responded without token");let n=U0(this.url,`room?token=${f.token}`);if(n.type==="Failure")return n;let i=await A0(n.value,this.closeSignal);return i.type==="Success"?(this._PeerIdMap.set(i.value,f.peer_id),W0(new M(i.value))):i}async getReconnectToken(j){let e=await this._Request("RequestReconnectToken",{peer_id:j});return e.type==="Failure"?e:g.parse(e.value)}async healthCheck(){let j=await this._RequestPing(b.HealthCheckTimeout);return j||this.close(),j}async ping(j=3e4){let e=Date.now();return await this._RequestPing(j)?Date.now()-e:0}sendDatagram(j){if(this._AudioChannel.readyState==="open"){let e=j.byteLength;this._AudioChannel.send(j),this._ConnectionStats.packetsSent+=1,this._ConnectionStats.bytesSent+=e}}_CleanUp(){a(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId),T0(this._AudioChannel),S0(this.webRtc),this._WebRtcSession.cleanup(),this.connection.close()}async _HandleWebRtcUpdates(){for(;;){let j=await this.connection.recv();if(j==="closed")break;j.name==="WebRtcUpdate"&&this._WebRtcSession.handleWebRtcUpdate(j.properties)}this.close()}async _Request(j,e,B){let v=Date.now(),E=await(B===void 0?this.connection.request(j,e):this.connection.request(j,e,B)),f=(Date.now()-v)/1e3;return j!=="Ping"&&a(`sent main rpc '${j}'; took: ${f}s`,{properties:e,timeout:B,result:E}),E==="closed"?kx("connection lost"):E}_RequestPing(j=3e4){return this._PingFlight.run(async()=>{let e=await this._Request("Ping",{},j);return e!=="timeout"&&e.type==="Success"})}async startLocalVideo(j,e,B="H264"){await this._WebRtcSession.startLocalVideo(j,e,B)}stopLocalVideo(j){this._WebRtcSession.stopLocalVideo(j)}async startRemoteVideo(j,e="H264"){return this._WebRtcSession.startRemoteVideo(j,e)}stopRemoteVideo(j){this._WebRtcSession.stopRemoteVideo(j)}async dump(){return{type:"WebRtc",id:this.id,address:this.address,url:this.url.toString(),closed:this.closed,audioChannel:{readyState:this._AudioChannel.readyState,bufferedAmount:this._AudioChannel.bufferedAmount},datagrams:{sent:this.connectionStats.packetsSent,received:this.connectionStats.packetsReceived},webRtc:{signalingState:this.webRtc.signalingState,connectionState:this.webRtc.connectionState,iceGatheringState:this.webRtc.iceGatheringState,iceConnectionState:this.webRtc.iceConnectionState}}}};function z0(C,j,e,B,v){switch(o(`creating ${j} main connection to '${e}'`),j){case"H3":return lx.create(C,e,B,v);case"WebRTC":return cx.create(C,e,B,v);default:throw new Error(`transport ${j} is not supported`)}}import{Backend as aB,failure as Y0,success as KF}from"@4players/odin-common";import{parseCommand as wF,parseNotification as JF,RoomCommandsRpc as X0,RoomNotificationsRpc as Q0}from"@4players/odin-common/api";k();var dx=class{constructor(j,e,B,v){this.id=j;this.connection=e;this.cipher=B;this.mediaMap=v;this._DatagramReceived=0;this._DatagramSent=0;this._DatagramReceivedInvalid=0;this._DatagramSentInvalid=0;e.closeSignal.addEventListener("abort",()=>this.close())}get connectionStats(){return this.connection.connectionStats}get transport(){return this.connection.transport}get address(){return this.connection.address}get status(){return this.closed?2:this.connection.status}get closePromise(){return this.connection.closePromise}get closeSignal(){return this.connection.closeSignal}get closed(){return this.connection.closed}waitForConnected(){return this.connection.waitForConnected()}close(){this.connection.close()}async joinRoom(j,e,B,v){this.cipher.reset();let E=await this.cipher.encryptUserData(B);if(E===s)return Y0("unable to encrypt initial user-data");let f=await this.connection.joinRoom(j,e,E,v);return f==="closed"||f.type==="Failure"?f:KF(new F0(f.value,this.cipher,this))}getReconnectToken(j){return this.connection.getReconnectToken(j)}healthCheck(){return this.connection.healthCheck()}async sendDatagram(j){let e=await this.cipher.encryptDatagram(j);e!==s?(this._DatagramSent+=1,this.connection.sendDatagram(e)):this._DatagramSentInvalid+=1}async decryptDatagram(j,e){let B=await this.cipher.decryptDatagram(j,e);return B!==s?this._DatagramReceived+=1:this._DatagramReceivedInvalid+=1,B}startLocalVideo(j,e){return this.connection.startLocalVideo(j,e)}stopLocalVideo(j){return this.connection.stopLocalVideo(j)}startRemoteVideo(j){return this.connection.startRemoteVideo(j)}stopRemoteVideo(j){return this.connection.stopRemoteVideo(j)}async dump(){return{type:"Encrypted",id:this.id,address:this.address,connectionId:this.connection.id,closed:this.closed,transport:this.transport,datagrams:{sent:this._DatagramSent,received:this._DatagramReceived,sentInvalid:this._DatagramSentInvalid,receivedInvalid:this._DatagramReceivedInvalid},cipher:await this.cipher.dump()}}},px=class{constructor(j){this.room=j}resendUserData(){this.room.roomConnection?.notify("UpdatePeer",{user_data:this.room.roomConnection.userData})}setUserData(j,e){let B={kind:"UserDataChanged",peer_id:j,user_data:e};this.room.onEvent("PeerUpdated",B)}},F0=class{constructor(j,e,B){this.rpc=j;this.cipher=e;this.connection=B;this.peers=new Map;this.closeSignal.addEventListener("abort",this.cleanup.bind(this),{once:!0})}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(j,e,B){let v=await this.outgoing(j,e);return v===s?Y0("can not be encrypted"):await this.rpc.request(j,v,B)}async notify(j,e){let B=await this.outgoing(j,e);if(B!==s)return this.rpc.notify(j,B)}async recv(){for(;;){let j=await this.rpc.recv();if(j==="closed")return j;let e=await this.incoming(j.name,j.properties);if(e!==s)return{name:j.name,properties:e}}}close(){return this.rpc.close()}async outgoing(j,e){if(!(j in X0))return e;let B=wF(j,e,X0);if(B===void 0)return s;switch(B.name){case"UpdatePeer":{let v=await this.cipher.encryptUserData(B.request.user_data);if(v===s)return s;B.request.user_data=v}break;case"SendMessage":{let v=await this.cipher.encryptMessage(B.request.message);if(v===s)return s;B.request.message=v}break}return B.request}async incoming(j,e){if(!(j in Q0))return e;let B=JF(j,e,Q0);if(B===void 0)return s;switch(B.name){case"RoomUpdated":for(let v=0;v<B.properties.updates.length;v++){let E=await this.roomUpdate(B.properties.updates[v]);if(E===s)return s;B.properties.updates[v]=E}break;case"PeerUpdated":{let v=await this.peerUpdate(B.properties);if(v===s)return s;B.properties=v}break;case"MessageReceived":{let v=await this.cipher.decryptMessage(B.properties.sender_peer_id,B.properties.message);if(v===s)return s;B.properties.message=v}break}return B.properties}async peerUpdate(j){switch(j.kind){case"UserDataChanged":{let e=await this.cipher.decryptUserData(j.peer_id,j.user_data);if(e===s)return s;j.user_data=e}break;case"MediaStarted":this.mediaStarted(j.peer_id,j.media.id);break;case"MediaStopped":this.mediaStopped(j.peer_id,j.media_id);break}return j}async roomUpdate(j){switch(j.kind){case"Joined":for(let e of j.room.peers){for(let v of e.medias)this.mediaStarted(e.id,v.id);let B=await this.cipher.decryptUserData(e.id,e.user_data);B!==s?e.user_data=B:e.user_data=new Uint8Array}break;case"PeerJoined":{for(let B of j.peer.medias)this.mediaStarted(j.peer.id,B.id);let e=await this.cipher.decryptUserData(j.peer.id,j.peer.user_data);e!==s?j.peer.user_data=e:j.peer.user_data=new Uint8Array}break;case"PeerLeft":{let e=this.peers.get(j.peer_id);this.peers.delete(j.peer_id);for(let B of e??[])this.mediaStopped(j.peer_id,B)}break}return j}mediaStarted(j,e){let B=this.peers.get(j);B===void 0&&(B=new Set,this.peers.set(j,B)),B.add(e);let v=h({connectionId:this.connection.connection.id,mediaId:e});this.connection.mediaMap.set(v,{peerId:j,connection:this.connection})}mediaStopped(j,e){this.peers.get(j)?.delete(e);let v=h({connectionId:this.connection.connection.id,mediaId:e});this.connection.mediaMap.delete(v)}cleanup(){for(let[j,e]of this.peers)for(let B of e)this.mediaStopped(j,B)}};var hx=class{constructor(j){this.onDatagram=j;this._LastConnectionId=0;this._Connections=new Map;this._Close=new AbortController;this._MediaMap=new Map;let e=Date.now(),B=setInterval(()=>{Math.abs(Date.now()-e)>b.ClockJumpThreshold&&this.checkHealth(),e=Date.now()},b.ClockJumpCheckInterval);addEventListener("offline",()=>this.checkHealth(),{signal:this._Close.signal}),this._Close.signal.addEventListener("abort",()=>{clearInterval(B);for(let v of this._Connections.values())v.type==="establishing"?v.abort.abort():v.connection.close();this._Connections.clear()},{once:!0})}get closed(){return this._Close.signal.aborted}sendDatagram(j,e){let B=this._Connections.get(j);(B?.type==="established"||B?.type==="virtual")&&B.connection.sendDatagram(e)}async recvDatagram(j,e){let B=MF(e);if(B===void 0||B.length===0)return;let v=this._MediaMap.get(h({connectionId:j,mediaId:B[0]}));if(v===void 0)this.onDatagram(j,e);else{let E=await v.connection.decryptDatagram(v.peerId,e);if(E===s)return;this.onDatagram(v.connection.id,E)}}async acquireConnection(j,e,B,v){if(await PF(),this.closed)return"closed";let E=this.findConnection(j,e),f;switch(E?.type){case"established":a(`reusing existing connection ${E.id}`),f=E;break;case"establishing":{a(`waiting for connecting to '${e}' finish`);let u=await E.finished;if(u.type!=="Success")return u;f=u.value}break;case void 0:{a(`connecting to '${e}'`);let u=await this.createConnection(j,e,v);if(u.type!=="Success")return u;f=u.value}break}let n=f.id,i=new r0(f.connection,()=>this.releaseConnection(n));return f.references+=1,B&&(i=new dx(++this._LastConnectionId,i,B,this._MediaMap),this.addConnection({type:"virtual",id:i.id,connection:i,createdAt:Date.now()})),Z0(i)}async createConnection(j,e,B){let v=++this._LastConnectionId,E=Date.now(),f=new AbortController;B.addEventListener("abort",()=>f.abort(),{once:!0}),a(`creating new connection ${v}`);let n=z0(v,j,e,this.recvDatagram.bind(this),B),{promise:i,resolve:u}=Promise.withResolvers();this.addConnection({type:"establishing",id:v,address:e,transport:j,finished:i,createdAt:Date.now(),abort:f});let y=await n;if(this._Connections.delete(v),y.type!=="Success")return u(y),y;let U={type:"established",id:v,address:e,transport:j,createdAt:E,references:0,connection:y.value};return this.addConnection(U),Z0(U)}addConnection(j){(j.type==="established"||j.type==="virtual")&&j.connection.closeSignal.addEventListener("abort",()=>{o(`connection ${j.id} has been closed`),this._Connections.delete(j.id)},{once:!0}),this._Connections.set(j.id,j)}releaseConnection(j){let e=this._Connections.get(j);e?.type==="established"&&(e.references-=1,e.references<=0&&e.connection.close())}checkHealth(){for(let j of this._Connections.values())j.type==="established"&&j.connection.healthCheck()}close(){this._Close.abort()}async dump(){let j=[];for(let B of this._Connections.values()){let v;switch(B.type){case"established":v={transport:B.transport,address:B.address,connection:await B.connection.dump(),references:B.references};break;case"establishing":v={transport:B.transport,address:B.address,aborted:B.abort.signal.aborted};break;case"virtual":v={connection:await B.connection.dump()};break}j.push({type:B.type,id:B.id,createdAt:B.createdAt,...v})}let e=[];for(let[B,v]of this._MediaMap)e.push(`${B} -> ${v.peerId} @${v.connection.id} `);return{lastConnectionId:this._LastConnectionId,connections:j,mediaMap:e,closed:this.closed}}findConnection(j,e){for(let B of this._Connections.values())if(B.type!=="virtual"&&B.transport===j&&B.address===e)return B}},r0=class{constructor(j,e){this.connection=j;this.release=e;this.closeController=new AbortController;this.closePromise=new Promise(j=>this.closeController.signal.addEventListener("abort",()=>j("closed"),{once:!0}));j.closeSignal.addEventListener("abort",()=>this.close(),{once:!0})}get closeSignal(){return this.closeController.signal}get closed(){return this.closeSignal.aborted}close(){this.release(),this.closeController.abort("closed")}get connectionStats(){return this.connection.connectionStats}get id(){return this.connection.id}get transport(){return this.connection.transport}get address(){return this.connection.address}get status(){return this.connection.status}waitForConnected(){return this.connection.waitForConnected()}joinRoom(j,e,B,v){return this.connection.joinRoom(j,e,B,v)}getReconnectToken(j){return this.connection.getReconnectToken(j)}healthCheck(){return this.connection.healthCheck()}sendDatagram(j){return this.connection.sendDatagram(j)}startLocalVideo(j,e){return this.connection.startLocalVideo(j,e)}stopLocalVideo(j){return this.connection.stopLocalVideo(j)}startRemoteVideo(j){return this.connection.startRemoteVideo(j)}stopRemoteVideo(j){return this.connection.stopRemoteVideo(j)}async dump(){let j=await this.connection.dump();return typeof j=="object"&&(j={...j,isShared:!0,referenceClosed:this.closed}),j}};function MF(C){let j;try{j=OF(C)}catch{return}if(!Array.isArray(j)||j.length<2)return;let e=j[1];if(Array.isArray(e))return e.map(Number)}import{assert as D0,Backend as lB}from"@4players/odin-common";var w=class{constructor(j,e,B){this.id=j;this.uid=e;this.customType=B}#x;#A;get mediaStream(){return this.#x}get audioPlayback(){return D0(this.#A,"getting the audioPlayback failed, this video has no Audio"),this.#A}get volume(){return D0(this.audioPlayback,"getting the volume failed, this video has no Audio"),this.audioPlayback.volume}setVolume(j){D0(this.#A,"Can not set the volume, this video has no Audio"),this.#A.setVolume(j)}setMediaStream(j){this.mediaStream||(this.#x=j)}close(){this.#x?.getVideoTracks().forEach(j=>{j.stop(),this.#x?.removeTrack(j)}),this.#x=void 0}};import{Backend as kB,assert as fA,generateUUID as Cr,unwrap as Er,CONNECTION_STATS_INITIAL as fr}from"@4players/odin-common";import{RoomNotificationsRpc as nr,RoomV1 as cB}from"@4players/odin-common/api";import{Selector as TF,failure as N,sleep as qx,success as T,assert as SF}from"@4players/odin-common";import{parseResponse as RF,RoomCommandsRpc as mx,RoomNotificationsRpc as VF,RoomV1 as uB}from"@4players/odin-common/api";k();var Gx=class{constructor(j,e,B,v,E,f,n,i,u,y){this.connectionPool=j;this.transport=e;this.onEvent=B;this.gateway=v;this.roomId=f;this.cipher=u;this.disableAutoReconnect=y;this._Close=new AbortController;this._TokenUsed=!1;this._WasConnected=!1;this._FailedConnections=0;this._LastTokenRenew=performance.now();this._LastReconnectStartedAt=0;this._Closed=new Promise(j=>this._Close.signal.addEventListener("abort",()=>j(this._Close.signal.reason?"disconnected":"closed"),{once:!0}));this._Token=E,this._UserData=n,this._Position=i,this._Main().then(({reason:U})=>a(`_Main() resolved; ${U}`))}get token(){return this._Token}get userData(){return this._UserData}get position(){return this._Position}get closed(){return this._Close.signal.aborted}get mainConnection(){return this._MainConnection}async requestUnsafe(j,e){if(this._RoomConnection===void 0)return N("currently not connected");let B=await this._RoomConnection.request(j,e,void 0);return SF(B!=="timeout","request should not timeout"),B!=="closed"&&B.type==="Success"&&this._HandleRequests(j,e,B.value),B}async request(j,e){let B=Date.now(),v=mx[j],E=await this.requestUnsafe(j,e),f=(Date.now()-B)/1e3;if(a(`sent room rpc '${j}'; took: ${f}s`,{properties:e,result:E}),E==="closed"||E.type==="Failure")return E;let n=RF(j,E.value,mx);return n!==void 0?T(n):N(`received invalid response from ${j}`)}notify(j,e){this._RoomConnection!==void 0&&this._RoomConnection.notify(j,e)}close(){this._Close.abort(!0)}get renewTokenIn(){let j=this._LastTokenRenew-performance.now()+b.MinTokenRefreshInterval,e=this._Token.timeLeft-b.MinTokenLifetime;return Math.max(j,e)}async _Main(){let j="unable to establish connection";for(let e=0;;this._FailedConnections++){if(await qx(Math.max(e-performance.now(),0)),this._Close.signal.aborted||this.connectionPool.closed){j="user requested";break}if(e=performance.now()+1e3,this._TokenUsed=!0,this._Token.hasAudience("sfu")){let B=await this._ConnectToServer();if(B.type==="Success"&&B.value==="shutdown"){a("connection closed by user request; shutting down"),j="user requested";break}if(this.disableAutoReconnect&&this._WasConnected){j=B.type==="Failure"?B.reason:"connection lost";break}if(this._LastReconnectStartedAt===0&&(this._LastReconnectStartedAt=performance.now()),B.type==="Failure"&&!this._WasConnected&&this._FailedConnections>=3){j=B.reason;break}if(B.type==="Failure"&&!WF(this._LastReconnectStartedAt))continue}if(this.reset(),this._Close.signal.aborted||this.connectionPool.closed){j="user requested";break}if(this.gateway!==void 0&&this._Token.hasAudience("gateway")){this._ChangeStatus("Joining",`requesting new token from ${this.gateway}`);let B=await UF(this.gateway,this._Token,this._Close.signal);if(B.type==="Success")if(B.value instanceof g)e=0,this._Token=B.value,this._TokenUsed=!1;else{j=`gateway error; ${B.value}`;break}else if(!this._WasConnected&&this._FailedConnections>=3){j="unable to contact the gateway";break}}if(this._TokenUsed&&this._Token.timeLeft<=0){j="token has expired";break}if(this._Close.signal.aborted||this.connectionPool.closed){j="user requested";break}}return this._ChangeStatus("Closed",j),this.close(),N(j)}async _ConnectToServer(){let j=this._Token;for(;j.upstream!==void 0;)j=j.upstream;let e=j.claims.adr??this.gateway?.toString();if(!e)return T("continue");if(this._ChangeStatus("Joining",`connecting to ${j.claims.adr}`),this._MainConnection===void 0||this._MainConnection.closed||this._MainConnection.address!==j.claims.adr){this._MainConnection?.close();let E=await this.connectionPool.acquireConnection(this.transport,e,this.cipher,this._Close.signal);if(E==="closed")return N("connection pool closed");if(E.type==="Failure")return this._ChangeStatus("Joining",`connection failed; ${E.reason}`),N(`connection failed; ${E.reason}`);this._MainConnection=E.value,this._OwnPeerId=void 0}let B=await Promise.race([Promise.all([this._MainConnection.joinRoom(j,this.roomId,this.userData,this.position)]),qx(b.ConnectTimeout,"timeout"),this._Closed]);if(B==="closed"||B==="disconnected")return T("continue");if(B==="timeout")return this._ChangeStatus("Joining","timed out"),T("continue");let[v]=B;if(v==="closed")return T("continue");if(v.type==="Failure")return N(`unable to join room; ${v.reason}`);this._RoomConnection=v.value,this._WasConnected=!0,this._FailedConnections=0,this._ChangeStatus("Joined",`joined ${this.roomId}`);try{await this._MainConnection.waitForConnected();let E=await this._HandleConnection(this._MainConnection);return T(E?"shutdown":"continue")}catch(E){return N(`unable to handle connection; ${E}`)}}_ChangeStatus(j,e){let B={status:j,message:e};this.onEvent("RoomStatusChanged",B)}async _HandleConnection(j){if(this._RoomConnection===void 0)return!1;let e=new TF([()=>qx(this.renewTokenIn,"renewToken"),()=>qx(500,"tick"),async()=>await this._RoomConnection?.recv(),()=>this._Closed,()=>j.closePromise]);for(;;){let B=await e.next();switch(B){case void 0:case"closed":return this._RoomConnection?.close(),this._MainConnection?.close(),!1;case"disconnected":return this._RoomConnection?.close(),this._MainConnection?.close(),!0;case"renewToken":this._RenewToken();break;case"tick":break;default:this._HandleEvent(B);break}}}_HandleEvent(j){if(j.name==="RoomUpdated"){let e=VF.RoomUpdated.safeParse(j.properties);if(!e.success)return;for(let B of e.data.updates)B.kind==="Joined"&&(this._OwnPeerId=B.own_peer_id)}this.onEvent(j.name,j.properties)}_HandleRequests(j,e,B){switch(j){case"SetPeerPosition":{let v=mx.SetPeerPosition.request.safeParse(e);if(v.success){let E=v.data.position;this._Position=E.length===2?[E[0],E[1],0]:E}else q("unable to process SetPeerPosition command");break}case"UpdatePeer":{let v=mx.UpdatePeer.request.safeParse(e);v.success?this._UserData=v.data.user_data:q("unable to process UpdatePeer command");break}}}async _RenewToken(j){if(this._LastTokenRenew=performance.now(),!j&&this.token.timeLeft>b.MinTokenLifetime)return;if(this._MainConnection===void 0||this._OwnPeerId===void 0)return N("connection is not established");let e=await this._MainConnection.getReconnectToken(this._OwnPeerId);return e.type==="Success"?(this._Token=e.value,T()):N(`${this._MainConnection.address} rejected reconnect token request; ${e.reason}`)}reset(){this._LastReconnectStartedAt=0,this._RoomConnection?.close(),this._RoomConnection=void 0,this._MainConnection?.close(),this._MainConnection=void 0,this._OwnPeerId=void 0}};async function UF(C,j,e){try{let B={jsonrpc:"2.0",id:1,method:"Connect",params:{}};o(`sending authentication request to '${C}'`,B);let E=await(await fetch(C,{body:JSON.stringify(B),method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${j}`},signal:e})).json();if(o(`received authentication response fom '${C}'`,E),"result"in E)return g.parse(E.result.token);{let f=E.error?.message??"malformed response";return d(`gateway rejected token; ${f}`),T(f)}}catch(B){return N(String(B))}}function WF(C,j=8e3){return performance.now()-C>j}k();import{assert as vr}from"@4players/odin-common";k();import{Backend as tx,Strand as Br}from"@4players/odin-common";k();import{assert as ZF}from"@4players/odin-common";k();import{decode as zF}from"@msgpack/msgpack";var xA={name:"PBKDF2",hash:"SHA-256",iterations:6e5,salt:new Uint8Array([111,100,105,110,95,99,114,121,112,116,111,95,109,97,115,116,101,114,95,107,101,121])},AA=C=>({name:"PBKDF2",hash:"SHA-256",iterations:600,salt:C}),FA=32,rA=1e6,DA=2147483648,tA=32,J=[79,68,73,78,1,75,105,109],xx=16,Ax=64,jA=16;function eA(C,j){if(C.length!==j.length)return!1;for(let e=0;e<C.length;e++)if(C[e]!==j[e])return!1;return!0}function XF(C){return isFinite(C)}function QF(C){return Array.isArray(C)}function Ix(C){return XF(C)?C:s}function Dx(C){return C instanceof Uint8Array?C:s}function YF(C,...j){let e;try{e=zF(C)}catch{return s}if(!QF(e))return s;let B=new Array(e.length);for(let v in j)if(B[v]=j[v](e[v]),B[v]===s)return s;return B}function $x(C,...j){if(C.length<J.length)return m;for(let e=0;e<J.length;e++)if(C[e]!==J[e])return m;return YF(C.subarray(J.length),...j)}var Fx=class{constructor(j){this.first=1;this.offset=0;this.window=Array(j)}isReplay(j){let e=j-this.first;if(e<0)return!0;if(e>=this.window.length)if(e<this.window.length*2){let E=e-this.window.length+1;e-=E;for(let f=0;f<E;f++)this.advance()}else return this.first=j+1-self.window.length,this.offset=0,this.window.fill(!1),!1;let B=(this.offset+e)%this.window.length,v=this.window[B]===!0;for(this.window[B]=!0;this.window[this.offset]===!0;)this.advance();return v}advance(){this.window[this.offset]=!1,this.first+=1,this.offset=(this.offset+1)%this.window.length}};var gx=class C{constructor(j){this.key=j}static async create(j){typeof j=="string"&&(j=new TextEncoder().encode(j));let e=await globalThis.crypto.subtle.importKey("raw",j,"PBKDF2",!1,["deriveBits"]),B=await globalThis.crypto.subtle.deriveBits(xA,e,256),v=await globalThis.crypto.subtle.importKey("raw",B,"PBKDF2",!1,["deriveKey"]);return new C(v)}async generatePeerKey(j,e){return await globalThis.crypto.subtle.deriveKey(AA(j),this.key,{name:"AES-GCM",length:256},!1,[e])}},yx=class C{constructor(j,e){this.seed=j;this.key=e;this.sequenceNumbers={datagram:1,message:1,userData:1};this.number_of_packets=0;this.number_of_bytes=0}static async create(j){let e=globalThis.crypto.getRandomValues(new Uint8Array(FA)),B=await j.generatePeerKey(e,"encrypt");return new C(e,B)}get limitReached(){return this.key===void 0?!1:this.number_of_bytes>=DA||this.number_of_packets>=rA}nextSequenceNumber(j){return this.sequenceNumbers[j]++}};function t0(C,j){return{kind:"encrypted",key:C,material:j,antiReplays:{datagram:new Fx(tA),userData:new Fx(0),message:new Fx(0)}}}var _x=class C{constructor(j,e,B,v){this.additionalData=j;this.sequenceNumber=e;this.seed=B;this.encrypted=v}static parse(j){let e=$x(j,Dx,Ix,Dx);if(e===s||e===m)return e;let[B,v,E]=e,f=j.subarray(0,j.length-E.length);return new C(f,v,B,E)}isSameSeed(j){return eA(this.seed,j.seed)}async generateKey(j){return await j.generatePeerKey(this.seed,"decrypt")}};function Lx(C,j){let e=new Uint8Array(12);switch(e[0]=j&255,e[1]=j>>8&255,e[2]=j>>16&255,e[3]=j>>24&255,C){case"datagram":e[5]=1;break;case"userData":e[5]=2;break;case"message":e[5]=3;break;default:ZF(!1,"missing content implementation")}return e}k();import{encode as vA}from"@msgpack/msgpack";import{assert as Ar}from"@4players/odin-common";var Hx=class{constructor(j){this.actions=j}changeKey(j){this.masterKey!==j&&(this.masterKey=j,this.ownKey=s,this.actions.resendUserData())}async encryptDatagram(j){let e=await this.getKey("datagram");return e===void 0?j:e===P?s:await rr(e,j)}async encryptMessage(j){let e=await this.getKey("message");return e===void 0?j:e===P?P:await BA(e,j,"message")}async encryptUserData(j){let e=await this.getKey("userData");return e===void 0?j:(Ar(e!==P,"key unavailable for user data encryption"),await BA(e,j,"userData",e.seed))}async getKey(j){if(this.ownKey===s||this.ownKey?.limitReached)if(j==="userData")this.ownKey=this.masterKey?await yx.create(this.masterKey):void 0;else return this.ownKey!==s&&(this.ownKey=s,this.actions.resendUserData()),P;return this.ownKey}reset(){this.ownKey=this.masterKey?s:void 0}};async function BA(C,j,e,...B){let v=C.nextSequenceNumber(e),E=j.length+xx,f=Fr(v,B,E),n=f.length-E,i=await CA(C,e,v,f.subarray(0,n),j);return f.set(new Uint8Array(i),n),f}function Fr(C,j,e){let B=[];j.forEach(f=>B.push(f)),B.push(C),B.push(new Uint8Array(e));let v=vA(B),E=new Uint8Array(J.length+v.length);return E.set(J,0),E.set(v,J.length),E}async function rr(C,j){let e=Dr(j);if(e===s)return s;if((e.kind&Ax)!==0)return s;let B=e.body.length+xx,v=C.nextSequenceNumber("datagram"),E=vA([e.kind|Ax,e.mediaIds,v,new Uint8Array(B)]),f=E.length-B,n=await CA(C,"datagram",v,E.subarray(0,f),e.body);return E.set(n,f),E}async function CA(C,j,e,B,v){return new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:Lx(j,e),additionalData:B,tagLength:xx*8},C.key,v))}function Dr(C){let j=new O(C),e=j.readArrayLength();if(l(e)||e<2)return s;let B=j.readNumber(),v=j.readArrayLength();if(l(B)||l(v))return s;if(v>jA)return s;let E=Array(v);for(let n=0;n<E.length;n++){let i=j.readNumber();if(l(i))return s;E[n]=i}let f=C.subarray(j.position);return{kind:B,mediaIds:E,body:f}}k();import{encode as tr}from"@msgpack/msgpack";var Kx=class{constructor(j){this.actions=j;this.peerKeys=new Map}async changeKey(j){this.masterKey=j;for(let[e,{kind:B,material:v}]of this.peerKeys)if(j!==void 0){let E=await v.generateKey(j),f=t0(E,v),n=await Nx(f,"userData",v.additionalData,v.sequenceNumber,v.encrypted);n!==s?(this.peerKeys.set(e,f),this.actions.setUserData(e,n)):(this.peerKeys.set(e,{kind:"broken",material:v}),this.actions.setUserData(e,new Uint8Array))}else B==="encrypted"&&this.peerKeys.set(e,{kind:"broken",material:v})}async decryptDatagram(j,e){let B=jr(e);if(this.masterKey===void 0)return B===m?e:s;if(B===s||B===m)return s;let v=this.peerKeys.get(j);if(v?.kind!=="encrypted")return s;let E=await Nx(v,"datagram",B.additionalData,B.sequenceNumber,B.encrypted);return E===s?s:er(B.kind&~Ax,B.mediaIds,E)}async decryptMessage(j,e){let B=$x(e,Ix,Dx);if(this.masterKey===void 0)return B===m?e:s;if(B===s||B===m)return s;let v=this.peerKeys.get(j);if(v?.kind!=="encrypted")return s;let[E,f]=B,n=e.subarray(0,e.length-f.length);return Nx(v,"message",n,E,f)}async decryptUserData(j,e){let B=_x.parse(e);if(B===s)return s;if(B===m)return this.peerKeys.delete(j),this.masterKey===void 0?e:s;if(this.masterKey===void 0)return this.peerKeys.set(j,{kind:"broken",material:B}),s;let v=this.peerKeys.get(j);if(v?.kind==="encrypted"&&v.material.isSameSeed(B))v.material=B;else{let f=await B.generateKey(this.masterKey);v=t0(f,B)}let E=await Nx(v,"userData",B.additionalData,B.sequenceNumber,B.encrypted);return E===s?this.peerKeys.set(j,{kind:"broken",material:B}):v!==void 0&&this.peerKeys.set(j,v),E}reset(){this.peerKeys.clear()}};function jr(C){let j=new O(C),e=j.readArrayLength();if(l(e)||e<1)return s;let B=j.readNumber();if(l(B))return s;if((B&Ax)===0)return m;if(e!==4)return s;let v=j.position;j.readObjects(1);let E=C.subarray(v,j.position),f=j.readNumber(),n=j.readBytes();if(l(f)||l(n))return s;let i=C.subarray(0,C.length-n.length);return{kind:B,mediaIds:E,additionalData:i,sequenceNumber:f,encrypted:n}}async function Nx(C,j,e,B,v){let E=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:Lx(j,B),additionalData:e,tagLength:xx*8},C.key,v).catch(()=>s);return E===s?s:C.antiReplays[j].isReplay(B)?s:new Uint8Array(E)}function er(C,j,e){let B=2;try{let f=new O(e);for(f.position=0;f.position<e.length;)f.readObjects(1),B+=1}catch{return s}let v=tr(C),E=new Uint8Array(3+v.length+j.length+e.length);return E[0]=220,E[1]=B>>8&255,E[2]=B&255,E.set(v,3),E.set(j,3+v.length),E.set(e,3+v.length+j.length),E}var wx=class{constructor(j,e){this.active=!1;let B=new Kx(e),v=new Hx(e);this.crypto=new Br({encryption:v,decryption:B}),this.peerKeys=B.peerKeys,this.configure(j)}encryptUserData(j){return this.crypto.enqueue(({encryption:e})=>e.encryptUserData(j))}async encryptMessage(j){let e;do e=await this.crypto.enqueue(({encryption:B})=>B.encryptMessage(j));while(e===P);return e}async encryptDatagram(j){return await this.crypto.enqueue(({encryption:e})=>e.encryptDatagram(j))}decryptUserData(j,e){return this.crypto.enqueue(({decryption:B})=>B.decryptUserData(j,e))}decryptMessage(j,e){return this.crypto.enqueue(({decryption:B})=>B.decryptMessage(j,e))}decryptDatagram(j,e){return this.crypto.enqueue(({decryption:B})=>B.decryptDatagram(j,e))}configure(j){return this.crypto.enqueue(async e=>{let B=j.password?await gx.create(j.password):void 0;this.active=B!==void 0,await e.encryption.changeKey(B),await e.decryption.changeKey(B)})}getPeerStatus(j){switch(this.peerKeys.get(j)?.kind??"unencrypted"){case"broken":return tx.PeerCipherStatus.InvalidPassword;case"encrypted":return tx.PeerCipherStatus.Encrypted;case"unencrypted":return this.active?tx.PeerCipherStatus.InvalidPassword:tx.PeerCipherStatus.Unencrypted;default:return tx.PeerCipherStatus.Unknown}}reset(){return this.crypto.enqueue(async({encryption:j,decryption:e})=>{j.reset(),e.reset()})}async dump(){return this.crypto.enqueue(async()=>({active:this.active,peers:Array.from(this.peerKeys).map(([j,e])=>`${j} => ${e.kind}`)}))}};function EA(C,j){return vr(C.type==="OdinCrypto","only OdinCrypto supported"),new wx(C,j)}var Jx=class{constructor(j,e,B){this._Captures=new Map;this._Playbacks=new Map;this._Peers=new Map;this._AvailableMediaIds=[];let{url:v,onEvent:E}=e,f=Er(g.parse(e.token)),n=e.roomId??f.defaultRoomId,i=e.userData??new Uint8Array(0),u=e.position??[0,0,0];fA(n!==void 0,"room id required for multi-room-tokens"),this.cipher=e.cipher?EA(e.cipher,new px(this)):void 0,this.onEvent=E,o(`creating new room '${n}' ${this.cipher?"with":"without"} cipher`,f,i,u),this._Connection=new Gx(j,e.transport??"H3",this._HandleEvent.bind(this),v?new URL(v):void 0,f,n,i,u,this.cipher,B?.disableAutoReconnect??!1)}get connectionStats(){let j={...fr};return this.mainConnection?this.mainConnection.connectionStats:j}get roomConnection(){return this._Connection}get mainConnection(){return this.roomConnection?.mainConnection}get token(){return this._Connection.token.text}request(j,e){return this._Connection.requestUnsafe(j,e)}async link(j){if(j instanceof H){let e=this._Playbacks.get(j.uid)??{media:void 0,playback:void 0};e.playback!==void 0&&this.unlink(e.playback),e.media!==void 0&&j.start(e.media),e.playback=j,o(`linking audio playback media '${j.uid}' with volume ${j.volume} to room '${this._Connection.roomId}'`),this._Playbacks.set(j.uid,e)}else if(j instanceof K){let e=this._Captures.get(j);e&&this.unlink(j);let B=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();e={media:B?{connectionId:this.mainConnection.id,mediaId:B}:void 0},o(`linking audio capture media '${j.uid}' with volume ${j.volume} to room '${this._Connection.roomId}'`),this._Captures.set(j,e),e.media!==void 0&&await j.start(this._Connection,e.media)}else if(j instanceof w){let e=this._Playbacks.get(j.uid)??{media:void 0,playback:void 0};if(e.playback!==void 0&&this.unlink(e.playback),e.media!==void 0){let B=await this.mainConnection?.startRemoteVideo(e.media.mediaId);B&&j.setMediaStream(new MediaStream([B]))}e.playback=j,o(`linking video playback media '${j.uid}' with type '${j.customType}' to room '${this._Connection.roomId}'`),this._Playbacks.set(j.uid,e)}else if(j instanceof $){let e=this._Captures.get(j);e&&this.unlink(j);let B=j.mediaStream?.getVideoTracks()[0];if(B){let v=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();e={media:v?{connectionId:this.mainConnection.id,mediaId:v}:void 0},o(`linking video capture media '${j.uid}' with type '${j.options?.customType}' to room '${this._Connection.roomId}'`),this._Captures.set(j,e),e.media!==void 0&&(await j.start(this._Connection,e.media),this.mainConnection?.startLocalVideo(e.media.mediaId,B,j.options?.codec)),j.audioCapture&&await this.link(j.audioCapture)}}else throw new Error("Linking failed, media was not supported")}unlink(j){if(j instanceof H||j instanceof w){let e=this._Playbacks.get(j.uid);if(e?.playback!==j)return;e.playback=void 0,e.media!==void 0&&(j instanceof H?j.stop(e.media):(this.mainConnection?.stopRemoteVideo(e.media.mediaId),j.setMediaStream(void 0))),o(`unlinking playback media '${j.uid}' from room '${this._Connection.roomId}'`),this._Playbacks.set(j.uid,e)}else if(j instanceof K||j instanceof $){j instanceof $&&j.audioCapture&&this.unlink(j.audioCapture);let e=this._Captures.get(j);if(e===void 0)return;e.media!==void 0&&(j.stop(this._Connection,e.media),this._AvailableMediaIds.push(e.media.mediaId),j instanceof $&&this.mainConnection?.stopLocalVideo(e.media.mediaId)),o(`unlinking capture media '${j.uid}' from room '${this._Connection.roomId}'`),this._Captures.delete(j)}else throw new Error("invalid media")}close(){o(`closing room '${this._Connection.roomId}'`),this._Connection.close()}_HandleEvent(j,e){let B=Zx(nr,{name:j,properties:e});B!==void 0&&(this._HandleKnownEvent(B),e=B.properties),this.onEvent(j,e)}_HandleKnownEvent(j){switch(a(`processing event '${j.name}'`,j.properties),j.name){case"RoomStatusChanged":j.properties.status!=="Joined"&&this._HandleConnectionLost();break;case"RoomUpdated":for(let e of j.properties.updates)this._HandleRoomUpdate(e);break;case"PeerUpdated":this._HandlePeerUpdate(j.properties);break}}_HandleConnectionLost(){for(let j of this._Peers.keys())this._HandlePeerLeft(j);for(let[j,e]of this._Captures)e.media!==void 0&&(j instanceof $,j instanceof K&&(j.stop(this._Connection,e.media),e.media=void 0));this._AvailableMediaIds.length=0}_HandleRoomUpdate(j){if(j.kind==="Joined"){fA(this._AvailableMediaIds.length===0,"left over media ids"),this._AvailableMediaIds.push(...j.media_ids),this._HandleRoomJoined();for(let e of j.room.peers)this._HandlePeerJoined(e)}else j.kind==="PeerJoined"?this._HandlePeerJoined(j.peer):j.kind==="PeerLeft"&&this._HandlePeerLeft(j.peer_id)}_HandleRoomJoined(){for(let[j,e]of this._Captures)this._AvailableMediaIds.length===0||this.mainConnection===void 0||(e.media={connectionId:this.mainConnection.id,mediaId:this._AvailableMediaIds.shift()},j instanceof K&&j.start(this._Connection,e.media),j instanceof $)}_HandlePeerUpdate(j){j.kind==="MediaStarted"?this._HandleMediaStart(j.peer_id,j.media):j.kind==="MediaStopped"&&this._HandleMediaStopped(j.peer_id,j.media_id)}_HandlePeerJoined(j){this._Peers.has(j.id)||this._Peers.set(j.id,{mediaIds:new Map});for(let e of j.medias)this._HandleMediaStart(j.id,e)}_HandlePeerLeft(j){let e=this._Peers.get(j);if(e!==void 0){for(let B of e.mediaIds.keys())this._HandleMediaStopped(j,B);this._Peers.delete(j)}}_HandleMediaStart(j,e){if(this.mainConnection===void 0)return;let B=this._Peers.get(j);if(B===void 0||e.properties.kind!=="audio"&&e.properties.kind!=="video")return;let v=String(e.properties.uid??Cr());e.properties.uid=v;let E=this._Playbacks.get(v)??{media:void 0,playback:void 0};this._Playbacks.set(v,E),B.mediaIds.set(e.id,v),E.media={connectionId:this.mainConnection.id,mediaId:e.id},E.playback!==void 0&&(E.playback instanceof H&&E.playback.start(E.media),E.playback instanceof w&&this.mainConnection.startRemoteVideo(E.media.mediaId).then())}_HandleMediaStopped(j,e){let B=this._Peers.get(j);if(B===void 0)return;let v=B?.mediaIds.get(e);if(v===void 0)return;let E=this._Playbacks.get(v);E!==void 0&&(E.media!==void 0&&E.playback!==void 0&&(E.playback instanceof H&&E.playback.stop(E.media),E.playback instanceof w&&this.mainConnection?.stopRemoteVideo(E.media.mediaId)),E.media=void 0,B.mediaIds.delete(e))}};Cx();function rB(C,j){u0(j?.logger,j?.onLogMessage);let e,B=new hx((E,f)=>e.receivePacket(E,f)),v=new sx(C);return e=new ix(v,B.sendDatagram.bind(B)),new j0(B,e,j)}var ux=sr(),e0=[],nA=!1;function ir(){nA||typeof window>"u"||(window.addEventListener("beforeunload",()=>{for(let C of e0)C.deref()?.close()}),nA=!0)}var j0=class{constructor(j,e,B){this.version="8";this.supportedTransports=["H3","WebRTC"];this._PlaybackVolume=[1,1];this._CreatedAt=Date.now();this._Options=B??{},this._Options.disableBeforeUnload||ir(),this._ConnectionPool=j,this._MediaController=e,e0.push(new WeakRef(this)),o("plugin initialized")}get playbackVolume(){return this._PlaybackVolume}joinRoom(j){return new Jx(this._ConnectionPool,j,this._Options)}async createAudioPlayback(j){return this._MediaController.createAudioPlayback(j)}async createAudioCapture(j){return this._MediaController.createAudioCapture(j)}async createVideoCapture(j,e){return this._MediaController.createVideoCapture(j,e)}async createVideoPlayback(j){return new w(j.id,j.uid,j.customType)}enumerateDevices(){return vx()}setOutputVolume(j){this._MediaController.playbackSetGlobalVolume(j)}async setOutputDevice(j){await this._MediaController.playbackSetDevice(j.device)}close(){this._MediaController.close(),this._ConnectionPool.close(),o("plugin closed")}async dump(){return{createdAt:this._CreatedAt,connections:await this._ConnectionPool.dump(),medias:await this._MediaController.dump()}}};async function sA(){let C=[];for(let j of e0){let e=j.deref();e!==void 0&&C.push(await e.dump())}return JSON.stringify({timestamp:Date.now(),instances:C,background:await q0()})}globalThis.odin_debug_dump_state=sA;window!==void 0&&(window.odin_debug_dump_state=sA);export{ux as SESSION_ID,rB as createPlugin};
6412
+ \`,new Function(m,C)}function SA(j,r,s,l,o,a){var k=r.length;k<2&&G("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var u=r[1]!==null&&s!==null,c=Jr(r),C=!r[0].isVoid,f=r[0],m=r[1],E=[j,G,l,o,Br,f.fromWireType.bind(f),m?.toWireType.bind(m)],h=2;h<k;++h){var $=r[h];E.push($.toWireType.bind($))}if(!c)for(var h=u?1:2;h<r.length;++h)r[h].destructorFunction!==null&&E.push(r[h].destructorFunction);var J=$t(r,u,C,a)(...E);return Hr(j,J)}var Ft=(j,r,s,l,o,a)=>{var k=VA(r,s);o=N(l,o),w([],[j],u=>{u=u[0];var c=\`constructor \${u.name}\`;if(u.registeredClass.constructor_body===void 0&&(u.registeredClass.constructor_body=[]),u.registeredClass.constructor_body[r-1]!==void 0)throw new AA(\`Cannot register multiple constructors with identical number of parameters (\${r-1}) for class '\${u.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!\`);return u.registeredClass.constructor_body[r-1]=()=>{Q(\`Cannot construct \${u.name} due to unbound types\`,k)},w([],k,C=>(C.splice(1,0,null),u.registeredClass.constructor_body[r-1]=SA(c,C,null,o,a),[])),[]})},br=j=>{j=j.trim();let r=j.indexOf("(");return r===-1?j:j.slice(0,r)},vt=(j,r,s,l,o,a,k,u,c,C)=>{var f=VA(s,l);r=v(r),r=br(r),a=N(o,a,c),w([],[j],m=>{m=m[0];var E=\`\${m.name}.\${r}\`;r.startsWith("@@")&&(r=Symbol[r.substring(2)]),u&&m.registeredClass.pureVirtualFunctions.push(r);function h(){Q(\`Cannot call \${E} due to unbound types\`,f)}var $=m.registeredClass.instancePrototype,H=$[r];return H===void 0||H.overloadTable===void 0&&H.className!==m.name&&H.argCount===s-2?(h.argCount=s-2,h.className=m.name,$[r]=h):(_r($,r,E),$[r].overloadTable[s-2]=h),w([],f,J=>{var y=SA(E,J,m,a,k,c);return $[r].overloadTable===void 0?(y.argCount=s-2,$[r]=y):$[r].overloadTable[s-2]=y,[]}),[]})},Or=(j,r,s)=>(j instanceof Object||G(\`\${s} with invalid "this": \${j}\`),j instanceof r.registeredClass.constructor||G(\`\${s} incompatible with "this" of type \${j.constructor.name}\`),j.$$.ptr||G(\`cannot call emscripten binding method \${s} on deleted object\`),fA(j.$$.ptr,j.$$.ptrType.registeredClass,r.registeredClass)),Lt=(j,r,s,l,o,a,k,u,c,C)=>{r=v(r),o=N(l,o),w([],[j],f=>{f=f[0];var m=\`\${f.name}.\${r}\`,E={get(){Q(\`Cannot access \${m} due to unbound types\`,[s,k])},enumerable:!0,configurable:!0};return c?E.set=()=>Q(\`Cannot access \${m} due to unbound types\`,[s,k]):E.set=h=>G(m+" is a read-only property"),Object.defineProperty(f.registeredClass.instancePrototype,r,E),w([],c?[s,k]:[s],h=>{var $=h[0],H={get(){var y=Or(this,f,m+" getter");return $.fromWireType(o(a,y))},enumerable:!0};if(c){c=N(u,c);var J=h[1];H.set=function(y){var eA=Or(this,f,m+" setter"),g=[];c(C,eA,J.toWireType(g,y)),Br(g)}}return Object.defineProperty(f.registeredClass.instancePrototype,r,H),[]}),[]})},wr=[],Y=[0,1,,1,null,1,!0,1,!1,1],gt=j=>{j>9&&--Y[j+1]===0&&(Y[j]=void 0,wr.push(j))},WA={toValue:j=>(j||G(\`Cannot use deleted val. handle = \${j}\`),Y[j]),toHandle:j=>{switch(j){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:{let r=wr.pop()||Y.length;return Y[r]=j,Y[r+1]=1,r}}}},Ht={name:"emscripten::val",fromWireType:j=>{var r=WA.toValue(j);return gt(j),r},toWireType:(j,r)=>WA.toHandle(r),readValueFromPointer:GA,destructorFunction:null},yt=j=>K(j,Ht),_t=(j,r)=>{switch(r){case 4:return function(s){return this.fromWireType(qr[s>>2])};case 8:return function(s){return this.fromWireType(Cr[s>>3])};default:throw new TypeError(\`invalid float width (\${r}): \${j}\`)}},Dt=(j,r,s)=>{r=v(r),K(j,{name:r,fromWireType:l=>l,toWireType:(l,o)=>o,readValueFromPointer:_t(r,s),destructorFunction:null})},xt=(j,r,s,l,o,a,k,u)=>{var c=VA(r,s);j=v(j),j=br(j),o=N(l,o,k),Dr(j,function(){Q(\`Cannot call \${j} due to unbound types\`,c)},r-1),w([],c,C=>{var f=[C[0],null].concat(C.slice(1));return Kr(j,SA(j,f,null,o,a,k),r-1),[]})},Kt=(j,r,s,l,o)=>{r=v(r);let a=l===0,k=c=>c;if(a){var u=32-8*s;k=c=>c<<u>>>u,o=k(o)}K(j,{name:r,fromWireType:k,toWireType:(c,C)=>C,readValueFromPointer:Fr(r,s,l!==0),destructorFunction:null})},Nt=(j,r,s)=>{var l=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=l[r];function a(k){var u=I[k>>2],c=I[k+4>>2];return new o(V.buffer,c,u)}s=v(s),K(j,{name:s,fromWireType:a,readValueFromPointer:a},{ignoreDuplicateRegistrations:!0})},Bt=(j,r,s,l)=>{if(!(l>0))return 0;for(var o=s,a=s+l-1,k=0;k<j.length;++k){var u=j.codePointAt(k);if(u<=127){if(s>=a)break;r[s++]=u}else if(u<=2047){if(s+1>=a)break;r[s++]=192|u>>6,r[s++]=128|u&63}else if(u<=65535){if(s+2>=a)break;r[s++]=224|u>>12,r[s++]=128|u>>6&63,r[s++]=128|u&63}else{if(s+3>=a)break;r[s++]=240|u>>18,r[s++]=128|u>>12&63,r[s++]=128|u>>6&63,r[s++]=128|u&63,k++}}return r[s]=0,s-o},Jt=(j,r,s)=>Bt(j,_,r,s),bt=j=>{for(var r=0,s=0;s<j.length;++s){var l=j.charCodeAt(s);l<=127?r++:l<=2047?r+=2:l>=55296&&l<=57343?(r+=4,++s):r+=3}return r},Pr=globalThis.TextDecoder&&new TextDecoder,Mr=(j,r,s,l)=>{var o=r+s;if(l)return o;for(;j[r]&&!(r>=o);)++r;return r},Tr=(j,r=0,s,l)=>{var o=Mr(j,r,s,l);if(o-r>16&&j.buffer&&Pr)return Pr.decode(j.subarray(r,o));for(var a="";r<o;){var k=j[r++];if(!(k&128)){a+=String.fromCharCode(k);continue}var u=j[r++]&63;if((k&224)==192){a+=String.fromCharCode((k&31)<<6|u);continue}var c=j[r++]&63;if((k&240)==224?k=(k&15)<<12|u<<6|c:k=(k&7)<<18|u<<12|c<<6|j[r++]&63,k<65536)a+=String.fromCharCode(k);else{var C=k-65536;a+=String.fromCharCode(55296|C>>10,56320|C&1023)}}return a},Ot=(j,r,s)=>j?Tr(_,j,r,s):"",wt=(j,r)=>{r=v(r);var s=!0;K(j,{name:r,fromWireType(l){var o=I[l>>2],a=l+4,k;if(s)k=Ot(a,o,!0);else{k="";for(var u=0;u<o;++u)k+=String.fromCharCode(_[a+u])}return B(l),k},toWireType(l,o){o instanceof ArrayBuffer&&(o=new Uint8Array(o));var a,k=typeof o=="string";k||ArrayBuffer.isView(o)&&o.BYTES_PER_ELEMENT==1||G("Cannot pass non-string to std::string"),s&&k?a=bt(o):a=o.length;var u=RA(4+a+1),c=u+4;if(I[u>>2]=a,k)if(s)Jt(o,c,a+1);else for(var C=0;C<a;++C){var f=o.charCodeAt(C);f>255&&(B(u),G("String has UTF-16 code units that do not fit in 8 bits")),_[c+C]=f}else _.set(o,c);return l!==null&&l.push(B,u),u},readValueFromPointer:GA,destructorFunction(l){B(l)}})},Ur=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Pt=(j,r,s)=>{var l=j>>1,o=Mr(Z,l,r/2,s);if(o-l>16&&Ur)return Ur.decode(Z.subarray(l,o));for(var a="",k=l;k<o;++k){var u=Z[k];a+=String.fromCharCode(u)}return a},Mt=(j,r,s)=>{if(s??=2147483647,s<2)return 0;s-=2;for(var l=r,o=s<j.length*2?s/2:j.length,a=0;a<o;++a){var k=j.charCodeAt(a);uA[r>>1]=k,r+=2}return uA[r>>1]=0,r-l},Tt=j=>j.length*2,Ut=(j,r,s)=>{for(var l="",o=j>>2,a=0;!(a>=r/4);a++){var k=I[o+a];if(!k&&!s)break;l+=String.fromCodePoint(k)}return l},Vt=(j,r,s)=>{if(s??=2147483647,s<4)return 0;for(var l=r,o=l+s-4,a=0;a<j.length;++a){var k=j.codePointAt(a);if(k>65535&&a++,cA[r>>2]=k,r+=4,r+4>o)break}return cA[r>>2]=0,r-l},St=j=>{for(var r=0,s=0;s<j.length;++s){var l=j.codePointAt(s);l>65535&&s++,r+=4}return r},Wt=(j,r,s)=>{s=v(s);var l,o,a;r===2?(l=Pt,o=Mt,a=Tt):(l=Ut,o=Vt,a=St),K(j,{name:s,fromWireType:k=>{var u=I[k>>2],c=l(k+4,u*r,!0);return B(k),c},toWireType:(k,u)=>{typeof u!="string"&&G(\`Cannot pass non-string to C++ string type \${s}\`);var c=a(u),C=RA(4+c+r);return I[C>>2]=c/r,o(u,C+4,c+r),k!==null&&k.push(B,C),C},readValueFromPointer:GA,destructorFunction(k){B(k)}})},Rt=(j,r)=>{r=v(r),K(j,{isVoid:!0,name:r,fromWireType:()=>{},toWireType:(s,l)=>{}})},zt=j=>{PA("OOM")},Xt=j=>{var r=_.length;j>>>=0,zt(j)},Qt=j=>52,Yt=9007199254740992,Zt=-9007199254740992,Ae=j=>j<Zt||j>Yt?NaN:Number(j);function re(j,r,s,l){return r=Ae(r),70}for(var je=[null,[],[]],te=(j,r)=>{var s=je[j];r===0||r===10?((j===1?ar:kA)(Tr(s)),s.length=0):s.push(r)},ee=(j,r,s,l)=>{for(var o=0,a=0;a<s;a++){var k=I[r>>2],u=I[r+4>>2];r+=8;for(var c=0;c<u;c++)te(j,_[k+c]);o+=u}return I[l>>2]=o,0},jA=new Uint8Array(123),P=25;P>=0;--P)jA[48+P]=52+P,jA[65+P]=P,jA[97+P]=26+P;if(jA[43]=62,jA[47]=63,st(),pt(),e.noExitRuntime&&(zj=e.noExitRuntime),e.print&&(ar=e.print),e.printErr&&(kA=e.printErr),e.wasmBinary&&(kr=e.wasmBinary),e.arguments&&(p=e.arguments),e.thisProgram&&(F=e.thisProgram),e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.shift()();var Vr,RA,B,ne,se,Sr,Wr;function ie(j){Vr=j.w,RA=e._malloc=j.y,B=e._free=j.z,ne=Sr=j.u,se=Wr=j.x}var le={g:Yj,r:Zj,f:rt,l:jt,k:Et,j:Ft,d:vt,a:Lt,s:yt,i:Dt,n:xt,c:Kt,b:Nt,t:wt,e:Wt,m:Rt,o:Xt,q:Qt,p:re,h:ee};function oe(){bj();function j(){e.calledRun=!0,!ur&&(Oj(),cr?.(e),e.onRuntimeInitialized?.(),wj())}e.setStatus?(e.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>e.setStatus(""),1),j()},1)):j()}var tA;return tA=await Sj(),oe(),pr?t=e:t=new Promise((j,r)=>{cr=j,dr=r}),t}})();typeof yj=="object"&&typeof OA=="object"?(OA.exports=sr,OA.exports.default=sr):typeof define=="function"&&define.amd&&define([],()=>sr)});var M={};fe(M,{AdditionalCaptureBlocks:()=>me,AdditionalPlaybackBlocks:()=>he,ClockJumpCheckInterval:()=>ge,ClockJumpThreshold:()=>He,ConnectInterval:()=>Je,ConnectTimeout:()=>Ke,DefaultRefreshRate:()=>Ee,DefaultVideoCodec:()=>be,HealthCheckTimeout:()=>Le,MainConnectionPingInterval:()=>ye,MaxNumberOfDecoders:()=>Fe,MinDBFs:()=>Qr,MinTokenLifetime:()=>Ne,MinTokenRefreshInterval:()=>Be,PlaybackPreload:()=>Ie,RenderQuantumSize:()=>ve,VadPreload:()=>$e,WebRtcIceTimeout:()=>De,WebRtcStatsSnapshotInterval:()=>_e,WebRtcTimeout:()=>xe});var he=3,me=3,Ie=3,Ee=250,$e=3,Fe=512,ve=128,Qr=-758.596,Le=1e4,ge=1e3,He=1e4,ye=3e3,_e=1e3,De=3e3,xe=1e4,Ke=5e3,Ne=6e4,Be=5e3,Je=[0,100,200,200,500],be="H264";function T(n,A,t){return n.postMessage(A,t)}function Yr(n){return[n.values[0],n.values[1]]}function IA(n,A){n.values[0]=A[0],n.values[1]=A[1]}function EA(n,A){return n.values[2+A*5]}function Zr(n,A,t){n.values[2+A*5]=t}function Aj(n,A){let t=2+A*5+1;return[n.values[t+0],n.values[t+1]]}function $A(n,A,t){let e=2+A*5+1;n.values[e+0]=t[0],n.values[e+1]=t[1]}function rj(n,A){return n.values[2+A*5+3]}function jj(n,A,t){n.values[2+A*5+3]=t}function tj(n,A){return n.values[2+A*5+4]}function ej(n,A,t){n.values[2+A*5+4]=t}function FA(n){return n.values[0]!==0}function vA(n){return n.values[1]}function LA(n){return n.values[2]}function nj(n){return n.values[3]}function gA(n,A){return n.values[3]=A}function sj(n){return n?Array.from(n).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var Oe;(n=>{let A;(t=>(t[t.InvalidPassword=-1]="InvalidPassword",t[t.Unknown=0]="Unknown",t[t.Unencrypted=1]="Unencrypted",t[t.Encrypted=2]="Encrypted"))(A=n.PeerCipherStatus||={})})(Oe||={});function kj(n){return{type:"Success",value:n}}function D(n){return{type:"Failure",reason:n}}var{Deno:ij}=globalThis,we=typeof ij?.noColor=="boolean"?ij.noColor:!1,Pe=!we;function YA(n,A){return{open:\`\\x1B[\${n.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function ZA(n,A){return Pe?\`\${A.open}\${n.replace(A.regexp,A.open)}\${A.close}\`:n}function QA(n){return ZA(n,YA([0],0))}function lj(n){return ZA(n,YA([1],22))}function Me(n){return ZA(n,YA([2],22))}var Jn=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),Te=new Date,HA=(n=>(n[n.CRITICAL=0]="CRITICAL",n[n.ERROR=1]="ERROR",n[n.WARN=2]="WARN",n[n.INFO=3]="INFO",n[n.DEBUG=4]="DEBUG",n))(HA||{}),uj={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},Ue={4:Me,3:QA,2:QA,1:lj,0:lj};function Ve({message:n}){return String(n)}function oj(n){return JSON.stringify({timestamp:n.date.toISOString(),level:HA[n.level],message:n.message,extra:n.extra})}function aj(n){function A(q,p){return[Math.floor(q/p),q%p]}function t(){let q,p=n.date.valueOf()-Te.valueOf();[p,q]=A(p,1e3);let[F,x]=A(p,60);return\`\${F.toString().padStart(4,"0")}:\${x.toString().padStart(2,"0")}.\${q.toString().padStart(4,"0")}\`}function e(){return n.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(n.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(n.extra)}let i=uj[n.level],d=n.logger.name!==void 0?\`@\${n.logger}\`:"";return\`\${QA(t())}\${d} \${i} \${Ue[n.level](String(n.message))}\${e()}\`}function Se(n){let A=\`[\${n.date.toISOString()}]\`,t=\`[\${HA[n.level]}]\`,e=n.logger.name!==void 0?\`[\${n.logger.name}] \`:"",i=uj[n.level];return\`\${A} \${i} \${t.padEnd(7," ")} \${e}\${n.message}\`}function We(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var cj=class{static sparse=Ve;static json=oj;static pretty=aj;static structured=Se;static default=We()?aj:oj;constructor(){}},Re=class{formatter;consoleObject;filter;constructor(n=cj.default,A=4,t=console){this.filter=A,this.formatter=n,this.consoleObject=t}handle(n){let A=this.formatter(n);switch(n.level){case 1:this.consoleObject.error(A);break;case 2:this.consoleObject.warn(A);break;case 3:this.consoleObject.info(A);break;case 4:this.consoleObject.debug(A);break}}};var S=class{#A;sinks;filter;parent;get name(){return this.#A}constructor(n,A=void 0,t=[],e=void 0){this.#A=A,this.sinks=t,this.filter=n,this.parent=e}log(n,A,t=void 0){let e={date:new Date,level:n,logger:this,message:A,extra:t};this.filter<n||this.insert(e)}insert(n){if(!(this.filter<n.level)){for(let A of this.sinks)A.filter>=n.level&&A.handle(n);this.parent!==void 0&&this.parent.insert(n)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},nA=new S(3,void 0,[new Re]),ze=S.prototype.log.bind(nA,1),Xe=S.prototype.log.bind(nA,2),dj=S.prototype.log.bind(nA,3),Qe=S.prototype.log.bind(nA,4),bn=S.prototype.log.bind(nA);var qj;function Cj(n,...A){let t=Ye(A);qj?qj?.info(n,t):dj(n,t)}function Ye(...n){if(n.length===1&&typeof n[0]=="object"&&n[0]!==null)return{...n[0]};if(n.length>0)return{args:n}}function yA(n){return n.connectionId*4294967296+n.mediaId}function fj(n){return{mediaId:n%4294967296,connectionId:Math.floor(n/4294967296)}}function b(n,A,t){let e;switch(A){case"f32":e=n.HEAPF32;break;case"u32":e=n.HEAPU32;break;case"i32":e=n.HEAP32;break;case"u8":e=n.HEAPU8;break;default:throw new Error(\`allocating \${A} is not supported\`)}let i=n._malloc(t*e.BYTES_PER_ELEMENT);if(i===0||i%e.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${t} \${A} array\`);let d=i/e.BYTES_PER_ELEMENT;return e.subarray(d,d+t)}function W(n,A){n._free(A.byteOffset)}function Gj(n,A){return{values:b(n,"f32",2+A*5),length:A}}function pj(n,A){W(n,A.values)}function hj(n){return{values:b(n,"f32",4)}}function mj(n,A){W(n,A.values)}function Ij(n){let A=n.length,t=0,e=0;for(;e<A;){let i=n.charCodeAt(e++);if((i&4294967168)===0){t++;continue}else if((i&4294965248)===0)t+=2;else{if(i>=55296&&i<=56319&&e<A){let d=n.charCodeAt(e);(d&64512)===56320&&(++e,i=((i&1023)<<10)+(d&1023)+65536)}(i&4294901760)===0?t+=3:t+=4}}return t}function Ze(n,A,t){let e=n.length,i=t,d=0;for(;d<e;){let q=n.charCodeAt(d++);if((q&4294967168)===0){A[i++]=q;continue}else if((q&4294965248)===0)A[i++]=q>>6&31|192;else{if(q>=55296&&q<=56319&&d<e){let p=n.charCodeAt(d);(p&64512)===56320&&(++d,q=((q&1023)<<10)+(p&1023)+65536)}(q&4294901760)===0?(A[i++]=q>>12&15|224,A[i++]=q>>6&63|128):(A[i++]=q>>18&7|240,A[i++]=q>>12&63|128,A[i++]=q>>6&63|128)}A[i++]=q&63|128}}var An=new TextEncoder,rn=50;function jn(n,A,t){An.encodeInto(n,A.subarray(t))}function Ej(n,A,t){n.length>rn?jn(n,A,t):Ze(n,A,t)}var tn=4096;function Ar(n,A,t){let e=A,i=e+t,d=[],q="";for(;e<i;){let p=n[e++];if((p&128)===0)d.push(p);else if((p&224)===192){let F=n[e++]&63;d.push((p&31)<<6|F)}else if((p&240)===224){let F=n[e++]&63,x=n[e++]&63;d.push((p&31)<<12|F<<6|x)}else if((p&248)===240){let F=n[e++]&63,x=n[e++]&63,wA=n[e++]&63,O=(p&7)<<18|F<<12|x<<6|wA;O>65535&&(O-=65536,d.push(O>>>10&1023|55296),O=56320|O&1023),d.push(O)}else d.push(p);d.length>=tn&&(q+=String.fromCharCode(...d),d.length=0)}return d.length>0&&(q+=String.fromCharCode(...d)),q}var en=new TextDecoder,nn=200;function sn(n,A,t){let e=n.subarray(A,A+t);return en.decode(e)}function $j(n,A,t){return t>nn?sn(n,A,t):Ar(n,A,t)}var R=class{constructor(A,t){this.type=A,this.data=t}};var L=class n extends Error{constructor(A){super(A);let t=Object.create(n.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:n.name})}};function Fj(n,A,t){let e=t/4294967296,i=t;n.setUint32(A,e),n.setUint32(A+4,i)}function _A(n,A,t){let e=Math.floor(t/4294967296),i=t;n.setUint32(A,e),n.setUint32(A+4,i)}function DA(n,A){let t=n.getInt32(A),e=n.getUint32(A+4);return t*4294967296+e}function vj(n,A){let t=n.getUint32(A),e=n.getUint32(A+4);return t*4294967296+e}var ln=-1,on=4294967296-1,an=17179869184-1;function kn({sec:n,nsec:A}){if(n>=0&&A>=0&&n<=an)if(A===0&&n<=on){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{let t=n/4294967296,e=n&4294967295,i=new Uint8Array(8),d=new DataView(i.buffer);return d.setUint32(0,A<<2|t&3),d.setUint32(4,e),i}else{let t=new Uint8Array(12),e=new DataView(t.buffer);return e.setUint32(0,A),_A(e,4,n),t}}function un(n){let A=n.getTime(),t=Math.floor(A/1e3),e=(A-t*1e3)*1e6,i=Math.floor(e/1e9);return{sec:t+i,nsec:e-i*1e9}}function cn(n){if(n instanceof Date){let A=un(n);return kn(A)}else return null}function dn(n){let A=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:A.getUint32(0),nsec:0};case 8:{let t=A.getUint32(0),e=A.getUint32(4),i=(t&3)*4294967296+e,d=t>>>2;return{sec:i,nsec:d}}case 12:{let t=DA(A,4),e=A.getUint32(0);return{sec:t,nsec:e}}default:throw new L(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${n.length}\`)}}function qn(n){let A=dn(n);return new Date(A.sec*1e3+A.nsec/1e6)}var Lj={type:ln,encode:cn,decode:qn};var U=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Lj)}register({type:A,encode:t,decode:e}){if(A>=0)this.encoders[A]=t,this.decoders[A]=e;else{let i=-1-A;this.builtInEncoders[i]=t,this.builtInDecoders[i]=e}}tryToEncode(A,t){for(let e=0;e<this.builtInEncoders.length;e++){let i=this.builtInEncoders[e];if(i!=null){let d=i(A,t);if(d!=null){let q=-1-e;return new R(q,d)}}}for(let e=0;e<this.encoders.length;e++){let i=this.encoders[e];if(i!=null){let d=i(A,t);if(d!=null){let q=e;return new R(q,d)}}}return A instanceof R?A:null}decode(A,t,e){let i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(A,t,e):new R(t,A)}};U.defaultCodec=new U;function Cn(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function sA(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):Cn(n)?new Uint8Array(n):Uint8Array.from(n)}var fn=100,Gn=2048,xA=class n{constructor(A){this.entered=!1,this.extensionCodec=A?.extensionCodec??U.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??fn,this.initialBufferSize=A?.initialBufferSize??Gn,this.sortKeys=A?.sortKeys??!1,this.forceFloat32=A?.forceFloat32??!1,this.ignoreUndefined=A?.ignoreUndefined??!1,this.forceIntegerToFloat=A?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(A){if(this.entered)return this.clone().encodeSharedRef(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(A){if(this.entered)return this.clone().encode(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(A,t){if(t>this.maxDepth)throw new Error(\`Too deep objects in depth \${t}\`);A==null?this.encodeNil():typeof A=="boolean"?this.encodeBoolean(A):typeof A=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(A):this.encodeNumber(A):typeof A=="string"?this.encodeString(A):this.useBigInt64&&typeof A=="bigint"?this.encodeBigInt64(A):this.encodeObject(A,t)}ensureBufferSizeToWrite(A){let t=this.pos+A;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(A){let t=new ArrayBuffer(A),e=new Uint8Array(t),i=new DataView(t);e.set(this.bytes),this.view=i,this.bytes=e}encodeNil(){this.writeU8(192)}encodeBoolean(A){A===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(A){!this.forceIntegerToFloat&&Number.isSafeInteger(A)?A>=0?A<128?this.writeU8(A):A<256?(this.writeU8(204),this.writeU8(A)):A<65536?(this.writeU8(205),this.writeU16(A)):A<4294967296?(this.writeU8(206),this.writeU32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(207),this.writeU64(A)):A>=-32?this.writeU8(224|A+32):A>=-128?(this.writeU8(208),this.writeI8(A)):A>=-32768?(this.writeU8(209),this.writeI16(A)):A>=-2147483648?(this.writeU8(210),this.writeI32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(211),this.writeI64(A)):this.encodeNumberAsFloat(A)}encodeNumberAsFloat(A){this.forceFloat32?(this.writeU8(202),this.writeF32(A)):(this.writeU8(203),this.writeF64(A))}encodeBigInt64(A){A>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(A)):(this.writeU8(211),this.writeBigInt64(A))}writeStringHeader(A){if(A<32)this.writeU8(160+A);else if(A<256)this.writeU8(217),this.writeU8(A);else if(A<65536)this.writeU8(218),this.writeU16(A);else if(A<4294967296)this.writeU8(219),this.writeU32(A);else throw new Error(\`Too long string: \${A} bytes in UTF-8\`)}encodeString(A){let e=Ij(A);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),Ej(A,this.bytes,this.pos),this.pos+=e}encodeObject(A,t){let e=this.extensionCodec.tryToEncode(A,this.context);if(e!=null)this.encodeExtension(e);else if(Array.isArray(A))this.encodeArray(A,t);else if(ArrayBuffer.isView(A))this.encodeBinary(A);else if(typeof A=="object")this.encodeMap(A,t);else throw new Error(\`Unrecognized object: \${Object.prototype.toString.apply(A)}\`)}encodeBinary(A){let t=A.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(\`Too large binary: \${t}\`);let e=sA(A);this.writeU8a(e)}encodeArray(A,t){let e=A.length;if(e<16)this.writeU8(144+e);else if(e<65536)this.writeU8(220),this.writeU16(e);else if(e<4294967296)this.writeU8(221),this.writeU32(e);else throw new Error(\`Too large array: \${e}\`);for(let i of A)this.doEncode(i,t+1)}countWithoutUndefined(A,t){let e=0;for(let i of t)A[i]!==void 0&&e++;return e}encodeMap(A,t){let e=Object.keys(A);this.sortKeys&&e.sort();let i=this.ignoreUndefined?this.countWithoutUndefined(A,e):e.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(\`Too large map object: \${i}\`);for(let d of e){let q=A[d];this.ignoreUndefined&&q===void 0||(this.encodeString(d),this.doEncode(q,t+1))}}encodeExtension(A){if(typeof A.data=="function"){let e=A.data(this.pos+6),i=e.length;if(i>=4294967296)throw new Error(\`Too large extension object: \${i}\`);this.writeU8(201),this.writeU32(i),this.writeI8(A.type),this.writeU8a(e);return}let t=A.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(\`Too large extension object: \${t}\`);this.writeI8(A.type),this.writeU8a(A.data)}writeU8(A){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,A),this.pos++}writeU8a(A){let t=A.length;this.ensureBufferSizeToWrite(t),this.bytes.set(A,this.pos),this.pos+=t}writeI8(A){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,A),this.pos++}writeU16(A){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,A),this.pos+=2}writeI16(A){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,A),this.pos+=2}writeU32(A){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,A),this.pos+=4}writeI32(A){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,A),this.pos+=4}writeF32(A){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,A),this.pos+=4}writeF64(A){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,A),this.pos+=8}writeU64(A){this.ensureBufferSizeToWrite(8),Fj(this.view,this.pos,A),this.pos+=8}writeI64(A){this.ensureBufferSizeToWrite(8),_A(this.view,this.pos,A),this.pos+=8}writeBigUint64(A){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,A),this.pos+=8}writeBigInt64(A){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,A),this.pos+=8}};function rr(n,A){return new xA(A).encodeSharedRef(n)}function KA(n){return\`\${n<0?"-":""}0x\${Math.abs(n).toString(16).padStart(2,"0")}\`}var pn=16,hn=16,NA=class{constructor(A=pn,t=hn){this.hit=0,this.miss=0,this.maxKeyLength=A,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,t,e){let i=this.caches[e-1];A:for(let d of i){let q=d.bytes;for(let p=0;p<e;p++)if(q[p]!==A[t+p])continue A;return d.str}return null}store(A,t){let e=this.caches[A.length-1],i={bytes:A,str:t};e.length>=this.maxLengthPerKey?e[Math.random()*e.length|0]=i:e.push(i)}decode(A,t,e){let i=this.find(A,t,e);if(i!=null)return this.hit++,i;this.miss++;let d=Ar(A,t,e),q=Uint8Array.prototype.slice.call(A,t,t+e);return this.store(q,d),d}};var jr="array",oA="map_key",Hj="map_value",mn=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new L("The type of key must be string or number but "+typeof n)},tr=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let t=this.getUninitializedStateFromPool();t.type=jr,t.position=0,t.size=A,t.array=new Array(A)}pushMapState(A){let t=this.getUninitializedStateFromPool();t.type=oA,t.readCount=0,t.size=A,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let A={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(A)}return this.stack[this.stackHeadPosition]}release(A){if(this.stack[this.stackHeadPosition]!==A)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(A.type===jr){let e=A;e.size=0,e.array=void 0,e.position=0,e.type=void 0}if(A.type===oA||A.type===Hj){let e=A;e.size=0,e.map=void 0,e.readCount=0,e.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},lA=-1,er=new DataView(new ArrayBuffer(0)),In=new Uint8Array(er.buffer);try{er.getInt8(0)}catch(n){if(!(n instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var gj=new RangeError("Insufficient data"),En=new NA,BA=class n{constructor(A){this.totalPos=0,this.pos=0,this.view=er,this.bytes=In,this.headByte=lA,this.stack=new tr,this.entered=!1,this.extensionCodec=A?.extensionCodec??U.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.rawStrings=A?.rawStrings??!1,this.maxStrLength=A?.maxStrLength??4294967295,this.maxBinLength=A?.maxBinLength??4294967295,this.maxArrayLength=A?.maxArrayLength??4294967295,this.maxMapLength=A?.maxMapLength??4294967295,this.maxExtLength=A?.maxExtLength??4294967295,this.keyDecoder=A?.keyDecoder!==void 0?A.keyDecoder:En,this.mapKeyConverter=A?.mapKeyConverter??mn}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=lA,this.stack.reset()}setBuffer(A){let t=sA(A);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(A){if(this.headByte===lA&&!this.hasRemaining(1))this.setBuffer(A);else{let t=this.bytes.subarray(this.pos),e=sA(A),i=new Uint8Array(t.length+e.length);i.set(t),i.set(e,t.length),this.setBuffer(i)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:t,pos:e}=this;return new RangeError(\`Extra \${t.byteLength-e} of \${t.byteLength} byte(s) found at buffer[\${A}]\`)}decode(A){if(this.entered)return this.clone().decode(A);try{this.entered=!0,this.reinitializeState(),this.setBuffer(A);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(A){if(this.entered){yield*this.clone().decodeMulti(A);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(A);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(A){if(this.entered)return this.clone().decodeAsync(A);try{this.entered=!0;let t=!1,e;for await(let p of A){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(p);try{e=this.doDecodeSync(),t=!0}catch(F){if(!(F instanceof RangeError))throw F}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return e}let{headByte:i,pos:d,totalPos:q}=this;throw new RangeError(\`Insufficient data in parsing \${KA(i)} at \${q} (\${d} in the current buffer)\`)}finally{this.entered=!1}}decodeArrayStream(A){return this.decodeMultiAsync(A,!0)}decodeStream(A){return this.decodeMultiAsync(A,!1)}async*decodeMultiAsync(A,t){if(this.entered){yield*this.clone().decodeMultiAsync(A,t);return}try{this.entered=!0;let e=t,i=-1;for await(let d of A){if(t&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(d),e&&(i=this.readArraySize(),e=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(q){if(!(q instanceof RangeError))throw q}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){A:for(;;){let A=this.readHeadByte(),t;if(A>=224)t=A-256;else if(A<192)if(A<128)t=A;else if(A<144){let i=A-128;if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A<160){let i=A-144;if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else{let i=A-160;t=this.decodeString(i,0)}else if(A===192)t=null;else if(A===194)t=!1;else if(A===195)t=!0;else if(A===202)t=this.readF32();else if(A===203)t=this.readF64();else if(A===204)t=this.readU8();else if(A===205)t=this.readU16();else if(A===206)t=this.readU32();else if(A===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(A===208)t=this.readI8();else if(A===209)t=this.readI16();else if(A===210)t=this.readI32();else if(A===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(A===217){let i=this.lookU8();t=this.decodeString(i,1)}else if(A===218){let i=this.lookU16();t=this.decodeString(i,2)}else if(A===219){let i=this.lookU32();t=this.decodeString(i,4)}else if(A===220){let i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===221){let i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===222){let i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===223){let i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===196){let i=this.lookU8();t=this.decodeBinary(i,1)}else if(A===197){let i=this.lookU16();t=this.decodeBinary(i,2)}else if(A===198){let i=this.lookU32();t=this.decodeBinary(i,4)}else if(A===212)t=this.decodeExtension(1,0);else if(A===213)t=this.decodeExtension(2,0);else if(A===214)t=this.decodeExtension(4,0);else if(A===215)t=this.decodeExtension(8,0);else if(A===216)t=this.decodeExtension(16,0);else if(A===199){let i=this.lookU8();t=this.decodeExtension(i,1)}else if(A===200){let i=this.lookU16();t=this.decodeExtension(i,2)}else if(A===201){let i=this.lookU32();t=this.decodeExtension(i,4)}else throw new L(\`Unrecognized type byte: \${KA(A)}\`);this.complete();let e=this.stack;for(;e.length>0;){let i=e.top();if(i.type===jr)if(i.array[i.position]=t,i.position++,i.position===i.size)t=i.array,e.release(i);else continue A;else if(i.type===oA){if(t==="__proto__")throw new L("The key __proto__ is not allowed");i.key=this.mapKeyConverter(t),i.type=Hj;continue A}else if(i.map[i.key]=t,i.readCount++,i.readCount===i.size)t=i.map,e.release(i);else{i.key=null,i.type=oA;continue A}}return t}}readHeadByte(){return this.headByte===lA&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=lA}readArraySize(){let A=this.readHeadByte();switch(A){case 220:return this.readU16();case 221:return this.readU32();default:{if(A<160)return A-144;throw new L(\`Unrecognized array type byte: \${KA(A)}\`)}}}pushMapState(A){if(A>this.maxMapLength)throw new L(\`Max length exceeded: map length (\${A}) > maxMapLengthLength (\${this.maxMapLength})\`);this.stack.pushMapState(A)}pushArrayState(A){if(A>this.maxArrayLength)throw new L(\`Max length exceeded: array length (\${A}) > maxArrayLength (\${this.maxArrayLength})\`);this.stack.pushArrayState(A)}decodeString(A,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(A,t):this.decodeBinary(A,t)}decodeUtf8String(A,t){if(A>this.maxStrLength)throw new L(\`Max length exceeded: UTF-8 byte length (\${A}) > maxStrLength (\${this.maxStrLength})\`);if(this.bytes.byteLength<this.pos+t+A)throw gj;let e=this.pos+t,i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?i=this.keyDecoder.decode(this.bytes,e,A):i=$j(this.bytes,e,A),this.pos+=t+A,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===oA:!1}decodeBinary(A,t){if(A>this.maxBinLength)throw new L(\`Max length exceeded: bin length (\${A}) > maxBinLength (\${this.maxBinLength})\`);if(!this.hasRemaining(A+t))throw gj;let e=this.pos+t,i=this.bytes.subarray(e,e+A);return this.pos+=t+A,i}decodeExtension(A,t){if(A>this.maxExtLength)throw new L(\`Max length exceeded: ext length (\${A}) > maxExtLength (\${this.maxExtLength})\`);let e=this.view.getInt8(this.pos+t),i=this.decodeBinary(A,t+1);return this.extensionCodec.decode(i,e,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let A=this.view.getUint8(this.pos);return this.pos++,A}readI8(){let A=this.view.getInt8(this.pos);return this.pos++,A}readU16(){let A=this.view.getUint16(this.pos);return this.pos+=2,A}readI16(){let A=this.view.getInt16(this.pos);return this.pos+=2,A}readU32(){let A=this.view.getUint32(this.pos);return this.pos+=4,A}readI32(){let A=this.view.getInt32(this.pos);return this.pos+=4,A}readU64(){let A=vj(this.view,this.pos);return this.pos+=8,A}readI64(){let A=DA(this.view,this.pos);return this.pos+=8,A}readU64AsBigInt(){let A=this.view.getBigUint64(this.pos);return this.pos+=8,A}readI64AsBigInt(){let A=this.view.getBigInt64(this.pos);return this.pos+=8,A}readF32(){let A=this.view.getFloat32(this.pos);return this.pos+=4,A}readF64(){let A=this.view.getFloat64(this.pos);return this.pos+=8,A}};function nr(n,A){return new BA(A).decode(n)}var aA=class n{constructor(A,t,e,i,d){this.mediaIds=A;this.sequenceNumber=t;this.timeStamp=e;this.isEndOfSpurt=i;this.payload=d}static parse(A){let t;try{t=nr(A)}catch{return D("not valid msgpack")}if(!Array.isArray(t))return D("container must be an array");if(t.length<6)return D("missing fields");if(t[0]!==1)return D("unknown type");if(!Array.isArray(t[1]))return D("media ids must be an array");if(!t[1].every(x=>typeof x=="number"))return D("media ids must be numbers");if(typeof t[2]!="number")return D("sequence number must be a number");if(typeof t[3]!="number")return D("timestamp must be a number");if(typeof t[4]!="number")return D("flags must be a number");let e=t[1],i=t[2]>>>0,d=t[3]>>>0,p=(t[4]&1)!==0,F=t[t.length-1];return F instanceof Uint8Array?kj(new n(e,i,d,p,F)):D("payload must be bytes")}toBytes(){let A=Number(this.isEndOfSpurt),t=[1,this.mediaIds,this.sequenceNumber>>>0,this.timeStamp>>>0,A,this.payload];return new Uint8Array(rr(t,{forceFloat32:!0,ignoreUndefined:!0}))}};var JA=class{constructor(A,t){this.sampleRate=A;this.wasm=t;this.sequenceNumber=Math.random()*Math.pow(2,32)>>0;this.timestamp=Math.random()*Math.pow(2,32)>>0;this.connections=[];this.monitoring=!1;this.active=!1;this.stats={numberPackets:0,numberTicks:0,numberPacketError:0,numberPacketsMediaNotFound:0};this.encoder=new t.Encoder(A,15,!0,M.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=hj(this.wasm),this.outBuffer=b(this.wasm,"u8",1270),gA(this.information,1)}setVad(A){this.encoder.set_volume_gate(A.volumeGate!==void 0,A.volumeGate?.attackThreshold??0,A.volumeGate?.releaseThreshold??0),this.encoder.set_speech_detection(A.voiceActivity!==void 0,A.voiceActivity?.attackThreshold??0,A.voiceActivity?.releaseThreshold??0)}setMedias(A){this.connections=A.filter(({mediaIds:t})=>t.length>0)}close(){mj(this.wasm,this.information),W(this.wasm,this.outBuffer),this.encoder.delete()}encode(A){for(this.encoder.push(A.byteOffset,this.information.values.byteOffset);;){let t=this.encoder.pop(this.connections.length===0?0:this.outBuffer.byteOffset,this.outBuffer.length);if(t===0)break;if(t<0){Cj(\`failed encoding packet: \${t}\`);return}if(this.timestamp=this.timestamp+1800>>0,t===1)continue;this.sequenceNumber=this.sequenceNumber+1>>0;let e=this.active&&!this.encoder.active;this.active=this.encoder.active,this.monitoring=this.connections.some(i=>i.id===0);for(let i of this.connections){if(this.monitoring&&i.id!==0)continue;let d=new aA(i.mediaIds,this.sequenceNumber,this.timestamp,e,this.outBuffer.subarray(0,t));T(globalThis,["sendPacket",{connectionId:i.id,packet:d.toBytes()}])}}}onMessage(A){let[t,e]=A;switch(t){case"captureSetVad":this?.setVad(e);break;case"captureSetMedias":this?.setMedias(e.connections);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){return{sequenceNumber:this.sequenceNumber,timestamp:this.timestamp,connections:this.connections.map(A=>\`\${A.id} => \${A.mediaIds.join(",")}\`),active:this.active,monitoring:this.monitoring,information:{active:FA(this.information),speechProbability:vA(this.information),rmsDBFS:LA(this.information),volume:nj(this.information)},encoder:{sample_rate:this.encoder.sample_rate,fec_packet_loss:this.encoder.fec_packet_loss,voip:this.encoder.voip,vad_preload:this.encoder.vad_preload,complexity:this.encoder.complexity,speech_probability:this.encoder.speech_probability,rms_dbfs:this.encoder.rms_dbfs,active:this.encoder.active,speech_detection_enabled:this.encoder.speech_detection_enabled,speech_detection_going_active:this.encoder.speech_detection_going_active,speech_detection_going_inactive:this.encoder.speech_detection_going_inactive,volume_gate_enabled:this.encoder.volume_gate_enabled,volume_gate_going_active:this.encoder.volume_gate_going_active,volume_gate_going_inactive:this.encoder.volume_gate_going_inactive}}}},bA=class{constructor(A){this.wasm=A;this.medias=new Map;this.stats={numberPackets:0,numberTicks:0,numberPacketError:0,numberPacketsMediaNotFound:0,numberTicksWithAudio:0};this.largestIndex=-1;this.decoders=b(this.wasm,"u32",M.MaxNumberOfDecoders),this.information=Gj(this.wasm,M.MaxNumberOfDecoders),IA(this.information,[1,1])}close(){pj(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,t){this.stats.numberPackets++;let e=aA.parse(t);if(e.type==="Failure"){this.stats.numberPacketError++;let i=Array.from(t).map(d=>d.toString(16).padStart(2,"0")).join("");console.error(\`failed decoding audio packet; reason: \${e.reason}, connection: \${A}, dump: \${i}\`);return}for(let i of e.value.mediaIds){let d=this.medias.get(yA({connectionId:A,mediaId:i}));if(d===void 0){this.stats.numberPacketsMediaNotFound++;continue}d.lastPacket=t;let q=b(this.wasm,"u8",e.value.payload.length);q.set(e.value.payload),d.decoder.push(e.value.sequenceNumber,e.value.timeStamp,e.value.isEndOfSpurt,q.byteOffset,q.length)}}insertMedia(A,t,e,i=[1,1]){let d=yA({connectionId:t,mediaId:e}),q=new this.wasm.Decoder;this.medias.set(d,{index:A,decoder:q,lastPacket:void 0}),this.decoders[A]=q.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),$A(this.information,A,i),ej(this.information,A,0),jj(this.information,A,0)}removeMedia(A,t,e){let i=yA({connectionId:t,mediaId:e}),d=this.medias.get(i);if(!(d===void 0||d.index!==A)&&(this.medias.delete(i),Zr(this.information,A,0),this.decoders[A]=0,d.decoder.delete(),A===this.largestIndex)){for(A=A-1;A>=0&&this.decoders[A]===0;A--);this.largestIndex=A}}decode(A){return{hasAudio:this.wasm.pop_many(this.decoders.byteOffset,this.information.values.byteOffset,this.largestIndex+1,A.byteOffset)}}onMessage(A){let[t,e]=A;switch(t){case"playbackReceivePacket":this.receivePacket(e.connectionId,e.packet);break;case"playbackUpdateMedias":for(let{index:i,connectionId:d,mediaId:q}of e.removed)this.removeMedia(i,d,q);for(let{index:i,connectionId:d,mediaId:q,volume:p}of e.added)this.insertMedia(i,d,q,p);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){let A=[];for(let[t,e]of this.medias){let i=fj(t);A.push({index:e.index,connectionId:i.connectionId,mediaId:i.mediaId,rmsDBFS:EA(this.information,e.index),volume:Aj(this.information,e.index),voicedBlocks:tj(this.information,e.index),silentBlocks:rj(this.information,e.index),time:e.decoder.time,consecutive_silence:e.decoder.consecutive_silence,last_voiced_time_point:e.decoder.last_voiced_time_point,sequence_number:e.decoder.sequence_number,packetsSeen:e.decoder.packets_seen,packetsInvalid:e.decoder.packets_invalid,packetsTooLate:e.decoder.packets_too_late,packetsTooEarly:e.decoder.packets_too_early,packetsRepeated:e.decoder.packets_repeated,packetsProcessed:e.decoder.packets_processed,packetsLost:e.decoder.packets_lost,rewinds:e.decoder.rewinds,cacheLength:e.decoder.cache_length,lastPacket:sj(e.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:Yr(this.information),decoders:A}}};var Nj=pe(_j()),Dj=(0,Nj.default)(),xj,Kj;globalThis.addEventListener("message",ir);async function ir(n){let A=n.data,[t,e]=A;switch(t){case"captureInit":e.workletPort.onmessage=ir,xj=new lr(e.sampleRate,await Dj,e.refreshRate);break;case"playbackInit":e.workletPort.onmessage=ir,Kj=new or(await Dj,e.workletPort,e.refreshRate);break;case"close":globalThis.close();break}xj?.onMessage(A),Kj?.onMessage(A)}var lr=class extends JA{constructor(t,e,i){super(t,e);this.sampleRate=t;this.inBuffer=b(this.wasm,"f32",t*.02),this.updateHandle=setInterval(()=>this.update(),i),T(globalThis,["captureReady",{}])}close(){super.close(),W(this.wasm,this.inBuffer),clearInterval(this.updateHandle)}onMessage(t){super.onMessage(t);let[e,i]=t;switch(e){case"captureSetVolume":this.setVolume(i.value);break;case"captureTick":this.tick(i.buffer);break}}setVolume(t){gA(this.information,t)}tick(t){this.inBuffer.set(t,0),this.encode(this.inBuffer)}update(){T(globalThis,["captureUpdate",{active:FA(this.information),rmsDBFs:LA(this.information),speechProbability:vA(this.information)}])}dump(){return{type:"unshared capture worker",sampleRate:this.sampleRate,...super.dump()}}},or=class extends bA{constructor(t,e,i){super(t);this.workletPort=e;this.id=M.PlaybackPreload,this.outBuffer=b(this.wasm,"f32",48e3*.02*2),this.updateHandle=setInterval(()=>this.update(),i),T(globalThis,["playbackReady",{}])}close(){super.close(),W(this.wasm,this.outBuffer),clearInterval(this.updateHandle)}onMessage(t){super.onMessage(t);let[e,i]=t;switch(e){case"playbackSetVolume":this.setVolume(i.index,i.value);break;case"playbackTick":this.tick();break}}setVolume(t,e){t==="global"?IA(this.information,e):$A(this.information,t,e)}tick(){this.stats.numberTicks++,this.id+=1;let{hasAudio:t}=this.decode(this.outBuffer);if(t){let e=this.outBuffer.slice();T(this.workletPort,["samples",{id:this.id,buffer:e}],[e.buffer])}}update(){let t=new Float32Array(this.information.length*2);for(let i=0;i<=this.largestIndex;i++)t[i]=EA(this.information,i);let e=[];for(let[i,d]of this.medias)e[d.index]={packetsBuffered:d.decoder.cache_length,packetsSeen:d.decoder.packets_seen,packetsProcessed:d.decoder.packets_processed,packetsTooEarly:d.decoder.packets_too_early,packetsTooLate:d.decoder.packets_too_late,packetsDropped:0,packetsInvalid:d.decoder.packets_invalid,packetsRepeated:d.decoder.packets_repeated,packetsLost:d.decoder.packets_lost};T(globalThis,["playbackUpdate",{activities:t,jitterStats:e}],[t.buffer])}dump(){return{type:"unshared playback worker",id:this.id,...super.dump()}}};})();
6413
+ `});var Xx,g0=d(()=>{Xx='"use strict";(()=>{var P=Object.defineProperty;var M=(e,t)=>{for(var r in t)P(e,r,{get:t[r],enumerable:!0})};var u={};M(u,{AdditionalCaptureBlocks:()=>R,AdditionalPlaybackBlocks:()=>E,ClockJumpCheckInterval:()=>_,ClockJumpThreshold:()=>N,ConnectInterval:()=>Z,ConnectTimeout:()=>J,DefaultRefreshRate:()=>D,DefaultVideoCodec:()=>q,HealthCheckTimeout:()=>O,MainConnectionPingInterval:()=>W,MaxNumberOfDecoders:()=>L,MinDBFs:()=>v,MinTokenLifetime:()=>z,MinTokenRefreshInterval:()=>G,PlaybackPreload:()=>F,RenderQuantumSize:()=>V,VadPreload:()=>C,WebRtcIceTimeout:()=>j,WebRtcStatsSnapshotInterval:()=>$,WebRtcTimeout:()=>H});var E=3,R=3,F=3,D=250,C=3,L=512,V=128,v=-758.596,O=1e4,_=1e3,N=1e4,W=3e3,$=1e3,j=3e3,H=1e4,J=5e3,z=6e4,G=5e3,Z=[0,100,200,200,500],q="H264";function d(e,t,r){return e.postMessage(t,r)}var Q;(e=>{let t;(r=>(r[r.InvalidPassword=-1]="InvalidPassword",r[r.Unknown=0]="Unknown",r[r.Unencrypted=1]="Unencrypted",r[r.Encrypted=2]="Encrypted"))(t=e.PeerCipherStatus||={})})(Q||={});var{Deno:k}=globalThis,K=typeof k?.noColor=="boolean"?k.noColor:!1,X=!K;function m(e,t){return{open:`\\x1B[${e.join(";")}m`,close:`\\x1B[${t}m`,regexp:new RegExp(`\\\\x1b\\\\[${t}m`,"g")}}function h(e,t){return X?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}function p(e){return h(e,m([0],0))}function U(e){return h(e,m([1],22))}function Y(e){return h(e,m([2],22))}var ke=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),ee=new Date,f=(e=>(e[e.CRITICAL=0]="CRITICAL",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(f||{}),T={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},te={4:Y,3:p,2:p,1:U,0:U};function re({message:e}){return String(e)}function S(e){return JSON.stringify({timestamp:e.date.toISOString(),level:f[e.level],message:e.message,extra:e.extra})}function I(e){function t(c,i){return[Math.floor(c/i),c%i]}function r(){let c,i=e.date.valueOf()-ee.valueOf();[i,c]=t(i,1e3);let[B,A]=t(i,60);return`${B.toString().padStart(4,"0")}:${A.toString().padStart(2,"0")}.${c.toString().padStart(4,"0")}`}function n(){return e.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(e.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(e.extra)}let s=T[e.level],a=e.logger.name!==void 0?`@${e.logger}`:"";return`${p(r())}${a} ${s} ${te[e.level](String(e.message))}${n()}`}function ne(e){let t=`[${e.date.toISOString()}]`,r=`[${f[e.level]}]`,n=e.logger.name!==void 0?`[${e.logger.name}] `:"",s=T[e.level];return`${t} ${s} ${r.padEnd(7," ")} ${n}${e.message}`}function se(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var w=class{static sparse=re;static json=S;static pretty=I;static structured=ne;static default=se()?I:S;constructor(){}},oe=class{formatter;consoleObject;filter;constructor(e=w.default,t=4,r=console){this.filter=t,this.formatter=e,this.consoleObject=r}handle(e){let t=this.formatter(e);switch(e.level){case 1:this.consoleObject.error(t);break;case 2:this.consoleObject.warn(t);break;case 3:this.consoleObject.info(t);break;case 4:this.consoleObject.debug(t);break}}};var o=class{#e;sinks;filter;parent;get name(){return this.#e}constructor(e,t=void 0,r=[],n=void 0){this.#e=t,this.sinks=r,this.filter=e,this.parent=n}log(e,t,r=void 0){let n={date:new Date,level:e,logger:this,message:t,extra:r};this.filter<e||this.insert(n)}insert(e){if(!(this.filter<e.level)){for(let t of this.sinks)t.filter>=e.level&&t.handle(e);this.parent!==void 0&&this.parent.insert(e)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},l=new o(3,void 0,[new oe]),ae=o.prototype.log.bind(l,1),ie=o.prototype.log.bind(l,2),ce=o.prototype.log.bind(l,3),ue=o.prototype.log.bind(l,4),Ue=o.prototype.log.bind(l);var b=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.blocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"init":this.state=new y(s.workerPort,sampleRate*.02);break;case"close":this.alive=!1;break;case"dump":s.result.postMessage(this.dump());break}}process(r,n,s){if(this.state===void 0||r.length<1||r[0].length<1)return this.alive;let a=this.state.fill(0,r[0][0]);return this.state.offset===this.state.length&&(this.state.flush(),this.state.fill(a,r[0][0])),this.alive}dump(){return{type:"unshared capture worklet",alive:this.alive,sampleRate,offset:this.state?.offset||null,length:this.state?.length||null,blocks:this.blocks}}},x=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.silenceBlocks=0;this.voiceBlocks=0;this.totalBlocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"close":this.alive=!1;break;case"init":this.state=new g(s.workerPort,sampleRate*.02),s.workerPort.onmessage=this.onMessage.bind(this);break;case"samples":this.state?.add(s.id,s.buffer);break;case"dump":s.result.postMessage(this.dump());break}n==="close"&&(this.alive=!1)}process(r,n,s){if(this.state===void 0||n.length<1||n[0].length<2)return this.alive;let a=this.state.fill(0,n[0][0],n[0][1]);return a<u.RenderQuantumSize&&(this.totalBlocks+=1,this.state.next(),this.state.hasVoice?this.voiceBlocks+=1:this.silenceBlocks+=1,this.state.fill(a,n[0][0],n[0][1])),this.alive}dump(){return{type:"unshared playback worklet",alive:this.alive,sampleRate,id:this.state?.id||null,offset:this.state?.offset||null,length:this.state?.length||null,hasVoice:this.state?.hasVoice??!1,silenceBlocks:this.silenceBlocks,voiceBlocks:this.voiceBlocks,totalBlocks:this.totalBlocks}}},y=class{constructor(t,r){this.port=t;this.length=r;this.offset=0,this.buffer=new Float32Array(r)}fill(t,r){let n=Math.min(r.length-t,this.length-this.offset);return this.buffer.set(r.subarray(t,t+n),this.offset),this.offset+=n,t+n}flush(){d(this.port,["captureTick",{buffer:this.buffer}],[this.buffer.buffer]),this.offset=0,this.buffer=new Float32Array(this.length)}},g=class{constructor(t,r){this.port=t;this.length=r;this.cache=[];this.id=-1,this.offset=0,this.buffer=void 0,this.next()}get hasVoice(){return this.buffer!==void 0}fill(t,r,n){let s=Math.min(u.RenderQuantumSize-t,this.length-this.offset);return this.buffer!==void 0&&(r.set(this.buffer.subarray(this.offset,this.offset+s),t),n.set(this.buffer.subarray(this.offset+this.length,this.offset+this.length+s),t)),this.offset+=s,t+s}add(t,r){this.cache.push({id:t,buffer:r})}next(){for(this.id+=1;this.cache[0]?.id<this.id;)this.cache.shift();this.cache[0]?.id===this.id?(this.buffer=this.cache[0].buffer,this.cache.shift()):this.buffer=void 0,this.offset=0,d(this.port,["playbackTick",{}])}};registerProcessor("OdinCaptureProcessor",b);registerProcessor("OdinPlaybackProcessor",x);})();\n'});var y0={};Ox(y0,{UnsharedCaptureWorker:()=>fx,UnsharedPlaybackWorker:()=>nx,createCaptureWorker:()=>jF,createPlaybackWorker:()=>eF});import{Strand as DF}from"@4players/odin-common";function jF(v,t,j,e,B=i.DefaultRefreshRate){return tF.enqueue(async()=>{let[C,E]=await Z(zx,Xx,v,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return console.warn("SharedArrayBuffer is not available; creating ODIN CaptureWorker in fallback mode"),fx.create(v,t,j,B,C,E,e)})}async function eF(v,t=i.DefaultRefreshRate){if(v.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[j,e]=await Z(zx,Xx,v,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return nx.create(v,t,j,e)}var tF,fx,nx,_0=d(()=>{"use strict";u();Ex();$0();g0();tF=new DF;fx=class v extends Q{constructor(j,e,B,C,E){super(j,e,B,C,E);this._Activity=y;this._SpeechProbability=0;e.addEventListener("message",this._OnMessages.bind(this))}static async create(j,e,B,C,E,f,s){let{port1:a,port2:q}=new MessageChannel;return k(E,["captureInit",{sampleRate:j.sampleRate,refreshRate:C,workletPort:a}],[a]),await W(E,"captureReady"),k(f.port,["init",{workerPort:q}],[q]),new v(f,E,e,B,s)}get activity(){return this._Activity}get speechProbability(){return this._SpeechProbability}setVolume(j){k(this.worker,["captureSetVolume",{value:j}])}_OnMessages(j){super._OnMessages(j);let[e,B]=j.data;e==="captureUpdate"&&(this._Activity={isSilent:!B.active,rmsDBFS:B.rmsDBFs},this._SpeechProbability=B.speechProbability)}},nx=class v extends X{constructor(j,e,B){super(j,e,B);this.activities=new Float32Array;this.jitterStats=[]}static async create(j,e,B,C){let{port1:E,port2:f}=new MessageChannel;return k(B,["playbackInit",{workletPort:E,refreshRate:e}],[E]),await W(B,"playbackReady"),k(C.port,["init",{workerPort:f}],[f]),C.connect(j.destination),new v(j,C,B)}getActivity(j){let e=this.medias.get(p(j));if(e===void 0)return;let B=this.activities.at(e.index);if(B!==void 0)return B===0?y:{isSilent:!1,rmsDBFS:B}}getJitterStats(j){let e=this.medias.get(p(j));if(e===void 0)return;let B=this.jitterStats.at(e.index);if(B!==void 0)return B}setGlobalVolume(j){k(this.worker,["playbackSetVolume",{index:"global",value:j}])}setVolume(j,e){let B=this.medias.get(p(j));B!==void 0&&k(this.worker,["playbackSetVolume",{index:B.index,value:e}])}_GetFreeIndex(){let j=super._GetFreeIndex();if(j!==void 0)return j;if(this.medias.size<i.MaxNumberOfDecoders)return this.medias.size}_OnMessages(j){super._OnMessages(j);let[e,B]=j.data;e==="playbackUpdate"&&(this.activities=B.activities,this.jitterStats=B.jitterStats)}}});u();import{Backend as r,generateUUID as br}from"@4players/odin-common";u();import{Backend as x,JITTER_STATS_INITIAL as K0,Strand as sF,assert as iF}from"@4players/odin-common";u();import{APM_DEFAULTS as CF,Backend as hB,generateUUID as EF,VAD_DEFAULTS as fF}from"@4players/odin-common";import{failure as c0,isFirefoxBrowser as TA,sleep as SA,success as RA}from"@4players/odin-common";async function d0(v,t,j){let e;if(t.device?.device.kind==="track"&&t.device?.device.audioTrack)e=new MediaStream([t.device.device.audioTrack]);else{let E=t.device?{exact:t.device.device.deviceId==="default"?void 0:t.device.device.deviceId}:void 0;try{let f=await Promise.race([navigator.mediaDevices.getUserMedia({audio:{echoCancellation:j.echoCanceller,noiseSuppression:j.noiseSuppression!=="None",autoGainControl:j.gainController,echoCancellationType:"system",deviceId:E}}),SA(3e4,"timeout")]);if(f==="timeout")return c0("getUserMedia; timeout");e=f}catch(f){return c0(`getUserMedia; ${f}`)}}let B=e.getAudioTracks()[0].getSettings().sampleRate,C=await v.audioContexts.acquire(B);return RA(C.createMediaStreamSource(e))}function R(v){v.getTracks().forEach(t=>{t.stop(),v.removeTrack(t)})}async function p0(v){return new _({deviceId:v.id,kind:"track",name:v.label??"MediaStreamTrack",audioTrack:v},!1)}async function Cx(){if(TA()){let B=await VA("microphone");(B==="granted"||B===!1)&&await UA("audio")}let v=(await navigator.mediaDevices.enumerateDevices()).filter(B=>!!B.label),t=[],j=new _({deviceId:"default",name:"Default",kind:"audioinput"},!0),e=new _({deviceId:"default",name:"Default",kind:"audiooutput"},!0);t.push(j),t.push(e);for(let B of v){if(B.deviceId==="default"){B.kind==="audioinput"&&(j=new _({deviceId:"default",name:B.label,kind:"audioinput"},!0),t[0]=j),B.kind==="audiooutput"&&(e=new _({deviceId:"default",name:B.label,kind:"audiooutput"},!0),t[1]=e);continue}B.kind==="audioinput"&&t.push(new _({deviceId:B.deviceId,name:B.label,kind:"audioinput"},!1)),B.kind==="audiooutput"&&t.push(new _({deviceId:B.deviceId,name:B.label,kind:"audiooutput"},!1))}return t}async function VA(v){try{return(await navigator.permissions.query({name:v})).state}catch{return!1}}async function UA(v){try{let t=await navigator.mediaDevices.getUserMedia({[v]:!0});return t?.getTracks().forEach(j=>{j.stop(),t.removeTrack(j)}),!0}catch{return!1}}u();import{isSafariBrowser as BF,isSharedArrayBufferCapable as vF}from"@4players/odin-common";var L0=vF()&&!BF()?Promise.resolve().then(()=>(I0(),G0)):Promise.resolve().then(()=>(_0(),y0));async function H0(v,t,j,e){return L0.then(B=>B.createCaptureWorker(v,t,j,e,i.DefaultRefreshRate))}async function N0(v){return L0.then(t=>t.createPlaybackWorker(v,i.DefaultRefreshRate))}var K=class{constructor(t,j){this.controller=t;this._Medias=new Map;this._Vad={...fF};this._Apm={...CF};this._Volume=1;this._ProcessingDevice=!1;this._DeviceCb=async()=>{(await Cx()).some(e=>e.device.deviceId===this._DeviceParameters?.device?.device.deviceId)||(this._DeviceParameters?.onStatusChanged?.("stopped"),navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._DeviceParameters=void 0,this._Capture!==void 0&&(R(this._Capture.source.mediaStream),this._Capture.source.disconnect(this._Capture.worker.worklet)))};j.apm&&this.setApm(j.apm).catch(console.error),j.vad&&this.setVad(j.vad),typeof j.volume<"u"&&this.setVolume(j.volume).catch(console.error),this.uid=EF(),this.#x=j.customType,this.#A=j.ref}#x;#A;get vad(){return this._Vad}get apm(){return this._Apm}get volume(){return this._Volume}get activity(){return this._Capture?.worker.activity??y}get speechProbability(){return this._Capture?.worker.speechProbability??0}get deviceId(){return this._DeviceParameters?.device?.device.deviceId}async start(t,j){let e=this._Medias.get(j.connectionId);e===void 0&&this._Medias.set(j.connectionId,e=new Set),b(`starting audio capture media ${j.mediaId} on connection ${j.connectionId}`),!e.has(j.mediaId)&&(e.add(j.mediaId),t.mainConnection?.id===j.connectionId&&await t.request("StartMedia",{media_id:j.mediaId,properties:{kind:"audio",uid:this.uid,ref:this.#A,customType:this.#x}}).catch(B=>c(`StartMedia got rejected; ${B}`)),this._UpdateMedias())}async stop(t,j){let e=this._Medias.get(j.connectionId);b(`stopping audio capture media ${j.mediaId} on connection ${j.connectionId}`),e?.delete(j.mediaId)&&(t.mainConnection?.id===j.connectionId&&await t.request("StopMedia",{media_id:j.mediaId}).catch(B=>c(`StopMedia got rejected; ${B}`)),this._UpdateMedias())}setVad(t){o("updating vad config",t),this._Vad=t,this._Capture&&this._Capture.worker.setVad(t)}async setApm(t){o("updating apm config",t),this._Apm=t,this._DeviceParameters&&await this.setDevice(this._DeviceParameters)}async setDevice(t){if(o("updating capture device parameters",t),this._ProcessingDevice)return;this._ProcessingDevice=!0;let j=this._DeviceParameters;if(this._DeviceParameters=t,this._Volume==="muted"){this._ProcessingDevice=!1;return}try{let e=await d0(this.controller,t,{...this._Apm,echoCanceller:this._Monitor?!1:this._Apm.echoCanceller});if(e.type!=="Success"){c(`unable to open capture device; ${e.reason}`),this._DeviceParameters=j,this._ProcessingDevice=!1;return}this._DeviceParameters.onStatusChanged&&navigator.mediaDevices.addEventListener("devicechange",this._DeviceCb),this._Capture!==void 0&&(R(this._Capture.source.mediaStream),this._Capture.source.disconnect(this._Capture.worker.worklet)),this._Capture===void 0||this._Capture.worker.worklet.context!==e.value.context?(this._Capture?.worker.close(),this._Capture={worker:await H0(e.value.context,this.controller.sink,this.controller.receiveMonitoredPacket.bind(this.controller),new WeakRef(this)),source:e.value},await this._UpdateMedias(),await this.setVolume(this._Volume),this.setVad(this.vad)):this._Capture.source=e.value,this._Capture.source.connect(this._Capture.worker.worklet)}catch(e){throw this._ProcessingDevice=!1,new Error(`Error in setDevice(); ${e}`)}this._ProcessingDevice=!1}async setVolume(t){o(`updating capture volume to ${t}`),this._Volume=t,t==="muted"?await this.close():(!this._Capture&&this._DeviceParameters&&await this.setDevice(this._DeviceParameters),this._Capture?.worker.setVolume(t)),t!==this._Volume&&await this.setVolume(this._Volume)}async close(){if(o("closing audio capture"),this._Capture!==void 0){this._Capture.worker.close(),R(this._Capture.source.mediaStream);try{this._Capture.source.disconnect(this._Capture.worker.worklet)}catch(t){h("failed to disconnect audio node",t)}await this.controller.audioContexts.release(this._Capture.source.context)}navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._Capture=void 0}async dump(){let t=[];for(let[j,e]of this._Medias)t.push(`${j} => ${Array.from(e.values()).join(",")}`);return{uid:this.uid,ref:this.#A??null,customType:this.#x??null,worker:await this._Capture?.worker.dump()??null,vad:this._Vad,apm:this._Apm,volume:this._Volume,processingSetDevice:this._ProcessingDevice,medias:t}}async _UpdateMedias(){if(this._Capture!==void 0){let t=Array.from(this._Medias).map(([j,e])=>({id:j,mediaIds:Array.from(e)}));this._Capture.worker.setMedias(t)}}async startLoopback(){this._Monitor===void 0&&(o("starting audio capture loopback"),this.setApm(this._Apm),this._Monitor=await this.controller.createAudioPlayback({uid:"loopback"}),this._Monitor.start({connectionId:0,mediaId:0}),this._Medias.set(0,new Set([0])),await this._UpdateMedias())}async stopLoopback(){this._Monitor!==void 0&&(o("stopping audio capture loopback"),this._Monitor.close(),this._Monitor=void 0,this.setApm(this._Apm),this._Medias.delete(0),await this._UpdateMedias())}};import{assert as sx,Backend as D,generateUUID as nF}from"@4players/odin-common";u();var $=class{constructor(t,j){this.controller=t;this.parameters=j;this.uid=nF()}#x;#A=new Map;#F;get customType(){return this.parameters?.customType}get mediaStream(){return this.#x}get audioCapture(){return this.#F}get volume(){return sx(this.audioCapture,"getting the volume failed, this video has no Audio"),this.audioCapture.volume}async setVolume(t){sx(this.audioCapture,"setVolume() failed, this video has no Audio"),await this.audioCapture.setVolume(t)}get vad(){return sx(this.audioCapture,"getting the vad config failed, this video has no Audio"),this.audioCapture.vad}setVad(t){sx(this.audioCapture,"setVad() failed, this video has no Audio"),this.audioCapture.setVad(t)}async setDevice(t,j={voiceActivity:void 0,volumeGate:void 0}){if(this.#x)throw new Error("This VideoCapture already has a MediaStream.");if(!t.getVideoTracks()[0])throw new Error("Error when calling setDevice(), MediaStream does not contain a VideoStreamTrack!");if(this.#x=t,t.getAudioTracks()[0]){let B={device:await p0(t.getAudioTracks()[0]),vad:j,ref:this.uid};this.#F=await this.controller.createAudioCapture(B)}}async start(t,j){let e=this.#A.get(j.connectionId);if(e===void 0&&this.#A.set(j.connectionId,e=new Set),!e.has(j.mediaId)&&(e.add(j.mediaId),t.mainConnection?.id===j.connectionId)){let B={kind:"video",codec:this.parameters?.codec??"H264",ref:this.#F?.uid,uid:this.uid};this.parameters?.customType&&(B.customType=this.parameters.customType),await t.request("StartMedia",{media_id:j.mediaId,properties:B}).catch(C=>c(`StartMedia got rejected; ${C}`))}}async stop(t,j){this.#x&&R(this.#x),this.#A.get(j.connectionId)?.delete(j.mediaId)&&t.mainConnection?.id===j.connectionId&&await t.request("StopMedia",{media_id:j.mediaId}).catch(B=>c(`StopMedia got rejected; ${B}`))}async dump(){let t=[];for(let[j,e]of this.#A)t.push(`${j} => ${Array.from(e.values()).join(",")}`);return{uid:this.uid,ref:this.#F?.uid??null,customType:this.customType??null,tracks:this.#x?.getVideoTracks().map(j=>({id:j.id,kind:j.kind,label:j.label,ready:j.readyState,muted:j.muted,settings:{...j.getSettings()}}))??[],volume:this.#F?.volume??0,medias:t}}close(){this.#x&&R(this.#x),this.audioCapture?.close(),this.#F=void 0}};u();import{Backend as qB}from"@4players/odin-common";var L=class{constructor(t,j,e){this.controller=t;this.uid=j;this.customType=e}get volume(){return this.controller.playbackGetVolume(this.uid)}get activity(){return this.controller.playbackGetActivity(this.uid)}get jitterStats(){return this.controller.playbackGetJitterStats(this.uid)}start(t){b(`starting audio playback media ${t.mediaId} on connection ${t.connectionId}`),this.controller.playbackStart(this.uid,t)}stop(t){b(`stopping audio playback media ${t.mediaId} on connection ${t.connectionId}`),this.controller.playbackStop(this.uid,t)}setVolume(t){o(`updating audio playback media '${this.uid}' volume to ${t}`),this.controller.playbackSetVolume(this.uid,t)}close(){o(`closing audio playback media '${this.uid}'`),this.controller.closePlayback(this.uid)}};var ix=class{constructor(t){this.audioContextFactory=t;this.entries=[]}async acquire(t){for(let e of this.entries){if(e.sampleRate===t)return e.references+=1,e.audioContext;if(e.sampleRate===void 0&&e.audioContext.sampleRate===t)return e.references+=1,e.audioContext}let j={sampleRate:t,audioContext:await this.audioContextFactory(t),references:1};return this.entries.push(j),j.audioContext}async release(t){let j=this.entries.findIndex(e=>e.audioContext===t);if(!(j<0)&&(this.entries[j].references-=1,this.entries[j].references<=0)){let e=this.entries[j].audioContext;this.entries.splice(j,1),await e.close()}}close(){for(let t of this.entries)t.audioContext.close()}},bx=class v{constructor(t,j){this.audioContexts=t;this.sink=j;this.audioCaptures=[];this.videoCaptures=[];this.globalVolume=[1,1];this.playbacks=new Map;this.setPlaybackStrand=new sF}async create(t,j){return new v(t,j)}receivePacket(t,j){this.playbackWorker?.receivePacket(t,j)}receiveMonitoredPacket(t,j){let e=j.slice();this.receivePacket(t,e)}async createAudioPlayback(t){let j=this.playbacks.get(t.uid),e=t.volume;if(j===void 0){e=e??[1,1];let B=new L(this,t.uid,t.customType);j={id:void 0,volume:e,playback:B},this.playbacks.set(t.uid,j)}return e!==void 0&&j.playback.setVolume(e),j.playback}async createAudioCapture(t){let j=new K(this,t);return await j.setDevice(t),this.audioCaptures.push(new WeakRef(j)),j}async createVideoCapture(t,j){let e=new $(this,j);return await e.setDevice(t),this.videoCaptures.push(new WeakRef(e)),e}playbackSetDevice(t){return this.setPlaybackStrand.enqueue(async()=>{let j=t?.device.deviceId??"";j==="default"&&(j="");let e;if(this.playbackWorker===void 0){e=await this.audioContexts.acquire(48e3),this.playbackWorker=await N0(e),this.playbackWorker.setGlobalVolume(this.globalVolume);for(let[,B]of this.playbacks)B.id!==void 0&&this.playbackWorker.addMedias(B.id.connectionId,[B.id.mediaId],B.volume)}else e=this.playbackWorker.audioContext;e?.setSinkId!==void 0&&t&&e?.state==="running"&&await e.setSinkId(j)})}playbackSetGlobalVolume(t){this.globalVolume=t,this.playbackWorker?.setGlobalVolume(this.globalVolume)}playbackStart(t,j){let e=this.playbacks.get(t);e!==void 0&&(e.id!==void 0&&this.playbackStop(t,e.id),e.id=j,this.playbackWorker?.addMedias(j.connectionId,[j.mediaId],e.volume))}playbackStop(t,j){let e=this.playbacks.get(t);e!==void 0&&(e.id!==j&&h(`playback media ${j.mediaId} on connection ${j.connectionId} is out of sync`,e.id,j),e.id=void 0,this.playbackWorker?.removeMedias(j.connectionId,[j.mediaId]))}playbackGetActivity(t){let j=this.playbacks.get(t);return j?.id===void 0?y:this.playbackWorker?.getActivity(j.id)??y}playbackGetJitterStats(t){let j=this.playbacks.get(t);return j?.id===void 0?K0:this.playbackWorker?.getJitterStats(j.id)??K0}playbackSetVolume(t,j){let e=this.playbacks.get(t);e!==void 0&&(e.volume=j,e.id!==void 0&&this.playbackWorker?.setVolume(e.id,e.volume))}playbackGetVolume(t){return this.playbacks.get(t)?.volume??[1,1]}closePlayback(t){let j=this.playbacks.get(t);j!==void 0&&(j.id!==void 0&&this.playbackStop(t,j.id),this.playbacks.delete(t))}close(){this.playbackWorker?.close(),this.audioContexts.close()}async dump(){let t=[];for(let B of this.audioCaptures){let C=B.deref();C!==void 0&&t.push(await C.dump())}let j=[];for(let B of this.videoCaptures){let C=B.deref();C!==void 0&&j.push(await C.dump())}let e=[];for(let[B,C]of this.playbacks)e.push({uid:B,id:C.id||null,volume:C.volume});return{globalVolume:this.globalVolume,playbackWorker:await this.playbackWorker?.dump()||null,audioCaptures:t,videoCaptures:j,playbacks:e}}},_=class{constructor(t,j=!1){this.device=t;this.isDefault=j}get type(){switch(this.device.kind){case"audioinput":return"AudioCapture";case"audiooutput":return"AudioPlayback";default:iF(!1,"not supported device")}}get id(){return this.device.deviceId}get name(){return this.device.name}};u();import{nextTick as MF,success as Y0}from"@4players/odin-common";import{decode as TF}from"@msgpack/msgpack";u();import{Backend as mB}from"@4players/odin-common";u();import{Backend as A,failure as x0,success as S0,CONNECTION_STATS_INITIAL as qF}from"@4players/odin-common";import{MainCommandsRpc as mF,MainNotificationsRpc as GF,RoomCommandsRpc as IF,RoomNotificationsRpc as $F}from"@4players/odin-common/api";u();import{failure as Qx,success as Yx}from"@4players/odin-common";import{MessagePackRpcSchema as bF,parseRequest as w0,parseResponse as oF}from"@4players/odin-common/api";import{encode as aF,decode as lF}from"@msgpack/msgpack";var M=class{constructor(t){this.stream=t;this._SendQueue=[];this._RecvQueue=[];this._EventQueue=[];this._Requests=new Map;this._Close=new AbortController;this._NextId=1;t instanceof WebSocket?(t.addEventListener("open",this._OnWebSocketOpen.bind(this)),t.addEventListener("close",this.close.bind(this)),t.addEventListener("message",j=>this._OnRpcMessage(j.data)),t.binaryType="arraybuffer"):(kF(t.readable.getReader(),this._OnRpcMessage.bind(this)).finally(this.close.bind(this)),this._Writer=t.writable.getWriter()),this._Close.signal.addEventListener("abort",this._Cleanup.bind(this),{once:!0})}get closed(){return this._Close.signal.aborted}get closeSignal(){return this._Close.signal}async request(t,j,e){if(this.closed)return Promise.resolve("closed");let B=this._NextId,C=e===void 0?void 0:setTimeout(()=>this._TimeoutRequest(B),e);return this._Send([0,B,t,j]),new Promise(E=>{this._Requests.set(B,{accept:E,timeoutId:C}),this._NextId+=1})}notify(t,j){this.closed||this._Send([2,t,j])}recv(){if(this.closed)return Promise.resolve("closed");let t=this._EventQueue.shift();return t!==void 0?Promise.resolve(t):new Promise(j=>this._RecvQueue.push(j))}close(){this._Close.abort()}_TimeoutRequest(t){let j=this._Requests.get(t);j!==void 0&&(this._Requests.delete(t),clearTimeout(j.timeoutId),j.accept("timeout"))}_Send(t){let j;t instanceof Uint8Array?j=t:j=new Uint8Array(aF(t,{ignoreUndefined:!0,forceFloat32:!0})),this.stream instanceof WebSocket?this.stream.send(j):this._Writer.write(j)}_OnWebSocketOpen(t){for(let j of this._SendQueue)this._Send(j);this._SendQueue.length=0}_OnRpcMessage(t){let j=uF(t);if(j.type!=="Success"){this.close();return}switch(j.value[0]){case 0:this._Send([1,j.value[1],"not supported",null]);break;case 1:this._OnResponse(j.value[1],j.value[2],j.value[3]);break;case 2:this._OnEvent(j.value[1],j.value[2]);break}}_OnResponse(t,j,e){let B=this._Requests.get(t);B!==void 0&&(clearTimeout(B.timeoutId),B.accept(j===null?Yx(e):Qx(j)))}_OnEvent(t,j){let e=this._RecvQueue.shift();e!==void 0?e({name:t,properties:j}):this._EventQueue.push({name:t,properties:j})}_Cleanup(){for(let t of this._Requests.values())clearTimeout(t.timeoutId),t.accept("closed");this._Requests.clear();for(let t of this._RecvQueue)t("closed");this._RecvQueue.length=0,this._SendQueue.length=0,this.stream instanceof WebSocket?this.stream.close():this._Writer?.close().catch(()=>{})}},U=class{constructor(t,j,e){this.rpc=t;this._Commands=j;this._Events=e}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(t,j,e){j=w0(t,j,this._Commands);let B=await this.rpc.request(t,j,e);if(B==="closed"||B==="timeout"||B.type==="Failure")return B;let C=oF(t,B.value,this._Commands);return C!==void 0?Yx(C):Qx("response schema failed validation")}notify(t,j){j=w0(t,j,this._Commands),this.rpc.notify(t,j)}async recv(){let t=await this.rpc.recv();if(t==="closed")return t;let j=Zx(this._Events,t);return j!==void 0?j:(J0(this._Events,t.name)?(c(`schema validation for ${t.name} failed; closing connection`),this.rpc.close()):h(`dropping unknown event ${t.name}`),"closed")}close(){this.rpc.close()}};function uF(v){try{return Yx(bF.parse(lF(new Uint8Array(v))))}catch(t){return Qx(String(t))}}function Zx(v,t){if(!J0(v,t.name))return;let j=v[t.name].safeParse(t.properties);if(j.success)return{name:t.name,properties:j.data}}function J0(v,t){return t in v}async function kF(v,t){let j=new Uint8Array;for(;;){let e=b0(j,0);if(e===n){v.cancel("protocol violation");break}if(e!==G&&e<=j.length){t(j.subarray(0,e)),j=j.subarray(e);continue}let B;try{B=await v.read()}catch{break}if(B.done)break;j=cF(j,B.value)}j.length>0&&h("unprocessed bytes left in rpc stream",j)}function cF(v,t){if(v.length===0)return t;if(t.length===0)return v;let j=new Uint8Array(v.length+t.length);return j.set(v,0),j.set(t,v.length),j}u();import{failure as ox,fromBase64Url as dF,success as pF}from"@4players/odin-common";import{TokenClaimsSchema as hF}from"@4players/odin-common/api";var g=class v{constructor(t,j){this.text=t;this.claims=j;if(j.ups!==void 0){let e=v.parse(j.ups);e.type==="Success"?this._Upstream=e.value:c(`upstream in token can not be parsed; ${e.reason}`)}}static parse(t){let j=t.split(".");if(j.length!==3)return ox("expected three segments");let e=dF(j[1]);if(e.type==="Failure")return ox(`invalid token; ${e.reason}`);let B;try{B=JSON.parse(e.value)}catch(E){return ox(`invalid token; ${E}`)}let C=hF.safeParse(B);return C.success===!1?ox(`invalid token; ${C.error}`):pF(new v(t,C.data))}get timeLeft(){return this.claims.exp===void 0?1/0:this.claims.exp*1e3-Date.now()}get upstream(){return this._Upstream}get defaultRoomId(){return Array.isArray(this.claims.rid)?this.claims.rid.length===1?this.claims.rid[0]:void 0:this.claims.rid}hasAudience(t){return this.claims.aud===void 0&&t==="gateway"?!0:Array.isArray(this.claims.aud)?this.claims.aud.includes(t):this.claims.aud===t}toString(){return this.text}};u();import{VideoCodec as P0,assert as ax}from"@4players/odin-common";function O0(v){typeof globalThis.rtcDataChannels>"u"&&(globalThis.rtcDataChannels=[]),Array.isArray(globalThis.rtcDataChannels)&&globalThis.rtcDataChannels.length<=100&&globalThis.rtcDataChannels.push(v)}function M0(v){let t=globalThis.rtcDataChannels?.indexOf(v);t!==void 0&&t>=0&&globalThis.rtcDataChannels.splice(t,1),v.readyState!=="closed"&&v.close()}function lx(v){typeof globalThis.rtcPeerConnections>"u"&&(globalThis.rtcPeerConnections=[]),Array.isArray(globalThis.rtcPeerConnections)&&globalThis.rtcPeerConnections.length<=100&&globalThis.rtcPeerConnections.push(v)}function T0(v){let t=globalThis.rtcPeerConnections?.indexOf(v);t!==void 0&&t>=0&&globalThis.rtcPeerConnections.splice(t,1),v.connectionState!=="closed"&&v.close()}var xx=class{constructor(t,j){this._localVideos=new Map;this._remoteVideos=new Map;this._negotiation={requested:!1,running:!1,waitForAnswer:!1};this._WebRtcStatsSnapshot=null;this._peerConnection=t,this._signaling=j,this._peerConnection.ontrack=this._onTrack.bind(this),this._peerConnection.onconnectionstatechange=()=>this._onStatusChanged(),this._peerConnection.onicecandidate=async e=>{e.candidate?await this._signaling.sendIceCandidate(e.candidate):await this._signaling.sendIceComplete()},this._WebRtcStatsInterval=setInterval(()=>{this._snapshotStats()},i.WebRtcStatsSnapshotInterval)}requestNegotiation(t){this._negotiation.requested=!0,t&&(this._negotiation.waitForAnswer=!0),!this._negotiation.running&&(this._negotiation.running=!0,setTimeout(async()=>{let j=this._negotiation.waitForAnswer;this._negotiation.requested=!1,this._negotiation.waitForAnswer=!1;try{let e;j&&(e=new Promise(B=>{this._resolveOffer=B})),await this._sendOffer(),e&&await e}catch(e){c("negotiation failed during sdp offer/answer exchange",e)}finally{this._resolveOffer=void 0,this._negotiation.running=!1,this._negotiation.requested&&this.requestNegotiation(this._negotiation.waitForAnswer)}}))}async startLocalVideo(t,j,e){if(this._localVideos.has(t))return;b(`starting local video for media ${t}`);let B=this._peerConnection.getTransceivers().find(f=>f.sender.track===j);if(B)await B.sender.replaceTrack(j);else{let f=this._peerConnection.addTrack(j);B=this._peerConnection.getTransceivers().find(s=>s.sender===f),ax(B,"failed to create transceiver for local video")}if(e){let f=B.sender.getParameters(),{maxBitrate:s,maxFramerate:a,scaleResolutionDownBy:q}=e,N={...s!==void 0&&{maxBitrate:s},...a!==void 0&&{maxFramerate:a},...q!==void 0&&{scaleResolutionDownBy:q}};if(f.encodings.length===0)f.encodings.push(N);else for(let sA of f.encodings)Object.assign(sA,N);e.degradationPreference&&(f.degradationPreference=e.degradationPreference),await B.sender.setParameters(f)}let E=new P0(e?.codec??i.DefaultVideoCodec).isSupported();E&&B.setCodecPreferences([E]),this._localVideos.set(t,{transceiver:B}),this.requestNegotiation(!0)}stopLocalVideo(t){let j=this._localVideos.get(t);j&&(b(`stopping local video for media ${t}`),this._localVideos.delete(t),j.transceiver.sender.track&&(j.transceiver.sender.track.enabled=!1),j.transceiver.direction="inactive",this.requestNegotiation(!1))}startRemoteVideo(t,j){b(`starting remote video for media ${t}`);let e=this._peerConnection.addTransceiver("video"),C=new P0(j??i.DefaultVideoCodec).isSupported();C&&e.setCodecPreferences([C]);let E=new Promise((f,s)=>{this._remoteVideos.set(t,{state:"Requested",transceiver:e,promise:{resolve:f,reject:s}})});return this.requestNegotiation(!0),E}stopRemoteVideo(t){let j=this._remoteVideos.get(t);j&&(b(`stopping remote video for media ${t}`),this._remoteVideos.delete(t),j.state!=="Active"&&j.promise.reject(new Error("video stopped")),this.requestNegotiation(!1))}async handleWebRtcUpdate(t){switch(t.kind){case"Sdp":await this._updateRemoteSdp(t.type==="Answer"?"answer":"offer",t.sdp,t.media_map);break;case"Trickle":this._addIceCandidate({candidate:t.candidate,sdpMid:t.spd_mid??void 0,sdpMLineIndex:t.spd_mline_index??void 0,usernameFragment:t.username_fragment??void 0});break;case"TrickleFinished":this._addIceCandidate(void 0);break}}async startup(){if(this._peerConnection.connectionState==="new")try{let t=await this._peerConnection.createOffer();ax(t.type==="offer"&&t.sdp,"generated broken webrtc offer"),await this._peerConnection.setLocalDescription(t),await this._signaling.sendOffer(t.sdp,[])}catch{c("failed to create initial sdp offer")}}cleanup(){for(let[,t]of this._remoteVideos)t.state!=="Active"&&t.promise.reject(new Error("connection closed"));clearTimeout(this._WebRtcIceTimeout),clearTimeout(this._WebRtcTimeout),clearInterval(this._WebRtcStatsInterval),this._localVideos.clear(),this._remoteVideos.clear()}get stats(){return this._WebRtcStatsSnapshot}get peerConnection(){return this._peerConnection}get localVideos(){return this._localVideos}get remoteVideos(){return this._remoteVideos}get isConnected(){return this._peerConnection.connectionState==="connected"}get isNegotiating(){return this._negotiation.running}async _snapshotStats(){try{let t=await this._peerConnection.getStats(),j={},e={bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,rtt:0};t.forEach(B=>{let{type:C,...E}=B;C!=="certificate"&&(C==="candidate-pair"&&B.nominated&&(e.bytesSent+=B.bytesSent??0,e.bytesReceived+=B.bytesReceived??0,e.packetsSent+=B.packetsSent??0,e.packetsReceived+=B.packetsReceived??0,e.rtt=B.currentRoundTripTime??0),j[C]||(j[C]=[]),j[C].push(E))}),this._WebRtcStatsSnapshot={timestamp:Date.now(),status:this._peerConnection.connectionState,stats:e,report:j}}catch{}}_addIceCandidate(t){t&&(t.sdpMid===void 0&&t.sdpMLineIndex===void 0&&(t={...t,sdpMid:"0"}),o(`adding new ice ${t.candidate}`,t)),this._peerConnection.addIceCandidate(t)}async _sendOffer(){try{let t=await this._peerConnection.createOffer();ax(t.type==="offer"&&t.sdp,"generated broken payload"),await this._peerConnection.setLocalDescription(t);let j=[];for(let[e,{transceiver:B}]of this._localVideos)B.mid&&j.push([e,B.mid]);for(let[e,B]of this._remoteVideos)B.state!=="Active"&&B.transceiver.mid&&j.push([e,B.transceiver.mid]);await this._signaling.sendOffer(t.sdp,j)}catch(t){throw c("failed to send sdp offer",t),t}}async _updateRemoteSdp(t,j,e){for(let[B,C]of e){let E=this._remoteVideos.get(B);E?.state==="Requested"&&(this._remoteVideos.set(B,{state:"Mapped",transceiver:E.transceiver,mid:C,promise:E.promise}),o(`updated remote video list with media ${B}`,E,this._remoteVideos))}await this._peerConnection.setRemoteDescription({type:t,sdp:j}),this._resolveOffer?.(!0)}async _onStatusChanged(){switch(o(`peer connection state changed to ${this._peerConnection.connectionState}`),this._peerConnection.connectionState){case"closed":break;case"connected":clearTimeout(this._WebRtcIceTimeout),this._WebRtcIceTimeout=void 0,clearTimeout(this._WebRtcTimeout),this._WebRtcTimeout=void 0;break;case"failed":this._peerConnection.restartIce(),this.requestNegotiation(!0);case"disconnected":i.MainConnectionPingInterval!==void 0&&await this._signaling.checkConnection();default:this._WebRtcIceTimeout===void 0&&(this._WebRtcIceTimeout=setTimeout(()=>{o("ice connection timeout was reached"),this._peerConnection.restartIce(),this._WebRtcIceTimeout=void 0},i.WebRtcIceTimeout)),this._WebRtcTimeout===void 0&&(this._WebRtcTimeout=setTimeout(async()=>{o("peer connection timeout was reached"),await this._signaling.closeConnection()},i.WebRtcTimeout));break}}_onTrack(t){let j=Array.from(this._remoteVideos).find(([,C])=>C.state==="Mapped"&&C.mid===t.transceiver.mid);if(!j){h(`unexpected track with mid: ${t.transceiver.mid}`);return}let[e,B]=j;ax(B.state==="Mapped","expected video state to be Mapped"),this._remoteVideos.set(e,{state:"Active",transceiver:t.transceiver}),o(`updated local video list with media ${e}`,j,t.transceiver,this._localVideos),t.track.onended=()=>{o(`video track with mid ${t.transceiver.mid} ended`,j)},B.promise.resolve(t.track)}};var ux=class v{constructor(t,j,e,B,C,E){this.id=t;this.address=j;this.connection=B;this.rpc=C;this.closeController=E;this._ConnectionStats={...qF};this._WebRtcSessionFlight=new S;this._PingFlight=new S;this.status=0;this._ClosePromise=(async()=>{try{await this.connection.closed}catch{}return"closed"})(),i.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(i.HealthCheckTimeout)},i.MainConnectionPingInterval)),E.signal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this.datagramWriter=B.datagrams.writable.getWriter(),this.connection.closed.then(()=>{this.status=2}).catch(()=>{}),this.connection.ready.then(()=>{this.status=1}).catch(()=>{}),this.readDatagrams(this.connection,this.id,(f,s)=>{this._ConnectionStats.packetsReceived+=1,e(f,s)})}static async create(t,j,e,B){try{let C=new URL(`https://${j}?version=${a0}&uid=${kx}`),E=new AbortController;B.addEventListener("abort",()=>E.abort(),{once:!0});let f=new WebTransport(C);E.signal.addEventListener("abort",()=>{try{f.close()}catch{}},{once:!0}),await f.ready;let s=await f.createBidirectionalStream(),a=new U(new M(s),mF,GF);return E.signal.addEventListener("abort",()=>a.close(),{once:!0}),a.notify("Hello",{stream:"main"}),S0(new v(t,j,e,f,a,E))}catch(C){return x0(`connecting to ${j} failed with ${C}`)}}get connectionStats(){return this._ConnectionStats}get transport(){return"H3"}get closePromise(){return this._ClosePromise}get closeSignal(){return this.closeController.signal}get closed(){return this.closeSignal.aborted}waitForConnected(){return Promise.race([this.connection.ready,this.connection.closed.then(()=>{throw new Error("connection closed")})])}close(){b(`closing connection to '${this.address}' with id ${this.id}`),this.closeController.abort("request")}async joinRoom(t,j,e,B){try{if(this.closed)return"closed";let C=await this.connection.createBidirectionalStream().catch(()=>"closed");if(C==="closed")return"closed";let E=new U(new M(C),IF,$F),f=await E.request("Hello",{stream:"room",token:String(t),room_id:j,user_data:e,position:B});return f==="closed"||f.type==="Failure"?f:S0(E.rpc)}catch(C){return x0(`JoinRoom failed; ${C}`)}}async getReconnectToken(t){let j=await this._Request("RequestReconnectToken",{peer_id:t});return j.type==="Failure"?j:g.parse(j.value)}async healthCheck(){let t=await this._RequestPing(i.HealthCheckTimeout);return t||this.close(),t}async ping(t=3e4){let j=Date.now();return await this._RequestPing(t)?Date.now()-j:0}sendDatagram(t){try{this.datagramWriter.write(t),this._ConnectionStats.packetsSent+=1;let j=t.byteLength;this.connectionStats.bytesSent+=j}catch{}}async readDatagrams(t,j,e){try{let B=t.datagrams.readable.getReader();for(;;){let C=await B.read();if(C.done)break;let E=C.value.byteLength;this.connectionStats.bytesReceived+=E,e(j,C.value)}}catch{}}_CleanUp(){o(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId)}async _EnsureWebRtcSession(){return this._WebRtcSession?this._WebRtcSession:this._WebRtcSessionFlight.run(async()=>(this._PeerConnection=new RTCPeerConnection,lx(this._PeerConnection),this._WebRtcSession=new xx(this._PeerConnection,{sendOffer:async(t,j)=>{await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:t,media_map:j})},sendIceCandidate:async t=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:t.candidate,spd_mid:t.sdpMid??void 0,spd_mline_index:t.sdpMLineIndex??void 0,username_fragment:t.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async()=>{this._PeerConnection?.restartIce(),this._WebRtcSession?.requestNegotiation(!0)},checkConnection:async()=>{}}),this._HandleWebRtcUpdates(),this._WebRtcSession))}async _HandleWebRtcUpdates(){for(;;){let t=await this.rpc.recv();if(t==="closed")break;t.name==="WebRtcUpdate"&&this._WebRtcSession?.handleWebRtcUpdate(t.properties)}this.close()}async _Request(t,j,e){let B=Date.now(),C=await(e===void 0?this.rpc.request(t,j):this.rpc.request(t,j,e)),E=(Date.now()-B)/1e3;return t!=="Ping"&&o(`sent main rpc '${t}'; took: ${E}s`,{properties:j,timeout:e,result:C}),C==="closed"?x0("connection lost"):C}_RequestPing(t=3e4){return this._PingFlight.run(async()=>{let j=await this._Request("Ping",{},t);return j!=="timeout"&&j.type==="Success"})}async startLocalVideo(t,j,e){await(await this._EnsureWebRtcSession()).startLocalVideo(t,j,e)}stopLocalVideo(t){this._WebRtcSession?.stopLocalVideo(t)}async startRemoteVideo(t,j){return(await this._EnsureWebRtcSession()).startRemoteVideo(t,j)}stopRemoteVideo(t){this._WebRtcSession?.stopRemoteVideo(t)}async dump(){return{type:"H3",id:this.id,address:this.address,closed:this.closed,status:this.status,datagrams:{sent:this._ConnectionStats.packetsSent,received:this._ConnectionStats.packetsReceived},webRtc:{signalingState:this._PeerConnection?.signalingState??null,connectionState:this._PeerConnection?.connectionState??null,iceGatheringState:this._PeerConnection?.iceGatheringState??null,iceConnectionState:this._PeerConnection?.iceConnectionState??null,connectionStats:this._WebRtcSession?.stats??null}}}};u();import{Backend as F,extendUrl as V0,failure as cx,success as U0,fail as HF,CONNECTION_STATS_INITIAL as NF}from"@4players/odin-common";import{MainCommandsRpc as KF,MainNotificationsRpc as wF}from"@4players/odin-common/api";u();import{abortableSleep as gF,failure as Dx,success as yF}from"@4players/odin-common";async function A0(v,t){let j=performance.now(),e=Dx("no connection was attempted");for(let B=0;B<i.ConnectInterval.length&&!t.aborted;B++){let C=j+LF(B);if(await gF(C-performance.now(),t)==="aborted")return Dx("aborted");if(e=await _F(v,t),e.type==="Success")return e}return e}async function _F(v,t){let j;try{j=new WebSocket(v)}catch(s){return Dx(`unable to create websocket; ${s}`)}let e=new AbortController,B=new Promise(s=>j.addEventListener("open",()=>s(yF(j)),{signal:e.signal})),C=new Promise(s=>j.addEventListener("close",a=>s(Dx(a.reason!==""?a.reason:"unable to establish websocket connection")),{signal:e.signal})),E=new Promise(s=>t.addEventListener("abort",()=>s(Dx("aborted")),{signal:e.signal})),f=await Promise.race([B,C,E]);return e.abort(),f}function LF(v){let t=i.ConnectInterval.slice(0,v).reduce((e,B)=>e+B,0),j=i.ConnectInterval[v]*Math.random();return t+j}var dx=class v{constructor(t,j,e,B,C,E){this.id=t;this.address=j;this.url=e;this.onDatagram=B;this.connection=C;this.webRtc=E;this._PeerIdMap=new WeakMap;this._ConnectionStats={...NF};this._PingFlight=new S;b(`creating new webrtc connection to '${this.address}' with id ${this.id}`),this.closeSignal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this._ClosePromise=new Promise(f=>{this.closeSignal.addEventListener("abort",()=>{f("closed")},{once:!0})}),lx(E),this._AudioChannel=this.webRtc.createDataChannel("audio",{id:2,negotiated:!0,ordered:!1,maxRetransmits:0}),this._AudioChannel.binaryType="arraybuffer",this._AudioChannel.onmessage=f=>{this._ConnectionStats.packetsReceived++;let s=new Uint8Array(f.data);this._ConnectionStats.bytesReceived+=s.byteLength,this.onDatagram(this.id,s)},this._AudioChannel.onerror=f=>h(`webrtc audio data channel for connection with id ${t} raised an error`,f),this._AudioChannel.onclosing=f=>b(`webrtc audio data channel for connection with id ${t} begins shutting down`,f),this._AudioChannel.onclose=f=>b(`webrtc audio data channel for connection with id ${t} has closed`,f),O0(this._AudioChannel),this._WebRtcSession=new xx(this.webRtc,{sendOffer:async(f,s)=>{await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:f,media_map:s})},sendIceCandidate:async f=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:f.candidate,spd_mid:f.sdpMid??void 0,spd_mline_index:f.sdpMLineIndex??void 0,username_fragment:f.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async()=>{this.close()},checkConnection:async()=>{this.healthCheck().then()}}),this._WebRtcSession.startup(),i.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(i.HealthCheckTimeout)},i.MainConnectionPingInterval)),this._HandleWebRtcUpdates()}static async create(t,j,e,B){if(B.aborted)return cx("aborted");let C;try{C=new URL(`wss://${j}`)}catch(a){return HF(`address in token(${j}) can not be parsed; ${a}`)}let E=V0(C,`main?uid=${kx}`);if(E.type!=="Success")return E;let f=await A0(E.value,B);if(f.type!=="Success")return f;let s=new U(new M(f.value),KF,wF);try{return U0(new v(t,j,C,e,s,new RTCPeerConnection))}catch(a){return s.close(),cx(`unable to create webrtc connection; ${a}`)}}get status(){switch(this.webRtc.connectionState){case"connected":return 1;case"failed":case"closed":return 2;default:return 0}}get connectionStats(){return this._ConnectionStats}get transport(){return"WebRTC"}get closePromise(){return this._ClosePromise}get closeSignal(){return this.connection.closeSignal}get closed(){return this.connection.closed}async waitForConnected(){return new Promise((t,j)=>{let e=()=>{let B=this.status;B!==0&&(this.webRtc.removeEventListener("connectionstatechange",e),B===1?t():j(new Error("connection closed")))};this.webRtc.addEventListener("connectionstatechange",e),e(),this.closePromise.then(()=>{j(new Error("connection closed"))})})}close(){b(`closing ${this.transport} connection to '${this.address}' with id ${this.id}`),this.connection.close()}async joinRoom(t,j,e,B){let C=await this.connection.request("JoinRoom",{token:String(t),room_id:j,user_data:e,position:B});if(C==="closed"||C.type==="Failure")return C;let E=C.value;if(!("token"in E))return cx("JoinRoom responded without token");let f=V0(this.url,`room?token=${E.token}`);if(f.type==="Failure")return f;let s=await A0(f.value,this.closeSignal);return s.type==="Success"?(this._PeerIdMap.set(s.value,E.peer_id),U0(new M(s.value))):s}async getReconnectToken(t){let j=await this._Request("RequestReconnectToken",{peer_id:t});return j.type==="Failure"?j:g.parse(j.value)}async healthCheck(){let t=await this._RequestPing(i.HealthCheckTimeout);return t||this.close(),t}async ping(t=3e4){let j=Date.now();return await this._RequestPing(t)?Date.now()-j:0}sendDatagram(t){if(this._AudioChannel.readyState==="open"){let j=t.byteLength;this._AudioChannel.send(t),this._ConnectionStats.packetsSent+=1,this._ConnectionStats.bytesSent+=j}}_CleanUp(){o(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId),M0(this._AudioChannel),T0(this.webRtc),this._WebRtcSession.cleanup(),this.connection.close()}async _HandleWebRtcUpdates(){for(;;){let t=await this.connection.recv();if(t==="closed")break;t.name==="WebRtcUpdate"&&this._WebRtcSession.handleWebRtcUpdate(t.properties)}this.close()}async _Request(t,j,e){let B=Date.now(),C=await(e===void 0?this.connection.request(t,j):this.connection.request(t,j,e)),E=(Date.now()-B)/1e3;return t!=="Ping"&&o(`sent main rpc '${t}'; took: ${E}s`,{properties:j,timeout:e,result:C}),C==="closed"?cx("connection lost"):C}_RequestPing(t=3e4){return this._PingFlight.run(async()=>{let j=await this._Request("Ping",{},t);return j!=="timeout"&&j.type==="Success"})}async startLocalVideo(t,j,e){await this._WebRtcSession.startLocalVideo(t,j,e)}stopLocalVideo(t){this._WebRtcSession.stopLocalVideo(t)}async startRemoteVideo(t,j){return this._WebRtcSession.startRemoteVideo(t,j)}stopRemoteVideo(t){this._WebRtcSession.stopRemoteVideo(t)}async dump(){return{type:"WebRtc",id:this.id,address:this.address,url:this.url.toString(),closed:this.closed,audioChannel:{readyState:this._AudioChannel.readyState,bufferedAmount:this._AudioChannel.bufferedAmount},datagrams:{sent:this.connectionStats.packetsSent,received:this.connectionStats.packetsReceived},webRtc:{signalingState:this.webRtc.signalingState,connectionState:this.webRtc.connectionState,iceGatheringState:this.webRtc.iceGatheringState,iceConnectionState:this.webRtc.iceConnectionState,connectionStats:this._WebRtcSession.stats}}}};function W0(v,t,j,e,B){switch(b(`creating ${t} main connection to '${j}'`),t){case"H3":return ux.create(v,j,e,B);case"WebRTC":return dx.create(v,j,e,B);default:throw new Error(`transport ${t} is not supported`)}}import{Backend as GB,failure as Q0,success as JF}from"@4players/odin-common";import{parseCommand as PF,parseNotification as OF,RoomCommandsRpc as z0,RoomNotificationsRpc as X0}from"@4players/odin-common/api";u();var px=class{constructor(t,j,e,B){this.id=t;this.connection=j;this.cipher=e;this.mediaMap=B;this._DatagramReceived=0;this._DatagramSent=0;this._DatagramReceivedInvalid=0;this._DatagramSentInvalid=0;j.closeSignal.addEventListener("abort",()=>this.close())}get connectionStats(){return this.connection.connectionStats}get transport(){return this.connection.transport}get address(){return this.connection.address}get status(){return this.closed?2:this.connection.status}get closePromise(){return this.connection.closePromise}get closeSignal(){return this.connection.closeSignal}get closed(){return this.connection.closed}waitForConnected(){return this.connection.waitForConnected()}close(){this.connection.close()}async joinRoom(t,j,e,B){this.cipher.reset();let C=await this.cipher.encryptUserData(e);if(C===n)return Q0("unable to encrypt initial user-data");let E=await this.connection.joinRoom(t,j,C,B);return E==="closed"||E.type==="Failure"?E:JF(new F0(E.value,this.cipher,this))}getReconnectToken(t){return this.connection.getReconnectToken(t)}healthCheck(){return this.connection.healthCheck()}async sendDatagram(t){let j=await this.cipher.encryptDatagram(t);j!==n?(this._DatagramSent+=1,this.connection.sendDatagram(j)):this._DatagramSentInvalid+=1}async decryptDatagram(t,j){let e=await this.cipher.decryptDatagram(t,j);return e!==n?this._DatagramReceived+=1:this._DatagramReceivedInvalid+=1,e}startLocalVideo(t,j,e){return this.connection.startLocalVideo(t,j,e)}stopLocalVideo(t){return this.connection.stopLocalVideo(t)}startRemoteVideo(t,j){return this.connection.startRemoteVideo(t,j)}stopRemoteVideo(t){return this.connection.stopRemoteVideo(t)}async dump(){return{type:"Encrypted",id:this.id,address:this.address,connectionId:this.connection.id,closed:this.closed,transport:this.transport,datagrams:{sent:this._DatagramSent,received:this._DatagramReceived,sentInvalid:this._DatagramSentInvalid,receivedInvalid:this._DatagramReceivedInvalid},cipher:await this.cipher.dump()}}},hx=class{constructor(t){this.room=t}resendUserData(){this.room.roomConnection?.notify("UpdatePeer",{user_data:this.room.roomConnection.userData})}setUserData(t,j){let e={kind:"UserDataChanged",peer_id:t,user_data:j};this.room.onEvent("PeerUpdated",e)}},F0=class{constructor(t,j,e){this.rpc=t;this.cipher=j;this.connection=e;this.peers=new Map;this.closeSignal.addEventListener("abort",this.cleanup.bind(this),{once:!0})}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(t,j,e){let B=await this.outgoing(t,j);return B===n?Q0("can not be encrypted"):await this.rpc.request(t,B,e)}async notify(t,j){let e=await this.outgoing(t,j);if(e!==n)return this.rpc.notify(t,e)}async recv(){for(;;){let t=await this.rpc.recv();if(t==="closed")return t;let j=await this.incoming(t.name,t.properties);if(j!==n)return{name:t.name,properties:j}}}close(){return this.rpc.close()}async outgoing(t,j){if(!(t in z0))return j;let e=PF(t,j,z0);if(e===void 0)return n;switch(e.name){case"UpdatePeer":{let B=await this.cipher.encryptUserData(e.request.user_data);if(B===n)return n;e.request.user_data=B}break;case"SendMessage":{let B=await this.cipher.encryptMessage(e.request.message);if(B===n)return n;e.request.message=B}break}return e.request}async incoming(t,j){if(!(t in X0))return j;let e=OF(t,j,X0);if(e===void 0)return n;switch(e.name){case"RoomUpdated":for(let B=0;B<e.properties.updates.length;B++){let C=await this.roomUpdate(e.properties.updates[B]);if(C===n)return n;e.properties.updates[B]=C}break;case"PeerUpdated":{let B=await this.peerUpdate(e.properties);if(B===n)return n;e.properties=B}break;case"MessageReceived":{let B=await this.cipher.decryptMessage(e.properties.sender_peer_id,e.properties.message);if(B===n)return n;e.properties.message=B}break}return e.properties}async peerUpdate(t){switch(t.kind){case"UserDataChanged":{let j=await this.cipher.decryptUserData(t.peer_id,t.user_data);if(j===n)return n;t.user_data=j}break;case"MediaStarted":this.mediaStarted(t.peer_id,t.media.id);break;case"MediaStopped":this.mediaStopped(t.peer_id,t.media_id);break}return t}async roomUpdate(t){switch(t.kind){case"Joined":for(let j of t.room.peers){for(let B of j.medias)this.mediaStarted(j.id,B.id);let e=await this.cipher.decryptUserData(j.id,j.user_data);e!==n?j.user_data=e:j.user_data=new Uint8Array}break;case"PeerJoined":{for(let e of t.peer.medias)this.mediaStarted(t.peer.id,e.id);let j=await this.cipher.decryptUserData(t.peer.id,t.peer.user_data);j!==n?t.peer.user_data=j:t.peer.user_data=new Uint8Array}break;case"PeerLeft":{let j=this.peers.get(t.peer_id);this.peers.delete(t.peer_id),this.cipher.deletePeerKey(t.peer_id);for(let e of j??[])this.mediaStopped(t.peer_id,e)}break}return t}mediaStarted(t,j){let e=this.peers.get(t);e===void 0&&(e=new Set,this.peers.set(t,e)),e.add(j);let B=p({connectionId:this.connection.connection.id,mediaId:j});this.connection.mediaMap.set(B,{peerId:t,connection:this.connection})}mediaStopped(t,j){this.peers.get(t)?.delete(j);let B=p({connectionId:this.connection.connection.id,mediaId:j});this.connection.mediaMap.delete(B)}cleanup(){for(let[t,j]of this.peers)for(let e of j)this.mediaStopped(t,e)}};var qx=class{constructor(t){this.onDatagram=t;this._LastConnectionId=0;this._Connections=new Map;this._Close=new AbortController;this._MediaMap=new Map;let j=Date.now(),e=setInterval(()=>{Math.abs(Date.now()-j)>i.ClockJumpThreshold&&this.checkHealth(),j=Date.now()},i.ClockJumpCheckInterval);addEventListener("offline",()=>this.checkHealth(),{signal:this._Close.signal}),this._Close.signal.addEventListener("abort",()=>{clearInterval(e);for(let B of this._Connections.values())B.type==="establishing"?B.abort.abort():B.connection.close();this._Connections.clear()},{once:!0})}get closed(){return this._Close.signal.aborted}sendDatagram(t,j){let e=this._Connections.get(t);(e?.type==="established"||e?.type==="virtual")&&e.connection.sendDatagram(j)}async recvDatagram(t,j){let e=SF(j);if(e===void 0||e.length===0)return;let B=this._MediaMap.get(p({connectionId:t,mediaId:e[0]}));if(B===void 0)this.onDatagram(t,j);else{let C=await B.connection.decryptDatagram(B.peerId,j);if(C===n)return;this.onDatagram(B.connection.id,C)}}async acquireConnection(t,j,e,B){if(await MF(),this.closed)return"closed";let C=this.findConnection(t,j),E;switch(C?.type){case"established":o(`reusing existing connection ${C.id}`),E=C;break;case"establishing":{o(`waiting for connecting to '${j}' finish`);let a=await C.finished;if(a.type!=="Success")return a;E=a.value}break;case void 0:{o(`connecting to '${j}'`);let a=await this.createConnection(t,j,B);if(a.type!=="Success")return a;E=a.value}break}let f=E.id,s=new r0(E.connection,()=>this.releaseConnection(f));return E.references+=1,e&&(s=new px(++this._LastConnectionId,s,e,this._MediaMap),this.addConnection({type:"virtual",id:s.id,connection:s,createdAt:Date.now()})),Y0(s)}async createConnection(t,j,e){let B=++this._LastConnectionId,C=Date.now(),E=new AbortController;e.addEventListener("abort",()=>E.abort(),{once:!0}),o(`creating new connection ${B}`);let f=W0(B,t,j,this.recvDatagram.bind(this),e),{promise:s,resolve:a}=Promise.withResolvers();this.addConnection({type:"establishing",id:B,address:j,transport:t,finished:s,createdAt:Date.now(),abort:E});let q=await f;if(this._Connections.delete(B),q.type!=="Success")return a(q),q;let N={type:"established",id:B,address:j,transport:t,createdAt:C,references:0,connection:q.value};return this.addConnection(N),Y0(N)}addConnection(t){(t.type==="established"||t.type==="virtual")&&t.connection.closeSignal.addEventListener("abort",()=>{b(`connection ${t.id} has been closed`),this._Connections.delete(t.id)},{once:!0}),this._Connections.set(t.id,t)}releaseConnection(t){let j=this._Connections.get(t);j?.type==="established"&&(j.references-=1,j.references<=0&&j.connection.close())}checkHealth(){for(let t of this._Connections.values())t.type==="established"&&t.connection.healthCheck()}close(){this._Close.abort()}async dump(){let t=[];for(let e of this._Connections.values()){let B;switch(e.type){case"established":B={transport:e.transport,address:e.address,connection:await e.connection.dump(),references:e.references};break;case"establishing":B={transport:e.transport,address:e.address,aborted:e.abort.signal.aborted};break;case"virtual":B={connection:await e.connection.dump()};break}t.push({type:e.type,id:e.id,createdAt:e.createdAt,...B})}let j=[];for(let[e,B]of this._MediaMap)j.push(`${e} -> ${B.peerId} @${B.connection.id} `);return{lastConnectionId:this._LastConnectionId,connections:t,mediaMap:j,closed:this.closed}}findConnection(t,j){for(let e of this._Connections.values())if(e.type!=="virtual"&&e.transport===t&&e.address===j)return e}},r0=class{constructor(t,j){this.connection=t;this.release=j;this.closeController=new AbortController;this.closePromise=new Promise(t=>this.closeController.signal.addEventListener("abort",()=>t("closed"),{once:!0}));t.closeSignal.addEventListener("abort",()=>this.close(),{once:!0})}get closeSignal(){return this.closeController.signal}get closed(){return this.closeSignal.aborted}close(){this.release(),this.closeController.abort("closed")}get connectionStats(){return this.connection.connectionStats}get id(){return this.connection.id}get transport(){return this.connection.transport}get address(){return this.connection.address}get status(){return this.connection.status}waitForConnected(){return this.connection.waitForConnected()}joinRoom(t,j,e,B){return this.connection.joinRoom(t,j,e,B)}getReconnectToken(t){return this.connection.getReconnectToken(t)}healthCheck(){return this.connection.healthCheck()}sendDatagram(t){return this.connection.sendDatagram(t)}startLocalVideo(t,j,e){return this.connection.startLocalVideo(t,j,e)}stopLocalVideo(t){return this.connection.stopLocalVideo(t)}startRemoteVideo(t,j){return this.connection.startRemoteVideo(t,j)}stopRemoteVideo(t){return this.connection.stopRemoteVideo(t)}async dump(){let t=await this.connection.dump();return typeof t=="object"&&(t={...t,isShared:!0,referenceClosed:this.closed}),t}};function SF(v){let t;try{t=TF(v)}catch{return}if(!Array.isArray(t)||t.length<2)return;let j=t[1];if(Array.isArray(j))return j.map(Number)}import{assert as D0,Backend as IB}from"@4players/odin-common";var w=class{constructor(t,j){this.uid=t;this.customType=j}#x;#A;get mediaStream(){return this.#x}get audioPlayback(){return D0(this.#A,"getting the audioPlayback failed, this video has no Audio"),this.#A}get volume(){return D0(this.audioPlayback,"getting the volume failed, this video has no Audio"),this.audioPlayback.volume}setVolume(t){D0(this.#A,"Can not set the volume, this video has no Audio"),this.#A.setVolume(t)}setMediaStream(t){this.mediaStream||(this.#x=t)}close(){this.#x?.getVideoTracks().forEach(t=>{t.stop(),this.#x?.removeTrack(t)}),this.#x=void 0}};import{Backend as gB,assert as EA,generateUUID as fr,unwrap as nr,CONNECTION_STATS_INITIAL as sr}from"@4players/odin-common";import{RoomNotificationsRpc as ir,RoomV1 as yB}from"@4players/odin-common/api";import{Selector as RF,failure as H,sleep as mx,success as T,assert as VF}from"@4players/odin-common";import{parseResponse as UF,RoomCommandsRpc as Gx,RoomNotificationsRpc as WF,RoomV1 as $B}from"@4players/odin-common/api";u();var Ix=class{constructor(t,j,e,B,C,E,f,s,a,q){this.connectionPool=t;this.transport=j;this.onEvent=e;this.gateway=B;this.roomId=E;this.cipher=a;this.disableAutoReconnect=q;this._Close=new AbortController;this._TokenUsed=!1;this._WasConnected=!1;this._FailedConnections=0;this._LastTokenRenew=performance.now();this._LastReconnectStartedAt=0;this._Closed=new Promise(t=>this._Close.signal.addEventListener("abort",()=>t(this._Close.signal.reason?"disconnected":"closed"),{once:!0}));this._Token=C,this._UserData=f,this._Position=s,this._Main().then(({reason:N})=>o(`_Main() resolved; ${N}`))}get token(){return this._Token}get userData(){return this._UserData}get position(){return this._Position}get closed(){return this._Close.signal.aborted}get mainConnection(){return this._MainConnection}async requestUnsafe(t,j){if(this._RoomConnection===void 0)return H("currently not connected");let e=await this._RoomConnection.request(t,j,void 0);return VF(e!=="timeout","request should not timeout"),e!=="closed"&&e.type==="Success"&&this._HandleRequests(t,j,e.value),e}async request(t,j){let e=Date.now(),B=Gx[t],C=await this.requestUnsafe(t,j),E=(Date.now()-e)/1e3;if(o(`sent room rpc '${t}'; took: ${E}s`,{properties:j,result:C}),C==="closed"||C.type==="Failure")return C;let f=UF(t,C.value,Gx);return f!==void 0?T(f):H(`received invalid response from ${t}`)}notify(t,j){this._RoomConnection!==void 0&&this._RoomConnection.notify(t,j)}close(){this._Close.abort(!0)}get renewTokenIn(){let t=this._LastTokenRenew-performance.now()+i.MinTokenRefreshInterval,j=this._Token.timeLeft-i.MinTokenLifetime;return Math.max(t,j)}async _Main(){let t="unable to establish connection";for(let j=0;;this._FailedConnections++){if(await mx(Math.max(j-performance.now(),0)),this._Close.signal.aborted||this.connectionPool.closed){t="user requested";break}if(j=performance.now()+1e3,this._TokenUsed=!0,this._Token.hasAudience("sfu")){let e=await this._ConnectToServer();if(e.type==="Success"&&e.value==="shutdown"){o("connection closed by user request; shutting down"),t="user requested";break}if(this.disableAutoReconnect&&this._WasConnected){t=e.type==="Failure"?e.reason:"connection lost";break}if(this._LastReconnectStartedAt===0&&(this._LastReconnectStartedAt=performance.now()),e.type==="Failure"&&!this._WasConnected&&this._FailedConnections>=3){t=e.reason;break}if(e.type==="Failure"&&!XF(this._LastReconnectStartedAt))continue}if(this.reset(),this._Close.signal.aborted||this.connectionPool.closed){t="user requested";break}if(this.gateway!==void 0&&this._Token.hasAudience("gateway")){this._ChangeStatus("Joining",`requesting new token from ${this.gateway}`);let e=await zF(this.gateway,this._Token,this._Close.signal);if(e.type==="Success")if(e.value instanceof g)j=0,this._Token=e.value,this._TokenUsed=!1;else{t=`gateway error; ${e.value}`;break}else if(!this._WasConnected&&this._FailedConnections>=3){t="unable to contact the gateway";break}}if(this._TokenUsed&&this._Token.timeLeft<=0){t="token has expired";break}if(this._Close.signal.aborted||this.connectionPool.closed){t="user requested";break}}return this._ChangeStatus("Closed",t),this.close(),H(t)}async _ConnectToServer(){let t=this._Token;for(;t.upstream!==void 0;)t=t.upstream;let j=t.claims.adr??this.gateway?.toString();if(!j)return T("continue");if(this._ChangeStatus("Joining",`connecting to ${t.claims.adr}`),this._MainConnection===void 0||this._MainConnection.closed||this._MainConnection.address!==t.claims.adr){this._MainConnection?.close();let C=await this.connectionPool.acquireConnection(this.transport,j,this.cipher,this._Close.signal);if(C==="closed")return H("connection pool closed");if(C.type==="Failure")return this._ChangeStatus("Joining",`connection failed; ${C.reason}`),H(`connection failed; ${C.reason}`);this._MainConnection=C.value,this._OwnPeerId=void 0}let e=await Promise.race([Promise.all([this._MainConnection.joinRoom(t,this.roomId,this.userData,this.position)]),mx(i.ConnectTimeout,"timeout"),this._Closed]);if(e==="closed"||e==="disconnected")return T("continue");if(e==="timeout")return this._ChangeStatus("Joining","timed out"),T("continue");let[B]=e;if(B==="closed")return T("continue");if(B.type==="Failure")return H(`unable to join room; ${B.reason}`);this._RoomConnection=B.value,this._WasConnected=!0,this._FailedConnections=0,this._ChangeStatus("Joined",`joined ${this.roomId}`);try{await this._MainConnection.waitForConnected();let C=await this._HandleConnection(this._MainConnection);return T(C?"shutdown":"continue")}catch(C){return H(`unable to handle connection; ${C}`)}}_ChangeStatus(t,j){let e={status:t,message:j};this.onEvent("RoomStatusChanged",e)}async _HandleConnection(t){if(this._RoomConnection===void 0)return!1;let j=new RF([()=>mx(this.renewTokenIn,"renewToken"),()=>mx(500,"tick"),async()=>await this._RoomConnection?.recv(),()=>this._Closed,()=>t.closePromise]);for(;;){let e=await j.next();switch(e){case void 0:case"closed":return this._RoomConnection?.close(),this._MainConnection?.close(),!1;case"disconnected":return this._RoomConnection?.close(),this._MainConnection?.close(),!0;case"renewToken":this._RenewToken();break;case"tick":break;default:this._HandleEvent(e);break}}}_HandleEvent(t){if(t.name==="RoomUpdated"){let j=WF.RoomUpdated.safeParse(t.properties);if(!j.success)return;for(let e of j.data.updates)e.kind==="Joined"&&(this._OwnPeerId=e.own_peer_id)}this.onEvent(t.name,t.properties)}_HandleRequests(t,j,e){switch(t){case"SetPeerPosition":{let B=Gx.SetPeerPosition.request.safeParse(j);if(B.success){let C=B.data.position;this._Position=C.length===2?[C[0],C[1],0]:C}else h("unable to process SetPeerPosition command");break}case"UpdatePeer":{let B=Gx.UpdatePeer.request.safeParse(j);B.success?this._UserData=B.data.user_data:h("unable to process UpdatePeer command");break}}}async _RenewToken(t){if(this._LastTokenRenew=performance.now(),!t&&this.token.timeLeft>i.MinTokenLifetime)return;if(this._MainConnection===void 0||this._OwnPeerId===void 0)return H("connection is not established");let j=await this._MainConnection.getReconnectToken(this._OwnPeerId);return j.type==="Success"?(this._Token=j.value,T()):H(`${this._MainConnection.address} rejected reconnect token request; ${j.reason}`)}reset(){this._LastReconnectStartedAt=0,this._RoomConnection?.close(),this._RoomConnection=void 0,this._MainConnection?.close(),this._MainConnection=void 0,this._OwnPeerId=void 0}};async function zF(v,t,j){try{let e={jsonrpc:"2.0",id:1,method:"Connect",params:{}};b(`sending authentication request to '${v}'`,e);let C=await(await fetch(v,{body:JSON.stringify(e),method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},signal:j})).json();if(b(`received authentication response fom '${v}'`,C),"result"in C)return g.parse(C.result.token);{let E=C.error?.message??"malformed response";return c(`gateway rejected token; ${E}`),T(E)}}catch(e){return H(String(e))}}function XF(v,t=8e3){return performance.now()-v>t}u();import{assert as Er}from"@4players/odin-common";u();import{Backend as jx,Strand as Cr}from"@4players/odin-common";u();import{assert as Ar}from"@4players/odin-common";u();import{decode as QF}from"@msgpack/msgpack";var Z0={name:"PBKDF2",hash:"SHA-256",iterations:6e5,salt:new Uint8Array([111,100,105,110,95,99,114,121,112,116,111,95,109,97,115,116,101,114,95,107,101,121])},xA=v=>({name:"PBKDF2",hash:"SHA-256",iterations:600,salt:v}),AA=32,FA=1e6,rA=2147483648,DA=32,J=[79,68,73,78,1,75,105,109],Ax=16,Fx=64,tA=16;function jA(v,t){if(v.length!==t.length)return!1;for(let j=0;j<v.length;j++)if(v[j]!==t[j])return!1;return!0}function YF(v){return isFinite(v)}function ZF(v){return Array.isArray(v)}function $x(v){return YF(v)?v:n}function tx(v){return v instanceof Uint8Array?v:n}function xr(v,...t){let j;try{j=QF(v)}catch{return n}if(!ZF(j))return n;let e=new Array(j.length);for(let B in t)if(e[B]=t[B](j[B]),e[B]===n)return n;return e}function gx(v,...t){if(v.length<J.length)return m;for(let j=0;j<J.length;j++)if(v[j]!==J[j])return m;return xr(v.subarray(J.length),...t)}var rx=class{constructor(t){this.first=1;this.offset=0;this.window=Array(t)}isReplay(t){let j=t-this.first;if(j<0)return!0;if(j>=this.window.length)if(j<this.window.length*2){let C=j-this.window.length+1;j-=C;for(let E=0;E<C;E++)this.advance()}else return this.first=t+1-self.window.length,this.offset=0,this.window.fill(!1),!1;let e=(this.offset+j)%this.window.length,B=this.window[e]===!0;for(this.window[e]=!0;this.window[this.offset]===!0;)this.advance();return B}advance(){this.window[this.offset]=!1,this.first+=1,this.offset=(this.offset+1)%this.window.length}};var yx=class v{constructor(t){this.key=t}static async create(t){typeof t=="string"&&(t=new TextEncoder().encode(t));let j=await globalThis.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits"]),e=await globalThis.crypto.subtle.deriveBits(Z0,j,256),B=await globalThis.crypto.subtle.importKey("raw",e,"PBKDF2",!1,["deriveKey"]);return new v(B)}async generatePeerKey(t,j){return await globalThis.crypto.subtle.deriveKey(xA(t),this.key,{name:"AES-GCM",length:256},!1,[j])}},_x=class v{constructor(t,j){this.seed=t;this.key=j;this.sequenceNumbers={datagram:1,message:1,userData:1};this.number_of_packets=0;this.number_of_bytes=0}static async create(t){let j=globalThis.crypto.getRandomValues(new Uint8Array(AA)),e=await t.generatePeerKey(j,"encrypt");return new v(j,e)}get limitReached(){return this.key===void 0?!1:this.number_of_bytes>=rA||this.number_of_packets>=FA}nextSequenceNumber(t){return this.sequenceNumbers[t]++}};function t0(v,t){return{kind:"encrypted",key:v,material:t,antiReplays:{datagram:new rx(DA),userData:new rx(0),message:new rx(0)}}}var Lx=class v{constructor(t,j,e,B){this.additionalData=t;this.sequenceNumber=j;this.seed=e;this.encrypted=B}static parse(t){let j=gx(t,tx,$x,tx);if(j===n||j===m)return j;let[e,B,C]=j,E=t.subarray(0,t.length-C.length);return new v(E,B,e,C)}isSameSeed(t){return jA(this.seed,t.seed)}async generateKey(t){return await t.generatePeerKey(this.seed,"decrypt")}};function Hx(v,t){let j=new Uint8Array(12);switch(j[0]=t&255,j[1]=t>>8&255,j[2]=t>>16&255,j[3]=t>>24&255,v){case"datagram":j[5]=1;break;case"userData":j[5]=2;break;case"message":j[5]=3;break;default:Ar(!1,"missing content implementation")}return j}u();import{encode as BA}from"@msgpack/msgpack";import{assert as rr}from"@4players/odin-common";var Nx=class{constructor(t){this.actions=t}changeKey(t){this.masterKey!==t&&(this.masterKey=t,this.ownKey=n,this.actions.resendUserData())}async encryptDatagram(t){let j=await this.getKey("datagram");return j===void 0?t:j===P?n:await tr(j,t)}async encryptMessage(t){let j=await this.getKey("message");return j===void 0?t:j===P?P:await eA(j,t,"message")}async encryptUserData(t){let j=await this.getKey("userData");return j===void 0?t:(rr(j!==P,"key unavailable for user data encryption"),await eA(j,t,"userData",j.seed))}async getKey(t){if(this.ownKey===n||this.ownKey?.limitReached)if(t==="userData")this.ownKey=this.masterKey?await _x.create(this.masterKey):void 0;else return this.ownKey!==n&&(this.ownKey=n,this.actions.resendUserData()),P;return this.ownKey}reset(){this.ownKey=this.masterKey?n:void 0}};async function eA(v,t,j,...e){let B=v.nextSequenceNumber(j),C=t.length+Ax,E=Dr(B,e,C),f=E.length-C,s=await vA(v,j,B,E.subarray(0,f),t);return E.set(new Uint8Array(s),f),E}function Dr(v,t,j){let e=[];t.forEach(E=>e.push(E)),e.push(v),e.push(new Uint8Array(j));let B=BA(e),C=new Uint8Array(J.length+B.length);return C.set(J,0),C.set(B,J.length),C}async function tr(v,t){let j=jr(t);if(j===n)return n;if((j.kind&Fx)!==0)return n;let e=j.body.length+Ax,B=v.nextSequenceNumber("datagram"),C=BA([j.kind|Fx,j.mediaIds,B,new Uint8Array(e)]),E=C.length-e,f=await vA(v,"datagram",B,C.subarray(0,E),j.body);return C.set(f,E),C}async function vA(v,t,j,e,B){return new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:Hx(t,j),additionalData:e,tagLength:Ax*8},v.key,B))}function jr(v){let t=new O(v),j=t.readArrayLength();if(l(j)||j<2)return n;let e=t.readNumber(),B=t.readArrayLength();if(l(e)||l(B))return n;if(B>tA)return n;let C=Array(B);for(let f=0;f<C.length;f++){let s=t.readNumber();if(l(s))return n;C[f]=s}let E=v.subarray(t.position);return{kind:e,mediaIds:C,body:E}}u();import{encode as er}from"@msgpack/msgpack";var wx=class{constructor(t){this.actions=t;this.peerKeys=new Map}async changeKey(t){this.masterKey=t;for(let[j,{kind:e,material:B}]of this.peerKeys)if(t!==void 0){let C=await B.generateKey(t),E=t0(C,B),f=await Kx(E,"userData",B.additionalData,B.sequenceNumber,B.encrypted);f!==n?(this.peerKeys.set(j,E),this.actions.setUserData(j,f)):(this.peerKeys.set(j,{kind:"broken",material:B}),this.actions.setUserData(j,new Uint8Array))}else e==="encrypted"&&this.peerKeys.set(j,{kind:"broken",material:B})}async decryptDatagram(t,j){let e=Br(j);if(this.masterKey===void 0)return e===m?j:n;if(e===n||e===m)return n;let B=this.peerKeys.get(t);if(B?.kind!=="encrypted")return n;let C=await Kx(B,"datagram",e.additionalData,e.sequenceNumber,e.encrypted);return C===n?n:vr(e.kind&~Fx,e.mediaIds,C)}async decryptMessage(t,j){let e=gx(j,$x,tx);if(this.masterKey===void 0)return e===m?j:n;if(e===n||e===m)return n;let B=this.peerKeys.get(t);if(B?.kind!=="encrypted")return n;let[C,E]=e,f=j.subarray(0,j.length-E.length);return Kx(B,"message",f,C,E)}async decryptUserData(t,j){let e=Lx.parse(j);if(e===n)return n;if(e===m)return this.peerKeys.delete(t),this.masterKey===void 0?j:n;if(this.masterKey===void 0)return this.peerKeys.set(t,{kind:"broken",material:e}),n;let B=this.peerKeys.get(t);if(B?.kind==="encrypted"&&B.material.isSameSeed(e))B.material=e;else{let E=await e.generateKey(this.masterKey);B=t0(E,e)}let C=await Kx(B,"userData",e.additionalData,e.sequenceNumber,e.encrypted);return C===n?this.peerKeys.set(t,{kind:"broken",material:e}):B!==void 0&&this.peerKeys.set(t,B),C}reset(){this.peerKeys.clear()}};function Br(v){let t=new O(v),j=t.readArrayLength();if(l(j)||j<1)return n;let e=t.readNumber();if(l(e))return n;if((e&Fx)===0)return m;if(j!==4)return n;let B=t.position;t.readObjects(1);let C=v.subarray(B,t.position),E=t.readNumber(),f=t.readBytes();if(l(E)||l(f))return n;let s=v.subarray(0,v.length-f.length);return{kind:e,mediaIds:C,additionalData:s,sequenceNumber:E,encrypted:f}}async function Kx(v,t,j,e,B){let C=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:Hx(t,e),additionalData:j,tagLength:Ax*8},v.key,B).catch(()=>n);return C===n?n:v.antiReplays[t].isReplay(e)?n:new Uint8Array(C)}function vr(v,t,j){let e=2;try{let E=new O(j);for(E.position=0;E.position<j.length;)E.readObjects(1),e+=1}catch{return n}let B=er(v),C=new Uint8Array(3+B.length+t.length+j.length);return C[0]=220,C[1]=e>>8&255,C[2]=e&255,C.set(B,3),C.set(t,3+B.length),C.set(j,3+B.length+t.length),C}var Jx=class{constructor(t,j){this.active=!1;let e=new wx(j),B=new Nx(j);this.crypto=new Cr({encryption:B,decryption:e}),this.peerKeys=e.peerKeys,this.configure(t)}encryptUserData(t){return this.crypto.enqueue(({encryption:j})=>j.encryptUserData(t))}async encryptMessage(t){let j;do j=await this.crypto.enqueue(({encryption:e})=>e.encryptMessage(t));while(j===P);return j}async encryptDatagram(t){return await this.crypto.enqueue(({encryption:j})=>j.encryptDatagram(t))}decryptUserData(t,j){return this.crypto.enqueue(({decryption:e})=>e.decryptUserData(t,j))}decryptMessage(t,j){return this.crypto.enqueue(({decryption:e})=>e.decryptMessage(t,j))}decryptDatagram(t,j){return this.crypto.enqueue(({decryption:e})=>e.decryptDatagram(t,j))}configure(t){return this.crypto.enqueue(async j=>{let e=t.password?await yx.create(t.password):void 0;this.active=e!==void 0,await j.encryption.changeKey(e),await j.decryption.changeKey(e)})}getPeerStatus(t){switch(this.peerKeys.get(t)?.kind??"unencrypted"){case"broken":return jx.PeerCipherStatus.InvalidPassword;case"encrypted":return jx.PeerCipherStatus.Encrypted;case"unencrypted":return this.active?jx.PeerCipherStatus.InvalidPassword:jx.PeerCipherStatus.Unencrypted;default:return jx.PeerCipherStatus.Unknown}}deletePeerKey(t){this.peerKeys.delete(t)}reset(){return this.crypto.enqueue(async({encryption:t,decryption:j})=>{t.reset(),j.reset()})}async dump(){return this.crypto.enqueue(async()=>({active:this.active,peers:Array.from(this.peerKeys).map(([t,j])=>`${t} => ${j.kind}`)}))}};function CA(v,t){return Er(v.type==="OdinCrypto","only OdinCrypto supported"),new Jx(v,t)}var Px=class{constructor(t,j,e){this._Captures=new Map;this._Playbacks=new Map;this._Peers=new Map;this._AvailableMediaIds=[];let{url:B,onEvent:C}=j,E=nr(g.parse(j.token)),f=j.roomId??E.defaultRoomId,s=j.userData??new Uint8Array(0),a=j.position??[0,0,0];EA(f!==void 0,"room id required for multi-room-tokens"),this.cipher=j.cipher?CA(j.cipher,new hx(this)):void 0,this.onEvent=C,b(`creating new room '${f}' ${this.cipher?"with":"without"} cipher`,E,s,a),this._Connection=new Ix(t,j.transport??"H3",this._HandleEvent.bind(this),B?new URL(B):void 0,E,f,s,a,this.cipher,e?.disableAutoReconnect??!1)}get connectionStats(){let t={...sr};return this.mainConnection?this.mainConnection.connectionStats:t}get roomConnection(){return this._Connection}get mainConnection(){return this.roomConnection?.mainConnection}get token(){return this._Connection.token.text}request(t,j){return this._Connection.requestUnsafe(t,j)}async link(t){if(t instanceof L){let j=this._Playbacks.get(t.uid)??{media:void 0,playback:void 0};j.playback!==void 0&&this.unlink(j.playback),j.media!==void 0&&t.start(j.media),j.playback=t,b(`linking audio playback media '${t.uid}' with volume ${t.volume} to room '${this._Connection.roomId}'`),this._Playbacks.set(t.uid,j)}else if(t instanceof K){let j=this._Captures.get(t);j&&this.unlink(t);let e=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();j={media:e?{connectionId:this.mainConnection.id,mediaId:e}:void 0},b(`linking audio capture media '${t.uid}' with volume ${t.volume} to room '${this._Connection.roomId}'`),this._Captures.set(t,j),j.media!==void 0&&await t.start(this._Connection,j.media)}else if(t instanceof w){let j=this._Playbacks.get(t.uid)??{media:void 0,playback:void 0};if(j.playback!==void 0&&this.unlink(j.playback),j.media!==void 0){let e=await this.mainConnection?.startRemoteVideo(j.media.mediaId);e&&t.setMediaStream(new MediaStream([e]))}j.playback=t,b(`linking video playback media '${t.uid}' with type '${t.customType}' to room '${this._Connection.roomId}'`),this._Playbacks.set(t.uid,j)}else if(t instanceof $){let j=this._Captures.get(t);j&&this.unlink(t);let e=t.mediaStream?.getVideoTracks()[0];if(e){let B=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();j={media:B?{connectionId:this.mainConnection.id,mediaId:B}:void 0},b(`linking video capture media '${t.uid}' with type '${t.parameters?.customType}' to room '${this._Connection.roomId}'`),this._Captures.set(t,j),j.media!==void 0&&(await t.start(this._Connection,j.media),this.mainConnection?.startLocalVideo(j.media.mediaId,e,t.parameters)),t.audioCapture&&await this.link(t.audioCapture)}}else throw new Error("Linking failed, media was not supported")}unlink(t){if(t instanceof L||t instanceof w){let j=this._Playbacks.get(t.uid);if(j?.playback!==t)return;j.playback=void 0,j.media!==void 0&&(t instanceof L?t.stop(j.media):(this.mainConnection?.stopRemoteVideo(j.media.mediaId),t.setMediaStream(void 0))),b(`unlinking playback media '${t.uid}' from room '${this._Connection.roomId}'`),this._Playbacks.set(t.uid,j)}else if(t instanceof K||t instanceof $){t instanceof $&&t.audioCapture&&this.unlink(t.audioCapture);let j=this._Captures.get(t);if(j===void 0)return;j.media!==void 0&&(t.stop(this._Connection,j.media),this._AvailableMediaIds.push(j.media.mediaId),t instanceof $&&this.mainConnection?.stopLocalVideo(j.media.mediaId)),b(`unlinking capture media '${t.uid}' from room '${this._Connection.roomId}'`),this._Captures.delete(t)}else throw new Error("invalid media")}close(){b(`closing room '${this._Connection.roomId}'`),this._Connection.close()}_HandleEvent(t,j){let e=Zx(ir,{name:t,properties:j});e!==void 0&&(this._HandleKnownEvent(e),j=e.properties),this.onEvent(t,j)}_HandleKnownEvent(t){switch(o(`processing event '${t.name}'`,t.properties),t.name){case"RoomStatusChanged":t.properties.status!=="Joined"&&this._HandleConnectionLost();break;case"RoomUpdated":for(let j of t.properties.updates)this._HandleRoomUpdate(j);break;case"PeerUpdated":this._HandlePeerUpdate(t.properties);break}}_HandleConnectionLost(){for(let t of this._Peers.keys())this._HandlePeerLeft(t);for(let[t,j]of this._Captures)j.media!==void 0&&(t instanceof $,t instanceof K&&(t.stop(this._Connection,j.media),j.media=void 0));this._AvailableMediaIds.length=0}_HandleRoomUpdate(t){if(t.kind==="Joined"){EA(this._AvailableMediaIds.length===0,"left over media ids"),this._AvailableMediaIds.push(...t.media_ids),this._HandleRoomJoined();for(let j of t.room.peers)this._HandlePeerJoined(j)}else t.kind==="PeerJoined"?this._HandlePeerJoined(t.peer):t.kind==="PeerLeft"&&this._HandlePeerLeft(t.peer_id)}_HandleRoomJoined(){for(let[t,j]of this._Captures)this._AvailableMediaIds.length===0||this.mainConnection===void 0||(j.media={connectionId:this.mainConnection.id,mediaId:this._AvailableMediaIds.shift()},t instanceof K&&t.start(this._Connection,j.media),t instanceof $)}_HandlePeerUpdate(t){t.kind==="MediaStarted"?this._HandleMediaStart(t.peer_id,t.media):t.kind==="MediaStopped"&&this._HandleMediaStopped(t.peer_id,t.media_id)}_HandlePeerJoined(t){this._Peers.has(t.id)||this._Peers.set(t.id,{mediaIds:new Map});for(let j of t.medias)this._HandleMediaStart(t.id,j)}_HandlePeerLeft(t){let j=this._Peers.get(t);if(j!==void 0){for(let e of j.mediaIds.keys())this._HandleMediaStopped(t,e);this._Peers.delete(t)}}_HandleMediaStart(t,j){if(this.mainConnection===void 0)return;let e=this._Peers.get(t);if(e===void 0||j.properties.kind!=="audio"&&j.properties.kind!=="video")return;let B=String(j.properties.uid??fr());j.properties.uid=B;let C=this._Playbacks.get(B)??{media:void 0,playback:void 0};this._Playbacks.set(B,C),e.mediaIds.set(j.id,B),C.media={connectionId:this.mainConnection.id,mediaId:j.id},C.playback!==void 0&&(C.playback instanceof L&&C.playback.start(C.media),C.playback instanceof w&&this.mainConnection.startRemoteVideo(C.media.mediaId).then())}_HandleMediaStopped(t,j){let e=this._Peers.get(t);if(e===void 0)return;let B=e?.mediaIds.get(j);if(B===void 0)return;let C=this._Playbacks.get(B);C!==void 0&&(C.media!==void 0&&C.playback!==void 0&&(C.playback instanceof L&&C.playback.stop(C.media),C.playback instanceof w&&this.mainConnection?.stopRemoteVideo(C.media.mediaId)),C.media=void 0,e.mediaIds.delete(j))}};Ex();function sB(v,t){u0(t?.logger,t?.onLogMessage);let j,e=new qx((C,E)=>j.receivePacket(C,E)),B=new ix(v);return j=new bx(B,e.sendDatagram.bind(e)),new j0(e,j,t)}var kx=br(),e0=[],fA=!1;function or(){fA||typeof window>"u"||(window.addEventListener("beforeunload",()=>{for(let v of e0)v.deref()?.close()}),fA=!0)}var j0=class{constructor(t,j,e){this.version="9";this.supportedTransports=["H3","WebRTC"];this._PlaybackVolume=[1,1];this._CreatedAt=Date.now();this._Options=e??{},this._Options.disableBeforeUnload||or(),this._ConnectionPool=t,this._MediaController=j,e0.push(new WeakRef(this)),b("plugin initialized")}get playbackVolume(){return this._PlaybackVolume}joinRoom(t){return new Px(this._ConnectionPool,t,this._Options)}async createAudioPlayback(t){return this._MediaController.createAudioPlayback(t)}async createAudioCapture(t){return this._MediaController.createAudioCapture(t)}async createVideoCapture(t,j){return this._MediaController.createVideoCapture(t,j)}async createVideoPlayback(t){return new w(t.uid,t.customType)}enumerateDevices(){return Cx()}setOutputVolume(t){this._MediaController.playbackSetGlobalVolume(t)}async setOutputDevice(t){await this._MediaController.playbackSetDevice(t.device)}close(){this._MediaController.close(),this._ConnectionPool.close(),b("plugin closed")}async dump(){return{createdAt:this._CreatedAt,connections:await this._ConnectionPool.dump(),medias:await this._MediaController.dump()}}};async function nA(){let v=[];for(let t of e0){let j=t.deref();j!==void 0&&v.push(await j.dump())}return JSON.stringify({timestamp:Date.now(),instances:v,background:await h0()})}globalThis.odin_debug_dump_state=nA;window!==void 0&&(window.odin_debug_dump_state=nA);export{kx as SESSION_ID,sB as createPlugin};