@stormstreaming/stormstreamer 0.9.2-beta.0 → 0.9.2-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/amd/index.js +71 -71
- package/dist/cjs/index.js +4 -4
- package/dist/esm/index.js +12 -12
- package/dist/iife/index.js +3 -3
- package/dist/types/StormStreamer.d.ts +2 -2
- package/dist/types/events/StormStreamerEvent.d.ts +2 -2
- package/dist/types/index.amd.d.ts +1 -1
- package/dist/types/index.cjs.d.ts +1 -1
- package/dist/types/index.esm.d.ts +1 -1
- package/dist/types/index.umd.d.ts +1 -1
- package/dist/types/playback/StreamerController.d.ts +4 -4
- package/dist/types/playback/enum/{StreamerState.d.ts → InputDevicesState.d.ts} +1 -1
- package/dist/types/playback/model/InputDevice.d.ts +5 -5
- package/dist/umd/index.js +4 -4
- package/package.json +1 -1
package/dist/umd/index.js
CHANGED
|
@@ -4,14 +4,14 @@
|
|
|
4
4
|
* contact@stormstreaming.com
|
|
5
5
|
* https://stormstreaming.com
|
|
6
6
|
*
|
|
7
|
-
* Version: 0.9.2-beta.
|
|
8
|
-
* Version: 3/6/2025,
|
|
7
|
+
* Version: 0.9.2-beta.2
|
|
8
|
+
* Version: 3/6/2025, 2:53:17 PM
|
|
9
9
|
*
|
|
10
10
|
* LEGAL NOTICE:
|
|
11
11
|
* This software is subject to the terms and conditions defined in
|
|
12
12
|
* separate license conditions ('LICENSE.txt')
|
|
13
13
|
*
|
|
14
|
-
*/!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).stormStreamer={})}(this,function(h){"use strict";function r(e,o,a,h){return new(a=a||Promise)(function(i,t){function s(e){try{r(h.next(e))}catch(e){t(e)}}function n(e){try{r(h.throw(e))}catch(e){t(e)}}function r(e){var t;e.done?i(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(s,n)}r((h=h.apply(e,o||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class o{constructor(e,t,i=443,s=!0){this.host=e,this.application=t,this.port=i,this.isSSL=s,this.hasFaild=!1}getHost(){return this.host}getApplication(){return this.application}getPort(){return this.port}getIfSSL(){return this.isSSL}getIfFaild(){return this.hasFaild}setAsFaild(e){this.hasFaild=e}getData(){return{serverURL:this.getHost(),application:this.getHost(),serverPort:this.getPort(),isSSL:this.getIfSSL()}}toString(){return"host: "+this.host+" | application: "+this.application+" | port: "+this.port+" | isSSL: "+this.isSSL}}class a{constructor(e){this._serverList=new Array,this._sourceList=new Array,this._streamKey=null,this.parse(e)}parse(e){if(this._streamConfig=e,!this._streamConfig)throw new Error("Stream configuration is missing. Please check stream config!");if(void 0===this._streamConfig.serverList||null===this._streamConfig.serverList)throw new Error("StormLibrary: Server list configuration is missing. Please check the config!");if(0===this._streamConfig.serverList.length)throw new Error("StormLibrary: Server list configuration is empty. Please check the config!");for(let i=0;i<this._streamConfig.serverList.length;i++){let e,t;if(null==this._streamConfig.serverList[i].host)throw new Error('Error while parsing server object ("host" field is missing). Please check player config!');if(e=this._streamConfig.serverList[i].host,null==this._streamConfig.serverList[i].application)throw new Error('Error while parsing server object ("application" field is missing). Please check player config!');t=this._streamConfig.serverList[i].application;var s=null!=(s=this._streamConfig.serverList[i].port)?s:a.DEFAULT_CONNECTION_PORT,n=null!=(n=this._streamConfig.serverList[i].ssl)?n:a.IS_SSL_BY_DEFAULT;this._serverList.push(new o(e,t,s,n))}this._streamKey=null!=(e=this._streamConfig.streamKey)?e:this._streamKey}getServerList(){return this._serverList}getSourceList(){return this._sourceList}get streamKey(){return this._streamKey}set streamKey(e){this._streamKey=e}set serverList(e){this._serverList=e}set sourceList(e){this._sourceList=e}clearSourceList(){this._sourceList=new Array}clearServerList(){this._serverList=new Array}print(t,e=!1){if(a.PRINT_ON_STARTUP||e){t.info(this,"Server List:");for(let e=0;e<this._serverList.length;e++)t.info(this,"=> ["+e+"] "+this._serverList[e].toString());t.info(this,"StreamKey: "+this._streamKey)}}}var n,i,s;a.PRINT_ON_STARTUP=!0,a.DEFAULT_CONNECTION_PORT=443,a.IS_SSL_BY_DEFAULT=!0,(p=n=n||{}).FILL="fill",p.LETTER_BOX="letterbox",p.CROP="crop",p.ORIGINAL="original",(p=i=i||{}).CLIENT_DIMENSIONS="clientDimensions",p.BOUNDING_BOX="boundingBox",p.FULL_BOX="fullBox";class t{constructor(e){this._scalingMode=n.LETTER_BOX,this._aspectRatio="none",this._videoWidthValue=100,this._isVideoWidthInPixels=!1,this._wasVideoWidthProvided=!1,this._videoHeightValue=100,this._isVideoHeightInPixels=!1,this._wasVideoHeightProvided=!1,this._resizeDebounce=250,this._parentSizeCalculationMethod=i.CLIENT_DIMENSIONS,this.parse(e)}parse(e){if(this.videoConfig=e,null==this.videoConfig)throw new Error("Missing video configuration. Please check player config!");if(null!=this.videoConfig.aspectRatio){var e=new RegExp("^[0-9]*\\.?[0-9]+:[0-9]*\\.?[0-9]+$"),t=this.videoConfig.aspectRatio;if(!e.test(t))throw new Error('Parameter "aspectRatio" - must match "number:number" pattern ');this._aspectRatio=t,this._aspectRatio=this.videoConfig.aspectRatio}if(null!=this.videoConfig.scalingMode)switch(this.videoConfig.scalingMode.toLowerCase()){case"fill":this._scalingMode=n.FILL;break;case"letterbox":this._scalingMode=n.LETTER_BOX;break;case"crop":this._scalingMode=n.CROP;break;case"original":this._scalingMode=n.ORIGINAL;break;default:throw new Error("Unknown video scaling mode. Please check player config!")}if(void 0!==this.videoConfig.width){if(null===this.videoConfig.width)throw new Error('Parameter "width" cannot be empty');if("number"==typeof this.videoConfig.width)this._videoWidthValue=this.videoConfig.width,this._isVideoWidthInPixels=!0;else{if("string"!=typeof this.videoConfig.width)throw new Error('Unknown type for parameter "width" - it must be a number or a string! ');this.videoConfig.width.toLowerCase().endsWith("px")?(this._videoWidthValue=parseInt(this.videoConfig.width),this._isVideoWidthInPixels=!0):this.videoConfig.width.toLowerCase().endsWith("%")&&(this._videoWidthValue=parseInt(this.videoConfig.width),this._isVideoWidthInPixels=!1)}this._wasVideoWidthProvided=!0}if(void 0!==this.videoConfig.height){if(null===this.videoConfig.height)throw new Error('Parameter "height" cannot be empty');if("number"==typeof this.videoConfig.height)this._videoHeightValue=this.videoConfig.height,this._isVideoHeightInPixels=!0;else{if("string"!=typeof this.videoConfig.height)throw new Error('Unknown type for parameter "height" - it must be a number or a string!');this.videoConfig.height.toLowerCase().endsWith("px")?(this._videoHeightValue=parseInt(this.videoConfig.height),this._isVideoHeightInPixels=!0):this.videoConfig.height.toLowerCase().endsWith("%")&&(this._videoHeightValue=parseInt(this.videoConfig.height),this._isVideoHeightInPixels=!1)}this._wasVideoHeightProvided=!0}if(void 0!==this.videoConfig.sizeCalculationMethod&&null!==this.videoConfig.sizeCalculationMethod)switch(this.videoConfig.sizeCalculationMethod){case"clientDimensions":this._parentSizeCalculationMethod=i.CLIENT_DIMENSIONS;break;case"boundingBox":this._parentSizeCalculationMethod=i.BOUNDING_BOX;break;case"fullBox":this._parentSizeCalculationMethod=i.FULL_BOX}this._containerID=null!=(e=this.videoConfig.containerID)?e:null,this._resizeDebounce=null!=(t=this.videoConfig.resizeDebounce)?t:this._resizeDebounce}get scalingMode(){return this._scalingMode}get containerID(){return this._containerID}get videoWidthValue(){return this._videoWidthValue}get videoWidthInPixels(){return this._isVideoWidthInPixels}get videoWidthProvided(){return this._wasVideoWidthProvided}get videoHeightValue(){return this._videoHeightValue}get videoHeightInPixels(){return this._isVideoHeightInPixels}get videoHeightProvided(){return this._wasVideoHeightProvided}get aspectRatio(){return this._aspectRatio}get resizeDebounce(){return this._resizeDebounce}set resizeDebounce(e){this._resizeDebounce=e}set videoWidthValue(e){this._videoWidthValue=e}set videoWidthInPixels(e){this._isVideoWidthInPixels=e}set videoHeightValue(e){this._videoHeightValue=e}set videoHeightInPixels(e){this._isVideoHeightInPixels=e}set containerID(e){this._containerID=e}set scalingMode(e){switch(e.toLowerCase()){case"fill":this._scalingMode=n.FILL;break;case"letterbox":this._scalingMode=n.LETTER_BOX;break;case"crop":this._scalingMode=n.CROP;break;case"original":this._scalingMode=n.ORIGINAL;break;default:throw new Error("Unknown video scaling mode. Please check player config!")}}get parentSizeCalculationMethod(){return this._parentSizeCalculationMethod}print(e){let t="";switch(this._scalingMode){case n.FILL:t="fill";break;case n.LETTER_BOX:t="letterbox";break;case n.CROP:t="crop";break;case n.ORIGINAL:t="original"}e.info(this,"VideoConfig :: containerID: "+this._containerID),e.info(this,"VideoConfig :: scalingMode: "+t),e.info(this,"VideoConfig :: width: "+this._videoWidthValue+(this._isVideoWidthInPixels?"px":"%")+(this._wasVideoWidthProvided?" (provided)":" (default)")),e.info(this,"VideoConfig :: height: "+this._videoHeightValue+(this._isVideoHeightInPixels?"px":"%")+(this._wasVideoHeightProvided?" (provided)":" (default)")),e.info(this,"VideoConfig :: aspectRatio: "+this._aspectRatio)}}(p=s=s||{})[p.TRACE=0]="TRACE",p[p.INFO=1]="INFO",p[p.SUCCESS=2]="SUCCESS",p[p.WARNING=3]="WARNING",p[p.ERROR=4]="ERROR";class l{constructor(e){this._consoleLogEnabled=!1,this._enabledConsoleTypes=[s.INFO,s.ERROR,s.SUCCESS,s.TRACE,s.WARNING],this._consoleMonoColor=!1,this._containerLogEnabled=!1,this._enabledContainerTypes=[s.INFO,s.ERROR,s.SUCCESS,s.TRACE,s.WARNING],this._containerLogMonoColor=!1,this._stageController=!0,this._streamerController=!0,this.parse(e)}parse(e){this._debugConfig=e,this._debugConfig&&(this._consoleLogEnabled=null!=(e=null==(e=null==(e=this._debugConfig)?void 0:e.console)?void 0:e.enabled)?e:this._consoleLogEnabled,this._consoleMonoColor=null!=(e=null==(e=null==(e=this._debugConfig)?void 0:e.console)?void 0:e.monoColor)?e:this._consoleMonoColor,this._enabledConsoleTypes=null!=(e=this.parseLogTypes(null==(e=null==(e=this._debugConfig)?void 0:e.console)?void 0:e.logTypes))?e:this._enabledConsoleTypes,this._containerLogEnabled=null!=(e=null==(e=null==(e=this._debugConfig)?void 0:e.container)?void 0:e.enabled)?e:this._containerLogEnabled,this._containerLogMonoColor=null!=(e=null==(e=null==(e=this._debugConfig)?void 0:e.container)?void 0:e.monoColor)?e:this._containerLogMonoColor,this._enabledContainerTypes=null!=(e=this.parseLogTypes(null==(e=null==(e=this._debugConfig)?void 0:e.container)?void 0:e.logTypes))?e:this._enabledContainerTypes,this._containerID=null!=(e=null==(e=null==(e=this._debugConfig)?void 0:e.container)?void 0:e.containerID)?e:this._containerID,this._streamerController=null!=(e=null==(e=this._debugConfig)?void 0:e.streamerController)?e:this._streamerController,this._stageController=null!=(e=null==(e=this._debugConfig)?void 0:e.stageController)?e:this._stageController)}parseLogTypes(e){return null==e?void 0:e.map(e=>{switch(e.toLowerCase()){case"info":return s.INFO;case"error":return s.ERROR;case"warning":return s.WARNING;case"success":return s.SUCCESS;case"trace":return s.TRACE;default:throw new Error("Unsupported log type: "+e)}})}get consoleLogEnabled(){return this._consoleLogEnabled}set consoleLogEnabled(e){this._consoleLogEnabled=e}get enabledConsoleTypes(){return this._enabledConsoleTypes}set enabledConsoleTypes(t){this._enabledConsoleTypes=new Array;for(let e=0;e<t.length;e++)switch(t[e].toLowerCase()){case"info":this._enabledConsoleTypes.push(s.INFO);break;case"error":this._enabledConsoleTypes.push(s.ERROR);break;case"warning":this._enabledConsoleTypes.push(s.WARNING);break;case"success":this._enabledConsoleTypes.push(s.SUCCESS);break;case"trace":this._enabledConsoleTypes.push(s.TRACE)}}get containerLogEnabled(){return this._containerLogEnabled}set containerLogEnabled(e){this._consoleLogEnabled=e}get consoleLogMonoColor(){return this._consoleMonoColor}set consoleLogMonoColor(e){this._consoleMonoColor=e}get enabledContainerTypes(){return this._enabledContainerTypes}set enabledContainerTypes(t){this._enabledContainerTypes=new Array;for(let e=0;e<t.length;e++)switch(t[e].toLowerCase()){case"info":this._enabledContainerTypes.push(s.INFO);break;case"error":this._enabledContainerTypes.push(s.ERROR);break;case"warning":this._enabledContainerTypes.push(s.WARNING);break;case"success":this._enabledContainerTypes.push(s.SUCCESS);break;case"trace":this._enabledContainerTypes.push(s.TRACE)}}get containerID(){return this._containerID}set containerID(e){this._containerID=e}get containerLogMonoColor(){return this._containerLogMonoColor}set containerLogMonoColor(e){this._containerLogMonoColor=e}get stageControllerDebug(){return this._stageController}get streamerControllerDebug(){return this._streamerController}print(e,t=!1){if(l.PRINT_ON_STARTUP||t){let t="";for(let e=0;e<this._enabledConsoleTypes.length;e++)switch(this._enabledConsoleTypes[e]){case s.TRACE:t+="TRACE, ";break;case s.SUCCESS:t+="SUCCESS, ";break;case s.WARNING:t+="WARNING, ";break;case s.INFO:t+="INFO, ";break;case s.ERROR:t+="ERROR, "}e.info(this,"Console:: enabled: "+this._consoleLogEnabled),e.info(this,"Console:: logTypes: "+t),e.info(this,"Console:: monoColor: "+this._consoleMonoColor);let i="";for(let e=0;e<this._enabledContainerTypes.length;e++)switch(this._enabledContainerTypes[e]){case s.TRACE:i+="TRACE, ";break;case s.SUCCESS:i+="SUCCESS, ";break;case s.WARNING:i+="WARNING, ";break;case s.INFO:i+="INFO, ";break;case s.ERROR:i+="ERROR, "}e.info(this,"Container:: enabled: "+this._containerLogEnabled),e.info(this,"Container:: logTypes: "+i),e.info(this,"Container:: containerID: "+this._containerID),e.info(this,"Container:: monoColor: "+this._consoleMonoColor)}}}l.PRINT_ON_STARTUP=!0;class c{constructor(e){this._startVolume=100,this._isMuted=!1,this.parse(e)}parse(e){this._audioConfig=e,this._audioConfig&&(this._startVolume=null!=(e=null==(e=this._audioConfig)?void 0:e.startVolume)?e:this._startVolume,this._isMuted=null!=(e=null==(e=this._audioConfig)?void 0:e.muted)?e:this._isMuted)}get startVolume(){return this._startVolume}set startVolume(e){this._startVolume=e}get muted(){return this._isMuted}set muted(e){this._isMuted=e}print(e,t=!1){(c.PRINT_ON_STARTUP||t)&&e.info(this,"Audio :: startVolume: "+this._startVolume+" | isMuted: "+this._isMuted)}}c.PRINT_ON_STARTUP=!0;class d{constructor(e){this._enabled=!0,this._prefix="storm",this.parse(e)}parse(e){this._storageConfig=e,this._enabled=null!=(e=null==(e=this._storageConfig)?void 0:e.enabled)?e:this._enabled,this._prefix=null!=(e=null==(e=this._storageConfig)?void 0:e.prefix)?e:this._prefix}get enabled(){return this._enabled}set enabled(e){this._enabled=e}get prefix(){return this._prefix}set prefix(e){this._prefix=e}print(e,t=!1){(d.PRINT_ON_STARTUP||t)&&e.info(this,"Storage :: startVolume: "+this._enabled+" | prefix: "+this._prefix)}}d.PRINT_ON_STARTUP=!0;class g{constructor(e){this._restartOnError=!0,this._reconnectTime=1,this._autoStart=!1,this._autoConnect=!0,this.startOnDOMReady=!1,this.iOSOnDomReadyFix=!0,this._restartOnFocus=!0,this._preselectDevices=!0,this._cancelPublishOnError=!0,this.parse(e)}parse(e){this._settingsConfig=e,this._autoConnect=null!=(e=this._settingsConfig.autoConnect)?e:this._autoConnect,this._autoStart=null!=(e=this._settingsConfig.autoStart)?e:this._autoStart,this._restartOnFocus=null!=(e=this._settingsConfig.restartOnFocus)?e:this._restartOnFocus,this._restartOnError=null!=(e=this._settingsConfig.restartOnError)?e:this._restartOnError,this._reconnectTime=null!=(e=this._settingsConfig.reconnectTime)?e:this._reconnectTime,this._preselectDevices=null!=(e=this._settingsConfig.preselectDevices)?e:this._preselectDevices,this._cancelPublishOnError=null!=(e=this._settingsConfig.cancelPublishOnError)?e:this._cancelPublishOnError,this._videoData=new t(null!=(e=this._settingsConfig.video)?e:null),this._audioData=new c(null!=(e=this._settingsConfig.audio)?e:null),this._storageData=new d(null!=(e=this._settingsConfig.storage)?e:null),this._debugData=new l(null!=(e=this._settingsConfig.debug)?e:null)}getAudioData(){return this._audioData}getVideoData(){return this._videoData}getStorageData(){return this._storageData}getIfRestartOnError(){return this._restartOnError}getReconnectTime(){return this._reconnectTime}get autoStart(){return this._autoStart}set autoStart(e){this._autoStart=e}get autoConnect(){return this._autoConnect}get restartOnFocus(){return this._restartOnFocus}getDebugData(){return this._debugData}getIfForceSelection(){return this._preselectDevices}getIfCancelPublishOnError(){return this._cancelPublishOnError}getIfStartOnDOMReadyEnabled(){return this.startOnDOMReady}getIfIOSOnDomStartFixEnabled(){return this.iOSOnDomReadyFix}print(e,t=!1){(g.PRINT_ON_STARTUP||t)&&(e.info(this,"SettingsConfig :: autoConnect: "+this._autoConnect),e.info(this,"SettingsConfig :: autoStart: "+this._autoStart),e.info(this,"SettingsConfig :: restartOnError: "+this._restartOnError),e.info(this,"SettingsConfig :: reconnectTime: "+this._reconnectTime),e.info(this,"SettingsConfig :: enabledProtocols: "),this._videoData.print(e),this._audioData.print(e),this._debugData.print(e),this._debugData.print(e))}}g.PRINT_ON_STARTUP=!0;class u{constructor(e){this.PRINT_ON_STARTUP=!0,this.demoMode=!1,this.parse(e)}parse(e){if(this.configTemplate=e,null==this.configTemplate.stream)throw new Error("No stream field was provided. Please check your player config!");this.streamData=new a(this.configTemplate.stream),this.settingsData=new g(null!=(e=this.configTemplate.settings)?e:null),this.demoMode=null!=(e=this.configTemplate.demoMode)&&e}getStreamData(){return this.streamData}getSettingsData(){return this.settingsData}getIfDemoMode(){return this.demoMode}print(e,t=!1){(this.PRINT_ON_STARTUP||t)&&(this.streamData.print(e),this.settingsData.print(e))}}class _{static addLeadingZero(e){return e<10?"0"+e:String(e)}static isNear(e,t,i){return Math.abs(e-t)<=i}static generateUniqueString(t){let i="";var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=s.length;for(let e=0;e<t;e++)i+=s.charAt(Math.floor(Math.random()*n));return i}}_.parseValue=e=>{var t;return"string"==typeof e?(t=e.toLowerCase().endsWith("px"),{value:parseInt(e,10),isPixels:t}):{value:e,isPixels:!0}};class m{constructor(e,t){this.colorOrder=["red","green","blue","orange","black","violet"],this._logMemory=[],this._streamerInstanceID=-1,this._debugConfig=e,this._stormStreamer=t,this._streamerInstanceID=this._stormStreamer.getStreamerID();e=this.colorOrder.length<t.getStreamerID()?this.colorOrder.length-1:t.getStreamerID();this._monoColor=this.colorOrder[e]}info(e,t){e=this.logData(e,t);this._debugConfig.consoleLogEnabled&&0<=this._debugConfig.enabledConsoleTypes.indexOf(s.INFO)&&(t=this._debugConfig.consoleLogMonoColor?this._monoColor:m.INFO_COLOR,console.log("%c "+e,"color: "+t)),this._debugConfig.containerLogEnabled&&0<=this._debugConfig.enabledContainerTypes.indexOf(s.INFO)&&(t=this._debugConfig.containerLogMonoColor?this._monoColor:m.INFO_COLOR,this.writeToContainer(e,t))}warning(e,t){e=this.logData(e,t);this._debugConfig.consoleLogEnabled&&0<=this._debugConfig.enabledConsoleTypes.indexOf(s.WARNING)&&(t=this._debugConfig.consoleLogMonoColor?this._monoColor:m.WARNING_COLOR,console.log("%c "+e,"color: "+t)),this._debugConfig.containerLogEnabled&&0<=this._debugConfig.enabledContainerTypes.indexOf(s.WARNING)&&(t=this._debugConfig.containerLogMonoColor?this._monoColor:m.WARNING_COLOR,this.writeToContainer(e,t))}decoratedLog(e,t){var i=["0️⃣","1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣","8️⃣","9️⃣","🔟"],s=this._stormStreamer.getStreamerID(),t={"dark-blue":"#4c9fee","dark-green":"#4bcb64","dark-orange":"#daa33a","dark-red":"#f86464","dark-pink":"#f864e8","dark-yellow":"#e1f864"}[t];t&&console.log(`%c 🎦️${0<=s&&s<i.length?i[s]:`[${s}]`} `+e,`background: black; color: ${t}; border: 1px solid ${t}; padding: 5px 5px 5px 0px`)}error(e,t){e=this.logData(e,t);this._debugConfig.consoleLogEnabled&&0<=this._debugConfig.enabledConsoleTypes.indexOf(s.ERROR)&&(t=this._debugConfig.consoleLogMonoColor?this._monoColor:m.ERROR_COLOR,console.log("%c "+e,"color: "+t)),this._debugConfig.containerLogEnabled&&0<=this._debugConfig.enabledContainerTypes.indexOf(s.ERROR)&&(t=this._debugConfig.containerLogMonoColor?this._monoColor:m.ERROR_COLOR,this.writeToContainer(e,t))}success(e,t){e=this.logData(e,t);this._debugConfig.consoleLogEnabled&&0<=this._debugConfig.enabledConsoleTypes.indexOf(s.SUCCESS)&&(t=this._debugConfig.consoleLogMonoColor?this._monoColor:m.SUCCESS_COLOR,console.log("%c "+e,"color: "+t)),this._debugConfig.containerLogEnabled&&0<=this._debugConfig.enabledContainerTypes.indexOf(s.SUCCESS)&&(t=this._debugConfig.containerLogMonoColor?this._monoColor:m.SUCCESS_COLOR,this.writeToContainer(e,t))}trace(e,t){e=this.logData(e,t);this._debugConfig.consoleLogEnabled&&0<=this._debugConfig.enabledConsoleTypes.indexOf(s.TRACE)&&(t=this._debugConfig.consoleLogMonoColor?this._monoColor:m.TRACE_COLOR,console.log("%c "+e,"color: "+t)),this._debugConfig.containerLogEnabled&&0<=this._debugConfig.enabledContainerTypes.indexOf(s.TRACE)&&(t=this._debugConfig.containerLogMonoColor?this._monoColor:m.TRACE_COLOR,this.writeToContainer(e,t))}logData(e,t){var i=new Date,s=_.addLeadingZero(i.getHours()),n=_.addLeadingZero(i.getMinutes()),i=_.addLeadingZero(i.getSeconds());let r=String(this._streamerInstanceID);0<=this._streamerInstanceID&&(r+="|"+this._streamerInstanceID);s="[Storm-ID:"+r+"] ["+s+":"+n+":"+i+"] :: "+t;return this._logMemory.push(s),s}writeToContainer(e,t){var i,s=this._debugConfig.containerID;s&&(s=document.getElementById(s),(i=document.createElement("span")).innerText=e,i.style.color=t,s.appendChild(i))}setPlayerID(e){this._streamerInstanceID=e}getAllLogs(){return this._logMemory}}m.INFO_COLOR="blue",m.WARNING_COLOR="orange",m.ERROR_COLOR="red",m.SUCCESS_COLOR="green",m.TRACE_COLOR="black";class v{static hasWebSocketsSupport(){return null!=window.WebSocket}static isMobile(){return new RegExp("Mobile|mini|Fennec|Android|iP(ad|od|hone)").test(navigator.userAgent)}static isCookieEnabled(){let e=!!navigator.cookieEnabled;return"undefined"!=typeof navigator.cookieEnabled||e||(document.cookie="testcookie",e=-1!=document.cookie.indexOf("testcookie")),e}static getOSVersion(){let e="Unknown version",t=v.getOS();if(null!=t){var i;switch(new RegExp("Windows").test(t)&&(i=new RegExp("Windows (.*)"),e=null!=i.exec(t)[1]?i.exec(t)[1]:e,t="Windows"),t){case"Mac OS":case"Mac OS X":case"Android":var s=new RegExp("(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([\\.\\_\\d]+)");e=s.exec(navigator.userAgent)[1];break;case"iOS":s=new RegExp("OS (\\d+)_(\\d+)_?(\\d+)?");e=(e=s.exec(navigator.userAgent))[1]+"."+e[2]+"."+(0|e[3])}}return e}static getBrowserName(){return v.getFullBrowser().name}static getBrowserVersion(){return v.getFullBrowser().version}static getFullBrowser(){var e=navigator.userAgent;let t=navigator.appName,i=""+parseFloat(navigator.appVersion),s=parseInt(navigator.appVersion,10),n,r,o;return-1!=(r=e.indexOf("Opera"))?(t="Opera",i=e.substring(r+6),-1!=(r=e.indexOf("Version"))&&(i=e.substring(r+8))):-1!=(r=e.indexOf("MSIE"))?(t="Microsoft Internet Explorer",i=e.substring(r+5)):"Netscape"==t&&-1!=e.indexOf("Trident/")?(t="Microsoft Internet Explorer",i=e.substring(r+5),-1!=(r=e.indexOf("rv:"))&&(i=e.substring(r+3))):-1!=(r=e.indexOf("Chrome"))?(t="Chrome",(-1<e.indexOf("FBAV")||-1<e.indexOf("FBAN"))&&(t="Facebook"),-1<e.indexOf("OPR")&&(t="Opera"),-1<e.indexOf("SamsungBrowser")&&(t="Samsung"),i=e.substring(r+7)):-1!=(r=e.indexOf("Safari"))?(t="Safari",i=e.substring(r+7),-1!=(r=e.indexOf("Version"))&&(i=e.substring(r+8)),-1!=e.indexOf("CriOS")&&(t="Chrome"),-1!=e.indexOf("FxiOS")&&(t="Firefox")):-1!=(r=e.indexOf("Firefox"))?(t="Firefox",i=e.substring(r+8)):(n=e.lastIndexOf(" ")+1)<(r=e.lastIndexOf("/"))&&(t=e.substring(n,r),i=e.substring(r+1),t.toLowerCase()==t.toUpperCase())&&(t=navigator.appName),-1!=(o=(i=-1!=(o=(i=-1!=(o=i.indexOf(";"))?i.substring(0,o):i).indexOf(" "))?i.substring(0,o):i).indexOf(")"))&&(i=i.substring(0,o)),s=parseInt(""+i,10),isNaN(s)&&(i=""+parseFloat(navigator.appVersion),s=parseInt(navigator.appVersion,10)),{name:t,fullVersion:i,version:s}}static getOS(){let e="Unknown OS";var t,i=[{os:"Windows 10",code:"(Windows 10.0|Windows NT 10.0)"},{os:"Windows 8.1",code:"(Windows 8.1|Windows NT 6.3)"},{os:"Windows 8",code:"(Windows 8|Windows NT 6.2)"},{os:"Windows 7",code:"(Windows 7|Windows NT 6.1)"},{os:"Windows Vista",code:"Windows NT 6.0"},{os:"Windows Server 2003",code:"Windows NT 5.2"},{os:"Windows XP",code:"(Windows NT 5.1|Windows XP)"},{os:"Windows 2000",code:"(Windows NT 5.0|Windows 2000)"},{os:"Windows ME",code:"(Win 9x 4.90|Windows ME)"},{os:"Windows 98",code:"(Windows 98|Win98)"},{os:"Windows 95",code:"(Windows 95|Win95|Windows_95)"},{os:"Windows NT 4.0",code:"(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)"},{os:"Windows CE",code:"Windows CE"},{os:"Windows 3.11",code:"Win16"},{os:"Android",code:"Android"},{os:"Open BSD",code:"OpenBSD"},{os:"Sun OS",code:"SunOS"},{os:"Chrome OS",code:"CrOS"},{os:"Linux",code:"(Linux|X11(?!.*CrOS))"},{os:"iOS",code:"(iPhone|iPad|iPod)"},{os:"Mac OS X",code:"Mac OS X"},{os:"Mac OS",code:"(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)"},{os:"QNX",code:"QNX"},{os:"UNIX",code:"UNIX"},{os:"BeOS",code:"BeOS"},{os:"OS/2",code:"OS\\/2"},{os:"Search Bot",code:"(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\\/Teoma|ia_archiver)"}];for(t in i){var s=i[t];if(new RegExp(s.code).test(navigator.userAgent)){e=s.os;break}}return e}static hasWebRTCSupport(){let t=!1;try{navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||window.RTCPeerConnection;t=!0}catch(e){t=!1}return t}static hasHLSSupport(e){return null!==e&&Boolean(e.canPlayType("application/vnd.apple.mpegURL")||e.canPlayType("audio/mpegurl"))}static hasMSESupport(){var e=window.MediaSource=window.MediaSource||window.WebKitMediaSource;return window.SourceBuffer=window.SourceBuffer||window.WebKitSourceBuffer,e&&"function"==typeof e.isTypeSupported}static hasMMSSupport(){return window.ManagedMediaSource}static isSSL(){return"https:"===location.protocol}}class e{constructor(e){var t;this.LOG_ACTIVITY=!1,this.isEnabled=!0,this.prefix="",this.logger=e.getLogger(),this.isEnabled=null!=(t=null==(t=null==(t=e.getConfigManager())?void 0:t.getSettingsData())?void 0:t.getStorageData().enabled)?t:this.isEnabled,this.prefix=null!=(t=null==(e=null==(t=e.getConfigManager())?void 0:t.getSettingsData())?void 0:e.getStorageData().prefix)?t:this.prefix,this.LOG_ACTIVITY&&this.logger.info(this,"Creating new StorageManager")}saveField(e,t){1==this.isEnabled&&(this.LOG_ACTIVITY&&this.logger.info(this,"Saving data: "+e+" | "+t),localStorage.setItem(this.prefix+e,t))}removeField(e){this.isEnabled&&(this.LOG_ACTIVITY&&this.logger.info(this,"Removing data: "+e),localStorage.removeItem(this.prefix+e))}getField(e){var t;return 1==this.isEnabled?(t=localStorage.getItem(this.prefix+e),this.LOG_ACTIVITY&&this.logger.info(this,"Grabbing data: "+e+" | "+t),t):null}}var p="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function S(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function C(){return F.Date.now()}var f=NaN,b="[object Symbol]",E=/^\s+|\s+$/g,I=/^[-+]0x[0-9a-f]+$/i,W=/^0b[01]+$/i,x=/^0o[0-7]+$/i,V=parseInt,p="object"==typeof p&&p&&p.Object===Object&&p,D="object"==typeof self&&self&&self.Object===Object&&self,F=p||D||Function("return this")(),U=Object.prototype.toString,B=Math.max,H=Math.min;function T(e){var t=typeof e;return e&&("object"==t||"function"==t)}function w(e){if("number"==typeof e)return e;if("symbol"==typeof(i=e)||!!(t=i)&&"object"==typeof t&&U.call(i)==b)return f;var t;if("string"!=typeof(e=T(e)?T(t="function"==typeof e.valueOf?e.valueOf():e)?t+"":t:e))return 0===e?e:+e;e=e.replace(E,"");var i=W.test(e);return i||x.test(e)?V(e.slice(2),i?2:8):I.test(e)?f:+e}var L,M,z=S(function(s,i,e){var n,r,o,a,h,l,c=0,d=!1,g=!1,t=!0;if("function"!=typeof s)throw new TypeError("Expected a function");function u(e){var t=n,i=r;return n=r=void 0,c=e,a=s.apply(i,t)}function _(e){var t=e-l;return void 0===l||i<=t||t<0||g&&o<=e-c}function m(){var e,t=C();if(_(t))return v(t);h=setTimeout(m,(e=i-((t=t)-l),g?H(e,o-(t-c)):e))}function v(e){return h=void 0,t&&n?u(e):(n=r=void 0,a)}function p(){var e=C(),t=_(e);if(n=arguments,r=this,l=e,t){if(void 0===h)return c=e=l,h=setTimeout(m,i),d?u(e):a;if(g)return h=setTimeout(m,i),u(l)}return void 0===h&&(h=setTimeout(m,i)),a}return i=w(i)||0,T(e)&&(d=!!e.leading,g="maxWait"in e,o=g?B(w(e.maxWait)||0,i):o,t="trailing"in e?!!e.trailing:t),p.cancel=function(){void 0!==h&&clearTimeout(h),n=l=r=h=void(c=0)},p.flush=function(){return void 0===h?a:v(C())},p});class G{constructor(e){this.LOG_ACTIVITY=!0,this._volume=100,this._isMuted=!1,this._isMutedByBrowser=!1,this.onForceMute=()=>{this._isMuted=!0,this._isMutedByBrowser=!0,this.dispatchVolumeEvent()},this._main=e,this._logger=e.getLogger(),this._videoElement=document.createElement("video"),this._main.addEventListener("playbackForceMute",this.onForceMute,!1);let t=null!=(e=null==(e=this._main.getConfigManager())?void 0:e.getSettingsData().getAudioData().startVolume)?e:100,i=null!=(e=null==(e=this._main.getConfigManager())?void 0:e.getSettingsData().getAudioData().muted)&&e;null!=(null==(e=this._main.getStorageManager())?void 0:e.getField("volume"))&&(t=Number(this._main.getStorageManager().getField("volume"))),null!=(null==(e=this._main.getStorageManager())?void 0:e.getField("muted"))&&"true"==this._main.getStorageManager().getField("muted")&&(i=!0,this._isMutedByBrowser=!0),this._volume=t,this._isMuted=i,this.LOG_ACTIVITY&&this._logger.info(this,"VideoElement :: Start Volume: "+this._volume+" | Muted: "+this._isMuted),this._videoElement.volume=this._volume/100,this._videoElement.muted=this._isMuted,this._videoElement.setAttribute("playsinline","playsinline"),this._videoElement.setAttribute("webkit-playsinline","webkit-playsinline"),this._main.dispatchEvent("videoElementCreate",{ref:this._main,videoElement:this._videoElement}),this.initialize()}initialize(){this._videoElement.onload=function(e){},this._videoElement.onstalled=e=>{this._logger.info(this,"VideoElement :: onstalled")},this._videoElement.onerror=e=>{this._logger.info(this,"VideoElement :: onerror :: "+JSON.stringify(e))},this._videoElement.onvolumechange=()=>{this.dispatchVolumeEvent()},this._videoElement.onpause=()=>{},this._videoElement.addEventListener("loadedmetadata",()=>{this._main.dispatchEvent("metadata",{ref:this._main,videoWidth:this._videoElement.videoWidth,videoHeight:this._videoElement.videoHeight})}),this._videoElement.ontimeupdate=function(e){},this._videoElement.onended=e=>{this._logger.info(this,"VideoElement :: onended")},this._videoElement.onplay=()=>{}}setVolume(e){this._isMuted&&0<e&&this.setMuted(!1),this._volume=e,this._videoElement.volume=e/100,this._main.getStorageManager().saveField("volume",String(e)),0==e&&this.setMuted(!0)}getVolume(){return this._volume}setMuted(e){this._isMuted=e,this._videoElement.muted=e,this._isMutedByBrowser=!1,this._main.getStorageManager().saveField("muted",String(e)),0!=this.getVolume()||e||this.setVolume(100)}getIfMuted(){return this._isMuted}dispatchVolumeEvent(){var e=this._isMutedByBrowser?"browser":"user",t={volume:this._volume,isMuted:this._isMuted,type:e};this.LOG_ACTIVITY&&this._logger.info(this,"ScreenElement :: Event: onVolumeChange: "+JSON.stringify(t)),this._main.dispatchEvent("volumeChange",{ref:this._main,volume:this._volume,muted:this._isMuted,invokedBy:e})}getVideoElement(){return this._videoElement}}class O{constructor(e){this._containerWidth=0,this._tempContainerWidth=0,this._containerHeight=0,this._tempContainerHeight=0,this._videoWidth=0,this._videoHeight=0,this._scalingMode=n.FILL,this.isInFullScreenMode=!1,this._isResizing=!1,this._autoResizeEnabled=!0,this._parentOriginalOverflow="",this._debug=!1,this.onFullScreenChange=()=>{null==document.fullscreenElement?(this.isInFullScreenMode=!1,this._logger.info(this,"The library has exited FullScreen mode!"),this._main.dispatchEvent("fullScreenExit",{ref:this._main})):(this.isInFullScreenMode=!0,this._logger.info(this,"The library has entered FullScreen mode!"),this._main.dispatchEvent("fullScreenEnter",{ref:this._main}))},this._main=e,this._logger=e.getLogger(),this._logger.info(this,"Creating new StageController"),this.initialize()}initialize(){var e=null!=(e=null==(e=null==(e=null==(e=this._main.getConfigManager())?void 0:e.getSettingsData())?void 0:e.getVideoData())?void 0:e.containerID)?e:null,t=(this._scalingMode=null!=(t=null==(t=this._main.getConfigManager())?void 0:t.getSettingsData().getVideoData().scalingMode)?t:n.FILL,this._debug=null!=(t=null==(t=this._main.getConfigManager())?void 0:t.getSettingsData().getDebugData().stageControllerDebug)?t:this._debug,this._videoContainer=document.createElement("div"),this._videoContainer.setAttribute("id","stormStreamer_"+this._main.getStreamerID()),this._videoContainer.style.overflow="hidden",this._videoContainer.style.position="relative",this._videoContainer.classList.add("stormStreamer"),this._screenElement=new G(this._main),this._videoContainer.appendChild(this._screenElement.getVideoElement()),this._main.getConfigManager().getSettingsData().getVideoData().resizeDebounce);this._resizeObserver=0<t?new ResizeObserver(z(()=>()=>{this._autoResizeEnabled&&this.handleResize()},t,{leading:!1,trailing:!0})):new ResizeObserver(()=>{this._autoResizeEnabled&&this.handleResize()}),document.addEventListener("fullscreenchange",this.onFullScreenChange,!1),document.addEventListener("webkitfullscreenchange",this.onFullScreenChange,!1),document.addEventListener("mozfullscreenchange",this.onFullScreenChange,!1),document.addEventListener("webkitendfullscreen",this.onFullScreenChange,!1),this._screenElement.getVideoElement().addEventListener("webkitendfullscreen",this.onFullScreenChange,!1),this._main.addEventListener("metadata",e=>{this._videoWidth=e.videoWidth,this._videoHeight=e.videoHeight,this.handleResize()},!1),e?this.attachToParent(e):this._logger.warning(this,'Could not create HTMLObject for the library - "containerID" was not provided')}attachToParent(e){let t=!1,i=null;return"string"==typeof e?(this._logger.info(this,"Attaching container to ID: "+e),i=document.getElementById(e)):e instanceof HTMLElement&&(this._logger.info(this,"Attaching container to HTMLElement: "+e),i=e),i===this._parentElement?(this._debug&&this._logger.decoratedLog("Attaching Failed (container is the same)","dark-pink"),this._logger.warning(this,"attachToParent :: container is the same"),!1):(i&&this._videoContainer?(this._debug&&this._logger.decoratedLog("Attach To Parent: "+e+" (success)","dark-pink"),this._parentElement=i,this._parentElement.appendChild(this._videoContainer),this._resizeObserver.observe(this._parentElement),this._parentElement.addEventListener("transitionend",()=>{this.handleResize()}),this._main.dispatchEvent("containerChange",{ref:this._main,container:this._parentElement}),this.handleResize(),t=!0):(this._debug&&this._logger.decoratedLog("Attach To Parent: "+e+" (failure - container not found)","dark-pink"),this._logger.warning(this,'attachToParent :: container "'+e+'"+ was not found')),t)}detachFromParent(){this._debug&&this._logger.decoratedLog("Detach From Parent","dark-pink");let e=!1;return null!=this._parentElement&&null!=this._videoContainer?(this._logger.info(this,"Detaching from parent: "+this._videoContainer),this._parentElement.removeChild(this._videoContainer),this._resizeObserver&&(this._resizeObserver.unobserve(this._parentElement),this._resizeObserver.disconnect()),this._autoResizeEnabled&&this._parentElement.removeEventListener("transitionend",this.handleResize),this._main.dispatchEvent("containerChange",{ref:this._main,container:null}),e=!0):this._logger.info(this,"Failed detaching from parent!"),this._parentElement=null,e}handleResize(){this._parentElement&&!this._isResizing&&(this._isResizing=!0,this._parentOriginalOverflow=this._parentElement.style.overflow,this._parentElement.style.overflow="hidden",requestAnimationFrame(()=>{this.calculateNewDimensions(),this._parentElement.style.overflow=this._parentOriginalOverflow,this._isResizing=!1,this._tempContainerWidth===this._containerWidth&&this._tempContainerHeight===this._containerHeight||this._main.dispatchEvent("resizeUpdate",{ref:this._main,width:this._tempContainerWidth,height:this._tempContainerHeight})}))}calculateNewDimensions(){var e=this._main.getConfigManager().getSettingsData().getVideoData().parentSizeCalculationMethod;switch(e){case i.CLIENT_DIMENSIONS:this._tempContainerWidth=this._parentElement.clientWidth,this._tempContainerHeight=this._parentElement.clientHeight;break;case i.BOUNDING_BOX:var t=this._parentElement.getBoundingClientRect();this._tempContainerWidth=t.width,this._tempContainerHeight=t.height;break;case i.FULL_BOX:t=class{static calculateDimensionsWithMargins(e){var t=window.getComputedStyle(e),e=e.getBoundingClientRect(),i=parseFloat(t.paddingLeft),s=parseFloat(t.paddingRight),n=parseFloat(t.paddingTop),r=parseFloat(t.paddingBottom),o=parseFloat(t.borderLeftWidth),a=parseFloat(t.borderRightWidth),h=parseFloat(t.borderTopWidth),t=parseFloat(t.borderBottomWidth);return{width:e.width-i-s-o-a,height:e.height-n-r-h-t}}}.calculateDimensionsWithMargins(this._parentElement);this._tempContainerWidth=t.width,this._tempContainerHeight=t.height}this._logger.info(this,`New dimensions calculated: ${this._tempContainerWidth}x${this._tempContainerHeight} (${e})`),this.resizeVideoContainer(),this.scaleVideo()}resizeVideoContainer(){var e=this._main.getConfigManager().getSettingsData().getVideoData().videoWidthInPixels,t=this._main.getConfigManager().getSettingsData().getVideoData().videoHeightInPixels,i=this._main.getConfigManager().getSettingsData().getVideoData().videoWidthValue,s=this._main.getConfigManager().getSettingsData().getVideoData().videoHeightValue,n=this._main.getConfigManager().getSettingsData().getVideoData().aspectRatio;let r=0,o=0;var a=Number(n.split(":")[0]),h=Number(n.split(":")[1]);"none"==n?(e?r=i:null!=this._parentElement&&(r=this._tempContainerWidth*i/100),t?o=s:null!=this._parentElement&&0==(o=this._tempContainerHeight*s/100)&&0!=this._videoHeight&&0!=this._videoWidth&&(o=this._videoHeight*r/this._videoWidth)):(e?r=i:null!=this._parentElement&&(r=this._tempContainerWidth*i/100),o=r*h/a),this._containerWidth=Math.ceil(r),this._containerHeight=Math.ceil(o),null!==this._videoContainer&&(this._videoContainer.style.width=this._containerWidth+"px",this._videoContainer.style.height=this._containerHeight+"px")}scaleVideo(){if(null!==this._screenElement){let e=0,t=0,i=0,s=0;switch(this._scalingMode){case n.FILL:i=this._containerWidth,s=this._containerHeight;break;case n.CROP:i=this._containerWidth,(s=this._videoHeight*this._containerWidth/this._videoWidth)>=this._containerHeight?(e=0,t=(s-this._containerHeight)/2*-1):(s=this._containerHeight,i=this._videoWidth*this._containerHeight/this._videoHeight,t=0,e=(i-this._containerWidth)/2*-1);break;case n.LETTER_BOX:i=this._containerWidth,(!((s=this._videoHeight*this._containerWidth/this._videoWidth)<=this._containerHeight)||(e=0,t=(s-this._containerHeight)/2*-1,s>this._containerHeight))&&(s=this._containerHeight,i=this._videoWidth*this._containerHeight/this._videoHeight,t=0,e=(i-this._containerWidth)/2*-1);break;case n.ORIGINAL:i=this._videoWidth,s=this._videoHeight,e=(this._videoWidth-this._containerWidth)/-2,t=(this._videoHeight-this._containerHeight)/-2}this._screenElement.getVideoElement().style.left=Math.floor(e)+"px",this._screenElement.getVideoElement().style.top=Math.floor(t)+"px",this._screenElement.getVideoElement().style.width=Math.ceil(i)+"px",this._screenElement.getVideoElement().style.height=Math.ceil(s)+"px",this._screenElement.getVideoElement().style.position="absolute",this._screenElement.getVideoElement().style.objectFit="fill"}}enterFullScreen(){var e;null!=(e=this._screenElement)&&e.getVideoElement().webkitEnterFullScreen?null!=(e=this._screenElement)&&e.getVideoElement().webkitEnterFullScreen():null!=(e=this._screenElement)&&e.getVideoElement().requestFullscreen()}exitFullScreen(){var e;null!=(e=this._screenElement)&&e.getVideoElement().webkitExitFullscreen?document.webkitExitFullscreen():document.exitFullscreen()}isFullScreenMode(){return this.isInFullScreenMode}setDimension(e,t){var i="width"===e?"videoWidth":"videoHeight";let s,n;if("number"==typeof t)n=t,s=!0;else{if("string"!=typeof t)throw new Error(`Unknown value for parameter "${e}" - it must be a number or a string!`);n=parseInt(t),s=t.toLowerCase().endsWith("px")}this._main.getConfigManager().getSettingsData().getVideoData()[i+"Value"]=n,this._main.getConfigManager().getSettingsData().getVideoData()[i+"InPixels"]=s,this.resizeVideoContainer(),this.scaleVideo()}setSize(e,t){this.setDimension("width",e),this.setDimension("height",t)}setWidth(e){this.setDimension("width",e)}setHeight(e){this.setDimension("height",e)}getParentElement(){return this._parentElement}setScalingMode(e){switch(e.toLowerCase()){case"fill":this._scalingMode=n.FILL;break;case"crop":this._scalingMode=n.CROP;break;case"letterbox":this._scalingMode=n.LETTER_BOX;break;case"original":this._scalingMode=n.ORIGINAL}this.scaleVideo()}getContainerWidth(){return this._containerWidth}getContainerHeight(){return this._containerHeight}getScalingModeAsString(){let e="";switch(this._scalingMode){case n.FILL:e="fill";break;case n.CROP:e="crop";break;case n.LETTER_BOX:e="letterbox";break;case n.ORIGINAL:e="original"}return e}getScalingMode(){return this._scalingMode}getScreenElement(){return this._screenElement}getContainer(){return this._videoContainer}destroy(){this.detachFromParent()}}O.LOG_ACTIVITY=!0;class y{constructor(){}addAudio(e,t){let i="",s="",n=!1;for(const r of e.split(/\r\n/))r.length<=0||(0===r.indexOf("m=audio")?i="audio":0===r.indexOf("m=video")&&(i="video"),s=s+r+"\r\n","audio"!==i)||0!=="a=rtcp-mux".localeCompare(r)||n||(s+=t,n=!0);return s}addVideo(e,t){e=e.split(/\r\n/);let i="",s=!1,n=!1;for(const o of e)o.length<=0||(o.includes("a=rtcp-rsize")&&(n=!0),o.includes("a=rtcp-mux"));let r=!1;for(const a of e)a.startsWith("m=video")&&(r=!0),i=i+a+"\r\n",r&&(0==="a=rtcp-rsize".localeCompare(a)&&!s&&n&&(i+=t,s=!0),0==="a=rtcp-mux".localeCompare(a)&&s&&!n&&(i+=t,s=!0),0!=="a=rtcp-mux".localeCompare(a)||s||n||(s=!0));return i}deliverCheckLine(e,t){for(const s in y.SDPOutput){var i=y.SDPOutput[s];if(i.includes(e)){if(e.includes("VP9")||e.includes("VP8")){let e="";for(const n of i.split(/\r\n/))e=e+n+"\r\n";return t.includes("audio")&&(y.audioIndex=parseInt(s)),t.includes("video")&&(y.videoIndex=parseInt(s)),e}return t.includes("audio")&&(y.audioIndex=parseInt(s)),t.includes("video")&&(y.videoIndex=parseInt(s)),i}}return""}checkLine(t){if(t.startsWith("a=rtpmap")||t.startsWith("a=rtcp-fb")||t.startsWith("a=fmtp")){var i=t.split(":");if(1<i.length){i=i[1].split(" ");if(!isNaN(parseInt(i[0]))&&!i[1].startsWith("http")&&!i[1].startsWith("ur")){let e=y.SDPOutput[i[0]];return e=e||"",e+=t+"\r\n",y.SDPOutput[i[0]]=e,!1}}}return!0}getrtpMapID(e){var t=new RegExp("a=rtpmap:(\\d+) (\\w+)/(\\d+)"),e=e.match(t);return e&&3<=e.length?e:null}mungeSDPPublish(e,t){y.SDPOutput={},y.videoChoice=t.videoCodec||"42e01f",y.audioChoice=t.audioCodec||"opus",y.videoIndex=-1,y.audioIndex=-1;const i=t.videoFrameRate?Math.min(Math.max(t.videoFrameRate,1),60):30;let s="";for(const c of e.split(/\r\n/))c.length<=0||this.checkLine(c)&&(s+=c+"\r\n");s=this.addAudio(s,this.deliverCheckLine(y.audioChoice,"audio"));e=(s=this.addVideo(s,this.deliverCheckLine(y.videoChoice,"video"))).split(/\r\n/);s="";let n="header",r=!1;for(const d of e)if(!(d.length<=0))if(0===d.indexOf("m=audio")&&-1!==y.audioIndex){var o=d.split(" ");s+=`${o[0]} ${o[1]} ${o[2]} ${y.audioIndex}\r\n`,n="audio",r=!1}else if(0===d.indexOf("m=video")&&-1!==y.videoIndex){o=d.split(" ");s=(s=(s=(s+=`${o[0]} ${o[1]} ${o[2]} ${y.videoIndex}\r\n`)+`a=framerate:${i}\r
|
|
14
|
+
*/!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).stormStreamer={})}(this,function(h){"use strict";function r(e,o,a,h){return new(a=a||Promise)(function(i,t){function s(e){try{r(h.next(e))}catch(e){t(e)}}function n(e){try{r(h.throw(e))}catch(e){t(e)}}function r(e){var t;e.done?i(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(s,n)}r((h=h.apply(e,o||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class o{constructor(e,t,i=443,s=!0){this.host=e,this.application=t,this.port=i,this.isSSL=s,this.hasFaild=!1}getHost(){return this.host}getApplication(){return this.application}getPort(){return this.port}getIfSSL(){return this.isSSL}getIfFaild(){return this.hasFaild}setAsFaild(e){this.hasFaild=e}getData(){return{serverURL:this.getHost(),application:this.getHost(),serverPort:this.getPort(),isSSL:this.getIfSSL()}}toString(){return"host: "+this.host+" | application: "+this.application+" | port: "+this.port+" | isSSL: "+this.isSSL}}class a{constructor(e){this._serverList=new Array,this._sourceList=new Array,this._streamKey=null,this.parse(e)}parse(e){if(this._streamConfig=e,!this._streamConfig)throw new Error("Stream configuration is missing. Please check stream config!");if(void 0===this._streamConfig.serverList||null===this._streamConfig.serverList)throw new Error("StormLibrary: Server list configuration is missing. Please check the config!");if(0===this._streamConfig.serverList.length)throw new Error("StormLibrary: Server list configuration is empty. Please check the config!");for(let i=0;i<this._streamConfig.serverList.length;i++){let e,t;if(null==this._streamConfig.serverList[i].host)throw new Error('Error while parsing server object ("host" field is missing). Please check player config!');if(e=this._streamConfig.serverList[i].host,null==this._streamConfig.serverList[i].application)throw new Error('Error while parsing server object ("application" field is missing). Please check player config!');t=this._streamConfig.serverList[i].application;var s=null!=(s=this._streamConfig.serverList[i].port)?s:a.DEFAULT_CONNECTION_PORT,n=null!=(n=this._streamConfig.serverList[i].ssl)?n:a.IS_SSL_BY_DEFAULT;this._serverList.push(new o(e,t,s,n))}this._streamKey=null!=(e=this._streamConfig.streamKey)?e:this._streamKey}getServerList(){return this._serverList}getSourceList(){return this._sourceList}get streamKey(){return this._streamKey}set streamKey(e){this._streamKey=e}set serverList(e){this._serverList=e}set sourceList(e){this._sourceList=e}clearSourceList(){this._sourceList=new Array}clearServerList(){this._serverList=new Array}print(t,e=!1){if(a.PRINT_ON_STARTUP||e){t.info(this,"Server List:");for(let e=0;e<this._serverList.length;e++)t.info(this,"=> ["+e+"] "+this._serverList[e].toString());t.info(this,"StreamKey: "+this._streamKey)}}}var n,i,s;a.PRINT_ON_STARTUP=!0,a.DEFAULT_CONNECTION_PORT=443,a.IS_SSL_BY_DEFAULT=!0,(p=n=n||{}).FILL="fill",p.LETTER_BOX="letterbox",p.CROP="crop",p.ORIGINAL="original",(p=i=i||{}).CLIENT_DIMENSIONS="clientDimensions",p.BOUNDING_BOX="boundingBox",p.FULL_BOX="fullBox";class t{constructor(e){this._scalingMode=n.LETTER_BOX,this._aspectRatio="none",this._videoWidthValue=100,this._isVideoWidthInPixels=!1,this._wasVideoWidthProvided=!1,this._videoHeightValue=100,this._isVideoHeightInPixels=!1,this._wasVideoHeightProvided=!1,this._resizeDebounce=250,this._parentSizeCalculationMethod=i.CLIENT_DIMENSIONS,this.parse(e)}parse(e){if(this.videoConfig=e,null==this.videoConfig)throw new Error("Missing video configuration. Please check player config!");if(null!=this.videoConfig.aspectRatio){var e=new RegExp("^[0-9]*\\.?[0-9]+:[0-9]*\\.?[0-9]+$"),t=this.videoConfig.aspectRatio;if(!e.test(t))throw new Error('Parameter "aspectRatio" - must match "number:number" pattern ');this._aspectRatio=t,this._aspectRatio=this.videoConfig.aspectRatio}if(null!=this.videoConfig.scalingMode)switch(this.videoConfig.scalingMode.toLowerCase()){case"fill":this._scalingMode=n.FILL;break;case"letterbox":this._scalingMode=n.LETTER_BOX;break;case"crop":this._scalingMode=n.CROP;break;case"original":this._scalingMode=n.ORIGINAL;break;default:throw new Error("Unknown video scaling mode. Please check player config!")}if(void 0!==this.videoConfig.width){if(null===this.videoConfig.width)throw new Error('Parameter "width" cannot be empty');if("number"==typeof this.videoConfig.width)this._videoWidthValue=this.videoConfig.width,this._isVideoWidthInPixels=!0;else{if("string"!=typeof this.videoConfig.width)throw new Error('Unknown type for parameter "width" - it must be a number or a string! ');this.videoConfig.width.toLowerCase().endsWith("px")?(this._videoWidthValue=parseInt(this.videoConfig.width),this._isVideoWidthInPixels=!0):this.videoConfig.width.toLowerCase().endsWith("%")&&(this._videoWidthValue=parseInt(this.videoConfig.width),this._isVideoWidthInPixels=!1)}this._wasVideoWidthProvided=!0}if(void 0!==this.videoConfig.height){if(null===this.videoConfig.height)throw new Error('Parameter "height" cannot be empty');if("number"==typeof this.videoConfig.height)this._videoHeightValue=this.videoConfig.height,this._isVideoHeightInPixels=!0;else{if("string"!=typeof this.videoConfig.height)throw new Error('Unknown type for parameter "height" - it must be a number or a string!');this.videoConfig.height.toLowerCase().endsWith("px")?(this._videoHeightValue=parseInt(this.videoConfig.height),this._isVideoHeightInPixels=!0):this.videoConfig.height.toLowerCase().endsWith("%")&&(this._videoHeightValue=parseInt(this.videoConfig.height),this._isVideoHeightInPixels=!1)}this._wasVideoHeightProvided=!0}if(void 0!==this.videoConfig.sizeCalculationMethod&&null!==this.videoConfig.sizeCalculationMethod)switch(this.videoConfig.sizeCalculationMethod){case"clientDimensions":this._parentSizeCalculationMethod=i.CLIENT_DIMENSIONS;break;case"boundingBox":this._parentSizeCalculationMethod=i.BOUNDING_BOX;break;case"fullBox":this._parentSizeCalculationMethod=i.FULL_BOX}this._containerID=null!=(e=this.videoConfig.containerID)?e:null,this._resizeDebounce=null!=(t=this.videoConfig.resizeDebounce)?t:this._resizeDebounce}get scalingMode(){return this._scalingMode}get containerID(){return this._containerID}get videoWidthValue(){return this._videoWidthValue}get videoWidthInPixels(){return this._isVideoWidthInPixels}get videoWidthProvided(){return this._wasVideoWidthProvided}get videoHeightValue(){return this._videoHeightValue}get videoHeightInPixels(){return this._isVideoHeightInPixels}get videoHeightProvided(){return this._wasVideoHeightProvided}get aspectRatio(){return this._aspectRatio}get resizeDebounce(){return this._resizeDebounce}set resizeDebounce(e){this._resizeDebounce=e}set videoWidthValue(e){this._videoWidthValue=e}set videoWidthInPixels(e){this._isVideoWidthInPixels=e}set videoHeightValue(e){this._videoHeightValue=e}set videoHeightInPixels(e){this._isVideoHeightInPixels=e}set containerID(e){this._containerID=e}set scalingMode(e){switch(e.toLowerCase()){case"fill":this._scalingMode=n.FILL;break;case"letterbox":this._scalingMode=n.LETTER_BOX;break;case"crop":this._scalingMode=n.CROP;break;case"original":this._scalingMode=n.ORIGINAL;break;default:throw new Error("Unknown video scaling mode. Please check player config!")}}get parentSizeCalculationMethod(){return this._parentSizeCalculationMethod}print(e){let t="";switch(this._scalingMode){case n.FILL:t="fill";break;case n.LETTER_BOX:t="letterbox";break;case n.CROP:t="crop";break;case n.ORIGINAL:t="original"}e.info(this,"VideoConfig :: containerID: "+this._containerID),e.info(this,"VideoConfig :: scalingMode: "+t),e.info(this,"VideoConfig :: width: "+this._videoWidthValue+(this._isVideoWidthInPixels?"px":"%")+(this._wasVideoWidthProvided?" (provided)":" (default)")),e.info(this,"VideoConfig :: height: "+this._videoHeightValue+(this._isVideoHeightInPixels?"px":"%")+(this._wasVideoHeightProvided?" (provided)":" (default)")),e.info(this,"VideoConfig :: aspectRatio: "+this._aspectRatio)}}(p=s=s||{})[p.TRACE=0]="TRACE",p[p.INFO=1]="INFO",p[p.SUCCESS=2]="SUCCESS",p[p.WARNING=3]="WARNING",p[p.ERROR=4]="ERROR";class l{constructor(e){this._consoleLogEnabled=!1,this._enabledConsoleTypes=[s.INFO,s.ERROR,s.SUCCESS,s.TRACE,s.WARNING],this._consoleMonoColor=!1,this._containerLogEnabled=!1,this._enabledContainerTypes=[s.INFO,s.ERROR,s.SUCCESS,s.TRACE,s.WARNING],this._containerLogMonoColor=!1,this._stageController=!0,this._streamerController=!0,this.parse(e)}parse(e){this._debugConfig=e,this._debugConfig&&(this._consoleLogEnabled=null!=(e=null==(e=null==(e=this._debugConfig)?void 0:e.console)?void 0:e.enabled)?e:this._consoleLogEnabled,this._consoleMonoColor=null!=(e=null==(e=null==(e=this._debugConfig)?void 0:e.console)?void 0:e.monoColor)?e:this._consoleMonoColor,this._enabledConsoleTypes=null!=(e=this.parseLogTypes(null==(e=null==(e=this._debugConfig)?void 0:e.console)?void 0:e.logTypes))?e:this._enabledConsoleTypes,this._containerLogEnabled=null!=(e=null==(e=null==(e=this._debugConfig)?void 0:e.container)?void 0:e.enabled)?e:this._containerLogEnabled,this._containerLogMonoColor=null!=(e=null==(e=null==(e=this._debugConfig)?void 0:e.container)?void 0:e.monoColor)?e:this._containerLogMonoColor,this._enabledContainerTypes=null!=(e=this.parseLogTypes(null==(e=null==(e=this._debugConfig)?void 0:e.container)?void 0:e.logTypes))?e:this._enabledContainerTypes,this._containerID=null!=(e=null==(e=null==(e=this._debugConfig)?void 0:e.container)?void 0:e.containerID)?e:this._containerID,this._streamerController=null!=(e=null==(e=this._debugConfig)?void 0:e.streamerController)?e:this._streamerController,this._stageController=null!=(e=null==(e=this._debugConfig)?void 0:e.stageController)?e:this._stageController)}parseLogTypes(e){return null==e?void 0:e.map(e=>{switch(e.toLowerCase()){case"info":return s.INFO;case"error":return s.ERROR;case"warning":return s.WARNING;case"success":return s.SUCCESS;case"trace":return s.TRACE;default:throw new Error("Unsupported log type: "+e)}})}get consoleLogEnabled(){return this._consoleLogEnabled}set consoleLogEnabled(e){this._consoleLogEnabled=e}get enabledConsoleTypes(){return this._enabledConsoleTypes}set enabledConsoleTypes(t){this._enabledConsoleTypes=new Array;for(let e=0;e<t.length;e++)switch(t[e].toLowerCase()){case"info":this._enabledConsoleTypes.push(s.INFO);break;case"error":this._enabledConsoleTypes.push(s.ERROR);break;case"warning":this._enabledConsoleTypes.push(s.WARNING);break;case"success":this._enabledConsoleTypes.push(s.SUCCESS);break;case"trace":this._enabledConsoleTypes.push(s.TRACE)}}get containerLogEnabled(){return this._containerLogEnabled}set containerLogEnabled(e){this._consoleLogEnabled=e}get consoleLogMonoColor(){return this._consoleMonoColor}set consoleLogMonoColor(e){this._consoleMonoColor=e}get enabledContainerTypes(){return this._enabledContainerTypes}set enabledContainerTypes(t){this._enabledContainerTypes=new Array;for(let e=0;e<t.length;e++)switch(t[e].toLowerCase()){case"info":this._enabledContainerTypes.push(s.INFO);break;case"error":this._enabledContainerTypes.push(s.ERROR);break;case"warning":this._enabledContainerTypes.push(s.WARNING);break;case"success":this._enabledContainerTypes.push(s.SUCCESS);break;case"trace":this._enabledContainerTypes.push(s.TRACE)}}get containerID(){return this._containerID}set containerID(e){this._containerID=e}get containerLogMonoColor(){return this._containerLogMonoColor}set containerLogMonoColor(e){this._containerLogMonoColor=e}get stageControllerDebug(){return this._stageController}get streamerControllerDebug(){return this._streamerController}print(e,t=!1){if(l.PRINT_ON_STARTUP||t){let t="";for(let e=0;e<this._enabledConsoleTypes.length;e++)switch(this._enabledConsoleTypes[e]){case s.TRACE:t+="TRACE, ";break;case s.SUCCESS:t+="SUCCESS, ";break;case s.WARNING:t+="WARNING, ";break;case s.INFO:t+="INFO, ";break;case s.ERROR:t+="ERROR, "}e.info(this,"Console:: enabled: "+this._consoleLogEnabled),e.info(this,"Console:: logTypes: "+t),e.info(this,"Console:: monoColor: "+this._consoleMonoColor);let i="";for(let e=0;e<this._enabledContainerTypes.length;e++)switch(this._enabledContainerTypes[e]){case s.TRACE:i+="TRACE, ";break;case s.SUCCESS:i+="SUCCESS, ";break;case s.WARNING:i+="WARNING, ";break;case s.INFO:i+="INFO, ";break;case s.ERROR:i+="ERROR, "}e.info(this,"Container:: enabled: "+this._containerLogEnabled),e.info(this,"Container:: logTypes: "+i),e.info(this,"Container:: containerID: "+this._containerID),e.info(this,"Container:: monoColor: "+this._consoleMonoColor)}}}l.PRINT_ON_STARTUP=!0;class c{constructor(e){this._startVolume=100,this._isMuted=!1,this.parse(e)}parse(e){this._audioConfig=e,this._audioConfig&&(this._startVolume=null!=(e=null==(e=this._audioConfig)?void 0:e.startVolume)?e:this._startVolume,this._isMuted=null!=(e=null==(e=this._audioConfig)?void 0:e.muted)?e:this._isMuted)}get startVolume(){return this._startVolume}set startVolume(e){this._startVolume=e}get muted(){return this._isMuted}set muted(e){this._isMuted=e}print(e,t=!1){(c.PRINT_ON_STARTUP||t)&&e.info(this,"Audio :: startVolume: "+this._startVolume+" | isMuted: "+this._isMuted)}}c.PRINT_ON_STARTUP=!0;class d{constructor(e){this._enabled=!0,this._prefix="storm",this.parse(e)}parse(e){this._storageConfig=e,this._enabled=null!=(e=null==(e=this._storageConfig)?void 0:e.enabled)?e:this._enabled,this._prefix=null!=(e=null==(e=this._storageConfig)?void 0:e.prefix)?e:this._prefix}get enabled(){return this._enabled}set enabled(e){this._enabled=e}get prefix(){return this._prefix}set prefix(e){this._prefix=e}print(e,t=!1){(d.PRINT_ON_STARTUP||t)&&e.info(this,"Storage :: startVolume: "+this._enabled+" | prefix: "+this._prefix)}}d.PRINT_ON_STARTUP=!0;class g{constructor(e){this._restartOnError=!0,this._reconnectTime=1,this._autoStart=!1,this._autoConnect=!0,this.startOnDOMReady=!1,this.iOSOnDomReadyFix=!0,this._restartOnFocus=!0,this._preselectDevices=!0,this._cancelPublishOnError=!0,this.parse(e)}parse(e){this._settingsConfig=e,this._autoConnect=null!=(e=this._settingsConfig.autoConnect)?e:this._autoConnect,this._autoStart=null!=(e=this._settingsConfig.autoStart)?e:this._autoStart,this._restartOnFocus=null!=(e=this._settingsConfig.restartOnFocus)?e:this._restartOnFocus,this._restartOnError=null!=(e=this._settingsConfig.restartOnError)?e:this._restartOnError,this._reconnectTime=null!=(e=this._settingsConfig.reconnectTime)?e:this._reconnectTime,this._preselectDevices=null!=(e=this._settingsConfig.preselectDevices)?e:this._preselectDevices,this._cancelPublishOnError=null!=(e=this._settingsConfig.cancelPublishOnError)?e:this._cancelPublishOnError,this._videoData=new t(null!=(e=this._settingsConfig.video)?e:null),this._audioData=new c(null!=(e=this._settingsConfig.audio)?e:null),this._storageData=new d(null!=(e=this._settingsConfig.storage)?e:null),this._debugData=new l(null!=(e=this._settingsConfig.debug)?e:null)}getAudioData(){return this._audioData}getVideoData(){return this._videoData}getStorageData(){return this._storageData}getIfRestartOnError(){return this._restartOnError}getReconnectTime(){return this._reconnectTime}get autoStart(){return this._autoStart}set autoStart(e){this._autoStart=e}get autoConnect(){return this._autoConnect}get restartOnFocus(){return this._restartOnFocus}getDebugData(){return this._debugData}getIfForceSelection(){return this._preselectDevices}getIfCancelPublishOnError(){return this._cancelPublishOnError}getIfStartOnDOMReadyEnabled(){return this.startOnDOMReady}getIfIOSOnDomStartFixEnabled(){return this.iOSOnDomReadyFix}print(e,t=!1){(g.PRINT_ON_STARTUP||t)&&(e.info(this,"SettingsConfig :: autoConnect: "+this._autoConnect),e.info(this,"SettingsConfig :: autoStart: "+this._autoStart),e.info(this,"SettingsConfig :: restartOnError: "+this._restartOnError),e.info(this,"SettingsConfig :: reconnectTime: "+this._reconnectTime),e.info(this,"SettingsConfig :: enabledProtocols: "),this._videoData.print(e),this._audioData.print(e),this._debugData.print(e),this._debugData.print(e))}}g.PRINT_ON_STARTUP=!0;class u{constructor(e){this.PRINT_ON_STARTUP=!0,this.demoMode=!1,this.parse(e)}parse(e){if(this.configTemplate=e,null==this.configTemplate.stream)throw new Error("No stream field was provided. Please check your player config!");this.streamData=new a(this.configTemplate.stream),this.settingsData=new g(null!=(e=this.configTemplate.settings)?e:null),this.demoMode=null!=(e=this.configTemplate.demoMode)&&e}getStreamData(){return this.streamData}getSettingsData(){return this.settingsData}getIfDemoMode(){return this.demoMode}print(e,t=!1){(this.PRINT_ON_STARTUP||t)&&(this.streamData.print(e),this.settingsData.print(e))}}class _{static addLeadingZero(e){return e<10?"0"+e:String(e)}static isNear(e,t,i){return Math.abs(e-t)<=i}static generateUniqueString(t){let i="";var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=s.length;for(let e=0;e<t;e++)i+=s.charAt(Math.floor(Math.random()*n));return i}}_.parseValue=e=>{var t;return"string"==typeof e?(t=e.toLowerCase().endsWith("px"),{value:parseInt(e,10),isPixels:t}):{value:e,isPixels:!0}};class m{constructor(e,t){this.colorOrder=["red","green","blue","orange","black","violet"],this._logMemory=[],this._streamerInstanceID=-1,this._debugConfig=e,this._stormStreamer=t,this._streamerInstanceID=this._stormStreamer.getStreamerID();e=this.colorOrder.length<t.getStreamerID()?this.colorOrder.length-1:t.getStreamerID();this._monoColor=this.colorOrder[e]}info(e,t){e=this.logData(e,t);this._debugConfig.consoleLogEnabled&&0<=this._debugConfig.enabledConsoleTypes.indexOf(s.INFO)&&(t=this._debugConfig.consoleLogMonoColor?this._monoColor:m.INFO_COLOR,console.log("%c "+e,"color: "+t)),this._debugConfig.containerLogEnabled&&0<=this._debugConfig.enabledContainerTypes.indexOf(s.INFO)&&(t=this._debugConfig.containerLogMonoColor?this._monoColor:m.INFO_COLOR,this.writeToContainer(e,t))}warning(e,t){e=this.logData(e,t);this._debugConfig.consoleLogEnabled&&0<=this._debugConfig.enabledConsoleTypes.indexOf(s.WARNING)&&(t=this._debugConfig.consoleLogMonoColor?this._monoColor:m.WARNING_COLOR,console.log("%c "+e,"color: "+t)),this._debugConfig.containerLogEnabled&&0<=this._debugConfig.enabledContainerTypes.indexOf(s.WARNING)&&(t=this._debugConfig.containerLogMonoColor?this._monoColor:m.WARNING_COLOR,this.writeToContainer(e,t))}decoratedLog(e,t){var i=["0️⃣","1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣","8️⃣","9️⃣","🔟"],s=this._stormStreamer.getStreamerID(),t={"dark-blue":"#4c9fee","dark-green":"#4bcb64","dark-orange":"#daa33a","dark-red":"#f86464","dark-pink":"#f864e8","dark-yellow":"#e1f864"}[t];t&&console.log(`%c 🎦️${0<=s&&s<i.length?i[s]:`[${s}]`} `+e,`background: black; color: ${t}; border: 1px solid ${t}; padding: 5px 5px 5px 0px`)}error(e,t){e=this.logData(e,t);this._debugConfig.consoleLogEnabled&&0<=this._debugConfig.enabledConsoleTypes.indexOf(s.ERROR)&&(t=this._debugConfig.consoleLogMonoColor?this._monoColor:m.ERROR_COLOR,console.log("%c "+e,"color: "+t)),this._debugConfig.containerLogEnabled&&0<=this._debugConfig.enabledContainerTypes.indexOf(s.ERROR)&&(t=this._debugConfig.containerLogMonoColor?this._monoColor:m.ERROR_COLOR,this.writeToContainer(e,t))}success(e,t){e=this.logData(e,t);this._debugConfig.consoleLogEnabled&&0<=this._debugConfig.enabledConsoleTypes.indexOf(s.SUCCESS)&&(t=this._debugConfig.consoleLogMonoColor?this._monoColor:m.SUCCESS_COLOR,console.log("%c "+e,"color: "+t)),this._debugConfig.containerLogEnabled&&0<=this._debugConfig.enabledContainerTypes.indexOf(s.SUCCESS)&&(t=this._debugConfig.containerLogMonoColor?this._monoColor:m.SUCCESS_COLOR,this.writeToContainer(e,t))}trace(e,t){e=this.logData(e,t);this._debugConfig.consoleLogEnabled&&0<=this._debugConfig.enabledConsoleTypes.indexOf(s.TRACE)&&(t=this._debugConfig.consoleLogMonoColor?this._monoColor:m.TRACE_COLOR,console.log("%c "+e,"color: "+t)),this._debugConfig.containerLogEnabled&&0<=this._debugConfig.enabledContainerTypes.indexOf(s.TRACE)&&(t=this._debugConfig.containerLogMonoColor?this._monoColor:m.TRACE_COLOR,this.writeToContainer(e,t))}logData(e,t){var i=new Date,s=_.addLeadingZero(i.getHours()),n=_.addLeadingZero(i.getMinutes()),i=_.addLeadingZero(i.getSeconds());let r=String(this._streamerInstanceID);0<=this._streamerInstanceID&&(r+="|"+this._streamerInstanceID);s="[Storm-ID:"+r+"] ["+s+":"+n+":"+i+"] :: "+t;return this._logMemory.push(s),s}writeToContainer(e,t){var i,s=this._debugConfig.containerID;s&&(s=document.getElementById(s),(i=document.createElement("span")).innerText=e,i.style.color=t,s.appendChild(i))}setPlayerID(e){this._streamerInstanceID=e}getAllLogs(){return this._logMemory}}m.INFO_COLOR="blue",m.WARNING_COLOR="orange",m.ERROR_COLOR="red",m.SUCCESS_COLOR="green",m.TRACE_COLOR="black";class v{static hasWebSocketsSupport(){return null!=window.WebSocket}static isMobile(){return new RegExp("Mobile|mini|Fennec|Android|iP(ad|od|hone)").test(navigator.userAgent)}static isCookieEnabled(){let e=!!navigator.cookieEnabled;return"undefined"!=typeof navigator.cookieEnabled||e||(document.cookie="testcookie",e=-1!=document.cookie.indexOf("testcookie")),e}static getOSVersion(){let e="Unknown version",t=v.getOS();if(null!=t){var i;switch(new RegExp("Windows").test(t)&&(i=new RegExp("Windows (.*)"),e=null!=i.exec(t)[1]?i.exec(t)[1]:e,t="Windows"),t){case"Mac OS":case"Mac OS X":case"Android":var s=new RegExp("(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([\\.\\_\\d]+)");e=s.exec(navigator.userAgent)[1];break;case"iOS":s=new RegExp("OS (\\d+)_(\\d+)_?(\\d+)?");e=(e=s.exec(navigator.userAgent))[1]+"."+e[2]+"."+(0|e[3])}}return e}static getBrowserName(){return v.getFullBrowser().name}static getBrowserVersion(){return v.getFullBrowser().version}static getFullBrowser(){var e=navigator.userAgent;let t=navigator.appName,i=""+parseFloat(navigator.appVersion),s=parseInt(navigator.appVersion,10),n,r,o;return-1!=(r=e.indexOf("Opera"))?(t="Opera",i=e.substring(r+6),-1!=(r=e.indexOf("Version"))&&(i=e.substring(r+8))):-1!=(r=e.indexOf("MSIE"))?(t="Microsoft Internet Explorer",i=e.substring(r+5)):"Netscape"==t&&-1!=e.indexOf("Trident/")?(t="Microsoft Internet Explorer",i=e.substring(r+5),-1!=(r=e.indexOf("rv:"))&&(i=e.substring(r+3))):-1!=(r=e.indexOf("Chrome"))?(t="Chrome",(-1<e.indexOf("FBAV")||-1<e.indexOf("FBAN"))&&(t="Facebook"),-1<e.indexOf("OPR")&&(t="Opera"),-1<e.indexOf("SamsungBrowser")&&(t="Samsung"),i=e.substring(r+7)):-1!=(r=e.indexOf("Safari"))?(t="Safari",i=e.substring(r+7),-1!=(r=e.indexOf("Version"))&&(i=e.substring(r+8)),-1!=e.indexOf("CriOS")&&(t="Chrome"),-1!=e.indexOf("FxiOS")&&(t="Firefox")):-1!=(r=e.indexOf("Firefox"))?(t="Firefox",i=e.substring(r+8)):(n=e.lastIndexOf(" ")+1)<(r=e.lastIndexOf("/"))&&(t=e.substring(n,r),i=e.substring(r+1),t.toLowerCase()==t.toUpperCase())&&(t=navigator.appName),-1!=(o=(i=-1!=(o=(i=-1!=(o=i.indexOf(";"))?i.substring(0,o):i).indexOf(" "))?i.substring(0,o):i).indexOf(")"))&&(i=i.substring(0,o)),s=parseInt(""+i,10),isNaN(s)&&(i=""+parseFloat(navigator.appVersion),s=parseInt(navigator.appVersion,10)),{name:t,fullVersion:i,version:s}}static getOS(){let e="Unknown OS";var t,i=[{os:"Windows 10",code:"(Windows 10.0|Windows NT 10.0)"},{os:"Windows 8.1",code:"(Windows 8.1|Windows NT 6.3)"},{os:"Windows 8",code:"(Windows 8|Windows NT 6.2)"},{os:"Windows 7",code:"(Windows 7|Windows NT 6.1)"},{os:"Windows Vista",code:"Windows NT 6.0"},{os:"Windows Server 2003",code:"Windows NT 5.2"},{os:"Windows XP",code:"(Windows NT 5.1|Windows XP)"},{os:"Windows 2000",code:"(Windows NT 5.0|Windows 2000)"},{os:"Windows ME",code:"(Win 9x 4.90|Windows ME)"},{os:"Windows 98",code:"(Windows 98|Win98)"},{os:"Windows 95",code:"(Windows 95|Win95|Windows_95)"},{os:"Windows NT 4.0",code:"(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)"},{os:"Windows CE",code:"Windows CE"},{os:"Windows 3.11",code:"Win16"},{os:"Android",code:"Android"},{os:"Open BSD",code:"OpenBSD"},{os:"Sun OS",code:"SunOS"},{os:"Chrome OS",code:"CrOS"},{os:"Linux",code:"(Linux|X11(?!.*CrOS))"},{os:"iOS",code:"(iPhone|iPad|iPod)"},{os:"Mac OS X",code:"Mac OS X"},{os:"Mac OS",code:"(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)"},{os:"QNX",code:"QNX"},{os:"UNIX",code:"UNIX"},{os:"BeOS",code:"BeOS"},{os:"OS/2",code:"OS\\/2"},{os:"Search Bot",code:"(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\\/Teoma|ia_archiver)"}];for(t in i){var s=i[t];if(new RegExp(s.code).test(navigator.userAgent)){e=s.os;break}}return e}static hasWebRTCSupport(){let t=!1;try{navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||window.RTCPeerConnection;t=!0}catch(e){t=!1}return t}static hasHLSSupport(e){return null!==e&&Boolean(e.canPlayType("application/vnd.apple.mpegURL")||e.canPlayType("audio/mpegurl"))}static hasMSESupport(){var e=window.MediaSource=window.MediaSource||window.WebKitMediaSource;return window.SourceBuffer=window.SourceBuffer||window.WebKitSourceBuffer,e&&"function"==typeof e.isTypeSupported}static hasMMSSupport(){return window.ManagedMediaSource}static isSSL(){return"https:"===location.protocol}}class e{constructor(e){var t;this.LOG_ACTIVITY=!1,this.isEnabled=!0,this.prefix="",this.logger=e.getLogger(),this.isEnabled=null!=(t=null==(t=null==(t=e.getConfigManager())?void 0:t.getSettingsData())?void 0:t.getStorageData().enabled)?t:this.isEnabled,this.prefix=null!=(t=null==(e=null==(t=e.getConfigManager())?void 0:t.getSettingsData())?void 0:e.getStorageData().prefix)?t:this.prefix,this.LOG_ACTIVITY&&this.logger.info(this,"Creating new StorageManager")}saveField(e,t){1==this.isEnabled&&(this.LOG_ACTIVITY&&this.logger.info(this,"Saving data: "+e+" | "+t),localStorage.setItem(this.prefix+e,t))}removeField(e){this.isEnabled&&(this.LOG_ACTIVITY&&this.logger.info(this,"Removing data: "+e),localStorage.removeItem(this.prefix+e))}getField(e){var t;return 1==this.isEnabled?(t=localStorage.getItem(this.prefix+e),this.LOG_ACTIVITY&&this.logger.info(this,"Grabbing data: "+e+" | "+t),t):null}}var p="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function C(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function S(){return F.Date.now()}var f=NaN,b="[object Symbol]",E=/^\s+|\s+$/g,I=/^[-+]0x[0-9a-f]+$/i,W=/^0b[01]+$/i,x=/^0o[0-7]+$/i,V=parseInt,p="object"==typeof p&&p&&p.Object===Object&&p,D="object"==typeof self&&self&&self.Object===Object&&self,F=p||D||Function("return this")(),U=Object.prototype.toString,B=Math.max,H=Math.min;function T(e){var t=typeof e;return e&&("object"==t||"function"==t)}function w(e){if("number"==typeof e)return e;if("symbol"==typeof(i=e)||!!(t=i)&&"object"==typeof t&&U.call(i)==b)return f;var t;if("string"!=typeof(e=T(e)?T(t="function"==typeof e.valueOf?e.valueOf():e)?t+"":t:e))return 0===e?e:+e;e=e.replace(E,"");var i=W.test(e);return i||x.test(e)?V(e.slice(2),i?2:8):I.test(e)?f:+e}var L,M,z=C(function(s,i,e){var n,r,o,a,h,l,c=0,d=!1,g=!1,t=!0;if("function"!=typeof s)throw new TypeError("Expected a function");function u(e){var t=n,i=r;return n=r=void 0,c=e,a=s.apply(i,t)}function _(e){var t=e-l;return void 0===l||i<=t||t<0||g&&o<=e-c}function m(){var e,t=S();if(_(t))return v(t);h=setTimeout(m,(e=i-((t=t)-l),g?H(e,o-(t-c)):e))}function v(e){return h=void 0,t&&n?u(e):(n=r=void 0,a)}function p(){var e=S(),t=_(e);if(n=arguments,r=this,l=e,t){if(void 0===h)return c=e=l,h=setTimeout(m,i),d?u(e):a;if(g)return h=setTimeout(m,i),u(l)}return void 0===h&&(h=setTimeout(m,i)),a}return i=w(i)||0,T(e)&&(d=!!e.leading,g="maxWait"in e,o=g?B(w(e.maxWait)||0,i):o,t="trailing"in e?!!e.trailing:t),p.cancel=function(){void 0!==h&&clearTimeout(h),n=l=r=h=void(c=0)},p.flush=function(){return void 0===h?a:v(S())},p});class G{constructor(e){this.LOG_ACTIVITY=!0,this._volume=100,this._isMuted=!1,this._isMutedByBrowser=!1,this.onForceMute=()=>{this._isMuted=!0,this._isMutedByBrowser=!0,this.dispatchVolumeEvent()},this._main=e,this._logger=e.getLogger(),this._videoElement=document.createElement("video"),this._main.addEventListener("playbackForceMute",this.onForceMute,!1);let t=null!=(e=null==(e=this._main.getConfigManager())?void 0:e.getSettingsData().getAudioData().startVolume)?e:100,i=null!=(e=null==(e=this._main.getConfigManager())?void 0:e.getSettingsData().getAudioData().muted)&&e;null!=(null==(e=this._main.getStorageManager())?void 0:e.getField("volume"))&&(t=Number(this._main.getStorageManager().getField("volume"))),null!=(null==(e=this._main.getStorageManager())?void 0:e.getField("muted"))&&"true"==this._main.getStorageManager().getField("muted")&&(i=!0,this._isMutedByBrowser=!0),this._volume=t,this._isMuted=i,this.LOG_ACTIVITY&&this._logger.info(this,"VideoElement :: Start Volume: "+this._volume+" | Muted: "+this._isMuted),this._videoElement.volume=this._volume/100,this._videoElement.muted=this._isMuted,this._videoElement.setAttribute("playsinline","playsinline"),this._videoElement.setAttribute("webkit-playsinline","webkit-playsinline"),this._main.dispatchEvent("videoElementCreate",{ref:this._main,videoElement:this._videoElement}),this.initialize()}initialize(){this._videoElement.onload=function(e){},this._videoElement.onstalled=e=>{this._logger.info(this,"VideoElement :: onstalled")},this._videoElement.onerror=e=>{this._logger.info(this,"VideoElement :: onerror :: "+JSON.stringify(e))},this._videoElement.onvolumechange=()=>{this.dispatchVolumeEvent()},this._videoElement.onpause=()=>{},this._videoElement.addEventListener("loadedmetadata",()=>{this._main.dispatchEvent("metadata",{ref:this._main,videoWidth:this._videoElement.videoWidth,videoHeight:this._videoElement.videoHeight})}),this._videoElement.ontimeupdate=function(e){},this._videoElement.onended=e=>{this._logger.info(this,"VideoElement :: onended")},this._videoElement.onplay=()=>{}}setVolume(e){this._isMuted&&0<e&&this.setMuted(!1),this._volume=e,this._videoElement.volume=e/100,this._main.getStorageManager().saveField("volume",String(e)),0==e&&this.setMuted(!0)}getVolume(){return this._volume}setMuted(e){this._isMuted=e,this._videoElement.muted=e,this._isMutedByBrowser=!1,this._main.getStorageManager().saveField("muted",String(e)),0!=this.getVolume()||e||this.setVolume(100)}getIfMuted(){return this._isMuted}dispatchVolumeEvent(){var e=this._isMutedByBrowser?"browser":"user",t={volume:this._volume,isMuted:this._isMuted,type:e};this.LOG_ACTIVITY&&this._logger.info(this,"ScreenElement :: Event: onVolumeChange: "+JSON.stringify(t)),this._main.dispatchEvent("volumeChange",{ref:this._main,volume:this._volume,muted:this._isMuted,invokedBy:e})}getVideoElement(){return this._videoElement}}class O{constructor(e){this._containerWidth=0,this._tempContainerWidth=0,this._containerHeight=0,this._tempContainerHeight=0,this._videoWidth=0,this._videoHeight=0,this._scalingMode=n.FILL,this.isInFullScreenMode=!1,this._isResizing=!1,this._autoResizeEnabled=!0,this._parentOriginalOverflow="",this._debug=!1,this.onFullScreenChange=()=>{null==document.fullscreenElement?(this.isInFullScreenMode=!1,this._logger.info(this,"The library has exited FullScreen mode!"),this._main.dispatchEvent("fullScreenExit",{ref:this._main})):(this.isInFullScreenMode=!0,this._logger.info(this,"The library has entered FullScreen mode!"),this._main.dispatchEvent("fullScreenEnter",{ref:this._main}))},this._main=e,this._logger=e.getLogger(),this._logger.info(this,"Creating new StageController"),this.initialize()}initialize(){var e=null!=(e=null==(e=null==(e=null==(e=this._main.getConfigManager())?void 0:e.getSettingsData())?void 0:e.getVideoData())?void 0:e.containerID)?e:null,t=(this._scalingMode=null!=(t=null==(t=this._main.getConfigManager())?void 0:t.getSettingsData().getVideoData().scalingMode)?t:n.FILL,this._debug=null!=(t=null==(t=this._main.getConfigManager())?void 0:t.getSettingsData().getDebugData().stageControllerDebug)?t:this._debug,this._videoContainer=document.createElement("div"),this._videoContainer.setAttribute("id","stormStreamer_"+this._main.getStreamerID()),this._videoContainer.style.overflow="hidden",this._videoContainer.style.position="relative",this._videoContainer.classList.add("stormStreamer"),this._screenElement=new G(this._main),this._videoContainer.appendChild(this._screenElement.getVideoElement()),this._main.getConfigManager().getSettingsData().getVideoData().resizeDebounce);this._resizeObserver=0<t?new ResizeObserver(z(()=>()=>{this._autoResizeEnabled&&this.handleResize()},t,{leading:!1,trailing:!0})):new ResizeObserver(()=>{this._autoResizeEnabled&&this.handleResize()}),document.addEventListener("fullscreenchange",this.onFullScreenChange,!1),document.addEventListener("webkitfullscreenchange",this.onFullScreenChange,!1),document.addEventListener("mozfullscreenchange",this.onFullScreenChange,!1),document.addEventListener("webkitendfullscreen",this.onFullScreenChange,!1),this._screenElement.getVideoElement().addEventListener("webkitendfullscreen",this.onFullScreenChange,!1),this._main.addEventListener("metadata",e=>{this._videoWidth=e.videoWidth,this._videoHeight=e.videoHeight,this.handleResize()},!1),e?this.attachToParent(e):this._logger.warning(this,'Could not create HTMLObject for the library - "containerID" was not provided')}attachToParent(e){let t=!1,i=null;return"string"==typeof e?(this._logger.info(this,"Attaching container to ID: "+e),i=document.getElementById(e)):e instanceof HTMLElement&&(this._logger.info(this,"Attaching container to HTMLElement: "+e),i=e),i===this._parentElement?(this._debug&&this._logger.decoratedLog("Attaching Failed (container is the same)","dark-pink"),this._logger.warning(this,"attachToParent :: container is the same"),!1):(i&&this._videoContainer?(this._debug&&this._logger.decoratedLog("Attach To Parent: "+e+" (success)","dark-pink"),this._parentElement=i,this._parentElement.appendChild(this._videoContainer),this._resizeObserver.observe(this._parentElement),this._parentElement.addEventListener("transitionend",()=>{this.handleResize()}),this._main.dispatchEvent("containerChange",{ref:this._main,container:this._parentElement}),this.handleResize(),t=!0):(this._debug&&this._logger.decoratedLog("Attach To Parent: "+e+" (failure - container not found)","dark-pink"),this._logger.warning(this,'attachToParent :: container "'+e+'"+ was not found')),t)}detachFromParent(){this._debug&&this._logger.decoratedLog("Detach From Parent","dark-pink");let e=!1;return null!=this._parentElement&&null!=this._videoContainer?(this._logger.info(this,"Detaching from parent: "+this._videoContainer),this._parentElement.removeChild(this._videoContainer),this._resizeObserver&&(this._resizeObserver.unobserve(this._parentElement),this._resizeObserver.disconnect()),this._autoResizeEnabled&&this._parentElement.removeEventListener("transitionend",this.handleResize),this._main.dispatchEvent("containerChange",{ref:this._main,container:null}),e=!0):this._logger.info(this,"Failed detaching from parent!"),this._parentElement=null,e}handleResize(){this._parentElement&&!this._isResizing&&(this._isResizing=!0,this._parentOriginalOverflow=this._parentElement.style.overflow,this._parentElement.style.overflow="hidden",requestAnimationFrame(()=>{this.calculateNewDimensions(),this._parentElement.style.overflow=this._parentOriginalOverflow,this._isResizing=!1,this._tempContainerWidth===this._containerWidth&&this._tempContainerHeight===this._containerHeight||this._main.dispatchEvent("resizeUpdate",{ref:this._main,width:this._tempContainerWidth,height:this._tempContainerHeight})}))}calculateNewDimensions(){var e=this._main.getConfigManager().getSettingsData().getVideoData().parentSizeCalculationMethod;switch(e){case i.CLIENT_DIMENSIONS:this._tempContainerWidth=this._parentElement.clientWidth,this._tempContainerHeight=this._parentElement.clientHeight;break;case i.BOUNDING_BOX:var t=this._parentElement.getBoundingClientRect();this._tempContainerWidth=t.width,this._tempContainerHeight=t.height;break;case i.FULL_BOX:t=class{static calculateDimensionsWithMargins(e){var t=window.getComputedStyle(e),e=e.getBoundingClientRect(),i=parseFloat(t.paddingLeft),s=parseFloat(t.paddingRight),n=parseFloat(t.paddingTop),r=parseFloat(t.paddingBottom),o=parseFloat(t.borderLeftWidth),a=parseFloat(t.borderRightWidth),h=parseFloat(t.borderTopWidth),t=parseFloat(t.borderBottomWidth);return{width:e.width-i-s-o-a,height:e.height-n-r-h-t}}}.calculateDimensionsWithMargins(this._parentElement);this._tempContainerWidth=t.width,this._tempContainerHeight=t.height}this._logger.info(this,`New dimensions calculated: ${this._tempContainerWidth}x${this._tempContainerHeight} (${e})`),this.resizeVideoContainer(),this.scaleVideo()}resizeVideoContainer(){var e=this._main.getConfigManager().getSettingsData().getVideoData().videoWidthInPixels,t=this._main.getConfigManager().getSettingsData().getVideoData().videoHeightInPixels,i=this._main.getConfigManager().getSettingsData().getVideoData().videoWidthValue,s=this._main.getConfigManager().getSettingsData().getVideoData().videoHeightValue,n=this._main.getConfigManager().getSettingsData().getVideoData().aspectRatio;let r=0,o=0;var a=Number(n.split(":")[0]),h=Number(n.split(":")[1]);"none"==n?(e?r=i:null!=this._parentElement&&(r=this._tempContainerWidth*i/100),t?o=s:null!=this._parentElement&&0==(o=this._tempContainerHeight*s/100)&&0!=this._videoHeight&&0!=this._videoWidth&&(o=this._videoHeight*r/this._videoWidth)):(e?r=i:null!=this._parentElement&&(r=this._tempContainerWidth*i/100),o=r*h/a),this._containerWidth=Math.ceil(r),this._containerHeight=Math.ceil(o),null!==this._videoContainer&&(this._videoContainer.style.width=this._containerWidth+"px",this._videoContainer.style.height=this._containerHeight+"px")}scaleVideo(){if(null!==this._screenElement){let e=0,t=0,i=0,s=0;switch(this._scalingMode){case n.FILL:i=this._containerWidth,s=this._containerHeight;break;case n.CROP:i=this._containerWidth,(s=this._videoHeight*this._containerWidth/this._videoWidth)>=this._containerHeight?(e=0,t=(s-this._containerHeight)/2*-1):(s=this._containerHeight,i=this._videoWidth*this._containerHeight/this._videoHeight,t=0,e=(i-this._containerWidth)/2*-1);break;case n.LETTER_BOX:i=this._containerWidth,(!((s=this._videoHeight*this._containerWidth/this._videoWidth)<=this._containerHeight)||(e=0,t=(s-this._containerHeight)/2*-1,s>this._containerHeight))&&(s=this._containerHeight,i=this._videoWidth*this._containerHeight/this._videoHeight,t=0,e=(i-this._containerWidth)/2*-1);break;case n.ORIGINAL:i=this._videoWidth,s=this._videoHeight,e=(this._videoWidth-this._containerWidth)/-2,t=(this._videoHeight-this._containerHeight)/-2}this._screenElement.getVideoElement().style.left=Math.floor(e)+"px",this._screenElement.getVideoElement().style.top=Math.floor(t)+"px",this._screenElement.getVideoElement().style.width=Math.ceil(i)+"px",this._screenElement.getVideoElement().style.height=Math.ceil(s)+"px",this._screenElement.getVideoElement().style.position="absolute",this._screenElement.getVideoElement().style.objectFit="fill"}}enterFullScreen(){var e;null!=(e=this._screenElement)&&e.getVideoElement().webkitEnterFullScreen?null!=(e=this._screenElement)&&e.getVideoElement().webkitEnterFullScreen():null!=(e=this._screenElement)&&e.getVideoElement().requestFullscreen()}exitFullScreen(){var e;null!=(e=this._screenElement)&&e.getVideoElement().webkitExitFullscreen?document.webkitExitFullscreen():document.exitFullscreen()}isFullScreenMode(){return this.isInFullScreenMode}setDimension(e,t){var i="width"===e?"videoWidth":"videoHeight";let s,n;if("number"==typeof t)n=t,s=!0;else{if("string"!=typeof t)throw new Error(`Unknown value for parameter "${e}" - it must be a number or a string!`);n=parseInt(t),s=t.toLowerCase().endsWith("px")}this._main.getConfigManager().getSettingsData().getVideoData()[i+"Value"]=n,this._main.getConfigManager().getSettingsData().getVideoData()[i+"InPixels"]=s,this.resizeVideoContainer(),this.scaleVideo()}setSize(e,t){this.setDimension("width",e),this.setDimension("height",t)}setWidth(e){this.setDimension("width",e)}setHeight(e){this.setDimension("height",e)}getParentElement(){return this._parentElement}setScalingMode(e){switch(e.toLowerCase()){case"fill":this._scalingMode=n.FILL;break;case"crop":this._scalingMode=n.CROP;break;case"letterbox":this._scalingMode=n.LETTER_BOX;break;case"original":this._scalingMode=n.ORIGINAL}this.scaleVideo()}getContainerWidth(){return this._containerWidth}getContainerHeight(){return this._containerHeight}getScalingModeAsString(){let e="";switch(this._scalingMode){case n.FILL:e="fill";break;case n.CROP:e="crop";break;case n.LETTER_BOX:e="letterbox";break;case n.ORIGINAL:e="original"}return e}getScalingMode(){return this._scalingMode}getScreenElement(){return this._screenElement}getContainer(){return this._videoContainer}destroy(){this.detachFromParent()}}O.LOG_ACTIVITY=!0;class y{constructor(){}addAudio(e,t){let i="",s="",n=!1;for(const r of e.split(/\r\n/))r.length<=0||(0===r.indexOf("m=audio")?i="audio":0===r.indexOf("m=video")&&(i="video"),s=s+r+"\r\n","audio"!==i)||0!=="a=rtcp-mux".localeCompare(r)||n||(s+=t,n=!0);return s}addVideo(e,t){e=e.split(/\r\n/);let i="",s=!1,n=!1;for(const o of e)o.length<=0||(o.includes("a=rtcp-rsize")&&(n=!0),o.includes("a=rtcp-mux"));let r=!1;for(const a of e)a.startsWith("m=video")&&(r=!0),i=i+a+"\r\n",r&&(0==="a=rtcp-rsize".localeCompare(a)&&!s&&n&&(i+=t,s=!0),0==="a=rtcp-mux".localeCompare(a)&&s&&!n&&(i+=t,s=!0),0!=="a=rtcp-mux".localeCompare(a)||s||n||(s=!0));return i}deliverCheckLine(e,t){for(const s in y.SDPOutput){var i=y.SDPOutput[s];if(i.includes(e)){if(e.includes("VP9")||e.includes("VP8")){let e="";for(const n of i.split(/\r\n/))e=e+n+"\r\n";return t.includes("audio")&&(y.audioIndex=parseInt(s)),t.includes("video")&&(y.videoIndex=parseInt(s)),e}return t.includes("audio")&&(y.audioIndex=parseInt(s)),t.includes("video")&&(y.videoIndex=parseInt(s)),i}}return""}checkLine(t){if(t.startsWith("a=rtpmap")||t.startsWith("a=rtcp-fb")||t.startsWith("a=fmtp")){var i=t.split(":");if(1<i.length){i=i[1].split(" ");if(!isNaN(parseInt(i[0]))&&!i[1].startsWith("http")&&!i[1].startsWith("ur")){let e=y.SDPOutput[i[0]];return e=e||"",e+=t+"\r\n",y.SDPOutput[i[0]]=e,!1}}}return!0}getrtpMapID(e){var t=new RegExp("a=rtpmap:(\\d+) (\\w+)/(\\d+)"),e=e.match(t);return e&&3<=e.length?e:null}mungeSDPPublish(e,t){y.SDPOutput={},y.videoChoice=t.videoCodec||"42e01f",y.audioChoice=t.audioCodec||"opus",y.videoIndex=-1,y.audioIndex=-1;const i=t.videoFrameRate?Math.min(Math.max(t.videoFrameRate,1),60):30;let s="";for(const c of e.split(/\r\n/))c.length<=0||this.checkLine(c)&&(s+=c+"\r\n");s=this.addAudio(s,this.deliverCheckLine(y.audioChoice,"audio"));e=(s=this.addVideo(s,this.deliverCheckLine(y.videoChoice,"video"))).split(/\r\n/);s="";let n="header",r=!1;for(const d of e)if(!(d.length<=0))if(0===d.indexOf("m=audio")&&-1!==y.audioIndex){var o=d.split(" ");s+=`${o[0]} ${o[1]} ${o[2]} ${y.audioIndex}\r\n`,n="audio",r=!1}else if(0===d.indexOf("m=video")&&-1!==y.videoIndex){o=d.split(" ");s=(s=(s=(s+=`${o[0]} ${o[1]} ${o[2]} ${y.videoIndex}\r\n`)+`a=framerate:${i}\r
|
|
15
15
|
`)+`a=x-google-max-framerate:${i}\r
|
|
16
16
|
`)+`a=max-fr:${i}\r
|
|
17
17
|
`,n="video",r=!1}else{s+=d,0===d.indexOf("a=rtpmap")&&(null===(h=this.getrtpMapID(d))||"vp9"!==(a=h[2].toLowerCase())&&"vp8"!==a&&"h264"!==a||(s+=(a=h[1],void 0,`\r
|
|
@@ -31,4 +31,4 @@ b=TIAS:${1e3*(1e3*l*.95-16e3)}\r
|
|
|
31
31
|
`+`b=CT:${l}\r
|
|
32
32
|
`)+`a=framerate:${i}\r
|
|
33
33
|
`)+`a=max-fr:${i}\r
|
|
34
|
-
`;continue}s+="\r\n"}return s}mungeSDPPlay(e){let s="";for(const o of e.split(/\r\n/))if(0!==o.length){if(o.includes("profile-level-id")){var n=o.substr(o.indexOf("profile-level-id")+17,6);let e=Number("0x"+n.substr(0,2)),t=Number("0x"+n.substr(2,2)),i=Number("0x"+n.substr(4,2));66<e&&(e=66,t=224,i=31),0===t&&(t=224);var r=("00"+e.toString(16)).slice(-2).toLowerCase()+("00"+t.toString(16)).slice(-2).toLowerCase()+("00"+i.toString(16)).slice(-2).toLowerCase();s+=o.replace(n,r)}else s+=o;s+="\r\n"}return s}}y.SDPOutput={},(p=L=L||{})[p.VIDEO_INPUT=0]="VIDEO_INPUT",p[p.AUDIO_INPUT=1]="AUDIO_INPUT";class N{constructor(e,t){if(this._groupID="",this._isSelected=!1,null==e)throw new Error("no input device");if(void 0===e.deviceId||null===e.deviceId)throw new Error("no deviceID");if(this._id=e.deviceId,void 0===e.kind||null===e.kind)throw new Error("no device kind");switch(e.kind){case"videoinput":this._inputType=L.VIDEO_INPUT;break;case"audioinput":this._inputType=L.AUDIO_INPUT;break;default:throw new Error("incorrect kind")}null!==e.label&&""!==e.label?this._label=this.cleanLabel(e.label):this._label=this._inputType==L.VIDEO_INPUT?"Camera "+t:"Microphone "+t,void 0!==e.groupId&&null!==e.groupId&&(this._groupID=e.groupId)}cleanLabel(e){return e}getLabel(){return this._label}getID(){return this._id}getGroupID(){return this._groupID}getIfSelected(){return this._isSelected}setSelected(e){this._isSelected=e}}class R{constructor(){this._internalList=new Array}push(t){let i=!1;if(0<this._internalList.length){for(let e=0;e<this._internalList.length;e++)""!==this._internalList[e].getGroupID()&&this._internalList[e].getGroupID()==t.getGroupID()&&(i=!0,this._internalList[e]=t);return 0==i?this._internalList.push(t):this._internalList.length}return this._internalList.push(t)}get(e){return this._internalList[e]}getSize(){return this._internalList.length}getArray(){return this._internalList}}h.PublishState=void 0,(D=h.PublishState||(h.PublishState={})).NOT_INITIALIZED="NOT_INITIALIZED",D.INITIALIZED="INITIALIZED",D.CONNECTING="CONNECTING",D.CONNECTED="CONNECTED",D.PUBLISHED="PUBLISHED",D.UNPUBLISHED="UNPUBLISHED",D.STOPPED="STOPPED",D.UNKNOWN="UNKNOWN",D.ERROR="ERROR";class K{constructor(e){this._audioContext=null,this._analyser=null,this._microphone=null,this._lastEventTime=0,this.THROTTLE_INTERVAL=100,this._isMonitoring=!1,this._instant=0,this._slow=0,this._main=e}attach(e){if(e.getAudioTracks().length){this.detach();try{this._audioContext=new AudioContext,this._microphone=this._audioContext.createMediaStreamSource(e),this._analyser=this._audioContext.createAnalyser(),this._analyser.fftSize=2048,this._analyser.smoothingTimeConstant=.3,this._microphone.connect(this._analyser),this.startMonitoring()}catch(e){console.error("SoundMeter: Error during attach:",e),this.detach()}}else console.warn("SoundMeter: Attempted to attach stream without audio tracks")}detach(){var e,t;if(this._isMonitoring=!1,this._microphone){try{this._microphone.disconnect()}catch(e){console.warn("SoundMeter: Error disconnecting microphone:",e)}this._microphone=null}if(this._analyser){try{this._analyser.disconnect()}catch(e){console.warn("SoundMeter: Error disconnecting analyser:",e)}this._analyser=null}if("closed"!==(null==(e=this._audioContext)?void 0:e.state))try{null!=(t=this._audioContext)&&t.close()}catch(e){console.warn("SoundMeter: Error closing audio context:",e)}this._audioContext=null,this.clear()}clear(){this._instant=0,this._slow=0,this._lastEventTime=0}startMonitoring(){if(this._analyser&&!this._isMonitoring){this._isMonitoring=!0;const n=new Float32Array(this._analyser.frequencyBinCount),t=()=>{if(this._analyser&&this._isMonitoring){var e=Date.now();try{this._analyser.getFloatTimeDomainData(n);let t=0,i=0;for(let e=0;e<n.length;++e){var s=n[e];t+=s*s,.99<Math.abs(s)&&(i+=1)}this._instant=Math.sqrt(t/n.length),this._slow=.05*this._instant+.95*this._slow,e-this._lastEventTime>=this.THROTTLE_INTERVAL&&(this._lastEventTime=e,this._main.dispatchEvent("soundMeter",{ref:this._main,high:this._instant,low:this._slow}))}catch(e){return console.error("SoundMeter: Error during analysis:",e),void(this._isMonitoring=!1)}requestAnimationFrame(t)}};requestAnimationFrame(t)}}}h.StreamerState=void 0,(p=h.StreamerState||(h.StreamerState={})).NOT_INITIALIZED="NOT_INITIALIZED",p.INITIALIZED="INITIALIZED",p.READY="READY",p.UPDATING="UPDATING",p.INVALID="INVALID",p.UNKNOWN="UNKNOWN",p.STOPPED="STOPPED",h.DeviceState=void 0,(D=h.DeviceState||(h.DeviceState={})).NOT_INITIALIZED="NOT_INITIALIZED",D.ENABLED="ENABLED",D.ACCESS_DENIED="ACCESS_DENIED",D.NOT_FOUND="NOT_FOUND",D.STOPPED="STOPPED",(p=M=M||{})[p.NOT_INITIALIZED=0]="NOT_INITIALIZED",p[p.STARTED=1]="STARTED",p[p.CONNECTING=2]="CONNECTING",p[p.CONNECTED=3]="CONNECTED",p[p.CLOSED=4]="CLOSED",p[p.FAILED=5]="FAILED";class k{constructor(){this.CONNECTION_TIMEOUT=5,this.isBinary=!0,this._connectionState=M.NOT_INITIALIZED,this._messageCount=0,this._disconnectedByUser=!1,this._isConnected=!1,this._sequenceNumber=-1}startConnection(){this._disconnectedByUser=!1,this._messageCount=0,this._isConnected=!1,this._disconnectedByUser=!1,this._connectionState=M.CONNECTING,this.socket=new WebSocket(this.socketURL),this.isBinary&&(this.socket.binaryType="arraybuffer"),this.socket.onopen=e=>{clearTimeout(this._connectionTimeout),this._sequenceNumber++,this._connectionState=M.CONNECTED,this.onSocketOpen(e)},this.socket.onmessage=e=>{this._messageCount++,this.onSocketMessage(e)},this.socket.onclose=e=>{clearTimeout(this._connectionTimeout),this._connectionState==M.CONNECTED?(this._connectionState=M.CLOSED,this.onSocketClose(e)):this._connectionState=M.FAILED},this.socket.onerror=e=>{if(clearTimeout(this._connectionTimeout),this._connectionState==M.CONNECTING&&this.onSocketError(e),this._connectionState==M.CONNECTED)try{this.socket.close()}catch(e){}},this._connectionTimeout=setTimeout(()=>{try{this.socket.close()}catch(e){}this._connectionState==M.CONNECTING&&(this._connectionState=M.FAILED,this.onSocketError(new ErrorEvent("connectionTimeout")))},1e3*this.CONNECTION_TIMEOUT)}onSocketOpen(e){}onSocketClose(e){}onSocketMessage(e){}onSocketError(e){}onError(e){}sendData(e){if(this._connectionState==M.CONNECTED&&null!==this.socket){if(null!=e)return void this.socket.send(e);this.onError("no data to send")}this.onError("socket not connected")}getConnectionState(){return this._connectionState}disconnect(e=!0){this._isConnected=!1,this._connectionState=M.CLOSED,e&&(this._logger.warning(this,"Disconnected by user"),this._disconnectedByUser=e),null!=this.socket&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close())}destroy(){void 0!==this.socket&&null!==this.socket&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this._connectionState=M.CLOSED}getSocketURL(){return this.socketURL}}class ${constructor(){this._publishState=h.PublishState.NOT_INITIALIZED,this._videoPublishBitrate=0,this._audioPublishBitrate=0,this._currentBitrate=0,this._audioFrameCount=0,this._videoFrameCount=0,this._frameRate=0,this._videoWidth=0,this._videoHeight=0}get publishState(){return this._publishState}set publishState(e){this._publishState="published"===e?h.PublishState.PUBLISHED:h.PublishState.CONNECTED}get videoPublishBitrate(){return this._videoPublishBitrate}set videoPublishBitrate(e){this._videoPublishBitrate=e}get audioPublishBitrate(){return this._audioPublishBitrate}set audioPublishBitrate(e){this._audioPublishBitrate=e}set currentBitrate(e){this._currentBitrate=e}get currentBitrate(){return this._currentBitrate}get audioFrameCount(){return this._audioFrameCount}set audioFrameCount(e){this._audioFrameCount=e}get videoFrameCount(){return this._videoFrameCount}set videoFrameCount(e){this._videoFrameCount=e}get frameRate(){return this._frameRate}set frameRate(e){this._frameRate=e}set videoWidth(e){this._videoWidth=e}get videoWidth(){return this._videoWidth}set videoHeight(e){this._videoHeight=e}get videoHeight(){return this._videoHeight}}class Z extends k{constructor(e,t){super(),this._logger=e.getLogger(),this._main=e,this._currServer=t,this.initialize()}initialize(){this._logger.info(this,"Starting new status check connection with a storm server"),null!=this._currServer?(this.socketURL=this.createURL(this._currServer),this._logger.info(this,"Starting WebSocket connection with: "+this.socketURL),this.startConnection()):this._logger.error(this,"Connection with the server could not be initialized!")}onSocketOpen(e){this._logger.success(this,"Connection with the server has been established!"),this._main.dispatchEvent("statusServerConnect",{ref:this._main,serverURL:this.socketURL,sequenceNum:this._sequenceNumber}),this._isConnected=!0}onSocketError(e){this._isConnected=!1,this._disconnectedByUser||(this._logger.error(this,"Connection with the server failed"),this._main.dispatchEvent("serverConnectionError",{ref:this._main,serverURL:this.socketURL,restart:this._main.getConfigManager().getSettingsData().getIfRestartOnError(),sequenceNum:this._sequenceNumber}))}onSocketClose(e){this._isConnected=!1,this._disconnectedByUser?this._logger.warning(this,"Force disconnect from server!"):(this._logger.error(this,"Connection with the server has been closed"),this._main.dispatchEvent("statusServerDisconnect",{ref:this._main,serverURL:this.socketURL,restart:this._main.getConfigManager().getSettingsData().getIfRestartOnError(),sequenceNum:this._sequenceNumber}),this.initiateReconnect())}onSocketMessage(e){var t;"string"==typeof e.data&&"STREAM_STATUS_RESPONSE"===(e=JSON.parse(e.data)).packetID&&((t=new $).publishState=e.streamStatus,t.videoPublishBitrate=e.publishVideoBitrate,t.audioPublishBitrate=e.publishAudioBitrate,t.videoFrameCount=e.videoFrameCount,t.audioFrameCount=e.audioFrameCount,t.frameRate=e.frameRate,t.videoWidth=e.videoWidth,t.videoHeight=e.videoHeight,t.currentBitrate=e.realBitrate,console.log(t),this._main.dispatchEvent("streamStatusUpdate",{ref:this._main,streamStatus:t}))}initiateReconnect(){var e=this._main.getConfigManager().getSettingsData().getIfRestartOnError();const t=this._main.getConfigManager().getSettingsData().getReconnectTime();this._disconnectedByUser||e&&(null!=this._reconnectTimer&&clearTimeout(this._reconnectTimer),this._reconnectTimer=setTimeout(()=>{null!=this._currServer&&(this._logger.info(this,`Will reconnect to the server in ${t} seconds...`),this.socketURL=this.createURL(this._currServer),this._logger.info(this,"Starting WebSocket connection with: "+this.socketURL),this._main.dispatchEvent("serverConnectionInitiate",{ref:this._main,serverURL:this.socketURL}),this.startConnection())},1e3*t))}createURL(e){var t="";return(t+=e.getIfSSL()?"wss://":"ws://")+e.getHost()+(":"+e.getPort())+"/statuschecker"}isConnectionActive(){return this._isConnected}getCurrentServer(){return this._currServer}destroy(){super.destroy()}}class X{constructor(){this._streamWidth=0,this._streamHeight=0,this._aspectRatio="",this._hasVideoTrack=!1,this._hasAudioTrack=!1}get streamWidth(){return this._streamWidth}set streamWidth(e){this._streamWidth=e}get streamHeight(){return this._streamHeight}set streamHeight(e){this._streamHeight=e}get aspectRatio(){return this._aspectRatio}set aspectRatio(e){this._aspectRatio=e}get videoTrackPresent(){return this._hasVideoTrack}set videoTrackPresent(e){this._hasVideoTrack=e}get audioTrackPresent(){return this._hasAudioTrack}set audioTrackPresent(e){this._hasAudioTrack=e}}class j{constructor(e){var t;this._isWindowActive=!0,this._peerConnectionConfig={iceServers:[]},this._isMicrophoneMuted=!1,this._pendingMicrophoneState=null,this._permissionChecked=!1,this._constraints={video:{width:{min:"640",ideal:"1024",max:"1024"},height:{min:"360",ideal:"576",max:"576"},frameRate:{min:24,ideal:30,max:30}},audio:!0},this._restartTimerCount=0,this._restartTimerMaxCount=5,this._publishState=h.PublishState.NOT_INITIALIZED,this._publishTime=0,this._inputDeviceState=h.StreamerState.NOT_INITIALIZED,this._cameraState=h.DeviceState.NOT_INITIALIZED,this._microphoneState=h.DeviceState.NOT_INITIALIZED,this._publishTimer=0,this._currentOrientation=(null==(t=window.screen.orientation)?void 0:t.type)||"",this._statusTimer=null,this._debug=!1,this.onDeviceStateChange=e=>{var t=null==(t=this._main.getConfigManager())?void 0:t.getStreamData().streamKey;e.state==h.StreamerState.READY&&null!=t&&this.publish(t)},this.handleOrientationChange=()=>r(this,void 0,void 0,function*(){yield new Promise(e=>setTimeout(e,500));var e=(null==(e=window.screen.orientation)?void 0:e.type)||"";if(this._currentOrientation!==e){this._logger.info(this,`Orientation changed from ${this._currentOrientation} to `+e),this._currentOrientation=e;e=null==(e=this._main.getConfigManager())?void 0:e.getStreamData().streamKey;this._publishState,h.PublishState.PUBLISHED,this.closeWebRTCConnection(),this._stream&&(this._stream.getTracks().forEach(e=>{e.stop()}),this._stream=null);try{yield this.startCamera(),e&&this.publish(e)}catch(e){this._logger.error(this,"Error restarting stream after orientation change: "+JSON.stringify(e)),this.setInputDeviceState(h.StreamerState.INVALID)}}}),this.onServerDisconnect=()=>{},this.onStreamKeyTaken=()=>{null!=this._restartTimer&&(clearInterval(this._restartTimer),this._restartTimerCount=0),this._logger.info(this,"WebRTCStreamer :: Starting StreamKeyTaken Interval"),this.setPublishState(h.PublishState.ERROR),this._restartTimer=setInterval(()=>{var e;null!=this._restartTimer&&(this._restartTimerCount<this._restartTimerMaxCount?(this._logger.info(this,"WebRTCStreamer :: StreamKeyTaken Interval: "+this._restartTimerCount+"/"+this._restartTimerMaxCount),this._restartTimerCount++):(clearInterval(this._restartTimer),this._restartTimer=null,this._restartTimerCount=0,null!=(e=null==(e=null==(e=this._main.getConfigManager())?void 0:e.getStreamData())?void 0:e.streamKey)&&this.publish(e)),e=null!=(e=this._main.getConfigManager().getStreamData().streamKey)?e:"unknown",this._main.dispatchEvent("streamKeyInUseInterval",{ref:this._main,streamKey:e,count:this._restartTimerCount,maxCount:this._restartTimerMaxCount}))},1e3)},this.onServerConnect=()=>{if(this._peerConnection&&this.closeWebRTCConnection(),this._peerConnection=new RTCPeerConnection(this._peerConnectionConfig),this._stream){var e,t=this._stream.getTracks();for(e in t)this._peerConnection.addTrack(t[e],this._stream)}this._peerConnection.onicecandidate=e=>{this.onIceCandidate(e)},this._peerConnection.onconnectionstatechange=e=>{this.onConnectionStateChange(e)},this._peerConnection.onnegotiationneeded=e=>r(this,void 0,void 0,function*(){if(this._peerConnection)try{var e=yield this._peerConnection.createOffer();yield this.onDescriptionSuccess(e)}catch(e){this.onDescriptionError(e),console.error("Error creating offer:",e)}}),this.createStatusConnection()},this.onStatusServerConnect=()=>{var e=this._main.getConfigManager().getStreamData().streamKey;null==this._statusTimer&&null!=this._statusConnection&&null!=e&&(this._statusTimer=setInterval(()=>{this.requestStatusData()},1e3))},this.requestStatusData=()=>{var e,t=this._main.getConfigManager().getStreamData().streamKey;null!=(e=this._statusConnection)&&e.sendData('{"packetID":"STREAM_STATUS", "streamKey": "'+t+'"}')},this.onStatusServerDisconnect=()=>{null!=this._statusTimer&&clearInterval(this._statusTimer),this._statusTimer=null},this.onStreamStatsUpdate=e=>{e=e.streamStatus;this._publishState==h.PublishState.PUBLISHED&&e.publishState!=h.PublishState.PUBLISHED&&this.setPublishState(h.PublishState.UNPUBLISHED),this._publishState==h.PublishState.CONNECTED&&e.publishState==h.PublishState.PUBLISHED&&this.setPublishState(h.PublishState.PUBLISHED)},this.onDescriptionSuccess=t=>{var e;const i={applicationName:null==(e=null==(e=this._main.getNetworkController())?void 0:e.getConnection().getCurrentServer())?void 0:e.getApplication(),streamName:null==(e=this._main.getConfigManager())?void 0:e.getStreamData().streamKey,sessionId:"[empty]"};t.sdp=this._mungeSDP.mungeSDPPublish(t.sdp,{audioBitrate:"64",videoBitrate:"1500",videoFrameRate:30,videoCodec:"42e01f",audioCodec:"opus"}),this._peerConnection&&this._peerConnection.setLocalDescription(t).then(()=>{var e;null!=(e=this._main.getNetworkController())&&e.sendMessage('{"direction":"publish", "command":"sendOffer", "streamInfo":'+JSON.stringify(i)+', "sdp":'+JSON.stringify(t)+"}")}).catch(e=>{console.log(e)})},this.visibilityChange=()=>{"hidden"===document.visibilityState?this.onWindowBlur():"visible"===document.visibilityState&&this.onWindowFocus()},this.onWindowBlur=()=>{this._isWindowActive&&this._logger.warning(this,"Player window is no longer in focus!"),this._isWindowActive=!1},this.onWindowFocus=()=>{this._isWindowActive||this._logger.info(this,"Player window is focused again!"),this._isWindowActive=!0},this._main=e,this._logger=e.getLogger(),this._mungeSDP=new y,this._soundMeter=new K(this._main),this._debug=null!=(e=null==(t=this._main.getConfigManager())?void 0:t.getSettingsData().getDebugData().streamerControllerDebug)?e:this._debug,this.initialize()}initialize(){var e,t;return r(this,void 0,void 0,function*(){try{yield this.initializeDevices(),this.setupEventListeners(),this.initializeStream(),this.setupOrientationListener(),this.setupPermissionListeners(),null!=(e=this._main.getConfigManager())&&e.getSettingsData().autoConnect?(this._logger.info(this,"Initializing NetworkController (autoConnect is true)"),null!=(t=this._main.getNetworkController())&&t.initialize()):this._logger.warning(this,"Warning - autoConnect is set to false, switching to standby mode!")}catch(e){this._logger.error(this,"Initialization failed: "+JSON.stringify(e)),this.setInputDeviceState(h.StreamerState.INVALID)}})}setupEventListeners(){this._main.addEventListener("serverConnect",this.onServerConnect,!1),this._main.addEventListener("serverDisconnect",this.onServerDisconnect,!1),this._main.addEventListener("streamKeyInUse",this.onStreamKeyTaken,!1),this._main.addEventListener("statusServerConnect",this.onStatusServerConnect,!1),this._main.addEventListener("statusServerDisconnect",this.onStatusServerDisconnect,!1),this._main.addEventListener("streamStatusUpdate",this.onStreamStatsUpdate,!1),this._main.addEventListener("deviceStateChange",this.onDeviceStateChange,!1),document.addEventListener("visibilitychange",this.visibilityChange),window.addEventListener("blur",this.onWindowBlur),window.addEventListener("focus",this.onWindowFocus)}initializeDevices(){return r(this,void 0,void 0,function*(){try{(yield navigator.mediaDevices.getUserMedia({video:!0,audio:!0})).getTracks().forEach(e=>e.stop()),yield this.grabDevices()}catch(e){this._logger.error(this,"Error initializing devices: "+JSON.stringify(e)),yield this.grabDevices()}})}initializeStream(){(this._selectedCamera||this._selectedMicrophone)&&this.startCamera()}setupPermissionListeners(){navigator.permissions.query({name:"camera"}).then(e=>{e.onchange=()=>{this._permissionChecked=!1,this.handlePermissionChange("camera",e.state)}}),navigator.permissions.query({name:"microphone"}).then(e=>{e.onchange=()=>{this._permissionChecked=!1,this.handlePermissionChange("microphone",e.state)}})}handlePermissionChange(e,t){return r(this,void 0,void 0,function*(){"denied"===t&&(this.setInputDeviceState(h.StreamerState.INVALID),this._publishState==h.PublishState.CONNECTED)&&this.closeStream(),yield this.grabDevices(),"granted"===t&&(yield this.startCamera())})}onCameraStreamSuccess(e){this._logger.success(this,"Camera stream successfully retrieved");var s=e.getVideoTracks()[0],t=e.getAudioTracks()[0],n=new X;if(s){s=s.getSettings();let e=s.width,t=s.height;/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)&&(e>t&&window.innerWidth<window.innerHeight||e<t&&window.innerWidth>window.innerHeight)&&([e,t]=[t,e]),n.streamWidth=e,n.streamHeight=t,n.videoTrackPresent=!0;const a=(e,t)=>t?a(t,e%t):e;var s=a(e,t),r=e/s,s=t/s,o=e/t;let i=r+":"+s;Math.abs(o-16/9)<.1?i=e>t?"16:9":"9:16":Math.abs(o-4/3)<.1&&(i=e>t?"4:3":"3:4"),n.aspectRatio=i}else n.videoTrackPresent=!1;n.audioTrackPresent=!!t,this._logger.info(this,`Publish MetaData :: Resolution: ${n.streamWidth}x${n.streamHeight} | `+`Aspect ratio: ${n.aspectRatio}, `+`Video track: ${n.videoTrackPresent} | Audio track: `+n.audioTrackPresent),this._main.dispatchEvent("publishMetadataUpdate",{ref:this._main,metadata:n}),this._stream=e,null!==this._pendingMicrophoneState?(this.applyMicrophoneState(this._pendingMicrophoneState),this._pendingMicrophoneState=null):this.applyMicrophoneState(!this._isMicrophoneMuted),0<this._stream.getAudioTracks().length&&this._soundMeter.attach(this._stream),null!=this._cameraList&&null!=this._microphoneList||this.grabDevices();r=this._main.getStageController().getScreenElement().getVideoElement();r.srcObject=e,r.autoplay=!0,r.playsInline=!0,r.disableRemotePlayback=!0,r.controls=!1,r.muted=!0,this.setPublishState(h.PublishState.INITIALIZED)}initializeWebRTC(){var e;this._stream?this._peerConnection?(this._logger.info(this,"WebRTC connection already exists, updating stream"),this.updateWebRTCStream()):(this._logger.info(this,"Initializing new WebRTC connection"),null!=(e=this._main.getNetworkController())&&e.start()):this._logger.error(this,"Cannot initialize WebRTC - no camera stream available")}publish(e){return null!=this._statusTimer&&clearInterval(this._statusTimer),this._main.getConfigManager().getStreamData().streamKey==e&&this._publishState==h.PublishState.CONNECTED?(this._logger.warning(this,"Already published!"),!1):(null!=this._main.getConfigManager().getStreamData().streamKey&&this.unpublish(),this._main.getConfigManager().getStreamData().streamKey=e,this.isStreamReady(!0,!0)?(this._debug&&this._logger.decoratedLog("Publishing: "+e,"dark-red"),this._logger.info(this,"Publish: "+e),this.closeWebRTCConnection(),this._main.dispatchEvent("publish",{ref:this._main,streamKey:e}),this.initializeWebRTC(),!0):(this._logger.warning(this,"Cannot publish - stream not ready (missing video or audio track)"),!1))}unpublish(){this._debug&&this._logger.decoratedLog("Unpublish","dark-red"),null!=this._statusConnection&&(this._statusConnection.destroy(),this._statusConnection=null),null!=this._statusTimer&&(clearInterval(this._statusTimer),this._statusTimer=null),clearTimeout(this._publishTimer),this._main.getConfigManager().getStreamData().streamKey=null,this._main.dispatchEvent("unpublish",{ref:this._main}),this.closeStream()}setupOrientationListener(){window.screen&&window.screen.orientation?window.screen.orientation.addEventListener("change",this.handleOrientationChange):window.addEventListener("orientationchange",this.handleOrientationChange)}onUserMediaError(e){return r(this,void 0,void 0,function*(){yield this.grabDevices(),"OverconstrainedError"===e.name&&this._logger.warning(this,"Device constraints not satisfied")})}checkIndividualDeviceAccess(){return r(this,void 0,void 0,function*(){var t={camera:{allowed:!1,available:!1},microphone:{allowed:!1,available:!1}};try{var e=yield navigator.mediaDevices.enumerateDevices(),i=(t.camera.available=e.some(e=>"videoinput"===e.kind),t.microphone.available=e.some(e=>"audioinput"===e.kind),e.some(e=>""!==e.label));if(i)t.camera.allowed=e.some(e=>"videoinput"===e.kind&&""!==e.label),t.microphone.allowed=e.some(e=>"audioinput"===e.kind&&""!==e.label);else try{var s=yield navigator.mediaDevices.getUserMedia({video:t.camera.available,audio:t.microphone.available});t.camera.allowed=0<s.getVideoTracks().length,t.microphone.allowed=0<s.getAudioTracks().length,s.getTracks().forEach(e=>e.stop()),yield this.grabDevices()}catch(e){console.error("Error requesting permissions:",e),t.camera.allowed=!1,t.microphone.allowed=!1}}catch(e){console.error("Error checking devices:",e),t.camera.available=!1,t.microphone.available=!1,t.camera.allowed=!1,t.microphone.allowed=!1}return t})}onSocketMessage(e){var t=JSON.parse(e);switch(Number(t.status)){case 200:this._logger.info(this,"SDP Exchange Successful");var i=t.sdp,s=(void 0!==i&&this._peerConnection.setRemoteDescription(new RTCSessionDescription(i),()=>{},()=>{}),t.iceCandidates);if(void 0!==s)for(var n in s)this._peerConnection&&this._peerConnection.addIceCandidate(new RTCIceCandidate(s[n]));break;case 503:this._logger.error(this,"StreamKey already use");i=null!=(i=this._main.getConfigManager().getStreamData().streamKey)?i:"unknown";this._main.dispatchEvent("streamKeyInUse",{ref:this._main,streamKey:i}),this.setPublishState(h.PublishState.ERROR)}}onConnectionStateChange(e){if(this._logger.info(this,"Connection State Change: "+JSON.stringify(e)),null!==e)switch(e.currentTarget.connectionState){case"connecting":this._logger.info(this,"WebRTCStreamer :: Event: onStreamerConnecting"),this.setPublishState(h.PublishState.CONNECTING);break;case"connected":this._logger.info(this,"WebRTCStreamer :: Event: onStreamerConnected"),this.setPublishState(h.PublishState.CONNECTED),this.muteMicrophone(this._isMicrophoneMuted);break;case"disconnected":this._logger.info(this,"WebRTCStreamer :: Event: onStreamerDisconnected"),this.setPublishState(h.PublishState.UNPUBLISHED);break;case"failed":this._logger.info(this,"WebRTCStreamer :: Event: onPlayerFailed"),this.setPublishState(h.PublishState.ERROR);break;default:this._logger.info(this,"WebRTCStreamer :: Unsupported onConnectionStateChange: "+e.currentTarget.connectionState)}}grabDevices(){return r(this,void 0,void 0,function*(){try{var e,t,i=yield this.checkIndividualDeviceAccess(),s=(this._cameraList=new R,this._microphoneList=new R,this._permissionChecked||(i.camera.allowed?i.camera.available||(this._main.dispatchEvent("noCameraFound",{ref:this._main}),this.setCameraState(h.DeviceState.NOT_FOUND),this.setInputDeviceState(h.StreamerState.INVALID)):(this._main.dispatchEvent("cameraAccessDenied",{ref:this._main}),this.setCameraState(h.DeviceState.ACCESS_DENIED),this.setInputDeviceState(h.StreamerState.INVALID)),i.microphone.allowed?i.microphone.available||(this._main.dispatchEvent("noMicrophoneFound",{ref:this._main}),this.setMicrophoneState(h.DeviceState.NOT_FOUND),this.setInputDeviceState(h.StreamerState.INVALID)):(this._main.dispatchEvent("microphoneAccessDenied",{ref:this._main}),this.setMicrophoneState(h.DeviceState.ACCESS_DENIED),this.setInputDeviceState(h.StreamerState.INVALID))),yield navigator.mediaDevices.enumerateDevices());for(const n of s)n.deviceId&&n.label&&("videoinput"===n.kind&&i.camera.allowed?(e=new N(n,this._cameraList.getSize()),this._cameraList.push(e)):"audioinput"===n.kind&&i.microphone.allowed&&(t=new N(n,this._microphoneList.getSize()),this._microphoneList.push(t)));try{i.camera.allowed&&(this._selectedCamera=this.pickCamera()),i.microphone.allowed&&(this._selectedMicrophone=this.pickMicrophone())}catch(e){this.setInputDeviceState(h.StreamerState.INVALID),this._logger.error(this,"Errror on grab devices: "+JSON.stringify(e))}this._main.dispatchEvent("deviceListUpdate",{ref:this._main,cameraList:this._cameraList.getArray(),microphoneList:this._microphoneList.getArray()}),this._permissionChecked=!0}catch(e){console.error("Error in grabDevices:",e),this._cameraList=new R,this._microphoneList=new R,this._main.dispatchEvent("deviceListUpdate",{ref:this._main,cameraList:this._cameraList.getArray(),microphoneList:this._microphoneList.getArray()}),this._main.dispatchEvent("inputDeviceError",{ref:this._main})}})}selectCamera(t){var e,i;for(let e=0;e<this._cameraList.getSize();e++)this._cameraList.get(e).setSelected(!1);this._selectedCamera=null,this.setInputDeviceState(h.StreamerState.UPDATING),this.setCameraState(h.DeviceState.NOT_INITIALIZED);const s=null==(e=this._main.getConfigManager())?void 0:e.getStreamData().streamKey,n=this._publishState===h.PublishState.CONNECTED;for(let e=0;e<this._cameraList.getSize();e++)if(this._cameraList.get(e).getID()==t){this._selectedCamera=this._cameraList.get(e),this._selectedCamera.setSelected(!0),null!=(i=this._main.getStorageManager())&&i.saveField("cameraID",this._selectedCamera.getID());break}this._main.dispatchEvent("deviceListUpdate",{ref:this._main,cameraList:this._cameraList.getArray(),microphoneList:this._microphoneList.getArray()}),this.stopCameraStream(),null!=this._selectedCamera?(this._constraints.video.deviceId=this._selectedCamera.getID(),this.startCamera().then(()=>{this.setCameraState(h.DeviceState.ENABLED),this._cameraState==h.DeviceState.ENABLED&&this._microphoneState==h.DeviceState.ENABLED?this.setInputDeviceState(h.StreamerState.READY):this.setInputDeviceState(h.StreamerState.INVALID),n&&s&&this.publish(s)})):this.setInputDeviceState(h.StreamerState.INVALID)}selectMicrophone(i){var s,n;return r(this,void 0,void 0,function*(){for(let e=0;e<this._microphoneList.getSize();e++)this._microphoneList.get(e).setSelected(!1);this._selectedMicrophone=null,this.setInputDeviceState(h.StreamerState.UPDATING),this.setMicrophoneState(h.DeviceState.NOT_INITIALIZED),this._logger.info(this,"Selecting microphone: "+i);var e=null==(s=this._main.getConfigManager())?void 0:s.getStreamData().streamKey,t=this._publishState===h.PublishState.CONNECTED;for(let e=0;e<this._microphoneList.getSize();e++)if(this._microphoneList.get(e).getID()==i){this._selectedMicrophone=this._microphoneList.get(e),this._selectedMicrophone.setSelected(!0),null!=(n=this._main.getStorageManager())&&n.saveField("microphoneID",this._selectedMicrophone.getID());break}this._main.dispatchEvent("deviceListUpdate",{ref:this._main,cameraList:this._cameraList.getArray(),microphoneList:this._microphoneList.getArray()}),this._soundMeter.detach(),this.closeWebRTCConnection(),this._stream&&(this._stream.getTracks().forEach(e=>{e.stop()}),this._stream=null);try{yield this.startCamera(),this.setMicrophoneState(h.DeviceState.ENABLED),this._cameraState==h.DeviceState.ENABLED&&this._microphoneState==h.DeviceState.ENABLED?this.setInputDeviceState(h.StreamerState.READY):this.setInputDeviceState(h.StreamerState.INVALID),t&&e&&this.publish(e)}catch(e){console.error("Error changing microphone:",e),this._main.dispatchEvent("inputDeviceError",{ref:this._main}),this.setInputDeviceState(h.StreamerState.INVALID)}})}startCamera(){return r(this,void 0,void 0,function*(){this._stream&&(this._stream.getTracks().forEach(e=>{e.stop()}),this._stream=null);try{var t={video:!!this._selectedCamera&&Object.assign(Object.assign({},this._constraints.video),{deviceId:{exact:this._selectedCamera.getID()}}),audio:!!this._selectedMicrophone&&{deviceId:{exact:this._selectedMicrophone.getID()}}};try{var e=yield navigator.mediaDevices.getUserMedia(t);this._stream=e,this.onCameraStreamSuccess(this._stream)}catch(e){t.video&&this.onUserMediaError({name:e.name||"Error",message:e.message||"Unknown error",deviceType:"video"}),t.audio&&this.onUserMediaError({name:e.name||"Error",message:e.message||"Unknown error",deviceType:"audio"})}this._cameraState==h.DeviceState.ENABLED&&this._microphoneState==h.DeviceState.ENABLED&&this.setInputDeviceState(h.StreamerState.READY)}catch(e){console.error("Error in startCamera:",e),yield this.grabDevices()}})}updateWebRTCStream(){this._peerConnection&&this._stream&&(this._peerConnection.getSenders().forEach(e=>{this._peerConnection&&this._peerConnection.removeTrack(e)}),this._stream.getTracks().forEach(e=>{null!=this._stream&&this._peerConnection&&this._peerConnection.addTrack(e,this._stream)}))}closeStream(){void 0!==this._peerConnection&&null!==this._peerConnection&&this._peerConnection.close(),this.setPublishState(h.PublishState.UNPUBLISHED)}pickCamera(){var e;for(let e=0;e<this._cameraList.getSize();e++)this._cameraList.get(e).setSelected(!1);var i=null!=(e=null==(e=this._main.getStorageManager())?void 0:e.getField("cameraID"))?e:null;if(0<this._cameraList.getSize()){if(i){let t=!1;for(let e=0;e<this._cameraList.getSize();e++)if(this._cameraList.get(e).getID()===i){this._selectedCamera=this._cameraList.get(e),this._selectedCamera.setSelected(!0),this.setCameraState(h.DeviceState.ENABLED),t=!0,this._constraints.video.deviceId=this._selectedCamera.getID();break}if(!t)return this.setCameraState(h.DeviceState.NOT_FOUND),this.setInputDeviceState(h.StreamerState.INVALID),this._main.dispatchEvent("savedCameraNotFound",{ref:this._main,savedDeviceID:i}),null!=(e=this._main.getConfigManager())&&e.getSettingsData().getIfCancelPublishOnError()&&(this._logger.info(this,"Canceling Publish!"),this._main.getConfigManager().getStreamData().streamKey=null),null}if(!this._selectedCamera){if(this._main.dispatchEvent("savedCameraNotFound",{ref:this._main,savedDeviceID:null}),null!=(e=this._main.getConfigManager())&&e.getSettingsData().getIfCancelPublishOnError()&&(this._logger.info(this,"Canceling Publish!"),this._main.getConfigManager().getStreamData().streamKey=null),null==(e=this._main.getConfigManager())||!e.getSettingsData().getIfForceSelection())return this.setCameraState(h.DeviceState.NOT_FOUND),this.setInputDeviceState(h.StreamerState.INVALID),null;this._selectedCamera=this._cameraList.get(0),this._selectedCamera.setSelected(!0),null!=(e=this._main.getStorageManager())&&e.saveField("cameraID",this._selectedCamera.getID()),this._constraints.video.deviceId=this._selectedCamera.getID(),this.setCameraState(h.DeviceState.ENABLED)}}return this._main.dispatchEvent("deviceListUpdate",{ref:this._main,cameraList:this._cameraList.getArray(),microphoneList:this._microphoneList.getArray()}),this._selectedCamera}pickMicrophone(){var e;for(let e=0;e<this._microphoneList.getSize();e++)this._microphoneList.get(e).setSelected(!1);var i=null!=(e=null==(e=this._main.getStorageManager())?void 0:e.getField("microphoneID"))?e:null;if(0<this._microphoneList.getSize()){if(i){let t=!1;for(let e=0;e<this._microphoneList.getSize();e++)if(this._microphoneList.get(e).getID()===i){this._selectedMicrophone=this._microphoneList.get(e),t=!0,this.setMicrophoneState(h.DeviceState.ENABLED);break}if(!t)return this._main.dispatchEvent("savedMicrophoneNotFound",{ref:this._main,savedDeviceID:i}),this.setMicrophoneState(h.DeviceState.NOT_FOUND),this.setInputDeviceState(h.StreamerState.INVALID),null!=(e=this._main.getConfigManager())&&e.getSettingsData().getIfCancelPublishOnError()&&(this._logger.info(this,"Canceling Publish!"),this._main.getConfigManager().getStreamData().streamKey=null),null}if(!this._selectedMicrophone){if(this._main.dispatchEvent("savedMicrophoneNotFound",{ref:this._main,savedDeviceID:null}),null!=(e=this._main.getConfigManager())&&e.getSettingsData().getIfCancelPublishOnError()&&(this._logger.info(this,"Canceling Publish!"),this._main.getConfigManager().getStreamData().streamKey=null),null==(e=this._main.getConfigManager())||!e.getSettingsData().getIfForceSelection())return this.setMicrophoneState(h.DeviceState.NOT_FOUND),this.setInputDeviceState(h.StreamerState.INVALID),null;this._selectedMicrophone=this._microphoneList.get(0),this.setMicrophoneState(h.DeviceState.ENABLED),null!=(e=this._main.getStorageManager())&&e.saveField("microphoneID",this._selectedMicrophone.getID())}this._selectedMicrophone.setSelected(!0),this._constraints.audio={deviceId:this._selectedMicrophone.getID()}}return this._selectedMicrophone}clearSavedDevices(){var e;null!=(e=this._main.getStorageManager())&&e.removeField("cameraID"),null!=(e=this._main.getStorageManager())&&e.removeField("microphoneID")}messSavedDevices(){var e;null!=(e=this._main.getStorageManager())&&e.saveField("cameraID","a"),null!=(e=this._main.getStorageManager())&&e.saveField("microphoneID","b")}muteMicrophone(e){this._isMicrophoneMuted!==e&&(this._isMicrophoneMuted=e,this._stream?this.applyMicrophoneState(!e):(this._pendingMicrophoneState=!e,this._logger.info(this,`WebRTCStreamer :: Stream not yet available, storing microphone state (muted: ${e})`)),this._main.dispatchEvent("microphoneStateChange",{ref:this._main,isMuted:this._isMicrophoneMuted}))}applyMicrophoneState(t){var e;this._stream?(e=this._stream.getAudioTracks())&&0<e.length?(this._logger.success(this,`WebRTCStreamer :: ${t?"Unmuting":"Muting"} microphone`),e.forEach(e=>e.enabled=t)):this._logger.warning(this,"WebRTCStreamer :: No audio tracks found in stream"):this._logger.warning(this,"WebRTCStreamer :: Cannot apply microphone state - stream not available")}isStreamReady(e=!0,t=!0){var i,s;return!!this._stream&&(s=this._stream.getVideoTracks(),i=this._stream.getAudioTracks(),e=!e||0<s.length&&"live"===s[0].readyState,s=!t||0<i.length&&"live"===i[0].readyState,e)&&s}closeWebRTCConnection(){this._peerConnection&&(this._peerConnection.close(),this._peerConnection=null)}onDescriptionError(e){this._logger.info(this,"WebRTCStreamer :: onDescriptionError: "+JSON.stringify(e))}onIceCandidate(e){e.candidate}createStatusConnection(){var e=null==(e=null==(e=null==(e=this._main)?void 0:e.getNetworkController())?void 0:e.getConnection())?void 0:e.getCurrentServer();e&&(this._statusConnection&&!this._statusConnection.isConnectionActive()&&this._statusConnection.destroy(),this._statusConnection=new Z(this._main,e))}isMicrophoneMuted(){return this._isMicrophoneMuted}getCurrentCamera(){return this._selectedCamera}getCurrentMicrophone(){return this._selectedMicrophone}setPublishState(e){this._publishState!=e&&(this._debug&&this._logger.decoratedLog("Publish State: "+e,"dark-blue"),this._logger.info(this,"Publish State: "+e),e==h.PublishState.PUBLISHED&&(this._publishTime=(new Date).getTime()),this._publishState=e,this._main.dispatchEvent("publishStateChange",{ref:this._main,state:this._publishState}))}getPublishTime(){return this._publishState==h.PublishState.PUBLISHED?this._publishTime:0}setInputDeviceState(e){this._inputDeviceState!=e&&(this._inputDeviceState=e,this._main.dispatchEvent("deviceStateChange",{ref:this._main,state:this._inputDeviceState,selectedCamera:this._selectedCamera,selectedMicrophone:this._selectedMicrophone}))}getInputDeviceState(){return this._inputDeviceState}setCameraState(e){this._cameraState!=e&&(this._cameraState=e,this._main.dispatchEvent("cameraDeviceStateChange",{ref:this._main,state:e,selectedCamera:this._selectedCamera}))}getCamerState(){return this._cameraState}setMicrophoneState(e){this._microphoneState!=e&&(this._microphoneState=e,this._main.dispatchEvent("microphoneDeviceStateChange",{ref:this._main,state:e,selectedMicrophone:this._selectedMicrophone}))}getMicrophoneState(){return this._microphoneState}getCameraList(){return null!=this._cameraList?this._cameraList.getArray():[]}getMicrophoneList(){return null!=this._microphoneList?this._microphoneList.getArray():[]}getPublishState(){return this._publishState}stopCameraStream(){var e;this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),(e=null==(e=null==(e=this._main.getStageController())?void 0:e.getScreenElement())?void 0:e.getVideoElement())&&(e.srcObject=null),this._soundMeter.detach(),this._stream=null)}forceStopAllStreams(){var e,t;if(this._peerConnection)try{this._peerConnection.getSenders().forEach(e=>{var t;try{e.track&&(e.track.enabled=!1,e.track.stop(),null!=(t=this._peerConnection))&&t.removeTrack(e)}catch(e){console.error("Error stopping sender track:",e)}}),this._peerConnection.close(),this._peerConnection=null}catch(e){console.error("Error closing peer connection:",e)}try{var i=null==(t=null==(e=this._main.getStageController())?void 0:e.getScreenElement())?void 0:t.getVideoElement();i&&i.srcObject instanceof MediaStream&&(i.srcObject.getTracks().forEach(e=>{try{e.enabled=!1,e.stop()}catch(e){console.error("Error stopping video element track:",e)}}),i.srcObject=null,i.removeAttribute("src"),i.load())}catch(e){console.error("Error cleaning video element:",e)}if(this._stream)try{this._stream.getTracks().forEach(t=>{try{t.enabled=!1,t.stop()}catch(e){console.error(`Error stopping ${t.kind} track:`,e)}}),this._stream=null}catch(e){console.error("Error stopping main stream:",e)}}stop(){this._statusConnection&&(this._statusConnection.destroy(),this._statusConnection=null),this._statusTimer&&(clearInterval(this._statusTimer),this._statusTimer=null),this._main.getConfigManager().getStreamData().streamKey=null,this.closeWebRTCConnection(),this.stopCameraStream(),this.setPublishState(h.PublishState.STOPPED),this.setInputDeviceState(h.StreamerState.STOPPED),this.setCameraState(h.DeviceState.STOPPED),this.setMicrophoneState(h.DeviceState.STOPPED),this._restartTimer&&(clearInterval(this._restartTimer),this._restartTimer=null),this._restartTimerCount=0,clearTimeout(this._publishTimer)}start(){var e,t,i;return r(this,void 0,void 0,function*(){try{this._publishState=h.PublishState.NOT_INITIALIZED,this._inputDeviceState=h.StreamerState.NOT_INITIALIZED,this._cameraState=h.DeviceState.NOT_INITIALIZED,this._microphoneState=h.DeviceState.NOT_INITIALIZED,yield this.initializeDevices(),yield this.startCamera(),null!=(e=this._main.getConfigManager())&&e.getSettingsData().autoConnect&&null!=(t=this._main.getNetworkController())&&t.initialize(),null!=(i=this._main.getConfigManager())&&i.getStreamData().streamKey&&this.createStatusConnection()}catch(e){throw this._logger.error(this,"Start failed: "+JSON.stringify(e)),this.setInputDeviceState(h.StreamerState.INVALID),e}})}destroy(){window.screen&&window.screen.orientation?window.screen.orientation.removeEventListener("change",this.handleOrientationChange):window.removeEventListener("orientationchange",this.handleOrientationChange),this.forceStopAllStreams(),this._soundMeter&&this._soundMeter.detach(),clearTimeout(this._publishTimer),this._pendingMicrophoneState=null,this._cameraList=new R,this._microphoneList=new R,this._permissionChecked=!1,this._isWindowActive=!1,this._isMicrophoneMuted=!1;try{this._main.removeEventListener("serverConnect",this.onServerConnect),this._main.removeEventListener("serverDisconnect",this.onServerDisconnect),document.removeEventListener("visibilitychange",this.visibilityChange),window.removeEventListener("blur",this.onWindowBlur),window.removeEventListener("focus",this.onWindowFocus)}catch(e){console.error("Error removing event listeners:",e)}this._publishState=h.PublishState.NOT_INITIALIZED,null!=this._restartTimer&&clearInterval(this._restartTimer)}}class q extends k{constructor(e,t){super(),this._logger=e.getLogger(),this._main=e,this._networkController=t,this.initialize()}initialize(){this._logger.info(this,"Starting new connection with a storm server"),this.pickServerFromList(this._main.getConfigManager().getStreamData().getServerList()),null!=this._currServer?(this.socketURL=this.createURL(this._currServer),this._logger.info(this,"Starting WebSocket connection with: "+this.socketURL),this._main.dispatchEvent("serverConnectionInitiate",{ref:this._main,serverURL:this.socketURL}),this._main.getConfigManager().getIfDemoMode()?(this._logger.warning(this,"Player is in demo mode, and will not connect with a server!"),this._main.dispatchEvent("authorizationComplete",{ref:this._main})):this.startConnection()):this._logger.error(this,"Connection with the server could not be initialized!")}onSocketOpen(e){this._logger.success(this,"Connection with the server has been established!"),this._main.dispatchEvent("serverConnect",{ref:this._main,serverURL:this.socketURL,sequenceNum:this._sequenceNumber}),this._isConnected=!0}onSocketError(e){this._isConnected=!1,this._disconnectedByUser||(this._logger.error(this,"Connection with the server failed"),this._main.dispatchEvent("serverConnectionError",{ref:this._main,serverURL:this.socketURL,restart:this._main.getConfigManager().getSettingsData().getIfRestartOnError(),sequenceNum:this._sequenceNumber}),0==this._isConnected&&(this._currServer.setAsFaild(!0),this.initiateReconnect()))}onSocketClose(e){this._isConnected=!1,this._disconnectedByUser?this._logger.warning(this,"Force disconnect from server!"):(this._logger.error(this,"Connection with the server has been closed"),this._main.dispatchEvent("serverDisconnect",{ref:this._main,serverURL:this.socketURL,restart:this._main.getConfigManager().getSettingsData().getIfRestartOnError(),sequenceNum:this._sequenceNumber}),this.initiateReconnect())}onSocketMessage(e){this._networkController.onMessage(e)}createURL(e){var t="";return(t+=e.getIfSSL()?"wss://":"ws://")+e.getHost()+(":"+e.getPort())+"/webrtc-session.json"}initiateReconnect(){var e=this._main.getConfigManager().getSettingsData().getIfRestartOnError();const t=this._main.getConfigManager().getSettingsData().getReconnectTime();this._disconnectedByUser||e&&(null!=this._reconnectTimer&&clearTimeout(this._reconnectTimer),this._reconnectTimer=setTimeout(()=>{this.pickServerFromList(this._main.getConfigManager().getStreamData().getServerList()),null!=this._currServer&&(this._logger.info(this,`Will reconnect to the server in ${t} seconds...`),this.socketURL=this.createURL(this._currServer),this._logger.info(this,"Starting WebSocket connection with: "+this.socketURL),this._main.dispatchEvent("serverConnectionInitiate",{ref:this._main,serverURL:this.socketURL}),this.startConnection())},1e3*t))}pickServerFromList(t){let i=null;for(let e=0;e<t.length;e++)if(!t[e].getIfFaild()){i=t[e];break}null==i?(this._logger.error(this,"All connections failed!"),this._main.dispatchEvent("allConnectionsFailed",{ref:this._main,mode:"none"}),this._currServer=null):this._currServer=i}isConnectionActive(){return this._isConnected}getCurrentServer(){return this._currServer}destroy(){super.destroy(),null!=this._reconnectTimer&&clearTimeout(this._reconnectTimer)}}class Y{constructor(e){this._currentStreamKey="none",this._lastState="",this.onServerConnect=()=>{},this.onServerDisconnect=()=>{this._lastState="none"},this.onMessage=e=>{var t;null!=(t=this._main.getStreamerController())&&t.onSocketMessage(e.data)},this._main=e,this._logger=e.getLogger(),this._main.addEventListener("serverConnect",this.onServerConnect,!1),this._main.addEventListener("serverDisconnect",this.onServerDisconnect,!1)}initialize(){null!=this._connection&&(this._connection.getConnectionState()==M.CONNECTING||this._connection.getConnectionState()==M.CONNECTED?this._logger.info(this,"Connection is alive, not doing anything!"):(this._logger.info(this,"Connection is dead, restarting!"),this._connection.startConnection()))}start(){this._connection=new q(this._main,this)}stop(){this._connection.disconnect(!0),this._lastState=""}sendMessage(e){this._connection.isConnectionActive()&&this._connection.sendData(e)}getConnection(){return this._connection}getCurrentStreamKey(){return this._currentStreamKey}}class J{constructor(e){this._publishVideoWidth=0,this._publishVideoHeight=0,this._publishVideoBitrate=0,this._publishAudioBitrate=0,this._currentBitrate=0,this._currentFPS=0,this._deliveredVideoFrames=0,this._deliveredAudioFrames=0,this.onStreamStatsUpdate=e=>{this._publishVideoWidth=e.streamStatus.videoWidth,this._publishVideoHeight=e.streamStatus.videoHeight,this._currentBitrate=e.streamStatus.currentBitrate,this._publishVideoBitrate=e.streamStatus.videoPublishBitrate,this._publishAudioBitrate=e.streamStatus.audioPublishBitrate,this._currentFPS=e.streamStatus.frameRate,this._deliveredVideoFrames=e.streamStatus.videoFrameCount,this._deliveredAudioFrames=e.streamStatus.audioFrameCount},this._main=e,this._logger=e.getLogger(),this._logger.info(this,"Creating new StatsController"),this.initialize()}initialize(){this._main.addEventListener("streamStatusUpdate",this.onStreamStatsUpdate,!1)}get deliveredVideoFrames(){return this._deliveredVideoFrames}get deliveredAudioFrames(){return this._deliveredAudioFrames}get currentFPS(){return this._currentFPS}get publishVideoWidth(){return this._publishVideoWidth}get publishVideoHeight(){return this._publishVideoHeight}get currentBitrate(){return this._currentBitrate}get publishVideoBitrate(){return this._publishVideoBitrate}get publishAudioBitrate(){return this._publishAudioBitrate}}class P{constructor(e,t,i,s=1){if(this._currentX=0,this._isFullyDrawn=!1,this._lastTimestamp=null,this._isTimemarkLine=!1,this._borderWidth=1,i.length!==t.length+1)throw new Error(`Colors array must have exactly ${t.length+1} elements (one more than valueRanges)`);for(let e=1;e<t.length;e++)if(t[e]<=t[e-1])throw new Error("ValueRanges must be in ascending order");const n=/^#[0-9A-Fa-f]{6}$/;if(!i.every(e=>n.test(e)))throw new Error("All colors must be in valid hex format (e.g., #FF0000)");let r;if("string"==typeof e){var o=document.getElementById(e);if(!o)throw new Error(`Container element with id ${e} not found`);r=o}else r=e;o=r.getBoundingClientRect(),this._width=Math.floor(o.width),this._height=Math.floor(o.height),this._effectiveWidth=this._width-2*this._borderWidth,this._effectiveHeight=this._height-2*this._borderWidth,this._canvas=document.createElement("canvas"),r.appendChild(this._canvas),e=this._canvas.getContext("2d",{willReadFrequently:!0});if(!e)throw new Error("Failed to get canvas context");this._ctx=e,this._valueRanges=[0,...t],this._colors=i,this._lineWidth=s,this._canvas.width=this._width,this._canvas.height=this._height,this._canvas.style.width=this._width+"px",this._canvas.style.height=this._height+"px",this.clear()}drawBorder(){this._ctx.strokeStyle="#000000",this._ctx.lineWidth=this._borderWidth,this._ctx.strokeRect(this._borderWidth/2,this._borderWidth/2,this._width-this._borderWidth,this._height-this._borderWidth)}clear(){this._ctx.clearRect(0,0,this._width,this._height),this._ctx.fillStyle=this._colors[0],this._ctx.fillRect(this._borderWidth,this._borderWidth,this._effectiveWidth,this._effectiveHeight),this.drawBorder(),this._isFullyDrawn=!1,this._currentX=this._borderWidth,this._lastTimestamp=null,this._isTimemarkLine=!1}getColorIndices(t){for(let e=0;e<this._valueRanges.length-1;e++)if(t>=this._valueRanges[e]&&t<=this._valueRanges[e+1])return{lowerIndex:e,upperIndex:e+1};return{lowerIndex:this._valueRanges.length-2,upperIndex:this._valueRanges.length-1}}calculateHeightRatio(e,t,i){return(e-t)/(i-t)}shiftCanvasLeft(e){e=this._ctx.getImageData(this._borderWidth+e,this._borderWidth,this._effectiveWidth-e,this._effectiveHeight);this._ctx.fillStyle=this._colors[0],this._ctx.fillRect(this._borderWidth,this._borderWidth,this._effectiveWidth,this._effectiveHeight),this._ctx.putImageData(e,this._borderWidth,this._borderWidth),this.drawBorder()}applyOverlayEffect(e,s=.5){var t=parseInt(e.slice(1,3),16),i=parseInt(e.slice(3,5),16),e=parseInt(e.slice(5,7),16),n=e=>{var t=e/255;let i;return i=t<=.5?2*t*1:1-2*(1-t)*0,Math.round(255*i*s+e*(1-s))},t=n(t),i=n(i),n=n(e),e=e=>{e=e.toString(16);return 1===e.length?"0"+e:e};return"#"+e(t)+e(i)+e(n)}addEntry(e){e=Math.round(100*e)/100;var t=Date.now(),t=(null===this._lastTimestamp?(this._lastTimestamp=t,this._isTimemarkLine=!1):1e3<=t-this._lastTimestamp?(this._isTimemarkLine=!0,this._lastTimestamp=t):this._isTimemarkLine=!1,this._isTimemarkLine?1:this._lineWidth);!this._isFullyDrawn&&this._currentX>=this._width-this._borderWidth&&(this._isFullyDrawn=!0),this._isFullyDrawn?(this.shiftCanvasLeft(t),this.drawLine(this._width-this._borderWidth-t,e,t)):(this.drawLine(this._currentX,e,t),this._currentX+=t)}drawLine(e,t,i){var{lowerIndex:s,upperIndex:n}=this.getColorIndices(t),t=this.calculateHeightRatio(t,this._valueRanges[s],this._valueRanges[n]);let r=this._colors[s],o=this._colors[n];this._isTimemarkLine&&(r=this.applyOverlayEffect(r,.3),o=this.applyOverlayEffect(o,.3));s=Math.round(this._effectiveHeight*t),n=this._effectiveHeight-s;this._ctx.fillStyle=r,this._ctx.fillRect(e,this._height-this._borderWidth-n,i,n),this._ctx.fillStyle=o,this._ctx.fillRect(e,this._borderWidth,i,s)}clearGraph(){this._currentX=this._borderWidth,this._isFullyDrawn=!1,this._lastTimestamp=null,this._isTimemarkLine=!1,this.clear()}destroy(){this._canvas.parentNode&&this._canvas.parentNode.removeChild(this._canvas)}}class Q{constructor(e,t){this.onStreamStatsUpdate=e=>{var t;null!=(t=this._graph)&&t.addEntry(e.streamStatus.currentBitrate)},this._main=e,this._object=t,this._main.addGraph(this)}start(){null!=this._graph&&stop();return this._graph=new P(this._object,[1e6,2e6,3e6,5e6,6e6,7e6],["#000000","#0a3980","#2793dd","#3bc39c","#c3df3e","#f89539","#f83f3f"]),this._main.addEventListener("streamStatusUpdate",this.onStreamStatsUpdate),this}stop(){return this._main.removeEventListener("streamStatusUpdate",this.onStreamStatsUpdate),null!=this._graph&&this._graph.destroy(),this._graph=null,this}}class ee{constructor(e,t){this.onStreamStatsUpdate=e=>{var t;null!=(t=this._graph)&&t.addEntry(e.streamStatus.frameRate)},this._main=e,this._object=t,this._main.addGraph(this)}start(){null!=this._graph&&stop();return this._graph=new P(this._object,[25,26,27,28,29,30],["#000000","#0a3980","#2793dd","#3bc39c","#c3df3e","#f89539","#f83f3f"]),this._main.addEventListener("streamStatusUpdate",this.onStreamStatsUpdate),this}stop(){return this._main.removeEventListener("streamStatusUpdate",this.onStreamStatsUpdate),null!=this._graph&&this._graph.destroy(),this._graph=null,this}}class A extends class{constructor(){this._isRemoved=!1,this._listeners={}}addEventListener(t,i,e=!0){this._listeners[t]||(this._listeners[t]=[]);let s=!1;if(null!=this._listeners[t]&&0<this._listeners[t].length)for(let e=0;e<this._listeners[t].length;e++)if(this._listeners[t][e][1]==i){s=!0;break}return this._logger.success(this,"Registering a new event: "+t),!s&&(this._listeners[t].push([t,i,e]),!0)}removeEventListener(t,i){let s=!1;if(null!=this._listeners[t]&&0<this._listeners[t].length)for(let e=0;e<this._listeners[t].length;e++){var n=this._listeners[t][e];if(i){if(n[1]==i){if(1!=n[2])break;s=!0,this._listeners[t].splice(e,1);break}}else s=!0,1==n[2]&&this._listeners[t].splice(e,1)}return this._logger.success(this,"Removing listener: "+t),s}removeAllEventListeners(){this._logger.success(this,"Removing all listeners!");for(const i in this._listeners){var e=i,t=this._listeners[e];if(t&&0<t.length)for(let e=t.length-1;0<=e;e--)!0===t[e][2]&&t.splice(e,1)}}dispatchEvent(t,i){if(!this._isRemoved&&null!=this._listeners[t]&&0<this._listeners[t].length)for(let e=0;e<this._listeners[t].length;e++)this._listeners[t][e][1].call(this,i)}}{constructor(e,t=!1){super(),this.DEV_MODE=!0,this.STREAMER_VERSION="0.9.2-beta.0",this.COMPILE_DATE="3/6/2025, 12:46:45 PM",this.STREAMER_BRANCH="Experimental",this.STREAMER_PROTOCOL_VERSION=1,this._initialized=!1,"undefined"!=typeof window&&window.document&&window.document.createElement?(!this.DEV_MODE||"StormStreamerArray"in window||(window.StormStreamerArray=[]),window.StormStreamerArray.push(this),this._streamerID=A.NEXT_STREAMER_ID++,null!=e&&(this.setStreamConfig(e),t)&&this.initialize()):console.error('StormStreamer Creation Error - No "window" element in the provided context!')}initialize(){if(!this._isRemoved){if(null==this._configManager)throw Error("Stream Config was not provided for this streamer! A properly configured object must be provided through the constructor or via the setConfig method before using the initialize() method.");this._storageManager=new e(this),this._stageController=new O(this),this._networkController=new Y(this),this._streamerController=new j(this),this._statsController=new J(this),this._graphs=[],this._initialized=!0,this.dispatchEvent("streamerReady",{ref:this})}}setStreamConfig(e){this._isRemoved||(e=JSON.parse(JSON.stringify(e)),null==this._configManager?(this._configManager=new u(e),this._logger=new m(this._configManager.getSettingsData().getDebugData(),this),this._logger.info(this,"StreamerID: "+this._streamerID),this._logger.info(this,"Version: "+this.STREAMER_VERSION+" | Compile Date: "+this.COMPILE_DATE+" | Branch: "+this.STREAMER_BRANCH),this._logger.info(this,"UserCapabilities :: Browser: "+v.getBrowserName()+" "+v.getBrowserVersion()),this._logger.info(this,"UserCapabilities :: Operating System: "+v.getOS()+" "+v.getOSVersion()),this._logger.info(this,"UserCapabilities :: isMobile: "+v.isMobile()),this._logger.info(this,"UserCapabilities :: hasMSESupport: "+v.hasMSESupport()),this._logger.info(this,"UserCapabilities :: hasWebSocketSupport: "+v.hasWebSocketsSupport()),this._logger.info(this,"UserCapabilities :: hasWebRTCSupport: "+v.hasWebRTCSupport()),this._configManager.print(this._logger)):(this._logger.info(this,"StreamConfig has been overwritten, dispatching streamConfigChanged!"),this._configManager=new u(e),this._configManager.print(this._logger),this.dispatchEvent("streamConfigChange",{ref:this,newConfig:this._configManager})))}isConnected(){var e;return null!=(e=null==(e=this._networkController)?void 0:e.getConnection().isConnectionActive())&&e}mute(){null!=this._stageController&&null!=this._stageController.getScreenElement()?this._stageController.getScreenElement().setMuted(!0):this._configManager.getSettingsData().getAudioData().muted=!0}unmute(){null!=this._stageController&&null!=this._stageController.getScreenElement()?this._stageController.getScreenElement().setMuted(!1):this._configManager.getSettingsData().getAudioData().muted=!1}isMute(){var e;return null!=(e=null!=(e=null==(e=null==(e=this._stageController)?void 0:e.getScreenElement())?void 0:e.getIfMuted())?e:this._configManager.getSettingsData().getAudioData().muted)&&e}toggleMute(){var e=this.isMute();return e?this.unmute():this.mute(),!e}setVolume(e){var t;void 0===(null==(t=null==(t=this._stageController)?void 0:t.getScreenElement())?void 0:t.setVolume(e))&&(this._configManager.getSettingsData().getAudioData().startVolume=e)}getVolume(){var e;return null!=(e=null==(e=null==(e=this._stageController)?void 0:e.getScreenElement())?void 0:e.getVolume())?e:this._configManager.getSettingsData().getAudioData().startVolume}getCameraList(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.getCameraList())?e:[]}getMicrophoneList(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.getMicrophoneList())?e:[]}setCamera(e){var t;null!=(t=this._streamerController)&&t.selectCamera(e)}setMicrophone(e){var t;null!=(t=this._streamerController)&&t.selectMicrophone(e)}getCurrentCamera(){return this._streamerController.getCurrentCamera()}getCurrentMicrophone(){return this._streamerController.getCurrentMicrophone()}muteMicrophone(e){var t;null!=(t=this._streamerController)&&t.muteMicrophone(e)}isMicrophoneMuted(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.isMicrophoneMuted())&&e}getPublishState(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.getPublishState())?e:h.PublishState.NOT_INITIALIZED}getPublishTime(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.getPublishTime())?e:0}publish(e){var t;return null!=(t=null==(t=this._streamerController)?void 0:t.publish(e))&&t}getInputDeviceState(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.getInputDeviceState())?e:h.StreamerState.NOT_INITIALIZED}getCamerState(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.getCamerState())?e:h.DeviceState.NOT_INITIALIZED}getMicrophoneState(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.getMicrophoneState())?e:h.DeviceState.NOT_INITIALIZED}clearSavedDevices(){var e;return null==(e=this._streamerController)?void 0:e.clearSavedDevices()}messSavedDevices(){var e;return null==(e=this._streamerController)?void 0:e.messSavedDevices()}isStreamReady(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.isStreamReady())&&e}unpublish(){var e;null!=(e=this._streamerController)&&e.unpublish()}attachToContainer(e){var t;return!!this._initialized&&null!=(t=null==(t=this._stageController)?void 0:t.attachToParent(e))&&t}detachFromContainer(){var e;return!!this._initialized&&null!=(e=null==(e=this._stageController)?void 0:e.detachFromParent())&&e}getContainer(){var e;return null!=(e=null==(e=this._stageController)?void 0:e.getParentElement())?e:null}setSize(e,t){this._initialized?this._stageController.setSize(e,t):(e=_.parseValue(e),t=_.parseValue(t),this._configManager.getSettingsData().getVideoData().videoWidthValue=e.value,this._configManager.getSettingsData().getVideoData().videoWidthInPixels=e.isPixels,this._configManager.getSettingsData().getVideoData().videoHeightValue=t.value,this._configManager.getSettingsData().getVideoData().videoHeightInPixels=t.isPixels)}setWidth(e){this._initialized?this._stageController.setWidth(e):(e=_.parseValue(e),this._configManager.getSettingsData().getVideoData().videoWidthValue=e.value,this._configManager.getSettingsData().getVideoData().videoWidthInPixels=e.isPixels)}setHeight(e){this._initialized?this._stageController.setHeight(e):(e=_.parseValue(e),this._configManager.getSettingsData().getVideoData().videoHeightValue=e.value,this._configManager.getSettingsData().getVideoData().videoHeightInPixels=e.isPixels)}getWidth(){return this._initialized?this._stageController.getContainerWidth():this._configManager.getSettingsData().getVideoData().videoWidthInPixels?this._configManager.getSettingsData().getVideoData().videoWidthValue:0}getHeight(){return this._initialized?this._stageController.getContainerHeight():this._configManager.getSettingsData().getVideoData().videoHeightInPixels?this._configManager.getSettingsData().getVideoData().videoHeightValue:0}setScalingMode(e){this._stageController?this._stageController.setScalingMode(e):this._configManager.getSettingsData().getVideoData().scalingMode=e}getScalingMode(){return this._stageController?this._stageController.getScalingMode():this._configManager.getSettingsData().getVideoData().scalingMode}updateToSize(){this._initialized&&this._stageController.handleResize()}makeScreenshot(){let i=document.createElement("canvas"),s=i.getContext("2d");return new Promise(t=>{var e;null!=this._stageController&&(i.width=this._stageController.getScreenElement().getVideoElement().videoWidth,i.height=this._stageController.getScreenElement().getVideoElement().videoHeight,e=this._stageController.getScreenElement().getVideoElement(),s)?(s.drawImage(e,0,0,i.width,i.height),i.toBlob(e=>{t(e)},"image/png")):t(null)})}createFPSGraph(e){return new ee(this,e)}createBitrateGraph(e){return new Q(this,e)}addGraph(e){null!=this._graphs&&this._graphs.push(e)}stopAllGraphs(){if(null!=this._graphs&&0<this._graphs.length)for(let e=0;e<this._graphs.length;e++)this._graphs[e].stop()}enterFullScreen(){this._initialized&&this._stageController&&this._stageController.enterFullScreen()}exitFullScreen(){this._initialized&&this._stageController&&this._stageController.exitFullScreen()}isFullScreenMode(){return!(!this._initialized||!this._stageController)&&this._stageController.isFullScreenMode()}getStreamKey(){var e;return null!=(e=null==(e=null==(e=this.getConfigManager())?void 0:e.getStreamData())?void 0:e.streamKey)?e:null}getStatsController(){return this._statsController}getStreamerID(){return this._streamerID}getLogger(){return this._logger}getConfigManager(){return this._configManager}getNetworkController(){return this._networkController}getStreamerController(){return this._streamerController}getStageController(){return this._stageController}getVideoElement(){var e;return null!=(e=null==(e=null==(e=this._stageController)?void 0:e.getScreenElement())?void 0:e.getVideoElement())?e:null}isInitialized(){return this._initialized}getVersion(){return this.STREAMER_VERSION}getBranch(){return this.STREAMER_BRANCH}getStorageManager(){return this._storageManager}dispatchEvent(e,t){super.dispatchEvent(e,t)}start(){var e;return r(this,void 0,void 0,function*(){return null==(e=this._streamerController)?void 0:e.start()})}stop(){var e;return null==(e=this._streamerController)?void 0:e.stop()}destroy(){var e;this._logger.warning(this,"Destroying streamer instance, bye, bye!"),this.DEV_MODE&&"StormStreamerArray"in window&&(window.StormStreamerArray[this._streamerID]=null),this._initialized=!1,this._isRemoved=!0,null!=(e=null==(e=this._networkController)?void 0:e.getConnection())&&e.destroy(),null!=(e=this._streamerController)&&e.destroy(),null!=(e=this._stageController)&&e.destroy(),this.removeAllEventListeners()}}A.NEXT_STREAMER_ID=0,h.StormStreamer=A,h.create=function(e){return new A(e)}});
|
|
34
|
+
`;continue}s+="\r\n"}return s}mungeSDPPlay(e){let s="";for(const o of e.split(/\r\n/))if(0!==o.length){if(o.includes("profile-level-id")){var n=o.substr(o.indexOf("profile-level-id")+17,6);let e=Number("0x"+n.substr(0,2)),t=Number("0x"+n.substr(2,2)),i=Number("0x"+n.substr(4,2));66<e&&(e=66,t=224,i=31),0===t&&(t=224);var r=("00"+e.toString(16)).slice(-2).toLowerCase()+("00"+t.toString(16)).slice(-2).toLowerCase()+("00"+i.toString(16)).slice(-2).toLowerCase();s+=o.replace(n,r)}else s+=o;s+="\r\n"}return s}}y.SDPOutput={},(p=L=L||{})[p.VIDEO_INPUT=0]="VIDEO_INPUT",p[p.AUDIO_INPUT=1]="AUDIO_INPUT";class N{constructor(e,t){if(this._groupID="",this._isSelected=!1,null==e)throw new Error("no input device");if(void 0===e.deviceId||null===e.deviceId)throw new Error("no deviceID");if(this._id=e.deviceId,void 0===e.kind||null===e.kind)throw new Error("no device kind");switch(e.kind){case"videoinput":this._inputType=L.VIDEO_INPUT;break;case"audioinput":this._inputType=L.AUDIO_INPUT;break;default:throw new Error("incorrect kind")}null!==e.label&&""!==e.label?this._label=this.cleanLabel(e.label):this._label=this._inputType==L.VIDEO_INPUT?"Camera "+t:"Microphone "+t,void 0!==e.groupId&&null!==e.groupId&&(this._groupID=e.groupId)}cleanLabel(e){return e}get label(){return this._label}get id(){return this._id}get groupID(){return this._groupID}get isSelected(){return this._isSelected}set isSelected(e){this._isSelected=e}}class R{constructor(){this._internalList=new Array}push(t){let i=!1;if(0<this._internalList.length){for(let e=0;e<this._internalList.length;e++)""!==this._internalList[e].groupID&&this._internalList[e].groupID==t.groupID&&(i=!0,this._internalList[e]=t);return 0==i?this._internalList.push(t):this._internalList.length}return this._internalList.push(t)}get(e){return this._internalList[e]}getSize(){return this._internalList.length}getArray(){return this._internalList}}h.PublishState=void 0,(D=h.PublishState||(h.PublishState={})).NOT_INITIALIZED="NOT_INITIALIZED",D.INITIALIZED="INITIALIZED",D.CONNECTING="CONNECTING",D.CONNECTED="CONNECTED",D.PUBLISHED="PUBLISHED",D.UNPUBLISHED="UNPUBLISHED",D.STOPPED="STOPPED",D.UNKNOWN="UNKNOWN",D.ERROR="ERROR";class K{constructor(e){this._audioContext=null,this._analyser=null,this._microphone=null,this._lastEventTime=0,this.THROTTLE_INTERVAL=100,this._isMonitoring=!1,this._instant=0,this._slow=0,this._main=e}attach(e){if(e.getAudioTracks().length){this.detach();try{this._audioContext=new AudioContext,this._microphone=this._audioContext.createMediaStreamSource(e),this._analyser=this._audioContext.createAnalyser(),this._analyser.fftSize=2048,this._analyser.smoothingTimeConstant=.3,this._microphone.connect(this._analyser),this.startMonitoring()}catch(e){console.error("SoundMeter: Error during attach:",e),this.detach()}}else console.warn("SoundMeter: Attempted to attach stream without audio tracks")}detach(){var e,t;if(this._isMonitoring=!1,this._microphone){try{this._microphone.disconnect()}catch(e){console.warn("SoundMeter: Error disconnecting microphone:",e)}this._microphone=null}if(this._analyser){try{this._analyser.disconnect()}catch(e){console.warn("SoundMeter: Error disconnecting analyser:",e)}this._analyser=null}if("closed"!==(null==(e=this._audioContext)?void 0:e.state))try{null!=(t=this._audioContext)&&t.close()}catch(e){console.warn("SoundMeter: Error closing audio context:",e)}this._audioContext=null,this.clear()}clear(){this._instant=0,this._slow=0,this._lastEventTime=0}startMonitoring(){if(this._analyser&&!this._isMonitoring){this._isMonitoring=!0;const n=new Float32Array(this._analyser.frequencyBinCount),t=()=>{if(this._analyser&&this._isMonitoring){var e=Date.now();try{this._analyser.getFloatTimeDomainData(n);let t=0,i=0;for(let e=0;e<n.length;++e){var s=n[e];t+=s*s,.99<Math.abs(s)&&(i+=1)}this._instant=Math.sqrt(t/n.length),this._slow=.05*this._instant+.95*this._slow,e-this._lastEventTime>=this.THROTTLE_INTERVAL&&(this._lastEventTime=e,this._main.dispatchEvent("soundMeter",{ref:this._main,high:this._instant,low:this._slow}))}catch(e){return console.error("SoundMeter: Error during analysis:",e),void(this._isMonitoring=!1)}requestAnimationFrame(t)}};requestAnimationFrame(t)}}}h.InputDevicesState=void 0,(p=h.InputDevicesState||(h.InputDevicesState={})).NOT_INITIALIZED="NOT_INITIALIZED",p.INITIALIZED="INITIALIZED",p.READY="READY",p.UPDATING="UPDATING",p.INVALID="INVALID",p.UNKNOWN="UNKNOWN",p.STOPPED="STOPPED",h.DeviceState=void 0,(D=h.DeviceState||(h.DeviceState={})).NOT_INITIALIZED="NOT_INITIALIZED",D.ENABLED="ENABLED",D.ACCESS_DENIED="ACCESS_DENIED",D.NOT_FOUND="NOT_FOUND",D.STOPPED="STOPPED",(p=M=M||{})[p.NOT_INITIALIZED=0]="NOT_INITIALIZED",p[p.STARTED=1]="STARTED",p[p.CONNECTING=2]="CONNECTING",p[p.CONNECTED=3]="CONNECTED",p[p.CLOSED=4]="CLOSED",p[p.FAILED=5]="FAILED";class k{constructor(){this.CONNECTION_TIMEOUT=5,this.isBinary=!0,this._connectionState=M.NOT_INITIALIZED,this._messageCount=0,this._disconnectedByUser=!1,this._isConnected=!1,this._sequenceNumber=-1}startConnection(){this._disconnectedByUser=!1,this._messageCount=0,this._isConnected=!1,this._disconnectedByUser=!1,this._connectionState=M.CONNECTING,this.socket=new WebSocket(this.socketURL),this.isBinary&&(this.socket.binaryType="arraybuffer"),this.socket.onopen=e=>{clearTimeout(this._connectionTimeout),this._sequenceNumber++,this._connectionState=M.CONNECTED,this.onSocketOpen(e)},this.socket.onmessage=e=>{this._messageCount++,this.onSocketMessage(e)},this.socket.onclose=e=>{clearTimeout(this._connectionTimeout),this._connectionState==M.CONNECTED?(this._connectionState=M.CLOSED,this.onSocketClose(e)):this._connectionState=M.FAILED},this.socket.onerror=e=>{if(clearTimeout(this._connectionTimeout),this._connectionState==M.CONNECTING&&this.onSocketError(e),this._connectionState==M.CONNECTED)try{this.socket.close()}catch(e){}},this._connectionTimeout=setTimeout(()=>{try{this.socket.close()}catch(e){}this._connectionState==M.CONNECTING&&(this._connectionState=M.FAILED,this.onSocketError(new ErrorEvent("connectionTimeout")))},1e3*this.CONNECTION_TIMEOUT)}onSocketOpen(e){}onSocketClose(e){}onSocketMessage(e){}onSocketError(e){}onError(e){}sendData(e){if(this._connectionState==M.CONNECTED&&null!==this.socket){if(null!=e)return void this.socket.send(e);this.onError("no data to send")}this.onError("socket not connected")}getConnectionState(){return this._connectionState}disconnect(e=!0){this._isConnected=!1,this._connectionState=M.CLOSED,e&&(this._logger.warning(this,"Disconnected by user"),this._disconnectedByUser=e),null!=this.socket&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close())}destroy(){void 0!==this.socket&&null!==this.socket&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this._connectionState=M.CLOSED}getSocketURL(){return this.socketURL}}class ${constructor(){this._publishState=h.PublishState.NOT_INITIALIZED,this._videoPublishBitrate=0,this._audioPublishBitrate=0,this._currentBitrate=0,this._audioFrameCount=0,this._videoFrameCount=0,this._frameRate=0,this._videoWidth=0,this._videoHeight=0}get publishState(){return this._publishState}set publishState(e){this._publishState="published"===e?h.PublishState.PUBLISHED:h.PublishState.CONNECTED}get videoPublishBitrate(){return this._videoPublishBitrate}set videoPublishBitrate(e){this._videoPublishBitrate=e}get audioPublishBitrate(){return this._audioPublishBitrate}set audioPublishBitrate(e){this._audioPublishBitrate=e}set currentBitrate(e){this._currentBitrate=e}get currentBitrate(){return this._currentBitrate}get audioFrameCount(){return this._audioFrameCount}set audioFrameCount(e){this._audioFrameCount=e}get videoFrameCount(){return this._videoFrameCount}set videoFrameCount(e){this._videoFrameCount=e}get frameRate(){return this._frameRate}set frameRate(e){this._frameRate=e}set videoWidth(e){this._videoWidth=e}get videoWidth(){return this._videoWidth}set videoHeight(e){this._videoHeight=e}get videoHeight(){return this._videoHeight}}class Z extends k{constructor(e,t){super(),this._logger=e.getLogger(),this._main=e,this._currServer=t,this.initialize()}initialize(){this._logger.info(this,"Starting new status check connection with a storm server"),null!=this._currServer?(this.socketURL=this.createURL(this._currServer),this._logger.info(this,"Starting WebSocket connection with: "+this.socketURL),this.startConnection()):this._logger.error(this,"Connection with the server could not be initialized!")}onSocketOpen(e){this._logger.success(this,"Connection with the server has been established!"),this._main.dispatchEvent("statusServerConnect",{ref:this._main,serverURL:this.socketURL,sequenceNum:this._sequenceNumber}),this._isConnected=!0}onSocketError(e){this._isConnected=!1,this._disconnectedByUser||(this._logger.error(this,"Connection with the server failed"),this._main.dispatchEvent("serverConnectionError",{ref:this._main,serverURL:this.socketURL,restart:this._main.getConfigManager().getSettingsData().getIfRestartOnError(),sequenceNum:this._sequenceNumber}))}onSocketClose(e){this._isConnected=!1,this._disconnectedByUser?this._logger.warning(this,"Force disconnect from server!"):(this._logger.error(this,"Connection with the server has been closed"),this._main.dispatchEvent("statusServerDisconnect",{ref:this._main,serverURL:this.socketURL,restart:this._main.getConfigManager().getSettingsData().getIfRestartOnError(),sequenceNum:this._sequenceNumber}),this.initiateReconnect())}onSocketMessage(e){var t;"string"==typeof e.data&&"STREAM_STATUS_RESPONSE"===(e=JSON.parse(e.data)).packetID&&((t=new $).publishState=e.streamStatus,t.videoPublishBitrate=e.publishVideoBitrate,t.audioPublishBitrate=e.publishAudioBitrate,t.videoFrameCount=e.videoFrameCount,t.audioFrameCount=e.audioFrameCount,t.frameRate=e.frameRate,t.videoWidth=e.videoWidth,t.videoHeight=e.videoHeight,t.currentBitrate=e.realBitrate,console.log(t),this._main.dispatchEvent("streamStatusUpdate",{ref:this._main,streamStatus:t}))}initiateReconnect(){var e=this._main.getConfigManager().getSettingsData().getIfRestartOnError();const t=this._main.getConfigManager().getSettingsData().getReconnectTime();this._disconnectedByUser||e&&(null!=this._reconnectTimer&&clearTimeout(this._reconnectTimer),this._reconnectTimer=setTimeout(()=>{null!=this._currServer&&(this._logger.info(this,`Will reconnect to the server in ${t} seconds...`),this.socketURL=this.createURL(this._currServer),this._logger.info(this,"Starting WebSocket connection with: "+this.socketURL),this._main.dispatchEvent("serverConnectionInitiate",{ref:this._main,serverURL:this.socketURL}),this.startConnection())},1e3*t))}createURL(e){var t="";return(t+=e.getIfSSL()?"wss://":"ws://")+e.getHost()+(":"+e.getPort())+"/statuschecker"}isConnectionActive(){return this._isConnected}getCurrentServer(){return this._currServer}destroy(){super.destroy()}}class X{constructor(){this._streamWidth=0,this._streamHeight=0,this._aspectRatio="",this._hasVideoTrack=!1,this._hasAudioTrack=!1}get streamWidth(){return this._streamWidth}set streamWidth(e){this._streamWidth=e}get streamHeight(){return this._streamHeight}set streamHeight(e){this._streamHeight=e}get aspectRatio(){return this._aspectRatio}set aspectRatio(e){this._aspectRatio=e}get videoTrackPresent(){return this._hasVideoTrack}set videoTrackPresent(e){this._hasVideoTrack=e}get audioTrackPresent(){return this._hasAudioTrack}set audioTrackPresent(e){this._hasAudioTrack=e}}class j{constructor(e){var t;this._isWindowActive=!0,this._peerConnectionConfig={iceServers:[]},this._isMicrophoneMuted=!1,this._pendingMicrophoneState=null,this._permissionChecked=!1,this._constraints={video:{width:{min:"640",ideal:"1024",max:"1024"},height:{min:"360",ideal:"576",max:"576"},frameRate:{min:24,ideal:30,max:30}},audio:!0},this._restartTimerCount=0,this._restartTimerMaxCount=5,this._publishState=h.PublishState.NOT_INITIALIZED,this._publishTime=0,this._inputDeviceState=h.InputDevicesState.NOT_INITIALIZED,this._cameraState=h.DeviceState.NOT_INITIALIZED,this._microphoneState=h.DeviceState.NOT_INITIALIZED,this._publishTimer=0,this._currentOrientation=(null==(t=window.screen.orientation)?void 0:t.type)||"",this._statusTimer=null,this._debug=!1,this.onDeviceStateChange=e=>{var t=null==(t=this._main.getConfigManager())?void 0:t.getStreamData().streamKey;e.state==h.InputDevicesState.READY&&null!=t&&this.publish(t)},this.handleOrientationChange=()=>r(this,void 0,void 0,function*(){yield new Promise(e=>setTimeout(e,500));var e=(null==(e=window.screen.orientation)?void 0:e.type)||"";if(this._currentOrientation!==e){this._logger.info(this,`Orientation changed from ${this._currentOrientation} to `+e),this._currentOrientation=e;e=null==(e=this._main.getConfigManager())?void 0:e.getStreamData().streamKey;this._publishState,h.PublishState.PUBLISHED,this.closeWebRTCConnection(),this._stream&&(this._stream.getTracks().forEach(e=>{e.stop()}),this._stream=null);try{yield this.startCamera(),e&&this.publish(e)}catch(e){this._logger.error(this,"Error restarting stream after orientation change: "+JSON.stringify(e)),this.setInputDeviceState(h.InputDevicesState.INVALID)}}}),this.onServerDisconnect=()=>{},this.onStreamKeyTaken=()=>{null!=this._restartTimer&&(clearInterval(this._restartTimer),this._restartTimerCount=0),this._logger.info(this,"WebRTCStreamer :: Starting StreamKeyTaken Interval"),this.setPublishState(h.PublishState.ERROR),this._restartTimer=setInterval(()=>{var e;null!=this._restartTimer&&(this._restartTimerCount<this._restartTimerMaxCount?(this._logger.info(this,"WebRTCStreamer :: StreamKeyTaken Interval: "+this._restartTimerCount+"/"+this._restartTimerMaxCount),this._restartTimerCount++):(clearInterval(this._restartTimer),this._restartTimer=null,this._restartTimerCount=0,null!=(e=null==(e=null==(e=this._main.getConfigManager())?void 0:e.getStreamData())?void 0:e.streamKey)&&this.publish(e)),e=null!=(e=this._main.getConfigManager().getStreamData().streamKey)?e:"unknown",this._main.dispatchEvent("streamKeyInUseInterval",{ref:this._main,streamKey:e,count:this._restartTimerCount,maxCount:this._restartTimerMaxCount}))},1e3)},this.onServerConnect=()=>{if(this._peerConnection&&this.closeWebRTCConnection(),this._peerConnection=new RTCPeerConnection(this._peerConnectionConfig),this._stream){var e,t=this._stream.getTracks();for(e in t)this._peerConnection.addTrack(t[e],this._stream)}this._peerConnection.onicecandidate=e=>{this.onIceCandidate(e)},this._peerConnection.onconnectionstatechange=e=>{this.onConnectionStateChange(e)},this._peerConnection.onnegotiationneeded=e=>r(this,void 0,void 0,function*(){if(this._peerConnection)try{var e=yield this._peerConnection.createOffer();yield this.onDescriptionSuccess(e)}catch(e){this.onDescriptionError(e),console.error("Error creating offer:",e)}}),this.createStatusConnection()},this.onStatusServerConnect=()=>{var e=this._main.getConfigManager().getStreamData().streamKey;null==this._statusTimer&&null!=this._statusConnection&&null!=e&&(this._statusTimer=setInterval(()=>{this.requestStatusData()},1e3))},this.requestStatusData=()=>{var e,t=this._main.getConfigManager().getStreamData().streamKey;null!=(e=this._statusConnection)&&e.sendData('{"packetID":"STREAM_STATUS", "streamKey": "'+t+'"}')},this.onStatusServerDisconnect=()=>{null!=this._statusTimer&&clearInterval(this._statusTimer),this._statusTimer=null},this.onStreamStatsUpdate=e=>{e=e.streamStatus;this._publishState==h.PublishState.PUBLISHED&&e.publishState!=h.PublishState.PUBLISHED&&this.setPublishState(h.PublishState.UNPUBLISHED),this._publishState==h.PublishState.CONNECTED&&e.publishState==h.PublishState.PUBLISHED&&this.setPublishState(h.PublishState.PUBLISHED)},this.onDescriptionSuccess=t=>{var e;const i={applicationName:null==(e=null==(e=this._main.getNetworkController())?void 0:e.getConnection().getCurrentServer())?void 0:e.getApplication(),streamName:null==(e=this._main.getConfigManager())?void 0:e.getStreamData().streamKey,sessionId:"[empty]"};t.sdp=this._mungeSDP.mungeSDPPublish(t.sdp,{audioBitrate:"64",videoBitrate:"1500",videoFrameRate:30,videoCodec:"42e01f",audioCodec:"opus"}),this._peerConnection&&this._peerConnection.setLocalDescription(t).then(()=>{var e;null!=(e=this._main.getNetworkController())&&e.sendMessage('{"direction":"publish", "command":"sendOffer", "streamInfo":'+JSON.stringify(i)+', "sdp":'+JSON.stringify(t)+"}")}).catch(e=>{console.log(e)})},this.visibilityChange=()=>{"hidden"===document.visibilityState?this.onWindowBlur():"visible"===document.visibilityState&&this.onWindowFocus()},this.onWindowBlur=()=>{this._isWindowActive&&this._logger.warning(this,"Player window is no longer in focus!"),this._isWindowActive=!1},this.onWindowFocus=()=>{this._isWindowActive||this._logger.info(this,"Player window is focused again!"),this._isWindowActive=!0},this._main=e,this._logger=e.getLogger(),this._mungeSDP=new y,this._soundMeter=new K(this._main),this._debug=null!=(e=null==(t=this._main.getConfigManager())?void 0:t.getSettingsData().getDebugData().streamerControllerDebug)?e:this._debug,this.initialize()}initialize(){var e,t;return r(this,void 0,void 0,function*(){try{yield this.initializeDevices(),this.setupEventListeners(),this.initializeStream(),this.setupOrientationListener(),this.setupPermissionListeners(),null!=(e=this._main.getConfigManager())&&e.getSettingsData().autoConnect?(this._logger.info(this,"Initializing NetworkController (autoConnect is true)"),null!=(t=this._main.getNetworkController())&&t.initialize()):this._logger.warning(this,"Warning - autoConnect is set to false, switching to standby mode!")}catch(e){this._logger.error(this,"Initialization failed: "+JSON.stringify(e)),this.setInputDeviceState(h.InputDevicesState.INVALID)}})}setupEventListeners(){this._main.addEventListener("serverConnect",this.onServerConnect,!1),this._main.addEventListener("serverDisconnect",this.onServerDisconnect,!1),this._main.addEventListener("streamKeyInUse",this.onStreamKeyTaken,!1),this._main.addEventListener("statusServerConnect",this.onStatusServerConnect,!1),this._main.addEventListener("statusServerDisconnect",this.onStatusServerDisconnect,!1),this._main.addEventListener("streamStatusUpdate",this.onStreamStatsUpdate,!1),this._main.addEventListener("deviceStateChange",this.onDeviceStateChange,!1),document.addEventListener("visibilitychange",this.visibilityChange),window.addEventListener("blur",this.onWindowBlur),window.addEventListener("focus",this.onWindowFocus)}initializeDevices(){return r(this,void 0,void 0,function*(){try{(yield navigator.mediaDevices.getUserMedia({video:!0,audio:!0})).getTracks().forEach(e=>e.stop()),yield this.grabDevices()}catch(e){this._logger.error(this,"Error initializing devices: "+JSON.stringify(e)),yield this.grabDevices()}})}initializeStream(){(this._selectedCamera||this._selectedMicrophone)&&this.startCamera()}setupPermissionListeners(){navigator.permissions.query({name:"camera"}).then(e=>{e.onchange=()=>{this._permissionChecked=!1,this.handlePermissionChange("camera",e.state)}}),navigator.permissions.query({name:"microphone"}).then(e=>{e.onchange=()=>{this._permissionChecked=!1,this.handlePermissionChange("microphone",e.state)}})}handlePermissionChange(e,t){return r(this,void 0,void 0,function*(){"denied"===t&&(this.setInputDeviceState(h.InputDevicesState.INVALID),this._publishState==h.PublishState.CONNECTED)&&this.closeStream(),yield this.grabDevices(),"granted"===t&&(yield this.startCamera())})}onCameraStreamSuccess(e){this._logger.success(this,"Camera stream successfully retrieved");var s=e.getVideoTracks()[0],t=e.getAudioTracks()[0],n=new X;if(s){s=s.getSettings();let e=s.width,t=s.height;/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)&&(e>t&&window.innerWidth<window.innerHeight||e<t&&window.innerWidth>window.innerHeight)&&([e,t]=[t,e]),n.streamWidth=e,n.streamHeight=t,n.videoTrackPresent=!0;const a=(e,t)=>t?a(t,e%t):e;var s=a(e,t),r=e/s,s=t/s,o=e/t;let i=r+":"+s;Math.abs(o-16/9)<.1?i=e>t?"16:9":"9:16":Math.abs(o-4/3)<.1&&(i=e>t?"4:3":"3:4"),n.aspectRatio=i}else n.videoTrackPresent=!1;n.audioTrackPresent=!!t,this._logger.info(this,`Publish MetaData :: Resolution: ${n.streamWidth}x${n.streamHeight} | `+`Aspect ratio: ${n.aspectRatio}, `+`Video track: ${n.videoTrackPresent} | Audio track: `+n.audioTrackPresent),this._main.dispatchEvent("publishMetadataUpdate",{ref:this._main,metadata:n}),this._stream=e,null!==this._pendingMicrophoneState?(this.applyMicrophoneState(this._pendingMicrophoneState),this._pendingMicrophoneState=null):this.applyMicrophoneState(!this._isMicrophoneMuted),0<this._stream.getAudioTracks().length&&this._soundMeter.attach(this._stream),null!=this._cameraList&&null!=this._microphoneList||this.grabDevices();r=this._main.getStageController().getScreenElement().getVideoElement();r.srcObject=e,r.autoplay=!0,r.playsInline=!0,r.disableRemotePlayback=!0,r.controls=!1,r.muted=!0,this.setPublishState(h.PublishState.INITIALIZED)}initializeWebRTC(){var e;this._stream?this._peerConnection?(this._logger.info(this,"WebRTC connection already exists, updating stream"),this.updateWebRTCStream()):(this._logger.info(this,"Initializing new WebRTC connection"),null!=(e=this._main.getNetworkController())&&e.start()):this._logger.error(this,"Cannot initialize WebRTC - no camera stream available")}publish(e){return null!=this._statusTimer&&clearInterval(this._statusTimer),this._main.getConfigManager().getStreamData().streamKey==e&&this._publishState==h.PublishState.CONNECTED?(this._logger.warning(this,"Already published!"),!1):(null!=this._main.getConfigManager().getStreamData().streamKey&&this.unpublish(),this._main.getConfigManager().getStreamData().streamKey=e,this.isStreamReady(!0,!0)?(this._debug&&this._logger.decoratedLog("Publishing: "+e,"dark-red"),this._logger.info(this,"Publish: "+e),this.closeWebRTCConnection(),this._main.dispatchEvent("publish",{ref:this._main,streamKey:e}),this.initializeWebRTC(),!0):(this._logger.warning(this,"Cannot publish - stream not ready (missing video or audio track)"),!1))}unpublish(){this._debug&&this._logger.decoratedLog("Unpublish","dark-red"),null!=this._statusConnection&&(this._statusConnection.destroy(),this._statusConnection=null),null!=this._statusTimer&&(clearInterval(this._statusTimer),this._statusTimer=null),clearTimeout(this._publishTimer),this._main.getConfigManager().getStreamData().streamKey=null,this._main.dispatchEvent("unpublish",{ref:this._main}),this.closeStream()}setupOrientationListener(){window.screen&&window.screen.orientation?window.screen.orientation.addEventListener("change",this.handleOrientationChange):window.addEventListener("orientationchange",this.handleOrientationChange)}onUserMediaError(e){return r(this,void 0,void 0,function*(){yield this.grabDevices(),"OverconstrainedError"===e.name&&this._logger.warning(this,"Device constraints not satisfied")})}checkIndividualDeviceAccess(){return r(this,void 0,void 0,function*(){var t={camera:{allowed:!1,available:!1},microphone:{allowed:!1,available:!1}};try{var e=yield navigator.mediaDevices.enumerateDevices(),i=(t.camera.available=e.some(e=>"videoinput"===e.kind),t.microphone.available=e.some(e=>"audioinput"===e.kind),e.some(e=>""!==e.label));if(i)t.camera.allowed=e.some(e=>"videoinput"===e.kind&&""!==e.label),t.microphone.allowed=e.some(e=>"audioinput"===e.kind&&""!==e.label);else try{var s=yield navigator.mediaDevices.getUserMedia({video:t.camera.available,audio:t.microphone.available});t.camera.allowed=0<s.getVideoTracks().length,t.microphone.allowed=0<s.getAudioTracks().length,s.getTracks().forEach(e=>e.stop()),yield this.grabDevices()}catch(e){console.error("Error requesting permissions:",e),t.camera.allowed=!1,t.microphone.allowed=!1}}catch(e){console.error("Error checking devices:",e),t.camera.available=!1,t.microphone.available=!1,t.camera.allowed=!1,t.microphone.allowed=!1}return t})}onSocketMessage(e){var t=JSON.parse(e);switch(Number(t.status)){case 200:this._logger.info(this,"SDP Exchange Successful");var i=t.sdp,s=(void 0!==i&&this._peerConnection.setRemoteDescription(new RTCSessionDescription(i),()=>{},()=>{}),t.iceCandidates);if(void 0!==s)for(var n in s)this._peerConnection&&this._peerConnection.addIceCandidate(new RTCIceCandidate(s[n]));break;case 503:this._logger.error(this,"StreamKey already use");i=null!=(i=this._main.getConfigManager().getStreamData().streamKey)?i:"unknown";this._main.dispatchEvent("streamKeyInUse",{ref:this._main,streamKey:i}),this.setPublishState(h.PublishState.ERROR)}}onConnectionStateChange(e){if(this._logger.info(this,"Connection State Change: "+JSON.stringify(e)),null!==e)switch(e.currentTarget.connectionState){case"connecting":this._logger.info(this,"WebRTCStreamer :: Event: onStreamerConnecting"),this.setPublishState(h.PublishState.CONNECTING);break;case"connected":this._logger.info(this,"WebRTCStreamer :: Event: onStreamerConnected"),this.setPublishState(h.PublishState.CONNECTED),this.muteMicrophone(this._isMicrophoneMuted);break;case"disconnected":this._logger.info(this,"WebRTCStreamer :: Event: onStreamerDisconnected"),this.setPublishState(h.PublishState.UNPUBLISHED);break;case"failed":this._logger.info(this,"WebRTCStreamer :: Event: onPlayerFailed"),this.setPublishState(h.PublishState.ERROR);break;default:this._logger.info(this,"WebRTCStreamer :: Unsupported onConnectionStateChange: "+e.currentTarget.connectionState)}}grabDevices(){return r(this,void 0,void 0,function*(){try{var e,t,i=yield this.checkIndividualDeviceAccess(),s=(this._cameraList=new R,this._microphoneList=new R,this._permissionChecked||(i.camera.allowed?i.camera.available||(this._main.dispatchEvent("noCameraFound",{ref:this._main}),this.setCameraState(h.DeviceState.NOT_FOUND),this.setInputDeviceState(h.InputDevicesState.INVALID)):(this._main.dispatchEvent("cameraAccessDenied",{ref:this._main}),this.setCameraState(h.DeviceState.ACCESS_DENIED),this.setInputDeviceState(h.InputDevicesState.INVALID)),i.microphone.allowed?i.microphone.available||(this._main.dispatchEvent("noMicrophoneFound",{ref:this._main}),this.setMicrophoneState(h.DeviceState.NOT_FOUND),this.setInputDeviceState(h.InputDevicesState.INVALID)):(this._main.dispatchEvent("microphoneAccessDenied",{ref:this._main}),this.setMicrophoneState(h.DeviceState.ACCESS_DENIED),this.setInputDeviceState(h.InputDevicesState.INVALID))),yield navigator.mediaDevices.enumerateDevices());for(const n of s)n.deviceId&&n.label&&("videoinput"===n.kind&&i.camera.allowed?(e=new N(n,this._cameraList.getSize()),this._cameraList.push(e)):"audioinput"===n.kind&&i.microphone.allowed&&(t=new N(n,this._microphoneList.getSize()),this._microphoneList.push(t)));try{i.camera.allowed&&(this._selectedCamera=this.pickCamera()),i.microphone.allowed&&(this._selectedMicrophone=this.pickMicrophone())}catch(e){this.setInputDeviceState(h.InputDevicesState.INVALID),this._logger.error(this,"Errror on grab devices: "+JSON.stringify(e))}this._main.dispatchEvent("deviceListUpdate",{ref:this._main,cameraList:this._cameraList.getArray(),microphoneList:this._microphoneList.getArray()}),this._permissionChecked=!0}catch(e){console.error("Error in grabDevices:",e),this._cameraList=new R,this._microphoneList=new R,this._main.dispatchEvent("deviceListUpdate",{ref:this._main,cameraList:this._cameraList.getArray(),microphoneList:this._microphoneList.getArray()}),this._main.dispatchEvent("inputDeviceError",{ref:this._main})}})}selectCamera(t){var e,i;for(let e=0;e<this._cameraList.getSize();e++)this._cameraList.get(e).isSelected=!1;this._selectedCamera=null,this.setInputDeviceState(h.InputDevicesState.UPDATING),this.setCameraState(h.DeviceState.NOT_INITIALIZED);const s=null==(e=this._main.getConfigManager())?void 0:e.getStreamData().streamKey,n=this._publishState===h.PublishState.CONNECTED;for(let e=0;e<this._cameraList.getSize();e++)if(this._cameraList.get(e).id==t){this._selectedCamera=this._cameraList.get(e),this._selectedCamera.isSelected=!0,null!=(i=this._main.getStorageManager())&&i.saveField("cameraID",this._selectedCamera.id);break}this._main.dispatchEvent("deviceListUpdate",{ref:this._main,cameraList:this._cameraList.getArray(),microphoneList:this._microphoneList.getArray()}),this.stopCameraStream(),null!=this._selectedCamera?(this._constraints.video.deviceId=this._selectedCamera.id,this.startCamera().then(()=>{this.setCameraState(h.DeviceState.ENABLED),this._cameraState==h.DeviceState.ENABLED&&this._microphoneState==h.DeviceState.ENABLED?this.setInputDeviceState(h.InputDevicesState.READY):this.setInputDeviceState(h.InputDevicesState.INVALID),n&&s&&this.publish(s)})):this.setInputDeviceState(h.InputDevicesState.INVALID)}selectMicrophone(i){var s,n;return r(this,void 0,void 0,function*(){for(let e=0;e<this._microphoneList.getSize();e++)this._microphoneList.get(e).isSelected=!1;this._selectedMicrophone=null,this.setInputDeviceState(h.InputDevicesState.UPDATING),this.setMicrophoneState(h.DeviceState.NOT_INITIALIZED),this._logger.info(this,"Selecting microphone: "+i);var e=null==(s=this._main.getConfigManager())?void 0:s.getStreamData().streamKey,t=this._publishState===h.PublishState.CONNECTED;for(let e=0;e<this._microphoneList.getSize();e++)if(this._microphoneList.get(e).id==i){this._selectedMicrophone=this._microphoneList.get(e),this._selectedMicrophone.isSelected=!0,null!=(n=this._main.getStorageManager())&&n.saveField("microphoneID",this._selectedMicrophone.id);break}this._main.dispatchEvent("deviceListUpdate",{ref:this._main,cameraList:this._cameraList.getArray(),microphoneList:this._microphoneList.getArray()}),this._soundMeter.detach(),this.closeWebRTCConnection(),this._stream&&(this._stream.getTracks().forEach(e=>{e.stop()}),this._stream=null);try{yield this.startCamera(),this.setMicrophoneState(h.DeviceState.ENABLED),this._cameraState==h.DeviceState.ENABLED&&this._microphoneState==h.DeviceState.ENABLED?this.setInputDeviceState(h.InputDevicesState.READY):this.setInputDeviceState(h.InputDevicesState.INVALID),t&&e&&this.publish(e)}catch(e){console.error("Error changing microphone:",e),this._main.dispatchEvent("inputDeviceError",{ref:this._main}),this.setInputDeviceState(h.InputDevicesState.INVALID)}})}startCamera(){return r(this,void 0,void 0,function*(){this._stream&&(this._stream.getTracks().forEach(e=>{e.stop()}),this._stream=null);try{var t={video:!!this._selectedCamera&&Object.assign(Object.assign({},this._constraints.video),{deviceId:{exact:this._selectedCamera.id}}),audio:!!this._selectedMicrophone&&{deviceId:{exact:this._selectedMicrophone.id}}};try{var e=yield navigator.mediaDevices.getUserMedia(t);this._stream=e,this.onCameraStreamSuccess(this._stream)}catch(e){t.video&&this.onUserMediaError({name:e.name||"Error",message:e.message||"Unknown error",deviceType:"video"}),t.audio&&this.onUserMediaError({name:e.name||"Error",message:e.message||"Unknown error",deviceType:"audio"})}this._cameraState==h.DeviceState.ENABLED&&this._microphoneState==h.DeviceState.ENABLED&&this.setInputDeviceState(h.InputDevicesState.READY)}catch(e){console.error("Error in startCamera:",e),yield this.grabDevices()}})}updateWebRTCStream(){this._peerConnection&&this._stream&&(this._peerConnection.getSenders().forEach(e=>{this._peerConnection&&this._peerConnection.removeTrack(e)}),this._stream.getTracks().forEach(e=>{null!=this._stream&&this._peerConnection&&this._peerConnection.addTrack(e,this._stream)}))}closeStream(){void 0!==this._peerConnection&&null!==this._peerConnection&&this._peerConnection.close(),this.setPublishState(h.PublishState.UNPUBLISHED)}pickCamera(){var e;for(let e=0;e<this._cameraList.getSize();e++)this._cameraList.get(e).isSelected=!1;var i=null!=(e=null==(e=this._main.getStorageManager())?void 0:e.getField("cameraID"))?e:null;if(0<this._cameraList.getSize()){if(i){let t=!1;for(let e=0;e<this._cameraList.getSize();e++)if(this._cameraList.get(e).id===i){this._selectedCamera=this._cameraList.get(e),this._selectedCamera.isSelected=!0,this.setCameraState(h.DeviceState.ENABLED),t=!0,this._constraints.video.deviceId=this._selectedCamera.id;break}if(!t)return this.setCameraState(h.DeviceState.NOT_FOUND),this.setInputDeviceState(h.InputDevicesState.INVALID),this._main.dispatchEvent("savedCameraNotFound",{ref:this._main,savedDeviceID:i}),null!=(e=this._main.getConfigManager())&&e.getSettingsData().getIfCancelPublishOnError()&&(this._logger.info(this,"Canceling Publish!"),this._main.getConfigManager().getStreamData().streamKey=null),null}if(!this._selectedCamera){if(this._main.dispatchEvent("savedCameraNotFound",{ref:this._main,savedDeviceID:null}),null!=(e=this._main.getConfigManager())&&e.getSettingsData().getIfCancelPublishOnError()&&(this._logger.info(this,"Canceling Publish!"),this._main.getConfigManager().getStreamData().streamKey=null),null==(e=this._main.getConfigManager())||!e.getSettingsData().getIfForceSelection())return this.setCameraState(h.DeviceState.NOT_FOUND),this.setInputDeviceState(h.InputDevicesState.INVALID),null;this._selectedCamera=this._cameraList.get(0),this._selectedCamera.isSelected=!0,null!=(e=this._main.getStorageManager())&&e.saveField("cameraID",this._selectedCamera.id),this._constraints.video.deviceId=this._selectedCamera.id,this.setCameraState(h.DeviceState.ENABLED)}}return this._main.dispatchEvent("deviceListUpdate",{ref:this._main,cameraList:this._cameraList.getArray(),microphoneList:this._microphoneList.getArray()}),this._selectedCamera}pickMicrophone(){var e;for(let e=0;e<this._microphoneList.getSize();e++)this._microphoneList.get(e).isSelected=!1;var i=null!=(e=null==(e=this._main.getStorageManager())?void 0:e.getField("microphoneID"))?e:null;if(0<this._microphoneList.getSize()){if(i){let t=!1;for(let e=0;e<this._microphoneList.getSize();e++)if(this._microphoneList.get(e).id===i){this._selectedMicrophone=this._microphoneList.get(e),t=!0,this.setMicrophoneState(h.DeviceState.ENABLED);break}if(!t)return this._main.dispatchEvent("savedMicrophoneNotFound",{ref:this._main,savedDeviceID:i}),this.setMicrophoneState(h.DeviceState.NOT_FOUND),this.setInputDeviceState(h.InputDevicesState.INVALID),null!=(e=this._main.getConfigManager())&&e.getSettingsData().getIfCancelPublishOnError()&&(this._logger.info(this,"Canceling Publish!"),this._main.getConfigManager().getStreamData().streamKey=null),null}if(!this._selectedMicrophone){if(this._main.dispatchEvent("savedMicrophoneNotFound",{ref:this._main,savedDeviceID:null}),null!=(e=this._main.getConfigManager())&&e.getSettingsData().getIfCancelPublishOnError()&&(this._logger.info(this,"Canceling Publish!"),this._main.getConfigManager().getStreamData().streamKey=null),null==(e=this._main.getConfigManager())||!e.getSettingsData().getIfForceSelection())return this.setMicrophoneState(h.DeviceState.NOT_FOUND),this.setInputDeviceState(h.InputDevicesState.INVALID),null;this._selectedMicrophone=this._microphoneList.get(0),this.setMicrophoneState(h.DeviceState.ENABLED),null!=(e=this._main.getStorageManager())&&e.saveField("microphoneID",this._selectedMicrophone.id)}this._selectedMicrophone.isSelected=!0,this._constraints.audio={deviceId:this._selectedMicrophone.id}}return this._selectedMicrophone}clearSavedDevices(){var e;null!=(e=this._main.getStorageManager())&&e.removeField("cameraID"),null!=(e=this._main.getStorageManager())&&e.removeField("microphoneID")}messSavedDevices(){var e;null!=(e=this._main.getStorageManager())&&e.saveField("cameraID","a"),null!=(e=this._main.getStorageManager())&&e.saveField("microphoneID","b")}muteMicrophone(e){this._isMicrophoneMuted!==e&&(this._isMicrophoneMuted=e,this._stream?this.applyMicrophoneState(!e):(this._pendingMicrophoneState=!e,this._logger.info(this,`WebRTCStreamer :: Stream not yet available, storing microphone state (muted: ${e})`)),this._main.dispatchEvent("microphoneStateChange",{ref:this._main,isMuted:this._isMicrophoneMuted}))}applyMicrophoneState(t){var e;this._stream?(e=this._stream.getAudioTracks())&&0<e.length?(this._logger.success(this,`WebRTCStreamer :: ${t?"Unmuting":"Muting"} microphone`),e.forEach(e=>e.enabled=t)):this._logger.warning(this,"WebRTCStreamer :: No audio tracks found in stream"):this._logger.warning(this,"WebRTCStreamer :: Cannot apply microphone state - stream not available")}isStreamReady(e=!0,t=!0){var i,s;return!!this._stream&&(s=this._stream.getVideoTracks(),i=this._stream.getAudioTracks(),e=!e||0<s.length&&"live"===s[0].readyState,s=!t||0<i.length&&"live"===i[0].readyState,e)&&s}closeWebRTCConnection(){this._peerConnection&&(this._peerConnection.close(),this._peerConnection=null)}onDescriptionError(e){this._logger.info(this,"WebRTCStreamer :: onDescriptionError: "+JSON.stringify(e))}onIceCandidate(e){e.candidate}createStatusConnection(){var e=null==(e=null==(e=null==(e=this._main)?void 0:e.getNetworkController())?void 0:e.getConnection())?void 0:e.getCurrentServer();e&&(this._statusConnection&&!this._statusConnection.isConnectionActive()&&this._statusConnection.destroy(),this._statusConnection=new Z(this._main,e))}isMicrophoneMuted(){return this._isMicrophoneMuted}getCurrentCamera(){return this._selectedCamera}getCurrentMicrophone(){return this._selectedMicrophone}setPublishState(e){this._publishState!=e&&(this._debug&&this._logger.decoratedLog("Publish State: "+e,"dark-blue"),this._logger.info(this,"Publish State: "+e),e==h.PublishState.PUBLISHED&&(this._publishTime=(new Date).getTime()),this._publishState=e,this._main.dispatchEvent("publishStateChange",{ref:this._main,state:this._publishState}))}getPublishTime(){return this._publishState==h.PublishState.PUBLISHED?this._publishTime:0}setInputDeviceState(e){this._inputDeviceState!=e&&(this._inputDeviceState=e,this._main.dispatchEvent("deviceStateChange",{ref:this._main,state:this._inputDeviceState,selectedCamera:this._selectedCamera,selectedMicrophone:this._selectedMicrophone}))}getInputDeviceState(){return this._inputDeviceState}setCameraState(e){this._cameraState!=e&&(this._cameraState=e,this._main.dispatchEvent("cameraDeviceStateChange",{ref:this._main,state:e,selectedCamera:this._selectedCamera}))}getCamerState(){return this._cameraState}setMicrophoneState(e){this._microphoneState!=e&&(this._microphoneState=e,this._main.dispatchEvent("microphoneDeviceStateChange",{ref:this._main,state:e,selectedMicrophone:this._selectedMicrophone}))}getMicrophoneState(){return this._microphoneState}getCameraList(){return null!=this._cameraList?this._cameraList.getArray():[]}getMicrophoneList(){return null!=this._microphoneList?this._microphoneList.getArray():[]}getPublishState(){return this._publishState}stopCameraStream(){var e;this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),(e=null==(e=null==(e=this._main.getStageController())?void 0:e.getScreenElement())?void 0:e.getVideoElement())&&(e.srcObject=null),this._soundMeter.detach(),this._stream=null)}forceStopAllStreams(){var e,t;if(this._peerConnection)try{this._peerConnection.getSenders().forEach(e=>{var t;try{e.track&&(e.track.enabled=!1,e.track.stop(),null!=(t=this._peerConnection))&&t.removeTrack(e)}catch(e){console.error("Error stopping sender track:",e)}}),this._peerConnection.close(),this._peerConnection=null}catch(e){console.error("Error closing peer connection:",e)}try{var i=null==(t=null==(e=this._main.getStageController())?void 0:e.getScreenElement())?void 0:t.getVideoElement();i&&i.srcObject instanceof MediaStream&&(i.srcObject.getTracks().forEach(e=>{try{e.enabled=!1,e.stop()}catch(e){console.error("Error stopping video element track:",e)}}),i.srcObject=null,i.removeAttribute("src"),i.load())}catch(e){console.error("Error cleaning video element:",e)}if(this._stream)try{this._stream.getTracks().forEach(t=>{try{t.enabled=!1,t.stop()}catch(e){console.error(`Error stopping ${t.kind} track:`,e)}}),this._stream=null}catch(e){console.error("Error stopping main stream:",e)}}stop(){this._statusConnection&&(this._statusConnection.destroy(),this._statusConnection=null),this._statusTimer&&(clearInterval(this._statusTimer),this._statusTimer=null),this._main.getConfigManager().getStreamData().streamKey=null,this.closeWebRTCConnection(),this.stopCameraStream(),this.setPublishState(h.PublishState.STOPPED),this.setInputDeviceState(h.InputDevicesState.STOPPED),this.setCameraState(h.DeviceState.STOPPED),this.setMicrophoneState(h.DeviceState.STOPPED),this._restartTimer&&(clearInterval(this._restartTimer),this._restartTimer=null),this._restartTimerCount=0,clearTimeout(this._publishTimer)}start(){var e,t,i;return r(this,void 0,void 0,function*(){try{this._publishState=h.PublishState.NOT_INITIALIZED,this._inputDeviceState=h.InputDevicesState.NOT_INITIALIZED,this._cameraState=h.DeviceState.NOT_INITIALIZED,this._microphoneState=h.DeviceState.NOT_INITIALIZED,yield this.initializeDevices(),yield this.startCamera(),null!=(e=this._main.getConfigManager())&&e.getSettingsData().autoConnect&&null!=(t=this._main.getNetworkController())&&t.initialize(),null!=(i=this._main.getConfigManager())&&i.getStreamData().streamKey&&this.createStatusConnection()}catch(e){throw this._logger.error(this,"Start failed: "+JSON.stringify(e)),this.setInputDeviceState(h.InputDevicesState.INVALID),e}})}destroy(){window.screen&&window.screen.orientation?window.screen.orientation.removeEventListener("change",this.handleOrientationChange):window.removeEventListener("orientationchange",this.handleOrientationChange),this.forceStopAllStreams(),this._soundMeter&&this._soundMeter.detach(),clearTimeout(this._publishTimer),this._pendingMicrophoneState=null,this._cameraList=new R,this._microphoneList=new R,this._permissionChecked=!1,this._isWindowActive=!1,this._isMicrophoneMuted=!1;try{this._main.removeEventListener("serverConnect",this.onServerConnect),this._main.removeEventListener("serverDisconnect",this.onServerDisconnect),document.removeEventListener("visibilitychange",this.visibilityChange),window.removeEventListener("blur",this.onWindowBlur),window.removeEventListener("focus",this.onWindowFocus)}catch(e){console.error("Error removing event listeners:",e)}this._publishState=h.PublishState.NOT_INITIALIZED,null!=this._restartTimer&&clearInterval(this._restartTimer)}}class q extends k{constructor(e,t){super(),this._logger=e.getLogger(),this._main=e,this._networkController=t,this.initialize()}initialize(){this._logger.info(this,"Starting new connection with a storm server"),this.pickServerFromList(this._main.getConfigManager().getStreamData().getServerList()),null!=this._currServer?(this.socketURL=this.createURL(this._currServer),this._logger.info(this,"Starting WebSocket connection with: "+this.socketURL),this._main.dispatchEvent("serverConnectionInitiate",{ref:this._main,serverURL:this.socketURL}),this._main.getConfigManager().getIfDemoMode()?(this._logger.warning(this,"Player is in demo mode, and will not connect with a server!"),this._main.dispatchEvent("authorizationComplete",{ref:this._main})):this.startConnection()):this._logger.error(this,"Connection with the server could not be initialized!")}onSocketOpen(e){this._logger.success(this,"Connection with the server has been established!"),this._main.dispatchEvent("serverConnect",{ref:this._main,serverURL:this.socketURL,sequenceNum:this._sequenceNumber}),this._isConnected=!0}onSocketError(e){this._isConnected=!1,this._disconnectedByUser||(this._logger.error(this,"Connection with the server failed"),this._main.dispatchEvent("serverConnectionError",{ref:this._main,serverURL:this.socketURL,restart:this._main.getConfigManager().getSettingsData().getIfRestartOnError(),sequenceNum:this._sequenceNumber}),0==this._isConnected&&(this._currServer.setAsFaild(!0),this.initiateReconnect()))}onSocketClose(e){this._isConnected=!1,this._disconnectedByUser?this._logger.warning(this,"Force disconnect from server!"):(this._logger.error(this,"Connection with the server has been closed"),this._main.dispatchEvent("serverDisconnect",{ref:this._main,serverURL:this.socketURL,restart:this._main.getConfigManager().getSettingsData().getIfRestartOnError(),sequenceNum:this._sequenceNumber}),this.initiateReconnect())}onSocketMessage(e){this._networkController.onMessage(e)}createURL(e){var t="";return(t+=e.getIfSSL()?"wss://":"ws://")+e.getHost()+(":"+e.getPort())+"/webrtc-session.json"}initiateReconnect(){var e=this._main.getConfigManager().getSettingsData().getIfRestartOnError();const t=this._main.getConfigManager().getSettingsData().getReconnectTime();this._disconnectedByUser||e&&(null!=this._reconnectTimer&&clearTimeout(this._reconnectTimer),this._reconnectTimer=setTimeout(()=>{this.pickServerFromList(this._main.getConfigManager().getStreamData().getServerList()),null!=this._currServer&&(this._logger.info(this,`Will reconnect to the server in ${t} seconds...`),this.socketURL=this.createURL(this._currServer),this._logger.info(this,"Starting WebSocket connection with: "+this.socketURL),this._main.dispatchEvent("serverConnectionInitiate",{ref:this._main,serverURL:this.socketURL}),this.startConnection())},1e3*t))}pickServerFromList(t){let i=null;for(let e=0;e<t.length;e++)if(!t[e].getIfFaild()){i=t[e];break}null==i?(this._logger.error(this,"All connections failed!"),this._main.dispatchEvent("allConnectionsFailed",{ref:this._main,mode:"none"}),this._currServer=null):this._currServer=i}isConnectionActive(){return this._isConnected}getCurrentServer(){return this._currServer}destroy(){super.destroy(),null!=this._reconnectTimer&&clearTimeout(this._reconnectTimer)}}class Y{constructor(e){this._currentStreamKey="none",this._lastState="",this.onServerConnect=()=>{},this.onServerDisconnect=()=>{this._lastState="none"},this.onMessage=e=>{var t;null!=(t=this._main.getStreamerController())&&t.onSocketMessage(e.data)},this._main=e,this._logger=e.getLogger(),this._main.addEventListener("serverConnect",this.onServerConnect,!1),this._main.addEventListener("serverDisconnect",this.onServerDisconnect,!1)}initialize(){null!=this._connection&&(this._connection.getConnectionState()==M.CONNECTING||this._connection.getConnectionState()==M.CONNECTED?this._logger.info(this,"Connection is alive, not doing anything!"):(this._logger.info(this,"Connection is dead, restarting!"),this._connection.startConnection()))}start(){this._connection=new q(this._main,this)}stop(){this._connection.disconnect(!0),this._lastState=""}sendMessage(e){this._connection.isConnectionActive()&&this._connection.sendData(e)}getConnection(){return this._connection}getCurrentStreamKey(){return this._currentStreamKey}}class J{constructor(e){this._publishVideoWidth=0,this._publishVideoHeight=0,this._publishVideoBitrate=0,this._publishAudioBitrate=0,this._currentBitrate=0,this._currentFPS=0,this._deliveredVideoFrames=0,this._deliveredAudioFrames=0,this.onStreamStatsUpdate=e=>{this._publishVideoWidth=e.streamStatus.videoWidth,this._publishVideoHeight=e.streamStatus.videoHeight,this._currentBitrate=e.streamStatus.currentBitrate,this._publishVideoBitrate=e.streamStatus.videoPublishBitrate,this._publishAudioBitrate=e.streamStatus.audioPublishBitrate,this._currentFPS=e.streamStatus.frameRate,this._deliveredVideoFrames=e.streamStatus.videoFrameCount,this._deliveredAudioFrames=e.streamStatus.audioFrameCount},this._main=e,this._logger=e.getLogger(),this._logger.info(this,"Creating new StatsController"),this.initialize()}initialize(){this._main.addEventListener("streamStatusUpdate",this.onStreamStatsUpdate,!1)}get deliveredVideoFrames(){return this._deliveredVideoFrames}get deliveredAudioFrames(){return this._deliveredAudioFrames}get currentFPS(){return this._currentFPS}get publishVideoWidth(){return this._publishVideoWidth}get publishVideoHeight(){return this._publishVideoHeight}get currentBitrate(){return this._currentBitrate}get publishVideoBitrate(){return this._publishVideoBitrate}get publishAudioBitrate(){return this._publishAudioBitrate}}class P{constructor(e,t,i,s=1){if(this._currentX=0,this._isFullyDrawn=!1,this._lastTimestamp=null,this._isTimemarkLine=!1,this._borderWidth=1,i.length!==t.length+1)throw new Error(`Colors array must have exactly ${t.length+1} elements (one more than valueRanges)`);for(let e=1;e<t.length;e++)if(t[e]<=t[e-1])throw new Error("ValueRanges must be in ascending order");const n=/^#[0-9A-Fa-f]{6}$/;if(!i.every(e=>n.test(e)))throw new Error("All colors must be in valid hex format (e.g., #FF0000)");let r;if("string"==typeof e){var o=document.getElementById(e);if(!o)throw new Error(`Container element with id ${e} not found`);r=o}else r=e;o=r.getBoundingClientRect(),this._width=Math.floor(o.width),this._height=Math.floor(o.height),this._effectiveWidth=this._width-2*this._borderWidth,this._effectiveHeight=this._height-2*this._borderWidth,this._canvas=document.createElement("canvas"),r.appendChild(this._canvas),e=this._canvas.getContext("2d",{willReadFrequently:!0});if(!e)throw new Error("Failed to get canvas context");this._ctx=e,this._valueRanges=[0,...t],this._colors=i,this._lineWidth=s,this._canvas.width=this._width,this._canvas.height=this._height,this._canvas.style.width=this._width+"px",this._canvas.style.height=this._height+"px",this.clear()}drawBorder(){this._ctx.strokeStyle="#000000",this._ctx.lineWidth=this._borderWidth,this._ctx.strokeRect(this._borderWidth/2,this._borderWidth/2,this._width-this._borderWidth,this._height-this._borderWidth)}clear(){this._ctx.clearRect(0,0,this._width,this._height),this._ctx.fillStyle=this._colors[0],this._ctx.fillRect(this._borderWidth,this._borderWidth,this._effectiveWidth,this._effectiveHeight),this.drawBorder(),this._isFullyDrawn=!1,this._currentX=this._borderWidth,this._lastTimestamp=null,this._isTimemarkLine=!1}getColorIndices(t){for(let e=0;e<this._valueRanges.length-1;e++)if(t>=this._valueRanges[e]&&t<=this._valueRanges[e+1])return{lowerIndex:e,upperIndex:e+1};return{lowerIndex:this._valueRanges.length-2,upperIndex:this._valueRanges.length-1}}calculateHeightRatio(e,t,i){return(e-t)/(i-t)}shiftCanvasLeft(e){e=this._ctx.getImageData(this._borderWidth+e,this._borderWidth,this._effectiveWidth-e,this._effectiveHeight);this._ctx.fillStyle=this._colors[0],this._ctx.fillRect(this._borderWidth,this._borderWidth,this._effectiveWidth,this._effectiveHeight),this._ctx.putImageData(e,this._borderWidth,this._borderWidth),this.drawBorder()}applyOverlayEffect(e,s=.5){var t=parseInt(e.slice(1,3),16),i=parseInt(e.slice(3,5),16),e=parseInt(e.slice(5,7),16),n=e=>{var t=e/255;let i;return i=t<=.5?2*t*1:1-2*(1-t)*0,Math.round(255*i*s+e*(1-s))},t=n(t),i=n(i),n=n(e),e=e=>{e=e.toString(16);return 1===e.length?"0"+e:e};return"#"+e(t)+e(i)+e(n)}addEntry(e){e=Math.round(100*e)/100;var t=Date.now(),t=(null===this._lastTimestamp?(this._lastTimestamp=t,this._isTimemarkLine=!1):1e3<=t-this._lastTimestamp?(this._isTimemarkLine=!0,this._lastTimestamp=t):this._isTimemarkLine=!1,this._isTimemarkLine?1:this._lineWidth);!this._isFullyDrawn&&this._currentX>=this._width-this._borderWidth&&(this._isFullyDrawn=!0),this._isFullyDrawn?(this.shiftCanvasLeft(t),this.drawLine(this._width-this._borderWidth-t,e,t)):(this.drawLine(this._currentX,e,t),this._currentX+=t)}drawLine(e,t,i){var{lowerIndex:s,upperIndex:n}=this.getColorIndices(t),t=this.calculateHeightRatio(t,this._valueRanges[s],this._valueRanges[n]);let r=this._colors[s],o=this._colors[n];this._isTimemarkLine&&(r=this.applyOverlayEffect(r,.3),o=this.applyOverlayEffect(o,.3));s=Math.round(this._effectiveHeight*t),n=this._effectiveHeight-s;this._ctx.fillStyle=r,this._ctx.fillRect(e,this._height-this._borderWidth-n,i,n),this._ctx.fillStyle=o,this._ctx.fillRect(e,this._borderWidth,i,s)}clearGraph(){this._currentX=this._borderWidth,this._isFullyDrawn=!1,this._lastTimestamp=null,this._isTimemarkLine=!1,this.clear()}destroy(){this._canvas.parentNode&&this._canvas.parentNode.removeChild(this._canvas)}}class Q{constructor(e,t){this.onStreamStatsUpdate=e=>{var t;null!=(t=this._graph)&&t.addEntry(e.streamStatus.currentBitrate)},this._main=e,this._object=t,this._main.addGraph(this)}start(){null!=this._graph&&stop();return this._graph=new P(this._object,[1e6,2e6,3e6,5e6,6e6,7e6],["#000000","#0a3980","#2793dd","#3bc39c","#c3df3e","#f89539","#f83f3f"]),this._main.addEventListener("streamStatusUpdate",this.onStreamStatsUpdate),this}stop(){return this._main.removeEventListener("streamStatusUpdate",this.onStreamStatsUpdate),null!=this._graph&&this._graph.destroy(),this._graph=null,this}}class ee{constructor(e,t){this.onStreamStatsUpdate=e=>{var t;null!=(t=this._graph)&&t.addEntry(e.streamStatus.frameRate)},this._main=e,this._object=t,this._main.addGraph(this)}start(){null!=this._graph&&stop();return this._graph=new P(this._object,[25,26,27,28,29,30],["#000000","#0a3980","#2793dd","#3bc39c","#c3df3e","#f89539","#f83f3f"]),this._main.addEventListener("streamStatusUpdate",this.onStreamStatsUpdate),this}stop(){return this._main.removeEventListener("streamStatusUpdate",this.onStreamStatsUpdate),null!=this._graph&&this._graph.destroy(),this._graph=null,this}}class A extends class{constructor(){this._isRemoved=!1,this._listeners={}}addEventListener(t,i,e=!0){this._listeners[t]||(this._listeners[t]=[]);let s=!1;if(null!=this._listeners[t]&&0<this._listeners[t].length)for(let e=0;e<this._listeners[t].length;e++)if(this._listeners[t][e][1]==i){s=!0;break}return this._logger.success(this,"Registering a new event: "+t),!s&&(this._listeners[t].push([t,i,e]),!0)}removeEventListener(t,i){let s=!1;if(null!=this._listeners[t]&&0<this._listeners[t].length)for(let e=0;e<this._listeners[t].length;e++){var n=this._listeners[t][e];if(i){if(n[1]==i){if(1!=n[2])break;s=!0,this._listeners[t].splice(e,1);break}}else s=!0,1==n[2]&&this._listeners[t].splice(e,1)}return this._logger.success(this,"Removing listener: "+t),s}removeAllEventListeners(){this._logger.success(this,"Removing all listeners!");for(const i in this._listeners){var e=i,t=this._listeners[e];if(t&&0<t.length)for(let e=t.length-1;0<=e;e--)!0===t[e][2]&&t.splice(e,1)}}dispatchEvent(t,i){if(!this._isRemoved&&null!=this._listeners[t]&&0<this._listeners[t].length)for(let e=0;e<this._listeners[t].length;e++)this._listeners[t][e][1].call(this,i)}}{constructor(e,t=!1){super(),this.DEV_MODE=!0,this.STREAMER_VERSION="0.9.2-beta.2",this.COMPILE_DATE="3/6/2025, 2:53:15 PM",this.STREAMER_BRANCH="Experimental",this.STREAMER_PROTOCOL_VERSION=1,this._initialized=!1,"undefined"!=typeof window&&window.document&&window.document.createElement?(!this.DEV_MODE||"StormStreamerArray"in window||(window.StormStreamerArray=[]),window.StormStreamerArray.push(this),this._streamerID=A.NEXT_STREAMER_ID++,null!=e&&(this.setStreamConfig(e),t)&&this.initialize()):console.error('StormStreamer Creation Error - No "window" element in the provided context!')}initialize(){if(!this._isRemoved){if(null==this._configManager)throw Error("Stream Config was not provided for this streamer! A properly configured object must be provided through the constructor or via the setConfig method before using the initialize() method.");this._storageManager=new e(this),this._stageController=new O(this),this._networkController=new Y(this),this._streamerController=new j(this),this._statsController=new J(this),this._graphs=[],this._initialized=!0,this.dispatchEvent("streamerReady",{ref:this})}}setStreamConfig(e){this._isRemoved||(e=JSON.parse(JSON.stringify(e)),null==this._configManager?(this._configManager=new u(e),this._logger=new m(this._configManager.getSettingsData().getDebugData(),this),this._logger.info(this,"StreamerID: "+this._streamerID),this._logger.info(this,"Version: "+this.STREAMER_VERSION+" | Compile Date: "+this.COMPILE_DATE+" | Branch: "+this.STREAMER_BRANCH),this._logger.info(this,"UserCapabilities :: Browser: "+v.getBrowserName()+" "+v.getBrowserVersion()),this._logger.info(this,"UserCapabilities :: Operating System: "+v.getOS()+" "+v.getOSVersion()),this._logger.info(this,"UserCapabilities :: isMobile: "+v.isMobile()),this._logger.info(this,"UserCapabilities :: hasMSESupport: "+v.hasMSESupport()),this._logger.info(this,"UserCapabilities :: hasWebSocketSupport: "+v.hasWebSocketsSupport()),this._logger.info(this,"UserCapabilities :: hasWebRTCSupport: "+v.hasWebRTCSupport()),this._configManager.print(this._logger)):(this._logger.info(this,"StreamConfig has been overwritten, dispatching streamConfigChanged!"),this._configManager=new u(e),this._configManager.print(this._logger),this.dispatchEvent("streamConfigChange",{ref:this,newConfig:this._configManager})))}isConnected(){var e;return null!=(e=null==(e=this._networkController)?void 0:e.getConnection().isConnectionActive())&&e}mute(){null!=this._stageController&&null!=this._stageController.getScreenElement()?this._stageController.getScreenElement().setMuted(!0):this._configManager.getSettingsData().getAudioData().muted=!0}unmute(){null!=this._stageController&&null!=this._stageController.getScreenElement()?this._stageController.getScreenElement().setMuted(!1):this._configManager.getSettingsData().getAudioData().muted=!1}isMute(){var e;return null!=(e=null!=(e=null==(e=null==(e=this._stageController)?void 0:e.getScreenElement())?void 0:e.getIfMuted())?e:this._configManager.getSettingsData().getAudioData().muted)&&e}toggleMute(){var e=this.isMute();return e?this.unmute():this.mute(),!e}setVolume(e){var t;void 0===(null==(t=null==(t=this._stageController)?void 0:t.getScreenElement())?void 0:t.setVolume(e))&&(this._configManager.getSettingsData().getAudioData().startVolume=e)}getVolume(){var e;return null!=(e=null==(e=null==(e=this._stageController)?void 0:e.getScreenElement())?void 0:e.getVolume())?e:this._configManager.getSettingsData().getAudioData().startVolume}getCameraList(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.getCameraList())?e:[]}getMicrophoneList(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.getMicrophoneList())?e:[]}setCamera(e){var t;null!=(t=this._streamerController)&&t.selectCamera(e)}setMicrophone(e){var t;null!=(t=this._streamerController)&&t.selectMicrophone(e)}getCurrentCamera(){return this._streamerController.getCurrentCamera()}getCurrentMicrophone(){return this._streamerController.getCurrentMicrophone()}muteMicrophone(e){var t;null!=(t=this._streamerController)&&t.muteMicrophone(e)}isMicrophoneMuted(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.isMicrophoneMuted())&&e}getPublishState(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.getPublishState())?e:h.PublishState.NOT_INITIALIZED}getPublishTime(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.getPublishTime())?e:0}publish(e){var t;return null!=(t=null==(t=this._streamerController)?void 0:t.publish(e))&&t}getInputDevicesState(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.getInputDeviceState())?e:h.InputDevicesState.NOT_INITIALIZED}getCamerState(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.getCamerState())?e:h.DeviceState.NOT_INITIALIZED}getMicrophoneState(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.getMicrophoneState())?e:h.DeviceState.NOT_INITIALIZED}clearSavedDevices(){var e;return null==(e=this._streamerController)?void 0:e.clearSavedDevices()}messSavedDevices(){var e;return null==(e=this._streamerController)?void 0:e.messSavedDevices()}isStreamReady(){var e;return null!=(e=null==(e=this._streamerController)?void 0:e.isStreamReady())&&e}unpublish(){var e;null!=(e=this._streamerController)&&e.unpublish()}attachToContainer(e){var t;return!!this._initialized&&null!=(t=null==(t=this._stageController)?void 0:t.attachToParent(e))&&t}detachFromContainer(){var e;return!!this._initialized&&null!=(e=null==(e=this._stageController)?void 0:e.detachFromParent())&&e}getContainer(){var e;return null!=(e=null==(e=this._stageController)?void 0:e.getParentElement())?e:null}setSize(e,t){this._initialized?this._stageController.setSize(e,t):(e=_.parseValue(e),t=_.parseValue(t),this._configManager.getSettingsData().getVideoData().videoWidthValue=e.value,this._configManager.getSettingsData().getVideoData().videoWidthInPixels=e.isPixels,this._configManager.getSettingsData().getVideoData().videoHeightValue=t.value,this._configManager.getSettingsData().getVideoData().videoHeightInPixels=t.isPixels)}setWidth(e){this._initialized?this._stageController.setWidth(e):(e=_.parseValue(e),this._configManager.getSettingsData().getVideoData().videoWidthValue=e.value,this._configManager.getSettingsData().getVideoData().videoWidthInPixels=e.isPixels)}setHeight(e){this._initialized?this._stageController.setHeight(e):(e=_.parseValue(e),this._configManager.getSettingsData().getVideoData().videoHeightValue=e.value,this._configManager.getSettingsData().getVideoData().videoHeightInPixels=e.isPixels)}getWidth(){return this._initialized?this._stageController.getContainerWidth():this._configManager.getSettingsData().getVideoData().videoWidthInPixels?this._configManager.getSettingsData().getVideoData().videoWidthValue:0}getHeight(){return this._initialized?this._stageController.getContainerHeight():this._configManager.getSettingsData().getVideoData().videoHeightInPixels?this._configManager.getSettingsData().getVideoData().videoHeightValue:0}setScalingMode(e){this._stageController?this._stageController.setScalingMode(e):this._configManager.getSettingsData().getVideoData().scalingMode=e}getScalingMode(){return this._stageController?this._stageController.getScalingMode():this._configManager.getSettingsData().getVideoData().scalingMode}updateToSize(){this._initialized&&this._stageController.handleResize()}makeScreenshot(){let i=document.createElement("canvas"),s=i.getContext("2d");return new Promise(t=>{var e;null!=this._stageController&&(i.width=this._stageController.getScreenElement().getVideoElement().videoWidth,i.height=this._stageController.getScreenElement().getVideoElement().videoHeight,e=this._stageController.getScreenElement().getVideoElement(),s)?(s.drawImage(e,0,0,i.width,i.height),i.toBlob(e=>{t(e)},"image/png")):t(null)})}createFPSGraph(e){return new ee(this,e)}createBitrateGraph(e){return new Q(this,e)}addGraph(e){null!=this._graphs&&this._graphs.push(e)}stopAllGraphs(){if(null!=this._graphs&&0<this._graphs.length)for(let e=0;e<this._graphs.length;e++)this._graphs[e].stop()}enterFullScreen(){this._initialized&&this._stageController&&this._stageController.enterFullScreen()}exitFullScreen(){this._initialized&&this._stageController&&this._stageController.exitFullScreen()}isFullScreenMode(){return!(!this._initialized||!this._stageController)&&this._stageController.isFullScreenMode()}getStreamKey(){var e;return null!=(e=null==(e=null==(e=this.getConfigManager())?void 0:e.getStreamData())?void 0:e.streamKey)?e:null}getStatsController(){return this._statsController}getStreamerID(){return this._streamerID}getLogger(){return this._logger}getConfigManager(){return this._configManager}getNetworkController(){return this._networkController}getStreamerController(){return this._streamerController}getStageController(){return this._stageController}getVideoElement(){var e;return null!=(e=null==(e=null==(e=this._stageController)?void 0:e.getScreenElement())?void 0:e.getVideoElement())?e:null}isInitialized(){return this._initialized}getVersion(){return this.STREAMER_VERSION}getBranch(){return this.STREAMER_BRANCH}getStorageManager(){return this._storageManager}dispatchEvent(e,t){super.dispatchEvent(e,t)}start(){var e;return r(this,void 0,void 0,function*(){return null==(e=this._streamerController)?void 0:e.start()})}stop(){var e;return null==(e=this._streamerController)?void 0:e.stop()}destroy(){var e;this._logger.warning(this,"Destroying streamer instance, bye, bye!"),this.DEV_MODE&&"StormStreamerArray"in window&&(window.StormStreamerArray[this._streamerID]=null),this._initialized=!1,this._isRemoved=!0,null!=(e=null==(e=this._networkController)?void 0:e.getConnection())&&e.destroy(),null!=(e=this._streamerController)&&e.destroy(),null!=(e=this._stageController)&&e.destroy(),this.removeAllEventListeners()}}A.NEXT_STREAMER_ID=0,h.StormStreamer=A,h.create=function(e){return new A(e)}});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stormstreaming/stormstreamer",
|
|
3
|
-
"version": "0.9.2-beta.
|
|
3
|
+
"version": "0.9.2-beta.2",
|
|
4
4
|
"description": "A JavaScript library containing core webrtc streamer functionality for embedding live-video streams on a website. Part of StormStreaming Suite.",
|
|
5
5
|
"author": "Web-Anatomy s.c. <contact@web-anatomy.com>",
|
|
6
6
|
"main": "dist/iife/index.js",
|