@4players/odin-plugin-web 1.9.8 → 1.10.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.
package/lib/esm/plugin/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var bA=Object.defineProperty;var q=(v,t)=>()=>(v&&(t=v(v=0)),t);var Tx=(v,t)=>{for(var j in t)bA(v,j,{get:t[j],enumerable:!0})};var i={};Tx(i,{AdditionalCaptureBlocks:()=>aA,AdditionalPlaybackBlocks:()=>oA,ClockJumpCheckInterval:()=>hA,ClockJumpThreshold:()=>qA,ConnectInterval:()=>LA,ConnectTimeout:()=>$A,DefaultRefreshRate:()=>uA,DefaultVideoCodec:()=>HA,HealthCheckTimeout:()=>pA,MainConnectionPingInterval:()=>mA,MaxNumberOfDecoders:()=>cA,MinDBFs:()=>Sx,MinTokenLifetime:()=>yA,MinTokenRefreshInterval:()=>_A,PlaybackPreload:()=>lA,RenderQuantumSize:()=>dA,VadPreload:()=>kA,WebRtcIceTimeout:()=>IA,WebRtcStatsSnapshotInterval:()=>GA,WebRtcTimeout:()=>gA});var oA,aA,lA,uA,kA,cA,dA,Sx,pA,hA,qA,mA,GA,IA,gA,$A,yA,_A,LA,HA,Rx=q(()=>{"use strict";oA=3,aA=3,lA=3,uA=250,kA=3,cA=512,dA=128,Sx=-758.596,pA=1e4,hA=1e3,qA=1e4,mA=3e3,GA=1e3,IA=3e3,gA=1e4,$A=5e3,yA=6e4,_A=5e3,LA=[0,100,200,200,500],HA="H264"});function vx(v){return typeof v!="symbol"}function l(v){return typeof v=="symbol"}var G,n,J,I,Cx=q(()=>{"use strict";G=Symbol("Unencrypted"),n=Symbol("Invalid"),J=Symbol("Retry"),I=Symbol("UnexpectedEof")});function k(v,t,j){return v.postMessage(t,j)}function U(v,t){return new Promise(j=>{let e=B=>{let[C,E]=B.data;C===t&&(j(B.data[1]),v.removeEventListener("message",e))};v.addEventListener("message",e)})}var E0=q(()=>{"use strict"});function Vx(v,t){v.values[0]=t[0],v.values[1]=t[1]}function f0(v,t){return v.values[2+t*5]}function n0(v,t,j){let e=2+t*5+1;v.values[e+0]=j[0],v.values[e+1]=j[1]}function s0(v){return v.values[0]!==0}function i0(v){return v.values[1]}function b0(v){return v.values[2]}function o0(v,t){return v.values[3]=t}var a0=q(()=>{"use strict"});function l0(v,t){let j=new O(v);j.position=t;let e=j.readObjects(1);return vx(e)?j.position:e}var O,u0=q(()=>{"use strict";Cx();O=class{constructor(t,j=0){this.bytes=t;this.position=j}readArrayLength(){let t=this.readTag();return l(t)?t:(t&240)===144?t&15:t===220?this.readUint16():t===221?this.readUint32():n}readNumber(){let t=this.readTag();return l(t)||(t&128)===0?t:(t&224)===224?t-256:t===202?this.readFloat32():t===203?this.readFloat64():t===204?this.readUint8():t===205?this.readUint16():t===206?this.readUint32():t===207?this.readUint64():t===208?this.readInt8():t===209?this.readInt16():t===210?this.readInt32():t===211?this.readInt64():n}readBytes(){let t=this.readTag();if(l(t))return t;let j;if(t===196)j=this.readUint8();else if(t===197)j=this.readUint16();else if(t===198)j=this.readUint32();else return n;if(l(j))return j;let e=this.consume(j);return e!==I?this.bytes.subarray(e,e+j):I}readObjects(t){for(;t>0;t-=1){let j=this.readTag();if(l(j))return j;let e,B=0,C=0;switch(j){case 192:break;case 194:break;case 195:break;case 196:B=this.readUint8();break;case 197:B=this.readUint16();break;case 198:B=this.readUint32();break;case 199:B=this.readUint8(),C=1;break;case 200:B=this.readUint8(),C=1;break;case 201:B=this.readUint32(),C=1;break;case 202:B=4;break;case 203:B=8;break;case 204:B=1;break;case 205:B=2;break;case 206:B=4;break;case 207:B=8;break;case 208:B=1;break;case 209:B=2;break;case 210:B=4;break;case 211:B=8;break;case 212:B=2;break;case 213:B=3;break;case 214:B=5;break;case 215:B=9;break;case 216:B=17;break;case 217:B=this.readUint8();break;case 218:B=this.readUint16();break;case 219:B=this.readUint32();break;case 220:if(e=this.readUint16(),l(e))return e;t+=e;break;case 221:if(e=this.readUint32(),l(e))return e;t+=e;break;case 222:if(e=this.readUint16(),l(e))return e;t+=e*2;break;case 223:if(e=this.readUint32(),l(e))return e;t+=e*2;break;default:if((j&128)!==0){if((j&240)===128)t+=(j&15)*2;else if((j&240)===144)t+=j&15;else if((j&224)===160)B=j&31;else if((j&224)!==224)return n}}if(B===I)return I;if(this.consume(B+C)===I)return I}}consume(t){if(t===I||this.position+t>this.bytes.length)return I;let j=this.position;return this.position=j+t,j}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 j=this.readUint32();return l(j)?j:t<<32|j}readInt8(){let t=this.readUint8();return l(t)||t>=128&&(t=t-256),t}readInt16(){let t=this.readUint16();return l(t)||t>=32768&&(t=t-65536),t}readInt32(){let t=this.readUint32();return l(t)||t>=2147483648&&(t=t-4294967296),t}readInt64(){let t=this.readUint32();if(l(t))return t;if(t>=2097152||t<-2097152)return n;let j=this.readUint32();return l(j)?j:t<<32|j}readFloat32(){let t=this.consume(4);return l(t)?t:new Float32Array(this.bytes.subarray(t,t+4))[0]}readFloat64(){let t=this.consume(8);return l(t)?t:new Float64Array(this.bytes.subarray(t,t+8))[0]}}});var k0,c0=q(()=>{"use strict";k0="1.9.8"});import{error as NA,warn as wA,info as PA,debug as KA,Logger as JA,LogLevel as OA,CallbackSink as MA,Formatter as TA}from"@4players/odin-common";function d0(v,t){g||(g=v??new JA(OA.DEBUG,"odin-plugin-web",[]),t&&g.sinks.push(new MA(t,TA.structured)))}function c(v,...t){let j=Ex(t);g?g?.error(v,j):NA(v,j)}function d(v,...t){let j=Ex(t);g?g?.warn(v,j):wA(v,j)}function b(v,...t){let j=Ex(t);g?g?.info(v,j):PA(v,j)}function a(v,...t){let j=Ex(t);g?g?.debug(v,j):KA(v,j)}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 g,p0=q(()=>{"use strict"});function m(v){return v.connectionId*4294967296+v.mediaId}var _,S,u=q(()=>{"use strict";Rx();Cx();Rx();E0();a0();u0();c0();p0();Cx();_={isSilent:!0,rmsDBFS:-758.596};S=class{constructor(){this.inFlight=null}run(t){return this.inFlight||(this.inFlight=t().finally(()=>{this.inFlight=null})),this.inFlight}}});function Y(v,t,j,e,B){return Promise.all([QA(v),zA(j,t,e,B)])}async function QA(v){let t=URL.createObjectURL(new Blob([v],{type:"text/javascript"})),j=new Worker(t,{type:"module",name:"odin worker"});return Q.push(j),j}async function zA(v,t,j,e){try{let E=new AudioWorkletNode(v,j,e);return R.push(E),E}catch{}let B=Ux.get(v);if(B===void 0){let E=URL.createObjectURL(new Blob([t],{type:"text/javascript"}));B=v.audioWorklet.addModule(E),Ux.set(v,B),B.catch(()=>Ux.delete(v))}await B;let C=new AudioWorkletNode(v,j,e);return R.push(C),C}async function G0(){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:j}=new MessageChannel,{promise:e,resolve:B}=Promise.withResolvers();return j.onmessage=C=>B(C.data),setTimeout(()=>B("timeout"),100),k(v,["dump",{result:t}],[t]),e}var Q,R,z,X,Ux,nx=q(()=>{"use strict";u();Q=[],R=[],z=class{constructor(t,j,e){this.audioContext=t;this.worklet=j;this.worker=e;this.availableIndexes=[];this.medias=new Map;e.addEventListener("message",this._OnMessages.bind(this))}connectOutput(t){this.worklet.disconnect(),this.worklet.connect(t)}receivePacket(t,j){k(this.worker,["playbackReceivePacket",{connectionId:t,packet:j}],[j.buffer])}addMedias(t,j,e=[1,1]){let B=[];for(let C of j){let E=this._GetFreeIndex();E!==void 0&&(this.medias.set(m({connectionId:t,mediaId:C}),{index:E}),B.push({connectionId:t,mediaId:C,index:E,volume:e}))}k(this.worker,["playbackUpdateMedias",{added:B,removed:[]}])}removeMedias(t,j){let e=[];for(let B of j){let C=m({connectionId:t,mediaId:B}),E=this.medias.get(C);E!==void 0&&(this.medias.delete(C),this.availableIndexes.push(E.index),e.push({connectionId:t,mediaId:B,index:E.index}))}k(this.worker,["playbackUpdateMedias",{added:[],removed:e}])}close(){k(this.worker,["close",void 0]),k(this.worklet.port,["close",void 0]);let t=Q.indexOf(this.worker);t>=0&&Q.splice(t,1);let j=R.indexOf(this.worklet);j>=0&&R.splice(j,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,j,e,B,C){this.worklet=t;this.worker=j;this.sink=(E,f)=>{C.deref()!==void 0?e(E,f):(c("capture worker was left abandoned, aborting capture worker"),v.shutdown(t,j))},this.monitorSink=(E,f)=>{C.deref()!==void 0?B(E,f):(c("capture worker was left abandoned, aborting capture worker"),v.shutdown(t,j))},j.addEventListener("message",this._OnMessages.bind(this))}get context(){return this.worklet.context}setMedias(t){k(this.worker,["captureSetMedias",{connections:t}])}setVad(t){k(this.worker,["captureSetVad",t])}close(){v.shutdown(this.worklet,this.worker)}static shutdown(t,j){k(t.port,["close",void 0]),k(j,["close",void 0]);let e=Q.indexOf(j);e>=0&&Q.splice(e,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[j,e]=t.data;j==="sendPacket"&&(e.connectionId===0?this.monitorSink(e.connectionId,e.packet):this.sink(e.connectionId,e.packet))}};Ux=new WeakMap});var Wx,I0=q(()=>{Wx=`"use strict";(()=>{var Cn=Object.create;var or=Object.defineProperty;var Gn=Object.getOwnPropertyDescriptor;var pn=Object.getOwnPropertyNames;var hn=Object.getPrototypeOf,In=Object.prototype.hasOwnProperty;var mn=(n,A)=>()=>(A||n((A={exports:{}}).exports,A),A.exports),En=(n,A)=>{for(var t in A)or(n,t,{get:A[t],enumerable:!0})},$n=(n,A,t,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of pn(A))!In.call(n,i)&&i!==t&&or(n,i,{get:()=>A[i],enumerable:!(e=Gn(A,i))||e.enumerable});return n};var Fn=(n,A,t)=>(t=n!=null?Cn(hn(n)):{},$n(A||!n||!n.__esModule?or(t,"default",{value:n,enumerable:!0}):t,n));var $t=mn((Et,MA)=>{"use strict";var wA=(()=>{var n=globalThis.document?.currentScript?.src;return async function(A={}){var t,e=A,i=!!globalThis.window,d=!!globalThis.WorkerGlobalScope,q=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",C=d&&globalThis.name=="em-pthread",v=[],B="./this.program",CA=(r,j)=>{throw j};d&&(n=self.location.href);var w="",Ht,_t;if(i||d){try{w=new URL(".",n).href}catch{}d&&(_t=r=>{var j=new XMLHttpRequest;return j.open("GET",r,!1),j.responseType="arraybuffer",j.send(null),new Uint8Array(j.response)}),Ht=async r=>{var j=await fetch(r,{credentials:"same-origin"});if(j.ok)return j.arrayBuffer();throw new Error(j.status+" : "+j.url)}}var TA=console.log.bind(console),N=console.error.bind(console),gr,eA,GA=!1,Q;function yt(r){for(var j=0,s=r.length,l=new Uint8Array(s),o;j<s;++j)o=r.charCodeAt(j),l[j]=~o>>8&o;return l}var UA,Lr,Hr;if(C){let r=function(j){try{var s=j.data,l=s.cmd;if(l==="load"){let o=[];self.onmessage=k=>o.push(k),Hr=()=>{postMessage({cmd:"loaded"});for(let k of o)r(k);self.onmessage=r};for(let k of s.handlers)(!e[k]||e[k].proxy)&&(e[k]=(...a)=>{postMessage({cmd:"callHandler",handler:k,args:a})},k=="print"&&(TA=e[k]),k=="printErr"&&(N=e[k]));X=s.wasmMemory,yr(),eA=s.wasmModule,Nr(),Dj()}else if(l==="run"){St(s.pthread_ptr),sr(s.pthread_ptr,0,0,1,0,0),h.threadInitTLS(),tr(s.pthread_ptr),SA||(Ij(),SA=!0);try{Vt(s.start_routine,s.arg)}catch(o){if(o!="unwind")throw o}}else s.target==="setimmediate"||(l==="checkMailbox"?SA&&HA():l&&(N(\`worker: received unknown command \${l}\`),N(s)))}catch(o){throw mj(),o}};var ys=r,SA=!1;self.onunhandledrejection=j=>{throw j.reason||j},self.onmessage=r}var _r=!1;function yr(){var r=X.buffer;V=new Int8Array(r),pA=new Int16Array(r),e.HEAPU8=x=new Uint8Array(r),nA=new Uint16Array(r),e.HEAP32=z=new Int32Array(r),e.HEAPU32=E=new Uint32Array(r),e.HEAPF32=Jr=new Float32Array(r),hA=new Float64Array(r),S=new BigInt64Array(r),Kr=new BigUint64Array(r)}function xt(){if(!C){if(e.wasmMemory)X=e.wasmMemory;else{var r=e.INITIAL_MEMORY||16777216;X=new WebAssembly.Memory({initial:r/65536,maximum:r/65536,shared:!0})}yr()}}function Dt(){if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)Ot(e.preRun.shift());wr(Mr)}function xr(){if(_r=!0,C)return Hr();jA.F()}function Bt(){if(!C){if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)Ut(e.postRun.shift());wr(Vr)}}function VA(r){e.onAbort?.(r),r="Aborted("+r+")",N(r),GA=!0,r+=". Build with -sASSERTIONS for more info.";var j=new WebAssembly.RuntimeError(r);throw Lr?.(j),j}var Dr;function Nt(){return yt(\`\\0asm\\0\\0\\0\\xB2>\\\`\\x7F\\0\\\`\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\\`\\0\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`||\\\`\\x7F}\\\`}}\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\0\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F~\\\`\\x7F\\x7F}\\\`\\x7F}}\\\`\\x7F\\x7F}}\\0\\\`
|
|
1
|
+
var bA=Object.defineProperty;var q=(v,D)=>()=>(v&&(D=v(v=0)),D);var Tx=(v,D)=>{for(var j in D)bA(v,j,{get:D[j],enumerable:!0})};var i={};Tx(i,{AdditionalCaptureBlocks:()=>aA,AdditionalPlaybackBlocks:()=>oA,ClockJumpCheckInterval:()=>hA,ClockJumpThreshold:()=>qA,ConnectInterval:()=>NA,ConnectTimeout:()=>_A,DefaultRefreshRate:()=>uA,DefaultVideoCodec:()=>wA,HealthCheckTimeout:()=>pA,MainConnectionPingInterval:()=>mA,MaxNumberOfDecoders:()=>cA,MinDBFs:()=>Sx,MinTokenLifetime:()=>LA,MinTokenRefreshInterval:()=>HA,PlaybackPreload:()=>lA,RenderQuantumSize:()=>dA,VadPreload:()=>kA,WebRtcAnswerTimeout:()=>$A,WebRtcIceTimeout:()=>IA,WebRtcMaxNegotiationAttempts:()=>yA,WebRtcStatsSnapshotInterval:()=>GA,WebRtcTimeout:()=>gA});var oA,aA,lA,uA,kA,cA,dA,Sx,pA,hA,qA,mA,GA,IA,gA,$A,yA,_A,LA,HA,NA,wA,Rx=q(()=>{"use strict";oA=3,aA=3,lA=3,uA=250,kA=3,cA=512,dA=128,Sx=-758.596,pA=1e4,hA=1e3,qA=1e4,mA=3e3,GA=1e3,IA=3e3,gA=1e4,$A=1e4,yA=3,_A=5e3,LA=6e4,HA=5e3,NA=[0,100,200,200,500],wA="H264"});function vx(v){return typeof v!="symbol"}function l(v){return typeof v=="symbol"}var G,n,J,I,Cx=q(()=>{"use strict";G=Symbol("Unencrypted"),n=Symbol("Invalid"),J=Symbol("Retry"),I=Symbol("UnexpectedEof")});function c(v,D,j){return v.postMessage(D,j)}function U(v,D){return new Promise(j=>{let e=B=>{let[C,E]=B.data;C===D&&(j(B.data[1]),v.removeEventListener("message",e))};v.addEventListener("message",e)})}var C0=q(()=>{"use strict"});function Vx(v,D){v.values[0]=D[0],v.values[1]=D[1]}function E0(v,D){return v.values[2+D*5]}function f0(v,D,j){let e=2+D*5+1;v.values[e+0]=j[0],v.values[e+1]=j[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,D){return v.values[3]=D}var o0=q(()=>{"use strict"});function a0(v,D){let j=new O(v);j.position=D;let e=j.readObjects(1);return vx(e)?j.position:e}var O,l0=q(()=>{"use strict";Cx();O=class{constructor(D,j=0){this.bytes=D;this.position=j}readArrayLength(){let D=this.readTag();return l(D)?D:(D&240)===144?D&15:D===220?this.readUint16():D===221?this.readUint32():n}readNumber(){let D=this.readTag();return l(D)||(D&128)===0?D:(D&224)===224?D-256:D===202?this.readFloat32():D===203?this.readFloat64():D===204?this.readUint8():D===205?this.readUint16():D===206?this.readUint32():D===207?this.readUint64():D===208?this.readInt8():D===209?this.readInt16():D===210?this.readInt32():D===211?this.readInt64():n}readBytes(){let D=this.readTag();if(l(D))return D;let j;if(D===196)j=this.readUint8();else if(D===197)j=this.readUint16();else if(D===198)j=this.readUint32();else return n;if(l(j))return j;let e=this.consume(j);return e!==I?this.bytes.subarray(e,e+j):I}readObjects(D){for(;D>0;D-=1){let j=this.readTag();if(l(j))return j;let e,B=0,C=0;switch(j){case 192:break;case 194:break;case 195:break;case 196:B=this.readUint8();break;case 197:B=this.readUint16();break;case 198:B=this.readUint32();break;case 199:B=this.readUint8(),C=1;break;case 200:B=this.readUint8(),C=1;break;case 201:B=this.readUint32(),C=1;break;case 202:B=4;break;case 203:B=8;break;case 204:B=1;break;case 205:B=2;break;case 206:B=4;break;case 207:B=8;break;case 208:B=1;break;case 209:B=2;break;case 210:B=4;break;case 211:B=8;break;case 212:B=2;break;case 213:B=3;break;case 214:B=5;break;case 215:B=9;break;case 216:B=17;break;case 217:B=this.readUint8();break;case 218:B=this.readUint16();break;case 219:B=this.readUint32();break;case 220:if(e=this.readUint16(),l(e))return e;D+=e;break;case 221:if(e=this.readUint32(),l(e))return e;D+=e;break;case 222:if(e=this.readUint16(),l(e))return e;D+=e*2;break;case 223:if(e=this.readUint32(),l(e))return e;D+=e*2;break;default:if((j&128)!==0){if((j&240)===128)D+=(j&15)*2;else if((j&240)===144)D+=j&15;else if((j&224)===160)B=j&31;else if((j&224)!==224)return n}}if(B===I)return I;if(this.consume(B+C)===I)return I}}consume(D){if(D===I||this.position+D>this.bytes.length)return I;let j=this.position;return this.position=j+D,j}readTag(){let D=this.consume(1);return vx(D)?this.bytes[D]:D}readUint8(){let D=this.consume(1);return vx(D)?this.bytes[D]:D}readUint16(){let D=this.consume(2);return l(D)?D:this.bytes[D]<<8|this.bytes[D+1]}readUint32(){let D=this.consume(4);return l(D)?D:this.bytes[D]<<24|this.bytes[D+1]<<16|this.bytes[D+2]<<8|this.bytes[D+3]}readUint64(){let D=this.readUint32();if(l(D))return D;if(D>=2097152)return n;let j=this.readUint32();return l(j)?j:D<<32|j}readInt8(){let D=this.readUint8();return l(D)||D>=128&&(D=D-256),D}readInt16(){let D=this.readUint16();return l(D)||D>=32768&&(D=D-65536),D}readInt32(){let D=this.readUint32();return l(D)||D>=2147483648&&(D=D-4294967296),D}readInt64(){let D=this.readUint32();if(l(D))return D;if(D>=2097152||D<-2097152)return n;let j=this.readUint32();return l(j)?j:D<<32|j}readFloat32(){let D=this.consume(4);return l(D)?D:new Float32Array(this.bytes.subarray(D,D+4))[0]}readFloat64(){let D=this.consume(8);return l(D)?D:new Float64Array(this.bytes.subarray(D,D+8))[0]}}});var u0,k0=q(()=>{"use strict";u0="1.10.1"});import{error as PA,warn as KA,info as JA,debug as OA,Logger as MA,LogLevel as TA,CallbackSink as SA,Formatter as RA}from"@4players/odin-common";function c0(v,D){g||(g=v??new MA(TA.DEBUG,"odin-plugin-web",[]),D&&g.sinks.push(new SA(D,RA.structured)))}function p(v,...D){let j=Ex(D);g?g?.error(v,j):PA(v,j)}function k(v,...D){let j=Ex(D);g?g?.warn(v,j):KA(v,j)}function o(v,...D){let j=Ex(D);g?g?.info(v,j):JA(v,j)}function a(v,...D){let j=Ex(D);g?g?.debug(v,j):OA(v,j)}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 g,d0=q(()=>{"use strict"});function m(v){return v.connectionId*4294967296+v.mediaId}var _,S,u=q(()=>{"use strict";Rx();Cx();Rx();C0();o0();l0();k0();d0();Cx();_={isSilent:!0,rmsDBFS:-758.596};S=class{constructor(){this.inFlight=null}run(D){return this.inFlight||(this.inFlight=D().finally(()=>{this.inFlight=null})),this.inFlight}}});function Y(v,D,j,e,B){return Promise.all([XA(v),ZA(j,D,e,B)])}async function XA(v){let D=URL.createObjectURL(new Blob([v],{type:"text/javascript"})),j=new Worker(D,{type:"module",name:"odin worker"});return Q.push(j),j}async function ZA(v,D,j,e){try{let E=new AudioWorkletNode(v,j,e);return R.push(E),E}catch{}let B=Ux.get(v);if(B===void 0){let E=URL.createObjectURL(new Blob([D],{type:"text/javascript"}));B=v.audioWorklet.addModule(E),Ux.set(v,B),B.catch(()=>Ux.delete(v))}await B;let C=new AudioWorkletNode(v,j,e);return R.push(C),C}async function m0(){return{workers:await Promise.all(Q.map(Z)),worklets:await Promise.all(R.map(v=>Z(v.port)))}}function Z(v){let{port1:D,port2:j}=new MessageChannel,{promise:e,resolve:B}=Promise.withResolvers();return j.onmessage=C=>B(C.data),setTimeout(()=>B("timeout"),100),c(v,["dump",{result:D}],[D]),e}var Q,R,z,X,Ux,nx=q(()=>{"use strict";u();Q=[],R=[],z=class{constructor(D,j,e){this.audioContext=D;this.worklet=j;this.worker=e;this.availableIndexes=[];this.medias=new Map;e.addEventListener("message",this._OnMessages.bind(this))}connectOutput(D){this.worklet.disconnect(),this.worklet.connect(D)}receivePacket(D,j){c(this.worker,["playbackReceivePacket",{connectionId:D,packet:j}],[j.buffer])}addMedias(D,j,e=[1,1]){let B=[];for(let C of j){let E=this._GetFreeIndex();E!==void 0&&(this.medias.set(m({connectionId:D,mediaId:C}),{index:E}),B.push({connectionId:D,mediaId:C,index:E,volume:e}))}c(this.worker,["playbackUpdateMedias",{added:B,removed:[]}])}removeMedias(D,j){let e=[];for(let B of j){let C=m({connectionId:D,mediaId:B}),E=this.medias.get(C);E!==void 0&&(this.medias.delete(C),this.availableIndexes.push(E.index),e.push({connectionId:D,mediaId:B,index:E.index}))}c(this.worker,["playbackUpdateMedias",{added:[],removed:e}])}close(){c(this.worker,["close",void 0]),c(this.worklet.port,["close",void 0]);let D=Q.indexOf(this.worker);D>=0&&Q.splice(D,1);let j=R.indexOf(this.worklet);j>=0&&R.splice(j,1)}async dump(){return{playbackWorker:await Z(this.worker),playbackWorklet:await Z(this.worklet.port)}}_GetFreeIndex(){return this.availableIndexes.pop()}_OnMessages(D){}},X=class v{constructor(D,j,e,B,C){this.worklet=D;this.worker=j;this.sink=(E,f)=>{C.deref()!==void 0?e(E,f):(p("capture worker was left abandoned, aborting capture worker"),v.shutdown(D,j))},this.monitorSink=(E,f)=>{C.deref()!==void 0?B(E,f):(p("capture worker was left abandoned, aborting capture worker"),v.shutdown(D,j))},j.addEventListener("message",this._OnMessages.bind(this))}get context(){return this.worklet.context}setMedias(D){c(this.worker,["captureSetMedias",{connections:D}])}setVad(D){c(this.worker,["captureSetVad",D])}close(){v.shutdown(this.worklet,this.worker)}static shutdown(D,j){c(D.port,["close",void 0]),c(j,["close",void 0]);let e=Q.indexOf(j);e>=0&&Q.splice(e,1);let B=R.indexOf(D);B>=0&&R.splice(B,1)}async dump(){return{captureWorker:await Z(this.worker),captureWorklet:await Z(this.worklet.port)}}_OnMessages(D){let[j,e]=D.data;j==="sendPacket"&&(e.connectionId===0?this.monitorSink(e.connectionId,e.packet):this.sink(e.connectionId,e.packet))}};Ux=new WeakMap});var Wx,G0=q(()=>{Wx=`"use strict";(()=>{var Cn=Object.create;var or=Object.defineProperty;var Gn=Object.getOwnPropertyDescriptor;var pn=Object.getOwnPropertyNames;var hn=Object.getPrototypeOf,In=Object.prototype.hasOwnProperty;var mn=(n,A)=>()=>(A||n((A={exports:{}}).exports,A),A.exports),En=(n,A)=>{for(var t in A)or(n,t,{get:A[t],enumerable:!0})},$n=(n,A,t,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of pn(A))!In.call(n,i)&&i!==t&&or(n,i,{get:()=>A[i],enumerable:!(e=Gn(A,i))||e.enumerable});return n};var Fn=(n,A,t)=>(t=n!=null?Cn(hn(n)):{},$n(A||!n||!n.__esModule?or(t,"default",{value:n,enumerable:!0}):t,n));var $t=mn((Et,MA)=>{"use strict";var wA=(()=>{var n=globalThis.document?.currentScript?.src;return async function(A={}){var t,e=A,i=!!globalThis.window,d=!!globalThis.WorkerGlobalScope,q=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",C=d&&globalThis.name=="em-pthread",v=[],B="./this.program",CA=(r,j)=>{throw j};d&&(n=self.location.href);var w="",Ht,_t;if(i||d){try{w=new URL(".",n).href}catch{}d&&(_t=r=>{var j=new XMLHttpRequest;return j.open("GET",r,!1),j.responseType="arraybuffer",j.send(null),new Uint8Array(j.response)}),Ht=async r=>{var j=await fetch(r,{credentials:"same-origin"});if(j.ok)return j.arrayBuffer();throw new Error(j.status+" : "+j.url)}}var TA=console.log.bind(console),N=console.error.bind(console),gr,eA,GA=!1,Q;function yt(r){for(var j=0,s=r.length,l=new Uint8Array(s),o;j<s;++j)o=r.charCodeAt(j),l[j]=~o>>8&o;return l}var UA,Lr,Hr;if(C){let r=function(j){try{var s=j.data,l=s.cmd;if(l==="load"){let o=[];self.onmessage=k=>o.push(k),Hr=()=>{postMessage({cmd:"loaded"});for(let k of o)r(k);self.onmessage=r};for(let k of s.handlers)(!e[k]||e[k].proxy)&&(e[k]=(...a)=>{postMessage({cmd:"callHandler",handler:k,args:a})},k=="print"&&(TA=e[k]),k=="printErr"&&(N=e[k]));X=s.wasmMemory,yr(),eA=s.wasmModule,Nr(),Dj()}else if(l==="run"){St(s.pthread_ptr),sr(s.pthread_ptr,0,0,1,0,0),h.threadInitTLS(),tr(s.pthread_ptr),SA||(Ij(),SA=!0);try{Vt(s.start_routine,s.arg)}catch(o){if(o!="unwind")throw o}}else s.target==="setimmediate"||(l==="checkMailbox"?SA&&HA():l&&(N(\`worker: received unknown command \${l}\`),N(s)))}catch(o){throw mj(),o}};var Ds=r,SA=!1;self.onunhandledrejection=j=>{throw j.reason||j},self.onmessage=r}var _r=!1;function yr(){var r=X.buffer;V=new Int8Array(r),pA=new Int16Array(r),e.HEAPU8=x=new Uint8Array(r),nA=new Uint16Array(r),e.HEAP32=z=new Int32Array(r),e.HEAPU32=E=new Uint32Array(r),e.HEAPF32=Jr=new Float32Array(r),hA=new Float64Array(r),S=new BigInt64Array(r),Kr=new BigUint64Array(r)}function xt(){if(!C){if(e.wasmMemory)X=e.wasmMemory;else{var r=e.INITIAL_MEMORY||16777216;X=new WebAssembly.Memory({initial:r/65536,maximum:r/65536,shared:!0})}yr()}}function Dt(){if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)Ot(e.preRun.shift());wr(Mr)}function xr(){if(_r=!0,C)return Hr();jA.F()}function Bt(){if(!C){if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)Ut(e.postRun.shift());wr(Vr)}}function VA(r){e.onAbort?.(r),r="Aborted("+r+")",N(r),GA=!0,r+=". Build with -sASSERTIONS for more info.";var j=new WebAssembly.RuntimeError(r);throw Lr?.(j),j}var Dr;function Nt(){return yt(\`\\0asm\\0\\0\\0\\xB2>\\\`\\x7F\\0\\\`\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\\`\\0\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`||\\\`\\x7F}\\\`}}\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\0\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F~\\\`\\x7F\\x7F}\\\`\\x7F}}\\\`\\x7F\\x7F}}\\0\\\`
|
|
2
2
|
\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`|}\\\`|\\x7F|\\\`\\x7F\\x7F}\\0\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\` \\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\f\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F|\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F|}\\\`\\0|\\\`\\x7F\\x7F\\x7F~~\\0\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F|\\\`\\r\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F\\x7F\\x7F\\\`\\x7F\\x7F|\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\x7F\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F}}\\x7F\\x7F\\x7F\\x7F\\0\\\`~\\x7F\\x7F\\\` \\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\\`||\\x7F|\\\`|||\\\`\\x7F\\x7F\\x7F|\\\`\\x7F\\x7F|\\x7F\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\\`\\f\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`}\\x7F\\x7F\\\`|\\x7F\\x7F\\\`\\x7F\\x7F\\x7F}\\\`\\x7F}\\x7F\\0\\\`\\x7F\\x7F}\\x7F\\x7F\\x7F}\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F}}\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F|\\\`\\x7F\\x7F|\\0\\xBFab\\0ac\\0ad\\0ae\\0af\\0!ag\\0ah\\0"ai\\0aj\\0
|
|
3
3
|
ak\\0#al\\0am\\0 an\\0$ao\\0ap\\0aq\\0ar\\0\\0as\\0\\0at\\0au\\0av\\0%aw\\0ax\\0\\bay\\0\\0az\\0\\0aA\\0\\baB\\0\\0aC\\0\\baD\\0\\0aE\\0aa\\x80\\x80\\xFB\\xF9\\0\\x07\\f&\\0\\f\\x07\\f\\f\\0\\x07\\0\\x07'(
|
|
4
4
|
\\b\\v)\\x07*\\0\\f+,-\\v\\0\\0\\x07\\0.\\b\\b\\x1B
|
|
@@ -3222,7 +3222,7 @@ K\\xE08\\xDF\\0}\\xBC\\x8A\\x1B\\f\\xE5\\xFF\\xCF\\xE8?\\x9F\\xFFFq\\0\\x88\\xB
|
|
|
3222
3222
|
|
|
3223
3223
|
|
|
3224
3224
|
\\x07\\0\\0 \\v\\0\\0 \\v\\0\\0\\v\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\v\\r\\0\\r\\0\\0\\0 \\0\\0\\0 \\0\\0\\0!\\f\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\f\\0\\0\\0\\0\\0\\f\\0\\0\\f!\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0*\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 !\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\xC0 \\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\x000123456789ABCDEF\\xA0\\0\\xF8\\0NSt3__214__shared_countE\\0\\0\\0\\0$\\0,\\0\\0\\0\\0\\0\\0\\0\\0\\xF0\\0\\0\\0\\0\\0NSt3__219__shared_weak_countE\\0\\0\\0\\xC8\\0X\\0h\\0N10__cxxabiv116__shim_type_infoE\\0\\0\\0\\0\\xC8\\0\\x88\\0L\\0N10__cxxabiv117__class_type_infoE\\0\\0\\0\\xC8\\0\\xB8\\0L\\0N10__cxxabiv117__pbase_type_infoE\\0\\0\\0\\xC8\\0\\xE8\\0\\xAC\\0N10__cxxabiv119__pointer_type_infoE\\0\\xC8\\0\\0L\\0N10__cxxabiv120__function_type_infoE\\0\\0\\0\\0\\xC8\\0L\\0\\xAC\\0N10__cxxabiv129__pointer_to_member_type_infoE\\0\\0\\0\\0\\0\\0\\0\\x98\\0n\\0\\0\\0o\\0\\0\\0p\\0\\0\\0q\\0\\0\\0r\\0\\0\\0\\xC8\\0\\xA4\\0L\\0N10__cxxabiv123__fundamental_type_infoE\\0\\x84\\0\\xD4\\0v\\0Dn\\0\\0\\0\\0\\x84\\0\\xE4\\0b\\0\\0\\0\\x84\\0\\xF0\\0c\\0\\0\\0\\x84\\0\\xFC\\0h\\0\\0\\0\\x84\\0\\b\\0a\\0\\0\\0\\x84\\0\\0s\\0\\0\\0\\x84\\0 \\0t\\0\\0\\0\\x84\\0,\\0i\\0\\0\\0\\x84\\x008\\0j\\0\\0\\0\\x84\\0D\\0l\\0\\0\\0\\x84\\0P\\0m\\0\\0\\0\\x84\\0\\\\\\0x\\0\\0\\0\\x84\\0h\\0y\\0\\0\\0\\x84\\0t\\0f\\0\\0\\0\\x80\\0\\x88\\0\\0\\0\\0\\0l\\0Pf\\0\\0\\x84\\0\\x94\\0d\\0\\0\\0\\0\\0\\0\\0|\\0n\\0\\0\\0s\\0\\0\\0p\\0\\0\\0q\\0\\0\\0t\\0\\0\\0u\\0\\0\\0v\\0\\0\\0w\\0\\0\\0\\0\\0\\0\\0\\xE8\\0n\\0\\0\\0x\\0\\0\\0p\\0\\0\\0q\\0\\0\\0t\\0\\0\\0y\\0\\0\\0z\\0\\0\\0{\\0\\0\\0\\xC8\\0\\xF4\\0|\\0N10__cxxabiv120__si_class_type_infoE\\0\\0\\0\\0\\0\\0\\0\\0D\\0n\\0\\0\\0|\\0\\0\\0p\\0\\0\\0q\\0\\0\\0t\\0\\0\\0}\\0\\0\\0~\\0\\0\\0\\x7F\\0\\0\\0\\xC8\\0P\\0|\\0N10__cxxabiv121__vmi_class_type_infoE\\0\\0\\0\\0\\0\\0\\0\\xDC\\0n\\0\\0\\0\\x80\\0\\0\\0p\\0\\0\\0q\\0\\0\\0\\x81\\0\\0\\0\\0\\0\\0\\0\\xDC\\0F\\0\\0\\0\\x82\\0\\0\\0\\x83\\0\\0\\0\\xA0\\0\\xB0\\0St9exception\\0\\0\\0\\0\\xC8\\0\\xCC\\0\\xA8\\0St9bad_alloc\\0\\0\\0\\0\\xC8\\0\\xE8\\0\\xC0\\0St20bad_array_new_length\\0\\0\\0\\0\\0\\0\\0\\0\\0H\\0\\0\\0\\x84\\0\\0\\0\\x85\\0\\0\\0\\xC8\\0$\\0\\xA8\\0St11logic_error\\0\\0\\0\\0\\0H\\0H\\0\\0\\0\\x86\\0\\0\\0\\x85\\0\\0\\0\\xC8\\0T\\0\\0St12length_error\\0\\0\\0\\0\\xA0\\0p\\0St9type_info\\0\\\`\\x80\\0\\x80\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0f\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0g\\0\\0\\0h\\0\\0\\0P\\x1B\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFFY\\xC0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0i\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0g\\0\\0\\0j\\0\\0\\0X\\x1B\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\xFF\\xFF\\xFF\\xFF
|
|
3225
|
-
\\fX\\0\\x90!\\0\\0\\0\\0\`)}function _s(r){return r}async function bt(r){return r}async function Jt(r,j){try{var s=await bt(r),l=await WebAssembly.instantiate(s,j);return l}catch(o){N(\`failed to asynchronously prepare wasm: \${o}\`),VA(o)}}async function Kt(r,j,s){return Jt(j,s)}function Br(){qn();var r={a:xj};return r}async function Nr(){function r(a,u){return jA=a.exports,Rt(jA.M),dn(jA),eA=u,jA}function j(a){return r(a.instance,a.module)}var s=Br();if(e.instantiateWasm)return new Promise((a,u)=>{e.instantiateWasm(s,(c,f)=>{a(r(c,f))})});if(C){var l=new WebAssembly.Instance(eA,Br());return r(l,eA)}Dr??=Nt();var o=await Kt(gr,Dr,s),k=j(o);return k}class br{name="ExitStatus";constructor(j){this.message=\`Program terminated with exit(\${j})\`,this.status=j}}var pA,z,S,V,Jr,hA,nA,E,Kr,x,Or=r=>{r.terminate(),r.onmessage=j=>{}},Pr=r=>{var j=h.pthreads[r];h.returnWorkerToPool(j)},wr=r=>{for(;r.length>0;)r.shift()(e)},Mr=[],Ot=r=>Mr.push(r),Pt=r=>{var j=h.getNewWorker();if(!j)return 6;h.runningWorkers.push(j),h.pthreads[r.pthread_ptr]=j,j.pthread_ptr=r.pthread_ptr;var s={cmd:"run",start_routine:r.startRoutine,arg:r.arg,pthread_ptr:r.pthread_ptr};return j.postMessage(s,r.transferList),0},RA=0,WA=()=>zA||RA>0,wt=()=>_j(),Tr=r=>Lj(r),Mt=r=>Hj(r),sA=(r,j,s,...l)=>{var o=8*l.length*2,k=wt(),a=Mt(o),u=a>>3;for(var c of l)typeof c=="bigint"?(S[u++]=1n,S[u++]=c):(S[u++]=0n,hA[u++]=c);var f=$j(r,j,o,a,s);return Tr(k),f};function Ur(r){if(C)return sA(0,0,1,r);Q=r,WA()||(h.terminateAllThreads(),e.onExit?.(r),GA=!0),CA(r,new br(r))}function Sr(r){if(C)return sA(1,0,0,r);QA(r)}var Tt=(r,j)=>{if(Q=r,C)throw Sr(r),"unwind";Ur(r)},QA=Tt,h={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init(){C||h.initMainThread()},initMainThread(){},terminateAllThreads:()=>{for(var r of h.runningWorkers)Or(r);for(var r of h.unusedWorkers)Or(r);h.unusedWorkers=[],h.runningWorkers=[],h.pthreads={}},returnWorkerToPool:r=>{var j=r.pthread_ptr;delete h.pthreads[j],h.unusedWorkers.push(r),h.runningWorkers.splice(h.runningWorkers.indexOf(r),1),r.pthread_ptr=0,Fj(j)},threadInitTLS(){h.tlsInitFunctions.forEach(r=>r())},loadWasmModuleToWorker:r=>new Promise(j=>{r.onmessage=k=>{var a=k.data,u=a.cmd;if(a.targetThread&&a.targetThread!=_A()){var c=h.pthreads[a.targetThread];c?c.postMessage(a,a.transferList):N(\`Internal error! Worker sent a message "\${u}" to target pthread \${a.targetThread}, but that thread no longer exists!\`);return}u==="checkMailbox"?HA():u==="spawnThread"?Pt(a):u==="cleanupThread"?fj(()=>Pr(a.thread)):u==="loaded"?(r.loaded=!0,j(r)):a.target==="setimmediate"?r.postMessage(a):u==="callHandler"?e[a.handler](...a.args):u&&N(\`worker sent an unknown command \${u}\`)},r.onerror=k=>{var a="worker sent an error!";throw N(\`\${a} \${k.filename}:\${k.lineno}: \${k.message}\`),k};var s=[],l=["onExit","onAbort","print","printErr"];for(var o of l)e.propertyIsEnumerable(o)&&s.push(o);r.postMessage({cmd:"load",handlers:s,wasmMemory:X,wasmModule:eA})}),allocateUnusedWorker(){var r,j=n;e.mainScriptUrlOrBlob&&(j=e.mainScriptUrlOrBlob,typeof j!="string"&&(j=URL.createObjectURL(j))),r=new Worker(j,{name:"em-pthread"}),h.unusedWorkers.push(r)},getNewWorker(){return h.unusedWorkers.length==0&&(h.allocateUnusedWorker(),h.loadWasmModuleToWorker(h.unusedWorkers[0])),h.unusedWorkers.pop()}},Vr=[],Ut=r=>Vr.push(r);function St(r){var j=E[r+48>>2],s=E[r+52>>2],l=j-s;gj(j,l),Tr(j)}var Rr=[],Wr=r=>{var j=Rr[r];return j||(Rr[r]=j=yj.get(r)),j},Vt=(r,j)=>{RA=0,zA=0;var s=Wr(r)(j);function l(o){if(WA()){Q=o;return}ir(o)}l(s)},zA=!0,Rt=r=>h.tlsInitFunctions.push(r),X;class Wt{constructor(j){this.excPtr=j,this.ptr=j-24}set_type(j){E[this.ptr+4>>2]=j}get_type(){return E[this.ptr+4>>2]}set_destructor(j){E[this.ptr+8>>2]=j}get_destructor(){return E[this.ptr+8>>2]}set_caught(j){j=j?1:0,V[this.ptr+12]=j}get_caught(){return V[this.ptr+12]!=0}set_rethrown(j){j=j?1:0,V[this.ptr+13]=j}get_rethrown(){return V[this.ptr+13]!=0}init(j,s){this.set_adjusted_ptr(0),this.set_type(j),this.set_destructor(s)}set_adjusted_ptr(j){E[this.ptr+16>>2]=j}get_adjusted_ptr(){return E[this.ptr+16>>2]}}var Qr=0,Qt=0,zt=(r,j,s)=>{var l=new Wt(r);throw l.init(j,s),Qr=r,Qt++,Qr},Xt=()=>VA(""),g=r=>{for(var j="";;){var s=x[r++];if(!s)return j;j+=String.fromCharCode(s)}},Z={},Y={},IA={},iA=class extends Error{constructor(j){super(j),this.name="BindingError"}},p=r=>{throw new iA(r)};function Zt(r,j,s={}){var l=j.name;if(r||p(\`type "\${l}" must have a positive integer typeid pointer\`),Y.hasOwnProperty(r)){if(s.ignoreDuplicateRegistrations)return;p(\`Cannot register type '\${l}' twice\`)}if(Y[r]=j,delete IA[r],Z.hasOwnProperty(r)){var o=Z[r];delete Z[r],o.forEach(k=>k())}}function b(r,j,s={}){return Zt(r,j,s)}var zr=(r,j,s)=>{switch(j){case 1:return s?l=>V[l]:l=>x[l];case 2:return s?l=>pA[l>>1]:l=>nA[l>>1];case 4:return s?l=>z[l>>2]:l=>E[l>>2];case 8:return s?l=>S[l>>3]:l=>Kr[l>>3];default:throw new TypeError(\`invalid integer width (\${j}): \${r}\`)}},Yt=(r,j,s,l,o)=>{j=g(j);let k=l===0n,a=u=>u;if(k){let u=s*8;a=c=>BigInt.asUintN(u,c),o=a(o)}b(r,{name:j,fromWireType:a,toWireType:(u,c)=>(typeof c=="number"&&(c=BigInt(c)),c),readValueFromPointer:zr(j,s,!k),destructorFunction:null})},Ae=(r,j,s,l)=>{j=g(j),b(r,{name:j,fromWireType:function(o){return!!o},toWireType:function(o,k){return k?s:l},readValueFromPointer:function(o){return this.fromWireType(x[o])},destructorFunction:null})},re=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(s){return s.$$.ptrType.registeredClass.name}p(j(r)+" instance already deleted")},ZA=!1,Xr=r=>{},je=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&&je(r)},lA=r=>globalThis.FinalizationRegistry?(ZA=new FinalizationRegistry(j=>{Zr(j.$$)}),lA=j=>{var s=j.$$,l=!!s.smartPtr;if(l){var o={$$:s};ZA.register(j,o,j)}return j},Xr=j=>ZA.unregister(j),lA(r)):(lA=j=>j,r),mA=[],te=()=>{for(;mA.length;){var r=mA.pop();r.$$.deleteScheduled=!1,r.delete()}},Yr,ee=()=>{let r=EA.prototype;Object.assign(r,{isAliasOf(s){if(!(this instanceof EA)||!(s instanceof EA))return!1;var l=this.$$.ptrType.registeredClass,o=this.$$.ptr;s.$$=s.$$;for(var k=s.$$.ptrType.registeredClass,a=s.$$.ptr;l.baseClass;)o=l.upcast(o),l=l.baseClass;for(;k.baseClass;)a=k.upcast(a),k=k.baseClass;return l===k&&o===a},clone(){if(this.$$.ptr||XA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var s=lA(Object.create(Object.getPrototypeOf(this),{$$:{value:re(this.$$)}}));return s.$$.count.value+=1,s.$$.deleteScheduled=!1,s},delete(){this.$$.ptr||XA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&p("Object already scheduled for deletion"),Xr(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&&p("Object already scheduled for deletion"),mA.push(this),mA.length===1&&Yr&&Yr(te),this.$$.deleteScheduled=!0,this}});let j=Symbol.dispose;j&&(r[j]=r.delete)};function EA(){}var Aj=(r,j)=>Object.defineProperty(j,"name",{value:r}),rj={},jj=(r,j,s)=>{if(r[j].overloadTable===void 0){var l=r[j];r[j]=function(...o){return r[j].overloadTable.hasOwnProperty(o.length)||p(\`Function '\${s}' called with an invalid number of arguments (\${o.length}) - expects one of (\${r[j].overloadTable})!\`),r[j].overloadTable[o.length].apply(this,o)},r[j].overloadTable=[],r[j].overloadTable[l.argCount]=l}},tj=(r,j,s)=>{e.hasOwnProperty(r)?((s===void 0||e[r].overloadTable!==void 0&&e[r].overloadTable[s]!==void 0)&&p(\`Cannot register public name '\${r}' twice\`),jj(e,r,r),e[r].overloadTable.hasOwnProperty(s)&&p(\`Cannot register multiple overloads of a function with the same number of arguments (\${s})!\`),e[r].overloadTable[s]=j):(e[r]=j,e[r].argCount=s)},ne=48,se=57,ie=r=>{r=r.replace(/[^a-zA-Z0-9_]/g,"$");var j=r.charCodeAt(0);return j>=ne&&j<=se?\`_\${r}\`:r};function le(r,j,s,l,o,k,a,u){this.name=r,this.constructor=j,this.instancePrototype=s,this.rawDestructor=l,this.baseClass=o,this.getActualType=k,this.upcast=a,this.downcast=u,this.pureVirtualFunctions=[]}var $A=(r,j,s)=>{for(;j!==s;)j.upcast||p(\`Expected null or instance of \${s.name}, got an instance of \${j.name}\`),r=j.upcast(r),j=j.baseClass;return r},YA=r=>{if(r===null)return"null";var j=typeof r;return j==="object"||j==="array"||j==="function"?r.toString():""+r};function oe(r,j){if(j===null)return this.isReference&&p(\`null is not a valid \${this.name}\`),0;j.$$||p(\`Cannot pass "\${YA(j)}" as a \${this.name}\`),j.$$.ptr||p(\`Cannot pass deleted object as a pointer of type \${this.name}\`);var s=j.$$.ptrType.registeredClass,l=$A(j.$$.ptr,s,this.registeredClass);return l}function ae(r,j){var s;if(j===null)return this.isReference&&p(\`null is not a valid \${this.name}\`),this.isSmartPointer?(s=this.rawConstructor(),r!==null&&r.push(this.rawDestructor,s),s):0;(!j||!j.$$)&&p(\`Cannot pass "\${YA(j)}" as a \${this.name}\`),j.$$.ptr||p(\`Cannot pass deleted object as a pointer of type \${this.name}\`),!this.isConst&&j.$$.ptrType.isConst&&p(\`Cannot convert argument of type \${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type \${this.name}\`);var l=j.$$.ptrType.registeredClass;if(s=$A(j.$$.ptr,l,this.registeredClass),this.isSmartPointer)switch(j.$$.smartPtr===void 0&&p("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:j.$$.smartPtrType===this?s=j.$$.smartPtr:p(\`Cannot convert argument of type \${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type \${this.name}\`);break;case 1:s=j.$$.smartPtr;break;case 2:if(j.$$.smartPtrType===this)s=j.$$.smartPtr;else{var o=j.clone();s=this.rawShare(s,jr.toHandle(()=>o.delete())),r!==null&&r.push(this.rawDestructor,s)}break;default:p("Unsupported sharing policy")}return s}function ke(r,j){if(j===null)return this.isReference&&p(\`null is not a valid \${this.name}\`),0;j.$$||p(\`Cannot pass "\${YA(j)}" as a \${this.name}\`),j.$$.ptr||p(\`Cannot pass deleted object as a pointer of type \${this.name}\`),j.$$.ptrType.isConst&&p(\`Cannot convert argument of type \${j.$$.ptrType.name} to parameter type \${this.name}\`);var s=j.$$.ptrType.registeredClass,l=$A(j.$$.ptr,s,this.registeredClass);return l}function FA(r){return this.fromWireType(E[r>>2])}var ej=(r,j,s)=>{if(j===s)return r;if(s.baseClass===void 0)return null;var l=ej(r,j,s.baseClass);return l===null?null:s.downcast(l)},ue={},ce=(r,j)=>{for(j===void 0&&p("ptr should not be undefined");r.baseClass;)j=r.upcast(j),r=r.baseClass;return j},de=(r,j)=>(j=ce(r,j),ue[j]),qe=class extends Error{constructor(j){super(j),this.name="InternalError"}},vA=r=>{throw new qe(r)},gA=(r,j)=>{(!j.ptrType||!j.ptr)&&vA("makeClassHandle requires ptr and ptrType");var s=!!j.smartPtrType,l=!!j.smartPtr;return s!==l&&vA("Both smartPtrType and smartPtr must be specified"),j.count={value:1},lA(Object.create(r,{$$:{value:j,writable:!0}}))};function fe(r){var j=this.getPointee(r);if(!j)return this.destructor(r),null;var s=de(this.registeredClass,j);if(s!==void 0){if(s.$$.count.value===0)return s.$$.ptr=j,s.$$.smartPtr=r,s.clone();var l=s.clone();return this.destructor(r),l}function o(){return this.isSmartPointer?gA(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:j,smartPtrType:this,smartPtr:r}):gA(this.registeredClass.instancePrototype,{ptrType:this,ptr:r})}var k=this.registeredClass.getActualType(j),a=rj[k];if(!a)return o.call(this);var u;this.isConst?u=a.constPointerType:u=a.pointerType;var c=ej(j,this.registeredClass,u.registeredClass);return c===null?o.call(this):this.isSmartPointer?gA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c,smartPtrType:this,smartPtr:r}):gA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c})}var Ce=()=>{Object.assign(LA.prototype,{getPointee(r){return this.rawGetPointee&&(r=this.rawGetPointee(r)),r},destructor(r){this.rawDestructor?.(r)},readValueFromPointer:FA,fromWireType:fe})};function LA(r,j,s,l,o,k,a,u,c,f,G){this.name=r,this.registeredClass=j,this.isReference=s,this.isConst=l,this.isSmartPointer=o,this.pointeeType=k,this.sharingPolicy=a,this.rawGetPointee=u,this.rawConstructor=c,this.rawShare=f,this.rawDestructor=G,!o&&j.baseClass===void 0?l?(this.toWireType=oe,this.destructorFunction=null):(this.toWireType=ke,this.destructorFunction=null):this.toWireType=ae}var nj=(r,j,s)=>{e.hasOwnProperty(r)||vA("Replacing nonexistent public symbol"),e[r].overloadTable!==void 0&&s!==void 0?e[r].overloadTable[s]=j:(e[r]=j,e[r].argCount=s)},K=(r,j,s=!1)=>{r=g(r);function l(){var k=Wr(j);return k}var o=l();return typeof o!="function"&&p(\`unknown function pointer with signature \${r}: \${j}\`),o};class Ge extends Error{}var pe=r=>{var j=hj(r),s=g(j);return O(j),s},AA=(r,j)=>{var s=[],l={};function o(k){if(!l[k]&&!Y[k]){if(IA[k]){IA[k].forEach(o);return}s.push(k),l[k]=!0}}throw j.forEach(o),new Ge(\`\${r}: \`+s.map(pe).join([", "]))},M=(r,j,s)=>{r.forEach(u=>IA[u]=j);function l(u){var c=s(u);c.length!==r.length&&vA("Mismatched type converter count");for(var f=0;f<r.length;++f)b(r[f],c[f])}var o=new Array(j.length),k=[],a=0;for(let[u,c]of j.entries())Y.hasOwnProperty(c)?o[u]=Y[c]:(k.push(c),Z.hasOwnProperty(c)||(Z[c]=[]),Z[c].push(()=>{o[u]=Y[c],++a,a===k.length&&l(o)}));k.length===0&&l(o)},he=(r,j,s,l,o,k,a,u,c,f,G,I,$)=>{G=g(G),k=K(o,k),u&&=K(a,u),f&&=K(c,f),$=K(I,$);var m=ie(G);tj(m,function(){AA(\`Cannot construct \${G} due to unbound types\`,[l])}),M([r,j,s],l?[l]:[],F=>{F=F[0];var _,P;l?(_=F.registeredClass,P=_.instancePrototype):P=EA.prototype;var y=Aj(G,function(...lr){if(Object.getPrototypeOf(this)!==oA)throw new iA(\`Use 'new' to construct \${G}\`);if(H.constructor_body===void 0)throw new iA(\`\${G} has no accessible constructor\`);var bj=H.constructor_body[lr.length];if(bj===void 0)throw new iA(\`Tried to invoke ctor of \${G} with invalid number of parameters (\${lr.length}) - expected (\${Object.keys(H.constructor_body).toString()}) parameters instead!\`);return bj.apply(this,lr)}),oA=Object.create(P,{constructor:{value:y}});y.prototype=oA;var H=new le(G,y,oA,$,_,k,u,f);H.baseClass&&(H.baseClass.__derivedClasses??=[],H.baseClass.__derivedClasses.push(H));var fn=new LA(G,H,!0,!1,!1),Bj=new LA(G+"*",H,!1,!1,!1),Nj=new LA(G+" const*",H,!1,!0,!1);return rj[r]={pointerType:Bj,constPointerType:Nj},nj(m,y),[fn,Bj,Nj]})},Ar=(r,j)=>{for(var s=[],l=0;l<r;l++)s.push(E[j+l*4>>2]);return s},sj=r=>{for(;r.length;){var j=r.pop(),s=r.pop();s(j)}};function ij(r){for(var j=1;j<r.length;++j)if(r[j]!==null&&r[j].destructorFunction===void 0)return!0;return!1}function Ie(r,j,s,l){var o=ij(r),k=r.length-2,a=[],u=["fn"];j&&u.push("thisWired");for(var c=0;c<k;++c)a.push(\`arg\${c}\`),u.push(\`arg\${c}Wired\`);a=a.join(","),u=u.join(",");var f=\`return function (\${a}) {
|
|
3225
|
+
\\fX\\0\\x90!\\0\\0\\0\\0\`)}function xs(r){return r}async function bt(r){return r}async function Jt(r,j){try{var s=await bt(r),l=await WebAssembly.instantiate(s,j);return l}catch(o){N(\`failed to asynchronously prepare wasm: \${o}\`),VA(o)}}async function Kt(r,j,s){return Jt(j,s)}function Br(){qn();var r={a:xj};return r}async function Nr(){function r(a,u){return jA=a.exports,Rt(jA.M),dn(jA),eA=u,jA}function j(a){return r(a.instance,a.module)}var s=Br();if(e.instantiateWasm)return new Promise((a,u)=>{e.instantiateWasm(s,(c,f)=>{a(r(c,f))})});if(C){var l=new WebAssembly.Instance(eA,Br());return r(l,eA)}Dr??=Nt();var o=await Kt(gr,Dr,s),k=j(o);return k}class br{name="ExitStatus";constructor(j){this.message=\`Program terminated with exit(\${j})\`,this.status=j}}var pA,z,S,V,Jr,hA,nA,E,Kr,x,Or=r=>{r.terminate(),r.onmessage=j=>{}},Pr=r=>{var j=h.pthreads[r];h.returnWorkerToPool(j)},wr=r=>{for(;r.length>0;)r.shift()(e)},Mr=[],Ot=r=>Mr.push(r),Pt=r=>{var j=h.getNewWorker();if(!j)return 6;h.runningWorkers.push(j),h.pthreads[r.pthread_ptr]=j,j.pthread_ptr=r.pthread_ptr;var s={cmd:"run",start_routine:r.startRoutine,arg:r.arg,pthread_ptr:r.pthread_ptr};return j.postMessage(s,r.transferList),0},RA=0,WA=()=>zA||RA>0,wt=()=>_j(),Tr=r=>Lj(r),Mt=r=>Hj(r),sA=(r,j,s,...l)=>{var o=8*l.length*2,k=wt(),a=Mt(o),u=a>>3;for(var c of l)typeof c=="bigint"?(S[u++]=1n,S[u++]=c):(S[u++]=0n,hA[u++]=c);var f=$j(r,j,o,a,s);return Tr(k),f};function Ur(r){if(C)return sA(0,0,1,r);Q=r,WA()||(h.terminateAllThreads(),e.onExit?.(r),GA=!0),CA(r,new br(r))}function Sr(r){if(C)return sA(1,0,0,r);QA(r)}var Tt=(r,j)=>{if(Q=r,C)throw Sr(r),"unwind";Ur(r)},QA=Tt,h={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init(){C||h.initMainThread()},initMainThread(){},terminateAllThreads:()=>{for(var r of h.runningWorkers)Or(r);for(var r of h.unusedWorkers)Or(r);h.unusedWorkers=[],h.runningWorkers=[],h.pthreads={}},returnWorkerToPool:r=>{var j=r.pthread_ptr;delete h.pthreads[j],h.unusedWorkers.push(r),h.runningWorkers.splice(h.runningWorkers.indexOf(r),1),r.pthread_ptr=0,Fj(j)},threadInitTLS(){h.tlsInitFunctions.forEach(r=>r())},loadWasmModuleToWorker:r=>new Promise(j=>{r.onmessage=k=>{var a=k.data,u=a.cmd;if(a.targetThread&&a.targetThread!=_A()){var c=h.pthreads[a.targetThread];c?c.postMessage(a,a.transferList):N(\`Internal error! Worker sent a message "\${u}" to target pthread \${a.targetThread}, but that thread no longer exists!\`);return}u==="checkMailbox"?HA():u==="spawnThread"?Pt(a):u==="cleanupThread"?fj(()=>Pr(a.thread)):u==="loaded"?(r.loaded=!0,j(r)):a.target==="setimmediate"?r.postMessage(a):u==="callHandler"?e[a.handler](...a.args):u&&N(\`worker sent an unknown command \${u}\`)},r.onerror=k=>{var a="worker sent an error!";throw N(\`\${a} \${k.filename}:\${k.lineno}: \${k.message}\`),k};var s=[],l=["onExit","onAbort","print","printErr"];for(var o of l)e.propertyIsEnumerable(o)&&s.push(o);r.postMessage({cmd:"load",handlers:s,wasmMemory:X,wasmModule:eA})}),allocateUnusedWorker(){var r,j=n;e.mainScriptUrlOrBlob&&(j=e.mainScriptUrlOrBlob,typeof j!="string"&&(j=URL.createObjectURL(j))),r=new Worker(j,{name:"em-pthread"}),h.unusedWorkers.push(r)},getNewWorker(){return h.unusedWorkers.length==0&&(h.allocateUnusedWorker(),h.loadWasmModuleToWorker(h.unusedWorkers[0])),h.unusedWorkers.pop()}},Vr=[],Ut=r=>Vr.push(r);function St(r){var j=E[r+48>>2],s=E[r+52>>2],l=j-s;gj(j,l),Tr(j)}var Rr=[],Wr=r=>{var j=Rr[r];return j||(Rr[r]=j=yj.get(r)),j},Vt=(r,j)=>{RA=0,zA=0;var s=Wr(r)(j);function l(o){if(WA()){Q=o;return}ir(o)}l(s)},zA=!0,Rt=r=>h.tlsInitFunctions.push(r),X;class Wt{constructor(j){this.excPtr=j,this.ptr=j-24}set_type(j){E[this.ptr+4>>2]=j}get_type(){return E[this.ptr+4>>2]}set_destructor(j){E[this.ptr+8>>2]=j}get_destructor(){return E[this.ptr+8>>2]}set_caught(j){j=j?1:0,V[this.ptr+12]=j}get_caught(){return V[this.ptr+12]!=0}set_rethrown(j){j=j?1:0,V[this.ptr+13]=j}get_rethrown(){return V[this.ptr+13]!=0}init(j,s){this.set_adjusted_ptr(0),this.set_type(j),this.set_destructor(s)}set_adjusted_ptr(j){E[this.ptr+16>>2]=j}get_adjusted_ptr(){return E[this.ptr+16>>2]}}var Qr=0,Qt=0,zt=(r,j,s)=>{var l=new Wt(r);throw l.init(j,s),Qr=r,Qt++,Qr},Xt=()=>VA(""),g=r=>{for(var j="";;){var s=x[r++];if(!s)return j;j+=String.fromCharCode(s)}},Z={},Y={},IA={},iA=class extends Error{constructor(j){super(j),this.name="BindingError"}},p=r=>{throw new iA(r)};function Zt(r,j,s={}){var l=j.name;if(r||p(\`type "\${l}" must have a positive integer typeid pointer\`),Y.hasOwnProperty(r)){if(s.ignoreDuplicateRegistrations)return;p(\`Cannot register type '\${l}' twice\`)}if(Y[r]=j,delete IA[r],Z.hasOwnProperty(r)){var o=Z[r];delete Z[r],o.forEach(k=>k())}}function b(r,j,s={}){return Zt(r,j,s)}var zr=(r,j,s)=>{switch(j){case 1:return s?l=>V[l]:l=>x[l];case 2:return s?l=>pA[l>>1]:l=>nA[l>>1];case 4:return s?l=>z[l>>2]:l=>E[l>>2];case 8:return s?l=>S[l>>3]:l=>Kr[l>>3];default:throw new TypeError(\`invalid integer width (\${j}): \${r}\`)}},Yt=(r,j,s,l,o)=>{j=g(j);let k=l===0n,a=u=>u;if(k){let u=s*8;a=c=>BigInt.asUintN(u,c),o=a(o)}b(r,{name:j,fromWireType:a,toWireType:(u,c)=>(typeof c=="number"&&(c=BigInt(c)),c),readValueFromPointer:zr(j,s,!k),destructorFunction:null})},Ae=(r,j,s,l)=>{j=g(j),b(r,{name:j,fromWireType:function(o){return!!o},toWireType:function(o,k){return k?s:l},readValueFromPointer:function(o){return this.fromWireType(x[o])},destructorFunction:null})},re=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(s){return s.$$.ptrType.registeredClass.name}p(j(r)+" instance already deleted")},ZA=!1,Xr=r=>{},je=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&&je(r)},lA=r=>globalThis.FinalizationRegistry?(ZA=new FinalizationRegistry(j=>{Zr(j.$$)}),lA=j=>{var s=j.$$,l=!!s.smartPtr;if(l){var o={$$:s};ZA.register(j,o,j)}return j},Xr=j=>ZA.unregister(j),lA(r)):(lA=j=>j,r),mA=[],te=()=>{for(;mA.length;){var r=mA.pop();r.$$.deleteScheduled=!1,r.delete()}},Yr,ee=()=>{let r=EA.prototype;Object.assign(r,{isAliasOf(s){if(!(this instanceof EA)||!(s instanceof EA))return!1;var l=this.$$.ptrType.registeredClass,o=this.$$.ptr;s.$$=s.$$;for(var k=s.$$.ptrType.registeredClass,a=s.$$.ptr;l.baseClass;)o=l.upcast(o),l=l.baseClass;for(;k.baseClass;)a=k.upcast(a),k=k.baseClass;return l===k&&o===a},clone(){if(this.$$.ptr||XA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var s=lA(Object.create(Object.getPrototypeOf(this),{$$:{value:re(this.$$)}}));return s.$$.count.value+=1,s.$$.deleteScheduled=!1,s},delete(){this.$$.ptr||XA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&p("Object already scheduled for deletion"),Xr(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&&p("Object already scheduled for deletion"),mA.push(this),mA.length===1&&Yr&&Yr(te),this.$$.deleteScheduled=!0,this}});let j=Symbol.dispose;j&&(r[j]=r.delete)};function EA(){}var Aj=(r,j)=>Object.defineProperty(j,"name",{value:r}),rj={},jj=(r,j,s)=>{if(r[j].overloadTable===void 0){var l=r[j];r[j]=function(...o){return r[j].overloadTable.hasOwnProperty(o.length)||p(\`Function '\${s}' called with an invalid number of arguments (\${o.length}) - expects one of (\${r[j].overloadTable})!\`),r[j].overloadTable[o.length].apply(this,o)},r[j].overloadTable=[],r[j].overloadTable[l.argCount]=l}},tj=(r,j,s)=>{e.hasOwnProperty(r)?((s===void 0||e[r].overloadTable!==void 0&&e[r].overloadTable[s]!==void 0)&&p(\`Cannot register public name '\${r}' twice\`),jj(e,r,r),e[r].overloadTable.hasOwnProperty(s)&&p(\`Cannot register multiple overloads of a function with the same number of arguments (\${s})!\`),e[r].overloadTable[s]=j):(e[r]=j,e[r].argCount=s)},ne=48,se=57,ie=r=>{r=r.replace(/[^a-zA-Z0-9_]/g,"$");var j=r.charCodeAt(0);return j>=ne&&j<=se?\`_\${r}\`:r};function le(r,j,s,l,o,k,a,u){this.name=r,this.constructor=j,this.instancePrototype=s,this.rawDestructor=l,this.baseClass=o,this.getActualType=k,this.upcast=a,this.downcast=u,this.pureVirtualFunctions=[]}var $A=(r,j,s)=>{for(;j!==s;)j.upcast||p(\`Expected null or instance of \${s.name}, got an instance of \${j.name}\`),r=j.upcast(r),j=j.baseClass;return r},YA=r=>{if(r===null)return"null";var j=typeof r;return j==="object"||j==="array"||j==="function"?r.toString():""+r};function oe(r,j){if(j===null)return this.isReference&&p(\`null is not a valid \${this.name}\`),0;j.$$||p(\`Cannot pass "\${YA(j)}" as a \${this.name}\`),j.$$.ptr||p(\`Cannot pass deleted object as a pointer of type \${this.name}\`);var s=j.$$.ptrType.registeredClass,l=$A(j.$$.ptr,s,this.registeredClass);return l}function ae(r,j){var s;if(j===null)return this.isReference&&p(\`null is not a valid \${this.name}\`),this.isSmartPointer?(s=this.rawConstructor(),r!==null&&r.push(this.rawDestructor,s),s):0;(!j||!j.$$)&&p(\`Cannot pass "\${YA(j)}" as a \${this.name}\`),j.$$.ptr||p(\`Cannot pass deleted object as a pointer of type \${this.name}\`),!this.isConst&&j.$$.ptrType.isConst&&p(\`Cannot convert argument of type \${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type \${this.name}\`);var l=j.$$.ptrType.registeredClass;if(s=$A(j.$$.ptr,l,this.registeredClass),this.isSmartPointer)switch(j.$$.smartPtr===void 0&&p("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:j.$$.smartPtrType===this?s=j.$$.smartPtr:p(\`Cannot convert argument of type \${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type \${this.name}\`);break;case 1:s=j.$$.smartPtr;break;case 2:if(j.$$.smartPtrType===this)s=j.$$.smartPtr;else{var o=j.clone();s=this.rawShare(s,jr.toHandle(()=>o.delete())),r!==null&&r.push(this.rawDestructor,s)}break;default:p("Unsupported sharing policy")}return s}function ke(r,j){if(j===null)return this.isReference&&p(\`null is not a valid \${this.name}\`),0;j.$$||p(\`Cannot pass "\${YA(j)}" as a \${this.name}\`),j.$$.ptr||p(\`Cannot pass deleted object as a pointer of type \${this.name}\`),j.$$.ptrType.isConst&&p(\`Cannot convert argument of type \${j.$$.ptrType.name} to parameter type \${this.name}\`);var s=j.$$.ptrType.registeredClass,l=$A(j.$$.ptr,s,this.registeredClass);return l}function FA(r){return this.fromWireType(E[r>>2])}var ej=(r,j,s)=>{if(j===s)return r;if(s.baseClass===void 0)return null;var l=ej(r,j,s.baseClass);return l===null?null:s.downcast(l)},ue={},ce=(r,j)=>{for(j===void 0&&p("ptr should not be undefined");r.baseClass;)j=r.upcast(j),r=r.baseClass;return j},de=(r,j)=>(j=ce(r,j),ue[j]),qe=class extends Error{constructor(j){super(j),this.name="InternalError"}},vA=r=>{throw new qe(r)},gA=(r,j)=>{(!j.ptrType||!j.ptr)&&vA("makeClassHandle requires ptr and ptrType");var s=!!j.smartPtrType,l=!!j.smartPtr;return s!==l&&vA("Both smartPtrType and smartPtr must be specified"),j.count={value:1},lA(Object.create(r,{$$:{value:j,writable:!0}}))};function fe(r){var j=this.getPointee(r);if(!j)return this.destructor(r),null;var s=de(this.registeredClass,j);if(s!==void 0){if(s.$$.count.value===0)return s.$$.ptr=j,s.$$.smartPtr=r,s.clone();var l=s.clone();return this.destructor(r),l}function o(){return this.isSmartPointer?gA(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:j,smartPtrType:this,smartPtr:r}):gA(this.registeredClass.instancePrototype,{ptrType:this,ptr:r})}var k=this.registeredClass.getActualType(j),a=rj[k];if(!a)return o.call(this);var u;this.isConst?u=a.constPointerType:u=a.pointerType;var c=ej(j,this.registeredClass,u.registeredClass);return c===null?o.call(this):this.isSmartPointer?gA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c,smartPtrType:this,smartPtr:r}):gA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c})}var Ce=()=>{Object.assign(LA.prototype,{getPointee(r){return this.rawGetPointee&&(r=this.rawGetPointee(r)),r},destructor(r){this.rawDestructor?.(r)},readValueFromPointer:FA,fromWireType:fe})};function LA(r,j,s,l,o,k,a,u,c,f,G){this.name=r,this.registeredClass=j,this.isReference=s,this.isConst=l,this.isSmartPointer=o,this.pointeeType=k,this.sharingPolicy=a,this.rawGetPointee=u,this.rawConstructor=c,this.rawShare=f,this.rawDestructor=G,!o&&j.baseClass===void 0?l?(this.toWireType=oe,this.destructorFunction=null):(this.toWireType=ke,this.destructorFunction=null):this.toWireType=ae}var nj=(r,j,s)=>{e.hasOwnProperty(r)||vA("Replacing nonexistent public symbol"),e[r].overloadTable!==void 0&&s!==void 0?e[r].overloadTable[s]=j:(e[r]=j,e[r].argCount=s)},K=(r,j,s=!1)=>{r=g(r);function l(){var k=Wr(j);return k}var o=l();return typeof o!="function"&&p(\`unknown function pointer with signature \${r}: \${j}\`),o};class Ge extends Error{}var pe=r=>{var j=hj(r),s=g(j);return O(j),s},AA=(r,j)=>{var s=[],l={};function o(k){if(!l[k]&&!Y[k]){if(IA[k]){IA[k].forEach(o);return}s.push(k),l[k]=!0}}throw j.forEach(o),new Ge(\`\${r}: \`+s.map(pe).join([", "]))},M=(r,j,s)=>{r.forEach(u=>IA[u]=j);function l(u){var c=s(u);c.length!==r.length&&vA("Mismatched type converter count");for(var f=0;f<r.length;++f)b(r[f],c[f])}var o=new Array(j.length),k=[],a=0;for(let[u,c]of j.entries())Y.hasOwnProperty(c)?o[u]=Y[c]:(k.push(c),Z.hasOwnProperty(c)||(Z[c]=[]),Z[c].push(()=>{o[u]=Y[c],++a,a===k.length&&l(o)}));k.length===0&&l(o)},he=(r,j,s,l,o,k,a,u,c,f,G,I,$)=>{G=g(G),k=K(o,k),u&&=K(a,u),f&&=K(c,f),$=K(I,$);var m=ie(G);tj(m,function(){AA(\`Cannot construct \${G} due to unbound types\`,[l])}),M([r,j,s],l?[l]:[],F=>{F=F[0];var _,P;l?(_=F.registeredClass,P=_.instancePrototype):P=EA.prototype;var y=Aj(G,function(...lr){if(Object.getPrototypeOf(this)!==oA)throw new iA(\`Use 'new' to construct \${G}\`);if(H.constructor_body===void 0)throw new iA(\`\${G} has no accessible constructor\`);var bj=H.constructor_body[lr.length];if(bj===void 0)throw new iA(\`Tried to invoke ctor of \${G} with invalid number of parameters (\${lr.length}) - expected (\${Object.keys(H.constructor_body).toString()}) parameters instead!\`);return bj.apply(this,lr)}),oA=Object.create(P,{constructor:{value:y}});y.prototype=oA;var H=new le(G,y,oA,$,_,k,u,f);H.baseClass&&(H.baseClass.__derivedClasses??=[],H.baseClass.__derivedClasses.push(H));var fn=new LA(G,H,!0,!1,!1),Bj=new LA(G+"*",H,!1,!1,!1),Nj=new LA(G+" const*",H,!1,!0,!1);return rj[r]={pointerType:Bj,constPointerType:Nj},nj(m,y),[fn,Bj,Nj]})},Ar=(r,j)=>{for(var s=[],l=0;l<r;l++)s.push(E[j+l*4>>2]);return s},sj=r=>{for(;r.length;){var j=r.pop(),s=r.pop();s(j)}};function ij(r){for(var j=1;j<r.length;++j)if(r[j]!==null&&r[j].destructorFunction===void 0)return!0;return!1}function Ie(r,j,s,l){var o=ij(r),k=r.length-2,a=[],u=["fn"];j&&u.push("thisWired");for(var c=0;c<k;++c)a.push(\`arg\${c}\`),u.push(\`arg\${c}Wired\`);a=a.join(","),u=u.join(",");var f=\`return function (\${a}) {
|
|
3226
3226
|
\`;o&&(f+=\`var destructors = [];
|
|
3227
3227
|
\`);var G=o?"destructors":"null",I=["humanName","throwBindingError","invoker","fn","runDestructors","fromRetWire","toClassParamWire"];j&&(f+=\`var thisWired = toClassParamWire(\${G}, this);
|
|
3228
3228
|
\`);for(var c=0;c<k;++c){var $=\`toArg\${c}Wire\`;f+=\`var arg\${c}Wired = \${$}(\${G}, arg\${c});
|
|
@@ -3232,8 +3232,8 @@ K\\xE08\\xDF\\0}\\xBC\\x8A\\x1B\\f\\xE5\\xFF\\xCF\\xE8?\\x9F\\xFFFq\\0\\x88\\xB
|
|
|
3232
3232
|
\`,I.push(\`\${m}_dtor\`))}return s&&(f+=\`var ret = fromRetWire(rv);
|
|
3233
3233
|
return ret;
|
|
3234
3234
|
\`),f+=\`}
|
|
3235
|
-
\`,new Function(I,f)}function rr(r,j,s,l,o,k){var a=j.length;a<2&&p("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var u=j[1]!==null&&s!==null,c=ij(j),f=!j[0].isVoid,G=j[0],I=j[1],$=[r,p,l,o,sj,G.fromWireType.bind(G),I?.toWireType.bind(I)],m=2;m<a;++m){var F=j[m];$.push(F.toWireType.bind(F))}if(!c)for(var m=u?1:2;m<j.length;++m)j[m].destructorFunction!==null&&$.push(j[m].destructorFunction);var P=Ie(j,u,f,k)(...$);return Aj(r,P)}var me=(r,j,s,l,o,k)=>{var a=Ar(j,s);o=K(l,o),M([],[r],u=>{u=u[0];var c=\`constructor \${u.name}\`;if(u.registeredClass.constructor_body===void 0&&(u.registeredClass.constructor_body=[]),u.registeredClass.constructor_body[j-1]!==void 0)throw new iA(\`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\`,a)},M([],a,f=>(f.splice(1,0,null),u.registeredClass.constructor_body[j-1]=rr(c,f,null,o,k),[])),[]})},lj=r=>{r=r.trim();let j=r.indexOf("(");return j===-1?r:r.slice(0,j)},Ee=(r,j,s,l,o,k,a,u,c,f)=>{var G=Ar(s,l);j=g(j),j=lj(j),k=K(o,k,c),M([],[r],I=>{I=I[0];var $=\`\${I.name}.\${j}\`;j.startsWith("@@")&&(j=Symbol[j.substring(2)]),u&&I.registeredClass.pureVirtualFunctions.push(j);function m(){AA(\`Cannot call \${$} due to unbound types\`,G)}var F=I.registeredClass.instancePrototype,_=F[j];return _===void 0||_.overloadTable===void 0&&_.className!==I.name&&_.argCount===s-2?(m.argCount=s-2,m.className=I.name,F[j]=m):(jj(F,j,$),F[j].overloadTable[s-2]=m),M([],G,P=>{var y=rr($,P,I,k,a,c);return F[j].overloadTable===void 0?(y.argCount=s-2,F[j]=y):F[j].overloadTable[s-2]=y,[]}),[]})},oj=(r,j,s)=>(r instanceof Object||p(\`\${s} with invalid "this": \${r}\`),r instanceof j.registeredClass.constructor||p(\`\${s} incompatible with "this" of type \${r.constructor.name}\`),r.$$.ptr||p(\`cannot call emscripten binding method \${s} on deleted object\`),$A(r.$$.ptr,r.$$.ptrType.registeredClass,j.registeredClass)),$e=(r,j,s,l,o,k,a,u,c,f)=>{j=g(j),o=K(l,o),M([],[r],G=>{G=G[0];var I=\`\${G.name}.\${j}\`,$={get(){AA(\`Cannot access \${I} due to unbound types\`,[s,a])},enumerable:!0,configurable:!0};return c?$.set=()=>AA(\`Cannot access \${I} due to unbound types\`,[s,a]):$.set=m=>p(I+" is a read-only property"),Object.defineProperty(G.registeredClass.instancePrototype,j,$),M([],c?[s,a]:[s],m=>{var F=m[0],_={get(){var y=oj(this,G,I+" getter");return F.fromWireType(o(k,y))},enumerable:!0};if(c){c=K(u,c);var P=m[1];_.set=function(y){var oA=oj(this,G,I+" setter"),H=[];c(f,oA,P.toWireType(H,y)),sj(H)}}return Object.defineProperty(G.registeredClass.instancePrototype,j,_),[]}),[]})},aj=[],rA=[0,1,,1,null,1,!0,1,!1,1],Fe=r=>{r>9&&--rA[r+1]===0&&(rA[r]=void 0,aj.push(r))},jr={toValue:r=>(r||p(\`Cannot use deleted val. handle = \${r}\`),rA[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=aj.pop()||rA.length;return rA[j]=r,rA[j+1]=1,j}}}},ve={name:"emscripten::val",fromWireType:r=>{var j=jr.toValue(r);return Fe(r),j},toWireType:(r,j)=>jr.toHandle(j),readValueFromPointer:FA,destructorFunction:null},ge=r=>b(r,ve),Le=(r,j)=>{switch(j){case 4:return function(s){return this.fromWireType(Jr[s>>2])};case 8:return function(s){return this.fromWireType(hA[s>>3])};default:throw new TypeError(\`invalid float width (\${j}): \${r}\`)}},He=(r,j,s)=>{j=g(j),b(r,{name:j,fromWireType:l=>l,toWireType:(l,o)=>o,readValueFromPointer:Le(j,s),destructorFunction:null})},_e=(r,j,s,l,o,k,a,u)=>{var c=Ar(j,s);r=g(r),r=lj(r),o=K(l,o,a),tj(r,function(){AA(\`Cannot call \${r} due to unbound types\`,c)},j-1),M([],c,f=>{var G=[f[0],null].concat(f.slice(1));return nj(r,rr(r,G,null,o,k,a),j-1),[]})},ye=(r,j,s,l,o)=>{j=g(j);let k=l===0,a=c=>c;if(k){var u=32-8*s;a=c=>c<<u>>>u,o=a(o)}b(r,{name:j,fromWireType:a,toWireType:(c,f)=>f,readValueFromPointer:zr(j,s,l!==0),destructorFunction:null})},xe=(r,j,s)=>{var l=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=l[j];function k(a){var u=E[a>>2],c=E[a+4>>2];return new o(V.buffer,c,u)}s=g(s),b(r,{name:s,fromWireType:k,readValueFromPointer:k},{ignoreDuplicateRegistrations:!0})},De=(r,j,s,l)=>{if(!(l>0))return 0;for(var o=s,k=s+l-1,a=0;a<r.length;++a){var u=r.codePointAt(a);if(u<=127){if(s>=k)break;j[s++]=u}else if(u<=2047){if(s+1>=k)break;j[s++]=192|u>>6,j[s++]=128|u&63}else if(u<=65535){if(s+2>=k)break;j[s++]=224|u>>12,j[s++]=128|u>>6&63,j[s++]=128|u&63}else{if(s+3>=k)break;j[s++]=240|u>>18,j[s++]=128|u>>12&63,j[s++]=128|u>>6&63,j[s++]=128|u&63,a++}}return j[s]=0,s-o},Be=(r,j,s)=>De(r,x,j,s),Ne=r=>{for(var j=0,s=0;s<r.length;++s){var l=r.charCodeAt(s);l<=127?j++:l<=2047?j+=2:l>=55296&&l<=57343?(j+=4,++s):j+=3}return j},kj=globalThis.TextDecoder&&new TextDecoder,uj=(r,j,s,l)=>{var o=j+s;if(l)return o;for(;r[j]&&!(j>=o);)++j;return j},cj=(r,j=0,s,l)=>{var o=uj(r,j,s,l);if(o-j>16&&r.buffer&&kj)return kj.decode(r.buffer instanceof ArrayBuffer?r.subarray(j,o):r.slice(j,o));for(var k="";j<o;){var a=r[j++];if(!(a&128)){k+=String.fromCharCode(a);continue}var u=r[j++]&63;if((a&224)==192){k+=String.fromCharCode((a&31)<<6|u);continue}var c=r[j++]&63;if((a&240)==224?a=(a&15)<<12|u<<6|c:a=(a&7)<<18|u<<12|c<<6|r[j++]&63,a<65536)k+=String.fromCharCode(a);else{var f=a-65536;k+=String.fromCharCode(55296|f>>10,56320|f&1023)}}return k},be=(r,j,s)=>r?cj(x,r,j,s):"",Je=(r,j)=>{j=g(j);var s=!0;b(r,{name:j,fromWireType(l){var o=E[l>>2],k=l+4,a;if(s)a=be(k,o,!0);else{a="";for(var u=0;u<o;++u)a+=String.fromCharCode(x[k+u])}return O(l),a},toWireType(l,o){o instanceof ArrayBuffer&&(o=new Uint8Array(o));var k,a=typeof o=="string";a||ArrayBuffer.isView(o)&&o.BYTES_PER_ELEMENT==1||p("Cannot pass non-string to std::string"),s&&a?k=Ne(o):k=o.length;var u=nr(4+k+1),c=u+4;if(E[u>>2]=k,a)if(s)Be(o,c,k+1);else for(var f=0;f<k;++f){var G=o.charCodeAt(f);G>255&&(O(u),p("String has UTF-16 code units that do not fit in 8 bits")),x[c+f]=G}else x.set(o,c);return l!==null&&l.push(O,u),u},readValueFromPointer:FA,destructorFunction(l){O(l)}})},dj=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Ke=(r,j,s)=>{var l=r>>1,o=uj(nA,l,j/2,s);if(o-l>16&&dj)return dj.decode(nA.slice(l,o));for(var k="",a=l;a<o;++a){var u=nA[a];k+=String.fromCharCode(u)}return k},Oe=(r,j,s)=>{if(s??=2147483647,s<2)return 0;s-=2;for(var l=j,o=s<r.length*2?s/2:r.length,k=0;k<o;++k){var a=r.charCodeAt(k);pA[j>>1]=a,j+=2}return pA[j>>1]=0,j-l},Pe=r=>r.length*2,we=(r,j,s)=>{for(var l="",o=r>>2,k=0;!(k>=j/4);k++){var a=E[o+k];if(!a&&!s)break;l+=String.fromCodePoint(a)}return l},Me=(r,j,s)=>{if(s??=2147483647,s<4)return 0;for(var l=j,o=l+s-4,k=0;k<r.length;++k){var a=r.codePointAt(k);if(a>65535&&k++,z[j>>2]=a,j+=4,j+4>o)break}return z[j>>2]=0,j-l},Te=r=>{for(var j=0,s=0;s<r.length;++s){var l=r.codePointAt(s);l>65535&&s++,j+=4}return j},Ue=(r,j,s)=>{s=g(s);var l,o,k;j===2?(l=Ke,o=Oe,k=Pe):(l=we,o=Me,k=Te),b(r,{name:s,fromWireType:a=>{var u=E[a>>2],c=l(a+4,u*j,!0);return O(a),c},toWireType:(a,u)=>{typeof u!="string"&&p(\`Cannot pass non-string to C++ string type \${s}\`);var c=k(u),f=nr(4+c+j);return E[f>>2]=c/j,o(u,f+4,c+j),a!==null&&a.push(O,f),f},readValueFromPointer:FA,destructorFunction(a){O(a)}})},Se=(r,j)=>{j=g(j),b(r,{isVoid:!0,name:j,fromWireType:()=>{},toWireType:(s,l)=>{}})},Ve=r=>{sr(r,!d,1,!i,65536,!1),h.threadInitTLS()},qj=r=>{if(r instanceof br||r=="unwind")return Q;CA(1,r)},Re=()=>{if(!WA())try{if(C){_A()&&ir(Q);return}QA(Q)}catch(r){qj(r)}},fj=r=>{if(!GA)try{return r()}catch(j){qj(j)}finally{Re()}},We=!Atomics.waitAsync||globalThis.navigator?.userAgent&&Number((navigator.userAgent.match(/Chrom(e|ium)\\/([0-9]+)\\./)||[])[2])<91,tr=r=>{if(!We){var j=Atomics.waitAsync(z,r>>2,r);j.value.then(HA);var s=r+120;Atomics.store(z,s>>2,1)}},HA=()=>fj(()=>{var r=_A();r&&(tr(r),vj())}),Qe=(r,j)=>{if(r==j)setTimeout(HA);else if(C)postMessage({targetThread:r,cmd:"checkMailbox"});else{var s=h.pthreads[r];if(!s)return;s.postMessage({cmd:"checkMailbox"})}},er=[],ze=(r,j,s,l,o,k,a)=>{er.length=0;for(var u=o>>3,c=o+l>>3;u<c;){var f;S[u++]?f=S[u++]:f=hA[u++],er.push(f)}var G=kn[r];h.currentProxiedOperationCallerThread=s;var I=G(...er);if(h.currentProxiedOperationCallerThread=0,k){I.then($=>Ej(k,a,$));return}return I},Xe=r=>{C?postMessage({cmd:"cleanupThread",thread:r}):Pr(r)},Ze=r=>{},Ye=()=>performance.timeOrigin+performance.now(),An=9007199254740992,rn=-9007199254740992,jn=r=>r<rn||r>An?NaN:Number(r),tn=()=>{},en=()=>{RA+=1},nn=()=>{throw en(),"unwind"},sn=r=>{VA("OOM")},ln=r=>{var j=x.length;r>>>=0,sn(r)};function Cj(r){return C?sA(2,0,1,r):52}function Gj(r,j,s,l){return C?sA(3,0,1,r,j,s,l):(j=jn(j),70)}var on=[null,[],[]],an=(r,j)=>{var s=on[r];j===0||j===10?((r===1?TA:N)(cj(s)),s.length=0):s.push(j)};function pj(r,j,s,l){if(C)return sA(4,0,1,r,j,s,l);for(var o=0,k=0;k<s;k++){var a=E[j>>2],u=E[j+4>>2];j+=8;for(var c=0;c<u;c++)an(r,x[a+c]);o+=u}return E[l>>2]=o,0}if(h.init(),ee(),Ce(),xt(),e.noExitRuntime&&(zA=e.noExitRuntime),e.print&&(TA=e.print),e.printErr&&(N=e.printErr),e.wasmBinary&&(gr=e.wasmBinary),e.arguments&&(v=e.arguments),e.thisProgram&&(B=e.thisProgram),e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.shift()();var kn=[Ur,Sr,Cj,Gj,pj],hj,Ij,_A,nr,O,un,sr,mj,Ej,$j,Fj,ir,vj,gj,Lj,Hj,_j,cn,yj;function dn(r){hj=r.G,Ij=r.H,_A=r.J,nr=e._malloc=r.K,O=e._free=r.L,un=r.M,sr=r.N,mj=r.O,Ej=r.P,$j=r.Q,Fj=r.R,ir=r.S,vj=r.T,gj=r.U,Lj=r.V,Hj=r.W,_j=r.X,cn=yj=r.I}var xj;function qn(){xj={i:zt,C:Xt,h:Yt,o:Ae,n:he,m:me,e:Ee,b:$e,D:ge,l:He,q:_e,d:ye,c:xe,E:Je,g:Ue,p:Se,z:Ve,u:Qe,k:ze,s:Xe,y:tr,B:Ze,x:tn,A:nn,f:Ye,t:ln,r:QA,w:Cj,v:Gj,j:pj,a:X}}function Dj(){if(C){UA?.(e),xr();return}Dt();function r(){e.calledRun=!0,!GA&&(xr(),UA?.(e),e.onRuntimeInitialized?.(),Bt())}e.setStatus?(e.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>e.setStatus(""),1),r()},1)):r()}var jA;return C||(jA=await Nr(),Dj()),_r?t=e:t=new Promise((r,j)=>{UA=r,Lr=j}),t}})();typeof Et=="object"&&typeof MA=="object"?(MA.exports=wA,MA.exports.default=wA):typeof define=="function"&&define.amd&&define([],()=>wA);var Hs=globalThis.name=="em-pthread";Hs&&wA()});var J={};En(J,{AdditionalCaptureBlocks:()=>gn,AdditionalPlaybackBlocks:()=>vn,ClockJumpCheckInterval:()=>Bn,ClockJumpThreshold:()=>Nn,ConnectInterval:()=>Tn,ConnectTimeout:()=>Pn,DefaultRefreshRate:()=>Hn,DefaultVideoCodec:()=>Un,HealthCheckTimeout:()=>Dn,MainConnectionPingInterval:()=>bn,MaxNumberOfDecoders:()=>yn,MinDBFs:()=>Jj,MinTokenLifetime:()=>wn,MinTokenRefreshInterval:()=>Mn,PlaybackPreload:()=>Ln,RenderQuantumSize:()=>xn,VadPreload:()=>_n,WebRtcIceTimeout:()=>Kn,WebRtcStatsSnapshotInterval:()=>Jn,WebRtcTimeout:()=>On});var vn=3,gn=3,Ln=3,Hn=250,_n=3,yn=512,xn=128,Jj=-758.596,Dn=1e4,Bn=1e3,Nn=1e4,bn=3e3,Jn=1e3,Kn=3e3,On=1e4,Pn=5e3,wn=6e4,Mn=5e3,Tn=[0,100,200,200,500],Un="H264";function aA(n,A,t){return n.postMessage(A,t)}function ar(n){return n.sampleRate*.02*(n.stereo?2:1)}function kr(n,A){let t=ar(n),e=t*A,i=e+t;return n.samples.subarray(e,i)}function ur(n,A,t){n.headers[A]=t.id}function Kj(n){return[n.values[0],n.values[1]]}function Oj(n,A){n.values[0]=A[0],n.values[1]=A[1]}function Pj(n,A){return n.values[2+A*5]}function wj(n,A,t){n.values[2+A*5]=t}function Mj(n,A){let t=2+A*5+1;return[n.values[t+0],n.values[t+1]]}function Tj(n,A,t){let e=2+A*5+1;n.values[e+0]=t[0],n.values[e+1]=t[1]}function Uj(n,A){return n.values[2+A*5+3]}function Sj(n,A,t){n.values[2+A*5+3]=t}function Vj(n,A){return n.values[2+A*5+4]}function Rj(n,A,t){n.values[2+A*5+4]=t}function Wj(n){return n.values[0]!==0}function Qj(n){return n.values[1]}function zj(n){return n.values[2]}function Xj(n){return n.values[3]}function Zj(n,A){return n.values[3]=A}function Yj(n){return n?Array.from(n).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var Sn;(n=>{let A;(t=>(t[t.InvalidPassword=-1]="InvalidPassword",t[t.Unknown=0]="Unknown",t[t.Unencrypted=1]="Unencrypted",t[t.Encrypted=2]="Encrypted"))(A=n.PeerCipherStatus||={})})(Sn||={});function et(n){return{type:"Success",value:n}}function D(n){return{type:"Failure",reason:n}}var{Deno:At}=globalThis,Vn=typeof At?.noColor=="boolean"?At.noColor:!1,Rn=!Vn;function dr(n,A){return{open:\`\\x1B[\${n.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function qr(n,A){return Rn?\`\${A.open}\${n.replace(A.regexp,A.open)}\${A.close}\`:n}function cr(n){return qr(n,dr([0],0))}function rt(n){return qr(n,dr([1],22))}function Wn(n){return qr(n,dr([2],22))}var Ts=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),Qn=new Date,yA=(n=>(n[n.CRITICAL=0]="CRITICAL",n[n.ERROR=1]="ERROR",n[n.WARN=2]="WARN",n[n.INFO=3]="INFO",n[n.DEBUG=4]="DEBUG",n))(yA||{}),nt={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},zn={4:Wn,3:cr,2:cr,1:rt,0:rt};function Xn({message:n}){return String(n)}function jt(n){return JSON.stringify({timestamp:n.date.toISOString(),level:yA[n.level],message:n.message,extra:n.extra})}function tt(n){function A(q,C){return[Math.floor(q/C),q%C]}function t(){let q,C=n.date.valueOf()-Qn.valueOf();[C,q]=A(C,1e3);let[v,B]=A(C,60);return\`\${v.toString().padStart(4,"0")}:\${B.toString().padStart(2,"0")}.\${q.toString().padStart(3,"0")}\`}function e(){return n.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(n.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(n.extra)}let i=nt[n.level],d=n.logger.name!==void 0?\`@\${n.logger.name}\`:"";return\`\${cr(t())}\${d} \${i} \${zn[n.level](String(n.message))}\${e()}\`}function Zn(n){let A=\`[\${n.date.toISOString()}]\`,t=\`[\${yA[n.level]}]\`,e=n.logger.name!==void 0?\`[\${n.logger.name}] \`:"",i=nt[n.level];return\`\${A} \${i} \${t.padEnd(7," ")} \${e}\${n.message}\`}function Yn(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var st=class{static sparse=Xn;static json=jt;static pretty=tt;static structured=Zn;static default=Yn()?tt:jt;constructor(){}};var As=class{formatter;consoleObject;filter;constructor(n=st.default,A=4,t=console){this.filter=A,this.formatter=n,this.consoleObject=t}handle(n){let A=this.formatter(n);switch(n.level){case 0:case 1:this.consoleObject.error(A);break;case 2:this.consoleObject.warn(A);break;case 3:this.consoleObject.info(A);break;case 4:this.consoleObject.debug(A);break}}};var R=class{#A;sinks;filter;parent;get name(){return this.#A}constructor(n,A=void 0,t=[],e=void 0){this.#A=A,this.sinks=t,this.filter=n,this.parent=e}log(n,A,t=void 0){let e={date:new Date,level:n,logger:this,message:A,extra:t};this.filter<n||this.insert(e)}insert(n){if(!(this.filter<n.level)){for(let A of this.sinks)A.filter>=n.level&&A.handle(n);this.parent!==void 0&&this.parent.insert(n)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},kA=globalThis[Symbol.for("odin-global-logger")]??=new R(3,void 0,[new As]),rs=R.prototype.log.bind(kA,1),js=R.prototype.log.bind(kA,2),it=R.prototype.log.bind(kA,3),ts=R.prototype.log.bind(kA,4),Us=R.prototype.log.bind(kA);var lt;function ot(n,...A){let t=es(A);lt?lt?.info(n,t):it(n,t)}function es(...n){if(n.length===1&&typeof n[0]=="object"&&n[0]!==null)return{...n[0]};if(n.length>0)return{args:n}}function xA(n){return n.connectionId*4294967296+n.mediaId}function at(n){return{mediaId:n%4294967296,connectionId:Math.floor(n/4294967296)}}function T(n,A,t){let e;switch(A){case"f32":e=n.HEAPF32;break;case"u32":e=n.HEAPU32;break;case"i32":e=n.HEAP32;break;case"u8":e=n.HEAPU8;break;default:throw new Error(\`allocating \${A} is not supported\`)}let i=n._malloc(t*e.BYTES_PER_ELEMENT);if(i===0||i%e.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${t} \${A} array\`);let d=i/e.BYTES_PER_ELEMENT;return e.subarray(d,d+t)}function tA(n,A){n._free(A.byteOffset)}function fr(n,A,t,e){return{headers:T(n,"i32",t),samples:T(n,"f32",t*ar({sampleRate:A,stereo:e})),length:t,sampleRate:A,stereo:e}}function Cr(n,A){tA(n,A.headers),tA(n,A.samples)}function kt(n,A){return{values:T(n,"f32",2+A*5),length:A}}function ut(n,A){tA(n,A.values)}function ct(n){return{values:T(n,"f32",4)}}function dt(n,A){tA(n,A.values)}function qt(n){let A=n.length,t=0,e=0;for(;e<A;){let i=n.charCodeAt(e++);if((i&4294967168)===0){t++;continue}else if((i&4294965248)===0)t+=2;else{if(i>=55296&&i<=56319&&e<A){let d=n.charCodeAt(e);(d&64512)===56320&&(++e,i=((i&1023)<<10)+(d&1023)+65536)}(i&4294901760)===0?t+=3:t+=4}}return t}function ns(n,A,t){let e=n.length,i=t,d=0;for(;d<e;){let q=n.charCodeAt(d++);if((q&4294967168)===0){A[i++]=q;continue}else if((q&4294965248)===0)A[i++]=q>>6&31|192;else{if(q>=55296&&q<=56319&&d<e){let C=n.charCodeAt(d);(C&64512)===56320&&(++d,q=((q&1023)<<10)+(C&1023)+65536)}(q&4294901760)===0?(A[i++]=q>>12&15|224,A[i++]=q>>6&63|128):(A[i++]=q>>18&7|240,A[i++]=q>>12&63|128,A[i++]=q>>6&63|128)}A[i++]=q&63|128}}var ss=new TextEncoder,is=50;function ls(n,A,t){ss.encodeInto(n,A.subarray(t))}function ft(n,A,t){n.length>is?ls(n,A,t):ns(n,A,t)}var os=4096;function Gr(n,A,t){let e=A,i=e+t,d=[],q="";for(;e<i;){let C=n[e++];if((C&128)===0)d.push(C);else if((C&224)===192){let v=n[e++]&63;d.push((C&31)<<6|v)}else if((C&240)===224){let v=n[e++]&63,B=n[e++]&63;d.push((C&31)<<12|v<<6|B)}else if((C&248)===240){let v=n[e++]&63,B=n[e++]&63,CA=n[e++]&63,w=(C&7)<<18|v<<12|B<<6|CA;w>65535&&(w-=65536,d.push(w>>>10&1023|55296),w=56320|w&1023),d.push(w)}else d.push(C);d.length>=os&&(q+=String.fromCharCode(...d),d.length=0)}return d.length>0&&(q+=String.fromCharCode(...d)),q}var as=new TextDecoder,ks=200;function us(n,A,t){let e=n.subarray(A,A+t);return as.decode(e)}function Ct(n,A,t){return t>ks?us(n,A,t):Gr(n,A,t)}var W=class{constructor(A,t){this.type=A,this.data=t}};var L=class n extends Error{constructor(A){super(A);let t=Object.create(n.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:n.name})}};function Gt(n,A,t){let e=t/4294967296,i=t;n.setUint32(A,e),n.setUint32(A+4,i)}function DA(n,A,t){let e=Math.floor(t/4294967296),i=t;n.setUint32(A,e),n.setUint32(A+4,i)}function BA(n,A){let t=n.getInt32(A),e=n.getUint32(A+4);return t*4294967296+e}function pt(n,A){let t=n.getUint32(A),e=n.getUint32(A+4);return t*4294967296+e}var cs=-1,ds=4294967296-1,qs=17179869184-1;function fs({sec:n,nsec:A}){if(n>=0&&A>=0&&n<=qs)if(A===0&&n<=ds){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{let t=n/4294967296,e=n&4294967295,i=new Uint8Array(8),d=new DataView(i.buffer);return d.setUint32(0,A<<2|t&3),d.setUint32(4,e),i}else{let t=new Uint8Array(12),e=new DataView(t.buffer);return e.setUint32(0,A),DA(e,4,n),t}}function Cs(n){let A=n.getTime(),t=Math.floor(A/1e3),e=(A-t*1e3)*1e6,i=Math.floor(e/1e9);return{sec:t+i,nsec:e-i*1e9}}function Gs(n){if(n instanceof Date){let A=Cs(n);return fs(A)}else return null}function ps(n){let A=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:A.getUint32(0),nsec:0};case 8:{let t=A.getUint32(0),e=A.getUint32(4),i=(t&3)*4294967296+e,d=t>>>2;return{sec:i,nsec:d}}case 12:{let t=BA(A,4),e=A.getUint32(0);return{sec:t,nsec:e}}default:throw new L(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${n.length}\`)}}function hs(n){let A=ps(n);return new Date(A.sec*1e3+A.nsec/1e6)}var ht={type:cs,encode:Gs,decode:hs};var U=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(ht)}register({type:A,encode:t,decode:e}){if(A>=0)this.encoders[A]=t,this.decoders[A]=e;else{let i=-1-A;this.builtInEncoders[i]=t,this.builtInDecoders[i]=e}}tryToEncode(A,t){for(let e=0;e<this.builtInEncoders.length;e++){let i=this.builtInEncoders[e];if(i!=null){let d=i(A,t);if(d!=null){let q=-1-e;return new W(q,d)}}}for(let e=0;e<this.encoders.length;e++){let i=this.encoders[e];if(i!=null){let d=i(A,t);if(d!=null){let q=e;return new W(q,d)}}}return A instanceof W?A:null}decode(A,t,e){let i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(A,t,e):new W(t,A)}};U.defaultCodec=new U;function Is(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function uA(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):Is(n)?new Uint8Array(n):Uint8Array.from(n)}var ms=100,Es=2048,NA=class n{constructor(A){this.entered=!1,this.extensionCodec=A?.extensionCodec??U.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??ms,this.initialBufferSize=A?.initialBufferSize??Es,this.sortKeys=A?.sortKeys??!1,this.forceFloat32=A?.forceFloat32??!1,this.ignoreUndefined=A?.ignoreUndefined??!1,this.forceIntegerToFloat=A?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(A){if(this.entered)return this.clone().encodeSharedRef(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(A){if(this.entered)return this.clone().encode(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(A,t){if(t>this.maxDepth)throw new Error(\`Too deep objects in depth \${t}\`);A==null?this.encodeNil():typeof A=="boolean"?this.encodeBoolean(A):typeof A=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(A):this.encodeNumber(A):typeof A=="string"?this.encodeString(A):this.useBigInt64&&typeof A=="bigint"?this.encodeBigInt64(A):this.encodeObject(A,t)}ensureBufferSizeToWrite(A){let t=this.pos+A;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(A){let t=new ArrayBuffer(A),e=new Uint8Array(t),i=new DataView(t);e.set(this.bytes),this.view=i,this.bytes=e}encodeNil(){this.writeU8(192)}encodeBoolean(A){A===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(A){!this.forceIntegerToFloat&&Number.isSafeInteger(A)?A>=0?A<128?this.writeU8(A):A<256?(this.writeU8(204),this.writeU8(A)):A<65536?(this.writeU8(205),this.writeU16(A)):A<4294967296?(this.writeU8(206),this.writeU32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(207),this.writeU64(A)):A>=-32?this.writeU8(224|A+32):A>=-128?(this.writeU8(208),this.writeI8(A)):A>=-32768?(this.writeU8(209),this.writeI16(A)):A>=-2147483648?(this.writeU8(210),this.writeI32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(211),this.writeI64(A)):this.encodeNumberAsFloat(A)}encodeNumberAsFloat(A){this.forceFloat32?(this.writeU8(202),this.writeF32(A)):(this.writeU8(203),this.writeF64(A))}encodeBigInt64(A){A>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(A)):(this.writeU8(211),this.writeBigInt64(A))}writeStringHeader(A){if(A<32)this.writeU8(160+A);else if(A<256)this.writeU8(217),this.writeU8(A);else if(A<65536)this.writeU8(218),this.writeU16(A);else if(A<4294967296)this.writeU8(219),this.writeU32(A);else throw new Error(\`Too long string: \${A} bytes in UTF-8\`)}encodeString(A){let e=qt(A);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),ft(A,this.bytes,this.pos),this.pos+=e}encodeObject(A,t){let e=this.extensionCodec.tryToEncode(A,this.context);if(e!=null)this.encodeExtension(e);else if(Array.isArray(A))this.encodeArray(A,t);else if(ArrayBuffer.isView(A))this.encodeBinary(A);else if(typeof A=="object")this.encodeMap(A,t);else throw new Error(\`Unrecognized object: \${Object.prototype.toString.apply(A)}\`)}encodeBinary(A){let t=A.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(\`Too large binary: \${t}\`);let e=uA(A);this.writeU8a(e)}encodeArray(A,t){let e=A.length;if(e<16)this.writeU8(144+e);else if(e<65536)this.writeU8(220),this.writeU16(e);else if(e<4294967296)this.writeU8(221),this.writeU32(e);else throw new Error(\`Too large array: \${e}\`);for(let i of A)this.doEncode(i,t+1)}countWithoutUndefined(A,t){let e=0;for(let i of t)A[i]!==void 0&&e++;return e}encodeMap(A,t){let e=Object.keys(A);this.sortKeys&&e.sort();let i=this.ignoreUndefined?this.countWithoutUndefined(A,e):e.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(\`Too large map object: \${i}\`);for(let d of e){let q=A[d];this.ignoreUndefined&&q===void 0||(this.encodeString(d),this.doEncode(q,t+1))}}encodeExtension(A){if(typeof A.data=="function"){let e=A.data(this.pos+6),i=e.length;if(i>=4294967296)throw new Error(\`Too large extension object: \${i}\`);this.writeU8(201),this.writeU32(i),this.writeI8(A.type),this.writeU8a(e);return}let t=A.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(\`Too large extension object: \${t}\`);this.writeI8(A.type),this.writeU8a(A.data)}writeU8(A){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,A),this.pos++}writeU8a(A){let t=A.length;this.ensureBufferSizeToWrite(t),this.bytes.set(A,this.pos),this.pos+=t}writeI8(A){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,A),this.pos++}writeU16(A){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,A),this.pos+=2}writeI16(A){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,A),this.pos+=2}writeU32(A){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,A),this.pos+=4}writeI32(A){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,A),this.pos+=4}writeF32(A){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,A),this.pos+=4}writeF64(A){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,A),this.pos+=8}writeU64(A){this.ensureBufferSizeToWrite(8),Gt(this.view,this.pos,A),this.pos+=8}writeI64(A){this.ensureBufferSizeToWrite(8),DA(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(n,A){return new NA(A).encodeSharedRef(n)}function bA(n){return\`\${n<0?"-":""}0x\${Math.abs(n).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 e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,t,e){let i=this.caches[e-1];A:for(let d of i){let q=d.bytes;for(let C=0;C<e;C++)if(q[C]!==A[t+C])continue A;return d.str}return null}store(A,t){let e=this.caches[A.length-1],i={bytes:A,str:t};e.length>=this.maxLengthPerKey?e[Math.random()*e.length|0]=i:e.push(i)}decode(A,t,e){let i=this.find(A,t,e);if(i!=null)return this.hit++,i;this.miss++;let d=Gr(A,t,e),q=Uint8Array.prototype.slice.call(A,t,t+e);return this.store(q,d),d}};var hr="array",qA="map_key",mt="map_value",vs=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new L("The type of key must be string or number but "+typeof n)},Ir=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let t=this.getUninitializedStateFromPool();t.type=hr,t.position=0,t.size=A,t.array=new Array(A)}pushMapState(A){let t=this.getUninitializedStateFromPool();t.type=qA,t.readCount=0,t.size=A,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let A={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(A)}return this.stack[this.stackHeadPosition]}release(A){if(this.stack[this.stackHeadPosition]!==A)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(A.type===hr){let e=A;e.size=0,e.array=void 0,e.position=0,e.type=void 0}if(A.type===qA||A.type===mt){let e=A;e.size=0,e.map=void 0,e.readCount=0,e.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},dA=-1,mr=new DataView(new ArrayBuffer(0)),gs=new Uint8Array(mr.buffer);try{mr.getInt8(0)}catch(n){if(!(n instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var It=new RangeError("Insufficient data"),Ls=new JA,KA=class n{constructor(A){this.totalPos=0,this.pos=0,this.view=mr,this.bytes=gs,this.headByte=dA,this.stack=new Ir,this.entered=!1,this.extensionCodec=A?.extensionCodec??U.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.rawStrings=A?.rawStrings??!1,this.maxStrLength=A?.maxStrLength??4294967295,this.maxBinLength=A?.maxBinLength??4294967295,this.maxArrayLength=A?.maxArrayLength??4294967295,this.maxMapLength=A?.maxMapLength??4294967295,this.maxExtLength=A?.maxExtLength??4294967295,this.keyDecoder=A?.keyDecoder!==void 0?A.keyDecoder:Ls,this.mapKeyConverter=A?.mapKeyConverter??vs}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=dA,this.stack.reset()}setBuffer(A){let t=uA(A);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(A){if(this.headByte===dA&&!this.hasRemaining(1))this.setBuffer(A);else{let t=this.bytes.subarray(this.pos),e=uA(A),i=new Uint8Array(t.length+e.length);i.set(t),i.set(e,t.length),this.setBuffer(i)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:t,pos:e}=this;return new RangeError(\`Extra \${t.byteLength-e} of \${t.byteLength} byte(s) found at buffer[\${A}]\`)}decode(A){if(this.entered)return this.clone().decode(A);try{this.entered=!0,this.reinitializeState(),this.setBuffer(A);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(A){if(this.entered){yield*this.clone().decodeMulti(A);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(A);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(A){if(this.entered)return this.clone().decodeAsync(A);try{this.entered=!0;let t=!1,e;for await(let C of A){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(C);try{e=this.doDecodeSync(),t=!0}catch(v){if(!(v instanceof RangeError))throw v}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return e}let{headByte:i,pos:d,totalPos:q}=this;throw new RangeError(\`Insufficient data in parsing \${bA(i)} at \${q} (\${d} in the current buffer)\`)}finally{this.entered=!1}}decodeArrayStream(A){return this.decodeMultiAsync(A,!0)}decodeStream(A){return this.decodeMultiAsync(A,!1)}async*decodeMultiAsync(A,t){if(this.entered){yield*this.clone().decodeMultiAsync(A,t);return}try{this.entered=!0;let e=t,i=-1;for await(let d of A){if(t&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(d),e&&(i=this.readArraySize(),e=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(q){if(!(q instanceof RangeError))throw q}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){A:for(;;){let A=this.readHeadByte(),t;if(A>=224)t=A-256;else if(A<192)if(A<128)t=A;else if(A<144){let i=A-128;if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A<160){let i=A-144;if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else{let i=A-160;t=this.decodeString(i,0)}else if(A===192)t=null;else if(A===194)t=!1;else if(A===195)t=!0;else if(A===202)t=this.readF32();else if(A===203)t=this.readF64();else if(A===204)t=this.readU8();else if(A===205)t=this.readU16();else if(A===206)t=this.readU32();else if(A===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(A===208)t=this.readI8();else if(A===209)t=this.readI16();else if(A===210)t=this.readI32();else if(A===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(A===217){let i=this.lookU8();t=this.decodeString(i,1)}else if(A===218){let i=this.lookU16();t=this.decodeString(i,2)}else if(A===219){let i=this.lookU32();t=this.decodeString(i,4)}else if(A===220){let i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===221){let i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===222){let i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===223){let i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===196){let i=this.lookU8();t=this.decodeBinary(i,1)}else if(A===197){let i=this.lookU16();t=this.decodeBinary(i,2)}else if(A===198){let i=this.lookU32();t=this.decodeBinary(i,4)}else if(A===212)t=this.decodeExtension(1,0);else if(A===213)t=this.decodeExtension(2,0);else if(A===214)t=this.decodeExtension(4,0);else if(A===215)t=this.decodeExtension(8,0);else if(A===216)t=this.decodeExtension(16,0);else if(A===199){let i=this.lookU8();t=this.decodeExtension(i,1)}else if(A===200){let i=this.lookU16();t=this.decodeExtension(i,2)}else if(A===201){let i=this.lookU32();t=this.decodeExtension(i,4)}else throw new L(\`Unrecognized type byte: \${bA(A)}\`);this.complete();let e=this.stack;for(;e.length>0;){let i=e.top();if(i.type===hr)if(i.array[i.position]=t,i.position++,i.position===i.size)t=i.array,e.release(i);else continue A;else if(i.type===qA){if(t==="__proto__")throw new L("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,e.release(i);else{i.key=null,i.type=qA;continue A}}return t}}readHeadByte(){return this.headByte===dA&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=dA}readArraySize(){let A=this.readHeadByte();switch(A){case 220:return this.readU16();case 221:return this.readU32();default:{if(A<160)return A-144;throw new L(\`Unrecognized array type byte: \${bA(A)}\`)}}}pushMapState(A){if(A>this.maxMapLength)throw new L(\`Max length exceeded: map length (\${A}) > maxMapLengthLength (\${this.maxMapLength})\`);this.stack.pushMapState(A)}pushArrayState(A){if(A>this.maxArrayLength)throw new L(\`Max length exceeded: array length (\${A}) > maxArrayLength (\${this.maxArrayLength})\`);this.stack.pushArrayState(A)}decodeString(A,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(A,t):this.decodeBinary(A,t)}decodeUtf8String(A,t){if(A>this.maxStrLength)throw new L(\`Max length exceeded: UTF-8 byte length (\${A}) > maxStrLength (\${this.maxStrLength})\`);if(this.bytes.byteLength<this.pos+t+A)throw It;let e=this.pos+t,i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?i=this.keyDecoder.decode(this.bytes,e,A):i=Ct(this.bytes,e,A),this.pos+=t+A,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===qA:!1}decodeBinary(A,t){if(A>this.maxBinLength)throw new L(\`Max length exceeded: bin length (\${A}) > maxBinLength (\${this.maxBinLength})\`);if(!this.hasRemaining(A+t))throw It;let e=this.pos+t,i=this.bytes.subarray(e,e+A);return this.pos+=t+A,i}decodeExtension(A,t){if(A>this.maxExtLength)throw new L(\`Max length exceeded: ext length (\${A}) > maxExtLength (\${this.maxExtLength})\`);let e=this.view.getInt8(this.pos+t),i=this.decodeBinary(A,t+1);return this.extensionCodec.decode(i,e,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let A=this.view.getUint8(this.pos);return this.pos++,A}readI8(){let A=this.view.getInt8(this.pos);return this.pos++,A}readU16(){let A=this.view.getUint16(this.pos);return this.pos+=2,A}readI16(){let A=this.view.getInt16(this.pos);return this.pos+=2,A}readU32(){let A=this.view.getUint32(this.pos);return this.pos+=4,A}readI32(){let A=this.view.getInt32(this.pos);return this.pos+=4,A}readU64(){let A=pt(this.view,this.pos);return this.pos+=8,A}readI64(){let A=BA(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(n,A){return new KA(A).decode(n)}var fA=class n{constructor(A,t,e,i,d){this.mediaIds=A;this.sequenceNumber=t;this.timeStamp=e;this.isEndOfSpurt=i;this.payload=d}static parse(A){let t;try{t=Er(A)}catch{return D("not valid msgpack")}if(!Array.isArray(t))return D("container must be an array");if(t.length<6)return D("missing fields");if(t[0]!==1)return D("unknown type");if(!Array.isArray(t[1]))return D("media ids must be an array");if(!t[1].every(B=>typeof B=="number"))return D("media ids must be numbers");if(typeof t[2]!="number")return D("sequence number must be a number");if(typeof t[3]!="number")return D("timestamp must be a number");if(typeof t[4]!="number")return D("flags must be a number");let e=t[1],i=t[2]>>>0,d=t[3]>>>0,C=(t[4]&1)!==0,v=t[t.length-1];return v instanceof Uint8Array?et(new n(e,i,d,C,v)):D("payload must be bytes")}toBytes(){let A=Number(this.isEndOfSpurt),t=[1,this.mediaIds,this.sequenceNumber>>>0,this.timeStamp>>>0,A,this.payload];return new Uint8Array(pr(t,{forceFloat32:!0,ignoreUndefined:!0}))}};var OA=class{constructor(A,t){this.sampleRate=A;this.wasm=t;this.sequenceNumber=Math.random()*Math.pow(2,32)>>0;this.timestamp=Math.random()*Math.pow(2,32)>>0;this.connections=[];this.monitoring=!1;this.active=!1;this.stats={numberPackets:0,numberTicks:0,numberPacketError:0,numberPacketsMediaNotFound:0};this.encoder=new t.Encoder(A,15,!0,J.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=ct(this.wasm),this.outBuffer=T(this.wasm,"u8",1270),Zj(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(){dt(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){ot(\`failed encoding packet: \${t}\`);return}if(this.timestamp=this.timestamp+1800>>0,t===1)continue;this.sequenceNumber=this.sequenceNumber+1>>0;let e=this.active&&!this.encoder.active;this.active=this.encoder.active,this.monitoring=this.connections.some(i=>i.id===0);for(let i of this.connections){if(this.monitoring&&i.id!==0)continue;let d=new fA(i.mediaIds,this.sequenceNumber,this.timestamp,e,this.outBuffer.subarray(0,t));aA(globalThis,["sendPacket",{connectionId:i.id,packet:d.toBytes()}])}}}onMessage(A){let[t,e]=A;switch(t){case"captureSetVad":this?.setVad(e);break;case"captureSetMedias":this?.setMedias(e.connections);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){return{sequenceNumber:this.sequenceNumber,timestamp:this.timestamp,connections:this.connections.map(A=>\`\${A.id} => \${A.mediaIds.join(",")}\`),active:this.active,monitoring:this.monitoring,information:{active:Wj(this.information),speechProbability:Qj(this.information),rmsDBFS:zj(this.information),volume:Xj(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=T(this.wasm,"u32",J.MaxNumberOfDecoders),this.information=kt(this.wasm,J.MaxNumberOfDecoders),Oj(this.information,[1,1])}close(){ut(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,t){this.stats.numberPackets++;let e=fA.parse(t);if(e.type==="Failure"){this.stats.numberPacketError++;let i=Array.from(t).map(d=>d.toString(16).padStart(2,"0")).join("");console.error(\`failed decoding audio packet; reason: \${e.reason}, connection: \${A}, dump: \${i}\`);return}for(let i of e.value.mediaIds){let d=this.medias.get(xA({connectionId:A,mediaId:i}));if(d===void 0){this.stats.numberPacketsMediaNotFound++;continue}d.lastPacket=t;let q=T(this.wasm,"u8",e.value.payload.length);q.set(e.value.payload),d.decoder.push(e.value.sequenceNumber,e.value.timeStamp,e.value.isEndOfSpurt,q.byteOffset,q.length)}}insertMedia(A,t,e,i=[1,1]){let d=xA({connectionId:t,mediaId:e}),q=new this.wasm.Decoder;this.medias.set(d,{index:A,decoder:q,lastPacket:void 0}),this.decoders[A]=q.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),Tj(this.information,A,i),Rj(this.information,A,0),Sj(this.information,A,0)}removeMedia(A,t,e){let i=xA({connectionId:t,mediaId:e}),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,e]=A;switch(t){case"playbackReceivePacket":this.receivePacket(e.connectionId,e.packet);break;case"playbackUpdateMedias":for(let{index:i,connectionId:d,mediaId:q}of e.removed)this.removeMedia(i,d,q);for(let{index:i,connectionId:d,mediaId:q,volume:C}of e.added)this.insertMedia(i,d,q,C);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){let A=[];for(let[t,e]of this.medias){let i=at(t);A.push({index:e.index,connectionId:i.connectionId,mediaId:i.mediaId,rmsDBFS:Pj(this.information,e.index),volume:Mj(this.information,e.index),voicedBlocks:Vj(this.information,e.index),silentBlocks:Uj(this.information,e.index),time:e.decoder.time,consecutive_silence:e.decoder.consecutive_silence,last_voiced_time_point:e.decoder.last_voiced_time_point,sequence_number:e.decoder.sequence_number,packetsSeen:e.decoder.packets_seen,packetsInvalid:e.decoder.packets_invalid,packetsTooLate:e.decoder.packets_too_late,packetsTooEarly:e.decoder.packets_too_early,packetsRepeated:e.decoder.packets_repeated,packetsProcessed:e.decoder.packets_processed,packetsLost:e.decoder.packets_lost,rewinds:e.decoder.rewinds,cacheLength:e.decoder.cache_length,lastPacket:Yj(e.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:Kj(this.information),decoders:A}}};var Lt=Fn($t()),Ft=(0,Lt.default)(),vt,gt;globalThis.addEventListener("message",$r);async function $r(n){let A=n.data,[t,e]=A;switch(t){case"captureInit":e.workletPort.onmessage=$r,vt=new Fr(e.sampleRate,await Ft);break;case"playbackInit":e.workletPort.onmessage=$r,gt=new vr(await Ft);break;case"close":globalThis.close();break}vt?.onMessage(A),gt?.onMessage(A)}var Fr=class extends OA{constructor(t,e){super(t,e);this.id=-1;this.samples=fr(this.wasm,t,2+J.VadPreload+J.AdditionalCaptureBlocks,!1),aA(globalThis,["captureReady",{sampleBuffer:this.samples,informationBuffer:this.information}])}close(){super.close(),Cr(this.wasm,this.samples)}onMessage(t){super.onMessage(t);let[e,i]=t;e==="captureTick"&&this.tick(i.id)}tick(t){for(;this.id<t;this.id+=1)this.encode(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()}}},vr=class extends PA{constructor(A){super(A);let t=2+J.AdditionalPlaybackBlocks;this.sampleBuffer=fr(A,48e3,t,!0),this.sampleBuffer.samples.fill(0),this.prefill=t-2;for(let e=0;e<this.prefill;e++)ur(this.sampleBuffer,e,{id:e});this.id=this.prefill,aA(globalThis,["playbackReady",{sampleBuffer:this.sampleBuffer,informationBuffer:this.information}])}close(){super.close(),Cr(this.wasm,this.sampleBuffer)}onMessage(A){super.onMessage(A);let[t,e]=A;t==="playbackTick"&&this.tick(e.id)}tick(A){for(this.stats.numberTicks++;this.id<A+this.prefill;this.id++){let t=this.id%this.sampleBuffer.length,{hasAudio:e}=this.decode(kr(this.sampleBuffer,t));e&&(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()}}};})();
|
|
3236
|
-
`});var Qx,g0=q(()=>{Qx='"use strict";(()=>{var R=Object.defineProperty;var F=(e,t)=>{for(var r in t)R(e,r,{get:t[r],enumerable:!0})};var l={};F(l,{AdditionalCaptureBlocks:()=>D,AdditionalPlaybackBlocks:()=>C,ClockJumpCheckInterval:()=>j,ClockJumpThreshold:()=>$,ConnectInterval:()=>Y,ConnectTimeout:()=>Z,DefaultRefreshRate:()=>V,DefaultVideoCodec:()=>K,HealthCheckTimeout:()=>W,MainConnectionPingInterval:()=>H,MaxNumberOfDecoders:()=>_,MinDBFs:()=>k,MinTokenLifetime:()=>q,MinTokenRefreshInterval:()=>Q,PlaybackPreload:()=>L,RenderQuantumSize:()=>N,VadPreload:()=>O,WebRtcIceTimeout:()=>z,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=5e3,q=6e4,Q=5e3,Y=[0,100,200,200,500],K="H264";function p(e,t,r){return e.postMessage(t,r)}function X(e){return e.sampleRate*.02*(e.stereo?2:1)}function f(e,t){let r=X(e),n=r*t,s=n+r;return e.samples.subarray(n,s)}function S(e,t){return{id:e.headers[t]}}function I(e,t,r){e.headers[t]=r.id}var ee;(e=>{let t;(r=>(r[r.InvalidPassword=-1]="InvalidPassword",r[r.Unknown=0]="Unknown",r[r.Unencrypted=1]="Unencrypted",r[r.Encrypted=2]="Encrypted"))(t=e.PeerCipherStatus||={})})(ee||={});var{Deno:U}=globalThis,te=typeof U?.noColor=="boolean"?U.noColor:!1,re=!te;function h(e,t){return{open:`\\x1B[${e.join(";")}m`,close:`\\x1B[${t}m`,regexp:new RegExp(`\\\\x1b\\\\[${t}m`,"g")}}function b(e,t){return re?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}function m(e){return b(e,h([0],0))}function T(e){return b(e,h([1],22))}function ne(e){return b(e,h([2],22))}var Te=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),se=new Date,d=(e=>(e[e.CRITICAL=0]="CRITICAL",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(d||{}),P={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},oe={4:ne,3:m,2:m,1:T,0:T};function ae({message:e}){return String(e)}function B(e){return JSON.stringify({timestamp:e.date.toISOString(),level:d[e.level],message:e.message,extra:e.extra})}function w(e){function t(c,i){return[Math.floor(c/i),c%i]}function r(){let c,i=e.date.valueOf()-se.valueOf();[i,c]=t(i,1e3);let[M,E]=t(i,60);return`${M.toString().padStart(4,"0")}:${E.toString().padStart(2,"0")}.${c.toString().padStart(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} ${oe[e.level](String(e.message))}${n()}`}function ie(e){let t=`[${e.date.toISOString()}]`,r=`[${d[e.level]}]`,n=e.logger.name!==void 0?`[${e.logger.name}] `:"",s=P[e.level];return`${t} ${s} ${r.padEnd(7," ")} ${n}${e.message}`}function ce(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var A=class{static sparse=ae;static json=B;static pretty=w;static structured=ie;static default=ce()?w:B;constructor(){}};var le=class{formatter;consoleObject;filter;constructor(e=A.default,t=4,r=console){this.filter=t,this.formatter=e,this.consoleObject=r}handle(e){let t=this.formatter(e);switch(e.level){case 0:case 1:this.consoleObject.error(t);break;case 2:this.consoleObject.warn(t);break;case 3:this.consoleObject.info(t);break;case 4:this.consoleObject.debug(t);break}}};var 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 le]),ue=o.prototype.log.bind(u,1),fe=o.prototype.log.bind(u,2),de=o.prototype.log.bind(u,3),pe=o.prototype.log.bind(u,4),Be=o.prototype.log.bind(u);var y=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}}},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 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",y);registerProcessor("OdinPlaybackProcessor",x);})();\n'});var $0={};Tx($0,{createCaptureWorker:()=>AF,createPlaybackWorker:()=>FF});import{Strand as YA}from"@4players/odin-common";function AF(v,t,j,e,B=i.DefaultRefreshRate){return xF.enqueue(async()=>{let[C,E]=await Y(Wx,Qx,v,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return Xx.create(v,t,j,C,E,e)})}async function FF(v,t=i.DefaultRefreshRate){if(v.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[j,e]=await Y(Wx,Qx,v,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return zx.create(v,j,e)}var xF,zx,Xx,y0=q(()=>{"use strict";u();nx();I0();g0();xF=new YA;zx=class v extends z{constructor(j,e,B,C){super(j,e,B);this.information=C}static async create(j,e,B){let{port1:C,port2:E}=new MessageChannel;k(e,["playbackInit",{workletPort:C}],[C]);let{informationBuffer:f,sampleBuffer:s}=await U(e,"playbackReady");return Vx(f,[1,1]),k(B.port,["init",{sampleBuffer:s,workerPort:E}],[E]),new v(j,B,e,f)}getActivity(j){let e=this.medias.get(m(j));if(e===void 0)return;let B=f0(this.information,e.index);return B===0?_:{isSilent:!1,rmsDBFS:B}}getJitterStats(j){}setGlobalVolume(j){Vx(this.information,j)}setVolume(j,e){let B=this.medias.get(m(j));B!==void 0&&n0(this.information,B.index,e)}_GetFreeIndex(){let j=super._GetFreeIndex();if(j!==void 0)return j;if(this.information.length>this.medias.size)return this.medias.size}},Xx=class v extends X{constructor(j,e,B,C,E,f){super(j,e,B,C,f);this.information=E}static async create(j,e,B,C,E,f){let{port1:s,port2:o}=new MessageChannel;k(C,["captureInit",{sampleRate:j.sampleRate,workletPort:s}],[s]);let{sampleBuffer:p,informationBuffer:h}=await U(C,"captureReady");return k(E.port,["init",{workerPort:o,sampleBuffer:p}],[o]),new v(E,C,e,B,h,f)}get activity(){return{isSilent:!s0(this.information),rmsDBFS:b0(this.information)}}get speechProbability(){return i0(this.information)}setVolume(j){o0(this.information,j)}}});var Zx,_0=q(()=>{Zx=`"use strict";(()=>{var oe=Object.create;var WA=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var ue=Object.getPrototypeOf,ce=Object.prototype.hasOwnProperty;var de=(n,A)=>()=>(A||n((A={exports:{}}).exports,A),A.exports),qe=(n,A)=>{for(var t in A)WA(n,t,{get:A[t],enumerable:!0})},fe=(n,A,t,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let l of ke(A))!ce.call(n,l)&&l!==t&&WA(n,l,{get:()=>A[l],enumerable:!(e=ae(A,l))||e.enumerable});return n};var Ce=(n,A,t)=>(t=n!=null?oe(ue(n)):{},fe(A||!n||!n.__esModule?WA(t,"default",{value:n,enumerable:!0}):t,n));var Hj=de((Lj,JA)=>{"use strict";var er=(()=>{var n=globalThis.document?.currentScript?.src;return async function(A={}){var t,e=A,l=!!globalThis.window,d=!!globalThis.WorkerGlobalScope,q=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",p=[],F="./this.program";d&&(n=self.location.href);var x="",KA,O;if(l||d){try{x=new URL(".",n).href}catch{}d&&(O=j=>{var r=new XMLHttpRequest;return r.open("GET",j,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),KA=async j=>{var r=await fetch(j,{credentials:"same-origin"});if(r.ok)return r.arrayBuffer();throw new Error(r.status+" : "+r.url)}}var ir=console.log.bind(console),oA=console.error.bind(console),or,ar=!1;function Nj(j){for(var r=0,s=j.length,i=new Uint8Array(s),o;r<s;++r)o=j.charCodeAt(r),i[r]=~o>>8&o;return i}var kr,ur,cr=!1;function Bj(){var j=Ur.buffer;U=new Int8Array(j),aA=new Int16Array(j),e.HEAPU8=_=new Uint8Array(j),Z=new Uint16Array(j),e.HEAP32=kA=new Int32Array(j),e.HEAPU32=m=new Uint32Array(j),e.HEAPF32=fr=new Float32Array(j),Cr=new Float64Array(j),qr=new BigInt64Array(j),Gr=new BigUint64Array(j)}function bj(){if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)Sj(e.preRun.shift());pr(hr)}function Jj(){cr=!0,rA.v()}function Kj(){if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)Vj(e.postRun.shift());pr(Ir)}function OA(j){e.onAbort?.(j),j="Aborted("+j+")",oA(j),ar=!0,j+=". Build with -sASSERTIONS for more info.";var r=new WebAssembly.RuntimeError(j);throw ur?.(r),r}var dr;function Oj(){return Nj(\`\\0asm\\0\\0\\0\\x8D9\\\`\\x7F\\x7F\\\`\\x7F\\0\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\0\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`||\\\`\\x7F}\\\`}}\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F~\\\`\\x7F\\x7F}\\\`\\x7F}}\\\`\\x7F\\x7F}}\\0\\\`
|
|
3235
|
+
\`,new Function(I,f)}function rr(r,j,s,l,o,k){var a=j.length;a<2&&p("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var u=j[1]!==null&&s!==null,c=ij(j),f=!j[0].isVoid,G=j[0],I=j[1],$=[r,p,l,o,sj,G.fromWireType.bind(G),I?.toWireType.bind(I)],m=2;m<a;++m){var F=j[m];$.push(F.toWireType.bind(F))}if(!c)for(var m=u?1:2;m<j.length;++m)j[m].destructorFunction!==null&&$.push(j[m].destructorFunction);var P=Ie(j,u,f,k)(...$);return Aj(r,P)}var me=(r,j,s,l,o,k)=>{var a=Ar(j,s);o=K(l,o),M([],[r],u=>{u=u[0];var c=\`constructor \${u.name}\`;if(u.registeredClass.constructor_body===void 0&&(u.registeredClass.constructor_body=[]),u.registeredClass.constructor_body[j-1]!==void 0)throw new iA(\`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\`,a)},M([],a,f=>(f.splice(1,0,null),u.registeredClass.constructor_body[j-1]=rr(c,f,null,o,k),[])),[]})},lj=r=>{r=r.trim();let j=r.indexOf("(");return j===-1?r:r.slice(0,j)},Ee=(r,j,s,l,o,k,a,u,c,f)=>{var G=Ar(s,l);j=g(j),j=lj(j),k=K(o,k,c),M([],[r],I=>{I=I[0];var $=\`\${I.name}.\${j}\`;j.startsWith("@@")&&(j=Symbol[j.substring(2)]),u&&I.registeredClass.pureVirtualFunctions.push(j);function m(){AA(\`Cannot call \${$} due to unbound types\`,G)}var F=I.registeredClass.instancePrototype,_=F[j];return _===void 0||_.overloadTable===void 0&&_.className!==I.name&&_.argCount===s-2?(m.argCount=s-2,m.className=I.name,F[j]=m):(jj(F,j,$),F[j].overloadTable[s-2]=m),M([],G,P=>{var y=rr($,P,I,k,a,c);return F[j].overloadTable===void 0?(y.argCount=s-2,F[j]=y):F[j].overloadTable[s-2]=y,[]}),[]})},oj=(r,j,s)=>(r instanceof Object||p(\`\${s} with invalid "this": \${r}\`),r instanceof j.registeredClass.constructor||p(\`\${s} incompatible with "this" of type \${r.constructor.name}\`),r.$$.ptr||p(\`cannot call emscripten binding method \${s} on deleted object\`),$A(r.$$.ptr,r.$$.ptrType.registeredClass,j.registeredClass)),$e=(r,j,s,l,o,k,a,u,c,f)=>{j=g(j),o=K(l,o),M([],[r],G=>{G=G[0];var I=\`\${G.name}.\${j}\`,$={get(){AA(\`Cannot access \${I} due to unbound types\`,[s,a])},enumerable:!0,configurable:!0};return c?$.set=()=>AA(\`Cannot access \${I} due to unbound types\`,[s,a]):$.set=m=>p(I+" is a read-only property"),Object.defineProperty(G.registeredClass.instancePrototype,j,$),M([],c?[s,a]:[s],m=>{var F=m[0],_={get(){var y=oj(this,G,I+" getter");return F.fromWireType(o(k,y))},enumerable:!0};if(c){c=K(u,c);var P=m[1];_.set=function(y){var oA=oj(this,G,I+" setter"),H=[];c(f,oA,P.toWireType(H,y)),sj(H)}}return Object.defineProperty(G.registeredClass.instancePrototype,j,_),[]}),[]})},aj=[],rA=[0,1,,1,null,1,!0,1,!1,1],Fe=r=>{r>9&&--rA[r+1]===0&&(rA[r]=void 0,aj.push(r))},jr={toValue:r=>(r||p(\`Cannot use deleted val. handle = \${r}\`),rA[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=aj.pop()||rA.length;return rA[j]=r,rA[j+1]=1,j}}}},ve={name:"emscripten::val",fromWireType:r=>{var j=jr.toValue(r);return Fe(r),j},toWireType:(r,j)=>jr.toHandle(j),readValueFromPointer:FA,destructorFunction:null},ge=r=>b(r,ve),Le=(r,j)=>{switch(j){case 4:return function(s){return this.fromWireType(Jr[s>>2])};case 8:return function(s){return this.fromWireType(hA[s>>3])};default:throw new TypeError(\`invalid float width (\${j}): \${r}\`)}},He=(r,j,s)=>{j=g(j),b(r,{name:j,fromWireType:l=>l,toWireType:(l,o)=>o,readValueFromPointer:Le(j,s),destructorFunction:null})},_e=(r,j,s,l,o,k,a,u)=>{var c=Ar(j,s);r=g(r),r=lj(r),o=K(l,o,a),tj(r,function(){AA(\`Cannot call \${r} due to unbound types\`,c)},j-1),M([],c,f=>{var G=[f[0],null].concat(f.slice(1));return nj(r,rr(r,G,null,o,k,a),j-1),[]})},ye=(r,j,s,l,o)=>{j=g(j);let k=l===0,a=c=>c;if(k){var u=32-8*s;a=c=>c<<u>>>u,o=a(o)}b(r,{name:j,fromWireType:a,toWireType:(c,f)=>f,readValueFromPointer:zr(j,s,l!==0),destructorFunction:null})},xe=(r,j,s)=>{var l=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=l[j];function k(a){var u=E[a>>2],c=E[a+4>>2];return new o(V.buffer,c,u)}s=g(s),b(r,{name:s,fromWireType:k,readValueFromPointer:k},{ignoreDuplicateRegistrations:!0})},De=(r,j,s,l)=>{if(!(l>0))return 0;for(var o=s,k=s+l-1,a=0;a<r.length;++a){var u=r.codePointAt(a);if(u<=127){if(s>=k)break;j[s++]=u}else if(u<=2047){if(s+1>=k)break;j[s++]=192|u>>6,j[s++]=128|u&63}else if(u<=65535){if(s+2>=k)break;j[s++]=224|u>>12,j[s++]=128|u>>6&63,j[s++]=128|u&63}else{if(s+3>=k)break;j[s++]=240|u>>18,j[s++]=128|u>>12&63,j[s++]=128|u>>6&63,j[s++]=128|u&63,a++}}return j[s]=0,s-o},Be=(r,j,s)=>De(r,x,j,s),Ne=r=>{for(var j=0,s=0;s<r.length;++s){var l=r.charCodeAt(s);l<=127?j++:l<=2047?j+=2:l>=55296&&l<=57343?(j+=4,++s):j+=3}return j},kj=globalThis.TextDecoder&&new TextDecoder,uj=(r,j,s,l)=>{var o=j+s;if(l)return o;for(;r[j]&&!(j>=o);)++j;return j},cj=(r,j=0,s,l)=>{var o=uj(r,j,s,l);if(o-j>16&&r.buffer&&kj)return kj.decode(r.buffer instanceof ArrayBuffer?r.subarray(j,o):r.slice(j,o));for(var k="";j<o;){var a=r[j++];if(!(a&128)){k+=String.fromCharCode(a);continue}var u=r[j++]&63;if((a&224)==192){k+=String.fromCharCode((a&31)<<6|u);continue}var c=r[j++]&63;if((a&240)==224?a=(a&15)<<12|u<<6|c:a=(a&7)<<18|u<<12|c<<6|r[j++]&63,a<65536)k+=String.fromCharCode(a);else{var f=a-65536;k+=String.fromCharCode(55296|f>>10,56320|f&1023)}}return k},be=(r,j,s)=>r?cj(x,r,j,s):"",Je=(r,j)=>{j=g(j);var s=!0;b(r,{name:j,fromWireType(l){var o=E[l>>2],k=l+4,a;if(s)a=be(k,o,!0);else{a="";for(var u=0;u<o;++u)a+=String.fromCharCode(x[k+u])}return O(l),a},toWireType(l,o){o instanceof ArrayBuffer&&(o=new Uint8Array(o));var k,a=typeof o=="string";a||ArrayBuffer.isView(o)&&o.BYTES_PER_ELEMENT==1||p("Cannot pass non-string to std::string"),s&&a?k=Ne(o):k=o.length;var u=nr(4+k+1),c=u+4;if(E[u>>2]=k,a)if(s)Be(o,c,k+1);else for(var f=0;f<k;++f){var G=o.charCodeAt(f);G>255&&(O(u),p("String has UTF-16 code units that do not fit in 8 bits")),x[c+f]=G}else x.set(o,c);return l!==null&&l.push(O,u),u},readValueFromPointer:FA,destructorFunction(l){O(l)}})},dj=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Ke=(r,j,s)=>{var l=r>>1,o=uj(nA,l,j/2,s);if(o-l>16&&dj)return dj.decode(nA.slice(l,o));for(var k="",a=l;a<o;++a){var u=nA[a];k+=String.fromCharCode(u)}return k},Oe=(r,j,s)=>{if(s??=2147483647,s<2)return 0;s-=2;for(var l=j,o=s<r.length*2?s/2:r.length,k=0;k<o;++k){var a=r.charCodeAt(k);pA[j>>1]=a,j+=2}return pA[j>>1]=0,j-l},Pe=r=>r.length*2,we=(r,j,s)=>{for(var l="",o=r>>2,k=0;!(k>=j/4);k++){var a=E[o+k];if(!a&&!s)break;l+=String.fromCodePoint(a)}return l},Me=(r,j,s)=>{if(s??=2147483647,s<4)return 0;for(var l=j,o=l+s-4,k=0;k<r.length;++k){var a=r.codePointAt(k);if(a>65535&&k++,z[j>>2]=a,j+=4,j+4>o)break}return z[j>>2]=0,j-l},Te=r=>{for(var j=0,s=0;s<r.length;++s){var l=r.codePointAt(s);l>65535&&s++,j+=4}return j},Ue=(r,j,s)=>{s=g(s);var l,o,k;j===2?(l=Ke,o=Oe,k=Pe):(l=we,o=Me,k=Te),b(r,{name:s,fromWireType:a=>{var u=E[a>>2],c=l(a+4,u*j,!0);return O(a),c},toWireType:(a,u)=>{typeof u!="string"&&p(\`Cannot pass non-string to C++ string type \${s}\`);var c=k(u),f=nr(4+c+j);return E[f>>2]=c/j,o(u,f+4,c+j),a!==null&&a.push(O,f),f},readValueFromPointer:FA,destructorFunction(a){O(a)}})},Se=(r,j)=>{j=g(j),b(r,{isVoid:!0,name:j,fromWireType:()=>{},toWireType:(s,l)=>{}})},Ve=r=>{sr(r,!d,1,!i,65536,!1),h.threadInitTLS()},qj=r=>{if(r instanceof br||r=="unwind")return Q;CA(1,r)},Re=()=>{if(!WA())try{if(C){_A()&&ir(Q);return}QA(Q)}catch(r){qj(r)}},fj=r=>{if(!GA)try{return r()}catch(j){qj(j)}finally{Re()}},We=!Atomics.waitAsync||globalThis.navigator?.userAgent&&Number((navigator.userAgent.match(/Chrom(e|ium)\\/([0-9]+)\\./)||[])[2])<91,tr=r=>{if(!We){var j=Atomics.waitAsync(z,r>>2,r);j.value.then(HA);var s=r+120;Atomics.store(z,s>>2,1)}},HA=()=>fj(()=>{var r=_A();r&&(tr(r),vj())}),Qe=(r,j)=>{if(r==j)setTimeout(HA);else if(C)postMessage({targetThread:r,cmd:"checkMailbox"});else{var s=h.pthreads[r];if(!s)return;s.postMessage({cmd:"checkMailbox"})}},er=[],ze=(r,j,s,l,o,k,a)=>{er.length=0;for(var u=o>>3,c=o+l>>3;u<c;){var f;S[u++]?f=S[u++]:f=hA[u++],er.push(f)}var G=kn[r];h.currentProxiedOperationCallerThread=s;var I=G(...er);if(h.currentProxiedOperationCallerThread=0,k){I.then($=>Ej(k,a,$));return}return I},Xe=r=>{C?postMessage({cmd:"cleanupThread",thread:r}):Pr(r)},Ze=r=>{},Ye=()=>performance.timeOrigin+performance.now(),An=9007199254740992,rn=-9007199254740992,jn=r=>r<rn||r>An?NaN:Number(r),tn=()=>{},en=()=>{RA+=1},nn=()=>{throw en(),"unwind"},sn=r=>{VA("OOM")},ln=r=>{var j=x.length;r>>>=0,sn(r)};function Cj(r){return C?sA(2,0,1,r):52}function Gj(r,j,s,l){return C?sA(3,0,1,r,j,s,l):(j=jn(j),70)}var on=[null,[],[]],an=(r,j)=>{var s=on[r];j===0||j===10?((r===1?TA:N)(cj(s)),s.length=0):s.push(j)};function pj(r,j,s,l){if(C)return sA(4,0,1,r,j,s,l);for(var o=0,k=0;k<s;k++){var a=E[j>>2],u=E[j+4>>2];j+=8;for(var c=0;c<u;c++)an(r,x[a+c]);o+=u}return E[l>>2]=o,0}if(h.init(),ee(),Ce(),xt(),e.noExitRuntime&&(zA=e.noExitRuntime),e.print&&(TA=e.print),e.printErr&&(N=e.printErr),e.wasmBinary&&(gr=e.wasmBinary),e.arguments&&(v=e.arguments),e.thisProgram&&(B=e.thisProgram),e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.shift()();var kn=[Ur,Sr,Cj,Gj,pj],hj,Ij,_A,nr,O,un,sr,mj,Ej,$j,Fj,ir,vj,gj,Lj,Hj,_j,cn,yj;function dn(r){hj=r.G,Ij=r.H,_A=r.J,nr=e._malloc=r.K,O=e._free=r.L,un=r.M,sr=r.N,mj=r.O,Ej=r.P,$j=r.Q,Fj=r.R,ir=r.S,vj=r.T,gj=r.U,Lj=r.V,Hj=r.W,_j=r.X,cn=yj=r.I}var xj;function qn(){xj={i:zt,C:Xt,h:Yt,o:Ae,n:he,m:me,e:Ee,b:$e,D:ge,l:He,q:_e,d:ye,c:xe,E:Je,g:Ue,p:Se,z:Ve,u:Qe,k:ze,s:Xe,y:tr,B:Ze,x:tn,A:nn,f:Ye,t:ln,r:QA,w:Cj,v:Gj,j:pj,a:X}}function Dj(){if(C){UA?.(e),xr();return}Dt();function r(){e.calledRun=!0,!GA&&(xr(),UA?.(e),e.onRuntimeInitialized?.(),Bt())}e.setStatus?(e.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>e.setStatus(""),1),r()},1)):r()}var jA;return C||(jA=await Nr(),Dj()),_r?t=e:t=new Promise((r,j)=>{UA=r,Lr=j}),t}})();typeof Et=="object"&&typeof MA=="object"?(MA.exports=wA,MA.exports.default=wA):typeof define=="function"&&define.amd&&define([],()=>wA);var ys=globalThis.name=="em-pthread";ys&&wA()});var J={};En(J,{AdditionalCaptureBlocks:()=>gn,AdditionalPlaybackBlocks:()=>vn,ClockJumpCheckInterval:()=>Bn,ClockJumpThreshold:()=>Nn,ConnectInterval:()=>Sn,ConnectTimeout:()=>Mn,DefaultRefreshRate:()=>Hn,DefaultVideoCodec:()=>Vn,HealthCheckTimeout:()=>Dn,MainConnectionPingInterval:()=>bn,MaxNumberOfDecoders:()=>yn,MinDBFs:()=>Jj,MinTokenLifetime:()=>Tn,MinTokenRefreshInterval:()=>Un,PlaybackPreload:()=>Ln,RenderQuantumSize:()=>xn,VadPreload:()=>_n,WebRtcAnswerTimeout:()=>Pn,WebRtcIceTimeout:()=>Kn,WebRtcMaxNegotiationAttempts:()=>wn,WebRtcStatsSnapshotInterval:()=>Jn,WebRtcTimeout:()=>On});var vn=3,gn=3,Ln=3,Hn=250,_n=3,yn=512,xn=128,Jj=-758.596,Dn=1e4,Bn=1e3,Nn=1e4,bn=3e3,Jn=1e3,Kn=3e3,On=1e4,Pn=1e4,wn=3,Mn=5e3,Tn=6e4,Un=5e3,Sn=[0,100,200,200,500],Vn="H264";function aA(n,A,t){return n.postMessage(A,t)}function ar(n){return n.sampleRate*.02*(n.stereo?2:1)}function kr(n,A){let t=ar(n),e=t*A,i=e+t;return n.samples.subarray(e,i)}function ur(n,A,t){n.headers[A]=t.id}function Kj(n){return[n.values[0],n.values[1]]}function Oj(n,A){n.values[0]=A[0],n.values[1]=A[1]}function Pj(n,A){return n.values[2+A*5]}function wj(n,A,t){n.values[2+A*5]=t}function Mj(n,A){let t=2+A*5+1;return[n.values[t+0],n.values[t+1]]}function Tj(n,A,t){let e=2+A*5+1;n.values[e+0]=t[0],n.values[e+1]=t[1]}function Uj(n,A){return n.values[2+A*5+3]}function Sj(n,A,t){n.values[2+A*5+3]=t}function Vj(n,A){return n.values[2+A*5+4]}function Rj(n,A,t){n.values[2+A*5+4]=t}function Wj(n){return n.values[0]!==0}function Qj(n){return n.values[1]}function zj(n){return n.values[2]}function Xj(n){return n.values[3]}function Zj(n,A){return n.values[3]=A}function Yj(n){return n?Array.from(n).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var Rn;(n=>{let A;(t=>(t[t.InvalidPassword=-1]="InvalidPassword",t[t.Unknown=0]="Unknown",t[t.Unencrypted=1]="Unencrypted",t[t.Encrypted=2]="Encrypted"))(A=n.PeerCipherStatus||={})})(Rn||={});function et(n){return{type:"Success",value:n}}function D(n){return{type:"Failure",reason:n}}var{Deno:At}=globalThis,Wn=typeof At?.noColor=="boolean"?At.noColor:!1,Qn=!Wn;function dr(n,A){return{open:\`\\x1B[\${n.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function qr(n,A){return Qn?\`\${A.open}\${n.replace(A.regexp,A.open)}\${A.close}\`:n}function cr(n){return qr(n,dr([0],0))}function rt(n){return qr(n,dr([1],22))}function zn(n){return qr(n,dr([2],22))}var Ss=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),Xn=new Date,yA=(n=>(n[n.CRITICAL=0]="CRITICAL",n[n.ERROR=1]="ERROR",n[n.WARN=2]="WARN",n[n.INFO=3]="INFO",n[n.DEBUG=4]="DEBUG",n))(yA||{}),nt={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},Zn={4:zn,3:cr,2:cr,1:rt,0:rt};function Yn({message:n}){return String(n)}function jt(n){return JSON.stringify({timestamp:n.date.toISOString(),level:yA[n.level],message:n.message,extra:n.extra})}function tt(n){function A(q,C){return[Math.floor(q/C),q%C]}function t(){let q,C=n.date.valueOf()-Xn.valueOf();[C,q]=A(C,1e3);let[v,B]=A(C,60);return\`\${v.toString().padStart(4,"0")}:\${B.toString().padStart(2,"0")}.\${q.toString().padStart(3,"0")}\`}function e(){return n.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(n.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(n.extra)}let i=nt[n.level],d=n.logger.name!==void 0?\`@\${n.logger.name}\`:"";return\`\${cr(t())}\${d} \${i} \${Zn[n.level](String(n.message))}\${e()}\`}function As(n){let A=\`[\${n.date.toISOString()}]\`,t=\`[\${yA[n.level]}]\`,e=n.logger.name!==void 0?\`[\${n.logger.name}] \`:"",i=nt[n.level];return\`\${A} \${i} \${t.padEnd(7," ")} \${e}\${n.message}\`}function rs(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var st=class{static sparse=Yn;static json=jt;static pretty=tt;static structured=As;static default=rs()?tt:jt;constructor(){}};var js=class{formatter;consoleObject;filter;constructor(n=st.default,A=4,t=console){this.filter=A,this.formatter=n,this.consoleObject=t}handle(n){let A=this.formatter(n);switch(n.level){case 0:case 1:this.consoleObject.error(A);break;case 2:this.consoleObject.warn(A);break;case 3:this.consoleObject.info(A);break;case 4:this.consoleObject.debug(A);break}}};var R=class{#A;sinks;filter;parent;get name(){return this.#A}constructor(n,A=void 0,t=[],e=void 0){this.#A=A,this.sinks=t,this.filter=n,this.parent=e}log(n,A,t=void 0){let e={date:new Date,level:n,logger:this,message:A,extra:t};this.filter<n||this.insert(e)}insert(n){if(!(this.filter<n.level)){for(let A of this.sinks)A.filter>=n.level&&A.handle(n);this.parent!==void 0&&this.parent.insert(n)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},kA=globalThis[Symbol.for("odin-global-logger")]??=new R(3,void 0,[new js]),ts=R.prototype.log.bind(kA,1),es=R.prototype.log.bind(kA,2),it=R.prototype.log.bind(kA,3),ns=R.prototype.log.bind(kA,4),Vs=R.prototype.log.bind(kA);var lt;function ot(n,...A){let t=ss(A);lt?lt?.info(n,t):it(n,t)}function ss(...n){if(n.length===1&&typeof n[0]=="object"&&n[0]!==null)return{...n[0]};if(n.length>0)return{args:n}}function xA(n){return n.connectionId*4294967296+n.mediaId}function at(n){return{mediaId:n%4294967296,connectionId:Math.floor(n/4294967296)}}function T(n,A,t){let e;switch(A){case"f32":e=n.HEAPF32;break;case"u32":e=n.HEAPU32;break;case"i32":e=n.HEAP32;break;case"u8":e=n.HEAPU8;break;default:throw new Error(\`allocating \${A} is not supported\`)}let i=n._malloc(t*e.BYTES_PER_ELEMENT);if(i===0||i%e.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${t} \${A} array\`);let d=i/e.BYTES_PER_ELEMENT;return e.subarray(d,d+t)}function tA(n,A){n._free(A.byteOffset)}function fr(n,A,t,e){return{headers:T(n,"i32",t),samples:T(n,"f32",t*ar({sampleRate:A,stereo:e})),length:t,sampleRate:A,stereo:e}}function Cr(n,A){tA(n,A.headers),tA(n,A.samples)}function kt(n,A){return{values:T(n,"f32",2+A*5),length:A}}function ut(n,A){tA(n,A.values)}function ct(n){return{values:T(n,"f32",4)}}function dt(n,A){tA(n,A.values)}function qt(n){let A=n.length,t=0,e=0;for(;e<A;){let i=n.charCodeAt(e++);if((i&4294967168)===0){t++;continue}else if((i&4294965248)===0)t+=2;else{if(i>=55296&&i<=56319&&e<A){let d=n.charCodeAt(e);(d&64512)===56320&&(++e,i=((i&1023)<<10)+(d&1023)+65536)}(i&4294901760)===0?t+=3:t+=4}}return t}function is(n,A,t){let e=n.length,i=t,d=0;for(;d<e;){let q=n.charCodeAt(d++);if((q&4294967168)===0){A[i++]=q;continue}else if((q&4294965248)===0)A[i++]=q>>6&31|192;else{if(q>=55296&&q<=56319&&d<e){let C=n.charCodeAt(d);(C&64512)===56320&&(++d,q=((q&1023)<<10)+(C&1023)+65536)}(q&4294901760)===0?(A[i++]=q>>12&15|224,A[i++]=q>>6&63|128):(A[i++]=q>>18&7|240,A[i++]=q>>12&63|128,A[i++]=q>>6&63|128)}A[i++]=q&63|128}}var ls=new TextEncoder,os=50;function as(n,A,t){ls.encodeInto(n,A.subarray(t))}function ft(n,A,t){n.length>os?as(n,A,t):is(n,A,t)}var ks=4096;function Gr(n,A,t){let e=A,i=e+t,d=[],q="";for(;e<i;){let C=n[e++];if((C&128)===0)d.push(C);else if((C&224)===192){let v=n[e++]&63;d.push((C&31)<<6|v)}else if((C&240)===224){let v=n[e++]&63,B=n[e++]&63;d.push((C&31)<<12|v<<6|B)}else if((C&248)===240){let v=n[e++]&63,B=n[e++]&63,CA=n[e++]&63,w=(C&7)<<18|v<<12|B<<6|CA;w>65535&&(w-=65536,d.push(w>>>10&1023|55296),w=56320|w&1023),d.push(w)}else d.push(C);d.length>=ks&&(q+=String.fromCharCode(...d),d.length=0)}return d.length>0&&(q+=String.fromCharCode(...d)),q}var us=new TextDecoder,cs=200;function ds(n,A,t){let e=n.subarray(A,A+t);return us.decode(e)}function Ct(n,A,t){return t>cs?ds(n,A,t):Gr(n,A,t)}var W=class{constructor(A,t){this.type=A,this.data=t}};var L=class n extends Error{constructor(A){super(A);let t=Object.create(n.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:n.name})}};function Gt(n,A,t){let e=t/4294967296,i=t;n.setUint32(A,e),n.setUint32(A+4,i)}function DA(n,A,t){let e=Math.floor(t/4294967296),i=t;n.setUint32(A,e),n.setUint32(A+4,i)}function BA(n,A){let t=n.getInt32(A),e=n.getUint32(A+4);return t*4294967296+e}function pt(n,A){let t=n.getUint32(A),e=n.getUint32(A+4);return t*4294967296+e}var qs=-1,fs=4294967296-1,Cs=17179869184-1;function Gs({sec:n,nsec:A}){if(n>=0&&A>=0&&n<=Cs)if(A===0&&n<=fs){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{let t=n/4294967296,e=n&4294967295,i=new Uint8Array(8),d=new DataView(i.buffer);return d.setUint32(0,A<<2|t&3),d.setUint32(4,e),i}else{let t=new Uint8Array(12),e=new DataView(t.buffer);return e.setUint32(0,A),DA(e,4,n),t}}function ps(n){let A=n.getTime(),t=Math.floor(A/1e3),e=(A-t*1e3)*1e6,i=Math.floor(e/1e9);return{sec:t+i,nsec:e-i*1e9}}function hs(n){if(n instanceof Date){let A=ps(n);return Gs(A)}else return null}function Is(n){let A=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:A.getUint32(0),nsec:0};case 8:{let t=A.getUint32(0),e=A.getUint32(4),i=(t&3)*4294967296+e,d=t>>>2;return{sec:i,nsec:d}}case 12:{let t=BA(A,4),e=A.getUint32(0);return{sec:t,nsec:e}}default:throw new L(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${n.length}\`)}}function ms(n){let A=Is(n);return new Date(A.sec*1e3+A.nsec/1e6)}var ht={type:qs,encode:hs,decode:ms};var U=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(ht)}register({type:A,encode:t,decode:e}){if(A>=0)this.encoders[A]=t,this.decoders[A]=e;else{let i=-1-A;this.builtInEncoders[i]=t,this.builtInDecoders[i]=e}}tryToEncode(A,t){for(let e=0;e<this.builtInEncoders.length;e++){let i=this.builtInEncoders[e];if(i!=null){let d=i(A,t);if(d!=null){let q=-1-e;return new W(q,d)}}}for(let e=0;e<this.encoders.length;e++){let i=this.encoders[e];if(i!=null){let d=i(A,t);if(d!=null){let q=e;return new W(q,d)}}}return A instanceof W?A:null}decode(A,t,e){let i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(A,t,e):new W(t,A)}};U.defaultCodec=new U;function Es(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function uA(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):Es(n)?new Uint8Array(n):Uint8Array.from(n)}var $s=100,Fs=2048,NA=class n{constructor(A){this.entered=!1,this.extensionCodec=A?.extensionCodec??U.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??$s,this.initialBufferSize=A?.initialBufferSize??Fs,this.sortKeys=A?.sortKeys??!1,this.forceFloat32=A?.forceFloat32??!1,this.ignoreUndefined=A?.ignoreUndefined??!1,this.forceIntegerToFloat=A?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(A){if(this.entered)return this.clone().encodeSharedRef(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(A){if(this.entered)return this.clone().encode(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(A,t){if(t>this.maxDepth)throw new Error(\`Too deep objects in depth \${t}\`);A==null?this.encodeNil():typeof A=="boolean"?this.encodeBoolean(A):typeof A=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(A):this.encodeNumber(A):typeof A=="string"?this.encodeString(A):this.useBigInt64&&typeof A=="bigint"?this.encodeBigInt64(A):this.encodeObject(A,t)}ensureBufferSizeToWrite(A){let t=this.pos+A;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(A){let t=new ArrayBuffer(A),e=new Uint8Array(t),i=new DataView(t);e.set(this.bytes),this.view=i,this.bytes=e}encodeNil(){this.writeU8(192)}encodeBoolean(A){A===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(A){!this.forceIntegerToFloat&&Number.isSafeInteger(A)?A>=0?A<128?this.writeU8(A):A<256?(this.writeU8(204),this.writeU8(A)):A<65536?(this.writeU8(205),this.writeU16(A)):A<4294967296?(this.writeU8(206),this.writeU32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(207),this.writeU64(A)):A>=-32?this.writeU8(224|A+32):A>=-128?(this.writeU8(208),this.writeI8(A)):A>=-32768?(this.writeU8(209),this.writeI16(A)):A>=-2147483648?(this.writeU8(210),this.writeI32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(211),this.writeI64(A)):this.encodeNumberAsFloat(A)}encodeNumberAsFloat(A){this.forceFloat32?(this.writeU8(202),this.writeF32(A)):(this.writeU8(203),this.writeF64(A))}encodeBigInt64(A){A>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(A)):(this.writeU8(211),this.writeBigInt64(A))}writeStringHeader(A){if(A<32)this.writeU8(160+A);else if(A<256)this.writeU8(217),this.writeU8(A);else if(A<65536)this.writeU8(218),this.writeU16(A);else if(A<4294967296)this.writeU8(219),this.writeU32(A);else throw new Error(\`Too long string: \${A} bytes in UTF-8\`)}encodeString(A){let e=qt(A);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),ft(A,this.bytes,this.pos),this.pos+=e}encodeObject(A,t){let e=this.extensionCodec.tryToEncode(A,this.context);if(e!=null)this.encodeExtension(e);else if(Array.isArray(A))this.encodeArray(A,t);else if(ArrayBuffer.isView(A))this.encodeBinary(A);else if(typeof A=="object")this.encodeMap(A,t);else throw new Error(\`Unrecognized object: \${Object.prototype.toString.apply(A)}\`)}encodeBinary(A){let t=A.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(\`Too large binary: \${t}\`);let e=uA(A);this.writeU8a(e)}encodeArray(A,t){let e=A.length;if(e<16)this.writeU8(144+e);else if(e<65536)this.writeU8(220),this.writeU16(e);else if(e<4294967296)this.writeU8(221),this.writeU32(e);else throw new Error(\`Too large array: \${e}\`);for(let i of A)this.doEncode(i,t+1)}countWithoutUndefined(A,t){let e=0;for(let i of t)A[i]!==void 0&&e++;return e}encodeMap(A,t){let e=Object.keys(A);this.sortKeys&&e.sort();let i=this.ignoreUndefined?this.countWithoutUndefined(A,e):e.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(\`Too large map object: \${i}\`);for(let d of e){let q=A[d];this.ignoreUndefined&&q===void 0||(this.encodeString(d),this.doEncode(q,t+1))}}encodeExtension(A){if(typeof A.data=="function"){let e=A.data(this.pos+6),i=e.length;if(i>=4294967296)throw new Error(\`Too large extension object: \${i}\`);this.writeU8(201),this.writeU32(i),this.writeI8(A.type),this.writeU8a(e);return}let t=A.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(\`Too large extension object: \${t}\`);this.writeI8(A.type),this.writeU8a(A.data)}writeU8(A){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,A),this.pos++}writeU8a(A){let t=A.length;this.ensureBufferSizeToWrite(t),this.bytes.set(A,this.pos),this.pos+=t}writeI8(A){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,A),this.pos++}writeU16(A){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,A),this.pos+=2}writeI16(A){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,A),this.pos+=2}writeU32(A){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,A),this.pos+=4}writeI32(A){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,A),this.pos+=4}writeF32(A){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,A),this.pos+=4}writeF64(A){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,A),this.pos+=8}writeU64(A){this.ensureBufferSizeToWrite(8),Gt(this.view,this.pos,A),this.pos+=8}writeI64(A){this.ensureBufferSizeToWrite(8),DA(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(n,A){return new NA(A).encodeSharedRef(n)}function bA(n){return\`\${n<0?"-":""}0x\${Math.abs(n).toString(16).padStart(2,"0")}\`}var vs=16,gs=16,JA=class{constructor(A=vs,t=gs){this.hit=0,this.miss=0,this.maxKeyLength=A,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,t,e){let i=this.caches[e-1];A:for(let d of i){let q=d.bytes;for(let C=0;C<e;C++)if(q[C]!==A[t+C])continue A;return d.str}return null}store(A,t){let e=this.caches[A.length-1],i={bytes:A,str:t};e.length>=this.maxLengthPerKey?e[Math.random()*e.length|0]=i:e.push(i)}decode(A,t,e){let i=this.find(A,t,e);if(i!=null)return this.hit++,i;this.miss++;let d=Gr(A,t,e),q=Uint8Array.prototype.slice.call(A,t,t+e);return this.store(q,d),d}};var hr="array",qA="map_key",mt="map_value",Ls=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new L("The type of key must be string or number but "+typeof n)},Ir=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let t=this.getUninitializedStateFromPool();t.type=hr,t.position=0,t.size=A,t.array=new Array(A)}pushMapState(A){let t=this.getUninitializedStateFromPool();t.type=qA,t.readCount=0,t.size=A,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let A={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(A)}return this.stack[this.stackHeadPosition]}release(A){if(this.stack[this.stackHeadPosition]!==A)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(A.type===hr){let e=A;e.size=0,e.array=void 0,e.position=0,e.type=void 0}if(A.type===qA||A.type===mt){let e=A;e.size=0,e.map=void 0,e.readCount=0,e.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},dA=-1,mr=new DataView(new ArrayBuffer(0)),Hs=new Uint8Array(mr.buffer);try{mr.getInt8(0)}catch(n){if(!(n instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var It=new RangeError("Insufficient data"),_s=new JA,KA=class n{constructor(A){this.totalPos=0,this.pos=0,this.view=mr,this.bytes=Hs,this.headByte=dA,this.stack=new Ir,this.entered=!1,this.extensionCodec=A?.extensionCodec??U.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.rawStrings=A?.rawStrings??!1,this.maxStrLength=A?.maxStrLength??4294967295,this.maxBinLength=A?.maxBinLength??4294967295,this.maxArrayLength=A?.maxArrayLength??4294967295,this.maxMapLength=A?.maxMapLength??4294967295,this.maxExtLength=A?.maxExtLength??4294967295,this.keyDecoder=A?.keyDecoder!==void 0?A.keyDecoder:_s,this.mapKeyConverter=A?.mapKeyConverter??Ls}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=dA,this.stack.reset()}setBuffer(A){let t=uA(A);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(A){if(this.headByte===dA&&!this.hasRemaining(1))this.setBuffer(A);else{let t=this.bytes.subarray(this.pos),e=uA(A),i=new Uint8Array(t.length+e.length);i.set(t),i.set(e,t.length),this.setBuffer(i)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:t,pos:e}=this;return new RangeError(\`Extra \${t.byteLength-e} of \${t.byteLength} byte(s) found at buffer[\${A}]\`)}decode(A){if(this.entered)return this.clone().decode(A);try{this.entered=!0,this.reinitializeState(),this.setBuffer(A);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(A){if(this.entered){yield*this.clone().decodeMulti(A);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(A);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(A){if(this.entered)return this.clone().decodeAsync(A);try{this.entered=!0;let t=!1,e;for await(let C of A){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(C);try{e=this.doDecodeSync(),t=!0}catch(v){if(!(v instanceof RangeError))throw v}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return e}let{headByte:i,pos:d,totalPos:q}=this;throw new RangeError(\`Insufficient data in parsing \${bA(i)} at \${q} (\${d} in the current buffer)\`)}finally{this.entered=!1}}decodeArrayStream(A){return this.decodeMultiAsync(A,!0)}decodeStream(A){return this.decodeMultiAsync(A,!1)}async*decodeMultiAsync(A,t){if(this.entered){yield*this.clone().decodeMultiAsync(A,t);return}try{this.entered=!0;let e=t,i=-1;for await(let d of A){if(t&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(d),e&&(i=this.readArraySize(),e=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(q){if(!(q instanceof RangeError))throw q}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){A:for(;;){let A=this.readHeadByte(),t;if(A>=224)t=A-256;else if(A<192)if(A<128)t=A;else if(A<144){let i=A-128;if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A<160){let i=A-144;if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else{let i=A-160;t=this.decodeString(i,0)}else if(A===192)t=null;else if(A===194)t=!1;else if(A===195)t=!0;else if(A===202)t=this.readF32();else if(A===203)t=this.readF64();else if(A===204)t=this.readU8();else if(A===205)t=this.readU16();else if(A===206)t=this.readU32();else if(A===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(A===208)t=this.readI8();else if(A===209)t=this.readI16();else if(A===210)t=this.readI32();else if(A===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(A===217){let i=this.lookU8();t=this.decodeString(i,1)}else if(A===218){let i=this.lookU16();t=this.decodeString(i,2)}else if(A===219){let i=this.lookU32();t=this.decodeString(i,4)}else if(A===220){let i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===221){let i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue A}else t=[]}else if(A===222){let i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===223){let i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue A}else t={}}else if(A===196){let i=this.lookU8();t=this.decodeBinary(i,1)}else if(A===197){let i=this.lookU16();t=this.decodeBinary(i,2)}else if(A===198){let i=this.lookU32();t=this.decodeBinary(i,4)}else if(A===212)t=this.decodeExtension(1,0);else if(A===213)t=this.decodeExtension(2,0);else if(A===214)t=this.decodeExtension(4,0);else if(A===215)t=this.decodeExtension(8,0);else if(A===216)t=this.decodeExtension(16,0);else if(A===199){let i=this.lookU8();t=this.decodeExtension(i,1)}else if(A===200){let i=this.lookU16();t=this.decodeExtension(i,2)}else if(A===201){let i=this.lookU32();t=this.decodeExtension(i,4)}else throw new L(\`Unrecognized type byte: \${bA(A)}\`);this.complete();let e=this.stack;for(;e.length>0;){let i=e.top();if(i.type===hr)if(i.array[i.position]=t,i.position++,i.position===i.size)t=i.array,e.release(i);else continue A;else if(i.type===qA){if(t==="__proto__")throw new L("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,e.release(i);else{i.key=null,i.type=qA;continue A}}return t}}readHeadByte(){return this.headByte===dA&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=dA}readArraySize(){let A=this.readHeadByte();switch(A){case 220:return this.readU16();case 221:return this.readU32();default:{if(A<160)return A-144;throw new L(\`Unrecognized array type byte: \${bA(A)}\`)}}}pushMapState(A){if(A>this.maxMapLength)throw new L(\`Max length exceeded: map length (\${A}) > maxMapLengthLength (\${this.maxMapLength})\`);this.stack.pushMapState(A)}pushArrayState(A){if(A>this.maxArrayLength)throw new L(\`Max length exceeded: array length (\${A}) > maxArrayLength (\${this.maxArrayLength})\`);this.stack.pushArrayState(A)}decodeString(A,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(A,t):this.decodeBinary(A,t)}decodeUtf8String(A,t){if(A>this.maxStrLength)throw new L(\`Max length exceeded: UTF-8 byte length (\${A}) > maxStrLength (\${this.maxStrLength})\`);if(this.bytes.byteLength<this.pos+t+A)throw It;let e=this.pos+t,i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?i=this.keyDecoder.decode(this.bytes,e,A):i=Ct(this.bytes,e,A),this.pos+=t+A,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===qA:!1}decodeBinary(A,t){if(A>this.maxBinLength)throw new L(\`Max length exceeded: bin length (\${A}) > maxBinLength (\${this.maxBinLength})\`);if(!this.hasRemaining(A+t))throw It;let e=this.pos+t,i=this.bytes.subarray(e,e+A);return this.pos+=t+A,i}decodeExtension(A,t){if(A>this.maxExtLength)throw new L(\`Max length exceeded: ext length (\${A}) > maxExtLength (\${this.maxExtLength})\`);let e=this.view.getInt8(this.pos+t),i=this.decodeBinary(A,t+1);return this.extensionCodec.decode(i,e,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let A=this.view.getUint8(this.pos);return this.pos++,A}readI8(){let A=this.view.getInt8(this.pos);return this.pos++,A}readU16(){let A=this.view.getUint16(this.pos);return this.pos+=2,A}readI16(){let A=this.view.getInt16(this.pos);return this.pos+=2,A}readU32(){let A=this.view.getUint32(this.pos);return this.pos+=4,A}readI32(){let A=this.view.getInt32(this.pos);return this.pos+=4,A}readU64(){let A=pt(this.view,this.pos);return this.pos+=8,A}readI64(){let A=BA(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(n,A){return new KA(A).decode(n)}var fA=class n{constructor(A,t,e,i,d){this.mediaIds=A;this.sequenceNumber=t;this.timeStamp=e;this.isEndOfSpurt=i;this.payload=d}static parse(A){let t;try{t=Er(A)}catch{return D("not valid msgpack")}if(!Array.isArray(t))return D("container must be an array");if(t.length<6)return D("missing fields");if(t[0]!==1)return D("unknown type");if(!Array.isArray(t[1]))return D("media ids must be an array");if(!t[1].every(B=>typeof B=="number"))return D("media ids must be numbers");if(typeof t[2]!="number")return D("sequence number must be a number");if(typeof t[3]!="number")return D("timestamp must be a number");if(typeof t[4]!="number")return D("flags must be a number");let e=t[1],i=t[2]>>>0,d=t[3]>>>0,C=(t[4]&1)!==0,v=t[t.length-1];return v instanceof Uint8Array?et(new n(e,i,d,C,v)):D("payload must be bytes")}toBytes(){let A=Number(this.isEndOfSpurt),t=[1,this.mediaIds,this.sequenceNumber>>>0,this.timeStamp>>>0,A,this.payload];return new Uint8Array(pr(t,{forceFloat32:!0,ignoreUndefined:!0}))}};var OA=class{constructor(A,t){this.sampleRate=A;this.wasm=t;this.sequenceNumber=Math.random()*Math.pow(2,32)>>0;this.timestamp=Math.random()*Math.pow(2,32)>>0;this.connections=[];this.monitoring=!1;this.active=!1;this.stats={numberPackets:0,numberTicks:0,numberPacketError:0,numberPacketsMediaNotFound:0};this.encoder=new t.Encoder(A,15,!0,J.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=ct(this.wasm),this.outBuffer=T(this.wasm,"u8",1270),Zj(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(){dt(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){ot(\`failed encoding packet: \${t}\`);return}if(this.timestamp=this.timestamp+1800>>0,t===1)continue;this.sequenceNumber=this.sequenceNumber+1>>0;let e=this.active&&!this.encoder.active;this.active=this.encoder.active,this.monitoring=this.connections.some(i=>i.id===0);for(let i of this.connections){if(this.monitoring&&i.id!==0)continue;let d=new fA(i.mediaIds,this.sequenceNumber,this.timestamp,e,this.outBuffer.subarray(0,t));aA(globalThis,["sendPacket",{connectionId:i.id,packet:d.toBytes()}])}}}onMessage(A){let[t,e]=A;switch(t){case"captureSetVad":this?.setVad(e);break;case"captureSetMedias":this?.setMedias(e.connections);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){return{sequenceNumber:this.sequenceNumber,timestamp:this.timestamp,connections:this.connections.map(A=>\`\${A.id} => \${A.mediaIds.join(",")}\`),active:this.active,monitoring:this.monitoring,information:{active:Wj(this.information),speechProbability:Qj(this.information),rmsDBFS:zj(this.information),volume:Xj(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=T(this.wasm,"u32",J.MaxNumberOfDecoders),this.information=kt(this.wasm,J.MaxNumberOfDecoders),Oj(this.information,[1,1])}close(){ut(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,t){this.stats.numberPackets++;let e=fA.parse(t);if(e.type==="Failure"){this.stats.numberPacketError++;let i=Array.from(t).map(d=>d.toString(16).padStart(2,"0")).join("");console.error(\`failed decoding audio packet; reason: \${e.reason}, connection: \${A}, dump: \${i}\`);return}for(let i of e.value.mediaIds){let d=this.medias.get(xA({connectionId:A,mediaId:i}));if(d===void 0){this.stats.numberPacketsMediaNotFound++;continue}d.lastPacket=t;let q=T(this.wasm,"u8",e.value.payload.length);q.set(e.value.payload),d.decoder.push(e.value.sequenceNumber,e.value.timeStamp,e.value.isEndOfSpurt,q.byteOffset,q.length)}}insertMedia(A,t,e,i=[1,1]){let d=xA({connectionId:t,mediaId:e}),q=new this.wasm.Decoder;this.medias.set(d,{index:A,decoder:q,lastPacket:void 0}),this.decoders[A]=q.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),Tj(this.information,A,i),Rj(this.information,A,0),Sj(this.information,A,0)}removeMedia(A,t,e){let i=xA({connectionId:t,mediaId:e}),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,e]=A;switch(t){case"playbackReceivePacket":this.receivePacket(e.connectionId,e.packet);break;case"playbackUpdateMedias":for(let{index:i,connectionId:d,mediaId:q}of e.removed)this.removeMedia(i,d,q);for(let{index:i,connectionId:d,mediaId:q,volume:C}of e.added)this.insertMedia(i,d,q,C);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){let A=[];for(let[t,e]of this.medias){let i=at(t);A.push({index:e.index,connectionId:i.connectionId,mediaId:i.mediaId,rmsDBFS:Pj(this.information,e.index),volume:Mj(this.information,e.index),voicedBlocks:Vj(this.information,e.index),silentBlocks:Uj(this.information,e.index),time:e.decoder.time,consecutive_silence:e.decoder.consecutive_silence,last_voiced_time_point:e.decoder.last_voiced_time_point,sequence_number:e.decoder.sequence_number,packetsSeen:e.decoder.packets_seen,packetsInvalid:e.decoder.packets_invalid,packetsTooLate:e.decoder.packets_too_late,packetsTooEarly:e.decoder.packets_too_early,packetsRepeated:e.decoder.packets_repeated,packetsProcessed:e.decoder.packets_processed,packetsLost:e.decoder.packets_lost,rewinds:e.decoder.rewinds,cacheLength:e.decoder.cache_length,lastPacket:Yj(e.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:Kj(this.information),decoders:A}}};var Lt=Fn($t()),Ft=(0,Lt.default)(),vt,gt;globalThis.addEventListener("message",$r);async function $r(n){let A=n.data,[t,e]=A;switch(t){case"captureInit":e.workletPort.onmessage=$r,vt=new Fr(e.sampleRate,await Ft);break;case"playbackInit":e.workletPort.onmessage=$r,gt=new vr(await Ft);break;case"close":globalThis.close();break}vt?.onMessage(A),gt?.onMessage(A)}var Fr=class extends OA{constructor(t,e){super(t,e);this.id=-1;this.samples=fr(this.wasm,t,2+J.VadPreload+J.AdditionalCaptureBlocks,!1),aA(globalThis,["captureReady",{sampleBuffer:this.samples,informationBuffer:this.information}])}close(){super.close(),Cr(this.wasm,this.samples)}onMessage(t){super.onMessage(t);let[e,i]=t;e==="captureTick"&&this.tick(i.id)}tick(t){for(;this.id<t;this.id+=1)this.encode(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()}}},vr=class extends PA{constructor(A){super(A);let t=2+J.AdditionalPlaybackBlocks;this.sampleBuffer=fr(A,48e3,t,!0),this.sampleBuffer.samples.fill(0),this.prefill=t-2;for(let e=0;e<this.prefill;e++)ur(this.sampleBuffer,e,{id:e});this.id=this.prefill,aA(globalThis,["playbackReady",{sampleBuffer:this.sampleBuffer,informationBuffer:this.information}])}close(){super.close(),Cr(this.wasm,this.sampleBuffer)}onMessage(A){super.onMessage(A);let[t,e]=A;t==="playbackTick"&&this.tick(e.id)}tick(A){for(this.stats.numberTicks++;this.id<A+this.prefill;this.id++){let t=this.id%this.sampleBuffer.length,{hasAudio:e}=this.decode(kr(this.sampleBuffer,t));e&&(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()}}};})();
|
|
3236
|
+
`});var Qx,I0=q(()=>{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 g0={};Tx(g0,{createCaptureWorker:()=>rF,createPlaybackWorker:()=>tF});import{Strand as AF}from"@4players/odin-common";function rF(v,D,j,e,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,D,j,C,E,e)})}async function tF(v,D=i.DefaultRefreshRate){if(v.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[j,e]=await Y(Wx,Qx,v,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return zx.create(v,j,e)}var FF,zx,Xx,$0=q(()=>{"use strict";u();nx();G0();I0();FF=new AF;zx=class v extends z{constructor(j,e,B,C){super(j,e,B);this.information=C}static async create(j,e,B){let{port1:C,port2:E}=new MessageChannel;c(e,["playbackInit",{workletPort:C}],[C]);let{informationBuffer:f,sampleBuffer:s}=await U(e,"playbackReady");return Vx(f,[1,1]),c(B.port,["init",{sampleBuffer:s,workerPort:E}],[E]),new v(j,B,e,f)}getActivity(j){let e=this.medias.get(m(j));if(e===void 0)return;let B=E0(this.information,e.index);return B===0?_:{isSilent:!1,rmsDBFS:B}}getJitterStats(j){}setGlobalVolume(j){Vx(this.information,j)}setVolume(j,e){let B=this.medias.get(m(j));B!==void 0&&f0(this.information,B.index,e)}_GetFreeIndex(){let j=super._GetFreeIndex();if(j!==void 0)return j;if(this.information.length>this.medias.size)return this.medias.size}},Xx=class v extends X{constructor(j,e,B,C,E,f){super(j,e,B,C,f);this.information=E}static async create(j,e,B,C,E,f){let{port1:s,port2:b}=new MessageChannel;c(C,["captureInit",{sampleRate:j.sampleRate,workletPort:s}],[s]);let{sampleBuffer:d,informationBuffer:h}=await U(C,"captureReady");return c(E.port,["init",{workerPort:b,sampleBuffer:d}],[b]),new v(E,C,e,B,h,f)}get activity(){return{isSilent:!n0(this.information),rmsDBFS:i0(this.information)}}get speechProbability(){return s0(this.information)}setVolume(j){b0(this.information,j)}}});var Zx,y0=q(()=>{Zx=`"use strict";(()=>{var oe=Object.create;var WA=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var ue=Object.getPrototypeOf,ce=Object.prototype.hasOwnProperty;var de=(n,A)=>()=>(A||n((A={exports:{}}).exports,A),A.exports),qe=(n,A)=>{for(var t in A)WA(n,t,{get:A[t],enumerable:!0})},fe=(n,A,t,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let l of ke(A))!ce.call(n,l)&&l!==t&&WA(n,l,{get:()=>A[l],enumerable:!(e=ae(A,l))||e.enumerable});return n};var Ce=(n,A,t)=>(t=n!=null?oe(ue(n)):{},fe(A||!n||!n.__esModule?WA(t,"default",{value:n,enumerable:!0}):t,n));var Hj=de((Lj,JA)=>{"use strict";var er=(()=>{var n=globalThis.document?.currentScript?.src;return async function(A={}){var t,e=A,l=!!globalThis.window,d=!!globalThis.WorkerGlobalScope,q=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",p=[],F="./this.program";d&&(n=self.location.href);var D="",KA,O;if(l||d){try{D=new URL(".",n).href}catch{}d&&(O=j=>{var r=new XMLHttpRequest;return r.open("GET",j,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),KA=async j=>{var r=await fetch(j,{credentials:"same-origin"});if(r.ok)return r.arrayBuffer();throw new Error(r.status+" : "+r.url)}}var ir=console.log.bind(console),oA=console.error.bind(console),or,ar=!1;function Nj(j){for(var r=0,s=j.length,i=new Uint8Array(s),o;r<s;++r)o=j.charCodeAt(r),i[r]=~o>>8&o;return i}var kr,ur,cr=!1;function Bj(){var j=Ur.buffer;U=new Int8Array(j),aA=new Int16Array(j),e.HEAPU8=_=new Uint8Array(j),Z=new Uint16Array(j),e.HEAP32=kA=new Int32Array(j),e.HEAPU32=m=new Uint32Array(j),e.HEAPF32=fr=new Float32Array(j),Cr=new Float64Array(j),qr=new BigInt64Array(j),Gr=new BigUint64Array(j)}function bj(){if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)Sj(e.preRun.shift());pr(hr)}function Jj(){cr=!0,rA.v()}function Kj(){if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)Vj(e.postRun.shift());pr(Ir)}function OA(j){e.onAbort?.(j),j="Aborted("+j+")",oA(j),ar=!0,j+=". Build with -sASSERTIONS for more info.";var r=new WebAssembly.RuntimeError(j);throw ur?.(r),r}var dr;function Oj(){return Nj(\`\\0asm\\0\\0\\0\\x8D9\\\`\\x7F\\x7F\\\`\\x7F\\0\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\0\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`||\\\`\\x7F}\\\`}}\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F~\\\`\\x7F\\x7F}\\\`\\x7F}}\\\`\\x7F\\x7F}}\\0\\\`
|
|
3237
3237
|
\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`|}\\\`|\\x7F|\\\`\\x7F\\x7F}\\0\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\` \\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\f\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F|\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F|}\\\`\\0\\x7F\\\`\\x7F\\x7F\\x7F~~\\0\\\`\\r\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F\\x7F\\x7F\\\`\\x7F\\x7F|\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\x7F\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F}}\\x7F\\x7F\\x7F\\x7F\\0\\\`~\\x7F\\x7F\\\` \\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\\`||\\x7F|\\\`|||\\\`\\x7F\\x7F\\x7F|\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\\`\\f\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`}\\x7F\\x7F\\\`|\\x7F\\x7F\\\`\\x7F\\x7F\\x7F}\\\`\\x7F}\\x7F\\0\\\`\\x7F\\x7F}\\x7F\\x7F\\x7F}\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F}}\\0yaa\\0ab\\0ac\\0ad\\0ae\\0af\\0!ag\\0ah\\0 ai\\0aj\\0\\bak\\0"al\\0am\\0an\\0ao\\0\\0ap\\0#aq\\0\\0ar\\0
|
|
3238
3238
|
as\\0at\\0\\xBB\\xB9\\0\\0\\f$\\f\\x07\\0\\f\\x07\\f\\x07\\0%& \\0
|
|
3239
3239
|
\\0\\x07\\v\\0'\\0\\0(\\0\\f\\0)*+\\x07\\v\\x07\\0
|
|
@@ -6422,7 +6422,7 @@ K\\xE08\\xDF\\0}\\xBC\\x8A\\x1B\\f\\xE5\\xFF\\xCF\\xE8?\\x9F\\xFFFq\\0\\x88\\xB
|
|
|
6422
6422
|
|
|
6423
6423
|
|
|
6424
6424
|
\\x07\\0\\0 \\v\\0\\0 \\v\\0\\0\\v\\0\\0\\0\\0\\0A\\xC1\\x9D\\v!\\0\\0\\0\\0\\0\\0\\0\\0\\0\\v\\r\\0\\r\\0\\0\\0 \\0\\0\\0 \\0\\0\\0\\0A\\xFB\\x9D\\v\\f\\0A\\x87\\x9E\\v\\0\\0\\0\\0\\0\\0\\0\\0 \\f\\0\\0\\0\\0\\0\\f\\0\\0\\f\\0A\\xB5\\x9E\\v\\0A\\xC1\\x9E\\v\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0A\\xEF\\x9E\\v\\0A\\xFB\\x9E\\v\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0A\\xB2\\x9F\\v\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0A\\xE3\\x9F\\v\\0A\\xEF\\x9F\\v\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0A\\x9D\\xA0\\v\\0A\\xA9\\xA0\\v\\xB3 \\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\x000123456789ABCDEF\\0\\0X\\0NSt3__214__shared_countE\\0\\0\\0\\0\\x84\\0\\x8C\\0\\0\\0\\0\\0\\0\\0\\0P\\0\\0\\0\\0\\0NSt3__219__shared_weak_countE\\0\\0\\0(\\0\\xB8\\0\\xC8\\0N10__cxxabiv116__shim_type_infoE\\0\\0\\0\\0(\\0\\xE8\\0\\xAC\\0N10__cxxabiv117__class_type_infoE\\0\\0\\0(\\0\\0\\xAC\\0N10__cxxabiv117__pbase_type_infoE\\0\\0\\0(\\0H\\0\\f\\0N10__cxxabiv119__pointer_type_infoE\\0(\\0x\\0\\xAC\\0N10__cxxabiv120__function_type_infoE\\0\\0\\0\\0(\\0\\xAC\\0\\f\\0N10__cxxabiv129__pointer_to_member_type_infoE\\0\\0\\0\\0\\0\\0\\0\\xF8\\0\\\`\\0\\0\\0a\\0\\0\\0b\\0\\0\\0c\\0\\0\\0d\\0\\0\\0(\\0\\0\\xAC\\0N10__cxxabiv123__fundamental_type_infoE\\0\\xE4\\x004\\0v\\0Dn\\0\\0\\0\\0\\xE4\\0D\\0b\\0\\0\\0\\xE4\\0P\\0c\\0\\0\\0\\xE4\\0\\\\\\0h\\0\\0\\0\\xE4\\0h\\0a\\0\\0\\0\\xE4\\0t\\0s\\0\\0\\0\\xE4\\0\\x80\\0t\\0\\0\\0\\xE4\\0\\x8C\\0i\\0\\0\\0\\xE4\\0\\x98\\0j\\0\\0\\0\\xE4\\0\\xA4\\0l\\0\\0\\0\\xE4\\0\\xB0\\0m\\0\\0\\0\\xE4\\0\\xBC\\0x\\0\\0\\0\\xE4\\0\\xC8\\0y\\0\\0\\0\\xE4\\0\\xD4\\0f\\0\\0\\0\\xE0\\0\\xE8\\0\\0\\0\\0\\0\\xCC\\0Pf\\0\\0\\xE4\\0\\xF4\\0d\\0\\0\\0\\0\\0\\0\\0\\xDC\\0\\\`\\0\\0\\0e\\0\\0\\0b\\0\\0\\0c\\0\\0\\0f\\0\\0\\0g\\0\\0\\0h\\0\\0\\0i\\0\\0\\0\\0\\0\\0\\0H\\0\\\`\\0\\0\\0j\\0\\0\\0b\\0\\0\\0c\\0\\0\\0f\\0\\0\\0k\\0\\0\\0l\\0\\0\\0m\\0\\0\\0(\\0T\\0\\xDC\\0N10__cxxabiv120__si_class_type_infoE\\0\\0\\0\\0\\0\\0\\0\\0\\xA4\\0\\\`\\0\\0\\0n\\0\\0\\0b\\0\\0\\0c\\0\\0\\0f\\0\\0\\0o\\0\\0\\0p\\0\\0\\0q\\0\\0\\0(\\0\\xB0\\0\\xDC\\0N10__cxxabiv121__vmi_class_type_infoE\\0\\0\\0\\0\\0\\0\\0<\\0\\\`\\0\\0\\0r\\0\\0\\0b\\0\\0\\0c\\0\\0\\0s\\0\\0\\0\\0\\0\\0\\0<\\0F\\0\\0\\0t\\0\\0\\0u\\0\\0\\0\\0\\0\\0St9exception\\0\\0\\0\\0(\\0,\\0\\b\\0St9bad_alloc\\0\\0\\0\\0(\\0H\\0 \\0St20bad_array_new_length\\0\\0\\0\\0\\0\\0\\0\\0x\\0H\\0\\0\\0v\\0\\0\\0w\\0\\0\\0(\\0\\x84\\0\\b\\0St11logic_error\\0\\0\\0\\0\\0\\xA8\\0H\\0\\0\\0x\\0\\0\\0w\\0\\0\\0(\\0\\xB4\\0x\\0St12length_error\\0\\0\\0\\0\\0\\0\\xD0\\0St9type_info\\0A\\xE0\\xA9\\v\\0A\\xEC\\xA9\\vX\\0A\\x84\\xAA\\v\\vY\\0\\0\\0Z\\0\\0\\0H\\0A\\x9C\\xAA\\v\\0A\\xAC\\xAA\\v\\b\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\0A\\xF0\\xAA\\v \\xE0\\0\\0\\0\\0\\0\\0A\\x84\\xAB\\v[\\0A\\x9C\\xAB\\vY\\0\\0\\0\\\\\\0\\0\\0X\\0\\0\\0A\\xB4\\xAB\\v\\0A\\xC4\\xAB\\v\\xFF\\xFF\\xFF\\xFF
|
|
6425
|
-
\\0A\\x88\\xAC\\v\\vx\\0x\\0\\x90\`)}function mn(j){return j}async function Pj(j){return j}async function wj(j,r){try{var s=await Pj(j),i=await WebAssembly.instantiate(s,r);return i}catch(o){oA(\`failed to asynchronously prepare wasm: \${o}\`),OA(o)}}async function Mj(j,r,s){return wj(r,s)}function Tj(){var j={a:se};return j}async function Uj(){function j(a,k){return rA=a.exports,ne(rA),Bj(),rA}function r(a){return j(a.instance)}var s=Tj();if(e.instantiateWasm)return new Promise((a,k)=>{e.instantiateWasm(s,(u,c)=>{a(j(u,c))})});dr??=Oj();var i=await Mj(or,dr,s),o=r(i);return o}class En{name="ExitStatus";constructor(r){this.message=\`Program terminated with exit(\${r})\`,this.status=r}}var aA,kA,qr,U,fr,Cr,Z,m,Gr,_,pr=j=>{for(;j.length>0;)j.shift()(e)},Ir=[],Vj=j=>Ir.push(j),hr=[],Sj=j=>hr.push(j),Rj=!0;class Wj{constructor(r){this.excPtr=r,this.ptr=r-24}set_type(r){m[this.ptr+4>>2]=r}get_type(){return m[this.ptr+4>>2]}set_destructor(r){m[this.ptr+8>>2]=r}get_destructor(){return m[this.ptr+8>>2]}set_caught(r){r=r?1:0,U[this.ptr+12]=r}get_caught(){return U[this.ptr+12]!=0}set_rethrown(r){r=r?1:0,U[this.ptr+13]=r}get_rethrown(){return U[this.ptr+13]!=0}init(r,s){this.set_adjusted_ptr(0),this.set_type(r),this.set_destructor(s)}set_adjusted_ptr(r){m[this.ptr+16>>2]=r}get_adjusted_ptr(){return m[this.ptr+16>>2]}}var mr=0,Qj=0,zj=(j,r,s)=>{var i=new Wj(j);throw i.init(r,s),mr=j,Qj++,mr},Xj=()=>OA(""),v=j=>{for(var r="";;){var s=_[j++];if(!s)return r;r+=String.fromCharCode(s)}},W={},Q={},uA={},Y=class extends Error{constructor(r){super(r),this.name="BindingError"}},G=j=>{throw new Y(j)};function Zj(j,r,s={}){var i=r.name;if(j||G(\`type "\${i}" must have a positive integer typeid pointer\`),Q.hasOwnProperty(j)){if(s.ignoreDuplicateRegistrations)return;G(\`Cannot register type '\${i}' twice\`)}if(Q[j]=r,delete uA[j],W.hasOwnProperty(j)){var o=W[j];delete W[j],o.forEach(a=>a())}}function N(j,r,s={}){return Zj(j,r,s)}var Er=(j,r,s)=>{switch(r){case 1:return s?i=>U[i]:i=>_[i];case 2:return s?i=>aA[i>>1]:i=>Z[i>>1];case 4:return s?i=>kA[i>>2]:i=>m[i>>2];case 8:return s?i=>qr[i>>3]:i=>Gr[i>>3];default:throw new TypeError(\`invalid integer width (\${r}): \${j}\`)}},Yj=(j,r,s,i,o)=>{r=v(r);let a=i===0n,k=u=>u;if(a){let u=s*8;k=c=>BigInt.asUintN(u,c),o=k(o)}N(j,{name:r,fromWireType:k,toWireType:(u,c)=>(typeof c=="number"&&(c=BigInt(c)),c),readValueFromPointer:Er(r,s,!a),destructorFunction:null})},At=(j,r,s,i)=>{r=v(r),N(j,{name:r,fromWireType:function(o){return!!o},toWireType:function(o,a){return a?s:i},readValueFromPointer:function(o){return this.fromWireType(_[o])},destructorFunction:null})},rt=j=>({count:j.count,deleteScheduled:j.deleteScheduled,preservePointerOnDelete:j.preservePointerOnDelete,ptr:j.ptr,ptrType:j.ptrType,smartPtr:j.smartPtr,smartPtrType:j.smartPtrType}),PA=j=>{function r(s){return s.$$.ptrType.registeredClass.name}G(r(j)+" instance already deleted")},wA=!1,$r=j=>{},jt=j=>{j.smartPtr?j.smartPtrType.rawDestructor(j.smartPtr):j.ptrType.registeredClass.rawDestructor(j.ptr)},Fr=j=>{j.count.value-=1;var r=j.count.value===0;r&&jt(j)},AA=j=>globalThis.FinalizationRegistry?(wA=new FinalizationRegistry(r=>{Fr(r.$$)}),AA=r=>{var s=r.$$,i=!!s.smartPtr;if(i){var o={$$:s};wA.register(r,o,r)}return r},$r=r=>wA.unregister(r),AA(j)):(AA=r=>r,j),cA=[],tt=()=>{for(;cA.length;){var j=cA.pop();j.$$.deleteScheduled=!1,j.delete()}},vr,et=()=>{let j=dA.prototype;Object.assign(j,{isAliasOf(s){if(!(this instanceof dA)||!(s instanceof dA))return!1;var i=this.$$.ptrType.registeredClass,o=this.$$.ptr;s.$$=s.$$;for(var a=s.$$.ptrType.registeredClass,k=s.$$.ptr;i.baseClass;)o=i.upcast(o),i=i.baseClass;for(;a.baseClass;)k=a.upcast(k),a=a.baseClass;return i===a&&o===k},clone(){if(this.$$.ptr||PA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var s=AA(Object.create(Object.getPrototypeOf(this),{$$:{value:rt(this.$$)}}));return s.$$.count.value+=1,s.$$.deleteScheduled=!1,s},delete(){this.$$.ptr||PA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),$r(this),Fr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||PA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),cA.push(this),cA.length===1&&vr&&vr(tt),this.$$.deleteScheduled=!0,this}});let r=Symbol.dispose;r&&(j[r]=j.delete)};function dA(){}var gr=(j,r)=>Object.defineProperty(r,"name",{value:j}),Lr={},Hr=(j,r,s)=>{if(j[r].overloadTable===void 0){var i=j[r];j[r]=function(...o){return j[r].overloadTable.hasOwnProperty(o.length)||G(\`Function '\${s}' called with an invalid number of arguments (\${o.length}) - expects one of (\${j[r].overloadTable})!\`),j[r].overloadTable[o.length].apply(this,o)},j[r].overloadTable=[],j[r].overloadTable[i.argCount]=i}},yr=(j,r,s)=>{e.hasOwnProperty(j)?((s===void 0||e[j].overloadTable!==void 0&&e[j].overloadTable[s]!==void 0)&&G(\`Cannot register public name '\${j}' twice\`),Hr(e,j,j),e[j].overloadTable.hasOwnProperty(s)&&G(\`Cannot register multiple overloads of a function with the same number of arguments (\${s})!\`),e[j].overloadTable[s]=r):(e[j]=r,e[j].argCount=s)},nt=48,st=57,lt=j=>{j=j.replace(/[^a-zA-Z0-9_]/g,"$");var r=j.charCodeAt(0);return r>=nt&&r<=st?\`_\${j}\`:j};function it(j,r,s,i,o,a,k,u){this.name=j,this.constructor=r,this.instancePrototype=s,this.rawDestructor=i,this.baseClass=o,this.getActualType=a,this.upcast=k,this.downcast=u,this.pureVirtualFunctions=[]}var qA=(j,r,s)=>{for(;r!==s;)r.upcast||G(\`Expected null or instance of \${s.name}, got an instance of \${r.name}\`),j=r.upcast(j),r=r.baseClass;return j},MA=j=>{if(j===null)return"null";var r=typeof j;return r==="object"||r==="array"||r==="function"?j.toString():""+j};function ot(j,r){if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;r.$$||G(\`Cannot pass "\${MA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`);var s=r.$$.ptrType.registeredClass,i=qA(r.$$.ptr,s,this.registeredClass);return i}function at(j,r){var s;if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),this.isSmartPointer?(s=this.rawConstructor(),j!==null&&j.push(this.rawDestructor,s),s):0;(!r||!r.$$)&&G(\`Cannot pass "\${MA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),!this.isConst&&r.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name} to parameter type \${this.name}\`);var i=r.$$.ptrType.registeredClass;if(s=qA(r.$$.ptr,i,this.registeredClass),this.isSmartPointer)switch(r.$$.smartPtr===void 0&&G("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:r.$$.smartPtrType===this?s=r.$$.smartPtr:G(\`Cannot convert argument of type \${r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name} to parameter type \${this.name}\`);break;case 1:s=r.$$.smartPtr;break;case 2:if(r.$$.smartPtrType===this)s=r.$$.smartPtr;else{var o=r.clone();s=this.rawShare(s,VA.toHandle(()=>o.delete())),j!==null&&j.push(this.rawDestructor,s)}break;default:G("Unsupported sharing policy")}return s}function kt(j,r){if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;r.$$||G(\`Cannot pass "\${MA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),r.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${r.$$.ptrType.name} to parameter type \${this.name}\`);var s=r.$$.ptrType.registeredClass,i=qA(r.$$.ptr,s,this.registeredClass);return i}function fA(j){return this.fromWireType(m[j>>2])}var _r=(j,r,s)=>{if(r===s)return j;if(s.baseClass===void 0)return null;var i=_r(j,r,s.baseClass);return i===null?null:s.downcast(i)},ut={},ct=(j,r)=>{for(r===void 0&&G("ptr should not be undefined");j.baseClass;)r=j.upcast(r),j=j.baseClass;return r},dt=(j,r)=>(r=ct(j,r),ut[r]),qt=class extends Error{constructor(r){super(r),this.name="InternalError"}},CA=j=>{throw new qt(j)},GA=(j,r)=>{(!r.ptrType||!r.ptr)&&CA("makeClassHandle requires ptr and ptrType");var s=!!r.smartPtrType,i=!!r.smartPtr;return s!==i&&CA("Both smartPtrType and smartPtr must be specified"),r.count={value:1},AA(Object.create(j,{$$:{value:r,writable:!0}}))};function ft(j){var r=this.getPointee(j);if(!r)return this.destructor(j),null;var s=dt(this.registeredClass,r);if(s!==void 0){if(s.$$.count.value===0)return s.$$.ptr=r,s.$$.smartPtr=j,s.clone();var i=s.clone();return this.destructor(j),i}function o(){return this.isSmartPointer?GA(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:r,smartPtrType:this,smartPtr:j}):GA(this.registeredClass.instancePrototype,{ptrType:this,ptr:j})}var a=this.registeredClass.getActualType(r),k=Lr[a];if(!k)return o.call(this);var u;this.isConst?u=k.constPointerType:u=k.pointerType;var c=_r(r,this.registeredClass,u.registeredClass);return c===null?o.call(this):this.isSmartPointer?GA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c,smartPtrType:this,smartPtr:j}):GA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c})}var Ct=()=>{Object.assign(pA.prototype,{getPointee(j){return this.rawGetPointee&&(j=this.rawGetPointee(j)),j},destructor(j){this.rawDestructor?.(j)},readValueFromPointer:fA,fromWireType:ft})};function pA(j,r,s,i,o,a,k,u,c,f,C){this.name=j,this.registeredClass=r,this.isReference=s,this.isConst=i,this.isSmartPointer=o,this.pointeeType=a,this.sharingPolicy=k,this.rawGetPointee=u,this.rawConstructor=c,this.rawShare=f,this.rawDestructor=C,!o&&r.baseClass===void 0?i?(this.toWireType=ot,this.destructorFunction=null):(this.toWireType=kt,this.destructorFunction=null):this.toWireType=at}var Dr=(j,r,s)=>{e.hasOwnProperty(j)||CA("Replacing nonexistent public symbol"),e[j].overloadTable!==void 0&&s!==void 0?e[j].overloadTable[s]=r:(e[j]=r,e[j].argCount=s)},xr=[],Gt=j=>{var r=xr[j];return r||(xr[j]=r=Vr.get(j)),r},B=(j,r,s=!1)=>{j=v(j);function i(){var a=Gt(r);return a}var o=i();return typeof o!="function"&&G(\`unknown function pointer with signature \${j}: \${r}\`),o};class pt extends Error{}var It=j=>{var r=Tr(j),s=v(r);return b(r),s},z=(j,r)=>{var s=[],i={};function o(a){if(!i[a]&&!Q[a]){if(uA[a]){uA[a].forEach(o);return}s.push(a),i[a]=!0}}throw r.forEach(o),new pt(\`\${j}: \`+s.map(It).join([", "]))},P=(j,r,s)=>{j.forEach(u=>uA[u]=r);function i(u){var c=s(u);c.length!==j.length&&CA("Mismatched type converter count");for(var f=0;f<j.length;++f)N(j[f],c[f])}var o=new Array(r.length),a=[],k=0;for(let[u,c]of r.entries())Q.hasOwnProperty(c)?o[u]=Q[c]:(a.push(c),W.hasOwnProperty(c)||(W[c]=[]),W[c].push(()=>{o[u]=Q[c],++k,k===a.length&&i(o)}));a.length===0&&i(o)},ht=(j,r,s,i,o,a,k,u,c,f,C,h,E)=>{C=v(C),a=B(o,a),u&&=B(k,u),f&&=B(c,f),E=B(h,E);var I=lt(C);yr(I,function(){z(\`Cannot construct \${C} due to unbound types\`,[i])}),P([j,r,s],i?[i]:[],$=>{$=$[0];var H,J;i?(H=$.registeredClass,J=H.instancePrototype):J=dA.prototype;var y=gr(C,function(...RA){if(Object.getPrototypeOf(this)!==jA)throw new Y(\`Use 'new' to construct \${C}\`);if(L.constructor_body===void 0)throw new Y(\`\${C} has no accessible constructor\`);var Wr=L.constructor_body[RA.length];if(Wr===void 0)throw new Y(\`Tried to invoke ctor of \${C} with invalid number of parameters (\${RA.length}) - expected (\${Object.keys(L.constructor_body).toString()}) parameters instead!\`);return Wr.apply(this,RA)}),jA=Object.create(J,{constructor:{value:y}});y.prototype=jA;var L=new it(C,y,jA,E,H,a,u,f);L.baseClass&&(L.baseClass.__derivedClasses??=[],L.baseClass.__derivedClasses.push(L));var ie=new pA(C,L,!0,!1,!1),Sr=new pA(C+"*",L,!1,!1,!1),Rr=new pA(C+" const*",L,!1,!0,!1);return Lr[j]={pointerType:Sr,constPointerType:Rr},Dr(I,y),[ie,Sr,Rr]})},TA=(j,r)=>{for(var s=[],i=0;i<j;i++)s.push(m[r+i*4>>2]);return s},Nr=j=>{for(;j.length;){var r=j.pop(),s=j.pop();s(r)}};function Br(j){for(var r=1;r<j.length;++r)if(j[r]!==null&&j[r].destructorFunction===void 0)return!0;return!1}function mt(j,r,s,i){var o=Br(j),a=j.length-2,k=[],u=["fn"];r&&u.push("thisWired");for(var c=0;c<a;++c)k.push(\`arg\${c}\`),u.push(\`arg\${c}Wired\`);k=k.join(","),u=u.join(",");var f=\`return function (\${k}) {
|
|
6425
|
+
\\0A\\x88\\xAC\\v\\vx\\0x\\0\\x90\`)}function $n(j){return j}async function Pj(j){return j}async function wj(j,r){try{var s=await Pj(j),i=await WebAssembly.instantiate(s,r);return i}catch(o){oA(\`failed to asynchronously prepare wasm: \${o}\`),OA(o)}}async function Mj(j,r,s){return wj(r,s)}function Tj(){var j={a:se};return j}async function Uj(){function j(a,k){return rA=a.exports,ne(rA),Bj(),rA}function r(a){return j(a.instance)}var s=Tj();if(e.instantiateWasm)return new Promise((a,k)=>{e.instantiateWasm(s,(u,c)=>{a(j(u,c))})});dr??=Oj();var i=await Mj(or,dr,s),o=r(i);return o}class Fn{name="ExitStatus";constructor(r){this.message=\`Program terminated with exit(\${r})\`,this.status=r}}var aA,kA,qr,U,fr,Cr,Z,m,Gr,_,pr=j=>{for(;j.length>0;)j.shift()(e)},Ir=[],Vj=j=>Ir.push(j),hr=[],Sj=j=>hr.push(j),Rj=!0;class Wj{constructor(r){this.excPtr=r,this.ptr=r-24}set_type(r){m[this.ptr+4>>2]=r}get_type(){return m[this.ptr+4>>2]}set_destructor(r){m[this.ptr+8>>2]=r}get_destructor(){return m[this.ptr+8>>2]}set_caught(r){r=r?1:0,U[this.ptr+12]=r}get_caught(){return U[this.ptr+12]!=0}set_rethrown(r){r=r?1:0,U[this.ptr+13]=r}get_rethrown(){return U[this.ptr+13]!=0}init(r,s){this.set_adjusted_ptr(0),this.set_type(r),this.set_destructor(s)}set_adjusted_ptr(r){m[this.ptr+16>>2]=r}get_adjusted_ptr(){return m[this.ptr+16>>2]}}var mr=0,Qj=0,zj=(j,r,s)=>{var i=new Wj(j);throw i.init(r,s),mr=j,Qj++,mr},Xj=()=>OA(""),v=j=>{for(var r="";;){var s=_[j++];if(!s)return r;r+=String.fromCharCode(s)}},W={},Q={},uA={},Y=class extends Error{constructor(r){super(r),this.name="BindingError"}},G=j=>{throw new Y(j)};function Zj(j,r,s={}){var i=r.name;if(j||G(\`type "\${i}" must have a positive integer typeid pointer\`),Q.hasOwnProperty(j)){if(s.ignoreDuplicateRegistrations)return;G(\`Cannot register type '\${i}' twice\`)}if(Q[j]=r,delete uA[j],W.hasOwnProperty(j)){var o=W[j];delete W[j],o.forEach(a=>a())}}function N(j,r,s={}){return Zj(j,r,s)}var Er=(j,r,s)=>{switch(r){case 1:return s?i=>U[i]:i=>_[i];case 2:return s?i=>aA[i>>1]:i=>Z[i>>1];case 4:return s?i=>kA[i>>2]:i=>m[i>>2];case 8:return s?i=>qr[i>>3]:i=>Gr[i>>3];default:throw new TypeError(\`invalid integer width (\${r}): \${j}\`)}},Yj=(j,r,s,i,o)=>{r=v(r);let a=i===0n,k=u=>u;if(a){let u=s*8;k=c=>BigInt.asUintN(u,c),o=k(o)}N(j,{name:r,fromWireType:k,toWireType:(u,c)=>(typeof c=="number"&&(c=BigInt(c)),c),readValueFromPointer:Er(r,s,!a),destructorFunction:null})},At=(j,r,s,i)=>{r=v(r),N(j,{name:r,fromWireType:function(o){return!!o},toWireType:function(o,a){return a?s:i},readValueFromPointer:function(o){return this.fromWireType(_[o])},destructorFunction:null})},rt=j=>({count:j.count,deleteScheduled:j.deleteScheduled,preservePointerOnDelete:j.preservePointerOnDelete,ptr:j.ptr,ptrType:j.ptrType,smartPtr:j.smartPtr,smartPtrType:j.smartPtrType}),PA=j=>{function r(s){return s.$$.ptrType.registeredClass.name}G(r(j)+" instance already deleted")},wA=!1,$r=j=>{},jt=j=>{j.smartPtr?j.smartPtrType.rawDestructor(j.smartPtr):j.ptrType.registeredClass.rawDestructor(j.ptr)},Fr=j=>{j.count.value-=1;var r=j.count.value===0;r&&jt(j)},AA=j=>globalThis.FinalizationRegistry?(wA=new FinalizationRegistry(r=>{Fr(r.$$)}),AA=r=>{var s=r.$$,i=!!s.smartPtr;if(i){var o={$$:s};wA.register(r,o,r)}return r},$r=r=>wA.unregister(r),AA(j)):(AA=r=>r,j),cA=[],tt=()=>{for(;cA.length;){var j=cA.pop();j.$$.deleteScheduled=!1,j.delete()}},vr,et=()=>{let j=dA.prototype;Object.assign(j,{isAliasOf(s){if(!(this instanceof dA)||!(s instanceof dA))return!1;var i=this.$$.ptrType.registeredClass,o=this.$$.ptr;s.$$=s.$$;for(var a=s.$$.ptrType.registeredClass,k=s.$$.ptr;i.baseClass;)o=i.upcast(o),i=i.baseClass;for(;a.baseClass;)k=a.upcast(k),a=a.baseClass;return i===a&&o===k},clone(){if(this.$$.ptr||PA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var s=AA(Object.create(Object.getPrototypeOf(this),{$$:{value:rt(this.$$)}}));return s.$$.count.value+=1,s.$$.deleteScheduled=!1,s},delete(){this.$$.ptr||PA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),$r(this),Fr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||PA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&G("Object already scheduled for deletion"),cA.push(this),cA.length===1&&vr&&vr(tt),this.$$.deleteScheduled=!0,this}});let r=Symbol.dispose;r&&(j[r]=j.delete)};function dA(){}var gr=(j,r)=>Object.defineProperty(r,"name",{value:j}),Lr={},Hr=(j,r,s)=>{if(j[r].overloadTable===void 0){var i=j[r];j[r]=function(...o){return j[r].overloadTable.hasOwnProperty(o.length)||G(\`Function '\${s}' called with an invalid number of arguments (\${o.length}) - expects one of (\${j[r].overloadTable})!\`),j[r].overloadTable[o.length].apply(this,o)},j[r].overloadTable=[],j[r].overloadTable[i.argCount]=i}},yr=(j,r,s)=>{e.hasOwnProperty(j)?((s===void 0||e[j].overloadTable!==void 0&&e[j].overloadTable[s]!==void 0)&&G(\`Cannot register public name '\${j}' twice\`),Hr(e,j,j),e[j].overloadTable.hasOwnProperty(s)&&G(\`Cannot register multiple overloads of a function with the same number of arguments (\${s})!\`),e[j].overloadTable[s]=r):(e[j]=r,e[j].argCount=s)},nt=48,st=57,lt=j=>{j=j.replace(/[^a-zA-Z0-9_]/g,"$");var r=j.charCodeAt(0);return r>=nt&&r<=st?\`_\${j}\`:j};function it(j,r,s,i,o,a,k,u){this.name=j,this.constructor=r,this.instancePrototype=s,this.rawDestructor=i,this.baseClass=o,this.getActualType=a,this.upcast=k,this.downcast=u,this.pureVirtualFunctions=[]}var qA=(j,r,s)=>{for(;r!==s;)r.upcast||G(\`Expected null or instance of \${s.name}, got an instance of \${r.name}\`),j=r.upcast(j),r=r.baseClass;return j},MA=j=>{if(j===null)return"null";var r=typeof j;return r==="object"||r==="array"||r==="function"?j.toString():""+j};function ot(j,r){if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;r.$$||G(\`Cannot pass "\${MA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`);var s=r.$$.ptrType.registeredClass,i=qA(r.$$.ptr,s,this.registeredClass);return i}function at(j,r){var s;if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),this.isSmartPointer?(s=this.rawConstructor(),j!==null&&j.push(this.rawDestructor,s),s):0;(!r||!r.$$)&&G(\`Cannot pass "\${MA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),!this.isConst&&r.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name} to parameter type \${this.name}\`);var i=r.$$.ptrType.registeredClass;if(s=qA(r.$$.ptr,i,this.registeredClass),this.isSmartPointer)switch(r.$$.smartPtr===void 0&&G("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:r.$$.smartPtrType===this?s=r.$$.smartPtr:G(\`Cannot convert argument of type \${r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name} to parameter type \${this.name}\`);break;case 1:s=r.$$.smartPtr;break;case 2:if(r.$$.smartPtrType===this)s=r.$$.smartPtr;else{var o=r.clone();s=this.rawShare(s,VA.toHandle(()=>o.delete())),j!==null&&j.push(this.rawDestructor,s)}break;default:G("Unsupported sharing policy")}return s}function kt(j,r){if(r===null)return this.isReference&&G(\`null is not a valid \${this.name}\`),0;r.$$||G(\`Cannot pass "\${MA(r)}" as a \${this.name}\`),r.$$.ptr||G(\`Cannot pass deleted object as a pointer of type \${this.name}\`),r.$$.ptrType.isConst&&G(\`Cannot convert argument of type \${r.$$.ptrType.name} to parameter type \${this.name}\`);var s=r.$$.ptrType.registeredClass,i=qA(r.$$.ptr,s,this.registeredClass);return i}function fA(j){return this.fromWireType(m[j>>2])}var _r=(j,r,s)=>{if(r===s)return j;if(s.baseClass===void 0)return null;var i=_r(j,r,s.baseClass);return i===null?null:s.downcast(i)},ut={},ct=(j,r)=>{for(r===void 0&&G("ptr should not be undefined");j.baseClass;)r=j.upcast(r),j=j.baseClass;return r},dt=(j,r)=>(r=ct(j,r),ut[r]),qt=class extends Error{constructor(r){super(r),this.name="InternalError"}},CA=j=>{throw new qt(j)},GA=(j,r)=>{(!r.ptrType||!r.ptr)&&CA("makeClassHandle requires ptr and ptrType");var s=!!r.smartPtrType,i=!!r.smartPtr;return s!==i&&CA("Both smartPtrType and smartPtr must be specified"),r.count={value:1},AA(Object.create(j,{$$:{value:r,writable:!0}}))};function ft(j){var r=this.getPointee(j);if(!r)return this.destructor(j),null;var s=dt(this.registeredClass,r);if(s!==void 0){if(s.$$.count.value===0)return s.$$.ptr=r,s.$$.smartPtr=j,s.clone();var i=s.clone();return this.destructor(j),i}function o(){return this.isSmartPointer?GA(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:r,smartPtrType:this,smartPtr:j}):GA(this.registeredClass.instancePrototype,{ptrType:this,ptr:j})}var a=this.registeredClass.getActualType(r),k=Lr[a];if(!k)return o.call(this);var u;this.isConst?u=k.constPointerType:u=k.pointerType;var c=_r(r,this.registeredClass,u.registeredClass);return c===null?o.call(this):this.isSmartPointer?GA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c,smartPtrType:this,smartPtr:j}):GA(u.registeredClass.instancePrototype,{ptrType:u,ptr:c})}var Ct=()=>{Object.assign(pA.prototype,{getPointee(j){return this.rawGetPointee&&(j=this.rawGetPointee(j)),j},destructor(j){this.rawDestructor?.(j)},readValueFromPointer:fA,fromWireType:ft})};function pA(j,r,s,i,o,a,k,u,c,f,C){this.name=j,this.registeredClass=r,this.isReference=s,this.isConst=i,this.isSmartPointer=o,this.pointeeType=a,this.sharingPolicy=k,this.rawGetPointee=u,this.rawConstructor=c,this.rawShare=f,this.rawDestructor=C,!o&&r.baseClass===void 0?i?(this.toWireType=ot,this.destructorFunction=null):(this.toWireType=kt,this.destructorFunction=null):this.toWireType=at}var xr=(j,r,s)=>{e.hasOwnProperty(j)||CA("Replacing nonexistent public symbol"),e[j].overloadTable!==void 0&&s!==void 0?e[j].overloadTable[s]=r:(e[j]=r,e[j].argCount=s)},Dr=[],Gt=j=>{var r=Dr[j];return r||(Dr[j]=r=Vr.get(j)),r},B=(j,r,s=!1)=>{j=v(j);function i(){var a=Gt(r);return a}var o=i();return typeof o!="function"&&G(\`unknown function pointer with signature \${j}: \${r}\`),o};class pt extends Error{}var It=j=>{var r=Tr(j),s=v(r);return b(r),s},z=(j,r)=>{var s=[],i={};function o(a){if(!i[a]&&!Q[a]){if(uA[a]){uA[a].forEach(o);return}s.push(a),i[a]=!0}}throw r.forEach(o),new pt(\`\${j}: \`+s.map(It).join([", "]))},P=(j,r,s)=>{j.forEach(u=>uA[u]=r);function i(u){var c=s(u);c.length!==j.length&&CA("Mismatched type converter count");for(var f=0;f<j.length;++f)N(j[f],c[f])}var o=new Array(r.length),a=[],k=0;for(let[u,c]of r.entries())Q.hasOwnProperty(c)?o[u]=Q[c]:(a.push(c),W.hasOwnProperty(c)||(W[c]=[]),W[c].push(()=>{o[u]=Q[c],++k,k===a.length&&i(o)}));a.length===0&&i(o)},ht=(j,r,s,i,o,a,k,u,c,f,C,h,E)=>{C=v(C),a=B(o,a),u&&=B(k,u),f&&=B(c,f),E=B(h,E);var I=lt(C);yr(I,function(){z(\`Cannot construct \${C} due to unbound types\`,[i])}),P([j,r,s],i?[i]:[],$=>{$=$[0];var H,J;i?(H=$.registeredClass,J=H.instancePrototype):J=dA.prototype;var y=gr(C,function(...RA){if(Object.getPrototypeOf(this)!==jA)throw new Y(\`Use 'new' to construct \${C}\`);if(L.constructor_body===void 0)throw new Y(\`\${C} has no accessible constructor\`);var Wr=L.constructor_body[RA.length];if(Wr===void 0)throw new Y(\`Tried to invoke ctor of \${C} with invalid number of parameters (\${RA.length}) - expected (\${Object.keys(L.constructor_body).toString()}) parameters instead!\`);return Wr.apply(this,RA)}),jA=Object.create(J,{constructor:{value:y}});y.prototype=jA;var L=new it(C,y,jA,E,H,a,u,f);L.baseClass&&(L.baseClass.__derivedClasses??=[],L.baseClass.__derivedClasses.push(L));var ie=new pA(C,L,!0,!1,!1),Sr=new pA(C+"*",L,!1,!1,!1),Rr=new pA(C+" const*",L,!1,!0,!1);return Lr[j]={pointerType:Sr,constPointerType:Rr},xr(I,y),[ie,Sr,Rr]})},TA=(j,r)=>{for(var s=[],i=0;i<j;i++)s.push(m[r+i*4>>2]);return s},Nr=j=>{for(;j.length;){var r=j.pop(),s=j.pop();s(r)}};function Br(j){for(var r=1;r<j.length;++r)if(j[r]!==null&&j[r].destructorFunction===void 0)return!0;return!1}function mt(j,r,s,i){var o=Br(j),a=j.length-2,k=[],u=["fn"];r&&u.push("thisWired");for(var c=0;c<a;++c)k.push(\`arg\${c}\`),u.push(\`arg\${c}Wired\`);k=k.join(","),u=u.join(",");var f=\`return function (\${k}) {
|
|
6426
6426
|
\`;o&&(f+=\`var destructors = [];
|
|
6427
6427
|
\`);var C=o?"destructors":"null",h=["humanName","throwBindingError","invoker","fn","runDestructors","fromRetWire","toClassParamWire"];r&&(f+=\`var thisWired = toClassParamWire(\${C}, this);
|
|
6428
6428
|
\`);for(var c=0;c<a;++c){var E=\`toArg\${c}Wire\`;f+=\`var arg\${c}Wired = \${E}(\${C}, arg\${c});
|
|
@@ -6432,5 +6432,5 @@ K\\xE08\\xDF\\0}\\xBC\\x8A\\x1B\\f\\xE5\\xFF\\xCF\\xE8?\\x9F\\xFFFq\\0\\x88\\xB
|
|
|
6432
6432
|
\`,h.push(\`\${I}_dtor\`))}return s&&(f+=\`var ret = fromRetWire(rv);
|
|
6433
6433
|
return ret;
|
|
6434
6434
|
\`),f+=\`}
|
|
6435
|
-
\`,new Function(h,f)}function UA(j,r,s,i,o,a){var k=r.length;k<2&&G("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var u=r[1]!==null&&s!==null,c=Br(r),f=!r[0].isVoid,C=r[0],h=r[1],E=[j,G,i,o,Nr,C.fromWireType.bind(C),h?.toWireType.bind(h)],I=2;I<k;++I){var $=r[I];E.push($.toWireType.bind($))}if(!c)for(var I=u?1:2;I<r.length;++I)r[I].destructorFunction!==null&&E.push(r[I].destructorFunction);var J=mt(r,u,f,a)(...E);return gr(j,J)}var Et=(j,r,s,i,o,a)=>{var k=TA(r,s);o=B(i,o),P([],[j],u=>{u=u[0];var c=\`constructor \${u.name}\`;if(u.registeredClass.constructor_body===void 0&&(u.registeredClass.constructor_body=[]),u.registeredClass.constructor_body[r-1]!==void 0)throw new Y(\`Cannot register multiple constructors with identical number of parameters (\${r-1}) for class '\${u.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!\`);return u.registeredClass.constructor_body[r-1]=()=>{z(\`Cannot construct \${u.name} due to unbound types\`,k)},P([],k,f=>(f.splice(1,0,null),u.registeredClass.constructor_body[r-1]=UA(c,f,null,o,a),[])),[]})},br=j=>{j=j.trim();let r=j.indexOf("(");return r===-1?j:j.slice(0,r)},$t=(j,r,s,i,o,a,k,u,c,f)=>{var C=TA(s,i);r=v(r),r=br(r),a=B(o,a,c),P([],[j],h=>{h=h[0];var E=\`\${h.name}.\${r}\`;r.startsWith("@@")&&(r=Symbol[r.substring(2)]),u&&h.registeredClass.pureVirtualFunctions.push(r);function I(){z(\`Cannot call \${E} due to unbound types\`,C)}var $=h.registeredClass.instancePrototype,H=$[r];return H===void 0||H.overloadTable===void 0&&H.className!==h.name&&H.argCount===s-2?(I.argCount=s-2,I.className=h.name,$[r]=I):(Hr($,r,E),$[r].overloadTable[s-2]=I),P([],C,J=>{var y=UA(E,J,h,a,k,c);return $[r].overloadTable===void 0?(y.argCount=s-2,$[r]=y):$[r].overloadTable[s-2]=y,[]}),[]})},Jr=(j,r,s)=>(j instanceof Object||G(\`\${s} with invalid "this": \${j}\`),j instanceof r.registeredClass.constructor||G(\`\${s} incompatible with "this" of type \${j.constructor.name}\`),j.$$.ptr||G(\`cannot call emscripten binding method \${s} on deleted object\`),qA(j.$$.ptr,j.$$.ptrType.registeredClass,r.registeredClass)),Ft=(j,r,s,i,o,a,k,u,c,f)=>{r=v(r),o=B(i,o),P([],[j],C=>{C=C[0];var h=\`\${C.name}.\${r}\`,E={get(){z(\`Cannot access \${h} due to unbound types\`,[s,k])},enumerable:!0,configurable:!0};return c?E.set=()=>z(\`Cannot access \${h} due to unbound types\`,[s,k]):E.set=I=>G(h+" is a read-only property"),Object.defineProperty(C.registeredClass.instancePrototype,r,E),P([],c?[s,k]:[s],I=>{var $=I[0],H={get(){var y=Jr(this,C,h+" getter");return $.fromWireType(o(a,y))},enumerable:!0};if(c){c=B(u,c);var J=I[1];H.set=function(y){var jA=Jr(this,C,h+" setter"),L=[];c(f,jA,J.toWireType(L,y)),Nr(L)}}return Object.defineProperty(C.registeredClass.instancePrototype,r,H),[]}),[]})},Kr=[],X=[0,1,,1,null,1,!0,1,!1,1],vt=j=>{j>9&&--X[j+1]===0&&(X[j]=void 0,Kr.push(j))},VA={toValue:j=>(j||G(\`Cannot use deleted val. handle = \${j}\`),X[j]),toHandle:j=>{switch(j){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:{let r=Kr.pop()||X.length;return X[r]=j,X[r+1]=1,r}}}},gt={name:"emscripten::val",fromWireType:j=>{var r=VA.toValue(j);return vt(j),r},toWireType:(j,r)=>VA.toHandle(r),readValueFromPointer:fA,destructorFunction:null},Lt=j=>N(j,gt),Ht=(j,r)=>{switch(r){case 4:return function(s){return this.fromWireType(fr[s>>2])};case 8:return function(s){return this.fromWireType(Cr[s>>3])};default:throw new TypeError(\`invalid float width (\${r}): \${j}\`)}},yt=(j,r,s)=>{r=v(r),N(j,{name:r,fromWireType:i=>i,toWireType:(i,o)=>o,readValueFromPointer:Ht(r,s),destructorFunction:null})},_t=(j,r,s,i,o,a,k,u)=>{var c=TA(r,s);j=v(j),j=br(j),o=B(i,o,k),yr(j,function(){z(\`Cannot call \${j} due to unbound types\`,c)},r-1),P([],c,f=>{var C=[f[0],null].concat(f.slice(1));return Dr(j,UA(j,C,null,o,a,k),r-1),[]})},Dt=(j,r,s,i,o)=>{r=v(r);let a=i===0,k=c=>c;if(a){var u=32-8*s;k=c=>c<<u>>>u,o=k(o)}N(j,{name:r,fromWireType:k,toWireType:(c,f)=>f,readValueFromPointer:Er(r,s,i!==0),destructorFunction:null})},xt=(j,r,s)=>{var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=i[r];function a(k){var u=m[k>>2],c=m[k+4>>2];return new o(U.buffer,c,u)}s=v(s),N(j,{name:s,fromWireType:a,readValueFromPointer:a},{ignoreDuplicateRegistrations:!0})},Nt=(j,r,s,i)=>{if(!(i>0))return 0;for(var o=s,a=s+i-1,k=0;k<j.length;++k){var u=j.codePointAt(k);if(u<=127){if(s>=a)break;r[s++]=u}else if(u<=2047){if(s+1>=a)break;r[s++]=192|u>>6,r[s++]=128|u&63}else if(u<=65535){if(s+2>=a)break;r[s++]=224|u>>12,r[s++]=128|u>>6&63,r[s++]=128|u&63}else{if(s+3>=a)break;r[s++]=240|u>>18,r[s++]=128|u>>12&63,r[s++]=128|u>>6&63,r[s++]=128|u&63,k++}}return r[s]=0,s-o},Bt=(j,r,s)=>Nt(j,_,r,s),bt=j=>{for(var r=0,s=0;s<j.length;++s){var i=j.charCodeAt(s);i<=127?r++:i<=2047?r+=2:i>=55296&&i<=57343?(r+=4,++s):r+=3}return r},Or=globalThis.TextDecoder&&new TextDecoder,Pr=(j,r,s,i)=>{var o=r+s;if(i)return o;for(;j[r]&&!(r>=o);)++r;return r},wr=(j,r=0,s,i)=>{var o=Pr(j,r,s,i);if(o-r>16&&j.buffer&&Or)return Or.decode(j.subarray(r,o));for(var a="";r<o;){var k=j[r++];if(!(k&128)){a+=String.fromCharCode(k);continue}var u=j[r++]&63;if((k&224)==192){a+=String.fromCharCode((k&31)<<6|u);continue}var c=j[r++]&63;if((k&240)==224?k=(k&15)<<12|u<<6|c:k=(k&7)<<18|u<<12|c<<6|j[r++]&63,k<65536)a+=String.fromCharCode(k);else{var f=k-65536;a+=String.fromCharCode(55296|f>>10,56320|f&1023)}}return a},Jt=(j,r,s)=>j?wr(_,j,r,s):"",Kt=(j,r)=>{r=v(r);var s=!0;N(j,{name:r,fromWireType(i){var o=m[i>>2],a=i+4,k;if(s)k=Jt(a,o,!0);else{k="";for(var u=0;u<o;++u)k+=String.fromCharCode(_[a+u])}return b(i),k},toWireType(i,o){o instanceof ArrayBuffer&&(o=new Uint8Array(o));var a,k=typeof o=="string";k||ArrayBuffer.isView(o)&&o.BYTES_PER_ELEMENT==1||G("Cannot pass non-string to std::string"),s&&k?a=bt(o):a=o.length;var u=SA(4+a+1),c=u+4;if(m[u>>2]=a,k)if(s)Bt(o,c,a+1);else for(var f=0;f<a;++f){var C=o.charCodeAt(f);C>255&&(b(u),G("String has UTF-16 code units that do not fit in 8 bits")),_[c+f]=C}else _.set(o,c);return i!==null&&i.push(b,u),u},readValueFromPointer:fA,destructorFunction(i){b(i)}})},Mr=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Ot=(j,r,s)=>{var i=j>>1,o=Pr(Z,i,r/2,s);if(o-i>16&&Mr)return Mr.decode(Z.subarray(i,o));for(var a="",k=i;k<o;++k){var u=Z[k];a+=String.fromCharCode(u)}return a},Pt=(j,r,s)=>{if(s??=2147483647,s<2)return 0;s-=2;for(var i=r,o=s<j.length*2?s/2:j.length,a=0;a<o;++a){var k=j.charCodeAt(a);aA[r>>1]=k,r+=2}return aA[r>>1]=0,r-i},wt=j=>j.length*2,Mt=(j,r,s)=>{for(var i="",o=j>>2,a=0;!(a>=r/4);a++){var k=m[o+a];if(!k&&!s)break;i+=String.fromCodePoint(k)}return i},Tt=(j,r,s)=>{if(s??=2147483647,s<4)return 0;for(var i=r,o=i+s-4,a=0;a<j.length;++a){var k=j.codePointAt(a);if(k>65535&&a++,kA[r>>2]=k,r+=4,r+4>o)break}return kA[r>>2]=0,r-i},Ut=j=>{for(var r=0,s=0;s<j.length;++s){var i=j.codePointAt(s);i>65535&&s++,r+=4}return r},Vt=(j,r,s)=>{s=v(s);var i,o,a;r===2?(i=Ot,o=Pt,a=wt):(i=Mt,o=Tt,a=Ut),N(j,{name:s,fromWireType:k=>{var u=m[k>>2],c=i(k+4,u*r,!0);return b(k),c},toWireType:(k,u)=>{typeof u!="string"&&G(\`Cannot pass non-string to C++ string type \${s}\`);var c=a(u),f=SA(4+c+r);return m[f>>2]=c/r,o(u,f+4,c+r),k!==null&&k.push(b,f),f},readValueFromPointer:fA,destructorFunction(k){b(k)}})},St=(j,r)=>{r=v(r),N(j,{isVoid:!0,name:r,fromWireType:()=>{},toWireType:(s,i)=>{}})},Rt=j=>{OA("OOM")},Wt=j=>{var r=_.length;j>>>=0,Rt(j)},Qt=j=>52,zt=9007199254740992,Xt=-9007199254740992,Zt=j=>j<Xt||j>zt?NaN:Number(j);function Yt(j,r,s,i){return r=Zt(r),70}var Ae=[null,[],[]],re=(j,r)=>{var s=Ae[j];r===0||r===10?((j===1?ir:oA)(wr(s)),s.length=0):s.push(r)},je=(j,r,s,i)=>{for(var o=0,a=0;a<s;a++){var k=m[r>>2],u=m[r+4>>2];r+=8;for(var c=0;c<u;c++)re(j,_[k+c]);o+=u}return m[i>>2]=o,0};if(et(),Ct(),e.noExitRuntime&&(Rj=e.noExitRuntime),e.print&&(ir=e.print),e.printErr&&(oA=e.printErr),e.wasmBinary&&(or=e.wasmBinary),e.arguments&&(p=e.arguments),e.thisProgram&&(F=e.thisProgram),e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.shift()();var Tr,SA,b,te,ee,Ur,Vr;function ne(j){Tr=j.w,SA=e._malloc=j.y,b=e._free=j.z,te=Ur=j.u,ee=Vr=j.x}var se={g:zj,r:Xj,f:Yj,l:At,k:ht,j:Et,d:$t,a:Ft,s:Lt,i:yt,n:_t,c:Dt,b:xt,t:Kt,e:Vt,m:St,o:Wt,q:Qt,p:Yt,h:je};function le(){bj();function j(){e.calledRun=!0,!ar&&(Jj(),kr?.(e),e.onRuntimeInitialized?.(),Kj())}e.setStatus?(e.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>e.setStatus(""),1),j()},1)):j()}var rA;return rA=await Uj(),le(),cr?t=e:t=new Promise((j,r)=>{kr=j,ur=r}),t}})();typeof Lj=="object"&&typeof JA=="object"?(JA.exports=er,JA.exports.default=er):typeof define=="function"&&define.amd&&define([],()=>er)});var w={};qe(w,{AdditionalCaptureBlocks:()=>pe,AdditionalPlaybackBlocks:()=>Ge,ClockJumpCheckInterval:()=>ve,ClockJumpThreshold:()=>ge,ConnectInterval:()=>Be,ConnectTimeout:()=>De,DefaultRefreshRate:()=>he,DefaultVideoCodec:()=>be,HealthCheckTimeout:()=>Fe,MainConnectionPingInterval:()=>Le,MaxNumberOfDecoders:()=>Ee,MinDBFs:()=>Qr,MinTokenLifetime:()=>xe,MinTokenRefreshInterval:()=>Ne,PlaybackPreload:()=>Ie,RenderQuantumSize:()=>$e,VadPreload:()=>me,WebRtcIceTimeout:()=>ye,WebRtcStatsSnapshotInterval:()=>He,WebRtcTimeout:()=>_e});var Ge=3,pe=3,Ie=3,he=250,me=3,Ee=512,$e=128,Qr=-758.596,Fe=1e4,ve=1e3,ge=1e4,Le=3e3,He=1e3,ye=3e3,_e=1e4,De=5e3,xe=6e4,Ne=5e3,Be=[0,100,200,200,500],be="H264";function M(n,A,t){return n.postMessage(A,t)}function zr(n){return[n.values[0],n.values[1]]}function IA(n,A){n.values[0]=A[0],n.values[1]=A[1]}function hA(n,A){return n.values[2+A*5]}function Xr(n,A,t){n.values[2+A*5]=t}function Zr(n,A){let t=2+A*5+1;return[n.values[t+0],n.values[t+1]]}function mA(n,A,t){let e=2+A*5+1;n.values[e+0]=t[0],n.values[e+1]=t[1]}function Yr(n,A){return n.values[2+A*5+3]}function Aj(n,A,t){n.values[2+A*5+3]=t}function rj(n,A){return n.values[2+A*5+4]}function jj(n,A,t){n.values[2+A*5+4]=t}function EA(n){return n.values[0]!==0}function $A(n){return n.values[1]}function FA(n){return n.values[2]}function tj(n){return n.values[3]}function vA(n,A){return n.values[3]=A}function ej(n){return n?Array.from(n).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var Je;(n=>{let A;(t=>(t[t.InvalidPassword=-1]="InvalidPassword",t[t.Unknown=0]="Unknown",t[t.Unencrypted=1]="Unencrypted",t[t.Encrypted=2]="Encrypted"))(A=n.PeerCipherStatus||={})})(Je||={});function oj(n){return{type:"Success",value:n}}function D(n){return{type:"Failure",reason:n}}var{Deno:nj}=globalThis,Ke=typeof nj?.noColor=="boolean"?nj.noColor:!1,Oe=!Ke;function zA(n,A){return{open:\`\\x1B[\${n.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function XA(n,A){return Oe?\`\${A.open}\${n.replace(A.regexp,A.open)}\${A.close}\`:n}function QA(n){return XA(n,zA([0],0))}function sj(n){return XA(n,zA([1],22))}function Pe(n){return XA(n,zA([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"),we=new Date,gA=(n=>(n[n.CRITICAL=0]="CRITICAL",n[n.ERROR=1]="ERROR",n[n.WARN=2]="WARN",n[n.INFO=3]="INFO",n[n.DEBUG=4]="DEBUG",n))(gA||{}),aj={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},Me={4:Pe,3:QA,2:QA,1:sj,0:sj};function Te({message:n}){return String(n)}function lj(n){return JSON.stringify({timestamp:n.date.toISOString(),level:gA[n.level],message:n.message,extra:n.extra})}function ij(n){function A(q,p){return[Math.floor(q/p),q%p]}function t(){let q,p=n.date.valueOf()-we.valueOf();[p,q]=A(p,1e3);let[F,x]=A(p,60);return\`\${F.toString().padStart(4,"0")}:\${x.toString().padStart(2,"0")}.\${q.toString().padStart(3,"0")}\`}function e(){return n.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(n.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(n.extra)}let l=aj[n.level],d=n.logger.name!==void 0?\`@\${n.logger.name}\`:"";return\`\${QA(t())}\${d} \${l} \${Me[n.level](String(n.message))}\${e()}\`}function Ue(n){let A=\`[\${n.date.toISOString()}]\`,t=\`[\${gA[n.level]}]\`,e=n.logger.name!==void 0?\`[\${n.logger.name}] \`:"",l=aj[n.level];return\`\${A} \${l} \${t.padEnd(7," ")} \${e}\${n.message}\`}function Ve(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var kj=class{static sparse=Te;static json=lj;static pretty=ij;static structured=Ue;static default=Ve()?ij:lj;constructor(){}};var Se=class{formatter;consoleObject;filter;constructor(n=kj.default,A=4,t=console){this.filter=A,this.formatter=n,this.consoleObject=t}handle(n){let A=this.formatter(n);switch(n.level){case 0:case 1:this.consoleObject.error(A);break;case 2:this.consoleObject.warn(A);break;case 3:this.consoleObject.info(A);break;case 4:this.consoleObject.debug(A);break}}};var V=class{#A;sinks;filter;parent;get name(){return this.#A}constructor(n,A=void 0,t=[],e=void 0){this.#A=A,this.sinks=t,this.filter=n,this.parent=e}log(n,A,t=void 0){let e={date:new Date,level:n,logger:this,message:A,extra:t};this.filter<n||this.insert(e)}insert(n){if(!(this.filter<n.level)){for(let A of this.sinks)A.filter>=n.level&&A.handle(n);this.parent!==void 0&&this.parent.insert(n)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},tA=globalThis[Symbol.for("odin-global-logger")]??=new V(3,void 0,[new Se]),Re=V.prototype.log.bind(tA,1),We=V.prototype.log.bind(tA,2),uj=V.prototype.log.bind(tA,3),Qe=V.prototype.log.bind(tA,4),bn=V.prototype.log.bind(tA);var cj;function dj(n,...A){let t=ze(A);cj?cj?.info(n,t):uj(n,t)}function ze(...n){if(n.length===1&&typeof n[0]=="object"&&n[0]!==null)return{...n[0]};if(n.length>0)return{args:n}}function LA(n){return n.connectionId*4294967296+n.mediaId}function qj(n){return{mediaId:n%4294967296,connectionId:Math.floor(n/4294967296)}}function K(n,A,t){let e;switch(A){case"f32":e=n.HEAPF32;break;case"u32":e=n.HEAPU32;break;case"i32":e=n.HEAP32;break;case"u8":e=n.HEAPU8;break;default:throw new Error(\`allocating \${A} is not supported\`)}let l=n._malloc(t*e.BYTES_PER_ELEMENT);if(l===0||l%e.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${t} \${A} array\`);let d=l/e.BYTES_PER_ELEMENT;return e.subarray(d,d+t)}function S(n,A){n._free(A.byteOffset)}function fj(n,A){return{values:K(n,"f32",2+A*5),length:A}}function Cj(n,A){S(n,A.values)}function Gj(n){return{values:K(n,"f32",4)}}function pj(n,A){S(n,A.values)}function Ij(n){let A=n.length,t=0,e=0;for(;e<A;){let l=n.charCodeAt(e++);if((l&4294967168)===0){t++;continue}else if((l&4294965248)===0)t+=2;else{if(l>=55296&&l<=56319&&e<A){let d=n.charCodeAt(e);(d&64512)===56320&&(++e,l=((l&1023)<<10)+(d&1023)+65536)}(l&4294901760)===0?t+=3:t+=4}}return t}function Xe(n,A,t){let e=n.length,l=t,d=0;for(;d<e;){let q=n.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<e){let p=n.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,Ye=50;function An(n,A,t){Ze.encodeInto(n,A.subarray(t))}function hj(n,A,t){n.length>Ye?An(n,A,t):Xe(n,A,t)}var rn=4096;function ZA(n,A,t){let e=A,l=e+t,d=[],q="";for(;e<l;){let p=n[e++];if((p&128)===0)d.push(p);else if((p&224)===192){let F=n[e++]&63;d.push((p&31)<<6|F)}else if((p&240)===224){let F=n[e++]&63,x=n[e++]&63;d.push((p&31)<<12|F<<6|x)}else if((p&248)===240){let F=n[e++]&63,x=n[e++]&63,KA=n[e++]&63,O=(p&7)<<18|F<<12|x<<6|KA;O>65535&&(O-=65536,d.push(O>>>10&1023|55296),O=56320|O&1023),d.push(O)}else d.push(p);d.length>=rn&&(q+=String.fromCharCode(...d),d.length=0)}return d.length>0&&(q+=String.fromCharCode(...d)),q}var jn=new TextDecoder,tn=200;function en(n,A,t){let e=n.subarray(A,A+t);return jn.decode(e)}function mj(n,A,t){return t>tn?en(n,A,t):ZA(n,A,t)}var R=class{constructor(A,t){this.type=A,this.data=t}};var g=class n extends Error{constructor(A){super(A);let t=Object.create(n.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:n.name})}};function Ej(n,A,t){let e=t/4294967296,l=t;n.setUint32(A,e),n.setUint32(A+4,l)}function HA(n,A,t){let e=Math.floor(t/4294967296),l=t;n.setUint32(A,e),n.setUint32(A+4,l)}function yA(n,A){let t=n.getInt32(A),e=n.getUint32(A+4);return t*4294967296+e}function $j(n,A){let t=n.getUint32(A),e=n.getUint32(A+4);return t*4294967296+e}var nn=-1,sn=4294967296-1,ln=17179869184-1;function on({sec:n,nsec:A}){if(n>=0&&A>=0&&n<=ln)if(A===0&&n<=sn){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{let t=n/4294967296,e=n&4294967295,l=new Uint8Array(8),d=new DataView(l.buffer);return d.setUint32(0,A<<2|t&3),d.setUint32(4,e),l}else{let t=new Uint8Array(12),e=new DataView(t.buffer);return e.setUint32(0,A),HA(e,4,n),t}}function an(n){let A=n.getTime(),t=Math.floor(A/1e3),e=(A-t*1e3)*1e6,l=Math.floor(e/1e9);return{sec:t+l,nsec:e-l*1e9}}function kn(n){if(n instanceof Date){let A=an(n);return on(A)}else return null}function un(n){let A=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:A.getUint32(0),nsec:0};case 8:{let t=A.getUint32(0),e=A.getUint32(4),l=(t&3)*4294967296+e,d=t>>>2;return{sec:l,nsec:d}}case 12:{let t=yA(A,4),e=A.getUint32(0);return{sec:t,nsec:e}}default:throw new g(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${n.length}\`)}}function cn(n){let A=un(n);return new Date(A.sec*1e3+A.nsec/1e6)}var Fj={type:nn,encode:kn,decode:cn};var T=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Fj)}register({type:A,encode:t,decode:e}){if(A>=0)this.encoders[A]=t,this.decoders[A]=e;else{let l=-1-A;this.builtInEncoders[l]=t,this.builtInDecoders[l]=e}}tryToEncode(A,t){for(let e=0;e<this.builtInEncoders.length;e++){let l=this.builtInEncoders[e];if(l!=null){let d=l(A,t);if(d!=null){let q=-1-e;return new R(q,d)}}}for(let e=0;e<this.encoders.length;e++){let l=this.encoders[e];if(l!=null){let d=l(A,t);if(d!=null){let q=e;return new R(q,d)}}}return A instanceof R?A:null}decode(A,t,e){let l=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return l?l(A,t,e):new R(t,A)}};T.defaultCodec=new T;function dn(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function eA(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):dn(n)?new Uint8Array(n):Uint8Array.from(n)}var qn=100,fn=2048,_A=class n{constructor(A){this.entered=!1,this.extensionCodec=A?.extensionCodec??T.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??qn,this.initialBufferSize=A?.initialBufferSize??fn,this.sortKeys=A?.sortKeys??!1,this.forceFloat32=A?.forceFloat32??!1,this.ignoreUndefined=A?.ignoreUndefined??!1,this.forceIntegerToFloat=A?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(A){if(this.entered)return this.clone().encodeSharedRef(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(A){if(this.entered)return this.clone().encode(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(A,t){if(t>this.maxDepth)throw new Error(\`Too deep objects in depth \${t}\`);A==null?this.encodeNil():typeof A=="boolean"?this.encodeBoolean(A):typeof A=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(A):this.encodeNumber(A):typeof A=="string"?this.encodeString(A):this.useBigInt64&&typeof A=="bigint"?this.encodeBigInt64(A):this.encodeObject(A,t)}ensureBufferSizeToWrite(A){let t=this.pos+A;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(A){let t=new ArrayBuffer(A),e=new Uint8Array(t),l=new DataView(t);e.set(this.bytes),this.view=l,this.bytes=e}encodeNil(){this.writeU8(192)}encodeBoolean(A){A===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(A){!this.forceIntegerToFloat&&Number.isSafeInteger(A)?A>=0?A<128?this.writeU8(A):A<256?(this.writeU8(204),this.writeU8(A)):A<65536?(this.writeU8(205),this.writeU16(A)):A<4294967296?(this.writeU8(206),this.writeU32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(207),this.writeU64(A)):A>=-32?this.writeU8(224|A+32):A>=-128?(this.writeU8(208),this.writeI8(A)):A>=-32768?(this.writeU8(209),this.writeI16(A)):A>=-2147483648?(this.writeU8(210),this.writeI32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(211),this.writeI64(A)):this.encodeNumberAsFloat(A)}encodeNumberAsFloat(A){this.forceFloat32?(this.writeU8(202),this.writeF32(A)):(this.writeU8(203),this.writeF64(A))}encodeBigInt64(A){A>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(A)):(this.writeU8(211),this.writeBigInt64(A))}writeStringHeader(A){if(A<32)this.writeU8(160+A);else if(A<256)this.writeU8(217),this.writeU8(A);else if(A<65536)this.writeU8(218),this.writeU16(A);else if(A<4294967296)this.writeU8(219),this.writeU32(A);else throw new Error(\`Too long string: \${A} bytes in UTF-8\`)}encodeString(A){let e=Ij(A);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),hj(A,this.bytes,this.pos),this.pos+=e}encodeObject(A,t){let e=this.extensionCodec.tryToEncode(A,this.context);if(e!=null)this.encodeExtension(e);else if(Array.isArray(A))this.encodeArray(A,t);else if(ArrayBuffer.isView(A))this.encodeBinary(A);else if(typeof A=="object")this.encodeMap(A,t);else throw new Error(\`Unrecognized object: \${Object.prototype.toString.apply(A)}\`)}encodeBinary(A){let t=A.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(\`Too large binary: \${t}\`);let e=eA(A);this.writeU8a(e)}encodeArray(A,t){let e=A.length;if(e<16)this.writeU8(144+e);else if(e<65536)this.writeU8(220),this.writeU16(e);else if(e<4294967296)this.writeU8(221),this.writeU32(e);else throw new Error(\`Too large array: \${e}\`);for(let l of A)this.doEncode(l,t+1)}countWithoutUndefined(A,t){let e=0;for(let l of t)A[l]!==void 0&&e++;return e}encodeMap(A,t){let e=Object.keys(A);this.sortKeys&&e.sort();let l=this.ignoreUndefined?this.countWithoutUndefined(A,e):e.length;if(l<16)this.writeU8(128+l);else if(l<65536)this.writeU8(222),this.writeU16(l);else if(l<4294967296)this.writeU8(223),this.writeU32(l);else throw new Error(\`Too large map object: \${l}\`);for(let d of e){let q=A[d];this.ignoreUndefined&&q===void 0||(this.encodeString(d),this.doEncode(q,t+1))}}encodeExtension(A){if(typeof A.data=="function"){let e=A.data(this.pos+6),l=e.length;if(l>=4294967296)throw new Error(\`Too large extension object: \${l}\`);this.writeU8(201),this.writeU32(l),this.writeI8(A.type),this.writeU8a(e);return}let 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),Ej(this.view,this.pos,A),this.pos+=8}writeI64(A){this.ensureBufferSizeToWrite(8),HA(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 YA(n,A){return new _A(A).encodeSharedRef(n)}function DA(n){return\`\${n<0?"-":""}0x\${Math.abs(n).toString(16).padStart(2,"0")}\`}var Cn=16,Gn=16,xA=class{constructor(A=Cn,t=Gn){this.hit=0,this.miss=0,this.maxKeyLength=A,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,t,e){let l=this.caches[e-1];A:for(let d of l){let q=d.bytes;for(let p=0;p<e;p++)if(q[p]!==A[t+p])continue A;return d.str}return null}store(A,t){let e=this.caches[A.length-1],l={bytes:A,str:t};e.length>=this.maxLengthPerKey?e[Math.random()*e.length|0]=l:e.push(l)}decode(A,t,e){let l=this.find(A,t,e);if(l!=null)return this.hit++,l;this.miss++;let d=ZA(A,t,e),q=Uint8Array.prototype.slice.call(A,t,t+e);return this.store(q,d),d}};var Ar="array",lA="map_key",gj="map_value",pn=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new g("The type of key must be string or number but "+typeof n)},rr=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=Ar,t.position=0,t.size=A,t.array=new Array(A)}pushMapState(A){let t=this.getUninitializedStateFromPool();t.type=lA,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===Ar){let e=A;e.size=0,e.array=void 0,e.position=0,e.type=void 0}if(A.type===lA||A.type===gj){let e=A;e.size=0,e.map=void 0,e.readCount=0,e.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},sA=-1,jr=new DataView(new ArrayBuffer(0)),In=new Uint8Array(jr.buffer);try{jr.getInt8(0)}catch(n){if(!(n instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var vj=new RangeError("Insufficient data"),hn=new xA,NA=class n{constructor(A){this.totalPos=0,this.pos=0,this.view=jr,this.bytes=In,this.headByte=sA,this.stack=new rr,this.entered=!1,this.extensionCodec=A?.extensionCodec??T.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:hn,this.mapKeyConverter=A?.mapKeyConverter??pn}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=sA,this.stack.reset()}setBuffer(A){let t=eA(A);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(A){if(this.headByte===sA&&!this.hasRemaining(1))this.setBuffer(A);else{let t=this.bytes.subarray(this.pos),e=eA(A),l=new Uint8Array(t.length+e.length);l.set(t),l.set(e,t.length),this.setBuffer(l)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:t,pos:e}=this;return new RangeError(\`Extra \${t.byteLength-e} of \${t.byteLength} byte(s) found at buffer[\${A}]\`)}decode(A){if(this.entered)return this.clone().decode(A);try{this.entered=!0,this.reinitializeState(),this.setBuffer(A);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(A){if(this.entered){yield*this.clone().decodeMulti(A);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(A);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(A){if(this.entered)return this.clone().decodeAsync(A);try{this.entered=!0;let t=!1,e;for await(let p of A){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(p);try{e=this.doDecodeSync(),t=!0}catch(F){if(!(F instanceof RangeError))throw F}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return e}let{headByte:l,pos:d,totalPos:q}=this;throw new RangeError(\`Insufficient data in parsing \${DA(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,t){if(this.entered){yield*this.clone().decodeMultiAsync(A,t);return}try{this.entered=!0;let e=t,l=-1;for await(let d of A){if(t&&l===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(d),e&&(l=this.readArraySize(),e=!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(),t;if(A>=224)t=A-256;else if(A<192)if(A<128)t=A;else if(A<144){let l=A-128;if(l!==0){this.pushMapState(l),this.complete();continue A}else t={}}else if(A<160){let l=A-144;if(l!==0){this.pushArrayState(l),this.complete();continue A}else t=[]}else{let l=A-160;t=this.decodeString(l,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 l=this.lookU8();t=this.decodeString(l,1)}else if(A===218){let l=this.lookU16();t=this.decodeString(l,2)}else if(A===219){let l=this.lookU32();t=this.decodeString(l,4)}else if(A===220){let l=this.readU16();if(l!==0){this.pushArrayState(l),this.complete();continue A}else t=[]}else if(A===221){let l=this.readU32();if(l!==0){this.pushArrayState(l),this.complete();continue A}else t=[]}else if(A===222){let l=this.readU16();if(l!==0){this.pushMapState(l),this.complete();continue A}else t={}}else if(A===223){let l=this.readU32();if(l!==0){this.pushMapState(l),this.complete();continue A}else t={}}else if(A===196){let l=this.lookU8();t=this.decodeBinary(l,1)}else if(A===197){let l=this.lookU16();t=this.decodeBinary(l,2)}else if(A===198){let l=this.lookU32();t=this.decodeBinary(l,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 l=this.lookU8();t=this.decodeExtension(l,1)}else if(A===200){let l=this.lookU16();t=this.decodeExtension(l,2)}else if(A===201){let l=this.lookU32();t=this.decodeExtension(l,4)}else throw new g(\`Unrecognized type byte: \${DA(A)}\`);this.complete();let e=this.stack;for(;e.length>0;){let l=e.top();if(l.type===Ar)if(l.array[l.position]=t,l.position++,l.position===l.size)t=l.array,e.release(l);else continue A;else if(l.type===lA){if(t==="__proto__")throw new g("The key __proto__ is not allowed");l.key=this.mapKeyConverter(t),l.type=gj;continue A}else if(l.map[l.key]=t,l.readCount++,l.readCount===l.size)t=l.map,e.release(l);else{l.key=null,l.type=lA;continue A}}return t}}readHeadByte(){return this.headByte===sA&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=sA}readArraySize(){let A=this.readHeadByte();switch(A){case 220:return this.readU16();case 221:return this.readU32();default:{if(A<160)return A-144;throw new g(\`Unrecognized array type byte: \${DA(A)}\`)}}}pushMapState(A){if(A>this.maxMapLength)throw new g(\`Max length exceeded: map length (\${A}) > maxMapLengthLength (\${this.maxMapLength})\`);this.stack.pushMapState(A)}pushArrayState(A){if(A>this.maxArrayLength)throw new g(\`Max length exceeded: array length (\${A}) > maxArrayLength (\${this.maxArrayLength})\`);this.stack.pushArrayState(A)}decodeString(A,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(A,t):this.decodeBinary(A,t)}decodeUtf8String(A,t){if(A>this.maxStrLength)throw new g(\`Max length exceeded: UTF-8 byte length (\${A}) > maxStrLength (\${this.maxStrLength})\`);if(this.bytes.byteLength<this.pos+t+A)throw vj;let e=this.pos+t,l;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?l=this.keyDecoder.decode(this.bytes,e,A):l=mj(this.bytes,e,A),this.pos+=t+A,l}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===lA:!1}decodeBinary(A,t){if(A>this.maxBinLength)throw new g(\`Max length exceeded: bin length (\${A}) > maxBinLength (\${this.maxBinLength})\`);if(!this.hasRemaining(A+t))throw vj;let e=this.pos+t,l=this.bytes.subarray(e,e+A);return this.pos+=t+A,l}decodeExtension(A,t){if(A>this.maxExtLength)throw new g(\`Max length exceeded: ext length (\${A}) > maxExtLength (\${this.maxExtLength})\`);let e=this.view.getInt8(this.pos+t),l=this.decodeBinary(A,t+1);return this.extensionCodec.decode(l,e,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let A=this.view.getUint8(this.pos);return this.pos++,A}readI8(){let A=this.view.getInt8(this.pos);return this.pos++,A}readU16(){let A=this.view.getUint16(this.pos);return this.pos+=2,A}readI16(){let A=this.view.getInt16(this.pos);return this.pos+=2,A}readU32(){let A=this.view.getUint32(this.pos);return this.pos+=4,A}readI32(){let A=this.view.getInt32(this.pos);return this.pos+=4,A}readU64(){let A=$j(this.view,this.pos);return this.pos+=8,A}readI64(){let A=yA(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 tr(n,A){return new NA(A).decode(n)}var iA=class n{constructor(A,t,e,l,d){this.mediaIds=A;this.sequenceNumber=t;this.timeStamp=e;this.isEndOfSpurt=l;this.payload=d}static parse(A){let t;try{t=tr(A)}catch{return D("not valid msgpack")}if(!Array.isArray(t))return D("container must be an array");if(t.length<6)return D("missing fields");if(t[0]!==1)return D("unknown type");if(!Array.isArray(t[1]))return D("media ids must be an array");if(!t[1].every(x=>typeof x=="number"))return D("media ids must be numbers");if(typeof t[2]!="number")return D("sequence number must be a number");if(typeof t[3]!="number")return D("timestamp must be a number");if(typeof t[4]!="number")return D("flags must be a number");let e=t[1],l=t[2]>>>0,d=t[3]>>>0,p=(t[4]&1)!==0,F=t[t.length-1];return F instanceof Uint8Array?oj(new n(e,l,d,p,F)):D("payload must be bytes")}toBytes(){let A=Number(this.isEndOfSpurt),t=[1,this.mediaIds,this.sequenceNumber>>>0,this.timeStamp>>>0,A,this.payload];return new Uint8Array(YA(t,{forceFloat32:!0,ignoreUndefined:!0}))}};var BA=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,w.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=Gj(this.wasm),this.outBuffer=K(this.wasm,"u8",1270),vA(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(){pj(this.wasm,this.information),S(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){dj(\`failed encoding packet: \${t}\`);return}if(this.timestamp=this.timestamp+1800>>0,t===1)continue;this.sequenceNumber=this.sequenceNumber+1>>0;let e=this.active&&!this.encoder.active;this.active=this.encoder.active,this.monitoring=this.connections.some(l=>l.id===0);for(let l of this.connections){if(this.monitoring&&l.id!==0)continue;let d=new iA(l.mediaIds,this.sequenceNumber,this.timestamp,e,this.outBuffer.subarray(0,t));M(globalThis,["sendPacket",{connectionId:l.id,packet:d.toBytes()}])}}}onMessage(A){let[t,e]=A;switch(t){case"captureSetVad":this?.setVad(e);break;case"captureSetMedias":this?.setMedias(e.connections);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){return{sequenceNumber:this.sequenceNumber,timestamp:this.timestamp,connections:this.connections.map(A=>\`\${A.id} => \${A.mediaIds.join(",")}\`),active:this.active,monitoring:this.monitoring,information:{active:EA(this.information),speechProbability:$A(this.information),rmsDBFS:FA(this.information),volume:tj(this.information)},encoder:{sample_rate:this.encoder.sample_rate,fec_packet_loss:this.encoder.fec_packet_loss,voip:this.encoder.voip,vad_preload:this.encoder.vad_preload,complexity:this.encoder.complexity,speech_probability:this.encoder.speech_probability,rms_dbfs:this.encoder.rms_dbfs,active:this.encoder.active,speech_detection_enabled:this.encoder.speech_detection_enabled,speech_detection_going_active:this.encoder.speech_detection_going_active,speech_detection_going_inactive:this.encoder.speech_detection_going_inactive,volume_gate_enabled:this.encoder.volume_gate_enabled,volume_gate_going_active:this.encoder.volume_gate_going_active,volume_gate_going_inactive:this.encoder.volume_gate_going_inactive}}}},bA=class{constructor(A){this.wasm=A;this.medias=new Map;this.stats={numberPackets:0,numberTicks:0,numberPacketError:0,numberPacketsMediaNotFound:0,numberTicksWithAudio:0};this.largestIndex=-1;this.decoders=K(this.wasm,"u32",w.MaxNumberOfDecoders),this.information=fj(this.wasm,w.MaxNumberOfDecoders),IA(this.information,[1,1])}close(){Cj(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,t){this.stats.numberPackets++;let e=iA.parse(t);if(e.type==="Failure"){this.stats.numberPacketError++;let l=Array.from(t).map(d=>d.toString(16).padStart(2,"0")).join("");console.error(\`failed decoding audio packet; reason: \${e.reason}, connection: \${A}, dump: \${l}\`);return}for(let l of e.value.mediaIds){let d=this.medias.get(LA({connectionId:A,mediaId:l}));if(d===void 0){this.stats.numberPacketsMediaNotFound++;continue}d.lastPacket=t;let q=K(this.wasm,"u8",e.value.payload.length);q.set(e.value.payload),d.decoder.push(e.value.sequenceNumber,e.value.timeStamp,e.value.isEndOfSpurt,q.byteOffset,q.length)}}insertMedia(A,t,e,l=[1,1]){let d=LA({connectionId:t,mediaId:e}),q=new this.wasm.Decoder;this.medias.set(d,{index:A,decoder:q,lastPacket:void 0}),this.decoders[A]=q.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),mA(this.information,A,l),jj(this.information,A,0),Aj(this.information,A,0)}removeMedia(A,t,e){let l=LA({connectionId:t,mediaId:e}),d=this.medias.get(l);if(!(d===void 0||d.index!==A)&&(this.medias.delete(l),Xr(this.information,A,0),this.decoders[A]=0,d.decoder.delete(),A===this.largestIndex)){for(A=A-1;A>=0&&this.decoders[A]===0;A--);this.largestIndex=A}}decode(A){return{hasAudio:this.wasm.pop_many(this.decoders.byteOffset,this.information.values.byteOffset,this.largestIndex+1,A.byteOffset)}}onMessage(A){let[t,e]=A;switch(t){case"playbackReceivePacket":this.receivePacket(e.connectionId,e.packet);break;case"playbackUpdateMedias":for(let{index:l,connectionId:d,mediaId:q}of e.removed)this.removeMedia(l,d,q);for(let{index:l,connectionId:d,mediaId:q,volume:p}of e.added)this.insertMedia(l,d,q,p);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){let A=[];for(let[t,e]of this.medias){let l=qj(t);A.push({index:e.index,connectionId:l.connectionId,mediaId:l.mediaId,rmsDBFS:hA(this.information,e.index),volume:Zr(this.information,e.index),voicedBlocks:rj(this.information,e.index),silentBlocks:Yr(this.information,e.index),time:e.decoder.time,consecutive_silence:e.decoder.consecutive_silence,last_voiced_time_point:e.decoder.last_voiced_time_point,sequence_number:e.decoder.sequence_number,packetsSeen:e.decoder.packets_seen,packetsInvalid:e.decoder.packets_invalid,packetsTooLate:e.decoder.packets_too_late,packetsTooEarly:e.decoder.packets_too_early,packetsRepeated:e.decoder.packets_repeated,packetsProcessed:e.decoder.packets_processed,packetsLost:e.decoder.packets_lost,rewinds:e.decoder.rewinds,cacheLength:e.decoder.cache_length,lastPacket:ej(e.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:zr(this.information),decoders:A}}};var xj=Ce(Hj()),yj=(0,xj.default)(),_j,Dj;globalThis.addEventListener("message",nr);async function nr(n){let A=n.data,[t,e]=A;switch(t){case"captureInit":e.workletPort.onmessage=nr,_j=new sr(e.sampleRate,await yj,e.refreshRate);break;case"playbackInit":e.workletPort.onmessage=nr,Dj=new lr(await yj,e.workletPort,e.refreshRate);break;case"close":globalThis.close();break}_j?.onMessage(A),Dj?.onMessage(A)}var sr=class extends BA{constructor(t,e,l){super(t,e);this.sampleRate=t;this.inBuffer=K(this.wasm,"f32",t*.02),this.updateHandle=setInterval(()=>this.update(),l),M(globalThis,["captureReady",{}])}close(){super.close(),S(this.wasm,this.inBuffer),clearInterval(this.updateHandle)}onMessage(t){super.onMessage(t);let[e,l]=t;switch(e){case"captureSetVolume":this.setVolume(l.value);break;case"captureTick":this.tick(l.buffer);break}}setVolume(t){vA(this.information,t)}tick(t){this.inBuffer.set(t,0),this.encode(this.inBuffer)}update(){M(globalThis,["captureUpdate",{active:EA(this.information),rmsDBFs:FA(this.information),speechProbability:$A(this.information)}])}dump(){return{type:"unshared capture worker",sampleRate:this.sampleRate,...super.dump()}}},lr=class extends bA{constructor(t,e,l){super(t);this.workletPort=e;this.id=w.PlaybackPreload,this.outBuffer=K(this.wasm,"f32",48e3*.02*2),this.updateHandle=setInterval(()=>this.update(),l),M(globalThis,["playbackReady",{}])}close(){super.close(),S(this.wasm,this.outBuffer),clearInterval(this.updateHandle)}onMessage(t){super.onMessage(t);let[e,l]=t;switch(e){case"playbackSetVolume":this.setVolume(l.index,l.value);break;case"playbackTick":this.tick();break}}setVolume(t,e){t==="global"?IA(this.information,e):mA(this.information,t,e)}tick(){this.stats.numberTicks++,this.id+=1;let{hasAudio:t}=this.decode(this.outBuffer);if(t){let e=this.outBuffer.slice();M(this.workletPort,["samples",{id:this.id,buffer:e}],[e.buffer])}}update(){let t=new Float32Array(this.information.length*2);for(let l=0;l<=this.largestIndex;l++)t[l]=hA(this.information,l);let e=[];for(let[l,d]of this.medias)e[d.index]={packetsBuffered:d.decoder.cache_length,packetsSeen:d.decoder.packets_seen,packetsProcessed:d.decoder.packets_processed,packetsTooEarly:d.decoder.packets_too_early,packetsTooLate:d.decoder.packets_too_late,packetsDropped:0,packetsInvalid:d.decoder.packets_invalid,packetsRepeated:d.decoder.packets_repeated,packetsLost:d.decoder.packets_lost};M(globalThis,["playbackUpdate",{activities:t,jitterStats:e}],[t.buffer])}dump(){return{type:"unshared playback worker",id:this.id,...super.dump()}}};})();
|
|
6436
|
-
`});var Yx,L0=q(()=>{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:()=>R,AdditionalPlaybackBlocks:()=>E,ClockJumpCheckInterval:()=>_,ClockJumpThreshold:()=>N,ConnectInterval:()=>Z,ConnectTimeout:()=>J,DefaultRefreshRate:()=>C,DefaultVideoCodec:()=>q,HealthCheckTimeout:()=>O,MainConnectionPingInterval:()=>W,MaxNumberOfDecoders:()=>L,MinDBFs:()=>v,MinTokenLifetime:()=>z,MinTokenRefreshInterval:()=>G,PlaybackPreload:()=>F,RenderQuantumSize:()=>V,VadPreload:()=>D,WebRtcIceTimeout:()=>$,WebRtcStatsSnapshotInterval:()=>j,WebRtcTimeout:()=>H});var E=3,R=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=5e3,z=6e4,G=5e3,Z=[0,100,200,200,500],q="H264";function d(e,t,r){return e.postMessage(t,r)}var Q;(e=>{let t;(r=>(r[r.InvalidPassword=-1]="InvalidPassword",r[r.Unknown=0]="Unknown",r[r.Unencrypted=1]="Unencrypted",r[r.Encrypted=2]="Encrypted"))(t=e.PeerCipherStatus||={})})(Q||={});var{Deno:k}=globalThis,Y=typeof k?.noColor=="boolean"?k.noColor:!1,K=!Y;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 K?`${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 X(e){return h(e,m([2],22))}var ke=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),ee=new Date,f=(e=>(e[e.CRITICAL=0]="CRITICAL",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(f||{}),T={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},te={4:X,3:p,2:p,1:U,0:U};function re({message:e}){return String(e)}function S(e){return JSON.stringify({timestamp:e.date.toISOString(),level:f[e.level],message:e.message,extra:e.extra})}function I(e){function t(c,i){return[Math.floor(c/i),c%i]}function r(){let c,i=e.date.valueOf()-ee.valueOf();[i,c]=t(i,1e3);let[B,A]=t(i,60);return`${B.toString().padStart(4,"0")}:${A.toString().padStart(2,"0")}.${c.toString().padStart(3,"0")}`}function n(){return e.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(e.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(e.extra)}let s=T[e.level],a=e.logger.name!==void 0?`@${e.logger.name}`:"";return`${p(r())}${a} ${s} ${te[e.level](String(e.message))}${n()}`}function ne(e){let t=`[${e.date.toISOString()}]`,r=`[${f[e.level]}]`,n=e.logger.name!==void 0?`[${e.logger.name}] `:"",s=T[e.level];return`${t} ${s} ${r.padEnd(7," ")} ${n}${e.message}`}function se(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var w=class{static sparse=re;static json=S;static pretty=I;static structured=ne;static default=se()?I:S;constructor(){}};var oe=class{formatter;consoleObject;filter;constructor(e=w.default,t=4,r=console){this.filter=t,this.formatter=e,this.consoleObject=r}handle(e){let t=this.formatter(e);switch(e.level){case 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 oe]),ae=o.prototype.log.bind(l,1),ie=o.prototype.log.bind(l,2),ce=o.prototype.log.bind(l,3),ue=o.prototype.log.bind(l,4),Ue=o.prototype.log.bind(l);var b=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.blocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"init":this.state=new y(s.workerPort,sampleRate*.02);break;case"close":this.alive=!1;break;case"dump":s.result.postMessage(this.dump());break}}process(r,n,s){if(this.state===void 0||r.length<1||r[0].length<1)return this.alive;let a=this.state.fill(0,r[0][0]);return this.state.offset===this.state.length&&(this.state.flush(),this.state.fill(a,r[0][0])),this.alive}dump(){return{type:"unshared capture worklet",alive:this.alive,sampleRate,offset:this.state?.offset||null,length:this.state?.length||null,blocks:this.blocks}}},x=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.silenceBlocks=0;this.voiceBlocks=0;this.totalBlocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"close":this.alive=!1;break;case"init":this.state=new g(s.workerPort,sampleRate*.02),s.workerPort.onmessage=this.onMessage.bind(this);break;case"samples":this.state?.add(s.id,s.buffer);break;case"dump":s.result.postMessage(this.dump());break}n==="close"&&(this.alive=!1)}process(r,n,s){if(this.state===void 0||n.length<1||n[0].length<2)return this.alive;let a=this.state.fill(0,n[0][0],n[0][1]);return a<u.RenderQuantumSize&&(this.totalBlocks+=1,this.state.next(),this.state.hasVoice?this.voiceBlocks+=1:this.silenceBlocks+=1,this.state.fill(a,n[0][0],n[0][1])),this.alive}dump(){return{type:"unshared playback worklet",alive:this.alive,sampleRate,id:this.state?.id||null,offset:this.state?.offset||null,length:this.state?.length||null,hasVoice:this.state?.hasVoice??!1,silenceBlocks:this.silenceBlocks,voiceBlocks:this.voiceBlocks,totalBlocks:this.totalBlocks}}},y=class{constructor(t,r){this.port=t;this.length=r;this.offset=0,this.buffer=new Float32Array(r)}fill(t,r){let n=Math.min(r.length-t,this.length-this.offset);return this.buffer.set(r.subarray(t,t+n),this.offset),this.offset+=n,t+n}flush(){d(this.port,["captureTick",{buffer:this.buffer}],[this.buffer.buffer]),this.offset=0,this.buffer=new Float32Array(this.length)}},g=class{constructor(t,r){this.port=t;this.length=r;this.cache=[];this.id=-1,this.offset=0,this.buffer=void 0,this.next()}get hasVoice(){return this.buffer!==void 0}fill(t,r,n){let s=Math.min(u.RenderQuantumSize-t,this.length-this.offset);return this.buffer!==void 0&&(r.set(this.buffer.subarray(this.offset,this.offset+s),t),n.set(this.buffer.subarray(this.offset+this.length,this.offset+this.length+s),t)),this.offset+=s,t+s}add(t,r){this.cache.push({id:t,buffer:r})}next(){for(this.id+=1;this.cache[0]?.id<this.id;)this.cache.shift();this.cache[0]?.id===this.id?(this.buffer=this.cache[0].buffer,this.cache.shift()):this.buffer=void 0,this.offset=0,d(this.port,["playbackTick",{}])}};registerProcessor("OdinCaptureProcessor",b);registerProcessor("OdinPlaybackProcessor",x);})();\n'});var H0={};Tx(H0,{UnsharedCaptureWorker:()=>sx,UnsharedPlaybackWorker:()=>ix,createCaptureWorker:()=>eF,createPlaybackWorker:()=>BF});import{Strand as tF}from"@4players/odin-common";function eF(v,t,j,e,B=i.DefaultRefreshRate){return jF.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,j,B,C,E,e)})}async function BF(v,t=i.DefaultRefreshRate){if(v.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[j,e]=await Y(Zx,Yx,v,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return ix.create(v,t,j,e)}var jF,sx,ix,N0=q(()=>{"use strict";u();nx();_0();L0();jF=new tF;sx=class v extends X{constructor(j,e,B,C,E){super(j,e,B,C,E);this._Activity=_;this._SpeechProbability=0;e.addEventListener("message",this._OnMessages.bind(this))}static async create(j,e,B,C,E,f,s){let{port1:o,port2:p}=new MessageChannel;return k(E,["captureInit",{sampleRate:j.sampleRate,refreshRate:C,workletPort:o}],[o]),await U(E,"captureReady"),k(f.port,["init",{workerPort:p}],[p]),new v(f,E,e,B,s)}get activity(){return this._Activity}get speechProbability(){return this._SpeechProbability}setVolume(j){k(this.worker,["captureSetVolume",{value:j}])}_OnMessages(j){super._OnMessages(j);let[e,B]=j.data;e==="captureUpdate"&&(this._Activity={isSilent:!B.active,rmsDBFS:B.rmsDBFs},this._SpeechProbability=B.speechProbability)}},ix=class v extends z{constructor(j,e,B){super(j,e,B);this.activities=new Float32Array;this.jitterStats=[]}static async create(j,e,B,C){let{port1:E,port2:f}=new MessageChannel;return k(B,["playbackInit",{workletPort:E,refreshRate:e}],[E]),await U(B,"playbackReady"),k(C.port,["init",{workerPort:f}],[f]),new v(j,C,B)}getActivity(j){let e=this.medias.get(m(j));if(e===void 0)return;let B=this.activities.at(e.index);if(B!==void 0)return B===0?_:{isSilent:!1,rmsDBFS:B}}getJitterStats(j){let e=this.medias.get(m(j));if(e===void 0)return;let B=this.jitterStats.at(e.index);if(B!==void 0)return B}setGlobalVolume(j){k(this.worker,["playbackSetVolume",{index:"global",value:j}])}setVolume(j,e){let B=this.medias.get(m(j));B!==void 0&&k(this.worker,["playbackSetVolume",{index:B.index,value:e}])}_GetFreeIndex(){let j=super._GetFreeIndex();if(j!==void 0)return j;if(this.medias.size<i.MaxNumberOfDecoders)return this.medias.size}_OnMessages(j){super._OnMessages(j);let[e,B]=j.data;e==="playbackUpdate"&&(this.activities=B.activities,this.jitterStats=B.jitterStats)}}});u();import{Backend as r,generateUUID as lr}from"@4players/odin-common";u();import{Backend as x,JITTER_STATS_INITIAL as J0,Strand as iF,assert as bF}from"@4players/odin-common";u();import{APM_DEFAULTS as EF,Backend as cB,generateUUID as fF,VAD_DEFAULTS as nF}from"@4players/odin-common";import{failure as h0,isFirefoxBrowser as SA,sleep as RA,success as VA}from"@4players/odin-common";async function q0(v,t,j){let e;if(t.device?.device.kind==="track"&&t.device?.device.audioTrack)e=new MediaStream([t.device.device.audioTrack]);else{let E=t.device?{exact:t.device.device.deviceId==="default"?void 0:t.device.device.deviceId}:void 0;try{let f=await Promise.race([navigator.mediaDevices.getUserMedia({audio:{echoCancellation:j.echoCanceller,noiseSuppression:j.noiseSuppression!=="None",autoGainControl:j.gainController,echoCancellationType:"system",deviceId:E}}),RA(3e4,"timeout")]);if(f==="timeout")return h0("getUserMedia; timeout");e=f}catch(f){return h0(`getUserMedia; ${f}`)}}let B=e.getAudioTracks()[0].getSettings().sampleRate,C=await v.audioContexts.acquire(B);return VA(C.createMediaStreamSource(e))}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(SA()){let B=await UA("microphone");(B==="granted"||B===!1)&&await WA("audio")}let v=(await navigator.mediaDevices.enumerateDevices()).filter(B=>!!B.label),t=[],j=new L({deviceId:"default",name:"Default",kind:"audioinput"},!0),e=new L({deviceId:"default",name:"Default",kind:"audiooutput"},!0);t.push(j),t.push(e);for(let B of v){if(B.deviceId==="default"){B.kind==="audioinput"&&(j=new L({deviceId:"default",name:B.label,kind:"audioinput"},!0),t[0]=j),B.kind==="audiooutput"&&(e=new L({deviceId:"default",name:B.label,kind:"audiooutput"},!0),t[1]=e);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 UA(v){try{return(await navigator.permissions.query({name:v})).state}catch{return!1}}async function WA(v){try{let t=await navigator.mediaDevices.getUserMedia({[v]:!0});return t?.getTracks().forEach(j=>{j.stop(),t.removeTrack(j)}),!0}catch{return!1}}u();import{isSafariBrowser as vF,isSharedArrayBufferCapable as CF}from"@4players/odin-common";var w0=CF()&&!vF()?Promise.resolve().then(()=>(y0(),$0)):Promise.resolve().then(()=>(N0(),H0));async function P0(v,t,j,e){return w0.then(B=>B.createCaptureWorker(v,t,j,e,i.DefaultRefreshRate))}async function K0(v){return w0.then(t=>t.createPlaybackWorker(v,i.DefaultRefreshRate))}var w=class{constructor(t,j){this.controller=t;this._Medias=new Map;this._Vad={...nF};this._Apm={...EF};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=>d("device-change handler failed",t))};j.apm&&this.setApm(j.apm).catch(console.error),j.vad&&this.setVad(j.vad),typeof j.volume<"u"&&this.setVolume(j.volume).catch(console.error),this.uid=fF(),this.#x=j.customType,this.#A=j.ref}#x;#A;_enqueue(t){let j=this._Queue.then(t,t);return this._Queue=j.catch(()=>{}),j}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,j){let e=this._Medias.get(j.connectionId);e===void 0&&this._Medias.set(j.connectionId,e=new Set),b(`starting audio capture media ${j.mediaId} on connection ${j.connectionId}`),!e.has(j.mediaId)&&(e.add(j.mediaId),t.mainConnection?.id===j.connectionId&&await t.request("StartMedia",{media_id:j.mediaId,properties:{kind:"audio",uid:this.uid,ref:this.#A,customType:this.#x}}).catch(B=>c(`StartMedia got rejected; ${B}`)),this._UpdateMedias())}async stop(t,j){let e=this._Medias.get(j.connectionId);b(`stopping audio capture media ${j.mediaId} on connection ${j.connectionId}`),e?.delete(j.mediaId)&&(t.mainConnection?.id===j.connectionId&&await t.request("StopMedia",{media_id:j.mediaId}).catch(B=>c(`StopMedia got rejected; ${B}`)),this._UpdateMedias())}setVad(t){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 j=this._DeviceParameters;if(this._DeviceParameters=t,this._Volume!=="muted")try{let e=await q0(this.controller,t,{...this._Apm,echoCanceller:this._Monitor?!1:this._Apm.echoCanceller});if(e.type!=="Success"){c(`unable to open capture device; ${e.reason}`),this._DeviceParameters=j;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){d("failed to disconnect previous capture source",B)}}this._Capture===void 0||this._Capture.worker.worklet.context!==e.value.context?(this._Capture?.worker.close(),this._Capture={worker:await P0(e.value.context,this.controller.sink,this.controller.receiveMonitoredPacket.bind(this.controller),new WeakRef(this)),source:e.value},await this._UpdateMedias(),this._Capture.worker.setVolume(this._Volume),this.setVad(this.vad)):this._Capture.source=e.value,this._Capture.source.connect(this._Capture.worker.worklet)}catch(e){throw new Error(`Error in setDevice(); ${e}`)}}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){d("failed to disconnect audio node",t)}await this.controller.audioContexts.release(this._Capture.source.context)}navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._Capture=void 0}async dump(){let t=[];for(let[j,e]of this._Medias)t.push(`${j} => ${Array.from(e.values()).join(",")}`);return{uid:this.uid,ref:this.#A??null,customType:this.#x??null,worker:await this._Capture?.worker.dump()??null,vad:this._Vad,apm:this._Apm,volume:this._Volume,medias:t}}async _UpdateMedias(){if(this._Capture!==void 0){let t=Array.from(this._Medias).map(([j,e])=>({id:j,mediaIds:Array.from(e)}));this._Capture.worker.setMedias(t)}}async startLoopback(){this._Monitor===void 0&&(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 sF}from"@4players/odin-common";u();var $=class{constructor(t,j){this.controller=t;this.parameters=j;this.uid=sF()}#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,j={voiceActivity:void 0,volumeGate:void 0}){if(this.#x)throw new Error("This VideoCapture already has a MediaStream.");if(!t.getVideoTracks()[0])throw new Error("Error when calling setDevice(), MediaStream does not contain a VideoStreamTrack!");if(this.#x=t,t.getAudioTracks()[0]){let B={device:await m0(t.getAudioTracks()[0]),vad:j,ref:this.uid};this.#F=await this.controller.createAudioCapture(B)}}async start(t,j){let e=this.#A.get(j.connectionId);if(e===void 0&&this.#A.set(j.connectionId,e=new Set),!e.has(j.mediaId)&&(e.add(j.mediaId),t.mainConnection?.id===j.connectionId)){let B={kind:"video",codec:this.parameters?.codec??i.DefaultVideoCodec,ref:this.#F?.uid,uid:this.uid};this.parameters?.customType&&(B.customType=this.parameters.customType),await t.request("StartMedia",{media_id:j.mediaId,properties:B}).catch(C=>c(`StartMedia got rejected; ${C}`))}}async stop(t,j){this.#x&&W(this.#x),this.#A.get(j.connectionId)?.delete(j.mediaId)&&t.mainConnection?.id===j.connectionId&&await t.request("StopMedia",{media_id:j.mediaId}).catch(B=>c(`StopMedia got rejected; ${B}`))}async dump(){let t=[];for(let[j,e]of this.#A)t.push(`${j} => ${Array.from(e.values()).join(",")}`);return{uid:this.uid,ref:this.#F?.uid??null,customType:this.customType??null,tracks:this.#x?.getVideoTracks().map(j=>({id:j.id,kind:j.kind,label:j.label,ready:j.readyState,muted:j.muted,settings:{...j.getSettings()}}))??[],volume:this.#F?.volume??0,medias:t}}close(){this.#x&&W(this.#x),this.audioCapture?.close(),this.#F=void 0}};u();import{Backend as dB}from"@4players/odin-common";var H=class{constructor(t,j,e){this.controller=t;this.uid=j;this.customType=e}get volume(){return this.controller.playbackGetVolume(this.uid)}get activity(){return this.controller.playbackGetActivity(this.uid)}get jitterStats(){return this.controller.playbackGetJitterStats(this.uid)}start(t){b(`starting audio playback media ${t.mediaId} on connection ${t.connectionId}`),this.controller.playbackStart(this.uid,t)}stop(t){b(`stopping audio playback media ${t.mediaId} on connection ${t.connectionId}`),this.controller.playbackStop(this.uid,t)}setVolume(t){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 oF(v,t){let j=v.audioContext;if(typeof j.setSinkId=="function"){v.connectOutput(j.destination);let e,B=()=>{if(j.state==="running"&&e!==void 0){let C=e;e=void 0,j.setSinkId(C).catch(E=>d("failed to apply deferred sinkId",E))}};return j.addEventListener("statechange",B),{async setSinkId(C){if(j.state!=="running"){e=C;return}await j.setSinkId(C)},dispose(){j.removeEventListener("statechange",B)}}}if(t&&typeof document<"u"&&typeof HTMLAudioElement<"u"&&typeof HTMLAudioElement.prototype.setSinkId=="function"){let e=j.createMediaStreamDestination();v.connectOutput(e);let B=new Audio;B.srcObject=e.stream,B.muted=!1,B.volume=1;let C=!1,E=!1,f={once:!0,passive:!0,capture:!0},s=()=>{E=!1,h()},o=()=>{E||C||(E=!0,document.addEventListener("pointerdown",s,f),document.addEventListener("keydown",s,f))},p=()=>{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"?o():d("failed to start playback audio element",Dx))})},Bx=()=>{j.state==="running"&&B.paused&&h()};return j.addEventListener("statechange",Bx),h(),{async setSinkId(Dx){await B.setSinkId(Dx)},dispose(){C=!0,p(),j.removeEventListener("statechange",Bx),B.pause(),B.srcObject=null,B.removeAttribute("src");try{B.load()}catch{}e.disconnect()}}}return v.connectOutput(j.destination),{async setSinkId(){},dispose(){}}}var ox=class{constructor(t){this.audioContextFactory=t;this.entries=[]}async acquire(t){for(let e of this.entries){if(e.sampleRate===t)return e.references+=1,e.audioContext;if(e.sampleRate===void 0&&e.audioContext.sampleRate===t)return e.references+=1,e.audioContext}let j={sampleRate:t,audioContext:await this.audioContextFactory(t),references:1};return this.entries.push(j),j.audioContext}async release(t){let j=this.entries.findIndex(e=>e.audioContext===t);if(!(j<0)&&(this.entries[j].references-=1,this.entries[j].references<=0)){let e=this.entries[j].audioContext;this.entries.splice(j,1),await e.close()}}close(){for(let t of this.entries)t.audioContext.close()}},ax=class v{constructor(t,j,e=!1){this.audioContexts=t;this.sink=j;this.enableHTMLAudioElementFallback=e;this.audioCaptures=[];this.videoCaptures=[];this.globalVolume=[1,1];this.playbacks=new Map;this.setPlaybackStrand=new iF}async create(t,j){return new v(t,j)}receivePacket(t,j){this.playbackWorker?.receivePacket(t,j)}receiveMonitoredPacket(t,j){let e=j.slice();this.receivePacket(t,e)}async createAudioPlayback(t){let j=this.playbacks.get(t.uid),e=t.volume;if(j===void 0){e=e??[1,1];let B=new H(this,t.uid,t.customType);j={id:void 0,volume:e,playback:B},this.playbacks.set(t.uid,j)}return e!==void 0&&j.playback.setVolume(e),j.playback}async createAudioCapture(t){let j=new w(this,t);return await j.setDevice(t),this.audioCaptures.push(new WeakRef(j)),j}async createVideoCapture(t,j){let e=new $(this,j);return await e.setDevice(t),this.videoCaptures.push(new WeakRef(e)),e}playbackSetDevice(t){return this.setPlaybackStrand.enqueue(async()=>{let j=t?.device.deviceId??"";if(j==="default"&&(j=""),this.playbackWorker===void 0){let e=await this.audioContexts.acquire(48e3);this.playbackWorker=await K0(e),this.playbackSink=oF(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(j)}catch(e){d("failed to set playback sink",e)}})}playbackSetGlobalVolume(t){this.globalVolume=t,this.playbackWorker?.setGlobalVolume(this.globalVolume)}playbackStart(t,j){let e=this.playbacks.get(t);e!==void 0&&(e.id!==void 0&&this.playbackStop(t,e.id),e.id=j,this.playbackWorker?.addMedias(j.connectionId,[j.mediaId],e.volume))}playbackStop(t,j){let e=this.playbacks.get(t);e!==void 0&&(e.id!==j&&d(`playback media ${j.mediaId} on connection ${j.connectionId} is out of sync`,e.id,j),e.id=void 0,this.playbackWorker?.removeMedias(j.connectionId,[j.mediaId]))}playbackGetActivity(t){let j=this.playbacks.get(t);return j?.id===void 0?_:this.playbackWorker?.getActivity(j.id)??_}playbackGetJitterStats(t){let j=this.playbacks.get(t);return j?.id===void 0?J0:this.playbackWorker?.getJitterStats(j.id)??J0}playbackSetVolume(t,j){let e=this.playbacks.get(t);e!==void 0&&(e.volume=j,e.id!==void 0&&this.playbackWorker?.setVolume(e.id,e.volume))}playbackGetVolume(t){return this.playbacks.get(t)?.volume??[1,1]}closePlayback(t){let j=this.playbacks.get(t);j!==void 0&&(j.id!==void 0&&this.playbackStop(t,j.id),this.playbacks.delete(t))}close(){this.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 j=[];for(let B of this.videoCaptures){let C=B.deref();C!==void 0&&j.push(await C.dump())}let e=[];for(let[B,C]of this.playbacks)e.push({uid:B,id:C.id||null,volume:C.volume});return{globalVolume:this.globalVolume,playbackWorker:await this.playbackWorker?.dump()||null,audioCaptures:t,videoCaptures:j,playbacks:e}}},L=class{constructor(t,j=!1){this.device=t;this.isDefault=j}get type(){switch(this.device.kind){case"audioinput":return"AudioCapture";case"audiooutput":return"AudioPlayback";default:bF(!1,"not supported device")}}get id(){return this.device.deviceId}get name(){return this.device.name}};u();import{nextTick as RF,success as xA}from"@4players/odin-common";import{decode as VF}from"@msgpack/msgpack";u();import{Backend as pB}from"@4players/odin-common";u();import{Backend as A,failure as kx,success as V0,CONNECTION_STATS_INITIAL as IF}from"@4players/odin-common";import{MainCommandsRpc as gF,MainNotificationsRpc as $F,RoomCommandsRpc as yF,RoomNotificationsRpc as _F}from"@4players/odin-common/api";u();import{failure as x0,success as A0}from"@4players/odin-common";import{MessagePackRpcSchema as aF,parseRequest as O0,parseResponse as lF}from"@4players/odin-common/api";import{encode as uF,decode as kF}from"@msgpack/msgpack";var M=class{constructor(t){this.stream=t;this._SendQueue=[];this._RecvQueue=[];this._EventQueue=[];this._Requests=new Map;this._Close=new AbortController;this._NextId=1;t instanceof WebSocket?(t.addEventListener("open",this._OnWebSocketOpen.bind(this)),t.addEventListener("close",this.close.bind(this)),t.addEventListener("message",j=>this._OnRpcMessage(j.data)),t.binaryType="arraybuffer"):(dF(t.readable.getReader(),this._OnRpcMessage.bind(this)).finally(this.close.bind(this)),this._Writer=t.writable.getWriter()),this._Close.signal.addEventListener("abort",this._Cleanup.bind(this),{once:!0})}get closed(){return this._Close.signal.aborted}get closeSignal(){return this._Close.signal}async request(t,j,e){if(this.closed)return Promise.resolve("closed");let B=this._NextId,C=e===void 0?void 0:setTimeout(()=>this._TimeoutRequest(B),e);return this._Send([0,B,t,j]),new Promise(E=>{this._Requests.set(B,{accept:E,timeoutId:C}),this._NextId+=1})}notify(t,j){this.closed||this._Send([2,t,j])}recv(){if(this.closed)return Promise.resolve("closed");let t=this._EventQueue.shift();return t!==void 0?Promise.resolve(t):new Promise(j=>this._RecvQueue.push(j))}close(){this._Close.abort()}_TimeoutRequest(t){let j=this._Requests.get(t);j!==void 0&&(this._Requests.delete(t),clearTimeout(j.timeoutId),j.accept("timeout"))}_Send(t){let j;t instanceof Uint8Array?j=t:j=new Uint8Array(uF(t,{ignoreUndefined:!0,forceFloat32:!0})),this.stream instanceof WebSocket?this.stream.send(j):this._Writer.write(j)}_OnWebSocketOpen(t){for(let j of this._SendQueue)this._Send(j);this._SendQueue.length=0}_OnRpcMessage(t){let j=cF(t);if(j.type!=="Success"){this.close();return}switch(j.value[0]){case 0:this._Send([1,j.value[1],"not supported",null]);break;case 1:this._OnResponse(j.value[1],j.value[2],j.value[3]);break;case 2:this._OnEvent(j.value[1],j.value[2]);break}}_OnResponse(t,j,e){let B=this._Requests.get(t);B!==void 0&&(clearTimeout(B.timeoutId),B.accept(j===null?A0(e):x0(j)))}_OnEvent(t,j){let e=this._RecvQueue.shift();e!==void 0?e({name:t,properties:j}):this._EventQueue.push({name:t,properties:j})}_Cleanup(){for(let t of this._Requests.values())clearTimeout(t.timeoutId),t.accept("closed");this._Requests.clear();for(let t of this._RecvQueue)t("closed");this._RecvQueue.length=0,this._SendQueue.length=0,this.stream instanceof WebSocket?this.stream.close():this._Writer?.close().catch(()=>{})}},V=class{constructor(t,j,e){this.rpc=t;this._Commands=j;this._Events=e}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(t,j,e){j=O0(t,j,this._Commands);let B=await this.rpc.request(t,j,e);if(B==="closed"||B==="timeout"||B.type==="Failure")return B;let C=lF(t,B.value,this._Commands);return C!==void 0?A0(C):x0("response schema failed validation")}notify(t,j){j=O0(t,j,this._Commands),this.rpc.notify(t,j)}async recv(){let t=await this.rpc.recv();if(t==="closed")return t;let j=F0(this._Events,t);return j!==void 0?j:(M0(this._Events,t.name)?(c(`schema validation for ${t.name} failed; closing connection`),this.rpc.close()):d(`dropping unknown event ${t.name}`),"closed")}close(){this.rpc.close()}};function cF(v){try{return A0(aF.parse(kF(new Uint8Array(v))))}catch(t){return x0(String(t))}}function F0(v,t){if(!M0(v,t.name))return;let j=v[t.name].safeParse(t.properties);if(j.success)return{name:t.name,properties:j.data}}function M0(v,t){return t in v}async function dF(v,t){let j=new Uint8Array;for(;;){let e=l0(j,0);if(e===n){v.cancel("protocol violation");break}if(e!==I&&e<=j.length){t(j.subarray(0,e)),j=j.subarray(e);continue}let B;try{B=await v.read()}catch{break}if(B.done)break;j=pF(j,B.value)}j.length>0&&d("unprocessed bytes left in rpc stream",j)}function pF(v,t){if(v.length===0)return t;if(t.length===0)return v;let j=new Uint8Array(v.length+t.length);return j.set(v,0),j.set(t,v.length),j}u();import{failure as lx,fromBase64Url as hF,success as qF}from"@4players/odin-common";import{TokenClaimsSchema as mF}from"@4players/odin-common/api";var y=class v{constructor(t,j){this.text=t;this.claims=j;if(j.ups!==void 0){let e=v.parse(j.ups);e.type==="Success"?this._Upstream=e.value:c(`upstream in token can not be parsed; ${e.reason}`)}}static parse(t){let j=t.split(".");if(j.length!==3)return lx("expected three segments");let e=hF(j[1]);if(e.type==="Failure")return lx(`invalid token; ${e.reason}`);let B;try{B=JSON.parse(e.value)}catch(E){return lx(`invalid token; ${E}`)}let C=mF.safeParse(B);return C.success===!1?lx(`invalid token; ${C.error}`):qF(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 r0}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 S0(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,j){this._localVideos=new Map;this._remoteVideos=new Map;this._freeLocalVideoTransceivers=[];this._negotiation={requested:!1,running:!1,waitForAnswer:!1};this._WebRtcStatsSnapshot=null;this._peerConnection=t,this._signaling=j,this._peerConnection.ontrack=this._onTrack.bind(this),this._peerConnection.onconnectionstatechange=()=>this._onStatusChanged(),this._peerConnection.onicecandidate=async e=>{e.candidate?await this._signaling.sendIceCandidate(e.candidate):await this._signaling.sendIceComplete()},this._WebRtcStatsInterval=setInterval(()=>{this._snapshotStats()},i.WebRtcStatsSnapshotInterval)}requestNegotiation(t){this._negotiation.requested=!0,t&&(this._negotiation.waitForAnswer=!0),!this._negotiation.running&&(this._negotiation.running=!0,setTimeout(async()=>{let j=this._negotiation.waitForAnswer;this._negotiation.requested=!1,this._negotiation.waitForAnswer=!1;try{let e;j&&(e=new Promise(B=>{this._resolveOffer=B})),await this._sendOffer(),e&&await e}catch(e){c("negotiation failed during sdp offer/answer exchange",e)}finally{this._resolveOffer=void 0,this._negotiation.running=!1,this._negotiation.requested&&this.requestNegotiation(this._negotiation.waitForAnswer)}}))}async startLocalVideo(t,j,e){if(this._localVideos.has(t))return;b(`starting local video for media ${t}`);let B=this._freeLocalVideoTransceivers.pop();if(B?(await B.sender.replaceTrack(j),B.direction="sendrecv"):B=this._peerConnection.addTransceiver(j),e){let f=B.sender.getParameters(),{maxBitrate:s,maxFramerate:o,scaleResolutionDownBy:p}=e,h={...s!==void 0&&{maxBitrate:s},...o!==void 0&&{maxFramerate:o},...p!==void 0&&{scaleResolutionDownBy:p}};if(f.encodings.length===0)f.encodings.push(h);else for(let Bx of f.encodings)Object.assign(Bx,h);e.degradationPreference&&(f.degradationPreference=e.degradationPreference),await B.sender.setParameters(f)}let E=new GF(e?.codec??i.DefaultVideoCodec).isSupported();E&&B.setCodecPreferences([E]),this._localVideos.set(t,{transceiver:B}),this.requestNegotiation(!0)}stopLocalVideo(t){let j=this._localVideos.get(t);j&&(b(`stopping local video for media ${t}`),this._localVideos.delete(t),j.transceiver.sender.track&&(j.transceiver.sender.track.enabled=!1),j.transceiver.direction="inactive",j.transceiver.sender.replaceTrack(null).catch(()=>{}),this._freeLocalVideoTransceivers.push(j.transceiver),this.requestNegotiation(!1))}startRemoteVideo(t){b(`starting remote video for media ${t}`);let j=this._peerConnection.addTransceiver("video",{direction:"recvonly"}),e=new Promise((B,C)=>{this._remoteVideos.set(t,{state:"Requested",transceiver:j,promise:{resolve:B,reject:C}})});return this.requestNegotiation(!0),e}stopRemoteVideo(t){let j=this._remoteVideos.get(t);j&&(b(`stopping remote video for media ${t}`),this._remoteVideos.delete(t),j.state!=="Active"&&j.promise.reject(new Error("video stopped")),this.requestNegotiation(!1))}async handleWebRtcUpdate(t){switch(t.kind){case"Sdp":await this._updateRemoteSdp(t.type==="Answer"?"answer":"offer",t.sdp,t.media_map);break;case"Trickle":this._addIceCandidate({candidate:t.candidate,sdpMid:t.spd_mid??void 0,sdpMLineIndex:t.spd_mline_index??void 0,usernameFragment:t.username_fragment??void 0});break;case"TrickleFinished":this._addIceCandidate(void 0);break}}async startup(){if(this._peerConnection.connectionState==="new")try{let t=await this._peerConnection.createOffer();r0(t.type==="offer"&&t.sdp,"generated broken webrtc offer"),await this._peerConnection.setLocalDescription(t),await this._signaling.sendOffer(t.sdp,[])}catch{c("failed to create initial sdp offer")}}cleanup(){for(let[,t]of this._remoteVideos)t.state!=="Active"&&t.promise.reject(new Error("connection closed"));clearTimeout(this._WebRtcIceTimeout),clearTimeout(this._WebRtcTimeout),clearInterval(this._WebRtcStatsInterval),this._localVideos.clear(),this._remoteVideos.clear(),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._negotiation.running}async _snapshotStats(){try{let t=await this._peerConnection.getStats(),j={},e={bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,rtt:0};t.forEach(B=>{let{type:C,...E}=B;C!=="certificate"&&(C==="candidate-pair"&&B.nominated&&(e.bytesSent+=B.bytesSent??0,e.bytesReceived+=B.bytesReceived??0,e.packetsSent+=B.packetsSent??0,e.packetsReceived+=B.packetsReceived??0,e.rtt=B.currentRoundTripTime??0),j[C]||(j[C]=[]),j[C].push(E))}),this._WebRtcStatsSnapshot={timestamp:Date.now(),status:this._peerConnection.connectionState,stats:e,report:j}}catch{}}_addIceCandidate(t){t&&(t.sdpMid===void 0&&t.sdpMLineIndex===void 0&&(t={...t,sdpMid:"0"}),a(`adding new ice ${t.candidate}`,t)),this._peerConnection.addIceCandidate(t)}async _sendOffer(){try{let t=await this._peerConnection.createOffer();r0(t.type==="offer"&&t.sdp,"generated broken payload"),await this._peerConnection.setLocalDescription(t);let j=[];for(let[e,{transceiver:B}]of this._localVideos)B.mid&&j.push([e,B.mid]);for(let[e,B]of this._remoteVideos)B.state!=="Active"&&B.transceiver.mid&&j.push([e,B.transceiver.mid]);await this._signaling.sendOffer(t.sdp,j)}catch(t){throw c("failed to send sdp offer",t),t}}async _updateRemoteSdp(t,j,e){for(let[B,C]of e){let E=this._remoteVideos.get(B);E?.state==="Requested"&&(this._remoteVideos.set(B,{state:"Mapped",transceiver:E.transceiver,mid:C,promise:E.promise}),a(`updated remote video list with media ${B}`,E,this._remoteVideos))}await this._peerConnection.setRemoteDescription({type:t,sdp:j}),this._resolveOffer?.(!0)}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(!0);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 j=Array.from(this._remoteVideos).find(([,C])=>C.state==="Mapped"&&C.mid===t.transceiver.mid);if(!j){d(`unexpected track with mid: ${t.transceiver.mid}`);return}let[e,B]=j;r0(B.state==="Mapped","expected video state to be Mapped"),this._remoteVideos.set(e,{state:"Active",transceiver:t.transceiver}),a(`updated local video list with media ${e}`,j,t.transceiver,this._localVideos),t.track.onended=()=>{a(`video track with mid ${t.transceiver.mid} ended`,j)},B.promise.resolve(t.track)}};var cx=class v{constructor(t,j,e,B,C,E,f){this.id=t;this.address=j;this.connection=B;this.datagramWritable=C;this.rpc=E;this.closeController=f;this._ConnectionStats={...IF};this._WebRtcSessionFlight=new S;this._PingFlight=new S;this.status=0;this._ClosePromise=(async()=>{try{await this.connection.closed}catch{}return"closed"})(),i.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(i.HealthCheckTimeout)},i.MainConnectionPingInterval)),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,o)=>{this._ConnectionStats.packetsReceived+=1,e(s,o)})}static async create(t,j,e,B){try{let C=new URL(`https://${j}?version=${k0}&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,o=s?.createWritable?.()??s?.writable;if(!o)return E.abort(),kx(`connecting to ${j} failed because WebTransport datagrams are not supported by this browser`);let p=await f.createBidirectionalStream(),h=new V(new M(p),gF,$F);return E.signal.addEventListener("abort",()=>h.close(),{once:!0}),h.notify("Hello",{stream:"main"}),V0(new v(t,j,e,f,o,h,E))}catch(C){return kx(`connecting to ${j} failed with ${C}`)}}get connectionStats(){return this._ConnectionStats}get transport(){return"H3"}get closePromise(){return this._ClosePromise}get closeSignal(){return this.closeController.signal}get closed(){return this.closeSignal.aborted}waitForConnected(){return Promise.race([this.connection.ready,this.connection.closed.then(()=>{throw new Error("connection closed")})])}close(){b(`closing connection to '${this.address}' with id ${this.id}`),this.closeController.abort("request")}async joinRoom(t,j,e,B){try{if(this.closed)return"closed";let C=await this.connection.createBidirectionalStream().catch(()=>"closed");if(C==="closed")return"closed";let E=new V(new M(C),yF,_F),f=await E.request("Hello",{stream:"room",token:String(t),room_id:j,user_data:e,position:B});return f==="closed"||f.type==="Failure"?f:V0(E.rpc)}catch(C){return kx(`JoinRoom failed; ${C}`)}}async getReconnectToken(t){let j=await this._Request("RequestReconnectToken",{peer_id:t});return j.type==="Failure"?j:y.parse(j.value)}async healthCheck(){let t=await this._RequestPing(i.HealthCheckTimeout);return t||this.close(),t}async ping(t=3e4){let j=Date.now();return await this._RequestPing(t)?Date.now()-j:0}sendDatagram(t){try{this.datagramWriter.write(t),this._ConnectionStats.packetsSent+=1;let j=t.byteLength;this.connectionStats.bytesSent+=j}catch{}}async readDatagrams(t,j,e){try{let B=t.datagrams.readable.getReader();for(;;){let C=await B.read();if(C.done)break;let E=C.value.byteLength;this.connectionStats.bytesReceived+=E,e(j,C.value)}}catch{}}_CleanUp(){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,j)=>{await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:t,media_map:j})},sendIceCandidate:async t=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:t.candidate,spd_mid:t.sdpMid??void 0,spd_mline_index:t.sdpMLineIndex??void 0,username_fragment:t.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async()=>{this._PeerConnection?.restartIce(),this._WebRtcSession?.requestNegotiation(!0)},checkConnection:async()=>{}}),this._HandleWebRtcUpdates(),this._WebRtcSession))}async _HandleWebRtcUpdates(){for(;;){let t=await this.rpc.recv();if(t==="closed")break;t.name==="WebRtcUpdate"&&this._WebRtcSession?.handleWebRtcUpdate(t.properties)}this.close()}async _Request(t,j,e){let B=Date.now(),C=await(e===void 0?this.rpc.request(t,j):this.rpc.request(t,j,e)),E=(Date.now()-B)/1e3;return t!=="Ping"&&a(`sent main rpc '${t}'; took: ${E}s`,{properties:j,timeout:e,result:C}),C==="closed"?kx("connection lost"):C}_RequestPing(t=3e4){return this._PingFlight.run(async()=>{let j=await this._Request("Ping",{},t);return j!=="timeout"&&j.type==="Success"})}async startLocalVideo(t,j,e){await(await this._EnsureWebRtcSession()).startLocalVideo(t,j,e)}stopLocalVideo(t){this._WebRtcSession?.stopLocalVideo(t)}async startRemoteVideo(t){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 PF,CONNECTION_STATS_INITIAL as KF}from"@4players/odin-common";import{MainCommandsRpc as JF,MainNotificationsRpc as OF}from"@4players/odin-common/api";u();import{abortableSleep as LF,failure as tx,success as HF}from"@4players/odin-common";async function D0(v,t){let j=performance.now(),e=tx("no connection was attempted");for(let B=0;B<i.ConnectInterval.length&&!t.aborted;B++){let C=j+wF(B);if(await LF(C-performance.now(),t)==="aborted")return tx("aborted");if(e=await NF(v,t),e.type==="Success")return e}return e}async function NF(v,t){let j;try{j=new WebSocket(v)}catch(s){return tx(`unable to create websocket; ${s}`)}let e=new AbortController,B=new Promise(s=>j.addEventListener("open",()=>s(HF(j)),{signal:e.signal})),C=new Promise(s=>j.addEventListener("close",o=>s(tx(o.reason!==""?o.reason:"unable to establish websocket connection")),{signal:e.signal})),E=new Promise(s=>t.addEventListener("abort",()=>s(tx("aborted")),{signal:e.signal})),f=await Promise.race([B,C,E]);return e.abort(),f}function wF(v){let t=i.ConnectInterval.slice(0,v).reduce((e,B)=>e+B,0),j=i.ConnectInterval[v]*Math.random();return t+j}var hx=class v{constructor(t,j,e,B,C,E){this.id=t;this.address=j;this.url=e;this.onDatagram=B;this.connection=C;this.webRtc=E;this._PeerIdMap=new WeakMap;this._ConnectionStats={...KF};this._PingFlight=new S;b(`creating new webrtc connection to '${this.address}' with id ${this.id}`),this.closeSignal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this._ClosePromise=new Promise(f=>{this.closeSignal.addEventListener("abort",()=>{f("closed")},{once:!0})}),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=>d(`webrtc audio data channel for connection with id ${t} raised an error`,f),this._AudioChannel.onclosing=f=>b(`webrtc audio data channel for connection with id ${t} begins shutting down`,f),this._AudioChannel.onclose=f=>b(`webrtc audio data channel for connection with id ${t} has closed`,f),T0(this._AudioChannel),this._WebRtcSession=new xx(this.webRtc,{sendOffer:async(f,s)=>{await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:f,media_map:s})},sendIceCandidate:async f=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:f.candidate,spd_mid:f.sdpMid??void 0,spd_mline_index:f.sdpMLineIndex??void 0,username_fragment:f.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async()=>{this.close()},checkConnection:async()=>{this.healthCheck().then()}}),this._WebRtcSession.startup(),i.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(i.HealthCheckTimeout)},i.MainConnectionPingInterval)),this._HandleWebRtcUpdates()}static async create(t,j,e,B){if(B.aborted)return px("aborted");let C;try{C=new URL(`wss://${j}`)}catch(o){return PF(`address in token(${j}) can not be parsed; ${o}`)}let E=W0(C,`main?uid=${dx}`);if(E.type!=="Success")return E;let f=await D0(E.value,B);if(f.type!=="Success")return f;let s=new V(new M(f.value),JF,OF);try{return Q0(new v(t,j,C,e,s,new RTCPeerConnection))}catch(o){return s.close(),px(`unable to create webrtc connection; ${o}`)}}get status(){switch(this.webRtc.connectionState){case"connected":return 1;case"failed":case"closed":return 2;default:return 0}}get connectionStats(){return this._ConnectionStats}get transport(){return"WebRTC"}get closePromise(){return this._ClosePromise}get closeSignal(){return this.connection.closeSignal}get closed(){return this.connection.closed}async waitForConnected(){return new Promise((t,j)=>{let e=()=>{let B=this.status;B!==0&&(this.webRtc.removeEventListener("connectionstatechange",e),B===1?t():j(new Error("connection closed")))};this.webRtc.addEventListener("connectionstatechange",e),e(),this.closePromise.then(()=>{j(new Error("connection closed"))})})}close(){b(`closing ${this.transport} connection to '${this.address}' with id ${this.id}`),this.connection.close()}async joinRoom(t,j,e,B){let C=await this.connection.request("JoinRoom",{token:String(t),room_id:j,user_data:e,position:B});if(C==="closed"||C.type==="Failure")return C;let E=C.value;if(!("token"in E))return px("JoinRoom responded without token");let f=W0(this.url,`room?token=${E.token}`);if(f.type==="Failure")return f;let s=await D0(f.value,this.closeSignal);return s.type==="Success"?(this._PeerIdMap.set(s.value,E.peer_id),Q0(new M(s.value))):s}async getReconnectToken(t){let j=await this._Request("RequestReconnectToken",{peer_id:t});return j.type==="Failure"?j:y.parse(j.value)}async healthCheck(){let t=await this._RequestPing(i.HealthCheckTimeout);return t||this.close(),t}async ping(t=3e4){let j=Date.now();return await this._RequestPing(t)?Date.now()-j:0}sendDatagram(t){if(this._AudioChannel.readyState==="open"){let j=t.byteLength;this._AudioChannel.send(t),this._ConnectionStats.packetsSent+=1,this._ConnectionStats.bytesSent+=j}}_CleanUp(){a(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId),S0(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,j,e){let B=Date.now(),C=await(e===void 0?this.connection.request(t,j):this.connection.request(t,j,e)),E=(Date.now()-B)/1e3;return t!=="Ping"&&a(`sent main rpc '${t}'; took: ${E}s`,{properties:j,timeout:e,result:C}),C==="closed"?px("connection lost"):C}_RequestPing(t=3e4){return this._PingFlight.run(async()=>{let j=await this._Request("Ping",{},t);return j!=="timeout"&&j.type==="Success"})}async startLocalVideo(t,j,e){await this._WebRtcSession.startLocalVideo(t,j,e)}stopLocalVideo(t){this._WebRtcSession.stopLocalVideo(t)}async startRemoteVideo(t){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,j,e,B){switch(b(`creating ${t} main connection to '${j}'`),t){case"H3":return cx.create(v,j,e,B);case"WebRTC":return hx.create(v,j,e,B);default:throw new Error(`transport ${t} is not supported`)}}import{Backend as hB,failure as Y0,success as MF}from"@4players/odin-common";import{parseCommand as TF,parseNotification as SF,RoomCommandsRpc as X0,RoomNotificationsRpc as Z0}from"@4players/odin-common/api";u();var qx=class{constructor(t,j,e,B){this.id=t;this.connection=j;this.cipher=e;this.mediaMap=B;this._DatagramReceived=0;this._DatagramSent=0;this._DatagramReceivedInvalid=0;this._DatagramSentInvalid=0;j.closeSignal.addEventListener("abort",()=>this.close())}get connectionStats(){return this.connection.connectionStats}get transport(){return this.connection.transport}get address(){return this.connection.address}get status(){return this.closed?2:this.connection.status}get closePromise(){return this.connection.closePromise}get closeSignal(){return this.connection.closeSignal}get closed(){return this.connection.closed}waitForConnected(){return this.connection.waitForConnected()}close(){this.connection.close()}async joinRoom(t,j,e,B){this.cipher.reset();let C=await this.cipher.encryptUserData(e);if(C===n)return Y0("unable to encrypt initial user-data");let E=await this.connection.joinRoom(t,j,C,B);return E==="closed"||E.type==="Failure"?E:MF(new t0(E.value,this.cipher,this))}getReconnectToken(t){return this.connection.getReconnectToken(t)}healthCheck(){return this.connection.healthCheck()}async sendDatagram(t){let j=await this.cipher.encryptDatagram(t);j!==n?(this._DatagramSent+=1,this.connection.sendDatagram(j)):this._DatagramSentInvalid+=1}async decryptDatagram(t,j){let e=await this.cipher.decryptDatagram(t,j);return e!==n?this._DatagramReceived+=1:this._DatagramReceivedInvalid+=1,e}startLocalVideo(t,j,e){return this.connection.startLocalVideo(t,j,e)}stopLocalVideo(t){return this.connection.stopLocalVideo(t)}startRemoteVideo(t){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()}}},mx=class{constructor(t){this.room=t}resendUserData(){this.room.roomConnection?.notify("UpdatePeer",{user_data:this.room.roomConnection.userData})}setUserData(t,j){let e={kind:"UserDataChanged",peer_id:t,user_data:j};this.room.onEvent("PeerUpdated",e)}},t0=class{constructor(t,j,e){this.rpc=t;this.cipher=j;this.connection=e;this.peers=new Map;this.closeSignal.addEventListener("abort",this.cleanup.bind(this),{once:!0})}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(t,j,e){let B=await this.outgoing(t,j);return B===n?Y0("can not be encrypted"):await this.rpc.request(t,B,e)}async notify(t,j){let e=await this.outgoing(t,j);if(e!==n)return this.rpc.notify(t,e)}async recv(){for(;;){let t=await this.rpc.recv();if(t==="closed")return t;let j=await this.incoming(t.name,t.properties);if(j!==n)return{name:t.name,properties:j}}}close(){return this.rpc.close()}async outgoing(t,j){if(!(t in X0))return j;let e=TF(t,j,X0);if(e===void 0)return n;switch(e.name){case"UpdatePeer":{let B=await this.cipher.encryptUserData(e.request.user_data);if(B===n)return n;e.request.user_data=B}break;case"SendMessage":{let B=await this.cipher.encryptMessage(e.request.message);if(B===n)return n;e.request.message=B}break}return e.request}async incoming(t,j){if(!(t in Z0))return j;let e=SF(t,j,Z0);if(e===void 0)return n;switch(e.name){case"RoomUpdated":for(let B=0;B<e.properties.updates.length;B++){let C=await this.roomUpdate(e.properties.updates[B]);if(C===n)return n;e.properties.updates[B]=C}break;case"PeerUpdated":{let B=await this.peerUpdate(e.properties);if(B===n)return n;e.properties=B}break;case"MessageReceived":{let B=await this.cipher.decryptMessage(e.properties.sender_peer_id,e.properties.message);if(B===n)return n;e.properties.message=B}break}return e.properties}async peerUpdate(t){switch(t.kind){case"UserDataChanged":{let j=await this.cipher.decryptUserData(t.peer_id,t.user_data);if(j===n)return n;t.user_data=j}break;case"MediaStarted":this.mediaStarted(t.peer_id,t.media.id);break;case"MediaStopped":this.mediaStopped(t.peer_id,t.media_id);break}return t}async roomUpdate(t){switch(t.kind){case"Joined":for(let j of t.room.peers){for(let B of j.medias)this.mediaStarted(j.id,B.id);let e=await this.cipher.decryptUserData(j.id,j.user_data);e!==n?j.user_data=e:j.user_data=new Uint8Array}break;case"PeerJoined":{for(let e of t.peer.medias)this.mediaStarted(t.peer.id,e.id);let j=await this.cipher.decryptUserData(t.peer.id,t.peer.user_data);j!==n?t.peer.user_data=j:t.peer.user_data=new Uint8Array}break;case"PeerLeft":{let j=this.peers.get(t.peer_id);this.peers.delete(t.peer_id),this.cipher.deletePeerKey(t.peer_id);for(let e of j??[])this.mediaStopped(t.peer_id,e)}break}return t}mediaStarted(t,j){let e=this.peers.get(t);e===void 0&&(e=new Set,this.peers.set(t,e)),e.add(j);let B=m({connectionId:this.connection.connection.id,mediaId:j});this.connection.mediaMap.set(B,{peerId:t,connection:this.connection})}mediaStopped(t,j){this.peers.get(t)?.delete(j);let B=m({connectionId:this.connection.connection.id,mediaId:j});this.connection.mediaMap.delete(B)}cleanup(){for(let[t,j]of this.peers)for(let e of j)this.mediaStopped(t,e)}};var Gx=class{constructor(t){this.onDatagram=t;this._LastConnectionId=0;this._Connections=new Map;this._Close=new AbortController;this._MediaMap=new Map;let j=Date.now(),e=setInterval(()=>{Math.abs(Date.now()-j)>i.ClockJumpThreshold&&this.checkHealth(),j=Date.now()},i.ClockJumpCheckInterval);addEventListener("offline",()=>this.checkHealth(),{signal:this._Close.signal}),this._Close.signal.addEventListener("abort",()=>{clearInterval(e);for(let B of this._Connections.values())B.type==="establishing"?B.abort.abort():B.connection.close();this._Connections.clear()},{once:!0})}get closed(){return this._Close.signal.aborted}sendDatagram(t,j){let e=this._Connections.get(t);(e?.type==="established"||e?.type==="virtual")&&e.connection.sendDatagram(j)}async recvDatagram(t,j){let e=UF(j);if(e===void 0||e.length===0)return;let B=this._MediaMap.get(m({connectionId:t,mediaId:e[0]}));if(B===void 0)this.onDatagram(t,j);else{let C=await B.connection.decryptDatagram(B.peerId,j);if(C===n)return;this.onDatagram(B.connection.id,C)}}async acquireConnection(t,j,e,B){if(await RF(),this.closed)return"closed";let C=this.findConnection(t,j),E;switch(C?.type){case"established":a(`reusing existing connection ${C.id}`),E=C;break;case"establishing":{a(`waiting for connecting to '${j}' finish`);let o=await C.finished;if(o.type!=="Success")return o;E=o.value}break;case void 0:{a(`connecting to '${j}'`);let o=await this.createConnection(t,j,B);if(o.type!=="Success")return o;E=o.value}break}let f=E.id,s=new j0(E.connection,()=>this.releaseConnection(f));return E.references+=1,e&&(s=new qx(++this._LastConnectionId,s,e,this._MediaMap),this.addConnection({type:"virtual",id:s.id,connection:s,createdAt:Date.now()})),xA(s)}async createConnection(t,j,e){let B=++this._LastConnectionId,C=Date.now(),E=new AbortController;e.addEventListener("abort",()=>E.abort(),{once:!0}),a(`creating new connection ${B}`);let f=z0(B,t,j,this.recvDatagram.bind(this),e),{promise:s,resolve:o}=Promise.withResolvers();this.addConnection({type:"establishing",id:B,address:j,transport:t,finished:s,createdAt:Date.now(),abort:E});let p=await f;if(this._Connections.delete(B),p.type!=="Success")return o(p),p;let h={type:"established",id:B,address:j,transport:t,createdAt:C,references:0,connection:p.value};return this.addConnection(h),xA(h)}addConnection(t){(t.type==="established"||t.type==="virtual")&&t.connection.closeSignal.addEventListener("abort",()=>{b(`connection ${t.id} has been closed`),this._Connections.delete(t.id)},{once:!0}),this._Connections.set(t.id,t)}releaseConnection(t){let j=this._Connections.get(t);j?.type==="established"&&(j.references-=1,j.references<=0&&j.connection.close())}checkHealth(){for(let t of this._Connections.values())t.type==="established"&&t.connection.healthCheck()}close(){this._Close.abort()}async dump(){let t=[];for(let e of this._Connections.values()){let B;switch(e.type){case"established":B={transport:e.transport,address:e.address,connection:await e.connection.dump(),references:e.references};break;case"establishing":B={transport:e.transport,address:e.address,aborted:e.abort.signal.aborted};break;case"virtual":B={connection:await e.connection.dump()};break}t.push({type:e.type,id:e.id,createdAt:e.createdAt,...B})}let j=[];for(let[e,B]of this._MediaMap)j.push(`${e} -> ${B.peerId} @${B.connection.id} `);return{lastConnectionId:this._LastConnectionId,connections:t,mediaMap:j,closed:this.closed}}findConnection(t,j){for(let e of this._Connections.values())if(e.type!=="virtual"&&e.transport===t&&e.address===j)return e}},j0=class{constructor(t,j){this.connection=t;this.release=j;this.closeController=new AbortController;this.closePromise=new Promise(t=>this.closeController.signal.addEventListener("abort",()=>t("closed"),{once:!0}));t.closeSignal.addEventListener("abort",()=>this.close(),{once:!0})}get closeSignal(){return this.closeController.signal}get closed(){return this.closeSignal.aborted}close(){this.release(),this.closeController.abort("closed")}get connectionStats(){return this.connection.connectionStats}get id(){return this.connection.id}get transport(){return this.connection.transport}get address(){return this.connection.address}get status(){return this.connection.status}waitForConnected(){return this.connection.waitForConnected()}joinRoom(t,j,e,B){return this.connection.joinRoom(t,j,e,B)}getReconnectToken(t){return this.connection.getReconnectToken(t)}healthCheck(){return this.connection.healthCheck()}sendDatagram(t){return this.connection.sendDatagram(t)}startLocalVideo(t,j,e){return this.connection.startLocalVideo(t,j,e)}stopLocalVideo(t){return this.connection.stopLocalVideo(t)}startRemoteVideo(t){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 UF(v){let t;try{t=VF(v)}catch{return}if(!Array.isArray(t)||t.length<2)return;let j=t[1];if(Array.isArray(j))return j.map(Number)}import{assert as e0,Backend as qB}from"@4players/odin-common";var P=class{constructor(t,j){this.uid=t;this.customType=j}#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 nA,generateUUID as ir,unwrap as br,CONNECTION_STATS_INITIAL as or}from"@4players/odin-common";import{RoomNotificationsRpc as ar,RoomV1 as IB}from"@4players/odin-common/api";import{Selector as WF,failure as N,sleep as Ix,success as T,assert as QF}from"@4players/odin-common";import{parseResponse as zF,RoomCommandsRpc as gx,RoomNotificationsRpc as XF,RoomV1 as mB}from"@4players/odin-common/api";u();var $x=class{constructor(t,j,e,B,C,E,f,s,o,p){this.connectionPool=t;this.transport=j;this.onEvent=e;this.gateway=B;this.roomId=E;this.cipher=o;this.disableAutoReconnect=p;this._Close=new AbortController;this._TokenUsed=!1;this._WasConnected=!1;this._FailedConnections=0;this._LastTokenRenew=performance.now();this._LastReconnectStartedAt=0;this._Closed=new Promise(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,j){if(this._RoomConnection===void 0)return N("currently not connected");let e=await this._RoomConnection.request(t,j,void 0);return QF(e!=="timeout","request should not timeout"),e!=="closed"&&e.type==="Success"&&this._HandleRequests(t,j,e.value),e}async request(t,j){let e=Date.now(),B=gx[t],C=await this.requestUnsafe(t,j),E=(Date.now()-e)/1e3;if(a(`sent room rpc '${t}'; took: ${E}s`,{properties:j,result:C}),C==="closed"||C.type==="Failure")return C;let f=zF(t,C.value,gx);return f!==void 0?T(f):N(`received invalid response from ${t}`)}notify(t,j){this._RoomConnection!==void 0&&this._RoomConnection.notify(t,j)}close(){this._Close.abort(!0)}get renewTokenIn(){let t=this._LastTokenRenew-performance.now()+i.MinTokenRefreshInterval,j=this._Token.timeLeft-i.MinTokenLifetime;return Math.max(t,j)}async _Main(){let t="unable to establish connection";for(let j=0;;this._FailedConnections++){if(await Ix(Math.max(j-performance.now(),0)),this._Close.signal.aborted||this.connectionPool.closed){t="user requested";break}if(j=performance.now()+1e3,this._TokenUsed=!0,this._Token.hasAudience("sfu")){let e=await this._ConnectToServer();if(e.type==="Success"&&e.value==="shutdown"){a("connection closed by user request; shutting down"),t="user requested";break}if(this.disableAutoReconnect&&this._WasConnected){t=e.type==="Failure"?e.reason:"connection lost";break}if(this._LastReconnectStartedAt===0&&(this._LastReconnectStartedAt=performance.now()),e.type==="Failure"&&!this._WasConnected&&this._FailedConnections>=3){t=e.reason;break}if(e.type==="Failure"&&!YF(this._LastReconnectStartedAt))continue}if(this.reset(),this._Close.signal.aborted||this.connectionPool.closed){t="user requested";break}if(this.gateway!==void 0&&this._Token.hasAudience("gateway")){this._ChangeStatus("Joining",`requesting new token from ${this.gateway}`);let e=await ZF(this.gateway,this._Token,this._Close.signal);if(e.type==="Success")if(e.value instanceof y)j=0,this._Token=e.value,this._TokenUsed=!1;else{t=`gateway error; ${e.value}`;break}else if(!this._WasConnected&&this._FailedConnections>=3){t="unable to contact the gateway";break}}if(this._TokenUsed&&this._Token.timeLeft<=0){t="token has expired";break}if(this._Close.signal.aborted||this.connectionPool.closed){t="user requested";break}}return this._ChangeStatus("Closed",t),this.close(),N(t)}async _ConnectToServer(){let t=this._Token;for(;t.upstream!==void 0;)t=t.upstream;let j=t.claims.adr??this.gateway?.toString();if(!j)return T("continue");if(this._ChangeStatus("Joining",`connecting to ${t.claims.adr}`),this._MainConnection===void 0||this._MainConnection.closed||this._MainConnection.address!==t.claims.adr){this._MainConnection?.close();let C=await this.connectionPool.acquireConnection(this.transport,j,this.cipher,this._Close.signal);if(C==="closed")return N("connection pool closed");if(C.type==="Failure")return this._ChangeStatus("Joining",`connection failed; ${C.reason}`),N(`connection failed; ${C.reason}`);this._MainConnection=C.value,this._OwnPeerId=void 0}let e=await Promise.race([Promise.all([this._MainConnection.joinRoom(t,this.roomId,this.userData,this.position)]),Ix(i.ConnectTimeout,"timeout"),this._Closed]);if(e==="closed"||e==="disconnected")return T("continue");if(e==="timeout")return this._ChangeStatus("Joining","timed out"),T("continue");let[B]=e;if(B==="closed")return T("continue");if(B.type==="Failure")return N(`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 N(`unable to handle connection; ${C}`)}}_ChangeStatus(t,j){let e={status:t,message:j};this.onEvent("RoomStatusChanged",e)}async _HandleConnection(t){if(this._RoomConnection===void 0)return!1;let j=new WF([()=>Ix(this.renewTokenIn,"renewToken"),()=>Ix(500,"tick"),async()=>await this._RoomConnection?.recv(),()=>this._Closed,()=>t.closePromise]);for(;;){let e=await j.next();switch(e){case void 0:case"closed":return this._RoomConnection?.close(),this._MainConnection?.close(),!1;case"disconnected":return this._RoomConnection?.close(),this._MainConnection?.close(),!0;case"renewToken":this._RenewToken();break;case"tick":break;default:this._HandleEvent(e);break}}}_HandleEvent(t){if(t.name==="RoomUpdated"){let j=XF.RoomUpdated.safeParse(t.properties);if(!j.success)return;for(let e of j.data.updates)e.kind==="Joined"&&(this._OwnPeerId=e.own_peer_id)}this.onEvent(t.name,t.properties)}_HandleRequests(t,j,e){switch(t){case"SetPeerPosition":{let B=gx.SetPeerPosition.request.safeParse(j);if(B.success){let C=B.data.position;this._Position=C.length===2?[C[0],C[1],0]:C}else d("unable to process SetPeerPosition command");break}case"UpdatePeer":{let B=gx.UpdatePeer.request.safeParse(j);B.success?this._UserData=B.data.user_data:d("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 N("connection is not established");let j=await this._MainConnection.getReconnectToken(this._OwnPeerId);return j.type==="Success"?(this._Token=j.value,T()):N(`${this._MainConnection.address} rejected reconnect token request; ${j.reason}`)}reset(){this._LastReconnectStartedAt=0,this._RoomConnection?.close(),this._RoomConnection=void 0,this._MainConnection?.close(),this._MainConnection=void 0,this._OwnPeerId=void 0}};async function ZF(v,t,j){try{let e={jsonrpc:"2.0",id:1,method:"Connect",params:{}};b(`sending authentication request to '${v}'`,e);let C=await(await fetch(v,{body:JSON.stringify(e),method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},signal:j})).json();if(b(`received authentication response fom '${v}'`,C),"result"in C)return y.parse(C.result.token);{let E=C.error?.message??"malformed response";return c(`gateway rejected token; ${E}`),T(E)}}catch(e){return N(String(e))}}function YF(v,t=8e3){return performance.now()-v>t}u();import{assert as sr}from"@4players/odin-common";u();import{Backend as ex,Strand as nr}from"@4players/odin-common";u();import{assert as Dr}from"@4players/odin-common";u();import{decode as xr}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,jA=32,K=[79,68,73,78,1,75,105,109],Ax=16,Fx=64,eA=16;function BA(v,t){if(v.length!==t.length)return!1;for(let j=0;j<v.length;j++)if(v[j]!==t[j])return!1;return!0}function Ar(v){return isFinite(v)}function Fr(v){return Array.isArray(v)}function yx(v){return Ar(v)?v:n}function jx(v){return v instanceof Uint8Array?v:n}function rr(v,...t){let j;try{j=xr(v)}catch{return n}if(!Fr(j))return n;let e=new Array(j.length);for(let B in t)if(e[B]=t[B](j[B]),e[B]===n)return n;return e}function _x(v,...t){if(v.length<K.length)return G;for(let j=0;j<K.length;j++)if(v[j]!==K[j])return G;return rr(v.subarray(K.length),...t)}var rx=class{constructor(t){this.first=1;this.offset=0;this.window=Array(t)}isReplay(t){let j=t-this.first;if(j<0)return!0;if(j>=this.window.length)if(j<this.window.length*2){let C=j-this.window.length+1;j-=C;for(let E=0;E<C;E++)this.advance()}else return this.first=t+1-self.window.length,this.offset=0,this.window.fill(!1),!1;let e=(this.offset+j)%this.window.length,B=this.window[e]===!0;for(this.window[e]=!0;this.window[this.offset]===!0;)this.advance();return B}advance(){this.window[this.offset]=!1,this.first+=1,this.offset=(this.offset+1)%this.window.length}};var Lx=class v{constructor(t){this.key=t}static async create(t){typeof t=="string"&&(t=new TextEncoder().encode(t));let j=await globalThis.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits"]),e=await globalThis.crypto.subtle.deriveBits(AA,j,256),B=await globalThis.crypto.subtle.importKey("raw",e,"PBKDF2",!1,["deriveKey"]);return new v(B)}async generatePeerKey(t,j){return await globalThis.crypto.subtle.deriveKey(FA(t),this.key,{name:"AES-GCM",length:256},!1,[j])}},Hx=class v{constructor(t,j){this.seed=t;this.key=j;this.sequenceNumbers={datagram:1,message:1,userData:1};this.number_of_packets=0;this.number_of_bytes=0}static async create(t){let j=globalThis.crypto.getRandomValues(new Uint8Array(rA)),e=await t.generatePeerKey(j,"encrypt");return new v(j,e)}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 B0(v,t){return{kind:"encrypted",key:v,material:t,antiReplays:{datagram:new rx(jA),userData:new rx(0),message:new rx(0)}}}var Nx=class v{constructor(t,j,e,B){this.additionalData=t;this.sequenceNumber=j;this.seed=e;this.encrypted=B}static parse(t){let j=_x(t,jx,yx,jx);if(j===n||j===G)return j;let[e,B,C]=j,E=t.subarray(0,t.length-C.length);return new v(E,B,e,C)}isSameSeed(t){return BA(this.seed,t.seed)}async generateKey(t){return await t.generatePeerKey(this.seed,"decrypt")}};function wx(v,t){let j=new Uint8Array(12);switch(j[0]=t&255,j[1]=t>>8&255,j[2]=t>>16&255,j[3]=t>>24&255,v){case"datagram":j[5]=1;break;case"userData":j[5]=2;break;case"message":j[5]=3;break;default:Dr(!1,"missing content implementation")}return j}u();import{encode as CA}from"@msgpack/msgpack";import{assert as jr}from"@4players/odin-common";var Px=class{constructor(t){this.actions=t}changeKey(t){this.masterKey!==t&&(this.masterKey=t,this.ownKey=n,this.actions.resendUserData())}async encryptDatagram(t){let j=await this.getKey("datagram");return j===void 0?t:j===J?n:await Br(j,t)}async encryptMessage(t){let j=await this.getKey("message");return j===void 0?t:j===J?J:await vA(j,t,"message")}async encryptUserData(t){let j=await this.getKey("userData");return j===void 0?t:(jr(j!==J,"key unavailable for user data encryption"),await vA(j,t,"userData",j.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()),J;return this.ownKey}reset(){this.ownKey=this.masterKey?n:void 0}};async function vA(v,t,j,...e){let B=v.nextSequenceNumber(j),C=t.length+Ax,E=er(B,e,C),f=E.length-C,s=await EA(v,j,B,E.subarray(0,f),t);return E.set(new Uint8Array(s),f),E}function er(v,t,j){let e=[];t.forEach(E=>e.push(E)),e.push(v),e.push(new Uint8Array(j));let B=CA(e),C=new Uint8Array(K.length+B.length);return C.set(K,0),C.set(B,K.length),C}async function Br(v,t){let j=vr(t);if(j===n)return n;if((j.kind&Fx)!==0)return n;let e=j.body.length+Ax,B=v.nextSequenceNumber("datagram"),C=CA([j.kind|Fx,j.mediaIds,B,new Uint8Array(e)]),E=C.length-e,f=await EA(v,"datagram",B,C.subarray(0,E),j.body);return C.set(f,E),C}async function EA(v,t,j,e,B){return new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:wx(t,j),additionalData:e,tagLength:Ax*8},v.key,B))}function vr(v){let t=new O(v),j=t.readArrayLength();if(l(j)||j<2)return n;let e=t.readNumber(),B=t.readArrayLength();if(l(e)||l(B))return n;if(B>eA)return n;let C=Array(B);for(let f=0;f<C.length;f++){let s=t.readNumber();if(l(s))return n;C[f]=s}let E=v.subarray(t.position);return{kind:e,mediaIds:C,body:E}}u();import{encode as Cr}from"@msgpack/msgpack";var Jx=class{constructor(t){this.actions=t;this.peerKeys=new Map}async changeKey(t){this.masterKey=t;for(let[j,{kind:e,material:B}]of this.peerKeys)if(t!==void 0){let C=await B.generateKey(t),E=B0(C,B),f=await Kx(E,"userData",B.additionalData,B.sequenceNumber,B.encrypted);f!==n?(this.peerKeys.set(j,E),this.actions.setUserData(j,f)):(this.peerKeys.set(j,{kind:"broken",material:B}),this.actions.setUserData(j,new Uint8Array))}else e==="encrypted"&&this.peerKeys.set(j,{kind:"broken",material:B})}async decryptDatagram(t,j){let e=Er(j);if(this.masterKey===void 0)return e===G?j:n;if(e===n||e===G)return n;let B=this.peerKeys.get(t);if(B?.kind!=="encrypted")return n;let C=await Kx(B,"datagram",e.additionalData,e.sequenceNumber,e.encrypted);return C===n?n:fr(e.kind&~Fx,e.mediaIds,C)}async decryptMessage(t,j){let e=_x(j,yx,jx);if(this.masterKey===void 0)return e===G?j:n;if(e===n||e===G)return n;let B=this.peerKeys.get(t);if(B?.kind!=="encrypted")return n;let[C,E]=e,f=j.subarray(0,j.length-E.length);return Kx(B,"message",f,C,E)}async decryptUserData(t,j){let e=Nx.parse(j);if(e===n)return n;if(e===G)return this.peerKeys.delete(t),this.masterKey===void 0?j:n;if(this.masterKey===void 0)return this.peerKeys.set(t,{kind:"broken",material:e}),n;let B=this.peerKeys.get(t);if(B?.kind==="encrypted"&&B.material.isSameSeed(e))B.material=e;else{let E=await e.generateKey(this.masterKey);B=B0(E,e)}let C=await Kx(B,"userData",e.additionalData,e.sequenceNumber,e.encrypted);return C===n?this.peerKeys.set(t,{kind:"broken",material:e}):B!==void 0&&this.peerKeys.set(t,B),C}reset(){this.peerKeys.clear()}};function Er(v){let t=new O(v),j=t.readArrayLength();if(l(j)||j<1)return n;let e=t.readNumber();if(l(e))return n;if((e&Fx)===0)return G;if(j!==4)return n;let B=t.position;t.readObjects(1);let C=v.subarray(B,t.position),E=t.readNumber(),f=t.readBytes();if(l(E)||l(f))return n;let s=v.subarray(0,v.length-f.length);return{kind:e,mediaIds:C,additionalData:s,sequenceNumber:E,encrypted:f}}async function Kx(v,t,j,e,B){let C=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:wx(t,e),additionalData:j,tagLength:Ax*8},v.key,B).catch(()=>n);return C===n?n:v.antiReplays[t].isReplay(e)?n:new Uint8Array(C)}function fr(v,t,j){let e=2;try{let E=new O(j);for(E.position=0;E.position<j.length;)E.readObjects(1),e+=1}catch{return n}let B=Cr(v),C=new Uint8Array(3+B.length+t.length+j.length);return C[0]=220,C[1]=e>>8&255,C[2]=e&255,C.set(B,3),C.set(t,3+B.length),C.set(j,3+B.length+t.length),C}var Ox=class{constructor(t,j){this.active=!1;let e=new Jx(j),B=new Px(j);this.crypto=new nr({encryption:B,decryption:e}),this.peerKeys=e.peerKeys,this.configure(t)}encryptUserData(t){return this.crypto.enqueue(({encryption:j})=>j.encryptUserData(t))}async encryptMessage(t){let j;do j=await this.crypto.enqueue(({encryption:e})=>e.encryptMessage(t));while(j===J);return j}async encryptDatagram(t){return await this.crypto.enqueue(({encryption:j})=>j.encryptDatagram(t))}decryptUserData(t,j){return this.crypto.enqueue(({decryption:e})=>e.decryptUserData(t,j))}decryptMessage(t,j){return this.crypto.enqueue(({decryption:e})=>e.decryptMessage(t,j))}decryptDatagram(t,j){return this.crypto.enqueue(({decryption:e})=>e.decryptDatagram(t,j))}configure(t){return this.crypto.enqueue(async j=>{let e=t.password?await Lx.create(t.password):void 0;this.active=e!==void 0,await j.encryption.changeKey(e),await j.decryption.changeKey(e)})}getPeerStatus(t){switch(this.peerKeys.get(t)?.kind??"unencrypted"){case"broken":return ex.PeerCipherStatus.InvalidPassword;case"encrypted":return ex.PeerCipherStatus.Encrypted;case"unencrypted":return this.active?ex.PeerCipherStatus.InvalidPassword:ex.PeerCipherStatus.Unencrypted;default:return ex.PeerCipherStatus.Unknown}}deletePeerKey(t){this.peerKeys.delete(t)}reset(){return this.crypto.enqueue(async({encryption:t,decryption:j})=>{t.reset(),j.reset()})}async dump(){return this.crypto.enqueue(async()=>({active:this.active,peers:Array.from(this.peerKeys).map(([t,j])=>`${t} => ${j.kind}`)}))}};function fA(v,t){return sr(v.type==="OdinCrypto","only OdinCrypto supported"),new Ox(v,t)}var Mx=class{constructor(t,j,e){this._Captures=new Map;this._Playbacks=new Map;this._Peers=new Map;this._AvailableMediaIds=[];let{url:B,onEvent:C}=j,E=br(y.parse(j.token)),f=j.roomId??E.defaultRoomId,s=j.userData??new Uint8Array(0),o=j.position??[0,0,0];nA(f!==void 0,"room id required for multi-room-tokens"),this.cipher=j.cipher?fA(j.cipher,new mx(this)):void 0,this.onEvent=C,b(`creating new room '${f}' ${this.cipher?"with":"without"} cipher`,E,s,o),this._Connection=new $x(t,j.transport??"H3",this._HandleEvent.bind(this),B?new URL(B):void 0,E,f,s,o,this.cipher,e?.disableAutoReconnect??!1)}get connectionStats(){let t={...or};return this.mainConnection?this.mainConnection.connectionStats:t}get roomConnection(){return this._Connection}get mainConnection(){return this.roomConnection?.mainConnection}get token(){return this._Connection.token.text}request(t,j){return this._Connection.requestUnsafe(t,j)}async link(t){if(t instanceof H){let j=this._Playbacks.get(t.uid)??{media:void 0,playback:void 0};j.playback!==void 0&&this.unlink(j.playback),j.media!==void 0&&t.start(j.media),j.playback=t,b(`linking audio playback media '${t.uid}' with volume ${t.volume} to room '${this._Connection.roomId}'`),this._Playbacks.set(t.uid,j)}else if(t instanceof w){let j=this._Captures.get(t);j&&this.unlink(t);let e=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();j={media:e?{connectionId:this.mainConnection.id,mediaId:e}:void 0},b(`linking audio capture media '${t.uid}' with volume ${t.volume} to room '${this._Connection.roomId}'`),this._Captures.set(t,j),j.media!==void 0&&await t.start(this._Connection,j.media)}else if(t instanceof P){let j=this._Playbacks.get(t.uid)??{media:void 0,playback:void 0};if(j.playback!==void 0&&this.unlink(j.playback),j.media!==void 0){let e=await this.mainConnection?.startRemoteVideo(j.media.mediaId);e&&t.setMediaStream(new MediaStream([e]))}j.playback=t,b(`linking video playback media '${t.uid}' with type '${t.customType}' to room '${this._Connection.roomId}'`),this._Playbacks.set(t.uid,j)}else if(t instanceof $){let j=this._Captures.get(t);j&&this.unlink(t);let e=t.mediaStream?.getVideoTracks()[0];if(e){let B=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();j={media:B?{connectionId:this.mainConnection.id,mediaId:B}:void 0},b(`linking video capture media '${t.uid}' with type '${t.parameters?.customType}' to room '${this._Connection.roomId}'`),this._Captures.set(t,j),j.media!==void 0&&(await t.start(this._Connection,j.media),this.mainConnection?.startLocalVideo(j.media.mediaId,e,t.parameters)),t.audioCapture&&await this.link(t.audioCapture)}}else throw new Error("Linking failed, media was not supported")}unlink(t){if(t instanceof H||t instanceof P){let j=this._Playbacks.get(t.uid);if(j?.playback!==t)return;j.playback=void 0,j.media!==void 0&&(t instanceof H?t.stop(j.media):(this.mainConnection?.stopRemoteVideo(j.media.mediaId),t.setMediaStream(void 0))),b(`unlinking playback media '${t.uid}' from room '${this._Connection.roomId}'`),this._Playbacks.set(t.uid,j)}else if(t instanceof w||t instanceof $){t instanceof $&&t.audioCapture&&this.unlink(t.audioCapture);let j=this._Captures.get(t);if(j===void 0)return;j.media!==void 0&&(t.stop(this._Connection,j.media),this._AvailableMediaIds.push(j.media.mediaId),t instanceof $&&this.mainConnection?.stopLocalVideo(j.media.mediaId)),b(`unlinking capture media '${t.uid}' from room '${this._Connection.roomId}'`),this._Captures.delete(t)}else throw new Error("invalid media")}close(){b(`closing room '${this._Connection.roomId}'`),this._Connection.close()}_HandleEvent(t,j){let e=F0(ar,{name:t,properties:j});e!==void 0&&(this._HandleKnownEvent(e),j=e.properties),this.onEvent(t,j)}_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 j of t.properties.updates)this._HandleRoomUpdate(j);break;case"PeerUpdated":this._HandlePeerUpdate(t.properties);break}}_HandleConnectionLost(){for(let t of this._Peers.keys())this._HandlePeerLeft(t);for(let[t,j]of this._Captures)j.media!==void 0&&(t instanceof $,t instanceof w&&(t.stop(this._Connection,j.media),j.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 j of t.room.peers)this._HandlePeerJoined(j)}else t.kind==="PeerJoined"?this._HandlePeerJoined(t.peer):t.kind==="PeerLeft"&&this._HandlePeerLeft(t.peer_id)}_HandleRoomJoined(){for(let[t,j]of this._Captures)this._AvailableMediaIds.length===0||this.mainConnection===void 0||(j.media={connectionId:this.mainConnection.id,mediaId:this._AvailableMediaIds.shift()},t instanceof w&&t.start(this._Connection,j.media),t instanceof $)}_HandlePeerUpdate(t){t.kind==="MediaStarted"?this._HandleMediaStart(t.peer_id,t.media):t.kind==="MediaStopped"&&this._HandleMediaStopped(t.peer_id,t.media_id)}_HandlePeerJoined(t){this._Peers.has(t.id)||this._Peers.set(t.id,{mediaIds:new Map});for(let j of t.medias)this._HandleMediaStart(t.id,j)}_HandlePeerLeft(t){let j=this._Peers.get(t);if(j!==void 0){for(let e of j.mediaIds.keys())this._HandleMediaStopped(t,e);this._Peers.delete(t)}}_HandleMediaStart(t,j){if(this.mainConnection===void 0)return;let e=this._Peers.get(t);if(e===void 0||j.properties.kind!=="audio"&&j.properties.kind!=="video")return;let B=String(j.properties.uid??ir());j.properties.uid=B;let C=this._Playbacks.get(B)??{media:void 0,playback:void 0};this._Playbacks.set(B,C),e.mediaIds.set(j.id,B),C.media={connectionId:this.mainConnection.id,mediaId:j.id},C.playback!==void 0&&(C.playback instanceof H&&C.playback.start(C.media),C.playback instanceof P&&this.mainConnection.startRemoteVideo(C.media.mediaId).then())}_HandleMediaStopped(t,j){let e=this._Peers.get(t);if(e===void 0)return;let B=e?.mediaIds.get(j);if(B===void 0)return;let C=this._Playbacks.get(B);C!==void 0&&(C.media!==void 0&&C.media.mediaId===j&&C.playback!==void 0&&(C.playback instanceof H&&C.playback.stop(C.media),C.playback instanceof P&&this.mainConnection?.stopRemoteVideo(C.media.mediaId),C.media=void 0),e.mediaIds.delete(j))}};nx();function fB(v,t){d0(t?.logger,t?.onLogMessage);let j,e=new Gx((C,E)=>j.receivePacket(C,E)),B=new ox(v);return j=new ax(B,e.sendDatagram.bind(e),t?.enableHTMLAudioElementFallback??!1),new v0(e,j,t)}var dx=lr(),C0=[],sA=!1;function ur(){sA||typeof window>"u"||(window.addEventListener("beforeunload",()=>{for(let v of C0)v.deref()?.close()}),sA=!0)}var v0=class{constructor(t,j,e){this.version="9";this.supportedTransports=["H3","WebRTC"];this._PlaybackVolume=[1,1];this._CreatedAt=Date.now();this._Options=e??{},this._Options.disableBeforeUnload||ur(),this._ConnectionPool=t,this._MediaController=j,C0.push(new WeakRef(this)),b("plugin initialized")}get playbackVolume(){return this._PlaybackVolume}joinRoom(t){return new Mx(this._ConnectionPool,t,this._Options)}async createAudioPlayback(t){return this._MediaController.createAudioPlayback(t)}async createAudioCapture(t){return this._MediaController.createAudioCapture(t)}async createVideoCapture(t,j){return this._MediaController.createVideoCapture(t,j)}async createVideoPlayback(t){return new P(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(),b("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 C0){let j=t.deref();j!==void 0&&v.push(await j.dump())}return JSON.stringify({timestamp:Date.now(),instances:v,background:await G0()})}globalThis.odin_debug_dump_state=iA;window!==void 0&&(window.odin_debug_dump_state=iA);export{dx as SESSION_ID,fB as createPlugin};
|
|
6435
|
+
\`,new Function(h,f)}function UA(j,r,s,i,o,a){var k=r.length;k<2&&G("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var u=r[1]!==null&&s!==null,c=Br(r),f=!r[0].isVoid,C=r[0],h=r[1],E=[j,G,i,o,Nr,C.fromWireType.bind(C),h?.toWireType.bind(h)],I=2;I<k;++I){var $=r[I];E.push($.toWireType.bind($))}if(!c)for(var I=u?1:2;I<r.length;++I)r[I].destructorFunction!==null&&E.push(r[I].destructorFunction);var J=mt(r,u,f,a)(...E);return gr(j,J)}var Et=(j,r,s,i,o,a)=>{var k=TA(r,s);o=B(i,o),P([],[j],u=>{u=u[0];var c=\`constructor \${u.name}\`;if(u.registeredClass.constructor_body===void 0&&(u.registeredClass.constructor_body=[]),u.registeredClass.constructor_body[r-1]!==void 0)throw new Y(\`Cannot register multiple constructors with identical number of parameters (\${r-1}) for class '\${u.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!\`);return u.registeredClass.constructor_body[r-1]=()=>{z(\`Cannot construct \${u.name} due to unbound types\`,k)},P([],k,f=>(f.splice(1,0,null),u.registeredClass.constructor_body[r-1]=UA(c,f,null,o,a),[])),[]})},br=j=>{j=j.trim();let r=j.indexOf("(");return r===-1?j:j.slice(0,r)},$t=(j,r,s,i,o,a,k,u,c,f)=>{var C=TA(s,i);r=v(r),r=br(r),a=B(o,a,c),P([],[j],h=>{h=h[0];var E=\`\${h.name}.\${r}\`;r.startsWith("@@")&&(r=Symbol[r.substring(2)]),u&&h.registeredClass.pureVirtualFunctions.push(r);function I(){z(\`Cannot call \${E} due to unbound types\`,C)}var $=h.registeredClass.instancePrototype,H=$[r];return H===void 0||H.overloadTable===void 0&&H.className!==h.name&&H.argCount===s-2?(I.argCount=s-2,I.className=h.name,$[r]=I):(Hr($,r,E),$[r].overloadTable[s-2]=I),P([],C,J=>{var y=UA(E,J,h,a,k,c);return $[r].overloadTable===void 0?(y.argCount=s-2,$[r]=y):$[r].overloadTable[s-2]=y,[]}),[]})},Jr=(j,r,s)=>(j instanceof Object||G(\`\${s} with invalid "this": \${j}\`),j instanceof r.registeredClass.constructor||G(\`\${s} incompatible with "this" of type \${j.constructor.name}\`),j.$$.ptr||G(\`cannot call emscripten binding method \${s} on deleted object\`),qA(j.$$.ptr,j.$$.ptrType.registeredClass,r.registeredClass)),Ft=(j,r,s,i,o,a,k,u,c,f)=>{r=v(r),o=B(i,o),P([],[j],C=>{C=C[0];var h=\`\${C.name}.\${r}\`,E={get(){z(\`Cannot access \${h} due to unbound types\`,[s,k])},enumerable:!0,configurable:!0};return c?E.set=()=>z(\`Cannot access \${h} due to unbound types\`,[s,k]):E.set=I=>G(h+" is a read-only property"),Object.defineProperty(C.registeredClass.instancePrototype,r,E),P([],c?[s,k]:[s],I=>{var $=I[0],H={get(){var y=Jr(this,C,h+" getter");return $.fromWireType(o(a,y))},enumerable:!0};if(c){c=B(u,c);var J=I[1];H.set=function(y){var jA=Jr(this,C,h+" setter"),L=[];c(f,jA,J.toWireType(L,y)),Nr(L)}}return Object.defineProperty(C.registeredClass.instancePrototype,r,H),[]}),[]})},Kr=[],X=[0,1,,1,null,1,!0,1,!1,1],vt=j=>{j>9&&--X[j+1]===0&&(X[j]=void 0,Kr.push(j))},VA={toValue:j=>(j||G(\`Cannot use deleted val. handle = \${j}\`),X[j]),toHandle:j=>{switch(j){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:{let r=Kr.pop()||X.length;return X[r]=j,X[r+1]=1,r}}}},gt={name:"emscripten::val",fromWireType:j=>{var r=VA.toValue(j);return vt(j),r},toWireType:(j,r)=>VA.toHandle(r),readValueFromPointer:fA,destructorFunction:null},Lt=j=>N(j,gt),Ht=(j,r)=>{switch(r){case 4:return function(s){return this.fromWireType(fr[s>>2])};case 8:return function(s){return this.fromWireType(Cr[s>>3])};default:throw new TypeError(\`invalid float width (\${r}): \${j}\`)}},yt=(j,r,s)=>{r=v(r),N(j,{name:r,fromWireType:i=>i,toWireType:(i,o)=>o,readValueFromPointer:Ht(r,s),destructorFunction:null})},_t=(j,r,s,i,o,a,k,u)=>{var c=TA(r,s);j=v(j),j=br(j),o=B(i,o,k),yr(j,function(){z(\`Cannot call \${j} due to unbound types\`,c)},r-1),P([],c,f=>{var C=[f[0],null].concat(f.slice(1));return xr(j,UA(j,C,null,o,a,k),r-1),[]})},xt=(j,r,s,i,o)=>{r=v(r);let a=i===0,k=c=>c;if(a){var u=32-8*s;k=c=>c<<u>>>u,o=k(o)}N(j,{name:r,fromWireType:k,toWireType:(c,f)=>f,readValueFromPointer:Er(r,s,i!==0),destructorFunction:null})},Dt=(j,r,s)=>{var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=i[r];function a(k){var u=m[k>>2],c=m[k+4>>2];return new o(U.buffer,c,u)}s=v(s),N(j,{name:s,fromWireType:a,readValueFromPointer:a},{ignoreDuplicateRegistrations:!0})},Nt=(j,r,s,i)=>{if(!(i>0))return 0;for(var o=s,a=s+i-1,k=0;k<j.length;++k){var u=j.codePointAt(k);if(u<=127){if(s>=a)break;r[s++]=u}else if(u<=2047){if(s+1>=a)break;r[s++]=192|u>>6,r[s++]=128|u&63}else if(u<=65535){if(s+2>=a)break;r[s++]=224|u>>12,r[s++]=128|u>>6&63,r[s++]=128|u&63}else{if(s+3>=a)break;r[s++]=240|u>>18,r[s++]=128|u>>12&63,r[s++]=128|u>>6&63,r[s++]=128|u&63,k++}}return r[s]=0,s-o},Bt=(j,r,s)=>Nt(j,_,r,s),bt=j=>{for(var r=0,s=0;s<j.length;++s){var i=j.charCodeAt(s);i<=127?r++:i<=2047?r+=2:i>=55296&&i<=57343?(r+=4,++s):r+=3}return r},Or=globalThis.TextDecoder&&new TextDecoder,Pr=(j,r,s,i)=>{var o=r+s;if(i)return o;for(;j[r]&&!(r>=o);)++r;return r},wr=(j,r=0,s,i)=>{var o=Pr(j,r,s,i);if(o-r>16&&j.buffer&&Or)return Or.decode(j.subarray(r,o));for(var a="";r<o;){var k=j[r++];if(!(k&128)){a+=String.fromCharCode(k);continue}var u=j[r++]&63;if((k&224)==192){a+=String.fromCharCode((k&31)<<6|u);continue}var c=j[r++]&63;if((k&240)==224?k=(k&15)<<12|u<<6|c:k=(k&7)<<18|u<<12|c<<6|j[r++]&63,k<65536)a+=String.fromCharCode(k);else{var f=k-65536;a+=String.fromCharCode(55296|f>>10,56320|f&1023)}}return a},Jt=(j,r,s)=>j?wr(_,j,r,s):"",Kt=(j,r)=>{r=v(r);var s=!0;N(j,{name:r,fromWireType(i){var o=m[i>>2],a=i+4,k;if(s)k=Jt(a,o,!0);else{k="";for(var u=0;u<o;++u)k+=String.fromCharCode(_[a+u])}return b(i),k},toWireType(i,o){o instanceof ArrayBuffer&&(o=new Uint8Array(o));var a,k=typeof o=="string";k||ArrayBuffer.isView(o)&&o.BYTES_PER_ELEMENT==1||G("Cannot pass non-string to std::string"),s&&k?a=bt(o):a=o.length;var u=SA(4+a+1),c=u+4;if(m[u>>2]=a,k)if(s)Bt(o,c,a+1);else for(var f=0;f<a;++f){var C=o.charCodeAt(f);C>255&&(b(u),G("String has UTF-16 code units that do not fit in 8 bits")),_[c+f]=C}else _.set(o,c);return i!==null&&i.push(b,u),u},readValueFromPointer:fA,destructorFunction(i){b(i)}})},Mr=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Ot=(j,r,s)=>{var i=j>>1,o=Pr(Z,i,r/2,s);if(o-i>16&&Mr)return Mr.decode(Z.subarray(i,o));for(var a="",k=i;k<o;++k){var u=Z[k];a+=String.fromCharCode(u)}return a},Pt=(j,r,s)=>{if(s??=2147483647,s<2)return 0;s-=2;for(var i=r,o=s<j.length*2?s/2:j.length,a=0;a<o;++a){var k=j.charCodeAt(a);aA[r>>1]=k,r+=2}return aA[r>>1]=0,r-i},wt=j=>j.length*2,Mt=(j,r,s)=>{for(var i="",o=j>>2,a=0;!(a>=r/4);a++){var k=m[o+a];if(!k&&!s)break;i+=String.fromCodePoint(k)}return i},Tt=(j,r,s)=>{if(s??=2147483647,s<4)return 0;for(var i=r,o=i+s-4,a=0;a<j.length;++a){var k=j.codePointAt(a);if(k>65535&&a++,kA[r>>2]=k,r+=4,r+4>o)break}return kA[r>>2]=0,r-i},Ut=j=>{for(var r=0,s=0;s<j.length;++s){var i=j.codePointAt(s);i>65535&&s++,r+=4}return r},Vt=(j,r,s)=>{s=v(s);var i,o,a;r===2?(i=Ot,o=Pt,a=wt):(i=Mt,o=Tt,a=Ut),N(j,{name:s,fromWireType:k=>{var u=m[k>>2],c=i(k+4,u*r,!0);return b(k),c},toWireType:(k,u)=>{typeof u!="string"&&G(\`Cannot pass non-string to C++ string type \${s}\`);var c=a(u),f=SA(4+c+r);return m[f>>2]=c/r,o(u,f+4,c+r),k!==null&&k.push(b,f),f},readValueFromPointer:fA,destructorFunction(k){b(k)}})},St=(j,r)=>{r=v(r),N(j,{isVoid:!0,name:r,fromWireType:()=>{},toWireType:(s,i)=>{}})},Rt=j=>{OA("OOM")},Wt=j=>{var r=_.length;j>>>=0,Rt(j)},Qt=j=>52,zt=9007199254740992,Xt=-9007199254740992,Zt=j=>j<Xt||j>zt?NaN:Number(j);function Yt(j,r,s,i){return r=Zt(r),70}var Ae=[null,[],[]],re=(j,r)=>{var s=Ae[j];r===0||r===10?((j===1?ir:oA)(wr(s)),s.length=0):s.push(r)},je=(j,r,s,i)=>{for(var o=0,a=0;a<s;a++){var k=m[r>>2],u=m[r+4>>2];r+=8;for(var c=0;c<u;c++)re(j,_[k+c]);o+=u}return m[i>>2]=o,0};if(et(),Ct(),e.noExitRuntime&&(Rj=e.noExitRuntime),e.print&&(ir=e.print),e.printErr&&(oA=e.printErr),e.wasmBinary&&(or=e.wasmBinary),e.arguments&&(p=e.arguments),e.thisProgram&&(F=e.thisProgram),e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.shift()();var Tr,SA,b,te,ee,Ur,Vr;function ne(j){Tr=j.w,SA=e._malloc=j.y,b=e._free=j.z,te=Ur=j.u,ee=Vr=j.x}var se={g:zj,r:Xj,f:Yj,l:At,k:ht,j:Et,d:$t,a:Ft,s:Lt,i:yt,n:_t,c:xt,b:Dt,t:Kt,e:Vt,m:St,o:Wt,q:Qt,p:Yt,h:je};function le(){bj();function j(){e.calledRun=!0,!ar&&(Jj(),kr?.(e),e.onRuntimeInitialized?.(),Kj())}e.setStatus?(e.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>e.setStatus(""),1),j()},1)):j()}var rA;return rA=await Uj(),le(),cr?t=e:t=new Promise((j,r)=>{kr=j,ur=r}),t}})();typeof Lj=="object"&&typeof JA=="object"?(JA.exports=er,JA.exports.default=er):typeof define=="function"&&define.amd&&define([],()=>er)});var w={};qe(w,{AdditionalCaptureBlocks:()=>pe,AdditionalPlaybackBlocks:()=>Ge,ClockJumpCheckInterval:()=>ve,ClockJumpThreshold:()=>ge,ConnectInterval:()=>Je,ConnectTimeout:()=>Ne,DefaultRefreshRate:()=>he,DefaultVideoCodec:()=>Ke,HealthCheckTimeout:()=>Fe,MainConnectionPingInterval:()=>Le,MaxNumberOfDecoders:()=>Ee,MinDBFs:()=>Qr,MinTokenLifetime:()=>Be,MinTokenRefreshInterval:()=>be,PlaybackPreload:()=>Ie,RenderQuantumSize:()=>$e,VadPreload:()=>me,WebRtcAnswerTimeout:()=>xe,WebRtcIceTimeout:()=>ye,WebRtcMaxNegotiationAttempts:()=>De,WebRtcStatsSnapshotInterval:()=>He,WebRtcTimeout:()=>_e});var Ge=3,pe=3,Ie=3,he=250,me=3,Ee=512,$e=128,Qr=-758.596,Fe=1e4,ve=1e3,ge=1e4,Le=3e3,He=1e3,ye=3e3,_e=1e4,xe=1e4,De=3,Ne=5e3,Be=6e4,be=5e3,Je=[0,100,200,200,500],Ke="H264";function M(n,A,t){return n.postMessage(A,t)}function zr(n){return[n.values[0],n.values[1]]}function IA(n,A){n.values[0]=A[0],n.values[1]=A[1]}function hA(n,A){return n.values[2+A*5]}function Xr(n,A,t){n.values[2+A*5]=t}function Zr(n,A){let t=2+A*5+1;return[n.values[t+0],n.values[t+1]]}function mA(n,A,t){let e=2+A*5+1;n.values[e+0]=t[0],n.values[e+1]=t[1]}function Yr(n,A){return n.values[2+A*5+3]}function Aj(n,A,t){n.values[2+A*5+3]=t}function rj(n,A){return n.values[2+A*5+4]}function jj(n,A,t){n.values[2+A*5+4]=t}function EA(n){return n.values[0]!==0}function $A(n){return n.values[1]}function FA(n){return n.values[2]}function tj(n){return n.values[3]}function vA(n,A){return n.values[3]=A}function ej(n){return n?Array.from(n).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var Oe;(n=>{let A;(t=>(t[t.InvalidPassword=-1]="InvalidPassword",t[t.Unknown=0]="Unknown",t[t.Unencrypted=1]="Unencrypted",t[t.Encrypted=2]="Encrypted"))(A=n.PeerCipherStatus||={})})(Oe||={});function oj(n){return{type:"Success",value:n}}function x(n){return{type:"Failure",reason:n}}var{Deno:nj}=globalThis,Pe=typeof nj?.noColor=="boolean"?nj.noColor:!1,we=!Pe;function zA(n,A){return{open:\`\\x1B[\${n.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function XA(n,A){return we?\`\${A.open}\${n.replace(A.regexp,A.open)}\${A.close}\`:n}function QA(n){return XA(n,zA([0],0))}function sj(n){return XA(n,zA([1],22))}function Me(n){return XA(n,zA([2],22))}var Jn=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),Te=new Date,gA=(n=>(n[n.CRITICAL=0]="CRITICAL",n[n.ERROR=1]="ERROR",n[n.WARN=2]="WARN",n[n.INFO=3]="INFO",n[n.DEBUG=4]="DEBUG",n))(gA||{}),aj={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},Ue={4:Me,3:QA,2:QA,1:sj,0:sj};function Ve({message:n}){return String(n)}function lj(n){return JSON.stringify({timestamp:n.date.toISOString(),level:gA[n.level],message:n.message,extra:n.extra})}function ij(n){function A(q,p){return[Math.floor(q/p),q%p]}function t(){let q,p=n.date.valueOf()-Te.valueOf();[p,q]=A(p,1e3);let[F,D]=A(p,60);return\`\${F.toString().padStart(4,"0")}:\${D.toString().padStart(2,"0")}.\${q.toString().padStart(3,"0")}\`}function e(){return n.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(n.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(n.extra)}let l=aj[n.level],d=n.logger.name!==void 0?\`@\${n.logger.name}\`:"";return\`\${QA(t())}\${d} \${l} \${Ue[n.level](String(n.message))}\${e()}\`}function Se(n){let A=\`[\${n.date.toISOString()}]\`,t=\`[\${gA[n.level]}]\`,e=n.logger.name!==void 0?\`[\${n.logger.name}] \`:"",l=aj[n.level];return\`\${A} \${l} \${t.padEnd(7," ")} \${e}\${n.message}\`}function Re(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var kj=class{static sparse=Ve;static json=lj;static pretty=ij;static structured=Se;static default=Re()?ij:lj;constructor(){}};var We=class{formatter;consoleObject;filter;constructor(n=kj.default,A=4,t=console){this.filter=A,this.formatter=n,this.consoleObject=t}handle(n){let A=this.formatter(n);switch(n.level){case 0:case 1:this.consoleObject.error(A);break;case 2:this.consoleObject.warn(A);break;case 3:this.consoleObject.info(A);break;case 4:this.consoleObject.debug(A);break}}};var V=class{#A;sinks;filter;parent;get name(){return this.#A}constructor(n,A=void 0,t=[],e=void 0){this.#A=A,this.sinks=t,this.filter=n,this.parent=e}log(n,A,t=void 0){let e={date:new Date,level:n,logger:this,message:A,extra:t};this.filter<n||this.insert(e)}insert(n){if(!(this.filter<n.level)){for(let A of this.sinks)A.filter>=n.level&&A.handle(n);this.parent!==void 0&&this.parent.insert(n)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},tA=globalThis[Symbol.for("odin-global-logger")]??=new V(3,void 0,[new We]),Qe=V.prototype.log.bind(tA,1),ze=V.prototype.log.bind(tA,2),uj=V.prototype.log.bind(tA,3),Xe=V.prototype.log.bind(tA,4),Kn=V.prototype.log.bind(tA);var cj;function dj(n,...A){let t=Ze(A);cj?cj?.info(n,t):uj(n,t)}function Ze(...n){if(n.length===1&&typeof n[0]=="object"&&n[0]!==null)return{...n[0]};if(n.length>0)return{args:n}}function LA(n){return n.connectionId*4294967296+n.mediaId}function qj(n){return{mediaId:n%4294967296,connectionId:Math.floor(n/4294967296)}}function K(n,A,t){let e;switch(A){case"f32":e=n.HEAPF32;break;case"u32":e=n.HEAPU32;break;case"i32":e=n.HEAP32;break;case"u8":e=n.HEAPU8;break;default:throw new Error(\`allocating \${A} is not supported\`)}let l=n._malloc(t*e.BYTES_PER_ELEMENT);if(l===0||l%e.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${t} \${A} array\`);let d=l/e.BYTES_PER_ELEMENT;return e.subarray(d,d+t)}function S(n,A){n._free(A.byteOffset)}function fj(n,A){return{values:K(n,"f32",2+A*5),length:A}}function Cj(n,A){S(n,A.values)}function Gj(n){return{values:K(n,"f32",4)}}function pj(n,A){S(n,A.values)}function Ij(n){let A=n.length,t=0,e=0;for(;e<A;){let l=n.charCodeAt(e++);if((l&4294967168)===0){t++;continue}else if((l&4294965248)===0)t+=2;else{if(l>=55296&&l<=56319&&e<A){let d=n.charCodeAt(e);(d&64512)===56320&&(++e,l=((l&1023)<<10)+(d&1023)+65536)}(l&4294901760)===0?t+=3:t+=4}}return t}function Ye(n,A,t){let e=n.length,l=t,d=0;for(;d<e;){let q=n.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<e){let p=n.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 An=new TextEncoder,rn=50;function jn(n,A,t){An.encodeInto(n,A.subarray(t))}function hj(n,A,t){n.length>rn?jn(n,A,t):Ye(n,A,t)}var tn=4096;function ZA(n,A,t){let e=A,l=e+t,d=[],q="";for(;e<l;){let p=n[e++];if((p&128)===0)d.push(p);else if((p&224)===192){let F=n[e++]&63;d.push((p&31)<<6|F)}else if((p&240)===224){let F=n[e++]&63,D=n[e++]&63;d.push((p&31)<<12|F<<6|D)}else if((p&248)===240){let F=n[e++]&63,D=n[e++]&63,KA=n[e++]&63,O=(p&7)<<18|F<<12|D<<6|KA;O>65535&&(O-=65536,d.push(O>>>10&1023|55296),O=56320|O&1023),d.push(O)}else d.push(p);d.length>=tn&&(q+=String.fromCharCode(...d),d.length=0)}return d.length>0&&(q+=String.fromCharCode(...d)),q}var en=new TextDecoder,nn=200;function sn(n,A,t){let e=n.subarray(A,A+t);return en.decode(e)}function mj(n,A,t){return t>nn?sn(n,A,t):ZA(n,A,t)}var R=class{constructor(A,t){this.type=A,this.data=t}};var g=class n extends Error{constructor(A){super(A);let t=Object.create(n.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:n.name})}};function Ej(n,A,t){let e=t/4294967296,l=t;n.setUint32(A,e),n.setUint32(A+4,l)}function HA(n,A,t){let e=Math.floor(t/4294967296),l=t;n.setUint32(A,e),n.setUint32(A+4,l)}function yA(n,A){let t=n.getInt32(A),e=n.getUint32(A+4);return t*4294967296+e}function $j(n,A){let t=n.getUint32(A),e=n.getUint32(A+4);return t*4294967296+e}var ln=-1,on=4294967296-1,an=17179869184-1;function kn({sec:n,nsec:A}){if(n>=0&&A>=0&&n<=an)if(A===0&&n<=on){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{let t=n/4294967296,e=n&4294967295,l=new Uint8Array(8),d=new DataView(l.buffer);return d.setUint32(0,A<<2|t&3),d.setUint32(4,e),l}else{let t=new Uint8Array(12),e=new DataView(t.buffer);return e.setUint32(0,A),HA(e,4,n),t}}function un(n){let A=n.getTime(),t=Math.floor(A/1e3),e=(A-t*1e3)*1e6,l=Math.floor(e/1e9);return{sec:t+l,nsec:e-l*1e9}}function cn(n){if(n instanceof Date){let A=un(n);return kn(A)}else return null}function dn(n){let A=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:A.getUint32(0),nsec:0};case 8:{let t=A.getUint32(0),e=A.getUint32(4),l=(t&3)*4294967296+e,d=t>>>2;return{sec:l,nsec:d}}case 12:{let t=yA(A,4),e=A.getUint32(0);return{sec:t,nsec:e}}default:throw new g(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${n.length}\`)}}function qn(n){let A=dn(n);return new Date(A.sec*1e3+A.nsec/1e6)}var Fj={type:ln,encode:cn,decode:qn};var T=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Fj)}register({type:A,encode:t,decode:e}){if(A>=0)this.encoders[A]=t,this.decoders[A]=e;else{let l=-1-A;this.builtInEncoders[l]=t,this.builtInDecoders[l]=e}}tryToEncode(A,t){for(let e=0;e<this.builtInEncoders.length;e++){let l=this.builtInEncoders[e];if(l!=null){let d=l(A,t);if(d!=null){let q=-1-e;return new R(q,d)}}}for(let e=0;e<this.encoders.length;e++){let l=this.encoders[e];if(l!=null){let d=l(A,t);if(d!=null){let q=e;return new R(q,d)}}}return A instanceof R?A:null}decode(A,t,e){let l=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return l?l(A,t,e):new R(t,A)}};T.defaultCodec=new T;function fn(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function eA(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):fn(n)?new Uint8Array(n):Uint8Array.from(n)}var Cn=100,Gn=2048,_A=class n{constructor(A){this.entered=!1,this.extensionCodec=A?.extensionCodec??T.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??Cn,this.initialBufferSize=A?.initialBufferSize??Gn,this.sortKeys=A?.sortKeys??!1,this.forceFloat32=A?.forceFloat32??!1,this.ignoreUndefined=A?.ignoreUndefined??!1,this.forceIntegerToFloat=A?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(A){if(this.entered)return this.clone().encodeSharedRef(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(A){if(this.entered)return this.clone().encode(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(A,t){if(t>this.maxDepth)throw new Error(\`Too deep objects in depth \${t}\`);A==null?this.encodeNil():typeof A=="boolean"?this.encodeBoolean(A):typeof A=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(A):this.encodeNumber(A):typeof A=="string"?this.encodeString(A):this.useBigInt64&&typeof A=="bigint"?this.encodeBigInt64(A):this.encodeObject(A,t)}ensureBufferSizeToWrite(A){let t=this.pos+A;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(A){let t=new ArrayBuffer(A),e=new Uint8Array(t),l=new DataView(t);e.set(this.bytes),this.view=l,this.bytes=e}encodeNil(){this.writeU8(192)}encodeBoolean(A){A===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(A){!this.forceIntegerToFloat&&Number.isSafeInteger(A)?A>=0?A<128?this.writeU8(A):A<256?(this.writeU8(204),this.writeU8(A)):A<65536?(this.writeU8(205),this.writeU16(A)):A<4294967296?(this.writeU8(206),this.writeU32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(207),this.writeU64(A)):A>=-32?this.writeU8(224|A+32):A>=-128?(this.writeU8(208),this.writeI8(A)):A>=-32768?(this.writeU8(209),this.writeI16(A)):A>=-2147483648?(this.writeU8(210),this.writeI32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(211),this.writeI64(A)):this.encodeNumberAsFloat(A)}encodeNumberAsFloat(A){this.forceFloat32?(this.writeU8(202),this.writeF32(A)):(this.writeU8(203),this.writeF64(A))}encodeBigInt64(A){A>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(A)):(this.writeU8(211),this.writeBigInt64(A))}writeStringHeader(A){if(A<32)this.writeU8(160+A);else if(A<256)this.writeU8(217),this.writeU8(A);else if(A<65536)this.writeU8(218),this.writeU16(A);else if(A<4294967296)this.writeU8(219),this.writeU32(A);else throw new Error(\`Too long string: \${A} bytes in UTF-8\`)}encodeString(A){let e=Ij(A);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),hj(A,this.bytes,this.pos),this.pos+=e}encodeObject(A,t){let e=this.extensionCodec.tryToEncode(A,this.context);if(e!=null)this.encodeExtension(e);else if(Array.isArray(A))this.encodeArray(A,t);else if(ArrayBuffer.isView(A))this.encodeBinary(A);else if(typeof A=="object")this.encodeMap(A,t);else throw new Error(\`Unrecognized object: \${Object.prototype.toString.apply(A)}\`)}encodeBinary(A){let t=A.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(\`Too large binary: \${t}\`);let e=eA(A);this.writeU8a(e)}encodeArray(A,t){let e=A.length;if(e<16)this.writeU8(144+e);else if(e<65536)this.writeU8(220),this.writeU16(e);else if(e<4294967296)this.writeU8(221),this.writeU32(e);else throw new Error(\`Too large array: \${e}\`);for(let l of A)this.doEncode(l,t+1)}countWithoutUndefined(A,t){let e=0;for(let l of t)A[l]!==void 0&&e++;return e}encodeMap(A,t){let e=Object.keys(A);this.sortKeys&&e.sort();let l=this.ignoreUndefined?this.countWithoutUndefined(A,e):e.length;if(l<16)this.writeU8(128+l);else if(l<65536)this.writeU8(222),this.writeU16(l);else if(l<4294967296)this.writeU8(223),this.writeU32(l);else throw new Error(\`Too large map object: \${l}\`);for(let d of e){let q=A[d];this.ignoreUndefined&&q===void 0||(this.encodeString(d),this.doEncode(q,t+1))}}encodeExtension(A){if(typeof A.data=="function"){let e=A.data(this.pos+6),l=e.length;if(l>=4294967296)throw new Error(\`Too large extension object: \${l}\`);this.writeU8(201),this.writeU32(l),this.writeI8(A.type),this.writeU8a(e);return}let 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),Ej(this.view,this.pos,A),this.pos+=8}writeI64(A){this.ensureBufferSizeToWrite(8),HA(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 YA(n,A){return new _A(A).encodeSharedRef(n)}function xA(n){return\`\${n<0?"-":""}0x\${Math.abs(n).toString(16).padStart(2,"0")}\`}var pn=16,In=16,DA=class{constructor(A=pn,t=In){this.hit=0,this.miss=0,this.maxKeyLength=A,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,t,e){let l=this.caches[e-1];A:for(let d of l){let q=d.bytes;for(let p=0;p<e;p++)if(q[p]!==A[t+p])continue A;return d.str}return null}store(A,t){let e=this.caches[A.length-1],l={bytes:A,str:t};e.length>=this.maxLengthPerKey?e[Math.random()*e.length|0]=l:e.push(l)}decode(A,t,e){let l=this.find(A,t,e);if(l!=null)return this.hit++,l;this.miss++;let d=ZA(A,t,e),q=Uint8Array.prototype.slice.call(A,t,t+e);return this.store(q,d),d}};var Ar="array",lA="map_key",gj="map_value",hn=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new g("The type of key must be string or number but "+typeof n)},rr=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=Ar,t.position=0,t.size=A,t.array=new Array(A)}pushMapState(A){let t=this.getUninitializedStateFromPool();t.type=lA,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===Ar){let e=A;e.size=0,e.array=void 0,e.position=0,e.type=void 0}if(A.type===lA||A.type===gj){let e=A;e.size=0,e.map=void 0,e.readCount=0,e.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},sA=-1,jr=new DataView(new ArrayBuffer(0)),mn=new Uint8Array(jr.buffer);try{jr.getInt8(0)}catch(n){if(!(n instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var vj=new RangeError("Insufficient data"),En=new DA,NA=class n{constructor(A){this.totalPos=0,this.pos=0,this.view=jr,this.bytes=mn,this.headByte=sA,this.stack=new rr,this.entered=!1,this.extensionCodec=A?.extensionCodec??T.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??hn}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=sA,this.stack.reset()}setBuffer(A){let t=eA(A);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(A){if(this.headByte===sA&&!this.hasRemaining(1))this.setBuffer(A);else{let t=this.bytes.subarray(this.pos),e=eA(A),l=new Uint8Array(t.length+e.length);l.set(t),l.set(e,t.length),this.setBuffer(l)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:t,pos:e}=this;return new RangeError(\`Extra \${t.byteLength-e} of \${t.byteLength} byte(s) found at buffer[\${A}]\`)}decode(A){if(this.entered)return this.clone().decode(A);try{this.entered=!0,this.reinitializeState(),this.setBuffer(A);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(A){if(this.entered){yield*this.clone().decodeMulti(A);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(A);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(A){if(this.entered)return this.clone().decodeAsync(A);try{this.entered=!0;let t=!1,e;for await(let p of A){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(p);try{e=this.doDecodeSync(),t=!0}catch(F){if(!(F instanceof RangeError))throw F}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return e}let{headByte:l,pos:d,totalPos:q}=this;throw new RangeError(\`Insufficient data in parsing \${xA(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,t){if(this.entered){yield*this.clone().decodeMultiAsync(A,t);return}try{this.entered=!0;let e=t,l=-1;for await(let d of A){if(t&&l===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(d),e&&(l=this.readArraySize(),e=!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(),t;if(A>=224)t=A-256;else if(A<192)if(A<128)t=A;else if(A<144){let l=A-128;if(l!==0){this.pushMapState(l),this.complete();continue A}else t={}}else if(A<160){let l=A-144;if(l!==0){this.pushArrayState(l),this.complete();continue A}else t=[]}else{let l=A-160;t=this.decodeString(l,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 l=this.lookU8();t=this.decodeString(l,1)}else if(A===218){let l=this.lookU16();t=this.decodeString(l,2)}else if(A===219){let l=this.lookU32();t=this.decodeString(l,4)}else if(A===220){let l=this.readU16();if(l!==0){this.pushArrayState(l),this.complete();continue A}else t=[]}else if(A===221){let l=this.readU32();if(l!==0){this.pushArrayState(l),this.complete();continue A}else t=[]}else if(A===222){let l=this.readU16();if(l!==0){this.pushMapState(l),this.complete();continue A}else t={}}else if(A===223){let l=this.readU32();if(l!==0){this.pushMapState(l),this.complete();continue A}else t={}}else if(A===196){let l=this.lookU8();t=this.decodeBinary(l,1)}else if(A===197){let l=this.lookU16();t=this.decodeBinary(l,2)}else if(A===198){let l=this.lookU32();t=this.decodeBinary(l,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 l=this.lookU8();t=this.decodeExtension(l,1)}else if(A===200){let l=this.lookU16();t=this.decodeExtension(l,2)}else if(A===201){let l=this.lookU32();t=this.decodeExtension(l,4)}else throw new g(\`Unrecognized type byte: \${xA(A)}\`);this.complete();let e=this.stack;for(;e.length>0;){let l=e.top();if(l.type===Ar)if(l.array[l.position]=t,l.position++,l.position===l.size)t=l.array,e.release(l);else continue A;else if(l.type===lA){if(t==="__proto__")throw new g("The key __proto__ is not allowed");l.key=this.mapKeyConverter(t),l.type=gj;continue A}else if(l.map[l.key]=t,l.readCount++,l.readCount===l.size)t=l.map,e.release(l);else{l.key=null,l.type=lA;continue A}}return t}}readHeadByte(){return this.headByte===sA&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=sA}readArraySize(){let A=this.readHeadByte();switch(A){case 220:return this.readU16();case 221:return this.readU32();default:{if(A<160)return A-144;throw new g(\`Unrecognized array type byte: \${xA(A)}\`)}}}pushMapState(A){if(A>this.maxMapLength)throw new g(\`Max length exceeded: map length (\${A}) > maxMapLengthLength (\${this.maxMapLength})\`);this.stack.pushMapState(A)}pushArrayState(A){if(A>this.maxArrayLength)throw new g(\`Max length exceeded: array length (\${A}) > maxArrayLength (\${this.maxArrayLength})\`);this.stack.pushArrayState(A)}decodeString(A,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(A,t):this.decodeBinary(A,t)}decodeUtf8String(A,t){if(A>this.maxStrLength)throw new g(\`Max length exceeded: UTF-8 byte length (\${A}) > maxStrLength (\${this.maxStrLength})\`);if(this.bytes.byteLength<this.pos+t+A)throw vj;let e=this.pos+t,l;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?l=this.keyDecoder.decode(this.bytes,e,A):l=mj(this.bytes,e,A),this.pos+=t+A,l}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===lA:!1}decodeBinary(A,t){if(A>this.maxBinLength)throw new g(\`Max length exceeded: bin length (\${A}) > maxBinLength (\${this.maxBinLength})\`);if(!this.hasRemaining(A+t))throw vj;let e=this.pos+t,l=this.bytes.subarray(e,e+A);return this.pos+=t+A,l}decodeExtension(A,t){if(A>this.maxExtLength)throw new g(\`Max length exceeded: ext length (\${A}) > maxExtLength (\${this.maxExtLength})\`);let e=this.view.getInt8(this.pos+t),l=this.decodeBinary(A,t+1);return this.extensionCodec.decode(l,e,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let A=this.view.getUint8(this.pos);return this.pos++,A}readI8(){let A=this.view.getInt8(this.pos);return this.pos++,A}readU16(){let A=this.view.getUint16(this.pos);return this.pos+=2,A}readI16(){let A=this.view.getInt16(this.pos);return this.pos+=2,A}readU32(){let A=this.view.getUint32(this.pos);return this.pos+=4,A}readI32(){let A=this.view.getInt32(this.pos);return this.pos+=4,A}readU64(){let A=$j(this.view,this.pos);return this.pos+=8,A}readI64(){let A=yA(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 tr(n,A){return new NA(A).decode(n)}var iA=class n{constructor(A,t,e,l,d){this.mediaIds=A;this.sequenceNumber=t;this.timeStamp=e;this.isEndOfSpurt=l;this.payload=d}static parse(A){let t;try{t=tr(A)}catch{return x("not valid msgpack")}if(!Array.isArray(t))return x("container must be an array");if(t.length<6)return x("missing fields");if(t[0]!==1)return x("unknown type");if(!Array.isArray(t[1]))return x("media ids must be an array");if(!t[1].every(D=>typeof D=="number"))return x("media ids must be numbers");if(typeof t[2]!="number")return x("sequence number must be a number");if(typeof t[3]!="number")return x("timestamp must be a number");if(typeof t[4]!="number")return x("flags must be a number");let e=t[1],l=t[2]>>>0,d=t[3]>>>0,p=(t[4]&1)!==0,F=t[t.length-1];return F instanceof Uint8Array?oj(new n(e,l,d,p,F)):x("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(YA(t,{forceFloat32:!0,ignoreUndefined:!0}))}};var BA=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,w.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=Gj(this.wasm),this.outBuffer=K(this.wasm,"u8",1270),vA(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(){pj(this.wasm,this.information),S(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){dj(\`failed encoding packet: \${t}\`);return}if(this.timestamp=this.timestamp+1800>>0,t===1)continue;this.sequenceNumber=this.sequenceNumber+1>>0;let e=this.active&&!this.encoder.active;this.active=this.encoder.active,this.monitoring=this.connections.some(l=>l.id===0);for(let l of this.connections){if(this.monitoring&&l.id!==0)continue;let d=new iA(l.mediaIds,this.sequenceNumber,this.timestamp,e,this.outBuffer.subarray(0,t));M(globalThis,["sendPacket",{connectionId:l.id,packet:d.toBytes()}])}}}onMessage(A){let[t,e]=A;switch(t){case"captureSetVad":this?.setVad(e);break;case"captureSetMedias":this?.setMedias(e.connections);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){return{sequenceNumber:this.sequenceNumber,timestamp:this.timestamp,connections:this.connections.map(A=>\`\${A.id} => \${A.mediaIds.join(",")}\`),active:this.active,monitoring:this.monitoring,information:{active:EA(this.information),speechProbability:$A(this.information),rmsDBFS:FA(this.information),volume:tj(this.information)},encoder:{sample_rate:this.encoder.sample_rate,fec_packet_loss:this.encoder.fec_packet_loss,voip:this.encoder.voip,vad_preload:this.encoder.vad_preload,complexity:this.encoder.complexity,speech_probability:this.encoder.speech_probability,rms_dbfs:this.encoder.rms_dbfs,active:this.encoder.active,speech_detection_enabled:this.encoder.speech_detection_enabled,speech_detection_going_active:this.encoder.speech_detection_going_active,speech_detection_going_inactive:this.encoder.speech_detection_going_inactive,volume_gate_enabled:this.encoder.volume_gate_enabled,volume_gate_going_active:this.encoder.volume_gate_going_active,volume_gate_going_inactive:this.encoder.volume_gate_going_inactive}}}},bA=class{constructor(A){this.wasm=A;this.medias=new Map;this.stats={numberPackets:0,numberTicks:0,numberPacketError:0,numberPacketsMediaNotFound:0,numberTicksWithAudio:0};this.largestIndex=-1;this.decoders=K(this.wasm,"u32",w.MaxNumberOfDecoders),this.information=fj(this.wasm,w.MaxNumberOfDecoders),IA(this.information,[1,1])}close(){Cj(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,t){this.stats.numberPackets++;let e=iA.parse(t);if(e.type==="Failure"){this.stats.numberPacketError++;let l=Array.from(t).map(d=>d.toString(16).padStart(2,"0")).join("");console.error(\`failed decoding audio packet; reason: \${e.reason}, connection: \${A}, dump: \${l}\`);return}for(let l of e.value.mediaIds){let d=this.medias.get(LA({connectionId:A,mediaId:l}));if(d===void 0){this.stats.numberPacketsMediaNotFound++;continue}d.lastPacket=t;let q=K(this.wasm,"u8",e.value.payload.length);q.set(e.value.payload),d.decoder.push(e.value.sequenceNumber,e.value.timeStamp,e.value.isEndOfSpurt,q.byteOffset,q.length)}}insertMedia(A,t,e,l=[1,1]){let d=LA({connectionId:t,mediaId:e}),q=new this.wasm.Decoder;this.medias.set(d,{index:A,decoder:q,lastPacket:void 0}),this.decoders[A]=q.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),mA(this.information,A,l),jj(this.information,A,0),Aj(this.information,A,0)}removeMedia(A,t,e){let l=LA({connectionId:t,mediaId:e}),d=this.medias.get(l);if(!(d===void 0||d.index!==A)&&(this.medias.delete(l),Xr(this.information,A,0),this.decoders[A]=0,d.decoder.delete(),A===this.largestIndex)){for(A=A-1;A>=0&&this.decoders[A]===0;A--);this.largestIndex=A}}decode(A){return{hasAudio:this.wasm.pop_many(this.decoders.byteOffset,this.information.values.byteOffset,this.largestIndex+1,A.byteOffset)}}onMessage(A){let[t,e]=A;switch(t){case"playbackReceivePacket":this.receivePacket(e.connectionId,e.packet);break;case"playbackUpdateMedias":for(let{index:l,connectionId:d,mediaId:q}of e.removed)this.removeMedia(l,d,q);for(let{index:l,connectionId:d,mediaId:q,volume:p}of e.added)this.insertMedia(l,d,q,p);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){let A=[];for(let[t,e]of this.medias){let l=qj(t);A.push({index:e.index,connectionId:l.connectionId,mediaId:l.mediaId,rmsDBFS:hA(this.information,e.index),volume:Zr(this.information,e.index),voicedBlocks:rj(this.information,e.index),silentBlocks:Yr(this.information,e.index),time:e.decoder.time,consecutive_silence:e.decoder.consecutive_silence,last_voiced_time_point:e.decoder.last_voiced_time_point,sequence_number:e.decoder.sequence_number,packetsSeen:e.decoder.packets_seen,packetsInvalid:e.decoder.packets_invalid,packetsTooLate:e.decoder.packets_too_late,packetsTooEarly:e.decoder.packets_too_early,packetsRepeated:e.decoder.packets_repeated,packetsProcessed:e.decoder.packets_processed,packetsLost:e.decoder.packets_lost,rewinds:e.decoder.rewinds,cacheLength:e.decoder.cache_length,lastPacket:ej(e.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:zr(this.information),decoders:A}}};var Dj=Ce(Hj()),yj=(0,Dj.default)(),_j,xj;globalThis.addEventListener("message",nr);async function nr(n){let A=n.data,[t,e]=A;switch(t){case"captureInit":e.workletPort.onmessage=nr,_j=new sr(e.sampleRate,await yj,e.refreshRate);break;case"playbackInit":e.workletPort.onmessage=nr,xj=new lr(await yj,e.workletPort,e.refreshRate);break;case"close":globalThis.close();break}_j?.onMessage(A),xj?.onMessage(A)}var sr=class extends BA{constructor(t,e,l){super(t,e);this.sampleRate=t;this.inBuffer=K(this.wasm,"f32",t*.02),this.updateHandle=setInterval(()=>this.update(),l),M(globalThis,["captureReady",{}])}close(){super.close(),S(this.wasm,this.inBuffer),clearInterval(this.updateHandle)}onMessage(t){super.onMessage(t);let[e,l]=t;switch(e){case"captureSetVolume":this.setVolume(l.value);break;case"captureTick":this.tick(l.buffer);break}}setVolume(t){vA(this.information,t)}tick(t){this.inBuffer.set(t,0),this.encode(this.inBuffer)}update(){M(globalThis,["captureUpdate",{active:EA(this.information),rmsDBFs:FA(this.information),speechProbability:$A(this.information)}])}dump(){return{type:"unshared capture worker",sampleRate:this.sampleRate,...super.dump()}}},lr=class extends bA{constructor(t,e,l){super(t);this.workletPort=e;this.id=w.PlaybackPreload,this.outBuffer=K(this.wasm,"f32",48e3*.02*2),this.updateHandle=setInterval(()=>this.update(),l),M(globalThis,["playbackReady",{}])}close(){super.close(),S(this.wasm,this.outBuffer),clearInterval(this.updateHandle)}onMessage(t){super.onMessage(t);let[e,l]=t;switch(e){case"playbackSetVolume":this.setVolume(l.index,l.value);break;case"playbackTick":this.tick();break}}setVolume(t,e){t==="global"?IA(this.information,e):mA(this.information,t,e)}tick(){this.stats.numberTicks++,this.id+=1;let{hasAudio:t}=this.decode(this.outBuffer);if(t){let e=this.outBuffer.slice();M(this.workletPort,["samples",{id:this.id,buffer:e}],[e.buffer])}}update(){let t=new Float32Array(this.information.length*2);for(let l=0;l<=this.largestIndex;l++)t[l]=hA(this.information,l);let e=[];for(let[l,d]of this.medias)e[d.index]={packetsBuffered:d.decoder.cache_length,packetsSeen:d.decoder.packets_seen,packetsProcessed:d.decoder.packets_processed,packetsTooEarly:d.decoder.packets_too_early,packetsTooLate:d.decoder.packets_too_late,packetsDropped:0,packetsInvalid:d.decoder.packets_invalid,packetsRepeated:d.decoder.packets_repeated,packetsLost:d.decoder.packets_lost};M(globalThis,["playbackUpdate",{activities:t,jitterStats:e}],[t.buffer])}dump(){return{type:"unshared playback worker",id:this.id,...super.dump()}}};})();
|
|
6436
|
+
`});var Yx,_0=q(()=>{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 eF}from"@4players/odin-common";function vF(v,D,j,e,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,D,j,B,C,E,e)})}async function CF(v,D=i.DefaultRefreshRate){if(v.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[j,e]=await Y(Zx,Yx,v,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return ix.create(v,D,j,e)}var BF,sx,ix,H0=q(()=>{"use strict";u();nx();y0();_0();BF=new eF;sx=class v extends X{constructor(j,e,B,C,E){super(j,e,B,C,E);this._Activity=_;this._SpeechProbability=0;e.addEventListener("message",this._OnMessages.bind(this))}static async create(j,e,B,C,E,f,s){let{port1:b,port2:d}=new MessageChannel;return c(E,["captureInit",{sampleRate:j.sampleRate,refreshRate:C,workletPort:b}],[b]),await U(E,"captureReady"),c(f.port,["init",{workerPort:d}],[d]),new v(f,E,e,B,s)}get activity(){return this._Activity}get speechProbability(){return this._SpeechProbability}setVolume(j){c(this.worker,["captureSetVolume",{value:j}])}_OnMessages(j){super._OnMessages(j);let[e,B]=j.data;e==="captureUpdate"&&(this._Activity={isSilent:!B.active,rmsDBFS:B.rmsDBFs},this._SpeechProbability=B.speechProbability)}},ix=class v extends z{constructor(j,e,B){super(j,e,B);this.activities=new Float32Array;this.jitterStats=[]}static async create(j,e,B,C){let{port1:E,port2:f}=new MessageChannel;return c(B,["playbackInit",{workletPort:E,refreshRate:e}],[E]),await U(B,"playbackReady"),c(C.port,["init",{workerPort:f}],[f]),new v(j,C,B)}getActivity(j){let e=this.medias.get(m(j));if(e===void 0)return;let B=this.activities.at(e.index);if(B!==void 0)return B===0?_:{isSilent:!1,rmsDBFS:B}}getJitterStats(j){let e=this.medias.get(m(j));if(e===void 0)return;let B=this.jitterStats.at(e.index);if(B!==void 0)return B}setGlobalVolume(j){c(this.worker,["playbackSetVolume",{index:"global",value:j}])}setVolume(j,e){let B=this.medias.get(m(j));B!==void 0&&c(this.worker,["playbackSetVolume",{index:B.index,value:e}])}_GetFreeIndex(){let j=super._GetFreeIndex();if(j!==void 0)return j;if(this.medias.size<i.MaxNumberOfDecoders)return this.medias.size}_OnMessages(j){super._OnMessages(j);let[e,B]=j.data;e==="playbackUpdate"&&(this.activities=B.activities,this.jitterStats=B.jitterStats)}}});u();import{Backend as r,generateUUID as cr}from"@4players/odin-common";u();import{Backend as x,JITTER_STATS_INITIAL as K0,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 VA,sleep as UA,success as WA}from"@4players/odin-common";async function h0(v,D,j){let e;if(D.device?.device.kind==="track"&&D.device?.device.audioTrack)e=new MediaStream([D.device.device.audioTrack]);else{let E=D.device?{exact:D.device.device.deviceId==="default"?void 0:D.device.device.deviceId}:void 0;try{let f=await Promise.race([navigator.mediaDevices.getUserMedia({audio:{echoCancellation:j.echoCanceller,noiseSuppression:j.noiseSuppression!=="None",autoGainControl:j.gainController,echoCancellationType:"system",deviceId:E}}),UA(3e4,"timeout")]);if(f==="timeout")return p0("getUserMedia; timeout");e=f}catch(f){return p0(`getUserMedia; ${f}`)}}let B=e.getAudioTracks()[0].getSettings().sampleRate,C=await v.audioContexts.acquire(B);return WA(C.createMediaStreamSource(e))}function W(v){v.getTracks().forEach(D=>{D.stop(),v.removeTrack(D)})}async function q0(v){return new L({deviceId:v.id,kind:"track",name:v.label??"MediaStreamTrack",audioTrack:v},!1)}async function fx(){if(VA()){let B=await QA("microphone");(B==="granted"||B===!1)&&await zA("audio")}let v=(await navigator.mediaDevices.enumerateDevices()).filter(B=>!!B.label),D=[],j=new L({deviceId:"default",name:"Default",kind:"audioinput"},!0),e=new L({deviceId:"default",name:"Default",kind:"audiooutput"},!0);D.push(j),D.push(e);for(let B of v){if(B.deviceId==="default"){B.kind==="audioinput"&&(j=new L({deviceId:"default",name:B.label,kind:"audioinput"},!0),D[0]=j),B.kind==="audiooutput"&&(e=new L({deviceId:"default",name:B.label,kind:"audiooutput"},!0),D[1]=e);continue}B.kind==="audioinput"&&D.push(new L({deviceId:B.deviceId,name:B.label,kind:"audioinput"},!1)),B.kind==="audiooutput"&&D.push(new L({deviceId:B.deviceId,name:B.label,kind:"audiooutput"},!1))}return D}async function QA(v){try{return(await navigator.permissions.query({name:v})).state}catch{return!1}}async function zA(v){try{let D=await navigator.mediaDevices.getUserMedia({[v]:!0});return D?.getTracks().forEach(j=>{j.stop(),D.removeTrack(j)}),!0}catch{return!1}}u();import{isSafariBrowser as EF,isSharedArrayBufferCapable as fF}from"@4players/odin-common";var N0=fF()&&!EF()?Promise.resolve().then(()=>($0(),g0)):Promise.resolve().then(()=>(H0(),L0));async function w0(v,D,j,e){return N0.then(B=>B.createCaptureWorker(v,D,j,e,i.DefaultRefreshRate))}async function P0(v){return N0.then(D=>D.createPlaybackWorker(v,i.DefaultRefreshRate))}var w=class{constructor(D,j){this.controller=D;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(D=>k("device-change handler failed",D))};j.apm&&this.setApm(j.apm).catch(console.error),j.vad&&this.setVad(j.vad),typeof j.volume<"u"&&this.setVolume(j.volume).catch(console.error),this.uid=sF(),this.#x=j.customType,this.#A=j.ref}#x;#A;_enqueue(D){let j=this._Queue.then(D,D);return this._Queue=j.catch(()=>{}),j}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(D,j){let e=this._Medias.get(j.connectionId);e===void 0&&this._Medias.set(j.connectionId,e=new Set),o(`starting audio capture media ${j.mediaId} on connection ${j.connectionId}`),!e.has(j.mediaId)&&(e.add(j.mediaId),D.mainConnection?.id===j.connectionId&&await D.request("StartMedia",{media_id:j.mediaId,properties:{kind:"audio",uid:this.uid,ref:this.#A,customType:this.#x}}).catch(B=>p(`StartMedia got rejected; ${B}`)),this._UpdateMedias())}async stop(D,j){let e=this._Medias.get(j.connectionId);o(`stopping audio capture media ${j.mediaId} on connection ${j.connectionId}`),e?.delete(j.mediaId)&&(D.mainConnection?.id===j.connectionId&&await D.request("StopMedia",{media_id:j.mediaId}).catch(B=>p(`StopMedia got rejected; ${B}`)),this._UpdateMedias())}setVad(D){a("updating vad config",D),this._Vad=D,this._Capture&&this._Capture.worker.setVad(D)}async setApm(D){await this._enqueue(()=>this._setApmImpl(D))}async _setApmImpl(D){a("updating apm config",D),this._Apm=D,this._DeviceParameters&&await this._setDeviceImpl(this._DeviceParameters)}async setDevice(D){await this._enqueue(()=>this._setDeviceImpl(D))}async _setDeviceImpl(D){a("updating capture device parameters",D);let j=this._DeviceParameters;if(this._DeviceParameters=D,this._Volume!=="muted")try{let e=await h0(this.controller,D,{...this._Apm,echoCanceller:this._Monitor?!1:this._Apm.echoCanceller});if(e.type!=="Success"){p(`unable to open capture device; ${e.reason}`),this._DeviceParameters=j;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!==e.value.context?(this._Capture?.worker.close(),this._Capture={worker:await w0(e.value.context,this.controller.sink,this.controller.receiveMonitoredPacket.bind(this.controller),new WeakRef(this)),source:e.value},await this._UpdateMedias(),this._Capture.worker.setVolume(this._Volume),this.setVad(this.vad)):this._Capture.source=e.value,this._Capture.source.connect(this._Capture.worker.worklet)}catch(e){throw new Error(`Error in setDevice(); ${e}`)}}async setVolume(D){await this._enqueue(()=>this._setVolumeImpl(D))}async _setVolumeImpl(D){a(`updating capture volume to ${D}`),this._Volume=D,D==="muted"?await this._closeImpl():(!this._Capture&&this._DeviceParameters&&await this._setDeviceImpl(this._DeviceParameters),this._Capture?.worker.setVolume(D))}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(D){k("failed to disconnect audio node",D)}await this.controller.audioContexts.release(this._Capture.source.context)}navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._Capture=void 0}async dump(){let D=[];for(let[j,e]of this._Medias)D.push(`${j} => ${Array.from(e.values()).join(",")}`);return{uid:this.uid,ref:this.#A??null,customType:this.#x??null,worker:await this._Capture?.worker.dump()??null,vad:this._Vad,apm:this._Apm,volume:this._Volume,medias:D}}async _UpdateMedias(){if(this._Capture!==void 0){let D=Array.from(this._Medias).map(([j,e])=>({id:j,mediaIds:Array.from(e)}));this._Capture.worker.setMedias(D)}}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 t,generateUUID as bF}from"@4players/odin-common";u();var $=class{constructor(D,j){this.controller=D;this.parameters=j;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(D){bx(this.audioCapture,"setVolume() failed, this video has no Audio"),await this.audioCapture.setVolume(D)}get vad(){return bx(this.audioCapture,"getting the vad config failed, this video has no Audio"),this.audioCapture.vad}setVad(D){bx(this.audioCapture,"setVad() failed, this video has no Audio"),this.audioCapture.setVad(D)}async setDevice(D,j={voiceActivity:void 0,volumeGate:void 0}){if(this.#x)throw new Error("This VideoCapture already has a MediaStream.");if(!D.getVideoTracks()[0])throw new Error("Error when calling setDevice(), MediaStream does not contain a VideoStreamTrack!");if(this.#x=D,D.getAudioTracks()[0]){let B={device:await q0(D.getAudioTracks()[0]),vad:j,ref:this.uid};this.#F=await this.controller.createAudioCapture(B)}}async start(D,j){let e=this.#A.get(j.connectionId);if(e===void 0&&this.#A.set(j.connectionId,e=new Set),!e.has(j.mediaId)&&(e.add(j.mediaId),D.mainConnection?.id===j.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 D.request("StartMedia",{media_id:j.mediaId,properties:B}).catch(C=>p(`StartMedia got rejected; ${C}`))}}async stop(D,j){this.#x&&W(this.#x),this.#A.get(j.connectionId)?.delete(j.mediaId)&&D.mainConnection?.id===j.connectionId&&await D.request("StopMedia",{media_id:j.mediaId}).catch(B=>p(`StopMedia got rejected; ${B}`))}async dump(){let D=[];for(let[j,e]of this.#A)D.push(`${j} => ${Array.from(e.values()).join(",")}`);return{uid:this.uid,ref:this.#F?.uid??null,customType:this.customType??null,tracks:this.#x?.getVideoTracks().map(j=>({id:j.id,kind:j.kind,label:j.label,ready:j.readyState,muted:j.muted,settings:{...j.getSettings()}}))??[],volume:this.#F?.volume??0,medias:D}}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(D,j,e){this.controller=D;this.uid=j;this.customType=e}get volume(){return this.controller.playbackGetVolume(this.uid)}get activity(){return this.controller.playbackGetActivity(this.uid)}get jitterStats(){return this.controller.playbackGetJitterStats(this.uid)}start(D){o(`starting audio playback media ${D.mediaId} on connection ${D.connectionId}`),this.controller.playbackStart(this.uid,D)}stop(D){o(`stopping audio playback media ${D.mediaId} on connection ${D.connectionId}`),this.controller.playbackStop(this.uid,D)}setVolume(D){a(`updating audio playback media '${this.uid}' volume to ${D}`),this.controller.playbackSetVolume(this.uid,D)}close(){a(`closing audio playback media '${this.uid}'`),this.controller.closePlayback(this.uid)}};function lF(v,D){let j=v.audioContext;if(typeof j.setSinkId=="function"){v.connectOutput(j.destination);let e,B=()=>{if(j.state==="running"&&e!==void 0){let C=e;e=void 0,j.setSinkId(C).catch(E=>k("failed to apply deferred sinkId",E))}};return j.addEventListener("statechange",B),{async setSinkId(C){if(j.state!=="running"){e=C;return}await j.setSinkId(C)},dispose(){j.removeEventListener("statechange",B)}}}if(D&&typeof document<"u"&&typeof HTMLAudioElement<"u"&&typeof HTMLAudioElement.prototype.setSinkId=="function"){let e=j.createMediaStreamDestination();v.connectOutput(e);let B=new Audio;B.srcObject=e.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(tx=>{C||(tx instanceof DOMException&&tx.name==="NotAllowedError"?b():k("failed to start playback audio element",tx))})},Bx=()=>{j.state==="running"&&B.paused&&h()};return j.addEventListener("statechange",Bx),h(),{async setSinkId(tx){await B.setSinkId(tx)},dispose(){C=!0,d(),j.removeEventListener("statechange",Bx),B.pause(),B.srcObject=null,B.removeAttribute("src");try{B.load()}catch{}e.disconnect()}}}return v.connectOutput(j.destination),{async setSinkId(){},dispose(){}}}var ox=class{constructor(D){this.audioContextFactory=D;this.entries=[]}async acquire(D){for(let e of this.entries){if(e.sampleRate===D)return e.references+=1,e.audioContext;if(e.sampleRate===void 0&&e.audioContext.sampleRate===D)return e.references+=1,e.audioContext}let j={sampleRate:D,audioContext:await this.audioContextFactory(D),references:1};return this.entries.push(j),j.audioContext}async release(D){let j=this.entries.findIndex(e=>e.audioContext===D);if(!(j<0)&&(this.entries[j].references-=1,this.entries[j].references<=0)){let e=this.entries[j].audioContext;this.entries.splice(j,1),await e.close()}}close(){for(let D of this.entries)D.audioContext.close()}},ax=class v{constructor(D,j,e=!1){this.audioContexts=D;this.sink=j;this.enableHTMLAudioElementFallback=e;this.audioCaptures=[];this.videoCaptures=[];this.globalVolume=[1,1];this.playbacks=new Map;this.setPlaybackStrand=new oF}async create(D,j){return new v(D,j)}receivePacket(D,j){this.playbackWorker?.receivePacket(D,j)}receiveMonitoredPacket(D,j){let e=j.slice();this.receivePacket(D,e)}async createAudioPlayback(D){let j=this.playbacks.get(D.uid),e=D.volume;if(j===void 0){e=e??[1,1];let B=new H(this,D.uid,D.customType);j={id:void 0,volume:e,playback:B},this.playbacks.set(D.uid,j)}return e!==void 0&&j.playback.setVolume(e),j.playback}async createAudioCapture(D){let j=new w(this,D);return await j.setDevice(D),this.audioCaptures.push(new WeakRef(j)),j}async createVideoCapture(D,j){let e=new $(this,j);return await e.setDevice(D),this.videoCaptures.push(new WeakRef(e)),e}playbackSetDevice(D){return this.setPlaybackStrand.enqueue(async()=>{let j=D?.device.deviceId??"";if(j==="default"&&(j=""),this.playbackWorker===void 0){let e=await this.audioContexts.acquire(48e3);this.playbackWorker=await P0(e),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(D&&this.playbackSink!==void 0)try{await this.playbackSink.setSinkId(j)}catch(e){k("failed to set playback sink",e)}})}playbackSetGlobalVolume(D){this.globalVolume=D,this.playbackWorker?.setGlobalVolume(this.globalVolume)}playbackStart(D,j){let e=this.playbacks.get(D);e!==void 0&&(e.id!==void 0&&this.playbackStop(D,e.id),e.id=j,this.playbackWorker?.addMedias(j.connectionId,[j.mediaId],e.volume))}playbackStop(D,j){let e=this.playbacks.get(D);e!==void 0&&(e.id!==j&&k(`playback media ${j.mediaId} on connection ${j.connectionId} is out of sync`,e.id,j),e.id=void 0,this.playbackWorker?.removeMedias(j.connectionId,[j.mediaId]))}playbackGetActivity(D){let j=this.playbacks.get(D);return j?.id===void 0?_:this.playbackWorker?.getActivity(j.id)??_}playbackGetJitterStats(D){let j=this.playbacks.get(D);return j?.id===void 0?K0:this.playbackWorker?.getJitterStats(j.id)??K0}playbackSetVolume(D,j){let e=this.playbacks.get(D);e!==void 0&&(e.volume=j,e.id!==void 0&&this.playbackWorker?.setVolume(e.id,e.volume))}playbackGetVolume(D){return this.playbacks.get(D)?.volume??[1,1]}closePlayback(D){let j=this.playbacks.get(D);j!==void 0&&(j.id!==void 0&&this.playbackStop(D,j.id),this.playbacks.delete(D))}close(){this.playbackSink?.dispose(),this.playbackSink=void 0,this.playbackWorker?.close(),this.audioContexts.close()}async dump(){let D=[];for(let B of this.audioCaptures){let C=B.deref();C!==void 0&&D.push(await C.dump())}let j=[];for(let B of this.videoCaptures){let C=B.deref();C!==void 0&&j.push(await C.dump())}let e=[];for(let[B,C]of this.playbacks)e.push({uid:B,id:C.id||null,volume:C.volume});return{globalVolume:this.globalVolume,playbackWorker:await this.playbackWorker?.dump()||null,audioCaptures:D,videoCaptures:j,playbacks:e}}},L=class{constructor(D,j=!1){this.device=D;this.isDefault=j}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 mB}from"@4players/odin-common";u();import{Backend as A,failure as kx,success as V0,CONNECTION_STATS_INITIAL as yF}from"@4players/odin-common";import{MainCommandsRpc as _F,MainNotificationsRpc as LF,RoomCommandsRpc as HF,RoomNotificationsRpc as NF}from"@4players/odin-common/api";u();import{failure as x0,success as A0}from"@4players/odin-common";import{MessagePackRpcSchema as uF,parseRequest as J0,parseResponse as kF}from"@4players/odin-common/api";import{encode as cF,decode as dF}from"@msgpack/msgpack";var M=class{constructor(D){this.stream=D;this._SendQueue=[];this._RecvQueue=[];this._EventQueue=[];this._Requests=new Map;this._Close=new AbortController;this._NextId=1;D instanceof WebSocket?(D.addEventListener("open",this._OnWebSocketOpen.bind(this)),D.addEventListener("close",this.close.bind(this)),D.addEventListener("message",j=>this._OnRpcMessage(j.data)),D.binaryType="arraybuffer"):(hF(D.readable.getReader(),this._OnRpcMessage.bind(this)).finally(this.close.bind(this)),this._Writer=D.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(D,j,e){if(this.closed)return Promise.resolve("closed");let B=this._NextId,C=e===void 0?void 0:setTimeout(()=>this._TimeoutRequest(B),e);return this._Send([0,B,D,j]),new Promise(E=>{this._Requests.set(B,{accept:E,timeoutId:C}),this._NextId+=1})}notify(D,j){this.closed||this._Send([2,D,j])}recv(){if(this.closed)return Promise.resolve("closed");let D=this._EventQueue.shift();return D!==void 0?Promise.resolve(D):new Promise(j=>this._RecvQueue.push(j))}close(){this._Close.abort()}_TimeoutRequest(D){let j=this._Requests.get(D);j!==void 0&&(this._Requests.delete(D),clearTimeout(j.timeoutId),j.accept("timeout"))}_Send(D){let j;D instanceof Uint8Array?j=D:j=new Uint8Array(cF(D,{ignoreUndefined:!0,forceFloat32:!0})),this.stream instanceof WebSocket?this.stream.send(j):this._Writer.write(j)}_OnWebSocketOpen(D){for(let j of this._SendQueue)this._Send(j);this._SendQueue.length=0}_OnRpcMessage(D){let j=pF(D);if(j.type!=="Success"){this.close();return}switch(j.value[0]){case 0:this._Send([1,j.value[1],"not supported",null]);break;case 1:this._OnResponse(j.value[1],j.value[2],j.value[3]);break;case 2:this._OnEvent(j.value[1],j.value[2]);break}}_OnResponse(D,j,e){let B=this._Requests.get(D);B!==void 0&&(clearTimeout(B.timeoutId),B.accept(j===null?A0(e):x0(j)))}_OnEvent(D,j){let e=this._RecvQueue.shift();e!==void 0?e({name:D,properties:j}):this._EventQueue.push({name:D,properties:j})}_Cleanup(){for(let D of this._Requests.values())clearTimeout(D.timeoutId),D.accept("closed");this._Requests.clear();for(let D of this._RecvQueue)D("closed");this._RecvQueue.length=0,this._SendQueue.length=0,this.stream instanceof WebSocket?this.stream.close():this._Writer?.close().catch(()=>{})}},V=class{constructor(D,j,e){this.rpc=D;this._Commands=j;this._Events=e}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(D,j,e){j=J0(D,j,this._Commands);let B=await this.rpc.request(D,j,e);if(B==="closed"||B==="timeout"||B.type==="Failure")return B;let C=kF(D,B.value,this._Commands);return C!==void 0?A0(C):x0("response schema failed validation")}notify(D,j){j=J0(D,j,this._Commands),this.rpc.notify(D,j)}async recv(){let D=await this.rpc.recv();if(D==="closed")return D;let j=F0(this._Events,D);return j!==void 0?j:(O0(this._Events,D.name)?(p(`schema validation for ${D.name} failed; closing connection`),this.rpc.close()):k(`dropping unknown event ${D.name}`),"closed")}close(){this.rpc.close()}};function pF(v){try{return A0(uF.parse(dF(new Uint8Array(v))))}catch(D){return x0(String(D))}}function F0(v,D){if(!O0(v,D.name))return;let j=v[D.name].safeParse(D.properties);if(j.success)return{name:D.name,properties:j.data}}function O0(v,D){return D in v}async function hF(v,D){let j=new Uint8Array;for(;;){let e=a0(j,0);if(e===n){v.cancel("protocol violation");break}if(e!==I&&e<=j.length){D(j.subarray(0,e)),j=j.subarray(e);continue}let B;try{B=await v.read()}catch{break}if(B.done)break;j=qF(j,B.value)}j.length>0&&k("unprocessed bytes left in rpc stream",j)}function qF(v,D){if(v.length===0)return D;if(D.length===0)return v;let j=new Uint8Array(v.length+D.length);return j.set(v,0),j.set(D,v.length),j}u();import{failure as lx,fromBase64Url as mF,success as GF}from"@4players/odin-common";import{TokenClaimsSchema as IF}from"@4players/odin-common/api";var y=class v{constructor(D,j){this.text=D;this.claims=j;if(j.ups!==void 0){let e=v.parse(j.ups);e.type==="Success"?this._Upstream=e.value:p(`upstream in token can not be parsed; ${e.reason}`)}}static parse(D){let j=D.split(".");if(j.length!==3)return lx("expected three segments");let e=mF(j[1]);if(e.type==="Failure")return lx(`invalid token; ${e.reason}`);let B;try{B=JSON.parse(e.value)}catch(E){return lx(`invalid token; ${E}`)}let C=IF.safeParse(B);return C.success===!1?lx(`invalid token; ${C.error}`):GF(new v(D,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(D){return this.claims.aud===void 0&&D==="gateway"?!0:Array.isArray(this.claims.aud)?this.claims.aud.includes(D):this.claims.aud===D}toString(){return this.text}};u();import{VideoCodec as gF,assert as M0}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 S0(v){let D=globalThis.rtcDataChannels?.indexOf(v);D!==void 0&&D>=0&&globalThis.rtcDataChannels.splice(D,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 D=globalThis.rtcPeerConnections?.indexOf(v);D!==void 0&&D>=0&&globalThis.rtcPeerConnections.splice(D,1),v.connectionState!=="closed"&&v.close()}var xx=class{constructor(D,j,e){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=D,this._signaling=j,this._answerTimeout=e?.answerTimeout??i.WebRtcAnswerTimeout,this._maxNegotiationAttempts=e?.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 D=0;for(;this._negotiationRequested;){this._negotiationRequested=!1;try{await this._negotiate(),D=0}catch(j){if(D+=1,p(`negotiation failed during sdp offer/answer exchange (attempt ${D})`,j),D<this._maxNegotiationAttempts)this._negotiationRequested=!0;else{this._negotiationRunning=!1,this._signaling.closeConnection().catch(()=>{});return}}}this._negotiationRunning=!1}))}async startLocalVideo(D,j,e){if(this._localVideos.has(D))return;o(`starting local video for media ${D}`);let B=this._freeLocalVideoTransceivers.pop();if(B?(await B.sender.replaceTrack(j),B.direction="sendrecv"):B=this._peerConnection.addTransceiver(j),e){let f=B.sender.getParameters(),{maxBitrate:s,maxFramerate:b,scaleResolutionDownBy:d}=e,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);e.degradationPreference&&(f.degradationPreference=e.degradationPreference),await B.sender.setParameters(f)}let E=new gF(e?.codec??i.DefaultVideoCodec).isSupported();E&&B.setCodecPreferences([E]),this._localVideos.set(D,{transceiver:B}),this.requestNegotiation()}stopLocalVideo(D){let j=this._localVideos.get(D);j&&(o(`stopping local video for media ${D}`),this._localVideos.delete(D),j.transceiver.sender.track&&(j.transceiver.sender.track.enabled=!1),j.transceiver.direction="inactive",j.transceiver.sender.replaceTrack(null).catch(()=>{}),this._freeLocalVideoTransceivers.push(j.transceiver),this.requestNegotiation())}startRemoteVideo(D){o(`starting remote video for media ${D}`);let j=this._peerConnection.addTransceiver("video",{direction:"recvonly"}),e=new Promise((B,C)=>{this._remoteVideos.set(D,{state:"Requested",transceiver:j,promise:{resolve:B,reject:C}})});return this.requestNegotiation(),e}stopRemoteVideo(D){let j=this._remoteVideos.get(D);if(j){o(`stopping remote video for media ${D}`),this._remoteVideos.delete(D),j.state!=="Active"&&j.promise.reject(new Error("video stopped"));try{j.transceiver.stop()}catch{}this.requestNegotiation()}}async handleWebRtcUpdate(D){try{switch(D.kind){case"Sdp":await this._updateRemoteSdp(D.type==="Answer"?"answer":"offer",D.sdp,D.media_map,D.negotiation_id);break;case"Trickle":this._addIceCandidate({candidate:D.candidate,sdpMid:D.spd_mid??void 0,sdpMLineIndex:D.spd_mline_index??void 0,usernameFragment:D.username_fragment??void 0});break;case"TrickleFinished":this._addIceCandidate(void 0);break}}catch(j){p("failed to handle webrtc update",j,D)}}startup(){this._peerConnection.connectionState==="new"&&this.requestNegotiation()}cleanup(){for(let[,D]of this._remoteVideos)D.state!=="Active"&&D.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 D=await this._peerConnection.getStats(),j={},e={bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,rtt:0};D.forEach(B=>{let{type:C,...E}=B;C!=="certificate"&&(C==="candidate-pair"&&B.nominated&&(e.bytesSent+=B.bytesSent??0,e.bytesReceived+=B.bytesReceived??0,e.packetsSent+=B.packetsSent??0,e.packetsReceived+=B.packetsReceived??0,e.rtt=B.currentRoundTripTime??0),j[C]||(j[C]=[]),j[C].push(E))}),this._WebRtcStatsSnapshot={timestamp:Date.now(),status:this._peerConnection.connectionState,stats:e,report:j}}catch{}}_addIceCandidate(D){if(D&&(D.sdpMid===void 0&&D.sdpMLineIndex===void 0&&(D={...D,sdpMid:"0"}),a(`adding new ice ${D.candidate}`,D)),this._peerConnection.remoteDescription===null){this._pendingRemoteCandidates.push(D);return}this._applyIceCandidate(D)}_applyIceCandidate(D){this._peerConnection.addIceCandidate(D).catch(j=>{k("failed to add remote ice candidate",j,D)})}_flushPendingIceCandidates(){let D=this._pendingRemoteCandidates.splice(0);for(let j of D)this._applyIceCandidate(j)}async _negotiate(){let D=++this._negotiationCounter,j=await this._peerConnection.createOffer();M0(j.type==="offer"&&j.sdp,"generated broken payload"),await this._peerConnection.setLocalDescription(j);let e=[];for(let[C,{transceiver:E}]of this._localVideos)E.mid&&e.push([C,E.mid]);for(let[C,E]of this._remoteVideos)E.state!=="Active"&&E.transceiver.mid&&e.push([C,E.transceiver.mid]);let B=new Promise((C,E)=>{this._pendingAnswer={negotiationId:D,resolve:C,reject:E}});try{await this._signaling.sendOffer(j.sdp,e,D),await $F(B,this._answerTimeout,`timed out waiting for answer to offer ${D}`)}finally{this._pendingAnswer=void 0}}async _updateRemoteSdp(D,j,e,B){if(D==="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 e){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:D,sdp:j})}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(D){let j=Array.from(this._remoteVideos).find(([,C])=>C.state==="Mapped"&&C.mid===D.transceiver.mid);if(!j){k(`unexpected track with mid: ${D.transceiver.mid}`);return}let[e,B]=j;M0(B.state==="Mapped","expected video state to be Mapped"),this._remoteVideos.set(e,{state:"Active",transceiver:D.transceiver}),a(`updated local video list with media ${e}`,j,D.transceiver,this._localVideos),D.track.onended=()=>{a(`video track with mid ${D.transceiver.mid} ended`,j)},B.promise.resolve(D.track)}};function $F(v,D,j){return new Promise((e,B)=>{let C=setTimeout(()=>B(new Error(j)),D);v.then(E=>{clearTimeout(C),e(E)},E=>{clearTimeout(C),B(E)})})}var cx=class v{constructor(D,j,e,B,C,E,f){this.id=D;this.address=j;this.connection=B;this.datagramWritable=C;this.rpc=E;this.closeController=f;this._ConnectionStats={...yF};this._WebRtcSessionFlight=new S;this._PingFlight=new S;this.status=0;this._ClosePromise=(async()=>{try{await this.connection.closed}catch{}return"closed"})(),i.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(i.HealthCheckTimeout)},i.MainConnectionPingInterval)),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,e(s,b)})}static async create(D,j,e,B){try{let C=new URL(`https://${j}?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 ${j} failed because WebTransport datagrams are not supported by this browser`);let d=await f.createBidirectionalStream(),h=new V(new M(d),_F,LF);return E.signal.addEventListener("abort",()=>h.close(),{once:!0}),h.notify("Hello",{stream:"main"}),V0(new v(D,j,e,f,b,h,E))}catch(C){return kx(`connecting to ${j} failed with ${C}`)}}get connectionStats(){return this._ConnectionStats}get transport(){return"H3"}get closePromise(){return this._ClosePromise}get closeSignal(){return this.closeController.signal}get closed(){return this.closeSignal.aborted}waitForConnected(){return Promise.race([this.connection.ready,this.connection.closed.then(()=>{throw new Error("connection closed")})])}close(){o(`closing connection to '${this.address}' with id ${this.id}`),this.closeController.abort("request")}async joinRoom(D,j,e,B){try{if(this.closed)return"closed";let C=await this.connection.createBidirectionalStream().catch(()=>"closed");if(C==="closed")return"closed";let E=new V(new M(C),HF,NF),f=await E.request("Hello",{stream:"room",token:String(D),room_id:j,user_data:e,position:B});return f==="closed"||f.type==="Failure"?f:V0(E.rpc)}catch(C){return kx(`JoinRoom failed; ${C}`)}}async getReconnectToken(D){let j=await this._Request("RequestReconnectToken",{peer_id:D});return j.type==="Failure"?j:y.parse(j.value)}async healthCheck(){let D=await this._RequestPing(i.HealthCheckTimeout);return D||this.close(),D}async ping(D=3e4){let j=Date.now();return await this._RequestPing(D)?Date.now()-j:0}sendDatagram(D){try{this.datagramWriter.write(D),this._ConnectionStats.packetsSent+=1;let j=D.byteLength;this.connectionStats.bytesSent+=j}catch{}}async readDatagrams(D,j,e){try{let B=D.datagrams.readable.getReader();for(;;){let C=await B.read();if(C.done)break;let E=C.value.byteLength;this.connectionStats.bytesReceived+=E,e(j,C.value)}}catch{}}_CleanUp(){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(D,j,e)=>{let B=await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:D,media_map:j,negotiation_id:e});if(B.type==="Failure")throw new Error(`failed to send sdp offer; ${B.reason}`)},sendIceCandidate:async D=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:D.candidate,spd_mid:D.sdpMid??void 0,spd_mline_index:D.sdpMLineIndex??void 0,username_fragment:D.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 D=await this.rpc.recv();if(D==="closed")break;D.name==="WebRtcUpdate"&&this._WebRtcSession?.handleWebRtcUpdate(D.properties)}this.close()}async _Request(D,j,e){let B=Date.now(),C=await(e===void 0?this.rpc.request(D,j):this.rpc.request(D,j,e)),E=(Date.now()-B)/1e3;return D!=="Ping"&&a(`sent main rpc '${D}'; took: ${E}s`,{properties:j,timeout:e,result:C}),C==="closed"?kx("connection lost"):C}_RequestPing(D=3e4){return this._PingFlight.run(async()=>{let j=await this._Request("Ping",{},D);return j!=="timeout"&&j.type==="Success"})}async startLocalVideo(D,j,e){await(await this._EnsureWebRtcSession()).startLocalVideo(D,j,e)}stopLocalVideo(D){this._WebRtcSession?.stopLocalVideo(D)}async startRemoteVideo(D){return(await this._EnsureWebRtcSession()).startRemoteVideo(D)}stopRemoteVideo(D){this._WebRtcSession?.stopRemoteVideo(D)}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 OF,CONNECTION_STATS_INITIAL as MF}from"@4players/odin-common";import{MainCommandsRpc as TF,MainNotificationsRpc as SF}from"@4players/odin-common/api";u();import{abortableSleep as wF,failure as Dx,success as PF}from"@4players/odin-common";async function r0(v,D){let j=performance.now(),e=Dx("no connection was attempted");for(let B=0;B<i.ConnectInterval.length&&!D.aborted;B++){let C=j+JF(B);if(await wF(C-performance.now(),D)==="aborted")return Dx("aborted");if(e=await KF(v,D),e.type==="Success")return e}return e}async function KF(v,D){let j;try{j=new WebSocket(v)}catch(s){return Dx(`unable to create websocket; ${s}`)}let e=new AbortController,B=new Promise(s=>j.addEventListener("open",()=>s(PF(j)),{signal:e.signal})),C=new Promise(s=>j.addEventListener("close",b=>s(Dx(b.reason!==""?b.reason:"unable to establish websocket connection")),{signal:e.signal})),E=new Promise(s=>D.addEventListener("abort",()=>s(Dx("aborted")),{signal:e.signal})),f=await Promise.race([B,C,E]);return e.abort(),f}function JF(v){let D=i.ConnectInterval.slice(0,v).reduce((e,B)=>e+B,0),j=i.ConnectInterval[v]*Math.random();return D+j}var hx=class v{constructor(D,j,e,B,C,E){this.id=D;this.address=j;this.url=e;this.onDatagram=B;this.connection=C;this.webRtc=E;this._PeerIdMap=new WeakMap;this._ConnectionStats={...MF};this._PingFlight=new S;o(`creating new webrtc connection to '${this.address}' with id ${this.id}`),this.closeSignal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this._ClosePromise=new Promise(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 ${D} raised an error`,f),this._AudioChannel.onclosing=f=>o(`webrtc audio data channel for connection with id ${D} begins shutting down`,f),this._AudioChannel.onclose=f=>o(`webrtc audio data channel for connection with id ${D} 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(D,j,e,B){if(B.aborted)return px("aborted");let C;try{C=new URL(`wss://${j}`)}catch(b){return OF(`address in token(${j}) 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 V(new M(f.value),TF,SF);try{return Q0(new v(D,j,C,e,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((D,j)=>{let e=()=>{let B=this.status;B!==0&&(this.webRtc.removeEventListener("connectionstatechange",e),B===1?D():j(new Error("connection closed")))};this.webRtc.addEventListener("connectionstatechange",e),e(),this.closePromise.then(()=>{j(new Error("connection closed"))})})}close(){o(`closing ${this.transport} connection to '${this.address}' with id ${this.id}`),this.connection.close()}async joinRoom(D,j,e,B){let C=await this.connection.request("JoinRoom",{token:String(D),room_id:j,user_data:e,position:B});if(C==="closed"||C.type==="Failure")return C;let E=C.value;if(!("token"in E))return 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 M(s.value))):s}async getReconnectToken(D){let j=await this._Request("RequestReconnectToken",{peer_id:D});return j.type==="Failure"?j:y.parse(j.value)}async healthCheck(){let D=await this._RequestPing(i.HealthCheckTimeout);return D||this.close(),D}async ping(D=3e4){let j=Date.now();return await this._RequestPing(D)?Date.now()-j:0}sendDatagram(D){if(this._AudioChannel.readyState==="open"){let j=D.byteLength;this._AudioChannel.send(D),this._ConnectionStats.packetsSent+=1,this._ConnectionStats.bytesSent+=j}}_CleanUp(){a(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId),S0(this._AudioChannel),R0(this.webRtc),this._WebRtcSession.cleanup(),this.connection.close()}async _HandleWebRtcUpdates(){for(;;){let D=await this.connection.recv();if(D==="closed")break;D.name==="WebRtcUpdate"&&this._WebRtcSession.handleWebRtcUpdate(D.properties)}this.close()}async _Request(D,j,e){let B=Date.now(),C=await(e===void 0?this.connection.request(D,j):this.connection.request(D,j,e)),E=(Date.now()-B)/1e3;return D!=="Ping"&&a(`sent main rpc '${D}'; took: ${E}s`,{properties:j,timeout:e,result:C}),C==="closed"?px("connection lost"):C}_RequestPing(D=3e4){return this._PingFlight.run(async()=>{let j=await this._Request("Ping",{},D);return j!=="timeout"&&j.type==="Success"})}async startLocalVideo(D,j,e){await this._WebRtcSession.startLocalVideo(D,j,e)}stopLocalVideo(D){this._WebRtcSession.stopLocalVideo(D)}async startRemoteVideo(D){return this._WebRtcSession.startRemoteVideo(D)}stopRemoteVideo(D){this._WebRtcSession.stopRemoteVideo(D)}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,D,j,e,B){switch(o(`creating ${D} main connection to '${j}'`),D){case"H3":return cx.create(v,j,e,B);case"WebRTC":return hx.create(v,j,e,B);default:throw new Error(`transport ${D} is not supported`)}}import{Backend as GB,failure as Y0,success as RF}from"@4players/odin-common";import{parseCommand as VF,parseNotification as UF,RoomCommandsRpc as X0,RoomNotificationsRpc as Z0}from"@4players/odin-common/api";u();var qx=class{constructor(D,j,e,B){this.id=D;this.connection=j;this.cipher=e;this.mediaMap=B;this._DatagramReceived=0;this._DatagramSent=0;this._DatagramReceivedInvalid=0;this._DatagramSentInvalid=0;j.closeSignal.addEventListener("abort",()=>this.close())}get connectionStats(){return this.connection.connectionStats}get transport(){return this.connection.transport}get address(){return this.connection.address}get status(){return this.closed?2:this.connection.status}get closePromise(){return this.connection.closePromise}get closeSignal(){return this.connection.closeSignal}get closed(){return this.connection.closed}waitForConnected(){return this.connection.waitForConnected()}close(){this.connection.close()}async joinRoom(D,j,e,B){this.cipher.reset();let C=await this.cipher.encryptUserData(e);if(C===n)return Y0("unable to encrypt initial user-data");let E=await this.connection.joinRoom(D,j,C,B);return E==="closed"||E.type==="Failure"?E:RF(new t0(E.value,this.cipher,this))}getReconnectToken(D){return this.connection.getReconnectToken(D)}healthCheck(){return this.connection.healthCheck()}async sendDatagram(D){let j=await this.cipher.encryptDatagram(D);j!==n?(this._DatagramSent+=1,this.connection.sendDatagram(j)):this._DatagramSentInvalid+=1}async decryptDatagram(D,j){let e=await this.cipher.decryptDatagram(D,j);return e!==n?this._DatagramReceived+=1:this._DatagramReceivedInvalid+=1,e}startLocalVideo(D,j,e){return this.connection.startLocalVideo(D,j,e)}stopLocalVideo(D){return this.connection.stopLocalVideo(D)}startRemoteVideo(D){return this.connection.startRemoteVideo(D)}stopRemoteVideo(D){return this.connection.stopRemoteVideo(D)}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()}}},mx=class{constructor(D){this.room=D}resendUserData(){this.room.roomConnection?.notify("UpdatePeer",{user_data:this.room.roomConnection.userData})}setUserData(D,j){let e={kind:"UserDataChanged",peer_id:D,user_data:j};this.room.onEvent("PeerUpdated",e)}},t0=class{constructor(D,j,e){this.rpc=D;this.cipher=j;this.connection=e;this.peers=new Map;this.closeSignal.addEventListener("abort",this.cleanup.bind(this),{once:!0})}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(D,j,e){let B=await this.outgoing(D,j);return B===n?Y0("can not be encrypted"):await this.rpc.request(D,B,e)}async notify(D,j){let e=await this.outgoing(D,j);if(e!==n)return this.rpc.notify(D,e)}async recv(){for(;;){let D=await this.rpc.recv();if(D==="closed")return D;let j=await this.incoming(D.name,D.properties);if(j!==n)return{name:D.name,properties:j}}}close(){return this.rpc.close()}async outgoing(D,j){if(!(D in X0))return j;let e=VF(D,j,X0);if(e===void 0)return n;switch(e.name){case"UpdatePeer":{let B=await this.cipher.encryptUserData(e.request.user_data);if(B===n)return n;e.request.user_data=B}break;case"SendMessage":{let B=await this.cipher.encryptMessage(e.request.message);if(B===n)return n;e.request.message=B}break}return e.request}async incoming(D,j){if(!(D in Z0))return j;let e=UF(D,j,Z0);if(e===void 0)return n;switch(e.name){case"RoomUpdated":for(let B=0;B<e.properties.updates.length;B++){let C=await this.roomUpdate(e.properties.updates[B]);if(C===n)return n;e.properties.updates[B]=C}break;case"PeerUpdated":{let B=await this.peerUpdate(e.properties);if(B===n)return n;e.properties=B}break;case"MessageReceived":{let B=await this.cipher.decryptMessage(e.properties.sender_peer_id,e.properties.message);if(B===n)return n;e.properties.message=B}break}return e.properties}async peerUpdate(D){switch(D.kind){case"UserDataChanged":{let j=await this.cipher.decryptUserData(D.peer_id,D.user_data);if(j===n)return n;D.user_data=j}break;case"MediaStarted":this.mediaStarted(D.peer_id,D.media.id);break;case"MediaStopped":this.mediaStopped(D.peer_id,D.media_id);break}return D}async roomUpdate(D){switch(D.kind){case"Joined":for(let j of D.room.peers){for(let B of j.medias)this.mediaStarted(j.id,B.id);let e=await this.cipher.decryptUserData(j.id,j.user_data);e!==n?j.user_data=e:j.user_data=new Uint8Array}break;case"PeerJoined":{for(let e of D.peer.medias)this.mediaStarted(D.peer.id,e.id);let j=await this.cipher.decryptUserData(D.peer.id,D.peer.user_data);j!==n?D.peer.user_data=j:D.peer.user_data=new Uint8Array}break;case"PeerLeft":{let j=this.peers.get(D.peer_id);this.peers.delete(D.peer_id),this.cipher.deletePeerKey(D.peer_id);for(let e of j??[])this.mediaStopped(D.peer_id,e)}break}return D}mediaStarted(D,j){let e=this.peers.get(D);e===void 0&&(e=new Set,this.peers.set(D,e)),e.add(j);let B=m({connectionId:this.connection.connection.id,mediaId:j});this.connection.mediaMap.set(B,{peerId:D,connection:this.connection})}mediaStopped(D,j){this.peers.get(D)?.delete(j);let B=m({connectionId:this.connection.connection.id,mediaId:j});this.connection.mediaMap.delete(B)}cleanup(){for(let[D,j]of this.peers)for(let e of j)this.mediaStopped(D,e)}};var Gx=class{constructor(D){this.onDatagram=D;this._LastConnectionId=0;this._Connections=new Map;this._Close=new AbortController;this._MediaMap=new Map;let j=Date.now(),e=setInterval(()=>{Math.abs(Date.now()-j)>i.ClockJumpThreshold&&this.checkHealth(),j=Date.now()},i.ClockJumpCheckInterval);addEventListener("offline",()=>this.checkHealth(),{signal:this._Close.signal}),this._Close.signal.addEventListener("abort",()=>{clearInterval(e);for(let B of this._Connections.values())B.type==="establishing"?B.abort.abort():B.connection.close();this._Connections.clear()},{once:!0})}get closed(){return this._Close.signal.aborted}sendDatagram(D,j){let e=this._Connections.get(D);(e?.type==="established"||e?.type==="virtual")&&e.connection.sendDatagram(j)}async recvDatagram(D,j){let e=zF(j);if(e===void 0||e.length===0)return;let B=this._MediaMap.get(m({connectionId:D,mediaId:e[0]}));if(B===void 0)this.onDatagram(D,j);else{let C=await B.connection.decryptDatagram(B.peerId,j);if(C===n)return;this.onDatagram(B.connection.id,C)}}async acquireConnection(D,j,e,B){if(await WF(),this.closed)return"closed";let C=this.findConnection(D,j),E;switch(C?.type){case"established":a(`reusing existing connection ${C.id}`),E=C;break;case"establishing":{a(`waiting for connecting to '${j}' finish`);let b=await C.finished;if(b.type!=="Success")return b;E=b.value}break;case void 0:{a(`connecting to '${j}'`);let b=await this.createConnection(D,j,B);if(b.type!=="Success")return b;E=b.value}break}let f=E.id,s=new D0(E.connection,()=>this.releaseConnection(f));return E.references+=1,e&&(s=new qx(++this._LastConnectionId,s,e,this._MediaMap),this.addConnection({type:"virtual",id:s.id,connection:s,createdAt:Date.now()})),xA(s)}async createConnection(D,j,e){let B=++this._LastConnectionId,C=Date.now(),E=new AbortController;e.addEventListener("abort",()=>E.abort(),{once:!0}),a(`creating new connection ${B}`);let f=z0(B,D,j,this.recvDatagram.bind(this),e),{promise:s,resolve:b}=Promise.withResolvers();this.addConnection({type:"establishing",id:B,address:j,transport:D,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:j,transport:D,createdAt:C,references:0,connection:d.value};return this.addConnection(h),xA(h)}addConnection(D){(D.type==="established"||D.type==="virtual")&&D.connection.closeSignal.addEventListener("abort",()=>{o(`connection ${D.id} has been closed`),this._Connections.delete(D.id)},{once:!0}),this._Connections.set(D.id,D)}releaseConnection(D){let j=this._Connections.get(D);j?.type==="established"&&(j.references-=1,j.references<=0&&j.connection.close())}checkHealth(){for(let D of this._Connections.values())D.type==="established"&&D.connection.healthCheck()}close(){this._Close.abort()}async dump(){let D=[];for(let e of this._Connections.values()){let B;switch(e.type){case"established":B={transport:e.transport,address:e.address,connection:await e.connection.dump(),references:e.references};break;case"establishing":B={transport:e.transport,address:e.address,aborted:e.abort.signal.aborted};break;case"virtual":B={connection:await e.connection.dump()};break}D.push({type:e.type,id:e.id,createdAt:e.createdAt,...B})}let j=[];for(let[e,B]of this._MediaMap)j.push(`${e} -> ${B.peerId} @${B.connection.id} `);return{lastConnectionId:this._LastConnectionId,connections:D,mediaMap:j,closed:this.closed}}findConnection(D,j){for(let e of this._Connections.values())if(e.type!=="virtual"&&e.transport===D&&e.address===j)return e}},D0=class{constructor(D,j){this.connection=D;this.release=j;this.closeController=new AbortController;this.closePromise=new Promise(D=>this.closeController.signal.addEventListener("abort",()=>D("closed"),{once:!0}));D.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(D,j,e,B){return this.connection.joinRoom(D,j,e,B)}getReconnectToken(D){return this.connection.getReconnectToken(D)}healthCheck(){return this.connection.healthCheck()}sendDatagram(D){return this.connection.sendDatagram(D)}startLocalVideo(D,j,e){return this.connection.startLocalVideo(D,j,e)}stopLocalVideo(D){return this.connection.stopLocalVideo(D)}startRemoteVideo(D){return this.connection.startRemoteVideo(D)}stopRemoteVideo(D){return this.connection.stopRemoteVideo(D)}async dump(){let D=await this.connection.dump();return typeof D=="object"&&(D={...D,isShared:!0,referenceClosed:this.closed}),D}};function zF(v){let D;try{D=QF(v)}catch{return}if(!Array.isArray(D)||D.length<2)return;let j=D[1];if(Array.isArray(j))return j.map(Number)}import{assert as j0,Backend as IB}from"@4players/odin-common";var P=class{constructor(D,j){this.uid=D;this.customType=j}#x;#A;get mediaStream(){return this.#x}get audioPlayback(){return j0(this.#A,"getting the audioPlayback failed, this video has no Audio"),this.#A}get volume(){return j0(this.audioPlayback,"getting the volume failed, this video has no Audio"),this.audioPlayback.volume}setVolume(D){j0(this.#A,"Can not set the volume, this video has no Audio"),this.#A.setVolume(D)}setMediaStream(D){this.mediaStream||(this.#x=D)}close(){this.#x?.getVideoTracks().forEach(D=>{D.stop(),this.#x?.removeTrack(D)}),this.#x=void 0}};import{Backend as $B,assert as nA,generateUUID as ar,unwrap as lr,CONNECTION_STATS_INITIAL as ur}from"@4players/odin-common";import{RoomNotificationsRpc as kr,RoomV1 as yB}from"@4players/odin-common/api";import{Selector as XF,failure as N,sleep as Ix,success as T,assert as ZF}from"@4players/odin-common";import{parseResponse as YF,RoomCommandsRpc as gx,RoomNotificationsRpc as xr,RoomV1 as gB}from"@4players/odin-common/api";u();var $x=class{constructor(D,j,e,B,C,E,f,s,b,d){this.connectionPool=D;this.transport=j;this.onEvent=e;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(D=>this._Close.signal.addEventListener("abort",()=>D(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(D,j){if(this._RoomConnection===void 0)return N("currently not connected");let e=await this._RoomConnection.request(D,j,void 0);return ZF(e!=="timeout","request should not timeout"),e!=="closed"&&e.type==="Success"&&this._HandleRequests(D,j,e.value),e}async request(D,j){let e=Date.now(),B=gx[D],C=await this.requestUnsafe(D,j),E=(Date.now()-e)/1e3;if(a(`sent room rpc '${D}'; took: ${E}s`,{properties:j,result:C}),C==="closed"||C.type==="Failure")return C;let f=YF(D,C.value,gx);return f!==void 0?T(f):N(`received invalid response from ${D}`)}notify(D,j){this._RoomConnection!==void 0&&this._RoomConnection.notify(D,j)}close(){this._Close.abort(!0)}get renewTokenIn(){let D=this._LastTokenRenew-performance.now()+i.MinTokenRefreshInterval,j=this._Token.timeLeft-i.MinTokenLifetime;return Math.max(D,j)}async _Main(){let D="unable to establish connection";for(let j=0;;this._FailedConnections++){if(await Ix(Math.max(j-performance.now(),0)),this._Close.signal.aborted||this.connectionPool.closed){D="user requested";break}if(j=performance.now()+1e3,this._TokenUsed=!0,this._Token.hasAudience("sfu")){let e=await this._ConnectToServer();if(e.type==="Success"&&e.value==="shutdown"){a("connection closed by user request; shutting down"),D="user requested";break}if(this.disableAutoReconnect&&this._WasConnected){D=e.type==="Failure"?e.reason:"connection lost";break}if(this._LastReconnectStartedAt===0&&(this._LastReconnectStartedAt=performance.now()),e.type==="Failure"&&!this._WasConnected&&this._FailedConnections>=3){D=e.reason;break}if(e.type==="Failure"&&!Fr(this._LastReconnectStartedAt))continue}if(this.reset(),this._Close.signal.aborted||this.connectionPool.closed){D="user requested";break}if(this.gateway!==void 0&&this._Token.hasAudience("gateway")){this._ChangeStatus("Joining",`requesting new token from ${this.gateway}`);let e=await Ar(this.gateway,this._Token,this._Close.signal);if(e.type==="Success")if(e.value instanceof y)j=0,this._Token=e.value,this._TokenUsed=!1;else{D=`gateway error; ${e.value}`;break}else if(!this._WasConnected&&this._FailedConnections>=3){D="unable to contact the gateway";break}}if(this._TokenUsed&&this._Token.timeLeft<=0){D="token has expired";break}if(this._Close.signal.aborted||this.connectionPool.closed){D="user requested";break}}return this._ChangeStatus("Closed",D),this.close(),N(D)}async _ConnectToServer(){let D=this._Token;for(;D.upstream!==void 0;)D=D.upstream;let j=D.claims.adr??this.gateway?.toString();if(!j)return T("continue");if(this._ChangeStatus("Joining",`connecting to ${D.claims.adr}`),this._MainConnection===void 0||this._MainConnection.closed||this._MainConnection.address!==D.claims.adr){this._MainConnection?.close();let C=await this.connectionPool.acquireConnection(this.transport,j,this.cipher,this._Close.signal);if(C==="closed")return N("connection pool closed");if(C.type==="Failure")return this._ChangeStatus("Joining",`connection failed; ${C.reason}`),N(`connection failed; ${C.reason}`);this._MainConnection=C.value,this._OwnPeerId=void 0}let e=await Promise.race([Promise.all([this._MainConnection.joinRoom(D,this.roomId,this.userData,this.position)]),Ix(i.ConnectTimeout,"timeout"),this._Closed]);if(e==="closed"||e==="disconnected")return T("continue");if(e==="timeout")return this._ChangeStatus("Joining","timed out"),T("continue");let[B]=e;if(B==="closed")return T("continue");if(B.type==="Failure")return N(`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 N(`unable to handle connection; ${C}`)}}_ChangeStatus(D,j){let e={status:D,message:j};this.onEvent("RoomStatusChanged",e)}async _HandleConnection(D){if(this._RoomConnection===void 0)return!1;let j=new XF([()=>Ix(this.renewTokenIn,"renewToken"),()=>Ix(500,"tick"),async()=>await this._RoomConnection?.recv(),()=>this._Closed,()=>D.closePromise]);for(;;){let e=await j.next();switch(e){case void 0:case"closed":return this._RoomConnection?.close(),this._MainConnection?.close(),!1;case"disconnected":return this._RoomConnection?.close(),this._MainConnection?.close(),!0;case"renewToken":this._RenewToken();break;case"tick":break;default:this._HandleEvent(e);break}}}_HandleEvent(D){if(D.name==="RoomUpdated"){let j=xr.RoomUpdated.safeParse(D.properties);if(!j.success)return;for(let e of j.data.updates)e.kind==="Joined"&&(this._OwnPeerId=e.own_peer_id)}this.onEvent(D.name,D.properties)}_HandleRequests(D,j,e){switch(D){case"SetPeerPosition":{let B=gx.SetPeerPosition.request.safeParse(j);if(B.success){let C=B.data.position;this._Position=C.length===2?[C[0],C[1],0]:C}else k("unable to process SetPeerPosition command");break}case"UpdatePeer":{let B=gx.UpdatePeer.request.safeParse(j);B.success?this._UserData=B.data.user_data:k("unable to process UpdatePeer command");break}}}async _RenewToken(D){if(this._LastTokenRenew=performance.now(),!D&&this.token.timeLeft>i.MinTokenLifetime)return;if(this._MainConnection===void 0||this._OwnPeerId===void 0)return N("connection is not established");let j=await this._MainConnection.getReconnectToken(this._OwnPeerId);return j.type==="Success"?(this._Token=j.value,T()):N(`${this._MainConnection.address} rejected reconnect token request; ${j.reason}`)}reset(){this._LastReconnectStartedAt=0,this._RoomConnection?.close(),this._RoomConnection=void 0,this._MainConnection?.close(),this._MainConnection=void 0,this._OwnPeerId=void 0}};async function Ar(v,D,j){try{let e={jsonrpc:"2.0",id:1,method:"Connect",params:{}};o(`sending authentication request to '${v}'`,e);let C=await(await fetch(v,{body:JSON.stringify(e),method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${D}`},signal:j})).json();if(o(`received authentication response fom '${v}'`,C),"result"in C)return y.parse(C.result.token);{let E=C.error?.message??"malformed response";return p(`gateway rejected token; ${E}`),T(E)}}catch(e){return N(String(e))}}function Fr(v,D=8e3){return performance.now()-v>D}u();import{assert as or}from"@4players/odin-common";u();import{Backend as ex,Strand as br}from"@4players/odin-common";u();import{assert as er}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,tA=1e6,DA=2147483648,jA=32,K=[79,68,73,78,1,75,105,109],Ax=16,Fx=64,eA=16;function BA(v,D){if(v.length!==D.length)return!1;for(let j=0;j<v.length;j++)if(v[j]!==D[j])return!1;return!0}function tr(v){return isFinite(v)}function Dr(v){return Array.isArray(v)}function yx(v){return tr(v)?v:n}function jx(v){return v instanceof Uint8Array?v:n}function jr(v,...D){let j;try{j=rr(v)}catch{return n}if(!Dr(j))return n;let e=new Array(j.length);for(let B in D)if(e[B]=D[B](j[B]),e[B]===n)return n;return e}function _x(v,...D){if(v.length<K.length)return G;for(let j=0;j<K.length;j++)if(v[j]!==K[j])return G;return jr(v.subarray(K.length),...D)}var rx=class{constructor(D){this.first=1;this.offset=0;this.window=Array(D)}isReplay(D){let j=D-this.first;if(j<0)return!0;if(j>=this.window.length)if(j<this.window.length*2){let C=j-this.window.length+1;j-=C;for(let E=0;E<C;E++)this.advance()}else return this.first=D+1-self.window.length,this.offset=0,this.window.fill(!1),!1;let e=(this.offset+j)%this.window.length,B=this.window[e]===!0;for(this.window[e]=!0;this.window[this.offset]===!0;)this.advance();return B}advance(){this.window[this.offset]=!1,this.first+=1,this.offset=(this.offset+1)%this.window.length}};var Lx=class v{constructor(D){this.key=D}static async create(D){typeof D=="string"&&(D=new TextEncoder().encode(D));let j=await globalThis.crypto.subtle.importKey("raw",D,"PBKDF2",!1,["deriveBits"]),e=await globalThis.crypto.subtle.deriveBits(AA,j,256),B=await globalThis.crypto.subtle.importKey("raw",e,"PBKDF2",!1,["deriveKey"]);return new v(B)}async generatePeerKey(D,j){return await globalThis.crypto.subtle.deriveKey(FA(D),this.key,{name:"AES-GCM",length:256},!1,[j])}},Hx=class v{constructor(D,j){this.seed=D;this.key=j;this.sequenceNumbers={datagram:1,message:1,userData:1};this.number_of_packets=0;this.number_of_bytes=0}static async create(D){let j=globalThis.crypto.getRandomValues(new Uint8Array(rA)),e=await D.generatePeerKey(j,"encrypt");return new v(j,e)}get limitReached(){return this.key===void 0?!1:this.number_of_bytes>=DA||this.number_of_packets>=tA}nextSequenceNumber(D){return this.sequenceNumbers[D]++}};function e0(v,D){return{kind:"encrypted",key:v,material:D,antiReplays:{datagram:new rx(jA),userData:new rx(0),message:new rx(0)}}}var Nx=class v{constructor(D,j,e,B){this.additionalData=D;this.sequenceNumber=j;this.seed=e;this.encrypted=B}static parse(D){let j=_x(D,jx,yx,jx);if(j===n||j===G)return j;let[e,B,C]=j,E=D.subarray(0,D.length-C.length);return new v(E,B,e,C)}isSameSeed(D){return BA(this.seed,D.seed)}async generateKey(D){return await D.generatePeerKey(this.seed,"decrypt")}};function wx(v,D){let j=new Uint8Array(12);switch(j[0]=D&255,j[1]=D>>8&255,j[2]=D>>16&255,j[3]=D>>24&255,v){case"datagram":j[5]=1;break;case"userData":j[5]=2;break;case"message":j[5]=3;break;default:er(!1,"missing content implementation")}return j}u();import{encode as CA}from"@msgpack/msgpack";import{assert as vr}from"@4players/odin-common";var Px=class{constructor(D){this.actions=D}changeKey(D){this.masterKey!==D&&(this.masterKey=D,this.ownKey=n,this.actions.resendUserData())}async encryptDatagram(D){let j=await this.getKey("datagram");return j===void 0?D:j===J?n:await Er(j,D)}async encryptMessage(D){let j=await this.getKey("message");return j===void 0?D:j===J?J:await vA(j,D,"message")}async encryptUserData(D){let j=await this.getKey("userData");return j===void 0?D:(vr(j!==J,"key unavailable for user data encryption"),await vA(j,D,"userData",j.seed))}async getKey(D){if(this.ownKey===n||this.ownKey?.limitReached)if(D==="userData")this.ownKey=this.masterKey?await Hx.create(this.masterKey):void 0;else return this.ownKey!==n&&(this.ownKey=n,this.actions.resendUserData()),J;return this.ownKey}reset(){this.ownKey=this.masterKey?n:void 0}};async function vA(v,D,j,...e){let B=v.nextSequenceNumber(j),C=D.length+Ax,E=Cr(B,e,C),f=E.length-C,s=await EA(v,j,B,E.subarray(0,f),D);return E.set(new Uint8Array(s),f),E}function Cr(v,D,j){let e=[];D.forEach(E=>e.push(E)),e.push(v),e.push(new Uint8Array(j));let B=CA(e),C=new Uint8Array(K.length+B.length);return C.set(K,0),C.set(B,K.length),C}async function Er(v,D){let j=fr(D);if(j===n)return n;if((j.kind&Fx)!==0)return n;let e=j.body.length+Ax,B=v.nextSequenceNumber("datagram"),C=CA([j.kind|Fx,j.mediaIds,B,new Uint8Array(e)]),E=C.length-e,f=await EA(v,"datagram",B,C.subarray(0,E),j.body);return C.set(f,E),C}async function EA(v,D,j,e,B){return new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:wx(D,j),additionalData:e,tagLength:Ax*8},v.key,B))}function fr(v){let D=new O(v),j=D.readArrayLength();if(l(j)||j<2)return n;let e=D.readNumber(),B=D.readArrayLength();if(l(e)||l(B))return n;if(B>eA)return n;let C=Array(B);for(let f=0;f<C.length;f++){let s=D.readNumber();if(l(s))return n;C[f]=s}let E=v.subarray(D.position);return{kind:e,mediaIds:C,body:E}}u();import{encode as nr}from"@msgpack/msgpack";var Jx=class{constructor(D){this.actions=D;this.peerKeys=new Map}async changeKey(D){this.masterKey=D;for(let[j,{kind:e,material:B}]of this.peerKeys)if(D!==void 0){let C=await B.generateKey(D),E=e0(C,B),f=await Kx(E,"userData",B.additionalData,B.sequenceNumber,B.encrypted);f!==n?(this.peerKeys.set(j,E),this.actions.setUserData(j,f)):(this.peerKeys.set(j,{kind:"broken",material:B}),this.actions.setUserData(j,new Uint8Array))}else e==="encrypted"&&this.peerKeys.set(j,{kind:"broken",material:B})}async decryptDatagram(D,j){let e=sr(j);if(this.masterKey===void 0)return e===G?j:n;if(e===n||e===G)return n;let B=this.peerKeys.get(D);if(B?.kind!=="encrypted")return n;let C=await Kx(B,"datagram",e.additionalData,e.sequenceNumber,e.encrypted);return C===n?n:ir(e.kind&~Fx,e.mediaIds,C)}async decryptMessage(D,j){let e=_x(j,yx,jx);if(this.masterKey===void 0)return e===G?j:n;if(e===n||e===G)return n;let B=this.peerKeys.get(D);if(B?.kind!=="encrypted")return n;let[C,E]=e,f=j.subarray(0,j.length-E.length);return Kx(B,"message",f,C,E)}async decryptUserData(D,j){let e=Nx.parse(j);if(e===n)return n;if(e===G)return this.peerKeys.delete(D),this.masterKey===void 0?j:n;if(this.masterKey===void 0)return this.peerKeys.set(D,{kind:"broken",material:e}),n;let B=this.peerKeys.get(D);if(B?.kind==="encrypted"&&B.material.isSameSeed(e))B.material=e;else{let E=await e.generateKey(this.masterKey);B=e0(E,e)}let C=await Kx(B,"userData",e.additionalData,e.sequenceNumber,e.encrypted);return C===n?this.peerKeys.set(D,{kind:"broken",material:e}):B!==void 0&&this.peerKeys.set(D,B),C}reset(){this.peerKeys.clear()}};function sr(v){let D=new O(v),j=D.readArrayLength();if(l(j)||j<1)return n;let e=D.readNumber();if(l(e))return n;if((e&Fx)===0)return G;if(j!==4)return n;let B=D.position;D.readObjects(1);let C=v.subarray(B,D.position),E=D.readNumber(),f=D.readBytes();if(l(E)||l(f))return n;let s=v.subarray(0,v.length-f.length);return{kind:e,mediaIds:C,additionalData:s,sequenceNumber:E,encrypted:f}}async function Kx(v,D,j,e,B){let C=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:wx(D,e),additionalData:j,tagLength:Ax*8},v.key,B).catch(()=>n);return C===n?n:v.antiReplays[D].isReplay(e)?n:new Uint8Array(C)}function ir(v,D,j){let e=2;try{let E=new O(j);for(E.position=0;E.position<j.length;)E.readObjects(1),e+=1}catch{return n}let B=nr(v),C=new Uint8Array(3+B.length+D.length+j.length);return C[0]=220,C[1]=e>>8&255,C[2]=e&255,C.set(B,3),C.set(D,3+B.length),C.set(j,3+B.length+D.length),C}var Ox=class{constructor(D,j){this.active=!1;let e=new Jx(j),B=new Px(j);this.crypto=new br({encryption:B,decryption:e}),this.peerKeys=e.peerKeys,this.configure(D)}encryptUserData(D){return this.crypto.enqueue(({encryption:j})=>j.encryptUserData(D))}async encryptMessage(D){let j;do j=await this.crypto.enqueue(({encryption:e})=>e.encryptMessage(D));while(j===J);return j}async encryptDatagram(D){return await this.crypto.enqueue(({encryption:j})=>j.encryptDatagram(D))}decryptUserData(D,j){return this.crypto.enqueue(({decryption:e})=>e.decryptUserData(D,j))}decryptMessage(D,j){return this.crypto.enqueue(({decryption:e})=>e.decryptMessage(D,j))}decryptDatagram(D,j){return this.crypto.enqueue(({decryption:e})=>e.decryptDatagram(D,j))}configure(D){return this.crypto.enqueue(async j=>{let e=D.password?await Lx.create(D.password):void 0;this.active=e!==void 0,await j.encryption.changeKey(e),await j.decryption.changeKey(e)})}getPeerStatus(D){switch(this.peerKeys.get(D)?.kind??"unencrypted"){case"broken":return ex.PeerCipherStatus.InvalidPassword;case"encrypted":return ex.PeerCipherStatus.Encrypted;case"unencrypted":return this.active?ex.PeerCipherStatus.InvalidPassword:ex.PeerCipherStatus.Unencrypted;default:return ex.PeerCipherStatus.Unknown}}deletePeerKey(D){this.peerKeys.delete(D)}reset(){return this.crypto.enqueue(async({encryption:D,decryption:j})=>{D.reset(),j.reset()})}async dump(){return this.crypto.enqueue(async()=>({active:this.active,peers:Array.from(this.peerKeys).map(([D,j])=>`${D} => ${j.kind}`)}))}};function fA(v,D){return or(v.type==="OdinCrypto","only OdinCrypto supported"),new Ox(v,D)}var Mx=class{constructor(D,j,e){this._Captures=new Map;this._Playbacks=new Map;this._Peers=new Map;this._AvailableMediaIds=[];let{url:B,onEvent:C}=j,E=lr(y.parse(j.token)),f=j.roomId??E.defaultRoomId,s=j.userData??new Uint8Array(0),b=j.position??[0,0,0];nA(f!==void 0,"room id required for multi-room-tokens"),this.cipher=j.cipher?fA(j.cipher,new mx(this)):void 0,this.onEvent=C,o(`creating new room '${f}' ${this.cipher?"with":"without"} cipher`,E,s,b),this._Connection=new $x(D,j.transport??"H3",this._HandleEvent.bind(this),B?new URL(B):void 0,E,f,s,b,this.cipher,e?.disableAutoReconnect??!1)}get connectionStats(){let D={...ur};return this.mainConnection?this.mainConnection.connectionStats:D}get roomConnection(){return this._Connection}get mainConnection(){return this.roomConnection?.mainConnection}get token(){return this._Connection.token.text}request(D,j){return this._Connection.requestUnsafe(D,j)}async link(D){if(D instanceof H){let j=this._Playbacks.get(D.uid)??{media:void 0,playback:void 0};j.playback!==void 0&&this.unlink(j.playback),j.media!==void 0&&D.start(j.media),j.playback=D,o(`linking audio playback media '${D.uid}' with volume ${D.volume} to room '${this._Connection.roomId}'`),this._Playbacks.set(D.uid,j)}else if(D instanceof w){let j=this._Captures.get(D);j&&this.unlink(D);let e=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();j={media:e?{connectionId:this.mainConnection.id,mediaId:e}:void 0},o(`linking audio capture media '${D.uid}' with volume ${D.volume} to room '${this._Connection.roomId}'`),this._Captures.set(D,j),j.media!==void 0&&await D.start(this._Connection,j.media)}else if(D instanceof P){let j=this._Playbacks.get(D.uid)??{media:void 0,playback:void 0};if(j.playback!==void 0&&this.unlink(j.playback),j.media!==void 0){let e=await this.mainConnection?.startRemoteVideo(j.media.mediaId);e&&D.setMediaStream(new MediaStream([e]))}j.playback=D,o(`linking video playback media '${D.uid}' with type '${D.customType}' to room '${this._Connection.roomId}'`),this._Playbacks.set(D.uid,j)}else if(D instanceof $){let j=this._Captures.get(D);j&&this.unlink(D);let e=D.mediaStream?.getVideoTracks()[0];if(e){let B=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();j={media:B?{connectionId:this.mainConnection.id,mediaId:B}:void 0},o(`linking video capture media '${D.uid}' with type '${D.parameters?.customType}' to room '${this._Connection.roomId}'`),this._Captures.set(D,j),j.media!==void 0&&(await D.start(this._Connection,j.media),this.mainConnection?.startLocalVideo(j.media.mediaId,e,D.parameters)),D.audioCapture&&await this.link(D.audioCapture)}}else throw new Error("Linking failed, media was not supported")}unlink(D){if(D instanceof H||D instanceof P){let j=this._Playbacks.get(D.uid);if(j?.playback!==D)return;j.playback=void 0,j.media!==void 0&&(D instanceof H?D.stop(j.media):(this.mainConnection?.stopRemoteVideo(j.media.mediaId),D.setMediaStream(void 0))),o(`unlinking playback media '${D.uid}' from room '${this._Connection.roomId}'`),this._Playbacks.set(D.uid,j)}else if(D instanceof w||D instanceof $){D instanceof $&&D.audioCapture&&this.unlink(D.audioCapture);let j=this._Captures.get(D);if(j===void 0)return;j.media!==void 0&&(D.stop(this._Connection,j.media),this._AvailableMediaIds.push(j.media.mediaId),D instanceof $&&this.mainConnection?.stopLocalVideo(j.media.mediaId)),o(`unlinking capture media '${D.uid}' from room '${this._Connection.roomId}'`),this._Captures.delete(D)}else throw new Error("invalid media")}close(){o(`closing room '${this._Connection.roomId}'`),this._Connection.close()}_HandleEvent(D,j){let e=F0(kr,{name:D,properties:j});e!==void 0&&(this._HandleKnownEvent(e),j=e.properties),this.onEvent(D,j)}_HandleKnownEvent(D){switch(a(`processing event '${D.name}'`,D.properties),D.name){case"RoomStatusChanged":D.properties.status!=="Joined"&&this._HandleConnectionLost();break;case"RoomUpdated":for(let j of D.properties.updates)this._HandleRoomUpdate(j);break;case"PeerUpdated":this._HandlePeerUpdate(D.properties);break}}_HandleConnectionLost(){for(let D of this._Peers.keys())this._HandlePeerLeft(D);for(let[D,j]of this._Captures)j.media!==void 0&&(D instanceof $,D instanceof w&&(D.stop(this._Connection,j.media),j.media=void 0));this._AvailableMediaIds.length=0}_HandleRoomUpdate(D){if(D.kind==="Joined"){nA(this._AvailableMediaIds.length===0,"left over media ids"),this._AvailableMediaIds.push(...D.media_ids),this._HandleRoomJoined();for(let j of D.room.peers)this._HandlePeerJoined(j)}else D.kind==="PeerJoined"?this._HandlePeerJoined(D.peer):D.kind==="PeerLeft"&&this._HandlePeerLeft(D.peer_id)}_HandleRoomJoined(){for(let[D,j]of this._Captures)this._AvailableMediaIds.length===0||this.mainConnection===void 0||(j.media={connectionId:this.mainConnection.id,mediaId:this._AvailableMediaIds.shift()},D instanceof w&&D.start(this._Connection,j.media),D instanceof $)}_HandlePeerUpdate(D){D.kind==="MediaStarted"?this._HandleMediaStart(D.peer_id,D.media):D.kind==="MediaStopped"&&this._HandleMediaStopped(D.peer_id,D.media_id)}_HandlePeerJoined(D){this._Peers.has(D.id)||this._Peers.set(D.id,{mediaIds:new Map});for(let j of D.medias)this._HandleMediaStart(D.id,j)}_HandlePeerLeft(D){let j=this._Peers.get(D);if(j!==void 0){for(let e of j.mediaIds.keys())this._HandleMediaStopped(D,e);this._Peers.delete(D)}}_HandleMediaStart(D,j){if(this.mainConnection===void 0)return;let e=this._Peers.get(D);if(e===void 0||j.properties.kind!=="audio"&&j.properties.kind!=="video")return;let B=String(j.properties.uid??ar());j.properties.uid=B;let C=this._Playbacks.get(B)??{media:void 0,playback:void 0};this._Playbacks.set(B,C),e.mediaIds.set(j.id,B),C.media={connectionId:this.mainConnection.id,mediaId:j.id},C.playback!==void 0&&(C.playback instanceof H&&C.playback.start(C.media),C.playback instanceof P&&this.mainConnection.startRemoteVideo(C.media.mediaId).then())}_HandleMediaStopped(D,j){let e=this._Peers.get(D);if(e===void 0)return;let B=e?.mediaIds.get(j);if(B===void 0)return;let C=this._Playbacks.get(B);C!==void 0&&(C.media!==void 0&&C.media.mediaId===j&&C.playback!==void 0&&(C.playback instanceof H&&C.playback.stop(C.media),C.playback instanceof P&&this.mainConnection?.stopRemoteVideo(C.media.mediaId),C.media=void 0),e.mediaIds.delete(j))}};nx();function iB(v,D){c0(D?.logger,D?.onLogMessage);let j,e=new Gx((C,E)=>j.receivePacket(C,E)),B=new ox(v);return j=new ax(B,e.sendDatagram.bind(e),D?.enableHTMLAudioElementFallback??!1),new B0(e,j,D)}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(D,j,e){this.version="9";this.supportedTransports=["H3","WebRTC"];this._PlaybackVolume=[1,1];this._CreatedAt=Date.now();this._Options=e??{},this._Options.disableBeforeUnload||dr(),this._ConnectionPool=D,this._MediaController=j,v0.push(new WeakRef(this)),o("plugin initialized")}get playbackVolume(){return this._PlaybackVolume}joinRoom(D){return new Mx(this._ConnectionPool,D,this._Options)}async createAudioPlayback(D){return this._MediaController.createAudioPlayback(D)}async createAudioCapture(D){return this._MediaController.createAudioCapture(D)}async createVideoCapture(D,j){return this._MediaController.createVideoCapture(D,j)}async createVideoPlayback(D){return new P(D.uid,D.customType)}enumerateDevices(){return fx()}setOutputVolume(D){this._MediaController.playbackSetGlobalVolume(D)}async setOutputDevice(D){await this._MediaController.playbackSetDevice(D.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 D of v0){let j=D.deref();j!==void 0&&v.push(await j.dump())}return JSON.stringify({timestamp:Date.now(),instances:v,background:await m0()})}globalThis.odin_debug_dump_state=iA;window!==void 0&&(window.odin_debug_dump_state=iA);export{dx as SESSION_ID,iB as createPlugin};
|