uneeq-js 3.16.1 → 3.16.2
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/dist/esm/index.js +8 -8
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/types/dhop-messages.d.ts +1 -0
- package/dist/version.d.ts +1 -0
- package/package.json +3 -3
package/dist/esm/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as Oe,B as Kn,C as Fe,D as jn,E as Qn,F as Gn,G as
|
|
1
|
+
import{A as Oe,B as Kn,C as Fe,D as jn,E as Qn,F as Gn,G as Jn,H as Xn,I as Yn,J as Zn,K as ei,L as ti,M as ni,N as ii,O as si,P as ri,Q as oi,R as ai,S as Ae,T as li,U as ci,V as Vs,b as xr,c as Us,d as Ir,e as Pr,f as p,g as z,h as se,i as Bs,j as Lr,k as Dr,l as Or,m as Fr,n as Ar,o as Nr,p as Bn,q as Vn,r as Ur,s as _n,t as Wn,u as Hn,v as q,w as Br,x as $n,y as zn,z as qn}from"./chunks/chunk-OXR5BQBV.js";var hr=xr((Gl,vs)=>{"use strict";var y={};y.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};y.localCName=y.generateIdentifier();y.splitLines=function(s){return s.trim().split(`
|
|
2
2
|
`).map(e=>e.trim())};y.splitSections=function(s){return s.split(`
|
|
3
3
|
m=`).map((t,n)=>(n>0?"m="+t:t).trim()+`\r
|
|
4
4
|
`)};y.getDescription=function(s){let e=y.splitSections(s);return e&&e[0]};y.getMediaSections=function(s){let e=y.splitSections(s);return e.shift(),e};y.matchPrefix=function(s,e){return y.splitLines(s).filter(t=>t.indexOf(e)===0)};y.parseCandidate=function(s){let e;s.indexOf("a=candidate:")===0?e=s.substring(12).split(" "):e=s.substring(10).split(" ");let t={foundation:e[0],component:{1:"rtp",2:"rtcp"}[e[1]]||e[1],protocol:e[2].toLowerCase(),priority:parseInt(e[3],10),ip:e[4],address:e[4],port:parseInt(e[5],10),type:e[7]};for(let n=8;n<e.length;n+=2)switch(e[n]){case"raddr":t.relatedAddress=e[n+1];break;case"rport":t.relatedPort=parseInt(e[n+1],10);break;case"tcptype":t.tcpType=e[n+1];break;case"ufrag":t.ufrag=e[n+1],t.usernameFragment=e[n+1];break;default:t[e[n]]===void 0&&(t[e[n]]=e[n+1]);break}return t};y.writeCandidate=function(s){let e=[];e.push(s.foundation);let t=s.component;t==="rtp"?e.push(1):t==="rtcp"?e.push(2):e.push(t),e.push(s.protocol.toUpperCase()),e.push(s.priority),e.push(s.address||s.ip),e.push(s.port);let n=s.type;return e.push("typ"),e.push(n),n!=="host"&&s.relatedAddress&&s.relatedPort&&(e.push("raddr"),e.push(s.relatedAddress),e.push("rport"),e.push(s.relatedPort)),s.tcpType&&s.protocol.toLowerCase()==="tcp"&&(e.push("tcptype"),e.push(s.tcpType)),(s.usernameFragment||s.ufrag)&&(e.push("ufrag"),e.push(s.usernameFragment||s.ufrag)),"candidate:"+e.join(" ")};y.parseIceOptions=function(s){return s.substring(14).split(" ")};y.parseRtpMap=function(s){let e=s.substring(9).split(" "),t={payloadType:parseInt(e.shift(),10)};return e=e[0].split("/"),t.name=e[0],t.clockRate=parseInt(e[1],10),t.channels=e.length===3?parseInt(e[2],10):1,t.numChannels=t.channels,t};y.writeRtpMap=function(s){let e=s.payloadType;s.preferredPayloadType!==void 0&&(e=s.preferredPayloadType);let t=s.channels||s.numChannels||1;return"a=rtpmap:"+e+" "+s.name+"/"+s.clockRate+(t!==1?"/"+t:"")+`\r
|
|
@@ -29,17 +29,17 @@ a=ice-pwd:`+s.password+`\r
|
|
|
29
29
|
o=`+(t||"thisisadapterortc")+" "+n+" "+i+` IN IP4 127.0.0.1\r
|
|
30
30
|
s=-\r
|
|
31
31
|
t=0 0\r
|
|
32
|
-
`};y.getDirection=function(s,e){let t=y.splitLines(s);for(let n=0;n<t.length;n++)switch(t[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return t[n].substring(2);default:}return e?y.getDirection(e):"sendrecv"};y.getKind=function(s){return y.splitLines(s)[0].split(" ")[0].substring(2)};y.isRejected=function(s){return s.split(" ",2)[1]==="0"};y.parseMLine=function(s){let t=y.splitLines(s)[0].substring(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}};y.parseOLine=function(s){let t=y.matchPrefix(s,"o=")[0].substring(2).split(" ");return{username:t[0],sessionId:t[1],sessionVersion:parseInt(t[2],10),netType:t[3],addressType:t[4],address:t[5]}};y.isValidSDP=function(s){if(typeof s!="string"||s.length===0)return!1;let e=y.splitLines(s);for(let t=0;t<e.length;t++)if(e[t].length<2||e[t].charAt(1)!=="=")return!1;return!0};typeof vs=="object"&&(vs.exports=y)});var di=(t=>(t.Google="google",t.Deepgram="deepgram",t))(di||{}),G=s=>s??"speech-recognition-service",re=s=>s==="pixel-streaming"||s==="both",
|
|
32
|
+
`};y.getDirection=function(s,e){let t=y.splitLines(s);for(let n=0;n<t.length;n++)switch(t[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return t[n].substring(2);default:}return e?y.getDirection(e):"sendrecv"};y.getKind=function(s){return y.splitLines(s)[0].split(" ")[0].substring(2)};y.isRejected=function(s){return s.split(" ",2)[1]==="0"};y.parseMLine=function(s){let t=y.splitLines(s)[0].substring(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}};y.parseOLine=function(s){let t=y.matchPrefix(s,"o=")[0].substring(2).split(" ");return{username:t[0],sessionId:t[1],sessionVersion:parseInt(t[2],10),netType:t[3],addressType:t[4],address:t[5]}};y.isValidSDP=function(s){if(typeof s!="string"||s.length===0)return!1;let e=y.splitLines(s);for(let t=0;t<e.length;t++)if(e[t].length<2||e[t].charAt(1)!=="=")return!1;return!0};typeof vs=="object"&&(vs.exports=y)});var di=(t=>(t.Google="google",t.Deepgram="deepgram",t))(di||{}),G=s=>s??"speech-recognition-service",re=s=>s==="pixel-streaming"||s==="both",J=s=>s==="speech-recognition-service"||s==="both",_s=s=>s==="speech-recognition-service"||s==="pixel-streaming"||s==="both";import{ReplaySubject as io}from"rxjs";var K;(function(s){s[s.Disabled=0]="Disabled",s[s.Error=1]="Error",s[s.Warning=2]="Warning",s[s.Info=3]="Info",s[s.Debug=4]="Debug"})(K||(K={}));var Ne=class{constructor(){this.logLevel=K.Debug,this.includeStack=!0}};var hi=class{InitLogging(e,t){this.ValidateContext(),this.context.logLevel=e,this.context.includeStack=t}Debug(e){this.ValidateContext(),this.context.logLevel>=K.Debug&&this.CommonLog("Debug",e)}Info(e){this.ValidateContext(),this.context.logLevel>=K.Info&&this.CommonLog("Info",e)}Warning(e){this.ValidateContext(),this.context.logLevel>=K.Warning&&this.CommonLog("Warning",e)}Error(e){this.ValidateContext(),this.context.logLevel>=K.Error&&this.CommonLog("Error",e)}CommonLog(e,t){let n=`[${e}] - ${t}`;this.context.includeStack&&(n+=`
|
|
33
33
|
Stack: ${this.GetStackTrace()}`),e==="Error"?console.error(n):e==="Warning"?console.warn(n):console.log(n)}GetStackTrace(){let e=new Error,t="No Stack Available for this browser";return e.stack&&(t=e.stack.toString().replace(/Error/g,"")),t}ValidateContext(){this.context||(typeof window>"u"||!window?this.context=new Ne:window.loggerContext?this.context=window.loggerContext:(this.context=new Ne,window.loggerContext=this.context))}},d=new hi;var Ue=class{constructor(e){this._args=[],this._callback=e}handleEvent(e){this._callback(...this._args),this._args=[]}setArgs(...e){this._args=e}},oe=class extends EventTarget{constructor(){super(),this._eventListeners=new Map}removeListenerInternal(e,t){if(this._eventListeners.has(e)){let n=this._eventListeners.get(e);if(n===void 0)return this;for(let i=0;i<n.length;++i){let r=n[i];if(r.callback===t){super.removeEventListener(e,r.eventListenerWrapper),n.splice(i,1);break}}}return this}addListener(e,t){return this.on(e,t)}on(e,t){var n;let i=new Ue(t);return super.addEventListener(e,i),this._eventListeners.has(e)||this._eventListeners.set(e,new Array),(n=this._eventListeners.get(e))===null||n===void 0||n.push({callback:t,eventListenerWrapper:i}),this}once(e,t){var n;let i={once:!0},r=new Ue((...o)=>{t(o),this.removeListenerInternal(e,t)});return super.addEventListener(e,r,i),this._eventListeners.has(e)||this._eventListeners.set(e,new Array),(n=this._eventListeners.get(e))===null||n===void 0||n.push({callback:t,eventListenerWrapper:r}),this}removeListener(e,t){return this.removeListenerInternal(e,t),this}off(e,t){return this.removeListener(e,t)}removeAllListeners(e){if(this._eventListeners.has(e)){let t=this._eventListeners.get(e);if(t===void 0)return this;for(let n of t)this.removeEventListener(e,n.eventListenerWrapper);this._eventListeners.delete(e)}return this}emit(e,...t){if(this._eventListeners.has(e)){let n=this._eventListeners.get(e);if(n===void 0)return!1;for(let i of n)i.eventListenerWrapper.setArgs(...t);return super.dispatchEvent(new Event(e)),!0}return!1}};var fe=class extends oe{constructor(e){super(),this.WS_OPEN_STATE=1,this.protocols=e}sendMessage(e){this.webSocket&&this.webSocket.send(e)}connect(e){d.Info(e);try{return this.webSocket=new WebSocket(e,this.protocols),this.webSocket.onopen=t=>this.handleOnOpen(),this.webSocket.onerror=t=>this.handleOnError(),this.webSocket.onclose=t=>this.handleOnClose(t),this.webSocket.onmessage=t=>this.handleOnMessage(t),this.webSocket.onmessagebinary=t=>this.handleOnMessageBinary(t),!0}catch(t){return d.Error(t),!1}}disconnect(e,t){this.webSocket&&this.webSocket.close(e,t)}isConnected(){return!!this.webSocket&&this.webSocket.readyState!=WebSocket.CLOSED}handleOnMessageBinary(e){!e||!e.data||e.data.text().then(t=>{let n=new MessageEvent("messageFromBinary",{data:t});this.handleOnMessage(n)}).catch(t=>{d.Error(`Failed to parse binary blob from websocket, reason: ${t.message}`)})}handleOnMessage(e){if(e.data&&e.data instanceof Blob){this.handleOnMessageBinary(e);return}this.onMessage&&this.onMessage(e.data)}handleOnOpen(){d.Info("Connected to the signalling server via WebSocket"),this.emit("open")}handleOnError(){this.emit("error")}handleOnClose(e){d.Info("Disconnected to the signalling server via WebSocket: "+JSON.stringify(e.code)+" - "+e.reason),this.emit("close",e)}};var ge=class extends oe{static get SIGNALLING_VERSION(){return"1.3.0"}constructor(e){super(),this.transport=e,e.onMessage=t=>{let n;try{let i=JSON.parse(t);d.Debug(`Protocol received =>
|
|
34
34
|
`+JSON.stringify(i,void 0,4)),n=i}catch(i){i instanceof Error?d.Error(`Error parsing message string ${t}.
|
|
35
35
|
${i.message}`):d.Error("Unknown error while parsing message data in handleOnMessage");return}e.emit("message",n),this.emit(n.type,n)||this.emit("unhandled",n)}}connect(e){return this.transport.connect(e)}disconnect(e,t){this.transport.disconnect(e,t)}isConnected(){return this.transport.isConnected()}sendMessage(e){this.transport.sendMessage(JSON.stringify(e)),this.transport.emit("out",e),d.Debug(`Protocol sent =>
|
|
36
|
-
`+JSON.stringify(e,void 0,4))}};var P={};
|
|
37
|
-
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:o=r,i=1;break;case 1:t[n++]=o<<2|(r&48)>>4,o=r,i=2;break;case 2:t[n++]=(o&15)<<4|(r&60)>>2,o=r,i=3;break;case 3:t[n++]=(o&3)<<6|r,i=0;break}}if(i==1)throw Error("invalid base64 string.");return t.subarray(0,n)}function Hs(s){let e="",t=0,n,i=0;for(let r=0;r<s.length;r++)switch(n=s[r],t){case 0:e+=Q[n>>2],i=(n&3)<<4,t=1;break;case 1:e+=Q[i|n>>4],i=(n&15)<<2,t=2;break;case 2:e+=Q[i|n>>6],e+=Q[n&63],t=0;break}return t&&(e+=Q[i],e+="=",t==1&&(e+="=")),e}var b;(function(s){s.symbol=Symbol.for("protobuf-ts/unknown"),s.onRead=(t,n,i,r,o)=>{(e(n)?n[s.symbol]:n[s.symbol]=[]).push({no:i,wireType:r,data:o})},s.onWrite=(t,n,i)=>{for(let{no:r,wireType:o,data:a}of s.list(n))i.tag(r,o).raw(a)},s.list=(t,n)=>{if(e(t)){let i=t[s.symbol];return n?i.filter(r=>r.no==n):i}return[]},s.last=(t,n)=>s.list(t,n).slice(-1)[0];let e=t=>t&&Array.isArray(t[s.symbol])})(b||(b={}));var g;(function(s){s[s.Varint=0]="Varint",s[s.Bit64=1]="Bit64",s[s.LengthDelimited=2]="LengthDelimited",s[s.StartGroup=3]="StartGroup",s[s.EndGroup=4]="EndGroup",s[s.Bit32=5]="Bit32"})(g||(g={}));function $s(){let s=0,e=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(s|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[s,e]}let t=this.buf[this.pos++];if(s|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[s,e];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(e|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[s,e]}throw new Error("invalid varint")}function We(s,e,t){for(let r=0;r<28;r=r+7){let o=s>>>r,a=!(!(o>>>7)&&e==0),l=(a?o|128:o)&255;if(t.push(l),!a)return}let n=s>>>28&15|(e&7)<<4,i=e>>3!=0;if(t.push((i?n|128:n)&255),!!i){for(let r=3;r<31;r=r+7){let o=e>>>r,a=!!(o>>>7),l=(a?o|128:o)&255;if(t.push(l),!a)return}t.push(e>>>31&1)}}var _e=65536*65536;function ui(s){let e=s[0]=="-";e&&(s=s.slice(1));let t=1e6,n=0,i=0;function r(o,a){let l=Number(s.slice(o,a));i*=t,n=n*t+l,n>=_e&&(i=i+(n/_e|0),n=n%_e)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),[e,n,i]}function He(s,e){if(e>>>0<=2097151)return""+(_e*e+(s>>>0));let t=s&16777215,n=(s>>>24|e<<8)>>>0&16777215,i=e>>16&65535,r=t+n*6777216+i*6710656,o=n+i*8147497,a=i*2,l=1e7;r>=l&&(o+=Math.floor(r/l),r%=l),o>=l&&(a+=Math.floor(o/l),o%=l);function c(u,w){let v=u?String(u):"";return w?"0000000".slice(v.length)+v:v}return c(a,0)+c(o,a)+c(r,1)}function pi(s,e){if(s>=0){for(;s>127;)e.push(s&127|128),s=s>>>7;e.push(s)}else{for(let t=0;t<9;t++)e.push(s&127|128),s=s>>7;e.push(1)}}function zs(){let s=this.buf[this.pos++],e=s&127;if((s&128)==0)return this.assertBounds(),e;if(s=this.buf[this.pos++],e|=(s&127)<<7,(s&128)==0)return this.assertBounds(),e;if(s=this.buf[this.pos++],e|=(s&127)<<14,(s&128)==0)return this.assertBounds(),e;if(s=this.buf[this.pos++],e|=(s&127)<<21,(s&128)==0)return this.assertBounds(),e;s=this.buf[this.pos++],e|=(s&15)<<28;for(let t=5;(s&128)!==0&&t<10;t++)s=this.buf[this.pos++];if((s&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}var x;function Br(){let s=new DataView(new ArrayBuffer(8));x=globalThis.BigInt!==void 0&&typeof s.getBigInt64=="function"&&typeof s.getBigUint64=="function"&&typeof s.setBigInt64=="function"&&typeof s.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:s}:void 0}Br();function qs(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}var Ks=/^-?[0-9]+$/,ze=4294967296,$e=2147483648,qe=class{constructor(e,t){this.lo=e|0,this.hi=t|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*ze+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}},O=class s extends qe{static from(e){if(x)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=x.C(e);case"number":if(e===0)return this.ZERO;e=x.C(e);case"bigint":if(!e)return this.ZERO;if(e<x.UMIN)throw new Error("signed value for ulong");if(e>x.UMAX)throw new Error("ulong too large");return x.V.setBigUint64(0,e,!0),new s(x.V.getInt32(0,!0),x.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!Ks.test(e))throw new Error("string is no integer");let[t,n,i]=ui(e);if(t)throw new Error("signed value for ulong");return new s(n,i);case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");if(e<0)throw new Error("signed value for ulong");return new s(e,e/ze)}throw new Error("unknown value "+typeof e)}toString(){return x?this.toBigInt().toString():He(this.lo,this.hi)}toBigInt(){return qs(x),x.V.setInt32(0,this.lo,!0),x.V.setInt32(4,this.hi,!0),x.V.getBigUint64(0,!0)}};O.ZERO=new O(0,0);var L=class s extends qe{static from(e){if(x)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=x.C(e);case"number":if(e===0)return this.ZERO;e=x.C(e);case"bigint":if(!e)return this.ZERO;if(e<x.MIN)throw new Error("signed long too small");if(e>x.MAX)throw new Error("signed long too large");return x.V.setBigInt64(0,e,!0),new s(x.V.getInt32(0,!0),x.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!Ks.test(e))throw new Error("string is no integer");let[t,n,i]=ui(e);if(t){if(i>$e||i==$e&&n!=0)throw new Error("signed long too small")}else if(i>=$e)throw new Error("signed long too large");let r=new s(n,i);return t?r.negate():r;case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new s(e,e/ze):new s(-e,-e/ze).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return(this.hi&$e)!==0}negate(){let e=~this.hi,t=this.lo;return t?t=~t+1:e+=1,new s(t,e)}toString(){if(x)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+He(e.lo,e.hi)}return He(this.lo,this.hi)}toBigInt(){return qs(x),x.V.setInt32(0,this.lo,!0),x.V.setInt32(4,this.hi,!0),x.V.getBigInt64(0,!0)}};L.ZERO=new L(0,0);var js={readUnknownField:!0,readerFactory:s=>new mi(s)};function Qs(s){return s?Object.assign(Object.assign({},js),s):js}var mi=class{constructor(e,t){this.varint64=$s,this.uint32=zs,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e){let t=this.pos;switch(e){case g.Varint:for(;this.buf[this.pos++]&128;);break;case g.Bit64:this.pos+=4;case g.Bit32:this.pos+=4;break;case g.LengthDelimited:let n=this.uint32();this.pos+=n;break;case g.StartGroup:let i;for(;(i=this.tag()[1])!==g.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return new L(...this.varint64())}uint64(){return new O(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,new L(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new O(this.sfixed32(),this.sfixed32())}sfixed64(){return new L(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}};function R(s,e){if(!s)throw new Error(e)}var Vr=34028234663852886e22,_r=-34028234663852886e22,Wr=4294967295,Hr=2147483647,$r=-2147483648;function J(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>Hr||s<$r)throw new Error("invalid int 32: "+s)}function ee(s){if(typeof s!="number")throw new Error("invalid uint 32: "+typeof s);if(!Number.isInteger(s)||s>Wr||s<0)throw new Error("invalid uint 32: "+s)}function ae(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>Vr||s<_r))throw new Error("invalid float 32: "+s)}var Gs={writeUnknownFields:!0,writerFactory:()=>new fi};function Xs(s){return s?Object.assign(Object.assign({},Gs),s):Gs}var fi=class{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let t=new Uint8Array(e),n=0;for(let i=0;i<this.chunks.length;i++)t.set(this.chunks[i],n),n+=this.chunks[i].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(ee(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return J(e),pi(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){ae(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){ee(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){J(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return J(e),e=(e<<1^e>>31)>>>0,pi(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=L.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=O.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=L.from(e);return We(t.lo,t.hi,this.buf),this}sint64(e){let t=L.from(e),n=t.hi>>31,i=t.lo<<1^n,r=(t.hi<<1|t.lo>>>31)^n;return We(i,r,this.buf),this}uint64(e){let t=O.from(e);return We(t.lo,t.hi,this.buf),this}};var Js={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Ys={ignoreUnknownFields:!1};function Zs(s){return s?Object.assign(Object.assign({},Ys),s):Ys}function er(s){return s?Object.assign(Object.assign({},Js),s):Js}var Ke=Symbol.for("protobuf-ts/message-type");function gi(s){let e=!1,t=[];for(let n=0;n<s.length;n++){let i=s.charAt(n);i=="_"?e=!0:/\d/.test(i)?(t.push(i),e=!0):e?(t.push(i.toUpperCase()),e=!1):n==0?t.push(i.toLowerCase()):t.push(i)}return t.join("")}var f;(function(s){s[s.DOUBLE=1]="DOUBLE",s[s.FLOAT=2]="FLOAT",s[s.INT64=3]="INT64",s[s.UINT64=4]="UINT64",s[s.INT32=5]="INT32",s[s.FIXED64=6]="FIXED64",s[s.FIXED32=7]="FIXED32",s[s.BOOL=8]="BOOL",s[s.STRING=9]="STRING",s[s.BYTES=12]="BYTES",s[s.UINT32=13]="UINT32",s[s.SFIXED32=15]="SFIXED32",s[s.SFIXED64=16]="SFIXED64",s[s.SINT32=17]="SINT32",s[s.SINT64=18]="SINT64"})(f||(f={}));var V;(function(s){s[s.BIGINT=0]="BIGINT",s[s.STRING=1]="STRING",s[s.NUMBER=2]="NUMBER"})(V||(V={}));var ye;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(ye||(ye={}));function tr(s){var e,t,n,i;return s.localName=(e=s.localName)!==null&&e!==void 0?e:gi(s.name),s.jsonName=(t=s.jsonName)!==null&&t!==void 0?t:gi(s.name),s.repeat=(n=s.repeat)!==null&&n!==void 0?n:ye.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function nr(s){if(typeof s!="object"||s===null||!s.hasOwnProperty("oneofKind"))return!1;switch(typeof s.oneofKind){case"string":return s[s.oneofKind]===void 0?!1:Object.keys(s).length==2;case"undefined":return Object.keys(s).length==1;default:return!1}}var je=class{constructor(e){var t;this.fields=(t=e.fields)!==null&&t!==void 0?t:[]}prepare(){if(this.data)return;let e=[],t=[],n=[];for(let i of this.fields)if(i.oneof)n.includes(i.oneof)||(n.push(i.oneof),e.push(i.oneof),t.push(i.oneof));else switch(t.push(i.localName),i.kind){case"scalar":case"enum":(!i.opt||i.repeat)&&e.push(i.localName);break;case"message":i.repeat&&e.push(i.localName);break;case"map":e.push(i.localName);break}this.data={req:e,known:t,oneofs:Object.values(n)}}is(e,t,n=!1){if(t<0)return!0;if(e==null||typeof e!="object")return!1;this.prepare();let i=Object.keys(e),r=this.data;if(i.length<r.req.length||r.req.some(o=>!i.includes(o))||!n&&i.some(o=>!r.known.includes(o)))return!1;if(t<1)return!0;for(let o of r.oneofs){let a=e[o];if(!nr(a))return!1;if(a.oneofKind===void 0)continue;let l=this.fields.find(c=>c.localName===a.oneofKind);if(!l||!this.field(a[a.oneofKind],l,n,t))return!1}for(let o of this.fields)if(o.oneof===void 0&&!this.field(e[o.localName],o,n,t))return!1;return!0}field(e,t,n,i){let r=t.repeat;switch(t.kind){case"scalar":return e===void 0?t.opt:r?this.scalars(e,t.T,i,t.L):this.scalar(e,t.T,t.L);case"enum":return e===void 0?t.opt:r?this.scalars(e,f.INT32,i):this.scalar(e,f.INT32);case"message":return e===void 0?!0:r?this.messages(e,t.T(),n,i):this.message(e,t.T(),n,i);case"map":if(typeof e!="object"||e===null)return!1;if(i<2)return!0;if(!this.mapKeys(e,t.K,i))return!1;switch(t.V.kind){case"scalar":return this.scalars(Object.values(e),t.V.T,i,t.V.L);case"enum":return this.scalars(Object.values(e),f.INT32,i);case"message":return this.messages(Object.values(e),t.V.T(),n,i)}break}return!0}message(e,t,n,i){return n?t.isAssignable(e,i):t.is(e,i)}messages(e,t,n,i){if(!Array.isArray(e))return!1;if(i<2)return!0;if(n){for(let r=0;r<e.length&&r<i;r++)if(!t.isAssignable(e[r],i-1))return!1}else for(let r=0;r<e.length&&r<i;r++)if(!t.is(e[r],i-1))return!1;return!0}scalar(e,t,n){let i=typeof e;switch(t){case f.UINT64:case f.FIXED64:case f.INT64:case f.SFIXED64:case f.SINT64:switch(n){case V.BIGINT:return i=="bigint";case V.NUMBER:return i=="number"&&!isNaN(e);default:return i=="string"}case f.BOOL:return i=="boolean";case f.STRING:return i=="string";case f.BYTES:return e instanceof Uint8Array;case f.DOUBLE:case f.FLOAT:return i=="number"&&!isNaN(e);default:return i=="number"&&Number.isInteger(e)}}scalars(e,t,n,i){if(!Array.isArray(e))return!1;if(n<2)return!0;if(Array.isArray(e)){for(let r=0;r<e.length&&r<n;r++)if(!this.scalar(e[r],t,i))return!1}return!0}mapKeys(e,t,n){let i=Object.keys(e);switch(t){case f.INT32:case f.FIXED32:case f.SFIXED32:case f.SINT32:case f.UINT32:return this.scalars(i.slice(0,n).map(r=>parseInt(r)),t,n);case f.BOOL:return this.scalars(i.slice(0,n).map(r=>r=="true"?!0:r=="false"?!1:r),t,n);default:return this.scalars(i,t,n,V.STRING)}}};function W(s,e){switch(e){case V.BIGINT:return s.toBigInt();case V.NUMBER:return s.toNumber();default:return s.toString()}}var Qe=class{constructor(e){this.info=e}prepare(){var e;if(this.fMap===void 0){this.fMap={};let t=(e=this.info.fields)!==null&&e!==void 0?e:[];for(let n of t)this.fMap[n.name]=n,this.fMap[n.jsonName]=n,this.fMap[n.localName]=n}}assert(e,t,n){if(!e){let i=Be(n);throw(i=="number"||i=="boolean")&&(i=n.toString()),new Error(`Cannot parse JSON ${i} for ${this.info.typeName}#${t}`)}}read(e,t,n){this.prepare();let i=[];for(let[r,o]of Object.entries(e)){let a=this.fMap[r];if(!a){if(!n.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${r}`);continue}let l=a.localName,c;if(a.oneof){if(o===null&&(a.kind!=="enum"||a.T()[0]!=="google.protobuf.NullValue"))continue;if(i.includes(a.oneof))throw new Error(`Multiple members of the oneof group "${a.oneof}" of ${this.info.typeName} are present in JSON.`);i.push(a.oneof),c=t[a.oneof]={oneofKind:l}}else c=t;if(a.kind=="map"){if(o===null)continue;this.assert(_s(o),a.name,o);let u=c[l];for(let[w,v]of Object.entries(o)){this.assert(v!==null,a.name+" map value",null);let C;switch(a.V.kind){case"message":C=a.V.T().internalJsonRead(v,n);break;case"enum":if(C=this.enum(a.V.T(),v,a.name,n.ignoreUnknownFields),C===!1)continue;break;case"scalar":C=this.scalar(v,a.V.T,a.V.L,a.name);break}this.assert(C!==void 0,a.name+" map value",v);let k=w;a.K==f.BOOL&&(k=k=="true"?!0:k=="false"?!1:k),k=this.scalar(k,a.K,V.STRING,a.name).toString(),u[k]=C}}else if(a.repeat){if(o===null)continue;this.assert(Array.isArray(o),a.name,o);let u=c[l];for(let w of o){this.assert(w!==null,a.name,null);let v;switch(a.kind){case"message":v=a.T().internalJsonRead(w,n);break;case"enum":if(v=this.enum(a.T(),w,a.name,n.ignoreUnknownFields),v===!1)continue;break;case"scalar":v=this.scalar(w,a.T,a.L,a.name);break}this.assert(v!==void 0,a.name,o),u.push(v)}}else switch(a.kind){case"message":if(o===null&&a.T().typeName!="google.protobuf.Value"){this.assert(a.oneof===void 0,a.name+" (oneof member)",null);continue}c[l]=a.T().internalJsonRead(o,n,c[l]);break;case"enum":if(o===null)continue;let u=this.enum(a.T(),o,a.name,n.ignoreUnknownFields);if(u===!1)continue;c[l]=u;break;case"scalar":if(o===null)continue;c[l]=this.scalar(o,a.T,a.L,a.name);break}}}enum(e,t,n,i){if(e[0]=="google.protobuf.NullValue"&&R(t===null||t==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} only accepts null.`),t===null)return 0;switch(typeof t){case"number":return R(Number.isInteger(t),`Unable to parse field ${this.info.typeName}#${n}, enum can only be integral number, got ${t}.`),t;case"string":let r=t;e[2]&&t.substring(0,e[2].length)===e[2]&&(r=t.substring(e[2].length));let o=e[1][r];return typeof o>"u"&&i?!1:(R(typeof o=="number",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} has no value for "${t}".`),o)}R(!1,`Unable to parse field ${this.info.typeName}#${n}, cannot parse enum value from ${typeof t}".`)}scalar(e,t,n,i){let r;try{switch(t){case f.DOUBLE:case f.FLOAT:if(e===null)return 0;if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""){r="empty string";break}if(typeof e=="string"&&e.trim().length!==e.length){r="extra whitespace";break}if(typeof e!="string"&&typeof e!="number")break;let o=Number(e);if(Number.isNaN(o)){r="not a number";break}if(!Number.isFinite(o)){r="too large or small";break}return t==f.FLOAT&&ae(o),o;case f.INT32:case f.FIXED32:case f.SFIXED32:case f.SINT32:case f.UINT32:if(e===null)return 0;let a;if(typeof e=="number"?a=e:e===""?r="empty string":typeof e=="string"&&(e.trim().length!==e.length?r="extra whitespace":a=Number(e)),a===void 0)break;return t==f.UINT32?ee(a):J(a),a;case f.INT64:case f.SFIXED64:case f.SINT64:if(e===null)return W(L.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return W(L.from(e),n);case f.FIXED64:case f.UINT64:if(e===null)return W(O.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return W(O.from(e),n);case f.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case f.STRING:if(e===null)return"";if(typeof e!="string"){r="extra whitespace";break}try{encodeURIComponent(e)}catch(l){l="invalid UTF8";break}return e;case f.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return Ws(e)}}catch(o){r=o.message}this.assert(!1,i+(r?" - "+r:""),e)}};var Ge=class{constructor(e){var t;this.fields=(t=e.fields)!==null&&t!==void 0?t:[]}write(e,t){let n={},i=e;for(let r of this.fields){if(!r.oneof){let c=this.field(r,i[r.localName],t);c!==void 0&&(n[t.useProtoFieldName?r.name:r.jsonName]=c);continue}let o=i[r.oneof];if(o.oneofKind!==r.localName)continue;let a=r.kind=="scalar"||r.kind=="enum"?Object.assign(Object.assign({},t),{emitDefaultValues:!0}):t,l=this.field(r,o[r.localName],a);R(l!==void 0),n[t.useProtoFieldName?r.name:r.jsonName]=l}return n}field(e,t,n){let i;if(e.kind=="map"){R(typeof t=="object"&&t!==null);let r={};switch(e.V.kind){case"scalar":for(let[l,c]of Object.entries(t)){let u=this.scalar(e.V.T,c,e.name,!1,!0);R(u!==void 0),r[l.toString()]=u}break;case"message":let o=e.V.T();for(let[l,c]of Object.entries(t)){let u=this.message(o,c,e.name,n);R(u!==void 0),r[l.toString()]=u}break;case"enum":let a=e.V.T();for(let[l,c]of Object.entries(t)){R(c===void 0||typeof c=="number");let u=this.enum(a,c,e.name,!1,!0,n.enumAsInteger);R(u!==void 0),r[l.toString()]=u}break}(n.emitDefaultValues||Object.keys(r).length>0)&&(i=r)}else if(e.repeat){R(Array.isArray(t));let r=[];switch(e.kind){case"scalar":for(let l=0;l<t.length;l++){let c=this.scalar(e.T,t[l],e.name,e.opt,!0);R(c!==void 0),r.push(c)}break;case"enum":let o=e.T();for(let l=0;l<t.length;l++){R(t[l]===void 0||typeof t[l]=="number");let c=this.enum(o,t[l],e.name,e.opt,!0,n.enumAsInteger);R(c!==void 0),r.push(c)}break;case"message":let a=e.T();for(let l=0;l<t.length;l++){let c=this.message(a,t[l],e.name,n);R(c!==void 0),r.push(c)}break}(n.emitDefaultValues||r.length>0||n.emitDefaultValues)&&(i=r)}else switch(e.kind){case"scalar":i=this.scalar(e.T,t,e.name,e.opt,n.emitDefaultValues);break;case"enum":i=this.enum(e.T(),t,e.name,e.opt,n.emitDefaultValues,n.enumAsInteger);break;case"message":i=this.message(e.T(),t,e.name,n);break}return i}enum(e,t,n,i,r,o){if(e[0]=="google.protobuf.NullValue")return!r&&!i?void 0:null;if(t===void 0){R(i);return}if(!(t===0&&!r&&!i))return R(typeof t=="number"),R(Number.isInteger(t)),o||!e[1].hasOwnProperty(t)?t:e[2]?e[2]+e[1][t]:e[1][t]}message(e,t,n,i){return t===void 0?i.emitDefaultValues?null:void 0:e.internalJsonWrite(t,i)}scalar(e,t,n,i,r){if(t===void 0){R(i);return}let o=r||i;switch(e){case f.INT32:case f.SFIXED32:case f.SINT32:return t===0?o?0:void 0:(J(t),t);case f.FIXED32:case f.UINT32:return t===0?o?0:void 0:(ee(t),t);case f.FLOAT:ae(t);case f.DOUBLE:return t===0?o?0:void 0:(R(typeof t=="number"),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t);case f.STRING:return t===""?o?"":void 0:(R(typeof t=="string"),t);case f.BOOL:return t===!1?o?!1:void 0:(R(typeof t=="boolean"),t);case f.UINT64:case f.FIXED64:R(typeof t=="number"||typeof t=="string"||typeof t=="bigint");let a=O.from(t);return a.isZero()&&!o?void 0:a.toString();case f.INT64:case f.SFIXED64:case f.SINT64:R(typeof t=="number"||typeof t=="string"||typeof t=="bigint");let l=L.from(t);return l.isZero()&&!o?void 0:l.toString();case f.BYTES:return R(t instanceof Uint8Array),t.byteLength?Hs(t):o?"":void 0}}};function Se(s,e=V.STRING){switch(s){case f.BOOL:return!1;case f.UINT64:case f.FIXED64:return W(O.ZERO,e);case f.INT64:case f.SFIXED64:case f.SINT64:return W(L.ZERO,e);case f.DOUBLE:case f.FLOAT:return 0;case f.BYTES:return new Uint8Array(0);case f.STRING:return"";default:return 0}}var Xe=class{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){let t=(e=this.info.fields)!==null&&e!==void 0?e:[];this.fieldNoToField=new Map(t.map(n=>[n.no,n]))}}read(e,t,n,i){this.prepare();let r=i===void 0?e.len:e.pos+i;for(;e.pos<r;){let[o,a]=e.tag(),l=this.fieldNoToField.get(o);if(!l){let v=n.readUnknownField;if(v=="throw")throw new Error(`Unknown field ${o} (wire type ${a}) for ${this.info.typeName}`);let C=e.skip(a);v!==!1&&(v===!0?b.onRead:v)(this.info.typeName,t,o,a,C);continue}let c=t,u=l.repeat,w=l.localName;switch(l.oneof&&(c=c[l.oneof],c.oneofKind!==w&&(c=t[l.oneof]={oneofKind:w})),l.kind){case"scalar":case"enum":let v=l.kind=="enum"?f.INT32:l.T,C=l.kind=="scalar"?l.L:void 0;if(u){let H=c[w];if(a==g.LengthDelimited&&v!=f.STRING&&v!=f.BYTES){let A=e.uint32()+e.pos;for(;e.pos<A;)H.push(this.scalar(e,v,C))}else H.push(this.scalar(e,v,C))}else c[w]=this.scalar(e,v,C);break;case"message":if(u){let H=c[w],A=l.T().internalBinaryRead(e,e.uint32(),n);H.push(A)}else c[w]=l.T().internalBinaryRead(e,e.uint32(),n,c[w]);break;case"map":let[k,U]=this.mapEntry(l,e,n);c[w][k]=U;break}}}mapEntry(e,t,n){let i=t.uint32(),r=t.pos+i,o,a;for(;t.pos<r;){let[l,c]=t.tag();switch(l){case 1:e.K==f.BOOL?o=t.bool().toString():o=this.scalar(t,e.K,V.STRING);break;case 2:switch(e.V.kind){case"scalar":a=this.scalar(t,e.V.T,e.V.L);break;case"enum":a=t.int32();break;case"message":a=e.V.T().internalBinaryRead(t,t.uint32(),n);break}break;default:throw new Error(`Unknown field ${l} (wire type ${c}) in map entry for ${this.info.typeName}#${e.name}`)}}if(o===void 0){let l=Se(e.K);o=e.K==f.BOOL?l.toString():l}if(a===void 0)switch(e.V.kind){case"scalar":a=Se(e.V.T,e.V.L);break;case"enum":a=0;break;case"message":a=e.V.T().create();break}return[o,a]}scalar(e,t,n){switch(t){case f.INT32:return e.int32();case f.STRING:return e.string();case f.BOOL:return e.bool();case f.DOUBLE:return e.double();case f.FLOAT:return e.float();case f.INT64:return W(e.int64(),n);case f.UINT64:return W(e.uint64(),n);case f.FIXED64:return W(e.fixed64(),n);case f.FIXED32:return e.fixed32();case f.BYTES:return e.bytes();case f.UINT32:return e.uint32();case f.SFIXED32:return e.sfixed32();case f.SFIXED64:return W(e.sfixed64(),n);case f.SINT32:return e.sint32();case f.SINT64:return W(e.sint64(),n)}}};var Je=class{constructor(e){this.info=e}prepare(){if(!this.fields){let e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((t,n)=>t.no-n.no)}}write(e,t,n){this.prepare();for(let r of this.fields){let o,a,l=r.repeat,c=r.localName;if(r.oneof){let u=e[r.oneof];if(u.oneofKind!==c)continue;o=u[c],a=!0}else o=e[c],a=!1;switch(r.kind){case"scalar":case"enum":let u=r.kind=="enum"?f.INT32:r.T;if(l)if(R(Array.isArray(o)),l==ye.PACKED)this.packed(t,u,r.no,o);else for(let w of o)this.scalar(t,u,r.no,w,!0);else o===void 0?R(r.opt):this.scalar(t,u,r.no,o,a||r.opt);break;case"message":if(l){R(Array.isArray(o));for(let w of o)this.message(t,n,r.T(),r.no,w)}else this.message(t,n,r.T(),r.no,o);break;case"map":R(typeof o=="object"&&o!==null);for(let[w,v]of Object.entries(o))this.mapEntry(t,n,r,w,v);break}}let i=n.writeUnknownFields;i!==!1&&(i===!0?b.onWrite:i)(this.info.typeName,e,t)}mapEntry(e,t,n,i,r){e.tag(n.no,g.LengthDelimited),e.fork();let o=i;switch(n.K){case f.INT32:case f.FIXED32:case f.UINT32:case f.SFIXED32:case f.SINT32:o=Number.parseInt(i);break;case f.BOOL:R(i=="true"||i=="false"),o=i=="true";break}switch(this.scalar(e,n.K,1,o,!0),n.V.kind){case"scalar":this.scalar(e,n.V.T,2,r,!0);break;case"enum":this.scalar(e,f.INT32,2,r,!0);break;case"message":this.message(e,t,n.V.T(),2,r);break}e.join()}message(e,t,n,i,r){r!==void 0&&(n.internalBinaryWrite(r,e.tag(i,g.LengthDelimited).fork(),t),e.join())}scalar(e,t,n,i,r){let[o,a,l]=this.scalarInfo(t,i);(!l||r)&&(e.tag(n,o),e[a](i))}packed(e,t,n,i){if(!i.length)return;R(t!==f.BYTES&&t!==f.STRING),e.tag(n,g.LengthDelimited),e.fork();let[,r]=this.scalarInfo(t);for(let o=0;o<i.length;o++)e[r](i[o]);e.join()}scalarInfo(e,t){let n=g.Varint,i,r=t===void 0,o=t===0;switch(e){case f.INT32:i="int32";break;case f.STRING:o=r||!t.length,n=g.LengthDelimited,i="string";break;case f.BOOL:o=t===!1,i="bool";break;case f.UINT32:i="uint32";break;case f.DOUBLE:n=g.Bit64,i="double";break;case f.FLOAT:n=g.Bit32,i="float";break;case f.INT64:o=r||L.from(t).isZero(),i="int64";break;case f.UINT64:o=r||O.from(t).isZero(),i="uint64";break;case f.FIXED64:o=r||O.from(t).isZero(),n=g.Bit64,i="fixed64";break;case f.BYTES:o=r||!t.byteLength,n=g.LengthDelimited,i="bytes";break;case f.FIXED32:n=g.Bit32,i="fixed32";break;case f.SFIXED32:n=g.Bit32,i="sfixed32";break;case f.SFIXED64:o=r||L.from(t).isZero(),n=g.Bit64,i="sfixed64";break;case f.SINT32:i="sint32";break;case f.SINT64:o=r||L.from(t).isZero(),i="sint64";break}return[n,i,r||o]}};function ir(s){let e=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},Ke,{value:s});for(let t of s.fields){let n=t.localName;if(!t.opt)if(t.oneof)e[t.oneof]={oneofKind:void 0};else if(t.repeat)e[n]=[];else switch(t.kind){case"scalar":e[n]=Se(t.T,t.L);break;case"enum":e[n]=0;break;case"map":e[n]={};break}}return e}function T(s,e,t){let n,i=t,r;for(let o of s.fields){let a=o.localName;if(o.oneof){let l=i[o.oneof];if(l?.oneofKind==null)continue;if(n=l[a],r=e[o.oneof],r.oneofKind=l.oneofKind,n==null){delete r[a];continue}}else if(n=i[a],r=e,n==null)continue;switch(o.repeat&&(r[a].length=n.length),o.kind){case"scalar":case"enum":if(o.repeat)for(let c=0;c<n.length;c++)r[a][c]=n[c];else r[a]=n;break;case"message":let l=o.T();if(o.repeat)for(let c=0;c<n.length;c++)r[a][c]=l.create(n[c]);else r[a]===void 0?r[a]=l.create(n):l.mergePartial(r[a],n);break;case"map":switch(o.V.kind){case"scalar":case"enum":Object.assign(r[a],n);break;case"message":let c=o.V.T();for(let u of Object.keys(n))r[a][u]=c.create(n[u]);break}break}}}function or(s,e,t){if(e===t)return!0;if(!e||!t)return!1;for(let n of s.fields){let i=n.localName,r=n.oneof?e[n.oneof][i]:e[i],o=n.oneof?t[n.oneof][i]:t[i];switch(n.kind){case"enum":case"scalar":let a=n.kind=="enum"?f.INT32:n.T;if(!(n.repeat?sr(a,r,o):ar(a,r,o)))return!1;break;case"map":if(!(n.V.kind=="message"?rr(n.V.T(),Ye(r),Ye(o)):sr(n.V.kind=="enum"?f.INT32:n.V.T,Ye(r),Ye(o))))return!1;break;case"message":let l=n.T();if(!(n.repeat?rr(l,r,o):l.equals(r,o)))return!1;break}}return!0}var Ye=Object.values;function ar(s,e,t){if(e===t)return!0;if(s!==f.BYTES)return!1;let n=e,i=t;if(n.length!==i.length)return!1;for(let r=0;r<n.length;r++)if(n[r]!=i[r])return!1;return!0}function sr(s,e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!ar(s,e[n],t[n]))return!1;return!0}function rr(s,e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!s.equals(e[n],t[n]))return!1;return!0}var lr=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),zr=lr[Ke]={},E=class{constructor(e,t,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=t.map(tr),this.options=n??{},zr.value=this,this.messagePrototype=Object.create(null,lr),this.refTypeCheck=new je(this),this.refJsonReader=new Qe(this),this.refJsonWriter=new Ge(this),this.refBinReader=new Xe(this),this.refBinWriter=new Je(this)}create(e){let t=ir(this);return e!==void 0&&T(this,t,e),t}clone(e){let t=this.create();return T(this,t,e),t}equals(e,t){return or(this,e,t)}is(e,t=this.defaultCheckDepth){return this.refTypeCheck.is(e,t,!1)}isAssignable(e,t=this.defaultCheckDepth){return this.refTypeCheck.is(e,t,!0)}mergePartial(e,t){T(this,e,t)}fromBinary(e,t){let n=Qs(t);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,t){return this.internalJsonRead(e,Zs(t))}fromJsonString(e,t){let n=JSON.parse(e);return this.fromJson(n,t)}toJson(e,t){return this.internalJsonWrite(e,er(t))}toJsonString(e,t){var n;let i=this.toJson(e,t);return JSON.stringify(i,null,(n=t?.prettySpaces)!==null&&n!==void 0?n:0)}toBinary(e,t){let n=Xs(t);return this.internalBinaryWrite(e,n.writerFactory(),n).finish()}internalJsonRead(e,t,n){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let i=n??this.create();return this.refJsonReader.read(e,i,t),i}throw new Error(`Unable to parse message ${this.typeName} from JSON ${Be(e)}.`)}internalJsonWrite(e,t){return this.refJsonWriter.write(e,t)}internalBinaryWrite(e,t,n){return this.refBinWriter.write(e,t,n),t}internalBinaryRead(e,t,n,i){let r=i??this.create();return this.refBinReader.read(e,r,n,t),r}};var yi=class extends E{constructor(){super("base_message",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},qr=new yi,Si=class extends E{constructor(){super("peerConnectionOptions",[])}create(e){let t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Ze=new Si,bi=class extends E{constructor(){super("config",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"peerConnectionOptions",kind:"message",T:()=>Ze},{no:3,name:"protocolVersion",kind:"scalar",opt:!0,T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.peerConnectionOptions=Ze.internalBinaryRead(e,e.uint32(),n,r.peerConnectionOptions);break;case 3:r.protocolVersion=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.peerConnectionOptions&&Ze.internalBinaryWrite(e.peerConnectionOptions,t.tag(2,g.LengthDelimited).fork(),n).join(),e.protocolVersion!==void 0&&t.tag(3,g.LengthDelimited).string(e.protocolVersion);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Qi=new bi,vi=class extends E{constructor(){super("identify",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Gi=new vi,wi=class extends E{constructor(){super("endpointId",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"protocolVersion",kind:"scalar",opt:!0,T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.id="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.id=e.string();break;case 3:r.protocolVersion=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.id!==""&&t.tag(2,g.LengthDelimited).string(e.id),e.protocolVersion!==void 0&&t.tag(3,g.LengthDelimited).string(e.protocolVersion);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Xi=new wi,Ci=class extends E{constructor(){super("endpointIdConfirm",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"committedId",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.committedId="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.committedId=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.committedId!==""&&t.tag(2,g.LengthDelimited).string(e.committedId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Ji=new Ci,Mi=class extends E{constructor(){super("streamerIdChanged",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"newID",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.newID="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.newID=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.newID!==""&&t.tag(2,g.LengthDelimited).string(e.newID);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Kr=new Mi,Ti=class extends E{constructor(){super("listStreamers",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Yi=new Ti,Ei=class extends E{constructor(){super("streamerList",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"ids",kind:"scalar",repeat:2,T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.ids=[],e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.ids.push(e.string());break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);for(let r=0;r<e.ids.length;r++)t.tag(2,g.LengthDelimited).string(e.ids[r]);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Zi=new Ei,Ri=class extends E{constructor(){super("subscribe",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"streamerId",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.streamerId="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.streamerId=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.streamerId!==""&&t.tag(2,g.LengthDelimited).string(e.streamerId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},es=new Ri,ki=class extends E{constructor(){super("unsubscribe",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ts=new ki,xi=class extends E{constructor(){super("subscribeFailed",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"message",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.message="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.message=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.message!==""&&t.tag(2,g.LengthDelimited).string(e.message);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},jr=new xi,Ii=class extends E{constructor(){super("playerConnected",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"dataChannel",kind:"scalar",T:8},{no:3,name:"sfu",kind:"scalar",T:8},{no:5,name:"playerId",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.dataChannel=!1,t.sfu=!1,t.playerId="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.dataChannel=e.bool();break;case 3:r.sfu=e.bool();break;case 5:r.playerId=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.dataChannel!==!1&&t.tag(2,g.Varint).bool(e.dataChannel),e.sfu!==!1&&t.tag(3,g.Varint).bool(e.sfu),e.playerId!==""&&t.tag(5,g.LengthDelimited).string(e.playerId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ns=new Ii,Pi=class extends E{constructor(){super("playerDisconnected",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"playerId",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.playerId="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.playerId=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.playerId!==""&&t.tag(2,g.LengthDelimited).string(e.playerId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},is=new Pi,Li=class extends E{constructor(){super("offer",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"playerId",kind:"scalar",opt:!0,T:9},{no:4,name:"sfu",kind:"scalar",opt:!0,T:8},{no:5,name:"multiplex",kind:"scalar",opt:!0,T:8},{no:6,name:"scalabilityMode",kind:"scalar",opt:!0,T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.sdp="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.sdp=e.string();break;case 3:r.playerId=e.string();break;case 4:r.sfu=e.bool();break;case 5:r.multiplex=e.bool();break;case 6:r.scalabilityMode=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.sdp!==""&&t.tag(2,g.LengthDelimited).string(e.sdp),e.playerId!==void 0&&t.tag(3,g.LengthDelimited).string(e.playerId),e.sfu!==void 0&&t.tag(4,g.Varint).bool(e.sfu),e.multiplex!==void 0&&t.tag(5,g.Varint).bool(e.multiplex),e.scalabilityMode!==void 0&&t.tag(6,g.LengthDelimited).string(e.scalabilityMode);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ss=new Li,Di=class extends E{constructor(){super("answer",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"playerId",kind:"scalar",opt:!0,T:9},{no:4,name:"minBitrateBps",kind:"scalar",opt:!0,T:5},{no:5,name:"maxBitrateBps",kind:"scalar",opt:!0,T:5}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.sdp="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.sdp=e.string();break;case 3:r.playerId=e.string();break;case 4:r.minBitrateBps=e.int32();break;case 5:r.maxBitrateBps=e.int32();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.sdp!==""&&t.tag(2,g.LengthDelimited).string(e.sdp),e.playerId!==void 0&&t.tag(3,g.LengthDelimited).string(e.playerId),e.minBitrateBps!==void 0&&t.tag(4,g.Varint).int32(e.minBitrateBps),e.maxBitrateBps!==void 0&&t.tag(5,g.Varint).int32(e.maxBitrateBps);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},rs=new Di,Oi=class extends E{constructor(){super("iceCandidateData",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"sdpMid",kind:"scalar",T:9},{no:3,name:"sdpMLineIndex",kind:"scalar",T:5},{no:4,name:"usernameFragment",kind:"scalar",opt:!0,T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.candidate="",t.sdpMid="",t.sdpMLineIndex=0,e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.candidate=e.string();break;case 2:r.sdpMid=e.string();break;case 3:r.sdpMLineIndex=e.int32();break;case 4:r.usernameFragment=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.candidate!==""&&t.tag(1,g.LengthDelimited).string(e.candidate),e.sdpMid!==""&&t.tag(2,g.LengthDelimited).string(e.sdpMid),e.sdpMLineIndex!==0&&t.tag(3,g.Varint).int32(e.sdpMLineIndex),e.usernameFragment!==void 0&&t.tag(4,g.LengthDelimited).string(e.usernameFragment);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},et=new Oi,Fi=class extends E{constructor(){super("iceCandidate",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"candidate",kind:"message",T:()=>et},{no:3,name:"playerId",kind:"scalar",opt:!0,T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.candidate=et.internalBinaryRead(e,e.uint32(),n,r.candidate);break;case 3:r.playerId=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.candidate&&et.internalBinaryWrite(e.candidate,t.tag(2,g.LengthDelimited).fork(),n).join(),e.playerId!==void 0&&t.tag(3,g.LengthDelimited).string(e.playerId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},os=new Fi,Ai=class extends E{constructor(){super("disconnectPlayer",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"playerId",kind:"scalar",T:9},{no:3,name:"reason",kind:"scalar",opt:!0,T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.playerId="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.playerId=e.string();break;case 3:r.reason=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.playerId!==""&&t.tag(2,g.LengthDelimited).string(e.playerId),e.reason!==void 0&&t.tag(3,g.LengthDelimited).string(e.reason);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},as=new Ai,Ni=class extends E{constructor(){super("ping",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"time",kind:"scalar",T:5}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.time=0,e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.time=e.int32();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.time!==0&&t.tag(2,g.Varint).int32(e.time);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},be=new Ni,Ui=class extends E{constructor(){super("pong",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"time",kind:"scalar",T:5}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.time=0,e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.time=e.int32();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.time!==0&&t.tag(2,g.Varint).int32(e.time);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ls=new Ui,Bi=class extends E{constructor(){super("streamerDisconnected",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},cs=new Bi,Vi=class extends E{constructor(){super("layerPreference",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"spatialLayer",kind:"scalar",T:5},{no:3,name:"temporalLayer",kind:"scalar",T:5},{no:4,name:"playerId",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.spatialLayer=0,t.temporalLayer=0,t.playerId="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.spatialLayer=e.int32();break;case 3:r.temporalLayer=e.int32();break;case 4:r.playerId=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.spatialLayer!==0&&t.tag(2,g.Varint).int32(e.spatialLayer),e.temporalLayer!==0&&t.tag(3,g.Varint).int32(e.temporalLayer),e.playerId!==""&&t.tag(4,g.LengthDelimited).string(e.playerId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ds=new Vi,_i=class extends E{constructor(){super("dataChannelRequest",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},hs=new _i,Wi=class extends E{constructor(){super("peerDataChannels",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"playerId",kind:"scalar",T:9},{no:3,name:"sendStreamId",kind:"scalar",T:5},{no:4,name:"recvStreamId",kind:"scalar",T:5}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.playerId="",t.sendStreamId=0,t.recvStreamId=0,e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.playerId=e.string();break;case 3:r.sendStreamId=e.int32();break;case 4:r.recvStreamId=e.int32();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.playerId!==""&&t.tag(2,g.LengthDelimited).string(e.playerId),e.sendStreamId!==0&&t.tag(3,g.Varint).int32(e.sendStreamId),e.recvStreamId!==0&&t.tag(4,g.Varint).int32(e.recvStreamId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},us=new Wi,Hi=class extends E{constructor(){super("peerDataChannelsReady",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ps=new Hi,$i=class extends E{constructor(){super("streamerDataChannels",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sfuId",kind:"scalar",T:9},{no:3,name:"sendStreamId",kind:"scalar",T:5},{no:4,name:"recvStreamId",kind:"scalar",T:5}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.sfuId="",t.sendStreamId=0,t.recvStreamId=0,e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.sfuId=e.string();break;case 3:r.sendStreamId=e.int32();break;case 4:r.recvStreamId=e.int32();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.sfuId!==""&&t.tag(2,g.LengthDelimited).string(e.sfuId),e.sendStreamId!==0&&t.tag(3,g.Varint).int32(e.sendStreamId),e.recvStreamId!==0&&t.tag(4,g.Varint).int32(e.recvStreamId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ms=new $i,zi=class extends E{constructor(){super("startStreaming",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},fs=new zi,qi=class extends E{constructor(){super("stopStreaming",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},gs=new qi,Ki=class extends E{constructor(){super("playerCount",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"count",kind:"scalar",T:5}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.count=0,e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.count=e.int32();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.count!==0&&t.tag(2,g.Varint).int32(e.count);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ys=new Ki,ji=class extends E{constructor(){super("stats",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"data",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.data="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.data=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.data!==""&&t.tag(2,g.LengthDelimited).string(e.data);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Ss=new ji;var cr={answer:rs,config:Qi,disconnectPlayer:as,endpointId:Xi,endpointIdConfirm:Ji,iceCandidate:os,identify:Gi,listStreamers:Yi,offer:ss,ping:be,playerConnected:ns,playerCount:ys,playerDisconnected:is,pong:ls,stats:Ss,streamerDisconnected:cs,streamerList:Zi,subscribe:es,unsubscribe:ts,layerPreference:ds,dataChannelRequest:hs,peerDataChannels:us,peerDataChannelsReady:ps,streamerDataChannels:ms,startStreaming:fs,stopStreaming:gs};var _={};Ns(_,{createMessage:()=>bs,validateMessage:()=>Qr});function bs(s,e){let t=s.create();return t.type=s.typeName,e&&s.mergePartial(t,e),t}function Qr(s){let e=!0;if(!s.type)return d.Error(`Parsed message has no type. Rejected. ${JSON.stringify(s)}`),null;let t=cr[s.type];if(!t)return d.Error(`Message is of an unknown type: "${s.type}". Rejected.`),null;if(t.fields)for(let n of t.fields)n.opt||Object.prototype.hasOwnProperty.call(s,n.name)||(d.Error(`Message "${s.type}"" is missing required field "${n.name}". Rejected.`),e=!1);for(let n in s)t.fields.find(r=>r.name===n)||(d.Error(`Message "${s.type}" contains unknown field "${n}". Rejected.`),e=!1);return e?t:null}var ve=class{get RTT(){return this.rtt}constructor(e,t){this.alive=!1,this.rtt=0,this.protocol=e,this.timeout=t,this.onResponse=this.onHeartbeatResponse.bind(this),this.protocol.transport.on("close",this.stop.bind(this)),this.start()}start(){this.alive=!0,this.protocol.on("pong",this.onResponse),this.keepalive=setInterval(this.sendHeartbeat.bind(this),this.timeout)}stop(){clearInterval(this.keepalive),this.protocol.off("pong",this.onResponse)}sendHeartbeat(){var e;if(this.alive===!1){(e=this.onTimeout)===null||e===void 0||e.call(this);return}this.alive=!1,this.protocol.sendMessage(bs(be,{time:new Date().getTime()}))}onHeartbeatResponse(e){this.rtt=new Date().getTime()-e.time,this.alive=!0}};var tt=class{static addVideoHeaderExtensionToSdp(e,t){let n=e.split(`
|
|
36
|
+
`+JSON.stringify(e,void 0,4))}};var P={};Us(P,{answer:()=>rs,base_message:()=>Kr,config:()=>Qi,dataChannelRequest:()=>hs,disconnectPlayer:()=>as,endpointId:()=>Ji,endpointIdConfirm:()=>Xi,iceCandidate:()=>os,iceCandidateData:()=>et,identify:()=>Gi,layerPreference:()=>ds,listStreamers:()=>Yi,offer:()=>ss,peerConnectionOptions:()=>Ze,peerDataChannels:()=>us,peerDataChannelsReady:()=>ps,ping:()=>be,playerConnected:()=>ns,playerCount:()=>ys,playerDisconnected:()=>is,pong:()=>ls,startStreaming:()=>fs,stats:()=>Ss,stopStreaming:()=>gs,streamerDataChannels:()=>ms,streamerDisconnected:()=>cs,streamerIdChanged:()=>jr,streamerList:()=>Zi,subscribe:()=>es,subscribeFailed:()=>Qr,unsubscribe:()=>ts});function Be(s){let e=typeof s;if(e=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return e}function Ws(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}var Q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Ve=[];for(let s=0;s<Q.length;s++)Ve[Q[s].charCodeAt(0)]=s;Ve[45]=Q.indexOf("+");Ve[95]=Q.indexOf("/");function Hs(s){let e=s.length*3/4;s[s.length-2]=="="?e-=2:s[s.length-1]=="="&&(e-=1);let t=new Uint8Array(e),n=0,i=0,r,o=0;for(let a=0;a<s.length;a++){if(r=Ve[s.charCodeAt(a)],r===void 0)switch(s[a]){case"=":i=0;case`
|
|
37
|
+
`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:o=r,i=1;break;case 1:t[n++]=o<<2|(r&48)>>4,o=r,i=2;break;case 2:t[n++]=(o&15)<<4|(r&60)>>2,o=r,i=3;break;case 3:t[n++]=(o&3)<<6|r,i=0;break}}if(i==1)throw Error("invalid base64 string.");return t.subarray(0,n)}function $s(s){let e="",t=0,n,i=0;for(let r=0;r<s.length;r++)switch(n=s[r],t){case 0:e+=Q[n>>2],i=(n&3)<<4,t=1;break;case 1:e+=Q[i|n>>4],i=(n&15)<<2,t=2;break;case 2:e+=Q[i|n>>6],e+=Q[n&63],t=0;break}return t&&(e+=Q[i],e+="=",t==1&&(e+="=")),e}var b;(function(s){s.symbol=Symbol.for("protobuf-ts/unknown"),s.onRead=(t,n,i,r,o)=>{(e(n)?n[s.symbol]:n[s.symbol]=[]).push({no:i,wireType:r,data:o})},s.onWrite=(t,n,i)=>{for(let{no:r,wireType:o,data:a}of s.list(n))i.tag(r,o).raw(a)},s.list=(t,n)=>{if(e(t)){let i=t[s.symbol];return n?i.filter(r=>r.no==n):i}return[]},s.last=(t,n)=>s.list(t,n).slice(-1)[0];let e=t=>t&&Array.isArray(t[s.symbol])})(b||(b={}));var g;(function(s){s[s.Varint=0]="Varint",s[s.Bit64=1]="Bit64",s[s.LengthDelimited=2]="LengthDelimited",s[s.StartGroup=3]="StartGroup",s[s.EndGroup=4]="EndGroup",s[s.Bit32=5]="Bit32"})(g||(g={}));function zs(){let s=0,e=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(s|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[s,e]}let t=this.buf[this.pos++];if(s|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[s,e];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(e|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[s,e]}throw new Error("invalid varint")}function We(s,e,t){for(let r=0;r<28;r=r+7){let o=s>>>r,a=!(!(o>>>7)&&e==0),l=(a?o|128:o)&255;if(t.push(l),!a)return}let n=s>>>28&15|(e&7)<<4,i=e>>3!=0;if(t.push((i?n|128:n)&255),!!i){for(let r=3;r<31;r=r+7){let o=e>>>r,a=!!(o>>>7),l=(a?o|128:o)&255;if(t.push(l),!a)return}t.push(e>>>31&1)}}var _e=65536*65536;function ui(s){let e=s[0]=="-";e&&(s=s.slice(1));let t=1e6,n=0,i=0;function r(o,a){let l=Number(s.slice(o,a));i*=t,n=n*t+l,n>=_e&&(i=i+(n/_e|0),n=n%_e)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),[e,n,i]}function He(s,e){if(e>>>0<=2097151)return""+(_e*e+(s>>>0));let t=s&16777215,n=(s>>>24|e<<8)>>>0&16777215,i=e>>16&65535,r=t+n*6777216+i*6710656,o=n+i*8147497,a=i*2,l=1e7;r>=l&&(o+=Math.floor(r/l),r%=l),o>=l&&(a+=Math.floor(o/l),o%=l);function c(u,w){let v=u?String(u):"";return w?"0000000".slice(v.length)+v:v}return c(a,0)+c(o,a)+c(r,1)}function pi(s,e){if(s>=0){for(;s>127;)e.push(s&127|128),s=s>>>7;e.push(s)}else{for(let t=0;t<9;t++)e.push(s&127|128),s=s>>7;e.push(1)}}function qs(){let s=this.buf[this.pos++],e=s&127;if((s&128)==0)return this.assertBounds(),e;if(s=this.buf[this.pos++],e|=(s&127)<<7,(s&128)==0)return this.assertBounds(),e;if(s=this.buf[this.pos++],e|=(s&127)<<14,(s&128)==0)return this.assertBounds(),e;if(s=this.buf[this.pos++],e|=(s&127)<<21,(s&128)==0)return this.assertBounds(),e;s=this.buf[this.pos++],e|=(s&15)<<28;for(let t=5;(s&128)!==0&&t<10;t++)s=this.buf[this.pos++];if((s&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}var x;function Vr(){let s=new DataView(new ArrayBuffer(8));x=globalThis.BigInt!==void 0&&typeof s.getBigInt64=="function"&&typeof s.getBigUint64=="function"&&typeof s.setBigInt64=="function"&&typeof s.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:s}:void 0}Vr();function Ks(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}var js=/^-?[0-9]+$/,ze=4294967296,$e=2147483648,qe=class{constructor(e,t){this.lo=e|0,this.hi=t|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*ze+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}},O=class s extends qe{static from(e){if(x)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=x.C(e);case"number":if(e===0)return this.ZERO;e=x.C(e);case"bigint":if(!e)return this.ZERO;if(e<x.UMIN)throw new Error("signed value for ulong");if(e>x.UMAX)throw new Error("ulong too large");return x.V.setBigUint64(0,e,!0),new s(x.V.getInt32(0,!0),x.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!js.test(e))throw new Error("string is no integer");let[t,n,i]=ui(e);if(t)throw new Error("signed value for ulong");return new s(n,i);case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");if(e<0)throw new Error("signed value for ulong");return new s(e,e/ze)}throw new Error("unknown value "+typeof e)}toString(){return x?this.toBigInt().toString():He(this.lo,this.hi)}toBigInt(){return Ks(x),x.V.setInt32(0,this.lo,!0),x.V.setInt32(4,this.hi,!0),x.V.getBigUint64(0,!0)}};O.ZERO=new O(0,0);var L=class s extends qe{static from(e){if(x)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=x.C(e);case"number":if(e===0)return this.ZERO;e=x.C(e);case"bigint":if(!e)return this.ZERO;if(e<x.MIN)throw new Error("signed long too small");if(e>x.MAX)throw new Error("signed long too large");return x.V.setBigInt64(0,e,!0),new s(x.V.getInt32(0,!0),x.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!js.test(e))throw new Error("string is no integer");let[t,n,i]=ui(e);if(t){if(i>$e||i==$e&&n!=0)throw new Error("signed long too small")}else if(i>=$e)throw new Error("signed long too large");let r=new s(n,i);return t?r.negate():r;case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new s(e,e/ze):new s(-e,-e/ze).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return(this.hi&$e)!==0}negate(){let e=~this.hi,t=this.lo;return t?t=~t+1:e+=1,new s(t,e)}toString(){if(x)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+He(e.lo,e.hi)}return He(this.lo,this.hi)}toBigInt(){return Ks(x),x.V.setInt32(0,this.lo,!0),x.V.setInt32(4,this.hi,!0),x.V.getBigInt64(0,!0)}};L.ZERO=new L(0,0);var Qs={readUnknownField:!0,readerFactory:s=>new mi(s)};function Gs(s){return s?Object.assign(Object.assign({},Qs),s):Qs}var mi=class{constructor(e,t){this.varint64=zs,this.uint32=qs,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e){let t=this.pos;switch(e){case g.Varint:for(;this.buf[this.pos++]&128;);break;case g.Bit64:this.pos+=4;case g.Bit32:this.pos+=4;break;case g.LengthDelimited:let n=this.uint32();this.pos+=n;break;case g.StartGroup:let i;for(;(i=this.tag()[1])!==g.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return new L(...this.varint64())}uint64(){return new O(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,new L(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new O(this.sfixed32(),this.sfixed32())}sfixed64(){return new L(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}};function R(s,e){if(!s)throw new Error(e)}var _r=34028234663852886e22,Wr=-34028234663852886e22,Hr=4294967295,$r=2147483647,zr=-2147483648;function X(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>$r||s<zr)throw new Error("invalid int 32: "+s)}function ee(s){if(typeof s!="number")throw new Error("invalid uint 32: "+typeof s);if(!Number.isInteger(s)||s>Hr||s<0)throw new Error("invalid uint 32: "+s)}function ae(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>_r||s<Wr))throw new Error("invalid float 32: "+s)}var Js={writeUnknownFields:!0,writerFactory:()=>new fi};function Xs(s){return s?Object.assign(Object.assign({},Js),s):Js}var fi=class{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let t=new Uint8Array(e),n=0;for(let i=0;i<this.chunks.length;i++)t.set(this.chunks[i],n),n+=this.chunks[i].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(ee(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return X(e),pi(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){ae(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){ee(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){X(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return X(e),e=(e<<1^e>>31)>>>0,pi(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=L.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=O.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=L.from(e);return We(t.lo,t.hi,this.buf),this}sint64(e){let t=L.from(e),n=t.hi>>31,i=t.lo<<1^n,r=(t.hi<<1|t.lo>>>31)^n;return We(i,r,this.buf),this}uint64(e){let t=O.from(e);return We(t.lo,t.hi,this.buf),this}};var Ys={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Zs={ignoreUnknownFields:!1};function er(s){return s?Object.assign(Object.assign({},Zs),s):Zs}function tr(s){return s?Object.assign(Object.assign({},Ys),s):Ys}var Ke=Symbol.for("protobuf-ts/message-type");function gi(s){let e=!1,t=[];for(let n=0;n<s.length;n++){let i=s.charAt(n);i=="_"?e=!0:/\d/.test(i)?(t.push(i),e=!0):e?(t.push(i.toUpperCase()),e=!1):n==0?t.push(i.toLowerCase()):t.push(i)}return t.join("")}var f;(function(s){s[s.DOUBLE=1]="DOUBLE",s[s.FLOAT=2]="FLOAT",s[s.INT64=3]="INT64",s[s.UINT64=4]="UINT64",s[s.INT32=5]="INT32",s[s.FIXED64=6]="FIXED64",s[s.FIXED32=7]="FIXED32",s[s.BOOL=8]="BOOL",s[s.STRING=9]="STRING",s[s.BYTES=12]="BYTES",s[s.UINT32=13]="UINT32",s[s.SFIXED32=15]="SFIXED32",s[s.SFIXED64=16]="SFIXED64",s[s.SINT32=17]="SINT32",s[s.SINT64=18]="SINT64"})(f||(f={}));var V;(function(s){s[s.BIGINT=0]="BIGINT",s[s.STRING=1]="STRING",s[s.NUMBER=2]="NUMBER"})(V||(V={}));var ye;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(ye||(ye={}));function nr(s){var e,t,n,i;return s.localName=(e=s.localName)!==null&&e!==void 0?e:gi(s.name),s.jsonName=(t=s.jsonName)!==null&&t!==void 0?t:gi(s.name),s.repeat=(n=s.repeat)!==null&&n!==void 0?n:ye.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function ir(s){if(typeof s!="object"||s===null||!s.hasOwnProperty("oneofKind"))return!1;switch(typeof s.oneofKind){case"string":return s[s.oneofKind]===void 0?!1:Object.keys(s).length==2;case"undefined":return Object.keys(s).length==1;default:return!1}}var je=class{constructor(e){var t;this.fields=(t=e.fields)!==null&&t!==void 0?t:[]}prepare(){if(this.data)return;let e=[],t=[],n=[];for(let i of this.fields)if(i.oneof)n.includes(i.oneof)||(n.push(i.oneof),e.push(i.oneof),t.push(i.oneof));else switch(t.push(i.localName),i.kind){case"scalar":case"enum":(!i.opt||i.repeat)&&e.push(i.localName);break;case"message":i.repeat&&e.push(i.localName);break;case"map":e.push(i.localName);break}this.data={req:e,known:t,oneofs:Object.values(n)}}is(e,t,n=!1){if(t<0)return!0;if(e==null||typeof e!="object")return!1;this.prepare();let i=Object.keys(e),r=this.data;if(i.length<r.req.length||r.req.some(o=>!i.includes(o))||!n&&i.some(o=>!r.known.includes(o)))return!1;if(t<1)return!0;for(let o of r.oneofs){let a=e[o];if(!ir(a))return!1;if(a.oneofKind===void 0)continue;let l=this.fields.find(c=>c.localName===a.oneofKind);if(!l||!this.field(a[a.oneofKind],l,n,t))return!1}for(let o of this.fields)if(o.oneof===void 0&&!this.field(e[o.localName],o,n,t))return!1;return!0}field(e,t,n,i){let r=t.repeat;switch(t.kind){case"scalar":return e===void 0?t.opt:r?this.scalars(e,t.T,i,t.L):this.scalar(e,t.T,t.L);case"enum":return e===void 0?t.opt:r?this.scalars(e,f.INT32,i):this.scalar(e,f.INT32);case"message":return e===void 0?!0:r?this.messages(e,t.T(),n,i):this.message(e,t.T(),n,i);case"map":if(typeof e!="object"||e===null)return!1;if(i<2)return!0;if(!this.mapKeys(e,t.K,i))return!1;switch(t.V.kind){case"scalar":return this.scalars(Object.values(e),t.V.T,i,t.V.L);case"enum":return this.scalars(Object.values(e),f.INT32,i);case"message":return this.messages(Object.values(e),t.V.T(),n,i)}break}return!0}message(e,t,n,i){return n?t.isAssignable(e,i):t.is(e,i)}messages(e,t,n,i){if(!Array.isArray(e))return!1;if(i<2)return!0;if(n){for(let r=0;r<e.length&&r<i;r++)if(!t.isAssignable(e[r],i-1))return!1}else for(let r=0;r<e.length&&r<i;r++)if(!t.is(e[r],i-1))return!1;return!0}scalar(e,t,n){let i=typeof e;switch(t){case f.UINT64:case f.FIXED64:case f.INT64:case f.SFIXED64:case f.SINT64:switch(n){case V.BIGINT:return i=="bigint";case V.NUMBER:return i=="number"&&!isNaN(e);default:return i=="string"}case f.BOOL:return i=="boolean";case f.STRING:return i=="string";case f.BYTES:return e instanceof Uint8Array;case f.DOUBLE:case f.FLOAT:return i=="number"&&!isNaN(e);default:return i=="number"&&Number.isInteger(e)}}scalars(e,t,n,i){if(!Array.isArray(e))return!1;if(n<2)return!0;if(Array.isArray(e)){for(let r=0;r<e.length&&r<n;r++)if(!this.scalar(e[r],t,i))return!1}return!0}mapKeys(e,t,n){let i=Object.keys(e);switch(t){case f.INT32:case f.FIXED32:case f.SFIXED32:case f.SINT32:case f.UINT32:return this.scalars(i.slice(0,n).map(r=>parseInt(r)),t,n);case f.BOOL:return this.scalars(i.slice(0,n).map(r=>r=="true"?!0:r=="false"?!1:r),t,n);default:return this.scalars(i,t,n,V.STRING)}}};function W(s,e){switch(e){case V.BIGINT:return s.toBigInt();case V.NUMBER:return s.toNumber();default:return s.toString()}}var Qe=class{constructor(e){this.info=e}prepare(){var e;if(this.fMap===void 0){this.fMap={};let t=(e=this.info.fields)!==null&&e!==void 0?e:[];for(let n of t)this.fMap[n.name]=n,this.fMap[n.jsonName]=n,this.fMap[n.localName]=n}}assert(e,t,n){if(!e){let i=Be(n);throw(i=="number"||i=="boolean")&&(i=n.toString()),new Error(`Cannot parse JSON ${i} for ${this.info.typeName}#${t}`)}}read(e,t,n){this.prepare();let i=[];for(let[r,o]of Object.entries(e)){let a=this.fMap[r];if(!a){if(!n.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${r}`);continue}let l=a.localName,c;if(a.oneof){if(o===null&&(a.kind!=="enum"||a.T()[0]!=="google.protobuf.NullValue"))continue;if(i.includes(a.oneof))throw new Error(`Multiple members of the oneof group "${a.oneof}" of ${this.info.typeName} are present in JSON.`);i.push(a.oneof),c=t[a.oneof]={oneofKind:l}}else c=t;if(a.kind=="map"){if(o===null)continue;this.assert(Ws(o),a.name,o);let u=c[l];for(let[w,v]of Object.entries(o)){this.assert(v!==null,a.name+" map value",null);let C;switch(a.V.kind){case"message":C=a.V.T().internalJsonRead(v,n);break;case"enum":if(C=this.enum(a.V.T(),v,a.name,n.ignoreUnknownFields),C===!1)continue;break;case"scalar":C=this.scalar(v,a.V.T,a.V.L,a.name);break}this.assert(C!==void 0,a.name+" map value",v);let k=w;a.K==f.BOOL&&(k=k=="true"?!0:k=="false"?!1:k),k=this.scalar(k,a.K,V.STRING,a.name).toString(),u[k]=C}}else if(a.repeat){if(o===null)continue;this.assert(Array.isArray(o),a.name,o);let u=c[l];for(let w of o){this.assert(w!==null,a.name,null);let v;switch(a.kind){case"message":v=a.T().internalJsonRead(w,n);break;case"enum":if(v=this.enum(a.T(),w,a.name,n.ignoreUnknownFields),v===!1)continue;break;case"scalar":v=this.scalar(w,a.T,a.L,a.name);break}this.assert(v!==void 0,a.name,o),u.push(v)}}else switch(a.kind){case"message":if(o===null&&a.T().typeName!="google.protobuf.Value"){this.assert(a.oneof===void 0,a.name+" (oneof member)",null);continue}c[l]=a.T().internalJsonRead(o,n,c[l]);break;case"enum":if(o===null)continue;let u=this.enum(a.T(),o,a.name,n.ignoreUnknownFields);if(u===!1)continue;c[l]=u;break;case"scalar":if(o===null)continue;c[l]=this.scalar(o,a.T,a.L,a.name);break}}}enum(e,t,n,i){if(e[0]=="google.protobuf.NullValue"&&R(t===null||t==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} only accepts null.`),t===null)return 0;switch(typeof t){case"number":return R(Number.isInteger(t),`Unable to parse field ${this.info.typeName}#${n}, enum can only be integral number, got ${t}.`),t;case"string":let r=t;e[2]&&t.substring(0,e[2].length)===e[2]&&(r=t.substring(e[2].length));let o=e[1][r];return typeof o>"u"&&i?!1:(R(typeof o=="number",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} has no value for "${t}".`),o)}R(!1,`Unable to parse field ${this.info.typeName}#${n}, cannot parse enum value from ${typeof t}".`)}scalar(e,t,n,i){let r;try{switch(t){case f.DOUBLE:case f.FLOAT:if(e===null)return 0;if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""){r="empty string";break}if(typeof e=="string"&&e.trim().length!==e.length){r="extra whitespace";break}if(typeof e!="string"&&typeof e!="number")break;let o=Number(e);if(Number.isNaN(o)){r="not a number";break}if(!Number.isFinite(o)){r="too large or small";break}return t==f.FLOAT&&ae(o),o;case f.INT32:case f.FIXED32:case f.SFIXED32:case f.SINT32:case f.UINT32:if(e===null)return 0;let a;if(typeof e=="number"?a=e:e===""?r="empty string":typeof e=="string"&&(e.trim().length!==e.length?r="extra whitespace":a=Number(e)),a===void 0)break;return t==f.UINT32?ee(a):X(a),a;case f.INT64:case f.SFIXED64:case f.SINT64:if(e===null)return W(L.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return W(L.from(e),n);case f.FIXED64:case f.UINT64:if(e===null)return W(O.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return W(O.from(e),n);case f.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case f.STRING:if(e===null)return"";if(typeof e!="string"){r="extra whitespace";break}try{encodeURIComponent(e)}catch(l){l="invalid UTF8";break}return e;case f.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return Hs(e)}}catch(o){r=o.message}this.assert(!1,i+(r?" - "+r:""),e)}};var Ge=class{constructor(e){var t;this.fields=(t=e.fields)!==null&&t!==void 0?t:[]}write(e,t){let n={},i=e;for(let r of this.fields){if(!r.oneof){let c=this.field(r,i[r.localName],t);c!==void 0&&(n[t.useProtoFieldName?r.name:r.jsonName]=c);continue}let o=i[r.oneof];if(o.oneofKind!==r.localName)continue;let a=r.kind=="scalar"||r.kind=="enum"?Object.assign(Object.assign({},t),{emitDefaultValues:!0}):t,l=this.field(r,o[r.localName],a);R(l!==void 0),n[t.useProtoFieldName?r.name:r.jsonName]=l}return n}field(e,t,n){let i;if(e.kind=="map"){R(typeof t=="object"&&t!==null);let r={};switch(e.V.kind){case"scalar":for(let[l,c]of Object.entries(t)){let u=this.scalar(e.V.T,c,e.name,!1,!0);R(u!==void 0),r[l.toString()]=u}break;case"message":let o=e.V.T();for(let[l,c]of Object.entries(t)){let u=this.message(o,c,e.name,n);R(u!==void 0),r[l.toString()]=u}break;case"enum":let a=e.V.T();for(let[l,c]of Object.entries(t)){R(c===void 0||typeof c=="number");let u=this.enum(a,c,e.name,!1,!0,n.enumAsInteger);R(u!==void 0),r[l.toString()]=u}break}(n.emitDefaultValues||Object.keys(r).length>0)&&(i=r)}else if(e.repeat){R(Array.isArray(t));let r=[];switch(e.kind){case"scalar":for(let l=0;l<t.length;l++){let c=this.scalar(e.T,t[l],e.name,e.opt,!0);R(c!==void 0),r.push(c)}break;case"enum":let o=e.T();for(let l=0;l<t.length;l++){R(t[l]===void 0||typeof t[l]=="number");let c=this.enum(o,t[l],e.name,e.opt,!0,n.enumAsInteger);R(c!==void 0),r.push(c)}break;case"message":let a=e.T();for(let l=0;l<t.length;l++){let c=this.message(a,t[l],e.name,n);R(c!==void 0),r.push(c)}break}(n.emitDefaultValues||r.length>0||n.emitDefaultValues)&&(i=r)}else switch(e.kind){case"scalar":i=this.scalar(e.T,t,e.name,e.opt,n.emitDefaultValues);break;case"enum":i=this.enum(e.T(),t,e.name,e.opt,n.emitDefaultValues,n.enumAsInteger);break;case"message":i=this.message(e.T(),t,e.name,n);break}return i}enum(e,t,n,i,r,o){if(e[0]=="google.protobuf.NullValue")return!r&&!i?void 0:null;if(t===void 0){R(i);return}if(!(t===0&&!r&&!i))return R(typeof t=="number"),R(Number.isInteger(t)),o||!e[1].hasOwnProperty(t)?t:e[2]?e[2]+e[1][t]:e[1][t]}message(e,t,n,i){return t===void 0?i.emitDefaultValues?null:void 0:e.internalJsonWrite(t,i)}scalar(e,t,n,i,r){if(t===void 0){R(i);return}let o=r||i;switch(e){case f.INT32:case f.SFIXED32:case f.SINT32:return t===0?o?0:void 0:(X(t),t);case f.FIXED32:case f.UINT32:return t===0?o?0:void 0:(ee(t),t);case f.FLOAT:ae(t);case f.DOUBLE:return t===0?o?0:void 0:(R(typeof t=="number"),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t);case f.STRING:return t===""?o?"":void 0:(R(typeof t=="string"),t);case f.BOOL:return t===!1?o?!1:void 0:(R(typeof t=="boolean"),t);case f.UINT64:case f.FIXED64:R(typeof t=="number"||typeof t=="string"||typeof t=="bigint");let a=O.from(t);return a.isZero()&&!o?void 0:a.toString();case f.INT64:case f.SFIXED64:case f.SINT64:R(typeof t=="number"||typeof t=="string"||typeof t=="bigint");let l=L.from(t);return l.isZero()&&!o?void 0:l.toString();case f.BYTES:return R(t instanceof Uint8Array),t.byteLength?$s(t):o?"":void 0}}};function Se(s,e=V.STRING){switch(s){case f.BOOL:return!1;case f.UINT64:case f.FIXED64:return W(O.ZERO,e);case f.INT64:case f.SFIXED64:case f.SINT64:return W(L.ZERO,e);case f.DOUBLE:case f.FLOAT:return 0;case f.BYTES:return new Uint8Array(0);case f.STRING:return"";default:return 0}}var Je=class{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){let t=(e=this.info.fields)!==null&&e!==void 0?e:[];this.fieldNoToField=new Map(t.map(n=>[n.no,n]))}}read(e,t,n,i){this.prepare();let r=i===void 0?e.len:e.pos+i;for(;e.pos<r;){let[o,a]=e.tag(),l=this.fieldNoToField.get(o);if(!l){let v=n.readUnknownField;if(v=="throw")throw new Error(`Unknown field ${o} (wire type ${a}) for ${this.info.typeName}`);let C=e.skip(a);v!==!1&&(v===!0?b.onRead:v)(this.info.typeName,t,o,a,C);continue}let c=t,u=l.repeat,w=l.localName;switch(l.oneof&&(c=c[l.oneof],c.oneofKind!==w&&(c=t[l.oneof]={oneofKind:w})),l.kind){case"scalar":case"enum":let v=l.kind=="enum"?f.INT32:l.T,C=l.kind=="scalar"?l.L:void 0;if(u){let H=c[w];if(a==g.LengthDelimited&&v!=f.STRING&&v!=f.BYTES){let A=e.uint32()+e.pos;for(;e.pos<A;)H.push(this.scalar(e,v,C))}else H.push(this.scalar(e,v,C))}else c[w]=this.scalar(e,v,C);break;case"message":if(u){let H=c[w],A=l.T().internalBinaryRead(e,e.uint32(),n);H.push(A)}else c[w]=l.T().internalBinaryRead(e,e.uint32(),n,c[w]);break;case"map":let[k,U]=this.mapEntry(l,e,n);c[w][k]=U;break}}}mapEntry(e,t,n){let i=t.uint32(),r=t.pos+i,o,a;for(;t.pos<r;){let[l,c]=t.tag();switch(l){case 1:e.K==f.BOOL?o=t.bool().toString():o=this.scalar(t,e.K,V.STRING);break;case 2:switch(e.V.kind){case"scalar":a=this.scalar(t,e.V.T,e.V.L);break;case"enum":a=t.int32();break;case"message":a=e.V.T().internalBinaryRead(t,t.uint32(),n);break}break;default:throw new Error(`Unknown field ${l} (wire type ${c}) in map entry for ${this.info.typeName}#${e.name}`)}}if(o===void 0){let l=Se(e.K);o=e.K==f.BOOL?l.toString():l}if(a===void 0)switch(e.V.kind){case"scalar":a=Se(e.V.T,e.V.L);break;case"enum":a=0;break;case"message":a=e.V.T().create();break}return[o,a]}scalar(e,t,n){switch(t){case f.INT32:return e.int32();case f.STRING:return e.string();case f.BOOL:return e.bool();case f.DOUBLE:return e.double();case f.FLOAT:return e.float();case f.INT64:return W(e.int64(),n);case f.UINT64:return W(e.uint64(),n);case f.FIXED64:return W(e.fixed64(),n);case f.FIXED32:return e.fixed32();case f.BYTES:return e.bytes();case f.UINT32:return e.uint32();case f.SFIXED32:return e.sfixed32();case f.SFIXED64:return W(e.sfixed64(),n);case f.SINT32:return e.sint32();case f.SINT64:return W(e.sint64(),n)}}};var Xe=class{constructor(e){this.info=e}prepare(){if(!this.fields){let e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((t,n)=>t.no-n.no)}}write(e,t,n){this.prepare();for(let r of this.fields){let o,a,l=r.repeat,c=r.localName;if(r.oneof){let u=e[r.oneof];if(u.oneofKind!==c)continue;o=u[c],a=!0}else o=e[c],a=!1;switch(r.kind){case"scalar":case"enum":let u=r.kind=="enum"?f.INT32:r.T;if(l)if(R(Array.isArray(o)),l==ye.PACKED)this.packed(t,u,r.no,o);else for(let w of o)this.scalar(t,u,r.no,w,!0);else o===void 0?R(r.opt):this.scalar(t,u,r.no,o,a||r.opt);break;case"message":if(l){R(Array.isArray(o));for(let w of o)this.message(t,n,r.T(),r.no,w)}else this.message(t,n,r.T(),r.no,o);break;case"map":R(typeof o=="object"&&o!==null);for(let[w,v]of Object.entries(o))this.mapEntry(t,n,r,w,v);break}}let i=n.writeUnknownFields;i!==!1&&(i===!0?b.onWrite:i)(this.info.typeName,e,t)}mapEntry(e,t,n,i,r){e.tag(n.no,g.LengthDelimited),e.fork();let o=i;switch(n.K){case f.INT32:case f.FIXED32:case f.UINT32:case f.SFIXED32:case f.SINT32:o=Number.parseInt(i);break;case f.BOOL:R(i=="true"||i=="false"),o=i=="true";break}switch(this.scalar(e,n.K,1,o,!0),n.V.kind){case"scalar":this.scalar(e,n.V.T,2,r,!0);break;case"enum":this.scalar(e,f.INT32,2,r,!0);break;case"message":this.message(e,t,n.V.T(),2,r);break}e.join()}message(e,t,n,i,r){r!==void 0&&(n.internalBinaryWrite(r,e.tag(i,g.LengthDelimited).fork(),t),e.join())}scalar(e,t,n,i,r){let[o,a,l]=this.scalarInfo(t,i);(!l||r)&&(e.tag(n,o),e[a](i))}packed(e,t,n,i){if(!i.length)return;R(t!==f.BYTES&&t!==f.STRING),e.tag(n,g.LengthDelimited),e.fork();let[,r]=this.scalarInfo(t);for(let o=0;o<i.length;o++)e[r](i[o]);e.join()}scalarInfo(e,t){let n=g.Varint,i,r=t===void 0,o=t===0;switch(e){case f.INT32:i="int32";break;case f.STRING:o=r||!t.length,n=g.LengthDelimited,i="string";break;case f.BOOL:o=t===!1,i="bool";break;case f.UINT32:i="uint32";break;case f.DOUBLE:n=g.Bit64,i="double";break;case f.FLOAT:n=g.Bit32,i="float";break;case f.INT64:o=r||L.from(t).isZero(),i="int64";break;case f.UINT64:o=r||O.from(t).isZero(),i="uint64";break;case f.FIXED64:o=r||O.from(t).isZero(),n=g.Bit64,i="fixed64";break;case f.BYTES:o=r||!t.byteLength,n=g.LengthDelimited,i="bytes";break;case f.FIXED32:n=g.Bit32,i="fixed32";break;case f.SFIXED32:n=g.Bit32,i="sfixed32";break;case f.SFIXED64:o=r||L.from(t).isZero(),n=g.Bit64,i="sfixed64";break;case f.SINT32:i="sint32";break;case f.SINT64:o=r||L.from(t).isZero(),i="sint64";break}return[n,i,r||o]}};function sr(s){let e=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},Ke,{value:s});for(let t of s.fields){let n=t.localName;if(!t.opt)if(t.oneof)e[t.oneof]={oneofKind:void 0};else if(t.repeat)e[n]=[];else switch(t.kind){case"scalar":e[n]=Se(t.T,t.L);break;case"enum":e[n]=0;break;case"map":e[n]={};break}}return e}function T(s,e,t){let n,i=t,r;for(let o of s.fields){let a=o.localName;if(o.oneof){let l=i[o.oneof];if(l?.oneofKind==null)continue;if(n=l[a],r=e[o.oneof],r.oneofKind=l.oneofKind,n==null){delete r[a];continue}}else if(n=i[a],r=e,n==null)continue;switch(o.repeat&&(r[a].length=n.length),o.kind){case"scalar":case"enum":if(o.repeat)for(let c=0;c<n.length;c++)r[a][c]=n[c];else r[a]=n;break;case"message":let l=o.T();if(o.repeat)for(let c=0;c<n.length;c++)r[a][c]=l.create(n[c]);else r[a]===void 0?r[a]=l.create(n):l.mergePartial(r[a],n);break;case"map":switch(o.V.kind){case"scalar":case"enum":Object.assign(r[a],n);break;case"message":let c=o.V.T();for(let u of Object.keys(n))r[a][u]=c.create(n[u]);break}break}}}function ar(s,e,t){if(e===t)return!0;if(!e||!t)return!1;for(let n of s.fields){let i=n.localName,r=n.oneof?e[n.oneof][i]:e[i],o=n.oneof?t[n.oneof][i]:t[i];switch(n.kind){case"enum":case"scalar":let a=n.kind=="enum"?f.INT32:n.T;if(!(n.repeat?rr(a,r,o):lr(a,r,o)))return!1;break;case"map":if(!(n.V.kind=="message"?or(n.V.T(),Ye(r),Ye(o)):rr(n.V.kind=="enum"?f.INT32:n.V.T,Ye(r),Ye(o))))return!1;break;case"message":let l=n.T();if(!(n.repeat?or(l,r,o):l.equals(r,o)))return!1;break}}return!0}var Ye=Object.values;function lr(s,e,t){if(e===t)return!0;if(s!==f.BYTES)return!1;let n=e,i=t;if(n.length!==i.length)return!1;for(let r=0;r<n.length;r++)if(n[r]!=i[r])return!1;return!0}function rr(s,e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!lr(s,e[n],t[n]))return!1;return!0}function or(s,e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!s.equals(e[n],t[n]))return!1;return!0}var cr=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),qr=cr[Ke]={},E=class{constructor(e,t,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=t.map(nr),this.options=n??{},qr.value=this,this.messagePrototype=Object.create(null,cr),this.refTypeCheck=new je(this),this.refJsonReader=new Qe(this),this.refJsonWriter=new Ge(this),this.refBinReader=new Je(this),this.refBinWriter=new Xe(this)}create(e){let t=sr(this);return e!==void 0&&T(this,t,e),t}clone(e){let t=this.create();return T(this,t,e),t}equals(e,t){return ar(this,e,t)}is(e,t=this.defaultCheckDepth){return this.refTypeCheck.is(e,t,!1)}isAssignable(e,t=this.defaultCheckDepth){return this.refTypeCheck.is(e,t,!0)}mergePartial(e,t){T(this,e,t)}fromBinary(e,t){let n=Gs(t);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,t){return this.internalJsonRead(e,er(t))}fromJsonString(e,t){let n=JSON.parse(e);return this.fromJson(n,t)}toJson(e,t){return this.internalJsonWrite(e,tr(t))}toJsonString(e,t){var n;let i=this.toJson(e,t);return JSON.stringify(i,null,(n=t?.prettySpaces)!==null&&n!==void 0?n:0)}toBinary(e,t){let n=Xs(t);return this.internalBinaryWrite(e,n.writerFactory(),n).finish()}internalJsonRead(e,t,n){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let i=n??this.create();return this.refJsonReader.read(e,i,t),i}throw new Error(`Unable to parse message ${this.typeName} from JSON ${Be(e)}.`)}internalJsonWrite(e,t){return this.refJsonWriter.write(e,t)}internalBinaryWrite(e,t,n){return this.refBinWriter.write(e,t,n),t}internalBinaryRead(e,t,n,i){let r=i??this.create();return this.refBinReader.read(e,r,n,t),r}};var yi=class extends E{constructor(){super("base_message",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Kr=new yi,Si=class extends E{constructor(){super("peerConnectionOptions",[])}create(e){let t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Ze=new Si,bi=class extends E{constructor(){super("config",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"peerConnectionOptions",kind:"message",T:()=>Ze},{no:3,name:"protocolVersion",kind:"scalar",opt:!0,T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.peerConnectionOptions=Ze.internalBinaryRead(e,e.uint32(),n,r.peerConnectionOptions);break;case 3:r.protocolVersion=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.peerConnectionOptions&&Ze.internalBinaryWrite(e.peerConnectionOptions,t.tag(2,g.LengthDelimited).fork(),n).join(),e.protocolVersion!==void 0&&t.tag(3,g.LengthDelimited).string(e.protocolVersion);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Qi=new bi,vi=class extends E{constructor(){super("identify",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Gi=new vi,wi=class extends E{constructor(){super("endpointId",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"protocolVersion",kind:"scalar",opt:!0,T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.id="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.id=e.string();break;case 3:r.protocolVersion=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.id!==""&&t.tag(2,g.LengthDelimited).string(e.id),e.protocolVersion!==void 0&&t.tag(3,g.LengthDelimited).string(e.protocolVersion);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Ji=new wi,Ci=class extends E{constructor(){super("endpointIdConfirm",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"committedId",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.committedId="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.committedId=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.committedId!==""&&t.tag(2,g.LengthDelimited).string(e.committedId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Xi=new Ci,Mi=class extends E{constructor(){super("streamerIdChanged",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"newID",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.newID="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.newID=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.newID!==""&&t.tag(2,g.LengthDelimited).string(e.newID);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},jr=new Mi,Ti=class extends E{constructor(){super("listStreamers",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Yi=new Ti,Ei=class extends E{constructor(){super("streamerList",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"ids",kind:"scalar",repeat:2,T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.ids=[],e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.ids.push(e.string());break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);for(let r=0;r<e.ids.length;r++)t.tag(2,g.LengthDelimited).string(e.ids[r]);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Zi=new Ei,Ri=class extends E{constructor(){super("subscribe",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"streamerId",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.streamerId="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.streamerId=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.streamerId!==""&&t.tag(2,g.LengthDelimited).string(e.streamerId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},es=new Ri,ki=class extends E{constructor(){super("unsubscribe",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ts=new ki,xi=class extends E{constructor(){super("subscribeFailed",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"message",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.message="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.message=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.message!==""&&t.tag(2,g.LengthDelimited).string(e.message);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Qr=new xi,Ii=class extends E{constructor(){super("playerConnected",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"dataChannel",kind:"scalar",T:8},{no:3,name:"sfu",kind:"scalar",T:8},{no:5,name:"playerId",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.dataChannel=!1,t.sfu=!1,t.playerId="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.dataChannel=e.bool();break;case 3:r.sfu=e.bool();break;case 5:r.playerId=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.dataChannel!==!1&&t.tag(2,g.Varint).bool(e.dataChannel),e.sfu!==!1&&t.tag(3,g.Varint).bool(e.sfu),e.playerId!==""&&t.tag(5,g.LengthDelimited).string(e.playerId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ns=new Ii,Pi=class extends E{constructor(){super("playerDisconnected",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"playerId",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.playerId="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.playerId=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.playerId!==""&&t.tag(2,g.LengthDelimited).string(e.playerId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},is=new Pi,Li=class extends E{constructor(){super("offer",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"playerId",kind:"scalar",opt:!0,T:9},{no:4,name:"sfu",kind:"scalar",opt:!0,T:8},{no:5,name:"multiplex",kind:"scalar",opt:!0,T:8},{no:6,name:"scalabilityMode",kind:"scalar",opt:!0,T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.sdp="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.sdp=e.string();break;case 3:r.playerId=e.string();break;case 4:r.sfu=e.bool();break;case 5:r.multiplex=e.bool();break;case 6:r.scalabilityMode=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.sdp!==""&&t.tag(2,g.LengthDelimited).string(e.sdp),e.playerId!==void 0&&t.tag(3,g.LengthDelimited).string(e.playerId),e.sfu!==void 0&&t.tag(4,g.Varint).bool(e.sfu),e.multiplex!==void 0&&t.tag(5,g.Varint).bool(e.multiplex),e.scalabilityMode!==void 0&&t.tag(6,g.LengthDelimited).string(e.scalabilityMode);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ss=new Li,Di=class extends E{constructor(){super("answer",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"playerId",kind:"scalar",opt:!0,T:9},{no:4,name:"minBitrateBps",kind:"scalar",opt:!0,T:5},{no:5,name:"maxBitrateBps",kind:"scalar",opt:!0,T:5}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.sdp="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.sdp=e.string();break;case 3:r.playerId=e.string();break;case 4:r.minBitrateBps=e.int32();break;case 5:r.maxBitrateBps=e.int32();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.sdp!==""&&t.tag(2,g.LengthDelimited).string(e.sdp),e.playerId!==void 0&&t.tag(3,g.LengthDelimited).string(e.playerId),e.minBitrateBps!==void 0&&t.tag(4,g.Varint).int32(e.minBitrateBps),e.maxBitrateBps!==void 0&&t.tag(5,g.Varint).int32(e.maxBitrateBps);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},rs=new Di,Oi=class extends E{constructor(){super("iceCandidateData",[{no:1,name:"candidate",kind:"scalar",T:9},{no:2,name:"sdpMid",kind:"scalar",T:9},{no:3,name:"sdpMLineIndex",kind:"scalar",T:5},{no:4,name:"usernameFragment",kind:"scalar",opt:!0,T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.candidate="",t.sdpMid="",t.sdpMLineIndex=0,e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.candidate=e.string();break;case 2:r.sdpMid=e.string();break;case 3:r.sdpMLineIndex=e.int32();break;case 4:r.usernameFragment=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.candidate!==""&&t.tag(1,g.LengthDelimited).string(e.candidate),e.sdpMid!==""&&t.tag(2,g.LengthDelimited).string(e.sdpMid),e.sdpMLineIndex!==0&&t.tag(3,g.Varint).int32(e.sdpMLineIndex),e.usernameFragment!==void 0&&t.tag(4,g.LengthDelimited).string(e.usernameFragment);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},et=new Oi,Fi=class extends E{constructor(){super("iceCandidate",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"candidate",kind:"message",T:()=>et},{no:3,name:"playerId",kind:"scalar",opt:!0,T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.candidate=et.internalBinaryRead(e,e.uint32(),n,r.candidate);break;case 3:r.playerId=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.candidate&&et.internalBinaryWrite(e.candidate,t.tag(2,g.LengthDelimited).fork(),n).join(),e.playerId!==void 0&&t.tag(3,g.LengthDelimited).string(e.playerId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},os=new Fi,Ai=class extends E{constructor(){super("disconnectPlayer",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"playerId",kind:"scalar",T:9},{no:3,name:"reason",kind:"scalar",opt:!0,T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.playerId="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.playerId=e.string();break;case 3:r.reason=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.playerId!==""&&t.tag(2,g.LengthDelimited).string(e.playerId),e.reason!==void 0&&t.tag(3,g.LengthDelimited).string(e.reason);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},as=new Ai,Ni=class extends E{constructor(){super("ping",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"time",kind:"scalar",T:5}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.time=0,e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.time=e.int32();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.time!==0&&t.tag(2,g.Varint).int32(e.time);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},be=new Ni,Ui=class extends E{constructor(){super("pong",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"time",kind:"scalar",T:5}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.time=0,e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.time=e.int32();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.time!==0&&t.tag(2,g.Varint).int32(e.time);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ls=new Ui,Bi=class extends E{constructor(){super("streamerDisconnected",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},cs=new Bi,Vi=class extends E{constructor(){super("layerPreference",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"spatialLayer",kind:"scalar",T:5},{no:3,name:"temporalLayer",kind:"scalar",T:5},{no:4,name:"playerId",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.spatialLayer=0,t.temporalLayer=0,t.playerId="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.spatialLayer=e.int32();break;case 3:r.temporalLayer=e.int32();break;case 4:r.playerId=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.spatialLayer!==0&&t.tag(2,g.Varint).int32(e.spatialLayer),e.temporalLayer!==0&&t.tag(3,g.Varint).int32(e.temporalLayer),e.playerId!==""&&t.tag(4,g.LengthDelimited).string(e.playerId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ds=new Vi,_i=class extends E{constructor(){super("dataChannelRequest",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},hs=new _i,Wi=class extends E{constructor(){super("peerDataChannels",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"playerId",kind:"scalar",T:9},{no:3,name:"sendStreamId",kind:"scalar",T:5},{no:4,name:"recvStreamId",kind:"scalar",T:5}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.playerId="",t.sendStreamId=0,t.recvStreamId=0,e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.playerId=e.string();break;case 3:r.sendStreamId=e.int32();break;case 4:r.recvStreamId=e.int32();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.playerId!==""&&t.tag(2,g.LengthDelimited).string(e.playerId),e.sendStreamId!==0&&t.tag(3,g.Varint).int32(e.sendStreamId),e.recvStreamId!==0&&t.tag(4,g.Varint).int32(e.recvStreamId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},us=new Wi,Hi=class extends E{constructor(){super("peerDataChannelsReady",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ps=new Hi,$i=class extends E{constructor(){super("streamerDataChannels",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sfuId",kind:"scalar",T:9},{no:3,name:"sendStreamId",kind:"scalar",T:5},{no:4,name:"recvStreamId",kind:"scalar",T:5}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.sfuId="",t.sendStreamId=0,t.recvStreamId=0,e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.sfuId=e.string();break;case 3:r.sendStreamId=e.int32();break;case 4:r.recvStreamId=e.int32();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.sfuId!==""&&t.tag(2,g.LengthDelimited).string(e.sfuId),e.sendStreamId!==0&&t.tag(3,g.Varint).int32(e.sendStreamId),e.recvStreamId!==0&&t.tag(4,g.Varint).int32(e.recvStreamId);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ms=new $i,zi=class extends E{constructor(){super("startStreaming",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},fs=new zi,qi=class extends E{constructor(){super("stopStreaming",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},gs=new qi,Ki=class extends E{constructor(){super("playerCount",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"count",kind:"scalar",T:5}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.count=0,e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.count=e.int32();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.count!==0&&t.tag(2,g.Varint).int32(e.count);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},ys=new Ki,ji=class extends E{constructor(){super("stats",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"data",kind:"scalar",T:9}])}create(e){let t=globalThis.Object.create(this.messagePrototype);return t.type="",t.data="",e!==void 0&&T(this,t,e),t}internalBinaryRead(e,t,n,i){let r=i??this.create(),o=e.pos+t;for(;e.pos<o;){let[a,l]=e.tag();switch(a){case 1:r.type=e.string();break;case 2:r.data=e.string();break;default:let c=n.readUnknownField;if(c==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${l}) for ${this.typeName}`);let u=e.skip(l);c!==!1&&(c===!0?b.onRead:c)(this.typeName,r,a,l,u)}}return r}internalBinaryWrite(e,t,n){e.type!==""&&t.tag(1,g.LengthDelimited).string(e.type),e.data!==""&&t.tag(2,g.LengthDelimited).string(e.data);let i=n.writeUnknownFields;return i!==!1&&(i==!0?b.onWrite:i)(this.typeName,e,t),t}},Ss=new ji;var dr={answer:rs,config:Qi,disconnectPlayer:as,endpointId:Ji,endpointIdConfirm:Xi,iceCandidate:os,identify:Gi,listStreamers:Yi,offer:ss,ping:be,playerConnected:ns,playerCount:ys,playerDisconnected:is,pong:ls,stats:Ss,streamerDisconnected:cs,streamerList:Zi,subscribe:es,unsubscribe:ts,layerPreference:ds,dataChannelRequest:hs,peerDataChannels:us,peerDataChannelsReady:ps,streamerDataChannels:ms,startStreaming:fs,stopStreaming:gs};var _={};Us(_,{createMessage:()=>bs,validateMessage:()=>Gr});function bs(s,e){let t=s.create();return t.type=s.typeName,e&&s.mergePartial(t,e),t}function Gr(s){let e=!0;if(!s.type)return d.Error(`Parsed message has no type. Rejected. ${JSON.stringify(s)}`),null;let t=dr[s.type];if(!t)return d.Error(`Message is of an unknown type: "${s.type}". Rejected.`),null;if(t.fields)for(let n of t.fields)n.opt||Object.prototype.hasOwnProperty.call(s,n.name)||(d.Error(`Message "${s.type}"" is missing required field "${n.name}". Rejected.`),e=!1);for(let n in s)t.fields.find(r=>r.name===n)||(d.Error(`Message "${s.type}" contains unknown field "${n}". Rejected.`),e=!1);return e?t:null}var ve=class{get RTT(){return this.rtt}constructor(e,t){this.alive=!1,this.rtt=0,this.protocol=e,this.timeout=t,this.onResponse=this.onHeartbeatResponse.bind(this),this.protocol.transport.on("close",this.stop.bind(this)),this.start()}start(){this.alive=!0,this.protocol.on("pong",this.onResponse),this.keepalive=setInterval(this.sendHeartbeat.bind(this),this.timeout)}stop(){clearInterval(this.keepalive),this.protocol.off("pong",this.onResponse)}sendHeartbeat(){var e;if(this.alive===!1){(e=this.onTimeout)===null||e===void 0||e.call(this);return}this.alive=!1,this.protocol.sendMessage(bs(be,{time:new Date().getTime()}))}onHeartbeatResponse(e){this.rtt=new Date().getTime()-e.time,this.alive=!0}};var tt=class{static addVideoHeaderExtensionToSdp(e,t){let n=e.split(`
|
|
38
38
|
`).filter(l=>l.startsWith("a=extmap:")).map(l=>parseInt(l.split(" ")[0].substring(9),10)).sort((l,c)=>l-c).filter((l,c,u)=>u.indexOf(l)===c),r="a=extmap:"+(n[n.length-1]+1)+" "+t+`\r
|
|
39
39
|
`,o=e.split(`
|
|
40
40
|
m=`).map((l,c)=>(c>0?"m="+l:l).trim()+`\r
|
|
41
|
-
`);return o.shift()+o.map(l=>l.startsWith("m=video")?l+r:l).join("")}};var nt=class{constructor(e){this.videoElementProvider=e,this.audioElement=document.createElement("Audio"),this.videoElementProvider.setAudioElement(this.audioElement)}handleOnTrack(e){if(d.Info("handleOnTrack "+JSON.stringify(e.streams)),e.streams.length<1||e.streams[0].id=="probator")return;let t=this.videoElementProvider.getVideoElement();if(e.track&&d.Info("Got track - "+e.track.kind+" id="+e.track.id+" readyState="+e.track.readyState),e.track.kind=="audio"){this.CreateAudioTrack(e.streams[0]);return}else if(e.track.kind=="video"&&t.srcObject!==e.streams[0]){t.srcObject=e.streams[0],d.Info("Set video source from video track ontrack.");return}}CreateAudioTrack(e){let t=this.videoElementProvider.getVideoElement();t.srcObject!=e&&t.srcObject&&t.srcObject!==e&&(this.audioElement.srcObject=e,d.Info("Created new audio element to play separate audio stream."))}};var it=class{constructor(e){this.freezeFrameHeight=0,this.freezeFrameWidth=0,this.rootDiv=e,this.rootElement=document.createElement("div"),this.rootElement.id="freezeFrame",this.rootElement.style.display="none",this.rootElement.style.pointerEvents="none",this.rootElement.style.position="absolute",this.rootElement.style.zIndex="20",this.imageElement=document.createElement("img"),this.imageElement.style.position="absolute",this.rootElement.appendChild(this.imageElement),this.rootDiv.appendChild(this.rootElement)}setElementForShow(){this.rootElement.style.display="block"}setElementForHide(){this.rootElement.style.display="none"}updateImageElementSource(e){let t=btoa(e.reduce((n,i)=>n+String.fromCharCode(i),""));this.imageElement.src="data:image/jpeg;base64,"+t}setDimensionsFromElementAndResize(){this.freezeFrameHeight=this.imageElement.naturalHeight,this.freezeFrameWidth=this.imageElement.naturalWidth,this.resize()}resize(){if(this.freezeFrameWidth!==0&&this.freezeFrameHeight!==0){let e=0,t=0,n=0,i=0,r=this.rootDiv.clientWidth/this.rootDiv.clientHeight,o=this.freezeFrameWidth/this.freezeFrameHeight;r<o?(e=this.rootDiv.clientWidth,t=Math.floor(this.rootDiv.clientWidth/o),n=Math.floor((this.rootDiv.clientHeight-t)*.5),i=0):(e=Math.floor(this.rootDiv.clientHeight*o),t=this.rootDiv.clientHeight,n=0,i=Math.floor((this.rootDiv.clientWidth-e)*.5)),this.rootElement.style.width=this.rootDiv.offsetWidth+"px",this.rootElement.style.height=this.rootDiv.offsetHeight+"px",this.rootElement.style.left="0px",this.rootElement.style.top="0px",this.imageElement.style.width=e+"px",this.imageElement.style.height=t+"px",this.imageElement.style.left=i+"px",this.imageElement.style.top=n+"px"}}};var st=class{constructor(e){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new it(e)}showFreezeFrame(){this.valid&&this.freezeFrame.setElementForShow()}hideFreezeFrame(){this.valid=!1,this.freezeFrame.setElementForHide()}updateFreezeFrameAndShow(e,t){this.freezeFrame.updateImageElementSource(e),this.freezeFrame.imageElement.onload=()=>{this.freezeFrame.setDimensionsFromElementAndResize(),t()}}processFreezeFrameMessage(e,t){this.receiving||(this.receiving=!0,this.valid=!1,this.size=0,this.jpeg=void 0),this.size=new DataView(e.slice(1,5).buffer).getInt32(0,!0);let n=e.slice(5);if(this.jpeg){let i=new Uint8Array(this.jpeg.length+n.length);i.set(this.jpeg,0),i.set(n,this.jpeg.length),this.jpeg=i}else this.jpeg=n,this.receiving=!0,d.Info(`received first chunk of freeze frame: ${this.jpeg.length}/${this.size}`);this.jpeg.length===this.size?(this.receiving=!1,this.valid=!0,d.Info(`received complete freeze frame ${this.size}`),this.updateFreezeFrameAndShow(this.jpeg,t)):this.jpeg.length>this.size&&(d.Error(`received bigger freeze frame than advertised: ${this.jpeg.length}/${this.size}`),this.jpeg=void 0,this.receiving=!1)}};var j=class{constructor(e,t,n,i,r=()=>{}){this.parseURLParams(),this.onChange=r,this.onChangeEmit=()=>{},this.id=e,this.description=n,this.label=t,this.value=i}set label(e){this._label=e,this.onChangeEmit(this._value)}get label(){return this._label}get value(){return this._value}set value(e){this._value=e,this.onChange(this._value,this),this.onChangeEmit(this._value)}updateURLParams(){if(this.useUrlParams){let e=new URLSearchParams(window.location.search),t=this.getValueAsString(),n=!1;for(let[i,r]of e)if(i.toLowerCase()==this.id.toLowerCase()){e.set(i,t),n=!0;break}n||e.set(this.id,t),window.history.replaceState({},"",e.toString()!==""?`${location.pathname}?${e}`:`${location.pathname}`)}}getValueAsString(){return""}parseURLParams(){this._urlParams={};let e=new URLSearchParams(window.location.search);for(let[t,n]of e)this._urlParams[t.toLowerCase()]=n}hasURLParam(e){return e.toLowerCase()in this._urlParams}getURLParam(e){return this.hasURLParam(e)?this._urlParams[e.toLowerCase()]:""}};var I=class extends j{constructor(e,t,n,i,r,o=()=>{}){if(super(e,t,n,i,o),!r||!this.hasURLParam(this.id))this.flag=i;else{let a=this.getURLParam(this.id);this.flag=a.toLowerCase()!="false"}this.useUrlParams=r}getValueAsString(){return this.flag?"true":"false"}enable(){this.flag=!0}get flag(){return!!this.value}set flag(e){this.value=e}};var B=class extends j{constructor(e,t,n,i,r,o,a,l=()=>{}){if(super(e,t,n,o,l),this._min=i,this._max=r,!a||!this.hasURLParam(this.id))this.number=o;else{let c=Number.parseFloat(this.getURLParam(this.id));this.number=Number.isNaN(c)?o:c}this.useUrlParams=a}getValueAsString(){return this.number.toString()}set number(e){this.value=this.clamp(e)}get number(){return this.value}clamp(e){return this._min==null&&this._max==null?e:this._min==null?Math.min(this._max,e):this._max==null?Math.max(this._min,e):Math.max(Math.min(this._max,e),this._min)}get min(){return this._min}get max(){return this._max}addOnChangedListener(e){this.onChange=e}};var rt=class extends j{constructor(e,t,n,i,r,o=()=>{}){super(e,t,n,i,o),!r||!this.hasURLParam(this.id)?this.text=i:this.text=this.getURLParam(this.id),this.useUrlParams=r}getValueAsString(){return this.text}get text(){return this.value}set text(e){this.value=e}};var le=class extends j{constructor(e,t,n,i,r,o,a=function(c){return c},l=()=>{}){super(e,t,n,i,l),this._urlParamResolver=a;let c=this.hasURLParam(this.id)?this._urlParamResolver(this.getURLParam(this.id)):i;this.options=r??[c],this.selected=c,this.useUrlParams=o}getValueAsString(){return this.selected}addOnChangedListener(e){this.onChange=e}get options(){return this._options}set options(e){this._options=e,this.onChangeEmit(this.selected)}get selected(){return this.value}set selected(e){e!==void 0&&(this.options.includes(e)?this.value=e:d.Error(`Could not set "${e}" as the selected option for ${this.id} because it wasn't one of the options.`))}set urlParamResolver(e){this._urlParamResolver=e}};var ot=class extends Event{constructor(e){super("afkWarningActivate"),this.data=e}},we=class extends Event{constructor(e){super("afkWarningUpdate"),this.data=e}},at=class extends Event{constructor(){super("afkWarningDeactivate")}},lt=class extends Event{constructor(){super("afkTimedOut")}},ct=class extends Event{constructor(e){super("videoEncoderAvgQP"),this.data=e}},dt=class extends Event{constructor(){super("webRtcSdp")}},ht=class extends Event{constructor(e){super("webRtcSdpAnswer"),this.data=e}},ut=class extends Event{constructor(e){super("webRtcSdpOffer"),this.data=e}},pt=class extends Event{constructor(){super("webRtcAutoConnect")}},mt=class extends Event{constructor(){super("webRtcConnecting")}},ft=class extends Event{constructor(){super("webRtcConnected")}},gt=class extends Event{constructor(){super("webRtcFailed")}},yt=class extends Event{constructor(e){super("webRtcDisconnected"),this.data=e}},St=class extends Event{constructor(e){super("dataChannelOpen"),this.data=e}},bt=class extends Event{constructor(e){super("dataChannelClose"),this.data=e}},vt=class extends Event{constructor(e){super("dataChannelError"),this.data=e}},wt=class extends Event{constructor(){super("videoInitialized")}},Ct=class extends Event{constructor(){super("streamLoading")}},Mt=class extends Event{constructor(){super("streamConnect")}},Tt=class extends Event{constructor(){super("streamDisconnect")}},Et=class extends Event{constructor(){super("streamReconnect")}},Rt=class extends Event{constructor(e){super("playStreamError"),this.data=e}},kt=class extends Event{constructor(){super("playStream")}},Ce=class extends Event{constructor(e){super("playStreamRejected"),this.data=e}},xt=class extends Event{constructor(e){super("loadFreezeFrame"),this.data=e}},It=class extends Event{constructor(){super("hideFreezeFrame")}},Pt=class extends Event{constructor(e){super("statsReceived"),this.data=e}},Lt=class extends Event{constructor(e){super("streamerListMessage"),this.data=e}},Dt=class extends Event{constructor(e){super("StreamerIDChangedMessage"),this.data=e}},Ot=class extends Event{constructor(e){super("latencyTestResult"),this.data=e}},Ft=class extends Event{constructor(e){super("latencyCalculated"),this.data=e}},At=class extends Event{constructor(e){super("showOnScreenKeyboard"),this.data=e}},Nt=class extends Event{constructor(e){super("dataChannelLatencyTestResponse"),this.data=e}},Ut=class extends Event{constructor(e){super("dataChannelLatencyTestResult"),this.data=e}},Bt=class extends Event{constructor(e){super("subscribeFailed"),this.data=e}},Vt=class extends Event{constructor(e){super("initialSettings"),this.data=e}},te=class extends Event{constructor(e){super("settingsChanged"),this.data=e}};var _t=class extends Event{constructor(e){super("xrFrame"),this.data=e}},Wt=class extends Event{constructor(e){super("playerCount"),this.data=e}},Ht=class extends Event{constructor(){super("webRtcTCPRelayDetected")}},$t=class extends EventTarget{dispatchEvent(e){return super.dispatchEvent(e)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}};var Y=class{static getSupportedVideoCodecs(){let e=[];if(!RTCRtpReceiver.getCapabilities)return d.Warning("RTCRtpReceiver.getCapabilities API is not available in your browser, defaulting to guess that we support H.264."),e.push("H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"),e;let t=/(VP\d|H26\d|AV1).*/,n=RTCRtpReceiver.getCapabilities("video");return n?(n.codecs.forEach(i=>{let r=i.mimeType.split("/")[1]+" "+(i.sdpFmtpLine||"");t.exec(r)!==null&&e.push(r)}),e):(e.push("H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"),e)}};var h=class{};h.AutoConnect="AutoConnect";h.AutoPlayVideo="AutoPlayVideo";h.AFKDetection="TimeoutIfIdle";h.HoveringMouseMode="HoveringMouse";h.ForceMonoAudio="ForceMonoAudio";h.ForceTURN="ForceTURN";h.FakeMouseWithTouches="FakeMouseWithTouches";h.IsQualityController="ControlsQuality";h.MatchViewportResolution="MatchViewportRes";h.StartVideoMuted="StartVideoMuted";h.SuppressBrowserKeys="SuppressBrowserKeys";h.UseMic="UseMic";h.UseModalForTextInput="UseModalForTextInput";h.UseCamera="UseCamera";h.KeyboardInput="KeyboardInput";h.MouseInput="MouseInput";h.TouchInput="TouchInput";h.GamepadInput="GamepadInput";h.XRControllerInput="XRControllerInput";h.WaitForStreamer="WaitForStreamer";h.HideUI="HideUI";h.EnableCaptureTimeExt="EnableCaptureTimeExt";h.BrowserSendOffer="BrowserSendOffer";h.LatencyCSV="LatencyCSV";var Gr=s=>Object.getOwnPropertyNames(h).some(e=>h[e]===s),m=class{};m.AFKTimeoutSecs="AFKTimeout";m.AFKCountdownSecs="AFKCountdown";m.MinQP="MinQP";m.MaxQP="MaxQP";m.MinQuality="MinQuality";m.MaxQuality="MaxQuality";m.CompatQualityMin="CompatQualityMin";m.CompatQualityMax="CompatQualityMax";m.WebRTCFPS="WebRTCFPS";m.WebRTCMinBitrate="WebRTCMinBitrate";m.WebRTCMaxBitrate="WebRTCMaxBitrate";m.MaxReconnectAttempts="MaxReconnectAttempts";m.StreamerAutoJoinInterval="StreamerAutoJoinInterval";m.KeepaliveDelay="KeepaliveDelay";var Xr=s=>Object.getOwnPropertyNames(m).some(e=>m[e]===s),$=class{};$.SignallingServerUrl="ss";var Jr=s=>Object.getOwnPropertyNames($).some(e=>$[e]===s),M=class{};M.PreferredCodec="PreferredCodec";M.StreamerId="StreamerId";M.PreferredQuality="PreferredQuality";var Yr=s=>Object.getOwnPropertyNames(M).some(e=>M[e]===s),zt=class{constructor(e={}){this.flags=new Map,this.numericParameters=new Map,this.textParameters=new Map,this.optionParameters=new Map;let{initialSettings:t,useUrlParams:n,webSocketProtocols:i}=e;this._useUrlParams=!!n,this._webSocketProtocols=i,this.populateDefaultSettings(this._useUrlParams,t)}get useUrlParams(){return this._useUrlParams}get webSocketProtocols(){return this._webSocketProtocols}populateDefaultSettings(e,t){this.textParameters.set($.SignallingServerUrl,new rt($.SignallingServerUrl,"Signalling url","Url of the signalling server",t&&Object.prototype.hasOwnProperty.call(t,$.SignallingServerUrl)?t[$.SignallingServerUrl]:(location.protocol==="https:"?"wss://":"ws://")+window.location.hostname+(window.location.port==="80"||window.location.port===""?"":`:${window.location.port}`),e)),this.optionParameters.set(M.StreamerId,new le(M.StreamerId,"Streamer ID","The ID of the streamer to stream.",t&&Object.prototype.hasOwnProperty.call(t,M.StreamerId)?t[M.StreamerId]:"",t&&Object.prototype.hasOwnProperty.call(t,M.StreamerId)?[t[M.StreamerId]]:void 0,e));let n=function(){let r=Y.getSupportedVideoCodecs();if(r.length==1)return r[0];if(r.length>0){let o=r[0];for(let a of r)if(a.startsWith("H264"))return a;return o}return d.Error("Could not find any reasonable video codec to assign as a default."),""},i=function(r){let o=Y.getSupportedVideoCodecs();if(o.includes(r))return r;for(let a of o)if(a.startsWith(r))return a;return r};this.optionParameters.set(M.PreferredCodec,new le(M.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation",t&&Object.prototype.hasOwnProperty.call(t,M.PreferredCodec)?i(t[M.PreferredCodec]):n(),Y.getSupportedVideoCodecs(),e,i)),this.optionParameters.set(M.PreferredQuality,new le(M.PreferredQuality,"Preferred Quality","The preferred quality of the stream (only applicable when using the SFU)",t&&Object.prototype.hasOwnProperty.call(t,M.PreferredQuality)?t[M.PreferredQuality]:"Default",["Default"],e)),this.flags.set(h.AutoConnect,new I(h.AutoConnect,"Auto connect to stream","Whether we should attempt to auto connect to the signalling server or show a click to start prompt.",t&&Object.prototype.hasOwnProperty.call(t,h.AutoConnect)?t[h.AutoConnect]:!1,e)),this.flags.set(h.AutoPlayVideo,new I(h.AutoPlayVideo,"Auto play video","When video is ready automatically start playing it as opposed to showing a play button.",t&&Object.prototype.hasOwnProperty.call(t,h.AutoPlayVideo)?t[h.AutoPlayVideo]:!0,e)),this.flags.set(h.UseMic,new I(h.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",t&&Object.prototype.hasOwnProperty.call(t,h.UseMic)?t[h.UseMic]:!1,e)),this.flags.set(h.UseModalForTextInput,new I(h.UseModalForTextInput,"Use modal for text input","When entering input into a streamed UE text widget, use an input modal.",t&&Object.prototype.hasOwnProperty.call(t,h.UseModalForTextInput)?t[h.UseModalForTextInput]:!0,e)),this.flags.set(h.UseCamera,new I(h.UseCamera,"Use webcam","Make browser request webcam access and open a input video track.",t&&Object.prototype.hasOwnProperty.call(t,h.UseCamera)?t[h.UseCamera]:!1,e)),this.flags.set(h.StartVideoMuted,new I(h.StartVideoMuted,"Start video muted","Video will start muted if true.",t&&Object.prototype.hasOwnProperty.call(t,h.StartVideoMuted)?t[h.StartVideoMuted]:!1,e)),this.flags.set(h.SuppressBrowserKeys,new I(h.SuppressBrowserKeys,"Suppress browser keys","Suppress certain browser keys that we use in UE, for example F5 to show shader complexity instead of refresh the page.",t&&Object.prototype.hasOwnProperty.call(t,h.SuppressBrowserKeys)?t[h.SuppressBrowserKeys]:!0,e)),this.flags.set(h.IsQualityController,new I(h.IsQualityController,"Is quality controller?","True if this peer controls stream quality",t&&Object.prototype.hasOwnProperty.call(t,h.IsQualityController)?t[h.IsQualityController]:!0,e)),this.flags.set(h.ForceMonoAudio,new I(h.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",t&&Object.prototype.hasOwnProperty.call(t,h.ForceMonoAudio)?t[h.ForceMonoAudio]:!1,e)),this.flags.set(h.ForceTURN,new I(h.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",t&&Object.prototype.hasOwnProperty.call(t,h.ForceTURN)?t[h.ForceTURN]:!1,e)),this.flags.set(h.AFKDetection,new I(h.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",t&&Object.prototype.hasOwnProperty.call(t,h.AFKDetection)?t[h.AFKDetection]:!1,e)),this.flags.set(h.MatchViewportResolution,new I(h.MatchViewportResolution,"Match viewport resolution","Pixel Streaming will be instructed to dynamically resize the video stream to match the size of the video element.",t&&Object.prototype.hasOwnProperty.call(t,h.MatchViewportResolution)?t[h.MatchViewportResolution]:!1,e)),this.flags.set(h.HoveringMouseMode,new I(h.HoveringMouseMode,"Control Scheme: Locked Mouse","Either locked mouse, where the pointer is consumed by the video and locked to it, or hovering mouse, where the mouse is not consumed.",t&&Object.prototype.hasOwnProperty.call(t,h.HoveringMouseMode)?t[h.HoveringMouseMode]:!1,e,(r,o)=>{o.label=`Control Scheme: ${r?"Hovering":"Locked"} Mouse`})),this.flags.set(h.FakeMouseWithTouches,new I(h.FakeMouseWithTouches,"Fake mouse with touches","A single finger touch is converted into a mouse event. This allows a non-touch application to be controlled partially via a touch device.",t&&Object.prototype.hasOwnProperty.call(t,h.FakeMouseWithTouches)?t[h.FakeMouseWithTouches]:!1,e)),this.flags.set(h.KeyboardInput,new I(h.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",t&&Object.prototype.hasOwnProperty.call(t,h.KeyboardInput)?t[h.KeyboardInput]:!0,e)),this.flags.set(h.MouseInput,new I(h.MouseInput,"Mouse input","If enabled, send mouse events to streamer",t&&Object.prototype.hasOwnProperty.call(t,h.MouseInput)?t[h.MouseInput]:!0,e)),this.flags.set(h.TouchInput,new I(h.TouchInput,"Touch input","If enabled, send touch events to streamer",t&&Object.prototype.hasOwnProperty.call(t,h.TouchInput)?t[h.TouchInput]:!0,e)),this.flags.set(h.GamepadInput,new I(h.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",t&&Object.prototype.hasOwnProperty.call(t,h.GamepadInput)?t[h.GamepadInput]:!0,e)),this.flags.set(h.XRControllerInput,new I(h.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",t&&Object.prototype.hasOwnProperty.call(t,h.XRControllerInput)?t[h.XRControllerInput]:!0,e)),this.flags.set(h.WaitForStreamer,new I(h.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",t&&Object.prototype.hasOwnProperty.call(t,h.WaitForStreamer)?t[h.WaitForStreamer]:!0,e)),this.flags.set(h.HideUI,new I(h.HideUI,"Hide the UI overlay","Will hide all UI overlay details",t&&Object.prototype.hasOwnProperty.call(t,h.HideUI)?t[h.HideUI]:!1,e)),this.flags.set(h.EnableCaptureTimeExt,new I(h.EnableCaptureTimeExt,"Enable abs-capture-time","Enables the abs-capture-time RTP header extension",t&&Object.prototype.hasOwnProperty.call(t,h.EnableCaptureTimeExt)?t[h.EnableCaptureTimeExt]:!1,e)),this.flags.set(h.BrowserSendOffer,new I(h.BrowserSendOffer,"Browser send offer (4.27 ONLY)","Browser will initiate the WebRTC handshake by sending the offer to the streamer (4.27 ONLY)",t&&Object.prototype.hasOwnProperty.call(t,h.BrowserSendOffer)?t[h.BrowserSendOffer]:!1,e)),this.flags.set(h.LatencyCSV,new I(h.LatencyCSV,"Export Latency CSV","Shows a button in the stats panel that allows to run a latency test and export the results to a CSV file.",t&&Object.prototype.hasOwnProperty.call(t,h.LatencyCSV)?t[h.LatencyCSV]:!1,e)),this.numericParameters.set(m.AFKTimeoutSecs,new B(m.AFKTimeoutSecs,"AFK timeout","The time (in seconds) it takes for the application to time out if AFK timeout is enabled.",0,null,t&&Object.prototype.hasOwnProperty.call(t,m.AFKTimeoutSecs)?t[m.AFKTimeoutSecs]:120,e)),this.numericParameters.set(m.AFKCountdownSecs,new B(m.AFKCountdownSecs,"AFK countdown","The time (in seconds) for a user to respond before the stream is ended after an AFK timeout.",10,null,10,e)),this.numericParameters.set(m.MaxReconnectAttempts,new B(m.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,t&&Object.prototype.hasOwnProperty.call(t,m.MaxReconnectAttempts)?t[m.MaxReconnectAttempts]:3,e)),this.numericParameters.set(m.MinQP,new B(m.MinQP,"Min QP","The lower bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,t&&Object.prototype.hasOwnProperty.call(t,m.MinQP)?t[m.MinQP]:0,e)),this.numericParameters.set(m.MaxQP,new B(m.MaxQP,"Max QP","The upper bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,t&&Object.prototype.hasOwnProperty.call(t,m.MaxQP)?t[m.MaxQP]:51,e)),this.numericParameters.set(m.MinQuality,new B(m.MinQuality,"Min Quality","The lower bound for the quality factor of the encoder. 0 = Worst quality, 100 = Best quality.",0,100,t&&Object.prototype.hasOwnProperty.call(t,m.MinQuality)?t[m.MinQuality]:0,e)),this.numericParameters.set(m.MaxQuality,new B(m.MaxQuality,"Max Quality","The upper bound for the quality factor of the encoder. 0 = Worst quality, 100 = Best quality.",0,100,t&&Object.prototype.hasOwnProperty.call(t,m.MaxQuality)?t[m.MaxQuality]:100,e)),this.numericParameters.set(m.CompatQualityMin,new B(m.CompatQualityMin,"Min Quality","The lower bound for encoding quality. 0 = Worst, 100 = Best.",0,100,t&&Object.prototype.hasOwnProperty.call(t,m.CompatQualityMin)?t[m.CompatQualityMin]:0,e)),this.numericParameters.set(m.CompatQualityMax,new B(m.CompatQualityMax,"Max Quality","The upper bound for encoding quality. 0 = Worst, 100 = Best.",0,100,t&&Object.prototype.hasOwnProperty.call(t,m.CompatQualityMax)?t[m.CompatQualityMax]:100,e)),this.numericParameters.set(m.WebRTCFPS,new B(m.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,t&&Object.prototype.hasOwnProperty.call(t,m.WebRTCFPS)?t[m.WebRTCFPS]:60,e)),this.numericParameters.set(m.WebRTCMinBitrate,new B(m.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,t&&Object.prototype.hasOwnProperty.call(t,m.WebRTCMinBitrate)?t[m.WebRTCMinBitrate]:0,e)),this.numericParameters.set(m.WebRTCMaxBitrate,new B(m.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,t&&Object.prototype.hasOwnProperty.call(t,m.WebRTCMaxBitrate)?t[m.WebRTCMaxBitrate]:0,e)),this.numericParameters.set(m.StreamerAutoJoinInterval,new B(m.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,t&&Object.prototype.hasOwnProperty.call(t,m.StreamerAutoJoinInterval)?t[m.StreamerAutoJoinInterval]:3e3,e)),this.numericParameters.set(m.KeepaliveDelay,new B(m.KeepaliveDelay,"Connection Keepalive delay","Delay between keepalive pings to the signalling server.",0,9e5,t&&Object.prototype.hasOwnProperty.call(t,m.KeepaliveDelay)?t[m.KeepaliveDelay]:3e4,e))}_addOnNumericSettingChangedListener(e,t){this.numericParameters.has(e)&&this.numericParameters.get(e).addOnChangedListener(t)}_addOnOptionSettingChangedListener(e,t){this.optionParameters.has(e)&&this.optionParameters.get(e).addOnChangedListener(t)}getNumericSettingValue(e){if(this.numericParameters.has(e))return this.numericParameters.get(e).number;throw new Error(`There is no numeric setting with the id of ${e}`)}getTextSettingValue(e){if(this.textParameters.has(e))return this.textParameters.get(e).value;throw new Error(`There is no numeric setting with the id of ${e}`)}setNumericSetting(e,t){if(this.numericParameters.has(e))this.numericParameters.get(e).number=t;else throw new Error(`There is no numeric setting with the id of ${e}`)}_addOnSettingChangedListener(e,t){this.flags.has(e)&&(this.flags.get(e).onChange=t)}_addOnTextSettingChangedListener(e,t){this.textParameters.has(e)&&(this.textParameters.get(e).onChange=t)}getSettingOption(e){return this.optionParameters.get(e)}isFlagEnabled(e){return this.flags.get(e).flag}setFlagEnabled(e,t){this.flags.has(e)?this.flags.get(e).flag=t:d.Warning(`Cannot toggle flag called ${e} - it does not exist in the Config.flags map.`)}setTextSetting(e,t){this.textParameters.has(e)?this.textParameters.get(e).text=t:d.Warning(`Cannot set text setting called ${e} - it does not exist in the Config.textParameters map.`)}setOptionSettingOptions(e,t){this.optionParameters.has(e)?this.optionParameters.get(e).options=t:d.Warning(`Cannot set text setting called ${e} - it does not exist in the Config.optionParameters map.`)}setOptionSettingValue(e,t){if(!this.optionParameters.has(e))d.Warning(`Cannot set text setting called ${e} - it does not exist in the Config.enumParameters map.`);else{let n=this.optionParameters.get(e),i=n.options;i.includes(t)||(i.push(t),n.options=i),n.selected=t}}setFlagLabel(e,t){this.flags.has(e)?this.flags.get(e).label=t:d.Warning(`Cannot set label for flag called ${e} - it does not exist in the Config.flags map.`)}setSettings(e){for(let t of Object.keys(e))Gr(t)?this.setFlagEnabled(t,e[t]):Xr(t)?this.setNumericSetting(t,e[t]):Jr(t)?this.setTextSetting(t,e[t]):Yr(t)&&this.setOptionSettingValue(t,e[t])}getSettings(){let e={};for(let[t,n]of this.flags.entries())e[t]=n.flag;for(let[t,n]of this.numericParameters.entries())e[t]=n.number;for(let[t,n]of this.textParameters.entries())e[t]=n.text;for(let[t,n]of this.optionParameters.entries())e[t]=n.selected;return e}getFlags(){return Array.from(this.flags.values())}getTextSettings(){return Array.from(this.textParameters.values())}getNumericSettings(){return Array.from(this.numericParameters.values())}getOptionSettings(){return Array.from(this.optionParameters.values())}_registerOnChangeEvents(e){for(let t of this.flags.keys()){let n=this.flags.get(t);n&&(n.onChangeEmit=i=>e.dispatchEvent(new te({id:n.id,type:"flag",value:i,target:n})))}for(let t of this.numericParameters.keys()){let n=this.numericParameters.get(t);n&&(n.onChangeEmit=i=>e.dispatchEvent(new te({id:n.id,type:"number",value:i,target:n})))}for(let t of this.textParameters.keys()){let n=this.textParameters.get(t);n&&(n.onChangeEmit=i=>e.dispatchEvent(new te({id:n.id,type:"text",value:i,target:n})))}for(let t of this.optionParameters.keys()){let n=this.optionParameters.get(t);n&&(n.onChangeEmit=i=>e.dispatchEvent(new te({id:n.id,type:"option",value:i,target:n})))}}},ne;(function(s){s[s.LockedMouse=0]="LockedMouse",s[s.HoveringMouse=1]="HoveringMouse"})(ne||(ne={}));var qt=class{constructor(e,t,n){this.active=!1,this.countdownActive=!1,this.warnTimer=void 0,this.countDown=0,this.countDownTimer=void 0,this.config=e,this.pixelStreaming=t,this.onDismissAfk=n,this.onAFKTimedOutCallback=()=>{console.log("AFK timed out, did you want to override this callback?")}}onAfkClick(){clearInterval(this.countDownTimer),(this.active||this.countdownActive)&&(this.startAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new at))}startAfkWarningTimer(){this.config.getNumericSettingValue(m.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(h.AFKDetection)?this.active=!0:this.active=!1,this.resetAfkWarningTimer()}stopAfkWarningTimer(){this.active=!1,this.countdownActive=!1,clearTimeout(this.warnTimer),clearInterval(this.countDownTimer)}pauseAfkWarningTimer(){this.active=!1}resetAfkWarningTimer(){this.active&&this.config.isFlagEnabled(h.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout(()=>this.activateAfkEvent(),this.config.getNumericSettingValue(m.AFKTimeoutSecs)*1e3))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new ot({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(m.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new we({countDown:this.countDown})),this.config.isFlagEnabled(h.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval(()=>{this.countDown--,this.countDown==0?(this.pixelStreaming.dispatchEvent(new lt),this.onAFKTimedOutCallback(),d.Info("You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new we({countDown:this.countDown}))},1e3)}};var Me=class{constructor(){this.isReceivingFreezeFrame=!1}getDataChannelInstance(){return this}createDataChannel(e,t,n){this.peerConnection=e,this.label=t,this.datachannelOptions=n,n==null&&(this.datachannelOptions={},this.datachannelOptions.ordered=!0),this.dataChannel=this.peerConnection.createDataChannel(this.label,this.datachannelOptions),this.setupDataChannel()}setupDataChannel(){this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=e=>this.handleOnOpen(e),this.dataChannel.onclose=e=>this.handleOnClose(e),this.dataChannel.onmessage=e=>this.handleOnMessage(e),this.dataChannel.onerror=e=>this.handleOnError(e)}handleOnOpen(e){var t;d.Info(`Data Channel (${this.label}) opened.`),this.onOpen((t=this.dataChannel)===null||t===void 0?void 0:t.label,e)}handleOnClose(e){var t;d.Info(`Data Channel (${this.label}) closed.`),this.onClose((t=this.dataChannel)===null||t===void 0?void 0:t.label,e)}handleOnMessage(e){d.Info(`Data Channel (${this.label}) message: ${e}`)}handleOnError(e){var t;d.Info(`Data Channel (${this.label}) error: ${e}`),this.onError((t=this.dataChannel)===null||t===void 0?void 0:t.label,e)}onOpen(e,t){}onClose(e,t){}onError(e,t){}};var Kt=class{},jt=class{};var Qt=class{};var Te=class{};var Ee=class{},Re=class{};var Gt=class{};var Xt=class{};var Jt=class{constructor(){this.inboundVideoStats=new jt,this.inboundAudioStats=new Kt,this.candidatePairs=new Array,this.datachannelStats=new Qt,this.localCandidates=new Array,this.remoteCandidates=new Array,this.outboundVideoStats=new Ee,this.outboundAudioStats=new Ee,this.remoteOutboundAudioStats=new Re,this.remoteOutboundVideoStats=new Re,this.sessionStats=new Gt,this.streamStats=new Xt,this.codecs=new Map}processStats(e){this.localCandidates=new Array,this.remoteCandidates=new Array,this.candidatePairs=new Array,e.forEach(t=>{switch(t.type){case"candidate-pair":this.handleCandidatePair(t);break;case"certificate":break;case"codec":this.handleCodec(t);break;case"data-channel":this.handleDataChannel(t);break;case"inbound-rtp":this.handleInboundRTP(t);break;case"local-candidate":this.handleLocalCandidate(t);break;case"media-source":break;case"media-playout":break;case"outbound-rtp":this.handleLocalOutbound(t);break;case"peer-connection":break;case"remote-candidate":this.handleRemoteCandidate(t);break;case"remote-inbound-rtp":break;case"remote-outbound-rtp":this.handleRemoteOutbound(t);break;case"track":this.handleTrack(t);break;case"transport":this.handleTransport(t);break;case"stream":this.handleStream(t);break;default:d.Error("unhandled Stat Type"),d.Info(t);break}})}handleStream(e){this.streamStats=e}handleCandidatePair(e){this.candidatePairs.push(e)}handleDataChannel(e){this.datachannelStats.bytesReceived=e.bytesReceived,this.datachannelStats.bytesSent=e.bytesSent,this.datachannelStats.dataChannelIdentifier=e.dataChannelIdentifier,this.datachannelStats.id=e.id,this.datachannelStats.label=e.label,this.datachannelStats.messagesReceived=e.messagesReceived,this.datachannelStats.messagesSent=e.messagesSent,this.datachannelStats.protocol=e.protocol,this.datachannelStats.state=e.state,this.datachannelStats.timestamp=e.timestamp}handleLocalCandidate(e){let t=new Te;t.label="local-candidate",t.address=e.address,t.port=e.port,t.protocol=e.protocol,t.candidateType=e.candidateType,t.id=e.id,t.relayProtocol=e.relayProtocol,t.transportId=e.transportId,this.localCandidates.push(t)}handleRemoteCandidate(e){let t=new Te;t.label="remote-candidate",t.address=e.address,t.port=e.port,t.protocol=e.protocol,t.id=e.id,t.candidateType=e.candidateType,t.relayProtocol=e.relayProtocol,t.transportId=e.transportId,this.remoteCandidates.push(t)}handleInboundRTP(e){switch(e.kind){case"video":e.bytesReceived>this.inboundVideoStats.bytesReceived&&e.timestamp>this.inboundVideoStats.timestamp&&(this.inboundVideoStats.bitrate=8*(e.bytesReceived-this.inboundVideoStats.bytesReceived)/(e.timestamp-this.inboundVideoStats.timestamp),this.inboundVideoStats.bitrate=Math.floor(this.inboundVideoStats.bitrate));for(let t in e)this.inboundVideoStats[t]=e[t];break;case"audio":e.bytesReceived>this.inboundAudioStats.bytesReceived&&e.timestamp>this.inboundAudioStats.timestamp&&(this.inboundAudioStats.bitrate=8*(e.bytesReceived-this.inboundAudioStats.bytesReceived)/(e.timestamp-this.inboundAudioStats.timestamp),this.inboundAudioStats.bitrate=Math.floor(this.inboundAudioStats.bitrate));for(let t in e)this.inboundAudioStats[t]=e[t];break;default:d.Error(`Kind should be audio or video, we got ${e.kind} - that's unsupported.`);break}}handleLocalOutbound(e){let t=e.kind==="audio"?this.outboundAudioStats:this.outboundVideoStats;t.active=e.active,t.codecId=e.codecId,t.bytesSent=e.bytesSent,t.frameHeight=e.frameHeight,t.frameWidth=e.frameWidth,t.framesEncoded=e.framesEncoded,t.framesPerSecond=e.framesPerSecond,t.headerBytesSent=e.headerBytesSent,t.id=e.id,t.keyFramesEncoded=e.keyFramesEncoded,t.kind=e.kind,t.mediaSourceId=e.mediaSourceId,t.mid=e.mid,t.nackCount=e.nackCount,t.packetsSent=e.packetsSent,t.qpSum=e.qpSum,t.qualityLimitationDurations=e.qualityLimitationDurations,t.qualityLimitationReason=e.qualityLimitationReason,t.remoteId=e.remoteId,t.retransmittedBytesSent=e.retransmittedBytesSent,t.rid=e.rid,t.scalabilityMode=e.scalabilityMode,t.ssrc=e.ssrc,t.targetBitrate=e.targetBitrate,t.timestamp=e.timestamp,t.totalEncodeTime=e.totalEncodeTime,t.totalEncodeBytesTarget=e.totalEncodeBytesTarget,t.totalPacketSendDelay=e.totalPacketSendDelay,t.transportId=e.transportId}handleRemoteOutbound(e){let t=e.kind==="audio"?this.remoteOutboundAudioStats:this.remoteOutboundVideoStats;t.bytesSent=e.bytesSent,t.codecId=e.codecId,t.id=e.id,t.kind=e.kind,t.localId=e.localId,t.packetsSent=e.packetsSent,t.remoteTimestamp=e.remoteTimestamp,t.reportsSent=e.reportsSent,t.roundTripTimeMeasurements=e.roundTripTimeMeasurements,t.ssrc=e.ssrc,t.timestamp=e.timestamp,t.totalRoundTripTime=e.totalRoundTripTime,t.transportId=e.transportId}handleTrack(e){e.type==="track"&&(e.trackIdentifier==="video_label"||e.kind==="video")&&(this.inboundVideoStats.framesDropped=e.framesDropped,this.inboundVideoStats.framesReceived=e.framesReceived,this.inboundVideoStats.frameHeight=e.frameHeight,this.inboundVideoStats.frameWidth=e.frameWidth)}handleTransport(e){this.transportStats=e}handleCodec(e){let t=e.id;this.codecs.set(t,e)}handleSessionStatistics(e,t,n){let i=Date.now()-e;this.sessionStats.runTime=new Date(i).toISOString().substr(11,8).toString();let r=t===null?"Not sent yet":t?"true":"false";this.sessionStats.controlsStreamInput=r,this.sessionStats.videoEncoderAvgQP=n}isNumber(e){return typeof e=="number"&&isFinite(e)}getActiveCandidatePair(){if(this.candidatePairs===void 0)return null;if(this.transportStats){let t=this.candidatePairs.find(n=>n.id===this.transportStats.selectedCandidatePairId);return t===void 0?null:t}let e=this.candidatePairs.find(t=>t.selected);return e===void 0?null:e}};var en=xr(dr());var Z=class{static isVideoTransceiver(e){return this.canTransceiverReceiveVideo(e)||this.canTransceiverSendVideo(e)}static canTransceiverReceiveVideo(e){return!!e&&(e.direction==="sendrecv"||e.direction==="recvonly")&&e.receiver&&e.receiver.track&&e.receiver.track.kind==="video"}static canTransceiverSendVideo(e){return!!e&&(e.direction==="sendrecv"||e.direction==="sendonly")&&e.sender&&e.sender.track&&e.sender.track.kind==="video"}static isAudioTransceiver(e){return this.canTransceiverReceiveAudio(e)||this.canTransceiverSendAudio(e)}static canTransceiverReceiveAudio(e){return!!e&&(e.direction==="sendrecv"||e.direction==="recvonly")&&e.receiver&&e.receiver.track&&e.receiver.track.kind==="audio"}static canTransceiverSendAudio(e){return!!e&&(e.direction==="sendrecv"||e.direction==="sendonly")&&e.sender&&e.sender.track&&e.sender.track.kind==="audio"}};var ws=class{},Cs=class{},Yt=class{constructor(){this.latestSenderRecvClockOffset=null}calculate(e,t){let n=new Ms,i=this.getRTTMs(e);if(i!=null){n.rttMs=i;let r=this.getCaptureSource(t);if(r!=null){let o=this.calculateSenderLatency(e,r);o!==null&&(n.senderLatencyMs=o)}}return e.inboundVideoStats.totalProcessingDelay!==void 0&&e.inboundVideoStats.framesDecoded!==void 0&&(n.averageProcessingDelayMs=e.inboundVideoStats.totalProcessingDelay/e.inboundVideoStats.framesDecoded*1e3),e.inboundVideoStats.jitterBufferDelay!==void 0&&e.inboundVideoStats.jitterBufferEmittedCount!==void 0&&(n.averageJitterBufferDelayMs=e.inboundVideoStats.jitterBufferDelay/e.inboundVideoStats.jitterBufferEmittedCount*1e3),e.inboundVideoStats.framesDecoded!==void 0&&e.inboundVideoStats.totalDecodeTime!==void 0&&(n.averageDecodeLatencyMs=e.inboundVideoStats.totalDecodeTime/e.inboundVideoStats.framesDecoded*1e3),e.inboundVideoStats.totalAssemblyTime!==void 0&&e.inboundVideoStats.framesAssembledFromMultiplePackets!==void 0&&(n.averageAssemblyDelayMs=e.inboundVideoStats.totalAssemblyTime/e.inboundVideoStats.framesAssembledFromMultiplePackets*1e3),e.inboundVideoStats.googTimingFrameInfo!==void 0&&e.inboundVideoStats.googTimingFrameInfo.length>0&&(n.frameTiming=this.extractFrameTimingInfo(e.inboundVideoStats.googTimingFrameInfo)),n.frameTiming!==void 0&&n.frameTiming.captureToSendLatencyMs!==void 0&&n.averageProcessingDelayMs!==void 0&&n.rttMs!==void 0&&(n.averageE2ELatency=n.frameTiming.captureToSendLatencyMs+n.rttMs*.5+n.averageProcessingDelayMs),n.senderLatencyMs!=null&&n.averageProcessingDelayMs!==void 0&&n.rttMs!==void 0&&(n.averageE2ELatency=n.senderLatencyMs+n.rttMs*.5+n.averageProcessingDelayMs),n}extractFrameTimingInfo(e){let t=new Cs,n=e.split(",");return n.length===15&&(t.rtpTimestamp=Number.parseInt(n[0]),t.captureTimestamp=Number.parseInt(n[1]),t.encodeStartTimestamp=Number.parseInt(n[2]),t.encodeFinishTimestamp=Number.parseInt(n[3]),t.packetizerFinishTimestamp=Number.parseInt(n[4]),t.pacerExitTimestamp=Number.parseInt(n[5]),t.networkTimestamp1=Number.parseInt(n[6]),t.networkTimestamp2=Number.parseInt(n[7]),t.receiveStart=Number.parseInt(n[8]),t.receiveFinish=Number.parseInt(n[9]),t.decodeStart=Number.parseInt(n[10]),t.decodeFinish=Number.parseInt(n[11]),t.renderTime=Number.parseInt(n[12]),t.isOutlier=Number.parseInt(n[13])>0,t.isTriggeredByTimer=Number.parseInt(n[14])>0,t.encoderLatencyMs=t.encodeFinishTimestamp-t.encodeStartTimestamp,t.packetizeLatencyMs=t.packetizerFinishTimestamp-t.encodeFinishTimestamp,t.pacerLatencyMs=t.pacerExitTimestamp-t.packetizerFinishTimestamp,t.captureToSendLatencyMs=t.pacerExitTimestamp-t.captureTimestamp),t}calculateSenderLatency(e,t){let n=t.captureTimestamp+t.senderCaptureTimeOffset,i=this.calculateSenderReceiverClockOffset(e);if(i==null)if(this.latestSenderRecvClockOffset!=null)i=this.latestSenderRecvClockOffset;else return null;else this.latestSenderRecvClockOffset=i;let a=n+i-22089888e5;return t.timestamp-a}getCaptureSource(e){e=e.filter(t=>t.track.kind==="video");for(let t of e){let n=t.getSynchronizationSources().concat(t.getContributingSources());for(let i of n)if(i.captureTimestamp!==void 0&&i.senderCaptureTimeOffset!==void 0&&i.timestamp!==void 0){let r=new ws;return r.timestamp=i.timestamp,r.captureTimestamp=i.captureTimestamp,r.senderCaptureTimeOffset=i.senderCaptureTimeOffset,r}}return null}calculateSenderReceiverClockOffset(e){if(!(e.remoteOutboundVideoStats!==void 0&&e.remoteOutboundVideoStats.timestamp!==void 0&&e.remoteOutboundVideoStats.remoteTimestamp!==void 0))return null;let n=e.remoteOutboundVideoStats.timestamp,i=e.remoteOutboundVideoStats.remoteTimestamp,r=this.getRTTMs(e);if(n!==void 0&&i!==void 0&&r!==null){let o=r*.5;return n-(i+o)}else return null}getRTTMs(e){let t=e.getActiveCandidatePair();return t&&t.currentRoundTripTime!==void 0?t.currentRoundTripTime*1e3:e.remoteOutboundVideoStats&&e.remoteOutboundVideoStats.totalRoundTripTime!==void 0&&e.remoteOutboundVideoStats.roundTripTimeMeasurements!==void 0&&e.remoteOutboundVideoStats.roundTripTimeMeasurements>0?e.remoteOutboundVideoStats.totalRoundTripTime/e.remoteOutboundVideoStats.roundTripTimeMeasurements*1e3:e.remoteOutboundAudioStats&&e.remoteOutboundAudioStats.totalRoundTripTime!==void 0&&e.remoteOutboundAudioStats.roundTripTimeMeasurements!==void 0&&e.remoteOutboundAudioStats.roundTripTimeMeasurements>0?e.remoteOutboundAudioStats.totalRoundTripTime/e.remoteOutboundAudioStats.roundTripTimeMeasurements*1e3:null}},Ms=class{constructor(){this.senderLatencyMs=void 0,this.senderLatencyAbsCaptureTimeMs=void 0,this.rttMs=void 0,this.averageProcessingDelayMs=void 0,this.averageJitterBufferDelayMs=void 0,this.averageDecodeLatencyMs=void 0,this.averageAssemblyDelayMs=void 0,this.averageE2ELatency=void 0,this.frameTiming=void 0}};var ke=function(s,e,t,n){function i(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function a(u){try{c(n.next(u))}catch(w){o(w)}}function l(u){try{c(n.throw(u))}catch(w){o(w)}}function c(u){u.done?r(u.value):i(u.value).then(a,l)}c((n=n.apply(s,e||[])).next())})},Zr="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",Zt=class{constructor(e,t,n){this.config=t,this.createPeerConnection(e,n),this.latencyCalculator=new Yt}createPeerConnection(e,t){this.config.isFlagEnabled(h.ForceTURN)&&(e.iceTransportPolicy="relay",d.Info("Forcing TURN usage by setting ICE Transport Policy in peer connection config.")),this.peerConnection=new RTCPeerConnection(e),this.peerConnection.onsignalingstatechange=n=>this.handleSignalStateChange(n),this.peerConnection.oniceconnectionstatechange=n=>this.handleIceConnectionStateChange(n),this.peerConnection.onicegatheringstatechange=n=>this.handleIceGatheringStateChange(n),this.peerConnection.ontrack=n=>this.handleOnTrack(n),this.peerConnection.onicecandidate=n=>this.handleIceCandidate(n),this.peerConnection.ondatachannel=n=>this.handleDataChannel(n),this.aggregatedStats=new Jt,this.preferredCodec=t,this.updateCodecSelection=!0}createOffer(e,t){return ke(this,void 0,void 0,function*(){d.Info("Create Offer");let n=location.hostname==="localhost"||location.hostname==="127.0.0.1",i=location.protocol==="https:",r=t.isFlagEnabled(h.UseMic),o=t.isFlagEnabled(h.UseCamera);(r||o)&&!(n||i)&&(r=!1,o=!1,d.Error("Microphone and Webcam access in the browser will not work if you are not on HTTPS or localhost. Disabling mic and webcam access."),d.Error("For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(r,o).finally(()=>{var a;(a=this.peerConnection)===null||a===void 0||a.createOffer(e).then(l=>{var c;this.showTextOverlayConnecting(),l.sdp=this.mungeSDP(l.sdp,r),(c=this.peerConnection)===null||c===void 0||c.setLocalDescription(l),this.onSendWebRTCOffer(l)}).catch(()=>{this.showTextOverlaySetupFailure()})})})}receiveOffer(e,t){return ke(this,void 0,void 0,function*(){var n;d.Info("Receive Offer"),this.isFirefox()&&(e.sdp=e.sdp.replace(/^a=extmap:\d+ http:\/\/www\.webrtc\.org\/experiments\/rtp-hdrext\/abs-capture-time\r\n/gm,"")),(n=this.peerConnection)===null||n===void 0||n.setRemoteDescription(e).then(()=>{this.onSetRemoteDescription(e);let i=location.hostname==="localhost"||location.hostname==="127.0.0.1",r=location.protocol==="https:",o=t.isFlagEnabled(h.UseMic),a=t.isFlagEnabled(h.UseCamera);(o||a)&&!(i||r)&&(o=!1,a=!1,d.Error("Microphone and Webcam access in the browser will not work if you are not on HTTPS or localhost. Disabling mic and webcam access."),d.Error("For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.config.setOptionSettingOptions(M.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e)),this.setupTransceiversAsync(o,a).finally(()=>{var l;(l=this.peerConnection)===null||l===void 0||l.createAnswer().then(c=>{var u;return c.sdp=this.mungeSDP(c.sdp,o),(u=this.peerConnection)===null||u===void 0?void 0:u.setLocalDescription(c)}).then(()=>{var c;this.onSetLocalDescription((c=this.peerConnection)===null||c===void 0?void 0:c.localDescription)}).catch(c=>{d.Error(`createAnswer() failed - ${c}`)})})})})}receiveAnswer(e){var t;(t=this.peerConnection)===null||t===void 0||t.setRemoteDescription(e),this.config.setOptionSettingOptions(M.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e))}generateStats(){this.peerConnection.getStats().then(e=>{this.aggregatedStats.processStats(e),this.onVideoStats(this.aggregatedStats);let t=this.latencyCalculator.calculate(this.aggregatedStats,this.peerConnection.getReceivers());if(this.onLatencyCalculated(t),this.updateCodecSelection&&this.aggregatedStats.inboundVideoStats.codecId){let n=this.aggregatedStats.codecs.get(this.aggregatedStats.inboundVideoStats.codecId);if(n===void 0)return;let i=n.mimeType.replace("video/",""),r=i;n.sdpFmtpLine&&n.sdpFmtpLine.trim()!==""&&(r=`${i} ${n.sdpFmtpLine.trim()}`);let o=this.config.getSettingOption(M.PreferredCodec).options;if(o.includes(r)){this.config.setOptionSettingValue(M.PreferredCodec,r);return}let a=o.filter(l=>l.indexOf(i)!==-1);if(a.length>0){this.config.setOptionSettingValue(M.PreferredCodec,a[0]);return}}})}close(){this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null)}mungeSDP(e,t){let n=e.replace(/(a=fmtp:\d+ .*level-asymmetry-allowed=.*)\r\n/gm,`$1;x-google-start-bitrate=10000;x-google-max-bitrate=100000\r
|
|
42
|
-
`),i="maxaveragebitrate=510000;";return t&&(i+="sprop-maxcapturerate=48000;"),i+=this.config.isFlagEnabled(h.ForceMonoAudio)?"stereo=0;":"stereo=1;",i+="useinbandfec=1",n=n.replace("useinbandfec=1",i),this.config.isFlagEnabled(h.EnableCaptureTimeExt)&&!this.isFirefox()&&(n=tt.addVideoHeaderExtensionToSdp(n,
|
|
41
|
+
`);return o.shift()+o.map(l=>l.startsWith("m=video")?l+r:l).join("")}};var nt=class{constructor(e){this.videoElementProvider=e,this.audioElement=document.createElement("Audio"),this.videoElementProvider.setAudioElement(this.audioElement)}handleOnTrack(e){if(d.Info("handleOnTrack "+JSON.stringify(e.streams)),e.streams.length<1||e.streams[0].id=="probator")return;let t=this.videoElementProvider.getVideoElement();if(e.track&&d.Info("Got track - "+e.track.kind+" id="+e.track.id+" readyState="+e.track.readyState),e.track.kind=="audio"){this.CreateAudioTrack(e.streams[0]);return}else if(e.track.kind=="video"&&t.srcObject!==e.streams[0]){t.srcObject=e.streams[0],d.Info("Set video source from video track ontrack.");return}}CreateAudioTrack(e){let t=this.videoElementProvider.getVideoElement();t.srcObject!=e&&t.srcObject&&t.srcObject!==e&&(this.audioElement.srcObject=e,d.Info("Created new audio element to play separate audio stream."))}};var it=class{constructor(e){this.freezeFrameHeight=0,this.freezeFrameWidth=0,this.rootDiv=e,this.rootElement=document.createElement("div"),this.rootElement.id="freezeFrame",this.rootElement.style.display="none",this.rootElement.style.pointerEvents="none",this.rootElement.style.position="absolute",this.rootElement.style.zIndex="20",this.imageElement=document.createElement("img"),this.imageElement.style.position="absolute",this.rootElement.appendChild(this.imageElement),this.rootDiv.appendChild(this.rootElement)}setElementForShow(){this.rootElement.style.display="block"}setElementForHide(){this.rootElement.style.display="none"}updateImageElementSource(e){let t=btoa(e.reduce((n,i)=>n+String.fromCharCode(i),""));this.imageElement.src="data:image/jpeg;base64,"+t}setDimensionsFromElementAndResize(){this.freezeFrameHeight=this.imageElement.naturalHeight,this.freezeFrameWidth=this.imageElement.naturalWidth,this.resize()}resize(){if(this.freezeFrameWidth!==0&&this.freezeFrameHeight!==0){let e=0,t=0,n=0,i=0,r=this.rootDiv.clientWidth/this.rootDiv.clientHeight,o=this.freezeFrameWidth/this.freezeFrameHeight;r<o?(e=this.rootDiv.clientWidth,t=Math.floor(this.rootDiv.clientWidth/o),n=Math.floor((this.rootDiv.clientHeight-t)*.5),i=0):(e=Math.floor(this.rootDiv.clientHeight*o),t=this.rootDiv.clientHeight,n=0,i=Math.floor((this.rootDiv.clientWidth-e)*.5)),this.rootElement.style.width=this.rootDiv.offsetWidth+"px",this.rootElement.style.height=this.rootDiv.offsetHeight+"px",this.rootElement.style.left="0px",this.rootElement.style.top="0px",this.imageElement.style.width=e+"px",this.imageElement.style.height=t+"px",this.imageElement.style.left=i+"px",this.imageElement.style.top=n+"px"}}};var st=class{constructor(e){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new it(e)}showFreezeFrame(){this.valid&&this.freezeFrame.setElementForShow()}hideFreezeFrame(){this.valid=!1,this.freezeFrame.setElementForHide()}updateFreezeFrameAndShow(e,t){this.freezeFrame.updateImageElementSource(e),this.freezeFrame.imageElement.onload=()=>{this.freezeFrame.setDimensionsFromElementAndResize(),t()}}processFreezeFrameMessage(e,t){this.receiving||(this.receiving=!0,this.valid=!1,this.size=0,this.jpeg=void 0),this.size=new DataView(e.slice(1,5).buffer).getInt32(0,!0);let n=e.slice(5);if(this.jpeg){let i=new Uint8Array(this.jpeg.length+n.length);i.set(this.jpeg,0),i.set(n,this.jpeg.length),this.jpeg=i}else this.jpeg=n,this.receiving=!0,d.Info(`received first chunk of freeze frame: ${this.jpeg.length}/${this.size}`);this.jpeg.length===this.size?(this.receiving=!1,this.valid=!0,d.Info(`received complete freeze frame ${this.size}`),this.updateFreezeFrameAndShow(this.jpeg,t)):this.jpeg.length>this.size&&(d.Error(`received bigger freeze frame than advertised: ${this.jpeg.length}/${this.size}`),this.jpeg=void 0,this.receiving=!1)}};var j=class{constructor(e,t,n,i,r=()=>{}){this.parseURLParams(),this.onChange=r,this.onChangeEmit=()=>{},this.id=e,this.description=n,this.label=t,this.value=i}set label(e){this._label=e,this.onChangeEmit(this._value)}get label(){return this._label}get value(){return this._value}set value(e){this._value=e,this.onChange(this._value,this),this.onChangeEmit(this._value)}updateURLParams(){if(this.useUrlParams){let e=new URLSearchParams(window.location.search),t=this.getValueAsString(),n=!1;for(let[i,r]of e)if(i.toLowerCase()==this.id.toLowerCase()){e.set(i,t),n=!0;break}n||e.set(this.id,t),window.history.replaceState({},"",e.toString()!==""?`${location.pathname}?${e}`:`${location.pathname}`)}}getValueAsString(){return""}parseURLParams(){this._urlParams={};let e=new URLSearchParams(window.location.search);for(let[t,n]of e)this._urlParams[t.toLowerCase()]=n}hasURLParam(e){return e.toLowerCase()in this._urlParams}getURLParam(e){return this.hasURLParam(e)?this._urlParams[e.toLowerCase()]:""}};var I=class extends j{constructor(e,t,n,i,r,o=()=>{}){if(super(e,t,n,i,o),!r||!this.hasURLParam(this.id))this.flag=i;else{let a=this.getURLParam(this.id);this.flag=a.toLowerCase()!="false"}this.useUrlParams=r}getValueAsString(){return this.flag?"true":"false"}enable(){this.flag=!0}get flag(){return!!this.value}set flag(e){this.value=e}};var B=class extends j{constructor(e,t,n,i,r,o,a,l=()=>{}){if(super(e,t,n,o,l),this._min=i,this._max=r,!a||!this.hasURLParam(this.id))this.number=o;else{let c=Number.parseFloat(this.getURLParam(this.id));this.number=Number.isNaN(c)?o:c}this.useUrlParams=a}getValueAsString(){return this.number.toString()}set number(e){this.value=this.clamp(e)}get number(){return this.value}clamp(e){return this._min==null&&this._max==null?e:this._min==null?Math.min(this._max,e):this._max==null?Math.max(this._min,e):Math.max(Math.min(this._max,e),this._min)}get min(){return this._min}get max(){return this._max}addOnChangedListener(e){this.onChange=e}};var rt=class extends j{constructor(e,t,n,i,r,o=()=>{}){super(e,t,n,i,o),!r||!this.hasURLParam(this.id)?this.text=i:this.text=this.getURLParam(this.id),this.useUrlParams=r}getValueAsString(){return this.text}get text(){return this.value}set text(e){this.value=e}};var le=class extends j{constructor(e,t,n,i,r,o,a=function(c){return c},l=()=>{}){super(e,t,n,i,l),this._urlParamResolver=a;let c=this.hasURLParam(this.id)?this._urlParamResolver(this.getURLParam(this.id)):i;this.options=r??[c],this.selected=c,this.useUrlParams=o}getValueAsString(){return this.selected}addOnChangedListener(e){this.onChange=e}get options(){return this._options}set options(e){this._options=e,this.onChangeEmit(this.selected)}get selected(){return this.value}set selected(e){e!==void 0&&(this.options.includes(e)?this.value=e:d.Error(`Could not set "${e}" as the selected option for ${this.id} because it wasn't one of the options.`))}set urlParamResolver(e){this._urlParamResolver=e}};var ot=class extends Event{constructor(e){super("afkWarningActivate"),this.data=e}},we=class extends Event{constructor(e){super("afkWarningUpdate"),this.data=e}},at=class extends Event{constructor(){super("afkWarningDeactivate")}},lt=class extends Event{constructor(){super("afkTimedOut")}},ct=class extends Event{constructor(e){super("videoEncoderAvgQP"),this.data=e}},dt=class extends Event{constructor(){super("webRtcSdp")}},ht=class extends Event{constructor(e){super("webRtcSdpAnswer"),this.data=e}},ut=class extends Event{constructor(e){super("webRtcSdpOffer"),this.data=e}},pt=class extends Event{constructor(){super("webRtcAutoConnect")}},mt=class extends Event{constructor(){super("webRtcConnecting")}},ft=class extends Event{constructor(){super("webRtcConnected")}},gt=class extends Event{constructor(){super("webRtcFailed")}},yt=class extends Event{constructor(e){super("webRtcDisconnected"),this.data=e}},St=class extends Event{constructor(e){super("dataChannelOpen"),this.data=e}},bt=class extends Event{constructor(e){super("dataChannelClose"),this.data=e}},vt=class extends Event{constructor(e){super("dataChannelError"),this.data=e}},wt=class extends Event{constructor(){super("videoInitialized")}},Ct=class extends Event{constructor(){super("streamLoading")}},Mt=class extends Event{constructor(){super("streamConnect")}},Tt=class extends Event{constructor(){super("streamDisconnect")}},Et=class extends Event{constructor(){super("streamReconnect")}},Rt=class extends Event{constructor(e){super("playStreamError"),this.data=e}},kt=class extends Event{constructor(){super("playStream")}},Ce=class extends Event{constructor(e){super("playStreamRejected"),this.data=e}},xt=class extends Event{constructor(e){super("loadFreezeFrame"),this.data=e}},It=class extends Event{constructor(){super("hideFreezeFrame")}},Pt=class extends Event{constructor(e){super("statsReceived"),this.data=e}},Lt=class extends Event{constructor(e){super("streamerListMessage"),this.data=e}},Dt=class extends Event{constructor(e){super("StreamerIDChangedMessage"),this.data=e}},Ot=class extends Event{constructor(e){super("latencyTestResult"),this.data=e}},Ft=class extends Event{constructor(e){super("latencyCalculated"),this.data=e}},At=class extends Event{constructor(e){super("showOnScreenKeyboard"),this.data=e}},Nt=class extends Event{constructor(e){super("dataChannelLatencyTestResponse"),this.data=e}},Ut=class extends Event{constructor(e){super("dataChannelLatencyTestResult"),this.data=e}},Bt=class extends Event{constructor(e){super("subscribeFailed"),this.data=e}},Vt=class extends Event{constructor(e){super("initialSettings"),this.data=e}},te=class extends Event{constructor(e){super("settingsChanged"),this.data=e}};var _t=class extends Event{constructor(e){super("xrFrame"),this.data=e}},Wt=class extends Event{constructor(e){super("playerCount"),this.data=e}},Ht=class extends Event{constructor(){super("webRtcTCPRelayDetected")}},$t=class extends EventTarget{dispatchEvent(e){return super.dispatchEvent(e)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}};var Y=class{static getSupportedVideoCodecs(){let e=[];if(!RTCRtpReceiver.getCapabilities)return d.Warning("RTCRtpReceiver.getCapabilities API is not available in your browser, defaulting to guess that we support H.264."),e.push("H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"),e;let t=/(VP\d|H26\d|AV1).*/,n=RTCRtpReceiver.getCapabilities("video");return n?(n.codecs.forEach(i=>{let r=i.mimeType.split("/")[1]+" "+(i.sdpFmtpLine||"");t.exec(r)!==null&&e.push(r)}),e):(e.push("H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"),e)}};var h=class{};h.AutoConnect="AutoConnect";h.AutoPlayVideo="AutoPlayVideo";h.AFKDetection="TimeoutIfIdle";h.HoveringMouseMode="HoveringMouse";h.ForceMonoAudio="ForceMonoAudio";h.ForceTURN="ForceTURN";h.FakeMouseWithTouches="FakeMouseWithTouches";h.IsQualityController="ControlsQuality";h.MatchViewportResolution="MatchViewportRes";h.StartVideoMuted="StartVideoMuted";h.SuppressBrowserKeys="SuppressBrowserKeys";h.UseMic="UseMic";h.UseModalForTextInput="UseModalForTextInput";h.UseCamera="UseCamera";h.KeyboardInput="KeyboardInput";h.MouseInput="MouseInput";h.TouchInput="TouchInput";h.GamepadInput="GamepadInput";h.XRControllerInput="XRControllerInput";h.WaitForStreamer="WaitForStreamer";h.HideUI="HideUI";h.EnableCaptureTimeExt="EnableCaptureTimeExt";h.BrowserSendOffer="BrowserSendOffer";h.LatencyCSV="LatencyCSV";var Jr=s=>Object.getOwnPropertyNames(h).some(e=>h[e]===s),m=class{};m.AFKTimeoutSecs="AFKTimeout";m.AFKCountdownSecs="AFKCountdown";m.MinQP="MinQP";m.MaxQP="MaxQP";m.MinQuality="MinQuality";m.MaxQuality="MaxQuality";m.CompatQualityMin="CompatQualityMin";m.CompatQualityMax="CompatQualityMax";m.WebRTCFPS="WebRTCFPS";m.WebRTCMinBitrate="WebRTCMinBitrate";m.WebRTCMaxBitrate="WebRTCMaxBitrate";m.MaxReconnectAttempts="MaxReconnectAttempts";m.StreamerAutoJoinInterval="StreamerAutoJoinInterval";m.KeepaliveDelay="KeepaliveDelay";var Xr=s=>Object.getOwnPropertyNames(m).some(e=>m[e]===s),$=class{};$.SignallingServerUrl="ss";var Yr=s=>Object.getOwnPropertyNames($).some(e=>$[e]===s),M=class{};M.PreferredCodec="PreferredCodec";M.StreamerId="StreamerId";M.PreferredQuality="PreferredQuality";var Zr=s=>Object.getOwnPropertyNames(M).some(e=>M[e]===s),zt=class{constructor(e={}){this.flags=new Map,this.numericParameters=new Map,this.textParameters=new Map,this.optionParameters=new Map;let{initialSettings:t,useUrlParams:n,webSocketProtocols:i}=e;this._useUrlParams=!!n,this._webSocketProtocols=i,this.populateDefaultSettings(this._useUrlParams,t)}get useUrlParams(){return this._useUrlParams}get webSocketProtocols(){return this._webSocketProtocols}populateDefaultSettings(e,t){this.textParameters.set($.SignallingServerUrl,new rt($.SignallingServerUrl,"Signalling url","Url of the signalling server",t&&Object.prototype.hasOwnProperty.call(t,$.SignallingServerUrl)?t[$.SignallingServerUrl]:(location.protocol==="https:"?"wss://":"ws://")+window.location.hostname+(window.location.port==="80"||window.location.port===""?"":`:${window.location.port}`),e)),this.optionParameters.set(M.StreamerId,new le(M.StreamerId,"Streamer ID","The ID of the streamer to stream.",t&&Object.prototype.hasOwnProperty.call(t,M.StreamerId)?t[M.StreamerId]:"",t&&Object.prototype.hasOwnProperty.call(t,M.StreamerId)?[t[M.StreamerId]]:void 0,e));let n=function(){let r=Y.getSupportedVideoCodecs();if(r.length==1)return r[0];if(r.length>0){let o=r[0];for(let a of r)if(a.startsWith("H264"))return a;return o}return d.Error("Could not find any reasonable video codec to assign as a default."),""},i=function(r){let o=Y.getSupportedVideoCodecs();if(o.includes(r))return r;for(let a of o)if(a.startsWith(r))return a;return r};this.optionParameters.set(M.PreferredCodec,new le(M.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation",t&&Object.prototype.hasOwnProperty.call(t,M.PreferredCodec)?i(t[M.PreferredCodec]):n(),Y.getSupportedVideoCodecs(),e,i)),this.optionParameters.set(M.PreferredQuality,new le(M.PreferredQuality,"Preferred Quality","The preferred quality of the stream (only applicable when using the SFU)",t&&Object.prototype.hasOwnProperty.call(t,M.PreferredQuality)?t[M.PreferredQuality]:"Default",["Default"],e)),this.flags.set(h.AutoConnect,new I(h.AutoConnect,"Auto connect to stream","Whether we should attempt to auto connect to the signalling server or show a click to start prompt.",t&&Object.prototype.hasOwnProperty.call(t,h.AutoConnect)?t[h.AutoConnect]:!1,e)),this.flags.set(h.AutoPlayVideo,new I(h.AutoPlayVideo,"Auto play video","When video is ready automatically start playing it as opposed to showing a play button.",t&&Object.prototype.hasOwnProperty.call(t,h.AutoPlayVideo)?t[h.AutoPlayVideo]:!0,e)),this.flags.set(h.UseMic,new I(h.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",t&&Object.prototype.hasOwnProperty.call(t,h.UseMic)?t[h.UseMic]:!1,e)),this.flags.set(h.UseModalForTextInput,new I(h.UseModalForTextInput,"Use modal for text input","When entering input into a streamed UE text widget, use an input modal.",t&&Object.prototype.hasOwnProperty.call(t,h.UseModalForTextInput)?t[h.UseModalForTextInput]:!0,e)),this.flags.set(h.UseCamera,new I(h.UseCamera,"Use webcam","Make browser request webcam access and open a input video track.",t&&Object.prototype.hasOwnProperty.call(t,h.UseCamera)?t[h.UseCamera]:!1,e)),this.flags.set(h.StartVideoMuted,new I(h.StartVideoMuted,"Start video muted","Video will start muted if true.",t&&Object.prototype.hasOwnProperty.call(t,h.StartVideoMuted)?t[h.StartVideoMuted]:!1,e)),this.flags.set(h.SuppressBrowserKeys,new I(h.SuppressBrowserKeys,"Suppress browser keys","Suppress certain browser keys that we use in UE, for example F5 to show shader complexity instead of refresh the page.",t&&Object.prototype.hasOwnProperty.call(t,h.SuppressBrowserKeys)?t[h.SuppressBrowserKeys]:!0,e)),this.flags.set(h.IsQualityController,new I(h.IsQualityController,"Is quality controller?","True if this peer controls stream quality",t&&Object.prototype.hasOwnProperty.call(t,h.IsQualityController)?t[h.IsQualityController]:!0,e)),this.flags.set(h.ForceMonoAudio,new I(h.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",t&&Object.prototype.hasOwnProperty.call(t,h.ForceMonoAudio)?t[h.ForceMonoAudio]:!1,e)),this.flags.set(h.ForceTURN,new I(h.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",t&&Object.prototype.hasOwnProperty.call(t,h.ForceTURN)?t[h.ForceTURN]:!1,e)),this.flags.set(h.AFKDetection,new I(h.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",t&&Object.prototype.hasOwnProperty.call(t,h.AFKDetection)?t[h.AFKDetection]:!1,e)),this.flags.set(h.MatchViewportResolution,new I(h.MatchViewportResolution,"Match viewport resolution","Pixel Streaming will be instructed to dynamically resize the video stream to match the size of the video element.",t&&Object.prototype.hasOwnProperty.call(t,h.MatchViewportResolution)?t[h.MatchViewportResolution]:!1,e)),this.flags.set(h.HoveringMouseMode,new I(h.HoveringMouseMode,"Control Scheme: Locked Mouse","Either locked mouse, where the pointer is consumed by the video and locked to it, or hovering mouse, where the mouse is not consumed.",t&&Object.prototype.hasOwnProperty.call(t,h.HoveringMouseMode)?t[h.HoveringMouseMode]:!1,e,(r,o)=>{o.label=`Control Scheme: ${r?"Hovering":"Locked"} Mouse`})),this.flags.set(h.FakeMouseWithTouches,new I(h.FakeMouseWithTouches,"Fake mouse with touches","A single finger touch is converted into a mouse event. This allows a non-touch application to be controlled partially via a touch device.",t&&Object.prototype.hasOwnProperty.call(t,h.FakeMouseWithTouches)?t[h.FakeMouseWithTouches]:!1,e)),this.flags.set(h.KeyboardInput,new I(h.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",t&&Object.prototype.hasOwnProperty.call(t,h.KeyboardInput)?t[h.KeyboardInput]:!0,e)),this.flags.set(h.MouseInput,new I(h.MouseInput,"Mouse input","If enabled, send mouse events to streamer",t&&Object.prototype.hasOwnProperty.call(t,h.MouseInput)?t[h.MouseInput]:!0,e)),this.flags.set(h.TouchInput,new I(h.TouchInput,"Touch input","If enabled, send touch events to streamer",t&&Object.prototype.hasOwnProperty.call(t,h.TouchInput)?t[h.TouchInput]:!0,e)),this.flags.set(h.GamepadInput,new I(h.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",t&&Object.prototype.hasOwnProperty.call(t,h.GamepadInput)?t[h.GamepadInput]:!0,e)),this.flags.set(h.XRControllerInput,new I(h.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",t&&Object.prototype.hasOwnProperty.call(t,h.XRControllerInput)?t[h.XRControllerInput]:!0,e)),this.flags.set(h.WaitForStreamer,new I(h.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",t&&Object.prototype.hasOwnProperty.call(t,h.WaitForStreamer)?t[h.WaitForStreamer]:!0,e)),this.flags.set(h.HideUI,new I(h.HideUI,"Hide the UI overlay","Will hide all UI overlay details",t&&Object.prototype.hasOwnProperty.call(t,h.HideUI)?t[h.HideUI]:!1,e)),this.flags.set(h.EnableCaptureTimeExt,new I(h.EnableCaptureTimeExt,"Enable abs-capture-time","Enables the abs-capture-time RTP header extension",t&&Object.prototype.hasOwnProperty.call(t,h.EnableCaptureTimeExt)?t[h.EnableCaptureTimeExt]:!1,e)),this.flags.set(h.BrowserSendOffer,new I(h.BrowserSendOffer,"Browser send offer (4.27 ONLY)","Browser will initiate the WebRTC handshake by sending the offer to the streamer (4.27 ONLY)",t&&Object.prototype.hasOwnProperty.call(t,h.BrowserSendOffer)?t[h.BrowserSendOffer]:!1,e)),this.flags.set(h.LatencyCSV,new I(h.LatencyCSV,"Export Latency CSV","Shows a button in the stats panel that allows to run a latency test and export the results to a CSV file.",t&&Object.prototype.hasOwnProperty.call(t,h.LatencyCSV)?t[h.LatencyCSV]:!1,e)),this.numericParameters.set(m.AFKTimeoutSecs,new B(m.AFKTimeoutSecs,"AFK timeout","The time (in seconds) it takes for the application to time out if AFK timeout is enabled.",0,null,t&&Object.prototype.hasOwnProperty.call(t,m.AFKTimeoutSecs)?t[m.AFKTimeoutSecs]:120,e)),this.numericParameters.set(m.AFKCountdownSecs,new B(m.AFKCountdownSecs,"AFK countdown","The time (in seconds) for a user to respond before the stream is ended after an AFK timeout.",10,null,10,e)),this.numericParameters.set(m.MaxReconnectAttempts,new B(m.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,t&&Object.prototype.hasOwnProperty.call(t,m.MaxReconnectAttempts)?t[m.MaxReconnectAttempts]:3,e)),this.numericParameters.set(m.MinQP,new B(m.MinQP,"Min QP","The lower bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,t&&Object.prototype.hasOwnProperty.call(t,m.MinQP)?t[m.MinQP]:0,e)),this.numericParameters.set(m.MaxQP,new B(m.MaxQP,"Max QP","The upper bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,t&&Object.prototype.hasOwnProperty.call(t,m.MaxQP)?t[m.MaxQP]:51,e)),this.numericParameters.set(m.MinQuality,new B(m.MinQuality,"Min Quality","The lower bound for the quality factor of the encoder. 0 = Worst quality, 100 = Best quality.",0,100,t&&Object.prototype.hasOwnProperty.call(t,m.MinQuality)?t[m.MinQuality]:0,e)),this.numericParameters.set(m.MaxQuality,new B(m.MaxQuality,"Max Quality","The upper bound for the quality factor of the encoder. 0 = Worst quality, 100 = Best quality.",0,100,t&&Object.prototype.hasOwnProperty.call(t,m.MaxQuality)?t[m.MaxQuality]:100,e)),this.numericParameters.set(m.CompatQualityMin,new B(m.CompatQualityMin,"Min Quality","The lower bound for encoding quality. 0 = Worst, 100 = Best.",0,100,t&&Object.prototype.hasOwnProperty.call(t,m.CompatQualityMin)?t[m.CompatQualityMin]:0,e)),this.numericParameters.set(m.CompatQualityMax,new B(m.CompatQualityMax,"Max Quality","The upper bound for encoding quality. 0 = Worst, 100 = Best.",0,100,t&&Object.prototype.hasOwnProperty.call(t,m.CompatQualityMax)?t[m.CompatQualityMax]:100,e)),this.numericParameters.set(m.WebRTCFPS,new B(m.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,t&&Object.prototype.hasOwnProperty.call(t,m.WebRTCFPS)?t[m.WebRTCFPS]:60,e)),this.numericParameters.set(m.WebRTCMinBitrate,new B(m.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,t&&Object.prototype.hasOwnProperty.call(t,m.WebRTCMinBitrate)?t[m.WebRTCMinBitrate]:0,e)),this.numericParameters.set(m.WebRTCMaxBitrate,new B(m.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,t&&Object.prototype.hasOwnProperty.call(t,m.WebRTCMaxBitrate)?t[m.WebRTCMaxBitrate]:0,e)),this.numericParameters.set(m.StreamerAutoJoinInterval,new B(m.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,t&&Object.prototype.hasOwnProperty.call(t,m.StreamerAutoJoinInterval)?t[m.StreamerAutoJoinInterval]:3e3,e)),this.numericParameters.set(m.KeepaliveDelay,new B(m.KeepaliveDelay,"Connection Keepalive delay","Delay between keepalive pings to the signalling server.",0,9e5,t&&Object.prototype.hasOwnProperty.call(t,m.KeepaliveDelay)?t[m.KeepaliveDelay]:3e4,e))}_addOnNumericSettingChangedListener(e,t){this.numericParameters.has(e)&&this.numericParameters.get(e).addOnChangedListener(t)}_addOnOptionSettingChangedListener(e,t){this.optionParameters.has(e)&&this.optionParameters.get(e).addOnChangedListener(t)}getNumericSettingValue(e){if(this.numericParameters.has(e))return this.numericParameters.get(e).number;throw new Error(`There is no numeric setting with the id of ${e}`)}getTextSettingValue(e){if(this.textParameters.has(e))return this.textParameters.get(e).value;throw new Error(`There is no numeric setting with the id of ${e}`)}setNumericSetting(e,t){if(this.numericParameters.has(e))this.numericParameters.get(e).number=t;else throw new Error(`There is no numeric setting with the id of ${e}`)}_addOnSettingChangedListener(e,t){this.flags.has(e)&&(this.flags.get(e).onChange=t)}_addOnTextSettingChangedListener(e,t){this.textParameters.has(e)&&(this.textParameters.get(e).onChange=t)}getSettingOption(e){return this.optionParameters.get(e)}isFlagEnabled(e){return this.flags.get(e).flag}setFlagEnabled(e,t){this.flags.has(e)?this.flags.get(e).flag=t:d.Warning(`Cannot toggle flag called ${e} - it does not exist in the Config.flags map.`)}setTextSetting(e,t){this.textParameters.has(e)?this.textParameters.get(e).text=t:d.Warning(`Cannot set text setting called ${e} - it does not exist in the Config.textParameters map.`)}setOptionSettingOptions(e,t){this.optionParameters.has(e)?this.optionParameters.get(e).options=t:d.Warning(`Cannot set text setting called ${e} - it does not exist in the Config.optionParameters map.`)}setOptionSettingValue(e,t){if(!this.optionParameters.has(e))d.Warning(`Cannot set text setting called ${e} - it does not exist in the Config.enumParameters map.`);else{let n=this.optionParameters.get(e),i=n.options;i.includes(t)||(i.push(t),n.options=i),n.selected=t}}setFlagLabel(e,t){this.flags.has(e)?this.flags.get(e).label=t:d.Warning(`Cannot set label for flag called ${e} - it does not exist in the Config.flags map.`)}setSettings(e){for(let t of Object.keys(e))Jr(t)?this.setFlagEnabled(t,e[t]):Xr(t)?this.setNumericSetting(t,e[t]):Yr(t)?this.setTextSetting(t,e[t]):Zr(t)&&this.setOptionSettingValue(t,e[t])}getSettings(){let e={};for(let[t,n]of this.flags.entries())e[t]=n.flag;for(let[t,n]of this.numericParameters.entries())e[t]=n.number;for(let[t,n]of this.textParameters.entries())e[t]=n.text;for(let[t,n]of this.optionParameters.entries())e[t]=n.selected;return e}getFlags(){return Array.from(this.flags.values())}getTextSettings(){return Array.from(this.textParameters.values())}getNumericSettings(){return Array.from(this.numericParameters.values())}getOptionSettings(){return Array.from(this.optionParameters.values())}_registerOnChangeEvents(e){for(let t of this.flags.keys()){let n=this.flags.get(t);n&&(n.onChangeEmit=i=>e.dispatchEvent(new te({id:n.id,type:"flag",value:i,target:n})))}for(let t of this.numericParameters.keys()){let n=this.numericParameters.get(t);n&&(n.onChangeEmit=i=>e.dispatchEvent(new te({id:n.id,type:"number",value:i,target:n})))}for(let t of this.textParameters.keys()){let n=this.textParameters.get(t);n&&(n.onChangeEmit=i=>e.dispatchEvent(new te({id:n.id,type:"text",value:i,target:n})))}for(let t of this.optionParameters.keys()){let n=this.optionParameters.get(t);n&&(n.onChangeEmit=i=>e.dispatchEvent(new te({id:n.id,type:"option",value:i,target:n})))}}},ne;(function(s){s[s.LockedMouse=0]="LockedMouse",s[s.HoveringMouse=1]="HoveringMouse"})(ne||(ne={}));var qt=class{constructor(e,t,n){this.active=!1,this.countdownActive=!1,this.warnTimer=void 0,this.countDown=0,this.countDownTimer=void 0,this.config=e,this.pixelStreaming=t,this.onDismissAfk=n,this.onAFKTimedOutCallback=()=>{console.log("AFK timed out, did you want to override this callback?")}}onAfkClick(){clearInterval(this.countDownTimer),(this.active||this.countdownActive)&&(this.startAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new at))}startAfkWarningTimer(){this.config.getNumericSettingValue(m.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(h.AFKDetection)?this.active=!0:this.active=!1,this.resetAfkWarningTimer()}stopAfkWarningTimer(){this.active=!1,this.countdownActive=!1,clearTimeout(this.warnTimer),clearInterval(this.countDownTimer)}pauseAfkWarningTimer(){this.active=!1}resetAfkWarningTimer(){this.active&&this.config.isFlagEnabled(h.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout(()=>this.activateAfkEvent(),this.config.getNumericSettingValue(m.AFKTimeoutSecs)*1e3))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new ot({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(m.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new we({countDown:this.countDown})),this.config.isFlagEnabled(h.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval(()=>{this.countDown--,this.countDown==0?(this.pixelStreaming.dispatchEvent(new lt),this.onAFKTimedOutCallback(),d.Info("You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new we({countDown:this.countDown}))},1e3)}};var Me=class{constructor(){this.isReceivingFreezeFrame=!1}getDataChannelInstance(){return this}createDataChannel(e,t,n){this.peerConnection=e,this.label=t,this.datachannelOptions=n,n==null&&(this.datachannelOptions={},this.datachannelOptions.ordered=!0),this.dataChannel=this.peerConnection.createDataChannel(this.label,this.datachannelOptions),this.setupDataChannel()}setupDataChannel(){this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=e=>this.handleOnOpen(e),this.dataChannel.onclose=e=>this.handleOnClose(e),this.dataChannel.onmessage=e=>this.handleOnMessage(e),this.dataChannel.onerror=e=>this.handleOnError(e)}handleOnOpen(e){var t;d.Info(`Data Channel (${this.label}) opened.`),this.onOpen((t=this.dataChannel)===null||t===void 0?void 0:t.label,e)}handleOnClose(e){var t;d.Info(`Data Channel (${this.label}) closed.`),this.onClose((t=this.dataChannel)===null||t===void 0?void 0:t.label,e)}handleOnMessage(e){d.Info(`Data Channel (${this.label}) message: ${e}`)}handleOnError(e){var t;d.Info(`Data Channel (${this.label}) error: ${e}`),this.onError((t=this.dataChannel)===null||t===void 0?void 0:t.label,e)}onOpen(e,t){}onClose(e,t){}onError(e,t){}};var Kt=class{},jt=class{};var Qt=class{};var Te=class{};var Ee=class{},Re=class{};var Gt=class{};var Jt=class{};var Xt=class{constructor(){this.inboundVideoStats=new jt,this.inboundAudioStats=new Kt,this.candidatePairs=new Array,this.datachannelStats=new Qt,this.localCandidates=new Array,this.remoteCandidates=new Array,this.outboundVideoStats=new Ee,this.outboundAudioStats=new Ee,this.remoteOutboundAudioStats=new Re,this.remoteOutboundVideoStats=new Re,this.sessionStats=new Gt,this.streamStats=new Jt,this.codecs=new Map}processStats(e){this.localCandidates=new Array,this.remoteCandidates=new Array,this.candidatePairs=new Array,e.forEach(t=>{switch(t.type){case"candidate-pair":this.handleCandidatePair(t);break;case"certificate":break;case"codec":this.handleCodec(t);break;case"data-channel":this.handleDataChannel(t);break;case"inbound-rtp":this.handleInboundRTP(t);break;case"local-candidate":this.handleLocalCandidate(t);break;case"media-source":break;case"media-playout":break;case"outbound-rtp":this.handleLocalOutbound(t);break;case"peer-connection":break;case"remote-candidate":this.handleRemoteCandidate(t);break;case"remote-inbound-rtp":break;case"remote-outbound-rtp":this.handleRemoteOutbound(t);break;case"track":this.handleTrack(t);break;case"transport":this.handleTransport(t);break;case"stream":this.handleStream(t);break;default:d.Error("unhandled Stat Type"),d.Info(t);break}})}handleStream(e){this.streamStats=e}handleCandidatePair(e){this.candidatePairs.push(e)}handleDataChannel(e){this.datachannelStats.bytesReceived=e.bytesReceived,this.datachannelStats.bytesSent=e.bytesSent,this.datachannelStats.dataChannelIdentifier=e.dataChannelIdentifier,this.datachannelStats.id=e.id,this.datachannelStats.label=e.label,this.datachannelStats.messagesReceived=e.messagesReceived,this.datachannelStats.messagesSent=e.messagesSent,this.datachannelStats.protocol=e.protocol,this.datachannelStats.state=e.state,this.datachannelStats.timestamp=e.timestamp}handleLocalCandidate(e){let t=new Te;t.label="local-candidate",t.address=e.address,t.port=e.port,t.protocol=e.protocol,t.candidateType=e.candidateType,t.id=e.id,t.relayProtocol=e.relayProtocol,t.transportId=e.transportId,this.localCandidates.push(t)}handleRemoteCandidate(e){let t=new Te;t.label="remote-candidate",t.address=e.address,t.port=e.port,t.protocol=e.protocol,t.id=e.id,t.candidateType=e.candidateType,t.relayProtocol=e.relayProtocol,t.transportId=e.transportId,this.remoteCandidates.push(t)}handleInboundRTP(e){switch(e.kind){case"video":e.bytesReceived>this.inboundVideoStats.bytesReceived&&e.timestamp>this.inboundVideoStats.timestamp&&(this.inboundVideoStats.bitrate=8*(e.bytesReceived-this.inboundVideoStats.bytesReceived)/(e.timestamp-this.inboundVideoStats.timestamp),this.inboundVideoStats.bitrate=Math.floor(this.inboundVideoStats.bitrate));for(let t in e)this.inboundVideoStats[t]=e[t];break;case"audio":e.bytesReceived>this.inboundAudioStats.bytesReceived&&e.timestamp>this.inboundAudioStats.timestamp&&(this.inboundAudioStats.bitrate=8*(e.bytesReceived-this.inboundAudioStats.bytesReceived)/(e.timestamp-this.inboundAudioStats.timestamp),this.inboundAudioStats.bitrate=Math.floor(this.inboundAudioStats.bitrate));for(let t in e)this.inboundAudioStats[t]=e[t];break;default:d.Error(`Kind should be audio or video, we got ${e.kind} - that's unsupported.`);break}}handleLocalOutbound(e){let t=e.kind==="audio"?this.outboundAudioStats:this.outboundVideoStats;t.active=e.active,t.codecId=e.codecId,t.bytesSent=e.bytesSent,t.frameHeight=e.frameHeight,t.frameWidth=e.frameWidth,t.framesEncoded=e.framesEncoded,t.framesPerSecond=e.framesPerSecond,t.headerBytesSent=e.headerBytesSent,t.id=e.id,t.keyFramesEncoded=e.keyFramesEncoded,t.kind=e.kind,t.mediaSourceId=e.mediaSourceId,t.mid=e.mid,t.nackCount=e.nackCount,t.packetsSent=e.packetsSent,t.qpSum=e.qpSum,t.qualityLimitationDurations=e.qualityLimitationDurations,t.qualityLimitationReason=e.qualityLimitationReason,t.remoteId=e.remoteId,t.retransmittedBytesSent=e.retransmittedBytesSent,t.rid=e.rid,t.scalabilityMode=e.scalabilityMode,t.ssrc=e.ssrc,t.targetBitrate=e.targetBitrate,t.timestamp=e.timestamp,t.totalEncodeTime=e.totalEncodeTime,t.totalEncodeBytesTarget=e.totalEncodeBytesTarget,t.totalPacketSendDelay=e.totalPacketSendDelay,t.transportId=e.transportId}handleRemoteOutbound(e){let t=e.kind==="audio"?this.remoteOutboundAudioStats:this.remoteOutboundVideoStats;t.bytesSent=e.bytesSent,t.codecId=e.codecId,t.id=e.id,t.kind=e.kind,t.localId=e.localId,t.packetsSent=e.packetsSent,t.remoteTimestamp=e.remoteTimestamp,t.reportsSent=e.reportsSent,t.roundTripTimeMeasurements=e.roundTripTimeMeasurements,t.ssrc=e.ssrc,t.timestamp=e.timestamp,t.totalRoundTripTime=e.totalRoundTripTime,t.transportId=e.transportId}handleTrack(e){e.type==="track"&&(e.trackIdentifier==="video_label"||e.kind==="video")&&(this.inboundVideoStats.framesDropped=e.framesDropped,this.inboundVideoStats.framesReceived=e.framesReceived,this.inboundVideoStats.frameHeight=e.frameHeight,this.inboundVideoStats.frameWidth=e.frameWidth)}handleTransport(e){this.transportStats=e}handleCodec(e){let t=e.id;this.codecs.set(t,e)}handleSessionStatistics(e,t,n){let i=Date.now()-e;this.sessionStats.runTime=new Date(i).toISOString().substr(11,8).toString();let r=t===null?"Not sent yet":t?"true":"false";this.sessionStats.controlsStreamInput=r,this.sessionStats.videoEncoderAvgQP=n}isNumber(e){return typeof e=="number"&&isFinite(e)}getActiveCandidatePair(){if(this.candidatePairs===void 0)return null;if(this.transportStats){let t=this.candidatePairs.find(n=>n.id===this.transportStats.selectedCandidatePairId);return t===void 0?null:t}let e=this.candidatePairs.find(t=>t.selected);return e===void 0?null:e}};var en=Ir(hr());var Z=class{static isVideoTransceiver(e){return this.canTransceiverReceiveVideo(e)||this.canTransceiverSendVideo(e)}static canTransceiverReceiveVideo(e){return!!e&&(e.direction==="sendrecv"||e.direction==="recvonly")&&e.receiver&&e.receiver.track&&e.receiver.track.kind==="video"}static canTransceiverSendVideo(e){return!!e&&(e.direction==="sendrecv"||e.direction==="sendonly")&&e.sender&&e.sender.track&&e.sender.track.kind==="video"}static isAudioTransceiver(e){return this.canTransceiverReceiveAudio(e)||this.canTransceiverSendAudio(e)}static canTransceiverReceiveAudio(e){return!!e&&(e.direction==="sendrecv"||e.direction==="recvonly")&&e.receiver&&e.receiver.track&&e.receiver.track.kind==="audio"}static canTransceiverSendAudio(e){return!!e&&(e.direction==="sendrecv"||e.direction==="sendonly")&&e.sender&&e.sender.track&&e.sender.track.kind==="audio"}};var ws=class{},Cs=class{},Yt=class{constructor(){this.latestSenderRecvClockOffset=null}calculate(e,t){let n=new Ms,i=this.getRTTMs(e);if(i!=null){n.rttMs=i;let r=this.getCaptureSource(t);if(r!=null){let o=this.calculateSenderLatency(e,r);o!==null&&(n.senderLatencyMs=o)}}return e.inboundVideoStats.totalProcessingDelay!==void 0&&e.inboundVideoStats.framesDecoded!==void 0&&(n.averageProcessingDelayMs=e.inboundVideoStats.totalProcessingDelay/e.inboundVideoStats.framesDecoded*1e3),e.inboundVideoStats.jitterBufferDelay!==void 0&&e.inboundVideoStats.jitterBufferEmittedCount!==void 0&&(n.averageJitterBufferDelayMs=e.inboundVideoStats.jitterBufferDelay/e.inboundVideoStats.jitterBufferEmittedCount*1e3),e.inboundVideoStats.framesDecoded!==void 0&&e.inboundVideoStats.totalDecodeTime!==void 0&&(n.averageDecodeLatencyMs=e.inboundVideoStats.totalDecodeTime/e.inboundVideoStats.framesDecoded*1e3),e.inboundVideoStats.totalAssemblyTime!==void 0&&e.inboundVideoStats.framesAssembledFromMultiplePackets!==void 0&&(n.averageAssemblyDelayMs=e.inboundVideoStats.totalAssemblyTime/e.inboundVideoStats.framesAssembledFromMultiplePackets*1e3),e.inboundVideoStats.googTimingFrameInfo!==void 0&&e.inboundVideoStats.googTimingFrameInfo.length>0&&(n.frameTiming=this.extractFrameTimingInfo(e.inboundVideoStats.googTimingFrameInfo)),n.frameTiming!==void 0&&n.frameTiming.captureToSendLatencyMs!==void 0&&n.averageProcessingDelayMs!==void 0&&n.rttMs!==void 0&&(n.averageE2ELatency=n.frameTiming.captureToSendLatencyMs+n.rttMs*.5+n.averageProcessingDelayMs),n.senderLatencyMs!=null&&n.averageProcessingDelayMs!==void 0&&n.rttMs!==void 0&&(n.averageE2ELatency=n.senderLatencyMs+n.rttMs*.5+n.averageProcessingDelayMs),n}extractFrameTimingInfo(e){let t=new Cs,n=e.split(",");return n.length===15&&(t.rtpTimestamp=Number.parseInt(n[0]),t.captureTimestamp=Number.parseInt(n[1]),t.encodeStartTimestamp=Number.parseInt(n[2]),t.encodeFinishTimestamp=Number.parseInt(n[3]),t.packetizerFinishTimestamp=Number.parseInt(n[4]),t.pacerExitTimestamp=Number.parseInt(n[5]),t.networkTimestamp1=Number.parseInt(n[6]),t.networkTimestamp2=Number.parseInt(n[7]),t.receiveStart=Number.parseInt(n[8]),t.receiveFinish=Number.parseInt(n[9]),t.decodeStart=Number.parseInt(n[10]),t.decodeFinish=Number.parseInt(n[11]),t.renderTime=Number.parseInt(n[12]),t.isOutlier=Number.parseInt(n[13])>0,t.isTriggeredByTimer=Number.parseInt(n[14])>0,t.encoderLatencyMs=t.encodeFinishTimestamp-t.encodeStartTimestamp,t.packetizeLatencyMs=t.packetizerFinishTimestamp-t.encodeFinishTimestamp,t.pacerLatencyMs=t.pacerExitTimestamp-t.packetizerFinishTimestamp,t.captureToSendLatencyMs=t.pacerExitTimestamp-t.captureTimestamp),t}calculateSenderLatency(e,t){let n=t.captureTimestamp+t.senderCaptureTimeOffset,i=this.calculateSenderReceiverClockOffset(e);if(i==null)if(this.latestSenderRecvClockOffset!=null)i=this.latestSenderRecvClockOffset;else return null;else this.latestSenderRecvClockOffset=i;let a=n+i-22089888e5;return t.timestamp-a}getCaptureSource(e){e=e.filter(t=>t.track.kind==="video");for(let t of e){let n=t.getSynchronizationSources().concat(t.getContributingSources());for(let i of n)if(i.captureTimestamp!==void 0&&i.senderCaptureTimeOffset!==void 0&&i.timestamp!==void 0){let r=new ws;return r.timestamp=i.timestamp,r.captureTimestamp=i.captureTimestamp,r.senderCaptureTimeOffset=i.senderCaptureTimeOffset,r}}return null}calculateSenderReceiverClockOffset(e){if(!(e.remoteOutboundVideoStats!==void 0&&e.remoteOutboundVideoStats.timestamp!==void 0&&e.remoteOutboundVideoStats.remoteTimestamp!==void 0))return null;let n=e.remoteOutboundVideoStats.timestamp,i=e.remoteOutboundVideoStats.remoteTimestamp,r=this.getRTTMs(e);if(n!==void 0&&i!==void 0&&r!==null){let o=r*.5;return n-(i+o)}else return null}getRTTMs(e){let t=e.getActiveCandidatePair();return t&&t.currentRoundTripTime!==void 0?t.currentRoundTripTime*1e3:e.remoteOutboundVideoStats&&e.remoteOutboundVideoStats.totalRoundTripTime!==void 0&&e.remoteOutboundVideoStats.roundTripTimeMeasurements!==void 0&&e.remoteOutboundVideoStats.roundTripTimeMeasurements>0?e.remoteOutboundVideoStats.totalRoundTripTime/e.remoteOutboundVideoStats.roundTripTimeMeasurements*1e3:e.remoteOutboundAudioStats&&e.remoteOutboundAudioStats.totalRoundTripTime!==void 0&&e.remoteOutboundAudioStats.roundTripTimeMeasurements!==void 0&&e.remoteOutboundAudioStats.roundTripTimeMeasurements>0?e.remoteOutboundAudioStats.totalRoundTripTime/e.remoteOutboundAudioStats.roundTripTimeMeasurements*1e3:null}},Ms=class{constructor(){this.senderLatencyMs=void 0,this.senderLatencyAbsCaptureTimeMs=void 0,this.rttMs=void 0,this.averageProcessingDelayMs=void 0,this.averageJitterBufferDelayMs=void 0,this.averageDecodeLatencyMs=void 0,this.averageAssemblyDelayMs=void 0,this.averageE2ELatency=void 0,this.frameTiming=void 0}};var ke=function(s,e,t,n){function i(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function a(u){try{c(n.next(u))}catch(w){o(w)}}function l(u){try{c(n.throw(u))}catch(w){o(w)}}function c(u){u.done?r(u.value):i(u.value).then(a,l)}c((n=n.apply(s,e||[])).next())})},eo="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",Zt=class{constructor(e,t,n){this.config=t,this.createPeerConnection(e,n),this.latencyCalculator=new Yt}createPeerConnection(e,t){this.config.isFlagEnabled(h.ForceTURN)&&(e.iceTransportPolicy="relay",d.Info("Forcing TURN usage by setting ICE Transport Policy in peer connection config.")),this.peerConnection=new RTCPeerConnection(e),this.peerConnection.onsignalingstatechange=n=>this.handleSignalStateChange(n),this.peerConnection.oniceconnectionstatechange=n=>this.handleIceConnectionStateChange(n),this.peerConnection.onicegatheringstatechange=n=>this.handleIceGatheringStateChange(n),this.peerConnection.ontrack=n=>this.handleOnTrack(n),this.peerConnection.onicecandidate=n=>this.handleIceCandidate(n),this.peerConnection.ondatachannel=n=>this.handleDataChannel(n),this.aggregatedStats=new Xt,this.preferredCodec=t,this.updateCodecSelection=!0}createOffer(e,t){return ke(this,void 0,void 0,function*(){d.Info("Create Offer");let n=location.hostname==="localhost"||location.hostname==="127.0.0.1",i=location.protocol==="https:",r=t.isFlagEnabled(h.UseMic),o=t.isFlagEnabled(h.UseCamera);(r||o)&&!(n||i)&&(r=!1,o=!1,d.Error("Microphone and Webcam access in the browser will not work if you are not on HTTPS or localhost. Disabling mic and webcam access."),d.Error("For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(r,o).finally(()=>{var a;(a=this.peerConnection)===null||a===void 0||a.createOffer(e).then(l=>{var c;this.showTextOverlayConnecting(),l.sdp=this.mungeSDP(l.sdp,r),(c=this.peerConnection)===null||c===void 0||c.setLocalDescription(l),this.onSendWebRTCOffer(l)}).catch(()=>{this.showTextOverlaySetupFailure()})})})}receiveOffer(e,t){return ke(this,void 0,void 0,function*(){var n;d.Info("Receive Offer"),this.isFirefox()&&(e.sdp=e.sdp.replace(/^a=extmap:\d+ http:\/\/www\.webrtc\.org\/experiments\/rtp-hdrext\/abs-capture-time\r\n/gm,"")),(n=this.peerConnection)===null||n===void 0||n.setRemoteDescription(e).then(()=>{this.onSetRemoteDescription(e);let i=location.hostname==="localhost"||location.hostname==="127.0.0.1",r=location.protocol==="https:",o=t.isFlagEnabled(h.UseMic),a=t.isFlagEnabled(h.UseCamera);(o||a)&&!(i||r)&&(o=!1,a=!1,d.Error("Microphone and Webcam access in the browser will not work if you are not on HTTPS or localhost. Disabling mic and webcam access."),d.Error("For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.config.setOptionSettingOptions(M.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e)),this.setupTransceiversAsync(o,a).finally(()=>{var l;(l=this.peerConnection)===null||l===void 0||l.createAnswer().then(c=>{var u;return c.sdp=this.mungeSDP(c.sdp,o),(u=this.peerConnection)===null||u===void 0?void 0:u.setLocalDescription(c)}).then(()=>{var c;this.onSetLocalDescription((c=this.peerConnection)===null||c===void 0?void 0:c.localDescription)}).catch(c=>{d.Error(`createAnswer() failed - ${c}`)})})})})}receiveAnswer(e){var t;(t=this.peerConnection)===null||t===void 0||t.setRemoteDescription(e),this.config.setOptionSettingOptions(M.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e))}generateStats(){this.peerConnection.getStats().then(e=>{this.aggregatedStats.processStats(e),this.onVideoStats(this.aggregatedStats);let t=this.latencyCalculator.calculate(this.aggregatedStats,this.peerConnection.getReceivers());if(this.onLatencyCalculated(t),this.updateCodecSelection&&this.aggregatedStats.inboundVideoStats.codecId){let n=this.aggregatedStats.codecs.get(this.aggregatedStats.inboundVideoStats.codecId);if(n===void 0)return;let i=n.mimeType.replace("video/",""),r=i;n.sdpFmtpLine&&n.sdpFmtpLine.trim()!==""&&(r=`${i} ${n.sdpFmtpLine.trim()}`);let o=this.config.getSettingOption(M.PreferredCodec).options;if(o.includes(r)){this.config.setOptionSettingValue(M.PreferredCodec,r);return}let a=o.filter(l=>l.indexOf(i)!==-1);if(a.length>0){this.config.setOptionSettingValue(M.PreferredCodec,a[0]);return}}})}close(){this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null)}mungeSDP(e,t){let n=e.replace(/(a=fmtp:\d+ .*level-asymmetry-allowed=.*)\r\n/gm,`$1;x-google-start-bitrate=10000;x-google-max-bitrate=100000\r
|
|
42
|
+
`),i="maxaveragebitrate=510000;";return t&&(i+="sprop-maxcapturerate=48000;"),i+=this.config.isFlagEnabled(h.ForceMonoAudio)?"stereo=0;":"stereo=1;",i+="useinbandfec=1",n=n.replace("useinbandfec=1",i),this.config.isFlagEnabled(h.EnableCaptureTimeExt)&&!this.isFirefox()&&(n=tt.addVideoHeaderExtensionToSdp(n,eo)),n}isFirefox(){return navigator.userAgent.indexOf("Firefox")>0}handleOnIce(e){var t;if(d.Info("peerconnection handleOnIce"),this.config.isFlagEnabled(h.ForceTURN)&&e.candidate.indexOf("relay")<0){d.Info(`Dropping candidate because it was not TURN relay. | Type= ${e.type} | Protocol= ${e.protocol} | Address=${e.address} | Port=${e.port} |`);return}(t=this.peerConnection)===null||t===void 0||t.addIceCandidate(e)}handleSignalStateChange(e){d.Info("signaling state change: "+e)}handleIceConnectionStateChange(e){d.Info("ice connection state change: "+e),this.onIceConnectionStateChange(e)}handleIceGatheringStateChange(e){d.Info("ice gathering state change: "+JSON.stringify(e))}handleOnTrack(e){e.streams.length<1||e.streams[0].id=="probator"||(e.track.kind=="video"&&(this.videoTrack=e.track),e.track.kind=="audio"&&(this.audioTrack=e.track),this.onTrack(e))}handleIceCandidate(e){this.onPeerIceCandidate(e)}handleDataChannel(e){this.onDataChannel(e)}onTrack(e){}onIceConnectionStateChange(e){}onPeerIceCandidate(e){}onDataChannel(e){}fuzzyIntersectUEAndBrowserCodecs(e){let t=new Array,n=this.parseAvailableCodecs(e),i=this.config.getSettingOption(M.PreferredCodec).options;for(let r of n)if(i.includes(r)){t.push(r);continue}else{let a=r.split(" ")[0];for(let l of i)if(l.includes(a)){t.push(l);break}}return t}setupTransceiversAsync(e,t){return ke(this,void 0,void 0,function*(){var n,i,r,o,a,l,c,u;let w=!1;for(let C of(i=(n=this.peerConnection)===null||n===void 0?void 0:n.getTransceivers())!==null&&i!==void 0?i:[])if(C&&C.receiver&&C.receiver.track&&C.receiver.track.kind==="video"){w=!0;break}if(t?yield this.setupVideoSender(w):w||(r=this.peerConnection)===null||r===void 0||r.addTransceiver("video",{direction:"recvonly"}),RTCRtpReceiver.getCapabilities&&this.preferredCodec!=""){for(let C of(a=(o=this.peerConnection)===null||o===void 0?void 0:o.getTransceivers())!==null&&a!==void 0?a:[])if(C&&C.receiver&&C.receiver.track&&C.receiver.track.kind==="video"&&C.setCodecPreferences){let k=this.preferredCodec.split(" "),U={mimeType:"video/"+k[0],clockRate:9e4,sdpFmtpLine:k[1]?k[1]:""},H=[U];RTCRtpReceiver.getCapabilities("video").codecs.forEach(A=>{(A.mimeType!=U.mimeType||A?.sdpFmtpLine!=U?.sdpFmtpLine)&&H.push(A)});for(let A of H)(A?.sdpFmtpLine===void 0||A.sdpFmtpLine==="")&&delete A.sdpFmtpLine;C.setCodecPreferences(H)}}let v=!1;for(let C of(c=(l=this.peerConnection)===null||l===void 0?void 0:l.getTransceivers())!==null&&c!==void 0?c:[])if(C&&C.receiver&&C.receiver.track&&C.receiver.track.kind==="audio"){v=!0;break}e?yield this.setupAudioSender(v):v||(u=this.peerConnection)===null||u===void 0||u.addTransceiver("audio",{direction:"recvonly"})})}setupVideoSender(e){return ke(this,void 0,void 0,function*(){var t,n,i,r;let o={video:!0},a=yield navigator.mediaDevices.getUserMedia(o);if(a)if(e){for(let l of(n=(t=this.peerConnection)===null||t===void 0?void 0:t.getTransceivers())!==null&&n!==void 0?n:[])if(Z.canTransceiverReceiveVideo(l))for(let c of a.getTracks())c.kind&&c.kind=="video"&&(l.sender.replaceTrack(c),l.direction="sendrecv")}else for(let l of a.getTracks())l.kind&&l.kind=="video"&&((i=this.peerConnection)===null||i===void 0||i.addTransceiver(l,{direction:"sendrecv"}));else e||(r=this.peerConnection)===null||r===void 0||r.addTransceiver("video",{direction:"recvonly"})})}setupAudioSender(e){return ke(this,void 0,void 0,function*(){var t,n,i,r;let a={video:!1,audio:{autoGainControl:!1,channelCount:1,echoCancellation:!1,latency:0,noiseSuppression:!1,sampleRate:48e3,sampleSize:16,volume:1}},l=yield navigator.mediaDevices.getUserMedia(a);if(l)if(e){for(let c of(n=(t=this.peerConnection)===null||t===void 0?void 0:t.getTransceivers())!==null&&n!==void 0?n:[])if(Z.canTransceiverReceiveAudio(c))for(let u of l.getTracks())u.kind&&u.kind=="audio"&&(c.sender.replaceTrack(u),c.direction="sendrecv")}else for(let c of l.getTracks())c.kind&&c.kind=="audio"&&((i=this.peerConnection)===null||i===void 0||i.addTransceiver(c,{direction:"sendrecv"}));else e||(r=this.peerConnection)===null||r===void 0||r.addTransceiver("audio",{direction:"recvonly"})})}onVideoStats(e){}onLatencyCalculated(e){}onSendWebRTCOffer(e){}onSetRemoteDescription(e){}onSetLocalDescription(e){}showTextOverlayConnecting(){}showTextOverlaySetupFailure(){}parseAvailableCodecs(e){if(!RTCRtpReceiver.getCapabilities)return["Only available on Chrome"];let t=[],n=(0,en.splitSections)(e.sdp);return n.shift(),n.forEach(i=>{let{codecs:r}=(0,en.parseRtpParameters)(i),o=/(VP\d|H26\d|AV1).*/;r.forEach(a=>{let l=a.name+" "+Object.keys(a.parameters||{}).map(u=>u+"="+a.parameters[u]).join(";");if(o.exec(l)!==null){a.name=="VP9"&&(a.parameters={"profile-id":"0"});let u=a.name+" "+Object.keys(a.parameters||{}).map(w=>w+"="+a.parameters[w]).join(";");t.push(u)}})}),t}};var tn=class{constructor(){this.PixelStreamingSettings=new Ts,this.EncoderSettings=new Es,this.WebRTCSettings=new Rs}ueCompatible(){this.WebRTCSettings.MaxFPS!=null&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}},Ts=class{},Es=class{},Rs=class{};var nn=class{constructor(){this.ReceiptTimeMs=null,this.TransmissionTimeMs=null,this.PreCaptureTimeMs=null,this.PostCaptureTimeMs=null,this.PreEncodeTimeMs=null,this.PostEncodeTimeMs=null,this.EncodeMs=null,this.CaptureToSendMs=null,this.testStartTimeMs=0,this.browserReceiptTimeMs=0,this.latencyExcludingDecode=0,this.testDuration=0,this.networkLatency=0,this.browserSendLatency=0,this.frameDisplayDeltaTimeMs=0,this.endToEndLatency=0,this.encodeLatency=0}setFrameDisplayDeltaTime(e){this.frameDisplayDeltaTimeMs==0&&(this.frameDisplayDeltaTimeMs=Math.round(e))}processFields(){this.EncodeMs==null&&(this.PreEncodeTimeMs!=null||this.PostEncodeTimeMs!=null)&&(d.Info(`Setting Encode Ms
|
|
43
43
|
${this.PostEncodeTimeMs}
|
|
44
44
|
${this.PreEncodeTimeMs}`),this.EncodeMs=this.PostEncodeTimeMs-this.PreEncodeTimeMs),this.CaptureToSendMs==null&&(this.PreCaptureTimeMs!=null||this.PostCaptureTimeMs!=null)&&(d.Info(`Setting CaptureToSendMs Ms
|
|
45
45
|
${this.PostCaptureTimeMs}
|
|
@@ -78,10 +78,10 @@ m=`).map((l,c)=>(c>0?"m="+l:l).trim()+`\r
|
|
|
78
78
|
}
|
|
79
79
|
`,n=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(n,e),this.gl.compileShader(n);let i=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(i,t),this.gl.compileShader(i);let r=this.gl.createProgram();this.gl.attachShader(r,n),this.gl.attachShader(r,i),this.gl.linkProgram(r),this.gl.useProgram(r),this.positionLocation=this.gl.getAttribLocation(r,"a_position"),this.texcoordLocation=this.gl.getAttribLocation(r,"a_texCoord")}updateVideoTexture(){this.videoTexture||(this.videoTexture=this.gl.createTexture(),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR));let e=this.webRtcController.videoPlayer.getVideoElement().videoHeight,t=this.webRtcController.videoPlayer.getVideoElement().videoWidth;this.prevVideoHeight!=e||this.prevVideoWidth!=t?this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,t,e,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()):this.gl.texSubImage2D(this.gl.TEXTURE_2D,0,0,0,t,e,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.webRtcController.videoPlayer.getVideoElement()),this.prevVideoHeight=e,this.prevVideoWidth=t}initBuffers(){this.positionBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.positionLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-1,1,1,1,-1,-1,-1,-1,1,1,1,-1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.positionLocation,2,this.gl.FLOAT,!1,0,0),this.texcoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texcoordBuffer),this.gl.enableVertexAttribArray(this.texcoordLocation),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(this.texcoordLocation,2,this.gl.FLOAT,!1,0,0)}onXrSessionStarted(e){d.Info("XR Session started"),this.xrSession=e,this.xrSession.addEventListener("end",()=>{this.onXrSessionEnded()}),this.initGL(),this.initShaders(),this.initBuffers(),e.requestReferenceSpace("local").then(t=>{if(this.xrRefSpace=t,this.xrSession.updateRenderState({baseLayer:new XRWebGLLayer(this.xrSession,this.gl)}),this.xrSession.supportedFrameRates)for(let n of this.xrSession.supportedFrameRates)n==90&&e.updateTargetFrameRate(90);this.xrSession.requestAnimationFrame(this.onXrFrame.bind(this))}),this.onSessionStarted.dispatchEvent(new Event("xrSessionStarted"))}areArraysEqual(e,t){return e.length===t.length&&e.every((n,i)=>Math.abs(n-t[i])<=this.EPSILON)}arePointsEqual(e,t){return Math.abs(e.x-t.x)>=this.EPSILON&&Math.abs(e.y-t.y)>=this.EPSILON&&Math.abs(e.z-t.z)>=this.EPSILON}sendXRDataToUE(){if(this.leftView==null||this.rightView==null)return;let e=this.lastSentLeftEyeProj==null||this.lastSentRightEyeProj==null||this.lastSentRelativeLeftEyePos==null||this.lastSentRelativeRightEyePos==null,t=this.leftView.transform.matrix,n=this.leftView.projectionMatrix,i=this.rightView.transform.matrix,r=this.rightView.projectionMatrix,o=this.xrViewerPose.transform.matrix;if(!e&&this.lastSentLeftEyeProj!=null&&this.lastSentRightEyeProj!=null){let c=this.areArraysEqual(n,this.lastSentLeftEyeProj),u=this.areArraysEqual(r,this.lastSentRightEyeProj);e=c==!1||u==!1}let a=new DOMPointReadOnly(this.leftView.transform.position.x-this.xrViewerPose.transform.position.x,this.leftView.transform.position.y-this.xrViewerPose.transform.position.y,this.leftView.transform.position.z-this.xrViewerPose.transform.position.z,1),l=new DOMPointReadOnly(this.leftView.transform.position.x-this.xrViewerPose.transform.position.x,this.leftView.transform.position.y-this.xrViewerPose.transform.position.y,this.leftView.transform.position.z-this.xrViewerPose.transform.position.z,1);if(!e&&this.lastSentRelativeLeftEyePos!=null&&this.lastSentRelativeRightEyePos!=null){let c=this.arePointsEqual(a,this.lastSentRelativeLeftEyePos),u=this.arePointsEqual(l,this.lastSentRelativeRightEyePos);e=c==!1||u==!1}e?(this.webRtcController.streamMessageController.toStreamerHandlers.get("XREyeViews")([t[0],t[4],t[8],t[12],t[1],t[5],t[9],t[13],t[2],t[6],t[10],t[14],t[3],t[7],t[11],t[15],n[0],n[4],n[8],n[12],n[1],n[5],n[9],n[13],n[2],n[6],n[10],n[14],n[3],n[7],n[11],n[15],i[0],i[4],i[8],i[12],i[1],i[5],i[9],i[13],i[2],i[6],i[10],i[14],i[3],i[7],i[11],i[15],r[0],r[4],r[8],r[12],r[1],r[5],r[9],r[13],r[2],r[6],r[10],r[14],r[3],r[7],r[11],r[15],o[0],o[4],o[8],o[12],o[1],o[5],o[9],o[13],o[2],o[6],o[10],o[14],o[3],o[7],o[11],o[15]]),this.lastSentLeftEyeProj=n,this.lastSentRightEyeProj=r,this.lastSentRelativeLeftEyePos=a,this.lastSentRelativeRightEyePos=l):this.webRtcController.streamMessageController.toStreamerHandlers.get("XRHMDTransform")([o[0],o[4],o[8],o[12],o[1],o[5],o[9],o[13],o[2],o[6],o[10],o[14],o[3],o[7],o[11],o[15]])}onXrFrame(e,t){if(this.xrViewerPose=t.getViewerPose(this.xrRefSpace),this.xrViewerPose){if(this.updateViews(),this.leftView==null||this.rightView==null)return;this.sendXRDataToUE(),this.updateVideoTexture(),this.render()}this.webRtcController.config.isFlagEnabled(h.XRControllerInput)&&this.xrSession.inputSources.forEach((n,i,r)=>{this.xrGamepadController.updateStatus(n,t,this.xrRefSpace)},this),this.xrSession.requestAnimationFrame((n,i)=>this.onXrFrame(n,i)),this.onFrame.dispatchEvent(new _t({time:e,frame:t}))}updateViews(){if(this.xrViewerPose)for(let e of this.xrViewerPose.views)e.eye==="left"?this.leftView=e:e.eye==="right"&&(this.rightView=e)}render(){if(!this.gl)return;let e=this.xrSession.renderState.baseLayer;this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,e.framebuffer),this.gl.viewport(0,0,e.framebufferWidth,e.framebufferHeight),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}static isSessionSupported(e){location.protocol!=="https:"&&d.Info("WebXR requires https, if you want WebXR use https.");try{if(navigator.xr)return navigator.xr.isSessionSupported(e)}catch{return Promise.resolve(!1)}return Promise.resolve(!1)}};var Cn=class{constructor(e){this.seq=e.Seq,this.playerSentTimestamp=Date.now(),this.requestFillerSize=e.Filler?e.Filler.length:0}update(e){this.playerReceivedTimestamp=Date.now(),this.streamerReceivedTimestamp=e.ReceivedTimestamp,this.streamerSentTimestamp=e.SentTimestamp,this.responseFillerSize=e.Filler?e.Filler.length:0}};var Mn=class{constructor(e,t){this.intervalHandle=void 0,this.sink=e,this.callback=t,this.records=new Map,this.seq=0}start(e){return this.isRunning()?!1:(this.startTime=Date.now(),this.records.clear(),this.intervalHandle=window.setInterval((()=>{Date.now()-this.startTime>=e.duration?this.stop():this.sendRequest(e.requestSize,e.responseSize)}).bind(this),Math.floor(1e3/e.rps)),!0)}stop(){this.intervalHandle&&(window.clearInterval(this.intervalHandle),this.intervalHandle=void 0,this.callback(this.produceResult()))}produceResult(){let e=new Map(this.records);return{records:e,dataChannelRtt:Math.ceil(Array.from(this.records.values()).reduce((t,n)=>t+(n.playerReceivedTimestamp-n.playerSentTimestamp),0)/this.records.size),playerToStreamerTime:Math.ceil(Array.from(this.records.values()).reduce((t,n)=>t+(n.streamerReceivedTimestamp-n.playerSentTimestamp),0)/this.records.size),streamerToPlayerTime:Math.ceil(Array.from(this.records.values()).reduce((t,n)=>t+(n.playerReceivedTimestamp-n.streamerSentTimestamp),0)/this.records.size),exportLatencyAsCSV:()=>{let t=`Timestamp;RTT;PlayerToStreamer;StreamerToPlayer;
|
|
80
80
|
`;return e.forEach(n=>{t+=n.playerSentTimestamp+";",t+=n.playerReceivedTimestamp-n.playerSentTimestamp+";",t+=n.streamerReceivedTimestamp-n.playerSentTimestamp+";",t+=n.playerReceivedTimestamp-n.streamerSentTimestamp+";",t+=`
|
|
81
|
-
`}),t}}}isRunning(){return!!this.intervalHandle}receive(e){if(!this.isRunning())return;if(!e){d.Error("Undefined response from server");return}let t=this.records.get(e.Seq);t&&t.update(e)}sendRequest(e,t){let n=this.createRequest(e,t),i=new Cn(n);this.records.set(i.seq,i),this.sink(n)}createRequest(e,t){return{Seq:this.seq++,FillResponseSize:t,Filler:e?"A".repeat(e):""}}};var xe=class{constructor(e,t){this.allowConsoleCommands=!1,this.config=e,t?.videoElementParent&&(this._videoElementParent=t.videoElementParent),this._eventEmitter=new $t,this.configureSettings(),this.setWebRtcPlayerController(new bn(this.config,this)),this._webXrController=new wn(this._webRtcController),this._setupWebRtcTCPRelayDetection=this._setupWebRtcTCPRelayDetection.bind(this),this._eventEmitter.addEventListener("webRtcConnected",n=>{this._eventEmitter.addEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)})}get videoElementParent(){return this._videoElementParent||(this._videoElementParent=document.createElement("div"),this._videoElementParent.id="videoElementParent"),this._videoElementParent}configureSettings(){this.config._addOnSettingChangedListener(h.IsQualityController,e=>{e===!0&&!this._webRtcController.isQualityController&&this._webRtcController.sendRequestQualityControlOwnership()}),this.config._addOnSettingChangedListener(h.AFKDetection,e=>{this._webRtcController.setAfkEnabled(e)}),this.config._addOnSettingChangedListener(h.MatchViewportResolution,()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()}),this.config._addOnSettingChangedListener(h.HoveringMouseMode,e=>{this.config.setFlagLabel(h.HoveringMouseMode,`Control Scheme: ${e?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(h.MouseInput))}),this.config._addOnSettingChangedListener(h.KeyboardInput,e=>{this._webRtcController.setKeyboardInputEnabled(e)}),this.config._addOnSettingChangedListener(h.MouseInput,e=>{this._webRtcController.setMouseInputEnabled(e)}),this.config._addOnSettingChangedListener(h.FakeMouseWithTouches,e=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(h.TouchInput))}),this.config._addOnSettingChangedListener(h.TouchInput,e=>{this._webRtcController.setTouchInputEnabled(e)}),this.config._addOnSettingChangedListener(h.GamepadInput,e=>{this._webRtcController.setGamePadInputEnabled(e)}),this.config._addOnNumericSettingChangedListener(m.MinQP,e=>{d.Info("-------- Sending MinQP --------"),this._webRtcController.sendEncoderMinQP(e),d.Info("-------------------------------------------");let t=Math.trunc(100*(1-e/51));this.config.setNumericSetting(m.CompatQualityMax,t)}),this.config._addOnNumericSettingChangedListener(m.MaxQP,e=>{d.Info("-------- Sending MaxQP --------"),this._webRtcController.sendEncoderMaxQP(e),d.Info("-------------------------------------------");let t=Math.trunc(100*(1-e/51));this.config.setNumericSetting(m.CompatQualityMin,t)}),this.config._addOnNumericSettingChangedListener(m.MinQuality,e=>{d.Info("-------- Sending MinQuality --------"),this._webRtcController.sendEncoderMinQuality(e),d.Info("-------------------------------------------"),this.config.setNumericSetting(m.CompatQualityMin,e)}),this.config._addOnNumericSettingChangedListener(m.MaxQuality,e=>{d.Info("-------- Sending MaxQuality --------"),this._webRtcController.sendEncoderMaxQuality(e),d.Info("-------------------------------------------"),this.config.setNumericSetting(m.CompatQualityMax,e)}),this.config._addOnNumericSettingChangedListener(m.CompatQualityMin,e=>{e=51-e/100*51,d.Info("-------- Sending MinQP from quality value --------"),this._webRtcController.sendEncoderMaxQP(e),d.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(m.CompatQualityMax,e=>{e=51-e/100*51,d.Info("-------- Sending MaxQP from quality value --------"),this._webRtcController.sendEncoderMinQP(e),d.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(m.WebRTCMinBitrate,e=>{d.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCMinBitrate(e*1e3),d.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(m.WebRTCMaxBitrate,e=>{d.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCMaxBitrate(e*1e3),d.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(m.WebRTCFPS,e=>{d.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCFps(e),d.Info("-------------------------------------------")}),this.config._addOnOptionSettingChangedListener(M.PreferredCodec,e=>{this._webRtcController&&this._webRtcController.setPreferredCodec(e)}),this.config._registerOnChangeEvents(this._eventEmitter)}_onInputControlOwnership(e){this._inputController=e}setWebRtcPlayerController(e){this._webRtcController=e,this._webRtcController.setPreferredCodec(this.config.getSettingOption(M.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Mt),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Et),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Tt),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(h.AutoConnect)&&(this._onWebRtcAutoConnect(),this._webRtcController.connectToSignallingServer())}unmuteMicrophone(e=!1){if(this.config.isFlagEnabled("UseMic")){this.setMicrophoneMuted(!1);return}if(e){this.config.setFlagEnabled("UseMic",!0),this.reconnect();return}d.Warning("Trying to unmute mic, but PixelStreaming was initialized with no microphone track. Call with forceEnable == true to re-connect with a mic track.")}muteMicrophone(){if(this.config.isFlagEnabled("UseMic")){this.setMicrophoneMuted(!0);return}d.Info("Trying to mute mic, but PixelStreaming has no microphone track, so sending sound is already disabled.")}setMicrophoneMuted(e){var t,n,i,r;for(let o of(r=(i=(n=(t=this._webRtcController)===null||t===void 0?void 0:t.peerConnectionController)===null||n===void 0?void 0:n.peerConnection)===null||i===void 0?void 0:i.getTransceivers())!==null&&r!==void 0?r:[])Z.canTransceiverSendAudio(o)&&(o.sender.track.enabled=!e)}unmuteCamera(e=!1){if(this.config.isFlagEnabled("UseCamera")){this.setCameraMuted(!1);return}if(e){this.config.setFlagEnabled("UseCamera",!0),this.reconnect();return}d.Warning("Trying to unmute video, but PixelStreaming was initialized with no video track. Call with forceEnable == true to re-connect with a video track.")}muteCamera(){if(this.config.isFlagEnabled("UseCamera")){this.setCameraMuted(!0);return}d.Info("Trying to mute camera, but PixelStreaming has no video track, so sending video is already disabled.")}setCameraMuted(e){var t,n,i,r;for(let o of(r=(i=(n=(t=this._webRtcController)===null||t===void 0?void 0:t.peerConnectionController)===null||n===void 0?void 0:n.peerConnection)===null||i===void 0?void 0:i.getTransceivers())!==null&&r!==void 0?r:[])Z.canTransceiverSendVideo(o)&&(o.sender.track.enabled=!e)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new pt)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new dt)}_onWebRtcSdpOffer(e){this._eventEmitter.dispatchEvent(new ut({sdp:e}))}_onWebRtcSdpAnswer(e){this._eventEmitter.dispatchEvent(new ht({sdp:e}))}_onLatencyCalculated(e){this._eventEmitter.dispatchEvent(new Ft({latencyInfo:e}))}_onStreamLoading(){this._eventEmitter.dispatchEvent(new Ct)}_onDisconnect(e,t){this._eventEmitter.dispatchEvent(new yt({eventString:e,allowClickToReconnect:t}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new mt)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new ft)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new gt)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new wt),this._videoStartTime=Date.now()}_onLatencyTestResult(e){this._eventEmitter.dispatchEvent(new Ot({latencyTimings:e}))}_onDataChannelLatencyTestResponse(e){this._eventEmitter.dispatchEvent(new Nt({response:e}))}_onVideoStats(e){(!this._videoStartTime||this._videoStartTime===void 0)&&(this._videoStartTime=Date.now()),e.handleSessionStatistics(this._videoStartTime,this._inputController,this._webRtcController.videoAvgQp),this._eventEmitter.dispatchEvent(new Pt({aggregatedStats:e}))}_onVideoEncoderAvgQP(e){this._eventEmitter.dispatchEvent(new ct({avgQP:e}))}_onInitialSettings(e){var t;this._eventEmitter.dispatchEvent(new Vt({settings:e})),e.PixelStreamingSettings&&(this.allowConsoleCommands=(t=e.PixelStreamingSettings.AllowPixelStreamingCommands)!==null&&t!==void 0?t:!1,this.allowConsoleCommands===!1&&d.Info("-AllowPixelStreamingCommands=false, sending arbitrary console commands from browser to UE is disabled."));let n=this.config.useUrlParams,i=new ue(window.location.search);d.Info(`using URL parameters ${n}`),e.EncoderSettings&&(e.EncoderSettings.MinQP&&(this.config.setNumericSetting(m.MinQP,n&&i.has(m.MinQP)?Number.parseFloat(i.get(m.MinQP)):e.EncoderSettings.MinQP||0),this.config.setNumericSetting(m.MaxQP,n&&i.has(m.MaxQP)?Number.parseFloat(i.get(m.MaxQP)):e.EncoderSettings.MaxQP||51)),e.EncoderSettings.MinQuality&&(this.config.setNumericSetting(m.MinQuality,n&&i.has(m.MinQuality)?Number.parseFloat(i.get(m.MinQuality)):e.EncoderSettings.MinQuality||0),this.config.setNumericSetting(m.MaxQuality,n&&i.has(m.MaxQuality)?Number.parseFloat(i.get(m.MaxQuality)):e.EncoderSettings.MaxQuality||100)),n&&(i.has(m.CompatQualityMin)&&this.config.setNumericSetting(m.CompatQualityMin,Number.parseFloat(i.get(m.CompatQualityMin))),i.has(m.CompatQualityMax)&&this.config.setNumericSetting(m.CompatQualityMax,Number.parseFloat(i.get(m.CompatQualityMax))))),e.WebRTCSettings&&(this.config.setNumericSetting(m.WebRTCMinBitrate,n&&i.has(m.WebRTCMinBitrate)?Number.parseFloat(i.get(m.WebRTCMinBitrate)):e.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(m.WebRTCMaxBitrate,n&&i.has(m.WebRTCMaxBitrate)?Number.parseFloat(i.get(m.WebRTCMaxBitrate)):e.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(m.WebRTCFPS,n&&i.has(m.WebRTCFPS)?Number.parseFloat(i.get(m.WebRTCFPS)):e.WebRTCSettings.FPS))}_onQualityControlOwnership(e){this.config.setFlagEnabled(h.IsQualityController,e)}_onPlayerCount(e){this._eventEmitter.dispatchEvent(new Wt({count:e}))}_onSubscribeFailed(e){this._eventEmitter.dispatchEvent(new Bt({message:e}))}_setupWebRtcTCPRelayDetection(e){let t=e.data.aggregatedStats.getActiveCandidatePair();if(t!=null){let n=e.data.aggregatedStats.localCandidates.find(i=>i.id==t.localCandidateId,null);n!=null&&n.candidateType=="relay"&&n.relayProtocol=="tcp"&&this._eventEmitter.dispatchEvent(new Ht),this._eventEmitter.removeEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}}requestLatencyTest(){return this._webRtcController.videoPlayer.isVideoReady()?(this._webRtcController.sendLatencyTest(),!0):!1}requestDataChannelLatencyTest(e){return this._webRtcController.videoPlayer.isVideoReady()?(this._dataChannelLatencyTestController||(this._dataChannelLatencyTestController=new Mn(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),t=>{this._eventEmitter.dispatchEvent(new Ut({result:t}))}),this.addEventListener("dataChannelLatencyTestResponse",({data:{response:t}})=>{this._dataChannelLatencyTestController.receive(t)})),this._dataChannelLatencyTestController.start(e)):!1}requestShowFps(){return this._webRtcController.videoPlayer.isVideoReady()?(this._webRtcController.sendShowFps(),!0):!1}requestIframe(){return this._webRtcController.videoPlayer.isVideoReady()?(this._webRtcController.sendIframeRequest(),!0):!1}emitUIInteraction(e){return this._webRtcController.videoPlayer.isVideoReady()?(this._webRtcController.emitUIInteraction(e),!0):!1}emitCommand(e){return!this._webRtcController.videoPlayer.isVideoReady()||!this.allowConsoleCommands&&"ConsoleCommand"in e?!1:(this._webRtcController.emitCommand(e),!0)}emitConsoleCommand(e){return!this.allowConsoleCommands||!this._webRtcController.videoPlayer.isVideoReady()?!1:(this._webRtcController.emitConsoleCommand(e),!0)}sendTextboxEntry(e){return this._webRtcController.videoPlayer.isVideoReady()?(this._webRtcController.sendTextboxEntry(e),!0):!1}addResponseEventListener(e,t){this._webRtcController.responseController.addResponseEventListener(e,t)}removeResponseEventListener(e){this._webRtcController.responseController.removeResponseEventListener(e)}dispatchEvent(e){return this._eventEmitter.dispatchEvent(e)}addEventListener(e,t){this._eventEmitter.addEventListener(e,t)}removeEventListener(e,t){this._eventEmitter.removeEventListener(e,t)}toggleXR(){this.webXrController.xrClicked()}setSignallingUrlBuilder(e){this._webRtcController.signallingUrlBuilder=e}get webRtcController(){return this._webRtcController}get signallingProtocol(){return this._webRtcController.protocol}get webXrController(){return this._webXrController}registerMessageHandler(e,t,n){if(t===S.FromStreamer&&typeof n>"u"){d.Warning(`Unable to register an undefined handler for ${e}`);return}t===S.ToStreamer&&typeof n>"u"?this._webRtcController.streamMessageController.registerMessageHandler(t,e,i=>this._webRtcController.sendMessageController.sendMessageToStreamer(e,i)):this._webRtcController.streamMessageController.registerMessageHandler(t,e,i=>n(i))}get toStreamerHandlers(){return this._webRtcController.streamMessageController.toStreamerHandlers}isReconnecting(){return this._webRtcController.isReconnecting}};var Tn=class{type=0},En=class{type=1},Rn=class{constructor(e){this.msg=e}msg;type=2};var kn=class{constructor(e){this.stats=e}stats;type=5};var hr="sessionEndedDueToInactivity",ur="sessionEndedByUser",Is="sessionEndedDueToConnectionLoss",Ps="sessionEndedDueToVideoPlaybackError",pr="sessionEndedDueToPermissionsError";var Ls="sessionEndedDueToRendererError";var mr=(n=>(n.Good="Good",n.Fair="Fair",n.Poor="Poor",n))(mr||{}),fr=(n=>(n.Always="always",n.WhenDegraded="when-degraded",n.Hidden="hidden",n))(fr||{}),gr=(i=>(i.TopLeft="top-left",i.TopRight="top-right",i.BottomLeft="bottom-left",i.BottomRight="bottom-right",i))(gr||{}),yr=(n=>(n.Click="click",n.Hover="hover",n.None="none",n))(yr||{});function Ie(s,e,t){return Math.max(e,Math.min(s,t))}function Sr(s){let e=s.packetLoss??0,t=s.bufferDelay??50,n=s.roundTripTime??50,i=s.fec??!0,r=s.dtx??!1,o=s.bitrate,a=20+t+n/2,l=100,c=r?8:o?Ie(55-4.6*Math.log(o),0,30):6,u=i?20:10,w=c+(100-c)*(e/(e+u)),v=a*.03+(a>150?.1*(a-150):0),C=Ie(l-w-v,0,100),k=1+.035*C+C*(C-60)*(100-C)*7/1e6;return Ie(Math.round(k*100)/100,1,5)}function br(s){let e=s.bitrate??0,t=s.roundTripTime??50,n=s.bufferDelay??0,i=s.width||640,r=s.height||480,o=s.frameRate??0,a=s.expectedFrameRate??30,l=s.codec?.toLowerCase();if(o===0)return 1;let c=i*r,u=l==="vp9"?1.2:1,w=n+t/2,v=u*e/c/o,k=Ie(.56*Math.log(v)+5.36,1,5)-1.9*Math.log(a/o)-w*.002;return Ie(Math.round(k*100)/100,1,5)}function xn(s){let e=s?.srcObject;return!!e&&typeof e.getAudioTracks=="function"&&e.getAudioTracks().length>0}var eo=3.5,to=2.5,pe=class{constructor(e,t,n){this.stream=e;this.videoElement=t;this.audioElement=n}stream;videoElement;audioElement;previousStats;getPeerConnection(){return this.stream?.webRtcController?.peerConnectionController?.peerConnection}async analyzeAudioStats(){let e=this.getPeerConnection();if(!e){p.error("Stream appears to be down, RTCPeerConnection is not defined");return}let t=await e.getStats(null),n=this.getInboundAudioStats(t);if(!n){p.warn("WebRTC Connection - No inbound audio RTP stats found.");return}let i=n.codecId,r=i?this.getCodecFromStats(t,i):void 0;this.logAudioStats(n,r),this.logElementStatus(r)}async collectNetworkQuality(e){let t=this.getPeerConnection();if(!t)return p.warn("Cannot collect network quality: RTCPeerConnection is not defined"),null;let n=await t.getStats(null),i=this.extractRawStats(n);if(!this.previousStats)return this.previousStats=i,null;let r=this.computeMetrics(i,this.previousStats,e);return this.previousStats=i,r}resetStats(){this.previousStats=void 0}extractRawStats(e){let t={timestamp:Date.now(),audio:{packetsReceived:0,packetsLost:0,bytesReceived:0,jitter:0},video:{packetsReceived:0,packetsLost:0,bytesReceived:0,framesDecoded:0,framesDropped:0,frameWidth:0,frameHeight:0,framesPerSecond:0,jitter:0},connection:{currentRoundTripTime:0}},n,i;if(e.forEach(r=>{r.type==="inbound-rtp"&&r.kind==="audio"?(t.audio.packetsReceived=r.packetsReceived??0,t.audio.packetsLost=r.packetsLost??0,t.audio.bytesReceived=r.bytesReceived??0,t.audio.jitter=r.jitter??0,n=r.codecId):r.type==="inbound-rtp"&&r.kind==="video"?(t.video.packetsReceived=r.packetsReceived??0,t.video.packetsLost=r.packetsLost??0,t.video.bytesReceived=r.bytesReceived??0,t.video.framesDecoded=r.framesDecoded??0,t.video.framesDropped=r.framesDropped??0,t.video.frameWidth=r.frameWidth??0,t.video.frameHeight=r.frameHeight??0,t.video.framesPerSecond=r.framesPerSecond??0,t.video.jitter=r.jitter??0,i=r.codecId):r.type==="candidate-pair"&&r.nominated&&(t.connection.currentRoundTripTime=r.currentRoundTripTime??0)}),n){let r=e.get(n);r&&(t.audio.codecMimeType=r.mimeType)}if(i){let r=e.get(i);r&&(t.video.codecMimeType=r.mimeType)}return t}computeMetrics(e,t,n){let i=(e.timestamp-t.timestamp)/1e3,r=e.audio.packetsReceived-t.audio.packetsReceived,o=e.audio.packetsLost-t.audio.packetsLost,a=r+o,l=a>0?o/a*100:0,c=i>0?(e.audio.bytesReceived-t.audio.bytesReceived)*8/i/1e3:0,u=e.video.packetsReceived-t.video.packetsReceived,w=e.video.packetsLost-t.video.packetsLost,v=u+w,C=v>0?w/v*100:0,k=i>0?(e.video.bytesReceived-t.video.bytesReceived)*8/i/1e3:0,U=e.connection.currentRoundTripTime*1e3,H=Sr({packetLoss:l,bitrate:c*1e3,roundTripTime:U,bufferDelay:e.audio.jitter*1e3}),A=n.expectedFrameRate??30,Tr=e.video.codecMimeType?.toLowerCase()??"",Er=[["vp9","vp9"],["vp8","vp8"],["h264","h264"],["avc","h264"],["h265","h265"],["hevc","h265"],["av1","av1"]].find(([Rr])=>Tr.includes(Rr))?.[1],Fs=br({bitrate:k*1e3,roundTripTime:U,width:e.video.frameWidth,height:e.video.frameHeight,frameRate:e.video.framesPerSecond,expectedFrameRate:A,codec:Er}),As=Math.min(H,Fs),De;return As>=eo?De="Good":As>=to?De="Fair":De="Poor",{audioPacketLossPercent:Math.round(l*100)/100,videoPacketLossPercent:Math.round(C*100)/100,audioBitrateKbps:Math.round(c),videoBitrateKbps:Math.round(k),frameRate:e.video.framesPerSecond,audioJitterMs:Math.round(e.audio.jitter*1e3*100)/100,videoJitterMs:Math.round(e.video.jitter*1e3*100)/100,roundTripTimeMs:Math.round(U*100)/100,audioMos:H,videoMos:Fs,qualityLevel:De}}getInboundAudioStats(e){let t=null;return e.forEach(n=>{n.type==="inbound-rtp"&&n.kind==="audio"&&(t=n)}),t}getCodecFromStats(e,t){let n;return e.forEach(i=>{i.type==="codec"&&i.id===t&&(n=i)}),n}logAudioStats(e,t){let{packetsReceived:n,packetsLost:i,bytesReceived:r,jitter:o,audioLevel:a}=e;p.info(`WebRTC Connection - Audio -
|
|
81
|
+
`}),t}}}isRunning(){return!!this.intervalHandle}receive(e){if(!this.isRunning())return;if(!e){d.Error("Undefined response from server");return}let t=this.records.get(e.Seq);t&&t.update(e)}sendRequest(e,t){let n=this.createRequest(e,t),i=new Cn(n);this.records.set(i.seq,i),this.sink(n)}createRequest(e,t){return{Seq:this.seq++,FillResponseSize:t,Filler:e?"A".repeat(e):""}}};var xe=class{constructor(e,t){this.allowConsoleCommands=!1,this.config=e,t?.videoElementParent&&(this._videoElementParent=t.videoElementParent),this._eventEmitter=new $t,this.configureSettings(),this.setWebRtcPlayerController(new bn(this.config,this)),this._webXrController=new wn(this._webRtcController),this._setupWebRtcTCPRelayDetection=this._setupWebRtcTCPRelayDetection.bind(this),this._eventEmitter.addEventListener("webRtcConnected",n=>{this._eventEmitter.addEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)})}get videoElementParent(){return this._videoElementParent||(this._videoElementParent=document.createElement("div"),this._videoElementParent.id="videoElementParent"),this._videoElementParent}configureSettings(){this.config._addOnSettingChangedListener(h.IsQualityController,e=>{e===!0&&!this._webRtcController.isQualityController&&this._webRtcController.sendRequestQualityControlOwnership()}),this.config._addOnSettingChangedListener(h.AFKDetection,e=>{this._webRtcController.setAfkEnabled(e)}),this.config._addOnSettingChangedListener(h.MatchViewportResolution,()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()}),this.config._addOnSettingChangedListener(h.HoveringMouseMode,e=>{this.config.setFlagLabel(h.HoveringMouseMode,`Control Scheme: ${e?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(h.MouseInput))}),this.config._addOnSettingChangedListener(h.KeyboardInput,e=>{this._webRtcController.setKeyboardInputEnabled(e)}),this.config._addOnSettingChangedListener(h.MouseInput,e=>{this._webRtcController.setMouseInputEnabled(e)}),this.config._addOnSettingChangedListener(h.FakeMouseWithTouches,e=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(h.TouchInput))}),this.config._addOnSettingChangedListener(h.TouchInput,e=>{this._webRtcController.setTouchInputEnabled(e)}),this.config._addOnSettingChangedListener(h.GamepadInput,e=>{this._webRtcController.setGamePadInputEnabled(e)}),this.config._addOnNumericSettingChangedListener(m.MinQP,e=>{d.Info("-------- Sending MinQP --------"),this._webRtcController.sendEncoderMinQP(e),d.Info("-------------------------------------------");let t=Math.trunc(100*(1-e/51));this.config.setNumericSetting(m.CompatQualityMax,t)}),this.config._addOnNumericSettingChangedListener(m.MaxQP,e=>{d.Info("-------- Sending MaxQP --------"),this._webRtcController.sendEncoderMaxQP(e),d.Info("-------------------------------------------");let t=Math.trunc(100*(1-e/51));this.config.setNumericSetting(m.CompatQualityMin,t)}),this.config._addOnNumericSettingChangedListener(m.MinQuality,e=>{d.Info("-------- Sending MinQuality --------"),this._webRtcController.sendEncoderMinQuality(e),d.Info("-------------------------------------------"),this.config.setNumericSetting(m.CompatQualityMin,e)}),this.config._addOnNumericSettingChangedListener(m.MaxQuality,e=>{d.Info("-------- Sending MaxQuality --------"),this._webRtcController.sendEncoderMaxQuality(e),d.Info("-------------------------------------------"),this.config.setNumericSetting(m.CompatQualityMax,e)}),this.config._addOnNumericSettingChangedListener(m.CompatQualityMin,e=>{e=51-e/100*51,d.Info("-------- Sending MinQP from quality value --------"),this._webRtcController.sendEncoderMaxQP(e),d.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(m.CompatQualityMax,e=>{e=51-e/100*51,d.Info("-------- Sending MaxQP from quality value --------"),this._webRtcController.sendEncoderMinQP(e),d.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(m.WebRTCMinBitrate,e=>{d.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCMinBitrate(e*1e3),d.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(m.WebRTCMaxBitrate,e=>{d.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCMaxBitrate(e*1e3),d.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(m.WebRTCFPS,e=>{d.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCFps(e),d.Info("-------------------------------------------")}),this.config._addOnOptionSettingChangedListener(M.PreferredCodec,e=>{this._webRtcController&&this._webRtcController.setPreferredCodec(e)}),this.config._registerOnChangeEvents(this._eventEmitter)}_onInputControlOwnership(e){this._inputController=e}setWebRtcPlayerController(e){this._webRtcController=e,this._webRtcController.setPreferredCodec(this.config.getSettingOption(M.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Mt),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Et),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Tt),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(h.AutoConnect)&&(this._onWebRtcAutoConnect(),this._webRtcController.connectToSignallingServer())}unmuteMicrophone(e=!1){if(this.config.isFlagEnabled("UseMic")){this.setMicrophoneMuted(!1);return}if(e){this.config.setFlagEnabled("UseMic",!0),this.reconnect();return}d.Warning("Trying to unmute mic, but PixelStreaming was initialized with no microphone track. Call with forceEnable == true to re-connect with a mic track.")}muteMicrophone(){if(this.config.isFlagEnabled("UseMic")){this.setMicrophoneMuted(!0);return}d.Info("Trying to mute mic, but PixelStreaming has no microphone track, so sending sound is already disabled.")}setMicrophoneMuted(e){var t,n,i,r;for(let o of(r=(i=(n=(t=this._webRtcController)===null||t===void 0?void 0:t.peerConnectionController)===null||n===void 0?void 0:n.peerConnection)===null||i===void 0?void 0:i.getTransceivers())!==null&&r!==void 0?r:[])Z.canTransceiverSendAudio(o)&&(o.sender.track.enabled=!e)}unmuteCamera(e=!1){if(this.config.isFlagEnabled("UseCamera")){this.setCameraMuted(!1);return}if(e){this.config.setFlagEnabled("UseCamera",!0),this.reconnect();return}d.Warning("Trying to unmute video, but PixelStreaming was initialized with no video track. Call with forceEnable == true to re-connect with a video track.")}muteCamera(){if(this.config.isFlagEnabled("UseCamera")){this.setCameraMuted(!0);return}d.Info("Trying to mute camera, but PixelStreaming has no video track, so sending video is already disabled.")}setCameraMuted(e){var t,n,i,r;for(let o of(r=(i=(n=(t=this._webRtcController)===null||t===void 0?void 0:t.peerConnectionController)===null||n===void 0?void 0:n.peerConnection)===null||i===void 0?void 0:i.getTransceivers())!==null&&r!==void 0?r:[])Z.canTransceiverSendVideo(o)&&(o.sender.track.enabled=!e)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new pt)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new dt)}_onWebRtcSdpOffer(e){this._eventEmitter.dispatchEvent(new ut({sdp:e}))}_onWebRtcSdpAnswer(e){this._eventEmitter.dispatchEvent(new ht({sdp:e}))}_onLatencyCalculated(e){this._eventEmitter.dispatchEvent(new Ft({latencyInfo:e}))}_onStreamLoading(){this._eventEmitter.dispatchEvent(new Ct)}_onDisconnect(e,t){this._eventEmitter.dispatchEvent(new yt({eventString:e,allowClickToReconnect:t}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new mt)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new ft)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new gt)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new wt),this._videoStartTime=Date.now()}_onLatencyTestResult(e){this._eventEmitter.dispatchEvent(new Ot({latencyTimings:e}))}_onDataChannelLatencyTestResponse(e){this._eventEmitter.dispatchEvent(new Nt({response:e}))}_onVideoStats(e){(!this._videoStartTime||this._videoStartTime===void 0)&&(this._videoStartTime=Date.now()),e.handleSessionStatistics(this._videoStartTime,this._inputController,this._webRtcController.videoAvgQp),this._eventEmitter.dispatchEvent(new Pt({aggregatedStats:e}))}_onVideoEncoderAvgQP(e){this._eventEmitter.dispatchEvent(new ct({avgQP:e}))}_onInitialSettings(e){var t;this._eventEmitter.dispatchEvent(new Vt({settings:e})),e.PixelStreamingSettings&&(this.allowConsoleCommands=(t=e.PixelStreamingSettings.AllowPixelStreamingCommands)!==null&&t!==void 0?t:!1,this.allowConsoleCommands===!1&&d.Info("-AllowPixelStreamingCommands=false, sending arbitrary console commands from browser to UE is disabled."));let n=this.config.useUrlParams,i=new ue(window.location.search);d.Info(`using URL parameters ${n}`),e.EncoderSettings&&(e.EncoderSettings.MinQP&&(this.config.setNumericSetting(m.MinQP,n&&i.has(m.MinQP)?Number.parseFloat(i.get(m.MinQP)):e.EncoderSettings.MinQP||0),this.config.setNumericSetting(m.MaxQP,n&&i.has(m.MaxQP)?Number.parseFloat(i.get(m.MaxQP)):e.EncoderSettings.MaxQP||51)),e.EncoderSettings.MinQuality&&(this.config.setNumericSetting(m.MinQuality,n&&i.has(m.MinQuality)?Number.parseFloat(i.get(m.MinQuality)):e.EncoderSettings.MinQuality||0),this.config.setNumericSetting(m.MaxQuality,n&&i.has(m.MaxQuality)?Number.parseFloat(i.get(m.MaxQuality)):e.EncoderSettings.MaxQuality||100)),n&&(i.has(m.CompatQualityMin)&&this.config.setNumericSetting(m.CompatQualityMin,Number.parseFloat(i.get(m.CompatQualityMin))),i.has(m.CompatQualityMax)&&this.config.setNumericSetting(m.CompatQualityMax,Number.parseFloat(i.get(m.CompatQualityMax))))),e.WebRTCSettings&&(this.config.setNumericSetting(m.WebRTCMinBitrate,n&&i.has(m.WebRTCMinBitrate)?Number.parseFloat(i.get(m.WebRTCMinBitrate)):e.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(m.WebRTCMaxBitrate,n&&i.has(m.WebRTCMaxBitrate)?Number.parseFloat(i.get(m.WebRTCMaxBitrate)):e.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(m.WebRTCFPS,n&&i.has(m.WebRTCFPS)?Number.parseFloat(i.get(m.WebRTCFPS)):e.WebRTCSettings.FPS))}_onQualityControlOwnership(e){this.config.setFlagEnabled(h.IsQualityController,e)}_onPlayerCount(e){this._eventEmitter.dispatchEvent(new Wt({count:e}))}_onSubscribeFailed(e){this._eventEmitter.dispatchEvent(new Bt({message:e}))}_setupWebRtcTCPRelayDetection(e){let t=e.data.aggregatedStats.getActiveCandidatePair();if(t!=null){let n=e.data.aggregatedStats.localCandidates.find(i=>i.id==t.localCandidateId,null);n!=null&&n.candidateType=="relay"&&n.relayProtocol=="tcp"&&this._eventEmitter.dispatchEvent(new Ht),this._eventEmitter.removeEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}}requestLatencyTest(){return this._webRtcController.videoPlayer.isVideoReady()?(this._webRtcController.sendLatencyTest(),!0):!1}requestDataChannelLatencyTest(e){return this._webRtcController.videoPlayer.isVideoReady()?(this._dataChannelLatencyTestController||(this._dataChannelLatencyTestController=new Mn(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),t=>{this._eventEmitter.dispatchEvent(new Ut({result:t}))}),this.addEventListener("dataChannelLatencyTestResponse",({data:{response:t}})=>{this._dataChannelLatencyTestController.receive(t)})),this._dataChannelLatencyTestController.start(e)):!1}requestShowFps(){return this._webRtcController.videoPlayer.isVideoReady()?(this._webRtcController.sendShowFps(),!0):!1}requestIframe(){return this._webRtcController.videoPlayer.isVideoReady()?(this._webRtcController.sendIframeRequest(),!0):!1}emitUIInteraction(e){return this._webRtcController.videoPlayer.isVideoReady()?(this._webRtcController.emitUIInteraction(e),!0):!1}emitCommand(e){return!this._webRtcController.videoPlayer.isVideoReady()||!this.allowConsoleCommands&&"ConsoleCommand"in e?!1:(this._webRtcController.emitCommand(e),!0)}emitConsoleCommand(e){return!this.allowConsoleCommands||!this._webRtcController.videoPlayer.isVideoReady()?!1:(this._webRtcController.emitConsoleCommand(e),!0)}sendTextboxEntry(e){return this._webRtcController.videoPlayer.isVideoReady()?(this._webRtcController.sendTextboxEntry(e),!0):!1}addResponseEventListener(e,t){this._webRtcController.responseController.addResponseEventListener(e,t)}removeResponseEventListener(e){this._webRtcController.responseController.removeResponseEventListener(e)}dispatchEvent(e){return this._eventEmitter.dispatchEvent(e)}addEventListener(e,t){this._eventEmitter.addEventListener(e,t)}removeEventListener(e,t){this._eventEmitter.removeEventListener(e,t)}toggleXR(){this.webXrController.xrClicked()}setSignallingUrlBuilder(e){this._webRtcController.signallingUrlBuilder=e}get webRtcController(){return this._webRtcController}get signallingProtocol(){return this._webRtcController.protocol}get webXrController(){return this._webXrController}registerMessageHandler(e,t,n){if(t===S.FromStreamer&&typeof n>"u"){d.Warning(`Unable to register an undefined handler for ${e}`);return}t===S.ToStreamer&&typeof n>"u"?this._webRtcController.streamMessageController.registerMessageHandler(t,e,i=>this._webRtcController.sendMessageController.sendMessageToStreamer(e,i)):this._webRtcController.streamMessageController.registerMessageHandler(t,e,i=>n(i))}get toStreamerHandlers(){return this._webRtcController.streamMessageController.toStreamerHandlers}isReconnecting(){return this._webRtcController.isReconnecting}};var Tn=class{type=0},En=class{type=1},Rn=class{constructor(e){this.msg=e}msg;type=2};var kn=class{constructor(e){this.stats=e}stats;type=5};var Is="3.16.2";var ur="sessionEndedDueToInactivity",pr="sessionEndedByUser",Ps="sessionEndedDueToConnectionLoss",Ls="sessionEndedDueToVideoPlaybackError",mr="sessionEndedDueToPermissionsError";var Ds="sessionEndedDueToRendererError";var fr=(n=>(n.Good="Good",n.Fair="Fair",n.Poor="Poor",n))(fr||{}),gr=(n=>(n.Always="always",n.WhenDegraded="when-degraded",n.Hidden="hidden",n))(gr||{}),yr=(i=>(i.TopLeft="top-left",i.TopRight="top-right",i.BottomLeft="bottom-left",i.BottomRight="bottom-right",i))(yr||{}),Sr=(n=>(n.Click="click",n.Hover="hover",n.None="none",n))(Sr||{});function Ie(s,e,t){return Math.max(e,Math.min(s,t))}function br(s){let e=s.packetLoss??0,t=s.bufferDelay??50,n=s.roundTripTime??50,i=s.fec??!0,r=s.dtx??!1,o=s.bitrate,a=20+t+n/2,l=100,c=r?8:o?Ie(55-4.6*Math.log(o),0,30):6,u=i?20:10,w=c+(100-c)*(e/(e+u)),v=a*.03+(a>150?.1*(a-150):0),C=Ie(l-w-v,0,100),k=1+.035*C+C*(C-60)*(100-C)*7/1e6;return Ie(Math.round(k*100)/100,1,5)}function vr(s){let e=s.bitrate??0,t=s.roundTripTime??50,n=s.bufferDelay??0,i=s.width||640,r=s.height||480,o=s.frameRate??0,a=s.expectedFrameRate??30,l=s.codec?.toLowerCase();if(o===0)return 1;let c=i*r,u=l==="vp9"?1.2:1,w=n+t/2,v=u*e/c/o,k=Ie(.56*Math.log(v)+5.36,1,5)-1.9*Math.log(a/o)-w*.002;return Ie(Math.round(k*100)/100,1,5)}function xn(s){let e=s?.srcObject;return!!e&&typeof e.getAudioTracks=="function"&&e.getAudioTracks().length>0}var to=3.5,no=2.5,pe=class{constructor(e,t,n){this.stream=e;this.videoElement=t;this.audioElement=n}stream;videoElement;audioElement;previousStats;getPeerConnection(){return this.stream?.webRtcController?.peerConnectionController?.peerConnection}async analyzeAudioStats(){let e=this.getPeerConnection();if(!e){p.error("Stream appears to be down, RTCPeerConnection is not defined");return}let t=await e.getStats(null),n=this.getInboundAudioStats(t);if(!n){p.warn("WebRTC Connection - No inbound audio RTP stats found.");return}let i=n.codecId,r=i?this.getCodecFromStats(t,i):void 0;this.logAudioStats(n,r),this.logElementStatus(r)}async collectNetworkQuality(e){let t=this.getPeerConnection();if(!t)return p.warn("Cannot collect network quality: RTCPeerConnection is not defined"),null;let n=await t.getStats(null),i=this.extractRawStats(n);if(!this.previousStats)return this.previousStats=i,null;let r=this.computeMetrics(i,this.previousStats,e);return this.previousStats=i,r}resetStats(){this.previousStats=void 0}extractRawStats(e){let t={timestamp:Date.now(),audio:{packetsReceived:0,packetsLost:0,bytesReceived:0,jitter:0},video:{packetsReceived:0,packetsLost:0,bytesReceived:0,framesDecoded:0,framesDropped:0,frameWidth:0,frameHeight:0,framesPerSecond:0,jitter:0},connection:{currentRoundTripTime:0}},n,i;if(e.forEach(r=>{r.type==="inbound-rtp"&&r.kind==="audio"?(t.audio.packetsReceived=r.packetsReceived??0,t.audio.packetsLost=r.packetsLost??0,t.audio.bytesReceived=r.bytesReceived??0,t.audio.jitter=r.jitter??0,n=r.codecId):r.type==="inbound-rtp"&&r.kind==="video"?(t.video.packetsReceived=r.packetsReceived??0,t.video.packetsLost=r.packetsLost??0,t.video.bytesReceived=r.bytesReceived??0,t.video.framesDecoded=r.framesDecoded??0,t.video.framesDropped=r.framesDropped??0,t.video.frameWidth=r.frameWidth??0,t.video.frameHeight=r.frameHeight??0,t.video.framesPerSecond=r.framesPerSecond??0,t.video.jitter=r.jitter??0,i=r.codecId):r.type==="candidate-pair"&&r.nominated&&(t.connection.currentRoundTripTime=r.currentRoundTripTime??0)}),n){let r=e.get(n);r&&(t.audio.codecMimeType=r.mimeType)}if(i){let r=e.get(i);r&&(t.video.codecMimeType=r.mimeType)}return t}computeMetrics(e,t,n){let i=(e.timestamp-t.timestamp)/1e3,r=e.audio.packetsReceived-t.audio.packetsReceived,o=e.audio.packetsLost-t.audio.packetsLost,a=r+o,l=a>0?o/a*100:0,c=i>0?(e.audio.bytesReceived-t.audio.bytesReceived)*8/i/1e3:0,u=e.video.packetsReceived-t.video.packetsReceived,w=e.video.packetsLost-t.video.packetsLost,v=u+w,C=v>0?w/v*100:0,k=i>0?(e.video.bytesReceived-t.video.bytesReceived)*8/i/1e3:0,U=e.connection.currentRoundTripTime*1e3,H=br({packetLoss:l,bitrate:c*1e3,roundTripTime:U,bufferDelay:e.audio.jitter*1e3}),A=n.expectedFrameRate??30,Er=e.video.codecMimeType?.toLowerCase()??"",Rr=[["vp9","vp9"],["vp8","vp8"],["h264","h264"],["avc","h264"],["h265","h265"],["hevc","h265"],["av1","av1"]].find(([kr])=>Er.includes(kr))?.[1],As=vr({bitrate:k*1e3,roundTripTime:U,width:e.video.frameWidth,height:e.video.frameHeight,frameRate:e.video.framesPerSecond,expectedFrameRate:A,codec:Rr}),Ns=Math.min(H,As),De;return Ns>=to?De="Good":Ns>=no?De="Fair":De="Poor",{audioPacketLossPercent:Math.round(l*100)/100,videoPacketLossPercent:Math.round(C*100)/100,audioBitrateKbps:Math.round(c),videoBitrateKbps:Math.round(k),frameRate:e.video.framesPerSecond,audioJitterMs:Math.round(e.audio.jitter*1e3*100)/100,videoJitterMs:Math.round(e.video.jitter*1e3*100)/100,roundTripTimeMs:Math.round(U*100)/100,audioMos:H,videoMos:As,qualityLevel:De}}getInboundAudioStats(e){let t=null;return e.forEach(n=>{n.type==="inbound-rtp"&&n.kind==="audio"&&(t=n)}),t}getCodecFromStats(e,t){let n;return e.forEach(i=>{i.type==="codec"&&i.id===t&&(n=i)}),n}logAudioStats(e,t){let{packetsReceived:n,packetsLost:i,bytesReceived:r,jitter:o,audioLevel:a}=e;p.info(`WebRTC Connection - Audio -
|
|
82
82
|
Codec: ${t?t.mimeType+" ("+t.payloadType+")":"Unknown"},
|
|
83
83
|
Packets received: ${n},
|
|
84
84
|
Packets lost: ${i},
|
|
85
85
|
Bytes received: ${r},
|
|
86
86
|
Jitter: ${o},
|
|
87
|
-
Audio level (0-1): ${a??"N/A"}`),n===0&&p.warn("WebRTC Connection - Audio - No audio packets received \u2014 remote is probably not sending audio."),i>0&&p.warn(`WebRTC Connection - Audio - packet loss detected: ${i} packets lost.`),a===void 0?p.warn("WebRTC Connection - Audio - Audio level not available in stats."):a===0?p.warn("WebRTC Connection - Audio - Audio level is zero \u2014 digital human might not be talking at this exact moment as audio is silent or muted."):a<.02?p.warn("WebRTC Connection - Audio - Audio level is very low \u2014 audio might be too quiet."):p.info("WebRTC Connection - Audio - Audio level looks normal, digital human is likely speaking.")}logElementStatus(e){let t=xn(this.videoElement),n=t?this.videoElement:this.audioElement;p.debug(`Audio plays from ${t?"video":"separate audio"} element (DisableAudioSync=${t?"false":"true"}).`),p.debug(`Video element muted: ${this.videoElement?.muted}, (should be ${t?"false to be able to hear the digital human":"true as part of avoiding auto play restrictions"})`),p.debug(`Playback element muted: ${n?.muted}, (should be false to be able to hear the digital human)`),p.debug(`Playback element volume: ${n?.volume}, (should be greater than zero to be able to hear the digital human)`);let i=e?.mimeType;i&&n&&(p.debug(`Playback element can play webrtc audio codec (${i}) : ${n.canPlayType(i)}, (should be 'probably' or 'maybe)'`),i==="audio/opus"&&p.debug(`Audio codec opus is often known as ogg, so checking can play ogg codec: ${n.canPlayType("audio/ogg")}, (should be 'probably' or 'maybe')`))}};var Pe={good:"#22c55e",fair:"#eab308",poor:"#ef4444",inactive:"#6b7280"},In=class{constructor(e,t){this.videoContainerElement=e;this.visibility=t.visibility??"when-degraded",this.position=t.position??"top-right",this.popupTrigger=t.popupTrigger??"click",this.onClickBound=this.onClick.bind(this),this.onMouseEventBound=n=>n.stopPropagation(),this.onDocumentClickBound=this.onDocumentClick.bind(this),this.onMouseEnterBound=this.onMouseEnter.bind(this),this.onMouseLeaveBound=this.onMouseLeave.bind(this),this.visibility!=="hidden"&&this.createElements()}videoContainerElement;container;panel;bars=[];panelVisible=!1;lastMetrics;visibility;position;popupTrigger;onClickBound;onMouseEventBound;onDocumentClickBound;onMouseEnterBound;onMouseLeaveBound;hoverHideTimeout;originalParentPosition;createElements(){getComputedStyle(this.videoContainerElement).position==="static"&&(this.originalParentPosition=this.videoContainerElement.style.position,this.videoContainerElement.style.position="relative"),this.container=document.createElement("div"),this.container.setAttribute("data-testid","network-indicator"),this.container.setAttribute("role","status"),this.container.setAttribute("aria-live","polite"),this.container.setAttribute("aria-label","Network quality: unknown"),Object.assign(this.container.style,{position:"absolute",zIndex:"1000",cursor:"pointer",padding:"6px 7px",borderRadius:"4px",background:"rgba(0, 0, 0, 0.5)",display:"none",alignItems:"flex-end",gap:"2px",pointerEvents:"auto",...this.getPositionStyles()});let t=[6,12,18];for(let n of t){let i=document.createElement("div");i.setAttribute("data-testid","network-indicator-bar"),Object.assign(i.style,{width:"4px",height:`${n}px`,borderRadius:"1px",background:Pe.inactive,transition:"background 0.3s ease"}),this.bars.push(i),this.container.appendChild(i)}this.container.addEventListener("mousedown",this.onMouseEventBound),this.container.addEventListener("mouseup",this.onMouseEventBound),this.popupTrigger==="click"?this.container.addEventListener("click",this.onClickBound):this.popupTrigger==="hover"&&(this.container.addEventListener("mouseenter",this.onMouseEnterBound),this.container.addEventListener("mouseleave",this.onMouseLeaveBound)),this.popupTrigger==="none"&&(this.container.style.cursor="default"),this.videoContainerElement.appendChild(this.container)}getPositionStyles(){switch(this.position){case"top-left":return{top:"8px",left:"8px"};case"top-right":return{top:"8px",right:"8px"};case"bottom-left":return{bottom:"8px",left:"8px"};case"bottom-right":return{bottom:"8px",right:"8px"};default:return{top:"8px",right:"8px"}}}onClick(e){e.stopPropagation(),this.panelVisible?this.hidePanel():this.showPanel()}onDocumentClick(e){this.panelVisible&&this.container&&!this.container.contains(e.target)&&this.hidePanel()}onMouseEnter(){clearTimeout(this.hoverHideTimeout),this.showPanel()}onMouseLeave(){this.scheduleHoverHide()}scheduleHoverHide(){clearTimeout(this.hoverHideTimeout),this.hoverHideTimeout=setTimeout(()=>this.hidePanel(),50)}showPanel(){!this.container||!this.lastMetrics||(this.panel||(this.panel=document.createElement("div"),this.panel.setAttribute("data-testid","network-indicator-panel"),Object.assign(this.panel.style,{position:"fixed",padding:"10px",borderRadius:"6px",background:"rgba(0, 0, 0, 0.85)",color:"#ffffff",fontSize:"11px",fontFamily:"system-ui, -apple-system, sans-serif",whiteSpace:"nowrap",lineHeight:"1.6",minWidth:"180px",zIndex:"10001",pointerEvents:"auto"}),this.popupTrigger==="hover"&&(this.panel.addEventListener("mouseenter",this.onMouseEnterBound),this.panel.addEventListener("mouseleave",this.onMouseLeaveBound)),document.body.appendChild(this.panel)),this.updatePanel(),this.positionPanel(),this.panel.style.display="block",this.panelVisible=!0,document.addEventListener("click",this.onDocumentClickBound))}hidePanel(){this.panel&&(this.panel.style.display="none"),this.panelVisible=!1,document.removeEventListener("click",this.onDocumentClickBound)}positionPanel(){if(!this.panel||!this.container)return;let e=4,t=4,n=window.innerWidth,i=window.innerHeight,r=this.container.getBoundingClientRect(),o={top:Math.max(0,Math.min(r.top,i)),bottom:Math.max(0,Math.min(r.bottom,i)),left:Math.max(0,Math.min(r.left,n)),right:Math.max(0,Math.min(r.right,n))};this.panel.style.top="",this.panel.style.bottom="",this.panel.style.left="",this.panel.style.right="",this.panel.style.visibility="hidden",this.panel.style.display="block";let{width:a,height:l}=this.panel.getBoundingClientRect();this.panel.style.visibility="";let c=o.top-e,u=i-o.bottom-e,w=o.left-e,v=n-o.right-e,C,k;c>=l||u>=l?(C=u>=l&&(c<l||u>=c)?o.bottom+e:o.top-e-l,k=this.position==="top-left"||this.position==="bottom-left"?o.left:o.right-a):(k=v>=a&&(w<a||v>=w)?o.right+e:o.left-e-a,C=o.bottom-l),k=Math.max(t,Math.min(k,n-a-t)),C=Math.max(0,Math.min(C,i-l-t)),this.panel.style.top=`${C}px`,this.panel.style.left=`${k}px`}updatePanel(){if(!this.panel||!this.lastMetrics)return;let e=this.lastMetrics,t=this.getColor(e.qualityLevel);this.panel.innerHTML=[`<div style="font-weight:600;margin-bottom:4px;color:${t}">${e.qualityLevel} Quality</div>`,this.panelSectionHeader("Quality Score (MOS)"),this.panelRow("Audio",e.audioMos.toFixed(1)+" / 5.0"),this.panelRow("Video",e.videoMos.toFixed(1)+" / 5.0"),this.panelSectionHeader("Connection"),this.panelRow("Round Trip",`${e.roundTripTimeMs} ms`),this.panelRow("Packet Loss",`${e.audioPacketLossPercent}% audio / ${e.videoPacketLossPercent}% video`),this.panelRow("Jitter",`${e.audioJitterMs} ms audio / ${e.videoJitterMs} ms video`),this.panelSectionHeader("Throughput"),this.panelRow("Bitrate",`${e.audioBitrateKbps} audio / ${e.videoBitrateKbps} video kbps`),this.panelRow("Frame Rate",`${e.frameRate} fps`)].join("")}panelSectionHeader(e){return`<div style="color:#6b7280;font-size:10px;text-transform:uppercase;letter-spacing:0.5px;margin-top:6px;margin-bottom:2px">${e}</div>`}panelRow(e,t){return`<div style="display:flex;justify-content:space-between;gap:12px"><span style="color:#9ca3af">${e}</span><span>${t}</span></div>`}getColor(e){switch(e){case"Good":return Pe.good;case"Fair":return Pe.fair;case"Poor":return Pe.poor}}update(e){if(this.lastMetrics=e,!this.container)return;this.container.setAttribute("aria-label",`Network quality: ${e.qualityLevel}`);let t=this.getColor(e.qualityLevel),n=e.qualityLevel==="Good"?3:e.qualityLevel==="Fair"?2:1;this.bars.forEach((i,r)=>{i.style.background=r<n?t:Pe.inactive}),this.visibility==="when-degraded"?this.container.style.display=e.qualityLevel==="Good"?"none":"flex":this.container.style.display="flex",this.panelVisible&&(this.updatePanel(),this.positionPanel())}destroy(){this.container&&(this.container.removeEventListener("click",this.onClickBound),this.container.removeEventListener("mousedown",this.onMouseEventBound),this.container.removeEventListener("mouseup",this.onMouseEventBound),this.container.removeEventListener("mouseenter",this.onMouseEnterBound),this.container.removeEventListener("mouseleave",this.onMouseLeaveBound),this.container.remove(),this.container=void 0),this.originalParentPosition!==void 0&&(this.videoContainerElement.style.position=this.originalParentPosition,this.originalParentPosition=void 0),clearTimeout(this.hoverHideTimeout),this.panel&&(this.panel.removeEventListener("mouseenter",this.onMouseEnterBound),this.panel.removeEventListener("mouseleave",this.onMouseLeaveBound),this.panel.remove(),this.panel=void 0),document.removeEventListener("click",this.onDocumentClickBound),this.bars=[],this.panelVisible=!1,this.lastMetrics=void 0}};var Pn=class{constructor(e,t,n){this.session=e;this.connectionUrl=t;this.videoContainerElement=n;this.config=e.config,this.clientMessages=e.messages,this._audioUpstreamMode=G(this.config.audioUpstreamMode)}session;connectionUrl;videoContainerElement;stream;messages=new no;videoElement;audioElement;videoInitialized=!1;dataChannelOpen=!1;sceneReady=!1;maxReconnectAttempts=4;reconnectionAttempts=0;allowReconnection=!0;reconnectTimeoutId;baseReconnectDelayMs=500;maxReconnectDelayMs=1e4;audioStatsInternal;freezeCount=0;lastDecodedFrames=0;lastCheckTime=Date.now();audioStatsAnalyzer;networkQualityInterval;networkIndicator;config;clientMessages;_audioUpstreamMode;get audioUpstreamMode(){return this._audioUpstreamMode}init(){p.info("Connection config",{connectionUrl:this.connectionUrl,forceTURN:this.config.forceTURN}),this.videoContainerElement||(this.videoContainerElement=document.createElement("div"),document.body.appendChild(this.videoContainerElement)),this.clientMessages?.next(new si);let e=re(this.audioUpstreamMode);this.audioUpstreamMode!=="speech-recognition-service"&&p.info(`audioUpstreamMode='${this.audioUpstreamMode}' is beta; behaviour may change.`);let t=new zt({initialSettings:{AutoConnect:!1,AutoPlayVideo:!1,ForceTURN:this.config.forceTURN,HoveringMouse:!1,KeyboardInput:!1,MaxReconnectAttempts:0,MouseInput:!1,ss:this.connectionUrl,StartVideoMuted:!0,TouchInput:!1,UseMic:e,WaitForStreamer:!0}});this.stream=new xe(t,{videoElementParent:this.videoContainerElement}),d.InitLogging(K.Warning,!1);let n=function(){let i=t.getTextSettingValue($.SignallingServerUrl);return t.isFlagEnabled(h.BrowserSendOffer)&&(i+=(i.includes("?")?"&":"?")+h.BrowserSendOffer+"=true"),i};this.stream.setSignallingUrlBuilder(n),this.addStreamHandlers(),this.stream.connect(),this.addWebSocketHandlers()}addStreamHandlers(){this.stream?.addEventListener("videoInitialized",this.handleVideoInitialized.bind(this)),this.stream?.addEventListener("dataChannelOpen",this.handleDataChannelOpen.bind(this)),this.stream?.addEventListener("webRtcFailed",this.handleWebRtcFailed.bind(this)),this.stream?.addEventListener("webRtcDisconnected",this.handleWebRtcDisconnected.bind(this)),this.stream?.addEventListener("statsReceived",this.handleWebRtcStats.bind(this)),this.stream?.addResponseEventListener("response-listener",this.handleDataChannelMessage.bind(this)),this.stream?.addEventListener("videoEncoderAvgQP",({data:{avgQP:e}})=>{p.trace("WebRTC: VideoEncoderAvgQP - lower is better, ranges from 0 to 51:",e)}),this.stream?.addEventListener("webRtcAutoConnect",()=>{p.debug("WebRTC: AutoConnect triggered")}),this.stream?.addEventListener("webRtcConnected",this.handleWebRtcConnectedMessage.bind(this)),this.stream?.addEventListener("statsReceived",({data:{aggregatedStats:e}})=>{p.trace("WebRTC: StatsReceived",e)}),this.stream?.addEventListener("webRtcTCPRelayDetected",()=>{p.warn("WebRTC: Stream quailty likely degraded due to network enviroment, stream is relayed over TCP.")})}addWebSocketHandlers(){this.stream?.signallingProtocol?.transport?.webSocket?.addEventListener("error",this.handleWebSocketError.bind(this)),this.stream?.signallingProtocol.on("error",t=>{p.error("Signaling: Received error message from server",t),this.clientMessages?.next(new q(`Signaling server error: ${t}`))}),this.stream?.signallingProtocol.on("index_in_queue",this.handleIndexInQueueMessage.bind(this)),this.stream?.signallingProtocol.on("renderer_taken",this.handleRendererTakenMessage.bind(this)),this.stream?.signallingProtocol.on("renderer_gone",this.handleRendererGoneEvent.bind(this)),this.stream?.signallingProtocol.on("switch_renderer_request",this.handleSwitchRendererRequestEvent.bind(this)),this.stream?.signallingProtocol.on("customer_concurrency_limit_reached",this.handleCustomerConcurrencyLimitReachedMessage.bind(this)),this.stream?.signallingProtocol.on("renderer_error",this.handleRendererErrorMessage.bind(this)),this.stream?.signallingProtocol.on("config",this.checkForStubbedTurnConfig.bind(this))}checkForStubbedTurnConfig(e){let t=e?.peerConnectionOptions?.iceServers??[];p.info("Signaling: Received ice config message with urls:",t.map(i=>({urls:i.urls}))),t.some(i=>i.username?.includes("disabled")&&i.urls?.some(r=>r.includes("0.0.0.0")))&&p.warn("Signaling: TURN server configuration is stubbed (turn:0.0.0.0 with disabled credentials). This should be intentional, is intended for locally run renderers e.g. kiosk, miniprem etc.")}handleWebSocketError(e){p.error("Signaling: WebSocket error",p.serialiseError(e)),this.reconnectIfSafe(e)}handleVideoInitialized(){p.info("Video initialized."),this.videoElement=this.videoContainerElement?.getElementsByTagName("video")[0],this.audioElement=this.stream?.webRtcController?.streamController?.audioElement,this.audioStatsAnalyzer=new pe(this.stream,this.videoElement,this.audioElement);let e=this.getAudioPlaybackElement();if(e&&this.config.speakerDeviceId&&this.setSpeakerDevice(e,this.config.speakerDeviceId),this.videoElement)this.videoElement.muted=!0,this.videoElement.play().then(()=>{this.playAudioElement()}).catch(t=>{if(t instanceof DOMException&&t.name==="NotAllowedError")p.warn("Video autoplay blocked by browser. Requesting user gesture to resume playback."),this.clientMessages?.next(new li);else{let n="Fatal Error: Digital Human video cannot be played.";p.error(n,p.serialiseError(t)),this.clientMessages?.next(new q(n)),this.endSession(Ps,!0)}}),this.videoInitialized=!0,this.messages.next(new Tn),this.reconnectionAttempts=0,this.clearReconnectTimer();else{let t="Fatal Error: Video element not found.";p.error(t),this.clientMessages?.next(new q(t)),this.endSession(Ps,!0)}setTimeout(()=>{this.clientMessages?.next(new ti)},Ds)}getAudioPlaybackElement(){return xn(this.videoElement)?this.videoElement:this.audioElement}playAudioElement(){let e=this.getAudioPlaybackElement();if(!e){this.handleMissingAudioElement();return}let t=e===this.videoElement;e.muted=!1,e.play().then(()=>{p.info("Audio playback successfully started."),this.clientMessages?.next(new Kn)}).catch(n=>{p.warn("Audio cannot be played.",n),this.clientMessages?.next(new Fe),t?(e.muted=!0,e.play().then(()=>{this.clientMessages?.next(new Oe)}).catch(i=>{p.warn("Muted video reveal also blocked.",i),this.clientMessages?.next(new q(`Video playback failed: ${i}`))})):this.clientMessages?.next(new Oe)})}resumeVideoPlayback(){if(!this.videoElement){p.warn("resumeVideoPlayback called but no video element available");return}this.videoElement.play().then(()=>{this.playAudioElement()}).catch(e=>{p.error("Video playback failed after user gesture",p.serialiseError(e)),this.clientMessages?.next(new q("Video playback failed after user gesture")),this.endSession(pr,!0)})}pauseAudioElement(){let e=this.getAudioPlaybackElement();if(!e){this.handleMissingAudioElement();return}e===this.videoElement?e.muted=!0:e.pause(),this.clientMessages?.next(new Fe)}muteUpstreamMic(){if(!re(this.audioUpstreamMode)){p.warn(`muteUpstreamMic called in '${this.audioUpstreamMode}' mode \u2014 no PS upstream audio track to mute; ignoring.`);return}if(!this.stream){p.warn("muteUpstreamMic called before PixelStreaming stream is initialised; ignoring.");return}this.stream.muteMicrophone()}unmuteUpstreamMic(){if(!re(this.audioUpstreamMode)){p.warn(`unmuteUpstreamMic called in '${this.audioUpstreamMode}' mode \u2014 no PS upstream audio track to unmute; ignoring.`);return}if(!this.stream){p.warn("unmuteUpstreamMic called before PixelStreaming stream is initialised; ignoring.");return}this.stream.unmuteMicrophone(!1)}setSpeakerDevice(e,t){let n=e;n.setSinkId?n.setSinkId(t).then(()=>{p.info(`Speaker device set to: ${t}`)}).catch(i=>{p.error(`Failed to set speaker device: ${t}`,p.serialiseError(i))}):p.error("setSinkId not supported in this browser, cannot set speaker device")}handleMissingAudioElement(){let e="Error: Digital Human audio element not found, cannot play audio.";p.error(e),this.clientMessages?.next(new q(e))}startAudioStatsMonitor(e=5e3){this.stopAudioStatsMonitor(),p.info("Starting audio stats monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new pe(this.stream,this.videoElement,this.audioElement)),this.audioStatsInternal=setInterval(()=>{this.audioStatsAnalyzer?.analyzeAudioStats().catch(t=>{p.error("Error analyzing audio stats",p.serialiseError(t))})},e)}stopAudioStatsMonitor(){this.audioStatsInternal&&clearInterval(this.audioStatsInternal)}startNetworkQualityMonitor(e){this.stopNetworkQualityMonitor(),p.info("Starting network quality monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new pe(this.stream,this.videoElement,this.audioElement)),this.videoContainerElement&&e.visibility!=="hidden"&&(this.networkIndicator=new In(this.videoContainerElement,e));let t=e.collectionIntervalMs??3e3;this.networkQualityInterval=setInterval(()=>{this.audioStatsAnalyzer?.collectNetworkQuality(e).then(n=>{n&&(this.networkIndicator?.update(n),this.clientMessages?.next(new ai(n)))}).catch(n=>{p.error("Error collecting network quality",p.serialiseError(n))})},t)}stopNetworkQualityMonitor(){this.networkQualityInterval&&(clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0),this.networkIndicator&&(this.networkIndicator.destroy(),this.networkIndicator=void 0)}handleDataChannelOpen(){p.info("DataChannelOpen"),this.dataChannelOpen=!0,this.messages.next(new En)}handleWebRtcFailed(e){p.error("WebRTC failed",e),this.reconnectIfSafe(e)}handleWebRtcDisconnected(e){p.warn(`WebRTC disconnected, message: ${e?.data?.eventString}, allowClickToReconnect: ${e?.data?.allowClickToReconnect}`),this.reconnectIfSafe(e)}handleWebRtcStats(e){let t=new kn(e.data.aggregatedStats);this.messages.next(t);let n=e.data.aggregatedStats.inboundVideoStats?.framesDecoded??0;this.checkForFreeze(n)}checkForFreeze(e){let t=Date.now();if(this.lastDecodedFrames===0&&e===0){p.debug("[WebRTC] Waiting for first video frame...");return}if(e===this.lastDecodedFrames){this.freezeCount++;let n=((t-this.lastCheckTime)/1e3).toFixed(1);p.warn(`[WebRTC] Video FROZEN for ${n}s (count=${this.freezeCount})`),this.freezeCount>=3&&(p.error("[WebRTC] Video frozen 3 times in a row, transferring session..."),this.session.sessionTransferManager.transferSession(),this.freezeCount=0)}else this.freezeCount=0,this.lastDecodedFrames=e,this.lastCheckTime=t}clearReconnectTimer(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=void 0)}scheduleReconnect(){let e=Math.min(this.baseReconnectDelayMs*Math.pow(2,this.reconnectionAttempts),this.maxReconnectDelayMs);p.info(`Scheduling reconnection attempt ${this.reconnectionAttempts} in ${e}ms`),this.reconnectTimeoutId=setTimeout(()=>{p.info(`Executing reconnection attempt ${this.reconnectionAttempts}`),this.reconnectTimeoutId=void 0,this.videoInitialized=!1,this.dataChannelOpen=!1,this.sceneReady=!1,this.audioStatsAnalyzer?.resetStats(),this.stream?.reconnect()},e)}reconnectIfSafe(e){try{this.allowReconnection&&!this.reconnectTimeoutId?(p.debug("Checking if should attempt reconnection after event",e),this.reconnectionAttempts<this.maxReconnectAttempts?(this.reconnectionAttempts++,this.clientMessages?.next(new ei),this.scheduleReconnect()):(p.info("Max reconnection attempts reached. Ending session."),this.clientMessages?.next(new Zn),this.endSession(Is,!1))):p.warn("Reconnection already scheduled or reconnecting is disabled")}catch(t){p.error("Error during reconnection attempt",p.serialiseError(t)),this.clientMessages?.next(new q("Error during reconnection attempt")),this.endSession(Is,!1)}}handleDataChannelMessage(e){p.trace("Signaling: Received data channel message",e);try{let t=JSON.parse(e);if(t.type!==void 0)this.messages.next(new Rn(t));else throw new Error("Signaling: Engine response missing type")}catch(t){p.error("Signaling: Failed to parse engine response",p.serialiseError(t))}}handleIndexInQueueMessage(e){try{let n=Number(e.message);this.clientMessages?.next(new Wn(n))}catch(t){p.error("Signaling: Failed to parse position in queue message",p.serialiseError(t))}}handleRendererTakenMessage(e){try{let t=e;this.clientMessages?.next(new Yn(t.message)),p.info("Signaling: Renderer taken event",t.message)}catch(t){p.error("Signaling: Failed to parse renderer taken message",p.serialiseError(t))}}handleWebRtcConnectedMessage(){this.clientMessages?.next(new ri),p.info("Signaling: WebRTC connected")}handleRendererGoneEvent(e){p.info("Signaling: Renderer gone event",e),this.reconnectIfSafe(e)}handleSwitchRendererRequestEvent(e){p.info("Signaling: Renderer switch renderer request event",e),this.session.sessionTransferManager.transferSession()}handleCustomerConcurrencyLimitReachedMessage(e){p.warn("Signaling: Customer concurrency limit reached message received",e),this.clientMessages?.next(new oi)}handleRendererErrorMessage(e){try{let t=e,n=t.code??-1,i=t.message??"An unknown renderer error occurred";p.error(`Signaling: Renderer error received - code: ${n}, message: ${i}`),this.clientMessages?.next(new Ae(n,i)),this.endSession(Ls,!0)}catch(t){p.error("Signaling: Failed to parse renderer error message",p.serialiseError(t)),this.clientMessages?.next(new Ae(-1,"An unknown renderer error occurred")),this.endSession(Ls,!0)}}socketSend(e){p.trace("Signaling: Sending socket message",e),this.stream?.signallingProtocol?.transport?.webSocket?.send(JSON.stringify(e))}dataSend(e){let t=e.toJSON();if(t.action==="chat_prompt"){let n=t.data?.requestId;p.info(`Signaling: Sending data channel message \u2014 action=chat_prompt, requestId=${n??"unknown"}`),(!(e instanceof se)||e.shouldEmitPromptRequest)&&this.clientMessages?.next(new Gn(t.data))}else p.info("Signaling: Sending data channel message",JSON.stringify(t));this.stream?.emitUIInteraction(e)}dataSendBinary(e){p.info("Signaling: Sending data channel binary message");let t=this.uint8ToBase64(e);this.stream?.emitUIInteraction(t)}uint8ToBase64(e){let t="",n=e.byteLength;for(let i=0;i<n;i++)t+=String.fromCharCode(e[i]);return btoa(t)}endSession(e=ur,t=!0){p.info("Signaling: Ending session"),this.clearReconnectTimer(),this.stopNetworkQualityMonitor(),this.socketSend({message:e,type:"client_gone",sessionId:this.config.sessionId}),this.streamDisconnect(),p.info("Session has ended, reason: "+e),t&&this.clientMessages?.next(new qn(e))}streamDisconnect(){p.info("Signaling: Disconnecting stream"),this.stopNetworkQualityMonitor(),this.stopAudioStatsMonitor(),this.allowReconnection=!1,this.clearReconnectTimer();let e=this.stream?.webRtcController?.statsTimerHandle;e&&window.clearInterval(e);let t=this.stream?.webRtcController?.peerConnectionController;if(t?.peerConnection){t.peerConnection.getReceivers=()=>[];let n=t.peerConnection;Object.defineProperty(t,"peerConnection",{get:()=>n,set:()=>{},configurable:!0})}this.stream?.disconnect(),this.dataChannelOpen=!1,this.videoInitialized=!1,this.sceneReady=!1}startSoftSwitch(){p.info("Signaling: Start soft switching"),this.clientMessages?.next(new ni)}stopSoftSwitch(){p.info("Signaling: Stop soft switching"),this.clientMessages?.next(new ii)}};import{Subject as io}from"rxjs";var vr=(o=>(o.CloseUp="close_up",o.LooseCloseUp="loose_close_up",o.TightMediumShot="tight_medium_shot",o.MediumShot="medium_shot",o.MediumFullShot="medium_full_shot",o.FullShot="full_shot",o))(vr||{}),wr=(i=>(i.Left="left",i.Right="right",i.Center="center",i.Centre="centre",i))(wr||{}),Le=class{constructor(e,t=2e3,n=z()){this.position=e;this.duration=t;this.requestId=n}position;duration;requestId;toJSON(){return{action:"camera_to_anchor",data:{requestId:this.requestId,position:this.position,transition_duration_ms:this.duration}}}};var Ln=class{constructor(e,t=z()){this.avatarId=e;this.requestId=t}avatarId;requestId;toJSON(){return{action:"change_avatar",data:{id:this.avatarId,requestId:this.requestId}}}};var Dn=class{constructor(e,t=z()){this.url=e;this.requestId=t}url;requestId;toJSON(){return{action:"load_background",data:{url:this.url,requestId:this.requestId}}}};var On=class{constructor(e,t=z()){this.actionName=e;this.requestId=t}actionName;requestId;toJSON(){return{action:"trigger_action",data:{action_name:this.actionName,requestId:this.requestId}}}};var Fn=class{constructor(e){this.session=e;this.addTransferSessionListener()}session;isTransferSessionInProgress=!1;addTransferSessionListener(){this.isTransferSessionInProgress=!1,document.addEventListener("keydown",e=>{e.ctrlKey&&e.shiftKey&&e.key.toLowerCase()==="y"&&(p.info("Session transfer via keyboard shortcut triggered"),this.transferSession())})}transferSession(){if(this.isTransferSessionInProgress){p.warn("Transfer already in progress, skipping");return}this.isTransferSessionInProgress=!0,p.info("Beginning session transfer"),this.session.config.videoContainerElement&&(this.session.config.videoContainerElement.querySelectorAll("#freezeFrame,#streamingVideo").forEach(n=>{n.remove()}),this.session.signaling&&this.session.signaling.streamDisconnect()),this.session.createSignaling(this.session.config.videoContainerElement??document.createElement("div")).init()}switchLiveVideo(e,t){p.info("New signaling video is ready for transfer"),this.session.signaling&&e&&t.videoElement&&(t.videoElement.classList.add("incoming-video"),this.session.signaling.videoElement&&t.videoElement&&e?.appendChild(t.videoElement),this.session.signaling.startSoftSwitch(),setTimeout(()=>{this.session.signaling?.streamDisconnect(),this.session.signaling=t,this.isTransferSessionInProgress=!1,this.session.signaling?.stopSoftSwitch(),p.info("Session transfer complete")},1e3))}};var Cr=[1103,1200,1402];var Ds=750,An=class{constructor(e){this.config=e;this.sessionTransferManager=new Fn(this),this._audioUpstreamMode=G(this.config.audioUpstreamMode)}config;id;signaling;messages=new io;speechRec;promptMetadata={};audioStreamId;sessionTransferManager;jwt;welcomeRequested=!1;resolutionLogged=!1;sttPausedByHost=!1;_audioUpstreamMode;get audioUpstreamMode(){return this._audioUpstreamMode}updatePromptMetadata(e){try{JSON.parse(JSON.stringify(e)),this.promptMetadata.custom=e,this.messages.next(new Qn(this.promptMetadata))}catch(t){p.error("Error parsing custom metadata",e,p.serialiseError(t))}}setEnableMicrophone(e){let t=this.audioUpstreamMode;this.config.enableMicrophone=e,this.sttPausedByHost=!1;let n=!1;X(t)&&(this.speechRec?(e?this.speechRec.startRecognition():this.speechRec.stopRecognition(),n=!0):p.warn("setEnableMicrophone: STT leg is configured but speech recognition is not initialised yet")),re(t)&&(this.signaling?(e?this.signaling.unmuteUpstreamMic():this.signaling.muteUpstreamMic(),n=!0,X(t)||this.messages.next(new jn(e))):p.warn("setEnableMicrophone: PS leg is configured but signaling is not initialised yet")),n||p.warn(`setEnableMicrophone(${e}) had nothing to do in mode '${t}' \u2014 session not ready?`)}pauseSpeechRecognition(){return this.sttPausedByHost=!0,this.speechRec?this.speechRec.pause():(p.warn("pauseSpeechRecognition: pause intent recorded, but speech recognition is not initialised yet \u2014 nothing to pause"),!1)}resumeSpeechRecognition(){return this.sttPausedByHost=!1,this.speechRec?this.speechRec.resume():(p.warn("resumeSpeechRecognition: pause intent cleared, but speech recognition is not initialised yet \u2014 nothing to resume"),!1)}setCameraAnchorDistance(e,t=0,n=this.signaling){this.config.cameraAnchorDistance=e,n?.dataSend(new Le(e,t))}setCameraAnchorHorizontal(e,t=0,n=this.signaling){this.config.cameraAnchorHorizontal=e,n?.dataSend(new Le(e,t))}changeAvatar(e,t=this.signaling){t?.dataSend(new Ln(e))}loadBackground(e,t=this.signaling){t?.dataSend(new Dn(e))}userStartSpeaking(e=this.signaling){e?.dataSend(new ci("start"))}userStopSpeaking(e=this.signaling){e?.dataSend(new ci("stop"))}triggerAction(e,t=this.signaling){t?.dataSend(new On(e))}resumeVideoPlayback(){this.signaling?.resumeVideoPlayback()}createSession(){this.messages.subscribe(e=>{if(this.config.messageHandler&&this.config.messageHandler(e),e.uneeqMessageType==="SoftSwitchFinished"||e.uneeqMessageType==="SessionReconnectingFinished"){if(!X(this.audioUpstreamMode))return;if(this.config.enableMicrophone&&!this.sttPausedByHost)e.uneeqMessageType==="SessionReconnectingFinished"?(p.info("Session, resuming speech recognition after reconnect"),this.speechRec?.resume()):(p.info("Session, restarting speech recognition after soft switch"),this.speechRec?.startRecognition());else{let t=e.uneeqMessageType==="SoftSwitchFinished"?"soft switch":"reconnect",n=this.sttPausedByHost?"paused by host":"microphone disabled";p.info(`Session, skipping speech recognition restart after ${t} (${n})`)}}}),this.id=this.config.sessionId,this.jwt=this.config.sessionToken,p.info("Session created with id: "+this.id),this.updatePromptMetadata(this.config.customMetadata||{}),this.promptMetadata=this.initMetadata(),this.listenForTabClosure(),this.signaling=this.createSignaling(this.config.videoContainerElement),this.signaling.init()}createSignaling(e=document.createElement("div")){let t=new URLSearchParams({token:this.jwt});this.config.backgroundUrl&&t.append("backgroundUrl",this.config.backgroundUrl);let n=(this.config.connectionUrl+`/session-service/v1/ws/session?${t.toString()}`).replace("http://","ws://").replace("https://","wss://");p.debug("Socket URL:",n);let i=new Pn(this,n,e);return i.messages.subscribe(r=>{this.signalingEventHandler(r,i)}),i}signalingEventHandler(e,t){switch(e.type){case 0:{this.handleSessionReady(t);break}case 1:{this.handleSessionReady(t);break}case 2:{this.handleDataChannelMessage(e,t);break}case 5:{let n=e.stats;!this.resolutionLogged&&n.inboundVideoStats?.frameWidth&&n.inboundVideoStats?.frameHeight&&(p.info("Video resolution:",`${n.inboundVideoStats.frameWidth}x${n.inboundVideoStats.frameHeight}`),this.resolutionLogged=!0),this.config.webRtcStatsEmitMessages&&this.messages.next(new Hn(n)),this.config.webRtcStatsLogMessages&&p.info("WebRTC stats",n);break}}}handleSessionReady(e){p.debug(`Session ready check - videoInitialized: ${e.videoInitialized}, dataChannelOpen: ${e.dataChannelOpen}, sceneReady: ${e.sceneReady}`),e.videoInitialized&&e.dataChannelOpen&&e.sceneReady&&(e.reconnectionAttempts=0,this.setCameraAnchorDistance(this.config.cameraAnchorDistance,0,e),this.setCameraAnchorHorizontal(this.config.cameraAnchorHorizontal,0,e),setTimeout(()=>{this.sessionTransferManager.isTransferSessionInProgress&&this.config.videoContainerElement?this.sessionTransferManager.switchLiveVideo(this.config.videoContainerElement,e):(this.initSpeechRecognition(this.jwt),this.sendWelcomePrompt(),document.body.classList.add("uneeq-streaming-live")),this.messages.next(new _n(this.id)),this.config.networkIndicator&&e.startNetworkQualityMonitor(this.config.networkIndicator),this.config.webRtcStatsLogMessages&&e.startAudioStatsMonitor()},Ds))}async initSpeechRecognition(e){if(!X(this.audioUpstreamMode)){p.info(`[STT] audioUpstreamMode='${this.audioUpstreamMode}' \u2014 skipping STT provider initialisation (no STT leg in this mode).`);return}if(this.speechRec){p.warn("Speech recognition already initialized");return}let t=this.config.speechRecognitionProvider||"google";p.info(`[STT] Config speechRecognitionProvider: "${this.config.speechRecognitionProvider}", resolved provider: "${t}"`),t!=="google"&&t!=="deepgram"&&(p.warn(`Invalid speechRecognitionProvider value: "${String(t)}". Supported values are "google" or "deepgram". Defaulting to "google".`),t="google",this.config.speechRecognitionProvider="google"),p.info(`[STT] Using provider: ${t}`);try{this.speechRec=await(t==="deepgram"?this.createDeepgramSTT(e):this.createGoogleSTT(e))}catch(n){p.error("[STT] Failed to initialise speech recognition provider",p.serialiseError(n));return}this.config.enableMicrophone&&!this.sttPausedByHost&&this.speechRec&&this.speechRec.startRecognition()}async createGoogleSTT(e){let t=this.getSpeechOptions(e);p.debug("Initializing Google STT (speech-recognition-service)");let{GoogleSTT:n}=await import("./chunks/google-stt-AOUGMCIB.js");return new n(t)}async createDeepgramSTT(e){let t=this.config.deepgramConfig||{};if(this.isFluxModel(t.model))return this.createDeepgramFluxSTT(e);p.warn("Deepgram STT is currently in beta, is subject to change, and is not suitable for production use"),p.debug("Initializing Deepgram STT");let n={connectionUrl:this.config.connectionUrl,jwtToken:e,sessionId:this.id,model:t.model,language:t.language,smartFormat:t.smartFormat,interimResults:t.interimResults,utteranceEndMs:t.utteranceEndMs,vadEvents:t.vadEvents,encoding:t.encoding,sampleRate:t.sampleRate,channels:t.channels,fillerWords:t.fillerWords,endpointing:t.endpointing,interruptionWordThreshold:t.interruptionWordThreshold,echoCancellation:t.microphone?.echoCancellation,noiseSuppression:t.microphone?.noiseSuppression,autoGainControl:t.microphone?.autoGainControl,microphoneDeviceId:this.config.microphoneDeviceId,promptMetadata:this.promptMetadata,messages:this.messages,sendMessage:r=>{this.signaling?.dataSend(r)},enableInterrupt:this.config.enableInterruptBySpeech,safetyNetTimeoutMs:t.safetyNetTimeoutMs,keyterms:t.keyterms,noDelay:t.noDelay},{DeepgramSTT:i}=await import("./chunks/deepgram-stt-Y67Z46KN.js");return new i(n)}isFluxModel(e){return e!==void 0&&e.toLowerCase().startsWith("flux")}async createDeepgramFluxSTT(e){p.debug("Initializing Deepgram Flux STT (v2 API)");let t=this.config.deepgramConfig||{},n={connectionUrl:this.config.connectionUrl,jwtToken:e,sessionId:this.id,model:t.model,language:t.language,eotThreshold:t.eotThreshold,eagerEotThreshold:t.eagerEotThreshold,eotTimeoutMs:t.eotTimeoutMs,eagerMaxTurnDurationMs:t.eagerMaxTurnDurationMs,keyterms:t.keyterms,safetyNetTimeoutMs:t.safetyNetTimeoutMs,echoCancellation:t.microphone?.echoCancellation,noiseSuppression:t.microphone?.noiseSuppression,autoGainControl:t.microphone?.autoGainControl,microphoneDeviceId:this.config.microphoneDeviceId,promptMetadata:this.promptMetadata,messages:this.messages,sendMessage:r=>{this.signaling?.dataSend(r)}},{DeepgramFluxSTT:i}=await import("./chunks/deepgram-flux-stt-NOTQ2K35.js");return new i(n)}getSpeechOptions(e){return{apiUrl:this.config.connectionUrl,assetBasePath:this.config.assetBasePath,enableInterrupt:this.config.enableInterruptBySpeech,enableVad:this.config.enableVad,jwtToken:e,hintPhrases:this.config.speechRecognitionHintPhrases,hintPhrasesBoost:this.config.speechRecognitionHintPhrasesBoost,locales:this.config.speechRecognitionLocales,messages:this.messages,promptMetadata:this.promptMetadata,sessionId:this.id,sendMessage:t=>{this.signaling?.dataSend(t)},microphoneDeviceId:this.config.microphoneDeviceId}}initMetadata(){return{userSpokenLocale:"",browserDetectedLocales:this.config.speechRecognitionLocales,userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userScreenWidth:window.screen.availWidth,userScreenHeight:window.screen.availHeight,userAgent:navigator.userAgent,personaId:this.config.personaId,custom:this.config.customMetadata}}handleDataChannelMessage(e,t){switch(p.debug("Processing data channel message",e),e.msg.type){case"nlp_prompt_result":this.messages.next(new Xn(e.msg));break;case"avatar_started_speaking":{this.messages.next(new Bn);break}case"avatar_stopped_speaking":{this.messages.next(new Vn);break}case"error":{p.error(`an error has occurred - ${JSON.stringify(e.msg)}`),this.handleChannelMessageError(e.msg);break}case"scene_ready":{p.debug("Scene is ready"),t.sceneReady=!0,this.handleSessionReady(t),this.messages.next(new Jn);break}case"speech_event":{this.messages.next(new zn(e.msg));break}case"session_ended":{let n=e.msg.reason==="UserInactivity"?hr:e.msg.reason;this.signaling?.endSession(n),this.signaling=void 0;break}case"speech_stream_opened":{this.audioStreamId=e.msg.streamId;break}case"speech_stream_closed":{e.msg.streamId===this.audioStreamId?this.audioStreamId=void 0:p.warn("Received SpeechStreamClosed message for unexpected streamId",e.msg.streamId);break}}}handleChannelMessageError(e){let t=e?.message?.trim()||"An unknown error occurred";e&&Cr.includes(e.code)?this.messages.next(new $n(e)):this.messages.next(new q(t))}sendWelcomePrompt(){p.debug("Checking if the welcome prompt should be sent. Welcome requested already = "+this.welcomeRequested+". Prompt = ",this.config.welcomePrompt),this.config.welcomePrompt&&this.config.welcomePrompt.length>0&&!this.welcomeRequested&&(this.welcomeRequested=!0,this.signaling?.dataSend(new se(this.config.welcomePrompt,this.promptMetadata)))}listenForTabClosure(){window.addEventListener("beforeunload",()=>{p.info("Window unload detected, ending session."),this.signaling?.endSession(),this.signaling=void 0})}};var Nn=class{constructor(e,t=z()){this.prompt=e;this.requestId=t}prompt;requestId;toJSON(){return{action:"speak",data:{requestId:this.requestId,prompt:this.prompt}}}};var me=class{constructor(e,t,n={},i=z()){this.action=e;this.streamId=t;this.metadata=n;this.requestId=i}action;streamId;metadata;requestId;toJSON(){return{action:"speech_stream",data:{requestId:this.requestId,action:this.action,streamId:this.streamId,metadata:this.metadata}}}};var Un=class{constructor(e,t,n,i){this.command=e;this.enabled=t;this.category=n;this.verbosity=i}command;enabled;category;verbosity;toJSON(){let e={command:this.command,enabled:this.enabled};return this.category!==void 0&&(e.category=this.category),this.verbosity!==void 0&&(e.verbosity=this.verbosity),{action:"execute_command",data:e}}};async function Mr(s,e){try{if(s?.audioStreamId===void 0){p.warn("Audio stream is not open | Call openAudioStream() first");return}let t;if(typeof e=="string"){let o=typeof atob<"u"?atob(e):Buffer.from(e,"base64").toString("binary");t=new Uint8Array(o.length);for(let a=0;a<o.length;a++)t[a]=o.charCodeAt(a)}else if(e instanceof Uint8Array)t=e;else if(typeof Blob<"u"&&e instanceof Blob){let o=await e.arrayBuffer();t=new Uint8Array(o)}else{p.error("speakAudio: Unsupported audio type",e);return}let n=Uint8Array.from([1]),i=Uint8Array.from([s.audioStreamId]),r=new Uint8Array(2+t.length);r.set(n,0),r.set(i,1),r.set(t,2),s.signaling?.dataSendBinary(r)}catch(t){p.error("speakAudioSend: Error sending audio",t)}}var Os=class{constructor(e){this.config=e;p.setLevel(e.logLevel??"info")}config;session;messageSubscription;init(){if(this.session){let e="Cannot initialize: session already active. Call endSession() first.";throw p.warn(e),new Error(e)}if(this.config.audioUpstreamMode!==void 0&&!Vs(this.config.audioUpstreamMode)){let e=`Invalid audioUpstreamMode: '${String(this.config.audioUpstreamMode)}'. Allowed: 'speech-recognition-service' | 'pixel-streaming' | 'both'.`;throw p.error(e),new Error(e)}p.info(`Initializing Uneeq with config:', ${JSON.stringify(this.config)}, for UserAgent: ${navigator.userAgent}`),this.session=new An(this.config),this.session.createSession(),this.messageSubscription=this.session.messages.subscribe(e=>{e.uneeqMessageType==="SessionEnded"&&(p.info("Session ended, resetting session state"),this.resetSessionState())})}isSessionActive(){return this.session!==void 0}ensureSessionExists(){return this.session?.id?!0:(p.warn("Cannot perform action, session has not started."),!1)}chatPrompt(e){e&&e.trim()!==""&&this.ensureSessionExists()&&this.session?.signaling?.dataSend(new se(e,this.session?.promptMetadata))}speak(e){e&&e.trim()!==""&&this.ensureSessionExists()&&this.session?.signaling?.dataSend(new Nn(e))}openAudioStream(){let e=this.session;this.ensureSessionExists()&&e?.signaling?.dataSend(new me("open",e?.audioStreamId))}closeAudioStream(){let e=this.session;this.ensureSessionExists()&&e?.audioStreamId!==void 0&&e.signaling?.dataSend(new me("close",e.audioStreamId))}interruptAudioStream(){let e=this.session;this.ensureSessionExists()&&e?.audioStreamId!==void 0&&e.signaling?.dataSend(new me("interrupt",e.audioStreamId))}async speakAudio(e){this.ensureSessionExists()&&await Mr(this.session,e)}cameraAnchorDistance(e,t){this.ensureSessionExists()&&this.session?.setCameraAnchorDistance(e,t)}cameraAnchorHorizontal(e,t){this.ensureSessionExists()&&this.session?.setCameraAnchorHorizontal(e,t)}changeAvatar(e){e&&e.trim()!==""&&this.ensureSessionExists()&&this.session?.changeAvatar(e)}loadBackground(e){e&&e.trim()!==""&&this.ensureSessionExists()&&this.session?.loadBackground(e)}userStartSpeaking(){this.ensureSessionExists()&&this.session?.userStartSpeaking()}userStopSpeaking(){this.ensureSessionExists()&&this.session?.userStopSpeaking()}triggerAction(e){e&&e.trim()!==""&&this.ensureSessionExists()&&this.session?.triggerAction(e)}resumeVideoPlayback(){this.session?.resumeVideoPlayback()}executeCommand(e,t,n,i){this.ensureSessionExists()&&this.session?.signaling?.dataSend(new Un(e,t,n,i))}endSession(){this.ensureSessionExists()&&(this.session?.signaling?.endSession(),this.resetSessionState())}resetSessionState(){this.messageSubscription?.unsubscribe(),this.messageSubscription=void 0,this.session=void 0}unmuteDigitalHuman(){this.ensureSessionExists()&&(this.session?.signaling?.playAudioElement(),p.debug("Unmuted digital human."))}muteDigitalHuman(){this.ensureSessionExists()&&(this.session?.signaling?.pauseAudioElement(),p.debug("Muted digital human."))}stopSpeaking(){this.ensureSessionExists()&&this.session?.signaling?.dataSend(new Bs)}setCustomPromptMetadata(e){this.ensureSessionExists()&&this.session?.updatePromptMetadata(e)}enableMicrophone(e=!0){this.ensureSessionExists()&&this.session?.setEnableMicrophone(e)}pauseSpeechRecognition(){if(!this.ensureSessionExists())return!1;let e=G(this.config.audioUpstreamMode);if(!X(e))return p.warn(`pauseSpeechRecognition called in '${e}' mode \u2014 no STT leg to pause; ignoring. Use muteUpstreamMic() to silence the PS mic track.`),!1;let t=this.session?.pauseSpeechRecognition()??!1;return t instanceof Promise?!0:t}resumeSpeechRecognition(){if(!this.ensureSessionExists())return!1;let e=G(this.config.audioUpstreamMode);if(!X(e))return p.warn(`resumeSpeechRecognition called in '${e}' mode \u2014 no STT leg to resume; ignoring. Use unmuteUpstreamMic() to re-enable the PS mic track.`),!1;let t=this.session?.resumeSpeechRecognition()??!1;return t instanceof Promise?!0:t}muteUpstreamMic(){this.ensureSessionExists()&&this.session?.signaling?.muteUpstreamMic()}unmuteUpstreamMic(){this.ensureSessionExists()&&this.session?.signaling?.unmuteUpstreamMic()}setWebRtcStatsEnabled(e,t){this.session?.config&&(this.session.config.webRtcStatsEmitMessages=e,this.session.config.webRtcStatsLogMessages=t,p.info(`Setting up WebRtcStats: webRtcStatsEmitMessages: ${this.session.config.webRtcStatsEmitMessages}, webRtcStatsLogMessages: ${this.session.config.webRtcStatsLogMessages}`),t?this.session.signaling?.startAudioStatsMonitor():this.session.signaling?.stopAudioStatsMonitor())}setNetworkIndicatorEnabled(e){this.ensureSessionExists()&&(e?this.session?.signaling?.startNetworkQualityMonitor(e):this.session?.signaling?.stopNetworkQualityMonitor())}};export{Lr as AvatarAnswerMessage,Nr as AvatarInterruptedMessage,Bn as AvatarStartedSpeakingMessage,Vn as AvatarStoppedSpeakingMessage,vr as CameraAnchorDistance,wr as CameraAnchorHorizontal,Qn as CustomMetadataUpdated,oi as CustomerConcurrencyLimitReachedMessage,Pr as DeviceErrorMessage,Fe as DigitalHumanMuted,Oe as DigitalHumanPlayedInMutedModeSuccess,Kn as DigitalHumanUnmuted,jn as EnableMicrophoneUpdatedMessage,Ir as LogLevel,yr as NetworkIndicatorPopupTrigger,gr as NetworkIndicatorPosition,fr as NetworkIndicatorVisibility,mr as NetworkQualityLevel,ai as NetworkQualityMessage,Gn as PromptRequestMessage,Xn as PromptResultMessage,Ae as RendererErrorMessage,Jn as SceneReadyMessage,$n as SessionBackendErrorMessage,Yn as SessionConnectingMessage,Zn as SessionDisconnectedMessage,qn as SessionEndedMessage,q as SessionErrorMessage,_n as SessionLiveMessage,ti as SessionReconnectingFinishedMessage,ei as SessionReconnectingMessage,ni as SoftSwitchStartingMessage,ii as SoftSwitchStoppingMessage,zn as SpeechEventMessage,di as SpeechRecognitionProvider,Ur as SpeechRecognitionTransientErrorMessage,Dr as SpeechTranscriptionMessage,Os as Uneeq,Us as UneeqMessageType,Fr as UserStartedSpeakingMessage,Ar as UserStoppedSpeakingMessage,Or as VadInterruptionAllowedMessage,li as VideoAutoplayBlockedMessage,si as VideoLayoutConfiguringMessage,Wn as WaitingInQueueMessage,ri as WebRtcConnectedMessage,Hn as WebRtcStatsMessage,G as resolveAudioUpstreamMode};
|
|
87
|
+
Audio level (0-1): ${a??"N/A"}`),n===0&&p.warn("WebRTC Connection - Audio - No audio packets received \u2014 remote is probably not sending audio."),i>0&&p.warn(`WebRTC Connection - Audio - packet loss detected: ${i} packets lost.`),a===void 0?p.warn("WebRTC Connection - Audio - Audio level not available in stats."):a===0?p.warn("WebRTC Connection - Audio - Audio level is zero \u2014 digital human might not be talking at this exact moment as audio is silent or muted."):a<.02?p.warn("WebRTC Connection - Audio - Audio level is very low \u2014 audio might be too quiet."):p.info("WebRTC Connection - Audio - Audio level looks normal, digital human is likely speaking.")}logElementStatus(e){let t=xn(this.videoElement),n=t?this.videoElement:this.audioElement;p.debug(`Audio plays from ${t?"video":"separate audio"} element (DisableAudioSync=${t?"false":"true"}).`),p.debug(`Video element muted: ${this.videoElement?.muted}, (should be ${t?"false to be able to hear the digital human":"true as part of avoiding auto play restrictions"})`),p.debug(`Playback element muted: ${n?.muted}, (should be false to be able to hear the digital human)`),p.debug(`Playback element volume: ${n?.volume}, (should be greater than zero to be able to hear the digital human)`);let i=e?.mimeType;i&&n&&(p.debug(`Playback element can play webrtc audio codec (${i}) : ${n.canPlayType(i)}, (should be 'probably' or 'maybe)'`),i==="audio/opus"&&p.debug(`Audio codec opus is often known as ogg, so checking can play ogg codec: ${n.canPlayType("audio/ogg")}, (should be 'probably' or 'maybe')`))}};var Pe={good:"#22c55e",fair:"#eab308",poor:"#ef4444",inactive:"#6b7280"},In=class{constructor(e,t){this.videoContainerElement=e;this.visibility=t.visibility??"when-degraded",this.position=t.position??"top-right",this.popupTrigger=t.popupTrigger??"click",this.onClickBound=this.onClick.bind(this),this.onMouseEventBound=n=>n.stopPropagation(),this.onDocumentClickBound=this.onDocumentClick.bind(this),this.onMouseEnterBound=this.onMouseEnter.bind(this),this.onMouseLeaveBound=this.onMouseLeave.bind(this),this.visibility!=="hidden"&&this.createElements()}videoContainerElement;container;panel;bars=[];panelVisible=!1;lastMetrics;visibility;position;popupTrigger;onClickBound;onMouseEventBound;onDocumentClickBound;onMouseEnterBound;onMouseLeaveBound;hoverHideTimeout;originalParentPosition;createElements(){getComputedStyle(this.videoContainerElement).position==="static"&&(this.originalParentPosition=this.videoContainerElement.style.position,this.videoContainerElement.style.position="relative"),this.container=document.createElement("div"),this.container.setAttribute("data-testid","network-indicator"),this.container.setAttribute("role","status"),this.container.setAttribute("aria-live","polite"),this.container.setAttribute("aria-label","Network quality: unknown"),Object.assign(this.container.style,{position:"absolute",zIndex:"1000",cursor:"pointer",padding:"6px 7px",borderRadius:"4px",background:"rgba(0, 0, 0, 0.5)",display:"none",alignItems:"flex-end",gap:"2px",pointerEvents:"auto",...this.getPositionStyles()});let t=[6,12,18];for(let n of t){let i=document.createElement("div");i.setAttribute("data-testid","network-indicator-bar"),Object.assign(i.style,{width:"4px",height:`${n}px`,borderRadius:"1px",background:Pe.inactive,transition:"background 0.3s ease"}),this.bars.push(i),this.container.appendChild(i)}this.container.addEventListener("mousedown",this.onMouseEventBound),this.container.addEventListener("mouseup",this.onMouseEventBound),this.popupTrigger==="click"?this.container.addEventListener("click",this.onClickBound):this.popupTrigger==="hover"&&(this.container.addEventListener("mouseenter",this.onMouseEnterBound),this.container.addEventListener("mouseleave",this.onMouseLeaveBound)),this.popupTrigger==="none"&&(this.container.style.cursor="default"),this.videoContainerElement.appendChild(this.container)}getPositionStyles(){switch(this.position){case"top-left":return{top:"8px",left:"8px"};case"top-right":return{top:"8px",right:"8px"};case"bottom-left":return{bottom:"8px",left:"8px"};case"bottom-right":return{bottom:"8px",right:"8px"};default:return{top:"8px",right:"8px"}}}onClick(e){e.stopPropagation(),this.panelVisible?this.hidePanel():this.showPanel()}onDocumentClick(e){this.panelVisible&&this.container&&!this.container.contains(e.target)&&this.hidePanel()}onMouseEnter(){clearTimeout(this.hoverHideTimeout),this.showPanel()}onMouseLeave(){this.scheduleHoverHide()}scheduleHoverHide(){clearTimeout(this.hoverHideTimeout),this.hoverHideTimeout=setTimeout(()=>this.hidePanel(),50)}showPanel(){!this.container||!this.lastMetrics||(this.panel||(this.panel=document.createElement("div"),this.panel.setAttribute("data-testid","network-indicator-panel"),Object.assign(this.panel.style,{position:"fixed",padding:"10px",borderRadius:"6px",background:"rgba(0, 0, 0, 0.85)",color:"#ffffff",fontSize:"11px",fontFamily:"system-ui, -apple-system, sans-serif",whiteSpace:"nowrap",lineHeight:"1.6",minWidth:"180px",zIndex:"10001",pointerEvents:"auto"}),this.popupTrigger==="hover"&&(this.panel.addEventListener("mouseenter",this.onMouseEnterBound),this.panel.addEventListener("mouseleave",this.onMouseLeaveBound)),document.body.appendChild(this.panel)),this.updatePanel(),this.positionPanel(),this.panel.style.display="block",this.panelVisible=!0,document.addEventListener("click",this.onDocumentClickBound))}hidePanel(){this.panel&&(this.panel.style.display="none"),this.panelVisible=!1,document.removeEventListener("click",this.onDocumentClickBound)}positionPanel(){if(!this.panel||!this.container)return;let e=4,t=4,n=window.innerWidth,i=window.innerHeight,r=this.container.getBoundingClientRect(),o={top:Math.max(0,Math.min(r.top,i)),bottom:Math.max(0,Math.min(r.bottom,i)),left:Math.max(0,Math.min(r.left,n)),right:Math.max(0,Math.min(r.right,n))};this.panel.style.top="",this.panel.style.bottom="",this.panel.style.left="",this.panel.style.right="",this.panel.style.visibility="hidden",this.panel.style.display="block";let{width:a,height:l}=this.panel.getBoundingClientRect();this.panel.style.visibility="";let c=o.top-e,u=i-o.bottom-e,w=o.left-e,v=n-o.right-e,C,k;c>=l||u>=l?(C=u>=l&&(c<l||u>=c)?o.bottom+e:o.top-e-l,k=this.position==="top-left"||this.position==="bottom-left"?o.left:o.right-a):(k=v>=a&&(w<a||v>=w)?o.right+e:o.left-e-a,C=o.bottom-l),k=Math.max(t,Math.min(k,n-a-t)),C=Math.max(0,Math.min(C,i-l-t)),this.panel.style.top=`${C}px`,this.panel.style.left=`${k}px`}updatePanel(){if(!this.panel||!this.lastMetrics)return;let e=this.lastMetrics,t=this.getColor(e.qualityLevel);this.panel.innerHTML=[`<div style="font-weight:600;margin-bottom:4px;color:${t}">${e.qualityLevel} Quality</div>`,this.panelSectionHeader("Quality Score (MOS)"),this.panelRow("Audio",e.audioMos.toFixed(1)+" / 5.0"),this.panelRow("Video",e.videoMos.toFixed(1)+" / 5.0"),this.panelSectionHeader("Connection"),this.panelRow("Round Trip",`${e.roundTripTimeMs} ms`),this.panelRow("Packet Loss",`${e.audioPacketLossPercent}% audio / ${e.videoPacketLossPercent}% video`),this.panelRow("Jitter",`${e.audioJitterMs} ms audio / ${e.videoJitterMs} ms video`),this.panelSectionHeader("Throughput"),this.panelRow("Bitrate",`${e.audioBitrateKbps} audio / ${e.videoBitrateKbps} video kbps`),this.panelRow("Frame Rate",`${e.frameRate} fps`)].join("")}panelSectionHeader(e){return`<div style="color:#6b7280;font-size:10px;text-transform:uppercase;letter-spacing:0.5px;margin-top:6px;margin-bottom:2px">${e}</div>`}panelRow(e,t){return`<div style="display:flex;justify-content:space-between;gap:12px"><span style="color:#9ca3af">${e}</span><span>${t}</span></div>`}getColor(e){switch(e){case"Good":return Pe.good;case"Fair":return Pe.fair;case"Poor":return Pe.poor}}update(e){if(this.lastMetrics=e,!this.container)return;this.container.setAttribute("aria-label",`Network quality: ${e.qualityLevel}`);let t=this.getColor(e.qualityLevel),n=e.qualityLevel==="Good"?3:e.qualityLevel==="Fair"?2:1;this.bars.forEach((i,r)=>{i.style.background=r<n?t:Pe.inactive}),this.visibility==="when-degraded"?this.container.style.display=e.qualityLevel==="Good"?"none":"flex":this.container.style.display="flex",this.panelVisible&&(this.updatePanel(),this.positionPanel())}destroy(){this.container&&(this.container.removeEventListener("click",this.onClickBound),this.container.removeEventListener("mousedown",this.onMouseEventBound),this.container.removeEventListener("mouseup",this.onMouseEventBound),this.container.removeEventListener("mouseenter",this.onMouseEnterBound),this.container.removeEventListener("mouseleave",this.onMouseLeaveBound),this.container.remove(),this.container=void 0),this.originalParentPosition!==void 0&&(this.videoContainerElement.style.position=this.originalParentPosition,this.originalParentPosition=void 0),clearTimeout(this.hoverHideTimeout),this.panel&&(this.panel.removeEventListener("mouseenter",this.onMouseEnterBound),this.panel.removeEventListener("mouseleave",this.onMouseLeaveBound),this.panel.remove(),this.panel=void 0),document.removeEventListener("click",this.onDocumentClickBound),this.bars=[],this.panelVisible=!1,this.lastMetrics=void 0}};var Pn=class{constructor(e,t,n){this.session=e;this.connectionUrl=t;this.videoContainerElement=n;this.config=e.config,this.clientMessages=e.messages,this._audioUpstreamMode=G(this.config.audioUpstreamMode)}session;connectionUrl;videoContainerElement;stream;messages=new io;videoElement;audioElement;videoInitialized=!1;dataChannelOpen=!1;sceneReady=!1;maxReconnectAttempts=4;reconnectionAttempts=0;allowReconnection=!0;reconnectTimeoutId;baseReconnectDelayMs=500;maxReconnectDelayMs=1e4;audioStatsInternal;freezeCount=0;lastDecodedFrames=0;lastCheckTime=Date.now();audioStatsAnalyzer;networkQualityInterval;networkIndicator;config;clientMessages;_audioUpstreamMode;get audioUpstreamMode(){return this._audioUpstreamMode}init(){p.info("Connection config",{connectionUrl:this.connectionUrl,forceTURN:this.config.forceTURN}),this.videoContainerElement||(this.videoContainerElement=document.createElement("div"),document.body.appendChild(this.videoContainerElement)),this.clientMessages?.next(new si);let e=re(this.audioUpstreamMode);this.audioUpstreamMode!=="speech-recognition-service"&&p.info(`audioUpstreamMode='${this.audioUpstreamMode}' is beta; behaviour may change.`);let t=new zt({initialSettings:{AutoConnect:!1,AutoPlayVideo:!1,ForceTURN:this.config.forceTURN,HoveringMouse:!1,KeyboardInput:!1,MaxReconnectAttempts:0,MouseInput:!1,ss:this.connectionUrl,StartVideoMuted:!0,TouchInput:!1,UseMic:e,WaitForStreamer:!0}});this.stream=new xe(t,{videoElementParent:this.videoContainerElement}),d.InitLogging(K.Warning,!1);let n=function(){let i=t.getTextSettingValue($.SignallingServerUrl);return t.isFlagEnabled(h.BrowserSendOffer)&&(i+=(i.includes("?")?"&":"?")+h.BrowserSendOffer+"=true"),i};this.stream.setSignallingUrlBuilder(n),this.addStreamHandlers(),this.stream.connect(),this.addWebSocketHandlers()}addStreamHandlers(){this.stream?.addEventListener("videoInitialized",this.handleVideoInitialized.bind(this)),this.stream?.addEventListener("dataChannelOpen",this.handleDataChannelOpen.bind(this)),this.stream?.addEventListener("webRtcFailed",this.handleWebRtcFailed.bind(this)),this.stream?.addEventListener("webRtcDisconnected",this.handleWebRtcDisconnected.bind(this)),this.stream?.addEventListener("statsReceived",this.handleWebRtcStats.bind(this)),this.stream?.addResponseEventListener("response-listener",this.handleDataChannelMessage.bind(this)),this.stream?.addEventListener("videoEncoderAvgQP",({data:{avgQP:e}})=>{p.trace("WebRTC: VideoEncoderAvgQP - lower is better, ranges from 0 to 51:",e)}),this.stream?.addEventListener("webRtcAutoConnect",()=>{p.debug("WebRTC: AutoConnect triggered")}),this.stream?.addEventListener("webRtcConnected",this.handleWebRtcConnectedMessage.bind(this)),this.stream?.addEventListener("statsReceived",({data:{aggregatedStats:e}})=>{p.trace("WebRTC: StatsReceived",e)}),this.stream?.addEventListener("webRtcTCPRelayDetected",()=>{p.warn("WebRTC: Stream quailty likely degraded due to network enviroment, stream is relayed over TCP.")})}addWebSocketHandlers(){let e=this.stream?.signallingProtocol?.transport;e?.webSocket?.addEventListener("error",this.handleWebSocketError.bind(this)),e?.webSocket?.addEventListener("open",()=>{e.webSocket?.send(JSON.stringify({type:"client_info",uneeqJsSdkVersion:Is}))}),this.stream?.signallingProtocol.on("error",t=>{p.error("Signaling: Received error message from server",t),this.clientMessages?.next(new q(`Signaling server error: ${t}`))}),this.stream?.signallingProtocol.on("index_in_queue",this.handleIndexInQueueMessage.bind(this)),this.stream?.signallingProtocol.on("renderer_taken",this.handleRendererTakenMessage.bind(this)),this.stream?.signallingProtocol.on("renderer_gone",this.handleRendererGoneEvent.bind(this)),this.stream?.signallingProtocol.on("switch_renderer_request",this.handleSwitchRendererRequestEvent.bind(this)),this.stream?.signallingProtocol.on("customer_concurrency_limit_reached",this.handleCustomerConcurrencyLimitReachedMessage.bind(this)),this.stream?.signallingProtocol.on("renderer_error",this.handleRendererErrorMessage.bind(this)),this.stream?.signallingProtocol.on("config",this.checkForStubbedTurnConfig.bind(this))}checkForStubbedTurnConfig(e){let t=e?.peerConnectionOptions?.iceServers??[];p.info("Signaling: Received ice config message with urls:",t.map(i=>({urls:i.urls}))),t.some(i=>i.username?.includes("disabled")&&i.urls?.some(r=>r.includes("0.0.0.0")))&&p.warn("Signaling: TURN server configuration is stubbed (turn:0.0.0.0 with disabled credentials). This should be intentional, is intended for locally run renderers e.g. kiosk, miniprem etc.")}handleWebSocketError(e){p.error("Signaling: WebSocket error",p.serialiseError(e)),this.reconnectIfSafe(e)}handleVideoInitialized(){p.info("Video initialized."),this.videoElement=this.videoContainerElement?.getElementsByTagName("video")[0],this.audioElement=this.stream?.webRtcController?.streamController?.audioElement,this.audioStatsAnalyzer=new pe(this.stream,this.videoElement,this.audioElement);let e=this.getAudioPlaybackElement();if(e&&this.config.speakerDeviceId&&this.setSpeakerDevice(e,this.config.speakerDeviceId),this.videoElement)this.videoElement.muted=!0,this.videoElement.play().then(()=>{this.playAudioElement()}).catch(t=>{if(t instanceof DOMException&&t.name==="NotAllowedError")p.warn("Video autoplay blocked by browser. Requesting user gesture to resume playback."),this.clientMessages?.next(new li);else{let n="Fatal Error: Digital Human video cannot be played.";p.error(n,p.serialiseError(t)),this.clientMessages?.next(new q(n)),this.endSession(Ls,!0)}}),this.videoInitialized=!0,this.messages.next(new Tn),this.reconnectionAttempts=0,this.clearReconnectTimer();else{let t="Fatal Error: Video element not found.";p.error(t),this.clientMessages?.next(new q(t)),this.endSession(Ls,!0)}setTimeout(()=>{this.clientMessages?.next(new ti)},Os)}getAudioPlaybackElement(){return xn(this.videoElement)?this.videoElement:this.audioElement}playAudioElement(){let e=this.getAudioPlaybackElement();if(!e){this.handleMissingAudioElement();return}let t=e===this.videoElement;e.muted=!1,e.play().then(()=>{p.info("Audio playback successfully started."),this.clientMessages?.next(new Kn)}).catch(n=>{p.warn("Audio cannot be played.",n),this.clientMessages?.next(new Fe),t?(e.muted=!0,e.play().then(()=>{this.clientMessages?.next(new Oe)}).catch(i=>{p.warn("Muted video reveal also blocked.",i),this.clientMessages?.next(new q(`Video playback failed: ${i}`))})):this.clientMessages?.next(new Oe)})}resumeVideoPlayback(){if(!this.videoElement){p.warn("resumeVideoPlayback called but no video element available");return}this.videoElement.play().then(()=>{this.playAudioElement()}).catch(e=>{p.error("Video playback failed after user gesture",p.serialiseError(e)),this.clientMessages?.next(new q("Video playback failed after user gesture")),this.endSession(mr,!0)})}pauseAudioElement(){let e=this.getAudioPlaybackElement();if(!e){this.handleMissingAudioElement();return}e===this.videoElement?e.muted=!0:e.pause(),this.clientMessages?.next(new Fe)}muteUpstreamMic(){if(!re(this.audioUpstreamMode)){p.warn(`muteUpstreamMic called in '${this.audioUpstreamMode}' mode \u2014 no PS upstream audio track to mute; ignoring.`);return}if(!this.stream){p.warn("muteUpstreamMic called before PixelStreaming stream is initialised; ignoring.");return}this.stream.muteMicrophone()}unmuteUpstreamMic(){if(!re(this.audioUpstreamMode)){p.warn(`unmuteUpstreamMic called in '${this.audioUpstreamMode}' mode \u2014 no PS upstream audio track to unmute; ignoring.`);return}if(!this.stream){p.warn("unmuteUpstreamMic called before PixelStreaming stream is initialised; ignoring.");return}this.stream.unmuteMicrophone(!1)}setSpeakerDevice(e,t){let n=e;n.setSinkId?n.setSinkId(t).then(()=>{p.info(`Speaker device set to: ${t}`)}).catch(i=>{p.error(`Failed to set speaker device: ${t}`,p.serialiseError(i))}):p.error("setSinkId not supported in this browser, cannot set speaker device")}handleMissingAudioElement(){let e="Error: Digital Human audio element not found, cannot play audio.";p.error(e),this.clientMessages?.next(new q(e))}startAudioStatsMonitor(e=5e3){this.stopAudioStatsMonitor(),p.info("Starting audio stats monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new pe(this.stream,this.videoElement,this.audioElement)),this.audioStatsInternal=setInterval(()=>{this.audioStatsAnalyzer?.analyzeAudioStats().catch(t=>{p.error("Error analyzing audio stats",p.serialiseError(t))})},e)}stopAudioStatsMonitor(){this.audioStatsInternal&&clearInterval(this.audioStatsInternal)}startNetworkQualityMonitor(e){this.stopNetworkQualityMonitor(),p.info("Starting network quality monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new pe(this.stream,this.videoElement,this.audioElement)),this.videoContainerElement&&e.visibility!=="hidden"&&(this.networkIndicator=new In(this.videoContainerElement,e));let t=e.collectionIntervalMs??3e3;this.networkQualityInterval=setInterval(()=>{this.audioStatsAnalyzer?.collectNetworkQuality(e).then(n=>{n&&(this.networkIndicator?.update(n),this.clientMessages?.next(new ai(n)))}).catch(n=>{p.error("Error collecting network quality",p.serialiseError(n))})},t)}stopNetworkQualityMonitor(){this.networkQualityInterval&&(clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0),this.networkIndicator&&(this.networkIndicator.destroy(),this.networkIndicator=void 0)}handleDataChannelOpen(){p.info("DataChannelOpen"),this.dataChannelOpen=!0,this.messages.next(new En)}handleWebRtcFailed(e){p.error("WebRTC failed",e),this.reconnectIfSafe(e)}handleWebRtcDisconnected(e){p.warn(`WebRTC disconnected, message: ${e?.data?.eventString}, allowClickToReconnect: ${e?.data?.allowClickToReconnect}`),this.reconnectIfSafe(e)}handleWebRtcStats(e){let t=new kn(e.data.aggregatedStats);this.messages.next(t);let n=e.data.aggregatedStats.inboundVideoStats?.framesDecoded??0;this.checkForFreeze(n)}checkForFreeze(e){let t=Date.now();if(this.lastDecodedFrames===0&&e===0){p.debug("[WebRTC] Waiting for first video frame...");return}if(e===this.lastDecodedFrames){this.freezeCount++;let n=((t-this.lastCheckTime)/1e3).toFixed(1);p.warn(`[WebRTC] Video FROZEN for ${n}s (count=${this.freezeCount})`),this.freezeCount>=3&&(p.error("[WebRTC] Video frozen 3 times in a row, transferring session..."),this.session.sessionTransferManager.transferSession(),this.freezeCount=0)}else this.freezeCount=0,this.lastDecodedFrames=e,this.lastCheckTime=t}clearReconnectTimer(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=void 0)}scheduleReconnect(){let e=Math.min(this.baseReconnectDelayMs*Math.pow(2,this.reconnectionAttempts),this.maxReconnectDelayMs);p.info(`Scheduling reconnection attempt ${this.reconnectionAttempts} in ${e}ms`),this.reconnectTimeoutId=setTimeout(()=>{p.info(`Executing reconnection attempt ${this.reconnectionAttempts}`),this.reconnectTimeoutId=void 0,this.videoInitialized=!1,this.dataChannelOpen=!1,this.sceneReady=!1,this.audioStatsAnalyzer?.resetStats(),this.stream?.reconnect()},e)}reconnectIfSafe(e){try{this.allowReconnection&&!this.reconnectTimeoutId?(p.debug("Checking if should attempt reconnection after event",e),this.reconnectionAttempts<this.maxReconnectAttempts?(this.reconnectionAttempts++,this.clientMessages?.next(new ei),this.scheduleReconnect()):(p.info("Max reconnection attempts reached. Ending session."),this.clientMessages?.next(new Zn),this.endSession(Ps,!1))):p.warn("Reconnection already scheduled or reconnecting is disabled")}catch(t){p.error("Error during reconnection attempt",p.serialiseError(t)),this.clientMessages?.next(new q("Error during reconnection attempt")),this.endSession(Ps,!1)}}handleDataChannelMessage(e){p.trace("Signaling: Received data channel message",e);try{let t=JSON.parse(e);if(t.type!==void 0)this.messages.next(new Rn(t));else throw new Error("Signaling: Engine response missing type")}catch(t){p.error("Signaling: Failed to parse engine response",p.serialiseError(t))}}handleIndexInQueueMessage(e){try{let n=Number(e.message);this.clientMessages?.next(new Wn(n))}catch(t){p.error("Signaling: Failed to parse position in queue message",p.serialiseError(t))}}handleRendererTakenMessage(e){try{let t=e;this.clientMessages?.next(new Yn(t.message)),p.info("Signaling: Renderer taken event",t.message)}catch(t){p.error("Signaling: Failed to parse renderer taken message",p.serialiseError(t))}}handleWebRtcConnectedMessage(){this.clientMessages?.next(new ri),p.info("Signaling: WebRTC connected")}handleRendererGoneEvent(e){p.info("Signaling: Renderer gone event",e),this.reconnectIfSafe(e)}handleSwitchRendererRequestEvent(e){p.info("Signaling: Renderer switch renderer request event",e),this.session.sessionTransferManager.transferSession()}handleCustomerConcurrencyLimitReachedMessage(e){p.warn("Signaling: Customer concurrency limit reached message received",e),this.clientMessages?.next(new oi)}handleRendererErrorMessage(e){try{let t=e,n=t.code??-1,i=t.message??"An unknown renderer error occurred";p.error(`Signaling: Renderer error received - code: ${n}, message: ${i}`),this.clientMessages?.next(new Ae(n,i)),this.endSession(Ds,!0)}catch(t){p.error("Signaling: Failed to parse renderer error message",p.serialiseError(t)),this.clientMessages?.next(new Ae(-1,"An unknown renderer error occurred")),this.endSession(Ds,!0)}}socketSend(e){p.trace("Signaling: Sending socket message",e),this.stream?.signallingProtocol?.transport?.webSocket?.send(JSON.stringify(e))}dataSend(e){let t=e.toJSON();if(t.action==="chat_prompt"){let n=t.data?.requestId;p.info(`Signaling: Sending data channel message \u2014 action=chat_prompt, requestId=${n??"unknown"}`),(!(e instanceof se)||e.shouldEmitPromptRequest)&&this.clientMessages?.next(new Gn(t.data))}else p.info("Signaling: Sending data channel message",JSON.stringify(t));this.stream?.emitUIInteraction(e)}dataSendBinary(e){p.info("Signaling: Sending data channel binary message");let t=this.uint8ToBase64(e);this.stream?.emitUIInteraction(t)}uint8ToBase64(e){let t="",n=e.byteLength;for(let i=0;i<n;i++)t+=String.fromCharCode(e[i]);return btoa(t)}endSession(e=pr,t=!0){p.info("Signaling: Ending session"),this.clearReconnectTimer(),this.stopNetworkQualityMonitor(),this.socketSend({message:e,type:"client_gone",sessionId:this.config.sessionId}),this.streamDisconnect(),p.info("Session has ended, reason: "+e),t&&this.clientMessages?.next(new qn(e))}streamDisconnect(){p.info("Signaling: Disconnecting stream"),this.stopNetworkQualityMonitor(),this.stopAudioStatsMonitor(),this.allowReconnection=!1,this.clearReconnectTimer();let e=this.stream?.webRtcController?.statsTimerHandle;e&&window.clearInterval(e);let t=this.stream?.webRtcController?.peerConnectionController;if(t?.peerConnection){t.peerConnection.getReceivers=()=>[];let n=t.peerConnection;Object.defineProperty(t,"peerConnection",{get:()=>n,set:()=>{},configurable:!0})}this.stream?.disconnect(),this.dataChannelOpen=!1,this.videoInitialized=!1,this.sceneReady=!1}startSoftSwitch(){p.info("Signaling: Start soft switching"),this.clientMessages?.next(new ni)}stopSoftSwitch(){p.info("Signaling: Stop soft switching"),this.clientMessages?.next(new ii)}};import{Subject as so}from"rxjs";var wr=(o=>(o.CloseUp="close_up",o.LooseCloseUp="loose_close_up",o.TightMediumShot="tight_medium_shot",o.MediumShot="medium_shot",o.MediumFullShot="medium_full_shot",o.FullShot="full_shot",o))(wr||{}),Cr=(i=>(i.Left="left",i.Right="right",i.Center="center",i.Centre="centre",i))(Cr||{}),Le=class{constructor(e,t=2e3,n=z()){this.position=e;this.duration=t;this.requestId=n}position;duration;requestId;toJSON(){return{action:"camera_to_anchor",data:{requestId:this.requestId,position:this.position,transition_duration_ms:this.duration}}}};var Ln=class{constructor(e,t=z()){this.avatarId=e;this.requestId=t}avatarId;requestId;toJSON(){return{action:"change_avatar",data:{id:this.avatarId,requestId:this.requestId}}}};var Dn=class{constructor(e,t=z()){this.url=e;this.requestId=t}url;requestId;toJSON(){return{action:"load_background",data:{url:this.url,requestId:this.requestId}}}};var On=class{constructor(e,t=z()){this.actionName=e;this.requestId=t}actionName;requestId;toJSON(){return{action:"trigger_action",data:{action_name:this.actionName,requestId:this.requestId}}}};var Fn=class{constructor(e){this.session=e;this.addTransferSessionListener()}session;isTransferSessionInProgress=!1;addTransferSessionListener(){this.isTransferSessionInProgress=!1,document.addEventListener("keydown",e=>{e.ctrlKey&&e.shiftKey&&e.key.toLowerCase()==="y"&&(p.info("Session transfer via keyboard shortcut triggered"),this.transferSession())})}transferSession(){if(this.isTransferSessionInProgress){p.warn("Transfer already in progress, skipping");return}this.isTransferSessionInProgress=!0,p.info("Beginning session transfer"),this.session.config.videoContainerElement&&(this.session.config.videoContainerElement.querySelectorAll("#freezeFrame,#streamingVideo").forEach(n=>{n.remove()}),this.session.signaling&&this.session.signaling.streamDisconnect()),this.session.createSignaling(this.session.config.videoContainerElement??document.createElement("div")).init()}switchLiveVideo(e,t){p.info("New signaling video is ready for transfer"),this.session.signaling&&e&&t.videoElement&&(t.videoElement.classList.add("incoming-video"),this.session.signaling.videoElement&&t.videoElement&&e?.appendChild(t.videoElement),this.session.signaling.startSoftSwitch(),setTimeout(()=>{this.session.signaling?.streamDisconnect(),this.session.signaling=t,this.isTransferSessionInProgress=!1,this.session.signaling?.stopSoftSwitch(),p.info("Session transfer complete")},1e3))}};var Mr=[1103,1200,1402];var Os=750,An=class{constructor(e){this.config=e;this.sessionTransferManager=new Fn(this),this._audioUpstreamMode=G(this.config.audioUpstreamMode)}config;id;signaling;messages=new so;speechRec;promptMetadata={};audioStreamId;sessionTransferManager;jwt;welcomeRequested=!1;resolutionLogged=!1;sttPausedByHost=!1;_audioUpstreamMode;get audioUpstreamMode(){return this._audioUpstreamMode}updatePromptMetadata(e){try{JSON.parse(JSON.stringify(e)),this.promptMetadata.custom=e,this.messages.next(new Qn(this.promptMetadata))}catch(t){p.error("Error parsing custom metadata",e,p.serialiseError(t))}}setEnableMicrophone(e){let t=this.audioUpstreamMode;this.config.enableMicrophone=e,this.sttPausedByHost=!1;let n=!1;J(t)&&(this.speechRec?(e?this.speechRec.startRecognition():this.speechRec.stopRecognition(),n=!0):p.warn("setEnableMicrophone: STT leg is configured but speech recognition is not initialised yet")),re(t)&&(this.signaling?(e?this.signaling.unmuteUpstreamMic():this.signaling.muteUpstreamMic(),n=!0,J(t)||this.messages.next(new jn(e))):p.warn("setEnableMicrophone: PS leg is configured but signaling is not initialised yet")),n||p.warn(`setEnableMicrophone(${e}) had nothing to do in mode '${t}' \u2014 session not ready?`)}pauseSpeechRecognition(){return this.sttPausedByHost=!0,this.speechRec?this.speechRec.pause():(p.warn("pauseSpeechRecognition: pause intent recorded, but speech recognition is not initialised yet \u2014 nothing to pause"),!1)}resumeSpeechRecognition(){return this.sttPausedByHost=!1,this.speechRec?this.speechRec.resume():(p.warn("resumeSpeechRecognition: pause intent cleared, but speech recognition is not initialised yet \u2014 nothing to resume"),!1)}setCameraAnchorDistance(e,t=0,n=this.signaling){this.config.cameraAnchorDistance=e,n?.dataSend(new Le(e,t))}setCameraAnchorHorizontal(e,t=0,n=this.signaling){this.config.cameraAnchorHorizontal=e,n?.dataSend(new Le(e,t))}changeAvatar(e,t=this.signaling){t?.dataSend(new Ln(e))}loadBackground(e,t=this.signaling){t?.dataSend(new Dn(e))}userStartSpeaking(e=this.signaling){e?.dataSend(new ci("start"))}userStopSpeaking(e=this.signaling){e?.dataSend(new ci("stop"))}triggerAction(e,t=this.signaling){t?.dataSend(new On(e))}resumeVideoPlayback(){this.signaling?.resumeVideoPlayback()}createSession(){this.messages.subscribe(e=>{if(this.config.messageHandler&&this.config.messageHandler(e),e.uneeqMessageType==="SoftSwitchFinished"||e.uneeqMessageType==="SessionReconnectingFinished"){if(!J(this.audioUpstreamMode))return;if(this.config.enableMicrophone&&!this.sttPausedByHost)e.uneeqMessageType==="SessionReconnectingFinished"?(p.info("Session, resuming speech recognition after reconnect"),this.speechRec?.resume()):(p.info("Session, restarting speech recognition after soft switch"),this.speechRec?.startRecognition());else{let t=e.uneeqMessageType==="SoftSwitchFinished"?"soft switch":"reconnect",n=this.sttPausedByHost?"paused by host":"microphone disabled";p.info(`Session, skipping speech recognition restart after ${t} (${n})`)}}}),this.id=this.config.sessionId,this.jwt=this.config.sessionToken,p.info("Session created with id: "+this.id),this.updatePromptMetadata(this.config.customMetadata||{}),this.promptMetadata=this.initMetadata(),this.listenForTabClosure(),this.signaling=this.createSignaling(this.config.videoContainerElement),this.signaling.init()}createSignaling(e=document.createElement("div")){let t=new URLSearchParams({token:this.jwt});this.config.backgroundUrl&&t.append("backgroundUrl",this.config.backgroundUrl);let n=(this.config.connectionUrl+`/session-service/v1/ws/session?${t.toString()}`).replace("http://","ws://").replace("https://","wss://");p.debug("Socket URL:",n);let i=new Pn(this,n,e);return i.messages.subscribe(r=>{this.signalingEventHandler(r,i)}),i}signalingEventHandler(e,t){switch(e.type){case 0:{this.handleSessionReady(t);break}case 1:{this.handleSessionReady(t);break}case 2:{this.handleDataChannelMessage(e,t);break}case 5:{let n=e.stats;!this.resolutionLogged&&n.inboundVideoStats?.frameWidth&&n.inboundVideoStats?.frameHeight&&(p.info("Video resolution:",`${n.inboundVideoStats.frameWidth}x${n.inboundVideoStats.frameHeight}`),this.resolutionLogged=!0),this.config.webRtcStatsEmitMessages&&this.messages.next(new Hn(n)),this.config.webRtcStatsLogMessages&&p.info("WebRTC stats",n);break}}}handleSessionReady(e){p.debug(`Session ready check - videoInitialized: ${e.videoInitialized}, dataChannelOpen: ${e.dataChannelOpen}, sceneReady: ${e.sceneReady}`),e.videoInitialized&&e.dataChannelOpen&&e.sceneReady&&(e.reconnectionAttempts=0,this.setCameraAnchorDistance(this.config.cameraAnchorDistance,0,e),this.setCameraAnchorHorizontal(this.config.cameraAnchorHorizontal,0,e),setTimeout(()=>{this.sessionTransferManager.isTransferSessionInProgress&&this.config.videoContainerElement?this.sessionTransferManager.switchLiveVideo(this.config.videoContainerElement,e):(this.initSpeechRecognition(this.jwt),this.sendWelcomePrompt(),document.body.classList.add("uneeq-streaming-live")),this.messages.next(new _n(this.id)),this.config.networkIndicator&&e.startNetworkQualityMonitor(this.config.networkIndicator),this.config.webRtcStatsLogMessages&&e.startAudioStatsMonitor()},Os))}async initSpeechRecognition(e){if(!J(this.audioUpstreamMode)){p.info(`[STT] audioUpstreamMode='${this.audioUpstreamMode}' \u2014 skipping STT provider initialisation (no STT leg in this mode).`);return}if(this.speechRec){p.warn("Speech recognition already initialized");return}let t=this.config.speechRecognitionProvider||"google";p.info(`[STT] Config speechRecognitionProvider: "${this.config.speechRecognitionProvider}", resolved provider: "${t}"`),t!=="google"&&t!=="deepgram"&&(p.warn(`Invalid speechRecognitionProvider value: "${String(t)}". Supported values are "google" or "deepgram". Defaulting to "google".`),t="google",this.config.speechRecognitionProvider="google"),p.info(`[STT] Using provider: ${t}`);try{this.speechRec=await(t==="deepgram"?this.createDeepgramSTT(e):this.createGoogleSTT(e))}catch(n){p.error("[STT] Failed to initialise speech recognition provider",p.serialiseError(n));return}this.config.enableMicrophone&&!this.sttPausedByHost&&this.speechRec&&this.speechRec.startRecognition()}async createGoogleSTT(e){let t=this.getSpeechOptions(e);p.debug("Initializing Google STT (speech-recognition-service)");let{GoogleSTT:n}=await import("./chunks/google-stt-AOUGMCIB.js");return new n(t)}async createDeepgramSTT(e){let t=this.config.deepgramConfig||{};if(this.isFluxModel(t.model))return this.createDeepgramFluxSTT(e);p.warn("Deepgram STT is currently in beta, is subject to change, and is not suitable for production use"),p.debug("Initializing Deepgram STT");let n={connectionUrl:this.config.connectionUrl,jwtToken:e,sessionId:this.id,model:t.model,language:t.language,smartFormat:t.smartFormat,interimResults:t.interimResults,utteranceEndMs:t.utteranceEndMs,vadEvents:t.vadEvents,encoding:t.encoding,sampleRate:t.sampleRate,channels:t.channels,fillerWords:t.fillerWords,endpointing:t.endpointing,interruptionWordThreshold:t.interruptionWordThreshold,echoCancellation:t.microphone?.echoCancellation,noiseSuppression:t.microphone?.noiseSuppression,autoGainControl:t.microphone?.autoGainControl,microphoneDeviceId:this.config.microphoneDeviceId,promptMetadata:this.promptMetadata,messages:this.messages,sendMessage:r=>{this.signaling?.dataSend(r)},enableInterrupt:this.config.enableInterruptBySpeech,safetyNetTimeoutMs:t.safetyNetTimeoutMs,keyterms:t.keyterms,noDelay:t.noDelay},{DeepgramSTT:i}=await import("./chunks/deepgram-stt-Y67Z46KN.js");return new i(n)}isFluxModel(e){return e!==void 0&&e.toLowerCase().startsWith("flux")}async createDeepgramFluxSTT(e){p.debug("Initializing Deepgram Flux STT (v2 API)");let t=this.config.deepgramConfig||{},n={connectionUrl:this.config.connectionUrl,jwtToken:e,sessionId:this.id,model:t.model,language:t.language,eotThreshold:t.eotThreshold,eagerEotThreshold:t.eagerEotThreshold,eotTimeoutMs:t.eotTimeoutMs,eagerMaxTurnDurationMs:t.eagerMaxTurnDurationMs,keyterms:t.keyterms,safetyNetTimeoutMs:t.safetyNetTimeoutMs,echoCancellation:t.microphone?.echoCancellation,noiseSuppression:t.microphone?.noiseSuppression,autoGainControl:t.microphone?.autoGainControl,microphoneDeviceId:this.config.microphoneDeviceId,promptMetadata:this.promptMetadata,messages:this.messages,sendMessage:r=>{this.signaling?.dataSend(r)}},{DeepgramFluxSTT:i}=await import("./chunks/deepgram-flux-stt-NOTQ2K35.js");return new i(n)}getSpeechOptions(e){return{apiUrl:this.config.connectionUrl,assetBasePath:this.config.assetBasePath,enableInterrupt:this.config.enableInterruptBySpeech,enableVad:this.config.enableVad,jwtToken:e,hintPhrases:this.config.speechRecognitionHintPhrases,hintPhrasesBoost:this.config.speechRecognitionHintPhrasesBoost,locales:this.config.speechRecognitionLocales,messages:this.messages,promptMetadata:this.promptMetadata,sessionId:this.id,sendMessage:t=>{this.signaling?.dataSend(t)},microphoneDeviceId:this.config.microphoneDeviceId}}initMetadata(){return{userSpokenLocale:"",browserDetectedLocales:this.config.speechRecognitionLocales,userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userScreenWidth:window.screen.availWidth,userScreenHeight:window.screen.availHeight,userAgent:navigator.userAgent,personaId:this.config.personaId,custom:this.config.customMetadata}}handleDataChannelMessage(e,t){switch(p.debug("Processing data channel message",e),e.msg.type){case"nlp_prompt_result":this.messages.next(new Jn(e.msg));break;case"avatar_started_speaking":{this.messages.next(new Bn);break}case"avatar_stopped_speaking":{this.messages.next(new Vn);break}case"error":{p.error(`an error has occurred - ${JSON.stringify(e.msg)}`),this.handleChannelMessageError(e.msg);break}case"scene_ready":{p.debug("Scene is ready"),t.sceneReady=!0,this.handleSessionReady(t),this.messages.next(new Xn);break}case"speech_event":{this.messages.next(new zn(e.msg));break}case"session_ended":{let n=e.msg.reason==="UserInactivity"?ur:e.msg.reason;this.signaling?.endSession(n),this.signaling=void 0;break}case"speech_stream_opened":{this.audioStreamId=e.msg.streamId;break}case"speech_stream_closed":{e.msg.streamId===this.audioStreamId?this.audioStreamId=void 0:p.warn("Received SpeechStreamClosed message for unexpected streamId",e.msg.streamId);break}}}handleChannelMessageError(e){let t=e?.message?.trim()||"An unknown error occurred";e&&Mr.includes(e.code)?this.messages.next(new $n(e)):this.messages.next(new q(t))}sendWelcomePrompt(){p.debug("Checking if the welcome prompt should be sent. Welcome requested already = "+this.welcomeRequested+". Prompt = ",this.config.welcomePrompt),this.config.welcomePrompt&&this.config.welcomePrompt.length>0&&!this.welcomeRequested&&(this.welcomeRequested=!0,this.signaling?.dataSend(new se(this.config.welcomePrompt,this.promptMetadata)))}listenForTabClosure(){window.addEventListener("beforeunload",()=>{p.info("Window unload detected, ending session."),this.signaling?.endSession(),this.signaling=void 0})}};var Nn=class{constructor(e,t=z()){this.prompt=e;this.requestId=t}prompt;requestId;toJSON(){return{action:"speak",data:{requestId:this.requestId,prompt:this.prompt}}}};var me=class{constructor(e,t,n={},i=z()){this.action=e;this.streamId=t;this.metadata=n;this.requestId=i}action;streamId;metadata;requestId;toJSON(){return{action:"speech_stream",data:{requestId:this.requestId,action:this.action,streamId:this.streamId,metadata:this.metadata}}}};var Un=class{constructor(e,t,n,i){this.command=e;this.enabled=t;this.category=n;this.verbosity=i}command;enabled;category;verbosity;toJSON(){let e={command:this.command,enabled:this.enabled};return this.category!==void 0&&(e.category=this.category),this.verbosity!==void 0&&(e.verbosity=this.verbosity),{action:"execute_command",data:e}}};async function Tr(s,e){try{if(s?.audioStreamId===void 0){p.warn("Audio stream is not open | Call openAudioStream() first");return}let t;if(typeof e=="string"){let o=typeof atob<"u"?atob(e):Buffer.from(e,"base64").toString("binary");t=new Uint8Array(o.length);for(let a=0;a<o.length;a++)t[a]=o.charCodeAt(a)}else if(e instanceof Uint8Array)t=e;else if(typeof Blob<"u"&&e instanceof Blob){let o=await e.arrayBuffer();t=new Uint8Array(o)}else{p.error("speakAudio: Unsupported audio type",e);return}let n=Uint8Array.from([1]),i=Uint8Array.from([s.audioStreamId]),r=new Uint8Array(2+t.length);r.set(n,0),r.set(i,1),r.set(t,2),s.signaling?.dataSendBinary(r)}catch(t){p.error("speakAudioSend: Error sending audio",t)}}var Fs=class{constructor(e){this.config=e;p.setLevel(e.logLevel??"info")}config;session;messageSubscription;init(){if(this.session){let e="Cannot initialize: session already active. Call endSession() first.";throw p.warn(e),new Error(e)}if(this.config.audioUpstreamMode!==void 0&&!_s(this.config.audioUpstreamMode)){let e=`Invalid audioUpstreamMode: '${String(this.config.audioUpstreamMode)}'. Allowed: 'speech-recognition-service' | 'pixel-streaming' | 'both'.`;throw p.error(e),new Error(e)}p.info(`Initializing Uneeq with config:', ${JSON.stringify(this.config)}, for UserAgent: ${navigator.userAgent}`),this.session=new An(this.config),this.session.createSession(),this.messageSubscription=this.session.messages.subscribe(e=>{e.uneeqMessageType==="SessionEnded"&&(p.info("Session ended, resetting session state"),this.resetSessionState())})}isSessionActive(){return this.session!==void 0}ensureSessionExists(){return this.session?.id?!0:(p.warn("Cannot perform action, session has not started."),!1)}chatPrompt(e){e&&e.trim()!==""&&this.ensureSessionExists()&&this.session?.signaling?.dataSend(new se(e,this.session?.promptMetadata))}speak(e){e&&e.trim()!==""&&this.ensureSessionExists()&&this.session?.signaling?.dataSend(new Nn(e))}openAudioStream(){let e=this.session;this.ensureSessionExists()&&e?.signaling?.dataSend(new me("open",e?.audioStreamId))}closeAudioStream(){let e=this.session;this.ensureSessionExists()&&e?.audioStreamId!==void 0&&e.signaling?.dataSend(new me("close",e.audioStreamId))}interruptAudioStream(){let e=this.session;this.ensureSessionExists()&&e?.audioStreamId!==void 0&&e.signaling?.dataSend(new me("interrupt",e.audioStreamId))}async speakAudio(e){this.ensureSessionExists()&&await Tr(this.session,e)}cameraAnchorDistance(e,t){this.ensureSessionExists()&&this.session?.setCameraAnchorDistance(e,t)}cameraAnchorHorizontal(e,t){this.ensureSessionExists()&&this.session?.setCameraAnchorHorizontal(e,t)}changeAvatar(e){e&&e.trim()!==""&&this.ensureSessionExists()&&this.session?.changeAvatar(e)}loadBackground(e){e&&e.trim()!==""&&this.ensureSessionExists()&&this.session?.loadBackground(e)}userStartSpeaking(){this.ensureSessionExists()&&this.session?.userStartSpeaking()}userStopSpeaking(){this.ensureSessionExists()&&this.session?.userStopSpeaking()}triggerAction(e){e&&e.trim()!==""&&this.ensureSessionExists()&&this.session?.triggerAction(e)}resumeVideoPlayback(){this.session?.resumeVideoPlayback()}executeCommand(e,t,n,i){this.ensureSessionExists()&&this.session?.signaling?.dataSend(new Un(e,t,n,i))}endSession(){this.ensureSessionExists()&&(this.session?.signaling?.endSession(),this.resetSessionState())}resetSessionState(){this.messageSubscription?.unsubscribe(),this.messageSubscription=void 0,this.session=void 0}unmuteDigitalHuman(){this.ensureSessionExists()&&(this.session?.signaling?.playAudioElement(),p.debug("Unmuted digital human."))}muteDigitalHuman(){this.ensureSessionExists()&&(this.session?.signaling?.pauseAudioElement(),p.debug("Muted digital human."))}stopSpeaking(){this.ensureSessionExists()&&this.session?.signaling?.dataSend(new Vs)}setCustomPromptMetadata(e){this.ensureSessionExists()&&this.session?.updatePromptMetadata(e)}enableMicrophone(e=!0){this.ensureSessionExists()&&this.session?.setEnableMicrophone(e)}pauseSpeechRecognition(){if(!this.ensureSessionExists())return!1;let e=G(this.config.audioUpstreamMode);if(!J(e))return p.warn(`pauseSpeechRecognition called in '${e}' mode \u2014 no STT leg to pause; ignoring. Use muteUpstreamMic() to silence the PS mic track.`),!1;let t=this.session?.pauseSpeechRecognition()??!1;return t instanceof Promise?!0:t}resumeSpeechRecognition(){if(!this.ensureSessionExists())return!1;let e=G(this.config.audioUpstreamMode);if(!J(e))return p.warn(`resumeSpeechRecognition called in '${e}' mode \u2014 no STT leg to resume; ignoring. Use unmuteUpstreamMic() to re-enable the PS mic track.`),!1;let t=this.session?.resumeSpeechRecognition()??!1;return t instanceof Promise?!0:t}muteUpstreamMic(){this.ensureSessionExists()&&this.session?.signaling?.muteUpstreamMic()}unmuteUpstreamMic(){this.ensureSessionExists()&&this.session?.signaling?.unmuteUpstreamMic()}setWebRtcStatsEnabled(e,t){this.session?.config&&(this.session.config.webRtcStatsEmitMessages=e,this.session.config.webRtcStatsLogMessages=t,p.info(`Setting up WebRtcStats: webRtcStatsEmitMessages: ${this.session.config.webRtcStatsEmitMessages}, webRtcStatsLogMessages: ${this.session.config.webRtcStatsLogMessages}`),t?this.session.signaling?.startAudioStatsMonitor():this.session.signaling?.stopAudioStatsMonitor())}setNetworkIndicatorEnabled(e){this.ensureSessionExists()&&(e?this.session?.signaling?.startNetworkQualityMonitor(e):this.session?.signaling?.stopNetworkQualityMonitor())}};export{Dr as AvatarAnswerMessage,Ur as AvatarInterruptedMessage,Bn as AvatarStartedSpeakingMessage,Vn as AvatarStoppedSpeakingMessage,wr as CameraAnchorDistance,Cr as CameraAnchorHorizontal,Qn as CustomMetadataUpdated,oi as CustomerConcurrencyLimitReachedMessage,Lr as DeviceErrorMessage,Fe as DigitalHumanMuted,Oe as DigitalHumanPlayedInMutedModeSuccess,Kn as DigitalHumanUnmuted,jn as EnableMicrophoneUpdatedMessage,Pr as LogLevel,Sr as NetworkIndicatorPopupTrigger,yr as NetworkIndicatorPosition,gr as NetworkIndicatorVisibility,fr as NetworkQualityLevel,ai as NetworkQualityMessage,Gn as PromptRequestMessage,Jn as PromptResultMessage,Ae as RendererErrorMessage,Xn as SceneReadyMessage,$n as SessionBackendErrorMessage,Yn as SessionConnectingMessage,Zn as SessionDisconnectedMessage,qn as SessionEndedMessage,q as SessionErrorMessage,_n as SessionLiveMessage,ti as SessionReconnectingFinishedMessage,ei as SessionReconnectingMessage,ni as SoftSwitchStartingMessage,ii as SoftSwitchStoppingMessage,zn as SpeechEventMessage,di as SpeechRecognitionProvider,Br as SpeechRecognitionTransientErrorMessage,Or as SpeechTranscriptionMessage,Is as UNEEQ_JS_SDK_VERSION,Fs as Uneeq,Bs as UneeqMessageType,Ar as UserStartedSpeakingMessage,Nr as UserStoppedSpeakingMessage,Fr as VadInterruptionAllowedMessage,li as VideoAutoplayBlockedMessage,si as VideoLayoutConfiguringMessage,Wn as WaitingInQueueMessage,ri as WebRtcConnectedMessage,Hn as WebRtcStatsMessage,G as resolveAudioUpstreamMode};
|