uneeq-js 3.23.4 → 3.23.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.js +8 -8
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/signaling.d.ts +3 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("Uneeq",[],t):"object"==typeof exports?exports.Uneeq=t():e.Uneeq=t()}(Object("undefined"!=typeof self?self:this),()=>(()=>{"use strict";var e={514(e,t,n){n.d(t,{A:()=>o});var s=n(508);const i="UneeQ SDK: ",r={[s.$.Fatal]:0,[s.$.Error]:1,[s.$.Warn]:2,[s.$.Info]:3,[s.$.Debug]:4,[s.$.Trace]:5};class o{static currentLevel=s.$.Info;static shouldLog(e){return r[e]<=r[o.currentLevel]}static formatLogMessage(e,t){return 0===t.length?i+e:i+e+" | "+JSON.stringify(t)}static fatal(e,...t){o.shouldLog(s.$.Fatal)&&console.error(o.formatLogMessage(e,t))}static error(e,...t){o.shouldLog(s.$.Error)&&console.error(o.formatLogMessage(e,t))}static warn(e,...t){o.shouldLog(s.$.Warn)&&console.warn(o.formatLogMessage(e,t))}static info(e,...t){o.shouldLog(s.$.Info)&&console.info(o.formatLogMessage(e,t))}static debug(e,...t){o.shouldLog(s.$.Debug)&&console.debug(o.formatLogMessage(e,t))}static trace(e,...t){o.shouldLog(s.$.Trace)&&console.debug(o.formatLogMessage(e,t))}static setLevel(e){Object.values(s.$).includes(e)?(e!=s.$.Trace&&e!=s.$.Debug||console.warn(i+"you may need to set your browser's console settings to show verbose logs to be able to see debug or trace logs"),o.currentLevel=e):o.currentLevel=s.$.Info}static serialiseError(e){return JSON.stringify(e,Object.getOwnPropertyNames(e))}}},1(e,t,n){function s(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}n.d(t,{g:()=>s})},508(e,t,n){var s;n.d(t,{$:()=>s}),function(e){e.Fatal="fatal",e.Error="error",e.Warn="warn",e.Info="info",e.Debug="debug",e.Trace="trace"}(s||(s={}))},838(e,t,n){var s;n.d(t,{Cj:()=>f,Cl:()=>N,E1:()=>a,F8:()=>p,JP:()=>x,Ln:()=>P,M8:()=>C,MA:()=>W,MM:()=>U,N8:()=>B,O$:()=>m,Qd:()=>S,Tu:()=>M,Uh:()=>v,Ux:()=>o,WQ:()=>O,WY:()=>T,XC:()=>w,Yg:()=>s,_4:()=>l,aY:()=>b,bS:()=>R,co:()=>i,fI:()=>L,fP:()=>y,fh:()=>r,im:()=>c,j_:()=>V,kS:()=>h,n3:()=>_,nD:()=>k,qo:()=>I,qw:()=>F,sF:()=>D,ss:()=>E,tc:()=>u,wf:()=>g,xQ:()=>A,yr:()=>d}),function(e){e.AvatarAnswer="AvatarAnswer",e.AvatarInterrupted="AvatarInterrupted",e.AvatarStartedSpeaking="AvatarStartedSpeaking",e.AvatarStoppedSpeaking="AvatarStoppedSpeaking",e.CustomerConcurrencyLimitReached="CustomerConcurrencyLimitReached",e.CustomMetadataUpdated="CustomMetadataUpdated",e.DeviceError="DeviceError",e.DigitalHumanMuted="DigitalHumanMuted",e.DigitalHumanPlayedInMutedModeSuccess="DigitalHumanPlayedInMutedModeSuccess",e.DigitalHumanUnmuted="DigitalHumanUnmuted",e.EnableMicrophoneUpdated="EnableMicrophoneUpdated",e.NetworkQuality="NetworkQuality",e.PromptRequest="PromptRequest",e.PromptResult="PromptResult",e.RendererError="RendererError",e.RendererVersionWarning="RendererVersionWarning",e.SceneReady="SceneReady",e.SessionBackendError="SessionBackendError",e.SessionConnecting="SessionConnecting",e.SessionDisconnected="SessionDisconnected",e.SessionEnded="SessionEnded",e.SessionError="SessionError",e.SessionLive="SessionLive",e.SessionReconnecting="SessionReconnecting",e.SessionReconnectingFinished="SessionReconnectingFinished",e.SoftSwitchFinished="SoftSwitchFinished",e.SoftSwitchStarting="SoftSwitchStarting",e.SpeechEvent="SpeechEvent",e.SpeechRecognitionTransientError="SpeechRecognitionTransientError",e.SpeechTranscription="SpeechTranscription",e.UserStartedSpeaking="UserStartedSpeaking",e.UserStoppedSpeaking="UserStoppedSpeaking",e.VadInterruptionAllowed="VadInterruptionAllowed",e.VideoAutoplayBlocked="VideoAutoplayBlocked",e.VideoLayoutConfiguring="VideoLayoutConfiguring",e.WaitingInQueue="WaitingInQueue",e.WebRtcConnected="webRtcConnected",e.WebRtcStats="WebRtcStats"}(s||(s={}));class i{error;uneeqMessageType=s.DeviceError;constructor(e){this.error=e}}class r{answer;answerAvatar;answerSpeech;transcriptId;uneeqMessageType=s.AvatarAnswer;constructor(e,t,n,s){this.answer=e,this.answerAvatar=t,this.answerSpeech=n,this.transcriptId=s}}class o{speechTranscription;uneeqMessageType=s.SpeechTranscription;constructor(e){this.speechTranscription=e}}class a{interruptionAllowed;uneeqMessageType=s.VadInterruptionAllowed;constructor(e){this.interruptionAllowed=e}}class l{uneeqMessageType=s.UserStartedSpeaking}class c{uneeqMessageType=s.UserStoppedSpeaking}class d{uneeqMessageType=s.AvatarStartedSpeaking}class h{uneeqMessageType=s.AvatarStoppedSpeaking}class u{transcriptId;uneeqMessageType=s.AvatarInterrupted;constructor(e){this.transcriptId=e}}class g{sessionId;uneeqMessageType=s.SessionLive;constructor(e){this.sessionId=e}}class p{position;uneeqMessageType=s.WaitingInQueue;constructor(e){this.position=e}}class m{stats;uneeqMessageType=s.WebRtcStats;constructor(e){this.stats=e}}class f{error;uneeqMessageType=s.SessionError;constructor(e){this.error=e}}class y{error;uneeqMessageType=s.SpeechRecognitionTransientError;constructor(e){this.error=e}}class v{error;uneeqMessageType=s.SessionBackendError;constructor(e){this.error=e}}class S{speechEvent;uneeqMessageType=s.SpeechEvent;constructor(e){this.speechEvent=e}}class b{reason;uneeqMessageType=s.SessionEnded;constructor(e){this.reason=e}}class w{uneeqMessageType=s.DigitalHumanPlayedInMutedModeSuccess;msg="Digital Human was successfully played in muted mode. After the user interacts with the page you will need to call unmuteDigitalHuman() to unmute the video."}class C{uneeqMessageType=s.DigitalHumanUnmuted}class M{uneeqMessageType=s.DigitalHumanMuted}class T{enabled;uneeqMessageType=s.EnableMicrophoneUpdated;constructor(e){this.enabled=e}}class E{chatMetadata;uneeqMessageType=s.CustomMetadataUpdated;constructor(e){this.chatMetadata=e}}class R{promptRequest;uneeqMessageType=s.PromptRequest;constructor(e){this.promptRequest=e}}class k{promptResult;uneeqMessageType=s.PromptResult;constructor(e){this.promptResult=e}}class P{uneeqMessageType=s.SceneReady}class I{rendererId;uneeqMessageType=s.SessionConnecting;constructor(e){this.rendererId=e}}class x{uneeqMessageType=s.SessionDisconnected}class L{uneeqMessageType=s.SessionReconnecting}class A{uneeqMessageType=s.SessionReconnectingFinished}class D{uneeqMessageType=s.SoftSwitchStarting}class O{uneeqMessageType=s.SoftSwitchFinished}class F{uneeqMessageType=s.VideoLayoutConfiguring}class N{uneeqMessageType=s.WebRtcConnected}class U{uneeqMessageType=s.CustomerConcurrencyLimitReached}class B{metrics;uneeqMessageType=s.NetworkQuality;constructor(e){this.metrics=e}}class V{code;error;uneeqMessageType=s.RendererError;constructor(e,t){this.code=e,this.error=t}}class _{rendererVersion;latestVersion;message;uneeqMessageType=s.RendererVersionWarning;constructor(e,t,n){this.rendererVersion=e,this.latestVersion=t,this.message=n}}class W{uneeqMessageType=s.VideoAutoplayBlocked}},992(e,t,n){var s;n.d(t,{A:()=>s}),function(e){e.CameraAnchor="camera_to_anchor",e.ChangeAvatar="change_avatar",e.ChatPrompt="chat_prompt",e.ExecuteCommand="execute_command",e.InterimTranscript="interim_transcript",e.LoadBackground="load_background",e.StopSpeaking="stop_speaking",e.Speak="speak",e.SpeechStream="speech_stream",e.TriggerAction="trigger_action",e.UserSpeaking="user_speaking"}(s||(s={}))},388(e,t,n){n.d(t,{D:()=>r});var s=n(992),i=n(1);class r{prompt;metadata;requestId;shouldEmitPromptRequest;constructor(e,t,n=(0,i.g)(),s=!0){this.prompt=e,this.metadata=t,this.requestId=n,this.shouldEmitPromptRequest=s}toJSON(){return{action:s.A.ChatPrompt,data:{requestId:this.requestId,prompt:this.prompt,metadata:this.metadata}}}}},58(e,t,n){n.d(t,{f:()=>r});var s=n(992),i=n(1);class r{requestId;constructor(e=(0,i.g)()){this.requestId=e}toJSON(){return{action:s.A.StopSpeaking,data:{requestId:this.requestId}}}}},33(e,t,n){n.d(t,{A:()=>o,f:()=>s});var s,i=n(992),r=n(1);!function(e){e.Start="start",e.Stop="stop"}(s||(s={}));class o{state;requestId;constructor(e,t=(0,r.g)()){this.state=e,this.requestId=t}toJSON(){return{action:i.A.UserSpeaking,data:{requestId:this.requestId,event:this.state}}}}}};const t={};function n(s){const i=t[s];if(void 0!==i)return i.exports;const r=t[s]={exports:{}};return e[s].call(r.exports,r,r.exports,n),r.exports}n.m=e,n.cw=e=>{var t;return()=>{if(e){var n=e;e=0,t={exports:{}},n.call(t.exports,t,t.exports)}return t.exports}},(()=>{const e=Object.getPrototypeOf;let t;n.t=function(s,i){if(1&i&&(s=this(s)),8&i)return s;if("object"==typeof s&&s){if(4&i&&s.__esModule)return s;if(16&i&&"function"==typeof s.then)return s}const r=Object.create(null);n.r(r);const o={};t=t||[null,e({}),e([]),e(e)];for(var a=2&i&&s;("object"==typeof a||"function"==typeof a)&&!~t.indexOf(a);a=e(a))Object.getOwnPropertyNames(a).forEach(e=>o[e]=()=>s[e]);return o.default=()=>s,n.d(r,o),r}})(),n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.f={},n.e=e=>Promise.all(Object.keys(n.f).reduce((t,s)=>(n.f[s](e,t),t),[])),n.u=e=>e+".index.js",n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Uneeq:";n.l=(s,i,r,o)=>{if(e[s])return void e[s].push(i);let a,l;if(void 0!==r){const e=document.getElementsByTagName("script");for(var c=0;c<e.length;c++){const n=e[c];if(n.getAttribute("src")==s||n.getAttribute("data-webpack")==t+r){a=n;break}}}a||(l=!0,a=document.createElement("script"),a.charset="utf-8",n.nc&&a.setAttribute("nonce",n.nc),a.setAttribute("data-webpack",t+r),a.src=s),e[s]=[i];const d=(t,n)=>{a.onerror=a.onload=null,clearTimeout(h);const i=e[s];if(delete e[s],a.parentNode?.removeChild(a),i?.forEach(e=>e(n)),t)return t(n)},h=setTimeout(d.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=d.bind(null,a.onerror),a.onload=d.bind(null,a.onload),l&&document.head.appendChild(a)}})(),n.r=e=>{Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{let e;n.g.importScripts&&(e=n.g.location+"");const t=n.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const n=t.getElementsByTagName("script");if(n.length){let t=n.length-1;for(;t>-1&&(!e||!/^https?:/.test(e));)e=n[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:|[?#].*$/g,"").replace(/\/[^/]+$/,"/"),n.p=e})(),(()=>{const e={792:0};n.f.j=(t,s)=>{let i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)s.push(i[2]);else{const r=new Promise((n,s)=>i=e[t]=[n,s]);s.push(i[2]=r);const o=new Error,a=s=>{if(n.o(e,t)&&(i=e[t],0!==i&&(e[t]=void 0),i)){const e=s&&("load"===s.type?"missing":s.type),n=s&&s.target&&s.target.src;o.message="Loading chunk "+t+" failed.\n("+e+": "+n+")",o.name="ChunkLoadError",o.type=e,o.request=n,o.event=s,i[1](o)}};n.l(n.p+n.u(t),a,"chunk-"+t,t)}};const t=(t,s)=>{let[i,r,o]=s;var a,l,c=0;if(i.some(t=>0!==e[t])){for(a in r)n.o(r,a)&&(n.m[a]=r[a]);o&&o(n)}for(t&&t(s);c<i.length;c++)l=i[c],n.o(e,l)&&e[l]&&e[l][0](),e[l]=0},s=Object("undefined"!=typeof self?self:this).webpackChunkUneeq=Object("undefined"!=typeof self?self:this).webpackChunkUneeq||[];s.forEach(t.bind(null,0)),s.push=t.bind(null,s.push.bind(s))})();let s={};n.r(s),n.d(s,{AvatarAnswerMessage:()=>Fs.fh,AvatarInterruptedMessage:()=>Fs.tc,AvatarStartedSpeakingMessage:()=>Fs.yr,AvatarStoppedSpeakingMessage:()=>Fs.kS,CameraAnchorDistance:()=>ri,CameraAnchorHorizontal:()=>oi,CustomMetadataUpdated:()=>Fs.ss,CustomerConcurrencyLimitReachedMessage:()=>Fs.MM,DeviceErrorMessage:()=>Fs.co,DigitalHumanMuted:()=>Fs.Tu,DigitalHumanPlayedInMutedModeSuccess:()=>Fs.XC,DigitalHumanUnmuted:()=>Fs.M8,EnableMicrophoneUpdatedMessage:()=>Fs.WY,LogLevel:()=>Mi.$,NetworkIndicatorPopupTrigger:()=>Hs,NetworkIndicatorPosition:()=>$s,NetworkIndicatorVisibility:()=>Ws,NetworkQualityLevel:()=>_s,NetworkQualityMessage:()=>Fs.N8,PromptRequestMessage:()=>Fs.bS,PromptResultMessage:()=>Fs.nD,RendererErrorMessage:()=>Fs.j_,SceneReadyMessage:()=>Fs.Ln,SessionBackendErrorMessage:()=>Fs.Uh,SessionConnectingMessage:()=>Fs.qo,SessionDisconnectedMessage:()=>Fs.JP,SessionEndedMessage:()=>Fs.aY,SessionErrorMessage:()=>Fs.Cj,SessionLiveMessage:()=>Fs.wf,SessionReconnectingFinishedMessage:()=>Fs.xQ,SessionReconnectingMessage:()=>Fs.fI,SoftSwitchStartingMessage:()=>Fs.sF,SoftSwitchStoppingMessage:()=>Fs.WQ,SpeechEventMessage:()=>Fs.Qd,SpeechRecognitionProvider:()=>js,SpeechRecognitionTransientErrorMessage:()=>Fs.fP,SpeechTranscriptionMessage:()=>Fs.Ux,UNEEQ_JS_SDK_VERSION:()=>"3.23.4",Uneeq:()=>Ci,UneeqMessageType:()=>Fs.Yg,UserStartedSpeakingMessage:()=>Fs._4,UserStoppedSpeakingMessage:()=>Fs.im,VadInterruptionAllowedMessage:()=>Fs.E1,VideoAutoplayBlockedMessage:()=>Fs.MA,VideoLayoutConfiguringMessage:()=>Fs.qw,WaitingInQueueMessage:()=>Fs.F8,WebRtcConnectedMessage:()=>Fs.Cl,WebRtcStatsMessage:()=>Fs.O$,resolveAudioUpstreamMode:()=>Ks});var i=n.cw(function(e,t){const n={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};n.localCName=n.generateIdentifier(),n.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},n.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},n.getDescription=function(e){const t=n.splitSections(e);return t&&t[0]},n.getMediaSections=function(e){const t=n.splitSections(e);return t.shift(),t},n.matchPrefix=function(e,t){return n.splitLines(e).filter(e=>0===e.indexOf(t))},n.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":n.relatedAddress=t[e+1];break;case"rport":n.relatedPort=parseInt(t[e+1],10);break;case"tcptype":n.tcpType=t[e+1];break;case"ufrag":n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:void 0===n[t[e]]&&(n[t[e]]=t[e+1])}return n},n.writeCandidate=function(e){const t=[];t.push(e.foundation);const n=e.component;"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const s=e.type;return t.push("typ"),t.push(s),"host"!==s&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},n.parseIceOptions=function(e){return e.substring(14).split(" ")},n.parseRtpMap=function(e){let t=e.substring(9).split(" ");const n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},n.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\r\n"},n.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},n.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},n.parseFmtp=function(e){const t={};let n;const s=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<s.length;e++)n=s[e].trim().split("="),t[n[0].trim()]=n[1];return t},n.writeFmtp=function(e){let t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const s=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?s.push(t+"="+e.parameters[t]):s.push(t)}),t+="a=fmtp:"+n+" "+s.join(";")+"\r\n"}return t},n.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},n.writeRtcpFb=function(e){let t="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},n.parseSsrcMedia=function(e){const t=e.indexOf(" "),n={ssrc:parseInt(e.substring(7,t),10)},s=e.indexOf(":",t);return s>-1?(n.attribute=e.substring(t+1,s),n.value=e.substring(s+1)):n.attribute=e.substring(t+1),n},n.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},n.getMid=function(e){const t=n.matchPrefix(e,"a=mid:")[0];if(t)return t.substring(6)},n.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},n.getDtlsParameters=function(e,t){return{role:"auto",fingerprints:n.matchPrefix(e+t,"a=fingerprint:").map(n.parseFingerprint)}},n.writeDtlsParameters=function(e,t){let n="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),n},n.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},n.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?n.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},n.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},n.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},n.getCryptoParameters=function(e,t){return n.matchPrefix(e+t,"a=crypto:").map(n.parseCryptoLine)},n.getIceParameters=function(e,t){const s=n.matchPrefix(e+t,"a=ice-ufrag:")[0],i=n.matchPrefix(e+t,"a=ice-pwd:")[0];return s&&i?{usernameFragment:s.substring(12),password:i.substring(10)}:null},n.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},n.parseRtpParameters=function(e){const t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=n.splitLines(e)[0].split(" ");t.profile=s[2];for(let i=3;i<s.length;i++){const r=s[i],o=n.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(o){const s=n.parseRtpMap(o),i=n.matchPrefix(e,"a=fmtp:"+r+" ");switch(s.parameters=i.length?n.parseFmtp(i[0]):{},s.rtcpFeedback=n.matchPrefix(e,"a=rtcp-fb:"+r+" ").map(n.parseRtcpFb),t.codecs.push(s),s.name.toUpperCase()){case"RED":case"ULPFEC":t.fecMechanisms.push(s.name.toUpperCase())}}}n.matchPrefix(e,"a=extmap:").forEach(e=>{t.headerExtensions.push(n.parseExtmap(e))});const i=n.matchPrefix(e,"a=rtcp-fb:* ").map(n.parseRtcpFb);return t.codecs.forEach(e=>{i.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),t},n.writeRtpDescription=function(e,t){let s="";s+="m="+e+" ",s+=t.codecs.length>0?"9":"0",s+=" "+(t.profile||"UDP/TLS/RTP/SAVPF")+" ",s+=t.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",s+="c=IN IP4 0.0.0.0\r\n",s+="a=rtcp:9 IN IP4 0.0.0.0\r\n",t.codecs.forEach(e=>{s+=n.writeRtpMap(e),s+=n.writeFmtp(e),s+=n.writeRtcpFb(e)});let i=0;return t.codecs.forEach(e=>{e.maxptime>i&&(i=e.maxptime)}),i>0&&(s+="a=maxptime:"+i+"\r\n"),t.headerExtensions&&t.headerExtensions.forEach(e=>{s+=n.writeExtmap(e)}),s},n.parseRtpEncodingParameters=function(e){const t=[],s=n.parseRtpParameters(e),i=-1!==s.fecMechanisms.indexOf("RED"),r=-1!==s.fecMechanisms.indexOf("ULPFEC"),o=n.matchPrefix(e,"a=ssrc:").map(e=>n.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=o.length>0&&o[0].ssrc;let l;const c=n.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));c.length>0&&c[0].length>1&&c[0][0]===a&&(l=c[0][1]),s.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let n={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&l&&(n.rtx={ssrc:l}),t.push(n),i&&(n=JSON.parse(JSON.stringify(n)),n.fec={ssrc:a,mechanism:r?"red+ulpfec":"red"},t.push(n))}}),0===t.length&&a&&t.push({ssrc:a});let d=n.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,t.forEach(e=>{e.maxBitrate=d})),t},n.parseRtcpParameters=function(e){const t={},s=n.matchPrefix(e,"a=ssrc:").map(e=>n.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];s&&(t.cname=s.value,t.ssrc=s.ssrc);const i=n.matchPrefix(e,"a=rtcp-rsize");t.reducedSize=i.length>0,t.compound=0===i.length;const r=n.matchPrefix(e,"a=rtcp-mux");return t.mux=r.length>0,t},n.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},n.parseMsid=function(e){let t;const s=n.matchPrefix(e,"a=msid:");if(1===s.length)return t=s[0].substring(7).split(" "),{stream:t[0],track:t[1]};const i=n.matchPrefix(e,"a=ssrc:").map(e=>n.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return i.length>0?(t=i[0].value.split(" "),{stream:t[0],track:t[1]}):void 0},n.parseSctpDescription=function(e){const t=n.parseMLine(e),s=n.matchPrefix(e,"a=max-message-size:");let i;s.length>0&&(i=parseInt(s[0].substring(19),10)),isNaN(i)&&(i=65536);const r=n.matchPrefix(e,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:t.fmt,maxMessageSize:i};const o=n.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},n.writeSctpDescription=function(e,t){let n=[];return n="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},n.generateSessionId=function(){return Math.random().toString().substr(2,22)},n.writeSessionBoilerplate=function(e,t,s){let i;const r=void 0!==t?t:2;return i=e||n.generateSessionId(),"v=0\r\no="+(s||"thisisadapterortc")+" "+i+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},n.getDirection=function(e,t){const s=n.splitLines(e);for(let e=0;e<s.length;e++)switch(s[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[e].substring(2)}return t?n.getDirection(t):"sendrecv"},n.getKind=function(e){return n.splitLines(e)[0].split(" ")[0].substring(2)},n.isRejected=function(e){return"0"===e.split(" ",2)[1]},n.parseMLine=function(e){const t=n.splitLines(e)[0].substring(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}},n.parseOLine=function(e){const t=n.matchPrefix(e,"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]}},n.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const t=n.splitLines(e);for(let e=0;e<t.length;e++)if(t[e].length<2||"="!==t[e].charAt(1))return!1;return!0},e.exports=n}),r=n(514),o=function(e,t){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},o(e,t)};function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function l(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],s=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function c(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var s,i,r=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(e){i={error:e}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return o}function d(e,t,n){if(n||2===arguments.length)for(var s,i=0,r=t.length;i<r;i++)!s&&i in t||(s||(s=Array.prototype.slice.call(t,0,i)),s[i]=t[i]);return e.concat(s||Array.prototype.slice.call(t))}function h(e){return"function"==typeof e}function u(e){var t=e(function(e){Error.call(e),e.stack=(new Error).stack});return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}Object.create,Object.create;var g=u(function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map(function(e,t){return t+1+") "+e.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}});function p(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var m=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,n,s,i;if(!this.closed){this.closed=!0;var r=this._parentage;if(r)if(this._parentage=null,Array.isArray(r))try{for(var o=l(r),a=o.next();!a.done;a=o.next())a.value.remove(this)}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else r.remove(this);var u=this.initialTeardown;if(h(u))try{u()}catch(e){i=e instanceof g?e.errors:[e]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var m=l(p),f=m.next();!f.done;f=m.next()){var y=f.value;try{v(y)}catch(e){i=null!=i?i:[],e instanceof g?i=d(d([],c(i)),c(e.errors)):i.push(e)}}}catch(e){n={error:e}}finally{try{f&&!f.done&&(s=m.return)&&s.call(m)}finally{if(n)throw n.error}}}if(i)throw new g(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)v(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&p(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&p(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}(),f=m.EMPTY;function y(e){return e instanceof m||e&&"closed"in e&&h(e.remove)&&h(e.add)&&h(e.unsubscribe)}function v(e){h(e)?e():e.unsubscribe()}var S=null,b=null,w=void 0,C=!1,M=!1,T={setTimeout:function(e,t){for(var n=[],s=2;s<arguments.length;s++)n[s-2]=arguments[s];var i=T.delegate;return(null==i?void 0:i.setTimeout)?i.setTimeout.apply(i,d([e,t],c(n))):setTimeout.apply(void 0,d([e,t],c(n)))},clearTimeout:function(e){var t=T.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function E(){}var R=k("C",void 0,void 0);function k(e,t,n){return{kind:e,value:t,error:n}}var P=null;function I(e){if(C){var t=!P;if(t&&(P={errorThrown:!1,error:null}),e(),t){var n=P,s=n.errorThrown,i=n.error;if(P=null,s)throw i}}else e()}var x=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,y(t)&&t.add(n)):n.destination=U,n}return a(t,e),t.create=function(e,t,n){return new O(e,t,n)},t.prototype.next=function(e){this.isStopped?N(function(e){return k("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?N(k("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?N(R,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(m),L=Function.prototype.bind;function A(e,t){return L.call(e,t)}var D=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){F(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){F(e)}else F(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){F(e)}},e}(),O=function(e){function t(t,n,s){var i,r,o=e.call(this)||this;return h(t)||!t?i={next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=s?s:void 0}:o&&M?((r=Object.create(t)).unsubscribe=function(){return o.unsubscribe()},i={next:t.next&&A(t.next,r),error:t.error&&A(t.error,r),complete:t.complete&&A(t.complete,r)}):i=t,o.destination=new D(i),o}return a(t,e),t}(x);function F(e){var t;C?(t=e,C&&P&&(P.errorThrown=!0,P.error=t)):function(e){T.setTimeout(function(){if(!S)throw e;S(e)})}(e)}function N(e,t){var n=b;n&&T.setTimeout(function(){return n(e,t)})}var U={closed:!0,next:E,error:function(e){throw e},complete:E},B="function"==typeof Symbol&&Symbol.observable||"@@observable";function V(e){return e}var _=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var s,i=this,r=(s=e)&&s instanceof x||function(e){return e&&h(e.next)&&h(e.error)&&h(e.complete)}(s)&&y(s)?e:new O(e,t,n);return I(function(){var e=i,t=e.operator,n=e.source;r.add(t?t.call(r,n):n?i._subscribe(r):i._trySubscribe(r))}),r},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=W(t))(function(t,s){var i=new O({next:function(t){try{e(t)}catch(e){s(e),i.unsubscribe()}},error:s,complete:t});n.subscribe(i)})},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[B]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return(0===(n=e).length?V:1===n.length?n[0]:function(e){return n.reduce(function(e,t){return t(e)},e)})(this);var n},e.prototype.toPromise=function(e){var t=this;return new(e=W(e))(function(e,n){var s;t.subscribe(function(e){return s=e},function(e){return n(e)},function(){return e(s)})})},e.create=function(t){return new e(t)},e}();function W(e){var t;return null!==(t=null!=e?e:w)&&void 0!==t?t:Promise}var $,H=u(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),j=function(e){function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return a(t,e),t.prototype.lift=function(e){var t=new q(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new H},t.prototype.next=function(e){var t=this;I(function(){var n,s;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var i=l(t.currentObservers),r=i.next();!r.done;r=i.next())r.value.next(e)}catch(e){n={error:e}}finally{try{r&&!r.done&&(s=i.return)&&s.call(i)}finally{if(n)throw n.error}}}})},t.prototype.error=function(e){var t=this;I(function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var n=t.observers;n.length;)n.shift().error(e)}})},t.prototype.complete=function(){var e=this;I(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,n=this,s=n.hasError,i=n.isStopped,r=n.observers;return s||i?f:(this.currentObservers=null,r.push(e),new m(function(){t.currentObservers=null,p(r,e)}))},t.prototype._checkFinalizedStatuses=function(e){var t=this,n=t.hasError,s=t.thrownError,i=t.isStopped;n?e.error(s):i&&e.complete()},t.prototype.asObservable=function(){var e=new _;return e.source=this,e},t.create=function(e,t){return new q(e,t)},t}(_),q=function(e){function t(t,n){var s=e.call(this)||this;return s.destination=t,s.source=n,s}return a(t,e),t.prototype.next=function(e){var t,n;null===(n=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===n||n.call(t,e)},t.prototype.error=function(e){var t,n;null===(n=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===n||n.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,n;return null!==(n=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==n?n:f},t}(j),z={now:function(){return(z.delegate||Date).now()},delegate:void 0},Q=function(e){function t(t,n,s){void 0===t&&(t=1/0),void 0===n&&(n=1/0),void 0===s&&(s=z);var i=e.call(this)||this;return i._bufferSize=t,i._windowTime=n,i._timestampProvider=s,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=n===1/0,i._bufferSize=Math.max(1,t),i._windowTime=Math.max(1,n),i}return a(t,e),t.prototype.next=function(t){var n=this,s=n.isStopped,i=n._buffer,r=n._infiniteTimeWindow,o=n._timestampProvider,a=n._windowTime;s||(i.push(t),!r&&i.push(o.now()+a)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),n=this._infiniteTimeWindow,s=this._buffer.slice(),i=0;i<s.length&&!e.closed;i+=n?1:2)e.next(s[i]);return this._checkFinalizedStatuses(e),t},t.prototype._trimBuffer=function(){var e=this,t=e._bufferSize,n=e._timestampProvider,s=e._buffer,i=e._infiniteTimeWindow,r=(i?1:2)*t;if(t<1/0&&r<s.length&&s.splice(0,s.length-r),!i){for(var o=n.now(),a=0,l=1;l<s.length&&s[l]<=o;l+=2)a=l;a&&s.splice(0,a+1)}},t}(j);!function(e){e[e.Disabled=0]="Disabled",e[e.Error=1]="Error",e[e.Warning=2]="Warning",e[e.Info=3]="Info",e[e.Debug=4]="Debug"}($||($={}));class K{constructor(){this.logLevel=$.Debug,this.includeStack=!0}}let G=new class{InitLogging(e,t){this.ValidateContext(),this.context.logLevel=e,this.context.includeStack=t}Debug(e){this.ValidateContext(),this.context.logLevel>=$.Debug&&this.CommonLog("Debug",e)}Info(e){this.ValidateContext(),this.context.logLevel>=$.Info&&this.CommonLog("Info",e)}Warning(e){this.ValidateContext(),this.context.logLevel>=$.Warning&&this.CommonLog("Warning",e)}Error(e){this.ValidateContext(),this.context.logLevel>=$.Error&&this.CommonLog("Error",e)}CommonLog(e,t){let n=`[${e}] - ${t}`;this.context.includeStack&&(n+=`\nStack: ${this.GetStackTrace()}`),"Error"===e?console.error(n):"Warning"===e?console.warn(n):console.log(n)}GetStackTrace(){const e=new Error;let t="No Stack Available for this browser";return e.stack&&(t=e.stack.toString().replace(/Error/g,"")),t}ValidateContext(){this.context||("undefined"!=typeof window&&window?window.loggerContext?this.context=window.loggerContext:(this.context=new K,window.loggerContext=this.context):this.context=new K)}};class X{constructor(e,t,n,s,i=()=>{}){this.parseURLParams(),this.onChange=i,this.onChangeEmit=()=>{},this.id=e,this.description=n,this.label=t,this.value=s}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){const e=new URLSearchParams(window.location.search),t=this.getValueAsString();let n=!1;for(const[s,i]of e)if(s.toLowerCase()==this.id.toLowerCase()){e.set(s,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={};const e=new URLSearchParams(window.location.search);for(const[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()]:""}}class J extends X{constructor(e,t,n,s,i,r=()=>{}){if(super(e,t,n,s,r),i&&this.hasURLParam(this.id)){const e=this.getURLParam(this.id);this.flag="false"!=e.toLowerCase()}else this.flag=s;this.useUrlParams=i}getValueAsString(){return this.flag?"true":"false"}enable(){this.flag=!0}get flag(){return!!this.value}set flag(e){this.value=e}}class Y extends X{constructor(e,t,n,s,i,r,o,a=()=>{}){if(super(e,t,n,r,a),this._min=s,this._max=i,o&&this.hasURLParam(this.id)){const e=Number.parseFloat(this.getURLParam(this.id));this.number=Number.isNaN(e)?r:e}else this.number=r;this.useUrlParams=o}getValueAsString(){return this.number.toString()}set number(e){this.value=this.clamp(e)}get number(){return this.value}clamp(e){return null==this._min&&null==this._max?e:null==this._min?Math.min(this._max,e):null==this._max?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}}class Z extends X{constructor(e,t,n,s,i,r=()=>{}){super(e,t,n,s,r),i&&this.hasURLParam(this.id)?this.text=this.getURLParam(this.id):this.text=s,this.useUrlParams=i}getValueAsString(){return this.text}get text(){return this.value}set text(e){this.value=e}}class ee extends X{constructor(e,t,n,s,i,r,o=function(e){return e},a=()=>{}){super(e,t,n,s,a),this._urlParamResolver=o;const l=this.hasURLParam(this.id)?this._urlParamResolver(this.getURLParam(this.id)):s;this.options=null!=i?i:[l],this.selected=l,this.useUrlParams=r}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){void 0!==e&&(this.options.includes(e)?this.value=e:G.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}}class te extends Event{constructor(e){super("afkWarningActivate"),this.data=e}}class ne extends Event{constructor(e){super("afkWarningUpdate"),this.data=e}}class se extends Event{constructor(){super("afkWarningDeactivate")}}class ie extends Event{constructor(){super("afkTimedOut")}}class re extends Event{constructor(e){super("videoEncoderAvgQP"),this.data=e}}class oe extends Event{constructor(){super("webRtcSdp")}}class ae extends Event{constructor(e){super("webRtcSdpAnswer"),this.data=e}}class le extends Event{constructor(e){super("webRtcSdpOffer"),this.data=e}}class ce extends Event{constructor(){super("webRtcAutoConnect")}}class de extends Event{constructor(){super("webRtcConnecting")}}class he extends Event{constructor(){super("webRtcConnected")}}class ue extends Event{constructor(){super("webRtcFailed")}}class ge extends Event{constructor(e){super("webRtcDisconnected"),this.data=e}}class pe extends Event{constructor(e){super("dataChannelOpen"),this.data=e}}class me extends Event{constructor(e){super("dataChannelClose"),this.data=e}}class fe extends Event{constructor(e){super("dataChannelError"),this.data=e}}class ye extends Event{constructor(){super("videoInitialized")}}class ve extends Event{constructor(){super("streamLoading")}}class Se extends Event{constructor(){super("streamConnect")}}class be extends Event{constructor(){super("streamDisconnect")}}class we extends Event{constructor(){super("streamReconnect")}}class Ce extends Event{constructor(e){super("playStreamError"),this.data=e}}class Me extends Event{constructor(){super("playStream")}}class Te extends Event{constructor(e){super("playStreamRejected"),this.data=e}}class Ee extends Event{constructor(e){super("loadFreezeFrame"),this.data=e}}class Re extends Event{constructor(){super("hideFreezeFrame")}}class ke extends Event{constructor(e){super("statsReceived"),this.data=e}}class Pe extends Event{constructor(e){super("streamerListMessage"),this.data=e}}class Ie extends Event{constructor(e){super("StreamerIDChangedMessage"),this.data=e}}class xe extends Event{constructor(e){super("latencyTestResult"),this.data=e}}class Le extends Event{constructor(e){super("latencyCalculated"),this.data=e}}class Ae extends Event{constructor(e){super("showOnScreenKeyboard"),this.data=e}}class De extends Event{constructor(e){super("dataChannelLatencyTestResponse"),this.data=e}}class Oe extends Event{constructor(e){super("dataChannelLatencyTestResult"),this.data=e}}class Fe extends Event{constructor(e){super("subscribeFailed"),this.data=e}}class Ne extends Event{constructor(e){super("initialSettings"),this.data=e}}class Ue extends Event{constructor(e){super("settingsChanged"),this.data=e}}Event,Event;class Be extends Event{constructor(e){super("xrFrame"),this.data=e}}class Ve extends Event{constructor(e){super("playerCount"),this.data=e}}class _e extends Event{constructor(){super("webRtcTCPRelayDetected")}}class We extends EventTarget{dispatchEvent(e){return super.dispatchEvent(e)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}}class $e{static getSupportedVideoCodecs(){const e=[];if(!RTCRtpReceiver.getCapabilities)return G.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;const t=/(VP\d|H26\d|AV1).*/,n=RTCRtpReceiver.getCapabilities("video");return n?(n.codecs.forEach(n=>{const s=n.mimeType.split("/")[1]+" "+(n.sdpFmtpLine||"");null!==t.exec(s)&&e.push(s)}),e):(e.push("H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"),e)}}class He{}He.AutoConnect="AutoConnect",He.AutoPlayVideo="AutoPlayVideo",He.AFKDetection="TimeoutIfIdle",He.HoveringMouseMode="HoveringMouse",He.ForceMonoAudio="ForceMonoAudio",He.ForceTURN="ForceTURN",He.FakeMouseWithTouches="FakeMouseWithTouches",He.IsQualityController="ControlsQuality",He.MatchViewportResolution="MatchViewportRes",He.StartVideoMuted="StartVideoMuted",He.SuppressBrowserKeys="SuppressBrowserKeys",He.UseMic="UseMic",He.UseModalForTextInput="UseModalForTextInput",He.UseCamera="UseCamera",He.KeyboardInput="KeyboardInput",He.MouseInput="MouseInput",He.MouseDoubleClickAutoRelease="MouseDoubleClickAutoRelease",He.TouchInput="TouchInput",He.GamepadInput="GamepadInput",He.XRControllerInput="XRControllerInput",He.AutoEnterVR="AutoEnterVR",He.WaitForStreamer="WaitForStreamer",He.HideUI="HideUI",He.EnableCaptureTimeExt="EnableCaptureTimeExt",He.BrowserSendOffer="BrowserSendOffer",He.LatencyCSV="LatencyCSV";const je=e=>Object.getOwnPropertyNames(He).some(t=>He[t]===e);class qe{}qe.AFKTimeoutSecs="AFKTimeout",qe.AFKCountdownSecs="AFKCountdown",qe.MinQP="MinQP",qe.MaxQP="MaxQP",qe.MinQuality="MinQuality",qe.MaxQuality="MaxQuality",qe.CompatQualityMin="CompatQualityMin",qe.CompatQualityMax="CompatQualityMax",qe.WebRTCFPS="WebRTCFPS",qe.WebRTCMinBitrate="WebRTCMinBitrate",qe.WebRTCMaxBitrate="WebRTCMaxBitrate",qe.MaxReconnectAttempts="MaxReconnectAttempts",qe.StreamerAutoJoinInterval="StreamerAutoJoinInterval",qe.KeepaliveDelay="KeepaliveDelay",qe.ViewportResScale="ViewportResScale";const ze=e=>Object.getOwnPropertyNames(qe).some(t=>qe[t]===e);class Qe{}Qe.SignallingServerUrl="ss";const Ke=e=>Object.getOwnPropertyNames(Qe).some(t=>Qe[t]===e);class Ge{}Ge.PreferredCodec="PreferredCodec",Ge.StreamerId="StreamerId",Ge.PreferredQuality="PreferredQuality";const Xe=e=>Object.getOwnPropertyNames(Ge).some(t=>Ge[t]===e);class Je{constructor(e={}){this.flags=new Map,this.numericParameters=new Map,this.textParameters=new Map,this.optionParameters=new Map;const{initialSettings:t,useUrlParams:n,webSocketProtocols:s}=e;this._useUrlParams=!!n,this._webSocketProtocols=s,this.populateDefaultSettings(this._useUrlParams,t)}get useUrlParams(){return this._useUrlParams}get webSocketProtocols(){return this._webSocketProtocols}populateDefaultSettings(e,t){this.textParameters.set(Qe.SignallingServerUrl,new Z(Qe.SignallingServerUrl,"Signalling url","Url of the signalling server",t&&Object.prototype.hasOwnProperty.call(t,Qe.SignallingServerUrl)?t[Qe.SignallingServerUrl]:("https:"===location.protocol?"wss://":"ws://")+window.location.hostname+("80"===window.location.port||""===window.location.port?"":`:${window.location.port}`),e)),this.optionParameters.set(Ge.StreamerId,new ee(Ge.StreamerId,"Streamer ID","The ID of the streamer to stream.",t&&Object.prototype.hasOwnProperty.call(t,Ge.StreamerId)?t[Ge.StreamerId]:"",t&&Object.prototype.hasOwnProperty.call(t,Ge.StreamerId)?[t[Ge.StreamerId]]:void 0,e));const n=function(e){const t=$e.getSupportedVideoCodecs();if(t.includes(e))return e;for(const n of t)if(n.startsWith(e))return n;return e};this.optionParameters.set(Ge.PreferredCodec,new ee(Ge.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation",t&&Object.prototype.hasOwnProperty.call(t,Ge.PreferredCodec)?n(t[Ge.PreferredCodec]):function(){const e=$e.getSupportedVideoCodecs();if(1==e.length)return e[0];if(e.length>0){const t=e[0];for(const t of e)if(t.startsWith("H264"))return t;return t}return G.Error("Could not find any reasonable video codec to assign as a default."),""}(),$e.getSupportedVideoCodecs(),e,n)),this.optionParameters.set(Ge.PreferredQuality,new ee(Ge.PreferredQuality,"Preferred Quality","The preferred quality of the stream (only applicable when using the SFU)",t&&Object.prototype.hasOwnProperty.call(t,Ge.PreferredQuality)?t[Ge.PreferredQuality]:"Default",["Default"],e)),this.flags.set(He.AutoConnect,new J(He.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,He.AutoConnect))&&t[He.AutoConnect],e)),this.flags.set(He.AutoPlayVideo,new J(He.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,He.AutoPlayVideo)||t[He.AutoPlayVideo],e)),this.flags.set(He.UseMic,new J(He.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!t||!Object.prototype.hasOwnProperty.call(t,He.UseMic))&&t[He.UseMic],e)),this.flags.set(He.UseModalForTextInput,new J(He.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,He.UseModalForTextInput)||t[He.UseModalForTextInput],e)),this.flags.set(He.UseCamera,new J(He.UseCamera,"Use webcam","Make browser request webcam access and open a input video track.",!(!t||!Object.prototype.hasOwnProperty.call(t,He.UseCamera))&&t[He.UseCamera],e)),this.flags.set(He.StartVideoMuted,new J(He.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!t||!Object.prototype.hasOwnProperty.call(t,He.StartVideoMuted))&&t[He.StartVideoMuted],e)),this.flags.set(He.SuppressBrowserKeys,new J(He.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,He.SuppressBrowserKeys)||t[He.SuppressBrowserKeys],e)),this.flags.set(He.IsQualityController,new J(He.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!t||!Object.prototype.hasOwnProperty.call(t,He.IsQualityController)||t[He.IsQualityController],e)),this.flags.set(He.ForceMonoAudio,new J(He.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!t||!Object.prototype.hasOwnProperty.call(t,He.ForceMonoAudio))&&t[He.ForceMonoAudio],e)),this.flags.set(He.ForceTURN,new J(He.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!t||!Object.prototype.hasOwnProperty.call(t,He.ForceTURN))&&t[He.ForceTURN],e)),this.flags.set(He.AFKDetection,new J(He.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!t||!Object.prototype.hasOwnProperty.call(t,He.AFKDetection))&&t[He.AFKDetection],e)),this.flags.set(He.MatchViewportResolution,new J(He.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,He.MatchViewportResolution))&&t[He.MatchViewportResolution],e)),this.flags.set(He.HoveringMouseMode,new J(He.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,He.HoveringMouseMode))&&t[He.HoveringMouseMode],e,(e,t)=>{t.label=`Control Scheme: ${e?"Hovering":"Locked"} Mouse`})),this.flags.set(He.FakeMouseWithTouches,new J(He.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,He.FakeMouseWithTouches))&&t[He.FakeMouseWithTouches],e)),this.flags.set(He.KeyboardInput,new J(He.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,He.KeyboardInput)||t[He.KeyboardInput],e)),this.flags.set(He.MouseInput,new J(He.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,He.MouseInput)||t[He.MouseInput],e)),this.flags.set(He.MouseDoubleClickAutoRelease,new J(He.MouseDoubleClickAutoRelease,"Auto release after double-click","After sending a MouseDouble message, also send a matching MouseUp so the streamer’s pressed-button state stays balanced. Disable to restore pre-fix behaviour if your project handles the doubleclick release itself.",!t||!Object.prototype.hasOwnProperty.call(t,He.MouseDoubleClickAutoRelease)||t[He.MouseDoubleClickAutoRelease],e)),this.flags.set(He.TouchInput,new J(He.TouchInput,"Touch input","If enabled, send touch events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,He.TouchInput)||t[He.TouchInput],e)),this.flags.set(He.GamepadInput,new J(He.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,He.GamepadInput)||t[He.GamepadInput],e)),this.flags.set(He.XRControllerInput,new J(He.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,He.XRControllerInput)||t[He.XRControllerInput],e)),this.flags.set(He.AutoEnterVR,new J(He.AutoEnterVR,"Auto enter VR","When the video is ready and an immersive-vr session is supported, request the WebXR session automatically. May fail if the browser requires a user gesture to start a WebXR session.",!(!t||!Object.prototype.hasOwnProperty.call(t,He.AutoEnterVR))&&t[He.AutoEnterVR],e)),this.flags.set(He.WaitForStreamer,new J(He.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!t||!Object.prototype.hasOwnProperty.call(t,He.WaitForStreamer)||t[He.WaitForStreamer],e)),this.flags.set(He.HideUI,new J(He.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!t||!Object.prototype.hasOwnProperty.call(t,He.HideUI))&&t[He.HideUI],e)),this.flags.set(He.EnableCaptureTimeExt,new J(He.EnableCaptureTimeExt,"Enable abs-capture-time","Enables the abs-capture-time RTP header extension",!(!t||!Object.prototype.hasOwnProperty.call(t,He.EnableCaptureTimeExt))&&t[He.EnableCaptureTimeExt],e)),this.flags.set(He.BrowserSendOffer,new J(He.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,He.BrowserSendOffer))&&t[He.BrowserSendOffer],e)),this.flags.set(He.LatencyCSV,new J(He.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,He.LatencyCSV))&&t[He.LatencyCSV],e)),this.numericParameters.set(qe.AFKTimeoutSecs,new Y(qe.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,qe.AFKTimeoutSecs)?t[qe.AFKTimeoutSecs]:120,e)),this.numericParameters.set(qe.AFKCountdownSecs,new Y(qe.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(qe.MaxReconnectAttempts,new Y(qe.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,t&&Object.prototype.hasOwnProperty.call(t,qe.MaxReconnectAttempts)?t[qe.MaxReconnectAttempts]:3,e)),this.numericParameters.set(qe.MinQP,new Y(qe.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,qe.MinQP)?t[qe.MinQP]:0,e)),this.numericParameters.set(qe.MaxQP,new Y(qe.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,qe.MaxQP)?t[qe.MaxQP]:51,e)),this.numericParameters.set(qe.MinQuality,new Y(qe.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,qe.MinQuality)?t[qe.MinQuality]:0,e)),this.numericParameters.set(qe.MaxQuality,new Y(qe.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,qe.MaxQuality)?t[qe.MaxQuality]:100,e)),this.numericParameters.set(qe.CompatQualityMin,new Y(qe.CompatQualityMin,"Min Quality","The lower bound for encoding quality. 0 = Worst, 100 = Best.",0,100,t&&Object.prototype.hasOwnProperty.call(t,qe.CompatQualityMin)?t[qe.CompatQualityMin]:0,e)),this.numericParameters.set(qe.CompatQualityMax,new Y(qe.CompatQualityMax,"Max Quality","The upper bound for encoding quality. 0 = Worst, 100 = Best.",0,100,t&&Object.prototype.hasOwnProperty.call(t,qe.CompatQualityMax)?t[qe.CompatQualityMax]:100,e)),this.numericParameters.set(qe.WebRTCFPS,new Y(qe.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,t&&Object.prototype.hasOwnProperty.call(t,qe.WebRTCFPS)?t[qe.WebRTCFPS]:60,e)),this.numericParameters.set(qe.WebRTCMinBitrate,new Y(qe.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,t&&Object.prototype.hasOwnProperty.call(t,qe.WebRTCMinBitrate)?t[qe.WebRTCMinBitrate]:0,e)),this.numericParameters.set(qe.WebRTCMaxBitrate,new Y(qe.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,t&&Object.prototype.hasOwnProperty.call(t,qe.WebRTCMaxBitrate)?t[qe.WebRTCMaxBitrate]:0,e)),this.numericParameters.set(qe.StreamerAutoJoinInterval,new Y(qe.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,t&&Object.prototype.hasOwnProperty.call(t,qe.StreamerAutoJoinInterval)?t[qe.StreamerAutoJoinInterval]:3e3,e)),this.numericParameters.set(qe.KeepaliveDelay,new Y(qe.KeepaliveDelay,"Connection Keepalive delay","Delay between keepalive pings to the signalling server.",0,9e5,t&&Object.prototype.hasOwnProperty.call(t,qe.KeepaliveDelay)?t[qe.KeepaliveDelay]:3e4,e)),this.numericParameters.set(qe.ViewportResScale,new Y(qe.ViewportResScale,"Viewport Resolution Scale","Scale factor for viewport resolution when MatchViewportResolution is enabled. 1.0 = 100%, 0.5 = 50%, 2.0 = 200%.",.1,3,t&&Object.prototype.hasOwnProperty.call(t,qe.ViewportResScale)?t[qe.ViewportResScale]:1,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}`)}hasNumericSetting(e){return this.numericParameters.has(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))throw new Error(`There is no numeric setting with the id of ${e}`);this.numericParameters.get(e).number=t}_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:G.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:G.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:G.Warning(`Cannot set text setting called ${e} - it does not exist in the Config.optionParameters map.`)}setOptionSettingValue(e,t){if(this.optionParameters.has(e)){const n=this.optionParameters.get(e),s=n.options;s.includes(t)||(s.push(t),n.options=s),n.selected=t}else G.Warning(`Cannot set text setting called ${e} - it does not exist in the Config.enumParameters map.`)}setFlagLabel(e,t){this.flags.has(e)?this.flags.get(e).label=t:G.Warning(`Cannot set label for flag called ${e} - it does not exist in the Config.flags map.`)}setSettings(e){for(const t of Object.keys(e))je(t)?this.setFlagEnabled(t,e[t]):ze(t)?this.setNumericSetting(t,e[t]):Ke(t)?this.setTextSetting(t,e[t]):Xe(t)&&this.setOptionSettingValue(t,e[t])}getSettings(){const e={};for(const[t,n]of this.flags.entries())e[t]=n.flag;for(const[t,n]of this.numericParameters.entries())e[t]=n.number;for(const[t,n]of this.textParameters.entries())e[t]=n.text;for(const[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(const t of this.flags.keys()){const n=this.flags.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Ue({id:n.id,type:"flag",value:t,target:n})))}for(const t of this.numericParameters.keys()){const n=this.numericParameters.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Ue({id:n.id,type:"number",value:t,target:n})))}for(const t of this.textParameters.keys()){const n=this.textParameters.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Ue({id:n.id,type:"text",value:t,target:n})))}for(const t of this.optionParameters.keys()){const n=this.optionParameters.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Ue({id:n.id,type:"option",value:t,target:n})))}}}var Ye,Ze,et;!function(e){e[e.LockedMouse=0]="LockedMouse",e[e.HoveringMouse=1]="HoveringMouse"}(Ye||(Ye={}));class tt{constructor(e){this._args=[],this._callback=e}handleEvent(e){this._callback(...this._args),this._args=[]}setArgs(...e){this._args=e}}class nt extends EventTarget{constructor(){super(),this._eventListeners=new Map}removeListenerInternal(e,t){if(this._eventListeners.has(e)){const n=this._eventListeners.get(e);if(void 0===n)return this;for(let s=0;s<n.length;++s){const i=n[s];if(i.callback===t){super.removeEventListener(e,i.eventListenerWrapper),n.splice(s,1);break}}}return this}addListener(e,t){return this.on(e,t)}on(e,t){var n;const s=new tt(t);return super.addEventListener(e,s),this._eventListeners.has(e)||this._eventListeners.set(e,new Array),null===(n=this._eventListeners.get(e))||void 0===n||n.push({callback:t,eventListenerWrapper:s}),this}once(e,t){var n;const s=new tt((...n)=>{t(...n),this.removeListenerInternal(e,t)});return super.addEventListener(e,s,{once:!0}),this._eventListeners.has(e)||this._eventListeners.set(e,new Array),null===(n=this._eventListeners.get(e))||void 0===n||n.push({callback:t,eventListenerWrapper:s}),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)){const t=this._eventListeners.get(e);if(void 0===t)return this;for(const n of t)this.removeEventListener(e,n.eventListenerWrapper);this._eventListeners.delete(e)}return this}emit(e,...t){if(this._eventListeners.has(e)){const n=this._eventListeners.get(e);if(void 0===n)return!1;for(const e of n)e.eventListenerWrapper.setArgs(...t);return super.dispatchEvent(new Event(e)),!0}return!1}}class st extends nt{constructor(e){super(),this.WS_OPEN_STATE=1,this.protocols=e}sendMessage(e){this.webSocket&&this.webSocket.send(e)}connect(e){G.Info(e);try{return this.webSocket=new WebSocket(e,this.protocols),this.webSocket.onopen=e=>this.handleOnOpen(),this.webSocket.onerror=e=>this.handleOnError(),this.webSocket.onclose=e=>this.handleOnClose(e),this.webSocket.onmessage=e=>this.handleOnMessage(e),this.webSocket.onmessagebinary=e=>this.handleOnMessageBinary(e),!0}catch(e){return G.Error(e instanceof Error?e.message:String(e)),!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(e=>{const t=new MessageEvent("messageFromBinary",{data:e});this.handleOnMessage(t)}).catch(e=>{G.Error(`Failed to parse binary blob from websocket, reason: ${e.message}`)})}handleOnMessage(e){e.data&&e.data instanceof Blob?this.handleOnMessageBinary(e):this.onMessage&&this.onMessage(e.data)}handleOnOpen(){G.Info("Connected to the signalling server via WebSocket"),this.emit("open")}handleOnError(){this.emit("error")}handleOnClose(e){G.Info("Disconnected to the signalling server via WebSocket: "+JSON.stringify(e.code)+" - "+e.reason),this.emit("close",e)}}class it extends nt{static get SIGNALLING_VERSION(){return"1.3.0"}constructor(e){super(),this.transport=e,e.onMessage=t=>{let n;try{const e=JSON.parse(t);G.Debug("Protocol received => \n"+JSON.stringify(e,void 0,4)),n=e}catch(e){return void(e instanceof Error?G.Error(`Error parsing message string ${t}.\n${e.message}`):G.Error("Unknown error while parsing message data in handleOnMessage"))}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),G.Debug("Protocol sent => \n"+JSON.stringify(e,void 0,4))}}function rt(e,t,n){let s,i,r=n;for(let n of e.fields){let e=n.localName;if(n.oneof){const o=r[n.oneof];if(null==(null==o?void 0:o.oneofKind))continue;if(s=o[e],i=t[n.oneof],i.oneofKind=o.oneofKind,null==s){delete i[e];continue}}else if(s=r[e],i=t,null==s)continue;switch(n.repeat&&(i[e].length=s.length),n.kind){case"scalar":case"enum":if(n.repeat)for(let t=0;t<s.length;t++)i[e][t]=s[t];else i[e]=s;break;case"message":let t=n.T();if(n.repeat)for(let n=0;n<s.length;n++)i[e][n]=t.create(s[n]);else void 0===i[e]?i[e]=t.create(s):t.mergePartial(i[e],s);break;case"map":switch(n.V.kind){case"scalar":case"enum":Object.assign(i[e],s);break;case"message":let t=n.V.T();for(let n of Object.keys(s))i[e][n]=t.create(s[n])}}}}!function(e){e.symbol=Symbol.for("protobuf-ts/unknown"),e.onRead=(n,s,i,r,o)=>{(t(s)?s[e.symbol]:s[e.symbol]=[]).push({no:i,wireType:r,data:o})},e.onWrite=(t,n,s)=>{for(let{no:t,wireType:i,data:r}of e.list(n))s.tag(t,i).raw(r)},e.list=(n,s)=>{if(t(n)){let t=n[e.symbol];return s?t.filter(e=>e.no==s):t}return[]},e.last=(t,n)=>e.list(t,n).slice(-1)[0];const t=t=>t&&Array.isArray(t[e.symbol])}(Ze||(Ze={})),function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(et||(et={}));const ot=Symbol.for("protobuf-ts/message-type");function at(e){let t=!1;const n=[];for(let s=0;s<e.length;s++){let i=e.charAt(s);"_"==i?t=!0:/\d/.test(i)?(n.push(i),t=!0):t?(n.push(i.toUpperCase()),t=!1):0==s?n.push(i.toLowerCase()):n.push(i)}return n.join("")}var lt,ct,dt;function ht(e){var t,n,s,i;return e.localName=null!==(t=e.localName)&&void 0!==t?t:at(e.name),e.jsonName=null!==(n=e.jsonName)&&void 0!==n?n:at(e.name),e.repeat=null!==(s=e.repeat)&&void 0!==s?s:dt.NO,e.opt=null!==(i=e.opt)&&void 0!==i?i:!e.repeat&&!e.oneof&&"message"==e.kind,e}function ut(e){if("object"!=typeof e||null===e||!e.hasOwnProperty("oneofKind"))return!1;switch(typeof e.oneofKind){case"string":return void 0!==e[e.oneofKind]&&2==Object.keys(e).length;case"undefined":return 1==Object.keys(e).length;default:return!1}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(lt||(lt={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING",e[e.NUMBER=2]="NUMBER"}(ct||(ct={})),function(e){e[e.NO=0]="NO",e[e.PACKED=1]="PACKED",e[e.UNPACKED=2]="UNPACKED"}(dt||(dt={}));class gt{constructor(e){var t;this.fields=null!==(t=e.fields)&&void 0!==t?t:[]}prepare(){if(this.data)return;const e=[],t=[],n=[];for(let s of this.fields)if(s.oneof)n.includes(s.oneof)||(n.push(s.oneof),e.push(s.oneof),t.push(s.oneof));else switch(t.push(s.localName),s.kind){case"scalar":case"enum":s.opt&&!s.repeat||e.push(s.localName);break;case"message":s.repeat&&e.push(s.localName);break;case"map":e.push(s.localName)}this.data={req:e,known:t,oneofs:Object.values(n)}}is(e,t,n=!1){if(t<0)return!0;if(null==e||"object"!=typeof e)return!1;this.prepare();let s=Object.keys(e),i=this.data;if(s.length<i.req.length||i.req.some(e=>!s.includes(e)))return!1;if(!n&&s.some(e=>!i.known.includes(e)))return!1;if(t<1)return!0;for(const s of i.oneofs){const i=e[s];if(!ut(i))return!1;if(void 0===i.oneofKind)continue;const r=this.fields.find(e=>e.localName===i.oneofKind);if(!r)return!1;if(!this.field(i[i.oneofKind],r,n,t))return!1}for(const s of this.fields)if(void 0===s.oneof&&!this.field(e[s.localName],s,n,t))return!1;return!0}field(e,t,n,s){let i=t.repeat;switch(t.kind){case"scalar":return void 0===e?t.opt:i?this.scalars(e,t.T,s,t.L):this.scalar(e,t.T,t.L);case"enum":return void 0===e?t.opt:i?this.scalars(e,lt.INT32,s):this.scalar(e,lt.INT32);case"message":return void 0===e||(i?this.messages(e,t.T(),n,s):this.message(e,t.T(),n,s));case"map":if("object"!=typeof e||null===e)return!1;if(s<2)return!0;if(!this.mapKeys(e,t.K,s))return!1;switch(t.V.kind){case"scalar":return this.scalars(Object.values(e),t.V.T,s,t.V.L);case"enum":return this.scalars(Object.values(e),lt.INT32,s);case"message":return this.messages(Object.values(e),t.V.T(),n,s)}}return!0}message(e,t,n,s){return n?t.isAssignable(e,s):t.is(e,s)}messages(e,t,n,s){if(!Array.isArray(e))return!1;if(s<2)return!0;if(n){for(let n=0;n<e.length&&n<s;n++)if(!t.isAssignable(e[n],s-1))return!1}else for(let n=0;n<e.length&&n<s;n++)if(!t.is(e[n],s-1))return!1;return!0}scalar(e,t,n){let s=typeof e;switch(t){case lt.UINT64:case lt.FIXED64:case lt.INT64:case lt.SFIXED64:case lt.SINT64:switch(n){case ct.BIGINT:return"bigint"==s;case ct.NUMBER:return"number"==s&&!isNaN(e);default:return"string"==s}case lt.BOOL:return"boolean"==s;case lt.STRING:return"string"==s;case lt.BYTES:return e instanceof Uint8Array;case lt.DOUBLE:case lt.FLOAT:return"number"==s&&!isNaN(e);default:return"number"==s&&Number.isInteger(e)}}scalars(e,t,n,s){if(!Array.isArray(e))return!1;if(n<2)return!0;if(Array.isArray(e))for(let i=0;i<e.length&&i<n;i++)if(!this.scalar(e[i],t,s))return!1;return!0}mapKeys(e,t,n){let s=Object.keys(e);switch(t){case lt.INT32:case lt.FIXED32:case lt.SFIXED32:case lt.SINT32:case lt.UINT32:return this.scalars(s.slice(0,n).map(e=>parseInt(e)),t,n);case lt.BOOL:return this.scalars(s.slice(0,n).map(e=>"true"==e||"false"!=e&&e),t,n);default:return this.scalars(s,t,n,ct.STRING)}}}function pt(e){let t=typeof e;if("object"==t){if(Array.isArray(e))return"array";if(null===e)return"null"}return t}function mt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let ft="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),yt=[];for(let e=0;e<ft.length;e++)yt[ft[e].charCodeAt(0)]=e;function vt(){let e=0,t=0;for(let n=0;n<28;n+=7){let s=this.buf[this.pos++];if(e|=(127&s)<<n,!(128&s))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,!(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let s=this.buf[this.pos++];if(t|=(127&s)<<n,!(128&s))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function St(e,t,n){for(let s=0;s<28;s+=7){const i=e>>>s,r=!(i>>>7==0&&0==t),o=255&(r?128|i:i);if(n.push(o),!r)return}const s=e>>>28&15|(7&t)<<4,i=!!(t>>3);if(n.push(255&(i?128|s:s)),i){for(let e=3;e<31;e+=7){const s=t>>>e,i=!(s>>>7==0),r=255&(i?128|s:s);if(n.push(r),!i)return}n.push(t>>>31&1)}}yt["-".charCodeAt(0)]=ft.indexOf("+"),yt["_".charCodeAt(0)]=ft.indexOf("/");const bt=4294967296;function wt(e){let t="-"==e[0];t&&(e=e.slice(1));const n=1e6;let s=0,i=0;function r(t,r){const o=Number(e.slice(t,r));i*=n,s=s*n+o,s>=bt&&(i+=s/bt|0,s%=bt)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),[t,s,i]}function Ct(e,t){if(t>>>0<=2097151)return""+(bt*t+(e>>>0));let n=(e>>>24|t<<8)>>>0&16777215,s=t>>16&65535,i=(16777215&e)+6777216*n+6710656*s,r=n+8147497*s,o=2*s,a=1e7;function l(e,t){let n=e?String(e):"";return t?"0000000".slice(n.length)+n:n}return i>=a&&(r+=Math.floor(i/a),i%=a),r>=a&&(o+=Math.floor(r/a),r%=a),l(o,0)+l(r,o)+l(i,1)}function Mt(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function Tt(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;128&e&&t<10;t++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}let Et;function Rt(e){if(!e)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}!function(){const e=new DataView(new ArrayBuffer(8)),t=void 0!==globalThis.BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64;Et=t?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:e}:void 0}();const kt=/^-?[0-9]+$/,Pt=4294967296,It=2147483648;class xt{constructor(e,t){this.lo=0|e,this.hi=0|t}isZero(){return 0==this.lo&&0==this.hi}toNumber(){let e=this.hi*Pt+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class Lt extends xt{static from(e){if(Et)switch(typeof e){case"string":if("0"==e)return this.ZERO;if(""==e)throw new Error("string is no integer");e=Et.C(e);case"number":if(0===e)return this.ZERO;e=Et.C(e);case"bigint":if(!e)return this.ZERO;if(e<Et.UMIN)throw new Error("signed value for ulong");if(e>Et.UMAX)throw new Error("ulong too large");return Et.V.setBigUint64(0,e,!0),new Lt(Et.V.getInt32(0,!0),Et.V.getInt32(4,!0))}else switch(typeof e){case"string":if("0"==e)return this.ZERO;if(e=e.trim(),!kt.test(e))throw new Error("string is no integer");let[t,n,s]=wt(e);if(t)throw new Error("signed value for ulong");return new Lt(n,s);case"number":if(0==e)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 Lt(e,e/Pt)}throw new Error("unknown value "+typeof e)}toString(){return Et?this.toBigInt().toString():Ct(this.lo,this.hi)}toBigInt(){return Rt(Et),Et.V.setInt32(0,this.lo,!0),Et.V.setInt32(4,this.hi,!0),Et.V.getBigUint64(0,!0)}}Lt.ZERO=new Lt(0,0);class At extends xt{static from(e){if(Et)switch(typeof e){case"string":if("0"==e)return this.ZERO;if(""==e)throw new Error("string is no integer");e=Et.C(e);case"number":if(0===e)return this.ZERO;e=Et.C(e);case"bigint":if(!e)return this.ZERO;if(e<Et.MIN)throw new Error("signed long too small");if(e>Et.MAX)throw new Error("signed long too large");return Et.V.setBigInt64(0,e,!0),new At(Et.V.getInt32(0,!0),Et.V.getInt32(4,!0))}else switch(typeof e){case"string":if("0"==e)return this.ZERO;if(e=e.trim(),!kt.test(e))throw new Error("string is no integer");let[t,n,s]=wt(e);if(t){if(s>It||s==It&&0!=n)throw new Error("signed long too small")}else if(s>=It)throw new Error("signed long too large");let i=new At(n,s);return t?i.negate():i;case"number":if(0==e)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new At(e,e/Pt):new At(-e,-e/Pt).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return 0!==(this.hi&It)}negate(){let e=~this.hi,t=this.lo;return t?t=1+~t:e+=1,new At(t,e)}toString(){if(Et)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+Ct(e.lo,e.hi)}return Ct(this.lo,this.hi)}toBigInt(){return Rt(Et),Et.V.setInt32(0,this.lo,!0),Et.V.setInt32(4,this.hi,!0),Et.V.getBigInt64(0,!0)}}function Dt(e,t){if(!e)throw new Error(t)}function Ot(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function Ft(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function Nt(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}function Ut(e,t){switch(t){case ct.BIGINT:return e.toBigInt();case ct.NUMBER:return e.toNumber();default:return e.toString()}}At.ZERO=new At(0,0);class Bt{constructor(e){this.info=e}prepare(){var e;if(void 0===this.fMap){this.fMap={};const t=null!==(e=this.info.fields)&&void 0!==e?e:[];for(const e of t)this.fMap[e.name]=e,this.fMap[e.jsonName]=e,this.fMap[e.localName]=e}}assert(e,t,n){if(!e){let e=pt(n);throw"number"!=e&&"boolean"!=e||(e=n.toString()),new Error(`Cannot parse JSON ${e} for ${this.info.typeName}#${t}`)}}read(e,t,n){this.prepare();const s=[];for(const[i,r]of Object.entries(e)){const e=this.fMap[i];if(!e){if(!n.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${i}`);continue}const o=e.localName;let a;if(e.oneof){if(null===r&&("enum"!==e.kind||"google.protobuf.NullValue"!==e.T()[0]))continue;if(s.includes(e.oneof))throw new Error(`Multiple members of the oneof group "${e.oneof}" of ${this.info.typeName} are present in JSON.`);s.push(e.oneof),a=t[e.oneof]={oneofKind:o}}else a=t;if("map"==e.kind){if(null===r)continue;this.assert(mt(r),e.name,r);const t=a[o];for(const[s,i]of Object.entries(r)){let r;switch(this.assert(null!==i,e.name+" map value",null),e.V.kind){case"message":r=e.V.T().internalJsonRead(i,n);break;case"enum":if(r=this.enum(e.V.T(),i,e.name,n.ignoreUnknownFields),!1===r)continue;break;case"scalar":r=this.scalar(i,e.V.T,e.V.L,e.name)}this.assert(void 0!==r,e.name+" map value",i);let o=s;e.K==lt.BOOL&&(o="true"==o||"false"!=o&&o),o=this.scalar(o,e.K,ct.STRING,e.name).toString(),t[o]=r}}else if(e.repeat){if(null===r)continue;this.assert(Array.isArray(r),e.name,r);const t=a[o];for(const s of r){let i;switch(this.assert(null!==s,e.name,null),e.kind){case"message":i=e.T().internalJsonRead(s,n);break;case"enum":if(i=this.enum(e.T(),s,e.name,n.ignoreUnknownFields),!1===i)continue;break;case"scalar":i=this.scalar(s,e.T,e.L,e.name)}this.assert(void 0!==i,e.name,r),t.push(i)}}else switch(e.kind){case"message":if(null===r&&"google.protobuf.Value"!=e.T().typeName){this.assert(void 0===e.oneof,e.name+" (oneof member)",null);continue}a[o]=e.T().internalJsonRead(r,n,a[o]);break;case"enum":if(null===r)continue;let t=this.enum(e.T(),r,e.name,n.ignoreUnknownFields);if(!1===t)continue;a[o]=t;break;case"scalar":if(null===r)continue;a[o]=this.scalar(r,e.T,e.L,e.name)}}}enum(e,t,n,s){if("google.protobuf.NullValue"==e[0]&&Dt(null===t||"NULL_VALUE"===t,`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} only accepts null.`),null===t)return 0;switch(typeof t){case"number":return Dt(Number.isInteger(t),`Unable to parse field ${this.info.typeName}#${n}, enum can only be integral number, got ${t}.`),t;case"string":let i=t;e[2]&&t.substring(0,e[2].length)===e[2]&&(i=t.substring(e[2].length));let r=e[1][i];return(void 0!==r||!s)&&(Dt("number"==typeof r,`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} has no value for "${t}".`),r)}Dt(!1,`Unable to parse field ${this.info.typeName}#${n}, cannot parse enum value from ${typeof t}".`)}scalar(e,t,n,s){let i;try{switch(t){case lt.DOUBLE:case lt.FLOAT:if(null===e)return 0;if("NaN"===e)return Number.NaN;if("Infinity"===e)return Number.POSITIVE_INFINITY;if("-Infinity"===e)return Number.NEGATIVE_INFINITY;if(""===e){i="empty string";break}if("string"==typeof e&&e.trim().length!==e.length){i="extra whitespace";break}if("string"!=typeof e&&"number"!=typeof e)break;let s=Number(e);if(Number.isNaN(s)){i="not a number";break}if(!Number.isFinite(s)){i="too large or small";break}return t==lt.FLOAT&&Nt(s),s;case lt.INT32:case lt.FIXED32:case lt.SFIXED32:case lt.SINT32:case lt.UINT32:if(null===e)return 0;let r;if("number"==typeof e?r=e:""===e?i="empty string":"string"==typeof e&&(e.trim().length!==e.length?i="extra whitespace":r=Number(e)),void 0===r)break;return t==lt.UINT32?Ft(r):Ot(r),r;case lt.INT64:case lt.SFIXED64:case lt.SINT64:if(null===e)return Ut(At.ZERO,n);if("number"!=typeof e&&"string"!=typeof e)break;return Ut(At.from(e),n);case lt.FIXED64:case lt.UINT64:if(null===e)return Ut(Lt.ZERO,n);if("number"!=typeof e&&"string"!=typeof e)break;return Ut(Lt.from(e),n);case lt.BOOL:if(null===e)return!1;if("boolean"!=typeof e)break;return e;case lt.STRING:if(null===e)return"";if("string"!=typeof e){i="extra whitespace";break}try{encodeURIComponent(e)}catch(i){i="invalid UTF8";break}return e;case lt.BYTES:if(null===e||""===e)return new Uint8Array(0);if("string"!=typeof e)break;return function(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let n,s=new Uint8Array(t),i=0,r=0,o=0;for(let t=0;t<e.length;t++){if(n=yt[e.charCodeAt(t)],void 0===n)switch(e[t]){case"=":r=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=n,r=1;break;case 1:s[i++]=o<<2|(48&n)>>4,o=n,r=2;break;case 2:s[i++]=(15&o)<<4|(60&n)>>2,o=n,r=3;break;case 3:s[i++]=(3&o)<<6|n,r=0}}if(1==r)throw Error("invalid base64 string.");return s.subarray(0,i)}(e)}}catch(e){i=e.message}this.assert(!1,s+(i?" - "+i:""),e)}}class Vt{constructor(e){var t;this.fields=null!==(t=e.fields)&&void 0!==t?t:[]}write(e,t){const n={},s=e;for(const e of this.fields){if(!e.oneof){let i=this.field(e,s[e.localName],t);void 0!==i&&(n[t.useProtoFieldName?e.name:e.jsonName]=i);continue}const i=s[e.oneof];if(i.oneofKind!==e.localName)continue;const r="scalar"==e.kind||"enum"==e.kind?Object.assign(Object.assign({},t),{emitDefaultValues:!0}):t;let o=this.field(e,i[e.localName],r);Dt(void 0!==o),n[t.useProtoFieldName?e.name:e.jsonName]=o}return n}field(e,t,n){let s;if("map"==e.kind){Dt("object"==typeof t&&null!==t);const i={};switch(e.V.kind){case"scalar":for(const[n,s]of Object.entries(t)){const t=this.scalar(e.V.T,s,e.name,!1,!0);Dt(void 0!==t),i[n.toString()]=t}break;case"message":const s=e.V.T();for(const[r,o]of Object.entries(t)){const t=this.message(s,o,e.name,n);Dt(void 0!==t),i[r.toString()]=t}break;case"enum":const r=e.V.T();for(const[s,o]of Object.entries(t)){Dt(void 0===o||"number"==typeof o);const t=this.enum(r,o,e.name,!1,!0,n.enumAsInteger);Dt(void 0!==t),i[s.toString()]=t}}(n.emitDefaultValues||Object.keys(i).length>0)&&(s=i)}else if(e.repeat){Dt(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let n=0;n<t.length;n++){const s=this.scalar(e.T,t[n],e.name,e.opt,!0);Dt(void 0!==s),i.push(s)}break;case"enum":const s=e.T();for(let r=0;r<t.length;r++){Dt(void 0===t[r]||"number"==typeof t[r]);const o=this.enum(s,t[r],e.name,e.opt,!0,n.enumAsInteger);Dt(void 0!==o),i.push(o)}break;case"message":const r=e.T();for(let s=0;s<t.length;s++){const o=this.message(r,t[s],e.name,n);Dt(void 0!==o),i.push(o)}}(n.emitDefaultValues||i.length>0||n.emitDefaultValues)&&(s=i)}else switch(e.kind){case"scalar":s=this.scalar(e.T,t,e.name,e.opt,n.emitDefaultValues);break;case"enum":s=this.enum(e.T(),t,e.name,e.opt,n.emitDefaultValues,n.enumAsInteger);break;case"message":s=this.message(e.T(),t,e.name,n)}return s}enum(e,t,n,s,i,r){if("google.protobuf.NullValue"==e[0])return i||s?null:void 0;if(void 0!==t){if(0!==t||i||s)return Dt("number"==typeof t),Dt(Number.isInteger(t)),r||!e[1].hasOwnProperty(t)?t:e[2]?e[2]+e[1][t]:e[1][t]}else Dt(s)}message(e,t,n,s){return void 0===t?s.emitDefaultValues?null:void 0:e.internalJsonWrite(t,s)}scalar(e,t,n,s,i){if(void 0===t)return void Dt(s);const r=i||s;switch(e){case lt.INT32:case lt.SFIXED32:case lt.SINT32:return 0===t?r?0:void 0:(Ot(t),t);case lt.FIXED32:case lt.UINT32:return 0===t?r?0:void 0:(Ft(t),t);case lt.FLOAT:Nt(t);case lt.DOUBLE:return 0===t?r?0:void 0:(Dt("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t);case lt.STRING:return""===t?r?"":void 0:(Dt("string"==typeof t),t);case lt.BOOL:return!1===t?!r&&void 0:(Dt("boolean"==typeof t),t);case lt.UINT64:case lt.FIXED64:Dt("number"==typeof t||"string"==typeof t||"bigint"==typeof t);let e=Lt.from(t);if(e.isZero()&&!r)return;return e.toString();case lt.INT64:case lt.SFIXED64:case lt.SINT64:Dt("number"==typeof t||"string"==typeof t||"bigint"==typeof t);let n=At.from(t);if(n.isZero()&&!r)return;return n.toString();case lt.BYTES:return Dt(t instanceof Uint8Array),t.byteLength?function(e){let t,n="",s=0,i=0;for(let r=0;r<e.length;r++)switch(t=e[r],s){case 0:n+=ft[t>>2],i=(3&t)<<4,s=1;break;case 1:n+=ft[i|t>>4],i=(15&t)<<2,s=2;break;case 2:n+=ft[i|t>>6],n+=ft[63&t],s=0}return s&&(n+=ft[i],n+="=",1==s&&(n+="=")),n}(t):r?"":void 0}}}function _t(e,t=ct.STRING){switch(e){case lt.BOOL:return!1;case lt.UINT64:case lt.FIXED64:return Ut(Lt.ZERO,t);case lt.INT64:case lt.SFIXED64:case lt.SINT64:return Ut(At.ZERO,t);case lt.DOUBLE:case lt.FLOAT:return 0;case lt.BYTES:return new Uint8Array(0);case lt.STRING:return"";default:return 0}}class Wt{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){const t=null!==(e=this.info.fields)&&void 0!==e?e:[];this.fieldNoToField=new Map(t.map(e=>[e.no,e]))}}read(e,t,n,s){this.prepare();const i=void 0===s?e.len:e.pos+s;for(;e.pos<i;){const[s,i]=e.tag(),r=this.fieldNoToField.get(s);if(!r){let r=n.readUnknownField;if("throw"==r)throw new Error(`Unknown field ${s} (wire type ${i}) for ${this.info.typeName}`);let o=e.skip(i);!1!==r&&(!0===r?Ze.onRead:r)(this.info.typeName,t,s,i,o);continue}let o=t,a=r.repeat,l=r.localName;switch(r.oneof&&(o=o[r.oneof],o.oneofKind!==l&&(o=t[r.oneof]={oneofKind:l})),r.kind){case"scalar":case"enum":let t="enum"==r.kind?lt.INT32:r.T,s="scalar"==r.kind?r.L:void 0;if(a){let n=o[l];if(i==et.LengthDelimited&&t!=lt.STRING&&t!=lt.BYTES){let i=e.uint32()+e.pos;for(;e.pos<i;)n.push(this.scalar(e,t,s))}else n.push(this.scalar(e,t,s))}else o[l]=this.scalar(e,t,s);break;case"message":if(a){let t=o[l],s=r.T().internalBinaryRead(e,e.uint32(),n);t.push(s)}else o[l]=r.T().internalBinaryRead(e,e.uint32(),n,o[l]);break;case"map":let[c,d]=this.mapEntry(r,e,n);o[l][c]=d}}}mapEntry(e,t,n){let s,i,r=t.uint32(),o=t.pos+r;for(;t.pos<o;){let[r,o]=t.tag();switch(r){case 1:s=e.K==lt.BOOL?t.bool().toString():this.scalar(t,e.K,ct.STRING);break;case 2:switch(e.V.kind){case"scalar":i=this.scalar(t,e.V.T,e.V.L);break;case"enum":i=t.int32();break;case"message":i=e.V.T().internalBinaryRead(t,t.uint32(),n)}break;default:throw new Error(`Unknown field ${r} (wire type ${o}) in map entry for ${this.info.typeName}#${e.name}`)}}if(void 0===s){let t=_t(e.K);s=e.K==lt.BOOL?t.toString():t}if(void 0===i)switch(e.V.kind){case"scalar":i=_t(e.V.T,e.V.L);break;case"enum":i=0;break;case"message":i=e.V.T().create()}return[s,i]}scalar(e,t,n){switch(t){case lt.INT32:return e.int32();case lt.STRING:return e.string();case lt.BOOL:return e.bool();case lt.DOUBLE:return e.double();case lt.FLOAT:return e.float();case lt.INT64:return Ut(e.int64(),n);case lt.UINT64:return Ut(e.uint64(),n);case lt.FIXED64:return Ut(e.fixed64(),n);case lt.FIXED32:return e.fixed32();case lt.BYTES:return e.bytes();case lt.UINT32:return e.uint32();case lt.SFIXED32:return e.sfixed32();case lt.SFIXED64:return Ut(e.sfixed64(),n);case lt.SINT32:return e.sint32();case lt.SINT64:return Ut(e.sint64(),n)}}}class $t{constructor(e){this.info=e}prepare(){if(!this.fields){const e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((e,t)=>e.no-t.no)}}write(e,t,n){this.prepare();for(const s of this.fields){let i,r,o=s.repeat,a=s.localName;if(s.oneof){const t=e[s.oneof];if(t.oneofKind!==a)continue;i=t[a],r=!0}else i=e[a],r=!1;switch(s.kind){case"scalar":case"enum":let e="enum"==s.kind?lt.INT32:s.T;if(o)if(Dt(Array.isArray(i)),o==dt.PACKED)this.packed(t,e,s.no,i);else for(const n of i)this.scalar(t,e,s.no,n,!0);else void 0===i?Dt(s.opt):this.scalar(t,e,s.no,i,r||s.opt);break;case"message":if(o){Dt(Array.isArray(i));for(const e of i)this.message(t,n,s.T(),s.no,e)}else this.message(t,n,s.T(),s.no,i);break;case"map":Dt("object"==typeof i&&null!==i);for(const[e,r]of Object.entries(i))this.mapEntry(t,n,s,e,r)}}let s=n.writeUnknownFields;!1!==s&&(!0===s?Ze.onWrite:s)(this.info.typeName,e,t)}mapEntry(e,t,n,s,i){e.tag(n.no,et.LengthDelimited),e.fork();let r=s;switch(n.K){case lt.INT32:case lt.FIXED32:case lt.UINT32:case lt.SFIXED32:case lt.SINT32:r=Number.parseInt(s);break;case lt.BOOL:Dt("true"==s||"false"==s),r="true"==s}switch(this.scalar(e,n.K,1,r,!0),n.V.kind){case"scalar":this.scalar(e,n.V.T,2,i,!0);break;case"enum":this.scalar(e,lt.INT32,2,i,!0);break;case"message":this.message(e,t,n.V.T(),2,i)}e.join()}message(e,t,n,s,i){void 0!==i&&(n.internalBinaryWrite(i,e.tag(s,et.LengthDelimited).fork(),t),e.join())}scalar(e,t,n,s,i){let[r,o,a]=this.scalarInfo(t,s);a&&!i||(e.tag(n,r),e[o](s))}packed(e,t,n,s){if(!s.length)return;Dt(t!==lt.BYTES&&t!==lt.STRING),e.tag(n,et.LengthDelimited),e.fork();let[,i]=this.scalarInfo(t);for(let t=0;t<s.length;t++)e[i](s[t]);e.join()}scalarInfo(e,t){let n,s=et.Varint,i=void 0===t,r=0===t;switch(e){case lt.INT32:n="int32";break;case lt.STRING:r=i||!t.length,s=et.LengthDelimited,n="string";break;case lt.BOOL:r=!1===t,n="bool";break;case lt.UINT32:n="uint32";break;case lt.DOUBLE:s=et.Bit64,n="double";break;case lt.FLOAT:s=et.Bit32,n="float";break;case lt.INT64:r=i||At.from(t).isZero(),n="int64";break;case lt.UINT64:r=i||Lt.from(t).isZero(),n="uint64";break;case lt.FIXED64:r=i||Lt.from(t).isZero(),s=et.Bit64,n="fixed64";break;case lt.BYTES:r=i||!t.byteLength,s=et.LengthDelimited,n="bytes";break;case lt.FIXED32:s=et.Bit32,n="fixed32";break;case lt.SFIXED32:s=et.Bit32,n="sfixed32";break;case lt.SFIXED64:r=i||At.from(t).isZero(),s=et.Bit64,n="sfixed64";break;case lt.SINT32:n="sint32";break;case lt.SINT64:r=i||At.from(t).isZero(),n="sint64"}return[s,n,i||r]}}const Ht={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},jt={ignoreUnknownFields:!1},qt=Object.values;function zt(e,t,n){if(t===n)return!0;if(e!==lt.BYTES)return!1;let s=t,i=n;if(s.length!==i.length)return!1;for(let e=0;e<s.length;e++)if(s[e]!=i[e])return!1;return!0}function Qt(e,t,n){if(t.length!==n.length)return!1;for(let s=0;s<t.length;s++)if(!zt(e,t[s],n[s]))return!1;return!0}function Kt(e,t,n){if(t.length!==n.length)return!1;for(let s=0;s<t.length;s++)if(!e.equals(t[s],n[s]))return!1;return!0}const Gt={writeUnknownFields:!0,writerFactory:()=>new Xt};class Xt{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].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(Ft(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return Ot(e),Mt(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){Nt(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){Ft(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Ot(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Ot(e),Mt(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=At.from(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=Lt.from(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=At.from(e);return St(t.lo,t.hi,this.buf),this}sint64(e){let t=At.from(e),n=t.hi>>31;return St(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=Lt.from(e);return St(t.lo,t.hi,this.buf),this}}const Jt={readUnknownField:!0,readerFactory:e=>new Yt(e)};class Yt{constructor(e,t){this.varint64=vt,this.uint32=Tt,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),t=e>>>3,n=7&e;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 et.Varint:for(;128&this.buf[this.pos++];);break;case et.Bit64:this.pos+=4;case et.Bit32:this.pos+=4;break;case et.LengthDelimited:let t=this.uint32();this.pos+=t;break;case et.StartGroup:let n;for(;(n=this.tag()[1])!==et.EndGroup;)this.skip(n);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 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return new At(...this.varint64())}uint64(){return new Lt(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(1&e);return e=(e>>>1|(1&t)<<31)^n,t=t>>>1^n,new At(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new Lt(this.sfixed32(),this.sfixed32())}sfixed64(){return new At(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())}}const Zt=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),en=Zt[ot]={};class tn{constructor(e,t,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=t.map(ht),this.options=null!=n?n:{},en.value=this,this.messagePrototype=Object.create(null,Zt),this.refTypeCheck=new gt(this),this.refJsonReader=new Bt(this),this.refJsonWriter=new Vt(this),this.refBinReader=new Wt(this),this.refBinWriter=new $t(this)}create(e){let t=function(e){const t=e.messagePrototype?Object.create(e.messagePrototype):Object.defineProperty({},ot,{value:e});for(let n of e.fields){let e=n.localName;if(!n.opt)if(n.oneof)t[n.oneof]={oneofKind:void 0};else if(n.repeat)t[e]=[];else switch(n.kind){case"scalar":t[e]=_t(n.T,n.L);break;case"enum":t[e]=0;break;case"map":t[e]={}}}return t}(this);return void 0!==e&&rt(this,t,e),t}clone(e){let t=this.create();return rt(this,t,e),t}equals(e,t){return function(e,t,n){if(t===n)return!0;if(!t||!n)return!1;for(let s of e.fields){let e=s.localName,i=s.oneof?t[s.oneof][e]:t[e],r=s.oneof?n[s.oneof][e]:n[e];switch(s.kind){case"enum":case"scalar":let e="enum"==s.kind?lt.INT32:s.T;if(!(s.repeat?Qt(e,i,r):zt(e,i,r)))return!1;break;case"map":if(!("message"==s.V.kind?Kt(s.V.T(),qt(i),qt(r)):Qt("enum"==s.V.kind?lt.INT32:s.V.T,qt(i),qt(r))))return!1;break;case"message":let t=s.T();if(!(s.repeat?Kt(t,i,r):t.equals(i,r)))return!1}}return!0}(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){rt(this,e,t)}fromBinary(e,t){let n=function(e){return e?Object.assign(Object.assign({},Jt),e):Jt}(t);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,t){return this.internalJsonRead(e,function(e){return e?Object.assign(Object.assign({},jt),e):jt}(t))}fromJsonString(e,t){let n=JSON.parse(e);return this.fromJson(n,t)}toJson(e,t){return this.internalJsonWrite(e,function(e){return e?Object.assign(Object.assign({},Ht),e):Ht}(t))}toJsonString(e,t){var n;let s=this.toJson(e,t);return JSON.stringify(s,null,null!==(n=null==t?void 0:t.prettySpaces)&&void 0!==n?n:0)}toBinary(e,t){let n=function(e){return e?Object.assign(Object.assign({},Gt),e):Gt}(t);return this.internalBinaryWrite(e,n.writerFactory(),n).finish()}internalJsonRead(e,t,n){if(null!==e&&"object"==typeof e&&!Array.isArray(e)){let s=null!=n?n:this.create();return this.refJsonReader.read(e,s,t),s}throw new Error(`Unable to parse message ${this.typeName} from JSON ${pt(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,s){let i=null!=s?s:this.create();return this.refBinReader.read(e,i,n,t),i}}new class extends tn{constructor(){super("base_message",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};const nn=new class extends tn{constructor(){super("peerConnectionOptions",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},sn=new class extends tn{constructor(){super("config",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"peerConnectionOptions",kind:"message",T:()=>nn},{no:3,name:"protocolVersion",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.peerConnectionOptions=nn.internalBinaryRead(e,e.uint32(),n,i.peerConnectionOptions);break;case 3:i.protocolVersion=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),e.peerConnectionOptions&&nn.internalBinaryWrite(e.peerConnectionOptions,t.tag(2,et.LengthDelimited).fork(),n).join(),void 0!==e.protocolVersion&&t.tag(3,et.LengthDelimited).string(e.protocolVersion);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};new class extends tn{constructor(){super("identify",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.id="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.id=e.string();break;case 3:i.protocolVersion=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.id&&t.tag(2,et.LengthDelimited).string(e.id),void 0!==e.protocolVersion&&t.tag(3,et.LengthDelimited).string(e.protocolVersion);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},new class extends tn{constructor(){super("endpointIdConfirm",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"committedId",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.committedId="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.committedId=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.committedId&&t.tag(2,et.LengthDelimited).string(e.committedId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};const rn=new class extends tn{constructor(){super("streamerIdChanged",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"newID",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.newID="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.newID=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.newID&&t.tag(2,et.LengthDelimited).string(e.newID);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},on=new class extends tn{constructor(){super("listStreamers",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},an=new class extends tn{constructor(){super("streamerList",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"ids",kind:"scalar",repeat:2,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.ids=[],void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.ids.push(e.string());break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);for(let n=0;n<e.ids.length;n++)t.tag(2,et.LengthDelimited).string(e.ids[n]);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},ln=new class extends tn{constructor(){super("subscribe",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"streamerId",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.streamerId="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.streamerId=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.streamerId&&t.tag(2,et.LengthDelimited).string(e.streamerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};new class extends tn{constructor(){super("unsubscribe",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};const cn=new class extends tn{constructor(){super("subscribeFailed",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"message",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.message="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.message=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.message&&t.tag(2,et.LengthDelimited).string(e.message);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.dataChannel=!1,t.sfu=!1,t.playerId="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.dataChannel=e.bool();break;case 3:i.sfu=e.bool();break;case 5:i.playerId=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),!1!==e.dataChannel&&t.tag(2,et.Varint).bool(e.dataChannel),!1!==e.sfu&&t.tag(3,et.Varint).bool(e.sfu),""!==e.playerId&&t.tag(5,et.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},new class extends tn{constructor(){super("playerDisconnected",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"playerId",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.playerId="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.playerId=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.playerId&&t.tag(2,et.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};const dn=new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.sdp="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.sdp=e.string();break;case 3:i.playerId=e.string();break;case 4:i.sfu=e.bool();break;case 5:i.multiplex=e.bool();break;case 6:i.scalabilityMode=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.sdp&&t.tag(2,et.LengthDelimited).string(e.sdp),void 0!==e.playerId&&t.tag(3,et.LengthDelimited).string(e.playerId),void 0!==e.sfu&&t.tag(4,et.Varint).bool(e.sfu),void 0!==e.multiplex&&t.tag(5,et.Varint).bool(e.multiplex),void 0!==e.scalabilityMode&&t.tag(6,et.LengthDelimited).string(e.scalabilityMode);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},hn=new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.sdp="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.sdp=e.string();break;case 3:i.playerId=e.string();break;case 4:i.minBitrateBps=e.int32();break;case 5:i.maxBitrateBps=e.int32();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.sdp&&t.tag(2,et.LengthDelimited).string(e.sdp),void 0!==e.playerId&&t.tag(3,et.LengthDelimited).string(e.playerId),void 0!==e.minBitrateBps&&t.tag(4,et.Varint).int32(e.minBitrateBps),void 0!==e.maxBitrateBps&&t.tag(5,et.Varint).int32(e.maxBitrateBps);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},un=new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.candidate="",t.sdpMid="",t.sdpMLineIndex=0,void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.candidate=e.string();break;case 2:i.sdpMid=e.string();break;case 3:i.sdpMLineIndex=e.int32();break;case 4:i.usernameFragment=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.candidate&&t.tag(1,et.LengthDelimited).string(e.candidate),""!==e.sdpMid&&t.tag(2,et.LengthDelimited).string(e.sdpMid),0!==e.sdpMLineIndex&&t.tag(3,et.Varint).int32(e.sdpMLineIndex),void 0!==e.usernameFragment&&t.tag(4,et.LengthDelimited).string(e.usernameFragment);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},gn=new class extends tn{constructor(){super("iceCandidate",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"candidate",kind:"message",T:()=>un},{no:3,name:"playerId",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.candidate=un.internalBinaryRead(e,e.uint32(),n,i.candidate);break;case 3:i.playerId=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),e.candidate&&un.internalBinaryWrite(e.candidate,t.tag(2,et.LengthDelimited).fork(),n).join(),void 0!==e.playerId&&t.tag(3,et.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.playerId="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.playerId=e.string();break;case 3:i.reason=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.playerId&&t.tag(2,et.LengthDelimited).string(e.playerId),void 0!==e.reason&&t.tag(3,et.LengthDelimited).string(e.reason);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};const pn=new class extends tn{constructor(){super("ping",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"time",kind:"scalar",T:5}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.time=0,void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.time=e.int32();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),0!==e.time&&t.tag(2,et.Varint).int32(e.time);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},mn=new class extends tn{constructor(){super("pong",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"time",kind:"scalar",T:5}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.time=0,void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.time=e.int32();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),0!==e.time&&t.tag(2,et.Varint).int32(e.time);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};new class extends tn{constructor(){super("streamerDisconnected",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};const fn=new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.spatialLayer=0,t.temporalLayer=0,t.playerId="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.spatialLayer=e.int32();break;case 3:i.temporalLayer=e.int32();break;case 4:i.playerId=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),0!==e.spatialLayer&&t.tag(2,et.Varint).int32(e.spatialLayer),0!==e.temporalLayer&&t.tag(3,et.Varint).int32(e.temporalLayer),""!==e.playerId&&t.tag(4,et.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},yn=new class extends tn{constructor(){super("dataChannelRequest",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},vn=new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.playerId="",t.sendStreamId=0,t.recvStreamId=0,void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.playerId=e.string();break;case 3:i.sendStreamId=e.int32();break;case 4:i.recvStreamId=e.int32();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.playerId&&t.tag(2,et.LengthDelimited).string(e.playerId),0!==e.sendStreamId&&t.tag(3,et.Varint).int32(e.sendStreamId),0!==e.recvStreamId&&t.tag(4,et.Varint).int32(e.recvStreamId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},Sn=new class extends tn{constructor(){super("peerDataChannelsReady",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.sfuId="",t.sendStreamId=0,t.recvStreamId=0,void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.sfuId=e.string();break;case 3:i.sendStreamId=e.int32();break;case 4:i.recvStreamId=e.int32();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.sfuId&&t.tag(2,et.LengthDelimited).string(e.sfuId),0!==e.sendStreamId&&t.tag(3,et.Varint).int32(e.sendStreamId),0!==e.recvStreamId&&t.tag(4,et.Varint).int32(e.recvStreamId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},new class extends tn{constructor(){super("startStreaming",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},new class extends tn{constructor(){super("stopStreaming",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};const bn=new class extends tn{constructor(){super("playerCount",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"count",kind:"scalar",T:5}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.count=0,void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.count=e.int32();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),0!==e.count&&t.tag(2,et.Varint).int32(e.count);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};function wn(e,t){const n=e.create();return n.type=e.typeName,t&&e.mergePartial(n,t),n}new class extends tn{constructor(){super("stats",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"data",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.data="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.data=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.data&&t.tag(2,et.LengthDelimited).string(e.data);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};class Cn{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;!1!==this.alive?(this.alive=!1,this.protocol.sendMessage(wn(pn,{time:(new Date).getTime()}))):null===(e=this.onTimeout)||void 0===e||e.call(this)}onHeartbeatResponse(e){this.rtt=(new Date).getTime()-e.time,this.alive=!0}}class Mn{constructor(e){this.videoElementProvider=e,this.audioElement=document.createElement("Audio"),this.videoElementProvider.setAudioElement(this.audioElement)}handleOnTrack(e){if(G.Info("handleOnTrack "+JSON.stringify(e.streams)),e.streams.length<1||"probator"===e.streams[0].id)return;const t=this.videoElementProvider.getVideoElement();if(e.track&&G.Info("Got track - "+e.track.kind+" id="+e.track.id+" readyState="+e.track.readyState),"audio"!==e.track.kind)return"video"===e.track.kind&&t.srcObject!==e.streams[0]?(t.srcObject=e.streams[0],void G.Info("Set video source from video track ontrack.")):void 0;this.CreateAudioTrack(e.streams[0])}CreateAudioTrack(e){const t=this.videoElementProvider.getVideoElement();t.srcObject!=e&&t.srcObject&&t.srcObject!==e&&(this.audioElement.srcObject=e,G.Info("Created new audio element to play separate audio stream."))}}class Tn{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){const t=btoa(e.reduce((e,t)=>e+String.fromCharCode(t),""));this.imageElement.src="data:image/jpeg;base64,"+t}setDimensionsFromElementAndResize(){this.freezeFrameHeight=this.imageElement.naturalHeight,this.freezeFrameWidth=this.imageElement.naturalWidth,this.resize()}resize(){if(0!==this.freezeFrameWidth&&0!==this.freezeFrameHeight){let e=0,t=0,n=0,s=0;const i=this.rootDiv.clientWidth/this.rootDiv.clientHeight,r=this.freezeFrameWidth/this.freezeFrameHeight;i<r?(e=this.rootDiv.clientWidth,t=Math.floor(this.rootDiv.clientWidth/r),n=Math.floor(.5*(this.rootDiv.clientHeight-t)),s=0):(e=Math.floor(this.rootDiv.clientHeight*r),t=this.rootDiv.clientHeight,n=0,s=Math.floor(.5*(this.rootDiv.clientWidth-e))),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=s+"px",this.imageElement.style.top=n+"px"}}}class En{constructor(e){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new Tn(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);const n=e.slice(5);if(this.jpeg){const e=new Uint8Array(this.jpeg.length+n.length);e.set(this.jpeg,0),e.set(n,this.jpeg.length),this.jpeg=e}else this.jpeg=n,this.receiving=!0,G.Info(`received first chunk of freeze frame: ${this.jpeg.length}/${this.size}`);this.jpeg.length===this.size?(this.receiving=!1,this.valid=!0,G.Info(`received complete freeze frame ${this.size}`),this.updateFreezeFrameAndShow(this.jpeg,t)):this.jpeg.length>this.size&&(G.Error(`received bigger freeze frame than advertised: ${this.jpeg.length}/${this.size}`),this.jpeg=void 0,this.receiving=!1)}}class Rn{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=()=>{G.Warning("AFK timed out, did you want to override this callback?")}}onAfkClick(){clearInterval(this.countDownTimer),(this.active||this.countdownActive)&&(this.startAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new se))}startAfkWarningTimer(){this.config.getNumericSettingValue(qe.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(He.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(He.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout(()=>this.activateAfkEvent(),1e3*this.config.getNumericSettingValue(qe.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new te({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(qe.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new ne({countDown:this.countDown})),this.config.isFlagEnabled(He.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval(()=>{this.countDown--,0===this.countDown?(this.pixelStreaming.dispatchEvent(new ie),this.onAFKTimedOutCallback(),G.Info("You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new ne({countDown:this.countDown}))},1e3)}}class kn{constructor(){this.isReceivingFreezeFrame=!1}getDataChannelInstance(){return this}createDataChannel(e,t,n){this.peerConnection=e,this.label=t,this.datachannelOptions=n,null==n&&(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;G.Info(`Data Channel (${this.label}) opened.`),this.onOpen(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}handleOnClose(e){var t;G.Info(`Data Channel (${this.label}) closed.`),this.onClose(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}handleOnMessage(e){G.Info(`Data Channel (${this.label}) message: ${e.type}`)}handleOnError(e){var t;G.Info(`Data Channel (${this.label}) error: ${e.type}`),this.onError(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}onOpen(e,t){}onClose(e,t){}onError(e,t){}}class Pn{}class In{}class xn{}class Ln{}class An{}class Dn{}class On{}class Fn{}class Nn{constructor(){this.inboundVideoStats=new In,this.inboundAudioStats=new Pn,this.candidatePairs=new Array,this.datachannelStats=new xn,this.localCandidates=new Array,this.remoteCandidates=new Array,this.outboundVideoStats=new An,this.outboundAudioStats=new An,this.remoteOutboundAudioStats=new Dn,this.remoteOutboundVideoStats=new Dn,this.sessionStats=new On,this.streamStats=new Fn,this.codecs=new Map}processStats(e){this.localCandidates=new Array,this.remoteCandidates=new Array,this.candidatePairs=new Array,e.forEach(e=>{switch(e.type){case"candidate-pair":this.handleCandidatePair(e);break;case"certificate":case"media-source":case"media-playout":case"peer-connection":case"remote-inbound-rtp":break;case"codec":this.handleCodec(e);break;case"data-channel":this.handleDataChannel(e);break;case"inbound-rtp":this.handleInboundRTP(e);break;case"local-candidate":this.handleLocalCandidate(e);break;case"outbound-rtp":this.handleLocalOutbound(e);break;case"remote-candidate":this.handleRemoteCandidate(e);break;case"remote-outbound-rtp":this.handleRemoteOutbound(e);break;case"track":this.handleTrack(e);break;case"transport":this.handleTransport(e);break;case"stream":this.handleStream(e);break;default:G.Error("unhandled Stat Type"),G.Info(e)}})}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){const t=new Ln;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){const t=new Ln;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(const 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(const t in e)this.inboundAudioStats[t]=e[t];break;default:G.Error(`Kind should be audio or video, we got ${e.kind} - that's unsupported.`)}}handleLocalOutbound(e){const t="audio"===e.kind?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){const t="audio"===e.kind?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){"track"!==e.type||"video_label"!==e.trackIdentifier&&"video"!==e.kind||(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){const t=e.id;this.codecs.set(t,e)}handleSessionStatistics(e,t,n){const s=Date.now()-e;this.sessionStats.runTime=new Date(s).toISOString().substr(11,8).toString();const i=null===t?"Not sent yet":t?"true":"false";this.sessionStats.controlsStreamInput=i,this.sessionStats.videoEncoderAvgQP=n}isNumber(e){return"number"==typeof e&&isFinite(e)}getActiveCandidatePair(){if(void 0===this.candidatePairs)return null;if(this.transportStats){const e=this.candidatePairs.find(e=>e.id===this.transportStats.selectedCandidatePairId);return void 0===e?null:e}const e=this.candidatePairs.find(e=>e.selected);return void 0===e?null:e}}i();class Un{static isVideoTransceiver(e){return this.canTransceiverReceiveVideo(e)||this.canTransceiverSendVideo(e)}static canTransceiverReceiveVideo(e){return!!e&&("sendrecv"===e.direction||"recvonly"===e.direction)&&e.receiver&&e.receiver.track&&"video"===e.receiver.track.kind}static canTransceiverSendVideo(e){return!!e&&("sendrecv"===e.direction||"sendonly"===e.direction)&&e.sender&&e.sender.track&&"video"===e.sender.track.kind}static isAudioTransceiver(e){return this.canTransceiverReceiveAudio(e)||this.canTransceiverSendAudio(e)}static canTransceiverReceiveAudio(e){return!!e&&("sendrecv"===e.direction||"recvonly"===e.direction)&&e.receiver&&e.receiver.track&&"audio"===e.receiver.track.kind}static canTransceiverSendAudio(e){return!!e&&("sendrecv"===e.direction||"sendonly"===e.direction)&&e.sender&&e.sender.track&&"audio"===e.sender.track.kind}}class Bn{static addVideoHeaderExtensionToSdp(e,t){const n=e.split("\n").filter(e=>e.startsWith("a=extmap:")).map(e=>parseInt(e.split(" ")[0].substring(9),10)).sort((e,t)=>e-t).filter((e,t,n)=>n.indexOf(e)===t),s="a=extmap:"+(n[n.length-1]+1)+" "+t+"\r\n",i=e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n");return i.shift()+i.map(e=>e.startsWith("m=video")?e+s:e).join("")}}class Vn{}class _n{}class Wn{constructor(){this.latestSenderRecvClockOffset=null}calculate(e,t){const n=new $n,s=this.getRTTMs(e);if(null!=s){n.rttMs=s;const i=this.getCaptureSource(t);if(null!=i){const t=this.calculateSenderLatency(e,i);null!==t&&(n.senderLatencyMs=t)}}return void 0!==e.inboundVideoStats.totalProcessingDelay&&void 0!==e.inboundVideoStats.framesDecoded&&(n.averageProcessingDelayMs=e.inboundVideoStats.totalProcessingDelay/e.inboundVideoStats.framesDecoded*1e3),void 0!==e.inboundVideoStats.jitterBufferDelay&&void 0!==e.inboundVideoStats.jitterBufferEmittedCount&&(n.averageJitterBufferDelayMs=e.inboundVideoStats.jitterBufferDelay/e.inboundVideoStats.jitterBufferEmittedCount*1e3),void 0!==e.inboundVideoStats.framesDecoded&&void 0!==e.inboundVideoStats.totalDecodeTime&&(n.averageDecodeLatencyMs=e.inboundVideoStats.totalDecodeTime/e.inboundVideoStats.framesDecoded*1e3),void 0!==e.inboundVideoStats.totalAssemblyTime&&void 0!==e.inboundVideoStats.framesAssembledFromMultiplePackets&&(n.averageAssemblyDelayMs=e.inboundVideoStats.totalAssemblyTime/e.inboundVideoStats.framesAssembledFromMultiplePackets*1e3),void 0!==e.inboundVideoStats.googTimingFrameInfo&&e.inboundVideoStats.googTimingFrameInfo.length>0&&(n.frameTiming=this.extractFrameTimingInfo(e.inboundVideoStats.googTimingFrameInfo)),void 0!==n.frameTiming&&void 0!==n.frameTiming.captureToSendLatencyMs&&void 0!==n.averageProcessingDelayMs&&void 0!==n.rttMs&&(n.averageE2ELatency=n.frameTiming.captureToSendLatencyMs+.5*n.rttMs+n.averageProcessingDelayMs),null!=n.senderLatencyMs&&void 0!==n.averageProcessingDelayMs&&void 0!==n.rttMs&&(n.averageE2ELatency=n.senderLatencyMs+.5*n.rttMs+n.averageProcessingDelayMs),n}extractFrameTimingInfo(e){const t=new _n,n=e.split(",");return 15===n.length&&(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){const n=t.captureTimestamp+t.senderCaptureTimeOffset;let s=this.calculateSenderReceiverClockOffset(e);if(null==s){if(null==this.latestSenderRecvClockOffset)return null;s=this.latestSenderRecvClockOffset}else this.latestSenderRecvClockOffset=s;const i=n+s-22089888e5;return t.timestamp-i}getCaptureSource(e){e=e.filter(e=>"video"===e.track.kind);for(const t of e){const e=t.getSynchronizationSources().concat(t.getContributingSources());for(const t of e)if(void 0!==t.captureTimestamp&&void 0!==t.senderCaptureTimeOffset&&void 0!==t.timestamp){const e=new Vn;return e.timestamp=t.timestamp,e.captureTimestamp=t.captureTimestamp,e.senderCaptureTimeOffset=t.senderCaptureTimeOffset,e}}return null}calculateSenderReceiverClockOffset(e){if(void 0===e.remoteOutboundVideoStats||void 0===e.remoteOutboundVideoStats.timestamp||void 0===e.remoteOutboundVideoStats.remoteTimestamp)return null;const t=e.remoteOutboundVideoStats.timestamp,n=e.remoteOutboundVideoStats.remoteTimestamp,s=this.getRTTMs(e);return void 0!==t&&void 0!==n&&null!==s?t-(n+.5*s):null}getRTTMs(e){const t=e.getActiveCandidatePair();return t&&void 0!==t.currentRoundTripTime?1e3*t.currentRoundTripTime:e.remoteOutboundVideoStats&&void 0!==e.remoteOutboundVideoStats.totalRoundTripTime&&void 0!==e.remoteOutboundVideoStats.roundTripTimeMeasurements&&e.remoteOutboundVideoStats.roundTripTimeMeasurements>0?e.remoteOutboundVideoStats.totalRoundTripTime/e.remoteOutboundVideoStats.roundTripTimeMeasurements*1e3:e.remoteOutboundAudioStats&&void 0!==e.remoteOutboundAudioStats.totalRoundTripTime&&void 0!==e.remoteOutboundAudioStats.roundTripTimeMeasurements&&e.remoteOutboundAudioStats.roundTripTimeMeasurements>0?e.remoteOutboundAudioStats.totalRoundTripTime/e.remoteOutboundAudioStats.roundTripTimeMeasurements*1e3:null}}class $n{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 Hn=function(e,t,n,s){return new(n||(n=Promise))(function(i,r){function o(e){try{l(s.next(e))}catch(e){r(e)}}function a(e){try{l(s.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}l((s=s.apply(e,t||[])).next())})};class jn{constructor(e,t,n){this.config=t,this.createPeerConnection(e,n),this.latencyCalculator=new Wn}createPeerConnection(e,t){this.config.isFlagEnabled(He.ForceTURN)&&(e.iceTransportPolicy="relay",G.Info("Forcing TURN usage by setting ICE Transport Policy in peer connection config.")),this.peerConnection=new RTCPeerConnection(e),this.peerConnection.onsignalingstatechange=e=>this.handleSignalStateChange(e),this.peerConnection.oniceconnectionstatechange=e=>this.handleIceConnectionStateChange(e),this.peerConnection.onicegatheringstatechange=e=>this.handleIceGatheringStateChange(e),this.peerConnection.ontrack=e=>this.handleOnTrack(e),this.peerConnection.onicecandidate=e=>this.handleIceCandidate(e),this.peerConnection.ondatachannel=e=>this.handleDataChannel(e),this.aggregatedStats=new Nn,this.preferredCodec=t,this.updateCodecSelection=!0}createOffer(e,t){G.Info("Create Offer");const n="localhost"===location.hostname||"127.0.0.1"===location.hostname,s="https:"===location.protocol;let i=t.isFlagEnabled(He.UseMic),r=t.isFlagEnabled(He.UseCamera);!i&&!r||n||s||(i=!1,r=!1,G.Error("Microphone and Webcam access in the browser will not work if you are not on HTTPS or localhost. Disabling mic and webcam access."),G.Error("For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(i,r).finally(()=>{var t;null===(t=this.peerConnection)||void 0===t||t.createOffer(e).then(e=>{var t;this.showTextOverlayConnecting(),e.sdp=this.mungeSDP(e.sdp,i),null===(t=this.peerConnection)||void 0===t||t.setLocalDescription(e),this.onSendWebRTCOffer(e)}).catch(()=>{this.showTextOverlaySetupFailure()})})}receiveOffer(e,t){var n;G.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,"")),null===(n=this.peerConnection)||void 0===n||n.setRemoteDescription(e).then(()=>{this.onSetRemoteDescription(e);const n="localhost"===location.hostname||"127.0.0.1"===location.hostname,s="https:"===location.protocol;let i=t.isFlagEnabled(He.UseMic),r=t.isFlagEnabled(He.UseCamera);!i&&!r||n||s||(i=!1,r=!1,G.Error("Microphone and Webcam access in the browser will not work if you are not on HTTPS or localhost. Disabling mic and webcam access."),G.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(Ge.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e)),this.setupTransceiversAsync(i,r).finally(()=>{var e;null===(e=this.peerConnection)||void 0===e||e.createAnswer().then(e=>{var t;return e.sdp=this.mungeSDP(e.sdp,i),null===(t=this.peerConnection)||void 0===t?void 0:t.setLocalDescription(e)}).then(()=>{var e;this.onSetLocalDescription(null===(e=this.peerConnection)||void 0===e?void 0:e.localDescription)}).catch(e=>{G.Error(`createAnswer() failed - ${e}`)})})})}receiveAnswer(e){var t;null===(t=this.peerConnection)||void 0===t||t.setRemoteDescription(e),this.config.setOptionSettingOptions(Ge.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e))}generateStats(){var e;null===(e=this.peerConnection)||void 0===e||e.getStats().then(e=>{this.aggregatedStats.processStats(e),this.onVideoStats(this.aggregatedStats);const t=this.latencyCalculator.calculate(this.aggregatedStats,this.peerConnection.getReceivers());if(this.onLatencyCalculated(t),this.updateCodecSelection&&this.aggregatedStats.inboundVideoStats.codecId){const e=this.aggregatedStats.codecs.get(this.aggregatedStats.inboundVideoStats.codecId);if(void 0===e)return;const t=e.mimeType.replace("video/","");let n=t;e.sdpFmtpLine&&""!==e.sdpFmtpLine.trim()&&(n=`${t} ${e.sdpFmtpLine.trim()}`);const s=this.config.getSettingOption(Ge.PreferredCodec).options;if(s.includes(n))return void this.config.setOptionSettingValue(Ge.PreferredCodec,n);const i=s.filter(e=>-1!==e.indexOf(t));if(i.length>0)return void this.config.setOptionSettingValue(Ge.PreferredCodec,i[0])}})}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\n"),s="maxaveragebitrate=510000;";return t&&(s+="sprop-maxcapturerate=48000;"),s+=this.config.isFlagEnabled(He.ForceMonoAudio)?"stereo=0;":"stereo=1;",s+="useinbandfec=1",n=n.replace("useinbandfec=1",s),this.config.isFlagEnabled(He.EnableCaptureTimeExt)&&!this.isFirefox()&&(n=Bn.addVideoHeaderExtensionToSdp(n,"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time")),n}isFirefox(){return navigator.userAgent.indexOf("Firefox")>0}handleOnIce(e){var t;G.Info("peerconnection handleOnIce"),this.config.isFlagEnabled(He.ForceTURN)&&e.candidate.indexOf("relay")<0?G.Info(`Dropping candidate because it was not TURN relay. | Type= ${e.type} | Protocol= ${e.protocol} | Address=${e.address} | Port=${e.port} |`):null===(t=this.peerConnection)||void 0===t||t.addIceCandidate(e)}handleSignalStateChange(e){var t;G.Info("signaling state change: "+(null===(t=this.peerConnection)||void 0===t?void 0:t.signalingState))}handleIceConnectionStateChange(e){var t;G.Info("ice connection state change: "+(null===(t=this.peerConnection)||void 0===t?void 0:t.iceConnectionState)),this.onIceConnectionStateChange(e)}handleIceGatheringStateChange(e){G.Info("ice gathering state change: "+JSON.stringify(e))}handleOnTrack(e){e.streams.length<1||"probator"===e.streams[0].id||("video"===e.track.kind&&(this.videoTrack=e.track),"audio"===e.track.kind&&(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){const t=new Array,n=this.parseAvailableCodecs(e),s=this.config.getSettingOption(Ge.PreferredCodec).options;for(const e of n)if(s.includes(e))t.push(e);else{const n=e.split(" ")[0];for(const e of s)if(e.includes(n)){t.push(e);break}}return t}setupTransceiversAsync(e,t){return Hn(this,void 0,void 0,function*(){var n,s,i,r,o,a,l,c;let d=!1;for(const e of null!==(s=null===(n=this.peerConnection)||void 0===n?void 0:n.getTransceivers())&&void 0!==s?s:[])if(e&&e.receiver&&e.receiver.track&&"video"===e.receiver.track.kind){d=!0;break}if(t?yield this.setupVideoSender(d):d||null===(i=this.peerConnection)||void 0===i||i.addTransceiver("video",{direction:"recvonly"}),RTCRtpReceiver.getCapabilities&&""!=this.preferredCodec)for(const e of null!==(o=null===(r=this.peerConnection)||void 0===r?void 0:r.getTransceivers())&&void 0!==o?o:[])if(e&&e.receiver&&e.receiver.track&&"video"===e.receiver.track.kind&&e.setCodecPreferences){const t=this.preferredCodec.split(" "),n={mimeType:"video/"+t[0],clockRate:9e4,sdpFmtpLine:t[1]?t[1]:""},s=[n];RTCRtpReceiver.getCapabilities("video").codecs.forEach(e=>{(e.mimeType!=n.mimeType||(null==e?void 0:e.sdpFmtpLine)!=(null==n?void 0:n.sdpFmtpLine))&&s.push(e)});for(const e of s)void 0!==(null==e?void 0:e.sdpFmtpLine)&&""!==e.sdpFmtpLine||delete e.sdpFmtpLine;e.setCodecPreferences(s)}let h=!1;for(const e of null!==(l=null===(a=this.peerConnection)||void 0===a?void 0:a.getTransceivers())&&void 0!==l?l:[])if(e&&e.receiver&&e.receiver.track&&"audio"===e.receiver.track.kind){h=!0;break}e?yield this.setupAudioSender(h):h||null===(c=this.peerConnection)||void 0===c||c.addTransceiver("audio",{direction:"recvonly"})})}setupVideoSender(e){return Hn(this,void 0,void 0,function*(){var t,n,s,i;const r=yield navigator.mediaDevices.getUserMedia({video:!0});if(r)if(e){for(const e of null!==(n=null===(t=this.peerConnection)||void 0===t?void 0:t.getTransceivers())&&void 0!==n?n:[])if(Un.canTransceiverReceiveVideo(e))for(const t of r.getTracks())"video"===t.kind&&(e.sender.replaceTrack(t),e.direction="sendrecv")}else for(const e of r.getTracks())"video"===e.kind&&(null===(s=this.peerConnection)||void 0===s||s.addTransceiver(e,{direction:"sendrecv"}));else e||null===(i=this.peerConnection)||void 0===i||i.addTransceiver("video",{direction:"recvonly"})})}setupAudioSender(e){return Hn(this,void 0,void 0,function*(){var t,n,s,i;const r=yield navigator.mediaDevices.getUserMedia({video:!1,audio:{autoGainControl:!1,channelCount:1,echoCancellation:!1,latency:0,noiseSuppression:!1,sampleRate:48e3,sampleSize:16,volume:1}});if(r)if(e){for(const e of null!==(n=null===(t=this.peerConnection)||void 0===t?void 0:t.getTransceivers())&&void 0!==n?n:[])if(Un.canTransceiverReceiveAudio(e))for(const t of r.getTracks())"audio"===t.kind&&(e.sender.replaceTrack(t),e.direction="sendrecv")}else for(const e of r.getTracks())"audio"===e.kind&&(null===(s=this.peerConnection)||void 0===s||s.addTransceiver(e,{direction:"sendrecv"}));else e||null===(i=this.peerConnection)||void 0===i||i.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"];const t=[],n=(0,i().splitSections)(e.sdp);return n.shift(),n.forEach(e=>{const{codecs:n}=(0,i().parseRtpParameters)(e),s=/(VP\d|H26\d|AV1).*/;n.forEach(e=>{const n=e.name+" "+Object.keys(e.parameters||{}).map(t=>t+"="+e.parameters[t]).join(";");if(null!==s.exec(n)){"VP9"===e.name&&(e.parameters={"profile-id":"0"});const n=e.name+" "+Object.keys(e.parameters||{}).map(t=>t+"="+e.parameters[t]).join(";");t.push(n)}})}),t}}class qn{constructor(){this.PixelStreamingSettings=new zn,this.EncoderSettings=new Qn,this.WebRTCSettings=new Kn}ueCompatible(){null!=this.WebRTCSettings.MaxFPS&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}}class zn{}class Qn{}class Kn{}class Gn{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){0==this.frameDisplayDeltaTimeMs&&(this.frameDisplayDeltaTimeMs=Math.round(e))}processFields(){null!=this.EncodeMs||null==this.PreEncodeTimeMs&&null==this.PostEncodeTimeMs||(G.Info(`Setting Encode Ms \n ${this.PostEncodeTimeMs} \n ${this.PreEncodeTimeMs}`),this.EncodeMs=this.PostEncodeTimeMs-this.PreEncodeTimeMs),null!=this.CaptureToSendMs||null==this.PreCaptureTimeMs&&null==this.PostCaptureTimeMs||(G.Info(`Setting CaptureToSendMs Ms \n ${this.PostCaptureTimeMs} \n ${this.PreCaptureTimeMs}`),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}}class Xn{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(),G.Info("Received first chunk of file"));const n=new TextDecoder("utf-16").decode(e.slice(1));G.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(),G.Info("Received first chunk of file"));const n=new TextDecoder("utf-16").decode(e.slice(1));G.Info(n),t.mimetype=n}static setContentsFromBytes(e,t){if(!t.receiving)return;t.chunks=Math.ceil(new DataView(e.slice(1,5).buffer).getInt32(0,!0)/16379);const n=e.slice(5);if(t.data.push(n),G.Info(`Received file chunk: ${t.data.length}/${t.chunks}`),t.data.length===t.chunks){t.receiving=!1,t.valid=!0,G.Info("Received complete file");const e=(new Date).getTime()-t.timestampStart,n=Math.round(16384*t.chunks/e);G.Info(`Average transfer bitrate: ${n}kb/s over ${e/1e3} seconds`)}else t.data.length>t.chunks&&(t.receiving=!1,G.Error(`Received bigger file than advertised: ${t.data.length}/${t.chunks}`))}}class Jn{constructor(){this.mimetype="",this.extension="",this.receiving=!1,this.chunks=0,this.data=[],this.valid=!1}}class Yn{}Yn.backSpace=8,Yn.shift=16,Yn.control=17,Yn.alt=18,Yn.rightShift=253,Yn.rightControl=254,Yn.rightAlt=255;const Zn=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,MetaLeft:91,MetaRight:92,OSLeft:91,OSRight:92});class es{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;const n=this.getKeycode(e);n&&229!==n&&(null===(t=this.streamMessageController.toStreamerHandlers.get("KeyDown"))||void 0===t||t([this.getKeycode(e),e.repeat?1:0]),this.activeKeys.getActiveKeys().push(n),n===Yn.backSpace&&this.handleOnKeyPress(new KeyboardEvent("keypress",{charCode:Yn.backSpace,keyCode:Yn.backSpace})),this.config.isFlagEnabled(He.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(n)&&e.preventDefault())}handleOnKeyUp(e){var t;const n=this.getKeycode(e);n&&(null===(t=this.streamMessageController.toStreamerHandlers.get("KeyUp"))||void 0===t||t([n]),this.config.isFlagEnabled(He.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(n)&&e.preventDefault())}handleOnKeyPress(e){var t;const n=this.getKeycode(e);n&&(null===(t=this.streamMessageController.toStreamerHandlers.get("KeyPress"))||void 0===t||t([n]))}getKeycode(e){if(!("keyCode"in e)){const t=e;return t.code in Zn?Zn[t.code]:(G.Warning(`Keyboard code of ${t.code} is not supported in our mapping, ignoring this key.`),null)}return e.keyCode===Yn.shift&&"ShiftRight"===e.code?Yn.rightShift:e.keyCode===Yn.control&&"ControlRight"===e.code?Yn.rightControl:e.keyCode===Yn.alt&&"AltRight"===e.code?Yn.rightAlt:"MetaLeft"===e.code||"OSLeft"===e.code?Zn.MetaLeft:"MetaRight"===e.code||"OSRight"===e.code?Zn.MetaRight:e.keyCode}isKeyCodeBrowserKey(e){return e>=112&&e<=123||9===e}}class ts{}ts.mainButton=0,ts.auxiliaryButton=1,ts.secondaryButton=2,ts.fourthButton=3,ts.fifthButton=4;class ns{}ns.primaryButton=1,ns.secondaryButton=2,ns.auxiliaryButton=4,ns.fourthButton=8,ns.fifthButton=16;class ss{constructor(e,t,n,s,i){this.streamMessageController=e,this.coordinateConverter=n,this.videoPlayer=t,this.activeKeys=s,this.config=i,this.onEnterListener=this.onMouseEnter.bind(this),this.onLeaveListener=this.onMouseLeave.bind(this)}register(){this.registerMouseEnterAndLeaveEvents()}unregister(){this.unregisterMouseEnterAndLeaveEvents()}registerMouseEnterAndLeaveEvents(){const e=this.videoPlayer.getVideoParentElement();null==e||e.addEventListener("mouseenter",this.onEnterListener),null==e||e.addEventListener("mouseleave",this.onLeaveListener)}unregisterMouseEnterAndLeaveEvents(){const e=this.videoPlayer.getVideoParentElement();null==e||e.removeEventListener("mouseenter",this.onEnterListener),null==e||e.removeEventListener("mouseleave",this.onLeaveListener)}onMouseEnter(e){var t;this.videoPlayer.isVideoReady()&&(null===(t=this.streamMessageController.toStreamerHandlers.get("MouseEnter"))||void 0===t||t(),this.pressMouseButtons(e.buttons,e.x,e.y))}onMouseLeave(e){var t;this.videoPlayer.isVideoReady()&&(null===(t=this.streamMessageController.toStreamerHandlers.get("MouseLeave"))||void 0===t||t(),this.releaseMouseButtons(e.buttons,e.x,e.y))}releaseMouseButtons(e,t,n){const s=this.coordinateConverter.translateUnsigned(t,n);e&ns.primaryButton&&this.sendMouseUp(ts.mainButton,s.x,s.y),e&ns.secondaryButton&&this.sendMouseUp(ts.secondaryButton,s.x,s.y),e&ns.auxiliaryButton&&this.sendMouseUp(ts.auxiliaryButton,s.x,s.y),e&ns.fourthButton&&this.sendMouseUp(ts.fourthButton,s.x,s.y),e&ns.fifthButton&&this.sendMouseUp(ts.fifthButton,s.x,s.y)}pressMouseButtons(e,t,n){if(!this.videoPlayer.isVideoReady())return;const s=this.coordinateConverter.translateUnsigned(t,n);e&ns.primaryButton&&this.sendMouseDown(ts.mainButton,s.x,s.y),e&ns.secondaryButton&&this.sendMouseDown(ts.secondaryButton,s.x,s.y),e&ns.auxiliaryButton&&this.sendMouseDown(ts.auxiliaryButton,s.x,s.y),e&ns.fourthButton&&this.sendMouseDown(ts.fourthButton,s.x,s.y),e&ns.fifthButton&&this.sendMouseDown(ts.fifthButton,s.x,s.y)}sendMouseDown(e,t,n){var s;null===(s=this.streamMessageController.toStreamerHandlers.get("MouseDown"))||void 0===s||s([e,t,n])}sendMouseUp(e,t,n){var s;const i=this.coordinateConverter.translateUnsigned(t,n);null===(s=this.streamMessageController.toStreamerHandlers.get("MouseUp"))||void 0===s||s([e,i.x,i.y])}}class is extends ss{constructor(e,t,n,s,i){super(e,t,n,s,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(){const 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?(G.Info("Pointer locked"),document.addEventListener("mousemove",this.onMouseMoveListener)):(G.Info("The pointer lock status is now unlocked"),document.removeEventListener("mousemove",this.onMouseMoveListener),this.activeKeys.getActiveKeys().forEach(e=>{this.streamMessageController.toStreamerHandlers.get("KeyUp")([e])}))}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;const 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);const s=this.coordinateConverter.translateSigned(e.movementX,e.movementY);this.streamMessageController.toStreamerHandlers.get("MouseMove")([this.normalizedCoord.x,this.normalizedCoord.y,s.x,s.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]),this.config.isFlagEnabled(He.MouseDoubleClickAutoRelease)&&this.streamMessageController.toStreamerHandlers.get("MouseUp")([e.button,this.normalizedCoord.x,this.normalizedCoord.y]))}}class rs extends ss{constructor(e,t,n,s,i){super(e,t,n,s,i),this.pressedButtons=new Set,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),this.pressedButtons.size>0&&(window.removeEventListener("mousemove",this.onMouseMoveListener),window.removeEventListener("mouseup",this.onMouseUpListener),this.pressedButtons.clear()),super.unregister()}startCapturing(){this.videoElementParent.removeEventListener("mousemove",this.onMouseMoveListener),this.videoElementParent.removeEventListener("mouseup",this.onMouseUpListener),window.addEventListener("mousemove",this.onMouseMoveListener),window.addEventListener("mouseup",this.onMouseUpListener)}stopCapturing(){window.removeEventListener("mousemove",this.onMouseMoveListener),window.removeEventListener("mouseup",this.onMouseUpListener),this.videoElementParent.addEventListener("mousemove",this.onMouseMoveListener),this.videoElementParent.addEventListener("mouseup",this.onMouseUpListener)}offsetFromVideo(e){if(e.currentTarget===this.videoElementParent)return{x:e.offsetX,y:e.offsetY};const t=this.videoElementParent.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}onMouseDown(e){if(!this.videoPlayer.isVideoReady())return;const t=this.offsetFromVideo(e),n=this.coordinateConverter.translateUnsigned(t.x,t.y);this.streamMessageController.toStreamerHandlers.get("MouseDown")([e.button,n.x,n.y]),e.preventDefault(),0===this.pressedButtons.size&&this.startCapturing(),this.pressedButtons.add(e.button)}onMouseUp(e){if(!this.videoPlayer.isVideoReady())return;const t=this.offsetFromVideo(e),n=this.coordinateConverter.translateUnsigned(t.x,t.y);this.streamMessageController.toStreamerHandlers.get("MouseUp")([e.button,n.x,n.y]),e.preventDefault(),this.pressedButtons.delete(e.button),0===this.pressedButtons.size&&this.stopCapturing()}onContextMenu(e){this.videoPlayer.isVideoReady()&&e.preventDefault()}onMouseMove(e){if(!this.videoPlayer.isVideoReady())return;const t=this.offsetFromVideo(e),n=this.coordinateConverter.translateUnsigned(t.x,t.y),s=this.coordinateConverter.translateSigned(e.movementX,e.movementY);this.streamMessageController.toStreamerHandlers.get("MouseMove")([n.x,n.y,s.x,s.y]),e.currentTarget===this.videoElementParent&&e.preventDefault()}onMouseWheel(e){if(!this.videoPlayer.isVideoReady())return;const 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;const t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY);this.streamMessageController.toStreamerHandlers.get("MouseDouble")([e.button,t.x,t.y]),this.config.isFlagEnabled(He.MouseDoubleClickAutoRelease)&&this.streamMessageController.toStreamerHandlers.get("MouseUp")([e.button,t.x,t.y])}}class os{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){const t=this.fingers.pop();void 0===t&&G.Info("exhausted touch identifiers"),this.fingerIds.set(e.identifier,t)}forgetTouch(e){this.fingers.push(this.fingerIds.get(e.identifier)),this.fingers.sort(function(e,t){return t-e}),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;const n=this.videoPlayer.getVideoParentElement().getBoundingClientRect(),s=this.streamMessageController.toStreamerHandlers;for(let i=0;i<t.length;i++){const r=1,o=t[i],a=o.clientX-n.left,l=o.clientY-n.top;G.Info(`F${this.fingerIds.get(o.identifier)}=(${a}, ${l})`);const c=this.coordinateConverter.translateUnsigned(a,l);switch(e){case"TouchStart":s.get("TouchStart")([r,c.x,c.y,this.fingerIds.get(o.identifier),this.maxByteValue*(o.force>0?o.force:1),c.inRange?1:0]);break;case"TouchEnd":s.get("TouchEnd")([r,c.x,c.y,this.fingerIds.get(o.identifier),this.maxByteValue*o.force,c.inRange?1:0]);break;case"TouchMove":s.get("TouchMove")([r,c.x,c.y,this.fingerIds.get(o.identifier),this.maxByteValue*(o.force>0?o.force:1),c.inRange?1:0])}}}}class as{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(null==this.fakeTouchFinger){const t=e.changedTouches[0];this.fakeTouchFinger={id:t.identifier,x:t.clientX-this.videoElementParentClientRect.left,y:t.clientY-this.videoElementParentClientRect.top};const n=this.videoPlayer.getVideoParentElement(),s=new MouseEvent("mouseenter",t);n.dispatchEvent(s);const i=this.coordinateConverter.translateUnsigned(this.fakeTouchFinger.x,this.fakeTouchFinger.y);this.streamMessageController.toStreamerHandlers.get("MouseDown")([ts.mainButton,i.x,i.y])}e.preventDefault()}}onTouchEnd(e){if(!this.videoPlayer.isVideoReady()||null==this.fakeTouchFinger)return;const t=this.videoPlayer.getVideoParentElement(),n=this.streamMessageController.toStreamerHandlers;for(let s=0;s<e.changedTouches.length;s++){const i=e.changedTouches[s];if(i.identifier===this.fakeTouchFinger.id){const e=i.clientX-this.videoElementParentClientRect.left,s=i.clientY-this.videoElementParentClientRect.top,r=this.coordinateConverter.translateUnsigned(e,s);n.get("MouseUp")([ts.mainButton,r.x,r.y]);const o=new MouseEvent("mouseleave",i);t.dispatchEvent(o),this.fakeTouchFinger=null;break}}e.preventDefault()}onTouchMove(e){if(!this.videoPlayer.isVideoReady()||null==this.fakeTouchFinger)return;const t=this.streamMessageController.toStreamerHandlers;for(let n=0;n<e.touches.length;n++){const s=e.touches[n];if(s.identifier===this.fakeTouchFinger.id){const e=s.clientX-this.videoElementParentClientRect.left,n=s.clientY-this.videoElementParentClientRect.top,i=this.coordinateConverter.translateUnsigned(e,n),r=this.coordinateConverter.translateSigned(e-this.fakeTouchFinger.x,n-this.fakeTouchFinger.y);t.get("MouseMove")([i.x,i.y,r.x,r.y]),this.fakeTouchFinger.x=e,this.fakeTouchFinger.y=n;break}}e.preventDefault()}}function ls(e){return JSON.parse(JSON.stringify({buttons:e.buttons.map(e=>JSON.parse(JSON.stringify({pressed:e.pressed,touched:e.touched,value:e.value}))),axes:e.axes}))}var cs,ds,hs;!function(e){e[e.RightClusterBottomButton=0]="RightClusterBottomButton",e[e.RightClusterRightButton=1]="RightClusterRightButton",e[e.RightClusterLeftButton=2]="RightClusterLeftButton",e[e.RightClusterTopButton=3]="RightClusterTopButton",e[e.LeftShoulder=4]="LeftShoulder",e[e.RightShoulder=5]="RightShoulder",e[e.LeftTrigger=6]="LeftTrigger",e[e.RightTrigger=7]="RightTrigger",e[e.SelectOrBack=8]="SelectOrBack",e[e.StartOrForward=9]="StartOrForward",e[e.LeftAnalogPress=10]="LeftAnalogPress",e[e.RightAnalogPress=11]="RightAnalogPress",e[e.LeftClusterTopButton=12]="LeftClusterTopButton",e[e.LeftClusterBottomButton=13]="LeftClusterBottomButton",e[e.LeftClusterLeftButton=14]="LeftClusterLeftButton",e[e.LeftClusterRightButton=15]="LeftClusterRightButton",e[e.CentreButton=16]="CentreButton",e[e.LeftStickHorizontal=0]="LeftStickHorizontal",e[e.LeftStickVertical=1]="LeftStickVertical",e[e.RightStickHorizontal=2]="RightStickHorizontal",e[e.RightStickVertical=3]="RightStickVertical"}(cs||(cs={}));class us{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);const 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(const e of navigator.getGamepads())e&&this.onGamepadConnected(new GamepadEvent("gamepadconnected",{gamepad:e}))}unregister(){window.removeEventListener("gamepadconnected",this.onGamepadConnectedListener),window.removeEventListener("gamepaddisconnected",this.onGamepadDisconnectedListener),window.removeEventListener("webkitgamepadconnected",this.onGamepadConnectedListener),window.removeEventListener("webkitgamepaddisconnected",this.onGamepadDisconnectedListener);for(const e of this.controllers)e&&void 0!==e.id&&this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([e.id]);this.controllers=[]}onGamepadResponseReceived(e){for(const t of this.controllers)if(t&&void 0===t.id){t.id=e;break}}onGamepadConnected(e){const t=e.gamepad,n={currentState:ls(t),prevState:ls(t),id:void 0};this.controllers[t.index]=n,window.requestAnimationFrame(()=>this.updateStatus()),this.streamMessageController.toStreamerHandlers.get("GamepadConnected")()}onGamepadDisconnected(e){const t=e.gamepad,n=this.controllers[t.index];this.controllers=this.controllers.filter((e,n)=>n!==t.index),void 0!==n.id&&this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([n.id])}scanGamepads(){const e=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[];for(let t=0;t<e.length;t++)e[t]&&void 0!==this.controllers[e[t].index]&&(this.controllers[e[t].index].currentState=e[t])}updateStatus(){this.scanGamepads();const e=this.streamMessageController.toStreamerHandlers;for(const t of this.controllers){if(!t)continue;const n=void 0===t.id?this.controllers.indexOf(t):t.id,s=t.currentState;for(let s=0;s<t.currentState.buttons.length;s++){const i=t.currentState.buttons[s],r=t.prevState.buttons[s];i.pressed?s===cs.LeftTrigger?e.get("GamepadAnalog")([n,5,i.value]):s===cs.RightTrigger?e.get("GamepadAnalog")([n,6,i.value]):e.get("GamepadButtonPressed")([n,s,r.pressed?1:0]):!i.pressed&&r.pressed&&(s===cs.LeftTrigger?e.get("GamepadAnalog")([n,5,0]):s===cs.RightTrigger?e.get("GamepadAnalog")([n,6,0]):e.get("GamepadButtonReleased")([n,s,0]))}for(let t=0;t<s.axes.length;t+=2){const i=parseFloat(s.axes[t].toFixed(4)),r=-parseFloat(s.axes[t+1].toFixed(4));e.get("GamepadAnalog")([n,t+1,i]),e.get("GamepadAnalog")([n,t+2,r])}const i=this.controllers.indexOf(t);this.controllers[i].prevState=ls(s)}this.controllers.length>0&&this.requestAnimationFrame(()=>this.updateStatus())}onBeforeUnload(e){for(const e of this.controllers)e&&void 0!==e.id&&this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([e.id])}}class gs{constructor(e,t,n){this.activeKeys=new ps,this.toStreamerMessagesProvider=e,this.videoElementProvider=t,this.coordinateConverter=n}registerKeyBoard(e){G.Info("Register Keyboard Events");const t=new es(this.toStreamerMessagesProvider,e,this.activeKeys);return t.register(),t}registerMouse(e,t){let n;return G.Info("Register Mouse Events"),n=e==Ye.HoveringMouse?new rs(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys,t):new is(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys,t),n.register(),n}registerTouch(e){let t;return G.Info("Registering Touch"),t=e?new as(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter):new os(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter),t.register(),t}registerGamePad(){G.Info("Register Game Pad");const e=new us(this.toStreamerMessagesProvider);return e.register(),e}}class ps{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class ms{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=()=>{G.Warning("Resolution changed, restyling player, did you forget to override this function?")},this.onMatchViewportResolutionCallback=()=>{G.Warning("Resolution changed and match viewport resolution is turned on, did you forget to override this function?")},this.videoElement.onclick=()=>{void 0!==this.audioElement&&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(He.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(He.AutoPlayVideo),this.videoElement.play()}isPaused(){return this.videoElement.paused}isVideoReady(){return void 0!==this.videoElement.readyState&&this.videoElement.readyState>0}hasVideoSource(){return void 0!==this.videoElement.srcObject&&null!==this.videoElement.srcObject}getVideoElement(){return this.videoElement}getVideoParentElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0}setVideoEnabled(e){this.videoElement.srcObject.getTracks().forEach(t=>t.enabled=e)}onVideoInitialized(){}onOrientationChange(){clearTimeout(this.orientationChangeTimeout),this.orientationChangeTimeout=window.setTimeout(()=>{this.resizePlayerStyle()},500)}resizePlayerStyle(){const e=this.getVideoParentElement();e&&(this.updateVideoStreamSize(),e.classList.contains("fixed-size")||this.resizePlayerStyleToFillParentElement(),this.onResizePlayerCallback())}resizePlayerStyleToFillParentElement(){this.getVideoParentElement().setAttribute("style","top: 0px; left: 0px; width: 100%; height: 100%; cursor: default;")}updateVideoStreamSize(){if(this.config.isFlagEnabled(He.MatchViewportResolution))if((new Date).getTime()-this.lastTimeResized>300){const e=this.getVideoParentElement();if(!e)return;const t=this.config.hasNumericSetting(qe.ViewportResScale)?this.config.getNumericSettingValue(qe.ViewportResScale):1,n=Math.round(e.clientWidth*t),s=Math.round(e.clientHeight*t);(n>ms.maxEncoderDimension||s>ms.maxEncoderDimension)&&G.Warning(`Requested stream resolution (${n}x${s}) exceeds the common H.264 encoder limit of ${ms.maxEncoderDimension}x${ms.maxEncoderDimension}; encoding may fail. Lower ViewportResScale or disable MatchViewportResolution.`),this.onMatchViewportResolutionCallback(n,s),this.lastTimeResized=(new Date).getTime()}else G.Info("Resizing too often - skipping"),clearTimeout(this.resizeTimeoutHandle),this.resizeTimeoutHandle=window.setTimeout(()=>this.updateVideoStreamSize(),100)}}ms.maxEncoderDimension=4096;class fs{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 ds.ToStreamer:this.toStreamerHandlers.set(t,n);break;case ds.FromStreamer:this.fromStreamerHandlers.set(t,n);break;default:G.Info(`Unknown message direction ${e}`)}}}!function(e){e[e.ToStreamer=0]="ToStreamer",e[e.FromStreamer=1]="FromStreamer"}(ds||(ds={}));class ys{constructor(){this.responseEventListeners=new Map}addResponseEventListener(e,t){this.responseEventListeners.set(e,t)}removeResponseEventListener(e){this.responseEventListeners.delete(e)}onResponse(e){G.Info("DataChannelReceiveMessageType.Response");const t=new TextDecoder("utf-16").decode(e.slice(1));G.Info(t),this.responseEventListeners.forEach(e=>{e(t)})}}class vs{constructor(e,t){this.dataChannelSender=e,this.toStreamerMessagesMapProvider=t}sendMessageToStreamer(e,t){void 0===t&&(t=[]);const n=this.toStreamerMessagesMapProvider.toStreamerMessages.get(e);if(void 0===n)return void G.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`);if(n.structure&&t&&n.structure.length!==t.length)return void G.Error(`Provided message data doesn't match expected layout. Expected [ ${n.structure.map(e=>{switch(e){case"uint8":case"uint16":case"int16":case"float":case"double":default:return"number";case"string":return"string"}}).toString()} ] but received [ ${t.map(e=>typeof e).toString()} ]`);let s=0;t.forEach((e,t)=>{switch(n.structure[t]){case"uint8":s+=1;break;case"uint16":case"int16":s+=2;break;case"float":s+=4;break;case"double":s+=8;break;case"string":s+=2,s+=2*e.length}});const i=new DataView(new ArrayBuffer(s+1));i.setUint8(0,n.id);let r=1;t.forEach((e,t)=>{switch(n.structure[t]){case"uint8":i.setUint8(r,e),r+=1;break;case"uint16":i.setUint16(r,e,!0),r+=2;break;case"int16":i.setInt16(r,e,!0),r+=2;break;case"float":i.setFloat32(r,e,!0),r+=4;break;case"double":i.setFloat64(r,e,!0),r+=8;break;case"string":i.setUint16(r,e.length,!0),r+=2;for(let t=0;t<e.length;t++)i.setUint16(r,e.charCodeAt(t),!0),r+=2}}),this.dataChannelSender.canSend()?this.dataChannelSender.sendData(i.buffer):G.Info(`Data channel cannot send yet, skipping sending message: ${e} - ${new Uint8Array(i.buffer)}`)}}class Ss{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")}}class bs{constructor(e){this.dataChannelProvider=e}canSend(){return void 0!==this.dataChannelProvider.getDataChannelInstance().dataChannel&&"open"===this.dataChannelProvider.getDataChannelInstance().dataChannel.readyState}sendData(e){const t=this.dataChannelProvider.getDataChannelInstance();"open"===t.dataChannel.readyState?(t.dataChannel.send(e),G.Info(`Message Sent: ${new Uint8Array(e)}`),this.resetAfkWarningTimerOnDataSend()):G.Error(`Message Failed: ${new Uint8Array(e)}`)}resetAfkWarningTimerOnDataSend(){}}class ws{reconfigure(e,t){const n=e.height/e.width,s=t.height/t.width;this.playerIsLarger=n>s,this.playerSize=e,this.ratio=this.playerIsLarger?n/s:s/n}translateUnsigned(e,t){const n=this.playerIsLarger?e/this.playerSize.width:this.ratio*(e/this.playerSize.width-.5)+.5,s=this.playerIsLarger?this.ratio*(t/this.playerSize.height-.5)+.5:t/this.playerSize.height;return n<0||n>1||s<0||s>1?{inRange:!1,x:65535,y:65535}:{inRange:!0,x:65536*n,y:65536*s}}translateSigned(e,t){return{x:32767*(this.playerIsLarger?e/(.5*this.playerSize.width):this.ratio*e/(.5*this.playerSize.width)),y:32767*(this.playerIsLarger?this.ratio*t/(.5*this.playerSize.height):t/(.5*this.playerSize.height))}}untranslateUnsigned(e,t){const n=this.playerIsLarger?e/65536:(e/65536-.5)/this.ratio+.5,s=this.playerIsLarger?(t/65536-.5)/this.ratio+.5:t/65536;return{x:n*this.playerSize.width,y:s*this.playerSize.height}}}class Cs{constructor(e){this._urlParams={};const t=new URLSearchParams(e);for(const[e,n]of t)this._urlParams[e.toLowerCase()]=n}has(e){return e.toLowerCase()in this._urlParams}get(e){return this.has(e)?this._urlParams[e.toLowerCase()]:null}}class Ms{constructor(e,t){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=e,this.pixelStreaming=t,this.responseController=new ys,this.file=new Jn,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new Rn(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity.",!1)},this.freezeFrameController=new En(this.pixelStreaming.videoElementParent),this.videoPlayer=new ms(this.pixelStreaming.videoElementParent,this.config),this.videoPlayer.onVideoInitialized=()=>this.handleVideoInitialized(),this.videoPlayer.onMatchViewportResolutionCallback=(e,t)=>{const n={"Resolution.Width":e,"Resolution.Height":t};this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(n)])},this.videoPlayer.onResizePlayerCallback=()=>{this.setUpMouseAndFreezeFrame()},this.streamController=new Mn(this.videoPlayer),this.coordinateConverter=new ws,this.sendrecvDataChannelController=new kn,this.recvDataChannelController=new kn,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new bs(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new fs,this.transport=new st(e.webSocketProtocols),this.protocol=new it(this.transport),this.protocol.addListener(sn.typeName,e=>this.handleOnConfigMessage(e)),this.protocol.addListener(pn.typeName,e=>this.handlePingMessage(e)),this.protocol.addListener(an.typeName,e=>this.handleStreamerListMessage(e)),this.protocol.addListener(cn.typeName,e=>this.handleSubscribeFailedMessage(e)),this.protocol.addListener(rn.typeName,e=>this.handleStreamerIDChangedMessage(e)),this.protocol.addListener(bn.typeName,e=>{const t=e;this.pixelStreaming._onPlayerCount(t.count)}),this.protocol.addListener(hn.typeName,e=>this.handleWebRtcAnswer(e)),this.protocol.addListener(dn.typeName,e=>this.handleWebRtcOffer(e)),this.protocol.addListener(vn.typeName,e=>this.handleWebRtcSFUPeerDatachannels(e)),this.protocol.addListener(gn.typeName,e=>{const t=e;this.handleIceCandidate(t.candidate)}),this.protocol.transport.addListener("open",()=>{if(!this.config.isFlagEnabled(He.BrowserSendOffer)){const e=wn(on);this.protocol.sendMessage(e)}this.reconnectAttempt=0,this.isReconnecting=!1}),this.protocol.transport.addListener("error",()=>{G.Error("Got a transport error.")}),this.protocol.transport.addListener("close",e=>{const t=this.config.getNumericSettingValue(qe.MaxReconnectAttempts),n=this.reconnectAttempt<t,s=(this.forceReconnect||this.enableAutoReconnect&&t>0&&n)&&1001!=e.code,i=!s,r=this.disconnectMessage?this.disconnectMessage:e.reason;this.forceReconnect=!1,this.config.getSettingOption(Ge.PreferredCodec).options=$e.getSupportedVideoCodecs(),this.pixelStreaming._onDisconnect(r,i),this.afkController.stopAfkWarningTimer(),this.statsTimerHandle&&window.clearInterval(this.statsTimerHandle),this.setVideoEncoderAvgQP(0),this.setTouchInputEnabled(!1),this.setMouseInputEnabled(!1),this.setKeyboardInputEnabled(!1),this.setGamePadInputEnabled(!1),s&&setTimeout(()=>{this.reconnectAttempt++,this.doReconnect(e.reason)},2e3)}),this.sendMessageController=new vs(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new Ss(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new gs(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(Ge.StreamerId,e=>{if(void 0===e||""===e)return;this.peerConnectionController.peerConnection.close(),this.peerConnectionController.createPeerConnection(this.peerConfig,this.preferredCodec),this.subscribedStream=e;const t=wn(ln,{streamerId:e});this.protocol.sendMessage(t)}),this.config._addOnOptionSettingChangedListener(Ge.PreferredQuality,e=>{if(void 0===e||""===e)return;let t;if(this.isUsingSVC)t=wn(fn,{spatialLayer:+e[1]-1,temporalLayer:+e[3]-1});else{const n=this.config.getSettingOption(Ge.PreferredQuality).options.indexOf(e);t=wn(fn,{spatialLayer:n,temporalLayer:0})}this.protocol.sendMessage(t)}),this.setVideoEncoderAvgQP(-1),this.signallingUrlBuilder=()=>this.config.getTextSettingValue(Qe.SignallingServerUrl)}destroyVideoPlayer(){this.videoPlayer.destroy()}handleOnMessage(e){const t=new Uint8Array(e.data);G.Info("Message incoming:"+t);const n=this.streamMessageController.fromStreamerMessages.get(t[0]);this.streamMessageController.fromStreamerHandlers.get(n)(e.data)}registerMessageHandlers(){this.streamMessageController.registerMessageHandler(ds.FromStreamer,"QualityControlOwnership",e=>this.onQualityControlOwnership(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"Response",e=>this.responseController.onResponse(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"Command",e=>{this.onCommand(e)}),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"FreezeFrame",e=>this.onFreezeFrameMessage(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"UnfreezeFrame",()=>this.invalidateFreezeFrameAndEnableVideo()),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"VideoEncoderAvgQP",e=>this.handleVideoEncoderAvgQP(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"LatencyTest",e=>this.handleLatencyTestResult(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"DataChannelLatencyTest",e=>this.handleDataChannelLatencyTestResponse(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"InitialSettings",e=>this.handleInitialSettings(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"FileExtension",e=>this.onFileExtension(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"FileMimeType",e=>this.onFileMimeType(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"FileContents",e=>this.onFileContents(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"TestEcho",()=>{}),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"InputControlOwnership",e=>this.onInputControlOwnership(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"GamepadResponse",e=>this.onGamepadResponse(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"Multiplexed",()=>{}),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"Protocol",e=>this.onProtocolMessage(e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"IFrameRequest",()=>this.sendMessageController.sendMessageToStreamer("IFrameRequest")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"RequestQualityControl",()=>this.sendMessageController.sendMessageToStreamer("RequestQualityControl")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"FpsRequest",()=>this.sendMessageController.sendMessageToStreamer("FpsRequest")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"AverageBitrateRequest",()=>this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"StartStreaming",()=>this.sendMessageController.sendMessageToStreamer("StartStreaming")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"StopStreaming",()=>this.sendMessageController.sendMessageToStreamer("StopStreaming")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"LatencyTest",e=>this.sendMessageController.sendMessageToStreamer("LatencyTest",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"RequestInitialSettings",()=>this.sendMessageController.sendMessageToStreamer("RequestInitialSettings")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"TestEcho",()=>{}),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"UIInteraction",e=>this.sendMessageController.sendMessageToStreamer("UIInteraction",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"Command",e=>this.sendMessageController.sendMessageToStreamer("Command",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"TextboxEntry",e=>this.sendMessageController.sendMessageToStreamer("TextboxEntry",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"KeyDown",e=>this.sendMessageController.sendMessageToStreamer("KeyDown",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"KeyUp",e=>this.sendMessageController.sendMessageToStreamer("KeyUp",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"KeyPress",e=>this.sendMessageController.sendMessageToStreamer("KeyPress",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"MouseEnter",e=>this.sendMessageController.sendMessageToStreamer("MouseEnter",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"MouseLeave",e=>this.sendMessageController.sendMessageToStreamer("MouseLeave",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"MouseDown",e=>this.sendMessageController.sendMessageToStreamer("MouseDown",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"MouseUp",e=>this.sendMessageController.sendMessageToStreamer("MouseUp",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"MouseMove",e=>this.sendMessageController.sendMessageToStreamer("MouseMove",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"MouseWheel",e=>this.sendMessageController.sendMessageToStreamer("MouseWheel",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"MouseDouble",e=>this.sendMessageController.sendMessageToStreamer("MouseDouble",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"TouchStart",e=>this.sendMessageController.sendMessageToStreamer("TouchStart",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"TouchEnd",e=>this.sendMessageController.sendMessageToStreamer("TouchEnd",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"TouchMove",e=>this.sendMessageController.sendMessageToStreamer("TouchMove",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"GamepadConnected",()=>this.sendMessageController.sendMessageToStreamer("GamepadConnected")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"GamepadButtonPressed",e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonPressed",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"GamepadButtonReleased",e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonReleased",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"GamepadAnalog",e=>this.sendMessageController.sendMessageToStreamer("GamepadAnalog",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"GamepadDisconnected",e=>this.sendMessageController.sendMessageToStreamer("GamepadDisconnected",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XREyeViews",e=>this.sendMessageController.sendMessageToStreamer("XREyeViews",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRHMDTransform",e=>this.sendMessageController.sendMessageToStreamer("XRHMDTransform",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRControllerTransform",e=>this.sendMessageController.sendMessageToStreamer("XRControllerTransform",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRSystem",e=>this.sendMessageController.sendMessageToStreamer("XRSystem",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRButtonTouched",e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouched",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRButtonTouchReleased",e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouchReleased",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRButtonPressed",e=>this.sendMessageController.sendMessageToStreamer("XRButtonPressed",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRButtonReleased",e=>this.sendMessageController.sendMessageToStreamer("XRButtonReleased",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRAnalog",e=>this.sendMessageController.sendMessageToStreamer("XRAnalog",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"ChannelRelayStatus",()=>{}),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"Multiplexed",()=>{})}onCommand(e){G.Info("DataChannelReceiveMessageType.Command");const t=new TextDecoder("utf-16").decode(e.slice(1));G.Info("Data Channel Command: "+t);const n=JSON.parse(t);"onScreenKeyboard"===n.command&&this.handleOnScreenKeyboardCommand(n)}handleOnScreenKeyboardCommand(e){var t,n,s,i;const r={showOnScreenKeyboard:null===(t=e.showOnScreenKeyboard)||void 0===t||t,x:null!==(n=e.x)&&void 0!==n?n:0,y:null!==(s=e.y)&&void 0!==s?s:0,contents:null!==(i=e.contents)&&void 0!==i?i:""};this.pixelStreaming.dispatchEvent(new Ae(r))}onProtocolMessage(e){try{const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);Object.prototype.hasOwnProperty.call(n,"Direction")||G.Error("Malformed protocol received. Ensure the protocol message contains a direction");const s=n.Direction;delete n.Direction,G.Info(`Received new ${s==ds.FromStreamer?"FromStreamer":"ToStreamer"} protocol. Updating existing protocol...`),Object.keys(n).forEach(e=>{const t=n[e];switch(s){case ds.ToStreamer:if(!Object.prototype.hasOwnProperty.call(t,"id"))return void G.Error(`ToStreamer->${e} protocol definition was malformed as it didn't contain at least an id\n\n Definition was: ${JSON.stringify(t,null,2)}`);if("UIInteraction"===e||"Command"===e||"LatencyTest"===e)return;this.streamMessageController.toStreamerHandlers.get(e)?this.streamMessageController.toStreamerMessages.set(e,t):G.Error(`There was no registered handler for "${e}" - try adding one using registerMessageHandler(MessageDirection.ToStreamer, "${e}", myHandler)`);break;case ds.FromStreamer:if(!Object.prototype.hasOwnProperty.call(t,"id"))return void G.Error(`FromStreamer->${e} protocol definition was malformed as it didn't contain at least an id\n\n Definition was: ${JSON.stringify(t,null,2)}`);this.streamMessageController.fromStreamerHandlers.get(e)?this.streamMessageController.fromStreamerMessages.set(t.id,e):G.Error(`There was no registered handler for "${t}" - try adding one using registerMessageHandler(MessageDirection.FromStreamer, "${e}", myHandler)`);break;default:G.Error(`Unknown direction: ${s}`)}}),this.toStreamerMessagesController.SendRequestInitialSettings(),this.toStreamerMessagesController.SendRequestQualityControl()}catch(e){G.Info(e)}}onInputControlOwnership(e){const t=new Uint8Array(e);G.Info("DataChannelReceiveMessageType.InputControlOwnership");const n=new Boolean(t[1]).valueOf();G.Info(`Received input controller message - will your input control the stream: ${n}`),this.pixelStreaming._onInputControlOwnership(n)}onGamepadResponse(e){const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);this.gamePadController.onGamepadResponseReceived(n.controllerId)}onAfkTriggered(){this.afkController.onAfkClick(),this.videoPlayer.isPaused()&&this.videoPlayer.hasVideoSource()&&this.playStream()}setAfkEnabled(e){e?this.onAfkTriggered():this.afkController.stopAfkWarningTimer()}tryReconnect(e){this.forceReconnect=!0,this.doReconnect(e)}doReconnect(e){this.protocol?(this.isReconnecting=!0,this.protocol.isConnected()?(this.forceReconnect||(this.disconnectMessage=`${e} Reconnecting.`),this.closeSignalingServer(e,!0)):(this.pixelStreaming._onWebRtcAutoConnect(),this.connectToSignallingServer())):G.Info("This player has no protocol connection.")}loadFreezeFrameOrShowPlayOverlay(){this.pixelStreaming.dispatchEvent(new Ee({shouldShowPlayOverlay:this.shouldShowPlayOverlay,isValid:this.freezeFrameController.valid,jpegData:this.freezeFrameController.jpeg})),!0===this.shouldShowPlayOverlay?(G.Info("showing play overlay"),this.resizePlayerStyle()):(G.Info("showing freeze frame"),this.freezeFrameController.showFreezeFrame()),setTimeout(()=>{this.videoPlayer.setVideoEnabled(!1)},this.freezeFrameController.freezeFrameDelay)}onFreezeFrameMessage(e){G.Info("DataChannelReceiveMessageType.FreezeFrame");const t=new Uint8Array(e);this.freezeFrameController.processFreezeFrameMessage(t,()=>this.loadFreezeFrameOrShowPlayOverlay())}invalidateFreezeFrameAndEnableVideo(){G.Info("DataChannelReceiveMessageType.FreezeFrame"),setTimeout(()=>{this.pixelStreaming.dispatchEvent(new Re),this.freezeFrameController.hideFreezeFrame()},this.freezeFrameController.freezeFrameDelay),this.videoPlayer.getVideoElement()&&this.videoPlayer.setVideoEnabled(!0)}onFileExtension(e){const t=new Uint8Array(e);Xn.setExtensionFromBytes(t,this.file)}onFileMimeType(e){const t=new Uint8Array(e);Xn.setMimeTypeFromBytes(t,this.file)}onFileContents(e){const t=new Uint8Array(e);Xn.setContentsFromBytes(t,this.file)}playStream(){if(!this.videoPlayer.getVideoElement()){const e="Could not play video stream because the video player was not initialized correctly.";return this.pixelStreaming.dispatchEvent(new Ce({message:e})),G.Error(e),void this.closeSignalingServer("Stream not initialized correctly",!1)}if(this.videoPlayer.hasVideoSource()){if(this.setTouchInputEnabled(this.config.isFlagEnabled(He.TouchInput)),this.pixelStreaming.dispatchEvent(new Me),this.streamController.audioElement.srcObject){const e=this.config.isFlagEnabled(He.StartVideoMuted);this.streamController.audioElement.muted=e,e?this.playVideo():this.streamController.audioElement.play().then(()=>{this.playVideo()}).catch(e=>{G.Info(e),G.Info("Browser does not support autoplaying video without interaction - to resolve this we are going to show the play button overlay."),this.pixelStreaming.dispatchEvent(new Te({reason:e}))})}else this.playVideo();this.shouldShowPlayOverlay=!1,this.freezeFrameController.showFreezeFrame()}else G.Warning("Cannot play stream, the video element has no srcObject to play.")}playVideo(){this.videoPlayer.play().catch(e=>{this.streamController.audioElement.srcObject&&this.streamController.audioElement.pause(),G.Info(e),G.Info("Browser does not support autoplaying video without interaction - to resolve this we are going to show the play button overlay."),this.pixelStreaming.dispatchEvent(new Te({reason:e}))})}autoPlayVideoOrSetUpPlayOverlay(){this.config.isFlagEnabled(He.AutoPlayVideo)&&this.playStream(),this.resizePlayerStyle()}connectToSignallingServer(){this.locallyClosed=!1,this.enableAutoReconnect=!0,this.disconnectMessage=null;const e=this.signallingUrlBuilder();this.protocol.connect(e);const t=this.config.getNumericSettingValue(qe.KeepaliveDelay);t>0&&(this.keepalive=new Cn(this.protocol,t),this.keepalive.onTimeout=()=>{G.Error("Protocol timeout"),this.protocol.disconnect()})}startSession(e){if(this.peerConfig=e,this.config.isFlagEnabled(He.ForceTURN)&&!this.checkTurnServerAvailability(e))return G.Info("No turn server was found in the Peer Connection Options. TURN cannot be forced, closing connection. Please use STUN instead"),void this.closeSignalingServer("TURN cannot be forced, closing connection. Please use STUN instead.",!1);this.peerConnectionController=new jn(this.peerConfig,this.config,this.preferredCodec),this.peerConnectionController.onVideoStats=e=>{this.handleVideoStats(e)},this.peerConnectionController.onLatencyCalculated=e=>{this.pixelStreaming._onLatencyCalculated(e)},this.peerConnectionController.onSendWebRTCOffer=e=>{this.handleSendWebRTCOffer(e)},this.peerConnectionController.onSetLocalDescription=e=>{"offer"===e.type?this.handleSendWebRTCOffer(e):"answer"===e.type?this.handleSendWebRTCAnswer(e):G.Error(`PeerConnectionController onSetLocalDescription was called with unexpected type ${e.type}`)},this.peerConnectionController.onSetRemoteDescription=e=>{"offer"===e.type?this.pixelStreaming._onWebRtcSdpOffer(e):"answer"===e.type?this.pixelStreaming._onWebRtcSdpAnswer(e):G.Error(`PeerConnectionController onSetRemoteDescription was called with unexpected type ${e.type}`)},this.peerConnectionController.onPeerIceCandidate=e=>this.handleSendIceCandidate(e),this.peerConnectionController.onDataChannel=e=>this.handleDataChannel(e),this.peerConnectionController.showTextOverlayConnecting=()=>this.pixelStreaming._onWebRtcConnecting(),this.peerConnectionController.showTextOverlaySetupFailure=()=>this.pixelStreaming._onWebRtcFailed();let t=!1;this.peerConnectionController.onIceConnectionStateChange=()=>{!t&&["connected","completed"].includes(this.peerConnectionController.peerConnection.iceConnectionState)&&(this.pixelStreaming._onWebRtcConnected(),t=!0)},this.peerConnectionController.onTrack=e=>this.streamController.handleOnTrack(e),this.config.isFlagEnabled(He.BrowserSendOffer)&&(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"cirrus",this.datachannelOptions),this.sendrecvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e),this.peerConnectionController.createOffer(this.sdpConstraints,this.config))}checkTurnServerAvailability(e){if(!e.iceServers)return G.Info("A turn sever was not found"),!1;for(const t of e.iceServers)for(const e of t.urls)if(e.includes("turn"))return G.Info(`A turn sever was found at ${e}`),!0;return G.Info("A turn sever was not found"),!1}handleOnConfigMessage(e){this.resizePlayerStyle(),this.startSession(e.peerConnectionOptions)}handlePingMessage(e){this.protocol.sendMessage(wn(mn,{time:e.time}))}handleStreamerListMessage(e){G.Info(`Got streamer list ${e.ids}`);let t="";const n=this.config.getSettingOption(Ge.StreamerId);n.selected.toString().trim()&&(t=n.selected);const s=[...e.ids];s.unshift(""),this.config.setOptionSettingOptions(Ge.StreamerId,s);let i="";const r=this.config.isFlagEnabled(He.WaitForStreamer),o=this.config.getNumericSettingValue(qe.MaxReconnectAttempts),a=this.config.getNumericSettingValue(qe.StreamerAutoJoinInterval),l=this.config.useUrlParams,c=new Cs(window.location.search);l&&c.has(Ge.StreamerId)?t=c.get(Ge.StreamerId):this.subscribedStream&&(t=this.subscribedStream),t&&e.ids.includes(t)?i=t:t&&r||1!=e.ids.length||(i=e.ids[0]),i?(this.reconnectAttempt=0,this.isReconnecting=!1,this.config.setOptionSettingValue(Ge.StreamerId,i)):r&&(this.reconnectAttempt<o?(this.reconnectAttempt++,this.isReconnecting=!0,setTimeout(()=>{this.protocol.sendMessage(wn(on))},a)):(this.reconnectAttempt=0,this.isReconnecting=!1,this.enableAutoReconnect=!1)),this.pixelStreaming.dispatchEvent(new Pe({messageStreamerList:e,autoSelectedStreamerId:i,wantedStreamerId:t}))}handleSubscribeFailedMessage(e){this.reconnectAttempt=0,this.isReconnecting=!1,this.enableAutoReconnect=!1,this.pixelStreaming._onSubscribeFailed(e.message)}handleStreamerIDChangedMessage(e){const t=e.newID,n=this.config.getSettingOption(Ge.StreamerId),s=n.onChange;n.onChange=()=>{};const i=n.options;for(let e=0;e<i.length;++e)if(i[e]==this.subscribedStream){i[e]=t;break}n.options=i,n.selected=t,n.onChange=s,this.subscribedStream=e.newID,this.pixelStreaming.dispatchEvent(new Ie({newID:t}))}handleWebRtcAnswer(e){G.Info(`Got answer sdp ${e.sdp}`);const t={sdp:e.sdp,type:"answer"};this.peerConnectionController.receiveAnswer(t),this.handlePostWebrtcNegotiation()}handleWebRtcOffer(e){G.Info(`Got offer sdp ${e.sdp}`),this.isUsingSFU=!!e.sfu&&e.sfu,this.isUsingSVC=!!e.scalabilityMode&&"L1T1"!=e.scalabilityMode,(this.isUsingSFU||this.isUsingSVC)&&(this.peerConnectionController.preferredCodec="");const t=e.scalabilityMode?e.scalabilityMode:"L1T1";let n=["Default"];if(this.isUsingSFU)if(this.isUsingSVC){n=[];const e=+t[1],s=+t[3];for(let t=1;t<=e;t++)for(let e=1;e<=s;e++)n.push(`S${t}T${e}`)}else n=["Low","Medium","High"];this.config.setOptionSettingOptions(Ge.PreferredQuality,n),this.config.setOptionSettingValue(Ge.PreferredQuality,n.slice(-1)[0]);const s={sdp:e.sdp,type:"offer"};this.peerConnectionController.receiveOffer(s,this.config),this.handlePostWebrtcNegotiation()}handleWebRtcSFUPeerDatachannels(e){const t={ordered:!0,negotiated:!0,id:e.sendStreamId},n=e.sendStreamId!=e.recvStreamId;if(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,n?"send-datachannel":"datachannel",t),n){const t={ordered:!0,negotiated:!0,id:e.recvStreamId};this.recvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"recv-datachannel",t),this.recvDataChannelController.handleOnOpen=()=>this.protocol.sendMessage(wn(Sn)),this.recvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e)}else this.sendrecvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e)}handlePostWebrtcNegotiation(){this.afkController.startAfkWarningTimer(),this.pixelStreaming._onWebRtcSdp(),this.statsTimerHandle&&void 0!==this.statsTimerHandle&&window.clearInterval(this.statsTimerHandle),this.statsTimerHandle=window.setInterval(()=>this.getStats(),1e3),this.setMouseInputEnabled(this.config.isFlagEnabled(He.MouseInput)),this.setKeyboardInputEnabled(this.config.isFlagEnabled(He.KeyboardInput)),this.setGamePadInputEnabled(this.config.isFlagEnabled(He.GamepadInput))}handleIceCandidate(e){G.Info(`Remote ICE candidate information received: ${JSON.stringify(e)}`);const t=new RTCIceCandidate({candidate:e.candidate,sdpMLineIndex:0});this.peerConnectionController.handleOnIce(t)}handleSendIceCandidate(e){e.candidate&&e.candidate.candidate&&(G.Info("Local ICE candidate generated: "+JSON.stringify(e.candidate)),this.protocol.sendMessage(wn(gn,{candidate:e.candidate})))}handleDataChannel(e){G.Info("Data channel created for us by browser as we are a receiving peer."),this.sendrecvDataChannelController.dataChannel=e.channel,this.sendrecvDataChannelController.setupDataChannel(),this.sendrecvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e)}handleSendWebRTCOffer(e){if("offer"!==e.type)return void G.Error(`handleSendWebRTCOffer was called with type ${e.type} - it only expects "offer"`);G.Info("Sending the offer to the Server");const t={sdp:e.sdp,minBitrateBps:1e3*this.config.getNumericSettingValue(qe.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(qe.WebRTCMaxBitrate)};this.protocol.sendMessage(wn(dn,t)),this.pixelStreaming._onWebRtcSdpOffer(e)}handleSendWebRTCAnswer(e){if("answer"!==e.type)return void G.Error(`handleSendWebRTCAnswer was called with type ${e.type} - it only expects "answer"`);G.Info("Sending the answer to the Server");const t={sdp:e.sdp,minBitrateBps:1e3*this.config.getNumericSettingValue(qe.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(qe.WebRTCMaxBitrate)};this.protocol.sendMessage(wn(hn,t)),this.isUsingSFU&&this.protocol.sendMessage(wn(yn)),this.pixelStreaming._onWebRtcSdpAnswer(e)}setUpMouseAndFreezeFrame(){const e=this.videoPlayer.getVideoParentElement(),t=this.videoPlayer.getVideoElement();this.coordinateConverter.reconfigure({width:e.clientWidth,height:e.clientHeight},{width:t.videoWidth,height:t.videoHeight}),this.freezeFrameController.freezeFrame.resize()}closeSignalingServer(e,t){var n;this.locallyClosed=!0,this.enableAutoReconnect=t,this.disconnectMessage=e,null===(n=this.protocol)||void 0===n||n.disconnect(1e3,e)}closePeerConnection(){var e;null===(e=this.peerConnectionController)||void 0===e||e.close()}close(){this.closeSignalingServer("",!1),this.closePeerConnection()}getStats(){this.peerConnectionController.generateStats()}sendLatencyTest(){this.latencyStartTime=Date.now(),this.streamMessageController.toStreamerHandlers.get("LatencyTest")([JSON.stringify({StartTime:this.latencyStartTime})])}sendDataChannelLatencyTest(e){this.streamMessageController.toStreamerHandlers.get("DataChannelLatencyTest")([JSON.stringify(e)])}sendEncoderMinQP(e){G.Info(`MinQP=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MinQP":e})])}sendEncoderMaxQP(e){G.Info(`MaxQP=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MaxQP":e})])}sendEncoderMinQuality(e){G.Info(`MinQuality=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MinQuality":e})])}sendEncoderMaxQuality(e){G.Info(`MaxQuality=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MaxQuality":e})])}sendWebRTCMinBitrate(e){G.Info(`WebRTC Min Bitrate=${e}`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MinBitrate":e})])}sendWebRTCMaxBitrate(e){G.Info(`WebRTC Max Bitrate=${e}`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxBitrate":e})])}sendWebRTCFps(e){G.Info(`WebRTC FPS=${e}`),null!=e&&(this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.Fps":e})]),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxFps":e})]))}sendShowFps(){G.Info("---- Sending show stat to UE ----"),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"stat.fps":""})])}sendIframeRequest(){G.Info("---- Sending Request for an IFrame ----"),this.streamMessageController.toStreamerHandlers.get("IFrameRequest")()}emitUIInteraction(e){G.Info("---- Sending custom UIInteraction message ----"),this.streamMessageController.toStreamerHandlers.get("UIInteraction")([JSON.stringify(e)])}emitCommand(e){G.Info("---- Sending custom Command message ----"),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(e)])}emitConsoleCommand(e){G.Info("---- Sending custom Command:ConsoleCommand message ----"),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({ConsoleCommand:e})])}sendRequestQualityControlOwnership(){G.Info("---- Sending Request to Control Quality ----"),this.toStreamerMessagesController.SendRequestQualityControl()}sendTextboxEntry(e){var t;G.Info("---- Sending TextboxEntry message ----"),null===(t=this.streamMessageController.toStreamerHandlers.get("TextboxEntry"))||void 0===t||t([e])}handleLatencyTestResult(e){G.Info("DataChannelReceiveMessageType.latencyTest");const t=new TextDecoder("utf-16").decode(e.slice(1)),n=new Gn;Object.assign(n,JSON.parse(t)),n.processFields(),n.testStartTimeMs=this.latencyStartTime,n.browserReceiptTimeMs=Date.now(),n.latencyExcludingDecode=~~(n.browserReceiptTimeMs-n.testStartTimeMs),n.testDuration=~~(n.TransmissionTimeMs-n.ReceiptTimeMs),n.networkLatency=~~(n.latencyExcludingDecode-n.testDuration),n.frameDisplayDeltaTimeMs&&n.browserReceiptTimeMs&&(n.endToEndLatency=(n.frameDisplayDeltaTimeMs,n.networkLatency,~~+n.CaptureToSendMs)),this.pixelStreaming._onLatencyTestResult(n)}handleDataChannelLatencyTestResponse(e){G.Info("DataChannelReceiveMessageType.dataChannelLatencyResponse");const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);this.pixelStreaming._onDataChannelLatencyTestResponse(n)}handleInitialSettings(e){G.Info("DataChannelReceiveMessageType.InitialSettings");const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t),s=new qn;n.Encoder&&(s.EncoderSettings=n.Encoder),n.WebRTC&&(s.WebRTCSettings=n.WebRTC),n.PixelStreaming&&(s.PixelStreamingSettings=n.PixelStreaming),n.ConfigOptions&&void 0!==n.ConfigOptions.DefaultToHover&&this.config.setFlagEnabled(He.HoveringMouseMode,!!n.ConfigOptions.DefaultToHover),s.ueCompatible(),G.Info(t),this.pixelStreaming._onInitialSettings(s)}handleVideoEncoderAvgQP(e){G.Info("DataChannelReceiveMessageType.VideoEncoderAvgQP");const t=Number(new TextDecoder("utf-16").decode(e.slice(1)));this.setVideoEncoderAvgQP(t)}handleVideoInitialized(){this.pixelStreaming._onVideoInitialized(),this.autoPlayVideoOrSetUpPlayOverlay(),this.resizePlayerStyle(),this.videoPlayer.updateVideoStreamSize()}onQualityControlOwnership(e){const t=new Uint8Array(e);G.Info("DataChannelReceiveMessageType.QualityControlOwnership"),this.isQualityController=new Boolean(t[1]).valueOf(),G.Info(`Received quality controller message, will control quality: ${this.isQualityController}`),this.pixelStreaming._onQualityControlOwnership(this.isQualityController)}handleVideoStats(e){this.pixelStreaming._onVideoStats(e)}resizePlayerStyle(){this.videoPlayer.resizePlayerStyle()}setPreferredCodec(e){this.preferredCodec=e,this.peerConnectionController&&(this.peerConnectionController.preferredCodec=e,this.peerConnectionController.updateCodecSelection=!1)}setVideoEncoderAvgQP(e){this.videoAvgQp=e,this.pixelStreaming._onVideoEncoderAvgQP(this.videoAvgQp)}setKeyboardInputEnabled(e){var t;null===(t=this.keyboardController)||void 0===t||t.unregister(),e&&(this.keyboardController=this.inputClassesFactory.registerKeyBoard(this.config))}setMouseInputEnabled(e){var t;if(null===(t=this.mouseController)||void 0===t||t.unregister(),e){const e=this.config.isFlagEnabled(He.HoveringMouseMode)?Ye.HoveringMouse:Ye.LockedMouse;this.mouseController=this.inputClassesFactory.registerMouse(e,this.config)}}setTouchInputEnabled(e){var t;null===(t=this.touchController)||void 0===t||t.unregister(),e&&(this.touchController=this.inputClassesFactory.registerTouch(this.config.isFlagEnabled(He.FakeMouseWithTouches)))}setGamePadInputEnabled(e){var t;null===(t=this.gamePadController)||void 0===t||t.unregister(),e&&(this.gamePadController=this.inputClassesFactory.registerGamePad())}registerDataChannelEventEmitters(e){e.onOpen=(e,t)=>this.pixelStreaming.dispatchEvent(new pe({label:e,event:t})),e.onClose=(e,t)=>this.pixelStreaming.dispatchEvent(new me({label:e,event:t})),e.onError=(e,t)=>this.pixelStreaming.dispatchEvent(new fe({label:e,event:t}))}registerMessageHandler(e,t,n){t===ds.FromStreamer&&void 0===n&&G.Warning(`Unable to register handler for ${e} as no handler was passed`),this.streamMessageController.registerMessageHandler(t,e,s=>void 0===n&&t===ds.ToStreamer?this.sendMessageController.sendMessageToStreamer(e,s):n(s))}}class Ts{constructor(e){this.toStreamerMessagesProvider=e,this.controllers=[]}updateStatus(e,t,n){if(e.gamepad){const s=t.getPose(e.gripSpace,n);if(!s)return;let i=0;e.profiles.includes("htc-vive")?i=1:e.profiles.includes("oculus-touch")&&(i=2),this.toStreamerMessagesProvider.toStreamerHandlers.get("XRSystem")([i]);let r=2;switch(e.handedness){case"left":r=0;break;case"right":r=1}const o=s.transform.matrix,a=[];for(let e=0;e<16;e++)a[e]=new Float32Array([o[e]])[0];this.toStreamerMessagesProvider.toStreamerHandlers.get("XRControllerTransform")([a[0],a[4],a[8],a[12],a[1],a[5],a[9],a[13],a[2],a[6],a[10],a[14],a[3],a[7],a[11],a[15],r]),void 0===this.controllers[r]&&(this.controllers[r]={prevState:void 0,currentState:void 0,id:void 0},this.controllers[r].prevState=ls(e.gamepad)),this.controllers[r].currentState=ls(e.gamepad);const l=this.controllers[r],c=l.currentState,d=l.prevState;for(let e=0;e<c.buttons.length;e++){const t=c.buttons[e],n=d.buttons[e];if(t.pressed){const s=n.pressed?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonPressed")([r,e,s,t.value])}else n.pressed&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonReleased")([r,e,0]);if(t.touched){const t=n.touched?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouched")([r,e,t])}else n.touched&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouchReleased")([r,e,0])}for(let e=0;e<c.axes.length;e++){const t=c.axes[e];t!=d.axes[e]&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRAnalog")([r,e,t])}this.controllers[r].prevState=c}}}class Es{constructor(e){this.xrViewerPose=null,this.EPSILON=1e-7,this.videoTexture=null,this.prevVideoWidth=0,this.prevVideoHeight=0,this.leftView=null,this.rightView=null,this.lastSentLeftEyeProj=null,this.lastSentRightEyeProj=null,this.lastSentRelativeLeftEyePos=null,this.lastSentRelativeRightEyePos=null,this.xrSession=null,this.webRtcController=e,this.xrGamepadController=new Ts(this.webRtcController.streamMessageController),this.onSessionEnded=new EventTarget,this.onSessionStarted=new EventTarget,this.onFrame=new EventTarget}xrClicked(){if(this.xrSession)this.xrSession.end();else{if(!navigator.xr)return void G.Error("This browser does not support XR.");navigator.xr.requestSession("immersive-vr",{optionalFeatures:[]}).then(e=>{this.onXrSessionStarted(e)})}}onXrSessionEnded(){G.Info("XR Session ended"),this.xrSession=null,this.onSessionEnded.dispatchEvent(new Event("xrSessionEnded"))}initGL(){if(this.gl)return;const e=document.createElement("canvas");this.gl=e.getContext("webgl2",{xrCompatible:!0}),this.gl.clearColor(0,0,0,1)}initShaders(){const e=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(e,"\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n // varyings\n varying vec2 v_texCoord;\n\n void main() {\n gl_Position = vec4(a_position.x, a_position.y, 0, 1);\n // pass the texCoord to the fragment shader\n // The GPU will interpolate this value between points.\n v_texCoord = a_texCoord;\n }\n "),this.gl.compileShader(e);const t=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(t,"\n precision mediump float;\n\n // our texture\n uniform sampler2D u_image;\n\n // the texCoords passed in from the vertex shader.\n varying vec2 v_texCoord;\n\n void main() {\n gl_FragColor = texture2D(u_image, v_texCoord);\n }\n "),this.gl.compileShader(t);const n=this.gl.createProgram();this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),this.gl.useProgram(n),this.positionLocation=this.gl.getAttribLocation(n,"a_position"),this.texcoordLocation=this.gl.getAttribLocation(n,"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));const 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){G.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(const t of this.xrSession.supportedFrameRates)90==t&&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((e,n)=>Math.abs(e-t[n])<=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(null==this.leftView||null==this.rightView)return;let e=null==this.lastSentLeftEyeProj||null==this.lastSentRightEyeProj||null==this.lastSentRelativeLeftEyePos||null==this.lastSentRelativeRightEyePos;const t=this.leftView.transform.matrix,n=this.leftView.projectionMatrix,s=this.rightView.transform.matrix,i=this.rightView.projectionMatrix,r=this.xrViewerPose.transform.matrix;if(!e&&null!=this.lastSentLeftEyeProj&&null!=this.lastSentRightEyeProj){const t=this.areArraysEqual(n,this.lastSentLeftEyeProj),s=this.areArraysEqual(i,this.lastSentRightEyeProj);e=0==t||0==s}const o=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),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);if(!e&&null!=this.lastSentRelativeLeftEyePos&&null!=this.lastSentRelativeRightEyePos){const t=this.arePointsEqual(o,this.lastSentRelativeLeftEyePos),n=this.arePointsEqual(a,this.lastSentRelativeRightEyePos);e=0==t||0==n}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],s[0],s[4],s[8],s[12],s[1],s[5],s[9],s[13],s[2],s[6],s[10],s[14],s[3],s[7],s[11],s[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]]),this.lastSentLeftEyeProj=n,this.lastSentRightEyeProj=i,this.lastSentRelativeLeftEyePos=o,this.lastSentRelativeRightEyePos=a):this.webRtcController.streamMessageController.toStreamerHandlers.get("XRHMDTransform")([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]])}onXrFrame(e,t){if(this.xrViewerPose=t.getViewerPose(this.xrRefSpace),this.xrViewerPose){if(this.updateViews(),null==this.leftView||null==this.rightView)return;this.sendXRDataToUE(),this.updateVideoTexture(),this.render()}this.webRtcController.config.isFlagEnabled(He.XRControllerInput)&&this.xrSession.inputSources.forEach((e,n,s)=>{this.xrGamepadController.updateStatus(e,t,this.xrRefSpace)},this),this.xrSession.requestAnimationFrame((e,t)=>this.onXrFrame(e,t)),this.onFrame.dispatchEvent(new Be({time:e,frame:t}))}updateViews(){if(this.xrViewerPose)for(const e of this.xrViewerPose.views)"left"===e.eye?this.leftView=e:"right"===e.eye&&(this.rightView=e)}render(){if(!this.gl)return;const 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){"https:"!==location.protocol&&G.Info("WebXR requires https, if you want WebXR use https.");try{if(navigator.xr)return navigator.xr.isSessionSupported(e)}catch(e){return Promise.resolve(!1)}return Promise.resolve(!1)}}class Rs{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}}class ks{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()&&(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(){const e=new Map(this.records);return{records:e,dataChannelRtt:Math.ceil(Array.from(this.records.values()).reduce((e,t)=>e+(t.playerReceivedTimestamp-t.playerSentTimestamp),0)/this.records.size),playerToStreamerTime:Math.ceil(Array.from(this.records.values()).reduce((e,t)=>e+(t.streamerReceivedTimestamp-t.playerSentTimestamp),0)/this.records.size),streamerToPlayerTime:Math.ceil(Array.from(this.records.values()).reduce((e,t)=>e+(t.playerReceivedTimestamp-t.streamerSentTimestamp),0)/this.records.size),exportLatencyAsCSV:()=>{let t="Timestamp;RTT;PlayerToStreamer;StreamerToPlayer;\n";return e.forEach(e=>{t+=e.playerSentTimestamp+";",t+=e.playerReceivedTimestamp-e.playerSentTimestamp+";",t+=e.streamerReceivedTimestamp-e.playerSentTimestamp+";",t+=e.playerReceivedTimestamp-e.streamerSentTimestamp+";",t+="\n"}),t}}}isRunning(){return!!this.intervalHandle}receive(e){if(!this.isRunning())return;if(!e)return void G.Error("Undefined response from server");const t=this.records.get(e.Seq);t&&t.update(e)}sendRequest(e,t){const n=this.createRequest(e,t),s=new Rs(n);this.records.set(s.seq,s),this.sink(n)}createRequest(e,t){return{Seq:this.seq++,FillResponseSize:t,Filler:e?"A".repeat(e):""}}}class Ps{constructor(e,t){this.allowConsoleCommands=!1,this.config=e,(null==t?void 0:t.videoElementParent)&&(this._videoElementParent=t.videoElementParent),this._eventEmitter=new We,this.configureSettings(),this.setWebRtcPlayerController(new Ms(this.config,this)),this._webXrController=new Es(this._webRtcController),this._setupWebRtcTCPRelayDetection=this._setupWebRtcTCPRelayDetection.bind(this),this._eventEmitter.addEventListener("webRtcConnected",e=>{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(He.IsQualityController,e=>{!0!==e||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()}),this.config._addOnSettingChangedListener(He.AFKDetection,e=>{this._webRtcController.setAfkEnabled(e)}),this.config._addOnSettingChangedListener(He.MatchViewportResolution,()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()}),this.config._addOnSettingChangedListener(He.HoveringMouseMode,e=>{this.config.setFlagLabel(He.HoveringMouseMode,`Control Scheme: ${e?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(He.MouseInput))}),this.config._addOnSettingChangedListener(He.KeyboardInput,e=>{this._webRtcController.setKeyboardInputEnabled(e)}),this.config._addOnSettingChangedListener(He.MouseInput,e=>{this._webRtcController.setMouseInputEnabled(e)}),this.config._addOnSettingChangedListener(He.FakeMouseWithTouches,e=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(He.TouchInput))}),this.config._addOnSettingChangedListener(He.TouchInput,e=>{this._webRtcController.setTouchInputEnabled(e)}),this.config._addOnSettingChangedListener(He.GamepadInput,e=>{this._webRtcController.setGamePadInputEnabled(e)}),this.config._addOnNumericSettingChangedListener(qe.MinQP,e=>{G.Info("-------- Sending MinQP --------"),this._webRtcController.sendEncoderMinQP(e),G.Info("-------------------------------------------");const t=Math.trunc(100*(1-e/51));this.config.setNumericSetting(qe.CompatQualityMax,t)}),this.config._addOnNumericSettingChangedListener(qe.MaxQP,e=>{G.Info("-------- Sending MaxQP --------"),this._webRtcController.sendEncoderMaxQP(e),G.Info("-------------------------------------------");const t=Math.trunc(100*(1-e/51));this.config.setNumericSetting(qe.CompatQualityMin,t)}),this.config._addOnNumericSettingChangedListener(qe.MinQuality,e=>{G.Info("-------- Sending MinQuality --------"),this._webRtcController.sendEncoderMinQuality(e),G.Info("-------------------------------------------"),this.config.setNumericSetting(qe.CompatQualityMin,e)}),this.config._addOnNumericSettingChangedListener(qe.MaxQuality,e=>{G.Info("-------- Sending MaxQuality --------"),this._webRtcController.sendEncoderMaxQuality(e),G.Info("-------------------------------------------"),this.config.setNumericSetting(qe.CompatQualityMax,e)}),this.config._addOnNumericSettingChangedListener(qe.CompatQualityMin,e=>{e=51-e/100*51,G.Info("-------- Sending MinQP from quality value --------"),this._webRtcController.sendEncoderMaxQP(e),G.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(qe.CompatQualityMax,e=>{e=51-e/100*51,G.Info("-------- Sending MaxQP from quality value --------"),this._webRtcController.sendEncoderMinQP(e),G.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(qe.WebRTCMinBitrate,e=>{G.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCMinBitrate(1e3*e),G.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(qe.WebRTCMaxBitrate,e=>{G.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCMaxBitrate(1e3*e),G.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(qe.WebRTCFPS,e=>{G.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCFps(e),G.Info("-------------------------------------------")}),this.config._addOnOptionSettingChangedListener(Ge.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(Ge.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Se),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new we),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new be),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(He.AutoConnect)&&(this._onWebRtcAutoConnect(),this._webRtcController.connectToSignallingServer())}unmuteMicrophone(e=!1){if(!this.config.isFlagEnabled("UseMic"))return e?(this.config.setFlagEnabled("UseMic",!0),void this.reconnect()):void G.Warning("Trying to unmute mic, but PixelStreaming was initialized with no microphone track. Call with forceEnable == true to re-connect with a mic track.");this.setMicrophoneMuted(!1)}muteMicrophone(){this.config.isFlagEnabled("UseMic")?this.setMicrophoneMuted(!0):G.Info("Trying to mute mic, but PixelStreaming has no microphone track, so sending sound is already disabled.")}setMicrophoneMuted(e){var t,n,s,i;for(const r of null!==(i=null===(s=null===(n=null===(t=this._webRtcController)||void 0===t?void 0:t.peerConnectionController)||void 0===n?void 0:n.peerConnection)||void 0===s?void 0:s.getTransceivers())&&void 0!==i?i:[])Un.canTransceiverSendAudio(r)&&(r.sender.track.enabled=!e)}unmuteCamera(e=!1){if(!this.config.isFlagEnabled("UseCamera"))return e?(this.config.setFlagEnabled("UseCamera",!0),void this.reconnect()):void G.Warning("Trying to unmute video, but PixelStreaming was initialized with no video track. Call with forceEnable == true to re-connect with a video track.");this.setCameraMuted(!1)}muteCamera(){this.config.isFlagEnabled("UseCamera")?this.setCameraMuted(!0):G.Info("Trying to mute camera, but PixelStreaming has no video track, so sending video is already disabled.")}setCameraMuted(e){var t,n,s,i;for(const r of null!==(i=null===(s=null===(n=null===(t=this._webRtcController)||void 0===t?void 0:t.peerConnectionController)||void 0===n?void 0:n.peerConnection)||void 0===s?void 0:s.getTransceivers())&&void 0!==i?i:[])Un.canTransceiverSendVideo(r)&&(r.sender.track.enabled=!e)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new ce)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new oe)}_onWebRtcSdpOffer(e){this._eventEmitter.dispatchEvent(new le({sdp:e}))}_onWebRtcSdpAnswer(e){this._eventEmitter.dispatchEvent(new ae({sdp:e}))}_onLatencyCalculated(e){this._eventEmitter.dispatchEvent(new Le({latencyInfo:e}))}_onStreamLoading(){this._eventEmitter.dispatchEvent(new ve)}_onDisconnect(e,t){this._eventEmitter.dispatchEvent(new ge({eventString:e,allowClickToReconnect:t}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new de)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new he)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new ue)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new ye),this._videoStartTime=Date.now(),this.checkForAutoEnterVR()}checkForAutoEnterVR(){this.config.isFlagEnabled(He.AutoEnterVR)&&Es.isSessionSupported("immersive-vr").then(e=>{e?this._webXrController.xrClicked():G.Info("AutoEnterVR is on but immersive-vr is not supported on this device.")}).catch(e=>{const t=e instanceof Error?e.message:JSON.stringify(e);G.Warning(`AutoEnterVR check failed: ${t}`)})}_onLatencyTestResult(e){this._eventEmitter.dispatchEvent(new xe({latencyTimings:e}))}_onDataChannelLatencyTestResponse(e){this._eventEmitter.dispatchEvent(new De({response:e}))}_onVideoStats(e){this._videoStartTime&&void 0!==this._videoStartTime||(this._videoStartTime=Date.now()),e.handleSessionStatistics(this._videoStartTime,this._inputController,this._webRtcController.videoAvgQp),this._eventEmitter.dispatchEvent(new ke({aggregatedStats:e}))}_onVideoEncoderAvgQP(e){this._eventEmitter.dispatchEvent(new re({avgQP:e}))}_onInitialSettings(e){var t;this._eventEmitter.dispatchEvent(new Ne({settings:e})),e.PixelStreamingSettings&&(this.allowConsoleCommands=null!==(t=e.PixelStreamingSettings.AllowPixelStreamingCommands)&&void 0!==t&&t,!1===this.allowConsoleCommands&&G.Info("-AllowPixelStreamingCommands=false, sending arbitrary console commands from browser to UE is disabled."));const n=this.config.useUrlParams,s=new Cs(window.location.search);G.Info(`using URL parameters ${n}`),e.EncoderSettings&&(e.EncoderSettings.MinQP&&(this.config.setNumericSetting(qe.MinQP,n&&s.has(qe.MinQP)?Number.parseFloat(s.get(qe.MinQP)):e.EncoderSettings.MinQP||0),this.config.setNumericSetting(qe.MaxQP,n&&s.has(qe.MaxQP)?Number.parseFloat(s.get(qe.MaxQP)):e.EncoderSettings.MaxQP||51)),e.EncoderSettings.MinQuality&&(this.config.setNumericSetting(qe.MinQuality,n&&s.has(qe.MinQuality)?Number.parseFloat(s.get(qe.MinQuality)):e.EncoderSettings.MinQuality||0),this.config.setNumericSetting(qe.MaxQuality,n&&s.has(qe.MaxQuality)?Number.parseFloat(s.get(qe.MaxQuality)):e.EncoderSettings.MaxQuality||100)),n&&(s.has(qe.CompatQualityMin)&&this.config.setNumericSetting(qe.CompatQualityMin,Number.parseFloat(s.get(qe.CompatQualityMin))),s.has(qe.CompatQualityMax)&&this.config.setNumericSetting(qe.CompatQualityMax,Number.parseFloat(s.get(qe.CompatQualityMax))))),e.WebRTCSettings&&(this.config.setNumericSetting(qe.WebRTCMinBitrate,n&&s.has(qe.WebRTCMinBitrate)?Number.parseFloat(s.get(qe.WebRTCMinBitrate)):e.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(qe.WebRTCMaxBitrate,n&&s.has(qe.WebRTCMaxBitrate)?Number.parseFloat(s.get(qe.WebRTCMaxBitrate)):e.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(qe.WebRTCFPS,n&&s.has(qe.WebRTCFPS)?Number.parseFloat(s.get(qe.WebRTCFPS)):e.WebRTCSettings.FPS))}_onQualityControlOwnership(e){this.config.setFlagEnabled(He.IsQualityController,e)}_onPlayerCount(e){this._eventEmitter.dispatchEvent(new Ve({count:e}))}_onSubscribeFailed(e){this._eventEmitter.dispatchEvent(new Fe({message:e}))}_setupWebRtcTCPRelayDetection(e){const t=e.data.aggregatedStats.getActiveCandidatePair();if(null!=t){const n=e.data.aggregatedStats.localCandidates.find(e=>e.id==t.localCandidateId,null);null!=n&&"relay"==n.candidateType&&"tcp"==n.relayProtocol&&this._eventEmitter.dispatchEvent(new _e),this._eventEmitter.removeEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}}requestLatencyTest(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendLatencyTest(),!0)}requestDataChannelLatencyTest(e){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._dataChannelLatencyTestController||(this._dataChannelLatencyTestController=new ks(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),e=>{this._eventEmitter.dispatchEvent(new Oe({result:e}))}),this.addEventListener("dataChannelLatencyTestResponse",({data:{response:e}})=>{this._dataChannelLatencyTestController.receive(e)})),this._dataChannelLatencyTestController.start(e))}requestShowFps(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendShowFps(),!0)}requestIframe(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendIframeRequest(),!0)}emitUIInteraction(e){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.emitUIInteraction(e),!0)}emitCommand(e){return!(!this._webRtcController.videoPlayer.isVideoReady()||!this.allowConsoleCommands&&"ConsoleCommand"in e||(this._webRtcController.emitCommand(e),0))}emitConsoleCommand(e){return!(!this.allowConsoleCommands||!this._webRtcController.videoPlayer.isVideoReady()||(this._webRtcController.emitConsoleCommand(e),0))}sendTextboxEntry(e){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendTextboxEntry(e),!0)}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){t!==ds.FromStreamer||void 0!==n?t===ds.ToStreamer&&void 0===n?this._webRtcController.streamMessageController.registerMessageHandler(t,e,t=>this._webRtcController.sendMessageController.sendMessageToStreamer(e,t)):this._webRtcController.streamMessageController.registerMessageHandler(t,e,e=>n(e)):G.Warning(`Unable to register an undefined handler for ${e}`)}get toStreamerHandlers(){return this._webRtcController.streamMessageController.toStreamerHandlers}isReconnecting(){return this._webRtcController.isReconnecting}}!function(e){e[e.VideoInitialised=0]="VideoInitialised",e[e.DataChannelOpen=1]="DataChannelOpen",e[e.DataChannelResponse=2]="DataChannelResponse",e[e.WaitingForRenderer=3]="WaitingForRenderer",e[e.RendererTaken=4]="RendererTaken",e[e.WebRtcStats=5]="WebRtcStats"}(hs||(hs={}));class Is{type=hs.VideoInitialised}class xs{type=hs.DataChannelOpen}class Ls{msg;type=hs.DataChannelResponse;constructor(e){this.msg=e}}class As{stats;type=hs.WebRtcStats;constructor(e){this.stats=e}}var Ds,Os=n(388);!function(e){e.ClientInfo="client_info",e.ClientGone="client_gone",e.CustomerConcurrencyLimitReached="customer_concurrency_limit_reached",e.Config="config",e.Error="error",e.IndexInQueue="index_in_queue",e.RendererTaken="renderer_taken",e.RendererGone="renderer_gone",e.RendererError="renderer_error",e.RendererVersionWarning="renderer_version_warning",e.SwitchRendererRequest="switch_renderer_request"}(Ds||(Ds={}));var Fs=n(838),Ns=n(992);const Us="sessionEndedDueToConnectionLoss",Bs="sessionEndedDueToVideoPlaybackError",Vs="sessionEndedDueToRendererError";var _s,Ws,$s,Hs,js;function qs(e,t,n){return Math.max(t,Math.min(e,n))}function zs(e){const t=e?.srcObject;return!!t&&"function"==typeof t.getAudioTracks&&t.getAudioTracks().length>0}!function(e){e.Good="Good",e.Fair="Fair",e.Poor="Poor"}(_s||(_s={})),function(e){e.Always="always",e.WhenDegraded="when-degraded",e.Hidden="hidden"}(Ws||(Ws={})),function(e){e.TopLeft="top-left",e.TopRight="top-right",e.BottomLeft="bottom-left",e.BottomRight="bottom-right"}($s||($s={})),function(e){e.Click="click",e.Hover="hover",e.None="none"}(Hs||(Hs={}));class Qs{stream;videoElement;audioElement;previousStats;constructor(e,t,n){this.stream=e,this.videoElement=t,this.audioElement=n}getPeerConnection(){return this.stream?.webRtcController?.peerConnectionController?.peerConnection}async analyzeAudioStats(){const e=this.getPeerConnection();if(!e)return void r.A.error("Stream appears to be down, RTCPeerConnection is not defined");const t=await e.getStats(null),n=this.getInboundAudioStats(t);if(!n)return void r.A.warn("WebRTC Connection - No inbound audio RTP stats found.");const s=n.codecId,i=s?this.getCodecFromStats(t,s):void 0;this.logAudioStats(n,i),this.logElementStatus(i)}async collectNetworkQuality(e){const t=this.getPeerConnection();if(!t)return r.A.warn("Cannot collect network quality: RTCPeerConnection is not defined"),null;const n=await t.getStats(null),s=this.extractRawStats(n);if(!this.previousStats)return this.previousStats=s,null;const i=this.computeMetrics(s,this.previousStats,e);return this.previousStats=s,i}resetStats(){this.previousStats=void 0}extractRawStats(e){const 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}};let n,s;if(e.forEach(e=>{"inbound-rtp"===e.type&&"audio"===e.kind?(t.audio.packetsReceived=e.packetsReceived??0,t.audio.packetsLost=e.packetsLost??0,t.audio.bytesReceived=e.bytesReceived??0,t.audio.jitter=e.jitter??0,n=e.codecId):"inbound-rtp"===e.type&&"video"===e.kind?(t.video.packetsReceived=e.packetsReceived??0,t.video.packetsLost=e.packetsLost??0,t.video.bytesReceived=e.bytesReceived??0,t.video.framesDecoded=e.framesDecoded??0,t.video.framesDropped=e.framesDropped??0,t.video.frameWidth=e.frameWidth??0,t.video.frameHeight=e.frameHeight??0,t.video.framesPerSecond=e.framesPerSecond??0,t.video.jitter=e.jitter??0,s=e.codecId):"candidate-pair"===e.type&&e.nominated&&(t.connection.currentRoundTripTime=e.currentRoundTripTime??0)}),n){const s=e.get(n);s&&(t.audio.codecMimeType=s.mimeType)}if(s){const n=e.get(s);n&&(t.video.codecMimeType=n.mimeType)}return t}computeMetrics(e,t,n){const s=(e.timestamp-t.timestamp)/1e3,i=e.audio.packetsReceived-t.audio.packetsReceived,r=e.audio.packetsLost-t.audio.packetsLost,o=i+r,a=o>0?r/o*100:0,l=s>0?8*(e.audio.bytesReceived-t.audio.bytesReceived)/s/1e3:0,c=e.video.packetsReceived-t.video.packetsReceived,d=e.video.packetsLost-t.video.packetsLost,h=c+d,u=h>0?d/h*100:0,g=s>0?8*(e.video.bytesReceived-t.video.bytesReceived)/s/1e3:0,p=1e3*e.connection.currentRoundTripTime,m=function(e){const t=e.packetLoss??0,n=e.fec??!0,s=e.bitrate,i=20+(e.bufferDelay??50)+(e.roundTripTime??50)/2,r=e.dtx??!1?8:s?qs(55-4.6*Math.log(s),0,30):6,o=qs(100-(r+t/(t+(n?20:10))*(100-r))-(.03*i+(i>150?.1*(i-150):0)),0,100),a=1+.035*o+o*(o-60)*(100-o)*7/1e6;return qs(Math.round(100*a)/100,1,5)}({packetLoss:a,bitrate:1e3*l,roundTripTime:p,bufferDelay:1e3*e.audio.jitter}),f=n.expectedFrameRate??30,y=e.video.codecMimeType?.toLowerCase()??"",v=[["vp9","vp9"],["vp8","vp8"],["h264","h264"],["avc","h264"],["h265","h265"],["hevc","h265"],["av1","av1"]].find(([e])=>y.includes(e))?.[1],S=function(e){const t=e.bitrate??0,n=e.roundTripTime??50,s=e.bufferDelay??0,i=e.width||640,r=e.height||480,o=e.frameRate??0,a=e.expectedFrameRate??30,l=e.codec?.toLowerCase();if(0===o)return 1;const c=s+n/2,d=("vp9"===l?1.2:1)*t/(i*r)/o,h=qs(.56*Math.log(d)+5.36,1,5)-1.9*Math.log(a/o)-.002*c;return qs(Math.round(100*h)/100,1,5)}({bitrate:1e3*g,roundTripTime:p,width:e.video.frameWidth,height:e.video.frameHeight,frameRate:e.video.framesPerSecond,expectedFrameRate:f,codec:v}),b=Math.min(m,S);let w;return w=b>=3.5?_s.Good:b>=2.5?_s.Fair:_s.Poor,{audioPacketLossPercent:Math.round(100*a)/100,videoPacketLossPercent:Math.round(100*u)/100,audioBitrateKbps:Math.round(l),videoBitrateKbps:Math.round(g),frameRate:e.video.framesPerSecond,audioJitterMs:Math.round(1e3*e.audio.jitter*100)/100,videoJitterMs:Math.round(1e3*e.video.jitter*100)/100,roundTripTimeMs:Math.round(100*p)/100,audioMos:m,videoMos:S,qualityLevel:w}}getInboundAudioStats(e){let t=null;return e.forEach(e=>{"inbound-rtp"===e.type&&"audio"===e.kind&&(t=e)}),t}getCodecFromStats(e,t){let n;return e.forEach(e=>{"codec"===e.type&&e.id===t&&(n=e)}),n}logAudioStats(e,t){const{packetsReceived:n,packetsLost:s,bytesReceived:i,jitter:o,audioLevel:a}=e;r.A.info(`WebRTC Connection - Audio -\n Codec: ${t?t.mimeType+" ("+t.payloadType+")":"Unknown"},\n Packets received: ${n},\n Packets lost: ${s},\n Bytes received: ${i},\n Jitter: ${o},\n Audio level (0-1): ${a??"N/A"}`),0===n&&r.A.warn("WebRTC Connection - Audio - No audio packets received — remote is probably not sending audio."),s>0&&r.A.warn(`WebRTC Connection - Audio - packet loss detected: ${s} packets lost.`),void 0===a?r.A.warn("WebRTC Connection - Audio - Audio level not available in stats."):0===a?r.A.warn("WebRTC Connection - Audio - Audio level is zero — digital human might not be talking at this exact moment as audio is silent or muted."):a<.02?r.A.warn("WebRTC Connection - Audio - Audio level is very low — audio might be too quiet."):r.A.info("WebRTC Connection - Audio - Audio level looks normal, digital human is likely speaking.")}logElementStatus(e){const t=zs(this.videoElement),n=t?this.videoElement:this.audioElement;r.A.debug(`Audio plays from ${t?"video":"separate audio"} element (DisableAudioSync=${t?"false":"true"}).`),r.A.debug(`Video element muted: ${this.videoElement?.muted}, (should be ${t?"false to be able to hear the digital human":"true as part of avoiding auto play restrictions"})`),r.A.debug(`Playback element muted: ${n?.muted}, (should be false to be able to hear the digital human)`),r.A.debug(`Playback element volume: ${n?.volume}, (should be greater than zero to be able to hear the digital human)`);const s=e?.mimeType;s&&n&&(r.A.debug(`Playback element can play webrtc audio codec (${s}) : ${n.canPlayType(s)}, (should be 'probably' or 'maybe)'`),"audio/opus"===s&&r.A.debug(`Audio codec opus is often known as ogg, so checking can play ogg codec: ${n.canPlayType("audio/ogg")}, (should be 'probably' or 'maybe')`))}}!function(e){e.Google="google",e.Deepgram="deepgram"}(js||(js={}));const Ks=e=>e??"speech-recognition-service",Gs=e=>"pixel-streaming"===e||"both"===e,Xs=e=>"speech-recognition-service"===e||"both"===e,Js="#6b7280";let Ys=0;const Zs={position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:"0"},ei={message:"",qualityHeader:"{level} Quality",good:"Good",fair:"Fair",poor:"Poor",unknown:"unknown",networkQuality:"Network quality",qualityScoreMos:"Quality Score (MOS)",connection:"Connection",throughput:"Throughput",audio:"Audio",video:"Video",roundTrip:"Round Trip",packetLoss:"Packet Loss",jitter:"Jitter",bitrate:"Bitrate",frameRate:"Frame Rate"};class ti{videoContainerElement;container;panel;trigger;liveRegion;announcedLevel;panelId;bars=[];panelVisible=!1;lastMetrics;visibility;position;popupTrigger;strings;onClickBound;onMouseEventBound;onDocumentClickBound;onMouseEnterBound;onMouseLeaveBound;onKeyDownBound;hoverHideTimeout;originalParentPosition;constructor(e,t){this.videoContainerElement=e,this.visibility=t.visibility??Ws.WhenDegraded,this.position=t.position??$s.TopRight,this.popupTrigger=t.popupTrigger??Hs.Click,this.strings={...ei,...t.strings},this.onClickBound=this.onClick.bind(this),this.onMouseEventBound=e=>e.stopPropagation(),this.onDocumentClickBound=this.onDocumentClick.bind(this),this.onMouseEnterBound=this.onMouseEnter.bind(this),this.onMouseLeaveBound=this.onMouseLeave.bind(this),this.onKeyDownBound=this.onKeyDown.bind(this),this.panelId="uneeq-network-indicator-panel-"+ ++Ys,this.visibility!==Ws.Hidden&&this.createElements()}createElements(){"static"===getComputedStyle(this.videoContainerElement).position&&(this.originalParentPosition=this.videoContainerElement.style.position,this.videoContainerElement.style.position="relative"),this.liveRegion=document.createElement("div"),this.liveRegion.setAttribute("data-testid","network-indicator-live-region"),this.liveRegion.setAttribute("role","status"),this.liveRegion.setAttribute("aria-live","polite"),Object.assign(this.liveRegion.style,Zs),this.videoContainerElement.appendChild(this.liveRegion),this.container=document.createElement("div"),this.container.setAttribute("data-testid","network-indicator"),Object.assign(this.container.style,{position:"absolute",zIndex:"1000",display:"none",pointerEvents:"auto",...this.getPositionStyles()});const e=this.popupTrigger!==Hs.None;this.trigger=document.createElement(e?"button":"div"),this.trigger.setAttribute("data-testid","network-indicator-trigger"),Object.assign(this.trigger.style,{display:"flex",alignItems:"flex-end",gap:"2px",padding:"6px 7px",borderRadius:"4px",background:"rgba(0, 0, 0, 0.5)",margin:"0",border:"0",font:"inherit",color:"inherit",cursor:e?"pointer":"default"}),e&&(this.trigger.type="button",this.trigger.setAttribute("aria-expanded","false"),this.trigger.setAttribute("aria-controls",this.panelId)),this.trigger.setAttribute("aria-label",`${this.strings.networkQuality}: ${this.strings.unknown}`);const t=[6,12,18];for(const e of t){const t=document.createElement("div");t.setAttribute("data-testid","network-indicator-bar"),Object.assign(t.style,{width:"4px",height:`${e}px`,borderRadius:"1px",background:Js,transition:"background 0.3s ease"}),this.bars.push(t),this.trigger.appendChild(t)}this.container.appendChild(this.trigger),this.container.addEventListener("mousedown",this.onMouseEventBound),this.container.addEventListener("mouseup",this.onMouseEventBound),this.popupTrigger===Hs.Click?this.trigger.addEventListener("click",this.onClickBound):this.popupTrigger===Hs.Hover&&(this.container.addEventListener("mouseenter",this.onMouseEnterBound),this.container.addEventListener("mouseleave",this.onMouseLeaveBound),this.trigger.addEventListener("click",this.onClickBound)),this.popupTrigger===Hs.None&&(this.container.style.cursor="default"),this.videoContainerElement.appendChild(this.container)}getPositionStyles(){const e="8px";switch(this.position){case $s.TopLeft:return{top:e,left:e};case $s.TopRight:return{top:e,right:e};case $s.BottomLeft:return{bottom:e,left:e};case $s.BottomRight:return{bottom:e,right:e};default:return{top:e,right:e}}}onClick(e){e.stopPropagation(),this.panelVisible?this.hidePanel():this.showPanel()}onDocumentClick(e){this.panelVisible&&this.container&&!this.container.contains(e.target)&&this.hidePanel()}onKeyDown(e){"Escape"===e.key&&this.panelVisible&&(this.hidePanel(),this.trigger?.focus())}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"),this.panel.id=this.panelId,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===Hs.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,this.trigger?.setAttribute("aria-expanded","true"),document.addEventListener("click",this.onDocumentClickBound),document.addEventListener("keydown",this.onKeyDownBound))}hidePanel(){this.panel&&(this.panel.style.display="none"),this.panelVisible=!1,this.trigger?.setAttribute("aria-expanded","false"),document.removeEventListener("click",this.onDocumentClickBound),document.removeEventListener("keydown",this.onKeyDownBound)}positionPanel(){if(!this.panel||!this.container)return;const e=window.innerWidth,t=window.innerHeight,n=this.container.getBoundingClientRect(),s={top:Math.max(0,Math.min(n.top,t)),bottom:Math.max(0,Math.min(n.bottom,t)),left:Math.max(0,Math.min(n.left,e)),right:Math.max(0,Math.min(n.right,e))};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";const{width:i,height:r}=this.panel.getBoundingClientRect();this.panel.style.visibility="";const o=s.top-4,a=t-s.bottom-4,l=s.left-4,c=e-s.right-4;let d,h;o>=r||a>=r?(d=a>=r&&(o<r||a>=o)?s.bottom+4:s.top-4-r,h=this.position===$s.TopLeft||this.position===$s.BottomLeft?s.left:s.right-i):(h=c>=i&&(l<i||c>=l)?s.right+4:s.left-4-i,d=s.bottom-r),h=Math.max(4,Math.min(h,e-i-4)),d=Math.max(0,Math.min(d,t-r-4)),this.panel.style.top=`${d}px`,this.panel.style.left=`${h}px`}updatePanel(){if(!this.panel||!this.lastMetrics)return;const e=this.lastMetrics,t=this.strings,n=document.createElement("div");Object.assign(n.style,{fontWeight:"600",marginBottom:"4px",color:this.getColor(e.qualityLevel)}),n.textContent=t.qualityHeader.replace("{level}",this.levelName(e.qualityLevel));const s=[n];if(t.message&&e.qualityLevel!==_s.Good){const e=document.createElement("div");Object.assign(e.style,{marginBottom:"6px",whiteSpace:"normal",maxWidth:"240px"}),e.textContent=t.message,s.push(e)}s.push(this.panelSectionHeader(t.qualityScoreMos),this.panelRow(t.audio,`${e.audioMos.toFixed(1)} / 5.0`),this.panelRow(t.video,`${e.videoMos.toFixed(1)} / 5.0`),this.panelSectionHeader(t.connection),this.panelRow(t.roundTrip,`${e.roundTripTimeMs} ms`),this.panelRow(t.packetLoss,`${e.audioPacketLossPercent}% ${t.audio} / ${e.videoPacketLossPercent}% ${t.video}`),this.panelRow(t.jitter,`${e.audioJitterMs} ms ${t.audio} / ${e.videoJitterMs} ms ${t.video}`),this.panelSectionHeader(t.throughput),this.panelRow(t.bitrate,`${e.audioBitrateKbps} ${t.audio} / ${e.videoBitrateKbps} ${t.video} kbps`),this.panelRow(t.frameRate,`${e.frameRate} fps`)),this.panel.textContent="",this.panel.append(...s)}levelName(e){switch(e){case _s.Good:return this.strings.good;case _s.Fair:return this.strings.fair;case _s.Poor:return this.strings.poor}}panelSectionHeader(e){const t=document.createElement("div");return Object.assign(t.style,{color:"#6b7280",fontSize:"10px",textTransform:"uppercase",letterSpacing:"0.5px",marginTop:"6px",marginBottom:"2px"}),t.textContent=e,t}panelRow(e,t){const n=document.createElement("div");Object.assign(n.style,{display:"flex",justifyContent:"space-between",gap:"12px"});const s=document.createElement("span");s.style.color="#9ca3af",s.textContent=e;const i=document.createElement("span");return i.textContent=t,n.append(s,i),n}getColor(e){switch(e){case _s.Good:return"#22c55e";case _s.Fair:return"#eab308";case _s.Poor:return"#ef4444"}}update(e){if(this.lastMetrics=e,!this.container)return;const t=`${this.strings.networkQuality}: ${this.levelName(e.qualityLevel)}`;this.trigger?.setAttribute("aria-label",t),this.liveRegion&&e.qualityLevel!==this.announcedLevel&&(this.announcedLevel=e.qualityLevel,this.liveRegion.textContent=t);const n=this.getColor(e.qualityLevel),s=e.qualityLevel===_s.Good?3:e.qualityLevel===_s.Fair?2:1;this.bars.forEach((e,t)=>{e.style.background=t<s?n:Js}),this.visibility===Ws.WhenDegraded?this.container.style.display=e.qualityLevel===_s.Good?"none":"flex":this.container.style.display="flex",this.panelVisible&&(this.updatePanel(),this.positionPanel())}destroy(){this.trigger&&(this.trigger.removeEventListener("click",this.onClickBound),this.trigger=void 0),this.liveRegion&&(this.liveRegion.remove(),this.liveRegion=void 0),this.announcedLevel=void 0,this.container&&(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),void 0!==this.originalParentPosition&&(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),document.removeEventListener("keydown",this.onKeyDownBound),this.bars=[],this.panelVisible=!1,this.lastMetrics=void 0}}const ni="uneeq-js.avoid-av1-until";class si{session;connectionUrl;videoContainerElement;stream;messages=new Q;videoElement;audioElement;videoInitialized=!1;dataChannelOpen=!1;sceneReady=!1;maxReconnectAttempts=4;reconnectionAttempts=0;allowReconnection=!0;reconnectTimeoutId;baseReconnectDelayMs=500;maxReconnectDelayMs=1e4;currentRendererId;audioStatsInternal;freezeCount=0;lastDecodedFrames=0;lastCheckTime=Date.now();freezeTransferThreshold=10;audioStatsAnalyzer;networkQualityInterval;networkIndicator;lastQualityLevel=_s.Good;noIceServers=!1;implausibleFrameSizeLogged=!1;config;clientMessages;_audioUpstreamMode;constructor(e,t,n){this.session=e,this.connectionUrl=t,this.videoContainerElement=n,this.config=e.config,this.clientMessages=e.messages,this._audioUpstreamMode=Ks(this.config.audioUpstreamMode)}get audioUpstreamMode(){return this._audioUpstreamMode}init(){r.A.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 Fs.qw);const e=Gs(this.audioUpstreamMode);"speech-recognition-service"!==this.audioUpstreamMode&&r.A.info(`audioUpstreamMode='${this.audioUpstreamMode}' is beta; behaviour may change.`);const t=new Je({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 Ps(t,{videoElementParent:this.videoContainerElement});const n=(s=this.config.preferredVideoCodec,i=navigator.userAgent,o=((e=Date.now())=>{try{return Number(window.localStorage.getItem(ni))>e}catch{return!1}})(),"h264"===s?{codec:"h264",reason:"config"}:o?{codec:"h264",reason:"decoder-fault-hint"}:(e=>/Android/.test(e)&&/Chrome\//.test(e))(i)?{codec:"h264",reason:"android-chromium"}:{codec:"renderer-order"});var s,i,o;r.A.info("Video codec decision",n),"renderer-order"===n.codec&&t.setOptionSettingValue(Ge.PreferredCodec,""),G.InitLogging($.Warning,!1),this.stream.setSignallingUrlBuilder(function(){let e=t.getTextSettingValue(Qe.SignallingServerUrl);return t.isFlagEnabled(He.BrowserSendOffer)&&(e+=(e.includes("?")?"&":"?")+He.BrowserSendOffer+"=true"),e}),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}})=>{r.A.trace("WebRTC: VideoEncoderAvgQP - lower is better, ranges from 0 to 51:",e)}),this.stream?.addEventListener("webRtcAutoConnect",()=>{r.A.debug("WebRTC: AutoConnect triggered")}),this.stream?.addEventListener("webRtcConnected",this.handleWebRtcConnectedMessage.bind(this)),this.stream?.addEventListener("statsReceived",({data:{aggregatedStats:e}})=>{r.A.trace("WebRTC: StatsReceived",e)}),this.stream?.addEventListener("webRtcTCPRelayDetected",()=>{r.A.warn("WebRTC: Stream quailty likely degraded due to network enviroment, stream is relayed over TCP.")})}addWebSocketHandlers(){const e=this.stream?.signallingProtocol?.transport;e?.webSocket?.addEventListener("error",this.handleWebSocketError.bind(this)),e?.webSocket?.addEventListener("open",()=>{e.webSocket?.send(JSON.stringify({type:Ds.ClientInfo,uneeqJsSdkVersion:"3.23.4"}))}),this.stream?.signallingProtocol.on(Ds.Error,e=>{r.A.error("Signaling: Received error message from server",e),this.clientMessages?.next(new Fs.Cj(`Signaling server error: ${e}`))}),this.stream?.signallingProtocol.on(Ds.IndexInQueue,this.handleIndexInQueueMessage.bind(this)),this.stream?.signallingProtocol.on(Ds.RendererTaken,this.handleRendererTakenMessage.bind(this)),this.stream?.signallingProtocol.on(Ds.RendererGone,this.handleRendererGoneEvent.bind(this)),this.stream?.signallingProtocol.on(Ds.SwitchRendererRequest,this.handleSwitchRendererRequestEvent.bind(this)),this.stream?.signallingProtocol.on(Ds.CustomerConcurrencyLimitReached,this.handleCustomerConcurrencyLimitReachedMessage.bind(this)),this.stream?.signallingProtocol.on(Ds.RendererError,this.handleRendererErrorMessage.bind(this)),this.stream?.signallingProtocol.on(Ds.RendererVersionWarning,this.handleRendererVersionWarningMessage.bind(this)),this.stream?.signallingProtocol.on(Ds.Config,this.checkForUneeqIceServers.bind(this))}checkForUneeqIceServers(e){const t=e?.peerConnectionOptions?.iceServers;if(void 0===t)return void r.A.warn("Signaling: config message carried no peerConnectionOptions.iceServers; leaving ICE server status unchanged");r.A.info("Signaling: Received ice config message with urls:",(t??[]).map(e=>({urls:e.urls})));const n=(t??[]).some(e=>e.username?.includes("disabled")&&e.urls?.some(e=>e.includes("0.0.0.0")));this.noIceServers=!t?.length||n,this.noIceServers&&r.A.warn("Signaling: no usable UneeQ ICE servers in the session config. This should be intentional, is intended for locally run renderers e.g. kiosk, miniprem etc.")}handleWebSocketError(e){r.A.error("Signaling: WebSocket error",r.A.serialiseError(e)),this.reconnectIfSafe(e)}handleVideoInitialized(){r.A.info("Video initialized."),this.videoElement=this.videoContainerElement?.getElementsByTagName("video")[0],this.audioElement=this.stream?.webRtcController?.streamController?.audioElement,this.audioStatsAnalyzer=new Qs(this.stream,this.videoElement,this.audioElement);const e=this.getAudioPlaybackElement();if(e&&this.config.speakerDeviceId&&this.setSpeakerDevice(e,this.config.speakerDeviceId),this.videoElement)this.videoElement.muted=!0,this.videoElement.play().then(()=>{this.playAudioElement()}).catch(e=>{if(e instanceof DOMException&&"NotAllowedError"===e.name)r.A.warn("Video autoplay blocked by browser. Requesting user gesture to resume playback."),this.clientMessages?.next(new Fs.MA);else{const t="Fatal Error: Digital Human video cannot be played.";r.A.error(t,r.A.serialiseError(e)),this.clientMessages?.next(new Fs.Cj(t)),this.endSession(Bs,!0)}}),this.videoInitialized=!0,this.messages.next(new Is),this.reconnectionAttempts=0,this.clearReconnectTimer();else{const e="Fatal Error: Video element not found.";r.A.error(e),this.clientMessages?.next(new Fs.Cj(e)),this.endSession(Bs,!0)}setTimeout(()=>{this.clientMessages?.next(new Fs.xQ)},mi)}getAudioPlaybackElement(){return zs(this.videoElement)?this.videoElement:this.audioElement}playAudioElement(){const e=this.getAudioPlaybackElement();if(!e)return void this.handleMissingAudioElement();const t=e===this.videoElement;e.muted=!1,e.play().then(()=>{r.A.info("Audio playback successfully started."),this.clientMessages?.next(new Fs.M8)}).catch(n=>{r.A.warn("Audio cannot be played.",n),this.clientMessages?.next(new Fs.Tu),t?(e.muted=!0,e.play().then(()=>{this.clientMessages?.next(new Fs.XC)}).catch(e=>{r.A.warn("Muted video reveal also blocked.",e),this.clientMessages?.next(new Fs.Cj(`Video playback failed: ${e}`))})):this.clientMessages?.next(new Fs.XC)})}resumeVideoPlayback(){this.videoElement?this.videoElement.play().then(()=>{this.playAudioElement()}).catch(e=>{r.A.error("Video playback failed after user gesture",r.A.serialiseError(e)),this.clientMessages?.next(new Fs.Cj("Video playback failed after user gesture")),this.endSession("sessionEndedDueToPermissionsError",!0)}):r.A.warn("resumeVideoPlayback called but no video element available")}pauseAudioElement(){const e=this.getAudioPlaybackElement();e?(e===this.videoElement?e.muted=!0:e.pause(),this.clientMessages?.next(new Fs.Tu)):this.handleMissingAudioElement()}muteUpstreamMic(){Gs(this.audioUpstreamMode)?this.stream?this.stream.muteMicrophone():r.A.warn("muteUpstreamMic called before PixelStreaming stream is initialised; ignoring."):r.A.warn(`muteUpstreamMic called in '${this.audioUpstreamMode}' mode — no PS upstream audio track to mute; ignoring.`)}unmuteUpstreamMic(){Gs(this.audioUpstreamMode)?this.stream?this.stream.unmuteMicrophone(!1):r.A.warn("unmuteUpstreamMic called before PixelStreaming stream is initialised; ignoring."):r.A.warn(`unmuteUpstreamMic called in '${this.audioUpstreamMode}' mode — no PS upstream audio track to unmute; ignoring.`)}setSpeakerDevice(e,t){const n=e;n.setSinkId?n.setSinkId(t).then(()=>{r.A.info(`Speaker device set to: ${t}`)}).catch(e=>{r.A.error(`Failed to set speaker device: ${t}`,r.A.serialiseError(e))}):r.A.error("setSinkId not supported in this browser, cannot set speaker device")}handleMissingAudioElement(){const e="Error: Digital Human audio element not found, cannot play audio.";r.A.error(e),this.clientMessages?.next(new Fs.Cj(e))}startAudioStatsMonitor(e=5e3){this.stopAudioStatsMonitor(),r.A.info("Starting audio stats monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new Qs(this.stream,this.videoElement,this.audioElement)),this.audioStatsInternal=setInterval(()=>{this.audioStatsAnalyzer?.analyzeAudioStats().catch(e=>{r.A.error("Error analyzing audio stats",r.A.serialiseError(e))})},e)}stopAudioStatsMonitor(){this.audioStatsInternal&&clearInterval(this.audioStatsInternal)}startNetworkQualityMonitor(e){this.stopNetworkQualityMonitor(),r.A.info("Starting network quality monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new Qs(this.stream,this.videoElement,this.audioElement)),this.noIceServers&&r.A.info("Network indicator suppressed: session does not route through UneeQ");const t=this.noIceServers?{...e,visibility:Ws.Hidden}:e;this.videoContainerElement&&t.visibility!==Ws.Hidden&&(this.networkIndicator=new ti(this.videoContainerElement,t)),this.lastQualityLevel=_s.Good;const n=e.collectionIntervalMs??3e3;this.networkQualityInterval=setInterval(()=>{this.audioStatsAnalyzer?.collectNetworkQuality(e).then(e=>{e&&(this.networkIndicator?.update(e),this.logQualityTransition(e),this.clientMessages?.next(new Fs.N8(e)))}).catch(e=>{r.A.error("Error collecting network quality",r.A.serialiseError(e))})},n)}logQualityTransition(e){if(e.qualityLevel===this.lastQualityLevel)return;this.lastQualityLevel=e.qualityLevel;const t={qualityLevel:e.qualityLevel,videoPacketLossPercent:e.videoPacketLossPercent,audioPacketLossPercent:e.audioPacketLossPercent,roundTripTimeMs:e.roundTripTimeMs,videoJitterMs:e.videoJitterMs,frameRate:e.frameRate,videoMos:e.videoMos,audioMos:e.audioMos};e.qualityLevel===_s.Good?r.A.info("[Network] quality recovered to Good",t):r.A.warn(`[Network] quality degraded to ${e.qualityLevel}`,t)}stopNetworkQualityMonitor(){this.networkQualityInterval&&(clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0),this.networkIndicator&&(this.networkIndicator.destroy(),this.networkIndicator=void 0)}handleDataChannelOpen(){r.A.info("DataChannelOpen"),this.dataChannelOpen=!0,this.messages.next(new xs)}handleWebRtcFailed(e){this.stream?.isReconnecting()?r.A.debug("Ignoring webRtcFailed: Pixel Streaming is already reconnecting from our own call"):(r.A.error("WebRTC failed",e),this.reconnectIfSafe(e))}handleWebRtcDisconnected(e){this.stream?.isReconnecting()?r.A.debug("Ignoring webRtcDisconnected: Pixel Streaming is already reconnecting from our own call"):(r.A.warn(`WebRTC disconnected, message: ${e?.data?.eventString}, allowClickToReconnect: ${e?.data?.allowClickToReconnect}`),this.reconnectIfSafe(e))}handleWebRtcStats(e){const t=new As(e.data.aggregatedStats);this.messages.next(t);const n=e.data.aggregatedStats.inboundVideoStats?.framesDecoded??0;this.checkForFreeze(n),this.checkForImplausibleFrameSize(e.data.aggregatedStats)}checkForImplausibleFrameSize(e){const t=e.inboundVideoStats;if(this.implausibleFrameSizeLogged||!t||(n=t.frameWidth,s=t.frameHeight,!((n??0)>4096||(s??0)>4096)))return;var n,s;this.implausibleFrameSizeLogged=!0;const i=t.codecId?e.codecs?.get(t.codecId)?.mimeType:void 0;r.A.warn("[WebRTC] Decoder reported an implausible video frame size",{sessionId:this.session.id,codec:i,frameWidth:t.frameWidth,frameHeight:t.frameHeight,framesReceived:t.framesReceived,framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,userAgent:navigator.userAgent}),(e=>(e??"").toLowerCase().includes("av1"))(i)&&((e=Date.now())=>{try{window.localStorage.setItem(ni,String(e+6048e5))}catch{return}})()}checkForFreeze(e){const t=Date.now();if(0!==this.lastDecodedFrames||0!==e)if(e===this.lastDecodedFrames){this.freezeCount++;const e=((t-this.lastCheckTime)/1e3).toFixed(1);r.A.warn(`[WebRTC] Video FROZEN for ${e}s (count=${this.freezeCount})`),this.freezeCount>=this.freezeTransferThreshold&&(r.A.error(`[WebRTC] Video frozen ${this.freezeTransferThreshold} times in a row, transferring session...`),this.session.sessionTransferManager.transferSession(),this.freezeCount=0)}else this.freezeCount=0,this.lastDecodedFrames=e,this.lastCheckTime=t;else r.A.debug("[WebRTC] Waiting for first video frame...")}clearReconnectTimer(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=void 0)}scheduleReconnect(){const e=Math.min(this.baseReconnectDelayMs*Math.pow(2,this.reconnectionAttempts),this.maxReconnectDelayMs);r.A.info(`Scheduling reconnection attempt ${this.reconnectionAttempts} in ${e}ms`),this.reconnectTimeoutId=setTimeout(()=>{r.A.info(`Executing reconnection attempt ${this.reconnectionAttempts}`),this.reconnectTimeoutId=void 0,this.videoInitialized=!1,this.dataChannelOpen=!1,this.sceneReady=!1,this.audioStatsAnalyzer?.resetStats(),this.stream?.reconnect()},e)}reconnectIfSafe(e){try{this.allowReconnection&&!this.reconnectTimeoutId?(r.A.debug("Checking if should attempt reconnection after event",e),this.reconnectionAttempts<this.maxReconnectAttempts?(this.reconnectionAttempts++,this.clientMessages?.next(new Fs.fI),this.scheduleReconnect()):(r.A.info("Max reconnection attempts reached. Ending session."),this.clientMessages?.next(new Fs.JP),this.endSession(Us,!1))):r.A.warn("Reconnection already scheduled or reconnecting is disabled")}catch(e){r.A.error("Error during reconnection attempt",r.A.serialiseError(e)),this.clientMessages?.next(new Fs.Cj("Error during reconnection attempt")),this.endSession(Us,!1)}}handleDataChannelMessage(e){r.A.trace("Signaling: Received data channel message",e);try{const t=JSON.parse(e);if(void 0===t.type)throw new Error("Signaling: Engine response missing type");this.messages.next(new Ls(t))}catch(e){r.A.error("Signaling: Failed to parse engine response",r.A.serialiseError(e))}}handleIndexInQueueMessage(e){try{const t=Number(e.message);this.clientMessages?.next(new Fs.F8(t))}catch(e){r.A.error("Signaling: Failed to parse position in queue message",r.A.serialiseError(e))}}handleRendererTakenMessage(e){try{const t=e;this.currentRendererId=t.message,this.clientMessages?.next(new Fs.qo(t.message)),r.A.info("Signaling: Renderer taken event",t.message)}catch(e){r.A.error("Signaling: Failed to parse renderer taken message",r.A.serialiseError(e))}}handleWebRtcConnectedMessage(){this.clientMessages?.next(new Fs.Cl),r.A.info("Signaling: WebRTC connected")}extractRendererGoneId(e){const t=e;if(t?.rendererId)return t.rendererId;const n="string"==typeof t?.message?/^Renderer (\S+) /.exec(t.message):null;return n?.[1]}isStaleRendererMessage(e){return Boolean(e)&&Boolean(this.currentRendererId)&&e!==this.currentRendererId}handleRendererGoneEvent(e){const t=this.extractRendererGoneId(e);this.isStaleRendererMessage(t)?r.A.warn(`Signaling: Discarding renderer gone event for superseded renderer ${t}`,e):(r.A.info("Signaling: Renderer gone event",e),this.reconnectIfSafe(e))}handleSwitchRendererRequestEvent(e){const t=e;this.isStaleRendererMessage(t?.message)?r.A.warn(`Signaling: Discarding switch renderer request for superseded renderer ${t?.message}`,e):(r.A.info("Signaling: Renderer switch renderer request event",e),this.session.sessionTransferManager.transferSession())}handleCustomerConcurrencyLimitReachedMessage(e){r.A.warn("Signaling: Customer concurrency limit reached message received",e),this.clientMessages?.next(new Fs.MM)}handleRendererVersionWarningMessage(e){const t=e;r.A.warn("Signaling: session is served by an outdated renderer",t),this.clientMessages?.next(new Fs.n3(t?.rendererVersion??"",t?.latestVersion??"",t?.message??"Session is served by an outdated renderer"))}handleRendererErrorMessage(e){try{const t=e,n=t.code??-1,s=t.message??"An unknown renderer error occurred";r.A.error(`Signaling: Renderer error received - code: ${n}, message: ${s}`),this.clientMessages?.next(new Fs.j_(n,s)),this.endSession(Vs,!0)}catch(e){r.A.error("Signaling: Failed to parse renderer error message",r.A.serialiseError(e)),this.clientMessages?.next(new Fs.j_(-1,"An unknown renderer error occurred")),this.endSession(Vs,!0)}}socketSend(e){r.A.trace("Signaling: Sending socket message",e);const t=this.stream?.signallingProtocol?.transport;t?.webSocket?.send(JSON.stringify(e))}dataSend(e){const t=e.toJSON();if(t.action===Ns.A.ChatPrompt){const n=t.data?.requestId;r.A.info(`Signaling: Sending data channel message — action=chat_prompt, requestId=${n??"unknown"}`),(!(e instanceof Os.D)||e.shouldEmitPromptRequest)&&this.clientMessages?.next(new Fs.bS(t.data))}else r.A.info("Signaling: Sending data channel message",JSON.stringify(t));this.stream?.emitUIInteraction(e)}dataSendBinary(e){r.A.info("Signaling: Sending data channel binary message");const t=this.uint8ToBase64(e);this.stream?.emitUIInteraction(t)}uint8ToBase64(e){let t="";const n=e.byteLength;for(let s=0;s<n;s++)t+=String.fromCharCode(e[s]);return btoa(t)}endSession(e="sessionEndedByUser",t=!0){r.A.info("Signaling: Ending session"),this.clearReconnectTimer(),this.stopNetworkQualityMonitor(),this.socketSend({message:e,type:Ds.ClientGone,sessionId:this.config.sessionId}),this.streamDisconnect(),r.A.info("Session has ended, reason: "+e),t&&this.clientMessages?.next(new Fs.aY(e))}streamDisconnect(){r.A.info("Signaling: Disconnecting stream"),this.stopNetworkQualityMonitor(),this.stopAudioStatsMonitor(),this.allowReconnection=!1,this.clearReconnectTimer();const e=this.stream?.webRtcController?.statsTimerHandle;e&&window.clearInterval(e);const t=this.stream?.webRtcController?.peerConnectionController;if(t?.peerConnection){t.peerConnection.getReceivers=()=>[];const e=t.peerConnection;Object.defineProperty(t,"peerConnection",{get:()=>e,set:()=>{},configurable:!0})}this.stream?.disconnect(),this.dataChannelOpen=!1,this.videoInitialized=!1,this.sceneReady=!1}startSoftSwitch(){r.A.info("Signaling: Start soft switching"),this.clientMessages?.next(new Fs.sF)}stopSoftSwitch(){r.A.info("Signaling: Stop soft switching"),this.clientMessages?.next(new Fs.WQ)}}var ii;!function(e){e.NlpPromptResult="nlp_prompt_result",e.AvatarStartedSpeaking="avatar_started_speaking",e.AvatarStoppedSpeaking="avatar_stopped_speaking",e.Error="error",e.SceneReady="scene_ready",e.SpeechEvent="speech_event",e.SessionEnded="session_ended",e.SpeechStreamOpened="speech_stream_opened",e.SpeechStreamClosed="speech_stream_closed"}(ii||(ii={}));var ri,oi,ai=n(1);!function(e){e.CloseUp="close_up",e.LooseCloseUp="loose_close_up",e.TightMediumShot="tight_medium_shot",e.MediumShot="medium_shot",e.MediumFullShot="medium_full_shot",e.FullShot="full_shot"}(ri||(ri={})),function(e){e.Left="left",e.Right="right",e.Center="center",e.Centre="centre"}(oi||(oi={}));class li{position;duration;requestId;constructor(e,t=2e3,n=(0,ai.g)()){this.position=e,this.duration=t,this.requestId=n}toJSON(){return{action:Ns.A.CameraAnchor,data:{requestId:this.requestId,position:this.position,transition_duration_ms:this.duration}}}}class ci{avatarId;requestId;constructor(e,t=(0,ai.g)()){this.avatarId=e,this.requestId=t}toJSON(){return{action:Ns.A.ChangeAvatar,data:{id:this.avatarId,requestId:this.requestId}}}}class di{url;requestId;constructor(e,t=(0,ai.g)()){this.url=e,this.requestId=t}toJSON(){return{action:Ns.A.LoadBackground,data:{url:this.url,requestId:this.requestId}}}}class hi{actionName;requestId;constructor(e,t=(0,ai.g)()){this.actionName=e,this.requestId=t}toJSON(){return{action:Ns.A.TriggerAction,data:{action_name:this.actionName,requestId:this.requestId}}}}var ui=n(33);class gi{session;isTransferSessionInProgress=!1;constructor(e){this.session=e,this.addTransferSessionListener()}addTransferSessionListener(){this.isTransferSessionInProgress=!1,document.addEventListener("keydown",e=>{e.ctrlKey&&e.shiftKey&&"y"===e.key.toLowerCase()&&(r.A.info("Session transfer via keyboard shortcut triggered"),this.transferSession())})}transferSession(){this.isTransferSessionInProgress?r.A.warn("Transfer already in progress, skipping"):(this.isTransferSessionInProgress=!0,r.A.info("Beginning session transfer"),this.session.config.videoContainerElement&&(this.session.config.videoContainerElement.querySelectorAll("#freezeFrame,#streamingVideo").forEach(e=>{e.remove()}),this.session.signaling&&this.session.signaling.streamDisconnect()),this.session.createSignaling(this.session.config.videoContainerElement??document.createElement("div")).init())}switchLiveVideo(e,t){r.A.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(),r.A.info("Session transfer complete")},1e3))}}const pi=[1103,1200,1402],mi=750;class fi{config;id;signaling;messages=new j;speechRec;promptMetadata={};audioStreamId;sessionTransferManager;jwt;welcomeRequested=!1;resolutionLogged=!1;sttPausedByHost=!1;_audioUpstreamMode;constructor(e){this.config=e,this.sessionTransferManager=new gi(this),this._audioUpstreamMode=Ks(this.config.audioUpstreamMode)}get audioUpstreamMode(){return this._audioUpstreamMode}updatePromptMetadata(e){try{JSON.parse(JSON.stringify(e)),this.promptMetadata.custom=e,this.messages.next(new Fs.ss(this.promptMetadata))}catch(t){r.A.error("Error parsing custom metadata",e,r.A.serialiseError(t))}}setEnableMicrophone(e){const t=this.audioUpstreamMode;this.config.enableMicrophone=e,this.sttPausedByHost=!1;let n=!1;Xs(t)&&(this.speechRec?(e?this.speechRec.startRecognition():this.speechRec.stopRecognition(),n=!0):r.A.warn("setEnableMicrophone: STT leg is configured but speech recognition is not initialised yet")),Gs(t)&&(this.signaling?(e?this.signaling.unmuteUpstreamMic():this.signaling.muteUpstreamMic(),n=!0,Xs(t)||this.messages.next(new Fs.WY(e))):r.A.warn("setEnableMicrophone: PS leg is configured but signaling is not initialised yet")),n||r.A.warn(`setEnableMicrophone(${e}) had nothing to do in mode '${t}' — session not ready?`)}pauseSpeechRecognition(){return this.sttPausedByHost=!0,this.speechRec?this.speechRec.pause():(r.A.warn("pauseSpeechRecognition: pause intent recorded, but speech recognition is not initialised yet — nothing to pause"),!1)}resumeSpeechRecognition(){return this.sttPausedByHost=!1,this.speechRec?this.speechRec.resume():(r.A.warn("resumeSpeechRecognition: pause intent cleared, but speech recognition is not initialised yet — nothing to resume"),!1)}updateSpeechRecognitionConfig(e){return this.speechRec?.updateConfig?this.speechRec.updateConfig(e):(r.A.warn("updateSpeechRecognitionConfig: the active STT model does not support mid-session config updates"),!1)}setCameraAnchorDistance(e,t=0,n=this.signaling){this.config.cameraAnchorDistance=e,n?.dataSend(new li(e,t))}setCameraAnchorHorizontal(e,t=0,n=this.signaling){this.config.cameraAnchorHorizontal=e,n?.dataSend(new li(e,t))}changeAvatar(e,t=this.signaling){t?.dataSend(new ci(e))}loadBackground(e,t=this.signaling){t?.dataSend(new di(e))}userStartSpeaking(e=this.signaling){e?.dataSend(new ui.A(ui.f.Start))}userStopSpeaking(e=this.signaling){e?.dataSend(new ui.A(ui.f.Stop))}triggerAction(e,t=this.signaling){t?.dataSend(new hi(e))}resumeVideoPlayback(){this.signaling?.resumeVideoPlayback()}createSession(){this.messages.subscribe(e=>{if(this.config.messageHandler&&this.config.messageHandler(e),e.uneeqMessageType===Fs.Yg.SoftSwitchFinished||e.uneeqMessageType===Fs.Yg.SessionReconnectingFinished){if(!Xs(this.audioUpstreamMode))return;if(this.config.enableMicrophone&&!this.sttPausedByHost)e.uneeqMessageType===Fs.Yg.SessionReconnectingFinished?(r.A.info("Session, resuming speech recognition after reconnect"),this.speechRec?.resume()):(r.A.info("Session, restarting speech recognition after soft switch"),this.speechRec?.startRecognition());else{const t=e.uneeqMessageType===Fs.Yg.SoftSwitchFinished?"soft switch":"reconnect",n=this.sttPausedByHost?"paused by host":"microphone disabled";r.A.info(`Session, skipping speech recognition restart after ${t} (${n})`)}}}),this.id=this.config.sessionId,this.jwt=this.config.sessionToken,r.A.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")){const t=new URLSearchParams({token:this.jwt});this.config.backgroundUrl&&t.append("backgroundUrl",this.config.backgroundUrl);const n=(this.config.connectionUrl+`/session-service/v1/ws/session?${t.toString()}`).replace("http://","ws://").replace("https://","wss://");r.A.debug("Socket URL:",n);const s=new si(this,n,e);return s.messages.subscribe(e=>{this.signalingEventHandler(e,s)}),s}signalingEventHandler(e,t){switch(e.type){case hs.VideoInitialised:case hs.DataChannelOpen:this.handleSessionReady(t);break;case hs.DataChannelResponse:this.handleDataChannelMessage(e,t);break;case hs.WebRtcStats:{const t=e.stats;!this.resolutionLogged&&t.inboundVideoStats?.frameWidth&&t.inboundVideoStats?.frameHeight&&(r.A.info("Video resolution:",`${t.inboundVideoStats.frameWidth}x${t.inboundVideoStats.frameHeight}`),this.resolutionLogged=!0),this.config.webRtcStatsEmitMessages&&this.messages.next(new Fs.O$(t)),this.config.webRtcStatsLogMessages&&r.A.info("WebRTC stats",t);break}}}handleSessionReady(e){r.A.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 Fs.wf(this.id)),e.startNetworkQualityMonitor(this.config.networkIndicator??{visibility:Ws.Hidden}),this.config.webRtcStatsLogMessages&&e.startAudioStatsMonitor()},mi))}async initSpeechRecognition(e){if(!Xs(this.audioUpstreamMode))return void r.A.info(`[STT] audioUpstreamMode='${this.audioUpstreamMode}' — skipping STT provider initialisation (no STT leg in this mode).`);if(this.speechRec)return void r.A.warn("Speech recognition already initialized");let t=this.config.speechRecognitionProvider||js.Google;r.A.info(`[STT] Config speechRecognitionProvider: "${this.config.speechRecognitionProvider}", resolved provider: "${t}"`),t!==js.Google&&t!==js.Deepgram&&(r.A.warn(`Invalid speechRecognitionProvider value: "${String(t)}". Supported values are "google" or "deepgram". Defaulting to "google".`),t=js.Google,this.config.speechRecognitionProvider=js.Google),r.A.info(`[STT] Using provider: ${t}`);try{this.speechRec=await(t===js.Deepgram?this.createDeepgramSTT(e):this.createGoogleSTT(e))}catch(e){return void r.A.error("[STT] Failed to initialise speech recognition provider",r.A.serialiseError(e))}this.config.enableMicrophone&&!this.sttPausedByHost&&this.speechRec&&this.speechRec.startRecognition()}async createGoogleSTT(e){const t=this.getSpeechOptions(e);r.A.debug("Initializing Google STT (speech-recognition-service)");const{GoogleSTT:s}=await Promise.all([n.e(113),n.e(157)]).then(()=>n(157));return new s(t)}async createDeepgramSTT(e){const t=this.config.deepgramConfig||{};if(this.isFluxModel(t.model))return this.createDeepgramFluxSTT(e);r.A.debug("Initializing Deepgram STT");const s={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:e=>{this.signaling?.dataSend(e)},enableInterrupt:this.config.enableInterruptBySpeech,safetyNetTimeoutMs:t.safetyNetTimeoutMs,keyterms:t.keyterms,noDelay:t.noDelay},{DeepgramSTT:i}=await Promise.all([n.e(464),n.e(3)]).then(()=>n(3));return new i(s)}isFluxModel(e){return void 0!==e&&e.toLowerCase().startsWith("flux")}async createDeepgramFluxSTT(e){r.A.debug("Initializing Deepgram Flux STT (v2 API)");const t=this.config.deepgramConfig||{},s={connectionUrl:this.config.connectionUrl,jwtToken:e,sessionId:this.id,model:t.model,language:t.language,eotThreshold:t.eotThreshold,eagerEotThreshold:t.eagerEotThreshold,eotTimeoutMs:t.eotTimeoutMs,eagerMaxTurnDurationMs:t.eagerMaxTurnDurationMs,keyterms:t.keyterms,safetyNetTimeoutMs:t.safetyNetTimeoutMs,echoCancellation:t.microphone?.echoCancellation,noiseSuppression:t.microphone?.noiseSuppression,autoGainControl:t.microphone?.autoGainControl,microphoneDeviceId:this.config.microphoneDeviceId,promptMetadata:this.promptMetadata,messages:this.messages,sendMessage:e=>{this.signaling?.dataSend(e)}},{DeepgramFluxSTT:i}=await Promise.all([n.e(464),n.e(363)]).then(()=>n(363));return new i(s)}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:e=>{this.signaling?.dataSend(e)},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(r.A.debug("Processing data channel message",e),e.msg.type){case ii.NlpPromptResult:this.messages.next(new Fs.nD(e.msg));break;case ii.AvatarStartedSpeaking:this.messages.next(new Fs.yr);break;case ii.AvatarStoppedSpeaking:this.messages.next(new Fs.kS);break;case ii.Error:r.A.error(`an error has occurred - ${JSON.stringify(e.msg)}`),this.handleChannelMessageError(e.msg);break;case ii.SceneReady:r.A.debug("Scene is ready"),t.sceneReady=!0,this.handleSessionReady(t),this.messages.next(new Fs.Ln);break;case ii.SpeechEvent:this.messages.next(new Fs.Qd(e.msg));break;case ii.SessionEnded:{const t="UserInactivity"===e.msg.reason?"sessionEndedDueToInactivity":e.msg.reason;this.signaling?.endSession(t),this.signaling=void 0;break}case ii.SpeechStreamOpened:this.audioStreamId=e.msg.streamId;break;case ii.SpeechStreamClosed:e.msg.streamId===this.audioStreamId?this.audioStreamId=void 0:r.A.warn("Received SpeechStreamClosed message for unexpected streamId",e.msg.streamId)}}handleChannelMessageError(e){const t=e?.message?.trim()||"An unknown error occurred";e&&pi.includes(e.code)?this.messages.next(new Fs.Uh(e)):this.messages.next(new Fs.Cj(t))}sendWelcomePrompt(){r.A.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 Os.D(this.config.welcomePrompt,this.promptMetadata)))}listenForTabClosure(){window.addEventListener("beforeunload",()=>{r.A.info("Window unload detected, ending session."),this.signaling?.endSession(),this.signaling=void 0})}}class yi{prompt;requestId;constructor(e,t=(0,ai.g)()){this.prompt=e,this.requestId=t}toJSON(){return{action:Ns.A.Speak,data:{requestId:this.requestId,prompt:this.prompt}}}}var vi,Si=n(58);!function(e){e.Open="open",e.Close="close",e.Interrupt="interrupt"}(vi||(vi={}));class bi{action;streamId;metadata;requestId;constructor(e,t,n={},s=(0,ai.g)()){this.action=e,this.streamId=t,this.metadata=n,this.requestId=s}toJSON(){return{action:Ns.A.SpeechStream,data:{requestId:this.requestId,action:this.action,streamId:this.streamId,metadata:this.metadata}}}}class wi{command;enabled;category;verbosity;constructor(e,t,n,s){this.command=e,this.enabled=t,this.category=n,this.verbosity=s}toJSON(){const e={command:this.command,enabled:this.enabled};return void 0!==this.category&&(e.category=this.category),void 0!==this.verbosity&&(e.verbosity=this.verbosity),{action:Ns.A.ExecuteCommand,data:e}}}class Ci{config;session;messageSubscription;constructor(e){this.config=e,r.A.setLevel(e.logLevel??"info")}init(){if(this.session){const e="Cannot initialize: session already active. Call endSession() first.";throw r.A.warn(e),new Error(e)}if(void 0!==this.config.audioUpstreamMode&&"speech-recognition-service"!==(e=this.config.audioUpstreamMode)&&"pixel-streaming"!==e&&"both"!==e){const e=`Invalid audioUpstreamMode: '${String(this.config.audioUpstreamMode)}'. Allowed: 'speech-recognition-service' | 'pixel-streaming' | 'both'.`;throw r.A.error(e),new Error(e)}var e;r.A.info(`Initializing Uneeq with config:', ${JSON.stringify(this.config)}, for UserAgent: ${navigator.userAgent}`),this.session=new fi(this.config),this.session.createSession(),this.messageSubscription=this.session.messages.subscribe(e=>{e.uneeqMessageType===Fs.Yg.SessionEnded&&(r.A.info("Session ended, resetting session state"),this.resetSessionState())})}isSessionActive(){return void 0!==this.session}ensureSessionExists(){return!!this.session?.id||(r.A.warn("Cannot perform action, session has not started."),!1)}chatPrompt(e){e&&""!==e.trim()&&this.ensureSessionExists()&&this.session?.signaling?.dataSend(new Os.D(e,this.session?.promptMetadata))}speak(e){e&&""!==e.trim()&&this.ensureSessionExists()&&this.session?.signaling?.dataSend(new yi(e))}openAudioStream(){const e=this.session;this.ensureSessionExists()&&e?.signaling?.dataSend(new bi(vi.Open,e?.audioStreamId))}closeAudioStream(){const e=this.session;this.ensureSessionExists()&&void 0!==e?.audioStreamId&&e.signaling?.dataSend(new bi(vi.Close,e.audioStreamId))}interruptAudioStream(){const e=this.session;this.ensureSessionExists()&&void 0!==e?.audioStreamId&&e.signaling?.dataSend(new bi(vi.Interrupt,e.audioStreamId))}async speakAudio(e){this.ensureSessionExists()&&await async function(e,t){try{if(void 0===e?.audioStreamId)return void r.A.warn("Audio stream is not open | Call openAudioStream() first");let n;if("string"==typeof t){const e="undefined"!=typeof atob?atob(t):Buffer.from(t,"base64").toString("binary");n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t)}else if(t instanceof Uint8Array)n=t;else{if(!("undefined"!=typeof Blob&&t instanceof Blob))return void r.A.error("speakAudio: Unsupported audio type",t);{const e=await t.arrayBuffer();n=new Uint8Array(e)}}const s=Uint8Array.from([1]),i=Uint8Array.from([e.audioStreamId]),o=new Uint8Array(2+n.length);o.set(s,0),o.set(i,1),o.set(n,2),e.signaling?.dataSendBinary(o)}catch(e){r.A.error("speakAudioSend: Error sending audio",e)}}(this.session,e)}cameraAnchorDistance(e,t){this.ensureSessionExists()&&this.session?.setCameraAnchorDistance(e,t)}cameraAnchorHorizontal(e,t){this.ensureSessionExists()&&this.session?.setCameraAnchorHorizontal(e,t)}changeAvatar(e){e&&""!==e.trim()&&this.ensureSessionExists()&&this.session?.changeAvatar(e)}loadBackground(e){e&&""!==e.trim()&&this.ensureSessionExists()&&this.session?.loadBackground(e)}userStartSpeaking(){this.ensureSessionExists()&&this.session?.userStartSpeaking()}userStopSpeaking(){this.ensureSessionExists()&&this.session?.userStopSpeaking()}triggerAction(e){e&&""!==e.trim()&&this.ensureSessionExists()&&this.session?.triggerAction(e)}resumeVideoPlayback(){this.session?.resumeVideoPlayback()}executeCommand(e,t,n,s){this.ensureSessionExists()&&this.session?.signaling?.dataSend(new wi(e,t,n,s))}endSession(){this.ensureSessionExists()&&(this.releaseMicrophone(),this.session?.signaling?.endSession(),this.resetSessionState())}releaseMicrophone(){try{this.session?.speechRec?.stopRecognition()}catch(e){r.A.warn("endSession: error releasing microphone",r.A.serialiseError(e))}}resetSessionState(){this.messageSubscription?.unsubscribe(),this.messageSubscription=void 0,this.session=void 0}unmuteDigitalHuman(){this.ensureSessionExists()&&(this.session?.signaling?.playAudioElement(),r.A.debug("Unmuted digital human."))}muteDigitalHuman(){this.ensureSessionExists()&&(this.session?.signaling?.pauseAudioElement(),r.A.debug("Muted digital human."))}stopSpeaking(){this.ensureSessionExists()&&this.session?.signaling?.dataSend(new Si.f)}setCustomPromptMetadata(e){this.ensureSessionExists()&&this.session?.updatePromptMetadata(e)}enableMicrophone(e=!0){this.ensureSessionExists()&&this.session?.setEnableMicrophone(e)}pauseSpeechRecognition(){if(!this.ensureSessionExists())return!1;const e=Ks(this.config.audioUpstreamMode);if(!Xs(e))return r.A.warn(`pauseSpeechRecognition called in '${e}' mode — no STT leg to pause; ignoring. Use muteUpstreamMic() to silence the PS mic track.`),!1;const t=this.session?.pauseSpeechRecognition()??!1;return t instanceof Promise||t}resumeSpeechRecognition(){if(!this.ensureSessionExists())return!1;const e=Ks(this.config.audioUpstreamMode);if(!Xs(e))return r.A.warn(`resumeSpeechRecognition called in '${e}' mode — no STT leg to resume; ignoring. Use unmuteUpstreamMic() to re-enable the PS mic track.`),!1;const t=this.session?.resumeSpeechRecognition()??!1;return t instanceof Promise||t}updateSpeechRecognitionConfig(e){return!!this.ensureSessionExists()&&(this.session?.updateSpeechRecognitionConfig(e)??!1)}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,r.A.info(`Setting up WebRtcStats: webRtcStatsEmitMessages: ${this.session.config.webRtcStatsEmitMessages}, webRtcStatsLogMessages: ${this.session.config.webRtcStatsLogMessages}`),t?this.session.signaling?.startAudioStatsMonitor():this.session.signaling?.stopAudioStatsMonitor())}setNetworkIndicatorEnabled(e){this.ensureSessionExists()&&(e?this.session?.signaling?.startNetworkQualityMonitor(e):this.session?.signaling?.stopNetworkQualityMonitor())}}var Mi=n(508);return window.Uneeq=Ci,s})());
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("Uneeq",[],t):"object"==typeof exports?exports.Uneeq=t():e.Uneeq=t()}(Object("undefined"!=typeof self?self:this),()=>(()=>{"use strict";var e={514(e,t,n){n.d(t,{A:()=>o});var s=n(508);const i="UneeQ SDK: ",r={[s.$.Fatal]:0,[s.$.Error]:1,[s.$.Warn]:2,[s.$.Info]:3,[s.$.Debug]:4,[s.$.Trace]:5};class o{static currentLevel=s.$.Info;static shouldLog(e){return r[e]<=r[o.currentLevel]}static formatLogMessage(e,t){return 0===t.length?i+e:i+e+" | "+JSON.stringify(t)}static fatal(e,...t){o.shouldLog(s.$.Fatal)&&console.error(o.formatLogMessage(e,t))}static error(e,...t){o.shouldLog(s.$.Error)&&console.error(o.formatLogMessage(e,t))}static warn(e,...t){o.shouldLog(s.$.Warn)&&console.warn(o.formatLogMessage(e,t))}static info(e,...t){o.shouldLog(s.$.Info)&&console.info(o.formatLogMessage(e,t))}static debug(e,...t){o.shouldLog(s.$.Debug)&&console.debug(o.formatLogMessage(e,t))}static trace(e,...t){o.shouldLog(s.$.Trace)&&console.debug(o.formatLogMessage(e,t))}static setLevel(e){Object.values(s.$).includes(e)?(e!=s.$.Trace&&e!=s.$.Debug||console.warn(i+"you may need to set your browser's console settings to show verbose logs to be able to see debug or trace logs"),o.currentLevel=e):o.currentLevel=s.$.Info}static serialiseError(e){return JSON.stringify(e,Object.getOwnPropertyNames(e))}}},1(e,t,n){function s(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}n.d(t,{g:()=>s})},508(e,t,n){var s;n.d(t,{$:()=>s}),function(e){e.Fatal="fatal",e.Error="error",e.Warn="warn",e.Info="info",e.Debug="debug",e.Trace="trace"}(s||(s={}))},838(e,t,n){var s;n.d(t,{Cj:()=>f,Cl:()=>N,E1:()=>a,F8:()=>p,JP:()=>x,Ln:()=>P,M8:()=>C,MA:()=>W,MM:()=>U,N8:()=>B,O$:()=>m,Qd:()=>S,Tu:()=>M,Uh:()=>v,Ux:()=>o,WQ:()=>O,WY:()=>T,XC:()=>w,Yg:()=>s,_4:()=>l,aY:()=>b,bS:()=>R,co:()=>i,fI:()=>L,fP:()=>y,fh:()=>r,im:()=>c,j_:()=>V,kS:()=>h,n3:()=>_,nD:()=>k,qo:()=>I,qw:()=>F,sF:()=>D,ss:()=>E,tc:()=>u,wf:()=>g,xQ:()=>A,yr:()=>d}),function(e){e.AvatarAnswer="AvatarAnswer",e.AvatarInterrupted="AvatarInterrupted",e.AvatarStartedSpeaking="AvatarStartedSpeaking",e.AvatarStoppedSpeaking="AvatarStoppedSpeaking",e.CustomerConcurrencyLimitReached="CustomerConcurrencyLimitReached",e.CustomMetadataUpdated="CustomMetadataUpdated",e.DeviceError="DeviceError",e.DigitalHumanMuted="DigitalHumanMuted",e.DigitalHumanPlayedInMutedModeSuccess="DigitalHumanPlayedInMutedModeSuccess",e.DigitalHumanUnmuted="DigitalHumanUnmuted",e.EnableMicrophoneUpdated="EnableMicrophoneUpdated",e.NetworkQuality="NetworkQuality",e.PromptRequest="PromptRequest",e.PromptResult="PromptResult",e.RendererError="RendererError",e.RendererVersionWarning="RendererVersionWarning",e.SceneReady="SceneReady",e.SessionBackendError="SessionBackendError",e.SessionConnecting="SessionConnecting",e.SessionDisconnected="SessionDisconnected",e.SessionEnded="SessionEnded",e.SessionError="SessionError",e.SessionLive="SessionLive",e.SessionReconnecting="SessionReconnecting",e.SessionReconnectingFinished="SessionReconnectingFinished",e.SoftSwitchFinished="SoftSwitchFinished",e.SoftSwitchStarting="SoftSwitchStarting",e.SpeechEvent="SpeechEvent",e.SpeechRecognitionTransientError="SpeechRecognitionTransientError",e.SpeechTranscription="SpeechTranscription",e.UserStartedSpeaking="UserStartedSpeaking",e.UserStoppedSpeaking="UserStoppedSpeaking",e.VadInterruptionAllowed="VadInterruptionAllowed",e.VideoAutoplayBlocked="VideoAutoplayBlocked",e.VideoLayoutConfiguring="VideoLayoutConfiguring",e.WaitingInQueue="WaitingInQueue",e.WebRtcConnected="webRtcConnected",e.WebRtcStats="WebRtcStats"}(s||(s={}));class i{error;uneeqMessageType=s.DeviceError;constructor(e){this.error=e}}class r{answer;answerAvatar;answerSpeech;transcriptId;uneeqMessageType=s.AvatarAnswer;constructor(e,t,n,s){this.answer=e,this.answerAvatar=t,this.answerSpeech=n,this.transcriptId=s}}class o{speechTranscription;uneeqMessageType=s.SpeechTranscription;constructor(e){this.speechTranscription=e}}class a{interruptionAllowed;uneeqMessageType=s.VadInterruptionAllowed;constructor(e){this.interruptionAllowed=e}}class l{uneeqMessageType=s.UserStartedSpeaking}class c{uneeqMessageType=s.UserStoppedSpeaking}class d{uneeqMessageType=s.AvatarStartedSpeaking}class h{uneeqMessageType=s.AvatarStoppedSpeaking}class u{transcriptId;uneeqMessageType=s.AvatarInterrupted;constructor(e){this.transcriptId=e}}class g{sessionId;uneeqMessageType=s.SessionLive;constructor(e){this.sessionId=e}}class p{position;uneeqMessageType=s.WaitingInQueue;constructor(e){this.position=e}}class m{stats;uneeqMessageType=s.WebRtcStats;constructor(e){this.stats=e}}class f{error;uneeqMessageType=s.SessionError;constructor(e){this.error=e}}class y{error;uneeqMessageType=s.SpeechRecognitionTransientError;constructor(e){this.error=e}}class v{error;uneeqMessageType=s.SessionBackendError;constructor(e){this.error=e}}class S{speechEvent;uneeqMessageType=s.SpeechEvent;constructor(e){this.speechEvent=e}}class b{reason;uneeqMessageType=s.SessionEnded;constructor(e){this.reason=e}}class w{uneeqMessageType=s.DigitalHumanPlayedInMutedModeSuccess;msg="Digital Human was successfully played in muted mode. After the user interacts with the page you will need to call unmuteDigitalHuman() to unmute the video."}class C{uneeqMessageType=s.DigitalHumanUnmuted}class M{uneeqMessageType=s.DigitalHumanMuted}class T{enabled;uneeqMessageType=s.EnableMicrophoneUpdated;constructor(e){this.enabled=e}}class E{chatMetadata;uneeqMessageType=s.CustomMetadataUpdated;constructor(e){this.chatMetadata=e}}class R{promptRequest;uneeqMessageType=s.PromptRequest;constructor(e){this.promptRequest=e}}class k{promptResult;uneeqMessageType=s.PromptResult;constructor(e){this.promptResult=e}}class P{uneeqMessageType=s.SceneReady}class I{rendererId;uneeqMessageType=s.SessionConnecting;constructor(e){this.rendererId=e}}class x{uneeqMessageType=s.SessionDisconnected}class L{uneeqMessageType=s.SessionReconnecting}class A{uneeqMessageType=s.SessionReconnectingFinished}class D{uneeqMessageType=s.SoftSwitchStarting}class O{uneeqMessageType=s.SoftSwitchFinished}class F{uneeqMessageType=s.VideoLayoutConfiguring}class N{uneeqMessageType=s.WebRtcConnected}class U{uneeqMessageType=s.CustomerConcurrencyLimitReached}class B{metrics;uneeqMessageType=s.NetworkQuality;constructor(e){this.metrics=e}}class V{code;error;uneeqMessageType=s.RendererError;constructor(e,t){this.code=e,this.error=t}}class _{rendererVersion;latestVersion;message;uneeqMessageType=s.RendererVersionWarning;constructor(e,t,n){this.rendererVersion=e,this.latestVersion=t,this.message=n}}class W{uneeqMessageType=s.VideoAutoplayBlocked}},992(e,t,n){var s;n.d(t,{A:()=>s}),function(e){e.CameraAnchor="camera_to_anchor",e.ChangeAvatar="change_avatar",e.ChatPrompt="chat_prompt",e.ExecuteCommand="execute_command",e.InterimTranscript="interim_transcript",e.LoadBackground="load_background",e.StopSpeaking="stop_speaking",e.Speak="speak",e.SpeechStream="speech_stream",e.TriggerAction="trigger_action",e.UserSpeaking="user_speaking"}(s||(s={}))},388(e,t,n){n.d(t,{D:()=>r});var s=n(992),i=n(1);class r{prompt;metadata;requestId;shouldEmitPromptRequest;constructor(e,t,n=(0,i.g)(),s=!0){this.prompt=e,this.metadata=t,this.requestId=n,this.shouldEmitPromptRequest=s}toJSON(){return{action:s.A.ChatPrompt,data:{requestId:this.requestId,prompt:this.prompt,metadata:this.metadata}}}}},58(e,t,n){n.d(t,{f:()=>r});var s=n(992),i=n(1);class r{requestId;constructor(e=(0,i.g)()){this.requestId=e}toJSON(){return{action:s.A.StopSpeaking,data:{requestId:this.requestId}}}}},33(e,t,n){n.d(t,{A:()=>o,f:()=>s});var s,i=n(992),r=n(1);!function(e){e.Start="start",e.Stop="stop"}(s||(s={}));class o{state;requestId;constructor(e,t=(0,r.g)()){this.state=e,this.requestId=t}toJSON(){return{action:i.A.UserSpeaking,data:{requestId:this.requestId,event:this.state}}}}}};const t={};function n(s){const i=t[s];if(void 0!==i)return i.exports;const r=t[s]={exports:{}};return e[s].call(r.exports,r,r.exports,n),r.exports}n.m=e,n.cw=e=>{var t;return()=>{if(e){var n=e;e=0,t={exports:{}},n.call(t.exports,t,t.exports)}return t.exports}},(()=>{const e=Object.getPrototypeOf;let t;n.t=function(s,i){if(1&i&&(s=this(s)),8&i)return s;if("object"==typeof s&&s){if(4&i&&s.__esModule)return s;if(16&i&&"function"==typeof s.then)return s}const r=Object.create(null);n.r(r);const o={};t=t||[null,e({}),e([]),e(e)];for(var a=2&i&&s;("object"==typeof a||"function"==typeof a)&&!~t.indexOf(a);a=e(a))Object.getOwnPropertyNames(a).forEach(e=>o[e]=()=>s[e]);return o.default=()=>s,n.d(r,o),r}})(),n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.f={},n.e=e=>Promise.all(Object.keys(n.f).reduce((t,s)=>(n.f[s](e,t),t),[])),n.u=e=>e+".index.js",n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e={},t="Uneeq:";n.l=(s,i,r,o)=>{if(e[s])return void e[s].push(i);let a,l;if(void 0!==r){const e=document.getElementsByTagName("script");for(var c=0;c<e.length;c++){const n=e[c];if(n.getAttribute("src")==s||n.getAttribute("data-webpack")==t+r){a=n;break}}}a||(l=!0,a=document.createElement("script"),a.charset="utf-8",n.nc&&a.setAttribute("nonce",n.nc),a.setAttribute("data-webpack",t+r),a.src=s),e[s]=[i];const d=(t,n)=>{a.onerror=a.onload=null,clearTimeout(h);const i=e[s];if(delete e[s],a.parentNode?.removeChild(a),i?.forEach(e=>e(n)),t)return t(n)},h=setTimeout(d.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=d.bind(null,a.onerror),a.onload=d.bind(null,a.onload),l&&document.head.appendChild(a)}})(),n.r=e=>{Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{let e;n.g.importScripts&&(e=n.g.location+"");const t=n.g.document;if(!e&&t&&("SCRIPT"===t.currentScript?.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){const n=t.getElementsByTagName("script");if(n.length){let t=n.length-1;for(;t>-1&&(!e||!/^https?:/.test(e));)e=n[t--].src}}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:|[?#].*$/g,"").replace(/\/[^/]+$/,"/"),n.p=e})(),(()=>{const e={792:0};n.f.j=(t,s)=>{let i=n.o(e,t)?e[t]:void 0;if(0!==i)if(i)s.push(i[2]);else{const r=new Promise((n,s)=>i=e[t]=[n,s]);s.push(i[2]=r);const o=new Error,a=s=>{if(n.o(e,t)&&(i=e[t],0!==i&&(e[t]=void 0),i)){const e=s&&("load"===s.type?"missing":s.type),n=s&&s.target&&s.target.src;o.message="Loading chunk "+t+" failed.\n("+e+": "+n+")",o.name="ChunkLoadError",o.type=e,o.request=n,o.event=s,i[1](o)}};n.l(n.p+n.u(t),a,"chunk-"+t,t)}};const t=(t,s)=>{let[i,r,o]=s;var a,l,c=0;if(i.some(t=>0!==e[t])){for(a in r)n.o(r,a)&&(n.m[a]=r[a]);o&&o(n)}for(t&&t(s);c<i.length;c++)l=i[c],n.o(e,l)&&e[l]&&e[l][0](),e[l]=0},s=Object("undefined"!=typeof self?self:this).webpackChunkUneeq=Object("undefined"!=typeof self?self:this).webpackChunkUneeq||[];s.forEach(t.bind(null,0)),s.push=t.bind(null,s.push.bind(s))})();let s={};n.r(s),n.d(s,{AvatarAnswerMessage:()=>Fs.fh,AvatarInterruptedMessage:()=>Fs.tc,AvatarStartedSpeakingMessage:()=>Fs.yr,AvatarStoppedSpeakingMessage:()=>Fs.kS,CameraAnchorDistance:()=>ri,CameraAnchorHorizontal:()=>oi,CustomMetadataUpdated:()=>Fs.ss,CustomerConcurrencyLimitReachedMessage:()=>Fs.MM,DeviceErrorMessage:()=>Fs.co,DigitalHumanMuted:()=>Fs.Tu,DigitalHumanPlayedInMutedModeSuccess:()=>Fs.XC,DigitalHumanUnmuted:()=>Fs.M8,EnableMicrophoneUpdatedMessage:()=>Fs.WY,LogLevel:()=>Mi.$,NetworkIndicatorPopupTrigger:()=>Hs,NetworkIndicatorPosition:()=>$s,NetworkIndicatorVisibility:()=>Ws,NetworkQualityLevel:()=>_s,NetworkQualityMessage:()=>Fs.N8,PromptRequestMessage:()=>Fs.bS,PromptResultMessage:()=>Fs.nD,RendererErrorMessage:()=>Fs.j_,SceneReadyMessage:()=>Fs.Ln,SessionBackendErrorMessage:()=>Fs.Uh,SessionConnectingMessage:()=>Fs.qo,SessionDisconnectedMessage:()=>Fs.JP,SessionEndedMessage:()=>Fs.aY,SessionErrorMessage:()=>Fs.Cj,SessionLiveMessage:()=>Fs.wf,SessionReconnectingFinishedMessage:()=>Fs.xQ,SessionReconnectingMessage:()=>Fs.fI,SoftSwitchStartingMessage:()=>Fs.sF,SoftSwitchStoppingMessage:()=>Fs.WQ,SpeechEventMessage:()=>Fs.Qd,SpeechRecognitionProvider:()=>js,SpeechRecognitionTransientErrorMessage:()=>Fs.fP,SpeechTranscriptionMessage:()=>Fs.Ux,UNEEQ_JS_SDK_VERSION:()=>"3.23.5",Uneeq:()=>Ci,UneeqMessageType:()=>Fs.Yg,UserStartedSpeakingMessage:()=>Fs._4,UserStoppedSpeakingMessage:()=>Fs.im,VadInterruptionAllowedMessage:()=>Fs.E1,VideoAutoplayBlockedMessage:()=>Fs.MA,VideoLayoutConfiguringMessage:()=>Fs.qw,WaitingInQueueMessage:()=>Fs.F8,WebRtcConnectedMessage:()=>Fs.Cl,WebRtcStatsMessage:()=>Fs.O$,resolveAudioUpstreamMode:()=>Ks});var i=n.cw(function(e,t){const n={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};n.localCName=n.generateIdentifier(),n.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},n.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},n.getDescription=function(e){const t=n.splitSections(e);return t&&t[0]},n.getMediaSections=function(e){const t=n.splitSections(e);return t.shift(),t},n.matchPrefix=function(e,t){return n.splitLines(e).filter(e=>0===e.indexOf(t))},n.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":n.relatedAddress=t[e+1];break;case"rport":n.relatedPort=parseInt(t[e+1],10);break;case"tcptype":n.tcpType=t[e+1];break;case"ufrag":n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:void 0===n[t[e]]&&(n[t[e]]=t[e+1])}return n},n.writeCandidate=function(e){const t=[];t.push(e.foundation);const n=e.component;"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const s=e.type;return t.push("typ"),t.push(s),"host"!==s&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},n.parseIceOptions=function(e){return e.substring(14).split(" ")},n.parseRtpMap=function(e){let t=e.substring(9).split(" ");const n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},n.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\r\n"},n.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},n.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},n.parseFmtp=function(e){const t={};let n;const s=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<s.length;e++)n=s[e].trim().split("="),t[n[0].trim()]=n[1];return t},n.writeFmtp=function(e){let t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const s=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?s.push(t+"="+e.parameters[t]):s.push(t)}),t+="a=fmtp:"+n+" "+s.join(";")+"\r\n"}return t},n.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},n.writeRtcpFb=function(e){let t="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},n.parseSsrcMedia=function(e){const t=e.indexOf(" "),n={ssrc:parseInt(e.substring(7,t),10)},s=e.indexOf(":",t);return s>-1?(n.attribute=e.substring(t+1,s),n.value=e.substring(s+1)):n.attribute=e.substring(t+1),n},n.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},n.getMid=function(e){const t=n.matchPrefix(e,"a=mid:")[0];if(t)return t.substring(6)},n.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},n.getDtlsParameters=function(e,t){return{role:"auto",fingerprints:n.matchPrefix(e+t,"a=fingerprint:").map(n.parseFingerprint)}},n.writeDtlsParameters=function(e,t){let n="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),n},n.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},n.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?n.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},n.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},n.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},n.getCryptoParameters=function(e,t){return n.matchPrefix(e+t,"a=crypto:").map(n.parseCryptoLine)},n.getIceParameters=function(e,t){const s=n.matchPrefix(e+t,"a=ice-ufrag:")[0],i=n.matchPrefix(e+t,"a=ice-pwd:")[0];return s&&i?{usernameFragment:s.substring(12),password:i.substring(10)}:null},n.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},n.parseRtpParameters=function(e){const t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=n.splitLines(e)[0].split(" ");t.profile=s[2];for(let i=3;i<s.length;i++){const r=s[i],o=n.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(o){const s=n.parseRtpMap(o),i=n.matchPrefix(e,"a=fmtp:"+r+" ");switch(s.parameters=i.length?n.parseFmtp(i[0]):{},s.rtcpFeedback=n.matchPrefix(e,"a=rtcp-fb:"+r+" ").map(n.parseRtcpFb),t.codecs.push(s),s.name.toUpperCase()){case"RED":case"ULPFEC":t.fecMechanisms.push(s.name.toUpperCase())}}}n.matchPrefix(e,"a=extmap:").forEach(e=>{t.headerExtensions.push(n.parseExtmap(e))});const i=n.matchPrefix(e,"a=rtcp-fb:* ").map(n.parseRtcpFb);return t.codecs.forEach(e=>{i.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),t},n.writeRtpDescription=function(e,t){let s="";s+="m="+e+" ",s+=t.codecs.length>0?"9":"0",s+=" "+(t.profile||"UDP/TLS/RTP/SAVPF")+" ",s+=t.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",s+="c=IN IP4 0.0.0.0\r\n",s+="a=rtcp:9 IN IP4 0.0.0.0\r\n",t.codecs.forEach(e=>{s+=n.writeRtpMap(e),s+=n.writeFmtp(e),s+=n.writeRtcpFb(e)});let i=0;return t.codecs.forEach(e=>{e.maxptime>i&&(i=e.maxptime)}),i>0&&(s+="a=maxptime:"+i+"\r\n"),t.headerExtensions&&t.headerExtensions.forEach(e=>{s+=n.writeExtmap(e)}),s},n.parseRtpEncodingParameters=function(e){const t=[],s=n.parseRtpParameters(e),i=-1!==s.fecMechanisms.indexOf("RED"),r=-1!==s.fecMechanisms.indexOf("ULPFEC"),o=n.matchPrefix(e,"a=ssrc:").map(e=>n.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=o.length>0&&o[0].ssrc;let l;const c=n.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));c.length>0&&c[0].length>1&&c[0][0]===a&&(l=c[0][1]),s.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let n={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&l&&(n.rtx={ssrc:l}),t.push(n),i&&(n=JSON.parse(JSON.stringify(n)),n.fec={ssrc:a,mechanism:r?"red+ulpfec":"red"},t.push(n))}}),0===t.length&&a&&t.push({ssrc:a});let d=n.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,t.forEach(e=>{e.maxBitrate=d})),t},n.parseRtcpParameters=function(e){const t={},s=n.matchPrefix(e,"a=ssrc:").map(e=>n.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];s&&(t.cname=s.value,t.ssrc=s.ssrc);const i=n.matchPrefix(e,"a=rtcp-rsize");t.reducedSize=i.length>0,t.compound=0===i.length;const r=n.matchPrefix(e,"a=rtcp-mux");return t.mux=r.length>0,t},n.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},n.parseMsid=function(e){let t;const s=n.matchPrefix(e,"a=msid:");if(1===s.length)return t=s[0].substring(7).split(" "),{stream:t[0],track:t[1]};const i=n.matchPrefix(e,"a=ssrc:").map(e=>n.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return i.length>0?(t=i[0].value.split(" "),{stream:t[0],track:t[1]}):void 0},n.parseSctpDescription=function(e){const t=n.parseMLine(e),s=n.matchPrefix(e,"a=max-message-size:");let i;s.length>0&&(i=parseInt(s[0].substring(19),10)),isNaN(i)&&(i=65536);const r=n.matchPrefix(e,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:t.fmt,maxMessageSize:i};const o=n.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},n.writeSctpDescription=function(e,t){let n=[];return n="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},n.generateSessionId=function(){return Math.random().toString().substr(2,22)},n.writeSessionBoilerplate=function(e,t,s){let i;const r=void 0!==t?t:2;return i=e||n.generateSessionId(),"v=0\r\no="+(s||"thisisadapterortc")+" "+i+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},n.getDirection=function(e,t){const s=n.splitLines(e);for(let e=0;e<s.length;e++)switch(s[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[e].substring(2)}return t?n.getDirection(t):"sendrecv"},n.getKind=function(e){return n.splitLines(e)[0].split(" ")[0].substring(2)},n.isRejected=function(e){return"0"===e.split(" ",2)[1]},n.parseMLine=function(e){const t=n.splitLines(e)[0].substring(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}},n.parseOLine=function(e){const t=n.matchPrefix(e,"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]}},n.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const t=n.splitLines(e);for(let e=0;e<t.length;e++)if(t[e].length<2||"="!==t[e].charAt(1))return!1;return!0},e.exports=n}),r=n(514),o=function(e,t){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},o(e,t)};function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function l(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],s=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function c(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var s,i,r=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(e){i={error:e}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return o}function d(e,t,n){if(n||2===arguments.length)for(var s,i=0,r=t.length;i<r;i++)!s&&i in t||(s||(s=Array.prototype.slice.call(t,0,i)),s[i]=t[i]);return e.concat(s||Array.prototype.slice.call(t))}function h(e){return"function"==typeof e}function u(e){var t=e(function(e){Error.call(e),e.stack=(new Error).stack});return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}Object.create,Object.create;var g=u(function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map(function(e,t){return t+1+") "+e.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}});function p(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var m=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,n,s,i;if(!this.closed){this.closed=!0;var r=this._parentage;if(r)if(this._parentage=null,Array.isArray(r))try{for(var o=l(r),a=o.next();!a.done;a=o.next())a.value.remove(this)}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else r.remove(this);var u=this.initialTeardown;if(h(u))try{u()}catch(e){i=e instanceof g?e.errors:[e]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var m=l(p),f=m.next();!f.done;f=m.next()){var y=f.value;try{v(y)}catch(e){i=null!=i?i:[],e instanceof g?i=d(d([],c(i)),c(e.errors)):i.push(e)}}}catch(e){n={error:e}}finally{try{f&&!f.done&&(s=m.return)&&s.call(m)}finally{if(n)throw n.error}}}if(i)throw new g(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)v(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&p(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&p(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}(),f=m.EMPTY;function y(e){return e instanceof m||e&&"closed"in e&&h(e.remove)&&h(e.add)&&h(e.unsubscribe)}function v(e){h(e)?e():e.unsubscribe()}var S=null,b=null,w=void 0,C=!1,M=!1,T={setTimeout:function(e,t){for(var n=[],s=2;s<arguments.length;s++)n[s-2]=arguments[s];var i=T.delegate;return(null==i?void 0:i.setTimeout)?i.setTimeout.apply(i,d([e,t],c(n))):setTimeout.apply(void 0,d([e,t],c(n)))},clearTimeout:function(e){var t=T.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function E(){}var R=k("C",void 0,void 0);function k(e,t,n){return{kind:e,value:t,error:n}}var P=null;function I(e){if(C){var t=!P;if(t&&(P={errorThrown:!1,error:null}),e(),t){var n=P,s=n.errorThrown,i=n.error;if(P=null,s)throw i}}else e()}var x=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,y(t)&&t.add(n)):n.destination=U,n}return a(t,e),t.create=function(e,t,n){return new O(e,t,n)},t.prototype.next=function(e){this.isStopped?N(function(e){return k("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?N(k("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?N(R,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(m),L=Function.prototype.bind;function A(e,t){return L.call(e,t)}var D=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){F(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){F(e)}else F(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){F(e)}},e}(),O=function(e){function t(t,n,s){var i,r,o=e.call(this)||this;return h(t)||!t?i={next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=s?s:void 0}:o&&M?((r=Object.create(t)).unsubscribe=function(){return o.unsubscribe()},i={next:t.next&&A(t.next,r),error:t.error&&A(t.error,r),complete:t.complete&&A(t.complete,r)}):i=t,o.destination=new D(i),o}return a(t,e),t}(x);function F(e){var t;C?(t=e,C&&P&&(P.errorThrown=!0,P.error=t)):function(e){T.setTimeout(function(){if(!S)throw e;S(e)})}(e)}function N(e,t){var n=b;n&&T.setTimeout(function(){return n(e,t)})}var U={closed:!0,next:E,error:function(e){throw e},complete:E},B="function"==typeof Symbol&&Symbol.observable||"@@observable";function V(e){return e}var _=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var s,i=this,r=(s=e)&&s instanceof x||function(e){return e&&h(e.next)&&h(e.error)&&h(e.complete)}(s)&&y(s)?e:new O(e,t,n);return I(function(){var e=i,t=e.operator,n=e.source;r.add(t?t.call(r,n):n?i._subscribe(r):i._trySubscribe(r))}),r},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=W(t))(function(t,s){var i=new O({next:function(t){try{e(t)}catch(e){s(e),i.unsubscribe()}},error:s,complete:t});n.subscribe(i)})},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[B]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return(0===(n=e).length?V:1===n.length?n[0]:function(e){return n.reduce(function(e,t){return t(e)},e)})(this);var n},e.prototype.toPromise=function(e){var t=this;return new(e=W(e))(function(e,n){var s;t.subscribe(function(e){return s=e},function(e){return n(e)},function(){return e(s)})})},e.create=function(t){return new e(t)},e}();function W(e){var t;return null!==(t=null!=e?e:w)&&void 0!==t?t:Promise}var $,H=u(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),j=function(e){function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return a(t,e),t.prototype.lift=function(e){var t=new q(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new H},t.prototype.next=function(e){var t=this;I(function(){var n,s;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var i=l(t.currentObservers),r=i.next();!r.done;r=i.next())r.value.next(e)}catch(e){n={error:e}}finally{try{r&&!r.done&&(s=i.return)&&s.call(i)}finally{if(n)throw n.error}}}})},t.prototype.error=function(e){var t=this;I(function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var n=t.observers;n.length;)n.shift().error(e)}})},t.prototype.complete=function(){var e=this;I(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,n=this,s=n.hasError,i=n.isStopped,r=n.observers;return s||i?f:(this.currentObservers=null,r.push(e),new m(function(){t.currentObservers=null,p(r,e)}))},t.prototype._checkFinalizedStatuses=function(e){var t=this,n=t.hasError,s=t.thrownError,i=t.isStopped;n?e.error(s):i&&e.complete()},t.prototype.asObservable=function(){var e=new _;return e.source=this,e},t.create=function(e,t){return new q(e,t)},t}(_),q=function(e){function t(t,n){var s=e.call(this)||this;return s.destination=t,s.source=n,s}return a(t,e),t.prototype.next=function(e){var t,n;null===(n=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===n||n.call(t,e)},t.prototype.error=function(e){var t,n;null===(n=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===n||n.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,n;return null!==(n=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==n?n:f},t}(j),z={now:function(){return(z.delegate||Date).now()},delegate:void 0},Q=function(e){function t(t,n,s){void 0===t&&(t=1/0),void 0===n&&(n=1/0),void 0===s&&(s=z);var i=e.call(this)||this;return i._bufferSize=t,i._windowTime=n,i._timestampProvider=s,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=n===1/0,i._bufferSize=Math.max(1,t),i._windowTime=Math.max(1,n),i}return a(t,e),t.prototype.next=function(t){var n=this,s=n.isStopped,i=n._buffer,r=n._infiniteTimeWindow,o=n._timestampProvider,a=n._windowTime;s||(i.push(t),!r&&i.push(o.now()+a)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),n=this._infiniteTimeWindow,s=this._buffer.slice(),i=0;i<s.length&&!e.closed;i+=n?1:2)e.next(s[i]);return this._checkFinalizedStatuses(e),t},t.prototype._trimBuffer=function(){var e=this,t=e._bufferSize,n=e._timestampProvider,s=e._buffer,i=e._infiniteTimeWindow,r=(i?1:2)*t;if(t<1/0&&r<s.length&&s.splice(0,s.length-r),!i){for(var o=n.now(),a=0,l=1;l<s.length&&s[l]<=o;l+=2)a=l;a&&s.splice(0,a+1)}},t}(j);!function(e){e[e.Disabled=0]="Disabled",e[e.Error=1]="Error",e[e.Warning=2]="Warning",e[e.Info=3]="Info",e[e.Debug=4]="Debug"}($||($={}));class K{constructor(){this.logLevel=$.Debug,this.includeStack=!0}}let G=new class{InitLogging(e,t){this.ValidateContext(),this.context.logLevel=e,this.context.includeStack=t}Debug(e){this.ValidateContext(),this.context.logLevel>=$.Debug&&this.CommonLog("Debug",e)}Info(e){this.ValidateContext(),this.context.logLevel>=$.Info&&this.CommonLog("Info",e)}Warning(e){this.ValidateContext(),this.context.logLevel>=$.Warning&&this.CommonLog("Warning",e)}Error(e){this.ValidateContext(),this.context.logLevel>=$.Error&&this.CommonLog("Error",e)}CommonLog(e,t){let n=`[${e}] - ${t}`;this.context.includeStack&&(n+=`\nStack: ${this.GetStackTrace()}`),"Error"===e?console.error(n):"Warning"===e?console.warn(n):console.log(n)}GetStackTrace(){const e=new Error;let t="No Stack Available for this browser";return e.stack&&(t=e.stack.toString().replace(/Error/g,"")),t}ValidateContext(){this.context||("undefined"!=typeof window&&window?window.loggerContext?this.context=window.loggerContext:(this.context=new K,window.loggerContext=this.context):this.context=new K)}};class X{constructor(e,t,n,s,i=()=>{}){this.parseURLParams(),this.onChange=i,this.onChangeEmit=()=>{},this.id=e,this.description=n,this.label=t,this.value=s}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){const e=new URLSearchParams(window.location.search),t=this.getValueAsString();let n=!1;for(const[s,i]of e)if(s.toLowerCase()==this.id.toLowerCase()){e.set(s,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={};const e=new URLSearchParams(window.location.search);for(const[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()]:""}}class J extends X{constructor(e,t,n,s,i,r=()=>{}){if(super(e,t,n,s,r),i&&this.hasURLParam(this.id)){const e=this.getURLParam(this.id);this.flag="false"!=e.toLowerCase()}else this.flag=s;this.useUrlParams=i}getValueAsString(){return this.flag?"true":"false"}enable(){this.flag=!0}get flag(){return!!this.value}set flag(e){this.value=e}}class Y extends X{constructor(e,t,n,s,i,r,o,a=()=>{}){if(super(e,t,n,r,a),this._min=s,this._max=i,o&&this.hasURLParam(this.id)){const e=Number.parseFloat(this.getURLParam(this.id));this.number=Number.isNaN(e)?r:e}else this.number=r;this.useUrlParams=o}getValueAsString(){return this.number.toString()}set number(e){this.value=this.clamp(e)}get number(){return this.value}clamp(e){return null==this._min&&null==this._max?e:null==this._min?Math.min(this._max,e):null==this._max?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}}class Z extends X{constructor(e,t,n,s,i,r=()=>{}){super(e,t,n,s,r),i&&this.hasURLParam(this.id)?this.text=this.getURLParam(this.id):this.text=s,this.useUrlParams=i}getValueAsString(){return this.text}get text(){return this.value}set text(e){this.value=e}}class ee extends X{constructor(e,t,n,s,i,r,o=function(e){return e},a=()=>{}){super(e,t,n,s,a),this._urlParamResolver=o;const l=this.hasURLParam(this.id)?this._urlParamResolver(this.getURLParam(this.id)):s;this.options=null!=i?i:[l],this.selected=l,this.useUrlParams=r}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){void 0!==e&&(this.options.includes(e)?this.value=e:G.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}}class te extends Event{constructor(e){super("afkWarningActivate"),this.data=e}}class ne extends Event{constructor(e){super("afkWarningUpdate"),this.data=e}}class se extends Event{constructor(){super("afkWarningDeactivate")}}class ie extends Event{constructor(){super("afkTimedOut")}}class re extends Event{constructor(e){super("videoEncoderAvgQP"),this.data=e}}class oe extends Event{constructor(){super("webRtcSdp")}}class ae extends Event{constructor(e){super("webRtcSdpAnswer"),this.data=e}}class le extends Event{constructor(e){super("webRtcSdpOffer"),this.data=e}}class ce extends Event{constructor(){super("webRtcAutoConnect")}}class de extends Event{constructor(){super("webRtcConnecting")}}class he extends Event{constructor(){super("webRtcConnected")}}class ue extends Event{constructor(){super("webRtcFailed")}}class ge extends Event{constructor(e){super("webRtcDisconnected"),this.data=e}}class pe extends Event{constructor(e){super("dataChannelOpen"),this.data=e}}class me extends Event{constructor(e){super("dataChannelClose"),this.data=e}}class fe extends Event{constructor(e){super("dataChannelError"),this.data=e}}class ye extends Event{constructor(){super("videoInitialized")}}class ve extends Event{constructor(){super("streamLoading")}}class Se extends Event{constructor(){super("streamConnect")}}class be extends Event{constructor(){super("streamDisconnect")}}class we extends Event{constructor(){super("streamReconnect")}}class Ce extends Event{constructor(e){super("playStreamError"),this.data=e}}class Me extends Event{constructor(){super("playStream")}}class Te extends Event{constructor(e){super("playStreamRejected"),this.data=e}}class Ee extends Event{constructor(e){super("loadFreezeFrame"),this.data=e}}class Re extends Event{constructor(){super("hideFreezeFrame")}}class ke extends Event{constructor(e){super("statsReceived"),this.data=e}}class Pe extends Event{constructor(e){super("streamerListMessage"),this.data=e}}class Ie extends Event{constructor(e){super("StreamerIDChangedMessage"),this.data=e}}class xe extends Event{constructor(e){super("latencyTestResult"),this.data=e}}class Le extends Event{constructor(e){super("latencyCalculated"),this.data=e}}class Ae extends Event{constructor(e){super("showOnScreenKeyboard"),this.data=e}}class De extends Event{constructor(e){super("dataChannelLatencyTestResponse"),this.data=e}}class Oe extends Event{constructor(e){super("dataChannelLatencyTestResult"),this.data=e}}class Fe extends Event{constructor(e){super("subscribeFailed"),this.data=e}}class Ne extends Event{constructor(e){super("initialSettings"),this.data=e}}class Ue extends Event{constructor(e){super("settingsChanged"),this.data=e}}Event,Event;class Be extends Event{constructor(e){super("xrFrame"),this.data=e}}class Ve extends Event{constructor(e){super("playerCount"),this.data=e}}class _e extends Event{constructor(){super("webRtcTCPRelayDetected")}}class We extends EventTarget{dispatchEvent(e){return super.dispatchEvent(e)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}}class $e{static getSupportedVideoCodecs(){const e=[];if(!RTCRtpReceiver.getCapabilities)return G.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;const t=/(VP\d|H26\d|AV1).*/,n=RTCRtpReceiver.getCapabilities("video");return n?(n.codecs.forEach(n=>{const s=n.mimeType.split("/")[1]+" "+(n.sdpFmtpLine||"");null!==t.exec(s)&&e.push(s)}),e):(e.push("H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"),e)}}class He{}He.AutoConnect="AutoConnect",He.AutoPlayVideo="AutoPlayVideo",He.AFKDetection="TimeoutIfIdle",He.HoveringMouseMode="HoveringMouse",He.ForceMonoAudio="ForceMonoAudio",He.ForceTURN="ForceTURN",He.FakeMouseWithTouches="FakeMouseWithTouches",He.IsQualityController="ControlsQuality",He.MatchViewportResolution="MatchViewportRes",He.StartVideoMuted="StartVideoMuted",He.SuppressBrowserKeys="SuppressBrowserKeys",He.UseMic="UseMic",He.UseModalForTextInput="UseModalForTextInput",He.UseCamera="UseCamera",He.KeyboardInput="KeyboardInput",He.MouseInput="MouseInput",He.MouseDoubleClickAutoRelease="MouseDoubleClickAutoRelease",He.TouchInput="TouchInput",He.GamepadInput="GamepadInput",He.XRControllerInput="XRControllerInput",He.AutoEnterVR="AutoEnterVR",He.WaitForStreamer="WaitForStreamer",He.HideUI="HideUI",He.EnableCaptureTimeExt="EnableCaptureTimeExt",He.BrowserSendOffer="BrowserSendOffer",He.LatencyCSV="LatencyCSV";const je=e=>Object.getOwnPropertyNames(He).some(t=>He[t]===e);class qe{}qe.AFKTimeoutSecs="AFKTimeout",qe.AFKCountdownSecs="AFKCountdown",qe.MinQP="MinQP",qe.MaxQP="MaxQP",qe.MinQuality="MinQuality",qe.MaxQuality="MaxQuality",qe.CompatQualityMin="CompatQualityMin",qe.CompatQualityMax="CompatQualityMax",qe.WebRTCFPS="WebRTCFPS",qe.WebRTCMinBitrate="WebRTCMinBitrate",qe.WebRTCMaxBitrate="WebRTCMaxBitrate",qe.MaxReconnectAttempts="MaxReconnectAttempts",qe.StreamerAutoJoinInterval="StreamerAutoJoinInterval",qe.KeepaliveDelay="KeepaliveDelay",qe.ViewportResScale="ViewportResScale";const ze=e=>Object.getOwnPropertyNames(qe).some(t=>qe[t]===e);class Qe{}Qe.SignallingServerUrl="ss";const Ke=e=>Object.getOwnPropertyNames(Qe).some(t=>Qe[t]===e);class Ge{}Ge.PreferredCodec="PreferredCodec",Ge.StreamerId="StreamerId",Ge.PreferredQuality="PreferredQuality";const Xe=e=>Object.getOwnPropertyNames(Ge).some(t=>Ge[t]===e);class Je{constructor(e={}){this.flags=new Map,this.numericParameters=new Map,this.textParameters=new Map,this.optionParameters=new Map;const{initialSettings:t,useUrlParams:n,webSocketProtocols:s}=e;this._useUrlParams=!!n,this._webSocketProtocols=s,this.populateDefaultSettings(this._useUrlParams,t)}get useUrlParams(){return this._useUrlParams}get webSocketProtocols(){return this._webSocketProtocols}populateDefaultSettings(e,t){this.textParameters.set(Qe.SignallingServerUrl,new Z(Qe.SignallingServerUrl,"Signalling url","Url of the signalling server",t&&Object.prototype.hasOwnProperty.call(t,Qe.SignallingServerUrl)?t[Qe.SignallingServerUrl]:("https:"===location.protocol?"wss://":"ws://")+window.location.hostname+("80"===window.location.port||""===window.location.port?"":`:${window.location.port}`),e)),this.optionParameters.set(Ge.StreamerId,new ee(Ge.StreamerId,"Streamer ID","The ID of the streamer to stream.",t&&Object.prototype.hasOwnProperty.call(t,Ge.StreamerId)?t[Ge.StreamerId]:"",t&&Object.prototype.hasOwnProperty.call(t,Ge.StreamerId)?[t[Ge.StreamerId]]:void 0,e));const n=function(e){const t=$e.getSupportedVideoCodecs();if(t.includes(e))return e;for(const n of t)if(n.startsWith(e))return n;return e};this.optionParameters.set(Ge.PreferredCodec,new ee(Ge.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation",t&&Object.prototype.hasOwnProperty.call(t,Ge.PreferredCodec)?n(t[Ge.PreferredCodec]):function(){const e=$e.getSupportedVideoCodecs();if(1==e.length)return e[0];if(e.length>0){const t=e[0];for(const t of e)if(t.startsWith("H264"))return t;return t}return G.Error("Could not find any reasonable video codec to assign as a default."),""}(),$e.getSupportedVideoCodecs(),e,n)),this.optionParameters.set(Ge.PreferredQuality,new ee(Ge.PreferredQuality,"Preferred Quality","The preferred quality of the stream (only applicable when using the SFU)",t&&Object.prototype.hasOwnProperty.call(t,Ge.PreferredQuality)?t[Ge.PreferredQuality]:"Default",["Default"],e)),this.flags.set(He.AutoConnect,new J(He.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,He.AutoConnect))&&t[He.AutoConnect],e)),this.flags.set(He.AutoPlayVideo,new J(He.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,He.AutoPlayVideo)||t[He.AutoPlayVideo],e)),this.flags.set(He.UseMic,new J(He.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!t||!Object.prototype.hasOwnProperty.call(t,He.UseMic))&&t[He.UseMic],e)),this.flags.set(He.UseModalForTextInput,new J(He.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,He.UseModalForTextInput)||t[He.UseModalForTextInput],e)),this.flags.set(He.UseCamera,new J(He.UseCamera,"Use webcam","Make browser request webcam access and open a input video track.",!(!t||!Object.prototype.hasOwnProperty.call(t,He.UseCamera))&&t[He.UseCamera],e)),this.flags.set(He.StartVideoMuted,new J(He.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!t||!Object.prototype.hasOwnProperty.call(t,He.StartVideoMuted))&&t[He.StartVideoMuted],e)),this.flags.set(He.SuppressBrowserKeys,new J(He.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,He.SuppressBrowserKeys)||t[He.SuppressBrowserKeys],e)),this.flags.set(He.IsQualityController,new J(He.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!t||!Object.prototype.hasOwnProperty.call(t,He.IsQualityController)||t[He.IsQualityController],e)),this.flags.set(He.ForceMonoAudio,new J(He.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!t||!Object.prototype.hasOwnProperty.call(t,He.ForceMonoAudio))&&t[He.ForceMonoAudio],e)),this.flags.set(He.ForceTURN,new J(He.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!t||!Object.prototype.hasOwnProperty.call(t,He.ForceTURN))&&t[He.ForceTURN],e)),this.flags.set(He.AFKDetection,new J(He.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!t||!Object.prototype.hasOwnProperty.call(t,He.AFKDetection))&&t[He.AFKDetection],e)),this.flags.set(He.MatchViewportResolution,new J(He.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,He.MatchViewportResolution))&&t[He.MatchViewportResolution],e)),this.flags.set(He.HoveringMouseMode,new J(He.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,He.HoveringMouseMode))&&t[He.HoveringMouseMode],e,(e,t)=>{t.label=`Control Scheme: ${e?"Hovering":"Locked"} Mouse`})),this.flags.set(He.FakeMouseWithTouches,new J(He.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,He.FakeMouseWithTouches))&&t[He.FakeMouseWithTouches],e)),this.flags.set(He.KeyboardInput,new J(He.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,He.KeyboardInput)||t[He.KeyboardInput],e)),this.flags.set(He.MouseInput,new J(He.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,He.MouseInput)||t[He.MouseInput],e)),this.flags.set(He.MouseDoubleClickAutoRelease,new J(He.MouseDoubleClickAutoRelease,"Auto release after double-click","After sending a MouseDouble message, also send a matching MouseUp so the streamer’s pressed-button state stays balanced. Disable to restore pre-fix behaviour if your project handles the doubleclick release itself.",!t||!Object.prototype.hasOwnProperty.call(t,He.MouseDoubleClickAutoRelease)||t[He.MouseDoubleClickAutoRelease],e)),this.flags.set(He.TouchInput,new J(He.TouchInput,"Touch input","If enabled, send touch events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,He.TouchInput)||t[He.TouchInput],e)),this.flags.set(He.GamepadInput,new J(He.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,He.GamepadInput)||t[He.GamepadInput],e)),this.flags.set(He.XRControllerInput,new J(He.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,He.XRControllerInput)||t[He.XRControllerInput],e)),this.flags.set(He.AutoEnterVR,new J(He.AutoEnterVR,"Auto enter VR","When the video is ready and an immersive-vr session is supported, request the WebXR session automatically. May fail if the browser requires a user gesture to start a WebXR session.",!(!t||!Object.prototype.hasOwnProperty.call(t,He.AutoEnterVR))&&t[He.AutoEnterVR],e)),this.flags.set(He.WaitForStreamer,new J(He.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!t||!Object.prototype.hasOwnProperty.call(t,He.WaitForStreamer)||t[He.WaitForStreamer],e)),this.flags.set(He.HideUI,new J(He.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!t||!Object.prototype.hasOwnProperty.call(t,He.HideUI))&&t[He.HideUI],e)),this.flags.set(He.EnableCaptureTimeExt,new J(He.EnableCaptureTimeExt,"Enable abs-capture-time","Enables the abs-capture-time RTP header extension",!(!t||!Object.prototype.hasOwnProperty.call(t,He.EnableCaptureTimeExt))&&t[He.EnableCaptureTimeExt],e)),this.flags.set(He.BrowserSendOffer,new J(He.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,He.BrowserSendOffer))&&t[He.BrowserSendOffer],e)),this.flags.set(He.LatencyCSV,new J(He.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,He.LatencyCSV))&&t[He.LatencyCSV],e)),this.numericParameters.set(qe.AFKTimeoutSecs,new Y(qe.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,qe.AFKTimeoutSecs)?t[qe.AFKTimeoutSecs]:120,e)),this.numericParameters.set(qe.AFKCountdownSecs,new Y(qe.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(qe.MaxReconnectAttempts,new Y(qe.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,t&&Object.prototype.hasOwnProperty.call(t,qe.MaxReconnectAttempts)?t[qe.MaxReconnectAttempts]:3,e)),this.numericParameters.set(qe.MinQP,new Y(qe.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,qe.MinQP)?t[qe.MinQP]:0,e)),this.numericParameters.set(qe.MaxQP,new Y(qe.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,qe.MaxQP)?t[qe.MaxQP]:51,e)),this.numericParameters.set(qe.MinQuality,new Y(qe.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,qe.MinQuality)?t[qe.MinQuality]:0,e)),this.numericParameters.set(qe.MaxQuality,new Y(qe.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,qe.MaxQuality)?t[qe.MaxQuality]:100,e)),this.numericParameters.set(qe.CompatQualityMin,new Y(qe.CompatQualityMin,"Min Quality","The lower bound for encoding quality. 0 = Worst, 100 = Best.",0,100,t&&Object.prototype.hasOwnProperty.call(t,qe.CompatQualityMin)?t[qe.CompatQualityMin]:0,e)),this.numericParameters.set(qe.CompatQualityMax,new Y(qe.CompatQualityMax,"Max Quality","The upper bound for encoding quality. 0 = Worst, 100 = Best.",0,100,t&&Object.prototype.hasOwnProperty.call(t,qe.CompatQualityMax)?t[qe.CompatQualityMax]:100,e)),this.numericParameters.set(qe.WebRTCFPS,new Y(qe.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,t&&Object.prototype.hasOwnProperty.call(t,qe.WebRTCFPS)?t[qe.WebRTCFPS]:60,e)),this.numericParameters.set(qe.WebRTCMinBitrate,new Y(qe.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,t&&Object.prototype.hasOwnProperty.call(t,qe.WebRTCMinBitrate)?t[qe.WebRTCMinBitrate]:0,e)),this.numericParameters.set(qe.WebRTCMaxBitrate,new Y(qe.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,t&&Object.prototype.hasOwnProperty.call(t,qe.WebRTCMaxBitrate)?t[qe.WebRTCMaxBitrate]:0,e)),this.numericParameters.set(qe.StreamerAutoJoinInterval,new Y(qe.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,t&&Object.prototype.hasOwnProperty.call(t,qe.StreamerAutoJoinInterval)?t[qe.StreamerAutoJoinInterval]:3e3,e)),this.numericParameters.set(qe.KeepaliveDelay,new Y(qe.KeepaliveDelay,"Connection Keepalive delay","Delay between keepalive pings to the signalling server.",0,9e5,t&&Object.prototype.hasOwnProperty.call(t,qe.KeepaliveDelay)?t[qe.KeepaliveDelay]:3e4,e)),this.numericParameters.set(qe.ViewportResScale,new Y(qe.ViewportResScale,"Viewport Resolution Scale","Scale factor for viewport resolution when MatchViewportResolution is enabled. 1.0 = 100%, 0.5 = 50%, 2.0 = 200%.",.1,3,t&&Object.prototype.hasOwnProperty.call(t,qe.ViewportResScale)?t[qe.ViewportResScale]:1,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}`)}hasNumericSetting(e){return this.numericParameters.has(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))throw new Error(`There is no numeric setting with the id of ${e}`);this.numericParameters.get(e).number=t}_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:G.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:G.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:G.Warning(`Cannot set text setting called ${e} - it does not exist in the Config.optionParameters map.`)}setOptionSettingValue(e,t){if(this.optionParameters.has(e)){const n=this.optionParameters.get(e),s=n.options;s.includes(t)||(s.push(t),n.options=s),n.selected=t}else G.Warning(`Cannot set text setting called ${e} - it does not exist in the Config.enumParameters map.`)}setFlagLabel(e,t){this.flags.has(e)?this.flags.get(e).label=t:G.Warning(`Cannot set label for flag called ${e} - it does not exist in the Config.flags map.`)}setSettings(e){for(const t of Object.keys(e))je(t)?this.setFlagEnabled(t,e[t]):ze(t)?this.setNumericSetting(t,e[t]):Ke(t)?this.setTextSetting(t,e[t]):Xe(t)&&this.setOptionSettingValue(t,e[t])}getSettings(){const e={};for(const[t,n]of this.flags.entries())e[t]=n.flag;for(const[t,n]of this.numericParameters.entries())e[t]=n.number;for(const[t,n]of this.textParameters.entries())e[t]=n.text;for(const[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(const t of this.flags.keys()){const n=this.flags.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Ue({id:n.id,type:"flag",value:t,target:n})))}for(const t of this.numericParameters.keys()){const n=this.numericParameters.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Ue({id:n.id,type:"number",value:t,target:n})))}for(const t of this.textParameters.keys()){const n=this.textParameters.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Ue({id:n.id,type:"text",value:t,target:n})))}for(const t of this.optionParameters.keys()){const n=this.optionParameters.get(t);n&&(n.onChangeEmit=t=>e.dispatchEvent(new Ue({id:n.id,type:"option",value:t,target:n})))}}}var Ye,Ze,et;!function(e){e[e.LockedMouse=0]="LockedMouse",e[e.HoveringMouse=1]="HoveringMouse"}(Ye||(Ye={}));class tt{constructor(e){this._args=[],this._callback=e}handleEvent(e){this._callback(...this._args),this._args=[]}setArgs(...e){this._args=e}}class nt extends EventTarget{constructor(){super(),this._eventListeners=new Map}removeListenerInternal(e,t){if(this._eventListeners.has(e)){const n=this._eventListeners.get(e);if(void 0===n)return this;for(let s=0;s<n.length;++s){const i=n[s];if(i.callback===t){super.removeEventListener(e,i.eventListenerWrapper),n.splice(s,1);break}}}return this}addListener(e,t){return this.on(e,t)}on(e,t){var n;const s=new tt(t);return super.addEventListener(e,s),this._eventListeners.has(e)||this._eventListeners.set(e,new Array),null===(n=this._eventListeners.get(e))||void 0===n||n.push({callback:t,eventListenerWrapper:s}),this}once(e,t){var n;const s=new tt((...n)=>{t(...n),this.removeListenerInternal(e,t)});return super.addEventListener(e,s,{once:!0}),this._eventListeners.has(e)||this._eventListeners.set(e,new Array),null===(n=this._eventListeners.get(e))||void 0===n||n.push({callback:t,eventListenerWrapper:s}),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)){const t=this._eventListeners.get(e);if(void 0===t)return this;for(const n of t)this.removeEventListener(e,n.eventListenerWrapper);this._eventListeners.delete(e)}return this}emit(e,...t){if(this._eventListeners.has(e)){const n=this._eventListeners.get(e);if(void 0===n)return!1;for(const e of n)e.eventListenerWrapper.setArgs(...t);return super.dispatchEvent(new Event(e)),!0}return!1}}class st extends nt{constructor(e){super(),this.WS_OPEN_STATE=1,this.protocols=e}sendMessage(e){this.webSocket&&this.webSocket.send(e)}connect(e){G.Info(e);try{return this.webSocket=new WebSocket(e,this.protocols),this.webSocket.onopen=e=>this.handleOnOpen(),this.webSocket.onerror=e=>this.handleOnError(),this.webSocket.onclose=e=>this.handleOnClose(e),this.webSocket.onmessage=e=>this.handleOnMessage(e),this.webSocket.onmessagebinary=e=>this.handleOnMessageBinary(e),!0}catch(e){return G.Error(e instanceof Error?e.message:String(e)),!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(e=>{const t=new MessageEvent("messageFromBinary",{data:e});this.handleOnMessage(t)}).catch(e=>{G.Error(`Failed to parse binary blob from websocket, reason: ${e.message}`)})}handleOnMessage(e){e.data&&e.data instanceof Blob?this.handleOnMessageBinary(e):this.onMessage&&this.onMessage(e.data)}handleOnOpen(){G.Info("Connected to the signalling server via WebSocket"),this.emit("open")}handleOnError(){this.emit("error")}handleOnClose(e){G.Info("Disconnected to the signalling server via WebSocket: "+JSON.stringify(e.code)+" - "+e.reason),this.emit("close",e)}}class it extends nt{static get SIGNALLING_VERSION(){return"1.3.0"}constructor(e){super(),this.transport=e,e.onMessage=t=>{let n;try{const e=JSON.parse(t);G.Debug("Protocol received => \n"+JSON.stringify(e,void 0,4)),n=e}catch(e){return void(e instanceof Error?G.Error(`Error parsing message string ${t}.\n${e.message}`):G.Error("Unknown error while parsing message data in handleOnMessage"))}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),G.Debug("Protocol sent => \n"+JSON.stringify(e,void 0,4))}}function rt(e,t,n){let s,i,r=n;for(let n of e.fields){let e=n.localName;if(n.oneof){const o=r[n.oneof];if(null==(null==o?void 0:o.oneofKind))continue;if(s=o[e],i=t[n.oneof],i.oneofKind=o.oneofKind,null==s){delete i[e];continue}}else if(s=r[e],i=t,null==s)continue;switch(n.repeat&&(i[e].length=s.length),n.kind){case"scalar":case"enum":if(n.repeat)for(let t=0;t<s.length;t++)i[e][t]=s[t];else i[e]=s;break;case"message":let t=n.T();if(n.repeat)for(let n=0;n<s.length;n++)i[e][n]=t.create(s[n]);else void 0===i[e]?i[e]=t.create(s):t.mergePartial(i[e],s);break;case"map":switch(n.V.kind){case"scalar":case"enum":Object.assign(i[e],s);break;case"message":let t=n.V.T();for(let n of Object.keys(s))i[e][n]=t.create(s[n])}}}}!function(e){e.symbol=Symbol.for("protobuf-ts/unknown"),e.onRead=(n,s,i,r,o)=>{(t(s)?s[e.symbol]:s[e.symbol]=[]).push({no:i,wireType:r,data:o})},e.onWrite=(t,n,s)=>{for(let{no:t,wireType:i,data:r}of e.list(n))s.tag(t,i).raw(r)},e.list=(n,s)=>{if(t(n)){let t=n[e.symbol];return s?t.filter(e=>e.no==s):t}return[]},e.last=(t,n)=>e.list(t,n).slice(-1)[0];const t=t=>t&&Array.isArray(t[e.symbol])}(Ze||(Ze={})),function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(et||(et={}));const ot=Symbol.for("protobuf-ts/message-type");function at(e){let t=!1;const n=[];for(let s=0;s<e.length;s++){let i=e.charAt(s);"_"==i?t=!0:/\d/.test(i)?(n.push(i),t=!0):t?(n.push(i.toUpperCase()),t=!1):0==s?n.push(i.toLowerCase()):n.push(i)}return n.join("")}var lt,ct,dt;function ht(e){var t,n,s,i;return e.localName=null!==(t=e.localName)&&void 0!==t?t:at(e.name),e.jsonName=null!==(n=e.jsonName)&&void 0!==n?n:at(e.name),e.repeat=null!==(s=e.repeat)&&void 0!==s?s:dt.NO,e.opt=null!==(i=e.opt)&&void 0!==i?i:!e.repeat&&!e.oneof&&"message"==e.kind,e}function ut(e){if("object"!=typeof e||null===e||!e.hasOwnProperty("oneofKind"))return!1;switch(typeof e.oneofKind){case"string":return void 0!==e[e.oneofKind]&&2==Object.keys(e).length;case"undefined":return 1==Object.keys(e).length;default:return!1}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(lt||(lt={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING",e[e.NUMBER=2]="NUMBER"}(ct||(ct={})),function(e){e[e.NO=0]="NO",e[e.PACKED=1]="PACKED",e[e.UNPACKED=2]="UNPACKED"}(dt||(dt={}));class gt{constructor(e){var t;this.fields=null!==(t=e.fields)&&void 0!==t?t:[]}prepare(){if(this.data)return;const e=[],t=[],n=[];for(let s of this.fields)if(s.oneof)n.includes(s.oneof)||(n.push(s.oneof),e.push(s.oneof),t.push(s.oneof));else switch(t.push(s.localName),s.kind){case"scalar":case"enum":s.opt&&!s.repeat||e.push(s.localName);break;case"message":s.repeat&&e.push(s.localName);break;case"map":e.push(s.localName)}this.data={req:e,known:t,oneofs:Object.values(n)}}is(e,t,n=!1){if(t<0)return!0;if(null==e||"object"!=typeof e)return!1;this.prepare();let s=Object.keys(e),i=this.data;if(s.length<i.req.length||i.req.some(e=>!s.includes(e)))return!1;if(!n&&s.some(e=>!i.known.includes(e)))return!1;if(t<1)return!0;for(const s of i.oneofs){const i=e[s];if(!ut(i))return!1;if(void 0===i.oneofKind)continue;const r=this.fields.find(e=>e.localName===i.oneofKind);if(!r)return!1;if(!this.field(i[i.oneofKind],r,n,t))return!1}for(const s of this.fields)if(void 0===s.oneof&&!this.field(e[s.localName],s,n,t))return!1;return!0}field(e,t,n,s){let i=t.repeat;switch(t.kind){case"scalar":return void 0===e?t.opt:i?this.scalars(e,t.T,s,t.L):this.scalar(e,t.T,t.L);case"enum":return void 0===e?t.opt:i?this.scalars(e,lt.INT32,s):this.scalar(e,lt.INT32);case"message":return void 0===e||(i?this.messages(e,t.T(),n,s):this.message(e,t.T(),n,s));case"map":if("object"!=typeof e||null===e)return!1;if(s<2)return!0;if(!this.mapKeys(e,t.K,s))return!1;switch(t.V.kind){case"scalar":return this.scalars(Object.values(e),t.V.T,s,t.V.L);case"enum":return this.scalars(Object.values(e),lt.INT32,s);case"message":return this.messages(Object.values(e),t.V.T(),n,s)}}return!0}message(e,t,n,s){return n?t.isAssignable(e,s):t.is(e,s)}messages(e,t,n,s){if(!Array.isArray(e))return!1;if(s<2)return!0;if(n){for(let n=0;n<e.length&&n<s;n++)if(!t.isAssignable(e[n],s-1))return!1}else for(let n=0;n<e.length&&n<s;n++)if(!t.is(e[n],s-1))return!1;return!0}scalar(e,t,n){let s=typeof e;switch(t){case lt.UINT64:case lt.FIXED64:case lt.INT64:case lt.SFIXED64:case lt.SINT64:switch(n){case ct.BIGINT:return"bigint"==s;case ct.NUMBER:return"number"==s&&!isNaN(e);default:return"string"==s}case lt.BOOL:return"boolean"==s;case lt.STRING:return"string"==s;case lt.BYTES:return e instanceof Uint8Array;case lt.DOUBLE:case lt.FLOAT:return"number"==s&&!isNaN(e);default:return"number"==s&&Number.isInteger(e)}}scalars(e,t,n,s){if(!Array.isArray(e))return!1;if(n<2)return!0;if(Array.isArray(e))for(let i=0;i<e.length&&i<n;i++)if(!this.scalar(e[i],t,s))return!1;return!0}mapKeys(e,t,n){let s=Object.keys(e);switch(t){case lt.INT32:case lt.FIXED32:case lt.SFIXED32:case lt.SINT32:case lt.UINT32:return this.scalars(s.slice(0,n).map(e=>parseInt(e)),t,n);case lt.BOOL:return this.scalars(s.slice(0,n).map(e=>"true"==e||"false"!=e&&e),t,n);default:return this.scalars(s,t,n,ct.STRING)}}}function pt(e){let t=typeof e;if("object"==t){if(Array.isArray(e))return"array";if(null===e)return"null"}return t}function mt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let ft="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),yt=[];for(let e=0;e<ft.length;e++)yt[ft[e].charCodeAt(0)]=e;function vt(){let e=0,t=0;for(let n=0;n<28;n+=7){let s=this.buf[this.pos++];if(e|=(127&s)<<n,!(128&s))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,!(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let s=this.buf[this.pos++];if(t|=(127&s)<<n,!(128&s))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function St(e,t,n){for(let s=0;s<28;s+=7){const i=e>>>s,r=!(i>>>7==0&&0==t),o=255&(r?128|i:i);if(n.push(o),!r)return}const s=e>>>28&15|(7&t)<<4,i=!!(t>>3);if(n.push(255&(i?128|s:s)),i){for(let e=3;e<31;e+=7){const s=t>>>e,i=!(s>>>7==0),r=255&(i?128|s:s);if(n.push(r),!i)return}n.push(t>>>31&1)}}yt["-".charCodeAt(0)]=ft.indexOf("+"),yt["_".charCodeAt(0)]=ft.indexOf("/");const bt=4294967296;function wt(e){let t="-"==e[0];t&&(e=e.slice(1));const n=1e6;let s=0,i=0;function r(t,r){const o=Number(e.slice(t,r));i*=n,s=s*n+o,s>=bt&&(i+=s/bt|0,s%=bt)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),[t,s,i]}function Ct(e,t){if(t>>>0<=2097151)return""+(bt*t+(e>>>0));let n=(e>>>24|t<<8)>>>0&16777215,s=t>>16&65535,i=(16777215&e)+6777216*n+6710656*s,r=n+8147497*s,o=2*s,a=1e7;function l(e,t){let n=e?String(e):"";return t?"0000000".slice(n.length)+n:n}return i>=a&&(r+=Math.floor(i/a),i%=a),r>=a&&(o+=Math.floor(r/a),r%=a),l(o,0)+l(r,o)+l(i,1)}function Mt(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function Tt(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;128&e&&t<10;t++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}let Et;function Rt(e){if(!e)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}!function(){const e=new DataView(new ArrayBuffer(8)),t=void 0!==globalThis.BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64;Et=t?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:e}:void 0}();const kt=/^-?[0-9]+$/,Pt=4294967296,It=2147483648;class xt{constructor(e,t){this.lo=0|e,this.hi=0|t}isZero(){return 0==this.lo&&0==this.hi}toNumber(){let e=this.hi*Pt+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class Lt extends xt{static from(e){if(Et)switch(typeof e){case"string":if("0"==e)return this.ZERO;if(""==e)throw new Error("string is no integer");e=Et.C(e);case"number":if(0===e)return this.ZERO;e=Et.C(e);case"bigint":if(!e)return this.ZERO;if(e<Et.UMIN)throw new Error("signed value for ulong");if(e>Et.UMAX)throw new Error("ulong too large");return Et.V.setBigUint64(0,e,!0),new Lt(Et.V.getInt32(0,!0),Et.V.getInt32(4,!0))}else switch(typeof e){case"string":if("0"==e)return this.ZERO;if(e=e.trim(),!kt.test(e))throw new Error("string is no integer");let[t,n,s]=wt(e);if(t)throw new Error("signed value for ulong");return new Lt(n,s);case"number":if(0==e)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 Lt(e,e/Pt)}throw new Error("unknown value "+typeof e)}toString(){return Et?this.toBigInt().toString():Ct(this.lo,this.hi)}toBigInt(){return Rt(Et),Et.V.setInt32(0,this.lo,!0),Et.V.setInt32(4,this.hi,!0),Et.V.getBigUint64(0,!0)}}Lt.ZERO=new Lt(0,0);class At extends xt{static from(e){if(Et)switch(typeof e){case"string":if("0"==e)return this.ZERO;if(""==e)throw new Error("string is no integer");e=Et.C(e);case"number":if(0===e)return this.ZERO;e=Et.C(e);case"bigint":if(!e)return this.ZERO;if(e<Et.MIN)throw new Error("signed long too small");if(e>Et.MAX)throw new Error("signed long too large");return Et.V.setBigInt64(0,e,!0),new At(Et.V.getInt32(0,!0),Et.V.getInt32(4,!0))}else switch(typeof e){case"string":if("0"==e)return this.ZERO;if(e=e.trim(),!kt.test(e))throw new Error("string is no integer");let[t,n,s]=wt(e);if(t){if(s>It||s==It&&0!=n)throw new Error("signed long too small")}else if(s>=It)throw new Error("signed long too large");let i=new At(n,s);return t?i.negate():i;case"number":if(0==e)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new At(e,e/Pt):new At(-e,-e/Pt).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return 0!==(this.hi&It)}negate(){let e=~this.hi,t=this.lo;return t?t=1+~t:e+=1,new At(t,e)}toString(){if(Et)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+Ct(e.lo,e.hi)}return Ct(this.lo,this.hi)}toBigInt(){return Rt(Et),Et.V.setInt32(0,this.lo,!0),Et.V.setInt32(4,this.hi,!0),Et.V.getBigInt64(0,!0)}}function Dt(e,t){if(!e)throw new Error(t)}function Ot(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function Ft(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function Nt(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}function Ut(e,t){switch(t){case ct.BIGINT:return e.toBigInt();case ct.NUMBER:return e.toNumber();default:return e.toString()}}At.ZERO=new At(0,0);class Bt{constructor(e){this.info=e}prepare(){var e;if(void 0===this.fMap){this.fMap={};const t=null!==(e=this.info.fields)&&void 0!==e?e:[];for(const e of t)this.fMap[e.name]=e,this.fMap[e.jsonName]=e,this.fMap[e.localName]=e}}assert(e,t,n){if(!e){let e=pt(n);throw"number"!=e&&"boolean"!=e||(e=n.toString()),new Error(`Cannot parse JSON ${e} for ${this.info.typeName}#${t}`)}}read(e,t,n){this.prepare();const s=[];for(const[i,r]of Object.entries(e)){const e=this.fMap[i];if(!e){if(!n.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${i}`);continue}const o=e.localName;let a;if(e.oneof){if(null===r&&("enum"!==e.kind||"google.protobuf.NullValue"!==e.T()[0]))continue;if(s.includes(e.oneof))throw new Error(`Multiple members of the oneof group "${e.oneof}" of ${this.info.typeName} are present in JSON.`);s.push(e.oneof),a=t[e.oneof]={oneofKind:o}}else a=t;if("map"==e.kind){if(null===r)continue;this.assert(mt(r),e.name,r);const t=a[o];for(const[s,i]of Object.entries(r)){let r;switch(this.assert(null!==i,e.name+" map value",null),e.V.kind){case"message":r=e.V.T().internalJsonRead(i,n);break;case"enum":if(r=this.enum(e.V.T(),i,e.name,n.ignoreUnknownFields),!1===r)continue;break;case"scalar":r=this.scalar(i,e.V.T,e.V.L,e.name)}this.assert(void 0!==r,e.name+" map value",i);let o=s;e.K==lt.BOOL&&(o="true"==o||"false"!=o&&o),o=this.scalar(o,e.K,ct.STRING,e.name).toString(),t[o]=r}}else if(e.repeat){if(null===r)continue;this.assert(Array.isArray(r),e.name,r);const t=a[o];for(const s of r){let i;switch(this.assert(null!==s,e.name,null),e.kind){case"message":i=e.T().internalJsonRead(s,n);break;case"enum":if(i=this.enum(e.T(),s,e.name,n.ignoreUnknownFields),!1===i)continue;break;case"scalar":i=this.scalar(s,e.T,e.L,e.name)}this.assert(void 0!==i,e.name,r),t.push(i)}}else switch(e.kind){case"message":if(null===r&&"google.protobuf.Value"!=e.T().typeName){this.assert(void 0===e.oneof,e.name+" (oneof member)",null);continue}a[o]=e.T().internalJsonRead(r,n,a[o]);break;case"enum":if(null===r)continue;let t=this.enum(e.T(),r,e.name,n.ignoreUnknownFields);if(!1===t)continue;a[o]=t;break;case"scalar":if(null===r)continue;a[o]=this.scalar(r,e.T,e.L,e.name)}}}enum(e,t,n,s){if("google.protobuf.NullValue"==e[0]&&Dt(null===t||"NULL_VALUE"===t,`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} only accepts null.`),null===t)return 0;switch(typeof t){case"number":return Dt(Number.isInteger(t),`Unable to parse field ${this.info.typeName}#${n}, enum can only be integral number, got ${t}.`),t;case"string":let i=t;e[2]&&t.substring(0,e[2].length)===e[2]&&(i=t.substring(e[2].length));let r=e[1][i];return(void 0!==r||!s)&&(Dt("number"==typeof r,`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} has no value for "${t}".`),r)}Dt(!1,`Unable to parse field ${this.info.typeName}#${n}, cannot parse enum value from ${typeof t}".`)}scalar(e,t,n,s){let i;try{switch(t){case lt.DOUBLE:case lt.FLOAT:if(null===e)return 0;if("NaN"===e)return Number.NaN;if("Infinity"===e)return Number.POSITIVE_INFINITY;if("-Infinity"===e)return Number.NEGATIVE_INFINITY;if(""===e){i="empty string";break}if("string"==typeof e&&e.trim().length!==e.length){i="extra whitespace";break}if("string"!=typeof e&&"number"!=typeof e)break;let s=Number(e);if(Number.isNaN(s)){i="not a number";break}if(!Number.isFinite(s)){i="too large or small";break}return t==lt.FLOAT&&Nt(s),s;case lt.INT32:case lt.FIXED32:case lt.SFIXED32:case lt.SINT32:case lt.UINT32:if(null===e)return 0;let r;if("number"==typeof e?r=e:""===e?i="empty string":"string"==typeof e&&(e.trim().length!==e.length?i="extra whitespace":r=Number(e)),void 0===r)break;return t==lt.UINT32?Ft(r):Ot(r),r;case lt.INT64:case lt.SFIXED64:case lt.SINT64:if(null===e)return Ut(At.ZERO,n);if("number"!=typeof e&&"string"!=typeof e)break;return Ut(At.from(e),n);case lt.FIXED64:case lt.UINT64:if(null===e)return Ut(Lt.ZERO,n);if("number"!=typeof e&&"string"!=typeof e)break;return Ut(Lt.from(e),n);case lt.BOOL:if(null===e)return!1;if("boolean"!=typeof e)break;return e;case lt.STRING:if(null===e)return"";if("string"!=typeof e){i="extra whitespace";break}try{encodeURIComponent(e)}catch(i){i="invalid UTF8";break}return e;case lt.BYTES:if(null===e||""===e)return new Uint8Array(0);if("string"!=typeof e)break;return function(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let n,s=new Uint8Array(t),i=0,r=0,o=0;for(let t=0;t<e.length;t++){if(n=yt[e.charCodeAt(t)],void 0===n)switch(e[t]){case"=":r=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=n,r=1;break;case 1:s[i++]=o<<2|(48&n)>>4,o=n,r=2;break;case 2:s[i++]=(15&o)<<4|(60&n)>>2,o=n,r=3;break;case 3:s[i++]=(3&o)<<6|n,r=0}}if(1==r)throw Error("invalid base64 string.");return s.subarray(0,i)}(e)}}catch(e){i=e.message}this.assert(!1,s+(i?" - "+i:""),e)}}class Vt{constructor(e){var t;this.fields=null!==(t=e.fields)&&void 0!==t?t:[]}write(e,t){const n={},s=e;for(const e of this.fields){if(!e.oneof){let i=this.field(e,s[e.localName],t);void 0!==i&&(n[t.useProtoFieldName?e.name:e.jsonName]=i);continue}const i=s[e.oneof];if(i.oneofKind!==e.localName)continue;const r="scalar"==e.kind||"enum"==e.kind?Object.assign(Object.assign({},t),{emitDefaultValues:!0}):t;let o=this.field(e,i[e.localName],r);Dt(void 0!==o),n[t.useProtoFieldName?e.name:e.jsonName]=o}return n}field(e,t,n){let s;if("map"==e.kind){Dt("object"==typeof t&&null!==t);const i={};switch(e.V.kind){case"scalar":for(const[n,s]of Object.entries(t)){const t=this.scalar(e.V.T,s,e.name,!1,!0);Dt(void 0!==t),i[n.toString()]=t}break;case"message":const s=e.V.T();for(const[r,o]of Object.entries(t)){const t=this.message(s,o,e.name,n);Dt(void 0!==t),i[r.toString()]=t}break;case"enum":const r=e.V.T();for(const[s,o]of Object.entries(t)){Dt(void 0===o||"number"==typeof o);const t=this.enum(r,o,e.name,!1,!0,n.enumAsInteger);Dt(void 0!==t),i[s.toString()]=t}}(n.emitDefaultValues||Object.keys(i).length>0)&&(s=i)}else if(e.repeat){Dt(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let n=0;n<t.length;n++){const s=this.scalar(e.T,t[n],e.name,e.opt,!0);Dt(void 0!==s),i.push(s)}break;case"enum":const s=e.T();for(let r=0;r<t.length;r++){Dt(void 0===t[r]||"number"==typeof t[r]);const o=this.enum(s,t[r],e.name,e.opt,!0,n.enumAsInteger);Dt(void 0!==o),i.push(o)}break;case"message":const r=e.T();for(let s=0;s<t.length;s++){const o=this.message(r,t[s],e.name,n);Dt(void 0!==o),i.push(o)}}(n.emitDefaultValues||i.length>0||n.emitDefaultValues)&&(s=i)}else switch(e.kind){case"scalar":s=this.scalar(e.T,t,e.name,e.opt,n.emitDefaultValues);break;case"enum":s=this.enum(e.T(),t,e.name,e.opt,n.emitDefaultValues,n.enumAsInteger);break;case"message":s=this.message(e.T(),t,e.name,n)}return s}enum(e,t,n,s,i,r){if("google.protobuf.NullValue"==e[0])return i||s?null:void 0;if(void 0!==t){if(0!==t||i||s)return Dt("number"==typeof t),Dt(Number.isInteger(t)),r||!e[1].hasOwnProperty(t)?t:e[2]?e[2]+e[1][t]:e[1][t]}else Dt(s)}message(e,t,n,s){return void 0===t?s.emitDefaultValues?null:void 0:e.internalJsonWrite(t,s)}scalar(e,t,n,s,i){if(void 0===t)return void Dt(s);const r=i||s;switch(e){case lt.INT32:case lt.SFIXED32:case lt.SINT32:return 0===t?r?0:void 0:(Ot(t),t);case lt.FIXED32:case lt.UINT32:return 0===t?r?0:void 0:(Ft(t),t);case lt.FLOAT:Nt(t);case lt.DOUBLE:return 0===t?r?0:void 0:(Dt("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t);case lt.STRING:return""===t?r?"":void 0:(Dt("string"==typeof t),t);case lt.BOOL:return!1===t?!r&&void 0:(Dt("boolean"==typeof t),t);case lt.UINT64:case lt.FIXED64:Dt("number"==typeof t||"string"==typeof t||"bigint"==typeof t);let e=Lt.from(t);if(e.isZero()&&!r)return;return e.toString();case lt.INT64:case lt.SFIXED64:case lt.SINT64:Dt("number"==typeof t||"string"==typeof t||"bigint"==typeof t);let n=At.from(t);if(n.isZero()&&!r)return;return n.toString();case lt.BYTES:return Dt(t instanceof Uint8Array),t.byteLength?function(e){let t,n="",s=0,i=0;for(let r=0;r<e.length;r++)switch(t=e[r],s){case 0:n+=ft[t>>2],i=(3&t)<<4,s=1;break;case 1:n+=ft[i|t>>4],i=(15&t)<<2,s=2;break;case 2:n+=ft[i|t>>6],n+=ft[63&t],s=0}return s&&(n+=ft[i],n+="=",1==s&&(n+="=")),n}(t):r?"":void 0}}}function _t(e,t=ct.STRING){switch(e){case lt.BOOL:return!1;case lt.UINT64:case lt.FIXED64:return Ut(Lt.ZERO,t);case lt.INT64:case lt.SFIXED64:case lt.SINT64:return Ut(At.ZERO,t);case lt.DOUBLE:case lt.FLOAT:return 0;case lt.BYTES:return new Uint8Array(0);case lt.STRING:return"";default:return 0}}class Wt{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){const t=null!==(e=this.info.fields)&&void 0!==e?e:[];this.fieldNoToField=new Map(t.map(e=>[e.no,e]))}}read(e,t,n,s){this.prepare();const i=void 0===s?e.len:e.pos+s;for(;e.pos<i;){const[s,i]=e.tag(),r=this.fieldNoToField.get(s);if(!r){let r=n.readUnknownField;if("throw"==r)throw new Error(`Unknown field ${s} (wire type ${i}) for ${this.info.typeName}`);let o=e.skip(i);!1!==r&&(!0===r?Ze.onRead:r)(this.info.typeName,t,s,i,o);continue}let o=t,a=r.repeat,l=r.localName;switch(r.oneof&&(o=o[r.oneof],o.oneofKind!==l&&(o=t[r.oneof]={oneofKind:l})),r.kind){case"scalar":case"enum":let t="enum"==r.kind?lt.INT32:r.T,s="scalar"==r.kind?r.L:void 0;if(a){let n=o[l];if(i==et.LengthDelimited&&t!=lt.STRING&&t!=lt.BYTES){let i=e.uint32()+e.pos;for(;e.pos<i;)n.push(this.scalar(e,t,s))}else n.push(this.scalar(e,t,s))}else o[l]=this.scalar(e,t,s);break;case"message":if(a){let t=o[l],s=r.T().internalBinaryRead(e,e.uint32(),n);t.push(s)}else o[l]=r.T().internalBinaryRead(e,e.uint32(),n,o[l]);break;case"map":let[c,d]=this.mapEntry(r,e,n);o[l][c]=d}}}mapEntry(e,t,n){let s,i,r=t.uint32(),o=t.pos+r;for(;t.pos<o;){let[r,o]=t.tag();switch(r){case 1:s=e.K==lt.BOOL?t.bool().toString():this.scalar(t,e.K,ct.STRING);break;case 2:switch(e.V.kind){case"scalar":i=this.scalar(t,e.V.T,e.V.L);break;case"enum":i=t.int32();break;case"message":i=e.V.T().internalBinaryRead(t,t.uint32(),n)}break;default:throw new Error(`Unknown field ${r} (wire type ${o}) in map entry for ${this.info.typeName}#${e.name}`)}}if(void 0===s){let t=_t(e.K);s=e.K==lt.BOOL?t.toString():t}if(void 0===i)switch(e.V.kind){case"scalar":i=_t(e.V.T,e.V.L);break;case"enum":i=0;break;case"message":i=e.V.T().create()}return[s,i]}scalar(e,t,n){switch(t){case lt.INT32:return e.int32();case lt.STRING:return e.string();case lt.BOOL:return e.bool();case lt.DOUBLE:return e.double();case lt.FLOAT:return e.float();case lt.INT64:return Ut(e.int64(),n);case lt.UINT64:return Ut(e.uint64(),n);case lt.FIXED64:return Ut(e.fixed64(),n);case lt.FIXED32:return e.fixed32();case lt.BYTES:return e.bytes();case lt.UINT32:return e.uint32();case lt.SFIXED32:return e.sfixed32();case lt.SFIXED64:return Ut(e.sfixed64(),n);case lt.SINT32:return e.sint32();case lt.SINT64:return Ut(e.sint64(),n)}}}class $t{constructor(e){this.info=e}prepare(){if(!this.fields){const e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((e,t)=>e.no-t.no)}}write(e,t,n){this.prepare();for(const s of this.fields){let i,r,o=s.repeat,a=s.localName;if(s.oneof){const t=e[s.oneof];if(t.oneofKind!==a)continue;i=t[a],r=!0}else i=e[a],r=!1;switch(s.kind){case"scalar":case"enum":let e="enum"==s.kind?lt.INT32:s.T;if(o)if(Dt(Array.isArray(i)),o==dt.PACKED)this.packed(t,e,s.no,i);else for(const n of i)this.scalar(t,e,s.no,n,!0);else void 0===i?Dt(s.opt):this.scalar(t,e,s.no,i,r||s.opt);break;case"message":if(o){Dt(Array.isArray(i));for(const e of i)this.message(t,n,s.T(),s.no,e)}else this.message(t,n,s.T(),s.no,i);break;case"map":Dt("object"==typeof i&&null!==i);for(const[e,r]of Object.entries(i))this.mapEntry(t,n,s,e,r)}}let s=n.writeUnknownFields;!1!==s&&(!0===s?Ze.onWrite:s)(this.info.typeName,e,t)}mapEntry(e,t,n,s,i){e.tag(n.no,et.LengthDelimited),e.fork();let r=s;switch(n.K){case lt.INT32:case lt.FIXED32:case lt.UINT32:case lt.SFIXED32:case lt.SINT32:r=Number.parseInt(s);break;case lt.BOOL:Dt("true"==s||"false"==s),r="true"==s}switch(this.scalar(e,n.K,1,r,!0),n.V.kind){case"scalar":this.scalar(e,n.V.T,2,i,!0);break;case"enum":this.scalar(e,lt.INT32,2,i,!0);break;case"message":this.message(e,t,n.V.T(),2,i)}e.join()}message(e,t,n,s,i){void 0!==i&&(n.internalBinaryWrite(i,e.tag(s,et.LengthDelimited).fork(),t),e.join())}scalar(e,t,n,s,i){let[r,o,a]=this.scalarInfo(t,s);a&&!i||(e.tag(n,r),e[o](s))}packed(e,t,n,s){if(!s.length)return;Dt(t!==lt.BYTES&&t!==lt.STRING),e.tag(n,et.LengthDelimited),e.fork();let[,i]=this.scalarInfo(t);for(let t=0;t<s.length;t++)e[i](s[t]);e.join()}scalarInfo(e,t){let n,s=et.Varint,i=void 0===t,r=0===t;switch(e){case lt.INT32:n="int32";break;case lt.STRING:r=i||!t.length,s=et.LengthDelimited,n="string";break;case lt.BOOL:r=!1===t,n="bool";break;case lt.UINT32:n="uint32";break;case lt.DOUBLE:s=et.Bit64,n="double";break;case lt.FLOAT:s=et.Bit32,n="float";break;case lt.INT64:r=i||At.from(t).isZero(),n="int64";break;case lt.UINT64:r=i||Lt.from(t).isZero(),n="uint64";break;case lt.FIXED64:r=i||Lt.from(t).isZero(),s=et.Bit64,n="fixed64";break;case lt.BYTES:r=i||!t.byteLength,s=et.LengthDelimited,n="bytes";break;case lt.FIXED32:s=et.Bit32,n="fixed32";break;case lt.SFIXED32:s=et.Bit32,n="sfixed32";break;case lt.SFIXED64:r=i||At.from(t).isZero(),s=et.Bit64,n="sfixed64";break;case lt.SINT32:n="sint32";break;case lt.SINT64:r=i||At.from(t).isZero(),n="sint64"}return[s,n,i||r]}}const Ht={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},jt={ignoreUnknownFields:!1},qt=Object.values;function zt(e,t,n){if(t===n)return!0;if(e!==lt.BYTES)return!1;let s=t,i=n;if(s.length!==i.length)return!1;for(let e=0;e<s.length;e++)if(s[e]!=i[e])return!1;return!0}function Qt(e,t,n){if(t.length!==n.length)return!1;for(let s=0;s<t.length;s++)if(!zt(e,t[s],n[s]))return!1;return!0}function Kt(e,t,n){if(t.length!==n.length)return!1;for(let s=0;s<t.length;s++)if(!e.equals(t[s],n[s]))return!1;return!0}const Gt={writeUnknownFields:!0,writerFactory:()=>new Xt};class Xt{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].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(Ft(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return Ot(e),Mt(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){Nt(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){Ft(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Ot(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Ot(e),Mt(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=At.from(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=Lt.from(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=At.from(e);return St(t.lo,t.hi,this.buf),this}sint64(e){let t=At.from(e),n=t.hi>>31;return St(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=Lt.from(e);return St(t.lo,t.hi,this.buf),this}}const Jt={readUnknownField:!0,readerFactory:e=>new Yt(e)};class Yt{constructor(e,t){this.varint64=vt,this.uint32=Tt,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),t=e>>>3,n=7&e;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 et.Varint:for(;128&this.buf[this.pos++];);break;case et.Bit64:this.pos+=4;case et.Bit32:this.pos+=4;break;case et.LengthDelimited:let t=this.uint32();this.pos+=t;break;case et.StartGroup:let n;for(;(n=this.tag()[1])!==et.EndGroup;)this.skip(n);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 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return new At(...this.varint64())}uint64(){return new Lt(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(1&e);return e=(e>>>1|(1&t)<<31)^n,t=t>>>1^n,new At(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new Lt(this.sfixed32(),this.sfixed32())}sfixed64(){return new At(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())}}const Zt=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),en=Zt[ot]={};class tn{constructor(e,t,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=t.map(ht),this.options=null!=n?n:{},en.value=this,this.messagePrototype=Object.create(null,Zt),this.refTypeCheck=new gt(this),this.refJsonReader=new Bt(this),this.refJsonWriter=new Vt(this),this.refBinReader=new Wt(this),this.refBinWriter=new $t(this)}create(e){let t=function(e){const t=e.messagePrototype?Object.create(e.messagePrototype):Object.defineProperty({},ot,{value:e});for(let n of e.fields){let e=n.localName;if(!n.opt)if(n.oneof)t[n.oneof]={oneofKind:void 0};else if(n.repeat)t[e]=[];else switch(n.kind){case"scalar":t[e]=_t(n.T,n.L);break;case"enum":t[e]=0;break;case"map":t[e]={}}}return t}(this);return void 0!==e&&rt(this,t,e),t}clone(e){let t=this.create();return rt(this,t,e),t}equals(e,t){return function(e,t,n){if(t===n)return!0;if(!t||!n)return!1;for(let s of e.fields){let e=s.localName,i=s.oneof?t[s.oneof][e]:t[e],r=s.oneof?n[s.oneof][e]:n[e];switch(s.kind){case"enum":case"scalar":let e="enum"==s.kind?lt.INT32:s.T;if(!(s.repeat?Qt(e,i,r):zt(e,i,r)))return!1;break;case"map":if(!("message"==s.V.kind?Kt(s.V.T(),qt(i),qt(r)):Qt("enum"==s.V.kind?lt.INT32:s.V.T,qt(i),qt(r))))return!1;break;case"message":let t=s.T();if(!(s.repeat?Kt(t,i,r):t.equals(i,r)))return!1}}return!0}(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){rt(this,e,t)}fromBinary(e,t){let n=function(e){return e?Object.assign(Object.assign({},Jt),e):Jt}(t);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,t){return this.internalJsonRead(e,function(e){return e?Object.assign(Object.assign({},jt),e):jt}(t))}fromJsonString(e,t){let n=JSON.parse(e);return this.fromJson(n,t)}toJson(e,t){return this.internalJsonWrite(e,function(e){return e?Object.assign(Object.assign({},Ht),e):Ht}(t))}toJsonString(e,t){var n;let s=this.toJson(e,t);return JSON.stringify(s,null,null!==(n=null==t?void 0:t.prettySpaces)&&void 0!==n?n:0)}toBinary(e,t){let n=function(e){return e?Object.assign(Object.assign({},Gt),e):Gt}(t);return this.internalBinaryWrite(e,n.writerFactory(),n).finish()}internalJsonRead(e,t,n){if(null!==e&&"object"==typeof e&&!Array.isArray(e)){let s=null!=n?n:this.create();return this.refJsonReader.read(e,s,t),s}throw new Error(`Unable to parse message ${this.typeName} from JSON ${pt(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,s){let i=null!=s?s:this.create();return this.refBinReader.read(e,i,n,t),i}}new class extends tn{constructor(){super("base_message",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};const nn=new class extends tn{constructor(){super("peerConnectionOptions",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},sn=new class extends tn{constructor(){super("config",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"peerConnectionOptions",kind:"message",T:()=>nn},{no:3,name:"protocolVersion",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.peerConnectionOptions=nn.internalBinaryRead(e,e.uint32(),n,i.peerConnectionOptions);break;case 3:i.protocolVersion=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),e.peerConnectionOptions&&nn.internalBinaryWrite(e.peerConnectionOptions,t.tag(2,et.LengthDelimited).fork(),n).join(),void 0!==e.protocolVersion&&t.tag(3,et.LengthDelimited).string(e.protocolVersion);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};new class extends tn{constructor(){super("identify",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.id="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.id=e.string();break;case 3:i.protocolVersion=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.id&&t.tag(2,et.LengthDelimited).string(e.id),void 0!==e.protocolVersion&&t.tag(3,et.LengthDelimited).string(e.protocolVersion);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},new class extends tn{constructor(){super("endpointIdConfirm",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"committedId",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.committedId="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.committedId=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.committedId&&t.tag(2,et.LengthDelimited).string(e.committedId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};const rn=new class extends tn{constructor(){super("streamerIdChanged",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"newID",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.newID="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.newID=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.newID&&t.tag(2,et.LengthDelimited).string(e.newID);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},on=new class extends tn{constructor(){super("listStreamers",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},an=new class extends tn{constructor(){super("streamerList",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"ids",kind:"scalar",repeat:2,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.ids=[],void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.ids.push(e.string());break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);for(let n=0;n<e.ids.length;n++)t.tag(2,et.LengthDelimited).string(e.ids[n]);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},ln=new class extends tn{constructor(){super("subscribe",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"streamerId",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.streamerId="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.streamerId=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.streamerId&&t.tag(2,et.LengthDelimited).string(e.streamerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};new class extends tn{constructor(){super("unsubscribe",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};const cn=new class extends tn{constructor(){super("subscribeFailed",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"message",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.message="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.message=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.message&&t.tag(2,et.LengthDelimited).string(e.message);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.dataChannel=!1,t.sfu=!1,t.playerId="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.dataChannel=e.bool();break;case 3:i.sfu=e.bool();break;case 5:i.playerId=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),!1!==e.dataChannel&&t.tag(2,et.Varint).bool(e.dataChannel),!1!==e.sfu&&t.tag(3,et.Varint).bool(e.sfu),""!==e.playerId&&t.tag(5,et.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},new class extends tn{constructor(){super("playerDisconnected",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"playerId",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.playerId="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.playerId=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.playerId&&t.tag(2,et.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};const dn=new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.sdp="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.sdp=e.string();break;case 3:i.playerId=e.string();break;case 4:i.sfu=e.bool();break;case 5:i.multiplex=e.bool();break;case 6:i.scalabilityMode=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.sdp&&t.tag(2,et.LengthDelimited).string(e.sdp),void 0!==e.playerId&&t.tag(3,et.LengthDelimited).string(e.playerId),void 0!==e.sfu&&t.tag(4,et.Varint).bool(e.sfu),void 0!==e.multiplex&&t.tag(5,et.Varint).bool(e.multiplex),void 0!==e.scalabilityMode&&t.tag(6,et.LengthDelimited).string(e.scalabilityMode);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},hn=new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.sdp="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.sdp=e.string();break;case 3:i.playerId=e.string();break;case 4:i.minBitrateBps=e.int32();break;case 5:i.maxBitrateBps=e.int32();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.sdp&&t.tag(2,et.LengthDelimited).string(e.sdp),void 0!==e.playerId&&t.tag(3,et.LengthDelimited).string(e.playerId),void 0!==e.minBitrateBps&&t.tag(4,et.Varint).int32(e.minBitrateBps),void 0!==e.maxBitrateBps&&t.tag(5,et.Varint).int32(e.maxBitrateBps);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},un=new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.candidate="",t.sdpMid="",t.sdpMLineIndex=0,void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.candidate=e.string();break;case 2:i.sdpMid=e.string();break;case 3:i.sdpMLineIndex=e.int32();break;case 4:i.usernameFragment=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.candidate&&t.tag(1,et.LengthDelimited).string(e.candidate),""!==e.sdpMid&&t.tag(2,et.LengthDelimited).string(e.sdpMid),0!==e.sdpMLineIndex&&t.tag(3,et.Varint).int32(e.sdpMLineIndex),void 0!==e.usernameFragment&&t.tag(4,et.LengthDelimited).string(e.usernameFragment);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},gn=new class extends tn{constructor(){super("iceCandidate",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"candidate",kind:"message",T:()=>un},{no:3,name:"playerId",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.candidate=un.internalBinaryRead(e,e.uint32(),n,i.candidate);break;case 3:i.playerId=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),e.candidate&&un.internalBinaryWrite(e.candidate,t.tag(2,et.LengthDelimited).fork(),n).join(),void 0!==e.playerId&&t.tag(3,et.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.playerId="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.playerId=e.string();break;case 3:i.reason=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.playerId&&t.tag(2,et.LengthDelimited).string(e.playerId),void 0!==e.reason&&t.tag(3,et.LengthDelimited).string(e.reason);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};const pn=new class extends tn{constructor(){super("ping",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"time",kind:"scalar",T:5}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.time=0,void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.time=e.int32();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),0!==e.time&&t.tag(2,et.Varint).int32(e.time);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},mn=new class extends tn{constructor(){super("pong",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"time",kind:"scalar",T:5}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.time=0,void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.time=e.int32();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),0!==e.time&&t.tag(2,et.Varint).int32(e.time);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};new class extends tn{constructor(){super("streamerDisconnected",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};const fn=new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.spatialLayer=0,t.temporalLayer=0,t.playerId="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.spatialLayer=e.int32();break;case 3:i.temporalLayer=e.int32();break;case 4:i.playerId=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),0!==e.spatialLayer&&t.tag(2,et.Varint).int32(e.spatialLayer),0!==e.temporalLayer&&t.tag(3,et.Varint).int32(e.temporalLayer),""!==e.playerId&&t.tag(4,et.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},yn=new class extends tn{constructor(){super("dataChannelRequest",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},vn=new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.playerId="",t.sendStreamId=0,t.recvStreamId=0,void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.playerId=e.string();break;case 3:i.sendStreamId=e.int32();break;case 4:i.recvStreamId=e.int32();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.playerId&&t.tag(2,et.LengthDelimited).string(e.playerId),0!==e.sendStreamId&&t.tag(3,et.Varint).int32(e.sendStreamId),0!==e.recvStreamId&&t.tag(4,et.Varint).int32(e.recvStreamId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},Sn=new class extends tn{constructor(){super("peerDataChannelsReady",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};new class extends tn{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){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.sfuId="",t.sendStreamId=0,t.recvStreamId=0,void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.sfuId=e.string();break;case 3:i.sendStreamId=e.int32();break;case 4:i.recvStreamId=e.int32();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.sfuId&&t.tag(2,et.LengthDelimited).string(e.sfuId),0!==e.sendStreamId&&t.tag(3,et.Varint).int32(e.sendStreamId),0!==e.recvStreamId&&t.tag(4,et.Varint).int32(e.recvStreamId);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},new class extends tn{constructor(){super("startStreaming",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}},new class extends tn{constructor(){super("stopStreaming",[{no:1,name:"type",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();if(1===t)i.type=e.string();else{let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};const bn=new class extends tn{constructor(){super("playerCount",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"count",kind:"scalar",T:5}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.count=0,void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.count=e.int32();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),0!==e.count&&t.tag(2,et.Varint).int32(e.count);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};function wn(e,t){const n=e.create();return n.type=e.typeName,t&&e.mergePartial(n,t),n}new class extends tn{constructor(){super("stats",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"data",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.type="",t.data="",void 0!==e&&rt(this,t,e),t}internalBinaryRead(e,t,n,s){let i=null!=s?s:this.create(),r=e.pos+t;for(;e.pos<r;){let[t,s]=e.tag();switch(t){case 1:i.type=e.string();break;case 2:i.data=e.string();break;default:let r=n.readUnknownField;if("throw"===r)throw new globalThis.Error(`Unknown field ${t} (wire type ${s}) for ${this.typeName}`);let o=e.skip(s);!1!==r&&(!0===r?Ze.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,et.LengthDelimited).string(e.type),""!==e.data&&t.tag(2,et.LengthDelimited).string(e.data);let s=n.writeUnknownFields;return!1!==s&&(1==s?Ze.onWrite:s)(this.typeName,e,t),t}};class Cn{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;!1!==this.alive?(this.alive=!1,this.protocol.sendMessage(wn(pn,{time:(new Date).getTime()}))):null===(e=this.onTimeout)||void 0===e||e.call(this)}onHeartbeatResponse(e){this.rtt=(new Date).getTime()-e.time,this.alive=!0}}class Mn{constructor(e){this.videoElementProvider=e,this.audioElement=document.createElement("Audio"),this.videoElementProvider.setAudioElement(this.audioElement)}handleOnTrack(e){if(G.Info("handleOnTrack "+JSON.stringify(e.streams)),e.streams.length<1||"probator"===e.streams[0].id)return;const t=this.videoElementProvider.getVideoElement();if(e.track&&G.Info("Got track - "+e.track.kind+" id="+e.track.id+" readyState="+e.track.readyState),"audio"!==e.track.kind)return"video"===e.track.kind&&t.srcObject!==e.streams[0]?(t.srcObject=e.streams[0],void G.Info("Set video source from video track ontrack.")):void 0;this.CreateAudioTrack(e.streams[0])}CreateAudioTrack(e){const t=this.videoElementProvider.getVideoElement();t.srcObject!=e&&t.srcObject&&t.srcObject!==e&&(this.audioElement.srcObject=e,G.Info("Created new audio element to play separate audio stream."))}}class Tn{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){const t=btoa(e.reduce((e,t)=>e+String.fromCharCode(t),""));this.imageElement.src="data:image/jpeg;base64,"+t}setDimensionsFromElementAndResize(){this.freezeFrameHeight=this.imageElement.naturalHeight,this.freezeFrameWidth=this.imageElement.naturalWidth,this.resize()}resize(){if(0!==this.freezeFrameWidth&&0!==this.freezeFrameHeight){let e=0,t=0,n=0,s=0;const i=this.rootDiv.clientWidth/this.rootDiv.clientHeight,r=this.freezeFrameWidth/this.freezeFrameHeight;i<r?(e=this.rootDiv.clientWidth,t=Math.floor(this.rootDiv.clientWidth/r),n=Math.floor(.5*(this.rootDiv.clientHeight-t)),s=0):(e=Math.floor(this.rootDiv.clientHeight*r),t=this.rootDiv.clientHeight,n=0,s=Math.floor(.5*(this.rootDiv.clientWidth-e))),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=s+"px",this.imageElement.style.top=n+"px"}}}class En{constructor(e){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new Tn(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);const n=e.slice(5);if(this.jpeg){const e=new Uint8Array(this.jpeg.length+n.length);e.set(this.jpeg,0),e.set(n,this.jpeg.length),this.jpeg=e}else this.jpeg=n,this.receiving=!0,G.Info(`received first chunk of freeze frame: ${this.jpeg.length}/${this.size}`);this.jpeg.length===this.size?(this.receiving=!1,this.valid=!0,G.Info(`received complete freeze frame ${this.size}`),this.updateFreezeFrameAndShow(this.jpeg,t)):this.jpeg.length>this.size&&(G.Error(`received bigger freeze frame than advertised: ${this.jpeg.length}/${this.size}`),this.jpeg=void 0,this.receiving=!1)}}class Rn{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=()=>{G.Warning("AFK timed out, did you want to override this callback?")}}onAfkClick(){clearInterval(this.countDownTimer),(this.active||this.countdownActive)&&(this.startAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new se))}startAfkWarningTimer(){this.config.getNumericSettingValue(qe.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(He.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(He.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout(()=>this.activateAfkEvent(),1e3*this.config.getNumericSettingValue(qe.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new te({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(qe.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new ne({countDown:this.countDown})),this.config.isFlagEnabled(He.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval(()=>{this.countDown--,0===this.countDown?(this.pixelStreaming.dispatchEvent(new ie),this.onAFKTimedOutCallback(),G.Info("You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new ne({countDown:this.countDown}))},1e3)}}class kn{constructor(){this.isReceivingFreezeFrame=!1}getDataChannelInstance(){return this}createDataChannel(e,t,n){this.peerConnection=e,this.label=t,this.datachannelOptions=n,null==n&&(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;G.Info(`Data Channel (${this.label}) opened.`),this.onOpen(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}handleOnClose(e){var t;G.Info(`Data Channel (${this.label}) closed.`),this.onClose(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}handleOnMessage(e){G.Info(`Data Channel (${this.label}) message: ${e.type}`)}handleOnError(e){var t;G.Info(`Data Channel (${this.label}) error: ${e.type}`),this.onError(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}onOpen(e,t){}onClose(e,t){}onError(e,t){}}class Pn{}class In{}class xn{}class Ln{}class An{}class Dn{}class On{}class Fn{}class Nn{constructor(){this.inboundVideoStats=new In,this.inboundAudioStats=new Pn,this.candidatePairs=new Array,this.datachannelStats=new xn,this.localCandidates=new Array,this.remoteCandidates=new Array,this.outboundVideoStats=new An,this.outboundAudioStats=new An,this.remoteOutboundAudioStats=new Dn,this.remoteOutboundVideoStats=new Dn,this.sessionStats=new On,this.streamStats=new Fn,this.codecs=new Map}processStats(e){this.localCandidates=new Array,this.remoteCandidates=new Array,this.candidatePairs=new Array,e.forEach(e=>{switch(e.type){case"candidate-pair":this.handleCandidatePair(e);break;case"certificate":case"media-source":case"media-playout":case"peer-connection":case"remote-inbound-rtp":break;case"codec":this.handleCodec(e);break;case"data-channel":this.handleDataChannel(e);break;case"inbound-rtp":this.handleInboundRTP(e);break;case"local-candidate":this.handleLocalCandidate(e);break;case"outbound-rtp":this.handleLocalOutbound(e);break;case"remote-candidate":this.handleRemoteCandidate(e);break;case"remote-outbound-rtp":this.handleRemoteOutbound(e);break;case"track":this.handleTrack(e);break;case"transport":this.handleTransport(e);break;case"stream":this.handleStream(e);break;default:G.Error("unhandled Stat Type"),G.Info(e)}})}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){const t=new Ln;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){const t=new Ln;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(const 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(const t in e)this.inboundAudioStats[t]=e[t];break;default:G.Error(`Kind should be audio or video, we got ${e.kind} - that's unsupported.`)}}handleLocalOutbound(e){const t="audio"===e.kind?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){const t="audio"===e.kind?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){"track"!==e.type||"video_label"!==e.trackIdentifier&&"video"!==e.kind||(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){const t=e.id;this.codecs.set(t,e)}handleSessionStatistics(e,t,n){const s=Date.now()-e;this.sessionStats.runTime=new Date(s).toISOString().substr(11,8).toString();const i=null===t?"Not sent yet":t?"true":"false";this.sessionStats.controlsStreamInput=i,this.sessionStats.videoEncoderAvgQP=n}isNumber(e){return"number"==typeof e&&isFinite(e)}getActiveCandidatePair(){if(void 0===this.candidatePairs)return null;if(this.transportStats){const e=this.candidatePairs.find(e=>e.id===this.transportStats.selectedCandidatePairId);return void 0===e?null:e}const e=this.candidatePairs.find(e=>e.selected);return void 0===e?null:e}}i();class Un{static isVideoTransceiver(e){return this.canTransceiverReceiveVideo(e)||this.canTransceiverSendVideo(e)}static canTransceiverReceiveVideo(e){return!!e&&("sendrecv"===e.direction||"recvonly"===e.direction)&&e.receiver&&e.receiver.track&&"video"===e.receiver.track.kind}static canTransceiverSendVideo(e){return!!e&&("sendrecv"===e.direction||"sendonly"===e.direction)&&e.sender&&e.sender.track&&"video"===e.sender.track.kind}static isAudioTransceiver(e){return this.canTransceiverReceiveAudio(e)||this.canTransceiverSendAudio(e)}static canTransceiverReceiveAudio(e){return!!e&&("sendrecv"===e.direction||"recvonly"===e.direction)&&e.receiver&&e.receiver.track&&"audio"===e.receiver.track.kind}static canTransceiverSendAudio(e){return!!e&&("sendrecv"===e.direction||"sendonly"===e.direction)&&e.sender&&e.sender.track&&"audio"===e.sender.track.kind}}class Bn{static addVideoHeaderExtensionToSdp(e,t){const n=e.split("\n").filter(e=>e.startsWith("a=extmap:")).map(e=>parseInt(e.split(" ")[0].substring(9),10)).sort((e,t)=>e-t).filter((e,t,n)=>n.indexOf(e)===t),s="a=extmap:"+(n[n.length-1]+1)+" "+t+"\r\n",i=e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n");return i.shift()+i.map(e=>e.startsWith("m=video")?e+s:e).join("")}}class Vn{}class _n{}class Wn{constructor(){this.latestSenderRecvClockOffset=null}calculate(e,t){const n=new $n,s=this.getRTTMs(e);if(null!=s){n.rttMs=s;const i=this.getCaptureSource(t);if(null!=i){const t=this.calculateSenderLatency(e,i);null!==t&&(n.senderLatencyMs=t)}}return void 0!==e.inboundVideoStats.totalProcessingDelay&&void 0!==e.inboundVideoStats.framesDecoded&&(n.averageProcessingDelayMs=e.inboundVideoStats.totalProcessingDelay/e.inboundVideoStats.framesDecoded*1e3),void 0!==e.inboundVideoStats.jitterBufferDelay&&void 0!==e.inboundVideoStats.jitterBufferEmittedCount&&(n.averageJitterBufferDelayMs=e.inboundVideoStats.jitterBufferDelay/e.inboundVideoStats.jitterBufferEmittedCount*1e3),void 0!==e.inboundVideoStats.framesDecoded&&void 0!==e.inboundVideoStats.totalDecodeTime&&(n.averageDecodeLatencyMs=e.inboundVideoStats.totalDecodeTime/e.inboundVideoStats.framesDecoded*1e3),void 0!==e.inboundVideoStats.totalAssemblyTime&&void 0!==e.inboundVideoStats.framesAssembledFromMultiplePackets&&(n.averageAssemblyDelayMs=e.inboundVideoStats.totalAssemblyTime/e.inboundVideoStats.framesAssembledFromMultiplePackets*1e3),void 0!==e.inboundVideoStats.googTimingFrameInfo&&e.inboundVideoStats.googTimingFrameInfo.length>0&&(n.frameTiming=this.extractFrameTimingInfo(e.inboundVideoStats.googTimingFrameInfo)),void 0!==n.frameTiming&&void 0!==n.frameTiming.captureToSendLatencyMs&&void 0!==n.averageProcessingDelayMs&&void 0!==n.rttMs&&(n.averageE2ELatency=n.frameTiming.captureToSendLatencyMs+.5*n.rttMs+n.averageProcessingDelayMs),null!=n.senderLatencyMs&&void 0!==n.averageProcessingDelayMs&&void 0!==n.rttMs&&(n.averageE2ELatency=n.senderLatencyMs+.5*n.rttMs+n.averageProcessingDelayMs),n}extractFrameTimingInfo(e){const t=new _n,n=e.split(",");return 15===n.length&&(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){const n=t.captureTimestamp+t.senderCaptureTimeOffset;let s=this.calculateSenderReceiverClockOffset(e);if(null==s){if(null==this.latestSenderRecvClockOffset)return null;s=this.latestSenderRecvClockOffset}else this.latestSenderRecvClockOffset=s;const i=n+s-22089888e5;return t.timestamp-i}getCaptureSource(e){e=e.filter(e=>"video"===e.track.kind);for(const t of e){const e=t.getSynchronizationSources().concat(t.getContributingSources());for(const t of e)if(void 0!==t.captureTimestamp&&void 0!==t.senderCaptureTimeOffset&&void 0!==t.timestamp){const e=new Vn;return e.timestamp=t.timestamp,e.captureTimestamp=t.captureTimestamp,e.senderCaptureTimeOffset=t.senderCaptureTimeOffset,e}}return null}calculateSenderReceiverClockOffset(e){if(void 0===e.remoteOutboundVideoStats||void 0===e.remoteOutboundVideoStats.timestamp||void 0===e.remoteOutboundVideoStats.remoteTimestamp)return null;const t=e.remoteOutboundVideoStats.timestamp,n=e.remoteOutboundVideoStats.remoteTimestamp,s=this.getRTTMs(e);return void 0!==t&&void 0!==n&&null!==s?t-(n+.5*s):null}getRTTMs(e){const t=e.getActiveCandidatePair();return t&&void 0!==t.currentRoundTripTime?1e3*t.currentRoundTripTime:e.remoteOutboundVideoStats&&void 0!==e.remoteOutboundVideoStats.totalRoundTripTime&&void 0!==e.remoteOutboundVideoStats.roundTripTimeMeasurements&&e.remoteOutboundVideoStats.roundTripTimeMeasurements>0?e.remoteOutboundVideoStats.totalRoundTripTime/e.remoteOutboundVideoStats.roundTripTimeMeasurements*1e3:e.remoteOutboundAudioStats&&void 0!==e.remoteOutboundAudioStats.totalRoundTripTime&&void 0!==e.remoteOutboundAudioStats.roundTripTimeMeasurements&&e.remoteOutboundAudioStats.roundTripTimeMeasurements>0?e.remoteOutboundAudioStats.totalRoundTripTime/e.remoteOutboundAudioStats.roundTripTimeMeasurements*1e3:null}}class $n{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 Hn=function(e,t,n,s){return new(n||(n=Promise))(function(i,r){function o(e){try{l(s.next(e))}catch(e){r(e)}}function a(e){try{l(s.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}l((s=s.apply(e,t||[])).next())})};class jn{constructor(e,t,n){this.config=t,this.createPeerConnection(e,n),this.latencyCalculator=new Wn}createPeerConnection(e,t){this.config.isFlagEnabled(He.ForceTURN)&&(e.iceTransportPolicy="relay",G.Info("Forcing TURN usage by setting ICE Transport Policy in peer connection config.")),this.peerConnection=new RTCPeerConnection(e),this.peerConnection.onsignalingstatechange=e=>this.handleSignalStateChange(e),this.peerConnection.oniceconnectionstatechange=e=>this.handleIceConnectionStateChange(e),this.peerConnection.onicegatheringstatechange=e=>this.handleIceGatheringStateChange(e),this.peerConnection.ontrack=e=>this.handleOnTrack(e),this.peerConnection.onicecandidate=e=>this.handleIceCandidate(e),this.peerConnection.ondatachannel=e=>this.handleDataChannel(e),this.aggregatedStats=new Nn,this.preferredCodec=t,this.updateCodecSelection=!0}createOffer(e,t){G.Info("Create Offer");const n="localhost"===location.hostname||"127.0.0.1"===location.hostname,s="https:"===location.protocol;let i=t.isFlagEnabled(He.UseMic),r=t.isFlagEnabled(He.UseCamera);!i&&!r||n||s||(i=!1,r=!1,G.Error("Microphone and Webcam access in the browser will not work if you are not on HTTPS or localhost. Disabling mic and webcam access."),G.Error("For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(i,r).finally(()=>{var t;null===(t=this.peerConnection)||void 0===t||t.createOffer(e).then(e=>{var t;this.showTextOverlayConnecting(),e.sdp=this.mungeSDP(e.sdp,i),null===(t=this.peerConnection)||void 0===t||t.setLocalDescription(e),this.onSendWebRTCOffer(e)}).catch(()=>{this.showTextOverlaySetupFailure()})})}receiveOffer(e,t){var n;G.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,"")),null===(n=this.peerConnection)||void 0===n||n.setRemoteDescription(e).then(()=>{this.onSetRemoteDescription(e);const n="localhost"===location.hostname||"127.0.0.1"===location.hostname,s="https:"===location.protocol;let i=t.isFlagEnabled(He.UseMic),r=t.isFlagEnabled(He.UseCamera);!i&&!r||n||s||(i=!1,r=!1,G.Error("Microphone and Webcam access in the browser will not work if you are not on HTTPS or localhost. Disabling mic and webcam access."),G.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(Ge.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e)),this.setupTransceiversAsync(i,r).finally(()=>{var e;null===(e=this.peerConnection)||void 0===e||e.createAnswer().then(e=>{var t;return e.sdp=this.mungeSDP(e.sdp,i),null===(t=this.peerConnection)||void 0===t?void 0:t.setLocalDescription(e)}).then(()=>{var e;this.onSetLocalDescription(null===(e=this.peerConnection)||void 0===e?void 0:e.localDescription)}).catch(e=>{G.Error(`createAnswer() failed - ${e}`)})})})}receiveAnswer(e){var t;null===(t=this.peerConnection)||void 0===t||t.setRemoteDescription(e),this.config.setOptionSettingOptions(Ge.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e))}generateStats(){var e;null===(e=this.peerConnection)||void 0===e||e.getStats().then(e=>{this.aggregatedStats.processStats(e),this.onVideoStats(this.aggregatedStats);const t=this.latencyCalculator.calculate(this.aggregatedStats,this.peerConnection.getReceivers());if(this.onLatencyCalculated(t),this.updateCodecSelection&&this.aggregatedStats.inboundVideoStats.codecId){const e=this.aggregatedStats.codecs.get(this.aggregatedStats.inboundVideoStats.codecId);if(void 0===e)return;const t=e.mimeType.replace("video/","");let n=t;e.sdpFmtpLine&&""!==e.sdpFmtpLine.trim()&&(n=`${t} ${e.sdpFmtpLine.trim()}`);const s=this.config.getSettingOption(Ge.PreferredCodec).options;if(s.includes(n))return void this.config.setOptionSettingValue(Ge.PreferredCodec,n);const i=s.filter(e=>-1!==e.indexOf(t));if(i.length>0)return void this.config.setOptionSettingValue(Ge.PreferredCodec,i[0])}})}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\n"),s="maxaveragebitrate=510000;";return t&&(s+="sprop-maxcapturerate=48000;"),s+=this.config.isFlagEnabled(He.ForceMonoAudio)?"stereo=0;":"stereo=1;",s+="useinbandfec=1",n=n.replace("useinbandfec=1",s),this.config.isFlagEnabled(He.EnableCaptureTimeExt)&&!this.isFirefox()&&(n=Bn.addVideoHeaderExtensionToSdp(n,"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time")),n}isFirefox(){return navigator.userAgent.indexOf("Firefox")>0}handleOnIce(e){var t;G.Info("peerconnection handleOnIce"),this.config.isFlagEnabled(He.ForceTURN)&&e.candidate.indexOf("relay")<0?G.Info(`Dropping candidate because it was not TURN relay. | Type= ${e.type} | Protocol= ${e.protocol} | Address=${e.address} | Port=${e.port} |`):null===(t=this.peerConnection)||void 0===t||t.addIceCandidate(e)}handleSignalStateChange(e){var t;G.Info("signaling state change: "+(null===(t=this.peerConnection)||void 0===t?void 0:t.signalingState))}handleIceConnectionStateChange(e){var t;G.Info("ice connection state change: "+(null===(t=this.peerConnection)||void 0===t?void 0:t.iceConnectionState)),this.onIceConnectionStateChange(e)}handleIceGatheringStateChange(e){G.Info("ice gathering state change: "+JSON.stringify(e))}handleOnTrack(e){e.streams.length<1||"probator"===e.streams[0].id||("video"===e.track.kind&&(this.videoTrack=e.track),"audio"===e.track.kind&&(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){const t=new Array,n=this.parseAvailableCodecs(e),s=this.config.getSettingOption(Ge.PreferredCodec).options;for(const e of n)if(s.includes(e))t.push(e);else{const n=e.split(" ")[0];for(const e of s)if(e.includes(n)){t.push(e);break}}return t}setupTransceiversAsync(e,t){return Hn(this,void 0,void 0,function*(){var n,s,i,r,o,a,l,c;let d=!1;for(const e of null!==(s=null===(n=this.peerConnection)||void 0===n?void 0:n.getTransceivers())&&void 0!==s?s:[])if(e&&e.receiver&&e.receiver.track&&"video"===e.receiver.track.kind){d=!0;break}if(t?yield this.setupVideoSender(d):d||null===(i=this.peerConnection)||void 0===i||i.addTransceiver("video",{direction:"recvonly"}),RTCRtpReceiver.getCapabilities&&""!=this.preferredCodec)for(const e of null!==(o=null===(r=this.peerConnection)||void 0===r?void 0:r.getTransceivers())&&void 0!==o?o:[])if(e&&e.receiver&&e.receiver.track&&"video"===e.receiver.track.kind&&e.setCodecPreferences){const t=this.preferredCodec.split(" "),n={mimeType:"video/"+t[0],clockRate:9e4,sdpFmtpLine:t[1]?t[1]:""},s=[n];RTCRtpReceiver.getCapabilities("video").codecs.forEach(e=>{(e.mimeType!=n.mimeType||(null==e?void 0:e.sdpFmtpLine)!=(null==n?void 0:n.sdpFmtpLine))&&s.push(e)});for(const e of s)void 0!==(null==e?void 0:e.sdpFmtpLine)&&""!==e.sdpFmtpLine||delete e.sdpFmtpLine;e.setCodecPreferences(s)}let h=!1;for(const e of null!==(l=null===(a=this.peerConnection)||void 0===a?void 0:a.getTransceivers())&&void 0!==l?l:[])if(e&&e.receiver&&e.receiver.track&&"audio"===e.receiver.track.kind){h=!0;break}e?yield this.setupAudioSender(h):h||null===(c=this.peerConnection)||void 0===c||c.addTransceiver("audio",{direction:"recvonly"})})}setupVideoSender(e){return Hn(this,void 0,void 0,function*(){var t,n,s,i;const r=yield navigator.mediaDevices.getUserMedia({video:!0});if(r)if(e){for(const e of null!==(n=null===(t=this.peerConnection)||void 0===t?void 0:t.getTransceivers())&&void 0!==n?n:[])if(Un.canTransceiverReceiveVideo(e))for(const t of r.getTracks())"video"===t.kind&&(e.sender.replaceTrack(t),e.direction="sendrecv")}else for(const e of r.getTracks())"video"===e.kind&&(null===(s=this.peerConnection)||void 0===s||s.addTransceiver(e,{direction:"sendrecv"}));else e||null===(i=this.peerConnection)||void 0===i||i.addTransceiver("video",{direction:"recvonly"})})}setupAudioSender(e){return Hn(this,void 0,void 0,function*(){var t,n,s,i;const r=yield navigator.mediaDevices.getUserMedia({video:!1,audio:{autoGainControl:!1,channelCount:1,echoCancellation:!1,latency:0,noiseSuppression:!1,sampleRate:48e3,sampleSize:16,volume:1}});if(r)if(e){for(const e of null!==(n=null===(t=this.peerConnection)||void 0===t?void 0:t.getTransceivers())&&void 0!==n?n:[])if(Un.canTransceiverReceiveAudio(e))for(const t of r.getTracks())"audio"===t.kind&&(e.sender.replaceTrack(t),e.direction="sendrecv")}else for(const e of r.getTracks())"audio"===e.kind&&(null===(s=this.peerConnection)||void 0===s||s.addTransceiver(e,{direction:"sendrecv"}));else e||null===(i=this.peerConnection)||void 0===i||i.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"];const t=[],n=(0,i().splitSections)(e.sdp);return n.shift(),n.forEach(e=>{const{codecs:n}=(0,i().parseRtpParameters)(e),s=/(VP\d|H26\d|AV1).*/;n.forEach(e=>{const n=e.name+" "+Object.keys(e.parameters||{}).map(t=>t+"="+e.parameters[t]).join(";");if(null!==s.exec(n)){"VP9"===e.name&&(e.parameters={"profile-id":"0"});const n=e.name+" "+Object.keys(e.parameters||{}).map(t=>t+"="+e.parameters[t]).join(";");t.push(n)}})}),t}}class qn{constructor(){this.PixelStreamingSettings=new zn,this.EncoderSettings=new Qn,this.WebRTCSettings=new Kn}ueCompatible(){null!=this.WebRTCSettings.MaxFPS&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}}class zn{}class Qn{}class Kn{}class Gn{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){0==this.frameDisplayDeltaTimeMs&&(this.frameDisplayDeltaTimeMs=Math.round(e))}processFields(){null!=this.EncodeMs||null==this.PreEncodeTimeMs&&null==this.PostEncodeTimeMs||(G.Info(`Setting Encode Ms \n ${this.PostEncodeTimeMs} \n ${this.PreEncodeTimeMs}`),this.EncodeMs=this.PostEncodeTimeMs-this.PreEncodeTimeMs),null!=this.CaptureToSendMs||null==this.PreCaptureTimeMs&&null==this.PostCaptureTimeMs||(G.Info(`Setting CaptureToSendMs Ms \n ${this.PostCaptureTimeMs} \n ${this.PreCaptureTimeMs}`),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}}class Xn{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(),G.Info("Received first chunk of file"));const n=new TextDecoder("utf-16").decode(e.slice(1));G.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(),G.Info("Received first chunk of file"));const n=new TextDecoder("utf-16").decode(e.slice(1));G.Info(n),t.mimetype=n}static setContentsFromBytes(e,t){if(!t.receiving)return;t.chunks=Math.ceil(new DataView(e.slice(1,5).buffer).getInt32(0,!0)/16379);const n=e.slice(5);if(t.data.push(n),G.Info(`Received file chunk: ${t.data.length}/${t.chunks}`),t.data.length===t.chunks){t.receiving=!1,t.valid=!0,G.Info("Received complete file");const e=(new Date).getTime()-t.timestampStart,n=Math.round(16384*t.chunks/e);G.Info(`Average transfer bitrate: ${n}kb/s over ${e/1e3} seconds`)}else t.data.length>t.chunks&&(t.receiving=!1,G.Error(`Received bigger file than advertised: ${t.data.length}/${t.chunks}`))}}class Jn{constructor(){this.mimetype="",this.extension="",this.receiving=!1,this.chunks=0,this.data=[],this.valid=!1}}class Yn{}Yn.backSpace=8,Yn.shift=16,Yn.control=17,Yn.alt=18,Yn.rightShift=253,Yn.rightControl=254,Yn.rightAlt=255;const Zn=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,MetaLeft:91,MetaRight:92,OSLeft:91,OSRight:92});class es{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;const n=this.getKeycode(e);n&&229!==n&&(null===(t=this.streamMessageController.toStreamerHandlers.get("KeyDown"))||void 0===t||t([this.getKeycode(e),e.repeat?1:0]),this.activeKeys.getActiveKeys().push(n),n===Yn.backSpace&&this.handleOnKeyPress(new KeyboardEvent("keypress",{charCode:Yn.backSpace,keyCode:Yn.backSpace})),this.config.isFlagEnabled(He.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(n)&&e.preventDefault())}handleOnKeyUp(e){var t;const n=this.getKeycode(e);n&&(null===(t=this.streamMessageController.toStreamerHandlers.get("KeyUp"))||void 0===t||t([n]),this.config.isFlagEnabled(He.SuppressBrowserKeys)&&this.isKeyCodeBrowserKey(n)&&e.preventDefault())}handleOnKeyPress(e){var t;const n=this.getKeycode(e);n&&(null===(t=this.streamMessageController.toStreamerHandlers.get("KeyPress"))||void 0===t||t([n]))}getKeycode(e){if(!("keyCode"in e)){const t=e;return t.code in Zn?Zn[t.code]:(G.Warning(`Keyboard code of ${t.code} is not supported in our mapping, ignoring this key.`),null)}return e.keyCode===Yn.shift&&"ShiftRight"===e.code?Yn.rightShift:e.keyCode===Yn.control&&"ControlRight"===e.code?Yn.rightControl:e.keyCode===Yn.alt&&"AltRight"===e.code?Yn.rightAlt:"MetaLeft"===e.code||"OSLeft"===e.code?Zn.MetaLeft:"MetaRight"===e.code||"OSRight"===e.code?Zn.MetaRight:e.keyCode}isKeyCodeBrowserKey(e){return e>=112&&e<=123||9===e}}class ts{}ts.mainButton=0,ts.auxiliaryButton=1,ts.secondaryButton=2,ts.fourthButton=3,ts.fifthButton=4;class ns{}ns.primaryButton=1,ns.secondaryButton=2,ns.auxiliaryButton=4,ns.fourthButton=8,ns.fifthButton=16;class ss{constructor(e,t,n,s,i){this.streamMessageController=e,this.coordinateConverter=n,this.videoPlayer=t,this.activeKeys=s,this.config=i,this.onEnterListener=this.onMouseEnter.bind(this),this.onLeaveListener=this.onMouseLeave.bind(this)}register(){this.registerMouseEnterAndLeaveEvents()}unregister(){this.unregisterMouseEnterAndLeaveEvents()}registerMouseEnterAndLeaveEvents(){const e=this.videoPlayer.getVideoParentElement();null==e||e.addEventListener("mouseenter",this.onEnterListener),null==e||e.addEventListener("mouseleave",this.onLeaveListener)}unregisterMouseEnterAndLeaveEvents(){const e=this.videoPlayer.getVideoParentElement();null==e||e.removeEventListener("mouseenter",this.onEnterListener),null==e||e.removeEventListener("mouseleave",this.onLeaveListener)}onMouseEnter(e){var t;this.videoPlayer.isVideoReady()&&(null===(t=this.streamMessageController.toStreamerHandlers.get("MouseEnter"))||void 0===t||t(),this.pressMouseButtons(e.buttons,e.x,e.y))}onMouseLeave(e){var t;this.videoPlayer.isVideoReady()&&(null===(t=this.streamMessageController.toStreamerHandlers.get("MouseLeave"))||void 0===t||t(),this.releaseMouseButtons(e.buttons,e.x,e.y))}releaseMouseButtons(e,t,n){const s=this.coordinateConverter.translateUnsigned(t,n);e&ns.primaryButton&&this.sendMouseUp(ts.mainButton,s.x,s.y),e&ns.secondaryButton&&this.sendMouseUp(ts.secondaryButton,s.x,s.y),e&ns.auxiliaryButton&&this.sendMouseUp(ts.auxiliaryButton,s.x,s.y),e&ns.fourthButton&&this.sendMouseUp(ts.fourthButton,s.x,s.y),e&ns.fifthButton&&this.sendMouseUp(ts.fifthButton,s.x,s.y)}pressMouseButtons(e,t,n){if(!this.videoPlayer.isVideoReady())return;const s=this.coordinateConverter.translateUnsigned(t,n);e&ns.primaryButton&&this.sendMouseDown(ts.mainButton,s.x,s.y),e&ns.secondaryButton&&this.sendMouseDown(ts.secondaryButton,s.x,s.y),e&ns.auxiliaryButton&&this.sendMouseDown(ts.auxiliaryButton,s.x,s.y),e&ns.fourthButton&&this.sendMouseDown(ts.fourthButton,s.x,s.y),e&ns.fifthButton&&this.sendMouseDown(ts.fifthButton,s.x,s.y)}sendMouseDown(e,t,n){var s;null===(s=this.streamMessageController.toStreamerHandlers.get("MouseDown"))||void 0===s||s([e,t,n])}sendMouseUp(e,t,n){var s;const i=this.coordinateConverter.translateUnsigned(t,n);null===(s=this.streamMessageController.toStreamerHandlers.get("MouseUp"))||void 0===s||s([e,i.x,i.y])}}class is extends ss{constructor(e,t,n,s,i){super(e,t,n,s,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(){const 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?(G.Info("Pointer locked"),document.addEventListener("mousemove",this.onMouseMoveListener)):(G.Info("The pointer lock status is now unlocked"),document.removeEventListener("mousemove",this.onMouseMoveListener),this.activeKeys.getActiveKeys().forEach(e=>{this.streamMessageController.toStreamerHandlers.get("KeyUp")([e])}))}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;const 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);const s=this.coordinateConverter.translateSigned(e.movementX,e.movementY);this.streamMessageController.toStreamerHandlers.get("MouseMove")([this.normalizedCoord.x,this.normalizedCoord.y,s.x,s.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]),this.config.isFlagEnabled(He.MouseDoubleClickAutoRelease)&&this.streamMessageController.toStreamerHandlers.get("MouseUp")([e.button,this.normalizedCoord.x,this.normalizedCoord.y]))}}class rs extends ss{constructor(e,t,n,s,i){super(e,t,n,s,i),this.pressedButtons=new Set,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),this.pressedButtons.size>0&&(window.removeEventListener("mousemove",this.onMouseMoveListener),window.removeEventListener("mouseup",this.onMouseUpListener),this.pressedButtons.clear()),super.unregister()}startCapturing(){this.videoElementParent.removeEventListener("mousemove",this.onMouseMoveListener),this.videoElementParent.removeEventListener("mouseup",this.onMouseUpListener),window.addEventListener("mousemove",this.onMouseMoveListener),window.addEventListener("mouseup",this.onMouseUpListener)}stopCapturing(){window.removeEventListener("mousemove",this.onMouseMoveListener),window.removeEventListener("mouseup",this.onMouseUpListener),this.videoElementParent.addEventListener("mousemove",this.onMouseMoveListener),this.videoElementParent.addEventListener("mouseup",this.onMouseUpListener)}offsetFromVideo(e){if(e.currentTarget===this.videoElementParent)return{x:e.offsetX,y:e.offsetY};const t=this.videoElementParent.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}onMouseDown(e){if(!this.videoPlayer.isVideoReady())return;const t=this.offsetFromVideo(e),n=this.coordinateConverter.translateUnsigned(t.x,t.y);this.streamMessageController.toStreamerHandlers.get("MouseDown")([e.button,n.x,n.y]),e.preventDefault(),0===this.pressedButtons.size&&this.startCapturing(),this.pressedButtons.add(e.button)}onMouseUp(e){if(!this.videoPlayer.isVideoReady())return;const t=this.offsetFromVideo(e),n=this.coordinateConverter.translateUnsigned(t.x,t.y);this.streamMessageController.toStreamerHandlers.get("MouseUp")([e.button,n.x,n.y]),e.preventDefault(),this.pressedButtons.delete(e.button),0===this.pressedButtons.size&&this.stopCapturing()}onContextMenu(e){this.videoPlayer.isVideoReady()&&e.preventDefault()}onMouseMove(e){if(!this.videoPlayer.isVideoReady())return;const t=this.offsetFromVideo(e),n=this.coordinateConverter.translateUnsigned(t.x,t.y),s=this.coordinateConverter.translateSigned(e.movementX,e.movementY);this.streamMessageController.toStreamerHandlers.get("MouseMove")([n.x,n.y,s.x,s.y]),e.currentTarget===this.videoElementParent&&e.preventDefault()}onMouseWheel(e){if(!this.videoPlayer.isVideoReady())return;const 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;const t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY);this.streamMessageController.toStreamerHandlers.get("MouseDouble")([e.button,t.x,t.y]),this.config.isFlagEnabled(He.MouseDoubleClickAutoRelease)&&this.streamMessageController.toStreamerHandlers.get("MouseUp")([e.button,t.x,t.y])}}class os{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){const t=this.fingers.pop();void 0===t&&G.Info("exhausted touch identifiers"),this.fingerIds.set(e.identifier,t)}forgetTouch(e){this.fingers.push(this.fingerIds.get(e.identifier)),this.fingers.sort(function(e,t){return t-e}),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;const n=this.videoPlayer.getVideoParentElement().getBoundingClientRect(),s=this.streamMessageController.toStreamerHandlers;for(let i=0;i<t.length;i++){const r=1,o=t[i],a=o.clientX-n.left,l=o.clientY-n.top;G.Info(`F${this.fingerIds.get(o.identifier)}=(${a}, ${l})`);const c=this.coordinateConverter.translateUnsigned(a,l);switch(e){case"TouchStart":s.get("TouchStart")([r,c.x,c.y,this.fingerIds.get(o.identifier),this.maxByteValue*(o.force>0?o.force:1),c.inRange?1:0]);break;case"TouchEnd":s.get("TouchEnd")([r,c.x,c.y,this.fingerIds.get(o.identifier),this.maxByteValue*o.force,c.inRange?1:0]);break;case"TouchMove":s.get("TouchMove")([r,c.x,c.y,this.fingerIds.get(o.identifier),this.maxByteValue*(o.force>0?o.force:1),c.inRange?1:0])}}}}class as{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(null==this.fakeTouchFinger){const t=e.changedTouches[0];this.fakeTouchFinger={id:t.identifier,x:t.clientX-this.videoElementParentClientRect.left,y:t.clientY-this.videoElementParentClientRect.top};const n=this.videoPlayer.getVideoParentElement(),s=new MouseEvent("mouseenter",t);n.dispatchEvent(s);const i=this.coordinateConverter.translateUnsigned(this.fakeTouchFinger.x,this.fakeTouchFinger.y);this.streamMessageController.toStreamerHandlers.get("MouseDown")([ts.mainButton,i.x,i.y])}e.preventDefault()}}onTouchEnd(e){if(!this.videoPlayer.isVideoReady()||null==this.fakeTouchFinger)return;const t=this.videoPlayer.getVideoParentElement(),n=this.streamMessageController.toStreamerHandlers;for(let s=0;s<e.changedTouches.length;s++){const i=e.changedTouches[s];if(i.identifier===this.fakeTouchFinger.id){const e=i.clientX-this.videoElementParentClientRect.left,s=i.clientY-this.videoElementParentClientRect.top,r=this.coordinateConverter.translateUnsigned(e,s);n.get("MouseUp")([ts.mainButton,r.x,r.y]);const o=new MouseEvent("mouseleave",i);t.dispatchEvent(o),this.fakeTouchFinger=null;break}}e.preventDefault()}onTouchMove(e){if(!this.videoPlayer.isVideoReady()||null==this.fakeTouchFinger)return;const t=this.streamMessageController.toStreamerHandlers;for(let n=0;n<e.touches.length;n++){const s=e.touches[n];if(s.identifier===this.fakeTouchFinger.id){const e=s.clientX-this.videoElementParentClientRect.left,n=s.clientY-this.videoElementParentClientRect.top,i=this.coordinateConverter.translateUnsigned(e,n),r=this.coordinateConverter.translateSigned(e-this.fakeTouchFinger.x,n-this.fakeTouchFinger.y);t.get("MouseMove")([i.x,i.y,r.x,r.y]),this.fakeTouchFinger.x=e,this.fakeTouchFinger.y=n;break}}e.preventDefault()}}function ls(e){return JSON.parse(JSON.stringify({buttons:e.buttons.map(e=>JSON.parse(JSON.stringify({pressed:e.pressed,touched:e.touched,value:e.value}))),axes:e.axes}))}var cs,ds,hs;!function(e){e[e.RightClusterBottomButton=0]="RightClusterBottomButton",e[e.RightClusterRightButton=1]="RightClusterRightButton",e[e.RightClusterLeftButton=2]="RightClusterLeftButton",e[e.RightClusterTopButton=3]="RightClusterTopButton",e[e.LeftShoulder=4]="LeftShoulder",e[e.RightShoulder=5]="RightShoulder",e[e.LeftTrigger=6]="LeftTrigger",e[e.RightTrigger=7]="RightTrigger",e[e.SelectOrBack=8]="SelectOrBack",e[e.StartOrForward=9]="StartOrForward",e[e.LeftAnalogPress=10]="LeftAnalogPress",e[e.RightAnalogPress=11]="RightAnalogPress",e[e.LeftClusterTopButton=12]="LeftClusterTopButton",e[e.LeftClusterBottomButton=13]="LeftClusterBottomButton",e[e.LeftClusterLeftButton=14]="LeftClusterLeftButton",e[e.LeftClusterRightButton=15]="LeftClusterRightButton",e[e.CentreButton=16]="CentreButton",e[e.LeftStickHorizontal=0]="LeftStickHorizontal",e[e.LeftStickVertical=1]="LeftStickVertical",e[e.RightStickHorizontal=2]="RightStickHorizontal",e[e.RightStickVertical=3]="RightStickVertical"}(cs||(cs={}));class us{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);const 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(const e of navigator.getGamepads())e&&this.onGamepadConnected(new GamepadEvent("gamepadconnected",{gamepad:e}))}unregister(){window.removeEventListener("gamepadconnected",this.onGamepadConnectedListener),window.removeEventListener("gamepaddisconnected",this.onGamepadDisconnectedListener),window.removeEventListener("webkitgamepadconnected",this.onGamepadConnectedListener),window.removeEventListener("webkitgamepaddisconnected",this.onGamepadDisconnectedListener);for(const e of this.controllers)e&&void 0!==e.id&&this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([e.id]);this.controllers=[]}onGamepadResponseReceived(e){for(const t of this.controllers)if(t&&void 0===t.id){t.id=e;break}}onGamepadConnected(e){const t=e.gamepad,n={currentState:ls(t),prevState:ls(t),id:void 0};this.controllers[t.index]=n,window.requestAnimationFrame(()=>this.updateStatus()),this.streamMessageController.toStreamerHandlers.get("GamepadConnected")()}onGamepadDisconnected(e){const t=e.gamepad,n=this.controllers[t.index];this.controllers=this.controllers.filter((e,n)=>n!==t.index),void 0!==n.id&&this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([n.id])}scanGamepads(){const e=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads():[];for(let t=0;t<e.length;t++)e[t]&&void 0!==this.controllers[e[t].index]&&(this.controllers[e[t].index].currentState=e[t])}updateStatus(){this.scanGamepads();const e=this.streamMessageController.toStreamerHandlers;for(const t of this.controllers){if(!t)continue;const n=void 0===t.id?this.controllers.indexOf(t):t.id,s=t.currentState;for(let s=0;s<t.currentState.buttons.length;s++){const i=t.currentState.buttons[s],r=t.prevState.buttons[s];i.pressed?s===cs.LeftTrigger?e.get("GamepadAnalog")([n,5,i.value]):s===cs.RightTrigger?e.get("GamepadAnalog")([n,6,i.value]):e.get("GamepadButtonPressed")([n,s,r.pressed?1:0]):!i.pressed&&r.pressed&&(s===cs.LeftTrigger?e.get("GamepadAnalog")([n,5,0]):s===cs.RightTrigger?e.get("GamepadAnalog")([n,6,0]):e.get("GamepadButtonReleased")([n,s,0]))}for(let t=0;t<s.axes.length;t+=2){const i=parseFloat(s.axes[t].toFixed(4)),r=-parseFloat(s.axes[t+1].toFixed(4));e.get("GamepadAnalog")([n,t+1,i]),e.get("GamepadAnalog")([n,t+2,r])}const i=this.controllers.indexOf(t);this.controllers[i].prevState=ls(s)}this.controllers.length>0&&this.requestAnimationFrame(()=>this.updateStatus())}onBeforeUnload(e){for(const e of this.controllers)e&&void 0!==e.id&&this.streamMessageController.toStreamerHandlers.get("GamepadDisconnected")([e.id])}}class gs{constructor(e,t,n){this.activeKeys=new ps,this.toStreamerMessagesProvider=e,this.videoElementProvider=t,this.coordinateConverter=n}registerKeyBoard(e){G.Info("Register Keyboard Events");const t=new es(this.toStreamerMessagesProvider,e,this.activeKeys);return t.register(),t}registerMouse(e,t){let n;return G.Info("Register Mouse Events"),n=e==Ye.HoveringMouse?new rs(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys,t):new is(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys,t),n.register(),n}registerTouch(e){let t;return G.Info("Registering Touch"),t=e?new as(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter):new os(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter),t.register(),t}registerGamePad(){G.Info("Register Game Pad");const e=new us(this.toStreamerMessagesProvider);return e.register(),e}}class ps{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class ms{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=()=>{G.Warning("Resolution changed, restyling player, did you forget to override this function?")},this.onMatchViewportResolutionCallback=()=>{G.Warning("Resolution changed and match viewport resolution is turned on, did you forget to override this function?")},this.videoElement.onclick=()=>{void 0!==this.audioElement&&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(He.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(He.AutoPlayVideo),this.videoElement.play()}isPaused(){return this.videoElement.paused}isVideoReady(){return void 0!==this.videoElement.readyState&&this.videoElement.readyState>0}hasVideoSource(){return void 0!==this.videoElement.srcObject&&null!==this.videoElement.srcObject}getVideoElement(){return this.videoElement}getVideoParentElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0}setVideoEnabled(e){this.videoElement.srcObject.getTracks().forEach(t=>t.enabled=e)}onVideoInitialized(){}onOrientationChange(){clearTimeout(this.orientationChangeTimeout),this.orientationChangeTimeout=window.setTimeout(()=>{this.resizePlayerStyle()},500)}resizePlayerStyle(){const e=this.getVideoParentElement();e&&(this.updateVideoStreamSize(),e.classList.contains("fixed-size")||this.resizePlayerStyleToFillParentElement(),this.onResizePlayerCallback())}resizePlayerStyleToFillParentElement(){this.getVideoParentElement().setAttribute("style","top: 0px; left: 0px; width: 100%; height: 100%; cursor: default;")}updateVideoStreamSize(){if(this.config.isFlagEnabled(He.MatchViewportResolution))if((new Date).getTime()-this.lastTimeResized>300){const e=this.getVideoParentElement();if(!e)return;const t=this.config.hasNumericSetting(qe.ViewportResScale)?this.config.getNumericSettingValue(qe.ViewportResScale):1,n=Math.round(e.clientWidth*t),s=Math.round(e.clientHeight*t);(n>ms.maxEncoderDimension||s>ms.maxEncoderDimension)&&G.Warning(`Requested stream resolution (${n}x${s}) exceeds the common H.264 encoder limit of ${ms.maxEncoderDimension}x${ms.maxEncoderDimension}; encoding may fail. Lower ViewportResScale or disable MatchViewportResolution.`),this.onMatchViewportResolutionCallback(n,s),this.lastTimeResized=(new Date).getTime()}else G.Info("Resizing too often - skipping"),clearTimeout(this.resizeTimeoutHandle),this.resizeTimeoutHandle=window.setTimeout(()=>this.updateVideoStreamSize(),100)}}ms.maxEncoderDimension=4096;class fs{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 ds.ToStreamer:this.toStreamerHandlers.set(t,n);break;case ds.FromStreamer:this.fromStreamerHandlers.set(t,n);break;default:G.Info(`Unknown message direction ${e}`)}}}!function(e){e[e.ToStreamer=0]="ToStreamer",e[e.FromStreamer=1]="FromStreamer"}(ds||(ds={}));class ys{constructor(){this.responseEventListeners=new Map}addResponseEventListener(e,t){this.responseEventListeners.set(e,t)}removeResponseEventListener(e){this.responseEventListeners.delete(e)}onResponse(e){G.Info("DataChannelReceiveMessageType.Response");const t=new TextDecoder("utf-16").decode(e.slice(1));G.Info(t),this.responseEventListeners.forEach(e=>{e(t)})}}class vs{constructor(e,t){this.dataChannelSender=e,this.toStreamerMessagesMapProvider=t}sendMessageToStreamer(e,t){void 0===t&&(t=[]);const n=this.toStreamerMessagesMapProvider.toStreamerMessages.get(e);if(void 0===n)return void G.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`);if(n.structure&&t&&n.structure.length!==t.length)return void G.Error(`Provided message data doesn't match expected layout. Expected [ ${n.structure.map(e=>{switch(e){case"uint8":case"uint16":case"int16":case"float":case"double":default:return"number";case"string":return"string"}}).toString()} ] but received [ ${t.map(e=>typeof e).toString()} ]`);let s=0;t.forEach((e,t)=>{switch(n.structure[t]){case"uint8":s+=1;break;case"uint16":case"int16":s+=2;break;case"float":s+=4;break;case"double":s+=8;break;case"string":s+=2,s+=2*e.length}});const i=new DataView(new ArrayBuffer(s+1));i.setUint8(0,n.id);let r=1;t.forEach((e,t)=>{switch(n.structure[t]){case"uint8":i.setUint8(r,e),r+=1;break;case"uint16":i.setUint16(r,e,!0),r+=2;break;case"int16":i.setInt16(r,e,!0),r+=2;break;case"float":i.setFloat32(r,e,!0),r+=4;break;case"double":i.setFloat64(r,e,!0),r+=8;break;case"string":i.setUint16(r,e.length,!0),r+=2;for(let t=0;t<e.length;t++)i.setUint16(r,e.charCodeAt(t),!0),r+=2}}),this.dataChannelSender.canSend()?this.dataChannelSender.sendData(i.buffer):G.Info(`Data channel cannot send yet, skipping sending message: ${e} - ${new Uint8Array(i.buffer)}`)}}class Ss{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")}}class bs{constructor(e){this.dataChannelProvider=e}canSend(){return void 0!==this.dataChannelProvider.getDataChannelInstance().dataChannel&&"open"===this.dataChannelProvider.getDataChannelInstance().dataChannel.readyState}sendData(e){const t=this.dataChannelProvider.getDataChannelInstance();"open"===t.dataChannel.readyState?(t.dataChannel.send(e),G.Info(`Message Sent: ${new Uint8Array(e)}`),this.resetAfkWarningTimerOnDataSend()):G.Error(`Message Failed: ${new Uint8Array(e)}`)}resetAfkWarningTimerOnDataSend(){}}class ws{reconfigure(e,t){const n=e.height/e.width,s=t.height/t.width;this.playerIsLarger=n>s,this.playerSize=e,this.ratio=this.playerIsLarger?n/s:s/n}translateUnsigned(e,t){const n=this.playerIsLarger?e/this.playerSize.width:this.ratio*(e/this.playerSize.width-.5)+.5,s=this.playerIsLarger?this.ratio*(t/this.playerSize.height-.5)+.5:t/this.playerSize.height;return n<0||n>1||s<0||s>1?{inRange:!1,x:65535,y:65535}:{inRange:!0,x:65536*n,y:65536*s}}translateSigned(e,t){return{x:32767*(this.playerIsLarger?e/(.5*this.playerSize.width):this.ratio*e/(.5*this.playerSize.width)),y:32767*(this.playerIsLarger?this.ratio*t/(.5*this.playerSize.height):t/(.5*this.playerSize.height))}}untranslateUnsigned(e,t){const n=this.playerIsLarger?e/65536:(e/65536-.5)/this.ratio+.5,s=this.playerIsLarger?(t/65536-.5)/this.ratio+.5:t/65536;return{x:n*this.playerSize.width,y:s*this.playerSize.height}}}class Cs{constructor(e){this._urlParams={};const t=new URLSearchParams(e);for(const[e,n]of t)this._urlParams[e.toLowerCase()]=n}has(e){return e.toLowerCase()in this._urlParams}get(e){return this.has(e)?this._urlParams[e.toLowerCase()]:null}}class Ms{constructor(e,t){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=e,this.pixelStreaming=t,this.responseController=new ys,this.file=new Jn,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new Rn(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity.",!1)},this.freezeFrameController=new En(this.pixelStreaming.videoElementParent),this.videoPlayer=new ms(this.pixelStreaming.videoElementParent,this.config),this.videoPlayer.onVideoInitialized=()=>this.handleVideoInitialized(),this.videoPlayer.onMatchViewportResolutionCallback=(e,t)=>{const n={"Resolution.Width":e,"Resolution.Height":t};this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(n)])},this.videoPlayer.onResizePlayerCallback=()=>{this.setUpMouseAndFreezeFrame()},this.streamController=new Mn(this.videoPlayer),this.coordinateConverter=new ws,this.sendrecvDataChannelController=new kn,this.recvDataChannelController=new kn,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new bs(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new fs,this.transport=new st(e.webSocketProtocols),this.protocol=new it(this.transport),this.protocol.addListener(sn.typeName,e=>this.handleOnConfigMessage(e)),this.protocol.addListener(pn.typeName,e=>this.handlePingMessage(e)),this.protocol.addListener(an.typeName,e=>this.handleStreamerListMessage(e)),this.protocol.addListener(cn.typeName,e=>this.handleSubscribeFailedMessage(e)),this.protocol.addListener(rn.typeName,e=>this.handleStreamerIDChangedMessage(e)),this.protocol.addListener(bn.typeName,e=>{const t=e;this.pixelStreaming._onPlayerCount(t.count)}),this.protocol.addListener(hn.typeName,e=>this.handleWebRtcAnswer(e)),this.protocol.addListener(dn.typeName,e=>this.handleWebRtcOffer(e)),this.protocol.addListener(vn.typeName,e=>this.handleWebRtcSFUPeerDatachannels(e)),this.protocol.addListener(gn.typeName,e=>{const t=e;this.handleIceCandidate(t.candidate)}),this.protocol.transport.addListener("open",()=>{if(!this.config.isFlagEnabled(He.BrowserSendOffer)){const e=wn(on);this.protocol.sendMessage(e)}this.reconnectAttempt=0,this.isReconnecting=!1}),this.protocol.transport.addListener("error",()=>{G.Error("Got a transport error.")}),this.protocol.transport.addListener("close",e=>{const t=this.config.getNumericSettingValue(qe.MaxReconnectAttempts),n=this.reconnectAttempt<t,s=(this.forceReconnect||this.enableAutoReconnect&&t>0&&n)&&1001!=e.code,i=!s,r=this.disconnectMessage?this.disconnectMessage:e.reason;this.forceReconnect=!1,this.config.getSettingOption(Ge.PreferredCodec).options=$e.getSupportedVideoCodecs(),this.pixelStreaming._onDisconnect(r,i),this.afkController.stopAfkWarningTimer(),this.statsTimerHandle&&window.clearInterval(this.statsTimerHandle),this.setVideoEncoderAvgQP(0),this.setTouchInputEnabled(!1),this.setMouseInputEnabled(!1),this.setKeyboardInputEnabled(!1),this.setGamePadInputEnabled(!1),s&&setTimeout(()=>{this.reconnectAttempt++,this.doReconnect(e.reason)},2e3)}),this.sendMessageController=new vs(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new Ss(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new gs(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(Ge.StreamerId,e=>{if(void 0===e||""===e)return;this.peerConnectionController.peerConnection.close(),this.peerConnectionController.createPeerConnection(this.peerConfig,this.preferredCodec),this.subscribedStream=e;const t=wn(ln,{streamerId:e});this.protocol.sendMessage(t)}),this.config._addOnOptionSettingChangedListener(Ge.PreferredQuality,e=>{if(void 0===e||""===e)return;let t;if(this.isUsingSVC)t=wn(fn,{spatialLayer:+e[1]-1,temporalLayer:+e[3]-1});else{const n=this.config.getSettingOption(Ge.PreferredQuality).options.indexOf(e);t=wn(fn,{spatialLayer:n,temporalLayer:0})}this.protocol.sendMessage(t)}),this.setVideoEncoderAvgQP(-1),this.signallingUrlBuilder=()=>this.config.getTextSettingValue(Qe.SignallingServerUrl)}destroyVideoPlayer(){this.videoPlayer.destroy()}handleOnMessage(e){const t=new Uint8Array(e.data);G.Info("Message incoming:"+t);const n=this.streamMessageController.fromStreamerMessages.get(t[0]);this.streamMessageController.fromStreamerHandlers.get(n)(e.data)}registerMessageHandlers(){this.streamMessageController.registerMessageHandler(ds.FromStreamer,"QualityControlOwnership",e=>this.onQualityControlOwnership(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"Response",e=>this.responseController.onResponse(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"Command",e=>{this.onCommand(e)}),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"FreezeFrame",e=>this.onFreezeFrameMessage(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"UnfreezeFrame",()=>this.invalidateFreezeFrameAndEnableVideo()),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"VideoEncoderAvgQP",e=>this.handleVideoEncoderAvgQP(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"LatencyTest",e=>this.handleLatencyTestResult(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"DataChannelLatencyTest",e=>this.handleDataChannelLatencyTestResponse(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"InitialSettings",e=>this.handleInitialSettings(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"FileExtension",e=>this.onFileExtension(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"FileMimeType",e=>this.onFileMimeType(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"FileContents",e=>this.onFileContents(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"TestEcho",()=>{}),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"InputControlOwnership",e=>this.onInputControlOwnership(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"GamepadResponse",e=>this.onGamepadResponse(e)),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"Multiplexed",()=>{}),this.streamMessageController.registerMessageHandler(ds.FromStreamer,"Protocol",e=>this.onProtocolMessage(e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"IFrameRequest",()=>this.sendMessageController.sendMessageToStreamer("IFrameRequest")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"RequestQualityControl",()=>this.sendMessageController.sendMessageToStreamer("RequestQualityControl")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"FpsRequest",()=>this.sendMessageController.sendMessageToStreamer("FpsRequest")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"AverageBitrateRequest",()=>this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"StartStreaming",()=>this.sendMessageController.sendMessageToStreamer("StartStreaming")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"StopStreaming",()=>this.sendMessageController.sendMessageToStreamer("StopStreaming")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"LatencyTest",e=>this.sendMessageController.sendMessageToStreamer("LatencyTest",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"RequestInitialSettings",()=>this.sendMessageController.sendMessageToStreamer("RequestInitialSettings")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"TestEcho",()=>{}),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"UIInteraction",e=>this.sendMessageController.sendMessageToStreamer("UIInteraction",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"Command",e=>this.sendMessageController.sendMessageToStreamer("Command",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"TextboxEntry",e=>this.sendMessageController.sendMessageToStreamer("TextboxEntry",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"KeyDown",e=>this.sendMessageController.sendMessageToStreamer("KeyDown",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"KeyUp",e=>this.sendMessageController.sendMessageToStreamer("KeyUp",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"KeyPress",e=>this.sendMessageController.sendMessageToStreamer("KeyPress",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"MouseEnter",e=>this.sendMessageController.sendMessageToStreamer("MouseEnter",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"MouseLeave",e=>this.sendMessageController.sendMessageToStreamer("MouseLeave",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"MouseDown",e=>this.sendMessageController.sendMessageToStreamer("MouseDown",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"MouseUp",e=>this.sendMessageController.sendMessageToStreamer("MouseUp",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"MouseMove",e=>this.sendMessageController.sendMessageToStreamer("MouseMove",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"MouseWheel",e=>this.sendMessageController.sendMessageToStreamer("MouseWheel",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"MouseDouble",e=>this.sendMessageController.sendMessageToStreamer("MouseDouble",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"TouchStart",e=>this.sendMessageController.sendMessageToStreamer("TouchStart",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"TouchEnd",e=>this.sendMessageController.sendMessageToStreamer("TouchEnd",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"TouchMove",e=>this.sendMessageController.sendMessageToStreamer("TouchMove",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"GamepadConnected",()=>this.sendMessageController.sendMessageToStreamer("GamepadConnected")),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"GamepadButtonPressed",e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonPressed",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"GamepadButtonReleased",e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonReleased",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"GamepadAnalog",e=>this.sendMessageController.sendMessageToStreamer("GamepadAnalog",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"GamepadDisconnected",e=>this.sendMessageController.sendMessageToStreamer("GamepadDisconnected",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XREyeViews",e=>this.sendMessageController.sendMessageToStreamer("XREyeViews",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRHMDTransform",e=>this.sendMessageController.sendMessageToStreamer("XRHMDTransform",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRControllerTransform",e=>this.sendMessageController.sendMessageToStreamer("XRControllerTransform",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRSystem",e=>this.sendMessageController.sendMessageToStreamer("XRSystem",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRButtonTouched",e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouched",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRButtonTouchReleased",e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouchReleased",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRButtonPressed",e=>this.sendMessageController.sendMessageToStreamer("XRButtonPressed",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRButtonReleased",e=>this.sendMessageController.sendMessageToStreamer("XRButtonReleased",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"XRAnalog",e=>this.sendMessageController.sendMessageToStreamer("XRAnalog",e)),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"ChannelRelayStatus",()=>{}),this.streamMessageController.registerMessageHandler(ds.ToStreamer,"Multiplexed",()=>{})}onCommand(e){G.Info("DataChannelReceiveMessageType.Command");const t=new TextDecoder("utf-16").decode(e.slice(1));G.Info("Data Channel Command: "+t);const n=JSON.parse(t);"onScreenKeyboard"===n.command&&this.handleOnScreenKeyboardCommand(n)}handleOnScreenKeyboardCommand(e){var t,n,s,i;const r={showOnScreenKeyboard:null===(t=e.showOnScreenKeyboard)||void 0===t||t,x:null!==(n=e.x)&&void 0!==n?n:0,y:null!==(s=e.y)&&void 0!==s?s:0,contents:null!==(i=e.contents)&&void 0!==i?i:""};this.pixelStreaming.dispatchEvent(new Ae(r))}onProtocolMessage(e){try{const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);Object.prototype.hasOwnProperty.call(n,"Direction")||G.Error("Malformed protocol received. Ensure the protocol message contains a direction");const s=n.Direction;delete n.Direction,G.Info(`Received new ${s==ds.FromStreamer?"FromStreamer":"ToStreamer"} protocol. Updating existing protocol...`),Object.keys(n).forEach(e=>{const t=n[e];switch(s){case ds.ToStreamer:if(!Object.prototype.hasOwnProperty.call(t,"id"))return void G.Error(`ToStreamer->${e} protocol definition was malformed as it didn't contain at least an id\n\n Definition was: ${JSON.stringify(t,null,2)}`);if("UIInteraction"===e||"Command"===e||"LatencyTest"===e)return;this.streamMessageController.toStreamerHandlers.get(e)?this.streamMessageController.toStreamerMessages.set(e,t):G.Error(`There was no registered handler for "${e}" - try adding one using registerMessageHandler(MessageDirection.ToStreamer, "${e}", myHandler)`);break;case ds.FromStreamer:if(!Object.prototype.hasOwnProperty.call(t,"id"))return void G.Error(`FromStreamer->${e} protocol definition was malformed as it didn't contain at least an id\n\n Definition was: ${JSON.stringify(t,null,2)}`);this.streamMessageController.fromStreamerHandlers.get(e)?this.streamMessageController.fromStreamerMessages.set(t.id,e):G.Error(`There was no registered handler for "${t}" - try adding one using registerMessageHandler(MessageDirection.FromStreamer, "${e}", myHandler)`);break;default:G.Error(`Unknown direction: ${s}`)}}),this.toStreamerMessagesController.SendRequestInitialSettings(),this.toStreamerMessagesController.SendRequestQualityControl()}catch(e){G.Info(e)}}onInputControlOwnership(e){const t=new Uint8Array(e);G.Info("DataChannelReceiveMessageType.InputControlOwnership");const n=new Boolean(t[1]).valueOf();G.Info(`Received input controller message - will your input control the stream: ${n}`),this.pixelStreaming._onInputControlOwnership(n)}onGamepadResponse(e){const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);this.gamePadController.onGamepadResponseReceived(n.controllerId)}onAfkTriggered(){this.afkController.onAfkClick(),this.videoPlayer.isPaused()&&this.videoPlayer.hasVideoSource()&&this.playStream()}setAfkEnabled(e){e?this.onAfkTriggered():this.afkController.stopAfkWarningTimer()}tryReconnect(e){this.forceReconnect=!0,this.doReconnect(e)}doReconnect(e){this.protocol?(this.isReconnecting=!0,this.protocol.isConnected()?(this.forceReconnect||(this.disconnectMessage=`${e} Reconnecting.`),this.closeSignalingServer(e,!0)):(this.pixelStreaming._onWebRtcAutoConnect(),this.connectToSignallingServer())):G.Info("This player has no protocol connection.")}loadFreezeFrameOrShowPlayOverlay(){this.pixelStreaming.dispatchEvent(new Ee({shouldShowPlayOverlay:this.shouldShowPlayOverlay,isValid:this.freezeFrameController.valid,jpegData:this.freezeFrameController.jpeg})),!0===this.shouldShowPlayOverlay?(G.Info("showing play overlay"),this.resizePlayerStyle()):(G.Info("showing freeze frame"),this.freezeFrameController.showFreezeFrame()),setTimeout(()=>{this.videoPlayer.setVideoEnabled(!1)},this.freezeFrameController.freezeFrameDelay)}onFreezeFrameMessage(e){G.Info("DataChannelReceiveMessageType.FreezeFrame");const t=new Uint8Array(e);this.freezeFrameController.processFreezeFrameMessage(t,()=>this.loadFreezeFrameOrShowPlayOverlay())}invalidateFreezeFrameAndEnableVideo(){G.Info("DataChannelReceiveMessageType.FreezeFrame"),setTimeout(()=>{this.pixelStreaming.dispatchEvent(new Re),this.freezeFrameController.hideFreezeFrame()},this.freezeFrameController.freezeFrameDelay),this.videoPlayer.getVideoElement()&&this.videoPlayer.setVideoEnabled(!0)}onFileExtension(e){const t=new Uint8Array(e);Xn.setExtensionFromBytes(t,this.file)}onFileMimeType(e){const t=new Uint8Array(e);Xn.setMimeTypeFromBytes(t,this.file)}onFileContents(e){const t=new Uint8Array(e);Xn.setContentsFromBytes(t,this.file)}playStream(){if(!this.videoPlayer.getVideoElement()){const e="Could not play video stream because the video player was not initialized correctly.";return this.pixelStreaming.dispatchEvent(new Ce({message:e})),G.Error(e),void this.closeSignalingServer("Stream not initialized correctly",!1)}if(this.videoPlayer.hasVideoSource()){if(this.setTouchInputEnabled(this.config.isFlagEnabled(He.TouchInput)),this.pixelStreaming.dispatchEvent(new Me),this.streamController.audioElement.srcObject){const e=this.config.isFlagEnabled(He.StartVideoMuted);this.streamController.audioElement.muted=e,e?this.playVideo():this.streamController.audioElement.play().then(()=>{this.playVideo()}).catch(e=>{G.Info(e),G.Info("Browser does not support autoplaying video without interaction - to resolve this we are going to show the play button overlay."),this.pixelStreaming.dispatchEvent(new Te({reason:e}))})}else this.playVideo();this.shouldShowPlayOverlay=!1,this.freezeFrameController.showFreezeFrame()}else G.Warning("Cannot play stream, the video element has no srcObject to play.")}playVideo(){this.videoPlayer.play().catch(e=>{this.streamController.audioElement.srcObject&&this.streamController.audioElement.pause(),G.Info(e),G.Info("Browser does not support autoplaying video without interaction - to resolve this we are going to show the play button overlay."),this.pixelStreaming.dispatchEvent(new Te({reason:e}))})}autoPlayVideoOrSetUpPlayOverlay(){this.config.isFlagEnabled(He.AutoPlayVideo)&&this.playStream(),this.resizePlayerStyle()}connectToSignallingServer(){this.locallyClosed=!1,this.enableAutoReconnect=!0,this.disconnectMessage=null;const e=this.signallingUrlBuilder();this.protocol.connect(e);const t=this.config.getNumericSettingValue(qe.KeepaliveDelay);t>0&&(this.keepalive=new Cn(this.protocol,t),this.keepalive.onTimeout=()=>{G.Error("Protocol timeout"),this.protocol.disconnect()})}startSession(e){if(this.peerConfig=e,this.config.isFlagEnabled(He.ForceTURN)&&!this.checkTurnServerAvailability(e))return G.Info("No turn server was found in the Peer Connection Options. TURN cannot be forced, closing connection. Please use STUN instead"),void this.closeSignalingServer("TURN cannot be forced, closing connection. Please use STUN instead.",!1);this.peerConnectionController=new jn(this.peerConfig,this.config,this.preferredCodec),this.peerConnectionController.onVideoStats=e=>{this.handleVideoStats(e)},this.peerConnectionController.onLatencyCalculated=e=>{this.pixelStreaming._onLatencyCalculated(e)},this.peerConnectionController.onSendWebRTCOffer=e=>{this.handleSendWebRTCOffer(e)},this.peerConnectionController.onSetLocalDescription=e=>{"offer"===e.type?this.handleSendWebRTCOffer(e):"answer"===e.type?this.handleSendWebRTCAnswer(e):G.Error(`PeerConnectionController onSetLocalDescription was called with unexpected type ${e.type}`)},this.peerConnectionController.onSetRemoteDescription=e=>{"offer"===e.type?this.pixelStreaming._onWebRtcSdpOffer(e):"answer"===e.type?this.pixelStreaming._onWebRtcSdpAnswer(e):G.Error(`PeerConnectionController onSetRemoteDescription was called with unexpected type ${e.type}`)},this.peerConnectionController.onPeerIceCandidate=e=>this.handleSendIceCandidate(e),this.peerConnectionController.onDataChannel=e=>this.handleDataChannel(e),this.peerConnectionController.showTextOverlayConnecting=()=>this.pixelStreaming._onWebRtcConnecting(),this.peerConnectionController.showTextOverlaySetupFailure=()=>this.pixelStreaming._onWebRtcFailed();let t=!1;this.peerConnectionController.onIceConnectionStateChange=()=>{!t&&["connected","completed"].includes(this.peerConnectionController.peerConnection.iceConnectionState)&&(this.pixelStreaming._onWebRtcConnected(),t=!0)},this.peerConnectionController.onTrack=e=>this.streamController.handleOnTrack(e),this.config.isFlagEnabled(He.BrowserSendOffer)&&(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"cirrus",this.datachannelOptions),this.sendrecvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e),this.peerConnectionController.createOffer(this.sdpConstraints,this.config))}checkTurnServerAvailability(e){if(!e.iceServers)return G.Info("A turn sever was not found"),!1;for(const t of e.iceServers)for(const e of t.urls)if(e.includes("turn"))return G.Info(`A turn sever was found at ${e}`),!0;return G.Info("A turn sever was not found"),!1}handleOnConfigMessage(e){this.resizePlayerStyle(),this.startSession(e.peerConnectionOptions)}handlePingMessage(e){this.protocol.sendMessage(wn(mn,{time:e.time}))}handleStreamerListMessage(e){G.Info(`Got streamer list ${e.ids}`);let t="";const n=this.config.getSettingOption(Ge.StreamerId);n.selected.toString().trim()&&(t=n.selected);const s=[...e.ids];s.unshift(""),this.config.setOptionSettingOptions(Ge.StreamerId,s);let i="";const r=this.config.isFlagEnabled(He.WaitForStreamer),o=this.config.getNumericSettingValue(qe.MaxReconnectAttempts),a=this.config.getNumericSettingValue(qe.StreamerAutoJoinInterval),l=this.config.useUrlParams,c=new Cs(window.location.search);l&&c.has(Ge.StreamerId)?t=c.get(Ge.StreamerId):this.subscribedStream&&(t=this.subscribedStream),t&&e.ids.includes(t)?i=t:t&&r||1!=e.ids.length||(i=e.ids[0]),i?(this.reconnectAttempt=0,this.isReconnecting=!1,this.config.setOptionSettingValue(Ge.StreamerId,i)):r&&(this.reconnectAttempt<o?(this.reconnectAttempt++,this.isReconnecting=!0,setTimeout(()=>{this.protocol.sendMessage(wn(on))},a)):(this.reconnectAttempt=0,this.isReconnecting=!1,this.enableAutoReconnect=!1)),this.pixelStreaming.dispatchEvent(new Pe({messageStreamerList:e,autoSelectedStreamerId:i,wantedStreamerId:t}))}handleSubscribeFailedMessage(e){this.reconnectAttempt=0,this.isReconnecting=!1,this.enableAutoReconnect=!1,this.pixelStreaming._onSubscribeFailed(e.message)}handleStreamerIDChangedMessage(e){const t=e.newID,n=this.config.getSettingOption(Ge.StreamerId),s=n.onChange;n.onChange=()=>{};const i=n.options;for(let e=0;e<i.length;++e)if(i[e]==this.subscribedStream){i[e]=t;break}n.options=i,n.selected=t,n.onChange=s,this.subscribedStream=e.newID,this.pixelStreaming.dispatchEvent(new Ie({newID:t}))}handleWebRtcAnswer(e){G.Info(`Got answer sdp ${e.sdp}`);const t={sdp:e.sdp,type:"answer"};this.peerConnectionController.receiveAnswer(t),this.handlePostWebrtcNegotiation()}handleWebRtcOffer(e){G.Info(`Got offer sdp ${e.sdp}`),this.isUsingSFU=!!e.sfu&&e.sfu,this.isUsingSVC=!!e.scalabilityMode&&"L1T1"!=e.scalabilityMode,(this.isUsingSFU||this.isUsingSVC)&&(this.peerConnectionController.preferredCodec="");const t=e.scalabilityMode?e.scalabilityMode:"L1T1";let n=["Default"];if(this.isUsingSFU)if(this.isUsingSVC){n=[];const e=+t[1],s=+t[3];for(let t=1;t<=e;t++)for(let e=1;e<=s;e++)n.push(`S${t}T${e}`)}else n=["Low","Medium","High"];this.config.setOptionSettingOptions(Ge.PreferredQuality,n),this.config.setOptionSettingValue(Ge.PreferredQuality,n.slice(-1)[0]);const s={sdp:e.sdp,type:"offer"};this.peerConnectionController.receiveOffer(s,this.config),this.handlePostWebrtcNegotiation()}handleWebRtcSFUPeerDatachannels(e){const t={ordered:!0,negotiated:!0,id:e.sendStreamId},n=e.sendStreamId!=e.recvStreamId;if(this.sendrecvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,n?"send-datachannel":"datachannel",t),n){const t={ordered:!0,negotiated:!0,id:e.recvStreamId};this.recvDataChannelController.createDataChannel(this.peerConnectionController.peerConnection,"recv-datachannel",t),this.recvDataChannelController.handleOnOpen=()=>this.protocol.sendMessage(wn(Sn)),this.recvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e)}else this.sendrecvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e)}handlePostWebrtcNegotiation(){this.afkController.startAfkWarningTimer(),this.pixelStreaming._onWebRtcSdp(),this.statsTimerHandle&&void 0!==this.statsTimerHandle&&window.clearInterval(this.statsTimerHandle),this.statsTimerHandle=window.setInterval(()=>this.getStats(),1e3),this.setMouseInputEnabled(this.config.isFlagEnabled(He.MouseInput)),this.setKeyboardInputEnabled(this.config.isFlagEnabled(He.KeyboardInput)),this.setGamePadInputEnabled(this.config.isFlagEnabled(He.GamepadInput))}handleIceCandidate(e){G.Info(`Remote ICE candidate information received: ${JSON.stringify(e)}`);const t=new RTCIceCandidate({candidate:e.candidate,sdpMLineIndex:0});this.peerConnectionController.handleOnIce(t)}handleSendIceCandidate(e){e.candidate&&e.candidate.candidate&&(G.Info("Local ICE candidate generated: "+JSON.stringify(e.candidate)),this.protocol.sendMessage(wn(gn,{candidate:e.candidate})))}handleDataChannel(e){G.Info("Data channel created for us by browser as we are a receiving peer."),this.sendrecvDataChannelController.dataChannel=e.channel,this.sendrecvDataChannelController.setupDataChannel(),this.sendrecvDataChannelController.handleOnMessage=e=>this.handleOnMessage(e)}handleSendWebRTCOffer(e){if("offer"!==e.type)return void G.Error(`handleSendWebRTCOffer was called with type ${e.type} - it only expects "offer"`);G.Info("Sending the offer to the Server");const t={sdp:e.sdp,minBitrateBps:1e3*this.config.getNumericSettingValue(qe.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(qe.WebRTCMaxBitrate)};this.protocol.sendMessage(wn(dn,t)),this.pixelStreaming._onWebRtcSdpOffer(e)}handleSendWebRTCAnswer(e){if("answer"!==e.type)return void G.Error(`handleSendWebRTCAnswer was called with type ${e.type} - it only expects "answer"`);G.Info("Sending the answer to the Server");const t={sdp:e.sdp,minBitrateBps:1e3*this.config.getNumericSettingValue(qe.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(qe.WebRTCMaxBitrate)};this.protocol.sendMessage(wn(hn,t)),this.isUsingSFU&&this.protocol.sendMessage(wn(yn)),this.pixelStreaming._onWebRtcSdpAnswer(e)}setUpMouseAndFreezeFrame(){const e=this.videoPlayer.getVideoParentElement(),t=this.videoPlayer.getVideoElement();this.coordinateConverter.reconfigure({width:e.clientWidth,height:e.clientHeight},{width:t.videoWidth,height:t.videoHeight}),this.freezeFrameController.freezeFrame.resize()}closeSignalingServer(e,t){var n;this.locallyClosed=!0,this.enableAutoReconnect=t,this.disconnectMessage=e,null===(n=this.protocol)||void 0===n||n.disconnect(1e3,e)}closePeerConnection(){var e;null===(e=this.peerConnectionController)||void 0===e||e.close()}close(){this.closeSignalingServer("",!1),this.closePeerConnection()}getStats(){this.peerConnectionController.generateStats()}sendLatencyTest(){this.latencyStartTime=Date.now(),this.streamMessageController.toStreamerHandlers.get("LatencyTest")([JSON.stringify({StartTime:this.latencyStartTime})])}sendDataChannelLatencyTest(e){this.streamMessageController.toStreamerHandlers.get("DataChannelLatencyTest")([JSON.stringify(e)])}sendEncoderMinQP(e){G.Info(`MinQP=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MinQP":e})])}sendEncoderMaxQP(e){G.Info(`MaxQP=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MaxQP":e})])}sendEncoderMinQuality(e){G.Info(`MinQuality=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MinQuality":e})])}sendEncoderMaxQuality(e){G.Info(`MaxQuality=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MaxQuality":e})])}sendWebRTCMinBitrate(e){G.Info(`WebRTC Min Bitrate=${e}`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MinBitrate":e})])}sendWebRTCMaxBitrate(e){G.Info(`WebRTC Max Bitrate=${e}`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxBitrate":e})])}sendWebRTCFps(e){G.Info(`WebRTC FPS=${e}`),null!=e&&(this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.Fps":e})]),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxFps":e})]))}sendShowFps(){G.Info("---- Sending show stat to UE ----"),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"stat.fps":""})])}sendIframeRequest(){G.Info("---- Sending Request for an IFrame ----"),this.streamMessageController.toStreamerHandlers.get("IFrameRequest")()}emitUIInteraction(e){G.Info("---- Sending custom UIInteraction message ----"),this.streamMessageController.toStreamerHandlers.get("UIInteraction")([JSON.stringify(e)])}emitCommand(e){G.Info("---- Sending custom Command message ----"),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(e)])}emitConsoleCommand(e){G.Info("---- Sending custom Command:ConsoleCommand message ----"),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({ConsoleCommand:e})])}sendRequestQualityControlOwnership(){G.Info("---- Sending Request to Control Quality ----"),this.toStreamerMessagesController.SendRequestQualityControl()}sendTextboxEntry(e){var t;G.Info("---- Sending TextboxEntry message ----"),null===(t=this.streamMessageController.toStreamerHandlers.get("TextboxEntry"))||void 0===t||t([e])}handleLatencyTestResult(e){G.Info("DataChannelReceiveMessageType.latencyTest");const t=new TextDecoder("utf-16").decode(e.slice(1)),n=new Gn;Object.assign(n,JSON.parse(t)),n.processFields(),n.testStartTimeMs=this.latencyStartTime,n.browserReceiptTimeMs=Date.now(),n.latencyExcludingDecode=~~(n.browserReceiptTimeMs-n.testStartTimeMs),n.testDuration=~~(n.TransmissionTimeMs-n.ReceiptTimeMs),n.networkLatency=~~(n.latencyExcludingDecode-n.testDuration),n.frameDisplayDeltaTimeMs&&n.browserReceiptTimeMs&&(n.endToEndLatency=(n.frameDisplayDeltaTimeMs,n.networkLatency,~~+n.CaptureToSendMs)),this.pixelStreaming._onLatencyTestResult(n)}handleDataChannelLatencyTestResponse(e){G.Info("DataChannelReceiveMessageType.dataChannelLatencyResponse");const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);this.pixelStreaming._onDataChannelLatencyTestResponse(n)}handleInitialSettings(e){G.Info("DataChannelReceiveMessageType.InitialSettings");const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t),s=new qn;n.Encoder&&(s.EncoderSettings=n.Encoder),n.WebRTC&&(s.WebRTCSettings=n.WebRTC),n.PixelStreaming&&(s.PixelStreamingSettings=n.PixelStreaming),n.ConfigOptions&&void 0!==n.ConfigOptions.DefaultToHover&&this.config.setFlagEnabled(He.HoveringMouseMode,!!n.ConfigOptions.DefaultToHover),s.ueCompatible(),G.Info(t),this.pixelStreaming._onInitialSettings(s)}handleVideoEncoderAvgQP(e){G.Info("DataChannelReceiveMessageType.VideoEncoderAvgQP");const t=Number(new TextDecoder("utf-16").decode(e.slice(1)));this.setVideoEncoderAvgQP(t)}handleVideoInitialized(){this.pixelStreaming._onVideoInitialized(),this.autoPlayVideoOrSetUpPlayOverlay(),this.resizePlayerStyle(),this.videoPlayer.updateVideoStreamSize()}onQualityControlOwnership(e){const t=new Uint8Array(e);G.Info("DataChannelReceiveMessageType.QualityControlOwnership"),this.isQualityController=new Boolean(t[1]).valueOf(),G.Info(`Received quality controller message, will control quality: ${this.isQualityController}`),this.pixelStreaming._onQualityControlOwnership(this.isQualityController)}handleVideoStats(e){this.pixelStreaming._onVideoStats(e)}resizePlayerStyle(){this.videoPlayer.resizePlayerStyle()}setPreferredCodec(e){this.preferredCodec=e,this.peerConnectionController&&(this.peerConnectionController.preferredCodec=e,this.peerConnectionController.updateCodecSelection=!1)}setVideoEncoderAvgQP(e){this.videoAvgQp=e,this.pixelStreaming._onVideoEncoderAvgQP(this.videoAvgQp)}setKeyboardInputEnabled(e){var t;null===(t=this.keyboardController)||void 0===t||t.unregister(),e&&(this.keyboardController=this.inputClassesFactory.registerKeyBoard(this.config))}setMouseInputEnabled(e){var t;if(null===(t=this.mouseController)||void 0===t||t.unregister(),e){const e=this.config.isFlagEnabled(He.HoveringMouseMode)?Ye.HoveringMouse:Ye.LockedMouse;this.mouseController=this.inputClassesFactory.registerMouse(e,this.config)}}setTouchInputEnabled(e){var t;null===(t=this.touchController)||void 0===t||t.unregister(),e&&(this.touchController=this.inputClassesFactory.registerTouch(this.config.isFlagEnabled(He.FakeMouseWithTouches)))}setGamePadInputEnabled(e){var t;null===(t=this.gamePadController)||void 0===t||t.unregister(),e&&(this.gamePadController=this.inputClassesFactory.registerGamePad())}registerDataChannelEventEmitters(e){e.onOpen=(e,t)=>this.pixelStreaming.dispatchEvent(new pe({label:e,event:t})),e.onClose=(e,t)=>this.pixelStreaming.dispatchEvent(new me({label:e,event:t})),e.onError=(e,t)=>this.pixelStreaming.dispatchEvent(new fe({label:e,event:t}))}registerMessageHandler(e,t,n){t===ds.FromStreamer&&void 0===n&&G.Warning(`Unable to register handler for ${e} as no handler was passed`),this.streamMessageController.registerMessageHandler(t,e,s=>void 0===n&&t===ds.ToStreamer?this.sendMessageController.sendMessageToStreamer(e,s):n(s))}}class Ts{constructor(e){this.toStreamerMessagesProvider=e,this.controllers=[]}updateStatus(e,t,n){if(e.gamepad){const s=t.getPose(e.gripSpace,n);if(!s)return;let i=0;e.profiles.includes("htc-vive")?i=1:e.profiles.includes("oculus-touch")&&(i=2),this.toStreamerMessagesProvider.toStreamerHandlers.get("XRSystem")([i]);let r=2;switch(e.handedness){case"left":r=0;break;case"right":r=1}const o=s.transform.matrix,a=[];for(let e=0;e<16;e++)a[e]=new Float32Array([o[e]])[0];this.toStreamerMessagesProvider.toStreamerHandlers.get("XRControllerTransform")([a[0],a[4],a[8],a[12],a[1],a[5],a[9],a[13],a[2],a[6],a[10],a[14],a[3],a[7],a[11],a[15],r]),void 0===this.controllers[r]&&(this.controllers[r]={prevState:void 0,currentState:void 0,id:void 0},this.controllers[r].prevState=ls(e.gamepad)),this.controllers[r].currentState=ls(e.gamepad);const l=this.controllers[r],c=l.currentState,d=l.prevState;for(let e=0;e<c.buttons.length;e++){const t=c.buttons[e],n=d.buttons[e];if(t.pressed){const s=n.pressed?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonPressed")([r,e,s,t.value])}else n.pressed&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonReleased")([r,e,0]);if(t.touched){const t=n.touched?1:0;this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouched")([r,e,t])}else n.touched&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRButtonTouchReleased")([r,e,0])}for(let e=0;e<c.axes.length;e++){const t=c.axes[e];t!=d.axes[e]&&this.toStreamerMessagesProvider.toStreamerHandlers.get("XRAnalog")([r,e,t])}this.controllers[r].prevState=c}}}class Es{constructor(e){this.xrViewerPose=null,this.EPSILON=1e-7,this.videoTexture=null,this.prevVideoWidth=0,this.prevVideoHeight=0,this.leftView=null,this.rightView=null,this.lastSentLeftEyeProj=null,this.lastSentRightEyeProj=null,this.lastSentRelativeLeftEyePos=null,this.lastSentRelativeRightEyePos=null,this.xrSession=null,this.webRtcController=e,this.xrGamepadController=new Ts(this.webRtcController.streamMessageController),this.onSessionEnded=new EventTarget,this.onSessionStarted=new EventTarget,this.onFrame=new EventTarget}xrClicked(){if(this.xrSession)this.xrSession.end();else{if(!navigator.xr)return void G.Error("This browser does not support XR.");navigator.xr.requestSession("immersive-vr",{optionalFeatures:[]}).then(e=>{this.onXrSessionStarted(e)})}}onXrSessionEnded(){G.Info("XR Session ended"),this.xrSession=null,this.onSessionEnded.dispatchEvent(new Event("xrSessionEnded"))}initGL(){if(this.gl)return;const e=document.createElement("canvas");this.gl=e.getContext("webgl2",{xrCompatible:!0}),this.gl.clearColor(0,0,0,1)}initShaders(){const e=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(e,"\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n // varyings\n varying vec2 v_texCoord;\n\n void main() {\n gl_Position = vec4(a_position.x, a_position.y, 0, 1);\n // pass the texCoord to the fragment shader\n // The GPU will interpolate this value between points.\n v_texCoord = a_texCoord;\n }\n "),this.gl.compileShader(e);const t=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(t,"\n precision mediump float;\n\n // our texture\n uniform sampler2D u_image;\n\n // the texCoords passed in from the vertex shader.\n varying vec2 v_texCoord;\n\n void main() {\n gl_FragColor = texture2D(u_image, v_texCoord);\n }\n "),this.gl.compileShader(t);const n=this.gl.createProgram();this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),this.gl.useProgram(n),this.positionLocation=this.gl.getAttribLocation(n,"a_position"),this.texcoordLocation=this.gl.getAttribLocation(n,"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));const 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){G.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(const t of this.xrSession.supportedFrameRates)90==t&&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((e,n)=>Math.abs(e-t[n])<=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(null==this.leftView||null==this.rightView)return;let e=null==this.lastSentLeftEyeProj||null==this.lastSentRightEyeProj||null==this.lastSentRelativeLeftEyePos||null==this.lastSentRelativeRightEyePos;const t=this.leftView.transform.matrix,n=this.leftView.projectionMatrix,s=this.rightView.transform.matrix,i=this.rightView.projectionMatrix,r=this.xrViewerPose.transform.matrix;if(!e&&null!=this.lastSentLeftEyeProj&&null!=this.lastSentRightEyeProj){const t=this.areArraysEqual(n,this.lastSentLeftEyeProj),s=this.areArraysEqual(i,this.lastSentRightEyeProj);e=0==t||0==s}const o=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),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);if(!e&&null!=this.lastSentRelativeLeftEyePos&&null!=this.lastSentRelativeRightEyePos){const t=this.arePointsEqual(o,this.lastSentRelativeLeftEyePos),n=this.arePointsEqual(a,this.lastSentRelativeRightEyePos);e=0==t||0==n}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],s[0],s[4],s[8],s[12],s[1],s[5],s[9],s[13],s[2],s[6],s[10],s[14],s[3],s[7],s[11],s[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]]),this.lastSentLeftEyeProj=n,this.lastSentRightEyeProj=i,this.lastSentRelativeLeftEyePos=o,this.lastSentRelativeRightEyePos=a):this.webRtcController.streamMessageController.toStreamerHandlers.get("XRHMDTransform")([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]])}onXrFrame(e,t){if(this.xrViewerPose=t.getViewerPose(this.xrRefSpace),this.xrViewerPose){if(this.updateViews(),null==this.leftView||null==this.rightView)return;this.sendXRDataToUE(),this.updateVideoTexture(),this.render()}this.webRtcController.config.isFlagEnabled(He.XRControllerInput)&&this.xrSession.inputSources.forEach((e,n,s)=>{this.xrGamepadController.updateStatus(e,t,this.xrRefSpace)},this),this.xrSession.requestAnimationFrame((e,t)=>this.onXrFrame(e,t)),this.onFrame.dispatchEvent(new Be({time:e,frame:t}))}updateViews(){if(this.xrViewerPose)for(const e of this.xrViewerPose.views)"left"===e.eye?this.leftView=e:"right"===e.eye&&(this.rightView=e)}render(){if(!this.gl)return;const 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){"https:"!==location.protocol&&G.Info("WebXR requires https, if you want WebXR use https.");try{if(navigator.xr)return navigator.xr.isSessionSupported(e)}catch(e){return Promise.resolve(!1)}return Promise.resolve(!1)}}class Rs{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}}class ks{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()&&(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(){const e=new Map(this.records);return{records:e,dataChannelRtt:Math.ceil(Array.from(this.records.values()).reduce((e,t)=>e+(t.playerReceivedTimestamp-t.playerSentTimestamp),0)/this.records.size),playerToStreamerTime:Math.ceil(Array.from(this.records.values()).reduce((e,t)=>e+(t.streamerReceivedTimestamp-t.playerSentTimestamp),0)/this.records.size),streamerToPlayerTime:Math.ceil(Array.from(this.records.values()).reduce((e,t)=>e+(t.playerReceivedTimestamp-t.streamerSentTimestamp),0)/this.records.size),exportLatencyAsCSV:()=>{let t="Timestamp;RTT;PlayerToStreamer;StreamerToPlayer;\n";return e.forEach(e=>{t+=e.playerSentTimestamp+";",t+=e.playerReceivedTimestamp-e.playerSentTimestamp+";",t+=e.streamerReceivedTimestamp-e.playerSentTimestamp+";",t+=e.playerReceivedTimestamp-e.streamerSentTimestamp+";",t+="\n"}),t}}}isRunning(){return!!this.intervalHandle}receive(e){if(!this.isRunning())return;if(!e)return void G.Error("Undefined response from server");const t=this.records.get(e.Seq);t&&t.update(e)}sendRequest(e,t){const n=this.createRequest(e,t),s=new Rs(n);this.records.set(s.seq,s),this.sink(n)}createRequest(e,t){return{Seq:this.seq++,FillResponseSize:t,Filler:e?"A".repeat(e):""}}}class Ps{constructor(e,t){this.allowConsoleCommands=!1,this.config=e,(null==t?void 0:t.videoElementParent)&&(this._videoElementParent=t.videoElementParent),this._eventEmitter=new We,this.configureSettings(),this.setWebRtcPlayerController(new Ms(this.config,this)),this._webXrController=new Es(this._webRtcController),this._setupWebRtcTCPRelayDetection=this._setupWebRtcTCPRelayDetection.bind(this),this._eventEmitter.addEventListener("webRtcConnected",e=>{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(He.IsQualityController,e=>{!0!==e||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()}),this.config._addOnSettingChangedListener(He.AFKDetection,e=>{this._webRtcController.setAfkEnabled(e)}),this.config._addOnSettingChangedListener(He.MatchViewportResolution,()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()}),this.config._addOnSettingChangedListener(He.HoveringMouseMode,e=>{this.config.setFlagLabel(He.HoveringMouseMode,`Control Scheme: ${e?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(He.MouseInput))}),this.config._addOnSettingChangedListener(He.KeyboardInput,e=>{this._webRtcController.setKeyboardInputEnabled(e)}),this.config._addOnSettingChangedListener(He.MouseInput,e=>{this._webRtcController.setMouseInputEnabled(e)}),this.config._addOnSettingChangedListener(He.FakeMouseWithTouches,e=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(He.TouchInput))}),this.config._addOnSettingChangedListener(He.TouchInput,e=>{this._webRtcController.setTouchInputEnabled(e)}),this.config._addOnSettingChangedListener(He.GamepadInput,e=>{this._webRtcController.setGamePadInputEnabled(e)}),this.config._addOnNumericSettingChangedListener(qe.MinQP,e=>{G.Info("-------- Sending MinQP --------"),this._webRtcController.sendEncoderMinQP(e),G.Info("-------------------------------------------");const t=Math.trunc(100*(1-e/51));this.config.setNumericSetting(qe.CompatQualityMax,t)}),this.config._addOnNumericSettingChangedListener(qe.MaxQP,e=>{G.Info("-------- Sending MaxQP --------"),this._webRtcController.sendEncoderMaxQP(e),G.Info("-------------------------------------------");const t=Math.trunc(100*(1-e/51));this.config.setNumericSetting(qe.CompatQualityMin,t)}),this.config._addOnNumericSettingChangedListener(qe.MinQuality,e=>{G.Info("-------- Sending MinQuality --------"),this._webRtcController.sendEncoderMinQuality(e),G.Info("-------------------------------------------"),this.config.setNumericSetting(qe.CompatQualityMin,e)}),this.config._addOnNumericSettingChangedListener(qe.MaxQuality,e=>{G.Info("-------- Sending MaxQuality --------"),this._webRtcController.sendEncoderMaxQuality(e),G.Info("-------------------------------------------"),this.config.setNumericSetting(qe.CompatQualityMax,e)}),this.config._addOnNumericSettingChangedListener(qe.CompatQualityMin,e=>{e=51-e/100*51,G.Info("-------- Sending MinQP from quality value --------"),this._webRtcController.sendEncoderMaxQP(e),G.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(qe.CompatQualityMax,e=>{e=51-e/100*51,G.Info("-------- Sending MaxQP from quality value --------"),this._webRtcController.sendEncoderMinQP(e),G.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(qe.WebRTCMinBitrate,e=>{G.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCMinBitrate(1e3*e),G.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(qe.WebRTCMaxBitrate,e=>{G.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCMaxBitrate(1e3*e),G.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(qe.WebRTCFPS,e=>{G.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCFps(e),G.Info("-------------------------------------------")}),this.config._addOnOptionSettingChangedListener(Ge.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(Ge.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Se),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new we),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new be),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(He.AutoConnect)&&(this._onWebRtcAutoConnect(),this._webRtcController.connectToSignallingServer())}unmuteMicrophone(e=!1){if(!this.config.isFlagEnabled("UseMic"))return e?(this.config.setFlagEnabled("UseMic",!0),void this.reconnect()):void G.Warning("Trying to unmute mic, but PixelStreaming was initialized with no microphone track. Call with forceEnable == true to re-connect with a mic track.");this.setMicrophoneMuted(!1)}muteMicrophone(){this.config.isFlagEnabled("UseMic")?this.setMicrophoneMuted(!0):G.Info("Trying to mute mic, but PixelStreaming has no microphone track, so sending sound is already disabled.")}setMicrophoneMuted(e){var t,n,s,i;for(const r of null!==(i=null===(s=null===(n=null===(t=this._webRtcController)||void 0===t?void 0:t.peerConnectionController)||void 0===n?void 0:n.peerConnection)||void 0===s?void 0:s.getTransceivers())&&void 0!==i?i:[])Un.canTransceiverSendAudio(r)&&(r.sender.track.enabled=!e)}unmuteCamera(e=!1){if(!this.config.isFlagEnabled("UseCamera"))return e?(this.config.setFlagEnabled("UseCamera",!0),void this.reconnect()):void G.Warning("Trying to unmute video, but PixelStreaming was initialized with no video track. Call with forceEnable == true to re-connect with a video track.");this.setCameraMuted(!1)}muteCamera(){this.config.isFlagEnabled("UseCamera")?this.setCameraMuted(!0):G.Info("Trying to mute camera, but PixelStreaming has no video track, so sending video is already disabled.")}setCameraMuted(e){var t,n,s,i;for(const r of null!==(i=null===(s=null===(n=null===(t=this._webRtcController)||void 0===t?void 0:t.peerConnectionController)||void 0===n?void 0:n.peerConnection)||void 0===s?void 0:s.getTransceivers())&&void 0!==i?i:[])Un.canTransceiverSendVideo(r)&&(r.sender.track.enabled=!e)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new ce)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new oe)}_onWebRtcSdpOffer(e){this._eventEmitter.dispatchEvent(new le({sdp:e}))}_onWebRtcSdpAnswer(e){this._eventEmitter.dispatchEvent(new ae({sdp:e}))}_onLatencyCalculated(e){this._eventEmitter.dispatchEvent(new Le({latencyInfo:e}))}_onStreamLoading(){this._eventEmitter.dispatchEvent(new ve)}_onDisconnect(e,t){this._eventEmitter.dispatchEvent(new ge({eventString:e,allowClickToReconnect:t}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new de)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new he)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new ue)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new ye),this._videoStartTime=Date.now(),this.checkForAutoEnterVR()}checkForAutoEnterVR(){this.config.isFlagEnabled(He.AutoEnterVR)&&Es.isSessionSupported("immersive-vr").then(e=>{e?this._webXrController.xrClicked():G.Info("AutoEnterVR is on but immersive-vr is not supported on this device.")}).catch(e=>{const t=e instanceof Error?e.message:JSON.stringify(e);G.Warning(`AutoEnterVR check failed: ${t}`)})}_onLatencyTestResult(e){this._eventEmitter.dispatchEvent(new xe({latencyTimings:e}))}_onDataChannelLatencyTestResponse(e){this._eventEmitter.dispatchEvent(new De({response:e}))}_onVideoStats(e){this._videoStartTime&&void 0!==this._videoStartTime||(this._videoStartTime=Date.now()),e.handleSessionStatistics(this._videoStartTime,this._inputController,this._webRtcController.videoAvgQp),this._eventEmitter.dispatchEvent(new ke({aggregatedStats:e}))}_onVideoEncoderAvgQP(e){this._eventEmitter.dispatchEvent(new re({avgQP:e}))}_onInitialSettings(e){var t;this._eventEmitter.dispatchEvent(new Ne({settings:e})),e.PixelStreamingSettings&&(this.allowConsoleCommands=null!==(t=e.PixelStreamingSettings.AllowPixelStreamingCommands)&&void 0!==t&&t,!1===this.allowConsoleCommands&&G.Info("-AllowPixelStreamingCommands=false, sending arbitrary console commands from browser to UE is disabled."));const n=this.config.useUrlParams,s=new Cs(window.location.search);G.Info(`using URL parameters ${n}`),e.EncoderSettings&&(e.EncoderSettings.MinQP&&(this.config.setNumericSetting(qe.MinQP,n&&s.has(qe.MinQP)?Number.parseFloat(s.get(qe.MinQP)):e.EncoderSettings.MinQP||0),this.config.setNumericSetting(qe.MaxQP,n&&s.has(qe.MaxQP)?Number.parseFloat(s.get(qe.MaxQP)):e.EncoderSettings.MaxQP||51)),e.EncoderSettings.MinQuality&&(this.config.setNumericSetting(qe.MinQuality,n&&s.has(qe.MinQuality)?Number.parseFloat(s.get(qe.MinQuality)):e.EncoderSettings.MinQuality||0),this.config.setNumericSetting(qe.MaxQuality,n&&s.has(qe.MaxQuality)?Number.parseFloat(s.get(qe.MaxQuality)):e.EncoderSettings.MaxQuality||100)),n&&(s.has(qe.CompatQualityMin)&&this.config.setNumericSetting(qe.CompatQualityMin,Number.parseFloat(s.get(qe.CompatQualityMin))),s.has(qe.CompatQualityMax)&&this.config.setNumericSetting(qe.CompatQualityMax,Number.parseFloat(s.get(qe.CompatQualityMax))))),e.WebRTCSettings&&(this.config.setNumericSetting(qe.WebRTCMinBitrate,n&&s.has(qe.WebRTCMinBitrate)?Number.parseFloat(s.get(qe.WebRTCMinBitrate)):e.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(qe.WebRTCMaxBitrate,n&&s.has(qe.WebRTCMaxBitrate)?Number.parseFloat(s.get(qe.WebRTCMaxBitrate)):e.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(qe.WebRTCFPS,n&&s.has(qe.WebRTCFPS)?Number.parseFloat(s.get(qe.WebRTCFPS)):e.WebRTCSettings.FPS))}_onQualityControlOwnership(e){this.config.setFlagEnabled(He.IsQualityController,e)}_onPlayerCount(e){this._eventEmitter.dispatchEvent(new Ve({count:e}))}_onSubscribeFailed(e){this._eventEmitter.dispatchEvent(new Fe({message:e}))}_setupWebRtcTCPRelayDetection(e){const t=e.data.aggregatedStats.getActiveCandidatePair();if(null!=t){const n=e.data.aggregatedStats.localCandidates.find(e=>e.id==t.localCandidateId,null);null!=n&&"relay"==n.candidateType&&"tcp"==n.relayProtocol&&this._eventEmitter.dispatchEvent(new _e),this._eventEmitter.removeEventListener("statsReceived",this._setupWebRtcTCPRelayDetection)}}requestLatencyTest(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendLatencyTest(),!0)}requestDataChannelLatencyTest(e){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._dataChannelLatencyTestController||(this._dataChannelLatencyTestController=new ks(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),e=>{this._eventEmitter.dispatchEvent(new Oe({result:e}))}),this.addEventListener("dataChannelLatencyTestResponse",({data:{response:e}})=>{this._dataChannelLatencyTestController.receive(e)})),this._dataChannelLatencyTestController.start(e))}requestShowFps(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendShowFps(),!0)}requestIframe(){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendIframeRequest(),!0)}emitUIInteraction(e){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.emitUIInteraction(e),!0)}emitCommand(e){return!(!this._webRtcController.videoPlayer.isVideoReady()||!this.allowConsoleCommands&&"ConsoleCommand"in e||(this._webRtcController.emitCommand(e),0))}emitConsoleCommand(e){return!(!this.allowConsoleCommands||!this._webRtcController.videoPlayer.isVideoReady()||(this._webRtcController.emitConsoleCommand(e),0))}sendTextboxEntry(e){return!!this._webRtcController.videoPlayer.isVideoReady()&&(this._webRtcController.sendTextboxEntry(e),!0)}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){t!==ds.FromStreamer||void 0!==n?t===ds.ToStreamer&&void 0===n?this._webRtcController.streamMessageController.registerMessageHandler(t,e,t=>this._webRtcController.sendMessageController.sendMessageToStreamer(e,t)):this._webRtcController.streamMessageController.registerMessageHandler(t,e,e=>n(e)):G.Warning(`Unable to register an undefined handler for ${e}`)}get toStreamerHandlers(){return this._webRtcController.streamMessageController.toStreamerHandlers}isReconnecting(){return this._webRtcController.isReconnecting}}!function(e){e[e.VideoInitialised=0]="VideoInitialised",e[e.DataChannelOpen=1]="DataChannelOpen",e[e.DataChannelResponse=2]="DataChannelResponse",e[e.WaitingForRenderer=3]="WaitingForRenderer",e[e.RendererTaken=4]="RendererTaken",e[e.WebRtcStats=5]="WebRtcStats"}(hs||(hs={}));class Is{type=hs.VideoInitialised}class xs{type=hs.DataChannelOpen}class Ls{msg;type=hs.DataChannelResponse;constructor(e){this.msg=e}}class As{stats;type=hs.WebRtcStats;constructor(e){this.stats=e}}var Ds,Os=n(388);!function(e){e.ClientInfo="client_info",e.ClientGone="client_gone",e.CustomerConcurrencyLimitReached="customer_concurrency_limit_reached",e.Config="config",e.Error="error",e.IndexInQueue="index_in_queue",e.RendererTaken="renderer_taken",e.RendererGone="renderer_gone",e.RendererError="renderer_error",e.RendererVersionWarning="renderer_version_warning",e.SwitchRendererRequest="switch_renderer_request"}(Ds||(Ds={}));var Fs=n(838),Ns=n(992);const Us="sessionEndedDueToConnectionLoss",Bs="sessionEndedDueToVideoPlaybackError",Vs="sessionEndedDueToRendererError";var _s,Ws,$s,Hs,js;function qs(e,t,n){return Math.max(t,Math.min(e,n))}function zs(e){const t=e?.srcObject;return!!t&&"function"==typeof t.getAudioTracks&&t.getAudioTracks().length>0}!function(e){e.Good="Good",e.Fair="Fair",e.Poor="Poor"}(_s||(_s={})),function(e){e.Always="always",e.WhenDegraded="when-degraded",e.Hidden="hidden"}(Ws||(Ws={})),function(e){e.TopLeft="top-left",e.TopRight="top-right",e.BottomLeft="bottom-left",e.BottomRight="bottom-right"}($s||($s={})),function(e){e.Click="click",e.Hover="hover",e.None="none"}(Hs||(Hs={}));class Qs{stream;videoElement;audioElement;previousStats;constructor(e,t,n){this.stream=e,this.videoElement=t,this.audioElement=n}getPeerConnection(){return this.stream?.webRtcController?.peerConnectionController?.peerConnection}async analyzeAudioStats(){const e=this.getPeerConnection();if(!e)return void r.A.error("Stream appears to be down, RTCPeerConnection is not defined");const t=await e.getStats(null),n=this.getInboundAudioStats(t);if(!n)return void r.A.warn("WebRTC Connection - No inbound audio RTP stats found.");const s=n.codecId,i=s?this.getCodecFromStats(t,s):void 0;this.logAudioStats(n,i),this.logElementStatus(i)}async collectNetworkQuality(e){const t=this.getPeerConnection();if(!t)return r.A.warn("Cannot collect network quality: RTCPeerConnection is not defined"),null;const n=await t.getStats(null),s=this.extractRawStats(n);if(!this.previousStats)return this.previousStats=s,null;const i=this.computeMetrics(s,this.previousStats,e);return this.previousStats=s,i}resetStats(){this.previousStats=void 0}extractRawStats(e){const 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}};let n,s;if(e.forEach(e=>{"inbound-rtp"===e.type&&"audio"===e.kind?(t.audio.packetsReceived=e.packetsReceived??0,t.audio.packetsLost=e.packetsLost??0,t.audio.bytesReceived=e.bytesReceived??0,t.audio.jitter=e.jitter??0,n=e.codecId):"inbound-rtp"===e.type&&"video"===e.kind?(t.video.packetsReceived=e.packetsReceived??0,t.video.packetsLost=e.packetsLost??0,t.video.bytesReceived=e.bytesReceived??0,t.video.framesDecoded=e.framesDecoded??0,t.video.framesDropped=e.framesDropped??0,t.video.frameWidth=e.frameWidth??0,t.video.frameHeight=e.frameHeight??0,t.video.framesPerSecond=e.framesPerSecond??0,t.video.jitter=e.jitter??0,s=e.codecId):"candidate-pair"===e.type&&e.nominated&&(t.connection.currentRoundTripTime=e.currentRoundTripTime??0)}),n){const s=e.get(n);s&&(t.audio.codecMimeType=s.mimeType)}if(s){const n=e.get(s);n&&(t.video.codecMimeType=n.mimeType)}return t}computeMetrics(e,t,n){const s=(e.timestamp-t.timestamp)/1e3,i=e.audio.packetsReceived-t.audio.packetsReceived,r=e.audio.packetsLost-t.audio.packetsLost,o=i+r,a=o>0?r/o*100:0,l=s>0?8*(e.audio.bytesReceived-t.audio.bytesReceived)/s/1e3:0,c=e.video.packetsReceived-t.video.packetsReceived,d=e.video.packetsLost-t.video.packetsLost,h=c+d,u=h>0?d/h*100:0,g=s>0?8*(e.video.bytesReceived-t.video.bytesReceived)/s/1e3:0,p=1e3*e.connection.currentRoundTripTime,m=function(e){const t=e.packetLoss??0,n=e.fec??!0,s=e.bitrate,i=20+(e.bufferDelay??50)+(e.roundTripTime??50)/2,r=e.dtx??!1?8:s?qs(55-4.6*Math.log(s),0,30):6,o=qs(100-(r+t/(t+(n?20:10))*(100-r))-(.03*i+(i>150?.1*(i-150):0)),0,100),a=1+.035*o+o*(o-60)*(100-o)*7/1e6;return qs(Math.round(100*a)/100,1,5)}({packetLoss:a,bitrate:1e3*l,roundTripTime:p,bufferDelay:1e3*e.audio.jitter}),f=n.expectedFrameRate??30,y=e.video.codecMimeType?.toLowerCase()??"",v=[["vp9","vp9"],["vp8","vp8"],["h264","h264"],["avc","h264"],["h265","h265"],["hevc","h265"],["av1","av1"]].find(([e])=>y.includes(e))?.[1],S=function(e){const t=e.bitrate??0,n=e.roundTripTime??50,s=e.bufferDelay??0,i=e.width||640,r=e.height||480,o=e.frameRate??0,a=e.expectedFrameRate??30,l=e.codec?.toLowerCase();if(0===o)return 1;const c=s+n/2,d=("vp9"===l?1.2:1)*t/(i*r)/o,h=qs(.56*Math.log(d)+5.36,1,5)-1.9*Math.log(a/o)-.002*c;return qs(Math.round(100*h)/100,1,5)}({bitrate:1e3*g,roundTripTime:p,width:e.video.frameWidth,height:e.video.frameHeight,frameRate:e.video.framesPerSecond,expectedFrameRate:f,codec:v}),b=Math.min(m,S);let w;return w=b>=3.5?_s.Good:b>=2.5?_s.Fair:_s.Poor,{audioPacketLossPercent:Math.round(100*a)/100,videoPacketLossPercent:Math.round(100*u)/100,audioBitrateKbps:Math.round(l),videoBitrateKbps:Math.round(g),frameRate:e.video.framesPerSecond,audioJitterMs:Math.round(1e3*e.audio.jitter*100)/100,videoJitterMs:Math.round(1e3*e.video.jitter*100)/100,roundTripTimeMs:Math.round(100*p)/100,audioMos:m,videoMos:S,qualityLevel:w}}getInboundAudioStats(e){let t=null;return e.forEach(e=>{"inbound-rtp"===e.type&&"audio"===e.kind&&(t=e)}),t}getCodecFromStats(e,t){let n;return e.forEach(e=>{"codec"===e.type&&e.id===t&&(n=e)}),n}logAudioStats(e,t){const{packetsReceived:n,packetsLost:s,bytesReceived:i,jitter:o,audioLevel:a}=e;r.A.info(`WebRTC Connection - Audio -\n Codec: ${t?t.mimeType+" ("+t.payloadType+")":"Unknown"},\n Packets received: ${n},\n Packets lost: ${s},\n Bytes received: ${i},\n Jitter: ${o},\n Audio level (0-1): ${a??"N/A"}`),0===n&&r.A.warn("WebRTC Connection - Audio - No audio packets received — remote is probably not sending audio."),s>0&&r.A.warn(`WebRTC Connection - Audio - packet loss detected: ${s} packets lost.`),void 0===a?r.A.warn("WebRTC Connection - Audio - Audio level not available in stats."):0===a?r.A.warn("WebRTC Connection - Audio - Audio level is zero — digital human might not be talking at this exact moment as audio is silent or muted."):a<.02?r.A.warn("WebRTC Connection - Audio - Audio level is very low — audio might be too quiet."):r.A.info("WebRTC Connection - Audio - Audio level looks normal, digital human is likely speaking.")}logElementStatus(e){const t=zs(this.videoElement),n=t?this.videoElement:this.audioElement;r.A.debug(`Audio plays from ${t?"video":"separate audio"} element (DisableAudioSync=${t?"false":"true"}).`),r.A.debug(`Video element muted: ${this.videoElement?.muted}, (should be ${t?"false to be able to hear the digital human":"true as part of avoiding auto play restrictions"})`),r.A.debug(`Playback element muted: ${n?.muted}, (should be false to be able to hear the digital human)`),r.A.debug(`Playback element volume: ${n?.volume}, (should be greater than zero to be able to hear the digital human)`);const s=e?.mimeType;s&&n&&(r.A.debug(`Playback element can play webrtc audio codec (${s}) : ${n.canPlayType(s)}, (should be 'probably' or 'maybe)'`),"audio/opus"===s&&r.A.debug(`Audio codec opus is often known as ogg, so checking can play ogg codec: ${n.canPlayType("audio/ogg")}, (should be 'probably' or 'maybe')`))}}!function(e){e.Google="google",e.Deepgram="deepgram"}(js||(js={}));const Ks=e=>e??"speech-recognition-service",Gs=e=>"pixel-streaming"===e||"both"===e,Xs=e=>"speech-recognition-service"===e||"both"===e,Js="#6b7280";let Ys=0;const Zs={position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:"0"},ei={message:"",qualityHeader:"{level} Quality",good:"Good",fair:"Fair",poor:"Poor",unknown:"unknown",networkQuality:"Network quality",qualityScoreMos:"Quality Score (MOS)",connection:"Connection",throughput:"Throughput",audio:"Audio",video:"Video",roundTrip:"Round Trip",packetLoss:"Packet Loss",jitter:"Jitter",bitrate:"Bitrate",frameRate:"Frame Rate"};class ti{videoContainerElement;container;panel;trigger;liveRegion;announcedLevel;panelId;bars=[];panelVisible=!1;lastMetrics;visibility;position;popupTrigger;strings;onClickBound;onMouseEventBound;onDocumentClickBound;onMouseEnterBound;onMouseLeaveBound;onKeyDownBound;hoverHideTimeout;originalParentPosition;constructor(e,t){this.videoContainerElement=e,this.visibility=t.visibility??Ws.WhenDegraded,this.position=t.position??$s.TopRight,this.popupTrigger=t.popupTrigger??Hs.Click,this.strings={...ei,...t.strings},this.onClickBound=this.onClick.bind(this),this.onMouseEventBound=e=>e.stopPropagation(),this.onDocumentClickBound=this.onDocumentClick.bind(this),this.onMouseEnterBound=this.onMouseEnter.bind(this),this.onMouseLeaveBound=this.onMouseLeave.bind(this),this.onKeyDownBound=this.onKeyDown.bind(this),this.panelId="uneeq-network-indicator-panel-"+ ++Ys,this.visibility!==Ws.Hidden&&this.createElements()}createElements(){"static"===getComputedStyle(this.videoContainerElement).position&&(this.originalParentPosition=this.videoContainerElement.style.position,this.videoContainerElement.style.position="relative"),this.liveRegion=document.createElement("div"),this.liveRegion.setAttribute("data-testid","network-indicator-live-region"),this.liveRegion.setAttribute("role","status"),this.liveRegion.setAttribute("aria-live","polite"),Object.assign(this.liveRegion.style,Zs),this.videoContainerElement.appendChild(this.liveRegion),this.container=document.createElement("div"),this.container.setAttribute("data-testid","network-indicator"),Object.assign(this.container.style,{position:"absolute",zIndex:"1000",display:"none",pointerEvents:"auto",...this.getPositionStyles()});const e=this.popupTrigger!==Hs.None;this.trigger=document.createElement(e?"button":"div"),this.trigger.setAttribute("data-testid","network-indicator-trigger"),Object.assign(this.trigger.style,{display:"flex",alignItems:"flex-end",gap:"2px",padding:"6px 7px",borderRadius:"4px",background:"rgba(0, 0, 0, 0.5)",margin:"0",border:"0",font:"inherit",color:"inherit",cursor:e?"pointer":"default"}),e&&(this.trigger.type="button",this.trigger.setAttribute("aria-expanded","false"),this.trigger.setAttribute("aria-controls",this.panelId)),this.trigger.setAttribute("aria-label",`${this.strings.networkQuality}: ${this.strings.unknown}`);const t=[6,12,18];for(const e of t){const t=document.createElement("div");t.setAttribute("data-testid","network-indicator-bar"),Object.assign(t.style,{width:"4px",height:`${e}px`,borderRadius:"1px",background:Js,transition:"background 0.3s ease"}),this.bars.push(t),this.trigger.appendChild(t)}this.container.appendChild(this.trigger),this.container.addEventListener("mousedown",this.onMouseEventBound),this.container.addEventListener("mouseup",this.onMouseEventBound),this.popupTrigger===Hs.Click?this.trigger.addEventListener("click",this.onClickBound):this.popupTrigger===Hs.Hover&&(this.container.addEventListener("mouseenter",this.onMouseEnterBound),this.container.addEventListener("mouseleave",this.onMouseLeaveBound),this.trigger.addEventListener("click",this.onClickBound)),this.popupTrigger===Hs.None&&(this.container.style.cursor="default"),this.videoContainerElement.appendChild(this.container)}getPositionStyles(){const e="8px";switch(this.position){case $s.TopLeft:return{top:e,left:e};case $s.TopRight:return{top:e,right:e};case $s.BottomLeft:return{bottom:e,left:e};case $s.BottomRight:return{bottom:e,right:e};default:return{top:e,right:e}}}onClick(e){e.stopPropagation(),this.panelVisible?this.hidePanel():this.showPanel()}onDocumentClick(e){this.panelVisible&&this.container&&!this.container.contains(e.target)&&this.hidePanel()}onKeyDown(e){"Escape"===e.key&&this.panelVisible&&(this.hidePanel(),this.trigger?.focus())}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"),this.panel.id=this.panelId,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===Hs.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,this.trigger?.setAttribute("aria-expanded","true"),document.addEventListener("click",this.onDocumentClickBound),document.addEventListener("keydown",this.onKeyDownBound))}hidePanel(){this.panel&&(this.panel.style.display="none"),this.panelVisible=!1,this.trigger?.setAttribute("aria-expanded","false"),document.removeEventListener("click",this.onDocumentClickBound),document.removeEventListener("keydown",this.onKeyDownBound)}positionPanel(){if(!this.panel||!this.container)return;const e=window.innerWidth,t=window.innerHeight,n=this.container.getBoundingClientRect(),s={top:Math.max(0,Math.min(n.top,t)),bottom:Math.max(0,Math.min(n.bottom,t)),left:Math.max(0,Math.min(n.left,e)),right:Math.max(0,Math.min(n.right,e))};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";const{width:i,height:r}=this.panel.getBoundingClientRect();this.panel.style.visibility="";const o=s.top-4,a=t-s.bottom-4,l=s.left-4,c=e-s.right-4;let d,h;o>=r||a>=r?(d=a>=r&&(o<r||a>=o)?s.bottom+4:s.top-4-r,h=this.position===$s.TopLeft||this.position===$s.BottomLeft?s.left:s.right-i):(h=c>=i&&(l<i||c>=l)?s.right+4:s.left-4-i,d=s.bottom-r),h=Math.max(4,Math.min(h,e-i-4)),d=Math.max(0,Math.min(d,t-r-4)),this.panel.style.top=`${d}px`,this.panel.style.left=`${h}px`}updatePanel(){if(!this.panel||!this.lastMetrics)return;const e=this.lastMetrics,t=this.strings,n=document.createElement("div");Object.assign(n.style,{fontWeight:"600",marginBottom:"4px",color:this.getColor(e.qualityLevel)}),n.textContent=t.qualityHeader.replace("{level}",this.levelName(e.qualityLevel));const s=[n];if(t.message&&e.qualityLevel!==_s.Good){const e=document.createElement("div");Object.assign(e.style,{marginBottom:"6px",whiteSpace:"normal",maxWidth:"240px"}),e.textContent=t.message,s.push(e)}s.push(this.panelSectionHeader(t.qualityScoreMos),this.panelRow(t.audio,`${e.audioMos.toFixed(1)} / 5.0`),this.panelRow(t.video,`${e.videoMos.toFixed(1)} / 5.0`),this.panelSectionHeader(t.connection),this.panelRow(t.roundTrip,`${e.roundTripTimeMs} ms`),this.panelRow(t.packetLoss,`${e.audioPacketLossPercent}% ${t.audio} / ${e.videoPacketLossPercent}% ${t.video}`),this.panelRow(t.jitter,`${e.audioJitterMs} ms ${t.audio} / ${e.videoJitterMs} ms ${t.video}`),this.panelSectionHeader(t.throughput),this.panelRow(t.bitrate,`${e.audioBitrateKbps} ${t.audio} / ${e.videoBitrateKbps} ${t.video} kbps`),this.panelRow(t.frameRate,`${e.frameRate} fps`)),this.panel.textContent="",this.panel.append(...s)}levelName(e){switch(e){case _s.Good:return this.strings.good;case _s.Fair:return this.strings.fair;case _s.Poor:return this.strings.poor}}panelSectionHeader(e){const t=document.createElement("div");return Object.assign(t.style,{color:"#6b7280",fontSize:"10px",textTransform:"uppercase",letterSpacing:"0.5px",marginTop:"6px",marginBottom:"2px"}),t.textContent=e,t}panelRow(e,t){const n=document.createElement("div");Object.assign(n.style,{display:"flex",justifyContent:"space-between",gap:"12px"});const s=document.createElement("span");s.style.color="#9ca3af",s.textContent=e;const i=document.createElement("span");return i.textContent=t,n.append(s,i),n}getColor(e){switch(e){case _s.Good:return"#22c55e";case _s.Fair:return"#eab308";case _s.Poor:return"#ef4444"}}update(e){if(this.lastMetrics=e,!this.container)return;const t=`${this.strings.networkQuality}: ${this.levelName(e.qualityLevel)}`;this.trigger?.setAttribute("aria-label",t),this.liveRegion&&e.qualityLevel!==this.announcedLevel&&(this.announcedLevel=e.qualityLevel,this.liveRegion.textContent=t);const n=this.getColor(e.qualityLevel),s=e.qualityLevel===_s.Good?3:e.qualityLevel===_s.Fair?2:1;this.bars.forEach((e,t)=>{e.style.background=t<s?n:Js}),this.visibility===Ws.WhenDegraded?this.container.style.display=e.qualityLevel===_s.Good?"none":"flex":this.container.style.display="flex",this.panelVisible&&(this.updatePanel(),this.positionPanel())}destroy(){this.trigger&&(this.trigger.removeEventListener("click",this.onClickBound),this.trigger=void 0),this.liveRegion&&(this.liveRegion.remove(),this.liveRegion=void 0),this.announcedLevel=void 0,this.container&&(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),void 0!==this.originalParentPosition&&(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),document.removeEventListener("keydown",this.onKeyDownBound),this.bars=[],this.panelVisible=!1,this.lastMetrics=void 0}}const ni="uneeq-js.avoid-av1-until";class si{session;connectionUrl;videoContainerElement;stream;messages=new Q;videoElement;audioElement;videoInitialized=!1;audioIntentId=0;dataChannelOpen=!1;sceneReady=!1;maxReconnectAttempts=4;reconnectionAttempts=0;allowReconnection=!0;reconnectTimeoutId;baseReconnectDelayMs=500;maxReconnectDelayMs=1e4;currentRendererId;audioStatsInternal;freezeCount=0;lastDecodedFrames=0;lastCheckTime=Date.now();freezeTransferThreshold=10;audioStatsAnalyzer;networkQualityInterval;networkIndicator;lastQualityLevel=_s.Good;noIceServers=!1;implausibleFrameSizeLogged=!1;config;clientMessages;_audioUpstreamMode;constructor(e,t,n){this.session=e,this.connectionUrl=t,this.videoContainerElement=n,this.config=e.config,this.clientMessages=e.messages,this._audioUpstreamMode=Ks(this.config.audioUpstreamMode)}get audioUpstreamMode(){return this._audioUpstreamMode}init(){r.A.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 Fs.qw);const e=Gs(this.audioUpstreamMode);"speech-recognition-service"!==this.audioUpstreamMode&&r.A.info(`audioUpstreamMode='${this.audioUpstreamMode}' is beta; behaviour may change.`);const t=new Je({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 Ps(t,{videoElementParent:this.videoContainerElement});const n=(s=this.config.preferredVideoCodec,i=navigator.userAgent,o=((e=Date.now())=>{try{return Number(window.localStorage.getItem(ni))>e}catch{return!1}})(),"h264"===s?{codec:"h264",reason:"config"}:o?{codec:"h264",reason:"decoder-fault-hint"}:(e=>/Android/.test(e)&&/Chrome\//.test(e))(i)?{codec:"h264",reason:"android-chromium"}:{codec:"renderer-order"});var s,i,o;r.A.info("Video codec decision",n),"renderer-order"===n.codec&&t.setOptionSettingValue(Ge.PreferredCodec,""),G.InitLogging($.Warning,!1),this.stream.setSignallingUrlBuilder(function(){let e=t.getTextSettingValue(Qe.SignallingServerUrl);return t.isFlagEnabled(He.BrowserSendOffer)&&(e+=(e.includes("?")?"&":"?")+He.BrowserSendOffer+"=true"),e}),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}})=>{r.A.trace("WebRTC: VideoEncoderAvgQP - lower is better, ranges from 0 to 51:",e)}),this.stream?.addEventListener("webRtcAutoConnect",()=>{r.A.debug("WebRTC: AutoConnect triggered")}),this.stream?.addEventListener("webRtcConnected",this.handleWebRtcConnectedMessage.bind(this)),this.stream?.addEventListener("statsReceived",({data:{aggregatedStats:e}})=>{r.A.trace("WebRTC: StatsReceived",e)}),this.stream?.addEventListener("webRtcTCPRelayDetected",()=>{r.A.warn("WebRTC: Stream quailty likely degraded due to network enviroment, stream is relayed over TCP.")})}addWebSocketHandlers(){const e=this.stream?.signallingProtocol?.transport;e?.webSocket?.addEventListener("error",this.handleWebSocketError.bind(this)),e?.webSocket?.addEventListener("open",()=>{e.webSocket?.send(JSON.stringify({type:Ds.ClientInfo,uneeqJsSdkVersion:"3.23.5"}))}),this.stream?.signallingProtocol.on(Ds.Error,e=>{r.A.error("Signaling: Received error message from server",e),this.clientMessages?.next(new Fs.Cj(`Signaling server error: ${e}`))}),this.stream?.signallingProtocol.on(Ds.IndexInQueue,this.handleIndexInQueueMessage.bind(this)),this.stream?.signallingProtocol.on(Ds.RendererTaken,this.handleRendererTakenMessage.bind(this)),this.stream?.signallingProtocol.on(Ds.RendererGone,this.handleRendererGoneEvent.bind(this)),this.stream?.signallingProtocol.on(Ds.SwitchRendererRequest,this.handleSwitchRendererRequestEvent.bind(this)),this.stream?.signallingProtocol.on(Ds.CustomerConcurrencyLimitReached,this.handleCustomerConcurrencyLimitReachedMessage.bind(this)),this.stream?.signallingProtocol.on(Ds.RendererError,this.handleRendererErrorMessage.bind(this)),this.stream?.signallingProtocol.on(Ds.RendererVersionWarning,this.handleRendererVersionWarningMessage.bind(this)),this.stream?.signallingProtocol.on(Ds.Config,this.checkForUneeqIceServers.bind(this))}checkForUneeqIceServers(e){const t=e?.peerConnectionOptions?.iceServers;if(void 0===t)return void r.A.warn("Signaling: config message carried no peerConnectionOptions.iceServers; leaving ICE server status unchanged");r.A.info("Signaling: Received ice config message with urls:",(t??[]).map(e=>({urls:e.urls})));const n=(t??[]).some(e=>e.username?.includes("disabled")&&e.urls?.some(e=>e.includes("0.0.0.0")));this.noIceServers=!t?.length||n,this.noIceServers&&r.A.warn("Signaling: no usable UneeQ ICE servers in the session config. This should be intentional, is intended for locally run renderers e.g. kiosk, miniprem etc.")}handleWebSocketError(e){r.A.error("Signaling: WebSocket error",r.A.serialiseError(e)),this.reconnectIfSafe(e)}handleVideoInitialized(){r.A.info("Video initialized."),this.videoElement=this.videoContainerElement?.getElementsByTagName("video")[0],this.audioElement=this.stream?.webRtcController?.streamController?.audioElement,this.audioStatsAnalyzer=new Qs(this.stream,this.videoElement,this.audioElement);const e=this.getAudioPlaybackElement();if(e&&this.config.speakerDeviceId&&this.setSpeakerDevice(e,this.config.speakerDeviceId),this.videoElement)this.videoElement.muted=!0,this.videoElement.play().then(()=>{this.playAudioElement()}).catch(e=>{if(e instanceof DOMException&&"NotAllowedError"===e.name)r.A.warn("Video autoplay blocked by browser. Requesting user gesture to resume playback."),this.clientMessages?.next(new Fs.MA);else{const t="Fatal Error: Digital Human video cannot be played.";r.A.error(t,r.A.serialiseError(e)),this.clientMessages?.next(new Fs.Cj(t)),this.endSession(Bs,!0)}}),this.videoInitialized=!0,this.messages.next(new Is),this.reconnectionAttempts=0,this.clearReconnectTimer();else{const e="Fatal Error: Video element not found.";r.A.error(e),this.clientMessages?.next(new Fs.Cj(e)),this.endSession(Bs,!0)}setTimeout(()=>{this.clientMessages?.next(new Fs.xQ)},mi)}getAudioPlaybackElement(){return zs(this.videoElement)?this.videoElement:this.audioElement}playAudioElement(){const e=this.getAudioPlaybackElement();e?this.routeThenPlay(e,++this.audioIntentId):this.handleMissingAudioElement()}routeThenPlay(e,t){const n=this.config.speakerDeviceId,s=e;n&&s.setSinkId&&s.sinkId!==n?this.setSpeakerDevice(e,n).then(()=>{if(t!==this.audioIntentId)return;const n=this.getAudioPlaybackElement();n&&(n!==e?this.routeThenPlay(n,t):this.unmuteAndPlay(e))}).catch(e=>{r.A.error("Deferred audio playback failed",r.A.serialiseError(e))}):this.unmuteAndPlay(e)}unmuteAndPlay(e){const t=e===this.videoElement;e.muted=!1,e.play().then(()=>{r.A.info("Audio playback successfully started."),this.clientMessages?.next(new Fs.M8)}).catch(n=>{r.A.warn("Audio cannot be played.",n),this.clientMessages?.next(new Fs.Tu),t?(e.muted=!0,e.play().then(()=>{this.clientMessages?.next(new Fs.XC)}).catch(e=>{r.A.warn("Muted video reveal also blocked.",e),this.clientMessages?.next(new Fs.Cj(`Video playback failed: ${e}`))})):this.clientMessages?.next(new Fs.XC)})}resumeVideoPlayback(){this.videoElement?this.videoElement.play().then(()=>{this.playAudioElement()}).catch(e=>{r.A.error("Video playback failed after user gesture",r.A.serialiseError(e)),this.clientMessages?.next(new Fs.Cj("Video playback failed after user gesture")),this.endSession("sessionEndedDueToPermissionsError",!0)}):r.A.warn("resumeVideoPlayback called but no video element available")}pauseAudioElement(){this.audioIntentId++;const e=this.getAudioPlaybackElement();e?(e===this.videoElement?e.muted=!0:e.pause(),this.clientMessages?.next(new Fs.Tu)):this.handleMissingAudioElement()}muteUpstreamMic(){Gs(this.audioUpstreamMode)?this.stream?this.stream.muteMicrophone():r.A.warn("muteUpstreamMic called before PixelStreaming stream is initialised; ignoring."):r.A.warn(`muteUpstreamMic called in '${this.audioUpstreamMode}' mode — no PS upstream audio track to mute; ignoring.`)}unmuteUpstreamMic(){Gs(this.audioUpstreamMode)?this.stream?this.stream.unmuteMicrophone(!1):r.A.warn("unmuteUpstreamMic called before PixelStreaming stream is initialised; ignoring."):r.A.warn(`unmuteUpstreamMic called in '${this.audioUpstreamMode}' mode — no PS upstream audio track to unmute; ignoring.`)}setSpeakerDevice(e,t){const n=e;return n.setSinkId?n.setSinkId(t).then(()=>{r.A.info(`Speaker device set to: ${t}`)}).catch(e=>{r.A.error(`Failed to set speaker device: ${t}`,r.A.serialiseError(e))}):(r.A.error("setSinkId not supported in this browser, cannot set speaker device"),Promise.resolve())}handleMissingAudioElement(){const e="Error: Digital Human audio element not found, cannot play audio.";r.A.error(e),this.clientMessages?.next(new Fs.Cj(e))}startAudioStatsMonitor(e=5e3){this.stopAudioStatsMonitor(),r.A.info("Starting audio stats monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new Qs(this.stream,this.videoElement,this.audioElement)),this.audioStatsInternal=setInterval(()=>{this.audioStatsAnalyzer?.analyzeAudioStats().catch(e=>{r.A.error("Error analyzing audio stats",r.A.serialiseError(e))})},e)}stopAudioStatsMonitor(){this.audioStatsInternal&&clearInterval(this.audioStatsInternal)}startNetworkQualityMonitor(e){this.stopNetworkQualityMonitor(),r.A.info("Starting network quality monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new Qs(this.stream,this.videoElement,this.audioElement)),this.noIceServers&&r.A.info("Network indicator suppressed: session does not route through UneeQ");const t=this.noIceServers?{...e,visibility:Ws.Hidden}:e;this.videoContainerElement&&t.visibility!==Ws.Hidden&&(this.networkIndicator=new ti(this.videoContainerElement,t)),this.lastQualityLevel=_s.Good;const n=e.collectionIntervalMs??3e3;this.networkQualityInterval=setInterval(()=>{this.audioStatsAnalyzer?.collectNetworkQuality(e).then(e=>{e&&(this.networkIndicator?.update(e),this.logQualityTransition(e),this.clientMessages?.next(new Fs.N8(e)))}).catch(e=>{r.A.error("Error collecting network quality",r.A.serialiseError(e))})},n)}logQualityTransition(e){if(e.qualityLevel===this.lastQualityLevel)return;this.lastQualityLevel=e.qualityLevel;const t={qualityLevel:e.qualityLevel,videoPacketLossPercent:e.videoPacketLossPercent,audioPacketLossPercent:e.audioPacketLossPercent,roundTripTimeMs:e.roundTripTimeMs,videoJitterMs:e.videoJitterMs,frameRate:e.frameRate,videoMos:e.videoMos,audioMos:e.audioMos};e.qualityLevel===_s.Good?r.A.info("[Network] quality recovered to Good",t):r.A.warn(`[Network] quality degraded to ${e.qualityLevel}`,t)}stopNetworkQualityMonitor(){this.networkQualityInterval&&(clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0),this.networkIndicator&&(this.networkIndicator.destroy(),this.networkIndicator=void 0)}handleDataChannelOpen(){r.A.info("DataChannelOpen"),this.dataChannelOpen=!0,this.messages.next(new xs)}handleWebRtcFailed(e){this.stream?.isReconnecting()?r.A.debug("Ignoring webRtcFailed: Pixel Streaming is already reconnecting from our own call"):(r.A.error("WebRTC failed",e),this.reconnectIfSafe(e))}handleWebRtcDisconnected(e){this.stream?.isReconnecting()?r.A.debug("Ignoring webRtcDisconnected: Pixel Streaming is already reconnecting from our own call"):(r.A.warn(`WebRTC disconnected, message: ${e?.data?.eventString}, allowClickToReconnect: ${e?.data?.allowClickToReconnect}`),this.reconnectIfSafe(e))}handleWebRtcStats(e){const t=new As(e.data.aggregatedStats);this.messages.next(t);const n=e.data.aggregatedStats.inboundVideoStats?.framesDecoded??0;this.checkForFreeze(n),this.checkForImplausibleFrameSize(e.data.aggregatedStats)}checkForImplausibleFrameSize(e){const t=e.inboundVideoStats;if(this.implausibleFrameSizeLogged||!t||(n=t.frameWidth,s=t.frameHeight,!((n??0)>4096||(s??0)>4096)))return;var n,s;this.implausibleFrameSizeLogged=!0;const i=t.codecId?e.codecs?.get(t.codecId)?.mimeType:void 0;r.A.warn("[WebRTC] Decoder reported an implausible video frame size",{sessionId:this.session.id,codec:i,frameWidth:t.frameWidth,frameHeight:t.frameHeight,framesReceived:t.framesReceived,framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,userAgent:navigator.userAgent}),(e=>(e??"").toLowerCase().includes("av1"))(i)&&((e=Date.now())=>{try{window.localStorage.setItem(ni,String(e+6048e5))}catch{return}})()}checkForFreeze(e){const t=Date.now();if(0!==this.lastDecodedFrames||0!==e)if(e===this.lastDecodedFrames){this.freezeCount++;const e=((t-this.lastCheckTime)/1e3).toFixed(1);r.A.warn(`[WebRTC] Video FROZEN for ${e}s (count=${this.freezeCount})`),this.freezeCount>=this.freezeTransferThreshold&&(r.A.error(`[WebRTC] Video frozen ${this.freezeTransferThreshold} times in a row, transferring session...`),this.session.sessionTransferManager.transferSession(),this.freezeCount=0)}else this.freezeCount=0,this.lastDecodedFrames=e,this.lastCheckTime=t;else r.A.debug("[WebRTC] Waiting for first video frame...")}clearReconnectTimer(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=void 0)}scheduleReconnect(){const e=Math.min(this.baseReconnectDelayMs*Math.pow(2,this.reconnectionAttempts),this.maxReconnectDelayMs);r.A.info(`Scheduling reconnection attempt ${this.reconnectionAttempts} in ${e}ms`),this.reconnectTimeoutId=setTimeout(()=>{r.A.info(`Executing reconnection attempt ${this.reconnectionAttempts}`),this.reconnectTimeoutId=void 0,this.videoInitialized=!1,this.dataChannelOpen=!1,this.sceneReady=!1,this.audioStatsAnalyzer?.resetStats(),this.stream?.reconnect()},e)}reconnectIfSafe(e){try{this.allowReconnection&&!this.reconnectTimeoutId?(r.A.debug("Checking if should attempt reconnection after event",e),this.reconnectionAttempts<this.maxReconnectAttempts?(this.reconnectionAttempts++,this.clientMessages?.next(new Fs.fI),this.scheduleReconnect()):(r.A.info("Max reconnection attempts reached. Ending session."),this.clientMessages?.next(new Fs.JP),this.endSession(Us,!1))):r.A.warn("Reconnection already scheduled or reconnecting is disabled")}catch(e){r.A.error("Error during reconnection attempt",r.A.serialiseError(e)),this.clientMessages?.next(new Fs.Cj("Error during reconnection attempt")),this.endSession(Us,!1)}}handleDataChannelMessage(e){r.A.trace("Signaling: Received data channel message",e);try{const t=JSON.parse(e);if(void 0===t.type)throw new Error("Signaling: Engine response missing type");this.messages.next(new Ls(t))}catch(e){r.A.error("Signaling: Failed to parse engine response",r.A.serialiseError(e))}}handleIndexInQueueMessage(e){try{const t=Number(e.message);this.clientMessages?.next(new Fs.F8(t))}catch(e){r.A.error("Signaling: Failed to parse position in queue message",r.A.serialiseError(e))}}handleRendererTakenMessage(e){try{const t=e;this.currentRendererId=t.message,this.clientMessages?.next(new Fs.qo(t.message)),r.A.info("Signaling: Renderer taken event",t.message)}catch(e){r.A.error("Signaling: Failed to parse renderer taken message",r.A.serialiseError(e))}}handleWebRtcConnectedMessage(){this.clientMessages?.next(new Fs.Cl),r.A.info("Signaling: WebRTC connected")}extractRendererGoneId(e){const t=e;if(t?.rendererId)return t.rendererId;const n="string"==typeof t?.message?/^Renderer (\S+) /.exec(t.message):null;return n?.[1]}isStaleRendererMessage(e){return Boolean(e)&&Boolean(this.currentRendererId)&&e!==this.currentRendererId}handleRendererGoneEvent(e){const t=this.extractRendererGoneId(e);this.isStaleRendererMessage(t)?r.A.warn(`Signaling: Discarding renderer gone event for superseded renderer ${t}`,e):(r.A.info("Signaling: Renderer gone event",e),this.reconnectIfSafe(e))}handleSwitchRendererRequestEvent(e){const t=e;this.isStaleRendererMessage(t?.message)?r.A.warn(`Signaling: Discarding switch renderer request for superseded renderer ${t?.message}`,e):(r.A.info("Signaling: Renderer switch renderer request event",e),this.session.sessionTransferManager.transferSession())}handleCustomerConcurrencyLimitReachedMessage(e){r.A.warn("Signaling: Customer concurrency limit reached message received",e),this.clientMessages?.next(new Fs.MM)}handleRendererVersionWarningMessage(e){const t=e;r.A.warn("Signaling: session is served by an outdated renderer",t),this.clientMessages?.next(new Fs.n3(t?.rendererVersion??"",t?.latestVersion??"",t?.message??"Session is served by an outdated renderer"))}handleRendererErrorMessage(e){try{const t=e,n=t.code??-1,s=t.message??"An unknown renderer error occurred";r.A.error(`Signaling: Renderer error received - code: ${n}, message: ${s}`),this.clientMessages?.next(new Fs.j_(n,s)),this.endSession(Vs,!0)}catch(e){r.A.error("Signaling: Failed to parse renderer error message",r.A.serialiseError(e)),this.clientMessages?.next(new Fs.j_(-1,"An unknown renderer error occurred")),this.endSession(Vs,!0)}}socketSend(e){r.A.trace("Signaling: Sending socket message",e);const t=this.stream?.signallingProtocol?.transport;t?.webSocket?.send(JSON.stringify(e))}dataSend(e){const t=e.toJSON();if(t.action===Ns.A.ChatPrompt){const n=t.data?.requestId;r.A.info(`Signaling: Sending data channel message — action=chat_prompt, requestId=${n??"unknown"}`),(!(e instanceof Os.D)||e.shouldEmitPromptRequest)&&this.clientMessages?.next(new Fs.bS(t.data))}else r.A.info("Signaling: Sending data channel message",JSON.stringify(t));this.stream?.emitUIInteraction(e)}dataSendBinary(e){r.A.info("Signaling: Sending data channel binary message");const t=this.uint8ToBase64(e);this.stream?.emitUIInteraction(t)}uint8ToBase64(e){let t="";const n=e.byteLength;for(let s=0;s<n;s++)t+=String.fromCharCode(e[s]);return btoa(t)}endSession(e="sessionEndedByUser",t=!0){r.A.info("Signaling: Ending session"),this.clearReconnectTimer(),this.stopNetworkQualityMonitor(),this.socketSend({message:e,type:Ds.ClientGone,sessionId:this.config.sessionId}),this.streamDisconnect(),r.A.info("Session has ended, reason: "+e),t&&this.clientMessages?.next(new Fs.aY(e))}streamDisconnect(){r.A.info("Signaling: Disconnecting stream"),this.stopNetworkQualityMonitor(),this.stopAudioStatsMonitor(),this.allowReconnection=!1,this.clearReconnectTimer();const e=this.stream?.webRtcController?.statsTimerHandle;e&&window.clearInterval(e);const t=this.stream?.webRtcController?.peerConnectionController;if(t?.peerConnection){t.peerConnection.getReceivers=()=>[];const e=t.peerConnection;Object.defineProperty(t,"peerConnection",{get:()=>e,set:()=>{},configurable:!0})}this.stream?.disconnect(),this.audioIntentId++,this.dataChannelOpen=!1,this.videoInitialized=!1,this.sceneReady=!1}startSoftSwitch(){r.A.info("Signaling: Start soft switching"),this.clientMessages?.next(new Fs.sF)}stopSoftSwitch(){r.A.info("Signaling: Stop soft switching"),this.clientMessages?.next(new Fs.WQ)}}var ii;!function(e){e.NlpPromptResult="nlp_prompt_result",e.AvatarStartedSpeaking="avatar_started_speaking",e.AvatarStoppedSpeaking="avatar_stopped_speaking",e.Error="error",e.SceneReady="scene_ready",e.SpeechEvent="speech_event",e.SessionEnded="session_ended",e.SpeechStreamOpened="speech_stream_opened",e.SpeechStreamClosed="speech_stream_closed"}(ii||(ii={}));var ri,oi,ai=n(1);!function(e){e.CloseUp="close_up",e.LooseCloseUp="loose_close_up",e.TightMediumShot="tight_medium_shot",e.MediumShot="medium_shot",e.MediumFullShot="medium_full_shot",e.FullShot="full_shot"}(ri||(ri={})),function(e){e.Left="left",e.Right="right",e.Center="center",e.Centre="centre"}(oi||(oi={}));class li{position;duration;requestId;constructor(e,t=2e3,n=(0,ai.g)()){this.position=e,this.duration=t,this.requestId=n}toJSON(){return{action:Ns.A.CameraAnchor,data:{requestId:this.requestId,position:this.position,transition_duration_ms:this.duration}}}}class ci{avatarId;requestId;constructor(e,t=(0,ai.g)()){this.avatarId=e,this.requestId=t}toJSON(){return{action:Ns.A.ChangeAvatar,data:{id:this.avatarId,requestId:this.requestId}}}}class di{url;requestId;constructor(e,t=(0,ai.g)()){this.url=e,this.requestId=t}toJSON(){return{action:Ns.A.LoadBackground,data:{url:this.url,requestId:this.requestId}}}}class hi{actionName;requestId;constructor(e,t=(0,ai.g)()){this.actionName=e,this.requestId=t}toJSON(){return{action:Ns.A.TriggerAction,data:{action_name:this.actionName,requestId:this.requestId}}}}var ui=n(33);class gi{session;isTransferSessionInProgress=!1;constructor(e){this.session=e,this.addTransferSessionListener()}addTransferSessionListener(){this.isTransferSessionInProgress=!1,document.addEventListener("keydown",e=>{e.ctrlKey&&e.shiftKey&&"y"===e.key.toLowerCase()&&(r.A.info("Session transfer via keyboard shortcut triggered"),this.transferSession())})}transferSession(){this.isTransferSessionInProgress?r.A.warn("Transfer already in progress, skipping"):(this.isTransferSessionInProgress=!0,r.A.info("Beginning session transfer"),this.session.config.videoContainerElement&&(this.session.config.videoContainerElement.querySelectorAll("#freezeFrame,#streamingVideo").forEach(e=>{e.remove()}),this.session.signaling&&this.session.signaling.streamDisconnect()),this.session.createSignaling(this.session.config.videoContainerElement??document.createElement("div")).init())}switchLiveVideo(e,t){r.A.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(),r.A.info("Session transfer complete")},1e3))}}const pi=[1103,1200,1402],mi=750;class fi{config;id;signaling;messages=new j;speechRec;promptMetadata={};audioStreamId;sessionTransferManager;jwt;welcomeRequested=!1;resolutionLogged=!1;sttPausedByHost=!1;_audioUpstreamMode;constructor(e){this.config=e,this.sessionTransferManager=new gi(this),this._audioUpstreamMode=Ks(this.config.audioUpstreamMode)}get audioUpstreamMode(){return this._audioUpstreamMode}updatePromptMetadata(e){try{JSON.parse(JSON.stringify(e)),this.promptMetadata.custom=e,this.messages.next(new Fs.ss(this.promptMetadata))}catch(t){r.A.error("Error parsing custom metadata",e,r.A.serialiseError(t))}}setEnableMicrophone(e){const t=this.audioUpstreamMode;this.config.enableMicrophone=e,this.sttPausedByHost=!1;let n=!1;Xs(t)&&(this.speechRec?(e?this.speechRec.startRecognition():this.speechRec.stopRecognition(),n=!0):r.A.warn("setEnableMicrophone: STT leg is configured but speech recognition is not initialised yet")),Gs(t)&&(this.signaling?(e?this.signaling.unmuteUpstreamMic():this.signaling.muteUpstreamMic(),n=!0,Xs(t)||this.messages.next(new Fs.WY(e))):r.A.warn("setEnableMicrophone: PS leg is configured but signaling is not initialised yet")),n||r.A.warn(`setEnableMicrophone(${e}) had nothing to do in mode '${t}' — session not ready?`)}pauseSpeechRecognition(){return this.sttPausedByHost=!0,this.speechRec?this.speechRec.pause():(r.A.warn("pauseSpeechRecognition: pause intent recorded, but speech recognition is not initialised yet — nothing to pause"),!1)}resumeSpeechRecognition(){return this.sttPausedByHost=!1,this.speechRec?this.speechRec.resume():(r.A.warn("resumeSpeechRecognition: pause intent cleared, but speech recognition is not initialised yet — nothing to resume"),!1)}updateSpeechRecognitionConfig(e){return this.speechRec?.updateConfig?this.speechRec.updateConfig(e):(r.A.warn("updateSpeechRecognitionConfig: the active STT model does not support mid-session config updates"),!1)}setCameraAnchorDistance(e,t=0,n=this.signaling){this.config.cameraAnchorDistance=e,n?.dataSend(new li(e,t))}setCameraAnchorHorizontal(e,t=0,n=this.signaling){this.config.cameraAnchorHorizontal=e,n?.dataSend(new li(e,t))}changeAvatar(e,t=this.signaling){t?.dataSend(new ci(e))}loadBackground(e,t=this.signaling){t?.dataSend(new di(e))}userStartSpeaking(e=this.signaling){e?.dataSend(new ui.A(ui.f.Start))}userStopSpeaking(e=this.signaling){e?.dataSend(new ui.A(ui.f.Stop))}triggerAction(e,t=this.signaling){t?.dataSend(new hi(e))}resumeVideoPlayback(){this.signaling?.resumeVideoPlayback()}createSession(){this.messages.subscribe(e=>{if(this.config.messageHandler&&this.config.messageHandler(e),e.uneeqMessageType===Fs.Yg.SoftSwitchFinished||e.uneeqMessageType===Fs.Yg.SessionReconnectingFinished){if(!Xs(this.audioUpstreamMode))return;if(this.config.enableMicrophone&&!this.sttPausedByHost)e.uneeqMessageType===Fs.Yg.SessionReconnectingFinished?(r.A.info("Session, resuming speech recognition after reconnect"),this.speechRec?.resume()):(r.A.info("Session, restarting speech recognition after soft switch"),this.speechRec?.startRecognition());else{const t=e.uneeqMessageType===Fs.Yg.SoftSwitchFinished?"soft switch":"reconnect",n=this.sttPausedByHost?"paused by host":"microphone disabled";r.A.info(`Session, skipping speech recognition restart after ${t} (${n})`)}}}),this.id=this.config.sessionId,this.jwt=this.config.sessionToken,r.A.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")){const t=new URLSearchParams({token:this.jwt});this.config.backgroundUrl&&t.append("backgroundUrl",this.config.backgroundUrl);const n=(this.config.connectionUrl+`/session-service/v1/ws/session?${t.toString()}`).replace("http://","ws://").replace("https://","wss://");r.A.debug("Socket URL:",n);const s=new si(this,n,e);return s.messages.subscribe(e=>{this.signalingEventHandler(e,s)}),s}signalingEventHandler(e,t){switch(e.type){case hs.VideoInitialised:case hs.DataChannelOpen:this.handleSessionReady(t);break;case hs.DataChannelResponse:this.handleDataChannelMessage(e,t);break;case hs.WebRtcStats:{const t=e.stats;!this.resolutionLogged&&t.inboundVideoStats?.frameWidth&&t.inboundVideoStats?.frameHeight&&(r.A.info("Video resolution:",`${t.inboundVideoStats.frameWidth}x${t.inboundVideoStats.frameHeight}`),this.resolutionLogged=!0),this.config.webRtcStatsEmitMessages&&this.messages.next(new Fs.O$(t)),this.config.webRtcStatsLogMessages&&r.A.info("WebRTC stats",t);break}}}handleSessionReady(e){r.A.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 Fs.wf(this.id)),e.startNetworkQualityMonitor(this.config.networkIndicator??{visibility:Ws.Hidden}),this.config.webRtcStatsLogMessages&&e.startAudioStatsMonitor()},mi))}async initSpeechRecognition(e){if(!Xs(this.audioUpstreamMode))return void r.A.info(`[STT] audioUpstreamMode='${this.audioUpstreamMode}' — skipping STT provider initialisation (no STT leg in this mode).`);if(this.speechRec)return void r.A.warn("Speech recognition already initialized");let t=this.config.speechRecognitionProvider||js.Google;r.A.info(`[STT] Config speechRecognitionProvider: "${this.config.speechRecognitionProvider}", resolved provider: "${t}"`),t!==js.Google&&t!==js.Deepgram&&(r.A.warn(`Invalid speechRecognitionProvider value: "${String(t)}". Supported values are "google" or "deepgram". Defaulting to "google".`),t=js.Google,this.config.speechRecognitionProvider=js.Google),r.A.info(`[STT] Using provider: ${t}`);try{this.speechRec=await(t===js.Deepgram?this.createDeepgramSTT(e):this.createGoogleSTT(e))}catch(e){return void r.A.error("[STT] Failed to initialise speech recognition provider",r.A.serialiseError(e))}this.config.enableMicrophone&&!this.sttPausedByHost&&this.speechRec&&this.speechRec.startRecognition()}async createGoogleSTT(e){const t=this.getSpeechOptions(e);r.A.debug("Initializing Google STT (speech-recognition-service)");const{GoogleSTT:s}=await Promise.all([n.e(113),n.e(157)]).then(()=>n(157));return new s(t)}async createDeepgramSTT(e){const t=this.config.deepgramConfig||{};if(this.isFluxModel(t.model))return this.createDeepgramFluxSTT(e);r.A.debug("Initializing Deepgram STT");const s={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:e=>{this.signaling?.dataSend(e)},enableInterrupt:this.config.enableInterruptBySpeech,safetyNetTimeoutMs:t.safetyNetTimeoutMs,keyterms:t.keyterms,noDelay:t.noDelay},{DeepgramSTT:i}=await Promise.all([n.e(464),n.e(3)]).then(()=>n(3));return new i(s)}isFluxModel(e){return void 0!==e&&e.toLowerCase().startsWith("flux")}async createDeepgramFluxSTT(e){r.A.debug("Initializing Deepgram Flux STT (v2 API)");const t=this.config.deepgramConfig||{},s={connectionUrl:this.config.connectionUrl,jwtToken:e,sessionId:this.id,model:t.model,language:t.language,eotThreshold:t.eotThreshold,eagerEotThreshold:t.eagerEotThreshold,eotTimeoutMs:t.eotTimeoutMs,eagerMaxTurnDurationMs:t.eagerMaxTurnDurationMs,keyterms:t.keyterms,safetyNetTimeoutMs:t.safetyNetTimeoutMs,echoCancellation:t.microphone?.echoCancellation,noiseSuppression:t.microphone?.noiseSuppression,autoGainControl:t.microphone?.autoGainControl,microphoneDeviceId:this.config.microphoneDeviceId,promptMetadata:this.promptMetadata,messages:this.messages,sendMessage:e=>{this.signaling?.dataSend(e)}},{DeepgramFluxSTT:i}=await Promise.all([n.e(464),n.e(363)]).then(()=>n(363));return new i(s)}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:e=>{this.signaling?.dataSend(e)},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(r.A.debug("Processing data channel message",e),e.msg.type){case ii.NlpPromptResult:this.messages.next(new Fs.nD(e.msg));break;case ii.AvatarStartedSpeaking:this.messages.next(new Fs.yr);break;case ii.AvatarStoppedSpeaking:this.messages.next(new Fs.kS);break;case ii.Error:r.A.error(`an error has occurred - ${JSON.stringify(e.msg)}`),this.handleChannelMessageError(e.msg);break;case ii.SceneReady:r.A.debug("Scene is ready"),t.sceneReady=!0,this.handleSessionReady(t),this.messages.next(new Fs.Ln);break;case ii.SpeechEvent:this.messages.next(new Fs.Qd(e.msg));break;case ii.SessionEnded:{const t="UserInactivity"===e.msg.reason?"sessionEndedDueToInactivity":e.msg.reason;this.signaling?.endSession(t),this.signaling=void 0;break}case ii.SpeechStreamOpened:this.audioStreamId=e.msg.streamId;break;case ii.SpeechStreamClosed:e.msg.streamId===this.audioStreamId?this.audioStreamId=void 0:r.A.warn("Received SpeechStreamClosed message for unexpected streamId",e.msg.streamId)}}handleChannelMessageError(e){const t=e?.message?.trim()||"An unknown error occurred";e&&pi.includes(e.code)?this.messages.next(new Fs.Uh(e)):this.messages.next(new Fs.Cj(t))}sendWelcomePrompt(){r.A.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 Os.D(this.config.welcomePrompt,this.promptMetadata)))}listenForTabClosure(){window.addEventListener("beforeunload",()=>{r.A.info("Window unload detected, ending session."),this.signaling?.endSession(),this.signaling=void 0})}}class yi{prompt;requestId;constructor(e,t=(0,ai.g)()){this.prompt=e,this.requestId=t}toJSON(){return{action:Ns.A.Speak,data:{requestId:this.requestId,prompt:this.prompt}}}}var vi,Si=n(58);!function(e){e.Open="open",e.Close="close",e.Interrupt="interrupt"}(vi||(vi={}));class bi{action;streamId;metadata;requestId;constructor(e,t,n={},s=(0,ai.g)()){this.action=e,this.streamId=t,this.metadata=n,this.requestId=s}toJSON(){return{action:Ns.A.SpeechStream,data:{requestId:this.requestId,action:this.action,streamId:this.streamId,metadata:this.metadata}}}}class wi{command;enabled;category;verbosity;constructor(e,t,n,s){this.command=e,this.enabled=t,this.category=n,this.verbosity=s}toJSON(){const e={command:this.command,enabled:this.enabled};return void 0!==this.category&&(e.category=this.category),void 0!==this.verbosity&&(e.verbosity=this.verbosity),{action:Ns.A.ExecuteCommand,data:e}}}class Ci{config;session;messageSubscription;constructor(e){this.config=e,r.A.setLevel(e.logLevel??"info")}init(){if(this.session){const e="Cannot initialize: session already active. Call endSession() first.";throw r.A.warn(e),new Error(e)}if(void 0!==this.config.audioUpstreamMode&&"speech-recognition-service"!==(e=this.config.audioUpstreamMode)&&"pixel-streaming"!==e&&"both"!==e){const e=`Invalid audioUpstreamMode: '${String(this.config.audioUpstreamMode)}'. Allowed: 'speech-recognition-service' | 'pixel-streaming' | 'both'.`;throw r.A.error(e),new Error(e)}var e;r.A.info(`Initializing Uneeq with config:', ${JSON.stringify(this.config)}, for UserAgent: ${navigator.userAgent}`),this.session=new fi(this.config),this.session.createSession(),this.messageSubscription=this.session.messages.subscribe(e=>{e.uneeqMessageType===Fs.Yg.SessionEnded&&(r.A.info("Session ended, resetting session state"),this.resetSessionState())})}isSessionActive(){return void 0!==this.session}ensureSessionExists(){return!!this.session?.id||(r.A.warn("Cannot perform action, session has not started."),!1)}chatPrompt(e){e&&""!==e.trim()&&this.ensureSessionExists()&&this.session?.signaling?.dataSend(new Os.D(e,this.session?.promptMetadata))}speak(e){e&&""!==e.trim()&&this.ensureSessionExists()&&this.session?.signaling?.dataSend(new yi(e))}openAudioStream(){const e=this.session;this.ensureSessionExists()&&e?.signaling?.dataSend(new bi(vi.Open,e?.audioStreamId))}closeAudioStream(){const e=this.session;this.ensureSessionExists()&&void 0!==e?.audioStreamId&&e.signaling?.dataSend(new bi(vi.Close,e.audioStreamId))}interruptAudioStream(){const e=this.session;this.ensureSessionExists()&&void 0!==e?.audioStreamId&&e.signaling?.dataSend(new bi(vi.Interrupt,e.audioStreamId))}async speakAudio(e){this.ensureSessionExists()&&await async function(e,t){try{if(void 0===e?.audioStreamId)return void r.A.warn("Audio stream is not open | Call openAudioStream() first");let n;if("string"==typeof t){const e="undefined"!=typeof atob?atob(t):Buffer.from(t,"base64").toString("binary");n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t)}else if(t instanceof Uint8Array)n=t;else{if(!("undefined"!=typeof Blob&&t instanceof Blob))return void r.A.error("speakAudio: Unsupported audio type",t);{const e=await t.arrayBuffer();n=new Uint8Array(e)}}const s=Uint8Array.from([1]),i=Uint8Array.from([e.audioStreamId]),o=new Uint8Array(2+n.length);o.set(s,0),o.set(i,1),o.set(n,2),e.signaling?.dataSendBinary(o)}catch(e){r.A.error("speakAudioSend: Error sending audio",e)}}(this.session,e)}cameraAnchorDistance(e,t){this.ensureSessionExists()&&this.session?.setCameraAnchorDistance(e,t)}cameraAnchorHorizontal(e,t){this.ensureSessionExists()&&this.session?.setCameraAnchorHorizontal(e,t)}changeAvatar(e){e&&""!==e.trim()&&this.ensureSessionExists()&&this.session?.changeAvatar(e)}loadBackground(e){e&&""!==e.trim()&&this.ensureSessionExists()&&this.session?.loadBackground(e)}userStartSpeaking(){this.ensureSessionExists()&&this.session?.userStartSpeaking()}userStopSpeaking(){this.ensureSessionExists()&&this.session?.userStopSpeaking()}triggerAction(e){e&&""!==e.trim()&&this.ensureSessionExists()&&this.session?.triggerAction(e)}resumeVideoPlayback(){this.session?.resumeVideoPlayback()}executeCommand(e,t,n,s){this.ensureSessionExists()&&this.session?.signaling?.dataSend(new wi(e,t,n,s))}endSession(){this.ensureSessionExists()&&(this.releaseMicrophone(),this.session?.signaling?.endSession(),this.resetSessionState())}releaseMicrophone(){try{this.session?.speechRec?.stopRecognition()}catch(e){r.A.warn("endSession: error releasing microphone",r.A.serialiseError(e))}}resetSessionState(){this.messageSubscription?.unsubscribe(),this.messageSubscription=void 0,this.session=void 0}unmuteDigitalHuman(){this.ensureSessionExists()&&(this.session?.signaling?.playAudioElement(),r.A.debug("Unmuted digital human."))}muteDigitalHuman(){this.ensureSessionExists()&&(this.session?.signaling?.pauseAudioElement(),r.A.debug("Muted digital human."))}stopSpeaking(){this.ensureSessionExists()&&this.session?.signaling?.dataSend(new Si.f)}setCustomPromptMetadata(e){this.ensureSessionExists()&&this.session?.updatePromptMetadata(e)}enableMicrophone(e=!0){this.ensureSessionExists()&&this.session?.setEnableMicrophone(e)}pauseSpeechRecognition(){if(!this.ensureSessionExists())return!1;const e=Ks(this.config.audioUpstreamMode);if(!Xs(e))return r.A.warn(`pauseSpeechRecognition called in '${e}' mode — no STT leg to pause; ignoring. Use muteUpstreamMic() to silence the PS mic track.`),!1;const t=this.session?.pauseSpeechRecognition()??!1;return t instanceof Promise||t}resumeSpeechRecognition(){if(!this.ensureSessionExists())return!1;const e=Ks(this.config.audioUpstreamMode);if(!Xs(e))return r.A.warn(`resumeSpeechRecognition called in '${e}' mode — no STT leg to resume; ignoring. Use unmuteUpstreamMic() to re-enable the PS mic track.`),!1;const t=this.session?.resumeSpeechRecognition()??!1;return t instanceof Promise||t}updateSpeechRecognitionConfig(e){return!!this.ensureSessionExists()&&(this.session?.updateSpeechRecognitionConfig(e)??!1)}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,r.A.info(`Setting up WebRtcStats: webRtcStatsEmitMessages: ${this.session.config.webRtcStatsEmitMessages}, webRtcStatsLogMessages: ${this.session.config.webRtcStatsLogMessages}`),t?this.session.signaling?.startAudioStatsMonitor():this.session.signaling?.stopAudioStatsMonitor())}setNetworkIndicatorEnabled(e){this.ensureSessionExists()&&(e?this.session?.signaling?.startNetworkQualityMonitor(e):this.session?.signaling?.stopNetworkQualityMonitor())}}var Mi=n(508);return window.Uneeq=Ci,s})());
|
|
2
2
|
//# sourceMappingURL=index.js.map
|