@4players/odin-plugin-web 1.11.0 → 1.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var bA=Object.defineProperty;var m=(v,t,e)=>()=>{if(e)throw e[0];try{return v&&(t=v(v=0)),t}catch(j){throw e=[j],j}};var Tx=(v,t)=>{for(var e in t)bA(v,e,{get:t[e],enumerable:!0})};var i={};Tx(i,{AdditionalCaptureBlocks:()=>aA,AdditionalPlaybackBlocks:()=>oA,ClockJumpCheckInterval:()=>hA,ClockJumpThreshold:()=>mA,ConnectInterval:()=>PA,ConnectTimeout:()=>_A,DefaultRefreshRate:()=>uA,DefaultVideoCodec:()=>NA,HealthCheckTimeout:()=>pA,MainConnectionPingInterval:()=>qA,MaxNumberOfDecoders:()=>cA,MinDBFs:()=>Mx,MinTokenLifetime:()=>LA,MinTokenRefreshInterval:()=>HA,PlaybackPreload:()=>lA,RenderQuantumSize:()=>dA,VadPreload:()=>kA,WebRtcAnswerTimeout:()=>IA,WebRtcIceTimeout:()=>$A,WebRtcMaxNegotiationAttempts:()=>gA,WebRtcStatsSnapshotInterval:()=>GA,WebRtcTimeout:()=>yA});var oA,aA,lA,uA,kA,cA,dA,Mx,pA,hA,mA,qA,GA,$A,yA,IA,gA,_A,LA,HA,PA,NA,Rx=m(()=>{"use strict";oA=3,aA=3,lA=3,uA=250,kA=3,cA=512,dA=128,Mx=-758.596,pA=1e4,hA=1e3,mA=1e4,qA=3e3,GA=1e3,$A=3e3,yA=1e4,IA=1e4,gA=3,_A=5e3,LA=6e4,HA=5e3,PA=[0,100,200,200,500],NA="H264"});function vx(v){return typeof v!="symbol"}function l(v){return typeof v=="symbol"}var G,n,O,$,Cx=m(()=>{"use strict";G=Symbol("Unencrypted"),n=Symbol("Invalid"),O=Symbol("Retry"),$=Symbol("UnexpectedEof")});function c(v,t,e){return v.postMessage(t,e)}function V(v,t){return new Promise(e=>{let j=B=>{let[C,E]=B.data;C===t&&(e(B.data[1]),v.removeEventListener("message",j))};v.addEventListener("message",j)})}var C0=m(()=>{"use strict"});function Kx(v,t){v.values[0]=t[0],v.values[1]=t[1]}function E0(v,t){return v.values[2+t*5]}function f0(v,t,e){let j=2+t*5+1;v.values[j+0]=e[0],v.values[j+1]=e[1]}function n0(v){return v.values[0]!==0}function s0(v){return v.values[1]}function i0(v){return v.values[2]}function b0(v,t){return v.values[3]=t}var o0=m(()=>{"use strict"});function a0(v,t){let e=new S(v);e.position=t;let j=e.readObjects(1);return vx(j)?e.position:j}var S,l0=m(()=>{"use strict";Cx();S=class{constructor(t,e=0){this.bytes=t;this.position=e}readArrayLength(){let t=this.readTag();return l(t)?t:(t&240)===144?t&15:t===220?this.readUint16():t===221?this.readUint32():n}readNumber(){let t=this.readTag();return l(t)||(t&128)===0?t:(t&224)===224?t-256:t===202?this.readFloat32():t===203?this.readFloat64():t===204?this.readUint8():t===205?this.readUint16():t===206?this.readUint32():t===207?this.readUint64():t===208?this.readInt8():t===209?this.readInt16():t===210?this.readInt32():t===211?this.readInt64():n}readBytes(){let t=this.readTag();if(l(t))return t;let e;if(t===196)e=this.readUint8();else if(t===197)e=this.readUint16();else if(t===198)e=this.readUint32();else return n;if(l(e))return e;let j=this.consume(e);return j!==$?this.bytes.subarray(j,j+e):$}readObjects(t){for(;t>0;t-=1){let e=this.readTag();if(l(e))return e;let j,B=0,C=0;switch(e){case 192:break;case 194:break;case 195:break;case 196:B=this.readUint8();break;case 197:B=this.readUint16();break;case 198:B=this.readUint32();break;case 199:B=this.readUint8(),C=1;break;case 200:B=this.readUint8(),C=1;break;case 201:B=this.readUint32(),C=1;break;case 202:B=4;break;case 203:B=8;break;case 204:B=1;break;case 205:B=2;break;case 206:B=4;break;case 207:B=8;break;case 208:B=1;break;case 209:B=2;break;case 210:B=4;break;case 211:B=8;break;case 212:B=2;break;case 213:B=3;break;case 214:B=5;break;case 215:B=9;break;case 216:B=17;break;case 217:B=this.readUint8();break;case 218:B=this.readUint16();break;case 219:B=this.readUint32();break;case 220:if(j=this.readUint16(),l(j))return j;t+=j;break;case 221:if(j=this.readUint32(),l(j))return j;t+=j;break;case 222:if(j=this.readUint16(),l(j))return j;t+=j*2;break;case 223:if(j=this.readUint32(),l(j))return j;t+=j*2;break;default:if((e&128)!==0){if((e&240)===128)t+=(e&15)*2;else if((e&240)===144)t+=e&15;else if((e&224)===160)B=e&31;else if((e&224)!==224)return n}}if(B===$)return $;if(this.consume(B+C)===$)return $}}consume(t){if(t===$||this.position+t>this.bytes.length)return $;let e=this.position;return this.position=e+t,e}readTag(){let t=this.consume(1);return vx(t)?this.bytes[t]:t}readUint8(){let t=this.consume(1);return vx(t)?this.bytes[t]:t}readUint16(){let t=this.consume(2);return l(t)?t:this.bytes[t]<<8|this.bytes[t+1]}readUint32(){let t=this.consume(4);return l(t)?t:this.bytes[t]<<24|this.bytes[t+1]<<16|this.bytes[t+2]<<8|this.bytes[t+3]}readUint64(){let t=this.readUint32();if(l(t))return t;if(t>=2097152)return n;let e=this.readUint32();return l(e)?e:t<<32|e}readInt8(){let t=this.readUint8();return l(t)||t>=128&&(t=t-256),t}readInt16(){let t=this.readUint16();return l(t)||t>=32768&&(t=t-65536),t}readInt32(){let t=this.readUint32();return l(t)||t>=2147483648&&(t=t-4294967296),t}readInt64(){let t=this.readUint32();if(l(t))return t;if(t>=2097152||t<-2097152)return n;let e=this.readUint32();return l(e)?e:t<<32|e}readFloat32(){let t=this.consume(4);return l(t)?t:new Float32Array(this.bytes.subarray(t,t+4))[0]}readFloat64(){let t=this.consume(8);return l(t)?t:new Float64Array(this.bytes.subarray(t,t+8))[0]}}});var u0,k0=m(()=>{"use strict";u0="1.11.0"});import{error as wA,warn as JA,info as OA,debug as SA,Logger as UA,LogLevel as TA,CallbackSink as MA,Formatter as RA}from"@4players/odin-common";function c0(v,t){y||(y=v??new UA(TA.DEBUG,"odin-plugin-web",[]),t&&y.sinks.push(new MA(t,RA.structured)))}function p(v,...t){let e=Ex(t);y?y?.error(v,e):wA(v,e)}function k(v,...t){let e=Ex(t);y?y?.warn(v,e):JA(v,e)}function o(v,...t){let e=Ex(t);y?y?.info(v,e):OA(v,e)}function a(v,...t){let e=Ex(t);y?y?.debug(v,e):SA(v,e)}function Ex(...v){if(v.length===1&&typeof v[0]=="object"&&v[0]!==null)return{...v[0]};if(v.length>0)return{args:v}}var y,d0=m(()=>{"use strict"});function q(v){return v.connectionId*4294967296+v.mediaId}var _,M,u=m(()=>{"use strict";Rx();Cx();Rx();C0();o0();l0();k0();d0();Cx();_={isSilent:!0,rmsDBFS:-758.596};M=class{constructor(){this.inFlight=null}run(t){return this.inFlight||(this.inFlight=t().finally(()=>{this.inFlight=null})),this.inFlight}}});function Y(v,t,e,j,B){return Promise.all([XA(v),ZA(e,t,j,B)])}async function XA(v){let t=URL.createObjectURL(new Blob([v],{type:"text/javascript"})),e=new Worker(t,{type:"module",name:"odin worker"});return Q.push(e),e}async function ZA(v,t,e,j){try{let E=new AudioWorkletNode(v,e,j);return R.push(E),E}catch{}let B=Vx.get(v);if(B===void 0){let E=URL.createObjectURL(new Blob([t],{type:"text/javascript"}));B=v.audioWorklet.addModule(E),Vx.set(v,B),B.catch(()=>Vx.delete(v))}await B;let C=new AudioWorkletNode(v,e,j);return R.push(C),C}async function q0(){return{workers:await Promise.all(Q.map(Z)),worklets:await Promise.all(R.map(v=>Z(v.port)))}}function Z(v){let{port1:t,port2:e}=new MessageChannel,{promise:j,resolve:B}=Promise.withResolvers();return e.onmessage=C=>B(C.data),setTimeout(()=>B("timeout"),100),c(v,["dump",{result:t}],[t]),j}var Q,R,z,X,Vx,nx=m(()=>{"use strict";u();Q=[],R=[],z=class{constructor(t,e,j){this.audioContext=t;this.worklet=e;this.worker=j;this.availableIndexes=[];this.medias=new Map;j.addEventListener("message",this._OnMessages.bind(this))}connectOutput(t){this.worklet.disconnect(),this.worklet.connect(t)}receivePacket(t,e){c(this.worker,["playbackReceivePacket",{connectionId:t,packet:e}],[e.buffer])}addMedias(t,e,j=[1,1]){let B=[];for(let C of e){let E=this._GetFreeIndex();E!==void 0&&(this.medias.set(q({connectionId:t,mediaId:C}),{index:E}),B.push({connectionId:t,mediaId:C,index:E,volume:j}))}c(this.worker,["playbackUpdateMedias",{added:B,removed:[]}])}removeMedias(t,e){let j=[];for(let B of e){let C=q({connectionId:t,mediaId:B}),E=this.medias.get(C);E!==void 0&&(this.medias.delete(C),this.availableIndexes.push(E.index),j.push({connectionId:t,mediaId:B,index:E.index}))}c(this.worker,["playbackUpdateMedias",{added:[],removed:j}])}close(){c(this.worker,["close",void 0]),c(this.worklet.port,["close",void 0]);let t=Q.indexOf(this.worker);t>=0&&Q.splice(t,1);let e=R.indexOf(this.worklet);e>=0&&R.splice(e,1)}async dump(){return{playbackWorker:await Z(this.worker),playbackWorklet:await Z(this.worklet.port)}}_GetFreeIndex(){return this.availableIndexes.pop()}_OnMessages(t){}},X=class v{constructor(t,e,j,B,C){this.worklet=t;this.worker=e;this.sink=(E,f)=>{C.deref()!==void 0?j(E,f):(p("capture worker was left abandoned, aborting capture worker"),v.shutdown(t,e))},this.monitorSink=(E,f)=>{C.deref()!==void 0?B(E,f):(p("capture worker was left abandoned, aborting capture worker"),v.shutdown(t,e))},e.addEventListener("message",this._OnMessages.bind(this))}get context(){return this.worklet.context}setMedias(t){c(this.worker,["captureSetMedias",{connections:t}])}setVad(t){c(this.worker,["captureSetVad",t])}close(){v.shutdown(this.worklet,this.worker)}static shutdown(t,e){c(t.port,["close",void 0]),c(e,["close",void 0]);let j=Q.indexOf(e);j>=0&&Q.splice(j,1);let B=R.indexOf(t);B>=0&&R.splice(B,1)}async dump(){return{captureWorker:await Z(this.worker),captureWorklet:await Z(this.worklet.port)}}_OnMessages(t){let[e,j]=t.data;e==="sendPacket"&&(j.connectionId===0?this.monitorSink(j.connectionId,j.packet):this.sink(j.connectionId,j.packet))}};Vx=new WeakMap});var Wx,G0=m(()=>{Wx=`"use strict";(()=>{var dn=Object.create;var or=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var Cn=Object.getPrototypeOf,Gn=Object.prototype.hasOwnProperty;var pn=(e,A)=>()=>{try{return A||e((A={exports:{}}).exports,A),A.exports}catch(t){throw A=0,t}},En=(e,A)=>{for(var t in A)or(e,t,{get:A[t],enumerable:!0})},mn=(e,A,t,s)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of fn(A))!Gn.call(e,i)&&i!==t&&or(e,i,{get:()=>A[i],enumerable:!(s=qn(A,i))||s.enumerable});return e};var hn=(e,A,t)=>(t=e!=null?dn(Cn(e)):{},mn(A||!e||!e.__esModule?or(t,"default",{value:e,enumerable:!0}):t,e));var $t=pn((ht,KA)=>{"use strict";var TA=(()=>{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",q=i&&globalThis.name=="em-pthread",p=[],I="./this.program",g=(r,j)=>{throw j};i&&(e=self.location.href);var MA="",U,Ht;if(s||i){try{MA=new URL(".",e).href}catch{}i&&(Ht=r=>{var j=new XMLHttpRequest;return j.open("GET",r,!1),j.responseType="arraybuffer",j.send(null),new Uint8Array(j.response)}),U=async r=>{var j=await fetch(r,{credentials:"same-origin"});if(j.ok)return j.arrayBuffer();throw new Error(j.status+" : "+j.url)}}var SA=console.log.bind(console),P=console.error.bind(console),Dt,eA,GA=!1,X;class yt{}class Ds extends yt{}function Lt(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 _r;if(q){let r=function(j){try{var n=j.data,l=n.cmd;if(l==1){let o=[];self.onmessage=a=>o.push(a),_r=()=>{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"&&(SA=t[a]),a=="printErr"&&(P=t[a]));iA=n.wasmMemory,Dr(),eA=n.wasmModule,Nr(),gj(),_r()}else if(l==2){Kt(n.pthread_ptr),sr(n.pthread_ptr,0,0,1,0,0),E.threadInitTLS(),tr(n.pthread_ptr),VA||(pj(),VA=!0);try{Mt(n.start_routine,n.arg)}catch(o){if(o!="unwind")throw o}}else l==4?VA&&yA():l&&(P(\`worker: received unknown command \${l}\`),P(n))}catch(o){throw Hr&&mj(),o}};var Ls=r,VA=!1;self.onunhandledrejection=j=>{throw j.reason||j},self.onmessage=r}var Hr=!1;function Dr(){var r=iA.buffer;R=new Int8Array(r),EA=new Int16Array(r),t.HEAPU8=N=new Uint8Array(r),nA=new Uint16Array(r),t.HEAP32=T=new Int32Array(r),t.HEAPU32=$=new Uint32Array(r),t.HEAPF32=xr=new Float32Array(r),mA=new Float64Array(r),V=new BigInt64Array(r),br=new BigUint64Array(r)}function gt(){if(!q){{var r=16777216;iA=new WebAssembly.Memory({initial:r/65536,maximum:r/65536,shared:!0})}Dr()}}function Nt(){var r=t.preRun;r&&(typeof r=="function"&&(r=[r]),wr.push(...r)),Or(wr)}function yr(){Hr=!0,!q&&jA.F()}function Bt(){var r=t.postRun;r&&(typeof r=="function"&&(r=[r]),Sr.push(...r)),Or(Sr)}function pA(r){t.onAbort?.(r),r=\`Aborted(\${r})\`,P(r),GA=!0,r+=". Build with -sASSERTIONS for more info.";var j=new WebAssembly.RuntimeError(r);throw j}var Lr;function xt(){return Lt(\`\\0asm\\0\\0\\0\\xAC=\\\`\\x7F\\0\\\`\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\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
+ var oA=Object.defineProperty;var m=(v,t,e)=>()=>{if(e)throw e[0];try{return v&&(t=v(v=0)),t}catch(j){throw e=[j],j}};var Tx=(v,t)=>{for(var e in t)oA(v,e,{get:t[e],enumerable:!0})};var i={};Tx(i,{AdditionalCaptureBlocks:()=>lA,AdditionalPlaybackBlocks:()=>aA,ClockJumpCheckInterval:()=>mA,ClockJumpThreshold:()=>qA,ConnectInterval:()=>NA,ConnectTimeout:()=>LA,DefaultRefreshRate:()=>kA,DefaultVideoCodec:()=>JA,HealthCheckTimeout:()=>hA,MainConnectionPingInterval:()=>GA,MaxNumberOfDecoders:()=>dA,MaxReconnectDuration:()=>wA,MinDBFs:()=>Mx,MinTokenLifetime:()=>HA,MinTokenRefreshInterval:()=>PA,PlaybackPreload:()=>uA,RenderQuantumSize:()=>pA,VadPreload:()=>cA,WebRtcAnswerTimeout:()=>gA,WebRtcIceTimeout:()=>yA,WebRtcMaxNegotiationAttempts:()=>_A,WebRtcStatsSnapshotInterval:()=>$A,WebRtcTimeout:()=>IA});var aA,lA,uA,kA,cA,dA,pA,Mx,hA,mA,qA,GA,$A,yA,IA,gA,_A,LA,HA,PA,NA,wA,JA,Rx=m(()=>{"use strict";aA=3,lA=3,uA=3,kA=250,cA=3,dA=512,pA=128,Mx=-758.596,hA=1e4,mA=1e3,qA=1e4,GA=3e3,$A=1e3,yA=3e3,IA=1e4,gA=1e4,_A=3,LA=5e3,HA=6e4,PA=5e3,NA=[0,100,200,200,500],wA=12e4,JA="H264"});function vx(v){return typeof v!="symbol"}function l(v){return typeof v=="symbol"}var G,n,O,$,Cx=m(()=>{"use strict";G=Symbol("Unencrypted"),n=Symbol("Invalid"),O=Symbol("Retry"),$=Symbol("UnexpectedEof")});function c(v,t,e){return v.postMessage(t,e)}function V(v,t){return new Promise(e=>{let j=B=>{let[C,E]=B.data;C===t&&(e(B.data[1]),v.removeEventListener("message",j))};v.addEventListener("message",j)})}var C0=m(()=>{"use strict"});function Kx(v,t){v.values[0]=t[0],v.values[1]=t[1]}function E0(v,t){return v.values[2+t*5]}function f0(v,t,e){let j=2+t*5+1;v.values[j+0]=e[0],v.values[j+1]=e[1]}function n0(v){return v.values[0]!==0}function s0(v){return v.values[1]}function i0(v){return v.values[2]}function b0(v,t){return v.values[3]=t}var o0=m(()=>{"use strict"});function a0(v,t){let e=new S(v);e.position=t;let j=e.readObjects(1);return vx(j)?e.position:j}var S,l0=m(()=>{"use strict";Cx();S=class{constructor(t,e=0){this.bytes=t;this.position=e}readArrayLength(){let t=this.readTag();return l(t)?t:(t&240)===144?t&15:t===220?this.readUint16():t===221?this.readUint32():n}readNumber(){let t=this.readTag();return l(t)||(t&128)===0?t:(t&224)===224?t-256:t===202?this.readFloat32():t===203?this.readFloat64():t===204?this.readUint8():t===205?this.readUint16():t===206?this.readUint32():t===207?this.readUint64():t===208?this.readInt8():t===209?this.readInt16():t===210?this.readInt32():t===211?this.readInt64():n}readBytes(){let t=this.readTag();if(l(t))return t;let e;if(t===196)e=this.readUint8();else if(t===197)e=this.readUint16();else if(t===198)e=this.readUint32();else return n;if(l(e))return e;let j=this.consume(e);return j!==$?this.bytes.subarray(j,j+e):$}readObjects(t){for(;t>0;t-=1){let e=this.readTag();if(l(e))return e;let j,B=0,C=0;switch(e){case 192:break;case 194:break;case 195:break;case 196:B=this.readUint8();break;case 197:B=this.readUint16();break;case 198:B=this.readUint32();break;case 199:B=this.readUint8(),C=1;break;case 200:B=this.readUint8(),C=1;break;case 201:B=this.readUint32(),C=1;break;case 202:B=4;break;case 203:B=8;break;case 204:B=1;break;case 205:B=2;break;case 206:B=4;break;case 207:B=8;break;case 208:B=1;break;case 209:B=2;break;case 210:B=4;break;case 211:B=8;break;case 212:B=2;break;case 213:B=3;break;case 214:B=5;break;case 215:B=9;break;case 216:B=17;break;case 217:B=this.readUint8();break;case 218:B=this.readUint16();break;case 219:B=this.readUint32();break;case 220:if(j=this.readUint16(),l(j))return j;t+=j;break;case 221:if(j=this.readUint32(),l(j))return j;t+=j;break;case 222:if(j=this.readUint16(),l(j))return j;t+=j*2;break;case 223:if(j=this.readUint32(),l(j))return j;t+=j*2;break;default:if((e&128)!==0){if((e&240)===128)t+=(e&15)*2;else if((e&240)===144)t+=e&15;else if((e&224)===160)B=e&31;else if((e&224)!==224)return n}}if(B===$)return $;if(this.consume(B+C)===$)return $}}consume(t){if(t===$||this.position+t>this.bytes.length)return $;let e=this.position;return this.position=e+t,e}readTag(){let t=this.consume(1);return vx(t)?this.bytes[t]:t}readUint8(){let t=this.consume(1);return vx(t)?this.bytes[t]:t}readUint16(){let t=this.consume(2);return l(t)?t:this.bytes[t]<<8|this.bytes[t+1]}readUint32(){let t=this.consume(4);return l(t)?t:this.bytes[t]<<24|this.bytes[t+1]<<16|this.bytes[t+2]<<8|this.bytes[t+3]}readUint64(){let t=this.readUint32();if(l(t))return t;if(t>=2097152)return n;let e=this.readUint32();return l(e)?e:t<<32|e}readInt8(){let t=this.readUint8();return l(t)||t>=128&&(t=t-256),t}readInt16(){let t=this.readUint16();return l(t)||t>=32768&&(t=t-65536),t}readInt32(){let t=this.readUint32();return l(t)||t>=2147483648&&(t=t-4294967296),t}readInt64(){let t=this.readUint32();if(l(t))return t;if(t>=2097152||t<-2097152)return n;let e=this.readUint32();return l(e)?e:t<<32|e}readFloat32(){let t=this.consume(4);return l(t)?t:new Float32Array(this.bytes.subarray(t,t+4))[0]}readFloat64(){let t=this.consume(8);return l(t)?t:new Float64Array(this.bytes.subarray(t,t+8))[0]}}});var u0,k0=m(()=>{"use strict";u0="1.11.1"});import{error as OA,warn as SA,info as UA,debug as TA,Logger as MA,LogLevel as RA,CallbackSink as KA,Formatter as VA}from"@4players/odin-common";function c0(v,t){y||(y=v??new MA(RA.DEBUG,"odin-plugin-web",[]),t&&y.sinks.push(new KA(t,VA.structured)))}function p(v,...t){let e=Ex(t);y?y?.error(v,e):OA(v,e)}function k(v,...t){let e=Ex(t);y?y?.warn(v,e):SA(v,e)}function o(v,...t){let e=Ex(t);y?y?.info(v,e):UA(v,e)}function a(v,...t){let e=Ex(t);y?y?.debug(v,e):TA(v,e)}function Ex(...v){if(v.length===1&&typeof v[0]=="object"&&v[0]!==null)return{...v[0]};if(v.length>0)return{args:v}}var y,d0=m(()=>{"use strict"});function q(v){return v.connectionId*4294967296+v.mediaId}var _,M,u=m(()=>{"use strict";Rx();Cx();Rx();C0();o0();l0();k0();d0();Cx();_={isSilent:!0,rmsDBFS:-758.596};M=class{constructor(){this.inFlight=null}run(t){return this.inFlight||(this.inFlight=t().finally(()=>{this.inFlight=null})),this.inFlight}}});function Y(v,t,e,j,B){return Promise.all([YA(v),xF(e,t,j,B)])}async function YA(v){let t=URL.createObjectURL(new Blob([v],{type:"text/javascript"})),e=new Worker(t,{type:"module",name:"odin worker"});return Q.push(e),e}async function xF(v,t,e,j){try{let E=new AudioWorkletNode(v,e,j);return R.push(E),E}catch{}let B=Vx.get(v);if(B===void 0){let E=URL.createObjectURL(new Blob([t],{type:"text/javascript"}));B=v.audioWorklet.addModule(E),Vx.set(v,B),B.catch(()=>Vx.delete(v))}await B;let C=new AudioWorkletNode(v,e,j);return R.push(C),C}async function q0(){return{workers:await Promise.all(Q.map(Z)),worklets:await Promise.all(R.map(v=>Z(v.port)))}}function Z(v){let{port1:t,port2:e}=new MessageChannel,{promise:j,resolve:B}=Promise.withResolvers();return e.onmessage=C=>B(C.data),setTimeout(()=>B("timeout"),100),c(v,["dump",{result:t}],[t]),j}var Q,R,z,X,Vx,nx=m(()=>{"use strict";u();Q=[],R=[],z=class{constructor(t,e,j){this.audioContext=t;this.worklet=e;this.worker=j;this.availableIndexes=[];this.medias=new Map;j.addEventListener("message",this._OnMessages.bind(this))}connectOutput(t){this.worklet.disconnect(),this.worklet.connect(t)}receivePacket(t,e){c(this.worker,["playbackReceivePacket",{connectionId:t,packet:e}],[e.buffer])}addMedias(t,e,j=[1,1]){let B=[];for(let C of e){let E=this._GetFreeIndex();E!==void 0&&(this.medias.set(q({connectionId:t,mediaId:C}),{index:E}),B.push({connectionId:t,mediaId:C,index:E,volume:j}))}c(this.worker,["playbackUpdateMedias",{added:B,removed:[]}])}removeMedias(t,e){let j=[];for(let B of e){let C=q({connectionId:t,mediaId:B}),E=this.medias.get(C);E!==void 0&&(this.medias.delete(C),this.availableIndexes.push(E.index),j.push({connectionId:t,mediaId:B,index:E.index}))}c(this.worker,["playbackUpdateMedias",{added:[],removed:j}])}close(){c(this.worker,["close",void 0]),c(this.worklet.port,["close",void 0]);let t=Q.indexOf(this.worker);t>=0&&Q.splice(t,1);let e=R.indexOf(this.worklet);e>=0&&R.splice(e,1)}async dump(){return{playbackWorker:await Z(this.worker),playbackWorklet:await Z(this.worklet.port)}}_GetFreeIndex(){return this.availableIndexes.pop()}_OnMessages(t){}},X=class v{constructor(t,e,j,B,C){this.worklet=t;this.worker=e;this.sink=(E,f)=>{C.deref()!==void 0?j(E,f):(p("capture worker was left abandoned, aborting capture worker"),v.shutdown(t,e))},this.monitorSink=(E,f)=>{C.deref()!==void 0?B(E,f):(p("capture worker was left abandoned, aborting capture worker"),v.shutdown(t,e))},e.addEventListener("message",this._OnMessages.bind(this))}get context(){return this.worklet.context}setMedias(t){c(this.worker,["captureSetMedias",{connections:t}])}setVad(t){c(this.worker,["captureSetVad",t])}close(){v.shutdown(this.worklet,this.worker)}static shutdown(t,e){c(t.port,["close",void 0]),c(e,["close",void 0]);let j=Q.indexOf(e);j>=0&&Q.splice(j,1);let B=R.indexOf(t);B>=0&&R.splice(B,1)}async dump(){return{captureWorker:await Z(this.worker),captureWorklet:await Z(this.worklet.port)}}_OnMessages(t){let[e,j]=t.data;e==="sendPacket"&&(j.connectionId===0?this.monitorSink(j.connectionId,j.packet):this.sink(j.connectionId,j.packet))}};Vx=new WeakMap});var Wx,G0=m(()=>{Wx=`"use strict";(()=>{var dn=Object.create;var or=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var Cn=Object.getPrototypeOf,Gn=Object.prototype.hasOwnProperty;var pn=(e,A)=>()=>{try{return A||e((A={exports:{}}).exports,A),A.exports}catch(t){throw A=0,t}},En=(e,A)=>{for(var t in A)or(e,t,{get:A[t],enumerable:!0})},mn=(e,A,t,s)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of fn(A))!Gn.call(e,i)&&i!==t&&or(e,i,{get:()=>A[i],enumerable:!(s=qn(A,i))||s.enumerable});return e};var hn=(e,A,t)=>(t=e!=null?dn(Cn(e)):{},mn(A||!e||!e.__esModule?or(t,"default",{value:e,enumerable:!0}):t,e));var $t=pn((ht,KA)=>{"use strict";var TA=(()=>{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",q=i&&globalThis.name=="em-pthread",p=[],I="./this.program",g=(r,j)=>{throw j};i&&(e=self.location.href);var MA="",U,Ht;if(s||i){try{MA=new URL(".",e).href}catch{}i&&(Ht=r=>{var j=new XMLHttpRequest;return j.open("GET",r,!1),j.responseType="arraybuffer",j.send(null),new Uint8Array(j.response)}),U=async r=>{var j=await fetch(r,{credentials:"same-origin"});if(j.ok)return j.arrayBuffer();throw new Error(j.status+" : "+j.url)}}var SA=console.log.bind(console),P=console.error.bind(console),Dt,eA,GA=!1,X;class yt{}class ys extends yt{}function Lt(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 _r;if(q){let r=function(j){try{var n=j.data,l=n.cmd;if(l==1){let o=[];self.onmessage=a=>o.push(a),_r=()=>{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"&&(SA=t[a]),a=="printErr"&&(P=t[a]));iA=n.wasmMemory,Dr(),eA=n.wasmModule,Nr(),gj(),_r()}else if(l==2){Kt(n.pthread_ptr),sr(n.pthread_ptr,0,0,1,0,0),E.threadInitTLS(),tr(n.pthread_ptr),VA||(pj(),VA=!0);try{Mt(n.start_routine,n.arg)}catch(o){if(o!="unwind")throw o}}else l==4?VA&&yA():l&&(P(\`worker: received unknown command \${l}\`),P(n))}catch(o){throw Hr&&mj(),o}};var gs=r,VA=!1;self.onunhandledrejection=j=>{throw j.reason||j},self.onmessage=r}var Hr=!1;function Dr(){var r=iA.buffer;R=new Int8Array(r),EA=new Int16Array(r),t.HEAPU8=N=new Uint8Array(r),nA=new Uint16Array(r),t.HEAP32=T=new Int32Array(r),t.HEAPU32=$=new Uint32Array(r),t.HEAPF32=xr=new Float32Array(r),mA=new Float64Array(r),V=new BigInt64Array(r),br=new BigUint64Array(r)}function gt(){if(!q){{var r=16777216;iA=new WebAssembly.Memory({initial:r/65536,maximum:r/65536,shared:!0})}Dr()}}function Nt(){var r=t.preRun;r&&(typeof r=="function"&&(r=[r]),wr.push(...r)),Or(wr)}function yr(){Hr=!0,!q&&jA.F()}function Bt(){var r=t.postRun;r&&(typeof r=="function"&&(r=[r]),Sr.push(...r)),Or(Sr)}function pA(r){t.onAbort?.(r),r=\`Aborted(\${r})\`,P(r),GA=!0,r+=". Build with -sASSERTIONS for more info.";var j=new WebAssembly.RuntimeError(r);throw j}var Lr;function xt(){return Lt(\`\\0asm\\0\\0\\0\\xAC=\\\`\\x7F\\0\\\`\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\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\\xBFab\\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\\0aa\\x80\\x80\\xFB\\xF9\\0\\x07\\f&\\0\\f\\x07\\f\\f\\0\\x07\\0\\x07'(
4
4
  \\b\\v)\\x07*\\0\\f+,-\\v\\0\\0\\x07\\0\\b\\b\\x1B
@@ -3231,7 +3231,7 @@ K\\xE08\\xDF\\0}\\xBC\\x8A\\x1B\\f\\xE5\\xFF\\xCF\\xE8?\\x9F\\xFFFq\\0\\x88\\xB
3231
3231
 
3232
3232
  
3233
3233
  \\x07\\0\\0 \\v\\0\\0 \\v\\0\\0\\v\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\v\\r\\0\\r\\0\\0\\0 \\0\\0\\0 \\0\\0\\0!\\f\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\f\\0\\0\\0\\0\\0\\f\\0\\0\\f!\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0*\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 !\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\xC0 \\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\x000123456789ABCDEF \\0x\\0NSt3__214__shared_countE\\0\\0\\0\\0\\xA4\\0\\xAC\\0\\0\\0\\0\\0\\0\\0\\0p\\0\\0\\0\\0\\0NSt3__219__shared_weak_countE\\0\\0\\0H\\0\\xD8\\0\\xE8\\0N10__cxxabiv116__shim_type_infoE\\0\\0\\0\\0H\\0\\b\\0\\xCC\\0N10__cxxabiv117__class_type_infoE\\0\\0\\0H\\x008\\0\\xCC\\0N10__cxxabiv117__pbase_type_infoE\\0\\0\\0H\\0h\\0,\\0N10__cxxabiv119__pointer_type_infoE\\0H\\0\\x98\\0\\xCC\\0N10__cxxabiv120__function_type_infoE\\0\\0\\0\\0H\\0\\xCC\\0,\\0N10__cxxabiv129__pointer_to_member_type_infoE\\0\\0\\0\\0\\0\\0\\0\\0m\\0\\0\\0n\\0\\0\\0o\\0\\0\\0p\\0\\0\\0q\\0\\0\\0H\\0$\\0\\xCC\\0N10__cxxabiv123__fundamental_type_infoE\\0\\0T\\0v\\0Dn\\0\\0\\0\\0\\0d\\0b\\0\\0\\0\\0p\\0c\\0\\0\\0\\0|\\0h\\0\\0\\0\\0\\x88\\0a\\0\\0\\0\\0\\x94\\0s\\0\\0\\0\\0\\xA0\\0t\\0\\0\\0\\0\\xAC\\0i\\0\\0\\0\\0\\xB8\\0j\\0\\0\\0\\0\\xC4\\0l\\0\\0\\0\\0\\xD0\\0m\\0\\0\\0\\0\\xDC\\0x\\0\\0\\0\\0\\xE8\\0y\\0\\0\\0\\0\\xF4\\0f\\0\\0\\0\\0\\0\\b\\0\\0\\0\\0\\0\\xEC\\0Pf\\0\\0\\0\\0d\\0\\0\\0\\0\\0\\0\\0\\xFC\\0m\\0\\0\\0r\\0\\0\\0o\\0\\0\\0p\\0\\0\\0s\\0\\0\\0t\\0\\0\\0u\\0\\0\\0v\\0\\0\\0\\0\\0\\0\\0h\\0m\\0\\0\\0w\\0\\0\\0o\\0\\0\\0p\\0\\0\\0s\\0\\0\\0x\\0\\0\\0y\\0\\0\\0z\\0\\0\\0H\\0t\\0\\xFC\\0N10__cxxabiv120__si_class_type_infoE\\0\\0\\0\\0\\0\\0\\0\\0\\xC4\\0m\\0\\0\\0{\\0\\0\\0o\\0\\0\\0p\\0\\0\\0s\\0\\0\\0|\\0\\0\\0}\\0\\0\\0~\\0\\0\\0H\\0\\xD0\\0\\xFC\\0N10__cxxabiv121__vmi_class_type_infoE\\0\\0\\0\\0\\0\\0\\0\\\\\\0m\\0\\0\\0\\x7F\\0\\0\\0o\\0\\0\\0p\\0\\0\\0\\x80\\0\\0\\0\\0\\0\\0\\0\\\\\\0E\\0\\0\\0\\x81\\0\\0\\0\\x82\\0\\0\\0 \\x000\\0St9exception\\0\\0\\0\\0H\\0L\\0(\\0St9bad_alloc\\0\\0\\0\\0H\\0h\\0@\\0St20bad_array_new_length\\0\\0\\0\\0\\0\\0\\0\\0\\x98\\0G\\0\\0\\0\\x83\\0\\0\\0\\x84\\0\\0\\0H\\0\\xA4\\0(\\0St11logic_error\\0\\0\\0\\0\\0\\xC8\\0G\\0\\0\\0\\x85\\0\\0\\0\\x84\\0\\0\\0H\\0\\xD4\\0\\x98\\0St12length_error\\0\\0\\0\\0 \\0\\xF0\\0St9type_info\\0_\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0e\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0f\\0\\0\\0g\\0\\0\\0\\xD0\\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@\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0h\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0f\\0\\0\\0i\\0\\0\\0\\xD8\\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
3234
- \\f\\xD8\\0"\\0\\0\\0\\0\`)}function ys(r){return r}async function bt(r){return r}async function Pt(r,j){try{var n=await bt(r),l=await WebAssembly.instantiate(n,j);return l}catch(o){P(\`failed to asynchronously prepare wasm: \${o}\`),pA(o)}}async function Jt(r,j,n){return Pt(j,n)}function gr(){un();var r={a:Lj};return r}async function Nr(){function r(u,c){return jA=u.exports,St(jA.M),kn(jA),eA=c,jA}function j(u){return r(u.instance,u.module)}var n=gr(),l=t.instantiateWasm;if(l)return new Promise(u=>{l(n,(c,f)=>u(r(c,f)))});if(q){var o=new WebAssembly.Instance(eA,gr());return r(o,eA)}Lr??=xt();var a=await Jt(Dt,Lr,n),k=j(a);return k}class Br{name="ExitStatus";constructor(j){this.message=\`Program terminated with exit(\${j})\`,this.status=j}}var EA,T,V,R,xr,mA,nA,$,br,N,Pr=r=>{r.terminate(),r.onmessage=j=>{}},Jr=r=>{var j=E.pthreads[r];E.returnWorkerToPool(j)},Or=r=>{for(;r.length>0;)r.shift()(t)},wr=[],Ot=r=>{var j=E.getNewWorker();if(!j)return 6;E.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},RA=0,WA=()=>zA||RA>0,wt=()=>Dj(),Ur=r=>_j(r),Ut=r=>Hj(r),sA=(r,j,n,...l)=>{var o=8*l.length*2,a=wt(),k=Ut(o),u=k>>3;for(var c of l)typeof c=="bigint"?(V[u++]=1n,V[u++]=c):(V[u++]=0n,mA[u++]=c);var f=$j(r,j,o,k,n);return Ur(a),f};function Tr(r){if(q)return sA(0,0,1,r);X=r,WA()||(E.terminateAllThreads(),t.onExit?.(r),GA=!0),g(r,new Br(r))}function Kr(r){if(q)return sA(1,0,0,r);QA(r)}var Tt=(r,j)=>{if(X=r,q)throw Kr(r),"unwind";Tr(r)},QA=Tt,Mr=!Atomics.waitAsync||globalThis.navigator?.userAgent&&Number((navigator.userAgent.match(/Chrom(e|ium)\\/([0-9]+)\\./)||[])[2])<91,E={unusedWorkers:[],tlsInitFunctions:[],pthreads:{},init(){q||E.initMainThread()},initMainThread(){},terminateAllThreads:()=>{for(var r of Object.values(E.pthreads))Pr(r);for(var r of E.unusedWorkers)Pr(r);E.unusedWorkers=[],E.pthreads={}},terminateRuntime:()=>{E.terminateAllThreads();var r=LA();Ej(0,0,0,1),Mr||Atomics.notify(T,r>>2)},returnWorkerToPool:r=>{var j=r.pthread_ptr;delete E.pthreads[j],E.unusedWorkers.push(r),r.pthread_ptr=0,Fj(j)},threadInitTLS(){E.tlsInitFunctions.forEach(r=>r())},loadWasmModuleToWorker:r=>new Promise(j=>{r.onmessage=a=>{var k=a.data,u=k.cmd;if(k.targetThread){var c=E.pthreads[k.targetThread];c?.postMessage(k);return}if(k==="setimmediate"||k==="_si"){r.postMessage(k);return}switch(u){case 4:yA();break;case 5:Ot(k);break;case 6:dj(()=>Jr(k.thread));break;case 3:j(r);break;case 9:t[k.handler](...k.args);break;default:u&&P(\`worker sent an unknown command \${u}\`)}},r.onerror=a=>{var k="worker sent an error!";throw P(\`\${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:eA})}),allocateUnusedWorker(){var r,j=e;return r=new Worker(j,{name:"em-pthread"}),E.unusedWorkers.push(r),r},getNewWorker(){if(E.unusedWorkers.length==0){var r=E.allocateUnusedWorker();E.loadWasmModuleToWorker(r)}return E.unusedWorkers.pop()}},Sr=[];function Kt(r){var j=$[r+48>>2],n=$[r+52>>2],l=j-n;Ij(j,l),Ur(j)}var Vr=[],Rr=r=>{var j=Vr[r];return j||(Vr[r]=j=yj.get(r)),j},Mt=(r,j)=>{RA=0,zA=0;var n=Rr(r)(j);function l(o){if(WA()){X=o;return}ir(o)}l(n)},zA=!0,St=r=>E.tlsInitFunctions.push(r),iA;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 Rt=0,Wt=(r,j,n)=>{var l=new Vt(r);l.init(j,n),Rt++,pA()},Qt=()=>pA(""),_=r=>{for(var j="";;){var n=N[r++];if(!n)return j;j+=String.fromCharCode(n)}},Z={},Y={},hA={},lA=class extends Error{constructor(j){super(j),this.name="BindingError"}},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 x(r,j,n={}){return zt(r,j,n)}var Wr=(r,j,n)=>{switch(j){case 1:return n?l=>R[l]:l=>N[l];case 2:return n?l=>EA[l>>1]:l=>nA[l>>1];case 4:return n?l=>T[l>>2]:l=>$[l>>2];case 8:return n?l=>V[l>>3]:l=>br[l>>3];default:throw new TypeError(\`invalid integer width (\${j}): \${r}\`)}},Xt=(r,j,n,l,o)=>{j=_(j);let a=l===0n,k=u=>u;if(a){let u=n*8;k=c=>BigInt.asUintN(u,c),o=k(o)}x(r,{name:j,fromWireType:k,toWireType:(u,c)=>(typeof c=="number"&&(c=BigInt(c)),c),readValueFromPointer:Wr(j,n,!a),destructorFunction:null})},Zt=(r,j,n,l)=>{j=_(j),x(r,{name:j,fromWireType:function(o){return!!o},toWireType:function(o,a){return a?n:l},readValueFromPointer:function(o){return this.fromWireType(N[o])},destructorFunction:null})},Yt=r=>({count:r.count,deleteScheduled:r.deleteScheduled,preservePointerOnDelete:r.preservePointerOnDelete,ptr:r.ptr,ptrType:r.ptrType,smartPtr:r.smartPtr,smartPtrType:r.smartPtrType}),XA=r=>{function j(n){return n.$$.ptrType.registeredClass.name}G(j(r)+" instance already deleted")},ZA=!1,Qr=r=>{},Ae=r=>{r.smartPtr?r.smartPtrType.rawDestructor(r.smartPtr):r.ptrType.registeredClass.rawDestructor(r.ptr)},zr=r=>{r.count.value-=1;var j=r.count.value===0;j&&Ae(r)},oA=r=>globalThis.FinalizationRegistry?(ZA=new FinalizationRegistry(j=>{zr(j.$$)}),oA=j=>{var n=j.$$,l=!!n.smartPtr;if(l){var o={$$:n};ZA.register(j,o,j)}return j},Qr=j=>ZA.unregister(j),oA(r)):(oA=j=>j,r),$A=[],re=()=>{for(;$A.length;){var r=$A.pop();r.$$.deleteScheduled=!1,r.delete()}},Xr,je=()=>{let r=FA.prototype;Object.assign(r,{isAliasOf(n){if(!(this instanceof FA)||!(n instanceof FA))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||XA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var n=oA(Object.create(Object.getPrototypeOf(this),{$$:{value:Yt(this.$$)}}));return n.$$.count.value+=1,n.$$.deleteScheduled=!1,n},delete(){this.$$.ptr||XA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),Qr(this),zr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||XA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),$A.push(this),$A.length===1&&Xr&&Xr(re),this.$$.deleteScheduled=!0,this}});let j=Symbol.dispose;j&&(r[j]=r.delete)};function FA(){}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)},te=48,ee=57,ne=r=>{r=r.replace(/[^a-zA-Z0-9_]/g,"$");var j=r.charCodeAt(0);return j>=te&&j<=ee?\`_\${r}\`:r};function se(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 vA=(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},YA=r=>{if(r===null)return"null";var j=typeof r;return j==="object"||j==="array"||j==="function"?r.toString():""+r};function ie(r,j){if(j===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;j.$$||G(\`Cannot pass "\${YA(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=vA(j.$$.ptr,n,this.registeredClass);return l}function le(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 "\${YA(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=vA(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,jr.toHandle(()=>o.delete())),r!==null&&r.push(this.rawDestructor,n)}break;default:G("Unsupported sharing policy")}return n}function oe(r,j){if(j===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;j.$$||G(\`Cannot pass "\${YA(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=vA(j.$$.ptr,n,this.registeredClass);return l}function IA(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)},ae={},ke=(r,j)=>{for(j===void 0&&G("ptr should not be undefined");r.baseClass;)j=r.upcast(j),r=r.baseClass;return j},ue=(r,j)=>(j=ke(r,j),ae[j]),ce=class extends Error{constructor(j){super(j),this.name="InternalError"}},_A=r=>{throw new ce(r)},HA=(r,j)=>{(!j.ptrType||!j.ptr)&&_A("makeClassHandle requires ptr and ptrType");var n=!!j.smartPtrType,l=!!j.smartPtr;return n!==l&&_A("Both smartPtrType and smartPtr must be specified"),j.count={value:1},oA(Object.create(r,{$$:{value:j,writable:!0}}))};function de(r){var j=this.getPointee(r);if(!j)return this.destructor(r),null;var n=ue(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?HA(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:j,smartPtrType:this,smartPtr:r}):HA(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?HA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c,smartPtrType:this,smartPtr:r}):HA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c})}var qe=()=>{Object.assign(DA.prototype,{getPointee(r){return this.rawGetPointee&&(r=this.rawGetPointee(r)),r},destructor(r){this.rawDestructor?.(r)},readValueFromPointer:IA,fromWireType:de})};function DA(r,j,n,l,o,a,k,u,c,f,C){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=f,this.rawDestructor=C,!o&&j.baseClass===void 0?l?(this.toWireType=ie,this.destructorFunction=null):(this.toWireType=oe,this.destructorFunction=null):this.toWireType=le}var tj=(r,j,n)=>{t.hasOwnProperty(r)||_A("Replacing nonexistent public symbol"),t[r].overloadTable!==void 0&&n!==void 0?t[r].overloadTable[n]=j:(t[r]=j,t[r].argCount=n)},J=(r,j,n=!1)=>{r=_(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 fe extends Error{}var Ce=r=>{var j=Gj(r),n=_(j);return O(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 fe(\`\${r}: \`+n.map(Ce).join([", "]))},K=(r,j,n)=>{r.forEach(u=>hA[u]=j);function l(u){var c=n(u);c.length!==r.length&&_A("Mismatched type converter count");for(var f=0;f<r.length;++f)x(r[f],c[f])}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)},Ge=(r,j,n,l,o,a,k,u,c,f,C,m,F)=>{C=_(C),a=J(o,a),u&&=J(k,u),f&&=J(c,f),F=J(m,F);var h=ne(C);rj(h,function(){AA(\`Cannot construct \${C} due to unbound types\`,[l])}),K([r,j,n],l?[l]:[],v=>{v=v[0];var y,w;l?(y=v.registeredClass,w=y.instancePrototype):w=FA.prototype;var L=Zr(C,function(...lr){if(Object.getPrototypeOf(this)!==aA)throw new lA(\`Use 'new' to construct \${C}\`);if(D.constructor_body===void 0)throw new lA(\`\${C} has no accessible constructor\`);var xj=D.constructor_body[lr.length];if(xj===void 0)throw new lA(\`Tried to invoke ctor of \${C} with invalid number of parameters (\${lr.length}) - expected (\${Object.keys(D.constructor_body).toString()}) parameters instead!\`);return xj.apply(this,lr)}),aA=Object.create(w,{constructor:{value:L}});L.prototype=aA;var D=new se(C,L,aA,F,y,a,u,f);D.baseClass&&(D.baseClass.__derivedClasses??=[],D.baseClass.__derivedClasses.push(D));var cn=new DA(C,D,!0,!1,!1),Nj=new DA(C+"*",D,!1,!1,!1),Bj=new DA(C+" const*",D,!1,!0,!1);return Yr[r]={pointerType:Nj,constPointerType:Bj},tj(h,L),[cn,Nj,Bj]})},Ar=(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 pe(r,j,n,l){var o=nj(r),a=r.length-2,k=[],u=["fn"];j&&u.push("thisWired");for(var c=0;c<a;++c)k.push(\`arg\${c}\`),u.push(\`arg\${c}Wired\`);k=k.join(),u=u.join();var f=\`return function (\${k}) {
3234
+ \\f\\xD8\\0"\\0\\0\\0\\0\`)}function Ls(r){return r}async function bt(r){return r}async function Pt(r,j){try{var n=await bt(r),l=await WebAssembly.instantiate(n,j);return l}catch(o){P(\`failed to asynchronously prepare wasm: \${o}\`),pA(o)}}async function Jt(r,j,n){return Pt(j,n)}function gr(){un();var r={a:Lj};return r}async function Nr(){function r(u,c){return jA=u.exports,St(jA.M),kn(jA),eA=c,jA}function j(u){return r(u.instance,u.module)}var n=gr(),l=t.instantiateWasm;if(l)return new Promise(u=>{l(n,(c,f)=>u(r(c,f)))});if(q){var o=new WebAssembly.Instance(eA,gr());return r(o,eA)}Lr??=xt();var a=await Jt(Dt,Lr,n),k=j(a);return k}class Br{name="ExitStatus";constructor(j){this.message=\`Program terminated with exit(\${j})\`,this.status=j}}var EA,T,V,R,xr,mA,nA,$,br,N,Pr=r=>{r.terminate(),r.onmessage=j=>{}},Jr=r=>{var j=E.pthreads[r];E.returnWorkerToPool(j)},Or=r=>{for(;r.length>0;)r.shift()(t)},wr=[],Ot=r=>{var j=E.getNewWorker();if(!j)return 6;E.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},RA=0,WA=()=>zA||RA>0,wt=()=>Dj(),Ur=r=>_j(r),Ut=r=>Hj(r),sA=(r,j,n,...l)=>{var o=8*l.length*2,a=wt(),k=Ut(o),u=k>>3;for(var c of l)typeof c=="bigint"?(V[u++]=1n,V[u++]=c):(V[u++]=0n,mA[u++]=c);var f=$j(r,j,o,k,n);return Ur(a),f};function Tr(r){if(q)return sA(0,0,1,r);X=r,WA()||(E.terminateAllThreads(),t.onExit?.(r),GA=!0),g(r,new Br(r))}function Kr(r){if(q)return sA(1,0,0,r);QA(r)}var Tt=(r,j)=>{if(X=r,q)throw Kr(r),"unwind";Tr(r)},QA=Tt,Mr=!Atomics.waitAsync||globalThis.navigator?.userAgent&&Number((navigator.userAgent.match(/Chrom(e|ium)\\/([0-9]+)\\./)||[])[2])<91,E={unusedWorkers:[],tlsInitFunctions:[],pthreads:{},init(){q||E.initMainThread()},initMainThread(){},terminateAllThreads:()=>{for(var r of Object.values(E.pthreads))Pr(r);for(var r of E.unusedWorkers)Pr(r);E.unusedWorkers=[],E.pthreads={}},terminateRuntime:()=>{E.terminateAllThreads();var r=LA();Ej(0,0,0,1),Mr||Atomics.notify(T,r>>2)},returnWorkerToPool:r=>{var j=r.pthread_ptr;delete E.pthreads[j],E.unusedWorkers.push(r),r.pthread_ptr=0,Fj(j)},threadInitTLS(){E.tlsInitFunctions.forEach(r=>r())},loadWasmModuleToWorker:r=>new Promise(j=>{r.onmessage=a=>{var k=a.data,u=k.cmd;if(k.targetThread){var c=E.pthreads[k.targetThread];c?.postMessage(k);return}if(k==="setimmediate"||k==="_si"){r.postMessage(k);return}switch(u){case 4:yA();break;case 5:Ot(k);break;case 6:dj(()=>Jr(k.thread));break;case 3:j(r);break;case 9:t[k.handler](...k.args);break;default:u&&P(\`worker sent an unknown command \${u}\`)}},r.onerror=a=>{var k="worker sent an error!";throw P(\`\${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:eA})}),allocateUnusedWorker(){var r,j=e;return r=new Worker(j,{name:"em-pthread"}),E.unusedWorkers.push(r),r},getNewWorker(){if(E.unusedWorkers.length==0){var r=E.allocateUnusedWorker();E.loadWasmModuleToWorker(r)}return E.unusedWorkers.pop()}},Sr=[];function Kt(r){var j=$[r+48>>2],n=$[r+52>>2],l=j-n;Ij(j,l),Ur(j)}var Vr=[],Rr=r=>{var j=Vr[r];return j||(Vr[r]=j=yj.get(r)),j},Mt=(r,j)=>{RA=0,zA=0;var n=Rr(r)(j);function l(o){if(WA()){X=o;return}ir(o)}l(n)},zA=!0,St=r=>E.tlsInitFunctions.push(r),iA;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 Rt=0,Wt=(r,j,n)=>{var l=new Vt(r);l.init(j,n),Rt++,pA()},Qt=()=>pA(""),_=r=>{for(var j="";;){var n=N[r++];if(!n)return j;j+=String.fromCharCode(n)}},Z={},Y={},hA={},lA=class extends Error{constructor(j){super(j),this.name="BindingError"}},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 x(r,j,n={}){return zt(r,j,n)}var Wr=(r,j,n)=>{switch(j){case 1:return n?l=>R[l]:l=>N[l];case 2:return n?l=>EA[l>>1]:l=>nA[l>>1];case 4:return n?l=>T[l>>2]:l=>$[l>>2];case 8:return n?l=>V[l>>3]:l=>br[l>>3];default:throw new TypeError(\`invalid integer width (\${j}): \${r}\`)}},Xt=(r,j,n,l,o)=>{j=_(j);let a=l===0n,k=u=>u;if(a){let u=n*8;k=c=>BigInt.asUintN(u,c),o=k(o)}x(r,{name:j,fromWireType:k,toWireType:(u,c)=>(typeof c=="number"&&(c=BigInt(c)),c),readValueFromPointer:Wr(j,n,!a),destructorFunction:null})},Zt=(r,j,n,l)=>{j=_(j),x(r,{name:j,fromWireType:function(o){return!!o},toWireType:function(o,a){return a?n:l},readValueFromPointer:function(o){return this.fromWireType(N[o])},destructorFunction:null})},Yt=r=>({count:r.count,deleteScheduled:r.deleteScheduled,preservePointerOnDelete:r.preservePointerOnDelete,ptr:r.ptr,ptrType:r.ptrType,smartPtr:r.smartPtr,smartPtrType:r.smartPtrType}),XA=r=>{function j(n){return n.$$.ptrType.registeredClass.name}G(j(r)+" instance already deleted")},ZA=!1,Qr=r=>{},Ae=r=>{r.smartPtr?r.smartPtrType.rawDestructor(r.smartPtr):r.ptrType.registeredClass.rawDestructor(r.ptr)},zr=r=>{r.count.value-=1;var j=r.count.value===0;j&&Ae(r)},oA=r=>globalThis.FinalizationRegistry?(ZA=new FinalizationRegistry(j=>{zr(j.$$)}),oA=j=>{var n=j.$$,l=!!n.smartPtr;if(l){var o={$$:n};ZA.register(j,o,j)}return j},Qr=j=>ZA.unregister(j),oA(r)):(oA=j=>j,r),$A=[],re=()=>{for(;$A.length;){var r=$A.pop();r.$$.deleteScheduled=!1,r.delete()}},Xr,je=()=>{let r=FA.prototype;Object.assign(r,{isAliasOf(n){if(!(this instanceof FA)||!(n instanceof FA))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||XA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var n=oA(Object.create(Object.getPrototypeOf(this),{$$:{value:Yt(this.$$)}}));return n.$$.count.value+=1,n.$$.deleteScheduled=!1,n},delete(){this.$$.ptr||XA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),Qr(this),zr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||XA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),$A.push(this),$A.length===1&&Xr&&Xr(re),this.$$.deleteScheduled=!0,this}});let j=Symbol.dispose;j&&(r[j]=r.delete)};function FA(){}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)},te=48,ee=57,ne=r=>{r=r.replace(/[^a-zA-Z0-9_]/g,"$");var j=r.charCodeAt(0);return j>=te&&j<=ee?\`_\${r}\`:r};function se(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 vA=(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},YA=r=>{if(r===null)return"null";var j=typeof r;return j==="object"||j==="array"||j==="function"?r.toString():""+r};function ie(r,j){if(j===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;j.$$||G(\`Cannot pass "\${YA(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=vA(j.$$.ptr,n,this.registeredClass);return l}function le(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 "\${YA(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=vA(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,jr.toHandle(()=>o.delete())),r!==null&&r.push(this.rawDestructor,n)}break;default:G("Unsupported sharing policy")}return n}function oe(r,j){if(j===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;j.$$||G(\`Cannot pass "\${YA(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=vA(j.$$.ptr,n,this.registeredClass);return l}function IA(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)},ae={},ke=(r,j)=>{for(j===void 0&&G("ptr should not be undefined");r.baseClass;)j=r.upcast(j),r=r.baseClass;return j},ue=(r,j)=>(j=ke(r,j),ae[j]),ce=class extends Error{constructor(j){super(j),this.name="InternalError"}},_A=r=>{throw new ce(r)},HA=(r,j)=>{(!j.ptrType||!j.ptr)&&_A("makeClassHandle requires ptr and ptrType");var n=!!j.smartPtrType,l=!!j.smartPtr;return n!==l&&_A("Both smartPtrType and smartPtr must be specified"),j.count={value:1},oA(Object.create(r,{$$:{value:j,writable:!0}}))};function de(r){var j=this.getPointee(r);if(!j)return this.destructor(r),null;var n=ue(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?HA(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:j,smartPtrType:this,smartPtr:r}):HA(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?HA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c,smartPtrType:this,smartPtr:r}):HA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c})}var qe=()=>{Object.assign(DA.prototype,{getPointee(r){return this.rawGetPointee&&(r=this.rawGetPointee(r)),r},destructor(r){this.rawDestructor?.(r)},readValueFromPointer:IA,fromWireType:de})};function DA(r,j,n,l,o,a,k,u,c,f,C){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=f,this.rawDestructor=C,!o&&j.baseClass===void 0?l?(this.toWireType=ie,this.destructorFunction=null):(this.toWireType=oe,this.destructorFunction=null):this.toWireType=le}var tj=(r,j,n)=>{t.hasOwnProperty(r)||_A("Replacing nonexistent public symbol"),t[r].overloadTable!==void 0&&n!==void 0?t[r].overloadTable[n]=j:(t[r]=j,t[r].argCount=n)},J=(r,j,n=!1)=>{r=_(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 fe extends Error{}var Ce=r=>{var j=Gj(r),n=_(j);return O(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 fe(\`\${r}: \`+n.map(Ce).join([", "]))},K=(r,j,n)=>{r.forEach(u=>hA[u]=j);function l(u){var c=n(u);c.length!==r.length&&_A("Mismatched type converter count");for(var f=0;f<r.length;++f)x(r[f],c[f])}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)},Ge=(r,j,n,l,o,a,k,u,c,f,C,m,F)=>{C=_(C),a=J(o,a),u&&=J(k,u),f&&=J(c,f),F=J(m,F);var h=ne(C);rj(h,function(){AA(\`Cannot construct \${C} due to unbound types\`,[l])}),K([r,j,n],l?[l]:[],v=>{v=v[0];var y,w;l?(y=v.registeredClass,w=y.instancePrototype):w=FA.prototype;var L=Zr(C,function(...lr){if(Object.getPrototypeOf(this)!==aA)throw new lA(\`Use 'new' to construct \${C}\`);if(D.constructor_body===void 0)throw new lA(\`\${C} has no accessible constructor\`);var xj=D.constructor_body[lr.length];if(xj===void 0)throw new lA(\`Tried to invoke ctor of \${C} with invalid number of parameters (\${lr.length}) - expected (\${Object.keys(D.constructor_body).toString()}) parameters instead!\`);return xj.apply(this,lr)}),aA=Object.create(w,{constructor:{value:L}});L.prototype=aA;var D=new se(C,L,aA,F,y,a,u,f);D.baseClass&&(D.baseClass.__derivedClasses??=[],D.baseClass.__derivedClasses.push(D));var cn=new DA(C,D,!0,!1,!1),Nj=new DA(C+"*",D,!1,!1,!1),Bj=new DA(C+" const*",D,!1,!0,!1);return Yr[r]={pointerType:Nj,constPointerType:Bj},tj(h,L),[cn,Nj,Bj]})},Ar=(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 pe(r,j,n,l){var o=nj(r),a=r.length-2,k=[],u=["fn"];j&&u.push("thisWired");for(var c=0;c<a;++c)k.push(\`arg\${c}\`),u.push(\`arg\${c}Wired\`);k=k.join(),u=u.join();var f=\`return function (\${k}) {
3235
3235
  \`;o&&(f+=\`var destructors = [];
3236
3236
  \`);var C=o?"destructors":"null",m=["humanName","throwBindingError","invoker","fn","runDestructors","fromRetWire","toClassParamWire"];j&&(f+=\`var thisWired = toClassParamWire(\${C}, this);
3237
3237
  \`);for(var c=0;c<a;++c){var F=\`toArg\${c}Wire\`;f+=\`var arg\${c}Wired = \${F}(\${C}, arg\${c});
@@ -3241,8 +3241,8 @@ K\\xE08\\xDF\\0}\\xBC\\x8A\\x1B\\f\\xE5\\xFF\\xCF\\xE8?\\x9F\\xFFFq\\0\\x88\\xB
3241
3241
  \`,m.push(\`\${h}_dtor\`))}return n&&(f+=\`var ret = fromRetWire(rv);
3242
3242
  return ret;
3243
3243
  \`),f+=\`}
3244
- \`,new Function(m,f)}function rr(r,j,n,l,o,a){var k=j.length;k<2&&G("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var u=j[1]!==null&&n!==null,c=nj(j),f=!j[0].isVoid,C=j[0],m=j[1],F=[r,G,l,o,ej,C.fromWireType.bind(C),m?.toWireType.bind(m)],h=2;h<k;++h){var v=j[h];F.push(v.toWireType.bind(v))}if(!c)for(var h=u?1:2;h<j.length;++h)j[h].destructorFunction!==null&&F.push(j[h].destructorFunction);var w=pe(j,u,f,a)(...F);return Zr(r,w)}var Ee=(r,j,n,l,o,a)=>{var k=Ar(j,n);o=J(l,o),K([],[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)},K([],k,f=>(f.splice(1,0,null),u.registeredClass.constructor_body[j-1]=rr(c,f,null,o,a),[])),[]})},sj=r=>{r=r.trim();let j=r.indexOf("(");return j===-1?r:r.slice(0,j)},me=(r,j,n,l,o,a,k,u,c,f)=>{var C=Ar(n,l);j=_(j),j=sj(j),a=J(o,a,c),K([],[r],m=>{m=m[0];var F=\`\${m.name}.\${j}\`;j.startsWith("@@")&&(j=Symbol[j.substring(2)]),u&&m.registeredClass.pureVirtualFunctions.push(j);function h(){AA(\`Cannot call \${F} due to unbound types\`,C)}var v=m.registeredClass.instancePrototype,y=v[j];return y===void 0||y.overloadTable===void 0&&y.className!==m.name&&y.argCount===n-2?(h.argCount=n-2,h.className=m.name,v[j]=h):(Aj(v,j,F),v[j].overloadTable[n-2]=h),K([],C,w=>{var L=rr(F,w,m,a,k,c);return v[j].overloadTable===void 0?(L.argCount=n-2,v[j]=L):v[j].overloadTable[n-2]=L,[]}),[]})},ij=(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\`),vA(r.$$.ptr,r.$$.ptrType.registeredClass,j.registeredClass)),he=(r,j,n,l,o,a,k,u,c,f)=>{j=_(j),o=J(l,o),K([],[r],C=>{C=C[0];var m=\`\${C.name}.\${j}\`,F={get(){AA(\`Cannot access \${m} due to unbound types\`,[n,k])},enumerable:!0,configurable:!0};return c?F.set=()=>AA(\`Cannot access \${m} due to unbound types\`,[n,k]):F.set=h=>G(m+" is a read-only property"),Object.defineProperty(C.registeredClass.instancePrototype,j,F),K([],c?[n,k]:[n],h=>{var v=h[0],y={get(){var L=ij(this,C,m+" getter");return v.fromWireType(o(a,L))},enumerable:!0};if(c){c=J(u,c);var w=h[1];y.set=function(L){var aA=ij(this,C,m+" setter"),D=[];c(f,aA,w.toWireType(D,L)),ej(D)}}return Object.defineProperty(C.registeredClass.instancePrototype,j,y),[]}),[]})},lj=[],W=[0,1,,1,null,1,!0,1,!1,1],$e=r=>{if(r>9&&--W[r+1]===0){var j=W[r];W[r]=void 0,lj.push(r)}},jr={toValue:r=>(r||G(\`Cannot use deleted val. handle = \${r}\`),W[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=lj.pop()||W.length;return W[j]=r,W[j+1]=1,j}}}},Fe={name:"emscripten::val",fromWireType:r=>{var j=jr.toValue(r);return $e(r),j},toWireType:(r,j)=>jr.toHandle(j),readValueFromPointer:IA,destructorFunction:null},ve=r=>x(r,Fe),Ie=(r,j)=>{switch(j){case 4:return function(n){return this.fromWireType(xr[n>>2])};case 8:return function(n){return this.fromWireType(mA[n>>3])};default:throw new TypeError(\`invalid float width (\${j}): \${r}\`)}},_e=(r,j,n)=>{j=_(j),x(r,{name:j,fromWireType:l=>l,toWireType:(l,o)=>o,readValueFromPointer:Ie(j,n),destructorFunction:null})},He=(r,j,n,l,o,a,k,u)=>{var c=Ar(j,n);r=_(r),r=sj(r),o=J(l,o,k),rj(r,function(){AA(\`Cannot call \${r} due to unbound types\`,c)},j-1),K([],c,f=>{var C=[f[0],null].concat(f.slice(1));return tj(r,rr(r,C,null,o,a,k),j-1),[]})},De=(r,j,n,l,o)=>{j=_(j);let a=l===0,k=c=>c;if(a){var u=32-8*n;k=c=>c<<u>>>u,o=k(o)}x(r,{name:j,fromWireType:k,toWireType:(c,f)=>f,readValueFromPointer:Wr(j,n,l!==0),destructorFunction:null})},ye=(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=_(n),x(r,{name:n,fromWireType:a,readValueFromPointer:a},{ignoreDuplicateRegistrations:!0})},Le=(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},ge=(r,j,n)=>Le(r,N,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},oj=globalThis.TextDecoder&&new TextDecoder,aj=(r,j,n,l)=>{var o=j+n;if(l)return o;for(;r[j]&&!(j>=o);)++j;return j},kj=(r,j=0,n,l)=>{var o=aj(r,j,n,l);if(o-j>16&&r.buffer&&oj)return oj.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 f=k-65536;a+=String.fromCharCode(55296|f>>10,56320|f&1023)}}return a},Be=(r,j,n)=>r?kj(N,r,j,n):"",xe=(r,j)=>{j=_(j);var n=!0;x(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(N[a+u])}return O(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=nr(4+a+1),c=u+4;if($[u>>2]=a,k)if(n)ge(o,c,a+1);else for(var f=0;f<a;++f){var C=o.charCodeAt(f);C>255&&(O(u),G("String has UTF-16 code units that do not fit in 8 bits")),N[c+f]=C}else N.set(o,c);return l!==null&&l.push(O,u),u},readValueFromPointer:IA,destructorFunction(l){O(l)}})},uj=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,be=(r,j,n)=>{var l=r>>1,o=aj(nA,l,j/2,n);if(o-l>16&&uj)return uj.decode(nA.slice(l,o));for(var a="",k=l;k<o;++k){var u=nA[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);EA[j>>1]=k,j+=2}return EA[j>>1]=0,j-l},Je=r=>r.length*2,Oe=(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},we=(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++,T[j>>2]=k,j+=4,j+4>o)break}return T[j>>2]=0,j-l},Ue=r=>{for(var j=0,n=0;n<r.length;++n){var l=r.codePointAt(n);l>65535&&n++,j+=4}return j},Te=(r,j,n)=>{n=_(n);var l,o,a;j===2?(l=be,o=Pe,a=Je):(l=Oe,o=we,a=Ue),x(r,{name:n,fromWireType:k=>{var u=$[k>>2],c=l(k+4,u*j,!0);return O(k),c},toWireType:(k,u)=>{typeof u!="string"&&G(\`Cannot pass non-string to C++ string type \${n}\`);var c=a(u),f=nr(4+c+j);return $[f>>2]=c/j,o(u,f+4,c+j),k!==null&&k.push(O,f),f},readValueFromPointer:IA,destructorFunction(k){O(k)}})},Ke=(r,j)=>{j=_(j),x(r,{isVoid:!0,name:j,fromWireType:()=>{},toWireType:(n,l)=>{}})},Me=r=>{var j=!s;try{Atomics.wait(T,0,0,0),j=!0}catch{}sr(r,!i,1,j,65536,!1),E.threadInitTLS()},cj=r=>{if(r instanceof Br||r=="unwind")return X;g(1,r)},Se=()=>{if(!WA())try{if(q){LA()&&ir(X);return}QA(X)}catch(r){cj(r)}},dj=r=>{if(!GA)try{return r()}catch(j){cj(j)}finally{Se()}},tr=r=>{if(!Mr){var j=Atomics.waitAsync(T,r>>2,r);j.value.then(yA);var n=r+112;Atomics.store(T,n>>2,1)}},yA=()=>{var r=LA();r&&dj(()=>{tr(r),vj()})},Ve=(r,j)=>{if(r==j)setTimeout(yA);else if(q)postMessage({targetThread:r,cmd:4});else{var n=E.pthreads[r];if(!n)return;n.postMessage({cmd:4})}},er=[],Re=(r,j,n,l,o,a,k)=>{er.length=0;for(var u=o>>3,c=o+l>>3;u<c;){var f;V[u++]?f=V[u++]:f=mA[u++],er.push(f)}var C=ln[r];E.currentProxiedOperationCallerThread=n;var m=C(...er);if(E.currentProxiedOperationCallerThread=0,a){m.then(F=>hj(a,k,F));return}return m},We=r=>{q?postMessage({cmd:6,thread:r}):Jr(r)},Qe=r=>{},ze=()=>performance.timeOrigin+performance.now(),Xe=9007199254740992,Ze=-9007199254740992,Ye=r=>r<Ze||r>Xe?NaN:Number(r),An=()=>{},rn=()=>{RA+=1},jn=()=>{throw rn(),"unwind"},tn=r=>{pA("OOM")},en=r=>{var j=N.length;r>>>=0,tn(r)};function qj(r){return q?sA(2,0,1,r):52}function fj(r,j,n,l){return q?sA(3,0,1,r,j,n,l):(j=Ye(j),70)}var nn=[null,[],[]],sn=(r,j)=>{var n=nn[r];j===0||j===10?((r===1?SA:P)(kj(n)),n.length=0):n.push(j)};function Cj(r,j,n,l){if(q)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++)sn(r,N[k+c]);o+=u}return $[l>>2]=o,0}E.init(),je(),qe();{gt(),t.noExitRuntime&&(zA=t.noExitRuntime),t.print&&(SA=t.print),t.printErr&&(P=t.printErr),t.arguments&&(p=t.arguments),t.thisProgram&&(I=t.thisProgram);var rA=t.preInit;if(rA)for(typeof rA=="function"&&(t.preInit=rA=[rA]);rA.length>0;)rA.shift()()}var ln=[Tr,Kr,qj,fj,Cj],Gj,pj,LA,nr,O,on,sr,Ej,mj,hj,$j,Fj,ir,vj,Ij,_j,Hj,Dj,an,yj;function kn(r){Gj=r.G,pj=r.H,LA=r.J,nr=t._malloc=r.K,O=t._free=r.L,on=r.M,sr=r.N,Ej=r.O,mj=r.P,hj=r.Q,$j=r.R,Fj=r.S,ir=r.T,vj=r.U,Ij=r.V,_j=r.W,Hj=r.X,Dj=r.Y,an=yj=r.I}var Lj;function un(){Lj={l:Wt,C:Qt,h:Xt,o:Zt,n:Ge,m:Ee,e:me,b:he,D:ve,g:_e,q:He,d:De,c:ye,E:xe,f:Te,p:Ke,z:Me,u:Ve,j:Re,s:We,y:tr,B:Qe,x:An,A:jn,k:ze,t:en,r:QA,w:qj,v:fj,i:Cj,a:iA}}async function gj(){if(q){yr();return}Nt();var r=t.setStatus;r&&(r("Running..."),await new Promise(j=>setTimeout(j,1)),setTimeout(r,1,"")),!GA&&(yr(),t.onRuntimeInitialized?.(),Bt())}var jA;return q||(jA=await Nr(),await gj()),t}})();typeof ht=="object"&&typeof KA=="object"?(KA.exports=TA,KA.exports.default=TA):typeof define=="function"&&define.amd&&define([],()=>TA);var Hs=globalThis.name=="em-pthread";Hs&&TA()});var b={};En(b,{AdditionalCaptureBlocks:()=>Fn,AdditionalPlaybackBlocks:()=>$n,ClockJumpCheckInterval:()=>Ln,ClockJumpThreshold:()=>gn,ConnectInterval:()=>Tn,ConnectTimeout:()=>On,DefaultRefreshRate:()=>In,DefaultVideoCodec:()=>Kn,HealthCheckTimeout:()=>yn,MainConnectionPingInterval:()=>Nn,MaxNumberOfDecoders:()=>Hn,MinDBFs:()=>bj,MinTokenLifetime:()=>wn,MinTokenRefreshInterval:()=>Un,PlaybackPreload:()=>vn,RenderQuantumSize:()=>Dn,VadPreload:()=>_n,WebRtcAnswerTimeout:()=>Pn,WebRtcIceTimeout:()=>xn,WebRtcMaxNegotiationAttempts:()=>Jn,WebRtcStatsSnapshotInterval:()=>Bn,WebRtcTimeout:()=>bn});var $n=3,Fn=3,vn=3,In=250,_n=3,Hn=512,Dn=128,bj=-758.596,yn=1e4,Ln=1e3,gn=1e4,Nn=3e3,Bn=1e3,xn=3e3,bn=1e4,Pn=1e4,Jn=3,On=5e3,wn=6e4,Un=5e3,Tn=[0,100,200,200,500],Kn="H264";function kA(e,A,t){return e.postMessage(A,t)}function ar(e){return e.sampleRate*.02*(e.stereo?2:1)}function kr(e,A){let t=ar(e),s=t*A,i=s+t;return e.samples.subarray(s,i)}function ur(e,A,t){e.headers[A]=t.id}function Pj(e){return[e.values[0],e.values[1]]}function Jj(e,A){e.values[0]=A[0],e.values[1]=A[1]}function Oj(e,A){return e.values[2+A*5]}function wj(e,A,t){e.values[2+A*5]=t}function Uj(e,A){let t=2+A*5+1;return[e.values[t+0],e.values[t+1]]}function Tj(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 Mj(e,A,t){e.values[2+A*5+3]=t}function Sj(e,A){return e.values[2+A*5+4]}function Vj(e,A,t){e.values[2+A*5+4]=t}function Rj(e){return e.values[0]!==0}function Wj(e){return e.values[1]}function Qj(e){return e.values[2]}function zj(e){return e.values[3]}function Xj(e,A){return e.values[3]=A}function Zj(e){return e?Array.from(e).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var Mn;(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||={})})(Mn||={});function tt(e){return{type:"Success",value:e}}function B(e){return{type:"Failure",reason:e}}var{Deno:Yj}=globalThis,Sn=typeof Yj?.noColor=="boolean"?Yj.noColor:!1,Vn=!Sn;function dr(e,A){return{open:\`\\x1B[\${e.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function qr(e,A){return Vn?\`\${A.open}\${e.replace(A.regexp,A.open)}\${A.close}\`:e}function cr(e){return qr(e,dr([0],0))}function At(e){return qr(e,dr([1],22))}function Rn(e){return qr(e,dr([2],22))}var Ks=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"),Wn=new Date,gA=(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))(gA||{}),et={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},Qn={4:Rn,3:cr,2:cr,1:At,0:At};function zn({message:e}){return String(e)}function rt(e){return JSON.stringify({timestamp:e.date.toISOString(),level:gA[e.level],message:e.message,extra:e.extra})}function jt(e){function A(q,p){return[Math.floor(q/p),q%p]}function t(){let q,p=e.date.valueOf()-Wn.valueOf();[p,q]=A(p,1e3);let[I,g]=A(p,60);return\`\${I.toString().padStart(4,"0")}:\${g.toString().padStart(2,"0")}.\${q.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=et[e.level],d=e.logger.name!==void 0?\`@\${e.logger.name}\`:"";return\`\${cr(t())}\${d} \${i} \${Qn[e.level](String(e.message))}\${s()}\`}function Xn(e){let A=\`[\${e.date.toISOString()}]\`,t=\`[\${gA[e.level]}]\`,s=e.logger.name!==void 0?\`[\${e.logger.name}] \`:"",i=et[e.level];return\`\${A} \${i} \${t.padEnd(7," ")} \${s}\${e.message}\`}function Zn(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var nt=class{static sparse=zn;static json=rt;static pretty=jt;static structured=Xn;static default=Zn()?jt:rt;constructor(){}};var Yn=class{formatter;consoleObject;filter;constructor(e=nt.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 Q=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)},uA=globalThis[Symbol.for("odin-global-logger")]??=new Q(3,void 0,[new Yn]),As=Q.prototype.log.bind(uA,1),rs=Q.prototype.log.bind(uA,2),st=Q.prototype.log.bind(uA,3),js=Q.prototype.log.bind(uA,4),Ms=Q.prototype.log.bind(uA);var it;function lt(e,...A){let t=ts(A);it?it?.info(e,t):st(e,t)}function ts(...e){if(e.length===1&&typeof e[0]=="object"&&e[0]!==null)return{...e[0]};if(e.length>0)return{args:e}}function NA(e){return e.connectionId*4294967296+e.mediaId}function ot(e){return{mediaId:e%4294967296,connectionId:Math.floor(e/4294967296)}}function M(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 fr(e,A,t,s){return{headers:M(e,"i32",t),samples:M(e,"f32",t*ar({sampleRate:A,stereo:s})),length:t,sampleRate:A,stereo:s}}function Cr(e,A){tA(e,A.headers),tA(e,A.samples)}function at(e,A){return{values:M(e,"f32",2+A*5),length:A}}function kt(e,A){tA(e,A.values)}function ut(e){return{values:M(e,"f32",4)}}function ct(e,A){tA(e,A.values)}function dt(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 es(e,A,t){let s=e.length,i=t,d=0;for(;d<s;){let q=e.charCodeAt(d++);if((q&4294967168)===0){A[i++]=q;continue}else if((q&4294965248)===0)A[i++]=q>>6&31|192;else{if(q>=55296&&q<=56319&&d<s){let p=e.charCodeAt(d);(p&64512)===56320&&(++d,q=((q&1023)<<10)+(p&1023)+65536)}(q&4294901760)===0?(A[i++]=q>>12&15|224,A[i++]=q>>6&63|128):(A[i++]=q>>18&7|240,A[i++]=q>>12&63|128,A[i++]=q>>6&63|128)}A[i++]=q&63|128}}var ns=new TextEncoder,ss=50;function is(e,A,t){ns.encodeInto(e,A.subarray(t))}function qt(e,A,t){e.length>ss?is(e,A,t):es(e,A,t)}var ls=4096;function Gr(e,A,t){let s=A,i=s+t,d=[],q="";for(;s<i;){let p=e[s++];if((p&128)===0)d.push(p);else if((p&224)===192){let I=e[s++]&63;d.push((p&31)<<6|I)}else if((p&240)===224){let I=e[s++]&63,g=e[s++]&63;d.push((p&31)<<12|I<<6|g)}else if((p&248)===240){let I=e[s++]&63,g=e[s++]&63,MA=e[s++]&63,U=(p&7)<<18|I<<12|g<<6|MA;U>65535&&(U-=65536,d.push(U>>>10&1023|55296),U=56320|U&1023),d.push(U)}else d.push(p);d.length>=ls&&(q+=String.fromCharCode(...d),d.length=0)}return d.length>0&&(q+=String.fromCharCode(...d)),q}var os=new TextDecoder,as=200;function ks(e,A,t){let s=e.subarray(A,A+t);return os.decode(s)}function ft(e,A,t){return t>as?ks(e,A,t):Gr(e,A,t)}var z=class{constructor(A,t){this.type=A,this.data=t}};var H=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 Ct(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 xA(e,A){let t=e.getInt32(A),s=e.getUint32(A+4);return t*4294967296+s}function Gt(e,A){let t=e.getUint32(A),s=e.getUint32(A+4);return t*4294967296+s}var us=-1,cs=4294967296-1,ds=17179869184-1;function qs({sec:e,nsec:A}){if(e>=0&&A>=0&&e<=ds)if(A===0&&e<=cs){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 fs(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 Cs(e){if(e instanceof Date){let A=fs(e);return qs(A)}else return null}function Gs(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=xA(A,4),s=A.getUint32(0);return{sec:t,nsec:s}}default:throw new H(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${e.length}\`)}}function ps(e){let A=Gs(e);return new Date(A.sec*1e3+A.nsec/1e6)}var pt={type:us,encode:Cs,decode:ps};var S=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(pt)}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 q=-1-s;return new z(q,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 q=s;return new z(q,d)}}}return A instanceof z?A:null}decode(A,t,s){let i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(A,t,s):new z(t,A)}};S.defaultCodec=new S;function Es(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function cA(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Es(e)?new Uint8Array(e):Uint8Array.from(e)}var ms=100,hs=2048,bA=class e{constructor(A){this.entered=!1,this.extensionCodec=A?.extensionCodec??S.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??ms,this.initialBufferSize=A?.initialBufferSize??hs,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=dt(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=cA(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 q=A[d];this.ignoreUndefined&&q===void 0||(this.encodeString(d),this.doEncode(q,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),Ct(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 pr(e,A){return new bA(A).encodeSharedRef(e)}function PA(e){return\`\${e<0?"-":""}0x\${Math.abs(e).toString(16).padStart(2,"0")}\`}var $s=16,Fs=16,JA=class{constructor(A=$s,t=Fs){this.hit=0,this.miss=0,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 q=d.bytes;for(let p=0;p<s;p++)if(q[p]!==A[t+p])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=Gr(A,t,s),q=Uint8Array.prototype.slice.call(A,t,t+s);return this.store(q,d),d}};var Er="array",fA="map_key",mt="map_value",vs=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new H("The type of key must be string or number but "+typeof e)},mr=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let t=this.getUninitializedStateFromPool();t.type=Er,t.position=0,t.size=A,t.array=new Array(A)}pushMapState(A){let t=this.getUninitializedStateFromPool();t.type=fA,t.readCount=0,t.size=A,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let A={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(A)}return this.stack[this.stackHeadPosition]}release(A){if(this.stack[this.stackHeadPosition]!==A)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(A.type===Er){let s=A;s.size=0,s.array=void 0,s.position=0,s.type=void 0}if(A.type===fA||A.type===mt){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}},qA=-1,hr=new DataView(new ArrayBuffer(0)),Is=new Uint8Array(hr.buffer);try{hr.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 Et=new RangeError("Insufficient data"),_s=new JA,OA=class e{constructor(A){this.totalPos=0,this.pos=0,this.view=hr,this.bytes=Is,this.headByte=qA,this.stack=new mr,this.entered=!1,this.extensionCodec=A?.extensionCodec??S.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.rawStrings=A?.rawStrings??!1,this.maxStrLength=A?.maxStrLength??4294967295,this.maxBinLength=A?.maxBinLength??4294967295,this.maxArrayLength=A?.maxArrayLength??4294967295,this.maxMapLength=A?.maxMapLength??4294967295,this.maxExtLength=A?.maxExtLength??4294967295,this.keyDecoder=A?.keyDecoder!==void 0?A.keyDecoder:_s,this.mapKeyConverter=A?.mapKeyConverter??vs}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=qA,this.stack.reset()}setBuffer(A){let t=cA(A);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(A){if(this.headByte===qA&&!this.hasRemaining(1))this.setBuffer(A);else{let t=this.bytes.subarray(this.pos),s=cA(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 p of A){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(p);try{s=this.doDecodeSync(),t=!0}catch(I){if(!(I instanceof RangeError))throw I}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return s}let{headByte:i,pos:d,totalPos:q}=this;throw new RangeError(\`Insufficient data in parsing \${PA(i)} at \${q} (\${d} in the current buffer)\`)}finally{this.entered=!1}}decodeArrayStream(A){return this.decodeMultiAsync(A,!0)}decodeStream(A){return this.decodeMultiAsync(A,!1)}async*decodeMultiAsync(A,t){if(this.entered){yield*this.clone().decodeMultiAsync(A,t);return}try{this.entered=!0;let 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(q){if(!(q instanceof RangeError))throw q}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){A:for(;;){let A=this.readHeadByte(),t;if(A>=224)t=A-256;else if(A<192)if(A<128)t=A;else if(A<144){let i=A-128;if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A<160){let i=A-144;if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else{let i=A-160;t=this.decodeString(i,0)}else if(A===192)t=null;else if(A===194)t=!1;else if(A===195)t=!0;else if(A===202)t=this.readF32();else if(A===203)t=this.readF64();else if(A===204)t=this.readU8();else if(A===205)t=this.readU16();else if(A===206)t=this.readU32();else if(A===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(A===208)t=this.readI8();else if(A===209)t=this.readI16();else if(A===210)t=this.readI32();else if(A===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(A===217){let i=this.lookU8();t=this.decodeString(i,1)}else if(A===218){let i=this.lookU16();t=this.decodeString(i,2)}else if(A===219){let i=this.lookU32();t=this.decodeString(i,4)}else if(A===220){let i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===221){let i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===222){let i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===223){let i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===196){let i=this.lookU8();t=this.decodeBinary(i,1)}else if(A===197){let i=this.lookU16();t=this.decodeBinary(i,2)}else if(A===198){let i=this.lookU32();t=this.decodeBinary(i,4)}else if(A===212)t=this.decodeExtension(1,0);else if(A===213)t=this.decodeExtension(2,0);else if(A===214)t=this.decodeExtension(4,0);else if(A===215)t=this.decodeExtension(8,0);else if(A===216)t=this.decodeExtension(16,0);else if(A===199){let i=this.lookU8();t=this.decodeExtension(i,1)}else if(A===200){let i=this.lookU16();t=this.decodeExtension(i,2)}else if(A===201){let i=this.lookU32();t=this.decodeExtension(i,4)}else throw new H(\`Unrecognized type byte: \${PA(A)}\`);this.complete();let s=this.stack;for(;s.length>0;){let i=s.top();if(i.type===Er)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===fA){if(t==="__proto__")throw new H("The key __proto__ is not allowed");i.key=this.mapKeyConverter(t),i.type=mt;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=fA;continue A}}return t}}readHeadByte(){return this.headByte===qA&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=qA}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 H(\`Unrecognized array type byte: \${PA(A)}\`)}}}pushMapState(A){if(A>this.maxMapLength)throw new H(\`Max length exceeded: map length (\${A}) > maxMapLengthLength (\${this.maxMapLength})\`);this.stack.pushMapState(A)}pushArrayState(A){if(A>this.maxArrayLength)throw new H(\`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 H(\`Max length exceeded: UTF-8 byte length (\${A}) > maxStrLength (\${this.maxStrLength})\`);if(this.bytes.byteLength<this.pos+t+A)throw Et;let s=this.pos+t,i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?i=this.keyDecoder.decode(this.bytes,s,A):i=ft(this.bytes,s,A),this.pos+=t+A,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===fA:!1}decodeBinary(A,t){if(A>this.maxBinLength)throw new H(\`Max length exceeded: bin length (\${A}) > maxBinLength (\${this.maxBinLength})\`);if(!this.hasRemaining(A+t))throw Et;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 H(\`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=Gt(this.view,this.pos);return this.pos+=8,A}readI64(){let A=xA(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 $r(e,A){return new OA(A).decode(e)}var CA=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=$r(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(g=>typeof g=="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,p=(t[4]&1)!==0,I=t[t.length-1];return I instanceof Uint8Array?tt(new e(s,i,d,p,I)):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(pr(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,b.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=ut(this.wasm),this.outBuffer=M(this.wasm,"u8",1270),Xj(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){lt(\`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 CA(i.mediaIds,this.sequenceNumber,this.timestamp,s,this.outBuffer.subarray(0,t));kA(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:Rj(this.information),speechProbability:Wj(this.information),rmsDBFS:Qj(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}}}},UA=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=M(this.wasm,"u32",b.MaxNumberOfDecoders),this.information=at(this.wasm,b.MaxNumberOfDecoders),Jj(this.information,[1,1])}close(){kt(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,t){this.stats.numberPackets++;let s=CA.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(NA({connectionId:A,mediaId:i}));if(d===void 0){this.stats.numberPacketsMediaNotFound++;continue}d.lastPacket=t;let q=M(this.wasm,"u8",s.value.payload.length);q.set(s.value.payload),d.decoder.push(s.value.sequenceNumber,s.value.timeStamp,s.value.isEndOfSpurt,q.byteOffset,q.length)}}insertMedia(A,t,s,i=[1,1]){let d=NA({connectionId:t,mediaId:s}),q=new this.wasm.Decoder;this.medias.set(d,{index:A,decoder:q,lastPacket:void 0}),this.decoders[A]=q.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),Tj(this.information,A,i),Vj(this.information,A,0),Mj(this.information,A,0)}removeMedia(A,t,s){let i=NA({connectionId:t,mediaId:s}),d=this.medias.get(i);if(!(d===void 0||d.index!==A)&&(this.medias.delete(i),wj(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:q}of s.removed)this.removeMedia(i,d,q);for(let{index:i,connectionId:d,mediaId:q,volume:p}of s.added)this.insertMedia(i,d,q,p);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=ot(t);A.push({index:s.index,connectionId:i.connectionId,mediaId:i.mediaId,rmsDBFS:Oj(this.information,s.index),volume:Uj(this.information,s.index),voicedBlocks:Sj(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,voiceAccelerated:s.decoder.voice_accelerated,silenceAccelerated:s.decoder.silence_accelerated,cacheLength:s.decoder.cache_length,lastPacket:Zj(s.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:Pj(this.information),decoders:A}}};var _t=hn($t()),Ft=(0,_t.default)(),vt,It;globalThis.addEventListener("message",Fr);async function Fr(e){let A=e.data,[t,s]=A;switch(t){case"captureInit":s.workletPort.onmessage=Fr,vt=new vr(s.sampleRate,await Ft);break;case"playbackInit":s.workletPort.onmessage=Fr,It=new Ir(await Ft);break;case"close":globalThis.close();break}vt?.onMessage(A),It?.onMessage(A)}var vr=class extends wA{constructor(t,s){super(t,s);this.id=-1;this.samples=fr(this.wasm,t,2+b.VadPreload+b.AdditionalCaptureBlocks,!1),kA(globalThis,["captureReady",{sampleBuffer:this.samples,informationBuffer:this.information}])}close(){super.close(),Cr(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(kr(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()}}},Ir=class extends UA{constructor(A){super(A);let t=2+b.AdditionalPlaybackBlocks;this.sampleBuffer=fr(A,48e3,t,!0),this.sampleBuffer.samples.fill(0),this.prefill=t-2;for(let s=0;s<this.prefill;s++)ur(this.sampleBuffer,s,{id:s});this.id=this.prefill,kA(globalThis,["playbackReady",{sampleBuffer:this.sampleBuffer,informationBuffer:this.information}])}close(){super.close(),Cr(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(kr(this.sampleBuffer,t));s&&(this.stats.numberTicksWithAudio++,ur(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()}}};})();
3245
- `});var Qx,$0=m(()=>{Qx='"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:()=>D,AdditionalPlaybackBlocks:()=>C,ClockJumpCheckInterval:()=>j,ClockJumpThreshold:()=>$,ConnectInterval:()=>X,ConnectTimeout:()=>Q,DefaultRefreshRate:()=>V,DefaultVideoCodec:()=>ee,HealthCheckTimeout:()=>W,MainConnectionPingInterval:()=>H,MaxNumberOfDecoders:()=>_,MinDBFs:()=>k,MinTokenLifetime:()=>Y,MinTokenRefreshInterval:()=>K,PlaybackPreload:()=>L,RenderQuantumSize:()=>N,VadPreload:()=>O,WebRtcAnswerTimeout:()=>Z,WebRtcIceTimeout:()=>z,WebRtcMaxNegotiationAttempts:()=>q,WebRtcStatsSnapshotInterval:()=>J,WebRtcTimeout:()=>G});var C=3,D=3,L=3,V=250,O=3,_=512,N=128,k=-758.596,W=1e4,j=1e3,$=1e4,H=3e3,J=1e3,z=3e3,G=1e4,Z=1e4,q=3,Q=5e3,Y=6e4,K=5e3,X=[0,100,200,200,500],ee="H264";function p(e,t,r){return e.postMessage(t,r)}function te(e){return e.sampleRate*.02*(e.stereo?2:1)}function f(e,t){let r=te(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 re;(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||={})})(re||={});var{Deno:U}=globalThis,ne=typeof U?.noColor=="boolean"?U.noColor:!1,se=!ne;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 se?`${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 oe(e){return b(e,h([2],22))}var we=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"),ae=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}"},ie={4:oe,3:m,2:m,1:T,0:T};function ce({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()-ae.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} ${ie[e.level](String(e.message))}${n()}`}function le(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 ue(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var A=class{static sparse=ce;static json=B;static pretty=w;static structured=le;static default=ue()?w:B;constructor(){}};var fe=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 fe]),de=o.prototype.log.bind(u,1),pe=o.prototype.log.bind(u,2),me=o.prototype.log.bind(u,3),he=o.prototype.log.bind(u,4),Pe=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 y0={};Tx(y0,{createCaptureWorker:()=>rF,createPlaybackWorker:()=>DF});import{Strand as AF}from"@4players/odin-common";function rF(v,t,e,j,B=i.DefaultRefreshRate){return FF.enqueue(async()=>{let[C,E]=await Y(Wx,Qx,v,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return Xx.create(v,t,e,C,E,j)})}async function DF(v,t=i.DefaultRefreshRate){if(v.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[e,j]=await Y(Wx,Qx,v,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return zx.create(v,e,j)}var FF,zx,Xx,I0=m(()=>{"use strict";u();nx();G0();$0();FF=new AF;zx=class v extends z{constructor(e,j,B,C){super(e,j,B);this.information=C}static async create(e,j,B){let{port1:C,port2:E}=new MessageChannel;c(j,["playbackInit",{workletPort:C}],[C]);let{informationBuffer:f,sampleBuffer:s}=await V(j,"playbackReady");return Kx(f,[1,1]),c(B.port,["init",{sampleBuffer:s,workerPort:E}],[E]),new v(e,B,j,f)}getActivity(e){let j=this.medias.get(q(e));if(j===void 0)return;let B=E0(this.information,j.index);return B===0?_:{isSilent:!1,rmsDBFS:B}}getJitterStats(e){}setGlobalVolume(e){Kx(this.information,e)}setVolume(e,j){let B=this.medias.get(q(e));B!==void 0&&f0(this.information,B.index,j)}_GetFreeIndex(){let e=super._GetFreeIndex();if(e!==void 0)return e;if(this.information.length>this.medias.size)return this.medias.size}},Xx=class v extends X{constructor(e,j,B,C,E,f){super(e,j,B,C,f);this.information=E}static async create(e,j,B,C,E,f){let{port1:s,port2:b}=new MessageChannel;c(C,["captureInit",{sampleRate:e.sampleRate,workletPort:s}],[s]);let{sampleBuffer:d,informationBuffer:h}=await V(C,"captureReady");return c(E.port,["init",{workerPort:b,sampleBuffer:d}],[b]),new v(E,C,j,B,h,f)}get activity(){return{isSilent:!n0(this.information),rmsDBFS:i0(this.information)}}get speechProbability(){return s0(this.information)}setVolume(e){b0(this.information,e)}}});var Zx,g0=m(()=>{Zx=`"use strict";(()=>{var ne=Object.create;var QA=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var ie=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty;var ae=(e,A)=>()=>{try{return A||e((A={exports:{}}).exports,A),A.exports}catch(r){throw A=0,r}},ke=(e,A)=>{for(var r in A)QA(e,r,{get:A[r],enumerable:!0})},ue=(e,A,r,n)=>{if(A&&typeof A=="object"||typeof A=="function")for(let l of le(A))!oe.call(e,l)&&l!==r&&QA(e,l,{get:()=>A[l],enumerable:!(n=se(A,l))||n.enumerable});return e};var ce=(e,A,r)=>(r=e!=null?ne(ie(e)):{},ue(A||!e||!e.__esModule?QA(r,"default",{value:e,enumerable:!0}):r,e));var Fj=ae(($j,OA)=>{"use strict";var nr=(()=>{var e=globalThis.document?.currentScript?.src;return async function(A={}){var r=A,n=!!globalThis.window,l=!!globalThis.WorkerGlobalScope,d=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",q=[],p="./this.program";l&&(e=self.location.href);var I="",N,UA;if(n||l){try{I=new URL(".",e).href}catch{}l&&(UA=t=>{var j=new XMLHttpRequest;return j.open("GET",t,!1),j.responseType="arraybuffer",j.send(null),new Uint8Array(j.response)}),N=async t=>{var j=await fetch(t,{credentials:"same-origin"});if(j.ok)return j.arrayBuffer();throw new Error(j.status+" : "+j.url)}}var x=console.log.bind(console),aA=console.error.bind(console),yj,or=!1;class Hj{}class En extends Hj{}function Lj(t){for(var j=0,s=t.length,i=new Uint8Array(s),o;j<s;++j)o=t.charCodeAt(j),i[j]=~o>>8&o;return i}var gj=!1;function Nj(){var t=Or.buffer;S=new Int8Array(t),uA=new Int16Array(t),r.HEAPU8=L=new Uint8Array(t),Y=new Uint16Array(t),r.HEAP32=cA=new Int32Array(t),r.HEAPU32=h=new Uint32Array(t),r.HEAPF32=ur=new Float32Array(t),cr=new Float64Array(t),kr=new BigInt64Array(t),dr=new BigUint64Array(t)}function Bj(){var t=r.preRun;t&&(typeof t=="function"&&(t=[t]),fr.push(...t)),qr(fr)}function xj(){gj=!0,jA.v()}function bj(){var t=r.postRun;t&&(typeof t=="function"&&(t=[t]),Cr.push(...t)),qr(Cr)}function kA(t){r.onAbort?.(t),t=\`Aborted(\${t})\`,aA(t),or=!0,t+=". Build with -sASSERTIONS for more info.";var j=new WebAssembly.RuntimeError(t);throw j}var ar;function Jj(){return Lj(\`\\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}}\\\`\\x7F\\x7F}}\\0\\\`
3244
+ \`,new Function(m,f)}function rr(r,j,n,l,o,a){var k=j.length;k<2&&G("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var u=j[1]!==null&&n!==null,c=nj(j),f=!j[0].isVoid,C=j[0],m=j[1],F=[r,G,l,o,ej,C.fromWireType.bind(C),m?.toWireType.bind(m)],h=2;h<k;++h){var v=j[h];F.push(v.toWireType.bind(v))}if(!c)for(var h=u?1:2;h<j.length;++h)j[h].destructorFunction!==null&&F.push(j[h].destructorFunction);var w=pe(j,u,f,a)(...F);return Zr(r,w)}var Ee=(r,j,n,l,o,a)=>{var k=Ar(j,n);o=J(l,o),K([],[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)},K([],k,f=>(f.splice(1,0,null),u.registeredClass.constructor_body[j-1]=rr(c,f,null,o,a),[])),[]})},sj=r=>{r=r.trim();let j=r.indexOf("(");return j===-1?r:r.slice(0,j)},me=(r,j,n,l,o,a,k,u,c,f)=>{var C=Ar(n,l);j=_(j),j=sj(j),a=J(o,a,c),K([],[r],m=>{m=m[0];var F=\`\${m.name}.\${j}\`;j.startsWith("@@")&&(j=Symbol[j.substring(2)]),u&&m.registeredClass.pureVirtualFunctions.push(j);function h(){AA(\`Cannot call \${F} due to unbound types\`,C)}var v=m.registeredClass.instancePrototype,y=v[j];return y===void 0||y.overloadTable===void 0&&y.className!==m.name&&y.argCount===n-2?(h.argCount=n-2,h.className=m.name,v[j]=h):(Aj(v,j,F),v[j].overloadTable[n-2]=h),K([],C,w=>{var L=rr(F,w,m,a,k,c);return v[j].overloadTable===void 0?(L.argCount=n-2,v[j]=L):v[j].overloadTable[n-2]=L,[]}),[]})},ij=(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\`),vA(r.$$.ptr,r.$$.ptrType.registeredClass,j.registeredClass)),he=(r,j,n,l,o,a,k,u,c,f)=>{j=_(j),o=J(l,o),K([],[r],C=>{C=C[0];var m=\`\${C.name}.\${j}\`,F={get(){AA(\`Cannot access \${m} due to unbound types\`,[n,k])},enumerable:!0,configurable:!0};return c?F.set=()=>AA(\`Cannot access \${m} due to unbound types\`,[n,k]):F.set=h=>G(m+" is a read-only property"),Object.defineProperty(C.registeredClass.instancePrototype,j,F),K([],c?[n,k]:[n],h=>{var v=h[0],y={get(){var L=ij(this,C,m+" getter");return v.fromWireType(o(a,L))},enumerable:!0};if(c){c=J(u,c);var w=h[1];y.set=function(L){var aA=ij(this,C,m+" setter"),D=[];c(f,aA,w.toWireType(D,L)),ej(D)}}return Object.defineProperty(C.registeredClass.instancePrototype,j,y),[]}),[]})},lj=[],W=[0,1,,1,null,1,!0,1,!1,1],$e=r=>{if(r>9&&--W[r+1]===0){var j=W[r];W[r]=void 0,lj.push(r)}},jr={toValue:r=>(r||G(\`Cannot use deleted val. handle = \${r}\`),W[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=lj.pop()||W.length;return W[j]=r,W[j+1]=1,j}}}},Fe={name:"emscripten::val",fromWireType:r=>{var j=jr.toValue(r);return $e(r),j},toWireType:(r,j)=>jr.toHandle(j),readValueFromPointer:IA,destructorFunction:null},ve=r=>x(r,Fe),Ie=(r,j)=>{switch(j){case 4:return function(n){return this.fromWireType(xr[n>>2])};case 8:return function(n){return this.fromWireType(mA[n>>3])};default:throw new TypeError(\`invalid float width (\${j}): \${r}\`)}},_e=(r,j,n)=>{j=_(j),x(r,{name:j,fromWireType:l=>l,toWireType:(l,o)=>o,readValueFromPointer:Ie(j,n),destructorFunction:null})},He=(r,j,n,l,o,a,k,u)=>{var c=Ar(j,n);r=_(r),r=sj(r),o=J(l,o,k),rj(r,function(){AA(\`Cannot call \${r} due to unbound types\`,c)},j-1),K([],c,f=>{var C=[f[0],null].concat(f.slice(1));return tj(r,rr(r,C,null,o,a,k),j-1),[]})},De=(r,j,n,l,o)=>{j=_(j);let a=l===0,k=c=>c;if(a){var u=32-8*n;k=c=>c<<u>>>u,o=k(o)}x(r,{name:j,fromWireType:k,toWireType:(c,f)=>f,readValueFromPointer:Wr(j,n,l!==0),destructorFunction:null})},ye=(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=_(n),x(r,{name:n,fromWireType:a,readValueFromPointer:a},{ignoreDuplicateRegistrations:!0})},Le=(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},ge=(r,j,n)=>Le(r,N,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},oj=globalThis.TextDecoder&&new TextDecoder,aj=(r,j,n,l)=>{var o=j+n;if(l)return o;for(;r[j]&&!(j>=o);)++j;return j},kj=(r,j=0,n,l)=>{var o=aj(r,j,n,l);if(o-j>16&&r.buffer&&oj)return oj.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 f=k-65536;a+=String.fromCharCode(55296|f>>10,56320|f&1023)}}return a},Be=(r,j,n)=>r?kj(N,r,j,n):"",xe=(r,j)=>{j=_(j);var n=!0;x(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(N[a+u])}return O(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=nr(4+a+1),c=u+4;if($[u>>2]=a,k)if(n)ge(o,c,a+1);else for(var f=0;f<a;++f){var C=o.charCodeAt(f);C>255&&(O(u),G("String has UTF-16 code units that do not fit in 8 bits")),N[c+f]=C}else N.set(o,c);return l!==null&&l.push(O,u),u},readValueFromPointer:IA,destructorFunction(l){O(l)}})},uj=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,be=(r,j,n)=>{var l=r>>1,o=aj(nA,l,j/2,n);if(o-l>16&&uj)return uj.decode(nA.slice(l,o));for(var a="",k=l;k<o;++k){var u=nA[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);EA[j>>1]=k,j+=2}return EA[j>>1]=0,j-l},Je=r=>r.length*2,Oe=(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},we=(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++,T[j>>2]=k,j+=4,j+4>o)break}return T[j>>2]=0,j-l},Ue=r=>{for(var j=0,n=0;n<r.length;++n){var l=r.codePointAt(n);l>65535&&n++,j+=4}return j},Te=(r,j,n)=>{n=_(n);var l,o,a;j===2?(l=be,o=Pe,a=Je):(l=Oe,o=we,a=Ue),x(r,{name:n,fromWireType:k=>{var u=$[k>>2],c=l(k+4,u*j,!0);return O(k),c},toWireType:(k,u)=>{typeof u!="string"&&G(\`Cannot pass non-string to C++ string type \${n}\`);var c=a(u),f=nr(4+c+j);return $[f>>2]=c/j,o(u,f+4,c+j),k!==null&&k.push(O,f),f},readValueFromPointer:IA,destructorFunction(k){O(k)}})},Ke=(r,j)=>{j=_(j),x(r,{isVoid:!0,name:j,fromWireType:()=>{},toWireType:(n,l)=>{}})},Me=r=>{var j=!s;try{Atomics.wait(T,0,0,0),j=!0}catch{}sr(r,!i,1,j,65536,!1),E.threadInitTLS()},cj=r=>{if(r instanceof Br||r=="unwind")return X;g(1,r)},Se=()=>{if(!WA())try{if(q){LA()&&ir(X);return}QA(X)}catch(r){cj(r)}},dj=r=>{if(!GA)try{return r()}catch(j){cj(j)}finally{Se()}},tr=r=>{if(!Mr){var j=Atomics.waitAsync(T,r>>2,r);j.value.then(yA);var n=r+112;Atomics.store(T,n>>2,1)}},yA=()=>{var r=LA();r&&dj(()=>{tr(r),vj()})},Ve=(r,j)=>{if(r==j)setTimeout(yA);else if(q)postMessage({targetThread:r,cmd:4});else{var n=E.pthreads[r];if(!n)return;n.postMessage({cmd:4})}},er=[],Re=(r,j,n,l,o,a,k)=>{er.length=0;for(var u=o>>3,c=o+l>>3;u<c;){var f;V[u++]?f=V[u++]:f=mA[u++],er.push(f)}var C=ln[r];E.currentProxiedOperationCallerThread=n;var m=C(...er);if(E.currentProxiedOperationCallerThread=0,a){m.then(F=>hj(a,k,F));return}return m},We=r=>{q?postMessage({cmd:6,thread:r}):Jr(r)},Qe=r=>{},ze=()=>performance.timeOrigin+performance.now(),Xe=9007199254740992,Ze=-9007199254740992,Ye=r=>r<Ze||r>Xe?NaN:Number(r),An=()=>{},rn=()=>{RA+=1},jn=()=>{throw rn(),"unwind"},tn=r=>{pA("OOM")},en=r=>{var j=N.length;r>>>=0,tn(r)};function qj(r){return q?sA(2,0,1,r):52}function fj(r,j,n,l){return q?sA(3,0,1,r,j,n,l):(j=Ye(j),70)}var nn=[null,[],[]],sn=(r,j)=>{var n=nn[r];j===0||j===10?((r===1?SA:P)(kj(n)),n.length=0):n.push(j)};function Cj(r,j,n,l){if(q)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++)sn(r,N[k+c]);o+=u}return $[l>>2]=o,0}E.init(),je(),qe();{gt(),t.noExitRuntime&&(zA=t.noExitRuntime),t.print&&(SA=t.print),t.printErr&&(P=t.printErr),t.arguments&&(p=t.arguments),t.thisProgram&&(I=t.thisProgram);var rA=t.preInit;if(rA)for(typeof rA=="function"&&(t.preInit=rA=[rA]);rA.length>0;)rA.shift()()}var ln=[Tr,Kr,qj,fj,Cj],Gj,pj,LA,nr,O,on,sr,Ej,mj,hj,$j,Fj,ir,vj,Ij,_j,Hj,Dj,an,yj;function kn(r){Gj=r.G,pj=r.H,LA=r.J,nr=t._malloc=r.K,O=t._free=r.L,on=r.M,sr=r.N,Ej=r.O,mj=r.P,hj=r.Q,$j=r.R,Fj=r.S,ir=r.T,vj=r.U,Ij=r.V,_j=r.W,Hj=r.X,Dj=r.Y,an=yj=r.I}var Lj;function un(){Lj={l:Wt,C:Qt,h:Xt,o:Zt,n:Ge,m:Ee,e:me,b:he,D:ve,g:_e,q:He,d:De,c:ye,E:xe,f:Te,p:Ke,z:Me,u:Ve,j:Re,s:We,y:tr,B:Qe,x:An,A:jn,k:ze,t:en,r:QA,w:qj,v:fj,i:Cj,a:iA}}async function gj(){if(q){yr();return}Nt();var r=t.setStatus;r&&(r("Running..."),await new Promise(j=>setTimeout(j,1)),setTimeout(r,1,"")),!GA&&(yr(),t.onRuntimeInitialized?.(),Bt())}var jA;return q||(jA=await Nr(),await gj()),t}})();typeof ht=="object"&&typeof KA=="object"?(KA.exports=TA,KA.exports.default=TA):typeof define=="function"&&define.amd&&define([],()=>TA);var Ds=globalThis.name=="em-pthread";Ds&&TA()});var b={};En(b,{AdditionalCaptureBlocks:()=>Fn,AdditionalPlaybackBlocks:()=>$n,ClockJumpCheckInterval:()=>Ln,ClockJumpThreshold:()=>gn,ConnectInterval:()=>Tn,ConnectTimeout:()=>On,DefaultRefreshRate:()=>In,DefaultVideoCodec:()=>Mn,HealthCheckTimeout:()=>yn,MainConnectionPingInterval:()=>Nn,MaxNumberOfDecoders:()=>Hn,MaxReconnectDuration:()=>Kn,MinDBFs:()=>bj,MinTokenLifetime:()=>wn,MinTokenRefreshInterval:()=>Un,PlaybackPreload:()=>vn,RenderQuantumSize:()=>Dn,VadPreload:()=>_n,WebRtcAnswerTimeout:()=>Pn,WebRtcIceTimeout:()=>xn,WebRtcMaxNegotiationAttempts:()=>Jn,WebRtcStatsSnapshotInterval:()=>Bn,WebRtcTimeout:()=>bn});var $n=3,Fn=3,vn=3,In=250,_n=3,Hn=512,Dn=128,bj=-758.596,yn=1e4,Ln=1e3,gn=1e4,Nn=3e3,Bn=1e3,xn=3e3,bn=1e4,Pn=1e4,Jn=3,On=5e3,wn=6e4,Un=5e3,Tn=[0,100,200,200,500],Kn=12e4,Mn="H264";function kA(e,A,t){return e.postMessage(A,t)}function ar(e){return e.sampleRate*.02*(e.stereo?2:1)}function kr(e,A){let t=ar(e),s=t*A,i=s+t;return e.samples.subarray(s,i)}function ur(e,A,t){e.headers[A]=t.id}function Pj(e){return[e.values[0],e.values[1]]}function Jj(e,A){e.values[0]=A[0],e.values[1]=A[1]}function Oj(e,A){return e.values[2+A*5]}function wj(e,A,t){e.values[2+A*5]=t}function Uj(e,A){let t=2+A*5+1;return[e.values[t+0],e.values[t+1]]}function Tj(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 Mj(e,A,t){e.values[2+A*5+3]=t}function Sj(e,A){return e.values[2+A*5+4]}function Vj(e,A,t){e.values[2+A*5+4]=t}function Rj(e){return e.values[0]!==0}function Wj(e){return e.values[1]}function Qj(e){return e.values[2]}function zj(e){return e.values[3]}function Xj(e,A){return e.values[3]=A}function Zj(e){return e?Array.from(e).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var Sn;(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||={})})(Sn||={});function tt(e){return{type:"Success",value:e}}function B(e){return{type:"Failure",reason:e}}var{Deno:Yj}=globalThis,Vn=typeof Yj?.noColor=="boolean"?Yj.noColor:!1,Rn=!Vn;function dr(e,A){return{open:\`\\x1B[\${e.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function qr(e,A){return Rn?\`\${A.open}\${e.replace(A.regexp,A.open)}\${A.close}\`:e}function cr(e){return qr(e,dr([0],0))}function At(e){return qr(e,dr([1],22))}function Wn(e){return qr(e,dr([2],22))}var Ms=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,gA=(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))(gA||{}),et={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},zn={4:Wn,3:cr,2:cr,1:At,0:At};function Xn({message:e}){return String(e)}function rt(e){return JSON.stringify({timestamp:e.date.toISOString(),level:gA[e.level],message:e.message,extra:e.extra})}function jt(e){function A(q,p){return[Math.floor(q/p),q%p]}function t(){let q,p=e.date.valueOf()-Qn.valueOf();[p,q]=A(p,1e3);let[I,g]=A(p,60);return\`\${I.toString().padStart(4,"0")}:\${g.toString().padStart(2,"0")}.\${q.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=et[e.level],d=e.logger.name!==void 0?\`@\${e.logger.name}\`:"";return\`\${cr(t())}\${d} \${i} \${zn[e.level](String(e.message))}\${s()}\`}function Zn(e){let A=\`[\${e.date.toISOString()}]\`,t=\`[\${gA[e.level]}]\`,s=e.logger.name!==void 0?\`[\${e.logger.name}] \`:"",i=et[e.level];return\`\${A} \${i} \${t.padEnd(7," ")} \${s}\${e.message}\`}function Yn(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var nt=class{static sparse=Xn;static json=rt;static pretty=jt;static structured=Zn;static default=Yn()?jt:rt;constructor(){}};var As=class{formatter;consoleObject;filter;constructor(e=nt.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 Q=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)},uA=globalThis[Symbol.for("odin-global-logger")]??=new Q(3,void 0,[new As]),rs=Q.prototype.log.bind(uA,1),js=Q.prototype.log.bind(uA,2),st=Q.prototype.log.bind(uA,3),ts=Q.prototype.log.bind(uA,4),Ss=Q.prototype.log.bind(uA);var it;function lt(e,...A){let t=es(A);it?it?.info(e,t):st(e,t)}function es(...e){if(e.length===1&&typeof e[0]=="object"&&e[0]!==null)return{...e[0]};if(e.length>0)return{args:e}}function NA(e){return e.connectionId*4294967296+e.mediaId}function ot(e){return{mediaId:e%4294967296,connectionId:Math.floor(e/4294967296)}}function M(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 fr(e,A,t,s){return{headers:M(e,"i32",t),samples:M(e,"f32",t*ar({sampleRate:A,stereo:s})),length:t,sampleRate:A,stereo:s}}function Cr(e,A){tA(e,A.headers),tA(e,A.samples)}function at(e,A){return{values:M(e,"f32",2+A*5),length:A}}function kt(e,A){tA(e,A.values)}function ut(e){return{values:M(e,"f32",4)}}function ct(e,A){tA(e,A.values)}function dt(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 ns(e,A,t){let s=e.length,i=t,d=0;for(;d<s;){let q=e.charCodeAt(d++);if((q&4294967168)===0){A[i++]=q;continue}else if((q&4294965248)===0)A[i++]=q>>6&31|192;else{if(q>=55296&&q<=56319&&d<s){let p=e.charCodeAt(d);(p&64512)===56320&&(++d,q=((q&1023)<<10)+(p&1023)+65536)}(q&4294901760)===0?(A[i++]=q>>12&15|224,A[i++]=q>>6&63|128):(A[i++]=q>>18&7|240,A[i++]=q>>12&63|128,A[i++]=q>>6&63|128)}A[i++]=q&63|128}}var ss=new TextEncoder,is=50;function ls(e,A,t){ss.encodeInto(e,A.subarray(t))}function qt(e,A,t){e.length>is?ls(e,A,t):ns(e,A,t)}var os=4096;function Gr(e,A,t){let s=A,i=s+t,d=[],q="";for(;s<i;){let p=e[s++];if((p&128)===0)d.push(p);else if((p&224)===192){let I=e[s++]&63;d.push((p&31)<<6|I)}else if((p&240)===224){let I=e[s++]&63,g=e[s++]&63;d.push((p&31)<<12|I<<6|g)}else if((p&248)===240){let I=e[s++]&63,g=e[s++]&63,MA=e[s++]&63,U=(p&7)<<18|I<<12|g<<6|MA;U>65535&&(U-=65536,d.push(U>>>10&1023|55296),U=56320|U&1023),d.push(U)}else d.push(p);d.length>=os&&(q+=String.fromCharCode(...d),d.length=0)}return d.length>0&&(q+=String.fromCharCode(...d)),q}var as=new TextDecoder,ks=200;function us(e,A,t){let s=e.subarray(A,A+t);return as.decode(s)}function ft(e,A,t){return t>ks?us(e,A,t):Gr(e,A,t)}var z=class{constructor(A,t){this.type=A,this.data=t}};var H=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 Ct(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 xA(e,A){let t=e.getInt32(A),s=e.getUint32(A+4);return t*4294967296+s}function Gt(e,A){let t=e.getUint32(A),s=e.getUint32(A+4);return t*4294967296+s}var cs=-1,ds=4294967296-1,qs=17179869184-1;function fs({sec:e,nsec:A}){if(e>=0&&A>=0&&e<=qs)if(A===0&&e<=ds){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 Cs(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 Gs(e){if(e instanceof Date){let A=Cs(e);return fs(A)}else return null}function ps(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=xA(A,4),s=A.getUint32(0);return{sec:t,nsec:s}}default:throw new H(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${e.length}\`)}}function Es(e){let A=ps(e);return new Date(A.sec*1e3+A.nsec/1e6)}var pt={type:cs,encode:Gs,decode:Es};var S=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(pt)}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 q=-1-s;return new z(q,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 q=s;return new z(q,d)}}}return A instanceof z?A:null}decode(A,t,s){let i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(A,t,s):new z(t,A)}};S.defaultCodec=new S;function ms(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function cA(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):ms(e)?new Uint8Array(e):Uint8Array.from(e)}var hs=100,$s=2048,bA=class e{constructor(A){this.entered=!1,this.extensionCodec=A?.extensionCodec??S.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??hs,this.initialBufferSize=A?.initialBufferSize??$s,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=dt(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=cA(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 q=A[d];this.ignoreUndefined&&q===void 0||(this.encodeString(d),this.doEncode(q,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),Ct(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 pr(e,A){return new bA(A).encodeSharedRef(e)}function PA(e){return\`\${e<0?"-":""}0x\${Math.abs(e).toString(16).padStart(2,"0")}\`}var Fs=16,vs=16,JA=class{constructor(A=Fs,t=vs){this.hit=0,this.miss=0,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 q=d.bytes;for(let p=0;p<s;p++)if(q[p]!==A[t+p])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=Gr(A,t,s),q=Uint8Array.prototype.slice.call(A,t,t+s);return this.store(q,d),d}};var Er="array",fA="map_key",mt="map_value",Is=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new H("The type of key must be string or number but "+typeof e)},mr=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let t=this.getUninitializedStateFromPool();t.type=Er,t.position=0,t.size=A,t.array=new Array(A)}pushMapState(A){let t=this.getUninitializedStateFromPool();t.type=fA,t.readCount=0,t.size=A,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let A={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(A)}return this.stack[this.stackHeadPosition]}release(A){if(this.stack[this.stackHeadPosition]!==A)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(A.type===Er){let s=A;s.size=0,s.array=void 0,s.position=0,s.type=void 0}if(A.type===fA||A.type===mt){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}},qA=-1,hr=new DataView(new ArrayBuffer(0)),_s=new Uint8Array(hr.buffer);try{hr.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 Et=new RangeError("Insufficient data"),Hs=new JA,OA=class e{constructor(A){this.totalPos=0,this.pos=0,this.view=hr,this.bytes=_s,this.headByte=qA,this.stack=new mr,this.entered=!1,this.extensionCodec=A?.extensionCodec??S.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.rawStrings=A?.rawStrings??!1,this.maxStrLength=A?.maxStrLength??4294967295,this.maxBinLength=A?.maxBinLength??4294967295,this.maxArrayLength=A?.maxArrayLength??4294967295,this.maxMapLength=A?.maxMapLength??4294967295,this.maxExtLength=A?.maxExtLength??4294967295,this.keyDecoder=A?.keyDecoder!==void 0?A.keyDecoder:Hs,this.mapKeyConverter=A?.mapKeyConverter??Is}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=qA,this.stack.reset()}setBuffer(A){let t=cA(A);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(A){if(this.headByte===qA&&!this.hasRemaining(1))this.setBuffer(A);else{let t=this.bytes.subarray(this.pos),s=cA(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 p of A){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(p);try{s=this.doDecodeSync(),t=!0}catch(I){if(!(I instanceof RangeError))throw I}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return s}let{headByte:i,pos:d,totalPos:q}=this;throw new RangeError(\`Insufficient data in parsing \${PA(i)} at \${q} (\${d} in the current buffer)\`)}finally{this.entered=!1}}decodeArrayStream(A){return this.decodeMultiAsync(A,!0)}decodeStream(A){return this.decodeMultiAsync(A,!1)}async*decodeMultiAsync(A,t){if(this.entered){yield*this.clone().decodeMultiAsync(A,t);return}try{this.entered=!0;let 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(q){if(!(q instanceof RangeError))throw q}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){A:for(;;){let A=this.readHeadByte(),t;if(A>=224)t=A-256;else if(A<192)if(A<128)t=A;else if(A<144){let i=A-128;if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A<160){let i=A-144;if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else{let i=A-160;t=this.decodeString(i,0)}else if(A===192)t=null;else if(A===194)t=!1;else if(A===195)t=!0;else if(A===202)t=this.readF32();else if(A===203)t=this.readF64();else if(A===204)t=this.readU8();else if(A===205)t=this.readU16();else if(A===206)t=this.readU32();else if(A===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(A===208)t=this.readI8();else if(A===209)t=this.readI16();else if(A===210)t=this.readI32();else if(A===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(A===217){let i=this.lookU8();t=this.decodeString(i,1)}else if(A===218){let i=this.lookU16();t=this.decodeString(i,2)}else if(A===219){let i=this.lookU32();t=this.decodeString(i,4)}else if(A===220){let i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===221){let i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===222){let i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===223){let i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===196){let i=this.lookU8();t=this.decodeBinary(i,1)}else if(A===197){let i=this.lookU16();t=this.decodeBinary(i,2)}else if(A===198){let i=this.lookU32();t=this.decodeBinary(i,4)}else if(A===212)t=this.decodeExtension(1,0);else if(A===213)t=this.decodeExtension(2,0);else if(A===214)t=this.decodeExtension(4,0);else if(A===215)t=this.decodeExtension(8,0);else if(A===216)t=this.decodeExtension(16,0);else if(A===199){let i=this.lookU8();t=this.decodeExtension(i,1)}else if(A===200){let i=this.lookU16();t=this.decodeExtension(i,2)}else if(A===201){let i=this.lookU32();t=this.decodeExtension(i,4)}else throw new H(\`Unrecognized type byte: \${PA(A)}\`);this.complete();let s=this.stack;for(;s.length>0;){let i=s.top();if(i.type===Er)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===fA){if(t==="__proto__")throw new H("The key __proto__ is not allowed");i.key=this.mapKeyConverter(t),i.type=mt;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=fA;continue A}}return t}}readHeadByte(){return this.headByte===qA&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=qA}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 H(\`Unrecognized array type byte: \${PA(A)}\`)}}}pushMapState(A){if(A>this.maxMapLength)throw new H(\`Max length exceeded: map length (\${A}) > maxMapLengthLength (\${this.maxMapLength})\`);this.stack.pushMapState(A)}pushArrayState(A){if(A>this.maxArrayLength)throw new H(\`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 H(\`Max length exceeded: UTF-8 byte length (\${A}) > maxStrLength (\${this.maxStrLength})\`);if(this.bytes.byteLength<this.pos+t+A)throw Et;let s=this.pos+t,i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?i=this.keyDecoder.decode(this.bytes,s,A):i=ft(this.bytes,s,A),this.pos+=t+A,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===fA:!1}decodeBinary(A,t){if(A>this.maxBinLength)throw new H(\`Max length exceeded: bin length (\${A}) > maxBinLength (\${this.maxBinLength})\`);if(!this.hasRemaining(A+t))throw Et;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 H(\`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=Gt(this.view,this.pos);return this.pos+=8,A}readI64(){let A=xA(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 $r(e,A){return new OA(A).decode(e)}var CA=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=$r(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(g=>typeof g=="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,p=(t[4]&1)!==0,I=t[t.length-1];return I instanceof Uint8Array?tt(new e(s,i,d,p,I)):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(pr(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,b.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=ut(this.wasm),this.outBuffer=M(this.wasm,"u8",1270),Xj(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){lt(\`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 CA(i.mediaIds,this.sequenceNumber,this.timestamp,s,this.outBuffer.subarray(0,t));kA(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:Rj(this.information),speechProbability:Wj(this.information),rmsDBFS:Qj(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}}}},UA=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=M(this.wasm,"u32",b.MaxNumberOfDecoders),this.information=at(this.wasm,b.MaxNumberOfDecoders),Jj(this.information,[1,1])}close(){kt(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,t){this.stats.numberPackets++;let s=CA.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(NA({connectionId:A,mediaId:i}));if(d===void 0){this.stats.numberPacketsMediaNotFound++;continue}d.lastPacket=t;let q=M(this.wasm,"u8",s.value.payload.length);q.set(s.value.payload),d.decoder.push(s.value.sequenceNumber,s.value.timeStamp,s.value.isEndOfSpurt,q.byteOffset,q.length)}}insertMedia(A,t,s,i=[1,1]){let d=NA({connectionId:t,mediaId:s}),q=new this.wasm.Decoder;this.medias.set(d,{index:A,decoder:q,lastPacket:void 0}),this.decoders[A]=q.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),Tj(this.information,A,i),Vj(this.information,A,0),Mj(this.information,A,0)}removeMedia(A,t,s){let i=NA({connectionId:t,mediaId:s}),d=this.medias.get(i);if(!(d===void 0||d.index!==A)&&(this.medias.delete(i),wj(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:q}of s.removed)this.removeMedia(i,d,q);for(let{index:i,connectionId:d,mediaId:q,volume:p}of s.added)this.insertMedia(i,d,q,p);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=ot(t);A.push({index:s.index,connectionId:i.connectionId,mediaId:i.mediaId,rmsDBFS:Oj(this.information,s.index),volume:Uj(this.information,s.index),voicedBlocks:Sj(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,voiceAccelerated:s.decoder.voice_accelerated,silenceAccelerated:s.decoder.silence_accelerated,cacheLength:s.decoder.cache_length,lastPacket:Zj(s.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:Pj(this.information),decoders:A}}};var _t=hn($t()),Ft=(0,_t.default)(),vt,It;globalThis.addEventListener("message",Fr);async function Fr(e){let A=e.data,[t,s]=A;switch(t){case"captureInit":s.workletPort.onmessage=Fr,vt=new vr(s.sampleRate,await Ft);break;case"playbackInit":s.workletPort.onmessage=Fr,It=new Ir(await Ft);break;case"close":globalThis.close();break}vt?.onMessage(A),It?.onMessage(A)}var vr=class extends wA{constructor(t,s){super(t,s);this.id=-1;this.samples=fr(this.wasm,t,2+b.VadPreload+b.AdditionalCaptureBlocks,!1),kA(globalThis,["captureReady",{sampleBuffer:this.samples,informationBuffer:this.information}])}close(){super.close(),Cr(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(kr(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()}}},Ir=class extends UA{constructor(A){super(A);let t=2+b.AdditionalPlaybackBlocks;this.sampleBuffer=fr(A,48e3,t,!0),this.sampleBuffer.samples.fill(0),this.prefill=t-2;for(let s=0;s<this.prefill;s++)ur(this.sampleBuffer,s,{id:s});this.id=this.prefill,kA(globalThis,["playbackReady",{sampleBuffer:this.sampleBuffer,informationBuffer:this.information}])}close(){super.close(),Cr(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(kr(this.sampleBuffer,t));s&&(this.stats.numberTicksWithAudio++,ur(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()}}};})();
3245
+ `});var Qx,$0=m(()=>{Qx='"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:()=>z,WebRtcMaxNegotiationAttempts:()=>q,WebRtcStatsSnapshotInterval:()=>J,WebRtcTimeout:()=>G});var D=3,C=3,L=3,V=250,O=3,_=512,N=128,k=-758.596,W=1e4,j=1e3,$=1e4,H=3e3,J=1e3,z=3e3,G=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 y0={};Tx(y0,{createCaptureWorker:()=>tF,createPlaybackWorker:()=>eF});import{Strand as rF}from"@4players/odin-common";function tF(v,t,e,j,B=i.DefaultRefreshRate){return DF.enqueue(async()=>{let[C,E]=await Y(Wx,Qx,v,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return Xx.create(v,t,e,C,E,j)})}async function eF(v,t=i.DefaultRefreshRate){if(v.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[e,j]=await Y(Wx,Qx,v,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return zx.create(v,e,j)}var DF,zx,Xx,I0=m(()=>{"use strict";u();nx();G0();$0();DF=new rF;zx=class v extends z{constructor(e,j,B,C){super(e,j,B);this.information=C}static async create(e,j,B){let{port1:C,port2:E}=new MessageChannel;c(j,["playbackInit",{workletPort:C}],[C]);let{informationBuffer:f,sampleBuffer:s}=await V(j,"playbackReady");return Kx(f,[1,1]),c(B.port,["init",{sampleBuffer:s,workerPort:E}],[E]),new v(e,B,j,f)}getActivity(e){let j=this.medias.get(q(e));if(j===void 0)return;let B=E0(this.information,j.index);return B===0?_:{isSilent:!1,rmsDBFS:B}}getJitterStats(e){}setGlobalVolume(e){Kx(this.information,e)}setVolume(e,j){let B=this.medias.get(q(e));B!==void 0&&f0(this.information,B.index,j)}_GetFreeIndex(){let e=super._GetFreeIndex();if(e!==void 0)return e;if(this.information.length>this.medias.size)return this.medias.size}},Xx=class v extends X{constructor(e,j,B,C,E,f){super(e,j,B,C,f);this.information=E}static async create(e,j,B,C,E,f){let{port1:s,port2:b}=new MessageChannel;c(C,["captureInit",{sampleRate:e.sampleRate,workletPort:s}],[s]);let{sampleBuffer:d,informationBuffer:h}=await V(C,"captureReady");return c(E.port,["init",{workerPort:b,sampleBuffer:d}],[b]),new v(E,C,j,B,h,f)}get activity(){return{isSilent:!n0(this.information),rmsDBFS:i0(this.information)}}get speechProbability(){return s0(this.information)}setVolume(e){b0(this.information,e)}}});var Zx,g0=m(()=>{Zx=`"use strict";(()=>{var ne=Object.create;var QA=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var ie=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty;var ae=(e,A)=>()=>{try{return A||e((A={exports:{}}).exports,A),A.exports}catch(r){throw A=0,r}},ke=(e,A)=>{for(var r in A)QA(e,r,{get:A[r],enumerable:!0})},ue=(e,A,r,n)=>{if(A&&typeof A=="object"||typeof A=="function")for(let l of le(A))!oe.call(e,l)&&l!==r&&QA(e,l,{get:()=>A[l],enumerable:!(n=se(A,l))||n.enumerable});return e};var ce=(e,A,r)=>(r=e!=null?ne(ie(e)):{},ue(A||!e||!e.__esModule?QA(r,"default",{value:e,enumerable:!0}):r,e));var Fj=ae(($j,OA)=>{"use strict";var nr=(()=>{var e=globalThis.document?.currentScript?.src;return async function(A={}){var r=A,n=!!globalThis.window,l=!!globalThis.WorkerGlobalScope,d=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",q=[],p="./this.program";l&&(e=self.location.href);var I="",N,UA;if(n||l){try{I=new URL(".",e).href}catch{}l&&(UA=t=>{var j=new XMLHttpRequest;return j.open("GET",t,!1),j.responseType="arraybuffer",j.send(null),new Uint8Array(j.response)}),N=async t=>{var j=await fetch(t,{credentials:"same-origin"});if(j.ok)return j.arrayBuffer();throw new Error(j.status+" : "+j.url)}}var x=console.log.bind(console),aA=console.error.bind(console),yj,or=!1;class Hj{}class mn extends Hj{}function Lj(t){for(var j=0,s=t.length,i=new Uint8Array(s),o;j<s;++j)o=t.charCodeAt(j),i[j]=~o>>8&o;return i}var gj=!1;function Nj(){var t=Or.buffer;S=new Int8Array(t),uA=new Int16Array(t),r.HEAPU8=L=new Uint8Array(t),Y=new Uint16Array(t),r.HEAP32=cA=new Int32Array(t),r.HEAPU32=h=new Uint32Array(t),r.HEAPF32=ur=new Float32Array(t),cr=new Float64Array(t),kr=new BigInt64Array(t),dr=new BigUint64Array(t)}function Bj(){var t=r.preRun;t&&(typeof t=="function"&&(t=[t]),fr.push(...t)),qr(fr)}function xj(){gj=!0,jA.v()}function bj(){var t=r.postRun;t&&(typeof t=="function"&&(t=[t]),Cr.push(...t)),qr(Cr)}function kA(t){r.onAbort?.(t),t=\`Aborted(\${t})\`,aA(t),or=!0,t+=". Build with -sASSERTIONS for more info.";var j=new WebAssembly.RuntimeError(t);throw j}var ar;function Jj(){return Lj(\`\\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}}\\\`\\x7F\\x7F}}\\0\\\`
3246
3246
  \\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|}\\\`\\0\\x7F\\\`\\x7F\\x7F\\x7F~~\\0\\\`\\r\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F\\x7F\\x7F\\\`\\x7F\\x7F|\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\x7F\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F}}\\x7F\\x7F\\x7F\\x7F\\0\\\`~\\x7F\\x7F\\\` \\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\\`||\\x7F|\\\`|||\\\`\\x7F\\x7F\\x7F|\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\\`\\f\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`}\\x7F\\x7F\\\`|\\x7F\\x7F\\\`\\x7F\\x7F\\x7F}\\\`\\x7F}\\x7F\\0\\\`\\x7F\\x7F}\\x7F\\x7F\\x7F}\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F}}\\0yaa\\0ab\\0ac\\0ad\\0ae\\0af\\0ag\\0!ah\\0 ai\\0aj\\0\\bak\\0"al\\0am\\0an\\0ao\\0\\0ap\\0#aq\\0\\0ar\\0
3247
3247
  as\\0at\\0\\xBA\\xB8\\0\\0\\f$\\f\\x07\\0\\f\\x07\\f\\x07\\0%& \\0
3248
3248
  \\0\\x07\\v\\0'\\0\\0(\\0\\f\\0)*+\\x07\\v\\x07\\0
@@ -6442,7 +6442,7 @@ K\\xE08\\xDF\\0}\\xBC\\x8A\\x1B\\f\\xE5\\xFF\\xCF\\xE8?\\x9F\\xFFFq\\0\\x88\\xB
6442
6442
 
6443
6443
  
6444
6444
  \\x07\\0\\0 \\v\\0\\0 \\v\\0\\0\\v\\0\\0\\0\\0\\0A\\xD1\\x9E\\v!\\0\\0\\0\\0\\0\\0\\0\\0\\0\\v\\r\\0\\r\\0\\0\\0 \\0\\0\\0 \\0\\0\\0\\0A\\x8B\\x9F\\v\\f\\0A\\x97\\x9F\\v\\0\\0\\0\\0\\0\\0\\0\\0 \\f\\0\\0\\0\\0\\0\\f\\0\\0\\f\\0A\\xC5\\x9F\\v\\0A\\xD1\\x9F\\v\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0A\\xFF\\x9F\\v\\0A\\x8B\\xA0\\v\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0A\\xC2\\xA0\\v\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0A\\xF3\\xA0\\v\\0A\\xFF\\xA0\\v\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0A\\xAD\\xA1\\v\\0A\\xB9\\xA1\\v\\xB3 \\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\x000123456789ABCDEF\\x90\\0\\xE8\\0NSt3__214__shared_countE\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\xE0\\0\\0\\0\\0\\0NSt3__219__shared_weak_countE\\0\\0\\0\\xB8\\0H\\0X\\0N10__cxxabiv116__shim_type_infoE\\0\\0\\0\\0\\xB8\\0x\\0<\\0N10__cxxabiv117__class_type_infoE\\0\\0\\0\\xB8\\0\\xA8\\0<\\0N10__cxxabiv117__pbase_type_infoE\\0\\0\\0\\xB8\\0\\xD8\\0\\x9C\\0N10__cxxabiv119__pointer_type_infoE\\0\\xB8\\0\\b\\0<\\0N10__cxxabiv120__function_type_infoE\\0\\0\\0\\0\\xB8\\0<\\0\\x9C\\0N10__cxxabiv129__pointer_to_member_type_infoE\\0\\0\\0\\0\\0\\0\\0\\x88\\0_\\0\\0\\0\\\`\\0\\0\\0a\\0\\0\\0b\\0\\0\\0c\\0\\0\\0\\xB8\\0\\x94\\0<\\0N10__cxxabiv123__fundamental_type_infoE\\0t\\0\\xC4\\0v\\0Dn\\0\\0\\0\\0t\\0\\xD4\\0b\\0\\0\\0t\\0\\xE0\\0c\\0\\0\\0t\\0\\xEC\\0h\\0\\0\\0t\\0\\xF8\\0a\\0\\0\\0t\\0\\0s\\0\\0\\0t\\0\\0t\\0\\0\\0t\\0\\0i\\0\\0\\0t\\0(\\0j\\0\\0\\0t\\x004\\0l\\0\\0\\0t\\0@\\0m\\0\\0\\0t\\0L\\0x\\0\\0\\0t\\0X\\0y\\0\\0\\0t\\0d\\0f\\0\\0\\0p\\0x\\0\\0\\0\\0\\0\\\\\\0Pf\\0\\0t\\0\\x84\\0d\\0\\0\\0\\0\\0\\0\\0l\\0_\\0\\0\\0d\\0\\0\\0a\\0\\0\\0b\\0\\0\\0e\\0\\0\\0f\\0\\0\\0g\\0\\0\\0h\\0\\0\\0\\0\\0\\0\\0\\xD8\\0_\\0\\0\\0i\\0\\0\\0a\\0\\0\\0b\\0\\0\\0e\\0\\0\\0j\\0\\0\\0k\\0\\0\\0l\\0\\0\\0\\xB8\\0\\xE4\\0l\\0N10__cxxabiv120__si_class_type_infoE\\0\\0\\0\\0\\0\\0\\0\\x004\\0_\\0\\0\\0m\\0\\0\\0a\\0\\0\\0b\\0\\0\\0e\\0\\0\\0n\\0\\0\\0o\\0\\0\\0p\\0\\0\\0\\xB8\\0@\\0l\\0N10__cxxabiv121__vmi_class_type_infoE\\0\\0\\0\\0\\0\\0\\0\\xCC\\0_\\0\\0\\0q\\0\\0\\0a\\0\\0\\0b\\0\\0\\0r\\0\\0\\0\\0\\0\\0\\0\\xCC\\0E\\0\\0\\0s\\0\\0\\0t\\0\\0\\0\\x90\\0\\xA0\\0St9exception\\0\\0\\0\\0\\xB8\\0\\xBC\\0\\x98\\0St9bad_alloc\\0\\0\\0\\0\\xB8\\0\\xD8\\0\\xB0\\0St20bad_array_new_length\\0\\0\\0\\0\\0\\0\\0\\0\\b\\0G\\0\\0\\0u\\0\\0\\0v\\0\\0\\0\\xB8\\0\\0\\x98\\0St11logic_error\\0\\0\\0\\0\\x008\\0G\\0\\0\\0w\\0\\0\\0v\\0\\0\\0\\xB8\\0D\\0\\b\\0St12length_error\\0\\0\\0\\0\\x90\\0\\\`\\0St9type_info\\0A\\xF0\\xAA\\v\\0A\\xFC\\xAA\\vW\\0A\\x94\\xAB\\v\\vX\\0\\0\\0Y\\0\\0\\0\\xD8\\0A\\xAC\\xAB\\v\\0A\\xBC\\xAB\\v\\b\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\0A\\x80\\xAC\\v p\\0\\0\\0\\0\\0\\0A\\x94\\xAC\\vZ\\0A\\xAC\\xAC\\vX\\0\\0\\0[\\0\\0\\0\\xE8\\0\\0\\0A\\xC4\\xAC\\v\\0A\\xD4\\xAC\\v\\xFF\\xFF\\xFF\\xFF
6445
- \\0A\\x98\\xAD\\v\\v\\b\\0\\b\\x1B\\0 \`)}function mn(t){return t}async function Pj(t){return t}async function Oj(t,j){try{var s=await Pj(t),i=await WebAssembly.instantiate(s,j);return i}catch(o){aA(\`failed to asynchronously prepare wasm: \${o}\`),kA(o)}}async function Uj(t,j,s){return Oj(j,s)}function wj(){var t={a:je};return t}async function Tj(){function t(a){return jA=a.exports,re(jA),Nj(),jA}function j(a){return t(a.instance)}var s=wj(),i=r.instantiateWasm;if(i)return new Promise(a=>{i(s,u=>a(t(u)))});ar??=Jj();var o=await Uj(yj,ar,s),k=j(o);return k}class hn{name="ExitStatus";constructor(j){this.message=\`Program terminated with exit(\${j})\`,this.status=j}}var uA,cA,kr,S,ur,cr,Y,h,dr,L,qr=t=>{for(;t.length>0;)t.shift()(r)},Cr=[],fr=[],Kj=!0;class Sj{constructor(j){this.excPtr=j,this.ptr=j-24}set_type(j){h[this.ptr+4>>2]=j}get_type(){return h[this.ptr+4>>2]}set_destructor(j){h[this.ptr+8>>2]=j}get_destructor(){return h[this.ptr+8>>2]}set_caught(j){j=j?1:0,S[this.ptr+12]=j}get_caught(){return S[this.ptr+12]!=0}set_rethrown(j){j=j?1:0,S[this.ptr+13]=j}get_rethrown(){return S[this.ptr+13]!=0}init(j,s){this.set_adjusted_ptr(0),this.set_type(j),this.set_destructor(s)}set_adjusted_ptr(j){h[this.ptr+16>>2]=j}get_adjusted_ptr(){return h[this.ptr+16>>2]}}var Mj=0,Vj=(t,j,s)=>{var i=new Sj(t);i.init(j,s),Mj++,kA()},Rj=()=>kA(""),v=t=>{for(var j="";;){var s=L[t++];if(!s)return j;j+=String.fromCharCode(s)}},Q={},z={},dA={},AA=class extends Error{constructor(j){super(j),this.name="BindingError"}},G=t=>{throw new AA(t)};function Wj(t,j,s={}){var i=j.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]=j,delete dA[t],Q.hasOwnProperty(t)){var o=Q[t];delete Q[t],o.forEach(k=>k())}}function B(t,j,s={}){return Wj(t,j,s)}var Gr=(t,j,s)=>{switch(j){case 1:return s?i=>S[i]:i=>L[i];case 2:return s?i=>uA[i>>1]:i=>Y[i>>1];case 4:return s?i=>cA[i>>2]:i=>h[i>>2];case 8:return s?i=>kr[i>>3]:i=>dr[i>>3];default:throw new TypeError(\`invalid integer width (\${j}): \${t}\`)}},Qj=(t,j,s,i,o)=>{j=v(j);let k=i===0n,a=u=>u;if(k){let u=s*8;a=c=>BigInt.asUintN(u,c),o=a(o)}B(t,{name:j,fromWireType:a,toWireType:(u,c)=>(typeof c=="number"&&(c=BigInt(c)),c),readValueFromPointer:Gr(j,s,!k),destructorFunction:null})},zj=(t,j,s,i)=>{j=v(j),B(t,{name:j,fromWireType:function(o){return!!o},toWireType:function(o,k){return k?s:i},readValueFromPointer:function(o){return this.fromWireType(L[o])},destructorFunction:null})},Xj=t=>({count:t.count,deleteScheduled:t.deleteScheduled,preservePointerOnDelete:t.preservePointerOnDelete,ptr:t.ptr,ptrType:t.ptrType,smartPtr:t.smartPtr,smartPtrType:t.smartPtrType}),wA=t=>{function j(s){return s.$$.ptrType.registeredClass.name}G(j(t)+" instance already deleted")},TA=!1,pr=t=>{},Zj=t=>{t.smartPtr?t.smartPtrType.rawDestructor(t.smartPtr):t.ptrType.registeredClass.rawDestructor(t.ptr)},Er=t=>{t.count.value-=1;var j=t.count.value===0;j&&Zj(t)},rA=t=>globalThis.FinalizationRegistry?(TA=new FinalizationRegistry(j=>{Er(j.$$)}),rA=j=>{var s=j.$$,i=!!s.smartPtr;if(i){var o={$$:s};TA.register(j,o,j)}return j},pr=j=>TA.unregister(j),rA(t)):(rA=j=>j,t),qA=[],Yj=()=>{for(;qA.length;){var t=qA.pop();t.$$.deleteScheduled=!1,t.delete()}},mr,At=()=>{let t=CA.prototype;Object.assign(t,{isAliasOf(s){if(!(this instanceof CA)||!(s instanceof CA))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||wA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var s=rA(Object.create(Object.getPrototypeOf(this),{$$:{value:Xj(this.$$)}}));return s.$$.count.value+=1,s.$$.deleteScheduled=!1,s},delete(){this.$$.ptr||wA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),pr(this),Er(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||wA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),qA.push(this),qA.length===1&&mr&&mr(Yj),this.$$.deleteScheduled=!0,this}});let j=Symbol.dispose;j&&(t[j]=t.delete)};function CA(){}var hr=(t,j)=>Object.defineProperty(j,"name",{value:t}),$r={},Fr=(t,j,s)=>{if(t[j].overloadTable===void 0){var i=t[j];t[j]=function(...o){return t[j].overloadTable.hasOwnProperty(o.length)||G(\`Function '\${s}' called with an invalid number of arguments (\${o.length}) - expects one of (\${t[j].overloadTable})!\`),t[j].overloadTable[o.length].apply(this,o)},t[j].overloadTable=[],t[j].overloadTable[i.argCount]=i}},Ir=(t,j,s)=>{r.hasOwnProperty(t)?((s===void 0||r[t].overloadTable!==void 0&&r[t].overloadTable[s]!==void 0)&&G(\`Cannot register public name '\${t}' twice\`),Fr(r,t,t),r[t].overloadTable.hasOwnProperty(s)&&G(\`Cannot register multiple overloads of a function with the same number of arguments (\${s})!\`),r[t].overloadTable[s]=j):(r[t]=j,r[t].argCount=s)},rt=48,jt=57,tt=t=>{t=t.replace(/[^a-zA-Z0-9_]/g,"$");var j=t.charCodeAt(0);return j>=rt&&j<=jt?\`_\${t}\`:t};function et(t,j,s,i,o,k,a,u){this.name=t,this.constructor=j,this.instancePrototype=s,this.rawDestructor=i,this.baseClass=o,this.getActualType=k,this.upcast=a,this.downcast=u,this.pureVirtualFunctions=[]}var fA=(t,j,s)=>{for(;j!==s;)j.upcast||G(\`Expected null or instance of \${s.name}, got an instance of \${j.name}\`),t=j.upcast(t),j=j.baseClass;return t},KA=t=>{if(t===null)return"null";var j=typeof t;return j==="object"||j==="array"||j==="function"?t.toString():""+t};function nt(t,j){if(j===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;j.$$||G(\`Cannot pass "\${KA(j)}" as a \${this.name}\`),j.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`);var s=j.$$.ptrType.registeredClass,i=fA(j.$$.ptr,s,this.registeredClass);return i}function st(t,j){var s;if(j===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;(!j||!j.$$)&&G(\`Cannot pass "\${KA(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 i=j.$$.ptrType.registeredClass;if(s=fA(j.$$.ptr,i,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?s=j.$$.smartPtr:G(\`Cannot convert argument of type \${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type \${this.name}\`);break;case 1:s=j.$$.smartPtr;break;case 2:if(j.$$.smartPtrType===this)s=j.$$.smartPtr;else{var o=j.clone();s=this.rawShare(s,VA.toHandle(()=>o.delete())),t!==null&&t.push(this.rawDestructor,s)}break;default:G("Unsupported sharing policy")}return s}function lt(t,j){if(j===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;j.$$||G(\`Cannot pass "\${KA(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 s=j.$$.ptrType.registeredClass,i=fA(j.$$.ptr,s,this.registeredClass);return i}function GA(t){return this.fromWireType(h[t>>2])}var vr=(t,j,s)=>{if(j===s)return t;if(s.baseClass===void 0)return null;var i=vr(t,j,s.baseClass);return i===null?null:s.downcast(i)},it={},ot=(t,j)=>{for(j===void 0&&G("ptr should not be undefined");t.baseClass;)j=t.upcast(j),t=t.baseClass;return j},at=(t,j)=>(j=ot(t,j),it[j]),kt=class extends Error{constructor(j){super(j),this.name="InternalError"}},pA=t=>{throw new kt(t)},EA=(t,j)=>{(!j.ptrType||!j.ptr)&&pA("makeClassHandle requires ptr and ptrType");var s=!!j.smartPtrType,i=!!j.smartPtr;return s!==i&&pA("Both smartPtrType and smartPtr must be specified"),j.count={value:1},rA(Object.create(t,{$$:{value:j,writable:!0}}))};function ut(t){var j=this.getPointee(t);if(!j)return this.destructor(t),null;var s=at(this.registeredClass,j);if(s!==void 0){if(s.$$.count.value===0)return s.$$.ptr=j,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:j,smartPtrType:this,smartPtr:t}):EA(this.registeredClass.instancePrototype,{ptrType:this,ptr:t})}var k=this.registeredClass.getActualType(j),a=$r[k];if(!a)return o.call(this);var u;this.isConst?u=a.constPointerType:u=a.pointerType;var c=vr(j,this.registeredClass,u.registeredClass);return c===null?o.call(this):this.isSmartPointer?EA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c,smartPtrType:this,smartPtr:t}):EA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c})}var ct=()=>{Object.assign(mA.prototype,{getPointee(t){return this.rawGetPointee&&(t=this.rawGetPointee(t)),t},destructor(t){this.rawDestructor?.(t)},readValueFromPointer:GA,fromWireType:ut})};function mA(t,j,s,i,o,k,a,u,c,C,f){this.name=t,this.registeredClass=j,this.isReference=s,this.isConst=i,this.isSmartPointer=o,this.pointeeType=k,this.sharingPolicy=a,this.rawGetPointee=u,this.rawConstructor=c,this.rawShare=C,this.rawDestructor=f,!o&&j.baseClass===void 0?i?(this.toWireType=nt,this.destructorFunction=null):(this.toWireType=lt,this.destructorFunction=null):this.toWireType=st}var Dr=(t,j,s)=>{r.hasOwnProperty(t)||pA("Replacing nonexistent public symbol"),r[t].overloadTable!==void 0&&s!==void 0?r[t].overloadTable[s]=j:(r[t]=j,r[t].argCount=s)},_r=[],dt=t=>{var j=_r[t];return j||(_r[t]=j=Ur.get(t)),j},b=(t,j,s=!1)=>{t=v(t);function i(){var k=dt(j);return k}var o=i();return typeof o!="function"&&G(\`unknown function pointer with signature \${t}: \${j}\`),o};class qt extends Error{}var Ct=t=>{var j=Pr(t),s=v(j);return J(j),s},X=(t,j)=>{var s=[],i={};function o(k){if(!i[k]&&!z[k]){if(dA[k]){dA[k].forEach(o);return}s.push(k),i[k]=!0}}throw j.forEach(o),new qt(\`\${t}: \`+s.map(Ct).join([", "]))},U=(t,j,s)=>{t.forEach(u=>dA[u]=j);function i(u){var c=s(u);c.length!==t.length&&pA("Mismatched type converter count");for(var C=0;C<t.length;++C)B(t[C],c[C])}var o=new Array(j.length),k=[],a=0;for(let[u,c]of j.entries())z.hasOwnProperty(c)?o[u]=z[c]:(k.push(c),Q.hasOwnProperty(c)||(Q[c]=[]),Q[c].push(()=>{o[u]=z[c],++a,a===k.length&&i(o)}));k.length===0&&i(o)},ft=(t,j,s,i,o,k,a,u,c,C,f,m,$)=>{f=v(f),k=b(o,k),u&&=b(a,u),C&&=b(c,C),$=b(m,$);var E=tt(f);Ir(E,function(){X(\`Cannot construct \${f} due to unbound types\`,[i])}),U([t,j,s],i?[i]:[],F=>{F=F[0];var y,P;i?(y=F.registeredClass,P=y.instancePrototype):P=CA.prototype;var H=hr(f,function(...WA){if(Object.getPrototypeOf(this)!==tA)throw new AA(\`Use 'new' to construct \${f}\`);if(_.constructor_body===void 0)throw new AA(\`\${f} has no accessible constructor\`);var Kr=_.constructor_body[WA.length];if(Kr===void 0)throw new AA(\`Tried to invoke ctor of \${f} with invalid number of parameters (\${WA.length}) - expected (\${Object.keys(_.constructor_body).toString()}) parameters instead!\`);return Kr.apply(this,WA)}),tA=Object.create(P,{constructor:{value:H}});H.prototype=tA;var _=new et(f,H,tA,$,y,k,u,C);_.baseClass&&(_.baseClass.__derivedClasses??=[],_.baseClass.__derivedClasses.push(_));var ee=new mA(f,_,!0,!1,!1),wr=new mA(f+"*",_,!1,!1,!1),Tr=new mA(f+" const*",_,!1,!0,!1);return $r[t]={pointerType:wr,constPointerType:Tr},Dr(E,H),[ee,wr,Tr]})},SA=(t,j)=>{for(var s=[],i=0;i<t;i++)s.push(h[j+i*4>>2]);return s},yr=t=>{for(;t.length;){var j=t.pop(),s=t.pop();s(j)}};function Hr(t){for(var j=1;j<t.length;++j)if(t[j]!==null&&t[j].destructorFunction===void 0)return!0;return!1}function Gt(t,j,s,i){var o=Hr(t),k=t.length-2,a=[],u=["fn"];j&&u.push("thisWired");for(var c=0;c<k;++c)a.push(\`arg\${c}\`),u.push(\`arg\${c}Wired\`);a=a.join(),u=u.join();var C=\`return function (\${a}) {
6445
+ \\0A\\x98\\xAD\\v\\v\\b\\0\\b\\x1B\\0 \`)}function hn(t){return t}async function Pj(t){return t}async function Oj(t,j){try{var s=await Pj(t),i=await WebAssembly.instantiate(s,j);return i}catch(o){aA(\`failed to asynchronously prepare wasm: \${o}\`),kA(o)}}async function Uj(t,j,s){return Oj(j,s)}function wj(){var t={a:je};return t}async function Tj(){function t(a){return jA=a.exports,re(jA),Nj(),jA}function j(a){return t(a.instance)}var s=wj(),i=r.instantiateWasm;if(i)return new Promise(a=>{i(s,u=>a(t(u)))});ar??=Jj();var o=await Uj(yj,ar,s),k=j(o);return k}class $n{name="ExitStatus";constructor(j){this.message=\`Program terminated with exit(\${j})\`,this.status=j}}var uA,cA,kr,S,ur,cr,Y,h,dr,L,qr=t=>{for(;t.length>0;)t.shift()(r)},Cr=[],fr=[],Kj=!0;class Sj{constructor(j){this.excPtr=j,this.ptr=j-24}set_type(j){h[this.ptr+4>>2]=j}get_type(){return h[this.ptr+4>>2]}set_destructor(j){h[this.ptr+8>>2]=j}get_destructor(){return h[this.ptr+8>>2]}set_caught(j){j=j?1:0,S[this.ptr+12]=j}get_caught(){return S[this.ptr+12]!=0}set_rethrown(j){j=j?1:0,S[this.ptr+13]=j}get_rethrown(){return S[this.ptr+13]!=0}init(j,s){this.set_adjusted_ptr(0),this.set_type(j),this.set_destructor(s)}set_adjusted_ptr(j){h[this.ptr+16>>2]=j}get_adjusted_ptr(){return h[this.ptr+16>>2]}}var Mj=0,Vj=(t,j,s)=>{var i=new Sj(t);i.init(j,s),Mj++,kA()},Rj=()=>kA(""),v=t=>{for(var j="";;){var s=L[t++];if(!s)return j;j+=String.fromCharCode(s)}},Q={},z={},dA={},AA=class extends Error{constructor(j){super(j),this.name="BindingError"}},G=t=>{throw new AA(t)};function Wj(t,j,s={}){var i=j.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]=j,delete dA[t],Q.hasOwnProperty(t)){var o=Q[t];delete Q[t],o.forEach(k=>k())}}function B(t,j,s={}){return Wj(t,j,s)}var Gr=(t,j,s)=>{switch(j){case 1:return s?i=>S[i]:i=>L[i];case 2:return s?i=>uA[i>>1]:i=>Y[i>>1];case 4:return s?i=>cA[i>>2]:i=>h[i>>2];case 8:return s?i=>kr[i>>3]:i=>dr[i>>3];default:throw new TypeError(\`invalid integer width (\${j}): \${t}\`)}},Qj=(t,j,s,i,o)=>{j=v(j);let k=i===0n,a=u=>u;if(k){let u=s*8;a=c=>BigInt.asUintN(u,c),o=a(o)}B(t,{name:j,fromWireType:a,toWireType:(u,c)=>(typeof c=="number"&&(c=BigInt(c)),c),readValueFromPointer:Gr(j,s,!k),destructorFunction:null})},zj=(t,j,s,i)=>{j=v(j),B(t,{name:j,fromWireType:function(o){return!!o},toWireType:function(o,k){return k?s:i},readValueFromPointer:function(o){return this.fromWireType(L[o])},destructorFunction:null})},Xj=t=>({count:t.count,deleteScheduled:t.deleteScheduled,preservePointerOnDelete:t.preservePointerOnDelete,ptr:t.ptr,ptrType:t.ptrType,smartPtr:t.smartPtr,smartPtrType:t.smartPtrType}),wA=t=>{function j(s){return s.$$.ptrType.registeredClass.name}G(j(t)+" instance already deleted")},TA=!1,pr=t=>{},Zj=t=>{t.smartPtr?t.smartPtrType.rawDestructor(t.smartPtr):t.ptrType.registeredClass.rawDestructor(t.ptr)},Er=t=>{t.count.value-=1;var j=t.count.value===0;j&&Zj(t)},rA=t=>globalThis.FinalizationRegistry?(TA=new FinalizationRegistry(j=>{Er(j.$$)}),rA=j=>{var s=j.$$,i=!!s.smartPtr;if(i){var o={$$:s};TA.register(j,o,j)}return j},pr=j=>TA.unregister(j),rA(t)):(rA=j=>j,t),qA=[],Yj=()=>{for(;qA.length;){var t=qA.pop();t.$$.deleteScheduled=!1,t.delete()}},mr,At=()=>{let t=CA.prototype;Object.assign(t,{isAliasOf(s){if(!(this instanceof CA)||!(s instanceof CA))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||wA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var s=rA(Object.create(Object.getPrototypeOf(this),{$$:{value:Xj(this.$$)}}));return s.$$.count.value+=1,s.$$.deleteScheduled=!1,s},delete(){this.$$.ptr||wA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),pr(this),Er(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||wA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),qA.push(this),qA.length===1&&mr&&mr(Yj),this.$$.deleteScheduled=!0,this}});let j=Symbol.dispose;j&&(t[j]=t.delete)};function CA(){}var hr=(t,j)=>Object.defineProperty(j,"name",{value:t}),$r={},Fr=(t,j,s)=>{if(t[j].overloadTable===void 0){var i=t[j];t[j]=function(...o){return t[j].overloadTable.hasOwnProperty(o.length)||G(\`Function '\${s}' called with an invalid number of arguments (\${o.length}) - expects one of (\${t[j].overloadTable})!\`),t[j].overloadTable[o.length].apply(this,o)},t[j].overloadTable=[],t[j].overloadTable[i.argCount]=i}},Ir=(t,j,s)=>{r.hasOwnProperty(t)?((s===void 0||r[t].overloadTable!==void 0&&r[t].overloadTable[s]!==void 0)&&G(\`Cannot register public name '\${t}' twice\`),Fr(r,t,t),r[t].overloadTable.hasOwnProperty(s)&&G(\`Cannot register multiple overloads of a function with the same number of arguments (\${s})!\`),r[t].overloadTable[s]=j):(r[t]=j,r[t].argCount=s)},rt=48,jt=57,tt=t=>{t=t.replace(/[^a-zA-Z0-9_]/g,"$");var j=t.charCodeAt(0);return j>=rt&&j<=jt?\`_\${t}\`:t};function et(t,j,s,i,o,k,a,u){this.name=t,this.constructor=j,this.instancePrototype=s,this.rawDestructor=i,this.baseClass=o,this.getActualType=k,this.upcast=a,this.downcast=u,this.pureVirtualFunctions=[]}var fA=(t,j,s)=>{for(;j!==s;)j.upcast||G(\`Expected null or instance of \${s.name}, got an instance of \${j.name}\`),t=j.upcast(t),j=j.baseClass;return t},KA=t=>{if(t===null)return"null";var j=typeof t;return j==="object"||j==="array"||j==="function"?t.toString():""+t};function nt(t,j){if(j===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;j.$$||G(\`Cannot pass "\${KA(j)}" as a \${this.name}\`),j.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`);var s=j.$$.ptrType.registeredClass,i=fA(j.$$.ptr,s,this.registeredClass);return i}function st(t,j){var s;if(j===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;(!j||!j.$$)&&G(\`Cannot pass "\${KA(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 i=j.$$.ptrType.registeredClass;if(s=fA(j.$$.ptr,i,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?s=j.$$.smartPtr:G(\`Cannot convert argument of type \${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type \${this.name}\`);break;case 1:s=j.$$.smartPtr;break;case 2:if(j.$$.smartPtrType===this)s=j.$$.smartPtr;else{var o=j.clone();s=this.rawShare(s,VA.toHandle(()=>o.delete())),t!==null&&t.push(this.rawDestructor,s)}break;default:G("Unsupported sharing policy")}return s}function lt(t,j){if(j===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;j.$$||G(\`Cannot pass "\${KA(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 s=j.$$.ptrType.registeredClass,i=fA(j.$$.ptr,s,this.registeredClass);return i}function GA(t){return this.fromWireType(h[t>>2])}var vr=(t,j,s)=>{if(j===s)return t;if(s.baseClass===void 0)return null;var i=vr(t,j,s.baseClass);return i===null?null:s.downcast(i)},it={},ot=(t,j)=>{for(j===void 0&&G("ptr should not be undefined");t.baseClass;)j=t.upcast(j),t=t.baseClass;return j},at=(t,j)=>(j=ot(t,j),it[j]),kt=class extends Error{constructor(j){super(j),this.name="InternalError"}},pA=t=>{throw new kt(t)},EA=(t,j)=>{(!j.ptrType||!j.ptr)&&pA("makeClassHandle requires ptr and ptrType");var s=!!j.smartPtrType,i=!!j.smartPtr;return s!==i&&pA("Both smartPtrType and smartPtr must be specified"),j.count={value:1},rA(Object.create(t,{$$:{value:j,writable:!0}}))};function ut(t){var j=this.getPointee(t);if(!j)return this.destructor(t),null;var s=at(this.registeredClass,j);if(s!==void 0){if(s.$$.count.value===0)return s.$$.ptr=j,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:j,smartPtrType:this,smartPtr:t}):EA(this.registeredClass.instancePrototype,{ptrType:this,ptr:t})}var k=this.registeredClass.getActualType(j),a=$r[k];if(!a)return o.call(this);var u;this.isConst?u=a.constPointerType:u=a.pointerType;var c=vr(j,this.registeredClass,u.registeredClass);return c===null?o.call(this):this.isSmartPointer?EA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c,smartPtrType:this,smartPtr:t}):EA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c})}var ct=()=>{Object.assign(mA.prototype,{getPointee(t){return this.rawGetPointee&&(t=this.rawGetPointee(t)),t},destructor(t){this.rawDestructor?.(t)},readValueFromPointer:GA,fromWireType:ut})};function mA(t,j,s,i,o,k,a,u,c,C,f){this.name=t,this.registeredClass=j,this.isReference=s,this.isConst=i,this.isSmartPointer=o,this.pointeeType=k,this.sharingPolicy=a,this.rawGetPointee=u,this.rawConstructor=c,this.rawShare=C,this.rawDestructor=f,!o&&j.baseClass===void 0?i?(this.toWireType=nt,this.destructorFunction=null):(this.toWireType=lt,this.destructorFunction=null):this.toWireType=st}var Dr=(t,j,s)=>{r.hasOwnProperty(t)||pA("Replacing nonexistent public symbol"),r[t].overloadTable!==void 0&&s!==void 0?r[t].overloadTable[s]=j:(r[t]=j,r[t].argCount=s)},_r=[],dt=t=>{var j=_r[t];return j||(_r[t]=j=Ur.get(t)),j},b=(t,j,s=!1)=>{t=v(t);function i(){var k=dt(j);return k}var o=i();return typeof o!="function"&&G(\`unknown function pointer with signature \${t}: \${j}\`),o};class qt extends Error{}var Ct=t=>{var j=Pr(t),s=v(j);return J(j),s},X=(t,j)=>{var s=[],i={};function o(k){if(!i[k]&&!z[k]){if(dA[k]){dA[k].forEach(o);return}s.push(k),i[k]=!0}}throw j.forEach(o),new qt(\`\${t}: \`+s.map(Ct).join([", "]))},U=(t,j,s)=>{t.forEach(u=>dA[u]=j);function i(u){var c=s(u);c.length!==t.length&&pA("Mismatched type converter count");for(var C=0;C<t.length;++C)B(t[C],c[C])}var o=new Array(j.length),k=[],a=0;for(let[u,c]of j.entries())z.hasOwnProperty(c)?o[u]=z[c]:(k.push(c),Q.hasOwnProperty(c)||(Q[c]=[]),Q[c].push(()=>{o[u]=z[c],++a,a===k.length&&i(o)}));k.length===0&&i(o)},ft=(t,j,s,i,o,k,a,u,c,C,f,m,$)=>{f=v(f),k=b(o,k),u&&=b(a,u),C&&=b(c,C),$=b(m,$);var E=tt(f);Ir(E,function(){X(\`Cannot construct \${f} due to unbound types\`,[i])}),U([t,j,s],i?[i]:[],F=>{F=F[0];var y,P;i?(y=F.registeredClass,P=y.instancePrototype):P=CA.prototype;var H=hr(f,function(...WA){if(Object.getPrototypeOf(this)!==tA)throw new AA(\`Use 'new' to construct \${f}\`);if(_.constructor_body===void 0)throw new AA(\`\${f} has no accessible constructor\`);var Kr=_.constructor_body[WA.length];if(Kr===void 0)throw new AA(\`Tried to invoke ctor of \${f} with invalid number of parameters (\${WA.length}) - expected (\${Object.keys(_.constructor_body).toString()}) parameters instead!\`);return Kr.apply(this,WA)}),tA=Object.create(P,{constructor:{value:H}});H.prototype=tA;var _=new et(f,H,tA,$,y,k,u,C);_.baseClass&&(_.baseClass.__derivedClasses??=[],_.baseClass.__derivedClasses.push(_));var ee=new mA(f,_,!0,!1,!1),wr=new mA(f+"*",_,!1,!1,!1),Tr=new mA(f+" const*",_,!1,!0,!1);return $r[t]={pointerType:wr,constPointerType:Tr},Dr(E,H),[ee,wr,Tr]})},SA=(t,j)=>{for(var s=[],i=0;i<t;i++)s.push(h[j+i*4>>2]);return s},yr=t=>{for(;t.length;){var j=t.pop(),s=t.pop();s(j)}};function Hr(t){for(var j=1;j<t.length;++j)if(t[j]!==null&&t[j].destructorFunction===void 0)return!0;return!1}function Gt(t,j,s,i){var o=Hr(t),k=t.length-2,a=[],u=["fn"];j&&u.push("thisWired");for(var c=0;c<k;++c)a.push(\`arg\${c}\`),u.push(\`arg\${c}Wired\`);a=a.join(),u=u.join();var C=\`return function (\${a}) {
6446
6446
  \`;o&&(C+=\`var destructors = [];
6447
6447
  \`);var f=o?"destructors":"null",m=["humanName","throwBindingError","invoker","fn","runDestructors","fromRetWire","toClassParamWire"];j&&(C+=\`var thisWired = toClassParamWire(\${f}, this);
6448
6448
  \`);for(var c=0;c<k;++c){var $=\`toArg\${c}Wire\`;C+=\`var arg\${c}Wired = \${$}(\${f}, arg\${c});
@@ -6452,5 +6452,5 @@ K\\xE08\\xDF\\0}\\xBC\\x8A\\x1B\\f\\xE5\\xFF\\xCF\\xE8?\\x9F\\xFFFq\\0\\x88\\xB
6452
6452
  \`,m.push(\`\${E}_dtor\`))}return s&&(C+=\`var ret = fromRetWire(rv);
6453
6453
  return ret;
6454
6454
  \`),C+=\`}
6455
- \`,new Function(m,C)}function MA(t,j,s,i,o,k){var a=j.length;a<2&&G("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var u=j[1]!==null&&s!==null,c=Hr(j),C=!j[0].isVoid,f=j[0],m=j[1],$=[t,G,i,o,yr,f.fromWireType.bind(f),m?.toWireType.bind(m)],E=2;E<a;++E){var F=j[E];$.push(F.toWireType.bind(F))}if(!c)for(var E=u?1:2;E<j.length;++E)j[E].destructorFunction!==null&&$.push(j[E].destructorFunction);var P=Gt(j,u,C,k)(...$);return hr(t,P)}var pt=(t,j,s,i,o,k)=>{var a=SA(j,s);o=b(i,o),U([],[t],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 AA(\`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]=()=>{X(\`Cannot construct \${u.name} due to unbound types\`,a)},U([],a,C=>(C.splice(1,0,null),u.registeredClass.constructor_body[j-1]=MA(c,C,null,o,k),[])),[]})},Lr=t=>{t=t.trim();let j=t.indexOf("(");return j===-1?t:t.slice(0,j)},Et=(t,j,s,i,o,k,a,u,c,C)=>{var f=SA(s,i);j=v(j),j=Lr(j),k=b(o,k,c),U([],[t],m=>{m=m[0];var $=\`\${m.name}.\${j}\`;j.startsWith("@@")&&(j=Symbol[j.substring(2)]),u&&m.registeredClass.pureVirtualFunctions.push(j);function E(){X(\`Cannot call \${$} due to unbound types\`,f)}var F=m.registeredClass.instancePrototype,y=F[j];return y===void 0||y.overloadTable===void 0&&y.className!==m.name&&y.argCount===s-2?(E.argCount=s-2,E.className=m.name,F[j]=E):(Fr(F,j,$),F[j].overloadTable[s-2]=E),U([],f,P=>{var H=MA($,P,m,k,a,c);return F[j].overloadTable===void 0?(H.argCount=s-2,F[j]=H):F[j].overloadTable[s-2]=H,[]}),[]})},gr=(t,j,s)=>(t instanceof Object||G(\`\${s} with invalid "this": \${t}\`),t instanceof j.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,j.registeredClass)),mt=(t,j,s,i,o,k,a,u,c,C)=>{j=v(j),o=b(i,o),U([],[t],f=>{f=f[0];var m=\`\${f.name}.\${j}\`,$={get(){X(\`Cannot access \${m} due to unbound types\`,[s,a])},enumerable:!0,configurable:!0};return c?$.set=()=>X(\`Cannot access \${m} due to unbound types\`,[s,a]):$.set=E=>G(m+" is a read-only property"),Object.defineProperty(f.registeredClass.instancePrototype,j,$),U([],c?[s,a]:[s],E=>{var F=E[0],y={get(){var H=gr(this,f,m+" getter");return F.fromWireType(o(k,H))},enumerable:!0};if(c){c=b(u,c);var P=E[1];y.set=function(H){var tA=gr(this,f,m+" setter"),_=[];c(C,tA,P.toWireType(_,H)),yr(_)}}return Object.defineProperty(f.registeredClass.instancePrototype,j,y),[]}),[]})},Nr=[],M=[0,1,,1,null,1,!0,1,!1,1],ht=t=>{if(t>9&&--M[t+1]===0){var j=M[t];M[t]=void 0,Nr.push(t)}},VA={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 j=Nr.pop()||M.length;return M[j]=t,M[j+1]=1,j}}}},$t={name:"emscripten::val",fromWireType:t=>{var j=VA.toValue(t);return ht(t),j},toWireType:(t,j)=>VA.toHandle(j),readValueFromPointer:GA,destructorFunction:null},Ft=t=>B(t,$t),It=(t,j)=>{switch(j){case 4:return function(s){return this.fromWireType(ur[s>>2])};case 8:return function(s){return this.fromWireType(cr[s>>3])};default:throw new TypeError(\`invalid float width (\${j}): \${t}\`)}},vt=(t,j,s)=>{j=v(j),B(t,{name:j,fromWireType:i=>i,toWireType:(i,o)=>o,readValueFromPointer:It(j,s),destructorFunction:null})},Dt=(t,j,s,i,o,k,a,u)=>{var c=SA(j,s);t=v(t),t=Lr(t),o=b(i,o,a),Ir(t,function(){X(\`Cannot call \${t} due to unbound types\`,c)},j-1),U([],c,C=>{var f=[C[0],null].concat(C.slice(1));return Dr(t,MA(t,f,null,o,k,a),j-1),[]})},_t=(t,j,s,i,o)=>{j=v(j);let k=i===0,a=c=>c;if(k){var u=32-8*s;a=c=>c<<u>>>u,o=a(o)}B(t,{name:j,fromWireType:a,toWireType:(c,C)=>C,readValueFromPointer:Gr(j,s,i!==0),destructorFunction:null})},yt=(t,j,s)=>{var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=i[j];function k(a){var u=h[a>>2],c=h[a+4>>2];return new o(S.buffer,c,u)}s=v(s),B(t,{name:s,fromWireType:k,readValueFromPointer:k},{ignoreDuplicateRegistrations:!0})},Ht=(t,j,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;j[s++]=u}else if(u<=2047){if(s+1>=k)break;j[s++]=192|u>>6,j[s++]=128|u&63}else if(u<=65535){if(s+2>=k)break;j[s++]=224|u>>12,j[s++]=128|u>>6&63,j[s++]=128|u&63}else{if(s+3>=k)break;j[s++]=240|u>>18,j[s++]=128|u>>12&63,j[s++]=128|u>>6&63,j[s++]=128|u&63,a++}}return j[s]=0,s-o},Lt=(t,j,s)=>Ht(t,L,j,s),gt=t=>{for(var j=0,s=0;s<t.length;++s){var i=t.charCodeAt(s);i<=127?j++:i<=2047?j+=2:i>=55296&&i<=57343?(j+=4,++s):j+=3}return j},Br=globalThis.TextDecoder&&new TextDecoder,xr=(t,j,s,i)=>{var o=j+s;if(i)return o;for(;t[j]&&!(j>=o);)++j;return j},br=(t,j=0,s,i)=>{var o=xr(t,j,s,i);if(o-j>16&&t.buffer&&Br)return Br.decode(t.subarray(j,o));for(var k="";j<o;){var a=t[j++];if(!(a&128)){k+=String.fromCharCode(a);continue}var u=t[j++]&63;if((a&224)==192){k+=String.fromCharCode((a&31)<<6|u);continue}var c=t[j++]&63;if((a&240)==224?a=(a&15)<<12|u<<6|c:a=(a&7)<<18|u<<12|c<<6|t[j++]&63,a<65536)k+=String.fromCharCode(a);else{var C=a-65536;k+=String.fromCharCode(55296|C>>10,56320|C&1023)}}return k},Nt=(t,j,s)=>t?br(L,t,j,s):"",Bt=(t,j)=>{j=v(j);var s=!0;B(t,{name:j,fromWireType(i){var o=h[i>>2],k=i+4,a;if(s)a=Nt(k,o,!0);else{a="";for(var u=0;u<o;++u)a+=String.fromCharCode(L[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=gt(o):k=o.length;var u=RA(4+k+1),c=u+4;if(h[u>>2]=k,a)if(s)Lt(o,c,k+1);else for(var C=0;C<k;++C){var f=o.charCodeAt(C);f>255&&(J(u),G("String has UTF-16 code units that do not fit in 8 bits")),L[c+C]=f}else L.set(o,c);return i!==null&&i.push(J,u),u},readValueFromPointer:GA,destructorFunction(i){J(i)}})},Jr=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,xt=(t,j,s)=>{var i=t>>1,o=xr(Y,i,j/2,s);if(o-i>16&&Jr)return Jr.decode(Y.subarray(i,o));for(var k="",a=i;a<o;++a){var u=Y[a];k+=String.fromCharCode(u)}return k},bt=(t,j,s=2147483647)=>{if(s<2)return 0;s-=2;for(var i=j,o=s<t.length*2?s/2:t.length,k=0;k<o;++k){var a=t.charCodeAt(k);uA[j>>1]=a,j+=2}return uA[j>>1]=0,j-i},Jt=t=>t.length*2,Pt=(t,j,s)=>{for(var i="",o=t>>2,k=0;!(k>=j/4);k++){var a=h[o+k];if(!a&&!s)break;i+=String.fromCodePoint(a)}return i},Ot=(t,j,s=2147483647)=>{if(s<4)return 0;for(var i=j,o=i+s-4,k=0;k<t.length;++k){var a=t.codePointAt(k);if(a>65535&&k++,cA[j>>2]=a,j+=4,j+4>o)break}return cA[j>>2]=0,j-i},Ut=t=>{for(var j=0,s=0;s<t.length;++s){var i=t.codePointAt(s);i>65535&&s++,j+=4}return j},wt=(t,j,s)=>{s=v(s);var i,o,k;j===2?(i=xt,o=bt,k=Jt):(i=Pt,o=Ot,k=Ut),B(t,{name:s,fromWireType:a=>{var u=h[a>>2],c=i(a+4,u*j,!0);return J(a),c},toWireType:(a,u)=>{typeof u!="string"&&G(\`Cannot pass non-string to C++ string type \${s}\`);var c=k(u),C=RA(4+c+j);return h[C>>2]=c/j,o(u,C+4,c+j),a!==null&&a.push(J,C),C},readValueFromPointer:GA,destructorFunction(a){J(a)}})},Tt=(t,j)=>{j=v(j),B(t,{isVoid:!0,name:j,fromWireType:()=>{},toWireType:(s,i)=>{}})},Kt=t=>{kA("OOM")},St=t=>{var j=L.length;t>>>=0,Kt(t)},Mt=t=>52,Vt=9007199254740992,Rt=-9007199254740992,Wt=t=>t<Rt||t>Vt?NaN:Number(t);function Qt(t,j,s,i){return j=Wt(j),70}var zt=[null,[],[]],Xt=(t,j)=>{var s=zt[t];j===0||j===10?((t===1?x:aA)(br(s)),s.length=0):s.push(j)},Zt=(t,j,s,i)=>{for(var o=0,k=0;k<s;k++){var a=h[j>>2],u=h[j+4>>2];j+=8;for(var c=0;c<u;c++)Xt(t,L[a+c]);o+=u}return h[i>>2]=o,0};At(),ct();{r.noExitRuntime&&(Kj=r.noExitRuntime),r.print&&(x=r.print),r.printErr&&(aA=r.printErr),r.arguments&&(q=r.arguments),r.thisProgram&&(p=r.thisProgram);var Z=r.preInit;if(Z)for(typeof Z=="function"&&(r.preInit=Z=[Z]);Z.length>0;)Z.shift()()}var Pr,RA,J,Yt,Ae,Or,Ur;function re(t){Pr=t.w,RA=r._malloc=t.y,J=r._free=t.z,Yt=Or=t.u,Ae=Ur=t.x}var je={i:Vj,r:Rj,g:Qj,l:zj,k:ft,j:pt,d:Et,a:mt,s:Ft,f:vt,n:Dt,c:_t,b:yt,t:Bt,e:wt,m:Tt,o:St,q:Mt,p:Qt,h:Zt};async function te(){Bj();var t=r.setStatus;t&&(t("Running..."),await new Promise(j=>setTimeout(j,1)),setTimeout(t,1,"")),!or&&(xj(),r.onRuntimeInitialized?.(),bj())}var jA;return jA=await Tj(),await te(),r}})();typeof $j=="object"&&typeof OA=="object"?(OA.exports=nr,OA.exports.default=nr):typeof define=="function"&&define.amd&&define([],()=>nr)});var w={};ke(w,{AdditionalCaptureBlocks:()=>qe,AdditionalPlaybackBlocks:()=>de,ClockJumpCheckInterval:()=>he,ClockJumpThreshold:()=>$e,ConnectInterval:()=>Ne,ConnectTimeout:()=>He,DefaultRefreshRate:()=>fe,DefaultVideoCodec:()=>Be,HealthCheckTimeout:()=>me,MainConnectionPingInterval:()=>Fe,MaxNumberOfDecoders:()=>pe,MinDBFs:()=>Sr,MinTokenLifetime:()=>Le,MinTokenRefreshInterval:()=>ge,PlaybackPreload:()=>Ce,RenderQuantumSize:()=>Ee,VadPreload:()=>Ge,WebRtcAnswerTimeout:()=>_e,WebRtcIceTimeout:()=>ve,WebRtcMaxNegotiationAttempts:()=>ye,WebRtcStatsSnapshotInterval:()=>Ie,WebRtcTimeout:()=>De});var de=3,qe=3,Ce=3,fe=250,Ge=3,pe=512,Ee=128,Sr=-758.596,me=1e4,he=1e3,$e=1e4,Fe=3e3,Ie=1e3,ve=3e3,De=1e4,_e=1e4,ye=3,He=5e3,Le=6e4,ge=5e3,Ne=[0,100,200,200,500],Be="H264";function T(e,A,r){return e.postMessage(A,r)}function Mr(e){return[e.values[0],e.values[1]]}function hA(e,A){e.values[0]=A[0],e.values[1]=A[1]}function $A(e,A){return e.values[2+A*5]}function Vr(e,A,r){e.values[2+A*5]=r}function Rr(e,A){let r=2+A*5+1;return[e.values[r+0],e.values[r+1]]}function FA(e,A,r){let n=2+A*5+1;e.values[n+0]=r[0],e.values[n+1]=r[1]}function Wr(e,A){return e.values[2+A*5+3]}function Qr(e,A,r){e.values[2+A*5+3]=r}function zr(e,A){return e.values[2+A*5+4]}function Xr(e,A,r){e.values[2+A*5+4]=r}function IA(e){return e.values[0]!==0}function vA(e){return e.values[1]}function DA(e){return e.values[2]}function Zr(e){return e.values[3]}function _A(e,A){return e.values[3]=A}function Yr(e){return e?Array.from(e).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var xe;(e=>{let A;(r=>(r[r.InvalidPassword=-1]="InvalidPassword",r[r.Unknown=0]="Unknown",r[r.Unencrypted=1]="Unencrypted",r[r.Encrypted=2]="Encrypted"))(A=e.PeerCipherStatus||={})})(xe||={});function ej(e){return{type:"Success",value:e}}function g(e){return{type:"Failure",reason:e}}var{Deno:Aj}=globalThis,be=typeof Aj?.noColor=="boolean"?Aj.noColor:!1,Je=!be;function XA(e,A){return{open:\`\\x1B[\${e.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function ZA(e,A){return Je?\`\${A.open}\${e.replace(A.regexp,A.open)}\${A.close}\`:e}function zA(e){return ZA(e,XA([0],0))}function rj(e){return ZA(e,XA([1],22))}function Pe(e){return ZA(e,XA([2],22))}var Bn=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"),Oe=new Date,yA=(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))(yA||{}),nj={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},Ue={4:Pe,3:zA,2:zA,1:rj,0:rj};function we({message:e}){return String(e)}function jj(e){return JSON.stringify({timestamp:e.date.toISOString(),level:yA[e.level],message:e.message,extra:e.extra})}function tj(e){function A(q,p){return[Math.floor(q/p),q%p]}function r(){let q,p=e.date.valueOf()-Oe.valueOf();[p,q]=A(p,1e3);let[I,N]=A(p,60);return\`\${I.toString().padStart(4,"0")}:\${N.toString().padStart(2,"0")}.\${q.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 l=nj[e.level],d=e.logger.name!==void 0?\`@\${e.logger.name}\`:"";return\`\${zA(r())}\${d} \${l} \${Ue[e.level](String(e.message))}\${n()}\`}function Te(e){let A=\`[\${e.date.toISOString()}]\`,r=\`[\${yA[e.level]}]\`,n=e.logger.name!==void 0?\`[\${e.logger.name}] \`:"",l=nj[e.level];return\`\${A} \${l} \${r.padEnd(7," ")} \${n}\${e.message}\`}function Ke(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var sj=class{static sparse=we;static json=jj;static pretty=tj;static structured=Te;static default=Ke()?tj:jj;constructor(){}};var Se=class{formatter;consoleObject;filter;constructor(e=sj.default,A=4,r=console){this.filter=A,this.formatter=e,this.consoleObject=r}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 V=class{#A;sinks;filter;parent;get name(){return this.#A}constructor(e,A=void 0,r=[],n=void 0){this.#A=A,this.sinks=r,this.filter=e,this.parent=n}log(e,A,r=void 0){let n={date:new Date,level:e,logger:this,message:A,extra:r};this.filter<e||this.insert(n)}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)},eA=globalThis[Symbol.for("odin-global-logger")]??=new V(3,void 0,[new Se]),Me=V.prototype.log.bind(eA,1),Ve=V.prototype.log.bind(eA,2),lj=V.prototype.log.bind(eA,3),Re=V.prototype.log.bind(eA,4),xn=V.prototype.log.bind(eA);var ij;function oj(e,...A){let r=We(A);ij?ij?.info(e,r):lj(e,r)}function We(...e){if(e.length===1&&typeof e[0]=="object"&&e[0]!==null)return{...e[0]};if(e.length>0)return{args:e}}function HA(e){return e.connectionId*4294967296+e.mediaId}function aj(e){return{mediaId:e%4294967296,connectionId:Math.floor(e/4294967296)}}function O(e,A,r){let n;switch(A){case"f32":n=e.HEAPF32;break;case"u32":n=e.HEAPU32;break;case"i32":n=e.HEAP32;break;case"u8":n=e.HEAPU8;break;default:throw new Error(\`allocating \${A} is not supported\`)}let l=e._malloc(r*n.BYTES_PER_ELEMENT);if(l===0||l%n.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${r} \${A} array\`);let d=l/n.BYTES_PER_ELEMENT;return n.subarray(d,d+r)}function R(e,A){e._free(A.byteOffset)}function kj(e,A){return{values:O(e,"f32",2+A*5),length:A}}function uj(e,A){R(e,A.values)}function cj(e){return{values:O(e,"f32",4)}}function dj(e,A){R(e,A.values)}function qj(e){let A=e.length,r=0,n=0;for(;n<A;){let l=e.charCodeAt(n++);if((l&4294967168)===0){r++;continue}else if((l&4294965248)===0)r+=2;else{if(l>=55296&&l<=56319&&n<A){let d=e.charCodeAt(n);(d&64512)===56320&&(++n,l=((l&1023)<<10)+(d&1023)+65536)}(l&4294901760)===0?r+=3:r+=4}}return r}function Qe(e,A,r){let n=e.length,l=r,d=0;for(;d<n;){let q=e.charCodeAt(d++);if((q&4294967168)===0){A[l++]=q;continue}else if((q&4294965248)===0)A[l++]=q>>6&31|192;else{if(q>=55296&&q<=56319&&d<n){let p=e.charCodeAt(d);(p&64512)===56320&&(++d,q=((q&1023)<<10)+(p&1023)+65536)}(q&4294901760)===0?(A[l++]=q>>12&15|224,A[l++]=q>>6&63|128):(A[l++]=q>>18&7|240,A[l++]=q>>12&63|128,A[l++]=q>>6&63|128)}A[l++]=q&63|128}}var ze=new TextEncoder,Xe=50;function Ze(e,A,r){ze.encodeInto(e,A.subarray(r))}function Cj(e,A,r){e.length>Xe?Ze(e,A,r):Qe(e,A,r)}var Ye=4096;function YA(e,A,r){let n=A,l=n+r,d=[],q="";for(;n<l;){let p=e[n++];if((p&128)===0)d.push(p);else if((p&224)===192){let I=e[n++]&63;d.push((p&31)<<6|I)}else if((p&240)===224){let I=e[n++]&63,N=e[n++]&63;d.push((p&31)<<12|I<<6|N)}else if((p&248)===240){let I=e[n++]&63,N=e[n++]&63,UA=e[n++]&63,x=(p&7)<<18|I<<12|N<<6|UA;x>65535&&(x-=65536,d.push(x>>>10&1023|55296),x=56320|x&1023),d.push(x)}else d.push(p);d.length>=Ye&&(q+=String.fromCharCode(...d),d.length=0)}return d.length>0&&(q+=String.fromCharCode(...d)),q}var An=new TextDecoder,rn=200;function jn(e,A,r){let n=e.subarray(A,A+r);return An.decode(n)}function fj(e,A,r){return r>rn?jn(e,A,r):YA(e,A,r)}var W=class{constructor(A,r){this.type=A,this.data=r}};var D=class e extends Error{constructor(A){super(A);let r=Object.create(e.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}};function Gj(e,A,r){let n=r/4294967296,l=r;e.setUint32(A,n),e.setUint32(A+4,l)}function LA(e,A,r){let n=Math.floor(r/4294967296),l=r;e.setUint32(A,n),e.setUint32(A+4,l)}function gA(e,A){let r=e.getInt32(A),n=e.getUint32(A+4);return r*4294967296+n}function pj(e,A){let r=e.getUint32(A),n=e.getUint32(A+4);return r*4294967296+n}var tn=-1,en=4294967296-1,nn=17179869184-1;function sn({sec:e,nsec:A}){if(e>=0&&A>=0&&e<=nn)if(A===0&&e<=en){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e),r}else{let r=e/4294967296,n=e&4294967295,l=new Uint8Array(8),d=new DataView(l.buffer);return d.setUint32(0,A<<2|r&3),d.setUint32(4,n),l}else{let r=new Uint8Array(12),n=new DataView(r.buffer);return n.setUint32(0,A),LA(n,4,e),r}}function ln(e){let A=e.getTime(),r=Math.floor(A/1e3),n=(A-r*1e3)*1e6,l=Math.floor(n/1e9);return{sec:r+l,nsec:n-l*1e9}}function on(e){if(e instanceof Date){let A=ln(e);return sn(A)}else return null}function an(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 r=A.getUint32(0),n=A.getUint32(4),l=(r&3)*4294967296+n,d=r>>>2;return{sec:l,nsec:d}}case 12:{let r=gA(A,4),n=A.getUint32(0);return{sec:r,nsec:n}}default:throw new D(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${e.length}\`)}}function kn(e){let A=an(e);return new Date(A.sec*1e3+A.nsec/1e6)}var Ej={type:tn,encode:on,decode:kn};var K=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Ej)}register({type:A,encode:r,decode:n}){if(A>=0)this.encoders[A]=r,this.decoders[A]=n;else{let l=-1-A;this.builtInEncoders[l]=r,this.builtInDecoders[l]=n}}tryToEncode(A,r){for(let n=0;n<this.builtInEncoders.length;n++){let l=this.builtInEncoders[n];if(l!=null){let d=l(A,r);if(d!=null){let q=-1-n;return new W(q,d)}}}for(let n=0;n<this.encoders.length;n++){let l=this.encoders[n];if(l!=null){let d=l(A,r);if(d!=null){let q=n;return new W(q,d)}}}return A instanceof W?A:null}decode(A,r,n){let l=r<0?this.builtInDecoders[-1-r]:this.decoders[r];return l?l(A,r,n):new W(r,A)}};K.defaultCodec=new K;function un(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function nA(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):un(e)?new Uint8Array(e):Uint8Array.from(e)}var cn=100,dn=2048,NA=class e{constructor(A){this.entered=!1,this.extensionCodec=A?.extensionCodec??K.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??cn,this.initialBufferSize=A?.initialBufferSize??dn,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,r){if(r>this.maxDepth)throw new Error(\`Too deep objects in depth \${r}\`);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,r)}ensureBufferSizeToWrite(A){let r=this.pos+A;this.view.byteLength<r&&this.resizeBuffer(r*2)}resizeBuffer(A){let r=new ArrayBuffer(A),n=new Uint8Array(r),l=new DataView(r);n.set(this.bytes),this.view=l,this.bytes=n}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 n=qj(A);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),Cj(A,this.bytes,this.pos),this.pos+=n}encodeObject(A,r){let n=this.extensionCodec.tryToEncode(A,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(A))this.encodeArray(A,r);else if(ArrayBuffer.isView(A))this.encodeBinary(A);else if(typeof A=="object")this.encodeMap(A,r);else throw new Error(\`Unrecognized object: \${Object.prototype.toString.apply(A)}\`)}encodeBinary(A){let r=A.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(\`Too large binary: \${r}\`);let n=nA(A);this.writeU8a(n)}encodeArray(A,r){let n=A.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(\`Too large array: \${n}\`);for(let l of A)this.doEncode(l,r+1)}countWithoutUndefined(A,r){let n=0;for(let l of r)A[l]!==void 0&&n++;return n}encodeMap(A,r){let n=Object.keys(A);this.sortKeys&&n.sort();let l=this.ignoreUndefined?this.countWithoutUndefined(A,n):n.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 d of n){let q=A[d];this.ignoreUndefined&&q===void 0||(this.encodeString(d),this.doEncode(q,r+1))}}encodeExtension(A){if(typeof A.data=="function"){let n=A.data(this.pos+6),l=n.length;if(l>=4294967296)throw new Error(\`Too large extension object: \${l}\`);this.writeU8(201),this.writeU32(l),this.writeI8(A.type),this.writeU8a(n);return}let r=A.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(\`Too large extension object: \${r}\`);this.writeI8(A.type),this.writeU8a(A.data)}writeU8(A){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,A),this.pos++}writeU8a(A){let r=A.length;this.ensureBufferSizeToWrite(r),this.bytes.set(A,this.pos),this.pos+=r}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),Gj(this.view,this.pos,A),this.pos+=8}writeI64(A){this.ensureBufferSizeToWrite(8),LA(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(e,A){return new NA(A).encodeSharedRef(e)}function BA(e){return\`\${e<0?"-":""}0x\${Math.abs(e).toString(16).padStart(2,"0")}\`}var qn=16,Cn=16,xA=class{constructor(A=qn,r=Cn){this.hit=0,this.miss=0,this.maxKeyLength=A,this.maxLengthPerKey=r,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,r,n){let l=this.caches[n-1];A:for(let d of l){let q=d.bytes;for(let p=0;p<n;p++)if(q[p]!==A[r+p])continue A;return d.str}return null}store(A,r){let n=this.caches[A.length-1],l={bytes:A,str:r};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=l:n.push(l)}decode(A,r,n){let l=this.find(A,r,n);if(l!=null)return this.hit++,l;this.miss++;let d=YA(A,r,n),q=Uint8Array.prototype.slice.call(A,r,r+n);return this.store(q,d),d}};var rr="array",iA="map_key",hj="map_value",fn=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new D("The type of key must be string or number but "+typeof e)},jr=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let r=this.getUninitializedStateFromPool();r.type=rr,r.position=0,r.size=A,r.array=new Array(A)}pushMapState(A){let r=this.getUninitializedStateFromPool();r.type=iA,r.readCount=0,r.size=A,r.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 n=A;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(A.type===iA||A.type===hj){let n=A;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},lA=-1,tr=new DataView(new ArrayBuffer(0)),Gn=new Uint8Array(tr.buffer);try{tr.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 mj=new RangeError("Insufficient data"),pn=new xA,bA=class e{constructor(A){this.totalPos=0,this.pos=0,this.view=tr,this.bytes=Gn,this.headByte=lA,this.stack=new jr,this.entered=!1,this.extensionCodec=A?.extensionCodec??K.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:pn,this.mapKeyConverter=A?.mapKeyConverter??fn}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=lA,this.stack.reset()}setBuffer(A){let r=nA(A);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(A){if(this.headByte===lA&&!this.hasRemaining(1))this.setBuffer(A);else{let r=this.bytes.subarray(this.pos),n=nA(A),l=new Uint8Array(r.length+n.length);l.set(r),l.set(n,r.length),this.setBuffer(l)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:r,pos:n}=this;return new RangeError(\`Extra \${r.byteLength-n} of \${r.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 r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}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 r=!1,n;for await(let p of A){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(p);try{n=this.doDecodeSync(),r=!0}catch(I){if(!(I instanceof RangeError))throw I}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:l,pos:d,totalPos:q}=this;throw new RangeError(\`Insufficient data in parsing \${BA(l)} at \${q} (\${d} in the current buffer)\`)}finally{this.entered=!1}}decodeArrayStream(A){return this.decodeMultiAsync(A,!0)}decodeStream(A){return this.decodeMultiAsync(A,!1)}async*decodeMultiAsync(A,r){if(this.entered){yield*this.clone().decodeMultiAsync(A,r);return}try{this.entered=!0;let n=r,l=-1;for await(let d of A){if(r&&l===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(d),n&&(l=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--l!==0;);}catch(q){if(!(q instanceof RangeError))throw q}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){A:for(;;){let A=this.readHeadByte(),r;if(A>=224)r=A-256;else if(A<192)if(A<128)r=A;else if(A<144){let l=A-128;if(l!==0){this.pushMapState(l),this.complete();continue A}else r={}}else if(A<160){let l=A-144;if(l!==0){this.pushArrayState(l),this.complete();continue A}else r=[]}else{let l=A-160;r=this.decodeString(l,0)}else if(A===192)r=null;else if(A===194)r=!1;else if(A===195)r=!0;else if(A===202)r=this.readF32();else if(A===203)r=this.readF64();else if(A===204)r=this.readU8();else if(A===205)r=this.readU16();else if(A===206)r=this.readU32();else if(A===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(A===208)r=this.readI8();else if(A===209)r=this.readI16();else if(A===210)r=this.readI32();else if(A===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(A===217){let l=this.lookU8();r=this.decodeString(l,1)}else if(A===218){let l=this.lookU16();r=this.decodeString(l,2)}else if(A===219){let l=this.lookU32();r=this.decodeString(l,4)}else if(A===220){let l=this.readU16();if(l!==0){this.pushArrayState(l),this.complete();continue A}else r=[]}else if(A===221){let l=this.readU32();if(l!==0){this.pushArrayState(l),this.complete();continue A}else r=[]}else if(A===222){let l=this.readU16();if(l!==0){this.pushMapState(l),this.complete();continue A}else r={}}else if(A===223){let l=this.readU32();if(l!==0){this.pushMapState(l),this.complete();continue A}else r={}}else if(A===196){let l=this.lookU8();r=this.decodeBinary(l,1)}else if(A===197){let l=this.lookU16();r=this.decodeBinary(l,2)}else if(A===198){let l=this.lookU32();r=this.decodeBinary(l,4)}else if(A===212)r=this.decodeExtension(1,0);else if(A===213)r=this.decodeExtension(2,0);else if(A===214)r=this.decodeExtension(4,0);else if(A===215)r=this.decodeExtension(8,0);else if(A===216)r=this.decodeExtension(16,0);else if(A===199){let l=this.lookU8();r=this.decodeExtension(l,1)}else if(A===200){let l=this.lookU16();r=this.decodeExtension(l,2)}else if(A===201){let l=this.lookU32();r=this.decodeExtension(l,4)}else throw new D(\`Unrecognized type byte: \${BA(A)}\`);this.complete();let n=this.stack;for(;n.length>0;){let l=n.top();if(l.type===rr)if(l.array[l.position]=r,l.position++,l.position===l.size)r=l.array,n.release(l);else continue A;else if(l.type===iA){if(r==="__proto__")throw new D("The key __proto__ is not allowed");l.key=this.mapKeyConverter(r),l.type=hj;continue A}else if(l.map[l.key]=r,l.readCount++,l.readCount===l.size)r=l.map,n.release(l);else{l.key=null,l.type=iA;continue A}}return r}}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 D(\`Unrecognized array type byte: \${BA(A)}\`)}}}pushMapState(A){if(A>this.maxMapLength)throw new D(\`Max length exceeded: map length (\${A}) > maxMapLengthLength (\${this.maxMapLength})\`);this.stack.pushMapState(A)}pushArrayState(A){if(A>this.maxArrayLength)throw new D(\`Max length exceeded: array length (\${A}) > maxArrayLength (\${this.maxArrayLength})\`);this.stack.pushArrayState(A)}decodeString(A,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(A,r):this.decodeBinary(A,r)}decodeUtf8String(A,r){if(A>this.maxStrLength)throw new D(\`Max length exceeded: UTF-8 byte length (\${A}) > maxStrLength (\${this.maxStrLength})\`);if(this.bytes.byteLength<this.pos+r+A)throw mj;let n=this.pos+r,l;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?l=this.keyDecoder.decode(this.bytes,n,A):l=fj(this.bytes,n,A),this.pos+=r+A,l}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===iA:!1}decodeBinary(A,r){if(A>this.maxBinLength)throw new D(\`Max length exceeded: bin length (\${A}) > maxBinLength (\${this.maxBinLength})\`);if(!this.hasRemaining(A+r))throw mj;let n=this.pos+r,l=this.bytes.subarray(n,n+A);return this.pos+=r+A,l}decodeExtension(A,r){if(A>this.maxExtLength)throw new D(\`Max length exceeded: ext length (\${A}) > maxExtLength (\${this.maxExtLength})\`);let n=this.view.getInt8(this.pos+r),l=this.decodeBinary(A,r+1);return this.extensionCodec.decode(l,n,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=pj(this.view,this.pos);return this.pos+=8,A}readI64(){let A=gA(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 er(e,A){return new bA(A).decode(e)}var oA=class e{constructor(A,r,n,l,d){this.mediaIds=A;this.sequenceNumber=r;this.timeStamp=n;this.isEndOfSpurt=l;this.payload=d}static parse(A){let r;try{r=er(A)}catch{return g("not valid msgpack")}if(!Array.isArray(r))return g("container must be an array");if(r.length<6)return g("missing fields");if(r[0]!==1)return g("unknown type");if(!Array.isArray(r[1]))return g("media ids must be an array");if(!r[1].every(N=>typeof N=="number"))return g("media ids must be numbers");if(typeof r[2]!="number")return g("sequence number must be a number");if(typeof r[3]!="number")return g("timestamp must be a number");if(typeof r[4]!="number")return g("flags must be a number");let n=r[1],l=r[2]>>>0,d=r[3]>>>0,p=(r[4]&1)!==0,I=r[r.length-1];return I instanceof Uint8Array?ej(new e(n,l,d,p,I)):g("payload must be bytes")}toBytes(){let A=Number(this.isEndOfSpurt),r=[1,this.mediaIds,this.sequenceNumber>>>0,this.timeStamp>>>0,A,this.payload];return new Uint8Array(Ar(r,{forceFloat32:!0,ignoreUndefined:!0}))}};var JA=class{constructor(A,r){this.sampleRate=A;this.wasm=r;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 r.Encoder(A,15,!0,w.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=cj(this.wasm),this.outBuffer=O(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:r})=>r.length>0)}close(){dj(this.wasm,this.information),R(this.wasm,this.outBuffer),this.encoder.delete()}encode(A){for(this.encoder.push(A.byteOffset,this.information.values.byteOffset);;){let r=this.encoder.pop(this.connections.length===0?0:this.outBuffer.byteOffset,this.outBuffer.length);if(r===0)break;if(r<0){oj(\`failed encoding packet: \${r}\`);return}if(this.timestamp=this.timestamp+1800>>0,r===1)continue;this.sequenceNumber=this.sequenceNumber+1>>0;let n=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 d=new oA(l.mediaIds,this.sequenceNumber,this.timestamp,n,this.outBuffer.subarray(0,r));T(globalThis,["sendPacket",{connectionId:l.id,packet:d.toBytes()}])}}}onMessage(A){let[r,n]=A;switch(r){case"captureSetVad":this?.setVad(n);break;case"captureSetMedias":this?.setMedias(n.connections);break;case"close":this.close();break;case"dump":n.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:IA(this.information),speechProbability:vA(this.information),rmsDBFS:DA(this.information),volume:Zr(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}}}},PA=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=O(this.wasm,"u32",w.MaxNumberOfDecoders),this.information=kj(this.wasm,w.MaxNumberOfDecoders),hA(this.information,[1,1])}close(){uj(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,r){this.stats.numberPackets++;let n=oA.parse(r);if(n.type==="Failure"){this.stats.numberPacketError++;let l=Array.from(r).map(d=>d.toString(16).padStart(2,"0")).join("");console.error(\`failed decoding audio packet; reason: \${n.reason}, connection: \${A}, dump: \${l}\`);return}for(let l of n.value.mediaIds){let d=this.medias.get(HA({connectionId:A,mediaId:l}));if(d===void 0){this.stats.numberPacketsMediaNotFound++;continue}d.lastPacket=r;let q=O(this.wasm,"u8",n.value.payload.length);q.set(n.value.payload),d.decoder.push(n.value.sequenceNumber,n.value.timeStamp,n.value.isEndOfSpurt,q.byteOffset,q.length)}}insertMedia(A,r,n,l=[1,1]){let d=HA({connectionId:r,mediaId:n}),q=new this.wasm.Decoder;this.medias.set(d,{index:A,decoder:q,lastPacket:void 0}),this.decoders[A]=q.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),FA(this.information,A,l),Xr(this.information,A,0),Qr(this.information,A,0)}removeMedia(A,r,n){let l=HA({connectionId:r,mediaId:n}),d=this.medias.get(l);if(!(d===void 0||d.index!==A)&&(this.medias.delete(l),Vr(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[r,n]=A;switch(r){case"playbackReceivePacket":this.receivePacket(n.connectionId,n.packet);break;case"playbackUpdateMedias":for(let{index:l,connectionId:d,mediaId:q}of n.removed)this.removeMedia(l,d,q);for(let{index:l,connectionId:d,mediaId:q,volume:p}of n.added)this.insertMedia(l,d,q,p);break;case"close":this.close();break;case"dump":n.result.postMessage(this.dump());break}}dump(){let A=[];for(let[r,n]of this.medias){let l=aj(r);A.push({index:n.index,connectionId:l.connectionId,mediaId:l.mediaId,rmsDBFS:$A(this.information,n.index),volume:Rr(this.information,n.index),voicedBlocks:zr(this.information,n.index),silentBlocks:Wr(this.information,n.index),time:n.decoder.time,consecutive_silence:n.decoder.consecutive_silence,last_voiced_time_point:n.decoder.last_voiced_time_point,sequence_number:n.decoder.sequence_number,packetsSeen:n.decoder.packets_seen,packetsInvalid:n.decoder.packets_invalid,packetsTooLate:n.decoder.packets_too_late,packetsTooEarly:n.decoder.packets_too_early,packetsRepeated:n.decoder.packets_repeated,packetsProcessed:n.decoder.packets_processed,packetsLost:n.decoder.packets_lost,rewinds:n.decoder.rewinds,voiceAccelerated:n.decoder.voice_accelerated,silenceAccelerated:n.decoder.silence_accelerated,cacheLength:n.decoder.cache_length,lastPacket:Yr(n.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:Mr(this.information),decoders:A}}};var _j=ce(Fj()),Ij=(0,_j.default)(),vj,Dj;globalThis.addEventListener("message",sr);async function sr(e){let A=e.data,[r,n]=A;switch(r){case"captureInit":n.workletPort.onmessage=sr,vj=new lr(n.sampleRate,await Ij,n.refreshRate);break;case"playbackInit":n.workletPort.onmessage=sr,Dj=new ir(await Ij,n.workletPort,n.refreshRate);break;case"close":globalThis.close();break}vj?.onMessage(A),Dj?.onMessage(A)}var lr=class extends JA{constructor(r,n,l){super(r,n);this.sampleRate=r;this.inBuffer=O(this.wasm,"f32",r*.02),this.updateHandle=setInterval(()=>this.update(),l),T(globalThis,["captureReady",{}])}close(){super.close(),R(this.wasm,this.inBuffer),clearInterval(this.updateHandle)}onMessage(r){super.onMessage(r);let[n,l]=r;switch(n){case"captureSetVolume":this.setVolume(l.value);break;case"captureTick":this.tick(l.buffer);break}}setVolume(r){_A(this.information,r)}tick(r){this.inBuffer.set(r,0),this.encode(this.inBuffer)}update(){T(globalThis,["captureUpdate",{active:IA(this.information),rmsDBFs:DA(this.information),speechProbability:vA(this.information)}])}dump(){return{type:"unshared capture worker",sampleRate:this.sampleRate,...super.dump()}}},ir=class extends PA{constructor(r,n,l){super(r);this.workletPort=n;this.id=w.PlaybackPreload,this.outBuffer=O(this.wasm,"f32",48e3*.02*2),this.updateHandle=setInterval(()=>this.update(),l),T(globalThis,["playbackReady",{}])}close(){super.close(),R(this.wasm,this.outBuffer),clearInterval(this.updateHandle)}onMessage(r){super.onMessage(r);let[n,l]=r;switch(n){case"playbackSetVolume":this.setVolume(l.index,l.value);break;case"playbackTick":this.tick();break}}setVolume(r,n){r==="global"?hA(this.information,n):FA(this.information,r,n)}tick(){this.stats.numberTicks++,this.id+=1;let{hasAudio:r}=this.decode(this.outBuffer);if(r){let n=this.outBuffer.slice();T(this.workletPort,["samples",{id:this.id,buffer:n}],[n.buffer])}}update(){let r=new Float32Array(this.information.length*2);for(let l=0;l<=this.largestIndex;l++)r[l]=$A(this.information,l);let n=[];for(let[l,d]of this.medias)n[d.index]={packetsBuffered:d.decoder.cache_length,packetsSeen:d.decoder.packets_seen,packetsProcessed:d.decoder.packets_processed,packetsTooEarly:d.decoder.packets_too_early,packetsTooLate:d.decoder.packets_too_late,packetsDropped:d.decoder.voice_accelerated,packetsInvalid:d.decoder.packets_invalid,packetsRepeated:d.decoder.packets_repeated,packetsLost:d.decoder.packets_lost};T(globalThis,["playbackUpdate",{activities:r,jitterStats:n}],[r.buffer])}dump(){return{type:"unshared playback worker",id:this.id,...super.dump()}}};})();
6456
- `});var Yx,_0=m(()=>{Yx='"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:()=>G,DefaultRefreshRate:()=>C,DefaultVideoCodec:()=>Y,HealthCheckTimeout:()=>O,MainConnectionPingInterval:()=>W,MaxNumberOfDecoders:()=>L,MinDBFs:()=>v,MinTokenLifetime:()=>Z,MinTokenRefreshInterval:()=>q,PlaybackPreload:()=>F,RenderQuantumSize:()=>V,VadPreload:()=>D,WebRtcAnswerTimeout:()=>J,WebRtcIceTimeout:()=>$,WebRtcMaxNegotiationAttempts:()=>z,WebRtcStatsSnapshotInterval:()=>j,WebRtcTimeout:()=>H});var R=3,E=3,F=3,C=250,D=3,L=512,V=128,v=-758.596,O=1e4,_=1e3,N=1e4,W=3e3,j=1e3,$=3e3,H=1e4,J=1e4,z=3,G=5e3,Z=6e4,q=5e3,Q=[0,100,200,200,500],Y="H264";function d(e,t,r){return e.postMessage(t,r)}var K;(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||={})})(K||={});var{Deno:k}=globalThis,X=typeof k?.noColor=="boolean"?k.noColor:!1,ee=!X;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 ee?`${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 te(e){return h(e,m([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"),re=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}"},ne={4:te,3:p,2:p,1:U,0:U};function se({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()-re.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} ${ne[e.level](String(e.message))}${n()}`}function oe(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 ae(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var w=class{static sparse=se;static json=S;static pretty=I;static structured=oe;static default=ae()?I:S;constructor(){}};var ie=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 ie]),ce=o.prototype.log.bind(l,1),ue=o.prototype.log.bind(l,2),le=o.prototype.log.bind(l,3),fe=o.prototype.log.bind(l,4),Ie=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 L0={};Tx(L0,{UnsharedCaptureWorker:()=>sx,UnsharedPlaybackWorker:()=>ix,createCaptureWorker:()=>vF,createPlaybackWorker:()=>CF});import{Strand as jF}from"@4players/odin-common";function vF(v,t,e,j,B=i.DefaultRefreshRate){return BF.enqueue(async()=>{let[C,E]=await Y(Zx,Yx,v,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return console.warn("SharedArrayBuffer is not available; creating ODIN CaptureWorker in fallback mode"),sx.create(v,t,e,B,C,E,j)})}async function CF(v,t=i.DefaultRefreshRate){if(v.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[e,j]=await Y(Zx,Yx,v,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return ix.create(v,t,e,j)}var BF,sx,ix,H0=m(()=>{"use strict";u();nx();g0();_0();BF=new jF;sx=class v extends X{constructor(e,j,B,C,E){super(e,j,B,C,E);this._Activity=_;this._SpeechProbability=0;j.addEventListener("message",this._OnMessages.bind(this))}static async create(e,j,B,C,E,f,s){let{port1:b,port2:d}=new MessageChannel;return c(E,["captureInit",{sampleRate:e.sampleRate,refreshRate:C,workletPort:b}],[b]),await V(E,"captureReady"),c(f.port,["init",{workerPort:d}],[d]),new v(f,E,j,B,s)}get activity(){return this._Activity}get speechProbability(){return this._SpeechProbability}setVolume(e){c(this.worker,["captureSetVolume",{value:e}])}_OnMessages(e){super._OnMessages(e);let[j,B]=e.data;j==="captureUpdate"&&(this._Activity={isSilent:!B.active,rmsDBFS:B.rmsDBFs},this._SpeechProbability=B.speechProbability)}},ix=class v extends z{constructor(e,j,B){super(e,j,B);this.activities=new Float32Array;this.jitterStats=[]}static async create(e,j,B,C){let{port1:E,port2:f}=new MessageChannel;return c(B,["playbackInit",{workletPort:E,refreshRate:j}],[E]),await V(B,"playbackReady"),c(C.port,["init",{workerPort:f}],[f]),new v(e,C,B)}getActivity(e){let j=this.medias.get(q(e));if(j===void 0)return;let B=this.activities.at(j.index);if(B!==void 0)return B===0?_:{isSilent:!1,rmsDBFS:B}}getJitterStats(e){let j=this.medias.get(q(e));if(j===void 0)return;let B=this.jitterStats.at(j.index);if(B!==void 0)return B}setGlobalVolume(e){c(this.worker,["playbackSetVolume",{index:"global",value:e}])}setVolume(e,j){let B=this.medias.get(q(e));B!==void 0&&c(this.worker,["playbackSetVolume",{index:B.index,value:j}])}_GetFreeIndex(){let e=super._GetFreeIndex();if(e!==void 0)return e;if(this.medias.size<i.MaxNumberOfDecoders)return this.medias.size}_OnMessages(e){super._OnMessages(e);let[j,B]=e.data;j==="playbackUpdate"&&(this.activities=B.activities,this.jitterStats=B.jitterStats)}}});u();import{Backend as r,generateUUID as cr}from"@4players/odin-common";u();import{Backend as x,JITTER_STATS_INITIAL as J0,Strand as oF,assert as aF}from"@4players/odin-common";u();import{APM_DEFAULTS as nF,Backend as hB,generateUUID as sF,VAD_DEFAULTS as iF}from"@4players/odin-common";import{failure as p0,isFirefoxBrowser as KA,sleep as VA,success as WA}from"@4players/odin-common";async function h0(v,t,e){let j;if(t.device?.device.kind==="track"&&t.device?.device.audioTrack)j=new MediaStream([t.device.device.audioTrack]);else{let E=t.device?{exact:t.device.device.deviceId==="default"?void 0:t.device.device.deviceId}:void 0;try{let f=await Promise.race([navigator.mediaDevices.getUserMedia({audio:{echoCancellation:e.echoCanceller,noiseSuppression:e.noiseSuppression!=="None",autoGainControl:e.gainController,echoCancellationType:"system",deviceId:E}}),VA(3e4,"timeout")]);if(f==="timeout")return p0("getUserMedia; timeout");j=f}catch(f){return p0(`getUserMedia; ${f}`)}}let B=j.getAudioTracks()[0].getSettings().sampleRate,C=await v.audioContexts.acquire(B);return WA(C.createMediaStreamSource(j))}function W(v){v.getTracks().forEach(t=>{t.stop(),v.removeTrack(t)})}async function m0(v){return new L({deviceId:v.id,kind:"track",name:v.label??"MediaStreamTrack",audioTrack:v},!1)}async function fx(){if(KA()){let B=await QA("microphone");(B==="granted"||B===!1)&&await zA("audio")}let v=(await navigator.mediaDevices.enumerateDevices()).filter(B=>!!B.label),t=[],e=new L({deviceId:"default",name:"Default",kind:"audioinput"},!0),j=new L({deviceId:"default",name:"Default",kind:"audiooutput"},!0);t.push(e),t.push(j);for(let B of v){if(B.deviceId==="default"){B.kind==="audioinput"&&(e=new L({deviceId:"default",name:B.label,kind:"audioinput"},!0),t[0]=e),B.kind==="audiooutput"&&(j=new L({deviceId:"default",name:B.label,kind:"audiooutput"},!0),t[1]=j);continue}B.kind==="audioinput"&&t.push(new L({deviceId:B.deviceId,name:B.label,kind:"audioinput"},!1)),B.kind==="audiooutput"&&t.push(new L({deviceId:B.deviceId,name:B.label,kind:"audiooutput"},!1))}return t}async function QA(v){try{return(await navigator.permissions.query({name:v})).state}catch{return!1}}async function zA(v){try{let t=await navigator.mediaDevices.getUserMedia({[v]:!0});return t?.getTracks().forEach(e=>{e.stop(),t.removeTrack(e)}),!0}catch{return!1}}u();import{isSafariBrowser as EF,isSharedArrayBufferCapable as fF}from"@4players/odin-common";var P0=fF()&&!EF()?Promise.resolve().then(()=>(I0(),y0)):Promise.resolve().then(()=>(H0(),L0));async function N0(v,t,e,j){return P0.then(B=>B.createCaptureWorker(v,t,e,j,i.DefaultRefreshRate))}async function w0(v){return P0.then(t=>t.createPlaybackWorker(v,i.DefaultRefreshRate))}var N=class{constructor(t,e){this.controller=t;this._Medias=new Map;this._Vad={...iF};this._Apm={...nF};this._Volume=1;this._Queue=Promise.resolve();this._DeviceCb=()=>{this._enqueue(async()=>{!this._DeviceParameters?.device||(await fx()).some(B=>B.device.deviceId===this._DeviceParameters?.device?.device.deviceId)||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())}).catch(t=>k("device-change handler failed",t))};e.apm&&this.setApm(e.apm).catch(console.error),e.vad&&this.setVad(e.vad),typeof e.volume<"u"&&this.setVolume(e.volume).catch(console.error),this.uid=sF(),this.#x=e.customType,this.#A=e.ref}#x;#A;_enqueue(t){let e=this._Queue.then(t,t);return this._Queue=e.catch(()=>{}),e}get vad(){return this._Vad}get apm(){return this._Apm}get volume(){return this._Volume}get activity(){return this._Capture?.worker.activity??_}get speechProbability(){return this._Capture?.worker.speechProbability??0}get deviceId(){return this._DeviceParameters?.device?.device.deviceId}async start(t,e){let j=this._Medias.get(e.connectionId);j===void 0&&this._Medias.set(e.connectionId,j=new Set),o(`starting audio capture media ${e.mediaId} on connection ${e.connectionId}`),!j.has(e.mediaId)&&(j.add(e.mediaId),t.mainConnection?.id===e.connectionId&&await t.request("StartMedia",{media_id:e.mediaId,properties:{kind:"audio",uid:this.uid,ref:this.#A,customType:this.#x}}).catch(B=>p(`StartMedia got rejected; ${B}`)),this._UpdateMedias())}async stop(t,e){let j=this._Medias.get(e.connectionId);o(`stopping audio capture media ${e.mediaId} on connection ${e.connectionId}`),j?.delete(e.mediaId)&&(t.mainConnection?.id===e.connectionId&&await t.request("StopMedia",{media_id:e.mediaId}).catch(B=>p(`StopMedia got rejected; ${B}`)),this._UpdateMedias())}setVad(t){a("updating vad config",t),this._Vad=t,this._Capture&&this._Capture.worker.setVad(t)}async setApm(t){await this._enqueue(()=>this._setApmImpl(t))}async _setApmImpl(t){a("updating apm config",t),this._Apm=t,this._DeviceParameters&&await this._setDeviceImpl(this._DeviceParameters)}async setDevice(t){await this._enqueue(()=>this._setDeviceImpl(t))}async _setDeviceImpl(t){a("updating capture device parameters",t);let e=this._DeviceParameters;if(this._DeviceParameters=t,this._Volume!=="muted")try{let j=await h0(this.controller,t,{...this._Apm,echoCanceller:this._Monitor?!1:this._Apm.echoCanceller});if(j.type!=="Success"){p(`unable to open capture device; ${j.reason}`),this._DeviceParameters=e;return}if(this._DeviceParameters.onStatusChanged&&navigator.mediaDevices.addEventListener("devicechange",this._DeviceCb),this._Capture!==void 0){W(this._Capture.source.mediaStream);try{this._Capture.source.disconnect(this._Capture.worker.worklet)}catch(B){k("failed to disconnect previous capture source",B)}}this._Capture===void 0||this._Capture.worker.worklet.context!==j.value.context?(this._Capture?.worker.close(),this._Capture={worker:await N0(j.value.context,this.controller.sink,this.controller.receiveMonitoredPacket.bind(this.controller),new WeakRef(this)),source:j.value},await this._UpdateMedias(),this._Capture.worker.setVolume(this._Volume),this.setVad(this.vad)):this._Capture.source=j.value,this._Capture.source.connect(this._Capture.worker.worklet)}catch(j){throw new Error(`Error in setDevice(); ${j}`)}}async setVolume(t){await this._enqueue(()=>this._setVolumeImpl(t))}async _setVolumeImpl(t){a(`updating capture volume to ${t}`),this._Volume=t,t==="muted"?await this._closeImpl():(!this._Capture&&this._DeviceParameters&&await this._setDeviceImpl(this._DeviceParameters),this._Capture?.worker.setVolume(t))}async close(){await this._enqueue(()=>this._closeImpl())}async _closeImpl(){if(a("closing audio capture"),this._Capture!==void 0){this._Capture.worker.close(),W(this._Capture.source.mediaStream);try{this._Capture.source.disconnect(this._Capture.worker.worklet)}catch(t){k("failed to disconnect audio node",t)}await this.controller.audioContexts.release(this._Capture.source.context)}navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._Capture=void 0}async dump(){let t=[];for(let[e,j]of this._Medias)t.push(`${e} => ${Array.from(j.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:t}}async _UpdateMedias(){if(this._Capture!==void 0){let t=Array.from(this._Medias).map(([e,j])=>({id:e,mediaIds:Array.from(j)}));this._Capture.worker.setMedias(t)}}async startLoopback(){this._Monitor===void 0&&(a("starting audio capture loopback"),this.setApm(this._Apm),this._Monitor=await this.controller.createAudioPlayback({uid:"loopback"}),this._Monitor.start({connectionId:0,mediaId:0}),this._Medias.set(0,new Set([0])),await this._UpdateMedias())}async stopLoopback(){this._Monitor!==void 0&&(a("stopping audio capture loopback"),this._Monitor.close(),this._Monitor=void 0,this.setApm(this._Apm),this._Medias.delete(0),await this._UpdateMedias())}};import{assert as bx,Backend as D,generateUUID as bF}from"@4players/odin-common";u();var I=class{constructor(t,e){this.controller=t;this.parameters=e;this.uid=bF()}#x;#A=new Map;#F;get customType(){return this.parameters?.customType}get mediaStream(){return this.#x}get audioCapture(){return this.#F}get volume(){return bx(this.audioCapture,"getting the volume failed, this video has no Audio"),this.audioCapture.volume}async setVolume(t){bx(this.audioCapture,"setVolume() failed, this video has no Audio"),await this.audioCapture.setVolume(t)}get vad(){return bx(this.audioCapture,"getting the vad config failed, this video has no Audio"),this.audioCapture.vad}setVad(t){bx(this.audioCapture,"setVad() failed, this video has no Audio"),this.audioCapture.setVad(t)}async setDevice(t,e={voiceActivity:void 0,volumeGate:void 0}){if(this.#x)throw new Error("This VideoCapture already has a MediaStream.");if(!t.getVideoTracks()[0])throw new Error("Error when calling setDevice(), MediaStream does not contain a VideoStreamTrack!");if(this.#x=t,t.getAudioTracks()[0]){let B={device:await m0(t.getAudioTracks()[0]),vad:e,ref:this.uid};this.#F=await this.controller.createAudioCapture(B)}}async start(t,e){let j=this.#A.get(e.connectionId);if(j===void 0&&this.#A.set(e.connectionId,j=new Set),!j.has(e.mediaId)&&(j.add(e.mediaId),t.mainConnection?.id===e.connectionId)){let B={kind:"video",codec:this.parameters?.codec??i.DefaultVideoCodec,ref:this.#F?.uid,uid:this.uid};this.parameters?.customType&&(B.customType=this.parameters.customType),await t.request("StartMedia",{media_id:e.mediaId,properties:B}).catch(C=>p(`StartMedia got rejected; ${C}`))}}async stop(t,e){this.#x&&W(this.#x),this.#A.get(e.connectionId)?.delete(e.mediaId)&&t.mainConnection?.id===e.connectionId&&await t.request("StopMedia",{media_id:e.mediaId}).catch(B=>p(`StopMedia got rejected; ${B}`))}async dump(){let t=[];for(let[e,j]of this.#A)t.push(`${e} => ${Array.from(j.values()).join(",")}`);return{uid:this.uid,ref:this.#F?.uid??null,customType:this.customType??null,tracks:this.#x?.getVideoTracks().map(e=>({id:e.id,kind:e.kind,label:e.label,ready:e.readyState,muted:e.muted,settings:{...e.getSettings()}}))??[],volume:this.#F?.volume??0,medias:t}}close(){this.#x&&W(this.#x),this.audioCapture?.close(),this.#F=void 0}};u();import{Backend as mB}from"@4players/odin-common";var H=class{constructor(t,e,j){this.controller=t;this.uid=e;this.customType=j}get volume(){return this.controller.playbackGetVolume(this.uid)}get activity(){return this.controller.playbackGetActivity(this.uid)}get jitterStats(){return this.controller.playbackGetJitterStats(this.uid)}start(t){o(`starting audio playback media ${t.mediaId} on connection ${t.connectionId}`),this.controller.playbackStart(this.uid,t)}stop(t){o(`stopping audio playback media ${t.mediaId} on connection ${t.connectionId}`),this.controller.playbackStop(this.uid,t)}setVolume(t){a(`updating audio playback media '${this.uid}' volume to ${t}`),this.controller.playbackSetVolume(this.uid,t)}close(){a(`closing audio playback media '${this.uid}'`),this.controller.closePlayback(this.uid)}};function lF(v,t){let e=v.audioContext;if(typeof e.setSinkId=="function"){v.connectOutput(e.destination);let j,B=()=>{if(e.state==="running"&&j!==void 0){let C=j;j=void 0,e.setSinkId(C).catch(E=>k("failed to apply deferred sinkId",E))}};return e.addEventListener("statechange",B),{async setSinkId(C){if(e.state!=="running"){j=C;return}await e.setSinkId(C)},dispose(){e.removeEventListener("statechange",B)}}}if(t&&typeof document<"u"&&typeof HTMLAudioElement<"u"&&typeof HTMLAudioElement.prototype.setSinkId=="function"){let j=e.createMediaStreamDestination();v.connectOutput(j);let B=new Audio;B.srcObject=j.stream,B.muted=!1,B.volume=1;let C=!1,E=!1,f={once:!0,passive:!0,capture:!0},s=()=>{E=!1,h()},b=()=>{E||C||(E=!0,document.addEventListener("pointerdown",s,f),document.addEventListener("keydown",s,f))},d=()=>{E&&(E=!1,document.removeEventListener("pointerdown",s,!0),document.removeEventListener("keydown",s,!0))},h=()=>{C||B.play().catch(Dx=>{C||(Dx instanceof DOMException&&Dx.name==="NotAllowedError"?b():k("failed to start playback audio element",Dx))})},Bx=()=>{e.state==="running"&&B.paused&&h()};return e.addEventListener("statechange",Bx),h(),{async setSinkId(Dx){await B.setSinkId(Dx)},dispose(){C=!0,d(),e.removeEventListener("statechange",Bx),B.pause(),B.srcObject=null,B.removeAttribute("src");try{B.load()}catch{}j.disconnect()}}}return v.connectOutput(e.destination),{async setSinkId(){},dispose(){}}}var ox=class{constructor(t){this.audioContextFactory=t;this.entries=[]}async acquire(t){for(let j of this.entries){if(j.sampleRate===t)return j.references+=1,j.audioContext;if(j.sampleRate===void 0&&j.audioContext.sampleRate===t)return j.references+=1,j.audioContext}let e={sampleRate:t,audioContext:await this.audioContextFactory(t),references:1};return this.entries.push(e),e.audioContext}async release(t){let e=this.entries.findIndex(j=>j.audioContext===t);if(!(e<0)&&(this.entries[e].references-=1,this.entries[e].references<=0)){let j=this.entries[e].audioContext;this.entries.splice(e,1),await j.close()}}close(){for(let t of this.entries)t.audioContext.close()}},ax=class v{constructor(t,e,j=!1){this.audioContexts=t;this.sink=e;this.enableHTMLAudioElementFallback=j;this.audioCaptures=[];this.videoCaptures=[];this.globalVolume=[1,1];this.playbacks=new Map;this.setPlaybackStrand=new oF}async create(t,e){return new v(t,e)}receivePacket(t,e){this.playbackWorker?.receivePacket(t,e)}receiveMonitoredPacket(t,e){let j=e.slice();this.receivePacket(t,j)}async createAudioPlayback(t){let e=this.playbacks.get(t.uid),j=t.volume;if(e===void 0){j=j??[1,1];let B=new H(this,t.uid,t.customType);e={id:void 0,volume:j,playback:B},this.playbacks.set(t.uid,e)}return j!==void 0&&e.playback.setVolume(j),e.playback}async createAudioCapture(t){let e=new N(this,t);return await e.setDevice(t),this.audioCaptures.push(new WeakRef(e)),e}async createVideoCapture(t,e){let j=new I(this,e);return await j.setDevice(t),this.videoCaptures.push(new WeakRef(j)),j}playbackSetDevice(t){return this.setPlaybackStrand.enqueue(async()=>{let e=t?.device.deviceId??"";if(e==="default"&&(e=""),this.playbackWorker===void 0){let j=await this.audioContexts.acquire(48e3);this.playbackWorker=await w0(j),this.playbackSink=lF(this.playbackWorker,this.enableHTMLAudioElementFallback),this.playbackWorker.setGlobalVolume(this.globalVolume);for(let[,B]of this.playbacks)B.id!==void 0&&this.playbackWorker.addMedias(B.id.connectionId,[B.id.mediaId],B.volume)}if(t&&this.playbackSink!==void 0)try{await this.playbackSink.setSinkId(e)}catch(j){k("failed to set playback sink",j)}})}playbackSetGlobalVolume(t){this.globalVolume=t,this.playbackWorker?.setGlobalVolume(this.globalVolume)}playbackStart(t,e){let j=this.playbacks.get(t);j!==void 0&&(j.id!==void 0&&this.playbackStop(t,j.id),j.id=e,this.playbackWorker?.addMedias(e.connectionId,[e.mediaId],j.volume))}playbackStop(t,e){let j=this.playbacks.get(t);j!==void 0&&(j.id!==e&&k(`playback media ${e.mediaId} on connection ${e.connectionId} is out of sync`,j.id,e),j.id=void 0,this.playbackWorker?.removeMedias(e.connectionId,[e.mediaId]))}playbackGetActivity(t){let e=this.playbacks.get(t);return e?.id===void 0?_:this.playbackWorker?.getActivity(e.id)??_}playbackGetJitterStats(t){let e=this.playbacks.get(t);return e?.id===void 0?J0:this.playbackWorker?.getJitterStats(e.id)??J0}playbackSetVolume(t,e){let j=this.playbacks.get(t);j!==void 0&&(j.volume=e,j.id!==void 0&&this.playbackWorker?.setVolume(j.id,j.volume))}playbackGetVolume(t){return this.playbacks.get(t)?.volume??[1,1]}closePlayback(t){let e=this.playbacks.get(t);e!==void 0&&(e.id!==void 0&&this.playbackStop(t,e.id),this.playbacks.delete(t))}close(){this.playbackSink?.dispose(),this.playbackSink=void 0,this.playbackWorker?.close(),this.audioContexts.close()}async dump(){let t=[];for(let B of this.audioCaptures){let C=B.deref();C!==void 0&&t.push(await C.dump())}let e=[];for(let B of this.videoCaptures){let C=B.deref();C!==void 0&&e.push(await C.dump())}let j=[];for(let[B,C]of this.playbacks)j.push({uid:B,id:C.id||null,volume:C.volume});return{globalVolume:this.globalVolume,playbackWorker:await this.playbackWorker?.dump()||null,audioCaptures:t,videoCaptures:e,playbacks:j}}},L=class{constructor(t,e=!1){this.device=t;this.isDefault=e}get type(){switch(this.device.kind){case"audioinput":return"AudioCapture";case"audiooutput":return"AudioPlayback";default:aF(!1,"not supported device")}}get id(){return this.device.deviceId}get name(){return this.device.name}};u();import{nextTick as WF,success as xA}from"@4players/odin-common";import{decode as QF}from"@msgpack/msgpack";u();import{Backend as qB}from"@4players/odin-common";u();import{Backend as A,failure as kx,success as K0,CONNECTION_STATS_INITIAL as gF}from"@4players/odin-common";import{MainCommandsRpc as _F,MainNotificationsRpc as LF,RoomCommandsRpc as HF,RoomNotificationsRpc as PF}from"@4players/odin-common/api";u();import{failure as x0,success as A0}from"@4players/odin-common";import{MessagePackRpcSchema as uF,parseRequest as O0,parseResponse as kF}from"@4players/odin-common/api";import{encode as cF,decode as dF}from"@msgpack/msgpack";var U=class{constructor(t){this.stream=t;this._SendQueue=[];this._RecvQueue=[];this._EventQueue=[];this._Requests=new Map;this._Close=new AbortController;this._NextId=1;t instanceof WebSocket?(t.addEventListener("open",this._OnWebSocketOpen.bind(this)),t.addEventListener("close",this.close.bind(this)),t.addEventListener("message",e=>this._OnRpcMessage(e.data)),t.binaryType="arraybuffer"):(hF(t.readable.getReader(),this._OnRpcMessage.bind(this)).finally(this.close.bind(this)),this._Writer=t.writable.getWriter()),this._Close.signal.addEventListener("abort",this._Cleanup.bind(this),{once:!0})}get closed(){return this._Close.signal.aborted}get closeSignal(){return this._Close.signal}async request(t,e,j){if(this.closed)return Promise.resolve("closed");let B=this._NextId,C=j===void 0?void 0:setTimeout(()=>this._TimeoutRequest(B),j);return this._Send([0,B,t,e]),new Promise(E=>{this._Requests.set(B,{accept:E,timeoutId:C}),this._NextId+=1})}notify(t,e){this.closed||this._Send([2,t,e])}recv(){if(this.closed)return Promise.resolve("closed");let t=this._EventQueue.shift();return t!==void 0?Promise.resolve(t):new Promise(e=>this._RecvQueue.push(e))}close(){this._Close.abort()}_TimeoutRequest(t){let e=this._Requests.get(t);e!==void 0&&(this._Requests.delete(t),clearTimeout(e.timeoutId),e.accept("timeout"))}_Send(t){let e;t instanceof Uint8Array?e=t:e=new Uint8Array(cF(t,{ignoreUndefined:!0,forceFloat32:!0})),this.stream instanceof WebSocket?this.stream.send(e):this._Writer.write(e)}_OnWebSocketOpen(t){for(let e of this._SendQueue)this._Send(e);this._SendQueue.length=0}_OnRpcMessage(t){let e=pF(t);if(e.type!=="Success"){this.close();return}switch(e.value[0]){case 0:this._Send([1,e.value[1],"not supported",null]);break;case 1:this._OnResponse(e.value[1],e.value[2],e.value[3]);break;case 2:this._OnEvent(e.value[1],e.value[2]);break}}_OnResponse(t,e,j){let B=this._Requests.get(t);B!==void 0&&(clearTimeout(B.timeoutId),B.accept(e===null?A0(j):x0(e)))}_OnEvent(t,e){let j=this._RecvQueue.shift();j!==void 0?j({name:t,properties:e}):this._EventQueue.push({name:t,properties:e})}_Cleanup(){for(let t of this._Requests.values())clearTimeout(t.timeoutId),t.accept("closed");this._Requests.clear();for(let t of this._RecvQueue)t("closed");this._RecvQueue.length=0,this._SendQueue.length=0,this.stream instanceof WebSocket?this.stream.close():this._Writer?.close().catch(()=>{})}},K=class{constructor(t,e,j){this.rpc=t;this._Commands=e;this._Events=j}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(t,e,j){e=O0(t,e,this._Commands);let B=await this.rpc.request(t,e,j);if(B==="closed"||B==="timeout"||B.type==="Failure")return B;let C=kF(t,B.value,this._Commands);return C!==void 0?A0(C):x0("response schema failed validation")}notify(t,e){e=O0(t,e,this._Commands),this.rpc.notify(t,e)}async recv(){let t=await this.rpc.recv();if(t==="closed")return t;let e=F0(this._Events,t);return e!==void 0?e:(S0(this._Events,t.name)?(p(`schema validation for ${t.name} failed; closing connection`),this.rpc.close()):k(`dropping unknown event ${t.name}`),"closed")}close(){this.rpc.close()}};function pF(v){try{return A0(uF.parse(dF(new Uint8Array(v))))}catch(t){return x0(String(t))}}function F0(v,t){if(!S0(v,t.name))return;let e=v[t.name].safeParse(t.properties);if(e.success)return{name:t.name,properties:e.data}}function S0(v,t){return t in v}async function hF(v,t){let e=new Uint8Array;for(;;){let j=a0(e,0);if(j===n){v.cancel("protocol violation");break}if(j!==$&&j<=e.length){t(e.subarray(0,j)),e=e.subarray(j);continue}let B;try{B=await v.read()}catch{break}if(B.done)break;e=mF(e,B.value)}e.length>0&&k("unprocessed bytes left in rpc stream",e)}function mF(v,t){if(v.length===0)return t;if(t.length===0)return v;let e=new Uint8Array(v.length+t.length);return e.set(v,0),e.set(t,v.length),e}u();import{failure as lx,fromBase64Url as qF,success as GF}from"@4players/odin-common";import{TokenClaimsSchema as $F}from"@4players/odin-common/api";var g=class v{constructor(t,e){this.text=t;this.claims=e;if(e.ups!==void 0){let j=v.parse(e.ups);j.type==="Success"?this._Upstream=j.value:p(`upstream in token can not be parsed; ${j.reason}`)}}static parse(t){let e=t.split(".");if(e.length!==3)return lx("expected three segments");let j=qF(e[1]);if(j.type==="Failure")return lx(`invalid token; ${j.reason}`);let B;try{B=JSON.parse(j.value)}catch(E){return lx(`invalid token; ${E}`)}let C=$F.safeParse(B);return C.success===!1?lx(`invalid token; ${C.error}`):GF(new v(t,C.data))}get timeLeft(){return this.claims.exp===void 0?1/0:this.claims.exp*1e3-Date.now()}get upstream(){return this._Upstream}get defaultRoomId(){return Array.isArray(this.claims.rid)?this.claims.rid.length===1?this.claims.rid[0]:void 0:this.claims.rid}hasAudience(t){return this.claims.aud===void 0&&t==="gateway"?!0:Array.isArray(this.claims.aud)?this.claims.aud.includes(t):this.claims.aud===t}toString(){return this.text}};u();import{VideoCodec as yF,assert as U0}from"@4players/odin-common";function T0(v){typeof globalThis.rtcDataChannels>"u"&&(globalThis.rtcDataChannels=[]),Array.isArray(globalThis.rtcDataChannels)&&globalThis.rtcDataChannels.length<=100&&globalThis.rtcDataChannels.push(v)}function M0(v){let t=globalThis.rtcDataChannels?.indexOf(v);t!==void 0&&t>=0&&globalThis.rtcDataChannels.splice(t,1),v.readyState!=="closed"&&v.close()}function ux(v){typeof globalThis.rtcPeerConnections>"u"&&(globalThis.rtcPeerConnections=[]),Array.isArray(globalThis.rtcPeerConnections)&&globalThis.rtcPeerConnections.length<=100&&globalThis.rtcPeerConnections.push(v)}function R0(v){let t=globalThis.rtcPeerConnections?.indexOf(v);t!==void 0&&t>=0&&globalThis.rtcPeerConnections.splice(t,1),v.connectionState!=="closed"&&v.close()}var xx=class{constructor(t,e,j){this._localVideos=new Map;this._remoteVideos=new Map;this._freeLocalVideoTransceivers=[];this._negotiationRequested=!1;this._negotiationRunning=!1;this._negotiationCounter=0;this._pendingRemoteCandidates=[];this._WebRtcStatsSnapshot=null;this._peerConnection=t,this._signaling=e,this._answerTimeout=j?.answerTimeout??i.WebRtcAnswerTimeout,this._maxNegotiationAttempts=j?.maxNegotiationAttempts??i.WebRtcMaxNegotiationAttempts,this._peerConnection.ontrack=this._onTrack.bind(this),this._peerConnection.onconnectionstatechange=()=>this._onStatusChanged(),this._peerConnection.onicecandidate=B=>{(B.candidate?this._signaling.sendIceCandidate(B.candidate):this._signaling.sendIceComplete()).catch(E=>{k("failed to send local ice candidate",E)})},this._WebRtcStatsInterval=setInterval(()=>{this._snapshotStats()},i.WebRtcStatsSnapshotInterval)}requestNegotiation(){this._negotiationRequested=!0,!this._negotiationRunning&&(this._negotiationRunning=!0,setTimeout(async()=>{let t=0;for(;this._negotiationRequested;){this._negotiationRequested=!1;try{await this._negotiate(),t=0}catch(e){if(t+=1,p(`negotiation failed during sdp offer/answer exchange (attempt ${t})`,e),t<this._maxNegotiationAttempts)this._negotiationRequested=!0;else{this._negotiationRunning=!1,this._signaling.closeConnection().catch(()=>{});return}}}this._negotiationRunning=!1}))}async startLocalVideo(t,e,j){if(this._localVideos.has(t))return;o(`starting local video for media ${t}`);let B=this._freeLocalVideoTransceivers.pop();if(B?(await B.sender.replaceTrack(e),B.direction="sendrecv"):B=this._peerConnection.addTransceiver(e),j){let f=B.sender.getParameters(),{maxBitrate:s,maxFramerate:b,scaleResolutionDownBy:d}=j,h={...s!==void 0&&{maxBitrate:s},...b!==void 0&&{maxFramerate:b},...d!==void 0&&{scaleResolutionDownBy:d}};if(f.encodings.length===0)f.encodings.push(h);else for(let Bx of f.encodings)Object.assign(Bx,h);j.degradationPreference&&(f.degradationPreference=j.degradationPreference),await B.sender.setParameters(f)}let E=new yF(j?.codec??i.DefaultVideoCodec).isSupported();E&&B.setCodecPreferences([E]),this._localVideos.set(t,{transceiver:B}),this.requestNegotiation()}stopLocalVideo(t){let e=this._localVideos.get(t);e&&(o(`stopping local video for media ${t}`),this._localVideos.delete(t),e.transceiver.sender.track&&(e.transceiver.sender.track.enabled=!1),e.transceiver.direction="inactive",e.transceiver.sender.replaceTrack(null).catch(()=>{}),this._freeLocalVideoTransceivers.push(e.transceiver),this.requestNegotiation())}startRemoteVideo(t){o(`starting remote video for media ${t}`);let e=this._peerConnection.addTransceiver("video",{direction:"recvonly"}),j=new Promise((B,C)=>{this._remoteVideos.set(t,{state:"Requested",transceiver:e,promise:{resolve:B,reject:C}})});return this.requestNegotiation(),j}stopRemoteVideo(t){let e=this._remoteVideos.get(t);if(e){o(`stopping remote video for media ${t}`),this._remoteVideos.delete(t),e.state!=="Active"&&e.promise.reject(new Error("video stopped"));try{e.transceiver.stop()}catch{}this.requestNegotiation()}}async handleWebRtcUpdate(t){try{switch(t.kind){case"Sdp":await this._updateRemoteSdp(t.type==="Answer"?"answer":"offer",t.sdp,t.media_map,t.negotiation_id);break;case"Trickle":this._addIceCandidate({candidate:t.candidate,sdpMid:t.spd_mid??void 0,sdpMLineIndex:t.spd_mline_index??void 0,usernameFragment:t.username_fragment??void 0});break;case"TrickleFinished":this._addIceCandidate(void 0);break}}catch(e){p("failed to handle webrtc update",e,t)}}startup(){this._peerConnection.connectionState==="new"&&this.requestNegotiation()}cleanup(){for(let[,t]of this._remoteVideos)t.state!=="Active"&&t.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 t=await this._peerConnection.getStats(),e={},j={bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,rtt:0};t.forEach(B=>{let{type:C,...E}=B;C!=="certificate"&&(C==="candidate-pair"&&B.nominated&&(j.bytesSent+=B.bytesSent??0,j.bytesReceived+=B.bytesReceived??0,j.packetsSent+=B.packetsSent??0,j.packetsReceived+=B.packetsReceived??0,j.rtt=B.currentRoundTripTime??0),e[C]||(e[C]=[]),e[C].push(E))}),this._WebRtcStatsSnapshot={timestamp:Date.now(),status:this._peerConnection.connectionState,stats:j,report:e}}catch{}}_addIceCandidate(t){if(t&&(t.sdpMid===void 0&&t.sdpMLineIndex===void 0&&(t={...t,sdpMid:"0"}),a(`adding new ice ${t.candidate}`,t)),this._peerConnection.remoteDescription===null){this._pendingRemoteCandidates.push(t);return}this._applyIceCandidate(t)}_applyIceCandidate(t){this._peerConnection.addIceCandidate(t).catch(e=>{k("failed to add remote ice candidate",e,t)})}_flushPendingIceCandidates(){let t=this._pendingRemoteCandidates.splice(0);for(let e of t)this._applyIceCandidate(e)}async _negotiate(){let t=++this._negotiationCounter,e=await this._peerConnection.createOffer();U0(e.type==="offer"&&e.sdp,"generated broken payload"),await this._peerConnection.setLocalDescription(e);let j=[];for(let[C,{transceiver:E}]of this._localVideos)E.mid&&j.push([C,E.mid]);for(let[C,E]of this._remoteVideos)E.state!=="Active"&&E.transceiver.mid&&j.push([C,E.transceiver.mid]);let B=new Promise((C,E)=>{this._pendingAnswer={negotiationId:t,resolve:C,reject:E}});try{await this._signaling.sendOffer(e.sdp,j,t),await IF(B,this._answerTimeout,`timed out waiting for answer to offer ${t}`)}finally{this._pendingAnswer=void 0}}async _updateRemoteSdp(t,e,j,B){if(t==="offer"){k("ignoring unexpected sdp offer from server");return}let C=this._pendingAnswer;if(C===void 0){k("ignoring sdp answer without pending negotiation");return}if(B!==void 0&&B!==C.negotiationId){k(`ignoring stale sdp answer for negotiation ${B}; current is ${C.negotiationId}`);return}if(this._peerConnection.signalingState!=="have-local-offer"){k(`ignoring sdp answer in signaling state ${this._peerConnection.signalingState}`);return}for(let[E,f]of j){let s=this._remoteVideos.get(E);s?.state==="Requested"&&(this._remoteVideos.set(E,{state:"Mapped",transceiver:s.transceiver,mid:f,promise:s.promise}),a(`updated remote video list with media ${E}`,s,this._remoteVideos))}try{await this._peerConnection.setRemoteDescription({type:t,sdp:e})}catch(E){C.reject(E);return}this._flushPendingIceCandidates(),C.resolve()}async _onStatusChanged(){switch(a(`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":i.MainConnectionPingInterval!==void 0&&await this._signaling.checkConnection();default:this._WebRtcIceTimeout===void 0&&(this._WebRtcIceTimeout=setTimeout(()=>{a("ice connection timeout was reached"),this._peerConnection.restartIce(),this._WebRtcIceTimeout=void 0},i.WebRtcIceTimeout)),this._WebRtcTimeout===void 0&&(this._WebRtcTimeout=setTimeout(async()=>{a("peer connection timeout was reached"),await this._signaling.closeConnection()},i.WebRtcTimeout));break}}_onTrack(t){let e=Array.from(this._remoteVideos).find(([,C])=>C.state==="Mapped"&&C.mid===t.transceiver.mid);if(!e){k(`unexpected track with mid: ${t.transceiver.mid}`);return}let[j,B]=e;U0(B.state==="Mapped","expected video state to be Mapped"),this._remoteVideos.set(j,{state:"Active",transceiver:t.transceiver}),a(`updated local video list with media ${j}`,e,t.transceiver,this._localVideos),t.track.onended=()=>{a(`video track with mid ${t.transceiver.mid} ended`,e)},B.promise.resolve(t.track)}};function IF(v,t,e){return new Promise((j,B)=>{let C=setTimeout(()=>B(new Error(e)),t);v.then(E=>{clearTimeout(C),j(E)},E=>{clearTimeout(C),B(E)})})}var cx=class v{constructor(t,e,j,B,C,E,f){this.id=t;this.address=e;this.connection=B;this.datagramWritable=C;this.rpc=E;this.closeController=f;this._ConnectionStats={...gF};this._WebRtcSessionFlight=new M;this._PingFlight=new M;this.status=0;this._ClosePromise=(async()=>{try{await this.connection.closed}catch{}return"closed"})(),i.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(i.HealthCheckTimeout)},i.MainConnectionPingInterval)),f.signal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this.datagramWriter=C.getWriter(),this.connection.closed.then(()=>{this.status=2}).catch(()=>{}),this.connection.ready.then(()=>{this.status=1}).catch(()=>{}),this.readDatagrams(this.connection,this.id,(s,b)=>{this._ConnectionStats.packetsReceived+=1,j(s,b)})}static async create(t,e,j,B){try{let C=new URL(`https://${e}?version=${u0}&uid=${dx}`),E=new AbortController;B.addEventListener("abort",()=>E.abort(),{once:!0});let f=new WebTransport(C);E.signal.addEventListener("abort",()=>{try{f.close()}catch{}},{once:!0}),await f.ready;let s=f.datagrams,b=s?.createWritable?.()??s?.writable;if(!b)return E.abort(),kx(`connecting to ${e} failed because WebTransport datagrams are not supported by this browser`);let d=await f.createBidirectionalStream(),h=new K(new U(d),_F,LF);return E.signal.addEventListener("abort",()=>h.close(),{once:!0}),h.notify("Hello",{stream:"main"}),K0(new v(t,e,j,f,b,h,E))}catch(C){return kx(`connecting to ${e} failed with ${C}`)}}get connectionStats(){return this._ConnectionStats}get transport(){return"H3"}get closePromise(){return this._ClosePromise}get closeSignal(){return this.closeController.signal}get closed(){return this.closeSignal.aborted}waitForConnected(){return Promise.race([this.connection.ready,this.connection.closed.then(()=>{throw new Error("connection closed")})])}close(){o(`closing connection to '${this.address}' with id ${this.id}`),this.closeController.abort("request")}async joinRoom(t,e,j,B){try{if(this.closed)return"closed";let C=await this.connection.createBidirectionalStream().catch(()=>"closed");if(C==="closed")return"closed";let E=new K(new U(C),HF,PF),f=await E.request("Hello",{stream:"room",token:String(t),room_id:e,user_data:j,position:B});return f==="closed"||f.type==="Failure"?f:K0(E.rpc)}catch(C){return kx(`JoinRoom failed; ${C}`)}}async getReconnectToken(t){let e=await this._Request("RequestReconnectToken",{peer_id:t});return e.type==="Failure"?e:g.parse(e.value)}async getRtcStats(){return this._PeerConnection?.getStats()}async healthCheck(){let t=await this._RequestPing(i.HealthCheckTimeout);return t||this.close(),t}async ping(t=3e4){let e=Date.now();return await this._RequestPing(t)?Date.now()-e:0}sendDatagram(t){try{this.datagramWriter.write(t),this._ConnectionStats.packetsSent+=1;let e=t.byteLength;this.connectionStats.bytesSent+=e}catch{}}async readDatagrams(t,e,j){try{let B=t.datagrams.readable.getReader();for(;;){let C=await B.read();if(C.done)break;let E=C.value.byteLength;this.connectionStats.bytesReceived+=E,j(e,C.value)}}catch{}}_CleanUp(){a(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId)}async _EnsureWebRtcSession(){return this._WebRtcSession?this._WebRtcSession:this._WebRtcSessionFlight.run(async()=>(this._PeerConnection=new RTCPeerConnection,ux(this._PeerConnection),this._WebRtcSession=new xx(this._PeerConnection,{sendOffer:async(t,e,j)=>{let B=await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:t,media_map:e,negotiation_id:j});if(B.type==="Failure")throw new Error(`failed to send sdp offer; ${B.reason}`)},sendIceCandidate:async t=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:t.candidate,spd_mid:t.sdpMid??void 0,spd_mline_index:t.sdpMLineIndex??void 0,username_fragment:t.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async()=>{this._PeerConnection?.restartIce(),this._WebRtcSession?.requestNegotiation()},checkConnection:async()=>{}}),this._HandleWebRtcUpdates(),this._WebRtcSession))}async _HandleWebRtcUpdates(){for(;;){let t=await this.rpc.recv();if(t==="closed")break;t.name==="WebRtcUpdate"&&this._WebRtcSession?.handleWebRtcUpdate(t.properties)}this.close()}async _Request(t,e,j){let B=Date.now(),C=await(j===void 0?this.rpc.request(t,e):this.rpc.request(t,e,j)),E=(Date.now()-B)/1e3;return t!=="Ping"&&a(`sent main rpc '${t}'; took: ${E}s`,{properties:e,timeout:j,result:C}),C==="closed"?kx("connection lost"):C}_RequestPing(t=3e4){return this._PingFlight.run(async()=>{let e=await this._Request("Ping",{},t);return e!=="timeout"&&e.type==="Success"})}async startLocalVideo(t,e,j){await(await this._EnsureWebRtcSession()).startLocalVideo(t,e,j)}stopLocalVideo(t){this._WebRtcSession?.stopLocalVideo(t)}async startRemoteVideo(t){return(await this._EnsureWebRtcSession()).startRemoteVideo(t)}stopRemoteVideo(t){this._WebRtcSession?.stopRemoteVideo(t)}async dump(){return{type:"H3",id:this.id,address:this.address,closed:this.closed,status:this.status,datagrams:{sent:this._ConnectionStats.packetsSent,received:this._ConnectionStats.packetsReceived},webRtc:{signalingState:this._PeerConnection?.signalingState??null,connectionState:this._PeerConnection?.connectionState??null,iceGatheringState:this._PeerConnection?.iceGatheringState??null,iceConnectionState:this._PeerConnection?.iceConnectionState??null,connectionStats:this._WebRtcSession?.stats??null}}}};u();import{Backend as F,extendUrl as W0,failure as px,success as Q0,fail as SF,CONNECTION_STATS_INITIAL as UF}from"@4players/odin-common";import{MainCommandsRpc as TF,MainNotificationsRpc as MF}from"@4players/odin-common/api";u();import{abortableSleep as NF,failure as tx,success as wF}from"@4players/odin-common";async function r0(v,t){let e=performance.now(),j=tx("no connection was attempted");for(let B=0;B<i.ConnectInterval.length&&!t.aborted;B++){let C=e+OF(B);if(await NF(C-performance.now(),t)==="aborted")return tx("aborted");if(j=await JF(v,t),j.type==="Success")return j}return j}async function JF(v,t){let e;try{e=new WebSocket(v)}catch(s){return tx(`unable to create websocket; ${s}`)}let j=new AbortController,B=new Promise(s=>e.addEventListener("open",()=>s(wF(e)),{signal:j.signal})),C=new Promise(s=>e.addEventListener("close",b=>s(tx(b.reason!==""?b.reason:"unable to establish websocket connection")),{signal:j.signal})),E=new Promise(s=>t.addEventListener("abort",()=>s(tx("aborted")),{signal:j.signal})),f=await Promise.race([B,C,E]);return j.abort(),f}function OF(v){let t=i.ConnectInterval.slice(0,v).reduce((j,B)=>j+B,0),e=i.ConnectInterval[v]*Math.random();return t+e}var hx=class v{constructor(t,e,j,B,C,E){this.id=t;this.address=e;this.url=j;this.onDatagram=B;this.connection=C;this.webRtc=E;this._PeerIdMap=new WeakMap;this._ConnectionStats={...UF};this._PingFlight=new M;o(`creating new webrtc connection to '${this.address}' with id ${this.id}`),this.closeSignal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this._ClosePromise=new Promise(f=>{this.closeSignal.addEventListener("abort",()=>{f("closed")},{once:!0})}),ux(E),this._AudioChannel=this.webRtc.createDataChannel("audio",{id:2,negotiated:!0,ordered:!1,maxRetransmits:0}),this._AudioChannel.binaryType="arraybuffer",this._AudioChannel.onmessage=f=>{this._ConnectionStats.packetsReceived++;let s=new Uint8Array(f.data);this._ConnectionStats.bytesReceived+=s.byteLength,this.onDatagram(this.id,s)},this._AudioChannel.onerror=f=>k(`webrtc audio data channel for connection with id ${t} raised an error`,f),this._AudioChannel.onclosing=f=>o(`webrtc audio data channel for connection with id ${t} begins shutting down`,f),this._AudioChannel.onclose=f=>o(`webrtc audio data channel for connection with id ${t} has closed`,f),T0(this._AudioChannel),this._WebRtcSession=new xx(this.webRtc,{sendOffer:async(f,s,b)=>{let d=await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:f,media_map:s,negotiation_id:b});if(d.type==="Failure")throw new Error(`failed to send sdp offer; ${d.reason}`)},sendIceCandidate:async f=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:f.candidate,spd_mid:f.sdpMid??void 0,spd_mline_index:f.sdpMLineIndex??void 0,username_fragment:f.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async()=>{this.close()},checkConnection:async()=>{this.healthCheck().then()}}),this._WebRtcSession.startup(),i.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(i.HealthCheckTimeout)},i.MainConnectionPingInterval)),this._HandleWebRtcUpdates()}static async create(t,e,j,B){if(B.aborted)return px("aborted");let C;try{C=new URL(`wss://${e}`)}catch(b){return SF(`address in token(${e}) can not be parsed; ${b}`)}let E=W0(C,`main?uid=${dx}`);if(E.type!=="Success")return E;let f=await r0(E.value,B);if(f.type!=="Success")return f;let s=new K(new U(f.value),TF,MF);try{return Q0(new v(t,e,C,j,s,new RTCPeerConnection))}catch(b){return s.close(),px(`unable to create webrtc connection; ${b}`)}}get status(){switch(this.webRtc.connectionState){case"connected":return 1;case"failed":case"closed":return 2;default:return 0}}get connectionStats(){return this._ConnectionStats}get transport(){return"WebRTC"}get closePromise(){return this._ClosePromise}get closeSignal(){return this.connection.closeSignal}get closed(){return this.connection.closed}async waitForConnected(){return new Promise((t,e)=>{let j=()=>{let B=this.status;B!==0&&(this.webRtc.removeEventListener("connectionstatechange",j),B===1?t():e(new Error("connection closed")))};this.webRtc.addEventListener("connectionstatechange",j),j(),this.closePromise.then(()=>{e(new Error("connection closed"))})})}close(){o(`closing ${this.transport} connection to '${this.address}' with id ${this.id}`),this.connection.close()}async joinRoom(t,e,j,B){let C=await this.connection.request("JoinRoom",{token:String(t),room_id:e,user_data:j,position:B});if(C==="closed"||C.type==="Failure")return C;let E=C.value;if(!("token"in E))return px("JoinRoom responded without token");let f=W0(this.url,`room?token=${E.token}`);if(f.type==="Failure")return f;let s=await r0(f.value,this.closeSignal);return s.type==="Success"?(this._PeerIdMap.set(s.value,E.peer_id),Q0(new U(s.value))):s}async getReconnectToken(t){let e=await this._Request("RequestReconnectToken",{peer_id:t});return e.type==="Failure"?e:g.parse(e.value)}async getRtcStats(){return this.webRtc.getStats()}async healthCheck(){let t=await this._RequestPing(i.HealthCheckTimeout);return t||this.close(),t}async ping(t=3e4){let e=Date.now();return await this._RequestPing(t)?Date.now()-e:0}sendDatagram(t){if(this._AudioChannel.readyState==="open"){let e=t.byteLength;this._AudioChannel.send(t),this._ConnectionStats.packetsSent+=1,this._ConnectionStats.bytesSent+=e}}_CleanUp(){a(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId),M0(this._AudioChannel),R0(this.webRtc),this._WebRtcSession.cleanup(),this.connection.close()}async _HandleWebRtcUpdates(){for(;;){let t=await this.connection.recv();if(t==="closed")break;t.name==="WebRtcUpdate"&&this._WebRtcSession.handleWebRtcUpdate(t.properties)}this.close()}async _Request(t,e,j){let B=Date.now(),C=await(j===void 0?this.connection.request(t,e):this.connection.request(t,e,j)),E=(Date.now()-B)/1e3;return t!=="Ping"&&a(`sent main rpc '${t}'; took: ${E}s`,{properties:e,timeout:j,result:C}),C==="closed"?px("connection lost"):C}_RequestPing(t=3e4){return this._PingFlight.run(async()=>{let e=await this._Request("Ping",{},t);return e!=="timeout"&&e.type==="Success"})}async startLocalVideo(t,e,j){await this._WebRtcSession.startLocalVideo(t,e,j)}stopLocalVideo(t){this._WebRtcSession.stopLocalVideo(t)}async startRemoteVideo(t){return this._WebRtcSession.startRemoteVideo(t)}stopRemoteVideo(t){this._WebRtcSession.stopRemoteVideo(t)}async dump(){return{type:"WebRtc",id:this.id,address:this.address,url:this.url.toString(),closed:this.closed,audioChannel:{readyState:this._AudioChannel.readyState,bufferedAmount:this._AudioChannel.bufferedAmount},datagrams:{sent:this.connectionStats.packetsSent,received:this.connectionStats.packetsReceived},webRtc:{signalingState:this.webRtc.signalingState,connectionState:this.webRtc.connectionState,iceGatheringState:this.webRtc.iceGatheringState,iceConnectionState:this.webRtc.iceConnectionState,connectionStats:this._WebRtcSession.stats}}}};function z0(v,t,e,j,B){switch(o(`creating ${t} main connection to '${e}'`),t){case"H3":return cx.create(v,e,j,B);case"WebRTC":return hx.create(v,e,j,B);default:throw new Error(`transport ${t} is not supported`)}}import{Backend as GB,failure as Y0,success as RF}from"@4players/odin-common";import{parseCommand as KF,parseNotification as VF,RoomCommandsRpc as X0,RoomNotificationsRpc as Z0}from"@4players/odin-common/api";u();var mx=class{constructor(t,e,j,B){this.id=t;this.connection=e;this.cipher=j;this.mediaMap=B;this._DatagramReceived=0;this._DatagramSent=0;this._DatagramReceivedInvalid=0;this._DatagramSentInvalid=0;e.closeSignal.addEventListener("abort",()=>this.close())}get connectionStats(){return this.connection.connectionStats}get transport(){return this.connection.transport}get address(){return this.connection.address}get status(){return this.closed?2:this.connection.status}get closePromise(){return this.connection.closePromise}get closeSignal(){return this.connection.closeSignal}get closed(){return this.connection.closed}waitForConnected(){return this.connection.waitForConnected()}close(){this.connection.close()}async joinRoom(t,e,j,B){this.cipher.reset();let C=await this.cipher.encryptUserData(j);if(C===n)return Y0("unable to encrypt initial user-data");let E=await this.connection.joinRoom(t,e,C,B);return E==="closed"||E.type==="Failure"?E:RF(new D0(E.value,this.cipher,this))}getReconnectToken(t){return this.connection.getReconnectToken(t)}getRtcStats(){return this.connection.getRtcStats()}healthCheck(){return this.connection.healthCheck()}async sendDatagram(t){let e=await this.cipher.encryptDatagram(t);e!==n?(this._DatagramSent+=1,this.connection.sendDatagram(e)):this._DatagramSentInvalid+=1}async decryptDatagram(t,e){let j=await this.cipher.decryptDatagram(t,e);return j!==n?this._DatagramReceived+=1:this._DatagramReceivedInvalid+=1,j}startLocalVideo(t,e,j){return this.connection.startLocalVideo(t,e,j)}stopLocalVideo(t){return this.connection.stopLocalVideo(t)}startRemoteVideo(t){return this.connection.startRemoteVideo(t)}stopRemoteVideo(t){return this.connection.stopRemoteVideo(t)}async dump(){return{type:"Encrypted",id:this.id,address:this.address,connectionId:this.connection.id,closed:this.closed,transport:this.transport,datagrams:{sent:this._DatagramSent,received:this._DatagramReceived,sentInvalid:this._DatagramSentInvalid,receivedInvalid:this._DatagramReceivedInvalid},cipher:await this.cipher.dump()}}},qx=class{constructor(t){this.room=t}resendUserData(){this.room.roomConnection?.notify("UpdatePeer",{user_data:this.room.roomConnection.userData})}setUserData(t,e){let j={kind:"UserDataChanged",peer_id:t,user_data:e};this.room.onEvent("PeerUpdated",j)}},D0=class{constructor(t,e,j){this.rpc=t;this.cipher=e;this.connection=j;this.peers=new Map;this.closeSignal.addEventListener("abort",this.cleanup.bind(this),{once:!0})}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(t,e,j){let B=await this.outgoing(t,e);return B===n?Y0("can not be encrypted"):await this.rpc.request(t,B,j)}async notify(t,e){let j=await this.outgoing(t,e);if(j!==n)return this.rpc.notify(t,j)}async recv(){for(;;){let t=await this.rpc.recv();if(t==="closed")return t;let e=await this.incoming(t.name,t.properties);if(e!==n)return{name:t.name,properties:e}}}close(){return this.rpc.close()}async outgoing(t,e){if(!(t in X0))return e;let j=KF(t,e,X0);if(j===void 0)return n;switch(j.name){case"UpdatePeer":{let B=await this.cipher.encryptUserData(j.request.user_data);if(B===n)return n;j.request.user_data=B}break;case"SendMessage":{let B=await this.cipher.encryptMessage(j.request.message);if(B===n)return n;j.request.message=B}break}return j.request}async incoming(t,e){if(!(t in Z0))return e;let j=VF(t,e,Z0);if(j===void 0)return n;switch(j.name){case"RoomUpdated":for(let B=0;B<j.properties.updates.length;B++){let C=await this.roomUpdate(j.properties.updates[B]);if(C===n)return n;j.properties.updates[B]=C}break;case"PeerUpdated":{let B=await this.peerUpdate(j.properties);if(B===n)return n;j.properties=B}break;case"MessageReceived":{let B=await this.cipher.decryptMessage(j.properties.sender_peer_id,j.properties.message);if(B===n)return n;j.properties.message=B}break}return j.properties}async peerUpdate(t){switch(t.kind){case"UserDataChanged":{let e=await this.cipher.decryptUserData(t.peer_id,t.user_data);if(e===n)return n;t.user_data=e}break;case"MediaStarted":this.mediaStarted(t.peer_id,t.media.id);break;case"MediaStopped":this.mediaStopped(t.peer_id,t.media_id);break}return t}async roomUpdate(t){switch(t.kind){case"Joined":for(let e of t.room.peers){for(let B of e.medias)this.mediaStarted(e.id,B.id);let j=await this.cipher.decryptUserData(e.id,e.user_data);j!==n?e.user_data=j:e.user_data=new Uint8Array}break;case"PeerJoined":{for(let j of t.peer.medias)this.mediaStarted(t.peer.id,j.id);let e=await this.cipher.decryptUserData(t.peer.id,t.peer.user_data);e!==n?t.peer.user_data=e:t.peer.user_data=new Uint8Array}break;case"PeerLeft":{let e=this.peers.get(t.peer_id);this.peers.delete(t.peer_id),this.cipher.deletePeerKey(t.peer_id);for(let j of e??[])this.mediaStopped(t.peer_id,j)}break}return t}mediaStarted(t,e){let j=this.peers.get(t);j===void 0&&(j=new Set,this.peers.set(t,j)),j.add(e);let B=q({connectionId:this.connection.connection.id,mediaId:e});this.connection.mediaMap.set(B,{peerId:t,connection:this.connection})}mediaStopped(t,e){this.peers.get(t)?.delete(e);let B=q({connectionId:this.connection.connection.id,mediaId:e});this.connection.mediaMap.delete(B)}cleanup(){for(let[t,e]of this.peers)for(let j of e)this.mediaStopped(t,j)}};var Gx=class{constructor(t){this.onDatagram=t;this._LastConnectionId=0;this._Connections=new Map;this._Close=new AbortController;this._MediaMap=new Map;let e=Date.now(),j=setInterval(()=>{Math.abs(Date.now()-e)>i.ClockJumpThreshold&&this.checkHealth(),e=Date.now()},i.ClockJumpCheckInterval);addEventListener("offline",()=>this.checkHealth(),{signal:this._Close.signal}),this._Close.signal.addEventListener("abort",()=>{clearInterval(j);for(let B of this._Connections.values())B.type==="establishing"?B.abort.abort():B.connection.close();this._Connections.clear()},{once:!0})}get closed(){return this._Close.signal.aborted}sendDatagram(t,e){let j=this._Connections.get(t);(j?.type==="established"||j?.type==="virtual")&&j.connection.sendDatagram(e)}async recvDatagram(t,e){let j=zF(e);if(j===void 0||j.length===0)return;let B=this._MediaMap.get(q({connectionId:t,mediaId:j[0]}));if(B===void 0)this.onDatagram(t,e);else{let C=await B.connection.decryptDatagram(B.peerId,e);if(C===n)return;this.onDatagram(B.connection.id,C)}}async acquireConnection(t,e,j,B){if(await WF(),this.closed)return"closed";let C=this.findConnection(t,e),E;switch(C?.type){case"established":a(`reusing existing connection ${C.id}`),E=C;break;case"establishing":{a(`waiting for connecting to '${e}' finish`);let b=await C.finished;if(b.type!=="Success")return b;E=b.value}break;case void 0:{a(`connecting to '${e}'`);let b=await this.createConnection(t,e,B);if(b.type!=="Success")return b;E=b.value}break}let f=E.id,s=new t0(E.connection,()=>this.releaseConnection(f));return E.references+=1,j&&(s=new mx(++this._LastConnectionId,s,j,this._MediaMap),this.addConnection({type:"virtual",id:s.id,connection:s,createdAt:Date.now()})),xA(s)}async createConnection(t,e,j){let B=++this._LastConnectionId,C=Date.now(),E=new AbortController;j.addEventListener("abort",()=>E.abort(),{once:!0}),a(`creating new connection ${B}`);let f=z0(B,t,e,this.recvDatagram.bind(this),j),{promise:s,resolve:b}=Promise.withResolvers();this.addConnection({type:"establishing",id:B,address:e,transport:t,finished:s,createdAt:Date.now(),abort:E});let d=await f;if(this._Connections.delete(B),d.type!=="Success")return b(d),d;let h={type:"established",id:B,address:e,transport:t,createdAt:C,references:0,connection:d.value};return this.addConnection(h),xA(h)}addConnection(t){(t.type==="established"||t.type==="virtual")&&t.connection.closeSignal.addEventListener("abort",()=>{o(`connection ${t.id} has been closed`),this._Connections.delete(t.id)},{once:!0}),this._Connections.set(t.id,t)}releaseConnection(t){let e=this._Connections.get(t);e?.type==="established"&&(e.references-=1,e.references<=0&&e.connection.close())}checkHealth(){for(let t of this._Connections.values())t.type==="established"&&t.connection.healthCheck()}close(){this._Close.abort()}async dump(){let t=[];for(let j of this._Connections.values()){let B;switch(j.type){case"established":B={transport:j.transport,address:j.address,connection:await j.connection.dump(),references:j.references};break;case"establishing":B={transport:j.transport,address:j.address,aborted:j.abort.signal.aborted};break;case"virtual":B={connection:await j.connection.dump()};break}t.push({type:j.type,id:j.id,createdAt:j.createdAt,...B})}let e=[];for(let[j,B]of this._MediaMap)e.push(`${j} -> ${B.peerId} @${B.connection.id} `);return{lastConnectionId:this._LastConnectionId,connections:t,mediaMap:e,closed:this.closed}}findConnection(t,e){for(let j of this._Connections.values())if(j.type!=="virtual"&&j.transport===t&&j.address===e)return j}},t0=class{constructor(t,e){this.connection=t;this.release=e;this.closeController=new AbortController;this.closePromise=new Promise(t=>this.closeController.signal.addEventListener("abort",()=>t("closed"),{once:!0}));t.closeSignal.addEventListener("abort",()=>this.close(),{once:!0})}get closeSignal(){return this.closeController.signal}get closed(){return this.closeSignal.aborted}close(){this.release(),this.closeController.abort("closed")}get connectionStats(){return this.connection.connectionStats}get id(){return this.connection.id}get transport(){return this.connection.transport}get address(){return this.connection.address}get status(){return this.connection.status}waitForConnected(){return this.connection.waitForConnected()}joinRoom(t,e,j,B){return this.connection.joinRoom(t,e,j,B)}getReconnectToken(t){return this.connection.getReconnectToken(t)}getRtcStats(){return this.connection.getRtcStats()}healthCheck(){return this.connection.healthCheck()}sendDatagram(t){return this.connection.sendDatagram(t)}startLocalVideo(t,e,j){return this.connection.startLocalVideo(t,e,j)}stopLocalVideo(t){return this.connection.stopLocalVideo(t)}startRemoteVideo(t){return this.connection.startRemoteVideo(t)}stopRemoteVideo(t){return this.connection.stopRemoteVideo(t)}async dump(){let t=await this.connection.dump();return typeof t=="object"&&(t={...t,isShared:!0,referenceClosed:this.closed}),t}};function zF(v){let t;try{t=QF(v)}catch{return}if(!Array.isArray(t)||t.length<2)return;let e=t[1];if(Array.isArray(e))return e.map(Number)}import{assert as e0,Backend as $B}from"@4players/odin-common";var w=class{constructor(t,e){this.uid=t;this.customType=e}#x;#A;get mediaStream(){return this.#x}get audioPlayback(){return e0(this.#A,"getting the audioPlayback failed, this video has no Audio"),this.#A}get volume(){return e0(this.audioPlayback,"getting the volume failed, this video has no Audio"),this.audioPlayback.volume}setVolume(t){e0(this.#A,"Can not set the volume, this video has no Audio"),this.#A.setVolume(t)}setMediaStream(t){this.mediaStream||(this.#x=t)}close(){this.#x?.getVideoTracks().forEach(t=>{t.stop(),this.#x?.removeTrack(t)}),this.#x=void 0}};import{Backend as IB,assert as nA,generateUUID as ar,unwrap as lr,CONNECTION_STATS_INITIAL as ur}from"@4players/odin-common";import{RoomNotificationsRpc as kr,RoomV1 as gB}from"@4players/odin-common/api";import{Selector as XF,failure as P,sleep as $x,success as T,assert as ZF}from"@4players/odin-common";import{parseResponse as YF,RoomCommandsRpc as yx,RoomNotificationsRpc as xr,RoomV1 as yB}from"@4players/odin-common/api";u();var Ix=class{constructor(t,e,j,B,C,E,f,s,b,d){this.connectionPool=t;this.transport=e;this.onEvent=j;this.gateway=B;this.roomId=E;this.cipher=b;this.disableAutoReconnect=d;this._Close=new AbortController;this._TokenUsed=!1;this._WasConnected=!1;this._FailedConnections=0;this._LastTokenRenew=performance.now();this._LastReconnectStartedAt=0;this._Closed=new Promise(t=>this._Close.signal.addEventListener("abort",()=>t(this._Close.signal.reason?"disconnected":"closed"),{once:!0}));this._Token=C,this._UserData=f,this._Position=s,this._Main().then(({reason:h})=>a(`_Main() resolved; ${h}`))}get token(){return this._Token}get userData(){return this._UserData}get position(){return this._Position}get closed(){return this._Close.signal.aborted}get mainConnection(){return this._MainConnection}async requestUnsafe(t,e){if(this._RoomConnection===void 0)return P("currently not connected");let j=await this._RoomConnection.request(t,e,void 0);return ZF(j!=="timeout","request should not timeout"),j!=="closed"&&j.type==="Success"&&this._HandleRequests(t,e,j.value),j}async request(t,e){let j=Date.now(),B=yx[t],C=await this.requestUnsafe(t,e),E=(Date.now()-j)/1e3;if(a(`sent room rpc '${t}'; took: ${E}s`,{properties:e,result:C}),C==="closed"||C.type==="Failure")return C;let f=YF(t,C.value,yx);return f!==void 0?T(f):P(`received invalid response from ${t}`)}notify(t,e){this._RoomConnection!==void 0&&this._RoomConnection.notify(t,e)}close(){this._Close.abort(!0)}get renewTokenIn(){let t=this._LastTokenRenew-performance.now()+i.MinTokenRefreshInterval,e=this._Token.timeLeft-i.MinTokenLifetime;return Math.max(t,e)}async _Main(){let t="unable to establish connection";for(let e=0;;this._FailedConnections++){if(await $x(Math.max(e-performance.now(),0)),this._Close.signal.aborted||this.connectionPool.closed){t="user requested";break}if(e=performance.now()+1e3,this._TokenUsed=!0,this._Token.hasAudience("sfu")){let j=await this._ConnectToServer();if(j.type==="Success"&&j.value==="shutdown"){a("connection closed by user request; shutting down"),t="user requested";break}if(this.disableAutoReconnect&&this._WasConnected){t=j.type==="Failure"?j.reason:"connection lost";break}if(this._LastReconnectStartedAt===0&&(this._LastReconnectStartedAt=performance.now()),j.type==="Failure"&&!this._WasConnected&&this._FailedConnections>=3){t=j.reason;break}if(j.type==="Failure"&&!Fr(this._LastReconnectStartedAt))continue}if(this.reset(),this._Close.signal.aborted||this.connectionPool.closed){t="user requested";break}if(this.gateway!==void 0&&this._Token.hasAudience("gateway")){this._ChangeStatus("Joining",`requesting new token from ${this.gateway}`);let j=await Ar(this.gateway,this._Token,this._Close.signal);if(j.type==="Success")if(j.value instanceof g)e=0,this._Token=j.value,this._TokenUsed=!1;else{t=`gateway error; ${j.value}`;break}else if(!this._WasConnected&&this._FailedConnections>=3){t="unable to contact the gateway";break}}if(this._TokenUsed&&this._Token.timeLeft<=0){t="token has expired";break}if(this._Close.signal.aborted||this.connectionPool.closed){t="user requested";break}}return this._ChangeStatus("Closed",t),this.close(),P(t)}async _ConnectToServer(){let t=this._Token;for(;t.upstream!==void 0;)t=t.upstream;let e=t.claims.adr??this.gateway?.toString();if(!e)return T("continue");if(this._ChangeStatus("Joining",`connecting to ${t.claims.adr}`),this._MainConnection===void 0||this._MainConnection.closed||this._MainConnection.address!==t.claims.adr){this._MainConnection?.close();let C=await this.connectionPool.acquireConnection(this.transport,e,this.cipher,this._Close.signal);if(C==="closed")return P("connection pool closed");if(C.type==="Failure")return this._ChangeStatus("Joining",`connection failed; ${C.reason}`),P(`connection failed; ${C.reason}`);this._MainConnection=C.value,this._OwnPeerId=void 0}let j=await Promise.race([Promise.all([this._MainConnection.joinRoom(t,this.roomId,this.userData,this.position)]),$x(i.ConnectTimeout,"timeout"),this._Closed]);if(j==="closed"||j==="disconnected")return T("continue");if(j==="timeout")return this._ChangeStatus("Joining","timed out"),T("continue");let[B]=j;if(B==="closed")return T("continue");if(B.type==="Failure")return P(`unable to join room; ${B.reason}`);this._RoomConnection=B.value,this._WasConnected=!0,this._FailedConnections=0,this._ChangeStatus("Joined",`joined ${this.roomId}`);try{await this._MainConnection.waitForConnected();let C=await this._HandleConnection(this._MainConnection);return T(C?"shutdown":"continue")}catch(C){return P(`unable to handle connection; ${C}`)}}_ChangeStatus(t,e){let j={status:t,message:e};this.onEvent("RoomStatusChanged",j)}async _HandleConnection(t){if(this._RoomConnection===void 0)return!1;let e=new XF([()=>$x(this.renewTokenIn,"renewToken"),()=>$x(500,"tick"),async()=>await this._RoomConnection?.recv(),()=>this._Closed,()=>t.closePromise]);for(;;){let j=await e.next();switch(j){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(j);break}}}_HandleEvent(t){if(t.name==="RoomUpdated"){let e=xr.RoomUpdated.safeParse(t.properties);if(!e.success)return;for(let j of e.data.updates)j.kind==="Joined"&&(this._OwnPeerId=j.own_peer_id)}this.onEvent(t.name,t.properties)}_HandleRequests(t,e,j){switch(t){case"SetPeerPosition":{let B=yx.SetPeerPosition.request.safeParse(e);if(B.success){let C=B.data.position;this._Position=C.length===2?[C[0],C[1],0]:C}else k("unable to process SetPeerPosition command");break}case"UpdatePeer":{let B=yx.UpdatePeer.request.safeParse(e);B.success?this._UserData=B.data.user_data:k("unable to process UpdatePeer command");break}}}async _RenewToken(t){if(this._LastTokenRenew=performance.now(),!t&&this.token.timeLeft>i.MinTokenLifetime)return;if(this._MainConnection===void 0||this._OwnPeerId===void 0)return P("connection is not established");let e=await this._MainConnection.getReconnectToken(this._OwnPeerId);return e.type==="Success"?(this._Token=e.value,T()):P(`${this._MainConnection.address} rejected reconnect token request; ${e.reason}`)}reset(){this._LastReconnectStartedAt=0,this._RoomConnection?.close(),this._RoomConnection=void 0,this._MainConnection?.close(),this._MainConnection=void 0,this._OwnPeerId=void 0}};async function Ar(v,t,e){try{let j={jsonrpc:"2.0",id:1,method:"Connect",params:{}};o(`sending authentication request to '${v}'`,j);let C=await(await fetch(v,{body:JSON.stringify(j),method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},signal:e})).json();if(o(`received authentication response fom '${v}'`,C),"result"in C)return g.parse(C.result.token);{let E=C.error?.message??"malformed response";return p(`gateway rejected token; ${E}`),T(E)}}catch(j){return P(String(j))}}function Fr(v,t=8e3){return performance.now()-v>t}u();import{assert as or}from"@4players/odin-common";u();import{Backend as jx,Strand as br}from"@4players/odin-common";u();import{assert as jr}from"@4players/odin-common";u();import{decode as rr}from"@msgpack/msgpack";var AA={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])},FA=v=>({name:"PBKDF2",hash:"SHA-256",iterations:600,salt:v}),rA=32,DA=1e6,tA=2147483648,eA=32,J=[79,68,73,78,1,75,105,109],Ax=16,Fx=64,jA=16;function BA(v,t){if(v.length!==t.length)return!1;for(let e=0;e<v.length;e++)if(v[e]!==t[e])return!1;return!0}function Dr(v){return isFinite(v)}function tr(v){return Array.isArray(v)}function gx(v){return Dr(v)?v:n}function ex(v){return v instanceof Uint8Array?v:n}function er(v,...t){let e;try{e=rr(v)}catch{return n}if(!tr(e))return n;let j=new Array(e.length);for(let B in t)if(j[B]=t[B](e[B]),j[B]===n)return n;return j}function _x(v,...t){if(v.length<J.length)return G;for(let e=0;e<J.length;e++)if(v[e]!==J[e])return G;return er(v.subarray(J.length),...t)}var rx=class{constructor(t){this.first=1;this.offset=0;this.window=Array(t)}isReplay(t){let e=t-this.first;if(e<0)return!0;if(e>=this.window.length)if(e<this.window.length*2){let C=e-this.window.length+1;e-=C;for(let E=0;E<C;E++)this.advance()}else return this.first=t+1-self.window.length,this.offset=0,this.window.fill(!1),!1;let j=(this.offset+e)%this.window.length,B=this.window[j]===!0;for(this.window[j]=!0;this.window[this.offset]===!0;)this.advance();return B}advance(){this.window[this.offset]=!1,this.first+=1,this.offset=(this.offset+1)%this.window.length}};var Lx=class v{constructor(t){this.key=t}static async create(t){typeof t=="string"&&(t=new TextEncoder().encode(t));let e=await globalThis.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits"]),j=await globalThis.crypto.subtle.deriveBits(AA,e,256),B=await globalThis.crypto.subtle.importKey("raw",j,"PBKDF2",!1,["deriveKey"]);return new v(B)}async generatePeerKey(t,e){return await globalThis.crypto.subtle.deriveKey(FA(t),this.key,{name:"AES-GCM",length:256},!1,[e])}},Hx=class v{constructor(t,e){this.seed=t;this.key=e;this.sequenceNumbers={datagram:1,message:1,userData:1};this.number_of_packets=0;this.number_of_bytes=0}static async create(t){let e=globalThis.crypto.getRandomValues(new Uint8Array(rA)),j=await t.generatePeerKey(e,"encrypt");return new v(e,j)}get limitReached(){return this.key===void 0?!1:this.number_of_bytes>=tA||this.number_of_packets>=DA}nextSequenceNumber(t){return this.sequenceNumbers[t]++}};function j0(v,t){return{kind:"encrypted",key:v,material:t,antiReplays:{datagram:new rx(eA),userData:new rx(0),message:new rx(0)}}}var Px=class v{constructor(t,e,j,B){this.additionalData=t;this.sequenceNumber=e;this.seed=j;this.encrypted=B}static parse(t){let e=_x(t,ex,gx,ex);if(e===n||e===G)return e;let[j,B,C]=e,E=t.subarray(0,t.length-C.length);return new v(E,B,j,C)}isSameSeed(t){return BA(this.seed,t.seed)}async generateKey(t){return await t.generatePeerKey(this.seed,"decrypt")}};function Nx(v,t){let e=new Uint8Array(12);switch(e[0]=t&255,e[1]=t>>8&255,e[2]=t>>16&255,e[3]=t>>24&255,v){case"datagram":e[5]=1;break;case"userData":e[5]=2;break;case"message":e[5]=3;break;default:jr(!1,"missing content implementation")}return e}u();import{encode as CA}from"@msgpack/msgpack";import{assert as vr}from"@4players/odin-common";var wx=class{constructor(t){this.actions=t}changeKey(t){this.masterKey!==t&&(this.masterKey=t,this.ownKey=n,this.actions.resendUserData())}async encryptDatagram(t){let e=await this.getKey("datagram");return e===void 0?t:e===O?n:await Er(e,t)}async encryptMessage(t){let e=await this.getKey("message");return e===void 0?t:e===O?O:await vA(e,t,"message")}async encryptUserData(t){let e=await this.getKey("userData");return e===void 0?t:(vr(e!==O,"key unavailable for user data encryption"),await vA(e,t,"userData",e.seed))}async getKey(t){if(this.ownKey===n||this.ownKey?.limitReached)if(t==="userData")this.ownKey=this.masterKey?await Hx.create(this.masterKey):void 0;else return this.ownKey!==n&&(this.ownKey=n,this.actions.resendUserData()),O;return this.ownKey}reset(){this.ownKey=this.masterKey?n:void 0}};async function vA(v,t,e,...j){let B=v.nextSequenceNumber(e),C=t.length+Ax,E=Cr(B,j,C),f=E.length-C,s=await EA(v,e,B,E.subarray(0,f),t);return E.set(new Uint8Array(s),f),E}function Cr(v,t,e){let j=[];t.forEach(E=>j.push(E)),j.push(v),j.push(new Uint8Array(e));let B=CA(j),C=new Uint8Array(J.length+B.length);return C.set(J,0),C.set(B,J.length),C}async function Er(v,t){let e=fr(t);if(e===n)return n;if((e.kind&Fx)!==0)return n;let j=e.body.length+Ax,B=v.nextSequenceNumber("datagram"),C=CA([e.kind|Fx,e.mediaIds,B,new Uint8Array(j)]),E=C.length-j,f=await EA(v,"datagram",B,C.subarray(0,E),e.body);return C.set(f,E),C}async function EA(v,t,e,j,B){return new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:Nx(t,e),additionalData:j,tagLength:Ax*8},v.key,B))}function fr(v){let t=new S(v),e=t.readArrayLength();if(l(e)||e<2)return n;let j=t.readNumber(),B=t.readArrayLength();if(l(j)||l(B))return n;if(B>jA)return n;let C=Array(B);for(let f=0;f<C.length;f++){let s=t.readNumber();if(l(s))return n;C[f]=s}let E=v.subarray(t.position);return{kind:j,mediaIds:C,body:E}}u();import{encode as nr}from"@msgpack/msgpack";var Ox=class{constructor(t){this.actions=t;this.peerKeys=new Map}async changeKey(t){this.masterKey=t;for(let[e,{kind:j,material:B}]of this.peerKeys)if(t!==void 0){let C=await B.generateKey(t),E=j0(C,B),f=await Jx(E,"userData",B.additionalData,B.sequenceNumber,B.encrypted);f!==n?(this.peerKeys.set(e,E),this.actions.setUserData(e,f)):(this.peerKeys.set(e,{kind:"broken",material:B}),this.actions.setUserData(e,new Uint8Array))}else j==="encrypted"&&this.peerKeys.set(e,{kind:"broken",material:B})}async decryptDatagram(t,e){let j=sr(e);if(this.masterKey===void 0)return j===G?e:n;if(j===n||j===G)return n;let B=this.peerKeys.get(t);if(B?.kind!=="encrypted")return n;let C=await Jx(B,"datagram",j.additionalData,j.sequenceNumber,j.encrypted);return C===n?n:ir(j.kind&~Fx,j.mediaIds,C)}async decryptMessage(t,e){let j=_x(e,gx,ex);if(this.masterKey===void 0)return j===G?e:n;if(j===n||j===G)return n;let B=this.peerKeys.get(t);if(B?.kind!=="encrypted")return n;let[C,E]=j,f=e.subarray(0,e.length-E.length);return Jx(B,"message",f,C,E)}async decryptUserData(t,e){let j=Px.parse(e);if(j===n)return n;if(j===G)return this.peerKeys.delete(t),this.masterKey===void 0?e:n;if(this.masterKey===void 0)return this.peerKeys.set(t,{kind:"broken",material:j}),n;let B=this.peerKeys.get(t);if(B?.kind==="encrypted"&&B.material.isSameSeed(j))B.material=j;else{let E=await j.generateKey(this.masterKey);B=j0(E,j)}let C=await Jx(B,"userData",j.additionalData,j.sequenceNumber,j.encrypted);return C===n?this.peerKeys.set(t,{kind:"broken",material:j}):B!==void 0&&this.peerKeys.set(t,B),C}reset(){this.peerKeys.clear()}};function sr(v){let t=new S(v),e=t.readArrayLength();if(l(e)||e<1)return n;let j=t.readNumber();if(l(j))return n;if((j&Fx)===0)return G;if(e!==4)return n;let B=t.position;t.readObjects(1);let C=v.subarray(B,t.position),E=t.readNumber(),f=t.readBytes();if(l(E)||l(f))return n;let s=v.subarray(0,v.length-f.length);return{kind:j,mediaIds:C,additionalData:s,sequenceNumber:E,encrypted:f}}async function Jx(v,t,e,j,B){let C=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:Nx(t,j),additionalData:e,tagLength:Ax*8},v.key,B).catch(()=>n);return C===n?n:v.antiReplays[t].isReplay(j)?n:new Uint8Array(C)}function ir(v,t,e){let j=2;try{let E=new S(e);for(E.position=0;E.position<e.length;)E.readObjects(1),j+=1}catch{return n}let B=nr(v),C=new Uint8Array(3+B.length+t.length+e.length);return C[0]=220,C[1]=j>>8&255,C[2]=j&255,C.set(B,3),C.set(t,3+B.length),C.set(e,3+B.length+t.length),C}var Sx=class{constructor(t,e){this.active=!1;let j=new Ox(e),B=new wx(e);this.crypto=new br({encryption:B,decryption:j}),this.peerKeys=j.peerKeys,this.configure(t)}encryptUserData(t){return this.crypto.enqueue(({encryption:e})=>e.encryptUserData(t))}async encryptMessage(t){let e;do e=await this.crypto.enqueue(({encryption:j})=>j.encryptMessage(t));while(e===O);return e}async encryptDatagram(t){return await this.crypto.enqueue(({encryption:e})=>e.encryptDatagram(t))}decryptUserData(t,e){return this.crypto.enqueue(({decryption:j})=>j.decryptUserData(t,e))}decryptMessage(t,e){return this.crypto.enqueue(({decryption:j})=>j.decryptMessage(t,e))}decryptDatagram(t,e){return this.crypto.enqueue(({decryption:j})=>j.decryptDatagram(t,e))}configure(t){return this.crypto.enqueue(async e=>{let j=t.password?await Lx.create(t.password):void 0;this.active=j!==void 0,await e.encryption.changeKey(j),await e.decryption.changeKey(j)})}getPeerStatus(t){switch(this.peerKeys.get(t)?.kind??"unencrypted"){case"broken":return jx.PeerCipherStatus.InvalidPassword;case"encrypted":return jx.PeerCipherStatus.Encrypted;case"unencrypted":return this.active?jx.PeerCipherStatus.InvalidPassword:jx.PeerCipherStatus.Unencrypted;default:return jx.PeerCipherStatus.Unknown}}deletePeerKey(t){this.peerKeys.delete(t)}reset(){return this.crypto.enqueue(async({encryption:t,decryption:e})=>{t.reset(),e.reset()})}async dump(){return this.crypto.enqueue(async()=>({active:this.active,peers:Array.from(this.peerKeys).map(([t,e])=>`${t} => ${e.kind}`)}))}};function fA(v,t){return or(v.type==="OdinCrypto","only OdinCrypto supported"),new Sx(v,t)}var Ux=class{constructor(t,e,j){this._Captures=new Map;this._Playbacks=new Map;this._Peers=new Map;this._AvailableMediaIds=[];let{url:B,onEvent:C}=e,E=lr(g.parse(e.token)),f=e.roomId??E.defaultRoomId,s=e.userData??new Uint8Array(0),b=e.position??[0,0,0];nA(f!==void 0,"room id required for multi-room-tokens"),this.cipher=e.cipher?fA(e.cipher,new qx(this)):void 0,this.onEvent=C,o(`creating new room '${f}' ${this.cipher?"with":"without"} cipher`,E,s,b),this._Connection=new Ix(t,e.transport??"H3",this._HandleEvent.bind(this),B?new URL(B):void 0,E,f,s,b,this.cipher,j?.disableAutoReconnect??!1)}get connectionStats(){let t={...ur};return this.mainConnection?this.mainConnection.connectionStats:t}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(t,e){return this._Connection.requestUnsafe(t,e)}async link(t){if(t instanceof H){let e=this._Playbacks.get(t.uid)??{media:void 0,playback:void 0};e.playback!==void 0&&this.unlink(e.playback),e.media!==void 0&&t.start(e.media),e.playback=t,o(`linking audio playback media '${t.uid}' with volume ${t.volume} to room '${this._Connection.roomId}'`),this._Playbacks.set(t.uid,e)}else if(t instanceof N){let e=this._Captures.get(t);e&&this.unlink(t);let j=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();e={media:j?{connectionId:this.mainConnection.id,mediaId:j}:void 0},o(`linking audio capture media '${t.uid}' with volume ${t.volume} to room '${this._Connection.roomId}'`),this._Captures.set(t,e),e.media!==void 0&&await t.start(this._Connection,e.media)}else if(t instanceof w){let e=this._Playbacks.get(t.uid)??{media:void 0,playback:void 0};if(e.playback!==void 0&&this.unlink(e.playback),e.media!==void 0){let j=await this.mainConnection?.startRemoteVideo(e.media.mediaId);j&&t.setMediaStream(new MediaStream([j]))}e.playback=t,o(`linking video playback media '${t.uid}' with type '${t.customType}' to room '${this._Connection.roomId}'`),this._Playbacks.set(t.uid,e)}else if(t instanceof I){let e=this._Captures.get(t);e&&this.unlink(t);let j=t.mediaStream?.getVideoTracks()[0];if(j){let B=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();e={media:B?{connectionId:this.mainConnection.id,mediaId:B}:void 0},o(`linking video capture media '${t.uid}' with type '${t.parameters?.customType}' to room '${this._Connection.roomId}'`),this._Captures.set(t,e),e.media!==void 0&&(await t.start(this._Connection,e.media),this.mainConnection?.startLocalVideo(e.media.mediaId,j,t.parameters)),t.audioCapture&&await this.link(t.audioCapture)}}else throw new Error("Linking failed, media was not supported")}unlink(t){if(t instanceof H||t instanceof w){let e=this._Playbacks.get(t.uid);if(e?.playback!==t)return;e.playback=void 0,e.media!==void 0&&(t instanceof H?t.stop(e.media):(this.mainConnection?.stopRemoteVideo(e.media.mediaId),t.setMediaStream(void 0))),o(`unlinking playback media '${t.uid}' from room '${this._Connection.roomId}'`),this._Playbacks.set(t.uid,e)}else if(t instanceof N||t instanceof I){t instanceof I&&t.audioCapture&&this.unlink(t.audioCapture);let e=this._Captures.get(t);if(e===void 0)return;e.media!==void 0&&(t.stop(this._Connection,e.media),this._AvailableMediaIds.push(e.media.mediaId),t instanceof I&&this.mainConnection?.stopLocalVideo(e.media.mediaId)),o(`unlinking capture media '${t.uid}' from room '${this._Connection.roomId}'`),this._Captures.delete(t)}else throw new Error("invalid media")}close(){o(`closing room '${this._Connection.roomId}'`),this._Connection.close()}_HandleEvent(t,e){let j=F0(kr,{name:t,properties:e});j!==void 0&&(this._HandleKnownEvent(j),e=j.properties),this.onEvent(t,e)}_HandleKnownEvent(t){switch(a(`processing event '${t.name}'`,t.properties),t.name){case"RoomStatusChanged":t.properties.status!=="Joined"&&this._HandleConnectionLost();break;case"RoomUpdated":for(let e of t.properties.updates)this._HandleRoomUpdate(e);break;case"PeerUpdated":this._HandlePeerUpdate(t.properties);break}}_HandleConnectionLost(){for(let t of this._Peers.keys())this._HandlePeerLeft(t);for(let[t,e]of this._Captures)e.media!==void 0&&(t instanceof I,t instanceof N&&(t.stop(this._Connection,e.media),e.media=void 0));this._AvailableMediaIds.length=0}_HandleRoomUpdate(t){if(t.kind==="Joined"){nA(this._AvailableMediaIds.length===0,"left over media ids"),this._AvailableMediaIds.push(...t.media_ids),this._HandleRoomJoined();for(let e of t.room.peers)this._HandlePeerJoined(e)}else t.kind==="PeerJoined"?this._HandlePeerJoined(t.peer):t.kind==="PeerLeft"&&this._HandlePeerLeft(t.peer_id)}_HandleRoomJoined(){for(let[t,e]of this._Captures)this._AvailableMediaIds.length===0||this.mainConnection===void 0||(e.media={connectionId:this.mainConnection.id,mediaId:this._AvailableMediaIds.shift()},t instanceof N&&t.start(this._Connection,e.media),t instanceof I)}_HandlePeerUpdate(t){t.kind==="MediaStarted"?this._HandleMediaStart(t.peer_id,t.media):t.kind==="MediaStopped"&&this._HandleMediaStopped(t.peer_id,t.media_id)}_HandlePeerJoined(t){this._Peers.has(t.id)||this._Peers.set(t.id,{mediaIds:new Map});for(let e of t.medias)this._HandleMediaStart(t.id,e)}_HandlePeerLeft(t){let e=this._Peers.get(t);if(e!==void 0){for(let j of e.mediaIds.keys())this._HandleMediaStopped(t,j);this._Peers.delete(t)}}_HandleMediaStart(t,e){if(this.mainConnection===void 0)return;let j=this._Peers.get(t);if(j===void 0||e.properties.kind!=="audio"&&e.properties.kind!=="video")return;let B=String(e.properties.uid??ar());e.properties.uid=B;let C=this._Playbacks.get(B)??{media:void 0,playback:void 0};this._Playbacks.set(B,C),j.mediaIds.set(e.id,B),C.media={connectionId:this.mainConnection.id,mediaId:e.id},C.playback!==void 0&&(C.playback instanceof H&&C.playback.start(C.media),C.playback instanceof w&&this.mainConnection.startRemoteVideo(C.media.mediaId).then())}_HandleMediaStopped(t,e){let j=this._Peers.get(t);if(j===void 0)return;let B=j?.mediaIds.get(e);if(B===void 0)return;let C=this._Playbacks.get(B);C!==void 0&&(C.media!==void 0&&C.media.mediaId===e&&C.playback!==void 0&&(C.playback instanceof H&&C.playback.stop(C.media),C.playback instanceof w&&this.mainConnection?.stopRemoteVideo(C.media.mediaId),C.media=void 0),j.mediaIds.delete(e))}};nx();function iB(v,t){c0(t?.logger,t?.onLogMessage);let e,j=new Gx((C,E)=>e.receivePacket(C,E)),B=new ox(v);return e=new ax(B,j.sendDatagram.bind(j),t?.enableHTMLAudioElementFallback??!1),new B0(j,e,t)}var dx=cr(),v0=[],sA=!1;function dr(){sA||typeof window>"u"||(window.addEventListener("beforeunload",()=>{for(let v of v0)v.deref()?.close()}),sA=!0)}var B0=class{constructor(t,e,j){this.version="9";this.supportedTransports=["H3","WebRTC"];this._PlaybackVolume=[1,1];this._CreatedAt=Date.now();this._Options=j??{},this._Options.disableBeforeUnload||dr(),this._ConnectionPool=t,this._MediaController=e,v0.push(new WeakRef(this)),o("plugin initialized")}get playbackVolume(){return this._PlaybackVolume}joinRoom(t){return new Ux(this._ConnectionPool,t,this._Options)}async createAudioPlayback(t){return this._MediaController.createAudioPlayback(t)}async createAudioCapture(t){return this._MediaController.createAudioCapture(t)}async createVideoCapture(t,e){return this._MediaController.createVideoCapture(t,e)}async createVideoPlayback(t){return new w(t.uid,t.customType)}enumerateDevices(){return fx()}setOutputVolume(t){this._MediaController.playbackSetGlobalVolume(t)}async setOutputDevice(t){await this._MediaController.playbackSetDevice(t.device)}close(){this._MediaController.close(),this._ConnectionPool.close(),o("plugin closed")}async dump(){return{createdAt:this._CreatedAt,connections:await this._ConnectionPool.dump(),medias:await this._MediaController.dump()}}};async function iA(){let v=[];for(let t of v0){let e=t.deref();e!==void 0&&v.push(await e.dump())}return JSON.stringify({timestamp:Date.now(),instances:v,background:await q0()})}globalThis.odin_debug_dump_state=iA;window!==void 0&&(window.odin_debug_dump_state=iA);export{dx as SESSION_ID,iB as createPlugin};
6455
+ \`,new Function(m,C)}function MA(t,j,s,i,o,k){var a=j.length;a<2&&G("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var u=j[1]!==null&&s!==null,c=Hr(j),C=!j[0].isVoid,f=j[0],m=j[1],$=[t,G,i,o,yr,f.fromWireType.bind(f),m?.toWireType.bind(m)],E=2;E<a;++E){var F=j[E];$.push(F.toWireType.bind(F))}if(!c)for(var E=u?1:2;E<j.length;++E)j[E].destructorFunction!==null&&$.push(j[E].destructorFunction);var P=Gt(j,u,C,k)(...$);return hr(t,P)}var pt=(t,j,s,i,o,k)=>{var a=SA(j,s);o=b(i,o),U([],[t],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 AA(\`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]=()=>{X(\`Cannot construct \${u.name} due to unbound types\`,a)},U([],a,C=>(C.splice(1,0,null),u.registeredClass.constructor_body[j-1]=MA(c,C,null,o,k),[])),[]})},Lr=t=>{t=t.trim();let j=t.indexOf("(");return j===-1?t:t.slice(0,j)},Et=(t,j,s,i,o,k,a,u,c,C)=>{var f=SA(s,i);j=v(j),j=Lr(j),k=b(o,k,c),U([],[t],m=>{m=m[0];var $=\`\${m.name}.\${j}\`;j.startsWith("@@")&&(j=Symbol[j.substring(2)]),u&&m.registeredClass.pureVirtualFunctions.push(j);function E(){X(\`Cannot call \${$} due to unbound types\`,f)}var F=m.registeredClass.instancePrototype,y=F[j];return y===void 0||y.overloadTable===void 0&&y.className!==m.name&&y.argCount===s-2?(E.argCount=s-2,E.className=m.name,F[j]=E):(Fr(F,j,$),F[j].overloadTable[s-2]=E),U([],f,P=>{var H=MA($,P,m,k,a,c);return F[j].overloadTable===void 0?(H.argCount=s-2,F[j]=H):F[j].overloadTable[s-2]=H,[]}),[]})},gr=(t,j,s)=>(t instanceof Object||G(\`\${s} with invalid "this": \${t}\`),t instanceof j.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,j.registeredClass)),mt=(t,j,s,i,o,k,a,u,c,C)=>{j=v(j),o=b(i,o),U([],[t],f=>{f=f[0];var m=\`\${f.name}.\${j}\`,$={get(){X(\`Cannot access \${m} due to unbound types\`,[s,a])},enumerable:!0,configurable:!0};return c?$.set=()=>X(\`Cannot access \${m} due to unbound types\`,[s,a]):$.set=E=>G(m+" is a read-only property"),Object.defineProperty(f.registeredClass.instancePrototype,j,$),U([],c?[s,a]:[s],E=>{var F=E[0],y={get(){var H=gr(this,f,m+" getter");return F.fromWireType(o(k,H))},enumerable:!0};if(c){c=b(u,c);var P=E[1];y.set=function(H){var tA=gr(this,f,m+" setter"),_=[];c(C,tA,P.toWireType(_,H)),yr(_)}}return Object.defineProperty(f.registeredClass.instancePrototype,j,y),[]}),[]})},Nr=[],M=[0,1,,1,null,1,!0,1,!1,1],ht=t=>{if(t>9&&--M[t+1]===0){var j=M[t];M[t]=void 0,Nr.push(t)}},VA={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 j=Nr.pop()||M.length;return M[j]=t,M[j+1]=1,j}}}},$t={name:"emscripten::val",fromWireType:t=>{var j=VA.toValue(t);return ht(t),j},toWireType:(t,j)=>VA.toHandle(j),readValueFromPointer:GA,destructorFunction:null},Ft=t=>B(t,$t),It=(t,j)=>{switch(j){case 4:return function(s){return this.fromWireType(ur[s>>2])};case 8:return function(s){return this.fromWireType(cr[s>>3])};default:throw new TypeError(\`invalid float width (\${j}): \${t}\`)}},vt=(t,j,s)=>{j=v(j),B(t,{name:j,fromWireType:i=>i,toWireType:(i,o)=>o,readValueFromPointer:It(j,s),destructorFunction:null})},Dt=(t,j,s,i,o,k,a,u)=>{var c=SA(j,s);t=v(t),t=Lr(t),o=b(i,o,a),Ir(t,function(){X(\`Cannot call \${t} due to unbound types\`,c)},j-1),U([],c,C=>{var f=[C[0],null].concat(C.slice(1));return Dr(t,MA(t,f,null,o,k,a),j-1),[]})},_t=(t,j,s,i,o)=>{j=v(j);let k=i===0,a=c=>c;if(k){var u=32-8*s;a=c=>c<<u>>>u,o=a(o)}B(t,{name:j,fromWireType:a,toWireType:(c,C)=>C,readValueFromPointer:Gr(j,s,i!==0),destructorFunction:null})},yt=(t,j,s)=>{var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=i[j];function k(a){var u=h[a>>2],c=h[a+4>>2];return new o(S.buffer,c,u)}s=v(s),B(t,{name:s,fromWireType:k,readValueFromPointer:k},{ignoreDuplicateRegistrations:!0})},Ht=(t,j,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;j[s++]=u}else if(u<=2047){if(s+1>=k)break;j[s++]=192|u>>6,j[s++]=128|u&63}else if(u<=65535){if(s+2>=k)break;j[s++]=224|u>>12,j[s++]=128|u>>6&63,j[s++]=128|u&63}else{if(s+3>=k)break;j[s++]=240|u>>18,j[s++]=128|u>>12&63,j[s++]=128|u>>6&63,j[s++]=128|u&63,a++}}return j[s]=0,s-o},Lt=(t,j,s)=>Ht(t,L,j,s),gt=t=>{for(var j=0,s=0;s<t.length;++s){var i=t.charCodeAt(s);i<=127?j++:i<=2047?j+=2:i>=55296&&i<=57343?(j+=4,++s):j+=3}return j},Br=globalThis.TextDecoder&&new TextDecoder,xr=(t,j,s,i)=>{var o=j+s;if(i)return o;for(;t[j]&&!(j>=o);)++j;return j},br=(t,j=0,s,i)=>{var o=xr(t,j,s,i);if(o-j>16&&t.buffer&&Br)return Br.decode(t.subarray(j,o));for(var k="";j<o;){var a=t[j++];if(!(a&128)){k+=String.fromCharCode(a);continue}var u=t[j++]&63;if((a&224)==192){k+=String.fromCharCode((a&31)<<6|u);continue}var c=t[j++]&63;if((a&240)==224?a=(a&15)<<12|u<<6|c:a=(a&7)<<18|u<<12|c<<6|t[j++]&63,a<65536)k+=String.fromCharCode(a);else{var C=a-65536;k+=String.fromCharCode(55296|C>>10,56320|C&1023)}}return k},Nt=(t,j,s)=>t?br(L,t,j,s):"",Bt=(t,j)=>{j=v(j);var s=!0;B(t,{name:j,fromWireType(i){var o=h[i>>2],k=i+4,a;if(s)a=Nt(k,o,!0);else{a="";for(var u=0;u<o;++u)a+=String.fromCharCode(L[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=gt(o):k=o.length;var u=RA(4+k+1),c=u+4;if(h[u>>2]=k,a)if(s)Lt(o,c,k+1);else for(var C=0;C<k;++C){var f=o.charCodeAt(C);f>255&&(J(u),G("String has UTF-16 code units that do not fit in 8 bits")),L[c+C]=f}else L.set(o,c);return i!==null&&i.push(J,u),u},readValueFromPointer:GA,destructorFunction(i){J(i)}})},Jr=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,xt=(t,j,s)=>{var i=t>>1,o=xr(Y,i,j/2,s);if(o-i>16&&Jr)return Jr.decode(Y.subarray(i,o));for(var k="",a=i;a<o;++a){var u=Y[a];k+=String.fromCharCode(u)}return k},bt=(t,j,s=2147483647)=>{if(s<2)return 0;s-=2;for(var i=j,o=s<t.length*2?s/2:t.length,k=0;k<o;++k){var a=t.charCodeAt(k);uA[j>>1]=a,j+=2}return uA[j>>1]=0,j-i},Jt=t=>t.length*2,Pt=(t,j,s)=>{for(var i="",o=t>>2,k=0;!(k>=j/4);k++){var a=h[o+k];if(!a&&!s)break;i+=String.fromCodePoint(a)}return i},Ot=(t,j,s=2147483647)=>{if(s<4)return 0;for(var i=j,o=i+s-4,k=0;k<t.length;++k){var a=t.codePointAt(k);if(a>65535&&k++,cA[j>>2]=a,j+=4,j+4>o)break}return cA[j>>2]=0,j-i},Ut=t=>{for(var j=0,s=0;s<t.length;++s){var i=t.codePointAt(s);i>65535&&s++,j+=4}return j},wt=(t,j,s)=>{s=v(s);var i,o,k;j===2?(i=xt,o=bt,k=Jt):(i=Pt,o=Ot,k=Ut),B(t,{name:s,fromWireType:a=>{var u=h[a>>2],c=i(a+4,u*j,!0);return J(a),c},toWireType:(a,u)=>{typeof u!="string"&&G(\`Cannot pass non-string to C++ string type \${s}\`);var c=k(u),C=RA(4+c+j);return h[C>>2]=c/j,o(u,C+4,c+j),a!==null&&a.push(J,C),C},readValueFromPointer:GA,destructorFunction(a){J(a)}})},Tt=(t,j)=>{j=v(j),B(t,{isVoid:!0,name:j,fromWireType:()=>{},toWireType:(s,i)=>{}})},Kt=t=>{kA("OOM")},St=t=>{var j=L.length;t>>>=0,Kt(t)},Mt=t=>52,Vt=9007199254740992,Rt=-9007199254740992,Wt=t=>t<Rt||t>Vt?NaN:Number(t);function Qt(t,j,s,i){return j=Wt(j),70}var zt=[null,[],[]],Xt=(t,j)=>{var s=zt[t];j===0||j===10?((t===1?x:aA)(br(s)),s.length=0):s.push(j)},Zt=(t,j,s,i)=>{for(var o=0,k=0;k<s;k++){var a=h[j>>2],u=h[j+4>>2];j+=8;for(var c=0;c<u;c++)Xt(t,L[a+c]);o+=u}return h[i>>2]=o,0};At(),ct();{r.noExitRuntime&&(Kj=r.noExitRuntime),r.print&&(x=r.print),r.printErr&&(aA=r.printErr),r.arguments&&(q=r.arguments),r.thisProgram&&(p=r.thisProgram);var Z=r.preInit;if(Z)for(typeof Z=="function"&&(r.preInit=Z=[Z]);Z.length>0;)Z.shift()()}var Pr,RA,J,Yt,Ae,Or,Ur;function re(t){Pr=t.w,RA=r._malloc=t.y,J=r._free=t.z,Yt=Or=t.u,Ae=Ur=t.x}var je={i:Vj,r:Rj,g:Qj,l:zj,k:ft,j:pt,d:Et,a:mt,s:Ft,f:vt,n:Dt,c:_t,b:yt,t:Bt,e:wt,m:Tt,o:St,q:Mt,p:Qt,h:Zt};async function te(){Bj();var t=r.setStatus;t&&(t("Running..."),await new Promise(j=>setTimeout(j,1)),setTimeout(t,1,"")),!or&&(xj(),r.onRuntimeInitialized?.(),bj())}var jA;return jA=await Tj(),await te(),r}})();typeof $j=="object"&&typeof OA=="object"?(OA.exports=nr,OA.exports.default=nr):typeof define=="function"&&define.amd&&define([],()=>nr)});var w={};ke(w,{AdditionalCaptureBlocks:()=>qe,AdditionalPlaybackBlocks:()=>de,ClockJumpCheckInterval:()=>he,ClockJumpThreshold:()=>$e,ConnectInterval:()=>Ne,ConnectTimeout:()=>He,DefaultRefreshRate:()=>fe,DefaultVideoCodec:()=>xe,HealthCheckTimeout:()=>me,MainConnectionPingInterval:()=>Fe,MaxNumberOfDecoders:()=>pe,MaxReconnectDuration:()=>Be,MinDBFs:()=>Sr,MinTokenLifetime:()=>Le,MinTokenRefreshInterval:()=>ge,PlaybackPreload:()=>Ce,RenderQuantumSize:()=>Ee,VadPreload:()=>Ge,WebRtcAnswerTimeout:()=>_e,WebRtcIceTimeout:()=>ve,WebRtcMaxNegotiationAttempts:()=>ye,WebRtcStatsSnapshotInterval:()=>Ie,WebRtcTimeout:()=>De});var de=3,qe=3,Ce=3,fe=250,Ge=3,pe=512,Ee=128,Sr=-758.596,me=1e4,he=1e3,$e=1e4,Fe=3e3,Ie=1e3,ve=3e3,De=1e4,_e=1e4,ye=3,He=5e3,Le=6e4,ge=5e3,Ne=[0,100,200,200,500],Be=12e4,xe="H264";function T(e,A,r){return e.postMessage(A,r)}function Mr(e){return[e.values[0],e.values[1]]}function hA(e,A){e.values[0]=A[0],e.values[1]=A[1]}function $A(e,A){return e.values[2+A*5]}function Vr(e,A,r){e.values[2+A*5]=r}function Rr(e,A){let r=2+A*5+1;return[e.values[r+0],e.values[r+1]]}function FA(e,A,r){let n=2+A*5+1;e.values[n+0]=r[0],e.values[n+1]=r[1]}function Wr(e,A){return e.values[2+A*5+3]}function Qr(e,A,r){e.values[2+A*5+3]=r}function zr(e,A){return e.values[2+A*5+4]}function Xr(e,A,r){e.values[2+A*5+4]=r}function IA(e){return e.values[0]!==0}function vA(e){return e.values[1]}function DA(e){return e.values[2]}function Zr(e){return e.values[3]}function _A(e,A){return e.values[3]=A}function Yr(e){return e?Array.from(e).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var be;(e=>{let A;(r=>(r[r.InvalidPassword=-1]="InvalidPassword",r[r.Unknown=0]="Unknown",r[r.Unencrypted=1]="Unencrypted",r[r.Encrypted=2]="Encrypted"))(A=e.PeerCipherStatus||={})})(be||={});function ej(e){return{type:"Success",value:e}}function g(e){return{type:"Failure",reason:e}}var{Deno:Aj}=globalThis,Je=typeof Aj?.noColor=="boolean"?Aj.noColor:!1,Pe=!Je;function XA(e,A){return{open:\`\\x1B[\${e.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function ZA(e,A){return Pe?\`\${A.open}\${e.replace(A.regexp,A.open)}\${A.close}\`:e}function zA(e){return ZA(e,XA([0],0))}function rj(e){return ZA(e,XA([1],22))}function Oe(e){return ZA(e,XA([2],22))}var xn=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"),Ue=new Date,yA=(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))(yA||{}),nj={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},we={4:Oe,3:zA,2:zA,1:rj,0:rj};function Te({message:e}){return String(e)}function jj(e){return JSON.stringify({timestamp:e.date.toISOString(),level:yA[e.level],message:e.message,extra:e.extra})}function tj(e){function A(q,p){return[Math.floor(q/p),q%p]}function r(){let q,p=e.date.valueOf()-Ue.valueOf();[p,q]=A(p,1e3);let[I,N]=A(p,60);return\`\${I.toString().padStart(4,"0")}:\${N.toString().padStart(2,"0")}.\${q.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 l=nj[e.level],d=e.logger.name!==void 0?\`@\${e.logger.name}\`:"";return\`\${zA(r())}\${d} \${l} \${we[e.level](String(e.message))}\${n()}\`}function Ke(e){let A=\`[\${e.date.toISOString()}]\`,r=\`[\${yA[e.level]}]\`,n=e.logger.name!==void 0?\`[\${e.logger.name}] \`:"",l=nj[e.level];return\`\${A} \${l} \${r.padEnd(7," ")} \${n}\${e.message}\`}function Se(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var sj=class{static sparse=Te;static json=jj;static pretty=tj;static structured=Ke;static default=Se()?tj:jj;constructor(){}};var Me=class{formatter;consoleObject;filter;constructor(e=sj.default,A=4,r=console){this.filter=A,this.formatter=e,this.consoleObject=r}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 V=class{#A;sinks;filter;parent;get name(){return this.#A}constructor(e,A=void 0,r=[],n=void 0){this.#A=A,this.sinks=r,this.filter=e,this.parent=n}log(e,A,r=void 0){let n={date:new Date,level:e,logger:this,message:A,extra:r};this.filter<e||this.insert(n)}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)},eA=globalThis[Symbol.for("odin-global-logger")]??=new V(3,void 0,[new Me]),Ve=V.prototype.log.bind(eA,1),Re=V.prototype.log.bind(eA,2),lj=V.prototype.log.bind(eA,3),We=V.prototype.log.bind(eA,4),bn=V.prototype.log.bind(eA);var ij;function oj(e,...A){let r=Qe(A);ij?ij?.info(e,r):lj(e,r)}function Qe(...e){if(e.length===1&&typeof e[0]=="object"&&e[0]!==null)return{...e[0]};if(e.length>0)return{args:e}}function HA(e){return e.connectionId*4294967296+e.mediaId}function aj(e){return{mediaId:e%4294967296,connectionId:Math.floor(e/4294967296)}}function O(e,A,r){let n;switch(A){case"f32":n=e.HEAPF32;break;case"u32":n=e.HEAPU32;break;case"i32":n=e.HEAP32;break;case"u8":n=e.HEAPU8;break;default:throw new Error(\`allocating \${A} is not supported\`)}let l=e._malloc(r*n.BYTES_PER_ELEMENT);if(l===0||l%n.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${r} \${A} array\`);let d=l/n.BYTES_PER_ELEMENT;return n.subarray(d,d+r)}function R(e,A){e._free(A.byteOffset)}function kj(e,A){return{values:O(e,"f32",2+A*5),length:A}}function uj(e,A){R(e,A.values)}function cj(e){return{values:O(e,"f32",4)}}function dj(e,A){R(e,A.values)}function qj(e){let A=e.length,r=0,n=0;for(;n<A;){let l=e.charCodeAt(n++);if((l&4294967168)===0){r++;continue}else if((l&4294965248)===0)r+=2;else{if(l>=55296&&l<=56319&&n<A){let d=e.charCodeAt(n);(d&64512)===56320&&(++n,l=((l&1023)<<10)+(d&1023)+65536)}(l&4294901760)===0?r+=3:r+=4}}return r}function ze(e,A,r){let n=e.length,l=r,d=0;for(;d<n;){let q=e.charCodeAt(d++);if((q&4294967168)===0){A[l++]=q;continue}else if((q&4294965248)===0)A[l++]=q>>6&31|192;else{if(q>=55296&&q<=56319&&d<n){let p=e.charCodeAt(d);(p&64512)===56320&&(++d,q=((q&1023)<<10)+(p&1023)+65536)}(q&4294901760)===0?(A[l++]=q>>12&15|224,A[l++]=q>>6&63|128):(A[l++]=q>>18&7|240,A[l++]=q>>12&63|128,A[l++]=q>>6&63|128)}A[l++]=q&63|128}}var Xe=new TextEncoder,Ze=50;function Ye(e,A,r){Xe.encodeInto(e,A.subarray(r))}function Cj(e,A,r){e.length>Ze?Ye(e,A,r):ze(e,A,r)}var An=4096;function YA(e,A,r){let n=A,l=n+r,d=[],q="";for(;n<l;){let p=e[n++];if((p&128)===0)d.push(p);else if((p&224)===192){let I=e[n++]&63;d.push((p&31)<<6|I)}else if((p&240)===224){let I=e[n++]&63,N=e[n++]&63;d.push((p&31)<<12|I<<6|N)}else if((p&248)===240){let I=e[n++]&63,N=e[n++]&63,UA=e[n++]&63,x=(p&7)<<18|I<<12|N<<6|UA;x>65535&&(x-=65536,d.push(x>>>10&1023|55296),x=56320|x&1023),d.push(x)}else d.push(p);d.length>=An&&(q+=String.fromCharCode(...d),d.length=0)}return d.length>0&&(q+=String.fromCharCode(...d)),q}var rn=new TextDecoder,jn=200;function tn(e,A,r){let n=e.subarray(A,A+r);return rn.decode(n)}function fj(e,A,r){return r>jn?tn(e,A,r):YA(e,A,r)}var W=class{constructor(A,r){this.type=A,this.data=r}};var D=class e extends Error{constructor(A){super(A);let r=Object.create(e.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}};function Gj(e,A,r){let n=r/4294967296,l=r;e.setUint32(A,n),e.setUint32(A+4,l)}function LA(e,A,r){let n=Math.floor(r/4294967296),l=r;e.setUint32(A,n),e.setUint32(A+4,l)}function gA(e,A){let r=e.getInt32(A),n=e.getUint32(A+4);return r*4294967296+n}function pj(e,A){let r=e.getUint32(A),n=e.getUint32(A+4);return r*4294967296+n}var en=-1,nn=4294967296-1,sn=17179869184-1;function ln({sec:e,nsec:A}){if(e>=0&&A>=0&&e<=sn)if(A===0&&e<=nn){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e),r}else{let r=e/4294967296,n=e&4294967295,l=new Uint8Array(8),d=new DataView(l.buffer);return d.setUint32(0,A<<2|r&3),d.setUint32(4,n),l}else{let r=new Uint8Array(12),n=new DataView(r.buffer);return n.setUint32(0,A),LA(n,4,e),r}}function on(e){let A=e.getTime(),r=Math.floor(A/1e3),n=(A-r*1e3)*1e6,l=Math.floor(n/1e9);return{sec:r+l,nsec:n-l*1e9}}function an(e){if(e instanceof Date){let A=on(e);return ln(A)}else return null}function kn(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 r=A.getUint32(0),n=A.getUint32(4),l=(r&3)*4294967296+n,d=r>>>2;return{sec:l,nsec:d}}case 12:{let r=gA(A,4),n=A.getUint32(0);return{sec:r,nsec:n}}default:throw new D(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${e.length}\`)}}function un(e){let A=kn(e);return new Date(A.sec*1e3+A.nsec/1e6)}var Ej={type:en,encode:an,decode:un};var K=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Ej)}register({type:A,encode:r,decode:n}){if(A>=0)this.encoders[A]=r,this.decoders[A]=n;else{let l=-1-A;this.builtInEncoders[l]=r,this.builtInDecoders[l]=n}}tryToEncode(A,r){for(let n=0;n<this.builtInEncoders.length;n++){let l=this.builtInEncoders[n];if(l!=null){let d=l(A,r);if(d!=null){let q=-1-n;return new W(q,d)}}}for(let n=0;n<this.encoders.length;n++){let l=this.encoders[n];if(l!=null){let d=l(A,r);if(d!=null){let q=n;return new W(q,d)}}}return A instanceof W?A:null}decode(A,r,n){let l=r<0?this.builtInDecoders[-1-r]:this.decoders[r];return l?l(A,r,n):new W(r,A)}};K.defaultCodec=new K;function cn(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function nA(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):cn(e)?new Uint8Array(e):Uint8Array.from(e)}var dn=100,qn=2048,NA=class e{constructor(A){this.entered=!1,this.extensionCodec=A?.extensionCodec??K.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??dn,this.initialBufferSize=A?.initialBufferSize??qn,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,r){if(r>this.maxDepth)throw new Error(\`Too deep objects in depth \${r}\`);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,r)}ensureBufferSizeToWrite(A){let r=this.pos+A;this.view.byteLength<r&&this.resizeBuffer(r*2)}resizeBuffer(A){let r=new ArrayBuffer(A),n=new Uint8Array(r),l=new DataView(r);n.set(this.bytes),this.view=l,this.bytes=n}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 n=qj(A);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),Cj(A,this.bytes,this.pos),this.pos+=n}encodeObject(A,r){let n=this.extensionCodec.tryToEncode(A,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(A))this.encodeArray(A,r);else if(ArrayBuffer.isView(A))this.encodeBinary(A);else if(typeof A=="object")this.encodeMap(A,r);else throw new Error(\`Unrecognized object: \${Object.prototype.toString.apply(A)}\`)}encodeBinary(A){let r=A.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(\`Too large binary: \${r}\`);let n=nA(A);this.writeU8a(n)}encodeArray(A,r){let n=A.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(\`Too large array: \${n}\`);for(let l of A)this.doEncode(l,r+1)}countWithoutUndefined(A,r){let n=0;for(let l of r)A[l]!==void 0&&n++;return n}encodeMap(A,r){let n=Object.keys(A);this.sortKeys&&n.sort();let l=this.ignoreUndefined?this.countWithoutUndefined(A,n):n.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 d of n){let q=A[d];this.ignoreUndefined&&q===void 0||(this.encodeString(d),this.doEncode(q,r+1))}}encodeExtension(A){if(typeof A.data=="function"){let n=A.data(this.pos+6),l=n.length;if(l>=4294967296)throw new Error(\`Too large extension object: \${l}\`);this.writeU8(201),this.writeU32(l),this.writeI8(A.type),this.writeU8a(n);return}let r=A.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(\`Too large extension object: \${r}\`);this.writeI8(A.type),this.writeU8a(A.data)}writeU8(A){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,A),this.pos++}writeU8a(A){let r=A.length;this.ensureBufferSizeToWrite(r),this.bytes.set(A,this.pos),this.pos+=r}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),Gj(this.view,this.pos,A),this.pos+=8}writeI64(A){this.ensureBufferSizeToWrite(8),LA(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(e,A){return new NA(A).encodeSharedRef(e)}function BA(e){return\`\${e<0?"-":""}0x\${Math.abs(e).toString(16).padStart(2,"0")}\`}var Cn=16,fn=16,xA=class{constructor(A=Cn,r=fn){this.hit=0,this.miss=0,this.maxKeyLength=A,this.maxLengthPerKey=r,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,r,n){let l=this.caches[n-1];A:for(let d of l){let q=d.bytes;for(let p=0;p<n;p++)if(q[p]!==A[r+p])continue A;return d.str}return null}store(A,r){let n=this.caches[A.length-1],l={bytes:A,str:r};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=l:n.push(l)}decode(A,r,n){let l=this.find(A,r,n);if(l!=null)return this.hit++,l;this.miss++;let d=YA(A,r,n),q=Uint8Array.prototype.slice.call(A,r,r+n);return this.store(q,d),d}};var rr="array",iA="map_key",hj="map_value",Gn=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new D("The type of key must be string or number but "+typeof e)},jr=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let r=this.getUninitializedStateFromPool();r.type=rr,r.position=0,r.size=A,r.array=new Array(A)}pushMapState(A){let r=this.getUninitializedStateFromPool();r.type=iA,r.readCount=0,r.size=A,r.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 n=A;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(A.type===iA||A.type===hj){let n=A;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},lA=-1,tr=new DataView(new ArrayBuffer(0)),pn=new Uint8Array(tr.buffer);try{tr.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 mj=new RangeError("Insufficient data"),En=new xA,bA=class e{constructor(A){this.totalPos=0,this.pos=0,this.view=tr,this.bytes=pn,this.headByte=lA,this.stack=new jr,this.entered=!1,this.extensionCodec=A?.extensionCodec??K.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.rawStrings=A?.rawStrings??!1,this.maxStrLength=A?.maxStrLength??4294967295,this.maxBinLength=A?.maxBinLength??4294967295,this.maxArrayLength=A?.maxArrayLength??4294967295,this.maxMapLength=A?.maxMapLength??4294967295,this.maxExtLength=A?.maxExtLength??4294967295,this.keyDecoder=A?.keyDecoder!==void 0?A.keyDecoder:En,this.mapKeyConverter=A?.mapKeyConverter??Gn}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=lA,this.stack.reset()}setBuffer(A){let r=nA(A);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(A){if(this.headByte===lA&&!this.hasRemaining(1))this.setBuffer(A);else{let r=this.bytes.subarray(this.pos),n=nA(A),l=new Uint8Array(r.length+n.length);l.set(r),l.set(n,r.length),this.setBuffer(l)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:r,pos:n}=this;return new RangeError(\`Extra \${r.byteLength-n} of \${r.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 r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}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 r=!1,n;for await(let p of A){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(p);try{n=this.doDecodeSync(),r=!0}catch(I){if(!(I instanceof RangeError))throw I}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:l,pos:d,totalPos:q}=this;throw new RangeError(\`Insufficient data in parsing \${BA(l)} at \${q} (\${d} in the current buffer)\`)}finally{this.entered=!1}}decodeArrayStream(A){return this.decodeMultiAsync(A,!0)}decodeStream(A){return this.decodeMultiAsync(A,!1)}async*decodeMultiAsync(A,r){if(this.entered){yield*this.clone().decodeMultiAsync(A,r);return}try{this.entered=!0;let n=r,l=-1;for await(let d of A){if(r&&l===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(d),n&&(l=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--l!==0;);}catch(q){if(!(q instanceof RangeError))throw q}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){A:for(;;){let A=this.readHeadByte(),r;if(A>=224)r=A-256;else if(A<192)if(A<128)r=A;else if(A<144){let l=A-128;if(l!==0){this.pushMapState(l),this.complete();continue A}else r={}}else if(A<160){let l=A-144;if(l!==0){this.pushArrayState(l),this.complete();continue A}else r=[]}else{let l=A-160;r=this.decodeString(l,0)}else if(A===192)r=null;else if(A===194)r=!1;else if(A===195)r=!0;else if(A===202)r=this.readF32();else if(A===203)r=this.readF64();else if(A===204)r=this.readU8();else if(A===205)r=this.readU16();else if(A===206)r=this.readU32();else if(A===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(A===208)r=this.readI8();else if(A===209)r=this.readI16();else if(A===210)r=this.readI32();else if(A===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(A===217){let l=this.lookU8();r=this.decodeString(l,1)}else if(A===218){let l=this.lookU16();r=this.decodeString(l,2)}else if(A===219){let l=this.lookU32();r=this.decodeString(l,4)}else if(A===220){let l=this.readU16();if(l!==0){this.pushArrayState(l),this.complete();continue A}else r=[]}else if(A===221){let l=this.readU32();if(l!==0){this.pushArrayState(l),this.complete();continue A}else r=[]}else if(A===222){let l=this.readU16();if(l!==0){this.pushMapState(l),this.complete();continue A}else r={}}else if(A===223){let l=this.readU32();if(l!==0){this.pushMapState(l),this.complete();continue A}else r={}}else if(A===196){let l=this.lookU8();r=this.decodeBinary(l,1)}else if(A===197){let l=this.lookU16();r=this.decodeBinary(l,2)}else if(A===198){let l=this.lookU32();r=this.decodeBinary(l,4)}else if(A===212)r=this.decodeExtension(1,0);else if(A===213)r=this.decodeExtension(2,0);else if(A===214)r=this.decodeExtension(4,0);else if(A===215)r=this.decodeExtension(8,0);else if(A===216)r=this.decodeExtension(16,0);else if(A===199){let l=this.lookU8();r=this.decodeExtension(l,1)}else if(A===200){let l=this.lookU16();r=this.decodeExtension(l,2)}else if(A===201){let l=this.lookU32();r=this.decodeExtension(l,4)}else throw new D(\`Unrecognized type byte: \${BA(A)}\`);this.complete();let n=this.stack;for(;n.length>0;){let l=n.top();if(l.type===rr)if(l.array[l.position]=r,l.position++,l.position===l.size)r=l.array,n.release(l);else continue A;else if(l.type===iA){if(r==="__proto__")throw new D("The key __proto__ is not allowed");l.key=this.mapKeyConverter(r),l.type=hj;continue A}else if(l.map[l.key]=r,l.readCount++,l.readCount===l.size)r=l.map,n.release(l);else{l.key=null,l.type=iA;continue A}}return r}}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 D(\`Unrecognized array type byte: \${BA(A)}\`)}}}pushMapState(A){if(A>this.maxMapLength)throw new D(\`Max length exceeded: map length (\${A}) > maxMapLengthLength (\${this.maxMapLength})\`);this.stack.pushMapState(A)}pushArrayState(A){if(A>this.maxArrayLength)throw new D(\`Max length exceeded: array length (\${A}) > maxArrayLength (\${this.maxArrayLength})\`);this.stack.pushArrayState(A)}decodeString(A,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(A,r):this.decodeBinary(A,r)}decodeUtf8String(A,r){if(A>this.maxStrLength)throw new D(\`Max length exceeded: UTF-8 byte length (\${A}) > maxStrLength (\${this.maxStrLength})\`);if(this.bytes.byteLength<this.pos+r+A)throw mj;let n=this.pos+r,l;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?l=this.keyDecoder.decode(this.bytes,n,A):l=fj(this.bytes,n,A),this.pos+=r+A,l}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===iA:!1}decodeBinary(A,r){if(A>this.maxBinLength)throw new D(\`Max length exceeded: bin length (\${A}) > maxBinLength (\${this.maxBinLength})\`);if(!this.hasRemaining(A+r))throw mj;let n=this.pos+r,l=this.bytes.subarray(n,n+A);return this.pos+=r+A,l}decodeExtension(A,r){if(A>this.maxExtLength)throw new D(\`Max length exceeded: ext length (\${A}) > maxExtLength (\${this.maxExtLength})\`);let n=this.view.getInt8(this.pos+r),l=this.decodeBinary(A,r+1);return this.extensionCodec.decode(l,n,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=pj(this.view,this.pos);return this.pos+=8,A}readI64(){let A=gA(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 er(e,A){return new bA(A).decode(e)}var oA=class e{constructor(A,r,n,l,d){this.mediaIds=A;this.sequenceNumber=r;this.timeStamp=n;this.isEndOfSpurt=l;this.payload=d}static parse(A){let r;try{r=er(A)}catch{return g("not valid msgpack")}if(!Array.isArray(r))return g("container must be an array");if(r.length<6)return g("missing fields");if(r[0]!==1)return g("unknown type");if(!Array.isArray(r[1]))return g("media ids must be an array");if(!r[1].every(N=>typeof N=="number"))return g("media ids must be numbers");if(typeof r[2]!="number")return g("sequence number must be a number");if(typeof r[3]!="number")return g("timestamp must be a number");if(typeof r[4]!="number")return g("flags must be a number");let n=r[1],l=r[2]>>>0,d=r[3]>>>0,p=(r[4]&1)!==0,I=r[r.length-1];return I instanceof Uint8Array?ej(new e(n,l,d,p,I)):g("payload must be bytes")}toBytes(){let A=Number(this.isEndOfSpurt),r=[1,this.mediaIds,this.sequenceNumber>>>0,this.timeStamp>>>0,A,this.payload];return new Uint8Array(Ar(r,{forceFloat32:!0,ignoreUndefined:!0}))}};var JA=class{constructor(A,r){this.sampleRate=A;this.wasm=r;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 r.Encoder(A,15,!0,w.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=cj(this.wasm),this.outBuffer=O(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:r})=>r.length>0)}close(){dj(this.wasm,this.information),R(this.wasm,this.outBuffer),this.encoder.delete()}encode(A){for(this.encoder.push(A.byteOffset,this.information.values.byteOffset);;){let r=this.encoder.pop(this.connections.length===0?0:this.outBuffer.byteOffset,this.outBuffer.length);if(r===0)break;if(r<0){oj(\`failed encoding packet: \${r}\`);return}if(this.timestamp=this.timestamp+1800>>0,r===1)continue;this.sequenceNumber=this.sequenceNumber+1>>0;let n=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 d=new oA(l.mediaIds,this.sequenceNumber,this.timestamp,n,this.outBuffer.subarray(0,r));T(globalThis,["sendPacket",{connectionId:l.id,packet:d.toBytes()}])}}}onMessage(A){let[r,n]=A;switch(r){case"captureSetVad":this?.setVad(n);break;case"captureSetMedias":this?.setMedias(n.connections);break;case"close":this.close();break;case"dump":n.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:IA(this.information),speechProbability:vA(this.information),rmsDBFS:DA(this.information),volume:Zr(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}}}},PA=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=O(this.wasm,"u32",w.MaxNumberOfDecoders),this.information=kj(this.wasm,w.MaxNumberOfDecoders),hA(this.information,[1,1])}close(){uj(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,r){this.stats.numberPackets++;let n=oA.parse(r);if(n.type==="Failure"){this.stats.numberPacketError++;let l=Array.from(r).map(d=>d.toString(16).padStart(2,"0")).join("");console.error(\`failed decoding audio packet; reason: \${n.reason}, connection: \${A}, dump: \${l}\`);return}for(let l of n.value.mediaIds){let d=this.medias.get(HA({connectionId:A,mediaId:l}));if(d===void 0){this.stats.numberPacketsMediaNotFound++;continue}d.lastPacket=r;let q=O(this.wasm,"u8",n.value.payload.length);q.set(n.value.payload),d.decoder.push(n.value.sequenceNumber,n.value.timeStamp,n.value.isEndOfSpurt,q.byteOffset,q.length)}}insertMedia(A,r,n,l=[1,1]){let d=HA({connectionId:r,mediaId:n}),q=new this.wasm.Decoder;this.medias.set(d,{index:A,decoder:q,lastPacket:void 0}),this.decoders[A]=q.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),FA(this.information,A,l),Xr(this.information,A,0),Qr(this.information,A,0)}removeMedia(A,r,n){let l=HA({connectionId:r,mediaId:n}),d=this.medias.get(l);if(!(d===void 0||d.index!==A)&&(this.medias.delete(l),Vr(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[r,n]=A;switch(r){case"playbackReceivePacket":this.receivePacket(n.connectionId,n.packet);break;case"playbackUpdateMedias":for(let{index:l,connectionId:d,mediaId:q}of n.removed)this.removeMedia(l,d,q);for(let{index:l,connectionId:d,mediaId:q,volume:p}of n.added)this.insertMedia(l,d,q,p);break;case"close":this.close();break;case"dump":n.result.postMessage(this.dump());break}}dump(){let A=[];for(let[r,n]of this.medias){let l=aj(r);A.push({index:n.index,connectionId:l.connectionId,mediaId:l.mediaId,rmsDBFS:$A(this.information,n.index),volume:Rr(this.information,n.index),voicedBlocks:zr(this.information,n.index),silentBlocks:Wr(this.information,n.index),time:n.decoder.time,consecutive_silence:n.decoder.consecutive_silence,last_voiced_time_point:n.decoder.last_voiced_time_point,sequence_number:n.decoder.sequence_number,packetsSeen:n.decoder.packets_seen,packetsInvalid:n.decoder.packets_invalid,packetsTooLate:n.decoder.packets_too_late,packetsTooEarly:n.decoder.packets_too_early,packetsRepeated:n.decoder.packets_repeated,packetsProcessed:n.decoder.packets_processed,packetsLost:n.decoder.packets_lost,rewinds:n.decoder.rewinds,voiceAccelerated:n.decoder.voice_accelerated,silenceAccelerated:n.decoder.silence_accelerated,cacheLength:n.decoder.cache_length,lastPacket:Yr(n.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:Mr(this.information),decoders:A}}};var _j=ce(Fj()),Ij=(0,_j.default)(),vj,Dj;globalThis.addEventListener("message",sr);async function sr(e){let A=e.data,[r,n]=A;switch(r){case"captureInit":n.workletPort.onmessage=sr,vj=new lr(n.sampleRate,await Ij,n.refreshRate);break;case"playbackInit":n.workletPort.onmessage=sr,Dj=new ir(await Ij,n.workletPort,n.refreshRate);break;case"close":globalThis.close();break}vj?.onMessage(A),Dj?.onMessage(A)}var lr=class extends JA{constructor(r,n,l){super(r,n);this.sampleRate=r;this.inBuffer=O(this.wasm,"f32",r*.02),this.updateHandle=setInterval(()=>this.update(),l),T(globalThis,["captureReady",{}])}close(){super.close(),R(this.wasm,this.inBuffer),clearInterval(this.updateHandle)}onMessage(r){super.onMessage(r);let[n,l]=r;switch(n){case"captureSetVolume":this.setVolume(l.value);break;case"captureTick":this.tick(l.buffer);break}}setVolume(r){_A(this.information,r)}tick(r){this.inBuffer.set(r,0),this.encode(this.inBuffer)}update(){T(globalThis,["captureUpdate",{active:IA(this.information),rmsDBFs:DA(this.information),speechProbability:vA(this.information)}])}dump(){return{type:"unshared capture worker",sampleRate:this.sampleRate,...super.dump()}}},ir=class extends PA{constructor(r,n,l){super(r);this.workletPort=n;this.id=w.PlaybackPreload,this.outBuffer=O(this.wasm,"f32",48e3*.02*2),this.updateHandle=setInterval(()=>this.update(),l),T(globalThis,["playbackReady",{}])}close(){super.close(),R(this.wasm,this.outBuffer),clearInterval(this.updateHandle)}onMessage(r){super.onMessage(r);let[n,l]=r;switch(n){case"playbackSetVolume":this.setVolume(l.index,l.value);break;case"playbackTick":this.tick();break}}setVolume(r,n){r==="global"?hA(this.information,n):FA(this.information,r,n)}tick(){this.stats.numberTicks++,this.id+=1;let{hasAudio:r}=this.decode(this.outBuffer);if(r){let n=this.outBuffer.slice();T(this.workletPort,["samples",{id:this.id,buffer:n}],[n.buffer])}}update(){let r=new Float32Array(this.information.length*2);for(let l=0;l<=this.largestIndex;l++)r[l]=$A(this.information,l);let n=[];for(let[l,d]of this.medias)n[d.index]={packetsBuffered:d.decoder.cache_length,packetsSeen:d.decoder.packets_seen,packetsProcessed:d.decoder.packets_processed,packetsTooEarly:d.decoder.packets_too_early,packetsTooLate:d.decoder.packets_too_late,packetsDropped:d.decoder.voice_accelerated,packetsInvalid:d.decoder.packets_invalid,packetsRepeated:d.decoder.packets_repeated,packetsLost:d.decoder.packets_lost};T(globalThis,["playbackUpdate",{activities:r,jitterStats:n}],[r.buffer])}dump(){return{type:"unshared playback worker",id:this.id,...super.dump()}}};})();
6456
+ `});var Yx,_0=m(()=>{Yx='"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:()=>G,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:()=>J,WebRtcIceTimeout:()=>$,WebRtcMaxNegotiationAttempts:()=>z,WebRtcStatsSnapshotInterval:()=>j,WebRtcTimeout:()=>H});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,H=1e4,J=1e4,z=3,G=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 L0={};Tx(L0,{UnsharedCaptureWorker:()=>sx,UnsharedPlaybackWorker:()=>ix,createCaptureWorker:()=>EF,createPlaybackWorker:()=>fF});import{Strand as vF}from"@4players/odin-common";function EF(v,t,e,j,B=i.DefaultRefreshRate){return CF.enqueue(async()=>{let[C,E]=await Y(Zx,Yx,v,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return console.warn("SharedArrayBuffer is not available; creating ODIN CaptureWorker in fallback mode"),sx.create(v,t,e,B,C,E,j)})}async function fF(v,t=i.DefaultRefreshRate){if(v.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[e,j]=await Y(Zx,Yx,v,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return ix.create(v,t,e,j)}var CF,sx,ix,H0=m(()=>{"use strict";u();nx();g0();_0();CF=new vF;sx=class v extends X{constructor(e,j,B,C,E){super(e,j,B,C,E);this._Activity=_;this._SpeechProbability=0;j.addEventListener("message",this._OnMessages.bind(this))}static async create(e,j,B,C,E,f,s){let{port1:b,port2:d}=new MessageChannel;return c(E,["captureInit",{sampleRate:e.sampleRate,refreshRate:C,workletPort:b}],[b]),await V(E,"captureReady"),c(f.port,["init",{workerPort:d}],[d]),new v(f,E,j,B,s)}get activity(){return this._Activity}get speechProbability(){return this._SpeechProbability}setVolume(e){c(this.worker,["captureSetVolume",{value:e}])}_OnMessages(e){super._OnMessages(e);let[j,B]=e.data;j==="captureUpdate"&&(this._Activity={isSilent:!B.active,rmsDBFS:B.rmsDBFs},this._SpeechProbability=B.speechProbability)}},ix=class v extends z{constructor(e,j,B){super(e,j,B);this.activities=new Float32Array;this.jitterStats=[]}static async create(e,j,B,C){let{port1:E,port2:f}=new MessageChannel;return c(B,["playbackInit",{workletPort:E,refreshRate:j}],[E]),await V(B,"playbackReady"),c(C.port,["init",{workerPort:f}],[f]),new v(e,C,B)}getActivity(e){let j=this.medias.get(q(e));if(j===void 0)return;let B=this.activities.at(j.index);if(B!==void 0)return B===0?_:{isSilent:!1,rmsDBFS:B}}getJitterStats(e){let j=this.medias.get(q(e));if(j===void 0)return;let B=this.jitterStats.at(j.index);if(B!==void 0)return B}setGlobalVolume(e){c(this.worker,["playbackSetVolume",{index:"global",value:e}])}setVolume(e,j){let B=this.medias.get(q(e));B!==void 0&&c(this.worker,["playbackSetVolume",{index:B.index,value:j}])}_GetFreeIndex(){let e=super._GetFreeIndex();if(e!==void 0)return e;if(this.medias.size<i.MaxNumberOfDecoders)return this.medias.size}_OnMessages(e){super._OnMessages(e);let[j,B]=e.data;j==="playbackUpdate"&&(this.activities=B.activities,this.jitterStats=B.jitterStats)}}});u();import{Backend as r,generateUUID as dr}from"@4players/odin-common";u();import{Backend as x,JITTER_STATS_INITIAL as J0,Strand as lF,assert as uF}from"@4players/odin-common";u();import{APM_DEFAULTS as iF,Backend as mB,generateUUID as bF,VAD_DEFAULTS as oF}from"@4players/odin-common";import{failure as p0,isFirefoxBrowser as WA,sleep as QA,success as zA}from"@4players/odin-common";async function h0(v,t,e){let j;if(t.device?.device.kind==="track"&&t.device?.device.audioTrack)j=new MediaStream([t.device.device.audioTrack]);else{let E=t.device?{exact:t.device.device.deviceId==="default"?void 0:t.device.device.deviceId}:void 0;try{let f=await Promise.race([navigator.mediaDevices.getUserMedia({audio:{echoCancellation:e.echoCanceller,noiseSuppression:e.noiseSuppression!=="None",autoGainControl:e.gainController,echoCancellationType:"system",deviceId:E}}),QA(3e4,"timeout")]);if(f==="timeout")return p0("getUserMedia; timeout");j=f}catch(f){return p0(`getUserMedia; ${f}`)}}let B=j.getAudioTracks()[0].getSettings().sampleRate,C=await v.audioContexts.acquire(B);return zA(C.createMediaStreamSource(j))}function W(v){v.getTracks().forEach(t=>{t.stop(),v.removeTrack(t)})}async function m0(v){return new L({deviceId:v.id,kind:"track",name:v.label??"MediaStreamTrack",audioTrack:v},!1)}async function fx(){if(WA()){let B=await XA("microphone");(B==="granted"||B===!1)&&await ZA("audio")}let v=(await navigator.mediaDevices.enumerateDevices()).filter(B=>!!B.label),t=[],e=new L({deviceId:"default",name:"Default",kind:"audioinput"},!0),j=new L({deviceId:"default",name:"Default",kind:"audiooutput"},!0);t.push(e),t.push(j);for(let B of v){if(B.deviceId==="default"){B.kind==="audioinput"&&(e=new L({deviceId:"default",name:B.label,kind:"audioinput"},!0),t[0]=e),B.kind==="audiooutput"&&(j=new L({deviceId:"default",name:B.label,kind:"audiooutput"},!0),t[1]=j);continue}B.kind==="audioinput"&&t.push(new L({deviceId:B.deviceId,name:B.label,kind:"audioinput"},!1)),B.kind==="audiooutput"&&t.push(new L({deviceId:B.deviceId,name:B.label,kind:"audiooutput"},!1))}return t}async function XA(v){try{return(await navigator.permissions.query({name:v})).state}catch{return!1}}async function ZA(v){try{let t=await navigator.mediaDevices.getUserMedia({[v]:!0});return t?.getTracks().forEach(e=>{e.stop(),t.removeTrack(e)}),!0}catch{return!1}}u();import{isSafariBrowser as nF,isSharedArrayBufferCapable as sF}from"@4players/odin-common";var P0=sF()&&!nF()?Promise.resolve().then(()=>(I0(),y0)):Promise.resolve().then(()=>(H0(),L0));async function N0(v,t,e,j){return P0.then(B=>B.createCaptureWorker(v,t,e,j,i.DefaultRefreshRate))}async function w0(v){return P0.then(t=>t.createPlaybackWorker(v,i.DefaultRefreshRate))}var N=class{constructor(t,e){this.controller=t;this._Medias=new Map;this._Vad={...oF};this._Apm={...iF};this._Volume=1;this._Queue=Promise.resolve();this._DeviceCb=()=>{this._enqueue(async()=>{!this._DeviceParameters?.device||(await fx()).some(B=>B.device.deviceId===this._DeviceParameters?.device?.device.deviceId)||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())}).catch(t=>k("device-change handler failed",t))};e.apm&&this.setApm(e.apm).catch(console.error),e.vad&&this.setVad(e.vad),typeof e.volume<"u"&&this.setVolume(e.volume).catch(console.error),this.uid=bF(),this.#x=e.customType,this.#A=e.ref}#x;#A;_enqueue(t){let e=this._Queue.then(t,t);return this._Queue=e.catch(()=>{}),e}get vad(){return this._Vad}get apm(){return this._Apm}get volume(){return this._Volume}get activity(){return this._Capture?.worker.activity??_}get speechProbability(){return this._Capture?.worker.speechProbability??0}get deviceId(){return this._DeviceParameters?.device?.device.deviceId}async start(t,e){let j=this._Medias.get(e.connectionId);j===void 0&&this._Medias.set(e.connectionId,j=new Set),o(`starting audio capture media ${e.mediaId} on connection ${e.connectionId}`),!j.has(e.mediaId)&&(j.add(e.mediaId),t.mainConnection?.id===e.connectionId&&await t.request("StartMedia",{media_id:e.mediaId,properties:{kind:"audio",uid:this.uid,ref:this.#A,customType:this.#x}}).catch(B=>p(`StartMedia got rejected; ${B}`)),this._UpdateMedias())}async stop(t,e){let j=this._Medias.get(e.connectionId);o(`stopping audio capture media ${e.mediaId} on connection ${e.connectionId}`),j?.delete(e.mediaId)&&(t.mainConnection?.id===e.connectionId&&await t.request("StopMedia",{media_id:e.mediaId}).catch(B=>p(`StopMedia got rejected; ${B}`)),this._UpdateMedias())}setVad(t){a("updating vad config",t),this._Vad=t,this._Capture&&this._Capture.worker.setVad(t)}async setApm(t){await this._enqueue(()=>this._setApmImpl(t))}async _setApmImpl(t){a("updating apm config",t),this._Apm=t,this._DeviceParameters&&await this._setDeviceImpl(this._DeviceParameters)}async setDevice(t){await this._enqueue(()=>this._setDeviceImpl(t))}async _setDeviceImpl(t){a("updating capture device parameters",t);let e=this._DeviceParameters;if(this._DeviceParameters=t,this._Volume!=="muted")try{let j=await h0(this.controller,t,{...this._Apm,echoCanceller:this._Monitor?!1:this._Apm.echoCanceller});if(j.type!=="Success"){p(`unable to open capture device; ${j.reason}`),this._DeviceParameters=e;return}if(this._DeviceParameters.onStatusChanged&&navigator.mediaDevices.addEventListener("devicechange",this._DeviceCb),this._Capture!==void 0){W(this._Capture.source.mediaStream);try{this._Capture.source.disconnect(this._Capture.worker.worklet)}catch(B){k("failed to disconnect previous capture source",B)}}this._Capture===void 0||this._Capture.worker.worklet.context!==j.value.context?(this._Capture?.worker.close(),this._Capture={worker:await N0(j.value.context,this.controller.sink,this.controller.receiveMonitoredPacket.bind(this.controller),new WeakRef(this)),source:j.value},await this._UpdateMedias(),this._Capture.worker.setVolume(this._Volume),this.setVad(this.vad)):this._Capture.source=j.value,this._Capture.source.connect(this._Capture.worker.worklet)}catch(j){throw new Error(`Error in setDevice(); ${j}`)}}async setVolume(t){await this._enqueue(()=>this._setVolumeImpl(t))}async _setVolumeImpl(t){a(`updating capture volume to ${t}`),this._Volume=t,t==="muted"?await this._closeImpl():(!this._Capture&&this._DeviceParameters&&await this._setDeviceImpl(this._DeviceParameters),this._Capture?.worker.setVolume(t))}async close(){await this._enqueue(()=>this._closeImpl())}async _closeImpl(){if(a("closing audio capture"),this._Capture!==void 0){this._Capture.worker.close(),W(this._Capture.source.mediaStream);try{this._Capture.source.disconnect(this._Capture.worker.worklet)}catch(t){k("failed to disconnect audio node",t)}await this.controller.audioContexts.release(this._Capture.source.context)}navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._Capture=void 0}async dump(){let t=[];for(let[e,j]of this._Medias)t.push(`${e} => ${Array.from(j.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:t}}async _UpdateMedias(){if(this._Capture!==void 0){let t=Array.from(this._Medias).map(([e,j])=>({id:e,mediaIds:Array.from(j)}));this._Capture.worker.setMedias(t)}}async startLoopback(){this._Monitor===void 0&&(a("starting audio capture loopback"),this.setApm(this._Apm),this._Monitor=await this.controller.createAudioPlayback({uid:"loopback"}),this._Monitor.start({connectionId:0,mediaId:0}),this._Medias.set(0,new Set([0])),await this._UpdateMedias())}async stopLoopback(){this._Monitor!==void 0&&(a("stopping audio capture loopback"),this._Monitor.close(),this._Monitor=void 0,this.setApm(this._Apm),this._Medias.delete(0),await this._UpdateMedias())}};import{assert as bx,Backend as D,generateUUID as aF}from"@4players/odin-common";u();var I=class{constructor(t,e){this.controller=t;this.parameters=e;this.uid=aF()}#x;#A=new Map;#F;get customType(){return this.parameters?.customType}get mediaStream(){return this.#x}get audioCapture(){return this.#F}get volume(){return bx(this.audioCapture,"getting the volume failed, this video has no Audio"),this.audioCapture.volume}async setVolume(t){bx(this.audioCapture,"setVolume() failed, this video has no Audio"),await this.audioCapture.setVolume(t)}get vad(){return bx(this.audioCapture,"getting the vad config failed, this video has no Audio"),this.audioCapture.vad}setVad(t){bx(this.audioCapture,"setVad() failed, this video has no Audio"),this.audioCapture.setVad(t)}async setDevice(t,e={voiceActivity:void 0,volumeGate:void 0}){if(this.#x)throw new Error("This VideoCapture already has a MediaStream.");if(!t.getVideoTracks()[0])throw new Error("Error when calling setDevice(), MediaStream does not contain a VideoStreamTrack!");if(this.#x=t,t.getAudioTracks()[0]){let B={device:await m0(t.getAudioTracks()[0]),vad:e,ref:this.uid};this.#F=await this.controller.createAudioCapture(B)}}async start(t,e){let j=this.#A.get(e.connectionId);if(j===void 0&&this.#A.set(e.connectionId,j=new Set),!j.has(e.mediaId)&&(j.add(e.mediaId),t.mainConnection?.id===e.connectionId)){let B={kind:"video",codec:this.parameters?.codec??i.DefaultVideoCodec,ref:this.#F?.uid,uid:this.uid};this.parameters?.customType&&(B.customType=this.parameters.customType),await t.request("StartMedia",{media_id:e.mediaId,properties:B}).catch(C=>p(`StartMedia got rejected; ${C}`))}}async stop(t,e){this.#x&&W(this.#x),this.#A.get(e.connectionId)?.delete(e.mediaId)&&t.mainConnection?.id===e.connectionId&&await t.request("StopMedia",{media_id:e.mediaId}).catch(B=>p(`StopMedia got rejected; ${B}`))}async dump(){let t=[];for(let[e,j]of this.#A)t.push(`${e} => ${Array.from(j.values()).join(",")}`);return{uid:this.uid,ref:this.#F?.uid??null,customType:this.customType??null,tracks:this.#x?.getVideoTracks().map(e=>({id:e.id,kind:e.kind,label:e.label,ready:e.readyState,muted:e.muted,settings:{...e.getSettings()}}))??[],volume:this.#F?.volume??0,medias:t}}close(){this.#x&&W(this.#x),this.audioCapture?.close(),this.#F=void 0}};u();import{Backend as qB}from"@4players/odin-common";var H=class{constructor(t,e,j){this.controller=t;this.uid=e;this.customType=j}get volume(){return this.controller.playbackGetVolume(this.uid)}get activity(){return this.controller.playbackGetActivity(this.uid)}get jitterStats(){return this.controller.playbackGetJitterStats(this.uid)}start(t){o(`starting audio playback media ${t.mediaId} on connection ${t.connectionId}`),this.controller.playbackStart(this.uid,t)}stop(t){o(`stopping audio playback media ${t.mediaId} on connection ${t.connectionId}`),this.controller.playbackStop(this.uid,t)}setVolume(t){a(`updating audio playback media '${this.uid}' volume to ${t}`),this.controller.playbackSetVolume(this.uid,t)}close(){a(`closing audio playback media '${this.uid}'`),this.controller.closePlayback(this.uid)}};function kF(v,t){let e=v.audioContext;if(typeof e.setSinkId=="function"){v.connectOutput(e.destination);let j,B=()=>{if(e.state==="running"&&j!==void 0){let C=j;j=void 0,e.setSinkId(C).catch(E=>k("failed to apply deferred sinkId",E))}};return e.addEventListener("statechange",B),{async setSinkId(C){if(e.state!=="running"){j=C;return}await e.setSinkId(C)},dispose(){e.removeEventListener("statechange",B)}}}if(t&&typeof document<"u"&&typeof HTMLAudioElement<"u"&&typeof HTMLAudioElement.prototype.setSinkId=="function"){let j=e.createMediaStreamDestination();v.connectOutput(j);let B=new Audio;B.srcObject=j.stream,B.muted=!1,B.volume=1;let C=!1,E=!1,f={once:!0,passive:!0,capture:!0},s=()=>{E=!1,h()},b=()=>{E||C||(E=!0,document.addEventListener("pointerdown",s,f),document.addEventListener("keydown",s,f))},d=()=>{E&&(E=!1,document.removeEventListener("pointerdown",s,!0),document.removeEventListener("keydown",s,!0))},h=()=>{C||B.play().catch(Dx=>{C||(Dx instanceof DOMException&&Dx.name==="NotAllowedError"?b():k("failed to start playback audio element",Dx))})},Bx=()=>{e.state==="running"&&B.paused&&h()};return e.addEventListener("statechange",Bx),h(),{async setSinkId(Dx){await B.setSinkId(Dx)},dispose(){C=!0,d(),e.removeEventListener("statechange",Bx),B.pause(),B.srcObject=null,B.removeAttribute("src");try{B.load()}catch{}j.disconnect()}}}return v.connectOutput(e.destination),{async setSinkId(){},dispose(){}}}var ox=class{constructor(t){this.audioContextFactory=t;this.entries=[]}async acquire(t){for(let j of this.entries){if(j.sampleRate===t)return j.references+=1,j.audioContext;if(j.sampleRate===void 0&&j.audioContext.sampleRate===t)return j.references+=1,j.audioContext}let e={sampleRate:t,audioContext:await this.audioContextFactory(t),references:1};return this.entries.push(e),e.audioContext}async release(t){let e=this.entries.findIndex(j=>j.audioContext===t);if(!(e<0)&&(this.entries[e].references-=1,this.entries[e].references<=0)){let j=this.entries[e].audioContext;this.entries.splice(e,1),await j.close()}}close(){for(let t of this.entries)t.audioContext.close()}},ax=class v{constructor(t,e,j=!1){this.audioContexts=t;this.sink=e;this.enableHTMLAudioElementFallback=j;this.audioCaptures=[];this.videoCaptures=[];this.globalVolume=[1,1];this.playbacks=new Map;this.setPlaybackStrand=new lF}async create(t,e){return new v(t,e)}receivePacket(t,e){this.playbackWorker?.receivePacket(t,e)}receiveMonitoredPacket(t,e){let j=e.slice();this.receivePacket(t,j)}async createAudioPlayback(t){let e=this.playbacks.get(t.uid),j=t.volume;if(e===void 0){j=j??[1,1];let B=new H(this,t.uid,t.customType);e={id:void 0,volume:j,playback:B},this.playbacks.set(t.uid,e)}return j!==void 0&&e.playback.setVolume(j),e.playback}async createAudioCapture(t){let e=new N(this,t);return await e.setDevice(t),this.audioCaptures.push(new WeakRef(e)),e}async createVideoCapture(t,e){let j=new I(this,e);return await j.setDevice(t),this.videoCaptures.push(new WeakRef(j)),j}playbackSetDevice(t){return this.setPlaybackStrand.enqueue(async()=>{let e=t?.device.deviceId??"";if(e==="default"&&(e=""),this.playbackWorker===void 0){let j=await this.audioContexts.acquire(48e3);this.playbackWorker=await w0(j),this.playbackSink=kF(this.playbackWorker,this.enableHTMLAudioElementFallback),this.playbackWorker.setGlobalVolume(this.globalVolume);for(let[,B]of this.playbacks)B.id!==void 0&&this.playbackWorker.addMedias(B.id.connectionId,[B.id.mediaId],B.volume)}if(t&&this.playbackSink!==void 0)try{await this.playbackSink.setSinkId(e)}catch(j){k("failed to set playback sink",j)}})}playbackSetGlobalVolume(t){this.globalVolume=t,this.playbackWorker?.setGlobalVolume(this.globalVolume)}playbackStart(t,e){let j=this.playbacks.get(t);j!==void 0&&(j.id!==void 0&&this.playbackStop(t,j.id),j.id=e,this.playbackWorker?.addMedias(e.connectionId,[e.mediaId],j.volume))}playbackStop(t,e){let j=this.playbacks.get(t);j!==void 0&&(j.id!==e&&k(`playback media ${e.mediaId} on connection ${e.connectionId} is out of sync`,j.id,e),j.id=void 0,this.playbackWorker?.removeMedias(e.connectionId,[e.mediaId]))}playbackGetActivity(t){let e=this.playbacks.get(t);return e?.id===void 0?_:this.playbackWorker?.getActivity(e.id)??_}playbackGetJitterStats(t){let e=this.playbacks.get(t);return e?.id===void 0?J0:this.playbackWorker?.getJitterStats(e.id)??J0}playbackSetVolume(t,e){let j=this.playbacks.get(t);j!==void 0&&(j.volume=e,j.id!==void 0&&this.playbackWorker?.setVolume(j.id,j.volume))}playbackGetVolume(t){return this.playbacks.get(t)?.volume??[1,1]}closePlayback(t){let e=this.playbacks.get(t);e!==void 0&&(e.id!==void 0&&this.playbackStop(t,e.id),this.playbacks.delete(t))}close(){this.playbackSink?.dispose(),this.playbackSink=void 0,this.playbackWorker?.close(),this.audioContexts.close()}async dump(){let t=[];for(let B of this.audioCaptures){let C=B.deref();C!==void 0&&t.push(await C.dump())}let e=[];for(let B of this.videoCaptures){let C=B.deref();C!==void 0&&e.push(await C.dump())}let j=[];for(let[B,C]of this.playbacks)j.push({uid:B,id:C.id||null,volume:C.volume});return{globalVolume:this.globalVolume,playbackWorker:await this.playbackWorker?.dump()||null,audioCaptures:t,videoCaptures:e,playbacks:j}}},L=class{constructor(t,e=!1){this.device=t;this.isDefault=e}get type(){switch(this.device.kind){case"audioinput":return"AudioCapture";case"audiooutput":return"AudioPlayback";default:uF(!1,"not supported device")}}get id(){return this.device.deviceId}get name(){return this.device.name}};u();import{nextTick as zF,success as xA}from"@4players/odin-common";import{decode as XF}from"@msgpack/msgpack";u();import{Backend as GB}from"@4players/odin-common";u();import{Backend as A,failure as kx,success as K0,CONNECTION_STATS_INITIAL as LF}from"@4players/odin-common";import{MainCommandsRpc as HF,MainNotificationsRpc as PF,RoomCommandsRpc as NF,RoomNotificationsRpc as wF}from"@4players/odin-common/api";u();import{failure as x0,success as A0}from"@4players/odin-common";import{MessagePackRpcSchema as cF,parseRequest as O0,parseResponse as dF}from"@4players/odin-common/api";import{encode as pF,decode as hF}from"@msgpack/msgpack";var U=class{constructor(t){this.stream=t;this._SendQueue=[];this._RecvQueue=[];this._EventQueue=[];this._Requests=new Map;this._Close=new AbortController;this._NextId=1;t instanceof WebSocket?(t.addEventListener("open",this._OnWebSocketOpen.bind(this)),t.addEventListener("close",this.close.bind(this)),t.addEventListener("message",e=>this._OnRpcMessage(e.data)),t.binaryType="arraybuffer"):(qF(t.readable.getReader(),this._OnRpcMessage.bind(this)).finally(this.close.bind(this)),this._Writer=t.writable.getWriter()),this._Close.signal.addEventListener("abort",this._Cleanup.bind(this),{once:!0})}get closed(){return this._Close.signal.aborted}get closeSignal(){return this._Close.signal}async request(t,e,j){if(this.closed)return Promise.resolve("closed");let B=this._NextId,C=j===void 0?void 0:setTimeout(()=>this._TimeoutRequest(B),j);return this._Send([0,B,t,e]),new Promise(E=>{this._Requests.set(B,{accept:E,timeoutId:C}),this._NextId+=1})}notify(t,e){this.closed||this._Send([2,t,e])}recv(){if(this.closed)return Promise.resolve("closed");let t=this._EventQueue.shift();return t!==void 0?Promise.resolve(t):new Promise(e=>this._RecvQueue.push(e))}close(){this._Close.abort()}_TimeoutRequest(t){let e=this._Requests.get(t);e!==void 0&&(this._Requests.delete(t),clearTimeout(e.timeoutId),e.accept("timeout"))}_Send(t){let e;t instanceof Uint8Array?e=t:e=new Uint8Array(pF(t,{ignoreUndefined:!0,forceFloat32:!0})),this.stream instanceof WebSocket?this.stream.send(e):this._Writer.write(e).catch(()=>{})}_OnWebSocketOpen(t){for(let e of this._SendQueue)this._Send(e);this._SendQueue.length=0}_OnRpcMessage(t){let e=mF(t);if(e.type!=="Success"){this.close();return}switch(e.value[0]){case 0:this._Send([1,e.value[1],"not supported",null]);break;case 1:this._OnResponse(e.value[1],e.value[2],e.value[3]);break;case 2:this._OnEvent(e.value[1],e.value[2]);break}}_OnResponse(t,e,j){let B=this._Requests.get(t);B!==void 0&&(clearTimeout(B.timeoutId),B.accept(e===null?A0(j):x0(e)))}_OnEvent(t,e){let j=this._RecvQueue.shift();j!==void 0?j({name:t,properties:e}):this._EventQueue.push({name:t,properties:e})}_Cleanup(){for(let t of this._Requests.values())clearTimeout(t.timeoutId),t.accept("closed");this._Requests.clear();for(let t of this._RecvQueue)t("closed");this._RecvQueue.length=0,this._SendQueue.length=0,this.stream instanceof WebSocket?this.stream.close():this._Writer?.close().catch(()=>{})}},K=class{constructor(t,e,j){this.rpc=t;this._Commands=e;this._Events=j}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(t,e,j){e=O0(t,e,this._Commands);let B=await this.rpc.request(t,e,j);if(B==="closed"||B==="timeout"||B.type==="Failure")return B;let C=dF(t,B.value,this._Commands);return C!==void 0?A0(C):x0("response schema failed validation")}notify(t,e){e=O0(t,e,this._Commands),this.rpc.notify(t,e)}async recv(){let t=await this.rpc.recv();if(t==="closed")return t;let e=F0(this._Events,t);return e!==void 0?e:(S0(this._Events,t.name)?(p(`schema validation for ${t.name} failed; closing connection`),this.rpc.close()):k(`dropping unknown event ${t.name}`),"closed")}close(){this.rpc.close()}};function mF(v){try{return A0(cF.parse(hF(new Uint8Array(v))))}catch(t){return x0(String(t))}}function F0(v,t){if(!S0(v,t.name))return;let e=v[t.name].safeParse(t.properties);if(e.success)return{name:t.name,properties:e.data}}function S0(v,t){return t in v}async function qF(v,t){let e=new Uint8Array;for(;;){let j=a0(e,0);if(j===n){v.cancel("protocol violation");break}if(j!==$&&j<=e.length){t(e.subarray(0,j)),e=e.subarray(j);continue}let B;try{B=await v.read()}catch{break}if(B.done)break;e=GF(e,B.value)}e.length>0&&k("unprocessed bytes left in rpc stream",e)}function GF(v,t){if(v.length===0)return t;if(t.length===0)return v;let e=new Uint8Array(v.length+t.length);return e.set(v,0),e.set(t,v.length),e}u();import{failure as lx,fromBase64Url as $F,success as yF}from"@4players/odin-common";import{TokenClaimsSchema as IF}from"@4players/odin-common/api";var g=class v{constructor(t,e){this.text=t;this.claims=e;if(e.ups!==void 0){let j=v.parse(e.ups);j.type==="Success"?this._Upstream=j.value:p(`upstream in token can not be parsed; ${j.reason}`)}}static parse(t){let e=t.split(".");if(e.length!==3)return lx("expected three segments");let j=$F(e[1]);if(j.type==="Failure")return lx(`invalid token; ${j.reason}`);let B;try{B=JSON.parse(j.value)}catch(E){return lx(`invalid token; ${E}`)}let C=IF.safeParse(B);return C.success===!1?lx(`invalid token; ${C.error}`):yF(new v(t,C.data))}get timeLeft(){return this.claims.exp===void 0?1/0:this.claims.exp*1e3-Date.now()}get upstream(){return this._Upstream}get defaultRoomId(){return Array.isArray(this.claims.rid)?this.claims.rid.length===1?this.claims.rid[0]:void 0:this.claims.rid}hasAudience(t){return this.claims.aud===void 0&&t==="gateway"?!0:Array.isArray(this.claims.aud)?this.claims.aud.includes(t):this.claims.aud===t}toString(){return this.text}};u();import{VideoCodec as gF,assert as U0}from"@4players/odin-common";function T0(v){typeof globalThis.rtcDataChannels>"u"&&(globalThis.rtcDataChannels=[]),Array.isArray(globalThis.rtcDataChannels)&&globalThis.rtcDataChannels.length<=100&&globalThis.rtcDataChannels.push(v)}function M0(v){let t=globalThis.rtcDataChannels?.indexOf(v);t!==void 0&&t>=0&&globalThis.rtcDataChannels.splice(t,1),v.readyState!=="closed"&&v.close()}function ux(v){typeof globalThis.rtcPeerConnections>"u"&&(globalThis.rtcPeerConnections=[]),Array.isArray(globalThis.rtcPeerConnections)&&globalThis.rtcPeerConnections.length<=100&&globalThis.rtcPeerConnections.push(v)}function R0(v){let t=globalThis.rtcPeerConnections?.indexOf(v);t!==void 0&&t>=0&&globalThis.rtcPeerConnections.splice(t,1),v.connectionState!=="closed"&&v.close()}var xx=class{constructor(t,e,j){this._localVideos=new Map;this._remoteVideos=new Map;this._freeLocalVideoTransceivers=[];this._negotiationRequested=!1;this._negotiationRunning=!1;this._negotiationCounter=0;this._pendingRemoteCandidates=[];this._WebRtcStatsSnapshot=null;this._peerConnection=t,this._signaling=e,this._answerTimeout=j?.answerTimeout??i.WebRtcAnswerTimeout,this._maxNegotiationAttempts=j?.maxNegotiationAttempts??i.WebRtcMaxNegotiationAttempts,this._peerConnection.ontrack=this._onTrack.bind(this),this._peerConnection.onconnectionstatechange=()=>this._onStatusChanged(),this._peerConnection.onicecandidate=B=>{(B.candidate?this._signaling.sendIceCandidate(B.candidate):this._signaling.sendIceComplete()).catch(E=>{k("failed to send local ice candidate",E)})},this._WebRtcStatsInterval=setInterval(()=>{this._snapshotStats()},i.WebRtcStatsSnapshotInterval)}requestNegotiation(){this._negotiationRequested=!0,!this._negotiationRunning&&(this._negotiationRunning=!0,setTimeout(async()=>{let t=0;for(;this._negotiationRequested;){this._negotiationRequested=!1;try{await this._negotiate(),t=0}catch(e){if(t+=1,p(`negotiation failed during sdp offer/answer exchange (attempt ${t})`,e),t<this._maxNegotiationAttempts)this._negotiationRequested=!0;else{this._negotiationRunning=!1,this._signaling.closeConnection().catch(()=>{});return}}}this._negotiationRunning=!1}))}async startLocalVideo(t,e,j){if(this._localVideos.has(t))return;o(`starting local video for media ${t}`);let B=this._freeLocalVideoTransceivers.pop();if(B?(await B.sender.replaceTrack(e),B.direction="sendrecv"):B=this._peerConnection.addTransceiver(e),j){let f=B.sender.getParameters(),{maxBitrate:s,maxFramerate:b,scaleResolutionDownBy:d}=j,h={...s!==void 0&&{maxBitrate:s},...b!==void 0&&{maxFramerate:b},...d!==void 0&&{scaleResolutionDownBy:d}};if(f.encodings.length===0)f.encodings.push(h);else for(let Bx of f.encodings)Object.assign(Bx,h);j.degradationPreference&&(f.degradationPreference=j.degradationPreference),await B.sender.setParameters(f)}let E=new gF(j?.codec??i.DefaultVideoCodec).isSupported();E&&B.setCodecPreferences([E]),this._localVideos.set(t,{transceiver:B}),this.requestNegotiation()}stopLocalVideo(t){let e=this._localVideos.get(t);e&&(o(`stopping local video for media ${t}`),this._localVideos.delete(t),e.transceiver.sender.track&&(e.transceiver.sender.track.enabled=!1),e.transceiver.direction="inactive",e.transceiver.sender.replaceTrack(null).catch(()=>{}),this._freeLocalVideoTransceivers.push(e.transceiver),this.requestNegotiation())}startRemoteVideo(t){o(`starting remote video for media ${t}`);let e=this._peerConnection.addTransceiver("video",{direction:"recvonly"}),j=new Promise((B,C)=>{this._remoteVideos.set(t,{state:"Requested",transceiver:e,promise:{resolve:B,reject:C}})});return this.requestNegotiation(),j}stopRemoteVideo(t){let e=this._remoteVideos.get(t);if(e){o(`stopping remote video for media ${t}`),this._remoteVideos.delete(t),e.state!=="Active"&&e.promise.reject(new Error("video stopped"));try{e.transceiver.stop()}catch{}this.requestNegotiation()}}async handleWebRtcUpdate(t){try{switch(t.kind){case"Sdp":await this._updateRemoteSdp(t.type==="Answer"?"answer":"offer",t.sdp,t.media_map,t.negotiation_id);break;case"Trickle":this._addIceCandidate({candidate:t.candidate,sdpMid:t.spd_mid??void 0,sdpMLineIndex:t.spd_mline_index??void 0,usernameFragment:t.username_fragment??void 0});break;case"TrickleFinished":this._addIceCandidate(void 0);break}}catch(e){p("failed to handle webrtc update",e,t)}}startup(){this._peerConnection.connectionState==="new"&&this.requestNegotiation()}cleanup(){for(let[,t]of this._remoteVideos)t.state!=="Active"&&t.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 t=await this._peerConnection.getStats(),e={},j={bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,rtt:0};t.forEach(B=>{let{type:C,...E}=B;C!=="certificate"&&(C==="candidate-pair"&&B.nominated&&(j.bytesSent+=B.bytesSent??0,j.bytesReceived+=B.bytesReceived??0,j.packetsSent+=B.packetsSent??0,j.packetsReceived+=B.packetsReceived??0,j.rtt=B.currentRoundTripTime??0),e[C]||(e[C]=[]),e[C].push(E))}),this._WebRtcStatsSnapshot={timestamp:Date.now(),status:this._peerConnection.connectionState,stats:j,report:e}}catch{}}_addIceCandidate(t){if(t&&(t.sdpMid===void 0&&t.sdpMLineIndex===void 0&&(t={...t,sdpMid:"0"}),a(`adding new ice ${t.candidate}`,t)),this._peerConnection.remoteDescription===null){this._pendingRemoteCandidates.push(t);return}this._applyIceCandidate(t)}_applyIceCandidate(t){this._peerConnection.addIceCandidate(t).catch(e=>{k("failed to add remote ice candidate",e,t)})}_flushPendingIceCandidates(){let t=this._pendingRemoteCandidates.splice(0);for(let e of t)this._applyIceCandidate(e)}async _negotiate(){let t=++this._negotiationCounter,e=await this._peerConnection.createOffer();U0(e.type==="offer"&&e.sdp,"generated broken payload"),await this._peerConnection.setLocalDescription(e);let j=[];for(let[C,{transceiver:E}]of this._localVideos)E.mid&&j.push([C,E.mid]);for(let[C,E]of this._remoteVideos)E.state!=="Active"&&E.transceiver.mid&&j.push([C,E.transceiver.mid]);let B=new Promise((C,E)=>{this._pendingAnswer={negotiationId:t,resolve:C,reject:E}});try{await this._signaling.sendOffer(e.sdp,j,t),await _F(B,this._answerTimeout,`timed out waiting for answer to offer ${t}`)}finally{this._pendingAnswer=void 0}}async _updateRemoteSdp(t,e,j,B){if(t==="offer"){k("ignoring unexpected sdp offer from server");return}let C=this._pendingAnswer;if(C===void 0){k("ignoring sdp answer without pending negotiation");return}if(B!==void 0&&B!==C.negotiationId){k(`ignoring stale sdp answer for negotiation ${B}; current is ${C.negotiationId}`);return}if(this._peerConnection.signalingState!=="have-local-offer"){k(`ignoring sdp answer in signaling state ${this._peerConnection.signalingState}`);return}for(let[E,f]of j){let s=this._remoteVideos.get(E);s?.state==="Requested"&&(this._remoteVideos.set(E,{state:"Mapped",transceiver:s.transceiver,mid:f,promise:s.promise}),a(`updated remote video list with media ${E}`,s,this._remoteVideos))}try{await this._peerConnection.setRemoteDescription({type:t,sdp:e})}catch(E){C.reject(E);return}this._flushPendingIceCandidates(),C.resolve()}async _onStatusChanged(){switch(a(`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":i.MainConnectionPingInterval!==void 0&&await this._signaling.checkConnection();default:this._WebRtcIceTimeout===void 0&&(this._WebRtcIceTimeout=setTimeout(()=>{a("ice connection timeout was reached"),this._peerConnection.restartIce(),this._WebRtcIceTimeout=void 0},i.WebRtcIceTimeout)),this._WebRtcTimeout===void 0&&(this._WebRtcTimeout=setTimeout(async()=>{a("peer connection timeout was reached"),await this._signaling.closeConnection()},i.WebRtcTimeout));break}}_onTrack(t){let e=Array.from(this._remoteVideos).find(([,C])=>C.state==="Mapped"&&C.mid===t.transceiver.mid);if(!e){k(`unexpected track with mid: ${t.transceiver.mid}`);return}let[j,B]=e;U0(B.state==="Mapped","expected video state to be Mapped"),this._remoteVideos.set(j,{state:"Active",transceiver:t.transceiver}),a(`updated local video list with media ${j}`,e,t.transceiver,this._localVideos),t.track.onended=()=>{a(`video track with mid ${t.transceiver.mid} ended`,e)},B.promise.resolve(t.track)}};function _F(v,t,e){return new Promise((j,B)=>{let C=setTimeout(()=>B(new Error(e)),t);v.then(E=>{clearTimeout(C),j(E)},E=>{clearTimeout(C),B(E)})})}var cx=class v{constructor(t,e,j,B,C,E,f){this.id=t;this.address=e;this.connection=B;this.datagramWritable=C;this.rpc=E;this.closeController=f;this._ConnectionStats={...LF};this._WebRtcSessionFlight=new M;this._PingFlight=new M;this.status=0;this._ClosePromise=(async()=>{try{await this.connection.closed}catch{}return"closed"})(),i.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(i.HealthCheckTimeout)},i.MainConnectionPingInterval)),f.signal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this.datagramWriter=C.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,(s,b)=>{this._ConnectionStats.packetsReceived+=1,j(s,b)})}static async create(t,e,j,B){try{let C=new URL(`https://${e}?version=${u0}&uid=${dx}`),E=new AbortController;B.addEventListener("abort",()=>E.abort(),{once:!0});let f=new WebTransport(C);E.signal.addEventListener("abort",()=>{try{f.close()}catch{}},{once:!0}),await f.ready;let s=f.datagrams,b=s?.createWritable?.()??s?.writable;if(!b)return E.abort(),kx(`connecting to ${e} failed because WebTransport datagrams are not supported by this browser`);let d=await f.createBidirectionalStream(),h=new K(new U(d),HF,PF);return E.signal.addEventListener("abort",()=>h.close(),{once:!0}),h.notify("Hello",{stream:"main"}),K0(new v(t,e,j,f,b,h,E))}catch(C){return kx(`connecting to ${e} failed with ${C}`)}}get connectionStats(){return this._ConnectionStats}get transport(){return"H3"}get closePromise(){return this._ClosePromise}get closeSignal(){return this.closeController.signal}get closed(){return this.closeSignal.aborted}waitForConnected(){return Promise.race([this.connection.ready,this.connection.closed.then(()=>{throw new Error("connection closed")})])}close(){o(`closing connection to '${this.address}' with id ${this.id}`),this.closeController.abort("request")}async joinRoom(t,e,j,B){try{if(this.closed)return"closed";let C=await this.connection.createBidirectionalStream().catch(()=>"closed");if(C==="closed")return"closed";let E=new K(new U(C),NF,wF),f=await E.request("Hello",{stream:"room",token:String(t),room_id:e,user_data:j,position:B});return f==="closed"||f.type==="Failure"?f:K0(E.rpc)}catch(C){return kx(`JoinRoom failed; ${C}`)}}async getReconnectToken(t){let e=await this._Request("RequestReconnectToken",{peer_id:t});return e.type==="Failure"?e:g.parse(e.value)}async getRtcStats(){return this._PeerConnection?.getStats()}async healthCheck(){let t=await this._RequestPing(i.HealthCheckTimeout);return t||this.close(),t}async ping(t=3e4){let e=Date.now();return await this._RequestPing(t)?Date.now()-e:0}sendDatagram(t){if(!this.closed)try{this.datagramWriter.write(t).catch(()=>{}),this._ConnectionStats.packetsSent+=1;let e=t.byteLength;this.connectionStats.bytesSent+=e}catch{}}async readDatagrams(t,e,j){try{let B=t.datagrams.readable.getReader();for(;;){let C=await B.read();if(C.done)break;let E=C.value.byteLength;this.connectionStats.bytesReceived+=E,j(e,C.value)}}catch{}}_CleanUp(){a(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId)}async _EnsureWebRtcSession(){return this._WebRtcSession?this._WebRtcSession:this._WebRtcSessionFlight.run(async()=>(this._PeerConnection=new RTCPeerConnection,ux(this._PeerConnection),this._WebRtcSession=new xx(this._PeerConnection,{sendOffer:async(t,e,j)=>{let B=await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:t,media_map:e,negotiation_id:j});if(B.type==="Failure")throw new Error(`failed to send sdp offer; ${B.reason}`)},sendIceCandidate:async t=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:t.candidate,spd_mid:t.sdpMid??void 0,spd_mline_index:t.sdpMLineIndex??void 0,username_fragment:t.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async()=>{this._PeerConnection?.restartIce(),this._WebRtcSession?.requestNegotiation()},checkConnection:async()=>{}}),this._HandleWebRtcUpdates(),this._WebRtcSession))}async _HandleWebRtcUpdates(){for(;;){let t=await this.rpc.recv();if(t==="closed")break;t.name==="WebRtcUpdate"&&this._WebRtcSession?.handleWebRtcUpdate(t.properties)}this.close()}async _Request(t,e,j){let B=Date.now(),C=await(j===void 0?this.rpc.request(t,e):this.rpc.request(t,e,j)),E=(Date.now()-B)/1e3;return t!=="Ping"&&a(`sent main rpc '${t}'; took: ${E}s`,{properties:e,timeout:j,result:C}),C==="closed"?kx("connection lost"):C}_RequestPing(t=3e4){return this._PingFlight.run(async()=>{let e=await this._Request("Ping",{},t);return e!=="timeout"&&e.type==="Success"})}async startLocalVideo(t,e,j){await(await this._EnsureWebRtcSession()).startLocalVideo(t,e,j)}stopLocalVideo(t){this._WebRtcSession?.stopLocalVideo(t)}async startRemoteVideo(t){return(await this._EnsureWebRtcSession()).startRemoteVideo(t)}stopRemoteVideo(t){this._WebRtcSession?.stopRemoteVideo(t)}async dump(){return{type:"H3",id:this.id,address:this.address,closed:this.closed,status:this.status,datagrams:{sent:this._ConnectionStats.packetsSent,received:this._ConnectionStats.packetsReceived},webRtc:{signalingState:this._PeerConnection?.signalingState??null,connectionState:this._PeerConnection?.connectionState??null,iceGatheringState:this._PeerConnection?.iceGatheringState??null,iceConnectionState:this._PeerConnection?.iceConnectionState??null,connectionStats:this._WebRtcSession?.stats??null}}}};u();import{Backend as F,extendUrl as W0,failure as px,success as Q0,fail as TF,CONNECTION_STATS_INITIAL as MF}from"@4players/odin-common";import{MainCommandsRpc as RF,MainNotificationsRpc as KF}from"@4players/odin-common/api";u();import{abortableSleep as JF,failure as tx,success as OF}from"@4players/odin-common";async function r0(v,t){let e=performance.now(),j=tx("no connection was attempted");for(let B=0;B<i.ConnectInterval.length&&!t.aborted;B++){let C=e+UF(B);if(await JF(C-performance.now(),t)==="aborted")return tx("aborted");if(j=await SF(v,t),j.type==="Success")return j}return j}async function SF(v,t){let e;try{e=new WebSocket(v)}catch(s){return tx(`unable to create websocket; ${s}`)}let j=new AbortController,B=new Promise(s=>e.addEventListener("open",()=>s(OF(e)),{signal:j.signal})),C=new Promise(s=>e.addEventListener("close",b=>s(tx(b.reason!==""?b.reason:"unable to establish websocket connection")),{signal:j.signal})),E=new Promise(s=>t.addEventListener("abort",()=>s(tx("aborted")),{signal:j.signal})),f=await Promise.race([B,C,E]);return j.abort(),f}function UF(v){let t=i.ConnectInterval.slice(0,v).reduce((j,B)=>j+B,0),e=i.ConnectInterval[v]*Math.random();return t+e}var hx=class v{constructor(t,e,j,B,C,E){this.id=t;this.address=e;this.url=j;this.onDatagram=B;this.connection=C;this.webRtc=E;this._PeerIdMap=new WeakMap;this._ConnectionStats={...MF};this._PingFlight=new M;o(`creating new webrtc connection to '${this.address}' with id ${this.id}`),this.closeSignal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this._ClosePromise=new Promise(f=>{this.closeSignal.addEventListener("abort",()=>{f("closed")},{once:!0})}),ux(E),this._AudioChannel=this.webRtc.createDataChannel("audio",{id:2,negotiated:!0,ordered:!1,maxRetransmits:0}),this._AudioChannel.binaryType="arraybuffer",this._AudioChannel.onmessage=f=>{this._ConnectionStats.packetsReceived++;let s=new Uint8Array(f.data);this._ConnectionStats.bytesReceived+=s.byteLength,this.onDatagram(this.id,s)},this._AudioChannel.onerror=f=>k(`webrtc audio data channel for connection with id ${t} raised an error`,f),this._AudioChannel.onclosing=f=>o(`webrtc audio data channel for connection with id ${t} begins shutting down`,f),this._AudioChannel.onclose=f=>o(`webrtc audio data channel for connection with id ${t} has closed`,f),T0(this._AudioChannel),this._WebRtcSession=new xx(this.webRtc,{sendOffer:async(f,s,b)=>{let d=await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:f,media_map:s,negotiation_id:b});if(d.type==="Failure")throw new Error(`failed to send sdp offer; ${d.reason}`)},sendIceCandidate:async f=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:f.candidate,spd_mid:f.sdpMid??void 0,spd_mline_index:f.sdpMLineIndex??void 0,username_fragment:f.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async()=>{this.close()},checkConnection:async()=>{this.healthCheck().then()}}),this._WebRtcSession.startup(),i.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(i.HealthCheckTimeout)},i.MainConnectionPingInterval)),this._HandleWebRtcUpdates()}static async create(t,e,j,B){if(B.aborted)return px("aborted");let C;try{C=new URL(`wss://${e}`)}catch(b){return TF(`address in token(${e}) can not be parsed; ${b}`)}let E=W0(C,`main?uid=${dx}`);if(E.type!=="Success")return E;let f=await r0(E.value,B);if(f.type!=="Success")return f;let s=new K(new U(f.value),RF,KF);try{return Q0(new v(t,e,C,j,s,new RTCPeerConnection))}catch(b){return s.close(),px(`unable to create webrtc connection; ${b}`)}}get status(){switch(this.webRtc.connectionState){case"connected":return 1;case"failed":case"closed":return 2;default:return 0}}get connectionStats(){return this._ConnectionStats}get transport(){return"WebRTC"}get closePromise(){return this._ClosePromise}get closeSignal(){return this.connection.closeSignal}get closed(){return this.connection.closed}async waitForConnected(){return new Promise((t,e)=>{let j=()=>{let B=this.status;B!==0&&(this.webRtc.removeEventListener("connectionstatechange",j),B===1?t():e(new Error("connection closed")))};this.webRtc.addEventListener("connectionstatechange",j),j(),this.closePromise.then(()=>{e(new Error("connection closed"))})})}close(){o(`closing ${this.transport} connection to '${this.address}' with id ${this.id}`),this.connection.close()}async joinRoom(t,e,j,B){let C=await this.connection.request("JoinRoom",{token:String(t),room_id:e,user_data:j,position:B});if(C==="closed"||C.type==="Failure")return C;let E=C.value;if(!("token"in E))return px("JoinRoom responded without token");let f=W0(this.url,`room?token=${E.token}`);if(f.type==="Failure")return f;let s=await r0(f.value,this.closeSignal);return s.type==="Success"?(this._PeerIdMap.set(s.value,E.peer_id),Q0(new U(s.value))):s}async getReconnectToken(t){let e=await this._Request("RequestReconnectToken",{peer_id:t});return e.type==="Failure"?e:g.parse(e.value)}async getRtcStats(){return this.webRtc.getStats()}async healthCheck(){let t=await this._RequestPing(i.HealthCheckTimeout);return t||this.close(),t}async ping(t=3e4){let e=Date.now();return await this._RequestPing(t)?Date.now()-e:0}sendDatagram(t){if(this._AudioChannel.readyState==="open"){let e=t.byteLength;this._AudioChannel.send(t),this._ConnectionStats.packetsSent+=1,this._ConnectionStats.bytesSent+=e}}_CleanUp(){a(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId),M0(this._AudioChannel),R0(this.webRtc),this._WebRtcSession.cleanup(),this.connection.close()}async _HandleWebRtcUpdates(){for(;;){let t=await this.connection.recv();if(t==="closed")break;t.name==="WebRtcUpdate"&&this._WebRtcSession.handleWebRtcUpdate(t.properties)}this.close()}async _Request(t,e,j){let B=Date.now(),C=await(j===void 0?this.connection.request(t,e):this.connection.request(t,e,j)),E=(Date.now()-B)/1e3;return t!=="Ping"&&a(`sent main rpc '${t}'; took: ${E}s`,{properties:e,timeout:j,result:C}),C==="closed"?px("connection lost"):C}_RequestPing(t=3e4){return this._PingFlight.run(async()=>{let e=await this._Request("Ping",{},t);return e!=="timeout"&&e.type==="Success"})}async startLocalVideo(t,e,j){await this._WebRtcSession.startLocalVideo(t,e,j)}stopLocalVideo(t){this._WebRtcSession.stopLocalVideo(t)}async startRemoteVideo(t){return this._WebRtcSession.startRemoteVideo(t)}stopRemoteVideo(t){this._WebRtcSession.stopRemoteVideo(t)}async dump(){return{type:"WebRtc",id:this.id,address:this.address,url:this.url.toString(),closed:this.closed,audioChannel:{readyState:this._AudioChannel.readyState,bufferedAmount:this._AudioChannel.bufferedAmount},datagrams:{sent:this.connectionStats.packetsSent,received:this.connectionStats.packetsReceived},webRtc:{signalingState:this.webRtc.signalingState,connectionState:this.webRtc.connectionState,iceGatheringState:this.webRtc.iceGatheringState,iceConnectionState:this.webRtc.iceConnectionState,connectionStats:this._WebRtcSession.stats}}}};function z0(v,t,e,j,B){switch(o(`creating ${t} main connection to '${e}'`),t){case"H3":return cx.create(v,e,j,B);case"WebRTC":return hx.create(v,e,j,B);default:throw new Error(`transport ${t} is not supported`)}}import{Backend as $B,failure as Y0,success as VF}from"@4players/odin-common";import{parseCommand as WF,parseNotification as QF,RoomCommandsRpc as X0,RoomNotificationsRpc as Z0}from"@4players/odin-common/api";u();var mx=class{constructor(t,e,j,B){this.id=t;this.connection=e;this.cipher=j;this.mediaMap=B;this._DatagramReceived=0;this._DatagramSent=0;this._DatagramReceivedInvalid=0;this._DatagramSentInvalid=0;e.closeSignal.addEventListener("abort",()=>this.close())}get connectionStats(){return this.connection.connectionStats}get transport(){return this.connection.transport}get address(){return this.connection.address}get status(){return this.closed?2:this.connection.status}get closePromise(){return this.connection.closePromise}get closeSignal(){return this.connection.closeSignal}get closed(){return this.connection.closed}waitForConnected(){return this.connection.waitForConnected()}close(){this.connection.close()}async joinRoom(t,e,j,B){this.cipher.reset();let C=await this.cipher.encryptUserData(j);if(C===n)return Y0("unable to encrypt initial user-data");let E=await this.connection.joinRoom(t,e,C,B);return E==="closed"||E.type==="Failure"?E:VF(new D0(E.value,this.cipher,this))}getReconnectToken(t){return this.connection.getReconnectToken(t)}getRtcStats(){return this.connection.getRtcStats()}healthCheck(){return this.connection.healthCheck()}async sendDatagram(t){let e=await this.cipher.encryptDatagram(t);e!==n?(this._DatagramSent+=1,this.connection.sendDatagram(e)):this._DatagramSentInvalid+=1}async decryptDatagram(t,e){let j=await this.cipher.decryptDatagram(t,e);return j!==n?this._DatagramReceived+=1:this._DatagramReceivedInvalid+=1,j}startLocalVideo(t,e,j){return this.connection.startLocalVideo(t,e,j)}stopLocalVideo(t){return this.connection.stopLocalVideo(t)}startRemoteVideo(t){return this.connection.startRemoteVideo(t)}stopRemoteVideo(t){return this.connection.stopRemoteVideo(t)}async dump(){return{type:"Encrypted",id:this.id,address:this.address,connectionId:this.connection.id,closed:this.closed,transport:this.transport,datagrams:{sent:this._DatagramSent,received:this._DatagramReceived,sentInvalid:this._DatagramSentInvalid,receivedInvalid:this._DatagramReceivedInvalid},cipher:await this.cipher.dump()}}},qx=class{constructor(t){this.room=t}resendUserData(){this.room.roomConnection?.notify("UpdatePeer",{user_data:this.room.roomConnection.userData})}setUserData(t,e){let j={kind:"UserDataChanged",peer_id:t,user_data:e};this.room.onEvent("PeerUpdated",j)}},D0=class{constructor(t,e,j){this.rpc=t;this.cipher=e;this.connection=j;this.peers=new Map;this.closeSignal.addEventListener("abort",this.cleanup.bind(this),{once:!0})}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(t,e,j){let B=await this.outgoing(t,e);return B===n?Y0("can not be encrypted"):await this.rpc.request(t,B,j)}async notify(t,e){let j=await this.outgoing(t,e);if(j!==n)return this.rpc.notify(t,j)}async recv(){for(;;){let t=await this.rpc.recv();if(t==="closed")return t;let e=await this.incoming(t.name,t.properties);if(e!==n)return{name:t.name,properties:e}}}close(){return this.rpc.close()}async outgoing(t,e){if(!(t in X0))return e;let j=WF(t,e,X0);if(j===void 0)return n;switch(j.name){case"UpdatePeer":{let B=await this.cipher.encryptUserData(j.request.user_data);if(B===n)return n;j.request.user_data=B}break;case"SendMessage":{let B=await this.cipher.encryptMessage(j.request.message);if(B===n)return n;j.request.message=B}break}return j.request}async incoming(t,e){if(!(t in Z0))return e;let j=QF(t,e,Z0);if(j===void 0)return n;switch(j.name){case"RoomUpdated":for(let B=0;B<j.properties.updates.length;B++){let C=await this.roomUpdate(j.properties.updates[B]);if(C===n)return n;j.properties.updates[B]=C}break;case"PeerUpdated":{let B=await this.peerUpdate(j.properties);if(B===n)return n;j.properties=B}break;case"MessageReceived":{let B=await this.cipher.decryptMessage(j.properties.sender_peer_id,j.properties.message);if(B===n)return n;j.properties.message=B}break}return j.properties}async peerUpdate(t){switch(t.kind){case"UserDataChanged":{let e=await this.cipher.decryptUserData(t.peer_id,t.user_data);if(e===n)return n;t.user_data=e}break;case"MediaStarted":this.mediaStarted(t.peer_id,t.media.id);break;case"MediaStopped":this.mediaStopped(t.peer_id,t.media_id);break}return t}async roomUpdate(t){switch(t.kind){case"Joined":for(let e of t.room.peers){for(let B of e.medias)this.mediaStarted(e.id,B.id);let j=await this.cipher.decryptUserData(e.id,e.user_data);j!==n?e.user_data=j:e.user_data=new Uint8Array}break;case"PeerJoined":{for(let j of t.peer.medias)this.mediaStarted(t.peer.id,j.id);let e=await this.cipher.decryptUserData(t.peer.id,t.peer.user_data);e!==n?t.peer.user_data=e:t.peer.user_data=new Uint8Array}break;case"PeerLeft":{let e=this.peers.get(t.peer_id);this.peers.delete(t.peer_id),this.cipher.deletePeerKey(t.peer_id);for(let j of e??[])this.mediaStopped(t.peer_id,j)}break}return t}mediaStarted(t,e){let j=this.peers.get(t);j===void 0&&(j=new Set,this.peers.set(t,j)),j.add(e);let B=q({connectionId:this.connection.connection.id,mediaId:e});this.connection.mediaMap.set(B,{peerId:t,connection:this.connection})}mediaStopped(t,e){this.peers.get(t)?.delete(e);let B=q({connectionId:this.connection.connection.id,mediaId:e});this.connection.mediaMap.delete(B)}cleanup(){for(let[t,e]of this.peers)for(let j of e)this.mediaStopped(t,j)}};var Gx=class{constructor(t){this.onDatagram=t;this._LastConnectionId=0;this._Connections=new Map;this._Close=new AbortController;this._MediaMap=new Map;let e=Date.now(),j=setInterval(()=>{Math.abs(Date.now()-e)>i.ClockJumpThreshold&&this.checkHealth(),e=Date.now()},i.ClockJumpCheckInterval);addEventListener("offline",()=>this.checkHealth(),{signal:this._Close.signal}),this._Close.signal.addEventListener("abort",()=>{clearInterval(j);for(let B of this._Connections.values())B.type==="establishing"?B.abort.abort():B.connection.close();this._Connections.clear()},{once:!0})}get closed(){return this._Close.signal.aborted}sendDatagram(t,e){let j=this._Connections.get(t);(j?.type==="established"||j?.type==="virtual")&&j.connection.sendDatagram(e)}async recvDatagram(t,e){let j=ZF(e);if(j===void 0||j.length===0)return;let B=this._MediaMap.get(q({connectionId:t,mediaId:j[0]}));if(B===void 0)this.onDatagram(t,e);else{let C=await B.connection.decryptDatagram(B.peerId,e);if(C===n)return;this.onDatagram(B.connection.id,C)}}async acquireConnection(t,e,j,B){if(await zF(),this.closed)return"closed";let C=this.findConnection(t,e),E;switch(C?.type){case"established":a(`reusing existing connection ${C.id}`),E=C;break;case"establishing":{a(`waiting for connecting to '${e}' finish`);let b=await C.finished;if(b.type!=="Success")return b;E=b.value}break;case void 0:{a(`connecting to '${e}'`);let b=await this.createConnection(t,e,B);if(b.type!=="Success")return b;E=b.value}break}let f=E.id,s=new t0(E.connection,()=>this.releaseConnection(f));return E.references+=1,j&&(s=new mx(++this._LastConnectionId,s,j,this._MediaMap),this.addConnection({type:"virtual",id:s.id,connection:s,createdAt:Date.now()})),xA(s)}async createConnection(t,e,j){let B=++this._LastConnectionId,C=Date.now(),E=new AbortController;j.addEventListener("abort",()=>E.abort(),{once:!0}),a(`creating new connection ${B}`);let f=z0(B,t,e,this.recvDatagram.bind(this),j),{promise:s,resolve:b}=Promise.withResolvers();this.addConnection({type:"establishing",id:B,address:e,transport:t,finished:s,createdAt:Date.now(),abort:E});let d=await f;if(this._Connections.delete(B),d.type!=="Success")return b(d),d;let h={type:"established",id:B,address:e,transport:t,createdAt:C,references:0,connection:d.value};return this.addConnection(h),xA(h)}addConnection(t){(t.type==="established"||t.type==="virtual")&&t.connection.closeSignal.addEventListener("abort",()=>{o(`connection ${t.id} has been closed`),this._Connections.delete(t.id)},{once:!0}),this._Connections.set(t.id,t)}releaseConnection(t){let e=this._Connections.get(t);e?.type==="established"&&(e.references-=1,e.references<=0&&e.connection.close())}checkHealth(){for(let t of this._Connections.values())t.type==="established"&&t.connection.healthCheck()}close(){this._Close.abort()}async dump(){let t=[];for(let j of this._Connections.values()){let B;switch(j.type){case"established":B={transport:j.transport,address:j.address,connection:await j.connection.dump(),references:j.references};break;case"establishing":B={transport:j.transport,address:j.address,aborted:j.abort.signal.aborted};break;case"virtual":B={connection:await j.connection.dump()};break}t.push({type:j.type,id:j.id,createdAt:j.createdAt,...B})}let e=[];for(let[j,B]of this._MediaMap)e.push(`${j} -> ${B.peerId} @${B.connection.id} `);return{lastConnectionId:this._LastConnectionId,connections:t,mediaMap:e,closed:this.closed}}findConnection(t,e){for(let j of this._Connections.values())if(j.type!=="virtual"&&j.transport===t&&j.address===e&&(j.type!=="established"||!j.connection.closed))return j}},t0=class{constructor(t,e){this.connection=t;this.release=e;this.closeController=new AbortController;this.closePromise=new Promise(t=>this.closeController.signal.addEventListener("abort",()=>t("closed"),{once:!0}));t.closeSignal.addEventListener("abort",()=>this.close(),{once:!0})}get closeSignal(){return this.closeController.signal}get closed(){return this.closeSignal.aborted}close(){this.release(),this.closeController.abort("closed")}get connectionStats(){return this.connection.connectionStats}get id(){return this.connection.id}get transport(){return this.connection.transport}get address(){return this.connection.address}get status(){return this.connection.status}waitForConnected(){return this.connection.waitForConnected()}joinRoom(t,e,j,B){return this.connection.joinRoom(t,e,j,B)}getReconnectToken(t){return this.connection.getReconnectToken(t)}getRtcStats(){return this.connection.getRtcStats()}healthCheck(){return this.connection.healthCheck()}sendDatagram(t){return this.connection.sendDatagram(t)}startLocalVideo(t,e,j){return this.connection.startLocalVideo(t,e,j)}stopLocalVideo(t){return this.connection.stopLocalVideo(t)}startRemoteVideo(t){return this.connection.startRemoteVideo(t)}stopRemoteVideo(t){return this.connection.stopRemoteVideo(t)}async dump(){let t=await this.connection.dump();return typeof t=="object"&&(t={...t,isShared:!0,referenceClosed:this.closed}),t}};function ZF(v){let t;try{t=XF(v)}catch{return}if(!Array.isArray(t)||t.length<2)return;let e=t[1];if(Array.isArray(e))return e.map(Number)}import{assert as e0,Backend as yB}from"@4players/odin-common";var w=class{constructor(t,e){this.uid=t;this.customType=e}#x;#A;get mediaStream(){return this.#x}get audioPlayback(){return e0(this.#A,"getting the audioPlayback failed, this video has no Audio"),this.#A}get volume(){return e0(this.audioPlayback,"getting the volume failed, this video has no Audio"),this.audioPlayback.volume}setVolume(t){e0(this.#A,"Can not set the volume, this video has no Audio"),this.#A.setVolume(t)}setMediaStream(t){this.mediaStream||(this.#x=t)}close(){this.#x?.getVideoTracks().forEach(t=>{t.stop(),this.#x?.removeTrack(t)}),this.#x=void 0}};import{Backend as gB,assert as sA,generateUUID as lr,unwrap as ur,CONNECTION_STATS_INITIAL as kr}from"@4players/odin-common";import{RoomNotificationsRpc as cr,RoomV1 as _B}from"@4players/odin-common/api";import{Selector as YF,failure as P,sleep as $x,success as T,assert as xr}from"@4players/odin-common";import{parseResponse as Ar,RoomCommandsRpc as yx,RoomNotificationsRpc as Fr,RoomV1 as IB}from"@4players/odin-common/api";u();var Ix=class{constructor(t,e,j,B,C,E,f,s,b,d){this.connectionPool=t;this.transport=e;this.onEvent=j;this.gateway=B;this.roomId=E;this.cipher=b;this.disableAutoReconnect=d;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(t=>this._Close.signal.addEventListener("abort",()=>t(this._Close.signal.reason?"disconnected":"closed"),{once:!0}));this._Token=C,this._UserData=f,this._Position=s,this._Main().then(({reason:h})=>a(`_Main() resolved; ${h}`))}get token(){return this._Token}get userData(){return this._UserData}get position(){return this._Position}get closed(){return this._Close.signal.aborted}get mainConnection(){return this._MainConnection}async requestUnsafe(t,e){if(this._RoomConnection===void 0)return P("currently not connected");let j=await this._RoomConnection.request(t,e,void 0);return xr(j!=="timeout","request should not timeout"),j!=="closed"&&j.type==="Success"&&this._HandleRequests(t,e,j.value),j}async request(t,e){let j=Date.now(),B=yx[t],C=await this.requestUnsafe(t,e),E=(Date.now()-j)/1e3;if(a(`sent room rpc '${t}'; took: ${E}s`,{properties:e,result:C}),C==="closed"||C.type==="Failure")return C;let f=Ar(t,C.value,yx);return f!==void 0?T(f):P(`received invalid response from ${t}`)}notify(t,e){this._RoomConnection!==void 0&&this._RoomConnection.notify(t,e)}close(){this._Close.abort(!0)}get renewTokenIn(){let t=this._LastTokenRenew-performance.now()+i.MinTokenRefreshInterval,e=this._Token.timeLeft-i.MinTokenLifetime;return Math.max(t,e)}async _Main(){let t="unable to establish connection";for(let e=0;;this._FailedConnections++){if(await $x(Math.max(e-performance.now(),0)),this._Close.signal.aborted||this.connectionPool.closed){t="user requested";break}if(this._WasConnected&&this._ReconnectingSince!==0&&AA(this._ReconnectingSince,i.MaxReconnectDuration)){t="reconnect time limit reached";break}if(e=performance.now()+1e3,this._TokenUsed=!0,this._Token.hasAudience("sfu")){let j=await this._ConnectToServer();if(j.type==="Success"&&j.value==="shutdown"){a("connection closed by user request; shutting down"),t="user requested";break}if(this.disableAutoReconnect&&this._WasConnected){t=j.type==="Failure"?j.reason:"connection lost";break}if(this._LastReconnectStartedAt===0&&(this._LastReconnectStartedAt=performance.now()),this._WasConnected&&this._ReconnectingSince===0&&(this._ReconnectingSince=performance.now()),j.type==="Failure"&&!this._WasConnected&&this._FailedConnections>=3){t=j.reason;break}if(j.type==="Failure"&&!AA(this._LastReconnectStartedAt))continue}if(this.reset(),this._Close.signal.aborted||this.connectionPool.closed){t="user requested";break}if(this.gateway!==void 0&&this._Token.hasAudience("gateway")){this._ChangeStatus("Joining",`requesting new token from ${this.gateway}`);let j=await rr(this.gateway,this._Token,this._Close.signal);if(j.type==="Success")if(j.value instanceof g)e=0,this._Token=j.value,this._TokenUsed=!1;else{t=`gateway error; ${j.value}`;break}else if(!this._WasConnected&&this._FailedConnections>=3){t="unable to contact the gateway";break}}if(this._TokenUsed&&this._Token.timeLeft<=0){t="token has expired";break}if(this._Close.signal.aborted||this.connectionPool.closed){t="user requested";break}}return this._ChangeStatus("Closed",t),this.close(),P(t)}async _ConnectToServer(){let t=this._Token;for(;t.upstream!==void 0;)t=t.upstream;let e=t.claims.adr??this.gateway?.toString();if(!e)return T("continue");if(this._ChangeStatus("Joining",`connecting to ${t.claims.adr}`),this._MainConnection===void 0||this._MainConnection.closed||this._MainConnection.address!==t.claims.adr){this._MainConnection?.close();let C=await this.connectionPool.acquireConnection(this.transport,e,this.cipher,this._Close.signal);if(C==="closed")return P("connection pool closed");if(C.type==="Failure")return this._ChangeStatus("Joining",`connection failed; ${C.reason}`),P(`connection failed; ${C.reason}`);this._MainConnection=C.value,this._OwnPeerId=void 0}let j=await Promise.race([Promise.all([this._MainConnection.joinRoom(t,this.roomId,this.userData,this.position)]),$x(i.ConnectTimeout,"timeout"),this._Closed]);if(j==="closed"||j==="disconnected")return T("continue");if(j==="timeout")return this._ChangeStatus("Joining","timed out"),T("continue");let[B]=j;if(B==="closed")return T("continue");if(B.type==="Failure")return P(`unable to join room; ${B.reason}`);this._RoomConnection=B.value,this._WasConnected=!0,this._FailedConnections=0,this._ReconnectingSince=0,this._ChangeStatus("Joined",`joined ${this.roomId}`);try{await this._MainConnection.waitForConnected();let C=await this._HandleConnection(this._MainConnection);return T(C?"shutdown":"continue")}catch(C){return P(`unable to handle connection; ${C}`)}}_ChangeStatus(t,e){let j={status:t,message:e};this.onEvent("RoomStatusChanged",j)}async _HandleConnection(t){if(this._RoomConnection===void 0)return!1;let e=new YF([()=>$x(this.renewTokenIn,"renewToken"),()=>$x(500,"tick"),async()=>await this._RoomConnection?.recv(),()=>this._Closed,()=>t.closePromise]);for(;;){let j=await e.next();switch(j){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(j);break}}}_HandleEvent(t){if(t.name==="RoomUpdated"){let e=Fr.RoomUpdated.safeParse(t.properties);if(!e.success)return;for(let j of e.data.updates)j.kind==="Joined"&&(this._OwnPeerId=j.own_peer_id)}this.onEvent(t.name,t.properties)}_HandleRequests(t,e,j){switch(t){case"SetPeerPosition":{let B=yx.SetPeerPosition.request.safeParse(e);if(B.success){let C=B.data.position;this._Position=C.length===2?[C[0],C[1],0]:C}else k("unable to process SetPeerPosition command");break}case"UpdatePeer":{let B=yx.UpdatePeer.request.safeParse(e);B.success?this._UserData=B.data.user_data:k("unable to process UpdatePeer command");break}}}async _RenewToken(t){if(this._LastTokenRenew=performance.now(),!t&&this.token.timeLeft>i.MinTokenLifetime)return;if(this._MainConnection===void 0||this._OwnPeerId===void 0)return P("connection is not established");let e=await this._MainConnection.getReconnectToken(this._OwnPeerId);return e.type==="Success"?(this._Token=e.value,T()):P(`${this._MainConnection.address} rejected reconnect token request; ${e.reason}`)}reset(){this._LastReconnectStartedAt=0,this._RoomConnection?.close(),this._RoomConnection=void 0,this._MainConnection?.close(),this._MainConnection=void 0,this._OwnPeerId=void 0}};async function rr(v,t,e){try{let j={jsonrpc:"2.0",id:1,method:"Connect",params:{}};o(`sending authentication request to '${v}'`,j);let C=await(await fetch(v,{body:JSON.stringify(j),method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},signal:e})).json();if(o(`received authentication response fom '${v}'`,C),"result"in C)return g.parse(C.result.token);{let E=C.error?.message??"malformed response";return p(`gateway rejected token; ${E}`),T(E)}}catch(j){return P(String(j))}}function AA(v,t=8e3){return performance.now()-v>t}u();import{assert as ar}from"@4players/odin-common";u();import{Backend as jx,Strand as or}from"@4players/odin-common";u();import{assert as Br}from"@4players/odin-common";u();import{decode as Dr}from"@msgpack/msgpack";var FA={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])},rA=v=>({name:"PBKDF2",hash:"SHA-256",iterations:600,salt:v}),DA=32,tA=1e6,eA=2147483648,jA=32,J=[79,68,73,78,1,75,105,109],Ax=16,Fx=64,BA=16;function vA(v,t){if(v.length!==t.length)return!1;for(let e=0;e<v.length;e++)if(v[e]!==t[e])return!1;return!0}function tr(v){return isFinite(v)}function er(v){return Array.isArray(v)}function gx(v){return tr(v)?v:n}function ex(v){return v instanceof Uint8Array?v:n}function jr(v,...t){let e;try{e=Dr(v)}catch{return n}if(!er(e))return n;let j=new Array(e.length);for(let B in t)if(j[B]=t[B](e[B]),j[B]===n)return n;return j}function _x(v,...t){if(v.length<J.length)return G;for(let e=0;e<J.length;e++)if(v[e]!==J[e])return G;return jr(v.subarray(J.length),...t)}var rx=class{constructor(t){this.first=1;this.offset=0;this.window=Array(t)}isReplay(t){let e=t-this.first;if(e<0)return!0;if(e>=this.window.length)if(e<this.window.length*2){let C=e-this.window.length+1;e-=C;for(let E=0;E<C;E++)this.advance()}else return this.first=t+1-self.window.length,this.offset=0,this.window.fill(!1),!1;let j=(this.offset+e)%this.window.length,B=this.window[j]===!0;for(this.window[j]=!0;this.window[this.offset]===!0;)this.advance();return B}advance(){this.window[this.offset]=!1,this.first+=1,this.offset=(this.offset+1)%this.window.length}};var Lx=class v{constructor(t){this.key=t}static async create(t){typeof t=="string"&&(t=new TextEncoder().encode(t));let e=await globalThis.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits"]),j=await globalThis.crypto.subtle.deriveBits(FA,e,256),B=await globalThis.crypto.subtle.importKey("raw",j,"PBKDF2",!1,["deriveKey"]);return new v(B)}async generatePeerKey(t,e){return await globalThis.crypto.subtle.deriveKey(rA(t),this.key,{name:"AES-GCM",length:256},!1,[e])}},Hx=class v{constructor(t,e){this.seed=t;this.key=e;this.sequenceNumbers={datagram:1,message:1,userData:1};this.number_of_packets=0;this.number_of_bytes=0}static async create(t){let e=globalThis.crypto.getRandomValues(new Uint8Array(DA)),j=await t.generatePeerKey(e,"encrypt");return new v(e,j)}get limitReached(){return this.key===void 0?!1:this.number_of_bytes>=eA||this.number_of_packets>=tA}nextSequenceNumber(t){return this.sequenceNumbers[t]++}};function j0(v,t){return{kind:"encrypted",key:v,material:t,antiReplays:{datagram:new rx(jA),userData:new rx(0),message:new rx(0)}}}var Px=class v{constructor(t,e,j,B){this.additionalData=t;this.sequenceNumber=e;this.seed=j;this.encrypted=B}static parse(t){let e=_x(t,ex,gx,ex);if(e===n||e===G)return e;let[j,B,C]=e,E=t.subarray(0,t.length-C.length);return new v(E,B,j,C)}isSameSeed(t){return vA(this.seed,t.seed)}async generateKey(t){return await t.generatePeerKey(this.seed,"decrypt")}};function Nx(v,t){let e=new Uint8Array(12);switch(e[0]=t&255,e[1]=t>>8&255,e[2]=t>>16&255,e[3]=t>>24&255,v){case"datagram":e[5]=1;break;case"userData":e[5]=2;break;case"message":e[5]=3;break;default:Br(!1,"missing content implementation")}return e}u();import{encode as EA}from"@msgpack/msgpack";import{assert as Cr}from"@4players/odin-common";var wx=class{constructor(t){this.actions=t}changeKey(t){this.masterKey!==t&&(this.masterKey=t,this.ownKey=n,this.actions.resendUserData())}async encryptDatagram(t){let e=await this.getKey("datagram");return e===void 0?t:e===O?n:await fr(e,t)}async encryptMessage(t){let e=await this.getKey("message");return e===void 0?t:e===O?O:await CA(e,t,"message")}async encryptUserData(t){let e=await this.getKey("userData");return e===void 0?t:(Cr(e!==O,"key unavailable for user data encryption"),await CA(e,t,"userData",e.seed))}async getKey(t){if(this.ownKey===n||this.ownKey?.limitReached)if(t==="userData")this.ownKey=this.masterKey?await Hx.create(this.masterKey):void 0;else return this.ownKey!==n&&(this.ownKey=n,this.actions.resendUserData()),O;return this.ownKey}reset(){this.ownKey=this.masterKey?n:void 0}};async function CA(v,t,e,...j){let B=v.nextSequenceNumber(e),C=t.length+Ax,E=Er(B,j,C),f=E.length-C,s=await fA(v,e,B,E.subarray(0,f),t);return E.set(new Uint8Array(s),f),E}function Er(v,t,e){let j=[];t.forEach(E=>j.push(E)),j.push(v),j.push(new Uint8Array(e));let B=EA(j),C=new Uint8Array(J.length+B.length);return C.set(J,0),C.set(B,J.length),C}async function fr(v,t){let e=nr(t);if(e===n)return n;if((e.kind&Fx)!==0)return n;let j=e.body.length+Ax,B=v.nextSequenceNumber("datagram"),C=EA([e.kind|Fx,e.mediaIds,B,new Uint8Array(j)]),E=C.length-j,f=await fA(v,"datagram",B,C.subarray(0,E),e.body);return C.set(f,E),C}async function fA(v,t,e,j,B){return new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:Nx(t,e),additionalData:j,tagLength:Ax*8},v.key,B))}function nr(v){let t=new S(v),e=t.readArrayLength();if(l(e)||e<2)return n;let j=t.readNumber(),B=t.readArrayLength();if(l(j)||l(B))return n;if(B>BA)return n;let C=Array(B);for(let f=0;f<C.length;f++){let s=t.readNumber();if(l(s))return n;C[f]=s}let E=v.subarray(t.position);return{kind:j,mediaIds:C,body:E}}u();import{encode as sr}from"@msgpack/msgpack";var Ox=class{constructor(t){this.actions=t;this.peerKeys=new Map}async changeKey(t){this.masterKey=t;for(let[e,{kind:j,material:B}]of this.peerKeys)if(t!==void 0){let C=await B.generateKey(t),E=j0(C,B),f=await Jx(E,"userData",B.additionalData,B.sequenceNumber,B.encrypted);f!==n?(this.peerKeys.set(e,E),this.actions.setUserData(e,f)):(this.peerKeys.set(e,{kind:"broken",material:B}),this.actions.setUserData(e,new Uint8Array))}else j==="encrypted"&&this.peerKeys.set(e,{kind:"broken",material:B})}async decryptDatagram(t,e){let j=ir(e);if(this.masterKey===void 0)return j===G?e:n;if(j===n||j===G)return n;let B=this.peerKeys.get(t);if(B?.kind!=="encrypted")return n;let C=await Jx(B,"datagram",j.additionalData,j.sequenceNumber,j.encrypted);return C===n?n:br(j.kind&~Fx,j.mediaIds,C)}async decryptMessage(t,e){let j=_x(e,gx,ex);if(this.masterKey===void 0)return j===G?e:n;if(j===n||j===G)return n;let B=this.peerKeys.get(t);if(B?.kind!=="encrypted")return n;let[C,E]=j,f=e.subarray(0,e.length-E.length);return Jx(B,"message",f,C,E)}async decryptUserData(t,e){let j=Px.parse(e);if(j===n)return n;if(j===G)return this.peerKeys.delete(t),this.masterKey===void 0?e:n;if(this.masterKey===void 0)return this.peerKeys.set(t,{kind:"broken",material:j}),n;let B=this.peerKeys.get(t);if(B?.kind==="encrypted"&&B.material.isSameSeed(j))B.material=j;else{let E=await j.generateKey(this.masterKey);B=j0(E,j)}let C=await Jx(B,"userData",j.additionalData,j.sequenceNumber,j.encrypted);return C===n?this.peerKeys.set(t,{kind:"broken",material:j}):B!==void 0&&this.peerKeys.set(t,B),C}reset(){this.peerKeys.clear()}};function ir(v){let t=new S(v),e=t.readArrayLength();if(l(e)||e<1)return n;let j=t.readNumber();if(l(j))return n;if((j&Fx)===0)return G;if(e!==4)return n;let B=t.position;t.readObjects(1);let C=v.subarray(B,t.position),E=t.readNumber(),f=t.readBytes();if(l(E)||l(f))return n;let s=v.subarray(0,v.length-f.length);return{kind:j,mediaIds:C,additionalData:s,sequenceNumber:E,encrypted:f}}async function Jx(v,t,e,j,B){let C=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:Nx(t,j),additionalData:e,tagLength:Ax*8},v.key,B).catch(()=>n);return C===n?n:v.antiReplays[t].isReplay(j)?n:new Uint8Array(C)}function br(v,t,e){let j=2;try{let E=new S(e);for(E.position=0;E.position<e.length;)E.readObjects(1),j+=1}catch{return n}let B=sr(v),C=new Uint8Array(3+B.length+t.length+e.length);return C[0]=220,C[1]=j>>8&255,C[2]=j&255,C.set(B,3),C.set(t,3+B.length),C.set(e,3+B.length+t.length),C}var Sx=class{constructor(t,e){this.active=!1;let j=new Ox(e),B=new wx(e);this.crypto=new or({encryption:B,decryption:j}),this.peerKeys=j.peerKeys,this.configure(t)}encryptUserData(t){return this.crypto.enqueue(({encryption:e})=>e.encryptUserData(t))}async encryptMessage(t){let e;do e=await this.crypto.enqueue(({encryption:j})=>j.encryptMessage(t));while(e===O);return e}async encryptDatagram(t){return await this.crypto.enqueue(({encryption:e})=>e.encryptDatagram(t))}decryptUserData(t,e){return this.crypto.enqueue(({decryption:j})=>j.decryptUserData(t,e))}decryptMessage(t,e){return this.crypto.enqueue(({decryption:j})=>j.decryptMessage(t,e))}decryptDatagram(t,e){return this.crypto.enqueue(({decryption:j})=>j.decryptDatagram(t,e))}configure(t){return this.crypto.enqueue(async e=>{let j=t.password?await Lx.create(t.password):void 0;this.active=j!==void 0,await e.encryption.changeKey(j),await e.decryption.changeKey(j)})}getPeerStatus(t){switch(this.peerKeys.get(t)?.kind??"unencrypted"){case"broken":return jx.PeerCipherStatus.InvalidPassword;case"encrypted":return jx.PeerCipherStatus.Encrypted;case"unencrypted":return this.active?jx.PeerCipherStatus.InvalidPassword:jx.PeerCipherStatus.Unencrypted;default:return jx.PeerCipherStatus.Unknown}}deletePeerKey(t){this.peerKeys.delete(t)}reset(){return this.crypto.enqueue(async({encryption:t,decryption:e})=>{t.reset(),e.reset()})}async dump(){return this.crypto.enqueue(async()=>({active:this.active,peers:Array.from(this.peerKeys).map(([t,e])=>`${t} => ${e.kind}`)}))}};function nA(v,t){return ar(v.type==="OdinCrypto","only OdinCrypto supported"),new Sx(v,t)}var Ux=class{constructor(t,e,j){this._Captures=new Map;this._Playbacks=new Map;this._Peers=new Map;this._AvailableMediaIds=[];let{url:B,onEvent:C}=e,E=ur(g.parse(e.token)),f=e.roomId??E.defaultRoomId,s=e.userData??new Uint8Array(0),b=e.position??[0,0,0];sA(f!==void 0,"room id required for multi-room-tokens"),this.cipher=e.cipher?nA(e.cipher,new qx(this)):void 0,this.onEvent=C,o(`creating new room '${f}' ${this.cipher?"with":"without"} cipher`,E,s,b),this._Connection=new Ix(t,e.transport??"H3",this._HandleEvent.bind(this),B?new URL(B):void 0,E,f,s,b,this.cipher,j?.disableAutoReconnect??!1)}get connectionStats(){let t={...kr};return this.mainConnection?this.mainConnection.connectionStats:t}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(t,e){return this._Connection.requestUnsafe(t,e)}async link(t){if(t instanceof H){let e=this._Playbacks.get(t.uid)??{media:void 0,playback:void 0};e.playback!==void 0&&this.unlink(e.playback),e.media!==void 0&&t.start(e.media),e.playback=t,o(`linking audio playback media '${t.uid}' with volume ${t.volume} to room '${this._Connection.roomId}'`),this._Playbacks.set(t.uid,e)}else if(t instanceof N){let e=this._Captures.get(t);e&&this.unlink(t);let j=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();e={media:j?{connectionId:this.mainConnection.id,mediaId:j}:void 0},o(`linking audio capture media '${t.uid}' with volume ${t.volume} to room '${this._Connection.roomId}'`),this._Captures.set(t,e),e.media!==void 0&&await t.start(this._Connection,e.media)}else if(t instanceof w){let e=this._Playbacks.get(t.uid)??{media:void 0,playback:void 0};if(e.playback!==void 0&&this.unlink(e.playback),e.media!==void 0){let j=await this.mainConnection?.startRemoteVideo(e.media.mediaId);j&&t.setMediaStream(new MediaStream([j]))}e.playback=t,o(`linking video playback media '${t.uid}' with type '${t.customType}' to room '${this._Connection.roomId}'`),this._Playbacks.set(t.uid,e)}else if(t instanceof I){let e=this._Captures.get(t);e&&this.unlink(t);let j=t.mediaStream?.getVideoTracks()[0];if(j){let B=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();e={media:B?{connectionId:this.mainConnection.id,mediaId:B}:void 0},o(`linking video capture media '${t.uid}' with type '${t.parameters?.customType}' to room '${this._Connection.roomId}'`),this._Captures.set(t,e),e.media!==void 0&&(await t.start(this._Connection,e.media),this.mainConnection?.startLocalVideo(e.media.mediaId,j,t.parameters)),t.audioCapture&&await this.link(t.audioCapture)}}else throw new Error("Linking failed, media was not supported")}unlink(t){if(t instanceof H||t instanceof w){let e=this._Playbacks.get(t.uid);if(e?.playback!==t)return;e.playback=void 0,e.media!==void 0&&(t instanceof H?t.stop(e.media):(this.mainConnection?.stopRemoteVideo(e.media.mediaId),t.setMediaStream(void 0))),o(`unlinking playback media '${t.uid}' from room '${this._Connection.roomId}'`),this._Playbacks.set(t.uid,e)}else if(t instanceof N||t instanceof I){t instanceof I&&t.audioCapture&&this.unlink(t.audioCapture);let e=this._Captures.get(t);if(e===void 0)return;e.media!==void 0&&(t.stop(this._Connection,e.media),this._AvailableMediaIds.push(e.media.mediaId),t instanceof I&&this.mainConnection?.stopLocalVideo(e.media.mediaId)),o(`unlinking capture media '${t.uid}' from room '${this._Connection.roomId}'`),this._Captures.delete(t)}else throw new Error("invalid media")}close(){o(`closing room '${this._Connection.roomId}'`),this._Connection.close()}_HandleEvent(t,e){let j=F0(cr,{name:t,properties:e});j!==void 0&&(this._HandleKnownEvent(j),e=j.properties),this.onEvent(t,e)}_HandleKnownEvent(t){switch(a(`processing event '${t.name}'`,t.properties),t.name){case"RoomStatusChanged":t.properties.status!=="Joined"&&this._HandleConnectionLost();break;case"RoomUpdated":for(let e of t.properties.updates)this._HandleRoomUpdate(e);break;case"PeerUpdated":this._HandlePeerUpdate(t.properties);break}}_HandleConnectionLost(){for(let t of this._Peers.keys())this._HandlePeerLeft(t);for(let[t,e]of this._Captures)e.media!==void 0&&(t instanceof I,t instanceof N&&(t.stop(this._Connection,e.media),e.media=void 0));this._AvailableMediaIds.length=0}_HandleRoomUpdate(t){if(t.kind==="Joined"){sA(this._AvailableMediaIds.length===0,"left over media ids"),this._AvailableMediaIds.push(...t.media_ids),this._HandleRoomJoined();for(let e of t.room.peers)this._HandlePeerJoined(e)}else t.kind==="PeerJoined"?this._HandlePeerJoined(t.peer):t.kind==="PeerLeft"&&this._HandlePeerLeft(t.peer_id)}_HandleRoomJoined(){for(let[t,e]of this._Captures)this._AvailableMediaIds.length===0||this.mainConnection===void 0||(e.media={connectionId:this.mainConnection.id,mediaId:this._AvailableMediaIds.shift()},t instanceof N&&t.start(this._Connection,e.media),t instanceof I)}_HandlePeerUpdate(t){t.kind==="MediaStarted"?this._HandleMediaStart(t.peer_id,t.media):t.kind==="MediaStopped"&&this._HandleMediaStopped(t.peer_id,t.media_id)}_HandlePeerJoined(t){this._Peers.has(t.id)||this._Peers.set(t.id,{mediaIds:new Map});for(let e of t.medias)this._HandleMediaStart(t.id,e)}_HandlePeerLeft(t){let e=this._Peers.get(t);if(e!==void 0){for(let j of e.mediaIds.keys())this._HandleMediaStopped(t,j);this._Peers.delete(t)}}_HandleMediaStart(t,e){if(this.mainConnection===void 0)return;let j=this._Peers.get(t);if(j===void 0||e.properties.kind!=="audio"&&e.properties.kind!=="video")return;let B=String(e.properties.uid??lr());e.properties.uid=B;let C=this._Playbacks.get(B)??{media:void 0,playback:void 0};this._Playbacks.set(B,C),j.mediaIds.set(e.id,B),C.media={connectionId:this.mainConnection.id,mediaId:e.id},C.playback!==void 0&&(C.playback instanceof H&&C.playback.start(C.media),C.playback instanceof w&&this.mainConnection.startRemoteVideo(C.media.mediaId).then())}_HandleMediaStopped(t,e){let j=this._Peers.get(t);if(j===void 0)return;let B=j?.mediaIds.get(e);if(B===void 0)return;let C=this._Playbacks.get(B);C!==void 0&&(C.media!==void 0&&C.media.mediaId===e&&C.playback!==void 0&&(C.playback instanceof H&&C.playback.stop(C.media),C.playback instanceof w&&this.mainConnection?.stopRemoteVideo(C.media.mediaId),C.media=void 0),j.mediaIds.delete(e))}};nx();function bB(v,t){c0(t?.logger,t?.onLogMessage);let e,j=new Gx((C,E)=>e.receivePacket(C,E)),B=new ox(v);return e=new ax(B,j.sendDatagram.bind(j),t?.enableHTMLAudioElementFallback??!1),new B0(j,e,t)}var dx=dr(),v0=[],iA=!1;function pr(){iA||typeof window>"u"||(window.addEventListener("beforeunload",()=>{for(let v of v0)v.deref()?.close()}),iA=!0)}var B0=class{constructor(t,e,j){this.version="9";this.supportedTransports=["H3","WebRTC"];this._PlaybackVolume=[1,1];this._CreatedAt=Date.now();this._Options=j??{},this._Options.disableBeforeUnload||pr(),this._ConnectionPool=t,this._MediaController=e,v0.push(new WeakRef(this)),o("plugin initialized")}get playbackVolume(){return this._PlaybackVolume}joinRoom(t){return new Ux(this._ConnectionPool,t,this._Options)}async createAudioPlayback(t){return this._MediaController.createAudioPlayback(t)}async createAudioCapture(t){return this._MediaController.createAudioCapture(t)}async createVideoCapture(t,e){return this._MediaController.createVideoCapture(t,e)}async createVideoPlayback(t){return new w(t.uid,t.customType)}enumerateDevices(){return fx()}setOutputVolume(t){this._MediaController.playbackSetGlobalVolume(t)}async setOutputDevice(t){await this._MediaController.playbackSetDevice(t.device)}close(){this._MediaController.close(),this._ConnectionPool.close(),o("plugin closed")}async dump(){return{createdAt:this._CreatedAt,connections:await this._ConnectionPool.dump(),medias:await this._MediaController.dump()}}};async function bA(){let v=[];for(let t of v0){let e=t.deref();e!==void 0&&v.push(await e.dump())}return JSON.stringify({timestamp:Date.now(),instances:v,background:await q0()})}globalThis.odin_debug_dump_state=bA;window!==void 0&&(window.odin_debug_dump_state=bA);export{dx as SESSION_ID,bB as createPlugin};