Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix stop request forward #126

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open

Fix stop request forward #126

wants to merge 15 commits into from

Conversation

USAMAWIZARD
Copy link

@USAMAWIZARD USAMAWIZARD commented Jan 30, 2025

Copy link

sonarqubecloud bot commented Feb 9, 2025

Copy link

sonarqubecloud bot commented Feb 9, 2025

Copy link
Contributor

@mekya mekya left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @USAMAWIZARD ,

Thank you for the implementation.

I think having integration test code is important for this case because it can be broken easily. An integration test will detect such cases.

Integration test code can be in the circle side because there is a cluster ready there and media-push is already deployed there.

It can be scheduled for next week

return result;
}

public Broadcast getBroadcast(String streamId) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to call getBroadcast through REST method. Just get it from dataStore

return ip.matches("^((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)$");
}

public boolean forwardMediaPushStopRequest(String streamId, String ip) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's a MUST to have integration test for this code. We may create another issue or increase the story point of this issue

(()=>{"use strict";var e={36:(e,t,i)=>{e.exports=i.p+"e4e4da7454e7cf2e6ffa.js"}},t={};function i(r){var a=t[r];if(void 0!==a)return a.exports;var n=t[r]={exports:{}};return e[r](n,n.exports,i),n.exports}i.m=e,i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e;i.g.importScripts&&(e=i.g.location+"");var t=i.g.document;if(!e&&t&&(t.currentScript&&(e=t.currentScript.src),!e)){var r=t.getElementsByTagName("script");if(r.length)for(var a=r.length-1;a>-1&&!e;)e=r[a--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),i.p=e})(),i.b=document.baseURI||self.location.href,(()=>{function e(e,t,i,r,a,n,o){try{var s=e[n](o),d=s.value}catch(e){return void i(e)}s.done?t(d):Promise.resolve(d).then(r,a)}function t(t){return function(){var i=this,r=arguments;return new Promise((function(a,n){var o=t.apply(i,r);function s(t){e(o,a,n,s,d,"next",t)}function d(t){e(o,a,n,s,d,"throw",t)}s(void 0)}))}}function r(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function a(e,t,i){if(!t.has(e))throw new TypeError("attempted to "+i+" private field on non-instance");return t.get(e)}function n(e,t,i){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return i}function o(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}window.log=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"];function a(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function n(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function o(t,i){for(var a=0;a<r.length;a++){var n=r[a];this[n]=a<t?e:this.methodFactory(n,t,i)}this.log=this.debug}function s(e,i,r){return function(){typeof console!==t&&(o.call(this,i,r),this[e].apply(this,arguments))}}function d(r,o,d){return function(r){return"debug"===r&&(r="log"),typeof console!==t&&("trace"===r&&i?n:void 0!==console[r]?a(console,r):void 0!==console.log?a(console,"log"):e)}(r)||s.apply(this,arguments)}function c(e,i,a){var n,s=this;i=null==i?"WARN":i;var c="loglevel";function l(){var e;if(typeof window!==t&&c){try{e=window.localStorage[c]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,r=i.indexOf(encodeURIComponent(c)+"=");-1!==r&&(e=/^([^;]+)/.exec(i.slice(r))[1])}catch(e){}return void 0===s.levels[e]&&(e=void 0),e}}"string"==typeof e?c+=":"+e:"symbol"==typeof e&&(c=void 0),s.name=e,s.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},s.methodFactory=a||d,s.getLevel=function(){return n},s.setLevel=function(i,a){if("string"==typeof i&&void 0!==s.levels[i.toUpperCase()]&&(i=s.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=s.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(n=i,!1!==a&&function(e){var i=(r[e]||"silent").toUpperCase();if(typeof window!==t&&c){try{return void(window.localStorage[c]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(c)+"="+i+";"}catch(e){}}}(i),o.call(s,i,e),typeof console===t&&i<s.levels.SILENT)return"No console available for logging"},s.setDefaultLevel=function(e){i=e,l()||s.setLevel(e,!1)},s.resetLevel=function(){s.setLevel(i,!1),function(){if(typeof window!==t&&c){try{return void window.localStorage.removeItem(c)}catch(e){}try{window.document.cookie=encodeURIComponent(c)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},s.enableAll=function(e){s.setLevel(s.levels.TRACE,e)},s.disableAll=function(e){s.setLevel(s.levels.SILENT,e)};var h=l();null==h&&(h=i),s.setLevel(h,!1)}var l=new c,h={};l.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=h[e];return t||(t=h[e]=new c(e,l.getLevel(),l.methodFactory)),t};var u=typeof window!==t?window.log:void 0;return l.noConflict=function(){return typeof window!==t&&window.log===l&&(window.log=u),l},l.getLoggers=function(){return h},l.default=l,l}();class s{constructor(e){this.streamId=e,this.totalBytesReceivedCount=0,this.totalBytesSent=0,this.videoPacketsLost=0,this.fractionLost=0,this.startTime=0,this.lastFramesEncoded=0,this.totalFramesEncodedCount=0,this.lastBytesReceived=0,this.lastBytesSent=0,this.totalVideoPacketsSent=0,this.totalAudioPacketsSent=0,this.currentTimestamp=0,this.lastTime=0,this.timerId=0,this.firstByteSentCount=0,this.firstBytesReceivedCount=0,this.audioLevel=-1,this.qualityLimitationReason="",this.resWidth=0,this.resHeight=0,this.srcFps=0,this.frameWidth=0,this.frameHeight=0,this.videoRoundTripTime=0,this.videoJitter=0,this.audioRoundTripTime=0,this.audioJitter=0,this.audioPacketsLost=0,this.framesReceived=0,this.framesDropped=0,this.framesDecoded=0,this.audioJitterAverageDelay=0,this.videoJitterAverageDelay=0,this.availableOutgoingBitrate=1/0}get averageOutgoingBitrate(){return Math.floor(8*(this.totalBytesSentCount-this.firstByteSentCount)/(this.currentTimestamp-this.startTime))}get currentFPS(){return((this.totalFramesEncodedCount-this.lastFramesEncoded)/(this.currentTimestamp-this.lastTime)*1e3).toFixed(1)}get averageIncomingBitrate(){return Math.floor(8*(this.totalBytesReceivedCount-this.firstBytesReceivedCount)/(this.currentTimestamp-this.startTime))}get currentOutgoingBitrate(){return Math.floor(8*(this.totalBytesSentCount-this.lastBytesSent)/(this.currentTimestamp-this.lastTime))}get currentIncomingBitrate(){return Math.floor(8*(this.totalBytesReceivedCount-this.lastBytesReceived)/(this.currentTimestamp-this.lastTime))}set currentTime(e){this.lastTime=this.currentTimestamp,this.currentTimestamp=e,0==this.startTime&&(this.startTime=e-1)}set totalBytesReceived(e){this.lastBytesReceived=this.totalBytesReceivedCount,this.totalBytesReceivedCount=e,0==this.firstBytesReceivedCount&&(this.firstBytesReceivedCount=e)}set totalBytesSent(e){this.lastBytesSent=this.totalBytesSentCount,this.totalBytesSentCount=e,0==this.firstByteSentCount&&(this.firstByteSentCount=e)}set totalFramesEncoded(e){this.lastFramesEncoded=this.totalFramesEncodedCount,this.totalFramesEncodedCount=e,0==this.lastFramesEncoded&&(this.lastFramesEncoded=e)}}var d=window.log;class c{constructor(e){for(var t in this.debug=!1,e)e.hasOwnProperty(t)&&(this[t]=e[t]);this.initWebSocketConnection()}initWebSocketConnection(e){this.connecting=!0,this.connected=!1,this.pingTimerId=-1;var t=new URL(this.websocket_url);["origin","edge"].includes(t.searchParams.get("target"))||(t.searchParams.set("target",this.webrtcadaptor.isPlayMode?"edge":"origin"),this.websocket_url=t.toString()),this.wsConn=new WebSocket(this.websocket_url),this.wsConn.onopen=()=>{this.debug&&d.debug("websocket connected"),this.pingTimerId=setInterval((()=>{this.sendPing()}),3e3),this.connected=!0,this.connecting=!1,this.callback("initialized"),void 0!==e&&e()},this.wsConn.onmessage=e=>{var t=JSON.parse(e.data);"start"==t.command?(this.debug&&d.debug("received start command"),this.webrtcadaptor.startPublishing(t.streamId)):"takeCandidate"==t.command?(this.debug&&(d.debug("received ice candidate for stream id "+t.streamId),d.debug(t.candidate)),this.webrtcadaptor.takeCandidate(t.streamId,t.label,t.candidate)):"takeConfiguration"==t.command?(this.debug&&d.debug("received remote description type for stream id: "+t.streamId+" type: "+t.type),this.webrtcadaptor.takeConfiguration(t.streamId,t.sdp,t.type,t.idMapping)):"stop"==t.command?(this.debug&&d.debug("Stop command received"),this.webrtcadaptor.closePeerConnection(t.streamId)):"error"==t.command?this.callbackError(t.definition,t):"notification"==t.command?this.callback(t.definition,t):"streamInformation"==t.command||"roomInformation"==t.command?this.callback(t.command,t):"pong"==t.command?this.callback(t.command):"trackList"==t.command?this.callback(t.command,t):"connectWithNewId"==t.command?(this.multiPeerStreamId=t.streamId,this.join(t.streamId)):"peerMessageCommand"==t.command&&this.callback(t.command,t)},this.wsConn.onerror=e=>{this.connecting=!1,this.connected=!1,d.info(" error occured: "+JSON.stringify(e)),this.clearPingTimer(),this.callbackError("WebSocketNotConnected",e)},this.wsConn.onclose=e=>{this.connecting=!1,this.connected=!1,this.debug&&d.debug("connection closed."),this.clearPingTimer(),this.callback("closed",e)}}clearPingTimer(){-1!=this.pingTimerId&&(this.debug&&d.debug("Clearing ping message timer"),clearInterval(this.pingTimerId),this.pingTimerId=-1)}sendPing(){this.wsConn.send(JSON.stringify({command:"ping"}))}close(){this.wsConn.close()}send(e){if(0!=this.connecting||0!=this.connected)try{this.wsConn.send(e),this.debug&&d.debug("sent message:"+e)}catch(t){d.warn("Cannot send message:"+e)}else this.initWebSocketConnection((()=>{this.send(e)}))}isConnected(){return this.connected}isConnecting(){return this.connecting}}var l=window.log;class h{constructor(e){this.context=e,this.instant=0,this.mic=null,this.volumeMeterNode=null}connectToSource(e,t,r){return this.context.audioWorklet.addModule(new URL(i(36),i.b)).then((()=>{this.mic=this.context.createMediaStreamSource(e),this.volumeMeterNode=new AudioWorkletNode(this.context,"volume-meter"),this.volumeMeterNode.port.onmessage=e=>{"debug"==e.data.type?l.debug(e.data.message):(this.instant=e.data,t(this.instant.toFixed(2)),l.debug("Audio level: "+this.instant.toFixed(2)))},this.mic.connect(this.volumeMeterNode)})).catch((e=>{throw void 0!==r&&r(e),l.error("Error in soundmeter: "+e),e}))}stop(){null!=this.volumeMeterNode&&(this.volumeMeterNode.port.postMessage("stop"),this.volumeMeterNode.disconnect(),this.volumeMeterNode.port.close(),this.volumeMeterNode=null),null!=this.mic&&(this.mic.disconnect(),this.mic=null)}}var u=window.log;class m{constructor(e){for(var t in this.bandwidth=1200,this.debug=!1,this.camera_location="top",this.camera_margin=15,this.camera_percent=15,this.mediaConstraints={video:!0,audio:!0},this.getSender=e.getSender,this.publishStreamId=null,this.localStream=null,this.publishMode="camera",this.callback=(e,t)=>{u.debug("Callback info: "+e+" object: "+typeof t!==void 0?JSON.stringify(t):0)},this.callbackError=e=>{u.error(e)},e.userParameters)e.userParameters.hasOwnProperty(t)&&(this[t]=e.userParameters[t]);this.currentVolume=null,this.previousAudioTrack=null,this.silentAudioTrack=null,this.desktopStream=null,this.smallVideoTrack=null,this.blackVideoTrack=null,this.audioContext=new AudioContext,this.oscillator=null,this.primaryAudioTrackGainNode=null,this.secondaryAudioTrackGainNode=null,this.localStreamSoundMeter=null,this.levelCallback=null,this.blackFrameTimer=null,this.desktopCameraCanvasDrawerTimer=null,this.mutedAudioStream=null,this.isMuted=!1,this.meterRefresh=null,this.cameraEnabled=!0,this.replacementStream=null,this.localVideo=this.localVideoElement||document.getElementById(this.localVideoId),this.dummyCanvas=document.createElement("canvas"),this.mediaConstraints?"camera"==this.mediaConstraints.video?this.publishMode="camera":"screen"==this.mediaConstraints.video?this.publishMode="screen":"screen+camera"==this.mediaConstraints.video&&(this.publishMode="screen+camera"):this.mediaConstraints={video:!0,audio:!0},this.checkBrowserScreenShareSupported()}initLocalStream(){if(this.checkWebRTCPermissions(),void 0!==this.mediaConstraints.video&&0!=this.mediaConstraints.video)return this.openStream(this.mediaConstraints);if(void 0!==this.mediaConstraints.audio&&0!=this.mediaConstraints.audio){var e={audio:this.mediaConstraints.audio};return this.navigatorUserMedia(e,(e=>this.gotStream(e)),!0)}return u.debug("no media requested, just return an empty stream"),new Promise(((e,t)=>{e(null)}))}checkWebRTCPermissions(){return"WebSocket"in window?void 0===navigator.mediaDevices?(u.debug("Cannot open camera and mic because of unsecure context. Please Install SSL(https)"),void this.callbackError("UnsecureContext")):void(void 0!==navigator.mediaDevices&&null!=navigator.mediaDevices&&null!=navigator.mediaDevices||this.callbackError("getUserMediaIsNotAllowed")):(u.debug("WebSocket not supported."),void this.callbackError("WebSocketNotSupported"))}getDevices(){return navigator.mediaDevices.enumerateDevices().then((e=>{var t=new Array,i=!1,r=!1;return e.forEach((e=>{"audioinput"!=e.kind&&"videoinput"!=e.kind||(t.push(e),"audioinput"==e.kind&&(i=!0),"videoinput"==e.kind&&(r=!0))})),this.callback("available_devices",t),0==i&&null==this.localStream&&(u.debug("Audio input not found"),u.debug("Retrying to get user media without audio"),this.inputDeviceNotFoundLimit<2?0!=r?(this.openStream({video:!0,audio:!1}),this.inputDeviceNotFoundLimit++):(u.debug("Video input not found"),alert("There is no video or audio input")):alert("No input device found, publish is not possible")),t})).catch((e=>{throw u.error("Cannot get devices -> error name: "+e.name+": "+e.message),e}))}trackDeviceChange(){navigator.mediaDevices.ondevicechange=()=>{this.getDevices()}}setDesktopwithCameraSource(e,t,i){return this.desktopStream=e,this.navigatorUserMedia({video:!0,audio:!1},(r=>{this.smallVideoTrack=r.getVideoTracks()[0];var a=document.createElement("canvas"),n=a.getContext("2d"),o=document.createElement("video");o.srcObject=e,o.play();var s=document.createElement("video");s.srcObject=r,s.play();var d=a.captureStream(15);null!=i&&(e.getVideoTracks()[0].onended=function(e){i(e)}),(null==this.localStream?this.gotStream(d):this.updateVideoTrack(d,t,onended,null)).then((()=>{this.desktopCameraCanvasDrawerTimer=setInterval((()=>{a.width=o.videoWidth,a.height=o.videoHeight,n.drawImage(o,0,0,a.width,a.height);var e,t=o.videoWidth*(this.camera_percent/100),i=s.videoHeight/s.videoWidth*t,r=a.width-t-this.camera_margin;e="top"==this.camera_location?this.camera_margin:a.height-i-this.camera_margin,n.drawImage(s,r,e,t,i)}),66)}))}),!0)}prepareStreamTracks(e,t,i,r){var a=i.getAudioTracks();if(a.length>0&&"camera"==this.publishMode&&(a[0].stop(),i.removeTrack(a[0])),"undefined"!=t&&0!=t){var n={audio:t};return this.navigatorUserMedia(n).then((n=>{n=this.setGainNodeStream(n);var o=t=>{this.callback("screen_share_stopped"),this.setVideoCameraSource(r,e,null,!0)};return"screen"==this.publishMode?this.updateVideoTrack(i,r,o,!0).then((()=>(a.length>0&&(n=this.mixAudioStreams(i,n)),this.updateAudioTrack(n,r,null)))):"screen+camera"==this.publishMode?(a.length>0&&(n=this.mixAudioStreams(i,n)),this.updateAudioTrack(n,r,null).then((()=>this.setDesktopwithCameraSource(i,r,o)))):(0!=t&&null!=t&&i.addTrack(n.getAudioTracks()[0]),i.getVideoTracks().length>0?this.updateVideoTrack(i,r,null,null).then((()=>this.updateAudioTrack(i,r,null).then((()=>this.gotStream(i))))):i.getAudioTracks().length>0?this.updateAudioTrack(i,r,null).then((()=>this.gotStream(i))):this.gotStream(i))})).catch((e=>{throw"NotFoundError"==e.name?this.getDevices():this.callbackError(e.name,e.message),e}))}return this.gotStream(i)}navigatorUserMedia(e,t,i){if("dummy"==e.video||"dummy"==e.audio){var r=new MediaStream;return"dummy"==e.audio&&r.addTrack(this.getSilentAudioTrack()),"dummy"==e.video&&r.addTrack(this.getBlackVideoTrack()),new Promise(((e,t)=>{e(r)}))}return navigator.mediaDevices.getUserMedia(e).then((e=>(void 0===t&&null==t||t(e),e))).catch((e=>{throw 1==i?"NotFoundError"==e.name?this.getDevices():this.callbackError(e.name,e.message):u.warn(e),e}))}navigatorDisplayMedia(e,t){return navigator.mediaDevices.getDisplayMedia(e).then((e=>(void 0!==t&&t(e),e))).catch((e=>{"NotAllowedError"===e.name&&(u.debug("Permission denied error"),this.callbackError("ScreenSharePermissionDenied"),null==this.localStream?this.openStream({video:!0,audio:!0}):this.switchVideoCameraCapture(streamId))}))}getMedia(e,t){var i=!1;return void 0!==e.audio&&0!=e.audio&&(i=e.audio),null!=this.desktopCameraCanvasDrawerTimer&&(clearInterval(this.desktopCameraCanvasDrawerTimer),this.desktopCameraCanvasDrawerTimer=null),"screen+camera"==this.publishMode||"screen"==this.publishMode?this.navigatorDisplayMedia(e).then((r=>(this.smallVideoTrack&&this.smallVideoTrack.stop(),this.prepareStreamTracks(e,i,r,t)))):this.navigatorUserMedia(e).then((r=>(this.smallVideoTrack&&this.smallVideoTrack.stop(),this.prepareStreamTracks(e,i,r,t)))).catch((e=>{"NotFoundError"==e.name?this.getDevices():this.callbackError(e.name,e.message)}))}openStream(e,t){return this.mediaConstraints=e,this.getMedia(e,t).then((()=>{"dummy"!=this.mediaConstraints.video&&null!=this.mediaConstraints.video&&(this.stopBlackVideoTrack(),this.clearBlackVideoTrackTimer()),"dummy"!=this.mediaConstraints.audio&&null!=this.mediaConstraints.audio&&this.stopSilentAudioTrack()}))}closeStream(){this.localStream&&(this.localStream.getVideoTracks().forEach((function(e){e.onended=null,e.stop()})),this.localStream.getAudioTracks().forEach((function(e){e.onended=null,e.stop()}))),this.videoTrack&&this.videoTrack.stop(),this.audioTrack&&this.audioTrack.stop(),this.smallVideoTrack&&this.smallVideoTrack.stop(),this.previousAudioTrack&&this.previousAudioTrack.stop()}checkBrowserScreenShareSupported(){(void 0!==navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia||navigator.getDisplayMedia)&&this.callback("browser_screen_share_supported")}enableSecondStreamInMixedAudio(e){null!=this.secondaryAudioTrackGainNode&&(this.secondaryAudioTrackGainNode.gain.value=e?1:0)}gotStream(e){return this.localStream=e,this.localVideo&&(this.localVideo.srcObject=e),this.getDevices(),this.trackDeviceChange(),new Promise(((e,t)=>{e()}))}changeLocalVideo(e){this.localVideo=e,this.localStream&&(this.localVideo.srcObject=this.localStream)}enableAudioLevelWhenMuted(){navigator.mediaDevices.getUserMedia({video:!1,audio:!0}).then((e=>{this.mutedAudioStream=e,this.mutedSoundMeter=new h(this.audioContext),soundMeter.connectToSource(this.mutedAudioStream,(e=>{e>.1&&this.callback("speaking_but_muted")}),(e=>{e?alert(e):this.meterRefresh=setInterval((()=>{soundMeter.instant.toFixed(2)>.1&&this.callback("speaking_but_muted")}),200)}))})).catch((function(e){u.debug("Can't get the soundlevel on mute")}))}disableAudioLevelWhenMuted(){null!=this.meterRefresh&&(clearInterval(this.meterRefresh),this.meterRefresh=null),null!=this.mutedSoundMeter&&(this.mutedSoundMeter.stop(),this.mutedSoundMeter=null),null!=this.mutedAudioStream&&this.mutedAudioStream.getTracks().forEach((function(e){e.stop()}))}mixAudioStreams(e,t){var i=new MediaStream;e.getVideoTracks().forEach((function(e){i.addTrack(e)}));var r=this.audioContext.createMediaStreamDestination();return e.getAudioTracks().length>0?(this.primaryAudioTrackGainNode=this.audioContext.createGain(),this.primaryAudioTrackGainNode.gain.value=1,this.audioContext.createMediaStreamSource(e).connect(this.primaryAudioTrackGainNode).connect(r)):u.debug("Origin stream does not have audio track"),t.getAudioTracks().length>0?(this.secondaryAudioTrackGainNode=this.audioContext.createGain(),this.secondaryAudioTrackGainNode.gain.value=1,this.audioContext.createMediaStreamSource(t).connect(this.secondaryAudioTrackGainNode).connect(r)):u.debug("Second stream does not have audio track"),r.stream.getAudioTracks().forEach((function(e){i.addTrack(e),u.debug("audio destination add track")})),i}setGainNodeStream(e){if(0!=this.mediaConstraints.audio&&void 0!==this.mediaConstraints.audio){var t=e.getVideoTracks(),i=e.getAudioTracks();this.audioContext=new AudioContext;var r=this.audioContext.createMediaStreamSource(e),a=this.audioContext.createMediaStreamDestination();this.primaryAudioTrackGainNode=this.audioContext.createGain(),r.connect(this.primaryAudioTrackGainNode),this.primaryAudioTrackGainNode.connect(a),null==this.currentVolume?this.primaryAudioTrackGainNode.gain.value=1:this.primaryAudioTrackGainNode.gain.value=this.currentVolume;var n=a.stream;for(var o of t)n.addTrack(o);for(var s of i)n.addTrack(s);return null!==this.previousAudioTrack&&this.previousAudioTrack.stop(),this.previousAudioTrack=n.getAudioTracks()[1],n}return e}switchDesktopCapture(e){return this.publishMode="screen",void 0!==this.mediaConstraints.video&&0!=this.mediaConstraints.video&&(this.mediaConstraints.video=!0),this.getMedia(this.mediaConstraints,e)}switchDesktopCaptureWithCamera(e){return void 0!==this.mediaConstraints.video&&0!=this.mediaConstraints.video&&(this.mediaConstraints.video=!0),this.publishMode="screen+camera",this.getMedia(this.mediaConstraints,e)}updateLocalAudioStream(e,t){var i=e.getAudioTracks()[0];if(null!=this.localStream&&null!=this.localStream.getAudioTracks()[0]){var r=this.localStream.getAudioTracks()[0];r!=i&&(this.localStream.removeTrack(r),r.stop(),this.localStream.addTrack(i))}else null!=this.localStream?this.localStream.addTrack(i):this.localStream=e;null!=this.localVideo&&(this.localVideo.srcObject=this.localStream),null!=t&&(e.getAudioTracks()[0].onended=function(e){t(e)}),this.isMuted?this.muteLocalMic():this.unmuteLocalMic(),null!=this.localStreamSoundMeter&&this.enableAudioLevelForLocalStream(this.levelCallback)}updateLocalVideoStream(e,t,i){i&&null!=this.desktopStream&&this.desktopStream.getVideoTracks()[0].stop();var r=e.getVideoTracks()[0];if(null!=this.localStream&&null!=this.localStream.getVideoTracks()[0]){var a=this.localStream.getVideoTracks()[0];a!=r&&(this.localStream.removeTrack(a),a.stop(),this.localStream.addTrack(r))}else null!=this.localStream?this.localStream.addTrack(r):this.localStream=e;this.localVideo&&(this.localVideo.srcObject=this.localStream),null!=t&&(e.getVideoTracks()[0].onended=function(e){t(e)})}switchAudioInputSource(e,t){var i=this.localStream.getAudioTracks()[0];if(i?i.stop():u.warn("There is no audio track in local stream"),void 0!==t){!0!==this.mediaConstraints.audio?this.mediaConstraints.audio.deviceId=t:this.mediaConstraints.audio={deviceId:t};var r={video:!1,audio:{deviceId:t}};return this.setAudioInputSource(e,r,null,t)}return new Promise(((e,t)=>{t("There is no device id for audio input source")}))}setAudioInputSource(e,t,i){return this.navigatorUserMedia(t,(r=>(r=this.setGainNodeStream(r),this.updateAudioTrack(r,e,t,i))),!0)}switchVideoCameraCapture(e,t,i){return this.localStream&&this.localStream.getVideoTracks().length>0?this.localStream.getVideoTracks()[0].stop():u.warn("There is no video track in local stream"),this.publishMode="camera",navigator.mediaDevices.enumerateDevices().then((i=>{for(var r=0;r<i.length;r++)if("videoinput"==i[r].kind&&i[r].deviceId==t){!0!==this.mediaConstraints.video?this.mediaConstraints.video.deviceId={exact:t}:this.mediaConstraints.video={deviceId:{exact:t}};break}return u.debug("Given deviceId = "+t+" - Media constraints video property = "+this.mediaConstraints.video),this.setVideoCameraSource(e,this.mediaConstraints,null,!0,t)}))}setVideoCameraSource(e,t,i,r){return this.navigatorUserMedia(t,(a=>(r&&this.secondaryAudioTrackGainNode&&a.getAudioTracks().length>0&&(this.secondaryAudioTrackGainNode=null,a=this.setGainNodeStream(a),this.updateAudioTrack(a,e,t,i)),this.cameraEnabled?this.updateVideoTrack(a,e,i,r):this.turnOffLocalCamera())),!0)}switchVideoCameraFacingMode(e,t){this.localStream&&this.localStream.getVideoTracks().length>0?this.localStream.getVideoTracks()[0].stop():u.warn("There is no video track in local stream"),void 0!==this.mediaConstraints.video&&void 0!==this.mediaConstraints.video.deviceId&&delete this.mediaConstraints.video.deviceId;var i={facingMode:t};return this.mediaConstraints.video=Object.assign({},this.mediaConstraints.video,i),this.publishMode="camera",u.debug("Media constraints video property = "+this.mediaConstraints.video),this.setVideoCameraSource(e,{video:this.mediaConstraints.video},null,!0)}updateAudioTrack(e,t,i){var r=this.getSender(t,"audio");return r?r.replaceTrack(e.getAudioTracks()[0]).then((t=>{this.updateLocalAudioStream(e,i)})).catch((function(e){throw u.debug(e.name),e})):(this.updateLocalAudioStream(e,i),new Promise(((e,t)=>{e()})))}updateVideoTrack(e,t,i,r){var a=this.getSender(t,"video");return a?a.replaceTrack(e.getVideoTracks()[0]).then((t=>{this.updateLocalVideoStream(e,i,r)})).catch((e=>{u.debug(e.name)})):(this.updateLocalVideoStream(e,i,r),new Promise(((e,t)=>{e()})))}getBlackVideoTrack(){return this.dummyCanvas.getContext("2d").fillRect(0,0,320,240),this.replacementStream=this.dummyCanvas.captureStream(),null==this.blackFrameTimer&&(this.blackFrameTimer=setInterval((()=>{this.getBlackVideoTrack()}),3e3)),this.blackVideoTrack=this.replacementStream.getVideoTracks()[0],this.blackVideoTrack}getSilentAudioTrack(){this.stopSilentAudioTrack(),this.oscillator=this.audioContext.createOscillator();var e=this.oscillator.connect(this.audioContext.createMediaStreamDestination());return this.oscillator.start(),this.silentAudioTrack=e.stream.getAudioTracks()[0],this.silentAudioTrack}stopSilentAudioTrack(){null!=this.oscillator&&(this.oscillator.stop(),this.oscillator.disconnect(),this.oscillator=null),null!=this.silentAudioTrack&&(this.silentAudioTrack.stop(),this.silentAudioTrack=null)}turnOffLocalCamera(e){var t;return this.getBlackVideoTrack(),null!=this.localStream?(t=null!=e||void 0!==e?e:this.publishStreamId,this.cameraEnabled=!1,this.updateVideoTrack(this.replacementStream,t,null,!0)):new Promise(((e,t)=>{this.callbackError("NoActiveConnection"),t("NoActiveStream")}))}clearBlackVideoTrackTimer(){null!=this.blackFrameTimer&&(clearInterval(this.blackFrameTimer),this.blackFrameTimer=null)}stopBlackVideoTrack(){null!=this.blackVideoTrack&&(this.blackVideoTrack.stop(),this.blackVideoTrack=null)}turnOnLocalCamera(e){return this.clearBlackVideoTrackTimer(),this.stopBlackVideoTrack(),null==this.localStream?this.navigatorUserMedia(this.mediaConstraints,(e=>{this.gotStream(e)}),!1):this.navigatorUserMedia(this.mediaConstraints,(t=>{var i;i=null!=e||void 0!==e?e:this.publishStreamId,this.cameraEnabled=!0,this.updateVideoTrack(t,i,null,!0)}),!1)}muteLocalMic(){this.isMuted=!0,null!=this.localStream?this.localStream.getAudioTracks().forEach((e=>e.enabled=!1)):this.callbackError("NoActiveConnection")}unmuteLocalMic(){this.isMuted=!1,null!=this.localStream?this.localStream.getAudioTracks().forEach((e=>e.enabled=!0)):this.callbackError("NoActiveConnection")}getVideoSender(e){var t=null;return"undefined"!=typeof adapter&&null!==adapter&&("chrome"===adapter.browserDetails.browser||"firefox"===adapter.browserDetails.browser||"safari"===adapter.browserDetails.browser&&adapter.browserDetails.version>=64)&&"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&(t=this.getSender(e,"video")),t}changeBandwidth(e,t){var i=this.getVideoSender(t);if(null!=i){var r=i.getParameters();return r.encodings||(r.encodings=[{}]),"unlimited"===e?delete r.encodings[0].maxBitrate:r.encodings[0].maxBitrate=1e3*e,i.setParameters(r)}return"Video sender not found to change bandwidth. Streaming may not be active",Promise.reject("Video sender not found to change bandwidth. Streaming may not be active")}setVolumeLevel(e){this.currentVolume=e,null!=this.primaryAudioTrackGainNode&&(this.primaryAudioTrackGainNode.gain.value=e),null!=this.secondaryAudioTrackGainNode&&(this.secondaryAudioTrackGainNode.gain.value=e)}enableAudioLevelForLocalStream(e){return this.levelCallback=e,this.disableAudioLevelForLocalStream(),this.localStreamSoundMeter=new h(this.audioContext),"running"!==this.audioContext.state?this.audioContext.resume().then((()=>this.localStreamSoundMeter.connectToSource(this.localStream,e))):this.localStreamSoundMeter.connectToSource(this.localStream,e)}disableAudioLevelForLocalStream(){null!=this.localStreamSoundMeter&&(this.localStreamSoundMeter.stop(),this.localStreamSoundMeter=null)}applyConstraints(e){var t={};void 0===e.audio&&void 0===e.video?(t.video=e,this.mediaConstraints.video=Object.assign({},this.mediaConstraints.video,t.video)):void 0!==e.video&&(t.video=e.video,this.mediaConstraints.video=Object.assign({},this.mediaConstraints.video,t.video)),void 0!==e.audio&&(t.audio=e.audio,this.mediaConstraints.audio=Object.assign({},this.mediaConstraints.audio,t.audio));var i=null;return void 0!==t.video&&(i=this.localStream&&this.localStream.getVideoTracks().length>0?this.localStream.getVideoTracks()[0].applyConstraints(this.mediaConstraints.video):new Promise(((e,t)=>{t("There is no video track to apply constraints")}))),void 0!==t.audio&&(i=this.setAudioInputSource(this.publishStreamId,{audio:this.mediaConstraints.audio},null)),null!=this.localStreamSoundMeter&&this.enableAudioLevelForLocalStream(this.levelCallback),i}}var p=window.log;class f{constructor(e){this.size=e,this.received=0,this.data=new ArrayBuffer(e)}}class g{static register(e){g.pluginInitMethods.push(e)}constructor(e){for(var t in this.peerconnection_config={iceServers:[{urls:"stun:stun1.l.google.com:19302"}],sdpSemantics:"unified-plan"},this.sdp_constraints={OfferToReceiveAudio:!1,OfferToReceiveVideo:!1},this.remotePeerConnection=new Array,this.remotePeerConnectionStats=new Array,this.remoteDescriptionSet=new Array,this.iceCandidateList=new Array,this.roomName=null,this.playStreamId=new Array,this.isMultiPeer=!1,this.multiPeerStreamId=null,this.webSocketAdaptor=null,this.isPlayMode=!1,this.debug=!1,this.publishStreamId=null,this.idMapping=new Array,this.onlyDataChannel=!1,this.dataChannelEnabled=!0,this.receivingMessages=new Map,this.candidateTypes=["udp","tcp"],this.callback=null,this.callbackError=null,this.reconnectIfRequiredFlag=!0,this.websocket_url=null,this.websocketURL=null,this.initializeComponents=!0,e)e.hasOwnProperty(t)&&(this[t]=e[t]);if(null==this.websocketURL&&(this.websocketURL=this.websocket_url),null==this.websocketURL)throw new Error("WebSocket URL is not defined. It's mandatory");this.remoteVideo=this.remoteVideoElement||document.getElementById(this.remoteVideoId),this.soundMeters=new Array,this.soundLevelList=new Array,this.eventListeners=new Array,this.errorEventListeners=new Array,this.publishToken=null,this.publishSubscriberId=null,this.publishSubscriberCode=null,this.publishStreamName=null,this.publishMainTrack=null,this.publishMetaData=null,this.playToken=null,this.playRoomId=null,this.playEnableTracks=null,this.playSubscriberId=null,this.playSubscriberCode=null,this.playMetaData=null,this.lastReconnectiontionTrialTime=0,this.mediaManager=new m({userParameters:e,webRTCAdaptor:this,callback:(e,t)=>{this.notifyEventListeners(e,t)},callbackError:(e,t)=>{this.notifyErrorEventListeners(e,t)},getSender:(e,t)=>this.getSender(e,t)}),this.initializeComponents&&this.initialize()}initPlugins(){g.pluginInitMethods.forEach((e=>{e(this)}))}addEventListener(e){this.eventListeners.push(e)}addErrorEventListener(e){this.errorEventListeners.push(e)}notifyEventListeners(e,t){this.eventListeners.forEach((i=>{i(e,t)})),null!=this.callback&&this.callback(e,t)}notifyErrorEventListeners(e,t){this.errorEventListeners.forEach((i=>{i(e,t)})),null!=this.callbackError&&this.callbackError(e,t)}initialize(){return this.isPlayMode||this.onlyDataChannel||null!=this.mediaManager.localStream?new Promise(((e,t)=>{this.initPlugins(),this.checkWebSocketConnection(),e("Wait 'initialized' callback from websocket")})):this.mediaManager.initLocalStream().then((()=>(this.initPlugins(),this.checkWebSocketConnection(),new Promise(((e,t)=>{e("Wait 'initialized' callback from websocket")}))))).catch((e=>{throw p.warn(e),e}))}publish(e,t,i,r,a,n,o){if(this.publishStreamId=e,this.mediaManager.publishStreamId=e,this.publishToken=t,this.publishSubscriberId=i,this.publishSubscriberCode=r,this.publishStreamName=a,this.publishMainTrack=n,this.publishMetaData=o,this.onlyDataChannel)this.sendPublishCommand(e,t,i,r,a,n,o,!1,!1);else if(null==this.mediaManager.localStream)this.mediaManager.initLocalStream().then((()=>{var s=!1,d=!1;null!=this.mediaManager.localStream&&(s=this.mediaManager.localStream.getVideoTracks().length>0,d=this.mediaManager.localStream.getAudioTracks().length>0),this.sendPublishCommand(e,t,i,r,a,n,o,s,d)})).catch((e=>{throw p.warn(e),e}));else{var s=this.mediaManager.localStream.getVideoTracks().length>0,d=this.mediaManager.localStream.getAudioTracks().length>0;this.sendPublishCommand(e,t,i,r,a,n,o,s,d)}this.initPeerConnection(e,"publish"),setTimeout((()=>{"checking"!=this.iceConnectionState(this.publishStreamId)&&"connected"!=this.iceConnectionState(this.publishStreamId)&&"completed"!=this.iceConnectionState(this.publishStreamId)&&this.reconnectIfRequired(0)}),5e3)}sendPublishCommand(e,t,i,r,a,n,o,s,d){var c={command:"publish",streamId:e,token:t,subscriberId:void 0!==typeof i&&null!=i?i:"",subscriberCode:void 0!==typeof r&&null!=r?r:"",streamName:void 0!==typeof a&&null!=a?a:"",mainTrack:void 0!==typeof n&&null!=n?n:"",video:s,audio:d,metaData:void 0!==typeof o&&null!=o?o:""};this.webSocketAdaptor.send(JSON.stringify(c))}joinRoom(e,t,i){this.roomName=e;var r={command:"joinRoom",room:e,streamId:t,mode:i};this.webSocketAdaptor.send(JSON.stringify(r))}play(e,t,i,r,a,n,o){this.playStreamId.push(e),this.playToken=t,this.playRoomId=i,this.playEnableTracks=r,this.playSubscriberId=a,this.playSubscriberCode=n,this.playMetaData=o;var s={command:"play",streamId:e,token:void 0!==typeof t&&null!=t?t:"",room:void 0!==typeof i&&null!=i?i:"",trackList:void 0!==typeof r&&null!=r?r:[],subscriberId:void 0!==typeof a&&null!=a?a:"",subscriberCode:void 0!==typeof n&&null!=a?n:"",viewerInfo:void 0!==typeof o&&null!=o?o:""};this.webSocketAdaptor.send(JSON.stringify(s)),this.initPeerConnection(e,"play"),setTimeout((()=>{"checking"!=this.iceConnectionState(e)&&"connected"!=this.iceConnectionState(e)&&"completed"!=this.iceConnectionState(e)&&this.reconnectIfRequired(0)}),5e3)}reconnectIfRequired(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3e3;this.reconnectIfRequiredFlag&&(e>0?setTimeout((()=>{this.tryAgain()}),e):this.tryAgain())}tryAgain(){var e=Date.now();if(!(e-this.lastReconnectiontionTrialTime<3e3))for(var t in this.lastReconnectiontionTrialTime=e,null!=this.remotePeerConnection[this.publishStreamId]&&"checking"!=this.iceConnectionState(this.publishStreamId)&&"connected"!=this.iceConnectionState(this.publishStreamId)&&"completed"!=this.iceConnectionState(this.publishStreamId)&&(this.notifyEventListeners("reconnection_attempt_for_publisher",this.publishStreamId),this.closePeerConnection(this.publishStreamId),p.log("It will try to publish again because it is not stopped on purpose"),this.publish(this.publishStreamId,this.publishToken,this.publishSubscriberId,this.publishSubscriberCode,this.publishStreamName,this.publishMainTrack,this.publishMetaData)),this.playStreamId){var i=this.playStreamId[t];"null"!=this.remotePeerConnection[i]&&"checking"!=this.iceConnectionState(i)&&"connected"!=this.iceConnectionState(i)&&"completed"!=this.iceConnectionState(i)&&(this.notifyEventListeners("reconnection_attempt_for_player",i),p.log("It will try to play again because it is not stopped on purpose"),this.closePeerConnection(i),this.play(i,this.playToken,this.playRoomId,this.playEnableTracks,this.playSubscriberId,this.playSubscriberCode,this.playMetaData))}}stop(e){if(this.closePeerConnection(e),null!=this.webSocketAdaptor&&this.webSocketAdaptor.isConnected()){var t={command:"stop",streamId:e};this.webSocketAdaptor.send(JSON.stringify(t))}}join(e){var t={command:"join",streamId:e,multiPeer:this.isMultiPeer&&null==this.multiPeerStreamId,mode:this.isPlayMode?"play":"both"};this.webSocketAdaptor.send(JSON.stringify(t))}onTrack(e,t){if(p.debug("onTrack for stream"),null!=this.remoteVideo)this.remoteVideo.srcObject!==e.streams[0]&&(this.remoteVideo.srcObject=e.streams[0],p.debug("Received remote stream"));else{var i={stream:e.streams[0],track:e.track,streamId:t,trackId:this.idMapping[t][e.transceiver.mid]};this.notifyEventListeners("newTrackAvailable",i),this.notifyEventListeners("newStreamAvailable",i)}}leaveFromRoom(e){for(var t in this.remotePeerConnection)this.closePeerConnection(t);this.roomName=e;var i={command:"leaveFromRoom",room:e};p.debug("leave request is sent for "+e),this.webSocketAdaptor.send(JSON.stringify(i))}leave(e){var t={command:"leave",streamId:this.isMultiPeer&&null!=this.multiPeerStreamId?this.multiPeerStreamId:e};this.webSocketAdaptor.send(JSON.stringify(t)),this.closePeerConnection(e),this.multiPeerStreamId=null}getStreamInfo(e){var t={command:"getStreamInfo",streamId:e};this.webSocketAdaptor.send(JSON.stringify(t))}requestVideoTrackAssignments(e){var t={command:"getVideoTrackAssignments",streamId:e};this.webSocketAdaptor.send(JSON.stringify(t))}getBroadcastObject(e){var t={command:"getBroadcastObject",streamId:e};this.webSocketAdaptor.send(JSON.stringify(t))}updateStreamMetaData(e,t){var i={command:"updateStreamMetaData",streamId:e,metaData:t};this.webSocketAdaptor.send(JSON.stringify(i))}getRoomInfo(e,t){var i={command:"getRoomInfo",streamId:t,room:e};this.webSocketAdaptor.send(JSON.stringify(i))}enableTrack(e,t,i){var r={command:"enableTrack",streamId:e,trackId:t,enabled:i};this.webSocketAdaptor.send(JSON.stringify(r))}getTracks(e,t){this.playStreamId.push(e);var i={command:"getTrackList",streamId:e,token:t};this.webSocketAdaptor.send(JSON.stringify(i))}iceCandidateReceived(e,t){if(e.candidate){var i=!1;if(""==e.candidate.candidate?i=!0:void 0===e.candidate.protocol?this.candidateTypes.forEach((t=>{e.candidate.candidate.toLowerCase().includes(t)&&(i=!0)})):i=this.candidateTypes.includes(e.candidate.protocol.toLowerCase()),i){var r={command:"takeCandidate",streamId:t,label:e.candidate.sdpMLineIndex,id:e.candidate.sdpMid,candidate:e.candidate.candidate};this.debug&&(p.debug("sending ice candiate for stream Id "+t),p.debug(JSON.stringify(e.candidate))),this.webSocketAdaptor.send(JSON.stringify(r))}else p.debug("Candidate's protocol(full sdp: "+e.candidate.candidate+") is not supported. Supported protocols: "+this.candidateTypes),""!=e.candidate.candidate&&this.notifyErrorEventListeners("protocol_not_supported","Support protocols: "+this.candidateTypes.toString()+" candidate: "+e.candidate.candidate)}else p.debug("No event.candidate in the iceCandidate event")}sanitizeHTML(e){return e.includes("script")?e.replace(/</g,"&lt;").replace(/>/g,"&gt;"):e}initDataChannel(e,t){t.onerror=i=>{p.debug("Data Channel Error:",i);var r={streamId:e,error:i};p.debug("channel status: ",t.readyState),"closed"!=t.readyState&&this.notifyErrorEventListeners("data_channel_error",r)},t.onmessage=t=>{var i={streamId:e,data:t.data},r=i.data;if("string"==typeof r||r instanceof String)i.data=this.sanitizeHTML(i.data),this.notifyEventListeners("data_received",i);else{var a=r.length||r.size||r.byteLength,n=new Int32Array(r,0,1)[0],o=this.receivingMessages[n];if(null==o){var s=new Int32Array(r,0,2)[1];return o=new f(s),this.receivingMessages[n]=o,void(a>8&&p.debug("something went wrong in msg receiving"))}var d=r.slice(4,a);new Uint8Array(o.data).set(new Uint8Array(d),o.received,a-4),o.received+=a-4,o.size==o.received&&(i.data=o.data,this.notifyEventListeners("data_received",i))}},t.onopen=()=>{this.remotePeerConnection[e].dataChannel=t,p.debug("Data channel is opened"),this.notifyEventListeners("data_channel_opened",e)},t.onclose=()=>{p.debug("Data channel is closed"),this.notifyEventListeners("data_channel_closed",e)}}initPeerConnection(e,t){if(null==this.remotePeerConnection[e]){var i=e;if(p.debug("stream id in init peer connection: "+e+" close stream id: "+i),this.remotePeerConnection[e]=new RTCPeerConnection(this.peerconnection_config),this.remoteDescriptionSet[e]=!1,this.iceCandidateList[e]=new Array,this.playStreamId.includes(e)||null!=this.mediaManager.localStream&&this.mediaManager.localStream.getTracks().forEach((t=>this.remotePeerConnection[e].addTrack(t,this.mediaManager.localStream))),this.remotePeerConnection[e].onicecandidate=e=>{this.iceCandidateReceived(e,i)},this.remotePeerConnection[e].ontrack=e=>{this.onTrack(e,i)},this.remotePeerConnection[e].onnegotiationneeded=e=>{p.debug("onnegotiationneeded")},this.dataChannelEnabled)if("publish"==t)if(this.remotePeerConnection[e].createDataChannel){var r=this.remotePeerConnection[e].createDataChannel(e,{ordered:!0});this.initDataChannel(e,r)}else p.warn("CreateDataChannel is not supported");else if("play"==t)this.remotePeerConnection[e].ondatachannel=t=>{this.initDataChannel(e,t.channel)};else if(this.remotePeerConnection[e].createDataChannel){var a=this.remotePeerConnection[e].createDataChannel(e,{ordered:!0});this.initDataChannel(e,a),this.remotePeerConnection[e].ondatachannel=t=>{this.initDataChannel(e,t.channel)}}else p.warn("CreateDataChannel is not supported");this.remotePeerConnection[e].oniceconnectionstatechange=t=>{var i={state:this.remotePeerConnection[e].iceConnectionState,streamId:e};"failed"!=i.state&&"disconnected"!=i.state&&"closed"!=i.state||this.reconnectIfRequired(3e3),this.notifyEventListeners("ice_connection_state_changed",i),this.isPlayMode||this.playStreamId.includes(e)||"connected"==this.remotePeerConnection[e].iceConnectionState&&this.mediaManager.changeBandwidth(this.mediaManager.bandwidth,e).then((()=>{p.debug("Bandwidth is changed to "+this.mediaManager.bandwidth)})).catch((e=>p.warn(e)))}}}closePeerConnection(e){var t=this.remotePeerConnection[e];if(null!=t){this.remotePeerConnection[e]=null,delete this.remotePeerConnection[e],null!=t.dataChannel&&t.dataChannel.close(),"closed"!=t.signalingState&&t.close();var i=this.playStreamId.indexOf(e);-1!=i&&this.playStreamId.splice(i,1)}null!=this.remotePeerConnectionStats[e]&&(clearInterval(this.remotePeerConnectionStats[e].timerId),delete this.remotePeerConnectionStats[e]),null!=this.soundMeters[e]&&delete this.soundMeters[e]}signallingState(e){return null!=this.remotePeerConnection[e]?this.remotePeerConnection[e].signalingState:null}iceConnectionState(e){return null!=this.remotePeerConnection[e]?this.remotePeerConnection[e].iceConnectionState:null}gotDescription(e,t){this.remotePeerConnection[t].setLocalDescription(e).then((i=>{p.debug("Set local description successfully for stream Id "+t);var r={command:"takeConfiguration",streamId:t,type:e.type,sdp:e.sdp};p.debug("setLocalDescription:"+e.sdp),this.webSocketAdaptor.send(JSON.stringify(r))})).catch((e=>{p.error("Cannot set local description. Error is: "+e)}))}takeConfiguration(e,t,i,r){var a=e,n=i,o=t,s="offer"==n,d="publish";s&&(d="play"),this.idMapping[a]=r,this.initPeerConnection(a,d),p.debug("setRemoteDescription:"+o),this.remotePeerConnection[a].setRemoteDescription(new RTCSessionDescription({sdp:o,type:n})).then((e=>{this.debug&&(p.debug("set remote description is succesfull with response: "+e+" for stream : "+a+" and type: "+n),p.debug(o)),this.remoteDescriptionSet[a]=!0;var t=this.iceCandidateList[a].length;p.debug("Ice candidate list size to be added: "+t);for(var i=0;i<t;i++)this.addIceCandidate(a,this.iceCandidateList[a][i]);this.iceCandidateList[a]=[],s&&(p.debug("try to create answer for stream id: "+a),this.remotePeerConnection[a].createAnswer(this.sdp_constraints).then((e=>{p.debug("created answer for stream id: "+a),e.sdp=e.sdp.replace("useinbandfec=1","useinbandfec=1; stereo=1"),this.gotDescription(e,a)})).catch((e=>{p.error("create answer error :"+e)})))})).catch((e=>{this.debug&&p.error("set remote description is failed with error: "+e),(e.toString().indexOf("InvalidAccessError")>-1||e.toString().indexOf("setRemoteDescription")>-1)&&this.notifyErrorEventListeners("notSetRemoteDescription")}))}takeCandidate(e,t,i){var r=e,a=i,n=new RTCIceCandidate({sdpMLineIndex:t,candidate:a});this.initPeerConnection(r,"peer"),p.debug("takeCandidate:"+a),1==this.remoteDescriptionSet[r]?this.addIceCandidate(r,n):(p.debug("Ice candidate is added to list because remote description is not set yet"),this.iceCandidateList[r].push(n))}addIceCandidate(e,t){var i=!1;""==t.candidate?i=!0:void 0===t.protocol?this.candidateTypes.forEach((e=>{t.candidate.toLowerCase().includes(e)&&(i=!0)})):i=this.candidateTypes.includes(t.protocol.toLowerCase()),i?this.remotePeerConnection[e].addIceCandidate(t).then((t=>{this.debug&&p.debug("Candidate is added for stream "+e)})).catch((i=>{p.error("ice candiate cannot be added for stream id: "+e+" error is: "+i),p.error(t)})):this.debug&&p.debug("Candidate's protocol("+t.protocol+") is not supported.Candidate: "+t.candidate+" Supported protocols:"+this.candidateTypes)}startPublishing(e){var t=e;this.initPeerConnection(t,"publish"),this.remotePeerConnection[t].createOffer(this.sdp_constraints).then((e=>{this.gotDescription(e,t)})).catch((e=>{p.error("create offer error for stream id: "+t+" error: "+e)}))}toggleVideo(e,t,i){var r={command:"toggleVideo",streamId:e,trackId:t,enabled:i};this.webSocketAdaptor.send(JSON.stringify(r))}toggleAudio(e,t,i){var r={command:"toggleAudio",streamId:e,trackId:t,enabled:i};this.webSocketAdaptor.send(JSON.stringify(r))}getStats(e){return p.debug("peerstatsgetstats = "+this.remotePeerConnectionStats[e]),new Promise(((t,i)=>{this.remotePeerConnection[e].getStats(null).then((i=>{var r=-1,a=-1,n=-1,o=-1,s=-1,d=-1,c=-1,l=-1,h=-1,u="",m=-1,p=-1,f=-1,g=-1,v=-1,y=-1,b=-1,S=-1,w=-1,C=-1,k=-1,T=-1,A=-1,E=-1,P=-1,I=1/0;i.forEach((e=>{"inbound-rtp"==e.type&&void 0!==e.kind?(r+=e.bytesReceived,"audio"==e.kind?n=e.packetsLost:"video"==e.kind&&(a=e.packetsLost),o+=e.fractionLost,s=e.timestamp):"outbound-rtp"==e.type?("audio"==e.kind?l=e.packetsSent:"video"==e.kind&&(c=e.packetsSent),d+=e.bytesSent,s=e.timestamp,u=e.qualityLimitationReason,null!=e.framesEncoded&&(m+=e.framesEncoded)):"track"==e.type&&void 0!==e.kind&&"audio"==e.kind?(void 0!==e.audioLevel&&(h=e.audioLevel),void 0!==e.jitterBufferDelay&&void 0!==e.jitterBufferEmittedCount&&(E=e.jitterBufferDelay/e.jitterBufferEmittedCount)):"track"==e.type&&void 0!==e.kind&&"video"==e.kind?(void 0!==e.frameWidth&&(v=e.frameWidth),void 0!==e.frameHeight&&(y=e.frameHeight),void 0!==e.framesDecoded&&(k=e.framesDecoded),void 0!==e.framesDropped&&(T=e.framesDropped),void 0!==e.framesReceived&&(A=e.framesReceived),void 0!==e.jitterBufferDelay&&void 0!==e.jitterBufferEmittedCount&&(P=e.jitterBufferDelay/e.jitterBufferEmittedCount)):"remote-inbound-rtp"==e.type&&void 0!==e.kind?(void 0!==e.packetsLost&&("video"==e.kind?a=e.packetsLost:"audio"==e.kind&&(n=e.packetsLost)),void 0!==e.roundTripTime&&("video"==e.kind?b=e.roundTripTime:"audio"==e.kind&&(w=e.roundTripTime)),void 0!==e.jitter&&("video"==e.kind?S=e.jitter:"audio"==e.kind&&(C=e.jitter))):"media-source"==e.type?"video"==e.kind&&(p=e.width,f=e.height,g=e.framesPerSecond):"candidate-pair"==e.type&&"succeeded"==e.state&&null!=e.availableOutgoingBitrate&&(I=e.availableOutgoingBitrate/1e3)})),this.remotePeerConnectionStats[e].totalBytesReceived=r,this.remotePeerConnectionStats[e].videoPacketsLost=a,this.remotePeerConnectionStats[e].audioPacketsLost=n,this.remotePeerConnectionStats[e].fractionLost=o,this.remotePeerConnectionStats[e].currentTime=s,this.remotePeerConnectionStats[e].totalBytesSent=d,this.remotePeerConnectionStats[e].totalVideoPacketsSent=c,this.remotePeerConnectionStats[e].totalAudioPacketsSent=l,this.remotePeerConnectionStats[e].audioLevel=h,this.remotePeerConnectionStats[e].qualityLimitationReason=u,this.remotePeerConnectionStats[e].totalFramesEncoded=m,this.remotePeerConnectionStats[e].resWidth=p,this.remotePeerConnectionStats[e].resHeight=f,this.remotePeerConnectionStats[e].srcFps=g,this.remotePeerConnectionStats[e].frameWidth=v,this.remotePeerConnectionStats[e].frameHeight=y,this.remotePeerConnectionStats[e].videoRoundTripTime=b,this.remotePeerConnectionStats[e].videoJitter=S,this.remotePeerConnectionStats[e].audioRoundTripTime=w,this.remotePeerConnectionStats[e].audioJitter=C,this.remotePeerConnectionStats[e].framesDecoded=k,this.remotePeerConnectionStats[e].framesDropped=T,this.remotePeerConnectionStats[e].framesReceived=A,this.remotePeerConnectionStats[e].videoJitterAverageDelay=P,this.remotePeerConnectionStats[e].audioJitterAverageDelay=E,this.remotePeerConnectionStats[e].availableOutgoingBitrate=I,this.notifyEventListeners("updated_stats",this.remotePeerConnectionStats[e]),t(!0)})).catch((e=>{t(!1)}))}))}enableStats(e){null==this.remotePeerConnectionStats[e]&&(this.remotePeerConnectionStats[e]=new s(e),this.remotePeerConnectionStats[e].timerId=setInterval((()=>{this.getStats(e)}),5e3))}disableStats(e){null==this.remotePeerConnectionStats[e]&&void 0===this.remotePeerConnectionStats[e]||clearInterval(this.remotePeerConnectionStats[e].timerId)}checkWebSocketConnection(){(null==this.webSocketAdaptor||0==this.webSocketAdaptor.isConnected()&&0==this.webSocketAdaptor.isConnecting())&&(p.debug("websocket url : "+this.websocketURL),this.webSocketAdaptor=new c({websocket_url:this.websocketURL,webrtcadaptor:this,callback:(e,t)=>{"closed"==e&&this.reconnectIfRequired(),this.notifyEventListeners(e,t)},callbackError:(e,t)=>{this.notifyErrorEventListeners(e,t)},debug:this.debug}))}closeWebSocket(){for(var e in this.remotePeerConnection)this.closePeerConnection(e);this.remotePeerConnection=new Array,this.webSocketAdaptor.close()}peerMessage(e,t,i){var r={command:"peerMessageCommand",streamId:e,definition:t,data:i};this.webSocketAdaptor.send(JSON.stringify(r))}forceStreamQuality(e,t){var i={command:"forceStreamQuality",streamId:e,streamHeight:t};this.webSocketAdaptor.send(JSON.stringify(i))}sendData(e,t){if(void 0!==this.remotePeerConnection[e]){var i=this.remotePeerConnection[e].dataChannel;if(null==i||void 0===i)return void p.warn("dataChannel is null or undefined");if("open"!==i.readyState)return void p.warn("dataChannel.readyState is not open: "+i.readyState);var r=t.length||t.size||t.byteLength,a=0;if("string"==typeof t||t instanceof String)i.send(t);else{var n=Math.floor(999999*Math.random()),o=new Int32Array(2);for(o[0]=n,o[1]=r,i.send(o),a=0;a<r;){var s=Math.min(r-a,16e3),d=new Uint8Array(s+4),c=new Int32Array(1);c[0]=n,d.set(new Uint8Array(c.buffer,0,4),0);var l=t.slice(a,a+s);d.set(new Uint8Array(l),4),a+=s,i.send(d)}}}else p.warn("Send data is called for undefined peer connection with stream id: "+e)}enableAudioLevel(e,t){var i=new h(this.mediaManager.audioContext);i.connectToSource(e,(()=>{}),(function(e){e?alert(e):p.debug("Added sound meter for stream: "+t+" = "+i.instant.toFixed(2))})),this.soundMeters[t]=i}getSoundLevelList(e){for(var t=0;t<e.length;t++)this.soundLevelList[e[t]]=this.soundMeters[e[t]].instant.toFixed(2);this.notifyEventListeners("gotSoundList",this.soundLevelList)}getSender(e,t){var i=null;return null!=this.remotePeerConnection[e]&&(i=this.remotePeerConnection[e].getSenders().find((function(e){return e.track.kind==t}))),i}assignVideoTrack(e,t,i){var r={command:"assignVideoTrackCommand",streamId:t,videoTrackId:e,enabled:i};this.webSocketAdaptor.send(JSON.stringify(r))}updateVideoTrackAssignments(e,t,i){var r={streamId:e,command:"updateVideoTrackAssignmentsCommand",offset:t,size:i};this.webSocketAdaptor.send(JSON.stringify(r))}setMaxVideoTrackCount(e,t){var i={streamId:e,command:"setMaxVideoTrackCountCommand",maxTrackCount:t};this.webSocketAdaptor.send(JSON.stringify(i))}updateAudioLevel(e,t){var i={streamId:e,eventType:"UPDATE_AUDIO_LEVEL",audioLevel:t};this.sendData(e,JSON.stringify(i))}getDebugInfo(e){var t={streamId:e,command:"getDebugInfo"};this.webSocketAdaptor.send(JSON.stringify(t))}turnOffLocalCamera(e){this.mediaManager.turnOffLocalCamera(e)}turnOnLocalCamera(e){return this.mediaManager.turnOnLocalCamera(e)}muteLocalMic(){this.mediaManager.muteLocalMic()}unmuteLocalMic(){this.mediaManager.unmuteLocalMic()}switchDesktopCapture(e){return this.mediaManager.switchDesktopCapture(e)}switchVideoCameraCapture(e,t){return this.mediaManager.switchVideoCameraCapture(e,t)}updateVideoTrack(e,t,i,r){return this.mediaManager.updateVideoTrack(e,t,i,r)}updateAudioTrack(e,t,i){return this.mediaManager.updateAudioTrack(e,t,i)}switchVideoCameraFacingMode(e,t){return this.mediaManager.switchVideoCameraFacingMode(e,t)}switchDesktopCaptureWithCamera(e){return this.mediaManager.switchDesktopCaptureWithCamera(e)}switchAudioInputSource(e,t){return this.mediaManager.switchAudioInputSource(e,t)}setVolumeLevel(e){this.mediaManager.setVolumeLevel(e)}enableAudioLevelForLocalStream(e,t){return this.mediaManager.enableAudioLevelForLocalStream(e)}disableAudioLevelForLocalStream(){this.mediaManager.disableAudioLevelForLocalStream()}applyConstraints(e){return this.mediaManager.applyConstraints(e)}changeBandwidth(e,t){this.mediaManager.changeBandwidth(e,t)}enableAudioLevelWhenMuted(){this.mediaManager.enableAudioLevelWhenMuted()}disableAudioLevelWhenMuted(){this.mediaManager.disableAudioLevelWhenMuted()}getVideoSender(e){return this.mediaManager.getVideoSender(e)}openStream(e,t){return this.mediaManager.openStream(e,t)}closeStream(){return this.mediaManager.closeStream()}}function v(e,t){void 0!==typeof t&&null!=t||(t=window.location.search);var i,r,a=decodeURIComponent(t.substring(1)).split("&");for(r=0;r<a.length;r++)if((i=a[r].split("="))[0]===e)return void 0===i[1]||i[1]}r(g,"pluginInitMethods",new Array),window.log,String.prototype.endsWith||(String.prototype.endsWith=function(e,t){var i=this.toString();("number"!=typeof t||!isFinite(t)||Math.floor(t)!==t||t>i.length)&&(t=i.length),t-=e.length;var r=i.lastIndexOf(e,t);return-1!==r&&r===t}),function(){function e(e){var t=0;return function(){return t<e.length?{done:!1,value:e[t++]}:{done:!0}}}var t,i="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,i){return e==Array.prototype||e==Object.prototype||(e[t]=i.value),e},r=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var t=0;t<e.length;++t){var i=e[t];if(i&&i.Math==Math)return i}throw Error("Cannot find global object")}(this);function a(e,t){if(t)e:{var a=r;e=e.split(".");for(var n=0;n<e.length-1;n++){var o=e[n];if(!(o in a))break e;a=a[o]}(t=t(n=a[e=e[e.length-1]]))!=n&&null!=t&&i(a,e,{configurable:!0,writable:!0,value:t})}}function n(e){return(e={next:e})[Symbol.iterator]=function(){return this},e}function o(t){var i="undefined"!=typeof Symbol&&Symbol.iterator&&t[Symbol.iterator];return i?i.call(t):{next:e(t)}}function s(e){if(!(e instanceof Array)){e=o(e);for(var t,i=[];!(t=e.next()).done;)i.push(t.value);e=i}return e}a("Symbol",(function(e){function t(e,t){this.g=e,i(this,"description",{configurable:!0,writable:!0,value:t})}if(e)return e;t.prototype.toString=function(){return this.g};var r="jscomp_symbol_"+(1e9*Math.random()>>>0)+"_",a=0;return function e(i){if(this instanceof e)throw TypeError("Symbol is not a constructor");return new t(r+(i||"")+"_"+a++,i)}})),a("Symbol.iterator",(function(t){if(t)return t;t=Symbol("Symbol.iterator");for(var a="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),o=0;o<a.length;o++){var s=r[a[o]];"function"==typeof s&&"function"!=typeof s.prototype[t]&&i(s.prototype,t,{configurable:!0,writable:!0,value:function(){return n(e(this))}})}return t}));var d,c,l="function"==typeof Object.create?Object.create:function(e){function t(){}return t.prototype=e,new t};if("function"==typeof Object.setPrototypeOf)c=Object.setPrototypeOf;else{e:{var h={};try{h.__proto__={a:!0},P=h.a;break e}catch(e){}P=!1}c=P?function(e,t){if(e.__proto__=t,e.__proto__!==t)throw TypeError(e+" is not extensible");return e}:null}var u=c;function m(e,t){if(e.prototype=l(t.prototype),e.prototype.constructor=e,u)u(e,t);else for(var i in t)if("prototype"!=i)if(Object.defineProperties){var r=Object.getOwnPropertyDescriptor(t,i);r&&Object.defineProperty(e,i,r)}else e[i]=t[i];e.ea=t.prototype}function p(){this.l=!1,this.i=null,this.h=void 0,this.g=1,this.s=this.m=0,this.j=null}function f(e){if(e.l)throw TypeError("Generator is already running");e.l=!0}function g(e,t){e.j={U:t,V:!0},e.g=e.m||e.s}function v(e,t,i){return e.g=i,{value:t}}function y(e){this.g=new p,this.h=e}function b(e,t,i,r){try{var a=t.call(e.g.i,i);if(!(a instanceof Object))throw TypeError("Iterator result "+a+" is not an object");if(!a.done)return e.g.l=!1,a;var n=a.value}catch(t){return e.g.i=null,g(e.g,t),S(e)}return e.g.i=null,r.call(e.g,n),S(e)}function S(e){for(;e.g.g;)try{var t=e.h(e.g);if(t)return e.g.l=!1,{value:t.value,done:!1}}catch(t){e.g.h=void 0,g(e.g,t)}if(e.g.l=!1,e.g.j){if(t=e.g.j,e.g.j=null,t.V)throw t.U;return{value:t.return,done:!0}}return{value:void 0,done:!0}}function w(e){this.next=function(t){return f(e.g),e.g.i?t=b(e,e.g.i.next,t,e.g.o):(e.g.o(t),t=S(e)),t},this.throw=function(t){return f(e.g),e.g.i?t=b(e,e.g.i.throw,t,e.g.o):(g(e.g,t),t=S(e)),t},this.return=function(t){var i,r,a;return r=t,f((i=e).g),(a=i.g.i)?b(i,"return"in a?a.return:function(e){return{value:e,done:!0}},r,i.g.return):(i.g.return(r),S(i))},this[Symbol.iterator]=function(){return this}}function C(e,t){return t=new w(new y(t)),u&&e.prototype&&u(t,e.prototype),t}p.prototype.o=function(e){this.h=e},p.prototype.return=function(e){this.j={return:e},this.g=this.s};var k="function"==typeof Object.assign?Object.assign:function(e,t){for(var i=1;i<arguments.length;i++){var r=arguments[i];if(r)for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(e[a]=r[a])}return e};a("Object.assign",(function(e){return e||k})),a("Promise",(function(e){function t(e){this.h=0,this.i=void 0,this.g=[],this.o=!1;var t=this.j();try{e(t.resolve,t.reject)}catch(e){t.reject(e)}}function i(){this.g=null}function a(e){return e instanceof t?e:new t((function(t){t(e)}))}if(e)return e;i.prototype.h=function(e){if(null==this.g){this.g=[];var t=this;this.i((function(){t.l()}))}this.g.push(e)};var n=r.setTimeout;i.prototype.i=function(e){n(e,0)},i.prototype.l=function(){for(;this.g&&this.g.length;){var e=this.g;this.g=[];for(var t=0;t<e.length;++t){var i=e[t];e[t]=null;try{i()}catch(e){this.j(e)}}}this.g=null},i.prototype.j=function(e){this.i((function(){throw e}))},t.prototype.j=function(){function e(e){return function(r){i||(i=!0,e.call(t,r))}}var t=this,i=!1;return{resolve:e(this.C),reject:e(this.l)}},t.prototype.C=function(e){if(e===this)this.l(TypeError("A Promise cannot resolve to itself"));else if(e instanceof t)this.F(e);else{e:switch(typeof e){case"object":var i=null!=e;break e;case"function":i=!0;break e;default:i=!1}i?this.u(e):this.m(e)}},t.prototype.u=function(e){var t=void 0;try{t=e.then}catch(e){return void this.l(e)}"function"==typeof t?this.G(t,e):this.m(e)},t.prototype.l=function(e){this.s(2,e)},t.prototype.m=function(e){this.s(1,e)},t.prototype.s=function(e,t){if(0!=this.h)throw Error("Cannot settle("+e+", "+t+"): Promise already settled in state"+this.h);this.h=e,this.i=t,2===this.h&&this.D(),this.A()},t.prototype.D=function(){var e=this;n((function(){if(e.B()){var t=r.console;void 0!==t&&t.error(e.i)}}),1)},t.prototype.B=function(){if(this.o)return!1;var e=r.CustomEvent,t=r.Event,i=r.dispatchEvent;return void 0===i||("function"==typeof e?e=new e("unhandledrejection",{cancelable:!0}):"function"==typeof t?e=new t("unhandledrejection",{cancelable:!0}):(e=r.document.createEvent("CustomEvent")).initCustomEvent("unhandledrejection",!1,!0,e),e.promise=this,e.reason=this.i,i(e))},t.prototype.A=function(){if(null!=this.g){for(var e=0;e<this.g.length;++e)s.h(this.g[e]);this.g=null}};var s=new i;return t.prototype.F=function(e){var t=this.j();e.J(t.resolve,t.reject)},t.prototype.G=function(e,t){var i=this.j();try{e.call(t,i.resolve,i.reject)}catch(e){i.reject(e)}},t.prototype.then=function(e,i){function r(e,t){return"function"==typeof e?function(t){try{a(e(t))}catch(e){n(e)}}:t}var a,n,o=new t((function(e,t){a=e,n=t}));return this.J(r(e,a),r(i,n)),o},t.prototype.catch=function(e){return this.then(void 0,e)},t.prototype.J=function(e,t){function i(){switch(r.h){case 1:e(r.i);break;case 2:t(r.i);break;default:throw Error("Unexpected state: "+r.h)}}var r=this;null==this.g?s.h(i):this.g.push(i),this.o=!0},t.resolve=a,t.reject=function(e){return new t((function(t,i){i(e)}))},t.race=function(e){return new t((function(t,i){for(var r=o(e),n=r.next();!n.done;n=r.next())a(n.value).J(t,i)}))},t.all=function(e){var i=o(e),r=i.next();return r.done?a([]):new t((function(e,t){function n(t){return function(i){o[t]=i,0==--s&&e(o)}}var o=[],s=0;do{o.push(void 0),s++,a(r.value).J(n(o.length-1),t),r=i.next()}while(!r.done)}))},t})),a("Object.is",(function(e){return e||function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}})),a("Array.prototype.includes",(function(e){return e||function(e,t){var i=this;i instanceof String&&(i=String(i));var r=i.length;for(0>(t=t||0)&&(t=Math.max(t+r,0));t<r;t++){var a=i[t];if(a===e||Object.is(a,e))return!0}return!1}})),a("String.prototype.includes",(function(e){return e||function(e,t){if(null==this)throw TypeError("The 'this' value for String.prototype.includes must not be null or undefined");if(e instanceof RegExp)throw TypeError("First argument to String.prototype.includes must not be a regular expression");return-1!==this.indexOf(e,t||0)}})),a("Array.prototype.keys",(function(e){return e||function(){var e,t,i,r,a;return t=function(e){return e},(e=this)instanceof String&&(e+=""),i=0,r=!1,(a={next:function(){if(!r&&i<e.length){var a=i++;return{value:t(a,e[a]),done:!1}}return r=!0,{done:!0,value:void 0}}})[Symbol.iterator]=function(){return a},a}}));var T=this||self;function A(e,t){e=e.split(".");var i,r=T;for((e[0]in r||void 0===r.execScript||r.execScript("var "+e[0]));e.length&&(i=e.shift());)e.length||void 0===t?r=r[i]&&r[i]!==Object.prototype[i]?r[i]:r[i]={}:r[i]=t}function E(e,t){return t=String.fromCharCode.apply(null,t),null==e?t:e+t}var P,I,L,R="undefined"!=typeof TextDecoder,M="undefined"!=typeof TextEncoder;function x(e){if(M)e=(L||(L=new TextEncoder)).encode(e);else{var t=void 0;t=void 0!==t&&t;for(var i=0,r=new Uint8Array(3*e.length),a=0;a<e.length;a++){var n=e.charCodeAt(a);if(128>n)r[i++]=n;else{if(2048>n)r[i++]=n>>6|192;else{if(55296<=n&&57343>=n){if(56319>=n&&a<e.length){var o=e.charCodeAt(++a);if(56320<=o&&57343>=o){n=1024*(n-55296)+o-56320+65536,r[i++]=n>>18|240,r[i++]=n>>12&63|128,r[i++]=n>>6&63|128,r[i++]=63&n|128;continue}a--}if(t)throw Error("Found an unpaired surrogate");n=65533}r[i++]=n>>12|224,r[i++]=n>>6&63|128}r[i++]=63&n|128}}e=r.subarray(0,i)}return e}var O={},_=null;function D(e,t){void 0===t&&(t=0),N(),t=O[t];for(var i=Array(Math.floor(e.length/3)),r=t[64]||"",a=0,n=0;a<e.length-2;a+=3){var o=e[a],s=e[a+1],d=e[a+2],c=t[o>>2];o=t[(3&o)<<4|s>>4],s=t[(15&s)<<2|d>>6],d=t[63&d],i[n++]=c+o+s+d}switch(c=0,d=r,e.length-a){case 2:d=t[(15&(c=e[a+1]))<<2]||r;case 1:e=e[a],i[n]=t[e>>2]+t[(3&e)<<4|c>>4]+d+r}return i.join("")}function N(){if(!_){_={};for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"],i=0;5>i;i++){var r=e.concat(t[i].split(""));O[i]=r;for(var a=0;a<r.length;a++){var n=r[a];void 0===_[n]&&(_[n]=a)}}}}var j,V="function"==typeof Uint8Array.prototype.slice;function F(e,t,i){return t===i?j||(j=new Uint8Array(0)):V?e.slice(t,i):new Uint8Array(e.subarray(t,i))}var B=0;function U(e,t){t=void 0!==(t=void 0===t?{}:t).v&&t.v,this.h=null,this.g=this.i=this.j=0,this.l=!1,this.v=t,e&&W(this,e)}function W(e,t){var i,r,a,n,o;t=t.constructor===Uint8Array?t:t.constructor===ArrayBuffer||t.constructor===Array?new Uint8Array(t):t.constructor===String?((a=3*(r=(i=t).length)/4)%3?a=Math.floor(a):-1!="=.".indexOf(i[r-1])&&(a=-1!="=.".indexOf(i[r-2])?a-2:a-1),n=new Uint8Array(a),o=0,function(e,t){function i(t){for(;r<e.length;){var i=e.charAt(r++),a=_[i];if(null!=a)return a;if(!/^[\s\xa0]*$/.test(i))throw Error("Unknown base64 encoding at char: "+i)}return t}N();for(var r=0;;){var a=i(-1),n=i(0),o=i(64),s=i(64);if(64===s&&-1===a)break;t(a<<2|n>>4),64!=o&&(t(n<<4&240|o>>2),64!=s&&t(o<<6&192|s))}}(i,(function(e){n[o++]=e})),n.subarray(0,o)):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(0),e.h=t,e.j=0,e.i=e.h.length,e.g=e.j}function G(e){var t=e.h,i=t[e.g],r=127&i;return 128>i?(e.g+=1,r):(r|=(127&(i=t[e.g+1]))<<7,128>i?(e.g+=2,r):(r|=(127&(i=t[e.g+2]))<<14,128>i?(e.g+=3,r):(r|=(127&(i=t[e.g+3]))<<21,128>i?(e.g+=4,r):(r|=(15&(i=t[e.g+4]))<<28,128>i?(e.g+=5,r>>>0):(e.g+=5,128<=t[e.g++]&&128<=t[e.g++]&&128<=t[e.g++]&&128<=t[e.g++]&&e.g++,r)))))}function J(e){var t=e.h[e.g],i=e.h[e.g+1],r=e.h[e.g+2],a=e.h[e.g+3];return e.g+=4,e=2*((i=(t<<0|i<<8|r<<16|a<<24)>>>0)>>31)+1,t=i>>>23&255,i&=8388607,255==t?i?NaN:1/0*e:0==t?1401298464324817e-60*e*i:e*Math.pow(2,t-150)*(i+8388608)}U.prototype.reset=function(){this.g=this.j};var H=[];function z(){this.g=new Uint8Array(64),this.h=0}function Y(e,t){for(;127<t;)e.push(127&t|128),t>>>=7;e.push(t)}function q(e){var t={},i=void 0!==t.N&&t.N;this.o={v:void 0!==t.v&&t.v},this.N=i,t=this.o,H.length?(i=H.pop(),t&&(i.v=t.v),e&&W(i,e),e=i):e=new U(e,t),this.g=e,this.m=this.g.g,this.h=this.i=this.l=-1,this.j=!1}function X(e){var t=e.g;if((t=t.g==t.i)||(t=e.j)||(t=(t=e.g).l||0>t.g||t.g>t.i),t)return!1;e.m=e.g.g;var i=7&(t=G(e.g));return 0!=i&&5!=i&&1!=i&&2!=i&&3!=i&&4!=i?(e.j=!0,!1):(e.i=t,e.l=t>>>3,e.h=i,!0)}function K(e,t,i){var r=e.g.i,a=G(e.g);return a=e.g.g+a,e.g.i=a,i(t,e),e.g.g=a,e.g.i=r,t}function Q(e){var t=G(e.g),i=(e=e.g).g;if(e.g+=t,e=e.h,R)(r=I)||(r=I=new TextDecoder("utf-8",{fatal:!1})),r=r.decode(e.subarray(i,i+t));else{t=i+t;for(var r,a,n,o,s=[],d=null;i<t;)128>(a=e[i++])?s.push(a):224>a?i>=t?s.push(65533):(n=e[i++],194>a||128!=(192&n)?(i--,s.push(65533)):s.push((31&a)<<6|63&n)):240>a?i>=t-1?s.push(65533):128!=(192&(n=e[i++]))||224===a&&160>n||237===a&&160<=n||128!=(192&(r=e[i++]))?(i--,s.push(65533)):s.push((15&a)<<12|(63&n)<<6|63&r):244>=a?i>=t-2?s.push(65533):128!=(192&(n=e[i++]))||0!=n-144+(a<<28)>>30||128!=(192&(r=e[i++]))||128!=(192&(o=e[i++]))?(i--,s.push(65533)):(a=(7&a)<<18|(63&n)<<12|(63&r)<<6|63&o,a-=65536,s.push(55296+(a>>10&1023),56320+(1023&a))):s.push(65533),8192<=s.length&&(d=E(d,s),s.length=0);r=E(d,s)}return r}function $(){this.h=[],this.i=0,this.g=new z}function Z(e,t){0!==t.length&&(e.h.push(t),e.i+=t.length)}function ee(e){var t=e.i+e.g.length();if(0===t)return new Uint8Array(0);t=new Uint8Array(t);for(var i=e.h,r=i.length,a=0,n=0;n<r;n++){var o=i[n];0!==o.length&&(t.set(o,a),a+=o.length)}return 0!==(r=(i=e.g).h)&&(t.set(i.g.subarray(0,r),a),i.h=0),e.h=[t],t}function te(e,t,i){if(null!=i){Y(e.g,8*t+5),e=e.g;var r=i;0===(r=(i=0>r?1:0)?-r:r)?B=0<1/r?0:2147483648:isNaN(r)?B=2147483647:34028234663852886e22<r?B=(i<<31|2139095040)>>>0:11754943508222875e-54>r?B=(i<<31|(r=Math.round(r/1401298464324817e-60)))>>>0:(t=Math.floor(Math.log(r)/Math.LN2),r*=Math.pow(2,-t),B=(i<<31|t+127<<23|(r=8388607&Math.round(8388608*r)))>>>0),i=B,e.push(i>>>0&255),e.push(i>>>8&255),e.push(i>>>16&255),e.push(i>>>24&255)}}z.prototype.push=function(e){if(!(this.h+1<this.g.length)){var t=this.g;this.g=new Uint8Array(Math.ceil(1+2*this.g.length)),this.g.set(t)}this.g[this.h++]=e},z.prototype.length=function(){return this.h},z.prototype.end=function(){var e=this.g,t=this.h;return this.h=0,F(e,0,t)},q.prototype.reset=function(){this.g.reset(),this.h=this.l=-1};var ie="function"==typeof Uint8Array;function re(e,t,i){if(null!=e)return"object"==typeof e?ie&&e instanceof Uint8Array?i(e):ae(e,t,i):t(e)}function ae(e,t,i){if(Array.isArray(e)){for(var r=Array(e.length),a=0;a<e.length;a++)r[a]=re(e[a],t,i);return Array.isArray(e)&&e.W&&se(r),r}for(a in r={},e)r[a]=re(e[a],t,i);return r}function ne(e){return"number"==typeof e?isFinite(e)?e:String(e):e}var oe={W:{value:!0,configurable:!0}};function se(e){return Array.isArray(e)&&!Object.isFrozen(e)&&Object.defineProperties(e,oe),e}function de(e,i,r){var a=t;if(t=null,e||(e=a),a=this.constructor.ca,e||(e=a?[a]:[]),this.j=a?0:-1,this.i=null,this.g=e,e=(a=this.g.length)-1,a&&null!==(a=this.g[e])&&"object"==typeof a&&a.constructor===Object?(this.l=e-this.j,this.h=a):void 0!==i&&-1<i?(this.l=Math.max(i,e+1-this.j),this.h=null):this.l=Number.MAX_VALUE,r)for(i=0;i<r.length;i++)(e=r[i])<this.l?(e+=this.j,(a=this.g[e])?se(a):this.g[e]=ce):(le(this),(a=this.h[e])?se(a):this.h[e]=ce)}var ce=Object.freeze(se([]));function le(e){var t=e.l+e.j;e.g[t]||(e.h=e.g[t]={})}function he(e,t,i){return-1===t?null:void 0!==i&&i||t>=e.l?e.h?e.h[t]:void 0:e.g[t+e.j]}function ue(e){var t=void 0!==t&&t,i=he(e,1,t);return null==i&&(i=ce),i===ce&&pe(e,1,i=se([]),t),i}function me(e,t,i){return null==(e=null==(e=he(e,t))?e:+e)?void 0===i?0:i:e}function pe(e,t,i,r){void 0!==r&&r||t>=e.l?(le(e),e.h[t]=i):e.g[t+e.j]=i}function fe(e,t){e.i||(e.i={});var i=e.i[1];if(!i){var r=ue(e);i=[];for(var a=0;a<r.length;a++)i[a]=new t(r[a]);e.i[1]=i}return i}function ge(e,t,i,r){var a=fe(e,i);t=t||new i,e=ue(e),null!=r?(a.splice(r,0,t),e.splice(r,0,ve(t))):(a.push(t),e.push(ve(t)))}function ve(e,t){if(e.i)for(var i in e.i){var r=e.i[i];if(Array.isArray(r))for(var a=0;a<r.length;a++)r[a]&&ve(r[a]);else r&&ve(r)}return e.g}function ye(e,t){return null==(e=he(e,t))?0:e}function be(e,t){return null==(e=he(e,t))?"":e}function Se(e,t){if(e=e.m){Z(t,t.g.end());for(var i=0;i<e.length;i++)Z(t,e[i])}}function we(e,t){if(4==t.h)return!1;var i=t.m;return function e(t){switch(t.h){case 0:if(0!=t.h)e(t);else{for(t=t.g;128&t.h[t.g];)t.g++;t.g++}break;case 1:1!=t.h?e(t):(t=t.g).g+=8;break;case 2:if(2!=t.h)e(t);else{var i=G(t.g);(t=t.g).g+=i}break;case 5:5!=t.h?e(t):(t=t.g).g+=4;break;case 3:for(i=t.l;;){if(!X(t)){t.j=!0;break}if(4==t.h){t.l!=i&&(t.j=!0);break}e(t)}break;default:t.j=!0}}(t),t.N||(t=F(t.g.h,i,t.g.g),(i=e.m)?i.push(t):e.m=[t]),!0}function Ce(e,t){var i=void 0;return new(i||(i=Promise))((function(r,a){function n(e){try{s(t.next(e))}catch(e){a(e)}}function o(e){try{s(t.throw(e))}catch(e){a(e)}}function s(e){e.done?r(e.value):new i((function(t){t(e.value)})).then(n,o)}s((t=t.apply(e,void 0)).next())}))}function ke(e){de.call(this,e)}function Te(e,t){for(;X(t);)switch(t.i){case 8:var i=G(t.g);pe(e,1,i);break;case 21:pe(e,2,i=J(t.g));break;case 26:pe(e,3,i=Q(t));break;case 34:pe(e,4,i=Q(t));break;default:if(!we(e,t))return e}return e}function Ae(e){de.call(this,e,-1,Ee)}de.prototype.toJSON=function(){return ae(ve(this),ne,D)},de.prototype.toString=function(){return ve(this).toString()},m(ke,de),m(Ae,de),Ae.prototype.addClassification=function(e,t){ge(this,e,ke,t)};var Ee=[1];function Pe(e){de.call(this,e)}function Ie(e,t){for(;X(t);)switch(t.i){case 13:var i=J(t.g);pe(e,1,i);break;case 21:pe(e,2,i=J(t.g));break;case 29:pe(e,3,i=J(t.g));break;case 37:pe(e,4,i=J(t.g));break;case 45:pe(e,5,i=J(t.g));break;default:if(!we(e,t))return e}return e}function Le(e){de.call(this,e,-1,Re)}m(Pe,de),m(Le,de);var Re=[1];function Me(e){de.call(this,e)}function xe(e,t,i){if(i=e.createShader(0===i?e.VERTEX_SHADER:e.FRAGMENT_SHADER),e.shaderSource(i,t),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS))throw Error("Could not compile WebGL shader.\n\n"+e.getShaderInfoLog(i));return i}function Oe(e){return fe(e,ke).map((function(e){return{index:ye(e,1),Y:me(e,2),label:null!=he(e,3)?be(e,3):void 0,displayName:null!=he(e,4)?be(e,4):void 0}}))}function _e(e){return{x:me(e,1),y:me(e,2),z:me(e,3),visibility:null!=he(e,4)?me(e,4):void 0}}function De(e,t){this.h=e,this.g=t,this.l=0}function Ne(e,t,i){return function(e,t){var i=e.g;if(void 0===e.m){var r=xe(i,"\n attribute vec2 aVertex;\n attribute vec2 aTex;\n varying vec2 vTex;\n void main(void) {\n gl_Position = vec4(aVertex, 0.0, 1.0);\n vTex = aTex;\n }",0),a=xe(i,"\n precision mediump float;\n varying vec2 vTex;\n uniform sampler2D sampler0;\n void main(){\n gl_FragColor = texture2D(sampler0, vTex);\n }",1),n=i.createProgram();if(i.attachShader(n,r),i.attachShader(n,a),i.linkProgram(n),!i.getProgramParameter(n,i.LINK_STATUS))throw Error("Could not compile WebGL program.\n\n"+i.getProgramInfoLog(n));r=e.m=n,i.useProgram(r),a=i.getUniformLocation(r,"sampler0"),e.j={I:i.getAttribLocation(r,"aVertex"),H:i.getAttribLocation(r,"aTex"),da:a},e.s=i.createBuffer(),i.bindBuffer(i.ARRAY_BUFFER,e.s),i.enableVertexAttribArray(e.j.I),i.vertexAttribPointer(e.j.I,2,i.FLOAT,!1,0,0),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),i.STATIC_DRAW),i.bindBuffer(i.ARRAY_BUFFER,null),e.o=i.createBuffer(),i.bindBuffer(i.ARRAY_BUFFER,e.o),i.enableVertexAttribArray(e.j.H),i.vertexAttribPointer(e.j.H,2,i.FLOAT,!1,0,0),i.bufferData(i.ARRAY_BUFFER,new Float32Array([0,1,0,0,1,0,1,1]),i.STATIC_DRAW),i.bindBuffer(i.ARRAY_BUFFER,null),i.uniform1i(a,0)}r=e.j,i.useProgram(e.m),i.canvas.width=t.width,i.canvas.height=t.height,i.viewport(0,0,t.width,t.height),i.activeTexture(i.TEXTURE0),e.h.bindTexture2d(t.glName),i.enableVertexAttribArray(r.I),i.bindBuffer(i.ARRAY_BUFFER,e.s),i.vertexAttribPointer(r.I,2,i.FLOAT,!1,0,0),i.enableVertexAttribArray(r.H),i.bindBuffer(i.ARRAY_BUFFER,e.o),i.vertexAttribPointer(r.H,2,i.FLOAT,!1,0,0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER?i.DRAW_FRAMEBUFFER:i.FRAMEBUFFER,null),i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT),i.colorMask(!0,!0,!0,!0),i.drawArrays(i.TRIANGLE_FAN,0,4),i.disableVertexAttribArray(r.I),i.disableVertexAttribArray(r.H),i.bindBuffer(i.ARRAY_BUFFER,null),e.h.bindTexture2d(0)}(e,t),"function"==typeof e.g.canvas.transferToImageBitmap?Promise.resolve(e.g.canvas.transferToImageBitmap()):i?Promise.resolve(e.g.canvas):"function"==typeof createImageBitmap?createImageBitmap(e.g.canvas):(void 0===e.i&&(e.i=document.createElement("canvas")),new Promise((function(t){e.i.height=e.g.canvas.height,e.i.width=e.g.canvas.width,e.i.getContext("2d",{}).drawImage(e.g.canvas,0,0,e.g.canvas.width,e.g.canvas.height),t(e.i)})))}function je(e){this.g=e}m(Me,de);var Ve=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,9,1,7,0,65,0,253,15,26,11]);function Fe(e,t){return t+e}function Be(e,t){window[e]=t}function Ue(e){if(this.g=e,this.listeners={},this.j={},this.F={},this.m={},this.s={},this.G=this.o=this.R=!0,this.C=Promise.resolve(),this.P="",this.B={},this.locateFile=e&&e.locateFile||Fe,"object"==typeof window)var t=window.location.pathname.toString().substring(0,window.location.pathname.toString().lastIndexOf("/"))+"/";else{if("undefined"==typeof location)throw Error("solutions can only be loaded on a web page or in a web worker");t=location.pathname.toString().substring(0,location.pathname.toString().lastIndexOf("/"))+"/"}if(this.S=t,e.options)for(var i=(t=o(Object.keys(e.options))).next();!i.done;i=t.next()){i=i.value;var r=e.options[i].default;void 0!==r&&(this.j[i]="function"==typeof r?r():r)}}function We(e,t){return Ce(e,(function e(){var i,r=this;return C(e,(function(e){return t in r.F?e.return(r.F[t]):(i=fetch(r.locateFile(t,"")).then((function(e){return e.arrayBuffer()})),r.F[t]=i,e.return(i))}))}))}function Ge(e,t){for(var i=t.name||"$",r=[].concat(s(t.wants)),a=new e.h.StringList,n=o(t.wants),d=n.next();!d.done;d=n.next())a.push_back(d.value);n=e.h.PacketListener.implement({onResults:function(a){for(var n={},s=0;s<t.wants.length;++s)n[r[s]]=a.get(s);var d,c,l,h=e.listeners[i];h&&(e.C=(d=e,c=n,l=t.outs,Ce(d,(function e(){var t,i,r,a,n,s,d,h,u,m,p,f,g,y=this;return C(e,(function(e){switch(e.g){case 1:if(!l)return e.return(c);for(t={},i=0,a=(r=o(Object.keys(l))).next();!a.done;a=r.next())"string"!=typeof(n=l[a.value])&&"texture"===n.type&&void 0!==c[n.stream]&&++i;1<i&&(y.G=!1),a=(s=o(Object.keys(l))).next();case 2:if(a.done){e.g=4;break}var b,S,w;if("string"==typeof(h=l[d=a.value]))return f=t,g=d,v(e,(b=y,S=d,w=c[h],Ce(b,(function e(){var t,i=this;return C(e,(function(e){return"number"==typeof w||w instanceof Uint8Array||w instanceof i.h.Uint8BlobList?e.return(w):w instanceof i.h.Texture2dDataOut?((t=i.s[S])||(t=new De(i.h,i.D),i.s[S]=t),e.return(Ne(t,w,i.G))):e.return(void 0)}))}))),14);if(u=c[h.stream],"detection_list"===h.type){if(u){for(var k=u.getRectList(),T=u.getLandmarksList(),A=u.getClassificationsList(),E=[],P=0;P<k.size();++P){var I=k.get(P);e:{var L=new Me;for(I=new q(I);X(I);)switch(I.i){case 13:var R=J(I.g);pe(L,1,R);break;case 21:pe(L,2,R=J(I.g));break;case 29:pe(L,3,R=J(I.g));break;case 37:pe(L,4,R=J(I.g));break;case 45:pe(L,5,R=J(I.g));break;case 48:for(var M=I.g,x=128,O=0,_=R=0;4>_&&128<=x;_++)O|=(127&(x=M.h[M.g++]))<<7*_;if(128<=x&&(O|=(127&(x=M.h[M.g++]))<<28,R|=(127&x)>>4),128<=x)for(_=0;5>_&&128<=x;_++)R|=(127&(x=M.h[M.g++]))<<7*_+3;128>x?(M=O>>>0,(R=2147483648&(x=R>>>0))&&(x=~x>>>0,0==(M=1+~M>>>0)&&(x=x+1>>>0)),M=4294967296*x+(M>>>0),R=R?-M:M):(M.l=!0,R=void 0),pe(L,6,R);break;default:if(!we(L,I))break e}}L={Z:me(L,1),$:me(L,2),height:me(L,3),width:me(L,4),rotation:me(L,5,0),X:ye(L,6)},R=T.get(P);e:for(I=new Le,R=new q(R);X(R);)if(10===R.i)ge(I,M=K(R,new Pe,Ie),Pe,void 0);else if(!we(I,R))break e;I=fe(I,Pe).map(_e),M=A.get(P);e:for(R=new Ae,M=new q(M);X(M);)if(10===M.i)R.addClassification(K(M,new ke,Te));else if(!we(R,M))break e;L={T:L,O:I,M:Oe(R)},E.push(L)}k=E}else k=[];t[d]=k,e.g=7;break}if("proto_list"===h.type){if(u){for(T=0,k=Array(u.size());T<u.size();T++)k[T]=u.get(T);u.delete()}else k=[];t[d]=k,e.g=7;break}if(void 0===u){e.g=3;break}if("float_list"===h.type||"proto"===h.type){t[d]=u,e.g=7;break}if("texture"!==h.type)throw Error("Unknown output config type: '"+h.type+"'");return(m=y.s[d])||(m=new De(y.h,y.D),y.s[d]=m),v(e,Ne(m,u,y.G),13);case 13:p=e.h,t[d]=p;case 7:h.transform&&t[d]&&(t[d]=h.transform(t[d])),e.g=3;break;case 14:f[g]=e.h;case 3:a=s.next(),e.g=2;break;case 4:return e.return(t)}}))}))).then((function(i){i=h(i);for(var a=0;a<t.wants.length;++a){var o=n[r[a]];"object"==typeof o&&o.hasOwnProperty&&o.hasOwnProperty("delete")&&o.delete()}i&&(e.C=i)})))}}),e.i.attachMultiListener(a,n),a.delete()}function Je(e){return void 0===e&&(e=0),1===e?"selfie_segmentation_landscape.tflite":"selfie_segmentation.tflite"}function He(e){var t=this;e=e||{},this.g=new Ue({locateFile:e.locateFile,files:function(e){return[{simd:!0,url:"selfie_segmentation_solution_simd_wasm_bin.js"},{simd:!1,url:"selfie_segmentation_solution_wasm_bin.js"},{data:!0,url:Je(e.modelSelection)}]},graph:{url:"selfie_segmentation.binarypb"},listeners:[{wants:["segmentation_mask","image_transformed"],outs:{image:{type:"texture",stream:"image_transformed"},segmentationMask:{type:"texture",stream:"segmentation_mask"}}}],inputs:{image:{type:"video",stream:"input_frames_gpu"}},options:{useCpuInference:{type:0,graphOptionXref:{calculatorType:"InferenceCalculator",fieldName:"use_cpu_inference"},default:"iPad Simulator;iPhone Simulator;iPod Simulator;iPad;iPhone;iPod".split(";").includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document},selfieMode:{type:0,graphOptionXref:{calculatorType:"GlScalerCalculator",calculatorIndex:1,fieldName:"flip_horizontal"}},modelSelection:{type:1,graphOptionXref:{calculatorType:"ConstantSidePacketCalculator",calculatorName:"ConstantSidePacketCalculatorModelSelection",fieldName:"int_value"},onChange:function(e){return Ce(t,(function t(){var i,r,a,n=this;return C(t,(function(t){return 1==t.g?(r="third_party/mediapipe/modules/selfie_segmentation/"+(i=Je(e)),v(t,We(n.g,i),2)):(a=t.h,n.g.overrideFile(r,a),t.return(!0))}))}))}}}})}(d=Ue.prototype).close=function(){return this.i&&this.i.delete(),Promise.resolve()},d.reset=function(){return Ce(this,(function e(){var t=this;return C(e,(function(e){t.i&&(t.i.reset(),t.m={},t.s={}),e.g=0}))}))},d.setOptions=function(e,t){var i=this;if(t=t||this.g.options){for(var r=[],a=[],n={},s=o(Object.keys(e)),d=s.next();!d.done;n={K:n.K,L:n.L},d=s.next()){var c=d.value;c in this.j&&this.j[c]===e[c]||(this.j[c]=e[c],void 0!==(d=t[c])&&(d.onChange&&(n.K=d.onChange,n.L=e[c],r.push(function(e){return function(){return Ce(i,(function t(){var i=this;return C(t,(function(t){if(1==t.g)return v(t,e.K(e.L),2);!0===t.h&&(i.o=!0),t.g=0}))}))}}(n))),d.graphOptionXref&&(c={valueNumber:1===d.type?e[c]:0,valueBoolean:0===d.type&&e[c],valueString:2===d.type?e[c]:""},d=Object.assign(Object.assign(Object.assign({},{calculatorName:"",calculatorIndex:0}),d.graphOptionXref),c),a.push(d))))}(0!==r.length||0!==a.length)&&(this.o=!0,this.A=(void 0===this.A?[]:this.A).concat(a),this.u=(void 0===this.u?[]:this.u).concat(r))}},d.initialize=function(){return Ce(this,(function e(){var t=this;return C(e,(function(e){return 1==e.g?v(e,Ce(t,(function e(){var t,i,r,a,n,o,d,c,l,h,u,m=this;return C(e,(function(e){switch(e.g){case 1:var p,f;return t=m,m.R?(p=m,f=m.j,i=void 0===p.g.files?[]:"function"==typeof p.g.files?p.g.files(f):p.g.files,v(e,function(){return Ce(this,(function e(){return C(e,(function(e){switch(e.g){case 1:return e.m=2,v(e,WebAssembly.instantiate(Ve),4);case 4:e.g=3,e.m=0;break;case 2:return e.m=0,e.j=null,e.return(!1);case 3:return e.return(!0)}}))}))}(),2)):e.return();case 2:if(r=e.h,"object"==typeof window)return Be("createMediapipeSolutionsWasm",{locateFile:m.locateFile}),Be("createMediapipeSolutionsPackedAssets",{locateFile:m.locateFile}),o=i.filter((function(e){return void 0!==e.data})),d=i.filter((function(e){return void 0===e.data})),c=Promise.all(o.map((function(e){var i=We(t,e.url);if(void 0!==e.path){var r=e.path;i=i.then((function(e){return t.overrideFile(r,e),Promise.resolve(e)}))}return i}))),l=Promise.all(d.map((function(e){var i,a;return void 0===e.simd||e.simd&&r||!e.simd&&!r?(i=t.locateFile(e.url,t.S),(a=document.createElement("script")).setAttribute("src",i),a.setAttribute("lang","text/javascript"),a.setAttribute("crossorigin","anonymous"),new Promise((function(e){a.addEventListener("load",(function(){e()}),!1),a.addEventListener("error",(function(){e()}),!1),document.body.appendChild(a)}))):Promise.resolve()}))).then((function(){return Ce(t,(function e(){var t=this;return C(e,(function(e){if(1==e.g)return v(e,window.createMediapipeSolutionsWasm(window.createMediapipeSolutionsPackedAssets),2);t.h=e.h,e.g=0}))}))})),h=Ce(t,(function e(){var t=this;return C(e,(function(e){return t.g.graph&&t.g.graph.url?e=v(e,We(t,t.g.graph.url),0):(e.g=0,e=void 0),e}))})),v(e,Promise.all([l,c,h]),7);if("function"!=typeof importScripts)throw Error("solutions can only be loaded on a web page or in a web worker");return a=i.filter((function(e){return void 0===e.simd||e.simd&&r||!e.simd&&!r})).map((function(e){return t.locateFile(e.url,t.S)})),importScripts.apply(null,s(a)),v(e,createMediapipeSolutionsWasm(Module),6);case 6:m.h=e.h,m.l=new OffscreenCanvas(1,1),m.h.canvas=m.l,n=m.h.GL.createContext(m.l,{antialias:!1,alpha:!1,ba:"undefined"!=typeof WebGL2RenderingContext?2:1}),m.h.GL.makeContextCurrent(n),e.g=4;break;case 7:if(m.l=document.createElement("canvas"),!(u=m.l.getContext("webgl2",{}))&&!(u=m.l.getContext("webgl",{})))return alert("Failed to create WebGL canvas context when passing video frame."),e.return();m.D=u,m.h.canvas=m.l,m.h.createContext(m.l,!0,!0,{});case 4:m.i=new m.h.SolutionWasm,m.R=!1,e.g=0}}))})),2):3!=e.g?v(e,Ce(t,(function e(){var t,i,r,a,n,s,d,c=this;return C(e,(function(e){if(1==e.g)return c.g.graph&&c.g.graph.url&&c.P===c.g.graph.url?e.return():(c.o=!0,c.g.graph&&c.g.graph.url?(c.P=c.g.graph.url,v(e,We(c,c.g.graph.url),3)):void(e.g=2));for(2!=e.g&&(t=e.h,c.i.loadGraph(t)),r=(i=o(Object.keys(c.B))).next();!r.done;r=i.next())a=r.value,c.i.overrideFile(a,c.B[a]);if(c.B={},c.g.listeners)for(s=(n=o(c.g.listeners)).next();!s.done;s=n.next())Ge(c,s.value);d=c.j,c.j={},c.setOptions(d),e.g=0}))})),3):v(e,Ce(t,(function e(){var t,i,r,a,n,s,d=this;return C(e,(function(e){switch(e.g){case 1:if(!d.o)return e.return();if(!d.u){e.g=2;break}i=(t=o(d.u)).next();case 3:if(i.done){e.g=5;break}return v(e,i.value(),4);case 4:i=t.next(),e.g=3;break;case 5:d.u=void 0;case 2:if(d.A){for(r=new d.h.GraphOptionChangeRequestList,n=(a=o(d.A)).next();!n.done;n=a.next())s=n.value,r.push_back(s);d.i.changeOptions(r),r.delete(),d.A=void 0}d.o=!1,e.g=0}}))})),0)}))}))},d.overrideFile=function(e,t){this.i?this.i.overrideFile(e,t):this.B[e]=t},d.clearOverriddenFiles=function(){this.B={},this.i&&this.i.clearOverriddenFiles()},d.send=function(e,t){return Ce(this,(function i(){var r,a,n,s,d,c,l,h,u,m=this;return C(i,(function(i){switch(i.g){case 1:return m.g.inputs?(r=1e3*(null==t?performance.now():t),v(i,m.C,2)):i.return();case 2:return v(i,m.initialize(),3);case 3:for(a=new m.h.PacketDataList,s=(n=o(Object.keys(e))).next();!s.done;s=n.next())if(d=s.value,c=m.g.inputs[d]){e:{var p=m,f=e[d];switch(c.type){case"video":var g=p.m[c.stream];if(g||(g=new De(p.h,p.D),p.m[c.stream]=g),0===(p=g).l&&(p.l=p.h.createTexture()),"undefined"!=typeof HTMLVideoElement&&f instanceof HTMLVideoElement){var y=f.videoWidth;g=f.videoHeight}else"undefined"!=typeof HTMLImageElement&&f instanceof HTMLImageElement?(y=f.naturalWidth,g=f.naturalHeight):(y=f.width,g=f.height);g={glName:p.l,width:y,height:g},(y=p.g).canvas.width=g.width,y.canvas.height=g.height,y.activeTexture(y.TEXTURE0),p.h.bindTexture2d(p.l),y.texImage2D(y.TEXTURE_2D,0,y.RGBA,y.RGBA,y.UNSIGNED_BYTE,f),p.h.bindTexture2d(0),p=g;break e;case"detections":for((g=p.m[c.stream])||(g=new je(p.h),p.m[c.stream]=g),(p=g).data||(p.data=new p.g.DetectionListData),p.data.reset(f.length),g=0;g<f.length;++g){y=f[g];var b=p.data,S=b.setBoundingBox,w=g,C=y.T,k=new Me;pe(k,1,C.Z),pe(k,2,C.$),pe(k,3,C.height),pe(k,4,C.width),pe(k,5,C.rotation),pe(k,6,C.X);var T=C=new $;te(T,1,he(k,1)),te(T,2,he(k,2)),te(T,3,he(k,3)),te(T,4,he(k,4)),te(T,5,he(k,5));var A=he(k,6);if(null!=A&&null!=A){Y(T.g,48);var E=T.g,P=A;A=0>P;var I=(P=Math.abs(P))>>>0;for(P=Math.floor((P-I)/4294967296),P>>>=0,A&&(P=~P>>>0,4294967295<(I=1+(~I>>>0))&&(I=0,4294967295<++P&&(P=0))),A=B=I,I=P;0<I||127<A;)E.push(127&A|128),A=(A>>>7|I<<25)>>>0,I>>>=7;E.push(A)}if(Se(k,T),C=ee(C),S.call(b,w,C),y.O)for(b=0;b<y.O.length;++b)T=!!(k=y.O[b]).visibility,w=(S=p.data).addNormalizedLandmark,C=g,k=Object.assign(Object.assign({},k),{visibility:T?k.visibility:0}),pe(T=new Pe,1,k.x),pe(T,2,k.y),pe(T,3,k.z),k.visibility&&pe(T,4,k.visibility),te(E=k=new $,1,he(T,1)),te(E,2,he(T,2)),te(E,3,he(T,3)),te(E,4,he(T,4)),te(E,5,he(T,5)),Se(T,E),k=ee(k),w.call(S,C,k);if(y.M)for(b=0;b<y.M.length;++b){if(w=(S=p.data).addClassification,C=g,k=y.M[b],pe(T=new ke,2,k.Y),k.index&&pe(T,1,k.index),k.label&&pe(T,3,k.label),k.displayName&&pe(T,4,k.displayName),E=k=new $,null!=(I=he(T,1))&&null!=I)if(Y(E.g,8),A=E.g,0<=I)Y(A,I);else{for(P=0;9>P;P++)A.push(127&I|128),I>>=7;A.push(1)}te(E,2,he(T,2)),null!=(A=he(T,3))&&(A=x(A),Y(E.g,26),Y(E.g,A.length),Z(E,E.g.end()),Z(E,A)),null!=(A=he(T,4))&&(A=x(A),Y(E.g,34),Y(E.g,A.length),Z(E,E.g.end()),Z(E,A)),Se(T,E),k=ee(k),w.call(S,C,k)}}p=p.data;break e;default:p={}}}switch(l=p,h=c.stream,c.type){case"video":a.pushTexture2d(Object.assign(Object.assign({},l),{stream:h,timestamp:r}));break;case"detections":(u=l).stream=h,u.timestamp=r,a.pushDetectionList(u);break;default:throw Error("Unknown input config type: '"+c.type+"'")}}return m.i.send(a),v(i,m.C,4);case 4:a.delete(),i.g=0}}))}))},d.onResults=function(e,t){this.listeners[t||"$"]=e},A("Solution",Ue),A("OptionType",{BOOL:0,NUMBER:1,aa:2,0:"BOOL",1:"NUMBER",2:"STRING"}),(d=He.prototype).close=function(){return this.g.close(),Promise.resolve()},d.onResults=function(e){this.g.onResults(e)},d.initialize=function(){return Ce(this,(function e(){var t=this;return C(e,(function(e){return v(e,t.g.initialize(),0)}))}))},d.reset=function(){this.g.reset()},d.send=function(e){return Ce(this,(function t(){var i=this;return C(t,(function(t){return v(t,i.g.send(e),0)}))}))},d.setOptions=function(e){this.g.setOptions(e)},A("SelfieSegmentation",He),A("VERSION","0.1.1632777926")}.call(void 0);var y=window.log,b=new WeakMap,S=new WeakSet;class w{constructor(e){var t;o(this,t=S),t.add(this),function(e,t,i){o(e,t),t.set(e,{writable:!0,value:null})}(this,b),this.webRTCAdaptor=e,this.selfieSegmentation=null,this.effectCanvas=null,this.ctx=null,this.rawLocalVideo=document.createElement("video"),this.deepAR=null,this.backgroundBlurRange=3,this.edgeBlurRange=4,this.effectName=w.NO_EFFECT,this.startTime=0,this.statTimerId=-1,this.renderedFrameCount=0,this.lastRenderedFrameCount=0,this.effectCanvasFPS=0,this.videoCallbackPeriodMs=0,this.initializeSelfieSegmentation(),this.isInitialized=!0}init(e){var i=this;return t((function*(){yield i.setRawLocalVideo(e);var t=e.getVideoTracks()[0].getSettings();return i.effectCanvasFPS=t.frameRate,i.videoCallbackPeriodMs=1e3/i.effectCanvasFPS,i.effectCanvas=i.createEffectCanvas(t.width,t.height),i.ctx=i.effectCanvas.getContext("2d"),i.canvasStream&&(i.canvasStream.getTracks().forEach((e=>e.stop())),i.canvasStream=null),i.canvasStream=i.effectCanvas.captureStream(i.effectCanvasFPS),new Promise(((e,t)=>{e(i.canvasStream)}))}))()}setRawLocalVideo(e){return this.rawLocalVideo.srcObject=e,this.rawLocalVideo.muted=!0,this.rawLocalVideo.autoplay=!0,this.rawLocalVideo.play()}createEffectCanvas(e,t){var i=document.createElement("canvas");return i.id="effectCanvas",i.width=e,i.height=t,i}initializeSelfieSegmentation(){this.selfieSegmentation=new SelfieSegmentation({locateFile:e=>w.LOCATE_FILE_URL+"/"+e}),this.selfieSegmentation.setOptions({selfieMode:!1,modelSelection:1}),this.selfieSegmentation.onResults((e=>{this.onResults(e)}))}set virtualBackgroundImage(e){var t,i;i=e,function(e,t,i){if(t.set)t.set.call(e,i);else{if(!t.writable)throw new TypeError("attempted to set read only private field");t.value=i}}(t=this,a(t,b,"set"),i)}startFpsCalculation(){this.statTimerId=setInterval((()=>{var e=(new Date).getTime(),t=(e-this.startTime)/1e3;this.startTime=e;var i=(this.renderedFrameCount-this.lastRenderedFrameCount)/t;this.renderedFrameCount=this.lastRenderedFrameCount,y.warn("Fps: "+i+"fps")}),1e3)}stopFpsCalculation(){-1!==this.statTimerId&&(clearInterval(this.statTimerId),this.statTimerId=-1)}processFrame(){var e=this;return t((function*(){yield e.selfieSegmentation.send({image:e.rawLocalVideo}),e.effectName!==w.NO_EFFECT&&setTimeout((()=>{e.processFrame()}),e.videoCallbackPeriodMs)}))()}enableEffect(e,i,r){var a=this;return t((function*(){if(a.isInitialized){switch(e){case w.DEEPAR:case w.VIRTUAL_BACKGROUND:case w.BLUR_BACKGROUND:case w.NO_EFFECT:break;default:return void y.warn("Unknown effect name please use the constants VideoEffect.VIRTUAL_BACKGROUND,VideoEffect.BLUR_BACKGROUND or VideoEffect.NO_EFFECT ")}var t=a.effectName;if(a.effectName=e,t===w.DEEPAR&&e!==w.DEEPAR&&(a.deepAR.shutdown(),a.deepAR=null),e===w.VIRTUAL_BACKGROUND||e===w.BLUR_BACKGROUND)return t===w.NO_EFFECT||t===w.DEEPAR?(w.DEBUG&&a.startFpsCalculation(),navigator.mediaDevices.getUserMedia({video:a.webRTCAdaptor.mediaConstraints.video,audio:!0}).then((e=>a.init(e).then((e=>a.webRTCAdaptor.updateVideoTrack(e,a.webRTCAdaptor.publishStreamId,null,!0).then((()=>{setTimeout((()=>{a.processFrame()}),a.videoCallbackPeriodMs)})))).catch((e=>{throw y.error(e),e}))))):new Promise(((e,t)=>{e()}));if(e!==w.DEEPAR){if(t===w.DEEPAR){var o=yield navigator.mediaDevices.getUserMedia({video:a.webRTCAdaptor.mediaConstraints.video,audio:!0});yield a.setRawLocalVideo(o)}return new Promise(((e,t)=>{a.stopFpsCalculation(),n(a,S,C).call(a),e()}))}if(null!=i&&""!==i&&null!=r&&""!==r)if(t!==w.DEEPAR){t!==w.BLUR_BACKGROUND&&t!==w.VIRTUAL_BACKGROUND||(a.stopFpsCalculation(),yield n(a,S,C).call(a));var s=a.createEffectCanvas(500,500),d=new DeepAR({licenseKey:i,canvas:s,deeparWasmPath:w.DEEP_AR_FOLDER_ROOT_URL+"/wasm/deepar.wasm",callbacks:{onInitialize:function(){d.startVideo(!0)}}});a.deepAR=d,a.deepAR.callbacks.onVideoStarted=()=>{a.canvasStream=s.captureStream(30),a.webRTCAdaptor.updateVideoTrack(a.canvasStream,a.webRTCAdaptor.publishStreamId,null,!0),a.deepAR.switchEffect(0,"slot",w.DEEP_AR_EFFECTS_URL+r+w.DEEP_AR_EXTENSION)},a.deepAR.downloadFaceTrackingModel(w.DEEP_AR_FOLDER_ROOT_URL+"/models/face/models-68-extreme.bin"),a.deepAR.setVideoElement(a.rawLocalVideo,!0)}else a.deepAR.switchEffect(0,"slot",w.DEEP_AR_EFFECTS_URL+r+w.DEEP_AR_EXTENSION);else y.error("DeepAR API key or DeepAR Model is not set!")}else y.error("VideoEffect is not initialized!")}))()}drawSegmentationMask(e){this.ctx.drawImage(e,0,0,this.effectCanvas.width,this.effectCanvas.height)}onResults(e){this.renderedFrameCount++,this.effectName==w.BLUR_BACKGROUND?this.drawBlurBackground(e.image,e.segmentationMask,this.backgroundBlurRange):this.effectName==w.VIRTUAL_BACKGROUND?this.drawVirtualBackground(e.image,e.segmentationMask,function(e,t){return t.get?t.get.call(e):t.value}(this,a(this,b,"get"))):this.drawImageDirectly(e.image)}drawImageDirectly(e){this.ctx.save(),this.ctx.globalCompositeOperation="source-over",this.ctx.filter="none",this.ctx.drawImage(e,0,0,e.width,e.height),this.ctx.restore()}drawVirtualBackground(e,t,i){this.ctx.save(),this.ctx.filter="none",this.ctx.clearRect(0,0,this.effectCanvas.width,this.effectCanvas.height),this.ctx.drawImage(t,0,0,this.effectCanvas.width,this.effectCanvas.height),this.ctx.globalCompositeOperation="source-out",this.ctx.drawImage(i,0,0,i.naturalWidth,i.naturalHeight,0,0,this.effectCanvas.width,this.effectCanvas.height),this.ctx.globalCompositeOperation="destination-atop",this.ctx.drawImage(e,0,0,this.effectCanvas.width,this.effectCanvas.height),this.ctx.restore()}drawBlurBackground(e,t,i){this.ctx.clearRect(0,0,this.effectCanvas.width,this.effectCanvas.height),this.ctx.globalCompositeOperation="copy",this.ctx.filter="none",this.ctx.filter="blur("+this.edgeBlurRange+"px)",this.drawSegmentationMask(t),this.ctx.globalCompositeOperation="source-in",this.ctx.filter="none",this.ctx.drawImage(e,0,0,this.effectCanvas.width,this.effectCanvas.height),this.ctx.globalCompositeOperation="destination-over",this.ctx.filter="blur("+i+"px)",this.ctx.drawImage(e,0,0,this.effectCanvas.width,this.effectCanvas.height),this.ctx.restore()}}function C(){return this.rawLocalVideo.pause(),null!=this.canvasStream&&this.canvasStream.getVideoTracks().forEach((e=>e.stop())),this.webRTCAdaptor.switchVideoCameraCapture(this.webRTCAdaptor.publishStreamId)}r(w,"DEEPAR","deepar"),r(w,"VIRTUAL_BACKGROUND","virtual-background"),r(w,"BLUR_BACKGROUND","blur-background"),r(w,"NO_EFFECT","no-effect"),r(w,"deepARModelList",["flower_face","Ping_Pong"]),r(w,"DEBUG",!1),r(w,"LOCATE_FILE_URL","https://cdn.jsdelivr.net/npm/@mediapipe/selfie_segmentation"),r(w,"DEEP_AR_FOLDER_ROOT_URL","https://cdn.jsdelivr.net/npm/[email protected]"),r(w,"DEEP_AR_EFFECTS_URL","../js/external/deepar-effects/"),r(w,"DEEP_AR_EXTENSION",".deepar"),g.register((e=>{var t=new w(e);Object.defineProperty(e,"enableEffect",{value:function(e,i,r){return t.enableEffect(e,i,r)}}),Object.defineProperty(e,"setBackgroundImage",{value:function(e){t.virtualBackgroundImage=e}})}));var k,T=window.log,A="<video id='video-player' class='video-js vjs-default-skin vjs-big-play-centered' controls playsinline></video>";class E{constructor(e,t,i){r(this,"playOrder",void 0),r(this,"currentPlayType",void 0),r(this,"is360",!1),r(this,"streamId",void 0),r(this,"playType",void 0),r(this,"token",void 0),r(this,"autoPlay",!0),r(this,"mute",!0),r(this,"targetLatency",3),r(this,"subscriberId",void 0),r(this,"subscriberCode",void 0),r(this,"window",void 0),r(this,"containerElement",void 0),r(this,"placeHolderElement",void 0),r(this,"videojsPlayer",void 0),r(this,"dashPlayer",void 0),r(this,"iceServers",void 0),r(this,"iceConnected",void 0),r(this,"errorCalled",void 0),r(this,"aScene",void 0),r(this,"playerListener",void 0),r(this,"webRTCDataListener",void 0),r(this,"tryNextTechTimer",void 0),E.DEFAULT_PLAY_ORDER=["webrtc","hls"],E.DEFAULT_PLAY_TYPE=["mp4","webm"],E.HLS_EXTENSION="m3u8",E.WEBRTC_EXTENSION="webrtc",E.DASH_EXTENSION="mpd",E.STREAMS_FOLDER="streams",E.VIDEO_HTML=A,E.VIDEO_PLAYER_ID="video-player",this.dom=e.document,this.window=e;var a=v("id",this.window.location.search);if(this.containerElement=t,this.placeHolderElement=i,this.errorCalled=!1,this.iceConnected=!1,this.tryNextTechTimer=-1,this.videojsPlayer=null,this.iceServers='[ { "urls": "stun:stun1.l.google.com:19302" } ]',null==a&&null==(a=v("name",this.window.location.search))&&T.warn("Please use id parameter instead of name parameter."),null==a){var n="Stream id is not set.Please add your stream id to the url as a query parameter such as ?id={STREAM_ID} to the url";throw T.error(n),alert(n),new Error(n)}this.streamId=a;var o=v("is360",this.window.location.search);null!=o&&(this.is360="true"==o.toLocaleLowerCase());var s=v("playType",this.window.location.search);this.playType=null!=s?s.split(","):E.DEFAULT_PLAY_TYPE,this.token=v("token",this.window.location.search),void 0===this.token&&(this.token=null);var d=v("autoplay",this.window.location.search);null!=d&&(this.autoPlay="true"==d.toLocaleLowerCase());var c=v("mute",this.window.location.search);null!=c&&(this.mute="true"==c.toLocaleLowerCase());var l=v("targetLatency",this.window.location.search);if(null!=l){var h=Number(l);isNaN(h)?T.warn("targetLatency parameter is not a number. It will be ignored."):this.targetLatency=h}this.subscriberId=v("subscriberId",this.window.location.search),void 0===this.subscriberId&&(this.subscriberId=null),this.subscriberCode=v("subscriberCode",this.window.location.search),null==this.subscriberCode&&(this.subscriberCode=null);var u=v("playOrder",this.window.location.search);this.playOrder=null!=u?u.split(","):E.DEFAULT_PLAY_ORDER,this.loadScripts(),this.setPlayerVisible(!1)}loadScripts(){if(this.playOrder.includes("hls")||this.playOrder.includes("vod")||this.playOrder.includes("webrtc")){var e=this.dom.createElement("link");e.setAttribute("rel","stylesheet"),e.setAttribute("type","text/css"),e.setAttribute("href","css/external/video-js.css"),this.dom.head.appendChild(e);var t=this.dom.createElement("script");t.type="text/javascript",t.src="js/external/video.js",t.async=!1,this.dom.head.appendChild(t),t.onload=()=>{var e=this.dom.createElement("script");e.type="text/javascript",e.src="js/external/videojs-contrib-quality-levels.min.js",this.dom.head.appendChild(e);var t=this.dom.createElement("script");t.type="text/javascript",t.src="js/external/videojs-hls-quality-selector.min.js",this.dom.head.appendChild(t)}}if(this.playOrder.includes("webrtc")){var i=this.dom.createElement("link");i.setAttribute("rel","stylesheet"),i.setAttribute("type","text/css"),i.setAttribute("href","css/videojs-webrtc-plugin.css"),this.dom.head.appendChild(i);var r=this.dom.createElement("script");r.type="text/javascript",r.src="js/videojs-webrtc-plugin.js",r.async=!1,this.dom.head.appendChild(r)}if(this.playOrder.includes("dash")){var a=this.dom.createElement("script");a.type="text/javascript",a.src="js/external/dash.all.min.js",this.dom.head.appendChild(a)}if(this.is360){var n=this.dom.createElement("script");n.type="text/javascript",n.src="js/external/aframe.min.js",this.dom.head.appendChild(n)}}enable360Player(){this.aScene=this.dom.createElement("a-scene");var e=this.dom.getElementsByTagName("video")[0].id;this.aScene.innerHTML='<a-videosphere src="#'+e+'" rotation="0 180 0" style="background-color: antiquewhite"></a-videosphere>',this.dom.body.appendChild(this.aScene)}setPlayerVisible(e){if(this.containerElement.style.display=e?"block":"none",this.placeHolderElement.style.display=e?"none":"block",this.is360)if(e)this.enable360Player();else if(null!=this.aScene){for(var t=this.dom.getElementsByTagName("a-scene");t.length>0;)this.dom.body.removeChild(t[0]),t=this.dom.getElementsByTagName("a-scene");this.aScene=null}}handleWebRTCInfoMessages(e){"ice_connection_state_changed"==e.info?(T.debug("ice connection state changed to "+e.obj.state),"completed"==e.obj.state||"connected"==e.obj.state?this.iceConnected=!0:"failed"!=e.obj.state&&"disconnected"!=e.obj.state&&"closed"!=e.obj.state||(T.debug("Ice connection is not connected. tryNextTech to replay"),this.tryNextTech())):"closed"==e.info&&(T.debug("Websocket is closed. tryNextTech to replay"),this.tryNextTech())}playWithVideoJS(e,t){var i;if("mp4"==t)i="video/mp4";else if("webm"==t)i="video/webm";else if("mov"==t)i="video/mp4",alert("Browsers do not support to play mov format");else if("avi"==t)i="video/mp4",alert("Browsers do not support to play avi format");else if("m3u8"==t)i="application/x-mpegURL";else if("mpd"==t)i="application/dash+xml";else{if("webrtc"!=t)return void T.warn("Unknown extension: "+t);i="video/webrtc"}var r=this.streamId;this.streamId.endsWith("_adaptive")&&(r=streamId.substring(0,streamId.indexOf("_adaptive"))),this.videojsPlayer=videojs(E.VIDEO_PLAYER_ID,{poster:"previews/"+r+".png",liveui:"m3u8"==t,liveTracker:{trackingThreshold:0},html5:{vhs:{limitRenditionByPlayerDimensions:!1}},controls:!0,class:"video-js vjs-default-skin vjs-big-play-centered",muted:this.mute,preload:"auto",autoplay:this.autoPlay}),this.videojsPlayer.on("error",(e=>{T.warn("There is an error in playback: "+e),this.errorCalled||(this.errorCalled=!0,setTimeout((()=>{this.tryNextTech(),this.errorCalled=!1}),2500))})),"webrtc"==t&&(this.videojsPlayer.on("webrtc-info",((e,t)=>{this.handleWebRTCInfoMessages(t)})),this.videojsPlayer.on("webrtc-error",((e,t)=>{T.warn("error callback: "+JSON.stringify(t)),"no_stream_exist"==t.error||"WebSocketNotConnected"==t.error||"not_initialized_yet"==t.error||"data_store_not_available"==t.error||"highResourceUsage"==t.error||"unauthorized_access"==t.error||"user_blocked"==t.error?this.tryNextTech():"notSetRemoteDescription"==t.error&&(T.warn("notSetRemoteDescription error. Redirecting to HLS player."),this.playIfExists("hls"))})),this.videojsPlayer.on("webrtc-data-received",((e,t)=>{T.warn("webrtc-data-received: "+JSON.stringify(t)),null!=this.webRTCDataListener&&this.webRTCDataListener(t)}))),"m3u8"==t&&(videojs.Vhs.xhr.beforeRequest=e=>{var t=this.getSecurityQueryParams();return e.uri.includes(t)||(e.uri.endsWith("?")||(e.uri=e.uri+"?"),e.uri+=t),T.debug("hls request: "+e.uri),e},this.videojsPlayer.ready((()=>{"function"==typeof this.videojsPlayer.hlsQualitySelector&&this.videojsPlayer.hlsQualitySelector({displayCurrentQuality:!0});var e=this.videojsPlayer.qualityLevels();e.on("addqualitylevel",(function(t){var i=t.qualityLevel;i.height?i.enabled=!0:(e.removeQualityLevel(i),i.enabled=!1)}))}))),"mp4"!=t&&"webm"!=t&&"m3u8"!=t||this.makeVideoJSVisibleWhenReady(),this.videojsPlayer.on("ended",(()=>{T.warn("stream is ended"),this.setPlayerVisible(!1),"vod"!=this.currentPlayType&&(this.iceConnected?this.playIfExists(this.playOrder[0]):"hls"==this.currentPlayType?(this.setPlayerVisible(!1),(this.playOrder[0]="hls")?setTimeout((()=>{this.playIfExists(this.playOrder[0])}),1e4):this.playIfExists(this.playOrder[0])):this.tryNextTech()),null!=this.playerListener&&this.playerListener("ended")})),this.videojsPlayer.on("play",(()=>{this.setPlayerVisible(!0),null!=this.playerListener&&this.playerListener("play")})),this.iceConnected=!1,this.videojsPlayer.src({src:e,type:i,withCredentials:!0,iceServers:this.iceServers,reconnect:!1}),this.autoPlay&&this.videojsPlayer.play().catch((e=>{T.warn("Problem in playback. The error is "+e)}))}makeVideoJSVisibleWhenReady(){this.videojsPlayer.ready((()=>{this.setPlayerVisible(!0)}))}checkStreamExistsViaHttp(e,t,i){var r="";return t.startsWith(e)||(r+=e+"/"),r+=t,null!=i&&""!=i&&(r+="_adaptive."+i),r=this.addSecurityParams(r),fetch(r,{method:"HEAD"}).then((a=>200==a.status?new Promise((function(e,t){e(r)})):(r=e+"/"+t+"."+i,r=this.addSecurityParams(r),fetch(r,{method:"HEAD"}).then((e=>200==e.status?new Promise((function(e,t){e(r)})):(T.warn("No stream found"),new Promise((function(e,t){t("resource_is_not_available")}))))))))}addSecurityParams(e){var t=this.getSecurityQueryParams();return null!=t&&""!=t&&(e+="?"+t),e}tryNextTech(){if(-1==this.tryNextTechTimer){this.destroyDashPlayer(),this.destroyVideoJSPlayer(),this.setPlayerVisible(!1);var e=this.playOrder.indexOf(this.currentPlayType);-1==e||e==this.playOrder.length-1?e=0:e++,this.tryNextTechTimer=setTimeout((()=>{this.tryNextTechTimer=-1,this.playIfExists(this.playOrder[e])}),3e3)}else T.debug("tryNextTech is already scheduled no need to schedule again")}playViaDash(e){this.destroyDashPlayer(),this.dashPlayer=dashjs.MediaPlayer().create(),this.dashPlayer.extend("RequestModifier",(()=>({modifyRequestHeader:function(e,t){return e},modifyRequestURL:e=>{var t="",i=this.getSecurityQueryParams();return e.includes(i)?e:(e.endsWith("?")||(e+="?"),t=e+i,T.warn(t),t)},modifyRequest(e){}}))),this.dashPlayer.updateSettings({streaming:{delay:{liveDelay:this.targetLatency},liveCatchup:{maxDrift:.05,playbackRate:.5,latencyThreshold:60}}}),this.dashPlayer.initialize(this.containerElement.firstChild,e,this.autoPlay),this.dashPlayer.setMute(this.mute),this.dashLatencyTimer=setInterval((()=>{T.warn("live latency: "+this.dashPlayer.getCurrentLiveLatency())}),2e3),this.makeDashPlayerVisibleWhenInitialized(),this.dashPlayer.on(dashjs.MediaPlayer.events.PLAYBACK_PLAYING,(e=>{T.warn("playback started"),this.setPlayerVisible(!0),null!=this.playerListener&&this.playerListener("play")})),this.dashPlayer.on(dashjs.MediaPlayer.events.PLAYBACK_ENDED,(()=>{T.warn("playback ended"),this.destroyDashPlayer(),this.setPlayerVisible(!1),(this.playOrder[0]="dash")?setTimeout((()=>{this.playIfExists(this.playOrder[0])}),1e4):this.playIfExists(this.playOrder[0]),null!=this.playerListener&&this.playerListener("ended")})),this.dashPlayer.on(dashjs.MediaPlayer.events.PLAYBACK_ERROR,(e=>{this.tryNextTech()})),this.dashPlayer.on(dashjs.MediaPlayer.events.ERROR,(e=>{this.tryNextTech()}))}makeDashPlayerVisibleWhenInitialized(){this.dashPlayer.on(dashjs.MediaPlayer.events.STREAM_INITIALIZED,(e=>{T.warn("Stream initialized"),this.setPlayerVisible(!0)}))}destroyDashPlayer(){this.dashPlayer&&(this.dashPlayer.destroy(),this.dashPlayer=null,clearInterval(this.dashLatencyTimer))}destroyVideoJSPlayer(){this.videojsPlayer&&(this.videojsPlayer.dispose(),this.videojsPlayer=null)}playIfExists(e){var i=this;return t((function*(){switch(i.currentPlayType=e,i.destroyVideoJSPlayer(),i.destroyDashPlayer(),i.setPlayerVisible(!1),i.containerElement.innerHTML=E.VIDEO_HTML,T.warn("Try to play the stream "+i.streamId+" with "+i.currentPlayType),i.currentPlayType){case"hls":return i.checkStreamExistsViaHttp(E.STREAMS_FOLDER,i.streamId,E.HLS_EXTENSION).then((e=>{i.playWithVideoJS(e,E.HLS_EXTENSION),T.warn("incoming stream path: "+e)})).catch((e=>{T.warn("HLS stream resource not available for stream:"+i.streamId+" error is "+e+". Try next play tech"),i.tryNextTech()}));case"dash":return i.checkStreamExistsViaHttp(E.STREAMS_FOLDER,i.streamId+"/"+i.streamId,E.DASH_EXTENSION).then((e=>{i.playViaDash(e)})).catch((e=>{T.warn("DASH stream resource not available for stream:"+i.streamId+" error is "+e+". Try next play tech"),i.tryNextTech()}));case"webrtc":var t=i.window.location.pathname.substring(0,i.window.location.pathname.lastIndexOf("/")+1),r=i.window.location.hostname+":"+i.window.location.port+t+i.streamId+".webrtc",a="ws://"+r;return location.protocol.startsWith("https")&&(a="wss://"+r),i.playWithVideoJS(i.addSecurityParams(a),E.WEBRTC_EXTENSION);case"vod":var n,o=i.streamId.lastIndexOf(".");return-1!=o?(i.playType[0]="",n=i.streamId.substring(o+1)):n=i.playType[0],i.checkStreamExistsViaHttp(E.STREAMS_FOLDER,i.streamId,i.playType[0]).then((e=>{i.playWithVideoJS(e,n)})).catch((e=>{T.warn("VOD stream resource not available for stream:"+i.streamId+" and play type "+i.playType[0]+". Error is "+e),i.playType.length>1&&(T.warn("Try next play type which is "+i.playType[1]+"."),i.checkStreamExistsViaHttp(E.STREAMS_FOLDER,i.streamId,i.playType[1]).then((e=>{i.playWithVideoJS(e,i.playType[1])})).catch((e=>{T.warn("VOD stream resource not available for stream:"+i.streamId+" and play type error is "+e)})))}))}}))()}getSecurityQueryParams(){var e="";return null!=this.token&&(e+="&token="+this.token),null!=this.subscriberId&&(e+="&subscriberId="+this.subscriberId),null!=this.subscriberCode&&(e+="&subscriberCode="+this.subscriberCode),e}play(){if(this.streamId.startsWith(E.STREAMS_FOLDER)){var e=this.streamId.lastIndexOf("."),t=this.streamId.substring(e+1);this.playOrder=["vod"],t==E.DASH_EXTENSION?this.playViaDash(this.addSecurityParams(this.streamId),t):this.playWithVideoJS(this.addSecurityParams(this.streamId),t)}else this.playIfExists(this.playOrder[0])}mutePlayer(e){this.mute=e,this.videojsPlayer&&this.videojsPlayer.muted(e),this.dashPlayer&&this.dashPlayer.setMute(e)}isMuted(){return this.mute}addPlayerListener(e){this.playerListener=e}addWebRTCDataListener(e){this.webRTCDataListener=e}sendWebRTCData(e){try{if(this.videojsPlayer&&"webrtc"==this.currentPlayType)return this.videojsPlayer.sendDataViaWebRTC(e),!0;T.warn("Player is not ready or playType is not WebRTC")}catch(e){T.error("An error occurred while sending WebRTC data: ",e)}return!1}}r(E,"DEFAULT_PLAY_ORDER",["webrtc","hls"]),r(E,"DEFAULT_PLAY_TYPE",["mp4","webm"]),r(E,"HLS_EXTENSION","m3u8"),r(E,"WEBRTC_EXTENSION","webrtc"),r(E,"DASH_EXTENSION","mpd"),r(E,"STREAMS_FOLDER","streams"),r(E,"VIDEO_HTML",A),r(E,"VIDEO_PLAYER_ID","video-player");var P=!1;window.startBroadcasting=async function(e){if(console.log("startBroadcasting is called websocket url:"+e.websocketURL+" streamId: "+e.streamId),void 0!==k)throw new Error("Called startBroadcasting while recording is in progress.");let t="",i=1280,r=720;void 0!==e.token&&(t=e.token),void 0!==e.width&&e.width>0&&(i=e.width),void 0!==e.height&&e.height>0&&(r=e.height);const a=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:{max:30}},audio:{channelCount:2,echoCancellation:!1,autoGainControl:!1,noiseSuppression:!1},preferCurrentTab:!0}),n=a.getVideoTracks()[0];console.log("video track settings: ",n.getSettings());const o=a.getAudioTracks()[0];console.log("audio track settings: ",o.getSettings());const s={width:{min:640,ideal:i},height:{min:360,ideal:r},advanced:[{width:i,height:r},{aspectRatio:i/r}],frameRate:{min:15,max:30},resizeMode:"crop-and-scale"};n.applyConstraints(s),k=new g({websocket_url:e.websocketURL,peerconnection_config:{iceServers:[{urls:"stun:stun1.l.google.com:19302"}]},bandwidth:4e3,localStream:a,callback:(i,r)=>{"initialized"==i?(console.log("WebRTC adaptor initialized"),k.publish(e.streamId,t,"","","","",e.driverIp,"")):"publish_started"==i?(console.log("mediapush_publish_started"),P=!0):"publish_finished"==i&&(P=!1),console.log(i)},callbackError:function(e,t){var i=JSON.stringify(e);i=void 0!==t?t:JSON.stringify(e),-1!=e.indexOf("WebSocketNotConnected")?i="WebSocket is disconnected.":-1!=e.indexOf("not_initialized_yet")?i="Server is getting initialized.":-1!=e.indexOf("data_store_not_available")?i="Data store is not available. It's likely that server is initialized or getting closed":-1!=e.indexOf("NotFoundError")?i="Camera or Mic are not found or not allowed in your device":-1!=e.indexOf("NotReadableError")||-1!=e.indexOf("TrackStartError")?i="Camera or Mic are already in use and they cannot be opened. Choose another video/audio source if you have on the page below ":-1!=e.indexOf("OverconstrainedError")||-1!=e.indexOf("ConstraintNotSatisfiedError")?i="There is no device found that fits your video and audio constraints. You may change video and audio constraints":-1!=e.indexOf("NotAllowedError")||-1!=e.indexOf("PermissionDeniedError")?i="You are not allowed to access camera and mic.":-1!=e.indexOf("TypeError")?i="Video/Audio is required":-1!=e.indexOf("getUserMediaIsNotAllowed")?i="You are not allowed to reach devices from an insecure origin, please enable ssl":-1!=e.indexOf("ScreenSharePermissionDenied")?(i="You are not allowed to access screen share",$(".video-source").first().prop("checked",!0)):i=-1!=e.indexOf("UnsecureContext")?"Please Install SSL(https). Camera and mic cannot be opened because of unsecure context. ":-1!=e.indexOf("no_stream_exist")?"There is no active live stream with this id to play":e,void 0!==t&&console.log("error callback: "+e+" message: "+i)}}),window.webRTCAdaptorMediaPush=k},window.stopBroadcasting=function(e){k.stop(e.streamId),k.closeWebSocket()},window.isConnected=function(e){var t=!1;if(P){var i=k.signallingState(e);if(null!=i&&"closed"!=i){var r=k.iceConnectionState(e);null!=r&&"failed"!=r&&"disconnected"!=r&&(t=!0)}}return t}})()})();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can remove these files from repo becuase it's created on build time automatically

@@ -0,0 +1 @@
var FRAME_PER_SECOND=10,FRAME_INTERVAL=1/FRAME_PER_SECOND;class VolumeMeter extends AudioWorkletProcessor{constructor(){super(),this._lastUpdate=currentTime,this._volume=0,this.stop=!1,this.port.onmessage=e=>{"stop"===e.data&&(this.port.postMessage({type:"debug",message:"Stop command is received"}),this.stop=!0)}}calculateRMS(e){for(var t=0,s=0;s<e.length;s++)t+=e[s]*e[s];var r=Math.sqrt(t/e.length);this._volume=r}process(e,t){var s=e[0][0];return currentTime-this._lastUpdate>FRAME_INTERVAL&&(this.calculateRMS(s),this.port.postMessage(this._volume),this._lastUpdate=currentTime),!this.stop}debug(e){this.port.postMessage({type:"debug",message:e})}}registerProcessor("volume-meter",VolumeMeter);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can remove these files from repo becuase it's created on build time automatically

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants