@4players/odin-plugin-web 1.8.0 → 1.9.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
- "use strict";var Qx=Object.defineProperty;var lA=Object.getOwnPropertyDescriptor;var uA=Object.getOwnPropertyNames;var kA=Object.prototype.hasOwnProperty;var u=(D,x)=>()=>(D&&(x=D(D=0)),x);var lx=(D,x)=>{for(var A in x)Qx(D,A,{get:x[A],enumerable:!0})},cA=(D,x,A,F)=>{if(x&&typeof x=="object"||typeof x=="function")for(let r of uA(x))!kA.call(D,r)&&r!==A&&Qx(D,r,{get:()=>x[r],enumerable:!(F=lA(x,r))||F.enumerable});return D};var dA=D=>cA(Qx({},"__esModule",{value:!0}),D);var C={};lx(C,{AdditionalCaptureBlocks:()=>hA,AdditionalPlaybackBlocks:()=>pA,ClockJumpCheckInterval:()=>yA,ClockJumpThreshold:()=>_A,ConnectInterval:()=>OA,ConnectTimeout:()=>wA,DefaultRefreshRate:()=>mA,DefaultVideoCodec:()=>MA,HealthCheckTimeout:()=>gA,MainConnectionPingInterval:()=>LA,MaxNumberOfDecoders:()=>IA,MinDBFs:()=>Yx,MinTokenLifetime:()=>JA,MinTokenRefreshInterval:()=>PA,PlaybackPreload:()=>qA,RenderQuantumSize:()=>$A,VadPreload:()=>GA,WebRtcIceTimeout:()=>NA,WebRtcStatsSnapshotInterval:()=>HA,WebRtcTimeout:()=>KA});var pA,hA,qA,mA,GA,IA,$A,Yx,gA,yA,_A,LA,HA,NA,KA,wA,JA,PA,OA,MA,Zx=u(()=>{"use strict";pA=3,hA=3,qA=3,mA=250,GA=3,IA=512,$A=128,Yx=-758.596,gA=1e4,yA=1e3,_A=1e4,LA=3e3,HA=1e3,NA=3e3,KA=1e4,wA=5e3,JA=6e4,PA=5e3,OA=[0,100,200,200,500],MA="H264"});function ux(D){return typeof D!="symbol"}function s(D){return typeof D=="symbol"}var h,B,T,q,kx=u(()=>{"use strict";h=Symbol("Unencrypted"),B=Symbol("Invalid"),T=Symbol("Retry"),q=Symbol("UnexpectedEof")});function o(D,x,A){return D.postMessage(x,A)}function Fx(D,x){return new Promise(A=>{let F=r=>{let[t,j]=r.data;t===x&&(A(r.data[1]),D.removeEventListener("message",F))};D.addEventListener("message",F)})}var i0=u(()=>{"use strict"});function x0(D,x){D.values[0]=x[0],D.values[1]=x[1]}function b0(D,x){return D.values[2+x*5]}function o0(D,x,A){let F=2+x*5+1;D.values[F+0]=A[0],D.values[F+1]=A[1]}function a0(D){return D.values[0]!==0}function l0(D){return D.values[1]}function u0(D){return D.values[2]}function k0(D,x){return D.values[3]=x}var c0=u(()=>{"use strict"});function d0(D,x){let A=new S(D);A.position=x;let F=A.readObjects(1);return ux(F)?A.position:F}var S,p0=u(()=>{"use strict";kx();S=class{constructor(x,A=0){this.bytes=x;this.position=A}readArrayLength(){let x=this.readTag();return s(x)?x:(x&240)===144?x&15:x===220?this.readUint16():x===221?this.readUint32():B}readNumber(){let x=this.readTag();return s(x)||(x&128)===0?x:(x&224)===224?x-256:x===202?this.readFloat32():x===203?this.readFloat64():x===204?this.readUint8():x===205?this.readUint16():x===206?this.readUint32():x===207?this.readUint64():x===208?this.readInt8():x===209?this.readInt16():x===210?this.readInt32():x===211?this.readInt64():B}readBytes(){let x=this.readTag();if(s(x))return x;let A;if(x===196)A=this.readUint8();else if(x===197)A=this.readUint16();else if(x===198)A=this.readUint32();else return B;if(s(A))return A;let F=this.consume(A);return F!==q?this.bytes.subarray(F,F+A):q}readObjects(x){for(;x>0;x-=1){let A=this.readTag();if(s(A))return A;let F,r=0,t=0;switch(A){case 192:break;case 194:break;case 195:break;case 196:r=this.readUint8();break;case 197:r=this.readUint16();break;case 198:r=this.readUint32();break;case 199:r=this.readUint8(),t=1;break;case 200:r=this.readUint8(),t=1;break;case 201:r=this.readUint32(),t=1;break;case 202:r=4;break;case 203:r=8;break;case 204:r=1;break;case 205:r=2;break;case 206:r=4;break;case 207:r=8;break;case 208:r=1;break;case 209:r=2;break;case 210:r=4;break;case 211:r=8;break;case 212:r=2;break;case 213:r=3;break;case 214:r=5;break;case 215:r=9;break;case 216:r=17;break;case 217:r=this.readUint8();break;case 218:r=this.readUint16();break;case 219:r=this.readUint32();break;case 220:if(F=this.readUint16(),s(F))return F;x+=F;break;case 221:if(F=this.readUint32(),s(F))return F;x+=F;break;case 222:if(F=this.readUint16(),s(F))return F;x+=F*2;break;case 223:if(F=this.readUint32(),s(F))return F;x+=F*2;break;default:if((A&128)!==0){if((A&240)===128)x+=(A&15)*2;else if((A&240)===144)x+=A&15;else if((A&224)===160)r=A&31;else if((A&224)!==224)return B}}if(r===q)return q;if(this.consume(r+t)===q)return q}}consume(x){if(x===q||this.position+x>this.bytes.length)return q;let A=this.position;return this.position=A+x,A}readTag(){let x=this.consume(1);return ux(x)?this.bytes[x]:x}readUint8(){let x=this.consume(1);return ux(x)?this.bytes[x]:x}readUint16(){let x=this.consume(2);return s(x)?x:this.bytes[x]<<8|this.bytes[x+1]}readUint32(){let x=this.consume(4);return s(x)?x:this.bytes[x]<<24|this.bytes[x+1]<<16|this.bytes[x+2]<<8|this.bytes[x+3]}readUint64(){let x=this.readUint32();if(s(x))return x;if(x>=2097152)return B;let A=this.readUint32();return s(A)?A:x<<32|A}readInt8(){let x=this.readUint8();return s(x)||x>=128&&(x=x-256),x}readInt16(){let x=this.readUint16();return s(x)||x>=32768&&(x=x-65536),x}readInt32(){let x=this.readUint32();return s(x)||x>=2147483648&&(x=x-4294967296),x}readInt64(){let x=this.readUint32();if(s(x))return x;if(x>=2097152||x<-2097152)return B;let A=this.readUint32();return s(A)?A:x<<32|A}readFloat32(){let x=this.consume(4);return s(x)?x:new Float32Array(this.bytes.subarray(x,x+4))[0]}readFloat64(){let x=this.consume(8);return s(x)?x:new Float64Array(this.bytes.subarray(x,x+8))[0]}}});var h0,q0=u(()=>{"use strict";h0="1.8.0"});function m0(D,x){m||(m=D??new l.Logger(l.LogLevel.DEBUG,"odin-plugin-web",[]),x&&m.sinks.push(new l.CallbackSink(x,l.Formatter.structured)))}function a(D,...x){let A=cx(x);m?m?.error(D,A):(0,l.error)(D,A)}function c(D,...x){let A=cx(x);m?m?.warn(D,A):(0,l.warn)(D,A)}function E(D,...x){let A=cx(x);m?m?.info(D,A):(0,l.info)(D,A)}function f(D,...x){let A=cx(x);m?m?.debug(D,A):(0,l.debug)(D,A)}function cx(...D){if(D.length===1&&typeof D[0]=="object"&&D[0]!==null)return{...D[0]};if(D.length>0)return{args:D}}var l,m,G0=u(()=>{"use strict";l=require("@4players/odin-common")});function k(D){return D.connectionId*4294967296+D.mediaId}var $,Q,b=u(()=>{"use strict";Zx();kx();Zx();i0();c0();p0();q0();G0();kx();$={isSilent:!0,rmsDBFS:-758.596};Q=class{constructor(){this.inFlight=null}run(x){return this.inFlight||(this.inFlight=x().finally(()=>{this.inFlight=null})),this.inFlight}}});function ex(D,x,A,F,r){return Promise.all([RA(D),VA(A,x,F,r)])}async function RA(D){let x=URL.createObjectURL(new Blob([D],{type:"text/javascript"})),A=new Worker(x,{type:"module",name:"odin worker"});return rx.push(A),A}async function VA(D,x,A,F){try{let j=new AudioWorkletNode(D,A,F);return Z.push(j),j}catch{}let r=URL.createObjectURL(new Blob([x],{type:"text/javascript"}));await D.audioWorklet.addModule(r);let t=new AudioWorkletNode(D,A,F);return Z.push(t),t}async function g0(){return{workers:await Promise.all(rx.map(jx)),worklets:await Promise.all(Z.map(D=>jx(D.port)))}}function jx(D){let{port1:x,port2:A}=new MessageChannel,{promise:F,resolve:r}=Promise.withResolvers();return A.onmessage=t=>r(t.data),setTimeout(()=>r("timeout"),100),o(D,["dump",{result:x}],[x]),F}var rx,Z,Dx,tx,px=u(()=>{"use strict";b();rx=[],Z=[],Dx=class{constructor(x,A,F){this.audioContext=x;this.worklet=A;this.worker=F;this.availableIndexes=[];this.medias=new Map;F.addEventListener("message",this._OnMessages.bind(this))}receivePacket(x,A){o(this.worker,["playbackReceivePacket",{connectionId:x,packet:A}],[A.buffer])}addMedias(x,A,F=[1,1]){let r=[];for(let t of A){let j=this._GetFreeIndex();j!==void 0&&(this.medias.set(k({connectionId:x,mediaId:t}),{index:j}),r.push({connectionId:x,mediaId:t,index:j,volume:F}))}o(this.worker,["playbackUpdateMedias",{added:r,removed:[]}])}removeMedias(x,A){let F=[];for(let r of A){let t=k({connectionId:x,mediaId:r}),j=this.medias.get(t);j!==void 0&&(this.medias.delete(t),this.availableIndexes.push(j.index),F.push({connectionId:x,mediaId:r,index:j.index}))}o(this.worker,["playbackUpdateMedias",{added:[],removed:F}])}close(){o(this.worker,["close",void 0]),o(this.worklet.port,["close",void 0]);let x=rx.indexOf(this.worker);x>=0&&rx.splice(x,1);let A=Z.indexOf(this.worklet);A>=0&&Z.splice(A,1)}async dump(){return{playbackWorker:await jx(this.worker),playbackWorklet:await jx(this.worklet.port)}}_GetFreeIndex(){return this.availableIndexes.pop()}_OnMessages(x){}},tx=class D{constructor(x,A,F,r,t){this.worklet=x;this.worker=A;this.sink=(j,e)=>{t.deref()!==void 0?F(j,e):(a("capture worker was left abandoned, aborting capture worker"),D.shutdown(x,A))},this.monitorSink=(j,e)=>{t.deref()!==void 0?r(j,e):(a("capture worker was left abandoned, aborting capture worker"),D.shutdown(x,A))},A.addEventListener("message",this._OnMessages.bind(this))}get context(){return this.worklet.context}setMedias(x){o(this.worker,["captureSetMedias",{connections:x}])}setVad(x){o(this.worker,["captureSetVad",x])}close(){D.shutdown(this.worklet,this.worker)}static shutdown(x,A){o(x.port,["close",void 0]),o(A,["close",void 0]);let F=rx.indexOf(A);F>=0&&rx.splice(F,1);let r=Z.indexOf(x);r>=0&&Z.splice(r,1)}async dump(){return{captureWorker:await jx(this.worker),captureWorklet:await jx(this.worklet.port)}}_OnMessages(x){let[A,F]=x.data;A==="sendPacket"&&(F.connectionId===0?this.monitorSink(F.connectionId,F.packet):this.sink(F.connectionId,F.packet))}}});var A0,y0=u(()=>{A0=`"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\\\`
1
+ "use strict";var Qx=Object.defineProperty;var lA=Object.getOwnPropertyDescriptor;var uA=Object.getOwnPropertyNames;var kA=Object.prototype.hasOwnProperty;var u=(D,x)=>()=>(D&&(x=D(D=0)),x);var lx=(D,x)=>{for(var A in x)Qx(D,A,{get:x[A],enumerable:!0})},cA=(D,x,A,F)=>{if(x&&typeof x=="object"||typeof x=="function")for(let r of uA(x))!kA.call(D,r)&&r!==A&&Qx(D,r,{get:()=>x[r],enumerable:!(F=lA(x,r))||F.enumerable});return D};var dA=D=>cA(Qx({},"__esModule",{value:!0}),D);var C={};lx(C,{AdditionalCaptureBlocks:()=>hA,AdditionalPlaybackBlocks:()=>pA,ClockJumpCheckInterval:()=>yA,ClockJumpThreshold:()=>_A,ConnectInterval:()=>OA,ConnectTimeout:()=>wA,DefaultRefreshRate:()=>mA,DefaultVideoCodec:()=>MA,HealthCheckTimeout:()=>gA,MainConnectionPingInterval:()=>LA,MaxNumberOfDecoders:()=>IA,MinDBFs:()=>Yx,MinTokenLifetime:()=>JA,MinTokenRefreshInterval:()=>PA,PlaybackPreload:()=>qA,RenderQuantumSize:()=>$A,VadPreload:()=>GA,WebRtcIceTimeout:()=>NA,WebRtcStatsSnapshotInterval:()=>HA,WebRtcTimeout:()=>KA});var pA,hA,qA,mA,GA,IA,$A,Yx,gA,yA,_A,LA,HA,NA,KA,wA,JA,PA,OA,MA,Zx=u(()=>{"use strict";pA=3,hA=3,qA=3,mA=250,GA=3,IA=512,$A=128,Yx=-758.596,gA=1e4,yA=1e3,_A=1e4,LA=3e3,HA=1e3,NA=3e3,KA=1e4,wA=5e3,JA=6e4,PA=5e3,OA=[0,100,200,200,500],MA="H264"});function ux(D){return typeof D!="symbol"}function s(D){return typeof D=="symbol"}var h,B,T,q,kx=u(()=>{"use strict";h=Symbol("Unencrypted"),B=Symbol("Invalid"),T=Symbol("Retry"),q=Symbol("UnexpectedEof")});function o(D,x,A){return D.postMessage(x,A)}function Fx(D,x){return new Promise(A=>{let F=r=>{let[t,j]=r.data;t===x&&(A(r.data[1]),D.removeEventListener("message",F))};D.addEventListener("message",F)})}var i0=u(()=>{"use strict"});function x0(D,x){D.values[0]=x[0],D.values[1]=x[1]}function b0(D,x){return D.values[2+x*5]}function o0(D,x,A){let F=2+x*5+1;D.values[F+0]=A[0],D.values[F+1]=A[1]}function a0(D){return D.values[0]!==0}function l0(D){return D.values[1]}function u0(D){return D.values[2]}function k0(D,x){return D.values[3]=x}var c0=u(()=>{"use strict"});function d0(D,x){let A=new S(D);A.position=x;let F=A.readObjects(1);return ux(F)?A.position:F}var S,p0=u(()=>{"use strict";kx();S=class{constructor(x,A=0){this.bytes=x;this.position=A}readArrayLength(){let x=this.readTag();return s(x)?x:(x&240)===144?x&15:x===220?this.readUint16():x===221?this.readUint32():B}readNumber(){let x=this.readTag();return s(x)||(x&128)===0?x:(x&224)===224?x-256:x===202?this.readFloat32():x===203?this.readFloat64():x===204?this.readUint8():x===205?this.readUint16():x===206?this.readUint32():x===207?this.readUint64():x===208?this.readInt8():x===209?this.readInt16():x===210?this.readInt32():x===211?this.readInt64():B}readBytes(){let x=this.readTag();if(s(x))return x;let A;if(x===196)A=this.readUint8();else if(x===197)A=this.readUint16();else if(x===198)A=this.readUint32();else return B;if(s(A))return A;let F=this.consume(A);return F!==q?this.bytes.subarray(F,F+A):q}readObjects(x){for(;x>0;x-=1){let A=this.readTag();if(s(A))return A;let F,r=0,t=0;switch(A){case 192:break;case 194:break;case 195:break;case 196:r=this.readUint8();break;case 197:r=this.readUint16();break;case 198:r=this.readUint32();break;case 199:r=this.readUint8(),t=1;break;case 200:r=this.readUint8(),t=1;break;case 201:r=this.readUint32(),t=1;break;case 202:r=4;break;case 203:r=8;break;case 204:r=1;break;case 205:r=2;break;case 206:r=4;break;case 207:r=8;break;case 208:r=1;break;case 209:r=2;break;case 210:r=4;break;case 211:r=8;break;case 212:r=2;break;case 213:r=3;break;case 214:r=5;break;case 215:r=9;break;case 216:r=17;break;case 217:r=this.readUint8();break;case 218:r=this.readUint16();break;case 219:r=this.readUint32();break;case 220:if(F=this.readUint16(),s(F))return F;x+=F;break;case 221:if(F=this.readUint32(),s(F))return F;x+=F;break;case 222:if(F=this.readUint16(),s(F))return F;x+=F*2;break;case 223:if(F=this.readUint32(),s(F))return F;x+=F*2;break;default:if((A&128)!==0){if((A&240)===128)x+=(A&15)*2;else if((A&240)===144)x+=A&15;else if((A&224)===160)r=A&31;else if((A&224)!==224)return B}}if(r===q)return q;if(this.consume(r+t)===q)return q}}consume(x){if(x===q||this.position+x>this.bytes.length)return q;let A=this.position;return this.position=A+x,A}readTag(){let x=this.consume(1);return ux(x)?this.bytes[x]:x}readUint8(){let x=this.consume(1);return ux(x)?this.bytes[x]:x}readUint16(){let x=this.consume(2);return s(x)?x:this.bytes[x]<<8|this.bytes[x+1]}readUint32(){let x=this.consume(4);return s(x)?x:this.bytes[x]<<24|this.bytes[x+1]<<16|this.bytes[x+2]<<8|this.bytes[x+3]}readUint64(){let x=this.readUint32();if(s(x))return x;if(x>=2097152)return B;let A=this.readUint32();return s(A)?A:x<<32|A}readInt8(){let x=this.readUint8();return s(x)||x>=128&&(x=x-256),x}readInt16(){let x=this.readUint16();return s(x)||x>=32768&&(x=x-65536),x}readInt32(){let x=this.readUint32();return s(x)||x>=2147483648&&(x=x-4294967296),x}readInt64(){let x=this.readUint32();if(s(x))return x;if(x>=2097152||x<-2097152)return B;let A=this.readUint32();return s(A)?A:x<<32|A}readFloat32(){let x=this.consume(4);return s(x)?x:new Float32Array(this.bytes.subarray(x,x+4))[0]}readFloat64(){let x=this.consume(8);return s(x)?x:new Float64Array(this.bytes.subarray(x,x+8))[0]}}});var h0,q0=u(()=>{"use strict";h0="1.9.0"});function m0(D,x){m||(m=D??new l.Logger(l.LogLevel.DEBUG,"odin-plugin-web",[]),x&&m.sinks.push(new l.CallbackSink(x,l.Formatter.structured)))}function a(D,...x){let A=cx(x);m?m?.error(D,A):(0,l.error)(D,A)}function c(D,...x){let A=cx(x);m?m?.warn(D,A):(0,l.warn)(D,A)}function E(D,...x){let A=cx(x);m?m?.info(D,A):(0,l.info)(D,A)}function f(D,...x){let A=cx(x);m?m?.debug(D,A):(0,l.debug)(D,A)}function cx(...D){if(D.length===1&&typeof D[0]=="object"&&D[0]!==null)return{...D[0]};if(D.length>0)return{args:D}}var l,m,G0=u(()=>{"use strict";l=require("@4players/odin-common")});function k(D){return D.connectionId*4294967296+D.mediaId}var $,X,b=u(()=>{"use strict";Zx();kx();Zx();i0();c0();p0();q0();G0();kx();$={isSilent:!0,rmsDBFS:-758.596};X=class{constructor(){this.inFlight=null}run(x){return this.inFlight||(this.inFlight=x().finally(()=>{this.inFlight=null})),this.inFlight}}});function ex(D,x,A,F,r){return Promise.all([RA(D),VA(A,x,F,r)])}async function RA(D){let x=URL.createObjectURL(new Blob([D],{type:"text/javascript"})),A=new Worker(x,{type:"module",name:"odin worker"});return rx.push(A),A}async function VA(D,x,A,F){try{let j=new AudioWorkletNode(D,A,F);return Y.push(j),j}catch{}let r=URL.createObjectURL(new Blob([x],{type:"text/javascript"}));await D.audioWorklet.addModule(r);let t=new AudioWorkletNode(D,A,F);return Y.push(t),t}async function g0(){return{workers:await Promise.all(rx.map(jx)),worklets:await Promise.all(Y.map(D=>jx(D.port)))}}function jx(D){let{port1:x,port2:A}=new MessageChannel,{promise:F,resolve:r}=Promise.withResolvers();return A.onmessage=t=>r(t.data),setTimeout(()=>r("timeout"),100),o(D,["dump",{result:x}],[x]),F}var rx,Y,Dx,tx,px=u(()=>{"use strict";b();rx=[],Y=[],Dx=class{constructor(x,A,F){this.audioContext=x;this.worklet=A;this.worker=F;this.availableIndexes=[];this.medias=new Map;F.addEventListener("message",this._OnMessages.bind(this))}receivePacket(x,A){o(this.worker,["playbackReceivePacket",{connectionId:x,packet:A}],[A.buffer])}addMedias(x,A,F=[1,1]){let r=[];for(let t of A){let j=this._GetFreeIndex();j!==void 0&&(this.medias.set(k({connectionId:x,mediaId:t}),{index:j}),r.push({connectionId:x,mediaId:t,index:j,volume:F}))}o(this.worker,["playbackUpdateMedias",{added:r,removed:[]}])}removeMedias(x,A){let F=[];for(let r of A){let t=k({connectionId:x,mediaId:r}),j=this.medias.get(t);j!==void 0&&(this.medias.delete(t),this.availableIndexes.push(j.index),F.push({connectionId:x,mediaId:r,index:j.index}))}o(this.worker,["playbackUpdateMedias",{added:[],removed:F}])}close(){o(this.worker,["close",void 0]),o(this.worklet.port,["close",void 0]);let x=rx.indexOf(this.worker);x>=0&&rx.splice(x,1);let A=Y.indexOf(this.worklet);A>=0&&Y.splice(A,1)}async dump(){return{playbackWorker:await jx(this.worker),playbackWorklet:await jx(this.worklet.port)}}_GetFreeIndex(){return this.availableIndexes.pop()}_OnMessages(x){}},tx=class D{constructor(x,A,F,r,t){this.worklet=x;this.worker=A;this.sink=(j,e)=>{t.deref()!==void 0?F(j,e):(a("capture worker was left abandoned, aborting capture worker"),D.shutdown(x,A))},this.monitorSink=(j,e)=>{t.deref()!==void 0?r(j,e):(a("capture worker was left abandoned, aborting capture worker"),D.shutdown(x,A))},A.addEventListener("message",this._OnMessages.bind(this))}get context(){return this.worklet.context}setMedias(x){o(this.worker,["captureSetMedias",{connections:x}])}setVad(x){o(this.worker,["captureSetVad",x])}close(){D.shutdown(this.worklet,this.worker)}static shutdown(x,A){o(x.port,["close",void 0]),o(A,["close",void 0]);let F=rx.indexOf(A);F>=0&&rx.splice(F,1);let r=Y.indexOf(x);r>=0&&Y.splice(r,1)}async dump(){return{captureWorker:await jx(this.worker),captureWorklet:await jx(this.worklet.port)}}_OnMessages(x){let[A,F]=x.data;A==="sendPacket"&&(F.connectionId===0?this.monitorSink(F.connectionId,F.packet):this.sink(F.connectionId,F.packet))}}});var A0,y0=u(()=>{A0=`"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
@@ -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 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 F0,_0=u(()=>{F0='"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 H0={};lx(H0,{createCaptureWorker:()=>XA,createPlaybackWorker:()=>QA});function XA(D,x,A,F,r=C.DefaultRefreshRate){return zA.enqueue(async()=>{let[t,j]=await ex(A0,F0,D,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return D0.create(D,x,A,t,j,F)})}async function QA(D,x=C.DefaultRefreshRate){if(D.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[A,F]=await ex(A0,F0,D,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return r0.create(D,A,F)}var L0,zA,r0,D0,N0=u(()=>{"use strict";L0=require("@4players/odin-common");b();px();y0();_0();zA=new L0.Strand;r0=class D extends Dx{constructor(A,F,r,t){super(A,F,r);this.information=t}static async create(A,F,r){let{port1:t,port2:j}=new MessageChannel;o(F,["playbackInit",{workletPort:t}],[t]);let{informationBuffer:e,sampleBuffer:v}=await Fx(F,"playbackReady");return x0(e,[1,1]),o(r.port,["init",{sampleBuffer:v,workerPort:j}],[j]),r.connect(A.destination),new D(A,r,F,e)}getActivity(A){let F=this.medias.get(k(A));if(F===void 0)return;let r=b0(this.information,F.index);return r===0?$:{isSilent:!1,rmsDBFS:r}}getJitterStats(A){}setGlobalVolume(A){x0(this.information,A)}setVolume(A,F){let r=this.medias.get(k(A));r!==void 0&&o0(this.information,r.index,F)}_GetFreeIndex(){let A=super._GetFreeIndex();if(A!==void 0)return A;if(this.information.length>this.medias.size)return this.medias.size}},D0=class D extends tx{constructor(A,F,r,t,j,e){super(A,F,r,t,e);this.information=j}static async create(A,F,r,t,j,e){let{port1:v,port2:n}=new MessageChannel;o(t,["captureInit",{sampleRate:A.sampleRate,workletPort:v}],[v]);let{sampleBuffer:p,informationBuffer:H}=await Fx(t,"captureReady");return o(j.port,["init",{workerPort:n,sampleBuffer:p}],[n]),new D(j,t,F,r,H,e)}get activity(){return{isSilent:!a0(this.information),rmsDBFS:u0(this.information)}}get speechProbability(){return l0(this.information)}setVolume(A){k0(this.information,A)}}});var t0,K0=u(()=>{t0=`"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(3,"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.name}\`:"";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 0: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 F0,_0=u(()=>{F0='"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}"},ae={4:ne,3:m,2:m,1:T,0:T};function oe({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(3,"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],o=e.logger.name!==void 0?`@${e.logger.name}`:"";return`${m(r())}${o} ${s} ${ae[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=oe;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 0: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 a=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 a(3,void 0,[new le]),ue=a.prototype.log.bind(u,1),fe=a.prototype.log.bind(u,2),de=a.prototype.log.bind(u,3),pe=a.prototype.log.bind(u,4),Be=a.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 o=this.state.fill(0,r[0][0]);return this.state.offset===this.state.length&&(this.blocks+=1,this.state.flush(),this.state.fill(o,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 o=this.state.fill(0,n[0][0],n[0][1]);return o<l.RenderQuantumSize&&(this.totalBlocks+=1,this.state.next(),this.state.hasVoice?this.voiceBlocks+=1:this.silenceBlocks+=1,this.state.fill(o,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 H0={};lx(H0,{createCaptureWorker:()=>XA,createPlaybackWorker:()=>QA});function XA(D,x,A,F,r=C.DefaultRefreshRate){return zA.enqueue(async()=>{let[t,j]=await ex(A0,F0,D,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return D0.create(D,x,A,t,j,F)})}async function QA(D,x=C.DefaultRefreshRate){if(D.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[A,F]=await ex(A0,F0,D,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return r0.create(D,A,F)}var L0,zA,r0,D0,N0=u(()=>{"use strict";L0=require("@4players/odin-common");b();px();y0();_0();zA=new L0.Strand;r0=class D extends Dx{constructor(A,F,r,t){super(A,F,r);this.information=t}static async create(A,F,r){let{port1:t,port2:j}=new MessageChannel;o(F,["playbackInit",{workletPort:t}],[t]);let{informationBuffer:e,sampleBuffer:v}=await Fx(F,"playbackReady");return x0(e,[1,1]),o(r.port,["init",{sampleBuffer:v,workerPort:j}],[j]),r.connect(A.destination),new D(A,r,F,e)}getActivity(A){let F=this.medias.get(k(A));if(F===void 0)return;let r=b0(this.information,F.index);return r===0?$:{isSilent:!1,rmsDBFS:r}}getJitterStats(A){}setGlobalVolume(A){x0(this.information,A)}setVolume(A,F){let r=this.medias.get(k(A));r!==void 0&&o0(this.information,r.index,F)}_GetFreeIndex(){let A=super._GetFreeIndex();if(A!==void 0)return A;if(this.information.length>this.medias.size)return this.medias.size}},D0=class D extends tx{constructor(A,F,r,t,j,e){super(A,F,r,t,e);this.information=j}static async create(A,F,r,t,j,e){let{port1:v,port2:n}=new MessageChannel;o(t,["captureInit",{sampleRate:A.sampleRate,workletPort:v}],[v]);let{sampleBuffer:p,informationBuffer:H}=await Fx(t,"captureReady");return o(j.port,["init",{workerPort:n,sampleBuffer:p}],[n]),new D(j,t,F,r,H,e)}get activity(){return{isSilent:!a0(this.information),rmsDBFS:u0(this.information)}}get speechProbability(){return l0(this.information)}setVolume(A){k0(this.information,A)}}});var t0,K0=u(()=>{t0=`"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
@@ -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:()=>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 j0,w0=u(()=>{j0='"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 P0={};lx(P0,{UnsharedCaptureWorker:()=>hx,UnsharedPlaybackWorker:()=>qx,createCaptureWorker:()=>AF,createPlaybackWorker:()=>FF});function AF(D,x,A,F,r=C.DefaultRefreshRate){return xF.enqueue(async()=>{let[t,j]=await ex(t0,j0,D,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return console.warn("SharedArrayBuffer is not available; creating ODIN CaptureWorker in fallback mode"),hx.create(D,x,A,r,t,j,F)})}async function FF(D,x=C.DefaultRefreshRate){if(D.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[A,F]=await ex(t0,j0,D,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return qx.create(D,x,A,F)}var J0,xF,hx,qx,O0=u(()=>{"use strict";J0=require("@4players/odin-common");b();px();K0();w0();xF=new J0.Strand;hx=class D extends tx{constructor(A,F,r,t,j){super(A,F,r,t,j);this._Activity=$;this._SpeechProbability=0;F.addEventListener("message",this._OnMessages.bind(this))}static async create(A,F,r,t,j,e,v){let{port1:n,port2:p}=new MessageChannel;return o(j,["captureInit",{sampleRate:A.sampleRate,refreshRate:t,workletPort:n}],[n]),await Fx(j,"captureReady"),o(e.port,["init",{workerPort:p}],[p]),new D(e,j,F,r,v)}get activity(){return this._Activity}get speechProbability(){return this._SpeechProbability}setVolume(A){o(this.worker,["captureSetVolume",{value:A}])}_OnMessages(A){super._OnMessages(A);let[F,r]=A.data;F==="captureUpdate"&&(this._Activity={isSilent:!r.active,rmsDBFS:r.rmsDBFs},this._SpeechProbability=r.speechProbability)}},qx=class D extends Dx{constructor(A,F,r){super(A,F,r);this.activities=new Float32Array;this.jitterStats=[]}static async create(A,F,r,t){let{port1:j,port2:e}=new MessageChannel;return o(r,["playbackInit",{workletPort:j,refreshRate:F}],[j]),await Fx(r,"playbackReady"),o(t.port,["init",{workerPort:e}],[e]),t.connect(A.destination),new D(A,t,r)}getActivity(A){let F=this.medias.get(k(A));if(F===void 0)return;let r=this.activities.at(F.index);if(r!==void 0)return r===0?$:{isSilent:!1,rmsDBFS:r}}getJitterStats(A){let F=this.medias.get(k(A));if(F===void 0)return;let r=this.jitterStats.at(F.index);if(r!==void 0)return r}setGlobalVolume(A){o(this.worker,["playbackSetVolume",{index:"global",value:A}])}setVolume(A,F){let r=this.medias.get(k(A));r!==void 0&&o(this.worker,["playbackSetVolume",{index:r.index,value:F}])}_GetFreeIndex(){let A=super._GetFreeIndex();if(A!==void 0)return A;if(this.medias.size<C.MaxNumberOfDecoders)return this.medias.size}_OnMessages(A){super._OnMessages(A);let[F,r]=A.data;F==="playbackUpdate"&&(this.activities=r.activities,this.jitterStats=r.jitterStats)}}});var dF={};lx(dF,{SESSION_ID:()=>ix,createPlugin:()=>kF});module.exports=dA(dF);var uF=require("@4players/odin-common");b();var vx=require("@4players/odin-common");b();var Bx=require("@4players/odin-common");b();var N=require("@4players/odin-common");async function I0(D,x,A){let F;if(x.device?.device.kind==="track"&&x.device?.device.audioTrack)F=new MediaStream([x.device.device.audioTrack]);else{let j=x.device?{exact:x.device.device.deviceId==="default"?void 0:x.device.device.deviceId}:void 0;try{let e=await Promise.race([navigator.mediaDevices.getUserMedia({audio:{echoCancellation:A.echoCanceller,noiseSuppression:A.noiseSuppression!=="None",autoGainControl:A.gainController,echoCancellationType:"system",deviceId:j}}),(0,N.sleep)(3e4,"timeout")]);if(e==="timeout")return(0,N.failure)("getUserMedia; timeout");F=e}catch(e){return(0,N.failure)(`getUserMedia; ${e}`)}}let r=F.getAudioTracks()[0].getSettings().sampleRate,t=await D.audioContexts.acquire(r);return(0,N.success)(t.createMediaStreamSource(F))}function Y(D){D.getTracks().forEach(x=>{x.stop(),D.removeTrack(x)})}async function $0(D){return new g({deviceId:D.id,kind:"track",name:D.label??"MediaStreamTrack",audioTrack:D},!1)}async function dx(){if((0,N.isFirefoxBrowser)()){let r=await TA("microphone");(r==="granted"||r===!1)&&await SA("audio")}let D=(await navigator.mediaDevices.enumerateDevices()).filter(r=>!!r.label),x=[],A=new g({deviceId:"default",name:"Default",kind:"audioinput"},!0),F=new g({deviceId:"default",name:"Default",kind:"audiooutput"},!0);x.push(A),x.push(F);for(let r of D){if(r.deviceId==="default"){r.kind==="audioinput"&&(A=new g({deviceId:"default",name:r.label,kind:"audioinput"},!0),x[0]=A),r.kind==="audiooutput"&&(F=new g({deviceId:"default",name:r.label,kind:"audiooutput"},!0),x[1]=F);continue}r.kind==="audioinput"&&x.push(new g({deviceId:r.deviceId,name:r.label,kind:"audioinput"},!1)),r.kind==="audiooutput"&&x.push(new g({deviceId:r.deviceId,name:r.label,kind:"audiooutput"},!1))}return x}async function TA(D){try{return(await navigator.permissions.query({name:D})).state}catch{return!1}}async function SA(D){try{let x=await navigator.mediaDevices.getUserMedia({[D]:!0});return x?.getTracks().forEach(A=>{A.stop(),x.removeTrack(A)}),!0}catch{return!1}}var mx=require("@4players/odin-common");b();var M0=(0,mx.isSharedArrayBufferCapable)()&&!(0,mx.isSafariBrowser)()?Promise.resolve().then(()=>(N0(),H0)):Promise.resolve().then(()=>(O0(),P0));async function T0(D,x,A,F){return M0.then(r=>r.createCaptureWorker(D,x,A,F,C.DefaultRefreshRate))}async function S0(D){return M0.then(x=>x.createPlaybackWorker(D,C.DefaultRefreshRate))}var K=class{constructor(x,A){this.controller=x;this._Medias=new Map;this._Vad={...Bx.VAD_DEFAULTS};this._Apm={...Bx.APM_DEFAULTS};this._Volume=1;this._ProcessingDevice=!1;this._DeviceCb=async()=>{(await dx()).some(F=>F.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&&(Y(this._Capture.source.mediaStream),this._Capture.source.disconnect(this._Capture.worker.worklet)))};A.apm&&this.setApm(A.apm).catch(console.error),A.vad&&this.setVad(A.vad),typeof A.volume<"u"&&this.setVolume(A.volume).catch(console.error),this.uid=(0,Bx.generateUUID)(),this.#x=A.customType,this.#A=A.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(x,A){let F=this._Medias.get(A.connectionId);F===void 0&&this._Medias.set(A.connectionId,F=new Set),E(`starting audio capture media ${A.mediaId} on connection ${A.connectionId}`),!F.has(A.mediaId)&&(F.add(A.mediaId),x.mainConnection?.id===A.connectionId&&await x.request("StartMedia",{media_id:A.mediaId,properties:{kind:"audio",uid:this.uid,ref:this.#A,customType:this.#x}}).catch(r=>a(`StartMedia got rejected; ${r}`)),this._UpdateMedias())}async stop(x,A){let F=this._Medias.get(A.connectionId);E(`stopping audio capture media ${A.mediaId} on connection ${A.connectionId}`),F?.delete(A.mediaId)&&(x.mainConnection?.id===A.connectionId&&await x.request("StopMedia",{media_id:A.mediaId}).catch(r=>a(`StopMedia got rejected; ${r}`)),this._UpdateMedias())}setVad(x){f("updating vad config",x),this._Vad=x,this._Capture&&this._Capture.worker.setVad(x)}async setApm(x){f("updating apm config",x),this._Apm=x,this._DeviceParameters&&await this.setDevice(this._DeviceParameters)}async setDevice(x){if(f("updating capture device parameters",x),this._ProcessingDevice)return;this._ProcessingDevice=!0;let A=this._DeviceParameters;if(this._DeviceParameters=x,this._Volume==="muted"){this._ProcessingDevice=!1;return}try{let F=await I0(this.controller,x,{...this._Apm,echoCanceller:this._Monitor?!1:this._Apm.echoCanceller});if(F.type!=="Success"){a(`unable to open capture device; ${F.reason}`),this._DeviceParameters=A,this._ProcessingDevice=!1;return}this._DeviceParameters.onStatusChanged&&navigator.mediaDevices.addEventListener("devicechange",this._DeviceCb),this._Capture!==void 0&&(Y(this._Capture.source.mediaStream),this._Capture.source.disconnect(this._Capture.worker.worklet)),this._Capture===void 0||this._Capture.worker.worklet.context!==F.value.context?(this._Capture?.worker.close(),this._Capture={worker:await T0(F.value.context,this.controller.sink,this.controller.receiveMonitoredPacket.bind(this.controller),new WeakRef(this)),source:F.value},await this._UpdateMedias(),await this.setVolume(this._Volume),this.setVad(this.vad)):this._Capture.source=F.value,this._Capture.source.connect(this._Capture.worker.worklet)}catch(F){throw this._ProcessingDevice=!1,new Error(`Error in setDevice(); ${F}`)}this._ProcessingDevice=!1}async setVolume(x){f(`updating capture volume to ${x}`),this._Volume=x,x==="muted"?await this.close():(!this._Capture&&this._DeviceParameters&&await this.setDevice(this._DeviceParameters),this._Capture?.worker.setVolume(x)),x!==this._Volume&&await this.setVolume(this._Volume)}async close(){if(f("closing audio capture"),this._Capture!==void 0){this._Capture.worker.close(),Y(this._Capture.source.mediaStream);try{this._Capture.source.disconnect(this._Capture.worker.worklet)}catch(x){c("failed to disconnect audio node",x)}await this.controller.audioContexts.release(this._Capture.source.context)}navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._Capture=void 0}async dump(){let x=[];for(let[A,F]of this._Medias)x.push(`${A} => ${Array.from(F.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:x}}async _UpdateMedias(){if(this._Capture!==void 0){let x=Array.from(this._Medias).map(([A,F])=>({id:A,mediaIds:Array.from(F)}));this._Capture.worker.setMedias(x)}}async startLoopback(){this._Monitor===void 0&&(f("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&&(f("stopping audio capture loopback"),this._Monitor.close(),this._Monitor=void 0,this.setApm(this._Apm),this._Medias.delete(0),await this._UpdateMedias())}};var sx=require("@4players/odin-common");b();var G=class{constructor(x,A){this.controller=x;this.parameters=A;this.uid=(0,sx.generateUUID)()}#x;#A=new Map;#F;get customType(){return this.parameters?.customType}get mediaStream(){return this.#x}get audioCapture(){return this.#F}get volume(){return(0,sx.assert)(this.audioCapture,"getting the volume failed, this video has no Audio"),this.audioCapture.volume}async setVolume(x){(0,sx.assert)(this.audioCapture,"setVolume() failed, this video has no Audio"),await this.audioCapture.setVolume(x)}get vad(){return(0,sx.assert)(this.audioCapture,"getting the vad config failed, this video has no Audio"),this.audioCapture.vad}setVad(x){(0,sx.assert)(this.audioCapture,"setVad() failed, this video has no Audio"),this.audioCapture.setVad(x)}async setDevice(x,A={voiceActivity:void 0,volumeGate:void 0}){if(this.#x)throw new Error("This VideoCapture already has a MediaStream.");if(!x.getVideoTracks()[0])throw new Error("Error when calling setDevice(), MediaStream does not contain a VideoStreamTrack!");if(this.#x=x,x.getAudioTracks()[0]){let r={device:await $0(x.getAudioTracks()[0]),vad:A,ref:this.uid};this.#F=await this.controller.createAudioCapture(r)}}async start(x,A){let F=this.#A.get(A.connectionId);if(F===void 0&&this.#A.set(A.connectionId,F=new Set),!F.has(A.mediaId)&&(F.add(A.mediaId),x.mainConnection?.id===A.connectionId)){let r={kind:"video",codec:this.parameters?.codec??"H264",ref:this.#F?.uid,uid:this.uid};this.parameters?.customType&&(r.customType=this.parameters.customType),await x.request("StartMedia",{media_id:A.mediaId,properties:r}).catch(t=>a(`StartMedia got rejected; ${t}`))}}async stop(x,A){this.#x&&Y(this.#x),this.#A.get(A.connectionId)?.delete(A.mediaId)&&x.mainConnection?.id===A.connectionId&&await x.request("StopMedia",{media_id:A.mediaId}).catch(r=>a(`StopMedia got rejected; ${r}`))}async dump(){let x=[];for(let[A,F]of this.#A)x.push(`${A} => ${Array.from(F.values()).join(",")}`);return{uid:this.uid,ref:this.#F?.uid??null,customType:this.customType??null,tracks:this.#x?.getVideoTracks().map(A=>({id:A.id,kind:A.kind,label:A.label,ready:A.readyState,muted:A.muted,settings:{...A.getSettings()}}))??[],volume:this.#F?.volume??0,medias:x}}close(){this.#x&&Y(this.#x),this.audioCapture?.close(),this.#F=void 0}};var Hr=require("@4players/odin-common");b();var y=class{constructor(x,A,F){this.controller=x;this.uid=A;this.customType=F}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(x){E(`starting audio playback media ${x.mediaId} on connection ${x.connectionId}`),this.controller.playbackStart(this.uid,x)}stop(x){E(`stopping audio playback media ${x.mediaId} on connection ${x.connectionId}`),this.controller.playbackStop(this.uid,x)}setVolume(x){f(`updating audio playback media '${this.uid}' volume to ${x}`),this.controller.playbackSetVolume(this.uid,x)}close(){f(`closing audio playback media '${this.uid}'`),this.controller.closePlayback(this.uid)}};var Gx=class{constructor(x){this.audioContextFactory=x;this.entries=[]}async acquire(x){for(let F of this.entries){if(F.sampleRate===x)return F.references+=1,F.audioContext;if(F.sampleRate===void 0&&F.audioContext.sampleRate===x)return F.references+=1,F.audioContext}let A={sampleRate:x,audioContext:await this.audioContextFactory(x),references:1};return this.entries.push(A),A.audioContext}async release(x){let A=this.entries.findIndex(F=>F.audioContext===x);if(!(A<0)&&(this.entries[A].references-=1,this.entries[A].references<=0)){let F=this.entries[A].audioContext;this.entries.splice(A,1),await F.close()}}close(){for(let x of this.entries)x.audioContext.close()}},Ix=class D{constructor(x,A){this.audioContexts=x;this.sink=A;this.audioCaptures=[];this.videoCaptures=[];this.globalVolume=[1,1];this.playbacks=new Map;this.setPlaybackStrand=new vx.Strand}async create(x,A){return new D(x,A)}receivePacket(x,A){this.playbackWorker?.receivePacket(x,A)}receiveMonitoredPacket(x,A){let F=A.slice();this.receivePacket(x,F)}async createAudioPlayback(x){let A=this.playbacks.get(x.uid),F=x.volume;if(A===void 0){F=F??[1,1];let r=new y(this,x.uid,x.customType);A={id:void 0,volume:F,playback:r},this.playbacks.set(x.uid,A)}return F!==void 0&&A.playback.setVolume(F),A.playback}async createAudioCapture(x){let A=new K(this,x);return await A.setDevice(x),this.audioCaptures.push(new WeakRef(A)),A}async createVideoCapture(x,A){let F=new G(this,A);return await F.setDevice(x),this.videoCaptures.push(new WeakRef(F)),F}playbackSetDevice(x){return this.setPlaybackStrand.enqueue(async()=>{let A=x?.device.deviceId??"";A==="default"&&(A="");let F;if(this.playbackWorker===void 0){F=await this.audioContexts.acquire(48e3),this.playbackWorker=await S0(F),this.playbackWorker.setGlobalVolume(this.globalVolume);for(let[,r]of this.playbacks)r.id!==void 0&&this.playbackWorker.addMedias(r.id.connectionId,[r.id.mediaId],r.volume)}else F=this.playbackWorker.audioContext;F?.setSinkId!==void 0&&x&&F?.state==="running"&&await F.setSinkId(A)})}playbackSetGlobalVolume(x){this.globalVolume=x,this.playbackWorker?.setGlobalVolume(this.globalVolume)}playbackStart(x,A){let F=this.playbacks.get(x);F!==void 0&&(F.id!==void 0&&this.playbackStop(x,F.id),F.id=A,this.playbackWorker?.addMedias(A.connectionId,[A.mediaId],F.volume))}playbackStop(x,A){let F=this.playbacks.get(x);F!==void 0&&(F.id!==A&&c(`playback media ${A.mediaId} on connection ${A.connectionId} is out of sync`,F.id,A),F.id=void 0,this.playbackWorker?.removeMedias(A.connectionId,[A.mediaId]))}playbackGetActivity(x){let A=this.playbacks.get(x);return A?.id===void 0?$:this.playbackWorker?.getActivity(A.id)??$}playbackGetJitterStats(x){let A=this.playbacks.get(x);return A?.id===void 0?vx.JITTER_STATS_INITIAL:this.playbackWorker?.getJitterStats(A.id)??vx.JITTER_STATS_INITIAL}playbackSetVolume(x,A){let F=this.playbacks.get(x);F!==void 0&&(F.volume=A,F.id!==void 0&&this.playbackWorker?.setVolume(F.id,F.volume))}playbackGetVolume(x){return this.playbacks.get(x)?.volume??[1,1]}closePlayback(x){let A=this.playbacks.get(x);A!==void 0&&(A.id!==void 0&&this.playbackStop(x,A.id),this.playbacks.delete(x))}close(){this.playbackWorker?.close(),this.audioContexts.close()}async dump(){let x=[];for(let r of this.audioCaptures){let t=r.deref();t!==void 0&&x.push(await t.dump())}let A=[];for(let r of this.videoCaptures){let t=r.deref();t!==void 0&&A.push(await t.dump())}let F=[];for(let[r,t]of this.playbacks)F.push({uid:r,id:t.id||null,volume:t.volume});return{globalVolume:this.globalVolume,playbackWorker:await this.playbackWorker?.dump()||null,audioCaptures:x,videoCaptures:A,playbacks:F}}},g=class{constructor(x,A=!1){this.device=x;this.isDefault=A}get type(){switch(this.device.kind){case"audioinput":return"AudioCapture";case"audiooutput":return"AudioPlayback";default:(0,vx.assert)(!1,"not supported device")}}get id(){return this.device.deviceId}get name(){return this.device.name}};var ox=require("@4players/odin-common"),Y0=require("@msgpack/msgpack");b();var WD=require("@4players/odin-common");b();var W=require("@4players/odin-common"),z=require("@4players/odin-common/api");b();var V=require("@4players/odin-common"),xx=require("@4players/odin-common/api"),$x=require("@msgpack/msgpack");b();var R=class{constructor(x){this.stream=x;this._SendQueue=[];this._RecvQueue=[];this._EventQueue=[];this._Requests=new Map;this._Close=new AbortController;this._NextId=1;x instanceof WebSocket?(x.addEventListener("open",this._OnWebSocketOpen.bind(this)),x.addEventListener("close",this.close.bind(this)),x.addEventListener("message",A=>this._OnRpcMessage(A.data)),x.binaryType="arraybuffer"):(DF(x.readable.getReader(),this._OnRpcMessage.bind(this)).finally(this.close.bind(this)),this._Writer=x.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(x,A,F){if(this.closed)return Promise.resolve("closed");let r=this._NextId,t=F===void 0?void 0:setTimeout(()=>this._TimeoutRequest(r),F);return this._Send([0,r,x,A]),new Promise(j=>{this._Requests.set(r,{accept:j,timeoutId:t}),this._NextId+=1})}notify(x,A){this.closed||this._Send([2,x,A])}recv(){if(this.closed)return Promise.resolve("closed");let x=this._EventQueue.shift();return x!==void 0?Promise.resolve(x):new Promise(A=>this._RecvQueue.push(A))}close(){this._Close.abort()}_TimeoutRequest(x){let A=this._Requests.get(x);A!==void 0&&(this._Requests.delete(x),clearTimeout(A.timeoutId),A.accept("timeout"))}_Send(x){let A;x instanceof Uint8Array?A=x:A=new Uint8Array((0,$x.encode)(x,{ignoreUndefined:!0,forceFloat32:!0})),this.stream instanceof WebSocket?this.stream.send(A):this._Writer.write(A)}_OnWebSocketOpen(x){for(let A of this._SendQueue)this._Send(A);this._SendQueue.length=0}_OnRpcMessage(x){let A=rF(x);if(A.type!=="Success"){this.close();return}switch(A.value[0]){case 0:this._Send([1,A.value[1],"not supported",null]);break;case 1:this._OnResponse(A.value[1],A.value[2],A.value[3]);break;case 2:this._OnEvent(A.value[1],A.value[2]);break}}_OnResponse(x,A,F){let r=this._Requests.get(x);r!==void 0&&(clearTimeout(r.timeoutId),r.accept(A===null?(0,V.success)(F):(0,V.failure)(A)))}_OnEvent(x,A){let F=this._RecvQueue.shift();F!==void 0?F({name:x,properties:A}):this._EventQueue.push({name:x,properties:A})}_Cleanup(){for(let x of this._Requests.values())clearTimeout(x.timeoutId),x.accept("closed");this._Requests.clear();for(let x of this._RecvQueue)x("closed");this._RecvQueue.length=0,this._SendQueue.length=0,this.stream instanceof WebSocket?this.stream.close():this._Writer?.close().catch(()=>{})}},Ax=class{constructor(x,A,F){this.rpc=x;this._Commands=A;this._Events=F}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(x,A,F){A=(0,xx.parseRequest)(x,A,this._Commands);let r=await this.rpc.request(x,A,F);if(r==="closed"||r==="timeout"||r.type==="Failure")return r;let t=(0,xx.parseResponse)(x,r.value,this._Commands);return t!==void 0?(0,V.success)(t):(0,V.failure)("response schema failed validation")}notify(x,A){A=(0,xx.parseRequest)(x,A,this._Commands),this.rpc.notify(x,A)}async recv(){let x=await this.rpc.recv();if(x==="closed")return x;let A=e0(this._Events,x);return A!==void 0?A:(R0(this._Events,x.name)?(a(`schema validation for ${x.name} failed; closing connection`),this.rpc.close()):c(`dropping unknown event ${x.name}`),"closed")}close(){this.rpc.close()}};function rF(D){try{return(0,V.success)(xx.MessagePackRpcSchema.parse((0,$x.decode)(new Uint8Array(D))))}catch(x){return(0,V.failure)(String(x))}}function e0(D,x){if(!R0(D,x.name))return;let A=D[x.name].safeParse(x.properties);if(A.success)return{name:x.name,properties:A.data}}function R0(D,x){return x in D}async function DF(D,x){let A=new Uint8Array;for(;;){let F=d0(A,0);if(F===B){D.cancel("protocol violation");break}if(F!==q&&F<=A.length){x(A.subarray(0,F)),A=A.subarray(F);continue}let r;try{r=await D.read()}catch{break}if(r.done)break;A=tF(A,r.value)}A.length>0&&c("unprocessed bytes left in rpc stream",A)}function tF(D,x){if(D.length===0)return x;if(x.length===0)return D;let A=new Uint8Array(D.length+x.length);return A.set(D,0),A.set(x,D.length),A}var w=require("@4players/odin-common"),V0=require("@4players/odin-common/api");b();var I=class D{constructor(x,A){this.text=x;this.claims=A;if(A.ups!==void 0){let F=D.parse(A.ups);F.type==="Success"?this._Upstream=F.value:a(`upstream in token can not be parsed; ${F.reason}`)}}static parse(x){let A=x.split(".");if(A.length!==3)return(0,w.failure)("expected three segments");let F=(0,w.fromBase64Url)(A[1]);if(F.type==="Failure")return(0,w.failure)(`invalid token; ${F.reason}`);let r;try{r=JSON.parse(F.value)}catch(j){return(0,w.failure)(`invalid token; ${j}`)}let t=V0.TokenClaimsSchema.safeParse(r);return t.success===!1?(0,w.failure)(`invalid token; ${t.error}`):(0,w.success)(new D(x,t.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(x){return this.claims.aud===void 0&&x==="gateway"?!0:Array.isArray(this.claims.aud)?this.claims.aud.includes(x):this.claims.aud===x}toString(){return this.text}};var U=require("@4players/odin-common");b();function U0(D){typeof globalThis.rtcDataChannels>"u"&&(globalThis.rtcDataChannels=[]),Array.isArray(globalThis.rtcDataChannels)&&globalThis.rtcDataChannels.length<=100&&globalThis.rtcDataChannels.push(D)}function W0(D){let x=globalThis.rtcDataChannels?.indexOf(D);x!==void 0&&x>=0&&globalThis.rtcDataChannels.splice(x,1),D.readyState!=="closed"&&D.close()}function gx(D){typeof globalThis.rtcPeerConnections>"u"&&(globalThis.rtcPeerConnections=[]),Array.isArray(globalThis.rtcPeerConnections)&&globalThis.rtcPeerConnections.length<=100&&globalThis.rtcPeerConnections.push(D)}function z0(D){let x=globalThis.rtcPeerConnections?.indexOf(D);x!==void 0&&x>=0&&globalThis.rtcPeerConnections.splice(x,1),D.connectionState!=="closed"&&D.close()}var Cx=class{constructor(x,A){this._localVideos=new Map;this._remoteVideos=new Map;this._negotiation={requested:!1,running:!1,waitForAnswer:!1};this._WebRtcStatsSnapshot=null;this._peerConnection=x,this._signaling=A,this._peerConnection.ontrack=this._onTrack.bind(this),this._peerConnection.onconnectionstatechange=()=>this._onStatusChanged(),this._peerConnection.onicecandidate=async F=>{F.candidate?await this._signaling.sendIceCandidate(F.candidate):await this._signaling.sendIceComplete()},this._WebRtcStatsInterval=setInterval(()=>{this._snapshotStats()},C.WebRtcStatsSnapshotInterval)}requestNegotiation(x){this._negotiation.requested=!0,x&&(this._negotiation.waitForAnswer=!0),!this._negotiation.running&&(this._negotiation.running=!0,setTimeout(async()=>{let A=this._negotiation.waitForAnswer;this._negotiation.requested=!1,this._negotiation.waitForAnswer=!1;try{let F;A&&(F=new Promise(r=>{this._resolveOffer=r})),await this._sendOffer(),F&&await F}catch(F){a("negotiation failed during sdp offer/answer exchange",F)}finally{this._resolveOffer=void 0,this._negotiation.running=!1,this._negotiation.requested&&this.requestNegotiation(this._negotiation.waitForAnswer)}}))}async startLocalVideo(x,A,F){if(this._localVideos.has(x))return;E(`starting local video for media ${x}`);let r=this._peerConnection.getTransceivers().find(e=>e.sender.track===A);if(r)await r.sender.replaceTrack(A);else{let e=this._peerConnection.addTrack(A);r=this._peerConnection.getTransceivers().find(v=>v.sender===e),(0,U.assert)(r,"failed to create transceiver for local video")}if(F){let e=r.sender.getParameters(),{maxBitrate:v,maxFramerate:n,scaleResolutionDownBy:p}=F,H={...v!==void 0&&{maxBitrate:v},...n!==void 0&&{maxFramerate:n},...p!==void 0&&{scaleResolutionDownBy:p}};if(e.encodings.length===0)e.encodings.push(H);else for(let aA of e.encodings)Object.assign(aA,H);F.degradationPreference&&(e.degradationPreference=F.degradationPreference),await r.sender.setParameters(e)}let j=new U.VideoCodec(F?.codec??C.DefaultVideoCodec).isSupported();j&&r.setCodecPreferences([j]),this._localVideos.set(x,{transceiver:r}),this.requestNegotiation(!0)}stopLocalVideo(x){let A=this._localVideos.get(x);A&&(E(`stopping local video for media ${x}`),this._localVideos.delete(x),A.transceiver.sender.track&&(A.transceiver.sender.track.enabled=!1),A.transceiver.direction="inactive",this.requestNegotiation(!1))}startRemoteVideo(x,A){E(`starting remote video for media ${x}`);let F=this._peerConnection.addTransceiver("video"),t=new U.VideoCodec(A??C.DefaultVideoCodec).isSupported();t&&F.setCodecPreferences([t]);let j=new Promise((e,v)=>{this._remoteVideos.set(x,{state:"Requested",transceiver:F,promise:{resolve:e,reject:v}})});return this.requestNegotiation(!0),j}stopRemoteVideo(x){let A=this._remoteVideos.get(x);A&&(E(`stopping remote video for media ${x}`),this._remoteVideos.delete(x),A.state!=="Active"&&A.promise.reject(new Error("video stopped")),this.requestNegotiation(!1))}async handleWebRtcUpdate(x){switch(x.kind){case"Sdp":await this._updateRemoteSdp(x.type==="Answer"?"answer":"offer",x.sdp,x.media_map);break;case"Trickle":this._addIceCandidate({candidate:x.candidate,sdpMid:x.spd_mid??void 0,sdpMLineIndex:x.spd_mline_index??void 0,usernameFragment:x.username_fragment??void 0});break;case"TrickleFinished":this._addIceCandidate(void 0);break}}async startup(){if(this._peerConnection.connectionState==="new")try{let x=await this._peerConnection.createOffer();(0,U.assert)(x.type==="offer"&&x.sdp,"generated broken webrtc offer"),await this._peerConnection.setLocalDescription(x),await this._signaling.sendOffer(x.sdp,[])}catch{a("failed to create initial sdp offer")}}cleanup(){for(let[,x]of this._remoteVideos)x.state!=="Active"&&x.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 x=await this._peerConnection.getStats(),A={},F={bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,rtt:0};x.forEach(r=>{let{type:t,...j}=r;t!=="certificate"&&(t==="candidate-pair"&&r.nominated&&(F.bytesSent+=r.bytesSent??0,F.bytesReceived+=r.bytesReceived??0,F.packetsSent+=r.packetsSent??0,F.packetsReceived+=r.packetsReceived??0,F.rtt=r.currentRoundTripTime??0),A[t]||(A[t]=[]),A[t].push(j))}),this._WebRtcStatsSnapshot={timestamp:Date.now(),status:this._peerConnection.connectionState,stats:F,report:A}}catch{}}_addIceCandidate(x){x&&(x.sdpMid===void 0&&x.sdpMLineIndex===void 0&&(x={...x,sdpMid:"0"}),f(`adding new ice ${x.candidate}`,x)),this._peerConnection.addIceCandidate(x)}async _sendOffer(){try{let x=await this._peerConnection.createOffer();(0,U.assert)(x.type==="offer"&&x.sdp,"generated broken payload"),await this._peerConnection.setLocalDescription(x);let A=[];for(let[F,{transceiver:r}]of this._localVideos)r.mid&&A.push([F,r.mid]);for(let[F,r]of this._remoteVideos)r.state!=="Active"&&r.transceiver.mid&&A.push([F,r.transceiver.mid]);await this._signaling.sendOffer(x.sdp,A)}catch(x){throw a("failed to send sdp offer",x),x}}async _updateRemoteSdp(x,A,F){for(let[r,t]of F){let j=this._remoteVideos.get(r);j?.state==="Requested"&&(this._remoteVideos.set(r,{state:"Mapped",transceiver:j.transceiver,mid:t,promise:j.promise}),f(`updated remote video list with media ${r}`,j,this._remoteVideos))}await this._peerConnection.setRemoteDescription({type:x,sdp:A}),this._resolveOffer?.(!0)}async _onStatusChanged(){switch(f(`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":C.MainConnectionPingInterval!==void 0&&await this._signaling.checkConnection();default:this._WebRtcIceTimeout===void 0&&(this._WebRtcIceTimeout=setTimeout(()=>{f("ice connection timeout was reached"),this._peerConnection.restartIce(),this._WebRtcIceTimeout=void 0},C.WebRtcIceTimeout)),this._WebRtcTimeout===void 0&&(this._WebRtcTimeout=setTimeout(async()=>{f("peer connection timeout was reached"),await this._signaling.closeConnection()},C.WebRtcTimeout));break}}_onTrack(x){let A=Array.from(this._remoteVideos).find(([,t])=>t.state==="Mapped"&&t.mid===x.transceiver.mid);if(!A){c(`unexpected track with mid: ${x.transceiver.mid}`);return}let[F,r]=A;(0,U.assert)(r.state==="Mapped","expected video state to be Mapped"),this._remoteVideos.set(F,{state:"Active",transceiver:x.transceiver}),f(`updated local video list with media ${F}`,A,x.transceiver,this._localVideos),x.track.onended=()=>{f(`video track with mid ${x.transceiver.mid} ended`,A)},r.promise.resolve(x.track)}};var yx=class D{constructor(x,A,F,r,t,j){this.id=x;this.address=A;this.connection=r;this.rpc=t;this.closeController=j;this._ConnectionStats={...W.CONNECTION_STATS_INITIAL};this._WebRtcSessionFlight=new Q;this._PingFlight=new Q;this.status=0;this._ClosePromise=(async()=>{try{await this.connection.closed}catch{}return"closed"})(),C.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(C.HealthCheckTimeout)},C.MainConnectionPingInterval)),j.signal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this.datagramWriter=r.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,(e,v)=>{this._ConnectionStats.packetsReceived+=1,F(e,v)})}static async create(x,A,F,r){try{let t=new URL(`https://${A}?version=${h0}&uid=${ix}`),j=new AbortController;r.addEventListener("abort",()=>j.abort(),{once:!0});let e=new WebTransport(t);j.signal.addEventListener("abort",()=>{try{e.close()}catch{}},{once:!0}),await e.ready;let v=await e.createBidirectionalStream(),n=new Ax(new R(v),z.MainCommandsRpc,z.MainNotificationsRpc);return j.signal.addEventListener("abort",()=>n.close(),{once:!0}),n.notify("Hello",{stream:"main"}),(0,W.success)(new D(x,A,F,e,n,j))}catch(t){return(0,W.failure)(`connecting to ${A} failed with ${t}`)}}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(){E(`closing connection to '${this.address}' with id ${this.id}`),this.closeController.abort("request")}async joinRoom(x,A,F,r){try{if(this.closed)return"closed";let t=await this.connection.createBidirectionalStream().catch(()=>"closed");if(t==="closed")return"closed";let j=new Ax(new R(t),z.RoomCommandsRpc,z.RoomNotificationsRpc),e=await j.request("Hello",{stream:"room",token:String(x),room_id:A,user_data:F,position:r});return e==="closed"||e.type==="Failure"?e:(0,W.success)(j.rpc)}catch(t){return(0,W.failure)(`JoinRoom failed; ${t}`)}}async getReconnectToken(x){let A=await this._Request("RequestReconnectToken",{peer_id:x});return A.type==="Failure"?A:I.parse(A.value)}async healthCheck(){let x=await this._RequestPing(C.HealthCheckTimeout);return x||this.close(),x}async ping(x=3e4){let A=Date.now();return await this._RequestPing(x)?Date.now()-A:0}sendDatagram(x){try{this.datagramWriter.write(x),this._ConnectionStats.packetsSent+=1;let A=x.byteLength;this.connectionStats.bytesSent+=A}catch{}}async readDatagrams(x,A,F){try{let r=x.datagrams.readable.getReader();for(;;){let t=await r.read();if(t.done)break;let j=t.value.byteLength;this.connectionStats.bytesReceived+=j,F(A,t.value)}}catch{}}_CleanUp(){f(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId)}async _EnsureWebRtcSession(){return this._WebRtcSession?this._WebRtcSession:this._WebRtcSessionFlight.run(async()=>(this._PeerConnection=new RTCPeerConnection,gx(this._PeerConnection),this._WebRtcSession=new Cx(this._PeerConnection,{sendOffer:async(x,A)=>{await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:x,media_map:A})},sendIceCandidate:async x=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:x.candidate,spd_mid:x.sdpMid??void 0,spd_mline_index:x.sdpMLineIndex??void 0,username_fragment:x.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 x=await this.rpc.recv();if(x==="closed")break;x.name==="WebRtcUpdate"&&this._WebRtcSession?.handleWebRtcUpdate(x.properties)}this.close()}async _Request(x,A,F){let r=Date.now(),t=await(F===void 0?this.rpc.request(x,A):this.rpc.request(x,A,F)),j=(Date.now()-r)/1e3;return x!=="Ping"&&f(`sent main rpc '${x}'; took: ${j}s`,{properties:A,timeout:F,result:t}),t==="closed"?(0,W.failure)("connection lost"):t}_RequestPing(x=3e4){return this._PingFlight.run(async()=>{let A=await this._Request("Ping",{},x);return A!=="timeout"&&A.type==="Success"})}async startLocalVideo(x,A,F){await(await this._EnsureWebRtcSession()).startLocalVideo(x,A,F)}stopLocalVideo(x){this._WebRtcSession?.stopLocalVideo(x)}async startRemoteVideo(x,A){return(await this._EnsureWebRtcSession()).startRemoteVideo(x,A)}stopRemoteVideo(x){this._WebRtcSession?.stopRemoteVideo(x)}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}}}};var d=require("@4players/odin-common"),Lx=require("@4players/odin-common/api");b();var _=require("@4players/odin-common");b();async function B0(D,x){let A=performance.now(),F=(0,_.failure)("no connection was attempted");for(let r=0;r<C.ConnectInterval.length&&!x.aborted;r++){let t=A+eF(r);if(await(0,_.abortableSleep)(t-performance.now(),x)==="aborted")return(0,_.failure)("aborted");if(F=await jF(D,x),F.type==="Success")return F}return F}async function jF(D,x){let A;try{A=new WebSocket(D)}catch(v){return(0,_.failure)(`unable to create websocket; ${v}`)}let F=new AbortController,r=new Promise(v=>A.addEventListener("open",()=>v((0,_.success)(A)),{signal:F.signal})),t=new Promise(v=>A.addEventListener("close",n=>v((0,_.failure)(n.reason!==""?n.reason:"unable to establish websocket connection")),{signal:F.signal})),j=new Promise(v=>x.addEventListener("abort",()=>v((0,_.failure)("aborted")),{signal:F.signal})),e=await Promise.race([r,t,j]);return F.abort(),e}function eF(D){let x=C.ConnectInterval.slice(0,D).reduce((F,r)=>F+r,0),A=C.ConnectInterval[D]*Math.random();return x+A}var _x=class D{constructor(x,A,F,r,t,j){this.id=x;this.address=A;this.url=F;this.onDatagram=r;this.connection=t;this.webRtc=j;this._PeerIdMap=new WeakMap;this._ConnectionStats={...d.CONNECTION_STATS_INITIAL};this._PingFlight=new Q;E(`creating new webrtc connection to '${this.address}' with id ${this.id}`),this.closeSignal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this._ClosePromise=new Promise(e=>{this.closeSignal.addEventListener("abort",()=>{e("closed")},{once:!0})}),gx(j),this._AudioChannel=this.webRtc.createDataChannel("audio",{id:2,negotiated:!0,ordered:!1,maxRetransmits:0}),this._AudioChannel.binaryType="arraybuffer",this._AudioChannel.onmessage=e=>{this._ConnectionStats.packetsReceived++;let v=new Uint8Array(e.data);this._ConnectionStats.bytesReceived+=v.byteLength,this.onDatagram(this.id,v)},this._AudioChannel.onerror=e=>c(`webrtc audio data channel for connection with id ${x} raised an error`,e),this._AudioChannel.onclosing=e=>E(`webrtc audio data channel for connection with id ${x} begins shutting down`,e),this._AudioChannel.onclose=e=>E(`webrtc audio data channel for connection with id ${x} has closed`,e),U0(this._AudioChannel),this._WebRtcSession=new Cx(this.webRtc,{sendOffer:async(e,v)=>{await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:e,media_map:v})},sendIceCandidate:async e=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:e.candidate,spd_mid:e.sdpMid??void 0,spd_mline_index:e.sdpMLineIndex??void 0,username_fragment:e.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async()=>{this.close()},checkConnection:async()=>{this.healthCheck().then()}}),this._WebRtcSession.startup(),C.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(C.HealthCheckTimeout)},C.MainConnectionPingInterval)),this._HandleWebRtcUpdates()}static async create(x,A,F,r){if(r.aborted)return(0,d.failure)("aborted");let t;try{t=new URL(`wss://${A}`)}catch(n){return(0,d.fail)(`address in token(${A}) can not be parsed; ${n}`)}let j=(0,d.extendUrl)(t,`main?uid=${ix}`);if(j.type!=="Success")return j;let e=await B0(j.value,r);if(e.type!=="Success")return e;let v=new Ax(new R(e.value),Lx.MainCommandsRpc,Lx.MainNotificationsRpc);try{return(0,d.success)(new D(x,A,t,F,v,new RTCPeerConnection))}catch(n){return v.close(),(0,d.failure)(`unable to create webrtc connection; ${n}`)}}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((x,A)=>{let F=()=>{let r=this.status;r!==0&&(this.webRtc.removeEventListener("connectionstatechange",F),r===1?x():A(new Error("connection closed")))};this.webRtc.addEventListener("connectionstatechange",F),F(),this.closePromise.then(()=>{A(new Error("connection closed"))})})}close(){E(`closing ${this.transport} connection to '${this.address}' with id ${this.id}`),this.connection.close()}async joinRoom(x,A,F,r){let t=await this.connection.request("JoinRoom",{token:String(x),room_id:A,user_data:F,position:r});if(t==="closed"||t.type==="Failure")return t;let j=t.value;if(!("token"in j))return(0,d.failure)("JoinRoom responded without token");let e=(0,d.extendUrl)(this.url,`room?token=${j.token}`);if(e.type==="Failure")return e;let v=await B0(e.value,this.closeSignal);return v.type==="Success"?(this._PeerIdMap.set(v.value,j.peer_id),(0,d.success)(new R(v.value))):v}async getReconnectToken(x){let A=await this._Request("RequestReconnectToken",{peer_id:x});return A.type==="Failure"?A:I.parse(A.value)}async healthCheck(){let x=await this._RequestPing(C.HealthCheckTimeout);return x||this.close(),x}async ping(x=3e4){let A=Date.now();return await this._RequestPing(x)?Date.now()-A:0}sendDatagram(x){if(this._AudioChannel.readyState==="open"){let A=x.byteLength;this._AudioChannel.send(x),this._ConnectionStats.packetsSent+=1,this._ConnectionStats.bytesSent+=A}}_CleanUp(){f(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId),W0(this._AudioChannel),z0(this.webRtc),this._WebRtcSession.cleanup(),this.connection.close()}async _HandleWebRtcUpdates(){for(;;){let x=await this.connection.recv();if(x==="closed")break;x.name==="WebRtcUpdate"&&this._WebRtcSession.handleWebRtcUpdate(x.properties)}this.close()}async _Request(x,A,F){let r=Date.now(),t=await(F===void 0?this.connection.request(x,A):this.connection.request(x,A,F)),j=(Date.now()-r)/1e3;return x!=="Ping"&&f(`sent main rpc '${x}'; took: ${j}s`,{properties:A,timeout:F,result:t}),t==="closed"?(0,d.failure)("connection lost"):t}_RequestPing(x=3e4){return this._PingFlight.run(async()=>{let A=await this._Request("Ping",{},x);return A!=="timeout"&&A.type==="Success"})}async startLocalVideo(x,A,F){await this._WebRtcSession.startLocalVideo(x,A,F)}stopLocalVideo(x){this._WebRtcSession.stopLocalVideo(x)}async startRemoteVideo(x,A){return this._WebRtcSession.startRemoteVideo(x,A)}stopRemoteVideo(x){this._WebRtcSession.stopRemoteVideo(x)}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 Q0(D,x,A,F,r){switch(E(`creating ${x} main connection to '${A}'`),x){case"H3":return yx.create(D,A,F,r);case"WebRTC":return _x.create(D,A,F,r);default:throw new Error(`transport ${x} is not supported`)}}var bx=require("@4players/odin-common"),L=require("@4players/odin-common/api");b();var Hx=class{constructor(x,A,F,r){this.id=x;this.connection=A;this.cipher=F;this.mediaMap=r;this._DatagramReceived=0;this._DatagramSent=0;this._DatagramReceivedInvalid=0;this._DatagramSentInvalid=0;A.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(x,A,F,r){this.cipher.reset();let t=await this.cipher.encryptUserData(F);if(t===B)return(0,bx.failure)("unable to encrypt initial user-data");let j=await this.connection.joinRoom(x,A,t,r);return j==="closed"||j.type==="Failure"?j:(0,bx.success)(new v0(j.value,this.cipher,this))}getReconnectToken(x){return this.connection.getReconnectToken(x)}healthCheck(){return this.connection.healthCheck()}async sendDatagram(x){let A=await this.cipher.encryptDatagram(x);A!==B?(this._DatagramSent+=1,this.connection.sendDatagram(A)):this._DatagramSentInvalid+=1}async decryptDatagram(x,A){let F=await this.cipher.decryptDatagram(x,A);return F!==B?this._DatagramReceived+=1:this._DatagramReceivedInvalid+=1,F}startLocalVideo(x,A,F){return this.connection.startLocalVideo(x,A,F)}stopLocalVideo(x){return this.connection.stopLocalVideo(x)}startRemoteVideo(x,A){return this.connection.startRemoteVideo(x,A)}stopRemoteVideo(x){return this.connection.stopRemoteVideo(x)}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()}}},Nx=class{constructor(x){this.room=x}resendUserData(){this.room.roomConnection?.notify("UpdatePeer",{user_data:this.room.roomConnection.userData})}setUserData(x,A){let F={kind:"UserDataChanged",peer_id:x,user_data:A};this.room.onEvent("PeerUpdated",F)}},v0=class{constructor(x,A,F){this.rpc=x;this.cipher=A;this.connection=F;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(x,A,F){let r=await this.outgoing(x,A);return r===B?(0,bx.failure)("can not be encrypted"):await this.rpc.request(x,r,F)}async notify(x,A){let F=await this.outgoing(x,A);if(F!==B)return this.rpc.notify(x,F)}async recv(){for(;;){let x=await this.rpc.recv();if(x==="closed")return x;let A=await this.incoming(x.name,x.properties);if(A!==B)return{name:x.name,properties:A}}}close(){return this.rpc.close()}async outgoing(x,A){if(!(x in L.RoomCommandsRpc))return A;let F=(0,L.parseCommand)(x,A,L.RoomCommandsRpc);if(F===void 0)return B;switch(F.name){case"UpdatePeer":{let r=await this.cipher.encryptUserData(F.request.user_data);if(r===B)return B;F.request.user_data=r}break;case"SendMessage":{let r=await this.cipher.encryptMessage(F.request.message);if(r===B)return B;F.request.message=r}break}return F.request}async incoming(x,A){if(!(x in L.RoomNotificationsRpc))return A;let F=(0,L.parseNotification)(x,A,L.RoomNotificationsRpc);if(F===void 0)return B;switch(F.name){case"RoomUpdated":for(let r=0;r<F.properties.updates.length;r++){let t=await this.roomUpdate(F.properties.updates[r]);if(t===B)return B;F.properties.updates[r]=t}break;case"PeerUpdated":{let r=await this.peerUpdate(F.properties);if(r===B)return B;F.properties=r}break;case"MessageReceived":{let r=await this.cipher.decryptMessage(F.properties.sender_peer_id,F.properties.message);if(r===B)return B;F.properties.message=r}break}return F.properties}async peerUpdate(x){switch(x.kind){case"UserDataChanged":{let A=await this.cipher.decryptUserData(x.peer_id,x.user_data);if(A===B)return B;x.user_data=A}break;case"MediaStarted":this.mediaStarted(x.peer_id,x.media.id);break;case"MediaStopped":this.mediaStopped(x.peer_id,x.media_id);break}return x}async roomUpdate(x){switch(x.kind){case"Joined":for(let A of x.room.peers){for(let r of A.medias)this.mediaStarted(A.id,r.id);let F=await this.cipher.decryptUserData(A.id,A.user_data);F!==B?A.user_data=F:A.user_data=new Uint8Array}break;case"PeerJoined":{for(let F of x.peer.medias)this.mediaStarted(x.peer.id,F.id);let A=await this.cipher.decryptUserData(x.peer.id,x.peer.user_data);A!==B?x.peer.user_data=A:x.peer.user_data=new Uint8Array}break;case"PeerLeft":{let A=this.peers.get(x.peer_id);this.peers.delete(x.peer_id),this.cipher.deletePeerKey(x.peer_id);for(let F of A??[])this.mediaStopped(x.peer_id,F)}break}return x}mediaStarted(x,A){let F=this.peers.get(x);F===void 0&&(F=new Set,this.peers.set(x,F)),F.add(A);let r=k({connectionId:this.connection.connection.id,mediaId:A});this.connection.mediaMap.set(r,{peerId:x,connection:this.connection})}mediaStopped(x,A){this.peers.get(x)?.delete(A);let r=k({connectionId:this.connection.connection.id,mediaId:A});this.connection.mediaMap.delete(r)}cleanup(){for(let[x,A]of this.peers)for(let F of A)this.mediaStopped(x,F)}};var Kx=class{constructor(x){this.onDatagram=x;this._LastConnectionId=0;this._Connections=new Map;this._Close=new AbortController;this._MediaMap=new Map;let A=Date.now(),F=setInterval(()=>{Math.abs(Date.now()-A)>C.ClockJumpThreshold&&this.checkHealth(),A=Date.now()},C.ClockJumpCheckInterval);addEventListener("offline",()=>this.checkHealth(),{signal:this._Close.signal}),this._Close.signal.addEventListener("abort",()=>{clearInterval(F);for(let r of this._Connections.values())r.type==="establishing"?r.abort.abort():r.connection.close();this._Connections.clear()},{once:!0})}get closed(){return this._Close.signal.aborted}sendDatagram(x,A){let F=this._Connections.get(x);(F?.type==="established"||F?.type==="virtual")&&F.connection.sendDatagram(A)}async recvDatagram(x,A){let F=BF(A);if(F===void 0||F.length===0)return;let r=this._MediaMap.get(k({connectionId:x,mediaId:F[0]}));if(r===void 0)this.onDatagram(x,A);else{let t=await r.connection.decryptDatagram(r.peerId,A);if(t===B)return;this.onDatagram(r.connection.id,t)}}async acquireConnection(x,A,F,r){if(await(0,ox.nextTick)(),this.closed)return"closed";let t=this.findConnection(x,A),j;switch(t?.type){case"established":f(`reusing existing connection ${t.id}`),j=t;break;case"establishing":{f(`waiting for connecting to '${A}' finish`);let n=await t.finished;if(n.type!=="Success")return n;j=n.value}break;case void 0:{f(`connecting to '${A}'`);let n=await this.createConnection(x,A,r);if(n.type!=="Success")return n;j=n.value}break}let e=j.id,v=new C0(j.connection,()=>this.releaseConnection(e));return j.references+=1,F&&(v=new Hx(++this._LastConnectionId,v,F,this._MediaMap),this.addConnection({type:"virtual",id:v.id,connection:v,createdAt:Date.now()})),(0,ox.success)(v)}async createConnection(x,A,F){let r=++this._LastConnectionId,t=Date.now(),j=new AbortController;F.addEventListener("abort",()=>j.abort(),{once:!0}),f(`creating new connection ${r}`);let e=Q0(r,x,A,this.recvDatagram.bind(this),F),{promise:v,resolve:n}=Promise.withResolvers();this.addConnection({type:"establishing",id:r,address:A,transport:x,finished:v,createdAt:Date.now(),abort:j});let p=await e;if(this._Connections.delete(r),p.type!=="Success")return n(p),p;let H={type:"established",id:r,address:A,transport:x,createdAt:t,references:0,connection:p.value};return this.addConnection(H),(0,ox.success)(H)}addConnection(x){(x.type==="established"||x.type==="virtual")&&x.connection.closeSignal.addEventListener("abort",()=>{E(`connection ${x.id} has been closed`),this._Connections.delete(x.id)},{once:!0}),this._Connections.set(x.id,x)}releaseConnection(x){let A=this._Connections.get(x);A?.type==="established"&&(A.references-=1,A.references<=0&&A.connection.close())}checkHealth(){for(let x of this._Connections.values())x.type==="established"&&x.connection.healthCheck()}close(){this._Close.abort()}async dump(){let x=[];for(let F of this._Connections.values()){let r;switch(F.type){case"established":r={transport:F.transport,address:F.address,connection:await F.connection.dump(),references:F.references};break;case"establishing":r={transport:F.transport,address:F.address,aborted:F.abort.signal.aborted};break;case"virtual":r={connection:await F.connection.dump()};break}x.push({type:F.type,id:F.id,createdAt:F.createdAt,...r})}let A=[];for(let[F,r]of this._MediaMap)A.push(`${F} -> ${r.peerId} @${r.connection.id} `);return{lastConnectionId:this._LastConnectionId,connections:x,mediaMap:A,closed:this.closed}}findConnection(x,A){for(let F of this._Connections.values())if(F.type!=="virtual"&&F.transport===x&&F.address===A)return F}},C0=class{constructor(x,A){this.connection=x;this.release=A;this.closeController=new AbortController;this.closePromise=new Promise(x=>this.closeController.signal.addEventListener("abort",()=>x("closed"),{once:!0}));x.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(x,A,F,r){return this.connection.joinRoom(x,A,F,r)}getReconnectToken(x){return this.connection.getReconnectToken(x)}healthCheck(){return this.connection.healthCheck()}sendDatagram(x){return this.connection.sendDatagram(x)}startLocalVideo(x,A,F){return this.connection.startLocalVideo(x,A,F)}stopLocalVideo(x){return this.connection.stopLocalVideo(x)}startRemoteVideo(x,A){return this.connection.startRemoteVideo(x,A)}stopRemoteVideo(x){return this.connection.stopRemoteVideo(x)}async dump(){let x=await this.connection.dump();return typeof x=="object"&&(x={...x,isShared:!0,referenceClosed:this.closed}),x}};function BF(D){let x;try{x=(0,Y0.decode)(D)}catch{return}if(!Array.isArray(x)||x.length<2)return;let A=x[1];if(Array.isArray(A))return A.map(Number)}var wx=require("@4players/odin-common"),J=class{constructor(x,A){this.uid=x;this.customType=A}#x;#A;get mediaStream(){return this.#x}get audioPlayback(){return(0,wx.assert)(this.#A,"getting the audioPlayback failed, this video has no Audio"),this.#A}get volume(){return(0,wx.assert)(this.audioPlayback,"getting the volume failed, this video has no Audio"),this.audioPlayback.volume}setVolume(x){(0,wx.assert)(this.#A,"Can not set the volume, this video has no Audio"),this.#A.setVolume(x)}setMediaStream(x){this.mediaStream||(this.#x=x)}close(){this.#x?.getVideoTracks().forEach(x=>{x.stop(),this.#x?.removeTrack(x)}),this.#x=void 0}};var M=require("@4players/odin-common"),iA=require("@4players/odin-common/api");var i=require("@4players/odin-common"),P=require("@4players/odin-common/api");b();var Jx=class{constructor(x,A,F,r,t,j,e,v,n,p){this.connectionPool=x;this.transport=A;this.onEvent=F;this.gateway=r;this.roomId=j;this.cipher=n;this.disableAutoReconnect=p;this._Close=new AbortController;this._TokenUsed=!1;this._WasConnected=!1;this._FailedConnections=0;this._LastTokenRenew=performance.now();this._LastReconnectStartedAt=0;this._Closed=new Promise(x=>this._Close.signal.addEventListener("abort",()=>x(this._Close.signal.reason?"disconnected":"closed"),{once:!0}));this._Token=t,this._UserData=e,this._Position=v,this._Main().then(({reason:H})=>f(`_Main() resolved; ${H}`))}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(x,A){if(this._RoomConnection===void 0)return(0,i.failure)("currently not connected");let F=await this._RoomConnection.request(x,A,void 0);return(0,i.assert)(F!=="timeout","request should not timeout"),F!=="closed"&&F.type==="Success"&&this._HandleRequests(x,A,F.value),F}async request(x,A){let F=Date.now(),r=P.RoomCommandsRpc[x],t=await this.requestUnsafe(x,A),j=(Date.now()-F)/1e3;if(f(`sent room rpc '${x}'; took: ${j}s`,{properties:A,result:t}),t==="closed"||t.type==="Failure")return t;let e=(0,P.parseResponse)(x,t.value,P.RoomCommandsRpc);return e!==void 0?(0,i.success)(e):(0,i.failure)(`received invalid response from ${x}`)}notify(x,A){this._RoomConnection!==void 0&&this._RoomConnection.notify(x,A)}close(){this._Close.abort(!0)}get renewTokenIn(){let x=this._LastTokenRenew-performance.now()+C.MinTokenRefreshInterval,A=this._Token.timeLeft-C.MinTokenLifetime;return Math.max(x,A)}async _Main(){let x="unable to establish connection";for(let A=0;;this._FailedConnections++){if(await(0,i.sleep)(Math.max(A-performance.now(),0)),this._Close.signal.aborted||this.connectionPool.closed){x="user requested";break}if(A=performance.now()+1e3,this._TokenUsed=!0,this._Token.hasAudience("sfu")){let F=await this._ConnectToServer();if(F.type==="Success"&&F.value==="shutdown"){f("connection closed by user request; shutting down"),x="user requested";break}if(this.disableAutoReconnect&&this._WasConnected){x=F.type==="Failure"?F.reason:"connection lost";break}if(this._LastReconnectStartedAt===0&&(this._LastReconnectStartedAt=performance.now()),F.type==="Failure"&&!this._WasConnected&&this._FailedConnections>=3){x=F.reason;break}if(F.type==="Failure"&&!CF(this._LastReconnectStartedAt))continue}if(this.reset(),this._Close.signal.aborted||this.connectionPool.closed){x="user requested";break}if(this.gateway!==void 0&&this._Token.hasAudience("gateway")){this._ChangeStatus("Joining",`requesting new token from ${this.gateway}`);let F=await vF(this.gateway,this._Token,this._Close.signal);if(F.type==="Success")if(F.value instanceof I)A=0,this._Token=F.value,this._TokenUsed=!1;else{x=`gateway error; ${F.value}`;break}else if(!this._WasConnected&&this._FailedConnections>=3){x="unable to contact the gateway";break}}if(this._TokenUsed&&this._Token.timeLeft<=0){x="token has expired";break}if(this._Close.signal.aborted||this.connectionPool.closed){x="user requested";break}}return this._ChangeStatus("Closed",x),this.close(),(0,i.failure)(x)}async _ConnectToServer(){let x=this._Token;for(;x.upstream!==void 0;)x=x.upstream;let A=x.claims.adr??this.gateway?.toString();if(!A)return(0,i.success)("continue");if(this._ChangeStatus("Joining",`connecting to ${x.claims.adr}`),this._MainConnection===void 0||this._MainConnection.closed||this._MainConnection.address!==x.claims.adr){this._MainConnection?.close();let t=await this.connectionPool.acquireConnection(this.transport,A,this.cipher,this._Close.signal);if(t==="closed")return(0,i.failure)("connection pool closed");if(t.type==="Failure")return this._ChangeStatus("Joining",`connection failed; ${t.reason}`),(0,i.failure)(`connection failed; ${t.reason}`);this._MainConnection=t.value,this._OwnPeerId=void 0}let F=await Promise.race([Promise.all([this._MainConnection.joinRoom(x,this.roomId,this.userData,this.position)]),(0,i.sleep)(C.ConnectTimeout,"timeout"),this._Closed]);if(F==="closed"||F==="disconnected")return(0,i.success)("continue");if(F==="timeout")return this._ChangeStatus("Joining","timed out"),(0,i.success)("continue");let[r]=F;if(r==="closed")return(0,i.success)("continue");if(r.type==="Failure")return(0,i.failure)(`unable to join room; ${r.reason}`);this._RoomConnection=r.value,this._WasConnected=!0,this._FailedConnections=0,this._ChangeStatus("Joined",`joined ${this.roomId}`);try{await this._MainConnection.waitForConnected();let t=await this._HandleConnection(this._MainConnection);return(0,i.success)(t?"shutdown":"continue")}catch(t){return(0,i.failure)(`unable to handle connection; ${t}`)}}_ChangeStatus(x,A){let F={status:x,message:A};this.onEvent("RoomStatusChanged",F)}async _HandleConnection(x){if(this._RoomConnection===void 0)return!1;let A=new i.Selector([()=>(0,i.sleep)(this.renewTokenIn,"renewToken"),()=>(0,i.sleep)(500,"tick"),async()=>await this._RoomConnection?.recv(),()=>this._Closed,()=>x.closePromise]);for(;;){let F=await A.next();switch(F){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(F);break}}}_HandleEvent(x){if(x.name==="RoomUpdated"){let A=P.RoomNotificationsRpc.RoomUpdated.safeParse(x.properties);if(!A.success)return;for(let F of A.data.updates)F.kind==="Joined"&&(this._OwnPeerId=F.own_peer_id)}this.onEvent(x.name,x.properties)}_HandleRequests(x,A,F){switch(x){case"SetPeerPosition":{let r=P.RoomCommandsRpc.SetPeerPosition.request.safeParse(A);if(r.success){let t=r.data.position;this._Position=t.length===2?[t[0],t[1],0]:t}else c("unable to process SetPeerPosition command");break}case"UpdatePeer":{let r=P.RoomCommandsRpc.UpdatePeer.request.safeParse(A);r.success?this._UserData=r.data.user_data:c("unable to process UpdatePeer command");break}}}async _RenewToken(x){if(this._LastTokenRenew=performance.now(),!x&&this.token.timeLeft>C.MinTokenLifetime)return;if(this._MainConnection===void 0||this._OwnPeerId===void 0)return(0,i.failure)("connection is not established");let A=await this._MainConnection.getReconnectToken(this._OwnPeerId);return A.type==="Success"?(this._Token=A.value,(0,i.success)()):(0,i.failure)(`${this._MainConnection.address} rejected reconnect token request; ${A.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 vF(D,x,A){try{let F={jsonrpc:"2.0",id:1,method:"Connect",params:{}};E(`sending authentication request to '${D}'`,F);let t=await(await fetch(D,{body:JSON.stringify(F),method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${x}`},signal:A})).json();if(E(`received authentication response fom '${D}'`,t),"result"in t)return I.parse(t.result.token);{let j=t.error?.message??"malformed response";return a(`gateway rejected token; ${j}`),(0,i.success)(j)}}catch(F){return(0,i.failure)(String(F))}}function CF(D,x=8e3){return performance.now()-D>x}b();var nA=require("@4players/odin-common");var X=require("@4players/odin-common");b();var BA=require("@4players/odin-common");b();var jA=require("@msgpack/msgpack");b();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=D=>({name:"PBKDF2",hash:"SHA-256",iterations:600,salt:D}),AA=32,FA=1e6,rA=2147483648,DA=32,O=[79,68,73,78,1,75,105,109],Ex=16,fx=64,tA=16;function eA(D,x){if(D.length!==x.length)return!1;for(let A=0;A<D.length;A++)if(D[A]!==x[A])return!1;return!0}function EF(D){return isFinite(D)}function fF(D){return Array.isArray(D)}function Px(D){return EF(D)?D:B}function ax(D){return D instanceof Uint8Array?D:B}function nF(D,...x){let A;try{A=(0,jA.decode)(D)}catch{return B}if(!fF(A))return B;let F=new Array(A.length);for(let r in x)if(F[r]=x[r](A[r]),F[r]===B)return B;return F}function Ox(D,...x){if(D.length<O.length)return h;for(let A=0;A<O.length;A++)if(D[A]!==O[A])return h;return nF(D.subarray(O.length),...x)}var nx=class{constructor(x){this.first=1;this.offset=0;this.window=Array(x)}isReplay(x){let A=x-this.first;if(A<0)return!0;if(A>=this.window.length)if(A<this.window.length*2){let t=A-this.window.length+1;A-=t;for(let j=0;j<t;j++)this.advance()}else return this.first=x+1-self.window.length,this.offset=0,this.window.fill(!1),!1;let F=(this.offset+A)%this.window.length,r=this.window[F]===!0;for(this.window[F]=!0;this.window[this.offset]===!0;)this.advance();return r}advance(){this.window[this.offset]=!1,this.first+=1,this.offset=(this.offset+1)%this.window.length}};var Mx=class D{constructor(x){this.key=x}static async create(x){typeof x=="string"&&(x=new TextEncoder().encode(x));let A=await globalThis.crypto.subtle.importKey("raw",x,"PBKDF2",!1,["deriveBits"]),F=await globalThis.crypto.subtle.deriveBits(Z0,A,256),r=await globalThis.crypto.subtle.importKey("raw",F,"PBKDF2",!1,["deriveKey"]);return new D(r)}async generatePeerKey(x,A){return await globalThis.crypto.subtle.deriveKey(xA(x),this.key,{name:"AES-GCM",length:256},!1,[A])}},Tx=class D{constructor(x,A){this.seed=x;this.key=A;this.sequenceNumbers={datagram:1,message:1,userData:1};this.number_of_packets=0;this.number_of_bytes=0}static async create(x){let A=globalThis.crypto.getRandomValues(new Uint8Array(AA)),F=await x.generatePeerKey(A,"encrypt");return new D(A,F)}get limitReached(){return this.key===void 0?!1:this.number_of_bytes>=rA||this.number_of_packets>=FA}nextSequenceNumber(x){return this.sequenceNumbers[x]++}};function E0(D,x){return{kind:"encrypted",key:D,material:x,antiReplays:{datagram:new nx(DA),userData:new nx(0),message:new nx(0)}}}var Sx=class D{constructor(x,A,F,r){this.additionalData=x;this.sequenceNumber=A;this.seed=F;this.encrypted=r}static parse(x){let A=Ox(x,ax,Px,ax);if(A===B||A===h)return A;let[F,r,t]=A,j=x.subarray(0,x.length-t.length);return new D(j,r,F,t)}isSameSeed(x){return eA(this.seed,x.seed)}async generateKey(x){return await x.generatePeerKey(this.seed,"decrypt")}};function Rx(D,x){let A=new Uint8Array(12);switch(A[0]=x&255,A[1]=x>>8&255,A[2]=x>>16&255,A[3]=x>>24&255,D){case"datagram":A[5]=1;break;case"userData":A[5]=2;break;case"message":A[5]=3;break;default:(0,BA.assert)(!1,"missing content implementation")}return A}var f0=require("@msgpack/msgpack"),CA=require("@4players/odin-common");b();var Vx=class{constructor(x){this.actions=x}changeKey(x){this.masterKey!==x&&(this.masterKey=x,this.ownKey=B,this.actions.resendUserData())}async encryptDatagram(x){let A=await this.getKey("datagram");return A===void 0?x:A===T?B:await bF(A,x)}async encryptMessage(x){let A=await this.getKey("message");return A===void 0?x:A===T?T:await vA(A,x,"message")}async encryptUserData(x){let A=await this.getKey("userData");return A===void 0?x:((0,CA.assert)(A!==T,"key unavailable for user data encryption"),await vA(A,x,"userData",A.seed))}async getKey(x){if(this.ownKey===B||this.ownKey?.limitReached)if(x==="userData")this.ownKey=this.masterKey?await Tx.create(this.masterKey):void 0;else return this.ownKey!==B&&(this.ownKey=B,this.actions.resendUserData()),T;return this.ownKey}reset(){this.ownKey=this.masterKey?B:void 0}};async function vA(D,x,A,...F){let r=D.nextSequenceNumber(A),t=x.length+Ex,j=iF(r,F,t),e=j.length-t,v=await EA(D,A,r,j.subarray(0,e),x);return j.set(new Uint8Array(v),e),j}function iF(D,x,A){let F=[];x.forEach(j=>F.push(j)),F.push(D),F.push(new Uint8Array(A));let r=(0,f0.encode)(F),t=new Uint8Array(O.length+r.length);return t.set(O,0),t.set(r,O.length),t}async function bF(D,x){let A=oF(x);if(A===B)return B;if((A.kind&fx)!==0)return B;let F=A.body.length+Ex,r=D.nextSequenceNumber("datagram"),t=(0,f0.encode)([A.kind|fx,A.mediaIds,r,new Uint8Array(F)]),j=t.length-F,e=await EA(D,"datagram",r,t.subarray(0,j),A.body);return t.set(e,j),t}async function EA(D,x,A,F,r){return new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:Rx(x,A),additionalData:F,tagLength:Ex*8},D.key,r))}function oF(D){let x=new S(D),A=x.readArrayLength();if(s(A)||A<2)return B;let F=x.readNumber(),r=x.readArrayLength();if(s(F)||s(r))return B;if(r>tA)return B;let t=Array(r);for(let e=0;e<t.length;e++){let v=x.readNumber();if(s(v))return B;t[e]=v}let j=D.subarray(x.position);return{kind:F,mediaIds:t,body:j}}var fA=require("@msgpack/msgpack");b();var Wx=class{constructor(x){this.actions=x;this.peerKeys=new Map}async changeKey(x){this.masterKey=x;for(let[A,{kind:F,material:r}]of this.peerKeys)if(x!==void 0){let t=await r.generateKey(x),j=E0(t,r),e=await Ux(j,"userData",r.additionalData,r.sequenceNumber,r.encrypted);e!==B?(this.peerKeys.set(A,j),this.actions.setUserData(A,e)):(this.peerKeys.set(A,{kind:"broken",material:r}),this.actions.setUserData(A,new Uint8Array))}else F==="encrypted"&&this.peerKeys.set(A,{kind:"broken",material:r})}async decryptDatagram(x,A){let F=aF(A);if(this.masterKey===void 0)return F===h?A:B;if(F===B||F===h)return B;let r=this.peerKeys.get(x);if(r?.kind!=="encrypted")return B;let t=await Ux(r,"datagram",F.additionalData,F.sequenceNumber,F.encrypted);return t===B?B:lF(F.kind&~fx,F.mediaIds,t)}async decryptMessage(x,A){let F=Ox(A,Px,ax);if(this.masterKey===void 0)return F===h?A:B;if(F===B||F===h)return B;let r=this.peerKeys.get(x);if(r?.kind!=="encrypted")return B;let[t,j]=F,e=A.subarray(0,A.length-j.length);return Ux(r,"message",e,t,j)}async decryptUserData(x,A){let F=Sx.parse(A);if(F===B)return B;if(F===h)return this.peerKeys.delete(x),this.masterKey===void 0?A:B;if(this.masterKey===void 0)return this.peerKeys.set(x,{kind:"broken",material:F}),B;let r=this.peerKeys.get(x);if(r?.kind==="encrypted"&&r.material.isSameSeed(F))r.material=F;else{let j=await F.generateKey(this.masterKey);r=E0(j,F)}let t=await Ux(r,"userData",F.additionalData,F.sequenceNumber,F.encrypted);return t===B?this.peerKeys.set(x,{kind:"broken",material:F}):r!==void 0&&this.peerKeys.set(x,r),t}reset(){this.peerKeys.clear()}};function aF(D){let x=new S(D),A=x.readArrayLength();if(s(A)||A<1)return B;let F=x.readNumber();if(s(F))return B;if((F&fx)===0)return h;if(A!==4)return B;let r=x.position;x.readObjects(1);let t=D.subarray(r,x.position),j=x.readNumber(),e=x.readBytes();if(s(j)||s(e))return B;let v=D.subarray(0,D.length-e.length);return{kind:F,mediaIds:t,additionalData:v,sequenceNumber:j,encrypted:e}}async function Ux(D,x,A,F,r){let t=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:Rx(x,F),additionalData:A,tagLength:Ex*8},D.key,r).catch(()=>B);return t===B?B:D.antiReplays[x].isReplay(F)?B:new Uint8Array(t)}function lF(D,x,A){let F=2;try{let j=new S(A);for(j.position=0;j.position<A.length;)j.readObjects(1),F+=1}catch{return B}let r=(0,fA.encode)(D),t=new Uint8Array(3+r.length+x.length+A.length);return t[0]=220,t[1]=F>>8&255,t[2]=F&255,t.set(r,3),t.set(x,3+r.length),t.set(A,3+r.length+x.length),t}var zx=class{constructor(x,A){this.active=!1;let F=new Wx(A),r=new Vx(A);this.crypto=new X.Strand({encryption:r,decryption:F}),this.peerKeys=F.peerKeys,this.configure(x)}encryptUserData(x){return this.crypto.enqueue(({encryption:A})=>A.encryptUserData(x))}async encryptMessage(x){let A;do A=await this.crypto.enqueue(({encryption:F})=>F.encryptMessage(x));while(A===T);return A}async encryptDatagram(x){return await this.crypto.enqueue(({encryption:A})=>A.encryptDatagram(x))}decryptUserData(x,A){return this.crypto.enqueue(({decryption:F})=>F.decryptUserData(x,A))}decryptMessage(x,A){return this.crypto.enqueue(({decryption:F})=>F.decryptMessage(x,A))}decryptDatagram(x,A){return this.crypto.enqueue(({decryption:F})=>F.decryptDatagram(x,A))}configure(x){return this.crypto.enqueue(async A=>{let F=x.password?await Mx.create(x.password):void 0;this.active=F!==void 0,await A.encryption.changeKey(F),await A.decryption.changeKey(F)})}getPeerStatus(x){switch(this.peerKeys.get(x)?.kind??"unencrypted"){case"broken":return X.Backend.PeerCipherStatus.InvalidPassword;case"encrypted":return X.Backend.PeerCipherStatus.Encrypted;case"unencrypted":return this.active?X.Backend.PeerCipherStatus.InvalidPassword:X.Backend.PeerCipherStatus.Unencrypted;default:return X.Backend.PeerCipherStatus.Unknown}}deletePeerKey(x){this.peerKeys.delete(x)}reset(){return this.crypto.enqueue(async({encryption:x,decryption:A})=>{x.reset(),A.reset()})}async dump(){return this.crypto.enqueue(async()=>({active:this.active,peers:Array.from(this.peerKeys).map(([x,A])=>`${x} => ${A.kind}`)}))}};function sA(D,x){return(0,nA.assert)(D.type==="OdinCrypto","only OdinCrypto supported"),new zx(D,x)}var Xx=class{constructor(x,A,F){this._Captures=new Map;this._Playbacks=new Map;this._Peers=new Map;this._AvailableMediaIds=[];let{url:r,onEvent:t}=A,j=(0,M.unwrap)(I.parse(A.token)),e=A.roomId??j.defaultRoomId,v=A.userData??new Uint8Array(0),n=A.position??[0,0,0];(0,M.assert)(e!==void 0,"room id required for multi-room-tokens"),this.cipher=A.cipher?sA(A.cipher,new Nx(this)):void 0,this.onEvent=t,E(`creating new room '${e}' ${this.cipher?"with":"without"} cipher`,j,v,n),this._Connection=new Jx(x,A.transport??"H3",this._HandleEvent.bind(this),r?new URL(r):void 0,j,e,v,n,this.cipher,F?.disableAutoReconnect??!1)}get connectionStats(){let x={...M.CONNECTION_STATS_INITIAL};return this.mainConnection?this.mainConnection.connectionStats:x}get roomConnection(){return this._Connection}get mainConnection(){return this.roomConnection?.mainConnection}get token(){return this._Connection.token.text}request(x,A){return this._Connection.requestUnsafe(x,A)}async link(x){if(x instanceof y){let A=this._Playbacks.get(x.uid)??{media:void 0,playback:void 0};A.playback!==void 0&&this.unlink(A.playback),A.media!==void 0&&x.start(A.media),A.playback=x,E(`linking audio playback media '${x.uid}' with volume ${x.volume} to room '${this._Connection.roomId}'`),this._Playbacks.set(x.uid,A)}else if(x instanceof K){let A=this._Captures.get(x);A&&this.unlink(x);let F=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();A={media:F?{connectionId:this.mainConnection.id,mediaId:F}:void 0},E(`linking audio capture media '${x.uid}' with volume ${x.volume} to room '${this._Connection.roomId}'`),this._Captures.set(x,A),A.media!==void 0&&await x.start(this._Connection,A.media)}else if(x instanceof J){let A=this._Playbacks.get(x.uid)??{media:void 0,playback:void 0};if(A.playback!==void 0&&this.unlink(A.playback),A.media!==void 0){let F=await this.mainConnection?.startRemoteVideo(A.media.mediaId);F&&x.setMediaStream(new MediaStream([F]))}A.playback=x,E(`linking video playback media '${x.uid}' with type '${x.customType}' to room '${this._Connection.roomId}'`),this._Playbacks.set(x.uid,A)}else if(x instanceof G){let A=this._Captures.get(x);A&&this.unlink(x);let F=x.mediaStream?.getVideoTracks()[0];if(F){let r=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();A={media:r?{connectionId:this.mainConnection.id,mediaId:r}:void 0},E(`linking video capture media '${x.uid}' with type '${x.parameters?.customType}' to room '${this._Connection.roomId}'`),this._Captures.set(x,A),A.media!==void 0&&(await x.start(this._Connection,A.media),this.mainConnection?.startLocalVideo(A.media.mediaId,F,x.parameters)),x.audioCapture&&await this.link(x.audioCapture)}}else throw new Error("Linking failed, media was not supported")}unlink(x){if(x instanceof y||x instanceof J){let A=this._Playbacks.get(x.uid);if(A?.playback!==x)return;A.playback=void 0,A.media!==void 0&&(x instanceof y?x.stop(A.media):(this.mainConnection?.stopRemoteVideo(A.media.mediaId),x.setMediaStream(void 0))),E(`unlinking playback media '${x.uid}' from room '${this._Connection.roomId}'`),this._Playbacks.set(x.uid,A)}else if(x instanceof K||x instanceof G){x instanceof G&&x.audioCapture&&this.unlink(x.audioCapture);let A=this._Captures.get(x);if(A===void 0)return;A.media!==void 0&&(x.stop(this._Connection,A.media),this._AvailableMediaIds.push(A.media.mediaId),x instanceof G&&this.mainConnection?.stopLocalVideo(A.media.mediaId)),E(`unlinking capture media '${x.uid}' from room '${this._Connection.roomId}'`),this._Captures.delete(x)}else throw new Error("invalid media")}close(){E(`closing room '${this._Connection.roomId}'`),this._Connection.close()}_HandleEvent(x,A){let F=e0(iA.RoomNotificationsRpc,{name:x,properties:A});F!==void 0&&(this._HandleKnownEvent(F),A=F.properties),this.onEvent(x,A)}_HandleKnownEvent(x){switch(f(`processing event '${x.name}'`,x.properties),x.name){case"RoomStatusChanged":x.properties.status!=="Joined"&&this._HandleConnectionLost();break;case"RoomUpdated":for(let A of x.properties.updates)this._HandleRoomUpdate(A);break;case"PeerUpdated":this._HandlePeerUpdate(x.properties);break}}_HandleConnectionLost(){for(let x of this._Peers.keys())this._HandlePeerLeft(x);for(let[x,A]of this._Captures)A.media!==void 0&&(x instanceof G,x instanceof K&&(x.stop(this._Connection,A.media),A.media=void 0));this._AvailableMediaIds.length=0}_HandleRoomUpdate(x){if(x.kind==="Joined"){(0,M.assert)(this._AvailableMediaIds.length===0,"left over media ids"),this._AvailableMediaIds.push(...x.media_ids),this._HandleRoomJoined();for(let A of x.room.peers)this._HandlePeerJoined(A)}else x.kind==="PeerJoined"?this._HandlePeerJoined(x.peer):x.kind==="PeerLeft"&&this._HandlePeerLeft(x.peer_id)}_HandleRoomJoined(){for(let[x,A]of this._Captures)this._AvailableMediaIds.length===0||this.mainConnection===void 0||(A.media={connectionId:this.mainConnection.id,mediaId:this._AvailableMediaIds.shift()},x instanceof K&&x.start(this._Connection,A.media),x instanceof G)}_HandlePeerUpdate(x){x.kind==="MediaStarted"?this._HandleMediaStart(x.peer_id,x.media):x.kind==="MediaStopped"&&this._HandleMediaStopped(x.peer_id,x.media_id)}_HandlePeerJoined(x){this._Peers.has(x.id)||this._Peers.set(x.id,{mediaIds:new Map});for(let A of x.medias)this._HandleMediaStart(x.id,A)}_HandlePeerLeft(x){let A=this._Peers.get(x);if(A!==void 0){for(let F of A.mediaIds.keys())this._HandleMediaStopped(x,F);this._Peers.delete(x)}}_HandleMediaStart(x,A){if(this.mainConnection===void 0)return;let F=this._Peers.get(x);if(F===void 0||A.properties.kind!=="audio"&&A.properties.kind!=="video")return;let r=String(A.properties.uid??(0,M.generateUUID)());A.properties.uid=r;let t=this._Playbacks.get(r)??{media:void 0,playback:void 0};this._Playbacks.set(r,t),F.mediaIds.set(A.id,r),t.media={connectionId:this.mainConnection.id,mediaId:A.id},t.playback!==void 0&&(t.playback instanceof y&&t.playback.start(t.media),t.playback instanceof J&&this.mainConnection.startRemoteVideo(t.media.mediaId).then())}_HandleMediaStopped(x,A){let F=this._Peers.get(x);if(F===void 0)return;let r=F?.mediaIds.get(A);if(r===void 0)return;let t=this._Playbacks.get(r);t!==void 0&&(t.media!==void 0&&t.playback!==void 0&&(t.playback instanceof y&&t.playback.stop(t.media),t.playback instanceof J&&this.mainConnection?.stopRemoteVideo(t.media.mediaId)),t.media=void 0,F.mediaIds.delete(A))}};px();function kF(D,x){m0(x?.logger,x?.onLogMessage);let A,F=new Kx((t,j)=>A.receivePacket(t,j)),r=new Gx(D);return A=new Ix(r,F.sendDatagram.bind(F)),new n0(F,A,x)}var ix=(0,uF.generateUUID)(),s0=[],bA=!1;function cF(){bA||typeof window>"u"||(window.addEventListener("beforeunload",()=>{for(let D of s0)D.deref()?.close()}),bA=!0)}var n0=class{constructor(x,A,F){this.version="9";this.supportedTransports=["H3","WebRTC"];this._PlaybackVolume=[1,1];this._CreatedAt=Date.now();this._Options=F??{},this._Options.disableBeforeUnload||cF(),this._ConnectionPool=x,this._MediaController=A,s0.push(new WeakRef(this)),E("plugin initialized")}get playbackVolume(){return this._PlaybackVolume}joinRoom(x){return new Xx(this._ConnectionPool,x,this._Options)}async createAudioPlayback(x){return this._MediaController.createAudioPlayback(x)}async createAudioCapture(x){return this._MediaController.createAudioCapture(x)}async createVideoCapture(x,A){return this._MediaController.createVideoCapture(x,A)}async createVideoPlayback(x){return new J(x.uid,x.customType)}enumerateDevices(){return dx()}setOutputVolume(x){this._MediaController.playbackSetGlobalVolume(x)}async setOutputDevice(x){await this._MediaController.playbackSetDevice(x.device)}close(){this._MediaController.close(),this._ConnectionPool.close(),E("plugin closed")}async dump(){return{createdAt:this._CreatedAt,connections:await this._ConnectionPool.dump(),medias:await this._MediaController.dump()}}};async function oA(){let D=[];for(let x of s0){let A=x.deref();A!==void 0&&D.push(await A.dump())}return JSON.stringify({timestamp:Date.now(),instances:D,background:await g0()})}globalThis.odin_debug_dump_state=oA;window!==void 0&&(window.odin_debug_dump_state=oA);0&&(module.exports={SESSION_ID,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(3,"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.name}\`:"";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 0: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 j0,w0=u(()=>{j0='"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(3,"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],o=e.logger.name!==void 0?`@${e.logger.name}`:"";return`${p(r())}${o} ${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(){}},ae=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 0: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 a=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 a(3,void 0,[new ae]),oe=a.prototype.log.bind(l,1),ie=a.prototype.log.bind(l,2),ce=a.prototype.log.bind(l,3),ue=a.prototype.log.bind(l,4),Ue=a.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 o=this.state.fill(0,r[0][0]);return this.state.offset===this.state.length&&(this.state.flush(),this.state.fill(o,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 o=this.state.fill(0,n[0][0],n[0][1]);return o<u.RenderQuantumSize&&(this.totalBlocks+=1,this.state.next(),this.state.hasVoice?this.voiceBlocks+=1:this.silenceBlocks+=1,this.state.fill(o,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 P0={};lx(P0,{UnsharedCaptureWorker:()=>hx,UnsharedPlaybackWorker:()=>qx,createCaptureWorker:()=>AF,createPlaybackWorker:()=>FF});function AF(D,x,A,F,r=C.DefaultRefreshRate){return xF.enqueue(async()=>{let[t,j]=await ex(t0,j0,D,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return console.warn("SharedArrayBuffer is not available; creating ODIN CaptureWorker in fallback mode"),hx.create(D,x,A,r,t,j,F)})}async function FF(D,x=C.DefaultRefreshRate){if(D.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[A,F]=await ex(t0,j0,D,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return qx.create(D,x,A,F)}var J0,xF,hx,qx,O0=u(()=>{"use strict";J0=require("@4players/odin-common");b();px();K0();w0();xF=new J0.Strand;hx=class D extends tx{constructor(A,F,r,t,j){super(A,F,r,t,j);this._Activity=$;this._SpeechProbability=0;F.addEventListener("message",this._OnMessages.bind(this))}static async create(A,F,r,t,j,e,v){let{port1:n,port2:p}=new MessageChannel;return o(j,["captureInit",{sampleRate:A.sampleRate,refreshRate:t,workletPort:n}],[n]),await Fx(j,"captureReady"),o(e.port,["init",{workerPort:p}],[p]),new D(e,j,F,r,v)}get activity(){return this._Activity}get speechProbability(){return this._SpeechProbability}setVolume(A){o(this.worker,["captureSetVolume",{value:A}])}_OnMessages(A){super._OnMessages(A);let[F,r]=A.data;F==="captureUpdate"&&(this._Activity={isSilent:!r.active,rmsDBFS:r.rmsDBFs},this._SpeechProbability=r.speechProbability)}},qx=class D extends Dx{constructor(A,F,r){super(A,F,r);this.activities=new Float32Array;this.jitterStats=[]}static async create(A,F,r,t){let{port1:j,port2:e}=new MessageChannel;return o(r,["playbackInit",{workletPort:j,refreshRate:F}],[j]),await Fx(r,"playbackReady"),o(t.port,["init",{workerPort:e}],[e]),t.connect(A.destination),new D(A,t,r)}getActivity(A){let F=this.medias.get(k(A));if(F===void 0)return;let r=this.activities.at(F.index);if(r!==void 0)return r===0?$:{isSilent:!1,rmsDBFS:r}}getJitterStats(A){let F=this.medias.get(k(A));if(F===void 0)return;let r=this.jitterStats.at(F.index);if(r!==void 0)return r}setGlobalVolume(A){o(this.worker,["playbackSetVolume",{index:"global",value:A}])}setVolume(A,F){let r=this.medias.get(k(A));r!==void 0&&o(this.worker,["playbackSetVolume",{index:r.index,value:F}])}_GetFreeIndex(){let A=super._GetFreeIndex();if(A!==void 0)return A;if(this.medias.size<C.MaxNumberOfDecoders)return this.medias.size}_OnMessages(A){super._OnMessages(A);let[F,r]=A.data;F==="playbackUpdate"&&(this.activities=r.activities,this.jitterStats=r.jitterStats)}}});var dF={};lx(dF,{SESSION_ID:()=>ix,createPlugin:()=>kF});module.exports=dA(dF);var uF=require("@4players/odin-common");b();var vx=require("@4players/odin-common");b();var Bx=require("@4players/odin-common");b();var N=require("@4players/odin-common");async function I0(D,x,A){let F;if(x.device?.device.kind==="track"&&x.device?.device.audioTrack)F=new MediaStream([x.device.device.audioTrack]);else{let j=x.device?{exact:x.device.device.deviceId==="default"?void 0:x.device.device.deviceId}:void 0;try{let e=await Promise.race([navigator.mediaDevices.getUserMedia({audio:{echoCancellation:A.echoCanceller,noiseSuppression:A.noiseSuppression!=="None",autoGainControl:A.gainController,echoCancellationType:"system",deviceId:j}}),(0,N.sleep)(3e4,"timeout")]);if(e==="timeout")return(0,N.failure)("getUserMedia; timeout");F=e}catch(e){return(0,N.failure)(`getUserMedia; ${e}`)}}let r=F.getAudioTracks()[0].getSettings().sampleRate,t=await D.audioContexts.acquire(r);return(0,N.success)(t.createMediaStreamSource(F))}function Q(D){D.getTracks().forEach(x=>{x.stop(),D.removeTrack(x)})}async function $0(D){return new g({deviceId:D.id,kind:"track",name:D.label??"MediaStreamTrack",audioTrack:D},!1)}async function dx(){if((0,N.isFirefoxBrowser)()){let r=await TA("microphone");(r==="granted"||r===!1)&&await SA("audio")}let D=(await navigator.mediaDevices.enumerateDevices()).filter(r=>!!r.label),x=[],A=new g({deviceId:"default",name:"Default",kind:"audioinput"},!0),F=new g({deviceId:"default",name:"Default",kind:"audiooutput"},!0);x.push(A),x.push(F);for(let r of D){if(r.deviceId==="default"){r.kind==="audioinput"&&(A=new g({deviceId:"default",name:r.label,kind:"audioinput"},!0),x[0]=A),r.kind==="audiooutput"&&(F=new g({deviceId:"default",name:r.label,kind:"audiooutput"},!0),x[1]=F);continue}r.kind==="audioinput"&&x.push(new g({deviceId:r.deviceId,name:r.label,kind:"audioinput"},!1)),r.kind==="audiooutput"&&x.push(new g({deviceId:r.deviceId,name:r.label,kind:"audiooutput"},!1))}return x}async function TA(D){try{return(await navigator.permissions.query({name:D})).state}catch{return!1}}async function SA(D){try{let x=await navigator.mediaDevices.getUserMedia({[D]:!0});return x?.getTracks().forEach(A=>{A.stop(),x.removeTrack(A)}),!0}catch{return!1}}var mx=require("@4players/odin-common");b();var M0=(0,mx.isSharedArrayBufferCapable)()&&!(0,mx.isSafariBrowser)()?Promise.resolve().then(()=>(N0(),H0)):Promise.resolve().then(()=>(O0(),P0));async function T0(D,x,A,F){return M0.then(r=>r.createCaptureWorker(D,x,A,F,C.DefaultRefreshRate))}async function S0(D){return M0.then(x=>x.createPlaybackWorker(D,C.DefaultRefreshRate))}var K=class{constructor(x,A){this.controller=x;this._Medias=new Map;this._Vad={...Bx.VAD_DEFAULTS};this._Apm={...Bx.APM_DEFAULTS};this._Volume=1;this._ProcessingDevice=!1;this._DeviceCb=async()=>{(await dx()).some(F=>F.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&&(Q(this._Capture.source.mediaStream),this._Capture.source.disconnect(this._Capture.worker.worklet)))};A.apm&&this.setApm(A.apm).catch(console.error),A.vad&&this.setVad(A.vad),typeof A.volume<"u"&&this.setVolume(A.volume).catch(console.error),this.uid=(0,Bx.generateUUID)(),this.#x=A.customType,this.#A=A.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(x,A){let F=this._Medias.get(A.connectionId);F===void 0&&this._Medias.set(A.connectionId,F=new Set),E(`starting audio capture media ${A.mediaId} on connection ${A.connectionId}`),!F.has(A.mediaId)&&(F.add(A.mediaId),x.mainConnection?.id===A.connectionId&&await x.request("StartMedia",{media_id:A.mediaId,properties:{kind:"audio",uid:this.uid,ref:this.#A,customType:this.#x}}).catch(r=>a(`StartMedia got rejected; ${r}`)),this._UpdateMedias())}async stop(x,A){let F=this._Medias.get(A.connectionId);E(`stopping audio capture media ${A.mediaId} on connection ${A.connectionId}`),F?.delete(A.mediaId)&&(x.mainConnection?.id===A.connectionId&&await x.request("StopMedia",{media_id:A.mediaId}).catch(r=>a(`StopMedia got rejected; ${r}`)),this._UpdateMedias())}setVad(x){f("updating vad config",x),this._Vad=x,this._Capture&&this._Capture.worker.setVad(x)}async setApm(x){f("updating apm config",x),this._Apm=x,this._DeviceParameters&&await this.setDevice(this._DeviceParameters)}async setDevice(x){if(f("updating capture device parameters",x),this._ProcessingDevice)return;this._ProcessingDevice=!0;let A=this._DeviceParameters;if(this._DeviceParameters=x,this._Volume==="muted"){this._ProcessingDevice=!1;return}try{let F=await I0(this.controller,x,{...this._Apm,echoCanceller:this._Monitor?!1:this._Apm.echoCanceller});if(F.type!=="Success"){a(`unable to open capture device; ${F.reason}`),this._DeviceParameters=A,this._ProcessingDevice=!1;return}this._DeviceParameters.onStatusChanged&&navigator.mediaDevices.addEventListener("devicechange",this._DeviceCb),this._Capture!==void 0&&(Q(this._Capture.source.mediaStream),this._Capture.source.disconnect(this._Capture.worker.worklet)),this._Capture===void 0||this._Capture.worker.worklet.context!==F.value.context?(this._Capture?.worker.close(),this._Capture={worker:await T0(F.value.context,this.controller.sink,this.controller.receiveMonitoredPacket.bind(this.controller),new WeakRef(this)),source:F.value},await this._UpdateMedias(),await this.setVolume(this._Volume),this.setVad(this.vad)):this._Capture.source=F.value,this._Capture.source.connect(this._Capture.worker.worklet)}catch(F){throw this._ProcessingDevice=!1,new Error(`Error in setDevice(); ${F}`)}this._ProcessingDevice=!1}async setVolume(x){f(`updating capture volume to ${x}`),this._Volume=x,x==="muted"?await this.close():(!this._Capture&&this._DeviceParameters&&await this.setDevice(this._DeviceParameters),this._Capture?.worker.setVolume(x)),x!==this._Volume&&await this.setVolume(this._Volume)}async close(){if(f("closing audio capture"),this._Capture!==void 0){this._Capture.worker.close(),Q(this._Capture.source.mediaStream);try{this._Capture.source.disconnect(this._Capture.worker.worklet)}catch(x){c("failed to disconnect audio node",x)}await this.controller.audioContexts.release(this._Capture.source.context)}navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._Capture=void 0}async dump(){let x=[];for(let[A,F]of this._Medias)x.push(`${A} => ${Array.from(F.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:x}}async _UpdateMedias(){if(this._Capture!==void 0){let x=Array.from(this._Medias).map(([A,F])=>({id:A,mediaIds:Array.from(F)}));this._Capture.worker.setMedias(x)}}async startLoopback(){this._Monitor===void 0&&(f("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&&(f("stopping audio capture loopback"),this._Monitor.close(),this._Monitor=void 0,this.setApm(this._Apm),this._Medias.delete(0),await this._UpdateMedias())}};var sx=require("@4players/odin-common");b();var G=class{constructor(x,A){this.controller=x;this.parameters=A;this.uid=(0,sx.generateUUID)()}#x;#A=new Map;#F;get customType(){return this.parameters?.customType}get mediaStream(){return this.#x}get audioCapture(){return this.#F}get volume(){return(0,sx.assert)(this.audioCapture,"getting the volume failed, this video has no Audio"),this.audioCapture.volume}async setVolume(x){(0,sx.assert)(this.audioCapture,"setVolume() failed, this video has no Audio"),await this.audioCapture.setVolume(x)}get vad(){return(0,sx.assert)(this.audioCapture,"getting the vad config failed, this video has no Audio"),this.audioCapture.vad}setVad(x){(0,sx.assert)(this.audioCapture,"setVad() failed, this video has no Audio"),this.audioCapture.setVad(x)}async setDevice(x,A={voiceActivity:void 0,volumeGate:void 0}){if(this.#x)throw new Error("This VideoCapture already has a MediaStream.");if(!x.getVideoTracks()[0])throw new Error("Error when calling setDevice(), MediaStream does not contain a VideoStreamTrack!");if(this.#x=x,x.getAudioTracks()[0]){let r={device:await $0(x.getAudioTracks()[0]),vad:A,ref:this.uid};this.#F=await this.controller.createAudioCapture(r)}}async start(x,A){let F=this.#A.get(A.connectionId);if(F===void 0&&this.#A.set(A.connectionId,F=new Set),!F.has(A.mediaId)&&(F.add(A.mediaId),x.mainConnection?.id===A.connectionId)){let r={kind:"video",codec:this.parameters?.codec??C.DefaultVideoCodec,ref:this.#F?.uid,uid:this.uid};this.parameters?.customType&&(r.customType=this.parameters.customType),await x.request("StartMedia",{media_id:A.mediaId,properties:r}).catch(t=>a(`StartMedia got rejected; ${t}`))}}async stop(x,A){this.#x&&Q(this.#x),this.#A.get(A.connectionId)?.delete(A.mediaId)&&x.mainConnection?.id===A.connectionId&&await x.request("StopMedia",{media_id:A.mediaId}).catch(r=>a(`StopMedia got rejected; ${r}`))}async dump(){let x=[];for(let[A,F]of this.#A)x.push(`${A} => ${Array.from(F.values()).join(",")}`);return{uid:this.uid,ref:this.#F?.uid??null,customType:this.customType??null,tracks:this.#x?.getVideoTracks().map(A=>({id:A.id,kind:A.kind,label:A.label,ready:A.readyState,muted:A.muted,settings:{...A.getSettings()}}))??[],volume:this.#F?.volume??0,medias:x}}close(){this.#x&&Q(this.#x),this.audioCapture?.close(),this.#F=void 0}};var Hr=require("@4players/odin-common");b();var y=class{constructor(x,A,F){this.controller=x;this.uid=A;this.customType=F}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(x){E(`starting audio playback media ${x.mediaId} on connection ${x.connectionId}`),this.controller.playbackStart(this.uid,x)}stop(x){E(`stopping audio playback media ${x.mediaId} on connection ${x.connectionId}`),this.controller.playbackStop(this.uid,x)}setVolume(x){f(`updating audio playback media '${this.uid}' volume to ${x}`),this.controller.playbackSetVolume(this.uid,x)}close(){f(`closing audio playback media '${this.uid}'`),this.controller.closePlayback(this.uid)}};var Gx=class{constructor(x){this.audioContextFactory=x;this.entries=[]}async acquire(x){for(let F of this.entries){if(F.sampleRate===x)return F.references+=1,F.audioContext;if(F.sampleRate===void 0&&F.audioContext.sampleRate===x)return F.references+=1,F.audioContext}let A={sampleRate:x,audioContext:await this.audioContextFactory(x),references:1};return this.entries.push(A),A.audioContext}async release(x){let A=this.entries.findIndex(F=>F.audioContext===x);if(!(A<0)&&(this.entries[A].references-=1,this.entries[A].references<=0)){let F=this.entries[A].audioContext;this.entries.splice(A,1),await F.close()}}close(){for(let x of this.entries)x.audioContext.close()}},Ix=class D{constructor(x,A){this.audioContexts=x;this.sink=A;this.audioCaptures=[];this.videoCaptures=[];this.globalVolume=[1,1];this.playbacks=new Map;this.setPlaybackStrand=new vx.Strand}async create(x,A){return new D(x,A)}receivePacket(x,A){this.playbackWorker?.receivePacket(x,A)}receiveMonitoredPacket(x,A){let F=A.slice();this.receivePacket(x,F)}async createAudioPlayback(x){let A=this.playbacks.get(x.uid),F=x.volume;if(A===void 0){F=F??[1,1];let r=new y(this,x.uid,x.customType);A={id:void 0,volume:F,playback:r},this.playbacks.set(x.uid,A)}return F!==void 0&&A.playback.setVolume(F),A.playback}async createAudioCapture(x){let A=new K(this,x);return await A.setDevice(x),this.audioCaptures.push(new WeakRef(A)),A}async createVideoCapture(x,A){let F=new G(this,A);return await F.setDevice(x),this.videoCaptures.push(new WeakRef(F)),F}playbackSetDevice(x){return this.setPlaybackStrand.enqueue(async()=>{let A=x?.device.deviceId??"";A==="default"&&(A="");let F;if(this.playbackWorker===void 0){F=await this.audioContexts.acquire(48e3),this.playbackWorker=await S0(F),this.playbackWorker.setGlobalVolume(this.globalVolume);for(let[,r]of this.playbacks)r.id!==void 0&&this.playbackWorker.addMedias(r.id.connectionId,[r.id.mediaId],r.volume)}else F=this.playbackWorker.audioContext;F?.setSinkId!==void 0&&x&&F?.state==="running"&&await F.setSinkId(A)})}playbackSetGlobalVolume(x){this.globalVolume=x,this.playbackWorker?.setGlobalVolume(this.globalVolume)}playbackStart(x,A){let F=this.playbacks.get(x);F!==void 0&&(F.id!==void 0&&this.playbackStop(x,F.id),F.id=A,this.playbackWorker?.addMedias(A.connectionId,[A.mediaId],F.volume))}playbackStop(x,A){let F=this.playbacks.get(x);F!==void 0&&(F.id!==A&&c(`playback media ${A.mediaId} on connection ${A.connectionId} is out of sync`,F.id,A),F.id=void 0,this.playbackWorker?.removeMedias(A.connectionId,[A.mediaId]))}playbackGetActivity(x){let A=this.playbacks.get(x);return A?.id===void 0?$:this.playbackWorker?.getActivity(A.id)??$}playbackGetJitterStats(x){let A=this.playbacks.get(x);return A?.id===void 0?vx.JITTER_STATS_INITIAL:this.playbackWorker?.getJitterStats(A.id)??vx.JITTER_STATS_INITIAL}playbackSetVolume(x,A){let F=this.playbacks.get(x);F!==void 0&&(F.volume=A,F.id!==void 0&&this.playbackWorker?.setVolume(F.id,F.volume))}playbackGetVolume(x){return this.playbacks.get(x)?.volume??[1,1]}closePlayback(x){let A=this.playbacks.get(x);A!==void 0&&(A.id!==void 0&&this.playbackStop(x,A.id),this.playbacks.delete(x))}close(){this.playbackWorker?.close(),this.audioContexts.close()}async dump(){let x=[];for(let r of this.audioCaptures){let t=r.deref();t!==void 0&&x.push(await t.dump())}let A=[];for(let r of this.videoCaptures){let t=r.deref();t!==void 0&&A.push(await t.dump())}let F=[];for(let[r,t]of this.playbacks)F.push({uid:r,id:t.id||null,volume:t.volume});return{globalVolume:this.globalVolume,playbackWorker:await this.playbackWorker?.dump()||null,audioCaptures:x,videoCaptures:A,playbacks:F}}},g=class{constructor(x,A=!1){this.device=x;this.isDefault=A}get type(){switch(this.device.kind){case"audioinput":return"AudioCapture";case"audiooutput":return"AudioPlayback";default:(0,vx.assert)(!1,"not supported device")}}get id(){return this.device.deviceId}get name(){return this.device.name}};var ox=require("@4players/odin-common"),Y0=require("@msgpack/msgpack");b();var VD=require("@4players/odin-common");b();var U=require("@4players/odin-common"),W=require("@4players/odin-common/api");b();var V=require("@4players/odin-common"),Z=require("@4players/odin-common/api"),$x=require("@msgpack/msgpack");b();var R=class{constructor(x){this.stream=x;this._SendQueue=[];this._RecvQueue=[];this._EventQueue=[];this._Requests=new Map;this._Close=new AbortController;this._NextId=1;x instanceof WebSocket?(x.addEventListener("open",this._OnWebSocketOpen.bind(this)),x.addEventListener("close",this.close.bind(this)),x.addEventListener("message",A=>this._OnRpcMessage(A.data)),x.binaryType="arraybuffer"):(DF(x.readable.getReader(),this._OnRpcMessage.bind(this)).finally(this.close.bind(this)),this._Writer=x.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(x,A,F){if(this.closed)return Promise.resolve("closed");let r=this._NextId,t=F===void 0?void 0:setTimeout(()=>this._TimeoutRequest(r),F);return this._Send([0,r,x,A]),new Promise(j=>{this._Requests.set(r,{accept:j,timeoutId:t}),this._NextId+=1})}notify(x,A){this.closed||this._Send([2,x,A])}recv(){if(this.closed)return Promise.resolve("closed");let x=this._EventQueue.shift();return x!==void 0?Promise.resolve(x):new Promise(A=>this._RecvQueue.push(A))}close(){this._Close.abort()}_TimeoutRequest(x){let A=this._Requests.get(x);A!==void 0&&(this._Requests.delete(x),clearTimeout(A.timeoutId),A.accept("timeout"))}_Send(x){let A;x instanceof Uint8Array?A=x:A=new Uint8Array((0,$x.encode)(x,{ignoreUndefined:!0,forceFloat32:!0})),this.stream instanceof WebSocket?this.stream.send(A):this._Writer.write(A)}_OnWebSocketOpen(x){for(let A of this._SendQueue)this._Send(A);this._SendQueue.length=0}_OnRpcMessage(x){let A=rF(x);if(A.type!=="Success"){this.close();return}switch(A.value[0]){case 0:this._Send([1,A.value[1],"not supported",null]);break;case 1:this._OnResponse(A.value[1],A.value[2],A.value[3]);break;case 2:this._OnEvent(A.value[1],A.value[2]);break}}_OnResponse(x,A,F){let r=this._Requests.get(x);r!==void 0&&(clearTimeout(r.timeoutId),r.accept(A===null?(0,V.success)(F):(0,V.failure)(A)))}_OnEvent(x,A){let F=this._RecvQueue.shift();F!==void 0?F({name:x,properties:A}):this._EventQueue.push({name:x,properties:A})}_Cleanup(){for(let x of this._Requests.values())clearTimeout(x.timeoutId),x.accept("closed");this._Requests.clear();for(let x of this._RecvQueue)x("closed");this._RecvQueue.length=0,this._SendQueue.length=0,this.stream instanceof WebSocket?this.stream.close():this._Writer?.close().catch(()=>{})}},xx=class{constructor(x,A,F){this.rpc=x;this._Commands=A;this._Events=F}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(x,A,F){A=(0,Z.parseRequest)(x,A,this._Commands);let r=await this.rpc.request(x,A,F);if(r==="closed"||r==="timeout"||r.type==="Failure")return r;let t=(0,Z.parseResponse)(x,r.value,this._Commands);return t!==void 0?(0,V.success)(t):(0,V.failure)("response schema failed validation")}notify(x,A){A=(0,Z.parseRequest)(x,A,this._Commands),this.rpc.notify(x,A)}async recv(){let x=await this.rpc.recv();if(x==="closed")return x;let A=e0(this._Events,x);return A!==void 0?A:(R0(this._Events,x.name)?(a(`schema validation for ${x.name} failed; closing connection`),this.rpc.close()):c(`dropping unknown event ${x.name}`),"closed")}close(){this.rpc.close()}};function rF(D){try{return(0,V.success)(Z.MessagePackRpcSchema.parse((0,$x.decode)(new Uint8Array(D))))}catch(x){return(0,V.failure)(String(x))}}function e0(D,x){if(!R0(D,x.name))return;let A=D[x.name].safeParse(x.properties);if(A.success)return{name:x.name,properties:A.data}}function R0(D,x){return x in D}async function DF(D,x){let A=new Uint8Array;for(;;){let F=d0(A,0);if(F===B){D.cancel("protocol violation");break}if(F!==q&&F<=A.length){x(A.subarray(0,F)),A=A.subarray(F);continue}let r;try{r=await D.read()}catch{break}if(r.done)break;A=tF(A,r.value)}A.length>0&&c("unprocessed bytes left in rpc stream",A)}function tF(D,x){if(D.length===0)return x;if(x.length===0)return D;let A=new Uint8Array(D.length+x.length);return A.set(D,0),A.set(x,D.length),A}var w=require("@4players/odin-common"),V0=require("@4players/odin-common/api");b();var I=class D{constructor(x,A){this.text=x;this.claims=A;if(A.ups!==void 0){let F=D.parse(A.ups);F.type==="Success"?this._Upstream=F.value:a(`upstream in token can not be parsed; ${F.reason}`)}}static parse(x){let A=x.split(".");if(A.length!==3)return(0,w.failure)("expected three segments");let F=(0,w.fromBase64Url)(A[1]);if(F.type==="Failure")return(0,w.failure)(`invalid token; ${F.reason}`);let r;try{r=JSON.parse(F.value)}catch(j){return(0,w.failure)(`invalid token; ${j}`)}let t=V0.TokenClaimsSchema.safeParse(r);return t.success===!1?(0,w.failure)(`invalid token; ${t.error}`):(0,w.success)(new D(x,t.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(x){return this.claims.aud===void 0&&x==="gateway"?!0:Array.isArray(this.claims.aud)?this.claims.aud.includes(x):this.claims.aud===x}toString(){return this.text}};var Ax=require("@4players/odin-common");b();function U0(D){typeof globalThis.rtcDataChannels>"u"&&(globalThis.rtcDataChannels=[]),Array.isArray(globalThis.rtcDataChannels)&&globalThis.rtcDataChannels.length<=100&&globalThis.rtcDataChannels.push(D)}function W0(D){let x=globalThis.rtcDataChannels?.indexOf(D);x!==void 0&&x>=0&&globalThis.rtcDataChannels.splice(x,1),D.readyState!=="closed"&&D.close()}function gx(D){typeof globalThis.rtcPeerConnections>"u"&&(globalThis.rtcPeerConnections=[]),Array.isArray(globalThis.rtcPeerConnections)&&globalThis.rtcPeerConnections.length<=100&&globalThis.rtcPeerConnections.push(D)}function z0(D){let x=globalThis.rtcPeerConnections?.indexOf(D);x!==void 0&&x>=0&&globalThis.rtcPeerConnections.splice(x,1),D.connectionState!=="closed"&&D.close()}var Cx=class{constructor(x,A){this._localVideos=new Map;this._remoteVideos=new Map;this._negotiation={requested:!1,running:!1,waitForAnswer:!1};this._WebRtcStatsSnapshot=null;this._peerConnection=x,this._signaling=A,this._peerConnection.ontrack=this._onTrack.bind(this),this._peerConnection.onconnectionstatechange=()=>this._onStatusChanged(),this._peerConnection.onicecandidate=async F=>{F.candidate?await this._signaling.sendIceCandidate(F.candidate):await this._signaling.sendIceComplete()},this._WebRtcStatsInterval=setInterval(()=>{this._snapshotStats()},C.WebRtcStatsSnapshotInterval)}requestNegotiation(x){this._negotiation.requested=!0,x&&(this._negotiation.waitForAnswer=!0),!this._negotiation.running&&(this._negotiation.running=!0,setTimeout(async()=>{let A=this._negotiation.waitForAnswer;this._negotiation.requested=!1,this._negotiation.waitForAnswer=!1;try{let F;A&&(F=new Promise(r=>{this._resolveOffer=r})),await this._sendOffer(),F&&await F}catch(F){a("negotiation failed during sdp offer/answer exchange",F)}finally{this._resolveOffer=void 0,this._negotiation.running=!1,this._negotiation.requested&&this.requestNegotiation(this._negotiation.waitForAnswer)}}))}async startLocalVideo(x,A,F){if(this._localVideos.has(x))return;E(`starting local video for media ${x}`);let r=this._peerConnection.getTransceivers().find(e=>e.sender.track===A);if(r)await r.sender.replaceTrack(A);else{let e=this._peerConnection.addTrack(A);r=this._peerConnection.getTransceivers().find(v=>v.sender===e),(0,Ax.assert)(r,"failed to create transceiver for local video")}if(F){let e=r.sender.getParameters(),{maxBitrate:v,maxFramerate:n,scaleResolutionDownBy:p}=F,H={...v!==void 0&&{maxBitrate:v},...n!==void 0&&{maxFramerate:n},...p!==void 0&&{scaleResolutionDownBy:p}};if(e.encodings.length===0)e.encodings.push(H);else for(let aA of e.encodings)Object.assign(aA,H);F.degradationPreference&&(e.degradationPreference=F.degradationPreference),await r.sender.setParameters(e)}let j=new Ax.VideoCodec(F?.codec??C.DefaultVideoCodec).isSupported();j&&r.setCodecPreferences([j]),this._localVideos.set(x,{transceiver:r}),this.requestNegotiation(!0)}stopLocalVideo(x){let A=this._localVideos.get(x);A&&(E(`stopping local video for media ${x}`),this._localVideos.delete(x),A.transceiver.sender.track&&(A.transceiver.sender.track.enabled=!1),A.transceiver.direction="inactive",this.requestNegotiation(!1))}startRemoteVideo(x){E(`starting remote video for media ${x}`);let A=this._peerConnection.addTransceiver("video"),F=new Promise((r,t)=>{this._remoteVideos.set(x,{state:"Requested",transceiver:A,promise:{resolve:r,reject:t}})});return this.requestNegotiation(!0),F}stopRemoteVideo(x){let A=this._remoteVideos.get(x);A&&(E(`stopping remote video for media ${x}`),this._remoteVideos.delete(x),A.state!=="Active"&&A.promise.reject(new Error("video stopped")),this.requestNegotiation(!1))}async handleWebRtcUpdate(x){switch(x.kind){case"Sdp":await this._updateRemoteSdp(x.type==="Answer"?"answer":"offer",x.sdp,x.media_map);break;case"Trickle":this._addIceCandidate({candidate:x.candidate,sdpMid:x.spd_mid??void 0,sdpMLineIndex:x.spd_mline_index??void 0,usernameFragment:x.username_fragment??void 0});break;case"TrickleFinished":this._addIceCandidate(void 0);break}}async startup(){if(this._peerConnection.connectionState==="new")try{let x=await this._peerConnection.createOffer();(0,Ax.assert)(x.type==="offer"&&x.sdp,"generated broken webrtc offer"),await this._peerConnection.setLocalDescription(x),await this._signaling.sendOffer(x.sdp,[])}catch{a("failed to create initial sdp offer")}}cleanup(){for(let[,x]of this._remoteVideos)x.state!=="Active"&&x.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 x=await this._peerConnection.getStats(),A={},F={bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,rtt:0};x.forEach(r=>{let{type:t,...j}=r;t!=="certificate"&&(t==="candidate-pair"&&r.nominated&&(F.bytesSent+=r.bytesSent??0,F.bytesReceived+=r.bytesReceived??0,F.packetsSent+=r.packetsSent??0,F.packetsReceived+=r.packetsReceived??0,F.rtt=r.currentRoundTripTime??0),A[t]||(A[t]=[]),A[t].push(j))}),this._WebRtcStatsSnapshot={timestamp:Date.now(),status:this._peerConnection.connectionState,stats:F,report:A}}catch{}}_addIceCandidate(x){x&&(x.sdpMid===void 0&&x.sdpMLineIndex===void 0&&(x={...x,sdpMid:"0"}),f(`adding new ice ${x.candidate}`,x)),this._peerConnection.addIceCandidate(x)}async _sendOffer(){try{let x=await this._peerConnection.createOffer();(0,Ax.assert)(x.type==="offer"&&x.sdp,"generated broken payload"),await this._peerConnection.setLocalDescription(x);let A=[];for(let[F,{transceiver:r}]of this._localVideos)r.mid&&A.push([F,r.mid]);for(let[F,r]of this._remoteVideos)r.state!=="Active"&&r.transceiver.mid&&A.push([F,r.transceiver.mid]);await this._signaling.sendOffer(x.sdp,A)}catch(x){throw a("failed to send sdp offer",x),x}}async _updateRemoteSdp(x,A,F){for(let[r,t]of F){let j=this._remoteVideos.get(r);j?.state==="Requested"&&(this._remoteVideos.set(r,{state:"Mapped",transceiver:j.transceiver,mid:t,promise:j.promise}),f(`updated remote video list with media ${r}`,j,this._remoteVideos))}await this._peerConnection.setRemoteDescription({type:x,sdp:A}),this._resolveOffer?.(!0)}async _onStatusChanged(){switch(f(`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":C.MainConnectionPingInterval!==void 0&&await this._signaling.checkConnection();default:this._WebRtcIceTimeout===void 0&&(this._WebRtcIceTimeout=setTimeout(()=>{f("ice connection timeout was reached"),this._peerConnection.restartIce(),this._WebRtcIceTimeout=void 0},C.WebRtcIceTimeout)),this._WebRtcTimeout===void 0&&(this._WebRtcTimeout=setTimeout(async()=>{f("peer connection timeout was reached"),await this._signaling.closeConnection()},C.WebRtcTimeout));break}}_onTrack(x){let A=Array.from(this._remoteVideos).find(([,t])=>t.state==="Mapped"&&t.mid===x.transceiver.mid);if(!A){c(`unexpected track with mid: ${x.transceiver.mid}`);return}let[F,r]=A;(0,Ax.assert)(r.state==="Mapped","expected video state to be Mapped"),this._remoteVideos.set(F,{state:"Active",transceiver:x.transceiver}),f(`updated local video list with media ${F}`,A,x.transceiver,this._localVideos),x.track.onended=()=>{f(`video track with mid ${x.transceiver.mid} ended`,A)},r.promise.resolve(x.track)}};var yx=class D{constructor(x,A,F,r,t,j){this.id=x;this.address=A;this.connection=r;this.rpc=t;this.closeController=j;this._ConnectionStats={...U.CONNECTION_STATS_INITIAL};this._WebRtcSessionFlight=new X;this._PingFlight=new X;this.status=0;this._ClosePromise=(async()=>{try{await this.connection.closed}catch{}return"closed"})(),C.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(C.HealthCheckTimeout)},C.MainConnectionPingInterval)),j.signal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this.datagramWriter=r.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,(e,v)=>{this._ConnectionStats.packetsReceived+=1,F(e,v)})}static async create(x,A,F,r){try{let t=new URL(`https://${A}?version=${h0}&uid=${ix}`),j=new AbortController;r.addEventListener("abort",()=>j.abort(),{once:!0});let e=new WebTransport(t);j.signal.addEventListener("abort",()=>{try{e.close()}catch{}},{once:!0}),await e.ready;let v=await e.createBidirectionalStream(),n=new xx(new R(v),W.MainCommandsRpc,W.MainNotificationsRpc);return j.signal.addEventListener("abort",()=>n.close(),{once:!0}),n.notify("Hello",{stream:"main"}),(0,U.success)(new D(x,A,F,e,n,j))}catch(t){return(0,U.failure)(`connecting to ${A} failed with ${t}`)}}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(){E(`closing connection to '${this.address}' with id ${this.id}`),this.closeController.abort("request")}async joinRoom(x,A,F,r){try{if(this.closed)return"closed";let t=await this.connection.createBidirectionalStream().catch(()=>"closed");if(t==="closed")return"closed";let j=new xx(new R(t),W.RoomCommandsRpc,W.RoomNotificationsRpc),e=await j.request("Hello",{stream:"room",token:String(x),room_id:A,user_data:F,position:r});return e==="closed"||e.type==="Failure"?e:(0,U.success)(j.rpc)}catch(t){return(0,U.failure)(`JoinRoom failed; ${t}`)}}async getReconnectToken(x){let A=await this._Request("RequestReconnectToken",{peer_id:x});return A.type==="Failure"?A:I.parse(A.value)}async healthCheck(){let x=await this._RequestPing(C.HealthCheckTimeout);return x||this.close(),x}async ping(x=3e4){let A=Date.now();return await this._RequestPing(x)?Date.now()-A:0}sendDatagram(x){try{this.datagramWriter.write(x),this._ConnectionStats.packetsSent+=1;let A=x.byteLength;this.connectionStats.bytesSent+=A}catch{}}async readDatagrams(x,A,F){try{let r=x.datagrams.readable.getReader();for(;;){let t=await r.read();if(t.done)break;let j=t.value.byteLength;this.connectionStats.bytesReceived+=j,F(A,t.value)}}catch{}}_CleanUp(){f(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId)}async _EnsureWebRtcSession(){return this._WebRtcSession?this._WebRtcSession:this._WebRtcSessionFlight.run(async()=>(this._PeerConnection=new RTCPeerConnection,gx(this._PeerConnection),this._WebRtcSession=new Cx(this._PeerConnection,{sendOffer:async(x,A)=>{await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:x,media_map:A})},sendIceCandidate:async x=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:x.candidate,spd_mid:x.sdpMid??void 0,spd_mline_index:x.sdpMLineIndex??void 0,username_fragment:x.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 x=await this.rpc.recv();if(x==="closed")break;x.name==="WebRtcUpdate"&&this._WebRtcSession?.handleWebRtcUpdate(x.properties)}this.close()}async _Request(x,A,F){let r=Date.now(),t=await(F===void 0?this.rpc.request(x,A):this.rpc.request(x,A,F)),j=(Date.now()-r)/1e3;return x!=="Ping"&&f(`sent main rpc '${x}'; took: ${j}s`,{properties:A,timeout:F,result:t}),t==="closed"?(0,U.failure)("connection lost"):t}_RequestPing(x=3e4){return this._PingFlight.run(async()=>{let A=await this._Request("Ping",{},x);return A!=="timeout"&&A.type==="Success"})}async startLocalVideo(x,A,F){await(await this._EnsureWebRtcSession()).startLocalVideo(x,A,F)}stopLocalVideo(x){this._WebRtcSession?.stopLocalVideo(x)}async startRemoteVideo(x){return(await this._EnsureWebRtcSession()).startRemoteVideo(x)}stopRemoteVideo(x){this._WebRtcSession?.stopRemoteVideo(x)}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}}}};var d=require("@4players/odin-common"),Lx=require("@4players/odin-common/api");b();var _=require("@4players/odin-common");b();async function B0(D,x){let A=performance.now(),F=(0,_.failure)("no connection was attempted");for(let r=0;r<C.ConnectInterval.length&&!x.aborted;r++){let t=A+eF(r);if(await(0,_.abortableSleep)(t-performance.now(),x)==="aborted")return(0,_.failure)("aborted");if(F=await jF(D,x),F.type==="Success")return F}return F}async function jF(D,x){let A;try{A=new WebSocket(D)}catch(v){return(0,_.failure)(`unable to create websocket; ${v}`)}let F=new AbortController,r=new Promise(v=>A.addEventListener("open",()=>v((0,_.success)(A)),{signal:F.signal})),t=new Promise(v=>A.addEventListener("close",n=>v((0,_.failure)(n.reason!==""?n.reason:"unable to establish websocket connection")),{signal:F.signal})),j=new Promise(v=>x.addEventListener("abort",()=>v((0,_.failure)("aborted")),{signal:F.signal})),e=await Promise.race([r,t,j]);return F.abort(),e}function eF(D){let x=C.ConnectInterval.slice(0,D).reduce((F,r)=>F+r,0),A=C.ConnectInterval[D]*Math.random();return x+A}var _x=class D{constructor(x,A,F,r,t,j){this.id=x;this.address=A;this.url=F;this.onDatagram=r;this.connection=t;this.webRtc=j;this._PeerIdMap=new WeakMap;this._ConnectionStats={...d.CONNECTION_STATS_INITIAL};this._PingFlight=new X;E(`creating new webrtc connection to '${this.address}' with id ${this.id}`),this.closeSignal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this._ClosePromise=new Promise(e=>{this.closeSignal.addEventListener("abort",()=>{e("closed")},{once:!0})}),gx(j),this._AudioChannel=this.webRtc.createDataChannel("audio",{id:2,negotiated:!0,ordered:!1,maxRetransmits:0}),this._AudioChannel.binaryType="arraybuffer",this._AudioChannel.onmessage=e=>{this._ConnectionStats.packetsReceived++;let v=new Uint8Array(e.data);this._ConnectionStats.bytesReceived+=v.byteLength,this.onDatagram(this.id,v)},this._AudioChannel.onerror=e=>c(`webrtc audio data channel for connection with id ${x} raised an error`,e),this._AudioChannel.onclosing=e=>E(`webrtc audio data channel for connection with id ${x} begins shutting down`,e),this._AudioChannel.onclose=e=>E(`webrtc audio data channel for connection with id ${x} has closed`,e),U0(this._AudioChannel),this._WebRtcSession=new Cx(this.webRtc,{sendOffer:async(e,v)=>{await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:e,media_map:v})},sendIceCandidate:async e=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:e.candidate,spd_mid:e.sdpMid??void 0,spd_mline_index:e.sdpMLineIndex??void 0,username_fragment:e.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async()=>{this.close()},checkConnection:async()=>{this.healthCheck().then()}}),this._WebRtcSession.startup(),C.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(C.HealthCheckTimeout)},C.MainConnectionPingInterval)),this._HandleWebRtcUpdates()}static async create(x,A,F,r){if(r.aborted)return(0,d.failure)("aborted");let t;try{t=new URL(`wss://${A}`)}catch(n){return(0,d.fail)(`address in token(${A}) can not be parsed; ${n}`)}let j=(0,d.extendUrl)(t,`main?uid=${ix}`);if(j.type!=="Success")return j;let e=await B0(j.value,r);if(e.type!=="Success")return e;let v=new xx(new R(e.value),Lx.MainCommandsRpc,Lx.MainNotificationsRpc);try{return(0,d.success)(new D(x,A,t,F,v,new RTCPeerConnection))}catch(n){return v.close(),(0,d.failure)(`unable to create webrtc connection; ${n}`)}}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((x,A)=>{let F=()=>{let r=this.status;r!==0&&(this.webRtc.removeEventListener("connectionstatechange",F),r===1?x():A(new Error("connection closed")))};this.webRtc.addEventListener("connectionstatechange",F),F(),this.closePromise.then(()=>{A(new Error("connection closed"))})})}close(){E(`closing ${this.transport} connection to '${this.address}' with id ${this.id}`),this.connection.close()}async joinRoom(x,A,F,r){let t=await this.connection.request("JoinRoom",{token:String(x),room_id:A,user_data:F,position:r});if(t==="closed"||t.type==="Failure")return t;let j=t.value;if(!("token"in j))return(0,d.failure)("JoinRoom responded without token");let e=(0,d.extendUrl)(this.url,`room?token=${j.token}`);if(e.type==="Failure")return e;let v=await B0(e.value,this.closeSignal);return v.type==="Success"?(this._PeerIdMap.set(v.value,j.peer_id),(0,d.success)(new R(v.value))):v}async getReconnectToken(x){let A=await this._Request("RequestReconnectToken",{peer_id:x});return A.type==="Failure"?A:I.parse(A.value)}async healthCheck(){let x=await this._RequestPing(C.HealthCheckTimeout);return x||this.close(),x}async ping(x=3e4){let A=Date.now();return await this._RequestPing(x)?Date.now()-A:0}sendDatagram(x){if(this._AudioChannel.readyState==="open"){let A=x.byteLength;this._AudioChannel.send(x),this._ConnectionStats.packetsSent+=1,this._ConnectionStats.bytesSent+=A}}_CleanUp(){f(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId),W0(this._AudioChannel),z0(this.webRtc),this._WebRtcSession.cleanup(),this.connection.close()}async _HandleWebRtcUpdates(){for(;;){let x=await this.connection.recv();if(x==="closed")break;x.name==="WebRtcUpdate"&&this._WebRtcSession.handleWebRtcUpdate(x.properties)}this.close()}async _Request(x,A,F){let r=Date.now(),t=await(F===void 0?this.connection.request(x,A):this.connection.request(x,A,F)),j=(Date.now()-r)/1e3;return x!=="Ping"&&f(`sent main rpc '${x}'; took: ${j}s`,{properties:A,timeout:F,result:t}),t==="closed"?(0,d.failure)("connection lost"):t}_RequestPing(x=3e4){return this._PingFlight.run(async()=>{let A=await this._Request("Ping",{},x);return A!=="timeout"&&A.type==="Success"})}async startLocalVideo(x,A,F){await this._WebRtcSession.startLocalVideo(x,A,F)}stopLocalVideo(x){this._WebRtcSession.stopLocalVideo(x)}async startRemoteVideo(x){return this._WebRtcSession.startRemoteVideo(x)}stopRemoteVideo(x){this._WebRtcSession.stopRemoteVideo(x)}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 Q0(D,x,A,F,r){switch(E(`creating ${x} main connection to '${A}'`),x){case"H3":return yx.create(D,A,F,r);case"WebRTC":return _x.create(D,A,F,r);default:throw new Error(`transport ${x} is not supported`)}}var bx=require("@4players/odin-common"),L=require("@4players/odin-common/api");b();var Hx=class{constructor(x,A,F,r){this.id=x;this.connection=A;this.cipher=F;this.mediaMap=r;this._DatagramReceived=0;this._DatagramSent=0;this._DatagramReceivedInvalid=0;this._DatagramSentInvalid=0;A.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(x,A,F,r){this.cipher.reset();let t=await this.cipher.encryptUserData(F);if(t===B)return(0,bx.failure)("unable to encrypt initial user-data");let j=await this.connection.joinRoom(x,A,t,r);return j==="closed"||j.type==="Failure"?j:(0,bx.success)(new v0(j.value,this.cipher,this))}getReconnectToken(x){return this.connection.getReconnectToken(x)}healthCheck(){return this.connection.healthCheck()}async sendDatagram(x){let A=await this.cipher.encryptDatagram(x);A!==B?(this._DatagramSent+=1,this.connection.sendDatagram(A)):this._DatagramSentInvalid+=1}async decryptDatagram(x,A){let F=await this.cipher.decryptDatagram(x,A);return F!==B?this._DatagramReceived+=1:this._DatagramReceivedInvalid+=1,F}startLocalVideo(x,A,F){return this.connection.startLocalVideo(x,A,F)}stopLocalVideo(x){return this.connection.stopLocalVideo(x)}startRemoteVideo(x){return this.connection.startRemoteVideo(x)}stopRemoteVideo(x){return this.connection.stopRemoteVideo(x)}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()}}},Nx=class{constructor(x){this.room=x}resendUserData(){this.room.roomConnection?.notify("UpdatePeer",{user_data:this.room.roomConnection.userData})}setUserData(x,A){let F={kind:"UserDataChanged",peer_id:x,user_data:A};this.room.onEvent("PeerUpdated",F)}},v0=class{constructor(x,A,F){this.rpc=x;this.cipher=A;this.connection=F;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(x,A,F){let r=await this.outgoing(x,A);return r===B?(0,bx.failure)("can not be encrypted"):await this.rpc.request(x,r,F)}async notify(x,A){let F=await this.outgoing(x,A);if(F!==B)return this.rpc.notify(x,F)}async recv(){for(;;){let x=await this.rpc.recv();if(x==="closed")return x;let A=await this.incoming(x.name,x.properties);if(A!==B)return{name:x.name,properties:A}}}close(){return this.rpc.close()}async outgoing(x,A){if(!(x in L.RoomCommandsRpc))return A;let F=(0,L.parseCommand)(x,A,L.RoomCommandsRpc);if(F===void 0)return B;switch(F.name){case"UpdatePeer":{let r=await this.cipher.encryptUserData(F.request.user_data);if(r===B)return B;F.request.user_data=r}break;case"SendMessage":{let r=await this.cipher.encryptMessage(F.request.message);if(r===B)return B;F.request.message=r}break}return F.request}async incoming(x,A){if(!(x in L.RoomNotificationsRpc))return A;let F=(0,L.parseNotification)(x,A,L.RoomNotificationsRpc);if(F===void 0)return B;switch(F.name){case"RoomUpdated":for(let r=0;r<F.properties.updates.length;r++){let t=await this.roomUpdate(F.properties.updates[r]);if(t===B)return B;F.properties.updates[r]=t}break;case"PeerUpdated":{let r=await this.peerUpdate(F.properties);if(r===B)return B;F.properties=r}break;case"MessageReceived":{let r=await this.cipher.decryptMessage(F.properties.sender_peer_id,F.properties.message);if(r===B)return B;F.properties.message=r}break}return F.properties}async peerUpdate(x){switch(x.kind){case"UserDataChanged":{let A=await this.cipher.decryptUserData(x.peer_id,x.user_data);if(A===B)return B;x.user_data=A}break;case"MediaStarted":this.mediaStarted(x.peer_id,x.media.id);break;case"MediaStopped":this.mediaStopped(x.peer_id,x.media_id);break}return x}async roomUpdate(x){switch(x.kind){case"Joined":for(let A of x.room.peers){for(let r of A.medias)this.mediaStarted(A.id,r.id);let F=await this.cipher.decryptUserData(A.id,A.user_data);F!==B?A.user_data=F:A.user_data=new Uint8Array}break;case"PeerJoined":{for(let F of x.peer.medias)this.mediaStarted(x.peer.id,F.id);let A=await this.cipher.decryptUserData(x.peer.id,x.peer.user_data);A!==B?x.peer.user_data=A:x.peer.user_data=new Uint8Array}break;case"PeerLeft":{let A=this.peers.get(x.peer_id);this.peers.delete(x.peer_id),this.cipher.deletePeerKey(x.peer_id);for(let F of A??[])this.mediaStopped(x.peer_id,F)}break}return x}mediaStarted(x,A){let F=this.peers.get(x);F===void 0&&(F=new Set,this.peers.set(x,F)),F.add(A);let r=k({connectionId:this.connection.connection.id,mediaId:A});this.connection.mediaMap.set(r,{peerId:x,connection:this.connection})}mediaStopped(x,A){this.peers.get(x)?.delete(A);let r=k({connectionId:this.connection.connection.id,mediaId:A});this.connection.mediaMap.delete(r)}cleanup(){for(let[x,A]of this.peers)for(let F of A)this.mediaStopped(x,F)}};var Kx=class{constructor(x){this.onDatagram=x;this._LastConnectionId=0;this._Connections=new Map;this._Close=new AbortController;this._MediaMap=new Map;let A=Date.now(),F=setInterval(()=>{Math.abs(Date.now()-A)>C.ClockJumpThreshold&&this.checkHealth(),A=Date.now()},C.ClockJumpCheckInterval);addEventListener("offline",()=>this.checkHealth(),{signal:this._Close.signal}),this._Close.signal.addEventListener("abort",()=>{clearInterval(F);for(let r of this._Connections.values())r.type==="establishing"?r.abort.abort():r.connection.close();this._Connections.clear()},{once:!0})}get closed(){return this._Close.signal.aborted}sendDatagram(x,A){let F=this._Connections.get(x);(F?.type==="established"||F?.type==="virtual")&&F.connection.sendDatagram(A)}async recvDatagram(x,A){let F=BF(A);if(F===void 0||F.length===0)return;let r=this._MediaMap.get(k({connectionId:x,mediaId:F[0]}));if(r===void 0)this.onDatagram(x,A);else{let t=await r.connection.decryptDatagram(r.peerId,A);if(t===B)return;this.onDatagram(r.connection.id,t)}}async acquireConnection(x,A,F,r){if(await(0,ox.nextTick)(),this.closed)return"closed";let t=this.findConnection(x,A),j;switch(t?.type){case"established":f(`reusing existing connection ${t.id}`),j=t;break;case"establishing":{f(`waiting for connecting to '${A}' finish`);let n=await t.finished;if(n.type!=="Success")return n;j=n.value}break;case void 0:{f(`connecting to '${A}'`);let n=await this.createConnection(x,A,r);if(n.type!=="Success")return n;j=n.value}break}let e=j.id,v=new C0(j.connection,()=>this.releaseConnection(e));return j.references+=1,F&&(v=new Hx(++this._LastConnectionId,v,F,this._MediaMap),this.addConnection({type:"virtual",id:v.id,connection:v,createdAt:Date.now()})),(0,ox.success)(v)}async createConnection(x,A,F){let r=++this._LastConnectionId,t=Date.now(),j=new AbortController;F.addEventListener("abort",()=>j.abort(),{once:!0}),f(`creating new connection ${r}`);let e=Q0(r,x,A,this.recvDatagram.bind(this),F),{promise:v,resolve:n}=Promise.withResolvers();this.addConnection({type:"establishing",id:r,address:A,transport:x,finished:v,createdAt:Date.now(),abort:j});let p=await e;if(this._Connections.delete(r),p.type!=="Success")return n(p),p;let H={type:"established",id:r,address:A,transport:x,createdAt:t,references:0,connection:p.value};return this.addConnection(H),(0,ox.success)(H)}addConnection(x){(x.type==="established"||x.type==="virtual")&&x.connection.closeSignal.addEventListener("abort",()=>{E(`connection ${x.id} has been closed`),this._Connections.delete(x.id)},{once:!0}),this._Connections.set(x.id,x)}releaseConnection(x){let A=this._Connections.get(x);A?.type==="established"&&(A.references-=1,A.references<=0&&A.connection.close())}checkHealth(){for(let x of this._Connections.values())x.type==="established"&&x.connection.healthCheck()}close(){this._Close.abort()}async dump(){let x=[];for(let F of this._Connections.values()){let r;switch(F.type){case"established":r={transport:F.transport,address:F.address,connection:await F.connection.dump(),references:F.references};break;case"establishing":r={transport:F.transport,address:F.address,aborted:F.abort.signal.aborted};break;case"virtual":r={connection:await F.connection.dump()};break}x.push({type:F.type,id:F.id,createdAt:F.createdAt,...r})}let A=[];for(let[F,r]of this._MediaMap)A.push(`${F} -> ${r.peerId} @${r.connection.id} `);return{lastConnectionId:this._LastConnectionId,connections:x,mediaMap:A,closed:this.closed}}findConnection(x,A){for(let F of this._Connections.values())if(F.type!=="virtual"&&F.transport===x&&F.address===A)return F}},C0=class{constructor(x,A){this.connection=x;this.release=A;this.closeController=new AbortController;this.closePromise=new Promise(x=>this.closeController.signal.addEventListener("abort",()=>x("closed"),{once:!0}));x.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(x,A,F,r){return this.connection.joinRoom(x,A,F,r)}getReconnectToken(x){return this.connection.getReconnectToken(x)}healthCheck(){return this.connection.healthCheck()}sendDatagram(x){return this.connection.sendDatagram(x)}startLocalVideo(x,A,F){return this.connection.startLocalVideo(x,A,F)}stopLocalVideo(x){return this.connection.stopLocalVideo(x)}startRemoteVideo(x){return this.connection.startRemoteVideo(x)}stopRemoteVideo(x){return this.connection.stopRemoteVideo(x)}async dump(){let x=await this.connection.dump();return typeof x=="object"&&(x={...x,isShared:!0,referenceClosed:this.closed}),x}};function BF(D){let x;try{x=(0,Y0.decode)(D)}catch{return}if(!Array.isArray(x)||x.length<2)return;let A=x[1];if(Array.isArray(A))return A.map(Number)}var wx=require("@4players/odin-common"),J=class{constructor(x,A){this.uid=x;this.customType=A}#x;#A;get mediaStream(){return this.#x}get audioPlayback(){return(0,wx.assert)(this.#A,"getting the audioPlayback failed, this video has no Audio"),this.#A}get volume(){return(0,wx.assert)(this.audioPlayback,"getting the volume failed, this video has no Audio"),this.audioPlayback.volume}setVolume(x){(0,wx.assert)(this.#A,"Can not set the volume, this video has no Audio"),this.#A.setVolume(x)}setMediaStream(x){this.mediaStream||(this.#x=x)}close(){this.#x?.getVideoTracks().forEach(x=>{x.stop(),this.#x?.removeTrack(x)}),this.#x=void 0}};var M=require("@4players/odin-common"),iA=require("@4players/odin-common/api");var i=require("@4players/odin-common"),P=require("@4players/odin-common/api");b();var Jx=class{constructor(x,A,F,r,t,j,e,v,n,p){this.connectionPool=x;this.transport=A;this.onEvent=F;this.gateway=r;this.roomId=j;this.cipher=n;this.disableAutoReconnect=p;this._Close=new AbortController;this._TokenUsed=!1;this._WasConnected=!1;this._FailedConnections=0;this._LastTokenRenew=performance.now();this._LastReconnectStartedAt=0;this._Closed=new Promise(x=>this._Close.signal.addEventListener("abort",()=>x(this._Close.signal.reason?"disconnected":"closed"),{once:!0}));this._Token=t,this._UserData=e,this._Position=v,this._Main().then(({reason:H})=>f(`_Main() resolved; ${H}`))}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(x,A){if(this._RoomConnection===void 0)return(0,i.failure)("currently not connected");let F=await this._RoomConnection.request(x,A,void 0);return(0,i.assert)(F!=="timeout","request should not timeout"),F!=="closed"&&F.type==="Success"&&this._HandleRequests(x,A,F.value),F}async request(x,A){let F=Date.now(),r=P.RoomCommandsRpc[x],t=await this.requestUnsafe(x,A),j=(Date.now()-F)/1e3;if(f(`sent room rpc '${x}'; took: ${j}s`,{properties:A,result:t}),t==="closed"||t.type==="Failure")return t;let e=(0,P.parseResponse)(x,t.value,P.RoomCommandsRpc);return e!==void 0?(0,i.success)(e):(0,i.failure)(`received invalid response from ${x}`)}notify(x,A){this._RoomConnection!==void 0&&this._RoomConnection.notify(x,A)}close(){this._Close.abort(!0)}get renewTokenIn(){let x=this._LastTokenRenew-performance.now()+C.MinTokenRefreshInterval,A=this._Token.timeLeft-C.MinTokenLifetime;return Math.max(x,A)}async _Main(){let x="unable to establish connection";for(let A=0;;this._FailedConnections++){if(await(0,i.sleep)(Math.max(A-performance.now(),0)),this._Close.signal.aborted||this.connectionPool.closed){x="user requested";break}if(A=performance.now()+1e3,this._TokenUsed=!0,this._Token.hasAudience("sfu")){let F=await this._ConnectToServer();if(F.type==="Success"&&F.value==="shutdown"){f("connection closed by user request; shutting down"),x="user requested";break}if(this.disableAutoReconnect&&this._WasConnected){x=F.type==="Failure"?F.reason:"connection lost";break}if(this._LastReconnectStartedAt===0&&(this._LastReconnectStartedAt=performance.now()),F.type==="Failure"&&!this._WasConnected&&this._FailedConnections>=3){x=F.reason;break}if(F.type==="Failure"&&!CF(this._LastReconnectStartedAt))continue}if(this.reset(),this._Close.signal.aborted||this.connectionPool.closed){x="user requested";break}if(this.gateway!==void 0&&this._Token.hasAudience("gateway")){this._ChangeStatus("Joining",`requesting new token from ${this.gateway}`);let F=await vF(this.gateway,this._Token,this._Close.signal);if(F.type==="Success")if(F.value instanceof I)A=0,this._Token=F.value,this._TokenUsed=!1;else{x=`gateway error; ${F.value}`;break}else if(!this._WasConnected&&this._FailedConnections>=3){x="unable to contact the gateway";break}}if(this._TokenUsed&&this._Token.timeLeft<=0){x="token has expired";break}if(this._Close.signal.aborted||this.connectionPool.closed){x="user requested";break}}return this._ChangeStatus("Closed",x),this.close(),(0,i.failure)(x)}async _ConnectToServer(){let x=this._Token;for(;x.upstream!==void 0;)x=x.upstream;let A=x.claims.adr??this.gateway?.toString();if(!A)return(0,i.success)("continue");if(this._ChangeStatus("Joining",`connecting to ${x.claims.adr}`),this._MainConnection===void 0||this._MainConnection.closed||this._MainConnection.address!==x.claims.adr){this._MainConnection?.close();let t=await this.connectionPool.acquireConnection(this.transport,A,this.cipher,this._Close.signal);if(t==="closed")return(0,i.failure)("connection pool closed");if(t.type==="Failure")return this._ChangeStatus("Joining",`connection failed; ${t.reason}`),(0,i.failure)(`connection failed; ${t.reason}`);this._MainConnection=t.value,this._OwnPeerId=void 0}let F=await Promise.race([Promise.all([this._MainConnection.joinRoom(x,this.roomId,this.userData,this.position)]),(0,i.sleep)(C.ConnectTimeout,"timeout"),this._Closed]);if(F==="closed"||F==="disconnected")return(0,i.success)("continue");if(F==="timeout")return this._ChangeStatus("Joining","timed out"),(0,i.success)("continue");let[r]=F;if(r==="closed")return(0,i.success)("continue");if(r.type==="Failure")return(0,i.failure)(`unable to join room; ${r.reason}`);this._RoomConnection=r.value,this._WasConnected=!0,this._FailedConnections=0,this._ChangeStatus("Joined",`joined ${this.roomId}`);try{await this._MainConnection.waitForConnected();let t=await this._HandleConnection(this._MainConnection);return(0,i.success)(t?"shutdown":"continue")}catch(t){return(0,i.failure)(`unable to handle connection; ${t}`)}}_ChangeStatus(x,A){let F={status:x,message:A};this.onEvent("RoomStatusChanged",F)}async _HandleConnection(x){if(this._RoomConnection===void 0)return!1;let A=new i.Selector([()=>(0,i.sleep)(this.renewTokenIn,"renewToken"),()=>(0,i.sleep)(500,"tick"),async()=>await this._RoomConnection?.recv(),()=>this._Closed,()=>x.closePromise]);for(;;){let F=await A.next();switch(F){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(F);break}}}_HandleEvent(x){if(x.name==="RoomUpdated"){let A=P.RoomNotificationsRpc.RoomUpdated.safeParse(x.properties);if(!A.success)return;for(let F of A.data.updates)F.kind==="Joined"&&(this._OwnPeerId=F.own_peer_id)}this.onEvent(x.name,x.properties)}_HandleRequests(x,A,F){switch(x){case"SetPeerPosition":{let r=P.RoomCommandsRpc.SetPeerPosition.request.safeParse(A);if(r.success){let t=r.data.position;this._Position=t.length===2?[t[0],t[1],0]:t}else c("unable to process SetPeerPosition command");break}case"UpdatePeer":{let r=P.RoomCommandsRpc.UpdatePeer.request.safeParse(A);r.success?this._UserData=r.data.user_data:c("unable to process UpdatePeer command");break}}}async _RenewToken(x){if(this._LastTokenRenew=performance.now(),!x&&this.token.timeLeft>C.MinTokenLifetime)return;if(this._MainConnection===void 0||this._OwnPeerId===void 0)return(0,i.failure)("connection is not established");let A=await this._MainConnection.getReconnectToken(this._OwnPeerId);return A.type==="Success"?(this._Token=A.value,(0,i.success)()):(0,i.failure)(`${this._MainConnection.address} rejected reconnect token request; ${A.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 vF(D,x,A){try{let F={jsonrpc:"2.0",id:1,method:"Connect",params:{}};E(`sending authentication request to '${D}'`,F);let t=await(await fetch(D,{body:JSON.stringify(F),method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${x}`},signal:A})).json();if(E(`received authentication response fom '${D}'`,t),"result"in t)return I.parse(t.result.token);{let j=t.error?.message??"malformed response";return a(`gateway rejected token; ${j}`),(0,i.success)(j)}}catch(F){return(0,i.failure)(String(F))}}function CF(D,x=8e3){return performance.now()-D>x}b();var nA=require("@4players/odin-common");var z=require("@4players/odin-common");b();var BA=require("@4players/odin-common");b();var jA=require("@msgpack/msgpack");b();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=D=>({name:"PBKDF2",hash:"SHA-256",iterations:600,salt:D}),AA=32,FA=1e6,rA=2147483648,DA=32,O=[79,68,73,78,1,75,105,109],Ex=16,fx=64,tA=16;function eA(D,x){if(D.length!==x.length)return!1;for(let A=0;A<D.length;A++)if(D[A]!==x[A])return!1;return!0}function EF(D){return isFinite(D)}function fF(D){return Array.isArray(D)}function Px(D){return EF(D)?D:B}function ax(D){return D instanceof Uint8Array?D:B}function nF(D,...x){let A;try{A=(0,jA.decode)(D)}catch{return B}if(!fF(A))return B;let F=new Array(A.length);for(let r in x)if(F[r]=x[r](A[r]),F[r]===B)return B;return F}function Ox(D,...x){if(D.length<O.length)return h;for(let A=0;A<O.length;A++)if(D[A]!==O[A])return h;return nF(D.subarray(O.length),...x)}var nx=class{constructor(x){this.first=1;this.offset=0;this.window=Array(x)}isReplay(x){let A=x-this.first;if(A<0)return!0;if(A>=this.window.length)if(A<this.window.length*2){let t=A-this.window.length+1;A-=t;for(let j=0;j<t;j++)this.advance()}else return this.first=x+1-self.window.length,this.offset=0,this.window.fill(!1),!1;let F=(this.offset+A)%this.window.length,r=this.window[F]===!0;for(this.window[F]=!0;this.window[this.offset]===!0;)this.advance();return r}advance(){this.window[this.offset]=!1,this.first+=1,this.offset=(this.offset+1)%this.window.length}};var Mx=class D{constructor(x){this.key=x}static async create(x){typeof x=="string"&&(x=new TextEncoder().encode(x));let A=await globalThis.crypto.subtle.importKey("raw",x,"PBKDF2",!1,["deriveBits"]),F=await globalThis.crypto.subtle.deriveBits(Z0,A,256),r=await globalThis.crypto.subtle.importKey("raw",F,"PBKDF2",!1,["deriveKey"]);return new D(r)}async generatePeerKey(x,A){return await globalThis.crypto.subtle.deriveKey(xA(x),this.key,{name:"AES-GCM",length:256},!1,[A])}},Tx=class D{constructor(x,A){this.seed=x;this.key=A;this.sequenceNumbers={datagram:1,message:1,userData:1};this.number_of_packets=0;this.number_of_bytes=0}static async create(x){let A=globalThis.crypto.getRandomValues(new Uint8Array(AA)),F=await x.generatePeerKey(A,"encrypt");return new D(A,F)}get limitReached(){return this.key===void 0?!1:this.number_of_bytes>=rA||this.number_of_packets>=FA}nextSequenceNumber(x){return this.sequenceNumbers[x]++}};function E0(D,x){return{kind:"encrypted",key:D,material:x,antiReplays:{datagram:new nx(DA),userData:new nx(0),message:new nx(0)}}}var Sx=class D{constructor(x,A,F,r){this.additionalData=x;this.sequenceNumber=A;this.seed=F;this.encrypted=r}static parse(x){let A=Ox(x,ax,Px,ax);if(A===B||A===h)return A;let[F,r,t]=A,j=x.subarray(0,x.length-t.length);return new D(j,r,F,t)}isSameSeed(x){return eA(this.seed,x.seed)}async generateKey(x){return await x.generatePeerKey(this.seed,"decrypt")}};function Rx(D,x){let A=new Uint8Array(12);switch(A[0]=x&255,A[1]=x>>8&255,A[2]=x>>16&255,A[3]=x>>24&255,D){case"datagram":A[5]=1;break;case"userData":A[5]=2;break;case"message":A[5]=3;break;default:(0,BA.assert)(!1,"missing content implementation")}return A}var f0=require("@msgpack/msgpack"),CA=require("@4players/odin-common");b();var Vx=class{constructor(x){this.actions=x}changeKey(x){this.masterKey!==x&&(this.masterKey=x,this.ownKey=B,this.actions.resendUserData())}async encryptDatagram(x){let A=await this.getKey("datagram");return A===void 0?x:A===T?B:await bF(A,x)}async encryptMessage(x){let A=await this.getKey("message");return A===void 0?x:A===T?T:await vA(A,x,"message")}async encryptUserData(x){let A=await this.getKey("userData");return A===void 0?x:((0,CA.assert)(A!==T,"key unavailable for user data encryption"),await vA(A,x,"userData",A.seed))}async getKey(x){if(this.ownKey===B||this.ownKey?.limitReached)if(x==="userData")this.ownKey=this.masterKey?await Tx.create(this.masterKey):void 0;else return this.ownKey!==B&&(this.ownKey=B,this.actions.resendUserData()),T;return this.ownKey}reset(){this.ownKey=this.masterKey?B:void 0}};async function vA(D,x,A,...F){let r=D.nextSequenceNumber(A),t=x.length+Ex,j=iF(r,F,t),e=j.length-t,v=await EA(D,A,r,j.subarray(0,e),x);return j.set(new Uint8Array(v),e),j}function iF(D,x,A){let F=[];x.forEach(j=>F.push(j)),F.push(D),F.push(new Uint8Array(A));let r=(0,f0.encode)(F),t=new Uint8Array(O.length+r.length);return t.set(O,0),t.set(r,O.length),t}async function bF(D,x){let A=oF(x);if(A===B)return B;if((A.kind&fx)!==0)return B;let F=A.body.length+Ex,r=D.nextSequenceNumber("datagram"),t=(0,f0.encode)([A.kind|fx,A.mediaIds,r,new Uint8Array(F)]),j=t.length-F,e=await EA(D,"datagram",r,t.subarray(0,j),A.body);return t.set(e,j),t}async function EA(D,x,A,F,r){return new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:Rx(x,A),additionalData:F,tagLength:Ex*8},D.key,r))}function oF(D){let x=new S(D),A=x.readArrayLength();if(s(A)||A<2)return B;let F=x.readNumber(),r=x.readArrayLength();if(s(F)||s(r))return B;if(r>tA)return B;let t=Array(r);for(let e=0;e<t.length;e++){let v=x.readNumber();if(s(v))return B;t[e]=v}let j=D.subarray(x.position);return{kind:F,mediaIds:t,body:j}}var fA=require("@msgpack/msgpack");b();var Wx=class{constructor(x){this.actions=x;this.peerKeys=new Map}async changeKey(x){this.masterKey=x;for(let[A,{kind:F,material:r}]of this.peerKeys)if(x!==void 0){let t=await r.generateKey(x),j=E0(t,r),e=await Ux(j,"userData",r.additionalData,r.sequenceNumber,r.encrypted);e!==B?(this.peerKeys.set(A,j),this.actions.setUserData(A,e)):(this.peerKeys.set(A,{kind:"broken",material:r}),this.actions.setUserData(A,new Uint8Array))}else F==="encrypted"&&this.peerKeys.set(A,{kind:"broken",material:r})}async decryptDatagram(x,A){let F=aF(A);if(this.masterKey===void 0)return F===h?A:B;if(F===B||F===h)return B;let r=this.peerKeys.get(x);if(r?.kind!=="encrypted")return B;let t=await Ux(r,"datagram",F.additionalData,F.sequenceNumber,F.encrypted);return t===B?B:lF(F.kind&~fx,F.mediaIds,t)}async decryptMessage(x,A){let F=Ox(A,Px,ax);if(this.masterKey===void 0)return F===h?A:B;if(F===B||F===h)return B;let r=this.peerKeys.get(x);if(r?.kind!=="encrypted")return B;let[t,j]=F,e=A.subarray(0,A.length-j.length);return Ux(r,"message",e,t,j)}async decryptUserData(x,A){let F=Sx.parse(A);if(F===B)return B;if(F===h)return this.peerKeys.delete(x),this.masterKey===void 0?A:B;if(this.masterKey===void 0)return this.peerKeys.set(x,{kind:"broken",material:F}),B;let r=this.peerKeys.get(x);if(r?.kind==="encrypted"&&r.material.isSameSeed(F))r.material=F;else{let j=await F.generateKey(this.masterKey);r=E0(j,F)}let t=await Ux(r,"userData",F.additionalData,F.sequenceNumber,F.encrypted);return t===B?this.peerKeys.set(x,{kind:"broken",material:F}):r!==void 0&&this.peerKeys.set(x,r),t}reset(){this.peerKeys.clear()}};function aF(D){let x=new S(D),A=x.readArrayLength();if(s(A)||A<1)return B;let F=x.readNumber();if(s(F))return B;if((F&fx)===0)return h;if(A!==4)return B;let r=x.position;x.readObjects(1);let t=D.subarray(r,x.position),j=x.readNumber(),e=x.readBytes();if(s(j)||s(e))return B;let v=D.subarray(0,D.length-e.length);return{kind:F,mediaIds:t,additionalData:v,sequenceNumber:j,encrypted:e}}async function Ux(D,x,A,F,r){let t=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:Rx(x,F),additionalData:A,tagLength:Ex*8},D.key,r).catch(()=>B);return t===B?B:D.antiReplays[x].isReplay(F)?B:new Uint8Array(t)}function lF(D,x,A){let F=2;try{let j=new S(A);for(j.position=0;j.position<A.length;)j.readObjects(1),F+=1}catch{return B}let r=(0,fA.encode)(D),t=new Uint8Array(3+r.length+x.length+A.length);return t[0]=220,t[1]=F>>8&255,t[2]=F&255,t.set(r,3),t.set(x,3+r.length),t.set(A,3+r.length+x.length),t}var zx=class{constructor(x,A){this.active=!1;let F=new Wx(A),r=new Vx(A);this.crypto=new z.Strand({encryption:r,decryption:F}),this.peerKeys=F.peerKeys,this.configure(x)}encryptUserData(x){return this.crypto.enqueue(({encryption:A})=>A.encryptUserData(x))}async encryptMessage(x){let A;do A=await this.crypto.enqueue(({encryption:F})=>F.encryptMessage(x));while(A===T);return A}async encryptDatagram(x){return await this.crypto.enqueue(({encryption:A})=>A.encryptDatagram(x))}decryptUserData(x,A){return this.crypto.enqueue(({decryption:F})=>F.decryptUserData(x,A))}decryptMessage(x,A){return this.crypto.enqueue(({decryption:F})=>F.decryptMessage(x,A))}decryptDatagram(x,A){return this.crypto.enqueue(({decryption:F})=>F.decryptDatagram(x,A))}configure(x){return this.crypto.enqueue(async A=>{let F=x.password?await Mx.create(x.password):void 0;this.active=F!==void 0,await A.encryption.changeKey(F),await A.decryption.changeKey(F)})}getPeerStatus(x){switch(this.peerKeys.get(x)?.kind??"unencrypted"){case"broken":return z.Backend.PeerCipherStatus.InvalidPassword;case"encrypted":return z.Backend.PeerCipherStatus.Encrypted;case"unencrypted":return this.active?z.Backend.PeerCipherStatus.InvalidPassword:z.Backend.PeerCipherStatus.Unencrypted;default:return z.Backend.PeerCipherStatus.Unknown}}deletePeerKey(x){this.peerKeys.delete(x)}reset(){return this.crypto.enqueue(async({encryption:x,decryption:A})=>{x.reset(),A.reset()})}async dump(){return this.crypto.enqueue(async()=>({active:this.active,peers:Array.from(this.peerKeys).map(([x,A])=>`${x} => ${A.kind}`)}))}};function sA(D,x){return(0,nA.assert)(D.type==="OdinCrypto","only OdinCrypto supported"),new zx(D,x)}var Xx=class{constructor(x,A,F){this._Captures=new Map;this._Playbacks=new Map;this._Peers=new Map;this._AvailableMediaIds=[];let{url:r,onEvent:t}=A,j=(0,M.unwrap)(I.parse(A.token)),e=A.roomId??j.defaultRoomId,v=A.userData??new Uint8Array(0),n=A.position??[0,0,0];(0,M.assert)(e!==void 0,"room id required for multi-room-tokens"),this.cipher=A.cipher?sA(A.cipher,new Nx(this)):void 0,this.onEvent=t,E(`creating new room '${e}' ${this.cipher?"with":"without"} cipher`,j,v,n),this._Connection=new Jx(x,A.transport??"H3",this._HandleEvent.bind(this),r?new URL(r):void 0,j,e,v,n,this.cipher,F?.disableAutoReconnect??!1)}get connectionStats(){let x={...M.CONNECTION_STATS_INITIAL};return this.mainConnection?this.mainConnection.connectionStats:x}get roomConnection(){return this._Connection}get mainConnection(){return this.roomConnection?.mainConnection}get token(){return this._Connection.token.text}request(x,A){return this._Connection.requestUnsafe(x,A)}async link(x){if(x instanceof y){let A=this._Playbacks.get(x.uid)??{media:void 0,playback:void 0};A.playback!==void 0&&this.unlink(A.playback),A.media!==void 0&&x.start(A.media),A.playback=x,E(`linking audio playback media '${x.uid}' with volume ${x.volume} to room '${this._Connection.roomId}'`),this._Playbacks.set(x.uid,A)}else if(x instanceof K){let A=this._Captures.get(x);A&&this.unlink(x);let F=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();A={media:F?{connectionId:this.mainConnection.id,mediaId:F}:void 0},E(`linking audio capture media '${x.uid}' with volume ${x.volume} to room '${this._Connection.roomId}'`),this._Captures.set(x,A),A.media!==void 0&&await x.start(this._Connection,A.media)}else if(x instanceof J){let A=this._Playbacks.get(x.uid)??{media:void 0,playback:void 0};if(A.playback!==void 0&&this.unlink(A.playback),A.media!==void 0){let F=await this.mainConnection?.startRemoteVideo(A.media.mediaId);F&&x.setMediaStream(new MediaStream([F]))}A.playback=x,E(`linking video playback media '${x.uid}' with type '${x.customType}' to room '${this._Connection.roomId}'`),this._Playbacks.set(x.uid,A)}else if(x instanceof G){let A=this._Captures.get(x);A&&this.unlink(x);let F=x.mediaStream?.getVideoTracks()[0];if(F){let r=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();A={media:r?{connectionId:this.mainConnection.id,mediaId:r}:void 0},E(`linking video capture media '${x.uid}' with type '${x.parameters?.customType}' to room '${this._Connection.roomId}'`),this._Captures.set(x,A),A.media!==void 0&&(await x.start(this._Connection,A.media),this.mainConnection?.startLocalVideo(A.media.mediaId,F,x.parameters)),x.audioCapture&&await this.link(x.audioCapture)}}else throw new Error("Linking failed, media was not supported")}unlink(x){if(x instanceof y||x instanceof J){let A=this._Playbacks.get(x.uid);if(A?.playback!==x)return;A.playback=void 0,A.media!==void 0&&(x instanceof y?x.stop(A.media):(this.mainConnection?.stopRemoteVideo(A.media.mediaId),x.setMediaStream(void 0))),E(`unlinking playback media '${x.uid}' from room '${this._Connection.roomId}'`),this._Playbacks.set(x.uid,A)}else if(x instanceof K||x instanceof G){x instanceof G&&x.audioCapture&&this.unlink(x.audioCapture);let A=this._Captures.get(x);if(A===void 0)return;A.media!==void 0&&(x.stop(this._Connection,A.media),this._AvailableMediaIds.push(A.media.mediaId),x instanceof G&&this.mainConnection?.stopLocalVideo(A.media.mediaId)),E(`unlinking capture media '${x.uid}' from room '${this._Connection.roomId}'`),this._Captures.delete(x)}else throw new Error("invalid media")}close(){E(`closing room '${this._Connection.roomId}'`),this._Connection.close()}_HandleEvent(x,A){let F=e0(iA.RoomNotificationsRpc,{name:x,properties:A});F!==void 0&&(this._HandleKnownEvent(F),A=F.properties),this.onEvent(x,A)}_HandleKnownEvent(x){switch(f(`processing event '${x.name}'`,x.properties),x.name){case"RoomStatusChanged":x.properties.status!=="Joined"&&this._HandleConnectionLost();break;case"RoomUpdated":for(let A of x.properties.updates)this._HandleRoomUpdate(A);break;case"PeerUpdated":this._HandlePeerUpdate(x.properties);break}}_HandleConnectionLost(){for(let x of this._Peers.keys())this._HandlePeerLeft(x);for(let[x,A]of this._Captures)A.media!==void 0&&(x instanceof G,x instanceof K&&(x.stop(this._Connection,A.media),A.media=void 0));this._AvailableMediaIds.length=0}_HandleRoomUpdate(x){if(x.kind==="Joined"){(0,M.assert)(this._AvailableMediaIds.length===0,"left over media ids"),this._AvailableMediaIds.push(...x.media_ids),this._HandleRoomJoined();for(let A of x.room.peers)this._HandlePeerJoined(A)}else x.kind==="PeerJoined"?this._HandlePeerJoined(x.peer):x.kind==="PeerLeft"&&this._HandlePeerLeft(x.peer_id)}_HandleRoomJoined(){for(let[x,A]of this._Captures)this._AvailableMediaIds.length===0||this.mainConnection===void 0||(A.media={connectionId:this.mainConnection.id,mediaId:this._AvailableMediaIds.shift()},x instanceof K&&x.start(this._Connection,A.media),x instanceof G)}_HandlePeerUpdate(x){x.kind==="MediaStarted"?this._HandleMediaStart(x.peer_id,x.media):x.kind==="MediaStopped"&&this._HandleMediaStopped(x.peer_id,x.media_id)}_HandlePeerJoined(x){this._Peers.has(x.id)||this._Peers.set(x.id,{mediaIds:new Map});for(let A of x.medias)this._HandleMediaStart(x.id,A)}_HandlePeerLeft(x){let A=this._Peers.get(x);if(A!==void 0){for(let F of A.mediaIds.keys())this._HandleMediaStopped(x,F);this._Peers.delete(x)}}_HandleMediaStart(x,A){if(this.mainConnection===void 0)return;let F=this._Peers.get(x);if(F===void 0||A.properties.kind!=="audio"&&A.properties.kind!=="video")return;let r=String(A.properties.uid??(0,M.generateUUID)());A.properties.uid=r;let t=this._Playbacks.get(r)??{media:void 0,playback:void 0};this._Playbacks.set(r,t),F.mediaIds.set(A.id,r),t.media={connectionId:this.mainConnection.id,mediaId:A.id},t.playback!==void 0&&(t.playback instanceof y&&t.playback.start(t.media),t.playback instanceof J&&this.mainConnection.startRemoteVideo(t.media.mediaId).then())}_HandleMediaStopped(x,A){let F=this._Peers.get(x);if(F===void 0)return;let r=F?.mediaIds.get(A);if(r===void 0)return;let t=this._Playbacks.get(r);t!==void 0&&(t.media!==void 0&&t.playback!==void 0&&(t.playback instanceof y&&t.playback.stop(t.media),t.playback instanceof J&&this.mainConnection?.stopRemoteVideo(t.media.mediaId)),t.media=void 0,F.mediaIds.delete(A))}};px();function kF(D,x){m0(x?.logger,x?.onLogMessage);let A,F=new Kx((t,j)=>A.receivePacket(t,j)),r=new Gx(D);return A=new Ix(r,F.sendDatagram.bind(F)),new n0(F,A,x)}var ix=(0,uF.generateUUID)(),s0=[],bA=!1;function cF(){bA||typeof window>"u"||(window.addEventListener("beforeunload",()=>{for(let D of s0)D.deref()?.close()}),bA=!0)}var n0=class{constructor(x,A,F){this.version="9";this.supportedTransports=["H3","WebRTC"];this._PlaybackVolume=[1,1];this._CreatedAt=Date.now();this._Options=F??{},this._Options.disableBeforeUnload||cF(),this._ConnectionPool=x,this._MediaController=A,s0.push(new WeakRef(this)),E("plugin initialized")}get playbackVolume(){return this._PlaybackVolume}joinRoom(x){return new Xx(this._ConnectionPool,x,this._Options)}async createAudioPlayback(x){return this._MediaController.createAudioPlayback(x)}async createAudioCapture(x){return this._MediaController.createAudioCapture(x)}async createVideoCapture(x,A){return this._MediaController.createVideoCapture(x,A)}async createVideoPlayback(x){return new J(x.uid,x.customType)}enumerateDevices(){return dx()}setOutputVolume(x){this._MediaController.playbackSetGlobalVolume(x)}async setOutputDevice(x){await this._MediaController.playbackSetDevice(x.device)}close(){this._MediaController.close(),this._ConnectionPool.close(),E("plugin closed")}async dump(){return{createdAt:this._CreatedAt,connections:await this._ConnectionPool.dump(),medias:await this._MediaController.dump()}}};async function oA(){let D=[];for(let x of s0){let A=x.deref();A!==void 0&&D.push(await A.dump())}return JSON.stringify({timestamp:Date.now(),instances:D,background:await g0()})}globalThis.odin_debug_dump_state=oA;window!==void 0&&(window.odin_debug_dump_state=oA);0&&(module.exports={SESSION_ID,createPlugin});