uneeq-js 3.13.3 → 3.13.4
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 +10 -10
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/session.d.ts +1 -0
- package/dist/uneeq.d.ts +1 -0
- package/dist/webrtc-data-channel/DataChannelAction.d.ts +2 -1
- package/dist/webrtc-data-channel/DataChannelActionType.d.ts +1 -0
- package/dist/webrtc-data-channel/messages/LoadBackground.d.ts +12 -0
- package/package.json +1 -1
- package/dist/esm/chunks/chunk-557JQDB4.js +0 -1
- package/dist/esm/chunks/chunk-DORXZBMU.js +0 -2
- package/dist/esm/chunks/chunk-QNPFEGCG.js +0 -1
- package/dist/esm/chunks/chunk-V5GQSIWD.js +0 -2
- package/dist/esm/chunks/deepgram-flux-stt-MHRGSAVD.js +0 -27
- package/dist/esm/chunks/deepgram-flux-stt-UPRNCBXC.js +0 -27
- package/dist/esm/chunks/deepgram-stt-BJWZFBHV.js +0 -1
- package/dist/esm/chunks/deepgram-stt-EO3Y4T3A.js +0 -1
- package/dist/esm/chunks/deepgram-stt-WX4KHFSO.js +0 -1
- package/dist/esm/chunks/google-stt-45HG42BE.js +0 -2486
- package/dist/esm/chunks/google-stt-P7QLHE5H.js +0 -2486
package/dist/esm/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as De,B as
|
|
1
|
+
import{A as De,B as jn,C as Qn,D as Gn,E as Xn,F as Jn,G as Yn,H as Zn,I as ei,J as ti,K as ni,L as ii,M as si,N as ri,O as oi,P as ai,Q as Oe,R as $,S as Fe,T as li,U as Us,b as Er,c as As,d as Rr,e as xr,f as p,g as Ns,h as Nn,i as kr,j as Ir,k as Pr,l as Lr,m as Dr,n as Un,o as Bn,p as Or,q as Vn,r as _n,s as Wn,t as j,u as Fr,v as Hn,w as zn,x as $n,y as qn,z as Kn}from"./chunks/chunk-6GQSOKKS.js";var cr=Er((ql,bs)=>{"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,21 +29,21 @@ 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
|
|
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 Ae:window.loggerContext?this.context=window.loggerContext:(this.context=new Ae,window.loggerContext=this.context))}},d=new
|
|
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 bs=="object"&&(bs.exports=y)});var ci=(t=>(t.Google="google",t.Deepgram="deepgram",t))(ci||{}),G=s=>s??"speech-recognition-service",se=s=>s==="pixel-streaming"||s==="both",X=s=>s==="speech-recognition-service"||s==="both",Bs=s=>s==="speech-recognition-service"||s==="pixel-streaming"||s==="both";import{ReplaySubject as Zr}from"rxjs";var q;(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"})(q||(q={}));var Ae=class{constructor(){this.logLevel=q.Debug,this.includeStack=!0}};var di=class{InitLogging(e,t){this.ValidateContext(),this.context.logLevel=e,this.context.includeStack=t}Debug(e){this.ValidateContext(),this.context.logLevel>=q.Debug&&this.CommonLog("Debug",e)}Info(e){this.ValidateContext(),this.context.logLevel>=q.Info&&this.CommonLog("Info",e)}Warning(e){this.ValidateContext(),this.context.logLevel>=q.Warning&&this.CommonLog("Warning",e)}Error(e){this.ValidateContext(),this.context.logLevel>=q.Error&&this.CommonLog("Error",e)}CommonLog(e,t){let n=`[${e}] - ${t}`;this.context.includeStack&&(n+=`
|
|
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 Ae:window.loggerContext?this.context=window.loggerContext:(this.context=new Ae,window.loggerContext=this.context))}},d=new di;var Ne=class{constructor(e){this._args=[],this._callback=e}handleEvent(e){this._callback(...this._args),this._args=[]}setArgs(...e){this._args=e}},re=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 Ne(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 Ne((...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 me=class extends re{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 fe=class extends re{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 _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 Ws(){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 _e(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 Ve=65536*65536;function di(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>=Ve&&(i=i+(n/Ve|0),n=n%Ve)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),[e,n,i]}function We(s,e){if(e>>>0<=2097151)return""+(Ve*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 hi(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 Hs(){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 k;function Fr(){let s=new DataView(new ArrayBuffer(8));k=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}Fr();function zs(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}var $s=/^-?[0-9]+$/,ze=4294967296,He=2147483648,$e=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 $e{static from(e){if(k)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=k.C(e);case"number":if(e===0)return this.ZERO;e=k.C(e);case"bigint":if(!e)return this.ZERO;if(e<k.UMIN)throw new Error("signed value for ulong");if(e>k.UMAX)throw new Error("ulong too large");return k.V.setBigUint64(0,e,!0),new s(k.V.getInt32(0,!0),k.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!$s.test(e))throw new Error("string is no integer");let[t,n,i]=di(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 k?this.toBigInt().toString():We(this.lo,this.hi)}toBigInt(){return zs(k),k.V.setInt32(0,this.lo,!0),k.V.setInt32(4,this.hi,!0),k.V.getBigUint64(0,!0)}};O.ZERO=new O(0,0);var L=class s extends $e{static from(e){if(k)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=k.C(e);case"number":if(e===0)return this.ZERO;e=k.C(e);case"bigint":if(!e)return this.ZERO;if(e<k.MIN)throw new Error("signed long too small");if(e>k.MAX)throw new Error("signed long too large");return k.V.setBigInt64(0,e,!0),new s(k.V.getInt32(0,!0),k.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!$s.test(e))throw new Error("string is no integer");let[t,n,i]=di(e);if(t){if(i>He||i==He&&n!=0)throw new Error("signed long too small")}else if(i>=He)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&He)!==0}negate(){let e=~this.hi,t=this.lo;return t?t=~t+1:e+=1,new s(t,e)}toString(){if(k)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+We(e.lo,e.hi)}return We(this.lo,this.hi)}toBigInt(){return zs(k),k.V.setInt32(0,this.lo,!0),k.V.setInt32(4,this.hi,!0),k.V.getBigInt64(0,!0)}};L.ZERO=new L(0,0);var qs={readUnknownField:!0,readerFactory:s=>new ui(s)};function Ks(s){return s?Object.assign(Object.assign({},qs),s):qs}var ui=class{constructor(e,t){this.varint64=Ws,this.uint32=Hs,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 Ar=34028234663852886e22,Nr=-34028234663852886e22,Ur=4294967295,Br=2147483647,Vr=-2147483648;function J(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>Br||s<Vr)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>Ur||s<0)throw new Error("invalid uint 32: "+s)}function oe(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>Ar||s<Nr))throw new Error("invalid float 32: "+s)}var js={writeUnknownFields:!0,writerFactory:()=>new pi};function Qs(s){return s?Object.assign(Object.assign({},js),s):js}var pi=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),hi(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){oe(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,hi(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 _e(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 _e(i,r,this.buf),this}uint64(e){let t=O.from(e);return _e(t.lo,t.hi,this.buf),this}};var Gs={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Xs={ignoreUnknownFields:!1};function Js(s){return s?Object.assign(Object.assign({},Xs),s):Xs}function Ys(s){return s?Object.assign(Object.assign({},Gs),s):Gs}var qe=Symbol.for("protobuf-ts/message-type");function mi(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 ge;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(ge||(ge={}));function Zs(s){var e,t,n,i;return s.localName=(e=s.localName)!==null&&e!==void 0?e:mi(s.name),s.jsonName=(t=s.jsonName)!==null&&t!==void 0?t:mi(s.name),s.repeat=(n=s.repeat)!==null&&n!==void 0?n:ge.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function er(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 Ke=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(!er(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 je=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=Ue(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(Bs(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 x=w;a.K==f.BOOL&&(x=x=="true"?!0:x=="false"?!1:x),x=this.scalar(x,a.K,V.STRING,a.name).toString(),u[x]=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&&oe(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 Vs(e)}}catch(o){r=o.message}this.assert(!1,i+(r?" - "+r:""),e)}};var Qe=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:oe(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 ye(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 Ge=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[x,U]=this.mapEntry(l,e,n);c[w][x]=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=ye(e.K);o=e.K==f.BOOL?l.toString():l}if(a===void 0)switch(e.V.kind){case"scalar":a=ye(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==ge.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 tr(s){let e=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},qe,{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]=ye(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 sr(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?nr(a,r,o):rr(a,r,o)))return!1;break;case"map":if(!(n.V.kind=="message"?ir(n.V.T(),Je(r),Je(o)):nr(n.V.kind=="enum"?f.INT32:n.V.T,Je(r),Je(o))))return!1;break;case"message":let l=n.T();if(!(n.repeat?ir(l,r,o):l.equals(r,o)))return!1;break}}return!0}var Je=Object.values;function rr(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 nr(s,e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!rr(s,e[n],t[n]))return!1;return!0}function ir(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 or=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),_r=or[qe]={},E=class{constructor(e,t,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=t.map(Zs),this.options=n??{},_r.value=this,this.messagePrototype=Object.create(null,or),this.refTypeCheck=new Ke(this),this.refJsonReader=new je(this),this.refJsonWriter=new Qe(this),this.refBinReader=new Ge(this),this.refBinWriter=new Xe(this)}create(e){let t=tr(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 sr(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=Ks(t);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,t){return this.internalJsonRead(e,Js(t))}fromJsonString(e,t){let n=JSON.parse(e);return this.fromJson(n,t)}toJson(e,t){return this.internalJsonWrite(e,Ys(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=Qs(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 ${Ue(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 fi=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}},Wr=new fi,gi=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}},Ye=new gi,yi=class extends E{constructor(){super("config",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"peerConnectionOptions",kind:"message",T:()=>Ye},{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=Ye.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&&Ye.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}},Ki=new yi,Si=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}},ji=new Si,bi=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}},Qi=new bi,vi=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}},Gi=new vi,wi=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}},Hr=new wi,Ci=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}},Xi=new Ci,Mi=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}},Ji=new Mi,Ti=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}},Yi=new Ti,Ei=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}},Zi=new Ei,Ri=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}},zr=new Ri,xi=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}},es=new xi,ki=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}},ts=new ki,Ii=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}},ns=new Ii,Pi=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}},is=new Pi,Li=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}},Ze=new Li,Di=class extends E{constructor(){super("iceCandidate",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"candidate",kind:"message",T:()=>Ze},{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=Ze.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&&Ze.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}},ss=new Di,Oi=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}},rs=new Oi,Fi=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}},Se=new Fi,Ai=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}},os=new Ai,Ni=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}},as=new Ni,Ui=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}},ls=new Ui,Bi=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}},cs=new Bi,Vi=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}},ds=new Vi,_i=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}},hs=new _i,Wi=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}},us=new Wi,Hi=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}},ps=new Hi,zi=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}},ms=new zi,$i=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}},fs=new $i,qi=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}},gs=new qi;var ar={answer:is,config:Ki,disconnectPlayer:rs,endpointId:Qi,endpointIdConfirm:Gi,iceCandidate:ss,identify:ji,listStreamers:Xi,offer:ns,ping:Se,playerConnected:es,playerCount:fs,playerDisconnected:ts,pong:os,stats:gs,streamerDisconnected:as,streamerList:Ji,subscribe:Yi,unsubscribe:Zi,layerPreference:ls,dataChannelRequest:cs,peerDataChannels:ds,peerDataChannelsReady:hs,streamerDataChannels:us,startStreaming:ps,stopStreaming:ms};var _={};Fs(_,{createMessage:()=>ys,validateMessage:()=>$r});function ys(s,e){let t=s.create();return t.type=s.typeName,e&&s.mergePartial(t,e),t}function $r(s){let e=!0;if(!s.type)return d.Error(`Parsed message has no type. Rejected. ${JSON.stringify(s)}`),null;let t=ar[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 be=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(ys(Se,{time:new Date().getTime()}))}onHeartbeatResponse(e){this.rtt=new Date().getTime()-e.time,this.alive=!0}};var et=class{static addVideoHeaderExtensionToSdp(e,t){let n=e.split(`
|
|
36
|
+
`+JSON.stringify(e,void 0,4))}};var P={};As(P,{answer:()=>ss,base_message:()=>Hr,config:()=>ji,dataChannelRequest:()=>ds,disconnectPlayer:()=>os,endpointId:()=>Gi,endpointIdConfirm:()=>Xi,iceCandidate:()=>rs,iceCandidateData:()=>Ze,identify:()=>Qi,layerPreference:()=>cs,listStreamers:()=>Ji,offer:()=>is,peerConnectionOptions:()=>Ye,peerDataChannels:()=>hs,peerDataChannelsReady:()=>us,ping:()=>Se,playerConnected:()=>ts,playerCount:()=>gs,playerDisconnected:()=>ns,pong:()=>as,startStreaming:()=>ms,stats:()=>ys,stopStreaming:()=>fs,streamerDataChannels:()=>ps,streamerDisconnected:()=>ls,streamerIdChanged:()=>zr,streamerList:()=>Yi,subscribe:()=>Zi,subscribeFailed:()=>$r,unsubscribe:()=>es});function Ue(s){let e=typeof s;if(e=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return e}function Vs(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}var Q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Be=[];for(let s=0;s<Q.length;s++)Be[Q[s].charCodeAt(0)]=s;Be[45]=Q.indexOf("+");Be[95]=Q.indexOf("/");function _s(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=Be[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 Ws(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 Hs(){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 _e(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 Ve=65536*65536;function hi(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>=Ve&&(i=i+(n/Ve|0),n=n%Ve)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),[e,n,i]}function We(s,e){if(e>>>0<=2097151)return""+(Ve*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 ui(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 k;function Ar(){let s=new DataView(new ArrayBuffer(8));k=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}Ar();function $s(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}var qs=/^-?[0-9]+$/,ze=4294967296,He=2147483648,$e=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 $e{static from(e){if(k)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=k.C(e);case"number":if(e===0)return this.ZERO;e=k.C(e);case"bigint":if(!e)return this.ZERO;if(e<k.UMIN)throw new Error("signed value for ulong");if(e>k.UMAX)throw new Error("ulong too large");return k.V.setBigUint64(0,e,!0),new s(k.V.getInt32(0,!0),k.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!qs.test(e))throw new Error("string is no integer");let[t,n,i]=hi(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 k?this.toBigInt().toString():We(this.lo,this.hi)}toBigInt(){return $s(k),k.V.setInt32(0,this.lo,!0),k.V.setInt32(4,this.hi,!0),k.V.getBigUint64(0,!0)}};O.ZERO=new O(0,0);var L=class s extends $e{static from(e){if(k)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=k.C(e);case"number":if(e===0)return this.ZERO;e=k.C(e);case"bigint":if(!e)return this.ZERO;if(e<k.MIN)throw new Error("signed long too small");if(e>k.MAX)throw new Error("signed long too large");return k.V.setBigInt64(0,e,!0),new s(k.V.getInt32(0,!0),k.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!qs.test(e))throw new Error("string is no integer");let[t,n,i]=hi(e);if(t){if(i>He||i==He&&n!=0)throw new Error("signed long too small")}else if(i>=He)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&He)!==0}negate(){let e=~this.hi,t=this.lo;return t?t=~t+1:e+=1,new s(t,e)}toString(){if(k)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+We(e.lo,e.hi)}return We(this.lo,this.hi)}toBigInt(){return $s(k),k.V.setInt32(0,this.lo,!0),k.V.setInt32(4,this.hi,!0),k.V.getBigInt64(0,!0)}};L.ZERO=new L(0,0);var Ks={readUnknownField:!0,readerFactory:s=>new pi(s)};function js(s){return s?Object.assign(Object.assign({},Ks),s):Ks}var pi=class{constructor(e,t){this.varint64=Hs,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 Nr=34028234663852886e22,Ur=-34028234663852886e22,Br=4294967295,Vr=2147483647,_r=-2147483648;function J(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>Vr||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>Br||s<0)throw new Error("invalid uint 32: "+s)}function oe(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>Nr||s<Ur))throw new Error("invalid float 32: "+s)}var Qs={writeUnknownFields:!0,writerFactory:()=>new mi};function Gs(s){return s?Object.assign(Object.assign({},Qs),s):Qs}var mi=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),ui(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){oe(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,ui(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 _e(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 _e(i,r,this.buf),this}uint64(e){let t=O.from(e);return _e(t.lo,t.hi,this.buf),this}};var Xs={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Js={ignoreUnknownFields:!1};function Ys(s){return s?Object.assign(Object.assign({},Js),s):Js}function Zs(s){return s?Object.assign(Object.assign({},Xs),s):Xs}var qe=Symbol.for("protobuf-ts/message-type");function fi(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 ge;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(ge||(ge={}));function er(s){var e,t,n,i;return s.localName=(e=s.localName)!==null&&e!==void 0?e:fi(s.name),s.jsonName=(t=s.jsonName)!==null&&t!==void 0?t:fi(s.name),s.repeat=(n=s.repeat)!==null&&n!==void 0?n:ge.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function tr(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 Ke=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(!tr(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 je=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=Ue(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(Vs(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 x=w;a.K==f.BOOL&&(x=x=="true"?!0:x=="false"?!1:x),x=this.scalar(x,a.K,V.STRING,a.name).toString(),u[x]=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&&oe(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 _s(e)}}catch(o){r=o.message}this.assert(!1,i+(r?" - "+r:""),e)}};var Qe=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:oe(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?Ws(t):o?"":void 0}}};function ye(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 Ge=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[x,U]=this.mapEntry(l,e,n);c[w][x]=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=ye(e.K);o=e.K==f.BOOL?l.toString():l}if(a===void 0)switch(e.V.kind){case"scalar":a=ye(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==ge.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 nr(s){let e=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},qe,{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]=ye(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 rr(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?ir(a,r,o):or(a,r,o)))return!1;break;case"map":if(!(n.V.kind=="message"?sr(n.V.T(),Je(r),Je(o)):ir(n.V.kind=="enum"?f.INT32:n.V.T,Je(r),Je(o))))return!1;break;case"message":let l=n.T();if(!(n.repeat?sr(l,r,o):l.equals(r,o)))return!1;break}}return!0}var Je=Object.values;function or(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 ir(s,e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!or(s,e[n],t[n]))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(!s.equals(e[n],t[n]))return!1;return!0}var ar=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),Wr=ar[qe]={},E=class{constructor(e,t,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=t.map(er),this.options=n??{},Wr.value=this,this.messagePrototype=Object.create(null,ar),this.refTypeCheck=new Ke(this),this.refJsonReader=new je(this),this.refJsonWriter=new Qe(this),this.refBinReader=new Ge(this),this.refBinWriter=new Xe(this)}create(e){let t=nr(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 rr(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=js(t);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,t){return this.internalJsonRead(e,Ys(t))}fromJsonString(e,t){let n=JSON.parse(e);return this.fromJson(n,t)}toJson(e,t){return this.internalJsonWrite(e,Zs(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=Gs(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 ${Ue(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 gi=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}},Hr=new gi,yi=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}},Ye=new yi,Si=class extends E{constructor(){super("config",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"peerConnectionOptions",kind:"message",T:()=>Ye},{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=Ye.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&&Ye.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}},ji=new Si,bi=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}},Qi=new bi,vi=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}},Gi=new vi,wi=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 wi,Ci=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}},zr=new Ci,Mi=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}},Ji=new Mi,Ti=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}},Yi=new Ti,Ei=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}},Zi=new Ei,Ri=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}},es=new Ri,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}},$r=new xi,ki=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}},ts=new ki,Ii=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}},ns=new Ii,Pi=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}},is=new Pi,Li=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}},ss=new Li,Di=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}},Ze=new Di,Oi=class extends E{constructor(){super("iceCandidate",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"candidate",kind:"message",T:()=>Ze},{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=Ze.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&&Ze.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}},rs=new Oi,Fi=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}},os=new Fi,Ai=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}},Se=new Ai,Ni=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}},as=new Ni,Ui=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}},ls=new Ui,Bi=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}},cs=new Bi,Vi=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}},ds=new Vi,_i=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}},hs=new _i,Wi=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}},us=new Wi,Hi=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}},ps=new Hi,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}},ms=new zi,$i=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}},fs=new $i,qi=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}},gs=new qi,Ki=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}},ys=new Ki;var lr={answer:ss,config:ji,disconnectPlayer:os,endpointId:Gi,endpointIdConfirm:Xi,iceCandidate:rs,identify:Qi,listStreamers:Ji,offer:is,ping:Se,playerConnected:ts,playerCount:gs,playerDisconnected:ns,pong:as,stats:ys,streamerDisconnected:ls,streamerList:Yi,subscribe:Zi,unsubscribe:es,layerPreference:cs,dataChannelRequest:ds,peerDataChannels:hs,peerDataChannelsReady:us,streamerDataChannels:ps,startStreaming:ms,stopStreaming:fs};var _={};As(_,{createMessage:()=>Ss,validateMessage:()=>qr});function Ss(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=lr[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 be=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(Ss(Se,{time:new Date().getTime()}))}onHeartbeatResponse(e){this.rtt=new Date().getTime()-e.time,this.alive=!0}};var et=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 tt=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 nt=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 it=class{constructor(e){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new nt(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 K=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 K{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 K{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 st=class extends K{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 ae=class extends K{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 rt=class extends Event{constructor(e){super("afkWarningActivate"),this.data=e}},ve=class extends Event{constructor(e){super("afkWarningUpdate"),this.data=e}},ot=class extends Event{constructor(){super("afkWarningDeactivate")}},at=class extends Event{constructor(){super("afkTimedOut")}},lt=class extends Event{constructor(e){super("videoEncoderAvgQP"),this.data=e}},ct=class extends Event{constructor(){super("webRtcSdp")}},dt=class extends Event{constructor(e){super("webRtcSdpAnswer"),this.data=e}},ht=class extends Event{constructor(e){super("webRtcSdpOffer"),this.data=e}},ut=class extends Event{constructor(){super("webRtcAutoConnect")}},pt=class extends Event{constructor(){super("webRtcConnecting")}},mt=class extends Event{constructor(){super("webRtcConnected")}},ft=class extends Event{constructor(){super("webRtcFailed")}},gt=class extends Event{constructor(e){super("webRtcDisconnected"),this.data=e}},yt=class extends Event{constructor(e){super("dataChannelOpen"),this.data=e}},St=class extends Event{constructor(e){super("dataChannelClose"),this.data=e}},bt=class extends Event{constructor(e){super("dataChannelError"),this.data=e}},vt=class extends Event{constructor(){super("videoInitialized")}},wt=class extends Event{constructor(){super("streamLoading")}},Ct=class extends Event{constructor(){super("streamConnect")}},Mt=class extends Event{constructor(){super("streamDisconnect")}},Tt=class extends Event{constructor(){super("streamReconnect")}},Et=class extends Event{constructor(e){super("playStreamError"),this.data=e}},Rt=class extends Event{constructor(){super("playStream")}},we=class extends Event{constructor(e){super("playStreamRejected"),this.data=e}},xt=class extends Event{constructor(e){super("loadFreezeFrame"),this.data=e}},kt=class extends Event{constructor(){super("hideFreezeFrame")}},It=class extends Event{constructor(e){super("statsReceived"),this.data=e}},Pt=class extends Event{constructor(e){super("streamerListMessage"),this.data=e}},Lt=class extends Event{constructor(e){super("StreamerIDChangedMessage"),this.data=e}},Dt=class extends Event{constructor(e){super("latencyTestResult"),this.data=e}},Ot=class extends Event{constructor(e){super("latencyCalculated"),this.data=e}},Ft=class extends Event{constructor(e){super("showOnScreenKeyboard"),this.data=e}},At=class extends Event{constructor(e){super("dataChannelLatencyTestResponse"),this.data=e}},Nt=class extends Event{constructor(e){super("dataChannelLatencyTestResult"),this.data=e}},Ut=class extends Event{constructor(e){super("subscribeFailed"),this.data=e}},Bt=class extends Event{constructor(e){super("initialSettings"),this.data=e}},te=class extends Event{constructor(e){super("settingsChanged"),this.data=e}};var Vt=class extends Event{constructor(e){super("xrFrame"),this.data=e}},_t=class extends Event{constructor(e){super("playerCount"),this.data=e}},Wt=class extends Event{constructor(){super("webRtcTCPRelayDetected")}},Ht=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 qr=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 Kr=s=>Object.getOwnPropertyNames(m).some(e=>m[e]===s),z=class{};z.SignallingServerUrl="ss";var jr=s=>Object.getOwnPropertyNames(z).some(e=>z[e]===s),M=class{};M.PreferredCodec="PreferredCodec";M.StreamerId="StreamerId";M.PreferredQuality="PreferredQuality";var Qr=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(z.SignallingServerUrl,new st(z.SignallingServerUrl,"Signalling url","Url of the signalling server",t&&Object.prototype.hasOwnProperty.call(t,z.SignallingServerUrl)?t[z.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 ae(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 ae(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 ae(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))qr(t)?this.setFlagEnabled(t,e[t]):Kr(t)?this.setNumericSetting(t,e[t]):jr(t)?this.setTextSetting(t,e[t]):Qr(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 $t=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 ot))}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 rt({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(m.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new ve({countDown:this.countDown})),this.config.isFlagEnabled(h.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval(()=>{this.countDown--,this.countDown==0?(this.pixelStreaming.dispatchEvent(new at),this.onAFKTimedOutCallback(),d.Info("You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new ve({countDown:this.countDown}))},1e3)}};var Ce=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 qt=class{},Kt=class{};var jt=class{};var Me=class{};var Te=class{},Ee=class{};var Qt=class{};var Gt=class{};var Xt=class{constructor(){this.inboundVideoStats=new Kt,this.inboundAudioStats=new qt,this.candidatePairs=new Array,this.datachannelStats=new jt,this.localCandidates=new Array,this.remoteCandidates=new Array,this.outboundVideoStats=new Te,this.outboundAudioStats=new Te,this.remoteOutboundAudioStats=new Ee,this.remoteOutboundVideoStats=new Ee,this.sessionStats=new Qt,this.streamStats=new Gt,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 Me;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 Me;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 Zt=Er(lr());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 bs=class{},vs=class{},Jt=class{constructor(){this.latestSenderRecvClockOffset=null}calculate(e,t){let n=new ws,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 vs,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 bs;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}},ws=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 Re=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())})},Gr="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",Yt=class{constructor(e,t,n){this.config=t,this.createPeerConnection(e,n),this.latencyCalculator=new Jt}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 Re(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 Re(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=et.addVideoHeaderExtensionToSdp(n,
|
|
41
|
+
`);return o.shift()+o.map(l=>l.startsWith("m=video")?l+r:l).join("")}};var tt=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 nt=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 it=class{constructor(e){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new nt(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 K=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 K{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 K{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 st=class extends K{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 ae=class extends K{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 rt=class extends Event{constructor(e){super("afkWarningActivate"),this.data=e}},ve=class extends Event{constructor(e){super("afkWarningUpdate"),this.data=e}},ot=class extends Event{constructor(){super("afkWarningDeactivate")}},at=class extends Event{constructor(){super("afkTimedOut")}},lt=class extends Event{constructor(e){super("videoEncoderAvgQP"),this.data=e}},ct=class extends Event{constructor(){super("webRtcSdp")}},dt=class extends Event{constructor(e){super("webRtcSdpAnswer"),this.data=e}},ht=class extends Event{constructor(e){super("webRtcSdpOffer"),this.data=e}},ut=class extends Event{constructor(){super("webRtcAutoConnect")}},pt=class extends Event{constructor(){super("webRtcConnecting")}},mt=class extends Event{constructor(){super("webRtcConnected")}},ft=class extends Event{constructor(){super("webRtcFailed")}},gt=class extends Event{constructor(e){super("webRtcDisconnected"),this.data=e}},yt=class extends Event{constructor(e){super("dataChannelOpen"),this.data=e}},St=class extends Event{constructor(e){super("dataChannelClose"),this.data=e}},bt=class extends Event{constructor(e){super("dataChannelError"),this.data=e}},vt=class extends Event{constructor(){super("videoInitialized")}},wt=class extends Event{constructor(){super("streamLoading")}},Ct=class extends Event{constructor(){super("streamConnect")}},Mt=class extends Event{constructor(){super("streamDisconnect")}},Tt=class extends Event{constructor(){super("streamReconnect")}},Et=class extends Event{constructor(e){super("playStreamError"),this.data=e}},Rt=class extends Event{constructor(){super("playStream")}},we=class extends Event{constructor(e){super("playStreamRejected"),this.data=e}},xt=class extends Event{constructor(e){super("loadFreezeFrame"),this.data=e}},kt=class extends Event{constructor(){super("hideFreezeFrame")}},It=class extends Event{constructor(e){super("statsReceived"),this.data=e}},Pt=class extends Event{constructor(e){super("streamerListMessage"),this.data=e}},Lt=class extends Event{constructor(e){super("StreamerIDChangedMessage"),this.data=e}},Dt=class extends Event{constructor(e){super("latencyTestResult"),this.data=e}},Ot=class extends Event{constructor(e){super("latencyCalculated"),this.data=e}},Ft=class extends Event{constructor(e){super("showOnScreenKeyboard"),this.data=e}},At=class extends Event{constructor(e){super("dataChannelLatencyTestResponse"),this.data=e}},Nt=class extends Event{constructor(e){super("dataChannelLatencyTestResult"),this.data=e}},Ut=class extends Event{constructor(e){super("subscribeFailed"),this.data=e}},Bt=class extends Event{constructor(e){super("initialSettings"),this.data=e}},te=class extends Event{constructor(e){super("settingsChanged"),this.data=e}};var Vt=class extends Event{constructor(e){super("xrFrame"),this.data=e}},_t=class extends Event{constructor(e){super("playerCount"),this.data=e}},Wt=class extends Event{constructor(){super("webRtcTCPRelayDetected")}},Ht=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 Kr=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 jr=s=>Object.getOwnPropertyNames(m).some(e=>m[e]===s),z=class{};z.SignallingServerUrl="ss";var Qr=s=>Object.getOwnPropertyNames(z).some(e=>z[e]===s),M=class{};M.PreferredCodec="PreferredCodec";M.StreamerId="StreamerId";M.PreferredQuality="PreferredQuality";var Gr=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(z.SignallingServerUrl,new st(z.SignallingServerUrl,"Signalling url","Url of the signalling server",t&&Object.prototype.hasOwnProperty.call(t,z.SignallingServerUrl)?t[z.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 ae(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 ae(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 ae(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))Kr(t)?this.setFlagEnabled(t,e[t]):jr(t)?this.setNumericSetting(t,e[t]):Qr(t)?this.setTextSetting(t,e[t]):Gr(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 $t=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 ot))}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 rt({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(m.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new ve({countDown:this.countDown})),this.config.isFlagEnabled(h.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval(()=>{this.countDown--,this.countDown==0?(this.pixelStreaming.dispatchEvent(new at),this.onAFKTimedOutCallback(),d.Info("You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new ve({countDown:this.countDown}))},1e3)}};var Ce=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 qt=class{},Kt=class{};var jt=class{};var Me=class{};var Te=class{},Ee=class{};var Qt=class{};var Gt=class{};var Xt=class{constructor(){this.inboundVideoStats=new Kt,this.inboundAudioStats=new qt,this.candidatePairs=new Array,this.datachannelStats=new jt,this.localCandidates=new Array,this.remoteCandidates=new Array,this.outboundVideoStats=new Te,this.outboundAudioStats=new Te,this.remoteOutboundAudioStats=new Ee,this.remoteOutboundVideoStats=new Ee,this.sessionStats=new Qt,this.streamStats=new Gt,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 Me;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 Me;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 Zt=Rr(cr());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 vs=class{},ws=class{},Jt=class{constructor(){this.latestSenderRecvClockOffset=null}calculate(e,t){let n=new Cs,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 ws,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 vs;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}},Cs=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 Re=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())})},Xr="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",Yt=class{constructor(e,t,n){this.config=t,this.createPeerConnection(e,n),this.latencyCalculator=new Jt}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 Re(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 Re(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=et.addVideoHeaderExtensionToSdp(n,Xr)),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 Re(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 x=this.preferredCodec.split(" "),U={mimeType:"video/"+x[0],clockRate:9e4,sdpFmtpLine:x[1]?x[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 Re(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 Re(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,Zt.splitSections)(e.sdp);return n.shift(),n.forEach(i=>{let{codecs:r}=(0,Zt.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 en=class{constructor(){this.PixelStreamingSettings=new Ms,this.EncoderSettings=new Ts,this.WebRTCSettings=new Es}ueCompatible(){this.WebRTCSettings.MaxFPS!=null&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}},Ms=class{},Ts=class{},Es=class{};var tn=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}
|
|
46
|
-
${this.PreCaptureTimeMs}`),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}};var le=class{static setExtensionFromBytes(e,t){t.receiving||(t.mimetype="",t.extension="",t.receiving=!0,t.valid=!1,t.chunks=0,t.data=[],t.timestampStart=new Date().getTime(),d.Info("Received first chunk of file"));let n=new TextDecoder("utf-16").decode(e.slice(1));d.Info(n),t.extension=n}static setMimeTypeFromBytes(e,t){t.receiving||(t.mimetype="",t.extension="",t.receiving=!0,t.valid=!1,t.chunks=0,t.data=[],t.timestampStart=new Date().getTime(),d.Info("Received first chunk of file"));let n=new TextDecoder("utf-16").decode(e.slice(1));d.Info(n),t.mimetype=n}static setContentsFromBytes(e,t){if(!t.receiving)return;let n=1,i=4,r=16*1024,o=n+i,a=r-o;t.chunks=Math.ceil(new DataView(e.slice(n,o).buffer).getInt32(0,!0)/a);let l=e.slice(o);if(t.data.push(l),d.Info(`Received file chunk: ${t.data.length}/${t.chunks}`),t.data.length===t.chunks){t.receiving=!1,t.valid=!0,d.Info("Received complete file");let c=new Date().getTime()-t.timestampStart,u=Math.round(t.chunks*r/c);d.Info(`Average transfer bitrate: ${u}kb/s over ${c/1e3} seconds`)}else t.data.length>t.chunks&&(t.receiving=!1,d.Error(`Received bigger file than advertised: ${t.data.length}/${t.chunks}`))}},nn=class{constructor(){this.mimetype="",this.extension="",this.receiving=!1,this.chunks=0,this.data=[],this.valid=!1}};var F=class{};F.backSpace=8;F.shift=16;F.control=17;F.alt=18;F.rightShift=253;F.rightControl=254;F.rightAlt=255;var Es=Object.freeze({Escape:27,Digit0:48,Digit1:49,Digit2:50,Digit3:51,Digit4:52,Digit5:53,Digit6:54,Digit7:55,Digit8:56,Digit9:57,Minus:173,Equal:187,Backspace:8,Tab:9,KeyQ:81,KeyW:87,KeyE:69,KeyR:82,KeyT:84,KeyY:89,KeyU:85,KeyI:73,KeyO:79,KeyP:80,BracketLeft:219,BracketRight:221,Enter:13,ControlLeft:17,KeyA:65,KeyS:83,KeyD:68,KeyF:70,KeyG:71,KeyH:72,KeyJ:74,KeyK:75,KeyL:76,Semicolon:186,Quote:222,Backquote:192,ShiftLeft:16,Backslash:220,KeyZ:90,KeyX:88,KeyC:67,KeyV:86,KeyB:66,KeyN:78,KeyM:77,Comma:188,Period:190,Slash:191,ShiftRight:253,AltLeft:18,Space:32,CapsLock:20,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,Pause:19,ScrollLock:145,NumpadDivide:111,NumpadMultiply:106,NumpadSubtract:109,NumpadAdd:107,NumpadDecimal:110,Numpad9:105,Numpad8:104,Numpad7:103,Numpad6:102,Numpad5:101,Numpad4:100,Numpad3:99,Numpad2:98,Numpad1:97,Numpad0:96,NumLock:144,ControlRight:254,AltRight:255,Home:36,End:35,ArrowUp:38,ArrowLeft:37,ArrowRight:39,ArrowDown:40,PageUp:33,PageDown:34,Insert:45,Delete:46,ContextMenu:93});var sn=class{constructor(e,t,n){this.streamMessageController=e,this.config=t,this.activeKeys=n,this.onKeyDownListener=this.handleOnKeyDown.bind(this),this.onKeyUpListener=this.handleOnKeyUp.bind(this),this.onKeyPressListener=this.handleOnKeyPress.bind(this)}register(){document.addEventListener("keydown",this.onKeyDownListener),document.addEventListener("keyup",this.onKeyUpListener),document.addEventListener("keypress",this.onKeyPressListener)}unregister(){document.removeEventListener("keydown",this.onKeyDownListener),document.removeEventListener("keyup",this.onKeyUpListener),document.removeEventListener("keypress",this.onKeyPressListener)}handleOnKeyDown(e){var t;let n=this.getKeycode(e);if(!n||n===229)return;(t=this.streamMessageController.toStreamerHandlers.get("KeyDown"))===null||t===void 0||t([this.getKeycode(e),e.repeat?1:0]),this.activeKeys.getActiveKeys().push(n),n===F.backSpace&&this.handleOnKeyPress(new KeyboardEvent("keypress",{charCode:F.backSpace,keyCode:F.backSpace})),this.config.isFlagEnabled(h.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(n)&&e.preventDefault()}handleOnKeyUp(e){var t;let n=this.getKeycode(e);if(!n)return;(t=this.streamMessageController.toStreamerHandlers.get("KeyUp"))===null||t===void 0||t([n]),this.config.isFlagEnabled(h.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(n)&&e.preventDefault()}handleOnKeyPress(e){var t;let n=this.getKeycode(e);if(!n)return;(t=this.streamMessageController.toStreamerHandlers.get("KeyPress"))===null||t===void 0||t([n])}getKeycode(e){if(!("keyCode"in e)){let t=e;return t.code in Es?Es[t.code]:(d.Warning(`Keyboard code of ${t.code} is not supported in our mapping, ignoring this key.`),null)}return e.keyCode===F.shift&&e.code==="ShiftRight"?F.rightShift:e.keyCode===F.control&&e.code==="ControlRight"?F.rightControl:e.keyCode===F.alt&&e.code==="AltRight"?F.rightAlt:e.keyCode}isKeyCodeBrowserKey(e){return e>=112&&e<=123||e===9}};var D=class{};D.mainButton=0;D.auxiliaryButton=1;D.secondaryButton=2;D.fourthButton=3;D.fifthButton=4;var N=class{};N.primaryButton=1;N.secondaryButton=2;N.auxiliaryButton=4;N.fourthButton=8;N.fifthButton=16;var ce=class{constructor(e,t,n,i){this.streamMessageController=e,this.coordinateConverter=n,this.videoPlayer=t,this.activeKeys=i,this.onEnterListener=this.onMouseEnter.bind(this),this.onLeaveListener=this.onMouseLeave.bind(this)}register(){this.registerMouseEnterAndLeaveEvents()}unregister(){this.unregisterMouseEnterAndLeaveEvents()}registerMouseEnterAndLeaveEvents(){let e=this.videoPlayer.getVideoParentElement();e?.addEventListener("mouseenter",this.onEnterListener),e?.addEventListener("mouseleave",this.onLeaveListener)}unregisterMouseEnterAndLeaveEvents(){let e=this.videoPlayer.getVideoParentElement();e?.removeEventListener("mouseenter",this.onEnterListener),e?.removeEventListener("mouseleave",this.onLeaveListener)}onMouseEnter(e){var t;this.videoPlayer.isVideoReady()&&((t=this.streamMessageController.toStreamerHandlers.get("MouseEnter"))===null||t===void 0||t(),this.pressMouseButtons(e.buttons,e.x,e.y))}onMouseLeave(e){var t;this.videoPlayer.isVideoReady()&&((t=this.streamMessageController.toStreamerHandlers.get("MouseLeave"))===null||t===void 0||t(),this.releaseMouseButtons(e.buttons,e.x,e.y))}releaseMouseButtons(e,t,n){let i=this.coordinateConverter.translateUnsigned(t,n);e&N.primaryButton&&this.sendMouseUp(D.mainButton,i.x,i.y),e&N.secondaryButton&&this.sendMouseUp(D.secondaryButton,i.x,i.y),e&N.auxiliaryButton&&this.sendMouseUp(D.auxiliaryButton,i.x,i.y),e&N.fourthButton&&this.sendMouseUp(D.fourthButton,i.x,i.y),e&N.fifthButton&&this.sendMouseUp(D.fifthButton,i.x,i.y)}pressMouseButtons(e,t,n){if(!this.videoPlayer.isVideoReady())return;let i=this.coordinateConverter.translateUnsigned(t,n);e&N.primaryButton&&this.sendMouseDown(D.mainButton,i.x,i.y),e&N.secondaryButton&&this.sendMouseDown(D.secondaryButton,i.x,i.y),e&N.auxiliaryButton&&this.sendMouseDown(D.auxiliaryButton,i.x,i.y),e&N.fourthButton&&this.sendMouseDown(D.fourthButton,i.x,i.y),e&N.fifthButton&&this.sendMouseDown(D.fifthButton,i.x,i.y)}sendMouseDown(e,t,n){var i;(i=this.streamMessageController.toStreamerHandlers.get("MouseDown"))===null||i===void 0||i([e,t,n])}sendMouseUp(e,t,n){var i;let r=this.coordinateConverter.translateUnsigned(t,n);(i=this.streamMessageController.toStreamerHandlers.get("MouseUp"))===null||i===void 0||i([e,r.x,r.y])}};var rn=class extends ce{constructor(e,t,n,i){super(e,t,n,i),this.videoElementParent=t.getVideoParentElement(),this.x=this.videoElementParent.getBoundingClientRect().width/2,this.y=this.videoElementParent.getBoundingClientRect().height/2,this.normalizedCoord=this.coordinateConverter.translateUnsigned(this.x,this.y),this.onRequestLockListener=this.onRequestLock.bind(this),this.onLockStateChangeListener=this.onLockStateChange.bind(this),this.onMouseUpListener=this.onMouseUp.bind(this),this.onMouseDownListener=this.onMouseDown.bind(this),this.onMouseDblClickListener=this.onMouseDblClick.bind(this),this.onMouseWheelListener=this.onMouseWheel.bind(this),this.onMouseMoveListener=this.onMouseMove.bind(this)}register(){super.register(),this.videoElementParent.requestPointerLock=this.videoElementParent.requestPointerLock||this.videoElementParent.mozRequestPointerLock,document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock,this.videoElementParent.requestPointerLock&&this.videoElementParent.addEventListener("click",this.onRequestLockListener),document.addEventListener("pointerlockchange",this.onLockStateChangeListener),document.addEventListener("mozpointerlockchange",this.onLockStateChangeListener),this.videoElementParent.addEventListener("mousedown",this.onMouseDownListener),this.videoElementParent.addEventListener("mouseup",this.onMouseUpListener),this.videoElementParent.addEventListener("wheel",this.onMouseWheelListener),this.videoElementParent.addEventListener("dblclick",this.onMouseDblClickListener)}unregister(){let e=document.pointerLockElement||document.mozPointerLockElement;document.exitPointerLock&&e===this.videoElementParent&&document.exitPointerLock(),this.videoElementParent.removeEventListener("click",this.onRequestLockListener),document.removeEventListener("pointerlockchange",this.onLockStateChangeListener),document.removeEventListener("mozpointerlockchange",this.onLockStateChangeListener),document.removeEventListener("mousemove",this.onMouseMoveListener),this.videoElementParent.removeEventListener("mousedown",this.onMouseDownListener),this.videoElementParent.removeEventListener("mouseup",this.onMouseUpListener),this.videoElementParent.removeEventListener("wheel",this.onMouseWheelListener),this.videoElementParent.removeEventListener("dblclick",this.onMouseDblClickListener),super.unregister()}onRequestLock(){this.videoElementParent.requestPointerLock()}onLockStateChange(){(document.pointerLockElement||document.mozPointerLockElement)===this.videoElementParent?(d.Info("Pointer locked"),document.addEventListener("mousemove",this.onMouseMoveListener)):(d.Info("The pointer lock status is now unlocked"),document.removeEventListener("mousemove",this.onMouseMoveListener),this.activeKeys.getActiveKeys().forEach(n=>{this.streamMessageController.toStreamerHandlers.get("KeyUp")([n])}))}onMouseDown(e){this.videoPlayer.isVideoReady()&&this.streamMessageController.toStreamerHandlers.get("MouseDown")([e.button,this.normalizedCoord.x,this.normalizedCoord.y])}onMouseUp(e){this.videoPlayer.isVideoReady()&&this.streamMessageController.toStreamerHandlers.get("MouseUp")([e.button,this.normalizedCoord.x,this.normalizedCoord.y])}onMouseMove(e){if(!this.videoPlayer.isVideoReady())return;let t=this.videoPlayer.getVideoParentElement().clientWidth,n=this.videoPlayer.getVideoParentElement().clientHeight;for(this.x+=e.movementX,this.y+=e.movementY;this.x>t;)this.x-=t;for(;this.y>n;)this.y-=n;for(;this.x<0;)this.x+=t;for(;this.y<0;)this.y+=n;this.normalizedCoord=this.coordinateConverter.translateUnsigned(this.x,this.y);let i=this.coordinateConverter.translateSigned(e.movementX,e.movementY);this.streamMessageController.toStreamerHandlers.get("MouseMove")([this.normalizedCoord.x,this.normalizedCoord.y,i.x,i.y])}onMouseWheel(e){this.videoPlayer.isVideoReady()&&this.streamMessageController.toStreamerHandlers.get("MouseWheel")([e.wheelDelta,this.normalizedCoord.x,this.normalizedCoord.y])}onMouseDblClick(e){this.videoPlayer.isVideoReady()&&this.streamMessageController.toStreamerHandlers.get("MouseDouble")([e.button,this.normalizedCoord.x,this.normalizedCoord.y])}};var on=class extends ce{constructor(e,t,n,i){super(e,t,n,i),this.videoElementParent=t.getVideoParentElement(),this.onMouseUpListener=this.onMouseUp.bind(this),this.onMouseDownListener=this.onMouseDown.bind(this),this.onMouseDblClickListener=this.onMouseDblClick.bind(this),this.onMouseWheelListener=this.onMouseWheel.bind(this),this.onMouseMoveListener=this.onMouseMove.bind(this),this.onContextMenuListener=this.onContextMenu.bind(this)}register(){super.register(),this.videoElementParent.addEventListener("mousemove",this.onMouseMoveListener),this.videoElementParent.addEventListener("mousedown",this.onMouseDownListener),this.videoElementParent.addEventListener("mouseup",this.onMouseUpListener),this.videoElementParent.addEventListener("contextmenu",this.onContextMenuListener),this.videoElementParent.addEventListener("wheel",this.onMouseWheelListener),this.videoElementParent.addEventListener("dblclick",this.onMouseDblClickListener)}unregister(){this.videoElementParent.removeEventListener("mousemove",this.onMouseMoveListener),this.videoElementParent.removeEventListener("mousedown",this.onMouseDownListener),this.videoElementParent.removeEventListener("mouseup",this.onMouseUpListener),this.videoElementParent.removeEventListener("contextmenu",this.onContextMenuListener),this.videoElementParent.removeEventListener("wheel",this.onMouseWheelListener),this.videoElementParent.removeEventListener("dblclick",this.onMouseDblClickListener),super.unregister()}onMouseDown(e){if(!this.videoPlayer.isVideoReady())return;let t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY);this.streamMessageController.toStreamerHandlers.get("MouseDown")([e.button,t.x,t.y]),e.preventDefault()}onMouseUp(e){if(!this.videoPlayer.isVideoReady())return;let t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY);this.streamMessageController.toStreamerHandlers.get("MouseUp")([e.button,t.x,t.y]),e.preventDefault()}onContextMenu(e){this.videoPlayer.isVideoReady()&&e.preventDefault()}onMouseMove(e){if(!this.videoPlayer.isVideoReady())return;let t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY),n=this.coordinateConverter.translateSigned(e.movementX,e.movementY);this.streamMessageController.toStreamerHandlers.get("MouseMove")([t.x,t.y,n.x,n.y]),e.preventDefault()}onMouseWheel(e){if(!this.videoPlayer.isVideoReady())return;let t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY);this.streamMessageController.toStreamerHandlers.get("MouseWheel")([e.wheelDelta,t.x,t.y]),e.preventDefault()}onMouseDblClick(e){if(!this.videoPlayer.isVideoReady())return;let t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY);this.streamMessageController.toStreamerHandlers.get("MouseDouble")([e.button,t.x,t.y])}};var an=class{constructor(e,t,n){this.fingers=[9,8,7,6,5,4,3,2,1,0],this.fingerIds=new Map,this.maxByteValue=255,this.streamMessageController=e,this.videoPlayer=t,this.coordinateConverter=n,this.videoElementParent=t.getVideoElement(),this.onTouchStartListener=this.onTouchStart.bind(this),this.onTouchEndListener=this.onTouchEnd.bind(this),this.onTouchMoveListener=this.onTouchMove.bind(this)}register(){this.videoElementParent.addEventListener("touchstart",this.onTouchStartListener),this.videoElementParent.addEventListener("touchend",this.onTouchEndListener),this.videoElementParent.addEventListener("touchmove",this.onTouchMoveListener)}unregister(){this.videoElementParent.removeEventListener("touchstart",this.onTouchStartListener),this.videoElementParent.removeEventListener("touchend",this.onTouchEndListener),this.videoElementParent.removeEventListener("touchmove",this.onTouchMoveListener)}rememberTouch(e){let t=this.fingers.pop();t===void 0&&d.Info("exhausted touch identifiers"),this.fingerIds.set(e.identifier,t)}forgetTouch(e){this.fingers.push(this.fingerIds.get(e.identifier)),this.fingers.sort(function(t,n){return n-t}),this.fingerIds.delete(e.identifier)}onTouchStart(e){if(this.videoPlayer.isVideoReady()){for(let t=0;t<e.changedTouches.length;t++)this.rememberTouch(e.changedTouches[t]);this.emitTouchData("TouchStart",e.changedTouches),e.preventDefault()}}onTouchEnd(e){if(this.videoPlayer.isVideoReady()){this.emitTouchData("TouchEnd",e.changedTouches);for(let t=0;t<e.changedTouches.length;t++)this.forgetTouch(e.changedTouches[t]);e.preventDefault()}}onTouchMove(e){this.videoPlayer.isVideoReady()&&(this.emitTouchData("TouchMove",e.touches),e.preventDefault())}emitTouchData(e,t){if(!this.videoPlayer.isVideoReady())return;let n=this.videoPlayer.getVideoParentElement().getBoundingClientRect(),i=this.streamMessageController.toStreamerHandlers;for(let r=0;r<t.length;r++){let a=t[r],l=a.clientX-n.left,c=a.clientY-n.top;d.Info(`F${this.fingerIds.get(a.identifier)}=(${l}, ${c})`);let u=this.coordinateConverter.translateUnsigned(l,c);switch(e){case"TouchStart":i.get("TouchStart")([1,u.x,u.y,this.fingerIds.get(a.identifier),this.maxByteValue*(a.force>0?a.force:1),u.inRange?1:0]);break;case"TouchEnd":i.get("TouchEnd")([1,u.x,u.y,this.fingerIds.get(a.identifier),this.maxByteValue*a.force,u.inRange?1:0]);break;case"TouchMove":i.get("TouchMove")([1,u.x,u.y,this.fingerIds.get(a.identifier),this.maxByteValue*(a.force>0?a.force:1),u.inRange?1:0]);break}}}};var ln=class{constructor(e,t,n){this.streamMessageController=e,this.videoPlayer=t,this.coordinateConverter=n,this.onTouchStartListener=this.onTouchStart.bind(this),this.onTouchEndListener=this.onTouchEnd.bind(this),this.onTouchMoveListener=this.onTouchMove.bind(this),this.videoElementParentClientRect=this.videoPlayer.getVideoParentElement().getBoundingClientRect()}register(){document.addEventListener("touchstart",this.onTouchStartListener),document.addEventListener("touchend",this.onTouchEndListener),document.addEventListener("touchmove",this.onTouchMoveListener)}unregister(){document.removeEventListener("touchstart",this.onTouchStartListener),document.removeEventListener("touchend",this.onTouchEndListener),document.removeEventListener("touchmove",this.onTouchMoveListener)}onTouchStart(e){if(!(!this.videoPlayer.isVideoReady()||e.target!==this.videoPlayer.getVideoElement())){if(this.fakeTouchFinger==null){let t=e.changedTouches[0];this.fakeTouchFinger={id:t.identifier,x:t.clientX-this.videoElementParentClientRect.left,y:t.clientY-this.videoElementParentClientRect.top};let n=this.videoPlayer.getVideoParentElement(),i=new MouseEvent("mouseenter",t);n.dispatchEvent(i);let r=this.coordinateConverter.translateUnsigned(this.fakeTouchFinger.x,this.fakeTouchFinger.y);this.streamMessageController.toStreamerHandlers.get("MouseDown")([D.mainButton,r.x,r.y])}e.preventDefault()}}onTouchEnd(e){if(!this.videoPlayer.isVideoReady()||this.fakeTouchFinger==null)return;let t=this.videoPlayer.getVideoParentElement(),n=this.streamMessageController.toStreamerHandlers;for(let i=0;i<e.changedTouches.length;i++){let r=e.changedTouches[i];if(r.identifier===this.fakeTouchFinger.id){let o=r.clientX-this.videoElementParentClientRect.left,a=r.clientY-this.videoElementParentClientRect.top,l=this.coordinateConverter.translateUnsigned(o,a);n.get("MouseUp")([D.mainButton,l.x,l.y]);let c=new MouseEvent("mouseleave",r);t.dispatchEvent(c),this.fakeTouchFinger=null;break}}e.preventDefault()}onTouchMove(e){if(!this.videoPlayer.isVideoReady()||this.fakeTouchFinger==null)return;let t=this.streamMessageController.toStreamerHandlers;for(let n=0;n<e.touches.length;n++){let i=e.touches[n];if(i.identifier===this.fakeTouchFinger.id){let r=i.clientX-this.videoElementParentClientRect.left,o=i.clientY-this.videoElementParentClientRect.top,a=this.coordinateConverter.translateUnsigned(r,o),l=this.coordinateConverter.translateSigned(r-this.fakeTouchFinger.x,o-this.fakeTouchFinger.y);t.get("MouseMove")([a.x,a.y,l.x,l.y]),this.fakeTouchFinger.x=r,this.fakeTouchFinger.y=o;break}}e.preventDefault()}};function ie(s){return JSON.parse(JSON.stringify({buttons:s.buttons.map(e=>JSON.parse(JSON.stringify({pressed:e.pressed,touched:e.touched,value:e.value}))),axes:s.axes}))}var de;(function(s){s[s.RightClusterBottomButton=0]="RightClusterBottomButton",s[s.RightClusterRightButton=1]="RightClusterRightButton",s[s.RightClusterLeftButton=2]="RightClusterLeftButton",s[s.RightClusterTopButton=3]="RightClusterTopButton",s[s.LeftShoulder=4]="LeftShoulder",s[s.RightShoulder=5]="RightShoulder",s[s.LeftTrigger=6]="LeftTrigger",s[s.RightTrigger=7]="RightTrigger",s[s.SelectOrBack=8]="SelectOrBack",s[s.StartOrForward=9]="StartOrForward",s[s.LeftAnalogPress=10]="LeftAnalogPress",s[s.RightAnalogPress=11]="RightAnalogPress",s[s.LeftClusterTopButton=12]="LeftClusterTopButton",s[s.LeftClusterBottomButton=13]="LeftClusterBottomButton",s[s.LeftClusterLeftButton=14]="LeftClusterLeftButton",s[s.LeftClusterRightButton=15]="LeftClusterRightButton",s[s.CentreButton=16]="CentreButton",s[s.LeftStickHorizontal=0]="LeftStickHorizontal",s[s.LeftStickVertical=1]="LeftStickVertical",s[s.RightStickHorizontal=2]="RightStickHorizontal",s[s.RightStickVertical=3]="RightStickVertical"})(de||(de={}));var cn=class{constructor(e){this.streamMessageController=e,this.onGamepadConnectedListener=this.onGamepadConnected.bind(this),this.onGamepadDisconnectedListener=this.onGamepadDisconnected.bind(this),this.beforeUnloadListener=this.onBeforeUnload.bind(this),this.requestAnimationFrame=(window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.requestAnimationFrame).bind(window)}register(){window.addEventListener("beforeunload",this.beforeUnloadListener);let e=window;if("GamepadEvent"in e?(window.addEventListener("gamepadconnected",this.onGamepadConnectedListener),window.addEventListener("gamepaddisconnected",this.onGamepadDisconnectedListener)):"WebKitGamepadEvent"in e&&(window.addEventListener("webkitgamepadconnected",this.onGamepadConnectedListener),window.addEventListener("webkitgamepaddisconnected",this.onGamepadDisconnectedListener)),this.controllers=[],navigator.getGamepads)for(let t of navigator.getGamepads())t&&this.onGamepadConnected(new GamepadEvent("gamepadconnected",{gamepad:t}))}unregister(){window.removeEventListener("gamepadconnected",this.onGamepadConnectedListener),window.removeEventListener("gamepaddisconnected",this.onGamepadDisconnectedListener),window.removeEventListener("webkitgamepadconnected",this.onGamepadConnectedListener),window.removeEventListener("webkitgamepaddisconnected",this.onGamepadDisconnectedListener);for(let e of this.controllers)e&&e.id!==void 0&&this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([e.id]);this.controllers=[]}onGamepadResponseReceived(e){for(let t of this.controllers)if(t&&t.id===void 0){t.id=e;break}}onGamepadConnected(e){let t=e.gamepad,n={currentState:ie(t),prevState:ie(t),id:void 0};this.controllers[t.index]=n,window.requestAnimationFrame(()=>this.updateStatus()),this.streamMessageController.toStreamerHandlers.get("GamepadConnected")()}onGamepadDisconnected(e){let t=e.gamepad,n=this.controllers[t.index];delete this.controllers[t.index],this.controllers=this.controllers.filter(i=>i!==void 0),n.id!==void 0&&this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([n.id])}scanGamepads(){let e=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[];for(let t=0;t<e.length;t++)e[t]&&this.controllers[e[t].index]!==void 0&&(this.controllers[e[t].index].currentState=e[t])}updateStatus(){this.scanGamepads();let e=this.streamMessageController.toStreamerHandlers;for(let t of this.controllers){if(!t)continue;let n=t.id===void 0?this.controllers.indexOf(t):t.id,i=t.currentState;for(let o=0;o<t.currentState.buttons.length;o++){let a=t.currentState.buttons[o],l=t.prevState.buttons[o];a.pressed?o==de.LeftTrigger?e.get("GamepadAnalog")([n,5,a.value]):o==de.RightTrigger?e.get("GamepadAnalog")([n,6,a.value]):e.get("GamepadButtonPressed")([n,o,l.pressed?1:0]):!a.pressed&&l.pressed&&(o==de.LeftTrigger?e.get("GamepadAnalog")([n,5,0]):o==de.RightTrigger?e.get("GamepadAnalog")([n,6,0]):e.get("GamepadButtonReleased")([n,o,0]))}for(let o=0;o<i.axes.length;o+=2){let a=parseFloat(i.axes[o].toFixed(4)),l=-parseFloat(i.axes[o+1].toFixed(4));e.get("GamepadAnalog")([n,o+1,a]),e.get("GamepadAnalog")([n,o+2,l])}let r=this.controllers.indexOf(t);this.controllers[r].prevState=ie(i)}this.controllers.length>0&&this.requestAnimationFrame(()=>this.updateStatus())}onBeforeUnload(e){for(let t of this.controllers)!t||t.id===void 0||this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([t.id])}};var dn=class{constructor(e,t,n){this.activeKeys=new Rs,this.toStreamerMessagesProvider=e,this.videoElementProvider=t,this.coordinateConverter=n}registerKeyBoard(e){d.Info("Register Keyboard Events");let t=new sn(this.toStreamerMessagesProvider,e,this.activeKeys);return t.register(),t}registerMouse(e){d.Info("Register Mouse Events");let t;return e==ne.HoveringMouse?t=new on(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys):t=new rn(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys),t.register(),t}registerTouch(e){d.Info("Registering Touch");let t;return e?t=new ln(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter):t=new an(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter),t.register(),t}registerGamePad(){d.Info("Register Game Pad");let e=new cn(this.toStreamerMessagesProvider);return e.register(),e}},Rs=class{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}};var hn=class{constructor(e,t){this.lastTimeResized=new Date().getTime(),this.videoElement=document.createElement("video"),this.config=t,this.videoElement.id="streamingVideo",this.videoElement.disablePictureInPicture=!0,this.videoElement.playsInline=!0,this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.pointerEvents="all",e.appendChild(this.videoElement),this.onResizePlayerCallback=()=>{console.log("Resolution changed, restyling player, did you forget to override this function?")},this.onMatchViewportResolutionCallback=()=>{console.log("Resolution changed and match viewport resolution is turned on, did you forget to override this function?")},this.videoElement.onclick=()=>{this.audioElement!=null&&this.audioElement.paused&&this.audioElement.play(),this.videoElement.paused&&this.videoElement.play()},this.videoElement.onloadedmetadata=()=>{this.onVideoInitialized()},window.addEventListener("resize",()=>this.resizePlayerStyle(),!0),window.addEventListener("orientationchange",()=>this.onOrientationChange())}destroy(){this.videoElement.src="",this.videoElement.srcObject=null,this.videoElement.remove(),this.audioElement&&(this.audioElement.src="",this.audioElement.srcObject=null,this.audioElement.remove())}setAudioElement(e){this.audioElement=e}play(){return this.videoElement.muted=this.config.isFlagEnabled(h.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(h.AutoPlayVideo),this.videoElement.play()}isPaused(){return this.videoElement.paused}isVideoReady(){return this.videoElement.readyState!==void 0&&this.videoElement.readyState>0}hasVideoSource(){return this.videoElement.srcObject!==void 0&&this.videoElement.srcObject!==null}getVideoElement(){return this.videoElement}getVideoParentElement(){var e;return(e=this.videoElement.parentElement)!==null&&e!==void 0?e:void 0}setVideoEnabled(e){this.videoElement.srcObject.getTracks().forEach(n=>n.enabled=e)}onVideoInitialized(){}onOrientationChange(){clearTimeout(this.orientationChangeTimeout),this.orientationChangeTimeout=window.setTimeout(()=>{this.resizePlayerStyle()},500)}resizePlayerStyle(){let e=this.getVideoParentElement();if(e){if(this.updateVideoStreamSize(),e.classList.contains("fixed-size")){this.onResizePlayerCallback();return}this.resizePlayerStyleToFillParentElement(),this.onResizePlayerCallback()}}resizePlayerStyleToFillParentElement(){this.getVideoParentElement().setAttribute("style","top: "+0+"px; left: "+0+"px; width: "+"100%"+"; height: "+"100%"+"; cursor: default;")}updateVideoStreamSize(){if(!this.config.isFlagEnabled(h.MatchViewportResolution))return;if(new Date().getTime()-this.lastTimeResized>300){let t=this.getVideoParentElement();if(!t)return;this.onMatchViewportResolutionCallback(t.clientWidth,t.clientHeight),this.lastTimeResized=new Date().getTime()}else d.Info("Resizing too often - skipping"),clearTimeout(this.resizeTimeoutHandle),this.resizeTimeoutHandle=window.setTimeout(()=>this.updateVideoStreamSize(),100)}};var un=class{constructor(){this.toStreamerHandlers=new Map,this.fromStreamerHandlers=new Map,this.toStreamerMessages=new Map,this.fromStreamerMessages=new Map}populateDefaultProtocol(){this.toStreamerMessages.set("IFrameRequest",{id:0,structure:[]}),this.toStreamerMessages.set("RequestQualityControl",{id:1,structure:[]}),this.toStreamerMessages.set("FpsRequest",{id:2,structure:[]}),this.toStreamerMessages.set("AverageBitrateRequest",{id:3,structure:[]}),this.toStreamerMessages.set("StartStreaming",{id:4,structure:[]}),this.toStreamerMessages.set("StopStreaming",{id:5,structure:[]}),this.toStreamerMessages.set("LatencyTest",{id:6,structure:["string"]}),this.toStreamerMessages.set("RequestInitialSettings",{id:7,structure:[]}),this.toStreamerMessages.set("TestEcho",{id:8,structure:[]}),this.toStreamerMessages.set("DataChannelLatencyTest",{id:9,structure:[]}),this.toStreamerMessages.set("UIInteraction",{id:50,structure:["string"]}),this.toStreamerMessages.set("Command",{id:51,structure:["string"]}),this.toStreamerMessages.set("TextboxEntry",{id:52,structure:["string"]}),this.toStreamerMessages.set("KeyDown",{id:60,structure:["uint8","uint8"]}),this.toStreamerMessages.set("KeyUp",{id:61,structure:["uint8"]}),this.toStreamerMessages.set("KeyPress",{id:62,structure:["uint16"]}),this.toStreamerMessages.set("MouseEnter",{id:70,structure:[]}),this.toStreamerMessages.set("MouseLeave",{id:71,structure:[]}),this.toStreamerMessages.set("MouseDown",{id:72,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseUp",{id:73,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseMove",{id:74,structure:["uint16","uint16","int16","int16"]}),this.toStreamerMessages.set("MouseWheel",{id:75,structure:["int16","uint16","uint16"]}),this.toStreamerMessages.set("MouseDouble",{id:76,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("TouchStart",{id:80,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchEnd",{id:81,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchMove",{id:82,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadConnected",{id:93,structure:[]}),this.toStreamerMessages.set("GamepadButtonPressed",{id:90,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadButtonReleased",{id:91,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadAnalog",{id:92,structure:["uint8","uint8","double"]}),this.toStreamerMessages.set("GamepadDisconnected",{id:94,structure:["uint8"]}),this.fromStreamerMessages.set(0,"QualityControlOwnership"),this.fromStreamerMessages.set(1,"Response"),this.fromStreamerMessages.set(2,"Command"),this.fromStreamerMessages.set(3,"FreezeFrame"),this.fromStreamerMessages.set(4,"UnfreezeFrame"),this.fromStreamerMessages.set(5,"VideoEncoderAvgQP"),this.fromStreamerMessages.set(6,"LatencyTest"),this.fromStreamerMessages.set(7,"InitialSettings"),this.fromStreamerMessages.set(8,"FileExtension"),this.fromStreamerMessages.set(9,"FileMimeType"),this.fromStreamerMessages.set(10,"FileContents"),this.fromStreamerMessages.set(11,"TestEcho"),this.fromStreamerMessages.set(12,"InputControlOwnership"),this.fromStreamerMessages.set(13,"GamepadResponse"),this.fromStreamerMessages.set(14,"DataChannelLatencyTest"),this.fromStreamerMessages.set(255,"Protocol")}registerMessageHandler(e,t,n){switch(e){case S.ToStreamer:this.toStreamerHandlers.set(t,n);break;case S.FromStreamer:this.fromStreamerHandlers.set(t,n);break;default:d.Info(`Unknown message direction ${e}`)}}},S;(function(s){s[s.ToStreamer=0]="ToStreamer",s[s.FromStreamer=1]="FromStreamer"})(S||(S={}));var pn=class{constructor(){this.responseEventListeners=new Map}addResponseEventListener(e,t){this.responseEventListeners.set(e,t)}removeResponseEventListener(e){this.responseEventListeners.delete(e)}onResponse(e){d.Info("DataChannelReceiveMessageType.Response");let t=new TextDecoder("utf-16").decode(e.slice(1));d.Info(t),this.responseEventListeners.forEach(n=>{n(t)})}};var mn=class{constructor(e,t){this.dataChannelSender=e,this.toStreamerMessagesMapProvider=t}sendMessageToStreamer(e,t){t===void 0&&(t=[]);let i=this.toStreamerMessagesMapProvider.toStreamerMessages.get(e);if(i===void 0){d.Error(`Attempted to send a message to the streamer with message type: ${e}, but the frontend hasn't been configured to send such a message. Check you've added the message type in your cpp`);return}if(i.structure&&t&&i.structure.length!==t.length){d.Error(`Provided message data doesn't match expected layout. Expected [ ${i.structure.map(c=>{switch(c){case"uint8":case"uint16":case"int16":case"float":case"double":default:return"number";case"string":return"string"}}).toString()} ] but received [ ${t.map(c=>typeof c).toString()} ]`);return}let r=0,o=new TextEncoder;t.forEach((c,u)=>{switch(i.structure[u]){case"uint8":r+=1;break;case"uint16":r+=2;break;case"int16":r+=2;break;case"float":r+=4;break;case"double":r+=8;break;case"string":r+=2,r+=2*o.encode(c).length;break}});let a=new DataView(new ArrayBuffer(r+1));a.setUint8(0,i.id);let l=1;if(t.forEach((c,u)=>{switch(i.structure[u]){case"uint8":a.setUint8(l,c),l+=1;break;case"uint16":a.setUint16(l,c,!0),l+=2;break;case"int16":a.setInt16(l,c,!0),l+=2;break;case"float":a.setFloat32(l,c,!0),l+=4;break;case"double":a.setFloat64(l,c,!0),l+=8;break;case"string":a.setUint16(l,c.length,!0),l+=2;for(let v=0;v<c.length;v++)a.setUint16(l,c.charCodeAt(v),!0),l+=2;break}}),!this.dataChannelSender.canSend()){d.Info(`Data channel cannot send yet, skipping sending message: ${e} - ${new Uint8Array(a.buffer)}`);return}this.dataChannelSender.sendData(a.buffer)}};var fn=class{constructor(e){this.sendMessageController=e}SendRequestQualityControl(){this.sendMessageController.sendMessageToStreamer("RequestQualityControl")}SendMaxFpsRequest(){this.sendMessageController.sendMessageToStreamer("FpsRequest")}SendAverageBitrateRequest(){this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest")}SendStartStreaming(){this.sendMessageController.sendMessageToStreamer("StartStreaming")}SendStopStreaming(){this.sendMessageController.sendMessageToStreamer("StopStreaming")}SendRequestInitialSettings(){this.sendMessageController.sendMessageToStreamer("RequestInitialSettings")}};var gn=class{constructor(e){this.dataChannelProvider=e}canSend(){return this.dataChannelProvider.getDataChannelInstance().dataChannel!==void 0&&this.dataChannelProvider.getDataChannelInstance().dataChannel.readyState=="open"}sendData(e){let t=this.dataChannelProvider.getDataChannelInstance();t.dataChannel.readyState=="open"?(t.dataChannel.send(e),d.Info(`Message Sent: ${new Uint8Array(e)}`),this.resetAfkWarningTimerOnDataSend()):d.Error(`Message Failed: ${new Uint8Array(e)}`)}resetAfkWarningTimerOnDataSend(){}};var yn=class{reconfigure(e,t){let n=e.height/e.width,i=t.height/t.width;this.playerIsLarger=n>i,this.playerSize=e,this.ratio=this.playerIsLarger?n/i:i/n}translateUnsigned(e,t){let n=this.playerIsLarger?e/this.playerSize.width:this.ratio*(e/this.playerSize.width-.5)+.5,i=this.playerIsLarger?this.ratio*(t/this.playerSize.height-.5)+.5:t/this.playerSize.height;return n<0||n>1||i<0||i>1?{inRange:!1,x:65535,y:65535}:{inRange:!0,x:n*65536,y:i*65536}}translateSigned(e,t){let n=this.playerIsLarger?e/(.5*this.playerSize.width):this.ratio*e/(.5*this.playerSize.width),i=this.playerIsLarger?this.ratio*t/(.5*this.playerSize.height):t/(.5*this.playerSize.height);return{x:n*32767,y:i*32767}}untranslateUnsigned(e,t){let n=this.playerIsLarger?e/65536:(e/65536-.5)/this.ratio+.5,i=this.playerIsLarger?(t/65536-.5)/this.ratio+.5:t/65536;return{x:n*this.playerSize.width,y:i*this.playerSize.height}}};var he=class{constructor(e){this._urlParams={};let t=new URLSearchParams(e);for(let[n,i]of t)this._urlParams[n.toLowerCase()]=i}has(e){return e.toLowerCase()in this._urlParams}get(e){return this.has(e)?this._urlParams[e.toLowerCase()]:null}};var Sn=class{constructor(e,t){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=e,this.pixelStreaming=t,this.responseController=new pn,this.file=new nn,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new $t(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity.",!1)},this.freezeFrameController=new it(this.pixelStreaming.videoElementParent),this.videoPlayer=new hn(this.pixelStreaming.videoElementParent,this.config),this.videoPlayer.onVideoInitialized=()=>this.handleVideoInitialized(),this.videoPlayer.onMatchViewportResolutionCallback=(n,i)=>{let r={"Resolution.Width":n,"Resolution.Height":i};this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(r)])},this.videoPlayer.onResizePlayerCallback=()=>{this.setUpMouseAndFreezeFrame()},this.streamController=new tt(this.videoPlayer),this.coordinateConverter=new yn,this.sendrecvDataChannelController=new Ce,this.recvDataChannelController=new Ce,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new gn(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new un,this.transport=new me(e.webSocketProtocols),this.protocol=new fe(this.transport),this.protocol.addListener(P.config.typeName,n=>this.handleOnConfigMessage(n)),this.protocol.addListener(P.ping.typeName,n=>this.handlePingMessage(n)),this.protocol.addListener(P.streamerList.typeName,n=>this.handleStreamerListMessage(n)),this.protocol.addListener(P.subscribeFailed.typeName,n=>this.handleSubscribeFailedMessage(n)),this.protocol.addListener(P.streamerIdChanged.typeName,n=>this.handleStreamerIDChangedMessage(n)),this.protocol.addListener(P.playerCount.typeName,n=>{let i=n;this.pixelStreaming._onPlayerCount(i.count)}),this.protocol.addListener(P.answer.typeName,n=>this.handleWebRtcAnswer(n)),this.protocol.addListener(P.offer.typeName,n=>this.handleWebRtcOffer(n)),this.protocol.addListener(P.peerDataChannels.typeName,n=>this.handleWebRtcSFUPeerDatachannels(n)),this.protocol.addListener(P.iceCandidate.typeName,n=>{let i=n;this.handleIceCandidate(i.candidate)}),this.protocol.transport.addListener("open",()=>{if(!this.config.isFlagEnabled(h.BrowserSendOffer)){let i=_.createMessage(P.listStreamers);this.protocol.sendMessage(i)}this.reconnectAttempt=0,this.isReconnecting=!1}),this.protocol.transport.addListener("error",()=>{d.Error("Got a transport error.")}),this.protocol.transport.addListener("close",n=>{let r=this.config.getNumericSettingValue(m.MaxReconnectAttempts),o=this.reconnectAttempt<r,l=(this.forceReconnect||this.enableAutoReconnect&&r>0&&o)&&n.code!=1001,c=!l,u=this.disconnectMessage?this.disconnectMessage:n.reason;this.forceReconnect=!1,this.config.getSettingOption(M.PreferredCodec).options=Y.getSupportedVideoCodecs(),this.pixelStreaming._onDisconnect(u,c),this.afkController.stopAfkWarningTimer(),this.statsTimerHandle&&this.statsTimerHandle!==void 0&&window.clearInterval(this.statsTimerHandle),this.setVideoEncoderAvgQP(0),this.setTouchInputEnabled(!1),this.setMouseInputEnabled(!1),this.setKeyboardInputEnabled(!1),this.setGamePadInputEnabled(!1),l&&setTimeout(()=>{this.reconnectAttempt++,this.doReconnect(n.reason)},2e3)}),this.sendMessageController=new mn(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new fn(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new dn(this.streamMessageController,this.videoPlayer,this.coordinateConverter),this.isUsingSFU=!1,this.isUsingSVC=!1,this.isQualityController=!1,this.preferredCodec="",this.enableAutoReconnect=!0,this.forceReconnect=!1,this.reconnectAttempt=0,this.isReconnecting=!1,this.config._addOnOptionSettingChangedListener(M.StreamerId,n=>{if(n===void 0||n==="")return;this.peerConnectionController.peerConnection.close(),this.peerConnectionController.createPeerConnection(this.peerConfig,this.preferredCodec),this.subscribedStream=n;let i=_.createMessage(P.subscribe,{streamerId:n});this.protocol.sendMessage(i)}),this.config._addOnOptionSettingChangedListener(M.PreferredQuality,n=>{if(n===void 0||n==="")return;let i;if(this.isUsingSVC)i=_.createMessage(P.layerPreference,{spatialLayer:+n[1]-1,temporalLayer:+n[3]-1});else{let o=this.config.getSettingOption(M.PreferredQuality).options.indexOf(n);i=_.createMessage(P.layerPreference,{spatialLayer:o,temporalLayer:0})}this.protocol.sendMessage(i)}),this.setVideoEncoderAvgQP(-1),this.signallingUrlBuilder=()=>this.config.getTextSettingValue(z.SignallingServerUrl)}destroyVideoPlayer(){this.videoPlayer.destroy()}handleOnMessage(e){let t=new Uint8Array(e.data);d.Info("Message incoming:"+t);let n=this.streamMessageController.fromStreamerMessages.get(t[0]);this.streamMessageController.fromStreamerHandlers.get(n)(e.data)}registerMessageHandlers(){this.streamMessageController.registerMessageHandler(S.FromStreamer,"QualityControlOwnership",e=>this.onQualityControlOwnership(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"Response",e=>this.responseController.onResponse(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"Command",e=>{this.onCommand(e)}),this.streamMessageController.registerMessageHandler(S.FromStreamer,"FreezeFrame",e=>this.onFreezeFrameMessage(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"UnfreezeFrame",()=>this.invalidateFreezeFrameAndEnableVideo()),this.streamMessageController.registerMessageHandler(S.FromStreamer,"VideoEncoderAvgQP",e=>this.handleVideoEncoderAvgQP(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"LatencyTest",e=>this.handleLatencyTestResult(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"DataChannelLatencyTest",e=>this.handleDataChannelLatencyTestResponse(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"InitialSettings",e=>this.handleInitialSettings(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"FileExtension",e=>this.onFileExtension(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"FileMimeType",e=>this.onFileMimeType(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"FileContents",e=>this.onFileContents(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"TestEcho",()=>{}),this.streamMessageController.registerMessageHandler(S.FromStreamer,"InputControlOwnership",e=>this.onInputControlOwnership(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"GamepadResponse",e=>this.onGamepadResponse(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"Multiplexed",()=>{}),this.streamMessageController.registerMessageHandler(S.FromStreamer,"Protocol",e=>this.onProtocolMessage(e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"IFrameRequest",()=>this.sendMessageController.sendMessageToStreamer("IFrameRequest")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"RequestQualityControl",()=>this.sendMessageController.sendMessageToStreamer("RequestQualityControl")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"FpsRequest",()=>this.sendMessageController.sendMessageToStreamer("FpsRequest")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"AverageBitrateRequest",()=>this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"StartStreaming",()=>this.sendMessageController.sendMessageToStreamer("StartStreaming")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"StopStreaming",()=>this.sendMessageController.sendMessageToStreamer("StopStreaming")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"LatencyTest",e=>this.sendMessageController.sendMessageToStreamer("LatencyTest",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"RequestInitialSettings",()=>this.sendMessageController.sendMessageToStreamer("RequestInitialSettings")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"TestEcho",()=>{}),this.streamMessageController.registerMessageHandler(S.ToStreamer,"UIInteraction",e=>this.sendMessageController.sendMessageToStreamer("UIInteraction",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"Command",e=>this.sendMessageController.sendMessageToStreamer("Command",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"TextboxEntry",e=>this.sendMessageController.sendMessageToStreamer("TextboxEntry",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"KeyDown",e=>this.sendMessageController.sendMessageToStreamer("KeyDown",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"KeyUp",e=>this.sendMessageController.sendMessageToStreamer("KeyUp",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"KeyPress",e=>this.sendMessageController.sendMessageToStreamer("KeyPress",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"MouseEnter",e=>this.sendMessageController.sendMessageToStreamer("MouseEnter",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"MouseLeave",e=>this.sendMessageController.sendMessageToStreamer("MouseLeave",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"MouseDown",e=>this.sendMessageController.sendMessageToStreamer("MouseDown",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"MouseUp",e=>this.sendMessageController.sendMessageToStreamer("MouseUp",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"MouseMove",e=>this.sendMessageController.sendMessageToStreamer("MouseMove",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"MouseWheel",e=>this.sendMessageController.sendMessageToStreamer("MouseWheel",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"MouseDouble",e=>this.sendMessageController.sendMessageToStreamer("MouseDouble",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"TouchStart",e=>this.sendMessageController.sendMessageToStreamer("TouchStart",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"TouchEnd",e=>this.sendMessageController.sendMessageToStreamer("TouchEnd",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"TouchMove",e=>this.sendMessageController.sendMessageToStreamer("TouchMove",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"GamepadConnected",()=>this.sendMessageController.sendMessageToStreamer("GamepadConnected")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"GamepadButtonPressed",e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonPressed",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"GamepadButtonReleased",e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonReleased",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"GamepadAnalog",e=>this.sendMessageController.sendMessageToStreamer("GamepadAnalog",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"GamepadDisconnected",e=>this.sendMessageController.sendMessageToStreamer("GamepadDisconnected",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XREyeViews",e=>this.sendMessageController.sendMessageToStreamer("XREyeViews",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRHMDTransform",e=>this.sendMessageController.sendMessageToStreamer("XRHMDTransform",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRControllerTransform",e=>this.sendMessageController.sendMessageToStreamer("XRControllerTransform",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRSystem",e=>this.sendMessageController.sendMessageToStreamer("XRSystem",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRButtonTouched",e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouched",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRButtonTouchReleased",e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouchReleased",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRButtonPressed",e=>this.sendMessageController.sendMessageToStreamer("XRButtonPressed",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRButtonReleased",e=>this.sendMessageController.sendMessageToStreamer("XRButtonReleased",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRAnalog",e=>this.sendMessageController.sendMessageToStreamer("XRAnalog",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"ChannelRelayStatus",()=>{}),this.streamMessageController.registerMessageHandler(S.ToStreamer,"Multiplexed",()=>{})}onCommand(e){d.Info("DataChannelReceiveMessageType.Command");let t=new TextDecoder("utf-16").decode(e.slice(1));d.Info("Data Channel Command: "+t);let n=JSON.parse(t);n.command==="onScreenKeyboard"&&this.handleOnScreenKeyboardCommand(n)}handleOnScreenKeyboardCommand(e){var t,n,i,r;let o={showOnScreenKeyboard:(t=e.showOnScreenKeyboard)!==null&&t!==void 0?t:!0,x:(n=e.x)!==null&&n!==void 0?n:0,y:(i=e.y)!==null&&i!==void 0?i:0,contents:(r=e.contents)!==null&&r!==void 0?r:""};this.pixelStreaming.dispatchEvent(new Ft(o))}onProtocolMessage(e){try{let t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);Object.prototype.hasOwnProperty.call(n,"Direction")||d.Error("Malformed protocol received. Ensure the protocol message contains a direction");let i=n.Direction;delete n.Direction,d.Info(`Received new ${i==S.FromStreamer?"FromStreamer":"ToStreamer"} protocol. Updating existing protocol...`),Object.keys(n).forEach(r=>{let o=n[r];switch(i){case S.ToStreamer:if(!Object.prototype.hasOwnProperty.call(o,"id")){d.Error(`ToStreamer->${r} protocol definition was malformed as it didn't contain at least an id
|
|
46
|
+
${this.PreCaptureTimeMs}`),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}};var le=class{static setExtensionFromBytes(e,t){t.receiving||(t.mimetype="",t.extension="",t.receiving=!0,t.valid=!1,t.chunks=0,t.data=[],t.timestampStart=new Date().getTime(),d.Info("Received first chunk of file"));let n=new TextDecoder("utf-16").decode(e.slice(1));d.Info(n),t.extension=n}static setMimeTypeFromBytes(e,t){t.receiving||(t.mimetype="",t.extension="",t.receiving=!0,t.valid=!1,t.chunks=0,t.data=[],t.timestampStart=new Date().getTime(),d.Info("Received first chunk of file"));let n=new TextDecoder("utf-16").decode(e.slice(1));d.Info(n),t.mimetype=n}static setContentsFromBytes(e,t){if(!t.receiving)return;let n=1,i=4,r=16*1024,o=n+i,a=r-o;t.chunks=Math.ceil(new DataView(e.slice(n,o).buffer).getInt32(0,!0)/a);let l=e.slice(o);if(t.data.push(l),d.Info(`Received file chunk: ${t.data.length}/${t.chunks}`),t.data.length===t.chunks){t.receiving=!1,t.valid=!0,d.Info("Received complete file");let c=new Date().getTime()-t.timestampStart,u=Math.round(t.chunks*r/c);d.Info(`Average transfer bitrate: ${u}kb/s over ${c/1e3} seconds`)}else t.data.length>t.chunks&&(t.receiving=!1,d.Error(`Received bigger file than advertised: ${t.data.length}/${t.chunks}`))}},nn=class{constructor(){this.mimetype="",this.extension="",this.receiving=!1,this.chunks=0,this.data=[],this.valid=!1}};var F=class{};F.backSpace=8;F.shift=16;F.control=17;F.alt=18;F.rightShift=253;F.rightControl=254;F.rightAlt=255;var Rs=Object.freeze({Escape:27,Digit0:48,Digit1:49,Digit2:50,Digit3:51,Digit4:52,Digit5:53,Digit6:54,Digit7:55,Digit8:56,Digit9:57,Minus:173,Equal:187,Backspace:8,Tab:9,KeyQ:81,KeyW:87,KeyE:69,KeyR:82,KeyT:84,KeyY:89,KeyU:85,KeyI:73,KeyO:79,KeyP:80,BracketLeft:219,BracketRight:221,Enter:13,ControlLeft:17,KeyA:65,KeyS:83,KeyD:68,KeyF:70,KeyG:71,KeyH:72,KeyJ:74,KeyK:75,KeyL:76,Semicolon:186,Quote:222,Backquote:192,ShiftLeft:16,Backslash:220,KeyZ:90,KeyX:88,KeyC:67,KeyV:86,KeyB:66,KeyN:78,KeyM:77,Comma:188,Period:190,Slash:191,ShiftRight:253,AltLeft:18,Space:32,CapsLock:20,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,Pause:19,ScrollLock:145,NumpadDivide:111,NumpadMultiply:106,NumpadSubtract:109,NumpadAdd:107,NumpadDecimal:110,Numpad9:105,Numpad8:104,Numpad7:103,Numpad6:102,Numpad5:101,Numpad4:100,Numpad3:99,Numpad2:98,Numpad1:97,Numpad0:96,NumLock:144,ControlRight:254,AltRight:255,Home:36,End:35,ArrowUp:38,ArrowLeft:37,ArrowRight:39,ArrowDown:40,PageUp:33,PageDown:34,Insert:45,Delete:46,ContextMenu:93});var sn=class{constructor(e,t,n){this.streamMessageController=e,this.config=t,this.activeKeys=n,this.onKeyDownListener=this.handleOnKeyDown.bind(this),this.onKeyUpListener=this.handleOnKeyUp.bind(this),this.onKeyPressListener=this.handleOnKeyPress.bind(this)}register(){document.addEventListener("keydown",this.onKeyDownListener),document.addEventListener("keyup",this.onKeyUpListener),document.addEventListener("keypress",this.onKeyPressListener)}unregister(){document.removeEventListener("keydown",this.onKeyDownListener),document.removeEventListener("keyup",this.onKeyUpListener),document.removeEventListener("keypress",this.onKeyPressListener)}handleOnKeyDown(e){var t;let n=this.getKeycode(e);if(!n||n===229)return;(t=this.streamMessageController.toStreamerHandlers.get("KeyDown"))===null||t===void 0||t([this.getKeycode(e),e.repeat?1:0]),this.activeKeys.getActiveKeys().push(n),n===F.backSpace&&this.handleOnKeyPress(new KeyboardEvent("keypress",{charCode:F.backSpace,keyCode:F.backSpace})),this.config.isFlagEnabled(h.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(n)&&e.preventDefault()}handleOnKeyUp(e){var t;let n=this.getKeycode(e);if(!n)return;(t=this.streamMessageController.toStreamerHandlers.get("KeyUp"))===null||t===void 0||t([n]),this.config.isFlagEnabled(h.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(n)&&e.preventDefault()}handleOnKeyPress(e){var t;let n=this.getKeycode(e);if(!n)return;(t=this.streamMessageController.toStreamerHandlers.get("KeyPress"))===null||t===void 0||t([n])}getKeycode(e){if(!("keyCode"in e)){let t=e;return t.code in Rs?Rs[t.code]:(d.Warning(`Keyboard code of ${t.code} is not supported in our mapping, ignoring this key.`),null)}return e.keyCode===F.shift&&e.code==="ShiftRight"?F.rightShift:e.keyCode===F.control&&e.code==="ControlRight"?F.rightControl:e.keyCode===F.alt&&e.code==="AltRight"?F.rightAlt:e.keyCode}isKeyCodeBrowserKey(e){return e>=112&&e<=123||e===9}};var D=class{};D.mainButton=0;D.auxiliaryButton=1;D.secondaryButton=2;D.fourthButton=3;D.fifthButton=4;var N=class{};N.primaryButton=1;N.secondaryButton=2;N.auxiliaryButton=4;N.fourthButton=8;N.fifthButton=16;var ce=class{constructor(e,t,n,i){this.streamMessageController=e,this.coordinateConverter=n,this.videoPlayer=t,this.activeKeys=i,this.onEnterListener=this.onMouseEnter.bind(this),this.onLeaveListener=this.onMouseLeave.bind(this)}register(){this.registerMouseEnterAndLeaveEvents()}unregister(){this.unregisterMouseEnterAndLeaveEvents()}registerMouseEnterAndLeaveEvents(){let e=this.videoPlayer.getVideoParentElement();e?.addEventListener("mouseenter",this.onEnterListener),e?.addEventListener("mouseleave",this.onLeaveListener)}unregisterMouseEnterAndLeaveEvents(){let e=this.videoPlayer.getVideoParentElement();e?.removeEventListener("mouseenter",this.onEnterListener),e?.removeEventListener("mouseleave",this.onLeaveListener)}onMouseEnter(e){var t;this.videoPlayer.isVideoReady()&&((t=this.streamMessageController.toStreamerHandlers.get("MouseEnter"))===null||t===void 0||t(),this.pressMouseButtons(e.buttons,e.x,e.y))}onMouseLeave(e){var t;this.videoPlayer.isVideoReady()&&((t=this.streamMessageController.toStreamerHandlers.get("MouseLeave"))===null||t===void 0||t(),this.releaseMouseButtons(e.buttons,e.x,e.y))}releaseMouseButtons(e,t,n){let i=this.coordinateConverter.translateUnsigned(t,n);e&N.primaryButton&&this.sendMouseUp(D.mainButton,i.x,i.y),e&N.secondaryButton&&this.sendMouseUp(D.secondaryButton,i.x,i.y),e&N.auxiliaryButton&&this.sendMouseUp(D.auxiliaryButton,i.x,i.y),e&N.fourthButton&&this.sendMouseUp(D.fourthButton,i.x,i.y),e&N.fifthButton&&this.sendMouseUp(D.fifthButton,i.x,i.y)}pressMouseButtons(e,t,n){if(!this.videoPlayer.isVideoReady())return;let i=this.coordinateConverter.translateUnsigned(t,n);e&N.primaryButton&&this.sendMouseDown(D.mainButton,i.x,i.y),e&N.secondaryButton&&this.sendMouseDown(D.secondaryButton,i.x,i.y),e&N.auxiliaryButton&&this.sendMouseDown(D.auxiliaryButton,i.x,i.y),e&N.fourthButton&&this.sendMouseDown(D.fourthButton,i.x,i.y),e&N.fifthButton&&this.sendMouseDown(D.fifthButton,i.x,i.y)}sendMouseDown(e,t,n){var i;(i=this.streamMessageController.toStreamerHandlers.get("MouseDown"))===null||i===void 0||i([e,t,n])}sendMouseUp(e,t,n){var i;let r=this.coordinateConverter.translateUnsigned(t,n);(i=this.streamMessageController.toStreamerHandlers.get("MouseUp"))===null||i===void 0||i([e,r.x,r.y])}};var rn=class extends ce{constructor(e,t,n,i){super(e,t,n,i),this.videoElementParent=t.getVideoParentElement(),this.x=this.videoElementParent.getBoundingClientRect().width/2,this.y=this.videoElementParent.getBoundingClientRect().height/2,this.normalizedCoord=this.coordinateConverter.translateUnsigned(this.x,this.y),this.onRequestLockListener=this.onRequestLock.bind(this),this.onLockStateChangeListener=this.onLockStateChange.bind(this),this.onMouseUpListener=this.onMouseUp.bind(this),this.onMouseDownListener=this.onMouseDown.bind(this),this.onMouseDblClickListener=this.onMouseDblClick.bind(this),this.onMouseWheelListener=this.onMouseWheel.bind(this),this.onMouseMoveListener=this.onMouseMove.bind(this)}register(){super.register(),this.videoElementParent.requestPointerLock=this.videoElementParent.requestPointerLock||this.videoElementParent.mozRequestPointerLock,document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock,this.videoElementParent.requestPointerLock&&this.videoElementParent.addEventListener("click",this.onRequestLockListener),document.addEventListener("pointerlockchange",this.onLockStateChangeListener),document.addEventListener("mozpointerlockchange",this.onLockStateChangeListener),this.videoElementParent.addEventListener("mousedown",this.onMouseDownListener),this.videoElementParent.addEventListener("mouseup",this.onMouseUpListener),this.videoElementParent.addEventListener("wheel",this.onMouseWheelListener),this.videoElementParent.addEventListener("dblclick",this.onMouseDblClickListener)}unregister(){let e=document.pointerLockElement||document.mozPointerLockElement;document.exitPointerLock&&e===this.videoElementParent&&document.exitPointerLock(),this.videoElementParent.removeEventListener("click",this.onRequestLockListener),document.removeEventListener("pointerlockchange",this.onLockStateChangeListener),document.removeEventListener("mozpointerlockchange",this.onLockStateChangeListener),document.removeEventListener("mousemove",this.onMouseMoveListener),this.videoElementParent.removeEventListener("mousedown",this.onMouseDownListener),this.videoElementParent.removeEventListener("mouseup",this.onMouseUpListener),this.videoElementParent.removeEventListener("wheel",this.onMouseWheelListener),this.videoElementParent.removeEventListener("dblclick",this.onMouseDblClickListener),super.unregister()}onRequestLock(){this.videoElementParent.requestPointerLock()}onLockStateChange(){(document.pointerLockElement||document.mozPointerLockElement)===this.videoElementParent?(d.Info("Pointer locked"),document.addEventListener("mousemove",this.onMouseMoveListener)):(d.Info("The pointer lock status is now unlocked"),document.removeEventListener("mousemove",this.onMouseMoveListener),this.activeKeys.getActiveKeys().forEach(n=>{this.streamMessageController.toStreamerHandlers.get("KeyUp")([n])}))}onMouseDown(e){this.videoPlayer.isVideoReady()&&this.streamMessageController.toStreamerHandlers.get("MouseDown")([e.button,this.normalizedCoord.x,this.normalizedCoord.y])}onMouseUp(e){this.videoPlayer.isVideoReady()&&this.streamMessageController.toStreamerHandlers.get("MouseUp")([e.button,this.normalizedCoord.x,this.normalizedCoord.y])}onMouseMove(e){if(!this.videoPlayer.isVideoReady())return;let t=this.videoPlayer.getVideoParentElement().clientWidth,n=this.videoPlayer.getVideoParentElement().clientHeight;for(this.x+=e.movementX,this.y+=e.movementY;this.x>t;)this.x-=t;for(;this.y>n;)this.y-=n;for(;this.x<0;)this.x+=t;for(;this.y<0;)this.y+=n;this.normalizedCoord=this.coordinateConverter.translateUnsigned(this.x,this.y);let i=this.coordinateConverter.translateSigned(e.movementX,e.movementY);this.streamMessageController.toStreamerHandlers.get("MouseMove")([this.normalizedCoord.x,this.normalizedCoord.y,i.x,i.y])}onMouseWheel(e){this.videoPlayer.isVideoReady()&&this.streamMessageController.toStreamerHandlers.get("MouseWheel")([e.wheelDelta,this.normalizedCoord.x,this.normalizedCoord.y])}onMouseDblClick(e){this.videoPlayer.isVideoReady()&&this.streamMessageController.toStreamerHandlers.get("MouseDouble")([e.button,this.normalizedCoord.x,this.normalizedCoord.y])}};var on=class extends ce{constructor(e,t,n,i){super(e,t,n,i),this.videoElementParent=t.getVideoParentElement(),this.onMouseUpListener=this.onMouseUp.bind(this),this.onMouseDownListener=this.onMouseDown.bind(this),this.onMouseDblClickListener=this.onMouseDblClick.bind(this),this.onMouseWheelListener=this.onMouseWheel.bind(this),this.onMouseMoveListener=this.onMouseMove.bind(this),this.onContextMenuListener=this.onContextMenu.bind(this)}register(){super.register(),this.videoElementParent.addEventListener("mousemove",this.onMouseMoveListener),this.videoElementParent.addEventListener("mousedown",this.onMouseDownListener),this.videoElementParent.addEventListener("mouseup",this.onMouseUpListener),this.videoElementParent.addEventListener("contextmenu",this.onContextMenuListener),this.videoElementParent.addEventListener("wheel",this.onMouseWheelListener),this.videoElementParent.addEventListener("dblclick",this.onMouseDblClickListener)}unregister(){this.videoElementParent.removeEventListener("mousemove",this.onMouseMoveListener),this.videoElementParent.removeEventListener("mousedown",this.onMouseDownListener),this.videoElementParent.removeEventListener("mouseup",this.onMouseUpListener),this.videoElementParent.removeEventListener("contextmenu",this.onContextMenuListener),this.videoElementParent.removeEventListener("wheel",this.onMouseWheelListener),this.videoElementParent.removeEventListener("dblclick",this.onMouseDblClickListener),super.unregister()}onMouseDown(e){if(!this.videoPlayer.isVideoReady())return;let t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY);this.streamMessageController.toStreamerHandlers.get("MouseDown")([e.button,t.x,t.y]),e.preventDefault()}onMouseUp(e){if(!this.videoPlayer.isVideoReady())return;let t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY);this.streamMessageController.toStreamerHandlers.get("MouseUp")([e.button,t.x,t.y]),e.preventDefault()}onContextMenu(e){this.videoPlayer.isVideoReady()&&e.preventDefault()}onMouseMove(e){if(!this.videoPlayer.isVideoReady())return;let t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY),n=this.coordinateConverter.translateSigned(e.movementX,e.movementY);this.streamMessageController.toStreamerHandlers.get("MouseMove")([t.x,t.y,n.x,n.y]),e.preventDefault()}onMouseWheel(e){if(!this.videoPlayer.isVideoReady())return;let t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY);this.streamMessageController.toStreamerHandlers.get("MouseWheel")([e.wheelDelta,t.x,t.y]),e.preventDefault()}onMouseDblClick(e){if(!this.videoPlayer.isVideoReady())return;let t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY);this.streamMessageController.toStreamerHandlers.get("MouseDouble")([e.button,t.x,t.y])}};var an=class{constructor(e,t,n){this.fingers=[9,8,7,6,5,4,3,2,1,0],this.fingerIds=new Map,this.maxByteValue=255,this.streamMessageController=e,this.videoPlayer=t,this.coordinateConverter=n,this.videoElementParent=t.getVideoElement(),this.onTouchStartListener=this.onTouchStart.bind(this),this.onTouchEndListener=this.onTouchEnd.bind(this),this.onTouchMoveListener=this.onTouchMove.bind(this)}register(){this.videoElementParent.addEventListener("touchstart",this.onTouchStartListener),this.videoElementParent.addEventListener("touchend",this.onTouchEndListener),this.videoElementParent.addEventListener("touchmove",this.onTouchMoveListener)}unregister(){this.videoElementParent.removeEventListener("touchstart",this.onTouchStartListener),this.videoElementParent.removeEventListener("touchend",this.onTouchEndListener),this.videoElementParent.removeEventListener("touchmove",this.onTouchMoveListener)}rememberTouch(e){let t=this.fingers.pop();t===void 0&&d.Info("exhausted touch identifiers"),this.fingerIds.set(e.identifier,t)}forgetTouch(e){this.fingers.push(this.fingerIds.get(e.identifier)),this.fingers.sort(function(t,n){return n-t}),this.fingerIds.delete(e.identifier)}onTouchStart(e){if(this.videoPlayer.isVideoReady()){for(let t=0;t<e.changedTouches.length;t++)this.rememberTouch(e.changedTouches[t]);this.emitTouchData("TouchStart",e.changedTouches),e.preventDefault()}}onTouchEnd(e){if(this.videoPlayer.isVideoReady()){this.emitTouchData("TouchEnd",e.changedTouches);for(let t=0;t<e.changedTouches.length;t++)this.forgetTouch(e.changedTouches[t]);e.preventDefault()}}onTouchMove(e){this.videoPlayer.isVideoReady()&&(this.emitTouchData("TouchMove",e.touches),e.preventDefault())}emitTouchData(e,t){if(!this.videoPlayer.isVideoReady())return;let n=this.videoPlayer.getVideoParentElement().getBoundingClientRect(),i=this.streamMessageController.toStreamerHandlers;for(let r=0;r<t.length;r++){let a=t[r],l=a.clientX-n.left,c=a.clientY-n.top;d.Info(`F${this.fingerIds.get(a.identifier)}=(${l}, ${c})`);let u=this.coordinateConverter.translateUnsigned(l,c);switch(e){case"TouchStart":i.get("TouchStart")([1,u.x,u.y,this.fingerIds.get(a.identifier),this.maxByteValue*(a.force>0?a.force:1),u.inRange?1:0]);break;case"TouchEnd":i.get("TouchEnd")([1,u.x,u.y,this.fingerIds.get(a.identifier),this.maxByteValue*a.force,u.inRange?1:0]);break;case"TouchMove":i.get("TouchMove")([1,u.x,u.y,this.fingerIds.get(a.identifier),this.maxByteValue*(a.force>0?a.force:1),u.inRange?1:0]);break}}}};var ln=class{constructor(e,t,n){this.streamMessageController=e,this.videoPlayer=t,this.coordinateConverter=n,this.onTouchStartListener=this.onTouchStart.bind(this),this.onTouchEndListener=this.onTouchEnd.bind(this),this.onTouchMoveListener=this.onTouchMove.bind(this),this.videoElementParentClientRect=this.videoPlayer.getVideoParentElement().getBoundingClientRect()}register(){document.addEventListener("touchstart",this.onTouchStartListener),document.addEventListener("touchend",this.onTouchEndListener),document.addEventListener("touchmove",this.onTouchMoveListener)}unregister(){document.removeEventListener("touchstart",this.onTouchStartListener),document.removeEventListener("touchend",this.onTouchEndListener),document.removeEventListener("touchmove",this.onTouchMoveListener)}onTouchStart(e){if(!(!this.videoPlayer.isVideoReady()||e.target!==this.videoPlayer.getVideoElement())){if(this.fakeTouchFinger==null){let t=e.changedTouches[0];this.fakeTouchFinger={id:t.identifier,x:t.clientX-this.videoElementParentClientRect.left,y:t.clientY-this.videoElementParentClientRect.top};let n=this.videoPlayer.getVideoParentElement(),i=new MouseEvent("mouseenter",t);n.dispatchEvent(i);let r=this.coordinateConverter.translateUnsigned(this.fakeTouchFinger.x,this.fakeTouchFinger.y);this.streamMessageController.toStreamerHandlers.get("MouseDown")([D.mainButton,r.x,r.y])}e.preventDefault()}}onTouchEnd(e){if(!this.videoPlayer.isVideoReady()||this.fakeTouchFinger==null)return;let t=this.videoPlayer.getVideoParentElement(),n=this.streamMessageController.toStreamerHandlers;for(let i=0;i<e.changedTouches.length;i++){let r=e.changedTouches[i];if(r.identifier===this.fakeTouchFinger.id){let o=r.clientX-this.videoElementParentClientRect.left,a=r.clientY-this.videoElementParentClientRect.top,l=this.coordinateConverter.translateUnsigned(o,a);n.get("MouseUp")([D.mainButton,l.x,l.y]);let c=new MouseEvent("mouseleave",r);t.dispatchEvent(c),this.fakeTouchFinger=null;break}}e.preventDefault()}onTouchMove(e){if(!this.videoPlayer.isVideoReady()||this.fakeTouchFinger==null)return;let t=this.streamMessageController.toStreamerHandlers;for(let n=0;n<e.touches.length;n++){let i=e.touches[n];if(i.identifier===this.fakeTouchFinger.id){let r=i.clientX-this.videoElementParentClientRect.left,o=i.clientY-this.videoElementParentClientRect.top,a=this.coordinateConverter.translateUnsigned(r,o),l=this.coordinateConverter.translateSigned(r-this.fakeTouchFinger.x,o-this.fakeTouchFinger.y);t.get("MouseMove")([a.x,a.y,l.x,l.y]),this.fakeTouchFinger.x=r,this.fakeTouchFinger.y=o;break}}e.preventDefault()}};function ie(s){return JSON.parse(JSON.stringify({buttons:s.buttons.map(e=>JSON.parse(JSON.stringify({pressed:e.pressed,touched:e.touched,value:e.value}))),axes:s.axes}))}var de;(function(s){s[s.RightClusterBottomButton=0]="RightClusterBottomButton",s[s.RightClusterRightButton=1]="RightClusterRightButton",s[s.RightClusterLeftButton=2]="RightClusterLeftButton",s[s.RightClusterTopButton=3]="RightClusterTopButton",s[s.LeftShoulder=4]="LeftShoulder",s[s.RightShoulder=5]="RightShoulder",s[s.LeftTrigger=6]="LeftTrigger",s[s.RightTrigger=7]="RightTrigger",s[s.SelectOrBack=8]="SelectOrBack",s[s.StartOrForward=9]="StartOrForward",s[s.LeftAnalogPress=10]="LeftAnalogPress",s[s.RightAnalogPress=11]="RightAnalogPress",s[s.LeftClusterTopButton=12]="LeftClusterTopButton",s[s.LeftClusterBottomButton=13]="LeftClusterBottomButton",s[s.LeftClusterLeftButton=14]="LeftClusterLeftButton",s[s.LeftClusterRightButton=15]="LeftClusterRightButton",s[s.CentreButton=16]="CentreButton",s[s.LeftStickHorizontal=0]="LeftStickHorizontal",s[s.LeftStickVertical=1]="LeftStickVertical",s[s.RightStickHorizontal=2]="RightStickHorizontal",s[s.RightStickVertical=3]="RightStickVertical"})(de||(de={}));var cn=class{constructor(e){this.streamMessageController=e,this.onGamepadConnectedListener=this.onGamepadConnected.bind(this),this.onGamepadDisconnectedListener=this.onGamepadDisconnected.bind(this),this.beforeUnloadListener=this.onBeforeUnload.bind(this),this.requestAnimationFrame=(window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.requestAnimationFrame).bind(window)}register(){window.addEventListener("beforeunload",this.beforeUnloadListener);let e=window;if("GamepadEvent"in e?(window.addEventListener("gamepadconnected",this.onGamepadConnectedListener),window.addEventListener("gamepaddisconnected",this.onGamepadDisconnectedListener)):"WebKitGamepadEvent"in e&&(window.addEventListener("webkitgamepadconnected",this.onGamepadConnectedListener),window.addEventListener("webkitgamepaddisconnected",this.onGamepadDisconnectedListener)),this.controllers=[],navigator.getGamepads)for(let t of navigator.getGamepads())t&&this.onGamepadConnected(new GamepadEvent("gamepadconnected",{gamepad:t}))}unregister(){window.removeEventListener("gamepadconnected",this.onGamepadConnectedListener),window.removeEventListener("gamepaddisconnected",this.onGamepadDisconnectedListener),window.removeEventListener("webkitgamepadconnected",this.onGamepadConnectedListener),window.removeEventListener("webkitgamepaddisconnected",this.onGamepadDisconnectedListener);for(let e of this.controllers)e&&e.id!==void 0&&this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([e.id]);this.controllers=[]}onGamepadResponseReceived(e){for(let t of this.controllers)if(t&&t.id===void 0){t.id=e;break}}onGamepadConnected(e){let t=e.gamepad,n={currentState:ie(t),prevState:ie(t),id:void 0};this.controllers[t.index]=n,window.requestAnimationFrame(()=>this.updateStatus()),this.streamMessageController.toStreamerHandlers.get("GamepadConnected")()}onGamepadDisconnected(e){let t=e.gamepad,n=this.controllers[t.index];delete this.controllers[t.index],this.controllers=this.controllers.filter(i=>i!==void 0),n.id!==void 0&&this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([n.id])}scanGamepads(){let e=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[];for(let t=0;t<e.length;t++)e[t]&&this.controllers[e[t].index]!==void 0&&(this.controllers[e[t].index].currentState=e[t])}updateStatus(){this.scanGamepads();let e=this.streamMessageController.toStreamerHandlers;for(let t of this.controllers){if(!t)continue;let n=t.id===void 0?this.controllers.indexOf(t):t.id,i=t.currentState;for(let o=0;o<t.currentState.buttons.length;o++){let a=t.currentState.buttons[o],l=t.prevState.buttons[o];a.pressed?o==de.LeftTrigger?e.get("GamepadAnalog")([n,5,a.value]):o==de.RightTrigger?e.get("GamepadAnalog")([n,6,a.value]):e.get("GamepadButtonPressed")([n,o,l.pressed?1:0]):!a.pressed&&l.pressed&&(o==de.LeftTrigger?e.get("GamepadAnalog")([n,5,0]):o==de.RightTrigger?e.get("GamepadAnalog")([n,6,0]):e.get("GamepadButtonReleased")([n,o,0]))}for(let o=0;o<i.axes.length;o+=2){let a=parseFloat(i.axes[o].toFixed(4)),l=-parseFloat(i.axes[o+1].toFixed(4));e.get("GamepadAnalog")([n,o+1,a]),e.get("GamepadAnalog")([n,o+2,l])}let r=this.controllers.indexOf(t);this.controllers[r].prevState=ie(i)}this.controllers.length>0&&this.requestAnimationFrame(()=>this.updateStatus())}onBeforeUnload(e){for(let t of this.controllers)!t||t.id===void 0||this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([t.id])}};var dn=class{constructor(e,t,n){this.activeKeys=new xs,this.toStreamerMessagesProvider=e,this.videoElementProvider=t,this.coordinateConverter=n}registerKeyBoard(e){d.Info("Register Keyboard Events");let t=new sn(this.toStreamerMessagesProvider,e,this.activeKeys);return t.register(),t}registerMouse(e){d.Info("Register Mouse Events");let t;return e==ne.HoveringMouse?t=new on(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys):t=new rn(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys),t.register(),t}registerTouch(e){d.Info("Registering Touch");let t;return e?t=new ln(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter):t=new an(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter),t.register(),t}registerGamePad(){d.Info("Register Game Pad");let e=new cn(this.toStreamerMessagesProvider);return e.register(),e}},xs=class{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}};var hn=class{constructor(e,t){this.lastTimeResized=new Date().getTime(),this.videoElement=document.createElement("video"),this.config=t,this.videoElement.id="streamingVideo",this.videoElement.disablePictureInPicture=!0,this.videoElement.playsInline=!0,this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.pointerEvents="all",e.appendChild(this.videoElement),this.onResizePlayerCallback=()=>{console.log("Resolution changed, restyling player, did you forget to override this function?")},this.onMatchViewportResolutionCallback=()=>{console.log("Resolution changed and match viewport resolution is turned on, did you forget to override this function?")},this.videoElement.onclick=()=>{this.audioElement!=null&&this.audioElement.paused&&this.audioElement.play(),this.videoElement.paused&&this.videoElement.play()},this.videoElement.onloadedmetadata=()=>{this.onVideoInitialized()},window.addEventListener("resize",()=>this.resizePlayerStyle(),!0),window.addEventListener("orientationchange",()=>this.onOrientationChange())}destroy(){this.videoElement.src="",this.videoElement.srcObject=null,this.videoElement.remove(),this.audioElement&&(this.audioElement.src="",this.audioElement.srcObject=null,this.audioElement.remove())}setAudioElement(e){this.audioElement=e}play(){return this.videoElement.muted=this.config.isFlagEnabled(h.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(h.AutoPlayVideo),this.videoElement.play()}isPaused(){return this.videoElement.paused}isVideoReady(){return this.videoElement.readyState!==void 0&&this.videoElement.readyState>0}hasVideoSource(){return this.videoElement.srcObject!==void 0&&this.videoElement.srcObject!==null}getVideoElement(){return this.videoElement}getVideoParentElement(){var e;return(e=this.videoElement.parentElement)!==null&&e!==void 0?e:void 0}setVideoEnabled(e){this.videoElement.srcObject.getTracks().forEach(n=>n.enabled=e)}onVideoInitialized(){}onOrientationChange(){clearTimeout(this.orientationChangeTimeout),this.orientationChangeTimeout=window.setTimeout(()=>{this.resizePlayerStyle()},500)}resizePlayerStyle(){let e=this.getVideoParentElement();if(e){if(this.updateVideoStreamSize(),e.classList.contains("fixed-size")){this.onResizePlayerCallback();return}this.resizePlayerStyleToFillParentElement(),this.onResizePlayerCallback()}}resizePlayerStyleToFillParentElement(){this.getVideoParentElement().setAttribute("style","top: "+0+"px; left: "+0+"px; width: "+"100%"+"; height: "+"100%"+"; cursor: default;")}updateVideoStreamSize(){if(!this.config.isFlagEnabled(h.MatchViewportResolution))return;if(new Date().getTime()-this.lastTimeResized>300){let t=this.getVideoParentElement();if(!t)return;this.onMatchViewportResolutionCallback(t.clientWidth,t.clientHeight),this.lastTimeResized=new Date().getTime()}else d.Info("Resizing too often - skipping"),clearTimeout(this.resizeTimeoutHandle),this.resizeTimeoutHandle=window.setTimeout(()=>this.updateVideoStreamSize(),100)}};var un=class{constructor(){this.toStreamerHandlers=new Map,this.fromStreamerHandlers=new Map,this.toStreamerMessages=new Map,this.fromStreamerMessages=new Map}populateDefaultProtocol(){this.toStreamerMessages.set("IFrameRequest",{id:0,structure:[]}),this.toStreamerMessages.set("RequestQualityControl",{id:1,structure:[]}),this.toStreamerMessages.set("FpsRequest",{id:2,structure:[]}),this.toStreamerMessages.set("AverageBitrateRequest",{id:3,structure:[]}),this.toStreamerMessages.set("StartStreaming",{id:4,structure:[]}),this.toStreamerMessages.set("StopStreaming",{id:5,structure:[]}),this.toStreamerMessages.set("LatencyTest",{id:6,structure:["string"]}),this.toStreamerMessages.set("RequestInitialSettings",{id:7,structure:[]}),this.toStreamerMessages.set("TestEcho",{id:8,structure:[]}),this.toStreamerMessages.set("DataChannelLatencyTest",{id:9,structure:[]}),this.toStreamerMessages.set("UIInteraction",{id:50,structure:["string"]}),this.toStreamerMessages.set("Command",{id:51,structure:["string"]}),this.toStreamerMessages.set("TextboxEntry",{id:52,structure:["string"]}),this.toStreamerMessages.set("KeyDown",{id:60,structure:["uint8","uint8"]}),this.toStreamerMessages.set("KeyUp",{id:61,structure:["uint8"]}),this.toStreamerMessages.set("KeyPress",{id:62,structure:["uint16"]}),this.toStreamerMessages.set("MouseEnter",{id:70,structure:[]}),this.toStreamerMessages.set("MouseLeave",{id:71,structure:[]}),this.toStreamerMessages.set("MouseDown",{id:72,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseUp",{id:73,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("MouseMove",{id:74,structure:["uint16","uint16","int16","int16"]}),this.toStreamerMessages.set("MouseWheel",{id:75,structure:["int16","uint16","uint16"]}),this.toStreamerMessages.set("MouseDouble",{id:76,structure:["uint8","uint16","uint16"]}),this.toStreamerMessages.set("TouchStart",{id:80,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchEnd",{id:81,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("TouchMove",{id:82,structure:["uint8","uint16","uint16","uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadConnected",{id:93,structure:[]}),this.toStreamerMessages.set("GamepadButtonPressed",{id:90,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadButtonReleased",{id:91,structure:["uint8","uint8","uint8"]}),this.toStreamerMessages.set("GamepadAnalog",{id:92,structure:["uint8","uint8","double"]}),this.toStreamerMessages.set("GamepadDisconnected",{id:94,structure:["uint8"]}),this.fromStreamerMessages.set(0,"QualityControlOwnership"),this.fromStreamerMessages.set(1,"Response"),this.fromStreamerMessages.set(2,"Command"),this.fromStreamerMessages.set(3,"FreezeFrame"),this.fromStreamerMessages.set(4,"UnfreezeFrame"),this.fromStreamerMessages.set(5,"VideoEncoderAvgQP"),this.fromStreamerMessages.set(6,"LatencyTest"),this.fromStreamerMessages.set(7,"InitialSettings"),this.fromStreamerMessages.set(8,"FileExtension"),this.fromStreamerMessages.set(9,"FileMimeType"),this.fromStreamerMessages.set(10,"FileContents"),this.fromStreamerMessages.set(11,"TestEcho"),this.fromStreamerMessages.set(12,"InputControlOwnership"),this.fromStreamerMessages.set(13,"GamepadResponse"),this.fromStreamerMessages.set(14,"DataChannelLatencyTest"),this.fromStreamerMessages.set(255,"Protocol")}registerMessageHandler(e,t,n){switch(e){case S.ToStreamer:this.toStreamerHandlers.set(t,n);break;case S.FromStreamer:this.fromStreamerHandlers.set(t,n);break;default:d.Info(`Unknown message direction ${e}`)}}},S;(function(s){s[s.ToStreamer=0]="ToStreamer",s[s.FromStreamer=1]="FromStreamer"})(S||(S={}));var pn=class{constructor(){this.responseEventListeners=new Map}addResponseEventListener(e,t){this.responseEventListeners.set(e,t)}removeResponseEventListener(e){this.responseEventListeners.delete(e)}onResponse(e){d.Info("DataChannelReceiveMessageType.Response");let t=new TextDecoder("utf-16").decode(e.slice(1));d.Info(t),this.responseEventListeners.forEach(n=>{n(t)})}};var mn=class{constructor(e,t){this.dataChannelSender=e,this.toStreamerMessagesMapProvider=t}sendMessageToStreamer(e,t){t===void 0&&(t=[]);let i=this.toStreamerMessagesMapProvider.toStreamerMessages.get(e);if(i===void 0){d.Error(`Attempted to send a message to the streamer with message type: ${e}, but the frontend hasn't been configured to send such a message. Check you've added the message type in your cpp`);return}if(i.structure&&t&&i.structure.length!==t.length){d.Error(`Provided message data doesn't match expected layout. Expected [ ${i.structure.map(c=>{switch(c){case"uint8":case"uint16":case"int16":case"float":case"double":default:return"number";case"string":return"string"}}).toString()} ] but received [ ${t.map(c=>typeof c).toString()} ]`);return}let r=0,o=new TextEncoder;t.forEach((c,u)=>{switch(i.structure[u]){case"uint8":r+=1;break;case"uint16":r+=2;break;case"int16":r+=2;break;case"float":r+=4;break;case"double":r+=8;break;case"string":r+=2,r+=2*o.encode(c).length;break}});let a=new DataView(new ArrayBuffer(r+1));a.setUint8(0,i.id);let l=1;if(t.forEach((c,u)=>{switch(i.structure[u]){case"uint8":a.setUint8(l,c),l+=1;break;case"uint16":a.setUint16(l,c,!0),l+=2;break;case"int16":a.setInt16(l,c,!0),l+=2;break;case"float":a.setFloat32(l,c,!0),l+=4;break;case"double":a.setFloat64(l,c,!0),l+=8;break;case"string":a.setUint16(l,c.length,!0),l+=2;for(let v=0;v<c.length;v++)a.setUint16(l,c.charCodeAt(v),!0),l+=2;break}}),!this.dataChannelSender.canSend()){d.Info(`Data channel cannot send yet, skipping sending message: ${e} - ${new Uint8Array(a.buffer)}`);return}this.dataChannelSender.sendData(a.buffer)}};var fn=class{constructor(e){this.sendMessageController=e}SendRequestQualityControl(){this.sendMessageController.sendMessageToStreamer("RequestQualityControl")}SendMaxFpsRequest(){this.sendMessageController.sendMessageToStreamer("FpsRequest")}SendAverageBitrateRequest(){this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest")}SendStartStreaming(){this.sendMessageController.sendMessageToStreamer("StartStreaming")}SendStopStreaming(){this.sendMessageController.sendMessageToStreamer("StopStreaming")}SendRequestInitialSettings(){this.sendMessageController.sendMessageToStreamer("RequestInitialSettings")}};var gn=class{constructor(e){this.dataChannelProvider=e}canSend(){return this.dataChannelProvider.getDataChannelInstance().dataChannel!==void 0&&this.dataChannelProvider.getDataChannelInstance().dataChannel.readyState=="open"}sendData(e){let t=this.dataChannelProvider.getDataChannelInstance();t.dataChannel.readyState=="open"?(t.dataChannel.send(e),d.Info(`Message Sent: ${new Uint8Array(e)}`),this.resetAfkWarningTimerOnDataSend()):d.Error(`Message Failed: ${new Uint8Array(e)}`)}resetAfkWarningTimerOnDataSend(){}};var yn=class{reconfigure(e,t){let n=e.height/e.width,i=t.height/t.width;this.playerIsLarger=n>i,this.playerSize=e,this.ratio=this.playerIsLarger?n/i:i/n}translateUnsigned(e,t){let n=this.playerIsLarger?e/this.playerSize.width:this.ratio*(e/this.playerSize.width-.5)+.5,i=this.playerIsLarger?this.ratio*(t/this.playerSize.height-.5)+.5:t/this.playerSize.height;return n<0||n>1||i<0||i>1?{inRange:!1,x:65535,y:65535}:{inRange:!0,x:n*65536,y:i*65536}}translateSigned(e,t){let n=this.playerIsLarger?e/(.5*this.playerSize.width):this.ratio*e/(.5*this.playerSize.width),i=this.playerIsLarger?this.ratio*t/(.5*this.playerSize.height):t/(.5*this.playerSize.height);return{x:n*32767,y:i*32767}}untranslateUnsigned(e,t){let n=this.playerIsLarger?e/65536:(e/65536-.5)/this.ratio+.5,i=this.playerIsLarger?(t/65536-.5)/this.ratio+.5:t/65536;return{x:n*this.playerSize.width,y:i*this.playerSize.height}}};var he=class{constructor(e){this._urlParams={};let t=new URLSearchParams(e);for(let[n,i]of t)this._urlParams[n.toLowerCase()]=i}has(e){return e.toLowerCase()in this._urlParams}get(e){return this.has(e)?this._urlParams[e.toLowerCase()]:null}};var Sn=class{constructor(e,t){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=e,this.pixelStreaming=t,this.responseController=new pn,this.file=new nn,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new $t(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity.",!1)},this.freezeFrameController=new it(this.pixelStreaming.videoElementParent),this.videoPlayer=new hn(this.pixelStreaming.videoElementParent,this.config),this.videoPlayer.onVideoInitialized=()=>this.handleVideoInitialized(),this.videoPlayer.onMatchViewportResolutionCallback=(n,i)=>{let r={"Resolution.Width":n,"Resolution.Height":i};this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(r)])},this.videoPlayer.onResizePlayerCallback=()=>{this.setUpMouseAndFreezeFrame()},this.streamController=new tt(this.videoPlayer),this.coordinateConverter=new yn,this.sendrecvDataChannelController=new Ce,this.recvDataChannelController=new Ce,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new gn(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new un,this.transport=new me(e.webSocketProtocols),this.protocol=new fe(this.transport),this.protocol.addListener(P.config.typeName,n=>this.handleOnConfigMessage(n)),this.protocol.addListener(P.ping.typeName,n=>this.handlePingMessage(n)),this.protocol.addListener(P.streamerList.typeName,n=>this.handleStreamerListMessage(n)),this.protocol.addListener(P.subscribeFailed.typeName,n=>this.handleSubscribeFailedMessage(n)),this.protocol.addListener(P.streamerIdChanged.typeName,n=>this.handleStreamerIDChangedMessage(n)),this.protocol.addListener(P.playerCount.typeName,n=>{let i=n;this.pixelStreaming._onPlayerCount(i.count)}),this.protocol.addListener(P.answer.typeName,n=>this.handleWebRtcAnswer(n)),this.protocol.addListener(P.offer.typeName,n=>this.handleWebRtcOffer(n)),this.protocol.addListener(P.peerDataChannels.typeName,n=>this.handleWebRtcSFUPeerDatachannels(n)),this.protocol.addListener(P.iceCandidate.typeName,n=>{let i=n;this.handleIceCandidate(i.candidate)}),this.protocol.transport.addListener("open",()=>{if(!this.config.isFlagEnabled(h.BrowserSendOffer)){let i=_.createMessage(P.listStreamers);this.protocol.sendMessage(i)}this.reconnectAttempt=0,this.isReconnecting=!1}),this.protocol.transport.addListener("error",()=>{d.Error("Got a transport error.")}),this.protocol.transport.addListener("close",n=>{let r=this.config.getNumericSettingValue(m.MaxReconnectAttempts),o=this.reconnectAttempt<r,l=(this.forceReconnect||this.enableAutoReconnect&&r>0&&o)&&n.code!=1001,c=!l,u=this.disconnectMessage?this.disconnectMessage:n.reason;this.forceReconnect=!1,this.config.getSettingOption(M.PreferredCodec).options=Y.getSupportedVideoCodecs(),this.pixelStreaming._onDisconnect(u,c),this.afkController.stopAfkWarningTimer(),this.statsTimerHandle&&this.statsTimerHandle!==void 0&&window.clearInterval(this.statsTimerHandle),this.setVideoEncoderAvgQP(0),this.setTouchInputEnabled(!1),this.setMouseInputEnabled(!1),this.setKeyboardInputEnabled(!1),this.setGamePadInputEnabled(!1),l&&setTimeout(()=>{this.reconnectAttempt++,this.doReconnect(n.reason)},2e3)}),this.sendMessageController=new mn(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new fn(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new dn(this.streamMessageController,this.videoPlayer,this.coordinateConverter),this.isUsingSFU=!1,this.isUsingSVC=!1,this.isQualityController=!1,this.preferredCodec="",this.enableAutoReconnect=!0,this.forceReconnect=!1,this.reconnectAttempt=0,this.isReconnecting=!1,this.config._addOnOptionSettingChangedListener(M.StreamerId,n=>{if(n===void 0||n==="")return;this.peerConnectionController.peerConnection.close(),this.peerConnectionController.createPeerConnection(this.peerConfig,this.preferredCodec),this.subscribedStream=n;let i=_.createMessage(P.subscribe,{streamerId:n});this.protocol.sendMessage(i)}),this.config._addOnOptionSettingChangedListener(M.PreferredQuality,n=>{if(n===void 0||n==="")return;let i;if(this.isUsingSVC)i=_.createMessage(P.layerPreference,{spatialLayer:+n[1]-1,temporalLayer:+n[3]-1});else{let o=this.config.getSettingOption(M.PreferredQuality).options.indexOf(n);i=_.createMessage(P.layerPreference,{spatialLayer:o,temporalLayer:0})}this.protocol.sendMessage(i)}),this.setVideoEncoderAvgQP(-1),this.signallingUrlBuilder=()=>this.config.getTextSettingValue(z.SignallingServerUrl)}destroyVideoPlayer(){this.videoPlayer.destroy()}handleOnMessage(e){let t=new Uint8Array(e.data);d.Info("Message incoming:"+t);let n=this.streamMessageController.fromStreamerMessages.get(t[0]);this.streamMessageController.fromStreamerHandlers.get(n)(e.data)}registerMessageHandlers(){this.streamMessageController.registerMessageHandler(S.FromStreamer,"QualityControlOwnership",e=>this.onQualityControlOwnership(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"Response",e=>this.responseController.onResponse(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"Command",e=>{this.onCommand(e)}),this.streamMessageController.registerMessageHandler(S.FromStreamer,"FreezeFrame",e=>this.onFreezeFrameMessage(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"UnfreezeFrame",()=>this.invalidateFreezeFrameAndEnableVideo()),this.streamMessageController.registerMessageHandler(S.FromStreamer,"VideoEncoderAvgQP",e=>this.handleVideoEncoderAvgQP(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"LatencyTest",e=>this.handleLatencyTestResult(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"DataChannelLatencyTest",e=>this.handleDataChannelLatencyTestResponse(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"InitialSettings",e=>this.handleInitialSettings(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"FileExtension",e=>this.onFileExtension(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"FileMimeType",e=>this.onFileMimeType(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"FileContents",e=>this.onFileContents(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"TestEcho",()=>{}),this.streamMessageController.registerMessageHandler(S.FromStreamer,"InputControlOwnership",e=>this.onInputControlOwnership(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"GamepadResponse",e=>this.onGamepadResponse(e)),this.streamMessageController.registerMessageHandler(S.FromStreamer,"Multiplexed",()=>{}),this.streamMessageController.registerMessageHandler(S.FromStreamer,"Protocol",e=>this.onProtocolMessage(e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"IFrameRequest",()=>this.sendMessageController.sendMessageToStreamer("IFrameRequest")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"RequestQualityControl",()=>this.sendMessageController.sendMessageToStreamer("RequestQualityControl")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"FpsRequest",()=>this.sendMessageController.sendMessageToStreamer("FpsRequest")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"AverageBitrateRequest",()=>this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"StartStreaming",()=>this.sendMessageController.sendMessageToStreamer("StartStreaming")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"StopStreaming",()=>this.sendMessageController.sendMessageToStreamer("StopStreaming")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"LatencyTest",e=>this.sendMessageController.sendMessageToStreamer("LatencyTest",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"RequestInitialSettings",()=>this.sendMessageController.sendMessageToStreamer("RequestInitialSettings")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"TestEcho",()=>{}),this.streamMessageController.registerMessageHandler(S.ToStreamer,"UIInteraction",e=>this.sendMessageController.sendMessageToStreamer("UIInteraction",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"Command",e=>this.sendMessageController.sendMessageToStreamer("Command",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"TextboxEntry",e=>this.sendMessageController.sendMessageToStreamer("TextboxEntry",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"KeyDown",e=>this.sendMessageController.sendMessageToStreamer("KeyDown",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"KeyUp",e=>this.sendMessageController.sendMessageToStreamer("KeyUp",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"KeyPress",e=>this.sendMessageController.sendMessageToStreamer("KeyPress",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"MouseEnter",e=>this.sendMessageController.sendMessageToStreamer("MouseEnter",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"MouseLeave",e=>this.sendMessageController.sendMessageToStreamer("MouseLeave",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"MouseDown",e=>this.sendMessageController.sendMessageToStreamer("MouseDown",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"MouseUp",e=>this.sendMessageController.sendMessageToStreamer("MouseUp",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"MouseMove",e=>this.sendMessageController.sendMessageToStreamer("MouseMove",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"MouseWheel",e=>this.sendMessageController.sendMessageToStreamer("MouseWheel",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"MouseDouble",e=>this.sendMessageController.sendMessageToStreamer("MouseDouble",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"TouchStart",e=>this.sendMessageController.sendMessageToStreamer("TouchStart",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"TouchEnd",e=>this.sendMessageController.sendMessageToStreamer("TouchEnd",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"TouchMove",e=>this.sendMessageController.sendMessageToStreamer("TouchMove",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"GamepadConnected",()=>this.sendMessageController.sendMessageToStreamer("GamepadConnected")),this.streamMessageController.registerMessageHandler(S.ToStreamer,"GamepadButtonPressed",e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonPressed",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"GamepadButtonReleased",e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonReleased",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"GamepadAnalog",e=>this.sendMessageController.sendMessageToStreamer("GamepadAnalog",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"GamepadDisconnected",e=>this.sendMessageController.sendMessageToStreamer("GamepadDisconnected",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XREyeViews",e=>this.sendMessageController.sendMessageToStreamer("XREyeViews",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRHMDTransform",e=>this.sendMessageController.sendMessageToStreamer("XRHMDTransform",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRControllerTransform",e=>this.sendMessageController.sendMessageToStreamer("XRControllerTransform",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRSystem",e=>this.sendMessageController.sendMessageToStreamer("XRSystem",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRButtonTouched",e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouched",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRButtonTouchReleased",e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouchReleased",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRButtonPressed",e=>this.sendMessageController.sendMessageToStreamer("XRButtonPressed",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRButtonReleased",e=>this.sendMessageController.sendMessageToStreamer("XRButtonReleased",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"XRAnalog",e=>this.sendMessageController.sendMessageToStreamer("XRAnalog",e)),this.streamMessageController.registerMessageHandler(S.ToStreamer,"ChannelRelayStatus",()=>{}),this.streamMessageController.registerMessageHandler(S.ToStreamer,"Multiplexed",()=>{})}onCommand(e){d.Info("DataChannelReceiveMessageType.Command");let t=new TextDecoder("utf-16").decode(e.slice(1));d.Info("Data Channel Command: "+t);let n=JSON.parse(t);n.command==="onScreenKeyboard"&&this.handleOnScreenKeyboardCommand(n)}handleOnScreenKeyboardCommand(e){var t,n,i,r;let o={showOnScreenKeyboard:(t=e.showOnScreenKeyboard)!==null&&t!==void 0?t:!0,x:(n=e.x)!==null&&n!==void 0?n:0,y:(i=e.y)!==null&&i!==void 0?i:0,contents:(r=e.contents)!==null&&r!==void 0?r:""};this.pixelStreaming.dispatchEvent(new Ft(o))}onProtocolMessage(e){try{let t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);Object.prototype.hasOwnProperty.call(n,"Direction")||d.Error("Malformed protocol received. Ensure the protocol message contains a direction");let i=n.Direction;delete n.Direction,d.Info(`Received new ${i==S.FromStreamer?"FromStreamer":"ToStreamer"} protocol. Updating existing protocol...`),Object.keys(n).forEach(r=>{let o=n[r];switch(i){case S.ToStreamer:if(!Object.prototype.hasOwnProperty.call(o,"id")){d.Error(`ToStreamer->${r} protocol definition was malformed as it didn't contain at least an id
|
|
47
47
|
|
|
48
48
|
Definition was: ${JSON.stringify(o,null,2)}`);return}if(r==="UIInteraction"||r==="Command"||r==="LatencyTest")return;this.streamMessageController.toStreamerHandlers.get(r)?this.streamMessageController.toStreamerMessages.set(r,o):d.Error(`There was no registered handler for "${r}" - try adding one using registerMessageHandler(MessageDirection.ToStreamer, "${r}", myHandler)`);break;case S.FromStreamer:if(!Object.prototype.hasOwnProperty.call(o,"id")){d.Error(`FromStreamer->${r} protocol definition was malformed as it didn't contain at least an id
|
|
49
49
|
|
|
@@ -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 Vt({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 wn=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 Cn=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 wn(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 Ht,this.configureSettings(),this.setWebRtcPlayerController(new Sn(this.config,this)),this._webXrController=new vn(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 Ct),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Tt),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Mt),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 ut)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new ct)}_onWebRtcSdpOffer(e){this._eventEmitter.dispatchEvent(new ht({sdp:e}))}_onWebRtcSdpAnswer(e){this._eventEmitter.dispatchEvent(new dt({sdp:e}))}_onLatencyCalculated(e){this._eventEmitter.dispatchEvent(new Ot({latencyInfo:e}))}_onStreamLoading(){this._eventEmitter.dispatchEvent(new wt)}_onDisconnect(e,t){this._eventEmitter.dispatchEvent(new gt({eventString:e,allowClickToReconnect:t}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new pt)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new mt)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new ft)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new vt),this._videoStartTime=Date.now()}_onLatencyTestResult(e){this._eventEmitter.dispatchEvent(new Dt({latencyTimings:e}))}_onDataChannelLatencyTestResponse(e){this._eventEmitter.dispatchEvent(new At({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 It({aggregatedStats:e}))}_onVideoEncoderAvgQP(e){this._eventEmitter.dispatchEvent(new lt({avgQP:e}))}_onInitialSettings(e){var t;this._eventEmitter.dispatchEvent(new Bt({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 he(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 _t({count:e}))}_onSubscribeFailed(e){this._eventEmitter.dispatchEvent(new Ut({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 Wt),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 Cn(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),t=>{this._eventEmitter.dispatchEvent(new Nt({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 Mn=class{type=0},Tn=class{type=1},En=class{constructor(e){this.msg=e}msg;type=2};var Rn=class{constructor(e){this.stats=e}stats;type=5};var cr="sessionEndedByUser",xs="sessionEndedDueToConnectionLoss",ks="sessionEndedDueToVideoPlaybackError",dr="sessionEndedDueToPermissionsError";var Is="sessionEndedDueToRendererError";var hr=(n=>(n.Good="Good",n.Fair="Fair",n.Poor="Poor",n))(hr||{}),ur=(n=>(n.Always="always",n.WhenDegraded="when-degraded",n.Hidden="hidden",n))(ur||{}),pr=(i=>(i.TopLeft="top-left",i.TopRight="top-right",i.BottomLeft="bottom-left",i.BottomRight="bottom-right",i))(pr||{}),mr=(n=>(n.Click="click",n.Hover="hover",n.None="none",n))(mr||{});function ke(s,e,t){return Math.max(e,Math.min(s,t))}function fr(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?ke(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=ke(l-w-v,0,100),x=1+.035*C+C*(C-60)*(100-C)*7/1e6;return ke(Math.round(x*100)/100,1,5)}function gr(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,x=ke(.56*Math.log(v)+5.36,1,5)-1.9*Math.log(a/o)-w*.002;return ke(Math.round(x*100)/100,1,5)}var Xr=3.5,Jr=2.5,ue=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,x=i>0?(e.video.bytesReceived-t.video.bytesReceived)*8/i/1e3:0,U=e.connection.currentRoundTripTime*1e3,H=fr({packetLoss:l,bitrate:c*1e3,roundTripTime:U,bufferDelay:e.audio.jitter*1e3}),A=n.expectedFrameRate??30,wr=e.video.codecMimeType?.toLowerCase()??"",Cr=[["vp9","vp9"],["vp8","vp8"],["h264","h264"],["avc","h264"],["h265","h265"],["hevc","h265"],["av1","av1"]].find(([Mr])=>wr.includes(Mr))?.[1],Ds=gr({bitrate:x*1e3,roundTripTime:U,width:e.video.frameWidth,height:e.video.frameHeight,frameRate:e.video.framesPerSecond,expectedFrameRate:A,codec:Cr}),Os=Math.min(H,Ds),Le;return Os>=Xr?Le="Good":Os>=Jr?Le="Fair":Le="Poor",{audioPacketLossPercent:Math.round(l*100)/100,videoPacketLossPercent:Math.round(C*100)/100,audioBitrateKbps:Math.round(c),videoBitrateKbps:Math.round(x),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:Ds,qualityLevel:Le}}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 wn(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 Ht,this.configureSettings(),this.setWebRtcPlayerController(new Sn(this.config,this)),this._webXrController=new vn(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 Ct),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Tt),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Mt),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 ut)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new ct)}_onWebRtcSdpOffer(e){this._eventEmitter.dispatchEvent(new ht({sdp:e}))}_onWebRtcSdpAnswer(e){this._eventEmitter.dispatchEvent(new dt({sdp:e}))}_onLatencyCalculated(e){this._eventEmitter.dispatchEvent(new Ot({latencyInfo:e}))}_onStreamLoading(){this._eventEmitter.dispatchEvent(new wt)}_onDisconnect(e,t){this._eventEmitter.dispatchEvent(new gt({eventString:e,allowClickToReconnect:t}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new pt)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new mt)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new ft)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new vt),this._videoStartTime=Date.now()}_onLatencyTestResult(e){this._eventEmitter.dispatchEvent(new Dt({latencyTimings:e}))}_onDataChannelLatencyTestResponse(e){this._eventEmitter.dispatchEvent(new At({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 It({aggregatedStats:e}))}_onVideoEncoderAvgQP(e){this._eventEmitter.dispatchEvent(new lt({avgQP:e}))}_onInitialSettings(e){var t;this._eventEmitter.dispatchEvent(new Bt({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 he(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 _t({count:e}))}_onSubscribeFailed(e){this._eventEmitter.dispatchEvent(new Ut({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 Wt),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 Cn(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),t=>{this._eventEmitter.dispatchEvent(new Nt({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 Mn=class{type=0},Tn=class{type=1},En=class{constructor(e){this.msg=e}msg;type=2};var Rn=class{constructor(e){this.stats=e}stats;type=5};var dr="sessionEndedByUser",ks="sessionEndedDueToConnectionLoss",Is="sessionEndedDueToVideoPlaybackError",hr="sessionEndedDueToPermissionsError";var Ps="sessionEndedDueToRendererError";var ur=(n=>(n.Good="Good",n.Fair="Fair",n.Poor="Poor",n))(ur||{}),pr=(n=>(n.Always="always",n.WhenDegraded="when-degraded",n.Hidden="hidden",n))(pr||{}),mr=(i=>(i.TopLeft="top-left",i.TopRight="top-right",i.BottomLeft="bottom-left",i.BottomRight="bottom-right",i))(mr||{}),fr=(n=>(n.Click="click",n.Hover="hover",n.None="none",n))(fr||{});function ke(s,e,t){return Math.max(e,Math.min(s,t))}function gr(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?ke(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=ke(l-w-v,0,100),x=1+.035*C+C*(C-60)*(100-C)*7/1e6;return ke(Math.round(x*100)/100,1,5)}function yr(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,x=ke(.56*Math.log(v)+5.36,1,5)-1.9*Math.log(a/o)-w*.002;return ke(Math.round(x*100)/100,1,5)}var Jr=3.5,Yr=2.5,ue=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,x=i>0?(e.video.bytesReceived-t.video.bytesReceived)*8/i/1e3:0,U=e.connection.currentRoundTripTime*1e3,H=gr({packetLoss:l,bitrate:c*1e3,roundTripTime:U,bufferDelay:e.audio.jitter*1e3}),A=n.expectedFrameRate??30,Cr=e.video.codecMimeType?.toLowerCase()??"",Mr=[["vp9","vp9"],["vp8","vp8"],["h264","h264"],["avc","h264"],["h265","h265"],["hevc","h265"],["av1","av1"]].find(([Tr])=>Cr.includes(Tr))?.[1],Os=yr({bitrate:x*1e3,roundTripTime:U,width:e.video.frameWidth,height:e.video.frameHeight,frameRate:e.video.framesPerSecond,expectedFrameRate:A,codec:Mr}),Fs=Math.min(H,Os),Le;return Fs>=Jr?Le="Good":Fs>=Yr?Le="Fair":Le="Poor",{audioPacketLossPercent:Math.round(l*100)/100,videoPacketLossPercent:Math.round(C*100)/100,audioBitrateKbps:Math.round(c),videoBitrateKbps:Math.round(x),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:Os,qualityLevel:Le}}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){p.debug(`Video element muted: ${this.videoElement?.muted}, (should be true as part of avoiding auto play restrictions)`),p.debug(`Audio element muted: ${this.audioElement?.muted}, (should be false to be able to hear the digital human)`),p.debug(`Audio element volume: ${this.audioElement?.volume}, (should be greater than zero to be able to hear the digital human)`);let t=e?.mimeType;t&&this.audioElement&&(p.debug(`Audio element can play webrtc audio codec (${t}) : ${this.audioElement.canPlayType(t)}, (should be 'probably' or 'maybe)'`),t==="audio/opus"&&p.debug(`Audio codec opus is often known as ogg, so checking can play ogg codec: ${this.audioElement.canPlayType("audio/ogg")}, (should be 'probably' or 'maybe')`))}};var Ie={good:"#22c55e",fair:"#eab308",poor:"#ef4444",inactive:"#6b7280"},xn=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:Ie.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,x;c>=l||u>=l?(C=u>=l&&(c<l||u>=c)?o.bottom+e:o.top-e-l,x=this.position==="top-left"||this.position==="bottom-left"?o.left:o.right-a):(x=v>=a&&(w<a||v>=w)?o.right+e:o.left-e-a,C=o.bottom-l),x=Math.max(t,Math.min(x,n-a-t)),C=Math.max(0,Math.min(C,i-l-t)),this.panel.style.top=`${C}px`,this.panel.style.left=`${x}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 Ie.good;case"Fair":return Ie.fair;case"Poor":return Ie.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:Ie.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 kn=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 Yr;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 ii);let e=se(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(q.Warning,!1);let n=function(){let i=t.getTextSettingValue(z.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 j(`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(){if(p.info("Video initialized."),this.videoElement=this.videoContainerElement?.getElementsByTagName("video")[0],this.audioElement=this.stream?.webRtcController?.streamController?.audioElement,this.audioStatsAnalyzer=new ue(this.stream,this.videoElement,this.audioElement),this.audioElement&&this.config.speakerDeviceId&&this.setSpeakerDevice(this.audioElement,this.config.speakerDeviceId),this.videoElement)this.videoElement.muted=!0,this.videoElement.play().then(()=>{this.playAudioElement()}).catch(e=>{if(e instanceof DOMException&&e.name==="NotAllowedError")p.error('Fatal Error: Video cannot be played. User interaction or client permissions update is required to be able to "play" the video element.',e),this.clientMessages?.next(new An(e)),this.endSession(dr,!0);else{let t="Fatal Error: Digital Human video cannot be played.";p.error(t,p.serialiseError(e)),this.clientMessages?.next(new j(t)),this.endSession(ks,!0)}}),this.videoInitialized=!0,this.messages.next(new Mn),this.reconnectionAttempts=0,this.clearReconnectTimer();else{let e="Fatal Error: Video element not found.";p.error(e),this.clientMessages?.next(new j(e)),this.endSession(ks,!0)}setTimeout(()=>{this.clientMessages?.next(new ei)},Ps)}playAudioElement(){this.audioElement?this.audioElement.play().then(()=>{p.info("Audio played successfully."),this.clientMessages?.next(new qn)}).catch(e=>{p.warn("Audio cannot be played.",e),this.clientMessages?.next(new De),this.clientMessages?.next(new $n)}):this.handleMissingAudioElement()}pauseAudioElement(){this.audioElement?(this.audioElement.pause(),this.clientMessages?.next(new De)):this.handleMissingAudioElement()}muteUpstreamMic(){if(!se(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(!se(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 j(e))}startAudioStatsMonitor(e=5e3){this.stopAudioStatsMonitor(),p.info("Starting audio stats monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new ue(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 ue(this.stream,this.videoElement,this.audioElement)),this.videoContainerElement&&e.visibility!=="hidden"&&(this.networkIndicator=new xn(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 oi(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 Tn)}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 Rn(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(),this.clientMessages?.next(new Zn)},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.scheduleReconnect()):(p.info("Max reconnection attempts reached. Ending session."),this.clientMessages?.next(new Yn),this.endSession(xs,!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 j("Error during reconnection attempt")),this.endSession(xs,!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 En(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 Vn(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 Jn(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 si),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 ri)}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 Oe(n,i)),this.endSession(Is,!0)}catch(t){p.error("Signaling: Failed to parse renderer error message",p.serialiseError(t)),this.clientMessages?.next(new Oe(-1,"An unknown renderer error occurred")),this.endSession(Is,!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();p.info("Signaling: Sending data channel message",JSON.stringify(t)),t.action==="chat_prompt"&&this.clientMessages?.next(new Qn(t.data)),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=cr,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 zn(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 ti)}stopSoftSwitch(){p.info("Signaling: Stop soft switching"),this.clientMessages?.next(new ni)}};import{Subject as Zr}from"rxjs";var yr=(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))(yr||{}),Sr=(i=>(i.Left="left",i.Right="right",i.Center="center",i.Centre="centre",i))(Sr||{}),Pe=class{constructor(e,t=2e3,n=$()){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 In=class{constructor(e,t=$()){this.avatarId=e;this.requestId=t}avatarId;requestId;toJSON(){return{action:"change_avatar",data:{id:this.avatarId,requestId:this.requestId}}}};var Pn=class{constructor(e,t=$()){this.actionName=e;this.requestId=t}actionName;requestId;toJSON(){return{action:"trigger_action",data:{action_name:this.actionName,requestId:this.requestId}}}};var Ln=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 br=[1103,1200,1402];var Ps=750,Dn=class{constructor(e){this.config=e;this.sessionTransferManager=new Ln(this),this._audioUpstreamMode=G(this.config.audioUpstreamMode)}config;id;signaling;messages=new Zr;speechRec;promptMetadata={};audioStreamId;sessionTransferManager;jwt;welcomeRequested=!1;resolutionLogged=!1;_audioUpstreamMode;get audioUpstreamMode(){return this._audioUpstreamMode}updatePromptMetadata(e){try{JSON.parse(JSON.stringify(e)),this.promptMetadata.custom=e,this.messages.next(new jn(this.promptMetadata))}catch(t){p.error("Error parsing custom metadata",e,p.serialiseError(t))}}setEnableMicrophone(e){let t=this.audioUpstreamMode;this.config.enableMicrophone=e;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")),se(t)&&(this.signaling?(e?this.signaling.unmuteUpstreamMic():this.signaling.muteUpstreamMic(),n=!0,X(t)||this.messages.next(new Kn(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?`)}setCameraAnchorDistance(e,t=0,n=this.signaling){this.config.cameraAnchorDistance=e,n?.dataSend(new Pe(e,t))}setCameraAnchorHorizontal(e,t=0,n=this.signaling){this.config.cameraAnchorHorizontal=e,n?.dataSend(new Pe(e,t))}changeAvatar(e,t=this.signaling){t?.dataSend(new In(e))}userStartSpeaking(e=this.signaling){e?.dataSend(new ai("start"))}userStopSpeaking(e=this.signaling){e?.dataSend(new ai("stop"))}triggerAction(e,t=this.signaling){t?.dataSend(new Pn(e))}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)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";p.info(`Session, skipping speech recognition restart after ${t} (microphone disabled)`)}}}),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 kn(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 _n(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 Bn(this.id)),this.config.networkIndicator&&e.startNetworkQualityMonitor(this.config.networkIndicator)},Ps))}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.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-NFBHMIH6.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-Y6E3H2SK.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,useEagerEndOfTurn:t.useEagerEndOfTurn,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-X5UIRUSW.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 Gn(e.msg));break}case"avatar_started_speaking":{this.messages.next(new Nn);break}case"avatar_stopped_speaking":{this.messages.next(new Un);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 Hn(e.msg));break}case"session_ended":{this.signaling?.endSession(e.msg.reason),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&&br.includes(e.code)?this.messages.next(new Wn(e)):this.messages.next(new j(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 Fe(this.config.welcomePrompt,this.promptMetadata)))}listenForTabClosure(){window.addEventListener("beforeunload",()=>{p.info("Window unload detected, ending session."),this.signaling?.endSession(),this.signaling=void 0})}};var On=class{constructor(e,t=$()){this.prompt=e;this.requestId=t}prompt;requestId;toJSON(){return{action:"speak",data:{requestId:this.requestId,prompt:this.prompt}}}};var pe=class{constructor(e,t,n={},i=$()){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 Fn=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 vr(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 Ls=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&&!Us(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 Dn(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 Fe(e,this.session?.promptMetadata))}speak(e){e&&e.trim()!==""&&this.ensureSessionExists()&&this.session?.signaling?.dataSend(new On(e))}openAudioStream(){let e=this.session;this.ensureSessionExists()&&e?.signaling?.dataSend(new pe("open",e?.audioStreamId))}closeAudioStream(){let e=this.session;this.ensureSessionExists()&&e?.audioStreamId!==void 0&&e.signaling?.dataSend(new pe("close",e.audioStreamId))}interruptAudioStream(){let e=this.session;this.ensureSessionExists()&&e?.audioStreamId!==void 0&&e.signaling?.dataSend(new pe("interrupt",e.audioStreamId))}async speakAudio(e){this.ensureSessionExists()&&await vr(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)}userStartSpeaking(){this.ensureSessionExists()&&this.session?.userStartSpeaking()}userStopSpeaking(){this.ensureSessionExists()&&this.session?.userStopSpeaking()}triggerAction(e){e&&e.trim()!==""&&this.ensureSessionExists()&&this.session?.triggerAction(e)}executeCommand(e,t,n,i){this.ensureSessionExists()&&this.session?.signaling?.dataSend(new Fn(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 Ns)}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?.speechRec?.pause()??!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?.speechRec?.resume()??!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,t?this.session.signaling?.startAudioStatsMonitor():this.session.signaling?.stopAudioStatsMonitor())}setNetworkIndicatorEnabled(e){this.ensureSessionExists()&&(e?this.session?.signaling?.startNetworkQualityMonitor(e):this.session?.signaling?.stopNetworkQualityMonitor())}};export{xr as AvatarAnswerMessage,Dr as AvatarInterruptedMessage,Nn as AvatarStartedSpeakingMessage,Un as AvatarStoppedSpeakingMessage,yr as CameraAnchorDistance,Sr as CameraAnchorHorizontal,jn as CustomMetadataUpdated,ri as CustomerConcurrencyLimitReachedMessage,An as DeviceErrorMessage,De as DigitalHumanMuted,$n as DigitalHumanPlayedInMutedModeSuccess,qn as DigitalHumanUnmuted,Kn as EnableMicrophoneUpdatedMessage,Rr as LogLevel,mr as NetworkIndicatorPopupTrigger,pr as NetworkIndicatorPosition,ur as NetworkIndicatorVisibility,hr as NetworkQualityLevel,oi as NetworkQualityMessage,Qn as PromptRequestMessage,Gn as PromptResultMessage,Oe as RendererErrorMessage,Xn as SceneReadyMessage,Wn as SessionBackendErrorMessage,Jn as SessionConnectingMessage,Yn as SessionDisconnectedMessage,zn as SessionEndedMessage,j as SessionErrorMessage,Bn as SessionLiveMessage,ei as SessionReconnectingFinishedMessage,Zn as SessionReconnectingMessage,ti as SoftSwitchStartingMessage,ni as SoftSwitchStoppingMessage,Hn as SpeechEventMessage,li as SpeechRecognitionProvider,Or as SpeechRecognitionTransientErrorMessage,kr as SpeechTranscriptionMessage,Ls as Uneeq,As as UneeqMessageType,Pr as UserStartedSpeakingMessage,Lr as UserStoppedSpeakingMessage,Ir as VadInterruptionAllowedMessage,ii as VideoLayoutConfiguringMessage,Vn as WaitingInQueueMessage,si as WebRtcConnectedMessage,_n 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){p.debug(`Video element muted: ${this.videoElement?.muted}, (should be true as part of avoiding auto play restrictions)`),p.debug(`Audio element muted: ${this.audioElement?.muted}, (should be false to be able to hear the digital human)`),p.debug(`Audio element volume: ${this.audioElement?.volume}, (should be greater than zero to be able to hear the digital human)`);let t=e?.mimeType;t&&this.audioElement&&(p.debug(`Audio element can play webrtc audio codec (${t}) : ${this.audioElement.canPlayType(t)}, (should be 'probably' or 'maybe)'`),t==="audio/opus"&&p.debug(`Audio codec opus is often known as ogg, so checking can play ogg codec: ${this.audioElement.canPlayType("audio/ogg")}, (should be 'probably' or 'maybe')`))}};var Ie={good:"#22c55e",fair:"#eab308",poor:"#ef4444",inactive:"#6b7280"},xn=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:Ie.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,x;c>=l||u>=l?(C=u>=l&&(c<l||u>=c)?o.bottom+e:o.top-e-l,x=this.position==="top-left"||this.position==="bottom-left"?o.left:o.right-a):(x=v>=a&&(w<a||v>=w)?o.right+e:o.left-e-a,C=o.bottom-l),x=Math.max(t,Math.min(x,n-a-t)),C=Math.max(0,Math.min(C,i-l-t)),this.panel.style.top=`${C}px`,this.panel.style.left=`${x}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 Ie.good;case"Fair":return Ie.fair;case"Poor":return Ie.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:Ie.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 kn=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 Zr;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=se(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(q.Warning,!1);let n=function(){let i=t.getTextSettingValue(z.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 j(`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(){if(p.info("Video initialized."),this.videoElement=this.videoContainerElement?.getElementsByTagName("video")[0],this.audioElement=this.stream?.webRtcController?.streamController?.audioElement,this.audioStatsAnalyzer=new ue(this.stream,this.videoElement,this.audioElement),this.audioElement&&this.config.speakerDeviceId&&this.setSpeakerDevice(this.audioElement,this.config.speakerDeviceId),this.videoElement)this.videoElement.muted=!0,this.videoElement.play().then(()=>{this.playAudioElement()}).catch(e=>{if(e instanceof DOMException&&e.name==="NotAllowedError")p.error('Fatal Error: Video cannot be played. User interaction or client permissions update is required to be able to "play" the video element.',e),this.clientMessages?.next(new Nn(e)),this.endSession(hr,!0);else{let t="Fatal Error: Digital Human video cannot be played.";p.error(t,p.serialiseError(e)),this.clientMessages?.next(new j(t)),this.endSession(Is,!0)}}),this.videoInitialized=!0,this.messages.next(new Mn),this.reconnectionAttempts=0,this.clearReconnectTimer();else{let e="Fatal Error: Video element not found.";p.error(e),this.clientMessages?.next(new j(e)),this.endSession(Is,!0)}setTimeout(()=>{this.clientMessages?.next(new ti)},Ls)}playAudioElement(){this.audioElement?this.audioElement.play().then(()=>{p.info("Audio played successfully."),this.clientMessages?.next(new Kn)}).catch(e=>{p.warn("Audio cannot be played.",e),this.clientMessages?.next(new De),this.clientMessages?.next(new qn)}):this.handleMissingAudioElement()}pauseAudioElement(){this.audioElement?(this.audioElement.pause(),this.clientMessages?.next(new De)):this.handleMissingAudioElement()}muteUpstreamMic(){if(!se(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(!se(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 j(e))}startAudioStatsMonitor(e=5e3){this.stopAudioStatsMonitor(),p.info("Starting audio stats monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new ue(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 ue(this.stream,this.videoElement,this.audioElement)),this.videoContainerElement&&e.visibility!=="hidden"&&(this.networkIndicator=new xn(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 Tn)}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 Rn(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(),this.clientMessages?.next(new ei)},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.scheduleReconnect()):(p.info("Max reconnection attempts reached. Ending session."),this.clientMessages?.next(new Zn),this.endSession(ks,!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 j("Error during reconnection attempt")),this.endSession(ks,!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 En(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 _n(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 Oe(n,i)),this.endSession(Ps,!0)}catch(t){p.error("Signaling: Failed to parse renderer error message",p.serialiseError(t)),this.clientMessages?.next(new Oe(-1,"An unknown renderer error occurred")),this.endSession(Ps,!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();p.info("Signaling: Sending data channel message",JSON.stringify(t)),t.action==="chat_prompt"&&this.clientMessages?.next(new Gn(t.data)),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=dr,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 $n(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 eo}from"rxjs";var Sr=(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))(Sr||{}),br=(i=>(i.Left="left",i.Right="right",i.Center="center",i.Centre="centre",i))(br||{}),Pe=class{constructor(e,t=2e3,n=$()){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 In=class{constructor(e,t=$()){this.avatarId=e;this.requestId=t}avatarId;requestId;toJSON(){return{action:"change_avatar",data:{id:this.avatarId,requestId:this.requestId}}}};var Pn=class{constructor(e,t=$()){this.url=e;this.requestId=t}url;requestId;toJSON(){return{action:"load_background",data:{url:this.url,requestId:this.requestId}}}};var Ln=class{constructor(e,t=$()){this.actionName=e;this.requestId=t}actionName;requestId;toJSON(){return{action:"trigger_action",data:{action_name:this.actionName,requestId:this.requestId}}}};var Dn=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 vr=[1103,1200,1402];var Ls=750,On=class{constructor(e){this.config=e;this.sessionTransferManager=new Dn(this),this._audioUpstreamMode=G(this.config.audioUpstreamMode)}config;id;signaling;messages=new eo;speechRec;promptMetadata={};audioStreamId;sessionTransferManager;jwt;welcomeRequested=!1;resolutionLogged=!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;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")),se(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?`)}setCameraAnchorDistance(e,t=0,n=this.signaling){this.config.cameraAnchorDistance=e,n?.dataSend(new Pe(e,t))}setCameraAnchorHorizontal(e,t=0,n=this.signaling){this.config.cameraAnchorHorizontal=e,n?.dataSend(new Pe(e,t))}changeAvatar(e,t=this.signaling){t?.dataSend(new In(e))}loadBackground(e,t=this.signaling){t?.dataSend(new Pn(e))}userStartSpeaking(e=this.signaling){e?.dataSend(new li("start"))}userStopSpeaking(e=this.signaling){e?.dataSend(new li("stop"))}triggerAction(e,t=this.signaling){t?.dataSend(new Ln(e))}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)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";p.info(`Session, skipping speech recognition restart after ${t} (microphone disabled)`)}}}),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 kn(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 Wn(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 Vn(this.id)),this.config.networkIndicator&&e.startNetworkQualityMonitor(this.config.networkIndicator)},Ls))}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.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-NFBHMIH6.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-Y6E3H2SK.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,useEagerEndOfTurn:t.useEagerEndOfTurn,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-X5UIRUSW.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 Un);break}case"avatar_stopped_speaking":{this.messages.next(new Bn);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":{this.signaling?.endSession(e.msg.reason),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&&vr.includes(e.code)?this.messages.next(new Hn(e)):this.messages.next(new j(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 Fe(this.config.welcomePrompt,this.promptMetadata)))}listenForTabClosure(){window.addEventListener("beforeunload",()=>{p.info("Window unload detected, ending session."),this.signaling?.endSession(),this.signaling=void 0})}};var Fn=class{constructor(e,t=$()){this.prompt=e;this.requestId=t}prompt;requestId;toJSON(){return{action:"speak",data:{requestId:this.requestId,prompt:this.prompt}}}};var pe=class{constructor(e,t,n={},i=$()){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 An=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 wr(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 Ds=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&&!Bs(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 On(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 Fe(e,this.session?.promptMetadata))}speak(e){e&&e.trim()!==""&&this.ensureSessionExists()&&this.session?.signaling?.dataSend(new Fn(e))}openAudioStream(){let e=this.session;this.ensureSessionExists()&&e?.signaling?.dataSend(new pe("open",e?.audioStreamId))}closeAudioStream(){let e=this.session;this.ensureSessionExists()&&e?.audioStreamId!==void 0&&e.signaling?.dataSend(new pe("close",e.audioStreamId))}interruptAudioStream(){let e=this.session;this.ensureSessionExists()&&e?.audioStreamId!==void 0&&e.signaling?.dataSend(new pe("interrupt",e.audioStreamId))}async speakAudio(e){this.ensureSessionExists()&&await wr(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)}executeCommand(e,t,n,i){this.ensureSessionExists()&&this.session?.signaling?.dataSend(new An(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 Us)}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?.speechRec?.pause()??!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?.speechRec?.resume()??!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,t?this.session.signaling?.startAudioStatsMonitor():this.session.signaling?.stopAudioStatsMonitor())}setNetworkIndicatorEnabled(e){this.ensureSessionExists()&&(e?this.session?.signaling?.startNetworkQualityMonitor(e):this.session?.signaling?.stopNetworkQualityMonitor())}};export{kr as AvatarAnswerMessage,Or as AvatarInterruptedMessage,Un as AvatarStartedSpeakingMessage,Bn as AvatarStoppedSpeakingMessage,Sr as CameraAnchorDistance,br as CameraAnchorHorizontal,Qn as CustomMetadataUpdated,oi as CustomerConcurrencyLimitReachedMessage,Nn as DeviceErrorMessage,De as DigitalHumanMuted,qn as DigitalHumanPlayedInMutedModeSuccess,Kn as DigitalHumanUnmuted,jn as EnableMicrophoneUpdatedMessage,xr as LogLevel,fr as NetworkIndicatorPopupTrigger,mr as NetworkIndicatorPosition,pr as NetworkIndicatorVisibility,ur as NetworkQualityLevel,ai as NetworkQualityMessage,Gn as PromptRequestMessage,Xn as PromptResultMessage,Oe as RendererErrorMessage,Jn as SceneReadyMessage,Hn as SessionBackendErrorMessage,Yn as SessionConnectingMessage,Zn as SessionDisconnectedMessage,$n as SessionEndedMessage,j as SessionErrorMessage,Vn as SessionLiveMessage,ti as SessionReconnectingFinishedMessage,ei as SessionReconnectingMessage,ni as SoftSwitchStartingMessage,ii as SoftSwitchStoppingMessage,zn as SpeechEventMessage,ci as SpeechRecognitionProvider,Fr as SpeechRecognitionTransientErrorMessage,Ir as SpeechTranscriptionMessage,Ds as Uneeq,Ns as UneeqMessageType,Lr as UserStartedSpeakingMessage,Dr as UserStoppedSpeakingMessage,Pr as VadInterruptionAllowedMessage,si as VideoLayoutConfiguringMessage,_n as WaitingInQueueMessage,ri as WebRtcConnectedMessage,Wn as WebRtcStatsMessage,G as resolveAudioUpstreamMode};
|