uneeq-js 3.16.2 → 3.16.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/363.index.js +1 -1
- package/dist/363.index.js.map +1 -1
- package/dist/948.index.js +1 -1
- package/dist/948.index.js.map +1 -1
- package/dist/esm/chunks/chunk-KSGM2NAE.js +1 -0
- package/dist/esm/chunks/chunk-MOT3AKDE.js +2 -0
- package/dist/esm/chunks/chunk-WJYCZSEJ.js +1 -0
- package/dist/esm/chunks/chunk-YEJDFRW6.js +2 -0
- package/dist/esm/chunks/deepgram-flux-stt-6DSS2LPY.js +27 -0
- package/dist/esm/chunks/deepgram-flux-stt-BHYXM2EH.js +27 -0
- package/dist/esm/chunks/deepgram-flux-stt-J6S6IOQO.js +27 -0
- package/dist/esm/chunks/deepgram-flux-stt-RQL6OWQ2.js +27 -0
- package/dist/esm/chunks/deepgram-stt-5MWRG5JL.js +1 -0
- package/dist/esm/chunks/deepgram-stt-LHOR4WN6.js +1 -0
- package/dist/esm/chunks/deepgram-stt-QCVIQMXI.js +1 -0
- package/dist/esm/chunks/google-stt-ICGJZD6H.js +2486 -0
- package/dist/esm/chunks/google-stt-JDMN7CZH.js +2486 -0
- package/dist/esm/chunks/google-stt-UNWDYI25.js +2486 -0
- package/dist/esm/index.js +2 -2
- package/dist/google-stt.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- 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,t,n,s,i={963(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},t.getDescription=function(e){const n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter(e=>0===e.indexOf(n))},t.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},t.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(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.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},t.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"},t.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(" ")}},t.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"},t.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},t.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},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.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},t.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},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){const n=t.matchPrefix(e,"a=mid:")[0];if(n)return n.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,n){return{role:"auto",fingerprints:t.matchPrefix(e+n,"a=fingerprint:").map(t.parseFingerprint)}},t.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},t.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)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.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}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,n){return t.matchPrefix(e+n,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,n){const s=t.matchPrefix(e+n,"a=ice-ufrag:")[0],i=t.matchPrefix(e+n,"a=ice-pwd:")[0];return s&&i?{usernameFragment:s.substring(12),password:i.substring(10)}:null},t.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},t.parseRtpParameters=function(e){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=t.splitLines(e)[0].split(" ");n.profile=s[2];for(let i=3;i<s.length;i++){const r=s[i],o=t.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(o){const s=t.parseRtpMap(o),i=t.matchPrefix(e,"a=fmtp:"+r+" ");switch(s.parameters=i.length?t.parseFmtp(i[0]):{},s.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+r+" ").map(t.parseRtcpFb),n.codecs.push(s),s.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(s.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach(e=>{n.headerExtensions.push(t.parseExtmap(e))});const i=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach(e=>{i.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),n},t.writeRtpDescription=function(e,n){let s="";s+="m="+e+" ",s+=n.codecs.length>0?"9":"0",s+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",s+=n.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",n.codecs.forEach(e=>{s+=t.writeRtpMap(e),s+=t.writeFmtp(e),s+=t.writeRtcpFb(e)});let i=0;return n.codecs.forEach(e=>{e.maxptime>i&&(i=e.maxptime)}),i>0&&(s+="a=maxptime:"+i+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach(e=>{s+=t.writeExtmap(e)}),s},t.parseRtpEncodingParameters=function(e){const n=[],s=t.parseRtpParameters(e),i=-1!==s.fecMechanisms.indexOf("RED"),r=-1!==s.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=o.length>0&&o[0].ssrc;let l;const c=t.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 t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&l&&(t.rtx={ssrc:l}),n.push(t),i&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:r?"red+ulpfec":"red"},n.push(t))}}),0===n.length&&a&&n.push({ssrc:a});let d=t.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,n.forEach(e=>{e.maxBitrate=d})),n},t.parseRtcpParameters=function(e){const n={},s=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];s&&(n.cname=s.value,n.ssrc=s.ssrc);const i=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=i.length>0,n.compound=0===i.length;const r=t.matchPrefix(e,"a=rtcp-mux");return n.mux=r.length>0,n},t.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},t.parseMsid=function(e){let n;const s=t.matchPrefix(e,"a=msid:");if(1===s.length)return n=s[0].substring(7).split(" "),{stream:n[0],track:n[1]};const i=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return i.length>0?(n=i[0].value.split(" "),{stream:n[0],track:n[1]}):void 0},t.parseSctpDescription=function(e){const n=t.parseMLine(e),s=t.matchPrefix(e,"a=max-message-size:");let i;s.length>0&&(i=parseInt(s[0].substring(19),10)),isNaN(i)&&(i=65536);const r=t.matchPrefix(e,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:n.fmt,maxMessageSize:i};const o=t.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}}},t.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("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,s){let i;const r=void 0!==n?n:2;return i=e||t.generateSessionId(),"v=0\r\no="+(s||"thisisadapterortc")+" "+i+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const s=t.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 n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){const n=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||"="!==n[e].charAt(1))return!1;return!0},e.exports=t},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:()=>m,JP:()=>x,Ln:()=>P,M8:()=>C,MA:()=>_,MM:()=>U,N8:()=>B,O$:()=>g,Qd:()=>S,Tu:()=>T,Uh:()=>v,Ux:()=>o,WQ:()=>D,WY:()=>M,XC:()=>w,Yg:()=>s,_4:()=>l,aY:()=>b,bS:()=>k,co:()=>i,fI:()=>L,fP:()=>y,fh:()=>r,im:()=>c,j_:()=>V,kS:()=>h,nD:()=>R,qo:()=>I,qw:()=>F,sF:()=>O,ss:()=>E,tc:()=>u,wf:()=>p,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.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 p{sessionId;uneeqMessageType=s.SessionLive;constructor(e){this.sessionId=e}}class m{position;uneeqMessageType=s.WaitingInQueue;constructor(e){this.position=e}}class g{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 T{uneeqMessageType=s.DigitalHumanMuted}class M{enabled;uneeqMessageType=s.EnableMicrophoneUpdated;constructor(e){this.enabled=e}}class E{chatMetadata;uneeqMessageType=s.CustomMetadataUpdated;constructor(e){this.chatMetadata=e}}class k{promptRequest;uneeqMessageType=s.PromptRequest;constructor(e){this.promptRequest=e}}class R{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 O{uneeqMessageType=s.SoftSwitchStarting}class D{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 _{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}}}}}},r={};function o(e){var t=r[e];if(void 0!==t)return t.exports;var n=r[e]={exports:{}};return i[e].call(n.exports,n,n.exports,o),n.exports}o.m=i,t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,o.t=function(n,s){if(1&s&&(n=this(n)),8&s)return n;if("object"==typeof n&&n){if(4&s&&n.__esModule)return n;if(16&s&&"function"==typeof n.then)return n}var i=Object.create(null);o.r(i);var r={};e=e||[null,t({}),t([]),t(t)];for(var a=2&s&&n;("object"==typeof a||"function"==typeof a)&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach(e=>r[e]=()=>n[e]);return r.default=()=>n,o.d(i,r),i},o.d=(e,t)=>{for(var n in t)o.o(t,n)&&!o.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o.f={},o.e=e=>Promise.all(Object.keys(o.f).reduce((t,n)=>(o.f[n](e,t),t),[])),o.u=e=>e+".index.js",o.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},s="Uneeq:",o.l=(e,t,i,r)=>{if(n[e])n[e].push(t);else{var a,l;if(void 0!==i)for(var c=document.getElementsByTagName("script"),d=0;d<c.length;d++){var h=c[d];if(h.getAttribute("src")==e||h.getAttribute("data-webpack")==s+i){a=h;break}}a||(l=!0,(a=document.createElement("script")).charset="utf-8",o.nc&&a.setAttribute("nonce",o.nc),a.setAttribute("data-webpack",s+i),a.src=e),n[e]=[t];var u=(t,s)=>{a.onerror=a.onload=null,clearTimeout(p);var i=n[e];if(delete n[e],a.parentNode&&a.parentNode.removeChild(a),i&&i.forEach(e=>e(s)),t)return t(s)},p=setTimeout(u.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=u.bind(null,a.onerror),a.onload=u.bind(null,a.onload),l&&document.head.appendChild(a)}},o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;o.g.importScripts&&(e=o.g.location+"");var t=o.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");if(n.length)for(var s=n.length-1;s>-1&&(!e||!/^http(s?):/.test(e));)e=n[s--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),o.p=e})(),(()=>{var e={792:0};o.f.j=(t,n)=>{var s=o.o(e,t)?e[t]:void 0;if(0!==s)if(s)n.push(s[2]);else{var i=new Promise((n,i)=>s=e[t]=[n,i]);n.push(s[2]=i);var r=o.p+o.u(t),a=new Error;o.l(r,n=>{if(o.o(e,t)&&(0!==(s=e[t])&&(e[t]=void 0),s)){var i=n&&("load"===n.type?"missing":n.type),r=n&&n.target&&n.target.src;a.message="Loading chunk "+t+" failed.\n("+i+": "+r+")",a.name="ChunkLoadError",a.type=i,a.request=r,s[1](a)}},"chunk-"+t,t)}};var t=(t,n)=>{var s,i,[r,a,l]=n,c=0;if(r.some(t=>0!==e[t])){for(s in a)o.o(a,s)&&(o.m[s]=a[s]);l&&l(o)}for(t&&t(n);c<r.length;c++)i=r[c],o.o(e,i)&&e[i]&&e[i][0](),e[i]=0},n=Object("undefined"!=typeof self?self:this).webpackChunkUneeq=Object("undefined"!=typeof self?self:this).webpackChunkUneeq||[];n.forEach(t.bind(null,0)),n.push=t.bind(null,n.push.bind(n))})();var a={};o.r(a),o.d(a,{AvatarAnswerMessage:()=>_s.fh,AvatarInterruptedMessage:()=>_s.tc,AvatarStartedSpeakingMessage:()=>_s.yr,AvatarStoppedSpeakingMessage:()=>_s.kS,CameraAnchorDistance:()=>oi,CameraAnchorHorizontal:()=>ai,CustomMetadataUpdated:()=>_s.ss,CustomerConcurrencyLimitReachedMessage:()=>_s.MM,DeviceErrorMessage:()=>_s.co,DigitalHumanMuted:()=>_s.Tu,DigitalHumanPlayedInMutedModeSuccess:()=>_s.XC,DigitalHumanUnmuted:()=>_s.M8,EnableMicrophoneUpdatedMessage:()=>_s.WY,LogLevel:()=>Mi.$,NetworkIndicatorPopupTrigger:()=>Ks,NetworkIndicatorPosition:()=>Qs,NetworkIndicatorVisibility:()=>qs,NetworkQualityLevel:()=>zs,NetworkQualityMessage:()=>_s.N8,PromptRequestMessage:()=>_s.bS,PromptResultMessage:()=>_s.nD,RendererErrorMessage:()=>_s.j_,SceneReadyMessage:()=>_s.Ln,SessionBackendErrorMessage:()=>_s.Uh,SessionConnectingMessage:()=>_s.qo,SessionDisconnectedMessage:()=>_s.JP,SessionEndedMessage:()=>_s.aY,SessionErrorMessage:()=>_s.Cj,SessionLiveMessage:()=>_s.wf,SessionReconnectingFinishedMessage:()=>_s.xQ,SessionReconnectingMessage:()=>_s.fI,SoftSwitchStartingMessage:()=>_s.sF,SoftSwitchStoppingMessage:()=>_s.WQ,SpeechEventMessage:()=>_s.Qd,SpeechRecognitionProvider:()=>Gs,SpeechRecognitionTransientErrorMessage:()=>_s.fP,SpeechTranscriptionMessage:()=>_s.Ux,UNEEQ_JS_SDK_VERSION:()=>Vs,Uneeq:()=>Ti,UneeqMessageType:()=>_s.Yg,UserStartedSpeakingMessage:()=>_s._4,UserStoppedSpeakingMessage:()=>_s.im,VadInterruptionAllowedMessage:()=>_s.E1,VideoAutoplayBlockedMessage:()=>_s.MA,VideoLayoutConfiguringMessage:()=>_s.qw,WaitingInQueueMessage:()=>_s.F8,WebRtcConnectedMessage:()=>_s.Cl,WebRtcStatsMessage:()=>_s.O$,resolveAudioUpstreamMode:()=>Zs});var l=o(514),c=function(e,t){return c=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])},c(e,t)};function d(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}c(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function h(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 u(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 p(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 m(e){return"function"==typeof e}function g(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,"function"==typeof SuppressedError&&SuppressedError;var f=g(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 y(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var v=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=h(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 l=this.initialTeardown;if(m(l))try{l()}catch(e){i=e instanceof f?e.errors:[e]}var c=this._finalizers;if(c){this._finalizers=null;try{for(var d=h(c),g=d.next();!g.done;g=d.next()){var y=g.value;try{w(y)}catch(e){i=null!=i?i:[],e instanceof f?i=p(p([],u(i)),u(e.errors)):i.push(e)}}}catch(e){n={error:e}}finally{try{g&&!g.done&&(s=d.return)&&s.call(d)}finally{if(n)throw n.error}}}if(i)throw new f(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)w(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)&&y(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&y(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}(),S=v.EMPTY;function b(e){return e instanceof v||e&&"closed"in e&&m(e.remove)&&m(e.add)&&m(e.unsubscribe)}function w(e){m(e)?e():e.unsubscribe()}var C=null,T=null,M=void 0,E=!1,k=!1,R={setTimeout:function(e,t){for(var n=[],s=2;s<arguments.length;s++)n[s-2]=arguments[s];var i=R.delegate;return(null==i?void 0:i.setTimeout)?i.setTimeout.apply(i,p([e,t],u(n))):setTimeout.apply(void 0,p([e,t],u(n)))},clearTimeout:function(e){var t=R.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function P(){}var I=x("C",void 0,void 0);function x(e,t,n){return{kind:e,value:t,error:n}}var L=null;function A(e){if(E){var t=!L;if(t&&(L={errorThrown:!1,error:null}),e(),t){var n=L,s=n.errorThrown,i=n.error;if(L=null,s)throw i}}else e()}var O=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,b(t)&&t.add(n)):n.destination=_,n}return d(t,e),t.create=function(e,t,n){return new U(e,t,n)},t.prototype.next=function(e){this.isStopped?V(function(e){return x("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?V(x("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?V(I,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}(v),D=Function.prototype.bind;function F(e,t){return D.call(e,t)}var N=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){B(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){B(e)}else B(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){B(e)}},e}(),U=function(e){function t(t,n,s){var i,r,o=e.call(this)||this;return m(t)||!t?i={next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=s?s:void 0}:o&&k?((r=Object.create(t)).unsubscribe=function(){return o.unsubscribe()},i={next:t.next&&F(t.next,r),error:t.error&&F(t.error,r),complete:t.complete&&F(t.complete,r)}):i=t,o.destination=new N(i),o}return d(t,e),t}(O);function B(e){var t;E?(t=e,E&&L&&(L.errorThrown=!0,L.error=t)):function(e){R.setTimeout(function(){if(!C)throw e;C(e)})}(e)}function V(e,t){var n=T;n&&R.setTimeout(function(){return n(e,t)})}var _={closed:!0,next:P,error:function(e){throw e},complete:P},W="function"==typeof Symbol&&Symbol.observable||"@@observable";function $(e){return e}var H=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 O||function(e){return e&&m(e.next)&&m(e.error)&&m(e.complete)}(s)&&b(s)?e:new U(e,t,n);return A(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=j(t))(function(t,s){var i=new U({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[W]=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?$: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=j(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 j(e){var t;return null!==(t=null!=e?e:M)&&void 0!==t?t:Promise}var z,q=g(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Q=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 d(t,e),t.prototype.lift=function(e){var t=new K(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new q},t.prototype.next=function(e){var t=this;A(function(){var n,s;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var i=h(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;A(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;A(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?S:(this.currentObservers=null,r.push(e),new v(function(){t.currentObservers=null,y(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 H;return e.source=this,e},t.create=function(e,t){return new K(e,t)},t}(H),K=function(e){function t(t,n){var s=e.call(this)||this;return s.destination=t,s.source=n,s}return d(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:S},t}(Q),G={now:function(){return(G.delegate||Date).now()},delegate:void 0},X=function(e){function t(t,n,s){void 0===t&&(t=1/0),void 0===n&&(n=1/0),void 0===s&&(s=G);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 d(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}(Q);!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"}(z||(z={}));class J{constructor(){this.logLevel=z.Debug,this.includeStack=!0}}let Y=new class{InitLogging(e,t){this.ValidateContext(),this.context.logLevel=e,this.context.includeStack=t}Debug(e){this.ValidateContext(),this.context.logLevel>=z.Debug&&this.CommonLog("Debug",e)}Info(e){this.ValidateContext(),this.context.logLevel>=z.Info&&this.CommonLog("Info",e)}Warning(e){this.ValidateContext(),this.context.logLevel>=z.Warning&&this.CommonLog("Warning",e)}Error(e){this.ValidateContext(),this.context.logLevel>=z.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 J,window.loggerContext=this.context):this.context=new J)}};class Z{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 ee extends Z{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 te extends Z{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 ne extends Z{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 se extends Z{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:Y.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 ie extends Event{constructor(e){super("afkWarningActivate"),this.data=e}}class re extends Event{constructor(e){super("afkWarningUpdate"),this.data=e}}class oe extends Event{constructor(){super("afkWarningDeactivate")}}class ae extends Event{constructor(){super("afkTimedOut")}}class le extends Event{constructor(e){super("videoEncoderAvgQP"),this.data=e}}class ce extends Event{constructor(){super("webRtcSdp")}}class de extends Event{constructor(e){super("webRtcSdpAnswer"),this.data=e}}class he extends Event{constructor(e){super("webRtcSdpOffer"),this.data=e}}class ue extends Event{constructor(){super("webRtcAutoConnect")}}class pe extends Event{constructor(){super("webRtcConnecting")}}class me extends Event{constructor(){super("webRtcConnected")}}class ge extends Event{constructor(){super("webRtcFailed")}}class fe extends Event{constructor(e){super("webRtcDisconnected"),this.data=e}}class ye extends Event{constructor(e){super("dataChannelOpen"),this.data=e}}class ve extends Event{constructor(e){super("dataChannelClose"),this.data=e}}class Se extends Event{constructor(e){super("dataChannelError"),this.data=e}}class be extends Event{constructor(){super("videoInitialized")}}class we extends Event{constructor(){super("streamLoading")}}class Ce extends Event{constructor(){super("streamConnect")}}class Te extends Event{constructor(){super("streamDisconnect")}}class Me extends Event{constructor(){super("streamReconnect")}}class Ee extends Event{constructor(e){super("playStreamError"),this.data=e}}class ke extends Event{constructor(){super("playStream")}}class Re extends Event{constructor(e){super("playStreamRejected"),this.data=e}}class Pe extends Event{constructor(e){super("loadFreezeFrame"),this.data=e}}class Ie extends Event{constructor(){super("hideFreezeFrame")}}class xe extends Event{constructor(e){super("statsReceived"),this.data=e}}class Le extends Event{constructor(e){super("streamerListMessage"),this.data=e}}class Ae extends Event{constructor(e){super("StreamerIDChangedMessage"),this.data=e}}class Oe extends Event{constructor(e){super("latencyTestResult"),this.data=e}}class De extends Event{constructor(e){super("latencyCalculated"),this.data=e}}class Fe extends Event{constructor(e){super("showOnScreenKeyboard"),this.data=e}}class Ne extends Event{constructor(e){super("dataChannelLatencyTestResponse"),this.data=e}}class Ue extends Event{constructor(e){super("dataChannelLatencyTestResult"),this.data=e}}class Be extends Event{constructor(e){super("subscribeFailed"),this.data=e}}class Ve extends Event{constructor(e){super("initialSettings"),this.data=e}}class _e extends Event{constructor(e){super("settingsChanged"),this.data=e}}Event,Event;class We extends Event{constructor(e){super("xrFrame"),this.data=e}}class $e extends Event{constructor(e){super("playerCount"),this.data=e}}class He extends Event{constructor(){super("webRtcTCPRelayDetected")}}class je extends EventTarget{dispatchEvent(e){return super.dispatchEvent(e)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}}class ze{static getSupportedVideoCodecs(){const e=[];if(!RTCRtpReceiver.getCapabilities)return Y.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 qe{}qe.AutoConnect="AutoConnect",qe.AutoPlayVideo="AutoPlayVideo",qe.AFKDetection="TimeoutIfIdle",qe.HoveringMouseMode="HoveringMouse",qe.ForceMonoAudio="ForceMonoAudio",qe.ForceTURN="ForceTURN",qe.FakeMouseWithTouches="FakeMouseWithTouches",qe.IsQualityController="ControlsQuality",qe.MatchViewportResolution="MatchViewportRes",qe.StartVideoMuted="StartVideoMuted",qe.SuppressBrowserKeys="SuppressBrowserKeys",qe.UseMic="UseMic",qe.UseModalForTextInput="UseModalForTextInput",qe.UseCamera="UseCamera",qe.KeyboardInput="KeyboardInput",qe.MouseInput="MouseInput",qe.TouchInput="TouchInput",qe.GamepadInput="GamepadInput",qe.XRControllerInput="XRControllerInput",qe.WaitForStreamer="WaitForStreamer",qe.HideUI="HideUI",qe.EnableCaptureTimeExt="EnableCaptureTimeExt",qe.BrowserSendOffer="BrowserSendOffer",qe.LatencyCSV="LatencyCSV";const Qe=e=>Object.getOwnPropertyNames(qe).some(t=>qe[t]===e);class Ke{}Ke.AFKTimeoutSecs="AFKTimeout",Ke.AFKCountdownSecs="AFKCountdown",Ke.MinQP="MinQP",Ke.MaxQP="MaxQP",Ke.MinQuality="MinQuality",Ke.MaxQuality="MaxQuality",Ke.CompatQualityMin="CompatQualityMin",Ke.CompatQualityMax="CompatQualityMax",Ke.WebRTCFPS="WebRTCFPS",Ke.WebRTCMinBitrate="WebRTCMinBitrate",Ke.WebRTCMaxBitrate="WebRTCMaxBitrate",Ke.MaxReconnectAttempts="MaxReconnectAttempts",Ke.StreamerAutoJoinInterval="StreamerAutoJoinInterval",Ke.KeepaliveDelay="KeepaliveDelay";const Ge=e=>Object.getOwnPropertyNames(Ke).some(t=>Ke[t]===e);class Xe{}Xe.SignallingServerUrl="ss";const Je=e=>Object.getOwnPropertyNames(Xe).some(t=>Xe[t]===e);class Ye{}Ye.PreferredCodec="PreferredCodec",Ye.StreamerId="StreamerId",Ye.PreferredQuality="PreferredQuality";const Ze=e=>Object.getOwnPropertyNames(Ye).some(t=>Ye[t]===e);class et{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(Xe.SignallingServerUrl,new ne(Xe.SignallingServerUrl,"Signalling url","Url of the signalling server",t&&Object.prototype.hasOwnProperty.call(t,Xe.SignallingServerUrl)?t[Xe.SignallingServerUrl]:("https:"===location.protocol?"wss://":"ws://")+window.location.hostname+("80"===window.location.port||""===window.location.port?"":`:${window.location.port}`),e)),this.optionParameters.set(Ye.StreamerId,new se(Ye.StreamerId,"Streamer ID","The ID of the streamer to stream.",t&&Object.prototype.hasOwnProperty.call(t,Ye.StreamerId)?t[Ye.StreamerId]:"",t&&Object.prototype.hasOwnProperty.call(t,Ye.StreamerId)?[t[Ye.StreamerId]]:void 0,e));const n=function(e){const t=ze.getSupportedVideoCodecs();if(t.includes(e))return e;for(const n of t)if(n.startsWith(e))return n;return e};this.optionParameters.set(Ye.PreferredCodec,new se(Ye.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation",t&&Object.prototype.hasOwnProperty.call(t,Ye.PreferredCodec)?n(t[Ye.PreferredCodec]):function(){const e=ze.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 Y.Error("Could not find any reasonable video codec to assign as a default."),""}(),ze.getSupportedVideoCodecs(),e,n)),this.optionParameters.set(Ye.PreferredQuality,new se(Ye.PreferredQuality,"Preferred Quality","The preferred quality of the stream (only applicable when using the SFU)",t&&Object.prototype.hasOwnProperty.call(t,Ye.PreferredQuality)?t[Ye.PreferredQuality]:"Default",["Default"],e)),this.flags.set(qe.AutoConnect,new ee(qe.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,qe.AutoConnect))&&t[qe.AutoConnect],e)),this.flags.set(qe.AutoPlayVideo,new ee(qe.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,qe.AutoPlayVideo)||t[qe.AutoPlayVideo],e)),this.flags.set(qe.UseMic,new ee(qe.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.UseMic))&&t[qe.UseMic],e)),this.flags.set(qe.UseModalForTextInput,new ee(qe.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,qe.UseModalForTextInput)||t[qe.UseModalForTextInput],e)),this.flags.set(qe.UseCamera,new ee(qe.UseCamera,"Use webcam","Make browser request webcam access and open a input video track.",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.UseCamera))&&t[qe.UseCamera],e)),this.flags.set(qe.StartVideoMuted,new ee(qe.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.StartVideoMuted))&&t[qe.StartVideoMuted],e)),this.flags.set(qe.SuppressBrowserKeys,new ee(qe.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,qe.SuppressBrowserKeys)||t[qe.SuppressBrowserKeys],e)),this.flags.set(qe.IsQualityController,new ee(qe.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!t||!Object.prototype.hasOwnProperty.call(t,qe.IsQualityController)||t[qe.IsQualityController],e)),this.flags.set(qe.ForceMonoAudio,new ee(qe.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.ForceMonoAudio))&&t[qe.ForceMonoAudio],e)),this.flags.set(qe.ForceTURN,new ee(qe.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.ForceTURN))&&t[qe.ForceTURN],e)),this.flags.set(qe.AFKDetection,new ee(qe.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.AFKDetection))&&t[qe.AFKDetection],e)),this.flags.set(qe.MatchViewportResolution,new ee(qe.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,qe.MatchViewportResolution))&&t[qe.MatchViewportResolution],e)),this.flags.set(qe.HoveringMouseMode,new ee(qe.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,qe.HoveringMouseMode))&&t[qe.HoveringMouseMode],e,(e,t)=>{t.label=`Control Scheme: ${e?"Hovering":"Locked"} Mouse`})),this.flags.set(qe.FakeMouseWithTouches,new ee(qe.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,qe.FakeMouseWithTouches))&&t[qe.FakeMouseWithTouches],e)),this.flags.set(qe.KeyboardInput,new ee(qe.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,qe.KeyboardInput)||t[qe.KeyboardInput],e)),this.flags.set(qe.MouseInput,new ee(qe.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,qe.MouseInput)||t[qe.MouseInput],e)),this.flags.set(qe.TouchInput,new ee(qe.TouchInput,"Touch input","If enabled, send touch events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,qe.TouchInput)||t[qe.TouchInput],e)),this.flags.set(qe.GamepadInput,new ee(qe.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,qe.GamepadInput)||t[qe.GamepadInput],e)),this.flags.set(qe.XRControllerInput,new ee(qe.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,qe.XRControllerInput)||t[qe.XRControllerInput],e)),this.flags.set(qe.WaitForStreamer,new ee(qe.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!t||!Object.prototype.hasOwnProperty.call(t,qe.WaitForStreamer)||t[qe.WaitForStreamer],e)),this.flags.set(qe.HideUI,new ee(qe.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.HideUI))&&t[qe.HideUI],e)),this.flags.set(qe.EnableCaptureTimeExt,new ee(qe.EnableCaptureTimeExt,"Enable abs-capture-time","Enables the abs-capture-time RTP header extension",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.EnableCaptureTimeExt))&&t[qe.EnableCaptureTimeExt],e)),this.flags.set(qe.BrowserSendOffer,new ee(qe.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,qe.BrowserSendOffer))&&t[qe.BrowserSendOffer],e)),this.flags.set(qe.LatencyCSV,new ee(qe.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,qe.LatencyCSV))&&t[qe.LatencyCSV],e)),this.numericParameters.set(Ke.AFKTimeoutSecs,new te(Ke.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,Ke.AFKTimeoutSecs)?t[Ke.AFKTimeoutSecs]:120,e)),this.numericParameters.set(Ke.AFKCountdownSecs,new te(Ke.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(Ke.MaxReconnectAttempts,new te(Ke.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,t&&Object.prototype.hasOwnProperty.call(t,Ke.MaxReconnectAttempts)?t[Ke.MaxReconnectAttempts]:3,e)),this.numericParameters.set(Ke.MinQP,new te(Ke.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,Ke.MinQP)?t[Ke.MinQP]:0,e)),this.numericParameters.set(Ke.MaxQP,new te(Ke.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,Ke.MaxQP)?t[Ke.MaxQP]:51,e)),this.numericParameters.set(Ke.MinQuality,new te(Ke.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,Ke.MinQuality)?t[Ke.MinQuality]:0,e)),this.numericParameters.set(Ke.MaxQuality,new te(Ke.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,Ke.MaxQuality)?t[Ke.MaxQuality]:100,e)),this.numericParameters.set(Ke.CompatQualityMin,new te(Ke.CompatQualityMin,"Min Quality","The lower bound for encoding quality. 0 = Worst, 100 = Best.",0,100,t&&Object.prototype.hasOwnProperty.call(t,Ke.CompatQualityMin)?t[Ke.CompatQualityMin]:0,e)),this.numericParameters.set(Ke.CompatQualityMax,new te(Ke.CompatQualityMax,"Max Quality","The upper bound for encoding quality. 0 = Worst, 100 = Best.",0,100,t&&Object.prototype.hasOwnProperty.call(t,Ke.CompatQualityMax)?t[Ke.CompatQualityMax]:100,e)),this.numericParameters.set(Ke.WebRTCFPS,new te(Ke.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,t&&Object.prototype.hasOwnProperty.call(t,Ke.WebRTCFPS)?t[Ke.WebRTCFPS]:60,e)),this.numericParameters.set(Ke.WebRTCMinBitrate,new te(Ke.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,t&&Object.prototype.hasOwnProperty.call(t,Ke.WebRTCMinBitrate)?t[Ke.WebRTCMinBitrate]:0,e)),this.numericParameters.set(Ke.WebRTCMaxBitrate,new te(Ke.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,t&&Object.prototype.hasOwnProperty.call(t,Ke.WebRTCMaxBitrate)?t[Ke.WebRTCMaxBitrate]:0,e)),this.numericParameters.set(Ke.StreamerAutoJoinInterval,new te(Ke.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,t&&Object.prototype.hasOwnProperty.call(t,Ke.StreamerAutoJoinInterval)?t[Ke.StreamerAutoJoinInterval]:3e3,e)),this.numericParameters.set(Ke.KeepaliveDelay,new te(Ke.KeepaliveDelay,"Connection Keepalive delay","Delay between keepalive pings to the signalling server.",0,9e5,t&&Object.prototype.hasOwnProperty.call(t,Ke.KeepaliveDelay)?t[Ke.KeepaliveDelay]:3e4,e))}_addOnNumericSettingChangedListener(e,t){this.numericParameters.has(e)&&this.numericParameters.get(e).addOnChangedListener(t)}_addOnOptionSettingChangedListener(e,t){this.optionParameters.has(e)&&this.optionParameters.get(e).addOnChangedListener(t)}getNumericSettingValue(e){if(this.numericParameters.has(e))return this.numericParameters.get(e).number;throw new Error(`There is no numeric setting with the id of ${e}`)}getTextSettingValue(e){if(this.textParameters.has(e))return this.textParameters.get(e).value;throw new Error(`There is no numeric setting with the id of ${e}`)}setNumericSetting(e,t){if(!this.numericParameters.has(e))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:Y.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:Y.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:Y.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 Y.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:Y.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))Qe(t)?this.setFlagEnabled(t,e[t]):Ge(t)?this.setNumericSetting(t,e[t]):Je(t)?this.setTextSetting(t,e[t]):Ze(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 _e({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 _e({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 _e({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 _e({id:n.id,type:"option",value:t,target:n})))}}}var tt,nt,st;!function(e){e[e.LockedMouse=0]="LockedMouse",e[e.HoveringMouse=1]="HoveringMouse"}(tt||(tt={}));class it{constructor(e){this._args=[],this._callback=e}handleEvent(e){this._callback(...this._args),this._args=[]}setArgs(...e){this._args=e}}class rt 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 it(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 it((...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 ot extends rt{constructor(e){super(),this.WS_OPEN_STATE=1,this.protocols=e}sendMessage(e){this.webSocket&&this.webSocket.send(e)}connect(e){Y.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 Y.Error(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=>{Y.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(){Y.Info("Connected to the signalling server via WebSocket"),this.emit("open")}handleOnError(){this.emit("error")}handleOnClose(e){Y.Info("Disconnected to the signalling server via WebSocket: "+JSON.stringify(e.code)+" - "+e.reason),this.emit("close",e)}}class at extends rt{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);Y.Debug("Protocol received => \n"+JSON.stringify(e,void 0,4)),n=e}catch(e){return void(e instanceof Error?Y.Error(`Error parsing message string ${t}.\n${e.message}`):Y.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),Y.Debug("Protocol sent => \n"+JSON.stringify(e,void 0,4))}}function lt(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])}(nt||(nt={})),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"}(st||(st={}));const ct=Symbol.for("protobuf-ts/message-type");function dt(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 ht,ut,pt;function mt(e){var t,n,s,i;return e.localName=null!==(t=e.localName)&&void 0!==t?t:dt(e.name),e.jsonName=null!==(n=e.jsonName)&&void 0!==n?n:dt(e.name),e.repeat=null!==(s=e.repeat)&&void 0!==s?s:pt.NO,e.opt=null!==(i=e.opt)&&void 0!==i?i:!e.repeat&&!e.oneof&&"message"==e.kind,e}function gt(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"}(ht||(ht={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING",e[e.NUMBER=2]="NUMBER"}(ut||(ut={})),function(e){e[e.NO=0]="NO",e[e.PACKED=1]="PACKED",e[e.UNPACKED=2]="UNPACKED"}(pt||(pt={}));class ft{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(!gt(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,ht.INT32,s):this.scalar(e,ht.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),ht.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 ht.UINT64:case ht.FIXED64:case ht.INT64:case ht.SFIXED64:case ht.SINT64:switch(n){case ut.BIGINT:return"bigint"==s;case ut.NUMBER:return"number"==s&&!isNaN(e);default:return"string"==s}case ht.BOOL:return"boolean"==s;case ht.STRING:return"string"==s;case ht.BYTES:return e instanceof Uint8Array;case ht.DOUBLE:case ht.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 ht.INT32:case ht.FIXED32:case ht.SFIXED32:case ht.SINT32:case ht.UINT32:return this.scalars(s.slice(0,n).map(e=>parseInt(e)),t,n);case ht.BOOL:return this.scalars(s.slice(0,n).map(e=>"true"==e||"false"!=e&&e),t,n);default:return this.scalars(s,t,n,ut.STRING)}}}function yt(e){let t=typeof e;if("object"==t){if(Array.isArray(e))return"array";if(null===e)return"null"}return t}function vt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let St="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),bt=[];for(let e=0;e<St.length;e++)bt[St[e].charCodeAt(0)]=e;function wt(){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 Ct(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)}}bt["-".charCodeAt(0)]=St.indexOf("+"),bt["_".charCodeAt(0)]=St.indexOf("/");const Tt=4294967296;function Mt(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>=Tt&&(i+=s/Tt|0,s%=Tt)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),[t,s,i]}function Et(e,t){if(t>>>0<=2097151)return""+(Tt*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 kt(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 Rt(){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 Pt;function It(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;Pt=t?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:e}:void 0}();const xt=/^-?[0-9]+$/,Lt=4294967296,At=2147483648;class Ot{constructor(e,t){this.lo=0|e,this.hi=0|t}isZero(){return 0==this.lo&&0==this.hi}toNumber(){let e=this.hi*Lt+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class Dt extends Ot{static from(e){if(Pt)switch(typeof e){case"string":if("0"==e)return this.ZERO;if(""==e)throw new Error("string is no integer");e=Pt.C(e);case"number":if(0===e)return this.ZERO;e=Pt.C(e);case"bigint":if(!e)return this.ZERO;if(e<Pt.UMIN)throw new Error("signed value for ulong");if(e>Pt.UMAX)throw new Error("ulong too large");return Pt.V.setBigUint64(0,e,!0),new Dt(Pt.V.getInt32(0,!0),Pt.V.getInt32(4,!0))}else switch(typeof e){case"string":if("0"==e)return this.ZERO;if(e=e.trim(),!xt.test(e))throw new Error("string is no integer");let[t,n,s]=Mt(e);if(t)throw new Error("signed value for ulong");return new Dt(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 Dt(e,e/Lt)}throw new Error("unknown value "+typeof e)}toString(){return Pt?this.toBigInt().toString():Et(this.lo,this.hi)}toBigInt(){return It(Pt),Pt.V.setInt32(0,this.lo,!0),Pt.V.setInt32(4,this.hi,!0),Pt.V.getBigUint64(0,!0)}}Dt.ZERO=new Dt(0,0);class Ft extends Ot{static from(e){if(Pt)switch(typeof e){case"string":if("0"==e)return this.ZERO;if(""==e)throw new Error("string is no integer");e=Pt.C(e);case"number":if(0===e)return this.ZERO;e=Pt.C(e);case"bigint":if(!e)return this.ZERO;if(e<Pt.MIN)throw new Error("signed long too small");if(e>Pt.MAX)throw new Error("signed long too large");return Pt.V.setBigInt64(0,e,!0),new Ft(Pt.V.getInt32(0,!0),Pt.V.getInt32(4,!0))}else switch(typeof e){case"string":if("0"==e)return this.ZERO;if(e=e.trim(),!xt.test(e))throw new Error("string is no integer");let[t,n,s]=Mt(e);if(t){if(s>At||s==At&&0!=n)throw new Error("signed long too small")}else if(s>=At)throw new Error("signed long too large");let i=new Ft(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 Ft(e,e/Lt):new Ft(-e,-e/Lt).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return 0!==(this.hi&At)}negate(){let e=~this.hi,t=this.lo;return t?t=1+~t:e+=1,new Ft(t,e)}toString(){if(Pt)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+Et(e.lo,e.hi)}return Et(this.lo,this.hi)}toBigInt(){return It(Pt),Pt.V.setInt32(0,this.lo,!0),Pt.V.setInt32(4,this.hi,!0),Pt.V.getBigInt64(0,!0)}}function Nt(e,t){if(!e)throw new Error(t)}function Ut(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 Bt(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 Vt(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 _t(e,t){switch(t){case ut.BIGINT:return e.toBigInt();case ut.NUMBER:return e.toNumber();default:return e.toString()}}Ft.ZERO=new Ft(0,0);class Wt{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=yt(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(vt(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==ht.BOOL&&(o="true"==o||"false"!=o&&o),o=this.scalar(o,e.K,ut.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]&&Nt(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 Nt(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)&&(Nt("number"==typeof r,`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} has no value for "${t}".`),r)}Nt(!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 ht.DOUBLE:case ht.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==ht.FLOAT&&Vt(s),s;case ht.INT32:case ht.FIXED32:case ht.SFIXED32:case ht.SINT32:case ht.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==ht.UINT32?Bt(r):Ut(r),r;case ht.INT64:case ht.SFIXED64:case ht.SINT64:if(null===e)return _t(Ft.ZERO,n);if("number"!=typeof e&&"string"!=typeof e)break;return _t(Ft.from(e),n);case ht.FIXED64:case ht.UINT64:if(null===e)return _t(Dt.ZERO,n);if("number"!=typeof e&&"string"!=typeof e)break;return _t(Dt.from(e),n);case ht.BOOL:if(null===e)return!1;if("boolean"!=typeof e)break;return e;case ht.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 ht.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=bt[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 $t{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);Nt(void 0!==o),n[t.useProtoFieldName?e.name:e.jsonName]=o}return n}field(e,t,n){let s;if("map"==e.kind){Nt("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);Nt(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);Nt(void 0!==t),i[r.toString()]=t}break;case"enum":const r=e.V.T();for(const[s,o]of Object.entries(t)){Nt(void 0===o||"number"==typeof o);const t=this.enum(r,o,e.name,!1,!0,n.enumAsInteger);Nt(void 0!==t),i[s.toString()]=t}}(n.emitDefaultValues||Object.keys(i).length>0)&&(s=i)}else if(e.repeat){Nt(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);Nt(void 0!==s),i.push(s)}break;case"enum":const s=e.T();for(let r=0;r<t.length;r++){Nt(void 0===t[r]||"number"==typeof t[r]);const o=this.enum(s,t[r],e.name,e.opt,!0,n.enumAsInteger);Nt(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);Nt(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 Nt("number"==typeof t),Nt(Number.isInteger(t)),r||!e[1].hasOwnProperty(t)?t:e[2]?e[2]+e[1][t]:e[1][t]}else Nt(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 Nt(s);const r=i||s;switch(e){case ht.INT32:case ht.SFIXED32:case ht.SINT32:return 0===t?r?0:void 0:(Ut(t),t);case ht.FIXED32:case ht.UINT32:return 0===t?r?0:void 0:(Bt(t),t);case ht.FLOAT:Vt(t);case ht.DOUBLE:return 0===t?r?0:void 0:(Nt("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t);case ht.STRING:return""===t?r?"":void 0:(Nt("string"==typeof t),t);case ht.BOOL:return!1===t?!r&&void 0:(Nt("boolean"==typeof t),t);case ht.UINT64:case ht.FIXED64:Nt("number"==typeof t||"string"==typeof t||"bigint"==typeof t);let e=Dt.from(t);if(e.isZero()&&!r)return;return e.toString();case ht.INT64:case ht.SFIXED64:case ht.SINT64:Nt("number"==typeof t||"string"==typeof t||"bigint"==typeof t);let n=Ft.from(t);if(n.isZero()&&!r)return;return n.toString();case ht.BYTES:return Nt(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+=St[t>>2],i=(3&t)<<4,s=1;break;case 1:n+=St[i|t>>4],i=(15&t)<<2,s=2;break;case 2:n+=St[i|t>>6],n+=St[63&t],s=0}return s&&(n+=St[i],n+="=",1==s&&(n+="=")),n}(t):r?"":void 0}}}function Ht(e,t=ut.STRING){switch(e){case ht.BOOL:return!1;case ht.UINT64:case ht.FIXED64:return _t(Dt.ZERO,t);case ht.INT64:case ht.SFIXED64:case ht.SINT64:return _t(Ft.ZERO,t);case ht.DOUBLE:case ht.FLOAT:return 0;case ht.BYTES:return new Uint8Array(0);case ht.STRING:return"";default:return 0}}class jt{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?nt.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?ht.INT32:r.T,s="scalar"==r.kind?r.L:void 0;if(a){let n=o[l];if(i==st.LengthDelimited&&t!=ht.STRING&&t!=ht.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==ht.BOOL?t.bool().toString():this.scalar(t,e.K,ut.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=Ht(e.K);s=e.K==ht.BOOL?t.toString():t}if(void 0===i)switch(e.V.kind){case"scalar":i=Ht(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 ht.INT32:return e.int32();case ht.STRING:return e.string();case ht.BOOL:return e.bool();case ht.DOUBLE:return e.double();case ht.FLOAT:return e.float();case ht.INT64:return _t(e.int64(),n);case ht.UINT64:return _t(e.uint64(),n);case ht.FIXED64:return _t(e.fixed64(),n);case ht.FIXED32:return e.fixed32();case ht.BYTES:return e.bytes();case ht.UINT32:return e.uint32();case ht.SFIXED32:return e.sfixed32();case ht.SFIXED64:return _t(e.sfixed64(),n);case ht.SINT32:return e.sint32();case ht.SINT64:return _t(e.sint64(),n)}}}class zt{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?ht.INT32:s.T;if(o)if(Nt(Array.isArray(i)),o==pt.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?Nt(s.opt):this.scalar(t,e,s.no,i,r||s.opt);break;case"message":if(o){Nt(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":Nt("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?nt.onWrite:s)(this.info.typeName,e,t)}mapEntry(e,t,n,s,i){e.tag(n.no,st.LengthDelimited),e.fork();let r=s;switch(n.K){case ht.INT32:case ht.FIXED32:case ht.UINT32:case ht.SFIXED32:case ht.SINT32:r=Number.parseInt(s);break;case ht.BOOL:Nt("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,ht.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,st.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;Nt(t!==ht.BYTES&&t!==ht.STRING),e.tag(n,st.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=st.Varint,i=void 0===t,r=0===t;switch(e){case ht.INT32:n="int32";break;case ht.STRING:r=i||!t.length,s=st.LengthDelimited,n="string";break;case ht.BOOL:r=!1===t,n="bool";break;case ht.UINT32:n="uint32";break;case ht.DOUBLE:s=st.Bit64,n="double";break;case ht.FLOAT:s=st.Bit32,n="float";break;case ht.INT64:r=i||Ft.from(t).isZero(),n="int64";break;case ht.UINT64:r=i||Dt.from(t).isZero(),n="uint64";break;case ht.FIXED64:r=i||Dt.from(t).isZero(),s=st.Bit64,n="fixed64";break;case ht.BYTES:r=i||!t.byteLength,s=st.LengthDelimited,n="bytes";break;case ht.FIXED32:s=st.Bit32,n="fixed32";break;case ht.SFIXED32:s=st.Bit32,n="sfixed32";break;case ht.SFIXED64:r=i||Ft.from(t).isZero(),s=st.Bit64,n="sfixed64";break;case ht.SINT32:n="sint32";break;case ht.SINT64:r=i||Ft.from(t).isZero(),n="sint64"}return[s,n,i||r]}}const qt={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Qt={ignoreUnknownFields:!1},Kt=Object.values;function Gt(e,t,n){if(t===n)return!0;if(e!==ht.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 Xt(e,t,n){if(t.length!==n.length)return!1;for(let s=0;s<t.length;s++)if(!Gt(e,t[s],n[s]))return!1;return!0}function Jt(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 Yt={writeUnknownFields:!0,writerFactory:()=>new Zt};class Zt{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(Bt(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return Ut(e),kt(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){Vt(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){Bt(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Ut(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Ut(e),kt(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=Ft.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=Dt.from(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=Ft.from(e);return Ct(t.lo,t.hi,this.buf),this}sint64(e){let t=Ft.from(e),n=t.hi>>31;return Ct(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=Dt.from(e);return Ct(t.lo,t.hi,this.buf),this}}const en={readUnknownField:!0,readerFactory:e=>new tn(e)};class tn{constructor(e,t){this.varint64=wt,this.uint32=Rt,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 st.Varint:for(;128&this.buf[this.pos++];);break;case st.Bit64:this.pos+=4;case st.Bit32:this.pos+=4;break;case st.LengthDelimited:let t=this.uint32();this.pos+=t;break;case st.StartGroup:let n;for(;(n=this.tag()[1])!==st.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 Ft(...this.varint64())}uint64(){return new Dt(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(1&e);return e=(e>>>1|(1&t)<<31)^n,t=t>>>1^n,new Ft(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 Dt(this.sfixed32(),this.sfixed32())}sfixed64(){return new Ft(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 nn=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),sn=nn[ct]={};class rn{constructor(e,t,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=t.map(mt),this.options=null!=n?n:{},sn.value=this,this.messagePrototype=Object.create(null,nn),this.refTypeCheck=new ft(this),this.refJsonReader=new Wt(this),this.refJsonWriter=new $t(this),this.refBinReader=new jt(this),this.refBinWriter=new zt(this)}create(e){let t=function(e){const t=e.messagePrototype?Object.create(e.messagePrototype):Object.defineProperty({},ct,{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]=Ht(n.T,n.L);break;case"enum":t[e]=0;break;case"map":t[e]={}}}return t}(this);return void 0!==e&<(this,t,e),t}clone(e){let t=this.create();return lt(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?ht.INT32:s.T;if(!(s.repeat?Xt(e,i,r):Gt(e,i,r)))return!1;break;case"map":if(!("message"==s.V.kind?Jt(s.V.T(),Kt(i),Kt(r)):Xt("enum"==s.V.kind?ht.INT32:s.V.T,Kt(i),Kt(r))))return!1;break;case"message":let t=s.T();if(!(s.repeat?Jt(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){lt(this,e,t)}fromBinary(e,t){let n=function(e){return e?Object.assign(Object.assign({},en),e):en}(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({},Qt),e):Qt}(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({},qt),e):qt}(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({},Yt),e):Yt}(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 ${yt(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 rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};const on=new class extends rn{constructor(){super("peerConnectionOptions",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},an=new class extends rn{constructor(){super("config",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"peerConnectionOptions",kind:"message",T:()=>on},{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&<(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=on.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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),e.peerConnectionOptions&&on.internalBinaryWrite(e.peerConnectionOptions,t.tag(2,st.LengthDelimited).fork(),n).join(),void 0!==e.protocolVersion&&t.tag(3,st.LengthDelimited).string(e.protocolVersion);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.id&&t.tag(2,st.LengthDelimited).string(e.id),void 0!==e.protocolVersion&&t.tag(3,st.LengthDelimited).string(e.protocolVersion);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.committedId&&t.tag(2,st.LengthDelimited).string(e.committedId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};const ln=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.newID&&t.tag(2,st.LengthDelimited).string(e.newID);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},cn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},dn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);for(let n=0;n<e.ids.length;n++)t.tag(2,st.LengthDelimited).string(e.ids[n]);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},hn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.streamerId&&t.tag(2,st.LengthDelimited).string(e.streamerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};const un=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.message&&t.tag(2,st.LengthDelimited).string(e.message);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),!1!==e.dataChannel&&t.tag(2,st.Varint).bool(e.dataChannel),!1!==e.sfu&&t.tag(3,st.Varint).bool(e.sfu),""!==e.playerId&&t.tag(5,st.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.playerId&&t.tag(2,st.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};const pn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.sdp&&t.tag(2,st.LengthDelimited).string(e.sdp),void 0!==e.playerId&&t.tag(3,st.LengthDelimited).string(e.playerId),void 0!==e.sfu&&t.tag(4,st.Varint).bool(e.sfu),void 0!==e.multiplex&&t.tag(5,st.Varint).bool(e.multiplex),void 0!==e.scalabilityMode&&t.tag(6,st.LengthDelimited).string(e.scalabilityMode);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},mn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.sdp&&t.tag(2,st.LengthDelimited).string(e.sdp),void 0!==e.playerId&&t.tag(3,st.LengthDelimited).string(e.playerId),void 0!==e.minBitrateBps&&t.tag(4,st.Varint).int32(e.minBitrateBps),void 0!==e.maxBitrateBps&&t.tag(5,st.Varint).int32(e.maxBitrateBps);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},gn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.candidate&&t.tag(1,st.LengthDelimited).string(e.candidate),""!==e.sdpMid&&t.tag(2,st.LengthDelimited).string(e.sdpMid),0!==e.sdpMLineIndex&&t.tag(3,st.Varint).int32(e.sdpMLineIndex),void 0!==e.usernameFragment&&t.tag(4,st.LengthDelimited).string(e.usernameFragment);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},fn=new class extends rn{constructor(){super("iceCandidate",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"candidate",kind:"message",T:()=>gn},{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&<(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=gn.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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),e.candidate&&gn.internalBinaryWrite(e.candidate,t.tag(2,st.LengthDelimited).fork(),n).join(),void 0!==e.playerId&&t.tag(3,st.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.playerId&&t.tag(2,st.LengthDelimited).string(e.playerId),void 0!==e.reason&&t.tag(3,st.LengthDelimited).string(e.reason);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};const yn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),0!==e.time&&t.tag(2,st.Varint).int32(e.time);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},vn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),0!==e.time&&t.tag(2,st.Varint).int32(e.time);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};const Sn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),0!==e.spatialLayer&&t.tag(2,st.Varint).int32(e.spatialLayer),0!==e.temporalLayer&&t.tag(3,st.Varint).int32(e.temporalLayer),""!==e.playerId&&t.tag(4,st.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},bn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},wn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.playerId&&t.tag(2,st.LengthDelimited).string(e.playerId),0!==e.sendStreamId&&t.tag(3,st.Varint).int32(e.sendStreamId),0!==e.recvStreamId&&t.tag(4,st.Varint).int32(e.recvStreamId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},Cn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.sfuId&&t.tag(2,st.LengthDelimited).string(e.sfuId),0!==e.sendStreamId&&t.tag(3,st.Varint).int32(e.sendStreamId),0!==e.recvStreamId&&t.tag(4,st.Varint).int32(e.recvStreamId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};const Tn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),0!==e.count&&t.tag(2,st.Varint).int32(e.count);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};function Mn(e,t){const n=e.create();return n.type=e.typeName,t&&e.mergePartial(n,t),n}new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.data&&t.tag(2,st.LengthDelimited).string(e.data);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};class En{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(Mn(yn,{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 kn{constructor(e){this.videoElementProvider=e,this.audioElement=document.createElement("Audio"),this.videoElementProvider.setAudioElement(this.audioElement)}handleOnTrack(e){if(Y.Info("handleOnTrack "+JSON.stringify(e.streams)),e.streams.length<1||"probator"==e.streams[0].id)return;const t=this.videoElementProvider.getVideoElement();if(e.track&&Y.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 Y.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,Y.Info("Created new audio element to play separate audio stream."))}}class Rn{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 Pn{constructor(e){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new Rn(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,Y.Info(`received first chunk of freeze frame: ${this.jpeg.length}/${this.size}`);this.jpeg.length===this.size?(this.receiving=!1,this.valid=!0,Y.Info(`received complete freeze frame ${this.size}`),this.updateFreezeFrameAndShow(this.jpeg,t)):this.jpeg.length>this.size&&(Y.Error(`received bigger freeze frame than advertised: ${this.jpeg.length}/${this.size}`),this.jpeg=void 0,this.receiving=!1)}}class In{constructor(e,t,n){this.active=!1,this.countdownActive=!1,this.warnTimer=void 0,this.countDown=0,this.countDownTimer=void 0,this.config=e,this.pixelStreaming=t,this.onDismissAfk=n,this.onAFKTimedOutCallback=()=>{console.log("AFK timed out, did you want to override this callback?")}}onAfkClick(){clearInterval(this.countDownTimer),(this.active||this.countdownActive)&&(this.startAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new oe))}startAfkWarningTimer(){this.config.getNumericSettingValue(Ke.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(qe.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(qe.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout(()=>this.activateAfkEvent(),1e3*this.config.getNumericSettingValue(Ke.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new ie({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(Ke.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new re({countDown:this.countDown})),this.config.isFlagEnabled(qe.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval(()=>{this.countDown--,0==this.countDown?(this.pixelStreaming.dispatchEvent(new ae),this.onAFKTimedOutCallback(),Y.Info("You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new re({countDown:this.countDown}))},1e3)}}class xn{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;Y.Info(`Data Channel (${this.label}) opened.`),this.onOpen(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}handleOnClose(e){var t;Y.Info(`Data Channel (${this.label}) closed.`),this.onClose(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}handleOnMessage(e){Y.Info(`Data Channel (${this.label}) message: ${e}`)}handleOnError(e){var t;Y.Info(`Data Channel (${this.label}) error: ${e}`),this.onError(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}onOpen(e,t){}onClose(e,t){}onError(e,t){}}class Ln{}class An{}class On{}class Dn{}class Fn{}class Nn{}class Un{}class Bn{}class Vn{constructor(){this.inboundVideoStats=new An,this.inboundAudioStats=new Ln,this.candidatePairs=new Array,this.datachannelStats=new On,this.localCandidates=new Array,this.remoteCandidates=new Array,this.outboundVideoStats=new Fn,this.outboundAudioStats=new Fn,this.remoteOutboundAudioStats=new Nn,this.remoteOutboundVideoStats=new Nn,this.sessionStats=new Un,this.streamStats=new Bn,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:Y.Error("unhandled Stat Type"),Y.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 Dn;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 Dn;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:Y.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}}var _n=o(963);class Wn{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 $n{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 Hn{}class jn{}class zn{constructor(){this.latestSenderRecvClockOffset=null}calculate(e,t){const n=new qn,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 jn,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 Hn;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 qn{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 Qn=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 Kn{constructor(e,t,n){this.config=t,this.createPeerConnection(e,n),this.latencyCalculator=new zn}createPeerConnection(e,t){this.config.isFlagEnabled(qe.ForceTURN)&&(e.iceTransportPolicy="relay",Y.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 Vn,this.preferredCodec=t,this.updateCodecSelection=!0}createOffer(e,t){return Qn(this,void 0,void 0,function*(){Y.Info("Create Offer");const n="localhost"===location.hostname||"127.0.0.1"===location.hostname,s="https:"===location.protocol;let i=t.isFlagEnabled(qe.UseMic),r=t.isFlagEnabled(qe.UseCamera);!i&&!r||n||s||(i=!1,r=!1,Y.Error("Microphone and Webcam access in the browser will not work if you are not on HTTPS or localhost. Disabling mic and webcam access."),Y.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){return Qn(this,void 0,void 0,function*(){var n;Y.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(qe.UseMic),r=t.isFlagEnabled(qe.UseCamera);!i&&!r||n||s||(i=!1,r=!1,Y.Error("Microphone and Webcam access in the browser will not work if you are not on HTTPS or localhost. Disabling mic and webcam access."),Y.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(Ye.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=>{Y.Error(`createAnswer() failed - ${e}`)})})})})}receiveAnswer(e){var t;null===(t=this.peerConnection)||void 0===t||t.setRemoteDescription(e),this.config.setOptionSettingOptions(Ye.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e))}generateStats(){this.peerConnection.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(Ye.PreferredCodec).options;if(s.includes(n))return void this.config.setOptionSettingValue(Ye.PreferredCodec,n);const i=s.filter(e=>-1!==e.indexOf(t));if(i.length>0)return void this.config.setOptionSettingValue(Ye.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(qe.ForceMonoAudio)?"stereo=0;":"stereo=1;",s+="useinbandfec=1",n=n.replace("useinbandfec=1",s),this.config.isFlagEnabled(qe.EnableCaptureTimeExt)&&!this.isFirefox()&&(n=$n.addVideoHeaderExtensionToSdp(n,"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time")),n}isFirefox(){return navigator.userAgent.indexOf("Firefox")>0}handleOnIce(e){var t;Y.Info("peerconnection handleOnIce"),this.config.isFlagEnabled(qe.ForceTURN)&&e.candidate.indexOf("relay")<0?Y.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){Y.Info("signaling state change: "+e)}handleIceConnectionStateChange(e){Y.Info("ice connection state change: "+e),this.onIceConnectionStateChange(e)}handleIceGatheringStateChange(e){Y.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(Ye.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 Qn(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 Qn(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(Wn.canTransceiverReceiveVideo(e))for(const t of r.getTracks())t.kind&&"video"==t.kind&&(e.sender.replaceTrack(t),e.direction="sendrecv")}else for(const e of r.getTracks())e.kind&&"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 Qn(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(Wn.canTransceiverReceiveAudio(e))for(const t of r.getTracks())t.kind&&"audio"==t.kind&&(e.sender.replaceTrack(t),e.direction="sendrecv")}else for(const e of r.getTracks())e.kind&&"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,_n.splitSections)(e.sdp);return n.shift(),n.forEach(e=>{const{codecs:n}=(0,_n.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 Gn{constructor(){this.PixelStreamingSettings=new Xn,this.EncoderSettings=new Jn,this.WebRTCSettings=new Yn}ueCompatible(){null!=this.WebRTCSettings.MaxFPS&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}}class Xn{}class Jn{}class Yn{}class Zn{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||(Y.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||(Y.Info(`Setting CaptureToSendMs Ms \n ${this.PostCaptureTimeMs} \n ${this.PreCaptureTimeMs}`),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}}class es{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(),Y.Info("Received first chunk of file"));const n=new TextDecoder("utf-16").decode(e.slice(1));Y.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(),Y.Info("Received first chunk of file"));const n=new TextDecoder("utf-16").decode(e.slice(1));Y.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),Y.Info(`Received file chunk: ${t.data.length}/${t.chunks}`),t.data.length===t.chunks){t.receiving=!1,t.valid=!0,Y.Info("Received complete file");const e=(new Date).getTime()-t.timestampStart,n=Math.round(16384*t.chunks/e);Y.Info(`Average transfer bitrate: ${n}kb/s over ${e/1e3} seconds`)}else t.data.length>t.chunks&&(t.receiving=!1,Y.Error(`Received bigger file than advertised: ${t.data.length}/${t.chunks}`))}}class ts{constructor(){this.mimetype="",this.extension="",this.receiving=!1,this.chunks=0,this.data=[],this.valid=!1}}class ns{}ns.backSpace=8,ns.shift=16,ns.control=17,ns.alt=18,ns.rightShift=253,ns.rightControl=254,ns.rightAlt=255;const ss=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});class is{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===ns.backSpace&&this.handleOnKeyPress(new KeyboardEvent("keypress",{charCode:ns.backSpace,keyCode:ns.backSpace})),this.config.isFlagEnabled(qe.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(qe.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 ss?ss[t.code]:(Y.Warning(`Keyboard code of ${t.code} is not supported in our mapping, ignoring this key.`),null)}return e.keyCode===ns.shift&&"ShiftRight"===e.code?ns.rightShift:e.keyCode===ns.control&&"ControlRight"===e.code?ns.rightControl:e.keyCode===ns.alt&&"AltRight"===e.code?ns.rightAlt:e.keyCode}isKeyCodeBrowserKey(e){return e>=112&&e<=123||9===e}}class rs{}rs.mainButton=0,rs.auxiliaryButton=1,rs.secondaryButton=2,rs.fourthButton=3,rs.fifthButton=4;class os{}os.primaryButton=1,os.secondaryButton=2,os.auxiliaryButton=4,os.fourthButton=8,os.fifthButton=16;class as{constructor(e,t,n,s){this.streamMessageController=e,this.coordinateConverter=n,this.videoPlayer=t,this.activeKeys=s,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&os.primaryButton&&this.sendMouseUp(rs.mainButton,s.x,s.y),e&os.secondaryButton&&this.sendMouseUp(rs.secondaryButton,s.x,s.y),e&os.auxiliaryButton&&this.sendMouseUp(rs.auxiliaryButton,s.x,s.y),e&os.fourthButton&&this.sendMouseUp(rs.fourthButton,s.x,s.y),e&os.fifthButton&&this.sendMouseUp(rs.fifthButton,s.x,s.y)}pressMouseButtons(e,t,n){if(!this.videoPlayer.isVideoReady())return;const s=this.coordinateConverter.translateUnsigned(t,n);e&os.primaryButton&&this.sendMouseDown(rs.mainButton,s.x,s.y),e&os.secondaryButton&&this.sendMouseDown(rs.secondaryButton,s.x,s.y),e&os.auxiliaryButton&&this.sendMouseDown(rs.auxiliaryButton,s.x,s.y),e&os.fourthButton&&this.sendMouseDown(rs.fourthButton,s.x,s.y),e&os.fifthButton&&this.sendMouseDown(rs.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 ls extends as{constructor(e,t,n,s){super(e,t,n,s),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?(Y.Info("Pointer locked"),document.addEventListener("mousemove",this.onMouseMoveListener)):(Y.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])}}class cs extends as{constructor(e,t,n,s){super(e,t,n,s),this.videoElementParent=t.getVideoParentElement(),this.onMouseUpListener=this.onMouseUp.bind(this),this.onMouseDownListener=this.onMouseDown.bind(this),this.onMouseDblClickListener=this.onMouseDblClick.bind(this),this.onMouseWheelListener=this.onMouseWheel.bind(this),this.onMouseMoveListener=this.onMouseMove.bind(this),this.onContextMenuListener=this.onContextMenu.bind(this)}register(){super.register(),this.videoElementParent.addEventListener("mousemove",this.onMouseMoveListener),this.videoElementParent.addEventListener("mousedown",this.onMouseDownListener),this.videoElementParent.addEventListener("mouseup",this.onMouseUpListener),this.videoElementParent.addEventListener("contextmenu",this.onContextMenuListener),this.videoElementParent.addEventListener("wheel",this.onMouseWheelListener),this.videoElementParent.addEventListener("dblclick",this.onMouseDblClickListener)}unregister(){this.videoElementParent.removeEventListener("mousemove",this.onMouseMoveListener),this.videoElementParent.removeEventListener("mousedown",this.onMouseDownListener),this.videoElementParent.removeEventListener("mouseup",this.onMouseUpListener),this.videoElementParent.removeEventListener("contextmenu",this.onContextMenuListener),this.videoElementParent.removeEventListener("wheel",this.onMouseWheelListener),this.videoElementParent.removeEventListener("dblclick",this.onMouseDblClickListener),super.unregister()}onMouseDown(e){if(!this.videoPlayer.isVideoReady())return;const t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY);this.streamMessageController.toStreamerHandlers.get("MouseDown")([e.button,t.x,t.y]),e.preventDefault()}onMouseUp(e){if(!this.videoPlayer.isVideoReady())return;const t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY);this.streamMessageController.toStreamerHandlers.get("MouseUp")([e.button,t.x,t.y]),e.preventDefault()}onContextMenu(e){this.videoPlayer.isVideoReady()&&e.preventDefault()}onMouseMove(e){if(!this.videoPlayer.isVideoReady())return;const t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY),n=this.coordinateConverter.translateSigned(e.movementX,e.movementY);this.streamMessageController.toStreamerHandlers.get("MouseMove")([t.x,t.y,n.x,n.y]),e.preventDefault()}onMouseWheel(e){if(!this.videoPlayer.isVideoReady())return;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])}}class ds{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&&Y.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;Y.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 hs{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")([rs.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")([rs.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 us(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 ps,ms,gs;!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"}(ps||(ps={}));class fs{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:us(t),prevState:us(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];delete this.controllers[t.index],this.controllers=this.controllers.filter(e=>void 0!==e),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==ps.LeftTrigger?e.get("GamepadAnalog")([n,5,i.value]):s==ps.RightTrigger?e.get("GamepadAnalog")([n,6,i.value]):e.get("GamepadButtonPressed")([n,s,r.pressed?1:0]):!i.pressed&&r.pressed&&(s==ps.LeftTrigger?e.get("GamepadAnalog")([n,5,0]):s==ps.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=us(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 ys{constructor(e,t,n){this.activeKeys=new vs,this.toStreamerMessagesProvider=e,this.videoElementProvider=t,this.coordinateConverter=n}registerKeyBoard(e){Y.Info("Register Keyboard Events");const t=new is(this.toStreamerMessagesProvider,e,this.activeKeys);return t.register(),t}registerMouse(e){let t;return Y.Info("Register Mouse Events"),t=e==tt.HoveringMouse?new cs(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys):new ls(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys),t.register(),t}registerTouch(e){let t;return Y.Info("Registering Touch"),t=e?new hs(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter):new ds(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter),t.register(),t}registerGamePad(){Y.Info("Register Game Pad");const e=new fs(this.toStreamerMessagesProvider);return e.register(),e}}class vs{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class Ss{constructor(e,t){this.lastTimeResized=(new Date).getTime(),this.videoElement=document.createElement("video"),this.config=t,this.videoElement.id="streamingVideo",this.videoElement.disablePictureInPicture=!0,this.videoElement.playsInline=!0,this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.pointerEvents="all",e.appendChild(this.videoElement),this.onResizePlayerCallback=()=>{console.log("Resolution changed, restyling player, did you forget to override this function?")},this.onMatchViewportResolutionCallback=()=>{console.log("Resolution changed and match viewport resolution is turned on, did you forget to override this function?")},this.videoElement.onclick=()=>{null!=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(qe.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(qe.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(qe.MatchViewportResolution))if((new Date).getTime()-this.lastTimeResized>300){const e=this.getVideoParentElement();if(!e)return;this.onMatchViewportResolutionCallback(e.clientWidth,e.clientHeight),this.lastTimeResized=(new Date).getTime()}else Y.Info("Resizing too often - skipping"),clearTimeout(this.resizeTimeoutHandle),this.resizeTimeoutHandle=window.setTimeout(()=>this.updateVideoStreamSize(),100)}}class bs{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 ms.ToStreamer:this.toStreamerHandlers.set(t,n);break;case ms.FromStreamer:this.fromStreamerHandlers.set(t,n);break;default:Y.Info(`Unknown message direction ${e}`)}}}!function(e){e[e.ToStreamer=0]="ToStreamer",e[e.FromStreamer=1]="FromStreamer"}(ms||(ms={}));class ws{constructor(){this.responseEventListeners=new Map}addResponseEventListener(e,t){this.responseEventListeners.set(e,t)}removeResponseEventListener(e){this.responseEventListeners.delete(e)}onResponse(e){Y.Info("DataChannelReceiveMessageType.Response");const t=new TextDecoder("utf-16").decode(e.slice(1));Y.Info(t),this.responseEventListeners.forEach(e=>{e(t)})}}class Cs{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 Y.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 Y.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;const i=new TextEncoder;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*i.encode(e).length}});const r=new DataView(new ArrayBuffer(s+1));r.setUint8(0,n.id);let o=1;t.forEach((e,t)=>{switch(n.structure[t]){case"uint8":r.setUint8(o,e),o+=1;break;case"uint16":r.setUint16(o,e,!0),o+=2;break;case"int16":r.setInt16(o,e,!0),o+=2;break;case"float":r.setFloat32(o,e,!0),o+=4;break;case"double":r.setFloat64(o,e,!0),o+=8;break;case"string":r.setUint16(o,e.length,!0),o+=2;for(let t=0;t<e.length;t++)r.setUint16(o,e.charCodeAt(t),!0),o+=2}}),this.dataChannelSender.canSend()?this.dataChannelSender.sendData(r.buffer):Y.Info(`Data channel cannot send yet, skipping sending message: ${e} - ${new Uint8Array(r.buffer)}`)}}class Ts{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 Ms{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),Y.Info(`Message Sent: ${new Uint8Array(e)}`),this.resetAfkWarningTimerOnDataSend()):Y.Error(`Message Failed: ${new Uint8Array(e)}`)}resetAfkWarningTimerOnDataSend(){}}class Es{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 ks{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 Rs{constructor(e,t){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=e,this.pixelStreaming=t,this.responseController=new ws,this.file=new ts,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new In(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity.",!1)},this.freezeFrameController=new Pn(this.pixelStreaming.videoElementParent),this.videoPlayer=new Ss(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 kn(this.videoPlayer),this.coordinateConverter=new Es,this.sendrecvDataChannelController=new xn,this.recvDataChannelController=new xn,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new Ms(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new bs,this.transport=new ot(e.webSocketProtocols),this.protocol=new at(this.transport),this.protocol.addListener(an.typeName,e=>this.handleOnConfigMessage(e)),this.protocol.addListener(yn.typeName,e=>this.handlePingMessage(e)),this.protocol.addListener(dn.typeName,e=>this.handleStreamerListMessage(e)),this.protocol.addListener(un.typeName,e=>this.handleSubscribeFailedMessage(e)),this.protocol.addListener(ln.typeName,e=>this.handleStreamerIDChangedMessage(e)),this.protocol.addListener(Tn.typeName,e=>{const t=e;this.pixelStreaming._onPlayerCount(t.count)}),this.protocol.addListener(mn.typeName,e=>this.handleWebRtcAnswer(e)),this.protocol.addListener(pn.typeName,e=>this.handleWebRtcOffer(e)),this.protocol.addListener(wn.typeName,e=>this.handleWebRtcSFUPeerDatachannels(e)),this.protocol.addListener(fn.typeName,e=>{const t=e;this.handleIceCandidate(t.candidate)}),this.protocol.transport.addListener("open",()=>{if(!this.config.isFlagEnabled(qe.BrowserSendOffer)){const e=Mn(cn);this.protocol.sendMessage(e)}this.reconnectAttempt=0,this.isReconnecting=!1}),this.protocol.transport.addListener("error",()=>{Y.Error("Got a transport error.")}),this.protocol.transport.addListener("close",e=>{const t=this.config.getNumericSettingValue(Ke.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(Ye.PreferredCodec).options=ze.getSupportedVideoCodecs(),this.pixelStreaming._onDisconnect(r,i),this.afkController.stopAfkWarningTimer(),this.statsTimerHandle&&void 0!==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 Cs(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new Ts(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new ys(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(Ye.StreamerId,e=>{if(void 0===e||""===e)return;this.peerConnectionController.peerConnection.close(),this.peerConnectionController.createPeerConnection(this.peerConfig,this.preferredCodec),this.subscribedStream=e;const t=Mn(hn,{streamerId:e});this.protocol.sendMessage(t)}),this.config._addOnOptionSettingChangedListener(Ye.PreferredQuality,e=>{if(void 0===e||""===e)return;let t;if(this.isUsingSVC)t=Mn(Sn,{spatialLayer:+e[1]-1,temporalLayer:+e[3]-1});else{const n=this.config.getSettingOption(Ye.PreferredQuality).options.indexOf(e);t=Mn(Sn,{spatialLayer:n,temporalLayer:0})}this.protocol.sendMessage(t)}),this.setVideoEncoderAvgQP(-1),this.signallingUrlBuilder=()=>this.config.getTextSettingValue(Xe.SignallingServerUrl)}destroyVideoPlayer(){this.videoPlayer.destroy()}handleOnMessage(e){const t=new Uint8Array(e.data);Y.Info("Message incoming:"+t);const n=this.streamMessageController.fromStreamerMessages.get(t[0]);this.streamMessageController.fromStreamerHandlers.get(n)(e.data)}registerMessageHandlers(){this.streamMessageController.registerMessageHandler(ms.FromStreamer,"QualityControlOwnership",e=>this.onQualityControlOwnership(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"Response",e=>this.responseController.onResponse(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"Command",e=>{this.onCommand(e)}),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"FreezeFrame",e=>this.onFreezeFrameMessage(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"UnfreezeFrame",()=>this.invalidateFreezeFrameAndEnableVideo()),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"VideoEncoderAvgQP",e=>this.handleVideoEncoderAvgQP(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"LatencyTest",e=>this.handleLatencyTestResult(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"DataChannelLatencyTest",e=>this.handleDataChannelLatencyTestResponse(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"InitialSettings",e=>this.handleInitialSettings(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"FileExtension",e=>this.onFileExtension(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"FileMimeType",e=>this.onFileMimeType(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"FileContents",e=>this.onFileContents(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"TestEcho",()=>{}),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"InputControlOwnership",e=>this.onInputControlOwnership(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"GamepadResponse",e=>this.onGamepadResponse(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"Multiplexed",()=>{}),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"Protocol",e=>this.onProtocolMessage(e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"IFrameRequest",()=>this.sendMessageController.sendMessageToStreamer("IFrameRequest")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"RequestQualityControl",()=>this.sendMessageController.sendMessageToStreamer("RequestQualityControl")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"FpsRequest",()=>this.sendMessageController.sendMessageToStreamer("FpsRequest")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"AverageBitrateRequest",()=>this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"StartStreaming",()=>this.sendMessageController.sendMessageToStreamer("StartStreaming")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"StopStreaming",()=>this.sendMessageController.sendMessageToStreamer("StopStreaming")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"LatencyTest",e=>this.sendMessageController.sendMessageToStreamer("LatencyTest",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"RequestInitialSettings",()=>this.sendMessageController.sendMessageToStreamer("RequestInitialSettings")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"TestEcho",()=>{}),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"UIInteraction",e=>this.sendMessageController.sendMessageToStreamer("UIInteraction",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"Command",e=>this.sendMessageController.sendMessageToStreamer("Command",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"TextboxEntry",e=>this.sendMessageController.sendMessageToStreamer("TextboxEntry",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"KeyDown",e=>this.sendMessageController.sendMessageToStreamer("KeyDown",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"KeyUp",e=>this.sendMessageController.sendMessageToStreamer("KeyUp",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"KeyPress",e=>this.sendMessageController.sendMessageToStreamer("KeyPress",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"MouseEnter",e=>this.sendMessageController.sendMessageToStreamer("MouseEnter",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"MouseLeave",e=>this.sendMessageController.sendMessageToStreamer("MouseLeave",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"MouseDown",e=>this.sendMessageController.sendMessageToStreamer("MouseDown",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"MouseUp",e=>this.sendMessageController.sendMessageToStreamer("MouseUp",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"MouseMove",e=>this.sendMessageController.sendMessageToStreamer("MouseMove",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"MouseWheel",e=>this.sendMessageController.sendMessageToStreamer("MouseWheel",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"MouseDouble",e=>this.sendMessageController.sendMessageToStreamer("MouseDouble",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"TouchStart",e=>this.sendMessageController.sendMessageToStreamer("TouchStart",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"TouchEnd",e=>this.sendMessageController.sendMessageToStreamer("TouchEnd",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"TouchMove",e=>this.sendMessageController.sendMessageToStreamer("TouchMove",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"GamepadConnected",()=>this.sendMessageController.sendMessageToStreamer("GamepadConnected")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"GamepadButtonPressed",e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonPressed",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"GamepadButtonReleased",e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonReleased",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"GamepadAnalog",e=>this.sendMessageController.sendMessageToStreamer("GamepadAnalog",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"GamepadDisconnected",e=>this.sendMessageController.sendMessageToStreamer("GamepadDisconnected",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XREyeViews",e=>this.sendMessageController.sendMessageToStreamer("XREyeViews",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRHMDTransform",e=>this.sendMessageController.sendMessageToStreamer("XRHMDTransform",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRControllerTransform",e=>this.sendMessageController.sendMessageToStreamer("XRControllerTransform",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRSystem",e=>this.sendMessageController.sendMessageToStreamer("XRSystem",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRButtonTouched",e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouched",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRButtonTouchReleased",e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouchReleased",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRButtonPressed",e=>this.sendMessageController.sendMessageToStreamer("XRButtonPressed",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRButtonReleased",e=>this.sendMessageController.sendMessageToStreamer("XRButtonReleased",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRAnalog",e=>this.sendMessageController.sendMessageToStreamer("XRAnalog",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"ChannelRelayStatus",()=>{}),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"Multiplexed",()=>{})}onCommand(e){Y.Info("DataChannelReceiveMessageType.Command");const t=new TextDecoder("utf-16").decode(e.slice(1));Y.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 Fe(r))}onProtocolMessage(e){try{const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);Object.prototype.hasOwnProperty.call(n,"Direction")||Y.Error("Malformed protocol received. Ensure the protocol message contains a direction");const s=n.Direction;delete n.Direction,Y.Info(`Received new ${s==ms.FromStreamer?"FromStreamer":"ToStreamer"} protocol. Updating existing protocol...`),Object.keys(n).forEach(e=>{const t=n[e];switch(s){case ms.ToStreamer:if(!Object.prototype.hasOwnProperty.call(t,"id"))return void Y.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):Y.Error(`There was no registered handler for "${e}" - try adding one using registerMessageHandler(MessageDirection.ToStreamer, "${e}", myHandler)`);break;case ms.FromStreamer:if(!Object.prototype.hasOwnProperty.call(t,"id"))return void Y.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):Y.Error(`There was no registered handler for "${t}" - try adding one using registerMessageHandler(MessageDirection.FromStreamer, "${e}", myHandler)`);break;default:Y.Error(`Unknown direction: ${s}`)}}),this.toStreamerMessagesController.SendRequestInitialSettings(),this.toStreamerMessagesController.SendRequestQualityControl()}catch(e){Y.Info(e)}}onInputControlOwnership(e){const t=new Uint8Array(e);Y.Info("DataChannelReceiveMessageType.InputControlOwnership");const n=new Boolean(t[1]).valueOf();Y.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())):Y.Info("This player has no protocol connection.")}loadFreezeFrameOrShowPlayOverlay(){this.pixelStreaming.dispatchEvent(new Pe({shouldShowPlayOverlay:this.shouldShowPlayOverlay,isValid:this.freezeFrameController.valid,jpegData:this.freezeFrameController.jpeg})),!0===this.shouldShowPlayOverlay?(Y.Info("showing play overlay"),this.resizePlayerStyle()):(Y.Info("showing freeze frame"),this.freezeFrameController.showFreezeFrame()),setTimeout(()=>{this.videoPlayer.setVideoEnabled(!1)},this.freezeFrameController.freezeFrameDelay)}onFreezeFrameMessage(e){Y.Info("DataChannelReceiveMessageType.FreezeFrame");const t=new Uint8Array(e);this.freezeFrameController.processFreezeFrameMessage(t,()=>this.loadFreezeFrameOrShowPlayOverlay())}invalidateFreezeFrameAndEnableVideo(){Y.Info("DataChannelReceiveMessageType.FreezeFrame"),setTimeout(()=>{this.pixelStreaming.dispatchEvent(new Ie),this.freezeFrameController.hideFreezeFrame()},this.freezeFrameController.freezeFrameDelay),this.videoPlayer.getVideoElement()&&this.videoPlayer.setVideoEnabled(!0)}onFileExtension(e){const t=new Uint8Array(e);es.setExtensionFromBytes(t,this.file)}onFileMimeType(e){const t=new Uint8Array(e);es.setMimeTypeFromBytes(t,this.file)}onFileContents(e){const t=new Uint8Array(e);es.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 Ee({message:e})),Y.Error(e),void this.closeSignalingServer("Stream not initialized correctly",!1)}if(this.videoPlayer.hasVideoSource()){if(this.setTouchInputEnabled(this.config.isFlagEnabled(qe.TouchInput)),this.pixelStreaming.dispatchEvent(new ke),this.streamController.audioElement.srcObject){const e=this.config.isFlagEnabled(qe.StartVideoMuted);this.streamController.audioElement.muted=e,e?this.playVideo():this.streamController.audioElement.play().then(()=>{this.playVideo()}).catch(e=>{Y.Info(e),Y.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 Re({reason:e}))})}else this.playVideo();this.shouldShowPlayOverlay=!1,this.freezeFrameController.showFreezeFrame()}else Y.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(),Y.Info(e),Y.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 Re({reason:e}))})}autoPlayVideoOrSetUpPlayOverlay(){this.config.isFlagEnabled(qe.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(Ke.KeepaliveDelay);t>0&&(this.keepalive=new En(this.protocol,t),this.keepalive.onTimeout=()=>{Y.Error("Protocol timeout"),this.protocol.disconnect()})}startSession(e){if(this.peerConfig=e,this.config.isFlagEnabled(qe.ForceTURN)&&!this.checkTurnServerAvailability(e))return Y.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 Kn(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):Y.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):Y.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(qe.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 Y.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 Y.Info(`A turn sever was found at ${e}`),!0;return Y.Info("A turn sever was not found"),!1}handleOnConfigMessage(e){this.resizePlayerStyle(),this.startSession(e.peerConnectionOptions)}handlePingMessage(e){this.protocol.sendMessage(Mn(vn,{time:e.time}))}handleStreamerListMessage(e){Y.Info(`Got streamer list ${e.ids}`);let t="";const n=this.config.getSettingOption(Ye.StreamerId);n.selected.toString().trim()&&(t=n.selected);const s=[...e.ids];s.unshift(""),this.config.setOptionSettingOptions(Ye.StreamerId,s);let i="";const r=this.config.isFlagEnabled(qe.WaitForStreamer),o=this.config.getNumericSettingValue(Ke.MaxReconnectAttempts),a=this.config.getNumericSettingValue(Ke.StreamerAutoJoinInterval),l=this.config.useUrlParams,c=new ks(window.location.search);l&&c.has(Ye.StreamerId)?t=c.get(Ye.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(Ye.StreamerId,i)):r&&(this.reconnectAttempt<o?(this.reconnectAttempt++,this.isReconnecting=!0,setTimeout(()=>{this.protocol.sendMessage(Mn(cn))},a)):(this.reconnectAttempt=0,this.isReconnecting=!1,this.enableAutoReconnect=!1)),this.pixelStreaming.dispatchEvent(new Le({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(Ye.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 Ae({newID:t}))}handleWebRtcAnswer(e){Y.Info(`Got answer sdp ${e.sdp}`);const t={sdp:e.sdp,type:"answer"};this.peerConnectionController.receiveAnswer(t),this.handlePostWebrtcNegotiation()}handleWebRtcOffer(e){Y.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(Ye.PreferredQuality,n),this.config.setOptionSettingValue(Ye.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(Mn(Cn)),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(qe.MouseInput)),this.setKeyboardInputEnabled(this.config.isFlagEnabled(qe.KeyboardInput)),this.setGamePadInputEnabled(this.config.isFlagEnabled(qe.GamepadInput))}handleIceCandidate(e){Y.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&&(Y.Info("Local ICE candidate generated: "+JSON.stringify(e.candidate)),this.protocol.sendMessage(Mn(fn,{candidate:e.candidate})))}handleDataChannel(e){Y.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 Y.Error(`handleSendWebRTCOffer was called with type ${e.type} - it only expects "offer"`);Y.Info("Sending the offer to the Server");const t={sdp:e.sdp,minBitrateBps:1e3*this.config.getNumericSettingValue(Ke.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(Ke.WebRTCMaxBitrate)};this.protocol.sendMessage(Mn(pn,t)),this.pixelStreaming._onWebRtcSdpOffer(e)}handleSendWebRTCAnswer(e){if("answer"!==e.type)return void Y.Error(`handleSendWebRTCAnswer was called with type ${e.type} - it only expects "answer"`);Y.Info("Sending the answer to the Server");const t={sdp:e.sdp,minBitrateBps:1e3*this.config.getNumericSettingValue(Ke.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(Ke.WebRTCMaxBitrate)};this.protocol.sendMessage(Mn(mn,t)),this.isUsingSFU&&this.protocol.sendMessage(Mn(bn)),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){Y.Info(`MinQP=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MinQP":e})])}sendEncoderMaxQP(e){Y.Info(`MaxQP=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MaxQP":e})])}sendEncoderMinQuality(e){Y.Info(`MinQuality=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MinQuality":e})])}sendEncoderMaxQuality(e){Y.Info(`MaxQuality=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MaxQuality":e})])}sendWebRTCMinBitrate(e){Y.Info(`WebRTC Min Bitrate=${e}`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MinBitrate":e})])}sendWebRTCMaxBitrate(e){Y.Info(`WebRTC Max Bitrate=${e}`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxBitrate":e})])}sendWebRTCFps(e){Y.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(){Y.Info("---- Sending show stat to UE ----"),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"stat.fps":""})])}sendIframeRequest(){Y.Info("---- Sending Request for an IFrame ----"),this.streamMessageController.toStreamerHandlers.get("IFrameRequest")()}emitUIInteraction(e){Y.Info("---- Sending custom UIInteraction message ----"),this.streamMessageController.toStreamerHandlers.get("UIInteraction")([JSON.stringify(e)])}emitCommand(e){Y.Info("---- Sending custom Command message ----"),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(e)])}emitConsoleCommand(e){Y.Info("---- Sending custom Command:ConsoleCommand message ----"),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({ConsoleCommand:e})])}sendRequestQualityControlOwnership(){Y.Info("---- Sending Request to Control Quality ----"),this.toStreamerMessagesController.SendRequestQualityControl()}sendTextboxEntry(e){var t;Y.Info("---- Sending TextboxEntry message ----"),null===(t=this.streamMessageController.toStreamerHandlers.get("TextboxEntry"))||void 0===t||t([e])}handleLatencyTestResult(e){Y.Info("DataChannelReceiveMessageType.latencyTest");const t=new TextDecoder("utf-16").decode(e.slice(1)),n=new Zn;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){Y.Info("DataChannelReceiveMessageType.dataChannelLatencyResponse");const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);this.pixelStreaming._onDataChannelLatencyTestResponse(n)}handleInitialSettings(e){Y.Info("DataChannelReceiveMessageType.InitialSettings");const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t),s=new Gn;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(qe.HoveringMouseMode,!!n.ConfigOptions.DefaultToHover),s.ueCompatible(),Y.Info(t),this.pixelStreaming._onInitialSettings(s)}handleVideoEncoderAvgQP(e){Y.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);Y.Info("DataChannelReceiveMessageType.QualityControlOwnership"),this.isQualityController=new Boolean(t[1]).valueOf(),Y.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(qe.HoveringMouseMode)?tt.HoveringMouse:tt.LockedMouse;this.mouseController=this.inputClassesFactory.registerMouse(e)}}setTouchInputEnabled(e){var t;null===(t=this.touchController)||void 0===t||t.unregister(),e&&(this.touchController=this.inputClassesFactory.registerTouch(this.config.isFlagEnabled(qe.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 ye({label:e,event:t})),e.onClose=(e,t)=>this.pixelStreaming.dispatchEvent(new ve({label:e,event:t})),e.onError=(e,t)=>this.pixelStreaming.dispatchEvent(new Se({label:e,event:t}))}registerMessageHandler(e,t,n){t===ms.FromStreamer&&void 0===n&&Y.Warning(`Unable to register handler for ${e} as no handler was passed`),this.streamMessageController.registerMessageHandler(t,e,s=>void 0===n&&t===ms.ToStreamer?this.sendMessageController.sendMessageToStreamer(e,s):n(s))}}class Ps{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=us(e.gamepad)),this.controllers[r].currentState=us(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 Is{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 Ps(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 Y.Error("This browser does not support XR.");navigator.xr.requestSession("immersive-vr",{optionalFeatures:[]}).then(e=>{this.onXrSessionStarted(e)})}}onXrSessionEnded(){Y.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){Y.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(qe.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 We({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&&Y.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 xs{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 Ls{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 Y.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 xs(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 As{constructor(e,t){this.allowConsoleCommands=!1,this.config=e,(null==t?void 0:t.videoElementParent)&&(this._videoElementParent=t.videoElementParent),this._eventEmitter=new je,this.configureSettings(),this.setWebRtcPlayerController(new Rs(this.config,this)),this._webXrController=new Is(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(qe.IsQualityController,e=>{!0!==e||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()}),this.config._addOnSettingChangedListener(qe.AFKDetection,e=>{this._webRtcController.setAfkEnabled(e)}),this.config._addOnSettingChangedListener(qe.MatchViewportResolution,()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()}),this.config._addOnSettingChangedListener(qe.HoveringMouseMode,e=>{this.config.setFlagLabel(qe.HoveringMouseMode,`Control Scheme: ${e?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(qe.MouseInput))}),this.config._addOnSettingChangedListener(qe.KeyboardInput,e=>{this._webRtcController.setKeyboardInputEnabled(e)}),this.config._addOnSettingChangedListener(qe.MouseInput,e=>{this._webRtcController.setMouseInputEnabled(e)}),this.config._addOnSettingChangedListener(qe.FakeMouseWithTouches,e=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(qe.TouchInput))}),this.config._addOnSettingChangedListener(qe.TouchInput,e=>{this._webRtcController.setTouchInputEnabled(e)}),this.config._addOnSettingChangedListener(qe.GamepadInput,e=>{this._webRtcController.setGamePadInputEnabled(e)}),this.config._addOnNumericSettingChangedListener(Ke.MinQP,e=>{Y.Info("-------- Sending MinQP --------"),this._webRtcController.sendEncoderMinQP(e),Y.Info("-------------------------------------------");const t=Math.trunc(100*(1-e/51));this.config.setNumericSetting(Ke.CompatQualityMax,t)}),this.config._addOnNumericSettingChangedListener(Ke.MaxQP,e=>{Y.Info("-------- Sending MaxQP --------"),this._webRtcController.sendEncoderMaxQP(e),Y.Info("-------------------------------------------");const t=Math.trunc(100*(1-e/51));this.config.setNumericSetting(Ke.CompatQualityMin,t)}),this.config._addOnNumericSettingChangedListener(Ke.MinQuality,e=>{Y.Info("-------- Sending MinQuality --------"),this._webRtcController.sendEncoderMinQuality(e),Y.Info("-------------------------------------------"),this.config.setNumericSetting(Ke.CompatQualityMin,e)}),this.config._addOnNumericSettingChangedListener(Ke.MaxQuality,e=>{Y.Info("-------- Sending MaxQuality --------"),this._webRtcController.sendEncoderMaxQuality(e),Y.Info("-------------------------------------------"),this.config.setNumericSetting(Ke.CompatQualityMax,e)}),this.config._addOnNumericSettingChangedListener(Ke.CompatQualityMin,e=>{e=51-e/100*51,Y.Info("-------- Sending MinQP from quality value --------"),this._webRtcController.sendEncoderMaxQP(e),Y.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(Ke.CompatQualityMax,e=>{e=51-e/100*51,Y.Info("-------- Sending MaxQP from quality value --------"),this._webRtcController.sendEncoderMinQP(e),Y.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(Ke.WebRTCMinBitrate,e=>{Y.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCMinBitrate(1e3*e),Y.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(Ke.WebRTCMaxBitrate,e=>{Y.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCMaxBitrate(1e3*e),Y.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(Ke.WebRTCFPS,e=>{Y.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCFps(e),Y.Info("-------------------------------------------")}),this.config._addOnOptionSettingChangedListener(Ye.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(Ye.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Ce),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Me),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Te),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(qe.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 Y.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):Y.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:[])Wn.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 Y.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):Y.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:[])Wn.canTransceiverSendVideo(r)&&(r.sender.track.enabled=!e)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new ue)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new ce)}_onWebRtcSdpOffer(e){this._eventEmitter.dispatchEvent(new he({sdp:e}))}_onWebRtcSdpAnswer(e){this._eventEmitter.dispatchEvent(new de({sdp:e}))}_onLatencyCalculated(e){this._eventEmitter.dispatchEvent(new De({latencyInfo:e}))}_onStreamLoading(){this._eventEmitter.dispatchEvent(new we)}_onDisconnect(e,t){this._eventEmitter.dispatchEvent(new fe({eventString:e,allowClickToReconnect:t}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new pe)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new me)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new ge)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new be),this._videoStartTime=Date.now()}_onLatencyTestResult(e){this._eventEmitter.dispatchEvent(new Oe({latencyTimings:e}))}_onDataChannelLatencyTestResponse(e){this._eventEmitter.dispatchEvent(new Ne({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 xe({aggregatedStats:e}))}_onVideoEncoderAvgQP(e){this._eventEmitter.dispatchEvent(new le({avgQP:e}))}_onInitialSettings(e){var t;this._eventEmitter.dispatchEvent(new Ve({settings:e})),e.PixelStreamingSettings&&(this.allowConsoleCommands=null!==(t=e.PixelStreamingSettings.AllowPixelStreamingCommands)&&void 0!==t&&t,!1===this.allowConsoleCommands&&Y.Info("-AllowPixelStreamingCommands=false, sending arbitrary console commands from browser to UE is disabled."));const n=this.config.useUrlParams,s=new ks(window.location.search);Y.Info(`using URL parameters ${n}`),e.EncoderSettings&&(e.EncoderSettings.MinQP&&(this.config.setNumericSetting(Ke.MinQP,n&&s.has(Ke.MinQP)?Number.parseFloat(s.get(Ke.MinQP)):e.EncoderSettings.MinQP||0),this.config.setNumericSetting(Ke.MaxQP,n&&s.has(Ke.MaxQP)?Number.parseFloat(s.get(Ke.MaxQP)):e.EncoderSettings.MaxQP||51)),e.EncoderSettings.MinQuality&&(this.config.setNumericSetting(Ke.MinQuality,n&&s.has(Ke.MinQuality)?Number.parseFloat(s.get(Ke.MinQuality)):e.EncoderSettings.MinQuality||0),this.config.setNumericSetting(Ke.MaxQuality,n&&s.has(Ke.MaxQuality)?Number.parseFloat(s.get(Ke.MaxQuality)):e.EncoderSettings.MaxQuality||100)),n&&(s.has(Ke.CompatQualityMin)&&this.config.setNumericSetting(Ke.CompatQualityMin,Number.parseFloat(s.get(Ke.CompatQualityMin))),s.has(Ke.CompatQualityMax)&&this.config.setNumericSetting(Ke.CompatQualityMax,Number.parseFloat(s.get(Ke.CompatQualityMax))))),e.WebRTCSettings&&(this.config.setNumericSetting(Ke.WebRTCMinBitrate,n&&s.has(Ke.WebRTCMinBitrate)?Number.parseFloat(s.get(Ke.WebRTCMinBitrate)):e.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(Ke.WebRTCMaxBitrate,n&&s.has(Ke.WebRTCMaxBitrate)?Number.parseFloat(s.get(Ke.WebRTCMaxBitrate)):e.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(Ke.WebRTCFPS,n&&s.has(Ke.WebRTCFPS)?Number.parseFloat(s.get(Ke.WebRTCFPS)):e.WebRTCSettings.FPS))}_onQualityControlOwnership(e){this.config.setFlagEnabled(qe.IsQualityController,e)}_onPlayerCount(e){this._eventEmitter.dispatchEvent(new $e({count:e}))}_onSubscribeFailed(e){this._eventEmitter.dispatchEvent(new Be({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 He),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 Ls(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),e=>{this._eventEmitter.dispatchEvent(new Ue({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!==ms.FromStreamer||void 0!==n?t===ms.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)):Y.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"}(gs||(gs={}));class Os{type=gs.VideoInitialised}class Ds{type=gs.DataChannelOpen}class Fs{msg;type=gs.DataChannelResponse;constructor(e){this.msg=e}}class Ns{stats;type=gs.WebRtcStats;constructor(e){this.stats=e}}var Us,Bs=o(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.SwitchRendererRequest="switch_renderer_request"}(Us||(Us={}));const Vs="3.16.2";var _s=o(838),Ws=o(992);const $s="sessionEndedDueToConnectionLoss",Hs="sessionEndedDueToVideoPlaybackError",js="sessionEndedDueToRendererError";var zs,qs,Qs,Ks,Gs;function Xs(e,t,n){return Math.max(t,Math.min(e,n))}function Js(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"}(zs||(zs={})),function(e){e.Always="always",e.WhenDegraded="when-degraded",e.Hidden="hidden"}(qs||(qs={})),function(e){e.TopLeft="top-left",e.TopRight="top-right",e.BottomLeft="bottom-left",e.BottomRight="bottom-right"}(Qs||(Qs={})),function(e){e.Click="click",e.Hover="hover",e.None="none"}(Ks||(Ks={}));class Ys{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 l.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 l.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 l.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,p=s>0?8*(e.video.bytesReceived-t.video.bytesReceived)/s/1e3:0,m=1e3*e.connection.currentRoundTripTime,g=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?Xs(55-4.6*Math.log(s),0,30):6,o=Xs(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 Xs(Math.round(100*a)/100,1,5)}({packetLoss:a,bitrate:1e3*l,roundTripTime:m,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=Xs(.56*Math.log(d)+5.36,1,5)-1.9*Math.log(a/o)-.002*c;return Xs(Math.round(100*h)/100,1,5)}({bitrate:1e3*p,roundTripTime:m,width:e.video.frameWidth,height:e.video.frameHeight,frameRate:e.video.framesPerSecond,expectedFrameRate:f,codec:v}),b=Math.min(g,S);let w;return w=b>=3.5?zs.Good:b>=2.5?zs.Fair:zs.Poor,{audioPacketLossPercent:Math.round(100*a)/100,videoPacketLossPercent:Math.round(100*u)/100,audioBitrateKbps:Math.round(l),videoBitrateKbps:Math.round(p),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*m)/100,audioMos:g,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:r,audioLevel:o}=e;l.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: ${r},\n Audio level (0-1): ${o??"N/A"}`),0===n&&l.A.warn("WebRTC Connection - Audio - No audio packets received — remote is probably not sending audio."),s>0&&l.A.warn(`WebRTC Connection - Audio - packet loss detected: ${s} packets lost.`),void 0===o?l.A.warn("WebRTC Connection - Audio - Audio level not available in stats."):0===o?l.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."):o<.02?l.A.warn("WebRTC Connection - Audio - Audio level is very low — audio might be too quiet."):l.A.info("WebRTC Connection - Audio - Audio level looks normal, digital human is likely speaking.")}logElementStatus(e){const t=Js(this.videoElement),n=t?this.videoElement:this.audioElement;l.A.debug(`Audio plays from ${t?"video":"separate audio"} element (DisableAudioSync=${t?"false":"true"}).`),l.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"})`),l.A.debug(`Playback element muted: ${n?.muted}, (should be false to be able to hear the digital human)`),l.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&&(l.A.debug(`Playback element can play webrtc audio codec (${s}) : ${n.canPlayType(s)}, (should be 'probably' or 'maybe)'`),"audio/opus"===s&&l.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"}(Gs||(Gs={}));const Zs=e=>e??"speech-recognition-service",ei=e=>"pixel-streaming"===e||"both"===e,ti=e=>"speech-recognition-service"===e||"both"===e,ni="#6b7280";class si{videoContainerElement;container;panel;bars=[];panelVisible=!1;lastMetrics;visibility;position;popupTrigger;onClickBound;onMouseEventBound;onDocumentClickBound;onMouseEnterBound;onMouseLeaveBound;hoverHideTimeout;originalParentPosition;constructor(e,t){this.videoContainerElement=e,this.visibility=t.visibility??qs.WhenDegraded,this.position=t.position??Qs.TopRight,this.popupTrigger=t.popupTrigger??Ks.Click,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.visibility!==qs.Hidden&&this.createElements()}createElements(){"static"===getComputedStyle(this.videoContainerElement).position&&(this.originalParentPosition=this.videoContainerElement.style.position,this.videoContainerElement.style.position="relative"),this.container=document.createElement("div"),this.container.setAttribute("data-testid","network-indicator"),this.container.setAttribute("role","status"),this.container.setAttribute("aria-live","polite"),this.container.setAttribute("aria-label","Network quality: unknown"),Object.assign(this.container.style,{position:"absolute",zIndex:"1000",cursor:"pointer",padding:"6px 7px",borderRadius:"4px",background:"rgba(0, 0, 0, 0.5)",display:"none",alignItems:"flex-end",gap:"2px",pointerEvents:"auto",...this.getPositionStyles()});const e=[6,12,18];for(const t of e){const e=document.createElement("div");e.setAttribute("data-testid","network-indicator-bar"),Object.assign(e.style,{width:"4px",height:`${t}px`,borderRadius:"1px",background:ni,transition:"background 0.3s ease"}),this.bars.push(e),this.container.appendChild(e)}this.container.addEventListener("mousedown",this.onMouseEventBound),this.container.addEventListener("mouseup",this.onMouseEventBound),this.popupTrigger===Ks.Click?this.container.addEventListener("click",this.onClickBound):this.popupTrigger===Ks.Hover&&(this.container.addEventListener("mouseenter",this.onMouseEnterBound),this.container.addEventListener("mouseleave",this.onMouseLeaveBound)),this.popupTrigger===Ks.None&&(this.container.style.cursor="default"),this.videoContainerElement.appendChild(this.container)}getPositionStyles(){const e="8px";switch(this.position){case Qs.TopLeft:return{top:e,left:e};case Qs.TopRight:return{top:e,right:e};case Qs.BottomLeft:return{bottom:e,left:e};case Qs.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()}onMouseEnter(){clearTimeout(this.hoverHideTimeout),this.showPanel()}onMouseLeave(){this.scheduleHoverHide()}scheduleHoverHide(){clearTimeout(this.hoverHideTimeout),this.hoverHideTimeout=setTimeout(()=>this.hidePanel(),50)}showPanel(){this.container&&this.lastMetrics&&(this.panel||(this.panel=document.createElement("div"),this.panel.setAttribute("data-testid","network-indicator-panel"),Object.assign(this.panel.style,{position:"fixed",padding:"10px",borderRadius:"6px",background:"rgba(0, 0, 0, 0.85)",color:"#ffffff",fontSize:"11px",fontFamily:"system-ui, -apple-system, sans-serif",whiteSpace:"nowrap",lineHeight:"1.6",minWidth:"180px",zIndex:"10001",pointerEvents:"auto"}),this.popupTrigger===Ks.Hover&&(this.panel.addEventListener("mouseenter",this.onMouseEnterBound),this.panel.addEventListener("mouseleave",this.onMouseLeaveBound)),document.body.appendChild(this.panel)),this.updatePanel(),this.positionPanel(),this.panel.style.display="block",this.panelVisible=!0,document.addEventListener("click",this.onDocumentClickBound))}hidePanel(){this.panel&&(this.panel.style.display="none"),this.panelVisible=!1,document.removeEventListener("click",this.onDocumentClickBound)}positionPanel(){if(!this.panel||!this.container)return;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===Qs.TopLeft||this.position===Qs.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.getColor(e.qualityLevel);this.panel.innerHTML=[`<div style="font-weight:600;margin-bottom:4px;color:${t}">${e.qualityLevel} Quality</div>`,this.panelSectionHeader("Quality Score (MOS)"),this.panelRow("Audio",e.audioMos.toFixed(1)+" / 5.0"),this.panelRow("Video",e.videoMos.toFixed(1)+" / 5.0"),this.panelSectionHeader("Connection"),this.panelRow("Round Trip",`${e.roundTripTimeMs} ms`),this.panelRow("Packet Loss",`${e.audioPacketLossPercent}% audio / ${e.videoPacketLossPercent}% video`),this.panelRow("Jitter",`${e.audioJitterMs} ms audio / ${e.videoJitterMs} ms video`),this.panelSectionHeader("Throughput"),this.panelRow("Bitrate",`${e.audioBitrateKbps} audio / ${e.videoBitrateKbps} video kbps`),this.panelRow("Frame Rate",`${e.frameRate} fps`)].join("")}panelSectionHeader(e){return`<div style="color:#6b7280;font-size:10px;text-transform:uppercase;letter-spacing:0.5px;margin-top:6px;margin-bottom:2px">${e}</div>`}panelRow(e,t){return`<div style="display:flex;justify-content:space-between;gap:12px"><span style="color:#9ca3af">${e}</span><span>${t}</span></div>`}getColor(e){switch(e){case zs.Good:return"#22c55e";case zs.Fair:return"#eab308";case zs.Poor:return"#ef4444"}}update(e){if(this.lastMetrics=e,!this.container)return;this.container.setAttribute("aria-label",`Network quality: ${e.qualityLevel}`);const t=this.getColor(e.qualityLevel),n=e.qualityLevel===zs.Good?3:e.qualityLevel===zs.Fair?2:1;this.bars.forEach((e,s)=>{e.style.background=s<n?t:ni}),this.visibility===qs.WhenDegraded?this.container.style.display=e.qualityLevel===zs.Good?"none":"flex":this.container.style.display="flex",this.panelVisible&&(this.updatePanel(),this.positionPanel())}destroy(){this.container&&(this.container.removeEventListener("click",this.onClickBound),this.container.removeEventListener("mousedown",this.onMouseEventBound),this.container.removeEventListener("mouseup",this.onMouseEventBound),this.container.removeEventListener("mouseenter",this.onMouseEnterBound),this.container.removeEventListener("mouseleave",this.onMouseLeaveBound),this.container.remove(),this.container=void 0),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),this.bars=[],this.panelVisible=!1,this.lastMetrics=void 0}}class ii{session;connectionUrl;videoContainerElement;stream;messages=new X;videoElement;audioElement;videoInitialized=!1;dataChannelOpen=!1;sceneReady=!1;maxReconnectAttempts=4;reconnectionAttempts=0;allowReconnection=!0;reconnectTimeoutId;baseReconnectDelayMs=500;maxReconnectDelayMs=1e4;audioStatsInternal;freezeCount=0;lastDecodedFrames=0;lastCheckTime=Date.now();audioStatsAnalyzer;networkQualityInterval;networkIndicator;config;clientMessages;_audioUpstreamMode;constructor(e,t,n){this.session=e,this.connectionUrl=t,this.videoContainerElement=n,this.config=e.config,this.clientMessages=e.messages,this._audioUpstreamMode=Zs(this.config.audioUpstreamMode)}get audioUpstreamMode(){return this._audioUpstreamMode}init(){l.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 _s.qw);const e=ei(this.audioUpstreamMode);"speech-recognition-service"!==this.audioUpstreamMode&&l.A.info(`audioUpstreamMode='${this.audioUpstreamMode}' is beta; behaviour may change.`);const t=new et({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 As(t,{videoElementParent:this.videoContainerElement}),Y.InitLogging(z.Warning,!1),this.stream.setSignallingUrlBuilder(function(){let e=t.getTextSettingValue(Xe.SignallingServerUrl);return t.isFlagEnabled(qe.BrowserSendOffer)&&(e+=(e.includes("?")?"&":"?")+qe.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}})=>{l.A.trace("WebRTC: VideoEncoderAvgQP - lower is better, ranges from 0 to 51:",e)}),this.stream?.addEventListener("webRtcAutoConnect",()=>{l.A.debug("WebRTC: AutoConnect triggered")}),this.stream?.addEventListener("webRtcConnected",this.handleWebRtcConnectedMessage.bind(this)),this.stream?.addEventListener("statsReceived",({data:{aggregatedStats:e}})=>{l.A.trace("WebRTC: StatsReceived",e)}),this.stream?.addEventListener("webRtcTCPRelayDetected",()=>{l.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:Us.ClientInfo,uneeqJsSdkVersion:Vs}))}),this.stream?.signallingProtocol.on(Us.Error,e=>{l.A.error("Signaling: Received error message from server",e),this.clientMessages?.next(new _s.Cj(`Signaling server error: ${e}`))}),this.stream?.signallingProtocol.on(Us.IndexInQueue,this.handleIndexInQueueMessage.bind(this)),this.stream?.signallingProtocol.on(Us.RendererTaken,this.handleRendererTakenMessage.bind(this)),this.stream?.signallingProtocol.on(Us.RendererGone,this.handleRendererGoneEvent.bind(this)),this.stream?.signallingProtocol.on(Us.SwitchRendererRequest,this.handleSwitchRendererRequestEvent.bind(this)),this.stream?.signallingProtocol.on(Us.CustomerConcurrencyLimitReached,this.handleCustomerConcurrencyLimitReachedMessage.bind(this)),this.stream?.signallingProtocol.on(Us.RendererError,this.handleRendererErrorMessage.bind(this)),this.stream?.signallingProtocol.on(Us.Config,this.checkForStubbedTurnConfig.bind(this))}checkForStubbedTurnConfig(e){const t=e?.peerConnectionOptions?.iceServers??[];l.A.info("Signaling: Received ice config message with urls:",t.map(e=>({urls:e.urls}))),t.some(e=>e.username?.includes("disabled")&&e.urls?.some(e=>e.includes("0.0.0.0")))&&l.A.warn("Signaling: TURN server configuration is stubbed (turn:0.0.0.0 with disabled credentials). This should be intentional, is intended for locally run renderers e.g. kiosk, miniprem etc.")}handleWebSocketError(e){l.A.error("Signaling: WebSocket error",l.A.serialiseError(e)),this.reconnectIfSafe(e)}handleVideoInitialized(){l.A.info("Video initialized."),this.videoElement=this.videoContainerElement?.getElementsByTagName("video")[0],this.audioElement=this.stream?.webRtcController?.streamController?.audioElement,this.audioStatsAnalyzer=new Ys(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)l.A.warn("Video autoplay blocked by browser. Requesting user gesture to resume playback."),this.clientMessages?.next(new _s.MA);else{const t="Fatal Error: Digital Human video cannot be played.";l.A.error(t,l.A.serialiseError(e)),this.clientMessages?.next(new _s.Cj(t)),this.endSession(Hs,!0)}}),this.videoInitialized=!0,this.messages.next(new Os),this.reconnectionAttempts=0,this.clearReconnectTimer();else{const e="Fatal Error: Video element not found.";l.A.error(e),this.clientMessages?.next(new _s.Cj(e)),this.endSession(Hs,!0)}setTimeout(()=>{this.clientMessages?.next(new _s.xQ)},fi)}getAudioPlaybackElement(){return Js(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(()=>{l.A.info("Audio playback successfully started."),this.clientMessages?.next(new _s.M8)}).catch(n=>{l.A.warn("Audio cannot be played.",n),this.clientMessages?.next(new _s.Tu),t?(e.muted=!0,e.play().then(()=>{this.clientMessages?.next(new _s.XC)}).catch(e=>{l.A.warn("Muted video reveal also blocked.",e),this.clientMessages?.next(new _s.Cj(`Video playback failed: ${e}`))})):this.clientMessages?.next(new _s.XC)})}resumeVideoPlayback(){this.videoElement?this.videoElement.play().then(()=>{this.playAudioElement()}).catch(e=>{l.A.error("Video playback failed after user gesture",l.A.serialiseError(e)),this.clientMessages?.next(new _s.Cj("Video playback failed after user gesture")),this.endSession("sessionEndedDueToPermissionsError",!0)}):l.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 _s.Tu)):this.handleMissingAudioElement()}muteUpstreamMic(){ei(this.audioUpstreamMode)?this.stream?this.stream.muteMicrophone():l.A.warn("muteUpstreamMic called before PixelStreaming stream is initialised; ignoring."):l.A.warn(`muteUpstreamMic called in '${this.audioUpstreamMode}' mode — no PS upstream audio track to mute; ignoring.`)}unmuteUpstreamMic(){ei(this.audioUpstreamMode)?this.stream?this.stream.unmuteMicrophone(!1):l.A.warn("unmuteUpstreamMic called before PixelStreaming stream is initialised; ignoring."):l.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(()=>{l.A.info(`Speaker device set to: ${t}`)}).catch(e=>{l.A.error(`Failed to set speaker device: ${t}`,l.A.serialiseError(e))}):l.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.";l.A.error(e),this.clientMessages?.next(new _s.Cj(e))}startAudioStatsMonitor(e=5e3){this.stopAudioStatsMonitor(),l.A.info("Starting audio stats monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new Ys(this.stream,this.videoElement,this.audioElement)),this.audioStatsInternal=setInterval(()=>{this.audioStatsAnalyzer?.analyzeAudioStats().catch(e=>{l.A.error("Error analyzing audio stats",l.A.serialiseError(e))})},e)}stopAudioStatsMonitor(){this.audioStatsInternal&&clearInterval(this.audioStatsInternal)}startNetworkQualityMonitor(e){this.stopNetworkQualityMonitor(),l.A.info("Starting network quality monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new Ys(this.stream,this.videoElement,this.audioElement)),this.videoContainerElement&&e.visibility!==qs.Hidden&&(this.networkIndicator=new si(this.videoContainerElement,e));const t=e.collectionIntervalMs??3e3;this.networkQualityInterval=setInterval(()=>{this.audioStatsAnalyzer?.collectNetworkQuality(e).then(e=>{e&&(this.networkIndicator?.update(e),this.clientMessages?.next(new _s.N8(e)))}).catch(e=>{l.A.error("Error collecting network quality",l.A.serialiseError(e))})},t)}stopNetworkQualityMonitor(){this.networkQualityInterval&&(clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0),this.networkIndicator&&(this.networkIndicator.destroy(),this.networkIndicator=void 0)}handleDataChannelOpen(){l.A.info("DataChannelOpen"),this.dataChannelOpen=!0,this.messages.next(new Ds)}handleWebRtcFailed(e){l.A.error("WebRTC failed",e),this.reconnectIfSafe(e)}handleWebRtcDisconnected(e){l.A.warn(`WebRTC disconnected, message: ${e?.data?.eventString}, allowClickToReconnect: ${e?.data?.allowClickToReconnect}`),this.reconnectIfSafe(e)}handleWebRtcStats(e){const t=new Ns(e.data.aggregatedStats);this.messages.next(t);const n=e.data.aggregatedStats.inboundVideoStats?.framesDecoded??0;this.checkForFreeze(n)}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);l.A.warn(`[WebRTC] Video FROZEN for ${e}s (count=${this.freezeCount})`),this.freezeCount>=3&&(l.A.error("[WebRTC] Video frozen 3 times in a row, transferring session..."),this.session.sessionTransferManager.transferSession(),this.freezeCount=0)}else this.freezeCount=0,this.lastDecodedFrames=e,this.lastCheckTime=t;else l.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);l.A.info(`Scheduling reconnection attempt ${this.reconnectionAttempts} in ${e}ms`),this.reconnectTimeoutId=setTimeout(()=>{l.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?(l.A.debug("Checking if should attempt reconnection after event",e),this.reconnectionAttempts<this.maxReconnectAttempts?(this.reconnectionAttempts++,this.clientMessages?.next(new _s.fI),this.scheduleReconnect()):(l.A.info("Max reconnection attempts reached. Ending session."),this.clientMessages?.next(new _s.JP),this.endSession($s,!1))):l.A.warn("Reconnection already scheduled or reconnecting is disabled")}catch(e){l.A.error("Error during reconnection attempt",l.A.serialiseError(e)),this.clientMessages?.next(new _s.Cj("Error during reconnection attempt")),this.endSession($s,!1)}}handleDataChannelMessage(e){l.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 Fs(t))}catch(e){l.A.error("Signaling: Failed to parse engine response",l.A.serialiseError(e))}}handleIndexInQueueMessage(e){try{const t=Number(e.message);this.clientMessages?.next(new _s.F8(t))}catch(e){l.A.error("Signaling: Failed to parse position in queue message",l.A.serialiseError(e))}}handleRendererTakenMessage(e){try{const t=e;this.clientMessages?.next(new _s.qo(t.message)),l.A.info("Signaling: Renderer taken event",t.message)}catch(e){l.A.error("Signaling: Failed to parse renderer taken message",l.A.serialiseError(e))}}handleWebRtcConnectedMessage(){this.clientMessages?.next(new _s.Cl),l.A.info("Signaling: WebRTC connected")}handleRendererGoneEvent(e){l.A.info("Signaling: Renderer gone event",e),this.reconnectIfSafe(e)}handleSwitchRendererRequestEvent(e){l.A.info("Signaling: Renderer switch renderer request event",e),this.session.sessionTransferManager.transferSession()}handleCustomerConcurrencyLimitReachedMessage(e){l.A.warn("Signaling: Customer concurrency limit reached message received",e),this.clientMessages?.next(new _s.MM)}handleRendererErrorMessage(e){try{const t=e,n=t.code??-1,s=t.message??"An unknown renderer error occurred";l.A.error(`Signaling: Renderer error received - code: ${n}, message: ${s}`),this.clientMessages?.next(new _s.j_(n,s)),this.endSession(js,!0)}catch(e){l.A.error("Signaling: Failed to parse renderer error message",l.A.serialiseError(e)),this.clientMessages?.next(new _s.j_(-1,"An unknown renderer error occurred")),this.endSession(js,!0)}}socketSend(e){l.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===Ws.A.ChatPrompt){const n=t.data?.requestId;l.A.info(`Signaling: Sending data channel message — action=chat_prompt, requestId=${n??"unknown"}`),(!(e instanceof Bs.D)||e.shouldEmitPromptRequest)&&this.clientMessages?.next(new _s.bS(t.data))}else l.A.info("Signaling: Sending data channel message",JSON.stringify(t));this.stream?.emitUIInteraction(e)}dataSendBinary(e){l.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){l.A.info("Signaling: Ending session"),this.clearReconnectTimer(),this.stopNetworkQualityMonitor(),this.socketSend({message:e,type:Us.ClientGone,sessionId:this.config.sessionId}),this.streamDisconnect(),l.A.info("Session has ended, reason: "+e),t&&this.clientMessages?.next(new _s.aY(e))}streamDisconnect(){l.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(){l.A.info("Signaling: Start soft switching"),this.clientMessages?.next(new _s.sF)}stopSoftSwitch(){l.A.info("Signaling: Stop soft switching"),this.clientMessages?.next(new _s.WQ)}}var ri;!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"}(ri||(ri={}));var oi,ai,li=o(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"}(oi||(oi={})),function(e){e.Left="left",e.Right="right",e.Center="center",e.Centre="centre"}(ai||(ai={}));class ci{position;duration;requestId;constructor(e,t=2e3,n=(0,li.g)()){this.position=e,this.duration=t,this.requestId=n}toJSON(){return{action:Ws.A.CameraAnchor,data:{requestId:this.requestId,position:this.position,transition_duration_ms:this.duration}}}}class di{avatarId;requestId;constructor(e,t=(0,li.g)()){this.avatarId=e,this.requestId=t}toJSON(){return{action:Ws.A.ChangeAvatar,data:{id:this.avatarId,requestId:this.requestId}}}}class hi{url;requestId;constructor(e,t=(0,li.g)()){this.url=e,this.requestId=t}toJSON(){return{action:Ws.A.LoadBackground,data:{url:this.url,requestId:this.requestId}}}}class ui{actionName;requestId;constructor(e,t=(0,li.g)()){this.actionName=e,this.requestId=t}toJSON(){return{action:Ws.A.TriggerAction,data:{action_name:this.actionName,requestId:this.requestId}}}}var pi=o(33);class mi{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()&&(l.A.info("Session transfer via keyboard shortcut triggered"),this.transferSession())})}transferSession(){this.isTransferSessionInProgress?l.A.warn("Transfer already in progress, skipping"):(this.isTransferSessionInProgress=!0,l.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){l.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(),l.A.info("Session transfer complete")},1e3))}}const gi=[1103,1200,1402],fi=750;class yi{config;id;signaling;messages=new Q;speechRec;promptMetadata={};audioStreamId;sessionTransferManager;jwt;welcomeRequested=!1;resolutionLogged=!1;sttPausedByHost=!1;_audioUpstreamMode;constructor(e){this.config=e,this.sessionTransferManager=new mi(this),this._audioUpstreamMode=Zs(this.config.audioUpstreamMode)}get audioUpstreamMode(){return this._audioUpstreamMode}updatePromptMetadata(e){try{JSON.parse(JSON.stringify(e)),this.promptMetadata.custom=e,this.messages.next(new _s.ss(this.promptMetadata))}catch(t){l.A.error("Error parsing custom metadata",e,l.A.serialiseError(t))}}setEnableMicrophone(e){const t=this.audioUpstreamMode;this.config.enableMicrophone=e,this.sttPausedByHost=!1;let n=!1;ti(t)&&(this.speechRec?(e?this.speechRec.startRecognition():this.speechRec.stopRecognition(),n=!0):l.A.warn("setEnableMicrophone: STT leg is configured but speech recognition is not initialised yet")),ei(t)&&(this.signaling?(e?this.signaling.unmuteUpstreamMic():this.signaling.muteUpstreamMic(),n=!0,ti(t)||this.messages.next(new _s.WY(e))):l.A.warn("setEnableMicrophone: PS leg is configured but signaling is not initialised yet")),n||l.A.warn(`setEnableMicrophone(${e}) had nothing to do in mode '${t}' — session not ready?`)}pauseSpeechRecognition(){return this.sttPausedByHost=!0,this.speechRec?this.speechRec.pause():(l.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():(l.A.warn("resumeSpeechRecognition: pause intent cleared, but speech recognition is not initialised yet — nothing to resume"),!1)}setCameraAnchorDistance(e,t=0,n=this.signaling){this.config.cameraAnchorDistance=e,n?.dataSend(new ci(e,t))}setCameraAnchorHorizontal(e,t=0,n=this.signaling){this.config.cameraAnchorHorizontal=e,n?.dataSend(new ci(e,t))}changeAvatar(e,t=this.signaling){t?.dataSend(new di(e))}loadBackground(e,t=this.signaling){t?.dataSend(new hi(e))}userStartSpeaking(e=this.signaling){e?.dataSend(new pi.A(pi.f.Start))}userStopSpeaking(e=this.signaling){e?.dataSend(new pi.A(pi.f.Stop))}triggerAction(e,t=this.signaling){t?.dataSend(new ui(e))}resumeVideoPlayback(){this.signaling?.resumeVideoPlayback()}createSession(){this.messages.subscribe(e=>{if(this.config.messageHandler&&this.config.messageHandler(e),e.uneeqMessageType===_s.Yg.SoftSwitchFinished||e.uneeqMessageType===_s.Yg.SessionReconnectingFinished){if(!ti(this.audioUpstreamMode))return;if(this.config.enableMicrophone&&!this.sttPausedByHost)e.uneeqMessageType===_s.Yg.SessionReconnectingFinished?(l.A.info("Session, resuming speech recognition after reconnect"),this.speechRec?.resume()):(l.A.info("Session, restarting speech recognition after soft switch"),this.speechRec?.startRecognition());else{const t=e.uneeqMessageType===_s.Yg.SoftSwitchFinished?"soft switch":"reconnect",n=this.sttPausedByHost?"paused by host":"microphone disabled";l.A.info(`Session, skipping speech recognition restart after ${t} (${n})`)}}}),this.id=this.config.sessionId,this.jwt=this.config.sessionToken,l.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://");l.A.debug("Socket URL:",n);const s=new ii(this,n,e);return s.messages.subscribe(e=>{this.signalingEventHandler(e,s)}),s}signalingEventHandler(e,t){switch(e.type){case gs.VideoInitialised:case gs.DataChannelOpen:this.handleSessionReady(t);break;case gs.DataChannelResponse:this.handleDataChannelMessage(e,t);break;case gs.WebRtcStats:{const t=e.stats;!this.resolutionLogged&&t.inboundVideoStats?.frameWidth&&t.inboundVideoStats?.frameHeight&&(l.A.info("Video resolution:",`${t.inboundVideoStats.frameWidth}x${t.inboundVideoStats.frameHeight}`),this.resolutionLogged=!0),this.config.webRtcStatsEmitMessages&&this.messages.next(new _s.O$(t)),this.config.webRtcStatsLogMessages&&l.A.info("WebRTC stats",t);break}}}handleSessionReady(e){l.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 _s.wf(this.id)),this.config.networkIndicator&&e.startNetworkQualityMonitor(this.config.networkIndicator),this.config.webRtcStatsLogMessages&&e.startAudioStatsMonitor()},fi))}async initSpeechRecognition(e){if(!ti(this.audioUpstreamMode))return void l.A.info(`[STT] audioUpstreamMode='${this.audioUpstreamMode}' — skipping STT provider initialisation (no STT leg in this mode).`);if(this.speechRec)return void l.A.warn("Speech recognition already initialized");let t=this.config.speechRecognitionProvider||Gs.Google;l.A.info(`[STT] Config speechRecognitionProvider: "${this.config.speechRecognitionProvider}", resolved provider: "${t}"`),t!==Gs.Google&&t!==Gs.Deepgram&&(l.A.warn(`Invalid speechRecognitionProvider value: "${String(t)}". Supported values are "google" or "deepgram". Defaulting to "google".`),t=Gs.Google,this.config.speechRecognitionProvider=Gs.Google),l.A.info(`[STT] Using provider: ${t}`);try{this.speechRec=await(t===Gs.Deepgram?this.createDeepgramSTT(e):this.createGoogleSTT(e))}catch(e){return void l.A.error("[STT] Failed to initialise speech recognition provider",l.A.serialiseError(e))}this.config.enableMicrophone&&!this.sttPausedByHost&&this.speechRec&&this.speechRec.startRecognition()}async createGoogleSTT(e){const t=this.getSpeechOptions(e);l.A.debug("Initializing Google STT (speech-recognition-service)");const{GoogleSTT:n}=await Promise.all([o.e(113),o.e(948)]).then(o.bind(o,948));return new n(t)}async createDeepgramSTT(e){const t=this.config.deepgramConfig||{};if(this.isFluxModel(t.model))return this.createDeepgramFluxSTT(e);l.A.warn("Deepgram STT is currently in beta, is subject to change, and is not suitable for production use"),l.A.debug("Initializing Deepgram STT");const n={connectionUrl:this.config.connectionUrl,jwtToken:e,sessionId:this.id,model:t.model,language:t.language,smartFormat:t.smartFormat,interimResults:t.interimResults,utteranceEndMs:t.utteranceEndMs,vadEvents:t.vadEvents,encoding:t.encoding,sampleRate:t.sampleRate,channels:t.channels,fillerWords:t.fillerWords,endpointing:t.endpointing,interruptionWordThreshold:t.interruptionWordThreshold,echoCancellation:t.microphone?.echoCancellation,noiseSuppression:t.microphone?.noiseSuppression,autoGainControl:t.microphone?.autoGainControl,microphoneDeviceId:this.config.microphoneDeviceId,promptMetadata:this.promptMetadata,messages:this.messages,sendMessage:e=>{this.signaling?.dataSend(e)},enableInterrupt:this.config.enableInterruptBySpeech,safetyNetTimeoutMs:t.safetyNetTimeoutMs,keyterms:t.keyterms,noDelay:t.noDelay},{DeepgramSTT:s}=await Promise.all([o.e(260),o.e(3)]).then(o.bind(o,3));return new s(n)}isFluxModel(e){return void 0!==e&&e.toLowerCase().startsWith("flux")}async createDeepgramFluxSTT(e){l.A.debug("Initializing Deepgram Flux STT (v2 API)");const t=this.config.deepgramConfig||{},n={connectionUrl:this.config.connectionUrl,jwtToken:e,sessionId:this.id,model:t.model,language:t.language,eotThreshold:t.eotThreshold,eagerEotThreshold:t.eagerEotThreshold,eotTimeoutMs:t.eotTimeoutMs,eagerMaxTurnDurationMs:t.eagerMaxTurnDurationMs,keyterms:t.keyterms,safetyNetTimeoutMs:t.safetyNetTimeoutMs,echoCancellation:t.microphone?.echoCancellation,noiseSuppression:t.microphone?.noiseSuppression,autoGainControl:t.microphone?.autoGainControl,microphoneDeviceId:this.config.microphoneDeviceId,promptMetadata:this.promptMetadata,messages:this.messages,sendMessage:e=>{this.signaling?.dataSend(e)}},{DeepgramFluxSTT:s}=await Promise.all([o.e(260),o.e(363)]).then(o.bind(o,363));return new s(n)}getSpeechOptions(e){return{apiUrl:this.config.connectionUrl,assetBasePath:this.config.assetBasePath,enableInterrupt:this.config.enableInterruptBySpeech,enableVad:this.config.enableVad,jwtToken:e,hintPhrases:this.config.speechRecognitionHintPhrases,hintPhrasesBoost:this.config.speechRecognitionHintPhrasesBoost,locales:this.config.speechRecognitionLocales,messages:this.messages,promptMetadata:this.promptMetadata,sessionId:this.id,sendMessage: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(l.A.debug("Processing data channel message",e),e.msg.type){case ri.NlpPromptResult:this.messages.next(new _s.nD(e.msg));break;case ri.AvatarStartedSpeaking:this.messages.next(new _s.yr);break;case ri.AvatarStoppedSpeaking:this.messages.next(new _s.kS);break;case ri.Error:l.A.error(`an error has occurred - ${JSON.stringify(e.msg)}`),this.handleChannelMessageError(e.msg);break;case ri.SceneReady:l.A.debug("Scene is ready"),t.sceneReady=!0,this.handleSessionReady(t),this.messages.next(new _s.Ln);break;case ri.SpeechEvent:this.messages.next(new _s.Qd(e.msg));break;case ri.SessionEnded:{const t="UserInactivity"===e.msg.reason?"sessionEndedDueToInactivity":e.msg.reason;this.signaling?.endSession(t),this.signaling=void 0;break}case ri.SpeechStreamOpened:this.audioStreamId=e.msg.streamId;break;case ri.SpeechStreamClosed:e.msg.streamId===this.audioStreamId?this.audioStreamId=void 0:l.A.warn("Received SpeechStreamClosed message for unexpected streamId",e.msg.streamId)}}handleChannelMessageError(e){const t=e?.message?.trim()||"An unknown error occurred";e&&gi.includes(e.code)?this.messages.next(new _s.Uh(e)):this.messages.next(new _s.Cj(t))}sendWelcomePrompt(){l.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 Bs.D(this.config.welcomePrompt,this.promptMetadata)))}listenForTabClosure(){window.addEventListener("beforeunload",()=>{l.A.info("Window unload detected, ending session."),this.signaling?.endSession(),this.signaling=void 0})}}class vi{prompt;requestId;constructor(e,t=(0,li.g)()){this.prompt=e,this.requestId=t}toJSON(){return{action:Ws.A.Speak,data:{requestId:this.requestId,prompt:this.prompt}}}}var Si,bi=o(58);!function(e){e.Open="open",e.Close="close",e.Interrupt="interrupt"}(Si||(Si={}));class wi{action;streamId;metadata;requestId;constructor(e,t,n={},s=(0,li.g)()){this.action=e,this.streamId=t,this.metadata=n,this.requestId=s}toJSON(){return{action:Ws.A.SpeechStream,data:{requestId:this.requestId,action:this.action,streamId:this.streamId,metadata:this.metadata}}}}class Ci{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:Ws.A.ExecuteCommand,data:e}}}class Ti{config;session;messageSubscription;constructor(e){this.config=e,l.A.setLevel(e.logLevel??"info")}init(){if(this.session){const e="Cannot initialize: session already active. Call endSession() first.";throw l.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 l.A.error(e),new Error(e)}var e;l.A.info(`Initializing Uneeq with config:', ${JSON.stringify(this.config)}, for UserAgent: ${navigator.userAgent}`),this.session=new yi(this.config),this.session.createSession(),this.messageSubscription=this.session.messages.subscribe(e=>{e.uneeqMessageType===_s.Yg.SessionEnded&&(l.A.info("Session ended, resetting session state"),this.resetSessionState())})}isSessionActive(){return void 0!==this.session}ensureSessionExists(){return!!this.session?.id||(l.A.warn("Cannot perform action, session has not started."),!1)}chatPrompt(e){e&&""!==e.trim()&&this.ensureSessionExists()&&this.session?.signaling?.dataSend(new Bs.D(e,this.session?.promptMetadata))}speak(e){e&&""!==e.trim()&&this.ensureSessionExists()&&this.session?.signaling?.dataSend(new vi(e))}openAudioStream(){const e=this.session;this.ensureSessionExists()&&e?.signaling?.dataSend(new wi(Si.Open,e?.audioStreamId))}closeAudioStream(){const e=this.session;this.ensureSessionExists()&&void 0!==e?.audioStreamId&&e.signaling?.dataSend(new wi(Si.Close,e.audioStreamId))}interruptAudioStream(){const e=this.session;this.ensureSessionExists()&&void 0!==e?.audioStreamId&&e.signaling?.dataSend(new wi(Si.Interrupt,e.audioStreamId))}async speakAudio(e){this.ensureSessionExists()&&await async function(e,t){try{if(void 0===e?.audioStreamId)return void l.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 l.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]),r=new Uint8Array(2+n.length);r.set(s,0),r.set(i,1),r.set(n,2),e.signaling?.dataSendBinary(r)}catch(e){l.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 Ci(e,t,n,s))}endSession(){this.ensureSessionExists()&&(this.session?.signaling?.endSession(),this.resetSessionState())}resetSessionState(){this.messageSubscription?.unsubscribe(),this.messageSubscription=void 0,this.session=void 0}unmuteDigitalHuman(){this.ensureSessionExists()&&(this.session?.signaling?.playAudioElement(),l.A.debug("Unmuted digital human."))}muteDigitalHuman(){this.ensureSessionExists()&&(this.session?.signaling?.pauseAudioElement(),l.A.debug("Muted digital human."))}stopSpeaking(){this.ensureSessionExists()&&this.session?.signaling?.dataSend(new bi.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=Zs(this.config.audioUpstreamMode);if(!ti(e))return l.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=Zs(this.config.audioUpstreamMode);if(!ti(e))return l.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}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,l.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=o(508);return window.Uneeq=Ti,a})());
|
|
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,t,n,s,i={963(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},t.getDescription=function(e){const n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter(e=>0===e.indexOf(n))},t.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},t.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(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.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},t.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"},t.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(" ")}},t.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"},t.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},t.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},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.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},t.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},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){const n=t.matchPrefix(e,"a=mid:")[0];if(n)return n.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,n){return{role:"auto",fingerprints:t.matchPrefix(e+n,"a=fingerprint:").map(t.parseFingerprint)}},t.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},t.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)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.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}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,n){return t.matchPrefix(e+n,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,n){const s=t.matchPrefix(e+n,"a=ice-ufrag:")[0],i=t.matchPrefix(e+n,"a=ice-pwd:")[0];return s&&i?{usernameFragment:s.substring(12),password:i.substring(10)}:null},t.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},t.parseRtpParameters=function(e){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=t.splitLines(e)[0].split(" ");n.profile=s[2];for(let i=3;i<s.length;i++){const r=s[i],o=t.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(o){const s=t.parseRtpMap(o),i=t.matchPrefix(e,"a=fmtp:"+r+" ");switch(s.parameters=i.length?t.parseFmtp(i[0]):{},s.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+r+" ").map(t.parseRtcpFb),n.codecs.push(s),s.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(s.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach(e=>{n.headerExtensions.push(t.parseExtmap(e))});const i=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach(e=>{i.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),n},t.writeRtpDescription=function(e,n){let s="";s+="m="+e+" ",s+=n.codecs.length>0?"9":"0",s+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",s+=n.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",n.codecs.forEach(e=>{s+=t.writeRtpMap(e),s+=t.writeFmtp(e),s+=t.writeRtcpFb(e)});let i=0;return n.codecs.forEach(e=>{e.maxptime>i&&(i=e.maxptime)}),i>0&&(s+="a=maxptime:"+i+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach(e=>{s+=t.writeExtmap(e)}),s},t.parseRtpEncodingParameters=function(e){const n=[],s=t.parseRtpParameters(e),i=-1!==s.fecMechanisms.indexOf("RED"),r=-1!==s.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=o.length>0&&o[0].ssrc;let l;const c=t.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 t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&l&&(t.rtx={ssrc:l}),n.push(t),i&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:r?"red+ulpfec":"red"},n.push(t))}}),0===n.length&&a&&n.push({ssrc:a});let d=t.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,n.forEach(e=>{e.maxBitrate=d})),n},t.parseRtcpParameters=function(e){const n={},s=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];s&&(n.cname=s.value,n.ssrc=s.ssrc);const i=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=i.length>0,n.compound=0===i.length;const r=t.matchPrefix(e,"a=rtcp-mux");return n.mux=r.length>0,n},t.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},t.parseMsid=function(e){let n;const s=t.matchPrefix(e,"a=msid:");if(1===s.length)return n=s[0].substring(7).split(" "),{stream:n[0],track:n[1]};const i=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return i.length>0?(n=i[0].value.split(" "),{stream:n[0],track:n[1]}):void 0},t.parseSctpDescription=function(e){const n=t.parseMLine(e),s=t.matchPrefix(e,"a=max-message-size:");let i;s.length>0&&(i=parseInt(s[0].substring(19),10)),isNaN(i)&&(i=65536);const r=t.matchPrefix(e,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:n.fmt,maxMessageSize:i};const o=t.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}}},t.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("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,s){let i;const r=void 0!==n?n:2;return i=e||t.generateSessionId(),"v=0\r\no="+(s||"thisisadapterortc")+" "+i+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const s=t.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 n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){const n=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||"="!==n[e].charAt(1))return!1;return!0},e.exports=t},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:()=>m,JP:()=>x,Ln:()=>P,M8:()=>C,MA:()=>_,MM:()=>U,N8:()=>B,O$:()=>g,Qd:()=>S,Tu:()=>T,Uh:()=>v,Ux:()=>o,WQ:()=>D,WY:()=>M,XC:()=>w,Yg:()=>s,_4:()=>l,aY:()=>b,bS:()=>k,co:()=>i,fI:()=>L,fP:()=>y,fh:()=>r,im:()=>c,j_:()=>V,kS:()=>h,nD:()=>R,qo:()=>I,qw:()=>F,sF:()=>O,ss:()=>E,tc:()=>u,wf:()=>p,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.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 p{sessionId;uneeqMessageType=s.SessionLive;constructor(e){this.sessionId=e}}class m{position;uneeqMessageType=s.WaitingInQueue;constructor(e){this.position=e}}class g{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 T{uneeqMessageType=s.DigitalHumanMuted}class M{enabled;uneeqMessageType=s.EnableMicrophoneUpdated;constructor(e){this.enabled=e}}class E{chatMetadata;uneeqMessageType=s.CustomMetadataUpdated;constructor(e){this.chatMetadata=e}}class k{promptRequest;uneeqMessageType=s.PromptRequest;constructor(e){this.promptRequest=e}}class R{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 O{uneeqMessageType=s.SoftSwitchStarting}class D{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 _{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}}}}}},r={};function o(e){var t=r[e];if(void 0!==t)return t.exports;var n=r[e]={exports:{}};return i[e].call(n.exports,n,n.exports,o),n.exports}o.m=i,t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,o.t=function(n,s){if(1&s&&(n=this(n)),8&s)return n;if("object"==typeof n&&n){if(4&s&&n.__esModule)return n;if(16&s&&"function"==typeof n.then)return n}var i=Object.create(null);o.r(i);var r={};e=e||[null,t({}),t([]),t(t)];for(var a=2&s&&n;("object"==typeof a||"function"==typeof a)&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach(e=>r[e]=()=>n[e]);return r.default=()=>n,o.d(i,r),i},o.d=(e,t)=>{for(var n in t)o.o(t,n)&&!o.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o.f={},o.e=e=>Promise.all(Object.keys(o.f).reduce((t,n)=>(o.f[n](e,t),t),[])),o.u=e=>e+".index.js",o.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},s="Uneeq:",o.l=(e,t,i,r)=>{if(n[e])n[e].push(t);else{var a,l;if(void 0!==i)for(var c=document.getElementsByTagName("script"),d=0;d<c.length;d++){var h=c[d];if(h.getAttribute("src")==e||h.getAttribute("data-webpack")==s+i){a=h;break}}a||(l=!0,(a=document.createElement("script")).charset="utf-8",o.nc&&a.setAttribute("nonce",o.nc),a.setAttribute("data-webpack",s+i),a.src=e),n[e]=[t];var u=(t,s)=>{a.onerror=a.onload=null,clearTimeout(p);var i=n[e];if(delete n[e],a.parentNode&&a.parentNode.removeChild(a),i&&i.forEach(e=>e(s)),t)return t(s)},p=setTimeout(u.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=u.bind(null,a.onerror),a.onload=u.bind(null,a.onload),l&&document.head.appendChild(a)}},o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;o.g.importScripts&&(e=o.g.location+"");var t=o.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");if(n.length)for(var s=n.length-1;s>-1&&(!e||!/^http(s?):/.test(e));)e=n[s--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),o.p=e})(),(()=>{var e={792:0};o.f.j=(t,n)=>{var s=o.o(e,t)?e[t]:void 0;if(0!==s)if(s)n.push(s[2]);else{var i=new Promise((n,i)=>s=e[t]=[n,i]);n.push(s[2]=i);var r=o.p+o.u(t),a=new Error;o.l(r,n=>{if(o.o(e,t)&&(0!==(s=e[t])&&(e[t]=void 0),s)){var i=n&&("load"===n.type?"missing":n.type),r=n&&n.target&&n.target.src;a.message="Loading chunk "+t+" failed.\n("+i+": "+r+")",a.name="ChunkLoadError",a.type=i,a.request=r,s[1](a)}},"chunk-"+t,t)}};var t=(t,n)=>{var s,i,[r,a,l]=n,c=0;if(r.some(t=>0!==e[t])){for(s in a)o.o(a,s)&&(o.m[s]=a[s]);l&&l(o)}for(t&&t(n);c<r.length;c++)i=r[c],o.o(e,i)&&e[i]&&e[i][0](),e[i]=0},n=Object("undefined"!=typeof self?self:this).webpackChunkUneeq=Object("undefined"!=typeof self?self:this).webpackChunkUneeq||[];n.forEach(t.bind(null,0)),n.push=t.bind(null,n.push.bind(n))})();var a={};o.r(a),o.d(a,{AvatarAnswerMessage:()=>_s.fh,AvatarInterruptedMessage:()=>_s.tc,AvatarStartedSpeakingMessage:()=>_s.yr,AvatarStoppedSpeakingMessage:()=>_s.kS,CameraAnchorDistance:()=>oi,CameraAnchorHorizontal:()=>ai,CustomMetadataUpdated:()=>_s.ss,CustomerConcurrencyLimitReachedMessage:()=>_s.MM,DeviceErrorMessage:()=>_s.co,DigitalHumanMuted:()=>_s.Tu,DigitalHumanPlayedInMutedModeSuccess:()=>_s.XC,DigitalHumanUnmuted:()=>_s.M8,EnableMicrophoneUpdatedMessage:()=>_s.WY,LogLevel:()=>Mi.$,NetworkIndicatorPopupTrigger:()=>Ks,NetworkIndicatorPosition:()=>Qs,NetworkIndicatorVisibility:()=>qs,NetworkQualityLevel:()=>zs,NetworkQualityMessage:()=>_s.N8,PromptRequestMessage:()=>_s.bS,PromptResultMessage:()=>_s.nD,RendererErrorMessage:()=>_s.j_,SceneReadyMessage:()=>_s.Ln,SessionBackendErrorMessage:()=>_s.Uh,SessionConnectingMessage:()=>_s.qo,SessionDisconnectedMessage:()=>_s.JP,SessionEndedMessage:()=>_s.aY,SessionErrorMessage:()=>_s.Cj,SessionLiveMessage:()=>_s.wf,SessionReconnectingFinishedMessage:()=>_s.xQ,SessionReconnectingMessage:()=>_s.fI,SoftSwitchStartingMessage:()=>_s.sF,SoftSwitchStoppingMessage:()=>_s.WQ,SpeechEventMessage:()=>_s.Qd,SpeechRecognitionProvider:()=>Gs,SpeechRecognitionTransientErrorMessage:()=>_s.fP,SpeechTranscriptionMessage:()=>_s.Ux,UNEEQ_JS_SDK_VERSION:()=>Vs,Uneeq:()=>Ti,UneeqMessageType:()=>_s.Yg,UserStartedSpeakingMessage:()=>_s._4,UserStoppedSpeakingMessage:()=>_s.im,VadInterruptionAllowedMessage:()=>_s.E1,VideoAutoplayBlockedMessage:()=>_s.MA,VideoLayoutConfiguringMessage:()=>_s.qw,WaitingInQueueMessage:()=>_s.F8,WebRtcConnectedMessage:()=>_s.Cl,WebRtcStatsMessage:()=>_s.O$,resolveAudioUpstreamMode:()=>Zs});var l=o(514),c=function(e,t){return c=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])},c(e,t)};function d(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}c(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function h(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 u(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 p(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 m(e){return"function"==typeof e}function g(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,"function"==typeof SuppressedError&&SuppressedError;var f=g(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 y(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var v=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=h(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 l=this.initialTeardown;if(m(l))try{l()}catch(e){i=e instanceof f?e.errors:[e]}var c=this._finalizers;if(c){this._finalizers=null;try{for(var d=h(c),g=d.next();!g.done;g=d.next()){var y=g.value;try{w(y)}catch(e){i=null!=i?i:[],e instanceof f?i=p(p([],u(i)),u(e.errors)):i.push(e)}}}catch(e){n={error:e}}finally{try{g&&!g.done&&(s=d.return)&&s.call(d)}finally{if(n)throw n.error}}}if(i)throw new f(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)w(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)&&y(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&y(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}(),S=v.EMPTY;function b(e){return e instanceof v||e&&"closed"in e&&m(e.remove)&&m(e.add)&&m(e.unsubscribe)}function w(e){m(e)?e():e.unsubscribe()}var C=null,T=null,M=void 0,E=!1,k=!1,R={setTimeout:function(e,t){for(var n=[],s=2;s<arguments.length;s++)n[s-2]=arguments[s];var i=R.delegate;return(null==i?void 0:i.setTimeout)?i.setTimeout.apply(i,p([e,t],u(n))):setTimeout.apply(void 0,p([e,t],u(n)))},clearTimeout:function(e){var t=R.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function P(){}var I=x("C",void 0,void 0);function x(e,t,n){return{kind:e,value:t,error:n}}var L=null;function A(e){if(E){var t=!L;if(t&&(L={errorThrown:!1,error:null}),e(),t){var n=L,s=n.errorThrown,i=n.error;if(L=null,s)throw i}}else e()}var O=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,b(t)&&t.add(n)):n.destination=_,n}return d(t,e),t.create=function(e,t,n){return new U(e,t,n)},t.prototype.next=function(e){this.isStopped?V(function(e){return x("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?V(x("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?V(I,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}(v),D=Function.prototype.bind;function F(e,t){return D.call(e,t)}var N=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){B(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){B(e)}else B(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){B(e)}},e}(),U=function(e){function t(t,n,s){var i,r,o=e.call(this)||this;return m(t)||!t?i={next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=s?s:void 0}:o&&k?((r=Object.create(t)).unsubscribe=function(){return o.unsubscribe()},i={next:t.next&&F(t.next,r),error:t.error&&F(t.error,r),complete:t.complete&&F(t.complete,r)}):i=t,o.destination=new N(i),o}return d(t,e),t}(O);function B(e){var t;E?(t=e,E&&L&&(L.errorThrown=!0,L.error=t)):function(e){R.setTimeout(function(){if(!C)throw e;C(e)})}(e)}function V(e,t){var n=T;n&&R.setTimeout(function(){return n(e,t)})}var _={closed:!0,next:P,error:function(e){throw e},complete:P},W="function"==typeof Symbol&&Symbol.observable||"@@observable";function $(e){return e}var H=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 O||function(e){return e&&m(e.next)&&m(e.error)&&m(e.complete)}(s)&&b(s)?e:new U(e,t,n);return A(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=j(t))(function(t,s){var i=new U({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[W]=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?$: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=j(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 j(e){var t;return null!==(t=null!=e?e:M)&&void 0!==t?t:Promise}var z,q=g(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Q=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 d(t,e),t.prototype.lift=function(e){var t=new K(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new q},t.prototype.next=function(e){var t=this;A(function(){var n,s;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var i=h(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;A(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;A(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?S:(this.currentObservers=null,r.push(e),new v(function(){t.currentObservers=null,y(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 H;return e.source=this,e},t.create=function(e,t){return new K(e,t)},t}(H),K=function(e){function t(t,n){var s=e.call(this)||this;return s.destination=t,s.source=n,s}return d(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:S},t}(Q),G={now:function(){return(G.delegate||Date).now()},delegate:void 0},X=function(e){function t(t,n,s){void 0===t&&(t=1/0),void 0===n&&(n=1/0),void 0===s&&(s=G);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 d(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}(Q);!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"}(z||(z={}));class J{constructor(){this.logLevel=z.Debug,this.includeStack=!0}}let Y=new class{InitLogging(e,t){this.ValidateContext(),this.context.logLevel=e,this.context.includeStack=t}Debug(e){this.ValidateContext(),this.context.logLevel>=z.Debug&&this.CommonLog("Debug",e)}Info(e){this.ValidateContext(),this.context.logLevel>=z.Info&&this.CommonLog("Info",e)}Warning(e){this.ValidateContext(),this.context.logLevel>=z.Warning&&this.CommonLog("Warning",e)}Error(e){this.ValidateContext(),this.context.logLevel>=z.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 J,window.loggerContext=this.context):this.context=new J)}};class Z{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 ee extends Z{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 te extends Z{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 ne extends Z{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 se extends Z{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:Y.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 ie extends Event{constructor(e){super("afkWarningActivate"),this.data=e}}class re extends Event{constructor(e){super("afkWarningUpdate"),this.data=e}}class oe extends Event{constructor(){super("afkWarningDeactivate")}}class ae extends Event{constructor(){super("afkTimedOut")}}class le extends Event{constructor(e){super("videoEncoderAvgQP"),this.data=e}}class ce extends Event{constructor(){super("webRtcSdp")}}class de extends Event{constructor(e){super("webRtcSdpAnswer"),this.data=e}}class he extends Event{constructor(e){super("webRtcSdpOffer"),this.data=e}}class ue extends Event{constructor(){super("webRtcAutoConnect")}}class pe extends Event{constructor(){super("webRtcConnecting")}}class me extends Event{constructor(){super("webRtcConnected")}}class ge extends Event{constructor(){super("webRtcFailed")}}class fe extends Event{constructor(e){super("webRtcDisconnected"),this.data=e}}class ye extends Event{constructor(e){super("dataChannelOpen"),this.data=e}}class ve extends Event{constructor(e){super("dataChannelClose"),this.data=e}}class Se extends Event{constructor(e){super("dataChannelError"),this.data=e}}class be extends Event{constructor(){super("videoInitialized")}}class we extends Event{constructor(){super("streamLoading")}}class Ce extends Event{constructor(){super("streamConnect")}}class Te extends Event{constructor(){super("streamDisconnect")}}class Me extends Event{constructor(){super("streamReconnect")}}class Ee extends Event{constructor(e){super("playStreamError"),this.data=e}}class ke extends Event{constructor(){super("playStream")}}class Re extends Event{constructor(e){super("playStreamRejected"),this.data=e}}class Pe extends Event{constructor(e){super("loadFreezeFrame"),this.data=e}}class Ie extends Event{constructor(){super("hideFreezeFrame")}}class xe extends Event{constructor(e){super("statsReceived"),this.data=e}}class Le extends Event{constructor(e){super("streamerListMessage"),this.data=e}}class Ae extends Event{constructor(e){super("StreamerIDChangedMessage"),this.data=e}}class Oe extends Event{constructor(e){super("latencyTestResult"),this.data=e}}class De extends Event{constructor(e){super("latencyCalculated"),this.data=e}}class Fe extends Event{constructor(e){super("showOnScreenKeyboard"),this.data=e}}class Ne extends Event{constructor(e){super("dataChannelLatencyTestResponse"),this.data=e}}class Ue extends Event{constructor(e){super("dataChannelLatencyTestResult"),this.data=e}}class Be extends Event{constructor(e){super("subscribeFailed"),this.data=e}}class Ve extends Event{constructor(e){super("initialSettings"),this.data=e}}class _e extends Event{constructor(e){super("settingsChanged"),this.data=e}}Event,Event;class We extends Event{constructor(e){super("xrFrame"),this.data=e}}class $e extends Event{constructor(e){super("playerCount"),this.data=e}}class He extends Event{constructor(){super("webRtcTCPRelayDetected")}}class je extends EventTarget{dispatchEvent(e){return super.dispatchEvent(e)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}}class ze{static getSupportedVideoCodecs(){const e=[];if(!RTCRtpReceiver.getCapabilities)return Y.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 qe{}qe.AutoConnect="AutoConnect",qe.AutoPlayVideo="AutoPlayVideo",qe.AFKDetection="TimeoutIfIdle",qe.HoveringMouseMode="HoveringMouse",qe.ForceMonoAudio="ForceMonoAudio",qe.ForceTURN="ForceTURN",qe.FakeMouseWithTouches="FakeMouseWithTouches",qe.IsQualityController="ControlsQuality",qe.MatchViewportResolution="MatchViewportRes",qe.StartVideoMuted="StartVideoMuted",qe.SuppressBrowserKeys="SuppressBrowserKeys",qe.UseMic="UseMic",qe.UseModalForTextInput="UseModalForTextInput",qe.UseCamera="UseCamera",qe.KeyboardInput="KeyboardInput",qe.MouseInput="MouseInput",qe.TouchInput="TouchInput",qe.GamepadInput="GamepadInput",qe.XRControllerInput="XRControllerInput",qe.WaitForStreamer="WaitForStreamer",qe.HideUI="HideUI",qe.EnableCaptureTimeExt="EnableCaptureTimeExt",qe.BrowserSendOffer="BrowserSendOffer",qe.LatencyCSV="LatencyCSV";const Qe=e=>Object.getOwnPropertyNames(qe).some(t=>qe[t]===e);class Ke{}Ke.AFKTimeoutSecs="AFKTimeout",Ke.AFKCountdownSecs="AFKCountdown",Ke.MinQP="MinQP",Ke.MaxQP="MaxQP",Ke.MinQuality="MinQuality",Ke.MaxQuality="MaxQuality",Ke.CompatQualityMin="CompatQualityMin",Ke.CompatQualityMax="CompatQualityMax",Ke.WebRTCFPS="WebRTCFPS",Ke.WebRTCMinBitrate="WebRTCMinBitrate",Ke.WebRTCMaxBitrate="WebRTCMaxBitrate",Ke.MaxReconnectAttempts="MaxReconnectAttempts",Ke.StreamerAutoJoinInterval="StreamerAutoJoinInterval",Ke.KeepaliveDelay="KeepaliveDelay";const Ge=e=>Object.getOwnPropertyNames(Ke).some(t=>Ke[t]===e);class Xe{}Xe.SignallingServerUrl="ss";const Je=e=>Object.getOwnPropertyNames(Xe).some(t=>Xe[t]===e);class Ye{}Ye.PreferredCodec="PreferredCodec",Ye.StreamerId="StreamerId",Ye.PreferredQuality="PreferredQuality";const Ze=e=>Object.getOwnPropertyNames(Ye).some(t=>Ye[t]===e);class et{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(Xe.SignallingServerUrl,new ne(Xe.SignallingServerUrl,"Signalling url","Url of the signalling server",t&&Object.prototype.hasOwnProperty.call(t,Xe.SignallingServerUrl)?t[Xe.SignallingServerUrl]:("https:"===location.protocol?"wss://":"ws://")+window.location.hostname+("80"===window.location.port||""===window.location.port?"":`:${window.location.port}`),e)),this.optionParameters.set(Ye.StreamerId,new se(Ye.StreamerId,"Streamer ID","The ID of the streamer to stream.",t&&Object.prototype.hasOwnProperty.call(t,Ye.StreamerId)?t[Ye.StreamerId]:"",t&&Object.prototype.hasOwnProperty.call(t,Ye.StreamerId)?[t[Ye.StreamerId]]:void 0,e));const n=function(e){const t=ze.getSupportedVideoCodecs();if(t.includes(e))return e;for(const n of t)if(n.startsWith(e))return n;return e};this.optionParameters.set(Ye.PreferredCodec,new se(Ye.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation",t&&Object.prototype.hasOwnProperty.call(t,Ye.PreferredCodec)?n(t[Ye.PreferredCodec]):function(){const e=ze.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 Y.Error("Could not find any reasonable video codec to assign as a default."),""}(),ze.getSupportedVideoCodecs(),e,n)),this.optionParameters.set(Ye.PreferredQuality,new se(Ye.PreferredQuality,"Preferred Quality","The preferred quality of the stream (only applicable when using the SFU)",t&&Object.prototype.hasOwnProperty.call(t,Ye.PreferredQuality)?t[Ye.PreferredQuality]:"Default",["Default"],e)),this.flags.set(qe.AutoConnect,new ee(qe.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,qe.AutoConnect))&&t[qe.AutoConnect],e)),this.flags.set(qe.AutoPlayVideo,new ee(qe.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,qe.AutoPlayVideo)||t[qe.AutoPlayVideo],e)),this.flags.set(qe.UseMic,new ee(qe.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.UseMic))&&t[qe.UseMic],e)),this.flags.set(qe.UseModalForTextInput,new ee(qe.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,qe.UseModalForTextInput)||t[qe.UseModalForTextInput],e)),this.flags.set(qe.UseCamera,new ee(qe.UseCamera,"Use webcam","Make browser request webcam access and open a input video track.",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.UseCamera))&&t[qe.UseCamera],e)),this.flags.set(qe.StartVideoMuted,new ee(qe.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.StartVideoMuted))&&t[qe.StartVideoMuted],e)),this.flags.set(qe.SuppressBrowserKeys,new ee(qe.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,qe.SuppressBrowserKeys)||t[qe.SuppressBrowserKeys],e)),this.flags.set(qe.IsQualityController,new ee(qe.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!t||!Object.prototype.hasOwnProperty.call(t,qe.IsQualityController)||t[qe.IsQualityController],e)),this.flags.set(qe.ForceMonoAudio,new ee(qe.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.ForceMonoAudio))&&t[qe.ForceMonoAudio],e)),this.flags.set(qe.ForceTURN,new ee(qe.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.ForceTURN))&&t[qe.ForceTURN],e)),this.flags.set(qe.AFKDetection,new ee(qe.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.AFKDetection))&&t[qe.AFKDetection],e)),this.flags.set(qe.MatchViewportResolution,new ee(qe.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,qe.MatchViewportResolution))&&t[qe.MatchViewportResolution],e)),this.flags.set(qe.HoveringMouseMode,new ee(qe.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,qe.HoveringMouseMode))&&t[qe.HoveringMouseMode],e,(e,t)=>{t.label=`Control Scheme: ${e?"Hovering":"Locked"} Mouse`})),this.flags.set(qe.FakeMouseWithTouches,new ee(qe.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,qe.FakeMouseWithTouches))&&t[qe.FakeMouseWithTouches],e)),this.flags.set(qe.KeyboardInput,new ee(qe.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,qe.KeyboardInput)||t[qe.KeyboardInput],e)),this.flags.set(qe.MouseInput,new ee(qe.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,qe.MouseInput)||t[qe.MouseInput],e)),this.flags.set(qe.TouchInput,new ee(qe.TouchInput,"Touch input","If enabled, send touch events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,qe.TouchInput)||t[qe.TouchInput],e)),this.flags.set(qe.GamepadInput,new ee(qe.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,qe.GamepadInput)||t[qe.GamepadInput],e)),this.flags.set(qe.XRControllerInput,new ee(qe.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!t||!Object.prototype.hasOwnProperty.call(t,qe.XRControllerInput)||t[qe.XRControllerInput],e)),this.flags.set(qe.WaitForStreamer,new ee(qe.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!t||!Object.prototype.hasOwnProperty.call(t,qe.WaitForStreamer)||t[qe.WaitForStreamer],e)),this.flags.set(qe.HideUI,new ee(qe.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.HideUI))&&t[qe.HideUI],e)),this.flags.set(qe.EnableCaptureTimeExt,new ee(qe.EnableCaptureTimeExt,"Enable abs-capture-time","Enables the abs-capture-time RTP header extension",!(!t||!Object.prototype.hasOwnProperty.call(t,qe.EnableCaptureTimeExt))&&t[qe.EnableCaptureTimeExt],e)),this.flags.set(qe.BrowserSendOffer,new ee(qe.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,qe.BrowserSendOffer))&&t[qe.BrowserSendOffer],e)),this.flags.set(qe.LatencyCSV,new ee(qe.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,qe.LatencyCSV))&&t[qe.LatencyCSV],e)),this.numericParameters.set(Ke.AFKTimeoutSecs,new te(Ke.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,Ke.AFKTimeoutSecs)?t[Ke.AFKTimeoutSecs]:120,e)),this.numericParameters.set(Ke.AFKCountdownSecs,new te(Ke.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(Ke.MaxReconnectAttempts,new te(Ke.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,t&&Object.prototype.hasOwnProperty.call(t,Ke.MaxReconnectAttempts)?t[Ke.MaxReconnectAttempts]:3,e)),this.numericParameters.set(Ke.MinQP,new te(Ke.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,Ke.MinQP)?t[Ke.MinQP]:0,e)),this.numericParameters.set(Ke.MaxQP,new te(Ke.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,Ke.MaxQP)?t[Ke.MaxQP]:51,e)),this.numericParameters.set(Ke.MinQuality,new te(Ke.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,Ke.MinQuality)?t[Ke.MinQuality]:0,e)),this.numericParameters.set(Ke.MaxQuality,new te(Ke.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,Ke.MaxQuality)?t[Ke.MaxQuality]:100,e)),this.numericParameters.set(Ke.CompatQualityMin,new te(Ke.CompatQualityMin,"Min Quality","The lower bound for encoding quality. 0 = Worst, 100 = Best.",0,100,t&&Object.prototype.hasOwnProperty.call(t,Ke.CompatQualityMin)?t[Ke.CompatQualityMin]:0,e)),this.numericParameters.set(Ke.CompatQualityMax,new te(Ke.CompatQualityMax,"Max Quality","The upper bound for encoding quality. 0 = Worst, 100 = Best.",0,100,t&&Object.prototype.hasOwnProperty.call(t,Ke.CompatQualityMax)?t[Ke.CompatQualityMax]:100,e)),this.numericParameters.set(Ke.WebRTCFPS,new te(Ke.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,t&&Object.prototype.hasOwnProperty.call(t,Ke.WebRTCFPS)?t[Ke.WebRTCFPS]:60,e)),this.numericParameters.set(Ke.WebRTCMinBitrate,new te(Ke.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,t&&Object.prototype.hasOwnProperty.call(t,Ke.WebRTCMinBitrate)?t[Ke.WebRTCMinBitrate]:0,e)),this.numericParameters.set(Ke.WebRTCMaxBitrate,new te(Ke.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,t&&Object.prototype.hasOwnProperty.call(t,Ke.WebRTCMaxBitrate)?t[Ke.WebRTCMaxBitrate]:0,e)),this.numericParameters.set(Ke.StreamerAutoJoinInterval,new te(Ke.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,t&&Object.prototype.hasOwnProperty.call(t,Ke.StreamerAutoJoinInterval)?t[Ke.StreamerAutoJoinInterval]:3e3,e)),this.numericParameters.set(Ke.KeepaliveDelay,new te(Ke.KeepaliveDelay,"Connection Keepalive delay","Delay between keepalive pings to the signalling server.",0,9e5,t&&Object.prototype.hasOwnProperty.call(t,Ke.KeepaliveDelay)?t[Ke.KeepaliveDelay]:3e4,e))}_addOnNumericSettingChangedListener(e,t){this.numericParameters.has(e)&&this.numericParameters.get(e).addOnChangedListener(t)}_addOnOptionSettingChangedListener(e,t){this.optionParameters.has(e)&&this.optionParameters.get(e).addOnChangedListener(t)}getNumericSettingValue(e){if(this.numericParameters.has(e))return this.numericParameters.get(e).number;throw new Error(`There is no numeric setting with the id of ${e}`)}getTextSettingValue(e){if(this.textParameters.has(e))return this.textParameters.get(e).value;throw new Error(`There is no numeric setting with the id of ${e}`)}setNumericSetting(e,t){if(!this.numericParameters.has(e))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:Y.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:Y.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:Y.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 Y.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:Y.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))Qe(t)?this.setFlagEnabled(t,e[t]):Ge(t)?this.setNumericSetting(t,e[t]):Je(t)?this.setTextSetting(t,e[t]):Ze(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 _e({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 _e({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 _e({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 _e({id:n.id,type:"option",value:t,target:n})))}}}var tt,nt,st;!function(e){e[e.LockedMouse=0]="LockedMouse",e[e.HoveringMouse=1]="HoveringMouse"}(tt||(tt={}));class it{constructor(e){this._args=[],this._callback=e}handleEvent(e){this._callback(...this._args),this._args=[]}setArgs(...e){this._args=e}}class rt 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 it(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 it((...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 ot extends rt{constructor(e){super(),this.WS_OPEN_STATE=1,this.protocols=e}sendMessage(e){this.webSocket&&this.webSocket.send(e)}connect(e){Y.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 Y.Error(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=>{Y.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(){Y.Info("Connected to the signalling server via WebSocket"),this.emit("open")}handleOnError(){this.emit("error")}handleOnClose(e){Y.Info("Disconnected to the signalling server via WebSocket: "+JSON.stringify(e.code)+" - "+e.reason),this.emit("close",e)}}class at extends rt{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);Y.Debug("Protocol received => \n"+JSON.stringify(e,void 0,4)),n=e}catch(e){return void(e instanceof Error?Y.Error(`Error parsing message string ${t}.\n${e.message}`):Y.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),Y.Debug("Protocol sent => \n"+JSON.stringify(e,void 0,4))}}function lt(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])}(nt||(nt={})),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"}(st||(st={}));const ct=Symbol.for("protobuf-ts/message-type");function dt(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 ht,ut,pt;function mt(e){var t,n,s,i;return e.localName=null!==(t=e.localName)&&void 0!==t?t:dt(e.name),e.jsonName=null!==(n=e.jsonName)&&void 0!==n?n:dt(e.name),e.repeat=null!==(s=e.repeat)&&void 0!==s?s:pt.NO,e.opt=null!==(i=e.opt)&&void 0!==i?i:!e.repeat&&!e.oneof&&"message"==e.kind,e}function gt(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"}(ht||(ht={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING",e[e.NUMBER=2]="NUMBER"}(ut||(ut={})),function(e){e[e.NO=0]="NO",e[e.PACKED=1]="PACKED",e[e.UNPACKED=2]="UNPACKED"}(pt||(pt={}));class ft{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(!gt(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,ht.INT32,s):this.scalar(e,ht.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),ht.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 ht.UINT64:case ht.FIXED64:case ht.INT64:case ht.SFIXED64:case ht.SINT64:switch(n){case ut.BIGINT:return"bigint"==s;case ut.NUMBER:return"number"==s&&!isNaN(e);default:return"string"==s}case ht.BOOL:return"boolean"==s;case ht.STRING:return"string"==s;case ht.BYTES:return e instanceof Uint8Array;case ht.DOUBLE:case ht.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 ht.INT32:case ht.FIXED32:case ht.SFIXED32:case ht.SINT32:case ht.UINT32:return this.scalars(s.slice(0,n).map(e=>parseInt(e)),t,n);case ht.BOOL:return this.scalars(s.slice(0,n).map(e=>"true"==e||"false"!=e&&e),t,n);default:return this.scalars(s,t,n,ut.STRING)}}}function yt(e){let t=typeof e;if("object"==t){if(Array.isArray(e))return"array";if(null===e)return"null"}return t}function vt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let St="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),bt=[];for(let e=0;e<St.length;e++)bt[St[e].charCodeAt(0)]=e;function wt(){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 Ct(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)}}bt["-".charCodeAt(0)]=St.indexOf("+"),bt["_".charCodeAt(0)]=St.indexOf("/");const Tt=4294967296;function Mt(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>=Tt&&(i+=s/Tt|0,s%=Tt)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),[t,s,i]}function Et(e,t){if(t>>>0<=2097151)return""+(Tt*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 kt(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 Rt(){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 Pt;function It(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;Pt=t?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:e}:void 0}();const xt=/^-?[0-9]+$/,Lt=4294967296,At=2147483648;class Ot{constructor(e,t){this.lo=0|e,this.hi=0|t}isZero(){return 0==this.lo&&0==this.hi}toNumber(){let e=this.hi*Lt+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class Dt extends Ot{static from(e){if(Pt)switch(typeof e){case"string":if("0"==e)return this.ZERO;if(""==e)throw new Error("string is no integer");e=Pt.C(e);case"number":if(0===e)return this.ZERO;e=Pt.C(e);case"bigint":if(!e)return this.ZERO;if(e<Pt.UMIN)throw new Error("signed value for ulong");if(e>Pt.UMAX)throw new Error("ulong too large");return Pt.V.setBigUint64(0,e,!0),new Dt(Pt.V.getInt32(0,!0),Pt.V.getInt32(4,!0))}else switch(typeof e){case"string":if("0"==e)return this.ZERO;if(e=e.trim(),!xt.test(e))throw new Error("string is no integer");let[t,n,s]=Mt(e);if(t)throw new Error("signed value for ulong");return new Dt(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 Dt(e,e/Lt)}throw new Error("unknown value "+typeof e)}toString(){return Pt?this.toBigInt().toString():Et(this.lo,this.hi)}toBigInt(){return It(Pt),Pt.V.setInt32(0,this.lo,!0),Pt.V.setInt32(4,this.hi,!0),Pt.V.getBigUint64(0,!0)}}Dt.ZERO=new Dt(0,0);class Ft extends Ot{static from(e){if(Pt)switch(typeof e){case"string":if("0"==e)return this.ZERO;if(""==e)throw new Error("string is no integer");e=Pt.C(e);case"number":if(0===e)return this.ZERO;e=Pt.C(e);case"bigint":if(!e)return this.ZERO;if(e<Pt.MIN)throw new Error("signed long too small");if(e>Pt.MAX)throw new Error("signed long too large");return Pt.V.setBigInt64(0,e,!0),new Ft(Pt.V.getInt32(0,!0),Pt.V.getInt32(4,!0))}else switch(typeof e){case"string":if("0"==e)return this.ZERO;if(e=e.trim(),!xt.test(e))throw new Error("string is no integer");let[t,n,s]=Mt(e);if(t){if(s>At||s==At&&0!=n)throw new Error("signed long too small")}else if(s>=At)throw new Error("signed long too large");let i=new Ft(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 Ft(e,e/Lt):new Ft(-e,-e/Lt).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return 0!==(this.hi&At)}negate(){let e=~this.hi,t=this.lo;return t?t=1+~t:e+=1,new Ft(t,e)}toString(){if(Pt)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+Et(e.lo,e.hi)}return Et(this.lo,this.hi)}toBigInt(){return It(Pt),Pt.V.setInt32(0,this.lo,!0),Pt.V.setInt32(4,this.hi,!0),Pt.V.getBigInt64(0,!0)}}function Nt(e,t){if(!e)throw new Error(t)}function Ut(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 Bt(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 Vt(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 _t(e,t){switch(t){case ut.BIGINT:return e.toBigInt();case ut.NUMBER:return e.toNumber();default:return e.toString()}}Ft.ZERO=new Ft(0,0);class Wt{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=yt(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(vt(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==ht.BOOL&&(o="true"==o||"false"!=o&&o),o=this.scalar(o,e.K,ut.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]&&Nt(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 Nt(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)&&(Nt("number"==typeof r,`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} has no value for "${t}".`),r)}Nt(!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 ht.DOUBLE:case ht.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==ht.FLOAT&&Vt(s),s;case ht.INT32:case ht.FIXED32:case ht.SFIXED32:case ht.SINT32:case ht.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==ht.UINT32?Bt(r):Ut(r),r;case ht.INT64:case ht.SFIXED64:case ht.SINT64:if(null===e)return _t(Ft.ZERO,n);if("number"!=typeof e&&"string"!=typeof e)break;return _t(Ft.from(e),n);case ht.FIXED64:case ht.UINT64:if(null===e)return _t(Dt.ZERO,n);if("number"!=typeof e&&"string"!=typeof e)break;return _t(Dt.from(e),n);case ht.BOOL:if(null===e)return!1;if("boolean"!=typeof e)break;return e;case ht.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 ht.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=bt[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 $t{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);Nt(void 0!==o),n[t.useProtoFieldName?e.name:e.jsonName]=o}return n}field(e,t,n){let s;if("map"==e.kind){Nt("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);Nt(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);Nt(void 0!==t),i[r.toString()]=t}break;case"enum":const r=e.V.T();for(const[s,o]of Object.entries(t)){Nt(void 0===o||"number"==typeof o);const t=this.enum(r,o,e.name,!1,!0,n.enumAsInteger);Nt(void 0!==t),i[s.toString()]=t}}(n.emitDefaultValues||Object.keys(i).length>0)&&(s=i)}else if(e.repeat){Nt(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);Nt(void 0!==s),i.push(s)}break;case"enum":const s=e.T();for(let r=0;r<t.length;r++){Nt(void 0===t[r]||"number"==typeof t[r]);const o=this.enum(s,t[r],e.name,e.opt,!0,n.enumAsInteger);Nt(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);Nt(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 Nt("number"==typeof t),Nt(Number.isInteger(t)),r||!e[1].hasOwnProperty(t)?t:e[2]?e[2]+e[1][t]:e[1][t]}else Nt(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 Nt(s);const r=i||s;switch(e){case ht.INT32:case ht.SFIXED32:case ht.SINT32:return 0===t?r?0:void 0:(Ut(t),t);case ht.FIXED32:case ht.UINT32:return 0===t?r?0:void 0:(Bt(t),t);case ht.FLOAT:Vt(t);case ht.DOUBLE:return 0===t?r?0:void 0:(Nt("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t);case ht.STRING:return""===t?r?"":void 0:(Nt("string"==typeof t),t);case ht.BOOL:return!1===t?!r&&void 0:(Nt("boolean"==typeof t),t);case ht.UINT64:case ht.FIXED64:Nt("number"==typeof t||"string"==typeof t||"bigint"==typeof t);let e=Dt.from(t);if(e.isZero()&&!r)return;return e.toString();case ht.INT64:case ht.SFIXED64:case ht.SINT64:Nt("number"==typeof t||"string"==typeof t||"bigint"==typeof t);let n=Ft.from(t);if(n.isZero()&&!r)return;return n.toString();case ht.BYTES:return Nt(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+=St[t>>2],i=(3&t)<<4,s=1;break;case 1:n+=St[i|t>>4],i=(15&t)<<2,s=2;break;case 2:n+=St[i|t>>6],n+=St[63&t],s=0}return s&&(n+=St[i],n+="=",1==s&&(n+="=")),n}(t):r?"":void 0}}}function Ht(e,t=ut.STRING){switch(e){case ht.BOOL:return!1;case ht.UINT64:case ht.FIXED64:return _t(Dt.ZERO,t);case ht.INT64:case ht.SFIXED64:case ht.SINT64:return _t(Ft.ZERO,t);case ht.DOUBLE:case ht.FLOAT:return 0;case ht.BYTES:return new Uint8Array(0);case ht.STRING:return"";default:return 0}}class jt{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?nt.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?ht.INT32:r.T,s="scalar"==r.kind?r.L:void 0;if(a){let n=o[l];if(i==st.LengthDelimited&&t!=ht.STRING&&t!=ht.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==ht.BOOL?t.bool().toString():this.scalar(t,e.K,ut.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=Ht(e.K);s=e.K==ht.BOOL?t.toString():t}if(void 0===i)switch(e.V.kind){case"scalar":i=Ht(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 ht.INT32:return e.int32();case ht.STRING:return e.string();case ht.BOOL:return e.bool();case ht.DOUBLE:return e.double();case ht.FLOAT:return e.float();case ht.INT64:return _t(e.int64(),n);case ht.UINT64:return _t(e.uint64(),n);case ht.FIXED64:return _t(e.fixed64(),n);case ht.FIXED32:return e.fixed32();case ht.BYTES:return e.bytes();case ht.UINT32:return e.uint32();case ht.SFIXED32:return e.sfixed32();case ht.SFIXED64:return _t(e.sfixed64(),n);case ht.SINT32:return e.sint32();case ht.SINT64:return _t(e.sint64(),n)}}}class zt{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?ht.INT32:s.T;if(o)if(Nt(Array.isArray(i)),o==pt.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?Nt(s.opt):this.scalar(t,e,s.no,i,r||s.opt);break;case"message":if(o){Nt(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":Nt("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?nt.onWrite:s)(this.info.typeName,e,t)}mapEntry(e,t,n,s,i){e.tag(n.no,st.LengthDelimited),e.fork();let r=s;switch(n.K){case ht.INT32:case ht.FIXED32:case ht.UINT32:case ht.SFIXED32:case ht.SINT32:r=Number.parseInt(s);break;case ht.BOOL:Nt("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,ht.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,st.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;Nt(t!==ht.BYTES&&t!==ht.STRING),e.tag(n,st.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=st.Varint,i=void 0===t,r=0===t;switch(e){case ht.INT32:n="int32";break;case ht.STRING:r=i||!t.length,s=st.LengthDelimited,n="string";break;case ht.BOOL:r=!1===t,n="bool";break;case ht.UINT32:n="uint32";break;case ht.DOUBLE:s=st.Bit64,n="double";break;case ht.FLOAT:s=st.Bit32,n="float";break;case ht.INT64:r=i||Ft.from(t).isZero(),n="int64";break;case ht.UINT64:r=i||Dt.from(t).isZero(),n="uint64";break;case ht.FIXED64:r=i||Dt.from(t).isZero(),s=st.Bit64,n="fixed64";break;case ht.BYTES:r=i||!t.byteLength,s=st.LengthDelimited,n="bytes";break;case ht.FIXED32:s=st.Bit32,n="fixed32";break;case ht.SFIXED32:s=st.Bit32,n="sfixed32";break;case ht.SFIXED64:r=i||Ft.from(t).isZero(),s=st.Bit64,n="sfixed64";break;case ht.SINT32:n="sint32";break;case ht.SINT64:r=i||Ft.from(t).isZero(),n="sint64"}return[s,n,i||r]}}const qt={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Qt={ignoreUnknownFields:!1},Kt=Object.values;function Gt(e,t,n){if(t===n)return!0;if(e!==ht.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 Xt(e,t,n){if(t.length!==n.length)return!1;for(let s=0;s<t.length;s++)if(!Gt(e,t[s],n[s]))return!1;return!0}function Jt(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 Yt={writeUnknownFields:!0,writerFactory:()=>new Zt};class Zt{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(Bt(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return Ut(e),kt(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){Vt(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){Bt(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Ut(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Ut(e),kt(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=Ft.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=Dt.from(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=Ft.from(e);return Ct(t.lo,t.hi,this.buf),this}sint64(e){let t=Ft.from(e),n=t.hi>>31;return Ct(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=Dt.from(e);return Ct(t.lo,t.hi,this.buf),this}}const en={readUnknownField:!0,readerFactory:e=>new tn(e)};class tn{constructor(e,t){this.varint64=wt,this.uint32=Rt,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 st.Varint:for(;128&this.buf[this.pos++];);break;case st.Bit64:this.pos+=4;case st.Bit32:this.pos+=4;break;case st.LengthDelimited:let t=this.uint32();this.pos+=t;break;case st.StartGroup:let n;for(;(n=this.tag()[1])!==st.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 Ft(...this.varint64())}uint64(){return new Dt(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(1&e);return e=(e>>>1|(1&t)<<31)^n,t=t>>>1^n,new Ft(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 Dt(this.sfixed32(),this.sfixed32())}sfixed64(){return new Ft(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 nn=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),sn=nn[ct]={};class rn{constructor(e,t,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=t.map(mt),this.options=null!=n?n:{},sn.value=this,this.messagePrototype=Object.create(null,nn),this.refTypeCheck=new ft(this),this.refJsonReader=new Wt(this),this.refJsonWriter=new $t(this),this.refBinReader=new jt(this),this.refBinWriter=new zt(this)}create(e){let t=function(e){const t=e.messagePrototype?Object.create(e.messagePrototype):Object.defineProperty({},ct,{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]=Ht(n.T,n.L);break;case"enum":t[e]=0;break;case"map":t[e]={}}}return t}(this);return void 0!==e&<(this,t,e),t}clone(e){let t=this.create();return lt(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?ht.INT32:s.T;if(!(s.repeat?Xt(e,i,r):Gt(e,i,r)))return!1;break;case"map":if(!("message"==s.V.kind?Jt(s.V.T(),Kt(i),Kt(r)):Xt("enum"==s.V.kind?ht.INT32:s.V.T,Kt(i),Kt(r))))return!1;break;case"message":let t=s.T();if(!(s.repeat?Jt(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){lt(this,e,t)}fromBinary(e,t){let n=function(e){return e?Object.assign(Object.assign({},en),e):en}(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({},Qt),e):Qt}(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({},qt),e):qt}(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({},Yt),e):Yt}(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 ${yt(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 rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};const on=new class extends rn{constructor(){super("peerConnectionOptions",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return void 0!==e&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},an=new class extends rn{constructor(){super("config",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"peerConnectionOptions",kind:"message",T:()=>on},{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&<(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=on.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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),e.peerConnectionOptions&&on.internalBinaryWrite(e.peerConnectionOptions,t.tag(2,st.LengthDelimited).fork(),n).join(),void 0!==e.protocolVersion&&t.tag(3,st.LengthDelimited).string(e.protocolVersion);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.id&&t.tag(2,st.LengthDelimited).string(e.id),void 0!==e.protocolVersion&&t.tag(3,st.LengthDelimited).string(e.protocolVersion);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.committedId&&t.tag(2,st.LengthDelimited).string(e.committedId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};const ln=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.newID&&t.tag(2,st.LengthDelimited).string(e.newID);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},cn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},dn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);for(let n=0;n<e.ids.length;n++)t.tag(2,st.LengthDelimited).string(e.ids[n]);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},hn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.streamerId&&t.tag(2,st.LengthDelimited).string(e.streamerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};const un=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.message&&t.tag(2,st.LengthDelimited).string(e.message);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),!1!==e.dataChannel&&t.tag(2,st.Varint).bool(e.dataChannel),!1!==e.sfu&&t.tag(3,st.Varint).bool(e.sfu),""!==e.playerId&&t.tag(5,st.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.playerId&&t.tag(2,st.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};const pn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.sdp&&t.tag(2,st.LengthDelimited).string(e.sdp),void 0!==e.playerId&&t.tag(3,st.LengthDelimited).string(e.playerId),void 0!==e.sfu&&t.tag(4,st.Varint).bool(e.sfu),void 0!==e.multiplex&&t.tag(5,st.Varint).bool(e.multiplex),void 0!==e.scalabilityMode&&t.tag(6,st.LengthDelimited).string(e.scalabilityMode);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},mn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.sdp&&t.tag(2,st.LengthDelimited).string(e.sdp),void 0!==e.playerId&&t.tag(3,st.LengthDelimited).string(e.playerId),void 0!==e.minBitrateBps&&t.tag(4,st.Varint).int32(e.minBitrateBps),void 0!==e.maxBitrateBps&&t.tag(5,st.Varint).int32(e.maxBitrateBps);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},gn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.candidate&&t.tag(1,st.LengthDelimited).string(e.candidate),""!==e.sdpMid&&t.tag(2,st.LengthDelimited).string(e.sdpMid),0!==e.sdpMLineIndex&&t.tag(3,st.Varint).int32(e.sdpMLineIndex),void 0!==e.usernameFragment&&t.tag(4,st.LengthDelimited).string(e.usernameFragment);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},fn=new class extends rn{constructor(){super("iceCandidate",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"candidate",kind:"message",T:()=>gn},{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&<(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=gn.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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),e.candidate&&gn.internalBinaryWrite(e.candidate,t.tag(2,st.LengthDelimited).fork(),n).join(),void 0!==e.playerId&&t.tag(3,st.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.playerId&&t.tag(2,st.LengthDelimited).string(e.playerId),void 0!==e.reason&&t.tag(3,st.LengthDelimited).string(e.reason);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};const yn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),0!==e.time&&t.tag(2,st.Varint).int32(e.time);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},vn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),0!==e.time&&t.tag(2,st.Varint).int32(e.time);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};const Sn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),0!==e.spatialLayer&&t.tag(2,st.Varint).int32(e.spatialLayer),0!==e.temporalLayer&&t.tag(3,st.Varint).int32(e.temporalLayer),""!==e.playerId&&t.tag(4,st.LengthDelimited).string(e.playerId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},bn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},wn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.playerId&&t.tag(2,st.LengthDelimited).string(e.playerId),0!==e.sendStreamId&&t.tag(3,st.Varint).int32(e.sendStreamId),0!==e.recvStreamId&&t.tag(4,st.Varint).int32(e.recvStreamId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},Cn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.sfuId&&t.tag(2,st.LengthDelimited).string(e.sfuId),0!==e.sendStreamId&&t.tag(3,st.Varint).int32(e.sendStreamId),0!==e.recvStreamId&&t.tag(4,st.Varint).int32(e.recvStreamId);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}},new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};const Tn=new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),0!==e.count&&t.tag(2,st.Varint).int32(e.count);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};function Mn(e,t){const n=e.create();return n.type=e.typeName,t&&e.mergePartial(n,t),n}new class extends rn{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&<(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?nt.onRead:r)(this.typeName,i,t,s,o)}}return i}internalBinaryWrite(e,t,n){""!==e.type&&t.tag(1,st.LengthDelimited).string(e.type),""!==e.data&&t.tag(2,st.LengthDelimited).string(e.data);let s=n.writeUnknownFields;return!1!==s&&(1==s?nt.onWrite:s)(this.typeName,e,t),t}};class En{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(Mn(yn,{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 kn{constructor(e){this.videoElementProvider=e,this.audioElement=document.createElement("Audio"),this.videoElementProvider.setAudioElement(this.audioElement)}handleOnTrack(e){if(Y.Info("handleOnTrack "+JSON.stringify(e.streams)),e.streams.length<1||"probator"==e.streams[0].id)return;const t=this.videoElementProvider.getVideoElement();if(e.track&&Y.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 Y.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,Y.Info("Created new audio element to play separate audio stream."))}}class Rn{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 Pn{constructor(e){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new Rn(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,Y.Info(`received first chunk of freeze frame: ${this.jpeg.length}/${this.size}`);this.jpeg.length===this.size?(this.receiving=!1,this.valid=!0,Y.Info(`received complete freeze frame ${this.size}`),this.updateFreezeFrameAndShow(this.jpeg,t)):this.jpeg.length>this.size&&(Y.Error(`received bigger freeze frame than advertised: ${this.jpeg.length}/${this.size}`),this.jpeg=void 0,this.receiving=!1)}}class In{constructor(e,t,n){this.active=!1,this.countdownActive=!1,this.warnTimer=void 0,this.countDown=0,this.countDownTimer=void 0,this.config=e,this.pixelStreaming=t,this.onDismissAfk=n,this.onAFKTimedOutCallback=()=>{console.log("AFK timed out, did you want to override this callback?")}}onAfkClick(){clearInterval(this.countDownTimer),(this.active||this.countdownActive)&&(this.startAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new oe))}startAfkWarningTimer(){this.config.getNumericSettingValue(Ke.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(qe.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(qe.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout(()=>this.activateAfkEvent(),1e3*this.config.getNumericSettingValue(Ke.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new ie({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(Ke.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new re({countDown:this.countDown})),this.config.isFlagEnabled(qe.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval(()=>{this.countDown--,0==this.countDown?(this.pixelStreaming.dispatchEvent(new ae),this.onAFKTimedOutCallback(),Y.Info("You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new re({countDown:this.countDown}))},1e3)}}class xn{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;Y.Info(`Data Channel (${this.label}) opened.`),this.onOpen(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}handleOnClose(e){var t;Y.Info(`Data Channel (${this.label}) closed.`),this.onClose(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}handleOnMessage(e){Y.Info(`Data Channel (${this.label}) message: ${e}`)}handleOnError(e){var t;Y.Info(`Data Channel (${this.label}) error: ${e}`),this.onError(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}onOpen(e,t){}onClose(e,t){}onError(e,t){}}class Ln{}class An{}class On{}class Dn{}class Fn{}class Nn{}class Un{}class Bn{}class Vn{constructor(){this.inboundVideoStats=new An,this.inboundAudioStats=new Ln,this.candidatePairs=new Array,this.datachannelStats=new On,this.localCandidates=new Array,this.remoteCandidates=new Array,this.outboundVideoStats=new Fn,this.outboundAudioStats=new Fn,this.remoteOutboundAudioStats=new Nn,this.remoteOutboundVideoStats=new Nn,this.sessionStats=new Un,this.streamStats=new Bn,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:Y.Error("unhandled Stat Type"),Y.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 Dn;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 Dn;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:Y.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}}var _n=o(963);class Wn{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 $n{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 Hn{}class jn{}class zn{constructor(){this.latestSenderRecvClockOffset=null}calculate(e,t){const n=new qn,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 jn,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 Hn;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 qn{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 Qn=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 Kn{constructor(e,t,n){this.config=t,this.createPeerConnection(e,n),this.latencyCalculator=new zn}createPeerConnection(e,t){this.config.isFlagEnabled(qe.ForceTURN)&&(e.iceTransportPolicy="relay",Y.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 Vn,this.preferredCodec=t,this.updateCodecSelection=!0}createOffer(e,t){return Qn(this,void 0,void 0,function*(){Y.Info("Create Offer");const n="localhost"===location.hostname||"127.0.0.1"===location.hostname,s="https:"===location.protocol;let i=t.isFlagEnabled(qe.UseMic),r=t.isFlagEnabled(qe.UseCamera);!i&&!r||n||s||(i=!1,r=!1,Y.Error("Microphone and Webcam access in the browser will not work if you are not on HTTPS or localhost. Disabling mic and webcam access."),Y.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){return Qn(this,void 0,void 0,function*(){var n;Y.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(qe.UseMic),r=t.isFlagEnabled(qe.UseCamera);!i&&!r||n||s||(i=!1,r=!1,Y.Error("Microphone and Webcam access in the browser will not work if you are not on HTTPS or localhost. Disabling mic and webcam access."),Y.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(Ye.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=>{Y.Error(`createAnswer() failed - ${e}`)})})})})}receiveAnswer(e){var t;null===(t=this.peerConnection)||void 0===t||t.setRemoteDescription(e),this.config.setOptionSettingOptions(Ye.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e))}generateStats(){this.peerConnection.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(Ye.PreferredCodec).options;if(s.includes(n))return void this.config.setOptionSettingValue(Ye.PreferredCodec,n);const i=s.filter(e=>-1!==e.indexOf(t));if(i.length>0)return void this.config.setOptionSettingValue(Ye.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(qe.ForceMonoAudio)?"stereo=0;":"stereo=1;",s+="useinbandfec=1",n=n.replace("useinbandfec=1",s),this.config.isFlagEnabled(qe.EnableCaptureTimeExt)&&!this.isFirefox()&&(n=$n.addVideoHeaderExtensionToSdp(n,"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time")),n}isFirefox(){return navigator.userAgent.indexOf("Firefox")>0}handleOnIce(e){var t;Y.Info("peerconnection handleOnIce"),this.config.isFlagEnabled(qe.ForceTURN)&&e.candidate.indexOf("relay")<0?Y.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){Y.Info("signaling state change: "+e)}handleIceConnectionStateChange(e){Y.Info("ice connection state change: "+e),this.onIceConnectionStateChange(e)}handleIceGatheringStateChange(e){Y.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(Ye.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 Qn(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 Qn(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(Wn.canTransceiverReceiveVideo(e))for(const t of r.getTracks())t.kind&&"video"==t.kind&&(e.sender.replaceTrack(t),e.direction="sendrecv")}else for(const e of r.getTracks())e.kind&&"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 Qn(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(Wn.canTransceiverReceiveAudio(e))for(const t of r.getTracks())t.kind&&"audio"==t.kind&&(e.sender.replaceTrack(t),e.direction="sendrecv")}else for(const e of r.getTracks())e.kind&&"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,_n.splitSections)(e.sdp);return n.shift(),n.forEach(e=>{const{codecs:n}=(0,_n.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 Gn{constructor(){this.PixelStreamingSettings=new Xn,this.EncoderSettings=new Jn,this.WebRTCSettings=new Yn}ueCompatible(){null!=this.WebRTCSettings.MaxFPS&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}}class Xn{}class Jn{}class Yn{}class Zn{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||(Y.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||(Y.Info(`Setting CaptureToSendMs Ms \n ${this.PostCaptureTimeMs} \n ${this.PreCaptureTimeMs}`),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}}class es{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(),Y.Info("Received first chunk of file"));const n=new TextDecoder("utf-16").decode(e.slice(1));Y.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(),Y.Info("Received first chunk of file"));const n=new TextDecoder("utf-16").decode(e.slice(1));Y.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),Y.Info(`Received file chunk: ${t.data.length}/${t.chunks}`),t.data.length===t.chunks){t.receiving=!1,t.valid=!0,Y.Info("Received complete file");const e=(new Date).getTime()-t.timestampStart,n=Math.round(16384*t.chunks/e);Y.Info(`Average transfer bitrate: ${n}kb/s over ${e/1e3} seconds`)}else t.data.length>t.chunks&&(t.receiving=!1,Y.Error(`Received bigger file than advertised: ${t.data.length}/${t.chunks}`))}}class ts{constructor(){this.mimetype="",this.extension="",this.receiving=!1,this.chunks=0,this.data=[],this.valid=!1}}class ns{}ns.backSpace=8,ns.shift=16,ns.control=17,ns.alt=18,ns.rightShift=253,ns.rightControl=254,ns.rightAlt=255;const ss=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});class is{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===ns.backSpace&&this.handleOnKeyPress(new KeyboardEvent("keypress",{charCode:ns.backSpace,keyCode:ns.backSpace})),this.config.isFlagEnabled(qe.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(qe.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 ss?ss[t.code]:(Y.Warning(`Keyboard code of ${t.code} is not supported in our mapping, ignoring this key.`),null)}return e.keyCode===ns.shift&&"ShiftRight"===e.code?ns.rightShift:e.keyCode===ns.control&&"ControlRight"===e.code?ns.rightControl:e.keyCode===ns.alt&&"AltRight"===e.code?ns.rightAlt:e.keyCode}isKeyCodeBrowserKey(e){return e>=112&&e<=123||9===e}}class rs{}rs.mainButton=0,rs.auxiliaryButton=1,rs.secondaryButton=2,rs.fourthButton=3,rs.fifthButton=4;class os{}os.primaryButton=1,os.secondaryButton=2,os.auxiliaryButton=4,os.fourthButton=8,os.fifthButton=16;class as{constructor(e,t,n,s){this.streamMessageController=e,this.coordinateConverter=n,this.videoPlayer=t,this.activeKeys=s,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&os.primaryButton&&this.sendMouseUp(rs.mainButton,s.x,s.y),e&os.secondaryButton&&this.sendMouseUp(rs.secondaryButton,s.x,s.y),e&os.auxiliaryButton&&this.sendMouseUp(rs.auxiliaryButton,s.x,s.y),e&os.fourthButton&&this.sendMouseUp(rs.fourthButton,s.x,s.y),e&os.fifthButton&&this.sendMouseUp(rs.fifthButton,s.x,s.y)}pressMouseButtons(e,t,n){if(!this.videoPlayer.isVideoReady())return;const s=this.coordinateConverter.translateUnsigned(t,n);e&os.primaryButton&&this.sendMouseDown(rs.mainButton,s.x,s.y),e&os.secondaryButton&&this.sendMouseDown(rs.secondaryButton,s.x,s.y),e&os.auxiliaryButton&&this.sendMouseDown(rs.auxiliaryButton,s.x,s.y),e&os.fourthButton&&this.sendMouseDown(rs.fourthButton,s.x,s.y),e&os.fifthButton&&this.sendMouseDown(rs.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 ls extends as{constructor(e,t,n,s){super(e,t,n,s),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?(Y.Info("Pointer locked"),document.addEventListener("mousemove",this.onMouseMoveListener)):(Y.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])}}class cs extends as{constructor(e,t,n,s){super(e,t,n,s),this.videoElementParent=t.getVideoParentElement(),this.onMouseUpListener=this.onMouseUp.bind(this),this.onMouseDownListener=this.onMouseDown.bind(this),this.onMouseDblClickListener=this.onMouseDblClick.bind(this),this.onMouseWheelListener=this.onMouseWheel.bind(this),this.onMouseMoveListener=this.onMouseMove.bind(this),this.onContextMenuListener=this.onContextMenu.bind(this)}register(){super.register(),this.videoElementParent.addEventListener("mousemove",this.onMouseMoveListener),this.videoElementParent.addEventListener("mousedown",this.onMouseDownListener),this.videoElementParent.addEventListener("mouseup",this.onMouseUpListener),this.videoElementParent.addEventListener("contextmenu",this.onContextMenuListener),this.videoElementParent.addEventListener("wheel",this.onMouseWheelListener),this.videoElementParent.addEventListener("dblclick",this.onMouseDblClickListener)}unregister(){this.videoElementParent.removeEventListener("mousemove",this.onMouseMoveListener),this.videoElementParent.removeEventListener("mousedown",this.onMouseDownListener),this.videoElementParent.removeEventListener("mouseup",this.onMouseUpListener),this.videoElementParent.removeEventListener("contextmenu",this.onContextMenuListener),this.videoElementParent.removeEventListener("wheel",this.onMouseWheelListener),this.videoElementParent.removeEventListener("dblclick",this.onMouseDblClickListener),super.unregister()}onMouseDown(e){if(!this.videoPlayer.isVideoReady())return;const t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY);this.streamMessageController.toStreamerHandlers.get("MouseDown")([e.button,t.x,t.y]),e.preventDefault()}onMouseUp(e){if(!this.videoPlayer.isVideoReady())return;const t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY);this.streamMessageController.toStreamerHandlers.get("MouseUp")([e.button,t.x,t.y]),e.preventDefault()}onContextMenu(e){this.videoPlayer.isVideoReady()&&e.preventDefault()}onMouseMove(e){if(!this.videoPlayer.isVideoReady())return;const t=this.coordinateConverter.translateUnsigned(e.offsetX,e.offsetY),n=this.coordinateConverter.translateSigned(e.movementX,e.movementY);this.streamMessageController.toStreamerHandlers.get("MouseMove")([t.x,t.y,n.x,n.y]),e.preventDefault()}onMouseWheel(e){if(!this.videoPlayer.isVideoReady())return;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])}}class ds{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&&Y.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;Y.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 hs{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")([rs.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")([rs.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 us(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 ps,ms,gs;!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"}(ps||(ps={}));class fs{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:us(t),prevState:us(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];delete this.controllers[t.index],this.controllers=this.controllers.filter(e=>void 0!==e),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==ps.LeftTrigger?e.get("GamepadAnalog")([n,5,i.value]):s==ps.RightTrigger?e.get("GamepadAnalog")([n,6,i.value]):e.get("GamepadButtonPressed")([n,s,r.pressed?1:0]):!i.pressed&&r.pressed&&(s==ps.LeftTrigger?e.get("GamepadAnalog")([n,5,0]):s==ps.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=us(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 ys{constructor(e,t,n){this.activeKeys=new vs,this.toStreamerMessagesProvider=e,this.videoElementProvider=t,this.coordinateConverter=n}registerKeyBoard(e){Y.Info("Register Keyboard Events");const t=new is(this.toStreamerMessagesProvider,e,this.activeKeys);return t.register(),t}registerMouse(e){let t;return Y.Info("Register Mouse Events"),t=e==tt.HoveringMouse?new cs(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys):new ls(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter,this.activeKeys),t.register(),t}registerTouch(e){let t;return Y.Info("Registering Touch"),t=e?new hs(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter):new ds(this.toStreamerMessagesProvider,this.videoElementProvider,this.coordinateConverter),t.register(),t}registerGamePad(){Y.Info("Register Game Pad");const e=new fs(this.toStreamerMessagesProvider);return e.register(),e}}class vs{constructor(){this.activeKeys=[],this.activeKeys=[]}getActiveKeys(){return this.activeKeys}}class Ss{constructor(e,t){this.lastTimeResized=(new Date).getTime(),this.videoElement=document.createElement("video"),this.config=t,this.videoElement.id="streamingVideo",this.videoElement.disablePictureInPicture=!0,this.videoElement.playsInline=!0,this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.pointerEvents="all",e.appendChild(this.videoElement),this.onResizePlayerCallback=()=>{console.log("Resolution changed, restyling player, did you forget to override this function?")},this.onMatchViewportResolutionCallback=()=>{console.log("Resolution changed and match viewport resolution is turned on, did you forget to override this function?")},this.videoElement.onclick=()=>{null!=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(qe.StartVideoMuted),this.videoElement.autoplay=this.config.isFlagEnabled(qe.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(qe.MatchViewportResolution))if((new Date).getTime()-this.lastTimeResized>300){const e=this.getVideoParentElement();if(!e)return;this.onMatchViewportResolutionCallback(e.clientWidth,e.clientHeight),this.lastTimeResized=(new Date).getTime()}else Y.Info("Resizing too often - skipping"),clearTimeout(this.resizeTimeoutHandle),this.resizeTimeoutHandle=window.setTimeout(()=>this.updateVideoStreamSize(),100)}}class bs{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 ms.ToStreamer:this.toStreamerHandlers.set(t,n);break;case ms.FromStreamer:this.fromStreamerHandlers.set(t,n);break;default:Y.Info(`Unknown message direction ${e}`)}}}!function(e){e[e.ToStreamer=0]="ToStreamer",e[e.FromStreamer=1]="FromStreamer"}(ms||(ms={}));class ws{constructor(){this.responseEventListeners=new Map}addResponseEventListener(e,t){this.responseEventListeners.set(e,t)}removeResponseEventListener(e){this.responseEventListeners.delete(e)}onResponse(e){Y.Info("DataChannelReceiveMessageType.Response");const t=new TextDecoder("utf-16").decode(e.slice(1));Y.Info(t),this.responseEventListeners.forEach(e=>{e(t)})}}class Cs{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 Y.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 Y.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;const i=new TextEncoder;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*i.encode(e).length}});const r=new DataView(new ArrayBuffer(s+1));r.setUint8(0,n.id);let o=1;t.forEach((e,t)=>{switch(n.structure[t]){case"uint8":r.setUint8(o,e),o+=1;break;case"uint16":r.setUint16(o,e,!0),o+=2;break;case"int16":r.setInt16(o,e,!0),o+=2;break;case"float":r.setFloat32(o,e,!0),o+=4;break;case"double":r.setFloat64(o,e,!0),o+=8;break;case"string":r.setUint16(o,e.length,!0),o+=2;for(let t=0;t<e.length;t++)r.setUint16(o,e.charCodeAt(t),!0),o+=2}}),this.dataChannelSender.canSend()?this.dataChannelSender.sendData(r.buffer):Y.Info(`Data channel cannot send yet, skipping sending message: ${e} - ${new Uint8Array(r.buffer)}`)}}class Ts{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 Ms{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),Y.Info(`Message Sent: ${new Uint8Array(e)}`),this.resetAfkWarningTimerOnDataSend()):Y.Error(`Message Failed: ${new Uint8Array(e)}`)}resetAfkWarningTimerOnDataSend(){}}class Es{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 ks{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 Rs{constructor(e,t){this.shouldShowPlayOverlay=!0,this.autoJoinTimer=void 0,this.config=e,this.pixelStreaming=t,this.responseController=new ws,this.file=new ts,this.sdpConstraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this.afkController=new In(this.config,this.pixelStreaming,this.onAfkTriggered.bind(this)),this.afkController.onAFKTimedOutCallback=()=>{this.closeSignalingServer("You have been disconnected due to inactivity.",!1)},this.freezeFrameController=new Pn(this.pixelStreaming.videoElementParent),this.videoPlayer=new Ss(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 kn(this.videoPlayer),this.coordinateConverter=new Es,this.sendrecvDataChannelController=new xn,this.recvDataChannelController=new xn,this.registerDataChannelEventEmitters(this.sendrecvDataChannelController),this.registerDataChannelEventEmitters(this.recvDataChannelController),this.dataChannelSender=new Ms(this.sendrecvDataChannelController),this.dataChannelSender.resetAfkWarningTimerOnDataSend=()=>this.afkController.resetAfkWarningTimer(),this.streamMessageController=new bs,this.transport=new ot(e.webSocketProtocols),this.protocol=new at(this.transport),this.protocol.addListener(an.typeName,e=>this.handleOnConfigMessage(e)),this.protocol.addListener(yn.typeName,e=>this.handlePingMessage(e)),this.protocol.addListener(dn.typeName,e=>this.handleStreamerListMessage(e)),this.protocol.addListener(un.typeName,e=>this.handleSubscribeFailedMessage(e)),this.protocol.addListener(ln.typeName,e=>this.handleStreamerIDChangedMessage(e)),this.protocol.addListener(Tn.typeName,e=>{const t=e;this.pixelStreaming._onPlayerCount(t.count)}),this.protocol.addListener(mn.typeName,e=>this.handleWebRtcAnswer(e)),this.protocol.addListener(pn.typeName,e=>this.handleWebRtcOffer(e)),this.protocol.addListener(wn.typeName,e=>this.handleWebRtcSFUPeerDatachannels(e)),this.protocol.addListener(fn.typeName,e=>{const t=e;this.handleIceCandidate(t.candidate)}),this.protocol.transport.addListener("open",()=>{if(!this.config.isFlagEnabled(qe.BrowserSendOffer)){const e=Mn(cn);this.protocol.sendMessage(e)}this.reconnectAttempt=0,this.isReconnecting=!1}),this.protocol.transport.addListener("error",()=>{Y.Error("Got a transport error.")}),this.protocol.transport.addListener("close",e=>{const t=this.config.getNumericSettingValue(Ke.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(Ye.PreferredCodec).options=ze.getSupportedVideoCodecs(),this.pixelStreaming._onDisconnect(r,i),this.afkController.stopAfkWarningTimer(),this.statsTimerHandle&&void 0!==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 Cs(this.dataChannelSender,this.streamMessageController),this.toStreamerMessagesController=new Ts(this.sendMessageController),this.registerMessageHandlers(),this.streamMessageController.populateDefaultProtocol(),this.inputClassesFactory=new ys(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(Ye.StreamerId,e=>{if(void 0===e||""===e)return;this.peerConnectionController.peerConnection.close(),this.peerConnectionController.createPeerConnection(this.peerConfig,this.preferredCodec),this.subscribedStream=e;const t=Mn(hn,{streamerId:e});this.protocol.sendMessage(t)}),this.config._addOnOptionSettingChangedListener(Ye.PreferredQuality,e=>{if(void 0===e||""===e)return;let t;if(this.isUsingSVC)t=Mn(Sn,{spatialLayer:+e[1]-1,temporalLayer:+e[3]-1});else{const n=this.config.getSettingOption(Ye.PreferredQuality).options.indexOf(e);t=Mn(Sn,{spatialLayer:n,temporalLayer:0})}this.protocol.sendMessage(t)}),this.setVideoEncoderAvgQP(-1),this.signallingUrlBuilder=()=>this.config.getTextSettingValue(Xe.SignallingServerUrl)}destroyVideoPlayer(){this.videoPlayer.destroy()}handleOnMessage(e){const t=new Uint8Array(e.data);Y.Info("Message incoming:"+t);const n=this.streamMessageController.fromStreamerMessages.get(t[0]);this.streamMessageController.fromStreamerHandlers.get(n)(e.data)}registerMessageHandlers(){this.streamMessageController.registerMessageHandler(ms.FromStreamer,"QualityControlOwnership",e=>this.onQualityControlOwnership(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"Response",e=>this.responseController.onResponse(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"Command",e=>{this.onCommand(e)}),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"FreezeFrame",e=>this.onFreezeFrameMessage(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"UnfreezeFrame",()=>this.invalidateFreezeFrameAndEnableVideo()),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"VideoEncoderAvgQP",e=>this.handleVideoEncoderAvgQP(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"LatencyTest",e=>this.handleLatencyTestResult(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"DataChannelLatencyTest",e=>this.handleDataChannelLatencyTestResponse(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"InitialSettings",e=>this.handleInitialSettings(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"FileExtension",e=>this.onFileExtension(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"FileMimeType",e=>this.onFileMimeType(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"FileContents",e=>this.onFileContents(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"TestEcho",()=>{}),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"InputControlOwnership",e=>this.onInputControlOwnership(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"GamepadResponse",e=>this.onGamepadResponse(e)),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"Multiplexed",()=>{}),this.streamMessageController.registerMessageHandler(ms.FromStreamer,"Protocol",e=>this.onProtocolMessage(e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"IFrameRequest",()=>this.sendMessageController.sendMessageToStreamer("IFrameRequest")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"RequestQualityControl",()=>this.sendMessageController.sendMessageToStreamer("RequestQualityControl")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"FpsRequest",()=>this.sendMessageController.sendMessageToStreamer("FpsRequest")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"AverageBitrateRequest",()=>this.sendMessageController.sendMessageToStreamer("AverageBitrateRequest")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"StartStreaming",()=>this.sendMessageController.sendMessageToStreamer("StartStreaming")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"StopStreaming",()=>this.sendMessageController.sendMessageToStreamer("StopStreaming")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"LatencyTest",e=>this.sendMessageController.sendMessageToStreamer("LatencyTest",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"RequestInitialSettings",()=>this.sendMessageController.sendMessageToStreamer("RequestInitialSettings")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"TestEcho",()=>{}),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"UIInteraction",e=>this.sendMessageController.sendMessageToStreamer("UIInteraction",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"Command",e=>this.sendMessageController.sendMessageToStreamer("Command",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"TextboxEntry",e=>this.sendMessageController.sendMessageToStreamer("TextboxEntry",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"KeyDown",e=>this.sendMessageController.sendMessageToStreamer("KeyDown",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"KeyUp",e=>this.sendMessageController.sendMessageToStreamer("KeyUp",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"KeyPress",e=>this.sendMessageController.sendMessageToStreamer("KeyPress",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"MouseEnter",e=>this.sendMessageController.sendMessageToStreamer("MouseEnter",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"MouseLeave",e=>this.sendMessageController.sendMessageToStreamer("MouseLeave",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"MouseDown",e=>this.sendMessageController.sendMessageToStreamer("MouseDown",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"MouseUp",e=>this.sendMessageController.sendMessageToStreamer("MouseUp",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"MouseMove",e=>this.sendMessageController.sendMessageToStreamer("MouseMove",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"MouseWheel",e=>this.sendMessageController.sendMessageToStreamer("MouseWheel",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"MouseDouble",e=>this.sendMessageController.sendMessageToStreamer("MouseDouble",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"TouchStart",e=>this.sendMessageController.sendMessageToStreamer("TouchStart",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"TouchEnd",e=>this.sendMessageController.sendMessageToStreamer("TouchEnd",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"TouchMove",e=>this.sendMessageController.sendMessageToStreamer("TouchMove",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"GamepadConnected",()=>this.sendMessageController.sendMessageToStreamer("GamepadConnected")),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"GamepadButtonPressed",e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonPressed",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"GamepadButtonReleased",e=>this.sendMessageController.sendMessageToStreamer("GamepadButtonReleased",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"GamepadAnalog",e=>this.sendMessageController.sendMessageToStreamer("GamepadAnalog",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"GamepadDisconnected",e=>this.sendMessageController.sendMessageToStreamer("GamepadDisconnected",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XREyeViews",e=>this.sendMessageController.sendMessageToStreamer("XREyeViews",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRHMDTransform",e=>this.sendMessageController.sendMessageToStreamer("XRHMDTransform",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRControllerTransform",e=>this.sendMessageController.sendMessageToStreamer("XRControllerTransform",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRSystem",e=>this.sendMessageController.sendMessageToStreamer("XRSystem",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRButtonTouched",e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouched",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRButtonTouchReleased",e=>this.sendMessageController.sendMessageToStreamer("XRButtonTouchReleased",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRButtonPressed",e=>this.sendMessageController.sendMessageToStreamer("XRButtonPressed",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRButtonReleased",e=>this.sendMessageController.sendMessageToStreamer("XRButtonReleased",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"XRAnalog",e=>this.sendMessageController.sendMessageToStreamer("XRAnalog",e)),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"ChannelRelayStatus",()=>{}),this.streamMessageController.registerMessageHandler(ms.ToStreamer,"Multiplexed",()=>{})}onCommand(e){Y.Info("DataChannelReceiveMessageType.Command");const t=new TextDecoder("utf-16").decode(e.slice(1));Y.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 Fe(r))}onProtocolMessage(e){try{const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);Object.prototype.hasOwnProperty.call(n,"Direction")||Y.Error("Malformed protocol received. Ensure the protocol message contains a direction");const s=n.Direction;delete n.Direction,Y.Info(`Received new ${s==ms.FromStreamer?"FromStreamer":"ToStreamer"} protocol. Updating existing protocol...`),Object.keys(n).forEach(e=>{const t=n[e];switch(s){case ms.ToStreamer:if(!Object.prototype.hasOwnProperty.call(t,"id"))return void Y.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):Y.Error(`There was no registered handler for "${e}" - try adding one using registerMessageHandler(MessageDirection.ToStreamer, "${e}", myHandler)`);break;case ms.FromStreamer:if(!Object.prototype.hasOwnProperty.call(t,"id"))return void Y.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):Y.Error(`There was no registered handler for "${t}" - try adding one using registerMessageHandler(MessageDirection.FromStreamer, "${e}", myHandler)`);break;default:Y.Error(`Unknown direction: ${s}`)}}),this.toStreamerMessagesController.SendRequestInitialSettings(),this.toStreamerMessagesController.SendRequestQualityControl()}catch(e){Y.Info(e)}}onInputControlOwnership(e){const t=new Uint8Array(e);Y.Info("DataChannelReceiveMessageType.InputControlOwnership");const n=new Boolean(t[1]).valueOf();Y.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())):Y.Info("This player has no protocol connection.")}loadFreezeFrameOrShowPlayOverlay(){this.pixelStreaming.dispatchEvent(new Pe({shouldShowPlayOverlay:this.shouldShowPlayOverlay,isValid:this.freezeFrameController.valid,jpegData:this.freezeFrameController.jpeg})),!0===this.shouldShowPlayOverlay?(Y.Info("showing play overlay"),this.resizePlayerStyle()):(Y.Info("showing freeze frame"),this.freezeFrameController.showFreezeFrame()),setTimeout(()=>{this.videoPlayer.setVideoEnabled(!1)},this.freezeFrameController.freezeFrameDelay)}onFreezeFrameMessage(e){Y.Info("DataChannelReceiveMessageType.FreezeFrame");const t=new Uint8Array(e);this.freezeFrameController.processFreezeFrameMessage(t,()=>this.loadFreezeFrameOrShowPlayOverlay())}invalidateFreezeFrameAndEnableVideo(){Y.Info("DataChannelReceiveMessageType.FreezeFrame"),setTimeout(()=>{this.pixelStreaming.dispatchEvent(new Ie),this.freezeFrameController.hideFreezeFrame()},this.freezeFrameController.freezeFrameDelay),this.videoPlayer.getVideoElement()&&this.videoPlayer.setVideoEnabled(!0)}onFileExtension(e){const t=new Uint8Array(e);es.setExtensionFromBytes(t,this.file)}onFileMimeType(e){const t=new Uint8Array(e);es.setMimeTypeFromBytes(t,this.file)}onFileContents(e){const t=new Uint8Array(e);es.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 Ee({message:e})),Y.Error(e),void this.closeSignalingServer("Stream not initialized correctly",!1)}if(this.videoPlayer.hasVideoSource()){if(this.setTouchInputEnabled(this.config.isFlagEnabled(qe.TouchInput)),this.pixelStreaming.dispatchEvent(new ke),this.streamController.audioElement.srcObject){const e=this.config.isFlagEnabled(qe.StartVideoMuted);this.streamController.audioElement.muted=e,e?this.playVideo():this.streamController.audioElement.play().then(()=>{this.playVideo()}).catch(e=>{Y.Info(e),Y.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 Re({reason:e}))})}else this.playVideo();this.shouldShowPlayOverlay=!1,this.freezeFrameController.showFreezeFrame()}else Y.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(),Y.Info(e),Y.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 Re({reason:e}))})}autoPlayVideoOrSetUpPlayOverlay(){this.config.isFlagEnabled(qe.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(Ke.KeepaliveDelay);t>0&&(this.keepalive=new En(this.protocol,t),this.keepalive.onTimeout=()=>{Y.Error("Protocol timeout"),this.protocol.disconnect()})}startSession(e){if(this.peerConfig=e,this.config.isFlagEnabled(qe.ForceTURN)&&!this.checkTurnServerAvailability(e))return Y.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 Kn(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):Y.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):Y.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(qe.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 Y.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 Y.Info(`A turn sever was found at ${e}`),!0;return Y.Info("A turn sever was not found"),!1}handleOnConfigMessage(e){this.resizePlayerStyle(),this.startSession(e.peerConnectionOptions)}handlePingMessage(e){this.protocol.sendMessage(Mn(vn,{time:e.time}))}handleStreamerListMessage(e){Y.Info(`Got streamer list ${e.ids}`);let t="";const n=this.config.getSettingOption(Ye.StreamerId);n.selected.toString().trim()&&(t=n.selected);const s=[...e.ids];s.unshift(""),this.config.setOptionSettingOptions(Ye.StreamerId,s);let i="";const r=this.config.isFlagEnabled(qe.WaitForStreamer),o=this.config.getNumericSettingValue(Ke.MaxReconnectAttempts),a=this.config.getNumericSettingValue(Ke.StreamerAutoJoinInterval),l=this.config.useUrlParams,c=new ks(window.location.search);l&&c.has(Ye.StreamerId)?t=c.get(Ye.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(Ye.StreamerId,i)):r&&(this.reconnectAttempt<o?(this.reconnectAttempt++,this.isReconnecting=!0,setTimeout(()=>{this.protocol.sendMessage(Mn(cn))},a)):(this.reconnectAttempt=0,this.isReconnecting=!1,this.enableAutoReconnect=!1)),this.pixelStreaming.dispatchEvent(new Le({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(Ye.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 Ae({newID:t}))}handleWebRtcAnswer(e){Y.Info(`Got answer sdp ${e.sdp}`);const t={sdp:e.sdp,type:"answer"};this.peerConnectionController.receiveAnswer(t),this.handlePostWebrtcNegotiation()}handleWebRtcOffer(e){Y.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(Ye.PreferredQuality,n),this.config.setOptionSettingValue(Ye.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(Mn(Cn)),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(qe.MouseInput)),this.setKeyboardInputEnabled(this.config.isFlagEnabled(qe.KeyboardInput)),this.setGamePadInputEnabled(this.config.isFlagEnabled(qe.GamepadInput))}handleIceCandidate(e){Y.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&&(Y.Info("Local ICE candidate generated: "+JSON.stringify(e.candidate)),this.protocol.sendMessage(Mn(fn,{candidate:e.candidate})))}handleDataChannel(e){Y.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 Y.Error(`handleSendWebRTCOffer was called with type ${e.type} - it only expects "offer"`);Y.Info("Sending the offer to the Server");const t={sdp:e.sdp,minBitrateBps:1e3*this.config.getNumericSettingValue(Ke.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(Ke.WebRTCMaxBitrate)};this.protocol.sendMessage(Mn(pn,t)),this.pixelStreaming._onWebRtcSdpOffer(e)}handleSendWebRTCAnswer(e){if("answer"!==e.type)return void Y.Error(`handleSendWebRTCAnswer was called with type ${e.type} - it only expects "answer"`);Y.Info("Sending the answer to the Server");const t={sdp:e.sdp,minBitrateBps:1e3*this.config.getNumericSettingValue(Ke.WebRTCMinBitrate),maxBitrateBps:1e3*this.config.getNumericSettingValue(Ke.WebRTCMaxBitrate)};this.protocol.sendMessage(Mn(mn,t)),this.isUsingSFU&&this.protocol.sendMessage(Mn(bn)),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){Y.Info(`MinQP=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MinQP":e})])}sendEncoderMaxQP(e){Y.Info(`MaxQP=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MaxQP":e})])}sendEncoderMinQuality(e){Y.Info(`MinQuality=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MinQuality":e})])}sendEncoderMaxQuality(e){Y.Info(`MaxQuality=${e}\n`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"Encoder.MaxQuality":e})])}sendWebRTCMinBitrate(e){Y.Info(`WebRTC Min Bitrate=${e}`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MinBitrate":e})])}sendWebRTCMaxBitrate(e){Y.Info(`WebRTC Max Bitrate=${e}`),null!=e&&this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"WebRTC.MaxBitrate":e})])}sendWebRTCFps(e){Y.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(){Y.Info("---- Sending show stat to UE ----"),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({"stat.fps":""})])}sendIframeRequest(){Y.Info("---- Sending Request for an IFrame ----"),this.streamMessageController.toStreamerHandlers.get("IFrameRequest")()}emitUIInteraction(e){Y.Info("---- Sending custom UIInteraction message ----"),this.streamMessageController.toStreamerHandlers.get("UIInteraction")([JSON.stringify(e)])}emitCommand(e){Y.Info("---- Sending custom Command message ----"),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify(e)])}emitConsoleCommand(e){Y.Info("---- Sending custom Command:ConsoleCommand message ----"),this.streamMessageController.toStreamerHandlers.get("Command")([JSON.stringify({ConsoleCommand:e})])}sendRequestQualityControlOwnership(){Y.Info("---- Sending Request to Control Quality ----"),this.toStreamerMessagesController.SendRequestQualityControl()}sendTextboxEntry(e){var t;Y.Info("---- Sending TextboxEntry message ----"),null===(t=this.streamMessageController.toStreamerHandlers.get("TextboxEntry"))||void 0===t||t([e])}handleLatencyTestResult(e){Y.Info("DataChannelReceiveMessageType.latencyTest");const t=new TextDecoder("utf-16").decode(e.slice(1)),n=new Zn;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){Y.Info("DataChannelReceiveMessageType.dataChannelLatencyResponse");const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t);this.pixelStreaming._onDataChannelLatencyTestResponse(n)}handleInitialSettings(e){Y.Info("DataChannelReceiveMessageType.InitialSettings");const t=new TextDecoder("utf-16").decode(e.slice(1)),n=JSON.parse(t),s=new Gn;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(qe.HoveringMouseMode,!!n.ConfigOptions.DefaultToHover),s.ueCompatible(),Y.Info(t),this.pixelStreaming._onInitialSettings(s)}handleVideoEncoderAvgQP(e){Y.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);Y.Info("DataChannelReceiveMessageType.QualityControlOwnership"),this.isQualityController=new Boolean(t[1]).valueOf(),Y.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(qe.HoveringMouseMode)?tt.HoveringMouse:tt.LockedMouse;this.mouseController=this.inputClassesFactory.registerMouse(e)}}setTouchInputEnabled(e){var t;null===(t=this.touchController)||void 0===t||t.unregister(),e&&(this.touchController=this.inputClassesFactory.registerTouch(this.config.isFlagEnabled(qe.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 ye({label:e,event:t})),e.onClose=(e,t)=>this.pixelStreaming.dispatchEvent(new ve({label:e,event:t})),e.onError=(e,t)=>this.pixelStreaming.dispatchEvent(new Se({label:e,event:t}))}registerMessageHandler(e,t,n){t===ms.FromStreamer&&void 0===n&&Y.Warning(`Unable to register handler for ${e} as no handler was passed`),this.streamMessageController.registerMessageHandler(t,e,s=>void 0===n&&t===ms.ToStreamer?this.sendMessageController.sendMessageToStreamer(e,s):n(s))}}class Ps{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=us(e.gamepad)),this.controllers[r].currentState=us(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 Is{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 Ps(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 Y.Error("This browser does not support XR.");navigator.xr.requestSession("immersive-vr",{optionalFeatures:[]}).then(e=>{this.onXrSessionStarted(e)})}}onXrSessionEnded(){Y.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){Y.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(qe.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 We({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&&Y.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 xs{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 Ls{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 Y.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 xs(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 As{constructor(e,t){this.allowConsoleCommands=!1,this.config=e,(null==t?void 0:t.videoElementParent)&&(this._videoElementParent=t.videoElementParent),this._eventEmitter=new je,this.configureSettings(),this.setWebRtcPlayerController(new Rs(this.config,this)),this._webXrController=new Is(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(qe.IsQualityController,e=>{!0!==e||this._webRtcController.isQualityController||this._webRtcController.sendRequestQualityControlOwnership()}),this.config._addOnSettingChangedListener(qe.AFKDetection,e=>{this._webRtcController.setAfkEnabled(e)}),this.config._addOnSettingChangedListener(qe.MatchViewportResolution,()=>{this._webRtcController.videoPlayer.updateVideoStreamSize()}),this.config._addOnSettingChangedListener(qe.HoveringMouseMode,e=>{this.config.setFlagLabel(qe.HoveringMouseMode,`Control Scheme: ${e?"Hovering":"Locked"} Mouse`),this._webRtcController.setMouseInputEnabled(this.config.isFlagEnabled(qe.MouseInput))}),this.config._addOnSettingChangedListener(qe.KeyboardInput,e=>{this._webRtcController.setKeyboardInputEnabled(e)}),this.config._addOnSettingChangedListener(qe.MouseInput,e=>{this._webRtcController.setMouseInputEnabled(e)}),this.config._addOnSettingChangedListener(qe.FakeMouseWithTouches,e=>{this._webRtcController.setTouchInputEnabled(this.config.isFlagEnabled(qe.TouchInput))}),this.config._addOnSettingChangedListener(qe.TouchInput,e=>{this._webRtcController.setTouchInputEnabled(e)}),this.config._addOnSettingChangedListener(qe.GamepadInput,e=>{this._webRtcController.setGamePadInputEnabled(e)}),this.config._addOnNumericSettingChangedListener(Ke.MinQP,e=>{Y.Info("-------- Sending MinQP --------"),this._webRtcController.sendEncoderMinQP(e),Y.Info("-------------------------------------------");const t=Math.trunc(100*(1-e/51));this.config.setNumericSetting(Ke.CompatQualityMax,t)}),this.config._addOnNumericSettingChangedListener(Ke.MaxQP,e=>{Y.Info("-------- Sending MaxQP --------"),this._webRtcController.sendEncoderMaxQP(e),Y.Info("-------------------------------------------");const t=Math.trunc(100*(1-e/51));this.config.setNumericSetting(Ke.CompatQualityMin,t)}),this.config._addOnNumericSettingChangedListener(Ke.MinQuality,e=>{Y.Info("-------- Sending MinQuality --------"),this._webRtcController.sendEncoderMinQuality(e),Y.Info("-------------------------------------------"),this.config.setNumericSetting(Ke.CompatQualityMin,e)}),this.config._addOnNumericSettingChangedListener(Ke.MaxQuality,e=>{Y.Info("-------- Sending MaxQuality --------"),this._webRtcController.sendEncoderMaxQuality(e),Y.Info("-------------------------------------------"),this.config.setNumericSetting(Ke.CompatQualityMax,e)}),this.config._addOnNumericSettingChangedListener(Ke.CompatQualityMin,e=>{e=51-e/100*51,Y.Info("-------- Sending MinQP from quality value --------"),this._webRtcController.sendEncoderMaxQP(e),Y.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(Ke.CompatQualityMax,e=>{e=51-e/100*51,Y.Info("-------- Sending MaxQP from quality value --------"),this._webRtcController.sendEncoderMinQP(e),Y.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(Ke.WebRTCMinBitrate,e=>{Y.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCMinBitrate(1e3*e),Y.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(Ke.WebRTCMaxBitrate,e=>{Y.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCMaxBitrate(1e3*e),Y.Info("-------------------------------------------")}),this.config._addOnNumericSettingChangedListener(Ke.WebRTCFPS,e=>{Y.Info("-------- Sending web rtc settings --------"),this._webRtcController.sendWebRTCFps(e),Y.Info("-------------------------------------------")}),this.config._addOnOptionSettingChangedListener(Ye.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(Ye.PreferredCodec).selected),this._webRtcController.resizePlayerStyle(),this.checkForAutoConnect()}connect(){this._eventEmitter.dispatchEvent(new Ce),this._webRtcController.connectToSignallingServer()}reconnect(){this._eventEmitter.dispatchEvent(new Me),this._webRtcController.tryReconnect("Reconnecting...")}disconnect(){this._eventEmitter.dispatchEvent(new Te),this._webRtcController.close()}play(){this._onStreamLoading(),this._webRtcController.playStream()}checkForAutoConnect(){this.config.isFlagEnabled(qe.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 Y.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):Y.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:[])Wn.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 Y.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):Y.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:[])Wn.canTransceiverSendVideo(r)&&(r.sender.track.enabled=!e)}_onWebRtcAutoConnect(){this._eventEmitter.dispatchEvent(new ue)}_onWebRtcSdp(){this._eventEmitter.dispatchEvent(new ce)}_onWebRtcSdpOffer(e){this._eventEmitter.dispatchEvent(new he({sdp:e}))}_onWebRtcSdpAnswer(e){this._eventEmitter.dispatchEvent(new de({sdp:e}))}_onLatencyCalculated(e){this._eventEmitter.dispatchEvent(new De({latencyInfo:e}))}_onStreamLoading(){this._eventEmitter.dispatchEvent(new we)}_onDisconnect(e,t){this._eventEmitter.dispatchEvent(new fe({eventString:e,allowClickToReconnect:t}))}_onWebRtcConnecting(){this._eventEmitter.dispatchEvent(new pe)}_onWebRtcConnected(){this._eventEmitter.dispatchEvent(new me)}_onWebRtcFailed(){this._eventEmitter.dispatchEvent(new ge)}_onVideoInitialized(){this._eventEmitter.dispatchEvent(new be),this._videoStartTime=Date.now()}_onLatencyTestResult(e){this._eventEmitter.dispatchEvent(new Oe({latencyTimings:e}))}_onDataChannelLatencyTestResponse(e){this._eventEmitter.dispatchEvent(new Ne({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 xe({aggregatedStats:e}))}_onVideoEncoderAvgQP(e){this._eventEmitter.dispatchEvent(new le({avgQP:e}))}_onInitialSettings(e){var t;this._eventEmitter.dispatchEvent(new Ve({settings:e})),e.PixelStreamingSettings&&(this.allowConsoleCommands=null!==(t=e.PixelStreamingSettings.AllowPixelStreamingCommands)&&void 0!==t&&t,!1===this.allowConsoleCommands&&Y.Info("-AllowPixelStreamingCommands=false, sending arbitrary console commands from browser to UE is disabled."));const n=this.config.useUrlParams,s=new ks(window.location.search);Y.Info(`using URL parameters ${n}`),e.EncoderSettings&&(e.EncoderSettings.MinQP&&(this.config.setNumericSetting(Ke.MinQP,n&&s.has(Ke.MinQP)?Number.parseFloat(s.get(Ke.MinQP)):e.EncoderSettings.MinQP||0),this.config.setNumericSetting(Ke.MaxQP,n&&s.has(Ke.MaxQP)?Number.parseFloat(s.get(Ke.MaxQP)):e.EncoderSettings.MaxQP||51)),e.EncoderSettings.MinQuality&&(this.config.setNumericSetting(Ke.MinQuality,n&&s.has(Ke.MinQuality)?Number.parseFloat(s.get(Ke.MinQuality)):e.EncoderSettings.MinQuality||0),this.config.setNumericSetting(Ke.MaxQuality,n&&s.has(Ke.MaxQuality)?Number.parseFloat(s.get(Ke.MaxQuality)):e.EncoderSettings.MaxQuality||100)),n&&(s.has(Ke.CompatQualityMin)&&this.config.setNumericSetting(Ke.CompatQualityMin,Number.parseFloat(s.get(Ke.CompatQualityMin))),s.has(Ke.CompatQualityMax)&&this.config.setNumericSetting(Ke.CompatQualityMax,Number.parseFloat(s.get(Ke.CompatQualityMax))))),e.WebRTCSettings&&(this.config.setNumericSetting(Ke.WebRTCMinBitrate,n&&s.has(Ke.WebRTCMinBitrate)?Number.parseFloat(s.get(Ke.WebRTCMinBitrate)):e.WebRTCSettings.MinBitrate/1e3),this.config.setNumericSetting(Ke.WebRTCMaxBitrate,n&&s.has(Ke.WebRTCMaxBitrate)?Number.parseFloat(s.get(Ke.WebRTCMaxBitrate)):e.WebRTCSettings.MaxBitrate/1e3),this.config.setNumericSetting(Ke.WebRTCFPS,n&&s.has(Ke.WebRTCFPS)?Number.parseFloat(s.get(Ke.WebRTCFPS)):e.WebRTCSettings.FPS))}_onQualityControlOwnership(e){this.config.setFlagEnabled(qe.IsQualityController,e)}_onPlayerCount(e){this._eventEmitter.dispatchEvent(new $e({count:e}))}_onSubscribeFailed(e){this._eventEmitter.dispatchEvent(new Be({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 He),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 Ls(this._webRtcController.sendDataChannelLatencyTest.bind(this._webRtcController),e=>{this._eventEmitter.dispatchEvent(new Ue({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!==ms.FromStreamer||void 0!==n?t===ms.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)):Y.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"}(gs||(gs={}));class Os{type=gs.VideoInitialised}class Ds{type=gs.DataChannelOpen}class Fs{msg;type=gs.DataChannelResponse;constructor(e){this.msg=e}}class Ns{stats;type=gs.WebRtcStats;constructor(e){this.stats=e}}var Us,Bs=o(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.SwitchRendererRequest="switch_renderer_request"}(Us||(Us={}));const Vs="3.16.4";var _s=o(838),Ws=o(992);const $s="sessionEndedDueToConnectionLoss",Hs="sessionEndedDueToVideoPlaybackError",js="sessionEndedDueToRendererError";var zs,qs,Qs,Ks,Gs;function Xs(e,t,n){return Math.max(t,Math.min(e,n))}function Js(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"}(zs||(zs={})),function(e){e.Always="always",e.WhenDegraded="when-degraded",e.Hidden="hidden"}(qs||(qs={})),function(e){e.TopLeft="top-left",e.TopRight="top-right",e.BottomLeft="bottom-left",e.BottomRight="bottom-right"}(Qs||(Qs={})),function(e){e.Click="click",e.Hover="hover",e.None="none"}(Ks||(Ks={}));class Ys{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 l.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 l.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 l.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,p=s>0?8*(e.video.bytesReceived-t.video.bytesReceived)/s/1e3:0,m=1e3*e.connection.currentRoundTripTime,g=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?Xs(55-4.6*Math.log(s),0,30):6,o=Xs(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 Xs(Math.round(100*a)/100,1,5)}({packetLoss:a,bitrate:1e3*l,roundTripTime:m,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=Xs(.56*Math.log(d)+5.36,1,5)-1.9*Math.log(a/o)-.002*c;return Xs(Math.round(100*h)/100,1,5)}({bitrate:1e3*p,roundTripTime:m,width:e.video.frameWidth,height:e.video.frameHeight,frameRate:e.video.framesPerSecond,expectedFrameRate:f,codec:v}),b=Math.min(g,S);let w;return w=b>=3.5?zs.Good:b>=2.5?zs.Fair:zs.Poor,{audioPacketLossPercent:Math.round(100*a)/100,videoPacketLossPercent:Math.round(100*u)/100,audioBitrateKbps:Math.round(l),videoBitrateKbps:Math.round(p),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*m)/100,audioMos:g,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:r,audioLevel:o}=e;l.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: ${r},\n Audio level (0-1): ${o??"N/A"}`),0===n&&l.A.warn("WebRTC Connection - Audio - No audio packets received — remote is probably not sending audio."),s>0&&l.A.warn(`WebRTC Connection - Audio - packet loss detected: ${s} packets lost.`),void 0===o?l.A.warn("WebRTC Connection - Audio - Audio level not available in stats."):0===o?l.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."):o<.02?l.A.warn("WebRTC Connection - Audio - Audio level is very low — audio might be too quiet."):l.A.info("WebRTC Connection - Audio - Audio level looks normal, digital human is likely speaking.")}logElementStatus(e){const t=Js(this.videoElement),n=t?this.videoElement:this.audioElement;l.A.debug(`Audio plays from ${t?"video":"separate audio"} element (DisableAudioSync=${t?"false":"true"}).`),l.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"})`),l.A.debug(`Playback element muted: ${n?.muted}, (should be false to be able to hear the digital human)`),l.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&&(l.A.debug(`Playback element can play webrtc audio codec (${s}) : ${n.canPlayType(s)}, (should be 'probably' or 'maybe)'`),"audio/opus"===s&&l.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"}(Gs||(Gs={}));const Zs=e=>e??"speech-recognition-service",ei=e=>"pixel-streaming"===e||"both"===e,ti=e=>"speech-recognition-service"===e||"both"===e,ni="#6b7280";class si{videoContainerElement;container;panel;bars=[];panelVisible=!1;lastMetrics;visibility;position;popupTrigger;onClickBound;onMouseEventBound;onDocumentClickBound;onMouseEnterBound;onMouseLeaveBound;hoverHideTimeout;originalParentPosition;constructor(e,t){this.videoContainerElement=e,this.visibility=t.visibility??qs.WhenDegraded,this.position=t.position??Qs.TopRight,this.popupTrigger=t.popupTrigger??Ks.Click,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.visibility!==qs.Hidden&&this.createElements()}createElements(){"static"===getComputedStyle(this.videoContainerElement).position&&(this.originalParentPosition=this.videoContainerElement.style.position,this.videoContainerElement.style.position="relative"),this.container=document.createElement("div"),this.container.setAttribute("data-testid","network-indicator"),this.container.setAttribute("role","status"),this.container.setAttribute("aria-live","polite"),this.container.setAttribute("aria-label","Network quality: unknown"),Object.assign(this.container.style,{position:"absolute",zIndex:"1000",cursor:"pointer",padding:"6px 7px",borderRadius:"4px",background:"rgba(0, 0, 0, 0.5)",display:"none",alignItems:"flex-end",gap:"2px",pointerEvents:"auto",...this.getPositionStyles()});const e=[6,12,18];for(const t of e){const e=document.createElement("div");e.setAttribute("data-testid","network-indicator-bar"),Object.assign(e.style,{width:"4px",height:`${t}px`,borderRadius:"1px",background:ni,transition:"background 0.3s ease"}),this.bars.push(e),this.container.appendChild(e)}this.container.addEventListener("mousedown",this.onMouseEventBound),this.container.addEventListener("mouseup",this.onMouseEventBound),this.popupTrigger===Ks.Click?this.container.addEventListener("click",this.onClickBound):this.popupTrigger===Ks.Hover&&(this.container.addEventListener("mouseenter",this.onMouseEnterBound),this.container.addEventListener("mouseleave",this.onMouseLeaveBound)),this.popupTrigger===Ks.None&&(this.container.style.cursor="default"),this.videoContainerElement.appendChild(this.container)}getPositionStyles(){const e="8px";switch(this.position){case Qs.TopLeft:return{top:e,left:e};case Qs.TopRight:return{top:e,right:e};case Qs.BottomLeft:return{bottom:e,left:e};case Qs.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()}onMouseEnter(){clearTimeout(this.hoverHideTimeout),this.showPanel()}onMouseLeave(){this.scheduleHoverHide()}scheduleHoverHide(){clearTimeout(this.hoverHideTimeout),this.hoverHideTimeout=setTimeout(()=>this.hidePanel(),50)}showPanel(){this.container&&this.lastMetrics&&(this.panel||(this.panel=document.createElement("div"),this.panel.setAttribute("data-testid","network-indicator-panel"),Object.assign(this.panel.style,{position:"fixed",padding:"10px",borderRadius:"6px",background:"rgba(0, 0, 0, 0.85)",color:"#ffffff",fontSize:"11px",fontFamily:"system-ui, -apple-system, sans-serif",whiteSpace:"nowrap",lineHeight:"1.6",minWidth:"180px",zIndex:"10001",pointerEvents:"auto"}),this.popupTrigger===Ks.Hover&&(this.panel.addEventListener("mouseenter",this.onMouseEnterBound),this.panel.addEventListener("mouseleave",this.onMouseLeaveBound)),document.body.appendChild(this.panel)),this.updatePanel(),this.positionPanel(),this.panel.style.display="block",this.panelVisible=!0,document.addEventListener("click",this.onDocumentClickBound))}hidePanel(){this.panel&&(this.panel.style.display="none"),this.panelVisible=!1,document.removeEventListener("click",this.onDocumentClickBound)}positionPanel(){if(!this.panel||!this.container)return;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===Qs.TopLeft||this.position===Qs.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.getColor(e.qualityLevel);this.panel.innerHTML=[`<div style="font-weight:600;margin-bottom:4px;color:${t}">${e.qualityLevel} Quality</div>`,this.panelSectionHeader("Quality Score (MOS)"),this.panelRow("Audio",e.audioMos.toFixed(1)+" / 5.0"),this.panelRow("Video",e.videoMos.toFixed(1)+" / 5.0"),this.panelSectionHeader("Connection"),this.panelRow("Round Trip",`${e.roundTripTimeMs} ms`),this.panelRow("Packet Loss",`${e.audioPacketLossPercent}% audio / ${e.videoPacketLossPercent}% video`),this.panelRow("Jitter",`${e.audioJitterMs} ms audio / ${e.videoJitterMs} ms video`),this.panelSectionHeader("Throughput"),this.panelRow("Bitrate",`${e.audioBitrateKbps} audio / ${e.videoBitrateKbps} video kbps`),this.panelRow("Frame Rate",`${e.frameRate} fps`)].join("")}panelSectionHeader(e){return`<div style="color:#6b7280;font-size:10px;text-transform:uppercase;letter-spacing:0.5px;margin-top:6px;margin-bottom:2px">${e}</div>`}panelRow(e,t){return`<div style="display:flex;justify-content:space-between;gap:12px"><span style="color:#9ca3af">${e}</span><span>${t}</span></div>`}getColor(e){switch(e){case zs.Good:return"#22c55e";case zs.Fair:return"#eab308";case zs.Poor:return"#ef4444"}}update(e){if(this.lastMetrics=e,!this.container)return;this.container.setAttribute("aria-label",`Network quality: ${e.qualityLevel}`);const t=this.getColor(e.qualityLevel),n=e.qualityLevel===zs.Good?3:e.qualityLevel===zs.Fair?2:1;this.bars.forEach((e,s)=>{e.style.background=s<n?t:ni}),this.visibility===qs.WhenDegraded?this.container.style.display=e.qualityLevel===zs.Good?"none":"flex":this.container.style.display="flex",this.panelVisible&&(this.updatePanel(),this.positionPanel())}destroy(){this.container&&(this.container.removeEventListener("click",this.onClickBound),this.container.removeEventListener("mousedown",this.onMouseEventBound),this.container.removeEventListener("mouseup",this.onMouseEventBound),this.container.removeEventListener("mouseenter",this.onMouseEnterBound),this.container.removeEventListener("mouseleave",this.onMouseLeaveBound),this.container.remove(),this.container=void 0),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),this.bars=[],this.panelVisible=!1,this.lastMetrics=void 0}}class ii{session;connectionUrl;videoContainerElement;stream;messages=new X;videoElement;audioElement;videoInitialized=!1;dataChannelOpen=!1;sceneReady=!1;maxReconnectAttempts=4;reconnectionAttempts=0;allowReconnection=!0;reconnectTimeoutId;baseReconnectDelayMs=500;maxReconnectDelayMs=1e4;audioStatsInternal;freezeCount=0;lastDecodedFrames=0;lastCheckTime=Date.now();audioStatsAnalyzer;networkQualityInterval;networkIndicator;config;clientMessages;_audioUpstreamMode;constructor(e,t,n){this.session=e,this.connectionUrl=t,this.videoContainerElement=n,this.config=e.config,this.clientMessages=e.messages,this._audioUpstreamMode=Zs(this.config.audioUpstreamMode)}get audioUpstreamMode(){return this._audioUpstreamMode}init(){l.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 _s.qw);const e=ei(this.audioUpstreamMode);"speech-recognition-service"!==this.audioUpstreamMode&&l.A.info(`audioUpstreamMode='${this.audioUpstreamMode}' is beta; behaviour may change.`);const t=new et({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 As(t,{videoElementParent:this.videoContainerElement}),Y.InitLogging(z.Warning,!1),this.stream.setSignallingUrlBuilder(function(){let e=t.getTextSettingValue(Xe.SignallingServerUrl);return t.isFlagEnabled(qe.BrowserSendOffer)&&(e+=(e.includes("?")?"&":"?")+qe.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}})=>{l.A.trace("WebRTC: VideoEncoderAvgQP - lower is better, ranges from 0 to 51:",e)}),this.stream?.addEventListener("webRtcAutoConnect",()=>{l.A.debug("WebRTC: AutoConnect triggered")}),this.stream?.addEventListener("webRtcConnected",this.handleWebRtcConnectedMessage.bind(this)),this.stream?.addEventListener("statsReceived",({data:{aggregatedStats:e}})=>{l.A.trace("WebRTC: StatsReceived",e)}),this.stream?.addEventListener("webRtcTCPRelayDetected",()=>{l.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:Us.ClientInfo,uneeqJsSdkVersion:Vs}))}),this.stream?.signallingProtocol.on(Us.Error,e=>{l.A.error("Signaling: Received error message from server",e),this.clientMessages?.next(new _s.Cj(`Signaling server error: ${e}`))}),this.stream?.signallingProtocol.on(Us.IndexInQueue,this.handleIndexInQueueMessage.bind(this)),this.stream?.signallingProtocol.on(Us.RendererTaken,this.handleRendererTakenMessage.bind(this)),this.stream?.signallingProtocol.on(Us.RendererGone,this.handleRendererGoneEvent.bind(this)),this.stream?.signallingProtocol.on(Us.SwitchRendererRequest,this.handleSwitchRendererRequestEvent.bind(this)),this.stream?.signallingProtocol.on(Us.CustomerConcurrencyLimitReached,this.handleCustomerConcurrencyLimitReachedMessage.bind(this)),this.stream?.signallingProtocol.on(Us.RendererError,this.handleRendererErrorMessage.bind(this)),this.stream?.signallingProtocol.on(Us.Config,this.checkForStubbedTurnConfig.bind(this))}checkForStubbedTurnConfig(e){const t=e?.peerConnectionOptions?.iceServers??[];l.A.info("Signaling: Received ice config message with urls:",t.map(e=>({urls:e.urls}))),t.some(e=>e.username?.includes("disabled")&&e.urls?.some(e=>e.includes("0.0.0.0")))&&l.A.warn("Signaling: TURN server configuration is stubbed (turn:0.0.0.0 with disabled credentials). This should be intentional, is intended for locally run renderers e.g. kiosk, miniprem etc.")}handleWebSocketError(e){l.A.error("Signaling: WebSocket error",l.A.serialiseError(e)),this.reconnectIfSafe(e)}handleVideoInitialized(){l.A.info("Video initialized."),this.videoElement=this.videoContainerElement?.getElementsByTagName("video")[0],this.audioElement=this.stream?.webRtcController?.streamController?.audioElement,this.audioStatsAnalyzer=new Ys(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)l.A.warn("Video autoplay blocked by browser. Requesting user gesture to resume playback."),this.clientMessages?.next(new _s.MA);else{const t="Fatal Error: Digital Human video cannot be played.";l.A.error(t,l.A.serialiseError(e)),this.clientMessages?.next(new _s.Cj(t)),this.endSession(Hs,!0)}}),this.videoInitialized=!0,"mediaSession"in navigator&&(navigator.mediaSession.setActionHandler("play",()=>this.playAudioElement()),navigator.mediaSession.setActionHandler("pause",()=>this.pauseAudioElement())),this.messages.next(new Os),this.reconnectionAttempts=0,this.clearReconnectTimer();else{const e="Fatal Error: Video element not found.";l.A.error(e),this.clientMessages?.next(new _s.Cj(e)),this.endSession(Hs,!0)}setTimeout(()=>{this.clientMessages?.next(new _s.xQ)},fi)}getAudioPlaybackElement(){return Js(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(()=>{l.A.info("Audio playback successfully started."),this.clientMessages?.next(new _s.M8),"mediaSession"in navigator&&(navigator.mediaSession.playbackState="playing")}).catch(n=>{l.A.warn("Audio cannot be played.",n),this.clientMessages?.next(new _s.Tu),t?(e.muted=!0,e.play().then(()=>{this.clientMessages?.next(new _s.XC)}).catch(e=>{l.A.warn("Muted video reveal also blocked.",e),this.clientMessages?.next(new _s.Cj(`Video playback failed: ${e}`))})):this.clientMessages?.next(new _s.XC)})}resumeVideoPlayback(){this.videoElement?this.videoElement.play().then(()=>{this.playAudioElement()}).catch(e=>{l.A.error("Video playback failed after user gesture",l.A.serialiseError(e)),this.clientMessages?.next(new _s.Cj("Video playback failed after user gesture")),this.endSession("sessionEndedDueToPermissionsError",!0)}):l.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 _s.Tu),"mediaSession"in navigator&&(navigator.mediaSession.playbackState="paused")):this.handleMissingAudioElement()}muteUpstreamMic(){ei(this.audioUpstreamMode)?this.stream?this.stream.muteMicrophone():l.A.warn("muteUpstreamMic called before PixelStreaming stream is initialised; ignoring."):l.A.warn(`muteUpstreamMic called in '${this.audioUpstreamMode}' mode — no PS upstream audio track to mute; ignoring.`)}unmuteUpstreamMic(){ei(this.audioUpstreamMode)?this.stream?this.stream.unmuteMicrophone(!1):l.A.warn("unmuteUpstreamMic called before PixelStreaming stream is initialised; ignoring."):l.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(()=>{l.A.info(`Speaker device set to: ${t}`)}).catch(e=>{l.A.error(`Failed to set speaker device: ${t}`,l.A.serialiseError(e))}):l.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.";l.A.error(e),this.clientMessages?.next(new _s.Cj(e))}startAudioStatsMonitor(e=5e3){this.stopAudioStatsMonitor(),l.A.info("Starting audio stats monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new Ys(this.stream,this.videoElement,this.audioElement)),this.audioStatsInternal=setInterval(()=>{this.audioStatsAnalyzer?.analyzeAudioStats().catch(e=>{l.A.error("Error analyzing audio stats",l.A.serialiseError(e))})},e)}stopAudioStatsMonitor(){this.audioStatsInternal&&clearInterval(this.audioStatsInternal)}startNetworkQualityMonitor(e){this.stopNetworkQualityMonitor(),l.A.info("Starting network quality monitor"),this.audioStatsAnalyzer||(this.audioStatsAnalyzer=new Ys(this.stream,this.videoElement,this.audioElement)),this.videoContainerElement&&e.visibility!==qs.Hidden&&(this.networkIndicator=new si(this.videoContainerElement,e));const t=e.collectionIntervalMs??3e3;this.networkQualityInterval=setInterval(()=>{this.audioStatsAnalyzer?.collectNetworkQuality(e).then(e=>{e&&(this.networkIndicator?.update(e),this.clientMessages?.next(new _s.N8(e)))}).catch(e=>{l.A.error("Error collecting network quality",l.A.serialiseError(e))})},t)}stopNetworkQualityMonitor(){this.networkQualityInterval&&(clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0),this.networkIndicator&&(this.networkIndicator.destroy(),this.networkIndicator=void 0)}handleDataChannelOpen(){l.A.info("DataChannelOpen"),this.dataChannelOpen=!0,this.messages.next(new Ds)}handleWebRtcFailed(e){l.A.error("WebRTC failed",e),this.reconnectIfSafe(e)}handleWebRtcDisconnected(e){l.A.warn(`WebRTC disconnected, message: ${e?.data?.eventString}, allowClickToReconnect: ${e?.data?.allowClickToReconnect}`),this.reconnectIfSafe(e)}handleWebRtcStats(e){const t=new Ns(e.data.aggregatedStats);this.messages.next(t);const n=e.data.aggregatedStats.inboundVideoStats?.framesDecoded??0;this.checkForFreeze(n)}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);l.A.warn(`[WebRTC] Video FROZEN for ${e}s (count=${this.freezeCount})`),this.freezeCount>=3&&(l.A.error("[WebRTC] Video frozen 3 times in a row, transferring session..."),this.session.sessionTransferManager.transferSession(),this.freezeCount=0)}else this.freezeCount=0,this.lastDecodedFrames=e,this.lastCheckTime=t;else l.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);l.A.info(`Scheduling reconnection attempt ${this.reconnectionAttempts} in ${e}ms`),this.reconnectTimeoutId=setTimeout(()=>{l.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?(l.A.debug("Checking if should attempt reconnection after event",e),this.reconnectionAttempts<this.maxReconnectAttempts?(this.reconnectionAttempts++,this.clientMessages?.next(new _s.fI),this.scheduleReconnect()):(l.A.info("Max reconnection attempts reached. Ending session."),this.clientMessages?.next(new _s.JP),this.endSession($s,!1))):l.A.warn("Reconnection already scheduled or reconnecting is disabled")}catch(e){l.A.error("Error during reconnection attempt",l.A.serialiseError(e)),this.clientMessages?.next(new _s.Cj("Error during reconnection attempt")),this.endSession($s,!1)}}handleDataChannelMessage(e){l.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 Fs(t))}catch(e){l.A.error("Signaling: Failed to parse engine response",l.A.serialiseError(e))}}handleIndexInQueueMessage(e){try{const t=Number(e.message);this.clientMessages?.next(new _s.F8(t))}catch(e){l.A.error("Signaling: Failed to parse position in queue message",l.A.serialiseError(e))}}handleRendererTakenMessage(e){try{const t=e;this.clientMessages?.next(new _s.qo(t.message)),l.A.info("Signaling: Renderer taken event",t.message)}catch(e){l.A.error("Signaling: Failed to parse renderer taken message",l.A.serialiseError(e))}}handleWebRtcConnectedMessage(){this.clientMessages?.next(new _s.Cl),l.A.info("Signaling: WebRTC connected")}handleRendererGoneEvent(e){l.A.info("Signaling: Renderer gone event",e),this.reconnectIfSafe(e)}handleSwitchRendererRequestEvent(e){l.A.info("Signaling: Renderer switch renderer request event",e),this.session.sessionTransferManager.transferSession()}handleCustomerConcurrencyLimitReachedMessage(e){l.A.warn("Signaling: Customer concurrency limit reached message received",e),this.clientMessages?.next(new _s.MM)}handleRendererErrorMessage(e){try{const t=e,n=t.code??-1,s=t.message??"An unknown renderer error occurred";l.A.error(`Signaling: Renderer error received - code: ${n}, message: ${s}`),this.clientMessages?.next(new _s.j_(n,s)),this.endSession(js,!0)}catch(e){l.A.error("Signaling: Failed to parse renderer error message",l.A.serialiseError(e)),this.clientMessages?.next(new _s.j_(-1,"An unknown renderer error occurred")),this.endSession(js,!0)}}socketSend(e){l.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===Ws.A.ChatPrompt){const n=t.data?.requestId;l.A.info(`Signaling: Sending data channel message — action=chat_prompt, requestId=${n??"unknown"}`),(!(e instanceof Bs.D)||e.shouldEmitPromptRequest)&&this.clientMessages?.next(new _s.bS(t.data))}else l.A.info("Signaling: Sending data channel message",JSON.stringify(t));this.stream?.emitUIInteraction(e)}dataSendBinary(e){l.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){l.A.info("Signaling: Ending session"),this.clearReconnectTimer(),this.stopNetworkQualityMonitor(),this.socketSend({message:e,type:Us.ClientGone,sessionId:this.config.sessionId}),this.streamDisconnect(),l.A.info("Session has ended, reason: "+e),t&&this.clientMessages?.next(new _s.aY(e))}streamDisconnect(){l.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,"mediaSession"in navigator&&(navigator.mediaSession.setActionHandler("play",null),navigator.mediaSession.setActionHandler("pause",null),navigator.mediaSession.playbackState="none")}startSoftSwitch(){l.A.info("Signaling: Start soft switching"),this.clientMessages?.next(new _s.sF)}stopSoftSwitch(){l.A.info("Signaling: Stop soft switching"),this.clientMessages?.next(new _s.WQ)}}var ri;!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"}(ri||(ri={}));var oi,ai,li=o(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"}(oi||(oi={})),function(e){e.Left="left",e.Right="right",e.Center="center",e.Centre="centre"}(ai||(ai={}));class ci{position;duration;requestId;constructor(e,t=2e3,n=(0,li.g)()){this.position=e,this.duration=t,this.requestId=n}toJSON(){return{action:Ws.A.CameraAnchor,data:{requestId:this.requestId,position:this.position,transition_duration_ms:this.duration}}}}class di{avatarId;requestId;constructor(e,t=(0,li.g)()){this.avatarId=e,this.requestId=t}toJSON(){return{action:Ws.A.ChangeAvatar,data:{id:this.avatarId,requestId:this.requestId}}}}class hi{url;requestId;constructor(e,t=(0,li.g)()){this.url=e,this.requestId=t}toJSON(){return{action:Ws.A.LoadBackground,data:{url:this.url,requestId:this.requestId}}}}class ui{actionName;requestId;constructor(e,t=(0,li.g)()){this.actionName=e,this.requestId=t}toJSON(){return{action:Ws.A.TriggerAction,data:{action_name:this.actionName,requestId:this.requestId}}}}var pi=o(33);class mi{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()&&(l.A.info("Session transfer via keyboard shortcut triggered"),this.transferSession())})}transferSession(){this.isTransferSessionInProgress?l.A.warn("Transfer already in progress, skipping"):(this.isTransferSessionInProgress=!0,l.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){l.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(),l.A.info("Session transfer complete")},1e3))}}const gi=[1103,1200,1402],fi=750;class yi{config;id;signaling;messages=new Q;speechRec;promptMetadata={};audioStreamId;sessionTransferManager;jwt;welcomeRequested=!1;resolutionLogged=!1;sttPausedByHost=!1;_audioUpstreamMode;constructor(e){this.config=e,this.sessionTransferManager=new mi(this),this._audioUpstreamMode=Zs(this.config.audioUpstreamMode)}get audioUpstreamMode(){return this._audioUpstreamMode}updatePromptMetadata(e){try{JSON.parse(JSON.stringify(e)),this.promptMetadata.custom=e,this.messages.next(new _s.ss(this.promptMetadata))}catch(t){l.A.error("Error parsing custom metadata",e,l.A.serialiseError(t))}}setEnableMicrophone(e){const t=this.audioUpstreamMode;this.config.enableMicrophone=e,this.sttPausedByHost=!1;let n=!1;ti(t)&&(this.speechRec?(e?this.speechRec.startRecognition():this.speechRec.stopRecognition(),n=!0):l.A.warn("setEnableMicrophone: STT leg is configured but speech recognition is not initialised yet")),ei(t)&&(this.signaling?(e?this.signaling.unmuteUpstreamMic():this.signaling.muteUpstreamMic(),n=!0,ti(t)||this.messages.next(new _s.WY(e))):l.A.warn("setEnableMicrophone: PS leg is configured but signaling is not initialised yet")),n||l.A.warn(`setEnableMicrophone(${e}) had nothing to do in mode '${t}' — session not ready?`)}pauseSpeechRecognition(){return this.sttPausedByHost=!0,this.speechRec?this.speechRec.pause():(l.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():(l.A.warn("resumeSpeechRecognition: pause intent cleared, but speech recognition is not initialised yet — nothing to resume"),!1)}setCameraAnchorDistance(e,t=0,n=this.signaling){this.config.cameraAnchorDistance=e,n?.dataSend(new ci(e,t))}setCameraAnchorHorizontal(e,t=0,n=this.signaling){this.config.cameraAnchorHorizontal=e,n?.dataSend(new ci(e,t))}changeAvatar(e,t=this.signaling){t?.dataSend(new di(e))}loadBackground(e,t=this.signaling){t?.dataSend(new hi(e))}userStartSpeaking(e=this.signaling){e?.dataSend(new pi.A(pi.f.Start))}userStopSpeaking(e=this.signaling){e?.dataSend(new pi.A(pi.f.Stop))}triggerAction(e,t=this.signaling){t?.dataSend(new ui(e))}resumeVideoPlayback(){this.signaling?.resumeVideoPlayback()}createSession(){this.messages.subscribe(e=>{if(this.config.messageHandler&&this.config.messageHandler(e),e.uneeqMessageType===_s.Yg.SoftSwitchFinished||e.uneeqMessageType===_s.Yg.SessionReconnectingFinished){if(!ti(this.audioUpstreamMode))return;if(this.config.enableMicrophone&&!this.sttPausedByHost)e.uneeqMessageType===_s.Yg.SessionReconnectingFinished?(l.A.info("Session, resuming speech recognition after reconnect"),this.speechRec?.resume()):(l.A.info("Session, restarting speech recognition after soft switch"),this.speechRec?.startRecognition());else{const t=e.uneeqMessageType===_s.Yg.SoftSwitchFinished?"soft switch":"reconnect",n=this.sttPausedByHost?"paused by host":"microphone disabled";l.A.info(`Session, skipping speech recognition restart after ${t} (${n})`)}}}),this.id=this.config.sessionId,this.jwt=this.config.sessionToken,l.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://");l.A.debug("Socket URL:",n);const s=new ii(this,n,e);return s.messages.subscribe(e=>{this.signalingEventHandler(e,s)}),s}signalingEventHandler(e,t){switch(e.type){case gs.VideoInitialised:case gs.DataChannelOpen:this.handleSessionReady(t);break;case gs.DataChannelResponse:this.handleDataChannelMessage(e,t);break;case gs.WebRtcStats:{const t=e.stats;!this.resolutionLogged&&t.inboundVideoStats?.frameWidth&&t.inboundVideoStats?.frameHeight&&(l.A.info("Video resolution:",`${t.inboundVideoStats.frameWidth}x${t.inboundVideoStats.frameHeight}`),this.resolutionLogged=!0),this.config.webRtcStatsEmitMessages&&this.messages.next(new _s.O$(t)),this.config.webRtcStatsLogMessages&&l.A.info("WebRTC stats",t);break}}}handleSessionReady(e){l.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 _s.wf(this.id)),this.config.networkIndicator&&e.startNetworkQualityMonitor(this.config.networkIndicator),this.config.webRtcStatsLogMessages&&e.startAudioStatsMonitor()},fi))}async initSpeechRecognition(e){if(!ti(this.audioUpstreamMode))return void l.A.info(`[STT] audioUpstreamMode='${this.audioUpstreamMode}' — skipping STT provider initialisation (no STT leg in this mode).`);if(this.speechRec)return void l.A.warn("Speech recognition already initialized");let t=this.config.speechRecognitionProvider||Gs.Google;l.A.info(`[STT] Config speechRecognitionProvider: "${this.config.speechRecognitionProvider}", resolved provider: "${t}"`),t!==Gs.Google&&t!==Gs.Deepgram&&(l.A.warn(`Invalid speechRecognitionProvider value: "${String(t)}". Supported values are "google" or "deepgram". Defaulting to "google".`),t=Gs.Google,this.config.speechRecognitionProvider=Gs.Google),l.A.info(`[STT] Using provider: ${t}`);try{this.speechRec=await(t===Gs.Deepgram?this.createDeepgramSTT(e):this.createGoogleSTT(e))}catch(e){return void l.A.error("[STT] Failed to initialise speech recognition provider",l.A.serialiseError(e))}this.config.enableMicrophone&&!this.sttPausedByHost&&this.speechRec&&this.speechRec.startRecognition()}async createGoogleSTT(e){const t=this.getSpeechOptions(e);l.A.debug("Initializing Google STT (speech-recognition-service)");const{GoogleSTT:n}=await Promise.all([o.e(113),o.e(948)]).then(o.bind(o,948));return new n(t)}async createDeepgramSTT(e){const t=this.config.deepgramConfig||{};if(this.isFluxModel(t.model))return this.createDeepgramFluxSTT(e);l.A.warn("Deepgram STT is currently in beta, is subject to change, and is not suitable for production use"),l.A.debug("Initializing Deepgram STT");const n={connectionUrl:this.config.connectionUrl,jwtToken:e,sessionId:this.id,model:t.model,language:t.language,smartFormat:t.smartFormat,interimResults:t.interimResults,utteranceEndMs:t.utteranceEndMs,vadEvents:t.vadEvents,encoding:t.encoding,sampleRate:t.sampleRate,channels:t.channels,fillerWords:t.fillerWords,endpointing:t.endpointing,interruptionWordThreshold:t.interruptionWordThreshold,echoCancellation:t.microphone?.echoCancellation,noiseSuppression:t.microphone?.noiseSuppression,autoGainControl:t.microphone?.autoGainControl,microphoneDeviceId:this.config.microphoneDeviceId,promptMetadata:this.promptMetadata,messages:this.messages,sendMessage:e=>{this.signaling?.dataSend(e)},enableInterrupt:this.config.enableInterruptBySpeech,safetyNetTimeoutMs:t.safetyNetTimeoutMs,keyterms:t.keyterms,noDelay:t.noDelay},{DeepgramSTT:s}=await Promise.all([o.e(260),o.e(3)]).then(o.bind(o,3));return new s(n)}isFluxModel(e){return void 0!==e&&e.toLowerCase().startsWith("flux")}async createDeepgramFluxSTT(e){l.A.debug("Initializing Deepgram Flux STT (v2 API)");const t=this.config.deepgramConfig||{},n={connectionUrl:this.config.connectionUrl,jwtToken:e,sessionId:this.id,model:t.model,language:t.language,eotThreshold:t.eotThreshold,eagerEotThreshold:t.eagerEotThreshold,eotTimeoutMs:t.eotTimeoutMs,eagerMaxTurnDurationMs:t.eagerMaxTurnDurationMs,keyterms:t.keyterms,safetyNetTimeoutMs:t.safetyNetTimeoutMs,echoCancellation:t.microphone?.echoCancellation,noiseSuppression:t.microphone?.noiseSuppression,autoGainControl:t.microphone?.autoGainControl,microphoneDeviceId:this.config.microphoneDeviceId,promptMetadata:this.promptMetadata,messages:this.messages,sendMessage:e=>{this.signaling?.dataSend(e)}},{DeepgramFluxSTT:s}=await Promise.all([o.e(260),o.e(363)]).then(o.bind(o,363));return new s(n)}getSpeechOptions(e){return{apiUrl:this.config.connectionUrl,assetBasePath:this.config.assetBasePath,enableInterrupt:this.config.enableInterruptBySpeech,enableVad:this.config.enableVad,jwtToken:e,hintPhrases:this.config.speechRecognitionHintPhrases,hintPhrasesBoost:this.config.speechRecognitionHintPhrasesBoost,locales:this.config.speechRecognitionLocales,messages:this.messages,promptMetadata:this.promptMetadata,sessionId:this.id,sendMessage: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(l.A.debug("Processing data channel message",e),e.msg.type){case ri.NlpPromptResult:this.messages.next(new _s.nD(e.msg));break;case ri.AvatarStartedSpeaking:this.messages.next(new _s.yr);break;case ri.AvatarStoppedSpeaking:this.messages.next(new _s.kS);break;case ri.Error:l.A.error(`an error has occurred - ${JSON.stringify(e.msg)}`),this.handleChannelMessageError(e.msg);break;case ri.SceneReady:l.A.debug("Scene is ready"),t.sceneReady=!0,this.handleSessionReady(t),this.messages.next(new _s.Ln);break;case ri.SpeechEvent:this.messages.next(new _s.Qd(e.msg));break;case ri.SessionEnded:{const t="UserInactivity"===e.msg.reason?"sessionEndedDueToInactivity":e.msg.reason;this.signaling?.endSession(t),this.signaling=void 0;break}case ri.SpeechStreamOpened:this.audioStreamId=e.msg.streamId;break;case ri.SpeechStreamClosed:e.msg.streamId===this.audioStreamId?this.audioStreamId=void 0:l.A.warn("Received SpeechStreamClosed message for unexpected streamId",e.msg.streamId)}}handleChannelMessageError(e){const t=e?.message?.trim()||"An unknown error occurred";e&&gi.includes(e.code)?this.messages.next(new _s.Uh(e)):this.messages.next(new _s.Cj(t))}sendWelcomePrompt(){l.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 Bs.D(this.config.welcomePrompt,this.promptMetadata)))}listenForTabClosure(){window.addEventListener("beforeunload",()=>{l.A.info("Window unload detected, ending session."),this.signaling?.endSession(),this.signaling=void 0})}}class vi{prompt;requestId;constructor(e,t=(0,li.g)()){this.prompt=e,this.requestId=t}toJSON(){return{action:Ws.A.Speak,data:{requestId:this.requestId,prompt:this.prompt}}}}var Si,bi=o(58);!function(e){e.Open="open",e.Close="close",e.Interrupt="interrupt"}(Si||(Si={}));class wi{action;streamId;metadata;requestId;constructor(e,t,n={},s=(0,li.g)()){this.action=e,this.streamId=t,this.metadata=n,this.requestId=s}toJSON(){return{action:Ws.A.SpeechStream,data:{requestId:this.requestId,action:this.action,streamId:this.streamId,metadata:this.metadata}}}}class Ci{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:Ws.A.ExecuteCommand,data:e}}}class Ti{config;session;messageSubscription;constructor(e){this.config=e,l.A.setLevel(e.logLevel??"info")}init(){if(this.session){const e="Cannot initialize: session already active. Call endSession() first.";throw l.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 l.A.error(e),new Error(e)}var e;l.A.info(`Initializing Uneeq with config:', ${JSON.stringify(this.config)}, for UserAgent: ${navigator.userAgent}`),this.session=new yi(this.config),this.session.createSession(),this.messageSubscription=this.session.messages.subscribe(e=>{e.uneeqMessageType===_s.Yg.SessionEnded&&(l.A.info("Session ended, resetting session state"),this.resetSessionState())})}isSessionActive(){return void 0!==this.session}ensureSessionExists(){return!!this.session?.id||(l.A.warn("Cannot perform action, session has not started."),!1)}chatPrompt(e){e&&""!==e.trim()&&this.ensureSessionExists()&&this.session?.signaling?.dataSend(new Bs.D(e,this.session?.promptMetadata))}speak(e){e&&""!==e.trim()&&this.ensureSessionExists()&&this.session?.signaling?.dataSend(new vi(e))}openAudioStream(){const e=this.session;this.ensureSessionExists()&&e?.signaling?.dataSend(new wi(Si.Open,e?.audioStreamId))}closeAudioStream(){const e=this.session;this.ensureSessionExists()&&void 0!==e?.audioStreamId&&e.signaling?.dataSend(new wi(Si.Close,e.audioStreamId))}interruptAudioStream(){const e=this.session;this.ensureSessionExists()&&void 0!==e?.audioStreamId&&e.signaling?.dataSend(new wi(Si.Interrupt,e.audioStreamId))}async speakAudio(e){this.ensureSessionExists()&&await async function(e,t){try{if(void 0===e?.audioStreamId)return void l.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 l.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]),r=new Uint8Array(2+n.length);r.set(s,0),r.set(i,1),r.set(n,2),e.signaling?.dataSendBinary(r)}catch(e){l.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 Ci(e,t,n,s))}endSession(){this.ensureSessionExists()&&(this.session?.signaling?.endSession(),this.resetSessionState())}resetSessionState(){this.messageSubscription?.unsubscribe(),this.messageSubscription=void 0,this.session=void 0}unmuteDigitalHuman(){this.ensureSessionExists()&&(this.session?.signaling?.playAudioElement(),l.A.debug("Unmuted digital human."))}muteDigitalHuman(){this.ensureSessionExists()&&(this.session?.signaling?.pauseAudioElement(),l.A.debug("Muted digital human."))}stopSpeaking(){this.ensureSessionExists()&&this.session?.signaling?.dataSend(new bi.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=Zs(this.config.audioUpstreamMode);if(!ti(e))return l.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=Zs(this.config.audioUpstreamMode);if(!ti(e))return l.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}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,l.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=o(508);return window.Uneeq=Ti,a})());
|
|
2
2
|
//# sourceMappingURL=index.js.map
|