@4players/odin-plugin-web 1.19.0 → 1.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/plugin/index.cjs +4 -4
- package/lib/esm/plugin/index.mjs +4 -4
- package/lib/index.d.ts +13 -0
- package/package.json +2 -1
package/lib/cjs/plugin/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var e0=Object.defineProperty;var IA=Object.getOwnPropertyDescriptor;var NA=Object.getOwnPropertyNames;var PA=Object.prototype.hasOwnProperty;var p=(t,x,A)=>()=>{if(A)throw A[0];try{return t&&(x=t(t=0)),x}catch(F){throw A=[F],F}};var hx=(t,x)=>{for(var A in x)e0(t,A,{get:x[A],enumerable:!0})},LA=(t,x,A,F)=>{if(x&&typeof x=="object"||typeof x=="function")for(let D of NA(x))!PA.call(t,D)&&D!==A&&e0(t,D,{get:()=>x[D],enumerable:!(F=IA(x,D))||F.enumerable});return t};var OA=t=>LA(e0({},"__esModule",{value:!0}),t);var E={};hx(E,{AdditionalCaptureBlocks:()=>wA,AdditionalPlaybackBlocks:()=>HA,ClockJumpCheckInterval:()=>UA,ClockJumpThreshold:()=>KA,ConnectInterval:()=>rF,ConnectTimeout:()=>AF,DefaultRefreshRate:()=>SA,DefaultVideoCodec:()=>eF,HealthCheckTimeout:()=>VA,MainConnectionPingInterval:()=>WA,MaxNumberOfDecoders:()=>MA,MaxReconnectDuration:()=>tF,MinDBFs:()=>j0,MinTokenLifetime:()=>FF,MinTokenRefreshInterval:()=>DF,PlaybackPreload:()=>RA,RenderQuantumSize:()=>JA,VadPreload:()=>TA,WebRtcAnswerTimeout:()=>ZA,WebRtcIceTimeout:()=>XA,WebRtcMaxNegotiationAttempts:()=>YA,WebRtcRecoveryDelays:()=>xF,WebRtcStatsSnapshotInterval:()=>QA,WebRtcTimeout:()=>zA});var HA,wA,RA,SA,TA,MA,JA,j0,VA,UA,KA,WA,QA,XA,zA,ZA,YA,xF,AF,FF,DF,rF,tF,eF,B0=p(()=>{"use strict";HA=3,wA=3,RA=3,SA=250,TA=3,MA=512,JA=128,j0=-758.596,VA=1e4,UA=1e3,KA=1e4,WA=3e3,QA=1e3,XA=3e3,zA=1e4,ZA=1e4,YA=3,xF=[0,2e3,5e3],AF=5e3,FF=6e4,DF=5e3,rF=[0,100,200,200,500],tF=12e4,eF="H264"});function mx(t){return typeof t!="symbol"}function i(t){return typeof t=="symbol"}var m,v,U,q,qx=p(()=>{"use strict";m=Symbol("Unencrypted"),v=Symbol("Invalid"),U=Symbol("Retry"),q=Symbol("UnexpectedEof")});function l(t,x,A){return t.postMessage(x,A)}function tx(t,x){return new Promise(A=>{let F=D=>{let[r]=D.data;r===x&&(A(D.data[1]),t.removeEventListener("message",F))};t.addEventListener("message",F)})}var q0=p(()=>{"use strict"});function v0(t,x){t.values[0]=x[0],t.values[1]=x[1]}function G0(t,x){return t.values[2+x*5]}function y0(t,x,A){let F=2+x*5+1;t.values[F+0]=A[0],t.values[F+1]=A[1]}function g0(t){return t.values[0]!==0}function $0(t){return t.values[1]}function _0(t){return t.values[2]}function I0(t,x){return t.values[3]=x}var N0=p(()=>{"use strict"});function P0(t,x){let A=new K(t);A.position=x;let F=A.readObjects(1);return mx(F)?A.position:F}var K,L0=p(()=>{"use strict";qx();K=class{constructor(x,A=0){this.bytes=x;this.position=A}readArrayLength(){let x=this.readTag();return i(x)?x:(x&240)===144?x&15:x===220?this.readUint16():x===221?this.readUint32():v}readNumber(){let x=this.readTag();return i(x)||(x&128)===0?x:(x&224)===224?x-256:x===202?this.readFloat32():x===203?this.readFloat64():x===204?this.readUint8():x===205?this.readUint16():x===206?this.readUint32():x===207?this.readUint64():x===208?this.readInt8():x===209?this.readInt16():x===210?this.readInt32():x===211?this.readInt64():v}readBytes(){let x=this.readTag();if(i(x))return x;let A;if(x===196)A=this.readUint8();else if(x===197)A=this.readUint16();else if(x===198)A=this.readUint32();else return v;if(i(A))return A;let F=this.consume(A);return F!==q?this.bytes.subarray(F,F+A):q}readObjects(x){for(;x>0;x-=1){let A=this.readTag();if(i(A))return A;let F,D=0,r=0;switch(A){case 192:break;case 194:break;case 195:break;case 196:D=this.readUint8();break;case 197:D=this.readUint16();break;case 198:D=this.readUint32();break;case 199:D=this.readUint8(),r=1;break;case 200:D=this.readUint8(),r=1;break;case 201:D=this.readUint32(),r=1;break;case 202:D=4;break;case 203:D=8;break;case 204:D=1;break;case 205:D=2;break;case 206:D=4;break;case 207:D=8;break;case 208:D=1;break;case 209:D=2;break;case 210:D=4;break;case 211:D=8;break;case 212:D=2;break;case 213:D=3;break;case 214:D=5;break;case 215:D=9;break;case 216:D=17;break;case 217:D=this.readUint8();break;case 218:D=this.readUint16();break;case 219:D=this.readUint32();break;case 220:if(F=this.readUint16(),i(F))return F;x+=F;break;case 221:if(F=this.readUint32(),i(F))return F;x+=F;break;case 222:if(F=this.readUint16(),i(F))return F;x+=F*2;break;case 223:if(F=this.readUint32(),i(F))return F;x+=F*2;break;default:if((A&128)!==0){if((A&240)===128)x+=(A&15)*2;else if((A&240)===144)x+=A&15;else if((A&224)===160)D=A&31;else if((A&224)!==224)return v}}if(D===q)return q;if(this.consume(D+r)===q)return q}}consume(x){if(x===q||this.position+x>this.bytes.length)return q;let A=this.position;return this.position=A+x,A}readTag(){let x=this.consume(1);return mx(x)?this.bytes[x]:x}readUint8(){let x=this.consume(1);return mx(x)?this.bytes[x]:x}readUint16(){let x=this.consume(2);return i(x)?x:this.bytes[x]<<8|this.bytes[x+1]}readUint32(){let x=this.consume(4);return i(x)?x:this.bytes[x]<<24|this.bytes[x+1]<<16|this.bytes[x+2]<<8|this.bytes[x+3]}readUint64(){let x=this.readUint32();if(i(x))return x;if(x>=2097152)return v;let A=this.readUint32();return i(A)?A:x<<32|A}readInt8(){let x=this.readUint8();return i(x)||x>=128&&(x=x-256),x}readInt16(){let x=this.readUint16();return i(x)||x>=32768&&(x=x-65536),x}readInt32(){let x=this.readUint32();return i(x)||x>=2147483648&&(x=x-4294967296),x}readInt64(){let x=this.readUint32();if(i(x))return x;if(x>=2097152||x<-2097152)return v;let A=this.readUint32();return i(A)?A:x<<32|A}readFloat32(){let x=this.consume(4);return i(x)?x:new Float32Array(this.bytes.subarray(x,x+4))[0]}readFloat64(){let x=this.consume(8);return i(x)?x:new Float64Array(this.bytes.subarray(x,x+8))[0]}}});var O0,H0=p(()=>{"use strict";O0="1.19.0"});function w0(t,x){G||(G=t??new d.Logger(d.LogLevel.DEBUG,"odin-plugin-web",[]),x&&G.sinks.push(new d.CallbackSink(x,d.Formatter.structured)))}function c(t,...x){let A=Gx(x);G?G?.error(t,A):(0,d.error)(t,A)}function C(t,...x){let A=Gx(x);G?G?.warn(t,A):(0,d.warn)(t,A)}function n(t,...x){let A=Gx(x);G?G?.info(t,A):(0,d.info)(t,A)}function s(t,...x){let A=Gx(x);G?G?.debug(t,A):(0,d.debug)(t,A)}function Gx(...t){if(t.length===1&&typeof t[0]=="object"&&t[0]!==null)return{...t[0]};if(t.length>0)return{args:t}}var d,G,R0=p(()=>{"use strict";d=require("@4players/odin-common")});function h(t){return t.connectionId*4294967296+t.mediaId}var I,Y,o=p(()=>{"use strict";B0();qx();B0();q0();N0();L0();H0();R0();qx();I={isSilent:!0,rmsDBFS:-758.596};Y=class{constructor(){this.inFlight=null}run(x){return this.inFlight||(this.inFlight=x().finally(()=>{this.inFlight=null})),this.inFlight}}});function nx(t,x,A,F,D){return Promise.all([CF(t),EF(A,x,F,D)])}async function CF(t){let x=URL.createObjectURL(new Blob([t],{type:"text/javascript"})),A=new Worker(x,{type:"module",name:"odin worker"});return Bx.push(A),A}async function EF(t,x,A,F){try{let e=new AudioWorkletNode(t,A,F);return xx.push(e),e}catch{}let D=C0.get(t);if(D===void 0){let e=URL.createObjectURL(new Blob([x],{type:"text/javascript"}));D=t.audioWorklet.addModule(e),C0.set(t,D),D.catch(()=>C0.delete(t))}await D;let r=new AudioWorkletNode(t,A,F);return xx.push(r),r}async function V0(){return{workers:await Promise.all(Bx.map(Ex)),worklets:await Promise.all(xx.map(t=>Ex(t.port)))}}function Ex(t){let{port1:x,port2:A}=new MessageChannel,{promise:F,resolve:D}=Promise.withResolvers();return A.onmessage=r=>D(r.data),setTimeout(()=>D("timeout"),100),l(t,["dump",{result:x}],[x]),F}var Bx,xx,vx,Cx,C0,gx=p(()=>{"use strict";o();Bx=[],xx=[],vx=class{constructor(x,A,F){this.audioContext=x;this.worklet=A;this.worker=F;this.availableIndexes=[];this.medias=new Map;F.addEventListener("message",this._OnMessages.bind(this))}connectOutput(x){this.worklet.disconnect(),this.worklet.connect(x)}receivePacket(x,A){l(this.worker,["playbackReceivePacket",{connectionId:x,packet:A}],[A.buffer])}addMedias(x,A,F=[1,1]){let D=[];for(let r of A){let e=this._GetFreeIndex();e!==void 0&&(this.medias.set(h({connectionId:x,mediaId:r}),{index:e}),D.push({connectionId:x,mediaId:r,index:e,volume:F}))}l(this.worker,["playbackUpdateMedias",{added:D,removed:[]}])}removeMedias(x,A){let F=[];for(let D of A){let r=h({connectionId:x,mediaId:D}),e=this.medias.get(r);e!==void 0&&(this.medias.delete(r),this.availableIndexes.push(e.index),F.push({connectionId:x,mediaId:D,index:e.index}))}l(this.worker,["playbackUpdateMedias",{added:[],removed:F}])}close(){l(this.worker,["close",void 0]),l(this.worklet.port,["close",void 0]);let x=Bx.indexOf(this.worker);x>=0&&Bx.splice(x,1);let A=xx.indexOf(this.worklet);A>=0&&xx.splice(A,1)}async dump(){return{playbackWorker:await Ex(this.worker),playbackWorklet:await Ex(this.worklet.port)}}_GetFreeIndex(){return this.availableIndexes.pop()}_OnMessages(x){}},Cx=class t{constructor(x,A,F,D,r){this.worklet=x;this.worker=A;this.sink=(e,j)=>{r.deref()!==void 0?F(e,j):(c("capture worker was left abandoned, aborting capture worker"),t.shutdown(x,A))},this.monitorSink=(e,j)=>{r.deref()!==void 0?D(e,j):(c("capture worker was left abandoned, aborting capture worker"),t.shutdown(x,A))},A.addEventListener("message",this._OnMessages.bind(this))}get context(){return this.worklet.context}setMedias(x){l(this.worker,["captureSetMedias",{connections:x}])}setVad(x){l(this.worker,["captureSetVad",x])}close(){t.shutdown(this.worklet,this.worker)}static shutdown(x,A){l(x.port,["close",void 0]),l(A,["close",void 0]);let F=Bx.indexOf(A);F>=0&&Bx.splice(F,1);let D=xx.indexOf(x);D>=0&&xx.splice(D,1)}async dump(){return{captureWorker:await Ex(this.worker),captureWorklet:await Ex(this.worklet.port)}}_OnMessages(x){let[A,F]=x.data;A==="sendPacket"&&(F.connectionId===0?this.monitorSink(F.connectionId,F.packet):this.sink(F.connectionId,F.packet))}};C0=new WeakMap});var E0,U0=p(()=>{E0=`"use strict";(()=>{var Xe=Object.create;var nr=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Ze=Object.getPrototypeOf,Ye=Object.prototype.hasOwnProperty;var An=(e,A)=>()=>{try{return A||e((A={exports:{}}).exports,A),A.exports}catch(t){throw A=0,t}},rn=(e,A)=>{for(var t in A)nr(e,t,{get:A[t],enumerable:!0})},jn=(e,A,t,s)=>{if(A&&typeof A=="object"||typeof A=="function")for(let l of ze(A))!Ye.call(e,l)&&l!==t&&nr(e,l,{get:()=>A[l],enumerable:!(s=We(A,l))||s.enumerable});return e};var tn=(e,A,t)=>(t=e!=null?Xe(Ze(e)):{},jn(A||!e||!e.__esModule?nr(t,"default",{value:e,enumerable:!0}):t,e));var pt=An((Gt,TA)=>{"use strict";var JA=(()=>{var e=globalThis.document?.currentScript?.src;return async function(A={}){var t=A,s=!!globalThis.window,l=!!globalThis.WorkerGlobalScope;globalThis.process?.versions?.node&&globalThis.process;var c=l&&globalThis.name=="em-pthread",C=(r,j)=>{throw j};if(l&&(e=self.location.href),s||l)try{new URL(".",e).href}catch{}var G=console.log.bind(console),h=console.error.bind(console),_,W=!1,y;function Ft(r){for(var j,n=0,i=r.length,o=new Uint8Array(i);n<i;++n)j=r.charCodeAt(n),o[n]=~j>>8&j;return o}var $r;if(c){var MA=!1;self.onunhandledrejection=r=>{throw r.reason||r},self.onmessage=function r(j){try{var n=j.data,i=n.cmd;if(i==1){let o=[];self.onmessage=a=>o.push(a),$r=()=>{postMessage({cmd:3});for(let a of o)r(a);self.onmessage=r};for(let a of n.handlers)(!t[a]||t[a].proxy)&&(t[a]=(...k)=>{postMessage({cmd:9,handler:a,args:k})},a=="print"&&(G=t[a]),a=="printErr"&&(h=t[a]));nA=n.wasmMemory,vr(),_=n.wasmModule,Hr(),_j(),$r()}else if(i==2){gt(n.pthread_ptr),jr(n.pthread_ptr,0,0,1,0,0),E.threadInitTLS(),YA(n.pthread_ptr),MA||(Cj(),MA=!0);try{Dt(n.start_routine,n.arg)}catch(o){if(o!="unwind")throw o}}else i==4?MA&&_A():i&&(h(\`worker: received unknown command \${i}\`),h(n))}catch(o){throw Fr&&qj(),o}}}var Fr=!1;function vr(){var r=nA.buffer;U=new Int8Array(r),EA=new Int16Array(r),t.HEAPU8=b=new Uint8Array(r),lA=new Uint16Array(r),t.HEAP32=T=new Int32Array(r),t.HEAPU32=$=new Uint32Array(r),t.HEAPF32=ej=new Float32Array(r),GA=new Float64Array(r),R=new BigInt64Array(r),Sr=new BigUint64Array(r)}function vt(){var r=t.preRun;r&&(typeof r=="function"&&(r=[r]),Dr.push(...r)),gr(Dr)}function Ir(){Fr=!0,!c&&rA.F()}function It(){var r=t.postRun;r&&(typeof r=="function"&&(r=[r]),Jr.push(...r)),gr(Jr)}function qA(r){throw t.onAbort?.(r),r=\`Aborted(\${r})\`,h(r),W=!0,r+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(r)}var Nr;function Nt(){return Ft(\`\\0asm\\0\\0\\0\\xAC=\\\`\\x7F\\0\\\`\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\0\\0\\\`\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`||\\\`\\x7F}\\\`}}\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\0\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F~\\\`\\x7F\\x7F}\\\`\\x7F}}\\\`\\x7F\\x7F}}\\0\\\`
|
|
1
|
+
"use strict";var j0=Object.defineProperty;var IA=Object.getOwnPropertyDescriptor;var NA=Object.getOwnPropertyNames;var PA=Object.prototype.hasOwnProperty;var h=(t,x,A)=>()=>{if(A)throw A[0];try{return t&&(x=t(t=0)),x}catch(F){throw A=[F],F}};var hx=(t,x)=>{for(var A in x)j0(t,A,{get:x[A],enumerable:!0})},LA=(t,x,A,F)=>{if(x&&typeof x=="object"||typeof x=="function")for(let D of NA(x))!PA.call(t,D)&&D!==A&&j0(t,D,{get:()=>x[D],enumerable:!(F=IA(x,D))||F.enumerable});return t};var OA=t=>LA(j0({},"__esModule",{value:!0}),t);var n={};hx(n,{AdditionalCaptureBlocks:()=>wA,AdditionalPlaybackBlocks:()=>HA,ClockJumpCheckInterval:()=>UA,ClockJumpThreshold:()=>KA,ConnectInterval:()=>rF,ConnectTimeout:()=>AF,DefaultRefreshRate:()=>RA,DefaultVideoCodec:()=>eF,HealthCheckTimeout:()=>VA,MainConnectionPingInterval:()=>WA,MaxNumberOfDecoders:()=>MA,MaxReconnectDuration:()=>tF,MinDBFs:()=>v0,MinTokenLifetime:()=>FF,MinTokenRefreshInterval:()=>DF,PlaybackPreload:()=>SA,RenderQuantumSize:()=>JA,VadPreload:()=>TA,WebRtcAnswerTimeout:()=>ZA,WebRtcIceTimeout:()=>XA,WebRtcMaxNegotiationAttempts:()=>YA,WebRtcRecoveryDelays:()=>xF,WebRtcStatsSnapshotInterval:()=>QA,WebRtcTimeout:()=>zA});var HA,wA,SA,RA,TA,MA,JA,v0,VA,UA,KA,WA,QA,XA,zA,ZA,YA,xF,AF,FF,DF,rF,tF,eF,B0=h(()=>{"use strict";HA=3,wA=3,SA=3,RA=250,TA=3,MA=512,JA=128,v0=-758.596,VA=1e4,UA=1e3,KA=1e4,WA=3e3,QA=1e3,XA=3e3,zA=1e4,ZA=1e4,YA=3,xF=[0,2e3,5e3],AF=5e3,FF=6e4,DF=5e3,rF=[0,100,200,200,500],tF=12e4,eF="H264"});function mx(t){return typeof t!="symbol"}function i(t){return typeof t=="symbol"}var m,B,U,q,qx=h(()=>{"use strict";m=Symbol("Unencrypted"),B=Symbol("Invalid"),U=Symbol("Retry"),q=Symbol("UnexpectedEof")});function u(t,x,A){return t.postMessage(x,A)}function tx(t,x){return new Promise(A=>{let F=D=>{let[r]=D.data;r===x&&(A(D.data[1]),t.removeEventListener("message",F))};t.addEventListener("message",F)})}var q0=h(()=>{"use strict"});function C0(t,x){t.values[0]=x[0],t.values[1]=x[1]}function G0(t,x){return t.values[2+x*5]}function y0(t,x,A){let F=2+x*5+1;t.values[F+0]=A[0],t.values[F+1]=A[1]}function g0(t){return t.values[0]!==0}function $0(t){return t.values[1]}function _0(t){return t.values[2]}function I0(t,x){return t.values[3]=x}var N0=h(()=>{"use strict"});function P0(t,x){let A=new K(t);A.position=x;let F=A.readObjects(1);return mx(F)?A.position:F}var K,L0=h(()=>{"use strict";qx();K=class{constructor(x,A=0){this.bytes=x;this.position=A}readArrayLength(){let x=this.readTag();return i(x)?x:(x&240)===144?x&15:x===220?this.readUint16():x===221?this.readUint32():B}readNumber(){let x=this.readTag();return i(x)||(x&128)===0?x:(x&224)===224?x-256:x===202?this.readFloat32():x===203?this.readFloat64():x===204?this.readUint8():x===205?this.readUint16():x===206?this.readUint32():x===207?this.readUint64():x===208?this.readInt8():x===209?this.readInt16():x===210?this.readInt32():x===211?this.readInt64():B}readBytes(){let x=this.readTag();if(i(x))return x;let A;if(x===196)A=this.readUint8();else if(x===197)A=this.readUint16();else if(x===198)A=this.readUint32();else return B;if(i(A))return A;let F=this.consume(A);return F!==q?this.bytes.subarray(F,F+A):q}readObjects(x){for(;x>0;x-=1){let A=this.readTag();if(i(A))return A;let F,D=0,r=0;switch(A){case 192:break;case 194:break;case 195:break;case 196:D=this.readUint8();break;case 197:D=this.readUint16();break;case 198:D=this.readUint32();break;case 199:D=this.readUint8(),r=1;break;case 200:D=this.readUint8(),r=1;break;case 201:D=this.readUint32(),r=1;break;case 202:D=4;break;case 203:D=8;break;case 204:D=1;break;case 205:D=2;break;case 206:D=4;break;case 207:D=8;break;case 208:D=1;break;case 209:D=2;break;case 210:D=4;break;case 211:D=8;break;case 212:D=2;break;case 213:D=3;break;case 214:D=5;break;case 215:D=9;break;case 216:D=17;break;case 217:D=this.readUint8();break;case 218:D=this.readUint16();break;case 219:D=this.readUint32();break;case 220:if(F=this.readUint16(),i(F))return F;x+=F;break;case 221:if(F=this.readUint32(),i(F))return F;x+=F;break;case 222:if(F=this.readUint16(),i(F))return F;x+=F*2;break;case 223:if(F=this.readUint32(),i(F))return F;x+=F*2;break;default:if((A&128)!==0){if((A&240)===128)x+=(A&15)*2;else if((A&240)===144)x+=A&15;else if((A&224)===160)D=A&31;else if((A&224)!==224)return B}}if(D===q)return q;if(this.consume(D+r)===q)return q}}consume(x){if(x===q||this.position+x>this.bytes.length)return q;let A=this.position;return this.position=A+x,A}readTag(){let x=this.consume(1);return mx(x)?this.bytes[x]:x}readUint8(){let x=this.consume(1);return mx(x)?this.bytes[x]:x}readUint16(){let x=this.consume(2);return i(x)?x:this.bytes[x]<<8|this.bytes[x+1]}readUint32(){let x=this.consume(4);return i(x)?x:this.bytes[x]<<24|this.bytes[x+1]<<16|this.bytes[x+2]<<8|this.bytes[x+3]}readUint64(){let x=this.readUint32();if(i(x))return x;if(x>=2097152)return B;let A=this.readUint32();return i(A)?A:x<<32|A}readInt8(){let x=this.readUint8();return i(x)||x>=128&&(x=x-256),x}readInt16(){let x=this.readUint16();return i(x)||x>=32768&&(x=x-65536),x}readInt32(){let x=this.readUint32();return i(x)||x>=2147483648&&(x=x-4294967296),x}readInt64(){let x=this.readUint32();if(i(x))return x;if(x>=2097152||x<-2097152)return B;let A=this.readUint32();return i(A)?A:x<<32|A}readFloat32(){let x=this.consume(4);return i(x)?x:new Float32Array(this.bytes.subarray(x,x+4))[0]}readFloat64(){let x=this.consume(8);return i(x)?x:new Float64Array(this.bytes.subarray(x,x+8))[0]}}});var O0,H0=h(()=>{"use strict";O0="1.20.0"});function w0(t,x){G||(G=t??new d.Logger(d.LogLevel.DEBUG,"odin-plugin-web",[]),x&&G.sinks.push(new d.CallbackSink(x,d.Formatter.structured)))}function c(t,...x){let A=Gx(x);G?G?.error(t,A):(0,d.error)(t,A)}function C(t,...x){let A=Gx(x);G?G?.warn(t,A):(0,d.warn)(t,A)}function f(t,...x){let A=Gx(x);G?G?.info(t,A):(0,d.info)(t,A)}function s(t,...x){let A=Gx(x);G?G?.debug(t,A):(0,d.debug)(t,A)}function Gx(...t){if(t.length===1&&typeof t[0]=="object"&&t[0]!==null)return{...t[0]};if(t.length>0)return{args:t}}var d,G,S0=h(()=>{"use strict";d=require("@4players/odin-common")});function k(t){return t.connectionId*4294967296+t.mediaId}var I,Y,b=h(()=>{"use strict";B0();qx();B0();q0();N0();L0();H0();S0();qx();I={isSilent:!0,rmsDBFS:-758.596};Y=class{constructor(){this.inFlight=null}run(x){return this.inFlight||(this.inFlight=x().finally(()=>{this.inFlight=null})),this.inFlight}}});function nx(t,x,A,F,D){return Promise.all([CF(t),EF(A,x,F,D)])}async function CF(t){let x=URL.createObjectURL(new Blob([t],{type:"text/javascript"})),A=new Worker(x,{type:"module",name:"odin worker"});return vx.push(A),A}async function EF(t,x,A,F){try{let e=new AudioWorkletNode(t,A,F);return xx.push(e),e}catch{}let D=E0.get(t);if(D===void 0){let e=URL.createObjectURL(new Blob([x],{type:"text/javascript"}));D=t.audioWorklet.addModule(e),E0.set(t,D),D.catch(()=>E0.delete(t))}await D;let r=new AudioWorkletNode(t,A,F);return xx.push(r),r}async function V0(){return{workers:await Promise.all(vx.map(Ex)),worklets:await Promise.all(xx.map(t=>Ex(t.port)))}}function Ex(t){let{port1:x,port2:A}=new MessageChannel,{promise:F,resolve:D}=Promise.withResolvers();return A.onmessage=r=>D(r.data),setTimeout(()=>D("timeout"),100),u(t,["dump",{result:x}],[x]),F}var vx,xx,Bx,Cx,E0,gx=h(()=>{"use strict";b();vx=[],xx=[],Bx=class{constructor(x,A,F){this.audioContext=x;this.worklet=A;this.worker=F;this.availableIndexes=[];this.medias=new Map;F.addEventListener("message",this._OnMessages.bind(this))}connectOutput(x){this.worklet.disconnect(),this.worklet.connect(x)}receivePacket(x,A){u(this.worker,["playbackReceivePacket",{connectionId:x,packet:A}],[A.buffer])}addMedias(x,A,F=[1,1]){let D=[];for(let r of A){let e=this._GetFreeIndex();e!==void 0&&(this.medias.set(k({connectionId:x,mediaId:r}),{index:e}),D.push({connectionId:x,mediaId:r,index:e,volume:F}))}u(this.worker,["playbackUpdateMedias",{added:D,removed:[]}])}removeMedias(x,A){let F=[];for(let D of A){let r=k({connectionId:x,mediaId:D}),e=this.medias.get(r);e!==void 0&&(this.medias.delete(r),this.availableIndexes.push(e.index),F.push({connectionId:x,mediaId:D,index:e.index}))}u(this.worker,["playbackUpdateMedias",{added:[],removed:F}])}close(){u(this.worker,["close",void 0]),u(this.worklet.port,["close",void 0]);let x=vx.indexOf(this.worker);x>=0&&vx.splice(x,1);let A=xx.indexOf(this.worklet);A>=0&&xx.splice(A,1)}async dump(){return{playbackWorker:await Ex(this.worker),playbackWorklet:await Ex(this.worklet.port)}}_GetFreeIndex(){return this.availableIndexes.pop()}_OnMessages(x){}},Cx=class t{constructor(x,A,F,D,r){this.worklet=x;this.worker=A;this.sink=(e,j)=>{r.deref()!==void 0?F(e,j):(c("capture worker was left abandoned, aborting capture worker"),t.shutdown(x,A))},this.monitorSink=(e,j)=>{r.deref()!==void 0?D(e,j):(c("capture worker was left abandoned, aborting capture worker"),t.shutdown(x,A))},A.addEventListener("message",this._OnMessages.bind(this))}get context(){return this.worklet.context}setMedias(x){u(this.worker,["captureSetMedias",{connections:x}])}setVad(x){u(this.worker,["captureSetVad",x])}close(){t.shutdown(this.worklet,this.worker)}static shutdown(x,A){u(x.port,["close",void 0]),u(A,["close",void 0]);let F=vx.indexOf(A);F>=0&&vx.splice(F,1);let D=xx.indexOf(x);D>=0&&xx.splice(D,1)}async dump(){return{captureWorker:await Ex(this.worker),captureWorklet:await Ex(this.worklet.port)}}_OnMessages(x){let[A,F]=x.data;A==="sendPacket"&&(F.connectionId===0?this.monitorSink(F.connectionId,F.packet):this.sink(F.connectionId,F.packet))}};E0=new WeakMap});var n0,U0=h(()=>{n0=`"use strict";(()=>{var Xe=Object.create;var nr=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Ze=Object.getPrototypeOf,Ye=Object.prototype.hasOwnProperty;var An=(e,A)=>()=>{try{return A||e((A={exports:{}}).exports,A),A.exports}catch(t){throw A=0,t}},rn=(e,A)=>{for(var t in A)nr(e,t,{get:A[t],enumerable:!0})},jn=(e,A,t,s)=>{if(A&&typeof A=="object"||typeof A=="function")for(let l of ze(A))!Ye.call(e,l)&&l!==t&&nr(e,l,{get:()=>A[l],enumerable:!(s=We(A,l))||s.enumerable});return e};var tn=(e,A,t)=>(t=e!=null?Xe(Ze(e)):{},jn(A||!e||!e.__esModule?nr(t,"default",{value:e,enumerable:!0}):t,e));var pt=An((Gt,TA)=>{"use strict";var JA=(()=>{var e=globalThis.document?.currentScript?.src;return async function(A={}){var t=A,s=!!globalThis.window,l=!!globalThis.WorkerGlobalScope;globalThis.process?.versions?.node&&globalThis.process;var c=l&&globalThis.name=="em-pthread",C=(r,j)=>{throw j};if(l&&(e=self.location.href),s||l)try{new URL(".",e).href}catch{}var G=console.log.bind(console),h=console.error.bind(console),_,W=!1,y;function Ft(r){for(var j,n=0,i=r.length,o=new Uint8Array(i);n<i;++n)j=r.charCodeAt(n),o[n]=~j>>8&j;return o}var $r;if(c){var MA=!1;self.onunhandledrejection=r=>{throw r.reason||r},self.onmessage=function r(j){try{var n=j.data,i=n.cmd;if(i==1){let o=[];self.onmessage=a=>o.push(a),$r=()=>{postMessage({cmd:3});for(let a of o)r(a);self.onmessage=r};for(let a of n.handlers)(!t[a]||t[a].proxy)&&(t[a]=(...k)=>{postMessage({cmd:9,handler:a,args:k})},a=="print"&&(G=t[a]),a=="printErr"&&(h=t[a]));nA=n.wasmMemory,vr(),_=n.wasmModule,Hr(),_j(),$r()}else if(i==2){gt(n.pthread_ptr),jr(n.pthread_ptr,0,0,1,0,0),E.threadInitTLS(),YA(n.pthread_ptr),MA||(Cj(),MA=!0);try{Dt(n.start_routine,n.arg)}catch(o){if(o!="unwind")throw o}}else i==4?MA&&_A():i&&(h(\`worker: received unknown command \${i}\`),h(n))}catch(o){throw Fr&&qj(),o}}}var Fr=!1;function vr(){var r=nA.buffer;U=new Int8Array(r),EA=new Int16Array(r),t.HEAPU8=b=new Uint8Array(r),lA=new Uint16Array(r),t.HEAP32=T=new Int32Array(r),t.HEAPU32=$=new Uint32Array(r),t.HEAPF32=ej=new Float32Array(r),GA=new Float64Array(r),R=new BigInt64Array(r),Sr=new BigUint64Array(r)}function vt(){var r=t.preRun;r&&(typeof r=="function"&&(r=[r]),Dr.push(...r)),gr(Dr)}function Ir(){Fr=!0,!c&&rA.F()}function It(){var r=t.postRun;r&&(typeof r=="function"&&(r=[r]),Jr.push(...r)),gr(Jr)}function qA(r){throw t.onAbort?.(r),r=\`Aborted(\${r})\`,h(r),W=!0,r+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(r)}var Nr;function Nt(){return Ft(\`\\0asm\\0\\0\\0\\xAC=\\\`\\x7F\\0\\\`\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\0\\0\\\`\\x7F\\x7F\\x7F\\x7F\\\`\\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\\\`\\x07\\x7F|\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F|}\\\`\\x7F\\x7F\\x7F~~\\0\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F|\\\`\\0|\\\`\\r\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F\\x7F\\x7F\\\`\\x7F\\x7F|\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\x7F\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F}}\\x7F\\x7F\\x7F\\x7F\\0\\\`~\\x7F\\x7F\\\` \\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\\`||\\x7F|\\\`|||\\\`\\x7F\\x7F\\x7F|\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\\`\\f\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`}\\x7F\\x7F\\\`|\\x7F\\x7F\\\`\\x7F\\x7F\\x7F}\\\`\\x7F}\\x7F\\0\\\`\\x7F\\x7F}\\x7F\\x7F\\x7F}\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F}}\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F|\\\`\\x7F\\x7F|\\0\\xBFaa\\x80\\x80ab\\0ac\\0ad\\0ae\\0af\\0ag\\0ah\\0!ai\\0
|
|
3
3
|
aj\\0"ak\\0#al\\0am\\0 an\\0$ao\\0ap\\0aq\\0ar\\0\\0as\\0\\0at\\0au\\0av\\0%aw\\0ax\\0\\x07ay\\0\\0az\\0\\0aA\\0\\x07aB\\0\\0aC\\0\\x07aD\\0\\0aE\\0\\xFE\\xFC\\0\\b\\f&\\0\\f\\b\\f\\f\\0\\b\\0\\0'(
|
|
4
4
|
\\x07\\v)*\\0\\f+,-\\b\\v\\0\\0\\b\\0\\x07\\x07\\x1B
|
|
@@ -3355,7 +3355,7 @@ stackRestore(sp);
|
|
|
3355
3355
|
return ret;
|
|
3356
3356
|
\`),m+=\`}
|
|
3357
3357
|
\`,new Function(F,m)}function zA(r,j,n,i,o,a){var k=j.length;k<2&&p("argTypes array size mismatch! Must at least get return value and receiver (this) types!");var u=j[1]!==null&&n!==null,d=Yr(j),q=Aj(j),f=q&&!a&&!d;q&&!f&&(d=!0);var m=!j[0].isVoid,I=j[0],F=j[1],N=[r,p,i,o,Zr,I.fromWireType.bind(I),F?.toWireType.bind(F)];f&&N.push(Br,RA);for(var v=2;v<k;++v){var g=j[v];N.push(g.toWireType.bind(g))}if(!d)for(v=u?1:2;v<j.length;++v)j[v].destructorFunction!==null&&N.push(j[v].destructorFunction);var K=ne(j,u,m,a)(...N);return Vr(r,K)}var se=(r,j,n,i,o,a)=>{var k=WA(j,n);o=P(i,o),M([],[r],u=>{u=u[0];var d=\`constructor \${u.name}\`;if(u.registeredClass.constructor_body===void 0&&(u.registeredClass.constructor_body=[]),u.registeredClass.constructor_body[j-1]!==void 0)throw new sA(\`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]=()=>{Y(\`Cannot construct \${u.name} due to unbound types\`,k)},M([],k,q=>(q.splice(1,0,null),u.registeredClass.constructor_body[j-1]=zA(d,q,null,o,a),[])),[]})},rj=r=>{r=r.trim();let j=r.indexOf("(");return j===-1?r:r.slice(0,j)},le=(r,j,n,i,o,a,k,u,d)=>{var q=WA(n,i);j=H(j),j=rj(j),a=P(o,a),M([],[r],f=>{f=f[0];var m=\`\${f.name}.\${j}\`;j.startsWith("@@")&&(j=Symbol[j.substring(2)]),u&&f.registeredClass.pureVirtualFunctions.push(j);function I(){Y(\`Cannot call \${m} due to unbound types\`,q)}var F=f.registeredClass.instancePrototype,N=F[j];return N===void 0||N.overloadTable===void 0&&N.className!==f.name&&N.argCount===n-2?(I.argCount=n-2,I.className=f.name,F[j]=I):(Qr(F,j,m),F[j].overloadTable[n-2]=I),M([],q,v=>{var g=zA(m,v,f,a,k,d);return F[j].overloadTable===void 0?(g.argCount=n-2,F[j]=g):F[j].overloadTable[n-2]=g,[]}),[]})},jj=(r,j,n)=>(r instanceof Object||p(\`\${n} with invalid "this": \${r}\`),r instanceof j.registeredClass.constructor||p(\`\${n} incompatible with "this" of type \${r.constructor.name}\`),r.$$.ptr||p(\`cannot call emscripten binding method \${n} on deleted object\`),$A(r.$$.ptr,r.$$.ptrType.registeredClass,j.registeredClass)),ie=(r,j,n,i,o,a,k,u,d,q)=>{j=H(j),o=P(i,o),M([],[r],f=>{f=f[0];var m=\`\${f.name}.\${j}\`,I={get(){Y(\`Cannot access \${m} due to unbound types\`,[n,k])},enumerable:!0,configurable:!0};return d?I.set=()=>Y(\`Cannot access \${m} due to unbound types\`,[n,k]):I.set=()=>p(m+" is a read-only property"),Object.defineProperty(f.registeredClass.instancePrototype,j,I),M([],d?[n,k]:[n],F=>{var N=F[0],v={get(){var J=jj(this,f,m+" getter");return N.fromWireType(o(a,J))},enumerable:!0};if(d){d=P(u,d);var g=F[1];v.set=function(J){var K=jj(this,f,m+" setter"),O=[];d(q,K,g.toWireType(O,J)),Zr(O)}}return Object.defineProperty(f.registeredClass.instancePrototype,j,v),[]}),[]})},tj=[],V=[0,1,,1,null,1,!0,1,!1,1],oe=r=>{r>9&&--V[r+1]===0&&(V[r],V[r]=void 0,tj.push(r))},ZA={toValue:r=>(r||p(\`Cannot use deleted val. handle = \${r}\`),V[r]),toHandle:r=>{switch(r){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:{let j=tj.pop()||V.length;return V[j]=r,V[j+1]=1,j}}}},ae={name:"emscripten::val",fromWireType:r=>{var j=ZA.toValue(r);return oe(r),j},toWireType:(r,j)=>ZA.toHandle(j),readValueFromPointer:FA,destructorFunction:null},ke=r=>B(r,ae),ej,ue=(r,j)=>{switch(j){case 4:return function(n){return this.fromWireType(ej[n>>2])};case 8:return function(n){return this.fromWireType(GA[n>>3])};default:throw new TypeError(\`invalid float width (\${j}): \${r}\`)}},ce=(r,j,n)=>{j=H(j),B(r,{name:j,fromWireType:i=>i,toWireType:(i,o)=>o,readValueFromPointer:ue(j,n),destructorFunction:null})},de=(r,j,n,i,o,a,k)=>{var u=WA(j,n);r=H(r),r=rj(r),o=P(i,o),Xr(r,function(){Y(\`Cannot call \${r} due to unbound types\`,u)},j-1),M([],u,d=>{var q=[d[0],null].concat(d.slice(1));return zr(r,zA(r,q,null,o,a,k),j-1),[]})},Ce=(r,j,n,i,o)=>{j=H(j);let a=i===0,k=d=>d;if(a){var u=32-8*n;k=d=>d<<u>>>u,o=k(o)}B(r,{name:j,fromWireType:k,toWireType:(d,q)=>q,readValueFromPointer:wr(j,n,i!==0),destructorFunction:null})},fe=(r,j,n)=>{var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=i[j];function a(k){var u=$[k>>2],d=$[k+4>>2];return new o(U.buffer,d,u)}n=H(n),B(r,{name:n,fromWireType:a,readValueFromPointer:a},{ignoreDuplicateRegistrations:!0})},qe=(r,j,n,i)=>{if(!(i>0))return 0;for(var o=n,a=n+i-1,k=0;k<r.length;++k){var u=r.codePointAt(k);if(u<=127){if(n>=a)break;j[n++]=u}else if(u<=2047){if(n+1>=a)break;j[n++]=192|u>>6,j[n++]=128|u&63}else if(u<=65535){if(n+2>=a)break;j[n++]=224|u>>12,j[n++]=128|u>>6&63,j[n++]=128|u&63}else{if(n+3>=a)break;j[n++]=240|u>>18,j[n++]=128|u>>12&63,j[n++]=128|u>>6&63,j[n++]=128|u&63,k++}}return j[n]=0,n-o},Ge=(r,j,n)=>qe(r,b,j,n),pe=r=>{for(var j=0,n=0;n<r.length;++n){var i=r.charCodeAt(n);i<=127?j++:i<=2047?j+=2:i>=55296&&i<=57343?(j+=4,++n):j+=3}return j},nj=globalThis.TextDecoder&&new TextDecoder,sj=(r,j,n,i)=>{var o=j+n;if(i)return o;for(;r[j]&&!(j>=o);)++j;return j},lj=(r,j=0,n,i)=>{var o=sj(r,j,n,i);if(o-j>16&&r.buffer&&nj)return nj.decode(r.buffer instanceof ArrayBuffer?r.subarray(j,o):r.slice(j,o));for(var a="";j<o;){var k=r[j++];if(!(k&128)){a+=String.fromCharCode(k);continue}var u=r[j++]&63;if((k&224)==192){a+=String.fromCharCode((k&31)<<6|u);continue}var d=r[j++]&63;if((k&240)==224?k=(k&15)<<12|u<<6|d:k=(k&7)<<18|u<<12|d<<6|r[j++]&63,k<65536)a+=String.fromCharCode(k);else{var q=k-65536;a+=String.fromCharCode(55296|q>>10,56320|q&1023)}}return a},Ee=(r,j,n)=>r?lj(b,r,j,n):"",me=(r,j)=>{j=H(j),B(r,{name:j,fromWireType(n){var i=$[n>>2],o=n+4,a;if(1)a=Ee(o,i,!0);else for(var k;k<i;++k);return S(n),a},toWireType(n,i){i instanceof ArrayBuffer&&(i=new Uint8Array(i));var o,a=typeof i=="string";a||ArrayBuffer.isView(i)&&i.BYTES_PER_ELEMENT==1||p("Cannot pass non-string to std::string"),a?o=pe(i):o=i.length;var k=rr(4+o+1),u=k+4;if($[k>>2]=o,a)if(1)Ge(i,u,o+1);else for(var d;d<o;++d)var q;else b.set(i,u);return n!==null&&n.push(S,k),k},readValueFromPointer:FA,destructorFunction(n){S(n)}})},ij=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,he=(r,j,n)=>{var i=r>>1,o=sj(lA,i,j/2,n);if(o-i>16&&ij)return ij.decode(lA.slice(i,o));for(var a="",k=i;k<o;++k){var u=lA[k];a+=String.fromCharCode(u)}return a},$e=(r,j,n=2147483647)=>{if(n<2)return 0;n-=2;for(var i=j,o=n<r.length*2?n/2:r.length,a=0;a<o;++a){var k=r.charCodeAt(a);EA[j>>1]=k,j+=2}return EA[j>>1]=0,j-i},Fe=r=>r.length*2,ve=(r,j,n)=>{for(var i="",o=r>>2,a=0;!(a>=j/4);a++){var k=$[o+a];if(!k&&!n)break;i+=String.fromCodePoint(k)}return i},Ie=(r,j,n=2147483647)=>{if(n<4)return 0;for(var i=j,o=i+n-4,a=0;a<r.length;++a){var k=r.codePointAt(a);if(k>65535&&a++,T[j>>2]=k,j+=4,j+4>o)break}return T[j>>2]=0,j-i},Ne=r=>{for(var j=0,n=0;n<r.length;++n){var i=r.codePointAt(n);i>65535&&n++,j+=4}return j},_e=(r,j,n)=>{n=H(n);var i,o,a;j===2?(i=he,o=$e,a=Fe):(i=ve,o=Ie,a=Ne),B(r,{name:n,fromWireType:k=>{var u=$[k>>2],d=i(k+4,u*j,!0);return S(k),d},toWireType:(k,u)=>{typeof u!="string"&&p(\`Cannot pass non-string to C++ string type \${n}\`);var d=a(u),q=rr(4+d+j);return $[q>>2]=d/j,o(u,q+4,d+j),k!==null&&k.push(S,q),q},readValueFromPointer:FA,destructorFunction(k){S(k)}})},He=(r,j)=>{j=H(j),B(r,{isVoid:!0,name:j,fromWireType:()=>{},toWireType:()=>{}})},Le=r=>{var j=!s;try{Atomics.wait(T,0,0,0),j=!0}catch{}jr(r,!l,1,j,65536,!1),E.threadInitTLS()},oj=r=>{if(r instanceof Lr||r=="unwind")return y;C(0,r)},ye=()=>{if(!wA())try{if(c){oA()&&tr(y);return}UA(y)}catch(r){oj(r)}},aj=(r,...j)=>{if(!W)try{return r(...j)}catch(n){oj(n)}finally{ye()}},YA=r=>{if(!Pr){var j=Atomics.waitAsync(T,r>>2,r);j.value.then(_A);var n=r+112;Atomics.store(T,n>>2,1)}},_A=()=>{var r=oA();r&&aj(()=>{YA(r),mj()})},Oe=(r,j)=>{if(r==j)setTimeout(_A);else if(c)postMessage({targetThread:r,cmd:4});else{var n=E.pthreads[r];if(!n)return;n.postMessage({cmd:4})}},Ar=[],ge=(r,j,n,i,o,a,k)=>{Ar.length=0;for(var u=o>>3,d=o+i>>3;u<d;){var q;R[u++]?q=R[u++]:q=GA[u++],Ar.push(q)}var f=Ue[r];E.currentProxiedOperationCallerThread=n;var m=f(...Ar);if(E.currentProxiedOperationCallerThread=0,a){Promise.resolve(m).then(I=>Gj(a,k,I));return}return m},De=r=>{c?postMessage({cmd:6,thread:r}):Or(r)},Be=()=>{},xe=()=>performance.timeOrigin+performance.now(),be=r=>r<-9007199254740992||r>9007199254740992?NaN:Number(r),Pe=()=>{},Je=()=>{SA+=1},Te=()=>{throw Je(),"unwind"},Me=()=>{qA("OOM")},Se=r=>{b.length,r>>>=0,Me()};function kj(r){return c?eA(2,0,1,r):52}function uj(r,j,n,i){return c?eA(3,0,1,r,j,n,i):(j=be(j),70)}var we=[null,[],[]],Re=(r,j)=>{var n=we[r];!j||j===10?((r===1?G:h)(lj(n)),n.length=0):n.push(j)};function cj(r,j,n,i){if(c)return eA(4,0,1,r,j,n,i);for(var o=0,a=0;a<n;a++){var k=$[j>>2],u=$[j+4>>2];j+=8;for(var d=0;d<u;d++)Re(r,b[k+d]);o+=u}return $[i>>2]=o,0}E.init(),(()=>{let r=hA.prototype;Object.assign(r,{isAliasOf(n){if(!(this instanceof hA)||!(n instanceof hA))return!1;var i=this.$$.ptrType.registeredClass,o=this.$$.ptr;n.$$=n.$$;for(var a=n.$$.ptrType.registeredClass,k=n.$$.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||KA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var n=iA(Object.create(Object.getPrototypeOf(this),{$$:{value:Rt(this.$$)}}));return n.$$.count.value+=1,n.$$.deleteScheduled=!1,n},delete(){this.$$.ptr||KA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&p("Object already scheduled for deletion"),Rr(this),Ur(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||KA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&p("Object already scheduled for deletion"),mA.push(this),mA.length,this.$$.deleteScheduled=!0,this}});let j=Symbol.dispose;j&&(r[j]=r.delete)})(),Object.assign(NA.prototype,{getPointee(r){return this.rawGetPointee&&(r=this.rawGetPointee(r)),r},destructor(r){this.rawDestructor?.(r)},readValueFromPointer:FA,fromWireType:re}),(function(){c||(nA=new WebAssembly.Memory({initial:256,maximum:256,shared:!0}),vr())})(),t.noExitRuntime&&(VA=t.noExitRuntime),t.print&&(G=t.print),t.printErr&&(h=t.printErr),t.arguments&&t.arguments,t.thisProgram&&t.thisProgram;var AA=t.preInit;if(AA)for(typeof AA=="function"&&(t.preInit=AA=[AA]);AA.length>0;)AA.shift()();var Ue=[xr,br,kj,uj,cj],dj,Cj,oA,rr,S,jr,fj,qj,Gj,pj,Ej,tr,mj,hj,$j,Fj,vj,Ij;function Ve(r){dj=r.G,Cj=r.H,oA=r.J,rr=t._malloc=r.K,S=t._free=r.L,r.M,jr=r.N,fj=r.O,qj=r.P,Gj=r.Q,pj=r.R,Ej=r.S,tr=r.T,mj=r.U,hj=r.V,$j=r.W,Fj=r.X,vj=r.Y,Ij=r.I}var Nj;function Ke(){Nj={l:Jt,C:Tt,h:St,o:wt,n:ee,m:se,e:le,b:ie,D:ke,g:ce,q:de,d:Ce,c:fe,E:me,f:_e,p:He,z:Le,u:Oe,j:ge,s:De,y:YA,B:Be,x:Pe,A:Te,k:xe,t:Se,r:UA,w:kj,v:uj,i:cj,a:nA}}async function _j(){if(c){Ir();return}vt();var r=t.setStatus;r&&(r("Running..."),await new Promise(j=>setTimeout(j,1)),setTimeout(r,1,"")),!W&&(Ir(),t.onRuntimeInitialized?.(),It())}var rA;return c||(rA=await Hr(),await _j()),t}})();typeof Gt=="object"&&typeof TA=="object"?(TA.exports=JA,TA.exports.default=JA):typeof define=="function"&&define.amd&&define([],()=>JA);var us=globalThis.name=="em-pthread";us&&JA()});var x={};rn(x,{AdditionalCaptureBlocks:()=>nn,AdditionalPlaybackBlocks:()=>en,ClockJumpCheckInterval:()=>cn,ClockJumpThreshold:()=>dn,ConnectInterval:()=>vn,ConnectTimeout:()=>hn,DefaultRefreshRate:()=>ln,DefaultVideoCodec:()=>Nn,HealthCheckTimeout:()=>un,MainConnectionPingInterval:()=>Cn,MaxNumberOfDecoders:()=>an,MaxReconnectDuration:()=>In,MinDBFs:()=>Oj,MinTokenLifetime:()=>$n,MinTokenRefreshInterval:()=>Fn,PlaybackPreload:()=>sn,RenderQuantumSize:()=>kn,VadPreload:()=>on,WebRtcAnswerTimeout:()=>pn,WebRtcIceTimeout:()=>qn,WebRtcMaxNegotiationAttempts:()=>En,WebRtcRecoveryDelays:()=>mn,WebRtcStatsSnapshotInterval:()=>fn,WebRtcTimeout:()=>Gn});var en=3,nn=3,sn=3,ln=250,on=3,an=512,kn=128,Oj=-758.596,un=1e4,cn=1e3,dn=1e4,Cn=3e3,fn=1e3,qn=3e3,Gn=1e4,pn=1e4,En=3,mn=[0,2e3,5e3],hn=5e3,$n=6e4,Fn=5e3,vn=[0,100,200,200,500],In=12e4,Nn="H264";function aA(e,A,t){return e.postMessage(A,t)}function sr(e){return e.sampleRate*.02*(e.stereo?2:1)}function lr(e,A){let t=sr(e),s=t*A,l=s+t;return e.samples.subarray(s,l)}function ir(e,A,t){e.headers[A]=t.id}function gj(e){return[e.values[0],e.values[1]]}function Dj(e,A){e.values[0]=A[0],e.values[1]=A[1]}function Bj(e,A){return e.values[2+A*5]}function xj(e,A,t){e.values[2+A*5]=t}function bj(e,A){let t=2+A*5+1;return[e.values[t+0],e.values[t+1]]}function Pj(e,A,t){let s=2+A*5+1;e.values[s+0]=t[0],e.values[s+1]=t[1]}function Jj(e,A){return e.values[2+A*5+3]}function Tj(e,A,t){e.values[2+A*5+3]=t}function Mj(e,A){return e.values[2+A*5+4]}function Sj(e,A,t){e.values[2+A*5+4]=t}function wj(e){return e.values[0]!==0}function Rj(e){return e.values[1]}function Uj(e){return e.values[2]}function Vj(e){return e.values[3]}function Kj(e,A){return e.values[3]=A}function Qj(e){return e?Array.from(e).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var _n;(e=>{let A;(t=>(t[t.InvalidPassword=-1]="InvalidPassword",t[t.Unknown=0]="Unknown",t[t.Unencrypted=1]="Unencrypted",t[t.Encrypted=2]="Encrypted"))(A=e.PeerCipherStatus||={})})(_n||={});function Yj(e){return{type:"Success",value:e}}function D(e){return{type:"Failure",reason:e}}var{Deno:Xj}=globalThis,Hn=typeof Xj?.noColor=="boolean"?Xj.noColor:!1,Ln=!Hn;function ar(e,A){return{open:\`\\x1B[\${e.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function kr(e,A){return Ln?\`\${A.open}\${e.replace(A.regexp,A.open)}\${A.close}\`:e}function or(e){return kr(e,ar([0],0))}function Wj(e){return kr(e,ar([1],22))}function yn(e){return kr(e,ar([2],22))}var Is=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"),On=new Date,HA=(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))(HA||{}),At={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},gn={4:yn,3:or,2:or,1:Wj,0:Wj};function Dn({message:e}){return String(e)}function zj(e){return JSON.stringify({timestamp:e.date.toISOString(),level:HA[e.level],message:e.message,extra:e.extra})}function Zj(e){function A(C,G){return[Math.floor(C/G),C%G]}function t(){let C,G=e.date.valueOf()-On.valueOf();[G,C]=A(G,1e3);let[h,_]=A(G,60);return\`\${h.toString().padStart(4,"0")}:\${_.toString().padStart(2,"0")}.\${C.toString().padStart(3,"0")}\`}function s(){return e.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(e.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(e.extra)}let l=At[e.level],c=e.logger.name!==void 0?\`@\${e.logger.name}\`:"";return\`\${or(t())}\${c} \${l} \${gn[e.level](String(e.message))}\${s()}\`}function Bn(e){let A=\`[\${e.date.toISOString()}]\`,t=\`[\${HA[e.level]}]\`,s=e.logger.name!==void 0?\`[\${e.logger.name}] \`:"",l=At[e.level];return\`\${A} \${l} \${t.padEnd(7," ")} \${s}\${e.message}\`}function xn(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var rt=class{static sparse=Dn;static json=zj;static pretty=Zj;static structured=Bn;static default=xn()?Zj:zj;constructor(){}};var bn=class{formatter;consoleObject;filter;constructor(e=rt.default,A=4,t=console){this.filter=A,this.formatter=e,this.consoleObject=t}handle(e){let A=this.formatter(e);switch(e.level){case 0:case 1:this.consoleObject.error(A);break;case 2:this.consoleObject.warn(A);break;case 3:this.consoleObject.info(A);break;case 4:this.consoleObject.debug(A);break}}};var Q=class{#A;sinks;filter;parent;get name(){return this.#A}constructor(e,A=void 0,t=[],s=void 0){this.#A=A,this.sinks=t,this.filter=e,this.parent=s}log(e,A,t=void 0){let s={date:new Date,level:e,logger:this,message:A,extra:t};this.filter<e||this.insert(s)}insert(e){if(!(this.filter<e.level)){for(let A of this.sinks)A.filter>=e.level&&A.handle(e);this.parent!==void 0&&this.parent.insert(e)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},kA=globalThis[Symbol.for("odin-global-logger")]??=new Q(3,void 0,[new bn]),Pn=Q.prototype.log.bind(kA,1),Jn=Q.prototype.log.bind(kA,2),jt=Q.prototype.log.bind(kA,3),Tn=Q.prototype.log.bind(kA,4),Ns=Q.prototype.log.bind(kA);var tt;function et(e,...A){let t=Mn(A);tt?tt?.info(e,t):jt(e,t)}function Mn(...e){if(e.length===1&&typeof e[0]=="object"&&e[0]!==null)return{...e[0]};if(e.length>0)return{args:e}}function LA(e){return e.connectionId*4294967296+e.mediaId}function nt(e){return{mediaId:e%4294967296,connectionId:Math.floor(e/4294967296)}}function w(e,A,t){let s;switch(A){case"f32":s=e.HEAPF32;break;case"u32":s=e.HEAPU32;break;case"i32":s=e.HEAP32;break;case"u8":s=e.HEAPU8;break;default:throw new Error(\`allocating \${A} is not supported\`)}let l=e._malloc(t*s.BYTES_PER_ELEMENT);if(l===0||l%s.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${t} \${A} array\`);let c=l/s.BYTES_PER_ELEMENT;return s.subarray(c,c+t)}function jA(e,A){e._free(A.byteOffset)}function ur(e,A,t,s){return{headers:w(e,"i32",t),samples:w(e,"f32",t*sr({sampleRate:A,stereo:s})),length:t,sampleRate:A,stereo:s}}function cr(e,A){jA(e,A.headers),jA(e,A.samples)}function st(e,A){return{values:w(e,"f32",2+A*5),length:A}}function lt(e,A){jA(e,A.values)}function it(e){return{values:w(e,"f32",4)}}function ot(e,A){jA(e,A.values)}function at(e){let A=e.length,t=0,s=0;for(;s<A;){let l=e.charCodeAt(s++);if((l&4294967168)===0){t++;continue}else if((l&4294965248)===0)t+=2;else{if(l>=55296&&l<=56319&&s<A){let c=e.charCodeAt(s);(c&64512)===56320&&(++s,l=((l&1023)<<10)+(c&1023)+65536)}(l&4294901760)===0?t+=3:t+=4}}return t}function Sn(e,A,t){let s=e.length,l=t,c=0;for(;c<s;){let C=e.charCodeAt(c++);if((C&4294967168)===0){A[l++]=C;continue}else if((C&4294965248)===0)A[l++]=C>>6&31|192;else{if(C>=55296&&C<=56319&&c<s){let G=e.charCodeAt(c);(G&64512)===56320&&(++c,C=((C&1023)<<10)+(G&1023)+65536)}(C&4294901760)===0?(A[l++]=C>>12&15|224,A[l++]=C>>6&63|128):(A[l++]=C>>18&7|240,A[l++]=C>>12&63|128,A[l++]=C>>6&63|128)}A[l++]=C&63|128}}var wn=new TextEncoder,Rn=50;function Un(e,A,t){wn.encodeInto(e,A.subarray(t))}function kt(e,A,t){e.length>Rn?Un(e,A,t):Sn(e,A,t)}var Vn=4096;function dr(e,A,t){let s=A,l=s+t,c=[],C="";for(;s<l;){let G=e[s++];if((G&128)===0)c.push(G);else if((G&224)===192){let h=e[s++]&63;c.push((G&31)<<6|h)}else if((G&240)===224){let h=e[s++]&63,_=e[s++]&63;c.push((G&31)<<12|h<<6|_)}else if((G&248)===240){let h=e[s++]&63,_=e[s++]&63,W=e[s++]&63,y=(G&7)<<18|h<<12|_<<6|W;y>65535&&(y-=65536,c.push(y>>>10&1023|55296),y=56320|y&1023),c.push(y)}else c.push(G);c.length>=Vn&&(C+=String.fromCharCode(...c),c.length=0)}return c.length>0&&(C+=String.fromCharCode(...c)),C}var Kn=new TextDecoder,Qn=200;function Xn(e,A,t){let s=e.subarray(A,A+t);return Kn.decode(s)}function ut(e,A,t){return t>Qn?Xn(e,A,t):dr(e,A,t)}var X=class{type;data;constructor(A,t){this.type=A,this.data=t}};var L=class e extends Error{constructor(A){super(A);let t=Object.create(e.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:e.name})}};function ct(e,A,t){let s=t/4294967296,l=t;e.setUint32(A,s),e.setUint32(A+4,l)}function yA(e,A,t){let s=Math.floor(t/4294967296),l=t;e.setUint32(A,s),e.setUint32(A+4,l)}function OA(e,A){let t=e.getInt32(A),s=e.getUint32(A+4);return t*4294967296+s}function dt(e,A){let t=e.getUint32(A),s=e.getUint32(A+4);return t*4294967296+s}var Wn=-1,zn=4294967296-1,Zn=17179869184-1;function Yn({sec:e,nsec:A}){if(e>=0&&A>=0&&e<=Zn)if(A===0&&e<=zn){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t}else{let t=e/4294967296,s=e&4294967295,l=new Uint8Array(8),c=new DataView(l.buffer);return c.setUint32(0,A<<2|t&3),c.setUint32(4,s),l}else{let t=new Uint8Array(12),s=new DataView(t.buffer);return s.setUint32(0,A),yA(s,4,e),t}}function As(e){let A=e.getTime(),t=Math.floor(A/1e3),s=(A-t*1e3)*1e6,l=Math.floor(s/1e9);return{sec:t+l,nsec:s-l*1e9}}function rs(e){if(e instanceof Date){let A=As(e);return Yn(A)}else return null}function js(e){let A=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:A.getUint32(0),nsec:0};case 8:{let t=A.getUint32(0),s=A.getUint32(4),l=(t&3)*4294967296+s,c=t>>>2;return{sec:l,nsec:c}}case 12:{let t=OA(A,4),s=A.getUint32(0);return{sec:t,nsec:s}}default:throw new L(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${e.length}\`)}}function ts(e){let A=js(e);return new Date(A.sec*1e3+A.nsec/1e6)}var Ct={type:Wn,encode:rs,decode:ts};var tA=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(Ct)}register({type:A,encode:t,decode:s}){if(A>=0)this.encoders[A]=t,this.decoders[A]=s;else{let l=-1-A;this.builtInEncoders[l]=t,this.builtInDecoders[l]=s}}tryToEncode(A,t){for(let s=0;s<this.builtInEncoders.length;s++){let l=this.builtInEncoders[s];if(l!=null){let c=l(A,t);if(c!=null){let C=-1-s;return new X(C,c)}}}for(let s=0;s<this.encoders.length;s++){let l=this.encoders[s];if(l!=null){let c=l(A,t);if(c!=null){let C=s;return new X(C,c)}}}return A instanceof X?A:null}decode(A,t,s){let l=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return l?l(A,t,s):new X(t,A)}};function es(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function uA(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):es(e)?new Uint8Array(e):Uint8Array.from(e)}var ns=100,ss=2048,gA=class e{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(A){this.extensionCodec=A?.extensionCodec??tA.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??ns,this.initialBufferSize=A?.initialBufferSize??ss,this.sortKeys=A?.sortKeys??!1,this.forceFloat32=A?.forceFloat32??!1,this.ignoreUndefined=A?.ignoreUndefined??!1,this.forceIntegerToFloat=A?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(A){if(this.entered)return this.clone().encodeSharedRef(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(A){if(this.entered)return this.clone().encode(A);try{return this.entered=!0,this.reinitializeState(),this.doEncode(A,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(A,t){if(t>this.maxDepth)throw new Error(\`Too deep objects in depth \${t}\`);A==null?this.encodeNil():typeof A=="boolean"?this.encodeBoolean(A):typeof A=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(A):this.encodeNumber(A):typeof A=="string"?this.encodeString(A):this.useBigInt64&&typeof A=="bigint"?this.encodeBigInt64(A):this.encodeObject(A,t)}ensureBufferSizeToWrite(A){let t=this.pos+A;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(A){let t=new ArrayBuffer(A),s=new Uint8Array(t),l=new DataView(t);s.set(this.bytes),this.view=l,this.bytes=s}encodeNil(){this.writeU8(192)}encodeBoolean(A){A===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(A){!this.forceIntegerToFloat&&Number.isSafeInteger(A)?A>=0?A<128?this.writeU8(A):A<256?(this.writeU8(204),this.writeU8(A)):A<65536?(this.writeU8(205),this.writeU16(A)):A<4294967296?(this.writeU8(206),this.writeU32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(207),this.writeU64(A)):A>=-32?this.writeU8(224|A+32):A>=-128?(this.writeU8(208),this.writeI8(A)):A>=-32768?(this.writeU8(209),this.writeI16(A)):A>=-2147483648?(this.writeU8(210),this.writeI32(A)):this.useBigInt64?this.encodeNumberAsFloat(A):(this.writeU8(211),this.writeI64(A)):this.encodeNumberAsFloat(A)}encodeNumberAsFloat(A){this.forceFloat32?(this.writeU8(202),this.writeF32(A)):(this.writeU8(203),this.writeF64(A))}encodeBigInt64(A){A>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(A)):(this.writeU8(211),this.writeBigInt64(A))}writeStringHeader(A){if(A<32)this.writeU8(160+A);else if(A<256)this.writeU8(217),this.writeU8(A);else if(A<65536)this.writeU8(218),this.writeU16(A);else if(A<4294967296)this.writeU8(219),this.writeU32(A);else throw new Error(\`Too long string: \${A} bytes in UTF-8\`)}encodeString(A){let s=at(A);this.ensureBufferSizeToWrite(5+s),this.writeStringHeader(s),kt(A,this.bytes,this.pos),this.pos+=s}encodeObject(A,t){let s=this.extensionCodec.tryToEncode(A,this.context);if(s!=null)this.encodeExtension(s);else if(Array.isArray(A))this.encodeArray(A,t);else if(ArrayBuffer.isView(A))this.encodeBinary(A);else if(typeof A=="object")this.encodeMap(A,t);else throw new Error(\`Unrecognized object: \${Object.prototype.toString.apply(A)}\`)}encodeBinary(A){let t=A.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(\`Too large binary: \${t}\`);let s=uA(A);this.writeU8a(s)}encodeArray(A,t){let s=A.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else if(s<4294967296)this.writeU8(221),this.writeU32(s);else throw new Error(\`Too large array: \${s}\`);for(let l of A)this.doEncode(l,t+1)}countWithoutUndefined(A,t){let s=0;for(let l of t)A[l]!==void 0&&s++;return s}encodeMap(A,t){let s=Object.keys(A);this.sortKeys&&s.sort();let l=this.ignoreUndefined?this.countWithoutUndefined(A,s):s.length;if(l<16)this.writeU8(128+l);else if(l<65536)this.writeU8(222),this.writeU16(l);else if(l<4294967296)this.writeU8(223),this.writeU32(l);else throw new Error(\`Too large map object: \${l}\`);for(let c of s){let C=A[c];this.ignoreUndefined&&C===void 0||(this.encodeString(c),this.doEncode(C,t+1))}}encodeExtension(A){if(typeof A.data=="function"){let s=A.data(this.pos+6),l=s.length;if(l>=4294967296)throw new Error(\`Too large extension object: \${l}\`);this.writeU8(201),this.writeU32(l),this.writeI8(A.type),this.writeU8a(s);return}let t=A.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(\`Too large extension object: \${t}\`);this.writeI8(A.type),this.writeU8a(A.data)}writeU8(A){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,A),this.pos++}writeU8a(A){let t=A.length;this.ensureBufferSizeToWrite(t),this.bytes.set(A,this.pos),this.pos+=t}writeI8(A){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,A),this.pos++}writeU16(A){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,A),this.pos+=2}writeI16(A){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,A),this.pos+=2}writeU32(A){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,A),this.pos+=4}writeI32(A){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,A),this.pos+=4}writeF32(A){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,A),this.pos+=4}writeF64(A){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,A),this.pos+=8}writeU64(A){this.ensureBufferSizeToWrite(8),ct(this.view,this.pos,A),this.pos+=8}writeI64(A){this.ensureBufferSizeToWrite(8),yA(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 Cr(e,A){return new gA(A).encodeSharedRef(e)}function DA(e){return\`\${e<0?"-":""}0x\${Math.abs(e).toString(16).padStart(2,"0")}\`}var ls=16,is=16,BA=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(A=ls,t=is){this.maxKeyLength=A,this.maxLengthPerKey=t,this.caches=[];for(let s=0;s<this.maxKeyLength;s++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,t,s){let l=this.caches[s-1];A:for(let c of l){let C=c.bytes;for(let G=0;G<s;G++)if(C[G]!==A[t+G])continue A;return c.str}return null}store(A,t){let s=this.caches[A.length-1],l={bytes:A,str:t};s.length>=this.maxLengthPerKey?s[Math.random()*s.length|0]=l:s.push(l)}decode(A,t,s){let l=this.find(A,t,s);if(l!=null)return this.hit++,l;this.miss++;let c=dr(A,t,s),C=Uint8Array.prototype.slice.call(A,t,t+s);return this.store(C,c),c}};var fr="array",CA="map_key",qt="map_value",os=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new L("The type of key must be string or number but "+typeof e)},qr=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let t=this.getUninitializedStateFromPool();t.type=fr,t.position=0,t.size=A,t.array=new Array(A)}pushMapState(A){let t=this.getUninitializedStateFromPool();t.type=CA,t.readCount=0,t.size=A,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let A={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(A)}return this.stack[this.stackHeadPosition]}release(A){if(this.stack[this.stackHeadPosition]!==A)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(A.type===fr){let s=A;s.size=0,s.array=void 0,s.position=0,s.type=void 0}if(A.type===CA||A.type===qt){let s=A;s.size=0,s.map=void 0,s.readCount=0,s.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},dA=-1,Gr=new DataView(new ArrayBuffer(0)),as=new Uint8Array(Gr.buffer);try{Gr.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var ft=new RangeError("Insufficient data"),ks=new BA,xA=class e{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=Gr;bytes=as;headByte=dA;stack=new qr;entered=!1;constructor(A){this.extensionCodec=A?.extensionCodec??tA.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:ks,this.mapKeyConverter=A?.mapKeyConverter??os}clone(){return new e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=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),s=uA(A),l=new Uint8Array(t.length+s.length);l.set(t),l.set(s,t.length),this.setBuffer(l)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:t,pos:s}=this;return new RangeError(\`Extra \${t.byteLength-s} of \${t.byteLength} byte(s) found at buffer[\${A}]\`)}decode(A){if(this.entered)return this.clone().decode(A);try{this.entered=!0,this.reinitializeState(),this.setBuffer(A);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(A){if(this.entered){yield*this.clone().decodeMulti(A);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(A);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(A){if(this.entered)return this.clone().decodeAsync(A);try{this.entered=!0;let t=!1,s;for await(let G of A){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(G);try{s=this.doDecodeSync(),t=!0}catch(h){if(!(h instanceof RangeError))throw h}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return s}let{headByte:l,pos:c,totalPos:C}=this;throw new RangeError(\`Insufficient data in parsing \${DA(l)} at \${C} (\${c} in the current buffer)\`)}finally{this.entered=!1}}decodeArrayStream(A){return this.decodeMultiAsync(A,!0)}decodeStream(A){return this.decodeMultiAsync(A,!1)}async*decodeMultiAsync(A,t){if(this.entered){yield*this.clone().decodeMultiAsync(A,t);return}try{this.entered=!0;let s=t,l=-1;for await(let c of A){if(t&&l===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c),s&&(l=this.readArraySize(),s=!1,this.complete());try{for(;yield this.doDecodeSync(),--l!==0;);}catch(C){if(!(C instanceof RangeError))throw C}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){A:for(;;){let A=this.readHeadByte(),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 L(\`Unrecognized type byte: \${DA(A)}\`);this.complete();let s=this.stack;for(;s.length>0;){let l=s.top();if(l.type===fr)if(l.array[l.position]=t,l.position++,l.position===l.size)t=l.array,s.release(l);else continue A;else if(l.type===CA){if(t==="__proto__")throw new L("The key __proto__ is not allowed");l.key=this.mapKeyConverter(t),l.type=qt;continue A}else if(l.map[l.key]=t,l.readCount++,l.readCount===l.size)t=l.map,s.release(l);else{l.key=null,l.type=CA;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: \${DA(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 ft;let s=this.pos+t,l;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?l=this.keyDecoder.decode(this.bytes,s,A):l=ut(this.bytes,s,A),this.pos+=t+A,l}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===CA:!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 ft;let s=this.pos+t,l=this.bytes.subarray(s,s+A);return this.pos+=t+A,l}decodeExtension(A,t){if(A>this.maxExtLength)throw new L(\`Max length exceeded: ext length (\${A}) > maxExtLength (\${this.maxExtLength})\`);let s=this.view.getInt8(this.pos+t),l=this.decodeBinary(A,t+1);return this.extensionCodec.decode(l,s,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let A=this.view.getUint8(this.pos);return this.pos++,A}readI8(){let A=this.view.getInt8(this.pos);return this.pos++,A}readU16(){let A=this.view.getUint16(this.pos);return this.pos+=2,A}readI16(){let A=this.view.getInt16(this.pos);return this.pos+=2,A}readU32(){let A=this.view.getUint32(this.pos);return this.pos+=4,A}readI32(){let A=this.view.getInt32(this.pos);return this.pos+=4,A}readU64(){let A=dt(this.view,this.pos);return this.pos+=8,A}readI64(){let A=OA(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 pr(e,A){return new xA(A).decode(e)}var fA=class e{constructor(A,t,s,l,c){this.mediaIds=A;this.sequenceNumber=t;this.timeStamp=s;this.isEndOfSpurt=l;this.payload=c}static parse(A){let t;try{t=pr(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(_=>typeof _=="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 s=t[1],l=t[2]>>>0,c=t[3]>>>0,G=(t[4]&1)!==0,h=t[t.length-1];return h instanceof Uint8Array?Yj(new e(s,l,c,G,h)):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(Cr(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,x.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=it(this.wasm),this.outBuffer=w(this.wasm,"u8",1270),Kj(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(){ot(this.wasm,this.information),jA(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){et(\`failed encoding packet: \${t}\`);return}if(this.timestamp=this.timestamp+1800>>0,t===1)continue;this.sequenceNumber=this.sequenceNumber+1>>0;let s=this.active&&!this.encoder.active;this.active=this.encoder.active,this.monitoring=this.connections.some(l=>l.id===0);for(let l of this.connections){if(this.monitoring&&l.id!==0)continue;let c=new fA(l.mediaIds,this.sequenceNumber,this.timestamp,s,this.outBuffer.subarray(0,t));aA(globalThis,["sendPacket",{connectionId:l.id,packet:c.toBytes()}])}}}onMessage(A){let[t,s]=A;switch(t){case"captureSetVad":this?.setVad(s);break;case"captureSetMedias":this?.setMedias(s.connections);break;case"close":this.close();break;case"dump":s.result.postMessage(this.dump());break}}dump(){return{sequenceNumber:this.sequenceNumber,timestamp:this.timestamp,connections:this.connections.map(A=>\`\${A.id} => \${A.mediaIds.join(",")}\`),active:this.active,monitoring:this.monitoring,information:{active:wj(this.information),speechProbability:Rj(this.information),rmsDBFS:Uj(this.information),volume:Vj(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=w(this.wasm,"u32",x.MaxNumberOfDecoders),this.information=st(this.wasm,x.MaxNumberOfDecoders),Dj(this.information,[1,1])}close(){lt(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,t){this.stats.numberPackets++;let s=fA.parse(t);if(s.type==="Failure"){this.stats.numberPacketError++;let l=Array.from(t).map(c=>c.toString(16).padStart(2,"0")).join("");console.error(\`failed decoding audio packet; reason: \${s.reason}, connection: \${A}, dump: \${l}\`);return}for(let l of s.value.mediaIds){let c=this.medias.get(LA({connectionId:A,mediaId:l}));if(c===void 0){this.stats.numberPacketsMediaNotFound++;continue}c.lastPacket=t;let C=w(this.wasm,"u8",s.value.payload.length);C.set(s.value.payload),c.decoder.push(s.value.sequenceNumber,s.value.timeStamp,s.value.isEndOfSpurt,C.byteOffset,C.length)}}insertMedia(A,t,s,l=[1,1]){let c=LA({connectionId:t,mediaId:s}),C=new this.wasm.Decoder;this.medias.set(c,{index:A,decoder:C,lastPacket:void 0}),this.decoders[A]=C.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),Pj(this.information,A,l),Sj(this.information,A,0),Tj(this.information,A,0)}removeMedia(A,t,s){let l=LA({connectionId:t,mediaId:s}),c=this.medias.get(l);if(!(c===void 0||c.index!==A)&&(this.medias.delete(l),xj(this.information,A,0),this.decoders[A]=0,c.decoder.delete(),A===this.largestIndex)){for(A=A-1;A>=0&&this.decoders[A]===0;A--);this.largestIndex=A}}decode(A){return{hasAudio:this.wasm.pop_many(this.decoders.byteOffset,this.information.values.byteOffset,this.largestIndex+1,A.byteOffset)}}onMessage(A){let[t,s]=A;switch(t){case"playbackReceivePacket":this.receivePacket(s.connectionId,s.packet);break;case"playbackUpdateMedias":for(let{index:l,connectionId:c,mediaId:C}of s.removed)this.removeMedia(l,c,C);for(let{index:l,connectionId:c,mediaId:C,volume:G}of s.added)this.insertMedia(l,c,C,G);break;case"close":this.close();break;case"dump":s.result.postMessage(this.dump());break}}dump(){let A=[];for(let[t,s]of this.medias){let l=nt(t);A.push({index:s.index,connectionId:l.connectionId,mediaId:l.mediaId,rmsDBFS:Bj(this.information,s.index),volume:bj(this.information,s.index),voicedBlocks:Mj(this.information,s.index),silentBlocks:Jj(this.information,s.index),time:s.decoder.time,consecutive_silence:s.decoder.consecutive_silence,last_voiced_time_point:s.decoder.last_voiced_time_point,sequence_number:s.decoder.sequence_number,packetsSeen:s.decoder.packets_seen,packetsInvalid:s.decoder.packets_invalid,packetsTooLate:s.decoder.packets_too_late,packetsTooEarly:s.decoder.packets_too_early,packetsRepeated:s.decoder.packets_repeated,packetsProcessed:s.decoder.packets_processed,packetsLost:s.decoder.packets_lost,rewinds:s.decoder.rewinds,cacheLength:s.decoder.cache_length,lastPacket:Qj(s.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:gj(this.information),decoders:A}}};var $t=tn(pt()),Et=(0,$t.default)(),mt,ht;globalThis.addEventListener("message",e=>{Er(e).catch(console.error)});async function Er(e){let A=e.data,[t,s]=A;switch(t){case"captureInit":s.workletPort.onmessage=Er,mt=new mr(s.sampleRate,await Et);break;case"playbackInit":s.workletPort.onmessage=Er,ht=new hr(await Et);break;case"close":globalThis.close();break}mt?.onMessage(A),ht?.onMessage(A)}var mr=class extends bA{constructor(t,s){super(t,s);this.id=-1;this.samples=ur(this.wasm,t,2+x.VadPreload+x.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[s,l]=t;s==="captureTick"&&this.tick(l.id)}tick(t){for(;this.id<t;this.id+=1)this.encode(lr(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()}}},hr=class extends PA{constructor(A){super(A);let t=2+x.AdditionalPlaybackBlocks;this.sampleBuffer=ur(A,48e3,t,!0),this.sampleBuffer.samples.fill(0),this.prefill=t-2;for(let s=0;s<this.prefill;s++)ir(this.sampleBuffer,s,{id:s});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,s]=A;t==="playbackTick"&&this.tick(s.id)}tick(A){for(this.stats.numberTicks++;this.id<A+this.prefill;this.id++){let t=this.id%this.sampleBuffer.length,{hasAudio:s}=this.decode(lr(this.sampleBuffer,t));s&&(this.stats.numberTicksWithAudio++,ir(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()}}};})();
|
|
3358
|
-
`});var n0,K0=p(()=>{n0='"use strict";(()=>{var E=Object.defineProperty;var M=(e,t)=>{for(var r in t)E(e,r,{get:t[r],enumerable:!0})};var l={};M(l,{AdditionalCaptureBlocks:()=>D,AdditionalPlaybackBlocks:()=>C,ClockJumpCheckInterval:()=>j,ClockJumpThreshold:()=>$,ConnectInterval:()=>ee,ConnectTimeout:()=>X,DefaultRefreshRate:()=>V,DefaultVideoCodec:()=>re,HealthCheckTimeout:()=>W,MainConnectionPingInterval:()=>H,MaxNumberOfDecoders:()=>_,MaxReconnectDuration:()=>te,MinDBFs:()=>k,MinTokenLifetime:()=>K,MinTokenRefreshInterval:()=>Y,PlaybackPreload:()=>L,RenderQuantumSize:()=>N,VadPreload:()=>O,WebRtcAnswerTimeout:()=>Z,WebRtcIceTimeout:()=>J,WebRtcMaxNegotiationAttempts:()=>q,WebRtcRecoveryDelays:()=>Q,WebRtcStatsSnapshotInterval:()=>G,WebRtcTimeout:()=>z});var C=3,D=3,L=3,V=250,O=3,_=512,N=128,k=-758.596,W=1e4,j=1e3,$=1e4,H=3e3,G=1e3,J=3e3,z=1e4,Z=1e4,q=3,Q=[0,2e3,5e3],X=5e3,K=6e4,Y=5e3,ee=[0,100,200,200,500],te=12e4,re="H264";function p(e,t,r){return e.postMessage(t,r)}function ne(e){return e.sampleRate*.02*(e.stereo?2:1)}function f(e,t){let r=ne(e),n=r*t,s=n+r;return e.samples.subarray(n,s)}function S(e,t){return{id:e.headers[t]}}function T(e,t,r){e.headers[t]=r.id}var se;(e=>{let t;(r=>(r[r.InvalidPassword=-1]="InvalidPassword",r[r.Unknown=0]="Unknown",r[r.Unencrypted=1]="Unencrypted",r[r.Encrypted=2]="Encrypted"))(t=e.PeerCipherStatus||={})})(se||={});var{Deno:I}=globalThis,oe=typeof I?.noColor=="boolean"?I.noColor:!1,ae=!oe;function h(e,t){return{open:`\\x1B[${e.join(";")}m`,close:`\\x1B[${t}m`,regexp:new RegExp(`\\\\x1b\\\\[${t}m`,"g")}}function b(e,t){return ae?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}function m(e){return b(e,h([0],0))}function U(e){return b(e,h([1],22))}function ie(e){return b(e,h([2],22))}var Fe=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),ce=new Date,d=(e=>(e[e.CRITICAL=0]="CRITICAL",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(d||{}),R={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},le={4:ie,3:m,2:m,1:U,0:U};function ue({message:e}){return String(e)}function B(e){return JSON.stringify({timestamp:e.date.toISOString(),level:d[e.level],message:e.message,extra:e.extra})}function w(e){function t(c,i){return[Math.floor(c/i),c%i]}function r(){let c,i=e.date.valueOf()-ce.valueOf();[i,c]=t(i,1e3);let[A,P]=t(i,60);return`${A.toString().padStart(4,"0")}:${P.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=R[e.level],a=e.logger.name!==void 0?`@${e.logger.name}`:"";return`${m(r())}${a} ${s} ${le[e.level](String(e.message))}${n()}`}function fe(e){let t=`[${e.date.toISOString()}]`,r=`[${d[e.level]}]`,n=e.logger.name!==void 0?`[${e.logger.name}] `:"",s=R[e.level];return`${t} ${s} ${r.padEnd(7," ")} ${n}${e.message}`}function de(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var F=class{static sparse=ue;static json=B;static pretty=w;static structured=fe;static default=de()?w:B;constructor(){}};var pe=class{formatter;consoleObject;filter;constructor(e=F.default,t=4,r=console){this.filter=t,this.formatter=e,this.consoleObject=r}handle(e){let t=this.formatter(e);switch(e.level){case 0:case 1:this.consoleObject.error(t);break;case 2:this.consoleObject.warn(t);break;case 3:this.consoleObject.info(t);break;case 4:this.consoleObject.debug(t);break}}};var o=class{#e;sinks;filter;parent;get name(){return this.#e}constructor(e,t=void 0,r=[],n=void 0){this.#e=t,this.sinks=r,this.filter=e,this.parent=n}log(e,t,r=void 0){let n={date:new Date,level:e,logger:this,message:t,extra:r};this.filter<e||this.insert(n)}insert(e){if(!(this.filter<e.level)){for(let t of this.sinks)t.filter>=e.level&&t.handle(e);this.parent!==void 0&&this.parent.insert(e)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},u=globalThis[Symbol.for("odin-global-logger")]??=new o(3,void 0,[new pe]),me=o.prototype.log.bind(u,1),he=o.prototype.log.bind(u,2),be=o.prototype.log.bind(u,3),xe=o.prototype.log.bind(u,4),Ae=o.prototype.log.bind(u);var x=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.blocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"init":this.state=new g(s.sampleBuffer,s.workerPort,sampleRate*.02);break;case"close":this.alive=!1;break;case"dump":s.result.postMessage(this.dump());break}}process(r,n,s){if(this.state===void 0||r.length<1||r[0].length<1)return this.alive;let a=this.state.fill(0,r[0][0]);return this.state.offset===this.state.length&&(this.blocks+=1,this.state.flush(),this.state.fill(a,r[0][0])),this.alive}dump(){return{type:"shared capture worklet",alive:this.alive,sampleRate,id:this.state?.id||null,offset:this.state?.offset||null,length:this.state?.length||null,blocks:this.blocks}}},y=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.silenceBlocks=0;this.voiceBlocks=0;this.totalBlocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"close":this.alive=!1;break;case"init":this.state=new v(s.workerPort,s.sampleBuffer,sampleRate*.02);break;case"dump":s.result.postMessage(this.dump());break}n==="close"&&(this.alive=!1)}process(r,n,s){if(this.state===void 0||n.length<1||n[0].length<2)return this.alive;let a=this.state.fill(0,n[0][0],n[0][1]);return a<l.RenderQuantumSize&&(this.totalBlocks+=1,this.state.next(),this.state.hasVoice?this.voiceBlocks+=1:this.silenceBlocks+=1,this.state.fill(a,n[0][0],n[0][1])),this.alive}dump(){return{type:"shared playback worklet",alive:this.alive,sampleRate,id:this.state?.id||null,offset:this.state?.offset||null,length:this.state?.length||null,hasVoice:this.state?.hasVoice??!1,silenceBlocks:this.silenceBlocks,voiceBlocks:this.voiceBlocks,totalBlocks:this.totalBlocks}}},g=class{constructor(t,r,n){this.samples=t;this.port=r;this.length=n;this.id=0,this.offset=0,this.entry=f(this.samples,0)}fill(t,r){let n=Math.min(r.length-t,this.length-this.offset);return this.entry.set(r.subarray(t,t+n),this.offset),this.offset+=n,t+n}flush(){this.id+=1,p(this.port,["captureTick",{id:this.id}]);let t=this.id%this.samples.length;this.entry=f(this.samples,t),T(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 Q0={};hx(Q0,{createCaptureWorker:()=>iF,createPlaybackWorker:()=>oF});function iF(t,x,A,F,D=E.DefaultRefreshRate){return sF.enqueue(async()=>{let[r,e]=await nx(E0,n0,t,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return s0.create(t,x,A,r,e,F)})}async function oF(t,x=E.DefaultRefreshRate){if(t.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[A,F]=await nx(E0,n0,t,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return f0.create(t,A,F)}var W0,sF,f0,s0,X0=p(()=>{"use strict";W0=require("@4players/odin-common");o();gx();U0();K0();sF=new W0.Strand;f0=class t extends vx{constructor(A,F,D,r){super(A,F,D);this.information=r}static async create(A,F,D){let{port1:r,port2:e}=new MessageChannel;l(F,["playbackInit",{workletPort:r}],[r]);let{informationBuffer:j,sampleBuffer:B}=await tx(F,"playbackReady");return v0(j,[1,1]),l(D.port,["init",{sampleBuffer:B,workerPort:e}],[e]),new t(A,D,F,j)}getActivity(A){let F=this.medias.get(h(A));if(F===void 0)return;let D=G0(this.information,F.index);return D===0?I:{isSilent:!1,rmsDBFS:D}}getJitterStats(A){}setGlobalVolume(A){v0(this.information,A)}setVolume(A,F){let D=this.medias.get(h(A));D!==void 0&&y0(this.information,D.index,F)}_GetFreeIndex(){let A=super._GetFreeIndex();if(A!==void 0)return A;if(this.information.length>this.medias.size)return this.medias.size}},s0=class t extends Cx{constructor(A,F,D,r,e,j){super(A,F,D,r,j);this.information=e}static async create(A,F,D,r,e,j){let{port1:B,port2:f}=new MessageChannel;l(r,["captureInit",{sampleRate:A.sampleRate,workletPort:B}],[B]);let{sampleBuffer:a,informationBuffer:u}=await tx(r,"captureReady");return l(e.port,["init",{workerPort:f,sampleBuffer:a}],[f]),new t(e,r,F,D,u,j)}get activity(){return{isSilent:!g0(this.information),rmsDBFS:_0(this.information)}}get speechProbability(){return $0(this.information)}setVolume(A){I0(this.information,A)}}});var i0,z0=p(()=>{i0=`"use strict";(()=>{var $t=Object.create;var QA=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var It=Object.getPrototypeOf,Nt=Object.prototype.hasOwnProperty;var Lt=(n,A)=>()=>{try{return A||n((A={exports:{}}).exports,A),A.exports}catch(r){throw A=0,r}},yt=(n,A)=>{for(var r in A)QA(n,r,{get:A[r],enumerable:!0})},Ht=(n,A,r,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let l of vt(A))!Nt.call(n,l)&&l!==r&&QA(n,l,{get:()=>A[l],enumerable:!(e=Ft(A,l))||e.enumerable});return n};var Ot=(n,A,r)=>(r=n!=null?$t(It(n)):{},Ht(A||!n||!n.__esModule?QA(r,"default",{value:n,enumerable:!0}):r,n));var Fj=Lt(($j,bA)=>{"use strict";var nr=(()=>{var n=globalThis.document?.currentScript?.src;return async function(A={}){var r=A,e=!!globalThis.window,l=!!globalThis.WorkerGlobalScope;if(globalThis.process?.versions?.node&&globalThis.process,l&&(n=self.location.href),e||l)try{new URL(".",n).href}catch{}var c=console.log.bind(console),C=console.error.bind(console),p=!1;function I(t){for(var j,s=0,i=t.length,o=new Uint8Array(i);s<i;++s)j=t.charCodeAt(s),o[s]=~j>>8&j;return o}function D(){var t=Jr.buffer;w=new Int8Array(t),uA=new Int16Array(t),r.HEAPU8=_=new Uint8Array(t),rA=new Uint16Array(t),r.HEAP32=cA=new Int32Array(t),r.HEAPU32=$=new Uint32Array(t),r.HEAPF32=Hr=new Float32Array(t),Or=new Float64Array(t),ur=new BigInt64Array(t),cr=new BigUint64Array(t)}function JA(){var t=r.preRun;t&&(typeof t=="function"&&(t=[t]),kr.push(...t)),or(kr)}function b(){tA.v()}function yj(){var t=r.postRun;t&&(typeof t=="function"&&(t=[t]),ar.push(...t)),or(ar)}function aA(t){throw r.onAbort?.(t),t=\`Aborted(\${t})\`,C(t),p=!0,t+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(t)}var ir;function Hj(){return I(\`\\0asm\\0\\0\\0\\x8E9\\\`\\x7F\\x7F\\\`\\x7F\\0\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\0\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`||\\\`\\x7F}\\\`}}\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F~\\\`\\x7F\\x7F}\\\`\\x7F}}\\\`\\0\\x7F\\\`\\x7F\\x7F}}\\0\\\`
|
|
3358
|
+
`});var f0,K0=h(()=>{f0='"use strict";(()=>{var E=Object.defineProperty;var M=(e,t)=>{for(var r in t)E(e,r,{get:t[r],enumerable:!0})};var l={};M(l,{AdditionalCaptureBlocks:()=>D,AdditionalPlaybackBlocks:()=>C,ClockJumpCheckInterval:()=>j,ClockJumpThreshold:()=>$,ConnectInterval:()=>ee,ConnectTimeout:()=>X,DefaultRefreshRate:()=>V,DefaultVideoCodec:()=>re,HealthCheckTimeout:()=>W,MainConnectionPingInterval:()=>H,MaxNumberOfDecoders:()=>_,MaxReconnectDuration:()=>te,MinDBFs:()=>k,MinTokenLifetime:()=>K,MinTokenRefreshInterval:()=>Y,PlaybackPreload:()=>L,RenderQuantumSize:()=>N,VadPreload:()=>O,WebRtcAnswerTimeout:()=>Z,WebRtcIceTimeout:()=>J,WebRtcMaxNegotiationAttempts:()=>q,WebRtcRecoveryDelays:()=>Q,WebRtcStatsSnapshotInterval:()=>G,WebRtcTimeout:()=>z});var C=3,D=3,L=3,V=250,O=3,_=512,N=128,k=-758.596,W=1e4,j=1e3,$=1e4,H=3e3,G=1e3,J=3e3,z=1e4,Z=1e4,q=3,Q=[0,2e3,5e3],X=5e3,K=6e4,Y=5e3,ee=[0,100,200,200,500],te=12e4,re="H264";function p(e,t,r){return e.postMessage(t,r)}function ne(e){return e.sampleRate*.02*(e.stereo?2:1)}function f(e,t){let r=ne(e),n=r*t,s=n+r;return e.samples.subarray(n,s)}function S(e,t){return{id:e.headers[t]}}function T(e,t,r){e.headers[t]=r.id}var se;(e=>{let t;(r=>(r[r.InvalidPassword=-1]="InvalidPassword",r[r.Unknown=0]="Unknown",r[r.Unencrypted=1]="Unencrypted",r[r.Encrypted=2]="Encrypted"))(t=e.PeerCipherStatus||={})})(se||={});var{Deno:I}=globalThis,oe=typeof I?.noColor=="boolean"?I.noColor:!1,ae=!oe;function h(e,t){return{open:`\\x1B[${e.join(";")}m`,close:`\\x1B[${t}m`,regexp:new RegExp(`\\\\x1b\\\\[${t}m`,"g")}}function b(e,t){return ae?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}function m(e){return b(e,h([0],0))}function U(e){return b(e,h([1],22))}function ie(e){return b(e,h([2],22))}var Fe=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),ce=new Date,d=(e=>(e[e.CRITICAL=0]="CRITICAL",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(d||{}),R={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},le={4:ie,3:m,2:m,1:U,0:U};function ue({message:e}){return String(e)}function B(e){return JSON.stringify({timestamp:e.date.toISOString(),level:d[e.level],message:e.message,extra:e.extra})}function w(e){function t(c,i){return[Math.floor(c/i),c%i]}function r(){let c,i=e.date.valueOf()-ce.valueOf();[i,c]=t(i,1e3);let[A,P]=t(i,60);return`${A.toString().padStart(4,"0")}:${P.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=R[e.level],a=e.logger.name!==void 0?`@${e.logger.name}`:"";return`${m(r())}${a} ${s} ${le[e.level](String(e.message))}${n()}`}function fe(e){let t=`[${e.date.toISOString()}]`,r=`[${d[e.level]}]`,n=e.logger.name!==void 0?`[${e.logger.name}] `:"",s=R[e.level];return`${t} ${s} ${r.padEnd(7," ")} ${n}${e.message}`}function de(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var F=class{static sparse=ue;static json=B;static pretty=w;static structured=fe;static default=de()?w:B;constructor(){}};var pe=class{formatter;consoleObject;filter;constructor(e=F.default,t=4,r=console){this.filter=t,this.formatter=e,this.consoleObject=r}handle(e){let t=this.formatter(e);switch(e.level){case 0:case 1:this.consoleObject.error(t);break;case 2:this.consoleObject.warn(t);break;case 3:this.consoleObject.info(t);break;case 4:this.consoleObject.debug(t);break}}};var o=class{#e;sinks;filter;parent;get name(){return this.#e}constructor(e,t=void 0,r=[],n=void 0){this.#e=t,this.sinks=r,this.filter=e,this.parent=n}log(e,t,r=void 0){let n={date:new Date,level:e,logger:this,message:t,extra:r};this.filter<e||this.insert(n)}insert(e){if(!(this.filter<e.level)){for(let t of this.sinks)t.filter>=e.level&&t.handle(e);this.parent!==void 0&&this.parent.insert(e)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},u=globalThis[Symbol.for("odin-global-logger")]??=new o(3,void 0,[new pe]),me=o.prototype.log.bind(u,1),he=o.prototype.log.bind(u,2),be=o.prototype.log.bind(u,3),xe=o.prototype.log.bind(u,4),Ae=o.prototype.log.bind(u);var x=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.blocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"init":this.state=new g(s.sampleBuffer,s.workerPort,sampleRate*.02);break;case"close":this.alive=!1;break;case"dump":s.result.postMessage(this.dump());break}}process(r,n,s){if(this.state===void 0||r.length<1||r[0].length<1)return this.alive;let a=this.state.fill(0,r[0][0]);return this.state.offset===this.state.length&&(this.blocks+=1,this.state.flush(),this.state.fill(a,r[0][0])),this.alive}dump(){return{type:"shared capture worklet",alive:this.alive,sampleRate,id:this.state?.id||null,offset:this.state?.offset||null,length:this.state?.length||null,blocks:this.blocks}}},y=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.silenceBlocks=0;this.voiceBlocks=0;this.totalBlocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"close":this.alive=!1;break;case"init":this.state=new v(s.workerPort,s.sampleBuffer,sampleRate*.02);break;case"dump":s.result.postMessage(this.dump());break}n==="close"&&(this.alive=!1)}process(r,n,s){if(this.state===void 0||n.length<1||n[0].length<2)return this.alive;let a=this.state.fill(0,n[0][0],n[0][1]);return a<l.RenderQuantumSize&&(this.totalBlocks+=1,this.state.next(),this.state.hasVoice?this.voiceBlocks+=1:this.silenceBlocks+=1,this.state.fill(a,n[0][0],n[0][1])),this.alive}dump(){return{type:"shared playback worklet",alive:this.alive,sampleRate,id:this.state?.id||null,offset:this.state?.offset||null,length:this.state?.length||null,hasVoice:this.state?.hasVoice??!1,silenceBlocks:this.silenceBlocks,voiceBlocks:this.voiceBlocks,totalBlocks:this.totalBlocks}}},g=class{constructor(t,r,n){this.samples=t;this.port=r;this.length=n;this.id=0,this.offset=0,this.entry=f(this.samples,0)}fill(t,r){let n=Math.min(r.length-t,this.length-this.offset);return this.entry.set(r.subarray(t,t+n),this.offset),this.offset+=n,t+n}flush(){this.id+=1,p(this.port,["captureTick",{id:this.id}]);let t=this.id%this.samples.length;this.entry=f(this.samples,t),T(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 Q0={};hx(Q0,{createCaptureWorker:()=>iF,createPlaybackWorker:()=>oF});function iF(t,x,A,F,D=n.DefaultRefreshRate){return sF.enqueue(async()=>{let[r,e]=await nx(n0,f0,t,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return i0.create(t,x,A,r,e,F)})}async function oF(t,x=n.DefaultRefreshRate){if(t.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[A,F]=await nx(n0,f0,t,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return s0.create(t,A,F)}var W0,sF,s0,i0,X0=h(()=>{"use strict";W0=require("@4players/odin-common");b();gx();U0();K0();sF=new W0.Strand;s0=class t extends Bx{constructor(A,F,D,r){super(A,F,D);this.information=r}static async create(A,F,D){let{port1:r,port2:e}=new MessageChannel;u(F,["playbackInit",{workletPort:r}],[r]);let{informationBuffer:j,sampleBuffer:v}=await tx(F,"playbackReady");return C0(j,[1,1]),u(D.port,["init",{sampleBuffer:v,workerPort:e}],[e]),new t(A,D,F,j)}getActivity(A){let F=this.medias.get(k(A));if(F===void 0)return;let D=G0(this.information,F.index);return D===0?I:{isSilent:!1,rmsDBFS:D}}getJitterStats(A){}setGlobalVolume(A){C0(this.information,A)}setVolume(A,F){let D=this.medias.get(k(A));D!==void 0&&y0(this.information,D.index,F)}_GetFreeIndex(){let A=super._GetFreeIndex();if(A!==void 0)return A;if(this.information.length>this.medias.size)return this.medias.size}},i0=class t extends Cx{constructor(A,F,D,r,e,j){super(A,F,D,r,j);this.information=e}static async create(A,F,D,r,e,j){let{port1:v,port2:E}=new MessageChannel;u(r,["captureInit",{sampleRate:A.sampleRate,workletPort:v}],[v]);let{sampleBuffer:o,informationBuffer:l}=await tx(r,"captureReady");return u(e.port,["init",{workerPort:E,sampleBuffer:o}],[E]),new t(e,r,F,D,l,j)}get activity(){return{isSilent:!g0(this.information),rmsDBFS:_0(this.information)}}get speechProbability(){return $0(this.information)}setVolume(A){I0(this.information,A)}}});var o0,z0=h(()=>{o0=`"use strict";(()=>{var $t=Object.create;var QA=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var It=Object.getPrototypeOf,Nt=Object.prototype.hasOwnProperty;var Lt=(n,A)=>()=>{try{return A||n((A={exports:{}}).exports,A),A.exports}catch(r){throw A=0,r}},yt=(n,A)=>{for(var r in A)QA(n,r,{get:A[r],enumerable:!0})},Ht=(n,A,r,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let l of vt(A))!Nt.call(n,l)&&l!==r&&QA(n,l,{get:()=>A[l],enumerable:!(e=Ft(A,l))||e.enumerable});return n};var Ot=(n,A,r)=>(r=n!=null?$t(It(n)):{},Ht(A||!n||!n.__esModule?QA(r,"default",{value:n,enumerable:!0}):r,n));var Fj=Lt(($j,bA)=>{"use strict";var nr=(()=>{var n=globalThis.document?.currentScript?.src;return async function(A={}){var r=A,e=!!globalThis.window,l=!!globalThis.WorkerGlobalScope;if(globalThis.process?.versions?.node&&globalThis.process,l&&(n=self.location.href),e||l)try{new URL(".",n).href}catch{}var c=console.log.bind(console),C=console.error.bind(console),p=!1;function I(t){for(var j,s=0,i=t.length,o=new Uint8Array(i);s<i;++s)j=t.charCodeAt(s),o[s]=~j>>8&j;return o}function D(){var t=Jr.buffer;w=new Int8Array(t),uA=new Int16Array(t),r.HEAPU8=_=new Uint8Array(t),rA=new Uint16Array(t),r.HEAP32=cA=new Int32Array(t),r.HEAPU32=$=new Uint32Array(t),r.HEAPF32=Hr=new Float32Array(t),Or=new Float64Array(t),ur=new BigInt64Array(t),cr=new BigUint64Array(t)}function JA(){var t=r.preRun;t&&(typeof t=="function"&&(t=[t]),kr.push(...t)),or(kr)}function b(){tA.v()}function yj(){var t=r.postRun;t&&(typeof t=="function"&&(t=[t]),ar.push(...t)),or(ar)}function aA(t){throw r.onAbort?.(t),t=\`Aborted(\${t})\`,C(t),p=!0,t+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(t)}var ir;function Hj(){return I(\`\\0asm\\0\\0\\0\\x8E9\\\`\\x7F\\x7F\\\`\\x7F\\0\\\`\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\0\\0\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`||\\\`\\x7F}\\\`}}\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F~\\\`\\x7F\\x7F}\\\`\\x7F}}\\\`\\0\\x7F\\\`\\x7F\\x7F}}\\0\\\`
|
|
3359
3359
|
\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`|}\\\`|\\x7F|\\\`\\x7F\\x7F}\\0\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\` \\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\f\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\b\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x07\\x7F|\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F|}\\\`\\x7F\\x7F\\x7F~~\\0\\\`\\r\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F~\\x7F\\x7F\\x7F\\\`\\x7F\\x7F|\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\x7F\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F}}\\x7F\\x7F\\x7F\\x7F\\0\\\`~\\x7F\\x7F\\\` \\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\\`||\\x7F|\\\`|||\\\`\\x7F\\x7F\\x7F|\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\v\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x07\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\\`\\f\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`}\\x7F\\x7F\\\`|\\x7F\\x7F\\\`\\x7F\\x7F\\x7F}\\\`\\x7F}\\x7F\\0\\\`\\x7F\\x7F}\\x7F\\x7F\\x7F}\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F}\\x7F\\x7F\\\`\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\x7F\\0\\\`\\x7F\\x7F\\x7F}}\\0yaa\\0ab\\0ac\\0ad\\0ae\\0af\\0ag\\0!ah\\0 ai\\0aj\\0\\bak\\0"al\\0am\\0an\\0ao\\0\\0ap\\0#aq\\0\\0ar\\0
|
|
3360
3360
|
as\\0at\\0\\xBE\\xBC\\x07\\0\\0\\f$\\f\\0\\x07\\f\\f\\x07\\0%& \\0
|
|
3361
3361
|
\\0\\v\\0'\\0\\0(\\0\\f\\0)*+\\x07\\v\\0
|
|
@@ -6678,5 +6678,5 @@ stackRestore(sp);
|
|
|
6678
6678
|
return ret;
|
|
6679
6679
|
\`),E+=\`}
|
|
6680
6680
|
\`,new Function(m,E)}function UA(t,j,s,i,o,a){var k=j.length;k<2&&q("argTypes array size mismatch! Must at least get return value and receiver (this) types!");var u=j[1]!==null&&s!==null,d=vr(j),G=Ir(j),f=G&&!a&&!d;G&&!f&&(d=!0);var E=!j[0].isVoid,F=j[0],m=j[1],v=[t,q,i,o,Fr,F.fromWireType.bind(F),m?.toWireType.bind(m)];f&&v.push(xj,Bj);for(var h=2;h<k;++h){var H=j[h];v.push(H.toWireType.bind(H))}if(!d)for(h=u?1:2;h<j.length;++h)j[h].destructorFunction!==null&&v.push(j[h].destructorFunction);var R=jt(j,u,E,a)(...v);return Gr(t,R)}var Nr=t=>{t=t.trim();let j=t.indexOf("(");return j===-1?t:t.slice(0,j)},Lr=(t,j,s)=>(t instanceof Object||q(\`\${s} with invalid "this": \${t}\`),t instanceof j.registeredClass.constructor||q(\`\${s} incompatible with "this" of type \${t.constructor.name}\`),t.$$.ptr||q(\`cannot call emscripten binding method \${s} on deleted object\`),fA(t.$$.ptr,t.$$.ptrType.registeredClass,j.registeredClass)),yr=[],U=[0,1,,1,null,1,!0,1,!1,1],tt=t=>{t>9&&--U[t+1]===0&&(U[t],U[t]=void 0,yr.push(t))},RA={toValue:t=>(t||q(\`Cannot use deleted val. handle = \${t}\`),U[t]),toHandle:t=>{switch(t){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:{let j=yr.pop()||U.length;return U[j]=t,U[j+1]=1,j}}}},nt={name:"emscripten::val",fromWireType:t=>{var j=RA.toValue(t);return tt(t),j},toWireType:(t,j)=>RA.toHandle(j),readValueFromPointer:GA,destructorFunction:null},Hr,Or,et=(t,j)=>{switch(j){case 4:return function(s){return this.fromWireType(Hr[s>>2])};case 8:return function(s){return this.fromWireType(Or[s>>3])};default:throw new TypeError(\`invalid float width (\${j}): \${t}\`)}},st=(t,j,s,i)=>{if(!(i>0))return 0;for(var o=s,a=s+i-1,k=0;k<t.length;++k){var u=t.codePointAt(k);if(u<=127){if(s>=a)break;j[s++]=u}else if(u<=2047){if(s+1>=a)break;j[s++]=192|u>>6,j[s++]=128|u&63}else if(u<=65535){if(s+2>=a)break;j[s++]=224|u>>12,j[s++]=128|u>>6&63,j[s++]=128|u&63}else{if(s+3>=a)break;j[s++]=240|u>>18,j[s++]=128|u>>12&63,j[s++]=128|u>>6&63,j[s++]=128|u&63,k++}}return j[s]=0,s-o},lt=(t,j,s)=>st(t,_,j,s),it=t=>{for(var j=0,s=0;s<t.length;++s){var i=t.charCodeAt(s);i<=127?j++:i<=2047?j+=2:i>=55296&&i<=57343?(j+=4,++s):j+=3}return j},Dr=globalThis.TextDecoder&&new TextDecoder,gr=(t,j,s,i)=>{var o=j+s;if(i)return o;for(;t[j]&&!(j>=o);)++j;return j},_r=(t,j=0,s,i)=>{var o=gr(t,j,s,i);if(o-j>16&&t.buffer&&Dr)return Dr.decode(t.subarray(j,o));for(var a="";j<o;){var k=t[j++];if(!(k&128)){a+=String.fromCharCode(k);continue}var u=t[j++]&63;if((k&224)==192){a+=String.fromCharCode((k&31)<<6|u);continue}var d=t[j++]&63;if((k&240)==224?k=(k&15)<<12|u<<6|d:k=(k&7)<<18|u<<12|d<<6|t[j++]&63,k<65536)a+=String.fromCharCode(k);else{var G=k-65536;a+=String.fromCharCode(55296|G>>10,56320|G&1023)}}return a},ot=(t,j,s)=>t?_r(_,t,j,s):"",Br=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,at=(t,j,s)=>{var i=t>>1,o=gr(rA,i,j/2,s);if(o-i>16&&Br)return Br.decode(rA.subarray(i,o));for(var a="",k=i;k<o;++k){var u=rA[k];a+=String.fromCharCode(u)}return a},kt=(t,j,s=2147483647)=>{if(s<2)return 0;s-=2;for(var i=j,o=s<t.length*2?s/2:t.length,a=0;a<o;++a){var k=t.charCodeAt(a);uA[j>>1]=k,j+=2}return uA[j>>1]=0,j-i},ut=t=>t.length*2,ct=(t,j,s)=>{for(var i="",o=t>>2,a=0;!(a>=j/4);a++){var k=$[o+a];if(!k&&!s)break;i+=String.fromCodePoint(k)}return i},dt=(t,j,s=2147483647)=>{if(s<4)return 0;for(var i=j,o=i+s-4,a=0;a<t.length;++a){var k=t.codePointAt(a);if(k>65535&&a++,cA[j>>2]=k,j+=4,j+4>o)break}return cA[j>>2]=0,j-i},Ct=t=>{for(var j=0,s=0;s<t.length;++s){var i=t.codePointAt(s);i>65535&&s++,j+=4}return j},ft=()=>{aA("OOM")},Gt=t=>t<-9007199254740992||t>9007199254740992?NaN:Number(t),qt=[null,[],[]],pt=(t,j)=>{var s=qt[t];!j||j===10?((t===1?c:C)(_r(s)),s.length=0):s.push(j)};(()=>{let t=CA.prototype;Object.assign(t,{isAliasOf(s){if(!(this instanceof CA)||!(s instanceof CA))return!1;var i=this.$$.ptrType.registeredClass,o=this.$$.ptr;s.$$=s.$$;for(var 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||TA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var s=jA(Object.create(Object.getPrototypeOf(this),{$$:{value:Mj(this.$$)}}));return s.$$.count.value+=1,s.$$.deleteScheduled=!1,s},delete(){this.$$.ptr||TA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&q("Object already scheduled for deletion"),Cr(this),fr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||TA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&q("Object already scheduled for deletion"),dA.push(this),dA.length,this.$$.deleteScheduled=!0,this}});let j=Symbol.dispose;j&&(t[j]=t.delete)})(),Object.assign(EA.prototype,{getPointee(t){return this.rawGetPointee&&(t=this.rawGetPointee(t)),t},destructor(t){this.rawDestructor?.(t)},readValueFromPointer:GA,fromWireType:Zj}),r.noExitRuntime&&r.noExitRuntime,r.print&&(c=r.print),r.printErr&&(C=r.printErr),r.arguments&&r.arguments,r.thisProgram&&r.thisProgram;var Z=r.preInit;if(Z)for(typeof Z=="function"&&(r.preInit=Z=[Z]);Z.length>0;)Z.shift()();var xr,VA,T,Pr,br,Jr,Tr;function Et(t){xr=t.w,VA=r._malloc=t.y,T=r._free=t.z,Pr=t.A,br=t.B,Jr=t.u,Tr=t.x}var mt={i:(t,j,s)=>{var i=new Pj(t);i.init(j,s),bj++,Jj()},r:()=>aA(""),g:(t,j,s,i,o)=>{j=N(j);let a=i===0n,k=u=>u;if(a){let u=s*8;k=d=>BigInt.asUintN(u,d),o=k(o)}g(t,{name:j,fromWireType:k,toWireType:(u,d)=>(typeof d=="number"&&(d=BigInt(d)),d),readValueFromPointer:dr(j,s,!a),destructorFunction:null})},l:(t,j,s,i)=>{j=N(j),g(t,{name:j,fromWireType:function(o){return!!o},toWireType:function(o,a){return a?s:i},readValueFromPointer:function(o){return this.fromWireType(_[o])},destructorFunction:null})},k:(t,j,s,i,o,a,k,u,d,G,f,E,F)=>{f=N(f),a=B(o,a),u&&=B(k,u),G&&=B(d,G),F=B(E,F);var m=wj(f);Er(m,function(){z(\`Cannot construct \${f} due to unbound types\`,[i])}),J([t,j,s],i?[i]:[],v=>{v=v[0];var h,H;i?(h=v.registeredClass,H=h.instancePrototype):H=CA.prototype;var x=Gr(f,function(...KA){if(Object.getPrototypeOf(this)!==R)throw new AA(\`Use 'new' to construct \${f}\`);if(y.constructor_body===void 0)throw new AA(\`\${f} has no accessible constructor\`);var wr=y.constructor_body[KA.length];if(wr===void 0)throw new AA(\`Tried to invoke ctor of \${f} with invalid number of parameters (\${KA.length}) - expected (\${Object.keys(y.constructor_body).toString()}) parameters instead!\`);return wr.apply(this,KA)}),R=Object.create(H,{constructor:{value:x}});x.prototype=R;var y=new Uj(f,x,R,F,h,a,u,G);y.baseClass&&(y.baseClass.__derivedClasses??=[],y.baseClass.__derivedClasses.push(y));var ht=new EA(f,y,!0,!1,!1),Mr=new EA(f+"*",y,!1,!1,!1),Sr=new EA(f+" const*",y,!1,!0,!1);return qr[t]={pointerType:Mr,constPointerType:Sr},hr(m,x),[ht,Mr,Sr]})},j:(t,j,s,i,o,a)=>{var k=wA(j,s);o=B(i,o),J([],[t],u=>{u=u[0];var d=\`constructor \${u.name}\`;if(u.registeredClass.constructor_body===void 0&&(u.registeredClass.constructor_body=[]),u.registeredClass.constructor_body[j-1]!==void 0)throw new AA(\`Cannot register multiple constructors with identical number of parameters (\${j-1}) for class '\${u.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!\`);return u.registeredClass.constructor_body[j-1]=()=>{z(\`Cannot construct \${u.name} due to unbound types\`,k)},J([],k,G=>(G.splice(1,0,null),u.registeredClass.constructor_body[j-1]=UA(d,G,null,o,a),[])),[]})},d:(t,j,s,i,o,a,k,u,d)=>{var G=wA(s,i);j=N(j),j=Nr(j),a=B(o,a),J([],[t],f=>{f=f[0];var E=\`\${f.name}.\${j}\`;j.startsWith("@@")&&(j=Symbol[j.substring(2)]),u&&f.registeredClass.pureVirtualFunctions.push(j);function F(){z(\`Cannot call \${E} due to unbound types\`,G)}var m=f.registeredClass.instancePrototype,v=m[j];return v===void 0||v.overloadTable===void 0&&v.className!==f.name&&v.argCount===s-2?(F.argCount=s-2,F.className=f.name,m[j]=F):(pr(m,j,E),m[j].overloadTable[s-2]=F),J([],G,h=>{var H=UA(E,h,f,a,k,d);return m[j].overloadTable===void 0?(H.argCount=s-2,m[j]=H):m[j].overloadTable[s-2]=H,[]}),[]})},a:(t,j,s,i,o,a,k,u,d,G)=>{j=N(j),o=B(i,o),J([],[t],f=>{f=f[0];var E=\`\${f.name}.\${j}\`,F={get(){z(\`Cannot access \${E} due to unbound types\`,[s,k])},enumerable:!0,configurable:!0};return d?F.set=()=>z(\`Cannot access \${E} due to unbound types\`,[s,k]):F.set=()=>q(E+" is a read-only property"),Object.defineProperty(f.registeredClass.instancePrototype,j,F),J([],d?[s,k]:[s],m=>{var v=m[0],h={get(){var x=Lr(this,f,E+" getter");return v.fromWireType(o(a,x))},enumerable:!0};if(d){d=B(u,d);var H=m[1];h.set=function(x){var R=Lr(this,f,E+" setter"),y=[];d(G,R,H.toWireType(y,x)),Fr(y)}}return Object.defineProperty(f.registeredClass.instancePrototype,j,h),[]}),[]})},s:t=>g(t,nt),f:(t,j,s)=>{j=N(j),g(t,{name:j,fromWireType:i=>i,toWireType:(i,o)=>o,readValueFromPointer:et(j,s),destructorFunction:null})},n:(t,j,s,i,o,a,k)=>{var u=wA(j,s);t=N(t),t=Nr(t),o=B(i,o),Er(t,function(){z(\`Cannot call \${t} due to unbound types\`,u)},j-1),J([],u,d=>{var G=[d[0],null].concat(d.slice(1));return hr(t,UA(t,G,null,o,a,k),j-1),[]})},c:(t,j,s,i,o)=>{j=N(j);let a=i===0,k=d=>d;if(a){var u=32-8*s;k=d=>d<<u>>>u,o=k(o)}g(t,{name:j,fromWireType:k,toWireType:(d,G)=>G,readValueFromPointer:dr(j,s,i!==0),destructorFunction:null})},b:(t,j,s)=>{var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],o=i[j];function a(k){var u=$[k>>2],d=$[k+4>>2];return new o(w.buffer,d,u)}s=N(s),g(t,{name:s,fromWireType:a,readValueFromPointer:a},{ignoreDuplicateRegistrations:!0})},t:(t,j)=>{j=N(j),g(t,{name:j,fromWireType(s){var i=$[s>>2],o=s+4,a;if(1)a=ot(o,i,!0);else for(var k;k<i;++k);return T(s),a},toWireType(s,i){i instanceof ArrayBuffer&&(i=new Uint8Array(i));var o,a=typeof i=="string";a||ArrayBuffer.isView(i)&&i.BYTES_PER_ELEMENT==1||q("Cannot pass non-string to std::string"),a?o=it(i):o=i.length;var k=VA(4+o+1),u=k+4;if($[k>>2]=o,a)if(1)lt(i,u,o+1);else for(var d;d<o;++d)var G;else _.set(i,u);return s!==null&&s.push(T,k),k},readValueFromPointer:GA,destructorFunction(s){T(s)}})},e:(t,j,s)=>{s=N(s);var i,o,a;j===2?(i=at,o=kt,a=ut):(i=ct,o=dt,a=Ct),g(t,{name:s,fromWireType:k=>{var u=$[k>>2],d=i(k+4,u*j,!0);return T(k),d},toWireType:(k,u)=>{typeof u!="string"&&q(\`Cannot pass non-string to C++ string type \${s}\`);var d=a(u),G=VA(4+d+j);return $[G>>2]=d/j,o(u,G+4,d+j),k!==null&&k.push(T,G),G},readValueFromPointer:GA,destructorFunction(k){T(k)}})},m:(t,j)=>{j=N(j),g(t,{isVoid:!0,name:j,fromWireType:()=>{},toWireType:()=>{}})},o:t=>{_.length,t>>>=0,ft()},q:()=>52,p:function(t,j){return j=Gt(j),70},h:(t,j,s,i)=>{for(var o=0,a=0;a<s;a++){var k=$[j>>2],u=$[j+4>>2];j+=8;for(var d=0;d<u;d++)pt(t,_[k+d]);o+=u}return $[i>>2]=o,0}},tA;return tA=await(async function(){function t(a){return tA=a.exports,Et(tA),D(),tA}var j=_j(),s=r.instantiateWasm;if(s)return new Promise(a=>{s(j,k=>a(t(k)))});ir??=Hj();var i=await gj(0,ir,j),o=(function(a){return t(a.instance)})(i);return o})(),await(async function(){JA();var t=r.setStatus;t&&(t("Running..."),await new Promise(j=>setTimeout(j,1)),setTimeout(t,1,"")),!p&&(b(),r.onRuntimeInitialized?.(),yj())})(),r}})();typeof $j=="object"&&typeof bA=="object"?(bA.exports=nr,bA.exports.default=nr):typeof define=="function"&&define.amd&&define([],()=>nr)});var M={};yt(M,{AdditionalCaptureBlocks:()=>gt,AdditionalPlaybackBlocks:()=>Dt,ClockJumpCheckInterval:()=>Tt,ClockJumpThreshold:()=>Mt,ConnectInterval:()=>Zt,ConnectTimeout:()=>Xt,DefaultRefreshRate:()=>Bt,DefaultVideoCodec:()=>An,HealthCheckTimeout:()=>Jt,MainConnectionPingInterval:()=>St,MaxNumberOfDecoders:()=>Pt,MaxReconnectDuration:()=>Yt,MinDBFs:()=>Ur,MinTokenLifetime:()=>Wt,MinTokenRefreshInterval:()=>zt,PlaybackPreload:()=>_t,RenderQuantumSize:()=>bt,VadPreload:()=>xt,WebRtcAnswerTimeout:()=>Vt,WebRtcIceTimeout:()=>Ut,WebRtcMaxNegotiationAttempts:()=>Kt,WebRtcRecoveryDelays:()=>Qt,WebRtcStatsSnapshotInterval:()=>wt,WebRtcTimeout:()=>Rt});var Dt=3,gt=3,_t=3,Bt=250,xt=3,Pt=512,bt=128,Ur=-758.596,Jt=1e4,Tt=1e3,Mt=1e4,St=3e3,wt=1e3,Ut=3e3,Rt=1e4,Vt=1e4,Kt=3,Qt=[0,2e3,5e3],Xt=5e3,Wt=6e4,zt=5e3,Zt=[0,100,200,200,500],Yt=12e4,An="H264";function S(n,A,r){return n.postMessage(A,r)}function Rr(n){return[n.values[0],n.values[1]]}function mA(n,A){n.values[0]=A[0],n.values[1]=A[1]}function hA(n,A){return n.values[2+A*5]}function Vr(n,A,r){n.values[2+A*5]=r}function Kr(n,A){let r=2+A*5+1;return[n.values[r+0],n.values[r+1]]}function $A(n,A,r){let e=2+A*5+1;n.values[e+0]=r[0],n.values[e+1]=r[1]}function Qr(n,A){return n.values[2+A*5+3]}function Xr(n,A,r){n.values[2+A*5+3]=r}function Wr(n,A){return n.values[2+A*5+4]}function zr(n,A,r){n.values[2+A*5+4]=r}function FA(n){return n.values[0]!==0}function vA(n){return n.values[1]}function IA(n){return n.values[2]}function Zr(n){return n.values[3]}function NA(n,A){return n.values[3]=A}function Yr(n){return n?Array.from(n).map(A=>A.toString(16).padStart(2,"0")).join(""):null}var rn;(n=>{let A;(r=>(r[r.InvalidPassword=-1]="InvalidPassword",r[r.Unknown=0]="Unknown",r[r.Unencrypted=1]="Unencrypted",r[r.Encrypted=2]="Encrypted"))(A=n.PeerCipherStatus||={})})(rn||={});function nj(n){return{type:"Success",value:n}}function O(n){return{type:"Failure",reason:n}}var{Deno:Aj}=globalThis,jn=typeof Aj?.noColor=="boolean"?Aj.noColor:!1,tn=!jn;function WA(n,A){return{open:\`\\x1B[\${n.join(";")}m\`,close:\`\\x1B[\${A}m\`,regexp:new RegExp(\`\\\\x1b\\\\[\${A}m\`,"g")}}function zA(n,A){return tn?\`\${A.open}\${n.replace(A.regexp,A.open)}\${A.close}\`:n}function XA(n){return zA(n,WA([0],0))}function rj(n){return zA(n,WA([1],22))}function nn(n){return zA(n,WA([2],22))}var Yn=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"),en=new Date,LA=(n=>(n[n.CRITICAL=0]="CRITICAL",n[n.ERROR=1]="ERROR",n[n.WARN=2]="WARN",n[n.INFO=3]="INFO",n[n.DEBUG=4]="DEBUG",n))(LA||{}),ej={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},sn={4:nn,3:XA,2:XA,1:rj,0:rj};function ln({message:n}){return String(n)}function jj(n){return JSON.stringify({timestamp:n.date.toISOString(),level:LA[n.level],message:n.message,extra:n.extra})}function tj(n){function A(C,p){return[Math.floor(C/p),C%p]}function r(){let C,p=n.date.valueOf()-en.valueOf();[p,C]=A(p,1e3);let[I,D]=A(p,60);return\`\${I.toString().padStart(4,"0")}:\${D.toString().padStart(2,"0")}.\${C.toString().padStart(3,"0")}\`}function e(){return n.extra===void 0?"":typeof Deno=="object"?" "+Deno.inspect(n.extra,{compact:!1,colors:!0,trailingComma:!0}).trimStart():" "+JSON.stringify(n.extra)}let l=ej[n.level],c=n.logger.name!==void 0?\`@\${n.logger.name}\`:"";return\`\${XA(r())}\${c} \${l} \${sn[n.level](String(n.message))}\${e()}\`}function on(n){let A=\`[\${n.date.toISOString()}]\`,r=\`[\${LA[n.level]}]\`,e=n.logger.name!==void 0?\`[\${n.logger.name}] \`:"",l=ej[n.level];return\`\${A} \${l} \${r.padEnd(7," ")} \${e}\${n.message}\`}function an(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var sj=class{static sparse=ln;static json=jj;static pretty=tj;static structured=on;static default=an()?tj:jj;constructor(){}};var kn=class{formatter;consoleObject;filter;constructor(n=sj.default,A=4,r=console){this.filter=A,this.formatter=n,this.consoleObject=r}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,r=[],e=void 0){this.#A=A,this.sinks=r,this.filter=n,this.parent=e}log(n,A,r=void 0){let e={date:new Date,level:n,logger:this,message:A,extra:r};this.filter<n||this.insert(e)}insert(n){if(!(this.filter<n.level)){for(let A of this.sinks)A.filter>=n.level&&A.handle(n);this.parent!==void 0&&this.parent.insert(n)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},nA=globalThis[Symbol.for("odin-global-logger")]??=new V(3,void 0,[new kn]),un=V.prototype.log.bind(nA,1),cn=V.prototype.log.bind(nA,2),lj=V.prototype.log.bind(nA,3),dn=V.prototype.log.bind(nA,4),Ae=V.prototype.log.bind(nA);var ij;function oj(n,...A){let r=Cn(A);ij?ij?.info(n,r):lj(n,r)}function Cn(...n){if(n.length===1&&typeof n[0]=="object"&&n[0]!==null)return{...n[0]};if(n.length>0)return{args:n}}function yA(n){return n.connectionId*4294967296+n.mediaId}function aj(n){return{mediaId:n%4294967296,connectionId:Math.floor(n/4294967296)}}function P(n,A,r){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(r*e.BYTES_PER_ELEMENT);if(l===0||l%e.BYTES_PER_ELEMENT!==0)throw new Error(\`failed allocating a \${r} \${A} array\`);let c=l/e.BYTES_PER_ELEMENT;return e.subarray(c,c+r)}function K(n,A){n._free(A.byteOffset)}function kj(n,A){return{values:P(n,"f32",2+A*5),length:A}}function uj(n,A){K(n,A.values)}function cj(n){return{values:P(n,"f32",4)}}function dj(n,A){K(n,A.values)}function Cj(n){let A=n.length,r=0,e=0;for(;e<A;){let l=n.charCodeAt(e++);if((l&4294967168)===0){r++;continue}else if((l&4294965248)===0)r+=2;else{if(l>=55296&&l<=56319&&e<A){let c=n.charCodeAt(e);(c&64512)===56320&&(++e,l=((l&1023)<<10)+(c&1023)+65536)}(l&4294901760)===0?r+=3:r+=4}}return r}function fn(n,A,r){let e=n.length,l=r,c=0;for(;c<e;){let C=n.charCodeAt(c++);if((C&4294967168)===0){A[l++]=C;continue}else if((C&4294965248)===0)A[l++]=C>>6&31|192;else{if(C>=55296&&C<=56319&&c<e){let p=n.charCodeAt(c);(p&64512)===56320&&(++c,C=((C&1023)<<10)+(p&1023)+65536)}(C&4294901760)===0?(A[l++]=C>>12&15|224,A[l++]=C>>6&63|128):(A[l++]=C>>18&7|240,A[l++]=C>>12&63|128,A[l++]=C>>6&63|128)}A[l++]=C&63|128}}var Gn=new TextEncoder,qn=50;function pn(n,A,r){Gn.encodeInto(n,A.subarray(r))}function fj(n,A,r){n.length>qn?pn(n,A,r):fn(n,A,r)}var En=4096;function ZA(n,A,r){let e=A,l=e+r,c=[],C="";for(;e<l;){let p=n[e++];if((p&128)===0)c.push(p);else if((p&224)===192){let I=n[e++]&63;c.push((p&31)<<6|I)}else if((p&240)===224){let I=n[e++]&63,D=n[e++]&63;c.push((p&31)<<12|I<<6|D)}else if((p&248)===240){let I=n[e++]&63,D=n[e++]&63,JA=n[e++]&63,b=(p&7)<<18|I<<12|D<<6|JA;b>65535&&(b-=65536,c.push(b>>>10&1023|55296),b=56320|b&1023),c.push(b)}else c.push(p);c.length>=En&&(C+=String.fromCharCode(...c),c.length=0)}return c.length>0&&(C+=String.fromCharCode(...c)),C}var mn=new TextDecoder,hn=200;function $n(n,A,r){let e=n.subarray(A,A+r);return mn.decode(e)}function Gj(n,A,r){return r>hn?$n(n,A,r):ZA(n,A,r)}var Q=class{type;data;constructor(A,r){this.type=A,this.data=r}};var L=class n extends Error{constructor(A){super(A);let r=Object.create(n.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:n.name})}};function qj(n,A,r){let e=r/4294967296,l=r;n.setUint32(A,e),n.setUint32(A+4,l)}function HA(n,A,r){let e=Math.floor(r/4294967296),l=r;n.setUint32(A,e),n.setUint32(A+4,l)}function OA(n,A){let r=n.getInt32(A),e=n.getUint32(A+4);return r*4294967296+e}function pj(n,A){let r=n.getUint32(A),e=n.getUint32(A+4);return r*4294967296+e}var Fn=-1,vn=4294967296-1,In=17179869184-1;function Nn({sec:n,nsec:A}){if(n>=0&&A>=0&&n<=In)if(A===0&&n<=vn){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,n),r}else{let r=n/4294967296,e=n&4294967295,l=new Uint8Array(8),c=new DataView(l.buffer);return c.setUint32(0,A<<2|r&3),c.setUint32(4,e),l}else{let r=new Uint8Array(12),e=new DataView(r.buffer);return e.setUint32(0,A),HA(e,4,n),r}}function Ln(n){let A=n.getTime(),r=Math.floor(A/1e3),e=(A-r*1e3)*1e6,l=Math.floor(e/1e9);return{sec:r+l,nsec:e-l*1e9}}function yn(n){if(n instanceof Date){let A=Ln(n);return Nn(A)}else return null}function Hn(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 r=A.getUint32(0),e=A.getUint32(4),l=(r&3)*4294967296+e,c=r>>>2;return{sec:l,nsec:c}}case 12:{let r=OA(A,4),e=A.getUint32(0);return{sec:r,nsec:e}}default:throw new L(\`Unrecognized data size for timestamp (expected 4, 8, or 12): \${n.length}\`)}}function On(n){let A=Hn(n);return new Date(A.sec*1e3+A.nsec/1e6)}var Ej={type:Fn,encode:yn,decode:On};var Y=class n{static defaultCodec=new n;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(Ej)}register({type:A,encode:r,decode:e}){if(A>=0)this.encoders[A]=r,this.decoders[A]=e;else{let l=-1-A;this.builtInEncoders[l]=r,this.builtInDecoders[l]=e}}tryToEncode(A,r){for(let e=0;e<this.builtInEncoders.length;e++){let l=this.builtInEncoders[e];if(l!=null){let c=l(A,r);if(c!=null){let C=-1-e;return new Q(C,c)}}}for(let e=0;e<this.encoders.length;e++){let l=this.encoders[e];if(l!=null){let c=l(A,r);if(c!=null){let C=e;return new Q(C,c)}}}return A instanceof Q?A:null}decode(A,r,e){let l=r<0?this.builtInDecoders[-1-r]:this.decoders[r];return l?l(A,r,e):new Q(r,A)}};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 gn=100,_n=2048,DA=class n{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(A){this.extensionCodec=A?.extensionCodec??Y.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.maxDepth=A?.maxDepth??gn,this.initialBufferSize=A?.initialBufferSize??_n,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,r){if(r>this.maxDepth)throw new Error(\`Too deep objects in depth \${r}\`);A==null?this.encodeNil():typeof A=="boolean"?this.encodeBoolean(A):typeof A=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(A):this.encodeNumber(A):typeof A=="string"?this.encodeString(A):this.useBigInt64&&typeof A=="bigint"?this.encodeBigInt64(A):this.encodeObject(A,r)}ensureBufferSizeToWrite(A){let r=this.pos+A;this.view.byteLength<r&&this.resizeBuffer(r*2)}resizeBuffer(A){let r=new ArrayBuffer(A),e=new Uint8Array(r),l=new DataView(r);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=Cj(A);this.ensureBufferSizeToWrite(5+e),this.writeStringHeader(e),fj(A,this.bytes,this.pos),this.pos+=e}encodeObject(A,r){let e=this.extensionCodec.tryToEncode(A,this.context);if(e!=null)this.encodeExtension(e);else if(Array.isArray(A))this.encodeArray(A,r);else if(ArrayBuffer.isView(A))this.encodeBinary(A);else if(typeof A=="object")this.encodeMap(A,r);else throw new Error(\`Unrecognized object: \${Object.prototype.toString.apply(A)}\`)}encodeBinary(A){let r=A.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(\`Too large binary: \${r}\`);let e=eA(A);this.writeU8a(e)}encodeArray(A,r){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,r+1)}countWithoutUndefined(A,r){let e=0;for(let l of r)A[l]!==void 0&&e++;return e}encodeMap(A,r){let e=Object.keys(A);this.sortKeys&&e.sort();let l=this.ignoreUndefined?this.countWithoutUndefined(A,e):e.length;if(l<16)this.writeU8(128+l);else if(l<65536)this.writeU8(222),this.writeU16(l);else if(l<4294967296)this.writeU8(223),this.writeU32(l);else throw new Error(\`Too large map object: \${l}\`);for(let c of e){let C=A[c];this.ignoreUndefined&&C===void 0||(this.encodeString(c),this.doEncode(C,r+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 r=A.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(\`Too large extension object: \${r}\`);this.writeI8(A.type),this.writeU8a(A.data)}writeU8(A){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,A),this.pos++}writeU8a(A){let r=A.length;this.ensureBufferSizeToWrite(r),this.bytes.set(A,this.pos),this.pos+=r}writeI8(A){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,A),this.pos++}writeU16(A){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,A),this.pos+=2}writeI16(A){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,A),this.pos+=2}writeU32(A){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,A),this.pos+=4}writeI32(A){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,A),this.pos+=4}writeF32(A){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,A),this.pos+=4}writeF64(A){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,A),this.pos+=8}writeU64(A){this.ensureBufferSizeToWrite(8),qj(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 DA(A).encodeSharedRef(n)}function gA(n){return\`\${n<0?"-":""}0x\${Math.abs(n).toString(16).padStart(2,"0")}\`}var Bn=16,xn=16,_A=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(A=Bn,r=xn){this.maxKeyLength=A,this.maxLengthPerKey=r,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(A){return A>0&&A<=this.maxKeyLength}find(A,r,e){let l=this.caches[e-1];A:for(let c of l){let C=c.bytes;for(let p=0;p<e;p++)if(C[p]!==A[r+p])continue A;return c.str}return null}store(A,r){let e=this.caches[A.length-1],l={bytes:A,str:r};e.length>=this.maxLengthPerKey?e[Math.random()*e.length|0]=l:e.push(l)}decode(A,r,e){let l=this.find(A,r,e);if(l!=null)return this.hit++,l;this.miss++;let c=ZA(A,r,e),C=Uint8Array.prototype.slice.call(A,r,r+e);return this.store(C,c),c}};var Ar="array",iA="map_key",hj="map_value",Pn=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new L("The type of key must be string or number but "+typeof n)},rr=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(A){let r=this.getUninitializedStateFromPool();r.type=Ar,r.position=0,r.size=A,r.array=new Array(A)}pushMapState(A){let r=this.getUninitializedStateFromPool();r.type=iA,r.readCount=0,r.size=A,r.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let A={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(A)}return this.stack[this.stackHeadPosition]}release(A){if(this.stack[this.stackHeadPosition]!==A)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(A.type===Ar){let e=A;e.size=0,e.array=void 0,e.position=0,e.type=void 0}if(A.type===iA||A.type===hj){let e=A;e.size=0,e.map=void 0,e.readCount=0,e.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},lA=-1,jr=new DataView(new ArrayBuffer(0)),bn=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 mj=new RangeError("Insufficient data"),Jn=new _A,BA=class n{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=jr;bytes=bn;headByte=lA;stack=new rr;entered=!1;constructor(A){this.extensionCodec=A?.extensionCodec??Y.defaultCodec,this.context=A?.context,this.useBigInt64=A?.useBigInt64??!1,this.rawStrings=A?.rawStrings??!1,this.maxStrLength=A?.maxStrLength??4294967295,this.maxBinLength=A?.maxBinLength??4294967295,this.maxArrayLength=A?.maxArrayLength??4294967295,this.maxMapLength=A?.maxMapLength??4294967295,this.maxExtLength=A?.maxExtLength??4294967295,this.keyDecoder=A?.keyDecoder!==void 0?A.keyDecoder:Jn,this.mapKeyConverter=A?.mapKeyConverter??Pn}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=lA,this.stack.reset()}setBuffer(A){let r=eA(A);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(A){if(this.headByte===lA&&!this.hasRemaining(1))this.setBuffer(A);else{let r=this.bytes.subarray(this.pos),e=eA(A),l=new Uint8Array(r.length+e.length);l.set(r),l.set(e,r.length),this.setBuffer(l)}}hasRemaining(A){return this.view.byteLength-this.pos>=A}createExtraByteError(A){let{view:r,pos:e}=this;return new RangeError(\`Extra \${r.byteLength-e} of \${r.byteLength} byte(s) found at buffer[\${A}]\`)}decode(A){if(this.entered)return this.clone().decode(A);try{this.entered=!0,this.reinitializeState(),this.setBuffer(A);let r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(A){if(this.entered){yield*this.clone().decodeMulti(A);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(A);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(A){if(this.entered)return this.clone().decodeAsync(A);try{this.entered=!0;let r=!1,e;for await(let p of A){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(p);try{e=this.doDecodeSync(),r=!0}catch(I){if(!(I instanceof RangeError))throw I}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return e}let{headByte:l,pos:c,totalPos:C}=this;throw new RangeError(\`Insufficient data in parsing \${gA(l)} at \${C} (\${c} in the current buffer)\`)}finally{this.entered=!1}}decodeArrayStream(A){return this.decodeMultiAsync(A,!0)}decodeStream(A){return this.decodeMultiAsync(A,!1)}async*decodeMultiAsync(A,r){if(this.entered){yield*this.clone().decodeMultiAsync(A,r);return}try{this.entered=!0;let e=r,l=-1;for await(let c of A){if(r&&l===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c),e&&(l=this.readArraySize(),e=!1,this.complete());try{for(;yield this.doDecodeSync(),--l!==0;);}catch(C){if(!(C instanceof RangeError))throw C}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){A:for(;;){let A=this.readHeadByte(),r;if(A>=224)r=A-256;else if(A<192)if(A<128)r=A;else if(A<144){let l=A-128;if(l!==0){this.pushMapState(l),this.complete();continue A}else r={}}else if(A<160){let l=A-144;if(l!==0){this.pushArrayState(l),this.complete();continue A}else r=[]}else{let l=A-160;r=this.decodeString(l,0)}else if(A===192)r=null;else if(A===194)r=!1;else if(A===195)r=!0;else if(A===202)r=this.readF32();else if(A===203)r=this.readF64();else if(A===204)r=this.readU8();else if(A===205)r=this.readU16();else if(A===206)r=this.readU32();else if(A===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(A===208)r=this.readI8();else if(A===209)r=this.readI16();else if(A===210)r=this.readI32();else if(A===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(A===217){let l=this.lookU8();r=this.decodeString(l,1)}else if(A===218){let l=this.lookU16();r=this.decodeString(l,2)}else if(A===219){let l=this.lookU32();r=this.decodeString(l,4)}else if(A===220){let l=this.readU16();if(l!==0){this.pushArrayState(l),this.complete();continue A}else r=[]}else if(A===221){let l=this.readU32();if(l!==0){this.pushArrayState(l),this.complete();continue A}else r=[]}else if(A===222){let l=this.readU16();if(l!==0){this.pushMapState(l),this.complete();continue A}else r={}}else if(A===223){let l=this.readU32();if(l!==0){this.pushMapState(l),this.complete();continue A}else r={}}else if(A===196){let l=this.lookU8();r=this.decodeBinary(l,1)}else if(A===197){let l=this.lookU16();r=this.decodeBinary(l,2)}else if(A===198){let l=this.lookU32();r=this.decodeBinary(l,4)}else if(A===212)r=this.decodeExtension(1,0);else if(A===213)r=this.decodeExtension(2,0);else if(A===214)r=this.decodeExtension(4,0);else if(A===215)r=this.decodeExtension(8,0);else if(A===216)r=this.decodeExtension(16,0);else if(A===199){let l=this.lookU8();r=this.decodeExtension(l,1)}else if(A===200){let l=this.lookU16();r=this.decodeExtension(l,2)}else if(A===201){let l=this.lookU32();r=this.decodeExtension(l,4)}else throw new L(\`Unrecognized type byte: \${gA(A)}\`);this.complete();let e=this.stack;for(;e.length>0;){let l=e.top();if(l.type===Ar)if(l.array[l.position]=r,l.position++,l.position===l.size)r=l.array,e.release(l);else continue A;else if(l.type===iA){if(r==="__proto__")throw new L("The key __proto__ is not allowed");l.key=this.mapKeyConverter(r),l.type=hj;continue A}else if(l.map[l.key]=r,l.readCount++,l.readCount===l.size)r=l.map,e.release(l);else{l.key=null,l.type=iA;continue A}}return r}}readHeadByte(){return this.headByte===lA&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=lA}readArraySize(){let A=this.readHeadByte();switch(A){case 220:return this.readU16();case 221:return this.readU32();default:{if(A<160)return A-144;throw new L(\`Unrecognized array type byte: \${gA(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,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(A,r):this.decodeBinary(A,r)}decodeUtf8String(A,r){if(A>this.maxStrLength)throw new L(\`Max length exceeded: UTF-8 byte length (\${A}) > maxStrLength (\${this.maxStrLength})\`);if(this.bytes.byteLength<this.pos+r+A)throw mj;let e=this.pos+r,l;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(A)?l=this.keyDecoder.decode(this.bytes,e,A):l=Gj(this.bytes,e,A),this.pos+=r+A,l}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===iA:!1}decodeBinary(A,r){if(A>this.maxBinLength)throw new L(\`Max length exceeded: bin length (\${A}) > maxBinLength (\${this.maxBinLength})\`);if(!this.hasRemaining(A+r))throw mj;let e=this.pos+r,l=this.bytes.subarray(e,e+A);return this.pos+=r+A,l}decodeExtension(A,r){if(A>this.maxExtLength)throw new L(\`Max length exceeded: ext length (\${A}) > maxExtLength (\${this.maxExtLength})\`);let e=this.view.getInt8(this.pos+r),l=this.decodeBinary(A,r+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=pj(this.view,this.pos);return this.pos+=8,A}readI64(){let A=OA(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 BA(A).decode(n)}var oA=class n{constructor(A,r,e,l,c){this.mediaIds=A;this.sequenceNumber=r;this.timeStamp=e;this.isEndOfSpurt=l;this.payload=c}static parse(A){let r;try{r=tr(A)}catch{return O("not valid msgpack")}if(!Array.isArray(r))return O("container must be an array");if(r.length<6)return O("missing fields");if(r[0]!==1)return O("unknown type");if(!Array.isArray(r[1]))return O("media ids must be an array");if(!r[1].every(D=>typeof D=="number"))return O("media ids must be numbers");if(typeof r[2]!="number")return O("sequence number must be a number");if(typeof r[3]!="number")return O("timestamp must be a number");if(typeof r[4]!="number")return O("flags must be a number");let e=r[1],l=r[2]>>>0,c=r[3]>>>0,p=(r[4]&1)!==0,I=r[r.length-1];return I instanceof Uint8Array?nj(new n(e,l,c,p,I)):O("payload must be bytes")}toBytes(){let A=Number(this.isEndOfSpurt),r=[1,this.mediaIds,this.sequenceNumber>>>0,this.timeStamp>>>0,A,this.payload];return new Uint8Array(YA(r,{forceFloat32:!0,ignoreUndefined:!0}))}};var xA=class{constructor(A,r){this.sampleRate=A;this.wasm=r;this.sequenceNumber=Math.random()*Math.pow(2,32)>>0;this.timestamp=Math.random()*Math.pow(2,32)>>0;this.connections=[];this.monitoring=!1;this.active=!1;this.stats={numberPackets:0,numberTicks:0,numberPacketError:0,numberPacketsMediaNotFound:0};this.encoder=new r.Encoder(A,15,!0,M.VadPreload),this.encoder.complexity=navigator.hardwareConcurrency>=4?6:4,this.information=cj(this.wasm),this.outBuffer=P(this.wasm,"u8",1270),NA(this.information,1)}setVad(A){this.encoder.set_volume_gate(A.volumeGate!==void 0,A.volumeGate?.attackThreshold??0,A.volumeGate?.releaseThreshold??0),this.encoder.set_speech_detection(A.voiceActivity!==void 0,A.voiceActivity?.attackThreshold??0,A.voiceActivity?.releaseThreshold??0)}setMedias(A){this.connections=A.filter(({mediaIds:r})=>r.length>0)}close(){dj(this.wasm,this.information),K(this.wasm,this.outBuffer),this.encoder.delete()}encode(A){for(this.encoder.push(A.byteOffset,this.information.values.byteOffset);;){let r=this.encoder.pop(this.connections.length===0?0:this.outBuffer.byteOffset,this.outBuffer.length);if(r===0)break;if(r<0){oj(\`failed encoding packet: \${r}\`);return}if(this.timestamp=this.timestamp+1800>>0,r===1)continue;this.sequenceNumber=this.sequenceNumber+1>>0;let e=this.active&&!this.encoder.active;this.active=this.encoder.active,this.monitoring=this.connections.some(l=>l.id===0);for(let l of this.connections){if(this.monitoring&&l.id!==0)continue;let c=new oA(l.mediaIds,this.sequenceNumber,this.timestamp,e,this.outBuffer.subarray(0,r));S(globalThis,["sendPacket",{connectionId:l.id,packet:c.toBytes()}])}}}onMessage(A){let[r,e]=A;switch(r){case"captureSetVad":this?.setVad(e);break;case"captureSetMedias":this?.setMedias(e.connections);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){return{sequenceNumber:this.sequenceNumber,timestamp:this.timestamp,connections:this.connections.map(A=>\`\${A.id} => \${A.mediaIds.join(",")}\`),active:this.active,monitoring:this.monitoring,information:{active:FA(this.information),speechProbability:vA(this.information),rmsDBFS:IA(this.information),volume:Zr(this.information)},encoder:{sample_rate:this.encoder.sample_rate,fec_packet_loss:this.encoder.fec_packet_loss,voip:this.encoder.voip,vad_preload:this.encoder.vad_preload,complexity:this.encoder.complexity,speech_probability:this.encoder.speech_probability,rms_dbfs:this.encoder.rms_dbfs,active:this.encoder.active,speech_detection_enabled:this.encoder.speech_detection_enabled,speech_detection_going_active:this.encoder.speech_detection_going_active,speech_detection_going_inactive:this.encoder.speech_detection_going_inactive,volume_gate_enabled:this.encoder.volume_gate_enabled,volume_gate_going_active:this.encoder.volume_gate_going_active,volume_gate_going_inactive:this.encoder.volume_gate_going_inactive}}}},PA=class{constructor(A){this.wasm=A;this.medias=new Map;this.stats={numberPackets:0,numberTicks:0,numberPacketError:0,numberPacketsMediaNotFound:0,numberTicksWithAudio:0};this.largestIndex=-1;this.decoders=P(this.wasm,"u32",M.MaxNumberOfDecoders),this.information=kj(this.wasm,M.MaxNumberOfDecoders),mA(this.information,[1,1])}close(){uj(this.wasm,this.information);for(let{decoder:A}of this.medias.values())A.delete()}receivePacket(A,r){this.stats.numberPackets++;let e=oA.parse(r);if(e.type==="Failure"){this.stats.numberPacketError++;let l=Array.from(r).map(c=>c.toString(16).padStart(2,"0")).join("");console.error(\`failed decoding audio packet; reason: \${e.reason}, connection: \${A}, dump: \${l}\`);return}for(let l of e.value.mediaIds){let c=this.medias.get(yA({connectionId:A,mediaId:l}));if(c===void 0){this.stats.numberPacketsMediaNotFound++;continue}c.lastPacket=r;let C=P(this.wasm,"u8",e.value.payload.length);C.set(e.value.payload),c.decoder.push(e.value.sequenceNumber,e.value.timeStamp,e.value.isEndOfSpurt,C.byteOffset,C.length)}}insertMedia(A,r,e,l=[1,1]){let c=yA({connectionId:r,mediaId:e}),C=new this.wasm.Decoder;this.medias.set(c,{index:A,decoder:C,lastPacket:void 0}),this.decoders[A]=C.$$.ptr,this.largestIndex=Math.max(this.largestIndex,A),$A(this.information,A,l),zr(this.information,A,0),Xr(this.information,A,0)}removeMedia(A,r,e){let l=yA({connectionId:r,mediaId:e}),c=this.medias.get(l);if(!(c===void 0||c.index!==A)&&(this.medias.delete(l),Vr(this.information,A,0),this.decoders[A]=0,c.decoder.delete(),A===this.largestIndex)){for(A=A-1;A>=0&&this.decoders[A]===0;A--);this.largestIndex=A}}decode(A){return{hasAudio:this.wasm.pop_many(this.decoders.byteOffset,this.information.values.byteOffset,this.largestIndex+1,A.byteOffset)}}onMessage(A){let[r,e]=A;switch(r){case"playbackReceivePacket":this.receivePacket(e.connectionId,e.packet);break;case"playbackUpdateMedias":for(let{index:l,connectionId:c,mediaId:C}of e.removed)this.removeMedia(l,c,C);for(let{index:l,connectionId:c,mediaId:C,volume:p}of e.added)this.insertMedia(l,c,C,p);break;case"close":this.close();break;case"dump":e.result.postMessage(this.dump());break}}dump(){let A=[];for(let[r,e]of this.medias){let l=aj(r);A.push({index:e.index,connectionId:l.connectionId,mediaId:l.mediaId,rmsDBFS:hA(this.information,e.index),volume:Kr(this.information,e.index),voicedBlocks:Wr(this.information,e.index),silentBlocks:Qr(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:Yr(e.lastPacket)})}return{largestIndex:this.largestIndex,globalVolume:Rr(this.information),decoders:A}}};var Lj=Ot(Fj()),vj=(0,Lj.default)(),Ij,Nj;globalThis.addEventListener("message",n=>{er(n).catch(console.error)});async function er(n){let A=n.data,[r,e]=A;switch(r){case"captureInit":e.workletPort.onmessage=er,Ij=new sr(e.sampleRate,await vj,e.refreshRate);break;case"playbackInit":e.workletPort.onmessage=er,Nj=new lr(await vj,e.workletPort,e.refreshRate);break;case"close":globalThis.close();break}Ij?.onMessage(A),Nj?.onMessage(A)}var sr=class extends xA{constructor(r,e,l){super(r,e);this.sampleRate=r;this.inBuffer=P(this.wasm,"f32",r*.02),this.updateHandle=setInterval(()=>this.update(),l),S(globalThis,["captureReady",{}])}close(){super.close(),K(this.wasm,this.inBuffer),clearInterval(this.updateHandle)}onMessage(r){super.onMessage(r);let[e,l]=r;switch(e){case"captureSetVolume":this.setVolume(l.value);break;case"captureTick":this.tick(l.buffer);break}}setVolume(r){NA(this.information,r)}tick(r){this.inBuffer.set(r,0),this.encode(this.inBuffer)}update(){S(globalThis,["captureUpdate",{active:FA(this.information),rmsDBFs:IA(this.information),speechProbability:vA(this.information)}])}dump(){return{type:"unshared capture worker",sampleRate:this.sampleRate,...super.dump()}}},lr=class extends PA{constructor(r,e,l){super(r);this.workletPort=e;this.id=M.PlaybackPreload,this.outBuffer=P(this.wasm,"f32",48e3*.02*2),this.updateHandle=setInterval(()=>this.update(),l),S(globalThis,["playbackReady",{}])}close(){super.close(),K(this.wasm,this.outBuffer),clearInterval(this.updateHandle)}onMessage(r){super.onMessage(r);let[e,l]=r;switch(e){case"playbackSetVolume":this.setVolume(l.index,l.value);break;case"playbackTick":this.tick();break}}setVolume(r,e){r==="global"?mA(this.information,e):$A(this.information,r,e)}tick(){this.stats.numberTicks++,this.id+=1;let{hasAudio:r}=this.decode(this.outBuffer);if(r){let e=this.outBuffer.slice();S(this.workletPort,["samples",{id:this.id,buffer:e}],[e.buffer])}}update(){let r=new Float32Array(this.information.length*2);for(let l=0;l<=this.largestIndex;l++)r[l]=hA(this.information,l);let e=[];for(let[l,c]of this.medias)e[c.index]={packetsBuffered:c.decoder.cache_length,packetsSeen:c.decoder.packets_seen,packetsProcessed:c.decoder.packets_processed,packetsTooEarly:c.decoder.packets_too_early,packetsTooLate:c.decoder.packets_too_late,packetsDropped:0,packetsInvalid:c.decoder.packets_invalid,packetsRepeated:c.decoder.packets_repeated,packetsLost:c.decoder.packets_lost};S(globalThis,["playbackUpdate",{activities:r,jitterStats:e}],[r.buffer])}dump(){return{type:"unshared playback worker",id:this.id,...super.dump()}}};})();
|
|
6681
|
-
`});var o0,Z0=p(()=>{o0='"use strict";(()=>{var R=Object.defineProperty;var A=(e,t)=>{for(var r in t)R(e,r,{get:t[r],enumerable:!0})};var u={};A(u,{AdditionalCaptureBlocks:()=>E,AdditionalPlaybackBlocks:()=>P,ClockJumpCheckInterval:()=>_,ClockJumpThreshold:()=>N,ConnectInterval:()=>X,ConnectTimeout:()=>Z,DefaultRefreshRate:()=>C,DefaultVideoCodec:()=>Y,HealthCheckTimeout:()=>O,MainConnectionPingInterval:()=>W,MaxNumberOfDecoders:()=>L,MaxReconnectDuration:()=>K,MinDBFs:()=>v,MinTokenLifetime:()=>q,MinTokenRefreshInterval:()=>Q,PlaybackPreload:()=>M,RenderQuantumSize:()=>V,VadPreload:()=>D,WebRtcAnswerTimeout:()=>H,WebRtcIceTimeout:()=>$,WebRtcMaxNegotiationAttempts:()=>J,WebRtcRecoveryDelays:()=>z,WebRtcStatsSnapshotInterval:()=>j,WebRtcTimeout:()=>G});var P=3,E=3,M=3,C=250,D=3,L=512,V=128,v=-758.596,O=1e4,_=1e3,N=1e4,W=3e3,j=1e3,$=3e3,G=1e4,H=1e4,J=3,z=[0,2e3,5e3],Z=5e3,q=6e4,Q=5e3,X=[0,100,200,200,500],K=12e4,Y="H264";function d(e,t,r){return e.postMessage(t,r)}var ee;(e=>{let t;(r=>(r[r.InvalidPassword=-1]="InvalidPassword",r[r.Unknown=0]="Unknown",r[r.Unencrypted=1]="Unencrypted",r[r.Encrypted=2]="Encrypted"))(t=e.PeerCipherStatus||={})})(ee||={});var{Deno:k}=globalThis,te=typeof k?.noColor=="boolean"?k.noColor:!1,re=!te;function m(e,t){return{open:`\\x1B[${e.join(";")}m`,close:`\\x1B[${t}m`,regexp:new RegExp(`\\\\x1b\\\\[${t}m`,"g")}}function h(e,t){return re?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}function p(e){return h(e,m([0],0))}function S(e){return h(e,m([1],22))}function ne(e){return h(e,m([2],22))}var Ie=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),se=new Date,f=(e=>(e[e.CRITICAL=0]="CRITICAL",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(f||{}),I={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},oe={4:ne,3:p,2:p,1:S,0:S};function ae({message:e}){return String(e)}function T(e){return JSON.stringify({timestamp:e.date.toISOString(),level:f[e.level],message:e.message,extra:e.extra})}function U(e){function t(c,i){return[Math.floor(c/i),c%i]}function r(){let c,i=e.date.valueOf()-se.valueOf();[i,c]=t(i,1e3);let[B,F]=t(i,60);return`${B.toString().padStart(4,"0")}:${F.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=I[e.level],a=e.logger.name!==void 0?`@${e.logger.name}`:"";return`${p(r())}${a} ${s} ${oe[e.level](String(e.message))}${n()}`}function ie(e){let t=`[${e.date.toISOString()}]`,r=`[${f[e.level]}]`,n=e.logger.name!==void 0?`[${e.logger.name}] `:"",s=I[e.level];return`${t} ${s} ${r.padEnd(7," ")} ${n}${e.message}`}function ce(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var w=class{static sparse=ae;static json=T;static pretty=U;static structured=ie;static default=ce()?U:T;constructor(){}};var ue=class{formatter;consoleObject;filter;constructor(e=w.default,t=4,r=console){this.filter=t,this.formatter=e,this.consoleObject=r}handle(e){let t=this.formatter(e);switch(e.level){case 0:case 1:this.consoleObject.error(t);break;case 2:this.consoleObject.warn(t);break;case 3:this.consoleObject.info(t);break;case 4:this.consoleObject.debug(t);break}}};var o=class{#e;sinks;filter;parent;get name(){return this.#e}constructor(e,t=void 0,r=[],n=void 0){this.#e=t,this.sinks=r,this.filter=e,this.parent=n}log(e,t,r=void 0){let n={date:new Date,level:e,logger:this,message:t,extra:r};this.filter<e||this.insert(n)}insert(e){if(!(this.filter<e.level)){for(let t of this.sinks)t.filter>=e.level&&t.handle(e);this.parent!==void 0&&this.parent.insert(e)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},l=globalThis[Symbol.for("odin-global-logger")]??=new o(3,void 0,[new ue]),le=o.prototype.log.bind(l,1),fe=o.prototype.log.bind(l,2),de=o.prototype.log.bind(l,3),pe=o.prototype.log.bind(l,4),we=o.prototype.log.bind(l);var b=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.blocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"init":this.state=new y(s.workerPort,sampleRate*.02);break;case"close":this.alive=!1;break;case"dump":s.result.postMessage(this.dump());break}}process(r,n,s){if(this.state===void 0||r.length<1||r[0].length<1)return this.alive;let a=this.state.fill(0,r[0][0]);return this.state.offset===this.state.length&&(this.state.flush(),this.state.fill(a,r[0][0])),this.alive}dump(){return{type:"unshared capture worklet",alive:this.alive,sampleRate,offset:this.state?.offset||null,length:this.state?.length||null,blocks:this.blocks}}},x=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.silenceBlocks=0;this.voiceBlocks=0;this.totalBlocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"close":this.alive=!1;break;case"init":this.state=new g(s.workerPort,sampleRate*.02),s.workerPort.onmessage=this.onMessage.bind(this);break;case"samples":this.state?.add(s.id,s.buffer);break;case"dump":s.result.postMessage(this.dump());break}n==="close"&&(this.alive=!1)}process(r,n,s){if(this.state===void 0||n.length<1||n[0].length<2)return this.alive;let a=this.state.fill(0,n[0][0],n[0][1]);return a<u.RenderQuantumSize&&(this.totalBlocks+=1,this.state.next(),this.state.hasVoice?this.voiceBlocks+=1:this.silenceBlocks+=1,this.state.fill(a,n[0][0],n[0][1])),this.alive}dump(){return{type:"unshared playback worklet",alive:this.alive,sampleRate,id:this.state?.id||null,offset:this.state?.offset||null,length:this.state?.length||null,hasVoice:this.state?.hasVoice??!1,silenceBlocks:this.silenceBlocks,voiceBlocks:this.voiceBlocks,totalBlocks:this.totalBlocks}}},y=class{constructor(t,r){this.port=t;this.length=r;this.offset=0,this.buffer=new Float32Array(r)}fill(t,r){let n=Math.min(r.length-t,this.length-this.offset);return this.buffer.set(r.subarray(t,t+n),this.offset),this.offset+=n,t+n}flush(){d(this.port,["captureTick",{buffer:this.buffer}],[this.buffer.buffer]),this.offset=0,this.buffer=new Float32Array(this.length)}},g=class{constructor(t,r){this.port=t;this.length=r;this.cache=[];this.id=-1,this.offset=0,this.buffer=void 0,this.next()}get hasVoice(){return this.buffer!==void 0}fill(t,r,n){let s=Math.min(u.RenderQuantumSize-t,this.length-this.offset);return this.buffer!==void 0&&(r.set(this.buffer.subarray(this.offset,this.offset+s),t),n.set(this.buffer.subarray(this.offset+this.length,this.offset+this.length+s),t)),this.offset+=s,t+s}add(t,r){this.cache.push({id:t,buffer:r})}next(){for(this.id+=1;this.cache[0]?.id<this.id;)this.cache.shift();this.cache[0]?.id===this.id?(this.buffer=this.cache[0].buffer,this.cache.shift()):this.buffer=void 0,this.offset=0,d(this.port,["playbackTick",{}])}};registerProcessor("OdinCaptureProcessor",b);registerProcessor("OdinPlaybackProcessor",x);})();\n'});var xA={};hx(xA,{UnsharedCaptureWorker:()=>$x,UnsharedPlaybackWorker:()=>_x,createCaptureWorker:()=>uF,createPlaybackWorker:()=>cF});function uF(t,x,A,F,D=E.DefaultRefreshRate){return lF.enqueue(async()=>{let[r,e]=await nx(i0,o0,t,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return console.warn("SharedArrayBuffer is not available; creating ODIN CaptureWorker in fallback mode"),$x.create(t,x,A,D,r,e,F)})}async function cF(t,x=E.DefaultRefreshRate){if(t.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[A,F]=await nx(i0,o0,t,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return _x.create(t,x,A,F)}var Y0,lF,$x,_x,AA=p(()=>{"use strict";Y0=require("@4players/odin-common");o();gx();z0();Z0();lF=new Y0.Strand;$x=class t extends Cx{constructor(A,F,D,r,e){super(A,F,D,r,e);this._Activity=I;this._SpeechProbability=0;F.addEventListener("message",this._OnMessages.bind(this))}static async create(A,F,D,r,e,j,B){let{port1:f,port2:a}=new MessageChannel;return l(e,["captureInit",{sampleRate:A.sampleRate,refreshRate:r,workletPort:f}],[f]),await tx(e,"captureReady"),l(j.port,["init",{workerPort:a}],[a]),new t(j,e,F,D,B)}get activity(){return this._Activity}get speechProbability(){return this._SpeechProbability}setVolume(A){l(this.worker,["captureSetVolume",{value:A}])}_OnMessages(A){super._OnMessages(A);let[F,D]=A.data;F==="captureUpdate"&&(this._Activity={isSilent:!D.active,rmsDBFS:D.rmsDBFs},this._SpeechProbability=D.speechProbability)}},_x=class t extends vx{constructor(A,F,D){super(A,F,D);this.activities=new Float32Array;this.jitterStats=[]}static async create(A,F,D,r){let{port1:e,port2:j}=new MessageChannel;return l(D,["playbackInit",{workletPort:e,refreshRate:F}],[e]),await tx(D,"playbackReady"),l(r.port,["init",{workerPort:j}],[j]),new t(A,r,D)}getActivity(A){let F=this.medias.get(h(A));if(F===void 0)return;let D=this.activities.at(F.index);if(D!==void 0)return D===0?I:{isSilent:!1,rmsDBFS:D}}getJitterStats(A){let F=this.medias.get(h(A));if(F===void 0)return;let D=this.jitterStats.at(F.index);if(D!==void 0)return D}setGlobalVolume(A){l(this.worker,["playbackSetVolume",{index:"global",value:A}])}setVolume(A,F){let D=this.medias.get(h(A));D!==void 0&&l(this.worker,["playbackSetVolume",{index:D.index,value:F}])}_GetFreeIndex(){let A=super._GetFreeIndex();if(A!==void 0)return A;if(this.medias.size<E.MaxNumberOfDecoders)return this.medias.size}_OnMessages(A){super._OnMessages(A);let[F,D]=A.data;F==="playbackUpdate"&&(this.activities=D.activities,this.jitterStats=D.jitterStats)}}});var KF={};hx(KF,{SESSION_ID:()=>ux,createPlugin:()=>VF});module.exports=OA(KF);var h0=require("@4players/odin-common");o();var T=require("@4players/odin-common");o();var Ax=require("@4players/odin-common");o();var N=require("@4players/odin-common");o();var T0="getUserMedia; timeout";async function S0(t,x){try{let A=await Promise.race([navigator.mediaDevices.getUserMedia({audio:{echoCancellation:t.echoCanceller,noiseSuppression:t.noiseSuppression!=="None",autoGainControl:t.gainController,echoCancellationType:"system",deviceId:x?{exact:x}:void 0}}),(0,N.sleep)(3e4,"timeout")]);return A==="timeout"?(0,N.failure)(T0):(0,N.success)(A)}catch(A){return(0,N.failure)(`getUserMedia; ${A}`)}}async function M0(t,x,A){let F,D=!1;if(x.device?.device.kind==="track"&&x.device?.device.audioTrack)F=new MediaStream([x.device.device.audioTrack]);else{let j=x.device&&x.device.device.deviceId!=="default"?x.device.device.deviceId:void 0,B=await S0(A,j);if(B.type!=="Success"&&B.reason!==T0&&j&&(C(`unable to open requested capture device, falling back to default; ${B.reason}`),B=await S0(A),D=B.type==="Success"),B.type!=="Success")return B;F=B.value}let r=F.getAudioTracks()[0].getSettings().sampleRate,e=await t.audioContexts.acquire(r);return(0,N.success)({source:e.createMediaStreamSource(F),defaulted:D})}function jx(t){t.getTracks().forEach(x=>{x.stop(),t.removeTrack(x)})}async function J0(t){return new ex({deviceId:t.id,kind:"track",name:t.label??"MediaStreamTrack",audioTrack:t},!1)}async function jF(){let t=(await navigator.mediaDevices.enumerateDevices()).filter(x=>!!x.label);if(t.length===0&&(0,N.isFirefoxBrowser)()){let x=await BF("microphone");(x==="granted"||x===!1)&&(await vF("audio"),t=(await navigator.mediaDevices.enumerateDevices()).filter(A=>!!A.label))}return t}async function yx(){let t=await jF(),x=new Map,A=[];for(let D of t){let r=D.kind;if(!(r!=="audioinput"&&r!=="audiooutput")){if(D.deviceId==="default"){x.set(r,D);continue}D.deviceId!=="communications"&&A.push(new ex({deviceId:D.deviceId,name:D.label,kind:r},!1))}}let F=D=>new ex({deviceId:"default",name:x.get(D)?.label??"Default",kind:D},!0);return[F("audioinput"),F("audiooutput"),...A]}async function BF(t){try{return(await navigator.permissions.query({name:t})).state}catch{return!1}}async function vF(t){try{let x=await navigator.mediaDevices.getUserMedia({[t]:!0});return x?.getTracks().forEach(A=>{A.stop(),x.removeTrack(A)}),!0}catch{return!1}}var Ix=require("@4players/odin-common");o();var FA=(0,Ix.isSharedArrayBufferCapable)()&&!(0,Ix.isSafariBrowser)()?Promise.resolve().then(()=>(X0(),Q0)):Promise.resolve().then(()=>(AA(),xA));async function DA(t,x,A,F){return FA.then(D=>D.createCaptureWorker(t,x,A,F,E.DefaultRefreshRate))}async function rA(t){return FA.then(x=>x.createPlaybackWorker(t,E.DefaultRefreshRate))}var dF=250,kF=1e3,S=class{constructor(x,A){this.controller=x;this._Medias=new Map;this._Vad={...Ax.VAD_DEFAULTS};this._Apm={...Ax.APM_DEFAULTS};this._Volume=1;this._Queue=Promise.resolve();this.#D=0;this._DeviceCb=()=>{clearTimeout(this.#F),this.#F=setTimeout(()=>{this._enqueue(async()=>{let x=this._DeviceParameters?.device;!x||x.device.kind==="track"||(x.device.deviceId==="default"?await this._followDefaultDevice():await this._detectSelectedDeviceRemoved(x.device.deviceId))}).catch(x=>C("device-change handler failed",x))},dF)};A.apm&&this.setApm(A.apm).catch(console.error),A.vad&&this.setVad(A.vad),typeof A.volume<"u"&&this.setVolume(A.volume).catch(console.error),this.uid=(0,Ax.generateUUID)(),this.#x=A.customType,this.#A=A.ref}#x;#A;#F;#D;async _followDefaultDevice(){let x=this._DeviceParameters;this._Volume==="muted"||!this._Capture||!x||Date.now()-this.#D<kF||(s("default capture device may have moved, re-opening capture"),await this._setDeviceImpl(x))}async _detectSelectedDeviceRemoved(x){(await yx()).some(r=>r.device.deviceId===x)||this._Capture?.source.mediaStream?.getAudioTracks()[0]?.readyState==="live"||(this._DeviceParameters?.onStatusChanged?.("stopped"),navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._DeviceParameters=void 0,await this._closeImpl())}_enqueue(x){let A=this._Queue.then(x,x);return this._Queue=A.catch(()=>{}),A}get vad(){return this._Vad}get apm(){return this._Apm}get volume(){return this._Volume}get activity(){return this._Capture?.worker.activity??I}get speechProbability(){return this._Capture?.worker.speechProbability??0}get deviceId(){return this._DeviceParameters?.device?.device.deviceId}async start(x,A){let F=this._Medias.get(A.connectionId);F===void 0&&this._Medias.set(A.connectionId,F=new Set),n(`starting audio capture media ${A.mediaId} on connection ${A.connectionId}`),!F.has(A.mediaId)&&(F.add(A.mediaId),x.mainConnection?.id===A.connectionId&&await x.request("StartMedia",{media_id:A.mediaId,properties:{kind:"audio",uid:this.uid,ref:this.#A,customType:this.#x}}).catch(D=>c(`StartMedia got rejected; ${D}`)),this._UpdateMedias().catch(console.error))}async stop(x,A){let F=this._Medias.get(A.connectionId);n(`stopping audio capture media ${A.mediaId} on connection ${A.connectionId}`),F?.delete(A.mediaId)&&(x.mainConnection?.id===A.connectionId&&await x.request("StopMedia",{media_id:A.mediaId}).catch(D=>c(`StopMedia got rejected; ${D}`)),this._UpdateMedias().catch(console.error))}setVad(x){s("updating vad config",x),this._Vad=x,this._Capture&&this._Capture.worker.setVad(x)}async setApm(x){await this._enqueue(()=>this._setApmImpl(x))}async _setApmImpl(x){s("updating apm config",x),this._Apm=x,this._DeviceParameters&&await this._setDeviceImpl(this._DeviceParameters)}async setDevice(x){await this._enqueue(()=>this._setDeviceImpl(x))}async _setDeviceImpl(x){s("updating capture device parameters",x);let A=this._DeviceParameters;if(this._DeviceParameters=x,this._Volume==="muted")return;let F;try{let D=await M0(this.controller,x,{...this._Apm,echoCanceller:this._Monitor?!1:this._Apm.echoCanceller});if(D.type!=="Success"){c(`unable to open capture device; ${D.reason}`),this._DeviceParameters=A;return}F=D.value.source.context,navigator.mediaDevices.addEventListener("devicechange",this._DeviceCb);let r=this._Capture?.source.context;if(this._Capture!==void 0){jx(this._Capture.source.mediaStream);try{this._Capture.source.disconnect(this._Capture.worker.worklet)}catch(e){C("failed to disconnect previous capture source",e)}}this._Capture===void 0||this._Capture.worker.worklet.context!==D.value.source.context?(this._Capture?.worker.close(),this._Capture={worker:await DA(D.value.source.context,this.controller.sink,this.controller.receiveMonitoredPacket.bind(this.controller),new WeakRef(this)),source:D.value.source},await this._UpdateMedias(),this._Capture.worker.setVolume(this._Volume),this.setVad(this.vad)):this._Capture.source=D.value.source,F=void 0,this._Capture.source.connect(this._Capture.worker.worklet),r!==void 0&&await this.controller.audioContexts.release(r),this.#D=Date.now(),x.onStatusChanged?.(D.value.defaulted?"defaulted":"started")}catch(D){throw F!==void 0&&await this.controller.audioContexts.release(F),new Error(`Error in setDevice(); ${D}`,{cause:D})}}async setVolume(x){await this._enqueue(()=>this._setVolumeImpl(x))}async _setVolumeImpl(x){s(`updating capture volume to ${x}`),this._Volume=x,x==="muted"?await this._closeImpl():(!this._Capture&&this._DeviceParameters&&await this._setDeviceImpl(this._DeviceParameters),this._Capture?.worker.setVolume(x))}close(){this._enqueue(()=>this._closeImpl()).catch(console.error)}async _closeImpl(){if(s("closing audio capture"),clearTimeout(this.#F),this.#F=void 0,this._Capture!==void 0){this._Capture.worker.close(),jx(this._Capture.source.mediaStream);try{this._Capture.source.disconnect(this._Capture.worker.worklet)}catch(x){C("failed to disconnect audio node",x)}await this.controller.audioContexts.release(this._Capture.source.context)}navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._Capture=void 0}async dump(){let x=[];for(let[A,F]of this._Medias)x.push(`${A} => ${Array.from(F.values()).join(",")}`);return{uid:this.uid,ref:this.#A??null,customType:this.#x??null,worker:await this._Capture?.worker.dump()??null,vad:this._Vad,apm:this._Apm,volume:this._Volume,medias:x}}async _UpdateMedias(){if(this._Capture!==void 0){let x=Array.from(this._Medias).map(([A,F])=>({id:A,mediaIds:Array.from(F)}));this._Capture.worker.setMedias(x)}}async startLoopback(){this._Monitor===void 0&&(s("starting audio capture loopback"),this.setApm(this._Apm).catch(console.error),this._Monitor=await this.controller.createAudioPlayback({uid:"loopback"}),this._Monitor.start({connectionId:0,mediaId:0}),this._Medias.set(0,new Set([0])),await this._UpdateMedias())}async stopLoopback(){this._Monitor!==void 0&&(s("stopping audio capture loopback"),this._Monitor.close(),this._Monitor=void 0,this.setApm(this._Apm).catch(console.error),this._Medias.delete(0),await this._UpdateMedias())}};var W=require("@4players/odin-common");o();var y=class{constructor(x,A){this.controller=x;this.parameters=A;this.uid=(0,W.generateUUID)()}#x;#A=new Map;#F;get customType(){return this.parameters?.customType}get mediaStream(){return this.#x}get audioCapture(){return this.#F}get volume(){return(0,W.assert)(this.audioCapture,"getting the volume failed, this video has no Audio"),this.audioCapture.volume}async setVolume(x){(0,W.assert)(this.audioCapture,"setVolume() failed, this video has no Audio"),await this.audioCapture.setVolume(x)}get vad(){return(0,W.assert)(this.audioCapture,"getting the vad config failed, this video has no Audio"),this.audioCapture.vad}setVad(x){(0,W.assert)(this.audioCapture,"setVad() failed, this video has no Audio"),this.audioCapture.setVad(x)}async setDevice(x,A={voiceActivity:void 0,volumeGate:void 0}){if(this.#x)throw new Error("This VideoCapture already has a MediaStream.");if(!x.getVideoTracks()[0])throw new Error("Error when calling setDevice(), MediaStream does not contain a VideoStreamTrack!");if(this.#x=x,x.getAudioTracks()[0]){let D={device:await J0(x.getAudioTracks()[0]),vad:A,ref:this.uid};this.#F=await this.controller.createAudioCapture(D)}}async start(x,A){let F=this.#A.get(A.connectionId);if(F===void 0&&this.#A.set(A.connectionId,F=new Set),!F.has(A.mediaId)&&(F.add(A.mediaId),x.mainConnection?.id===A.connectionId)){let D={kind:"video",codec:this.parameters?.codec??E.DefaultVideoCodec,ref:this.#F?.uid,uid:this.uid};this.parameters?.customType&&(D.customType=this.parameters.customType),await x.request("StartMedia",{media_id:A.mediaId,properties:D}).catch(r=>c(`StartMedia got rejected; ${r}`))}}async stop(x,A){this.#x&&jx(this.#x),this.#A.get(A.connectionId)?.delete(A.mediaId)&&x.mainConnection?.id===A.connectionId&&await x.request("StopMedia",{media_id:A.mediaId}).catch(D=>c(`StopMedia got rejected; ${D}`))}async dump(){let x=[];for(let[A,F]of this.#A)x.push(`${A} => ${Array.from(F.values()).join(",")}`);return{uid:this.uid,ref:this.#F?.uid??null,customType:this.customType??null,tracks:this.#x?.getVideoTracks().map(A=>({id:A.id,kind:A.kind,label:A.label,ready:A.readyState,muted:A.muted,settings:{...A.getSettings()}}))??[],volume:this.#F?.volume??0,medias:x}}close(){this.#x&&jx(this.#x),this.audioCapture?.close(),this.#F=void 0}};var pF=require("@4players/odin-common");o();var P=class{constructor(x,A,F){this.controller=x;this.uid=A;this.customType=F}get volume(){return this.controller.playbackGetVolume(this.uid)}get activity(){return this.controller.playbackGetActivity(this.uid)}get jitterStats(){return this.controller.playbackGetJitterStats(this.uid)}start(x){n(`starting audio playback media ${x.mediaId} on connection ${x.connectionId}`),this.controller.playbackStart(this.uid,x)}stop(x){n(`stopping audio playback media ${x.mediaId} on connection ${x.connectionId}`),this.controller.playbackStop(this.uid,x)}setVolume(x){s(`updating audio playback media '${this.uid}' volume to ${x}`),this.controller.playbackSetVolume(this.uid,x)}close(){s(`closing audio playback media '${this.uid}'`),this.controller.closePlayback(this.uid)}};function hF(t,x){let A=t.audioContext;if(typeof A.setSinkId=="function"){t.connectOutput(A.destination);let F,D=()=>{if(A.state==="running"&&F!==void 0){let r=F;F=void 0,A.setSinkId(r).catch(e=>C("failed to apply deferred sinkId",e))}};return A.addEventListener("statechange",D),{async setSinkId(r){if(A.state!=="running"){F=r;return}await A.setSinkId(r)},dispose(){A.removeEventListener("statechange",D)}}}if(x&&typeof document<"u"&&typeof HTMLAudioElement<"u"&&typeof HTMLAudioElement.prototype.setSinkId=="function"){let F=A.createMediaStreamDestination();t.connectOutput(F);let D=new Audio;D.srcObject=F.stream,D.muted=!1,D.volume=1;let r=!1,e=!1,j={once:!0,passive:!0,capture:!0},B=()=>{e=!1,u()},f=()=>{e||r||(e=!0,document.addEventListener("pointerdown",B,j),document.addEventListener("keydown",B,j))},a=()=>{e&&(e=!1,document.removeEventListener("pointerdown",B,!0),document.removeEventListener("keydown",B,!0))},u=()=>{r||D.play().catch(_=>{r||(_ instanceof DOMException&&_.name==="NotAllowedError"?f():C("failed to start playback audio element",_))})},Z=()=>{A.state==="running"&&D.paused&&u()};return A.addEventListener("statechange",Z),u(),{async setSinkId(_){await D.setSinkId(_)},dispose(){r=!0,a(),A.removeEventListener("statechange",Z),D.pause(),D.srcObject=null,D.removeAttribute("src");try{D.load()}catch{}F.disconnect()}}}return t.connectOutput(A.destination),{async setSinkId(){},dispose(){}}}var Nx=class{constructor(x){this.audioContextFactory=x;this.entries=[];this._acquireStrand=new T.Strand}acquire(x){return this._acquireStrand.enqueue(async()=>{for(let D of this.entries)if(D.sampleRate===x||D.sampleRate===void 0&&D.audioContext.sampleRate===x)return D.references+=1,D.audioContext;let A=await this.audioContextFactory(x),F=this.entries.find(D=>D.audioContext.sampleRate===A.sampleRate);return F?(F.references+=1,A.close().catch(()=>{}),F.audioContext):(this.entries.push({sampleRate:x,audioContext:A,references:1}),A)})}async release(x){let A=this.entries.findIndex(F=>F.audioContext===x);if(!(A<0)&&(this.entries[A].references-=1,this.entries[A].references<=0)){let F=this.entries[A].audioContext;this.entries.splice(A,1),await F.close()}}close(){for(let x of this.entries.splice(0))x.audioContext.close().catch(()=>{})}},Px=class t{constructor(x,A,F=!1){this.audioContexts=x;this.sink=A;this.enableHTMLAudioElementFallback=F;this.audioCaptures=[];this.videoCaptures=[];this.globalVolume=[1,1];this.playbacks=new Map;this.setPlaybackStrand=new T.Strand}async create(x,A){return new t(x,A)}receivePacket(x,A){this.playbackWorker?.receivePacket(x,A)}receiveMonitoredPacket(x,A){let F=A.slice();this.receivePacket(x,F)}async createAudioPlayback(x){let A=this.playbacks.get(x.uid),F=x.volume;if(A===void 0){F=F??[1,1];let D=new P(this,x.uid,x.customType);A={id:void 0,volume:F,playback:D},this.playbacks.set(x.uid,A)}return F!==void 0&&A.playback.setVolume(F),A.playback}async createAudioCapture(x){let A=new S(this,x);return await A.setDevice(x),this.audioCaptures.push(new WeakRef(A)),A}async createVideoCapture(x,A){let F=new y(this,A);return await F.setDevice(x),this.videoCaptures.push(new WeakRef(F)),F}playbackSetDevice(x){return this.setPlaybackStrand.enqueue(async()=>{let A=x?.device.deviceId??"";if(A==="default"&&(A=""),this.playbackWorker===void 0){let F=await this.audioContexts.acquire(48e3);this.playbackWorker=await rA(F),this.playbackSink=hF(this.playbackWorker,this.enableHTMLAudioElementFallback),this.playbackWorker.setGlobalVolume(this.globalVolume);for(let[,D]of this.playbacks)D.id!==void 0&&this.playbackWorker.addMedias(D.id.connectionId,[D.id.mediaId],D.volume)}if(x&&this.playbackSink!==void 0)try{await this.playbackSink.setSinkId(A)}catch(F){C("failed to set playback sink",F)}})}playbackSetGlobalVolume(x){this.globalVolume=x,this.playbackWorker?.setGlobalVolume(this.globalVolume)}playbackStart(x,A){let F=this.playbacks.get(x);F!==void 0&&(F.id!==void 0&&this.playbackStop(x,F.id),F.id=A,this.playbackWorker?.addMedias(A.connectionId,[A.mediaId],F.volume))}playbackStop(x,A){let F=this.playbacks.get(x);F!==void 0&&(F.id!==A&&C(`playback media ${A.mediaId} on connection ${A.connectionId} is out of sync`,F.id,A),F.id=void 0,this.playbackWorker?.removeMedias(A.connectionId,[A.mediaId]))}playbackGetActivity(x){let A=this.playbacks.get(x);return A?.id===void 0?I:this.playbackWorker?.getActivity(A.id)??I}playbackGetJitterStats(x){let A=this.playbacks.get(x);return A?.id===void 0?T.JITTER_STATS_INITIAL:this.playbackWorker?.getJitterStats(A.id)??T.JITTER_STATS_INITIAL}playbackSetVolume(x,A){let F=this.playbacks.get(x);F!==void 0&&(F.volume=A,F.id!==void 0&&this.playbackWorker?.setVolume(F.id,F.volume))}playbackGetVolume(x){return this.playbacks.get(x)?.volume??[1,1]}closePlayback(x){let A=this.playbacks.get(x);A!==void 0&&(A.id!==void 0&&this.playbackStop(x,A.id),this.playbacks.delete(x))}close(){this.playbackSink?.dispose(),this.playbackSink=void 0,this.playbackWorker?.close(),this.audioContexts.close()}async dump(){let x=[];for(let D of this.audioCaptures){let r=D.deref();r!==void 0&&x.push(await r.dump())}let A=[];for(let D of this.videoCaptures){let r=D.deref();r!==void 0&&A.push(await r.dump())}let F=[];for(let[D,r]of this.playbacks)F.push({uid:D,id:r.id||null,volume:r.volume});return{globalVolume:this.globalVolume,playbackWorker:await this.playbackWorker?.dump()||null,audioCaptures:x,videoCaptures:A,playbacks:F}}},ex=class{constructor(x,A=!1){this.device=x;this.isDefault=A}get type(){switch(this.device.kind){case"audioinput":return"AudioCapture";case"track":return"AudioCapture";case"audiooutput":return"AudioPlayback";default:(0,T.assert)(!1,"not supported device")}}get id(){return this.device.deviceId}get name(){return this.device.name}};var cx=require("@4players/odin-common"),CA=require("@msgpack/msgpack");o();var _F=require("@4players/odin-common");o();var $=require("@4players/odin-common"),z=require("@4players/odin-common/api");o();var Fx=class{constructor(x){this._Status=x;this._Listeners=new Set}get status(){return this._Status}set(x,A){if(!(x===this._Status||this._Status==="Closed")){this._Status=x;for(let F of[...this._Listeners])F(x,A)}}listen(x,A){A.aborted||(this._Listeners.add(x),A.addEventListener("abort",()=>this._Listeners.delete(x),{once:!0}))}};var X=require("@4players/odin-common"),Dx=require("@4players/odin-common/api"),Lx=require("@msgpack/msgpack");o();var Q=class{constructor(x){this.stream=x;this._SendQueue=[];this._RecvQueue=[];this._EventQueue=[];this._Requests=new Map;this._Close=new AbortController;this._NextId=1;x instanceof WebSocket?(x.addEventListener("open",this._OnWebSocketOpen.bind(this)),x.addEventListener("close",this.close.bind(this)),x.addEventListener("message",A=>this._OnRpcMessage(A.data)),x.binaryType="arraybuffer"):(qF(x.readable.getReader(),this._OnRpcMessage.bind(this)).catch(A=>C("rpc stream reader failed",A)).finally(this.close.bind(this)),this._Writer=x.writable.getWriter()),this._Close.signal.addEventListener("abort",this._Cleanup.bind(this),{once:!0})}get closed(){return this._Close.signal.aborted}get closeSignal(){return this._Close.signal}async request(x,A,F){if(this.closed)return Promise.resolve("closed");let D=this._NextId,r=F===void 0?void 0:setTimeout(()=>this._TimeoutRequest(D),F);return this._Send([0,D,x,A]),new Promise(e=>{this._Requests.set(D,{accept:e,timeoutId:r}),this._NextId+=1})}notify(x,A){this.closed||this._Send([2,x,A])}recv(){if(this.closed)return Promise.resolve("closed");let x=this._EventQueue.shift();return x!==void 0?Promise.resolve(x):new Promise(A=>this._RecvQueue.push(A))}close(){this._Close.abort()}_TimeoutRequest(x){let A=this._Requests.get(x);A!==void 0&&(this._Requests.delete(x),clearTimeout(A.timeoutId),A.accept("timeout"))}_Send(x){let A;x instanceof Uint8Array?A=x:A=new Uint8Array((0,Lx.encode)(x,{ignoreUndefined:!0,forceFloat32:!0})),this.stream instanceof WebSocket?this.stream.send(A):this._Writer.write(A).catch(()=>{})}_OnWebSocketOpen(x){for(let A of this._SendQueue)this._Send(A);this._SendQueue.length=0}_OnRpcMessage(x){let A=mF(x);if(A.type!=="Success"){this.close();return}switch(A.value[0]){case 0:this._Send([1,A.value[1],"not supported",null]);break;case 1:this._OnResponse(A.value[1],A.value[2],A.value[3]);break;case 2:this._OnEvent(A.value[1],A.value[2]);break}}_OnResponse(x,A,F){let D=this._Requests.get(x);D!==void 0&&(clearTimeout(D.timeoutId),D.accept(A===null?(0,X.success)(F):(0,X.failure)(A)))}_OnEvent(x,A){let F=this._RecvQueue.shift();F!==void 0?F({name:x,properties:A}):this._EventQueue.push({name:x,properties:A})}_Cleanup(){for(let x of this._Requests.values())clearTimeout(x.timeoutId),x.accept("closed");this._Requests.clear();for(let x of this._RecvQueue)x("closed");this._RecvQueue.length=0,this._SendQueue.length=0,this.stream instanceof WebSocket?this.stream.close():this._Writer?.close().catch(()=>{})}},rx=class{constructor(x,A,F){this.rpc=x;this._Commands=A;this._Events=F}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(x,A,F){A=(0,Dx.parseRequest)(x,A,this._Commands);let D=await this.rpc.request(x,A,F);if(D==="closed"||D==="timeout"||D.type==="Failure")return D;let r=(0,Dx.parseResponse)(x,D.value,this._Commands);return r!==void 0?(0,X.success)(r):(0,X.failure)("response schema failed validation")}notify(x,A){A=(0,Dx.parseRequest)(x,A,this._Commands),this.rpc.notify(x,A)}async recv(){let x=await this.rpc.recv();if(x==="closed")return x;let A=b0(this._Events,x);return A!==void 0?A:(tA(this._Events,x.name)?(c(`schema validation for ${x.name} failed; closing connection`),this.rpc.close()):C(`dropping unknown event ${x.name}`),"closed")}close(){this.rpc.close()}};function mF(t){try{return(0,X.success)(Dx.MessagePackRpcSchema.parse((0,Lx.decode)(new Uint8Array(t))))}catch(x){return(0,X.failure)(String(x))}}function b0(t,x){if(!tA(t,x.name))return;let A=t[x.name].safeParse(x.properties);if(A.success)return{name:x.name,properties:A.data}}function tA(t,x){return x in t}async function qF(t,x){let A=new Uint8Array;for(;;){let F=P0(A,0);if(F===v){t.cancel("protocol violation").catch(()=>{});break}if(F!==q&&F<=A.length){x(A.subarray(0,F)),A=A.subarray(F);continue}let D;try{D=await t.read()}catch{break}if(D.done)break;A=GF(A,D.value)}A.length>0&&C("unprocessed bytes left in rpc stream",A)}function GF(t,x){if(t.length===0)return x;if(x.length===0)return t;let A=new Uint8Array(t.length+x.length);return A.set(t,0),A.set(x,t.length),A}var M=require("@4players/odin-common"),eA=require("@4players/odin-common/api");o();var g=class t{constructor(x,A){this.text=x;this.claims=A;if(A.ups!==void 0){let F=t.parse(A.ups);F.type==="Success"?this._Upstream=F.value:c(`upstream in token can not be parsed; ${F.reason}`)}}static parse(x){let A=x.split(".");if(A.length!==3)return(0,M.failure)("expected three segments");let F=(0,M.fromBase64Url)(A[1]);if(F.type==="Failure")return(0,M.failure)(`invalid token; ${F.reason}`);let D;try{D=JSON.parse(F.value)}catch(e){return(0,M.failure)(`invalid token; ${e}`)}let r=eA.TokenClaimsSchema.safeParse(D);return r.success===!1?(0,M.failure)(`invalid token; ${r.error}`):(0,M.success)(new t(x,r.data))}get timeLeft(){return this.claims.exp===void 0?1/0:this.claims.exp*1e3-Date.now()}get upstream(){return this._Upstream}get defaultRoomId(){return Array.isArray(this.claims.rid)?this.claims.rid.length===1?this.claims.rid[0]:void 0:this.claims.rid}hasAudience(x){return this.claims.aud===void 0&&x==="gateway"?!0:Array.isArray(this.claims.aud)?this.claims.aud.includes(x):this.claims.aud===x}toString(){return this.text}};var fx=require("@4players/odin-common");o();function jA(t){typeof globalThis.rtcDataChannels>"u"&&(globalThis.rtcDataChannels=[]),Array.isArray(globalThis.rtcDataChannels)&&globalThis.rtcDataChannels.length<=100&&globalThis.rtcDataChannels.push(t)}function BA(t){let x=globalThis.rtcDataChannels?.indexOf(t);x!==void 0&&x>=0&&globalThis.rtcDataChannels.splice(x,1),t.readyState!=="closed"&&t.close()}function Ox(t){typeof globalThis.rtcPeerConnections>"u"&&(globalThis.rtcPeerConnections=[]),Array.isArray(globalThis.rtcPeerConnections)&&globalThis.rtcPeerConnections.length<=100&&globalThis.rtcPeerConnections.push(t)}function Hx(t){let x=globalThis.rtcPeerConnections?.indexOf(t);x!==void 0&&x>=0&&globalThis.rtcPeerConnections.splice(x,1),t.connectionState!=="closed"&&t.close()}var sx=class{constructor(x,A,F){this._localVideos=new Map;this._remoteVideos=new Map;this._freeLocalVideoTransceivers=[];this._startingLocalVideos=new Map;this._closed=!1;this._negotiationRequested=!1;this._negotiationRunning=!1;this._negotiationCounter=0;this._pendingRemoteCandidates=[];this._WebRtcStatsSnapshot=null;this._peerConnection=x,this._signaling=A,this._answerTimeout=F?.answerTimeout??E.WebRtcAnswerTimeout,this._maxNegotiationAttempts=F?.maxNegotiationAttempts??E.WebRtcMaxNegotiationAttempts,this._negotiationCounter=F?.firstNegotiationId??0,this._peerConnection.ontrack=this._onTrack.bind(this),this._peerConnection.onconnectionstatechange=()=>this._onStatusChanged(),this._peerConnection.onicecandidate=D=>{(D.candidate?this._signaling.sendIceCandidate(D.candidate):this._signaling.sendIceComplete()).catch(e=>{C("failed to send local ice candidate",e)})},this._WebRtcStatsInterval=setInterval(()=>{this._snapshotStats().catch(()=>{})},E.WebRtcStatsSnapshotInterval)}requestNegotiation(){this._closed||(this._negotiationRequested=!0,!this._negotiationRunning&&(this._negotiationRunning=!0,setTimeout(async()=>{let x=0;for(;this._negotiationRequested&&!this._closed;){this._negotiationRequested=!1;try{await this._negotiate(),x=0}catch(A){if(this._closed)break;if(x+=1,c(`negotiation failed during sdp offer/answer exchange (attempt ${x})`,A),x<this._maxNegotiationAttempts)this._negotiationRequested=!0;else{this._negotiationRunning=!1,this._signaling.closeConnection("negotiation gave up").catch(()=>{});return}}}this._negotiationRunning=!1})))}startLocalVideo(x,A,F){if(this._localVideos.has(x))return Promise.resolve();let D=this._startingLocalVideos.get(x);if(D)return D;let r=this._startLocalVideo(x,A,F).finally(()=>this._startingLocalVideos.delete(x));return this._startingLocalVideos.set(x,r),r}async _startLocalVideo(x,A,F){n(`starting local video for media ${x}`);let D=F?.transform,r=this._freeLocalVideoTransceivers.pop();if(r){try{D?.attach(r.sender)}catch(a){throw this._freeLocalVideoTransceivers.push(r),a}await r.sender.replaceTrack(A),r.direction="sendonly"}else{r=this._peerConnection.addTransceiver(A,{direction:"sendonly"});try{D?.attach(r.sender)}catch(a){throw r.direction="inactive",r.sender.replaceTrack(null).catch(()=>{}),this._freeLocalVideoTransceivers.push(r),a}}let{transform:e,...j}=F??{};if(F&&(!D||Object.keys(j).length>0)){let a=r.sender.getParameters(),{maxBitrate:u,maxFramerate:Z,scaleResolutionDownBy:_}=F,px={...u!==void 0&&{maxBitrate:u},...Z!==void 0&&{maxFramerate:Z},..._!==void 0&&{scaleResolutionDownBy:_}};if(a.encodings.length===0)a.encodings.push(px);else for(let _A of a.encodings)Object.assign(_A,px);F.degradationPreference&&(a.degradationPreference=F.degradationPreference),await r.sender.setParameters(a)}let f=new fx.VideoCodec(F?.codec??E.DefaultVideoCodec).isSupported();f&&r.setCodecPreferences([f]),this._localVideos.set(x,{transceiver:r,transform:D}),this.requestNegotiation()}stopLocalVideo(x){let A=this._localVideos.get(x);A&&(n(`stopping local video for media ${x}`),this._localVideos.delete(x),A.transceiver.sender.track&&(A.transceiver.sender.track.enabled=!1),A.transceiver.direction="inactive",A.transceiver.sender.replaceTrack(null).catch(()=>{}),A.transform?.detach(),this._freeLocalVideoTransceivers.push(A.transceiver),this.requestNegotiation())}startRemoteVideo(x,A){let F=this._remoteVideos.get(x);if(F)return F.track;n(`starting remote video for media ${x}`);let D=this._peerConnection.addTransceiver("video",{direction:"recvonly"});A?.attach(D.receiver);let r,e=new Promise((j,B)=>{r={resolve:j,reject:B}});return e.catch(()=>{}),(0,fx.assert)(r!==void 0,"promise executor must run synchronously"),this._remoteVideos.set(x,{state:"Requested",transceiver:D,transform:A,promise:r,track:e}),this.requestNegotiation(),e}stopRemoteVideo(x){let A=this._remoteVideos.get(x);if(A){n(`stopping remote video for media ${x}`),this._remoteVideos.delete(x),A.state!=="Active"&&A.promise.reject(new Error("video stopped")),A.transform?.detach();try{A.transceiver.direction="inactive"}catch{}this.requestNegotiation()}}async handleWebRtcUpdate(x){if(!this._closed)try{switch(x.kind){case"Sdp":await this._updateRemoteSdp(x.type==="Answer"?"answer":"offer",x.sdp,x.media_map,x.negotiation_id);break;case"Trickle":this._addIceCandidate({candidate:x.candidate,sdpMid:x.spd_mid??void 0,sdpMLineIndex:x.spd_mline_index??void 0,usernameFragment:x.username_fragment??void 0});break;case"TrickleFinished":this._addIceCandidate(void 0);break}}catch(A){c("failed to handle webrtc update",A,x)}}startup(){this._peerConnection.connectionState==="new"&&this.requestNegotiation()}cleanup(){this._closed=!0,this._peerConnection.ontrack=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onicecandidate=null;for(let[,x]of this._remoteVideos)x.state!=="Active"&&x.promise.reject(new Error("connection closed"));this._pendingAnswer?.reject(new Error("connection closed")),this._pendingRemoteCandidates.length=0,clearTimeout(this._WebRtcIceTimeout),clearTimeout(this._WebRtcTimeout),clearInterval(this._WebRtcStatsInterval);for(let x of this._localVideos.values())x.transform?.detach();for(let x of this._remoteVideos.values())x.transform?.detach();this._localVideos.clear(),this._remoteVideos.clear(),this._startingLocalVideos.clear(),this._freeLocalVideoTransceivers.length=0}get stats(){return this._WebRtcStatsSnapshot}get peerConnection(){return this._peerConnection}get negotiationCounter(){return this._negotiationCounter}get localVideos(){return this._localVideos}get remoteVideos(){return this._remoteVideos}get isConnected(){return this._peerConnection.connectionState==="connected"}get isNegotiating(){return this._negotiationRunning}async _snapshotStats(){try{let x=await this._peerConnection.getStats(),A={},F={bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,rtt:0};x.forEach(D=>{let{type:r,...e}=D;r!=="certificate"&&(r==="candidate-pair"&&D.nominated&&(F.bytesSent+=D.bytesSent??0,F.bytesReceived+=D.bytesReceived??0,F.packetsSent+=D.packetsSent??0,F.packetsReceived+=D.packetsReceived??0,F.rtt=D.currentRoundTripTime??0),A[r]||(A[r]=[]),A[r].push(e))}),this._WebRtcStatsSnapshot={timestamp:Date.now(),status:this._peerConnection.connectionState,stats:F,report:A}}catch{}}_addIceCandidate(x){if(x&&(x.sdpMid===void 0&&x.sdpMLineIndex===void 0&&(x={...x,sdpMid:"0"}),s(`adding new ice ${x.candidate}`,x)),this._peerConnection.remoteDescription===null){this._pendingRemoteCandidates.push(x);return}this._applyIceCandidate(x)}_applyIceCandidate(x){this._peerConnection.addIceCandidate(x).catch(A=>{C("failed to add remote ice candidate",A,x)})}_flushPendingIceCandidates(){let x=this._pendingRemoteCandidates.splice(0);for(let A of x)this._applyIceCandidate(A)}async _negotiate(){let x=++this._negotiationCounter,A=await this._peerConnection.createOffer();(0,fx.assert)(A.type==="offer"&&A.sdp,"generated broken payload"),await this._peerConnection.setLocalDescription(A);let F=[];for(let[r,{transceiver:e}]of this._localVideos)e.mid&&F.push([r,e.mid]);for(let[r,e]of this._remoteVideos)e.state!=="Active"&&e.transceiver.mid&&F.push([r,e.transceiver.mid]);let D=new Promise((r,e)=>{this._pendingAnswer={negotiationId:x,resolve:r,reject:e}});D.catch(()=>{});try{await yF((async()=>{await this._signaling.sendOffer(A.sdp,F,x),await D})(),this._answerTimeout,`timed out waiting for answer to offer ${x}`)}finally{this._pendingAnswer=void 0}}async _updateRemoteSdp(x,A,F,D){if(x==="offer"){C("ignoring unexpected sdp offer from server");return}let r=this._pendingAnswer;if(r===void 0){C("ignoring sdp answer without pending negotiation");return}if(D!==void 0&&D!==r.negotiationId){C(`ignoring stale sdp answer for negotiation ${D}; current is ${r.negotiationId}`);return}if(this._peerConnection.signalingState!=="have-local-offer"){C(`ignoring sdp answer in signaling state ${this._peerConnection.signalingState}`);return}for(let[e,j]of F){let B=this._remoteVideos.get(e);B?.state==="Requested"&&(this._remoteVideos.set(e,{state:"Mapped",transceiver:B.transceiver,transform:B.transform,mid:j,promise:B.promise,track:B.track}),s(`updated remote video list with media ${e}`,B,this._remoteVideos))}try{await this._peerConnection.setRemoteDescription({type:x,sdp:A})}catch(e){r.reject(e);return}this._flushPendingIceCandidates(),r.resolve()}async _onStatusChanged(){switch(s(`peer connection state changed to ${this._peerConnection.connectionState}`),this._peerConnection.connectionState){case"closed":break;case"connected":clearTimeout(this._WebRtcIceTimeout),this._WebRtcIceTimeout=void 0,clearTimeout(this._WebRtcTimeout),this._WebRtcTimeout=void 0,this._signaling.onConnected?.();break;case"failed":this._peerConnection.restartIce(),this.requestNegotiation();case"disconnected":E.MainConnectionPingInterval!==void 0&&await this._signaling.checkConnection();default:this._WebRtcIceTimeout===void 0&&(this._WebRtcIceTimeout=setTimeout(()=>{s("ice connection timeout was reached"),this._peerConnection.restartIce(),this.requestNegotiation(),this._WebRtcIceTimeout=void 0},E.WebRtcIceTimeout)),this._WebRtcTimeout===void 0&&(this._WebRtcTimeout=setTimeout(async()=>{s("peer connection timeout was reached"),await this._signaling.closeConnection("peer connection timeout")},E.WebRtcTimeout));break}}_onTrack(x){let A=Array.from(this._remoteVideos).find(([,r])=>r.state==="Mapped"&&r.mid===x.transceiver.mid);if(!A){C(`unexpected track with mid: ${x.transceiver.mid}`);return}let[F,D]=A;(0,fx.assert)(D.state==="Mapped","expected video state to be Mapped"),this._remoteVideos.set(F,{state:"Active",transceiver:x.transceiver,transform:D.transform,track:D.track}),s(`updated local video list with media ${F}`,A,x.transceiver,this._localVideos),x.track.onended=()=>{s(`video track with mid ${x.transceiver.mid} ended`,A)},D.promise.resolve(x.track)}};function yF(t,x,A){return new Promise((F,D)=>{let r=setTimeout(()=>D(new Error(A)),x);t.then(e=>{clearTimeout(r),F(e)},e=>{clearTimeout(r),D(e)})})}o();var ix=class{constructor(x,A){this.host=x;this.delays=A;this._LocalVideos=new Map;this._RemoteVideos=new Map;this._Attempt=0}async startLocalVideo(x,A,F){this._LocalVideos.set(x,{track:A,options:F}),await(await this._Session()).startLocalVideo(x,A,F)}stopLocalVideo(x){this._LocalVideos.delete(x),this.host.currentSession()?.stopLocalVideo(x),this._ForgetAttemptsIfIdle()}startRemoteVideo(x,A){let F=this._RemoteVideos.get(x);if(F)return F.first;let D,r=new Promise((j,B)=>{D={resolve:j,reject:B}});r.catch(()=>{});let e={stream:new MediaStream,first:r,transform:A,settle:D};return this._RemoteVideos.set(x,e),this._Session().then(j=>this._RequestRemoteVideo(j,x)).catch(j=>{C(`failed to request remote video for media ${x}`,j)}),r}stopRemoteVideo(x){let A=this._RemoteVideos.get(x);A!==void 0&&(this._RemoteVideos.delete(x),A.settle?.reject(new Error("video stopped")),A.settle=void 0,this.host.currentSession()?.stopRemoteVideo(x),this._ForgetAttemptsIfIdle())}sessionConnected(){this._Attempt=0}sessionFailed(x){this.host.recycleSession(x),this._Schedule()}sessionReplaced(){clearTimeout(this._Timer),this._Timer=void 0,this._Recover().catch(x=>{C("replaying webrtc video onto the replaced session failed",x)})}giveUp(x){this._RejectPending(new Error(x))}close(){clearTimeout(this._Timer),this._Timer=void 0,this._RejectPending(new Error("connection closed")),this._LocalVideos.clear(),this._RemoteVideos.clear(),this.host.recycleSession("connection closed")}dump(){return{attempt:this._Attempt,scheduled:this._Timer!==void 0,localVideos:[...this._LocalVideos.keys()],remoteVideos:[...this._RemoteVideos.keys()]}}async _Session(){return this.host.currentSession()===void 0&&this._Timer===void 0&&(this._Attempt=0),this.host.ensureSession()}_Schedule(){if(this.host.isClosed()||this._Timer!==void 0||this._LocalVideos.size===0&&this._RemoteVideos.size===0)return;let x=this.delays[this._Attempt];if(x===void 0){C(`giving up on webrtc video after ${this._Attempt} recovery attempts; audio stays connected`),this._RejectPending(new Error("video recovery gave up"));return}this._Attempt+=1,n(`recovering webrtc video in ${x}ms (attempt ${this._Attempt} of ${this.delays.length})`),this._Timer=setTimeout(()=>{this._Timer=void 0,this._Recover().catch(A=>{C("webrtc video recovery failed",A),this.sessionFailed("recovery failed")})},x)}async _Recover(){if(this.host.isClosed()||this._LocalVideos.size===0&&this._RemoteVideos.size===0)return;let x=await this.host.ensureSession();for(let[A,{track:F,options:D}]of this._LocalVideos){if(F.readyState==="ended"){this._LocalVideos.delete(A);continue}x.startLocalVideo(A,F,D).catch(r=>{C(`failed to republish local video for media ${A}`,r)})}for(let A of this._RemoteVideos.keys())this._RequestRemoteVideo(x,A)}_RequestRemoteVideo(x,A){let F=this._RemoteVideos.get(A);F!==void 0&&x.startRemoteVideo(A,F.transform).then(D=>{if(this._RemoteVideos.get(A)===F){for(let r of F.stream.getVideoTracks())F.stream.removeTrack(r);F.stream.addTrack(D),F.settle?.resolve(F.stream),F.settle=void 0}}).catch(D=>{s(`remote video for media ${A} did not arrive`,D)})}_RejectPending(x){for(let A of this._RemoteVideos.values())A.settle?.reject(x),A.settle=void 0}_ForgetAttemptsIfIdle(){this._LocalVideos.size>0||this._RemoteVideos.size>0||(clearTimeout(this._Timer),this._Timer=void 0,this._Attempt=0)}};var wx=class t{constructor(x,A,F,D,r,e,j){this.id=x;this.address=A;this.connection=D;this.datagramWritable=r;this.rpc=e;this.closeController=j;this._ConnectionStats={...$.CONNECTION_STATS_INITIAL};this._WebRtcUpdatesRunning=!1;this._NegotiationCounter=0;this._WebRtcSessionFlight=new Y;this._VideoRecovery=new ix({ensureSession:()=>this._EnsureWebRtcSession(),currentSession:()=>this._WebRtcSession,recycleSession:x=>this._RecycleWebRtcSession(x),isClosed:()=>this.closed},E.WebRtcRecoveryDelays);this._PingFlight=new Y;this._DatagramStatus=new Fx("Open");this._ClosePromise=(async()=>{try{await this.connection.closed}catch{}return"closed"})(),E.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(E.HealthCheckTimeout)},E.MainConnectionPingInterval)),j.signal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this.datagramWriter=r.getWriter(),this.connection.closed.catch(()=>{}).finally(()=>{this.closeController.abort("transport closed")}),this.readDatagrams(this.connection,this.id,(B,f)=>{this._ConnectionStats.packetsReceived+=1,F(B,f)}).catch(()=>{})}static async create(x,A,F,D){try{let r=new URL(`https://${A}?version=${O0}&uid=${ux}`),e=new AbortController;D.addEventListener("abort",()=>e.abort(),{once:!0});let j=new WebTransport(r);e.signal.addEventListener("abort",()=>{try{j.close()}catch{}},{once:!0}),await j.ready;let B=j.datagrams,f=B?.createWritable?.()??B?.writable;if(!f)return e.abort(),(0,$.failure)(`connecting to ${A} failed because WebTransport datagrams are not supported by this browser`);let a=await j.createBidirectionalStream(),u=new rx(new Q(a),z.MainCommandsRpc,z.MainNotificationsRpc);return e.signal.addEventListener("abort",()=>u.close(),{once:!0}),u.notify("Hello",{stream:"main"}),(0,$.success)(new t(x,A,F,j,f,u,e))}catch(r){return(0,$.failure)(`connecting to ${A} failed with ${r}`)}}get datagramStatus(){return this._DatagramStatus.status}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}onDatagramStatusChanged(x,A){this._DatagramStatus.listen(x,A)}close(){n(`closing connection to '${this.address}' with id ${this.id}`),this.closeController.abort("request")}async joinRoom(x,A,F,D){try{if(this.closed)return"closed";let r=await this.connection.createBidirectionalStream().catch(()=>"closed");if(r==="closed")return"closed";let e=new rx(new Q(r),z.RoomCommandsRpc,z.RoomNotificationsRpc),j=await e.request("Hello",{stream:"room",token:String(x),room_id:A,user_data:F,position:D});return j==="closed"||j.type==="Failure"?j:(0,$.success)(e.rpc)}catch(r){return(0,$.failure)(`JoinRoom failed; ${r}`)}}async getReconnectToken(x){let A=await this._Request("RequestReconnectToken",{peer_id:x});return A.type==="Failure"?A:g.parse(A.value)}async getRtcStats(){return this._PeerConnection?.getStats()}async healthCheck(){let x=await this._RequestPing(E.HealthCheckTimeout);return x||this.close(),x}async ping(x=3e4){let A=Date.now();return await this._RequestPing(x)?Date.now()-A:0}sendDatagram(x){if(!this.closed)try{this.datagramWriter.write(x).catch(()=>{}),this._ConnectionStats.packetsSent+=1;let A=x.byteLength;this.connectionStats.bytesSent+=A}catch{}}async readDatagrams(x,A,F){try{let D=x.datagrams.readable.getReader();for(;;){let r=await D.read();if(r.done)break;let e=r.value.byteLength;this.connectionStats.bytesReceived+=e,F(A,r.value)}}catch{}}_CleanUp(){s(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId),this._DatagramStatus.set("Closed"),this._VideoRecovery.close()}_RecycleWebRtcSession(x){let A=this._WebRtcSession,F=this._PeerConnection;A===void 0&&F===void 0||(C(`recycling webrtc session of connection ${this.id}; ${x}`),this._WebRtcSession=void 0,this._PeerConnection=void 0,A&&(this._NegotiationCounter=A.negotiationCounter,A.cleanup()),F&&Hx(F))}async _EnsureWebRtcSession(){return this._WebRtcSession?this._WebRtcSession:this._WebRtcSessionFlight.run(async()=>{this._PeerConnection=new RTCPeerConnection,Ox(this._PeerConnection);let x=this._PeerConnection;return this._WebRtcSession=new sx(x,{sendOffer:async(A,F,D)=>{let r=await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:A,media_map:F,negotiation_id:D});if(r.type==="Failure")throw new Error(`failed to send sdp offer; ${r.reason}`)},sendIceCandidate:async A=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:A.candidate,spd_mid:A.sdpMid??void 0,spd_mline_index:A.sdpMLineIndex??void 0,username_fragment:A.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async A=>{this._PeerConnection===x&&this._VideoRecovery.sessionFailed(A)},onConnected:()=>{this._PeerConnection===x&&this._VideoRecovery.sessionConnected()},checkConnection:async()=>{}},{firstNegotiationId:this._NegotiationCounter}),this._HandleWebRtcUpdates().catch(A=>C("webrtc update loop failed",A)),this._WebRtcSession})}async _HandleWebRtcUpdates(){if(!this._WebRtcUpdatesRunning){for(this._WebRtcUpdatesRunning=!0;;){let x=await this.rpc.recv();if(x==="closed")break;x.name==="WebRtcUpdate"&&this._WebRtcSession?.handleWebRtcUpdate(x.properties).catch(()=>{})}this.close()}}async _Request(x,A,F){let D=Date.now(),r=await(F===void 0?this.rpc.request(x,A):this.rpc.request(x,A,F)),e=(Date.now()-D)/1e3;return x!=="Ping"&&s(`sent main rpc '${x}'; took: ${e}s`,{properties:A,timeout:F,result:r}),r==="closed"?(0,$.failure)("connection lost"):r}_RequestPing(x=3e4){return this._PingFlight.run(async()=>{let A=await this._Request("Ping",{},x);return A!=="timeout"&&A.type==="Success"})}async startLocalVideo(x,A,F){await this._VideoRecovery.startLocalVideo(x,A,F)}stopLocalVideo(x){this._VideoRecovery.stopLocalVideo(x)}startRemoteVideo(x,A){return this._VideoRecovery.startRemoteVideo(x,A)}stopRemoteVideo(x){this._VideoRecovery.stopRemoteVideo(x)}async dump(){return{type:"H3",id:this.id,address:this.address,closed:this.closed,datagramStatus:this.datagramStatus,datagrams:{sent:this._ConnectionStats.packetsSent,received:this._ConnectionStats.packetsReceived},videoRecovery:this._VideoRecovery.dump(),webRtc:{signalingState:this._PeerConnection?.signalingState??null,connectionState:this._PeerConnection?.connectionState??null,iceGatheringState:this._PeerConnection?.iceGatheringState??null,iceConnectionState:this._PeerConnection?.iceConnectionState??null,connectionStats:this._WebRtcSession?.stats??null}}}};var k=require("@4players/odin-common"),Tx=require("@4players/odin-common/api");o();var L=require("@4players/odin-common");o();async function a0(t,x){let A=performance.now(),F=(0,L.failure)("no connection was attempted");for(let D=0;D<E.ConnectInterval.length&&!x.aborted;D++){let r=A+$F(D);if(await(0,L.abortableSleep)(r-performance.now(),x)==="aborted")return(0,L.failure)("aborted");if(F=await gF(t,x),F.type==="Success")return F}return F}async function gF(t,x){let A;try{A=new WebSocket(t)}catch(B){return(0,L.failure)(`unable to create websocket; ${B}`)}let F=new AbortController,D=new Promise(B=>A.addEventListener("open",()=>B((0,L.success)(A)),{signal:F.signal})),r=new Promise(B=>A.addEventListener("close",f=>B((0,L.failure)(f.reason!==""?f.reason:"unable to establish websocket connection")),{signal:F.signal})),e=new Promise(B=>x.addEventListener("abort",()=>B((0,L.failure)("aborted")),{signal:F.signal})),j=await Promise.race([D,r,e]);return F.abort(),j}function $F(t){let x=E.ConnectInterval.slice(0,t).reduce((F,D)=>F+D,0),A=E.ConnectInterval[t]*Math.random();return x+A}o();var Rx=class{constructor(x,A,F){this.host=x;this.delays=A;this.status=F;this._Attempt=0;this._WasOpen=!1}opened(){this._Attempt=0,this._WasOpen=!0,this.status.set("Open")}interrupted(x){this.status.status!=="Failed"&&this.status.set(this._Pending(),x)}failed(x){this.host.isClosed()||(this.host.recycle(x),this.status.status!=="Failed"&&this.status.set(this._Pending(),x),this._Schedule(x))}retry(x){this.host.isClosed()||this.status.status!=="Failed"||(n(`retrying webrtc datagram path; ${x}`),this._Attempt=0,this.status.set(this._Pending(),x),this._Build())}ensure(){this._Timer!==void 0?(clearTimeout(this._Timer),this._Timer=void 0,this._Build()):this.retry("transport requested")}close(){clearTimeout(this._Timer),this._Timer=void 0,this.status.set("Closed")}dump(){return{attempt:this._Attempt,scheduled:this._Timer!==void 0,wasOpen:this._WasOpen}}_Pending(){return this._WasOpen?"Reconnecting":"Connecting"}_Schedule(x){if(this.host.isClosed()||this._Timer!==void 0||this.status.status==="Failed")return;let A=this.delays[this._Attempt];if(A===void 0){if(this._WasOpen&&this.host.fallBack(x))return;C(`giving up on the webrtc datagram path after ${this._Attempt} rebuilds; ${x}`),this.status.set("Failed",x);return}this._Attempt+=1,n(`rebuilding webrtc peer connection in ${A}ms (attempt ${this._Attempt} of ${this.delays.length})`),this._Timer=setTimeout(()=>{this._Timer=void 0,this._Build()},A)}_Build(){if(!this.host.isClosed())try{this.host.build()}catch(x){this.failed(`unable to build peer connection; ${x}`)}}};var Sx=class t{constructor(x,A,F,D,r){this.id=x;this.address=A;this.url=F;this.onDatagram=D;this.connection=r;this._PeerIdMap=new WeakMap;this._ConnectionStats={...k.CONNECTION_STATS_INITIAL};this._NegotiationCounter=0;this._DatagramStatus=new Fx("Connecting");this._PingFlight=new Y;n(`creating new webrtc connection to '${this.address}' with id ${this.id}`),this.closeSignal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this._ClosePromise=new Promise(e=>{this.closeSignal.addEventListener("abort",()=>{e("closed")},{once:!0})}),this._Recovery=new Rx({build:()=>{this._BuildTransport(),this._VideoRecovery.sessionReplaced()},recycle:e=>this._RecycleTransport(e),fallBack:e=>(C(`webrtc peer connection could not be rebuilt; reconnecting connection ${this.id}; ${e}`),this.close(),!0),isClosed:()=>this.closed},E.WebRtcRecoveryDelays,this._DatagramStatus),this._VideoRecovery=new ix({ensureSession:async()=>{if(this._Transport===void 0&&this._Recovery.ensure(),this._Transport===void 0)throw new Error("webrtc peer connection is unavailable");return this._Transport.session},currentSession:()=>this._Transport?.session,recycleSession:e=>this._Recovery.failed(e),isClosed:()=>this.closed},E.WebRtcRecoveryDelays),this._DatagramStatus.listen((e,j)=>{e==="Failed"&&this._VideoRecovery.giveUp(j??"webrtc recovery gave up")},this.closeSignal),this._BuildTransport(),addEventListener("online",()=>this._Recovery.retry("network is back"),{signal:this.closeSignal}),E.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(E.HealthCheckTimeout)},E.MainConnectionPingInterval)),this._HandleWebRtcUpdates().catch(e=>C("webrtc update loop failed",e))}static async create(x,A,F,D){if(D.aborted)return(0,k.failure)("aborted");let r;try{r=new URL(`wss://${A}`)}catch(f){return(0,k.fail)(`address in token(${A}) can not be parsed; ${f}`)}let e=(0,k.extendUrl)(r,`main?uid=${ux}`);if(e.type!=="Success")return e;let j=await a0(e.value,D);if(j.type!=="Success")return j;let B=new rx(new Q(j.value),Tx.MainCommandsRpc,Tx.MainNotificationsRpc);try{return(0,k.success)(new t(x,A,r,F,B))}catch(f){return B.close(),(0,k.failure)(`unable to create webrtc connection; ${f}`)}}get datagramStatus(){return this._DatagramStatus.status}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}onDatagramStatusChanged(x,A){this._DatagramStatus.listen(x,A)}close(){n(`closing ${this.transport} connection to '${this.address}' with id ${this.id}`),this.connection.close()}async joinRoom(x,A,F,D){let r=await this.connection.request("JoinRoom",{token:String(x),room_id:A,user_data:F,position:D});if(r==="closed"||r.type==="Failure")return r;let e=r.value;if(!("token"in e))return(0,k.failure)("JoinRoom responded without token");let j=(0,k.extendUrl)(this.url,`room?token=${e.token}`);if(j.type==="Failure")return j;let B=await a0(j.value,this.closeSignal);return B.type==="Success"?(this._PeerIdMap.set(B.value,e.peer_id),(0,k.success)(new Q(B.value))):B}async getReconnectToken(x){let A=await this._Request("RequestReconnectToken",{peer_id:x});return A.type==="Failure"?A:g.parse(A.value)}async getRtcStats(){return this._Transport?.peerConnection.getStats()}async healthCheck(){let x=await this._RequestPing(E.HealthCheckTimeout);return x||this.close(),x}async ping(x=3e4){let A=Date.now();return await this._RequestPing(x)?Date.now()-A:0}sendDatagram(x){let A=this._Transport?.audioChannel;if(A?.readyState==="open"){let F=x.byteLength;A.send(x),this._ConnectionStats.packetsSent+=1,this._ConnectionStats.bytesSent+=F}}_CleanUp(){s(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId),this._Recovery.close(),this._VideoRecovery.close(),this._RecycleTransport("connection closed"),this.connection.close()}_BuildTransport(){let x=new RTCPeerConnection,A;try{A=x.createDataChannel("audio",{id:2,negotiated:!0,ordered:!1,maxRetransmits:0})}catch(B){throw x.close(),B}Ox(x),jA(A);let F=this.id;A.binaryType="arraybuffer",A.onmessage=B=>{this._ConnectionStats.packetsReceived++;let f=new Uint8Array(B.data);this._ConnectionStats.bytesReceived+=f.byteLength,this.onDatagram(this.id,f)},A.onerror=B=>C(`webrtc audio data channel for connection with id ${F} raised an error`,B),A.onclosing=B=>n(`webrtc audio data channel for connection with id ${F} begins shutting down`,B),A.onclose=B=>n(`webrtc audio data channel for connection with id ${F} has closed`,B);let D=()=>this._Transport?.peerConnection===x,r=new AbortController,e=()=>{D()&&this._UpdateDatagramStatus()};A.addEventListener("open",e,{signal:r.signal}),A.addEventListener("close",()=>{D()&&this._Recovery.failed("audio data channel closed")},{signal:r.signal}),x.addEventListener("connectionstatechange",e,{signal:r.signal});let j=new sx(x,{sendOffer:async(B,f,a)=>{let u=await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:B,media_map:f,negotiation_id:a});if(u.type==="Failure")throw new Error(`failed to send sdp offer; ${u.reason}`)},sendIceCandidate:async B=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:B.candidate,spd_mid:B.sdpMid??void 0,spd_mline_index:B.sdpMLineIndex??void 0,username_fragment:B.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async B=>{D()&&this._Recovery.failed(B)},checkConnection:async()=>{this.healthCheck().catch(()=>{})}},{firstNegotiationId:this._NegotiationCounter});this._Transport={peerConnection:x,audioChannel:A,session:j,listeners:r},j.startup()}_RecycleTransport(x){let A=this._Transport;A!==void 0&&(C(`recycling webrtc peer connection of connection ${this.id}; ${x}`),this._Transport=void 0,this._NegotiationCounter=A.session.negotiationCounter,A.listeners.abort(),A.session.cleanup(),BA(A.audioChannel),Hx(A.peerConnection))}_UpdateDatagramStatus(){let x=this._Transport;if(x===void 0)return;let A=x.peerConnection.connectionState;x.audioChannel.readyState==="open"&&A==="connected"?(this._Recovery.opened(),this._VideoRecovery.sessionConnected()):this._Recovery.interrupted(`peer connection is ${A}`)}async _HandleWebRtcUpdates(){for(;;){let x=await this.connection.recv();if(x==="closed")break;x.name==="WebRtcUpdate"&&this._Transport?.session.handleWebRtcUpdate(x.properties).catch(()=>{})}this.close()}async _Request(x,A,F){let D=Date.now(),r=await(F===void 0?this.connection.request(x,A):this.connection.request(x,A,F)),e=(Date.now()-D)/1e3;return x!=="Ping"&&s(`sent main rpc '${x}'; took: ${e}s`,{properties:A,timeout:F,result:r}),r==="closed"?(0,k.failure)("connection lost"):r}_RequestPing(x=3e4){return this._PingFlight.run(async()=>{let A=await this._Request("Ping",{},x);return A!=="timeout"&&A.type==="Success"})}async startLocalVideo(x,A,F){await this._VideoRecovery.startLocalVideo(x,A,F)}stopLocalVideo(x){this._VideoRecovery.stopLocalVideo(x)}startRemoteVideo(x,A){return this._VideoRecovery.startRemoteVideo(x,A)}stopRemoteVideo(x){this._VideoRecovery.stopRemoteVideo(x)}async dump(){let x=this._Transport;return{type:"WebRtc",id:this.id,address:this.address,url:this.url.toString(),closed:this.closed,datagramStatus:this.datagramStatus,recovery:this._Recovery.dump(),videoRecovery:this._VideoRecovery.dump(),audioChannel:x?{readyState:x.audioChannel.readyState,bufferedAmount:x.audioChannel.bufferedAmount}:null,datagrams:{sent:this.connectionStats.packetsSent,received:this.connectionStats.packetsReceived},webRtc:x?{signalingState:x.peerConnection.signalingState,connectionState:x.peerConnection.connectionState,iceGatheringState:x.peerConnection.iceGatheringState,iceConnectionState:x.peerConnection.iceConnectionState,connectionStats:x.session.stats}:null}}};function vA(t,x,A,F,D){switch(n(`creating ${x} main connection to '${A}'`),x){case"H3":return wx.create(t,A,F,D);case"WebRTC":return Sx.create(t,A,F,D);default:throw new Error(`transport ${x} is not supported`)}}var ox=require("@4players/odin-common"),O=require("@4players/odin-common/api");o();var Mx=class{constructor(x,A,F,D){this.id=x;this.connection=A;this.cipher=F;this.mediaMap=D;this._DatagramReceived=0;this._DatagramSent=0;this._DatagramReceivedInvalid=0;this._DatagramSentInvalid=0;A.closeSignal.addEventListener("abort",()=>this.close())}get connectionStats(){return this.connection.connectionStats}get transport(){return this.connection.transport}get address(){return this.connection.address}get datagramStatus(){return this.closed?"Closed":this.connection.datagramStatus}get closePromise(){return this.connection.closePromise}get closeSignal(){return this.connection.closeSignal}get closed(){return this.connection.closed}onDatagramStatusChanged(x,A){this.connection.onDatagramStatusChanged(x,A)}close(){this.connection.close()}async joinRoom(x,A,F,D){this.cipher.reset().catch(j=>C("cipher reset failed",j));let r=await this.cipher.encryptUserData(F);if(r===v)return(0,ox.failure)("unable to encrypt initial user-data");let e=await this.connection.joinRoom(x,A,r,D);return e==="closed"||e.type==="Failure"?e:(0,ox.success)(new l0(e.value,this.cipher,this))}getReconnectToken(x){return this.connection.getReconnectToken(x)}getRtcStats(){return this.connection.getRtcStats()}healthCheck(){return this.connection.healthCheck()}sendDatagram(x){this.cipher.encryptDatagram(x).then(A=>{A!==v?(this._DatagramSent+=1,this.connection.sendDatagram(A)):this._DatagramSentInvalid+=1}).catch(A=>C("datagram encryption failed",A))}async decryptDatagram(x,A){let F=await this.cipher.decryptDatagram(x,A);return F!==v?this._DatagramReceived+=1:this._DatagramReceivedInvalid+=1,F}startLocalVideo(x,A,F){return this.connection.startLocalVideo(x,A,{...F,transform:this.cipher.createVideoSenderTransform(x)})}stopLocalVideo(x){this.connection.stopLocalVideo(x),this.cipher.releaseVideoSenderTransform(x)}startRemoteVideo(x){return this.connection.startRemoteVideo(x,this.cipher.createVideoReceiverTransform(x))}stopRemoteVideo(x){this.connection.stopRemoteVideo(x),this.cipher.releaseVideoReceiverTransform(x)}async dump(){return{type:"Encrypted",id:this.id,address:this.address,connectionId:this.connection.id,closed:this.closed,transport:this.transport,datagrams:{sent:this._DatagramSent,received:this._DatagramReceived,sentInvalid:this._DatagramSentInvalid,receivedInvalid:this._DatagramReceivedInvalid},cipher:await this.cipher.dump()}}},Jx=class{constructor(x){this.room=x}resendUserData(){this.room.roomConnection?.notify("UpdatePeer",{user_data:this.room.roomConnection.userData})}setUserData(x,A){let F={kind:"UserDataChanged",peer_id:x,user_data:A};this.room.onEvent("PeerUpdated",F)}},l0=class{constructor(x,A,F){this.rpc=x;this.cipher=A;this.connection=F;this.peers=new Map;this.closeSignal.addEventListener("abort",this.cleanup.bind(this),{once:!0})}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(x,A,F){let D=await this.outgoing(x,A);return D===v?(0,ox.failure)("can not be encrypted"):await this.rpc.request(x,D,F)}notify(x,A){this.outgoing(x,A).then(F=>{F!==v&&this.rpc.notify(x,F)}).catch(F=>C(`encrypting notification '${x}' failed`,F))}async recv(){for(;;){let x=await this.rpc.recv();if(x==="closed")return x;let A=await this.incoming(x.name,x.properties);if(A!==v)return{name:x.name,properties:A}}}close(){return this.rpc.close()}async outgoing(x,A){if(!(x in O.RoomCommandsRpc))return A;let F=(0,O.parseCommand)(x,A,O.RoomCommandsRpc);if(F===void 0)return v;switch(F.name){case"UpdatePeer":{let D=await this.cipher.encryptUserData(F.request.user_data);if(D===v)return v;F.request.user_data=D}break;case"SendMessage":{let D=await this.cipher.encryptMessage(F.request.message);if(D===v)return v;F.request.message=D}break}return F.request}async incoming(x,A){if(!(x in O.RoomNotificationsRpc))return A;let F=(0,O.parseNotification)(x,A,O.RoomNotificationsRpc);if(F===void 0)return v;switch(F.name){case"RoomUpdated":for(let D=0;D<F.properties.updates.length;D++){let r=await this.roomUpdate(F.properties.updates[D]);if(r===v)return v;F.properties.updates[D]=r}break;case"PeerUpdated":{let D=await this.peerUpdate(F.properties);if(D===v)return v;F.properties=D}break;case"MessageReceived":{let D=await this.cipher.decryptMessage(F.properties.sender_peer_id,F.properties.message);if(D===v)return v;F.properties.message=D}break}return F.properties}async peerUpdate(x){switch(x.kind){case"UserDataChanged":{let A=await this.cipher.decryptUserData(x.peer_id,x.user_data);if(A===v)return v;x.user_data=A}break;case"MediaStarted":this.mediaStarted(x.peer_id,x.media.id);break;case"MediaStopped":this.mediaStopped(x.peer_id,x.media_id);break}return x}async roomUpdate(x){switch(x.kind){case"Joined":for(let A of x.room.peers){for(let D of A.medias)this.mediaStarted(A.id,D.id);let F=await this.cipher.decryptUserData(A.id,A.user_data);F!==v?A.user_data=F:A.user_data=new Uint8Array}break;case"PeerJoined":{for(let F of x.peer.medias)this.mediaStarted(x.peer.id,F.id);let A=await this.cipher.decryptUserData(x.peer.id,x.peer.user_data);A!==v?x.peer.user_data=A:x.peer.user_data=new Uint8Array}break;case"PeerLeft":{let A=this.peers.get(x.peer_id);this.peers.delete(x.peer_id),this.cipher.deletePeerKey(x.peer_id);for(let F of A??[])this.mediaStopped(x.peer_id,F)}break}return x}mediaStarted(x,A){let F=this.peers.get(x);F===void 0&&(F=new Set,this.peers.set(x,F)),F.add(A);let D=h({connectionId:this.connection.connection.id,mediaId:A});this.connection.mediaMap.set(D,{peerId:x,connection:this.connection})}mediaStopped(x,A){this.peers.get(x)?.delete(A);let D=h({connectionId:this.connection.connection.id,mediaId:A});this.connection.mediaMap.delete(D)}cleanup(){for(let[x,A]of this.peers)for(let F of A)this.mediaStopped(x,F)}};var Vx=class{constructor(x){this.onDatagram=x;this._LastConnectionId=0;this._Connections=new Map;this._Close=new AbortController;this._MediaMap=new Map;let A=Date.now(),F=setInterval(()=>{Math.abs(Date.now()-A)>E.ClockJumpThreshold&&this.checkHealth(),A=Date.now()},E.ClockJumpCheckInterval);addEventListener("offline",()=>this.checkHealth(),{signal:this._Close.signal}),this._Close.signal.addEventListener("abort",()=>{clearInterval(F);for(let D of this._Connections.values())D.type==="establishing"?D.abort.abort():D.connection.close();this._Connections.clear()},{once:!0})}get closed(){return this._Close.signal.aborted}sendDatagram(x,A){let F=this._Connections.get(x);(F?.type==="established"||F?.type==="virtual")&&F.connection.sendDatagram(A)}async recvDatagram(x,A){let F=IF(A);if(F===void 0||F.length===0)return;let D=this._MediaMap.get(h({connectionId:x,mediaId:F[0]}));if(D===void 0)this.onDatagram(x,A);else{let r=await D.connection.decryptDatagram(D.peerId,A);if(r===v)return;this.onDatagram(D.connection.id,r)}}async acquireConnection(x,A,F,D){if(await(0,cx.nextTick)(),this.closed)return"closed";let r=this.findConnection(x,A),e;switch(r?.type){case"established":s(`reusing existing connection ${r.id}`),e=r;break;case"establishing":{s(`waiting for connecting to '${A}' finish`);let f=await r.finished;if(f.type!=="Success")return f;e=f.value}break;case void 0:{s(`connecting to '${A}'`);let f=await this.createConnection(x,A,D);if(f.type!=="Success")return f;e=f.value}break}let j=e.id,B=new u0(e.connection,()=>this.releaseConnection(j));return e.references+=1,F&&(B=new Mx(++this._LastConnectionId,B,F,this._MediaMap),this.addConnection({type:"virtual",id:B.id,connection:B,createdAt:Date.now()})),(0,cx.success)(B)}async createConnection(x,A,F){let D=++this._LastConnectionId,r=Date.now(),e=new AbortController;F.addEventListener("abort",()=>e.abort(),{once:!0}),s(`creating new connection ${D}`);let j=vA(D,x,A,(Z,_)=>{this.recvDatagram(Z,_).catch(px=>s("dropping datagram",px))},F),{promise:B,resolve:f}=Promise.withResolvers();this.addConnection({type:"establishing",id:D,address:A,transport:x,finished:B,createdAt:Date.now(),abort:e});let a=await j;if(this._Connections.delete(D),a.type!=="Success")return f(a),a;let u={type:"established",id:D,address:A,transport:x,createdAt:r,references:0,connection:a.value};return this.addConnection(u),(0,cx.success)(u)}addConnection(x){(x.type==="established"||x.type==="virtual")&&x.connection.closeSignal.addEventListener("abort",()=>{n(`connection ${x.id} has been closed`),this._Connections.delete(x.id)},{once:!0}),this._Connections.set(x.id,x)}releaseConnection(x){let A=this._Connections.get(x);A?.type==="established"&&(A.references-=1,A.references<=0&&A.connection.close())}checkHealth(){for(let x of this._Connections.values())x.type==="established"&&x.connection.healthCheck().catch(()=>{})}close(){this._Close.abort()}async dump(){let x=[];for(let F of this._Connections.values()){let D;switch(F.type){case"established":D={transport:F.transport,address:F.address,connection:await F.connection.dump(),references:F.references};break;case"establishing":D={transport:F.transport,address:F.address,aborted:F.abort.signal.aborted};break;case"virtual":D={connection:await F.connection.dump()};break}x.push({type:F.type,id:F.id,createdAt:F.createdAt,...D})}let A=[];for(let[F,D]of this._MediaMap)A.push(`${F} -> ${D.peerId} @${D.connection.id} `);return{lastConnectionId:this._LastConnectionId,connections:x,mediaMap:A,closed:this.closed}}findConnection(x,A){for(let F of this._Connections.values())if(F.type!=="virtual"&&F.transport===x&&F.address===A&&(F.type!=="established"||!F.connection.closed))return F}},u0=class{constructor(x,A){this.connection=x;this.release=A;this.closeController=new AbortController;this.closePromise=new Promise(x=>this.closeController.signal.addEventListener("abort",()=>x("closed"),{once:!0}));x.closeSignal.addEventListener("abort",()=>this.close(),{once:!0})}get closeSignal(){return this.closeController.signal}get closed(){return this.closeSignal.aborted}close(){this.release(),this.closeController.abort("closed")}get connectionStats(){return this.connection.connectionStats}get id(){return this.connection.id}get transport(){return this.connection.transport}get address(){return this.connection.address}get datagramStatus(){return this.closed?"Closed":this.connection.datagramStatus}onDatagramStatusChanged(x,A){this.connection.onDatagramStatusChanged(x,A)}joinRoom(x,A,F,D){return this.connection.joinRoom(x,A,F,D)}getReconnectToken(x){return this.connection.getReconnectToken(x)}getRtcStats(){return this.connection.getRtcStats()}healthCheck(){return this.connection.healthCheck()}sendDatagram(x){return this.connection.sendDatagram(x)}startLocalVideo(x,A,F){return this.connection.startLocalVideo(x,A,F)}stopLocalVideo(x){return this.connection.stopLocalVideo(x)}startRemoteVideo(x,A){return this.connection.startRemoteVideo(x,A)}stopRemoteVideo(x){return this.connection.stopRemoteVideo(x)}async dump(){let x=await this.connection.dump();return typeof x=="object"&&(x={...x,isShared:!0,referenceClosed:this.closed}),x}};function IF(t){let x;try{x=(0,CA.decode)(t)}catch{return}if(!Array.isArray(x)||x.length<2)return;let A=x[1];if(Array.isArray(A))return A.map(Number)}var dx=require("@4players/odin-common"),H=class{constructor(x,A){this.uid=x;this.customType=A}#x;#A;get mediaStream(){return this.#x}get audioPlayback(){return(0,dx.assert)(this.#A,"getting the audioPlayback failed, this video has no Audio"),this.#A}get volume(){return(0,dx.assert)(this.audioPlayback,"getting the volume failed, this video has no Audio"),this.audioPlayback.volume}setVolume(x){(0,dx.assert)(this.#A,"Can not set the volume, this video has no Audio"),this.#A.setVolume(x)}setMediaStream(x){this.#x=x}close(){this.#x?.getVideoTracks().forEach(x=>{x.stop(),this.#x?.removeTrack(x)}),this.#x=void 0}};var R=require("@4players/odin-common"),k0=require("@4players/odin-common/api");var b=require("@4players/odin-common"),J=require("@4players/odin-common/api");o();var Ux=class{constructor(x,A,F,D,r,e,j,B,f,a){this.connectionPool=x;this.transport=A;this.onEvent=F;this.gateway=D;this.roomId=e;this.cipher=f;this.disableAutoReconnect=a;this._Close=new AbortController;this._TokenUsed=!1;this._WasConnected=!1;this._FailedConnections=0;this._LastTokenRenew=performance.now();this._LastReconnectStartedAt=0;this._ReconnectingSince=0;this._DatagramStatus="Connecting";this._DatagramsWereOpen=!1;this._Closed=new Promise(x=>this._Close.signal.addEventListener("abort",()=>x(this._Close.signal.reason?"disconnected":"closed"),{once:!0}));this._Token=r,this._UserData=j,this._Position=B,this._Main().then(({reason:u})=>s(`_Main() resolved; ${u}`),u=>c(`_Main() rejected; ${u}`))}get token(){return this._Token}get userData(){return this._UserData}get position(){return this._Position}get closed(){return this._Close.signal.aborted}get mainConnection(){return this._MainConnection}get datagramStatus(){return this._DatagramStatus}async requestUnsafe(x,A){if(this._RoomConnection===void 0)return(0,b.failure)("currently not connected");let F=await this._RoomConnection.request(x,A,void 0);return(0,b.assert)(F!=="timeout","request should not timeout"),F!=="closed"&&F.type==="Success"&&this._HandleRequests(x,A,F.value),F}async request(x,A){let F=Date.now(),D=await this.requestUnsafe(x,A),r=(Date.now()-F)/1e3;if(s(`sent room rpc '${x}'; took: ${r}s`,{properties:A,result:D}),D==="closed"||D.type==="Failure")return D;let e=(0,J.parseResponse)(x,D.value,J.RoomCommandsRpc);return e!==void 0?(0,b.success)(e):(0,b.failure)(`received invalid response from ${x}`)}notify(x,A){this._RoomConnection!==void 0&&this._RoomConnection.notify(x,A)}close(){this._Close.abort(!0)}get renewTokenIn(){let x=this._LastTokenRenew-performance.now()+E.MinTokenRefreshInterval,A=this._Token.timeLeft-E.MinTokenLifetime;return Math.max(x,A)}async _Main(){let x;for(let A=0;;this._FailedConnections++){if(await(0,b.sleep)(Math.max(A-performance.now(),0)),this._Close.signal.aborted||this.connectionPool.closed){x="user requested";break}if(this._WasConnected&&this._ReconnectingSince!==0&&EA(this._ReconnectingSince,E.MaxReconnectDuration)){x="reconnect time limit reached";break}if(A=performance.now()+1e3,this._TokenUsed=!0,this._Token.hasAudience("sfu")){let F=await this._ConnectToServer();if(F.type==="Success"&&F.value==="shutdown"){s("connection closed by user request; shutting down"),x="user requested";break}if(this.disableAutoReconnect&&this._WasConnected){x=F.type==="Failure"?F.reason:"connection lost";break}if(this._LastReconnectStartedAt===0&&(this._LastReconnectStartedAt=performance.now()),this._WasConnected&&this._ReconnectingSince===0&&(this._ReconnectingSince=performance.now()),F.type==="Failure"&&!this._WasConnected&&this._FailedConnections>=3){x=F.reason;break}if(F.type==="Failure"&&!EA(this._LastReconnectStartedAt))continue}if(this.reset(),this._Close.signal.aborted||this.connectionPool.closed){x="user requested";break}if(this.gateway!==void 0&&this._Token.hasAudience("gateway")){this._ChangeStatus("Joining",`requesting new token from ${this.gateway}`);let F=await NF(this.gateway,this._Token,this._Close.signal);if(F.type==="Success")if(F.value instanceof g)A=0,this._Token=F.value,this._TokenUsed=!1;else{x=`gateway error; ${F.value}`;break}else if(!this._WasConnected&&this._FailedConnections>=3){x="unable to contact the gateway";break}}if(this._TokenUsed&&this._Token.timeLeft<=0){x="token has expired";break}if(this._Close.signal.aborted||this.connectionPool.closed){x="user requested";break}}return this._ChangeDatagramStatus("Closed",x),this._ChangeStatus("Closed",x),this.close(),(0,b.failure)(x)}async _ConnectToServer(){let x=this._Token;for(;x.upstream!==void 0;)x=x.upstream;let A=x.claims.adr??this.gateway?.toString();if(!A)return(0,b.success)("continue");if(this._ChangeStatus("Joining",`connecting to ${x.claims.adr}`),this._MainConnection===void 0||this._MainConnection.closed||this._MainConnection.address!==x.claims.adr){this._MainConnection?.close();let j=await this.connectionPool.acquireConnection(this.transport,A,this.cipher,this._Close.signal);if(j==="closed")return(0,b.failure)("connection pool closed");if(j.type==="Failure")return this._ChangeStatus("Joining",`connection failed; ${j.reason}`),(0,b.failure)(`connection failed; ${j.reason}`);this._MainConnection=j.value,this._OwnPeerId=void 0}let F=await Promise.race([Promise.all([this._MainConnection.joinRoom(x,this.roomId,this.userData,this.position)]),(0,b.sleep)(E.ConnectTimeout,"timeout"),this._Closed]);if(F==="closed"||F==="disconnected")return(0,b.success)("continue");if(F==="timeout")return this._ChangeStatus("Joining","timed out"),(0,b.success)("continue");let[D]=F;if(D==="closed")return(0,b.success)("continue");if(D.type==="Failure")return(0,b.failure)(`unable to join room; ${D.reason}`);this._RoomConnection?.close(),this._RoomConnection=D.value,this._WasConnected=!0,this._FailedConnections=0,this._ReconnectingSince=0,this._ChangeStatus("Joined",`joined ${this.roomId}`);let r=this._MainConnection,e=new AbortController;r.onDatagramStatusChanged((j,B)=>this._ChangeDatagramStatus(j==="Closed"?this._PendingDatagramStatus():j,B),e.signal),this._ChangeDatagramStatus(r.datagramStatus);try{let j=await this._HandleConnection(r);return(0,b.success)(j?"shutdown":"continue")}catch(j){return(0,b.failure)(`unable to handle connection; ${j}`)}finally{e.abort(),this._ChangeDatagramStatus(this._PendingDatagramStatus())}}_PendingDatagramStatus(){return this._DatagramsWereOpen?"Reconnecting":"Connecting"}_ChangeDatagramStatus(x,A){if(x===this._DatagramStatus||this._DatagramStatus==="Closed")return;this._DatagramStatus=x,x==="Open"&&(this._DatagramsWereOpen=!0);let F={status:x,message:A};this.onEvent("DatagramStatusChanged",F)}_ChangeStatus(x,A){let F={status:x,message:A};this.onEvent("RoomStatusChanged",F)}async _HandleConnection(x){if(this._RoomConnection===void 0)return!1;let A=new b.Selector([()=>(0,b.sleep)(this.renewTokenIn,"renewToken"),()=>(0,b.sleep)(500,"tick"),async()=>await this._RoomConnection?.recv(),()=>this._Closed,()=>x.closePromise]);for(;;){let F=await A.next();switch(F){case void 0:case"closed":return this._RoomConnection?.close(),this._MainConnection?.close(),!1;case"disconnected":return this._RoomConnection?.close(),this._MainConnection?.close(),!0;case"renewToken":this._RenewToken().catch(D=>C("token renewal failed",D));break;case"tick":break;default:this._HandleEvent(F);break}}}_HandleEvent(x){if(x.name==="RoomUpdated"){let A=J.RoomNotificationsRpc.RoomUpdated.safeParse(x.properties);if(!A.success)return;for(let F of A.data.updates)F.kind==="Joined"&&(this._OwnPeerId=F.own_peer_id)}this.onEvent(x.name,x.properties)}_HandleRequests(x,A,F){switch(x){case"SetPeerPosition":{let D=J.RoomCommandsRpc.SetPeerPosition.request.safeParse(A);if(D.success){let r=D.data.position;this._Position=r.length===2?[r[0],r[1],0]:r}else C("unable to process SetPeerPosition command");break}case"UpdatePeer":{let D=J.RoomCommandsRpc.UpdatePeer.request.safeParse(A);D.success?this._UserData=D.data.user_data:C("unable to process UpdatePeer command");break}}}async _RenewToken(x){if(this._LastTokenRenew=performance.now(),!x&&this.token.timeLeft>E.MinTokenLifetime)return;if(this._MainConnection===void 0||this._OwnPeerId===void 0)return(0,b.failure)("connection is not established");let A=await this._MainConnection.getReconnectToken(this._OwnPeerId);return A.type==="Success"?(this._Token=A.value,(0,b.success)()):(0,b.failure)(`${this._MainConnection.address} rejected reconnect token request; ${A.reason}`)}reset(){this._LastReconnectStartedAt=0,this._RoomConnection?.close(),this._RoomConnection=void 0,this._MainConnection?.close(),this._MainConnection=void 0,this._OwnPeerId=void 0}};async function NF(t,x,A){try{let F={jsonrpc:"2.0",id:1,method:"Connect",params:{}};n(`sending authentication request to '${t}'`,F);let r=await(await fetch(t,{body:JSON.stringify(F),method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${x}`},signal:A})).json();if(n(`received authentication response fom '${t}'`,r),"result"in r)return g.parse(r.result.token);{let e=r.error?.message??"malformed response";return c(`gateway rejected token; ${e}`),(0,b.success)(e)}}catch(F){return(0,b.failure)(String(F))}}function EA(t,x=8e3){return performance.now()-t>x}o();var GA=require("@4players/odin-common");var w=require("@4players/odin-common");o();var fA=require("@4players/odin-common");o();var Kx=class{constructor(x){this.host=x;this.lastId=0;this.senders=new Set;this.sendersActive=!1}create(x){let A={id:++this.lastId,side:x,active:x==="receiver"||this.sendersActive,released:!1,installed:!1,known:!1};return x==="sender"&&this.senders.add(A),{attach:F=>{if(A.released)throw new Error("video transform was released");this.detach(A),A.target=F,A.active&&this.install(A)},detach:()=>this.detach(A),release:()=>{this.detach(A),A.released=!0,this.senders.delete(A),A.known&&this.host.release(A.id)}}}setSendersActive(x){if(this.sendersActive=x,!!x){for(let A of this.senders)if(!A.active){A.active=!0;try{this.install(A)}catch{A.target!==void 0&&this.host.block(A.target)}}}}clear(){this.senders.clear()}install(x){x.target===void 0||x.installed||(this.host.install(x.target,x.id,x.side),x.installed=!0,x.known=!0)}detach(x){let{target:A,installed:F}=x;A!==void 0&&(x.target=void 0,x.installed=!1,F&&this.host.uninstall(A))}};var nA=`"use strict";(()=>{var l=Symbol("Unencrypted"),c=Symbol("Invalid");function v(r){let e=[],n=-1,t=0;for(let o=0;o<r.length;o++){let s=r[o];if(s===0){t+=1;continue}if(s===1&&t>=2){let a=o-t;if(n>=0)a>n&&e.push({start:n,end:a});else if(a!==0)return;n=o+1}t=0}if(n<0)return;let i=r.length;for(;i>n&&r[i-1]===0;)i-=1;return i>n&&e.push({start:n,end:i}),e}function h(r,e){return r[e.start]&31}function A(r){return r>=1&&r<=5}function w(r){let e=0;for(;e<r.length&&r[r.length-1-e]===0;)e+=1;return e}function S(r,e=0){let n=0,t=e;for(let s=0;s<r.length;s++){let a=r[s];t>=2&&a<=3&&(n+=1,t=0),t=a===0?t+1:0}if(n===0)return r;let i=new Uint8Array(r.length+n),o=0;t=e;for(let s=0;s<r.length;s++){let a=r[s];t>=2&&a<=3&&(i[o++]=3,t=0),i[o++]=a,t=a===0?t+1:0}return i}function R(r,e=0){let n=new Uint8Array(r.length),t=0,i=e;for(let o=0;o<r.length;o++){let s=r[o];if(i>=2&&s===3){i=0;continue}n[t++]=s,i=s===0?i+1:0}return n.subarray(0,t)}function G(r,e){let n=r.length+e.length;if(r.length!==16||n>=255)throw new Error("unsupported sei payload size");let t=new Uint8Array(2+n);t[0]=5,t[1]=n,t.set(r,2),t.set(e,2+r.length);let i=S(t),o=new Uint8Array(1+i.length+1);return o[0]=6,o.set(i,1),o[o.length-1]=128,o}function B(r,e){if(r.length<3+e.length||(r[0]&31)!==6)return;let n=R(r.subarray(1));if(n[0]!==5)return;let t=n[1];if(!(t===255||t<e.length)&&n.length===2+t+1&&n[n.length-1]===128){for(let i=0;i<e.length;i++)if(n[2+i]!==e[i])return;return n.subarray(2+e.length,2+t)}}var F=1,q=new Uint8Array([79,68,73,78,45,86,67,45,155,62,113,196,90,210,78,134]),x=32,L=8,O=8,g=4294967295,ne=0xffffffffffff,N=16,V=1,K=128,m=14,te=65535,Y=[0,0,0,1],ie=600,I=new TextEncoder().encode("odin_crypto_video_key");async function C(r,e){let n=new Uint8Array(I.length+e.length);return n.set(I),n.set(e,I.length),await globalThis.crypto.subtle.deriveKey({name:"PBKDF2",hash:"SHA-256",iterations:ie,salt:n},r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function U(r){return r.subarray(0,L)}function M(r){let e=v(r);if(e===void 0||e.length===0)return l;let n=!1,t,i;for(let o=0;o<e.length;o++){let s=e[o];h(r,s)===5&&(n=!0);let a=B(r.subarray(s.start,s.end),q);if(a===void 0)continue;let f=oe(a);if(f===c)return c;t=f,i=o}return{nals:e,keyFrame:n,meta:t,metaIndex:i}}async function H(r,e,n,t){let i=v(r);if(i===void 0)return c;let o=i.filter(u=>A(h(r,u))).length;if(o===0||o>te)return c;if(n+o-1>g)return c;if(!(e.epoch>=0&&e.epoch<=ne))return c;let s=new Uint8Array(m+(t?x:L));s[0]=F,s[1]=t?V:0,P(s,2,n),b(s,6,o),Q(s,8,e.epoch),s.set(t?e.seed:U(e.seed),m);let a=[],f=0,d=0;for(let u of i){if(!A(h(r,u)))continue;let y=Math.min(u.end-u.start,O),p=r.subarray(u.start,u.start+y),ee=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:W(n+d),additionalData:z(e.epoch,n,o,d,p),tagLength:N*8},e.key,r.subarray(u.start+y,u.end));a.push(r.subarray(f,u.start+y)),a.push(S(new Uint8Array(ee),w(p))),a.push(new Uint8Array([K|y])),f=u.end,d+=1}return a.push(r.subarray(f,i[i.length-1].end)),a.push(new Uint8Array(Y)),a.push(G(q,s)),{data:j(a),count:o}}async function X(r,e,n){let t=e.meta;if(t===void 0)return c;let i=[],o=0;for(let s=0;s<e.nals.length;s++){if(s===e.metaIndex)continue;let a=e.nals[s];if(i.push(new Uint8Array(Y)),!A(h(r,a))){i.push(r.subarray(a.start,a.end));continue}if(o>=t.count)return c;let f=r[a.end-1],d=f&~K;if((f&K)===0)return c;if(d>O)return c;if(a.end-a.start<d+N+1)return c;let u=r.subarray(a.start,a.start+d),y=R(r.subarray(a.start+d,a.end-1),w(u)),p=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:W(t.sequenceNumber+o),additionalData:z(t.epoch,t.sequenceNumber,t.count,o,u),tagLength:N*8},n,y).catch(()=>c);if(p===c)return c;i.push(u),i.push(new Uint8Array(p)),o+=1}return o!==t.count?c:j(i)}function oe(r){if(r.length<m)return c;if(r[0]!==F)return c;let e=(r[1]&V)!==0,n=m+(e?x:L);if(r.length!==n)return c;let t=Z(r,2),i=r[6]<<8|r[7];if(i===0)return c;if(t+i-1>g)return c;let o=ae(r,8),s=r.slice(m);return e?{sequenceNumber:t,count:i,epoch:o,seed:s,keyId:U(s)}:{sequenceNumber:t,count:i,epoch:o,keyId:s}}function W(r){let e=new Uint8Array(12);return e[0]=r&255,e[1]=r>>>8&255,e[2]=r>>>16&255,e[3]=r>>>24&255,e[5]=4,e}function z(r,e,n,t,i){let o=new Uint8Array(15+i.length);return o[0]=F,Q(o,1,r),P(o,7,e),b(o,11,n),b(o,13,t),o.set(i,15),o}function Q(r,e,n){b(r,e,Math.floor(n/4294967296)),P(r,e+2,n%4294967296)}function P(r,e,n){r[e]=n>>>24&255,r[e+1]=n>>>16&255,r[e+2]=n>>>8&255,r[e+3]=n&255}function b(r,e,n){r[e]=n>>>8&255,r[e+1]=n&255}function ae(r,e){return(r[e]<<8|r[e+1])*4294967296+Z(r,e+2)}function Z(r,e){return r[e]*16777216+(r[e+1]<<16|r[e+2]<<8|r[e+3])}function j(r){let e=0;for(let i of r)e+=i.length;let n=new Uint8Array(e),t=0;for(let i of r)n.set(i,t),t+=i.length;return n}var se=g>>>1,k=0;function ce(r=Date.now()){return k=Math.max(k+1,Math.floor(r)),k}var E=class{constructor(){this.config={encrypt:!1,failed:!0};this.sequenceNumber=1;this.announce=!1}configure(e){e.masterKey!==this.config.masterKey&&(this.key=void 0),this.config=e}async process(e){let{masterKey:n,encrypt:t,failed:i}=this.config;if(i)return;if(!t||n===void 0)return e;if(this.key===void 0||this.sequenceNumber>se){let a=globalThis.crypto.getRandomValues(new Uint8Array(x)),f=await C(n,a);if(this.config.masterKey!==n)return;this.key={seed:a,epoch:ce(),key:f},this.sequenceNumber=1,this.announce=!0}let o=M(e);if(o===l||o===c)return;let s=await H(e,this.key,this.sequenceNumber,o.keyFrame||this.announce);if(s!==c)return this.sequenceNumber+=s.count,this.announce=!1,s.data}},_=class{constructor(){this.awaitingKeyFrame=!1}configure(e){e.masterKey!==this.masterKey&&(this.masterKey=e.masterKey,this.derived=void 0)}async process(e,n){let t=M(e);if(t===c)return this.drop(!0);if(t===l||t.meta===void 0)return t!==l&&(n=t.keyFrame),this.awaitingKeyFrame&&!n?this.drop(!0):(this.awaitingKeyFrame=!1,{frame:e,requestKeyFrame:!1});let i=this.masterKey;if(i===void 0)return this.drop(!1);if(this.awaitingKeyFrame&&!t.keyFrame)return this.drop(!0);let o=t.meta,s=this.selectSeed(o);if(s===void 0)return this.drop(!0);let a=this.derived;if((a===void 0||!D(a.seed,s))&&(a={seed:s,key:await C(i,s)},this.masterKey!==i))return this.drop(!0);let f=await X(e,t,a.key);return f===c?this.drop(!0):(this.derived=a,this.accepted={seed:s,epoch:o.epoch,lastSequenceNumber:o.sequenceNumber+o.count-1},this.awaitingKeyFrame=!1,{frame:f,requestKeyFrame:!1})}selectSeed(e){let n=this.accepted;if(n!==void 0&&e.epoch===n.epoch&&D(e.keyId,U(n.seed))&&(e.seed===void 0||D(e.seed,n.seed)))return e.sequenceNumber<=n.lastSequenceNumber?void 0:n.seed;if(!(n!==void 0&&e.epoch<=n.epoch))return e.seed}drop(e){return this.awaitingKeyFrame=!0,{requestKeyFrame:e}}};function D(r,e){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(r[n]!==e[n])return!1;return!0}var T=class{constructor(){this.config={encrypt:!1,failed:!0};this.generation=0;this.pendingGeneration=0;this.waiters=[];this.senders=new Map;this.receivers=new Map}handleRequest(e){switch(e.type){case"pending":this.pendingGeneration=Math.max(this.pendingGeneration,e.generation);break;case"configure":{this.config={masterKey:e.masterKey,encrypt:e.encrypt,failed:e.failed},this.generation=e.generation;for(let t of this.senders.values())t.configure(this.config);for(let t of this.receivers.values())t.configure(this.config);let n=this.waiters;this.waiters=[];for(let t of n)t();break}case"release":this.senders.delete(e.id),this.receivers.delete(e.id);break}}createHandler(e){let{id:n,side:t,generation:i}=e;if(t==="sender"){let a=this.senders.get(n);a===void 0&&(a=new E,a.configure(this.config),this.senders.set(n,a));let f=a;return async d=>(await this.reached(i),{frame:await f.process(d),requestKeyFrame:!1})}let o=this.receivers.get(n);o===void 0&&(o=new _,o.configure(this.config),this.receivers.set(n,o));let s=o;return async(a,f)=>(await this.reached(i),await s.process(a,f))}async reached(e){for(;this.generation<Math.max(e,this.pendingGeneration);)await new Promise(n=>this.waiters.push(n))}};var fe=1e3,J=globalThis,$=new T;J.onmessage=r=>$.handleRequest(r.data);J.onrtctransform=r=>{let e=r.transformer,n=$.createHandler(e.options),t=0;e.readable.pipeThrough(new TransformStream({async transform(i,o){try{let s=await n(new Uint8Array(i.data),i.type==="key");if(s.requestKeyFrame){let a=Date.now();a-t>=fe&&(t=a,e.sendKeyFrameRequest?.().catch(()=>{}))}if(s.frame===void 0)return;i.data=ue(s.frame),o.enqueue(i)}catch{}}})).pipeTo(e.writable).catch(()=>{})};function ue(r){let e=r.buffer;return r.byteOffset===0&&r.byteLength===e.byteLength?e:e.slice(r.byteOffset,r.byteOffset+r.byteLength)}})();
|
|
6682
|
-
`;var Wx=class{constructor(){this.generation=0;this.closed=!1;this.transforms=new Kx({install:(x,A,F)=>{if(!(0,fA.isVideoEncryptionCapable)())throw new Error("video encryption is not supported by this browser");let D={id:A,side:F,generation:this.generation};x.transform=new RTCRtpScriptTransform(this.ensureWorker(),D)},block:x=>{C("stopping a video that can not be encrypted in this browser"),x.replaceTrack(null).catch(()=>{})},uninstall:x=>{try{x.transform=null}catch{}},release:x=>this.post({type:"release",id:x})})}configure(x){let A=++this.generation;this.post({type:"pending",generation:A}),x.catch(()=>({encrypt:!0,failed:!0})).then(({masterKey:F,encrypt:D,failed:r})=>{A<(this.lastRequest?.generation??0)||(this.lastRequest={type:"configure",generation:A,masterKey:F,encrypt:D,failed:r===!0},this.post(this.lastRequest))}).catch(console.error)}createTransform(x){return this.transforms.create(x)}setSendersActive(x){this.transforms.setSendersActive(x)}close(){this.closed=!0,this.worker?.terminate(),this.worker=void 0,this.transforms.clear()}post(x){this.worker?.postMessage(x)}ensureWorker(){if(this.closed)throw new Error("video cipher was closed");if(this.worker!==void 0)return this.worker;let x=URL.createObjectURL(new Blob([nA],{type:"text/javascript"})),A=new Worker(x,{type:"module",name:"odin video cipher"});return this.lastRequest!==void 0&&A.postMessage(this.lastRequest),this.worker=A,A}};var kA=require("@4players/odin-common");o();var cA=require("@msgpack/msgpack");o();var sA={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])},iA=t=>({name:"PBKDF2",hash:"SHA-256",iterations:600,salt:t}),oA=32,bA=1e6,aA=2147483648,lA=32,V=[79,68,73,78,1,75,105,109],bx=16,ax=64,uA=16;function dA(t,x){if(t.length!==x.length)return!1;for(let A=0;A<t.length;A++)if(t[A]!==x[A])return!1;return!0}function LF(t){return isFinite(t)}function OF(t){return Array.isArray(t)}function Qx(t){return LF(t)?t:v}function kx(t){return t instanceof Uint8Array?t:v}function HF(t,...x){let A;try{A=(0,cA.decode)(t)}catch{return v}if(!OF(A))return v;let F=new Array(A.length);for(let D=0;D<x.length;D++)if(F[D]=x[D](A[D]),F[D]===v)return v;return F}function Xx(t,...x){if(t.length<V.length)return m;for(let A=0;A<V.length;A++)if(t[A]!==V[A])return m;return HF(t.subarray(V.length),...x)}var lx=class{constructor(x){this.first=1;this.offset=0;this.window=Array(x)}isReplay(x){let A=x-this.first;if(A<0)return!0;if(A>=this.window.length)if(A<this.window.length*2){let r=A-this.window.length+1;A-=r;for(let e=0;e<r;e++)this.advance()}else return this.first=x+1-self.window.length,this.offset=0,this.window.fill(!1),!1;let F=(this.offset+A)%this.window.length,D=this.window[F]===!0;for(this.window[F]=!0;this.window[this.offset]===!0;)this.advance();return D}advance(){this.window[this.offset]=!1,this.first+=1,this.offset=(this.offset+1)%this.window.length}};var zx=class t{constructor(x){this.key=x}static async create(x){typeof x=="string"&&(x=new TextEncoder().encode(x));let A=await globalThis.crypto.subtle.importKey("raw",x,"PBKDF2",!1,["deriveBits"]),F=await globalThis.crypto.subtle.deriveBits(sA,A,256),D=await globalThis.crypto.subtle.importKey("raw",F,"PBKDF2",!1,["deriveKey"]);return new t(D)}async generatePeerKey(x,A){return await globalThis.crypto.subtle.deriveKey(iA(x),this.key,{name:"AES-GCM",length:256},!1,[A])}},Zx=class t{constructor(x,A){this.seed=x;this.key=A;this.sequenceNumbers={datagram:1,message:1,userData:1};this.number_of_packets=0;this.number_of_bytes=0}static async create(x){let A=globalThis.crypto.getRandomValues(new Uint8Array(oA)),F=await x.generatePeerKey(A,"encrypt");return new t(A,F)}get limitReached(){return this.key===void 0?!1:this.number_of_bytes>=aA||this.number_of_packets>=bA}nextSequenceNumber(x){return this.sequenceNumbers[x]++}};function c0(t,x){return{kind:"encrypted",key:t,material:x,antiReplays:{datagram:new lx(lA),userData:new lx(0),message:new lx(0)}}}var Yx=class t{constructor(x,A,F,D){this.additionalData=x;this.sequenceNumber=A;this.seed=F;this.encrypted=D}static parse(x){let A=Xx(x,kx,Qx,kx);if(A===v||A===m)return A;let[F,D,r]=A,e=x.subarray(0,x.length-r.length);return new t(e,D,F,r)}isSameSeed(x){return dA(this.seed,x.seed)}async generateKey(x){return await x.generatePeerKey(this.seed,"decrypt")}};function x0(t,x){let A=new Uint8Array(12);switch(A[0]=x&255,A[1]=x>>8&255,A[2]=x>>16&255,A[3]=x>>24&255,t){case"datagram":A[5]=1;break;case"userData":A[5]=2;break;case"message":A[5]=3;break;default:(0,kA.assert)(!1,"missing content implementation")}return A}var d0=require("@msgpack/msgpack"),hA=require("@4players/odin-common");o();var A0=class{constructor(x){this.actions=x}changeKey(x){this.masterKey!==x&&(this.masterKey=x,this.ownKey=v,this.actions.resendUserData())}async encryptDatagram(x){let A=await this.getKey("datagram");return A===void 0?x:A===U?v:await SF(A,x)}async encryptMessage(x){let A=await this.getKey("message");return A===void 0?x:A===U?U:await pA(A,x,"message")}async encryptUserData(x){let A=await this.getKey("userData");return A===void 0?x:((0,hA.assert)(A!==U,"key unavailable for user data encryption"),await pA(A,x,"userData",A.seed))}async getKey(x){if(this.ownKey===v||this.ownKey?.limitReached)if(x==="userData")this.ownKey=this.masterKey?await Zx.create(this.masterKey):void 0;else return this.ownKey!==v&&(this.ownKey=v,this.actions.resendUserData()),U;return this.ownKey}reset(){this.ownKey=this.masterKey?v:void 0}};async function pA(t,x,A,...F){let D=t.nextSequenceNumber(A),r=x.length+bx,e=RF(D,F,r),j=e.length-r,B=await mA(t,A,D,e.subarray(0,j),x);return e.set(new Uint8Array(B),j),e}function RF(t,x,A){let F=[];x.forEach(e=>F.push(e)),F.push(t),F.push(new Uint8Array(A));let D=(0,d0.encode)(F),r=new Uint8Array(V.length+D.length);return r.set(V,0),r.set(D,V.length),r}async function SF(t,x){let A=TF(x);if(A===v)return v;if((A.kind&ax)!==0)return v;let F=A.body.length+bx,D=t.nextSequenceNumber("datagram"),r=(0,d0.encode)([A.kind|ax,A.mediaIds,D,new Uint8Array(F)]),e=r.length-F,j=await mA(t,"datagram",D,r.subarray(0,e),A.body);return r.set(j,e),r}async function mA(t,x,A,F,D){return new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:x0(x,A),additionalData:F,tagLength:bx*8},t.key,D))}function TF(t){let x=new K(t),A=x.readArrayLength();if(i(A)||A<2)return v;let F=x.readNumber(),D=x.readArrayLength();if(i(F)||i(D))return v;if(D>uA)return v;let r=Array(D);for(let j=0;j<r.length;j++){let B=x.readNumber();if(i(B))return v;r[j]=B}let e=t.subarray(x.position);return{kind:F,mediaIds:r,body:e}}var qA=require("@msgpack/msgpack");o();var D0=class{constructor(x){this.actions=x;this.peerKeys=new Map}async changeKey(x){this.masterKey=x;for(let[A,{kind:F,material:D}]of this.peerKeys)if(x!==void 0){let r=await D.generateKey(x),e=c0(r,D),j=await F0(e,"userData",D.additionalData,D.sequenceNumber,D.encrypted);j!==v?(this.peerKeys.set(A,e),this.actions.setUserData(A,j)):(this.peerKeys.set(A,{kind:"broken",material:D}),this.actions.setUserData(A,new Uint8Array))}else F==="encrypted"&&this.peerKeys.set(A,{kind:"broken",material:D})}async decryptDatagram(x,A){let F=MF(A);if(this.masterKey===void 0)return F===m?A:v;if(F===v||F===m)return v;let D=this.peerKeys.get(x);if(D?.kind!=="encrypted")return v;let r=await F0(D,"datagram",F.additionalData,F.sequenceNumber,F.encrypted);return r===v?v:JF(F.kind&~ax,F.mediaIds,r)}async decryptMessage(x,A){let F=Xx(A,Qx,kx);if(this.masterKey===void 0)return F===m?A:v;if(F===v||F===m)return v;let D=this.peerKeys.get(x);if(D?.kind!=="encrypted")return v;let[r,e]=F,j=A.subarray(0,A.length-e.length);return F0(D,"message",j,r,e)}async decryptUserData(x,A){let F=Yx.parse(A);if(F===v)return v;if(F===m)return this.peerKeys.delete(x),this.masterKey===void 0?A:v;if(this.masterKey===void 0)return this.peerKeys.set(x,{kind:"broken",material:F}),v;let D=this.peerKeys.get(x);if(D?.kind==="encrypted"&&D.material.isSameSeed(F))D.material=F;else{let e=await F.generateKey(this.masterKey);D=c0(e,F)}let r=await F0(D,"userData",F.additionalData,F.sequenceNumber,F.encrypted);return r===v?this.peerKeys.set(x,{kind:"broken",material:F}):D!==void 0&&this.peerKeys.set(x,D),r}reset(){this.peerKeys.clear()}};function MF(t){let x=new K(t),A=x.readArrayLength();if(i(A)||A<1)return v;let F=x.readNumber();if(i(F))return v;if((F&ax)===0)return m;if(A!==4)return v;let D=x.position;x.readObjects(1);let r=t.subarray(D,x.position),e=x.readNumber(),j=x.readBytes();if(i(e)||i(j))return v;let B=t.subarray(0,t.length-j.length);return{kind:F,mediaIds:r,additionalData:B,sequenceNumber:e,encrypted:j}}async function F0(t,x,A,F,D){let r=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:x0(x,F),additionalData:A,tagLength:bx*8},t.key,D).catch(()=>v);return r===v?v:t.antiReplays[x].isReplay(F)?v:new Uint8Array(r)}function JF(t,x,A){let F=2;try{let e=new K(A);for(e.position=0;e.position<A.length;)e.readObjects(1),F+=1}catch{return v}let D=(0,qA.encode)(t),r=new Uint8Array(3+D.length+x.length+A.length);return r[0]=220,r[1]=F>>8&255,r[2]=F&255,r.set(D,3),r.set(x,3+D.length),r.set(A,3+D.length+x.length),r}var r0=class{constructor(x,A){this.active=!1;this.video=new Wx;this.videoSenders=new Map;this.videoReceivers=new Map;let F=new D0(A),D=new A0(A);this.crypto=new w.Strand({encryption:D,decryption:F}),this.peerKeys=F.peerKeys,this.configure(x)}encryptUserData(x){return this.crypto.enqueue(({encryption:A})=>A.encryptUserData(x))}async encryptMessage(x){let A;do A=await this.crypto.enqueue(({encryption:F})=>F.encryptMessage(x));while(A===U);return A}async encryptDatagram(x){return await this.crypto.enqueue(({encryption:A})=>A.encryptDatagram(x))}decryptUserData(x,A){return this.crypto.enqueue(({decryption:F})=>F.decryptUserData(x,A))}decryptMessage(x,A){return this.crypto.enqueue(({decryption:F})=>F.decryptMessage(x,A))}decryptDatagram(x,A){return this.crypto.enqueue(({decryption:F})=>F.decryptDatagram(x,A))}configure(x){let A=x.withVideo===!0,F=this.crypto.enqueue(async D=>{let r=x.password?await zx.create(x.password):void 0;return this.active=r!==void 0,D.encryption.changeKey(r),await D.decryption.changeKey(r),{masterKey:r?.key,encrypt:A}});this.video.configure(F),this.video.setSendersActive(A),F.catch(console.error)}createVideoSenderTransform(x){let A=this.videoSenders.get(x);return A===void 0&&(A=this.video.createTransform("sender"),this.videoSenders.set(x,A)),A}releaseVideoSenderTransform(x){this.videoSenders.get(x)?.release(),this.videoSenders.delete(x)}createVideoReceiverTransform(x){if(!(0,w.isVideoEncryptionCapable)())return;let A=this.videoReceivers.get(x);return A===void 0&&(A=this.video.createTransform("receiver"),this.videoReceivers.set(x,A)),A}releaseVideoReceiverTransform(x){this.videoReceivers.get(x)?.release(),this.videoReceivers.delete(x)}close(){this.videoSenders.clear(),this.videoReceivers.clear(),this.video.close()}getPeerStatus(x){switch(this.peerKeys.get(x)?.kind??"unencrypted"){case"broken":return w.Backend.PeerCipherStatus.InvalidPassword;case"encrypted":return w.Backend.PeerCipherStatus.Encrypted;case"unencrypted":return this.active?w.Backend.PeerCipherStatus.InvalidPassword:w.Backend.PeerCipherStatus.Unencrypted;default:return w.Backend.PeerCipherStatus.Unknown}}deletePeerKey(x){this.peerKeys.delete(x)}reset(){return this.crypto.enqueue(async({encryption:x,decryption:A})=>{x.reset(),A.reset()})}async dump(){return this.crypto.enqueue(async()=>({active:this.active,peers:Array.from(this.peerKeys).map(([x,A])=>`${x} => ${A.kind}`)}))}};function yA(t,x){return(0,GA.assert)(t.type==="OdinCrypto","only OdinCrypto supported"),new r0(t,x)}var t0=class{constructor(x,A,F){this._Captures=new Map;this._Playbacks=new Map;this._Peers=new Map;this._AvailableMediaIds=[];let{url:D,onEvent:r}=A,e=(0,R.unwrap)(g.parse(A.token)),j=A.roomId??e.defaultRoomId,B=A.userData??new Uint8Array(0),f=A.position??[0,0,0];(0,R.assert)(j!==void 0,"room id required for multi-room-tokens"),this.cipher=A.cipher?yA(A.cipher,new Jx(this)):void 0,this.onEvent=r,n(`creating new room '${j}' ${this.cipher?"with":"without"} cipher`,e,B,f),this._Connection=new Ux(x,A.transport??"H3",this._HandleEvent.bind(this),D?new URL(D):void 0,e,j,B,f,this.cipher,F?.disableAutoReconnect??!1)}get connectionStats(){let x={...R.CONNECTION_STATS_INITIAL};return this.mainConnection?this.mainConnection.connectionStats:x}async getRtcStats(){return this.mainConnection?.getRtcStats()}get datagramStatus(){return this._Connection.datagramStatus}get roomConnection(){return this._Connection}get mainConnection(){return this.roomConnection?.mainConnection}get token(){return this._Connection.token.text}request(x,A){return this._Connection.requestUnsafe(x,A)}async link(x){if(x instanceof P){let A=this._Playbacks.get(x.uid)??{media:void 0,playback:void 0};A.playback!==void 0&&this.unlink(A.playback),A.media!==void 0&&x.start(A.media),A.playback=x,n(`linking audio playback media '${x.uid}' with volume ${x.volume} to room '${this._Connection.roomId}'`),this._Playbacks.set(x.uid,A)}else if(x instanceof S){let A=this._Captures.get(x);A&&this.unlink(x);let F=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();A={media:F?{connectionId:this.mainConnection.id,mediaId:F}:void 0},n(`linking audio capture media '${x.uid}' with volume ${x.volume} to room '${this._Connection.roomId}'`),this._Captures.set(x,A),A.media!==void 0&&await x.start(this._Connection,A.media)}else if(x instanceof H){let A=this._Playbacks.get(x.uid)??{media:void 0,playback:void 0};if(A.playback!==void 0&&A.playback!==x&&(A.playback instanceof H?(A.playback.setMediaStream(void 0),A.playback=void 0):this.unlink(A.playback)),A.media!==void 0){let F=await this.mainConnection?.startRemoteVideo(A.media.mediaId);F&&x.setMediaStream(F)}A.playback=x,n(`linking video playback media '${x.uid}' with type '${x.customType}' to room '${this._Connection.roomId}'`),this._Playbacks.set(x.uid,A)}else if(x instanceof y){let A=this._Captures.get(x);A&&this.unlink(x);let F=x.mediaStream?.getVideoTracks()[0];if(F){let D=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();A={media:D?{connectionId:this.mainConnection.id,mediaId:D}:void 0},n(`linking video capture media '${x.uid}' with type '${x.parameters?.customType}' to room '${this._Connection.roomId}'`),this._Captures.set(x,A),A.media!==void 0&&(await x.start(this._Connection,A.media),this.mainConnection?.startLocalVideo(A.media.mediaId,F,x.parameters).catch(r=>C("failed to start local video",r))),x.audioCapture&&await this.link(x.audioCapture)}}else throw new Error("Linking failed, media was not supported")}unlink(x){if(x instanceof P||x instanceof H){let A=this._Playbacks.get(x.uid);if(A?.playback!==x)return;A.playback=void 0,A.media!==void 0&&(x instanceof P?x.stop(A.media):(this.mainConnection?.stopRemoteVideo(A.media.mediaId),x.setMediaStream(void 0))),n(`unlinking playback media '${x.uid}' from room '${this._Connection.roomId}'`),this._Playbacks.set(x.uid,A)}else if(x instanceof S||x instanceof y){x instanceof y&&x.audioCapture&&this.unlink(x.audioCapture);let A=this._Captures.get(x);if(A===void 0)return;A.media!==void 0&&(x.stop(this._Connection,A.media).catch(F=>C("failed to stop media",F)),this._AvailableMediaIds.push(A.media.mediaId),x instanceof y&&this.mainConnection?.stopLocalVideo(A.media.mediaId)),n(`unlinking capture media '${x.uid}' from room '${this._Connection.roomId}'`),this._Captures.delete(x)}else throw new Error("invalid media")}close(){n(`closing room '${this._Connection.roomId}'`),this._Connection.close(),this.cipher?.close()}_HandleEvent(x,A){let F=b0(k0.RoomNotificationsRpc,{name:x,properties:A});F!==void 0&&(this._HandleKnownEvent(F),A=F.properties),this.onEvent(x,A)}_HandleKnownEvent(x){switch(s(`processing event '${x.name}'`,x.properties),x.name){case"RoomStatusChanged":x.properties.status!=="Joined"&&this._HandleConnectionLost();break;case"RoomUpdated":for(let A of x.properties.updates)this._HandleRoomUpdate(A);break;case"PeerUpdated":this._HandlePeerUpdate(x.properties);break}}_HandleConnectionLost(){for(let x of this._Peers.keys())this._HandlePeerLeft(x);for(let[x,A]of this._Captures)A.media!==void 0&&(x instanceof y,x instanceof S&&(x.stop(this._Connection,A.media).catch(F=>C("failed to stop media",F)),A.media=void 0));this._AvailableMediaIds.length=0}_HandleRoomUpdate(x){if(x.kind==="Joined"){(0,R.assert)(this._AvailableMediaIds.length===0,"left over media ids"),this._AvailableMediaIds.push(...x.media_ids),this._HandleRoomJoined();for(let A of x.room.peers)this._HandlePeerJoined(A)}else x.kind==="PeerJoined"?this._HandlePeerJoined(x.peer):x.kind==="PeerLeft"&&this._HandlePeerLeft(x.peer_id)}_HandleRoomJoined(){for(let[x,A]of this._Captures)this._AvailableMediaIds.length===0||this.mainConnection===void 0||(A.media={connectionId:this.mainConnection.id,mediaId:this._AvailableMediaIds.shift()},x instanceof S&&x.start(this._Connection,A.media).catch(F=>C("failed to start media",F)),x instanceof y)}_HandlePeerUpdate(x){x.kind==="MediaStarted"?this._HandleMediaStart(x.peer_id,x.media):x.kind==="MediaStopped"&&this._HandleMediaStopped(x.peer_id,x.media_id)}_HandlePeerJoined(x){this._Peers.has(x.id)||this._Peers.set(x.id,{mediaIds:new Map});for(let A of x.medias)this._HandleMediaStart(x.id,A)}_HandlePeerLeft(x){let A=this._Peers.get(x);if(A!==void 0){for(let F of A.mediaIds.keys())this._HandleMediaStopped(x,F);this._Peers.delete(x)}}_HandleMediaStart(x,A){if(this.mainConnection===void 0)return;let F=this._Peers.get(x);if(F===void 0||A.properties.kind!=="audio"&&A.properties.kind!=="video")return;let D=String(A.properties.uid??(0,R.generateUUID)());A.properties.uid=D;let r=this._Playbacks.get(D)??{media:void 0,playback:void 0};if(this._Playbacks.set(D,r),F.mediaIds.set(A.id,D),r.media={connectionId:this.mainConnection.id,mediaId:A.id},r.playback!==void 0&&(r.playback instanceof P&&r.playback.start(r.media),r.playback instanceof H)){let e=r.playback;this.mainConnection.startRemoteVideo(r.media.mediaId).then(j=>{e.setMediaStream(j)}).catch(j=>{C(`failed to start remote video for media ${A.id}`,j)})}}_HandleMediaStopped(x,A){let F=this._Peers.get(x);if(F===void 0)return;let D=F?.mediaIds.get(A);if(D===void 0)return;let r=this._Playbacks.get(D);r!==void 0&&(r.media!==void 0&&r.media.mediaId===A&&r.playback!==void 0&&(r.playback instanceof P&&r.playback.stop(r.media),r.playback instanceof H&&this.mainConnection?.stopRemoteVideo(r.media.mediaId),r.media=void 0),F.mediaIds.delete(A))}};gx();function VF(t,x){w0(x?.logger,x?.onLogMessage);let A,F=new Vx((r,e)=>A.receivePacket(r,e)),D=new Nx(t);return A=new Px(D,F.sendDatagram.bind(F),x?.enableHTMLAudioElementFallback??!1),new p0(F,A,x)}var ux=(0,h0.generateUUID)(),m0=[],gA=!1;function UF(){gA||typeof window>"u"||(window.addEventListener("beforeunload",()=>{for(let t of m0)t.deref()?.close()}),gA=!0)}var p0=class{constructor(x,A,F){this.version="9";this.supportedTransports=["H3","WebRTC"];this._PlaybackVolume=[1,1];this._CreatedAt=Date.now();this._Options=F??{},this._Options.disableBeforeUnload||UF(),this._ConnectionPool=x,this._MediaController=A,m0.push(new WeakRef(this)),n("plugin initialized")}get playbackVolume(){return this._PlaybackVolume}joinRoom(x){return new t0(this._ConnectionPool,x,this._Options)}async createAudioPlayback(x){return this._MediaController.createAudioPlayback(x)}async createAudioCapture(x){return this._MediaController.createAudioCapture(x)}async createVideoCapture(x,A){return this._MediaController.createVideoCapture(x,A)}async createVideoPlayback(x){return new H(x.uid,x.customType)}enumerateDevices(){return yx()}setOutputVolume(x){this._MediaController.playbackSetGlobalVolume(x)}async setOutputDevice(x){await this._MediaController.playbackSetDevice(x.device)}close(){this._MediaController.close(),this._ConnectionPool.close(),n("plugin closed")}async dump(){return{createdAt:this._CreatedAt,connections:await this._ConnectionPool.dump(),medias:await this._MediaController.dump()}}};async function $A(){let t=[];for(let x of m0){let A=x.deref();A!==void 0&&t.push(await A.dump())}return JSON.stringify({timestamp:Date.now(),instances:t,background:await V0()})}globalThis.odin_debug_dump_state=$A;window!==void 0&&(window.odin_debug_dump_state=$A);0&&(module.exports={SESSION_ID,createPlugin});
|
|
6681
|
+
`});var b0,Z0=h(()=>{b0='"use strict";(()=>{var R=Object.defineProperty;var A=(e,t)=>{for(var r in t)R(e,r,{get:t[r],enumerable:!0})};var u={};A(u,{AdditionalCaptureBlocks:()=>E,AdditionalPlaybackBlocks:()=>P,ClockJumpCheckInterval:()=>_,ClockJumpThreshold:()=>N,ConnectInterval:()=>X,ConnectTimeout:()=>Z,DefaultRefreshRate:()=>C,DefaultVideoCodec:()=>Y,HealthCheckTimeout:()=>O,MainConnectionPingInterval:()=>W,MaxNumberOfDecoders:()=>L,MaxReconnectDuration:()=>K,MinDBFs:()=>v,MinTokenLifetime:()=>q,MinTokenRefreshInterval:()=>Q,PlaybackPreload:()=>M,RenderQuantumSize:()=>V,VadPreload:()=>D,WebRtcAnswerTimeout:()=>H,WebRtcIceTimeout:()=>$,WebRtcMaxNegotiationAttempts:()=>J,WebRtcRecoveryDelays:()=>z,WebRtcStatsSnapshotInterval:()=>j,WebRtcTimeout:()=>G});var P=3,E=3,M=3,C=250,D=3,L=512,V=128,v=-758.596,O=1e4,_=1e3,N=1e4,W=3e3,j=1e3,$=3e3,G=1e4,H=1e4,J=3,z=[0,2e3,5e3],Z=5e3,q=6e4,Q=5e3,X=[0,100,200,200,500],K=12e4,Y="H264";function d(e,t,r){return e.postMessage(t,r)}var ee;(e=>{let t;(r=>(r[r.InvalidPassword=-1]="InvalidPassword",r[r.Unknown=0]="Unknown",r[r.Unencrypted=1]="Unencrypted",r[r.Encrypted=2]="Encrypted"))(t=e.PeerCipherStatus||={})})(ee||={});var{Deno:k}=globalThis,te=typeof k?.noColor=="boolean"?k.noColor:!1,re=!te;function m(e,t){return{open:`\\x1B[${e.join(";")}m`,close:`\\x1B[${t}m`,regexp:new RegExp(`\\\\x1b\\\\[${t}m`,"g")}}function h(e,t){return re?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}function p(e){return h(e,m([0],0))}function S(e){return h(e,m([1],22))}function ne(e){return h(e,m([2],22))}var Ie=new RegExp(["[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)","(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TXZcf-nq-uy=><~]))"].join("|"),"g"),se=new Date,f=(e=>(e[e.CRITICAL=0]="CRITICAL",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(f||{}),I={0:"\\u{1F4A5}",1:"\\u{1F534}",2:"\\u{1F7E1}",3:"\\u{1F535}",4:"\\u{1F7E3}"},oe={4:ne,3:p,2:p,1:S,0:S};function ae({message:e}){return String(e)}function T(e){return JSON.stringify({timestamp:e.date.toISOString(),level:f[e.level],message:e.message,extra:e.extra})}function U(e){function t(c,i){return[Math.floor(c/i),c%i]}function r(){let c,i=e.date.valueOf()-se.valueOf();[i,c]=t(i,1e3);let[B,F]=t(i,60);return`${B.toString().padStart(4,"0")}:${F.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=I[e.level],a=e.logger.name!==void 0?`@${e.logger.name}`:"";return`${p(r())}${a} ${s} ${oe[e.level](String(e.message))}${n()}`}function ie(e){let t=`[${e.date.toISOString()}]`,r=`[${f[e.level]}]`,n=e.logger.name!==void 0?`[${e.logger.name}] `:"",s=I[e.level];return`${t} ${s} ${r.padEnd(7," ")} ${n}${e.message}`}function ce(){return typeof Deno=="object"&&Deno.stdout.isTerminal()}var w=class{static sparse=ae;static json=T;static pretty=U;static structured=ie;static default=ce()?U:T;constructor(){}};var ue=class{formatter;consoleObject;filter;constructor(e=w.default,t=4,r=console){this.filter=t,this.formatter=e,this.consoleObject=r}handle(e){let t=this.formatter(e);switch(e.level){case 0:case 1:this.consoleObject.error(t);break;case 2:this.consoleObject.warn(t);break;case 3:this.consoleObject.info(t);break;case 4:this.consoleObject.debug(t);break}}};var o=class{#e;sinks;filter;parent;get name(){return this.#e}constructor(e,t=void 0,r=[],n=void 0){this.#e=t,this.sinks=r,this.filter=e,this.parent=n}log(e,t,r=void 0){let n={date:new Date,level:e,logger:this,message:t,extra:r};this.filter<e||this.insert(n)}insert(e){if(!(this.filter<e.level)){for(let t of this.sinks)t.filter>=e.level&&t.handle(e);this.parent!==void 0&&this.parent.insert(e)}}error=this.log.bind(this,1);warn=this.log.bind(this,2);info=this.log.bind(this,3);debug=this.log.bind(this,4)},l=globalThis[Symbol.for("odin-global-logger")]??=new o(3,void 0,[new ue]),le=o.prototype.log.bind(l,1),fe=o.prototype.log.bind(l,2),de=o.prototype.log.bind(l,3),pe=o.prototype.log.bind(l,4),we=o.prototype.log.bind(l);var b=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.blocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"init":this.state=new y(s.workerPort,sampleRate*.02);break;case"close":this.alive=!1;break;case"dump":s.result.postMessage(this.dump());break}}process(r,n,s){if(this.state===void 0||r.length<1||r[0].length<1)return this.alive;let a=this.state.fill(0,r[0][0]);return this.state.offset===this.state.length&&(this.state.flush(),this.state.fill(a,r[0][0])),this.alive}dump(){return{type:"unshared capture worklet",alive:this.alive,sampleRate,offset:this.state?.offset||null,length:this.state?.length||null,blocks:this.blocks}}},x=class extends AudioWorkletProcessor{constructor(){super();this.alive=!0;this.silenceBlocks=0;this.voiceBlocks=0;this.totalBlocks=0;this.port.onmessage=this.onMessage.bind(this)}async onMessage(r){let[n,s]=r.data;switch(n){case"close":this.alive=!1;break;case"init":this.state=new g(s.workerPort,sampleRate*.02),s.workerPort.onmessage=this.onMessage.bind(this);break;case"samples":this.state?.add(s.id,s.buffer);break;case"dump":s.result.postMessage(this.dump());break}n==="close"&&(this.alive=!1)}process(r,n,s){if(this.state===void 0||n.length<1||n[0].length<2)return this.alive;let a=this.state.fill(0,n[0][0],n[0][1]);return a<u.RenderQuantumSize&&(this.totalBlocks+=1,this.state.next(),this.state.hasVoice?this.voiceBlocks+=1:this.silenceBlocks+=1,this.state.fill(a,n[0][0],n[0][1])),this.alive}dump(){return{type:"unshared playback worklet",alive:this.alive,sampleRate,id:this.state?.id||null,offset:this.state?.offset||null,length:this.state?.length||null,hasVoice:this.state?.hasVoice??!1,silenceBlocks:this.silenceBlocks,voiceBlocks:this.voiceBlocks,totalBlocks:this.totalBlocks}}},y=class{constructor(t,r){this.port=t;this.length=r;this.offset=0,this.buffer=new Float32Array(r)}fill(t,r){let n=Math.min(r.length-t,this.length-this.offset);return this.buffer.set(r.subarray(t,t+n),this.offset),this.offset+=n,t+n}flush(){d(this.port,["captureTick",{buffer:this.buffer}],[this.buffer.buffer]),this.offset=0,this.buffer=new Float32Array(this.length)}},g=class{constructor(t,r){this.port=t;this.length=r;this.cache=[];this.id=-1,this.offset=0,this.buffer=void 0,this.next()}get hasVoice(){return this.buffer!==void 0}fill(t,r,n){let s=Math.min(u.RenderQuantumSize-t,this.length-this.offset);return this.buffer!==void 0&&(r.set(this.buffer.subarray(this.offset,this.offset+s),t),n.set(this.buffer.subarray(this.offset+this.length,this.offset+this.length+s),t)),this.offset+=s,t+s}add(t,r){this.cache.push({id:t,buffer:r})}next(){for(this.id+=1;this.cache[0]?.id<this.id;)this.cache.shift();this.cache[0]?.id===this.id?(this.buffer=this.cache[0].buffer,this.cache.shift()):this.buffer=void 0,this.offset=0,d(this.port,["playbackTick",{}])}};registerProcessor("OdinCaptureProcessor",b);registerProcessor("OdinPlaybackProcessor",x);})();\n'});var xA={};hx(xA,{UnsharedCaptureWorker:()=>$x,UnsharedPlaybackWorker:()=>_x,createCaptureWorker:()=>uF,createPlaybackWorker:()=>cF});function uF(t,x,A,F,D=n.DefaultRefreshRate){return lF.enqueue(async()=>{let[r,e]=await nx(o0,b0,t,"OdinCaptureProcessor",{channelCount:1,numberOfInputs:1,numberOfOutputs:0});return console.warn("SharedArrayBuffer is not available; creating ODIN CaptureWorker in fallback mode"),$x.create(t,x,A,D,r,e,F)})}async function cF(t,x=n.DefaultRefreshRate){if(t.sampleRate!==48e3)throw new Error("playback sample rate must be 48kHz ");let[A,F]=await nx(o0,b0,t,"OdinPlaybackProcessor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2]});return _x.create(t,x,A,F)}var Y0,lF,$x,_x,AA=h(()=>{"use strict";Y0=require("@4players/odin-common");b();gx();z0();Z0();lF=new Y0.Strand;$x=class t extends Cx{constructor(A,F,D,r,e){super(A,F,D,r,e);this._Activity=I;this._SpeechProbability=0;F.addEventListener("message",this._OnMessages.bind(this))}static async create(A,F,D,r,e,j,v){let{port1:E,port2:o}=new MessageChannel;return u(e,["captureInit",{sampleRate:A.sampleRate,refreshRate:r,workletPort:E}],[E]),await tx(e,"captureReady"),u(j.port,["init",{workerPort:o}],[o]),new t(j,e,F,D,v)}get activity(){return this._Activity}get speechProbability(){return this._SpeechProbability}setVolume(A){u(this.worker,["captureSetVolume",{value:A}])}_OnMessages(A){super._OnMessages(A);let[F,D]=A.data;F==="captureUpdate"&&(this._Activity={isSilent:!D.active,rmsDBFS:D.rmsDBFs},this._SpeechProbability=D.speechProbability)}},_x=class t extends Bx{constructor(A,F,D){super(A,F,D);this.activities=new Float32Array;this.jitterStats=[]}static async create(A,F,D,r){let{port1:e,port2:j}=new MessageChannel;return u(D,["playbackInit",{workletPort:e,refreshRate:F}],[e]),await tx(D,"playbackReady"),u(r.port,["init",{workerPort:j}],[j]),new t(A,r,D)}getActivity(A){let F=this.medias.get(k(A));if(F===void 0)return;let D=this.activities.at(F.index);if(D!==void 0)return D===0?I:{isSilent:!1,rmsDBFS:D}}getJitterStats(A){let F=this.medias.get(k(A));if(F===void 0)return;let D=this.jitterStats.at(F.index);if(D!==void 0)return D}setGlobalVolume(A){u(this.worker,["playbackSetVolume",{index:"global",value:A}])}setVolume(A,F){let D=this.medias.get(k(A));D!==void 0&&u(this.worker,["playbackSetVolume",{index:D.index,value:F}])}_GetFreeIndex(){let A=super._GetFreeIndex();if(A!==void 0)return A;if(this.medias.size<n.MaxNumberOfDecoders)return this.medias.size}_OnMessages(A){super._OnMessages(A);let[F,D]=A.data;F==="playbackUpdate"&&(this.activities=D.activities,this.jitterStats=D.jitterStats)}}});var WF={};hx(WF,{SESSION_ID:()=>ux,createPlugin:()=>UF});module.exports=OA(WF);var m0=require("@4players/odin-common");b();var T=require("@4players/odin-common");b();var Ax=require("@4players/odin-common");b();var N=require("@4players/odin-common");b();var T0="getUserMedia; timeout";async function R0(t,x){try{let A=await Promise.race([navigator.mediaDevices.getUserMedia({audio:{echoCancellation:t.echoCanceller,noiseSuppression:t.noiseSuppression!=="None",autoGainControl:t.gainController,echoCancellationType:"system",deviceId:x?{exact:x}:void 0}}),(0,N.sleep)(3e4,"timeout")]);return A==="timeout"?(0,N.failure)(T0):(0,N.success)(A)}catch(A){return(0,N.failure)(`getUserMedia; ${A}`)}}async function M0(t,x,A){let F,D=!1;if(x.device?.device.kind==="track"&&x.device?.device.audioTrack)F=new MediaStream([x.device.device.audioTrack]);else{let j=x.device&&x.device.device.deviceId!=="default"?x.device.device.deviceId:void 0,v=await R0(A,j);if(v.type!=="Success"&&v.reason!==T0&&j&&(C(`unable to open requested capture device, falling back to default; ${v.reason}`),v=await R0(A),D=v.type==="Success"),v.type!=="Success")return v;F=v.value}let r=F.getAudioTracks()[0].getSettings().sampleRate,e=await t.audioContexts.acquire(r);return(0,N.success)({source:e.createMediaStreamSource(F),defaulted:D})}function jx(t){t.getTracks().forEach(x=>{x.stop(),t.removeTrack(x)})}async function J0(t){return new ex({deviceId:t.id,kind:"track",name:t.label??"MediaStreamTrack",audioTrack:t},!1)}async function jF(){let t=(await navigator.mediaDevices.enumerateDevices()).filter(x=>!!x.label);if(t.length===0&&(0,N.isFirefoxBrowser)()){let x=await vF("microphone");(x==="granted"||x===!1)&&(await BF("audio"),t=(await navigator.mediaDevices.enumerateDevices()).filter(A=>!!A.label))}return t}async function yx(){let t=await jF(),x=new Map,A=[];for(let D of t){let r=D.kind;if(!(r!=="audioinput"&&r!=="audiooutput")){if(D.deviceId==="default"){x.set(r,D);continue}D.deviceId!=="communications"&&A.push(new ex({deviceId:D.deviceId,name:D.label,kind:r},!1))}}let F=D=>new ex({deviceId:"default",name:x.get(D)?.label??"Default",kind:D},!0);return[F("audioinput"),F("audiooutput"),...A]}async function vF(t){try{return(await navigator.permissions.query({name:t})).state}catch{return!1}}async function BF(t){try{let x=await navigator.mediaDevices.getUserMedia({[t]:!0});return x?.getTracks().forEach(A=>{A.stop(),x.removeTrack(A)}),!0}catch{return!1}}var Ix=require("@4players/odin-common");b();var FA=(0,Ix.isSharedArrayBufferCapable)()&&!(0,Ix.isSafariBrowser)()?Promise.resolve().then(()=>(X0(),Q0)):Promise.resolve().then(()=>(AA(),xA));async function DA(t,x,A,F){return FA.then(D=>D.createCaptureWorker(t,x,A,F,n.DefaultRefreshRate))}async function rA(t){return FA.then(x=>x.createPlaybackWorker(t,n.DefaultRefreshRate))}var dF=250,kF=1e3,R=class{constructor(x,A){this.controller=x;this._Medias=new Map;this._Vad={...Ax.VAD_DEFAULTS};this._Apm={...Ax.APM_DEFAULTS};this._Volume=1;this._Queue=Promise.resolve();this.#D=0;this._DeviceCb=()=>{clearTimeout(this.#F),this.#F=setTimeout(()=>{this._enqueue(async()=>{let x=this._DeviceParameters?.device;!x||x.device.kind==="track"||(x.device.deviceId==="default"?await this._followDefaultDevice():await this._detectSelectedDeviceRemoved(x.device.deviceId))}).catch(x=>C("device-change handler failed",x))},dF)};A.apm&&this.setApm(A.apm).catch(console.error),A.vad&&this.setVad(A.vad),typeof A.volume<"u"&&this.setVolume(A.volume).catch(console.error),this.uid=(0,Ax.generateUUID)(),this.#x=A.customType,this.#A=A.ref}#x;#A;#F;#D;async _followDefaultDevice(){let x=this._DeviceParameters;this._Volume==="muted"||!this._Capture||!x||Date.now()-this.#D<kF||(s("default capture device may have moved, re-opening capture"),await this._setDeviceImpl(x))}async _detectSelectedDeviceRemoved(x){(await yx()).some(r=>r.device.deviceId===x)||this._Capture?.source.mediaStream?.getAudioTracks()[0]?.readyState==="live"||(this._DeviceParameters?.onStatusChanged?.("stopped"),navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._DeviceParameters=void 0,await this._closeImpl())}_enqueue(x){let A=this._Queue.then(x,x);return this._Queue=A.catch(()=>{}),A}get vad(){return this._Vad}get apm(){return this._Apm}get volume(){return this._Volume}get activity(){return this._Capture?.worker.activity??I}get speechProbability(){return this._Capture?.worker.speechProbability??0}get deviceId(){return this._DeviceParameters?.device?.device.deviceId}async start(x,A){let F=this._Medias.get(A.connectionId);F===void 0&&this._Medias.set(A.connectionId,F=new Set),f(`starting audio capture media ${A.mediaId} on connection ${A.connectionId}`),!F.has(A.mediaId)&&(F.add(A.mediaId),x.mainConnection?.id===A.connectionId&&await x.request("StartMedia",{media_id:A.mediaId,properties:{kind:"audio",uid:this.uid,ref:this.#A,customType:this.#x}}).catch(D=>c(`StartMedia got rejected; ${D}`)),this._UpdateMedias().catch(console.error))}async stop(x,A){let F=this._Medias.get(A.connectionId);f(`stopping audio capture media ${A.mediaId} on connection ${A.connectionId}`),F?.delete(A.mediaId)&&(x.mainConnection?.id===A.connectionId&&await x.request("StopMedia",{media_id:A.mediaId}).catch(D=>c(`StopMedia got rejected; ${D}`)),this._UpdateMedias().catch(console.error))}setVad(x){s("updating vad config",x),this._Vad=x,this._Capture&&this._Capture.worker.setVad(x)}async setApm(x){await this._enqueue(()=>this._setApmImpl(x))}async _setApmImpl(x){s("updating apm config",x),this._Apm=x,this._DeviceParameters&&await this._setDeviceImpl(this._DeviceParameters)}async setDevice(x){await this._enqueue(()=>this._setDeviceImpl(x))}async _setDeviceImpl(x){s("updating capture device parameters",x);let A=this._DeviceParameters;if(this._DeviceParameters=x,this._Volume==="muted")return;let F;try{let D=await M0(this.controller,x,{...this._Apm,echoCanceller:this._Monitor?!1:this._Apm.echoCanceller});if(D.type!=="Success"){c(`unable to open capture device; ${D.reason}`),this._DeviceParameters=A;return}F=D.value.source.context,navigator.mediaDevices.addEventListener("devicechange",this._DeviceCb);let r=this._Capture?.source.context;if(this._Capture!==void 0){jx(this._Capture.source.mediaStream);try{this._Capture.source.disconnect(this._Capture.worker.worklet)}catch(e){C("failed to disconnect previous capture source",e)}}this._Capture===void 0||this._Capture.worker.worklet.context!==D.value.source.context?(this._Capture?.worker.close(),this._Capture={worker:await DA(D.value.source.context,this.controller.sink,this.controller.receiveMonitoredPacket.bind(this.controller),new WeakRef(this)),source:D.value.source},await this._UpdateMedias(),this._Capture.worker.setVolume(this._Volume),this.setVad(this.vad)):this._Capture.source=D.value.source,F=void 0,this._Capture.source.connect(this._Capture.worker.worklet),r!==void 0&&await this.controller.audioContexts.release(r),this.#D=Date.now(),x.onStatusChanged?.(D.value.defaulted?"defaulted":"started")}catch(D){throw F!==void 0&&await this.controller.audioContexts.release(F),new Error(`Error in setDevice(); ${D}`,{cause:D})}}async setVolume(x){await this._enqueue(()=>this._setVolumeImpl(x))}async _setVolumeImpl(x){s(`updating capture volume to ${x}`),this._Volume=x,x==="muted"?await this._closeImpl():(!this._Capture&&this._DeviceParameters&&await this._setDeviceImpl(this._DeviceParameters),this._Capture?.worker.setVolume(x))}close(){this._enqueue(()=>this._closeImpl()).catch(console.error)}async _closeImpl(){if(s("closing audio capture"),clearTimeout(this.#F),this.#F=void 0,this._Capture!==void 0){this._Capture.worker.close(),jx(this._Capture.source.mediaStream);try{this._Capture.source.disconnect(this._Capture.worker.worklet)}catch(x){C("failed to disconnect audio node",x)}await this.controller.audioContexts.release(this._Capture.source.context)}navigator.mediaDevices.removeEventListener("devicechange",this._DeviceCb),this._Capture=void 0}async dump(){let x=[];for(let[A,F]of this._Medias)x.push(`${A} => ${Array.from(F.values()).join(",")}`);return{uid:this.uid,ref:this.#A??null,customType:this.#x??null,worker:await this._Capture?.worker.dump()??null,vad:this._Vad,apm:this._Apm,volume:this._Volume,medias:x}}async _UpdateMedias(){if(this._Capture!==void 0){let x=Array.from(this._Medias).map(([A,F])=>({id:A,mediaIds:Array.from(F)}));this._Capture.worker.setMedias(x)}}async startLoopback(){this._Monitor===void 0&&(s("starting audio capture loopback"),this.setApm(this._Apm).catch(console.error),this._Monitor=await this.controller.createAudioPlayback({uid:"loopback"}),this._Monitor.start({connectionId:0,mediaId:0}),this._Medias.set(0,new Set([0])),await this._UpdateMedias())}async stopLoopback(){this._Monitor!==void 0&&(s("stopping audio capture loopback"),this._Monitor.close(),this._Monitor=void 0,this.setApm(this._Apm).catch(console.error),this._Medias.delete(0),await this._UpdateMedias())}};var W=require("@4players/odin-common");b();var y=class{constructor(x,A){this.controller=x;this.parameters=A;this.uid=(0,W.generateUUID)()}#x;#A=new Map;#F;get customType(){return this.parameters?.customType}get mediaStream(){return this.#x}get audioCapture(){return this.#F}get volume(){return(0,W.assert)(this.audioCapture,"getting the volume failed, this video has no Audio"),this.audioCapture.volume}async setVolume(x){(0,W.assert)(this.audioCapture,"setVolume() failed, this video has no Audio"),await this.audioCapture.setVolume(x)}get vad(){return(0,W.assert)(this.audioCapture,"getting the vad config failed, this video has no Audio"),this.audioCapture.vad}setVad(x){(0,W.assert)(this.audioCapture,"setVad() failed, this video has no Audio"),this.audioCapture.setVad(x)}async setDevice(x,A={voiceActivity:void 0,volumeGate:void 0}){if(this.#x)throw new Error("This VideoCapture already has a MediaStream.");if(!x.getVideoTracks()[0])throw new Error("Error when calling setDevice(), MediaStream does not contain a VideoStreamTrack!");if(this.#x=x,x.getAudioTracks()[0]){let D={device:await J0(x.getAudioTracks()[0]),vad:A,ref:this.uid};this.#F=await this.controller.createAudioCapture(D)}}async start(x,A){let F=this.#A.get(A.connectionId);if(F===void 0&&this.#A.set(A.connectionId,F=new Set),!F.has(A.mediaId)&&(F.add(A.mediaId),x.mainConnection?.id===A.connectionId)){let D={kind:"video",codec:this.parameters?.codec??n.DefaultVideoCodec,ref:this.#F?.uid,uid:this.uid};this.parameters?.customType&&(D.customType=this.parameters.customType),await x.request("StartMedia",{media_id:A.mediaId,properties:D}).catch(r=>c(`StartMedia got rejected; ${r}`))}}async stop(x,A){this.#x&&jx(this.#x),this.#A.get(A.connectionId)?.delete(A.mediaId)&&x.mainConnection?.id===A.connectionId&&await x.request("StopMedia",{media_id:A.mediaId}).catch(D=>c(`StopMedia got rejected; ${D}`))}async dump(){let x=[];for(let[A,F]of this.#A)x.push(`${A} => ${Array.from(F.values()).join(",")}`);return{uid:this.uid,ref:this.#F?.uid??null,customType:this.customType??null,tracks:this.#x?.getVideoTracks().map(A=>({id:A.id,kind:A.kind,label:A.label,ready:A.readyState,muted:A.muted,settings:{...A.getSettings()}}))??[],volume:this.#F?.volume??0,medias:x}}close(){this.#x&&jx(this.#x),this.audioCapture?.close(),this.#F=void 0}};var pF=require("@4players/odin-common");b();var P=class{constructor(x,A,F){this.controller=x;this.uid=A;this.customType=F}get volume(){return this.controller.playbackGetVolume(this.uid)}get activity(){return this.controller.playbackGetActivity(this.uid)}get jitterStats(){return this.controller.playbackGetJitterStats(this.uid)}start(x){f(`starting audio playback media ${x.mediaId} on connection ${x.connectionId}`),this.controller.playbackStart(this.uid,x)}stop(x){f(`stopping audio playback media ${x.mediaId} on connection ${x.connectionId}`),this.controller.playbackStop(this.uid,x)}setVolume(x){s(`updating audio playback media '${this.uid}' volume to ${x}`),this.controller.playbackSetVolume(this.uid,x)}close(){s(`closing audio playback media '${this.uid}'`),this.controller.closePlayback(this.uid)}};function hF(t,x){let A=t.audioContext;if(typeof A.setSinkId=="function"){t.connectOutput(A.destination);let F,D=()=>{if(A.state==="running"&&F!==void 0){let r=F;F=void 0,A.setSinkId(r).catch(e=>C("failed to apply deferred sinkId",e))}};return A.addEventListener("statechange",D),{async setSinkId(r){if(A.state!=="running"){F=r;return}await A.setSinkId(r)},dispose(){A.removeEventListener("statechange",D)}}}if(x&&typeof document<"u"&&typeof HTMLAudioElement<"u"&&typeof HTMLAudioElement.prototype.setSinkId=="function"){let F=A.createMediaStreamDestination();t.connectOutput(F);let D=new Audio;D.srcObject=F.stream,D.muted=!1,D.volume=1;let r=!1,e=!1,j={once:!0,passive:!0,capture:!0},v=()=>{e=!1,l()},E=()=>{e||r||(e=!0,document.addEventListener("pointerdown",v,j),document.addEventListener("keydown",v,j))},o=()=>{e&&(e=!1,document.removeEventListener("pointerdown",v,!0),document.removeEventListener("keydown",v,!0))},l=()=>{r||D.play().catch(_=>{r||(_ instanceof DOMException&&_.name==="NotAllowedError"?E():C("failed to start playback audio element",_))})},Z=()=>{A.state==="running"&&D.paused&&l()};return A.addEventListener("statechange",Z),l(),{async setSinkId(_){await D.setSinkId(_)},dispose(){r=!0,o(),A.removeEventListener("statechange",Z),D.pause(),D.srcObject=null,D.removeAttribute("src");try{D.load()}catch{}F.disconnect()}}}return t.connectOutput(A.destination),{async setSinkId(){},dispose(){}}}var Nx=class{constructor(x){this.audioContextFactory=x;this.entries=[];this._acquireStrand=new T.Strand}acquire(x){return this._acquireStrand.enqueue(async()=>{for(let D of this.entries)if(D.sampleRate===x||D.sampleRate===void 0&&D.audioContext.sampleRate===x)return D.references+=1,D.audioContext;let A=await this.audioContextFactory(x),F=this.entries.find(D=>D.audioContext.sampleRate===A.sampleRate);return F?(F.references+=1,A.close().catch(()=>{}),F.audioContext):(this.entries.push({sampleRate:x,audioContext:A,references:1}),A)})}async release(x){let A=this.entries.findIndex(F=>F.audioContext===x);if(!(A<0)&&(this.entries[A].references-=1,this.entries[A].references<=0)){let F=this.entries[A].audioContext;this.entries.splice(A,1),await F.close()}}close(){for(let x of this.entries.splice(0))x.audioContext.close().catch(()=>{})}},Px=class t{constructor(x,A,F=!1){this.audioContexts=x;this.sink=A;this.enableHTMLAudioElementFallback=F;this.audioCaptures=[];this.videoCaptures=[];this.globalVolume=[1,1];this.playbacks=new Map;this.setPlaybackStrand=new T.Strand}async create(x,A){return new t(x,A)}receivePacket(x,A){this.playbackWorker?.receivePacket(x,A)}receiveMonitoredPacket(x,A){let F=A.slice();this.receivePacket(x,F)}async createAudioPlayback(x){let A=this.playbacks.get(x.uid),F=x.volume;if(A===void 0){F=F??[1,1];let D=new P(this,x.uid,x.customType);A={id:void 0,volume:F,playback:D},this.playbacks.set(x.uid,A)}return F!==void 0&&A.playback.setVolume(F),A.playback}async createAudioCapture(x){let A=new R(this,x);return await A.setDevice(x),this.audioCaptures.push(new WeakRef(A)),A}async createVideoCapture(x,A){let F=new y(this,A);return await F.setDevice(x),this.videoCaptures.push(new WeakRef(F)),F}playbackSetDevice(x){return this.setPlaybackStrand.enqueue(async()=>{let A=x?.device.deviceId??"";if(A==="default"&&(A=""),this.playbackWorker===void 0){let F=await this.audioContexts.acquire(48e3);this.playbackWorker=await rA(F),this.playbackSink=hF(this.playbackWorker,this.enableHTMLAudioElementFallback),this.playbackWorker.setGlobalVolume(this.globalVolume);for(let[,D]of this.playbacks)D.id!==void 0&&this.playbackWorker.addMedias(D.id.connectionId,[D.id.mediaId],D.volume)}if(x&&this.playbackSink!==void 0)try{await this.playbackSink.setSinkId(A)}catch(F){C("failed to set playback sink",F)}})}playbackSetGlobalVolume(x){this.globalVolume=x,this.playbackWorker?.setGlobalVolume(this.globalVolume)}playbackStart(x,A){let F=this.playbacks.get(x);F!==void 0&&(F.id!==void 0&&this.playbackStop(x,F.id),F.id=A,this.playbackWorker?.addMedias(A.connectionId,[A.mediaId],F.volume))}playbackStop(x,A){let F=this.playbacks.get(x);F!==void 0&&(F.id!==A&&C(`playback media ${A.mediaId} on connection ${A.connectionId} is out of sync`,F.id,A),F.id=void 0,this.playbackWorker?.removeMedias(A.connectionId,[A.mediaId]))}playbackGetActivity(x){let A=this.playbacks.get(x);return A?.id===void 0?I:this.playbackWorker?.getActivity(A.id)??I}playbackGetJitterStats(x){let A=this.playbacks.get(x);return A?.id===void 0?T.JITTER_STATS_INITIAL:this.playbackWorker?.getJitterStats(A.id)??T.JITTER_STATS_INITIAL}playbackSetVolume(x,A){let F=this.playbacks.get(x);F!==void 0&&(F.volume=A,F.id!==void 0&&this.playbackWorker?.setVolume(F.id,F.volume))}playbackGetVolume(x){return this.playbacks.get(x)?.volume??[1,1]}closePlayback(x){let A=this.playbacks.get(x);A!==void 0&&(A.id!==void 0&&this.playbackStop(x,A.id),this.playbacks.delete(x))}close(){this.playbackSink?.dispose(),this.playbackSink=void 0,this.playbackWorker?.close(),this.audioContexts.close()}async dump(){let x=[];for(let D of this.audioCaptures){let r=D.deref();r!==void 0&&x.push(await r.dump())}let A=[];for(let D of this.videoCaptures){let r=D.deref();r!==void 0&&A.push(await r.dump())}let F=[];for(let[D,r]of this.playbacks)F.push({uid:D,id:r.id||null,volume:r.volume});return{globalVolume:this.globalVolume,playbackWorker:await this.playbackWorker?.dump()||null,audioCaptures:x,videoCaptures:A,playbacks:F}}},ex=class{constructor(x,A=!1){this.device=x;this.isDefault=A}get type(){switch(this.device.kind){case"audioinput":return"AudioCapture";case"track":return"AudioCapture";case"audiooutput":return"AudioPlayback";default:(0,T.assert)(!1,"not supported device")}}get id(){return this.device.deviceId}get name(){return this.device.name}};var cx=require("@4players/odin-common"),BA=require("@msgpack/msgpack");b();var IF=require("@4players/odin-common");b();var $=require("@4players/odin-common"),z=require("@4players/odin-common/api");b();var Fx=class{constructor(x){this._Status=x;this._Listeners=new Set}get status(){return this._Status}set(x,A){if(!(x===this._Status||this._Status==="Closed")){this._Status=x;for(let F of[...this._Listeners])F(x,A)}}listen(x,A){A.aborted||(this._Listeners.add(x),A.addEventListener("abort",()=>this._Listeners.delete(x),{once:!0}))}};var X=require("@4players/odin-common"),Dx=require("@4players/odin-common/api"),Lx=require("@msgpack/msgpack");b();function Ox(t){return typeof t=="string"?t:t.type==="Failure"?`failed; ${t.reason}`:"succeeded"}var Q=class{constructor(x){this.stream=x;this._SendQueue=[];this._RecvQueue=[];this._EventQueue=[];this._Requests=new Map;this._Close=new AbortController;this._NextId=1;x instanceof WebSocket?(x.addEventListener("open",this._OnWebSocketOpen.bind(this)),x.addEventListener("close",this.close.bind(this)),x.addEventListener("message",A=>this._OnRpcMessage(A.data)),x.binaryType="arraybuffer"):(qF(x.readable.getReader(),this._OnRpcMessage.bind(this)).catch(A=>C("rpc stream reader failed",A)).finally(this.close.bind(this)),this._Writer=x.writable.getWriter()),this._Close.signal.addEventListener("abort",this._Cleanup.bind(this),{once:!0})}get closed(){return this._Close.signal.aborted}get closeSignal(){return this._Close.signal}async request(x,A,F){if(this.closed)return Promise.resolve("closed");let D=this._NextId,r=F===void 0?void 0:setTimeout(()=>this._TimeoutRequest(D),F);return this._Send([0,D,x,A]),new Promise(e=>{this._Requests.set(D,{accept:e,timeoutId:r}),this._NextId+=1})}notify(x,A){this.closed||this._Send([2,x,A])}recv(){if(this.closed)return Promise.resolve("closed");let x=this._EventQueue.shift();return x!==void 0?Promise.resolve(x):new Promise(A=>this._RecvQueue.push(A))}close(){this._Close.abort()}_TimeoutRequest(x){let A=this._Requests.get(x);A!==void 0&&(this._Requests.delete(x),clearTimeout(A.timeoutId),A.accept("timeout"))}_Send(x){let A;x instanceof Uint8Array?A=x:A=new Uint8Array((0,Lx.encode)(x,{ignoreUndefined:!0,forceFloat32:!0})),this.stream instanceof WebSocket?this.stream.send(A):this._Writer.write(A).catch(()=>{})}_OnWebSocketOpen(x){for(let A of this._SendQueue)this._Send(A);this._SendQueue.length=0}_OnRpcMessage(x){let A=mF(x);if(A.type!=="Success"){this.close();return}switch(A.value[0]){case 0:this._Send([1,A.value[1],"not supported",null]);break;case 1:this._OnResponse(A.value[1],A.value[2],A.value[3]);break;case 2:this._OnEvent(A.value[1],A.value[2]);break}}_OnResponse(x,A,F){let D=this._Requests.get(x);D!==void 0&&(clearTimeout(D.timeoutId),D.accept(A===null?(0,X.success)(F):(0,X.failure)(A)))}_OnEvent(x,A){let F=this._RecvQueue.shift();F!==void 0?F({name:x,properties:A}):this._EventQueue.push({name:x,properties:A})}_Cleanup(){for(let x of this._Requests.values())clearTimeout(x.timeoutId),x.accept("closed");this._Requests.clear();for(let x of this._RecvQueue)x("closed");this._RecvQueue.length=0,this._SendQueue.length=0,this.stream instanceof WebSocket?this.stream.close():this._Writer?.close().catch(()=>{})}},rx=class{constructor(x,A,F){this.rpc=x;this._Commands=A;this._Events=F}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(x,A,F){A=(0,Dx.parseRequest)(x,A,this._Commands);let D=await this.rpc.request(x,A,F);if(D==="closed"||D==="timeout"||D.type==="Failure")return D;let r=(0,Dx.parseResponse)(x,D.value,this._Commands);return r!==void 0?(0,X.success)(r):(0,X.failure)("response schema failed validation")}notify(x,A){A=(0,Dx.parseRequest)(x,A,this._Commands),this.rpc.notify(x,A)}async recv(){let x=await this.rpc.recv();if(x==="closed")return x;let A=a0(this._Events,x);return A!==void 0?A:(tA(this._Events,x.name)?(c(`schema validation for ${x.name} failed; closing connection`),this.rpc.close()):C(`dropping unknown event ${x.name}`),"closed")}close(){this.rpc.close()}};function mF(t){try{return(0,X.success)(Dx.MessagePackRpcSchema.parse((0,Lx.decode)(new Uint8Array(t))))}catch(x){return(0,X.failure)(String(x))}}function a0(t,x){if(!tA(t,x.name))return;let A=t[x.name].safeParse(x.properties);if(A.success)return{name:x.name,properties:A.data}}function tA(t,x){return x in t}async function qF(t,x){let A=new Uint8Array;for(;;){let F=P0(A,0);if(F===B){t.cancel("protocol violation").catch(()=>{});break}if(F!==q&&F<=A.length){x(A.subarray(0,F)),A=A.subarray(F);continue}let D;try{D=await t.read()}catch{break}if(D.done)break;A=GF(A,D.value)}A.length>0&&C("unprocessed bytes left in rpc stream",A)}function GF(t,x){if(t.length===0)return x;if(x.length===0)return t;let A=new Uint8Array(t.length+x.length);return A.set(t,0),A.set(x,t.length),A}var M=require("@4players/odin-common"),eA=require("@4players/odin-common/api");b();var g=class t{constructor(x,A){this.text=x;this.claims=A;if(A.ups!==void 0){let F=t.parse(A.ups);F.type==="Success"?this._Upstream=F.value:c(`upstream in token can not be parsed; ${F.reason}`)}}static parse(x){let A=x.split(".");if(A.length!==3)return(0,M.failure)("expected three segments");let F=(0,M.fromBase64Url)(A[1]);if(F.type==="Failure")return(0,M.failure)(`invalid token; ${F.reason}`);let D;try{D=JSON.parse(F.value)}catch(e){return(0,M.failure)(`invalid token; ${e}`)}let r=eA.TokenClaimsSchema.safeParse(D);return r.success===!1?(0,M.failure)(`invalid token; ${r.error}`):(0,M.success)(new t(x,r.data))}get timeLeft(){return this.claims.exp===void 0?1/0:this.claims.exp*1e3-Date.now()}get upstream(){return this._Upstream}get defaultRoomId(){return Array.isArray(this.claims.rid)?this.claims.rid.length===1?this.claims.rid[0]:void 0:this.claims.rid}hasAudience(x){return this.claims.aud===void 0&&x==="gateway"?!0:Array.isArray(this.claims.aud)?this.claims.aud.includes(x):this.claims.aud===x}toString(){return this.text}};var fx=require("@4players/odin-common");b();function jA(t){t.readyState!=="closed"&&t.close()}function Hx(t){t.connectionState!=="closed"&&t.close()}async function wx(t){let x=await t.getStats(),A=new Map;for(let r of t.getTransceivers())r.mid!==null&&A.set(r.mid,r.receiver.track.id);let F=new Map;if(x.forEach((r,e)=>{if(r.type!=="inbound-rtp"||typeof r.mid!="string")return;let j=A.get(r.mid);j!==void 0&&r.trackIdentifier!==j&&F.set(e,j)}),F.size===0)return x;let D=new Map;return x.forEach((r,e)=>{let j=F.get(e);D.set(e,j===void 0?r:{...r,trackIdentifier:j})}),D}var yF=["address","ip","relatedAddress","url"],sx=class{constructor(x,A,F){this._localVideos=new Map;this._remoteVideos=new Map;this._freeLocalVideoTransceivers=[];this._startingLocalVideos=new Map;this._closed=!1;this._negotiationRequested=!1;this._negotiationRunning=!1;this._negotiationCounter=0;this._pendingRemoteCandidates=[];this._WebRtcStatsSnapshot=null;this._peerConnection=x,this._signaling=A,this._answerTimeout=F?.answerTimeout??n.WebRtcAnswerTimeout,this._maxNegotiationAttempts=F?.maxNegotiationAttempts??n.WebRtcMaxNegotiationAttempts,this._negotiationCounter=F?.firstNegotiationId??0,this._peerConnection.ontrack=this._onTrack.bind(this),this._peerConnection.onconnectionstatechange=()=>this._onStatusChanged(),this._peerConnection.onicecandidate=D=>{(D.candidate?this._signaling.sendIceCandidate(D.candidate):this._signaling.sendIceComplete()).catch(e=>{C("failed to send local ice candidate",e)})},this._WebRtcStatsInterval=setInterval(()=>{this._snapshotStats().catch(()=>{})},n.WebRtcStatsSnapshotInterval)}requestNegotiation(){this._closed||(this._negotiationRequested=!0,!this._negotiationRunning&&(this._negotiationRunning=!0,setTimeout(async()=>{let x=0;for(;this._negotiationRequested&&!this._closed;){this._negotiationRequested=!1;try{await this._negotiate(),x=0}catch(A){if(this._closed)break;if(x+=1,c(`negotiation failed during sdp offer/answer exchange (attempt ${x})`,A),x<this._maxNegotiationAttempts)this._negotiationRequested=!0;else{this._negotiationRunning=!1,this._signaling.closeConnection("negotiation gave up").catch(()=>{});return}}}this._negotiationRunning=!1})))}startLocalVideo(x,A,F){if(this._localVideos.has(x))return Promise.resolve();let D=this._startingLocalVideos.get(x);if(D)return D;let r=this._startLocalVideo(x,A,F).finally(()=>this._startingLocalVideos.delete(x));return this._startingLocalVideos.set(x,r),r}async _startLocalVideo(x,A,F){f(`starting local video for media ${x}`);let D=F?.transform,r=this._freeLocalVideoTransceivers.pop();if(r){try{D?.attach(r.sender)}catch(o){throw this._freeLocalVideoTransceivers.push(r),o}await r.sender.replaceTrack(A),r.direction="sendonly"}else{r=this._peerConnection.addTransceiver(A,{direction:"sendonly"});try{D?.attach(r.sender)}catch(o){throw r.direction="inactive",r.sender.replaceTrack(null).catch(()=>{}),this._freeLocalVideoTransceivers.push(r),o}}let{transform:e,...j}=F??{};if(F&&(!D||Object.keys(j).length>0)){let o=r.sender.getParameters(),{maxBitrate:l,maxFramerate:Z,scaleResolutionDownBy:_}=F,px={...l!==void 0&&{maxBitrate:l},...Z!==void 0&&{maxFramerate:Z},..._!==void 0&&{scaleResolutionDownBy:_}};if(o.encodings.length===0)o.encodings.push(px);else for(let _A of o.encodings)Object.assign(_A,px);F.degradationPreference&&(o.degradationPreference=F.degradationPreference),await r.sender.setParameters(o)}let E=new fx.VideoCodec(F?.codec??n.DefaultVideoCodec).isSupported();E&&r.setCodecPreferences([E]),this._localVideos.set(x,{transceiver:r,transform:D}),this.requestNegotiation()}stopLocalVideo(x){let A=this._localVideos.get(x);A&&(f(`stopping local video for media ${x}`),this._localVideos.delete(x),A.transceiver.sender.track&&(A.transceiver.sender.track.enabled=!1),A.transceiver.direction="inactive",A.transceiver.sender.replaceTrack(null).catch(()=>{}),A.transform?.detach(),this._freeLocalVideoTransceivers.push(A.transceiver),this.requestNegotiation())}startRemoteVideo(x,A){let F=this._remoteVideos.get(x);if(F)return F.track;f(`starting remote video for media ${x}`);let D=this._peerConnection.addTransceiver("video",{direction:"recvonly"});A?.attach(D.receiver);let r,e=new Promise((j,v)=>{r={resolve:j,reject:v}});return e.catch(()=>{}),(0,fx.assert)(r!==void 0,"promise executor must run synchronously"),this._remoteVideos.set(x,{state:"Requested",transceiver:D,transform:A,promise:r,track:e}),this.requestNegotiation(),e}stopRemoteVideo(x){let A=this._remoteVideos.get(x);if(A){f(`stopping remote video for media ${x}`),this._remoteVideos.delete(x),A.state!=="Active"&&A.promise.reject(new Error("video stopped")),A.transform?.detach();try{A.transceiver.direction="inactive"}catch{}this.requestNegotiation()}}async handleWebRtcUpdate(x){if(!this._closed)try{switch(x.kind){case"Sdp":await this._updateRemoteSdp(x.type==="Answer"?"answer":"offer",x.sdp,x.media_map,x.negotiation_id);break;case"Trickle":this._addIceCandidate({candidate:x.candidate,sdpMid:x.spd_mid??void 0,sdpMLineIndex:x.spd_mline_index??void 0,usernameFragment:x.username_fragment??void 0});break;case"TrickleFinished":this._addIceCandidate(void 0);break}}catch(A){c(`failed to handle webrtc update '${x.kind}'`,A)}}startup(){this._peerConnection.connectionState==="new"&&this.requestNegotiation()}cleanup(){this._closed=!0,this._peerConnection.ontrack=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onicecandidate=null;for(let[,x]of this._remoteVideos)x.state!=="Active"&&x.promise.reject(new Error("connection closed"));this._pendingAnswer?.reject(new Error("connection closed")),this._pendingRemoteCandidates.length=0,clearTimeout(this._WebRtcIceTimeout),clearTimeout(this._WebRtcTimeout),clearInterval(this._WebRtcStatsInterval);for(let x of this._localVideos.values())x.transform?.detach();for(let x of this._remoteVideos.values())x.transform?.detach();this._localVideos.clear(),this._remoteVideos.clear(),this._startingLocalVideos.clear(),this._freeLocalVideoTransceivers.length=0}get stats(){return this._WebRtcStatsSnapshot}get peerConnection(){return this._peerConnection}get negotiationCounter(){return this._negotiationCounter}get localVideos(){return this._localVideos}get remoteVideos(){return this._remoteVideos}get isConnected(){return this._peerConnection.connectionState==="connected"}get isNegotiating(){return this._negotiationRunning}async _snapshotStats(){try{let x=await this._peerConnection.getStats(),A={},F={bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,rtt:0};x.forEach(D=>{let{type:r,...e}=D;if(r!=="certificate"){if(r==="local-candidate"||r==="remote-candidate")for(let j of yF)delete e[j];r==="candidate-pair"&&D.nominated&&(F.bytesSent+=D.bytesSent??0,F.bytesReceived+=D.bytesReceived??0,F.packetsSent+=D.packetsSent??0,F.packetsReceived+=D.packetsReceived??0,F.rtt=D.currentRoundTripTime??0),A[r]||(A[r]=[]),A[r].push(e)}}),this._WebRtcStatsSnapshot={timestamp:Date.now(),status:this._peerConnection.connectionState,stats:F,report:A}}catch{}}_addIceCandidate(x){if(x&&(x.sdpMid===void 0&&x.sdpMLineIndex===void 0&&(x={...x,sdpMid:"0"}),s("adding remote ice candidate")),this._peerConnection.remoteDescription===null){this._pendingRemoteCandidates.push(x);return}this._applyIceCandidate(x)}_applyIceCandidate(x){this._peerConnection.addIceCandidate(x).catch(A=>{C("failed to add remote ice candidate",A)})}_flushPendingIceCandidates(){let x=this._pendingRemoteCandidates.splice(0);for(let A of x)this._applyIceCandidate(A)}async _negotiate(){let x=++this._negotiationCounter,A=await this._peerConnection.createOffer();(0,fx.assert)(A.type==="offer"&&A.sdp,"generated broken payload"),await this._peerConnection.setLocalDescription(A);let F=[];for(let[r,{transceiver:e}]of this._localVideos)e.mid&&F.push([r,e.mid]);for(let[r,e]of this._remoteVideos)e.state!=="Active"&&e.transceiver.mid&&F.push([r,e.transceiver.mid]);let D=new Promise((r,e)=>{this._pendingAnswer={negotiationId:x,resolve:r,reject:e}});D.catch(()=>{});try{await gF((async()=>{await this._signaling.sendOffer(A.sdp,F,x),await D})(),this._answerTimeout,`timed out waiting for answer to offer ${x}`)}finally{this._pendingAnswer=void 0}}async _updateRemoteSdp(x,A,F,D){if(x==="offer"){C("ignoring unexpected sdp offer from server");return}let r=this._pendingAnswer;if(r===void 0){C("ignoring sdp answer without pending negotiation");return}if(D!==void 0&&D!==r.negotiationId){C(`ignoring stale sdp answer for negotiation ${D}; current is ${r.negotiationId}`);return}if(this._peerConnection.signalingState!=="have-local-offer"){C(`ignoring sdp answer in signaling state ${this._peerConnection.signalingState}`);return}let e=[];for(let[j,v]of F){let E=this._remoteVideos.get(j);if(E?.state==="Requested"){let o=E.transceiver.mid===v?E.transceiver:this._peerConnection.getTransceivers().find(l=>l.mid===v)??E.transceiver;o!==E.transceiver&&E.transform&&e.push({transform:E.transform,receiver:o.receiver}),this._remoteVideos.set(j,{state:"Mapped",transceiver:o,transform:E.transform,mid:v,promise:E.promise,track:E.track}),s(`updated remote video list with media ${j}`,E,this._remoteVideos)}}for(let{transform:j}of e)j.detach();for(let{transform:j,receiver:v}of e)try{j.attach(v)}catch(E){C("failed to move a video transform to its receiver",E)}try{await this._peerConnection.setRemoteDescription({type:x,sdp:A})}catch(j){r.reject(j);return}this._flushPendingIceCandidates(),r.resolve()}async _onStatusChanged(){switch(s(`peer connection state changed to ${this._peerConnection.connectionState}`),this._peerConnection.connectionState){case"closed":break;case"connected":clearTimeout(this._WebRtcIceTimeout),this._WebRtcIceTimeout=void 0,clearTimeout(this._WebRtcTimeout),this._WebRtcTimeout=void 0,this._signaling.onConnected?.();break;case"failed":this._peerConnection.restartIce(),this.requestNegotiation();case"disconnected":n.MainConnectionPingInterval!==void 0&&await this._signaling.checkConnection();default:this._WebRtcIceTimeout===void 0&&(this._WebRtcIceTimeout=setTimeout(()=>{s("ice connection timeout was reached"),this._peerConnection.restartIce(),this.requestNegotiation(),this._WebRtcIceTimeout=void 0},n.WebRtcIceTimeout)),this._WebRtcTimeout===void 0&&(this._WebRtcTimeout=setTimeout(async()=>{s("peer connection timeout was reached"),await this._signaling.closeConnection("peer connection timeout")},n.WebRtcTimeout));break}}_onTrack(x){let A=Array.from(this._remoteVideos).find(([,r])=>r.state==="Mapped"&&r.mid===x.transceiver.mid);if(!A){C(`unexpected track with mid: ${x.transceiver.mid}`);return}let[F,D]=A;(0,fx.assert)(D.state==="Mapped","expected video state to be Mapped"),this._remoteVideos.set(F,{state:"Active",transceiver:x.transceiver,transform:D.transform,track:D.track}),s(`updated local video list with media ${F}`,A,x.transceiver,this._localVideos),x.track.onended=()=>{s(`video track with mid ${x.transceiver.mid} ended`,A)},D.promise.resolve(x.track)}};function gF(t,x,A){return new Promise((F,D)=>{let r=setTimeout(()=>D(new Error(A)),x);t.then(e=>{clearTimeout(r),F(e)},e=>{clearTimeout(r),D(e)})})}b();var ix=class{constructor(x,A){this.host=x;this.delays=A;this._LocalVideos=new Map;this._RemoteVideos=new Map;this._Attempt=0}async startLocalVideo(x,A,F){this._LocalVideos.set(x,{track:A,options:F}),await(await this._Session()).startLocalVideo(x,A,F)}stopLocalVideo(x){this._LocalVideos.delete(x),this.host.currentSession()?.stopLocalVideo(x),this._ForgetAttemptsIfIdle()}startRemoteVideo(x,A){let F=this._RemoteVideos.get(x);if(F)return F.first;let D,r=new Promise((j,v)=>{D={resolve:j,reject:v}});r.catch(()=>{});let e={stream:new MediaStream,first:r,transform:A,settle:D};return this._RemoteVideos.set(x,e),this._Session().then(j=>this._RequestRemoteVideo(j,x)).catch(j=>{C(`failed to request remote video for media ${x}`,j)}),r}stopRemoteVideo(x){let A=this._RemoteVideos.get(x);A!==void 0&&(this._RemoteVideos.delete(x),A.settle?.reject(new Error("video stopped")),A.settle=void 0,this.host.currentSession()?.stopRemoteVideo(x),this._ForgetAttemptsIfIdle())}sessionConnected(){this._Attempt=0}sessionFailed(x){this.host.recycleSession(x),this._Schedule()}sessionReplaced(){clearTimeout(this._Timer),this._Timer=void 0,this._Recover().catch(x=>{C("replaying webrtc video onto the replaced session failed",x)})}giveUp(x){this._RejectPending(new Error(x))}close(){clearTimeout(this._Timer),this._Timer=void 0,this._RejectPending(new Error("connection closed")),this._LocalVideos.clear(),this._RemoteVideos.clear(),this.host.recycleSession("connection closed")}dump(){return{attempt:this._Attempt,scheduled:this._Timer!==void 0,localVideos:[...this._LocalVideos.keys()],remoteVideos:[...this._RemoteVideos.keys()]}}async _Session(){return this.host.currentSession()===void 0&&this._Timer===void 0&&(this._Attempt=0),this.host.ensureSession()}_Schedule(){if(this.host.isClosed()||this._Timer!==void 0||this._LocalVideos.size===0&&this._RemoteVideos.size===0)return;let x=this.delays[this._Attempt];if(x===void 0){C(`giving up on webrtc video after ${this._Attempt} recovery attempts; audio stays connected`),this._RejectPending(new Error("video recovery gave up"));return}this._Attempt+=1,f(`recovering webrtc video in ${x}ms (attempt ${this._Attempt} of ${this.delays.length})`),this._Timer=setTimeout(()=>{this._Timer=void 0,this._Recover().catch(A=>{C("webrtc video recovery failed",A),this.sessionFailed("recovery failed")})},x)}async _Recover(){if(this.host.isClosed()||this._LocalVideos.size===0&&this._RemoteVideos.size===0)return;let x=await this.host.ensureSession();for(let[A,{track:F,options:D}]of this._LocalVideos){if(F.readyState==="ended"){this._LocalVideos.delete(A);continue}x.startLocalVideo(A,F,D).catch(r=>{C(`failed to republish local video for media ${A}`,r)})}for(let A of this._RemoteVideos.keys())this._RequestRemoteVideo(x,A)}_RequestRemoteVideo(x,A){let F=this._RemoteVideos.get(A);F!==void 0&&x.startRemoteVideo(A,F.transform).then(D=>{if(this._RemoteVideos.get(A)===F){for(let r of F.stream.getVideoTracks())F.stream.removeTrack(r);F.stream.addTrack(D),F.settle?.resolve(F.stream),F.settle=void 0}}).catch(D=>{s(`remote video for media ${A} did not arrive`,D)})}_RejectPending(x){for(let A of this._RemoteVideos.values())A.settle?.reject(x),A.settle=void 0}_ForgetAttemptsIfIdle(){this._LocalVideos.size>0||this._RemoteVideos.size>0||(clearTimeout(this._Timer),this._Timer=void 0,this._Attempt=0)}};var Sx=class t{constructor(x,A,F,D,r,e,j){this.id=x;this.address=A;this.connection=D;this.datagramWritable=r;this.rpc=e;this.closeController=j;this._ConnectionStats={...$.CONNECTION_STATS_INITIAL};this._WebRtcUpdatesRunning=!1;this._NegotiationCounter=0;this._WebRtcSessionFlight=new Y;this._VideoRecovery=new ix({ensureSession:()=>this._EnsureWebRtcSession(),currentSession:()=>this._WebRtcSession,recycleSession:x=>this._RecycleWebRtcSession(x),isClosed:()=>this.closed},n.WebRtcRecoveryDelays);this._PingFlight=new Y;this._DatagramStatus=new Fx("Open");this._ClosePromise=(async()=>{try{await this.connection.closed}catch{}return"closed"})(),n.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(n.HealthCheckTimeout)},n.MainConnectionPingInterval)),j.signal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this.datagramWriter=r.getWriter(),this.connection.closed.catch(()=>{}).finally(()=>{this.closeController.abort("transport closed")}),this.readDatagrams(this.connection,this.id,(v,E)=>{this._ConnectionStats.packetsReceived+=1,F(v,E)}).catch(()=>{})}static async create(x,A,F,D){try{let r=new URL(`https://${A}?version=${O0}&uid=${ux}`),e=new AbortController;D.addEventListener("abort",()=>e.abort(),{once:!0});let j=new WebTransport(r);e.signal.addEventListener("abort",()=>{try{j.close()}catch{}},{once:!0}),await j.ready;let v=j.datagrams,E=v?.createWritable?.()??v?.writable;if(!E)return e.abort(),(0,$.failure)(`connecting to ${A} failed because WebTransport datagrams are not supported by this browser`);let o=await j.createBidirectionalStream(),l=new rx(new Q(o),z.MainCommandsRpc,z.MainNotificationsRpc);return e.signal.addEventListener("abort",()=>l.close(),{once:!0}),l.notify("Hello",{stream:"main"}),(0,$.success)(new t(x,A,F,j,E,l,e))}catch(r){return(0,$.failure)(`connecting to ${A} failed with ${r}`)}}get datagramStatus(){return this._DatagramStatus.status}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}onDatagramStatusChanged(x,A){this._DatagramStatus.listen(x,A)}close(){f(`closing connection to '${this.address}' with id ${this.id}`),this.closeController.abort("request")}async joinRoom(x,A,F,D){try{if(this.closed)return"closed";let r=await this.connection.createBidirectionalStream().catch(()=>"closed");if(r==="closed")return"closed";let e=new rx(new Q(r),z.RoomCommandsRpc,z.RoomNotificationsRpc),j=await e.request("Hello",{stream:"room",token:String(x),room_id:A,user_data:F,position:D});return j==="closed"||j.type==="Failure"?j:(0,$.success)(e.rpc)}catch(r){return(0,$.failure)(`JoinRoom failed; ${r}`)}}async getReconnectToken(x){let A=await this._Request("RequestReconnectToken",{peer_id:x});return A.type==="Failure"?A:g.parse(A.value)}async getRtcStats(){let x=this._PeerConnection;return x&&wx(x)}async healthCheck(){let x=await this._RequestPing(n.HealthCheckTimeout);return x||this.close(),x}async ping(x=3e4){let A=Date.now();return await this._RequestPing(x)?Date.now()-A:0}sendDatagram(x){if(!this.closed)try{this.datagramWriter.write(x).catch(()=>{}),this._ConnectionStats.packetsSent+=1;let A=x.byteLength;this.connectionStats.bytesSent+=A}catch{}}async readDatagrams(x,A,F){try{let D=x.datagrams.readable.getReader();for(;;){let r=await D.read();if(r.done)break;let e=r.value.byteLength;this.connectionStats.bytesReceived+=e,F(A,r.value)}}catch{}}_CleanUp(){s(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId),this._DatagramStatus.set("Closed"),this._VideoRecovery.close()}_RecycleWebRtcSession(x){let A=this._WebRtcSession,F=this._PeerConnection;A===void 0&&F===void 0||(C(`recycling webrtc session of connection ${this.id}; ${x}`),this._WebRtcSession=void 0,this._PeerConnection=void 0,A&&(this._NegotiationCounter=A.negotiationCounter,A.cleanup()),F&&Hx(F))}async _EnsureWebRtcSession(){return this._WebRtcSession?this._WebRtcSession:this._WebRtcSessionFlight.run(async()=>{this._PeerConnection=new RTCPeerConnection;let x=this._PeerConnection;return this._WebRtcSession=new sx(x,{sendOffer:async(A,F,D)=>{let r=await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:A,media_map:F,negotiation_id:D});if(r.type==="Failure")throw new Error(`failed to send sdp offer; ${r.reason}`)},sendIceCandidate:async A=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:A.candidate,spd_mid:A.sdpMid??void 0,spd_mline_index:A.sdpMLineIndex??void 0,username_fragment:A.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async A=>{this._PeerConnection===x&&this._VideoRecovery.sessionFailed(A)},onConnected:()=>{this._PeerConnection===x&&this._VideoRecovery.sessionConnected()},checkConnection:async()=>{}},{firstNegotiationId:this._NegotiationCounter}),this._HandleWebRtcUpdates().catch(A=>C("webrtc update loop failed",A)),this._WebRtcSession})}async _HandleWebRtcUpdates(){if(!this._WebRtcUpdatesRunning){for(this._WebRtcUpdatesRunning=!0;;){let x=await this.rpc.recv();if(x==="closed")break;x.name==="WebRtcUpdate"&&this._WebRtcSession?.handleWebRtcUpdate(x.properties).catch(()=>{})}this.close()}}async _Request(x,A,F){let D=Date.now(),r=await(F===void 0?this.rpc.request(x,A):this.rpc.request(x,A,F)),e=(Date.now()-D)/1e3;return x!=="Ping"&&s(`sent main rpc '${x}'; took: ${e}s; ${Ox(r)}`),r==="closed"?(0,$.failure)("connection lost"):r}_RequestPing(x=3e4){return this._PingFlight.run(async()=>{let A=await this._Request("Ping",{},x);return A!=="timeout"&&A.type==="Success"})}async startLocalVideo(x,A,F){await this._VideoRecovery.startLocalVideo(x,A,F)}stopLocalVideo(x){this._VideoRecovery.stopLocalVideo(x)}startRemoteVideo(x,A){return this._VideoRecovery.startRemoteVideo(x,A)}stopRemoteVideo(x){this._VideoRecovery.stopRemoteVideo(x)}async dump(){return{type:"H3",id:this.id,address:this.address,closed:this.closed,datagramStatus:this.datagramStatus,datagrams:{sent:this._ConnectionStats.packetsSent,received:this._ConnectionStats.packetsReceived},videoRecovery:this._VideoRecovery.dump(),webRtc:{signalingState:this._PeerConnection?.signalingState??null,connectionState:this._PeerConnection?.connectionState??null,iceGatheringState:this._PeerConnection?.iceGatheringState??null,iceConnectionState:this._PeerConnection?.iceConnectionState??null,connectionStats:this._WebRtcSession?.stats??null}}}};var p=require("@4players/odin-common"),Mx=require("@4players/odin-common/api");b();var L=require("@4players/odin-common");b();async function l0(t,x){let A=performance.now(),F=(0,L.failure)("no connection was attempted");for(let D=0;D<n.ConnectInterval.length&&!x.aborted;D++){let r=A+_F(D);if(await(0,L.abortableSleep)(r-performance.now(),x)==="aborted")return(0,L.failure)("aborted");if(F=await $F(t,x),F.type==="Success")return F}return F}async function $F(t,x){let A;try{A=new WebSocket(t)}catch(v){return(0,L.failure)(`unable to create websocket; ${v}`)}let F=new AbortController,D=new Promise(v=>A.addEventListener("open",()=>v((0,L.success)(A)),{signal:F.signal})),r=new Promise(v=>A.addEventListener("close",E=>v((0,L.failure)(E.reason!==""?E.reason:"unable to establish websocket connection")),{signal:F.signal})),e=new Promise(v=>x.addEventListener("abort",()=>v((0,L.failure)("aborted")),{signal:F.signal})),j=await Promise.race([D,r,e]);return F.abort(),j}function _F(t){let x=n.ConnectInterval.slice(0,t).reduce((F,D)=>F+D,0),A=n.ConnectInterval[t]*Math.random();return x+A}b();var Rx=class{constructor(x,A,F){this.host=x;this.delays=A;this.status=F;this._Attempt=0;this._WasOpen=!1}opened(){this._Attempt=0,this._WasOpen=!0,this.status.set("Open")}interrupted(x){this.status.status!=="Failed"&&this.status.set(this._Pending(),x)}failed(x){this.host.isClosed()||(this.host.recycle(x),this.status.status!=="Failed"&&this.status.set(this._Pending(),x),this._Schedule(x))}retry(x){this.host.isClosed()||this.status.status!=="Failed"||(f(`retrying webrtc datagram path; ${x}`),this._Attempt=0,this.status.set(this._Pending(),x),this._Build())}ensure(){this._Timer!==void 0?(clearTimeout(this._Timer),this._Timer=void 0,this._Build()):this.retry("transport requested")}close(){clearTimeout(this._Timer),this._Timer=void 0,this.status.set("Closed")}dump(){return{attempt:this._Attempt,scheduled:this._Timer!==void 0,wasOpen:this._WasOpen}}_Pending(){return this._WasOpen?"Reconnecting":"Connecting"}_Schedule(x){if(this.host.isClosed()||this._Timer!==void 0||this.status.status==="Failed")return;let A=this.delays[this._Attempt];if(A===void 0){if(this._WasOpen&&this.host.fallBack(x))return;C(`giving up on the webrtc datagram path after ${this._Attempt} rebuilds; ${x}`),this.status.set("Failed",x);return}this._Attempt+=1,f(`rebuilding webrtc peer connection in ${A}ms (attempt ${this._Attempt} of ${this.delays.length})`),this._Timer=setTimeout(()=>{this._Timer=void 0,this._Build()},A)}_Build(){if(!this.host.isClosed())try{this.host.build()}catch(x){this.failed(`unable to build peer connection; ${x}`)}}};var Tx=class t{constructor(x,A,F,D,r){this.id=x;this.address=A;this.url=F;this.onDatagram=D;this.connection=r;this._PeerIdMap=new WeakMap;this._ConnectionStats={...p.CONNECTION_STATS_INITIAL};this._NegotiationCounter=0;this._DatagramStatus=new Fx("Connecting");this._PingFlight=new Y;f(`creating new webrtc connection to '${this.address}' with id ${this.id}`),this.closeSignal.addEventListener("abort",()=>this._CleanUp(),{once:!0}),this._ClosePromise=new Promise(e=>{this.closeSignal.addEventListener("abort",()=>{e("closed")},{once:!0})}),this._Recovery=new Rx({build:()=>{this._BuildTransport(),this._VideoRecovery.sessionReplaced()},recycle:e=>this._RecycleTransport(e),fallBack:e=>(C(`webrtc peer connection could not be rebuilt; reconnecting connection ${this.id}; ${e}`),this.close(),!0),isClosed:()=>this.closed},n.WebRtcRecoveryDelays,this._DatagramStatus),this._VideoRecovery=new ix({ensureSession:async()=>{if(this._Transport===void 0&&this._Recovery.ensure(),this._Transport===void 0)throw new Error("webrtc peer connection is unavailable");return this._Transport.session},currentSession:()=>this._Transport?.session,recycleSession:e=>this._Recovery.failed(e),isClosed:()=>this.closed},n.WebRtcRecoveryDelays),this._DatagramStatus.listen((e,j)=>{e==="Failed"&&this._VideoRecovery.giveUp(j??"webrtc recovery gave up")},this.closeSignal),this._BuildTransport(),addEventListener("online",()=>this._Recovery.retry("network is back"),{signal:this.closeSignal}),n.MainConnectionPingInterval!==void 0&&(this._PingIntervalId=setInterval(async()=>{this.connectionStats.rtt=await this.ping(n.HealthCheckTimeout)},n.MainConnectionPingInterval)),this._HandleWebRtcUpdates().catch(e=>C("webrtc update loop failed",e))}static async create(x,A,F,D){if(D.aborted)return(0,p.failure)("aborted");let r;try{r=new URL(`wss://${A}`)}catch(E){return(0,p.fail)(`address in token(${A}) can not be parsed; ${E}`)}let e=(0,p.extendUrl)(r,`main?uid=${ux}`);if(e.type!=="Success")return e;let j=await l0(e.value,D);if(j.type!=="Success")return j;let v=new rx(new Q(j.value),Mx.MainCommandsRpc,Mx.MainNotificationsRpc);try{return(0,p.success)(new t(x,A,r,F,v))}catch(E){return v.close(),(0,p.failure)(`unable to create webrtc connection; ${E}`)}}get datagramStatus(){return this._DatagramStatus.status}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}onDatagramStatusChanged(x,A){this._DatagramStatus.listen(x,A)}close(){f(`closing ${this.transport} connection to '${this.address}' with id ${this.id}`),this.connection.close()}async joinRoom(x,A,F,D){let r=await this.connection.request("JoinRoom",{token:String(x),room_id:A,user_data:F,position:D});if(r==="closed"||r.type==="Failure")return r;let e=r.value;if(!("token"in e))return(0,p.failure)("JoinRoom responded without token");let j=(0,p.extendUrl)(this.url,`room?token=${e.token}`);if(j.type==="Failure")return j;let v=await l0(j.value,this.closeSignal);return v.type==="Success"?(this._PeerIdMap.set(v.value,e.peer_id),(0,p.success)(new Q(v.value))):v}async getReconnectToken(x){let A=await this._Request("RequestReconnectToken",{peer_id:x});return A.type==="Failure"?A:g.parse(A.value)}async getRtcStats(){let x=this._Transport;return x&&wx(x.peerConnection)}async healthCheck(){let x=await this._RequestPing(n.HealthCheckTimeout);return x||this.close(),x}async ping(x=3e4){let A=Date.now();return await this._RequestPing(x)?Date.now()-A:0}sendDatagram(x){let A=this._Transport?.audioChannel;if(A?.readyState==="open"){let F=x.byteLength;A.send(x),this._ConnectionStats.packetsSent+=1,this._ConnectionStats.bytesSent+=F}}_CleanUp(){s(`performing cleanup for connection ${this.id}`),clearInterval(this._PingIntervalId),this._Recovery.close(),this._VideoRecovery.close(),this._RecycleTransport("connection closed"),this.connection.close()}_BuildTransport(){let x=new RTCPeerConnection,A;try{A=x.createDataChannel("audio",{id:2,negotiated:!0,ordered:!1,maxRetransmits:0})}catch(v){throw x.close(),v}let F=this.id;A.binaryType="arraybuffer",A.onmessage=v=>{this._ConnectionStats.packetsReceived++;let E=new Uint8Array(v.data);this._ConnectionStats.bytesReceived+=E.byteLength,this.onDatagram(this.id,E)},A.onerror=v=>C(`webrtc audio data channel for connection with id ${F} raised an error`,v),A.onclosing=v=>f(`webrtc audio data channel for connection with id ${F} begins shutting down`,v),A.onclose=v=>f(`webrtc audio data channel for connection with id ${F} has closed`,v);let D=()=>this._Transport?.peerConnection===x,r=new AbortController,e=()=>{D()&&this._UpdateDatagramStatus()};A.addEventListener("open",e,{signal:r.signal}),A.addEventListener("close",()=>{D()&&this._Recovery.failed("audio data channel closed")},{signal:r.signal}),x.addEventListener("connectionstatechange",e,{signal:r.signal});let j=new sx(x,{sendOffer:async(v,E,o)=>{let l=await this._Request("WebRtcUpdate",{kind:"Sdp",type:"Offer",sdp:v,media_map:E,negotiation_id:o});if(l.type==="Failure")throw new Error(`failed to send sdp offer; ${l.reason}`)},sendIceCandidate:async v=>{await this._Request("WebRtcUpdate",{kind:"Trickle",candidate:v.candidate,spd_mid:v.sdpMid??void 0,spd_mline_index:v.sdpMLineIndex??void 0,username_fragment:v.usernameFragment??void 0})},sendIceComplete:async()=>{await this._Request("WebRtcUpdate",{kind:"TrickleFinished"})},closeConnection:async v=>{D()&&this._Recovery.failed(v)},checkConnection:async()=>{this.healthCheck().catch(()=>{})}},{firstNegotiationId:this._NegotiationCounter});this._Transport={peerConnection:x,audioChannel:A,session:j,listeners:r},j.startup()}_RecycleTransport(x){let A=this._Transport;A!==void 0&&(C(`recycling webrtc peer connection of connection ${this.id}; ${x}`),this._Transport=void 0,this._NegotiationCounter=A.session.negotiationCounter,A.listeners.abort(),A.session.cleanup(),jA(A.audioChannel),Hx(A.peerConnection))}_UpdateDatagramStatus(){let x=this._Transport;if(x===void 0)return;let A=x.peerConnection.connectionState;x.audioChannel.readyState==="open"&&A==="connected"?(this._Recovery.opened(),this._VideoRecovery.sessionConnected()):this._Recovery.interrupted(`peer connection is ${A}`)}async _HandleWebRtcUpdates(){for(;;){let x=await this.connection.recv();if(x==="closed")break;x.name==="WebRtcUpdate"&&this._Transport?.session.handleWebRtcUpdate(x.properties).catch(()=>{})}this.close()}async _Request(x,A,F){let D=Date.now(),r=await(F===void 0?this.connection.request(x,A):this.connection.request(x,A,F)),e=(Date.now()-D)/1e3;return x!=="Ping"&&s(`sent main rpc '${x}'; took: ${e}s; ${Ox(r)}`),r==="closed"?(0,p.failure)("connection lost"):r}_RequestPing(x=3e4){return this._PingFlight.run(async()=>{let A=await this._Request("Ping",{},x);return A!=="timeout"&&A.type==="Success"})}async startLocalVideo(x,A,F){await this._VideoRecovery.startLocalVideo(x,A,F)}stopLocalVideo(x){this._VideoRecovery.stopLocalVideo(x)}startRemoteVideo(x,A){return this._VideoRecovery.startRemoteVideo(x,A)}stopRemoteVideo(x){this._VideoRecovery.stopRemoteVideo(x)}async dump(){let x=this._Transport;return{type:"WebRtc",id:this.id,address:this.address,url:this.url.toString(),closed:this.closed,datagramStatus:this.datagramStatus,recovery:this._Recovery.dump(),videoRecovery:this._VideoRecovery.dump(),audioChannel:x?{readyState:x.audioChannel.readyState,bufferedAmount:x.audioChannel.bufferedAmount}:null,datagrams:{sent:this.connectionStats.packetsSent,received:this.connectionStats.packetsReceived},webRtc:x?{signalingState:x.peerConnection.signalingState,connectionState:x.peerConnection.connectionState,iceGatheringState:x.peerConnection.iceGatheringState,iceConnectionState:x.peerConnection.iceConnectionState,connectionStats:x.session.stats}:null}}};function vA(t,x,A,F,D){switch(f(`creating ${x} main connection to '${A}'`),x){case"H3":return Sx.create(t,A,F,D);case"WebRTC":return Tx.create(t,A,F,D);default:throw new Error(`transport ${x} is not supported`)}}var ox=require("@4players/odin-common"),O=require("@4players/odin-common/api");b();var Jx=class{constructor(x,A,F,D){this.id=x;this.connection=A;this.cipher=F;this.mediaMap=D;this._DatagramReceived=0;this._DatagramSent=0;this._DatagramReceivedInvalid=0;this._DatagramSentInvalid=0;A.closeSignal.addEventListener("abort",()=>this.close())}get connectionStats(){return this.connection.connectionStats}get transport(){return this.connection.transport}get address(){return this.connection.address}get datagramStatus(){return this.closed?"Closed":this.connection.datagramStatus}get closePromise(){return this.connection.closePromise}get closeSignal(){return this.connection.closeSignal}get closed(){return this.connection.closed}onDatagramStatusChanged(x,A){this.connection.onDatagramStatusChanged(x,A)}close(){this.connection.close()}async joinRoom(x,A,F,D){this.cipher.reset().catch(j=>C("cipher reset failed",j));let r=await this.cipher.encryptUserData(F);if(r===B)return(0,ox.failure)("unable to encrypt initial user-data");let e=await this.connection.joinRoom(x,A,r,D);return e==="closed"||e.type==="Failure"?e:(0,ox.success)(new u0(e.value,this.cipher,this))}getReconnectToken(x){return this.connection.getReconnectToken(x)}getRtcStats(){return this.connection.getRtcStats()}healthCheck(){return this.connection.healthCheck()}sendDatagram(x){this.cipher.encryptDatagram(x).then(A=>{A!==B?(this._DatagramSent+=1,this.connection.sendDatagram(A)):this._DatagramSentInvalid+=1}).catch(A=>C("datagram encryption failed",A))}async decryptDatagram(x,A){let F=await this.cipher.decryptDatagram(x,A);return F!==B?this._DatagramReceived+=1:this._DatagramReceivedInvalid+=1,F}startLocalVideo(x,A,F){return this.connection.startLocalVideo(x,A,{...F,transform:this.cipher.createVideoSenderTransform(x)})}stopLocalVideo(x){this.connection.stopLocalVideo(x),this.cipher.releaseVideoSenderTransform(x)}startRemoteVideo(x){let A=this.mediaMap.get(k({connectionId:this.connection.id,mediaId:x}));return this.connection.startRemoteVideo(x,this.cipher.createVideoReceiverTransform(x,A?.peerId))}stopRemoteVideo(x){this.connection.stopRemoteVideo(x),this.cipher.releaseVideoReceiverTransform(x)}async dump(){return{type:"Encrypted",id:this.id,address:this.address,connectionId:this.connection.id,closed:this.closed,transport:this.transport,datagrams:{sent:this._DatagramSent,received:this._DatagramReceived,sentInvalid:this._DatagramSentInvalid,receivedInvalid:this._DatagramReceivedInvalid},cipher:await this.cipher.dump()}}},Vx=class{constructor(x){this.room=x}resendUserData(){this.room.roomConnection?.notify("UpdatePeer",{user_data:this.room.roomConnection.userData})}setUserData(x,A){let F={kind:"UserDataChanged",peer_id:x,user_data:A};this.room.onEvent("PeerUpdated",F)}},u0=class{constructor(x,A,F){this.rpc=x;this.cipher=A;this.connection=F;this.peers=new Map;this.closeSignal.addEventListener("abort",this.cleanup.bind(this),{once:!0})}get closed(){return this.rpc.closed}get closeSignal(){return this.rpc.closeSignal}async request(x,A,F){let D=await this.outgoing(x,A);return D===B?(0,ox.failure)("can not be encrypted"):await this.rpc.request(x,D,F)}notify(x,A){this.outgoing(x,A).then(F=>{F!==B&&this.rpc.notify(x,F)}).catch(F=>C(`encrypting notification '${x}' failed`,F))}async recv(){for(;;){let x=await this.rpc.recv();if(x==="closed")return x;let A=await this.incoming(x.name,x.properties);if(A!==B)return{name:x.name,properties:A}}}close(){return this.rpc.close()}async outgoing(x,A){if(!(x in O.RoomCommandsRpc))return A;let F=(0,O.parseCommand)(x,A,O.RoomCommandsRpc);if(F===void 0)return B;switch(F.name){case"UpdatePeer":{let D=await this.cipher.encryptUserData(F.request.user_data);if(D===B)return B;F.request.user_data=D}break;case"SendMessage":{let D=await this.cipher.encryptMessage(F.request.message);if(D===B)return B;F.request.message=D}break}return F.request}async incoming(x,A){if(!(x in O.RoomNotificationsRpc))return A;let F=(0,O.parseNotification)(x,A,O.RoomNotificationsRpc);if(F===void 0)return B;switch(F.name){case"RoomUpdated":for(let D=0;D<F.properties.updates.length;D++){let r=await this.roomUpdate(F.properties.updates[D]);if(r===B)return B;F.properties.updates[D]=r}break;case"PeerUpdated":{let D=await this.peerUpdate(F.properties);if(D===B)return B;F.properties=D}break;case"MessageReceived":{let D=await this.cipher.decryptMessage(F.properties.sender_peer_id,F.properties.message);if(D===B)return B;F.properties.message=D}break}return F.properties}async peerUpdate(x){switch(x.kind){case"UserDataChanged":{let A=await this.cipher.decryptUserData(x.peer_id,x.user_data);if(A===B)return B;x.user_data=A}break;case"MediaStarted":this.mediaStarted(x.peer_id,x.media.id);break;case"MediaStopped":this.mediaStopped(x.peer_id,x.media_id);break}return x}async roomUpdate(x){switch(x.kind){case"Joined":for(let A of x.room.peers){for(let D of A.medias)this.mediaStarted(A.id,D.id);let F=await this.cipher.decryptUserData(A.id,A.user_data);F!==B?A.user_data=F:A.user_data=new Uint8Array}break;case"PeerJoined":{for(let F of x.peer.medias)this.mediaStarted(x.peer.id,F.id);let A=await this.cipher.decryptUserData(x.peer.id,x.peer.user_data);A!==B?x.peer.user_data=A:x.peer.user_data=new Uint8Array}break;case"PeerLeft":{let A=this.peers.get(x.peer_id);this.peers.delete(x.peer_id),this.cipher.deletePeerKey(x.peer_id);for(let F of A??[])this.mediaStopped(x.peer_id,F)}break}return x}mediaStarted(x,A){let F=this.peers.get(x);F===void 0&&(F=new Set,this.peers.set(x,F)),F.add(A);let D=k({connectionId:this.connection.connection.id,mediaId:A});this.connection.mediaMap.set(D,{peerId:x,connection:this.connection})}mediaStopped(x,A){this.peers.get(x)?.delete(A);let D=k({connectionId:this.connection.connection.id,mediaId:A});this.connection.mediaMap.delete(D)}cleanup(){for(let[x,A]of this.peers)for(let F of A)this.mediaStopped(x,F)}};var Ux=class{constructor(x){this.onDatagram=x;this._LastConnectionId=0;this._Connections=new Map;this._Close=new AbortController;this._MediaMap=new Map;let A=Date.now(),F=setInterval(()=>{Math.abs(Date.now()-A)>n.ClockJumpThreshold&&this.checkHealth(),A=Date.now()},n.ClockJumpCheckInterval);addEventListener("offline",()=>this.checkHealth(),{signal:this._Close.signal}),this._Close.signal.addEventListener("abort",()=>{clearInterval(F);for(let D of this._Connections.values())D.type==="establishing"?D.abort.abort():D.connection.close();this._Connections.clear()},{once:!0})}get closed(){return this._Close.signal.aborted}sendDatagram(x,A){let F=this._Connections.get(x);(F?.type==="established"||F?.type==="virtual")&&F.connection.sendDatagram(A)}async recvDatagram(x,A){let F=NF(A);if(F===void 0||F.length===0)return;let D=this._MediaMap.get(k({connectionId:x,mediaId:F[0]}));if(D===void 0)this.onDatagram(x,A);else{let r=await D.connection.decryptDatagram(D.peerId,A);if(r===B)return;this.onDatagram(D.connection.id,r)}}async acquireConnection(x,A,F,D){if(await(0,cx.nextTick)(),this.closed)return"closed";let r=this.findConnection(x,A),e;switch(r?.type){case"established":s(`reusing existing connection ${r.id}`),e=r;break;case"establishing":{s(`waiting for connecting to '${A}' finish`);let E=await r.finished;if(E.type!=="Success")return E;e=E.value}break;case void 0:{s(`connecting to '${A}'`);let E=await this.createConnection(x,A,D);if(E.type!=="Success")return E;e=E.value}break}let j=e.id,v=new c0(e.connection,()=>this.releaseConnection(j));return e.references+=1,F&&(v=new Jx(++this._LastConnectionId,v,F,this._MediaMap),this.addConnection({type:"virtual",id:v.id,connection:v,createdAt:Date.now()})),(0,cx.success)(v)}async createConnection(x,A,F){let D=++this._LastConnectionId,r=Date.now(),e=new AbortController;F.addEventListener("abort",()=>e.abort(),{once:!0}),s(`creating new connection ${D}`);let j=vA(D,x,A,(Z,_)=>{this.recvDatagram(Z,_).catch(px=>s("dropping datagram",px))},F),{promise:v,resolve:E}=Promise.withResolvers();this.addConnection({type:"establishing",id:D,address:A,transport:x,finished:v,createdAt:Date.now(),abort:e});let o=await j;if(this._Connections.delete(D),o.type!=="Success")return E(o),o;let l={type:"established",id:D,address:A,transport:x,createdAt:r,references:0,connection:o.value};return this.addConnection(l),(0,cx.success)(l)}addConnection(x){(x.type==="established"||x.type==="virtual")&&x.connection.closeSignal.addEventListener("abort",()=>{f(`connection ${x.id} has been closed`),this._Connections.delete(x.id)},{once:!0}),this._Connections.set(x.id,x)}releaseConnection(x){let A=this._Connections.get(x);A?.type==="established"&&(A.references-=1,A.references<=0&&A.connection.close())}checkHealth(){for(let x of this._Connections.values())x.type==="established"&&x.connection.healthCheck().catch(()=>{})}close(){this._Close.abort()}async dump(){let x=[];for(let F of this._Connections.values()){let D;switch(F.type){case"established":D={transport:F.transport,address:F.address,connection:await F.connection.dump(),references:F.references};break;case"establishing":D={transport:F.transport,address:F.address,aborted:F.abort.signal.aborted};break;case"virtual":D={connection:await F.connection.dump()};break}x.push({type:F.type,id:F.id,createdAt:F.createdAt,...D})}let A=[];for(let[F,D]of this._MediaMap)A.push(`${F} -> ${D.peerId} @${D.connection.id} `);return{lastConnectionId:this._LastConnectionId,connections:x,mediaMap:A,closed:this.closed}}findConnection(x,A){for(let F of this._Connections.values())if(F.type!=="virtual"&&F.transport===x&&F.address===A&&(F.type!=="established"||!F.connection.closed))return F}},c0=class{constructor(x,A){this.connection=x;this.release=A;this.closeController=new AbortController;this.closePromise=new Promise(x=>this.closeController.signal.addEventListener("abort",()=>x("closed"),{once:!0}));x.closeSignal.addEventListener("abort",()=>this.close(),{once:!0})}get closeSignal(){return this.closeController.signal}get closed(){return this.closeSignal.aborted}close(){this.release(),this.closeController.abort("closed")}get connectionStats(){return this.connection.connectionStats}get id(){return this.connection.id}get transport(){return this.connection.transport}get address(){return this.connection.address}get datagramStatus(){return this.closed?"Closed":this.connection.datagramStatus}onDatagramStatusChanged(x,A){this.connection.onDatagramStatusChanged(x,A)}joinRoom(x,A,F,D){return this.connection.joinRoom(x,A,F,D)}getReconnectToken(x){return this.connection.getReconnectToken(x)}getRtcStats(){return this.connection.getRtcStats()}healthCheck(){return this.connection.healthCheck()}sendDatagram(x){return this.connection.sendDatagram(x)}startLocalVideo(x,A,F){return this.connection.startLocalVideo(x,A,F)}stopLocalVideo(x){return this.connection.stopLocalVideo(x)}startRemoteVideo(x,A){return this.connection.startRemoteVideo(x,A)}stopRemoteVideo(x){return this.connection.stopRemoteVideo(x)}async dump(){let x=await this.connection.dump();return typeof x=="object"&&(x={...x,isShared:!0,referenceClosed:this.closed}),x}};function NF(t){let x;try{x=(0,BA.decode)(t)}catch{return}if(!Array.isArray(x)||x.length<2)return;let A=x[1];if(Array.isArray(A))return A.map(Number)}var dx=require("@4players/odin-common"),H=class{constructor(x,A){this.uid=x;this.customType=A}#x;#A;get mediaStream(){return this.#x}get audioPlayback(){return(0,dx.assert)(this.#A,"getting the audioPlayback failed, this video has no Audio"),this.#A}get volume(){return(0,dx.assert)(this.audioPlayback,"getting the volume failed, this video has no Audio"),this.audioPlayback.volume}setVolume(x){(0,dx.assert)(this.#A,"Can not set the volume, this video has no Audio"),this.#A.setVolume(x)}setMediaStream(x){this.#x=x}close(){this.#x?.getVideoTracks().forEach(x=>{x.stop(),this.#x?.removeTrack(x)}),this.#x=void 0}};var S=require("@4players/odin-common"),p0=require("@4players/odin-common/api");var a=require("@4players/odin-common"),J=require("@4players/odin-common/api");b();var Kx=class{constructor(x,A,F,D,r,e,j,v,E,o){this.connectionPool=x;this.transport=A;this.onEvent=F;this.gateway=D;this.roomId=e;this.cipher=E;this.disableAutoReconnect=o;this._Close=new AbortController;this._TokenUsed=!1;this._WasConnected=!1;this._FailedConnections=0;this._LastTokenRenew=performance.now();this._LastReconnectStartedAt=0;this._ReconnectingSince=0;this._DatagramStatus="Connecting";this._DatagramsWereOpen=!1;this._Closed=new Promise(x=>this._Close.signal.addEventListener("abort",()=>x(this._Close.signal.reason?"disconnected":"closed"),{once:!0}));this._Token=r,this._UserData=j,this._Position=v,this._Main().then(({reason:l})=>s(`_Main() resolved; ${l}`),l=>c(`_Main() rejected; ${l}`))}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}get datagramStatus(){return this._DatagramStatus}async requestUnsafe(x,A){if(this._RoomConnection===void 0)return(0,a.failure)("currently not connected");let F=await this._RoomConnection.request(x,A,void 0);return(0,a.assert)(F!=="timeout","request should not timeout"),F!=="closed"&&F.type==="Success"&&this._HandleRequests(x,A,F.value),F}async request(x,A){let F=Date.now(),D=await this.requestUnsafe(x,A),r=(Date.now()-F)/1e3;if(s(`sent room rpc '${x}'; took: ${r}s`,{properties:A,result:D}),D==="closed"||D.type==="Failure")return D;let e=(0,J.parseResponse)(x,D.value,J.RoomCommandsRpc);return e!==void 0?(0,a.success)(e):(0,a.failure)(`received invalid response from ${x}`)}notify(x,A){this._RoomConnection!==void 0&&this._RoomConnection.notify(x,A)}close(){this._Close.abort(!0)}get renewTokenIn(){let x=this._LastTokenRenew-performance.now()+n.MinTokenRefreshInterval,A=this._Token.timeLeft-n.MinTokenLifetime;return Math.max(x,A)}async _Main(){let x;for(let A=0;;this._FailedConnections++){if(await(0,a.sleep)(Math.max(A-performance.now(),0)),this._Close.signal.aborted||this.connectionPool.closed){x="user requested";break}if(this._WasConnected&&this._ReconnectingSince!==0&&CA(this._ReconnectingSince,n.MaxReconnectDuration)){x="reconnect time limit reached";break}if(A=performance.now()+1e3,this._TokenUsed=!0,this._Token.hasAudience("sfu")){let F=await this._ConnectToServer();if(F.type==="Success"&&F.value==="shutdown"){s("connection closed by user request; shutting down"),x="user requested";break}if(this.disableAutoReconnect&&this._WasConnected){x=F.type==="Failure"?F.reason:"connection lost";break}if(this._LastReconnectStartedAt===0&&(this._LastReconnectStartedAt=performance.now()),this._WasConnected&&this._ReconnectingSince===0&&(this._ReconnectingSince=performance.now()),F.type==="Failure"&&!this._WasConnected&&this._FailedConnections>=3){x=F.reason;break}if(F.type==="Failure"&&!CA(this._LastReconnectStartedAt))continue}if(this.reset(),this._Close.signal.aborted||this.connectionPool.closed){x="user requested";break}if(this.gateway!==void 0&&this._Token.hasAudience("gateway")){this._ChangeStatus("Joining",`requesting new token from ${this.gateway}`);let F=await PF(this.gateway,this._Token,this._Close.signal);if(F.type==="Success")if(F.value instanceof g)A=0,this._Token=F.value,this._TokenUsed=!1;else{x=`gateway error; ${F.value}`;break}else if(!this._WasConnected&&this._FailedConnections>=3){x="unable to contact the gateway";break}}if(this._TokenUsed&&this._Token.timeLeft<=0){x="token has expired";break}if(this._Close.signal.aborted||this.connectionPool.closed){x="user requested";break}}return this._ChangeDatagramStatus("Closed",x),this._ChangeStatus("Closed",x),this.close(),(0,a.failure)(x)}async _ConnectToServer(){let x=this._Token;for(;x.upstream!==void 0;)x=x.upstream;let A=x.claims.adr??this.gateway?.toString();if(!A)return(0,a.success)("continue");if(this._ChangeStatus("Joining",`connecting to ${x.claims.adr}`),this._MainConnection===void 0||this._MainConnection.closed||this._MainConnection.address!==x.claims.adr){this._MainConnection?.close();let j=await this.connectionPool.acquireConnection(this.transport,A,this.cipher,this._Close.signal);if(j==="closed")return(0,a.failure)("connection pool closed");if(j.type==="Failure")return this._ChangeStatus("Joining",`connection failed; ${j.reason}`),(0,a.failure)(`connection failed; ${j.reason}`);this._MainConnection=j.value,this._OwnPeerId=void 0}let F=await Promise.race([Promise.all([this._MainConnection.joinRoom(x,this.roomId,this.userData,this.position)]),(0,a.sleep)(n.ConnectTimeout,"timeout"),this._Closed]);if(F==="closed"||F==="disconnected")return(0,a.success)("continue");if(F==="timeout")return this._ChangeStatus("Joining","timed out"),(0,a.success)("continue");let[D]=F;if(D==="closed")return(0,a.success)("continue");if(D.type==="Failure")return(0,a.failure)(`unable to join room; ${D.reason}`);this._RoomConnection?.close(),this._RoomConnection=D.value,this._WasConnected=!0,this._FailedConnections=0,this._ReconnectingSince=0,this._ChangeStatus("Joined",`joined ${this.roomId}`);let r=this._MainConnection,e=new AbortController;r.onDatagramStatusChanged((j,v)=>this._ChangeDatagramStatus(j==="Closed"?this._PendingDatagramStatus():j,v),e.signal),this._ChangeDatagramStatus(r.datagramStatus);try{let j=await this._HandleConnection(r);return(0,a.success)(j?"shutdown":"continue")}catch(j){return(0,a.failure)(`unable to handle connection; ${j}`)}finally{e.abort(),this._ChangeDatagramStatus(this._PendingDatagramStatus())}}_PendingDatagramStatus(){return this._DatagramsWereOpen?"Reconnecting":"Connecting"}_ChangeDatagramStatus(x,A){if(x===this._DatagramStatus||this._DatagramStatus==="Closed")return;this._DatagramStatus=x,x==="Open"&&(this._DatagramsWereOpen=!0);let F={status:x,message:A};this.onEvent("DatagramStatusChanged",F)}_ChangeStatus(x,A){let F={status:x,message:A};this.onEvent("RoomStatusChanged",F)}async _HandleConnection(x){if(this._RoomConnection===void 0)return!1;let A=new a.Selector([()=>(0,a.sleep)(this.renewTokenIn,"renewToken"),()=>(0,a.sleep)(500,"tick"),async()=>await this._RoomConnection?.recv(),()=>this._Closed,()=>x.closePromise]);for(;;){let F=await A.next();switch(F){case void 0:case"closed":return this._RoomConnection?.close(),this._MainConnection?.close(),!1;case"disconnected":return this._RoomConnection?.close(),this._MainConnection?.close(),!0;case"renewToken":this._RenewToken().catch(D=>C("token renewal failed",D));break;case"tick":break;default:this._HandleEvent(F);break}}}_HandleEvent(x){if(x.name==="RoomUpdated"){let A=J.RoomNotificationsRpc.RoomUpdated.safeParse(x.properties);if(!A.success)return;for(let F of A.data.updates)F.kind==="Joined"&&(this._OwnPeerId=F.own_peer_id)}this.onEvent(x.name,x.properties)}_HandleRequests(x,A,F){switch(x){case"SetPeerPosition":{let D=J.RoomCommandsRpc.SetPeerPosition.request.safeParse(A);if(D.success){let r=D.data.position;this._Position=r.length===2?[r[0],r[1],0]:r}else C("unable to process SetPeerPosition command");break}case"UpdatePeer":{let D=J.RoomCommandsRpc.UpdatePeer.request.safeParse(A);D.success?this._UserData=D.data.user_data:C("unable to process UpdatePeer command");break}}}async _RenewToken(x){if(this._LastTokenRenew=performance.now(),!x&&this.token.timeLeft>n.MinTokenLifetime)return;if(this._MainConnection===void 0||this._OwnPeerId===void 0)return(0,a.failure)("connection is not established");let A=await this._MainConnection.getReconnectToken(this._OwnPeerId);return A.type==="Success"?(this._Token=A.value,(0,a.success)()):(0,a.failure)(`${this._MainConnection.address} rejected reconnect token request; ${A.reason}`)}reset(){this._LastReconnectStartedAt=0,this._RoomConnection?.close(),this._RoomConnection=void 0,this._MainConnection?.close(),this._MainConnection=void 0,this._OwnPeerId=void 0}};async function PF(t,x,A){try{let F={jsonrpc:"2.0",id:1,method:"Connect",params:{}};f(`sending authentication request to '${t}'`,F);let r=await(await fetch(t,{body:JSON.stringify(F),method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${x}`},signal:A})).json();if(f(`received authentication response fom '${t}'`,r),"result"in r)return g.parse(r.result.token);{let e=r.error?.message??"malformed response";return c(`gateway rejected token; ${e}`),(0,a.success)(e)}}catch(F){return(0,a.failure)(String(F))}}function CA(t,x=8e3){return performance.now()-t>x}b();var GA=require("@4players/odin-common");var w=require("@4players/odin-common");b();var fA=require("@4players/odin-common");b();var Wx=class{constructor(x){this.host=x;this.lastId=0;this.senders=new Set;this.sendersRequired=!1;this.owners=new WeakMap}create(x){let A={id:++this.lastId,side:x,released:!1,installed:!1,known:!1};return x==="sender"&&this.senders.add(A),{id:A.id,attach:F=>{if(A.released)throw new Error("video transform was released");this.detach(A),A.target=F;try{this.install(A)}catch(D){if(x==="sender"&&!this.sendersRequired)return;throw A.target=void 0,D}},detach:()=>this.detach(A),release:()=>{this.detach(A),A.released=!0,this.senders.delete(A),A.known&&this.host.release(A.id)}}}setSendersRequired(x){if(this.sendersRequired=x,!!x)for(let A of this.senders)A.target===void 0||A.installed||(this.host.block(A.target),A.target=void 0)}clear(){this.senders.clear()}install(x){x.target===void 0||x.installed||(this.host.install(x.target,x.id,x.side),this.owners.set(x.target,x),x.installed=!0,x.known=!0)}detach(x){let{target:A,installed:F}=x;A!==void 0&&(x.target=void 0,x.installed=!1,!(!F||this.owners.get(A)!==x)&&(this.owners.delete(A),this.host.uninstall(A)))}};var EA=`"use strict";(()=>{var l=Symbol("Unencrypted"),d=Symbol("Invalid");function w(r){let e=[],t=-1,n=0;for(let a=0;a<r.length;a++){let s=r[a];if(s===0){n+=1;continue}if(s===1&&n>=2){let o=a-n;if(t>=0)o>t&&e.push({start:t,end:o});else if(o!==0)return;t=a+1}n=0}if(t<0)return;let i=r.length;for(;i>t&&r[i-1]===0;)i-=1;return i>t&&e.push({start:t,end:i}),e}function m(r,e){return r[e.start]&31}function U(r){return r>=1&&r<=5}function R(r){let e=0;for(;e<r.length&&r[r.length-1-e]===0;)e+=1;return e}function I(r,e=0){let t=0,n=e;for(let s=0;s<r.length;s++){let o=r[s];n>=2&&o<=3&&(t+=1,n=0),n=o===0?n+1:0}if(t===0)return r;let i=new Uint8Array(r.length+t),a=0;n=e;for(let s=0;s<r.length;s++){let o=r[s];n>=2&&o<=3&&(i[a++]=3,n=0),i[a++]=o,n=o===0?n+1:0}return i}function N(r,e=0){let t=new Uint8Array(r.length),n=0,i=e;for(let a=0;a<r.length;a++){let s=r[a];if(i>=2&&s===3){i=0;continue}t[n++]=s,i=s===0?i+1:0}return t.subarray(0,n)}function O(r,e){let t=r.length+e.length;if(r.length!==16||t>=255)throw new Error("unsupported sei payload size");let n=new Uint8Array(2+t);n[0]=5,n[1]=t,n.set(r,2),n.set(e,2+r.length);let i=I(n),a=new Uint8Array(1+i.length+1);return a[0]=6,a.set(i,1),a[a.length-1]=128,a}function V(r,e){if(r.length<3+e.length||(r[0]&31)!==6)return;let t=N(r.subarray(1));if(t[0]!==5)return;let n=t[1];if(!(n===255||n<e.length)&&t.length===2+n+1&&t[t.length-1]===128){for(let i=0;i<e.length;i++)if(t[2+i]!==e[i])return;return t.subarray(2+e.length,2+n)}}var L=2,H=new Uint8Array([79,68,73,78,45,86,67,45,155,62,113,196,90,210,78,134]),g=32,b=32,M=8,Y=8,E=4294967295,ie=0xffffffffffff,F=16,q=1,P=128,A=14,se=65535,X=[0,0,0,1],ae=600,K=new TextEncoder().encode("odin_crypto_video_key");async function k(r,e){let t=new Uint8Array(K.length+e.length);return t.set(K),t.set(e,K.length),await globalThis.crypto.subtle.deriveKey({name:"PBKDF2",hash:"SHA-256",iterations:ae,salt:t},r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function S(r){return r.subarray(0,M)}function C(r){let e=w(r);if(e===void 0||e.length===0)return l;let t=!1,n,i;for(let a=0;a<e.length;a++){let s=e[a];m(r,s)===5&&(t=!0);let o=V(r.subarray(s.start,s.end),H);if(o===void 0)continue;let c=oe(o);if(c===d)return d;n=c,i=a}return{nals:e,keyFrame:t,meta:n,metaIndex:i}}async function W(r,e,t,n,i){if(i.length!==b)return d;let a=w(r);if(a===void 0)return d;let s=a.filter(f=>U(m(r,f))).length;if(s===0||s>se)return d;if(t+s-1>E)return d;if(!(e.epoch>=0&&e.epoch<=ie))return d;let o=new Uint8Array(A+(n?g:M));o[0]=L,o[1]=n?q:0,D(o,2,t),x(o,6,s),j(o,8,e.epoch),o.set(n?e.seed:S(e.seed),A);let c=[],u=0,y=0;for(let f of a){if(!U(m(r,f)))continue;let p=Math.min(f.end-f.start,Y),h=r.subarray(f.start,f.start+p),te=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:Q(t+y),additionalData:Z(e.epoch,t,s,y,i,h),tagLength:F*8},e.key,r.subarray(f.start+p,f.end));c.push(r.subarray(u,f.start+p)),c.push(I(new Uint8Array(te),R(h))),c.push(new Uint8Array([P|p])),u=f.end,y+=1}return c.push(r.subarray(u,a[a.length-1].end)),c.push(new Uint8Array(X)),c.push(O(H,o)),{data:$(c),count:s}}async function z(r,e,t,n){let i=e.meta;if(i===void 0)return d;if(n.length!==b)return d;let a=[],s=0;for(let o=0;o<e.nals.length;o++){if(o===e.metaIndex)continue;let c=e.nals[o];if(a.push(new Uint8Array(X)),!U(m(r,c))){a.push(r.subarray(c.start,c.end));continue}if(s>=i.count)return d;let u=r[c.end-1],y=u&~P;if((u&P)===0)return d;if(y>Y)return d;if(c.end-c.start<y+F+1)return d;let f=r.subarray(c.start,c.start+y),p=N(r.subarray(c.start+y,c.end-1),R(f)),h=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:Q(i.sequenceNumber+s),additionalData:Z(i.epoch,i.sequenceNumber,i.count,s,n,f),tagLength:F*8},t,p).catch(()=>d);if(h===d)return d;a.push(f),a.push(new Uint8Array(h)),s+=1}return s!==i.count?d:$(a)}function oe(r){if(r.length<A)return d;if(r[0]!==L)return d;let e=(r[1]&q)!==0,t=A+(e?g:M);if(r.length!==t)return d;let n=J(r,2),i=r[6]<<8|r[7];if(i===0)return d;if(n+i-1>E)return d;let a=ce(r,8),s=r.slice(A);return e?{sequenceNumber:n,count:i,epoch:a,seed:s,keyId:S(s)}:{sequenceNumber:n,count:i,epoch:a,keyId:s}}function Q(r){let e=new Uint8Array(12);return e[0]=r&255,e[1]=r>>>8&255,e[2]=r>>>16&255,e[3]=r>>>24&255,e[5]=4,e}function Z(r,e,t,n,i,a){let s=new Uint8Array(15+b+a.length);return s[0]=L,j(s,1,r),D(s,7,e),x(s,11,t),x(s,13,n),s.set(i,15),s.set(a,15+b),s}function j(r,e,t){x(r,e,Math.floor(t/4294967296)),D(r,e+2,t%4294967296)}function D(r,e,t){r[e]=t>>>24&255,r[e+1]=t>>>16&255,r[e+2]=t>>>8&255,r[e+3]=t&255}function x(r,e,t){r[e]=t>>>8&255,r[e+1]=t&255}function ce(r,e){return(r[e]<<8|r[e+1])*4294967296+J(r,e+2)}function J(r,e){return r[e]*16777216+(r[e+1]<<16|r[e+2]<<8|r[e+3])}function $(r){let e=0;for(let i of r)e+=i.length;let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}var de=E>>>1,G=0;function fe(r=Date.now()){return G=Math.max(G+1,Math.floor(r)),G}var v=class{constructor(){this.config={encrypt:!1,failed:!0};this.sequenceNumber=1;this.announce=!1;this.queue=Promise.resolve()}configure(e){e.masterKey!==this.config.masterKey&&(this.key=void 0),this.config=e}setPeerSeed(e){this.peerSeed=e}process(e){let t=this.queue.then(()=>this.processNext(e));return this.queue=t.catch(()=>{}),t}async processNext(e){let{masterKey:t,encrypt:n,failed:i}=this.config;if(i)return;if(!n||t===void 0)return e;let a=this.peerSeed;if(a===void 0)return;if(this.key===void 0||this.sequenceNumber>de){let c=globalThis.crypto.getRandomValues(new Uint8Array(g)),u=await k(t,c);if(this.config.masterKey!==t)return;this.key={seed:c,epoch:fe(),key:u},this.sequenceNumber=1,this.announce=!0}let s=C(e);if(s===l||s===d)return;let o=await W(e,this.key,this.sequenceNumber,s.keyFrame||this.announce,a);if(o!==d)return this.sequenceNumber+=o.count,this.announce=!1,o.data}},_=class{constructor(){this.strict=!1;this.awaitingKeyFrame=!1}configure(e){this.strict=e.encrypt&&(e.masterKey!==void 0||e.failed===!0),e.masterKey!==this.masterKey&&(this.masterKey=e.masterKey,this.derived=void 0)}setPeerSeed(e){this.peerSeed=e}async process(e,t){let n=C(e);if(n===d)return this.drop(!0);if(n===l||n.meta===void 0)return this.strict?this.drop(!1):(n!==l&&(t=n.keyFrame),this.awaitingKeyFrame&&!t?this.drop(!0):(this.awaitingKeyFrame=!1,{frame:e,requestKeyFrame:!1}));let i=this.masterKey;if(i===void 0)return this.drop(!1);let a=this.peerSeed;if(a===void 0)return this.drop(!0);if(this.awaitingKeyFrame&&!n.keyFrame)return this.drop(!0);let s=n.meta,o=this.selectSeed(s);if(o===void 0)return this.drop(!0);let c=this.derived;if((c===void 0||!B(c.seed,o))&&(c={seed:o,key:await k(i,o)},this.masterKey!==i))return this.drop(!0);let u=await z(e,n,c.key,a);return u===d?this.drop(!0):(this.derived=c,this.accepted={seed:o,epoch:s.epoch,lastSequenceNumber:s.sequenceNumber+s.count-1},this.awaitingKeyFrame=!1,{frame:u,requestKeyFrame:!1})}selectSeed(e){let t=this.accepted;if(t!==void 0&&e.epoch===t.epoch&&B(e.keyId,S(t.seed))&&(e.seed===void 0||B(e.seed,t.seed)))return e.sequenceNumber<=t.lastSequenceNumber?void 0:t.seed;if(!(t!==void 0&&e.epoch<=t.epoch))return e.seed}drop(e){return this.awaitingKeyFrame=!0,{requestKeyFrame:e}}};function B(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}var T=class{constructor(){this.config={encrypt:!1,failed:!0};this.generation=0;this.pendingGeneration=0;this.waiters=[];this.senders=new Map;this.receivers=new Map;this.peerSeeds=new Map}handleRequest(e){switch(e.type){case"pending":this.pendingGeneration=Math.max(this.pendingGeneration,e.generation);break;case"configure":{this.config={masterKey:e.masterKey,encrypt:e.encrypt,failed:e.failed},this.generation=e.generation;for(let n of this.senders.values())n.configure(this.config);for(let n of this.receivers.values())n.configure(this.config);let t=this.waiters;this.waiters=[];for(let n of t)n();break}case"sender":this.senderSeed=e.seed;for(let t of this.senders.values())t.setPeerSeed(e.seed);break;case"peer":e.seed===void 0?this.peerSeeds.delete(e.id):this.peerSeeds.set(e.id,e.seed),this.receivers.get(e.id)?.setPeerSeed(e.seed);break;case"release":this.senders.delete(e.id),this.receivers.delete(e.id),this.peerSeeds.delete(e.id);break}}createHandler(e){let{id:t,side:n,generation:i}=e;if(n==="sender"){let o=this.senders.get(t);o===void 0&&(o=new v,o.configure(this.config),o.setPeerSeed(this.senderSeed),this.senders.set(t,o));let c=o;return async u=>(await this.reached(i),{frame:await c.process(u),requestKeyFrame:!1})}let a=this.receivers.get(t);a===void 0&&(a=new _,a.configure(this.config),a.setPeerSeed(this.peerSeeds.get(t)),this.receivers.set(t,a));let s=a;return async(o,c)=>(await this.reached(i),await s.process(o,c))}async reached(e){for(;this.generation<Math.max(e,this.pendingGeneration);)await new Promise(t=>this.waiters.push(t))}};var ue=1e3,ee=globalThis,re=new T;ee.onmessage=r=>re.handleRequest(r.data);ee.onrtctransform=r=>{let e=r.transformer,t=re.createHandler(e.options),n=0;e.readable.pipeThrough(new TransformStream({async transform(i,a){try{let s=await t(new Uint8Array(i.data),i.type==="key");if(s.requestKeyFrame){let o=Date.now();o-n>=ue&&(n=o,e.sendKeyFrameRequest?.().catch(()=>{}))}if(s.frame===void 0)return;i.data=ye(s.frame),a.enqueue(i)}catch{}}})).pipeTo(e.writable).catch(()=>{})};function ye(r){let e=r.buffer;return r.byteOffset===0&&r.byteLength===e.byteLength?e:e.slice(r.byteOffset,r.byteOffset+r.byteLength)}})();
|
|
6682
|
+
`;var Qx=class{constructor(){this.generation=0;this.closed=!1;this.peerSeeds=new Map;this.transforms=new Wx({install:(x,A,F)=>{if(!(0,fA.isVideoEncryptionCapable)())throw new Error("video encryption is not supported by this browser");let D={id:A,side:F,generation:this.generation};x.transform=new RTCRtpScriptTransform(this.ensureWorker(),D)},block:x=>{C("stopping a video that can not be encrypted in this browser"),x.replaceTrack(null).catch(()=>{})},uninstall:x=>{try{x.transform=null}catch{}},release:x=>{this.peerSeeds.delete(x),this.post({type:"release",id:x})}})}configure(x){let A=++this.generation;this.post({type:"pending",generation:A}),x.catch(()=>({encrypt:!0,failed:!0})).then(({masterKey:F,encrypt:D,failed:r})=>{A<(this.lastRequest?.generation??0)||(this.lastRequest={type:"configure",generation:A,masterKey:F,encrypt:D,failed:r===!0},this.post(this.lastRequest))}).catch(console.error)}createTransform(x){return this.transforms.create(x)}setSenderSeed(x){nA(x,this.senderSeed)||(this.senderSeed=x?.slice(),this.post({type:"sender",seed:this.senderSeed}))}setPeerSeed(x,A){if(nA(A,this.peerSeeds.get(x)))return;let F=A?.slice();F===void 0?this.peerSeeds.delete(x):this.peerSeeds.set(x,F),this.post({type:"peer",id:x,seed:F})}setSendersRequired(x){this.transforms.setSendersRequired(x)}close(){this.closed=!0,this.worker?.terminate(),this.worker=void 0,this.transforms.clear()}post(x){this.worker?.postMessage(x)}ensureWorker(){if(this.closed)throw new Error("video cipher was closed");if(this.worker!==void 0)return this.worker;let x=URL.createObjectURL(new Blob([EA],{type:"text/javascript"})),A=new Worker(x,{type:"module",name:"odin video cipher"});this.lastRequest!==void 0&&A.postMessage(this.lastRequest),this.worker=A,this.senderSeed!==void 0&&this.post({type:"sender",seed:this.senderSeed});for(let[F,D]of this.peerSeeds)this.post({type:"peer",id:F,seed:D});return A}};function nA(t,x){return t===void 0||x===void 0?t===x:t.length===x.length&&t.every((A,F)=>A===x[F])}var kA=require("@4players/odin-common");b();var cA=require("@msgpack/msgpack");b();var sA={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])},iA=t=>({name:"PBKDF2",hash:"SHA-256",iterations:600,salt:t}),oA=32,bA=1e6,aA=2147483648,lA=32,V=[79,68,73,78,1,75,105,109],bx=16,ax=64,uA=16;function dA(t,x){if(t.length!==x.length)return!1;for(let A=0;A<t.length;A++)if(t[A]!==x[A])return!1;return!0}function OF(t){return isFinite(t)}function HF(t){return Array.isArray(t)}function Xx(t){return OF(t)?t:B}function kx(t){return t instanceof Uint8Array?t:B}function wF(t,...x){let A;try{A=(0,cA.decode)(t)}catch{return B}if(!HF(A))return B;let F=new Array(A.length);for(let D=0;D<x.length;D++)if(F[D]=x[D](A[D]),F[D]===B)return B;return F}function zx(t,...x){if(t.length<V.length)return m;for(let A=0;A<V.length;A++)if(t[A]!==V[A])return m;return wF(t.subarray(V.length),...x)}var lx=class{constructor(x){this.first=1;this.offset=0;this.window=Array(x)}isReplay(x){let A=x-this.first;if(A<0)return!0;if(A>=this.window.length)if(A<this.window.length*2){let r=A-this.window.length+1;A-=r;for(let e=0;e<r;e++)this.advance()}else return this.first=x+1-self.window.length,this.offset=0,this.window.fill(!1),!1;let F=(this.offset+A)%this.window.length,D=this.window[F]===!0;for(this.window[F]=!0;this.window[this.offset]===!0;)this.advance();return D}advance(){this.window[this.offset]=!1,this.first+=1,this.offset=(this.offset+1)%this.window.length}};var Zx=class t{constructor(x){this.key=x}static async create(x){typeof x=="string"&&(x=new TextEncoder().encode(x));let A=await globalThis.crypto.subtle.importKey("raw",x,"PBKDF2",!1,["deriveBits"]),F=await globalThis.crypto.subtle.deriveBits(sA,A,256),D=await globalThis.crypto.subtle.importKey("raw",F,"PBKDF2",!1,["deriveKey"]);return new t(D)}async generatePeerKey(x,A){return await globalThis.crypto.subtle.deriveKey(iA(x),this.key,{name:"AES-GCM",length:256},!1,[A])}},Yx=class t{constructor(x,A){this.seed=x;this.key=A;this.sequenceNumbers={datagram:1,message:1,userData:1};this.number_of_packets=0;this.number_of_bytes=0}static async create(x){let A=globalThis.crypto.getRandomValues(new Uint8Array(oA)),F=await x.generatePeerKey(A,"encrypt");return new t(A,F)}get limitReached(){return this.key===void 0?!1:this.number_of_bytes>=aA||this.number_of_packets>=bA}nextSequenceNumber(x){return this.sequenceNumbers[x]++}};function d0(t,x){return{kind:"encrypted",key:t,material:x,antiReplays:{datagram:new lx(lA),userData:new lx(0),message:new lx(0)}}}var x0=class t{constructor(x,A,F,D){this.additionalData=x;this.sequenceNumber=A;this.seed=F;this.encrypted=D}static parse(x){let A=zx(x,kx,Xx,kx);if(A===B||A===m)return A;let[F,D,r]=A,e=x.subarray(0,x.length-r.length);return new t(e,D,F,r)}isSameSeed(x){return dA(this.seed,x.seed)}async generateKey(x){return await x.generatePeerKey(this.seed,"decrypt")}};function A0(t,x){let A=new Uint8Array(12);switch(A[0]=x&255,A[1]=x>>8&255,A[2]=x>>16&255,A[3]=x>>24&255,t){case"datagram":A[5]=1;break;case"userData":A[5]=2;break;case"message":A[5]=3;break;default:(0,kA.assert)(!1,"missing content implementation")}return A}var k0=require("@msgpack/msgpack"),hA=require("@4players/odin-common");b();var F0=class{constructor(x){this.actions=x}changeKey(x){this.masterKey!==x&&(this.masterKey=x,this.ownKey=B,this.actions.resendUserData())}async encryptDatagram(x){let A=await this.getKey("datagram");return A===void 0?x:A===U?B:await TF(A,x)}async encryptMessage(x){let A=await this.getKey("message");return A===void 0?x:A===U?U:await pA(A,x,"message")}async encryptUserData(x){let A=await this.getKey("userData");return A===void 0?x:((0,hA.assert)(A!==U,"key unavailable for user data encryption"),await pA(A,x,"userData",A.seed))}async getKey(x){if(this.ownKey===B||this.ownKey?.limitReached)if(x==="userData")this.ownKey=this.masterKey?await Yx.create(this.masterKey):void 0;else return this.ownKey!==B&&(this.ownKey=B,this.actions.resendUserData()),U;return this.ownKey}reset(){this.ownKey=this.masterKey?B:void 0}};async function pA(t,x,A,...F){let D=t.nextSequenceNumber(A),r=x.length+bx,e=RF(D,F,r),j=e.length-r,v=await mA(t,A,D,e.subarray(0,j),x);return e.set(new Uint8Array(v),j),e}function RF(t,x,A){let F=[];x.forEach(e=>F.push(e)),F.push(t),F.push(new Uint8Array(A));let D=(0,k0.encode)(F),r=new Uint8Array(V.length+D.length);return r.set(V,0),r.set(D,V.length),r}async function TF(t,x){let A=MF(x);if(A===B)return B;if((A.kind&ax)!==0)return B;let F=A.body.length+bx,D=t.nextSequenceNumber("datagram"),r=(0,k0.encode)([A.kind|ax,A.mediaIds,D,new Uint8Array(F)]),e=r.length-F,j=await mA(t,"datagram",D,r.subarray(0,e),A.body);return r.set(j,e),r}async function mA(t,x,A,F,D){return new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:A0(x,A),additionalData:F,tagLength:bx*8},t.key,D))}function MF(t){let x=new K(t),A=x.readArrayLength();if(i(A)||A<2)return B;let F=x.readNumber(),D=x.readArrayLength();if(i(F)||i(D))return B;if(D>uA)return B;let r=Array(D);for(let j=0;j<r.length;j++){let v=x.readNumber();if(i(v))return B;r[j]=v}let e=t.subarray(x.position);return{kind:F,mediaIds:r,body:e}}var qA=require("@msgpack/msgpack");b();var r0=class{constructor(x){this.actions=x;this.peerKeys=new Map}async changeKey(x){this.masterKey=x;for(let[A,{kind:F,material:D}]of this.peerKeys)if(x!==void 0){let r=await D.generateKey(x),e=d0(r,D),j=await D0(e,"userData",D.additionalData,D.sequenceNumber,D.encrypted);j!==B?(this.peerKeys.set(A,e),this.actions.setUserData(A,j)):(this.peerKeys.set(A,{kind:"broken",material:D}),this.actions.setUserData(A,new Uint8Array))}else F==="encrypted"&&this.peerKeys.set(A,{kind:"broken",material:D})}async decryptDatagram(x,A){let F=JF(A);if(this.masterKey===void 0)return F===m?A:B;if(F===B||F===m)return B;let D=this.peerKeys.get(x);if(D?.kind!=="encrypted")return B;let r=await D0(D,"datagram",F.additionalData,F.sequenceNumber,F.encrypted);return r===B?B:VF(F.kind&~ax,F.mediaIds,r)}async decryptMessage(x,A){let F=zx(A,Xx,kx);if(this.masterKey===void 0)return F===m?A:B;if(F===B||F===m)return B;let D=this.peerKeys.get(x);if(D?.kind!=="encrypted")return B;let[r,e]=F,j=A.subarray(0,A.length-e.length);return D0(D,"message",j,r,e)}async decryptUserData(x,A){let F=x0.parse(A);if(F===B)return B;if(F===m)return this.peerKeys.delete(x),this.masterKey===void 0?A:B;if(this.masterKey===void 0)return this.peerKeys.set(x,{kind:"broken",material:F}),B;let D=this.peerKeys.get(x);if(D?.kind==="encrypted"&&D.material.isSameSeed(F))D.material=F;else{let e=await F.generateKey(this.masterKey);D=d0(e,F)}let r=await D0(D,"userData",F.additionalData,F.sequenceNumber,F.encrypted);return r===B?this.peerKeys.set(x,{kind:"broken",material:F}):D!==void 0&&this.peerKeys.set(x,D),r}reset(){this.peerKeys.clear()}};function JF(t){let x=new K(t),A=x.readArrayLength();if(i(A)||A<1)return B;let F=x.readNumber();if(i(F))return B;if((F&ax)===0)return m;if(A!==4)return B;let D=x.position;x.readObjects(1);let r=t.subarray(D,x.position),e=x.readNumber(),j=x.readBytes();if(i(e)||i(j))return B;let v=t.subarray(0,t.length-j.length);return{kind:F,mediaIds:r,additionalData:v,sequenceNumber:e,encrypted:j}}async function D0(t,x,A,F,D){let r=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:A0(x,F),additionalData:A,tagLength:bx*8},t.key,D).catch(()=>B);return r===B?B:t.antiReplays[x].isReplay(F)?B:new Uint8Array(r)}function VF(t,x,A){let F=2;try{let e=new K(A);for(e.position=0;e.position<A.length;)e.readObjects(1),F+=1}catch{return B}let D=(0,qA.encode)(t),r=new Uint8Array(3+D.length+x.length+A.length);return r[0]=220,r[1]=F>>8&255,r[2]=F&255,r.set(D,3),r.set(x,3+D.length),r.set(A,3+D.length+x.length),r}var t0=class{constructor(x,A){this.active=!1;this.plainVideo=!1;this.warnedPlainVideo=!1;this.video=new Qx;this.videoSenders=new Map;this.videoReceivers=new Map;let F=new r0(A),D=new F0(A);this.crypto=new w.Strand({encryption:D,decryption:F}),this.peerKeys=F.peerKeys,this.configure(x)}encryptUserData(x){return this.crypto.enqueue(async({encryption:A})=>{let F=await A.encryptUserData(x);return this.updateOwnSeed(A.ownKey),F})}async encryptMessage(x){let A;do A=await this.crypto.enqueue(({encryption:F})=>F.encryptMessage(x));while(A===U);return A}async encryptDatagram(x){return await this.crypto.enqueue(({encryption:A})=>A.encryptDatagram(x))}decryptUserData(x,A){return this.crypto.enqueue(async({decryption:F})=>{let D=await F.decryptUserData(x,A);return this.updatePeerSeeds(x),D})}decryptMessage(x,A){return this.crypto.enqueue(({decryption:F})=>F.decryptMessage(x,A))}decryptDatagram(x,A){return this.crypto.enqueue(({decryption:F})=>F.decryptDatagram(x,A))}configure(x){let A=x.withVideo===!0;this.plainVideo=!!x.password&&!A;let F=this.crypto.enqueue(async D=>{let r=x.password?await Zx.create(x.password):void 0;return this.active=r!==void 0,D.encryption.changeKey(r),await D.decryption.changeKey(r),this.updatePeerSeeds(),{masterKey:r?.key,encrypt:A}});this.video.configure(F),this.video.setSendersRequired(A),F.catch(console.error)}createVideoSenderTransform(x){let A=this.videoSenders.get(x);return A===void 0&&(this.plainVideo&&!this.warnedPlainVideo&&(this.warnedPlainVideo=!0,C("the room has a password, but video is sent without end-to-end encryption; set withVideo in the cipher settings to encrypt it")),A=this.video.createTransform("sender"),this.videoSenders.set(x,A)),A}releaseVideoSenderTransform(x){this.videoSenders.get(x)?.release(),this.videoSenders.delete(x)}createVideoReceiverTransform(x,A){if(!(0,w.isVideoEncryptionCapable)())return;let F=this.videoReceivers.get(x);return F===void 0?(F={transform:this.video.createTransform("receiver"),peerId:A},this.videoReceivers.set(x,F)):F.peerId=A,this.video.setPeerSeed(F.transform.id,this.peerSeed(A)),F.transform}releaseVideoReceiverTransform(x){this.videoReceivers.get(x)?.transform.release(),this.videoReceivers.delete(x)}close(){this.videoSenders.clear(),this.videoReceivers.clear(),this.video.close()}getPeerStatus(x){switch(this.peerKeys.get(x)?.kind??"unencrypted"){case"broken":return w.Backend.PeerCipherStatus.InvalidPassword;case"encrypted":return w.Backend.PeerCipherStatus.Encrypted;case"unencrypted":return this.active?w.Backend.PeerCipherStatus.InvalidPassword:w.Backend.PeerCipherStatus.Unencrypted;default:return w.Backend.PeerCipherStatus.Unknown}}deletePeerKey(x){this.peerKeys.delete(x),this.updatePeerSeeds(x)}reset(){return this.crypto.enqueue(async({encryption:x,decryption:A})=>{x.reset(),A.reset(),this.updatePeerSeeds()})}updateOwnSeed(x){x===void 0||x===B||this.video.setSenderSeed(x.seed)}updatePeerSeeds(x){for(let A of this.videoReceivers.values())x!==void 0&&A.peerId!==x||this.video.setPeerSeed(A.transform.id,this.peerSeed(A.peerId))}peerSeed(x){if(x===void 0)return;let A=this.peerKeys.get(x);return A?.kind==="encrypted"?A.material.seed:void 0}async dump(){return this.crypto.enqueue(async()=>({active:this.active,peers:Array.from(this.peerKeys).map(([x,A])=>`${x} => ${A.kind}`)}))}};function yA(t,x){return(0,GA.assert)(t.type==="OdinCrypto","only OdinCrypto supported"),new t0(t,x)}var e0=class{constructor(x,A,F){this._Captures=new Map;this._Playbacks=new Map;this._Peers=new Map;this._AvailableMediaIds=[];let{url:D,onEvent:r}=A,e=(0,S.unwrap)(g.parse(A.token)),j=A.roomId??e.defaultRoomId,v=A.userData??new Uint8Array(0),E=A.position??[0,0,0];(0,S.assert)(j!==void 0,"room id required for multi-room-tokens"),this.cipher=A.cipher?yA(A.cipher,new Vx(this)):void 0,this.onEvent=r,f(`creating new room '${j}' ${this.cipher?"with":"without"} cipher`,e,v,E),this._Connection=new Kx(x,A.transport??"H3",this._HandleEvent.bind(this),D?new URL(D):void 0,e,j,v,E,this.cipher,F?.disableAutoReconnect??!1)}get connectionStats(){let x={...S.CONNECTION_STATS_INITIAL};return this.mainConnection?this.mainConnection.connectionStats:x}async getRtcStats(){return this.mainConnection?.getRtcStats()}get datagramStatus(){return this._Connection.datagramStatus}get roomConnection(){return this._Connection}get mainConnection(){return this.roomConnection?.mainConnection}get token(){return this._Connection.token.text}request(x,A){return this._Connection.requestUnsafe(x,A)}async link(x){if(x instanceof P){let A=this._Playbacks.get(x.uid)??{media:void 0,playback:void 0};A.playback!==void 0&&this.unlink(A.playback),A.media!==void 0&&x.start(A.media),A.playback=x,f(`linking audio playback media '${x.uid}' with volume ${x.volume} to room '${this._Connection.roomId}'`),this._Playbacks.set(x.uid,A)}else if(x instanceof R){let A=this._Captures.get(x);A&&this.unlink(x);let F=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();A={media:F?{connectionId:this.mainConnection.id,mediaId:F}:void 0},f(`linking audio capture media '${x.uid}' with volume ${x.volume} to room '${this._Connection.roomId}'`),this._Captures.set(x,A),A.media!==void 0&&await x.start(this._Connection,A.media)}else if(x instanceof H){let A=this._Playbacks.get(x.uid)??{media:void 0,playback:void 0};if(A.playback!==void 0&&A.playback!==x&&(A.playback instanceof H?(A.playback.setMediaStream(void 0),A.playback=void 0):this.unlink(A.playback)),A.media!==void 0){let F=await this.mainConnection?.startRemoteVideo(A.media.mediaId);F&&x.setMediaStream(F)}A.playback=x,f(`linking video playback media '${x.uid}' with type '${x.customType}' to room '${this._Connection.roomId}'`),this._Playbacks.set(x.uid,A)}else if(x instanceof y){let A=this._Captures.get(x);A&&this.unlink(x);let F=x.mediaStream?.getVideoTracks()[0];if(F){let D=this.mainConnection!==void 0&&this._AvailableMediaIds.shift();A={media:D?{connectionId:this.mainConnection.id,mediaId:D}:void 0},f(`linking video capture media '${x.uid}' with type '${x.parameters?.customType}' to room '${this._Connection.roomId}'`),this._Captures.set(x,A),A.media!==void 0&&(await x.start(this._Connection,A.media),this.mainConnection?.startLocalVideo(A.media.mediaId,F,x.parameters).catch(r=>C("failed to start local video",r))),x.audioCapture&&await this.link(x.audioCapture)}}else throw new Error("Linking failed, media was not supported")}unlink(x){if(x instanceof P||x instanceof H){let A=this._Playbacks.get(x.uid);if(A?.playback!==x)return;A.playback=void 0,A.media!==void 0&&(x instanceof P?x.stop(A.media):(this.mainConnection?.stopRemoteVideo(A.media.mediaId),x.setMediaStream(void 0))),f(`unlinking playback media '${x.uid}' from room '${this._Connection.roomId}'`),this._Playbacks.set(x.uid,A)}else if(x instanceof R||x instanceof y){x instanceof y&&x.audioCapture&&this.unlink(x.audioCapture);let A=this._Captures.get(x);if(A===void 0)return;A.media!==void 0&&(x.stop(this._Connection,A.media).catch(F=>C("failed to stop media",F)),this._AvailableMediaIds.push(A.media.mediaId),x instanceof y&&this.mainConnection?.stopLocalVideo(A.media.mediaId)),f(`unlinking capture media '${x.uid}' from room '${this._Connection.roomId}'`),this._Captures.delete(x)}else throw new Error("invalid media")}close(){f(`closing room '${this._Connection.roomId}'`),this._Connection.close(),this.cipher?.close()}_HandleEvent(x,A){let F=a0(p0.RoomNotificationsRpc,{name:x,properties:A});F!==void 0&&(this._HandleKnownEvent(F),A=F.properties),this.onEvent(x,A)}_HandleKnownEvent(x){switch(s(`processing event '${x.name}'`),x.name){case"RoomStatusChanged":x.properties.status!=="Joined"&&this._HandleConnectionLost();break;case"RoomUpdated":for(let A of x.properties.updates)this._HandleRoomUpdate(A);break;case"PeerUpdated":this._HandlePeerUpdate(x.properties);break}}_HandleConnectionLost(){for(let x of this._Peers.keys())this._HandlePeerLeft(x);for(let[x,A]of this._Captures)A.media!==void 0&&(x instanceof y,x instanceof R&&(x.stop(this._Connection,A.media).catch(F=>C("failed to stop media",F)),A.media=void 0));this._AvailableMediaIds.length=0}_HandleRoomUpdate(x){if(x.kind==="Joined"){(0,S.assert)(this._AvailableMediaIds.length===0,"left over media ids"),this._AvailableMediaIds.push(...x.media_ids),this._HandleRoomJoined();for(let A of x.room.peers)this._HandlePeerJoined(A)}else x.kind==="PeerJoined"?this._HandlePeerJoined(x.peer):x.kind==="PeerLeft"&&this._HandlePeerLeft(x.peer_id)}_HandleRoomJoined(){for(let[x,A]of this._Captures)this._AvailableMediaIds.length===0||this.mainConnection===void 0||(A.media={connectionId:this.mainConnection.id,mediaId:this._AvailableMediaIds.shift()},x instanceof R&&x.start(this._Connection,A.media).catch(F=>C("failed to start media",F)),x instanceof y)}_HandlePeerUpdate(x){x.kind==="MediaStarted"?this._HandleMediaStart(x.peer_id,x.media):x.kind==="MediaStopped"&&this._HandleMediaStopped(x.peer_id,x.media_id)}_HandlePeerJoined(x){this._Peers.has(x.id)||this._Peers.set(x.id,{mediaIds:new Map});for(let A of x.medias)this._HandleMediaStart(x.id,A)}_HandlePeerLeft(x){let A=this._Peers.get(x);if(A!==void 0){for(let F of A.mediaIds.keys())this._HandleMediaStopped(x,F);this._Peers.delete(x)}}_HandleMediaStart(x,A){if(this.mainConnection===void 0)return;let F=this._Peers.get(x);if(F===void 0||A.properties.kind!=="audio"&&A.properties.kind!=="video")return;let D=String(A.properties.uid??(0,S.generateUUID)());A.properties.uid=D;let r=this._Playbacks.get(D)??{media:void 0,playback:void 0};if(this._Playbacks.set(D,r),F.mediaIds.set(A.id,D),r.media={connectionId:this.mainConnection.id,mediaId:A.id},r.playback!==void 0&&(r.playback instanceof P&&r.playback.start(r.media),r.playback instanceof H)){let e=r.playback;this.mainConnection.startRemoteVideo(r.media.mediaId).then(j=>{e.setMediaStream(j)}).catch(j=>{C(`failed to start remote video for media ${A.id}`,j)})}}_HandleMediaStopped(x,A){let F=this._Peers.get(x);if(F===void 0)return;let D=F?.mediaIds.get(A);if(D===void 0)return;let r=this._Playbacks.get(D);r!==void 0&&(r.media!==void 0&&r.media.mediaId===A&&r.playback!==void 0&&(r.playback instanceof P&&r.playback.stop(r.media),r.playback instanceof H&&this.mainConnection?.stopRemoteVideo(r.media.mediaId),r.media=void 0),F.mediaIds.delete(A))}};gx();function UF(t,x){w0(x?.logger,x?.onLogMessage);let A,F=new Ux((r,e)=>A.receivePacket(r,e)),D=new Nx(t);return A=new Px(D,F.sendDatagram.bind(F),x?.enableHTMLAudioElementFallback??!1),new h0(F,A,x)}var ux=(0,m0.generateUUID)(),$A=[],gA=!1;function KF(){gA||typeof window>"u"||(window.addEventListener("beforeunload",()=>{for(let t of $A)t.deref()?.close()}),gA=!0)}var h0=class{constructor(x,A,F){this.version="9";this.supportedTransports=["H3","WebRTC"];this._PlaybackVolume=[1,1];this._CreatedAt=Date.now();this._Options=F??{},this._Options.disableBeforeUnload||KF(),this._ConnectionPool=x,this._MediaController=A,$A.push(new WeakRef(this)),f("plugin initialized")}get playbackVolume(){return this._PlaybackVolume}joinRoom(x){return new e0(this._ConnectionPool,x,this._Options)}async createAudioPlayback(x){return this._MediaController.createAudioPlayback(x)}async createAudioCapture(x){return this._MediaController.createAudioCapture(x)}async createVideoCapture(x,A){return this._MediaController.createVideoCapture(x,A)}async createVideoPlayback(x){return new H(x.uid,x.customType)}enumerateDevices(){return yx()}setOutputVolume(x){this._MediaController.playbackSetGlobalVolume(x)}async setOutputDevice(x){await this._MediaController.playbackSetDevice(x.device)}close(){this._MediaController.close(),this._ConnectionPool.close(),f("plugin closed")}async dump(){return{timestamp:Date.now(),createdAt:this._CreatedAt,connections:await this._ConnectionPool.dump(),medias:await this._MediaController.dump(),background:await V0()}}};0&&(module.exports={SESSION_ID,createPlugin});
|