@epicgames-ps/lib-pixelstreamingfrontend-ue5.4
Version:
Frontend library for Unreal Engine 5.4 Pixel Streaming
1 lines • 147 kB
JavaScript
import*as e from"sdp";var t,s,n={d:(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},r={};n.d(r,{Dz:()=>ye,g$:()=>A,Lt:()=>k,Q9:()=>x,qf:()=>L,hV:()=>Ae,z$:()=>wt,J0:()=>Pe,De:()=>Te,$C:()=>Ee,al:()=>_,_W:()=>V,Gv:()=>se,m:()=>ne,tz:()=>z,Nu:()=>Re,zg:()=>He,vp:()=>he,vU:()=>ue,wF:()=>J,rv:()=>we,Nh:()=>be,ss:()=>_e,qW:()=>re,QL:()=>te,cf:()=>Ne,eM:()=>j,Yd:()=>i,Tk:()=>Ge,iM:()=>S,qy:()=>a,ce:()=>v,sK:()=>me,Ok:()=>Ce,q5:()=>ke,g:()=>Mt,xl:()=>q,I:()=>$,bx:()=>X,dD:()=>de,Ib:()=>M,Az:()=>w,Iw:()=>b,qY:()=>P,db:()=>R,mR:()=>ie,Tn:()=>C,rV:()=>Y,gh:()=>W,Mi:()=>N,j:()=>K,YB:()=>Q,Yt:()=>ee,i5:()=>Z,x_:()=>Se,Am:()=>pt,eR:()=>F,r8:()=>H,u3:()=>We,vd:()=>O,iV:()=>U,jZ:()=>I,SW:()=>B,ZH:()=>G,Ni:()=>vt,lh:()=>D,ZP:()=>ce,bq:()=>f,$f:()=>ft,eu:()=>le,Ax:()=>oe,Mc:()=>ae});class i{static GetStackTrace(){const e=new Error;let t="No Stack Available for this browser";return e.stack&&(t=e.stack.toString().replace(/Error/g,"")),t}static SetLoggerVerbosity(e){null!=this.verboseLogLevel&&(this.verboseLogLevel=e)}static Log(e,t,s){if(s>this.verboseLogLevel)return;const n=`Level: Log\nMsg: ${t}\nCaller: ${e}`;console.log(n)}static Info(e,t,s){if(s>this.verboseLogLevel)return;const n=`Level: Info\nMsg: ${t}`;console.info(n)}static Error(e,t){const s=`Level: Error\nMsg: ${t}\nCaller: ${e}`;console.error(s)}static Warning(e,t){const s=`Level: Warning\nCaller: ${e}\nMsg: ${t}`;console.warn(s)}}i.verboseLogLevel=5,function(e){e.LIST_STREAMERS="listStreamers",e.SUBSCRIBE="subscribe",e.UNSUBSCRIBE="unsubscribe",e.ICE_CANDIDATE="iceCandidate",e.OFFER="offer",e.ANSWER="answer",e.DATACHANNELREQUEST="dataChannelRequest",e.SFURECVDATACHANNELREADY="peerDataChannelsReady",e.PONG="pong"}(t||(t={}));class a{sendFilter(e,t){return t}payload(){return i.Log(i.GetStackTrace(),"Sending => \n"+JSON.stringify(this,this.sendFilter,4),6),JSON.stringify(this,this.sendFilter)}}class o extends a{constructor(){super(),this.type=t.LIST_STREAMERS}}class l extends a{constructor(e){super(),this.type=t.SUBSCRIBE,this.streamerId=e}}class d extends a{constructor(){super(),this.type=t.UNSUBSCRIBE}}class c extends a{constructor(e){super(),this.type=t.PONG,this.time=e}}class h extends a{constructor(e,s){super(),this.type=t.OFFER,this.minBitrate=0,this.maxBitrate=0,e&&(this.type=e.type,this.sdp=e.sdp,this.minBitrate=s.minBitrateBps,this.maxBitrate=s.maxBitrateBps)}sendFilter(e,t){if("minBitrate"!=e&&"maxBitrate"!=e||!(t<=0))return t}}class u extends a{constructor(e,s){super(),this.type=t.ANSWER,this.minBitrate=0,this.maxBitrate=0,e&&(this.type=e.type,this.sdp=e.sdp,this.minBitrate=s.minBitrateBps,this.maxBitrate=s.maxBitrateBps)}sendFilter(e,t){if("minBitrate"!=e&&"maxBitrate"!=e||!(t<=0))return t}}class g extends a{constructor(){super(),this.type=t.DATACHANNELREQUEST}}class m extends a{constructor(){super(),this.type=t.SFURECVDATACHANNELREADY}}class p{constructor(e){this.type=t.ICE_CANDIDATE,this.candidate=e}payload(){return i.Log(i.GetStackTrace(),"Sending => \n"+JSON.stringify(this,void 0,4),6),JSON.stringify(this)}}!function(e){e.CONFIG="config",e.STREAMER_LIST="streamerList",e.STREAMER_ID_CHANGED="streamerIDChanged",e.PLAYER_COUNT="playerCount",e.OFFER="offer",e.ANSWER="answer",e.ICE_CANDIDATE="iceCandidate",e.PEER_DATA_CHANNELS="peerDataChannels",e.PING="ping",e.WARNING="warning"}(s||(s={}));class S{}class v extends S{}class C{constructor(){this.FromUEMessageHandlers=new Map}addMessageHandler(e,t){this.FromUEMessageHandlers.set(e,t)}handleMessage(e,t){this.FromUEMessageHandlers.has(e)?this.FromUEMessageHandlers.get(e)(t):i.Error(i.GetStackTrace(),`Message type of ${e} does not have a message handler registered on the frontend - ignoring message.`)}static setupDefaultHandlers(e){e.signallingProtocol.addMessageHandler(s.PING,(t=>{const n=new c((new Date).getTime()).payload();i.Log(i.GetStackTrace(),s.PING+": "+t,6),e.webSocket.send(n)})),e.signallingProtocol.addMessageHandler(s.CONFIG,(t=>{i.Log(i.GetStackTrace(),s.CONFIG,6);const n=JSON.parse(t);e.onConfig(n)})),e.signallingProtocol.addMessageHandler(s.STREAMER_LIST,(t=>{i.Log(i.GetStackTrace(),s.STREAMER_LIST,6);const n=JSON.parse(t);e.onStreamerList(n)})),e.signallingProtocol.addMessageHandler(s.STREAMER_ID_CHANGED,(t=>{i.Log(i.GetStackTrace(),s.STREAMER_ID_CHANGED,6);const n=JSON.parse(t);e.onStreamerIDChanged(n)})),e.signallingProtocol.addMessageHandler(s.PLAYER_COUNT,(t=>{i.Log(i.GetStackTrace(),s.PLAYER_COUNT,6);const n=JSON.parse(t);i.Log(i.GetStackTrace(),"Player Count: "+n.count,6),e.onPlayerCount(n)})),e.signallingProtocol.addMessageHandler(s.ANSWER,(t=>{i.Log(i.GetStackTrace(),s.ANSWER,6);const n=JSON.parse(t);e.onWebRtcAnswer(n)})),e.signallingProtocol.addMessageHandler(s.OFFER,(t=>{i.Log(i.GetStackTrace(),s.OFFER,6);const n=JSON.parse(t);e.onWebRtcOffer(n)})),e.signallingProtocol.addMessageHandler(s.ICE_CANDIDATE,(t=>{i.Log(i.GetStackTrace(),s.ICE_CANDIDATE,6);const n=JSON.parse(t);e.onIceCandidate(n.candidate)})),e.signallingProtocol.addMessageHandler(s.WARNING,(e=>{i.Warning(i.GetStackTrace(),`Warning received: ${e}`)})),e.signallingProtocol.addMessageHandler(s.PEER_DATA_CHANNELS,(t=>{i.Log(i.GetStackTrace(),s.PEER_DATA_CHANNELS,6);const n=JSON.parse(t);e.onWebRtcPeerDataChannels(n)}))}}class f{constructor(){this.WS_OPEN_STATE=1,this.onOpen=new EventTarget,this.onClose=new EventTarget,this.signallingProtocol=new C,C.setupDefaultHandlers(this)}connect(e){i.Log(i.GetStackTrace(),e,6);try{return this.webSocket=new WebSocket(e),this.webSocket.onopen=e=>this.handleOnOpen(e),this.webSocket.onerror=()=>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 i.Error(e,e),!1}}handleOnMessageBinary(e){e&&e.data&&e.data.text().then((e=>{const t=new MessageEvent("messageFromBinary",{data:e});this.handleOnMessage(t)})).catch((e=>{i.Error(i.GetStackTrace(),`Failed to parse binary blob from websocket, reason: ${e}`)}))}handleOnMessage(e){if(e.data&&e.data instanceof Blob)return void this.handleOnMessageBinary(e);const t=JSON.parse(e.data);i.Log(i.GetStackTrace(),"received => \n"+JSON.stringify(JSON.parse(e.data),void 0,4),6),this.signallingProtocol.handleMessage(t.type,e.data)}handleOnOpen(e){i.Log(i.GetStackTrace(),"Connected to the signalling server via WebSocket",6),this.onOpen.dispatchEvent(new Event("open"))}handleOnError(){i.Error(i.GetStackTrace(),"WebSocket error")}handleOnClose(e){i.Log(i.GetStackTrace(),"Disconnected to the signalling server via WebSocket: "+JSON.stringify(e.code)+" - "+e.reason),this.onClose.dispatchEvent(new CustomEvent("close",{detail:e}))}requestStreamerList(){const e=new o;this.webSocket.send(e.payload())}sendSubscribe(e){const t=new l(e);this.webSocket.send(t.payload())}sendUnsubscribe(){const e=new d;this.webSocket.send(e.payload())}sendWebRtcOffer(e,t){const s=new h(e,t);this.webSocket.send(s.payload())}sendWebRtcAnswer(e,t){const s=new u(e,t);this.webSocket.send(s.payload())}sendWebRtcDatachannelRequest(){const e=new g;this.webSocket.send(e.payload())}sendSFURecvDataChannelReady(){const e=new m;this.webSocket.send(e.payload())}sendIceCandidate(e){if(i.Log(i.GetStackTrace(),"Sending Ice Candidate"),this.webSocket&&this.webSocket.readyState===this.WS_OPEN_STATE){const t=new p(e);this.webSocket.send(t.payload())}}close(){var e;null===(e=this.webSocket)||void 0===e||e.close()}onConfig(e){}onStreamerList(e){}onStreamerIDChanged(e){}onIceCandidate(e){}onWebRtcAnswer(e){}onWebRtcOffer(e){}onWebRtcPeerDataChannels(e){}onPlayerCount(e){}}class T{constructor(e){this.videoElementProvider=e,this.audioElement=document.createElement("Audio"),this.videoElementProvider.setAudioElement(this.audioElement)}handleOnTrack(e){if(i.Log(i.GetStackTrace(),"handleOnTrack "+JSON.stringify(e.streams),6),"probator"==e.track.id)return;const t=this.videoElementProvider.getVideoElement();if(e.track&&i.Log(i.GetStackTrace(),"Got track - "+e.track.kind+" id="+e.track.id+" readyState="+e.track.readyState,6),"audio"!=e.track.kind)return"video"==e.track.kind&&t.srcObject!==e.streams[0]?(t.srcObject=e.streams[0],void i.Log(i.GetStackTrace(),"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,i.Log(i.GetStackTrace(),"Created new audio element to play separate audio stream."))}}class E{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,s=0,n=0;const r=this.rootDiv.clientWidth/this.rootDiv.clientHeight,i=this.freezeFrameWidth/this.freezeFrameHeight;r<i?(e=this.rootDiv.clientWidth,t=Math.floor(this.rootDiv.clientWidth/i),s=Math.floor(.5*(this.rootDiv.clientHeight-t)),n=0):(e=Math.floor(this.rootDiv.clientHeight*i),t=this.rootDiv.clientHeight,s=0,n=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=n+"px",this.imageElement.style.top=s+"px"}}}class y{constructor(e){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new E(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 s=e.slice(5);if(this.jpeg){const e=new Uint8Array(this.jpeg.length+s.length);e.set(this.jpeg,0),e.set(s,this.jpeg.length),this.jpeg=e}else this.jpeg=s,this.receiving=!0,i.Log(i.GetStackTrace(),`received first chunk of freeze frame: ${this.jpeg.length}/${this.size}`,6);this.jpeg.length===this.size?(this.receiving=!1,this.valid=!0,i.Log(i.GetStackTrace(),`received complete freeze frame ${this.size}`,6),this.updateFreezeFrameAndShow(this.jpeg,t)):this.jpeg.length>this.size&&(i.Error(i.GetStackTrace(),`received bigger freeze frame than advertised: ${this.jpeg.length}/${this.size}`),this.jpeg=void 0,this.receiving=!1)}}class M{constructor(e,t,s,n,r=(()=>{})){this.onChange=r,this.onChangeEmit=()=>{},this.id=e,this.description=s,this.label=t,this.value=n}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)}}class w extends M{constructor(e,t,s,n,r,i=(()=>{})){super(e,t,s,n,i);const a=new URLSearchParams(window.location.search);if(r&&a.has(this.id)){const e=this.getUrlParamFlag();this.flag=e}else this.flag=n;this.useUrlParams=r}getUrlParamFlag(){const e=new URLSearchParams(window.location.search);return!!e.has(this.id)&&"false"!==e.get(this.id)&&"False"!==e.get(this.id)}updateURLParams(){if(this.useUrlParams){const e=new URLSearchParams(window.location.search);!0===this.flag?e.set(this.id,"true"):e.set(this.id,"false"),window.history.replaceState({},"",""!==e.toString()?`${location.pathname}?${e}`:`${location.pathname}`)}}enable(){this.flag=!0}get flag(){return!!this.value}set flag(e){this.value=e}}class b extends M{constructor(e,t,s,n,r,i,a,o=(()=>{})){super(e,t,s,i,o),this._min=n,this._max=r;const l=new URLSearchParams(window.location.search);if(a&&l.has(this.id)){const e=Number.parseFloat(l.get(this.id));this.number=Number.isNaN(e)?i:e}else this.number=i;this.useUrlParams=a}updateURLParams(){if(this.useUrlParams){const e=new URLSearchParams(window.location.search);e.set(this.id,this.number.toString()),window.history.replaceState({},"",""!==e.toString()?`${location.pathname}?${e}`:`${location.pathname}`)}}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 R extends M{constructor(e,t,s,n,r,i=(()=>{})){super(e,t,s,n,i);const a=new URLSearchParams(window.location.search);if(r&&a.has(this.id)){const e=this.getUrlParamText();this.text=e}else this.text=n;this.useUrlParams=r}getUrlParamText(){var e;const t=new URLSearchParams(window.location.search);return t.has(this.id)&&null!==(e=t.get(this.id))&&void 0!==e?e:""}updateURLParams(){if(this.useUrlParams){const e=new URLSearchParams(window.location.search);e.set(this.id,this.text),window.history.replaceState({},"",""!==e.toString()?`${location.pathname}?${e}`:`${location.pathname}`)}}get text(){return this.value}set text(e){this.value=e}}class P extends M{constructor(e,t,s,n,r,i,a=(()=>{})){super(e,t,s,n,a),this.options=r;const o=new URLSearchParams(window.location.search),l=i&&o.has(this.id)?this.getUrlParamText():n;this.selected=l,this.useUrlParams=i}getUrlParamText(){var e;const t=new URLSearchParams(window.location.search);return t.has(this.id)&&null!==(e=t.get(this.id))&&void 0!==e?e:""}updateURLParams(){if(this.useUrlParams){const e=new URLSearchParams(window.location.search);e.set(this.id,this.selected),window.history.replaceState({},"",""!==e.toString()?`${location.pathname}?${e}`:`${location.pathname}`)}}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){let t=this.options.filter((t=>-1!==t.indexOf(e)));t.length?this.value=t[0]:(t=this.options.filter((t=>-1!==t.indexOf(e.split(" ")[0]))),t.length&&(this.value=t[0]))}}class k extends Event{constructor(e){super("afkWarningActivate"),this.data=e}}class L extends Event{constructor(e){super("afkWarningUpdate"),this.data=e}}class x extends Event{constructor(){super("afkWarningDeactivate")}}class A extends Event{constructor(){super("afkTimedOut")}}class F extends Event{constructor(e){super("videoEncoderAvgQP"),this.data=e}}class D extends Event{constructor(){super("webRtcSdp")}}class O extends Event{constructor(){super("webRtcAutoConnect")}}class I extends Event{constructor(){super("webRtcConnecting")}}class U extends Event{constructor(){super("webRtcConnected")}}class G extends Event{constructor(){super("webRtcFailed")}}class B extends Event{constructor(e){super("webRtcDisconnected"),this.data=e}}class z extends Event{constructor(e){super("dataChannelOpen"),this.data=e}}class _ extends Event{constructor(e){super("dataChannelClose"),this.data=e}}class V extends Event{constructor(e){super("dataChannelError"),this.data=e}}class H extends Event{constructor(){super("videoInitialized")}}class W extends Event{constructor(){super("streamLoading")}}class N extends Event{constructor(){super("streamConnect")}}class K extends Event{constructor(){super("streamDisconnect")}}class Q extends Event{constructor(){super("streamReconnect")}}class q extends Event{constructor(e){super("playStreamError"),this.data=e}}class $ extends Event{constructor(){super("playStream")}}class X extends Event{constructor(e){super("playStreamRejected"),this.data=e}}class j extends Event{constructor(e){super("loadFreezeFrame"),this.data=e}}class J extends Event{constructor(){super("hideFreezeFrame")}}class Y extends Event{constructor(e){super("statsReceived"),this.data=e}}class Z extends Event{constructor(e){super("streamerListMessage"),this.data=e}}class ee extends Event{constructor(e){super("StreamerIDChangedMessage"),this.data=e}}class te extends Event{constructor(e){super("latencyTestResult"),this.data=e}}class se extends Event{constructor(e){super("dataChannelLatencyTestResponse"),this.data=e}}class ne extends Event{constructor(e){super("dataChannelLatencyTestResult"),this.data=e}}class re extends Event{constructor(e){super("initialSettings"),this.data=e}}class ie extends Event{constructor(e){super("settingsChanged"),this.data=e}}class ae extends Event{constructor(){super("xrSessionStarted")}}class oe extends Event{constructor(){super("xrSessionEnded")}}class le extends Event{constructor(e){super("xrFrame"),this.data=e}}class de extends Event{constructor(e){super("playerCount"),this.data=e}}class ce extends Event{constructor(){super("webRtcTCPRelayDetected")}}class he extends EventTarget{dispatchEvent(e){return super.dispatchEvent(e)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}}class ue{}ue.AutoConnect="AutoConnect",ue.AutoPlayVideo="AutoPlayVideo",ue.AFKDetection="TimeoutIfIdle",ue.BrowserSendOffer="OfferToReceive",ue.HoveringMouseMode="HoveringMouse",ue.ForceMonoAudio="ForceMonoAudio",ue.ForceTURN="ForceTURN",ue.FakeMouseWithTouches="FakeMouseWithTouches",ue.IsQualityController="ControlsQuality",ue.MatchViewportResolution="MatchViewportRes",ue.StartVideoMuted="StartVideoMuted",ue.SuppressBrowserKeys="SuppressBrowserKeys",ue.UseMic="UseMic",ue.KeyboardInput="KeyboardInput",ue.MouseInput="MouseInput",ue.TouchInput="TouchInput",ue.GamepadInput="GamepadInput",ue.XRControllerInput="XRControllerInput",ue.WaitForStreamer="WaitForStreamer",ue.HideUI="HideUI";const ge=e=>Object.getOwnPropertyNames(ue).some((t=>ue[t]===e));class me{}me.AFKTimeoutSecs="AFKTimeout",me.AFKCountdownSecs="AFKCountdown",me.MinQP="MinQP",me.MaxQP="MaxQP",me.WebRTCFPS="WebRTCFPS",me.WebRTCMinBitrate="WebRTCMinBitrate",me.WebRTCMaxBitrate="WebRTCMaxBitrate",me.MaxReconnectAttempts="MaxReconnectAttempts",me.StreamerAutoJoinInterval="StreamerAutoJoinInterval";const pe=e=>Object.getOwnPropertyNames(me).some((t=>me[t]===e));class Se{}Se.SignallingServerUrl="ss";const ve=e=>Object.getOwnPropertyNames(Se).some((t=>Se[t]===e));class Ce{}Ce.PreferredCodec="PreferredCodec",Ce.StreamerId="StreamerId";const fe=e=>Object.getOwnPropertyNames(Ce).some((t=>Ce[t]===e));class Te{constructor(e={}){this.flags=new Map,this.numericParameters=new Map,this.textParameters=new Map,this.optionParameters=new Map;const{initialSettings:t,useUrlParams:s}=e;this._useUrlParams=!!s,this.populateDefaultSettings(this._useUrlParams,t)}get useUrlParams(){return this._useUrlParams}populateDefaultSettings(e,t){this.textParameters.set(Se.SignallingServerUrl,new R(Se.SignallingServerUrl,"Signalling url","Url of the signalling server",t&&t.hasOwnProperty(Se.SignallingServerUrl)?t[Se.SignallingServerUrl]:("https:"===location.protocol?"wss://":"ws://")+window.location.hostname+("80"===window.location.port||""===window.location.port?"":`:${window.location.port}`),e)),this.optionParameters.set(Ce.StreamerId,new P(Ce.StreamerId,"Streamer ID","The ID of the streamer to stream.",t&&t.hasOwnProperty(Ce.StreamerId)?t[Ce.StreamerId]:"",[],e)),this.optionParameters.set(Ce.PreferredCodec,new P(Ce.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation","H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",t&&t.hasOwnProperty(Ce.PreferredCodec)?[t[Ce.PreferredCodec]]:function(){const e=[];if(!RTCRtpReceiver.getCapabilities)return e.push("Only available on Chrome"),e;const t=/(VP\d|H26\d|AV1).*/;return RTCRtpReceiver.getCapabilities("video").codecs.forEach((s=>{const n=s.mimeType.split("/")[1]+" "+(s.sdpFmtpLine||"");null!==t.exec(n)&&e.push(n)})),e}(),e)),this.flags.set(ue.AutoConnect,new w(ue.AutoConnect,"Auto connect to stream","Whether we should attempt to auto connect to the signalling server or show a click to start prompt.",!(!t||!t.hasOwnProperty(ue.AutoConnect))&&t[ue.AutoConnect],e)),this.flags.set(ue.AutoPlayVideo,new w(ue.AutoPlayVideo,"Auto play video","When video is ready automatically start playing it as opposed to showing a play button.",!t||!t.hasOwnProperty(ue.AutoPlayVideo)||t[ue.AutoPlayVideo],e)),this.flags.set(ue.BrowserSendOffer,new w(ue.BrowserSendOffer,"Browser send offer","Browser will initiate the WebRTC handshake by sending the offer to the streamer",!(!t||!t.hasOwnProperty(ue.BrowserSendOffer))&&t[ue.BrowserSendOffer],e)),this.flags.set(ue.UseMic,new w(ue.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!t||!t.hasOwnProperty(ue.UseMic))&&t[ue.UseMic],e)),this.flags.set(ue.StartVideoMuted,new w(ue.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!t||!t.hasOwnProperty(ue.StartVideoMuted))&&t[ue.StartVideoMuted],e)),this.flags.set(ue.SuppressBrowserKeys,new w(ue.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||!t.hasOwnProperty(ue.SuppressBrowserKeys)||t[ue.SuppressBrowserKeys],e)),this.flags.set(ue.IsQualityController,new w(ue.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!t||!t.hasOwnProperty(ue.IsQualityController)||t[ue.IsQualityController],e)),this.flags.set(ue.ForceMonoAudio,new w(ue.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!t||!t.hasOwnProperty(ue.ForceMonoAudio))&&t[ue.ForceMonoAudio],e)),this.flags.set(ue.ForceTURN,new w(ue.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!t||!t.hasOwnProperty(ue.ForceTURN))&&t[ue.ForceTURN],e)),this.flags.set(ue.AFKDetection,new w(ue.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!t||!t.hasOwnProperty(ue.AFKDetection))&&t[ue.AFKDetection],e)),this.flags.set(ue.MatchViewportResolution,new w(ue.MatchViewportResolution,"Match viewport resolution","Pixel Streaming will be instructed to dynamically resize the video stream to match the size of the video element.",!(!t||!t.hasOwnProperty(ue.MatchViewportResolution))&&t[ue.MatchViewportResolution],e)),this.flags.set(ue.HoveringMouseMode,new w(ue.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||!t.hasOwnProperty(ue.HoveringMouseMode))&&t[ue.HoveringMouseMode],e,((e,t)=>{t.label=`Control Scheme: ${e?"Hovering":"Locked"} Mouse`}))),this.flags.set(ue.FakeMouseWithTouches,new w(ue.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||!t.hasOwnProperty(ue.FakeMouseWithTouches))&&t[ue.FakeMouseWithTouches],e)),this.flags.set(ue.KeyboardInput,new w(ue.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!t||!t.hasOwnProperty(ue.KeyboardInput)||t[ue.KeyboardInput],e)),this.flags.set(ue.MouseInput,new w(ue.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!t||!t.hasOwnProperty(ue.MouseInput)||t[ue.MouseInput],e)),this.flags.set(ue.TouchInput,new w(ue.TouchInput,"Touch input","If enabled, send touch events to streamer",!t||!t.hasOwnProperty(ue.TouchInput)||t[ue.TouchInput],e)),this.flags.set(ue.GamepadInput,new w(ue.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!t||!t.hasOwnProperty(ue.GamepadInput)||t[ue.GamepadInput],e)),this.flags.set(ue.XRControllerInput,new w(ue.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!t||!t.hasOwnProperty(ue.XRControllerInput)||t[ue.XRControllerInput],e)),this.flags.set(ue.WaitForStreamer,new w(ue.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!t||!t.hasOwnProperty(ue.WaitForStreamer)||t[ue.WaitForStreamer],e)),this.flags.set(ue.HideUI,new w(ue.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!t||!t.hasOwnProperty(ue.HideUI))&&t[ue.HideUI],e)),this.numericParameters.set(me.AFKTimeoutSecs,new b(me.AFKTimeoutSecs,"AFK timeout","The time (in seconds) it takes for the application to time out if AFK timeout is enabled.",0,null,t&&t.hasOwnProperty(me.AFKTimeoutSecs)?t[me.AFKTimeoutSecs]:120,e)),this.numericParameters.set(me.AFKCountdownSecs,new b(me.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(me.MaxReconnectAttempts,new b(me.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,t&&t.hasOwnProperty(me.MaxReconnectAttempts)?t[me.MaxReconnectAttempts]:3,e)),this.numericParameters.set(me.MinQP,new b(me.MinQP,"Min QP","The lower bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,t&&t.hasOwnProperty(me.MinQP)?t[me.MinQP]:0,e)),this.numericParameters.set(me.MaxQP,new b(me.MaxQP,"Max QP","The upper bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,t&&t.hasOwnProperty(me.MaxQP)?t[me.MaxQP]:51,e)),this.numericParameters.set(me.WebRTCFPS,new b(me.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,t&&t.hasOwnProperty(me.WebRTCFPS)?t[me.WebRTCFPS]:60,e)),this.numericParameters.set(me.WebRTCMinBitrate,new b(me.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,t&&t.hasOwnProperty(me.WebRTCMinBitrate)?t[me.WebRTCMinBitrate]:0,e)),this.numericParameters.set(me.WebRTCMaxBitrate,new b(me.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,t&&t.hasOwnProperty(me.WebRTCMaxBitrate)?t[me.WebRTCMaxBitrate]:0,e)),this.numericParameters.set(me.StreamerAutoJoinInterval,new b(me.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,t&&t.hasOwnProperty(me.StreamerAutoJoinInterval)?t[me.StreamerAutoJoinInterval]:3e3,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:i.Warning(i.GetStackTrace(),`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:i.Warning(i.GetStackTrace(),`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:i.Warning(i.GetStackTrace(),`Cannot set text setting called ${e} - it does not exist in the Config.optionParameters map.`)}setOptionSettingValue(e,t){if(this.optionParameters.has(e)){const s=this.optionParameters.get(e),n=s.options;n.includes(t)||(n.push(t),s.options=n),s.selected=t}else i.Warning(i.GetStackTrace(),`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:i.Warning(i.GetStackTrace(),`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))ge(t)?this.setFlagEnabled(t,e[t]):pe(t)?this.setNumericSetting(t,e[t]):ve(t)?this.setTextSetting(t,e[t]):fe(t)&&this.setOptionSettingValue(t,e[t])}getSettings(){const e={};for(const[t,s]of this.flags.entries())e[t]=s.flag;for(const[t,s]of this.numericParameters.entries())e[t]=s.number;for(const[t,s]of this.textParameters.entries())e[t]=s.text;for(const[t,s]of this.optionParameters.entries())e[t]=s.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 s=this.flags.get(t);s&&(s.onChangeEmit=t=>e.dispatchEvent(new ie({id:s.id,type:"flag",value:t,target:s})))}for(const t of this.numericParameters.keys()){const s=this.numericParameters.get(t);s&&(s.onChangeEmit=t=>e.dispatchEvent(new ie({id:s.id,type:"number",value:t,target:s})))}for(const t of this.textParameters.keys()){const s=this.textParameters.get(t);s&&(s.onChangeEmit=t=>e.dispatchEvent(new ie({id:s.id,type:"text",value:t,target:s})))}for(const t of this.optionParameters.keys()){const s=this.optionParameters.get(t);s&&(s.onChangeEmit=t=>e.dispatchEvent(new ie({id:s.id,type:"option",value:t,target:s})))}}}var Ee;!function(e){e[e.LockedMouse=0]="LockedMouse",e[e.HoveringMouse=1]="HoveringMouse"}(Ee||(Ee={}));class ye{constructor(e,t,s){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=s,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 x))}startAfkWarningTimer(){this.config.getNumericSettingValue(me.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(ue.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(ue.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout((()=>this.activateAfkEvent()),1e3*this.config.getNumericSettingValue(me.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new k({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(me.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new L({countDown:this.countDown})),this.config.isFlagEnabled(ue.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval((()=>{this.countDown--,0==this.countDown?(this.pixelStreaming.dispatchEvent(new A),this.onAFKTimedOutCallback(),i.Log(i.GetStackTrace(),"You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new L({countDown:this.countDown}))}),1e3)}}class Me{constructor(){this.isReceivingFreezeFrame=!1}getDataChannelInstance(){return this}createDataChannel(e,t,s){this.peerConnection=e,this.label=t,this.datachannelOptions=s,null==s&&(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;i.Log(i.GetStackTrace(),`Data Channel (${this.label}) opened.`,7),this.onOpen(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}handleOnClose(e){var t;i.Log(i.GetStackTrace(),`Data Channel (${this.label}) closed.`,7),this.onClose(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}handleOnMessage(e){i.Log(i.GetStackTrace(),`Data Channel (${this.label}) message: ${e}`,8)}handleOnError(e){var t;i.Log(i.GetStackTrace(),`Data Channel (${this.label}) error: ${e}`,7),this.onError(null===(t=this.dataChannel)||void 0===t?void 0:t.label,e)}onOpen(e,t){}onClose(e,t){}onError(e,t){}}class we{}class be{}class Re{}class Pe{}class ke{}class Le{}class xe{}class Ae{constructor(){this.inboundVideoStats=new be,this.inboundAudioStats=new we,this.DataChannelStats=new Re,this.outBoundVideoStats=new ke,this.sessionStats=new Le,this.streamStats=new xe,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"outbound-rtp":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"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:i.Error(i.GetStackTrace(),"unhandled Stat Type"),i.Log(i.GetStackTrace(),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 Pe;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 Pe;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":this.inboundVideoStats=e,null!=this.lastVideoStats&&(this.inboundVideoStats.bitrate=8*(this.inboundVideoStats.bytesReceived-this.lastVideoStats.bytesReceived)/(this.inboundVideoStats.timestamp-this.lastVideoStats.timestamp),this.inboundVideoStats.bitrate=Math.floor(this.inboundVideoStats.bitrate)),this.lastVideoStats=Object.assign({},this.inboundVideoStats);break;case"audio":this.inboundAudioStats=e,null!=this.lastAudioStats&&(this.inboundAudioStats.bitrate=8*(this.inboundAudioStats.bytesReceived-this.lastAudioStats.bytesReceived)/(this.inboundAudioStats.timestamp-this.lastAudioStats.timestamp),this.inboundAudioStats.bitrate=Math.floor(this.inboundAudioStats.bitrate)),this.lastAudioStats=Object.assign({},this.inboundAudioStats);break;default:i.Log(i.GetStackTrace(),"Kind is not handled")}}handleRemoteOutBound(e){"video"===e.kind&&(this.outBoundVideoStats.bytesSent=e.bytesSent,this.outBoundVideoStats.id=e.id,this.outBoundVideoStats.localId=e.localId,this.outBoundVideoStats.packetsSent=e.packetsSent,this.outBoundVideoStats.remoteTimestamp=e.remoteTimestamp,this.outBoundVideoStats.timestamp=e.timestamp)}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,s=`${e.mimeType.replace("video/","").replace("audio/","")}${e.sdpFmtpLine?` ${e.sdpFmtpLine}`:""}`;this.codecs.set(t,s)}handleSessionStatistics(e,t,s){const n=Date.now()-e;this.sessionStats.runTime=new Date(n).toISOString().substr(11,8).toString();const r=null===t?"Not sent yet":t?"true":"false";this.sessionStats.controlsStreamInput=r,this.sessionStats.videoEncoderAvgQP=s}isNumber(e){return"number"==typeof e&&isFinite(e)}getActiveCandidatePair(){return this.transportStats?this.candidatePairs.find((e=>e.id===this.transportStats.selectedCandidatePairId),null):this.candidatePairs.find((e=>e.selected),null)}}const Fe=(De={parseRtpParameters:()=>e.parseRtpParameters,splitSections:()=>e.splitSections},Oe={},n.d(Oe,De),Oe);var De,Oe;class Ie{static isVideoTransciever(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 isAudioTransciever(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}}var Ue,Ge,Be=function(e,t,s,n){return new(s||(s=Promise))((function(r,i){function a(e){try{l(n.next(e))}catch(e){i(e)}}function o(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(a,o)}l((n=n.apply(e,t||[])).next())}))};class ze{constructor(e,t,s){this.config=t,this.createPeerConnection(e,s)}createPeerConnection(e,t){this.config.isFlagEnabled(ue.ForceTURN)&&(e.iceTransportPolicy="relay",i.Log(i.GetStackTrace(),"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 Ae,this.preferredCodec=t,this.updateCodecSelection=!0}createOffer(e,t){return Be(this,void 0,void 0,(function*(){i.Log(i.GetStackTrace(),"Create Offer",6);const s="localhost"===location.hostname||"127.0.0.1"===location.hostname,n="https:"===location.protocol;let r=t.isFlagEnabled(ue.UseMic);!r||s||n||(r=!1,i.Error(i.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),i.Error(i.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(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,r),null===(t=this.peerConnection)||void 0===t||t.setLocalDescription(e),this.onSendWebRTCOffer(e)})).catch((()=>{this.showTextOverlaySetupFailure()}))}))}))}receiveOffer(e,t){var s;return Be(this,void 0,void 0,(function*(){i.Log(i.GetStackTrace(),"Receive Offer",6),null===(s=this.peerConnection)||void 0===s||s.setRemoteDescription(e).then((()=>{const s="localhost"===location.hostname||"127.0.0.1"===location.hostname,n="https:"===location.protocol;let r=t.isFlagEnabled(ue.UseMic);!r||s||n||(r=!1,i.Error(i.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),i.Error(i.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.config.setOptionSettingOptions(Ce.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e)),this.setupTransceiversAsync(r).finally((()=>{var e;null===(e=this.peerConnection)||void 0===e||e.createAnswer().then((e=>{var t;return e.sdp=this.mungeSDP(e.sdp,r),null===(t=this.peerConnection)||void 0===t?void 0:t.setLocalDescription(e)})).then((()=>{var e;this.onSendWebRTCAnswer(null===(e=this.peerConnection)||void 0===e?void 0:e.currentLocalDescription)})).catch((()=>{i.Error(i.GetStackTrace(),"createAnswer() failed")}))}))}))}))}receiveAnswer(e){var t;null===(t=this.peerConnection)||void 0===t||t.setRemoteDescription(e),this.config.setOptionSettingOptions(Ce.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(e))}generateStats(){var e;null===(e=this.peerConnection)||void 0===e||e.getStats(null).then((e=>{this.aggregatedStats.processStats(e),this.onVideoStats(this.aggregatedStats),this.updateCodecSelection&&this.aggregatedStats.inboundVideoStats.codecId&&this.config.setOptionSettingValue(Ce.PreferredCodec,this.aggregatedStats.codecs.get(this.aggregatedStats.inboundVideoStats.codecId))}))}close(){this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null)}mungeSDP(e,t){let s=e.replace(/(a=fmtp:\d+ .*level-asymmetry-allowed=.*)\r\n/gm,"$1;x-google-start-bitrate=10000;x-google-max-bitrate=100000\r\n"),n="maxaveragebitrate=510000;";return t&&(n+="sprop-maxcapturerate=48000;"),n+=this.config.isFlagEnabled(ue.ForceMonoAudio)?"stereo=0;":"stereo=1;",n+="useinbandfec=1",s=s.replace("useinbandfec=1",n),s}handleOnIce(e){var t;i.Log(i.GetStackTrace(),"peerconnection handleOnIce",6),this.config.isFlagEnabled(ue.ForceTURN)&&e.candidate.indexOf("relay")<0?i.Info(i.GetStackTrace(),`Dropping candidate because it was not TURN relay. | Type= ${e.type} | Protocol= ${e.protocol} | Address=${e.address} | Port=${e.port} |`,6):null===(t=this.peerConnection)||void 0===t||t.addIceCandidate(e)}handleSignalStateChange(e){i.Log(i.GetStackTrace(),"signaling state change: "+e,6)}handleIceConnectionStateChange(e){i.Log(i.GetStackTrace(),"ice connection state change: "+e,6),this.onIceConnectionStateChange(e)}handleIceGatheringStateChange(e){i.Log(i.GetStackTrace(),"ice gathering state change: "+JSON.stringify(e),6)}handleOnTrack(e){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,s=this.parseAvailableCodecs(e),n=this.config.getSettingOption(Ce.PreferredCodec).options;for(const e of s)if(n.includes(e))t.push(e);else{const s=e.split(" ")[0];for(const e of n)if(e.includes(s)){t.push(e);break}}return t}setupTransceiversAsync(e){var t,s,n,r,i,a,o,l,d,c,h,u;return Be(this,void 0,void 0,(function*(){let g=!1;for(const e of null!==(s=null===(t=this.peerConnection)||void 0===t?void 0:t.getTransceivers())&&void 0!==s?s:[])if(e&&e.receiver&&e.receiver.track&&"video"===e.receiver.track.kind){g=!0;break}if(g||null===(n=this.peerConnection)||void 0===n||n.addTransceiver("video",{direction:"recvonly"}),RTCRtpReceiver.getCapabilities&&""!=this.preferredCodec)for(const e of null!==(i=null===(r=this.peerConnection)||void 0===r?void 0:r.getTransceivers())&&void 0!==i?i:[])if(e&&e.receiver&&e.receiver.track&&"video"===e.receiver.track.kind&&e.setCodecPreferences){const t=this.preferredCodec.split(" "),s={mimeType:"video/"+t[0],clockRate:9e4,sdpFmtpLine:t[1]?t[1]:""},n=[s];RTCRtpReceiver.getCapabilities("video").codecs.forEach((e=>{(e.mimeType!=s.mimeType||(null==e?void 0:e.sdpFmtpLine)!=(null==s?void 0:s.sdpFmtpLine))&&n.push(e)}));for(const e of n)void 0!==(null==e?void 0:e.sdpFmtpLine)&&""!==e.sdpFmtpLine||delete e.sdpFmtpLine;e.setCodecPreferences(n)}let m=!1;for(const e of null!==(o=null===(a=this.peerConnection)||void 0===a?void 0:a.getTransceivers())&&void 0!==o?o:[])if(e&&e.receiver&&e.receiver.track&&"audio"===e.receiver.track.kind){m=!0;break}if(e){const e={video:!1,audio:{autoGainControl:!1,channelCount:1,echoCancellation:!1,latency:0,noiseSuppression:!1,sampleRate:48e3,sampleSize:16,volume:1}},t=yield navigator.mediaDevices.getUserMedia(e);if(t)if(m){for(const e of null!==(c=null===(d=this.peerConnection)||void 0===d?void 0:d.getTransceivers())&&void 0!==c?c:[])if(Ie.canTransceiverReceiveAudio(e))for(const s of t.getTracks())s.kind&&"audio"==s.kind&&(e.sender.replaceTrack(s),e.direction="sendrecv")}else for(const e of t.getTracks())e.kind&&"audio"==e.kind&&(null===(h=this.peerConnection)||void 0===h||h.addTransceiver(e,{direction:"sendrecv"}));else m||null===(u=this.peerConnection)||void 0===u||u.addTransceiver("audio",{direction:"recvonly"})}else m||null===(l=this.peerConnection)||void 0===l||l.addTransceiver("audio",{direction:"recvonly"})}))}onVideoStats(e){}onSendWebRTCOffer(e){}onSendWebRTCAnswer(e){}showTextOverlayConnecting(){}showTextOverlaySetupFailure(){}parseAvailableCodecs(e){if(!RTCRtpReceiver.getCapabilities)return["Only available on Chrome"];const t=[],s=(0,Fe.splitSections)(e.sdp);return s.shift(),s.forEach((e=>{const{codecs:s}=(0,Fe.parseRtpParameters)(e),n=/(VP\d|H26\d|AV1).*/;s.forEach((e=>{const s=e.name+" "+Object.keys(e.parameters||{}).map((t=>t+"="+e.parameters[t])).join(";");if(null!==n.exec(s)){"VP9"==e.name&&(e.parameters={"profile-id":"0"});const s=e.name+" "+Object.keys(e.parameters||{}).map((t=>t+"="+e.parameters[t])).join(";");t.push(s)}}))})),t}}class _e{constructor(){this.PixelStreamingSettings=new Ve,this.EncoderSettings=new He,this.WebRTCSettings=new We}ueCompatible(){null!=this.WebRTCSettings.MaxFPS&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}}class Ve{}class He{}class We{}class Ne{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||(i.Log(i.GetStackTrace(),`Setting Encode Ms \n ${this.PostEncodeTimeMs} \n ${this.PreEncodeTimeMs}`,6),this.EncodeMs=this.PostEncodeTimeMs-this.PreEncodeTimeMs),null!=this.CaptureToSendMs||null==this.PreCaptureTimeMs&&null==this.PostCaptureTimeMs||(i.Log(i.GetStackTrace(),`Setting CaptureToSendMs Ms \n ${this.PostCaptureTimeMs} \n ${this.PreCaptureTimeMs}`,6),this.CaptureToSendMs=this.PostCaptureTimeMs-this.PreCaptureTimeMs)}}class Ke{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(),i.Log(i.GetStackTrace(),"Received first chunk of file",6));const s=new TextDecoder("utf-16").decode(e.slice(1));i.Log(i.GetStackTrace(),s,6),t.extension=s}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(),i.Log(i.GetStackTrace(),"Received first chunk of file",6));const s=new TextDecoder("utf-16").decode(e.slice(1));i.Log(i.GetStackTrace(),s,6),t.mimetype=s}static setContentsFromBytes(e,t){if(!t.receiving)return;t.chunks=Math.ceil(new DataView(e.slice(1,5).buffer).getInt32(0,!0)/16379);const s=e.slice(5);if(t.data.push(s),i.Log(i.GetStackTrace(),`Received file chunk: ${t.data.length}/${t.chunks}`,6),t.data.length===t.chunks){t.receiving=!1,t.valid=!0,i.Log(i.GetStackTrace(),"Received complete file",6);const e=(new Date).getTime()-t.timestampStart,s=Math.round(16384*t.chunks/e);i.Log(i.GetStackTrace(),`Average transfer bitrate: ${s}kb/s over ${e/1e3} seconds`,6);const n=new Blob(t.data,{type:t.mimetype}),r=document.createElement("a");r.setAttribute("href",URL.createObjectURL(n)),r.setAttribute("download",`transfer.${t.extension}`),document.body.append(r),r.remove()}else t.data.length>t.chunks&&(t.receiving=!1,i.Error(i.GetStackTrace(),`Received bigger file than advertised: ${t.data.length}/${t.chunks}`))}}class Qe{constructor(){this.mimetype="",this.extension="",