@4players/odin-plugin-web 1.15.4 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/plugin/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var x0=Object.defineProperty;var hA=Object.getOwnPropertyDescriptor;var mA=Object.getOwnPropertyNames;var qA=Object.prototype.hasOwnProperty;var p=(D,x,A)=>()=>{if(A)throw A[0];try{return D&&(x=D(D=0)),x}catch(F){throw A=[F],F}};var kx=(D,x)=>{for(var A in x)x0(D,A,{get:x[A],enumerable:!0})},GA=(D,x,A,F)=>{if(x&&typeof x=="object"||typeof x=="function")for(let r of mA(x))!qA.call(D,r)&&r!==A&&x0(D,r,{get:()=>x[r],enumerable:!(F=hA(x,r))||F.enumerable});return D};var $A=D=>GA(x0({},"__esModule",{value:!0}),D);var C={};kx(C,{AdditionalCaptureBlocks:()=>gA,AdditionalPlaybackBlocks:()=>yA,ClockJumpCheckInterval:()=>wA,ClockJumpThreshold:()=>OA,ConnectInterval:()=>QA,ConnectTimeout:()=>KA,DefaultRefreshRate:()=>_A,DefaultVideoCodec:()=>zA,HealthCheckTimeout:()=>PA,MainConnectionPingInterval:()=>JA,MaxNumberOfDecoders:()=>HA,MaxReconnectDuration:()=>XA,MinDBFs:()=>A0,MinTokenLifetime:()=>VA,MinTokenRefreshInterval:()=>WA,PlaybackPreload:()=>IA,RenderQuantumSize:()=>NA,VadPreload:()=>LA,WebRtcAnswerTimeout:()=>MA,WebRtcIceTimeout:()=>SA,WebRtcMaxNegotiationAttempts:()=>UA,WebRtcStatsSnapshotInterval:()=>RA,WebRtcTimeout:()=>TA});var yA,gA,IA,_A,LA,HA,NA,A0,PA,wA,OA,JA,RA,SA,TA,MA,UA,KA,VA,WA,QA,XA,zA,F0=p(()=>{"use strict";yA=3,gA=3,IA=3,_A=250,LA=3,HA=512,NA=128,A0=-758.596,PA=1e4,wA=1e3,OA=1e4,JA=3e3,RA=1e3,SA=3e3,TA=1e4,MA=1e4,UA=3,KA=5e3,VA=6e4,WA=5e3,QA=[0,100,200,200,500],XA=12e4,zA="H264"});function dx(D){return typeof D!="symbol"}function s(D){return typeof D=="symbol"}var m,v,M,q,px=p(()=>{"use strict";m=Symbol("Unencrypted"),v=Symbol("Invalid"),M=Symbol("Retry"),q=Symbol("UnexpectedEof")});function a(D,x,A){return D.postMessage(x,A)}function Fx(D,x){return new Promise(A=>{let F=r=>{let[t]=r.data;t===x&&(A(r.data[1]),D.removeEventListener("message",F))};D.addEventListener("message",F)})}var c0=p(()=>{"use strict"});function r0(D,x){D.values[0]=x[0],D.values[1]=x[1]}function k0(D,x){return D.values[2+x*5]}function d0(D,x,A){let F=2+x*5+1;D.values[F+0]=A[0],D.values[F+1]=A[1]}function p0(D){return D.values[0]!==0}function h0(D){return D.values[1]}function m0(D){return D.values[2]}function q0(D,x){return D.values[3]=x}var G0=p(()=>{"use strict"});function $0(D,x){let A=new U(D);A.position=x;let F=A.readObjects(1);return dx(F)?A.position:F}var U,y0=p(()=>{"use strict";px();U=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():v}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():v}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 v;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 v}}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 dx(x)?this.bytes[x]:x}readUint8(){let x=this.consume(1);return dx(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 v;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 v;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 g0,I0=p(()=>{"use strict";g0="1.15.4"});function _0(D,x){G||(G=D??new k.Logger(k.LogLevel.DEBUG,"odin-plugin-web",[]),x&&G.sinks.push(new k.CallbackSink(x,k.Formatter.structured)))}function u(D,...x){let A=hx(x);G?G?.error(D,A):(0,k.error)(D,A)}function i(D,...x){let A=hx(x);G?G?.warn(D,A):(0,k.warn)(D,A)}function f(D,...x){let A=hx(x);G?G?.info(D,A):(0,k.info)(D,A)}function n(D,...x){let A=hx(x);G?G?.debug(D,A):(0,k.debug)(D,A)}function hx(...D){if(D.length===1&&typeof D[0]=="object"&&D[0]!==null)return{...D[0]};if(D.length>0)return{args:D}}var k,G,L0=p(()=>{"use strict";k=require("@4players/odin-common")});function h(D){return D.connectionId*4294967296+D.mediaId}var I,z,o=p(()=>{"use strict";F0();px();F0();c0();G0();y0();I0();L0();px();I={isSilent:!0,rmsDBFS:-758.596};z=class{constructor(){this.inFlight=null}run(x){return this.inFlight||(this.inFlight=x().finally(()=>{this.inFlight=null})),this.inFlight}}});function Bx(D,x,A,F,r){return Promise.all([AF(D),FF(A,x,F,r)])}async function AF(D){let x=URL.createObjectURL(new Blob([D],{type:"text/javascript"})),A=new Worker(x,{type:"module",name:"odin worker"});return tx.push(A),A}async function FF(D,x,A,F){try{let e=new AudioWorkletNode(D,A,F);return Z.push(e),e}catch{}let r=D0.get(D);if(r===void 0){let e=URL.createObjectURL(new Blob([x],{type:"text/javascript"}));r=D.audioWorklet.addModule(e),D0.set(D,r),r.catch(()=>D0.delete(D))}await r;let t=new AudioWorkletNode(D,A,F);return Z.push(t),t}async function O0(){return{workers:await Promise.all(tx.map(vx)),worklets:await Promise.all(Z.map(D=>vx(D.port)))}}function vx(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),a(D,["dump",{result:x}],[x]),F}var tx,Z,ex,jx,D0,qx=p(()=>{"use strict";o();tx=[],Z=[],ex=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))}connectOutput(x){this.worklet.disconnect(),this.worklet.connect(x)}receivePacket(x,A){a(this.worker,["playbackReceivePacket",{connectionId:x,packet:A}],[A.buffer])}addMedias(x,A,F=[1,1]){let r=[];for(let t of A){let e=this._GetFreeIndex();e!==void 0&&(this.medias.set(h({connectionId:x,mediaId:t}),{index:e}),r.push({connectionId:x,mediaId:t,index:e,volume:F}))}a(this.worker,["playbackUpdateMedias",{added:r,removed:[]}])}removeMedias(x,A){let F=[];for(let r of A){let t=h({connectionId:x,mediaId:r}),e=this.medias.get(t);e!==void 0&&(this.medias.delete(t),this.availableIndexes.push(e.index),F.push({connectionId:x,mediaId:r,index:e.index}))}a(this.worker,["playbackUpdateMedias",{added:[],removed:F}])}close(){a(this.worker,["close",void 0]),a(this.worklet.port,["close",void 0]);let x=tx.indexOf(this.worker);x>=0&&tx.splice(x,1);let A=Z.indexOf(this.worklet);A>=0&&Z.splice(A,1)}async dump(){return{playbackWorker:await vx(this.worker),playbackWorklet:await vx(this.worklet.port)}}_GetFreeIndex(){return this.availableIndexes.pop()}_OnMessages(x){}},jx=class D{constructor(x,A,F,r,t){this.worklet=x;this.worker=A;this.sink=(e,j)=>{t.deref()!==void 0?F(e,j):(u("capture worker was left abandoned, aborting capture worker"),D.shutdown(x,A))},this.monitorSink=(e,j)=>{t.deref()!==void 0?r(e,j):(u("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){a(this.worker,["captureSetMedias",{connections:x}])}setVad(x){a(this.worker,["captureSetVad",x])}close(){D.shutdown(this.worklet,this.worker)}static shutdown(x,A){a(x.port,["close",void 0]),a(A,["close",void 0]);let F=tx.indexOf(A);F>=0&&tx.splice(F,1);let r=Z.indexOf(x);r>=0&&Z.splice(r,1)}async dump(){return{captureWorker:await vx(this.worker),captureWorklet:await vx(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))}};D0=new WeakMap});var t0,J0=p(()=>{t0=`"use strict";(()=>{var fn=Object.create;var ar=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var Gn=Object.getOwnPropertyNames;var pn=Object.getPrototypeOf,En=Object.prototype.hasOwnProperty;var mn=(e,A)=>()=>{try{return A||e((A={exports:{}}).exports,A),A.exports}catch(t){throw A=0,t}},hn=(e,A)=>{for(var t in A)ar(e,t,{get:A[t],enumerable:!0})},$n=(e,A,t,s)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of Gn(A))!En.call(e,i)&&i!==t&&ar(e,i,{get:()=>A[i],enumerable:!(s=qn(A,i))||s.enumerable});return e};var Fn=(e,A,t)=>(t=e!=null?fn(pn(e)):{},$n(A||!e||!e.__esModule?ar(t,"default",{value:e,enumerable:!0}):t,e));var vt=mn((Ft,MA)=>{"use strict";var SA=(()=>{var e=globalThis.document?.currentScript?.src;return async function(A={}){var t=A,s=!!globalThis.window,i=!!globalThis.WorkerGlobalScope,d=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",C=i&&globalThis.name=="em-pthread",E=[],_="./this.program",D=(r,j)=>{throw j};i&&(e=self.location.href);var UA="",T,yt;if(s||i){try{UA=new URL(".",e).href}catch{}i&&(yt=r=>{var j=new XMLHttpRequest;return j.open("GET",r,!1),j.responseType="arraybuffer",j.send(null),new Uint8Array(j.response)}),T=async r=>{var j=await fetch(r,{credentials:"same-origin"});if(j.ok)return j.arrayBuffer();throw new Error(j.status+" : "+j.url)}}var KA=console.log.bind(console),J=console.error.bind(console),gt,nA,pA=!1,z;class Dt{}class Ds extends Dt{}function xt(r){for(var j=0,n=r.length,l=new Uint8Array(n),o;j<n;++j)o=r.charCodeAt(j),l[j]=~o>>8&o;return l}var Hr;if(C){let r=function(j){try{var n=j.data,l=n.cmd;if(l==1){let o=[];self.onmessage=a=>o.push(a),Hr=()=>{postMessage({cmd:3});for(let a of o)r(a);self.onmessage=r};for(let a of n.handlers)(!t[a]||t[a].proxy)&&(t[a]=(...k)=>{postMessage({cmd:9,handler:a,args:k})},a=="print"&&(KA=t[a]),a=="printErr"&&(J=t[a]));iA=n.wasmMemory,yr(),nA=n.wasmModule,Br(),Bj(),Hr()}else if(l==2){Ut(n.pthread_ptr),ir(n.pthread_ptr,0,0,1,0,0),m.threadInitTLS(),er(n.pthread_ptr),RA||(mj(),RA=!0);try{Kt(n.start_routine,n.arg)}catch(o){if(o!="unwind")throw o}}else l==4?RA&&gA():l&&(J(\`worker: received unknown command \${l}\`),J(n))}catch(o){throw Lr&&$j(),o}};var Bs=r,RA=!1;self.onunhandledrejection=j=>{throw j.reason||j},self.onmessage=r}var Lr=!1;function yr(){var r=iA.buffer;R=new Int8Array(r),$A=new Int16Array(r),t.HEAPU8=x=new Uint8Array(r),oA=new Uint16Array(r),t.HEAP32=S=new Int32Array(r),t.HEAPU32=$=new Uint32Array(r),t.HEAPF32=aj=new Float32Array(r),mA=new Float64Array(r),K=new BigInt64Array(r),Vr=new BigUint64Array(r)}function Bt(){if(!C){{var r=16777216;iA=new WebAssembly.Memory({initial:r/65536,maximum:r/65536,shared:!0})}yr()}}function Nt(){var r=t.preRun;r&&(typeof r=="function"&&(r=[r]),Pr.push(...r)),Jr(Pr)}function gr(){Lr=!0,!C&&jA.F()}function bt(){var r=t.postRun;r&&(typeof r=="function"&&(r=[r]),Ur.push(...r)),Jr(Ur)}function EA(r){t.onAbort?.(r),r=\`Aborted(\${r})\`,J(r),pA=!0,r+=". Build with -sASSERTIONS for more info.";var j=new WebAssembly.RuntimeError(r);throw j}var Dr;function Ot(){return xt(\`\\0asm\\0\\0\\0\\xAC=\\\`\\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\\\`||\\\`\\0\\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\\\`
|
|
1
|
+
"use strict";var A0=Object.defineProperty;var qA=Object.getOwnPropertyDescriptor;var GA=Object.getOwnPropertyNames;var $A=Object.prototype.hasOwnProperty;var p=(D,x,A)=>()=>{if(A)throw A[0];try{return D&&(x=D(D=0)),x}catch(F){throw A=[F],F}};var kx=(D,x)=>{for(var A in x)A0(D,A,{get:x[A],enumerable:!0})},yA=(D,x,A,F)=>{if(x&&typeof x=="object"||typeof x=="function")for(let r of GA(x))!$A.call(D,r)&&r!==A&&A0(D,r,{get:()=>x[r],enumerable:!(F=qA(x,r))||F.enumerable});return D};var gA=D=>yA(A0({},"__esModule",{value:!0}),D);var E={};kx(E,{AdditionalCaptureBlocks:()=>_A,AdditionalPlaybackBlocks:()=>IA,ClockJumpCheckInterval:()=>JA,ClockJumpThreshold:()=>RA,ConnectInterval:()=>ZA,ConnectTimeout:()=>QA,DefaultRefreshRate:()=>HA,DefaultVideoCodec:()=>xF,HealthCheckTimeout:()=>OA,MainConnectionPingInterval:()=>SA,MaxNumberOfDecoders:()=>PA,MaxReconnectDuration:()=>YA,MinDBFs:()=>F0,MinTokenLifetime:()=>XA,MinTokenRefreshInterval:()=>zA,PlaybackPreload:()=>LA,RenderQuantumSize:()=>wA,VadPreload:()=>NA,WebRtcAnswerTimeout:()=>KA,WebRtcIceTimeout:()=>MA,WebRtcMaxNegotiationAttempts:()=>VA,WebRtcRecoveryDelays:()=>WA,WebRtcStatsSnapshotInterval:()=>TA,WebRtcTimeout:()=>UA});var IA,_A,LA,HA,NA,PA,wA,F0,OA,JA,RA,SA,TA,MA,UA,KA,VA,WA,QA,XA,zA,ZA,YA,xF,r0=p(()=>{"use strict";IA=3,_A=3,LA=3,HA=250,NA=3,PA=512,wA=128,F0=-758.596,OA=1e4,JA=1e3,RA=1e4,SA=3e3,TA=1e3,MA=3e3,UA=1e4,KA=1e4,VA=3,WA=[0,2e3,5e3],QA=5e3,XA=6e4,zA=5e3,ZA=[0,100,200,200,500],YA=12e4,xF="H264"});function dx(D){return typeof D!="symbol"}function i(D){return typeof D=="symbol"}var m,v,M,q,px=p(()=>{"use strict";m=Symbol("Unencrypted"),v=Symbol("Invalid"),M=Symbol("Retry"),q=Symbol("UnexpectedEof")});function a(D,x,A){return D.postMessage(x,A)}function Dx(D,x){return new Promise(A=>{let F=r=>{let[t]=r.data;t===x&&(A(r.data[1]),D.removeEventListener("message",F))};D.addEventListener("message",F)})}var k0=p(()=>{"use strict"});function D0(D,x){D.values[0]=x[0],D.values[1]=x[1]}function d0(D,x){return D.values[2+x*5]}function p0(D,x,A){let F=2+x*5+1;D.values[F+0]=A[0],D.values[F+1]=A[1]}function h0(D){return D.values[0]!==0}function m0(D){return D.values[1]}function q0(D){return D.values[2]}function G0(D,x){return D.values[3]=x}var $0=p(()=>{"use strict"});function y0(D,x){let A=new U(D);A.position=x;let F=A.readObjects(1);return dx(F)?A.position:F}var U,g0=p(()=>{"use strict";px();U=class{constructor(x,A=0){this.bytes=x;this.position=A}readArrayLength(){let x=this.readTag();return i(x)?x:(x&240)===144?x&15:x===220?this.readUint16():x===221?this.readUint32():v}readNumber(){let x=this.readTag();return i(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():v}readBytes(){let x=this.readTag();if(i(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 v;if(i(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(i(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(),i(F))return F;x+=F;break;case 221:if(F=this.readUint32(),i(F))return F;x+=F;break;case 222:if(F=this.readUint16(),i(F))return F;x+=F*2;break;case 223:if(F=this.readUint32(),i(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 v}}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 dx(x)?this.bytes[x]:x}readUint8(){let x=this.consume(1);return dx(x)?this.bytes[x]:x}readUint16(){let x=this.consume(2);return i(x)?x:this.bytes[x]<<8|this.bytes[x+1]}readUint32(){let x=this.consume(4);return i(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(i(x))return x;if(x>=2097152)return v;let A=this.readUint32();return i(A)?A:x<<32|A}readInt8(){let x=this.readUint8();return i(x)||x>=128&&(x=x-256),x}readInt16(){let x=this.readUint16();return i(x)||x>=32768&&(x=x-65536),x}readInt32(){let x=this.readUint32();return i(x)||x>=2147483648&&(x=x-4294967296),x}readInt64(){let x=this.readUint32();if(i(x))return x;if(x>=2097152||x<-2097152)return v;let A=this.readUint32();return i(A)?A:x<<32|A}readFloat32(){let x=this.consume(4);return i(x)?x:new Float32Array(this.bytes.subarray(x,x+4))[0]}readFloat64(){let x=this.consume(8);return i(x)?x:new Float64Array(this.bytes.subarray(x,x+8))[0]}}});var I0,_0=p(()=>{"use strict";I0="1.16.0"});function L0(D,x){G||(G=D??new k.Logger(k.LogLevel.DEBUG,"odin-plugin-web",[]),x&&G.sinks.push(new k.CallbackSink(x,k.Formatter.structured)))}function u(D,...x){let A=hx(x);G?G?.error(D,A):(0,k.error)(D,A)}function C(D,...x){let A=hx(x);G?G?.warn(D,A):(0,k.warn)(D,A)}function n(D,...x){let A=hx(x);G?G?.info(D,A):(0,k.info)(D,A)}function f(D,...x){let A=hx(x);G?G?.debug(D,A):(0,k.debug)(D,A)}function hx(...D){if(D.length===1&&typeof D[0]=="object"&&D[0]!==null)return{...D[0]};if(D.length>0)return{args:D}}var k,G,H0=p(()=>{"use strict";k=require("@4players/odin-common")});function h(D){return D.connectionId*4294967296+D.mediaId}var I,Z,o=p(()=>{"use strict";r0();px();r0();k0();$0();g0();_0();H0();px();I={isSilent:!0,rmsDBFS:-758.596};Z=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([DF(D),tF(A,x,F,r)])}async function DF(D){let x=URL.createObjectURL(new Blob([D],{type:"text/javascript"})),A=new Worker(x,{type:"module",name:"odin worker"});return jx.push(A),A}async function tF(D,x,A,F){try{let e=new AudioWorkletNode(D,A,F);return Y.push(e),e}catch{}let r=t0.get(D);if(r===void 0){let e=URL.createObjectURL(new Blob([x],{type:"text/javascript"}));r=D.audioWorklet.addModule(e),t0.set(D,r),r.catch(()=>t0.delete(D))}await r;let t=new AudioWorkletNode(D,A,F);return Y.push(t),t}async function J0(){return{workers:await Promise.all(jx.map(Cx)),worklets:await Promise.all(Y.map(D=>Cx(D.port)))}}function Cx(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),a(D,["dump",{result:x}],[x]),F}var jx,Y,vx,Bx,t0,qx=p(()=>{"use strict";o();jx=[],Y=[],vx=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))}connectOutput(x){this.worklet.disconnect(),this.worklet.connect(x)}receivePacket(x,A){a(this.worker,["playbackReceivePacket",{connectionId:x,packet:A}],[A.buffer])}addMedias(x,A,F=[1,1]){let r=[];for(let t of A){let e=this._GetFreeIndex();e!==void 0&&(this.medias.set(h({connectionId:x,mediaId:t}),{index:e}),r.push({connectionId:x,mediaId:t,index:e,volume:F}))}a(this.worker,["playbackUpdateMedias",{added:r,removed:[]}])}removeMedias(x,A){let F=[];for(let r of A){let t=h({connectionId:x,mediaId:r}),e=this.medias.get(t);e!==void 0&&(this.medias.delete(t),this.availableIndexes.push(e.index),F.push({connectionId:x,mediaId:r,index:e.index}))}a(this.worker,["playbackUpdateMedias",{added:[],removed:F}])}close(){a(this.worker,["close",void 0]),a(this.worklet.port,["close",void 0]);let x=jx.indexOf(this.worker);x>=0&&jx.splice(x,1);let A=Y.indexOf(this.worklet);A>=0&&Y.splice(A,1)}async dump(){return{playbackWorker:await Cx(this.worker),playbackWorklet:await Cx(this.worklet.port)}}_GetFreeIndex(){return this.availableIndexes.pop()}_OnMessages(x){}},Bx=class D{constructor(x,A,F,r,t){this.worklet=x;this.worker=A;this.sink=(e,j)=>{t.deref()!==void 0?F(e,j):(u("capture worker was left abandoned, aborting capture worker"),D.shutdown(x,A))},this.monitorSink=(e,j)=>{t.deref()!==void 0?r(e,j):(u("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){a(this.worker,["captureSetMedias",{connections:x}])}setVad(x){a(this.worker,["captureSetVad",x])}close(){D.shutdown(this.worklet,this.worker)}static shutdown(x,A){a(x.port,["close",void 0]),a(A,["close",void 0]);let F=jx.indexOf(A);F>=0&&jx.splice(F,1);let r=Y.indexOf(x);r>=0&&Y.splice(r,1)}async dump(){return{captureWorker:await Cx(this.worker),captureWorklet:await Cx(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))}};t0=new WeakMap});var e0,R0=p(()=>{e0=`"use strict";(()=>{var fn=Object.create;var ar=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var Gn=Object.getOwnPropertyNames;var pn=Object.getPrototypeOf,En=Object.prototype.hasOwnProperty;var mn=(e,A)=>()=>{try{return A||e((A={exports:{}}).exports,A),A.exports}catch(t){throw A=0,t}},hn=(e,A)=>{for(var t in A)ar(e,t,{get:A[t],enumerable:!0})},$n=(e,A,t,s)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of Gn(A))!En.call(e,i)&&i!==t&&ar(e,i,{get:()=>A[i],enumerable:!(s=qn(A,i))||s.enumerable});return e};var Fn=(e,A,t)=>(t=e!=null?fn(pn(e)):{},$n(A||!e||!e.__esModule?ar(t,"default",{value:e,enumerable:!0}):t,e));var vt=mn((Ft,MA)=>{"use strict";var SA=(()=>{var e=globalThis.document?.currentScript?.src;return async function(A={}){var t=A,s=!!globalThis.window,i=!!globalThis.WorkerGlobalScope,d=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",C=i&&globalThis.name=="em-pthread",E=[],_="./this.program",D=(r,j)=>{throw j};i&&(e=self.location.href);var UA="",T,yt;if(s||i){try{UA=new URL(".",e).href}catch{}i&&(yt=r=>{var j=new XMLHttpRequest;return j.open("GET",r,!1),j.responseType="arraybuffer",j.send(null),new Uint8Array(j.response)}),T=async r=>{var j=await fetch(r,{credentials:"same-origin"});if(j.ok)return j.arrayBuffer();throw new Error(j.status+" : "+j.url)}}var KA=console.log.bind(console),J=console.error.bind(console),gt,nA,pA=!1,z;class Dt{}class xs extends Dt{}function xt(r){for(var j=0,n=r.length,l=new Uint8Array(n),o;j<n;++j)o=r.charCodeAt(j),l[j]=~o>>8&o;return l}var Hr;if(C){let r=function(j){try{var n=j.data,l=n.cmd;if(l==1){let o=[];self.onmessage=a=>o.push(a),Hr=()=>{postMessage({cmd:3});for(let a of o)r(a);self.onmessage=r};for(let a of n.handlers)(!t[a]||t[a].proxy)&&(t[a]=(...k)=>{postMessage({cmd:9,handler:a,args:k})},a=="print"&&(KA=t[a]),a=="printErr"&&(J=t[a]));iA=n.wasmMemory,yr(),nA=n.wasmModule,Br(),Bj(),Hr()}else if(l==2){Ut(n.pthread_ptr),ir(n.pthread_ptr,0,0,1,0,0),m.threadInitTLS(),er(n.pthread_ptr),RA||(mj(),RA=!0);try{Kt(n.start_routine,n.arg)}catch(o){if(o!="unwind")throw o}}else l==4?RA&&gA():l&&(J(\`worker: received unknown command \${l}\`),J(n))}catch(o){throw Lr&&$j(),o}};var Ns=r,RA=!1;self.onunhandledrejection=j=>{throw j.reason||j},self.onmessage=r}var Lr=!1;function yr(){var r=iA.buffer;R=new Int8Array(r),$A=new Int16Array(r),t.HEAPU8=x=new Uint8Array(r),oA=new Uint16Array(r),t.HEAP32=S=new Int32Array(r),t.HEAPU32=$=new Uint32Array(r),t.HEAPF32=aj=new Float32Array(r),mA=new Float64Array(r),K=new BigInt64Array(r),Vr=new BigUint64Array(r)}function Bt(){if(!C){{var r=16777216;iA=new WebAssembly.Memory({initial:r/65536,maximum:r/65536,shared:!0})}yr()}}function Nt(){var r=t.preRun;r&&(typeof r=="function"&&(r=[r]),Pr.push(...r)),Jr(Pr)}function gr(){Lr=!0,!C&&jA.F()}function bt(){var r=t.postRun;r&&(typeof r=="function"&&(r=[r]),Ur.push(...r)),Jr(Ur)}function EA(r){t.onAbort?.(r),r=\`Aborted(\${r})\`,J(r),pA=!0,r+=". Build with -sASSERTIONS for more info.";var j=new WebAssembly.RuntimeError(r);throw j}var Dr;function Ot(){return xt(\`\\0asm\\0\\0\\0\\xAC=\\\`\\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\\\`||\\\`\\0\\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\\\`
|
|
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\\\`\\x07\\x7F|\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F|}\\\`\\x7F\\x7F\\x7F~~\\0\\\`\\x07\\x7F\\x7F\\x7F\\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}}\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F|\\\`\\x7F\\x7F|\\0\\xBFaa\\x80\\x80ab\\0ac\\0ad\\0ae\\0af\\0ag\\0ah\\0!ai\\0
|
|
3
3
|
aj\\0"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\\0\\xFD\\xFB\\0\\x07\\f&\\0\\f\\x07\\f\\f\\0\\x07\\0'(
|
|
4
4
|
\\b\\v)*\\0\\f+,-\\x07\\v\\0\\0\\x07\\0\\b\\b\\x1B
|
|
@@ -3361,7 +3361,7 @@ K\\xE08\\xDF\\0}\\xBC\\x8A\\x1B\\f\\xE5\\xFF\\xCF\\xE8?\\x9F\\xFFFq\\0\\x88\\xB
|
|
|
3361
3361
|
|
|
3362
3362
|
|
|
3363
3363
|
\\x07\\0\\0 \\v\\0\\0 \\v\\0\\0\\v\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\v\\r\\0\\r\\0\\0\\0 \\0\\0\\0 \\0\\0\\0!\\f\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\f\\0\\0\\0\\0\\0\\f\\0\\0\\f!\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0*\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 !\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\xC0 \\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\x000123456789ABCDEFp\\0\\xC8\\0NSt3__214__shared_countE\\0\\0\\0\\0\\xF4\\0\\xFC\\0\\0\\0\\0\\0\\0\\0\\0\\xC0\\0\\0\\0\\0\\0NSt3__219__shared_weak_countE\\0\\0\\0\\x98\\0(\\x008\\0N10__cxxabiv116__shim_type_infoE\\0\\0\\0\\0\\x98\\0X\\0\\0N10__cxxabiv117__class_type_infoE\\0\\0\\0\\x98\\0\\x88\\0\\0N10__cxxabiv117__pbase_type_infoE\\0\\0\\0\\x98\\0\\xB8\\0|\\0N10__cxxabiv119__pointer_type_infoE\\0\\x98\\0\\xE8\\0\\0N10__cxxabiv120__function_type_infoE\\0\\0\\0\\0\\x98\\0\\0|\\0N10__cxxabiv129__pointer_to_member_type_infoE\\0\\0\\0\\0\\0\\0\\0h\\0k\\0\\0\\0l\\0\\0\\0m\\0\\0\\0n\\0\\0\\0o\\0\\0\\0\\x98\\0t\\0\\0N10__cxxabiv123__fundamental_type_infoE\\0T\\0\\xA4\\0v\\0Dn\\0\\0\\0\\0T\\0\\xB4\\0b\\0\\0\\0T\\0\\xC0\\0c\\0\\0\\0T\\0\\xCC\\0h\\0\\0\\0T\\0\\xD8\\0a\\0\\0\\0T\\0\\xE4\\0s\\0\\0\\0T\\0\\xF0\\0t\\0\\0\\0T\\0\\xFC\\0i\\0\\0\\0T\\0\\b\\0j\\0\\0\\0T\\0\\0l\\0\\0\\0T\\0 \\0m\\0\\0\\0T\\0,\\0x\\0\\0\\0T\\x008\\0y\\0\\0\\0T\\0D\\0f\\0\\0\\0P\\0X\\0\\0\\0\\0\\0<\\0Pf\\0\\0T\\0d\\0d\\0\\0\\0\\0\\0\\0\\0L\\0k\\0\\0\\0p\\0\\0\\0m\\0\\0\\0n\\0\\0\\0q\\0\\0\\0r\\0\\0\\0s\\0\\0\\0t\\0\\0\\0\\0\\0\\0\\0\\xB8\\0k\\0\\0\\0u\\0\\0\\0m\\0\\0\\0n\\0\\0\\0q\\0\\0\\0v\\0\\0\\0w\\0\\0\\0x\\0\\0\\0\\x98\\0\\xC4\\0L\\0N10__cxxabiv120__si_class_type_infoE\\0\\0\\0\\0\\0\\0\\0\\0\\0k\\0\\0\\0y\\0\\0\\0m\\0\\0\\0n\\0\\0\\0q\\0\\0\\0z\\0\\0\\0{\\0\\0\\0|\\0\\0\\0\\x98\\0 \\0L\\0N10__cxxabiv121__vmi_class_type_infoE\\0\\0\\0\\0\\0\\0\\0\\xAC\\0k\\0\\0\\0}\\0\\0\\0m\\0\\0\\0n\\0\\0\\0~\\0\\0\\0\\0\\0\\0\\0\\xAC\\0C\\0\\0\\0\\x7F\\0\\0\\0\\x80\\0\\0\\0p\\0\\x80\\0St9exception\\0\\0\\0\\0\\x98\\0\\x9C\\0x\\0St9bad_alloc\\0\\0\\0\\0\\x98\\0\\xB8\\0\\x90\\0St20bad_array_new_length\\0\\0\\0\\0\\0\\0\\0\\0\\xE8\\0E\\0\\0\\0\\x81\\0\\0\\0\\x82\\0\\0\\0\\x98\\0\\xF4\\0x\\0St11logic_error\\0\\0\\0\\0\\0\\0E\\0\\0\\0\\x83\\0\\0\\0\\x82\\0\\0\\0\\x98\\0$\\0\\xE8\\0St12length_error\\0\\0\\0\\0p\\0@\\0St9type_info\\0\\\`P\\0P\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0c\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0d\\0\\0\\0e\\0\\0\\x000\\x1B\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFFY\\x90\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0f\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0d\\0\\0\\0g\\0\\0\\x008\\x1B\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\xFF\\xFF\\xFF\\xFF
|
|
3364
|
-
\\f(\\0p!\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x94\\0\\0\\0\\0\\0\\0\\0\\0\\0\`)}function xs(r){return r}async function Jt(r){return r}async function Pt(r,j){try{var n=await Jt(r),l=await WebAssembly.instantiate(n,j);return l}catch(o){J(\`failed to asynchronously prepare wasm: \${o}\`),EA(o)}}async function wt(r,j,n){return Pt(j,n)}function xr(){dn();var r={a:xj};return r}async function Br(){function r(u,c){return jA=u.exports,Rt(jA.M),cn(jA),nA=c,jA}function j(u){return r(u.instance,u.module)}var n=xr(),l=t.instantiateWasm;if(l)return new Promise(u=>{l(n,(c,q)=>u(r(c,q)))});if(C){var o=new WebAssembly.Instance(nA,xr());return r(o,nA)}Dr??=Ot();var a=await wt(gt,Dr,n),k=j(a);return k}class Nr{name="ExitStatus";constructor(j){this.message=\`Program terminated with exit(\${j})\`,this.status=j}}var br=r=>{r.terminate(),r.onmessage=j=>{}},Or=r=>{var j=m.pthreads[r];m.returnWorkerToPool(j)},Jr=r=>{for(;r.length>0;)r.shift()(t)},Pr=[],Tt=r=>{var j=m.getNewWorker();if(!j)return 6;m.pthreads[r.pthread_ptr]=j,j.pthread_ptr=r.pthread_ptr;var n={cmd:2,start_routine:r.startRoutine,arg:r.arg,pthread_ptr:r.pthread_ptr};return j.postMessage(n,r.transferList),0},VA=0,QA=()=>zA||VA>0,wr=()=>gj(),WA=r=>Lj(r),St=r=>yj(r),mA,K,sA=(r,j,n,...l)=>{var o=8*l.length*2,a=wr(),k=St(o),u=k>>3;for(var c of l)typeof c=="bigint"?(K[u++]=1n,K[u++]=c):(K[u++]=0n,mA[u++]=c);var q=vj(r,j,o,k,n);return WA(a),q};function Tr(r){if(C)return sA(0,0,1,r);z=r,QA()||(m.terminateAllThreads(),t.onExit?.(r),pA=!0),D(r,new Nr(r))}function Sr(r){if(C)return sA(1,0,0,r);XA(r)}var Mt=(r,j)=>{if(z=r,C)throw Sr(r),"unwind";Tr(r)},XA=Mt,Mr=!Atomics.waitAsync||globalThis.navigator?.userAgent&&Number((navigator.userAgent.match(/Chrom(e|ium)\\/([0-9]+)\\./)||[])[2])<91,S,m={unusedWorkers:[],tlsInitFunctions:[],pthreads:{},init(){C||m.initMainThread()},initMainThread(){},terminateAllThreads:()=>{for(var r of Object.values(m.pthreads))br(r);for(var r of m.unusedWorkers)br(r);m.unusedWorkers=[],m.pthreads={}},clearMailboxAwait:r=>{Mr||Atomics.notify(S,r>>2)},terminateRuntime:()=>{m.terminateAllThreads();var r=kA();hj(0,0,0,1),m.clearMailboxAwait(r)},returnWorkerToPool:r=>{var j=r.pthread_ptr;delete m.pthreads[j],m.unusedWorkers.push(r),r.pthread_ptr=0,m.clearMailboxAwait(j),Ij(j)},threadInitTLS(){m.tlsInitFunctions.forEach(r=>r())},loadWasmModuleToWorker:r=>new Promise(j=>{r.onmessage=a=>{var k=a.data,u=k.cmd;if(k.targetThread&&k.targetThread!=kA()){var c=m.pthreads[k.targetThread];c?.postMessage(k);return}if(k==="setimmediate"||k==="_si"){r.postMessage(k);return}switch(u){case 4:gA();break;case 5:Tt(k);break;case 6:fj(()=>Or(k.thread));break;case 3:j(r);break;case 9:t[k.handler](...k.args);break;default:u&&J(\`worker sent an unknown command \${u}\`)}},r.onerror=a=>{var k="worker sent an error!";throw J(\`\${k} \${a.filename}:\${a.lineno}: \${a.message}\`),a};var n=[],l=["onExit","onAbort","print","printErr"];for(var o of l)t.propertyIsEnumerable(o)&&n.push(o);r.postMessage({cmd:1,handlers:n,wasmMemory:iA,wasmModule:nA})}),allocateUnusedWorker(){var r,j=e;return r=new Worker(j,{name:"em-pthread"}),m.unusedWorkers.push(r),r},getNewWorker(){if(m.unusedWorkers.length==0){var r=m.allocateUnusedWorker();m.loadWasmModuleToWorker(r)}return m.unusedWorkers.pop()}},Ur=[],$;function Ut(r){var j=$[r+48>>2],n=$[r+52>>2],l=j-n;Hj(j,l),WA(j)}var Kr=[],Rr=r=>{var j=Kr[r];return j||(Kr[r]=j=Dj.get(r)),j},Kt=(r,j)=>{VA=0,zA=0;var n=Rr(r)(j);function l(o){if(QA()){z=o;return}lr(o)}l(n)},zA=!0,Rt=r=>m.tlsInitFunctions.push(r),iA,R;class Vt{constructor(j){this.excPtr=j,this.ptr=j-24}set_type(j){$[this.ptr+4>>2]=j}get_type(){return $[this.ptr+4>>2]}set_destructor(j){$[this.ptr+8>>2]=j}get_destructor(){return $[this.ptr+8>>2]}set_caught(j){j=j?1:0,R[this.ptr+12]=j}get_caught(){return R[this.ptr+12]!=0}set_rethrown(j){j=j?1:0,R[this.ptr+13]=j}get_rethrown(){return R[this.ptr+13]!=0}init(j,n){this.set_adjusted_ptr(0),this.set_type(j),this.set_destructor(n)}set_adjusted_ptr(j){$[this.ptr+16>>2]=j}get_adjusted_ptr(){return $[this.ptr+16>>2]}}var Qt=0,Wt=r=>{EA()},Xt=(r,j,n)=>{var l=new Vt(r);l.init(j,n),Qt++,Wt(r)},zt=()=>EA(""),x,H=r=>{for(var j="";;){var n=x[r++];if(!n)return j;j+=String.fromCharCode(n)}},Z={},Y={},hA={};class lA extends Error{constructor(j){super(j),this.name="BindingError"}}var G=r=>{throw new lA(r)};function Zt(r,j,n={}){var l=j.name;if(r||G(\`type "\${l}" must have a positive integer typeid pointer\`),Y.hasOwnProperty(r)){if(n.ignoreDuplicateRegistrations)return;G(\`Cannot register type '\${l}' twice\`)}if(Y[r]=j,delete hA[r],Z.hasOwnProperty(r)){var o=Z[r];delete Z[r],o.forEach(a=>a())}}function N(r,j,n={}){return Zt(r,j,n)}var $A,oA,Vr,Qr=(r,j,n)=>{switch(j){case 1:return n?l=>R[l]:l=>x[l];case 2:return n?l=>$A[l>>1]:l=>oA[l>>1];case 4:return n?l=>S[l>>2]:l=>$[l>>2];case 8:return n?l=>K[l>>3]:l=>Vr[l>>3];default:throw new TypeError(\`invalid integer width (\${j}): \${r}\`)}},Yt=(r,j,n,l,o)=>{j=H(j);let a=l===0n,k=u=>u;if(a){let u=n*8;k=c=>BigInt.asUintN(u,c),o=k(o)}N(r,{name:j,fromWireType:k,toWireType:(u,c)=>(typeof c=="number"&&(c=BigInt(c)),c),readValueFromPointer:Qr(j,n,!a),destructorFunction:null})},Ae=(r,j,n,l)=>{j=H(j),N(r,{name:j,fromWireType:function(o){return!!o},toWireType:function(o,a){return a?n:l},readValueFromPointer:function(o){return this.fromWireType(x[o])},destructorFunction:null})},re=r=>({count:r.count,deleteScheduled:r.deleteScheduled,preservePointerOnDelete:r.preservePointerOnDelete,ptr:r.ptr,ptrType:r.ptrType,smartPtr:r.smartPtr,smartPtrType:r.smartPtrType}),ZA=r=>{function j(n){return n.$$.ptrType.registeredClass.name}G(j(r)+" instance already deleted")},YA=!1,Wr=r=>{},je=r=>{r.smartPtr?r.smartPtrType.rawDestructor(r.smartPtr):r.ptrType.registeredClass.rawDestructor(r.ptr)},Xr=r=>{r.count.value-=1;var j=r.count.value===0;j&&je(r)},aA=r=>globalThis.FinalizationRegistry?(YA=new FinalizationRegistry(j=>{Xr(j.$$)}),aA=j=>{var n=j.$$,l=!!n.smartPtr;if(l){var o={$$:n};YA.register(j,o,j)}return j},Wr=j=>YA.unregister(j),aA(r)):(aA=j=>j,r),FA=[],te=()=>{for(;FA.length;){var r=FA.pop();r.$$.deleteScheduled=!1,r.delete()}},zr,ee=()=>{let r=vA.prototype;Object.assign(r,{isAliasOf(n){if(!(this instanceof vA)||!(n instanceof vA))return!1;var l=this.$$.ptrType.registeredClass,o=this.$$.ptr;n.$$=n.$$;for(var a=n.$$.ptrType.registeredClass,k=n.$$.ptr;l.baseClass;)o=l.upcast(o),l=l.baseClass;for(;a.baseClass;)k=a.upcast(k),a=a.baseClass;return l===a&&o===k},clone(){if(this.$$.ptr||ZA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var n=aA(Object.create(Object.getPrototypeOf(this),{$$:{value:re(this.$$)}}));return n.$$.count.value+=1,n.$$.deleteScheduled=!1,n},delete(){this.$$.ptr||ZA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),Wr(this),Xr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||ZA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),FA.push(this),FA.length===1&&zr&&zr(te),this.$$.deleteScheduled=!0,this}});let j=Symbol.dispose;j&&(r[j]=r.delete)};function vA(){}var Zr=(r,j)=>Object.defineProperty(j,"name",{value:r}),Yr={},Aj=(r,j,n)=>{if(r[j].overloadTable===void 0){var l=r[j];r[j]=function(...o){return r[j].overloadTable.hasOwnProperty(o.length)||G(\`Function '\${n}' called with an invalid number of arguments (\${o.length}) - expects one of (\${r[j].overloadTable})!\`),r[j].overloadTable[o.length].apply(this,o)},r[j].overloadTable=[],r[j].overloadTable[l.argCount]=l}},rj=(r,j,n)=>{t.hasOwnProperty(r)?((n===void 0||t[r].overloadTable!==void 0&&t[r].overloadTable[n]!==void 0)&&G(\`Cannot register public name '\${r}' twice\`),Aj(t,r,r),t[r].overloadTable.hasOwnProperty(n)&&G(\`Cannot register multiple overloads of a function with the same number of arguments (\${n})!\`),t[r].overloadTable[n]=j):(t[r]=j,t[r].argCount=n)},ne=48,se=57,ie=r=>{r=r.replace(/[^a-zA-Z0-9_]/g,"$");var j=r.charCodeAt(0);return j>=ne&&j<=se?\`_\${r}\`:r};function le(r,j,n,l,o,a,k,u){this.name=r,this.constructor=j,this.instancePrototype=n,this.rawDestructor=l,this.baseClass=o,this.getActualType=a,this.upcast=k,this.downcast=u,this.pureVirtualFunctions=[]}var IA=(r,j,n)=>{for(;j!==n;)j.upcast||G(\`Expected null or instance of \${n.name}, got an instance of \${j.name}\`),r=j.upcast(r),j=j.baseClass;return r},Ar=r=>{if(r===null)return"null";var j=typeof r;return j==="object"||j==="array"||j==="function"?r.toString():""+r};function oe(r,j){if(j===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;j.$$||G(\`Cannot pass "\${Ar(j)}" as a \${this.name}\`),j.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`);var n=j.$$.ptrType.registeredClass,l=IA(j.$$.ptr,n,this.registeredClass);return l}function ae(r,j){var n;if(j===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),this.isSmartPointer?(n=this.rawConstructor(),r!==null&&r.push(this.rawDestructor,n),n):0;(!j||!j.$$)&&G(\`Cannot pass "\${Ar(j)}" as a \${this.name}\`),j.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),!this.isConst&&j.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type \${this.name}\`);var l=j.$$.ptrType.registeredClass;if(n=IA(j.$$.ptr,l,this.registeredClass),this.isSmartPointer)switch(j.$$.smartPtr===void 0&&G("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:j.$$.smartPtrType===this?n=j.$$.smartPtr:G(\`Cannot convert argument of type \${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type \${this.name}\`);break;case 1:n=j.$$.smartPtr;break;case 2:if(j.$$.smartPtrType===this)n=j.$$.smartPtr;else{var o=j.clone();n=this.rawShare(n,tr.toHandle(()=>o.delete())),r!==null&&r.push(this.rawDestructor,n)}break;default:G("Unsupported sharing policy")}return n}function ke(r,j){if(j===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;j.$$||G(\`Cannot pass "\${Ar(j)}" as a \${this.name}\`),j.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),j.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${j.$$.ptrType.name} to parameter type \${this.name}\`);var n=j.$$.ptrType.registeredClass,l=IA(j.$$.ptr,n,this.registeredClass);return l}function _A(r){return this.fromWireType($[r>>2])}var jj=(r,j,n)=>{if(j===n)return r;if(n.baseClass===void 0)return null;var l=jj(r,j,n.baseClass);return l===null?null:n.downcast(l)},ue={},ce=(r,j)=>{for(j===void 0&&G("ptr should not be undefined");r.baseClass;)j=r.upcast(j),r=r.baseClass;return j},de=(r,j)=>(j=ce(r,j),ue[j]);class Ce extends Error{constructor(j){super(j),this.name="InternalError"}}var HA=r=>{throw new Ce(r)},LA=(r,j)=>{(!j.ptrType||!j.ptr)&&HA("makeClassHandle requires ptr and ptrType");var n=!!j.smartPtrType,l=!!j.smartPtr;return n!==l&&HA("Both smartPtrType and smartPtr must be specified"),j.count={value:1},aA(Object.create(r,{$$:{value:j,writable:!0}}))};function fe(r){var j=this.getPointee(r);if(!j)return this.destructor(r),null;var n=de(this.registeredClass,j);if(n!==void 0){if(n.$$.count.value===0)return n.$$.ptr=j,n.$$.smartPtr=r,n.clone();var l=n.clone();return this.destructor(r),l}function o(){return this.isSmartPointer?LA(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:j,smartPtrType:this,smartPtr:r}):LA(this.registeredClass.instancePrototype,{ptrType:this,ptr:r})}var a=this.registeredClass.getActualType(j),k=Yr[a];if(!k)return o.call(this);var u;this.isConst?u=k.constPointerType:u=k.pointerType;var c=jj(j,this.registeredClass,u.registeredClass);return c===null?o.call(this):this.isSmartPointer?LA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c,smartPtrType:this,smartPtr:r}):LA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c})}var qe=()=>{Object.assign(yA.prototype,{getPointee(r){return this.rawGetPointee&&(r=this.rawGetPointee(r)),r},destructor(r){this.rawDestructor?.(r)},readValueFromPointer:_A,fromWireType:fe})};function yA(r,j,n,l,o,a,k,u,c,q,f){this.name=r,this.registeredClass=j,this.isReference=n,this.isConst=l,this.isSmartPointer=o,this.pointeeType=a,this.sharingPolicy=k,this.rawGetPointee=u,this.rawConstructor=c,this.rawShare=q,this.rawDestructor=f,!o&&j.baseClass===void 0?l?(this.toWireType=oe,this.destructorFunction=null):(this.toWireType=ke,this.destructorFunction=null):this.toWireType=ae}var tj=(r,j,n)=>{t.hasOwnProperty(r)||HA("Replacing nonexistent public symbol"),t[r].overloadTable!==void 0&&n!==void 0?t[r].overloadTable[n]=j:(t[r]=j,t[r].argCount=n)},P=(r,j,n=!1)=>{r=H(r);function l(){var a=Rr(j);return a}var o=l();return typeof o!="function"&&G(\`unknown function pointer with signature \${r}: \${j}\`),o};class Ge extends Error{}var pe=r=>{var j=Ej(r),n=H(j);return w(j),n},AA=(r,j)=>{var n=[],l={};function o(a){if(!l[a]&&!Y[a]){if(hA[a]){hA[a].forEach(o);return}n.push(a),l[a]=!0}}throw j.forEach(o),new Ge(\`\${r}: \`+n.map(pe).join([", "]))},M=(r,j,n)=>{r.forEach(u=>hA[u]=j);function l(u){var c=n(u);c.length!==r.length&&HA("Mismatched type converter count");for(var q=0;q<r.length;++q)N(r[q],c[q])}var o=new Array(j.length),a=[],k=0;for(let[u,c]of j.entries())Y.hasOwnProperty(c)?o[u]=Y[c]:(a.push(c),Z.hasOwnProperty(c)||(Z[c]=[]),Z[c].push(()=>{o[u]=Y[c],++k,k===a.length&&l(o)}));a.length===0&&l(o)},Ee=(r,j,n,l,o,a,k,u,c,q,f,p,v)=>{f=H(f),a=P(o,a),u&&=P(k,u),q&&=P(c,q),v=P(p,v);var I=ie(f);rj(I,function(){AA(\`Cannot construct \${f} due to unbound types\`,[l])}),M([r,j,n],l?[l]:[],F=>{F=F[0];var h,b;l?(h=F.registeredClass,b=h.instancePrototype):b=vA.prototype;var y=Zr(f,function(...or){if(Object.getPrototypeOf(this)!==Q)throw new lA(\`Use 'new' to construct \${f}\`);if(g.constructor_body===void 0)throw new lA(\`\${f} has no accessible constructor\`);var Oj=g.constructor_body[or.length];if(Oj===void 0)throw new lA(\`Tried to invoke ctor of \${f} with invalid number of parameters (\${or.length}) - expected (\${Object.keys(g.constructor_body).toString()}) parameters instead!\`);return Oj.apply(this,or)}),Q=Object.create(b,{constructor:{value:y}});y.prototype=Q;var g=new le(f,y,Q,v,h,a,u,q);g.baseClass&&(g.baseClass.__derivedClasses??=[],g.baseClass.__derivedClasses.push(g));var Cn=new yA(f,g,!0,!1,!1),Nj=new yA(f+"*",g,!1,!1,!1),bj=new yA(f+" const*",g,!1,!0,!1);return Yr[r]={pointerType:Nj,constPointerType:bj},tj(I,y),[Cn,Nj,bj]})},rr=(r,j)=>{for(var n=[],l=0;l<r;l++)n.push($[j+l*4>>2]);return n},ej=r=>{for(;r.length;){var j=r.pop(),n=r.pop();n(j)}};function nj(r){for(var j=1;j<r.length;++j)if(r[j]!==null&&r[j].destructorFunction===void 0)return!0;return!1}function sj(r){for(var j=1;j<r.length;++j)if(r[j]!==null&&r[j].argStackAlloc)return!0;return!1}function me(r,j,n,l){var o=nj(r),a=sj(r),k=a&&!l&&!o;a&&!k&&(o=!0);var u=r.length-2,c=[],q=["fn"];j&&q.push("thisWired");for(var f=0;f<u;++f)c.push(\`arg\${f}\`),q.push(\`arg\${f}Wired\`);c=c.join(),q=q.join();var p=\`return function (\${c}) {
|
|
3364
|
+
\\f(\\0p!\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\x94\\0\\0\\0\\0\\0\\0\\0\\0\\0\`)}function Bs(r){return r}async function Jt(r){return r}async function Pt(r,j){try{var n=await Jt(r),l=await WebAssembly.instantiate(n,j);return l}catch(o){J(\`failed to asynchronously prepare wasm: \${o}\`),EA(o)}}async function wt(r,j,n){return Pt(j,n)}function xr(){dn();var r={a:xj};return r}async function Br(){function r(u,c){return jA=u.exports,Rt(jA.M),cn(jA),nA=c,jA}function j(u){return r(u.instance,u.module)}var n=xr(),l=t.instantiateWasm;if(l)return new Promise(u=>{l(n,(c,q)=>u(r(c,q)))});if(C){var o=new WebAssembly.Instance(nA,xr());return r(o,nA)}Dr??=Ot();var a=await wt(gt,Dr,n),k=j(a);return k}class Nr{name="ExitStatus";constructor(j){this.message=\`Program terminated with exit(\${j})\`,this.status=j}}var br=r=>{r.terminate(),r.onmessage=j=>{}},Or=r=>{var j=m.pthreads[r];m.returnWorkerToPool(j)},Jr=r=>{for(;r.length>0;)r.shift()(t)},Pr=[],Tt=r=>{var j=m.getNewWorker();if(!j)return 6;m.pthreads[r.pthread_ptr]=j,j.pthread_ptr=r.pthread_ptr;var n={cmd:2,start_routine:r.startRoutine,arg:r.arg,pthread_ptr:r.pthread_ptr};return j.postMessage(n,r.transferList),0},VA=0,QA=()=>zA||VA>0,wr=()=>gj(),WA=r=>Lj(r),St=r=>yj(r),mA,K,sA=(r,j,n,...l)=>{var o=8*l.length*2,a=wr(),k=St(o),u=k>>3;for(var c of l)typeof c=="bigint"?(K[u++]=1n,K[u++]=c):(K[u++]=0n,mA[u++]=c);var q=vj(r,j,o,k,n);return WA(a),q};function Tr(r){if(C)return sA(0,0,1,r);z=r,QA()||(m.terminateAllThreads(),t.onExit?.(r),pA=!0),D(r,new Nr(r))}function Sr(r){if(C)return sA(1,0,0,r);XA(r)}var Mt=(r,j)=>{if(z=r,C)throw Sr(r),"unwind";Tr(r)},XA=Mt,Mr=!Atomics.waitAsync||globalThis.navigator?.userAgent&&Number((navigator.userAgent.match(/Chrom(e|ium)\\/([0-9]+)\\./)||[])[2])<91,S,m={unusedWorkers:[],tlsInitFunctions:[],pthreads:{},init(){C||m.initMainThread()},initMainThread(){},terminateAllThreads:()=>{for(var r of Object.values(m.pthreads))br(r);for(var r of m.unusedWorkers)br(r);m.unusedWorkers=[],m.pthreads={}},clearMailboxAwait:r=>{Mr||Atomics.notify(S,r>>2)},terminateRuntime:()=>{m.terminateAllThreads();var r=kA();hj(0,0,0,1),m.clearMailboxAwait(r)},returnWorkerToPool:r=>{var j=r.pthread_ptr;delete m.pthreads[j],m.unusedWorkers.push(r),r.pthread_ptr=0,m.clearMailboxAwait(j),Ij(j)},threadInitTLS(){m.tlsInitFunctions.forEach(r=>r())},loadWasmModuleToWorker:r=>new Promise(j=>{r.onmessage=a=>{var k=a.data,u=k.cmd;if(k.targetThread&&k.targetThread!=kA()){var c=m.pthreads[k.targetThread];c?.postMessage(k);return}if(k==="setimmediate"||k==="_si"){r.postMessage(k);return}switch(u){case 4:gA();break;case 5:Tt(k);break;case 6:fj(()=>Or(k.thread));break;case 3:j(r);break;case 9:t[k.handler](...k.args);break;default:u&&J(\`worker sent an unknown command \${u}\`)}},r.onerror=a=>{var k="worker sent an error!";throw J(\`\${k} \${a.filename}:\${a.lineno}: \${a.message}\`),a};var n=[],l=["onExit","onAbort","print","printErr"];for(var o of l)t.propertyIsEnumerable(o)&&n.push(o);r.postMessage({cmd:1,handlers:n,wasmMemory:iA,wasmModule:nA})}),allocateUnusedWorker(){var r,j=e;return r=new Worker(j,{name:"em-pthread"}),m.unusedWorkers.push(r),r},getNewWorker(){if(m.unusedWorkers.length==0){var r=m.allocateUnusedWorker();m.loadWasmModuleToWorker(r)}return m.unusedWorkers.pop()}},Ur=[],$;function Ut(r){var j=$[r+48>>2],n=$[r+52>>2],l=j-n;Hj(j,l),WA(j)}var Kr=[],Rr=r=>{var j=Kr[r];return j||(Kr[r]=j=Dj.get(r)),j},Kt=(r,j)=>{VA=0,zA=0;var n=Rr(r)(j);function l(o){if(QA()){z=o;return}lr(o)}l(n)},zA=!0,Rt=r=>m.tlsInitFunctions.push(r),iA,R;class Vt{constructor(j){this.excPtr=j,this.ptr=j-24}set_type(j){$[this.ptr+4>>2]=j}get_type(){return $[this.ptr+4>>2]}set_destructor(j){$[this.ptr+8>>2]=j}get_destructor(){return $[this.ptr+8>>2]}set_caught(j){j=j?1:0,R[this.ptr+12]=j}get_caught(){return R[this.ptr+12]!=0}set_rethrown(j){j=j?1:0,R[this.ptr+13]=j}get_rethrown(){return R[this.ptr+13]!=0}init(j,n){this.set_adjusted_ptr(0),this.set_type(j),this.set_destructor(n)}set_adjusted_ptr(j){$[this.ptr+16>>2]=j}get_adjusted_ptr(){return $[this.ptr+16>>2]}}var Qt=0,Wt=r=>{EA()},Xt=(r,j,n)=>{var l=new Vt(r);l.init(j,n),Qt++,Wt(r)},zt=()=>EA(""),x,H=r=>{for(var j="";;){var n=x[r++];if(!n)return j;j+=String.fromCharCode(n)}},Z={},Y={},hA={};class lA extends Error{constructor(j){super(j),this.name="BindingError"}}var G=r=>{throw new lA(r)};function Zt(r,j,n={}){var l=j.name;if(r||G(\`type "\${l}" must have a positive integer typeid pointer\`),Y.hasOwnProperty(r)){if(n.ignoreDuplicateRegistrations)return;G(\`Cannot register type '\${l}' twice\`)}if(Y[r]=j,delete hA[r],Z.hasOwnProperty(r)){var o=Z[r];delete Z[r],o.forEach(a=>a())}}function N(r,j,n={}){return Zt(r,j,n)}var $A,oA,Vr,Qr=(r,j,n)=>{switch(j){case 1:return n?l=>R[l]:l=>x[l];case 2:return n?l=>$A[l>>1]:l=>oA[l>>1];case 4:return n?l=>S[l>>2]:l=>$[l>>2];case 8:return n?l=>K[l>>3]:l=>Vr[l>>3];default:throw new TypeError(\`invalid integer width (\${j}): \${r}\`)}},Yt=(r,j,n,l,o)=>{j=H(j);let a=l===0n,k=u=>u;if(a){let u=n*8;k=c=>BigInt.asUintN(u,c),o=k(o)}N(r,{name:j,fromWireType:k,toWireType:(u,c)=>(typeof c=="number"&&(c=BigInt(c)),c),readValueFromPointer:Qr(j,n,!a),destructorFunction:null})},Ae=(r,j,n,l)=>{j=H(j),N(r,{name:j,fromWireType:function(o){return!!o},toWireType:function(o,a){return a?n:l},readValueFromPointer:function(o){return this.fromWireType(x[o])},destructorFunction:null})},re=r=>({count:r.count,deleteScheduled:r.deleteScheduled,preservePointerOnDelete:r.preservePointerOnDelete,ptr:r.ptr,ptrType:r.ptrType,smartPtr:r.smartPtr,smartPtrType:r.smartPtrType}),ZA=r=>{function j(n){return n.$$.ptrType.registeredClass.name}G(j(r)+" instance already deleted")},YA=!1,Wr=r=>{},je=r=>{r.smartPtr?r.smartPtrType.rawDestructor(r.smartPtr):r.ptrType.registeredClass.rawDestructor(r.ptr)},Xr=r=>{r.count.value-=1;var j=r.count.value===0;j&&je(r)},aA=r=>globalThis.FinalizationRegistry?(YA=new FinalizationRegistry(j=>{Xr(j.$$)}),aA=j=>{var n=j.$$,l=!!n.smartPtr;if(l){var o={$$:n};YA.register(j,o,j)}return j},Wr=j=>YA.unregister(j),aA(r)):(aA=j=>j,r),FA=[],te=()=>{for(;FA.length;){var r=FA.pop();r.$$.deleteScheduled=!1,r.delete()}},zr,ee=()=>{let r=vA.prototype;Object.assign(r,{isAliasOf(n){if(!(this instanceof vA)||!(n instanceof vA))return!1;var l=this.$$.ptrType.registeredClass,o=this.$$.ptr;n.$$=n.$$;for(var a=n.$$.ptrType.registeredClass,k=n.$$.ptr;l.baseClass;)o=l.upcast(o),l=l.baseClass;for(;a.baseClass;)k=a.upcast(k),a=a.baseClass;return l===a&&o===k},clone(){if(this.$$.ptr||ZA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var n=aA(Object.create(Object.getPrototypeOf(this),{$$:{value:re(this.$$)}}));return n.$$.count.value+=1,n.$$.deleteScheduled=!1,n},delete(){this.$$.ptr||ZA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),Wr(this),Xr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||ZA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),FA.push(this),FA.length===1&&zr&&zr(te),this.$$.deleteScheduled=!0,this}});let j=Symbol.dispose;j&&(r[j]=r.delete)};function vA(){}var Zr=(r,j)=>Object.defineProperty(j,"name",{value:r}),Yr={},Aj=(r,j,n)=>{if(r[j].overloadTable===void 0){var l=r[j];r[j]=function(...o){return r[j].overloadTable.hasOwnProperty(o.length)||G(\`Function '\${n}' called with an invalid number of arguments (\${o.length}) - expects one of (\${r[j].overloadTable})!\`),r[j].overloadTable[o.length].apply(this,o)},r[j].overloadTable=[],r[j].overloadTable[l.argCount]=l}},rj=(r,j,n)=>{t.hasOwnProperty(r)?((n===void 0||t[r].overloadTable!==void 0&&t[r].overloadTable[n]!==void 0)&&G(\`Cannot register public name '\${r}' twice\`),Aj(t,r,r),t[r].overloadTable.hasOwnProperty(n)&&G(\`Cannot register multiple overloads of a function with the same number of arguments (\${n})!\`),t[r].overloadTable[n]=j):(t[r]=j,t[r].argCount=n)},ne=48,se=57,ie=r=>{r=r.replace(/[^a-zA-Z0-9_]/g,"$");var j=r.charCodeAt(0);return j>=ne&&j<=se?\`_\${r}\`:r};function le(r,j,n,l,o,a,k,u){this.name=r,this.constructor=j,this.instancePrototype=n,this.rawDestructor=l,this.baseClass=o,this.getActualType=a,this.upcast=k,this.downcast=u,this.pureVirtualFunctions=[]}var IA=(r,j,n)=>{for(;j!==n;)j.upcast||G(\`Expected null or instance of \${n.name}, got an instance of \${j.name}\`),r=j.upcast(r),j=j.baseClass;return r},Ar=r=>{if(r===null)return"null";var j=typeof r;return j==="object"||j==="array"||j==="function"?r.toString():""+r};function oe(r,j){if(j===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;j.$$||G(\`Cannot pass "\${Ar(j)}" as a \${this.name}\`),j.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`);var n=j.$$.ptrType.registeredClass,l=IA(j.$$.ptr,n,this.registeredClass);return l}function ae(r,j){var n;if(j===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),this.isSmartPointer?(n=this.rawConstructor(),r!==null&&r.push(this.rawDestructor,n),n):0;(!j||!j.$$)&&G(\`Cannot pass "\${Ar(j)}" as a \${this.name}\`),j.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),!this.isConst&&j.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type \${this.name}\`);var l=j.$$.ptrType.registeredClass;if(n=IA(j.$$.ptr,l,this.registeredClass),this.isSmartPointer)switch(j.$$.smartPtr===void 0&&G("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:j.$$.smartPtrType===this?n=j.$$.smartPtr:G(\`Cannot convert argument of type \${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type \${this.name}\`);break;case 1:n=j.$$.smartPtr;break;case 2:if(j.$$.smartPtrType===this)n=j.$$.smartPtr;else{var o=j.clone();n=this.rawShare(n,tr.toHandle(()=>o.delete())),r!==null&&r.push(this.rawDestructor,n)}break;default:G("Unsupported sharing policy")}return n}function ke(r,j){if(j===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;j.$$||G(\`Cannot pass "\${Ar(j)}" as a \${this.name}\`),j.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),j.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${j.$$.ptrType.name} to parameter type \${this.name}\`);var n=j.$$.ptrType.registeredClass,l=IA(j.$$.ptr,n,this.registeredClass);return l}function _A(r){return this.fromWireType($[r>>2])}var jj=(r,j,n)=>{if(j===n)return r;if(n.baseClass===void 0)return null;var l=jj(r,j,n.baseClass);return l===null?null:n.downcast(l)},ue={},ce=(r,j)=>{for(j===void 0&&G("ptr should not be undefined");r.baseClass;)j=r.upcast(j),r=r.baseClass;return j},de=(r,j)=>(j=ce(r,j),ue[j]);class Ce extends Error{constructor(j){super(j),this.name="InternalError"}}var HA=r=>{throw new Ce(r)},LA=(r,j)=>{(!j.ptrType||!j.ptr)&&HA("makeClassHandle requires ptr and ptrType");var n=!!j.smartPtrType,l=!!j.smartPtr;return n!==l&&HA("Both smartPtrType and smartPtr must be specified"),j.count={value:1},aA(Object.create(r,{$$:{value:j,writable:!0}}))};function fe(r){var j=this.getPointee(r);if(!j)return this.destructor(r),null;var n=de(this.registeredClass,j);if(n!==void 0){if(n.$$.count.value===0)return n.$$.ptr=j,n.$$.smartPtr=r,n.clone();var l=n.clone();return this.destructor(r),l}function o(){return this.isSmartPointer?LA(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:j,smartPtrType:this,smartPtr:r}):LA(this.registeredClass.instancePrototype,{ptrType:this,ptr:r})}var a=this.registeredClass.getActualType(j),k=Yr[a];if(!k)return o.call(this);var u;this.isConst?u=k.constPointerType:u=k.pointerType;var c=jj(j,this.registeredClass,u.registeredClass);return c===null?o.call(this):this.isSmartPointer?LA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c,smartPtrType:this,smartPtr:r}):LA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c})}var qe=()=>{Object.assign(yA.prototype,{getPointee(r){return this.rawGetPointee&&(r=this.rawGetPointee(r)),r},destructor(r){this.rawDestructor?.(r)},readValueFromPointer:_A,fromWireType:fe})};function yA(r,j,n,l,o,a,k,u,c,q,f){this.name=r,this.registeredClass=j,this.isReference=n,this.isConst=l,this.isSmartPointer=o,this.pointeeType=a,this.sharingPolicy=k,this.rawGetPointee=u,this.rawConstructor=c,this.rawShare=q,this.rawDestructor=f,!o&&j.baseClass===void 0?l?(this.toWireType=oe,this.destructorFunction=null):(this.toWireType=ke,this.destructorFunction=null):this.toWireType=ae}var tj=(r,j,n)=>{t.hasOwnProperty(r)||HA("Replacing nonexistent public symbol"),t[r].overloadTable!==void 0&&n!==void 0?t[r].overloadTable[n]=j:(t[r]=j,t[r].argCount=n)},P=(r,j,n=!1)=>{r=H(r);function l(){var a=Rr(j);return a}var o=l();return typeof o!="function"&&G(\`unknown function pointer with signature \${r}: \${j}\`),o};class Ge extends Error{}var pe=r=>{var j=Ej(r),n=H(j);return w(j),n},AA=(r,j)=>{var n=[],l={};function o(a){if(!l[a]&&!Y[a]){if(hA[a]){hA[a].forEach(o);return}n.push(a),l[a]=!0}}throw j.forEach(o),new Ge(\`\${r}: \`+n.map(pe).join([", "]))},M=(r,j,n)=>{r.forEach(u=>hA[u]=j);function l(u){var c=n(u);c.length!==r.length&&HA("Mismatched type converter count");for(var q=0;q<r.length;++q)N(r[q],c[q])}var o=new Array(j.length),a=[],k=0;for(let[u,c]of j.entries())Y.hasOwnProperty(c)?o[u]=Y[c]:(a.push(c),Z.hasOwnProperty(c)||(Z[c]=[]),Z[c].push(()=>{o[u]=Y[c],++k,k===a.length&&l(o)}));a.length===0&&l(o)},Ee=(r,j,n,l,o,a,k,u,c,q,f,p,v)=>{f=H(f),a=P(o,a),u&&=P(k,u),q&&=P(c,q),v=P(p,v);var I=ie(f);rj(I,function(){AA(\`Cannot construct \${f} due to unbound types\`,[l])}),M([r,j,n],l?[l]:[],F=>{F=F[0];var h,b;l?(h=F.registeredClass,b=h.instancePrototype):b=vA.prototype;var y=Zr(f,function(...or){if(Object.getPrototypeOf(this)!==Q)throw new lA(\`Use 'new' to construct \${f}\`);if(g.constructor_body===void 0)throw new lA(\`\${f} has no accessible constructor\`);var Oj=g.constructor_body[or.length];if(Oj===void 0)throw new lA(\`Tried to invoke ctor of \${f} with invalid number of parameters (\${or.length}) - expected (\${Object.keys(g.constructor_body).toString()}) parameters instead!\`);return Oj.apply(this,or)}),Q=Object.create(b,{constructor:{value:y}});y.prototype=Q;var g=new le(f,y,Q,v,h,a,u,q);g.baseClass&&(g.baseClass.__derivedClasses??=[],g.baseClass.__derivedClasses.push(g));var Cn=new yA(f,g,!0,!1,!1),Nj=new yA(f+"*",g,!1,!1,!1),bj=new yA(f+" const*",g,!1,!0,!1);return Yr[r]={pointerType:Nj,constPointerType:bj},tj(I,y),[Cn,Nj,bj]})},rr=(r,j)=>{for(var n=[],l=0;l<r;l++)n.push($[j+l*4>>2]);return n},ej=r=>{for(;r.length;){var j=r.pop(),n=r.pop();n(j)}};function nj(r){for(var j=1;j<r.length;++j)if(r[j]!==null&&r[j].destructorFunction===void 0)return!0;return!1}function sj(r){for(var j=1;j<r.length;++j)if(r[j]!==null&&r[j].argStackAlloc)return!0;return!1}function me(r,j,n,l){var o=nj(r),a=sj(r),k=a&&!l&&!o;a&&!k&&(o=!0);var u=r.length-2,c=[],q=["fn"];j&&q.push("thisWired");for(var f=0;f<u;++f)c.push(\`arg\${f}\`),q.push(\`arg\${f}Wired\`);c=c.join(),q=q.join();var p=\`return function (\${c}) {
|
|
3365
3365
|
\`;o&&(p+=\`var destructors = [];
|
|
3366
3366
|
\`),k&&(p+=\`var sp = stackSave();
|
|
3367
3367
|
try {
|
|
@@ -3376,8 +3376,8 @@ stackRestore(sp);
|
|
|
3376
3376
|
\`,I.push(\`\${h}_dtor\`))}return n&&(p+=\`var ret = fromRetWire(rv);
|
|
3377
3377
|
return ret;
|
|
3378
3378
|
\`),p+=\`}
|
|
3379
|
-
\`,new Function(I,p)}function jr(r,j,n,l,o,a){var k=j.length;k<2&&G("argTypes array size mismatch! Must at least get return value and receiver (this) types!");var u=j[1]!==null&&n!==null,c=nj(j),q=sj(j),f=q&&!a&&!c;q&&!f&&(c=!0);var p=!j[0].isVoid,v=j[0],I=j[1],F=[r,G,l,o,ej,v.fromWireType.bind(v),I?.toWireType.bind(I)];f&&F.push(wr,WA);for(var h=2;h<k;++h){var b=j[h];F.push(b.toWireType.bind(b))}if(!c)for(var h=u?1:2;h<j.length;++h)j[h].destructorFunction!==null&&F.push(j[h].destructorFunction);var Q=me(j,u,p,a)(...F);return Zr(r,Q)}var he=(r,j,n,l,o,a)=>{var k=rr(j,n);o=P(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]=()=>{AA(\`Cannot construct \${u.name} due to unbound types\`,k)},M([],k,q=>(q.splice(1,0,null),u.registeredClass.constructor_body[j-1]=jr(c,q,null,o,a),[])),[]})},ij=r=>{r=r.trim();let j=r.indexOf("(");return j===-1?r:r.slice(0,j)},$e=(r,j,n,l,o,a,k,u,c,q)=>{var f=rr(n,l);j=H(j),j=ij(j),a=P(o,a,c),M([],[r],p=>{p=p[0];var v=\`\${p.name}.\${j}\`;j.startsWith("@@")&&(j=Symbol[j.substring(2)]),u&&p.registeredClass.pureVirtualFunctions.push(j);function I(){AA(\`Cannot call \${v} due to unbound types\`,f)}var F=p.registeredClass.instancePrototype,h=F[j];return h===void 0||h.overloadTable===void 0&&h.className!==p.name&&h.argCount===n-2?(I.argCount=n-2,I.className=p.name,F[j]=I):(Aj(F,j,v),F[j].overloadTable[n-2]=I),M([],f,b=>{var y=jr(v,b,p,a,k,c);return F[j].overloadTable===void 0?(y.argCount=n-2,F[j]=y):F[j].overloadTable[n-2]=y,[]}),[]})},lj=(r,j,n)=>(r instanceof Object||G(\`\${n} with invalid "this": \${r}\`),r instanceof j.registeredClass.constructor||G(\`\${n} incompatible with "this" of type \${r.constructor.name}\`),r.$$.ptr||G(\`cannot call emscripten binding method \${n} on deleted object\`),IA(r.$$.ptr,r.$$.ptrType.registeredClass,j.registeredClass)),Fe=(r,j,n,l,o,a,k,u,c,q)=>{j=H(j),o=P(l,o),M([],[r],f=>{f=f[0];var p=\`\${f.name}.\${j}\`,v={get(){AA(\`Cannot access \${p} due to unbound types\`,[n,k])},enumerable:!0,configurable:!0};return c?v.set=()=>AA(\`Cannot access \${p} due to unbound types\`,[n,k]):v.set=I=>G(p+" is a read-only property"),Object.defineProperty(f.registeredClass.instancePrototype,j,v),M([],c?[n,k]:[n],I=>{var F=I[0],h={get(){var y=lj(this,f,p+" getter");return F.fromWireType(o(a,y))},enumerable:!0};if(c){c=P(u,c);var b=I[1];h.set=function(y){var Q=lj(this,f,p+" setter"),g=[];c(q,Q,b.toWireType(g,y)),ej(g)}}return Object.defineProperty(f.registeredClass.instancePrototype,j,h),[]}),[]})},oj=[],V=[0,1,,1,null,1,!0,1,!1,1],ve=r=>{if(r>9&&--V[r+1]===0){var j=V[r];V[r]=void 0,oj.push(r)}},tr={toValue:r=>(r||G(\`Cannot use deleted val. handle = \${r}\`),V[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=oj.pop()||V.length;return V[j]=r,V[j+1]=1,j}}}},Ie={name:"emscripten::val",fromWireType:r=>{var j=tr.toValue(r);return ve(r),j},toWireType:(r,j)=>tr.toHandle(j),readValueFromPointer:_A,destructorFunction:null},_e=r=>N(r,Ie),aj,He=(r,j)=>{switch(j){case 4:return function(n){return this.fromWireType(aj[n>>2])};case 8:return function(n){return this.fromWireType(mA[n>>3])};default:throw new TypeError(\`invalid float width (\${j}): \${r}\`)}},Le=(r,j,n)=>{j=H(j),N(r,{name:j,fromWireType:l=>l,toWireType:(l,o)=>o,readValueFromPointer:He(j,n),destructorFunction:null})},ye=(r,j,n,l,o,a,k,u)=>{var c=rr(j,n);r=H(r),r=ij(r),o=P(l,o,k),rj(r,function(){AA(\`Cannot call \${r} due to unbound types\`,c)},j-1),M([],c,q=>{var f=[q[0],null].concat(q.slice(1));return tj(r,jr(r,f,null,o,a,k),j-1),[]})},ge=(r,j,n,l,o)=>{j=H(j);let a=l===0,k=c=>c;if(a){var u=32-8*n;k=c=>c<<u>>>u,o=k(o)}N(r,{name:j,fromWireType:k,toWireType:(c,q)=>q,readValueFromPointer:Qr(j,n,l!==0),destructorFunction:null})},De=(r,j,n)=>{var l=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=l[j];function a(k){var u=$[k>>2],c=$[k+4>>2];return new o(R.buffer,c,u)}n=H(n),N(r,{name:n,fromWireType:a,readValueFromPointer:a},{ignoreDuplicateRegistrations:!0})},xe=(r,j,n,l)=>{if(!(l>0))return 0;for(var o=n,a=n+l-1,k=0;k<r.length;++k){var u=r.codePointAt(k);if(u<=127){if(n>=a)break;j[n++]=u}else if(u<=2047){if(n+1>=a)break;j[n++]=192|u>>6,j[n++]=128|u&63}else if(u<=65535){if(n+2>=a)break;j[n++]=224|u>>12,j[n++]=128|u>>6&63,j[n++]=128|u&63}else{if(n+3>=a)break;j[n++]=240|u>>18,j[n++]=128|u>>12&63,j[n++]=128|u>>6&63,j[n++]=128|u&63,k++}}return j[n]=0,n-o},Be=(r,j,n)=>xe(r,x,j,n),Ne=r=>{for(var j=0,n=0;n<r.length;++n){var l=r.charCodeAt(n);l<=127?j++:l<=2047?j+=2:l>=55296&&l<=57343?(j+=4,++n):j+=3}return j},kj=globalThis.TextDecoder&&new TextDecoder,uj=(r,j,n,l)=>{var o=j+n;if(l)return o;for(;r[j]&&!(j>=o);)++j;return j},cj=(r,j=0,n,l)=>{var o=uj(r,j,n,l);if(o-j>16&&r.buffer&&kj)return kj.decode(r.buffer instanceof ArrayBuffer?r.subarray(j,o):r.slice(j,o));for(var a="";j<o;){var k=r[j++];if(!(k&128)){a+=String.fromCharCode(k);continue}var u=r[j++]&63;if((k&224)==192){a+=String.fromCharCode((k&31)<<6|u);continue}var c=r[j++]&63;if((k&240)==224?k=(k&15)<<12|u<<6|c:k=(k&7)<<18|u<<12|c<<6|r[j++]&63,k<65536)a+=String.fromCharCode(k);else{var q=k-65536;a+=String.fromCharCode(55296|q>>10,56320|q&1023)}}return a},be=(r,j,n)=>r?cj(x,r,j,n):"",Oe=(r,j)=>{j=H(j);var n=!0;N(r,{name:j,fromWireType(l){var o=$[l>>2],a=l+4,k;if(n)k=be(a,o,!0);else{k="";for(var u=0;u<o;++u)k+=String.fromCharCode(x[a+u])}return w(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"),n&&k?a=Ne(o):a=o.length;var u=sr(4+a+1),c=u+4;if($[u>>2]=a,k)if(n)Be(o,c,a+1);else for(var q=0;q<a;++q){var f=o.charCodeAt(q);f>255&&(w(u),G("String has UTF-16 code units that do not fit in 8 bits")),x[c+q]=f}else x.set(o,c);return l!==null&&l.push(w,u),u},readValueFromPointer:_A,destructorFunction(l){w(l)}})},dj=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Je=(r,j,n)=>{var l=r>>1,o=uj(oA,l,j/2,n);if(o-l>16&&dj)return dj.decode(oA.slice(l,o));for(var a="",k=l;k<o;++k){var u=oA[k];a+=String.fromCharCode(u)}return a},Pe=(r,j,n=2147483647)=>{if(n<2)return 0;n-=2;for(var l=j,o=n<r.length*2?n/2:r.length,a=0;a<o;++a){var k=r.charCodeAt(a);$A[j>>1]=k,j+=2}return $A[j>>1]=0,j-l},we=r=>r.length*2,Te=(r,j,n)=>{for(var l="",o=r>>2,a=0;!(a>=j/4);a++){var k=$[o+a];if(!k&&!n)break;l+=String.fromCodePoint(k)}return l},Se=(r,j,n=2147483647)=>{if(n<4)return 0;for(var l=j,o=l+n-4,a=0;a<r.length;++a){var k=r.codePointAt(a);if(k>65535&&a++,S[j>>2]=k,j+=4,j+4>o)break}return S[j>>2]=0,j-l},Me=r=>{for(var j=0,n=0;n<r.length;++n){var l=r.codePointAt(n);l>65535&&n++,j+=4}return j},Ue=(r,j,n)=>{n=H(n);var l,o,a;j===2?(l=Je,o=Pe,a=we):(l=Te,o=Se,a=Me),N(r,{name:n,fromWireType:k=>{var u=$[k>>2],c=l(k+4,u*j,!0);return w(k),c},toWireType:(k,u)=>{typeof u!="string"&&G(\`Cannot pass non-string to C++ string type \${n}\`);var c=a(u),q=sr(4+c+j);return $[q>>2]=c/j,o(u,q+4,c+j),k!==null&&k.push(w,q),q},readValueFromPointer:_A,destructorFunction(k){w(k)}})},Ke=(r,j)=>{j=H(j),N(r,{isVoid:!0,name:j,fromWireType:()=>{},toWireType:(n,l)=>{}})},Re=r=>{var j=!s;try{Atomics.wait(S,0,0,0),j=!0}catch{}ir(r,!i,1,j,65536,!1),m.threadInitTLS()},Cj=r=>{if(r instanceof Nr||r=="unwind")return z;D(1,r)},Ve=()=>{if(!QA())try{if(C){kA()&&lr(z);return}XA(z)}catch(r){Cj(r)}},fj=r=>{if(!pA)try{return r()}catch(j){Cj(j)}finally{Ve()}},er=r=>{if(!Mr){var j=Atomics.waitAsync(S,r>>2,r);j.value.then(gA);var n=r+112;Atomics.store(S,n>>2,1)}},gA=()=>{var r=kA();r&&fj(()=>{er(r),_j()})},Qe=(r,j)=>{if(r==j)setTimeout(gA);else if(C)postMessage({targetThread:r,cmd:4});else{var n=m.pthreads[r];if(!n)return;n.postMessage({cmd:4})}},nr=[],We=(r,j,n,l,o,a,k)=>{nr.length=0;for(var u=o>>3,c=o+l>>3;u<c;){var q;K[u++]?q=K[u++]:q=mA[u++],nr.push(q)}var f=an[r];m.currentProxiedOperationCallerThread=n;var p=f(...nr);if(m.currentProxiedOperationCallerThread=0,a){Promise.resolve(p).then(v=>Fj(a,k,v));return}return p},Xe=r=>{C?postMessage({cmd:6,thread:r}):Or(r)},ze=r=>{},Ze=()=>performance.timeOrigin+performance.now(),Ye=9007199254740992,An=-9007199254740992,rn=r=>r<An||r>Ye?NaN:Number(r),jn=()=>{},tn=()=>{VA+=1},en=()=>{throw tn(),"unwind"},nn=r=>{EA("OOM")},sn=r=>{var j=x.length;r>>>=0,nn(r)};function qj(r){return C?sA(2,0,1,r):52}function Gj(r,j,n,l){return C?sA(3,0,1,r,j,n,l):(j=rn(j),70)}var ln=[null,[],[]],on=(r,j)=>{var n=ln[r];!j||j===10?((r===1?KA:J)(cj(n)),n.length=0):n.push(j)};function pj(r,j,n,l){if(C)return sA(4,0,1,r,j,n,l);for(var o=0,a=0;a<n;a++){var k=$[j>>2],u=$[j+4>>2];j+=8;for(var c=0;c<u;c++)on(r,x[k+c]);o+=u}return $[l>>2]=o,0}m.init(),ee(),qe();{Bt(),t.noExitRuntime&&(zA=t.noExitRuntime),t.print&&(KA=t.print),t.printErr&&(J=t.printErr),t.arguments&&(E=t.arguments),t.thisProgram&&(_=t.thisProgram);var rA=t.preInit;if(rA)for(typeof rA=="function"&&(t.preInit=rA=[rA]);rA.length>0;)rA.shift()()}var an=[Tr,Sr,qj,Gj,pj],Ej,mj,kA,sr,w,kn,ir,hj,$j,Fj,vj,Ij,lr,_j,Hj,Lj,yj,gj,un,Dj;function cn(r){Ej=r.G,mj=r.H,kA=r.J,sr=t._malloc=r.K,w=t._free=r.L,kn=r.M,ir=r.N,hj=r.O,$j=r.P,Fj=r.Q,vj=r.R,Ij=r.S,lr=r.T,_j=r.U,Hj=r.V,Lj=r.W,yj=r.X,gj=r.Y,un=Dj=r.I}var xj;function dn(){xj={l:Xt,C:zt,h:Yt,o:Ae,n:Ee,m:he,e:$e,b:Fe,D:_e,g:Le,q:ye,d:ge,c:De,E:Oe,f:Ue,p:Ke,z:Re,u:Qe,j:We,s:Xe,y:er,B:ze,x:jn,A:en,k:Ze,t:sn,r:XA,w:qj,v:Gj,i:pj,a:iA}}async function Bj(){if(C){gr();return}Nt();var r=t.setStatus;r&&(r("Running..."),await new Promise(j=>setTimeout(j,1)),setTimeout(r,1,"")),!pA&&(gr(),t.onRuntimeInitialized?.(),bt())}var jA;return C||(jA=await Br(),await Bj()),t}})();typeof Ft=="object"&&typeof MA=="object"?(MA.exports=SA,MA.exports.default=SA):typeof define=="function"&&define.amd&&define([],()=>SA);var gs=globalThis.name=="em-pthread";gs&&SA()});var O={};hn(O,{AdditionalCaptureBlocks:()=>In,AdditionalPlaybackBlocks:()=>vn,ClockJumpCheckInterval:()=>xn,ClockJumpThreshold:()=>Bn,ConnectInterval:()=>Un,ConnectTimeout:()=>Tn,DefaultRefreshRate:()=>Hn,DefaultVideoCodec:()=>Rn,HealthCheckTimeout:()=>Dn,MainConnectionPingInterval:()=>Nn,MaxNumberOfDecoders:()=>yn,MaxReconnectDuration:()=>Kn,MinDBFs:()=>Jj,MinTokenLifetime:()=>Sn,MinTokenRefreshInterval:()=>Mn,PlaybackPreload:()=>_n,RenderQuantumSize:()=>gn,VadPreload:()=>Ln,WebRtcAnswerTimeout:()=>Pn,WebRtcIceTimeout:()=>On,WebRtcMaxNegotiationAttempts:()=>wn,WebRtcStatsSnapshotInterval:()=>bn,WebRtcTimeout:()=>Jn});var vn=3,In=3,_n=3,Hn=250,Ln=3,yn=512,gn=128,Jj=-758.596,Dn=1e4,xn=1e3,Bn=1e4,Nn=3e3,bn=1e3,On=3e3,Jn=1e4,Pn=1e4,wn=3,Tn=5e3,Sn=6e4,Mn=5e3,Un=[0,100,200,200,500],Kn=12e4,Rn="H264";function uA(e,A,t){return e.postMessage(A,t)}function kr(e){return e.sampleRate*.02*(e.stereo?2:1)}function ur(e,A){let t=kr(e),s=t*A,i=s+t;return e.samples.subarray(s,i)}function cr(e,A,t){e.headers[A]=t.id}function Pj(e){return[e.values[0],e.values[1]]}function wj(e,A){e.values[0]=A[0],e.values[1]=A[1]}function Tj(e,A){return e.values[2+A*5]}function Sj(e,A,t){e.values[2+A*5]=t}function Mj(e,A){let t=2+A*5+1;return[e.values[t+0],e.values[t+1]]}function Uj(e,A,t){let s=2+A*5+1;e.values[s+0]=t[0],e.values[s+1]=t[1]}function Kj(e,A){return e.values[2+A*5+3]}function Rj(e,A,t){e.values[2+A*5+3]=t}function Vj(e,A){return e.values[2+A*5+4]}function Qj(e,A,t){e.values[2+A*5+4]=t}function Wj(e){return e.values[0]!==0}function Xj(e){return e.values[1]}function zj(e){return e.values[2]}function Zj(e){return e.values[3]}function Yj(e,A){return e.values[3]=A}function At(e){return e?Array.from(e).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var Vn;(e=>{let A;(t=>(t[t.InvalidPassword=-1]="InvalidPassword",t[t.Unknown=0]="Unknown",t[t.Unencrypted=1]="Unencrypted",t[t.Encrypted=2]="Encrypted"))(A=e.PeerCipherStatus||={})})(Vn||={});function nt(e){return{type:"Success",value:e}}function B(e){return{type:"Failure",reason:e}}var{Deno:rt}=globalThis,Qn=typeof rt?.noColor=="boolean"?rt.noColor:!1,Wn=!Qn;function Cr(e,A){return{open:\`\\x1B[\${e.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function fr(e,A){return Wn?\`\${A.open}\${e.replace(A.regexp,A.open)}\${A.close}\`:e}function dr(e){return fr(e,Cr([0],0))}function jt(e){return fr(e,Cr([1],22))}function Xn(e){return fr(e,Cr([2],22))}var Rs=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"),zn=new Date,DA=(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))(DA||{}),st={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},Zn={4:Xn,3:dr,2:dr,1:jt,0:jt};function Yn({message:e}){return String(e)}function tt(e){return JSON.stringify({timestamp:e.date.toISOString(),level:DA[e.level],message:e.message,extra:e.extra})}function et(e){function A(C,E){return[Math.floor(C/E),C%E]}function t(){let C,E=e.date.valueOf()-zn.valueOf();[E,C]=A(E,1e3);let[_,D]=A(E,60);return\`\${_.toString().padStart(4,"0")}:\${D.toString().padStart(2,"0")}.\${C.toString().padStart(3,"0")}\`}function s(){return e.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(e.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(e.extra)}let i=st[e.level],d=e.logger.name!==void 0?\`@\${e.logger.name}\`:"";return\`\${dr(t())}\${d} \${i} \${Zn[e.level](String(e.message))}\${s()}\`}function As(e){let A=\`[\${e.date.toISOString()}]\`,t=\`[\${DA[e.level]}]\`,s=e.logger.name!==void 0?\`[\${e.logger.name}] \`:"",i=st[e.level];return\`\${A} \${i} \${t.padEnd(7," ")} \${s}\${e.message}\`}function rs(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var it=class{static sparse=Yn;static json=tt;static pretty=et;static structured=As;static default=rs()?et:tt;constructor(){}};var js=class{formatter;consoleObject;filter;constructor(e=it.default,A=4,t=console){this.filter=A,this.formatter=e,this.consoleObject=t}handle(e){let A=this.formatter(e);switch(e.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 W=class{#A;sinks;filter;parent;get name(){return this.#A}constructor(e,A=void 0,t=[],s=void 0){this.#A=A,this.sinks=t,this.filter=e,this.parent=s}log(e,A,t=void 0){let s={date:new Date,level:e,logger:this,message:A,extra:t};this.filter<e||this.insert(s)}insert(e){if(!(this.filter<e.level)){for(let A of this.sinks)A.filter>=e.level&&A.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)},cA=globalThis[Symbol.for("odin-global-logger")]??=new W(3,void 0,[new js]),ts=W.prototype.log.bind(cA,1),es=W.prototype.log.bind(cA,2),lt=W.prototype.log.bind(cA,3),ns=W.prototype.log.bind(cA,4),Vs=W.prototype.log.bind(cA);var ot;function at(e,...A){let t=ss(A);ot?ot?.info(e,t):lt(e,t)}function ss(...e){if(e.length===1&&typeof e[0]=="object"&&e[0]!==null)return{...e[0]};if(e.length>0)return{args:e}}function xA(e){return e.connectionId*4294967296+e.mediaId}function kt(e){return{mediaId:e%4294967296,connectionId:Math.floor(e/4294967296)}}function U(e,A,t){let s;switch(A){case"f32":s=e.HEAPF32;break;case"u32":s=e.HEAPU32;break;case"i32":s=e.HEAP32;break;case"u8":s=e.HEAPU8;break;default:throw new Error(\`allocating \${A} is not supported\`)}let i=e._malloc(t*s.BYTES_PER_ELEMENT);if(i===0||i%s.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${t} \${A} array\`);let d=i/s.BYTES_PER_ELEMENT;return s.subarray(d,d+t)}function tA(e,A){e._free(A.byteOffset)}function qr(e,A,t,s){return{headers:U(e,"i32",t),samples:U(e,"f32",t*kr({sampleRate:A,stereo:s})),length:t,sampleRate:A,stereo:s}}function Gr(e,A){tA(e,A.headers),tA(e,A.samples)}function ut(e,A){return{values:U(e,"f32",2+A*5),length:A}}function ct(e,A){tA(e,A.values)}function dt(e){return{values:U(e,"f32",4)}}function Ct(e,A){tA(e,A.values)}function ft(e){let A=e.length,t=0,s=0;for(;s<A;){let i=e.charCodeAt(s++);if((i&4294967168)===0){t++;continue}else if((i&4294965248)===0)t+=2;else{if(i>=55296&&i<=56319&&s<A){let d=e.charCodeAt(s);(d&64512)===56320&&(++s,i=((i&1023)<<10)+(d&1023)+65536)}(i&4294901760)===0?t+=3:t+=4}}return t}function is(e,A,t){let s=e.length,i=t,d=0;for(;d<s;){let C=e.charCodeAt(d++);if((C&4294967168)===0){A[i++]=C;continue}else if((C&4294965248)===0)A[i++]=C>>6&31|192;else{if(C>=55296&&C<=56319&&d<s){let E=e.charCodeAt(d);(E&64512)===56320&&(++d,C=((C&1023)<<10)+(E&1023)+65536)}(C&4294901760)===0?(A[i++]=C>>12&15|224,A[i++]=C>>6&63|128):(A[i++]=C>>18&7|240,A[i++]=C>>12&63|128,A[i++]=C>>6&63|128)}A[i++]=C&63|128}}var ls=new TextEncoder,os=50;function as(e,A,t){ls.encodeInto(e,A.subarray(t))}function qt(e,A,t){e.length>os?as(e,A,t):is(e,A,t)}var ks=4096;function pr(e,A,t){let s=A,i=s+t,d=[],C="";for(;s<i;){let E=e[s++];if((E&128)===0)d.push(E);else if((E&224)===192){let _=e[s++]&63;d.push((E&31)<<6|_)}else if((E&240)===224){let _=e[s++]&63,D=e[s++]&63;d.push((E&31)<<12|_<<6|D)}else if((E&248)===240){let _=e[s++]&63,D=e[s++]&63,UA=e[s++]&63,T=(E&7)<<18|_<<12|D<<6|UA;T>65535&&(T-=65536,d.push(T>>>10&1023|55296),T=56320|T&1023),d.push(T)}else d.push(E);d.length>=ks&&(C+=String.fromCharCode(...d),d.length=0)}return d.length>0&&(C+=String.fromCharCode(...d)),C}var us=new TextDecoder,cs=200;function ds(e,A,t){let s=e.subarray(A,A+t);return us.decode(s)}function Gt(e,A,t){return t>cs?ds(e,A,t):pr(e,A,t)}var X=class{type;data;constructor(A,t){this.type=A,this.data=t}};var L=class e extends Error{constructor(A){super(A);let t=Object.create(e.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}};function pt(e,A,t){let s=t/4294967296,i=t;e.setUint32(A,s),e.setUint32(A+4,i)}function BA(e,A,t){let s=Math.floor(t/4294967296),i=t;e.setUint32(A,s),e.setUint32(A+4,i)}function NA(e,A){let t=e.getInt32(A),s=e.getUint32(A+4);return t*4294967296+s}function Et(e,A){let t=e.getUint32(A),s=e.getUint32(A+4);return t*4294967296+s}var Cs=-1,fs=4294967296-1,qs=17179869184-1;function Gs({sec:e,nsec:A}){if(e>=0&&A>=0&&e<=qs)if(A===0&&e<=fs){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t}else{let t=e/4294967296,s=e&4294967295,i=new Uint8Array(8),d=new DataView(i.buffer);return d.setUint32(0,A<<2|t&3),d.setUint32(4,s),i}else{let t=new Uint8Array(12),s=new DataView(t.buffer);return s.setUint32(0,A),BA(s,4,e),t}}function ps(e){let A=e.getTime(),t=Math.floor(A/1e3),s=(A-t*1e3)*1e6,i=Math.floor(s/1e9);return{sec:t+i,nsec:s-i*1e9}}function Es(e){if(e instanceof Date){let A=ps(e);return Gs(A)}else return null}function ms(e){let A=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:A.getUint32(0),nsec:0};case 8:{let t=A.getUint32(0),s=A.getUint32(4),i=(t&3)*4294967296+s,d=t>>>2;return{sec:i,nsec:d}}case 12:{let t=NA(A,4),s=A.getUint32(0);return{sec:t,nsec:s}}default:throw new L(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${e.length}\`)}}function hs(e){let A=ms(e);return new Date(A.sec*1e3+A.nsec/1e6)}var mt={type:Cs,encode:Es,decode:hs};var eA=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(mt)}register({type:A,encode:t,decode:s}){if(A>=0)this.encoders[A]=t,this.decoders[A]=s;else{let i=-1-A;this.builtInEncoders[i]=t,this.builtInDecoders[i]=s}}tryToEncode(A,t){for(let s=0;s<this.builtInEncoders.length;s++){let i=this.builtInEncoders[s];if(i!=null){let d=i(A,t);if(d!=null){let C=-1-s;return new X(C,d)}}}for(let s=0;s<this.encoders.length;s++){let i=this.encoders[s];if(i!=null){let d=i(A,t);if(d!=null){let C=s;return new X(C,d)}}}return A instanceof X?A:null}decode(A,t,s){let i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(A,t,s):new X(t,A)}};function $s(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function dA(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):$s(e)?new Uint8Array(e):Uint8Array.from(e)}var Fs=100,vs=2048,bA=class e{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(A){this.extensionCodec=A?.extensionCodec??eA.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??Fs,this.initialBufferSize=A?.initialBufferSize??vs,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 e({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),s=new Uint8Array(t),i=new DataView(t);s.set(this.bytes),this.view=i,this.bytes=s}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 s=ft(A);this.ensureBufferSizeToWrite(5+s),this.writeStringHeader(s),qt(A,this.bytes,this.pos),this.pos+=s}encodeObject(A,t){let s=this.extensionCodec.tryToEncode(A,this.context);if(s!=null)this.encodeExtension(s);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 s=dA(A);this.writeU8a(s)}encodeArray(A,t){let s=A.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else if(s<4294967296)this.writeU8(221),this.writeU32(s);else throw new Error(\`Too large array: \${s}\`);for(let i of A)this.doEncode(i,t+1)}countWithoutUndefined(A,t){let s=0;for(let i of t)A[i]!==void 0&&s++;return s}encodeMap(A,t){let s=Object.keys(A);this.sortKeys&&s.sort();let i=this.ignoreUndefined?this.countWithoutUndefined(A,s):s.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 s){let C=A[d];this.ignoreUndefined&&C===void 0||(this.encodeString(d),this.doEncode(C,t+1))}}encodeExtension(A){if(typeof A.data=="function"){let s=A.data(this.pos+6),i=s.length;if(i>=4294967296)throw new Error(\`Too large extension object: \${i}\`);this.writeU8(201),this.writeU32(i),this.writeI8(A.type),this.writeU8a(s);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),pt(this.view,this.pos,A),this.pos+=8}writeI64(A){this.ensureBufferSizeToWrite(8),BA(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 Er(e,A){return new bA(A).encodeSharedRef(e)}function OA(e){return\`\${e<0?"-":""}0x\${Math.abs(e).toString(16).padStart(2,"0")}\`}var Is=16,_s=16,JA=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(A=Is,t=_s){this.maxKeyLength=A,this.maxLengthPerKey=t,this.caches=[];for(let s=0;s<this.maxKeyLength;s++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,t,s){let i=this.caches[s-1];A:for(let d of i){let C=d.bytes;for(let E=0;E<s;E++)if(C[E]!==A[t+E])continue A;return d.str}return null}store(A,t){let s=this.caches[A.length-1],i={bytes:A,str:t};s.length>=this.maxLengthPerKey?s[Math.random()*s.length|0]=i:s.push(i)}decode(A,t,s){let i=this.find(A,t,s);if(i!=null)return this.hit++,i;this.miss++;let d=pr(A,t,s),C=Uint8Array.prototype.slice.call(A,t,t+s);return this.store(C,d),d}};var mr="array",qA="map_key",$t="map_value",Hs=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new L("The type of key must be string or number but "+typeof e)},hr=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let t=this.getUninitializedStateFromPool();t.type=mr,t.position=0,t.size=A,t.array=new Array(A)}pushMapState(A){let t=this.getUninitializedStateFromPool();t.type=qA,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===mr){let s=A;s.size=0,s.array=void 0,s.position=0,s.type=void 0}if(A.type===qA||A.type===$t){let s=A;s.size=0,s.map=void 0,s.readCount=0,s.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},fA=-1,$r=new DataView(new ArrayBuffer(0)),Ls=new Uint8Array($r.buffer);try{$r.getInt8(0)}catch(e){if(!(e 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 ht=new RangeError("Insufficient data"),ys=new JA,PA=class e{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=$r;bytes=Ls;headByte=fA;stack=new hr;entered=!1;constructor(A){this.extensionCodec=A?.extensionCodec??eA.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:ys,this.mapKeyConverter=A?.mapKeyConverter??Hs}clone(){return new e({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),s=dA(A),i=new Uint8Array(t.length+s.length);i.set(t),i.set(s,t.length),this.setBuffer(i)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:t,pos:s}=this;return new RangeError(\`Extra \${t.byteLength-s} 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,s;for await(let E of A){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(E);try{s=this.doDecodeSync(),t=!0}catch(_){if(!(_ instanceof RangeError))throw _}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return s}let{headByte:i,pos:d,totalPos:C}=this;throw new RangeError(\`Insufficient data in parsing \${OA(i)} at \${C} (\${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 s=t,i=-1;for await(let d of A){if(t&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(d),s&&(i=this.readArraySize(),s=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(C){if(!(C instanceof RangeError))throw C}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: \${OA(A)}\`);this.complete();let s=this.stack;for(;s.length>0;){let i=s.top();if(i.type===mr)if(i.array[i.position]=t,i.position++,i.position===i.size)t=i.array,s.release(i);else continue A;else if(i.type===qA){if(t==="__proto__")throw new L("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,s.release(i);else{i.key=null,i.type=qA;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 L(\`Unrecognized array type byte: \${OA(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 ht;let s=this.pos+t,i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?i=this.keyDecoder.decode(this.bytes,s,A):i=Gt(this.bytes,s,A),this.pos+=t+A,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===qA:!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 ht;let s=this.pos+t,i=this.bytes.subarray(s,s+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 s=this.view.getInt8(this.pos+t),i=this.decodeBinary(A,t+1);return this.extensionCodec.decode(i,s,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=Et(this.view,this.pos);return this.pos+=8,A}readI64(){let A=NA(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(e,A){return new PA(A).decode(e)}var GA=class e{constructor(A,t,s,i,d){this.mediaIds=A;this.sequenceNumber=t;this.timeStamp=s;this.isEndOfSpurt=i;this.payload=d}static parse(A){let t;try{t=Fr(A)}catch{return B("not valid msgpack")}if(!Array.isArray(t))return B("container must be an array");if(t.length<6)return B("missing fields");if(t[0]!==1)return B("unknown type");if(!Array.isArray(t[1]))return B("media ids must be an array");if(!t[1].every(D=>typeof D=="number"))return B("media ids must be numbers");if(typeof t[2]!="number")return B("sequence number must be a number");if(typeof t[3]!="number")return B("timestamp must be a number");if(typeof t[4]!="number")return B("flags must be a number");let s=t[1],i=t[2]>>>0,d=t[3]>>>0,E=(t[4]&1)!==0,_=t[t.length-1];return _ instanceof Uint8Array?nt(new e(s,i,d,E,_)):B("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(Er(t,{forceFloat32:!0,ignoreUndefined:!0}))}};var wA=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,O.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=dt(this.wasm),this.outBuffer=U(this.wasm,"u8",1270),Yj(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(){Ct(this.wasm,this.information),tA(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){at(\`failed encoding packet: \${t}\`);return}if(this.timestamp=this.timestamp+1800>>0,t===1)continue;this.sequenceNumber=this.sequenceNumber+1>>0;let s=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,s,this.outBuffer.subarray(0,t));uA(globalThis,["sendPacket",{connectionId:i.id,packet:d.toBytes()}])}}}onMessage(A){let[t,s]=A;switch(t){case"captureSetVad":this?.setVad(s);break;case"captureSetMedias":this?.setMedias(s.connections);break;case"close":this.close();break;case"dump":s.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:Wj(this.information),speechProbability:Xj(this.information),rmsDBFS:zj(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}}}},TA=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",O.MaxNumberOfDecoders),this.information=ut(this.wasm,O.MaxNumberOfDecoders),wj(this.information,[1,1])}close(){ct(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,t){this.stats.numberPackets++;let s=GA.parse(t);if(s.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: \${s.reason}, connection: \${A}, dump: \${i}\`);return}for(let i of s.value.mediaIds){let d=this.medias.get(xA({connectionId:A,mediaId:i}));if(d===void 0){this.stats.numberPacketsMediaNotFound++;continue}d.lastPacket=t;let C=U(this.wasm,"u8",s.value.payload.length);C.set(s.value.payload),d.decoder.push(s.value.sequenceNumber,s.value.timeStamp,s.value.isEndOfSpurt,C.byteOffset,C.length)}}insertMedia(A,t,s,i=[1,1]){let d=xA({connectionId:t,mediaId:s}),C=new this.wasm.Decoder;this.medias.set(d,{index:A,decoder:C,lastPacket:void 0}),this.decoders[A]=C.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),Uj(this.information,A,i),Qj(this.information,A,0),Rj(this.information,A,0)}removeMedia(A,t,s){let i=xA({connectionId:t,mediaId:s}),d=this.medias.get(i);if(!(d===void 0||d.index!==A)&&(this.medias.delete(i),Sj(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,s]=A;switch(t){case"playbackReceivePacket":this.receivePacket(s.connectionId,s.packet);break;case"playbackUpdateMedias":for(let{index:i,connectionId:d,mediaId:C}of s.removed)this.removeMedia(i,d,C);for(let{index:i,connectionId:d,mediaId:C,volume:E}of s.added)this.insertMedia(i,d,C,E);break;case"close":this.close();break;case"dump":s.result.postMessage(this.dump());break}}dump(){let A=[];for(let[t,s]of this.medias){let i=kt(t);A.push({index:s.index,connectionId:i.connectionId,mediaId:i.mediaId,rmsDBFS:Tj(this.information,s.index),volume:Mj(this.information,s.index),voicedBlocks:Vj(this.information,s.index),silentBlocks:Kj(this.information,s.index),time:s.decoder.time,consecutive_silence:s.decoder.consecutive_silence,last_voiced_time_point:s.decoder.last_voiced_time_point,sequence_number:s.decoder.sequence_number,packetsSeen:s.decoder.packets_seen,packetsInvalid:s.decoder.packets_invalid,packetsTooLate:s.decoder.packets_too_late,packetsTooEarly:s.decoder.packets_too_early,packetsRepeated:s.decoder.packets_repeated,packetsProcessed:s.decoder.packets_processed,packetsLost:s.decoder.packets_lost,rewinds:s.decoder.rewinds,cacheLength:s.decoder.cache_length,lastPacket:At(s.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:Pj(this.information),decoders:A}}};var Lt=Fn(vt()),It=(0,Lt.default)(),_t,Ht;globalThis.addEventListener("message",vr);async function vr(e){let A=e.data,[t,s]=A;switch(t){case"captureInit":s.workletPort.onmessage=vr,_t=new Ir(s.sampleRate,await It);break;case"playbackInit":s.workletPort.onmessage=vr,Ht=new _r(await It);break;case"close":globalThis.close();break}_t?.onMessage(A),Ht?.onMessage(A)}var Ir=class extends wA{constructor(t,s){super(t,s);this.id=-1;this.samples=qr(this.wasm,t,2+O.VadPreload+O.AdditionalCaptureBlocks,!1),uA(globalThis,["captureReady",{sampleBuffer:this.samples,informationBuffer:this.information}])}close(){super.close(),Gr(this.wasm,this.samples)}onMessage(t){super.onMessage(t);let[s,i]=t;s==="captureTick"&&this.tick(i.id)}tick(t){for(;this.id<t;this.id+=1)this.encode(ur(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()}}},_r=class extends TA{constructor(A){super(A);let t=2+O.AdditionalPlaybackBlocks;this.sampleBuffer=qr(A,48e3,t,!0),this.sampleBuffer.samples.fill(0),this.prefill=t-2;for(let s=0;s<this.prefill;s++)cr(this.sampleBuffer,s,{id:s});this.id=this.prefill,uA(globalThis,["playbackReady",{sampleBuffer:this.sampleBuffer,informationBuffer:this.information}])}close(){super.close(),Gr(this.wasm,this.sampleBuffer)}onMessage(A){super.onMessage(A);let[t,s]=A;t==="playbackTick"&&this.tick(s.id)}tick(A){for(this.stats.numberTicks++;this.id<A+this.prefill;this.id++){let t=this.id%this.sampleBuffer.length,{hasAudio:s}=this.decode(ur(this.sampleBuffer,t));s&&(this.stats.numberTicksWithAudio++,cr(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()}}};})();
|
|
3380
|
-
`});var e0,R0=p(()=>{e0='"use strict";(()=>{var E=Object.defineProperty;var F=(e,t)=>{for(var r in t)E(e,r,{get:t[r],enumerable:!0})};var l={};F(l,{AdditionalCaptureBlocks:()=>C,AdditionalPlaybackBlocks:()=>D,ClockJumpCheckInterval:()=>j,ClockJumpThreshold:()=>$,ConnectInterval:()=>X,ConnectTimeout:()=>Q,DefaultRefreshRate:()=>V,DefaultVideoCodec:()=>te,HealthCheckTimeout:()=>W,MainConnectionPingInterval:()=>H,MaxNumberOfDecoders:()=>_,MaxReconnectDuration:()=>ee,MinDBFs:()=>k,MinTokenLifetime:()=>Y,MinTokenRefreshInterval:()=>K,PlaybackPreload:()=>L,RenderQuantumSize:()=>N,VadPreload:()=>O,WebRtcAnswerTimeout:()=>Z,WebRtcIceTimeout:()=>J,WebRtcMaxNegotiationAttempts:()=>q,WebRtcStatsSnapshotInterval:()=>G,WebRtcTimeout:()=>z});var D=3,C=3,L=3,V=250,O=3,_=512,N=128,k=-758.596,W=1e4,j=1e3,$=1e4,H=3e3,G=1e3,J=3e3,z=1e4,Z=1e4,q=3,Q=5e3,Y=6e4,K=5e3,X=[0,100,200,200,500],ee=12e4,te="H264";function p(e,t,r){return e.postMessage(t,r)}function re(e){return e.sampleRate*.02*(e.stereo?2:1)}function f(e,t){let r=re(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 ne;(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||={})})(ne||={});var{Deno:U}=globalThis,se=typeof U?.noColor=="boolean"?U.noColor:!1,oe=!se;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 oe?`${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 ae(e){return b(e,h([2],22))}var Pe=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"),ie=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}"},ce={4:ae,3:m,2:m,1:T,0:T};function le({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()-ie.valueOf();[i,c]=t(i,1e3);let[M,R]=t(i,60);return`${M.toString().padStart(4,"0")}:${R.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],a=e.logger.name!==void 0?`@${e.logger.name}`:"";return`${m(r())}${a} ${s} ${ce[e.level](String(e.message))}${n()}`}function ue(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 fe(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var A=class{static sparse=le;static json=B;static pretty=w;static structured=ue;static default=fe()?w:B;constructor(){}};var de=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 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=globalThis[Symbol.for("odin-global-logger")]??=new o(3,void 0,[new de]),pe=o.prototype.log.bind(u,1),me=o.prototype.log.bind(u,2),he=o.prototype.log.bind(u,3),be=o.prototype.log.bind(u,4),Ae=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 T0={};kx(T0,{createCaptureWorker:()=>eF,createPlaybackWorker:()=>jF});function eF(D,x,A,F,r=C.DefaultRefreshRate){return tF.enqueue(async()=>{let[t,e]=await Bx(t0,e0,D,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return v0.create(D,x,A,t,e,F)})}async function jF(D,x=C.DefaultRefreshRate){if(D.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[A,F]=await Bx(t0,e0,D,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return j0.create(D,A,F)}var S0,tF,j0,v0,M0=p(()=>{"use strict";S0=require("@4players/odin-common");o();qx();J0();R0();tF=new S0.Strand;j0=class D extends ex{constructor(A,F,r,t){super(A,F,r);this.information=t}static async create(A,F,r){let{port1:t,port2:e}=new MessageChannel;a(F,["playbackInit",{workletPort:t}],[t]);let{informationBuffer:j,sampleBuffer:B}=await Fx(F,"playbackReady");return r0(j,[1,1]),a(r.port,["init",{sampleBuffer:B,workerPort:e}],[e]),new D(A,r,F,j)}getActivity(A){let F=this.medias.get(h(A));if(F===void 0)return;let r=k0(this.information,F.index);return r===0?I:{isSilent:!1,rmsDBFS:r}}getJitterStats(A){}setGlobalVolume(A){r0(this.information,A)}setVolume(A,F){let r=this.medias.get(h(A));r!==void 0&&d0(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}},v0=class D extends jx{constructor(A,F,r,t,e,j){super(A,F,r,t,j);this.information=e}static async create(A,F,r,t,e,j){let{port1:B,port2:E}=new MessageChannel;a(t,["captureInit",{sampleRate:A.sampleRate,workletPort:B}],[B]);let{sampleBuffer:l,informationBuffer:c}=await Fx(t,"captureReady");return a(e.port,["init",{workerPort:E,sampleBuffer:l}],[E]),new D(e,t,F,r,c,j)}get activity(){return{isSilent:!p0(this.information),rmsDBFS:m0(this.information)}}get speechProbability(){return h0(this.information)}setVolume(A){q0(this.information,A)}}});var B0,U0=p(()=>{B0=`"use strict";(()=>{var un=Object.create;var XA=Object.defineProperty;var cn=Object.getOwnPropertyDescriptor;var dn=Object.getOwnPropertyNames;var Cn=Object.getPrototypeOf,qn=Object.prototype.hasOwnProperty;var fn=(n,A)=>()=>{try{return A||n((A={exports:{}}).exports,A),A.exports}catch(j){throw A=0,j}},Gn=(n,A)=>{for(var j in A)XA(n,j,{get:A[j],enumerable:!0})},pn=(n,A,j,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let l of dn(A))!qn.call(n,l)&&l!==j&&XA(n,l,{get:()=>A[l],enumerable:!(e=cn(A,l))||e.enumerable});return n};var En=(n,A,j)=>(j=n!=null?un(Cn(n)):{},pn(A||!n||!n.__esModule?XA(j,"default",{value:n,enumerable:!0}):j,n));var _j=fn((Ij,PA)=>{"use strict";var er=(()=>{var n=globalThis.document?.currentScript?.src;return async function(A={}){var j=A,e=!!globalThis.window,l=!!globalThis.WorkerGlobalScope,c=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",C=[],p="./this.program";l&&(n=self.location.href);var I="",B,wA;if(e||l){try{I=new URL(".",n).href}catch{}l&&(wA=t=>{var r=new XMLHttpRequest;return r.open("GET",t,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),B=async t=>{var r=await fetch(t,{credentials:"same-origin"});if(r.ok)return r.arrayBuffer();throw new Error(r.status+" : "+r.url)}}var b=console.log.bind(console),aA=console.error.bind(console),Dj,or=!1;class Bj{}class _e extends Bj{}function xj(t){for(var r=0,s=t.length,i=new Uint8Array(s),o;r<s;++r)o=t.charCodeAt(r),i[r]=~o>>8&o;return i}var Nj=!1;function bj(){var t=Sr.buffer;U=new Int8Array(t),cA=new Int16Array(t),j.HEAPU8=g=new Uint8Array(t),rA=new Uint16Array(t),j.HEAP32=dA=new Int32Array(t),j.HEAPU32=$=new Uint32Array(t),j.HEAPF32=Br=new Float32Array(t),xr=new Float64Array(t),dr=new BigInt64Array(t),Cr=new BigUint64Array(t)}function Oj(){var t=j.preRun;t&&(typeof t=="function"&&(t=[t]),cr.push(...t)),kr(cr)}function Jj(){Nj=!0,tA.v()}function Pj(){var t=j.postRun;t&&(typeof t=="function"&&(t=[t]),ur.push(...t)),kr(ur)}function kA(t){j.onAbort?.(t),t=\`Aborted(\${t})\`,aA(t),or=!0,t+=". Build with -sASSERTIONS for more info.";var r=new WebAssembly.RuntimeError(t);throw r}var ar;function wj(){return xj(\`\\0asm\\0\\0\\0\\x8E9\\\`\\x7F\\x7F\\\`\\x7F\\0\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\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}}\\\`\\0\\x7F\\\`\\x7F\\x7F}}\\0\\\`
|
|
3379
|
+
\`,new Function(I,p)}function jr(r,j,n,l,o,a){var k=j.length;k<2&&G("argTypes array size mismatch! Must at least get return value and receiver (this) types!");var u=j[1]!==null&&n!==null,c=nj(j),q=sj(j),f=q&&!a&&!c;q&&!f&&(c=!0);var p=!j[0].isVoid,v=j[0],I=j[1],F=[r,G,l,o,ej,v.fromWireType.bind(v),I?.toWireType.bind(I)];f&&F.push(wr,WA);for(var h=2;h<k;++h){var b=j[h];F.push(b.toWireType.bind(b))}if(!c)for(var h=u?1:2;h<j.length;++h)j[h].destructorFunction!==null&&F.push(j[h].destructorFunction);var Q=me(j,u,p,a)(...F);return Zr(r,Q)}var he=(r,j,n,l,o,a)=>{var k=rr(j,n);o=P(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]=()=>{AA(\`Cannot construct \${u.name} due to unbound types\`,k)},M([],k,q=>(q.splice(1,0,null),u.registeredClass.constructor_body[j-1]=jr(c,q,null,o,a),[])),[]})},ij=r=>{r=r.trim();let j=r.indexOf("(");return j===-1?r:r.slice(0,j)},$e=(r,j,n,l,o,a,k,u,c,q)=>{var f=rr(n,l);j=H(j),j=ij(j),a=P(o,a,c),M([],[r],p=>{p=p[0];var v=\`\${p.name}.\${j}\`;j.startsWith("@@")&&(j=Symbol[j.substring(2)]),u&&p.registeredClass.pureVirtualFunctions.push(j);function I(){AA(\`Cannot call \${v} due to unbound types\`,f)}var F=p.registeredClass.instancePrototype,h=F[j];return h===void 0||h.overloadTable===void 0&&h.className!==p.name&&h.argCount===n-2?(I.argCount=n-2,I.className=p.name,F[j]=I):(Aj(F,j,v),F[j].overloadTable[n-2]=I),M([],f,b=>{var y=jr(v,b,p,a,k,c);return F[j].overloadTable===void 0?(y.argCount=n-2,F[j]=y):F[j].overloadTable[n-2]=y,[]}),[]})},lj=(r,j,n)=>(r instanceof Object||G(\`\${n} with invalid "this": \${r}\`),r instanceof j.registeredClass.constructor||G(\`\${n} incompatible with "this" of type \${r.constructor.name}\`),r.$$.ptr||G(\`cannot call emscripten binding method \${n} on deleted object\`),IA(r.$$.ptr,r.$$.ptrType.registeredClass,j.registeredClass)),Fe=(r,j,n,l,o,a,k,u,c,q)=>{j=H(j),o=P(l,o),M([],[r],f=>{f=f[0];var p=\`\${f.name}.\${j}\`,v={get(){AA(\`Cannot access \${p} due to unbound types\`,[n,k])},enumerable:!0,configurable:!0};return c?v.set=()=>AA(\`Cannot access \${p} due to unbound types\`,[n,k]):v.set=I=>G(p+" is a read-only property"),Object.defineProperty(f.registeredClass.instancePrototype,j,v),M([],c?[n,k]:[n],I=>{var F=I[0],h={get(){var y=lj(this,f,p+" getter");return F.fromWireType(o(a,y))},enumerable:!0};if(c){c=P(u,c);var b=I[1];h.set=function(y){var Q=lj(this,f,p+" setter"),g=[];c(q,Q,b.toWireType(g,y)),ej(g)}}return Object.defineProperty(f.registeredClass.instancePrototype,j,h),[]}),[]})},oj=[],V=[0,1,,1,null,1,!0,1,!1,1],ve=r=>{if(r>9&&--V[r+1]===0){var j=V[r];V[r]=void 0,oj.push(r)}},tr={toValue:r=>(r||G(\`Cannot use deleted val. handle = \${r}\`),V[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=oj.pop()||V.length;return V[j]=r,V[j+1]=1,j}}}},Ie={name:"emscripten::val",fromWireType:r=>{var j=tr.toValue(r);return ve(r),j},toWireType:(r,j)=>tr.toHandle(j),readValueFromPointer:_A,destructorFunction:null},_e=r=>N(r,Ie),aj,He=(r,j)=>{switch(j){case 4:return function(n){return this.fromWireType(aj[n>>2])};case 8:return function(n){return this.fromWireType(mA[n>>3])};default:throw new TypeError(\`invalid float width (\${j}): \${r}\`)}},Le=(r,j,n)=>{j=H(j),N(r,{name:j,fromWireType:l=>l,toWireType:(l,o)=>o,readValueFromPointer:He(j,n),destructorFunction:null})},ye=(r,j,n,l,o,a,k,u)=>{var c=rr(j,n);r=H(r),r=ij(r),o=P(l,o,k),rj(r,function(){AA(\`Cannot call \${r} due to unbound types\`,c)},j-1),M([],c,q=>{var f=[q[0],null].concat(q.slice(1));return tj(r,jr(r,f,null,o,a,k),j-1),[]})},ge=(r,j,n,l,o)=>{j=H(j);let a=l===0,k=c=>c;if(a){var u=32-8*n;k=c=>c<<u>>>u,o=k(o)}N(r,{name:j,fromWireType:k,toWireType:(c,q)=>q,readValueFromPointer:Qr(j,n,l!==0),destructorFunction:null})},De=(r,j,n)=>{var l=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=l[j];function a(k){var u=$[k>>2],c=$[k+4>>2];return new o(R.buffer,c,u)}n=H(n),N(r,{name:n,fromWireType:a,readValueFromPointer:a},{ignoreDuplicateRegistrations:!0})},xe=(r,j,n,l)=>{if(!(l>0))return 0;for(var o=n,a=n+l-1,k=0;k<r.length;++k){var u=r.codePointAt(k);if(u<=127){if(n>=a)break;j[n++]=u}else if(u<=2047){if(n+1>=a)break;j[n++]=192|u>>6,j[n++]=128|u&63}else if(u<=65535){if(n+2>=a)break;j[n++]=224|u>>12,j[n++]=128|u>>6&63,j[n++]=128|u&63}else{if(n+3>=a)break;j[n++]=240|u>>18,j[n++]=128|u>>12&63,j[n++]=128|u>>6&63,j[n++]=128|u&63,k++}}return j[n]=0,n-o},Be=(r,j,n)=>xe(r,x,j,n),Ne=r=>{for(var j=0,n=0;n<r.length;++n){var l=r.charCodeAt(n);l<=127?j++:l<=2047?j+=2:l>=55296&&l<=57343?(j+=4,++n):j+=3}return j},kj=globalThis.TextDecoder&&new TextDecoder,uj=(r,j,n,l)=>{var o=j+n;if(l)return o;for(;r[j]&&!(j>=o);)++j;return j},cj=(r,j=0,n,l)=>{var o=uj(r,j,n,l);if(o-j>16&&r.buffer&&kj)return kj.decode(r.buffer instanceof ArrayBuffer?r.subarray(j,o):r.slice(j,o));for(var a="";j<o;){var k=r[j++];if(!(k&128)){a+=String.fromCharCode(k);continue}var u=r[j++]&63;if((k&224)==192){a+=String.fromCharCode((k&31)<<6|u);continue}var c=r[j++]&63;if((k&240)==224?k=(k&15)<<12|u<<6|c:k=(k&7)<<18|u<<12|c<<6|r[j++]&63,k<65536)a+=String.fromCharCode(k);else{var q=k-65536;a+=String.fromCharCode(55296|q>>10,56320|q&1023)}}return a},be=(r,j,n)=>r?cj(x,r,j,n):"",Oe=(r,j)=>{j=H(j);var n=!0;N(r,{name:j,fromWireType(l){var o=$[l>>2],a=l+4,k;if(n)k=be(a,o,!0);else{k="";for(var u=0;u<o;++u)k+=String.fromCharCode(x[a+u])}return w(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"),n&&k?a=Ne(o):a=o.length;var u=sr(4+a+1),c=u+4;if($[u>>2]=a,k)if(n)Be(o,c,a+1);else for(var q=0;q<a;++q){var f=o.charCodeAt(q);f>255&&(w(u),G("String has UTF-16 code units that do not fit in 8 bits")),x[c+q]=f}else x.set(o,c);return l!==null&&l.push(w,u),u},readValueFromPointer:_A,destructorFunction(l){w(l)}})},dj=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Je=(r,j,n)=>{var l=r>>1,o=uj(oA,l,j/2,n);if(o-l>16&&dj)return dj.decode(oA.slice(l,o));for(var a="",k=l;k<o;++k){var u=oA[k];a+=String.fromCharCode(u)}return a},Pe=(r,j,n=2147483647)=>{if(n<2)return 0;n-=2;for(var l=j,o=n<r.length*2?n/2:r.length,a=0;a<o;++a){var k=r.charCodeAt(a);$A[j>>1]=k,j+=2}return $A[j>>1]=0,j-l},we=r=>r.length*2,Te=(r,j,n)=>{for(var l="",o=r>>2,a=0;!(a>=j/4);a++){var k=$[o+a];if(!k&&!n)break;l+=String.fromCodePoint(k)}return l},Se=(r,j,n=2147483647)=>{if(n<4)return 0;for(var l=j,o=l+n-4,a=0;a<r.length;++a){var k=r.codePointAt(a);if(k>65535&&a++,S[j>>2]=k,j+=4,j+4>o)break}return S[j>>2]=0,j-l},Me=r=>{for(var j=0,n=0;n<r.length;++n){var l=r.codePointAt(n);l>65535&&n++,j+=4}return j},Ue=(r,j,n)=>{n=H(n);var l,o,a;j===2?(l=Je,o=Pe,a=we):(l=Te,o=Se,a=Me),N(r,{name:n,fromWireType:k=>{var u=$[k>>2],c=l(k+4,u*j,!0);return w(k),c},toWireType:(k,u)=>{typeof u!="string"&&G(\`Cannot pass non-string to C++ string type \${n}\`);var c=a(u),q=sr(4+c+j);return $[q>>2]=c/j,o(u,q+4,c+j),k!==null&&k.push(w,q),q},readValueFromPointer:_A,destructorFunction(k){w(k)}})},Ke=(r,j)=>{j=H(j),N(r,{isVoid:!0,name:j,fromWireType:()=>{},toWireType:(n,l)=>{}})},Re=r=>{var j=!s;try{Atomics.wait(S,0,0,0),j=!0}catch{}ir(r,!i,1,j,65536,!1),m.threadInitTLS()},Cj=r=>{if(r instanceof Nr||r=="unwind")return z;D(1,r)},Ve=()=>{if(!QA())try{if(C){kA()&&lr(z);return}XA(z)}catch(r){Cj(r)}},fj=r=>{if(!pA)try{return r()}catch(j){Cj(j)}finally{Ve()}},er=r=>{if(!Mr){var j=Atomics.waitAsync(S,r>>2,r);j.value.then(gA);var n=r+112;Atomics.store(S,n>>2,1)}},gA=()=>{var r=kA();r&&fj(()=>{er(r),_j()})},Qe=(r,j)=>{if(r==j)setTimeout(gA);else if(C)postMessage({targetThread:r,cmd:4});else{var n=m.pthreads[r];if(!n)return;n.postMessage({cmd:4})}},nr=[],We=(r,j,n,l,o,a,k)=>{nr.length=0;for(var u=o>>3,c=o+l>>3;u<c;){var q;K[u++]?q=K[u++]:q=mA[u++],nr.push(q)}var f=an[r];m.currentProxiedOperationCallerThread=n;var p=f(...nr);if(m.currentProxiedOperationCallerThread=0,a){Promise.resolve(p).then(v=>Fj(a,k,v));return}return p},Xe=r=>{C?postMessage({cmd:6,thread:r}):Or(r)},ze=r=>{},Ze=()=>performance.timeOrigin+performance.now(),Ye=9007199254740992,An=-9007199254740992,rn=r=>r<An||r>Ye?NaN:Number(r),jn=()=>{},tn=()=>{VA+=1},en=()=>{throw tn(),"unwind"},nn=r=>{EA("OOM")},sn=r=>{var j=x.length;r>>>=0,nn(r)};function qj(r){return C?sA(2,0,1,r):52}function Gj(r,j,n,l){return C?sA(3,0,1,r,j,n,l):(j=rn(j),70)}var ln=[null,[],[]],on=(r,j)=>{var n=ln[r];!j||j===10?((r===1?KA:J)(cj(n)),n.length=0):n.push(j)};function pj(r,j,n,l){if(C)return sA(4,0,1,r,j,n,l);for(var o=0,a=0;a<n;a++){var k=$[j>>2],u=$[j+4>>2];j+=8;for(var c=0;c<u;c++)on(r,x[k+c]);o+=u}return $[l>>2]=o,0}m.init(),ee(),qe();{Bt(),t.noExitRuntime&&(zA=t.noExitRuntime),t.print&&(KA=t.print),t.printErr&&(J=t.printErr),t.arguments&&(E=t.arguments),t.thisProgram&&(_=t.thisProgram);var rA=t.preInit;if(rA)for(typeof rA=="function"&&(t.preInit=rA=[rA]);rA.length>0;)rA.shift()()}var an=[Tr,Sr,qj,Gj,pj],Ej,mj,kA,sr,w,kn,ir,hj,$j,Fj,vj,Ij,lr,_j,Hj,Lj,yj,gj,un,Dj;function cn(r){Ej=r.G,mj=r.H,kA=r.J,sr=t._malloc=r.K,w=t._free=r.L,kn=r.M,ir=r.N,hj=r.O,$j=r.P,Fj=r.Q,vj=r.R,Ij=r.S,lr=r.T,_j=r.U,Hj=r.V,Lj=r.W,yj=r.X,gj=r.Y,un=Dj=r.I}var xj;function dn(){xj={l:Xt,C:zt,h:Yt,o:Ae,n:Ee,m:he,e:$e,b:Fe,D:_e,g:Le,q:ye,d:ge,c:De,E:Oe,f:Ue,p:Ke,z:Re,u:Qe,j:We,s:Xe,y:er,B:ze,x:jn,A:en,k:Ze,t:sn,r:XA,w:qj,v:Gj,i:pj,a:iA}}async function Bj(){if(C){gr();return}Nt();var r=t.setStatus;r&&(r("Running..."),await new Promise(j=>setTimeout(j,1)),setTimeout(r,1,"")),!pA&&(gr(),t.onRuntimeInitialized?.(),bt())}var jA;return C||(jA=await Br(),await Bj()),t}})();typeof Ft=="object"&&typeof MA=="object"?(MA.exports=SA,MA.exports.default=SA):typeof define=="function"&&define.amd&&define([],()=>SA);var Ds=globalThis.name=="em-pthread";Ds&&SA()});var O={};hn(O,{AdditionalCaptureBlocks:()=>In,AdditionalPlaybackBlocks:()=>vn,ClockJumpCheckInterval:()=>xn,ClockJumpThreshold:()=>Bn,ConnectInterval:()=>Kn,ConnectTimeout:()=>Sn,DefaultRefreshRate:()=>Hn,DefaultVideoCodec:()=>Vn,HealthCheckTimeout:()=>Dn,MainConnectionPingInterval:()=>Nn,MaxNumberOfDecoders:()=>yn,MaxReconnectDuration:()=>Rn,MinDBFs:()=>Jj,MinTokenLifetime:()=>Mn,MinTokenRefreshInterval:()=>Un,PlaybackPreload:()=>_n,RenderQuantumSize:()=>gn,VadPreload:()=>Ln,WebRtcAnswerTimeout:()=>Pn,WebRtcIceTimeout:()=>On,WebRtcMaxNegotiationAttempts:()=>wn,WebRtcRecoveryDelays:()=>Tn,WebRtcStatsSnapshotInterval:()=>bn,WebRtcTimeout:()=>Jn});var vn=3,In=3,_n=3,Hn=250,Ln=3,yn=512,gn=128,Jj=-758.596,Dn=1e4,xn=1e3,Bn=1e4,Nn=3e3,bn=1e3,On=3e3,Jn=1e4,Pn=1e4,wn=3,Tn=[0,2e3,5e3],Sn=5e3,Mn=6e4,Un=5e3,Kn=[0,100,200,200,500],Rn=12e4,Vn="H264";function uA(e,A,t){return e.postMessage(A,t)}function kr(e){return e.sampleRate*.02*(e.stereo?2:1)}function ur(e,A){let t=kr(e),s=t*A,i=s+t;return e.samples.subarray(s,i)}function cr(e,A,t){e.headers[A]=t.id}function Pj(e){return[e.values[0],e.values[1]]}function wj(e,A){e.values[0]=A[0],e.values[1]=A[1]}function Tj(e,A){return e.values[2+A*5]}function Sj(e,A,t){e.values[2+A*5]=t}function Mj(e,A){let t=2+A*5+1;return[e.values[t+0],e.values[t+1]]}function Uj(e,A,t){let s=2+A*5+1;e.values[s+0]=t[0],e.values[s+1]=t[1]}function Kj(e,A){return e.values[2+A*5+3]}function Rj(e,A,t){e.values[2+A*5+3]=t}function Vj(e,A){return e.values[2+A*5+4]}function Qj(e,A,t){e.values[2+A*5+4]=t}function Wj(e){return e.values[0]!==0}function Xj(e){return e.values[1]}function zj(e){return e.values[2]}function Zj(e){return e.values[3]}function Yj(e,A){return e.values[3]=A}function At(e){return e?Array.from(e).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var Qn;(e=>{let A;(t=>(t[t.InvalidPassword=-1]="InvalidPassword",t[t.Unknown=0]="Unknown",t[t.Unencrypted=1]="Unencrypted",t[t.Encrypted=2]="Encrypted"))(A=e.PeerCipherStatus||={})})(Qn||={});function nt(e){return{type:"Success",value:e}}function B(e){return{type:"Failure",reason:e}}var{Deno:rt}=globalThis,Wn=typeof rt?.noColor=="boolean"?rt.noColor:!1,Xn=!Wn;function Cr(e,A){return{open:\`\\x1B[\${e.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function fr(e,A){return Xn?\`\${A.open}\${e.replace(A.regexp,A.open)}\${A.close}\`:e}function dr(e){return fr(e,Cr([0],0))}function jt(e){return fr(e,Cr([1],22))}function zn(e){return fr(e,Cr([2],22))}var Vs=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"),Zn=new Date,DA=(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))(DA||{}),st={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},Yn={4:zn,3:dr,2:dr,1:jt,0:jt};function As({message:e}){return String(e)}function tt(e){return JSON.stringify({timestamp:e.date.toISOString(),level:DA[e.level],message:e.message,extra:e.extra})}function et(e){function A(C,E){return[Math.floor(C/E),C%E]}function t(){let C,E=e.date.valueOf()-Zn.valueOf();[E,C]=A(E,1e3);let[_,D]=A(E,60);return\`\${_.toString().padStart(4,"0")}:\${D.toString().padStart(2,"0")}.\${C.toString().padStart(3,"0")}\`}function s(){return e.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(e.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(e.extra)}let i=st[e.level],d=e.logger.name!==void 0?\`@\${e.logger.name}\`:"";return\`\${dr(t())}\${d} \${i} \${Yn[e.level](String(e.message))}\${s()}\`}function rs(e){let A=\`[\${e.date.toISOString()}]\`,t=\`[\${DA[e.level]}]\`,s=e.logger.name!==void 0?\`[\${e.logger.name}] \`:"",i=st[e.level];return\`\${A} \${i} \${t.padEnd(7," ")} \${s}\${e.message}\`}function js(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var it=class{static sparse=As;static json=tt;static pretty=et;static structured=rs;static default=js()?et:tt;constructor(){}};var ts=class{formatter;consoleObject;filter;constructor(e=it.default,A=4,t=console){this.filter=A,this.formatter=e,this.consoleObject=t}handle(e){let A=this.formatter(e);switch(e.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 W=class{#A;sinks;filter;parent;get name(){return this.#A}constructor(e,A=void 0,t=[],s=void 0){this.#A=A,this.sinks=t,this.filter=e,this.parent=s}log(e,A,t=void 0){let s={date:new Date,level:e,logger:this,message:A,extra:t};this.filter<e||this.insert(s)}insert(e){if(!(this.filter<e.level)){for(let A of this.sinks)A.filter>=e.level&&A.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)},cA=globalThis[Symbol.for("odin-global-logger")]??=new W(3,void 0,[new ts]),es=W.prototype.log.bind(cA,1),ns=W.prototype.log.bind(cA,2),lt=W.prototype.log.bind(cA,3),ss=W.prototype.log.bind(cA,4),Qs=W.prototype.log.bind(cA);var ot;function at(e,...A){let t=is(A);ot?ot?.info(e,t):lt(e,t)}function is(...e){if(e.length===1&&typeof e[0]=="object"&&e[0]!==null)return{...e[0]};if(e.length>0)return{args:e}}function xA(e){return e.connectionId*4294967296+e.mediaId}function kt(e){return{mediaId:e%4294967296,connectionId:Math.floor(e/4294967296)}}function U(e,A,t){let s;switch(A){case"f32":s=e.HEAPF32;break;case"u32":s=e.HEAPU32;break;case"i32":s=e.HEAP32;break;case"u8":s=e.HEAPU8;break;default:throw new Error(\`allocating \${A} is not supported\`)}let i=e._malloc(t*s.BYTES_PER_ELEMENT);if(i===0||i%s.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${t} \${A} array\`);let d=i/s.BYTES_PER_ELEMENT;return s.subarray(d,d+t)}function tA(e,A){e._free(A.byteOffset)}function qr(e,A,t,s){return{headers:U(e,"i32",t),samples:U(e,"f32",t*kr({sampleRate:A,stereo:s})),length:t,sampleRate:A,stereo:s}}function Gr(e,A){tA(e,A.headers),tA(e,A.samples)}function ut(e,A){return{values:U(e,"f32",2+A*5),length:A}}function ct(e,A){tA(e,A.values)}function dt(e){return{values:U(e,"f32",4)}}function Ct(e,A){tA(e,A.values)}function ft(e){let A=e.length,t=0,s=0;for(;s<A;){let i=e.charCodeAt(s++);if((i&4294967168)===0){t++;continue}else if((i&4294965248)===0)t+=2;else{if(i>=55296&&i<=56319&&s<A){let d=e.charCodeAt(s);(d&64512)===56320&&(++s,i=((i&1023)<<10)+(d&1023)+65536)}(i&4294901760)===0?t+=3:t+=4}}return t}function ls(e,A,t){let s=e.length,i=t,d=0;for(;d<s;){let C=e.charCodeAt(d++);if((C&4294967168)===0){A[i++]=C;continue}else if((C&4294965248)===0)A[i++]=C>>6&31|192;else{if(C>=55296&&C<=56319&&d<s){let E=e.charCodeAt(d);(E&64512)===56320&&(++d,C=((C&1023)<<10)+(E&1023)+65536)}(C&4294901760)===0?(A[i++]=C>>12&15|224,A[i++]=C>>6&63|128):(A[i++]=C>>18&7|240,A[i++]=C>>12&63|128,A[i++]=C>>6&63|128)}A[i++]=C&63|128}}var os=new TextEncoder,as=50;function ks(e,A,t){os.encodeInto(e,A.subarray(t))}function qt(e,A,t){e.length>as?ks(e,A,t):ls(e,A,t)}var us=4096;function pr(e,A,t){let s=A,i=s+t,d=[],C="";for(;s<i;){let E=e[s++];if((E&128)===0)d.push(E);else if((E&224)===192){let _=e[s++]&63;d.push((E&31)<<6|_)}else if((E&240)===224){let _=e[s++]&63,D=e[s++]&63;d.push((E&31)<<12|_<<6|D)}else if((E&248)===240){let _=e[s++]&63,D=e[s++]&63,UA=e[s++]&63,T=(E&7)<<18|_<<12|D<<6|UA;T>65535&&(T-=65536,d.push(T>>>10&1023|55296),T=56320|T&1023),d.push(T)}else d.push(E);d.length>=us&&(C+=String.fromCharCode(...d),d.length=0)}return d.length>0&&(C+=String.fromCharCode(...d)),C}var cs=new TextDecoder,ds=200;function Cs(e,A,t){let s=e.subarray(A,A+t);return cs.decode(s)}function Gt(e,A,t){return t>ds?Cs(e,A,t):pr(e,A,t)}var X=class{type;data;constructor(A,t){this.type=A,this.data=t}};var L=class e extends Error{constructor(A){super(A);let t=Object.create(e.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}};function pt(e,A,t){let s=t/4294967296,i=t;e.setUint32(A,s),e.setUint32(A+4,i)}function BA(e,A,t){let s=Math.floor(t/4294967296),i=t;e.setUint32(A,s),e.setUint32(A+4,i)}function NA(e,A){let t=e.getInt32(A),s=e.getUint32(A+4);return t*4294967296+s}function Et(e,A){let t=e.getUint32(A),s=e.getUint32(A+4);return t*4294967296+s}var fs=-1,qs=4294967296-1,Gs=17179869184-1;function ps({sec:e,nsec:A}){if(e>=0&&A>=0&&e<=Gs)if(A===0&&e<=qs){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t}else{let t=e/4294967296,s=e&4294967295,i=new Uint8Array(8),d=new DataView(i.buffer);return d.setUint32(0,A<<2|t&3),d.setUint32(4,s),i}else{let t=new Uint8Array(12),s=new DataView(t.buffer);return s.setUint32(0,A),BA(s,4,e),t}}function Es(e){let A=e.getTime(),t=Math.floor(A/1e3),s=(A-t*1e3)*1e6,i=Math.floor(s/1e9);return{sec:t+i,nsec:s-i*1e9}}function ms(e){if(e instanceof Date){let A=Es(e);return ps(A)}else return null}function hs(e){let A=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:A.getUint32(0),nsec:0};case 8:{let t=A.getUint32(0),s=A.getUint32(4),i=(t&3)*4294967296+s,d=t>>>2;return{sec:i,nsec:d}}case 12:{let t=NA(A,4),s=A.getUint32(0);return{sec:t,nsec:s}}default:throw new L(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${e.length}\`)}}function $s(e){let A=hs(e);return new Date(A.sec*1e3+A.nsec/1e6)}var mt={type:fs,encode:ms,decode:$s};var eA=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(mt)}register({type:A,encode:t,decode:s}){if(A>=0)this.encoders[A]=t,this.decoders[A]=s;else{let i=-1-A;this.builtInEncoders[i]=t,this.builtInDecoders[i]=s}}tryToEncode(A,t){for(let s=0;s<this.builtInEncoders.length;s++){let i=this.builtInEncoders[s];if(i!=null){let d=i(A,t);if(d!=null){let C=-1-s;return new X(C,d)}}}for(let s=0;s<this.encoders.length;s++){let i=this.encoders[s];if(i!=null){let d=i(A,t);if(d!=null){let C=s;return new X(C,d)}}}return A instanceof X?A:null}decode(A,t,s){let i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(A,t,s):new X(t,A)}};function Fs(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function dA(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Fs(e)?new Uint8Array(e):Uint8Array.from(e)}var vs=100,Is=2048,bA=class e{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(A){this.extensionCodec=A?.extensionCodec??eA.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??vs,this.initialBufferSize=A?.initialBufferSize??Is,this.sortKeys=A?.sortKeys??!1,this.forceFloat32=A?.forceFloat32??!1,this.ignoreUndefined=A?.ignoreUndefined??!1,this.forceIntegerToFloat=A?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new e({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),s=new Uint8Array(t),i=new DataView(t);s.set(this.bytes),this.view=i,this.bytes=s}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 s=ft(A);this.ensureBufferSizeToWrite(5+s),this.writeStringHeader(s),qt(A,this.bytes,this.pos),this.pos+=s}encodeObject(A,t){let s=this.extensionCodec.tryToEncode(A,this.context);if(s!=null)this.encodeExtension(s);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 s=dA(A);this.writeU8a(s)}encodeArray(A,t){let s=A.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else if(s<4294967296)this.writeU8(221),this.writeU32(s);else throw new Error(\`Too large array: \${s}\`);for(let i of A)this.doEncode(i,t+1)}countWithoutUndefined(A,t){let s=0;for(let i of t)A[i]!==void 0&&s++;return s}encodeMap(A,t){let s=Object.keys(A);this.sortKeys&&s.sort();let i=this.ignoreUndefined?this.countWithoutUndefined(A,s):s.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 s){let C=A[d];this.ignoreUndefined&&C===void 0||(this.encodeString(d),this.doEncode(C,t+1))}}encodeExtension(A){if(typeof A.data=="function"){let s=A.data(this.pos+6),i=s.length;if(i>=4294967296)throw new Error(\`Too large extension object: \${i}\`);this.writeU8(201),this.writeU32(i),this.writeI8(A.type),this.writeU8a(s);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),pt(this.view,this.pos,A),this.pos+=8}writeI64(A){this.ensureBufferSizeToWrite(8),BA(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 Er(e,A){return new bA(A).encodeSharedRef(e)}function OA(e){return\`\${e<0?"-":""}0x\${Math.abs(e).toString(16).padStart(2,"0")}\`}var _s=16,Hs=16,JA=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(A=_s,t=Hs){this.maxKeyLength=A,this.maxLengthPerKey=t,this.caches=[];for(let s=0;s<this.maxKeyLength;s++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,t,s){let i=this.caches[s-1];A:for(let d of i){let C=d.bytes;for(let E=0;E<s;E++)if(C[E]!==A[t+E])continue A;return d.str}return null}store(A,t){let s=this.caches[A.length-1],i={bytes:A,str:t};s.length>=this.maxLengthPerKey?s[Math.random()*s.length|0]=i:s.push(i)}decode(A,t,s){let i=this.find(A,t,s);if(i!=null)return this.hit++,i;this.miss++;let d=pr(A,t,s),C=Uint8Array.prototype.slice.call(A,t,t+s);return this.store(C,d),d}};var mr="array",qA="map_key",$t="map_value",Ls=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new L("The type of key must be string or number but "+typeof e)},hr=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let t=this.getUninitializedStateFromPool();t.type=mr,t.position=0,t.size=A,t.array=new Array(A)}pushMapState(A){let t=this.getUninitializedStateFromPool();t.type=qA,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===mr){let s=A;s.size=0,s.array=void 0,s.position=0,s.type=void 0}if(A.type===qA||A.type===$t){let s=A;s.size=0,s.map=void 0,s.readCount=0,s.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},fA=-1,$r=new DataView(new ArrayBuffer(0)),ys=new Uint8Array($r.buffer);try{$r.getInt8(0)}catch(e){if(!(e 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 ht=new RangeError("Insufficient data"),gs=new JA,PA=class e{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=$r;bytes=ys;headByte=fA;stack=new hr;entered=!1;constructor(A){this.extensionCodec=A?.extensionCodec??eA.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.rawStrings=A?.rawStrings??!1,this.maxStrLength=A?.maxStrLength??4294967295,this.maxBinLength=A?.maxBinLength??4294967295,this.maxArrayLength=A?.maxArrayLength??4294967295,this.maxMapLength=A?.maxMapLength??4294967295,this.maxExtLength=A?.maxExtLength??4294967295,this.keyDecoder=A?.keyDecoder!==void 0?A.keyDecoder:gs,this.mapKeyConverter=A?.mapKeyConverter??Ls}clone(){return new e({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),s=dA(A),i=new Uint8Array(t.length+s.length);i.set(t),i.set(s,t.length),this.setBuffer(i)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:t,pos:s}=this;return new RangeError(\`Extra \${t.byteLength-s} 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,s;for await(let E of A){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(E);try{s=this.doDecodeSync(),t=!0}catch(_){if(!(_ instanceof RangeError))throw _}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return s}let{headByte:i,pos:d,totalPos:C}=this;throw new RangeError(\`Insufficient data in parsing \${OA(i)} at \${C} (\${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 s=t,i=-1;for await(let d of A){if(t&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(d),s&&(i=this.readArraySize(),s=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(C){if(!(C instanceof RangeError))throw C}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: \${OA(A)}\`);this.complete();let s=this.stack;for(;s.length>0;){let i=s.top();if(i.type===mr)if(i.array[i.position]=t,i.position++,i.position===i.size)t=i.array,s.release(i);else continue A;else if(i.type===qA){if(t==="__proto__")throw new L("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,s.release(i);else{i.key=null,i.type=qA;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 L(\`Unrecognized array type byte: \${OA(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 ht;let s=this.pos+t,i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?i=this.keyDecoder.decode(this.bytes,s,A):i=Gt(this.bytes,s,A),this.pos+=t+A,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===qA:!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 ht;let s=this.pos+t,i=this.bytes.subarray(s,s+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 s=this.view.getInt8(this.pos+t),i=this.decodeBinary(A,t+1);return this.extensionCodec.decode(i,s,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=Et(this.view,this.pos);return this.pos+=8,A}readI64(){let A=NA(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(e,A){return new PA(A).decode(e)}var GA=class e{constructor(A,t,s,i,d){this.mediaIds=A;this.sequenceNumber=t;this.timeStamp=s;this.isEndOfSpurt=i;this.payload=d}static parse(A){let t;try{t=Fr(A)}catch{return B("not valid msgpack")}if(!Array.isArray(t))return B("container must be an array");if(t.length<6)return B("missing fields");if(t[0]!==1)return B("unknown type");if(!Array.isArray(t[1]))return B("media ids must be an array");if(!t[1].every(D=>typeof D=="number"))return B("media ids must be numbers");if(typeof t[2]!="number")return B("sequence number must be a number");if(typeof t[3]!="number")return B("timestamp must be a number");if(typeof t[4]!="number")return B("flags must be a number");let s=t[1],i=t[2]>>>0,d=t[3]>>>0,E=(t[4]&1)!==0,_=t[t.length-1];return _ instanceof Uint8Array?nt(new e(s,i,d,E,_)):B("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(Er(t,{forceFloat32:!0,ignoreUndefined:!0}))}};var wA=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,O.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=dt(this.wasm),this.outBuffer=U(this.wasm,"u8",1270),Yj(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(){Ct(this.wasm,this.information),tA(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){at(\`failed encoding packet: \${t}\`);return}if(this.timestamp=this.timestamp+1800>>0,t===1)continue;this.sequenceNumber=this.sequenceNumber+1>>0;let s=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,s,this.outBuffer.subarray(0,t));uA(globalThis,["sendPacket",{connectionId:i.id,packet:d.toBytes()}])}}}onMessage(A){let[t,s]=A;switch(t){case"captureSetVad":this?.setVad(s);break;case"captureSetMedias":this?.setMedias(s.connections);break;case"close":this.close();break;case"dump":s.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:Wj(this.information),speechProbability:Xj(this.information),rmsDBFS:zj(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}}}},TA=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",O.MaxNumberOfDecoders),this.information=ut(this.wasm,O.MaxNumberOfDecoders),wj(this.information,[1,1])}close(){ct(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,t){this.stats.numberPackets++;let s=GA.parse(t);if(s.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: \${s.reason}, connection: \${A}, dump: \${i}\`);return}for(let i of s.value.mediaIds){let d=this.medias.get(xA({connectionId:A,mediaId:i}));if(d===void 0){this.stats.numberPacketsMediaNotFound++;continue}d.lastPacket=t;let C=U(this.wasm,"u8",s.value.payload.length);C.set(s.value.payload),d.decoder.push(s.value.sequenceNumber,s.value.timeStamp,s.value.isEndOfSpurt,C.byteOffset,C.length)}}insertMedia(A,t,s,i=[1,1]){let d=xA({connectionId:t,mediaId:s}),C=new this.wasm.Decoder;this.medias.set(d,{index:A,decoder:C,lastPacket:void 0}),this.decoders[A]=C.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),Uj(this.information,A,i),Qj(this.information,A,0),Rj(this.information,A,0)}removeMedia(A,t,s){let i=xA({connectionId:t,mediaId:s}),d=this.medias.get(i);if(!(d===void 0||d.index!==A)&&(this.medias.delete(i),Sj(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,s]=A;switch(t){case"playbackReceivePacket":this.receivePacket(s.connectionId,s.packet);break;case"playbackUpdateMedias":for(let{index:i,connectionId:d,mediaId:C}of s.removed)this.removeMedia(i,d,C);for(let{index:i,connectionId:d,mediaId:C,volume:E}of s.added)this.insertMedia(i,d,C,E);break;case"close":this.close();break;case"dump":s.result.postMessage(this.dump());break}}dump(){let A=[];for(let[t,s]of this.medias){let i=kt(t);A.push({index:s.index,connectionId:i.connectionId,mediaId:i.mediaId,rmsDBFS:Tj(this.information,s.index),volume:Mj(this.information,s.index),voicedBlocks:Vj(this.information,s.index),silentBlocks:Kj(this.information,s.index),time:s.decoder.time,consecutive_silence:s.decoder.consecutive_silence,last_voiced_time_point:s.decoder.last_voiced_time_point,sequence_number:s.decoder.sequence_number,packetsSeen:s.decoder.packets_seen,packetsInvalid:s.decoder.packets_invalid,packetsTooLate:s.decoder.packets_too_late,packetsTooEarly:s.decoder.packets_too_early,packetsRepeated:s.decoder.packets_repeated,packetsProcessed:s.decoder.packets_processed,packetsLost:s.decoder.packets_lost,rewinds:s.decoder.rewinds,cacheLength:s.decoder.cache_length,lastPacket:At(s.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:Pj(this.information),decoders:A}}};var Lt=Fn(vt()),It=(0,Lt.default)(),_t,Ht;globalThis.addEventListener("message",e=>{vr(e).catch(console.error)});async function vr(e){let A=e.data,[t,s]=A;switch(t){case"captureInit":s.workletPort.onmessage=vr,_t=new Ir(s.sampleRate,await It);break;case"playbackInit":s.workletPort.onmessage=vr,Ht=new _r(await It);break;case"close":globalThis.close();break}_t?.onMessage(A),Ht?.onMessage(A)}var Ir=class extends wA{constructor(t,s){super(t,s);this.id=-1;this.samples=qr(this.wasm,t,2+O.VadPreload+O.AdditionalCaptureBlocks,!1),uA(globalThis,["captureReady",{sampleBuffer:this.samples,informationBuffer:this.information}])}close(){super.close(),Gr(this.wasm,this.samples)}onMessage(t){super.onMessage(t);let[s,i]=t;s==="captureTick"&&this.tick(i.id)}tick(t){for(;this.id<t;this.id+=1)this.encode(ur(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()}}},_r=class extends TA{constructor(A){super(A);let t=2+O.AdditionalPlaybackBlocks;this.sampleBuffer=qr(A,48e3,t,!0),this.sampleBuffer.samples.fill(0),this.prefill=t-2;for(let s=0;s<this.prefill;s++)cr(this.sampleBuffer,s,{id:s});this.id=this.prefill,uA(globalThis,["playbackReady",{sampleBuffer:this.sampleBuffer,informationBuffer:this.information}])}close(){super.close(),Gr(this.wasm,this.sampleBuffer)}onMessage(A){super.onMessage(A);let[t,s]=A;t==="playbackTick"&&this.tick(s.id)}tick(A){for(this.stats.numberTicks++;this.id<A+this.prefill;this.id++){let t=this.id%this.sampleBuffer.length,{hasAudio:s}=this.decode(ur(this.sampleBuffer,t));s&&(this.stats.numberTicksWithAudio++,cr(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()}}};})();
|
|
3380
|
+
`});var j0,S0=p(()=>{j0='"use strict";(()=>{var E=Object.defineProperty;var F=(e,t)=>{for(var r in t)E(e,r,{get:t[r],enumerable:!0})};var l={};F(l,{AdditionalCaptureBlocks:()=>C,AdditionalPlaybackBlocks:()=>D,ClockJumpCheckInterval:()=>j,ClockJumpThreshold:()=>$,ConnectInterval:()=>ee,ConnectTimeout:()=>Y,DefaultRefreshRate:()=>V,DefaultVideoCodec:()=>re,HealthCheckTimeout:()=>W,MainConnectionPingInterval:()=>H,MaxNumberOfDecoders:()=>_,MaxReconnectDuration:()=>te,MinDBFs:()=>k,MinTokenLifetime:()=>K,MinTokenRefreshInterval:()=>X,PlaybackPreload:()=>L,RenderQuantumSize:()=>N,VadPreload:()=>O,WebRtcAnswerTimeout:()=>Z,WebRtcIceTimeout:()=>J,WebRtcMaxNegotiationAttempts:()=>q,WebRtcRecoveryDelays:()=>Q,WebRtcStatsSnapshotInterval:()=>G,WebRtcTimeout:()=>z});var D=3,C=3,L=3,V=250,O=3,_=512,N=128,k=-758.596,W=1e4,j=1e3,$=1e4,H=3e3,G=1e3,J=3e3,z=1e4,Z=1e4,q=3,Q=[0,2e3,5e3],Y=5e3,K=6e4,X=5e3,ee=[0,100,200,200,500],te=12e4,re="H264";function p(e,t,r){return e.postMessage(t,r)}function ne(e){return e.sampleRate*.02*(e.stereo?2:1)}function f(e,t){let r=ne(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 se;(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||={})})(se||={});var{Deno:U}=globalThis,oe=typeof U?.noColor=="boolean"?U.noColor:!1,ae=!oe;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 ae?`${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 ie(e){return b(e,h([2],22))}var Ae=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"),ce=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}"},le={4:ie,3:m,2:m,1:T,0:T};function ue({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()-ce.valueOf();[i,c]=t(i,1e3);let[M,R]=t(i,60);return`${M.toString().padStart(4,"0")}:${R.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],a=e.logger.name!==void 0?`@${e.logger.name}`:"";return`${m(r())}${a} ${s} ${le[e.level](String(e.message))}${n()}`}function fe(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 de(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var A=class{static sparse=ue;static json=B;static pretty=w;static structured=fe;static default=de()?w:B;constructor(){}};var pe=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 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=globalThis[Symbol.for("odin-global-logger")]??=new o(3,void 0,[new pe]),me=o.prototype.log.bind(u,1),he=o.prototype.log.bind(u,2),be=o.prototype.log.bind(u,3),xe=o.prototype.log.bind(u,4),Me=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 M0={};kx(M0,{createCaptureWorker:()=>BF,createPlaybackWorker:()=>CF});function BF(D,x,A,F,r=E.DefaultRefreshRate){return vF.enqueue(async()=>{let[t,e]=await Ex(e0,j0,D,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return B0.create(D,x,A,t,e,F)})}async function CF(D,x=E.DefaultRefreshRate){if(D.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[A,F]=await Ex(e0,j0,D,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return v0.create(D,A,F)}var T0,vF,v0,B0,U0=p(()=>{"use strict";T0=require("@4players/odin-common");o();qx();R0();S0();vF=new T0.Strand;v0=class D extends vx{constructor(A,F,r,t){super(A,F,r);this.information=t}static async create(A,F,r){let{port1:t,port2:e}=new MessageChannel;a(F,["playbackInit",{workletPort:t}],[t]);let{informationBuffer:j,sampleBuffer:B}=await Dx(F,"playbackReady");return D0(j,[1,1]),a(r.port,["init",{sampleBuffer:B,workerPort:e}],[e]),new D(A,r,F,j)}getActivity(A){let F=this.medias.get(h(A));if(F===void 0)return;let r=d0(this.information,F.index);return r===0?I:{isSilent:!1,rmsDBFS:r}}getJitterStats(A){}setGlobalVolume(A){D0(this.information,A)}setVolume(A,F){let r=this.medias.get(h(A));r!==void 0&&p0(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}},B0=class D extends Bx{constructor(A,F,r,t,e,j){super(A,F,r,t,j);this.information=e}static async create(A,F,r,t,e,j){let{port1:B,port2:s}=new MessageChannel;a(t,["captureInit",{sampleRate:A.sampleRate,workletPort:B}],[B]);let{sampleBuffer:l,informationBuffer:c}=await Dx(t,"captureReady");return a(e.port,["init",{workerPort:s,sampleBuffer:l}],[s]),new D(e,t,F,r,c,j)}get activity(){return{isSilent:!h0(this.information),rmsDBFS:q0(this.information)}}get speechProbability(){return m0(this.information)}setVolume(A){G0(this.information,A)}}});var C0,K0=p(()=>{C0=`"use strict";(()=>{var un=Object.create;var XA=Object.defineProperty;var cn=Object.getOwnPropertyDescriptor;var dn=Object.getOwnPropertyNames;var Cn=Object.getPrototypeOf,qn=Object.prototype.hasOwnProperty;var fn=(n,A)=>()=>{try{return A||n((A={exports:{}}).exports,A),A.exports}catch(j){throw A=0,j}},Gn=(n,A)=>{for(var j in A)XA(n,j,{get:A[j],enumerable:!0})},pn=(n,A,j,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let l of dn(A))!qn.call(n,l)&&l!==j&&XA(n,l,{get:()=>A[l],enumerable:!(e=cn(A,l))||e.enumerable});return n};var En=(n,A,j)=>(j=n!=null?un(Cn(n)):{},pn(A||!n||!n.__esModule?XA(j,"default",{value:n,enumerable:!0}):j,n));var yj=fn((Ij,PA)=>{"use strict";var er=(()=>{var n=globalThis.document?.currentScript?.src;return async function(A={}){var j=A,e=!!globalThis.window,l=!!globalThis.WorkerGlobalScope,c=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",C=[],p="./this.program";l&&(n=self.location.href);var I="",B,wA;if(e||l){try{I=new URL(".",n).href}catch{}l&&(wA=t=>{var r=new XMLHttpRequest;return r.open("GET",t,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),B=async t=>{var r=await fetch(t,{credentials:"same-origin"});if(r.ok)return r.arrayBuffer();throw new Error(r.status+" : "+r.url)}}var b=console.log.bind(console),aA=console.error.bind(console),Dj,or=!1;class Bj{}class _e extends Bj{}function xj(t){for(var r=0,s=t.length,i=new Uint8Array(s),o;r<s;++r)o=t.charCodeAt(r),i[r]=~o>>8&o;return i}var Nj=!1;function bj(){var t=Sr.buffer;U=new Int8Array(t),cA=new Int16Array(t),j.HEAPU8=g=new Uint8Array(t),rA=new Uint16Array(t),j.HEAP32=dA=new Int32Array(t),j.HEAPU32=$=new Uint32Array(t),j.HEAPF32=Br=new Float32Array(t),xr=new Float64Array(t),dr=new BigInt64Array(t),Cr=new BigUint64Array(t)}function Oj(){var t=j.preRun;t&&(typeof t=="function"&&(t=[t]),cr.push(...t)),kr(cr)}function Jj(){Nj=!0,tA.v()}function Pj(){var t=j.postRun;t&&(typeof t=="function"&&(t=[t]),ur.push(...t)),kr(ur)}function kA(t){j.onAbort?.(t),t=\`Aborted(\${t})\`,aA(t),or=!0,t+=". Build with -sASSERTIONS for more info.";var r=new WebAssembly.RuntimeError(t);throw r}var ar;function wj(){return xj(\`\\0asm\\0\\0\\0\\x8E9\\\`\\x7F\\x7F\\\`\\x7F\\0\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\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}}\\\`\\0\\x7F\\\`\\x7F\\x7F}}\\0\\\`
|
|
3381
3381
|
\\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\\\`\\x07\\x7F|\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\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\\0ag\\0!ah\\0 ai\\0aj\\0\\bak\\0"al\\0am\\0an\\0ao\\0\\0ap\\0#aq\\0\\0ar\\0
|
|
3382
3382
|
as\\0at\\0\\xBD\\xBB\\x07\\0\\0\\f$\\f\\0\\x07\\f\\f\\x07\\0%& \\0
|
|
3383
3383
|
\\0\\v\\0'\\0\\0(\\0\\f\\0)*+\\x07\\v\\0
|
|
@@ -6706,7 +6706,7 @@ K\\xE08\\xDF\\0}\\xBC\\x8A\\x1B\\f\\xE5\\xFF\\xCF\\xE8?\\x9F\\xFFFq\\0\\x88\\xB
|
|
|
6706
6706
|
|
|
6707
6707
|
|
|
6708
6708
|
\\x07\\0\\0 \\v\\0\\0 \\v\\0\\0\\v\\0\\0\\0\\0\\0A\\xB1\\x9D\\v!\\0\\0\\0\\0\\0\\0\\0\\0\\0\\v\\r\\0\\r\\0\\0\\0 \\0\\0\\0 \\0\\0\\0\\0A\\xEB\\x9D\\v\\f\\0A\\xF7\\x9D\\v\\0\\0\\0\\0\\0\\0\\0\\0 \\f\\0\\0\\0\\0\\0\\f\\0\\0\\f\\0A\\xA5\\x9E\\v\\0A\\xB1\\x9E\\v\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0A\\xDF\\x9E\\v\\0A\\xEB\\x9E\\v\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0A\\xA2\\x9F\\v\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0A\\xD3\\x9F\\v\\0A\\xDF\\x9F\\v\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0A\\x8D\\xA0\\v\\0A\\x99\\xA0\\v\\xB3 \\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\x000123456789ABCDEF\\xF0\\0H\\0NSt3__214__shared_countE\\0\\0\\0\\0t\\0|\\0\\0\\0\\0\\0\\0\\0\\0@\\0\\0\\0\\0\\0NSt3__219__shared_weak_countE\\0\\0\\0\\0\\xA8\\0\\xB8\\0N10__cxxabiv116__shim_type_infoE\\0\\0\\0\\0\\0\\xD8\\0\\x9C\\0N10__cxxabiv117__class_type_infoE\\0\\0\\0\\0\\b\\0\\x9C\\0N10__cxxabiv117__pbase_type_infoE\\0\\0\\0\\x008\\0\\xFC\\0N10__cxxabiv119__pointer_type_infoE\\0\\0h\\0\\x9C\\0N10__cxxabiv120__function_type_infoE\\0\\0\\0\\0\\0\\x9C\\0\\xFC\\0N10__cxxabiv129__pointer_to_member_type_infoE\\0\\0\\0\\0\\0\\0\\0\\xE8\\0]\\0\\0\\0^\\0\\0\\0_\\0\\0\\0\\\`\\0\\0\\0a\\0\\0\\0\\0\\xF4\\0\\x9C\\0N10__cxxabiv123__fundamental_type_infoE\\0\\xD4\\0$\\0v\\0Dn\\0\\0\\0\\0\\xD4\\x004\\0b\\0\\0\\0\\xD4\\0@\\0c\\0\\0\\0\\xD4\\0L\\0h\\0\\0\\0\\xD4\\0X\\0a\\0\\0\\0\\xD4\\0d\\0s\\0\\0\\0\\xD4\\0p\\0t\\0\\0\\0\\xD4\\0|\\0i\\0\\0\\0\\xD4\\0\\x88\\0j\\0\\0\\0\\xD4\\0\\x94\\0l\\0\\0\\0\\xD4\\0\\xA0\\0m\\0\\0\\0\\xD4\\0\\xAC\\0x\\0\\0\\0\\xD4\\0\\xB8\\0y\\0\\0\\0\\xD4\\0\\xC4\\0f\\0\\0\\0\\xD0\\0\\xD8\\0\\0\\0\\0\\0\\xBC\\0Pf\\0\\0\\xD4\\0\\xE4\\0d\\0\\0\\0\\0\\0\\0\\0\\xCC\\0]\\0\\0\\0b\\0\\0\\0_\\0\\0\\0\\\`\\0\\0\\0c\\0\\0\\0d\\0\\0\\0e\\0\\0\\0f\\0\\0\\0\\0\\0\\0\\x008\\0]\\0\\0\\0g\\0\\0\\0_\\0\\0\\0\\\`\\0\\0\\0c\\0\\0\\0h\\0\\0\\0i\\0\\0\\0j\\0\\0\\0\\0D\\0\\xCC\\0N10__cxxabiv120__si_class_type_infoE\\0\\0\\0\\0\\0\\0\\0\\0\\x94\\0]\\0\\0\\0k\\0\\0\\0_\\0\\0\\0\\\`\\0\\0\\0c\\0\\0\\0l\\0\\0\\0m\\0\\0\\0n\\0\\0\\0\\0\\xA0\\0\\xCC\\0N10__cxxabiv121__vmi_class_type_infoE\\0\\0\\0\\0\\0\\0\\0,\\0]\\0\\0\\0o\\0\\0\\0_\\0\\0\\0\\\`\\0\\0\\0p\\0\\0\\0\\0\\0\\0\\0,\\0C\\0\\0\\0q\\0\\0\\0r\\0\\0\\0\\xF0\\0\\0\\0St9exception\\0\\0\\0\\0\\0\\0\\xF8\\0St9bad_alloc\\0\\0\\0\\0\\x008\\0\\0St20bad_array_new_length\\0\\0\\0\\0\\0\\0\\0\\0h\\0E\\0\\0\\0s\\0\\0\\0t\\0\\0\\0\\0t\\0\\xF8\\0St11logic_error\\0\\0\\0\\0\\0\\x98\\0E\\0\\0\\0u\\0\\0\\0t\\0\\0\\0\\0\\xA4\\0h\\0St12length_error\\0\\0\\0\\0\\xF0\\0\\xC0\\0St9type_info\\0A\\xD0\\xA9\\v\\0A\\xDC\\xA9\\vU\\0A\\xF4\\xA9\\v\\vV\\0\\0\\0W\\0\\0\\x008\\0A\\x8C\\xAA\\v\\0A\\x9C\\xAA\\v\\b\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\0A\\xE0\\xAA\\v \\xD0\\0\\0\\0\\0\\0\\0A\\xF4\\xAA\\vX\\0A\\x8C\\xAB\\vV\\0\\0\\0Y\\0\\0\\0H\\0\\0\\0A\\xA4\\xAB\\v\\0A\\xB4\\xAB\\v\\xFF\\xFF\\xFF\\xFF
|
|
6709
|
-
\\0A\\xF8\\xAB\\v\\vh\\0h\\0\\x80\`)}function ye(t){return t}async function Tj(t){return t}async function Sj(t,r){try{var s=await Tj(t),i=await WebAssembly.instantiate(s,r);return i}catch(o){aA(\`failed to asynchronously prepare wasm: \${o}\`),kA(o)}}async function Uj(t,r,s){return Sj(r,s)}function Mj(){var t={a:on};return t}async function Kj(){function t(a){return tA=a.exports,ln(tA),bj(),tA}function r(a){return t(a.instance)}var s=Mj(),i=j.instantiateWasm;if(i)return new Promise(a=>{i(s,u=>a(t(u)))});ar??=wj();var o=await Uj(Dj,ar,s),k=r(o);return k}class Le{name="ExitStatus";constructor(r){this.message=\`Program terminated with exit(\${r})\`,this.status=r}}var kr=t=>{for(;t.length>0;)t.shift()(j)},ur=[],cr=[],Rj=!0,Vj=t=>wr(t),Qj=()=>Tr(),U,$;class Xj{constructor(r){this.excPtr=r,this.ptr=r-24}set_type(r){$[this.ptr+4>>2]=r}get_type(){return $[this.ptr+4>>2]}set_destructor(r){$[this.ptr+8>>2]=r}get_destructor(){return $[this.ptr+8>>2]}set_caught(r){r=r?1:0,U[this.ptr+12]=r}get_caught(){return U[this.ptr+12]!=0}set_rethrown(r){r=r?1:0,U[this.ptr+13]=r}get_rethrown(){return U[this.ptr+13]!=0}init(r,s){this.set_adjusted_ptr(0),this.set_type(r),this.set_destructor(s)}set_adjusted_ptr(r){$[this.ptr+16>>2]=r}get_adjusted_ptr(){return $[this.ptr+16>>2]}}var zj=0,Wj=t=>{kA()},Zj=(t,r,s)=>{var i=new Xj(t);i.init(r,s),zj++,Wj(t)},Yj=()=>kA(""),g,_=t=>{for(var r="";;){var s=g[t++];if(!s)return r;r+=String.fromCharCode(s)}},X={},z={},uA={};class AA extends Error{constructor(r){super(r),this.name="BindingError"}}var G=t=>{throw new AA(t)};function At(t,r,s={}){var i=r.name;if(t||G(\`type "\${i}" must have a positive integer typeid pointer\`),z.hasOwnProperty(t)){if(s.ignoreDuplicateRegistrations)return;G(\`Cannot register type '\${i}' twice\`)}if(z[t]=r,delete uA[t],X.hasOwnProperty(t)){var o=X[t];delete X[t],o.forEach(k=>k())}}function x(t,r,s={}){return At(t,r,s)}var cA,rA,dA,dr,Cr,qr=(t,r,s)=>{switch(r){case 1:return s?i=>U[i]:i=>g[i];case 2:return s?i=>cA[i>>1]:i=>rA[i>>1];case 4:return s?i=>dA[i>>2]:i=>$[i>>2];case 8:return s?i=>dr[i>>3]:i=>Cr[i>>3];default:throw new TypeError(\`invalid integer width (\${r}): \${t}\`)}},rt=(t,r,s,i,o)=>{r=_(r);let k=i===0n,a=u=>u;if(k){let u=s*8;a=d=>BigInt.asUintN(u,d),o=a(o)}x(t,{name:r,fromWireType:a,toWireType:(u,d)=>(typeof d=="number"&&(d=BigInt(d)),d),readValueFromPointer:qr(r,s,!k),destructorFunction:null})},jt=(t,r,s,i)=>{r=_(r),x(t,{name:r,fromWireType:function(o){return!!o},toWireType:function(o,k){return k?s:i},readValueFromPointer:function(o){return this.fromWireType(g[o])},destructorFunction:null})},tt=t=>({count:t.count,deleteScheduled:t.deleteScheduled,preservePointerOnDelete:t.preservePointerOnDelete,ptr:t.ptr,ptrType:t.ptrType,smartPtr:t.smartPtr,smartPtrType:t.smartPtrType}),TA=t=>{function r(s){return s.$$.ptrType.registeredClass.name}G(r(t)+" instance already deleted")},SA=!1,fr=t=>{},nt=t=>{t.smartPtr?t.smartPtrType.rawDestructor(t.smartPtr):t.ptrType.registeredClass.rawDestructor(t.ptr)},Gr=t=>{t.count.value-=1;var r=t.count.value===0;r&&nt(t)},jA=t=>globalThis.FinalizationRegistry?(SA=new FinalizationRegistry(r=>{Gr(r.$$)}),jA=r=>{var s=r.$$,i=!!s.smartPtr;if(i){var o={$$:s};SA.register(r,o,r)}return r},fr=r=>SA.unregister(r),jA(t)):(jA=r=>r,t),CA=[],et=()=>{for(;CA.length;){var t=CA.pop();t.$$.deleteScheduled=!1,t.delete()}},pr,st=()=>{let t=qA.prototype;Object.assign(t,{isAliasOf(s){if(!(this instanceof qA)||!(s instanceof qA))return!1;var i=this.$$.ptrType.registeredClass,o=this.$$.ptr;s.$$=s.$$;for(var k=s.$$.ptrType.registeredClass,a=s.$$.ptr;i.baseClass;)o=i.upcast(o),i=i.baseClass;for(;k.baseClass;)a=k.upcast(a),k=k.baseClass;return i===k&&o===a},clone(){if(this.$$.ptr||TA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var s=jA(Object.create(Object.getPrototypeOf(this),{$$:{value:tt(this.$$)}}));return s.$$.count.value+=1,s.$$.deleteScheduled=!1,s},delete(){this.$$.ptr||TA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),fr(this),Gr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||TA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),CA.push(this),CA.length===1&&pr&&pr(et),this.$$.deleteScheduled=!0,this}});let r=Symbol.dispose;r&&(t[r]=t.delete)};function qA(){}var Er=(t,r)=>Object.defineProperty(r,"name",{value:t}),mr={},hr=(t,r,s)=>{if(t[r].overloadTable===void 0){var i=t[r];t[r]=function(...o){return t[r].overloadTable.hasOwnProperty(o.length)||G(\`Function '\${s}' called with an invalid number of arguments (\${o.length}) - expects one of (\${t[r].overloadTable})!\`),t[r].overloadTable[o.length].apply(this,o)},t[r].overloadTable=[],t[r].overloadTable[i.argCount]=i}},$r=(t,r,s)=>{j.hasOwnProperty(t)?((s===void 0||j[t].overloadTable!==void 0&&j[t].overloadTable[s]!==void 0)&&G(\`Cannot register public name '\${t}' twice\`),hr(j,t,t),j[t].overloadTable.hasOwnProperty(s)&&G(\`Cannot register multiple overloads of a function with the same number of arguments (\${s})!\`),j[t].overloadTable[s]=r):(j[t]=r,j[t].argCount=s)},lt=48,it=57,ot=t=>{t=t.replace(/[^a-zA-Z0-9_]/g,"$");var r=t.charCodeAt(0);return r>=lt&&r<=it?\`_\${t}\`:t};function at(t,r,s,i,o,k,a,u){this.name=t,this.constructor=r,this.instancePrototype=s,this.rawDestructor=i,this.baseClass=o,this.getActualType=k,this.upcast=a,this.downcast=u,this.pureVirtualFunctions=[]}var fA=(t,r,s)=>{for(;r!==s;)r.upcast||G(\`Expected null or instance of \${s.name}, got an instance of \${r.name}\`),t=r.upcast(t),r=r.baseClass;return t},UA=t=>{if(t===null)return"null";var r=typeof t;return r==="object"||r==="array"||r==="function"?t.toString():""+t};function kt(t,r){if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;r.$$||G(\`Cannot pass "\${UA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`);var s=r.$$.ptrType.registeredClass,i=fA(r.$$.ptr,s,this.registeredClass);return i}function ut(t,r){var s;if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),this.isSmartPointer?(s=this.rawConstructor(),t!==null&&t.push(this.rawDestructor,s),s):0;(!r||!r.$$)&&G(\`Cannot pass "\${UA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),!this.isConst&&r.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name} to parameter type \${this.name}\`);var i=r.$$.ptrType.registeredClass;if(s=fA(r.$$.ptr,i,this.registeredClass),this.isSmartPointer)switch(r.$$.smartPtr===void 0&&G("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:r.$$.smartPtrType===this?s=r.$$.smartPtr:G(\`Cannot convert argument of type \${r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name} to parameter type \${this.name}\`);break;case 1:s=r.$$.smartPtr;break;case 2:if(r.$$.smartPtrType===this)s=r.$$.smartPtr;else{var o=r.clone();s=this.rawShare(s,RA.toHandle(()=>o.delete())),t!==null&&t.push(this.rawDestructor,s)}break;default:G("Unsupported sharing policy")}return s}function ct(t,r){if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;r.$$||G(\`Cannot pass "\${UA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),r.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${r.$$.ptrType.name} to parameter type \${this.name}\`);var s=r.$$.ptrType.registeredClass,i=fA(r.$$.ptr,s,this.registeredClass);return i}function GA(t){return this.fromWireType($[t>>2])}var Fr=(t,r,s)=>{if(r===s)return t;if(s.baseClass===void 0)return null;var i=Fr(t,r,s.baseClass);return i===null?null:s.downcast(i)},dt={},Ct=(t,r)=>{for(r===void 0&&G("ptr should not be undefined");t.baseClass;)r=t.upcast(r),t=t.baseClass;return r},qt=(t,r)=>(r=Ct(t,r),dt[r]);class ft extends Error{constructor(r){super(r),this.name="InternalError"}}var pA=t=>{throw new ft(t)},EA=(t,r)=>{(!r.ptrType||!r.ptr)&&pA("makeClassHandle requires ptr and ptrType");var s=!!r.smartPtrType,i=!!r.smartPtr;return s!==i&&pA("Both smartPtrType and smartPtr must be specified"),r.count={value:1},jA(Object.create(t,{$$:{value:r,writable:!0}}))};function Gt(t){var r=this.getPointee(t);if(!r)return this.destructor(t),null;var s=qt(this.registeredClass,r);if(s!==void 0){if(s.$$.count.value===0)return s.$$.ptr=r,s.$$.smartPtr=t,s.clone();var i=s.clone();return this.destructor(t),i}function o(){return this.isSmartPointer?EA(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:r,smartPtrType:this,smartPtr:t}):EA(this.registeredClass.instancePrototype,{ptrType:this,ptr:t})}var k=this.registeredClass.getActualType(r),a=mr[k];if(!a)return o.call(this);var u;this.isConst?u=a.constPointerType:u=a.pointerType;var d=Fr(r,this.registeredClass,u.registeredClass);return d===null?o.call(this):this.isSmartPointer?EA(u.registeredClass.instancePrototype,{ptrType:u,ptr:d,smartPtrType:this,smartPtr:t}):EA(u.registeredClass.instancePrototype,{ptrType:u,ptr:d})}var pt=()=>{Object.assign(mA.prototype,{getPointee(t){return this.rawGetPointee&&(t=this.rawGetPointee(t)),t},destructor(t){this.rawDestructor?.(t)},readValueFromPointer:GA,fromWireType:Gt})};function mA(t,r,s,i,o,k,a,u,d,f,q){this.name=t,this.registeredClass=r,this.isReference=s,this.isConst=i,this.isSmartPointer=o,this.pointeeType=k,this.sharingPolicy=a,this.rawGetPointee=u,this.rawConstructor=d,this.rawShare=f,this.rawDestructor=q,!o&&r.baseClass===void 0?i?(this.toWireType=kt,this.destructorFunction=null):(this.toWireType=ct,this.destructorFunction=null):this.toWireType=ut}var vr=(t,r,s)=>{j.hasOwnProperty(t)||pA("Replacing nonexistent public symbol"),j[t].overloadTable!==void 0&&s!==void 0?j[t].overloadTable[s]=r:(j[t]=r,j[t].argCount=s)},Ir=[],Et=t=>{var r=Ir[t];return r||(Ir[t]=r=Ur.get(t)),r},O=(t,r,s=!1)=>{t=_(t);function i(){var k=Et(r);return k}var o=i();return typeof o!="function"&&G(\`unknown function pointer with signature \${t}: \${r}\`),o};class mt extends Error{}var ht=t=>{var r=Pr(t),s=_(r);return J(r),s},W=(t,r)=>{var s=[],i={};function o(k){if(!i[k]&&!z[k]){if(uA[k]){uA[k].forEach(o);return}s.push(k),i[k]=!0}}throw r.forEach(o),new mt(\`\${t}: \`+s.map(ht).join([", "]))},w=(t,r,s)=>{t.forEach(u=>uA[u]=r);function i(u){var d=s(u);d.length!==t.length&&pA("Mismatched type converter count");for(var f=0;f<t.length;++f)x(t[f],d[f])}var o=new Array(r.length),k=[],a=0;for(let[u,d]of r.entries())z.hasOwnProperty(d)?o[u]=z[d]:(k.push(d),X.hasOwnProperty(d)||(X[d]=[]),X[d].push(()=>{o[u]=z[d],++a,a===k.length&&i(o)}));k.length===0&&i(o)},$t=(t,r,s,i,o,k,a,u,d,f,q,E,v)=>{q=_(q),k=O(o,k),u&&=O(a,u),f&&=O(d,f),v=O(E,v);var F=ot(q);$r(F,function(){W(\`Cannot construct \${q} due to unbound types\`,[i])}),w([t,r,s],i?[i]:[],h=>{h=h[0];var m,N;i?(m=h.registeredClass,N=m.instancePrototype):N=qA.prototype;var L=Er(q,function(...QA){if(Object.getPrototypeOf(this)!==K)throw new AA(\`Use 'new' to construct \${q}\`);if(H.constructor_body===void 0)throw new AA(\`\${q} has no accessible constructor\`);var Rr=H.constructor_body[QA.length];if(Rr===void 0)throw new AA(\`Tried to invoke ctor of \${q} with invalid number of parameters (\${QA.length}) - expected (\${Object.keys(H.constructor_body).toString()}) parameters instead!\`);return Rr.apply(this,QA)}),K=Object.create(N,{constructor:{value:L}});L.prototype=K;var H=new at(q,L,K,v,m,k,u,f);H.baseClass&&(H.baseClass.__derivedClasses??=[],H.baseClass.__derivedClasses.push(H));var kn=new mA(q,H,!0,!1,!1),Mr=new mA(q+"*",H,!1,!1,!1),Kr=new mA(q+" const*",H,!1,!0,!1);return mr[t]={pointerType:Mr,constPointerType:Kr},vr(F,L),[kn,Mr,Kr]})},MA=(t,r)=>{for(var s=[],i=0;i<t;i++)s.push($[r+i*4>>2]);return s},_r=t=>{for(;t.length;){var r=t.pop(),s=t.pop();s(r)}};function yr(t){for(var r=1;r<t.length;++r)if(t[r]!==null&&t[r].destructorFunction===void 0)return!0;return!1}function Lr(t){for(var r=1;r<t.length;++r)if(t[r]!==null&&t[r].argStackAlloc)return!0;return!1}function Ft(t,r,s,i){var o=yr(t),k=Lr(t),a=k&&!i&&!o;k&&!a&&(o=!0);var u=t.length-2,d=[],f=["fn"];r&&f.push("thisWired");for(var q=0;q<u;++q)d.push(\`arg\${q}\`),f.push(\`arg\${q}Wired\`);d=d.join(),f=f.join();var E=\`return function (\${d}) {
|
|
6709
|
+
\\0A\\xF8\\xAB\\v\\vh\\0h\\0\\x80\`)}function Le(t){return t}async function Tj(t){return t}async function Sj(t,r){try{var s=await Tj(t),i=await WebAssembly.instantiate(s,r);return i}catch(o){aA(\`failed to asynchronously prepare wasm: \${o}\`),kA(o)}}async function Uj(t,r,s){return Sj(r,s)}function Mj(){var t={a:on};return t}async function Kj(){function t(a){return tA=a.exports,ln(tA),bj(),tA}function r(a){return t(a.instance)}var s=Mj(),i=j.instantiateWasm;if(i)return new Promise(a=>{i(s,u=>a(t(u)))});ar??=wj();var o=await Uj(Dj,ar,s),k=r(o);return k}class He{name="ExitStatus";constructor(r){this.message=\`Program terminated with exit(\${r})\`,this.status=r}}var kr=t=>{for(;t.length>0;)t.shift()(j)},ur=[],cr=[],Rj=!0,Vj=t=>wr(t),Qj=()=>Tr(),U,$;class Xj{constructor(r){this.excPtr=r,this.ptr=r-24}set_type(r){$[this.ptr+4>>2]=r}get_type(){return $[this.ptr+4>>2]}set_destructor(r){$[this.ptr+8>>2]=r}get_destructor(){return $[this.ptr+8>>2]}set_caught(r){r=r?1:0,U[this.ptr+12]=r}get_caught(){return U[this.ptr+12]!=0}set_rethrown(r){r=r?1:0,U[this.ptr+13]=r}get_rethrown(){return U[this.ptr+13]!=0}init(r,s){this.set_adjusted_ptr(0),this.set_type(r),this.set_destructor(s)}set_adjusted_ptr(r){$[this.ptr+16>>2]=r}get_adjusted_ptr(){return $[this.ptr+16>>2]}}var Wj=0,zj=t=>{kA()},Zj=(t,r,s)=>{var i=new Xj(t);i.init(r,s),Wj++,zj(t)},Yj=()=>kA(""),g,y=t=>{for(var r="";;){var s=g[t++];if(!s)return r;r+=String.fromCharCode(s)}},X={},W={},uA={};class AA extends Error{constructor(r){super(r),this.name="BindingError"}}var G=t=>{throw new AA(t)};function At(t,r,s={}){var i=r.name;if(t||G(\`type "\${i}" must have a positive integer typeid pointer\`),W.hasOwnProperty(t)){if(s.ignoreDuplicateRegistrations)return;G(\`Cannot register type '\${i}' twice\`)}if(W[t]=r,delete uA[t],X.hasOwnProperty(t)){var o=X[t];delete X[t],o.forEach(k=>k())}}function x(t,r,s={}){return At(t,r,s)}var cA,rA,dA,dr,Cr,qr=(t,r,s)=>{switch(r){case 1:return s?i=>U[i]:i=>g[i];case 2:return s?i=>cA[i>>1]:i=>rA[i>>1];case 4:return s?i=>dA[i>>2]:i=>$[i>>2];case 8:return s?i=>dr[i>>3]:i=>Cr[i>>3];default:throw new TypeError(\`invalid integer width (\${r}): \${t}\`)}},rt=(t,r,s,i,o)=>{r=y(r);let k=i===0n,a=u=>u;if(k){let u=s*8;a=d=>BigInt.asUintN(u,d),o=a(o)}x(t,{name:r,fromWireType:a,toWireType:(u,d)=>(typeof d=="number"&&(d=BigInt(d)),d),readValueFromPointer:qr(r,s,!k),destructorFunction:null})},jt=(t,r,s,i)=>{r=y(r),x(t,{name:r,fromWireType:function(o){return!!o},toWireType:function(o,k){return k?s:i},readValueFromPointer:function(o){return this.fromWireType(g[o])},destructorFunction:null})},tt=t=>({count:t.count,deleteScheduled:t.deleteScheduled,preservePointerOnDelete:t.preservePointerOnDelete,ptr:t.ptr,ptrType:t.ptrType,smartPtr:t.smartPtr,smartPtrType:t.smartPtrType}),TA=t=>{function r(s){return s.$$.ptrType.registeredClass.name}G(r(t)+" instance already deleted")},SA=!1,fr=t=>{},nt=t=>{t.smartPtr?t.smartPtrType.rawDestructor(t.smartPtr):t.ptrType.registeredClass.rawDestructor(t.ptr)},Gr=t=>{t.count.value-=1;var r=t.count.value===0;r&&nt(t)},jA=t=>globalThis.FinalizationRegistry?(SA=new FinalizationRegistry(r=>{Gr(r.$$)}),jA=r=>{var s=r.$$,i=!!s.smartPtr;if(i){var o={$$:s};SA.register(r,o,r)}return r},fr=r=>SA.unregister(r),jA(t)):(jA=r=>r,t),CA=[],et=()=>{for(;CA.length;){var t=CA.pop();t.$$.deleteScheduled=!1,t.delete()}},pr,st=()=>{let t=qA.prototype;Object.assign(t,{isAliasOf(s){if(!(this instanceof qA)||!(s instanceof qA))return!1;var i=this.$$.ptrType.registeredClass,o=this.$$.ptr;s.$$=s.$$;for(var k=s.$$.ptrType.registeredClass,a=s.$$.ptr;i.baseClass;)o=i.upcast(o),i=i.baseClass;for(;k.baseClass;)a=k.upcast(a),k=k.baseClass;return i===k&&o===a},clone(){if(this.$$.ptr||TA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var s=jA(Object.create(Object.getPrototypeOf(this),{$$:{value:tt(this.$$)}}));return s.$$.count.value+=1,s.$$.deleteScheduled=!1,s},delete(){this.$$.ptr||TA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),fr(this),Gr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||TA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),CA.push(this),CA.length===1&&pr&&pr(et),this.$$.deleteScheduled=!0,this}});let r=Symbol.dispose;r&&(t[r]=t.delete)};function qA(){}var Er=(t,r)=>Object.defineProperty(r,"name",{value:t}),mr={},hr=(t,r,s)=>{if(t[r].overloadTable===void 0){var i=t[r];t[r]=function(...o){return t[r].overloadTable.hasOwnProperty(o.length)||G(\`Function '\${s}' called with an invalid number of arguments (\${o.length}) - expects one of (\${t[r].overloadTable})!\`),t[r].overloadTable[o.length].apply(this,o)},t[r].overloadTable=[],t[r].overloadTable[i.argCount]=i}},$r=(t,r,s)=>{j.hasOwnProperty(t)?((s===void 0||j[t].overloadTable!==void 0&&j[t].overloadTable[s]!==void 0)&&G(\`Cannot register public name '\${t}' twice\`),hr(j,t,t),j[t].overloadTable.hasOwnProperty(s)&&G(\`Cannot register multiple overloads of a function with the same number of arguments (\${s})!\`),j[t].overloadTable[s]=r):(j[t]=r,j[t].argCount=s)},lt=48,it=57,ot=t=>{t=t.replace(/[^a-zA-Z0-9_]/g,"$");var r=t.charCodeAt(0);return r>=lt&&r<=it?\`_\${t}\`:t};function at(t,r,s,i,o,k,a,u){this.name=t,this.constructor=r,this.instancePrototype=s,this.rawDestructor=i,this.baseClass=o,this.getActualType=k,this.upcast=a,this.downcast=u,this.pureVirtualFunctions=[]}var fA=(t,r,s)=>{for(;r!==s;)r.upcast||G(\`Expected null or instance of \${s.name}, got an instance of \${r.name}\`),t=r.upcast(t),r=r.baseClass;return t},UA=t=>{if(t===null)return"null";var r=typeof t;return r==="object"||r==="array"||r==="function"?t.toString():""+t};function kt(t,r){if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;r.$$||G(\`Cannot pass "\${UA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`);var s=r.$$.ptrType.registeredClass,i=fA(r.$$.ptr,s,this.registeredClass);return i}function ut(t,r){var s;if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),this.isSmartPointer?(s=this.rawConstructor(),t!==null&&t.push(this.rawDestructor,s),s):0;(!r||!r.$$)&&G(\`Cannot pass "\${UA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),!this.isConst&&r.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name} to parameter type \${this.name}\`);var i=r.$$.ptrType.registeredClass;if(s=fA(r.$$.ptr,i,this.registeredClass),this.isSmartPointer)switch(r.$$.smartPtr===void 0&&G("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:r.$$.smartPtrType===this?s=r.$$.smartPtr:G(\`Cannot convert argument of type \${r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name} to parameter type \${this.name}\`);break;case 1:s=r.$$.smartPtr;break;case 2:if(r.$$.smartPtrType===this)s=r.$$.smartPtr;else{var o=r.clone();s=this.rawShare(s,RA.toHandle(()=>o.delete())),t!==null&&t.push(this.rawDestructor,s)}break;default:G("Unsupported sharing policy")}return s}function ct(t,r){if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;r.$$||G(\`Cannot pass "\${UA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),r.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${r.$$.ptrType.name} to parameter type \${this.name}\`);var s=r.$$.ptrType.registeredClass,i=fA(r.$$.ptr,s,this.registeredClass);return i}function GA(t){return this.fromWireType($[t>>2])}var Fr=(t,r,s)=>{if(r===s)return t;if(s.baseClass===void 0)return null;var i=Fr(t,r,s.baseClass);return i===null?null:s.downcast(i)},dt={},Ct=(t,r)=>{for(r===void 0&&G("ptr should not be undefined");t.baseClass;)r=t.upcast(r),t=t.baseClass;return r},qt=(t,r)=>(r=Ct(t,r),dt[r]);class ft extends Error{constructor(r){super(r),this.name="InternalError"}}var pA=t=>{throw new ft(t)},EA=(t,r)=>{(!r.ptrType||!r.ptr)&&pA("makeClassHandle requires ptr and ptrType");var s=!!r.smartPtrType,i=!!r.smartPtr;return s!==i&&pA("Both smartPtrType and smartPtr must be specified"),r.count={value:1},jA(Object.create(t,{$$:{value:r,writable:!0}}))};function Gt(t){var r=this.getPointee(t);if(!r)return this.destructor(t),null;var s=qt(this.registeredClass,r);if(s!==void 0){if(s.$$.count.value===0)return s.$$.ptr=r,s.$$.smartPtr=t,s.clone();var i=s.clone();return this.destructor(t),i}function o(){return this.isSmartPointer?EA(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:r,smartPtrType:this,smartPtr:t}):EA(this.registeredClass.instancePrototype,{ptrType:this,ptr:t})}var k=this.registeredClass.getActualType(r),a=mr[k];if(!a)return o.call(this);var u;this.isConst?u=a.constPointerType:u=a.pointerType;var d=Fr(r,this.registeredClass,u.registeredClass);return d===null?o.call(this):this.isSmartPointer?EA(u.registeredClass.instancePrototype,{ptrType:u,ptr:d,smartPtrType:this,smartPtr:t}):EA(u.registeredClass.instancePrototype,{ptrType:u,ptr:d})}var pt=()=>{Object.assign(mA.prototype,{getPointee(t){return this.rawGetPointee&&(t=this.rawGetPointee(t)),t},destructor(t){this.rawDestructor?.(t)},readValueFromPointer:GA,fromWireType:Gt})};function mA(t,r,s,i,o,k,a,u,d,f,q){this.name=t,this.registeredClass=r,this.isReference=s,this.isConst=i,this.isSmartPointer=o,this.pointeeType=k,this.sharingPolicy=a,this.rawGetPointee=u,this.rawConstructor=d,this.rawShare=f,this.rawDestructor=q,!o&&r.baseClass===void 0?i?(this.toWireType=kt,this.destructorFunction=null):(this.toWireType=ct,this.destructorFunction=null):this.toWireType=ut}var vr=(t,r,s)=>{j.hasOwnProperty(t)||pA("Replacing nonexistent public symbol"),j[t].overloadTable!==void 0&&s!==void 0?j[t].overloadTable[s]=r:(j[t]=r,j[t].argCount=s)},Ir=[],Et=t=>{var r=Ir[t];return r||(Ir[t]=r=Ur.get(t)),r},O=(t,r,s=!1)=>{t=y(t);function i(){var k=Et(r);return k}var o=i();return typeof o!="function"&&G(\`unknown function pointer with signature \${t}: \${r}\`),o};class mt extends Error{}var ht=t=>{var r=Pr(t),s=y(r);return J(r),s},z=(t,r)=>{var s=[],i={};function o(k){if(!i[k]&&!W[k]){if(uA[k]){uA[k].forEach(o);return}s.push(k),i[k]=!0}}throw r.forEach(o),new mt(\`\${t}: \`+s.map(ht).join([", "]))},w=(t,r,s)=>{t.forEach(u=>uA[u]=r);function i(u){var d=s(u);d.length!==t.length&&pA("Mismatched type converter count");for(var f=0;f<t.length;++f)x(t[f],d[f])}var o=new Array(r.length),k=[],a=0;for(let[u,d]of r.entries())W.hasOwnProperty(d)?o[u]=W[d]:(k.push(d),X.hasOwnProperty(d)||(X[d]=[]),X[d].push(()=>{o[u]=W[d],++a,a===k.length&&i(o)}));k.length===0&&i(o)},$t=(t,r,s,i,o,k,a,u,d,f,q,E,v)=>{q=y(q),k=O(o,k),u&&=O(a,u),f&&=O(d,f),v=O(E,v);var F=ot(q);$r(F,function(){z(\`Cannot construct \${q} due to unbound types\`,[i])}),w([t,r,s],i?[i]:[],h=>{h=h[0];var m,N;i?(m=h.registeredClass,N=m.instancePrototype):N=qA.prototype;var L=Er(q,function(...QA){if(Object.getPrototypeOf(this)!==K)throw new AA(\`Use 'new' to construct \${q}\`);if(H.constructor_body===void 0)throw new AA(\`\${q} has no accessible constructor\`);var Rr=H.constructor_body[QA.length];if(Rr===void 0)throw new AA(\`Tried to invoke ctor of \${q} with invalid number of parameters (\${QA.length}) - expected (\${Object.keys(H.constructor_body).toString()}) parameters instead!\`);return Rr.apply(this,QA)}),K=Object.create(N,{constructor:{value:L}});L.prototype=K;var H=new at(q,L,K,v,m,k,u,f);H.baseClass&&(H.baseClass.__derivedClasses??=[],H.baseClass.__derivedClasses.push(H));var kn=new mA(q,H,!0,!1,!1),Mr=new mA(q+"*",H,!1,!1,!1),Kr=new mA(q+" const*",H,!1,!0,!1);return mr[t]={pointerType:Mr,constPointerType:Kr},vr(F,L),[kn,Mr,Kr]})},MA=(t,r)=>{for(var s=[],i=0;i<t;i++)s.push($[r+i*4>>2]);return s},yr=t=>{for(;t.length;){var r=t.pop(),s=t.pop();s(r)}};function _r(t){for(var r=1;r<t.length;++r)if(t[r]!==null&&t[r].destructorFunction===void 0)return!0;return!1}function Lr(t){for(var r=1;r<t.length;++r)if(t[r]!==null&&t[r].argStackAlloc)return!0;return!1}function Ft(t,r,s,i){var o=_r(t),k=Lr(t),a=k&&!i&&!o;k&&!a&&(o=!0);var u=t.length-2,d=[],f=["fn"];r&&f.push("thisWired");for(var q=0;q<u;++q)d.push(\`arg\${q}\`),f.push(\`arg\${q}Wired\`);d=d.join(),f=f.join();var E=\`return function (\${d}) {
|
|
6710
6710
|
\`;o&&(E+=\`var destructors = [];
|
|
6711
6711
|
\`),a&&(E+=\`var sp = stackSave();
|
|
6712
6712
|
try {
|
|
@@ -6721,5 +6721,5 @@ stackRestore(sp);
|
|
|
6721
6721
|
\`,F.push(\`\${m}_dtor\`))}return s&&(E+=\`var ret = fromRetWire(rv);
|
|
6722
6722
|
return ret;
|
|
6723
6723
|
\`),E+=\`}
|
|
6724
|
-
\`,new Function(F,E)}function KA(t,r,s,i,o,k){var a=r.length;a<2&&G("argTypes array size mismatch! Must at least get return value and receiver (this) types!");var u=r[1]!==null&&s!==null,d=yr(r),f=Lr(r),q=f&&!k&&!d;f&&!q&&(d=!0);var E=!r[0].isVoid,v=r[0],F=r[1],h=[t,G,i,o,_r,v.fromWireType.bind(v),F?.toWireType.bind(F)];q&&h.push(Qj,Vj);for(var m=2;m<a;++m){var N=r[m];h.push(N.toWireType.bind(N))}if(!d)for(var m=u?1:2;m<r.length;++m)r[m].destructorFunction!==null&&h.push(r[m].destructorFunction);var K=Ft(r,u,E,k)(...h);return Er(t,K)}var vt=(t,r,s,i,o,k)=>{var a=MA(r,s);o=O(i,o),w([],[t],u=>{u=u[0];var d=\`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]=()=>{W(\`Cannot construct \${u.name} due to unbound types\`,a)},w([],a,f=>(f.splice(1,0,null),u.registeredClass.constructor_body[r-1]=KA(d,f,null,o,k),[])),[]})},Hr=t=>{t=t.trim();let r=t.indexOf("(");return r===-1?t:t.slice(0,r)},It=(t,r,s,i,o,k,a,u,d,f)=>{var q=MA(s,i);r=_(r),r=Hr(r),k=O(o,k,d),w([],[t],E=>{E=E[0];var v=\`\${E.name}.\${r}\`;r.startsWith("@@")&&(r=Symbol[r.substring(2)]),u&&E.registeredClass.pureVirtualFunctions.push(r);function F(){W(\`Cannot call \${v} due to unbound types\`,q)}var h=E.registeredClass.instancePrototype,m=h[r];return m===void 0||m.overloadTable===void 0&&m.className!==E.name&&m.argCount===s-2?(F.argCount=s-2,F.className=E.name,h[r]=F):(hr(h,r,v),h[r].overloadTable[s-2]=F),w([],q,N=>{var L=KA(v,N,E,k,a,d);return h[r].overloadTable===void 0?(L.argCount=s-2,h[r]=L):h[r].overloadTable[s-2]=L,[]}),[]})},gr=(t,r,s)=>(t instanceof Object||G(\`\${s} with invalid "this": \${t}\`),t instanceof r.registeredClass.constructor||G(\`\${s} incompatible with "this" of type \${t.constructor.name}\`),t.$$.ptr||G(\`cannot call emscripten binding method \${s} on deleted object\`),fA(t.$$.ptr,t.$$.ptrType.registeredClass,r.registeredClass)),_t=(t,r,s,i,o,k,a,u,d,f)=>{r=_(r),o=O(i,o),w([],[t],q=>{q=q[0];var E=\`\${q.name}.\${r}\`,v={get(){W(\`Cannot access \${E} due to unbound types\`,[s,a])},enumerable:!0,configurable:!0};return d?v.set=()=>W(\`Cannot access \${E} due to unbound types\`,[s,a]):v.set=F=>G(E+" is a read-only property"),Object.defineProperty(q.registeredClass.instancePrototype,r,v),w([],d?[s,a]:[s],F=>{var h=F[0],m={get(){var L=gr(this,q,E+" getter");return h.fromWireType(o(k,L))},enumerable:!0};if(d){d=O(u,d);var N=F[1];m.set=function(L){var K=gr(this,q,E+" setter"),H=[];d(f,K,N.toWireType(H,L)),_r(H)}}return Object.defineProperty(q.registeredClass.instancePrototype,r,m),[]}),[]})},Dr=[],M=[0,1,,1,null,1,!0,1,!1,1],yt=t=>{if(t>9&&--M[t+1]===0){var r=M[t];M[t]=void 0,Dr.push(t)}},RA={toValue:t=>(t||G(\`Cannot use deleted val. handle = \${t}\`),M[t]),toHandle:t=>{switch(t){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:{let r=Dr.pop()||M.length;return M[r]=t,M[r+1]=1,r}}}},Lt={name:"emscripten::val",fromWireType:t=>{var r=RA.toValue(t);return yt(t),r},toWireType:(t,r)=>RA.toHandle(r),readValueFromPointer:GA,destructorFunction:null},Ht=t=>x(t,Lt),Br,xr,gt=(t,r)=>{switch(r){case 4:return function(s){return this.fromWireType(Br[s>>2])};case 8:return function(s){return this.fromWireType(xr[s>>3])};default:throw new TypeError(\`invalid float width (\${r}): \${t}\`)}},Dt=(t,r,s)=>{r=_(r),x(t,{name:r,fromWireType:i=>i,toWireType:(i,o)=>o,readValueFromPointer:gt(r,s),destructorFunction:null})},Bt=(t,r,s,i,o,k,a,u)=>{var d=MA(r,s);t=_(t),t=Hr(t),o=O(i,o,a),$r(t,function(){W(\`Cannot call \${t} due to unbound types\`,d)},r-1),w([],d,f=>{var q=[f[0],null].concat(f.slice(1));return vr(t,KA(t,q,null,o,k,a),r-1),[]})},xt=(t,r,s,i,o)=>{r=_(r);let k=i===0,a=d=>d;if(k){var u=32-8*s;a=d=>d<<u>>>u,o=a(o)}x(t,{name:r,fromWireType:a,toWireType:(d,f)=>f,readValueFromPointer:qr(r,s,i!==0),destructorFunction:null})},Nt=(t,r,s)=>{var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=i[r];function k(a){var u=$[a>>2],d=$[a+4>>2];return new o(U.buffer,d,u)}s=_(s),x(t,{name:s,fromWireType:k,readValueFromPointer:k},{ignoreDuplicateRegistrations:!0})},bt=(t,r,s,i)=>{if(!(i>0))return 0;for(var o=s,k=s+i-1,a=0;a<t.length;++a){var u=t.codePointAt(a);if(u<=127){if(s>=k)break;r[s++]=u}else if(u<=2047){if(s+1>=k)break;r[s++]=192|u>>6,r[s++]=128|u&63}else if(u<=65535){if(s+2>=k)break;r[s++]=224|u>>12,r[s++]=128|u>>6&63,r[s++]=128|u&63}else{if(s+3>=k)break;r[s++]=240|u>>18,r[s++]=128|u>>12&63,r[s++]=128|u>>6&63,r[s++]=128|u&63,a++}}return r[s]=0,s-o},Ot=(t,r,s)=>bt(t,g,r,s),Jt=t=>{for(var r=0,s=0;s<t.length;++s){var i=t.charCodeAt(s);i<=127?r++:i<=2047?r+=2:i>=55296&&i<=57343?(r+=4,++s):r+=3}return r},Nr=globalThis.TextDecoder&&new TextDecoder,br=(t,r,s,i)=>{var o=r+s;if(i)return o;for(;t[r]&&!(r>=o);)++r;return r},Or=(t,r=0,s,i)=>{var o=br(t,r,s,i);if(o-r>16&&t.buffer&&Nr)return Nr.decode(t.subarray(r,o));for(var k="";r<o;){var a=t[r++];if(!(a&128)){k+=String.fromCharCode(a);continue}var u=t[r++]&63;if((a&224)==192){k+=String.fromCharCode((a&31)<<6|u);continue}var d=t[r++]&63;if((a&240)==224?a=(a&15)<<12|u<<6|d:a=(a&7)<<18|u<<12|d<<6|t[r++]&63,a<65536)k+=String.fromCharCode(a);else{var f=a-65536;k+=String.fromCharCode(55296|f>>10,56320|f&1023)}}return k},Pt=(t,r,s)=>t?Or(g,t,r,s):"",wt=(t,r)=>{r=_(r);var s=!0;x(t,{name:r,fromWireType(i){var o=$[i>>2],k=i+4,a;if(s)a=Pt(k,o,!0);else{a="";for(var u=0;u<o;++u)a+=String.fromCharCode(g[k+u])}return J(i),a},toWireType(i,o){o instanceof ArrayBuffer&&(o=new Uint8Array(o));var k,a=typeof o=="string";a||ArrayBuffer.isView(o)&&o.BYTES_PER_ELEMENT==1||G("Cannot pass non-string to std::string"),s&&a?k=Jt(o):k=o.length;var u=VA(4+k+1),d=u+4;if($[u>>2]=k,a)if(s)Ot(o,d,k+1);else for(var f=0;f<k;++f){var q=o.charCodeAt(f);q>255&&(J(u),G("String has UTF-16 code units that do not fit in 8 bits")),g[d+f]=q}else g.set(o,d);return i!==null&&i.push(J,u),u},readValueFromPointer:GA,destructorFunction(i){J(i)}})},Jr=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Tt=(t,r,s)=>{var i=t>>1,o=br(rA,i,r/2,s);if(o-i>16&&Jr)return Jr.decode(rA.subarray(i,o));for(var k="",a=i;a<o;++a){var u=rA[a];k+=String.fromCharCode(u)}return k},St=(t,r,s=2147483647)=>{if(s<2)return 0;s-=2;for(var i=r,o=s<t.length*2?s/2:t.length,k=0;k<o;++k){var a=t.charCodeAt(k);cA[r>>1]=a,r+=2}return cA[r>>1]=0,r-i},Ut=t=>t.length*2,Mt=(t,r,s)=>{for(var i="",o=t>>2,k=0;!(k>=r/4);k++){var a=$[o+k];if(!a&&!s)break;i+=String.fromCodePoint(a)}return i},Kt=(t,r,s=2147483647)=>{if(s<4)return 0;for(var i=r,o=i+s-4,k=0;k<t.length;++k){var a=t.codePointAt(k);if(a>65535&&k++,dA[r>>2]=a,r+=4,r+4>o)break}return dA[r>>2]=0,r-i},Rt=t=>{for(var r=0,s=0;s<t.length;++s){var i=t.codePointAt(s);i>65535&&s++,r+=4}return r},Vt=(t,r,s)=>{s=_(s);var i,o,k;r===2?(i=Tt,o=St,k=Ut):(i=Mt,o=Kt,k=Rt),x(t,{name:s,fromWireType:a=>{var u=$[a>>2],d=i(a+4,u*r,!0);return J(a),d},toWireType:(a,u)=>{typeof u!="string"&&G(\`Cannot pass non-string to C++ string type \${s}\`);var d=k(u),f=VA(4+d+r);return $[f>>2]=d/r,o(u,f+4,d+r),a!==null&&a.push(J,f),f},readValueFromPointer:GA,destructorFunction(a){J(a)}})},Qt=(t,r)=>{r=_(r),x(t,{isVoid:!0,name:r,fromWireType:()=>{},toWireType:(s,i)=>{}})},Xt=t=>{kA("OOM")},zt=t=>{var r=g.length;t>>>=0,Xt(t)},Wt=t=>52,Zt=9007199254740992,Yt=-9007199254740992,An=t=>t<Yt||t>Zt?NaN:Number(t);function rn(t,r,s,i){return r=An(r),70}var jn=[null,[],[]],tn=(t,r)=>{var s=jn[t];!r||r===10?((t===1?b:aA)(Or(s)),s.length=0):s.push(r)},nn=(t,r,s,i)=>{for(var o=0,k=0;k<s;k++){var a=$[r>>2],u=$[r+4>>2];r+=8;for(var d=0;d<u;d++)tn(t,g[a+d]);o+=u}return $[i>>2]=o,0};st(),pt();{j.noExitRuntime&&(Rj=j.noExitRuntime),j.print&&(b=j.print),j.printErr&&(aA=j.printErr),j.arguments&&(C=j.arguments),j.thisProgram&&(p=j.thisProgram);var Z=j.preInit;if(Z)for(typeof Z=="function"&&(j.preInit=Z=[Z]);Z.length>0;)Z.shift()()}var Pr,VA,J,wr,Tr,en,sn,Sr,Ur;function ln(t){Pr=t.w,VA=j._malloc=t.y,J=j._free=t.z,wr=t.A,Tr=t.B,en=Sr=t.u,sn=Ur=t.x}var on={i:Zj,r:Yj,g:rt,l:jt,k:$t,j:vt,d:It,a:_t,s:Ht,f:Dt,n:Bt,c:xt,b:Nt,t:wt,e:Vt,m:Qt,o:zt,q:Wt,p:rn,h:nn};async function an(){Oj();var t=j.setStatus;t&&(t("Running..."),await new Promise(r=>setTimeout(r,1)),setTimeout(t,1,"")),!or&&(Jj(),j.onRuntimeInitialized?.(),Pj())}var tA;return tA=await Kj(),await an(),j}})();typeof Ij=="object"&&typeof PA=="object"?(PA.exports=er,PA.exports.default=er):typeof define=="function"&&define.amd&&define([],()=>er)});var T={};Gn(T,{AdditionalCaptureBlocks:()=>hn,AdditionalPlaybackBlocks:()=>mn,ClockJumpCheckInterval:()=>Ln,ClockJumpThreshold:()=>Hn,ConnectInterval:()=>wn,ConnectTimeout:()=>On,DefaultRefreshRate:()=>Fn,DefaultVideoCodec:()=>Sn,HealthCheckTimeout:()=>yn,MainConnectionPingInterval:()=>gn,MaxNumberOfDecoders:()=>In,MaxReconnectDuration:()=>Tn,MinDBFs:()=>Vr,MinTokenLifetime:()=>Jn,MinTokenRefreshInterval:()=>Pn,PlaybackPreload:()=>$n,RenderQuantumSize:()=>_n,VadPreload:()=>vn,WebRtcAnswerTimeout:()=>Nn,WebRtcIceTimeout:()=>Bn,WebRtcMaxNegotiationAttempts:()=>bn,WebRtcStatsSnapshotInterval:()=>Dn,WebRtcTimeout:()=>xn});var mn=3,hn=3,$n=3,Fn=250,vn=3,In=512,_n=128,Vr=-758.596,yn=1e4,Ln=1e3,Hn=1e4,gn=3e3,Dn=1e3,Bn=3e3,xn=1e4,Nn=1e4,bn=3,On=5e3,Jn=6e4,Pn=5e3,wn=[0,100,200,200,500],Tn=12e4,Sn="H264";function S(n,A,j){return n.postMessage(A,j)}function Qr(n){return[n.values[0],n.values[1]]}function hA(n,A){n.values[0]=A[0],n.values[1]=A[1]}function $A(n,A){return n.values[2+A*5]}function Xr(n,A,j){n.values[2+A*5]=j}function zr(n,A){let j=2+A*5+1;return[n.values[j+0],n.values[j+1]]}function FA(n,A,j){let e=2+A*5+1;n.values[e+0]=j[0],n.values[e+1]=j[1]}function Wr(n,A){return n.values[2+A*5+3]}function Zr(n,A,j){n.values[2+A*5+3]=j}function Yr(n,A){return n.values[2+A*5+4]}function Aj(n,A,j){n.values[2+A*5+4]=j}function vA(n){return n.values[0]!==0}function IA(n){return n.values[1]}function _A(n){return n.values[2]}function rj(n){return n.values[3]}function yA(n,A){return n.values[3]=A}function jj(n){return n?Array.from(n).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var Un;(n=>{let A;(j=>(j[j.InvalidPassword=-1]="InvalidPassword",j[j.Unknown=0]="Unknown",j[j.Unencrypted=1]="Unencrypted",j[j.Encrypted=2]="Encrypted"))(A=n.PeerCipherStatus||={})})(Un||={});function lj(n){return{type:"Success",value:n}}function D(n){return{type:"Failure",reason:n}}var{Deno:tj}=globalThis,Mn=typeof tj?.noColor=="boolean"?tj.noColor:!1,Kn=!Mn;function WA(n,A){return{open:\`\\x1B[\${n.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function ZA(n,A){return Kn?\`\${A.open}\${n.replace(A.regexp,A.open)}\${A.close}\`:n}function zA(n){return ZA(n,WA([0],0))}function nj(n){return ZA(n,WA([1],22))}function Rn(n){return ZA(n,WA([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"),Vn=new Date,LA=(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))(LA||{}),ij={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},Qn={4:Rn,3:zA,2:zA,1:nj,0:nj};function Xn({message:n}){return String(n)}function ej(n){return JSON.stringify({timestamp:n.date.toISOString(),level:LA[n.level],message:n.message,extra:n.extra})}function sj(n){function A(C,p){return[Math.floor(C/p),C%p]}function j(){let C,p=n.date.valueOf()-Vn.valueOf();[p,C]=A(p,1e3);let[I,B]=A(p,60);return\`\${I.toString().padStart(4,"0")}:\${B.toString().padStart(2,"0")}.\${C.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 l=ij[n.level],c=n.logger.name!==void 0?\`@\${n.logger.name}\`:"";return\`\${zA(j())}\${c} \${l} \${Qn[n.level](String(n.message))}\${e()}\`}function zn(n){let A=\`[\${n.date.toISOString()}]\`,j=\`[\${LA[n.level]}]\`,e=n.logger.name!==void 0?\`[\${n.logger.name}] \`:"",l=ij[n.level];return\`\${A} \${l} \${j.padEnd(7," ")} \${e}\${n.message}\`}function Wn(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var oj=class{static sparse=Xn;static json=ej;static pretty=sj;static structured=zn;static default=Wn()?sj:ej;constructor(){}};var Zn=class{formatter;consoleObject;filter;constructor(n=oj.default,A=4,j=console){this.filter=A,this.formatter=n,this.consoleObject=j}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,j=[],e=void 0){this.#A=A,this.sinks=j,this.filter=n,this.parent=e}log(n,A,j=void 0){let e={date:new Date,level:n,logger:this,message:A,extra:j};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=globalThis[Symbol.for("odin-global-logger")]??=new R(3,void 0,[new Zn]),Yn=R.prototype.log.bind(nA,1),Ae=R.prototype.log.bind(nA,2),aj=R.prototype.log.bind(nA,3),re=R.prototype.log.bind(nA,4),Se=R.prototype.log.bind(nA);var kj;function uj(n,...A){let j=je(A);kj?kj?.info(n,j):aj(n,j)}function je(...n){if(n.length===1&&typeof n[0]=="object"&&n[0]!==null)return{...n[0]};if(n.length>0)return{args:n}}function HA(n){return n.connectionId*4294967296+n.mediaId}function cj(n){return{mediaId:n%4294967296,connectionId:Math.floor(n/4294967296)}}function P(n,A,j){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 l=n._malloc(j*e.BYTES_PER_ELEMENT);if(l===0||l%e.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${j} \${A} array\`);let c=l/e.BYTES_PER_ELEMENT;return e.subarray(c,c+j)}function V(n,A){n._free(A.byteOffset)}function dj(n,A){return{values:P(n,"f32",2+A*5),length:A}}function Cj(n,A){V(n,A.values)}function qj(n){return{values:P(n,"f32",4)}}function fj(n,A){V(n,A.values)}function Gj(n){let A=n.length,j=0,e=0;for(;e<A;){let l=n.charCodeAt(e++);if((l&4294967168)===0){j++;continue}else if((l&4294965248)===0)j+=2;else{if(l>=55296&&l<=56319&&e<A){let c=n.charCodeAt(e);(c&64512)===56320&&(++e,l=((l&1023)<<10)+(c&1023)+65536)}(l&4294901760)===0?j+=3:j+=4}}return j}function te(n,A,j){let e=n.length,l=j,c=0;for(;c<e;){let C=n.charCodeAt(c++);if((C&4294967168)===0){A[l++]=C;continue}else if((C&4294965248)===0)A[l++]=C>>6&31|192;else{if(C>=55296&&C<=56319&&c<e){let p=n.charCodeAt(c);(p&64512)===56320&&(++c,C=((C&1023)<<10)+(p&1023)+65536)}(C&4294901760)===0?(A[l++]=C>>12&15|224,A[l++]=C>>6&63|128):(A[l++]=C>>18&7|240,A[l++]=C>>12&63|128,A[l++]=C>>6&63|128)}A[l++]=C&63|128}}var ne=new TextEncoder,ee=50;function se(n,A,j){ne.encodeInto(n,A.subarray(j))}function pj(n,A,j){n.length>ee?se(n,A,j):te(n,A,j)}var le=4096;function YA(n,A,j){let e=A,l=e+j,c=[],C="";for(;e<l;){let p=n[e++];if((p&128)===0)c.push(p);else if((p&224)===192){let I=n[e++]&63;c.push((p&31)<<6|I)}else if((p&240)===224){let I=n[e++]&63,B=n[e++]&63;c.push((p&31)<<12|I<<6|B)}else if((p&248)===240){let I=n[e++]&63,B=n[e++]&63,wA=n[e++]&63,b=(p&7)<<18|I<<12|B<<6|wA;b>65535&&(b-=65536,c.push(b>>>10&1023|55296),b=56320|b&1023),c.push(b)}else c.push(p);c.length>=le&&(C+=String.fromCharCode(...c),c.length=0)}return c.length>0&&(C+=String.fromCharCode(...c)),C}var ie=new TextDecoder,oe=200;function ae(n,A,j){let e=n.subarray(A,A+j);return ie.decode(e)}function Ej(n,A,j){return j>oe?ae(n,A,j):YA(n,A,j)}var Q=class{type;data;constructor(A,j){this.type=A,this.data=j}};var y=class n extends Error{constructor(A){super(A);let j=Object.create(n.prototype);Object.setPrototypeOf(this,j),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:n.name})}};function mj(n,A,j){let e=j/4294967296,l=j;n.setUint32(A,e),n.setUint32(A+4,l)}function gA(n,A,j){let e=Math.floor(j/4294967296),l=j;n.setUint32(A,e),n.setUint32(A+4,l)}function DA(n,A){let j=n.getInt32(A),e=n.getUint32(A+4);return j*4294967296+e}function hj(n,A){let j=n.getUint32(A),e=n.getUint32(A+4);return j*4294967296+e}var ke=-1,ue=4294967296-1,ce=17179869184-1;function de({sec:n,nsec:A}){if(n>=0&&A>=0&&n<=ce)if(A===0&&n<=ue){let j=new Uint8Array(4);return new DataView(j.buffer).setUint32(0,n),j}else{let j=n/4294967296,e=n&4294967295,l=new Uint8Array(8),c=new DataView(l.buffer);return c.setUint32(0,A<<2|j&3),c.setUint32(4,e),l}else{let j=new Uint8Array(12),e=new DataView(j.buffer);return e.setUint32(0,A),gA(e,4,n),j}}function Ce(n){let A=n.getTime(),j=Math.floor(A/1e3),e=(A-j*1e3)*1e6,l=Math.floor(e/1e9);return{sec:j+l,nsec:e-l*1e9}}function qe(n){if(n instanceof Date){let A=Ce(n);return de(A)}else return null}function fe(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 j=A.getUint32(0),e=A.getUint32(4),l=(j&3)*4294967296+e,c=j>>>2;return{sec:l,nsec:c}}case 12:{let j=DA(A,4),e=A.getUint32(0);return{sec:j,nsec:e}}default:throw new y(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${n.length}\`)}}function Ge(n){let A=fe(n);return new Date(A.sec*1e3+A.nsec/1e6)}var $j={type:ke,encode:qe,decode:Ge};var Y=class n{static defaultCodec=new n;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register($j)}register({type:A,encode:j,decode:e}){if(A>=0)this.encoders[A]=j,this.decoders[A]=e;else{let l=-1-A;this.builtInEncoders[l]=j,this.builtInDecoders[l]=e}}tryToEncode(A,j){for(let e=0;e<this.builtInEncoders.length;e++){let l=this.builtInEncoders[e];if(l!=null){let c=l(A,j);if(c!=null){let C=-1-e;return new Q(C,c)}}}for(let e=0;e<this.encoders.length;e++){let l=this.encoders[e];if(l!=null){let c=l(A,j);if(c!=null){let C=e;return new Q(C,c)}}}return A instanceof Q?A:null}decode(A,j,e){let l=j<0?this.builtInDecoders[-1-j]:this.decoders[j];return l?l(A,j,e):new Q(j,A)}};function pe(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function eA(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):pe(n)?new Uint8Array(n):Uint8Array.from(n)}var Ee=100,me=2048,BA=class n{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(A){this.extensionCodec=A?.extensionCodec??Y.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??Ee,this.initialBufferSize=A?.initialBufferSize??me,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,j){if(j>this.maxDepth)throw new Error(\`Too deep objects in depth \${j}\`);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,j)}ensureBufferSizeToWrite(A){let j=this.pos+A;this.view.byteLength<j&&this.resizeBuffer(j*2)}resizeBuffer(A){let j=new ArrayBuffer(A),e=new Uint8Array(j),l=new DataView(j);e.set(this.bytes),this.view=l,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=Gj(A);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),pj(A,this.bytes,this.pos),this.pos+=e}encodeObject(A,j){let e=this.extensionCodec.tryToEncode(A,this.context);if(e!=null)this.encodeExtension(e);else if(Array.isArray(A))this.encodeArray(A,j);else if(ArrayBuffer.isView(A))this.encodeBinary(A);else if(typeof A=="object")this.encodeMap(A,j);else throw new Error(\`Unrecognized object: \${Object.prototype.toString.apply(A)}\`)}encodeBinary(A){let j=A.byteLength;if(j<256)this.writeU8(196),this.writeU8(j);else if(j<65536)this.writeU8(197),this.writeU16(j);else if(j<4294967296)this.writeU8(198),this.writeU32(j);else throw new Error(\`Too large binary: \${j}\`);let e=eA(A);this.writeU8a(e)}encodeArray(A,j){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 l of A)this.doEncode(l,j+1)}countWithoutUndefined(A,j){let e=0;for(let l of j)A[l]!==void 0&&e++;return e}encodeMap(A,j){let e=Object.keys(A);this.sortKeys&&e.sort();let l=this.ignoreUndefined?this.countWithoutUndefined(A,e):e.length;if(l<16)this.writeU8(128+l);else if(l<65536)this.writeU8(222),this.writeU16(l);else if(l<4294967296)this.writeU8(223),this.writeU32(l);else throw new Error(\`Too large map object: \${l}\`);for(let c of e){let C=A[c];this.ignoreUndefined&&C===void 0||(this.encodeString(c),this.doEncode(C,j+1))}}encodeExtension(A){if(typeof A.data=="function"){let e=A.data(this.pos+6),l=e.length;if(l>=4294967296)throw new Error(\`Too large extension object: \${l}\`);this.writeU8(201),this.writeU32(l),this.writeI8(A.type),this.writeU8a(e);return}let j=A.data.length;if(j===1)this.writeU8(212);else if(j===2)this.writeU8(213);else if(j===4)this.writeU8(214);else if(j===8)this.writeU8(215);else if(j===16)this.writeU8(216);else if(j<256)this.writeU8(199),this.writeU8(j);else if(j<65536)this.writeU8(200),this.writeU16(j);else if(j<4294967296)this.writeU8(201),this.writeU32(j);else throw new Error(\`Too large extension object: \${j}\`);this.writeI8(A.type),this.writeU8a(A.data)}writeU8(A){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,A),this.pos++}writeU8a(A){let j=A.length;this.ensureBufferSizeToWrite(j),this.bytes.set(A,this.pos),this.pos+=j}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),mj(this.view,this.pos,A),this.pos+=8}writeI64(A){this.ensureBufferSizeToWrite(8),gA(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 Ar(n,A){return new BA(A).encodeSharedRef(n)}function xA(n){return\`\${n<0?"-":""}0x\${Math.abs(n).toString(16).padStart(2,"0")}\`}var he=16,$e=16,NA=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(A=he,j=$e){this.maxKeyLength=A,this.maxLengthPerKey=j,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,j,e){let l=this.caches[e-1];A:for(let c of l){let C=c.bytes;for(let p=0;p<e;p++)if(C[p]!==A[j+p])continue A;return c.str}return null}store(A,j){let e=this.caches[A.length-1],l={bytes:A,str:j};e.length>=this.maxLengthPerKey?e[Math.random()*e.length|0]=l:e.push(l)}decode(A,j,e){let l=this.find(A,j,e);if(l!=null)return this.hit++,l;this.miss++;let c=YA(A,j,e),C=Uint8Array.prototype.slice.call(A,j,j+e);return this.store(C,c),c}};var rr="array",iA="map_key",vj="map_value",Fe=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new y("The type of key must be string or number but "+typeof n)},jr=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let j=this.getUninitializedStateFromPool();j.type=rr,j.position=0,j.size=A,j.array=new Array(A)}pushMapState(A){let j=this.getUninitializedStateFromPool();j.type=iA,j.readCount=0,j.size=A,j.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===rr){let e=A;e.size=0,e.array=void 0,e.position=0,e.type=void 0}if(A.type===iA||A.type===vj){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,tr=new DataView(new ArrayBuffer(0)),ve=new Uint8Array(tr.buffer);try{tr.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 Fj=new RangeError("Insufficient data"),Ie=new NA,bA=class n{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=tr;bytes=ve;headByte=lA;stack=new jr;entered=!1;constructor(A){this.extensionCodec=A?.extensionCodec??Y.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:Ie,this.mapKeyConverter=A?.mapKeyConverter??Fe}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 j=eA(A);this.bytes=j,this.view=new DataView(j.buffer,j.byteOffset,j.byteLength),this.pos=0}appendBuffer(A){if(this.headByte===lA&&!this.hasRemaining(1))this.setBuffer(A);else{let j=this.bytes.subarray(this.pos),e=eA(A),l=new Uint8Array(j.length+e.length);l.set(j),l.set(e,j.length),this.setBuffer(l)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:j,pos:e}=this;return new RangeError(\`Extra \${j.byteLength-e} of \${j.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 j=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return j}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 j=!1,e;for await(let p of A){if(j)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(p);try{e=this.doDecodeSync(),j=!0}catch(I){if(!(I instanceof RangeError))throw I}this.totalPos+=this.pos}if(j){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return e}let{headByte:l,pos:c,totalPos:C}=this;throw new RangeError(\`Insufficient data in parsing \${xA(l)} at \${C} (\${c} 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,j){if(this.entered){yield*this.clone().decodeMultiAsync(A,j);return}try{this.entered=!0;let e=j,l=-1;for await(let c of A){if(j&&l===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c),e&&(l=this.readArraySize(),e=!1,this.complete());try{for(;yield this.doDecodeSync(),--l!==0;);}catch(C){if(!(C instanceof RangeError))throw C}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){A:for(;;){let A=this.readHeadByte(),j;if(A>=224)j=A-256;else if(A<192)if(A<128)j=A;else if(A<144){let l=A-128;if(l!==0){this.pushMapState(l),this.complete();continue A}else j={}}else if(A<160){let l=A-144;if(l!==0){this.pushArrayState(l),this.complete();continue A}else j=[]}else{let l=A-160;j=this.decodeString(l,0)}else if(A===192)j=null;else if(A===194)j=!1;else if(A===195)j=!0;else if(A===202)j=this.readF32();else if(A===203)j=this.readF64();else if(A===204)j=this.readU8();else if(A===205)j=this.readU16();else if(A===206)j=this.readU32();else if(A===207)this.useBigInt64?j=this.readU64AsBigInt():j=this.readU64();else if(A===208)j=this.readI8();else if(A===209)j=this.readI16();else if(A===210)j=this.readI32();else if(A===211)this.useBigInt64?j=this.readI64AsBigInt():j=this.readI64();else if(A===217){let l=this.lookU8();j=this.decodeString(l,1)}else if(A===218){let l=this.lookU16();j=this.decodeString(l,2)}else if(A===219){let l=this.lookU32();j=this.decodeString(l,4)}else if(A===220){let l=this.readU16();if(l!==0){this.pushArrayState(l),this.complete();continue A}else j=[]}else if(A===221){let l=this.readU32();if(l!==0){this.pushArrayState(l),this.complete();continue A}else j=[]}else if(A===222){let l=this.readU16();if(l!==0){this.pushMapState(l),this.complete();continue A}else j={}}else if(A===223){let l=this.readU32();if(l!==0){this.pushMapState(l),this.complete();continue A}else j={}}else if(A===196){let l=this.lookU8();j=this.decodeBinary(l,1)}else if(A===197){let l=this.lookU16();j=this.decodeBinary(l,2)}else if(A===198){let l=this.lookU32();j=this.decodeBinary(l,4)}else if(A===212)j=this.decodeExtension(1,0);else if(A===213)j=this.decodeExtension(2,0);else if(A===214)j=this.decodeExtension(4,0);else if(A===215)j=this.decodeExtension(8,0);else if(A===216)j=this.decodeExtension(16,0);else if(A===199){let l=this.lookU8();j=this.decodeExtension(l,1)}else if(A===200){let l=this.lookU16();j=this.decodeExtension(l,2)}else if(A===201){let l=this.lookU32();j=this.decodeExtension(l,4)}else throw new y(\`Unrecognized type byte: \${xA(A)}\`);this.complete();let e=this.stack;for(;e.length>0;){let l=e.top();if(l.type===rr)if(l.array[l.position]=j,l.position++,l.position===l.size)j=l.array,e.release(l);else continue A;else if(l.type===iA){if(j==="__proto__")throw new y("The key __proto__ is not allowed");l.key=this.mapKeyConverter(j),l.type=vj;continue A}else if(l.map[l.key]=j,l.readCount++,l.readCount===l.size)j=l.map,e.release(l);else{l.key=null,l.type=iA;continue A}}return j}}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 y(\`Unrecognized array type byte: \${xA(A)}\`)}}}pushMapState(A){if(A>this.maxMapLength)throw new y(\`Max length exceeded: map length (\${A}) > maxMapLengthLength (\${this.maxMapLength})\`);this.stack.pushMapState(A)}pushArrayState(A){if(A>this.maxArrayLength)throw new y(\`Max length exceeded: array length (\${A}) > maxArrayLength (\${this.maxArrayLength})\`);this.stack.pushArrayState(A)}decodeString(A,j){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(A,j):this.decodeBinary(A,j)}decodeUtf8String(A,j){if(A>this.maxStrLength)throw new y(\`Max length exceeded: UTF-8 byte length (\${A}) > maxStrLength (\${this.maxStrLength})\`);if(this.bytes.byteLength<this.pos+j+A)throw Fj;let e=this.pos+j,l;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?l=this.keyDecoder.decode(this.bytes,e,A):l=Ej(this.bytes,e,A),this.pos+=j+A,l}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===iA:!1}decodeBinary(A,j){if(A>this.maxBinLength)throw new y(\`Max length exceeded: bin length (\${A}) > maxBinLength (\${this.maxBinLength})\`);if(!this.hasRemaining(A+j))throw Fj;let e=this.pos+j,l=this.bytes.subarray(e,e+A);return this.pos+=j+A,l}decodeExtension(A,j){if(A>this.maxExtLength)throw new y(\`Max length exceeded: ext length (\${A}) > maxExtLength (\${this.maxExtLength})\`);let e=this.view.getInt8(this.pos+j),l=this.decodeBinary(A,j+1);return this.extensionCodec.decode(l,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=hj(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 oA=class n{constructor(A,j,e,l,c){this.mediaIds=A;this.sequenceNumber=j;this.timeStamp=e;this.isEndOfSpurt=l;this.payload=c}static parse(A){let j;try{j=nr(A)}catch{return D("not valid msgpack")}if(!Array.isArray(j))return D("container must be an array");if(j.length<6)return D("missing fields");if(j[0]!==1)return D("unknown type");if(!Array.isArray(j[1]))return D("media ids must be an array");if(!j[1].every(B=>typeof B=="number"))return D("media ids must be numbers");if(typeof j[2]!="number")return D("sequence number must be a number");if(typeof j[3]!="number")return D("timestamp must be a number");if(typeof j[4]!="number")return D("flags must be a number");let e=j[1],l=j[2]>>>0,c=j[3]>>>0,p=(j[4]&1)!==0,I=j[j.length-1];return I instanceof Uint8Array?lj(new n(e,l,c,p,I)):D("payload must be bytes")}toBytes(){let A=Number(this.isEndOfSpurt),j=[1,this.mediaIds,this.sequenceNumber>>>0,this.timeStamp>>>0,A,this.payload];return new Uint8Array(Ar(j,{forceFloat32:!0,ignoreUndefined:!0}))}};var OA=class{constructor(A,j){this.sampleRate=A;this.wasm=j;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 j.Encoder(A,15,!0,T.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=qj(this.wasm),this.outBuffer=P(this.wasm,"u8",1270),yA(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:j})=>j.length>0)}close(){fj(this.wasm,this.information),V(this.wasm,this.outBuffer),this.encoder.delete()}encode(A){for(this.encoder.push(A.byteOffset,this.information.values.byteOffset);;){let j=this.encoder.pop(this.connections.length===0?0:this.outBuffer.byteOffset,this.outBuffer.length);if(j===0)break;if(j<0){uj(\`failed encoding packet: \${j}\`);return}if(this.timestamp=this.timestamp+1800>>0,j===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(l=>l.id===0);for(let l of this.connections){if(this.monitoring&&l.id!==0)continue;let c=new oA(l.mediaIds,this.sequenceNumber,this.timestamp,e,this.outBuffer.subarray(0,j));S(globalThis,["sendPacket",{connectionId:l.id,packet:c.toBytes()}])}}}onMessage(A){let[j,e]=A;switch(j){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:vA(this.information),speechProbability:IA(this.information),rmsDBFS:_A(this.information),volume:rj(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}}}},JA=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=P(this.wasm,"u32",T.MaxNumberOfDecoders),this.information=dj(this.wasm,T.MaxNumberOfDecoders),hA(this.information,[1,1])}close(){Cj(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,j){this.stats.numberPackets++;let e=oA.parse(j);if(e.type==="Failure"){this.stats.numberPacketError++;let l=Array.from(j).map(c=>c.toString(16).padStart(2,"0")).join("");console.error(\`failed decoding audio packet; reason: \${e.reason}, connection: \${A}, dump: \${l}\`);return}for(let l of e.value.mediaIds){let c=this.medias.get(HA({connectionId:A,mediaId:l}));if(c===void 0){this.stats.numberPacketsMediaNotFound++;continue}c.lastPacket=j;let C=P(this.wasm,"u8",e.value.payload.length);C.set(e.value.payload),c.decoder.push(e.value.sequenceNumber,e.value.timeStamp,e.value.isEndOfSpurt,C.byteOffset,C.length)}}insertMedia(A,j,e,l=[1,1]){let c=HA({connectionId:j,mediaId:e}),C=new this.wasm.Decoder;this.medias.set(c,{index:A,decoder:C,lastPacket:void 0}),this.decoders[A]=C.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),FA(this.information,A,l),Aj(this.information,A,0),Zr(this.information,A,0)}removeMedia(A,j,e){let l=HA({connectionId:j,mediaId:e}),c=this.medias.get(l);if(!(c===void 0||c.index!==A)&&(this.medias.delete(l),Xr(this.information,A,0),this.decoders[A]=0,c.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[j,e]=A;switch(j){case"playbackReceivePacket":this.receivePacket(e.connectionId,e.packet);break;case"playbackUpdateMedias":for(let{index:l,connectionId:c,mediaId:C}of e.removed)this.removeMedia(l,c,C);for(let{index:l,connectionId:c,mediaId:C,volume:p}of e.added)this.insertMedia(l,c,C,p);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){let A=[];for(let[j,e]of this.medias){let l=cj(j);A.push({index:e.index,connectionId:l.connectionId,mediaId:l.mediaId,rmsDBFS:$A(this.information,e.index),volume:zr(this.information,e.index),voicedBlocks:Yr(this.information,e.index),silentBlocks:Wr(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:jj(e.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:Qr(this.information),decoders:A}}};var gj=En(_j()),yj=(0,gj.default)(),Lj,Hj;globalThis.addEventListener("message",sr);async function sr(n){let A=n.data,[j,e]=A;switch(j){case"captureInit":e.workletPort.onmessage=sr,Lj=new lr(e.sampleRate,await yj,e.refreshRate);break;case"playbackInit":e.workletPort.onmessage=sr,Hj=new ir(await yj,e.workletPort,e.refreshRate);break;case"close":globalThis.close();break}Lj?.onMessage(A),Hj?.onMessage(A)}var lr=class extends OA{constructor(j,e,l){super(j,e);this.sampleRate=j;this.inBuffer=P(this.wasm,"f32",j*.02),this.updateHandle=setInterval(()=>this.update(),l),S(globalThis,["captureReady",{}])}close(){super.close(),V(this.wasm,this.inBuffer),clearInterval(this.updateHandle)}onMessage(j){super.onMessage(j);let[e,l]=j;switch(e){case"captureSetVolume":this.setVolume(l.value);break;case"captureTick":this.tick(l.buffer);break}}setVolume(j){yA(this.information,j)}tick(j){this.inBuffer.set(j,0),this.encode(this.inBuffer)}update(){S(globalThis,["captureUpdate",{active:vA(this.information),rmsDBFs:_A(this.information),speechProbability:IA(this.information)}])}dump(){return{type:"unshared capture worker",sampleRate:this.sampleRate,...super.dump()}}},ir=class extends JA{constructor(j,e,l){super(j);this.workletPort=e;this.id=T.PlaybackPreload,this.outBuffer=P(this.wasm,"f32",48e3*.02*2),this.updateHandle=setInterval(()=>this.update(),l),S(globalThis,["playbackReady",{}])}close(){super.close(),V(this.wasm,this.outBuffer),clearInterval(this.updateHandle)}onMessage(j){super.onMessage(j);let[e,l]=j;switch(e){case"playbackSetVolume":this.setVolume(l.index,l.value);break;case"playbackTick":this.tick();break}}setVolume(j,e){j==="global"?hA(this.information,e):FA(this.information,j,e)}tick(){this.stats.numberTicks++,this.id+=1;let{hasAudio:j}=this.decode(this.outBuffer);if(j){let e=this.outBuffer.slice();S(this.workletPort,["samples",{id:this.id,buffer:e}],[e.buffer])}}update(){let j=new Float32Array(this.information.length*2);for(let l=0;l<=this.largestIndex;l++)j[l]=$A(this.information,l);let e=[];for(let[l,c]of this.medias)e[c.index]={packetsBuffered:c.decoder.cache_length,packetsSeen:c.decoder.packets_seen,packetsProcessed:c.decoder.packets_processed,packetsTooEarly:c.decoder.packets_too_early,packetsTooLate:c.decoder.packets_too_late,packetsDropped:0,packetsInvalid:c.decoder.packets_invalid,packetsRepeated:c.decoder.packets_repeated,packetsLost:c.decoder.packets_lost};S(globalThis,["playbackUpdate",{activities:j,jitterStats:e}],[j.buffer])}dump(){return{type:"unshared playback worker",id:this.id,...super.dump()}}};})();
|
|
6725
|
-
`});var C0,K0=p(()=>{C0='"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:()=>E,AdditionalPlaybackBlocks:()=>R,ClockJumpCheckInterval:()=>_,ClockJumpThreshold:()=>N,ConnectInterval:()=>Q,ConnectTimeout:()=>z,DefaultRefreshRate:()=>D,DefaultVideoCodec:()=>K,HealthCheckTimeout:()=>O,MainConnectionPingInterval:()=>W,MaxNumberOfDecoders:()=>L,MaxReconnectDuration:()=>Y,MinDBFs:()=>v,MinTokenLifetime:()=>Z,MinTokenRefreshInterval:()=>q,PlaybackPreload:()=>F,RenderQuantumSize:()=>V,VadPreload:()=>C,WebRtcAnswerTimeout:()=>H,WebRtcIceTimeout:()=>$,WebRtcMaxNegotiationAttempts:()=>J,WebRtcStatsSnapshotInterval:()=>j,WebRtcTimeout:()=>G});var R=3,E=3,F=3,D=250,C=3,L=512,V=128,v=-758.596,O=1e4,_=1e3,N=1e4,W=3e3,j=1e3,$=3e3,G=1e4,H=1e4,J=3,z=5e3,Z=6e4,q=5e3,Q=[0,100,200,200,500],Y=12e4,K="H264";function d(e,t,r){return e.postMessage(t,r)}var X;(e=>{let t;(r=>(r[r.InvalidPassword=-1]="InvalidPassword",r[r.Unknown=0]="Unknown",r[r.Unencrypted=1]="Unencrypted",r[r.Encrypted=2]="Encrypted"))(t=e.PeerCipherStatus||={})})(X||={});var{Deno:k}=globalThis,ee=typeof k?.noColor=="boolean"?k.noColor:!1,te=!ee;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 te?`${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 re(e){return h(e,m([2],22))}var Ie=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"),ne=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}"},se={4:re,3:p,2:p,1:U,0:U};function oe({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()-ne.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],a=e.logger.name!==void 0?`@${e.logger.name}`:"";return`${p(r())}${a} ${s} ${se[e.level](String(e.message))}${n()}`}function ae(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 ie(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var w=class{static sparse=oe;static json=S;static pretty=I;static structured=ae;static default=ie()?I:S;constructor(){}};var ce=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 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=globalThis[Symbol.for("odin-global-logger")]??=new o(3,void 0,[new ce]),ue=o.prototype.log.bind(l,1),le=o.prototype.log.bind(l,2),fe=o.prototype.log.bind(l,3),de=o.prototype.log.bind(l,4),Te=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 W0={};kx(W0,{UnsharedCaptureWorker:()=>Gx,UnsharedPlaybackWorker:()=>$x,createCaptureWorker:()=>EF,createPlaybackWorker:()=>fF});function EF(D,x,A,F,r=C.DefaultRefreshRate){return CF.enqueue(async()=>{let[t,e]=await Bx(B0,C0,D,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return console.warn("SharedArrayBuffer is not available; creating ODIN CaptureWorker in fallback mode"),Gx.create(D,x,A,r,t,e,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 Bx(B0,C0,D,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return $x.create(D,x,A,F)}var V0,CF,Gx,$x,Q0=p(()=>{"use strict";V0=require("@4players/odin-common");o();qx();U0();K0();CF=new V0.Strand;Gx=class D extends jx{constructor(A,F,r,t,e){super(A,F,r,t,e);this._Activity=I;this._SpeechProbability=0;F.addEventListener("message",this._OnMessages.bind(this))}static async create(A,F,r,t,e,j,B){let{port1:E,port2:l}=new MessageChannel;return a(e,["captureInit",{sampleRate:A.sampleRate,refreshRate:t,workletPort:E}],[E]),await Fx(e,"captureReady"),a(j.port,["init",{workerPort:l}],[l]),new D(j,e,F,r,B)}get activity(){return this._Activity}get speechProbability(){return this._SpeechProbability}setVolume(A){a(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)}},$x=class D extends ex{constructor(A,F,r){super(A,F,r);this.activities=new Float32Array;this.jitterStats=[]}static async create(A,F,r,t){let{port1:e,port2:j}=new MessageChannel;return a(r,["playbackInit",{workletPort:e,refreshRate:F}],[e]),await Fx(r,"playbackReady"),a(t.port,["init",{workerPort:j}],[j]),new D(A,t,r)}getActivity(A){let F=this.medias.get(h(A));if(F===void 0)return;let r=this.activities.at(F.index);if(r!==void 0)return r===0?I:{isSilent:!1,rmsDBFS:r}}getJitterStats(A){let F=this.medias.get(h(A));if(F===void 0)return;let r=this.jitterStats.at(F.index);if(r!==void 0)return r}setGlobalVolume(A){a(this.worker,["playbackSetVolume",{index:"global",value:A}])}setVolume(A,F){let r=this.medias.get(h(A));r!==void 0&&a(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 PF={};kx(PF,{SESSION_ID:()=>ox,createPlugin:()=>HF});module.exports=$A(PF);var l0=require("@4players/odin-common");o();var J=require("@4players/odin-common");o();var Y=require("@4players/odin-common");o();var _=require("@4players/odin-common");o();var N0="getUserMedia; timeout";async function H0(D,x){try{let A=await Promise.race([navigator.mediaDevices.getUserMedia({audio:{echoCancellation:D.echoCanceller,noiseSuppression:D.noiseSuppression!=="None",autoGainControl:D.gainController,echoCancellationType:"system",deviceId:x?{exact:x}:void 0}}),(0,_.sleep)(3e4,"timeout")]);return A==="timeout"?(0,_.failure)(N0):(0,_.success)(A)}catch(A){return(0,_.failure)(`getUserMedia; ${A}`)}}async function P0(D,x,A){let F,r=!1;if(x.device?.device.kind==="track"&&x.device?.device.audioTrack)F=new MediaStream([x.device.device.audioTrack]);else{let j=x.device&&x.device.device.deviceId!=="default"?x.device.device.deviceId:void 0,B=await H0(A,j);if(B.type!=="Success"&&B.reason!==N0&&j&&(i(`unable to open requested capture device, falling back to default; ${B.reason}`),B=await H0(A),r=B.type==="Success"),B.type!=="Success")return B;F=B.value}let t=F.getAudioTracks()[0].getSettings().sampleRate,e=await D.audioContexts.acquire(t);return(0,_.success)({source:e.createMediaStreamSource(F),defaulted:r})}function Dx(D){D.getTracks().forEach(x=>{x.stop(),D.removeTrack(x)})}async function w0(D){return new rx({deviceId:D.id,kind:"track",name:D.label??"MediaStreamTrack",audioTrack:D},!1)}async function ZA(){let D=(await navigator.mediaDevices.enumerateDevices()).filter(x=>!!x.label);if(D.length===0&&(0,_.isFirefoxBrowser)()){let x=await YA("microphone");(x==="granted"||x===!1)&&(await xF("audio"),D=(await navigator.mediaDevices.enumerateDevices()).filter(A=>!!A.label))}return D}async function mx(){let D=await ZA(),x=new Map,A=[];for(let r of D){let t=r.kind;if(!(t!=="audioinput"&&t!=="audiooutput")){if(r.deviceId==="default"){x.set(t,r);continue}r.deviceId!=="communications"&&A.push(new rx({deviceId:r.deviceId,name:r.label,kind:t},!1))}}let F=r=>new rx({deviceId:"default",name:x.get(r)?.label??"Default",kind:r},!0);return[F("audioinput"),F("audiooutput"),...A]}async function YA(D){try{return(await navigator.permissions.query({name:D})).state}catch{return!1}}async function xF(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 yx=require("@4players/odin-common");o();var X0=(0,yx.isSharedArrayBufferCapable)()&&!(0,yx.isSafariBrowser)()?Promise.resolve().then(()=>(M0(),T0)):Promise.resolve().then(()=>(Q0(),W0));async function z0(D,x,A,F){return X0.then(r=>r.createCaptureWorker(D,x,A,F,C.DefaultRefreshRate))}async function Z0(D){return X0.then(x=>x.createPlaybackWorker(D,C.DefaultRefreshRate))}var nF=250,sF=1e3,O=class{constructor(x,A){this.controller=x;this._Medias=new Map;this._Vad={...Y.VAD_DEFAULTS};this._Apm={...Y.APM_DEFAULTS};this._Volume=1;this._Queue=Promise.resolve();this.#r=0;this._DeviceCb=()=>{clearTimeout(this.#F),this.#F=setTimeout(()=>{this._enqueue(async()=>{let x=this._DeviceParameters?.device;!x||x.device.kind==="track"||(x.device.deviceId==="default"?await this._followDefaultDevice():await this._detectSelectedDeviceRemoved(x.device.deviceId))}).catch(x=>i("device-change handler failed",x))},nF)};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,Y.generateUUID)(),this.#x=A.customType,this.#A=A.ref}#x;#A;#F;#r;async _followDefaultDevice(){let x=this._DeviceParameters;this._Volume==="muted"||!this._Capture||!x||Date.now()-this.#r<sF||(n("default capture device may have moved, re-opening capture"),await this._setDeviceImpl(x))}async _detectSelectedDeviceRemoved(x){(await mx()).some(t=>t.device.deviceId===x)||this._Capture?.source.mediaStream?.getAudioTracks()[0]?.readyState==="live"||(this._DeviceParameters?.onStatusChanged?.("stopped"),navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._DeviceParameters=void 0,await this._closeImpl())}_enqueue(x){let A=this._Queue.then(x,x);return this._Queue=A.catch(()=>{}),A}get vad(){return this._Vad}get apm(){return this._Apm}get volume(){return this._Volume}get activity(){return this._Capture?.worker.activity??I}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),f(`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=>u(`StartMedia got rejected; ${r}`)),this._UpdateMedias())}async stop(x,A){let F=this._Medias.get(A.connectionId);f(`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=>u(`StopMedia got rejected; ${r}`)),this._UpdateMedias())}setVad(x){n("updating vad config",x),this._Vad=x,this._Capture&&this._Capture.worker.setVad(x)}async setApm(x){await this._enqueue(()=>this._setApmImpl(x))}async _setApmImpl(x){n("updating apm config",x),this._Apm=x,this._DeviceParameters&&await this._setDeviceImpl(this._DeviceParameters)}async setDevice(x){await this._enqueue(()=>this._setDeviceImpl(x))}async _setDeviceImpl(x){n("updating capture device parameters",x);let A=this._DeviceParameters;if(this._DeviceParameters=x,this._Volume==="muted")return;let F;try{let r=await P0(this.controller,x,{...this._Apm,echoCanceller:this._Monitor?!1:this._Apm.echoCanceller});if(r.type!=="Success"){u(`unable to open capture device; ${r.reason}`),this._DeviceParameters=A;return}F=r.value.source.context,navigator.mediaDevices.addEventListener("devicechange",this._DeviceCb);let t=this._Capture?.source.context;if(this._Capture!==void 0){Dx(this._Capture.source.mediaStream);try{this._Capture.source.disconnect(this._Capture.worker.worklet)}catch(e){i("failed to disconnect previous capture source",e)}}this._Capture===void 0||this._Capture.worker.worklet.context!==r.value.source.context?(this._Capture?.worker.close(),this._Capture={worker:await z0(r.value.source.context,this.controller.sink,this.controller.receiveMonitoredPacket.bind(this.controller),new WeakRef(this)),source:r.value.source},await this._UpdateMedias(),this._Capture.worker.setVolume(this._Volume),this.setVad(this.vad)):this._Capture.source=r.value.source,F=void 0,this._Capture.source.connect(this._Capture.worker.worklet),t!==void 0&&await this.controller.audioContexts.release(t),this.#r=Date.now(),x.onStatusChanged?.(r.value.defaulted?"defaulted":"started")}catch(r){throw F!==void 0&&await this.controller.audioContexts.release(F),new Error(`Error in setDevice(); ${r}`,{cause:r})}}async setVolume(x){await this._enqueue(()=>this._setVolumeImpl(x))}async _setVolumeImpl(x){n(`updating capture volume to ${x}`),this._Volume=x,x==="muted"?await this._closeImpl():(!this._Capture&&this._DeviceParameters&&await this._setDeviceImpl(this._DeviceParameters),this._Capture?.worker.setVolume(x))}async close(){await this._enqueue(()=>this._closeImpl())}async _closeImpl(){if(n("closing audio capture"),clearTimeout(this.#F),this.#F=void 0,this._Capture!==void 0){this._Capture.worker.close(),Dx(this._Capture.source.mediaStream);try{this._Capture.source.disconnect(this._Capture.worker.worklet)}catch(x){i("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,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&&(n("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&&(n("stopping audio capture loopback"),this._Monitor.close(),this._Monitor=void 0,this.setApm(this._Apm),this._Medias.delete(0),await this._UpdateMedias())}};var K=require("@4players/odin-common");o();var $=class{constructor(x,A){this.controller=x;this.parameters=A;this.uid=(0,K.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,K.assert)(this.audioCapture,"getting the volume failed, this video has no Audio"),this.audioCapture.volume}async setVolume(x){(0,K.assert)(this.audioCapture,"setVolume() failed, this video has no Audio"),await this.audioCapture.setVolume(x)}get vad(){return(0,K.assert)(this.audioCapture,"getting the vad config failed, this video has no Audio"),this.audioCapture.vad}setVad(x){(0,K.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 w0(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=>u(`StartMedia got rejected; ${t}`))}}async stop(x,A){this.#x&&Dx(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=>u(`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&&Dx(this.#x),this.audioCapture?.close(),this.#F=void 0}};var iF=require("@4players/odin-common");o();var L=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){f(`starting audio playback media ${x.mediaId} on connection ${x.connectionId}`),this.controller.playbackStart(this.uid,x)}stop(x){f(`stopping audio playback media ${x.mediaId} on connection ${x.connectionId}`),this.controller.playbackStop(this.uid,x)}setVolume(x){n(`updating audio playback media '${this.uid}' volume to ${x}`),this.controller.playbackSetVolume(this.uid,x)}close(){n(`closing audio playback media '${this.uid}'`),this.controller.closePlayback(this.uid)}};function bF(D,x){let A=D.audioContext;if(typeof A.setSinkId=="function"){D.connectOutput(A.destination);let F,r=()=>{if(A.state==="running"&&F!==void 0){let t=F;F=void 0,A.setSinkId(t).catch(e=>i("failed to apply deferred sinkId",e))}};return A.addEventListener("statechange",r),{async setSinkId(t){if(A.state!=="running"){F=t;return}await A.setSinkId(t)},dispose(){A.removeEventListener("statechange",r)}}}if(x&&typeof document<"u"&&typeof HTMLAudioElement<"u"&&typeof HTMLAudioElement.prototype.setSinkId=="function"){let F=A.createMediaStreamDestination();D.connectOutput(F);let r=new Audio;r.srcObject=F.stream,r.muted=!1,r.volume=1;let t=!1,e=!1,j={once:!0,passive:!0,capture:!0},B=()=>{e=!1,c()},E=()=>{e||t||(e=!0,document.addEventListener("pointerdown",B,j),document.addEventListener("keydown",B,j))},l=()=>{e&&(e=!1,document.removeEventListener("pointerdown",B,!0),document.removeEventListener("keydown",B,!0))},c=()=>{t||r.play().catch(bx=>{t||(bx instanceof DOMException&&bx.name==="NotAllowedError"?E():i("failed to start playback audio element",bx))})},cx=()=>{A.state==="running"&&r.paused&&c()};return A.addEventListener("statechange",cx),c(),{async setSinkId(bx){await r.setSinkId(bx)},dispose(){t=!0,l(),A.removeEventListener("statechange",cx),r.pause(),r.srcObject=null,r.removeAttribute("src");try{r.load()}catch{}F.disconnect()}}}return D.connectOutput(A.destination),{async setSinkId(){},dispose(){}}}var gx=class{constructor(x){this.audioContextFactory=x;this.entries=[];this._acquireStrand=new J.Strand}acquire(x){return this._acquireStrand.enqueue(async()=>{for(let r of this.entries)if(r.sampleRate===x||r.sampleRate===void 0&&r.audioContext.sampleRate===x)return r.references+=1,r.audioContext;let A=await this.audioContextFactory(x),F=this.entries.find(r=>r.audioContext.sampleRate===A.sampleRate);return F?(F.references+=1,A.close().catch(()=>{}),F.audioContext):(this.entries.push({sampleRate:x,audioContext:A,references:1}),A)})}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.splice(0))x.audioContext.close().catch(()=>{})}},Ix=class D{constructor(x,A,F=!1){this.audioContexts=x;this.sink=A;this.enableHTMLAudioElementFallback=F;this.audioCaptures=[];this.videoCaptures=[];this.globalVolume=[1,1];this.playbacks=new Map;this.setPlaybackStrand=new J.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 L(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 O(this,x);return await A.setDevice(x),this.audioCaptures.push(new WeakRef(A)),A}async createVideoCapture(x,A){let F=new $(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??"";if(A==="default"&&(A=""),this.playbackWorker===void 0){let F=await this.audioContexts.acquire(48e3);this.playbackWorker=await Z0(F),this.playbackSink=bF(this.playbackWorker,this.enableHTMLAudioElementFallback),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)}if(x&&this.playbackSink!==void 0)try{await this.playbackSink.setSinkId(A)}catch(F){i("failed to set playback sink",F)}})}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&&i(`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?I:this.playbackWorker?.getActivity(A.id)??I}playbackGetJitterStats(x){let A=this.playbacks.get(x);return A?.id===void 0?J.JITTER_STATS_INITIAL:this.playbackWorker?.getJitterStats(A.id)??J.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.playbackSink?.dispose(),this.playbackSink=void 0,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}}},rx=class{constructor(x,A=!1){this.device=x;this.isDefault=A}get type(){switch(this.device.kind){case"audioinput":return"AudioCapture";case"track":return"AudioCapture";case"audiooutput":return"AudioPlayback";default:(0,J.assert)(!1,"not supported device")}}get id(){return this.device.deviceId}get name(){return this.device.name}};var ax=require("@4players/odin-common"),tA=require("@msgpack/msgpack");o();var dF=require("@4players/odin-common");o();var g=require("@4players/odin-common"),Q=require("@4players/odin-common/api");o();var W=require("@4players/odin-common"),xx=require("@4players/odin-common/api"),_x=require("@msgpack/msgpack");o();var V=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"):(aF(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(e=>{this._Requests.set(r,{accept:e,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).catch(()=>{})}_OnWebSocketOpen(x){for(let A of this._SendQueue)this._Send(A);this._SendQueue.length=0}_OnRpcMessage(x){let A=oF(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,W.success)(F):(0,W.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,W.success)(t):(0,W.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:(Y0(this._Events,x.name)?(u(`schema validation for ${x.name} failed; closing connection`),this.rpc.close()):i(`dropping unknown event ${x.name}`),"closed")}close(){this.rpc.close()}};function oF(D){try{return(0,W.success)(xx.MessagePackRpcSchema.parse((0,_x.decode)(new Uint8Array(D))))}catch(x){return(0,W.failure)(String(x))}}function E0(D,x){if(!Y0(D,x.name))return;let A=D[x.name].safeParse(x.properties);if(A.success)return{name:x.name,properties:A.data}}function Y0(D,x){return x in D}async function aF(D,x){let A=new Uint8Array;for(;;){let F=$0(A,0);if(F===v){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=lF(A,r.value)}A.length>0&&i("unprocessed bytes left in rpc stream",A)}function lF(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 R=require("@4players/odin-common"),xA=require("@4players/odin-common/api");o();var y=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:u(`upstream in token can not be parsed; ${F.reason}`)}}static parse(x){let A=x.split(".");if(A.length!==3)return(0,R.failure)("expected three segments");let F=(0,R.fromBase64Url)(A[1]);if(F.type==="Failure")return(0,R.failure)(`invalid token; ${F.reason}`);let r;try{r=JSON.parse(F.value)}catch(e){return(0,R.failure)(`invalid token; ${e}`)}let t=xA.TokenClaimsSchema.safeParse(r);return t.success===!1?(0,R.failure)(`invalid token; ${t.error}`):(0,R.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 Cx=require("@4players/odin-common");o();function AA(D){typeof globalThis.rtcDataChannels>"u"&&(globalThis.rtcDataChannels=[]),Array.isArray(globalThis.rtcDataChannels)&&globalThis.rtcDataChannels.length<=100&&globalThis.rtcDataChannels.push(D)}function FA(D){let x=globalThis.rtcDataChannels?.indexOf(D);x!==void 0&&x>=0&&globalThis.rtcDataChannels.splice(x,1),D.readyState!=="closed"&&D.close()}function Lx(D){typeof globalThis.rtcPeerConnections>"u"&&(globalThis.rtcPeerConnections=[]),Array.isArray(globalThis.rtcPeerConnections)&&globalThis.rtcPeerConnections.length<=100&&globalThis.rtcPeerConnections.push(D)}function Hx(D){let x=globalThis.rtcPeerConnections?.indexOf(D);x!==void 0&&x>=0&&globalThis.rtcPeerConnections.splice(x,1),D.connectionState!=="closed"&&D.close()}var Ex=class{constructor(x,A,F){this._localVideos=new Map;this._remoteVideos=new Map;this._freeLocalVideoTransceivers=[];this._closed=!1;this._negotiationRequested=!1;this._negotiationRunning=!1;this._negotiationCounter=0;this._pendingRemoteCandidates=[];this._WebRtcStatsSnapshot=null;this._peerConnection=x,this._signaling=A,this._answerTimeout=F?.answerTimeout??C.WebRtcAnswerTimeout,this._maxNegotiationAttempts=F?.maxNegotiationAttempts??C.WebRtcMaxNegotiationAttempts,this._peerConnection.ontrack=this._onTrack.bind(this),this._peerConnection.onconnectionstatechange=()=>this._onStatusChanged(),this._peerConnection.onicecandidate=r=>{(r.candidate?this._signaling.sendIceCandidate(r.candidate):this._signaling.sendIceComplete()).catch(e=>{i("failed to send local ice candidate",e)})},this._WebRtcStatsInterval=setInterval(()=>{this._snapshotStats()},C.WebRtcStatsSnapshotInterval)}requestNegotiation(){this._closed||(this._negotiationRequested=!0,!this._negotiationRunning&&(this._negotiationRunning=!0,setTimeout(async()=>{let x=0;for(;this._negotiationRequested&&!this._closed;){this._negotiationRequested=!1;try{await this._negotiate(),x=0}catch(A){if(this._closed)break;if(x+=1,u(`negotiation failed during sdp offer/answer exchange (attempt ${x})`,A),x<this._maxNegotiationAttempts)this._negotiationRequested=!0;else{this._negotiationRunning=!1,this._signaling.closeConnection().catch(()=>{});return}}}this._negotiationRunning=!1})))}async startLocalVideo(x,A,F){if(this._localVideos.has(x))return;f(`starting local video for media ${x}`);let r=this._freeLocalVideoTransceivers.pop();if(r?(await r.sender.replaceTrack(A),r.direction="sendrecv"):r=this._peerConnection.addTransceiver(A),F){let j=r.sender.getParameters(),{maxBitrate:B,maxFramerate:E,scaleResolutionDownBy:l}=F,c={...B!==void 0&&{maxBitrate:B},...E!==void 0&&{maxFramerate:E},...l!==void 0&&{scaleResolutionDownBy:l}};if(j.encodings.length===0)j.encodings.push(c);else for(let cx of j.encodings)Object.assign(cx,c);F.degradationPreference&&(j.degradationPreference=F.degradationPreference),await r.sender.setParameters(j)}let e=new Cx.VideoCodec(F?.codec??C.DefaultVideoCodec).isSupported();e&&r.setCodecPreferences([e]),this._localVideos.set(x,{transceiver:r}),this.requestNegotiation()}stopLocalVideo(x){let A=this._localVideos.get(x);A&&(f(`stopping local video for media ${x}`),this._localVideos.delete(x),A.transceiver.sender.track&&(A.transceiver.sender.track.enabled=!1),A.transceiver.direction="inactive",A.transceiver.sender.replaceTrack(null).catch(()=>{}),this._freeLocalVideoTransceivers.push(A.transceiver),this.requestNegotiation())}startRemoteVideo(x){let A=this._remoteVideos.get(x);if(A)return A.track;f(`starting remote video for media ${x}`);let F=this._peerConnection.addTransceiver("video",{direction:"recvonly"}),r,t=new Promise((e,j)=>{r={resolve:e,reject:j}});return t.catch(()=>{}),(0,Cx.assert)(r!==void 0,"promise executor must run synchronously"),this._remoteVideos.set(x,{state:"Requested",transceiver:F,promise:r,track:t}),this.requestNegotiation(),t}stopRemoteVideo(x){let A=this._remoteVideos.get(x);if(A){f(`stopping remote video for media ${x}`),this._remoteVideos.delete(x),A.state!=="Active"&&A.promise.reject(new Error("video stopped"));try{A.transceiver.direction="inactive"}catch{}this.requestNegotiation()}}async handleWebRtcUpdate(x){try{switch(x.kind){case"Sdp":await this._updateRemoteSdp(x.type==="Answer"?"answer":"offer",x.sdp,x.media_map,x.negotiation_id);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}}catch(A){u("failed to handle webrtc update",A,x)}}startup(){this._peerConnection.connectionState==="new"&&this.requestNegotiation()}cleanup(){this._closed=!0;for(let[,x]of this._remoteVideos)x.state!=="Active"&&x.promise.reject(new Error("connection closed"));this._pendingAnswer?.reject(new Error("connection closed")),this._pendingRemoteCandidates.length=0,clearTimeout(this._WebRtcIceTimeout),clearTimeout(this._WebRtcTimeout),clearInterval(this._WebRtcStatsInterval),this._localVideos.clear(),this._remoteVideos.clear(),this._freeLocalVideoTransceivers.length=0}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._negotiationRunning}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,...e}=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(e))}),this._WebRtcStatsSnapshot={timestamp:Date.now(),status:this._peerConnection.connectionState,stats:F,report:A}}catch{}}_addIceCandidate(x){if(x&&(x.sdpMid===void 0&&x.sdpMLineIndex===void 0&&(x={...x,sdpMid:"0"}),n(`adding new ice ${x.candidate}`,x)),this._peerConnection.remoteDescription===null){this._pendingRemoteCandidates.push(x);return}this._applyIceCandidate(x)}_applyIceCandidate(x){this._peerConnection.addIceCandidate(x).catch(A=>{i("failed to add remote ice candidate",A,x)})}_flushPendingIceCandidates(){let x=this._pendingRemoteCandidates.splice(0);for(let A of x)this._applyIceCandidate(A)}async _negotiate(){let x=++this._negotiationCounter,A=await this._peerConnection.createOffer();(0,Cx.assert)(A.type==="offer"&&A.sdp,"generated broken payload"),await this._peerConnection.setLocalDescription(A);let F=[];for(let[t,{transceiver:e}]of this._localVideos)e.mid&&F.push([t,e.mid]);for(let[t,e]of this._remoteVideos)e.state!=="Active"&&e.transceiver.mid&&F.push([t,e.transceiver.mid]);let r=new Promise((t,e)=>{this._pendingAnswer={negotiationId:x,resolve:t,reject:e}});try{await this._signaling.sendOffer(A.sdp,F,x),await uF(r,this._answerTimeout,`timed out waiting for answer to offer ${x}`)}finally{this._pendingAnswer=void 0}}async _updateRemoteSdp(x,A,F,r){if(x==="offer"){i("ignoring unexpected sdp offer from server");return}let t=this._pendingAnswer;if(t===void 0){i("ignoring sdp answer without pending negotiation");return}if(r!==void 0&&r!==t.negotiationId){i(`ignoring stale sdp answer for negotiation ${r}; current is ${t.negotiationId}`);return}if(this._peerConnection.signalingState!=="have-local-offer"){i(`ignoring sdp answer in signaling state ${this._peerConnection.signalingState}`);return}for(let[e,j]of F){let B=this._remoteVideos.get(e);B?.state==="Requested"&&(this._remoteVideos.set(e,{state:"Mapped",transceiver:B.transceiver,mid:j,promise:B.promise,track:B.track}),n(`updated remote video list with media ${e}`,B,this._remoteVideos))}try{await this._peerConnection.setRemoteDescription({type:x,sdp:A})}catch(e){t.reject(e);return}this._flushPendingIceCandidates(),t.resolve()}async _onStatusChanged(){switch(n(`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();case"disconnected":C.MainConnectionPingInterval!==void 0&&await this._signaling.checkConnection();default:this._WebRtcIceTimeout===void 0&&(this._WebRtcIceTimeout=setTimeout(()=>{n("ice connection timeout was reached"),this._peerConnection.restartIce(),this._WebRtcIceTimeout=void 0},C.WebRtcIceTimeout)),this._WebRtcTimeout===void 0&&(this._WebRtcTimeout=setTimeout(async()=>{n("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){i(`unexpected track with mid: ${x.transceiver.mid}`);return}let[F,r]=A;(0,Cx.assert)(r.state==="Mapped","expected video state to be Mapped"),this._remoteVideos.set(F,{state:"Active",transceiver:x.transceiver,track:r.track}),n(`updated local video list with media ${F}`,A,x.transceiver,this._localVideos),x.track.onended=()=>{n(`video track with mid ${x.transceiver.mid} ended`,A)},r.promise.resolve(x.track)}};function uF(D,x,A){return new Promise((F,r)=>{let t=setTimeout(()=>r(new Error(A)),x);D.then(e=>{clearTimeout(t),F(e)},e=>{clearTimeout(t),r(e)})})}var Nx=class D{constructor(x,A,F,r,t,e,j){this.id=x;this.address=A;this.connection=r;this.datagramWritable=t;this.rpc=e;this.closeController=j;this._ConnectionStats={...g.CONNECTION_STATS_INITIAL};this._WebRtcUpdatesRunning=!1;this._WebRtcSessionFlight=new z;this._PingFlight=new z;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=t.getWriter(),this.connection.closed.then(()=>{this.status=2}).catch(()=>{}).finally(()=>{this.closeController.abort("transport closed")}),this.connection.ready.then(()=>{this.status=1}).catch(()=>{}),this.readDatagrams(this.connection,this.id,(B,E)=>{this._ConnectionStats.packetsReceived+=1,F(B,E)})}static async create(x,A,F,r){try{let t=new URL(`https://${A}?version=${g0}&uid=${ox}`),e=new AbortController;r.addEventListener("abort",()=>e.abort(),{once:!0});let j=new WebTransport(t);e.signal.addEventListener("abort",()=>{try{j.close()}catch{}},{once:!0}),await j.ready;let B=j.datagrams,E=B?.createWritable?.()??B?.writable;if(!E)return e.abort(),(0,g.failure)(`connecting to ${A} failed because WebTransport datagrams are not supported by this browser`);let l=await j.createBidirectionalStream(),c=new Ax(new V(l),Q.MainCommandsRpc,Q.MainNotificationsRpc);return e.signal.addEventListener("abort",()=>c.close(),{once:!0}),c.notify("Hello",{stream:"main"}),(0,g.success)(new D(x,A,F,j,E,c,e))}catch(t){return(0,g.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(){f(`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 e=new Ax(new V(t),Q.RoomCommandsRpc,Q.RoomNotificationsRpc),j=await e.request("Hello",{stream:"room",token:String(x),room_id:A,user_data:F,position:r});return j==="closed"||j.type==="Failure"?j:(0,g.success)(e.rpc)}catch(t){return(0,g.failure)(`JoinRoom failed; ${t}`)}}async getReconnectToken(x){let A=await this._Request("RequestReconnectToken",{peer_id:x});return A.type==="Failure"?A:y.parse(A.value)}async getRtcStats(){return this._PeerConnection?.getStats()}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.closed)try{this.datagramWriter.write(x).catch(()=>{}),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 e=t.value.byteLength;this.connectionStats.bytesReceived+=e,F(A,t.value)}}catch{}}_CleanUp(){n(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId),this._RecycleWebRtcSession("connection closed")}_RecycleWebRtcSession(x){let A=this._WebRtcSession,F=this._PeerConnection;A===void 0&&F===void 0||(i(`recycling webrtc session of connection ${this.id}; ${x}`),this._WebRtcSession=void 0,this._PeerConnection=void 0,A?.cleanup(),F&&Hx(F))}async _EnsureWebRtcSession(){return this._WebRtcSession?this._WebRtcSession:this._WebRtcSessionFlight.run(async()=>(this._PeerConnection=new RTCPeerConnection,Lx(this._PeerConnection),this._WebRtcSession=new Ex(this._PeerConnection,{sendOffer:async(x,A,F)=>{let r=await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:x,media_map:A,negotiation_id:F});if(r.type==="Failure")throw new Error(`failed to send sdp offer; ${r.reason}`)},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._RecycleWebRtcSession("negotiation gave up")},checkConnection:async()=>{}}),this._HandleWebRtcUpdates(),this._WebRtcSession))}async _HandleWebRtcUpdates(){if(!this._WebRtcUpdatesRunning){for(this._WebRtcUpdatesRunning=!0;;){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)),e=(Date.now()-r)/1e3;return x!=="Ping"&&n(`sent main rpc '${x}'; took: ${e}s`,{properties:A,timeout:F,result:t}),t==="closed"?(0,g.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"),wx=require("@4players/odin-common/api");o();var H=require("@4players/odin-common");o();async function f0(D,x){let A=performance.now(),F=(0,H.failure)("no connection was attempted");for(let r=0;r<C.ConnectInterval.length&&!x.aborted;r++){let t=A+kF(r);if(await(0,H.abortableSleep)(t-performance.now(),x)==="aborted")return(0,H.failure)("aborted");if(F=await cF(D,x),F.type==="Success")return F}return F}async function cF(D,x){let A;try{A=new WebSocket(D)}catch(B){return(0,H.failure)(`unable to create websocket; ${B}`)}let F=new AbortController,r=new Promise(B=>A.addEventListener("open",()=>B((0,H.success)(A)),{signal:F.signal})),t=new Promise(B=>A.addEventListener("close",E=>B((0,H.failure)(E.reason!==""?E.reason:"unable to establish websocket connection")),{signal:F.signal})),e=new Promise(B=>x.addEventListener("abort",()=>B((0,H.failure)("aborted")),{signal:F.signal})),j=await Promise.race([r,t,e]);return F.abort(),j}function kF(D){let x=C.ConnectInterval.slice(0,D).reduce((F,r)=>F+r,0),A=C.ConnectInterval[D]*Math.random();return x+A}var Px=class D{constructor(x,A,F,r,t,e){this.id=x;this.address=A;this.url=F;this.onDatagram=r;this.connection=t;this.webRtc=e;this._PeerIdMap=new WeakMap;this._ConnectionStats={...d.CONNECTION_STATS_INITIAL};this._PingFlight=new z;f(`creating new webrtc connection to '${this.address}' with id ${this.id}`),this.closeSignal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this._ClosePromise=new Promise(j=>{this.closeSignal.addEventListener("abort",()=>{j("closed")},{once:!0})}),Lx(e),this._AudioChannel=this.webRtc.createDataChannel("audio",{id:2,negotiated:!0,ordered:!1,maxRetransmits:0}),this._AudioChannel.binaryType="arraybuffer",this._AudioChannel.onmessage=j=>{this._ConnectionStats.packetsReceived++;let B=new Uint8Array(j.data);this._ConnectionStats.bytesReceived+=B.byteLength,this.onDatagram(this.id,B)},this._AudioChannel.onerror=j=>i(`webrtc audio data channel for connection with id ${x} raised an error`,j),this._AudioChannel.onclosing=j=>f(`webrtc audio data channel for connection with id ${x} begins shutting down`,j),this._AudioChannel.onclose=j=>f(`webrtc audio data channel for connection with id ${x} has closed`,j),AA(this._AudioChannel),this._WebRtcSession=new Ex(this.webRtc,{sendOffer:async(j,B,E)=>{let l=await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:j,media_map:B,negotiation_id:E});if(l.type==="Failure")throw new Error(`failed to send sdp offer; ${l.reason}`)},sendIceCandidate:async j=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:j.candidate,spd_mid:j.sdpMid??void 0,spd_mline_index:j.sdpMLineIndex??void 0,username_fragment:j.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async()=>{this.close()},checkConnection:async()=>{this.healthCheck().then()}}),this._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(E){return(0,d.fail)(`address in token(${A}) can not be parsed; ${E}`)}let e=(0,d.extendUrl)(t,`main?uid=${ox}`);if(e.type!=="Success")return e;let j=await f0(e.value,r);if(j.type!=="Success")return j;let B=new Ax(new V(j.value),wx.MainCommandsRpc,wx.MainNotificationsRpc);try{return(0,d.success)(new D(x,A,t,F,B,new RTCPeerConnection))}catch(E){return B.close(),(0,d.failure)(`unable to create webrtc connection; ${E}`)}}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(){f(`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 e=t.value;if(!("token"in e))return(0,d.failure)("JoinRoom responded without token");let j=(0,d.extendUrl)(this.url,`room?token=${e.token}`);if(j.type==="Failure")return j;let B=await f0(j.value,this.closeSignal);return B.type==="Success"?(this._PeerIdMap.set(B.value,e.peer_id),(0,d.success)(new V(B.value))):B}async getReconnectToken(x){let A=await this._Request("RequestReconnectToken",{peer_id:x});return A.type==="Failure"?A:y.parse(A.value)}async getRtcStats(){return this.webRtc.getStats()}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(){n(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId),FA(this._AudioChannel),Hx(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)),e=(Date.now()-r)/1e3;return x!=="Ping"&&n(`sent main rpc '${x}'; took: ${e}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 DA(D,x,A,F,r){switch(f(`creating ${x} main connection to '${A}'`),x){case"H3":return Nx.create(D,A,F,r);case"WebRTC":return Px.create(D,A,F,r);default:throw new Error(`transport ${x} is not supported`)}}var fx=require("@4players/odin-common"),N=require("@4players/odin-common/api");o();var Ox=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===v)return(0,fx.failure)("unable to encrypt initial user-data");let e=await this.connection.joinRoom(x,A,t,r);return e==="closed"||e.type==="Failure"?e:(0,fx.success)(new n0(e.value,this.cipher,this))}getReconnectToken(x){return this.connection.getReconnectToken(x)}getRtcStats(){return this.connection.getRtcStats()}healthCheck(){return this.connection.healthCheck()}async sendDatagram(x){let A=await this.cipher.encryptDatagram(x);A!==v?(this._DatagramSent+=1,this.connection.sendDatagram(A)):this._DatagramSentInvalid+=1}async decryptDatagram(x,A){let F=await this.cipher.decryptDatagram(x,A);return F!==v?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()}}},Jx=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)}},n0=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===v?(0,fx.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!==v)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!==v)return{name:x.name,properties:A}}}close(){return this.rpc.close()}async outgoing(x,A){if(!(x in N.RoomCommandsRpc))return A;let F=(0,N.parseCommand)(x,A,N.RoomCommandsRpc);if(F===void 0)return v;switch(F.name){case"UpdatePeer":{let r=await this.cipher.encryptUserData(F.request.user_data);if(r===v)return v;F.request.user_data=r}break;case"SendMessage":{let r=await this.cipher.encryptMessage(F.request.message);if(r===v)return v;F.request.message=r}break}return F.request}async incoming(x,A){if(!(x in N.RoomNotificationsRpc))return A;let F=(0,N.parseNotification)(x,A,N.RoomNotificationsRpc);if(F===void 0)return v;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===v)return v;F.properties.updates[r]=t}break;case"PeerUpdated":{let r=await this.peerUpdate(F.properties);if(r===v)return v;F.properties=r}break;case"MessageReceived":{let r=await this.cipher.decryptMessage(F.properties.sender_peer_id,F.properties.message);if(r===v)return v;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===v)return v;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!==v?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!==v?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=h({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=h({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 Rx=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=pF(A);if(F===void 0||F.length===0)return;let r=this._MediaMap.get(h({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===v)return;this.onDatagram(r.connection.id,t)}}async acquireConnection(x,A,F,r){if(await(0,ax.nextTick)(),this.closed)return"closed";let t=this.findConnection(x,A),e;switch(t?.type){case"established":n(`reusing existing connection ${t.id}`),e=t;break;case"establishing":{n(`waiting for connecting to '${A}' finish`);let E=await t.finished;if(E.type!=="Success")return E;e=E.value}break;case void 0:{n(`connecting to '${A}'`);let E=await this.createConnection(x,A,r);if(E.type!=="Success")return E;e=E.value}break}let j=e.id,B=new s0(e.connection,()=>this.releaseConnection(j));return e.references+=1,F&&(B=new Ox(++this._LastConnectionId,B,F,this._MediaMap),this.addConnection({type:"virtual",id:B.id,connection:B,createdAt:Date.now()})),(0,ax.success)(B)}async createConnection(x,A,F){let r=++this._LastConnectionId,t=Date.now(),e=new AbortController;F.addEventListener("abort",()=>e.abort(),{once:!0}),n(`creating new connection ${r}`);let j=DA(r,x,A,this.recvDatagram.bind(this),F),{promise:B,resolve:E}=Promise.withResolvers();this.addConnection({type:"establishing",id:r,address:A,transport:x,finished:B,createdAt:Date.now(),abort:e});let l=await j;if(this._Connections.delete(r),l.type!=="Success")return E(l),l;let c={type:"established",id:r,address:A,transport:x,createdAt:t,references:0,connection:l.value};return this.addConnection(c),(0,ax.success)(c)}addConnection(x){(x.type==="established"||x.type==="virtual")&&x.connection.closeSignal.addEventListener("abort",()=>{f(`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&&(F.type!=="established"||!F.connection.closed))return F}},s0=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)}getRtcStats(){return this.connection.getRtcStats()}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 pF(D){let x;try{x=(0,tA.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 lx=require("@4players/odin-common"),P=class{constructor(x,A){this.uid=x;this.customType=A}#x;#A;get mediaStream(){return this.#x}get audioPlayback(){return(0,lx.assert)(this.#A,"getting the audioPlayback failed, this video has no Audio"),this.#A}get volume(){return(0,lx.assert)(this.audioPlayback,"getting the volume failed, this video has no Audio"),this.audioPlayback.volume}setVolume(x){(0,lx.assert)(this.#A,"Can not set the volume, this video has no Audio"),this.#A.setVolume(x)}setMediaStream(x){this.#x=x}close(){this.#x?.getVideoTracks().forEach(x=>{x.stop(),this.#x?.removeTrack(x)}),this.#x=void 0}};var w=require("@4players/odin-common"),o0=require("@4players/odin-common/api");var b=require("@4players/odin-common"),S=require("@4players/odin-common/api");o();var Sx=class{constructor(x,A,F,r,t,e,j,B,E,l){this.connectionPool=x;this.transport=A;this.onEvent=F;this.gateway=r;this.roomId=e;this.cipher=E;this.disableAutoReconnect=l;this._Close=new AbortController;this._TokenUsed=!1;this._WasConnected=!1;this._FailedConnections=0;this._LastTokenRenew=performance.now();this._LastReconnectStartedAt=0;this._ReconnectingSince=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=j,this._Position=B,this._Main().then(({reason:c})=>n(`_Main() resolved; ${c}`))}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,b.failure)("currently not connected");let F=await this._RoomConnection.request(x,A,void 0);return(0,b.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=await this.requestUnsafe(x,A),t=(Date.now()-F)/1e3;if(n(`sent room rpc '${x}'; took: ${t}s`,{properties:A,result:r}),r==="closed"||r.type==="Failure")return r;let e=(0,S.parseResponse)(x,r.value,S.RoomCommandsRpc);return e!==void 0?(0,b.success)(e):(0,b.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;for(let A=0;;this._FailedConnections++){if(await(0,b.sleep)(Math.max(A-performance.now(),0)),this._Close.signal.aborted||this.connectionPool.closed){x="user requested";break}if(this._WasConnected&&this._ReconnectingSince!==0&&eA(this._ReconnectingSince,C.MaxReconnectDuration)){x="reconnect time limit reached";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"){n("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()),this._WasConnected&&this._ReconnectingSince===0&&(this._ReconnectingSince=performance.now()),F.type==="Failure"&&!this._WasConnected&&this._FailedConnections>=3){x=F.reason;break}if(F.type==="Failure"&&!eA(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 hF(this.gateway,this._Token,this._Close.signal);if(F.type==="Success")if(F.value instanceof y)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,b.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,b.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,b.failure)("connection pool closed");if(t.type==="Failure")return this._ChangeStatus("Joining",`connection failed; ${t.reason}`),(0,b.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,b.sleep)(C.ConnectTimeout,"timeout"),this._Closed]);if(F==="closed"||F==="disconnected")return(0,b.success)("continue");if(F==="timeout")return this._ChangeStatus("Joining","timed out"),(0,b.success)("continue");let[r]=F;if(r==="closed")return(0,b.success)("continue");if(r.type==="Failure")return(0,b.failure)(`unable to join room; ${r.reason}`);this._RoomConnection=r.value,this._WasConnected=!0,this._FailedConnections=0,this._ReconnectingSince=0,this._ChangeStatus("Joined",`joined ${this.roomId}`);try{await this._MainConnection.waitForConnected();let t=await this._HandleConnection(this._MainConnection);return(0,b.success)(t?"shutdown":"continue")}catch(t){return(0,b.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 b.Selector([()=>(0,b.sleep)(this.renewTokenIn,"renewToken"),()=>(0,b.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=S.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=S.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 i("unable to process SetPeerPosition command");break}case"UpdatePeer":{let r=S.RoomCommandsRpc.UpdatePeer.request.safeParse(A);r.success?this._UserData=r.data.user_data:i("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,b.failure)("connection is not established");let A=await this._MainConnection.getReconnectToken(this._OwnPeerId);return A.type==="Success"?(this._Token=A.value,(0,b.success)()):(0,b.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 hF(D,x,A){try{let F={jsonrpc:"2.0",id:1,method:"Connect",params:{}};f(`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(f(`received authentication response fom '${D}'`,t),"result"in t)return y.parse(t.result.token);{let e=t.error?.message??"malformed response";return u(`gateway rejected token; ${e}`),(0,b.success)(e)}}catch(F){return(0,b.failure)(String(F))}}function eA(D,x=8e3){return performance.now()-D>x}o();var cA=require("@4players/odin-common");var X=require("@4players/odin-common");o();var bA=require("@4players/odin-common");o();var sA=require("@msgpack/msgpack");o();var jA={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])},vA=D=>({name:"PBKDF2",hash:"SHA-256",iterations:600,salt:D}),BA=32,CA=1e6,EA=2147483648,fA=32,T=[79,68,73,78,1,75,105,109],nx=16,sx=64,nA=16;function iA(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 mF(D){return isFinite(D)}function qF(D){return Array.isArray(D)}function Tx(D){return mF(D)?D:v}function ux(D){return D instanceof Uint8Array?D:v}function GF(D,...x){let A;try{A=(0,sA.decode)(D)}catch{return v}if(!qF(A))return v;let F=new Array(A.length);for(let r in x)if(F[r]=x[r](A[r]),F[r]===v)return v;return F}function Mx(D,...x){if(D.length<T.length)return m;for(let A=0;A<T.length;A++)if(D[A]!==T[A])return m;return GF(D.subarray(T.length),...x)}var ix=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 e=0;e<t;e++)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 Ux=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(jA,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(vA(x),this.key,{name:"AES-GCM",length:256},!1,[A])}},Kx=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(BA)),F=await x.generatePeerKey(A,"encrypt");return new D(A,F)}get limitReached(){return this.key===void 0?!1:this.number_of_bytes>=EA||this.number_of_packets>=CA}nextSequenceNumber(x){return this.sequenceNumbers[x]++}};function i0(D,x){return{kind:"encrypted",key:D,material:x,antiReplays:{datagram:new ix(fA),userData:new ix(0),message:new ix(0)}}}var Vx=class D{constructor(x,A,F,r){this.additionalData=x;this.sequenceNumber=A;this.seed=F;this.encrypted=r}static parse(x){let A=Mx(x,ux,Tx,ux);if(A===v||A===m)return A;let[F,r,t]=A,e=x.subarray(0,x.length-t.length);return new D(e,r,F,t)}isSameSeed(x){return iA(this.seed,x.seed)}async generateKey(x){return await x.generatePeerKey(this.seed,"decrypt")}};function Wx(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 b0=require("@msgpack/msgpack"),aA=require("@4players/odin-common");o();var Qx=class{constructor(x){this.actions=x}changeKey(x){this.masterKey!==x&&(this.masterKey=x,this.ownKey=v,this.actions.resendUserData())}async encryptDatagram(x){let A=await this.getKey("datagram");return A===void 0?x:A===M?v:await gF(A,x)}async encryptMessage(x){let A=await this.getKey("message");return A===void 0?x:A===M?M:await oA(A,x,"message")}async encryptUserData(x){let A=await this.getKey("userData");return A===void 0?x:((0,aA.assert)(A!==M,"key unavailable for user data encryption"),await oA(A,x,"userData",A.seed))}async getKey(x){if(this.ownKey===v||this.ownKey?.limitReached)if(x==="userData")this.ownKey=this.masterKey?await Kx.create(this.masterKey):void 0;else return this.ownKey!==v&&(this.ownKey=v,this.actions.resendUserData()),M;return this.ownKey}reset(){this.ownKey=this.masterKey?v:void 0}};async function oA(D,x,A,...F){let r=D.nextSequenceNumber(A),t=x.length+nx,e=yF(r,F,t),j=e.length-t,B=await lA(D,A,r,e.subarray(0,j),x);return e.set(new Uint8Array(B),j),e}function yF(D,x,A){let F=[];x.forEach(e=>F.push(e)),F.push(D),F.push(new Uint8Array(A));let r=(0,b0.encode)(F),t=new Uint8Array(T.length+r.length);return t.set(T,0),t.set(r,T.length),t}async function gF(D,x){let A=IF(x);if(A===v)return v;if((A.kind&sx)!==0)return v;let F=A.body.length+nx,r=D.nextSequenceNumber("datagram"),t=(0,b0.encode)([A.kind|sx,A.mediaIds,r,new Uint8Array(F)]),e=t.length-F,j=await lA(D,"datagram",r,t.subarray(0,e),A.body);return t.set(j,e),t}async function lA(D,x,A,F,r){return new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:Wx(x,A),additionalData:F,tagLength:nx*8},D.key,r))}function IF(D){let x=new U(D),A=x.readArrayLength();if(s(A)||A<2)return v;let F=x.readNumber(),r=x.readArrayLength();if(s(F)||s(r))return v;if(r>nA)return v;let t=Array(r);for(let j=0;j<t.length;j++){let B=x.readNumber();if(s(B))return v;t[j]=B}let e=D.subarray(x.position);return{kind:F,mediaIds:t,body:e}}var uA=require("@msgpack/msgpack");o();var zx=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),e=i0(t,r),j=await Xx(e,"userData",r.additionalData,r.sequenceNumber,r.encrypted);j!==v?(this.peerKeys.set(A,e),this.actions.setUserData(A,j)):(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=_F(A);if(this.masterKey===void 0)return F===m?A:v;if(F===v||F===m)return v;let r=this.peerKeys.get(x);if(r?.kind!=="encrypted")return v;let t=await Xx(r,"datagram",F.additionalData,F.sequenceNumber,F.encrypted);return t===v?v:LF(F.kind&~sx,F.mediaIds,t)}async decryptMessage(x,A){let F=Mx(A,Tx,ux);if(this.masterKey===void 0)return F===m?A:v;if(F===v||F===m)return v;let r=this.peerKeys.get(x);if(r?.kind!=="encrypted")return v;let[t,e]=F,j=A.subarray(0,A.length-e.length);return Xx(r,"message",j,t,e)}async decryptUserData(x,A){let F=Vx.parse(A);if(F===v)return v;if(F===m)return this.peerKeys.delete(x),this.masterKey===void 0?A:v;if(this.masterKey===void 0)return this.peerKeys.set(x,{kind:"broken",material:F}),v;let r=this.peerKeys.get(x);if(r?.kind==="encrypted"&&r.material.isSameSeed(F))r.material=F;else{let e=await F.generateKey(this.masterKey);r=i0(e,F)}let t=await Xx(r,"userData",F.additionalData,F.sequenceNumber,F.encrypted);return t===v?this.peerKeys.set(x,{kind:"broken",material:F}):r!==void 0&&this.peerKeys.set(x,r),t}reset(){this.peerKeys.clear()}};function _F(D){let x=new U(D),A=x.readArrayLength();if(s(A)||A<1)return v;let F=x.readNumber();if(s(F))return v;if((F&sx)===0)return m;if(A!==4)return v;let r=x.position;x.readObjects(1);let t=D.subarray(r,x.position),e=x.readNumber(),j=x.readBytes();if(s(e)||s(j))return v;let B=D.subarray(0,D.length-j.length);return{kind:F,mediaIds:t,additionalData:B,sequenceNumber:e,encrypted:j}}async function Xx(D,x,A,F,r){let t=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:Wx(x,F),additionalData:A,tagLength:nx*8},D.key,r).catch(()=>v);return t===v?v:D.antiReplays[x].isReplay(F)?v:new Uint8Array(t)}function LF(D,x,A){let F=2;try{let e=new U(A);for(e.position=0;e.position<A.length;)e.readObjects(1),F+=1}catch{return v}let r=(0,uA.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 zx(A),r=new Qx(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===M);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 Ux.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 kA(D,x){return(0,cA.assert)(D.type==="OdinCrypto","only OdinCrypto supported"),new Zx(D,x)}var Yx=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,e=(0,w.unwrap)(y.parse(A.token)),j=A.roomId??e.defaultRoomId,B=A.userData??new Uint8Array(0),E=A.position??[0,0,0];(0,w.assert)(j!==void 0,"room id required for multi-room-tokens"),this.cipher=A.cipher?kA(A.cipher,new Jx(this)):void 0,this.onEvent=t,f(`creating new room '${j}' ${this.cipher?"with":"without"} cipher`,e,B,E),this._Connection=new Sx(x,A.transport??"H3",this._HandleEvent.bind(this),r?new URL(r):void 0,e,j,B,E,this.cipher,F?.disableAutoReconnect??!1)}get connectionStats(){let x={...w.CONNECTION_STATS_INITIAL};return this.mainConnection?this.mainConnection.connectionStats:x}async getRtcStats(){return this.mainConnection?.getRtcStats()}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 L){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,f(`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 O){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},f(`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 P){let A=this._Playbacks.get(x.uid)??{media:void 0,playback:void 0};if(A.playback!==void 0&&A.playback!==x&&(A.playback instanceof P?(A.playback.setMediaStream(void 0),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,f(`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 $){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},f(`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 L||x instanceof P){let A=this._Playbacks.get(x.uid);if(A?.playback!==x)return;A.playback=void 0,A.media!==void 0&&(x instanceof L?x.stop(A.media):(this.mainConnection?.stopRemoteVideo(A.media.mediaId),x.setMediaStream(void 0))),f(`unlinking playback media '${x.uid}' from room '${this._Connection.roomId}'`),this._Playbacks.set(x.uid,A)}else if(x instanceof O||x instanceof $){x instanceof $&&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 $&&this.mainConnection?.stopLocalVideo(A.media.mediaId)),f(`unlinking capture media '${x.uid}' from room '${this._Connection.roomId}'`),this._Captures.delete(x)}else throw new Error("invalid media")}close(){f(`closing room '${this._Connection.roomId}'`),this._Connection.close()}_HandleEvent(x,A){let F=E0(o0.RoomNotificationsRpc,{name:x,properties:A});F!==void 0&&(this._HandleKnownEvent(F),A=F.properties),this.onEvent(x,A)}_HandleKnownEvent(x){switch(n(`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 $,x instanceof O&&(x.stop(this._Connection,A.media),A.media=void 0));this._AvailableMediaIds.length=0}_HandleRoomUpdate(x){if(x.kind==="Joined"){(0,w.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 O&&x.start(this._Connection,A.media),x instanceof $)}_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,w.generateUUID)());A.properties.uid=r;let t=this._Playbacks.get(r)??{media:void 0,playback:void 0};if(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 L&&t.playback.start(t.media),t.playback instanceof P)){let e=t.playback;this.mainConnection.startRemoteVideo(t.media.mediaId).then(j=>{e.setMediaStream(new MediaStream([j]))}).catch(j=>{i(`failed to start remote video for media ${A.id}`,j)})}}_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.media.mediaId===A&&t.playback!==void 0&&(t.playback instanceof L&&t.playback.stop(t.media),t.playback instanceof P&&this.mainConnection?.stopRemoteVideo(t.media.mediaId),t.media=void 0),F.mediaIds.delete(A))}};qx();function HF(D,x){_0(x?.logger,x?.onLogMessage);let A,F=new Rx((t,e)=>A.receivePacket(t,e)),r=new gx(D);return A=new Ix(r,F.sendDatagram.bind(F),x?.enableHTMLAudioElementFallback??!1),new a0(F,A,x)}var ox=(0,l0.generateUUID)(),u0=[],dA=!1;function NF(){dA||typeof window>"u"||(window.addEventListener("beforeunload",()=>{for(let D of u0)D.deref()?.close()}),dA=!0)}var a0=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||NF(),this._ConnectionPool=x,this._MediaController=A,u0.push(new WeakRef(this)),f("plugin initialized")}get playbackVolume(){return this._PlaybackVolume}joinRoom(x){return new Yx(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 P(x.uid,x.customType)}enumerateDevices(){return mx()}setOutputVolume(x){this._MediaController.playbackSetGlobalVolume(x)}async setOutputDevice(x){await this._MediaController.playbackSetDevice(x.device)}close(){this._MediaController.close(),this._ConnectionPool.close(),f("plugin closed")}async dump(){return{createdAt:this._CreatedAt,connections:await this._ConnectionPool.dump(),medias:await this._MediaController.dump()}}};async function pA(){let D=[];for(let x of u0){let A=x.deref();A!==void 0&&D.push(await A.dump())}return JSON.stringify({timestamp:Date.now(),instances:D,background:await O0()})}globalThis.odin_debug_dump_state=pA;window!==void 0&&(window.odin_debug_dump_state=pA);0&&(module.exports={SESSION_ID,createPlugin});
|
|
6724
|
+
\`,new Function(F,E)}function KA(t,r,s,i,o,k){var a=r.length;a<2&&G("argTypes array size mismatch! Must at least get return value and receiver (this) types!");var u=r[1]!==null&&s!==null,d=_r(r),f=Lr(r),q=f&&!k&&!d;f&&!q&&(d=!0);var E=!r[0].isVoid,v=r[0],F=r[1],h=[t,G,i,o,yr,v.fromWireType.bind(v),F?.toWireType.bind(F)];q&&h.push(Qj,Vj);for(var m=2;m<a;++m){var N=r[m];h.push(N.toWireType.bind(N))}if(!d)for(var m=u?1:2;m<r.length;++m)r[m].destructorFunction!==null&&h.push(r[m].destructorFunction);var K=Ft(r,u,E,k)(...h);return Er(t,K)}var vt=(t,r,s,i,o,k)=>{var a=MA(r,s);o=O(i,o),w([],[t],u=>{u=u[0];var d=\`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]=()=>{z(\`Cannot construct \${u.name} due to unbound types\`,a)},w([],a,f=>(f.splice(1,0,null),u.registeredClass.constructor_body[r-1]=KA(d,f,null,o,k),[])),[]})},Hr=t=>{t=t.trim();let r=t.indexOf("(");return r===-1?t:t.slice(0,r)},It=(t,r,s,i,o,k,a,u,d,f)=>{var q=MA(s,i);r=y(r),r=Hr(r),k=O(o,k,d),w([],[t],E=>{E=E[0];var v=\`\${E.name}.\${r}\`;r.startsWith("@@")&&(r=Symbol[r.substring(2)]),u&&E.registeredClass.pureVirtualFunctions.push(r);function F(){z(\`Cannot call \${v} due to unbound types\`,q)}var h=E.registeredClass.instancePrototype,m=h[r];return m===void 0||m.overloadTable===void 0&&m.className!==E.name&&m.argCount===s-2?(F.argCount=s-2,F.className=E.name,h[r]=F):(hr(h,r,v),h[r].overloadTable[s-2]=F),w([],q,N=>{var L=KA(v,N,E,k,a,d);return h[r].overloadTable===void 0?(L.argCount=s-2,h[r]=L):h[r].overloadTable[s-2]=L,[]}),[]})},gr=(t,r,s)=>(t instanceof Object||G(\`\${s} with invalid "this": \${t}\`),t instanceof r.registeredClass.constructor||G(\`\${s} incompatible with "this" of type \${t.constructor.name}\`),t.$$.ptr||G(\`cannot call emscripten binding method \${s} on deleted object\`),fA(t.$$.ptr,t.$$.ptrType.registeredClass,r.registeredClass)),yt=(t,r,s,i,o,k,a,u,d,f)=>{r=y(r),o=O(i,o),w([],[t],q=>{q=q[0];var E=\`\${q.name}.\${r}\`,v={get(){z(\`Cannot access \${E} due to unbound types\`,[s,a])},enumerable:!0,configurable:!0};return d?v.set=()=>z(\`Cannot access \${E} due to unbound types\`,[s,a]):v.set=F=>G(E+" is a read-only property"),Object.defineProperty(q.registeredClass.instancePrototype,r,v),w([],d?[s,a]:[s],F=>{var h=F[0],m={get(){var L=gr(this,q,E+" getter");return h.fromWireType(o(k,L))},enumerable:!0};if(d){d=O(u,d);var N=F[1];m.set=function(L){var K=gr(this,q,E+" setter"),H=[];d(f,K,N.toWireType(H,L)),yr(H)}}return Object.defineProperty(q.registeredClass.instancePrototype,r,m),[]}),[]})},Dr=[],M=[0,1,,1,null,1,!0,1,!1,1],_t=t=>{if(t>9&&--M[t+1]===0){var r=M[t];M[t]=void 0,Dr.push(t)}},RA={toValue:t=>(t||G(\`Cannot use deleted val. handle = \${t}\`),M[t]),toHandle:t=>{switch(t){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:{let r=Dr.pop()||M.length;return M[r]=t,M[r+1]=1,r}}}},Lt={name:"emscripten::val",fromWireType:t=>{var r=RA.toValue(t);return _t(t),r},toWireType:(t,r)=>RA.toHandle(r),readValueFromPointer:GA,destructorFunction:null},Ht=t=>x(t,Lt),Br,xr,gt=(t,r)=>{switch(r){case 4:return function(s){return this.fromWireType(Br[s>>2])};case 8:return function(s){return this.fromWireType(xr[s>>3])};default:throw new TypeError(\`invalid float width (\${r}): \${t}\`)}},Dt=(t,r,s)=>{r=y(r),x(t,{name:r,fromWireType:i=>i,toWireType:(i,o)=>o,readValueFromPointer:gt(r,s),destructorFunction:null})},Bt=(t,r,s,i,o,k,a,u)=>{var d=MA(r,s);t=y(t),t=Hr(t),o=O(i,o,a),$r(t,function(){z(\`Cannot call \${t} due to unbound types\`,d)},r-1),w([],d,f=>{var q=[f[0],null].concat(f.slice(1));return vr(t,KA(t,q,null,o,k,a),r-1),[]})},xt=(t,r,s,i,o)=>{r=y(r);let k=i===0,a=d=>d;if(k){var u=32-8*s;a=d=>d<<u>>>u,o=a(o)}x(t,{name:r,fromWireType:a,toWireType:(d,f)=>f,readValueFromPointer:qr(r,s,i!==0),destructorFunction:null})},Nt=(t,r,s)=>{var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=i[r];function k(a){var u=$[a>>2],d=$[a+4>>2];return new o(U.buffer,d,u)}s=y(s),x(t,{name:s,fromWireType:k,readValueFromPointer:k},{ignoreDuplicateRegistrations:!0})},bt=(t,r,s,i)=>{if(!(i>0))return 0;for(var o=s,k=s+i-1,a=0;a<t.length;++a){var u=t.codePointAt(a);if(u<=127){if(s>=k)break;r[s++]=u}else if(u<=2047){if(s+1>=k)break;r[s++]=192|u>>6,r[s++]=128|u&63}else if(u<=65535){if(s+2>=k)break;r[s++]=224|u>>12,r[s++]=128|u>>6&63,r[s++]=128|u&63}else{if(s+3>=k)break;r[s++]=240|u>>18,r[s++]=128|u>>12&63,r[s++]=128|u>>6&63,r[s++]=128|u&63,a++}}return r[s]=0,s-o},Ot=(t,r,s)=>bt(t,g,r,s),Jt=t=>{for(var r=0,s=0;s<t.length;++s){var i=t.charCodeAt(s);i<=127?r++:i<=2047?r+=2:i>=55296&&i<=57343?(r+=4,++s):r+=3}return r},Nr=globalThis.TextDecoder&&new TextDecoder,br=(t,r,s,i)=>{var o=r+s;if(i)return o;for(;t[r]&&!(r>=o);)++r;return r},Or=(t,r=0,s,i)=>{var o=br(t,r,s,i);if(o-r>16&&t.buffer&&Nr)return Nr.decode(t.subarray(r,o));for(var k="";r<o;){var a=t[r++];if(!(a&128)){k+=String.fromCharCode(a);continue}var u=t[r++]&63;if((a&224)==192){k+=String.fromCharCode((a&31)<<6|u);continue}var d=t[r++]&63;if((a&240)==224?a=(a&15)<<12|u<<6|d:a=(a&7)<<18|u<<12|d<<6|t[r++]&63,a<65536)k+=String.fromCharCode(a);else{var f=a-65536;k+=String.fromCharCode(55296|f>>10,56320|f&1023)}}return k},Pt=(t,r,s)=>t?Or(g,t,r,s):"",wt=(t,r)=>{r=y(r);var s=!0;x(t,{name:r,fromWireType(i){var o=$[i>>2],k=i+4,a;if(s)a=Pt(k,o,!0);else{a="";for(var u=0;u<o;++u)a+=String.fromCharCode(g[k+u])}return J(i),a},toWireType(i,o){o instanceof ArrayBuffer&&(o=new Uint8Array(o));var k,a=typeof o=="string";a||ArrayBuffer.isView(o)&&o.BYTES_PER_ELEMENT==1||G("Cannot pass non-string to std::string"),s&&a?k=Jt(o):k=o.length;var u=VA(4+k+1),d=u+4;if($[u>>2]=k,a)if(s)Ot(o,d,k+1);else for(var f=0;f<k;++f){var q=o.charCodeAt(f);q>255&&(J(u),G("String has UTF-16 code units that do not fit in 8 bits")),g[d+f]=q}else g.set(o,d);return i!==null&&i.push(J,u),u},readValueFromPointer:GA,destructorFunction(i){J(i)}})},Jr=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Tt=(t,r,s)=>{var i=t>>1,o=br(rA,i,r/2,s);if(o-i>16&&Jr)return Jr.decode(rA.subarray(i,o));for(var k="",a=i;a<o;++a){var u=rA[a];k+=String.fromCharCode(u)}return k},St=(t,r,s=2147483647)=>{if(s<2)return 0;s-=2;for(var i=r,o=s<t.length*2?s/2:t.length,k=0;k<o;++k){var a=t.charCodeAt(k);cA[r>>1]=a,r+=2}return cA[r>>1]=0,r-i},Ut=t=>t.length*2,Mt=(t,r,s)=>{for(var i="",o=t>>2,k=0;!(k>=r/4);k++){var a=$[o+k];if(!a&&!s)break;i+=String.fromCodePoint(a)}return i},Kt=(t,r,s=2147483647)=>{if(s<4)return 0;for(var i=r,o=i+s-4,k=0;k<t.length;++k){var a=t.codePointAt(k);if(a>65535&&k++,dA[r>>2]=a,r+=4,r+4>o)break}return dA[r>>2]=0,r-i},Rt=t=>{for(var r=0,s=0;s<t.length;++s){var i=t.codePointAt(s);i>65535&&s++,r+=4}return r},Vt=(t,r,s)=>{s=y(s);var i,o,k;r===2?(i=Tt,o=St,k=Ut):(i=Mt,o=Kt,k=Rt),x(t,{name:s,fromWireType:a=>{var u=$[a>>2],d=i(a+4,u*r,!0);return J(a),d},toWireType:(a,u)=>{typeof u!="string"&&G(\`Cannot pass non-string to C++ string type \${s}\`);var d=k(u),f=VA(4+d+r);return $[f>>2]=d/r,o(u,f+4,d+r),a!==null&&a.push(J,f),f},readValueFromPointer:GA,destructorFunction(a){J(a)}})},Qt=(t,r)=>{r=y(r),x(t,{isVoid:!0,name:r,fromWireType:()=>{},toWireType:(s,i)=>{}})},Xt=t=>{kA("OOM")},Wt=t=>{var r=g.length;t>>>=0,Xt(t)},zt=t=>52,Zt=9007199254740992,Yt=-9007199254740992,An=t=>t<Yt||t>Zt?NaN:Number(t);function rn(t,r,s,i){return r=An(r),70}var jn=[null,[],[]],tn=(t,r)=>{var s=jn[t];!r||r===10?((t===1?b:aA)(Or(s)),s.length=0):s.push(r)},nn=(t,r,s,i)=>{for(var o=0,k=0;k<s;k++){var a=$[r>>2],u=$[r+4>>2];r+=8;for(var d=0;d<u;d++)tn(t,g[a+d]);o+=u}return $[i>>2]=o,0};st(),pt();{j.noExitRuntime&&(Rj=j.noExitRuntime),j.print&&(b=j.print),j.printErr&&(aA=j.printErr),j.arguments&&(C=j.arguments),j.thisProgram&&(p=j.thisProgram);var Z=j.preInit;if(Z)for(typeof Z=="function"&&(j.preInit=Z=[Z]);Z.length>0;)Z.shift()()}var Pr,VA,J,wr,Tr,en,sn,Sr,Ur;function ln(t){Pr=t.w,VA=j._malloc=t.y,J=j._free=t.z,wr=t.A,Tr=t.B,en=Sr=t.u,sn=Ur=t.x}var on={i:Zj,r:Yj,g:rt,l:jt,k:$t,j:vt,d:It,a:yt,s:Ht,f:Dt,n:Bt,c:xt,b:Nt,t:wt,e:Vt,m:Qt,o:Wt,q:zt,p:rn,h:nn};async function an(){Oj();var t=j.setStatus;t&&(t("Running..."),await new Promise(r=>setTimeout(r,1)),setTimeout(t,1,"")),!or&&(Jj(),j.onRuntimeInitialized?.(),Pj())}var tA;return tA=await Kj(),await an(),j}})();typeof Ij=="object"&&typeof PA=="object"?(PA.exports=er,PA.exports.default=er):typeof define=="function"&&define.amd&&define([],()=>er)});var T={};Gn(T,{AdditionalCaptureBlocks:()=>hn,AdditionalPlaybackBlocks:()=>mn,ClockJumpCheckInterval:()=>Ln,ClockJumpThreshold:()=>Hn,ConnectInterval:()=>Tn,ConnectTimeout:()=>Jn,DefaultRefreshRate:()=>Fn,DefaultVideoCodec:()=>Un,HealthCheckTimeout:()=>_n,MainConnectionPingInterval:()=>gn,MaxNumberOfDecoders:()=>In,MaxReconnectDuration:()=>Sn,MinDBFs:()=>Vr,MinTokenLifetime:()=>Pn,MinTokenRefreshInterval:()=>wn,PlaybackPreload:()=>$n,RenderQuantumSize:()=>yn,VadPreload:()=>vn,WebRtcAnswerTimeout:()=>Nn,WebRtcIceTimeout:()=>Bn,WebRtcMaxNegotiationAttempts:()=>bn,WebRtcRecoveryDelays:()=>On,WebRtcStatsSnapshotInterval:()=>Dn,WebRtcTimeout:()=>xn});var mn=3,hn=3,$n=3,Fn=250,vn=3,In=512,yn=128,Vr=-758.596,_n=1e4,Ln=1e3,Hn=1e4,gn=3e3,Dn=1e3,Bn=3e3,xn=1e4,Nn=1e4,bn=3,On=[0,2e3,5e3],Jn=5e3,Pn=6e4,wn=5e3,Tn=[0,100,200,200,500],Sn=12e4,Un="H264";function S(n,A,j){return n.postMessage(A,j)}function Qr(n){return[n.values[0],n.values[1]]}function hA(n,A){n.values[0]=A[0],n.values[1]=A[1]}function $A(n,A){return n.values[2+A*5]}function Xr(n,A,j){n.values[2+A*5]=j}function Wr(n,A){let j=2+A*5+1;return[n.values[j+0],n.values[j+1]]}function FA(n,A,j){let e=2+A*5+1;n.values[e+0]=j[0],n.values[e+1]=j[1]}function zr(n,A){return n.values[2+A*5+3]}function Zr(n,A,j){n.values[2+A*5+3]=j}function Yr(n,A){return n.values[2+A*5+4]}function Aj(n,A,j){n.values[2+A*5+4]=j}function vA(n){return n.values[0]!==0}function IA(n){return n.values[1]}function yA(n){return n.values[2]}function rj(n){return n.values[3]}function _A(n,A){return n.values[3]=A}function jj(n){return n?Array.from(n).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var Mn;(n=>{let A;(j=>(j[j.InvalidPassword=-1]="InvalidPassword",j[j.Unknown=0]="Unknown",j[j.Unencrypted=1]="Unencrypted",j[j.Encrypted=2]="Encrypted"))(A=n.PeerCipherStatus||={})})(Mn||={});function lj(n){return{type:"Success",value:n}}function D(n){return{type:"Failure",reason:n}}var{Deno:tj}=globalThis,Kn=typeof tj?.noColor=="boolean"?tj.noColor:!1,Rn=!Kn;function zA(n,A){return{open:\`\\x1B[\${n.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function ZA(n,A){return Rn?\`\${A.open}\${n.replace(A.regexp,A.open)}\${A.close}\`:n}function WA(n){return ZA(n,zA([0],0))}function nj(n){return ZA(n,zA([1],22))}function Vn(n){return ZA(n,zA([2],22))}var Se=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,LA=(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))(LA||{}),ij={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},Xn={4:Vn,3:WA,2:WA,1:nj,0:nj};function Wn({message:n}){return String(n)}function ej(n){return JSON.stringify({timestamp:n.date.toISOString(),level:LA[n.level],message:n.message,extra:n.extra})}function sj(n){function A(C,p){return[Math.floor(C/p),C%p]}function j(){let C,p=n.date.valueOf()-Qn.valueOf();[p,C]=A(p,1e3);let[I,B]=A(p,60);return\`\${I.toString().padStart(4,"0")}:\${B.toString().padStart(2,"0")}.\${C.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 l=ij[n.level],c=n.logger.name!==void 0?\`@\${n.logger.name}\`:"";return\`\${WA(j())}\${c} \${l} \${Xn[n.level](String(n.message))}\${e()}\`}function zn(n){let A=\`[\${n.date.toISOString()}]\`,j=\`[\${LA[n.level]}]\`,e=n.logger.name!==void 0?\`[\${n.logger.name}] \`:"",l=ij[n.level];return\`\${A} \${l} \${j.padEnd(7," ")} \${e}\${n.message}\`}function Zn(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var oj=class{static sparse=Wn;static json=ej;static pretty=sj;static structured=zn;static default=Zn()?sj:ej;constructor(){}};var Yn=class{formatter;consoleObject;filter;constructor(n=oj.default,A=4,j=console){this.filter=A,this.formatter=n,this.consoleObject=j}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,j=[],e=void 0){this.#A=A,this.sinks=j,this.filter=n,this.parent=e}log(n,A,j=void 0){let e={date:new Date,level:n,logger:this,message:A,extra:j};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=globalThis[Symbol.for("odin-global-logger")]??=new R(3,void 0,[new Yn]),Ae=R.prototype.log.bind(nA,1),re=R.prototype.log.bind(nA,2),aj=R.prototype.log.bind(nA,3),je=R.prototype.log.bind(nA,4),Ue=R.prototype.log.bind(nA);var kj;function uj(n,...A){let j=te(A);kj?kj?.info(n,j):aj(n,j)}function te(...n){if(n.length===1&&typeof n[0]=="object"&&n[0]!==null)return{...n[0]};if(n.length>0)return{args:n}}function HA(n){return n.connectionId*4294967296+n.mediaId}function cj(n){return{mediaId:n%4294967296,connectionId:Math.floor(n/4294967296)}}function P(n,A,j){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 l=n._malloc(j*e.BYTES_PER_ELEMENT);if(l===0||l%e.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${j} \${A} array\`);let c=l/e.BYTES_PER_ELEMENT;return e.subarray(c,c+j)}function V(n,A){n._free(A.byteOffset)}function dj(n,A){return{values:P(n,"f32",2+A*5),length:A}}function Cj(n,A){V(n,A.values)}function qj(n){return{values:P(n,"f32",4)}}function fj(n,A){V(n,A.values)}function Gj(n){let A=n.length,j=0,e=0;for(;e<A;){let l=n.charCodeAt(e++);if((l&4294967168)===0){j++;continue}else if((l&4294965248)===0)j+=2;else{if(l>=55296&&l<=56319&&e<A){let c=n.charCodeAt(e);(c&64512)===56320&&(++e,l=((l&1023)<<10)+(c&1023)+65536)}(l&4294901760)===0?j+=3:j+=4}}return j}function ne(n,A,j){let e=n.length,l=j,c=0;for(;c<e;){let C=n.charCodeAt(c++);if((C&4294967168)===0){A[l++]=C;continue}else if((C&4294965248)===0)A[l++]=C>>6&31|192;else{if(C>=55296&&C<=56319&&c<e){let p=n.charCodeAt(c);(p&64512)===56320&&(++c,C=((C&1023)<<10)+(p&1023)+65536)}(C&4294901760)===0?(A[l++]=C>>12&15|224,A[l++]=C>>6&63|128):(A[l++]=C>>18&7|240,A[l++]=C>>12&63|128,A[l++]=C>>6&63|128)}A[l++]=C&63|128}}var ee=new TextEncoder,se=50;function le(n,A,j){ee.encodeInto(n,A.subarray(j))}function pj(n,A,j){n.length>se?le(n,A,j):ne(n,A,j)}var ie=4096;function YA(n,A,j){let e=A,l=e+j,c=[],C="";for(;e<l;){let p=n[e++];if((p&128)===0)c.push(p);else if((p&224)===192){let I=n[e++]&63;c.push((p&31)<<6|I)}else if((p&240)===224){let I=n[e++]&63,B=n[e++]&63;c.push((p&31)<<12|I<<6|B)}else if((p&248)===240){let I=n[e++]&63,B=n[e++]&63,wA=n[e++]&63,b=(p&7)<<18|I<<12|B<<6|wA;b>65535&&(b-=65536,c.push(b>>>10&1023|55296),b=56320|b&1023),c.push(b)}else c.push(p);c.length>=ie&&(C+=String.fromCharCode(...c),c.length=0)}return c.length>0&&(C+=String.fromCharCode(...c)),C}var oe=new TextDecoder,ae=200;function ke(n,A,j){let e=n.subarray(A,A+j);return oe.decode(e)}function Ej(n,A,j){return j>ae?ke(n,A,j):YA(n,A,j)}var Q=class{type;data;constructor(A,j){this.type=A,this.data=j}};var _=class n extends Error{constructor(A){super(A);let j=Object.create(n.prototype);Object.setPrototypeOf(this,j),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:n.name})}};function mj(n,A,j){let e=j/4294967296,l=j;n.setUint32(A,e),n.setUint32(A+4,l)}function gA(n,A,j){let e=Math.floor(j/4294967296),l=j;n.setUint32(A,e),n.setUint32(A+4,l)}function DA(n,A){let j=n.getInt32(A),e=n.getUint32(A+4);return j*4294967296+e}function hj(n,A){let j=n.getUint32(A),e=n.getUint32(A+4);return j*4294967296+e}var ue=-1,ce=4294967296-1,de=17179869184-1;function Ce({sec:n,nsec:A}){if(n>=0&&A>=0&&n<=de)if(A===0&&n<=ce){let j=new Uint8Array(4);return new DataView(j.buffer).setUint32(0,n),j}else{let j=n/4294967296,e=n&4294967295,l=new Uint8Array(8),c=new DataView(l.buffer);return c.setUint32(0,A<<2|j&3),c.setUint32(4,e),l}else{let j=new Uint8Array(12),e=new DataView(j.buffer);return e.setUint32(0,A),gA(e,4,n),j}}function qe(n){let A=n.getTime(),j=Math.floor(A/1e3),e=(A-j*1e3)*1e6,l=Math.floor(e/1e9);return{sec:j+l,nsec:e-l*1e9}}function fe(n){if(n instanceof Date){let A=qe(n);return Ce(A)}else return null}function Ge(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 j=A.getUint32(0),e=A.getUint32(4),l=(j&3)*4294967296+e,c=j>>>2;return{sec:l,nsec:c}}case 12:{let j=DA(A,4),e=A.getUint32(0);return{sec:j,nsec:e}}default:throw new _(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${n.length}\`)}}function pe(n){let A=Ge(n);return new Date(A.sec*1e3+A.nsec/1e6)}var $j={type:ue,encode:fe,decode:pe};var Y=class n{static defaultCodec=new n;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register($j)}register({type:A,encode:j,decode:e}){if(A>=0)this.encoders[A]=j,this.decoders[A]=e;else{let l=-1-A;this.builtInEncoders[l]=j,this.builtInDecoders[l]=e}}tryToEncode(A,j){for(let e=0;e<this.builtInEncoders.length;e++){let l=this.builtInEncoders[e];if(l!=null){let c=l(A,j);if(c!=null){let C=-1-e;return new Q(C,c)}}}for(let e=0;e<this.encoders.length;e++){let l=this.encoders[e];if(l!=null){let c=l(A,j);if(c!=null){let C=e;return new Q(C,c)}}}return A instanceof Q?A:null}decode(A,j,e){let l=j<0?this.builtInDecoders[-1-j]:this.decoders[j];return l?l(A,j,e):new Q(j,A)}};function Ee(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function eA(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):Ee(n)?new Uint8Array(n):Uint8Array.from(n)}var me=100,he=2048,BA=class n{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(A){this.extensionCodec=A?.extensionCodec??Y.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??me,this.initialBufferSize=A?.initialBufferSize??he,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,j){if(j>this.maxDepth)throw new Error(\`Too deep objects in depth \${j}\`);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,j)}ensureBufferSizeToWrite(A){let j=this.pos+A;this.view.byteLength<j&&this.resizeBuffer(j*2)}resizeBuffer(A){let j=new ArrayBuffer(A),e=new Uint8Array(j),l=new DataView(j);e.set(this.bytes),this.view=l,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=Gj(A);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),pj(A,this.bytes,this.pos),this.pos+=e}encodeObject(A,j){let e=this.extensionCodec.tryToEncode(A,this.context);if(e!=null)this.encodeExtension(e);else if(Array.isArray(A))this.encodeArray(A,j);else if(ArrayBuffer.isView(A))this.encodeBinary(A);else if(typeof A=="object")this.encodeMap(A,j);else throw new Error(\`Unrecognized object: \${Object.prototype.toString.apply(A)}\`)}encodeBinary(A){let j=A.byteLength;if(j<256)this.writeU8(196),this.writeU8(j);else if(j<65536)this.writeU8(197),this.writeU16(j);else if(j<4294967296)this.writeU8(198),this.writeU32(j);else throw new Error(\`Too large binary: \${j}\`);let e=eA(A);this.writeU8a(e)}encodeArray(A,j){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 l of A)this.doEncode(l,j+1)}countWithoutUndefined(A,j){let e=0;for(let l of j)A[l]!==void 0&&e++;return e}encodeMap(A,j){let e=Object.keys(A);this.sortKeys&&e.sort();let l=this.ignoreUndefined?this.countWithoutUndefined(A,e):e.length;if(l<16)this.writeU8(128+l);else if(l<65536)this.writeU8(222),this.writeU16(l);else if(l<4294967296)this.writeU8(223),this.writeU32(l);else throw new Error(\`Too large map object: \${l}\`);for(let c of e){let C=A[c];this.ignoreUndefined&&C===void 0||(this.encodeString(c),this.doEncode(C,j+1))}}encodeExtension(A){if(typeof A.data=="function"){let e=A.data(this.pos+6),l=e.length;if(l>=4294967296)throw new Error(\`Too large extension object: \${l}\`);this.writeU8(201),this.writeU32(l),this.writeI8(A.type),this.writeU8a(e);return}let j=A.data.length;if(j===1)this.writeU8(212);else if(j===2)this.writeU8(213);else if(j===4)this.writeU8(214);else if(j===8)this.writeU8(215);else if(j===16)this.writeU8(216);else if(j<256)this.writeU8(199),this.writeU8(j);else if(j<65536)this.writeU8(200),this.writeU16(j);else if(j<4294967296)this.writeU8(201),this.writeU32(j);else throw new Error(\`Too large extension object: \${j}\`);this.writeI8(A.type),this.writeU8a(A.data)}writeU8(A){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,A),this.pos++}writeU8a(A){let j=A.length;this.ensureBufferSizeToWrite(j),this.bytes.set(A,this.pos),this.pos+=j}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),mj(this.view,this.pos,A),this.pos+=8}writeI64(A){this.ensureBufferSizeToWrite(8),gA(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 Ar(n,A){return new BA(A).encodeSharedRef(n)}function xA(n){return\`\${n<0?"-":""}0x\${Math.abs(n).toString(16).padStart(2,"0")}\`}var $e=16,Fe=16,NA=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(A=$e,j=Fe){this.maxKeyLength=A,this.maxLengthPerKey=j,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,j,e){let l=this.caches[e-1];A:for(let c of l){let C=c.bytes;for(let p=0;p<e;p++)if(C[p]!==A[j+p])continue A;return c.str}return null}store(A,j){let e=this.caches[A.length-1],l={bytes:A,str:j};e.length>=this.maxLengthPerKey?e[Math.random()*e.length|0]=l:e.push(l)}decode(A,j,e){let l=this.find(A,j,e);if(l!=null)return this.hit++,l;this.miss++;let c=YA(A,j,e),C=Uint8Array.prototype.slice.call(A,j,j+e);return this.store(C,c),c}};var rr="array",iA="map_key",vj="map_value",ve=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new _("The type of key must be string or number but "+typeof n)},jr=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let j=this.getUninitializedStateFromPool();j.type=rr,j.position=0,j.size=A,j.array=new Array(A)}pushMapState(A){let j=this.getUninitializedStateFromPool();j.type=iA,j.readCount=0,j.size=A,j.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===rr){let e=A;e.size=0,e.array=void 0,e.position=0,e.type=void 0}if(A.type===iA||A.type===vj){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,tr=new DataView(new ArrayBuffer(0)),Ie=new Uint8Array(tr.buffer);try{tr.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 Fj=new RangeError("Insufficient data"),ye=new NA,bA=class n{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=tr;bytes=Ie;headByte=lA;stack=new jr;entered=!1;constructor(A){this.extensionCodec=A?.extensionCodec??Y.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:ye,this.mapKeyConverter=A?.mapKeyConverter??ve}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 j=eA(A);this.bytes=j,this.view=new DataView(j.buffer,j.byteOffset,j.byteLength),this.pos=0}appendBuffer(A){if(this.headByte===lA&&!this.hasRemaining(1))this.setBuffer(A);else{let j=this.bytes.subarray(this.pos),e=eA(A),l=new Uint8Array(j.length+e.length);l.set(j),l.set(e,j.length),this.setBuffer(l)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:j,pos:e}=this;return new RangeError(\`Extra \${j.byteLength-e} of \${j.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 j=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return j}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 j=!1,e;for await(let p of A){if(j)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(p);try{e=this.doDecodeSync(),j=!0}catch(I){if(!(I instanceof RangeError))throw I}this.totalPos+=this.pos}if(j){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return e}let{headByte:l,pos:c,totalPos:C}=this;throw new RangeError(\`Insufficient data in parsing \${xA(l)} at \${C} (\${c} 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,j){if(this.entered){yield*this.clone().decodeMultiAsync(A,j);return}try{this.entered=!0;let e=j,l=-1;for await(let c of A){if(j&&l===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c),e&&(l=this.readArraySize(),e=!1,this.complete());try{for(;yield this.doDecodeSync(),--l!==0;);}catch(C){if(!(C instanceof RangeError))throw C}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){A:for(;;){let A=this.readHeadByte(),j;if(A>=224)j=A-256;else if(A<192)if(A<128)j=A;else if(A<144){let l=A-128;if(l!==0){this.pushMapState(l),this.complete();continue A}else j={}}else if(A<160){let l=A-144;if(l!==0){this.pushArrayState(l),this.complete();continue A}else j=[]}else{let l=A-160;j=this.decodeString(l,0)}else if(A===192)j=null;else if(A===194)j=!1;else if(A===195)j=!0;else if(A===202)j=this.readF32();else if(A===203)j=this.readF64();else if(A===204)j=this.readU8();else if(A===205)j=this.readU16();else if(A===206)j=this.readU32();else if(A===207)this.useBigInt64?j=this.readU64AsBigInt():j=this.readU64();else if(A===208)j=this.readI8();else if(A===209)j=this.readI16();else if(A===210)j=this.readI32();else if(A===211)this.useBigInt64?j=this.readI64AsBigInt():j=this.readI64();else if(A===217){let l=this.lookU8();j=this.decodeString(l,1)}else if(A===218){let l=this.lookU16();j=this.decodeString(l,2)}else if(A===219){let l=this.lookU32();j=this.decodeString(l,4)}else if(A===220){let l=this.readU16();if(l!==0){this.pushArrayState(l),this.complete();continue A}else j=[]}else if(A===221){let l=this.readU32();if(l!==0){this.pushArrayState(l),this.complete();continue A}else j=[]}else if(A===222){let l=this.readU16();if(l!==0){this.pushMapState(l),this.complete();continue A}else j={}}else if(A===223){let l=this.readU32();if(l!==0){this.pushMapState(l),this.complete();continue A}else j={}}else if(A===196){let l=this.lookU8();j=this.decodeBinary(l,1)}else if(A===197){let l=this.lookU16();j=this.decodeBinary(l,2)}else if(A===198){let l=this.lookU32();j=this.decodeBinary(l,4)}else if(A===212)j=this.decodeExtension(1,0);else if(A===213)j=this.decodeExtension(2,0);else if(A===214)j=this.decodeExtension(4,0);else if(A===215)j=this.decodeExtension(8,0);else if(A===216)j=this.decodeExtension(16,0);else if(A===199){let l=this.lookU8();j=this.decodeExtension(l,1)}else if(A===200){let l=this.lookU16();j=this.decodeExtension(l,2)}else if(A===201){let l=this.lookU32();j=this.decodeExtension(l,4)}else throw new _(\`Unrecognized type byte: \${xA(A)}\`);this.complete();let e=this.stack;for(;e.length>0;){let l=e.top();if(l.type===rr)if(l.array[l.position]=j,l.position++,l.position===l.size)j=l.array,e.release(l);else continue A;else if(l.type===iA){if(j==="__proto__")throw new _("The key __proto__ is not allowed");l.key=this.mapKeyConverter(j),l.type=vj;continue A}else if(l.map[l.key]=j,l.readCount++,l.readCount===l.size)j=l.map,e.release(l);else{l.key=null,l.type=iA;continue A}}return j}}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 _(\`Unrecognized array type byte: \${xA(A)}\`)}}}pushMapState(A){if(A>this.maxMapLength)throw new _(\`Max length exceeded: map length (\${A}) > maxMapLengthLength (\${this.maxMapLength})\`);this.stack.pushMapState(A)}pushArrayState(A){if(A>this.maxArrayLength)throw new _(\`Max length exceeded: array length (\${A}) > maxArrayLength (\${this.maxArrayLength})\`);this.stack.pushArrayState(A)}decodeString(A,j){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(A,j):this.decodeBinary(A,j)}decodeUtf8String(A,j){if(A>this.maxStrLength)throw new _(\`Max length exceeded: UTF-8 byte length (\${A}) > maxStrLength (\${this.maxStrLength})\`);if(this.bytes.byteLength<this.pos+j+A)throw Fj;let e=this.pos+j,l;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?l=this.keyDecoder.decode(this.bytes,e,A):l=Ej(this.bytes,e,A),this.pos+=j+A,l}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===iA:!1}decodeBinary(A,j){if(A>this.maxBinLength)throw new _(\`Max length exceeded: bin length (\${A}) > maxBinLength (\${this.maxBinLength})\`);if(!this.hasRemaining(A+j))throw Fj;let e=this.pos+j,l=this.bytes.subarray(e,e+A);return this.pos+=j+A,l}decodeExtension(A,j){if(A>this.maxExtLength)throw new _(\`Max length exceeded: ext length (\${A}) > maxExtLength (\${this.maxExtLength})\`);let e=this.view.getInt8(this.pos+j),l=this.decodeBinary(A,j+1);return this.extensionCodec.decode(l,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=hj(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 oA=class n{constructor(A,j,e,l,c){this.mediaIds=A;this.sequenceNumber=j;this.timeStamp=e;this.isEndOfSpurt=l;this.payload=c}static parse(A){let j;try{j=nr(A)}catch{return D("not valid msgpack")}if(!Array.isArray(j))return D("container must be an array");if(j.length<6)return D("missing fields");if(j[0]!==1)return D("unknown type");if(!Array.isArray(j[1]))return D("media ids must be an array");if(!j[1].every(B=>typeof B=="number"))return D("media ids must be numbers");if(typeof j[2]!="number")return D("sequence number must be a number");if(typeof j[3]!="number")return D("timestamp must be a number");if(typeof j[4]!="number")return D("flags must be a number");let e=j[1],l=j[2]>>>0,c=j[3]>>>0,p=(j[4]&1)!==0,I=j[j.length-1];return I instanceof Uint8Array?lj(new n(e,l,c,p,I)):D("payload must be bytes")}toBytes(){let A=Number(this.isEndOfSpurt),j=[1,this.mediaIds,this.sequenceNumber>>>0,this.timeStamp>>>0,A,this.payload];return new Uint8Array(Ar(j,{forceFloat32:!0,ignoreUndefined:!0}))}};var OA=class{constructor(A,j){this.sampleRate=A;this.wasm=j;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 j.Encoder(A,15,!0,T.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=qj(this.wasm),this.outBuffer=P(this.wasm,"u8",1270),_A(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:j})=>j.length>0)}close(){fj(this.wasm,this.information),V(this.wasm,this.outBuffer),this.encoder.delete()}encode(A){for(this.encoder.push(A.byteOffset,this.information.values.byteOffset);;){let j=this.encoder.pop(this.connections.length===0?0:this.outBuffer.byteOffset,this.outBuffer.length);if(j===0)break;if(j<0){uj(\`failed encoding packet: \${j}\`);return}if(this.timestamp=this.timestamp+1800>>0,j===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(l=>l.id===0);for(let l of this.connections){if(this.monitoring&&l.id!==0)continue;let c=new oA(l.mediaIds,this.sequenceNumber,this.timestamp,e,this.outBuffer.subarray(0,j));S(globalThis,["sendPacket",{connectionId:l.id,packet:c.toBytes()}])}}}onMessage(A){let[j,e]=A;switch(j){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:vA(this.information),speechProbability:IA(this.information),rmsDBFS:yA(this.information),volume:rj(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}}}},JA=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=P(this.wasm,"u32",T.MaxNumberOfDecoders),this.information=dj(this.wasm,T.MaxNumberOfDecoders),hA(this.information,[1,1])}close(){Cj(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,j){this.stats.numberPackets++;let e=oA.parse(j);if(e.type==="Failure"){this.stats.numberPacketError++;let l=Array.from(j).map(c=>c.toString(16).padStart(2,"0")).join("");console.error(\`failed decoding audio packet; reason: \${e.reason}, connection: \${A}, dump: \${l}\`);return}for(let l of e.value.mediaIds){let c=this.medias.get(HA({connectionId:A,mediaId:l}));if(c===void 0){this.stats.numberPacketsMediaNotFound++;continue}c.lastPacket=j;let C=P(this.wasm,"u8",e.value.payload.length);C.set(e.value.payload),c.decoder.push(e.value.sequenceNumber,e.value.timeStamp,e.value.isEndOfSpurt,C.byteOffset,C.length)}}insertMedia(A,j,e,l=[1,1]){let c=HA({connectionId:j,mediaId:e}),C=new this.wasm.Decoder;this.medias.set(c,{index:A,decoder:C,lastPacket:void 0}),this.decoders[A]=C.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),FA(this.information,A,l),Aj(this.information,A,0),Zr(this.information,A,0)}removeMedia(A,j,e){let l=HA({connectionId:j,mediaId:e}),c=this.medias.get(l);if(!(c===void 0||c.index!==A)&&(this.medias.delete(l),Xr(this.information,A,0),this.decoders[A]=0,c.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[j,e]=A;switch(j){case"playbackReceivePacket":this.receivePacket(e.connectionId,e.packet);break;case"playbackUpdateMedias":for(let{index:l,connectionId:c,mediaId:C}of e.removed)this.removeMedia(l,c,C);for(let{index:l,connectionId:c,mediaId:C,volume:p}of e.added)this.insertMedia(l,c,C,p);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){let A=[];for(let[j,e]of this.medias){let l=cj(j);A.push({index:e.index,connectionId:l.connectionId,mediaId:l.mediaId,rmsDBFS:$A(this.information,e.index),volume:Wr(this.information,e.index),voicedBlocks:Yr(this.information,e.index),silentBlocks:zr(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:jj(e.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:Qr(this.information),decoders:A}}};var gj=En(yj()),_j=(0,gj.default)(),Lj,Hj;globalThis.addEventListener("message",n=>{sr(n).catch(console.error)});async function sr(n){let A=n.data,[j,e]=A;switch(j){case"captureInit":e.workletPort.onmessage=sr,Lj=new lr(e.sampleRate,await _j,e.refreshRate);break;case"playbackInit":e.workletPort.onmessage=sr,Hj=new ir(await _j,e.workletPort,e.refreshRate);break;case"close":globalThis.close();break}Lj?.onMessage(A),Hj?.onMessage(A)}var lr=class extends OA{constructor(j,e,l){super(j,e);this.sampleRate=j;this.inBuffer=P(this.wasm,"f32",j*.02),this.updateHandle=setInterval(()=>this.update(),l),S(globalThis,["captureReady",{}])}close(){super.close(),V(this.wasm,this.inBuffer),clearInterval(this.updateHandle)}onMessage(j){super.onMessage(j);let[e,l]=j;switch(e){case"captureSetVolume":this.setVolume(l.value);break;case"captureTick":this.tick(l.buffer);break}}setVolume(j){_A(this.information,j)}tick(j){this.inBuffer.set(j,0),this.encode(this.inBuffer)}update(){S(globalThis,["captureUpdate",{active:vA(this.information),rmsDBFs:yA(this.information),speechProbability:IA(this.information)}])}dump(){return{type:"unshared capture worker",sampleRate:this.sampleRate,...super.dump()}}},ir=class extends JA{constructor(j,e,l){super(j);this.workletPort=e;this.id=T.PlaybackPreload,this.outBuffer=P(this.wasm,"f32",48e3*.02*2),this.updateHandle=setInterval(()=>this.update(),l),S(globalThis,["playbackReady",{}])}close(){super.close(),V(this.wasm,this.outBuffer),clearInterval(this.updateHandle)}onMessage(j){super.onMessage(j);let[e,l]=j;switch(e){case"playbackSetVolume":this.setVolume(l.index,l.value);break;case"playbackTick":this.tick();break}}setVolume(j,e){j==="global"?hA(this.information,e):FA(this.information,j,e)}tick(){this.stats.numberTicks++,this.id+=1;let{hasAudio:j}=this.decode(this.outBuffer);if(j){let e=this.outBuffer.slice();S(this.workletPort,["samples",{id:this.id,buffer:e}],[e.buffer])}}update(){let j=new Float32Array(this.information.length*2);for(let l=0;l<=this.largestIndex;l++)j[l]=$A(this.information,l);let e=[];for(let[l,c]of this.medias)e[c.index]={packetsBuffered:c.decoder.cache_length,packetsSeen:c.decoder.packets_seen,packetsProcessed:c.decoder.packets_processed,packetsTooEarly:c.decoder.packets_too_early,packetsTooLate:c.decoder.packets_too_late,packetsDropped:0,packetsInvalid:c.decoder.packets_invalid,packetsRepeated:c.decoder.packets_repeated,packetsLost:c.decoder.packets_lost};S(globalThis,["playbackUpdate",{activities:j,jitterStats:e}],[j.buffer])}dump(){return{type:"unshared playback worker",id:this.id,...super.dump()}}};})();
|
|
6725
|
+
`});var E0,V0=p(()=>{E0='"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:()=>E,AdditionalPlaybackBlocks:()=>R,ClockJumpCheckInterval:()=>_,ClockJumpThreshold:()=>N,ConnectInterval:()=>Y,ConnectTimeout:()=>Z,DefaultRefreshRate:()=>D,DefaultVideoCodec:()=>X,HealthCheckTimeout:()=>O,MainConnectionPingInterval:()=>W,MaxNumberOfDecoders:()=>L,MaxReconnectDuration:()=>K,MinDBFs:()=>v,MinTokenLifetime:()=>q,MinTokenRefreshInterval:()=>Q,PlaybackPreload:()=>F,RenderQuantumSize:()=>V,VadPreload:()=>C,WebRtcAnswerTimeout:()=>H,WebRtcIceTimeout:()=>$,WebRtcMaxNegotiationAttempts:()=>J,WebRtcRecoveryDelays:()=>z,WebRtcStatsSnapshotInterval:()=>j,WebRtcTimeout:()=>G});var R=3,E=3,F=3,D=250,C=3,L=512,V=128,v=-758.596,O=1e4,_=1e3,N=1e4,W=3e3,j=1e3,$=3e3,G=1e4,H=1e4,J=3,z=[0,2e3,5e3],Z=5e3,q=6e4,Q=5e3,Y=[0,100,200,200,500],K=12e4,X="H264";function d(e,t,r){return e.postMessage(t,r)}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:k}=globalThis,te=typeof k?.noColor=="boolean"?k.noColor:!1,re=!te;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 re?`${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 ne(e){return h(e,m([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,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}"},oe={4:ne,3:p,2:p,1:U,0:U};function ae({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()-se.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],a=e.logger.name!==void 0?`@${e.logger.name}`:"";return`${p(r())}${a} ${s} ${oe[e.level](String(e.message))}${n()}`}function ie(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 ce(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var w=class{static sparse=ae;static json=S;static pretty=I;static structured=ie;static default=ce()?I:S;constructor(){}};var ue=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 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=globalThis[Symbol.for("odin-global-logger")]??=new o(3,void 0,[new ue]),le=o.prototype.log.bind(l,1),fe=o.prototype.log.bind(l,2),de=o.prototype.log.bind(l,3),pe=o.prototype.log.bind(l,4),we=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 Q0={};kx(Q0,{UnsharedCaptureWorker:()=>Gx,UnsharedPlaybackWorker:()=>$x,createCaptureWorker:()=>sF,createPlaybackWorker:()=>iF});function sF(D,x,A,F,r=E.DefaultRefreshRate){return nF.enqueue(async()=>{let[t,e]=await Ex(C0,E0,D,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return console.warn("SharedArrayBuffer is not available; creating ODIN CaptureWorker in fallback mode"),Gx.create(D,x,A,r,t,e,F)})}async function iF(D,x=E.DefaultRefreshRate){if(D.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[A,F]=await Ex(C0,E0,D,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return $x.create(D,x,A,F)}var W0,nF,Gx,$x,X0=p(()=>{"use strict";W0=require("@4players/odin-common");o();qx();K0();V0();nF=new W0.Strand;Gx=class D extends Bx{constructor(A,F,r,t,e){super(A,F,r,t,e);this._Activity=I;this._SpeechProbability=0;F.addEventListener("message",this._OnMessages.bind(this))}static async create(A,F,r,t,e,j,B){let{port1:s,port2:l}=new MessageChannel;return a(e,["captureInit",{sampleRate:A.sampleRate,refreshRate:t,workletPort:s}],[s]),await Dx(e,"captureReady"),a(j.port,["init",{workerPort:l}],[l]),new D(j,e,F,r,B)}get activity(){return this._Activity}get speechProbability(){return this._SpeechProbability}setVolume(A){a(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)}},$x=class D extends vx{constructor(A,F,r){super(A,F,r);this.activities=new Float32Array;this.jitterStats=[]}static async create(A,F,r,t){let{port1:e,port2:j}=new MessageChannel;return a(r,["playbackInit",{workletPort:e,refreshRate:F}],[e]),await Dx(r,"playbackReady"),a(t.port,["init",{workerPort:j}],[j]),new D(A,t,r)}getActivity(A){let F=this.medias.get(h(A));if(F===void 0)return;let r=this.activities.at(F.index);if(r!==void 0)return r===0?I:{isSilent:!1,rmsDBFS:r}}getJitterStats(A){let F=this.medias.get(h(A));if(F===void 0)return;let r=this.jitterStats.at(F.index);if(r!==void 0)return r}setGlobalVolume(A){a(this.worker,["playbackSetVolume",{index:"global",value:A}])}setVolume(A,F){let r=this.medias.get(h(A));r!==void 0&&a(this.worker,["playbackSetVolume",{index:r.index,value:F}])}_GetFreeIndex(){let A=super._GetFreeIndex();if(A!==void 0)return A;if(this.medias.size<E.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 JF={};kx(JF,{SESSION_ID:()=>ax,createPlugin:()=>wF});module.exports=gA(JF);var u0=require("@4players/odin-common");o();var J=require("@4players/odin-common");o();var xx=require("@4players/odin-common");o();var _=require("@4players/odin-common");o();var P0="getUserMedia; timeout";async function N0(D,x){try{let A=await Promise.race([navigator.mediaDevices.getUserMedia({audio:{echoCancellation:D.echoCanceller,noiseSuppression:D.noiseSuppression!=="None",autoGainControl:D.gainController,echoCancellationType:"system",deviceId:x?{exact:x}:void 0}}),(0,_.sleep)(3e4,"timeout")]);return A==="timeout"?(0,_.failure)(P0):(0,_.success)(A)}catch(A){return(0,_.failure)(`getUserMedia; ${A}`)}}async function w0(D,x,A){let F,r=!1;if(x.device?.device.kind==="track"&&x.device?.device.audioTrack)F=new MediaStream([x.device.device.audioTrack]);else{let j=x.device&&x.device.device.deviceId!=="default"?x.device.device.deviceId:void 0,B=await N0(A,j);if(B.type!=="Success"&&B.reason!==P0&&j&&(C(`unable to open requested capture device, falling back to default; ${B.reason}`),B=await N0(A),r=B.type==="Success"),B.type!=="Success")return B;F=B.value}let t=F.getAudioTracks()[0].getSettings().sampleRate,e=await D.audioContexts.acquire(t);return(0,_.success)({source:e.createMediaStreamSource(F),defaulted:r})}function ex(D){D.getTracks().forEach(x=>{x.stop(),D.removeTrack(x)})}async function O0(D){return new tx({deviceId:D.id,kind:"track",name:D.label??"MediaStreamTrack",audioTrack:D},!1)}async function AF(){let D=(await navigator.mediaDevices.enumerateDevices()).filter(x=>!!x.label);if(D.length===0&&(0,_.isFirefoxBrowser)()){let x=await FF("microphone");(x==="granted"||x===!1)&&(await rF("audio"),D=(await navigator.mediaDevices.enumerateDevices()).filter(A=>!!A.label))}return D}async function mx(){let D=await AF(),x=new Map,A=[];for(let r of D){let t=r.kind;if(!(t!=="audioinput"&&t!=="audiooutput")){if(r.deviceId==="default"){x.set(t,r);continue}r.deviceId!=="communications"&&A.push(new tx({deviceId:r.deviceId,name:r.label,kind:t},!1))}}let F=r=>new tx({deviceId:"default",name:x.get(r)?.label??"Default",kind:r},!0);return[F("audioinput"),F("audiooutput"),...A]}async function FF(D){try{return(await navigator.permissions.query({name:D})).state}catch{return!1}}async function rF(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 yx=require("@4players/odin-common");o();var z0=(0,yx.isSharedArrayBufferCapable)()&&!(0,yx.isSafariBrowser)()?Promise.resolve().then(()=>(U0(),M0)):Promise.resolve().then(()=>(X0(),Q0));async function Z0(D,x,A,F){return z0.then(r=>r.createCaptureWorker(D,x,A,F,E.DefaultRefreshRate))}async function Y0(D){return z0.then(x=>x.createPlaybackWorker(D,E.DefaultRefreshRate))}var bF=250,oF=1e3,O=class{constructor(x,A){this.controller=x;this._Medias=new Map;this._Vad={...xx.VAD_DEFAULTS};this._Apm={...xx.APM_DEFAULTS};this._Volume=1;this._Queue=Promise.resolve();this.#r=0;this._DeviceCb=()=>{clearTimeout(this.#F),this.#F=setTimeout(()=>{this._enqueue(async()=>{let x=this._DeviceParameters?.device;!x||x.device.kind==="track"||(x.device.deviceId==="default"?await this._followDefaultDevice():await this._detectSelectedDeviceRemoved(x.device.deviceId))}).catch(x=>C("device-change handler failed",x))},bF)};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,xx.generateUUID)(),this.#x=A.customType,this.#A=A.ref}#x;#A;#F;#r;async _followDefaultDevice(){let x=this._DeviceParameters;this._Volume==="muted"||!this._Capture||!x||Date.now()-this.#r<oF||(f("default capture device may have moved, re-opening capture"),await this._setDeviceImpl(x))}async _detectSelectedDeviceRemoved(x){(await mx()).some(t=>t.device.deviceId===x)||this._Capture?.source.mediaStream?.getAudioTracks()[0]?.readyState==="live"||(this._DeviceParameters?.onStatusChanged?.("stopped"),navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._DeviceParameters=void 0,await this._closeImpl())}_enqueue(x){let A=this._Queue.then(x,x);return this._Queue=A.catch(()=>{}),A}get vad(){return this._Vad}get apm(){return this._Apm}get volume(){return this._Volume}get activity(){return this._Capture?.worker.activity??I}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),n(`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=>u(`StartMedia got rejected; ${r}`)),this._UpdateMedias().catch(console.error))}async stop(x,A){let F=this._Medias.get(A.connectionId);n(`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=>u(`StopMedia got rejected; ${r}`)),this._UpdateMedias().catch(console.error))}setVad(x){f("updating vad config",x),this._Vad=x,this._Capture&&this._Capture.worker.setVad(x)}async setApm(x){await this._enqueue(()=>this._setApmImpl(x))}async _setApmImpl(x){f("updating apm config",x),this._Apm=x,this._DeviceParameters&&await this._setDeviceImpl(this._DeviceParameters)}async setDevice(x){await this._enqueue(()=>this._setDeviceImpl(x))}async _setDeviceImpl(x){f("updating capture device parameters",x);let A=this._DeviceParameters;if(this._DeviceParameters=x,this._Volume==="muted")return;let F;try{let r=await w0(this.controller,x,{...this._Apm,echoCanceller:this._Monitor?!1:this._Apm.echoCanceller});if(r.type!=="Success"){u(`unable to open capture device; ${r.reason}`),this._DeviceParameters=A;return}F=r.value.source.context,navigator.mediaDevices.addEventListener("devicechange",this._DeviceCb);let t=this._Capture?.source.context;if(this._Capture!==void 0){ex(this._Capture.source.mediaStream);try{this._Capture.source.disconnect(this._Capture.worker.worklet)}catch(e){C("failed to disconnect previous capture source",e)}}this._Capture===void 0||this._Capture.worker.worklet.context!==r.value.source.context?(this._Capture?.worker.close(),this._Capture={worker:await Z0(r.value.source.context,this.controller.sink,this.controller.receiveMonitoredPacket.bind(this.controller),new WeakRef(this)),source:r.value.source},await this._UpdateMedias(),this._Capture.worker.setVolume(this._Volume),this.setVad(this.vad)):this._Capture.source=r.value.source,F=void 0,this._Capture.source.connect(this._Capture.worker.worklet),t!==void 0&&await this.controller.audioContexts.release(t),this.#r=Date.now(),x.onStatusChanged?.(r.value.defaulted?"defaulted":"started")}catch(r){throw F!==void 0&&await this.controller.audioContexts.release(F),new Error(`Error in setDevice(); ${r}`,{cause:r})}}async setVolume(x){await this._enqueue(()=>this._setVolumeImpl(x))}async _setVolumeImpl(x){f(`updating capture volume to ${x}`),this._Volume=x,x==="muted"?await this._closeImpl():(!this._Capture&&this._DeviceParameters&&await this._setDeviceImpl(this._DeviceParameters),this._Capture?.worker.setVolume(x))}close(){this._enqueue(()=>this._closeImpl()).catch(console.error)}async _closeImpl(){if(f("closing audio capture"),clearTimeout(this.#F),this.#F=void 0,this._Capture!==void 0){this._Capture.worker.close(),ex(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,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).catch(console.error),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).catch(console.error),this._Medias.delete(0),await this._UpdateMedias())}};var K=require("@4players/odin-common");o();var $=class{constructor(x,A){this.controller=x;this.parameters=A;this.uid=(0,K.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,K.assert)(this.audioCapture,"getting the volume failed, this video has no Audio"),this.audioCapture.volume}async setVolume(x){(0,K.assert)(this.audioCapture,"setVolume() failed, this video has no Audio"),await this.audioCapture.setVolume(x)}get vad(){return(0,K.assert)(this.audioCapture,"getting the vad config failed, this video has no Audio"),this.audioCapture.vad}setVad(x){(0,K.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 O0(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??E.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=>u(`StartMedia got rejected; ${t}`))}}async stop(x,A){this.#x&&ex(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=>u(`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&&ex(this.#x),this.audioCapture?.close(),this.#F=void 0}};var aF=require("@4players/odin-common");o();var L=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){n(`starting audio playback media ${x.mediaId} on connection ${x.connectionId}`),this.controller.playbackStart(this.uid,x)}stop(x){n(`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)}};function lF(D,x){let A=D.audioContext;if(typeof A.setSinkId=="function"){D.connectOutput(A.destination);let F,r=()=>{if(A.state==="running"&&F!==void 0){let t=F;F=void 0,A.setSinkId(t).catch(e=>C("failed to apply deferred sinkId",e))}};return A.addEventListener("statechange",r),{async setSinkId(t){if(A.state!=="running"){F=t;return}await A.setSinkId(t)},dispose(){A.removeEventListener("statechange",r)}}}if(x&&typeof document<"u"&&typeof HTMLAudioElement<"u"&&typeof HTMLAudioElement.prototype.setSinkId=="function"){let F=A.createMediaStreamDestination();D.connectOutput(F);let r=new Audio;r.srcObject=F.stream,r.muted=!1,r.volume=1;let t=!1,e=!1,j={once:!0,passive:!0,capture:!0},B=()=>{e=!1,c()},s=()=>{e||t||(e=!0,document.addEventListener("pointerdown",B,j),document.addEventListener("keydown",B,j))},l=()=>{e&&(e=!1,document.removeEventListener("pointerdown",B,!0),document.removeEventListener("keydown",B,!0))},c=()=>{t||r.play().catch(z=>{t||(z instanceof DOMException&&z.name==="NotAllowedError"?s():C("failed to start playback audio element",z))})},rx=()=>{A.state==="running"&&r.paused&&c()};return A.addEventListener("statechange",rx),c(),{async setSinkId(z){await r.setSinkId(z)},dispose(){t=!0,l(),A.removeEventListener("statechange",rx),r.pause(),r.srcObject=null,r.removeAttribute("src");try{r.load()}catch{}F.disconnect()}}}return D.connectOutput(A.destination),{async setSinkId(){},dispose(){}}}var gx=class{constructor(x){this.audioContextFactory=x;this.entries=[];this._acquireStrand=new J.Strand}acquire(x){return this._acquireStrand.enqueue(async()=>{for(let r of this.entries)if(r.sampleRate===x||r.sampleRate===void 0&&r.audioContext.sampleRate===x)return r.references+=1,r.audioContext;let A=await this.audioContextFactory(x),F=this.entries.find(r=>r.audioContext.sampleRate===A.sampleRate);return F?(F.references+=1,A.close().catch(()=>{}),F.audioContext):(this.entries.push({sampleRate:x,audioContext:A,references:1}),A)})}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.splice(0))x.audioContext.close().catch(()=>{})}},Ix=class D{constructor(x,A,F=!1){this.audioContexts=x;this.sink=A;this.enableHTMLAudioElementFallback=F;this.audioCaptures=[];this.videoCaptures=[];this.globalVolume=[1,1];this.playbacks=new Map;this.setPlaybackStrand=new J.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 L(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 O(this,x);return await A.setDevice(x),this.audioCaptures.push(new WeakRef(A)),A}async createVideoCapture(x,A){let F=new $(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??"";if(A==="default"&&(A=""),this.playbackWorker===void 0){let F=await this.audioContexts.acquire(48e3);this.playbackWorker=await Y0(F),this.playbackSink=lF(this.playbackWorker,this.enableHTMLAudioElementFallback),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)}if(x&&this.playbackSink!==void 0)try{await this.playbackSink.setSinkId(A)}catch(F){C("failed to set playback sink",F)}})}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?I:this.playbackWorker?.getActivity(A.id)??I}playbackGetJitterStats(x){let A=this.playbacks.get(x);return A?.id===void 0?J.JITTER_STATS_INITIAL:this.playbackWorker?.getJitterStats(A.id)??J.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.playbackSink?.dispose(),this.playbackSink=void 0,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}}},tx=class{constructor(x,A=!1){this.device=x;this.isDefault=A}get type(){switch(this.device.kind){case"audioinput":return"AudioCapture";case"track":return"AudioCapture";case"audiooutput":return"AudioPlayback";default:(0,J.assert)(!1,"not supported device")}}get id(){return this.device.deviceId}get name(){return this.device.name}};var lx=require("@4players/odin-common"),eA=require("@msgpack/msgpack");o();var mF=require("@4players/odin-common");o();var g=require("@4players/odin-common"),Q=require("@4players/odin-common/api");o();var W=require("@4players/odin-common"),Ax=require("@4players/odin-common/api"),_x=require("@msgpack/msgpack");o();var V=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"):(cF(x.readable.getReader(),this._OnRpcMessage.bind(this)).catch(A=>C("rpc stream reader failed",A)).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(e=>{this._Requests.set(r,{accept:e,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).catch(()=>{})}_OnWebSocketOpen(x){for(let A of this._SendQueue)this._Send(A);this._SendQueue.length=0}_OnRpcMessage(x){let A=uF(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,W.success)(F):(0,W.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(()=>{})}},Fx=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,Ax.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,Ax.parseResponse)(x,r.value,this._Commands);return t!==void 0?(0,W.success)(t):(0,W.failure)("response schema failed validation")}notify(x,A){A=(0,Ax.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=f0(this._Events,x);return A!==void 0?A:(xA(this._Events,x.name)?(u(`schema validation for ${x.name} failed; closing connection`),this.rpc.close()):C(`dropping unknown event ${x.name}`),"closed")}close(){this.rpc.close()}};function uF(D){try{return(0,W.success)(Ax.MessagePackRpcSchema.parse((0,_x.decode)(new Uint8Array(D))))}catch(x){return(0,W.failure)(String(x))}}function f0(D,x){if(!xA(D,x.name))return;let A=D[x.name].safeParse(x.properties);if(A.success)return{name:x.name,properties:A.data}}function xA(D,x){return x in D}async function cF(D,x){let A=new Uint8Array;for(;;){let F=y0(A,0);if(F===v){D.cancel("protocol violation").catch(()=>{});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=kF(A,r.value)}A.length>0&&C("unprocessed bytes left in rpc stream",A)}function kF(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 R=require("@4players/odin-common"),AA=require("@4players/odin-common/api");o();var y=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:u(`upstream in token can not be parsed; ${F.reason}`)}}static parse(x){let A=x.split(".");if(A.length!==3)return(0,R.failure)("expected three segments");let F=(0,R.fromBase64Url)(A[1]);if(F.type==="Failure")return(0,R.failure)(`invalid token; ${F.reason}`);let r;try{r=JSON.parse(F.value)}catch(e){return(0,R.failure)(`invalid token; ${e}`)}let t=AA.TokenClaimsSchema.safeParse(r);return t.success===!1?(0,R.failure)(`invalid token; ${t.error}`):(0,R.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 fx=require("@4players/odin-common");o();function FA(D){typeof globalThis.rtcDataChannels>"u"&&(globalThis.rtcDataChannels=[]),Array.isArray(globalThis.rtcDataChannels)&&globalThis.rtcDataChannels.length<=100&&globalThis.rtcDataChannels.push(D)}function rA(D){let x=globalThis.rtcDataChannels?.indexOf(D);x!==void 0&&x>=0&&globalThis.rtcDataChannels.splice(x,1),D.readyState!=="closed"&&D.close()}function Lx(D){typeof globalThis.rtcPeerConnections>"u"&&(globalThis.rtcPeerConnections=[]),Array.isArray(globalThis.rtcPeerConnections)&&globalThis.rtcPeerConnections.length<=100&&globalThis.rtcPeerConnections.push(D)}function Hx(D){let x=globalThis.rtcPeerConnections?.indexOf(D);x!==void 0&&x>=0&&globalThis.rtcPeerConnections.splice(x,1),D.connectionState!=="closed"&&D.close()}var nx=class{constructor(x,A,F){this._localVideos=new Map;this._remoteVideos=new Map;this._freeLocalVideoTransceivers=[];this._closed=!1;this._negotiationRequested=!1;this._negotiationRunning=!1;this._negotiationCounter=0;this._pendingRemoteCandidates=[];this._WebRtcStatsSnapshot=null;this._peerConnection=x,this._signaling=A,this._answerTimeout=F?.answerTimeout??E.WebRtcAnswerTimeout,this._maxNegotiationAttempts=F?.maxNegotiationAttempts??E.WebRtcMaxNegotiationAttempts,this._negotiationCounter=F?.firstNegotiationId??0,this._peerConnection.ontrack=this._onTrack.bind(this),this._peerConnection.onconnectionstatechange=()=>this._onStatusChanged(),this._peerConnection.onicecandidate=r=>{(r.candidate?this._signaling.sendIceCandidate(r.candidate):this._signaling.sendIceComplete()).catch(e=>{C("failed to send local ice candidate",e)})},this._WebRtcStatsInterval=setInterval(()=>{this._snapshotStats().catch(()=>{})},E.WebRtcStatsSnapshotInterval)}requestNegotiation(){this._closed||(this._negotiationRequested=!0,!this._negotiationRunning&&(this._negotiationRunning=!0,setTimeout(async()=>{let x=0;for(;this._negotiationRequested&&!this._closed;){this._negotiationRequested=!1;try{await this._negotiate(),x=0}catch(A){if(this._closed)break;if(x+=1,u(`negotiation failed during sdp offer/answer exchange (attempt ${x})`,A),x<this._maxNegotiationAttempts)this._negotiationRequested=!0;else{this._negotiationRunning=!1,this._signaling.closeConnection("negotiation gave up").catch(()=>{});return}}}this._negotiationRunning=!1})))}async startLocalVideo(x,A,F){if(this._localVideos.has(x))return;n(`starting local video for media ${x}`);let r=this._freeLocalVideoTransceivers.pop();if(r?(await r.sender.replaceTrack(A),r.direction="sendonly"):r=this._peerConnection.addTransceiver(A,{direction:"sendonly"}),F){let j=r.sender.getParameters(),{maxBitrate:B,maxFramerate:s,scaleResolutionDownBy:l}=F,c={...B!==void 0&&{maxBitrate:B},...s!==void 0&&{maxFramerate:s},...l!==void 0&&{scaleResolutionDownBy:l}};if(j.encodings.length===0)j.encodings.push(c);else for(let rx of j.encodings)Object.assign(rx,c);F.degradationPreference&&(j.degradationPreference=F.degradationPreference),await r.sender.setParameters(j)}let e=new fx.VideoCodec(F?.codec??E.DefaultVideoCodec).isSupported();e&&r.setCodecPreferences([e]),this._localVideos.set(x,{transceiver:r}),this.requestNegotiation()}stopLocalVideo(x){let A=this._localVideos.get(x);A&&(n(`stopping local video for media ${x}`),this._localVideos.delete(x),A.transceiver.sender.track&&(A.transceiver.sender.track.enabled=!1),A.transceiver.direction="inactive",A.transceiver.sender.replaceTrack(null).catch(()=>{}),this._freeLocalVideoTransceivers.push(A.transceiver),this.requestNegotiation())}startRemoteVideo(x){let A=this._remoteVideos.get(x);if(A)return A.track;n(`starting remote video for media ${x}`);let F=this._peerConnection.addTransceiver("video",{direction:"recvonly"}),r,t=new Promise((e,j)=>{r={resolve:e,reject:j}});return t.catch(()=>{}),(0,fx.assert)(r!==void 0,"promise executor must run synchronously"),this._remoteVideos.set(x,{state:"Requested",transceiver:F,promise:r,track:t}),this.requestNegotiation(),t}stopRemoteVideo(x){let A=this._remoteVideos.get(x);if(A){n(`stopping remote video for media ${x}`),this._remoteVideos.delete(x),A.state!=="Active"&&A.promise.reject(new Error("video stopped"));try{A.transceiver.direction="inactive"}catch{}this.requestNegotiation()}}async handleWebRtcUpdate(x){if(!this._closed)try{switch(x.kind){case"Sdp":await this._updateRemoteSdp(x.type==="Answer"?"answer":"offer",x.sdp,x.media_map,x.negotiation_id);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}}catch(A){u("failed to handle webrtc update",A,x)}}startup(){this._peerConnection.connectionState==="new"&&this.requestNegotiation()}cleanup(){this._closed=!0,this._peerConnection.ontrack=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onicecandidate=null;for(let[,x]of this._remoteVideos)x.state!=="Active"&&x.promise.reject(new Error("connection closed"));this._pendingAnswer?.reject(new Error("connection closed")),this._pendingRemoteCandidates.length=0,clearTimeout(this._WebRtcIceTimeout),clearTimeout(this._WebRtcTimeout),clearInterval(this._WebRtcStatsInterval),this._localVideos.clear(),this._remoteVideos.clear(),this._freeLocalVideoTransceivers.length=0}get stats(){return this._WebRtcStatsSnapshot}get peerConnection(){return this._peerConnection}get negotiationCounter(){return this._negotiationCounter}get localVideos(){return this._localVideos}get remoteVideos(){return this._remoteVideos}get isConnected(){return this._peerConnection.connectionState==="connected"}get isNegotiating(){return this._negotiationRunning}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,...e}=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(e))}),this._WebRtcStatsSnapshot={timestamp:Date.now(),status:this._peerConnection.connectionState,stats:F,report:A}}catch{}}_addIceCandidate(x){if(x&&(x.sdpMid===void 0&&x.sdpMLineIndex===void 0&&(x={...x,sdpMid:"0"}),f(`adding new ice ${x.candidate}`,x)),this._peerConnection.remoteDescription===null){this._pendingRemoteCandidates.push(x);return}this._applyIceCandidate(x)}_applyIceCandidate(x){this._peerConnection.addIceCandidate(x).catch(A=>{C("failed to add remote ice candidate",A,x)})}_flushPendingIceCandidates(){let x=this._pendingRemoteCandidates.splice(0);for(let A of x)this._applyIceCandidate(A)}async _negotiate(){let x=++this._negotiationCounter,A=await this._peerConnection.createOffer();(0,fx.assert)(A.type==="offer"&&A.sdp,"generated broken payload"),await this._peerConnection.setLocalDescription(A);let F=[];for(let[t,{transceiver:e}]of this._localVideos)e.mid&&F.push([t,e.mid]);for(let[t,e]of this._remoteVideos)e.state!=="Active"&&e.transceiver.mid&&F.push([t,e.transceiver.mid]);let r=new Promise((t,e)=>{this._pendingAnswer={negotiationId:x,resolve:t,reject:e}});r.catch(()=>{});try{await dF((async()=>{await this._signaling.sendOffer(A.sdp,F,x),await r})(),this._answerTimeout,`timed out waiting for answer to offer ${x}`)}finally{this._pendingAnswer=void 0}}async _updateRemoteSdp(x,A,F,r){if(x==="offer"){C("ignoring unexpected sdp offer from server");return}let t=this._pendingAnswer;if(t===void 0){C("ignoring sdp answer without pending negotiation");return}if(r!==void 0&&r!==t.negotiationId){C(`ignoring stale sdp answer for negotiation ${r}; current is ${t.negotiationId}`);return}if(this._peerConnection.signalingState!=="have-local-offer"){C(`ignoring sdp answer in signaling state ${this._peerConnection.signalingState}`);return}for(let[e,j]of F){let B=this._remoteVideos.get(e);B?.state==="Requested"&&(this._remoteVideos.set(e,{state:"Mapped",transceiver:B.transceiver,mid:j,promise:B.promise,track:B.track}),f(`updated remote video list with media ${e}`,B,this._remoteVideos))}try{await this._peerConnection.setRemoteDescription({type:x,sdp:A})}catch(e){t.reject(e);return}this._flushPendingIceCandidates(),t.resolve()}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,this._signaling.onConnected?.();break;case"failed":this._peerConnection.restartIce(),this.requestNegotiation();case"disconnected":E.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},E.WebRtcIceTimeout)),this._WebRtcTimeout===void 0&&(this._WebRtcTimeout=setTimeout(async()=>{f("peer connection timeout was reached"),await this._signaling.closeConnection("peer connection timeout")},E.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,fx.assert)(r.state==="Mapped","expected video state to be Mapped"),this._remoteVideos.set(F,{state:"Active",transceiver:x.transceiver,track:r.track}),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)}};function dF(D,x,A){return new Promise((F,r)=>{let t=setTimeout(()=>r(new Error(A)),x);D.then(e=>{clearTimeout(t),F(e)},e=>{clearTimeout(t),r(e)})})}o();var Nx=class{constructor(x,A){this.host=x;this.delays=A;this._LocalVideos=new Map;this._RemoteVideos=new Map;this._Attempt=0}async startLocalVideo(x,A,F){this._LocalVideos.set(x,{track:A,options:F}),await(await this._Session()).startLocalVideo(x,A,F)}stopLocalVideo(x){this._LocalVideos.delete(x),this.host.currentSession()?.stopLocalVideo(x),this._ForgetAttemptsIfIdle()}startRemoteVideo(x){let A=this._RemoteVideos.get(x);if(A)return A.first;let F,r=new Promise((e,j)=>{F={resolve:e,reject:j}});r.catch(()=>{});let t={stream:new MediaStream,first:r,settle:F};return this._RemoteVideos.set(x,t),this._Session().then(e=>this._RequestRemoteVideo(e,x)).catch(e=>{C(`failed to request remote video for media ${x}`,e)}),r}stopRemoteVideo(x){let A=this._RemoteVideos.get(x);A!==void 0&&(this._RemoteVideos.delete(x),A.settle?.reject(new Error("video stopped")),A.settle=void 0,this.host.currentSession()?.stopRemoteVideo(x),this._ForgetAttemptsIfIdle())}sessionConnected(){this._Attempt=0}sessionFailed(x){this.host.recycleSession(x),this._Schedule()}close(){clearTimeout(this._Timer),this._Timer=void 0,this._RejectPending(new Error("connection closed")),this._LocalVideos.clear(),this._RemoteVideos.clear(),this.host.recycleSession("connection closed")}dump(){return{attempt:this._Attempt,scheduled:this._Timer!==void 0,localVideos:[...this._LocalVideos.keys()],remoteVideos:[...this._RemoteVideos.keys()]}}async _Session(){return this.host.currentSession()===void 0&&this._Timer===void 0&&(this._Attempt=0),this.host.ensureSession()}_Schedule(){if(this.host.isClosed()||this._Timer!==void 0||this._LocalVideos.size===0&&this._RemoteVideos.size===0)return;let x=this.delays[this._Attempt];if(x===void 0){C(`giving up on webrtc video after ${this._Attempt} recovery attempts; audio stays connected`),this._RejectPending(new Error("video recovery gave up"));return}this._Attempt+=1,n(`recovering webrtc video in ${x}ms (attempt ${this._Attempt} of ${this.delays.length})`),this._Timer=setTimeout(()=>{this._Timer=void 0,this._Recover().catch(A=>{C("webrtc video recovery failed",A),this.sessionFailed("recovery failed")})},x)}async _Recover(){if(this.host.isClosed()||this._LocalVideos.size===0&&this._RemoteVideos.size===0)return;let x=await this.host.ensureSession();for(let[A,{track:F,options:r}]of this._LocalVideos){if(F.readyState==="ended"){this._LocalVideos.delete(A);continue}x.startLocalVideo(A,F,r).catch(t=>{C(`failed to republish local video for media ${A}`,t)})}for(let A of this._RemoteVideos.keys())this._RequestRemoteVideo(x,A)}_RequestRemoteVideo(x,A){let F=this._RemoteVideos.get(A);F!==void 0&&x.startRemoteVideo(A).then(r=>{if(this._RemoteVideos.get(A)===F){for(let t of F.stream.getVideoTracks())F.stream.removeTrack(t);F.stream.addTrack(r),F.settle?.resolve(F.stream),F.settle=void 0}}).catch(r=>{f(`remote video for media ${A} did not arrive`,r)})}_RejectPending(x){for(let A of this._RemoteVideos.values())A.settle?.reject(x),A.settle=void 0}_ForgetAttemptsIfIdle(){this._LocalVideos.size>0||this._RemoteVideos.size>0||(clearTimeout(this._Timer),this._Timer=void 0,this._Attempt=0)}};var Px=class D{constructor(x,A,F,r,t,e,j){this.id=x;this.address=A;this.connection=r;this.datagramWritable=t;this.rpc=e;this.closeController=j;this._ConnectionStats={...g.CONNECTION_STATS_INITIAL};this._WebRtcUpdatesRunning=!1;this._NegotiationCounter=0;this._WebRtcSessionFlight=new Z;this._VideoRecovery=new Nx({ensureSession:()=>this._EnsureWebRtcSession(),currentSession:()=>this._WebRtcSession,recycleSession:x=>this._RecycleWebRtcSession(x),isClosed:()=>this.closed},E.WebRtcRecoveryDelays);this._PingFlight=new Z;this.status=0;this._ClosePromise=(async()=>{try{await this.connection.closed}catch{}return"closed"})(),E.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(E.HealthCheckTimeout)},E.MainConnectionPingInterval)),j.signal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this.datagramWriter=t.getWriter(),this.connection.closed.then(()=>{this.status=2}).catch(()=>{}).finally(()=>{this.closeController.abort("transport closed")}),this.connection.ready.then(()=>{this.status=1}).catch(()=>{}),this.readDatagrams(this.connection,this.id,(B,s)=>{this._ConnectionStats.packetsReceived+=1,F(B,s)}).catch(()=>{})}static async create(x,A,F,r){try{let t=new URL(`https://${A}?version=${I0}&uid=${ax}`),e=new AbortController;r.addEventListener("abort",()=>e.abort(),{once:!0});let j=new WebTransport(t);e.signal.addEventListener("abort",()=>{try{j.close()}catch{}},{once:!0}),await j.ready;let B=j.datagrams,s=B?.createWritable?.()??B?.writable;if(!s)return e.abort(),(0,g.failure)(`connecting to ${A} failed because WebTransport datagrams are not supported by this browser`);let l=await j.createBidirectionalStream(),c=new Fx(new V(l),Q.MainCommandsRpc,Q.MainNotificationsRpc);return e.signal.addEventListener("abort",()=>c.close(),{once:!0}),c.notify("Hello",{stream:"main"}),(0,g.success)(new D(x,A,F,j,s,c,e))}catch(t){return(0,g.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(){n(`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 e=new Fx(new V(t),Q.RoomCommandsRpc,Q.RoomNotificationsRpc),j=await e.request("Hello",{stream:"room",token:String(x),room_id:A,user_data:F,position:r});return j==="closed"||j.type==="Failure"?j:(0,g.success)(e.rpc)}catch(t){return(0,g.failure)(`JoinRoom failed; ${t}`)}}async getReconnectToken(x){let A=await this._Request("RequestReconnectToken",{peer_id:x});return A.type==="Failure"?A:y.parse(A.value)}async getRtcStats(){return this._PeerConnection?.getStats()}async healthCheck(){let x=await this._RequestPing(E.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.closed)try{this.datagramWriter.write(x).catch(()=>{}),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 e=t.value.byteLength;this.connectionStats.bytesReceived+=e,F(A,t.value)}}catch{}}_CleanUp(){f(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId),this._VideoRecovery.close()}_RecycleWebRtcSession(x){let A=this._WebRtcSession,F=this._PeerConnection;A===void 0&&F===void 0||(C(`recycling webrtc session of connection ${this.id}; ${x}`),this._WebRtcSession=void 0,this._PeerConnection=void 0,A&&(this._NegotiationCounter=A.negotiationCounter,A.cleanup()),F&&Hx(F))}async _EnsureWebRtcSession(){return this._WebRtcSession?this._WebRtcSession:this._WebRtcSessionFlight.run(async()=>{this._PeerConnection=new RTCPeerConnection,Lx(this._PeerConnection);let x=this._PeerConnection;return this._WebRtcSession=new nx(x,{sendOffer:async(A,F,r)=>{let t=await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:A,media_map:F,negotiation_id:r});if(t.type==="Failure")throw new Error(`failed to send sdp offer; ${t.reason}`)},sendIceCandidate:async A=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:A.candidate,spd_mid:A.sdpMid??void 0,spd_mline_index:A.sdpMLineIndex??void 0,username_fragment:A.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async A=>{this._PeerConnection===x&&this._VideoRecovery.sessionFailed(A)},onConnected:()=>{this._PeerConnection===x&&this._VideoRecovery.sessionConnected()},checkConnection:async()=>{}},{firstNegotiationId:this._NegotiationCounter}),this._HandleWebRtcUpdates().catch(A=>C("webrtc update loop failed",A)),this._WebRtcSession})}async _HandleWebRtcUpdates(){if(!this._WebRtcUpdatesRunning){for(this._WebRtcUpdatesRunning=!0;;){let x=await this.rpc.recv();if(x==="closed")break;x.name==="WebRtcUpdate"&&this._WebRtcSession?.handleWebRtcUpdate(x.properties).catch(()=>{})}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)),e=(Date.now()-r)/1e3;return x!=="Ping"&&f(`sent main rpc '${x}'; took: ${e}s`,{properties:A,timeout:F,result:t}),t==="closed"?(0,g.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._VideoRecovery.startLocalVideo(x,A,F)}stopLocalVideo(x){this._VideoRecovery.stopLocalVideo(x)}startRemoteVideo(x){return this._VideoRecovery.startRemoteVideo(x)}stopRemoteVideo(x){this._VideoRecovery.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},videoRecovery:this._VideoRecovery.dump(),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"),Ox=require("@4players/odin-common/api");o();var H=require("@4players/odin-common");o();async function n0(D,x){let A=performance.now(),F=(0,H.failure)("no connection was attempted");for(let r=0;r<E.ConnectInterval.length&&!x.aborted;r++){let t=A+hF(r);if(await(0,H.abortableSleep)(t-performance.now(),x)==="aborted")return(0,H.failure)("aborted");if(F=await pF(D,x),F.type==="Success")return F}return F}async function pF(D,x){let A;try{A=new WebSocket(D)}catch(B){return(0,H.failure)(`unable to create websocket; ${B}`)}let F=new AbortController,r=new Promise(B=>A.addEventListener("open",()=>B((0,H.success)(A)),{signal:F.signal})),t=new Promise(B=>A.addEventListener("close",s=>B((0,H.failure)(s.reason!==""?s.reason:"unable to establish websocket connection")),{signal:F.signal})),e=new Promise(B=>x.addEventListener("abort",()=>B((0,H.failure)("aborted")),{signal:F.signal})),j=await Promise.race([r,t,e]);return F.abort(),j}function hF(D){let x=E.ConnectInterval.slice(0,D).reduce((F,r)=>F+r,0),A=E.ConnectInterval[D]*Math.random();return x+A}var wx=class D{constructor(x,A,F,r,t,e){this.id=x;this.address=A;this.url=F;this.onDatagram=r;this.connection=t;this.webRtc=e;this._PeerIdMap=new WeakMap;this._ConnectionStats={...d.CONNECTION_STATS_INITIAL};this._PingFlight=new Z;n(`creating new webrtc connection to '${this.address}' with id ${this.id}`),this.closeSignal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this._ClosePromise=new Promise(j=>{this.closeSignal.addEventListener("abort",()=>{j("closed")},{once:!0})}),Lx(e),this._AudioChannel=this.webRtc.createDataChannel("audio",{id:2,negotiated:!0,ordered:!1,maxRetransmits:0}),this._AudioChannel.binaryType="arraybuffer",this._AudioChannel.onmessage=j=>{this._ConnectionStats.packetsReceived++;let B=new Uint8Array(j.data);this._ConnectionStats.bytesReceived+=B.byteLength,this.onDatagram(this.id,B)},this._AudioChannel.onerror=j=>C(`webrtc audio data channel for connection with id ${x} raised an error`,j),this._AudioChannel.onclosing=j=>n(`webrtc audio data channel for connection with id ${x} begins shutting down`,j),this._AudioChannel.onclose=j=>n(`webrtc audio data channel for connection with id ${x} has closed`,j),FA(this._AudioChannel),this._WebRtcSession=new nx(this.webRtc,{sendOffer:async(j,B,s)=>{let l=await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:j,media_map:B,negotiation_id:s});if(l.type==="Failure")throw new Error(`failed to send sdp offer; ${l.reason}`)},sendIceCandidate:async j=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:j.candidate,spd_mid:j.sdpMid??void 0,spd_mline_index:j.sdpMLineIndex??void 0,username_fragment:j.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async()=>{this.close()},checkConnection:async()=>{this.healthCheck().catch(()=>{})}}),this._WebRtcSession.startup(),E.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(E.HealthCheckTimeout)},E.MainConnectionPingInterval)),this._HandleWebRtcUpdates().catch(j=>C("webrtc update loop failed",j))}static async create(x,A,F,r){if(r.aborted)return(0,d.failure)("aborted");let t;try{t=new URL(`wss://${A}`)}catch(s){return(0,d.fail)(`address in token(${A}) can not be parsed; ${s}`)}let e=(0,d.extendUrl)(t,`main?uid=${ax}`);if(e.type!=="Success")return e;let j=await n0(e.value,r);if(j.type!=="Success")return j;let B=new Fx(new V(j.value),Ox.MainCommandsRpc,Ox.MainNotificationsRpc);try{return(0,d.success)(new D(x,A,t,F,B,new RTCPeerConnection))}catch(s){return B.close(),(0,d.failure)(`unable to create webrtc connection; ${s}`)}}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")),()=>A(new Error("connection closed")))})}close(){n(`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 e=t.value;if(!("token"in e))return(0,d.failure)("JoinRoom responded without token");let j=(0,d.extendUrl)(this.url,`room?token=${e.token}`);if(j.type==="Failure")return j;let B=await n0(j.value,this.closeSignal);return B.type==="Success"?(this._PeerIdMap.set(B.value,e.peer_id),(0,d.success)(new V(B.value))):B}async getReconnectToken(x){let A=await this._Request("RequestReconnectToken",{peer_id:x});return A.type==="Failure"?A:y.parse(A.value)}async getRtcStats(){return this.webRtc.getStats()}async healthCheck(){let x=await this._RequestPing(E.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),rA(this._AudioChannel),Hx(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).catch(()=>{})}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)),e=(Date.now()-r)/1e3;return x!=="Ping"&&f(`sent main rpc '${x}'; took: ${e}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 new MediaStream([await 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 tA(D,x,A,F,r){switch(n(`creating ${x} main connection to '${A}'`),x){case"H3":return Px.create(D,A,F,r);case"WebRTC":return wx.create(D,A,F,r);default:throw new Error(`transport ${x} is not supported`)}}var sx=require("@4players/odin-common"),N=require("@4players/odin-common/api");o();var Jx=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().catch(j=>C("cipher reset failed",j));let t=await this.cipher.encryptUserData(F);if(t===v)return(0,sx.failure)("unable to encrypt initial user-data");let e=await this.connection.joinRoom(x,A,t,r);return e==="closed"||e.type==="Failure"?e:(0,sx.success)(new s0(e.value,this.cipher,this))}getReconnectToken(x){return this.connection.getReconnectToken(x)}getRtcStats(){return this.connection.getRtcStats()}healthCheck(){return this.connection.healthCheck()}sendDatagram(x){this.cipher.encryptDatagram(x).then(A=>{A!==v?(this._DatagramSent+=1,this.connection.sendDatagram(A)):this._DatagramSentInvalid+=1}).catch(A=>C("datagram encryption failed",A))}async decryptDatagram(x,A){let F=await this.cipher.decryptDatagram(x,A);return F!==v?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()}}},Rx=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)}},s0=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===v?(0,sx.failure)("can not be encrypted"):await this.rpc.request(x,r,F)}notify(x,A){this.outgoing(x,A).then(F=>{F!==v&&this.rpc.notify(x,F)}).catch(F=>C(`encrypting notification '${x}' failed`,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!==v)return{name:x.name,properties:A}}}close(){return this.rpc.close()}async outgoing(x,A){if(!(x in N.RoomCommandsRpc))return A;let F=(0,N.parseCommand)(x,A,N.RoomCommandsRpc);if(F===void 0)return v;switch(F.name){case"UpdatePeer":{let r=await this.cipher.encryptUserData(F.request.user_data);if(r===v)return v;F.request.user_data=r}break;case"SendMessage":{let r=await this.cipher.encryptMessage(F.request.message);if(r===v)return v;F.request.message=r}break}return F.request}async incoming(x,A){if(!(x in N.RoomNotificationsRpc))return A;let F=(0,N.parseNotification)(x,A,N.RoomNotificationsRpc);if(F===void 0)return v;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===v)return v;F.properties.updates[r]=t}break;case"PeerUpdated":{let r=await this.peerUpdate(F.properties);if(r===v)return v;F.properties=r}break;case"MessageReceived":{let r=await this.cipher.decryptMessage(F.properties.sender_peer_id,F.properties.message);if(r===v)return v;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===v)return v;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!==v?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!==v?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=h({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=h({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 Sx=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)>E.ClockJumpThreshold&&this.checkHealth(),A=Date.now()},E.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=qF(A);if(F===void 0||F.length===0)return;let r=this._MediaMap.get(h({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===v)return;this.onDatagram(r.connection.id,t)}}async acquireConnection(x,A,F,r){if(await(0,lx.nextTick)(),this.closed)return"closed";let t=this.findConnection(x,A),e;switch(t?.type){case"established":f(`reusing existing connection ${t.id}`),e=t;break;case"establishing":{f(`waiting for connecting to '${A}' finish`);let s=await t.finished;if(s.type!=="Success")return s;e=s.value}break;case void 0:{f(`connecting to '${A}'`);let s=await this.createConnection(x,A,r);if(s.type!=="Success")return s;e=s.value}break}let j=e.id,B=new i0(e.connection,()=>this.releaseConnection(j));return e.references+=1,F&&(B=new Jx(++this._LastConnectionId,B,F,this._MediaMap),this.addConnection({type:"virtual",id:B.id,connection:B,createdAt:Date.now()})),(0,lx.success)(B)}async createConnection(x,A,F){let r=++this._LastConnectionId,t=Date.now(),e=new AbortController;F.addEventListener("abort",()=>e.abort(),{once:!0}),f(`creating new connection ${r}`);let j=tA(r,x,A,(rx,z)=>{this.recvDatagram(rx,z).catch(mA=>f("dropping datagram",mA))},F),{promise:B,resolve:s}=Promise.withResolvers();this.addConnection({type:"establishing",id:r,address:A,transport:x,finished:B,createdAt:Date.now(),abort:e});let l=await j;if(this._Connections.delete(r),l.type!=="Success")return s(l),l;let c={type:"established",id:r,address:A,transport:x,createdAt:t,references:0,connection:l.value};return this.addConnection(c),(0,lx.success)(c)}addConnection(x){(x.type==="established"||x.type==="virtual")&&x.connection.closeSignal.addEventListener("abort",()=>{n(`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().catch(()=>{})}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&&(F.type!=="established"||!F.connection.closed))return F}},i0=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)}getRtcStats(){return this.connection.getRtcStats()}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 qF(D){let x;try{x=(0,eA.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 ux=require("@4players/odin-common"),P=class{constructor(x,A){this.uid=x;this.customType=A}#x;#A;get mediaStream(){return this.#x}get audioPlayback(){return(0,ux.assert)(this.#A,"getting the audioPlayback failed, this video has no Audio"),this.#A}get volume(){return(0,ux.assert)(this.audioPlayback,"getting the volume failed, this video has no Audio"),this.audioPlayback.volume}setVolume(x){(0,ux.assert)(this.#A,"Can not set the volume, this video has no Audio"),this.#A.setVolume(x)}setMediaStream(x){this.#x=x}close(){this.#x?.getVideoTracks().forEach(x=>{x.stop(),this.#x?.removeTrack(x)}),this.#x=void 0}};var w=require("@4players/odin-common"),a0=require("@4players/odin-common/api");var b=require("@4players/odin-common"),S=require("@4players/odin-common/api");o();var Tx=class{constructor(x,A,F,r,t,e,j,B,s,l){this.connectionPool=x;this.transport=A;this.onEvent=F;this.gateway=r;this.roomId=e;this.cipher=s;this.disableAutoReconnect=l;this._Close=new AbortController;this._TokenUsed=!1;this._WasConnected=!1;this._FailedConnections=0;this._LastTokenRenew=performance.now();this._LastReconnectStartedAt=0;this._ReconnectingSince=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=j,this._Position=B,this._Main().then(({reason:c})=>f(`_Main() resolved; ${c}`),c=>u(`_Main() rejected; ${c}`))}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,b.failure)("currently not connected");let F=await this._RoomConnection.request(x,A,void 0);return(0,b.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=await this.requestUnsafe(x,A),t=(Date.now()-F)/1e3;if(f(`sent room rpc '${x}'; took: ${t}s`,{properties:A,result:r}),r==="closed"||r.type==="Failure")return r;let e=(0,S.parseResponse)(x,r.value,S.RoomCommandsRpc);return e!==void 0?(0,b.success)(e):(0,b.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()+E.MinTokenRefreshInterval,A=this._Token.timeLeft-E.MinTokenLifetime;return Math.max(x,A)}async _Main(){let x;for(let A=0;;this._FailedConnections++){if(await(0,b.sleep)(Math.max(A-performance.now(),0)),this._Close.signal.aborted||this.connectionPool.closed){x="user requested";break}if(this._WasConnected&&this._ReconnectingSince!==0&&jA(this._ReconnectingSince,E.MaxReconnectDuration)){x="reconnect time limit reached";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()),this._WasConnected&&this._ReconnectingSince===0&&(this._ReconnectingSince=performance.now()),F.type==="Failure"&&!this._WasConnected&&this._FailedConnections>=3){x=F.reason;break}if(F.type==="Failure"&&!jA(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 GF(this.gateway,this._Token,this._Close.signal);if(F.type==="Success")if(F.value instanceof y)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,b.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,b.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,b.failure)("connection pool closed");if(t.type==="Failure")return this._ChangeStatus("Joining",`connection failed; ${t.reason}`),(0,b.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,b.sleep)(E.ConnectTimeout,"timeout"),this._Closed]);if(F==="closed"||F==="disconnected")return(0,b.success)("continue");if(F==="timeout")return this._ChangeStatus("Joining","timed out"),(0,b.success)("continue");let[r]=F;if(r==="closed")return(0,b.success)("continue");if(r.type==="Failure")return(0,b.failure)(`unable to join room; ${r.reason}`);this._RoomConnection=r.value,this._WasConnected=!0,this._FailedConnections=0,this._ReconnectingSince=0,this._ChangeStatus("Joined",`joined ${this.roomId}`);try{await this._MainConnection.waitForConnected();let t=await this._HandleConnection(this._MainConnection);return(0,b.success)(t?"shutdown":"continue")}catch(t){return(0,b.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 b.Selector([()=>(0,b.sleep)(this.renewTokenIn,"renewToken"),()=>(0,b.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().catch(r=>C("token renewal failed",r));break;case"tick":break;default:this._HandleEvent(F);break}}}_HandleEvent(x){if(x.name==="RoomUpdated"){let A=S.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=S.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=S.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>E.MinTokenLifetime)return;if(this._MainConnection===void 0||this._OwnPeerId===void 0)return(0,b.failure)("connection is not established");let A=await this._MainConnection.getReconnectToken(this._OwnPeerId);return A.type==="Success"?(this._Token=A.value,(0,b.success)()):(0,b.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 GF(D,x,A){try{let F={jsonrpc:"2.0",id:1,method:"Connect",params:{}};n(`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(n(`received authentication response fom '${D}'`,t),"result"in t)return y.parse(t.result.token);{let e=t.error?.message??"malformed response";return u(`gateway rejected token; ${e}`),(0,b.success)(e)}}catch(F){return(0,b.failure)(String(F))}}function jA(D,x=8e3){return performance.now()-D>x}o();var kA=require("@4players/odin-common");var X=require("@4players/odin-common");o();var oA=require("@4players/odin-common");o();var iA=require("@msgpack/msgpack");o();var vA={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])},BA=D=>({name:"PBKDF2",hash:"SHA-256",iterations:600,salt:D}),CA=32,EA=1e6,fA=2147483648,nA=32,T=[79,68,73,78,1,75,105,109],ix=16,bx=64,sA=16;function bA(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 $F(D){return isFinite(D)}function yF(D){return Array.isArray(D)}function Mx(D){return $F(D)?D:v}function cx(D){return D instanceof Uint8Array?D:v}function gF(D,...x){let A;try{A=(0,iA.decode)(D)}catch{return v}if(!yF(A))return v;let F=new Array(A.length);for(let r=0;r<x.length;r++)if(F[r]=x[r](A[r]),F[r]===v)return v;return F}function Ux(D,...x){if(D.length<T.length)return m;for(let A=0;A<T.length;A++)if(D[A]!==T[A])return m;return gF(D.subarray(T.length),...x)}var ox=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 e=0;e<t;e++)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 Kx=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(vA,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(BA(x),this.key,{name:"AES-GCM",length:256},!1,[A])}},Vx=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(CA)),F=await x.generatePeerKey(A,"encrypt");return new D(A,F)}get limitReached(){return this.key===void 0?!1:this.number_of_bytes>=fA||this.number_of_packets>=EA}nextSequenceNumber(x){return this.sequenceNumbers[x]++}};function b0(D,x){return{kind:"encrypted",key:D,material:x,antiReplays:{datagram:new ox(nA),userData:new ox(0),message:new ox(0)}}}var Wx=class D{constructor(x,A,F,r){this.additionalData=x;this.sequenceNumber=A;this.seed=F;this.encrypted=r}static parse(x){let A=Ux(x,cx,Mx,cx);if(A===v||A===m)return A;let[F,r,t]=A,e=x.subarray(0,x.length-t.length);return new D(e,r,F,t)}isSameSeed(x){return bA(this.seed,x.seed)}async generateKey(x){return await x.generatePeerKey(this.seed,"decrypt")}};function Qx(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,oA.assert)(!1,"missing content implementation")}return A}var o0=require("@msgpack/msgpack"),lA=require("@4players/odin-common");o();var Xx=class{constructor(x){this.actions=x}changeKey(x){this.masterKey!==x&&(this.masterKey=x,this.ownKey=v,this.actions.resendUserData())}async encryptDatagram(x){let A=await this.getKey("datagram");return A===void 0?x:A===M?v:await LF(A,x)}async encryptMessage(x){let A=await this.getKey("message");return A===void 0?x:A===M?M:await aA(A,x,"message")}async encryptUserData(x){let A=await this.getKey("userData");return A===void 0?x:((0,lA.assert)(A!==M,"key unavailable for user data encryption"),await aA(A,x,"userData",A.seed))}async getKey(x){if(this.ownKey===v||this.ownKey?.limitReached)if(x==="userData")this.ownKey=this.masterKey?await Vx.create(this.masterKey):void 0;else return this.ownKey!==v&&(this.ownKey=v,this.actions.resendUserData()),M;return this.ownKey}reset(){this.ownKey=this.masterKey?v:void 0}};async function aA(D,x,A,...F){let r=D.nextSequenceNumber(A),t=x.length+ix,e=_F(r,F,t),j=e.length-t,B=await uA(D,A,r,e.subarray(0,j),x);return e.set(new Uint8Array(B),j),e}function _F(D,x,A){let F=[];x.forEach(e=>F.push(e)),F.push(D),F.push(new Uint8Array(A));let r=(0,o0.encode)(F),t=new Uint8Array(T.length+r.length);return t.set(T,0),t.set(r,T.length),t}async function LF(D,x){let A=HF(x);if(A===v)return v;if((A.kind&bx)!==0)return v;let F=A.body.length+ix,r=D.nextSequenceNumber("datagram"),t=(0,o0.encode)([A.kind|bx,A.mediaIds,r,new Uint8Array(F)]),e=t.length-F,j=await uA(D,"datagram",r,t.subarray(0,e),A.body);return t.set(j,e),t}async function uA(D,x,A,F,r){return new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:Qx(x,A),additionalData:F,tagLength:ix*8},D.key,r))}function HF(D){let x=new U(D),A=x.readArrayLength();if(i(A)||A<2)return v;let F=x.readNumber(),r=x.readArrayLength();if(i(F)||i(r))return v;if(r>sA)return v;let t=Array(r);for(let j=0;j<t.length;j++){let B=x.readNumber();if(i(B))return v;t[j]=B}let e=D.subarray(x.position);return{kind:F,mediaIds:t,body:e}}var cA=require("@msgpack/msgpack");o();var Zx=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),e=b0(t,r),j=await zx(e,"userData",r.additionalData,r.sequenceNumber,r.encrypted);j!==v?(this.peerKeys.set(A,e),this.actions.setUserData(A,j)):(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=NF(A);if(this.masterKey===void 0)return F===m?A:v;if(F===v||F===m)return v;let r=this.peerKeys.get(x);if(r?.kind!=="encrypted")return v;let t=await zx(r,"datagram",F.additionalData,F.sequenceNumber,F.encrypted);return t===v?v:PF(F.kind&~bx,F.mediaIds,t)}async decryptMessage(x,A){let F=Ux(A,Mx,cx);if(this.masterKey===void 0)return F===m?A:v;if(F===v||F===m)return v;let r=this.peerKeys.get(x);if(r?.kind!=="encrypted")return v;let[t,e]=F,j=A.subarray(0,A.length-e.length);return zx(r,"message",j,t,e)}async decryptUserData(x,A){let F=Wx.parse(A);if(F===v)return v;if(F===m)return this.peerKeys.delete(x),this.masterKey===void 0?A:v;if(this.masterKey===void 0)return this.peerKeys.set(x,{kind:"broken",material:F}),v;let r=this.peerKeys.get(x);if(r?.kind==="encrypted"&&r.material.isSameSeed(F))r.material=F;else{let e=await F.generateKey(this.masterKey);r=b0(e,F)}let t=await zx(r,"userData",F.additionalData,F.sequenceNumber,F.encrypted);return t===v?this.peerKeys.set(x,{kind:"broken",material:F}):r!==void 0&&this.peerKeys.set(x,r),t}reset(){this.peerKeys.clear()}};function NF(D){let x=new U(D),A=x.readArrayLength();if(i(A)||A<1)return v;let F=x.readNumber();if(i(F))return v;if((F&bx)===0)return m;if(A!==4)return v;let r=x.position;x.readObjects(1);let t=D.subarray(r,x.position),e=x.readNumber(),j=x.readBytes();if(i(e)||i(j))return v;let B=D.subarray(0,D.length-j.length);return{kind:F,mediaIds:t,additionalData:B,sequenceNumber:e,encrypted:j}}async function zx(D,x,A,F,r){let t=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:Qx(x,F),additionalData:A,tagLength:ix*8},D.key,r).catch(()=>v);return t===v?v:D.antiReplays[x].isReplay(F)?v:new Uint8Array(t)}function PF(D,x,A){let F=2;try{let e=new U(A);for(e.position=0;e.position<A.length;)e.readObjects(1),F+=1}catch{return v}let r=(0,cA.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 Yx=class{constructor(x,A){this.active=!1;let F=new Zx(A),r=new Xx(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===M);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){this.crypto.enqueue(async A=>{let F=x.password?await Kx.create(x.password):void 0;this.active=F!==void 0,A.encryption.changeKey(F),await A.decryption.changeKey(F)}).catch(console.error)}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 dA(D,x){return(0,kA.assert)(D.type==="OdinCrypto","only OdinCrypto supported"),new Yx(D,x)}var x0=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,e=(0,w.unwrap)(y.parse(A.token)),j=A.roomId??e.defaultRoomId,B=A.userData??new Uint8Array(0),s=A.position??[0,0,0];(0,w.assert)(j!==void 0,"room id required for multi-room-tokens"),this.cipher=A.cipher?dA(A.cipher,new Rx(this)):void 0,this.onEvent=t,n(`creating new room '${j}' ${this.cipher?"with":"without"} cipher`,e,B,s),this._Connection=new Tx(x,A.transport??"H3",this._HandleEvent.bind(this),r?new URL(r):void 0,e,j,B,s,this.cipher,F?.disableAutoReconnect??!1)}get connectionStats(){let x={...w.CONNECTION_STATS_INITIAL};return this.mainConnection?this.mainConnection.connectionStats:x}async getRtcStats(){return this.mainConnection?.getRtcStats()}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 L){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,n(`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 O){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},n(`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 P){let A=this._Playbacks.get(x.uid)??{media:void 0,playback:void 0};if(A.playback!==void 0&&A.playback!==x&&(A.playback instanceof P?(A.playback.setMediaStream(void 0),A.playback=void 0):this.unlink(A.playback)),A.media!==void 0){let F=await this.mainConnection?.startRemoteVideo(A.media.mediaId);F&&x.setMediaStream(F)}A.playback=x,n(`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 $){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},n(`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).catch(t=>C("failed to start local video",t))),x.audioCapture&&await this.link(x.audioCapture)}}else throw new Error("Linking failed, media was not supported")}unlink(x){if(x instanceof L||x instanceof P){let A=this._Playbacks.get(x.uid);if(A?.playback!==x)return;A.playback=void 0,A.media!==void 0&&(x instanceof L?x.stop(A.media):(this.mainConnection?.stopRemoteVideo(A.media.mediaId),x.setMediaStream(void 0))),n(`unlinking playback media '${x.uid}' from room '${this._Connection.roomId}'`),this._Playbacks.set(x.uid,A)}else if(x instanceof O||x instanceof $){x instanceof $&&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).catch(F=>C("failed to stop media",F)),this._AvailableMediaIds.push(A.media.mediaId),x instanceof $&&this.mainConnection?.stopLocalVideo(A.media.mediaId)),n(`unlinking capture media '${x.uid}' from room '${this._Connection.roomId}'`),this._Captures.delete(x)}else throw new Error("invalid media")}close(){n(`closing room '${this._Connection.roomId}'`),this._Connection.close()}_HandleEvent(x,A){let F=f0(a0.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 $,x instanceof O&&(x.stop(this._Connection,A.media).catch(F=>C("failed to stop media",F)),A.media=void 0));this._AvailableMediaIds.length=0}_HandleRoomUpdate(x){if(x.kind==="Joined"){(0,w.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 O&&x.start(this._Connection,A.media).catch(F=>C("failed to start media",F)),x instanceof $)}_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,w.generateUUID)());A.properties.uid=r;let t=this._Playbacks.get(r)??{media:void 0,playback:void 0};if(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 L&&t.playback.start(t.media),t.playback instanceof P)){let e=t.playback;this.mainConnection.startRemoteVideo(t.media.mediaId).then(j=>{e.setMediaStream(j)}).catch(j=>{C(`failed to start remote video for media ${A.id}`,j)})}}_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.media.mediaId===A&&t.playback!==void 0&&(t.playback instanceof L&&t.playback.stop(t.media),t.playback instanceof P&&this.mainConnection?.stopRemoteVideo(t.media.mediaId),t.media=void 0),F.mediaIds.delete(A))}};qx();function wF(D,x){L0(x?.logger,x?.onLogMessage);let A,F=new Sx((t,e)=>A.receivePacket(t,e)),r=new gx(D);return A=new Ix(r,F.sendDatagram.bind(F),x?.enableHTMLAudioElementFallback??!1),new l0(F,A,x)}var ax=(0,u0.generateUUID)(),c0=[],pA=!1;function OF(){pA||typeof window>"u"||(window.addEventListener("beforeunload",()=>{for(let D of c0)D.deref()?.close()}),pA=!0)}var l0=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||OF(),this._ConnectionPool=x,this._MediaController=A,c0.push(new WeakRef(this)),n("plugin initialized")}get playbackVolume(){return this._PlaybackVolume}joinRoom(x){return new x0(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 P(x.uid,x.customType)}enumerateDevices(){return mx()}setOutputVolume(x){this._MediaController.playbackSetGlobalVolume(x)}async setOutputDevice(x){await this._MediaController.playbackSetDevice(x.device)}close(){this._MediaController.close(),this._ConnectionPool.close(),n("plugin closed")}async dump(){return{createdAt:this._CreatedAt,connections:await this._ConnectionPool.dump(),medias:await this._MediaController.dump()}}};async function hA(){let D=[];for(let x of c0){let A=x.deref();A!==void 0&&D.push(await A.dump())}return JSON.stringify({timestamp:Date.now(),instances:D,background:await J0()})}globalThis.odin_debug_dump_state=hA;window!==void 0&&(window.odin_debug_dump_state=hA);0&&(module.exports={SESSION_ID,createPlugin});
|