@zoom/meetingsdk 3.13.0 → 3.13.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.
@@ -1,2 +1,2 @@
1
1
  (window.webpackJsonpJsMediaSDK_Instance=window.webpackJsonpJsMediaSDK_Instance||[]).push([[3],{100:function(e,t,i){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return s(t,e),t},r=this&&this.__awaiter||function(e,t,i,a){return new(i||(i=Promise))((function(s,n){function r(e){try{c(a.next(e))}catch(e){n(e)}}function o(e){try{c(a.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,o)}c((a=a.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.replaceComma=t.isDevelopment=t.compareResourceUsageState=t.compareArrays=t.decodeString=t.encodeString=t.base64ToArrayBuffer=t.arrayBufferToBase64=t.decompress=t.compress=t.setTrackContentHint=t.stopMediaStream=t.stopMediaStreams=t.getStreamId=t.getNodeId=void 0;const o=n(i(99));function c(e){(null==e?void 0:e.getTracks)&&e.getTracks().forEach(e=>{e.stop()})}function d(e,t){return r(this,void 0,void 0,(function*(){const a=(new TextEncoder).encode(e);if(window.CompressionStream){const e=new CompressionStream(t),i=e.writable.getWriter();return i.write(a),i.close(),new Response(e.readable).arrayBuffer()}{const{gzip:e}=yield Promise.resolve().then(()=>n(i(109)));return e(a).buffer}}))}function l(e,t){return r(this,void 0,void 0,(function*(){if(window.DecompressionStream){const i=new DecompressionStream(t),a=i.writable.getWriter();return a.write(e),a.close(),new Response(i.readable).arrayBuffer().then((function(e){return(new TextDecoder).decode(e)}))}{const{ungzip:t}=yield Promise.resolve().then(()=>n(i(109)));return(new TextDecoder).decode(t(e).buffer)}}))}function h(e){let t="";const i=new Uint8Array(e);for(let e=0;e<i.byteLength;e++)t+=String.fromCharCode(i[e]);return btoa(t)}function u(e){const t=atob(e),i=new Uint8Array(t.length);for(let e=0;e<i.length;e++)i[e]=t.charCodeAt(e);return i.buffer}t.getNodeId=function(e){return 4294966272&e},t.getStreamId=function(e,t){let i=0;switch(t){case o.SESSION_ID.VIDEO:i=o.STREAM_ID_MASK.VIDEO;break;case o.SESSION_ID.AUDIO:i=o.STREAM_ID_MASK.AUDIO;break;case o.SESSION_ID.SHARE:i=o.STREAM_ID_MASK.SHARE}return-4&e|i},t.stopMediaStreams=function(e){e&&(Array.isArray(e)?e.forEach(e=>{c(e)}):c(e))},t.stopMediaStream=c,t.setTrackContentHint=function(e,t){if(e.contentHint=t,e.contentHint!==t)throw new Error("Invalid track contentHint: "+t)},t.compress=d,t.decompress=l,t.arrayBufferToBase64=h,t.base64ToArrayBuffer=u,t.encodeString=function(e,t){return r(this,void 0,void 0,(function*(){switch(t){case o.TEXT_ENCODING.GZIP_BASE64:return h(yield d(e,"gzip"));case o.TEXT_ENCODING.PLAIN:return e;default:return null}}))},t.decodeString=function(e,t){return r(this,void 0,void 0,(function*(){switch(t){case o.TEXT_ENCODING.GZIP_BASE64:return l(u(e),"gzip");case o.TEXT_ENCODING.PLAIN:return e;default:return null}}))},t.compareArrays=function(e,t){return e.length===t.length&&e.every((e,i)=>e===t[i])},t.compareResourceUsageState=function(e,t){return e-t},t.isDevelopment=function(){return!1},t.replaceComma=function(e,t="|"){return e?e.toString().replaceAll(/[,,]/g,t):""}},101:function(e,t,i){"use strict";i.r(t);var a=i(102),s=i(99),n=i(100);const r=new class{constructor(){this.setTrace()}setTrace(e,t){t&&(t.log||t.info)&&t.error&&t.warn?(this.log=t.log||t.info,this.info=t.info||t.log,this.debug=t.debug||t.log,this.verbose=this._verbose,this.error=t.error,this.warn=t.warn):(this.verbose=this._verbose.bind(this),this.log=this._log.bind(this),this.info=this._info.bind(this),this.debug=this._debug.bind(this),this.error=this._error.bind(this),this.warn=this._warn.bind(this)),this.level=e||s.TRACE_LEVEL.INFO,this.level=this.level<s.TRACE_LEVEL.ERROR?s.TRACE_LEVEL.ERROR:this.level,this.level=this.level>s.TRACE_LEVEL.VERBOSE?s.TRACE_LEVEL.VERBOSE:this.level,this.getLevel=()=>this.level,this._trace=(e,t)=>{switch(e){case"log":console.log(...t);break;case"debug":console.debug(...t);break;case"info":console.info(...t);break;case"warn":console.warn(...t);break;case"error":console.error(...t)}}}getTracer(e){var t=this;return n.isDevelopment()?{log:function(){for(var i=arguments.length,a=new Array(i),s=0;s<i;s++)a[s]=arguments[s];return t.log(e,...a)},debug:function(){for(var i=arguments.length,a=new Array(i),s=0;s<i;s++)a[s]=arguments[s];return t.debug(e,...a)},info:function(){for(var i=arguments.length,a=new Array(i),s=0;s<i;s++)a[s]=arguments[s];return t.info(e,...a)},warn:function(){for(var i=arguments.length,a=new Array(i),s=0;s<i;s++)a[s]=arguments[s];return t.warn(e,...a)},error:function(){for(var i=arguments.length,a=new Array(i),s=0;s<i;s++)a[s]=arguments[s];return t.error(e,...a)}}:{log:()=>{},debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}}}setTelemetry(e){this._telemetry="function"==typeof e?e:null}monitorLog(e){e&&this._telemetry&&this._telemetry({type:a.eventOut.MONITOR,data:e})}directSendMonitorLog(e){e&&this._telemetry&&this._telemetry({type:a.eventOut.DIRECT_MONITOR,data:e})}globalTrace(e){e&&this._telemetry&&this._telemetry({type:a.eventOut.GLOBAL_TRACE,data:e})}_verbose(){if(this.level>=s.TRACE_LEVEL.VERBOSE){const e=[...arguments];return e.unshift("[VERBOSE]"),this._trace("log",e),!0}return!1}_debug(){return this.level>=s.TRACE_LEVEL.DEBUG&&(this._trace("debug",arguments),!0)}_log(){return this.level>=s.TRACE_LEVEL.INFO&&(this._trace("log",arguments),!0)}_info(){return this.level>=s.TRACE_LEVEL.INFO&&(this._trace("info",arguments),!0)}_warn(){return this.level>=s.TRACE_LEVEL.WARN&&(this._trace("warn",arguments),!0)}_error(){return this.level>=s.TRACE_LEVEL.ERROR&&(this._trace("error",arguments),!0)}};t.default=r},102:function(e,t,i){"use strict";var a,s;Object.defineProperty(t,"__esModule",{value:!0}),t.eventOut=t.eventExt=void 0,function(e){e.NOTIFY_SDK_JOIN_RWG_SUCCESS="NOTIFY_SDK_JOIN_RWG_SUCCESS",e.NOTIFY_SDK_JOIN_RWG_FAILURE="NOTIFY_SDK_JOIN_RWG_FAILURE",e.VIDEO_STREAMS="VIDEO_STREAMS",e.WMSC_MESSAGE_FROM_RWG="WMSC_MESSAGE_FROM_RWG",e.NOTIFY_WMSC_VIDEO_TAG_MAPPING="NOTIFY_WMSC_VIDEO_TAG_MAPPING",e.NOTIFY_SDK_SUBSCRIBE_VIDEO="NOTIFY_SDK_SUBSCRIBE_VIDEO",e.NOTIFY_SDK_UNSUBSCRIBE_VIDEO="NOTIFY_SDK_UNSUBSCRIBE_VIDEO",e.NOTIFY_SDK_ACTIVE_VIDEO_INDICATION="NOTIFY_SDK_ACTIVE_VIDEO_INDICATION",e.UPDATE_WMSC_PARAMS="UPDATE_WMSC_PARAMS"}(a||(t.eventExt=a={})),function(e){e.ERROR="ERROR",e.WMSC_MESSAGE_TO_RWG_BY_SDK="WMSC_MESSAGE_TO_RWG_BY_SDK",e.WMSC_MAPPING_STREAMID_AND_MID="WMSC_MAPPING_STREAMID_AND_MID",e.GLOBAL_TRACE="GLOBAL_TRACE",e.MONITOR="MONITOR",e.DIRECT_MONITOR="DIRECT_MONITOR",e.SDP_NEGOTIATION_FAIL="SDP_NEGOTIATION_FAIL",e.CREATE_VIDEO_STREAMS_SUCCESS="CREATE_VIDEO_STREAMS_SUCCESS",e.CREATE_VIDEO_STREAMS_FAIL="CREATE_VIDEO_STREAMS_FAIL",e.V_RECEV_PC_CONNECTED="V_RECEV_PC_CONNECTED",e.V_SEND_PC_CONNECTED="V_SEND_PC_CONNECTED",e.VIDEO_SOURCE_UPDATED="VIDEO_SOURCE_UPDATED",e.VIDEO_TAG_MAPPED="VIDEO_TAG_MAPPED",e.VIDEO_QOS_DATA="VIDEO_QOS_DATA",e.UPDATE_VIDEO_CAPTURE_CONSTRAINTS="UPDATE_VIDEO_CAPTURE_CONSTRAINTS",e.ERROR_MESSAGE="ERROR_MESSAGE",e.NETWORK_QUALITY_CHANGE="NETWORK_QUALITY_CHANGE"}(s||(t.eventOut=s={}))},104:function(e,t,i){"use strict";i.r(t),i.d(t,"BrowserInfo",(function(){return n}));var a=i(14),s=i.n(a);class n{constructor(){this.browser=void 0,this.browserVersion=void 0,this.os=void 0,this.osVersion=void 0,this.hardwareConcurrency=navigator.hardwareConcurrency||1,this.isMobile=this._isMobile(navigator.userAgent),this._getBrowserAndOSVersions(navigator.userAgent)}_getBrowserAndOSVersions(e){for(const[t,i]of Object.entries(n.regex)){const a=e.match(i);if(a)switch(t){case"iOS":this.os=t,this.osVersion=a[1].replace(/_/g,".");break;case"macOS":this.os=t;break;case"Windows":case"Android":case"ChromeOS":this.os=t,this.osVersion=a[1];break;case"Linux":e.match(n.regex.Android)||(this.os=t);break;case"SafariIOS":this.browser||(this.browser="Safari",this.browserVersion=a[1].split("/")[1]),this.os="iOS",this.osVersion=a[2];break;default:this.browser||(this.browser=t,this.browserVersion=a[1])}}}_isMobile(e){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(e)}getMajorBrowserVersion(){var e;const t=parseInt(null===(e=this.browserVersion)||void 0===e?void 0:e.split(".")[0],10);return isNaN(t)?void 0:t}getMinorBrowserVersion(){var e;const t=parseInt(null===(e=this.browserVersion)||void 0===e?void 0:e.split(".")[1],10);return isNaN(t)?void 0:t}isBrowserVersionGreaterEqualThan(e,t){const i=this.getMajorBrowserVersion(),a=this.getMinorBrowserVersion();return i>e||i===e&&a>=t}getMajorOsVersion(){var e;const t=parseInt(null===(e=this.osVersion)||void 0===e?void 0:e.split(".")[0],10);return isNaN(t)?void 0:t}getMinorOsVersion(){var e;const t=parseInt(null===(e=this.osVersion)||void 0===e?void 0:e.split(".")[1],10);return isNaN(t)?void 0:t}isOsVersionGreaterEqualThan(e,t){const i=this.getMajorOsVersion(),a=this.getMinorOsVersion();return i>e||i===e&&a>=t}}s()(n,"regex",{Chrome:/(?:Chrome|Chromium|CriOS)\/([\d.]+)/,Firefox:/(?:Firefox|FxiOS)\/([\d.]+)/,Safari:/Version\/([\d.]+)\sSafari/,SafariIOS:/(Version\/[\d.]+).*Mobile\/([\w]+)/,IE:/MSIE\s([\d.]+)/,Edge:/Edg\/([\d.]+)/,Opera:/(?:Opera|OPR)\/([\d.]+)/,Android:/Android\s([\d.]+)/,iOS:/(?:iPhone|iPad|iPod).*OS\s([\d_]+)/,Windows:/Windows NT\s([\d.]+)/,macOS:/Mac OS X\s([\d_.]+)/,Linux:/Linux/,ChromeOS:/CrOS/}),t.default=new n},105:function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isLowResolution=t.getLayerIdByVideoFormat=t.getMaxBitrateByVideoFormat=t.getMinBitrate=t.getTargetBitrate=t.getMaxBitrate=t.getMaxFramerate=t.findVideoFormat=t.findVideoFormatIndex=t.getLowestVideoFormat=t.getHighestVideoFormat=t.getVideoFormatByIndex=t.getLayerSettings=t.getMinEncodingBitrate=t.getMaxEnabledLayerId=t.isLayerEnabled=t.getMinEnabledLayerId=t.getEnabledLayerIds=t.getLayersSettings=t.setDefaultLayersSettings=t.setEnabledLayerIds=t.setLayersSettings=void 0;const a=i(108),s=[{layerId:4,width:1920,height:1080,maxFramerate:30,minBitrate:3e6,targetBitrate:4e6,maxBitrate:5e6},{layerId:4,width:1600,height:900,maxFramerate:30,minBitrate:15e5,targetBitrate:3e6,maxBitrate:35e5},{layerId:3,width:1280,height:720,maxFramerate:30,minBitrate:8e5,targetBitrate:2e6,maxBitrate:2e6},{layerId:3,width:960,height:540,maxFramerate:30,minBitrate:5e5,targetBitrate:8e5,maxBitrate:12e5},{layerId:2,width:640,height:360,maxFramerate:30,minBitrate:25e4,targetBitrate:5e5,maxBitrate:7e5},{layerId:2,width:480,height:270,maxFramerate:30,minBitrate:18e4,targetBitrate:35e4,maxBitrate:45e4},{layerId:1,width:320,height:180,maxFramerate:30,minBitrate:1e5,targetBitrate:15e4,maxBitrate:2e5},{layerId:1,width:256,height:144,maxFramerate:30,minBitrate:6e4,targetBitrate:1e5,maxBitrate:15e4}];function n(e){a.wmscConfig.setLayersSettings(e)}function r(){return a.wmscConfig.layersSettings}function o(){return a.wmscConfig.enabledLayerIds}function c(e){const t=r();if(!t||t.length<=e)return;const{width:i,height:a,maxFramerate:s,minBitrate:n,targetBitrate:o,maxBitrate:c}=t[e];return{width:i,height:a,maxFramerate:s,minBitrate:n,targetBitrate:o,maxBitrate:c}}function d(e){const t=r();if(!t)return;const i=t.findIndex(t=>t.layerId===e);return i>=0?c(i):void 0}function l(e){const t=r();if(t)for(let i=t.length-1;i>=0;i--)if(t[i].layerId===e)return c(i)}function h(e,t,i=!0){const a=r();if(!(null==a?void 0:a.length))return-1;const s=o();if(i)for(let i=0;i<a.length;i++){const n=a[i];if(s.includes(n.layerId)&&n.layerId===e&&t>=n.minBitrate&&t<=n.maxBitrate)return i}else for(let i=a.length-1;i>=0;i++){const n=a[i];if(s.includes(n.layerId)&&n.layerId===e&&t>=n.minBitrate&&t<=n.maxBitrate)return i}return-1}function u(e){return e.width*e.height<57600}t.setLayersSettings=n,t.setEnabledLayerIds=function(e){a.wmscConfig.setEnabledLayerIds(e)},t.setDefaultLayersSettings=function(e){const t=e?s.filter(({width:e,height:t})=>!u({width:e,height:t})):s;t.length&&(t[t.length-1].minBitrate=8e4),n(t)},t.getLayersSettings=r,t.getEnabledLayerIds=o,t.getMinEnabledLayerId=function(){return o()[0]},t.isLayerEnabled=function(e){return o().includes(e)},t.getMaxEnabledLayerId=function(){const e=o();return e[e.length-1]},t.getMinEncodingBitrate=function(){return 8e4},t.getLayerSettings=function(e){var t;const i=[];return null===(t=r())||void 0===t||t.forEach(t=>{t.layerId===e&&i.push(t)}),i},t.getVideoFormatByIndex=c,t.getHighestVideoFormat=d,t.getLowestVideoFormat=l,t.findVideoFormatIndex=h,t.findVideoFormat=function(e,t,i=!0){const a=h(e,t,i);if(a>=0)return c(a)},t.getMaxFramerate=function(e){var t;return(null===(t=d(e))||void 0===t?void 0:t.maxFramerate)||0},t.getMaxBitrate=function(e){var t;return(null===(t=d(e))||void 0===t?void 0:t.maxBitrate)||0},t.getTargetBitrate=function(e){var t;return(null===(t=d(e))||void 0===t?void 0:t.targetBitrate)||0},t.getMinBitrate=function(e){var t;return(null===(t=l(e))||void 0===t?void 0:t.minBitrate)||0},t.getMaxBitrateByVideoFormat=function(e,t){const i=d(e);if(i){const{width:e,height:a,maxBitrate:s}=i;return Math.floor(t.width*t.height/(e*a)*s)}},t.getLayerIdByVideoFormat=function(e){const t=e.width*e.height;return t>921600?4:t>307200?3:t>76800?2:t>19200?1:t>0?0:-1},t.isLowResolution=u},108:function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.wmscConfig=void 0;t.wmscConfig=new class{constructor(){this.confId="",this.nodeId="",this.maxCaptureVideoSize=4,this.maxRecvVideoNum=26,this.hdVideoEnabled=!1,this.isMacIntel=!1,this.videoSettings=null,this._enabledLayerIds=[],this._layersSettings=null,this.iceServers=[]}setConfig(e){const{confId:t,nodeId:i,maxCaptureResolution:a,maxVideoReceiveNum:s,HDVideo:n,isMacIntel:r,videoSettings:o,qosOptions:c,iceServers:d}=e;void 0!==t&&(this.confId=t),void 0!==i&&(this.nodeId=i),void 0!==a&&(this.maxCaptureVideoSize=a),void 0!==s&&(this.maxRecvVideoNum=s),void 0!==n&&(this.hdVideoEnabled=n),void 0!==r&&(this.isMacIntel=r),void 0!==o&&(this.videoSettings=o),void 0!==c&&(this.qosOptions=c),null!=d&&(this.iceServers=d||[])}getConfig(){const{confId:e,nodeId:t,maxRecvVideoNum:i,hdVideoEnabled:a,isMacIntel:s,videoSettings:n,qosOptions:r,iceServers:o}=this;return{confId:e,nodeId:t,maxRecvVideoNum:i,hdVideoEnabled:a,isMacIntel:s,videoSettings:n,qosOptions:r,iceServers:o}}setEnabledLayerIds(e){this._enabledLayerIds=e}get enabledLayerIds(){return this._enabledLayerIds}setLayersSettings(e){this._layersSettings=e}get layersSettings(){return this._layersSettings}}},112:function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.eventOut=t.eventExt=t.Wmsc=void 0;var a=i(121);Object.defineProperty(t,"Wmsc",{enumerable:!0,get:function(){return a.Wmsc}});var s=i(102);Object.defineProperty(t,"eventExt",{enumerable:!0,get:function(){return s.eventExt}}),Object.defineProperty(t,"eventOut",{enumerable:!0,get:function(){return s.eventOut}})},113:function(e,t,i){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return s(t,e),t},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WmscMidMgr=void 0;const o=r(i(101)),c=n(i(99)),d=r(i(104)),l=o.default.getTracer("WmscMidMgr"),h=e=>{l.log(e),o.default.monitorLog(""+e)};t.WmscMidMgr=class{constructor(e){this.mIdUsedStatus={},null==e||e.forEach(e=>{this.mIdUsedStatus[e]={userId:0,group:null,used:!1,videoStream:null,videoSize:-1,released:!0}}),this.user2VideoDom=new Map,this.hasPausedVideo=!1,this.activeSpeakerMId=c.DEFAULT_ACTIVE_SPEAKER_MID,this.userId2mId=new Map,this.userId2mId.set(1,"0"),this.hwDecoderLimit=c.MAX_RECV_MLINE_NUM+1}getNewMId(e,t=null){let i=this.userId2mId.get(e);if(void 0===i){let e="",t="";for(const a in this.mIdUsedStatus){const{used:s,released:n,preUserId:r}=this.mIdUsedStatus[a];if("0"!==a){if(!s){if(!r){i=a;break}n&&!e?e=a:t||(t=a)}if(parseInt(a,10)===this.hwDecoderLimit-1&&(e||t))break}}i||(i=e||t)}return i&&!this.mIdUsedStatus[i].used&&this._assignMid(i,e,t),i}_assignMid(e,t,i=null){this.mIdUsedStatus[e].userId=t,this.mIdUsedStatus[e].group=i,this.mIdUsedStatus[e].used=!0,t===c.ACTIVE_SPEAKER_ID&&(this.activeSpeakerMId=e);const{preUserId:a}=this.mIdUsedStatus[e];return a&&this.userId2mId.delete(a),this.userId2mId.set(t,e),e}releaseMId(e){const t=this.mIdUsedStatus[e];t&&(t.group=null,t.preUserId=t.userId,t.userId=0,t.used=!1,t.videoSize=-1)}getMId(e,t=null){const i=this.userId2mId.get(e);return void 0===i||this.mIdUsedStatus[i].userId!==e||this.mIdUsedStatus[i].group!==t?"":i}getUserId(e){return{userId:this.mIdUsedStatus[e].userId,group:this.mIdUsedStatus[e].group}}getVideoTags(e){const t=this.mIdUsedStatus[e].userId;if(t)return this.user2VideoDom.get(t)}saveVideoTag(e,t){const i=this.user2VideoDom.get(e)||[];i.push(t),this.user2VideoDom.set(e,i);for(const i in this.mIdUsedStatus)if(this.mIdUsedStatus[i].userId===e){this._setVideoTagStream(t,this.mIdUsedStatus[i].videoStream,e);break}}removeVideoTag(e,t){const i=this.user2VideoDom.get(e);if(i){for(let e=0;e<i.length;)i[e]===t?i.splice(e,1):e++;i.length||this.user2VideoDom.delete(e)}}updateUserId(e,t){const i=this.mIdUsedStatus[e];i&&(i.userId=t)}_setVideoTagStream(e,t,i){(!e.srcObject||e.srcObject&&t&&e.srcObject!==t)&&(e.srcObject=t,e.onpause=()=>{h(`WMSC_V_Tag_Pause: ${i}|${document.hidden}|${document.visibilityState}`),this.hasPausedVideo=!0})}updateVideoElement(e){if(this.mIdUsedStatus[e]){const t=this.mIdUsedStatus[e].userId,i=this.mIdUsedStatus[e].videoStream;(this.user2VideoDom.get(t)||[]).forEach(e=>{this._setVideoTagStream(e,i,t)})}}updateStream(e,t){this.mIdUsedStatus[e]&&(this.mIdUsedStatus[e].videoStream=t)}setVideoSize(e,t){this.mIdUsedStatus[e].videoSize=t}getVideoSizeByUserId(e){const t=this.userId2mId.get(e);return t?this.mIdUsedStatus[t].videoSize:-1}getUserIdByElem(e){let t=-1;return this.user2VideoDom.forEach((i,a)=>{for(let s=0;s<i.length;s++)if(e===i[s]){t=a;break}}),t}getHasPausedVideo(){return this.hasPausedVideo||Array.from(this.user2VideoDom.values()).flat().some(e=>e.paused)}playAllUsedVideoTag(){const e=Array.from(this.user2VideoDom.values()).flat().map(e=>{var t;if("visible"===document.visibilityState&&e.paused){const i=(null===(t=null==e?void 0:e.srcObject)||void 0===t?void 0:t.active)||!1;if(!(null==e?void 0:e.srcObject)||!i){const t=this.getUserIdByElem(e);return h(`WMSC_V_Tag_C_P: ${t}|${!!(null==e?void 0:e.srcObject)}|${i}`),Promise.reject(t)}return e.play().then(()=>Promise.resolve()).catch(t=>{const i=this.getUserIdByElem(e);return Promise.reject(`${i}|errorName:${null==t?void 0:t.name}|errorMessage:${null==t?void 0:t.message}`)})}return null}).filter(e=>!!e);return e.length<=0?Promise.resolve():Promise.all(e).then(()=>(this.hasPausedVideo=!1,Promise.resolve())).catch(e=>(this.hasPausedVideo=!0,Promise.reject(e)))}setMidReleasedStatus(e,t){this.mIdUsedStatus[e]&&(this.mIdUsedStatus[e].released=t)}getMidReleasedStatus(e){var t;return null===(t=this.mIdUsedStatus[e])||void 0===t?void 0:t.released}changeHWDecodeLimit(e){if(e===c.H264_HIGH_PROFILE&&("Edge"===d.default.browser||"Chrome"===d.default.browser)){if("macOS"===d.default.os||"Windows"===d.default.os)return void(this.hwDecoderLimit=8);if("ChromeOS"===d.default.os)return void(this.hwDecoderLimit=16)}this.hwDecoderLimit=c.MAX_RECV_MLINE_NUM+1}}},114:function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.default=class{constructor(){this.status="pending",this.promise=new Promise((e,t)=>{this.reject=e=>(this.status="rejected",t(e)),this.resolve=t=>(this.status="fullfilled",e(t))}),this.then=this.promise.then,this.catch=this.promise.catch}}},121:function(e,t,i){"use strict";i.r(t);var a=i(108),s=i(101),n=i(99);class r{static splitSections(e){return e.split("\r\nm=").map((e,t)=>t>0?"m="+e:e)}static splitLines(e){return e.split("\r\n")}static parseVersionLine(e){return parseInt(e.substring(2),10)}static writeVersionLine(e){return"v=".concat(e)}static parseOriginLine(e){const[t,i,a,s,n,r]=e.substring(2).split(" ");return{userName:t,sessionId:i,sessionVersion:parseInt(a,10),netType:s,addressType:n,address:r}}static writeOriginLine(e){const{userName:t,sessionId:i,sessionVersion:a,netType:s,addressType:n,address:r}=e;return"o=".concat(t," ").concat(i," ").concat(a," ").concat(s," ").concat(n," ").concat(r)}static parseSessionNameLine(e){return e.substring(2)}static writeSessionNameLine(e){return"s=".concat(e)}static parseInformationLine(e){return e.substring(2)}static writeInformationLine(e){return"i=".concat(e)}static parseConnectionLine(e){const[t,i,a]=e.substring(2).split(" ");return{netType:t,addressType:i,address:a}}static writeConnectionLine(e){const{netType:t,addressType:i,address:a}=e;return"c=".concat(t," ").concat(i," ").concat(a)}static parseBandwidthLine(e){return parseInt(e.substring(7),10)}static writeBandwidthLine(e){return"b=TIAS:".concat(e)}static parseTimingLine(e){const[t,i]=e.substring(2).split(" ");return{startTime:parseInt(t,10),stopTime:parseInt(i,10)}}static writeTimingLine(e){const{startTime:t,stopTime:i}=e;return"t=".concat(t," ").concat(i)}static parseRtpMapLine(e){const t=e.substring(9).match(/^(\d+) (.*)/),i=t[2].split("/");return{payloadType:parseInt(t[1],10),codecName:i[0],clockRate:parseInt(i[1],10),channels:i.length>=3?parseInt(i[2],10):null}}static writeRtpMapLine(e){const{payloadType:t,codecName:i,clockRate:a,channels:s}=e;let n="a=rtpmap:".concat(t," ").concat(i,"/").concat(a);return null!=s&&(n+="/"+s),n}static parseFmtpLine(e){const t=e.substring(7).match(/^(\d+) (.*)/),i={payloadType:parseInt(t[1],10)};return t[2].includes("=")?i.params=new Map(t[2].split(";").map(e=>e.trim().split("="))):i.plain=t[2],i}static writeFmtpLine(e){const{payloadType:t,params:i,plain:a}=e;let s="a=fmtp:".concat(t," ");return i?(i.forEach((e,t)=>{null!=e&&(s+="".concat(t,"=").concat(e,";"))}),s=s.slice(0,-1)):s+=a,s}static parseRtcpFbLine(e){const t=e.substring(10).match(/^(\d+) (.*)/);return{payloadType:parseInt(t[1],10),params:t[2].split(" ")}}static writeRtcpFbLine(e){const{payloadType:t,params:i}=e;let a="a=rtcp-fb:".concat(t);return i.forEach(e=>{a+=" "+e}),a}static parseRidLine(e){const t=e.substring(6).match(/^(\S+) (send|recv)/);return{rid:t[1],direction:t[2]}}static writeRidLine(e){const{rid:t,direction:i}=e;return"a=rid:".concat(t," ").concat(i)}static parseSimulcastLine(e){const t=e.substring(12).match(/^(send|recv) (.*)/);return{direction:t[1],rids:t[2].split(";").map(e=>"~"===e[0]?{id:e.substring(1),paused:!0}:{id:e,paused:!1})}}static writeSimulcastLine(e){const{direction:t,rids:i}=e;let a="a=simulcast:".concat(t," ");return i.forEach(e=>{const t=e.paused?"~"+e.id:e.id;a+=t+";"}),a.slice(0,-1)}static parseExtensionMapLine(e){const t=e.substring(9).match(/^(\d+)(\/sendrecv|\/sendonly|\/recvonly|\/inactive)? (\S+)(\s\S+)?/);return{id:parseInt(t[1],10),direction:t[2]?t[2].substring(1):null,uri:t[3],attributes:t[4]?t[4].trimStart():null}}static writeExtensionMapLine(e){const{id:t,direction:i,uri:a,attributes:s}=e;let n="a=extmap:".concat(t);return null!=i&&(n+="/"+i),n+=" "+a,null!=s&&(n+=" "+s),n}static parseMidLine(e){return e.substring(6)}static writeMidLine(e){return"a=mid:".concat(e)}static writeDirectionLine(e){return"a=".concat(e)}static parseMsidLine(e){const[t,i]=e.substring(7).split(" ");return{streamId:t,trackId:i}}static writeMsidLine(e){const{streamId:t,trackId:i}=e;return"a=msid:".concat(t," ").concat(i)}static parseSsrcLine(e){const t=e.indexOf(" ");return{ssrc:parseInt(e.substring(7,t),10),attribute:e.substring(t+1)}}static writeSsrcLine(e){const{ssrc:t,attribute:i}=e;return"a=ssrc:".concat(t," ").concat(i)}static parseSsrcGroupLine(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t}}static writeSsrcGroupLine(e){const{semantics:t,ssrcs:i}=e;let a="a=ssrc-group:".concat(t);return i.forEach(e=>{a+=" "+e}),a}static parseGroupLine(e){const t=e.indexOf(" ");return{semantics:e.substring(8,t),ids:e.substring(t+1).split(" ")}}static writeGroupLine(e){const{semantics:t,ids:i}=e;let a="a=group:".concat(t);return i.forEach(e=>{a+=" "+e}),a}static writeExtMapAllowMixedLine(){return"a=extmap-allow-mixed"}static writeRtcpMuxLine(){return"a=rtcp-mux"}static writeRtcpReducedSizeLine(){return"a=rtcp-rsize"}static parseCandidateLine(e){const t=e.substring(12).split(" "),i={foundation:t[0],componentId:parseInt(t[1],10),transport:t[2],priority:parseInt(t[3],10),address:t[4],port:parseInt(t[5],10),candType:t[6],type:t[7],relAddress:null,relPort:null,candExtensions:[]};return"raddr"===t[8]&&"rport"===t[10]?(i.relAddress=t[9],i.relPort=parseInt(t[11],10),i.candExtensions=t.slice(12)):i.candExtensions=t.slice(8),i}static writeCandidateLine(e){const{foundation:t,componentId:i,transport:a,priority:s,address:n,port:r,candType:o,type:c,relAddress:d,relPort:l,candExtensions:h}=e;let u="a=candidate:".concat(t," ").concat(i," ").concat(a," ").concat(s)+" ".concat(n," ").concat(r," ").concat(o," ").concat(c);return null!=d&&null!=l&&(u+=" raddr ".concat(d," rport ").concat(l)),h.length&&(u+=" "+h.join(" ")),u}static parseSessionSection(e){const t={version:0,origin:null,sessionName:null,information:null,connection:null,bandwidth:null,timing:null,groups:[],extMapAllowMixed:null,otherLines:[]},i=this.splitLines(e);for(let e=0;e<i.length;e++){const a=i[e];a.length&&(a.match(/^v=/)?t.version=this.parseVersionLine(a):a.match(/^o=/)?t.origin=this.parseOriginLine(a):a.match(/^s=/)?t.sessionName=this.parseSessionNameLine(a):a.match(/^i=/)?t.information=this.parseInformationLine(a):a.match(/^c=/)?t.connection=this.parseConnectionLine(a):a.match(/^b=TIAS:/)?t.bandwidth=this.parseBandwidthLine(a):a.match(/^t=/)?t.timing=this.parseTimingLine(a):a.match(/^a=group:/)?t.groups.push(this.parseGroupLine(a)):a.match(/^a=extmap-allow-mixed$/)?t.extMapAllowMixed=!0:t.otherLines.push(a))}return t}static writeSessionSection(e){const t=[];return t.push(this.writeVersionLine(e.version)),null!=e.origin&&t.push(this.writeOriginLine(e.origin)),null!=e.sessionName&&t.push(this.writeSessionNameLine(e.sessionName)),null!=e.information&&t.push(this.writeInformationLine(e.information)),null!=e.connection&&t.push(this.writeConnectionLine(e.connection)),null!=e.bandwidth&&t.push(this.writeBandwidthLine(e.bandwidth)),null!=e.timing&&t.push(this.writeTimingLine(e.timing)),e.groups.forEach(e=>{t.push(this.writeGroupLine(e))}),e.extMapAllowMixed&&t.push(this.writeExtMapAllowMixedLine()),e.otherLines.length&&t.push(...e.otherLines),t.join("\r\n")+"\r\n"}static parseMediaSection(e){const t={type:null,port:null,protocol:null,connection:null,bandwidth:null,mid:null,direction:null,msid:null,rtcpMux:null,rtcpReducedSize:null,codecs:[],extensionMap:new Map,rids:[],simulcast:null,ssrcs:[],ssrcGroups:[],candidates:[],otherLines:[]},i=[],a=[],s=this.splitLines(e),n=s[0].split(" ");t.type=n[0].substring(2),t.port=parseInt(n[1],10),t.protocol=n[2],t.payloadTypes=n.slice(3).map(e=>parseInt(e,10));for(let e=1;e<s.length;e++){let n;const r=s[e];if(r.length)if(r.match(/^c=/))t.connection=this.parseConnectionLine(r);else if(r.match(/^b=TIAS:/))t.bandwidth=this.parseBandwidthLine(r);else if(r.match(/^a=rtpmap:/)){const e=this.parseRtpMapLine(r);t.codecs.push({...e,codecParams:new Map,fmtpLines:[],rtcpFbParams:[]})}else if(r.match(/^a=fmtp:/))i.push(r);else if(r.match(/^a=rtcp-fb:/))a.push(r);else if(r.match(/^a=rid:/))t.rids.push(this.parseRidLine(r));else if(r.match(/^a=simulcast:/))t.simulcast=this.parseSimulcastLine(r);else if(r.match(/^a=ssrc:/))t.ssrcs.push(this.parseSsrcLine(r));else if(r.match(/^a=ssrc-group:/))t.ssrcGroups.push(this.parseSsrcGroupLine(r));else if(r.match(/^a=extmap:/)){const e=this.parseExtensionMapLine(r);t.extensionMap.set(e.id,e)}else r.match(/^a=mid:/)?t.mid=this.parseMidLine(r):(n=r.match(/^a=(sendrecv|sendonly|recvonly|inactive)/))?t.direction=n[1]:r.match(/^a=msid:/)?t.msid=this.parseMsidLine(r):r.match(/^a=rtcp-mux$/)?t.rtcpMux=!0:r.match(/^a=rtcp-rsize$/)?t.rtcpReducedSize=!0:r.match(/^a=candidate:/)?t.candidates.push(this.parseCandidateLine(r)):t.otherLines.push(r)}return i.forEach(e=>{const i=this.parseFmtpLine(e),a=t.codecs.find(e=>e.payloadType===i.payloadType);a&&(i.params?i.params.forEach((e,t)=>{"apt"===t&&(a.associatedPayloadType=parseInt(e,10)),a.codecParams.set(t,e)}):(a.fmtpLines.push(i.plain),"red"===a.codecName&&(a.associatedPayloadType=parseInt(i.plain.split("/")[0],10))))}),a.forEach(e=>{const i=this.parseRtcpFbLine(e),a=t.codecs.find(e=>e.payloadType===i.payloadType);a&&a.rtcpFbParams.push(i.params)}),t}static writeMediaSection(e){const t=[];let i="m=".concat(e.type," ").concat(e.port," ").concat(e.protocol);return e.payloadTypes.forEach(e=>{i+=" "+e}),t.push(i),e.connection&&t.push(this.writeConnectionLine(e.connection)),e.bandwidth&&t.push(this.writeBandwidthLine(e.bandwidth)),e.otherLines.length&&t.push(...e.otherLines),t.push(this.writeMidLine(e.mid)),e.extensionMap.size&&e.extensionMap.forEach((e,i)=>{t.push(this.writeExtensionMapLine(e))}),t.push(this.writeDirectionLine(e.direction)),e.msid&&t.push(this.writeMsidLine(e.msid)),e.rtcpMux&&t.push(this.writeRtcpMuxLine()),e.rtcpReducedSize&&t.push(this.writeRtcpReducedSizeLine()),e.codecs.forEach(e=>{const{payloadType:i,codecName:a,clockRate:s,channels:n,codecParams:r,fmtpLines:o,rtcpFbParams:c}=e;t.push(this.writeRtpMapLine({payloadType:i,codecName:a,clockRate:s,channels:n})),c.forEach(e=>{t.push(this.writeRtcpFbLine({payloadType:i,params:e}))}),r.size&&t.push(this.writeFmtpLine({payloadType:i,params:r})),o.forEach(e=>{t.push(this.writeFmtpLine({payloadType:i,plain:e}))})}),e.ssrcGroups.forEach(e=>{t.push(this.writeSsrcGroupLine(e))}),e.ssrcs.forEach(e=>{t.push(this.writeSsrcLine(e))}),e.rids.forEach(e=>{t.push(this.writeRidLine(e))}),e.candidates.forEach(e=>{t.push(this.writeCandidateLine(e))}),e.simulcast&&t.push(this.writeSimulcastLine(e.simulcast)),t.join("\r\n")+"\r\n"}static parse(e){const t={session:null,media:[],application:[]},i=this.splitSections(e);return t.session=this.parseSessionSection(i.shift()),i.forEach(e=>{const i=this.parseMediaSection(e);"audio"!==i.type&&"video"!==i.type||t.media.push(i),"application"===i.type&&t.application.push(i)}),t}static write(e){let t=this.writeSessionSection(e.session);return e.media.forEach(e=>{t+=this.writeMediaSection(e)}),e.application.forEach(e=>{t+=this.writeMediaSection(e)}),t}}var o=i(104);class c{static parseSdp(e){return r.parse(e)}static writeSdp(e){return r.write(e)}static generateSsrc(){return Math.floor(4294967294*Math.random())+1}static generateId(){return Math.random().toString(36).substring(2,12)}static generateSessionId(){return Math.random().toString().substring(2,22)}static generateUuid(){const e=Array.from(Array(256).keys()).map(e=>e.toString(16).padStart(2,"0")),t=crypto.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;return Array.from(t.entries()).map(t=>{let[i,a]=t;return[4,6,8,10].includes(i)?"-".concat(e[a]):e[a]}).join("")}static getSessionBoilerplate(){return"v=\r\no=- ".concat(this.generateSessionId()," 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n")}static getNtpSeconds(){return Math.floor((Date.now()+(Date.UTC(1970,0,1)-Date.UTC(1900,0,1)))/1e3)}static findHeaderExtensionByUri(e,t){for(const[i,a]of e.extensionMap)if(a.uri===t)return i;return-1}static addHeaderExtension(e,t){if(-1!==this.findHeaderExtensionByUri(e,t.uri))return!1;let i=0;e.extensionMap.forEach((e,t)=>{t>i&&(i=t)});const a=i+1;return e.extensionMap.set(a,{id:a,...t}),!0}static removeHeaderExtensionByUri(e,t){let i=!1;return e.extensionMap.forEach((e,a,s)=>{e.uri===t&&(s.delete(a),i=!0)}),i}static removeMidRidHeaderExtensions(e){e.extensionMap.forEach((e,t,i)=>{/^urn:ietf:params:rtp-hdrext:sdes:(?:mid|rtp-stream-id|repaired-rtp-stream-id)$/.test(e.uri)&&i.delete(t)})}static updateCodecParameters(e,t,i,a,s){e.media.filter(e=>e.type===t&&e.direction===i).forEach(e=>{e.codecs.filter(e=>e.codecName===a).forEach(e=>{s.forEach((t,i)=>{e.codecParams.set(i,t)})})})}static filterCodecs(e,t){e.media.forEach(e=>{const i=[];e.codecs.forEach(e=>{t.includes(e.codecName)&&i.push(e.payloadType)}),e.codecs.forEach(e=>{i.includes(e.associatedPayloadType)&&i.push(e.payloadType)}),e.payloadTypes=e.payloadTypes.filter(e=>i.includes(e)),e.codecs=e.codecs.filter(e=>i.includes(e.payloadType))}),e.media=e.media.filter(e=>e.payloadTypes.length)}static filterH264Profiles(e,t,i){e.media.filter(e=>e.direction===t).forEach(e=>{const t=[];e.codecs.filter(e=>"H264"===e.codecName).forEach(e=>{var a;const s=parseInt(null===(a=e.codecParams.get("profile-level-id"))||void 0===a?void 0:a.substring(0,2),16);i.includes(s)&&t.push(e.payloadType)}),e.codecs.forEach(e=>{t.includes(e.associatedPayloadType)&&t.push(e.payloadType)}),e.payloadTypes=e.payloadTypes.filter(e=>t.includes(e)),e.codecs=e.codecs.filter(e=>t.includes(e.payloadType))})}static getH264ProfileIds(e,t,i){const a=new Set,s=e.media.find(e=>"video"===e.type&&e.direction===t);return null==s||s.codecs.forEach(e=>{if("H264"===e.codecName&&(void 0===i||parseInt(e.codecParams.get("packetization-mode"))===i)){var t;const i=parseInt(null===(t=e.codecParams.get("profile-level-id"))||void 0===t?void 0:t.substring(0,2),16);i&&a.add(i)}}),Array.from(a.values())}static mungeEgressLocalOffer(e,t){c.filterCodecs(e,["H264"]);const i=e.media.find(e=>"video"===e.type&&"sendonly"===e.direction);if(!i)throw new Error("Failed to find a video media section for send");if(t>1){i.rids=[],i.simulcast=null,i.ssrcs=[],i.ssrcGroups=[];const e=i.codecs.some(e=>"rtx"===e.codecName),a=[],s=c.generateUuid(),n="- ".concat(c.generateUuid());for(let r=0;r<t;r++){const t=c.generateSsrc();if(a.push(t),i.ssrcs.push({ssrc:t,attribute:"cname:"+s}),i.ssrcs.push({ssrc:t,attribute:"msid:"+n}),e){const e=c.generateSsrc();i.ssrcs.push({ssrc:e,attribute:"cname:"+s}),i.ssrcs.push({ssrc:e,attribute:"msid:"+n}),i.ssrcGroups.push({semantics:"FID",ssrcs:[t,e]})}}i.ssrcGroups.push({semantics:"SIM",ssrcs:a})}c.removeMidRidHeaderExtensions(i),"iOS"===o.default.os&&15===o.default.getMajorOsVersion()&&1===o.default.getMinorOsVersion()||c.removeHeaderExtensionByUri(i,"urn:3gpp:video-orientation"),c.addHeaderExtension(i,{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time"}),t>1&&(e.session.extMapAllowMixed=!0,c.addHeaderExtension(i,{uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00"}))}static mungeEgressOfferToRemote(e){e.session.timing={startTime:c.getNtpSeconds(),stopTime:0}}static mungeEgressAnswer(e,t){t&&c.updateCodecParameters(e,"video","recvonly","H264",t)}static mungeIngressLocalOffer(e,t){c.filterCodecs(e,["H264","flexfec-03"]),t&&c.updateCodecParameters(e,"video","recvonly","H264",t)}}var d=i(105),l=i(14),h=i.n(l);class u{constructor(e){this._array=new Array(e),this._size=e,this._index=0,this._count=0}get size(){return this._size}get count(){return this._count}empty(){return 0===this._count}full(){return this._count===this._size}clear(){this._array=new Array(this._size),this._index=0,this._count=0}fill(e){return this._array.fill(e),this._index=0,this._count=this._size,this}get lastIndex(){return 0===this._index?this._size-1:this._index-1}nextIndex(e){return(e+1)%this._size}push(e){this._array[this._index]=e,this._index=this.nextIndex(this._index),this._count<this._size&&this._count++}pop(){if(this.empty())return;const e=this.lastIndex;return this._index=e,this._size>0&&this._size--,this._array[e]}at(e){if(!(this._count<this._size&&e>=this._count))return this._array[e]}front(){if(!this.empty())return this._array[this._count<this.size?0:this._index]}back(){if(!this.empty())return this._array[this.lastIndex]}unwrap(){return this._count<this._size?this._array.slice(0,this._count):[...this._array.slice(this._index),...this._array.slice(0,this._index)]}findIndex(e){if(this._count<this._size){for(let t=0;t<this._count;t++)if(e(this._array[t]))return t}else{for(let t=this._index;t<this._size;t++)if(e(this._array[t]))return t;for(let t=0;t<this._index;t++)if(e(this._array[t]))return t}return-1}findLastIndex(e){if(this._count<this._size){for(let t=this._count-1;t>=0;t--)if(e(this._array[t]))return t}else{for(let t=this._size-1;t>=this._index;t--)if(e(this._array[t]))return t;for(let t=this._index-1;t>=0;t--)if(e(this._array[t]))return t}return-1}find(e){const t=this.findIndex(e);return-1===t?void 0:this._array[t]}findLast(e){const t=this.findLastIndex(e);return-1===t?void 0:this._array[t]}}var m=i(100);s.default.getTracer("WmscStats");class S{constructor(){this.sendStatsMonitor=new g({cacheSize:S.sendStatsCacheSize}),this.recvStatsMonitor=new p({cacheSize:S.recvStatsCacheSize}),this.sendUsageStatsEnabled=!1,this.recvUsageStatsEnabled=!1,this.resourceUsageStatsReportTimestamp=0,this.resourceUsageStatsIntervalId=null,this.outgoingBitrateStatsCallback=null,this.resourceUsageStatsCallback=null}getSendStatsMonitor(){return this.sendStatsMonitor}getRecvStatsMonitor(){return this.recvStatsMonitor}setOptions(e){const{sendUsageStatsEnabled:t,recvUsageStatsEnabled:i}=e||{};void 0!==t&&(this.sendUsageStatsEnabled=t),void 0!==i&&(this.recvUsageStatsEnabled=i)}start(e){e&&this.setOptions(e),this.sendUsageStatsEnabled&&this.sendStatsMonitor.setOptions({outboundRtpStatsEnabled:!0}),this.sendStatsMonitor.start(),this.recvUsageStatsEnabled&&this.recvStatsMonitor.setOptions({inboundRtpStatsEnabled:!0}),this.recvStatsMonitor.start(),(this.sendUsageStatsEnabled||this.recvUsageStatsEnabled)&&(this.resourceUsageStatsIntervalId=setInterval(()=>{this._reportResourceUsageStats()},S.resourceUsageCheckInterval))}stop(){this.sendStatsMonitor.stop(),this.recvStatsMonitor.stop(),clearInterval(this.resourceUsageStatsIntervalId),this.resourceUsageStatsIntervalId=null}reset(){this.sendStatsMonitor.reset(),this.recvStatsMonitor.reset(),this.resourceUsageStatsReportTimestamp=0}registerOutgoingBitrateStatsCallback(e){this.sendStatsMonitor.outgoingBitrateStatsCallback=e}registerResourceUsageStatsCallback(e){this.resourceUsageStatsCallback=e}_reportResourceUsageStats(){const e={};let t=0;if(this.sendUsageStatsEnabled){const i=this._getSendResourceUsageStats();i&&(e.send={...i},t=Math.max(t,i.timestamp))}if(this.recvUsageStatsEnabled){const i=this._getRecvResourceUsageStats();i&&(e.recv={...i},t=Math.max(t,i.timestamp))}this.resourceUsageStatsReportTimestamp=t,this.resourceUsageStatsCallback(e)}_getSendResourceUsageStats(){if(!this.sendStatsMonitor.isStarted())return;const e=this.sendStatsMonitor.getOutboundRtpStats(),t=1e3/d.getVideoFormatByIndex(0).maxFramerate;let i=0,a=0,s=0,r=n.RESOURCE_USAGE_STATE.NONE;for(const[o,c]of e){const e=c.back(),o=Math.max(this.resourceUsageStatsReportTimestamp-500,e.timestamp-S.resourceUsageCheckInterval-500),d=c.find(e=>e.timestamp>o);if(!d)continue;const l=e.framesEncoded-d.framesEncoded,h=e.timestamp-d.timestamp;if(0===l||h<S.resourceUsageMinTimeSlice)continue;const u=e.framesSent-d.framesSent,g=l?1e3*(e.totalEncodeTime-d.totalEncodeTime)/l:0;let p,_,E=n.RESOURCE_USAGE_STATE.NONE,v=n.RESOURCE_USAGE_STATE.NONE,f=n.RESOURCE_USAGE_STATE.NONE;if(v=l>u||l>=S.encodeTimeMinFrameCount&&g>=t*S.encodeTimeFactorThresholdCritical?n.RESOURCE_USAGE_STATE.OVERUSING:l<=u&&l>=S.encodeTimeMinFrameCount&&g<t*S.encodeTimeFactorThresholdNormal?n.RESOURCE_USAGE_STATE.UNDERUSING:n.RESOURCE_USAGE_STATE.NORMAL,e.qualityLimitationDurations&&(p=1e3*(e.qualityLimitationDurations.cpu-d.qualityLimitationDurations.cpu)/h,_=1e3*(e.qualityLimitationDurations.other-d.qualityLimitationDurations.other)/h,f=p>=S.qualityLimitationRatioThresholdCritical||_>=S.qualityLimitationRatioThresholdCritical?n.RESOURCE_USAGE_STATE.OVERUSING:p<S.qualityLimitationRatioThresholdNormal&&_<S.qualityLimitationRatioThresholdNormal?n.RESOURCE_USAGE_STATE.UNDERUSING:n.RESOURCE_USAGE_STATE.NORMAL),E=v,m.compareResourceUsageState(f,E)>0&&(E=f),i+=l,a+=u,s=Math.max(s,e.timestamp),m.compareResourceUsageState(E,r)>0&&(r=E),r===n.RESOURCE_USAGE_STATE.OVERUSING)break}return{usageState:r,framesEncoded:i,framesSent:a,timestamp:s}}_getRecvResourceUsageStats(){if(!this.recvStatsMonitor.isStarted())return;const e=this.recvStatsMonitor.getInboundRtpStats();let t=0,i=0,a=0,s=0,r=n.RESOURCE_USAGE_STATE.NONE;for(const[o,c]of e){const e=c.back(),o=Math.max(this.resourceUsageStatsReportTimestamp-500,e.timestamp-S.resourceUsageCheckInterval-500),d=c.find(e=>e.timestamp>o);if(!d)continue;const l=e.timestamp-d.timestamp,h=e.framesReceived-d.framesReceived;if(0===h||l<S.resourceUsageMinTimeSlice)continue;const u=e.framesDropped-d.framesDropped,g=e.framesDecoded-d.framesDecoded,p=l/h,_=g?1e3*(e.totalDecodeTime-d.totalDecodeTime)/g:0;let E=n.RESOURCE_USAGE_STATE.NONE;if(t+=h,i+=u,a+=g,s=Math.max(s,e.timestamp),E=g>=S.decodeTimeMinFrameCount&&_>=p*S.decodeTimeFactorThresholdCritical?n.RESOURCE_USAGE_STATE.OVERUSING:g>=S.decodeTimeMinFrameCount&&_<p*S.decodeTimeFactorThresholdNormal?n.RESOURCE_USAGE_STATE.UNDERUSING:n.RESOURCE_USAGE_STATE.NORMAL,m.compareResourceUsageState(E,r)>0&&(r=E),r===n.RESOURCE_USAGE_STATE.OVERUSING)break}return{usageState:r,framesReceived:t,framesDropped:i,framesDecoded:a,timestamp:s}}}h()(S,"sendStatsCacheSize",6),h()(S,"recvStatsCacheSize",6),h()(S,"resourceUsageMinTimeSlice",4500),h()(S,"resourceUsageCheckInterval",5e3),h()(S,"encodeTimeMinFrameCount",20),h()(S,"encodeTimeFactorThresholdNormal",.9),h()(S,"encodeTimeFactorThresholdCritical",1.1),h()(S,"qualityLimitationRatioThresholdNormal",.05),h()(S,"qualityLimitationRatioThresholdCritical",.95),h()(S,"decodeTimeMinFrameCount",20),h()(S,"decodeTimeFactorThresholdNormal",.9),h()(S,"decodeTimeFactorThresholdCritical",1.1);class g{constructor(e){this.cacheSize=e.cacheSize||10,this.started=!1,this.selectedCandidatePairId=null,this.roundTripTime=0,this.remoteCandidateId=null,this.networkProtocol=null,this.localCandidateId=null,this.candidateType=null,this.outboundRtpStatsEnabled=!1,this.outboundRtpStatsMap=new Map}reset(){this.resetCandidateStats(),this.resetOutboundRtpStats()}resetCandidateStats(){this.selectedCandidatePairId=null,this.roundTripTime=0,this.remoteCandidateId=null,this.networkProtocol=null}resetOutboundRtpStats(){this.outboundRtpStatsMap.clear()}setOptions(e){const{outboundRtpStatsEnabled:t}=e||{};void 0!==t&&(this.outboundRtpStatsEnabled=t)}start(e){e&&this.setOptions(e),this.started=!0}stop(){this.started=!1}isStarted(){return this.started}getNetworkProtocol(){return this.networkProtocol}getCurrentRoundTripTime(){return this.roundTripTime}getOutboundRtpStats(){return this.outboundRtpStatsMap}onStatsReport(e){if(this.started)switch(e.type){case"transport":this.onTransportStats(e);break;case"candidate-pair":this.onCandidatePairStats(e);break;case"remote-candidate":this.onRemoteCandidateStats(e);break;case"outbound-rtp":this.onOutboundRtpStats(e);break;case"local-candidate":this.onLocalCandidateStats(e)}}onTransportStats(e){const{selectedCandidatePairId:t,dtlsState:i}=e;"connected"===i&&(this.selectedCandidatePairId=t)}onCandidatePairStats(e){const{id:t,state:i,nominated:a,availableOutgoingBitrate:s,currentRoundTripTime:n,remoteCandidateId:r,timestamp:o,localCandidateId:c}=e;t===this.selectedCandidatePairId&&"succeeded"===i&&a&&(this.roundTripTime=n,this.remoteCandidateId=r,this.localCandidateId=c,s&&this.outgoingBitrateStatsCallback({availableOutgoingBitrate:s,timestamp:o}))}onRemoteCandidateStats(e){const{id:t,protocol:i,port:a}=e;if(t===this.remoteCandidateId&&!this.networkProtocol){this.networkProtocol=i;const e="WMSC_Network_Change: send|".concat(i,"|").concat(a);s.default.globalTrace({logLevel:"log",log:e,tags:["WMSC_Network_Change"]}),s.default.monitorLog(e)}}onLocalCandidateStats(e){const{id:t,candidateType:i}=e;if(t==this.localCandidateId&&this.candidateType!=i){this.candidateType=i;const e="WMSC_LocalCandidatae_Change:send|".concat(i);s.default.globalTrace({logLevel:"directReport",log:e,tags:["WMSC_LocalCandidatae_Change"]}),s.default.monitorLog(e)}}onOutboundRtpStats(e){if(!this.outboundRtpStatsEnabled)return;const{ssrc:t,framesEncoded:i,framesSent:a,totalEncodeTime:s,qualityLimitationDurations:n,timestamp:r}=e;let o=this.outboundRtpStatsMap.get(t);o||(o=new u(this.cacheSize),this.outboundRtpStatsMap.set(t,o)),o.push({framesEncoded:i,framesSent:a,totalEncodeTime:s,qualityLimitationDurations:n,timestamp:r})}}class p{constructor(e){this.cacheSize=e.cacheSize||10,this.started=!1,this.selectedCandidatePairId=null,this.roundTripTime=0,this.remoteCandidateId=null,this.networkProtocol=null,this.localCandidateId=null,this.candidateType=null,this.inboundRtpStatsEnabled=!1,this.inboundRtpStatsMap=new Map}reset(){this.resetCandidateStats(),this.resetInboundRtpStats()}resetCandidateStats(){this.selectedCandidatePairId=null,this.roundTripTime=0,this.remoteCandidateId=null,this.networkProtocol=null}resetInboundRtpStats(){this.inboundRtpStatsMap.clear()}setOptions(e){const{inboundRtpStatsEnabled:t}=e||{};void 0!==t&&(this.inboundRtpStatsEnabled=t)}start(e){e&&this.setOptions(e),this.started=!0}stop(){this.started=!1}isStarted(){return this.started}getNetworkProtocol(){return this.networkProtocol}getCurrentRoundTripTime(){return this.roundTripTime}getInboundRtpStats(){return this.inboundRtpStatsMap}onStatsReport(e){if(this.started)switch(e.type){case"transport":this.onTransportStats(e);break;case"candidate-pair":this.onCandidatePairStats(e);break;case"remote-candidate":this.onRemoteCandidateStats(e);break;case"inbound-rtp":this.onInboundRtpStats(e);break;case"local-candidate":this.onLocalCandidateStats(e)}}onTransportStats(e){const{selectedCandidatePairId:t,dtlsState:i}=e;"connected"===i&&(this.selectedCandidatePairId=t)}onCandidatePairStats(e){const{id:t,state:i,nominated:a,currentRoundTripTime:s,remoteCandidateId:n,localCandidateId:r}=e;t===this.selectedCandidatePairId&&"succeeded"===i&&a&&(this.roundTripTime=s,this.remoteCandidateId=n,this.localCandidateId=r)}onRemoteCandidateStats(e){const{id:t,protocol:i,port:a}=e;if(t===this.remoteCandidateId&&!this.networkProtocol){this.networkProtocol=i;const e="WMSC_Network_Change: recv|".concat(i,"|").concat(a);s.default.globalTrace({logLevel:"log",log:e,tags:["WMSC_Network_Change"]}),s.default.monitorLog(e)}}onLocalCandidateStats(e){const{id:t,candidateType:i}=e;if(t==this.localCandidateId&&this.candidateType!=i){this.localCandidateId=t,this.candidateType=i;const e="WMSC_LocalCandidatae_Change:recv|".concat(i);s.default.globalTrace({logLevel:"directReport",log:e,tags:["WMSC_LocalCandidatae_Change"]}),s.default.monitorLog(e)}}onInboundRtpStats(e){if(!this.inboundRtpStatsEnabled)return;const{ssrc:t,framesDecoded:i,framesDropped:a,framesReceived:s,keyFramesDecoded:n,totalDecodeTime:r,pliCount:o,timestamp:c}=e;let d=this.inboundRtpStatsMap.get(t);d||(d=new u(this.cacheSize),this.inboundRtpStatsMap.set(t,d)),d.push({framesDecoded:i,framesDropped:a,framesReceived:s,keyFramesDecoded:n,totalDecodeTime:r,pliCount:o,timestamp:c})}}var _=new S;class E{static mean(e){if(e.length)return e.reduce((e,t)=>e+t,0)/e.length}static median(e){if(!e.length)return;e.sort((e,t)=>e-t);const t=Math.floor(e.length/2);return e.length%2!=0?e[t]:(e[t-1]+e[t])/2}static variance(e){if(!e.length)return;const t=e.reduce((e,t)=>e+t,0)/e.length,i=e.map(e=>Math.pow(e-t,2));return i.reduce((e,t)=>e+t,0)/i.length}static expMovingAverage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.5;if(!e.length)return[];const i=[e[0]];for(let a=1;a<e.length;a++)i.push(t*e[a]+(1-t)*i[a-1]);return i}static bestFitSlope(e){if(e.length<2)return;const t=e.length;let i=0,a=0,s=0,n=0;for(let r=0;r<t;r++)i+=r,a+=e[r],s+=r*e[r],n+=r*r;return(t*s-i*a)/(t*n-i*i)}}const v=s.default.getTracer("WmscQosMgr"),f=e=>{v.log(e),s.default.monitorLog("".concat(e))},I=Object.freeze({Hold:0,Increase:1,Decrease:2}),T=Object.freeze({None:0,Increase:1,Decrease:2}),C=Object.freeze({User:0,OutgoingBandwidth:1,ReceiverBandwidth:2,Other:3});class R{constructor(){this.outgoingBandwidthAdaptationEnabled=!0,this.receiverBandwidthAdaptationEnabled=!0,this.outgoingBandwidthProbingEnabled=!1,this.lossDetectionEnabled=!0,this.performanceAdaptationEnabled=!0,this.sendActive=!1,this.requestedLayerIds=[],this.additionalSubLayerIds=[],this.layersAllocation=[],this.layersAllocationCache=null,this.layersAllocationUpdateTimeoutId=null,this.isUpdatingLayers=!1,this.maxSubVideoSize=-1,this.maxFeasibleSendSize=4,this.sendUsageAdjustments=new u(R.resourceUsageAdjustmentHistorySize),this.sendUsageIncreaseFailedAttempts=0,this.sendUsageIncreaseFailedTime=0,this.encoderRestartedTime=0,this.maxFeasibleRecvSize=n.MIN_DEGRADATION_VIDEO_SIZE_RECV,this.recvUsageAdjustments=new u(R.resourceUsageAdjustmentHistorySize),this.recvUsageIncreaseFailedAttempts=0,this.recvUsageIncreaseFailedTime=0,this.outgoingBitrateStats=new u(R.outgoingBitrateStatsCacheSize),this.minOutgoingBitrate=8e4,this.outgoingBandwidth=5e5,this.outgoingBandwidthInProbing=!1,this.outgoingBandwidthProbedTime=0,this.outgoingBandwidthProbingTimeoutId=null,this.receiverBandwidth=1/0,this.receiverBandwidthReport=null,this.receiverL3BandwidthEvaluation=null,this.receiverBandwidthUpdatePending=!1,this.receiverBandwidthUpdateTimeoutId=null,this.isDualCall=!0,this.receiverStats=new u(R.receiverStatsCacheSize),this.minOutgoingBitrateAdjustments=new u(R.minOutgoingBitrateAdjustmentHistorySize),this.receiverReport=null,this.residualLossDetectedTimestamp=0,this.inherentLossDetectedTimestamp=0,this.minOutgoingBitrateUpdatedTime=0,this.messageCallback=null,this.maxRecvVideoSizeUpdateCallback=null,this.sendUsageStateUpdateCallback=null,_.registerOutgoingBitrateStatsCallback(this.onOutgoingBandwidthStats.bind(this)),_.registerResourceUsageStatsCallback(this.onResourceUsageStats.bind(this))}static areLayersAllocationsEqual(e,t){return e.length===t.length&&e.every((e,i)=>{const a=t[i];return e.layerId===a.layerId&&e.bitrate===a.bitrate&&e.formatIdx===a.formatIdx})}static getTotalAllocatedBitrate(e){return e.reduce((e,t)=>e+t.bitrate,0)}static isBitrateChangeAboveRatio(e,t,i){return!e||Math.abs(t-e)/e>i}resetSendStats(){_.getSendStatsMonitor().reset()}resetRecvStats(){_.getRecvStatsMonitor().reset()}_resetLayersAllocation(){this.requestedLayerIds=[],this.additionalSubLayerIds=[],this.layersAllocation=[],this.layersAllocationCache=null,this.isUpdatingLayers=!1}_resetLossDetection(){this.receiverStats.clear(),this.minOutgoingBitrateAdjustments.clear(),this.receiverReport=null,this.residualLossDetectedTimestamp=0,this.inherentLossDetectedTimestamp=0,this.minOutgoingBitrateUpdatedTime=0}_resetBandwidthState(){this._stopBandwidthProbingWait(),this._stopReceiverBandwidthUpdateWait(),this.outgoingBandwidthProbedTime=0,this.outgoingBitrateStats.clear(),this.minOutgoingBitrate=8e4,this.outgoingBandwidth=5e5,this.receiverBandwidth=1/0,this.receiverBandwidthReport=null,this.receiverL3BandwidthEvaluation=null,this.isDualCall=!0}_resetResourceUsageState(){this.maxFeasibleSendSize=d.getMaxEnabledLayerId(),this.sendUsageAdjustments.clear(),this.sendUsageIncreaseFailedAttempts=0,this.sendUsageIncreaseFailedTime=0,this.maxFeasibleRecvSize=n.MIN_DEGRADATION_VIDEO_SIZE_RECV,this.recvUsageAdjustments.clear(),this.recvUsageIncreaseFailedAttempts=0,this.recvUsageIncreaseFailedTime=0}resetSend(){this._stopBandwidthProbingWait(),this._stopReceiverBandwidthUpdateWait(),this._stopPollingLayersAllocation(),this.sendActive=!1,this._resetLayersAllocation(),this._resetLossDetection(),this._resetBandwidthState(),this.resetSendStats()}resetRecv(){this.maxSubVideoSize=-1,this.resetRecvStats()}registerMessageCallback(e){this.messageCallback=e}registerMaxRecvVideoSizeUpdateCallback(e){this.maxRecvVideoSizeUpdateCallback=e}registerSendUsageStateUpdateCallback(e){this.sendUsageStateUpdateCallback=e}setOptions(e){const{outgoingBandwidthAdaptationEnabled:t,receiverBandwidthAdaptationEnabled:i,lossDetectionEnabled:a,performanceAdaptationEnabled:s}=e||{};void 0!==t&&(this.outgoingBandwidthAdaptationEnabled=t),void 0!==i&&(this.receiverBandwidthAdaptationEnabled=i),void 0!==a&&(this.lossDetectionEnabled=a),void 0!==s&&(this.performanceAdaptationEnabled=s)}start(e){e&&this.setOptions(e);const t={};this.performanceAdaptationEnabled&&(t.sendUsageStatsEnabled=!0,t.recvUsageStatsEnabled=!0),_.start(t)}stop(){_.stop(),this.resetSend(),this.resetRecv()}updateLayers(e){v.log("updateLayers, ".concat(e)),this.requestedLayerIds=[...e],this.allocateBitrate(this._getAvailableBitrate(),C.User,this._maybeUpdateSubLayers()),this._setSendState(!!e.length)}_setSendState(e){this.sendActive!==e&&(this.sendActive=e,e?this._startPollingLayersAllocation():this.lossDetectionEnabled&&this._resetLossDetection())}async _startPollingLayersAllocation(){await this._sendLastLayersAllocation(),this.sendActive&&(this.layersAllocationUpdateTimeoutId=setTimeout(()=>{this._startPollingLayersAllocation()},R.layersAllocationUpdateInterval))}_stopPollingLayersAllocation(){clearTimeout(this.layersAllocationUpdateTimeoutId),this.layersAllocationUpdateTimeoutId=null}updateMaxSubVideoSize(e){this.maxSubVideoSize=e}getMaxFeasibleRecvVideoSize(){return this.maxFeasibleRecvSize}_waitBeforeReceiverBandwidthUpdate(){this.receiverBandwidthUpdatePending=!0,clearTimeout(this.receiverBandwidthUpdateTimeoutId),this.receiverBandwidthUpdateTimeoutId=setTimeout(()=>{this.receiverBandwidthUpdatePending=!1},R.receiverBandwidthUpdateDelay)}_stopReceiverBandwidthUpdateWait(){clearTimeout(this.receiverBandwidthUpdateTimeoutId),this.receiverBandwidthUpdateTimeoutId=null,this.receiverBandwidthUpdatePending=!1}_waitForBandwidthProbing(){this.outgoingBandwidthInProbing=!0,clearTimeout(this.outgoingBandwidthProbingTimeoutId),this.outgoingBandwidthProbingTimeoutId=setTimeout(()=>{this.outgoingBandwidthInProbing=!1},R.outgoingBandwidthProbingDelay)}_stopBandwidthProbingWait(){clearTimeout(this.outgoingBandwidthProbingTimeoutId),this.outgoingBandwidthProbingTimeoutId=null,this.outgoingBandwidthInProbing=!1}getMinBandwidth(){return 8e4}onOutgoingBandwidthStats(e){if(!this.outgoingBandwidthAdaptationEnabled||!this.sendActive)return;const{availableOutgoingBitrate:t,timestamp:i}=e;if(this.outgoingBandwidthInProbing){var a;const e=(null===(a=this.outgoingBitrateStats.back())||void 0===a?void 0:a.availableBitrate)||0;if(t>e)return;t<e&&this._stopBandwidthProbingWait()}this.outgoingBitrateStats.push({availableOutgoingBitrate:t,timestamp:i}),this._onOutgoingBandwidth(t)}onResourceUsageStats(e){this.performanceAdaptationEnabled&&(e.send&&this.sendActive&&this._handleSendUsageStats(e.send),e.recv&&this._handleRecvUsageStats(e.recv))}_handleSendUsageStats(e){const{framesEncoded:t,usageState:i,timestamp:s}=e,r=this._getFeasibleSendLayerIds();this.sendUsageStateUpdateCallback&&this.sendUsageStateUpdateCallback(i);let o=T.None;i===n.RESOURCE_USAGE_STATE.OVERUSING?o=a.wmscConfig.isMacIntel?T.None:T.Decrease:i===n.RESOURCE_USAGE_STATE.UNDERUSING&&(o=T.Increase);const c=r[r.length-1];this._maybeAdjustMaxSendSize(c,o)&&(f("WMSC_VEnc_Cap_Change: ".concat(this.maxFeasibleSendSize)),this.allocateBitrate(this._getAvailableBitrate(),C.Other))}_handleRecvUsageStats(e){const{usageState:t}=e;let i=T.None;t===n.RESOURCE_USAGE_STATE.OVERUSING?i=T.Decrease:t===n.RESOURCE_USAGE_STATE.UNDERUSING&&(i=T.Increase),this._maybeAdjustMaxRecvSize(this.maxSubVideoSize,i)&&(f("WMSC_VDec_Cap_Change: ".concat(this.maxFeasibleRecvSize)),this.maxRecvVideoSizeUpdateCallback&&this.maxRecvVideoSizeUpdateCallback(this.maxFeasibleRecvSize))}_maybeAdjustMaxSendSize(e,t){const i=Date.now();if(t===T.Decrease){const s=d.getMinEnabledLayerId();if(this.maxFeasibleSendSize>s){var a;const n=this.sendUsageAdjustments.back();return this.sendUsageAdjustments.push({layerChange:t,time:i}),(null==n?void 0:n.layerChange)===T.Increase&&(this.sendUsageIncreaseFailedAttempts++,this.sendUsageIncreaseFailedTime=n.time,v.log("Attempt to increase layer failed ".concat(this.sendUsageIncreaseFailedAttempts," times"))),this.maxFeasibleSendSize=null!==(a=d.getEnabledLayerIds().findLast(t=>t<e))&&void 0!==a?a:s,!0}}else if(t===T.Increase){const a=d.getMaxEnabledLayerId();var s;if(this.maxFeasibleSendSize<a&&this.sendUsageIncreaseFailedAttempts<R.resourceUsageIncreaseMaxAttempts&&i-this.sendUsageIncreaseFailedTime>=R.resourceUsageIncreaseInitialDelay*Math.pow(2,this.sendUsageIncreaseFailedAttempts-1))return this.sendUsageAdjustments.push({layerChange:t,time:i}),this.maxFeasibleSendSize=null!==(s=d.getEnabledLayerIds().find(t=>t>e))&&void 0!==s?s:a,!0}return!1}_maybeAdjustMaxRecvSize(e,t){if(e<=n.MIN_DEGRADATION_VIDEO_SIZE_RECV)return!1;const i=Date.now();if(t===T.Decrease){const e=this.recvUsageAdjustments.back();if(this.recvUsageAdjustments.push({layerChange:t,time:i}),(null==e?void 0:e.layerChange)===T.Increase&&(this.recvUsageIncreaseFailedAttempts++,this.recvUsageIncreaseFailedTime=e.time,v.log("Attempt to increase receive size failed ".concat(this.recvUsageIncreaseFailedAttempts," times"))),this.maxFeasibleRecvSize>n.MIN_DEGRADATION_VIDEO_SIZE_RECV)return this.maxFeasibleRecvSize--,!0}else if(t===T.Increase&&this.maxFeasibleRecvSize<e&&this.recvUsageIncreaseFailedAttempts<R.resourceUsageIncreaseMaxAttempts&&i-this.recvUsageIncreaseFailedTime>=R.resourceUsageIncreaseInitialDelay*Math.pow(2,this.recvUsageIncreaseFailedAttempts-1))return this.recvUsageAdjustments.push({layerChange:t,time:i}),this.maxFeasibleRecvSize++,!0;return!1}onSubInfo(e){const{isDualCall:t}=e;this.onDualCallState(t)}onDualCallState(e){this.isDualCall!==e&&(this.isDualCall=e,f("WMSC_Dual_Call_State_Changed: ".concat(e)),e?this._waitBeforeReceiverBandwidthUpdate():this._stopReceiverBandwidthUpdateWait())}_calcReceiverBandwidth(e,t){return e?t?Math.min(e.minBw,e.toMmrBw):e.toMmrBw:0}_evaluateBandwidthDistribution(e,t,i){const a=i.reduce((e,t)=>e+t,0),s=d.getMinBitrate(e),n=d.getTargetBitrate(e)*R.adequateQualityBitrateRatio;let r=0,o=0,c=0;if(t>=n)o=a,c=t;else if(a>0){let e=0,d=0,l=0,h=0,u=0,m=0,S=0;for(let r=i.length-1;r>=0;r--){const o=i[r];o&&(S=S?512*r:t,S>=s&&(e=r,d+=o),S>=n&&(l=r,h+=o),m||(u/a<.6?u+=o:m=r))}m<l&&(u-h)/a<.2?(r=l,o=h):m>e?(r=m,o=u):(r=e,o=d),c=o?Math.max(t,512*r):0}else c=n;return{minBandwidth:t,samples:a,selectedBandwidth:c,selectedSamples:o,excludedDist:o<a?i.slice(0,r):[]}}onReceiverBandwidthReport(e){if(!this.receiverBandwidthAdaptationEnabled||this.receiverBandwidthUpdatePending)return;let t=!1;const{minBW:i,minL3BW:a,toMmrBW:s,l3BWDist:n}=e;if(!this.isDualCall&&d.isLayerEnabled(3)){const e=this._getMinL3Bandwidth(),i=this._getSelectedL3Bandwidth();this.receiverL3BandwidthEvaluation=this._evaluateBandwidthDistribution(3,a,[]),this.receiverL3BandwidthEvaluation.minBandwidth===e&&this.receiverL3BandwidthEvaluation.selectedBandwidth===i||(t=!0)}this.receiverBandwidthReport={toMmrBw:s,minBw:i,minL3Bw:a};const r=this._calcReceiverBandwidth(this.receiverBandwidthReport,this.isDualCall);r!==this.receiverBandwidth&&(this.receiverBandwidth=r,t=!0),this.sendActive&&t&&this.allocateBitrate(this._getAvailableBitrate(),C.ReceiverBandwidth,this._maybeUpdateSubLayers())}onReceiverReport(e){if(!this.outgoingBandwidthAdaptationEnabled||!this.lossDetectionEnabled||!this.sendActive)return;if(!this.receiverReport)return void(this.receiverReport=e);const{recvPkts:t,preMissingPkts:i,postMissingPkts:a,maxJitterMs:s,maxSeqGap:n,timestampMs:r}=e,o=this.receiverReport,c=t-o.recvPkts,d=i-o.preMissingPkts,l=a-o.postMissingPkts,h=d+c,u={loss:h>0?d/h:0,residualLoss:h>0?l/h:0,jitter:s,sequenceGap:n,timestamp:r};this.receiverStats.push(u),this.receiverReport=e,"udp"===_.getSendStatsMonitor().getNetworkProtocol()&&this._updateOutgoingBandwidth(this._adjustOutgoingBandwidthForLoss(this.outgoingBandwidth))}_getAvailableReceiverBandwidth(){return Math.floor(this.receiverBandwidth*R.receiverBandwidthUseRatio)}_getMinL3Bandwidth(){var e;return(null===(e=this.receiverL3BandwidthEvaluation)||void 0===e?void 0:e.minBandwidth)||0}_getSelectedL3Bandwidth(){var e;return(null===(e=this.receiverL3BandwidthEvaluation)||void 0===e?void 0:e.selectedBandwidth)||0}_getOutgoingBandwidthHistory(e){if(this.outgoingBitrateStats.empty())return[];const t=this.outgoingBitrateStats.unwrap(),i=t[t.length-1].timestamp-e;let a=0;for(let e=t.length-1;e>=0;e--){if(t[e].timestamp<i){a=e+1;break}}return t.slice(a).map(e=>e.availableOutgoingBitrate)}_getSubLayersForLayer(e){const t=d.getEnabledLayerIds(),i=[];if(3===e){if(!this.receiverL3BandwidthEvaluation)return i;const{minBandwidth:a,selectedBandwidth:s}=this.receiverL3BandwidthEvaluation;if(s>a)for(const a of t)a<e&&i.push(a);return i}if(e<3)for(const a of t)a<e&&i.push(a);return i}_maybeUpdateSubLayers(){if(!this.receiverBandwidthAdaptationEnabled)return!1;const e=[];return!this.isDualCall&&this.requestedLayerIds.length&&this.requestedLayerIds.forEach(t=>{this._getSubLayersForLayer(t).forEach(t=>{this.requestedLayerIds.includes(t)||e.includes(t)||e.push(t)})}),!m.compareArrays(this.additionalSubLayerIds,e)&&(this.additionalSubLayerIds=e,!0)}_getAvailableBitrate(){const e=this._getAvailableReceiverBandwidth(),t=e?Math.min(this.outgoingBandwidth,e):this.outgoingBandwidth;return Math.max(8e4,t)}_onOutgoingBandwidth(e){this._updateOutgoingBandwidth(e)}_updateOutgoingBandwidth(e){this.outgoingBandwidth!==e&&(this.outgoingBandwidth=e,this.allocateBitrate(this._getAvailableBitrate(),C.OutgoingBandwidth))}_detectInherentLoss(e){const t=e.findIndex(e=>e.timestamp>this.inherentLossDetectedTimestamp&&e.loss);if(e.length-t>=R.inherentLossDetectionMinDataPoints){const i=e.slice(t).map(e=>e.loss),a=i.length?E.mean(i):0;if(a>=R.lossThresholdLow&&a<R.lossThresholdHigh){const e=E.variance(i);if(v.log("loss ratios: ".concat(i,", mean: ").concat(a,", variance: ").concat(e)),e<R.inherentLossVarianceThresholdHigh)return t}}return-1}_detectOutOfOrder(e){const t=e.findIndex(e=>e.timestamp>this.inherentLossDetectedTimestamp&&e.sequenceGap);if(e.length-t>=R.outOfOrderDetectionMinDataPoints){const i=e.slice(t).map(e=>e.sequenceGap),a=E.mean(i);if(a>=R.sequenceGapThresholdLow&&a<R.sequenceGapThresholdHigh)return v.log("sequence gaps: ".concat(i,", mean: ").concat(a)),t}return-1}_isOutgoingBandwidthNormal(e){return e>=Math.max(R.minOutgoingBitrateThresholdLow,this.minOutgoingBitrate*R.outgoingBitrateFactorThresholdNormalState)}_adjustOutgoingBandwidthForLoss(e){e<this.minOutgoingBitrate&&(e=this.minOutgoingBitrate),this._isOutgoingBandwidthNormal(e)&&this.minOutgoingBitrateAdjustments.clear();const t=this.receiverStats.unwrap(),{residualLoss:i,timestamp:a}=t[t.length-1],s=t.findIndex(e=>e.loss),n=t.slice(s).map(e=>e.loss),r=n.length?E.mean(n):0;if(i&&v.log("residual loss: ".concat(i,", mean loss: ").concat(r)),i>=R.residualLossThresholdMedium){this.residualLossDetectedTimestamp=a;const t=i>=R.residualLossThresholdHigh?R.residualLossBitrateFastDecreaseFactor:R.residualLossBitrateDecreaseFactor;return this._decreaseOutgoingBitrate(Math.floor(e*t))}if(i>=r*R.residualLossRatioThresholdLow){const i=t.findIndex(e=>e.timestamp>this.residualLossDetectedTimestamp);if(t.reduce((e,t,s)=>s>=i&&t.residualLoss&&a-t.timestamp<=R.residualLossMonitorTimeWindow?e+1:e,0)>=R.residualLossCountThreshold)return this.residualLossDetectedTimestamp=a,this._decreaseOutgoingBitrate(Math.floor(e*R.residualLossBitrateDecreaseFactor))}if(this.residualLossDetectedTimestamp&&a-this.residualLossDetectedTimestamp<R.outgoingBitrateIncreaseSuppressionIntervalResidualLoss)return e;const o=this._getOutgoingBitrateDemand();if(e>=o)return e;let c=-1;if(c=this._detectInherentLoss(t),-1===c&&(c=this._detectOutOfOrder(t)),-1!==c&&a-this.inherentLossDetectedTimestamp>=R.inherentLossDetectionMinInterval){const i=this._getOutgoingBandwidthHistory(a-t[c].timestamp+1500);if(i.length>=R.inherentLossDetectionMinDataPoints){const t=E.bestFitSlope(i),s=i[0];if(t<R.outgoingBitrateMaxSlopeRestoreBandwidth&&s>=e*R.outgoingBitrateMinFactorRestoreBandwidth)return v.log("bandwidth: ".concat(s," -> ").concat(e,", slope: ").concat(t)),this._maybeIncreaseMinOutgoingBitrate(Math.min(o,s)),this.inherentLossDetectedTimestamp=a,e}if(e<R.minOutgoingBitrateThresholdMedium)return this._maybeIncreaseMinOutgoingBitrate(Math.min(R.minOutgoingBitrateThresholdMedium,o,Math.floor(e*R.minOutgoingBitrateIncreaseFactor))),this.inherentLossDetectedTimestamp=a,e}return e}_decreaseOutgoingBitrate(e){return e=Math.max(8e4,e),this._maybeDecreaseMinOutgoingBitrate(e),e}_maybeIncreaseMinOutgoingBitrate(e){return!(this.minOutgoingBitrateAdjustments.unwrap().slice(-3).filter(e=>e===I.Decrease).length>=2)&&(this.minOutgoingBitrateAdjustments.push(I.Increase),this._adjustMinOutgoingBitrate(Math.max(R.minOutgoingBitrateThresholdLow,Math.min(R.minOutgoingBitrateThresholdHigh,e))))}_maybeDecreaseMinOutgoingBitrate(e){if(e<this.minOutgoingBitrate){this.minOutgoingBitrateAdjustments.push(I.Decrease);const t=this.minOutgoingBitrate<=R.minOutgoingBitrateThresholdLow?8e4:Math.max(8e4,Math.min(e,Math.floor(this.minOutgoingBitrate*R.minOutgoingBitrateLeastDecreaseFactor)));return this._adjustMinOutgoingBitrate(t)}return!1}async _adjustMinOutgoingBitrate(e){v.log("adjust min bitrate: ".concat(this.minOutgoingBitrate," -> ").concat(e));const t=Date.now();if(t-this.minOutgoingBitrateUpdatedTime<R.minOutgoingBitrateUpdateMinInterval)return;const i=1e3*Math.floor(e/1e3);if(i!==this.minOutgoingBitrate){v.log("update min bitrate: ".concat(this.minOutgoingBitrate," -> ").concat(i)),this.minOutgoingBitrateUpdatedTime=t;try{return await this.messageCallback({type:n.QOS_EVENT.MIN_BITRATE_UPDATE,data:i}),this.minOutgoingBitrate=i,!0}catch(e){return v.error("update min bitrate error: ".concat(e.message)),!1}}return!1}async _updateLayersAllocation(e){try{return await this.messageCallback({type:n.QOS_EVENT.LAYERS_UPDATE,data:e}),!0}catch(e){return v.error("update layers allocation error: ".concat(e.message)),!1}}async _sendLastLayersAllocation(){if(!this.layersAllocationCache||this.isUpdatingLayers)return;const{outgoingBandwidth:e,receiverBandwidthInfo:t,layerIds:i,layersAllocation:a,isProbing:s}=this.layersAllocationCache;if(this.layersAllocationCache=null,!R.areLayersAllocationsEqual(this.layersAllocation,a)){this.isUpdatingLayers=!0;const n=R.getTotalAllocatedBitrate(a),{receiverBandwidth:r,toMmrBw:o,minBw:c,minL3Bw:d}=t,l="WMSC_Update_Layers_Allocation, bandwidth: "+"S ".concat(e,", R ").concat(r," (").concat(o,",").concat(c,",").concat(d,"), A ").concat(n)+", layers: ".concat(i,", ").concat(a.map(e=>{let{layerId:t,bitrate:i,formatIdx:a}=e;return"{".concat(t,",").concat(i,",").concat(a,"}")}).join(","));f(Object(m.replaceComma)(l));const h=await this._updateLayersAllocation(a);this.isUpdatingLayers=!1,h&&(this.layersAllocation=a,s&&this._waitForBandwidthProbing())}}_getAdjustedTargetBitrate(e){const t=d.getTargetBitrate(e);if(this.receiverBandwidthAdaptationEnabled&&!this.isDualCall&&3===e){const e=this._getSelectedL3Bandwidth();return Math.min(t,e)}return t}_getAdjustedMaxBitrate(e){const t=d.getMaxBitrate(e);if(this.receiverBandwidthAdaptationEnabled&&!this.isDualCall&&3===e){const e=this._getSelectedL3Bandwidth();return Math.min(t,e)}return t}_getSendLayerIds(){return[...this.additionalSubLayerIds,...this.requestedLayerIds].sort()}_getFeasibleSendLayerIds(){const e=this._getSendLayerIds(),t=[];for(const i of e){if(i>this.maxFeasibleSendSize){t[t.length-1]!==this.maxFeasibleSendSize&&t.push(this.maxFeasibleSendSize);break}t.push(i)}return t}_getTotalMaxBitrate(e){let t=0;for(let i=0;i<e.length;i++)i===e.length-1?t+=this._getAdjustedMaxBitrate(e[i]):t+=this._getAdjustedTargetBitrate(e[i]);return t}_getFormatTotalMaxBitrate(e){let t=0;for(let i=0;i<e.length;i++){const a=d.getVideoFormatByIndex(e[i]);t+=i===e.length-1?a.maxBitrate:a.targetBitrate}return t}_getOutgoingBitrateDemand(){const e=this._getFeasibleSendLayerIds();return Math.min(this._getTotalMaxBitrate(e),this._getAvailableReceiverBandwidth())}_shouldProbeBandwidth(e,t,i){if(i<=this._getAvailableReceiverBandwidth()&&i>e&&i>t&&this._isOutgoingBandwidthNormal(e)){const e=Math.min(R.outgoingBandwidthProbingTimeWindow,Date.now()-this.outgoingBandwidthProbedTime);if("udp"===_.getSendStatsMonitor().getNetworkProtocol()&&!this.receiverStats.empty()){const t=this.receiverStats.back().timestamp-e;if(this.receiverStats.find(e=>e.timestamp>=t&&e.loss))return!1}const t=this._getOutgoingBandwidthHistory(e);if(t.length>=R.outgoingBandwidthProbingMinDataPoints){const e=E.bestFitSlope(t);if(e>=R.outgoingBandwidthProbingMinSlope&&e<R.outgoingBandwidthProbingMaxSlope)return!0}}return!1}_allocateBitrateToLayers(e,t,i){const a=[];let s;for(const i of t){const t=this._getAdjustedTargetBitrate(i),n=d.getMinBitrate(i);if(!(e>=n&&t>=n)){const t=d.getEnabledLayerIds(),n=void 0===s?t[0]:s+1;for(let r=i-1;r>=n&&t.includes(r);r--){const t=this._getAdjustedTargetBitrate(r),i=d.getMinBitrate(r);if(e>=i&&t>=i){a.push({layerId:r,bitrate:i,remainingBitrateDemand:t-i}),e-=i,s=r;break}}break}a.push({layerId:i,bitrate:n,remainingBitrateDemand:t-n}),e-=n,s=i}if(a.length&&e>0){const t=a.reduce((e,t)=>{let{remainingBitrateDemand:i}=t;return e+i},0);for(const i of a){const{remainingBitrateDemand:a}=i,s=Math.min(a,Math.floor(e/t*a));e-=s,i.bitrate+=s}}if(a.length){const t=a[a.length-1],i=this._getAdjustedMaxBitrate(t.layerId);t.bitrate=Math.min(i,t.bitrate+e)}return e>0&&t.length&&!a.length&&a.push({layerId:d.getMinEnabledLayerId(),bitrate:d.getMinEncodingBitrate()}),a.map(e=>{let{layerId:t,bitrate:a}=e;const s=d.findVideoFormatIndex(t,a);return i&&(a=d.getVideoFormatByIndex(s).maxBitrate),{layerId:t,bitrate:a,formatIdx:s}})}_reallocateBitrateToLayers(e,t,i,a){const s=[];let n=0,r=0;if(i.forEach((e,t)=>{let{layerId:a,formatIdx:o}=e;const c=d.getVideoFormatByIndex(o),l=c.minBitrate,h=t===i.length-1?Math.min(this._getAdjustedMaxBitrate(a),c.maxBitrate):Math.min(this._getAdjustedTargetBitrate(a),c.targetBitrate);s.push({layerId:a,formatIdx:o,minBitrate:l,maxBitrate:h}),n+=l,r+=h}),e>=n&&e<=r){const t=r-n,i=(a?r:e)-n;return s.forEach(e=>{e.bitrate=e.minBitrate+Math.floor((e.maxBitrate-e.minBitrate)/t*i)}),s.map(e=>{let{layerId:t,bitrate:i,formatIdx:a}=e;return{layerId:t,bitrate:i,formatIdx:a}})}return this._allocateBitrateToLayers(e,t,a)}allocateBitrate(e,t){var i;let a=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const s=this._getFeasibleSendLayerIds(),n=(null===(i=this.layersAllocationCache)||void 0===i?void 0:i.layersAllocation)||this.layersAllocation;let r,o=!1;if(this.outgoingBandwidthProbingEnabled&&(t===C.OutgoingBandwidth||t===C.ReceiverBandwidth)){var c;if(null!==(c=this.layersAllocationCache)&&void 0!==c&&c.isProbing)return;const e=Date.now();if(e-this.outgoingBandwidthProbedTime>=R.outgoingBandwidthProbingMinInterval){const i=this._getTotalMaxBitrate(s),a=this.layersAllocation?R.getTotalAllocatedBitrate(this.layersAllocation):0;this._shouldProbeBandwidth(this.outgoingBandwidth,a,i)&&(v.log("probe bandwidth, demand: ".concat(i,", reason: ").concat(t)),o=!0,this.outgoingBandwidthProbedTime=e)}}if(r=a||!n.length||t!==C.OutgoingBandwidth&&t!==C.ReceiverBandwidth?this._allocateBitrateToLayers(e,s,o):this._reallocateBitrateToLayers(e,s,n,o),r){const{toMmrBw:e=0,minBw:i=0,minL3Bw:a=0}=this.receiverBandwidthReport||{};this.layersAllocationCache={outgoingBandwidth:this.outgoingBandwidth,receiverBandwidthInfo:{receiverBandwidth:this.receiverBandwidth,toMmrBw:e,minBw:i,minL3Bw:a},layerIds:s,layersAllocation:r,reason:t,isProbing:o}}}}h()(R,"availableBitrateChangeRatioThresholdLow",.08),h()(R,"availableBitrateUpdateMinInterval",1e3),h()(R,"layersAllocationUpdateInterval",300),h()(R,"resourceUsageAdjustmentHistorySize",6),h()(R,"resourceUsageIncreaseInitialDelay",6e4),h()(R,"resourceUsageIncreaseMaxAttempts",6),h()(R,"encodingTimeout",3e3),h()(R,"encoderRestartMinInterval",3e4),h()(R,"outgoingBitrateStatsCacheSize",8),h()(R,"receiverBandwidthUseRatio",.9),h()(R,"receiverBandwidthUpdateDelay",1500),h()(R,"adequateQualityBitrateRatio",.6),h()(R,"outgoingBandwidthProbingMinInterval",1e4),h()(R,"outgoingBandwidthProbingTimeWindow",4e3),h()(R,"outgoingBandwidthProbingMinDataPoints",3),h()(R,"outgoingBandwidthProbingMinSlope",1e3),h()(R,"outgoingBandwidthProbingMaxSlope",5e4),h()(R,"outgoingBandwidthProbingDelay",3500),h()(R,"lossThresholdLow",.08),h()(R,"lossThresholdHigh",.6),h()(R,"receiverStatsCacheSize",6),h()(R,"minOutgoingBitrateAdjustmentHistorySize",5),h()(R,"outgoingBitrateFactorThresholdNormalState",1.5),h()(R,"outgoingBitrateMaxSlopeRestoreBandwidth",-1e5),h()(R,"outgoingBitrateMinFactorRestoreBandwidth",1.5),h()(R,"outgoingBitrateIncreaseSuppressionIntervalResidualLoss",15e3),h()(R,"minOutgoingBitrateUpdateMinInterval",900),h()(R,"minOutgoingBitrateThresholdLow",25e4),h()(R,"minOutgoingBitrateThresholdMedium",1e6),h()(R,"minOutgoingBitrateThresholdHigh",2e6),h()(R,"minOutgoingBitrateLeastDecreaseFactor",.8),h()(R,"minOutgoingBitrateIncreaseFactor",1.15),h()(R,"residualLossRatioThresholdLow",.05),h()(R,"residualLossThresholdMedium",.05),h()(R,"residualLossThresholdHigh",.15),h()(R,"residualLossMonitorTimeWindow",6e3),h()(R,"residualLossCountThreshold",2),h()(R,"residualLossBitrateDecreaseFactor",.8),h()(R,"residualLossBitrateFastDecreaseFactor",.64),h()(R,"inherentLossDetectionMinDataPoints",3),h()(R,"inherentLossDetectionMinInterval",3e3),h()(R,"inherentLossVarianceThresholdHigh",.02),h()(R,"outOfOrderDetectionMinDataPoints",3),h()(R,"sequenceGapThresholdLow",10),h()(R,"sequenceGapThresholdHigh",80);var M=new R;const b=s.default.getTracer("WmscMediaMgr"),L=e=>{b.log(e),s.default.monitorLog("".concat(e))};var y=new class{constructor(){var e,t;(this.videoPublished=!1,this.mediaRequested=!1,this.hdVideoEnabled=!1,this.maxSendLayerId=4,this.sourceVideoSettings={},this.pcs=new Map,this.videoMid=null,this.sendTransceivers=new Map,this.recvTransceivers=new Map,this.messageCallback=null,this.requestedLayerIds=[],this.sendLayerIds=[],this.encodingMap=new Map,this.timeCostMap=new Map,this.recvCodecNum=0,this.senderCodec=null,this.recvPreferCodecs=(null===(e=RTCRtpReceiver.getCapabilities("video"))||void 0===e||null===(e=e.codecs)||void 0===e?void 0:e.filter(e=>{let{mimeType:t,sdpFmtpLine:i}=e;if(-1!==t.indexOf("red")||-1!==t.indexOf("fec")||"video/rtx"===t)return!0;const a=i?i.toLowerCase():"";return!("video/H264"!==t||!a||-1===a.indexOf("packetization-mode=1"))&&(this.recvCodecNum++,!0)}))||[],"Chrome"!==o.default.browser||o.default.isBrowserVersionGreaterEqualThan(124,0))||(null===(t=RTCRtpSender.getCapabilities("video"))||void 0===t||null===(t=t.codecs)||void 0===t||t.some(e=>{const{mimeType:t,sdpFmtpLine:i}=e;return"video/H264"===t&&-1!==i.indexOf("profile-level-id=42")&&(this.senderCodec=e,!0)}));L("WMSC_RCN-".concat(this.recvCodecNum)),M.registerMessageCallback(this.onQosMessage.bind(this))}getSendEncodings(e){switch(e){case 1:return[{active:!1}];case 2:return[{active:!1,scaleResolutionDownBy:2},{active:!1,scaleResolutionDownBy:1}];default:return[{active:!1,scaleResolutionDownBy:4},{active:!1,scaleResolutionDownBy:2},{active:!1,scaleResolutionDownBy:1}]}}getDefaultEncodingIndex(e){return e<=1?0:2===e?1:2}getEncodingIndex(e){return this.layerEncodingIndexMap.get(e)}_configSimulcastLayers(e,t){this.numSimulcastLayers=e,this.layerEncodingIndexMap=t}setDefaultVideoSettings(){const e="Safari"===o.default.browser&&"macOS"===o.default.os,t="Android"===o.default.os;d.setDefaultLayersSettings(e||t),d.setEnabledLayerIds([1,2,3]),this._configSimulcastLayers(3,new Map([[1,0],[2,1],[3,2]])),this.resendVideo()}setVideoSettings(e){const{layersSettings:t}=e||{};if(null==t||!t.length)return void this.setDefaultVideoSettings();const i=t.sort((e,t)=>Math.min(t.width,t.height)-Math.min(e.width,e.height)),a=i.reduce((e,t)=>Math.min(t.maxFramerate,e),30);for(let e=0;e<i.length;e++){const{width:t,height:s,minBitrate:n,maxBitrate:r}=i[e],o=d.getLayerIdByVideoFormat({width:t,height:s});i[e].layerId=o,i[e].maxFramerate=a,void 0===r&&(i[e].maxBitrate=d.getMaxBitrateByVideoFormat(o,{width:t,height:s}),i[e].targetBitrate=i[e].maxBitrate),void 0===n&&(i[e].minBitrate=e>0?i[e-1].maxBitrate:d.getMinEncodingBitrate())}const s=new Map;i.forEach(e=>{const{layerId:t}=e,i=this.getDefaultEncodingIndex(t);s.get(t)?t.push(t):s.set(i,[t])});const n=s.size,r=Array.from(s.keys()),o=new Map;for(let e=0;e<n;e++){s.get(r[e]).forEach(t=>{o.set(t,e)})}d.setLayersSettings(i),d.setEnabledLayerIds(Array.from(o.keys()).sort()),this._configSimulcastLayers(n,o),this.resendVideo()}registerMessageCallback(e){this.messageCallback=e}getPc(e){return this.pcs.get(e)}getIngressPc(){return this.pcs.get(n.PEER_ID.INGRESS)}getEgressPc(){return this.pcs.get(n.PEER_ID.EGRESS)}getSendTransceivers(){return this.sendTransceivers}getSender(e){var t;return null===(t=this.sendTransceivers.get(e))||void 0===t?void 0:t.sender}getRecvTransceivers(){return this.recvTransceivers}getReceiver(e){var t;return null===(t=this.recvTransceivers.get(e))||void 0===t?void 0:t.receiver}getRemoteSourceId(e){var t;const i=this.getReceiver(e).getContributingSources(),a=parseInt(null===(t=i[0])||void 0===t?void 0:t.source,10);return isNaN(a)?void 0:a}enableHdVideo(e){L("WMSC_Enable_HD_Video: ".concat(e)),this.hdVideoEnabled=e,this.resendVideo()}setMaxSendLayerId(e){this.maxSendLayerId=e,this.sendLayerIds=this._reduceRequestLayerIds(this.requestedLayerIds)}async publishVideoTrack(e,t){e?(this.sourceVideoSettings=t,await this._replaceVideoTrack(e)):await this._replaceVideoTrack(null),this._onVideoPublished(!!e)}async _replaceVideoTrack(e){const t=this.getSender(this.videoMid),i=e?"{ kind: ".concat(e.kind,", id: ").concat(e.id,", enabled: ").concat(e.enabled,", muted: ").concat(e.muted)+", contentHint: ".concat(e.contentHint," }"):"";if(L(Object(m.replaceComma)("WMSC_Replace_Video_Track: sender: ".concat(!!t," track: ").concat(i))),t)return t.replaceTrack(e)}_onVideoPublished(e){this.videoPublished=e,this.mediaRequested&&(e?this._onVideoStart():this._onVideoStop())}_onVideoStart(){b.log("_onVideoStart"),M.updateLayers(this.sendLayerIds)}_onVideoStop(){b.log("_onVideoStop"),M.updateLayers([])}_onEgressPcClose(){b.log("_onEgressPcClose"),this.sendTransceivers.clear(),this.videoPublished=!1}_onIngressPcClose(){b.log("_onIngressPcClose"),this.recvTransceivers.clear()}_reduceRequestLayerIds(e){if(!e.length)return e;const t=new Map,i=d.getMinEnabledLayerId(),a=d.getMaxEnabledLayerId(),s=Math.min(this.maxSendLayerId,this.hdVideoEnabled?a:Math.min(2,a));return e.map(e=>{let t=Math.max(i,Math.min(s,e));for(;!d.isLayerEnabled(t);)--t;return t}).forEach(e=>{const i=this.getEncodingIndex(e),a=t.get(i);(void 0===a||e<a)&&t.set(i,e)}),Array.from(t.values()).sort()}onMediaRequest(e){const t=!!e.length;this.requestedLayerIds=[...e];const i=this._reduceRequestLayerIds(e);L(Object(m.replaceComma)("WMSC_New_Media_Request: layer ids: ".concat(JSON.stringify(e)," -> ").concat(JSON.stringify(i)))),this.sendLayerIds=i,this.mediaRequested!==t?(this.mediaRequested=t,this.videoPublished&&(t?this._onVideoStart():this._onVideoStop())):this.videoPublished&&t&&M.updateLayers(this.sendLayerIds)}resendVideo(){this.requestedLayerIds.length&&this.onMediaRequest(this.requestedLayerIds)}async onQosMessage(e){switch(e.type){case n.QOS_EVENT.LAYERS_UPDATE:return this.onLayersAllocationUpdate(e.data);case n.QOS_EVENT.MIN_BITRATE_UPDATE:return this.updateMinOutgoingBitrate(e.data)}}async onLayersAllocationUpdate(e){this.encodingMap.clear(),e.forEach(e=>{const{layerId:t,bitrate:i,formatIdx:a}=e,s=this.getEncodingIndex(t);this.encodingMap.set(s,{layerId:t,bitrate:i,formatIdx:a})}),await this._updateSendParameters()}async updateMinOutgoingBitrate(e){const t=this.getEgressPc();if(!t)throw new Error("Egress peer connection has not been created");L("WMSC_Update_Min_Bitrate: ".concat(e)),M.resetSendStats();const i=c.parseSdp(t.remoteDescription.sdp);c.updateCodecParameters(i,"video","recvonly","H264",new Map([["x-google-min-bitrate",Math.floor(e/1e3)]]));const a=c.writeSdp(i);try{await t.setLocalDescription(t.localDescription),await t.setRemoteDescription({type:"answer",sdp:a})}catch(e){return s.default.globalTrace({logLevel:"error",log:"WMSC_UMOBF: ".concat(e.message)}),L("WMSC_UMOBF"),Promise.reject(e)}}async _updateSendParameters(){const e=this.getSender(this.videoMid);if(null==e||!e.track)return void L("WMSC_USPTNP: ".concat(!!e));const{width:t,height:i}=this.sourceVideoSettings,a=Math.max(t,i);let n="WMSC_Update_Send_Params:";const r=e.getParameters();r.encodings.forEach((e,s)=>{const r=this.encodingMap.get(s);if(e.active=!!r,e.active){const{layerId:o,bitrate:c,formatIdx:l}=r,h=d.getVideoFormatByIndex(l),u=Math.max(1,a/Math.max(h.width,h.height)),m=d.getMaxBitrateByVideoFormat(o,{width:t/u,height:i/u});e.maxBitrate=Math.min(m,c),e.scaleResolutionDownBy=u,e.maxFramerate=d.getMaxFramerate(o),n+=" index ".concat(s,": ").concat(o,",").concat(e.maxBitrate,",").concat(e.maxFramerate)+",".concat(e.scaleResolutionDownBy)}}),r.degradationPreference="maintain-resolution",L(Object(m.replaceComma)(n));try{await e.setParameters(r)}catch(e){return s.default.globalTrace({logLevel:"error",log:"WMSC_SETPARAMSE",errorEvent:e}),L("WMSC_SETPARAMSE"),Promise.reject(e)}}_getEgressRemoteCodecParams(){const e=M.getMinBandwidth();return new Map([["x-google-min-bitrate",Math.floor(e/1e3)]])}_getIngressLocalCodecParams(){return new Map([["sps-pps-idr-in-keyframe",1]])}createPeerConnection(e,t,i,a,r){if(L("WMSC_Start_Create_PC: ".concat(e)),this.getPc(e))return b.error("WMSC_PC_Existed, PC ".concat(e," has been created, cannot create new one")),L("WMSC_PC_Existed: ".concat(e)),!1;const o=new RTCPeerConnection({bundlePolicy:"max-bundle",iceServers:r});if(L("WMSC_PC_Create_Success: ".concat(e)),e===n.PEER_ID.INGRESS){for(let e=0;e<a;e++){const a=o.addTransceiver(t,{direction:i}),n=e.toString();this.recvTransceivers.set(n,a);try{let e=this.recvPreferCodecs;this.senderCodec&&(e=[...this.recvPreferCodecs,this.senderCodec]),this.recvCodecNum>0&&a.setCodecPreferences(e)}catch(e){s.default.globalTrace({logLevel:"error",log:"WMSC_CODECPREFERENCE_ERROR",errorEvent:e}),L("WMSC_CPE")}}M.resetRecv()}else{const e=o.addTransceiver(t,{direction:i,sendEncodings:this.getSendEncodings(this.numSimulcastLayers)}),a="0";this.sendTransceivers.set(a,e),this.videoMid=a,M.resetSend()}return this.pcs.set(e,o),o.onicecandidate=e=>{},o.ontrack=this.onRemoteStream.bind(this,e),o.onconnectionstatechange=this.onconnectionstatechange.bind(this,e),o.onsignalingstatechange=this.onsignalingstatechange.bind(this,e),o.oniceconnectionstatechange=t=>{const i=t.target.iceConnectionState;b.log("oniceconnectionstatechange, peerId: ".concat(e," state: ").concat(i)),L("WMSC_ICESTATE: ".concat(e,"|").concat(i)),"failed"===i&&s.default.globalTrace({logLevel:"error",log:"WMSC_ICE_State_Error: ".concat(e,"|").concat(i)})},o.onnegotiationneeded=t=>{b.log("onnegotiationneeded, peerId: ".concat(e)),L("WMSC_onnegotiationneeded: ".concat(e))},o.onicegatheringstatechange=t=>{const{iceGatheringState:i}=t.target;L("WMSC_CANDGA: ".concat(e,"|").concat(i))},o.onicecandidateerror=t=>{const{errorCode:i,errorText:a,url:n}=t;L("WMSC_onicecandidateerror: ".concat(e,"|").concat(i)),s.default.globalTrace({logLevel:"error",log:"WMSC_onicecandidateerror: ".concat(i,"|").concat(a,"|").concat(n)})},o}onconnectionstatechange(e,t){const i=t.target.connectionState;b.log("WMSC_onconnectionstatechange, peerId: ".concat(e," state: ").concat(i)),L("WMSC_onconnectionstatechange: ".concat(e,"|").concat(i)),this._handlePcStateChange(e,i)}_handlePcStateChange(e,t){let i="";switch(t){case"connecting":setTimeout(()=>{const i=this.getPc(e);"connecting"===(null==i?void 0:i.connectionState)&&this.messageCallback({type:n.MEDIA_EVENT.PC_STATE_CHANGE,data:t,peerId:e})},n.PC_STATE_CONNECTING_TIMEOUT);break;case"connected":{this.messageCallback({type:n.MEDIA_EVENT.PC_STATE_CHANGE,data:t,peerId:e});const i=this.timeCostMap.get(e);if(i){const t=performance.now();i.push(t);const a=this.getNegotiationTime(e);s.default.globalTrace({logLevel:"log",log:"peerId: ".concat(e,"|result: ").concat(a),tags:["WMSC Negotiation time"]}),L("WMSCNT-".concat(e,"-").concat(a.join("-"))),this.timeCostMap.delete(e)}break}case"disconnected":setTimeout(()=>{const i=this.getPc(e);"disconnected"===(null==i?void 0:i.connectionState)&&this.messageCallback({type:n.MEDIA_EVENT.PC_STATE_CHANGE,data:t,peerId:e})},n.PC_STATE_DISCONNECTED_TIMEOUT);break;case"failed":this.messageCallback({type:n.MEDIA_EVENT.PC_STATE_CHANGE,data:t,peerId:e}),i="WMSC_PC_State_Failed: ".concat(e,"-").concat(this.getNegotiationTime().join("-")),L(i),s.default.globalTrace({logLevel:"error",log:i}),this.timeCostMap.delete(e)}}onsignalingstatechange(e,t){const{signalingState:i}=t.target;b.log("WMSC_onsignalingstatechange: peerId; ".concat(e," state: ").concat(i)),L("WMSC_onsignalingstatechange: ".concat(e,"|").concat(i))}onRemoteStream(e,t){this.messageCallback&&this.messageCallback({type:n.MEDIA_EVENT.STREAM,data:t,peerId:e})}async createOffer(e,t){const i=this.getPc(e);if(!i)throw new Error("Peer connection has not been created, peerId: ".concat(e));let a="";try{const s=[performance.now()];this.timeCostMap.set(e,s);const r=await i.createOffer(t);s.push(performance.now()),L("WMSC_CO: ".concat(e));const o=c.parseSdp(r.sdp);return e===n.PEER_ID.INGRESS?c.mungeIngressLocalOffer(o,this._getIngressLocalCodecParams()):c.mungeEgressLocalOffer(o,this.numSimulcastLayers),a=r.sdp=c.writeSdp(o),await i.setLocalDescription(r),s.push(performance.now()),L("WMSC_SLDS: ".concat(e)),b.log("createOffer, peerId: ".concat(e,", local offer sdp: ").concat(i.localDescription.sdp)),e!==n.PEER_ID.INGRESS&&c.mungeEgressOfferToRemote(o),c.writeSdp(o)}catch(t){return b.error(t),m.encodeString(a,n.TEXT_ENCODING.GZIP_BASE64).then(i=>{s.default.globalTrace({logLevel:"error",log:"WMSC_OFSLDF: peerId: ".concat(e,"|error: ").concat(t.message,"|sdp: ").concat(i)})}).catch(()=>{s.default.globalTrace({logLevel:"error",log:"WMSC_OFSLDF: peerId: ".concat(e,"|error: ").concat(t.message,"|sdp: ").concat(a)})}),L("WMSC_OFSLDF: ".concat(e)),Promise.reject(t)}}async setAnswer(e,t){const i=this.timeCostMap.get(e);null==i||i.push(performance.now());const a=this.getPc(e);if(!a)throw new Error("Peer connection has not been created, peerId: ".concat(e));const r=c.parseSdp(t);e===n.PEER_ID.EGRESS&&c.mungeEgressAnswer(r,this._getEgressRemoteCodecParams());const o=c.writeSdp(r);b.log("setAnswer, peerId: ".concat(e,", answer sdp: ").concat(o));try{await a.setRemoteDescription({type:"answer",sdp:o}),null==i||i.push(performance.now()),L("WMSC_SRDS: ".concat(e))}catch(t){return b.error(t),m.encodeString(o,n.TEXT_ENCODING.GZIP_BASE64).then(i=>{s.default.globalTrace({logLevel:"error",log:"WMSCSRDF: peerId: ".concat(e,", errorMsg:").concat(t.message,", sdp: ").concat(i)})}).catch(()=>{s.default.globalTrace({logLevel:"error",log:"WMSCSRDF: peerId: ".concat(e,", errorMsg:").concat(t.message,", sdp: ").concat(o)})}),L("WMSC_SRDF: ".concat(e)),Promise.reject(t)}}closePeerConnection(e){var t;L("WMSC_Close_PC: ".concat(e)),null===(t=this.pcs.get(e))||void 0===t||t.close(),this.pcs.delete(e),e===n.PEER_ID.EGRESS?this._onEgressPcClose():this._onIngressPcClose()}getNegotiationTime(e){const t=this.timeCostMap.get(e),i=[];if(t){const e=t.length;for(let a=0;a<e-1;a++)i.push(Math.round(t[a+1]-t[a]));i.push(Math.round(t[e-1]-t[0]))}return i}removeRecvCodecByProfile(e){this.recvCodecNum=0,this.recvPreferCodecs=this.recvPreferCodecs.filter(t=>{let{mimeType:i,sdpFmtpLine:a}=t;if("video/H264"!==i)return!0;return-1===a.toLowerCase().indexOf("profile-level-id=".concat(e))&&(this.recvCodecNum++,!0)})}},w=i(102);const A={SDP_OFFER:1,SDP_ANSWER:2,SDP_OK:3,SDP_BYE:4,STREAM_MAPPING:5,ICE_DISCONNECTED:6,CMD:110,CMD_PARAM:{CMD_NONE:0,CMD_BIT_STREAM_RECORD:1,CMD_BIT_STREAM_LOAD:2,STREAM_CONGEST_CTL:3,STREAM_CONGEST_REPORT:4},JOIN_CONF:200,JOIN_CONF_ACK:712,DROP_USER:201,CLOSE_CONF:202,ROSTER_REPORT:203,CAM_INDICATOR:204,SUBSCRIBE:205,SUBSCRIBE_LIST:206,KEEPALIVE:207,MEDIA_NEGOTIATION_FROM_RWG:4096,MEDIA_ACTION_FROM_RWG:4097,JOIN_CONF_SUCCESS:4098,JOIN_SESSION_SUCCESS:4099,ACTIVE_VIDEO:4101,ACTIVE_VIDEO_SOURCE:4102,DIRECT_MESSAGE_TO_RWG:1024,VIDEO_SUBSCRIBE_REQ:1027,MEDIA_NEGOTIATION_TO_RWG:1028,MEDIA_ACTION_TO_RWG:1029,WS_WEBRTC_MEDIA_NEGOTIATION:32769,WS_WEBRTC_MEDIA_ACTION:32770},D=(e,t,i,a,s,n,r)=>({type:A.STREAM_MAPPING,confID:e,sessionID:t,userID:i,peerID:a,mID:s,streamID:n,videoSize:r}),O=(e,t,i,a,s,n,r)=>({type:A.SDP_OFFER,confID:e,sessionID:t,userID:i,peerID:a,msgID:s,sdp:n,sdpEncoding:r}),N=(e,t,i,a,s,n)=>({type:A.SDP_BYE,confID:e,sessionID:t,userID:i,peerID:a,msgID:s,sdp:n});var B=i(113);var P=new class{constructor(){this.sendVideoSizeLowerLimit=0,this.sendVideoSizeUpperLimit=4,this.recvVideoSizeLowerLimit=0,this.recvVideoSizeUpperLimit=4,this.recvVideoNumLowerLimit=4,this.recvVideoNumUpperLimit="Android"===o.default.os?16:26,this.sendVideoSizeLowerLimitApp=this.sendVideoSizeLowerLimit,this.sendVideoSizeUpperLimitApp=this.sendVideoSizeUpperLimit,this.recvVideoSizeLowerLimitApp=this.recvVideoSizeLowerLimit,this.recvVideoSizeUpperLimitApp=this.recvVideoSizeUpperLimit,this.recvVideoNumLowerLimitApp=this.recvVideoNumLowerLimit,this.recvVideoNumUpperLimitApp=this.recvVideoNumUpperLimit,this.maxSendVideoSize=0,this.maxRecvVideoSize=0,this.maxRecvVideoNum=0,this.hardwareConcurrency=o.default.hardwareConcurrency,this._reset()}_reset(){let e,t;"iOS"===o.default.os||this.hardwareConcurrency>=8?(e=4,t=4):(e=3,t=3),this.maxSendVideoSize=Math.max(this.sendVideoSizeLowerLimit,this.sendVideoSizeLowerLimitApp,Math.min(this.sendVideoSizeUpperLimit,this.sendVideoSizeUpperLimitApp,e)),this.maxRecvVideoSize=Math.max(this.recvVideoSizeLowerLimit,this.recvVideoSizeLowerLimitApp,Math.min(this.recvVideoSizeUpperLimit,this.recvVideoSizeUpperLimitApp,t)),this.maxRecvVideoNum=Math.max(this.recvVideoNumLowerLimit,this.recvVideoNumLowerLimitApp,Math.min(this.recvVideoNumUpperLimit,this.recvVideoNumUpperLimitApp))}setLimits(e){const{minSendVideoSize:t,maxSendVideoSize:i,minRecvVideoSize:a,maxRecvVideoSize:s,minRecvVideoNum:n,maxRecvVideoNum:r}=e;void 0!==t&&(this.sendVideoSizeLowerLimitApp=t),void 0!==i&&(this.sendVideoSizeUpperLimitApp=i),void 0!==a&&(this.recvVideoSizeLowerLimitApp=a),void 0!==s&&(this.recvVideoSizeUpperLimitApp=s),void 0!==n&&(this.recvVideoNumLowerLimitApp=n),void 0!==r&&(this.recvVideoNumUpperLimitApp=r),this._reset()}getCapabilities(){return{maxSendVideoSize:this.maxSendVideoSize,maxRecvVideoSize:this.maxRecvVideoSize,maxRecvVideoNum:this.maxRecvVideoNum}}};const V=s.default.getTracer("WmscMonitor"),U=e=>{V.log(e),s.default.monitorLog("".concat(e))},{NET_QUALITY_LEVEL:x,NET_BW_LEVEL:W}=n;var F=new class{constructor(){this.bToPrint=!0,this.mIdMgr=null,this.captureTimer=null,this.reportTimer=null,this.userId="",this.recvStats={},this.sendStats={},this.isMonitoring=!1,this.subInfo={},this.activeSpeaker="",this.isPreActiveSpeaker=!1,this.recordUserId="",this.captureTimer=null,this.reportTimer=null,this.lastSendPCsStatRecord=new Map,this.captureCount=0,this._startCapture=this._startCapture.bind(this),this.rtpHeaderExt={"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay":0,"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01":1,"urn:ietf:params:rtp-hdrext:sdes:mid":2,"http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00":3},this.sdpDirection={recvonly:0,sendonly:1,sendrecv:2,inactive:3},this.recvStatisticData={},this.reportCount=0,this.maxSubscribedSize=-1,this._telemetry=null,this.uiQosData={},this.isUISubQos=!1,this.UIQosInterval=1,this.candidateLog={0:"",1:"",2:"",3:"",4:""},this.candidatePairLog={0:"",1:"",2:"",3:"",4:""},this.iceCandidatePairState={frozen:0,waiting:1,"in-progress":2,failed:3,succeeded:4},this.ssrcMidMap={},this.candidatePairMonitorLog=new Array(5).fill(""),this.candidatePairChangeCount=new Array(5).fill(0),this.ingressReport={},this.camStream=null,this.recvCodecProfile="",this.shouldReportNullDecoderError=!0,this.shouldReportEncodeFailedError=!0,this.recvRawStats={},this.sendRawStats={},this.ssrcLayerMap={},this.rawLog=[],this.prevUplinkState={},this.prevDownlinkState={},this.networkReportDelay=0}setTelemetry(e){this._telemetry="function"==typeof e?e:null}updateQosSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3;this.isUISubQos=e,this.UIQosInterval=Math.round(t/1e3)}setUserId(e){this.userId=parseInt(e,10)}setQoSDataCb(e){this.sendQoSData=e}updateSubInfo(e,t){U("WMSC_USBI: ".concat(e,"|").concat(t)),t>=0?this.subInfo[e]=t:(delete this.subInfo[e],this.resetRecvStats(e)),V.log("updateSubInfo:",this.subInfo)}setActiveSpeaker(e,t){this.activeSpeaker=m.getNodeId(parseInt(e,10)),this.isPreActiveSpeaker=t}updateSubscribedSize(e,t,i){let a=-1;Array.from(new Set([...e,...t,...i])).forEach(e=>{a=Math.max(a,e)}),this.maxSubscribedSize=a}start(){U("WMSC_MSTART: ".concat(this.isMonitoring)),this.isMonitoring||(this._startCapture(),this._startReport(),this.isMonitoring=!0,this.shouldReportNullDecoderError=!0,this.shouldReportEncodeFailedError=!0,this.networkReportDelay=0)}resetRecvStats(e){this.recvStats.statisticData&&delete this.recvStats.statisticData[e],this.recvStats["begin-video-inbound-rtp"]&&delete this.recvStats["begin-video-inbound-rtp"][e],this.recvStats["video-inbound-rtp"]&&delete this.recvStats["video-inbound-rtp"][e],this.recvStats["video-remote-outbound-rtp"]&&delete this.recvStats["video-remote-outbound-rtp"][e]}stop(){U("WMSC_MSTOP: ".concat(this.isMonitoring)),clearInterval(this.reportTimer),clearTimeout(this.captureTimer),this.recvStats={},this.sendStats={},this.isMonitoring=!1}getResolutionId(e){return e<=14400?0:e<=57600?1:e<=230400?2:e<=921600?3:e<=2073600?4:5}_sendQosData(){if(this.isUISubQos&&this.captureCount%this.UIQosInterval==0){if(this.uiQosData.receiving){const e=this.recvStats["candidate-pair"]||{},{currentRoundTripTime:t=0}=e,i=Math.round(1e3*t);this._telemetry&&this._telemetry({type:w.eventOut.VIDEO_QOS_DATA,data:{encoding:!1,...this.uiQosData.receiving,rtt:i}}),this.uiQosData.receiving=null}this.uiQosData.sending&&(this._telemetry&&this._telemetry({type:w.eventOut.VIDEO_QOS_DATA,data:{encoding:!0,...this.uiQosData.sending}}),this.uiQosData.sending=null)}}_sendNetworkState(e){const{isUplink:t}=e;let i=!1;i=t?e.networkLevel!==this.prevUplinkState.networkLevel||e.bwLevel!==this.prevUplinkState.bwLevel:e.networkLevel!==this.prevDownlinkState.networkLevel||e.bwLevel!==this.prevDownlinkState.bwLevel,i&&(this._telemetry&&this._telemetry({type:w.eventOut.NETWORK_QUALITY_CHANGE,data:e}),t?this.prevUplinkState=e:this.prevDownlinkState=e)}_getNetworkState(e,t,i){let a=x.NET_QUALITY_UNKNOWN,s=W.NET_BW_LEVEL_UNKNOWN;if(e>.5||t/2>5)a=x.NET_QUALITY_VERY_BAD;else if(e>.3||t/2>2)a=x.NET_QUALITY_BAD;else if(void 0!==i){const n=i/1024;n<320||e>.08&&t>.5?a=x.NET_QUALITY_NOT_GOOD:n>450?(a=x.NET_QUALITY_GOOD,s=W.NET_BW_LEVEL_NORMAL):n>850&&e<.05&&t<.3&&(a=x.NET_QUALITY_EXCELLENT,s=W.NET_BW_LEVEL_NORMAL)}return{networkLevel:a,bwLevel:s}}async _startCapture(){this.captureCount++;try{await Promise.all([this._captureRecvStats(),this._captureSenderStats()]),this._sendQosData()}catch(e){V.error("_startCapture, capture error: ".concat(e)),U("WMSC_LOGCE"),s.default.globalTrace({logLevel:"error",log:"WMSC_LOGCE",errorEvent:e})}finally{this.captureTimer=setTimeout(this._startCapture,n.STATS_MONITOR_INTERVAL)}}_startReport(){this.reportTimer=setInterval(this._reportStats.bind(this),n.STATS_REPORT_INTERVAL)}_reportStats(){try{this.reportCount++,this._getStats(),this._resetStats(),this.ingressReport.begin=null}catch(e){U("WMSC_LOGRE"),s.default.globalTrace({logLevel:"error",log:"WMSC_LOGRE",errorEvent:e})}}_resetStats(){for(const e in this.sendStats){const{statisticData:t}=this.sendStats[e];t.maxRtt=0,t.maxCamCaptureFps=t.maxCaptureFps=0,t.minCamCaptureFps=t.minCaptureFps=Math.MAX_SAFE_INTEGER,t.totalCamCaptureCount=t.totalCaptureCount=0,t.totalCamCaptureFps=t.totalCaptureFps=0;for(const i in this.sendStats[e]["video-outbound-rtp"])t[i]={maxEncodeTime:0,minEncodeTime:Number.MAX_SAFE_INTEGER,avgEncodeTime:0,minSendFrameRate:Number.MAX_SAFE_INTEGER,maxSendFrameRate:0,avgSendFrameRate:0,minSendBitRate:Number.MAX_SAFE_INTEGER,maxSendBitRate:0,avgSendBitRate:0,minPacketSentDelay:Number.MAX_SAFE_INTEGER,maxPacketSentDelay:0,avgPacketSentDelay:0,maxLossRate:"",avgLossRate:"",encodePauseCount:0,count:0},this.sendStats[e]["begin-video-outbound-rtp"][i]=this.sendStats[e]["video-outbound-rtp"][i],this.sendStats[e]["video-remote-inbound-rtp"]&&(this.sendStats[e]["begin-video-remote-inbound-rtp"][i]=this.sendStats[e]["video-remote-inbound-rtp"][i]);this.sendStats[e]["begin-candidate-pair"]=this.sendStats[e]["candidate-pair"],this.sendStats[e]["begin-video-media-source"]=this.sendStats[e]["video-media-source"],delete this.sendStats[e].codec}for(const e in this.recvStats["video-inbound-rtp"])this.recvStats.statisticData[e]={maxFps:0,minFps:Number.MAX_SAFE_INTEGER,avgFps:0,maxDecodeTime:0,minDecodeTime:Number.MAX_SAFE_INTEGER,avgDecodeTime:0,maxLossRate:0,avgLossRate:0,maxBt:0,minBt:Number.MAX_SAFE_INTEGER,avgBt:0,maxJitter:0,minLastRecvGap:Number.MAX_SAFE_INTEGER,maxLastRecvGap:0,avgLastRecvGap:0,noDataCount:0,count:0,decodePausedCount:0},this.recvStats["begin-video-inbound-rtp"][e]=this.recvStats["video-inbound-rtp"][e],this.recvStats["video-remote-outbound-rtp"]&&(this.recvStats["begin-video-remote-outbound-rtp"][e]=this.recvStats["video-remote-outbound-rtp"][e]);this.recvStats["begin-candidate-pair"]=this.recvStats["candidate-pair"],this.recvStats.statisticData.maxRtt=0,delete this.recvStats.codec}async _captureSenderStats(){const e=n.PEER_ID.EGRESS,t=y.getPc(e);if(!t)return;const i=await t.getStats(),a={};this.sendStats[e]||(this.sendStats[e]={});const r={},o={};let c="",d="",l=!1,h=0,u=0;if(i.forEach(t=>{_.getSendStatsMonitor().onStatsReport(t);const{kind:i,type:s}=t,n="".concat(i?i+"-":"").concat(s),l="begin-".concat(n);if("video"!==i||"outbound-rtp"!==s&&"remote-inbound-rtp"!==s)if("candidate-pair"===s){const{id:e}=t;r[e]=t,d+=this._getCandidatePairLog(t)}else if("local-candidate"===s||"remote-candidate"===s){const{id:e}=t;o[e]=t,c+=this._getCandidateLog(t)}else if("codec"===s){const{id:e}=t;a[n]||(a[n]={}),a[n][e]=t}else a[n]=t;else{const{ssrc:i}=t;a[n]||(a[n]={}),a[n][i]=t,this.sendStats[e][l]&&this.sendStats[e][l][i]||(this.sendStats[e][l]={...this.sendStats[e][l],[i]:t})}}),this._captureRawSendData(a["video-media-source"]),a.candidates=o,a.candidatePairs=r,a.transport){const{selectedCandidatePairId:t,dtlsState:i}=a.transport;if("connected"===i){const i=r[t];if(i){const{localCandidateId:t,remoteCandidateId:s}=i;a["remote-candidate"]=o[s],a["local-candidate"]=o[t],a["candidate-pair"]=i,this.sendStats[e]["begin-candidate-pair"]||(this.sendStats[e]["begin-candidate-pair"]=i)}}}this.sendStats[e]["begin-video-media-source"]||(this.sendStats[e]["begin-video-media-source"]=a["video-media-source"]),c!==this.candidateLog[e]&&(s.default.directSendMonitorLog("WMSC_CANDIDATE: ".concat(e,"|").concat(c)),this.candidateLog[e]=c),d!==this.candidatePairLog[e]&&(this.candidatePairChangeCount[e]++,this.candidatePairLog[e]=d);const{currentRoundTripTime:m}=a["candidate-pair"]||{},S=a["video-outbound-rtp"]||{},g=a["video-remote-inbound-rtp"]||{},p=a["video-media-source"]||{};this.sendStats[e].statisticData||(this.sendStats[e].statisticData={});const E=this.sendStats[e]["video-outbound-rtp"]||{},v=this.sendStats[e]["video-media-source"]||{},f=this.sendStats[e].statisticData,{minCaptureFps:I,maxCaptureFps:T,maxRtt:C,minCamCaptureFps:R,maxCamCaptureFps:M,totalCaptureFps:b=0,totalCaptureCount:L=0,totalCamCaptureFps:A=0,totalCamCaptureCount:D=0}=f,O=t.getSenders(),{frames:N}=p,{frames:B}=v;if(O[0]&&O[0].track){const{frameRate:e=0,width:t,height:i}=O[0].track.getSettings(),{framesPerSecond:a=e,height:s=t,width:n=i}=p;l=!0,f.minCaptureFps=Math.round(Math.min(a,I||Number.MAX_SAFE_INTEGER)),f.maxCaptureFps=Math.round(Math.max(a,T||0)),f.totalCaptureFps=b+a,f.totalCaptureCount=L+1,f.avgCaptureFps=Math.round(f.totalCaptureFps/f.totalCaptureCount),f.captureWidth=null!=s?s:"",f.captureHeight=null!=n?n:""}if(this.camStream){var P;const{frameRate:e=0}=null===(P=this.camStream.getVideoTracks()[0])||void 0===P?void 0:P.getSettings();f.minCamCaptureFps=Math.round(Math.min(e,R||Number.MAX_SAFE_INTEGER)),f.maxCamCaptureFps=Math.round(Math.max(e,M||0)),f.totalCamCaptureFps=A+e,f.totalCamCaptureCount=D+1,f.avgCamCaptureFps=Math.round(f.totalCamCaptureFps/f.totalCamCaptureCount)}m&&(f.maxRtt=Math.max(m,C||0));for(const t in S){const{framesPerSecond:i="",bytesSent:n,framesSent:r,timestamp:o,framesEncoded:c,totalEncodeTime:d,packetsSent:m,totalPacketSendDelay:p,frameHeight:_,frameWidth:v,retransmittedPacketsSent:I,active:T,qualityLimitationDurations:C}=S[t];let R=0;!1!==T&&this._captureRawSendData(S[t]);const{jitter:M}=g[t]||{};f[t]||(f[t]={});const b=f[t],{minEncodeFrameRate:L,maxEncodeFrameRate:y,minSendFrameRate:A,maxSendFrameRate:D,minSendBitRate:O,maxSendBitRate:P,maxEncodeTime:W,minEncodeTime:F,maxPacketSentDelay:k,minPacketSentDelay:G,maxJitter:z,maxLossRate:j,sendWidth:H,sendHeight:Y}=b;if(b.minEncodeFrameRate=Math.min(i,L||Number.MAX_SAFE_INTEGER),b.maxEncodeFrameRate=Math.max(i,y||0),b.maxJitter=Math.max(M,z||0),E&&E[t]){var V;if(!1===T||!l)continue;b.count++;const{timestamp:i,bytesSent:a,framesSent:h,framesEncoded:S,totalEncodeTime:g,packetsSent:M,totalPacketSendDelay:L,retransmittedPacketsSent:y}=E[t],{framesSent:z,bytesSent:Q,timestamp:q,framesEncoded:K,totalEncodeTime:J,packetsSent:$,totalPacketSendDelay:X,retransmittedPacketsSent:Z,qualityLimitationDurations:ee}=this.sendStats[e]["begin-video-outbound-rtp"][t];let te,ie,ae="",se="";R=r-h;const ne=Math.round(R/((o-i)/1e3)),re=(8*(n-a)/((o-i)/1e3)).toFixed(2),oe=Math.round((r-z)/((o-q)/1e3)),ce=(8*(n-Q)/((o-q)/1e3)).toFixed(2),de=(d-g)/(c-S)||0,le=(d-J)/(c-K)||0,he=Math.round((c-K)/((o-q)/1e3)),{current:ue,begin:me,prev:Se}=this.ingressReport;if(ue&&Se&&me){const{lostPkts:e,recvPkts:t}=ue,{lostPkts:i,recvPkts:a}=Se,{lostPkts:s,recvPkts:n}=me,r=e-i,o=e-s;se=r/(t-a+r)||0,ae=o/(t-n+o)||0}else ae=(I-Z)/(m-$)||0,se=(I-y)/(m-M)||0;if(void 0!==p&&(te=(1e3*(p-L)/(m-M)).toFixed(3),ie=(1e3*(p-X)/(m-$)).toFixed(3)),T&&c===S&&N&&N>B&&(b.encodePauseCount++,b.encodePauseCount>10&&this.shouldReportEncodeFailedError)){var x;const{frames:i=""}=this.sendStats[e]["begin-video-media-source"];let a="".concat(t,",").concat(c,",").concat(K,",").concat(N,",").concat(i,",");if(C&&ee){const{bandwidth:e,cpu:t,other:i}=C,{bandwidth:s,cpu:n,other:r}=ee;a+="".concat(e,",").concat(s,",").concat(t,",").concat(n,",").concat(i,",").concat(r)}const n=null===(x=this.camStream)||void 0===x?void 0:x.getVideoTracks()[0];n&&!n.muted&&this._telemetry({type:w.eventOut.ERROR_MESSAGE,data:{type:"WEBRTC_VIDEO_HEALTH_CHECK_FAILED"}}),a+="videoTrack:".concat(!!n,"|").concat(n&&(null==n?void 0:n.muted)),s.default.globalTrace({logLevel:"error",log:"WMSC_ENCODE_STOP: ".concat(a)}),U("WMSC_ENCODE_STOP: ".concat(a)),this.shouldReportEncodeFailedError=!1}f[t]={...b,maxEncodeTime:Math.max(W,de),minEncodeTime:Math.min(de,F),avgEncodeTime:le,minSendFrameRate:Math.min(ne,A),maxSendFrameRate:Math.max(D,ne),avgSendFrameRate:oe,minSendBitRate:Math.min(re,O),maxSendBitRate:Math.max(P,re),avgSendBitRate:ce,minPacketSentDelay:Math.min(te,G),maxPacketSentDelay:Math.max(te,k),avgPacketSentDelay:null!==(V=ie)&&void 0!==V?V:"",avgEncodeFrameRate:he,avgLossRate:isNaN(ae)?"":ae,maxLossRate:isNaN(se)?j:Math.max(se,j),sendWidth:v||H,sendHeight:_||Y},u=Math.max(u,f[t].avgLossRate)}else f[t]={...b,maxEncodeTime:0,minEncodeTime:Number.MAX_SAFE_INTEGER,avgEncodeTime:0,minSendFrameRate:Number.MAX_SAFE_INTEGER,maxSendFrameRate:0,avgSendFrameRate:0,minSendBitRate:Number.MAX_SAFE_INTEGER,maxSendBitRate:0,avgSendBitRate:0,minPacketSentDelay:Number.MAX_SAFE_INTEGER,maxPacketSentDelay:0,avgPacketSentDelay:0,maxLossRate:"",avgLossRate:"",encodePauseCount:0,count:0};if(_&&v){const e=_*v;if(e>h&&R>0){const{currentRoundTripTime:s=0}=a["candidate-pair"]||{};h=e,this.uiQosData.sending={width:v,height:_,fps:i,rtt:Math.round(1e3*s),max_loss:1e3*f[t].maxLossRate,avg_loss:1e3*f[t].avgLossRate,jitter:Math.round(1e3*(M||0)),bandwidth:f[t].avgSendBitRate}}}}if(l)if(this.networkReportDelay>5){const{currentRoundTripTime:e=0,availableOutgoingBitrate:t}=a["candidate-pair"]||{},i=this._getNetworkState(u,e,t);this._sendNetworkState({isUplink:!0,...i})}else this.networkReportDelay++;this.sendStats[e]={...this.sendStats[e],...a},this.captureCount%2==0&&l&&this.sendQoSData&&this.checkSendPCsStat()}async _captureRecvStats(){const e=y.getPc(n.PEER_ID.INGRESS);if(!e||!this.mIdMgr)return;const t=this.mIdMgr.mIdUsedStatus,i=await e.getStats();let a=0;const r={},o={};let c="",d="",l=0;this.recvStats.statisticData||(this.recvStats.statisticData={}),i.forEach(e=>{if(!this.recvCodecProfile)return;_.getRecvStatsMonitor().onStatsReport(e);const{kind:i,type:n}=e,h="".concat(i?i+"-":"").concat(n),u="begin-".concat(h);if("candidate-pair"===n){const{id:t}=e;r[t]=e,d+=this._getCandidatePairLog(e)}else if("remote-candidate"===n||"local-candidate"===n){const{id:t}=e;o[t]=e,c+=this._getCandidateLog(e)}else if("video"!==i||"inbound-rtp"!==n&&"remote-outbound-rtp"!==n)if("codec"===n){const{id:t}=e;this.recvStats[h]||(this.recvStats[h]={}),this.recvStats[h][t]=e}else this.recvStats[h]=e;else{let{mid:i,ssrc:r}=e;i||(i=this.ssrcMidMap[r]),this.recvStats[u]||(this.recvStats[u]={}),this.recvStats[h]||(this.recvStats[h]={});const{userId:o,used:c}=t[i]||{};if(i&&c&&"inbound-rtp"===n){let t;this._captureRawRecvData(e);let n=0;const{framesPerSecond:r="",timestamp:c="",framesDecoded:d="",frameWidth:h="",frameHeight:u="",bytesReceived:m="",framesReceived:S="",totalDecodeTime:g="",packetsReceived:p="",packetsLost:_="",jitter:E="",lastPacketReceivedTimestamp:v=0,fecPacketsReceived:f=0,retransmittedPacketsReceived:I=0,jitterBufferEmittedCount:T,decoderImplementation:C,pliCount:R}=e;if(this.recvStats.statisticData[o]){this.recvStats.statisticData[o].count++;const{maxFps:e,minFps:a,maxDecodeTime:h,minDecodeTime:u,maxLossRate:S,maxBt:R,minBt:M,maxJitter:b,minLastRecvGap:L,maxLastRecvGap:y,avgLastRecvGap:w,count:A}=this.recvStats.statisticData[o],D=this.recvStats["video-inbound-rtp"][o],O=this.recvStats["begin-video-inbound-rtp"][o],{timestamp:N,framesDecoded:B,totalDecodeTime:P,packetsLost:V,packetsReceived:x,bytesReceived:W,fecPacketsReceived:F=0,retransmittedPacketsReceived:k=0,jitterBufferEmittedCount:G=0,pliCount:z=0}=O||{},{packetsLost:j,packetsReceived:H,totalDecodeTime:Y,framesDecoded:Q,bytesReceived:q,timestamp:K,lastPacketReceivedTimestamp:J,fecPacketsReceived:$=0,retransmittedPacketsReceived:X=0,jitterBufferEmittedCount:Z=0}=D||{};n=d-Q,0===n&&T>Z&&this.recvStats.statisticData[o].decodePausedCount++,"NullVideoDecoder"===C&&this.shouldReportNullDecoderError&&(s.default.globalTrace({logLevel:"error",log:"WMSC_NULLDECODER: ".concat(i)}),U("WMSC_NULLDECODER,".concat(i)),this.shouldReportNullDecoderError=!1);const ee=p-x-(f-F)-(I-k),te=(_-j)/(p-H-(f-$)-(I-X)+(_-j))||0,ie=(g-Y)/(d-Q)||0;t=8*(m-q)/((c-K)/1e3);const ae=8*(m-W)/((c-N)/1e3);if(J){const e=parseInt(v-J,10);this.recvStats.statisticData[o].minLastRecvGap=Math.min(L,e),this.recvStats.statisticData[o].maxLastRecvGap=Math.max(y,e),this.recvStats.statisticData[o].avgLastRecvGap=parseInt((w*(A-1)+e)/A,10),0===e&&this.recvStats.statisticData[o].noDataCount++}else this.recvStats.statisticData[o].minLastRecvGap=0,this.recvStats.statisticData[o].noDataCount++;this.recvStats.statisticData[o].maxFps=Math.max(e,r),this.recvStats.statisticData[o].minFps=Math.min(a,r),this.recvStats.statisticData[o].avgFps=Math.round((d-B)/((c-N)/1e3)),this.recvStats.statisticData[o].maxDecodeTime=Math.max(h,ie),this.recvStats.statisticData[o].minDecodeTime=Math.min(ie,u),this.recvStats.statisticData[o].avgDecodeTime=(g-P)/(d-B)||0,this.recvStats.statisticData[o].prevTotalDecodeTime=g,this.recvStats.statisticData[o].prevFramesDecoded=d,this.recvStats.statisticData[o].maxLossRate=Math.max(S,te),this.recvStats.statisticData[o].avgLossRate=(_-V)/(ee+(_-V))||0,this.recvStats.statisticData[o].maxJitter=Math.max(b,E),this.recvStats.statisticData[o].maxBt=Math.max(t,R),this.recvStats.statisticData[o].minBt=Math.min(t,M),this.recvStats.statisticData[o].avgBt=ae,l=Math.max(this.recvStats.statisticData[o].avgLossRate,l)}else t=8*m/S*r||"",this.recvStats.statisticData[o]={maxFps:r,minFps:r,avgFps:r,maxDecodeTime:0,minDecodeTime:Number.MAX_SAFE_INTEGER,avgDecodeTime:0,maxLossRate:0,avgLossRate:0,maxBt:t,minBt:t,avgBt:t,maxJitter:E,minLastRecvGap:Number.MAX_SAFE_INTEGER,maxLastRecvGap:0,avgLastRecvGap:0,noDataCount:0,count:0,decodePausedCount:0};if(h&&u){const e=h*u;e>a&&n>0&&(this.uiQosData.receiving={avg_loss:Math.max(1e3*this.recvStats.statisticData[o].avgLossRate,0),max_loss:Math.max(1e3*this.recvStats.statisticData[o].maxLossRate,0),fps:r||0,height:u,width:h,jitter:Math.round(1e3*(E||0)),bandwidth:this.recvStats.statisticData[o].avgBt},a=e)}this.bToPrint&&this._renderStatsData(i,h,u,r,t)}else if(i&&"inbound-rtp"===n&&!this.mIdMgr.getMidReleasedStatus(i)){const{lastPacketReceivedTimestamp:t}=e;if(t){(new Date).getTime()-t>5e3&&this.mIdMgr.setMidReleasedStatus(i,!0)}}if(o&&(this.recvStats[u][o]||(this.recvStats[u][o]=e),this.recvStats[h][o]=e,"inbound-rtp"===n)){const t=this.detectDecodeFailed(o);if(this.recvCodecProfile&&t){const{codecId:a}=e,n=this.getRecvH264Profile(a),r=Object.keys(this.subInfo).length,o="".concat(this.userId,",").concat(i,",").concat(r,",").concat(t,",").concat(n);return s.default.globalTrace({logLevel:"error",log:"WMSC_DECODE_FAILED: ".concat(o)}),s.default.directSendMonitorLog("WMSC_DECODE_FAILED,".concat(o)),this.recvStats={},this.onDecodeError&&this.onDecodeError(n),void(this.recvCodecProfile="")}}}}),this.recvStats.candidatePairs=r,this.recvStats.candidates=o;const h=this.recvStats.transport;if(h){const{selectedCandidatePairId:e,dtlsState:t}=h;if("connected"===t){const t=r[e];if(t){const{localCandidateId:e,remoteCandidateId:i,currentRoundTripTime:a=0}=t;if(this.recvStats["remote-candidate"]=o[i],this.recvStats["local-candidate"]=o[e],this.recvStats["candidate-pair"]=t,this.recvStats["begin-candidate-pair"]){const{maxRtt:e}=this.recvStats.statisticData;this.recvStats.statisticData.maxRtt=Math.max(e,a)}else this.recvStats["begin-candidate-pair"]=t,this.recvStats.statisticData.maxRtt=a}}}c!==this.candidateLog[0]&&(s.default.directSendMonitorLog("WMSC_CANDIDATE 0: ".concat(c)),this.candidateLog[0]=c),d!==this.candidatePairLog[0]&&(this.candidatePairChangeCount[0]++,this.candidatePairLog[0]=d);const{currentRoundTripTime:u}=this.recvStats["candidate-pair"]||{},m=this._getNetworkState(l,u);this._sendNetworkState({isUplink:!1,...m})}_getVideoSenderLog(){var e;let t="",i="",a={};const s=y.getPc(n.PEER_ID.EGRESS);if(!s)return;const r=s.getSenders()[0];r&&null!==(e=r.track)&&void 0!==e&&e.getStats&&(a=r.track.getStats());const{fps:o="",receivingFps:c="",generatedFrames:d="",receivedFrames:l=""}=a;for(const e in this.sendStats){const a=this.sendStats[e];if(!a["video-media-source"])continue;const{frames:s=""}=a["video-media-source"];let n=0,r=0;for(const e in a["video-outbound-rtp"]){var h;const u="{[SEND".concat(this.ssrcLayerMap[e],"]}"),m="{[ENCO".concat(this.ssrcLayerMap[e],"]}"),{minEncodeFrameRate:S,maxEncodeFrameRate:g,avgEncodeFrameRate:p,minSendFrameRate:_,maxSendFrameRate:E,avgSendFrameRate:v,minSendBitRate:f,maxSendBitRate:I,avgSendBitRate:T,maxEncodeTime:C,minEncodeTime:R,avgEncodeTime:M,maxPacketSentDelay:b,minPacketSentDelay:L,avgPacketSentDelay:y,sendWidth:w="",sendHeight:A="",encodePauseCount:D,count:O}=a.statisticData[e];if(0===O)continue;let{minCaptureFps:N,maxCaptureFps:B,avgCaptureFps:P,captureHeight:V,captureWidth:U,minCamCaptureFps:x,maxCamCaptureFps:W,avgCamCaptureFps:F}=a.statisticData;this.camStream||(x=N,W=B,F=P);const{keyFramesEncoded:k="",qualityLimitationReason:G="",pliCount:z="",nackCount:j="",firCount:H="",framesSent:Y="",retransmittedPacketsSent:Q="",powerEfficientEncoder:q,hugeFramesSent:K="",packetsSent:J="",bytesSent:$="",qualityLimitationDurations:X={},encoderImplementation:Z="",targetBitrate:ee="",codecId:te,active:ie}=a["video-outbound-rtp"][e],{framesSent:ae}=a["begin-video-outbound-rtp"][e],{bandwidth:se="",cpu:ne="",none:re="",other:oe=""}=X,{mimeType:ce="h264",sdpFmtpLine:de=""}=(null===(h=a.codec)||void 0===h?void 0:h[te])||{};let le="";const he=de.match(/profile-level-id=([A-Za-z0-9]+);/);he&&(le=he[1]);let ue=-1!==ce.toLowerCase().indexOf("h264")?0:2;q&&(ue|=1);const me=w*A;Y-ae>0&&me>n&&(n=me,r=this.ssrcLayerMap[e]),t+="".concat(u,",").concat(this.maxSubscribedSize,",").concat(U,",").concat(V,",").concat(B,",").concat(N,",").concat(P,",,,,,,,").concat(g,",").concat(S,",").concat(p,",").concat(I,",").concat(f,",").concat(T,",").concat(E,",").concat(_,",").concat(v,",").concat(w,",").concat(A,",").concat(Y,",,,,").concat(W,",").concat(x,",").concat(F,",").concat(isNaN(b)?"":b,",").concat(isNaN(L)?"":L,",").concat(isNaN(y)?"":y,",").concat(J,",").concat($,",").concat(k,",").concat(K,",").concat(j,",").concat(H,",").concat(z,",").concat(Q,",").concat(G,",").concat(se,",").concat(ne,",").concat(oe,",").concat(re,",").concat(ee,",").concat(s,",").concat(D,",").concat(void 0===ie?"":ie,",").concat(O,",").concat(o,",").concat(c,",").concat(d,",").concat(l,",").concat(this.ssrcLayerMap[e],",").concat(e,","),i+="".concat(m,",").concat((1e3*C).toFixed(2),",").concat((1e3*R).toFixed(2),",").concat((1e3*M).toFixed(2),",,").concat(ue,",").concat(Z,",").concat(le,",")}t=t.replace("{[SEND".concat(r,"]}"),"{[SEND]}"),i=i.replace("{[ENCO".concat(r,"]}"),"{[ENCO]}")}return"".concat(t).concat(i)}_getVideoReceiveLog(){var e;const t=new Array(8).fill(0),i=new Array(8).fill(0);let a,r=-1;const o=new Set,c={};for(const e in this.recvStats["video-inbound-rtp"]){var d;const{maxFps:t,minFps:s,avgFps:n,maxBt:l,minBt:h,avgBt:u,minLastRecvGap:m,maxLastRecvGap:S,avgLastRecvGap:g,noDataCount:p,count:_,decodePausedCount:E}=(null===(d=this.recvStats.statisticData)||void 0===d?void 0:d[e])||{},v=this.recvStats["video-inbound-rtp"][e]||{},f=this.recvStats["begin-video-inbound-rtp"][e]||{},{framesReceived:I="",framesDropped:T="",framesDecoded:C="",totalProcessingDelay:R=""}=f,{frameHeight:M=0,frameWidth:b=0,freezeCount:L="",framesReceived:y="",framesDropped:w="",keyFramesDecoded:A="",pauseCount:D="",nackCount:O="",firCount:N="",pliCount:B="",totalProcessingDelay:P="",fecPacketsReceived:V="",retransmittedPacketsReceived:U="",framesDecoded:x="",bytesReceived:W="",packetsReceived:F="",packetsLost:k="",jitterBufferDelay:G=0,jitterBufferEmittedCount:z="",ssrc:j=""}=v,H=y-I,Y=w-T,Q=(Y/H||0).toFixed(2),q=((P-R)/(x-C)*1e3||0).toFixed(2),K=x-C;if(void 0!==this.subInfo[e]){const t=b*M;t>r&&(r=t,a=parseInt(e,10)),t>0&&K>0&&i[this.getResolutionId(t)]++}else o.add(parseInt(e,10));const J=this.mIdMgr.user2VideoDom.get(parseInt(e,10));let $="",X="",Z="";if(null!=J&&J.length){const e=J[0];$=e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>2?1:0;const t=e.getVideoPlaybackQuality();Z=t.droppedVideoFrames,X=t.totalVideoFrames-Z}c[e]="".concat(t,",").concat(s,",").concat(n,",").concat(b,",").concat(M,",").concat(e,",").concat(_,",").concat(p,",,,,,,,,,,,,,").concat(H,",").concat(Y,",").concat(Q,",").concat(this.subInfo[e]||"",",,,,").concat(K,",").concat($,",").concat(X,",").concat(Z,",").concat((l||0).toFixed(2),",").concat((h||0).toFixed(2),",").concat((u||0).toFixed(2),",").concat(F,",").concat(k,",").concat(W,",").concat(A,",").concat(D,",").concat(L,",").concat(O,",").concat(N,",").concat(B,",").concat(V,",").concat(U,",").concat(q,",").concat(Math.round(1e3*G),",").concat(z,",").concat(S,",").concat(m,",").concat(g,",").concat(E,",").concat(j,",").concat(this.ssrcMidMap[j])}this.activeSpeaker&&!o.has(this.activeSpeaker)&&null!==(e=this.recvStats.statisticData)&&void 0!==e&&e[this.activeSpeaker]?this.recordUserId=this.activeSpeaker:this.recordUserId=a;for(const e in this.subInfo){t[this.subInfo[e]]++}const l="{[RECV]},".concat(t.join(","),",").concat(i.join(","),",");if(this.recvStatisticData[(new Date).toUTCString()]=c,this.reportCount%4==0)try{const e=JSON.stringify(this.recvStatisticData);m.encodeString(e,n.TEXT_ENCODING.GZIP_BASE64).then(e=>{s.default.globalTrace({logLevel:"log",log:"WCL_WB_VIDEO,".concat(e)}),this.recvStatisticData={}}).catch(t=>{s.default.globalTrace({logLevel:"error",log:"WMSC compress video log failed",errorEvent:t}),s.default.globalTrace({logLevel:"log",log:"WCL_WB_VIDEO,".concat(e)}),this.recvStatisticData={}})}catch(e){s.default.globalTrace({logLevel:"error",log:"WMSC_Video_Log_Parse_Failed",errorEvent:e}),this.recvStatisticData={}}return c[this.recordUserId]?"".concat(l).concat(c[this.recordUserId]):l}_getVideoDecodeLog(){var e,t;if(null===(e=this.recvStats.statisticData)||void 0===e||!e[this.recordUserId])return"";const{maxDecodeTime:i,minDecodeTime:a,avgDecodeTime:s}=this.recvStats.statisticData[this.recordUserId],{powerEfficientDecoder:n,codecId:r,decoderImplementation:o=""}=this.recvStats["video-inbound-rtp"][this.recordUserId],c=(null===(t=this.recvStats.codec)||void 0===t?void 0:t[r])||{},{mimeType:d="h264"}=c,l=(-1!==d.toLowerCase().indexOf("h264")?0:2)|(n?1:0);return"{[DECO]},".concat((1e3*i).toFixed(2),",").concat((1e3*a).toFixed(2),",").concat((1e3*s).toFixed(3),",,").concat(l,",").concat(o)}_getDownLinkLog(){var e;const{maxLossRate:t="",avgLossRate:i="",maxJitter:a=""}=(null===(e=this.recvStats.statisticData)||void 0===e?void 0:e[this.recordUserId])||{},s=this.recvStats["video-inbound-rtp"][this.recordUserId]||{},{packetsLost:n="",jitter:r=""}=s,o=this.recvStats["remote-candidate"]||{},c=this.recvStats["candidate-pair"]||{},d=this.recvStats["begin-candidate-pair"]||{},{maxRtt:l}=this.recvStats.statisticData||{},{protocol:h}=o,{availableIncomingBitrate:u="",bytesReceived:m="",timestamp:S="",totalRoundTripTime:g="",responsesReceived:p="",packetsReceived:_=""}=c,{bytesReceived:E,timestamp:v}=d,f=(8*(m-E)/((S-v)/1e3)).toFixed(2),I=Math.round(g/p*1e3)||"";return"RWG_WB_DOWNLINK_NETWORK,".concat(this.userId,",3,").concat("udp"===h?0:1,",").concat(Math.round(S/1e3),",,").concat(u,",").concat(f,",").concat((100*i).toFixed(2),",").concat((100*t).toFixed(2),",,,,").concat(I,",").concat(1e3*l,",").concat(_,",").concat(n,",,,,,,,,,").concat(Math.round(1e3*r),",").concat(Math.round(1e3*a))}_getUpLinkLog(){let e="";for(const t in this.sendStats){const i=this.sendStats[t]["candidate-pair"]||{},a=this.sendStats[t]["begin-candidate-pair"]||{},s=this.sendStats[t]["remote-candidate"]||{},n=this.sendStats[t]["video-remote-inbound-rtp"]||{},{timestamp:r,availableOutgoingBitrate:o="",bytesSent:c,totalRoundTripTime:d,responsesReceived:l,packetsSent:h=""}=i,{timestamp:u,bytesSent:m}=a,{protocol:S}=s,{statisticData:g={}}=this.sendStats[t],p=isNaN(g.maxRtt)?"":Math.round(1e3*g.maxRtt);let _="",E="",v="",f="",I="";for(const e in n){const{maxJitter:t,avgLossRate:i,maxLossRate:a}=g[e],{packetsLost:s,jitter:r}=n[e];if(t&&!v&&(v=Math.round(1e3*t)),!i&&0!==i||_||(_=(100*i).toFixed(2)),!a&&0!==a||E||(E=(100*a).toFixed(2)),!s&&0!==s||f||(f=s),r&&!I&&(I=Math.round(1e3*r)),_&&E&&v&&f&&I)break}const T=(8*(c-m)/((r-u)/1e3)).toFixed(2),C=Math.round(d/l*1e3)||"";e+=",3,".concat("udp"===S?0:1,",").concat(Math.round(r/1e3),",,").concat(o,",").concat(T,",").concat(_,",").concat(E,",,,,").concat(C,",").concat(p,",").concat(h,",").concat(f,",,,,,,,,,").concat(I,",").concat(v)}return e?"RWG_WB_UPLINK_NETWORK,".concat(this.userId).concat(e):""}_getStats(){let e,t,i="WCL_WB_MCM_VIDEO,".concat(this.userId,",,").concat(document.hidden?0:1,",,");const a=this._getVideoSenderLog(),n=this._getVideoReceiveLog(),r=this._getVideoDecodeLog();this.reportCount%2==0&&(e=this._getDownLinkLog(),t=this._getUpLinkLog()),i+=a+n+r+"{[END]}",i&&s.default.directSendMonitorLog(i),e&&s.default.directSendMonitorLog(e),t&&s.default.directSendMonitorLog(t),this.candidatePairMonitorLog=this.candidatePairMonitorLog.map((e,t)=>{const i=this.candidatePairLog[t];return e!==i&&s.default.directSendMonitorLog("WMSC_CANDIDATE-PAIR: ".concat(t,"|").concat(i,"|").concat(this.candidatePairChangeCount[t])),this.candidatePairChangeCount[t]=0,i}),this.bToPrint&&(i&&V.log("_getStats, video log: ".concat(i)),e&&V.log("_getStats, downlink log: ".concat(e)),t&&V.log("_getStats, uplink log: ".concat(t)))}_renderStatsData(e){var t,i;let a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0;if(!m.isDevelopment())return;const o=null===(t=this.mIdMgr)||void 0===t?void 0:t.getVideoTags(e),{userId:c}=null===(i=this.mIdMgr)||void 0===i?void 0:i.getUserId(e);null==o||o.forEach(t=>{var i;const o=t.parentNode;if(!o)return;const d=[{elementId:"m_"+c,value:"Mid: ".concat(e)},{elementId:"u_"+c,value:"userId: ".concat(c)},{elementId:"f_"+c,value:"FrameRate: ".concat(n)},{elementId:"r_"+c,value:"Resolution: ".concat(a,"x").concat(s)},{elementId:"b_"+c,value:"Bitrate: ".concat((r/1024).toFixed(2),"kbps")},{elementId:"v_"+c,value:"video tag paused: ".concat(!!t.paused)},{elementId:"vr_"+c,value:"stream active: ".concat(!(null==t||null===(i=t.srcObject)||void 0===i||!i.active))}],l="wmsc_debug_".concat(c),h=o.querySelector("#".concat(l));h||t.insertAdjacentHTML("afterend",'<div id="'.concat(l,'" style="position: absolute; top: 50%; transform: translate(0, -50%); right: 0px; padding-right:3px"></div>')),d.reverse().forEach(e=>{const{elementId:t,value:i}=e,a=o.querySelector("#".concat(t));a?a.innerText!==i&&(a.innerText=i):h&&h.insertAdjacentHTML("afterbegin",'<div id="'.concat(t,'" style="color: red; font-size: 12px; text-align: right; margin-right: 5px">').concat(i,"</div>"))})})}checkSendPCsStat(){var e,t,i,a,s,r,o,c,d;const l=[],h=n.PEER_ID.EGRESS,u=y.getPc(h);if(!u||"connected"!==u.connectionState||!this.sendStats[h])return;const m=this.sendStats[h]["candidate-pair"]||{},S=this.sendStats[h]["video-outbound-rtp"]||{},g=S[Object.keys(S)[0]]||{},p={peerId:+h};p.bytesSent=m.bytesSent,p.availableOutgoingBitrate=m.availableOutgoingBitrate;const _=parseInt(1e3*(null!==(e=m.currentRoundTripTime)&&void 0!==e?e:0));p.rtt=_>1e4?1e4:_<0?0:_,p.timestamp=parseInt(null!==(t=g.timestamp)&&void 0!==t?t:0),p.framerate=g.framesPerSecond,p.frameHeight=g.frameHeight,p.frameWidth=g.frameWidth,p.rtpPacketsSent=g.packetsSent,p.rtpBytesSent=g.bytesSent,p.rtxBytesSent=g.retransmittedBytesSent,p.rtxPacketsSent=g.retransmittedPacketsSent,p.qualityLimitationDurationsBW=parseInt(null!==(i=null===(a=g.qualityLimitationDurations)||void 0===a?void 0:a.bandwidth)&&void 0!==i?i:0),p.qualityLimitationDurationsCPU=parseInt(null!==(s=null===(r=g.qualityLimitationDurations)||void 0===r?void 0:r.cpu)&&void 0!==s?s:0),p.qualityLimitationReason=null!==(o=g.qualityLimitationReason)&&void 0!==o?o:"none";const E=this.lastSendPCsStatRecord.get(h),v=E&&E.bytesSent||0,f=E&&E.timestamp||0;null!==(c=p.bytesSent)&&void 0!==c||(p.bytesSent=0),null!==(d=p.timestamp)&&void 0!==d||(p.timestamp=0);const I=p.timestamp-f||2*n.STATS_MONITOR_INTERVAL;p.bitrate=p.bytesSent&&parseInt(8e3*(p.bytesSent-v)/I)||0,l.push(p),this.lastSendPCsStatRecord.set(h,p),this.sendQoSData(l)}sendSdpLog(e,t,i){try{var a;const r=c.parseSdp(i),{session:o,media:d=[]}=r,{groups:l=[]}=o,{direction:h="",codecs:u=[],extensionMap:S,bandwidth:g,candidates:p}=d[0]||{},_=new Array(4).fill(-1),E=[],v={};let f="WCL_WB_SDP_".concat(t,",").concat(this.userId,",").concat(e,",").concat((null===(a=l[0])||void 0===a?void 0:a.ids.length)||0,",").concat(this.sdpDirection[h],",");if(S)for(const[e,t]of S){const{uri:i}=t,a=this.rtpHeaderExt[i];void 0!==a&&(_[a]=e)}f+=_.join(",")+",",u.forEach((i,a)=>{const{codecName:s,codecParams:r,payloadType:o,associatedPayloadType:c=""}=i;if("H264"===s&&r){"1"===r.get("packetization-mode")&&(E.push(o),E.push(r.get("profile-level-id")),E.push(r.get("max-mbps")||""),E.push(r.get("max-fs")||""),E.push(r.get("x-google-start-bitrate")||""),E.push(r.get("x-google-max-bitrate")||""),E.push(r.get("x-google-min-bitrate")||""),e===n.PEER_ID.INGRESS&&"ANSWER"===t&&0===a&&(this.recvCodecProfile=r.get("profile-level-id").substring(0,2).toLowerCase(),this.mIdMgr.changeHWDecodeLimit(this.recvCodecProfile)))}else"rtx"===s&&(v[c]=o)});for(let e=0,t=E.length;e<t;e+=7){const t=E[e];f+="".concat(t,",").concat(E[e+1],",").concat(E[e+2],",").concat(E[e+3],",").concat(E[e+4],",").concat(E[e+5],",").concat(E[e+6],",").concat(v[t],",")}d.forEach(e=>{let{ssrcGroups:t,mid:i}=e;t.forEach(e=>{let{semantics:t,ssrcs:a}=e;"FID"===t?(this.ssrcMidMap[a[0]]=i,f+="".concat(a.join(","),",")):"SIM"===t&&a.forEach((e,t)=>{this.ssrcLayerMap[e]=t})})}),f+="".concat(g||"",","),p&&p.length>0&&p.forEach(e=>{let{transport:t,address:i,port:a,priority:s}=e;f+="".concat(s,",").concat("udp"===t?0:1,",").concat(i,",").concat(a,",")}),s.default.directSendMonitorLog(f),m.encodeString(i,n.TEXT_ENCODING.GZIP_BASE64).then(i=>{s.default.globalTrace({logLevel:"log",log:"WCL_WB_SDP-".concat(e,"-").concat(t,"-").concat(i)})})}catch(a){s.default.globalTrace({logLevel:"error",log:"WMSCMonitor sendSdpLog error",errorEvent:a}),s.default.globalTrace({logLevel:"log",log:"WCL_WB_SDP: ".concat(e,"|").concat(t,"|").concat(i)}),U("WMSC_SDPLE: ".concat(e,"|").concat(t))}}_getCandidatePairLog(e){const{localCandidateId:t,remoteCandidateId:i,nominated:a,state:s,priority:n=""}=e;return"".concat(n,",").concat(t,",").concat(i,",").concat(this.iceCandidatePairState[s],",").concat(a?1:0,",")}_getCandidateLog(e){const{id:t,candidateType:i,port:a,priority:s,protocol:n,type:r,networkType:o=""}=e;return"".concat(t,",").concat(s,",").concat(n,",").concat(i,",").concat(a,",").concat(o,",").concat("remote-candidate"===r?1:0,",")}onReceiverReport(e){const{begin:t,current:i}=this.ingressReport;this.ingressReport.prev=i,this.ingressReport.current=e,t||(this.ingressReport.begin=i)}_captureRawRecvData(e){if(!e)return;const{timestamp:t,framesDecoded:i="",totalDecodeTime:a="",jitterBufferEmittedCount:s="",framesReceived:r="",ssrc:o}=e;if(!o)return;const c=this.ssrcMidMap[o],d="mid-".concat(c,"-ssrc-").concat(o);if(this.recvRawStats[d]){const{startTime:e}=this.recvRawStats[d],o=this.recvRawStats[d].framesDecoded.length,c=Math.floor((t-e)/1e3)-o;if(o+c>n.RAW_STATS_LIMIT)this._generateRecvRawLog(d),this.recvRawStats[d]={startTime:t,framesDecoded:[i],totalDecodeTime:[Math.round(1e3*a)],jitterBufferEmittedCount:[s],framesReceived:[r]};else for(let e=0;e<c;e++){const t=e===c-1;this.recvRawStats[d].framesDecoded.push(t?i:""),this.recvRawStats[d].totalDecodeTime.push(t?Math.round(1e3*a):""),this.recvRawStats[d].jitterBufferEmittedCount.push(t?s:""),this.recvRawStats[d].framesReceived.push(t?r:"")}}else this.recvRawStats[d]={startTime:t,framesDecoded:[i],totalDecodeTime:[Math.round(1e3*a)],jitterBufferEmittedCount:[s],framesReceived:[r]}}_captureRawSendData(e){if(!e)return;const{type:t}=e;if("outbound-rtp"===t){const{timestamp:t,framesSent:i,framesEncoded:a,totalEncodeTime:s,ssrc:r}=e,o="sim-".concat(this.ssrcLayerMap[r],"-ssrc-").concat(r);if(this.sendRawStats[o]){const{startTime:e}=this.sendRawStats[o],r=this.sendRawStats[o].framesSent.length,c=Math.floor((t-e)/1e3)-r;if(r+c>n.RAW_STATS_LIMIT)this._generateSendRawLog(o),this.sendRawStats[o]={startTime:t,framesSent:[i],framesEncoded:[a],totalEncodeTime:[Math.round(1e3*s)]};else for(let e=0;e<c;e++){const t=e===c-1;this.sendRawStats[o].framesSent.push(t?i:""),this.sendRawStats[o].framesEncoded.push(t?a:""),this.sendRawStats[o].totalEncodeTime.push(t?Math.round(1e3*s):"")}}else this.sendRawStats[o]={startTime:t,framesSent:[i],framesEncoded:[a],totalEncodeTime:[Math.round(1e3*s)]}}else if("media-source"===t){const{frames:t,timestamp:i}=e;if(!t&&0!==t)return;if(this.sendRawStats.capturedFrames){const{startTime:e}=this.sendRawStats.capturedFrames,a=this.sendRawStats.capturedFrames.frames.length,s=Math.floor((i-e)/1e3)-a;if(a+s>n.RAW_STATS_LIMIT)this._generateSendRawLog("capturedFrames"),this.sendRawStats.capturedFrames={startTime:i,frames:[t]};else for(let e=0;e<s;e++){const i=e===s-1;this.sendRawStats.capturedFrames.frames.push(i?t:"")}}else this.sendRawStats.capturedFrames={startTime:i,frames:[t]}}}reportRawStats(){for(const e in this.sendRawStats)this._generateSendRawLog(e,!1);for(const e in this.recvRawStats)this._generateRecvRawLog(e,!1);this._uploadRawStats()}_generateRecvRawLog(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const{startTime:i,framesDecoded:a,framesReceived:s,jitterBufferEmittedCount:n,totalDecodeTime:r}=this.recvRawStats[e],o="".concat(this.userId,",0,").concat(e,",").concat(Math.round(i/1e3),",framesDecoded=").concat(JSON.stringify(a),",framesReceived=").concat(JSON.stringify(s),",jitterBufferEmittedCount=").concat(JSON.stringify(n),",totalDecodeTime=").concat(JSON.stringify(r));this._sendRawLog(o,t),delete this.recvRawStats[e]}_generateSendRawLog(e){let t,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if("capturedFrames"===e){const{frames:i,startTime:a}=this.sendRawStats[e];t="".concat(this.userId,",1,").concat(e,",").concat(Math.round(a/1e3),",capturedFrames=").concat(JSON.stringify(i))}else{const{startTime:i,framesEncoded:a,framesSent:s,totalEncodeTime:n}=this.sendRawStats[e];t="".concat(this.userId,",1,").concat(e,",").concat(Math.round(i/1e3),",framesEncoded=").concat(JSON.stringify(a),",framesSent=").concat(JSON.stringify(s),",totalEncodeTime=").concat(JSON.stringify(n))}this._sendRawLog(t,i),delete this.sendRawStats[e]}_sendRawLog(e,t){this.rawLog.push(e),t&&this.rawLog.length>n.RAW_STATS_REPORT_LIMIT&&this._uploadRawStats()}_uploadRawStats(){if(this.rawLog.length>0){const e=this.rawLog.join("|");this.rawLog=[],m.encodeString(e,n.TEXT_ENCODING.GZIP_BASE64).then(e=>{s.default.globalTrace({logLevel:"directReport",log:e,tags:["WCL_WB_RAW_STATS"]})}).catch(()=>{s.default.globalTrace({logLevel:"directReport",log:rawLog,tags:["WCL_WB_RAW_STATS"]})})}}detectDecodeFailed(e){const{framesDecoded:t,jitterBufferEmittedCount:i="",pliCount:a,packetsLost:s,framesReceived:n=""}=this.recvStats["begin-video-inbound-rtp"][e],{framesDecoded:r,jitterBufferEmittedCount:o="",pliCount:c,packetsLost:d,decoderImplementation:l,framesReceived:h=""}=this.recvStats["video-inbound-rtp"][e],{decodePausedCount:u}=this.recvStats.statisticData[e],m="".concat(r,",").concat(t,",").concat(o,",").concat(i,",").concat(d,",").concat(s,",").concat(c,",").concat(a,",").concat(l,",").concat(u,",").concat(h,",").concat(n);return!(r>t)&&("NullVideoDecoder"===l?m:o-i<=5?!o&&h-n>150&&u>10&&m:(0===r&&c>a&&d===s||u>10)&&m)}getRecvH264Profile(e){if(this.recvStats.codec){var t;const i=null===(t=this.recvStats.codec)||void 0===t?void 0:t[e];if(i){const{sdpFmtpLine:e=""}=i,t=e.match(/profile-level-id=([A-Za-z0-9]+);/);if(t)return t[1].substring(0,2)}}return this.recvCodecProfile}};const k=s.default.getTracer("WmscApiImpl"),G=e=>{k.log(e),s.default.monitorLog("".concat(e))},z=n.PEER_ID.INGRESS,j=n.PEER_ID.EGRESS;var H=class{constructor(e,t){k.log("created, config: ".concat(JSON.stringify(e))),a.wmscConfig.setConfig(e||{}),this.messageCallback=t,this.resetRunTimeParams(),P.setLimits({maxSendVideoSize:a.wmscConfig.maxCaptureVideoSize,maxRecvVideoNum:a.wmscConfig.maxRecvVideoNum}),this.videoCapabilities=P.getCapabilities();const{maxSendVideoSize:i,maxRecvVideoSize:s,maxRecvVideoNum:n}=this.videoCapabilities;G("WMSC_V_Cap_Updated: ".concat(i,"|").concat(s,"|").concat(n)),this.recvMLineNum=n+1,this.maxRecvVideoSize=s,y.registerMessageCallback(this.onMediaMessage.bind(this)),y.enableHdVideo(a.wmscConfig.hdVideoEnabled),y.setVideoSettings(a.wmscConfig.videoSettings),this.renewEgressPeerConnection(),this.renewIngressPeerConnection(),F.setUserId(a.wmscConfig.nodeId),F.onDecodeError=this._handleDecodeError.bind(this),F.start(),M.registerSendUsageStateUpdateCallback(this.onSendUsageStateUpdate.bind(this)),M.registerMaxRecvVideoSizeUpdateCallback(this.onMaxRecvVideoSizeUpdate.bind(this)),M.start(a.wmscConfig.qosOptions),this.recevCSRCRecord=new Map,this._checkCSRCTimer=null,this.negotiationMsgId=0}destroy(){this.closeAllPeerConnections(),this.resetRunTimeParams(),this.recevCSRCRecord.clear(),clearInterval(this._checkCSRCTimer),M.stop(),null==F||F.stop()}resetRunTimeParams(){k.log("reset run time parameters"),this.pcInfos=new Map([[z,{status:n.PC_STATE.IDLE,reconnectionCount:0,negotiationTimer:0,offerMsgId:0,useIceServers:!1}],[j,{status:n.PC_STATE.IDLE,reconnectionCount:0,negotiationTimer:0,offerMsgId:0,useIceServers:!1}]]),this.camStreams=null,this.bSendEnabled=!1,this.bActiveVideo=!1,this.bPrevActiveVideo=!1,this.lastSubList=[],this.sourceVideoSize=-1,this.lastUpdatedSourceVideoSize=-1,this.bReceiveEnabled=!1,this._toSubscribeBuffer=[],this._videoTagMappingBuffer=new Map,this.mIdMgr=null,this.subscriptions=new Map,this.maxSubVideoSize=-1}async renewEgressPeerConnection(){const e=this._getPcInfo(j);let t=null==e?void 0:e.useIceServers;this.createPeerConnection(j,"video","sendonly",t?a.wmscConfig.iceServers:[]),t&&s.default.globalTrace({logLevel:"directReport",log:"WMSC_USE_TURN:Send"}),this.camStreams&&this._addVideoStreams(this.camStreams),this.bSendEnabled=!0,await this.startNegotiation(j),y.onMediaRequest(this.lastSubList)}async renewIngressPeerConnection(){G("WMSC_Start_Recv_Video");const e=this._getPcInfo(z);let t=null==e?void 0:e.useIceServers;this.createPeerConnection(z,"video","recvonly",t?a.wmscConfig.iceServers:[]),t&&s.default.globalTrace({logLevel:"directReport",log:"WMSC_USE_TURN:Recv"}),this.bReceiveEnabled=!0,await this.startNegotiation(z);const i=Array.from(y.getRecvTransceivers().keys());null!=i&&i.length?(this.mIdMgr=this.mIdMgr||new B.WmscMidMgr(i),this._mapBufferedVideoTag()):(G("WMSC_Get_Recv_Mid_Fail: ".concat(z)),this.mIdMgr=new B.WmscMidMgr([])),F.mIdMgr=this.mIdMgr}stopReceiveVideo(){G("WMSC_Stop_Recv_Video"),this.sendBye(z),this.closePeerConnection(z),this.mIdMgr=null,this.bReceiveEnabled=!1}createPeerConnection(e,t,i,a){k.log("createPeerConnection, peerId: ".concat(e,", type: ").concat(t," direction: ").concat(i));const s=e===z?this.recvMLineNum:1;return y.createPeerConnection(e,t,i,s,a)}async _addVideoStreams(e){var t,i;const a=null===(t=e[0])||void 0===t||null===(t=t.stream)||void 0===t?void 0:t.getVideoTracks()[0],s=null===(i=e[e.length-1])||void 0===i||null===(i=i.stream)||void 0===i?void 0:i.getVideoTracks()[0],n=null==s?void 0:s.getSettings();if(s){const{width:e,height:t,frameRate:i}=n||{};G("WMSC_Original_Video_Track: ".concat(e,"x").concat(t,"@").concat(i,"fps")),this.sourceVideoSize=d.getLayerIdByVideoFormat({width:e,height:t}),y.setMaxSendLayerId(Math.min(this.videoCapabilities.maxSendVideoSize,this.sourceVideoSize))}else this.sourceVideoSize=-1,this.lastUpdatedSourceVideoSize=-1;await y.publishVideoTrack(a,n)}async onVideoStreamsAsync(e){var t;return this.camStreams=e,F.camStream=null===(t=e[1])||void 0===t?void 0:t.stream,await this._addVideoStreams(e),Promise.resolve(!0)}async startNegotiation(e){const t=this._getPcInfo(e);t.negotiationTimer=setTimeout(()=>{const i=y.getNegotiationTime(e);s.default.globalTrace({logLevel:"error",log:"WMSC Negotiation timeout: ".concat(e,"-").concat(i.join("-"))}),t.reconnectionCount<n.MAX_PC_RECONNECT_COUNT?this.restartNegotiation(e):this.messageCallback({type:w.eventOut.SDP_NEGOTIATION_FAIL,data:e})},n.NEGOTIATION_TIMEOUT);const i=await y.createOffer(e);this._handleSdpOffer(e,i)}restartNegotiation(e){const t=this._getPcInfo(e);t.reconnectionCount++,G("WMSC_Restart_Nego: ".concat(e,"|").concat(t.reconnectionCount)),this.sendBye(e),this.closePeerConnection(e),this.messageCallback({type:w.eventOut.ERROR_MESSAGE,data:{type:"PC_RECONNECT",mediaType:"video"}}),e===z?this.bReceiveEnabled&&this.renewIngressPeerConnection():this.renewEgressPeerConnection()}closePeerConnection(e){const t=this._getPcInfo(e);return clearTimeout(t.negotiationTimer),t.status=n.PC_STATE.IDLE,y.closePeerConnection(e)}closeAllPeerConnections(){for(const e of this.pcInfos.keys())this.closePeerConnection(e)}onMediaMessage(e){const{type:t,data:i,peerId:a}=e;switch(k.log("onMediaMessage, peerId: ".concat(a," type: ").concat(t)),t){case n.MEDIA_EVENT.STREAM:this._handleRemoteStream(a,i);break;case n.MEDIA_EVENT.PC_STATE_CHANGE:this._handlePcStateChange(a,i);break;case n.MEDIA_EVENT.ERROR:k.error("onMediaMessage, error: ".concat(i));break;default:k.error("onMediaMessage, unknown type: ".concat(t))}}onSendUsageStateUpdate(e){e===n.RESOURCE_USAGE_STATE.UNDERUSING&&this.sourceVideoSize>=0&&this._maybeUpdateVideoSourceConstraints(this.sourceVideoSize+1)}_maybeUpdateVideoSourceConstraints(e){let t=a.wmscConfig.maxCaptureVideoSize;if(a.wmscConfig.hdVideoEnabled||(t=Math.min(2,t)),e<=t&&e!==this.lastUpdatedSourceVideoSize){const t=d.getHighestVideoFormat(e),i={width:t.width,height:t.height,frameRate:t.maxFramerate};return this.messageCallback({type:w.eventOut.UPDATE_VIDEO_CAPTURE_CONSTRAINTS,data:i}),this.lastUpdatedSourceVideoSize=e,!0}return!1}onMaxRecvVideoSizeUpdate(e){this.maxRecvVideoSize=e;const t=[];for(const[i,a]of this.subscriptions){const s=this.mIdMgr.getVideoSizeByUserId(i),n=Math.min(e,a);s!==n&&t.push({id:i,size:n})}t.length&&this._updateSubscriptions(t)}_handleVideoTagMappingBuffer(e,t,i){const a=this._videoTagMappingBuffer.get(e)||[];switch(t){case"add":a.push(i),this._videoTagMappingBuffer.set(e,a);break;case"remove":for(let e=0;e<a.length;)a[e]===i?a.splice(e,1):e++;a.length||this._videoTagMappingBuffer.delete(e);break;default:G("WMSC_Mapping_Buffer_Action_E: ".concat(e,"|").concat(t))}}onVideoTagMapping(e){const t=parseInt(e.userId),{videodom:i,action:a}=e;if(G("WMSC_Video_Tag_Mapping: ".concat(t,"|").concat(a,"|").concat(!!this.mIdMgr)),this.mIdMgr)switch(a){case"add":case"buffer":this.mIdMgr.saveVideoTag(t,i),this.messageCallback({type:w.eventOut.VIDEO_TAG_MAPPED,data:t});break;case"remove":this.mIdMgr.removeVideoTag(t,i);break;default:G("WMSC_Mapping_Action_E: ".concat(t,"|").concat(a))}else k.warn("onVideoTagMapping, mIdMgr not ready yet. Will do mapping later."),this._handleVideoTagMappingBuffer(t,a,i)}_mapBufferedVideoTag(){this._videoTagMappingBuffer.size&&(this._videoTagMappingBuffer.forEach((e,t)=>{(null==e?void 0:e.length)>0&&e.forEach(e=>{this.onVideoTagMapping({userId:t,videodom:e,action:"buffer"})})}),this._videoTagMappingBuffer.clear())}subscribeVideo(e){const t=this._getPcInfo(z);if(t.status!==n.PC_STATE.CONNECTED)return e.forEach(e=>{this._toSubscribeBuffer.push({params:e,toSub:!0})}),void G("WMSC_SubV_PC_N_Ready: ".concat(t.status));const i=Math.min(this.maxRecvVideoSize,M.getMaxFeasibleRecvVideoSize());let a=-1;const s=[];e.forEach(e=>{const{id:t,size:n}=e;this.subscriptions.set(t,n),n>a&&(a=n);const r=Math.min(n,i),o=this._addSubscription({id:t,size:r});if(o){s.push(o);const{userId:e,mId:t,videoSize:i}=o;this._updateVideoElement(e,t),this.mIdMgr.setMidReleasedStatus(t,!1),G("WMSC_Send_Stream_Mapping: ".concat(e,"|").concat(i,"|").concat(t)),F.updateSubInfo(e,i)}}),a>this.maxSubVideoSize&&(this.maxSubVideoSize=a,M.updateMaxSubVideoSize(a)),s.length&&this._sendStreamMappings(s)}unSubscribeVideo(e){if(this._getPcInfo(z).status!==n.PC_STATE.CONNECTED)return e.forEach(e=>{this._toSubscribeBuffer.push({params:e,toSub:!1})}),void G("WMSC_UnsubV_PC_N_Ready");let t=-1;const i=[];e.forEach(e=>{this.subscriptions.delete(e.id);const t=this._removeSubscription(e);if(t){const{userId:e,videoSize:a}=t;i.push(t),F.updateSubInfo(e,a)}});for(const[,e]of this.subscriptions)e>t&&(t=e);this.maxSubVideoSize!==t&&(this.maxSubVideoSize=t,M.updateMaxSubVideoSize(t)),i.length&&this._sendStreamMappings(i)}_addSubscription(e){var t,i;const a=parseInt(e.id),s=e.size;G("WMSC_SubV_Params: ".concat(a,"|").concat(s));const n=(null===(t=this.mIdMgr)||void 0===t?void 0:t.getMId(a))||(null===(i=this.mIdMgr)||void 0===i?void 0:i.getNewMId(a));if(n)return this.mIdMgr.setVideoSize(n,s),k.log("_addSubscription, userId: ".concat(a,", mId: ").concat(n,", videoSize: ").concat(s)),{userId:a,mId:n,videoSize:s};G("WMSC_SubV_No_Mid:".concat(a))}_removeSubscription(e){var t;const i=parseInt(e.id);this._videoTagMappingBuffer.delete(i),clearInterval(this.recevCSRCRecord.get(i));const a=null===(t=this.mIdMgr)||void 0===t?void 0:t.getMId(i);if(G("WMSC_UnsubV_Params: ".concat(i,"|").concat(a)),a)return this.mIdMgr.releaseMId(a),this.recevCSRCRecord.delete(i),{userId:i,mId:a,videoSize:-1}}_updateSubscriptions(e){const t=[],i=[];e.forEach(e=>{var a;const{id:s,size:n}=e,r=null===(a=this.mIdMgr)||void 0===a?void 0:a.getMId(s);r&&(t.push({userId:s,mId:r,videoSize:-1}),i.push({userId:s,mId:r,videoSize:n}),this.mIdMgr.setVideoSize(r,n))}),this._sendStreamMappings(t),this._sendStreamMappings(i)}onRwgMessage(e){const t="string"==typeof e.data?JSON.parse(e.data):e.data;if((null==t?void 0:t.evt)===A.WS_WEBRTC_MEDIA_NEGOTIATION||(null==t?void 0:t.evt)===A.WS_WEBRTC_MEDIA_ACTION){const e=t.body;switch(e.type){case A.SDP_ANSWER:return k.log("on SDP_ANSWER"),this.onSdpAnswer(e),!0;case A.SDP_BYE:return k.log("on SDP_BYE"),this.onSdpBye(e),!0;case A.ICE_DISCONNECTED:return k.log("on ICE_DISCONNECTED"),this.onIceDisconnected(e),!0;case A.SUBSCRIBE_LIST:return this.onSubscribeList(e.activeVideo,e.prevActiveVideo,e.privateVideo),!0;case A.CMD:return this.onCommand(e),!0;default:return k.warn("Received unknown RWG message type: ".concat(e.type)),!1}}}async onSdpAnswer(e){if(!this._checkMsgIdForPC(e))return;const{peerID:t,sdp:i,sdpEncoding:a}=e;try{const e=await m.decodeString(i,a);return F.sendSdpLog(t,"ANSWER",e),y.setAnswer(t,e)}catch(e){s.default.globalTrace({logLevel:"error",log:"WMSC_Decompress_SDP_Anwser_F",error:e})}}onSdpBye(e){if(!this._checkMsgIdForPC(e))return;const{peerID:t}=e;"have-local-offer"===y.getPc(t).signalingState?(this.closePeerConnection(t),s.default.globalTrace({logLevel:"error",log:"WMSC_SDP_BYE_REJECT"}),G("WMSC_BYEREJ"),this.messageCallback({type:w.eventOut.SDP_NEGOTIATION_FAIL,data:t})):(G("WMSC_BYERET"),this.restartNegotiation(t))}onIceDisconnected(e){this._checkMsgIdForPC(e)&&(G("WMSC_ICE_DISCON"),this.restartNegotiation(e.peerID))}onSubscribeList(e,t,i){G(m.replaceComma("WMSC_On_Sub_List: ".concat(JSON.stringify(e),"|").concat(JSON.stringify(t),"|").concat(JSON.stringify(i)))),F.updateSubscribedSize(e,t,i);const a=Array.from(new Set([...e,...t,...i]).values()).filter(e=>e>=0).sort();m.compareArrays(a,this.lastSubList)||(this.lastSubList=[...a],this.bSendEnabled||this.renewEgressPeerConnection(),y.onMediaRequest(a))}onCommand(e){switch(e.cmdId){case 0:{let t;try{t=JSON.parse(e.cmdParam)}catch(t){k.warn("Invalid command message: ".concat(JSON.stringify(e)))}void 0!==t.receiverBW?M.onReceiverBandwidthReport(t.receiverBW):void 0!==t.subInfo?M.onSubInfo(t.subInfo):void 0!==t.ingressReport&&(M.onReceiverReport(t.ingressReport),F.onReceiverReport(t.ingressReport))}break;default:k.warn("Unknown command id ".concat(e.cmdId))}}onActiveVideoSourceChange(e){const t=parseInt(a.wmscConfig.nodeId)===parseInt(e.userId);return this.bPrevActiveVideo=this.bActiveVideo&&!t,this.bActiveVideo=t,F.setActiveSpeaker(e.userId,this.bPrevActiveVideo),G("WMSC_OASC: ".concat(e.userId)),!0}updateWmscParams(e){k.log("updateWmscParams, data: ".concat(JSON.stringify(e)));Object.keys(e).forEach(t=>{switch(t){case"HDVideo":a.wmscConfig.setConfig({[t]:e[t]}),y.enableHdVideo(!!e[t]);break;default:k.warn("updateWmscParams, unknown param name: ".concat(t))}})}sendBye(e){const t=N(a.wmscConfig.confId,n.SESSION_ID.VIDEO,a.wmscConfig.nodeId,e,this.negotiationMsgId,"");G("WMSC_SDPBYE: ".concat(a.wmscConfig.confId,"|").concat(e)),this._sendMessageToRwg({evt:A.WS_WEBRTC_MEDIA_NEGOTIATION,body:t})}stopSendingVideo(){this._getPcInfo(j).status=n.PC_STATE.IDLE,this.sendBye(j),y.stopSendingVideo()}_sendStreamMappings(e){const t=e.map(e=>{let{userId:t,mId:i,videoSize:s}=e;return D(a.wmscConfig.confId,n.SESSION_ID.VIDEO,t,z,i,s>=0?m.getStreamId(t,n.SESSION_ID.VIDEO):0,s)});this.messageCallback({type:w.eventOut.WMSC_MAPPING_STREAMID_AND_MID,data:JSON.stringify({evt:A.WS_WEBRTC_MEDIA_ACTION,body:t})})}_sendMessageToRwg(e){this.messageCallback({type:w.eventOut.WMSC_MESSAGE_TO_RWG_BY_SDK,data:JSON.stringify(e)})}_handleRemoteStream(e,t){var i,a;if(e!==z){const t="WMSC_RSP_N_M: ".concat(e);return k.warn(t),void G(t)}const s=new MediaStream;s.addTrack(t.track);const n=t.transceiver.mid;null===(i=this.mIdMgr)||void 0===i||i.updateStream(n,s);const r=null===(a=this.mIdMgr)||void 0===a?void 0:a.getVideoTags(n);r&&r.length?(G("WMSC_RSV_M: ".concat(n)),r.forEach(e=>{e.srcObject=s})):k.log("_handleRemoteStream, video element is not mapped yet, mid= ".concat(n))}async _handleSdpOffer(e,t){let i=n.TEXT_ENCODING.PLAIN,r=t;try{r=await m.encodeString(t,n.TEXT_ENCODING.GZIP_BASE64),i=n.TEXT_ENCODING.GZIP_BASE64}catch(e){s.default.globalTrace({logLevel:"error",log:"WMSC_Compress_SDP_Offer_F",errorEvent:e})}const o=++this.negotiationMsgId,c=O(a.wmscConfig.confId,n.SESSION_ID.VIDEO,a.wmscConfig.nodeId,e,o,r,i);this._getPcInfo(e).offerMsgId=o,this._sendMessageToRwg({evt:A.WS_WEBRTC_MEDIA_NEGOTIATION,body:c}),F.sendSdpLog(e,"OFFER",t)}_handlePcStateChange(e,t){const i=this._getPcInfo(e);if("connected"===t)if(e===z){for(clearTimeout(i.negotiationTimer),i.status=n.PC_STATE.CONNECTED,i.reconnectionCount=0,i.negotiationTimer=0,k.log("_handlePcStateChange: peerId= ".concat(e," connected")),this._reSubVideo();this._toSubscribeBuffer.length;){const e=this._toSubscribeBuffer.shift();e.toSub?this.subscribeVideo([e.params]):this.unSubscribeVideo([e.params])}this.messageCallback({type:w.eventOut.V_RECEV_PC_CONNECTED,data:e})}else clearTimeout(i.negotiationTimer),i.status=n.PC_STATE.CONNECTED,i.negotiationTimer=0,i.reconnectionCount=0,k.log("_handlePcStateChange, peerId ".concat(e," connected")),this.messageCallback({type:w.eventOut.V_SEND_PC_CONNECTED,data:e});else if("disconnected"===t)G("WMSC_PC_Disconn: ".concat(e)),this.restartNegotiation(e);else if("failed"===t){G("WMSC_PC_Failed: ".concat(e));this._getPcInfo(e).reconnectionCount<n.MAX_PC_RECONNECT_COUNT?this.restartNegotiation(e):this.messageCallback({type:w.eventOut.SDP_NEGOTIATION_FAIL,data:e})}else if("connecting"===t){var s,r;G("WMSC_PC_ConnectTimeout: ".concat(e,",iceserver: ").concat(null===(s=a.wmscConfig.iceServers)||void 0===s?void 0:s.length));const t=this._getPcInfo(e);!t.useIceServers&&(null===(r=a.wmscConfig.iceServers)||void 0===r?void 0:r.length)>0&&(t.useIceServers=!0,this.restartNegotiation(e))}}_getPcInfo(e){return this.pcInfos.get(e)}_reSubVideo(){const e=this.mIdMgr.mIdUsedStatus,t=[];for(const i in e)if(e[i].used&&e[i].userId){const{userId:a,videoSize:s}=e[i];t.push({userId:a,mId:i,videoSize:s}),this._updateVideoElement(a,i),this.mIdMgr.setMidReleasedStatus(i,!1)}G("WMSC_ReSub_Video"),s.default.globalTrace({logLevel:"log",log:"WMSC_ReSub_Video"}),this._sendStreamMappings(t)}_updateVideoElement(e,t){const i=y.getPc(z);if(G("WMSC_UpdateV_Ele: ".concat(e,"|").concat(t,"|").concat(!!i)),!i)return;const{preUserId:a,released:s}=this.mIdMgr.mIdUsedStatus[t];if(!a||a===e||s)return void this.mIdMgr.updateVideoElement(t);const n=Date.now();this.recevCSRCRecord.set(e,{mId:t,startToWait:n}),this._checkCSRCTimer||(this._checkCSRCTimer=setInterval(this._checkCSRC.bind(this),100))}_checkCSRC(){if(0===this.recevCSRCRecord.size)return clearInterval(this._checkCSRCTimer),void(this._checkCSRCTimer=null);this.recevCSRCRecord.forEach((e,t)=>{const{mId:i,startToWait:a}=e,s=Date.now()-a;if(s>1e4)return G("WMSC_CSRC_Timeout: ".concat(t,"|").concat(i,"|").concat(a,"|").concat(s)),void this.recevCSRCRecord.delete(t);const n=y.getRemoteSourceId(i);n&&n>>2==t>>2&&(k.log("Receive subscribe video, userId: ".concat(t," in ").concat(s,"ms")),this.mIdMgr.updateVideoElement(i),this.messageCallback({type:w.eventOut.VIDEO_SOURCE_UPDATED,userId:t}),this.recevCSRCRecord.delete(t))})}_handleDecodeError(e){y.removeRecvCodecByProfile(e),0===y.recvCodecNum?(s.default.globalTrace({logLevel:"error",log:"WMSC_No_Recv_Codec"}),G("WMSC_ERC"),this.messageCallback({type:w.eventOut.SDP_NEGOTIATION_FAIL,data:n.PEER_ID.INGRESS})):this.restartNegotiation(n.PEER_ID.INGRESS)}_checkMsgIdForPC(e){const{peerID:t,msgID:i}=e,{offerMsgId:a}=this._getPcInfo(e.peerID);return i===a||(k.warn("Message id ".concat(i," doesn't match the offer message id ").concat(a," for peer id ").concat(t)),!1)}};i.d(t,"Wmsc",(function(){return q}));const Y=s.default.getTracer("Wmsc"),Q=e=>{Y.log(e),s.default.monitorLog("".concat(e))};class q{constructor(e,t){return s.default.setTrace(),s.default.setTelemetry(t),F.setTelemetry(t),this.messageCallback=t,this.config=e,Q("WMSC_INIT"),!0}setTrace(e,t){s.default.setTrace(e,t)}updateQosSubscription(e,t){F.updateQosSubscription(e,t)}reportWMSCPeerConnectionRawStats(){F.reportRawStats()}getHasPausedVideo(){var e;return null===(e=this.wmscApiImpl)||void 0===e||null===(e=e.mIdMgr)||void 0===e?void 0:e.getHasPausedVideo()}playAllUsedVideoTag(){var e;return null===(e=this.wmscApiImpl)||void 0===e||null===(e=e.mIdMgr)||void 0===e?void 0:e.playAllUsedVideoTag()}destroy(){var e;Q("WMSC_DESTROYED"),null===(e=this.wmscApiImpl)||void 0===e||e.destroy(),this.wmscApiImpl=null}onMessage(e,t){if(e!==w.eventExt.NOTIFY_SDK_JOIN_RWG_SUCCESS&&!this.wmscApiImpl)return this.sendMessage&&this.sendMessage({type:w.eventOut.ERROR,data:"WMSC on MediaSDK message, MediaSDK not ready, type = "+e}),Y.error("onMessage, the caller not ready type ".concat(e)),!1;switch(e){case w.eventExt.NOTIFY_SDK_JOIN_RWG_SUCCESS:return this.messageCallback?(this.wmscApiImpl=new H(this.config,this.sendMessage.bind(this)),!0):(Y.error("onMessage, messageCallback to the caller not set"),!1);case w.eventExt.NOTIFY_SDK_JOIN_RWG_FAILURE:return!0;case w.eventExt.WMSC_MESSAGE_FROM_RWG:return this._onRwgMessage(t.data);case w.eventExt.NOTIFY_WMSC_VIDEO_TAG_MAPPING:return this._onVideoTagMapping(t.data);case w.eventExt.NOTIFY_SDK_SUBSCRIBE_VIDEO:return this._onSubscribeVideo(t.data);case w.eventExt.NOTIFY_SDK_UNSUBSCRIBE_VIDEO:return this._onUnSubscribeVideo(t.data);case w.eventExt.NOTIFY_SDK_ACTIVE_VIDEO_INDICATION:return this._onActiveVideoSourceChange(t.data);case w.eventExt.UPDATE_WMSC_PARAMS:return this._onUpdateWmscParams(t.data);default:return this.sendMessage({type:w.eventOut.ERROR,data:"WSMC receive not handled event type = "+e}),Y.error("onMessage, unknown type ".concat(e)),Q("WSMC_Rece_U_E: ".concat(e)),!1}}onMessageAsync(e,t){switch(Y.log("WMSC_Recv_Async_M",e,JSON.stringify(t)),Q("WMSC_Recv_Async_M: ".concat(e)),e){case w.eventExt.VIDEO_STREAMS:return this._onVideoStreamsAsync(t.streams);default:return this.sendMessage({type:w.eventOut.ERROR,data:"WSMC receive not handled event type =".concat(e)}),Y.error("WSMC receive not handled event type =".concat(e)),Promise.reject("Unknown message type")}}sendMessage(e){Y.log("sendMessage",JSON.stringify(e)),this.messageCallback&&this.messageCallback(e)}_onVideoStreamsAsync(e){return this.wmscApiImpl.onVideoStreamsAsync(e)}_onRwgMessage(e){return this.wmscApiImpl.onRwgMessage(e)}_onVideoTagMapping(e){return this.wmscApiImpl.onVideoTagMapping(e)}_onSubscribeVideo(e){return this.wmscApiImpl.subscribeVideo(e)}_onUnSubscribeVideo(e){return this.wmscApiImpl.unSubscribeVideo(e)}_onActiveVideoSourceChange(e){return this.wmscApiImpl.onActiveVideoSourceChange(e)}_onUpdateWmscParams(e){return this.wmscApiImpl.updateWmscParams(e)}}},97:function(e,t,i){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,i,a){void 0===a&&(a=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,a,s)}:function(e,t,i,a){void 0===a&&(a=i),e[a]=t[i]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&a(t,e,i);return s(t,e),t},r=this&&this.__awaiter||function(e,t,i,a){return new(i||(i=Promise))((function(s,n){function r(e){try{c(a.next(e))}catch(e){n(e)}}function o(e){try{c(a.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,o)}c((a=a.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WMSCManager=t.eventExt=void 0;const c=i(112);Object.defineProperty(t,"eventExt",{enumerable:!0,get:function(){return c.eventExt}});const d=o(i(114)),l=o(i(0)),h=i(2),u=i(13),m=o(i(7)),S=o(i(4)),g=n(i(3)),p=o(i(34)),_=n(i(9));var E,v,f;!function(e){e.visibilitychange="visibilitychange",e.streamCaptureSuccess="streamCaptureSuccess",e.videoTrackUnmute="videoTrackUnmute",e.addRenderVideo="addRenderVideo",e.userClick="userClick",e.fromVBModule="fromVBModule",e.reuseCaptureStream="reuseCaptureStream"}(E||(E={})),function(e){e.destroy="destroy"}(v||(v={})),function(e){e.WMSC_WSS_OPEN_FAIL_IN_30s="WMSC_WSS_OPEN_FAIL_IN_30s",e.WMSC_WSS_NOT_RECEIVE_MSG_IN_30s="WMSC_WSS_NOT_RECEIVE_MSG_IN_30s",e.WMSC_WSS_CLOSE="WMSC_WSS_CLOSE",e.WMSC_WSS_ERROR="WMSC_WSS_ERROR",e.WMSC_SDP_NEGOTIATION_FAIL="WMSC_SDP_NEGOTIATION_FAIL"}(f||(f={}));t.WMSCManager=class{constructor(e){this._config={webRTCWebSocketUrl:"",confId:"",nodeId:"",HDVideo:!1,mediaStreamController:void 0,iceServers:[]},this._websocket=null,this._wmsc=null,this._isDestroyed=!1,this._qosFlag=new Set,this.isJoinRWGSuccess=!1,this._joinRWGSuccessPromise=new d.default,this._lastTimeStamp=0,this.selfVideoDomMap=new Map,this.activeSpeakerVideoDom=null,this._activeSpeakerRemoteStream=null,this._selfStream=null,this._activeSpeakerSsrc=-1,this.isMirror=!1,this._vbSettingVideoDom=null,this.meetingEnded=!1,this.resolutionUpgraded=!1,this._createWSS=()=>{this._onWSSOpenTimer=setTimeout(()=>{this._tryFailover(h.NOTIFY_UI_WMSC_WSS_DISCONNECTED,f.WMSC_WSS_OPEN_FAIL_IN_30s)},3e4);const{webRTCWebSocketUrl:e}=this._config;this._websocket=(0,g.createRlbSocket)(e),this._websocket.onopen=this._onOpen,this._websocket.onclose=this._onClose,this._websocket.onmessage=this._onMessage,this._websocket.onerror=this._onError,S.default.add_monitor(`WMSC_Create_WSS: ${e}}`)},this._onOpen=()=>{if(clearTimeout(this._onWSSOpenTimer),this._websocket.send(JSON.stringify({evt:h.WS_CONF_WCL_SET_FULL_HD_REQ,body:{fullHDOption:0}})),!this._wmsc){const{confId:e,nodeId:t,HDVideo:i,iceServers:a}=this._config,s=(0,g.isMacIntel)();if(S.default.add_monitor(`WMSC_Instance_Params: ${e}|${t}|${i}|${s}}`),!e||!t)return;const n={maxCaptureResolution:3,maxVideoReceiveNum:26,confId:e,nodeId:t,HDVideo:i,isMacIntel:s,iceServers:a};this._wmsc=new c.Wmsc(n,this._wmscCallBack),this.sendMessageToWMSC({type:c.eventExt.NOTIFY_SDK_JOIN_RWG_SUCCESS,data:""}),this.isJoinRWGSuccess=!0,this._joinRWGSuccessPromise.resolve()}},this._isKeepAliveMessage=e=>{let t=!0;for(let i=0;i<4;i++)if(0!==e[i]){t=!1;break}return t},this._checkReceiveTimeout=()=>{clearTimeout(this._keepAliveTimer),this._keepAliveTimer=setTimeout(()=>{Date.now();this._tryFailover(h.NOTIFY_UI_WMSC_WSS_DISCONNECTED,f.WMSC_WSS_NOT_RECEIVE_MSG_IN_30s)},3e4)},this._replyActiveAliveMessage=e=>{(null==e?void 0:e.data)instanceof Blob&&g.default.readBlobAsBuffer(e.data).then(e=>{var t;const i=new Int8Array(e);this._isKeepAliveMessage(i)&&(null===(t=this._websocket)||void 0===t||t.send(i))}).catch(e=>{m.default.error("WMSC_Read_Alive_F",e)})},this._onMessage=e=>{if(this._websocket.isRlb||(this._checkReceiveTimeout(),this._replyActiveAliveMessage(e)),!((null==e?void 0:e.data)instanceof Blob)&&this._wmsc){if(e.data&&"string"==typeof e.data){let t;try{const{evt:i=""}=JSON.parse(e.data);t=i}catch(e){return void m.default.error("WMSC_Unexpect_Wsss_Message",e)}t===h.WS_CONF_END_INDICATION&&(S.default.add_monitor("WMSC_Meeting_Ended_Indicat: "+Date.now()),this.meetingEnded=!0)}this.sendMessageToWMSC({type:c.eventExt.WMSC_MESSAGE_FROM_RWG,data:e})}},this._onClose=e=>{1e3!==e.code?this._tryFailover(h.NOTIFY_UI_WMSC_WSS_DISCONNECTED,f.WMSC_WSS_CLOSE,e):S.default.add_monitor(`WMSC_WSS_NORMAL_CLOSE: ${e.code}|${this._isDestroyed}|${this.meetingEnded}`)},this._onError=e=>{this._tryFailover(h.NOTIFY_UI_WMSC_WSS_DISCONNECTED,f.WMSC_WSS_ERROR,e)},this._tryFailover=(e,t,i)=>{const a=(0,g.isWebGLAvailable)();let s=`${this._isDestroyed}|${this.meetingEnded}|${a}`;switch(t){case f.WMSC_WSS_OPEN_FAIL_IN_30s:s="WMSC_WSS_OPEN_FAIL:"+s;break;case f.WMSC_WSS_NOT_RECEIVE_MSG_IN_30s:s="WMSC_WSS_RECV_FAIL:"+s;break;case f.WMSC_WSS_CLOSE:s=`WMSC_WSS_CLOSE: ${null==i?void 0:i.code}|`+s;break;case f.WMSC_WSS_ERROR:s="WMSC_WSS_ERROR:"+s;break;case f.WMSC_SDP_NEGOTIATION_FAIL:s="WMSC_SDP_NEGO_F:"+s;break;default:s="WMSC_FAILOVER_UNEXPECT:"+s}S.default.add_monitor(s),m.default.error(s,i),this._isDestroyed||this.meetingEnded||(this.destroy(),l.default.Notify_APPUI(e))},this._disconnect=e=>{var t;const i=`WMSC_WSS_Dissconn: ${e}|${null===(t=null==this?void 0:this._websocket)||void 0===t?void 0:t.readyState}`;S.default.add_monitor(i),m.default.log(i),!this._websocket||this._websocket.readyState!==WebSocket.CONNECTING&&this._websocket.readyState!==WebSocket.OPEN||this._websocket.close()},this.sendMessageToWMSC=e=>{var t;(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.data)instanceof Blob||this._wmsc&&this._wmsc.onMessage(e.type,e)},this.sendMessageToWMSCAsync=e=>{var t,i;if(!this._wmsc)return Promise.reject("this._wmsc is undefined");const{type:a}=e;switch(a){case c.eventExt.VIDEO_STREAMS:{const{streams:a=[]}=e;return(null===(i=null===(t=a[0])||void 0===t?void 0:t.stream)||void 0===i?void 0:i.id)&&(this.streamId=a[0].stream.id),0===a.length?this._selfStream=null:this._selfStream=a[0].stream,this._updateActiveSpeakerStream(),this._wmsc.onMessageAsync(e.type,e)}default:return Promise.reject("Not found event type "+e.type)}},this._wmscCallBack=e=>{var t,i;if(!e)return;const{type:a,data:s}=e;switch(a){case c.eventOut.WMSC_MESSAGE_TO_RWG_BY_SDK:this.sendMesssageToRWG(s);break;case c.eventOut.WMSC_MAPPING_STREAMID_AND_MID:const e=JSON.parse(s);if(!(null===(t=null==e?void 0:e.body)||void 0===t?void 0:t.length))return;const a=[],n=[];e.body.forEach(e=>{e.videoSize>=0?a.push({id:e.userID,size:e.videoSize,bOn:!1}):n.push({id:e.userID})}),a.length?(S.default.add_monitor("WMSC_Sub_List: "+(0,g.replaceComma)(JSON.stringify(a))),e.body.forEach(t=>{l.default.sendMessageToRwg(h.SEND_MESSAGE_TO_RWG,{evt:e.evt,body:t})}),l.default.sendMessageToRwg(h.SEND_MESSAGE_TO_RWG,{evt:h.WS_VIDEO_MULTI_SUBSCRIBE_REQ,body:{subInfoList:a}})):n.length&&(S.default.add_monitor("WMSC_Unsub_List: "+(0,g.replaceComma)(JSON.stringify(n))),l.default.sendMessageToRwg(h.SEND_MESSAGE_TO_RWG,{evt:h.WS_VIDEO_MULTI_UNSUBSCRIBE_REQ,body:{subIDList:n}}),e.body.forEach(t=>{l.default.sendMessageToRwg(h.SEND_MESSAGE_TO_RWG,{evt:e.evt,body:t})}));break;case c.eventOut.SDP_NEGOTIATION_FAIL:this._tryFailover(h.NOTIFY_UI_WMSC_FAILOVER,f.WMSC_SDP_NEGOTIATION_FAIL);break;case c.eventOut.GLOBAL_TRACE:{const{logLevel:e,log:t,errorEvent:i,tags:a}=s;m.default[e](t,i||a);break}case c.eventOut.MONITOR:S.default.add_monitor(s);break;case c.eventOut.DIRECT_MONITOR:S.default.send_monitor_directly(s);break;case c.eventOut.VIDEO_QOS_DATA:l.default.Notify_APPUI(h.VIDEO_QOS_DATA,s);break;case c.eventOut.NETWORK_QUALITY_CHANGE:l.default.Notify_APPUI(h.NETWORK_QUALITY_CHANGE,s);break;case c.eventOut.UPDATE_VIDEO_CAPTURE_CONSTRAINTS:if(!(null===(i=this._config.mediaStreamController)||void 0===i?void 0:i.isUsingFileInputVideoSource())){const{width:e,height:t,frameRate:i}=s;this._updateVideoConstraints(e,t,i)}break;case c.eventOut.V_RECEV_PC_CONNECTED:case c.eventOut.V_SEND_PC_CONNECTED:l.default.Notify_APPUI(h.MEDIA_CONNECTED,{mediaType:"video"});break;case c.eventOut.ERROR_MESSAGE:this.handleWMSCErrorMsg(s)}},this.waitJoinRWGSuccess=()=>this._joinRWGSuccessPromise.promise,this.updateQosSubscription=(e,t,i)=>{var a,s;e?(this._qosFlag.add(t),null===(a=this._wmsc)||void 0===a||a.updateQosSubscription(e,i)):(this._qosFlag.delete(t),0===this._qosFlag.size&&(null===(s=this._wmsc)||void 0===s||s.updateQosSubscription(e,i)))},this.playAllVideoTag=e=>{var t;if(this.selfVideoDomMap.forEach(t=>{t.paused&&this.playSelfVideo(e,t)}),null===(t=null==this?void 0:this._wmsc)||void 0===t?void 0:t.playAllUsedVideoTag){if(!this._wmsc.getHasPausedVideo())return;this._wmsc.playAllUsedVideoTag().then(()=>{}).catch(t=>{const i=`WMSC_RV_P_F: ${e}|${t}`;S.default.add_monitor(i),m.default.error(i)})}},this.playSelfVideo=(e,t)=>{var i;let a="";"visible"!==document.visibilityState&&(a=`WMSC_SV_V_F: ${document.visibilityState}-${e}`),t||(a="WMSC_SV_DOM_F: "+e),t.srcObject||(a="WMSC_SV_SRC_F: "+e);const s=null===(i=null==t?void 0:t.srcObject)||void 0===i?void 0:i.getVideoTracks();if(Array.isArray(s)&&s[0]&&s[0].muted&&(a=`WMSC_SV_TM_F: ${document.visibilityState}-${e}`),t.paused||(a="WMSC_SV_P_F: "+e),a)return S.default.add_monitor(a),void m.default.error(a);t.readyState>t.HAVE_CURRENT_DATA||t.play().then(()=>{S.default.add_monitor("WMSC_SV_SUCCESS: "+e)}).catch(t=>{a=`WMSC_SV_P_E: ${e}|${t.name}:${t.message}`,S.default.add_monitor(a),m.default.error(a,t)})},this.mirrorVideoEle=(e,t)=>{const i=`rotateY(${t?180:0}deg)`;let a=e.style.transform;-1!==a.indexOf("rotateY")?a=a.replace(/rotateY\([0-9]+(deg)?\)/,i):a+=" "+i,e.style.transform=a},this.mirrorSelfVideo=e=>{if(this.isMirror=e,this.selfVideoDomMap.size>0&&this.selfVideoDomMap.forEach(e=>{this.mirrorVideoEle(e,this.isMirror)}),this.activeSpeakerVideoDom&&this._activeSpeakerRemoteStream&&this.mirrorVideoEle(this.activeSpeakerVideoDom,this.isMirror),this.vbSettingVideoDom&&this.mirrorVideoEle(this.vbSettingVideoDom,this.isMirror),this.selfVideoDomMap.size<=0&&!this.activeSpeakerVideoDom&&!this.vbSettingVideoDom){const t="WMSC_MIRROR_F:"+e;S.default.add_monitor(t),m.default.error(t)}},this.sendStreamToWMSC=(e,t,i,a)=>r(this,void 0,void 0,(function*(){var s,n;const{mediaStreamController:r}=this._config,o=null===(n=null===(s=null==r?void 0:r.videoStream)||void 0===s?void 0:s.getVideoTracks()[0])||void 0===n?void 0:n.getSettings(),d=(null==o?void 0:o.width)||640,l=(null==o?void 0:o.height)||360;S.default.add_monitor(`WMSC_Update_V_Constraints_S: ${a}|${e}|${t}|${i}|${d}|${l}`);const h=[{stream:r.getVideoStream(),width:d,height:l}];r.isVideoStreamProcessed()&&h.push({stream:r.videoStream}),yield this.sendMessageToWMSCAsync({type:c.eventExt.VIDEO_STREAMS,streams:h})})),this.onActiveSpeakerChange=e=>{this.sendMessageToWMSC({type:c.eventExt.NOTIFY_SDK_ACTIVE_VIDEO_INDICATION,data:{userId:e}}),this._activeSpeakerSsrc=e,this._updateActiveSpeakerStream()},this._updateActiveSpeakerStream=()=>{if(this.activeSpeakerVideoDom){const{nodeId:e}=this._config;(0,g.Get_Logical_SSrc)(this._activeSpeakerSsrc)===(0,g.Get_Logical_SSrc)(e)?this._selfStream&&(this._activeSpeakerRemoteStream||(this._activeSpeakerRemoteStream=this.activeSpeakerVideoDom.srcObject),this.activeSpeakerVideoDom.srcObject=this._selfStream,this.isMirror&&this.mirrorVideoEle(this.activeSpeakerVideoDom,this.isMirror)):this._activeSpeakerRemoteStream&&(this.activeSpeakerVideoDom.srcObject=this._activeSpeakerRemoteStream,this._activeSpeakerRemoteStream=null,this.isMirror&&this.mirrorVideoEle(this.activeSpeakerVideoDom,!1))}},this.isSelfVideo=e=>{const{nodeId:t}=this._config;return(0,g.Get_Logical_SSrc)(e)===(0,g.Get_Logical_SSrc)(t)},this.handleWMSCErrorMsg=e=>{const{type:t}=e;switch(t){case"WEBRTC_VIDEO_HEALTH_CHECK_FAILED":(0,u.NotifyUIError)(h.MEDIA_HEALTH_CHECK_FAILED,_.WEBRTC_VIDEO_HEALTH_CHECK_FAILED);break;case"PC_RECONNECT":(0,u.NotifyUIError)(h.MEDIA_RECONNECT,e)}},this.destroy=()=>{var e;clearTimeout(this._onWSSOpenTimer),clearTimeout(this._keepAliveTimer),this._cleanUserEventListener&&this._cleanUserEventListener(),this.selfVideoDomMap.clear(),this.isJoinRWGSuccess=!1,this._isDestroyed=!0,this._disconnect(v.destroy),null===(e=this._wmsc)||void 0===e||e.destroy()},this._isDestroyed=!1,this._config=Object.assign(this._config,e),this._createWSS(),this._throttlePlayAllVideoTag=(0,p.default)(this.playAllVideoTag,500),this._cleanUserEventListener=(0,g.addUserEventListener)(()=>this._throttlePlayAllVideoTag(E.userClick)),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&this._throttlePlayAllVideoTag(E.visibilitychange)})}sendMesssageToRWG(e){this._websocket&&this._websocket.readyState===WebSocket.OPEN&&("object"==typeof e?this._websocket.send(JSON.stringify(e)):this._websocket.send(e))}reportWMSCPeerConnectionRawStats(){var e;null===(e=this._wmsc)||void 0===e||e.reportWMSCPeerConnectionRawStats()}_updateVideoConstraints(e,t,i){return r(this,void 0,void 0,(function*(){const{mediaStreamController:a}=this._config;a&&!this._isDestroyed&&e&&t&&i?(yield this.sendMessageToWMSCAsync({type:c.eventExt.VIDEO_STREAMS,streams:[]}),a.changeVideoResolution(e,t,i).then(()=>{this.sendStreamToWMSC(e,t,i,!0)}).catch(a=>{this.sendStreamToWMSC(e,t,i,!1),S.default.add_monitor(`WMSC_Update_V_Constraints_E: ${e}|${t}|${i}`),m.default.error("WMSC_Update_V_Constraints_E",a)})):S.default.add_monitor(`WMSC_Update_V_Constraints_F: ${!!a}|${this._isDestroyed}|${e}|${t}|${i}`)}))}set vbSettingVideoDom(e){this._vbSettingVideoDom=e,this._vbSettingVideoDom&&(this._vbSettingVideoDom.setAttribute("autoplay","true"),this._vbSettingVideoDom.setAttribute("playsinline","true"),this._vbSettingVideoDom.muted=!0,this.isMirror&&this.mirrorVideoEle(this._vbSettingVideoDom,this.isMirror),this._selfStream&&(this._vbSettingVideoDom.srcObject=this._selfStream))}get vbSettingVideoDom(){return this._vbSettingVideoDom}}},99:function(e,t,i){"use strict";var a,s,n,r,o,c,d,l,h,u,m,S;Object.defineProperty(t,"__esModule",{value:!0}),t.NET_BW_LEVEL=t.NET_QUALITY_LEVEL=t.RAW_STATS_REPORT_LIMIT=t.RAW_STATS_LIMIT=t.MAX_RECV_MLINE_NUM=t.H264_HIGH_PROFILE=t.MIN_DEGRADATION_VIDEO_SIZE_RECV=t.TEXT_ENCODING=t.DEFAULT_ACTIVE_SPEAKER_MID=t.ACTIVE_SPEAKER_ID=t.RESOURCE_USAGE_STATE=t.QOS_EVENT=t.MEDIA_EVENT=t.STATS_REPORT_INTERVAL=t.STATS_MONITOR_INTERVAL=t.MAX_PC_RECONNECT_COUNT=t.NEGOTIATION_TIMEOUT=t.PC_STATE_DISCONNECTED_TIMEOUT=t.PC_STATE_CONNECTING_TIMEOUT=t.PC_STATE=t.PEER_ID=t.STREAM_ID_MASK=t.SESSION_ID=t.VIDEO_SIZE=t.TRACE_LEVEL=void 0,function(e){e[e.ERROR=0]="ERROR",e[e.WARN=1]="WARN",e[e.INFO=2]="INFO",e[e.DEBUG=3]="DEBUG",e[e.VERBOSE=4]="VERBOSE"}(a||(t.TRACE_LEVEL=a={})),function(e){e[e._90P=0]="_90P",e[e._180P=1]="_180P",e[e._360P=2]="_360P",e[e._720P=3]="_720P",e[e._1080P=4]="_1080P",e[e._2160P=5]="_2160P"}(s||(t.VIDEO_SIZE=s={})),function(e){e[e.AUDIO=1]="AUDIO",e[e.VIDEO=2]="VIDEO",e[e.SHARE=3]="SHARE"}(n||(t.SESSION_ID=n={})),function(e){e[e.VIDEO=1]="VIDEO",e[e.AUDIO=2]="AUDIO",e[e.SHARE=3]="SHARE"}(r||(t.STREAM_ID_MASK=r={})),function(e){e[e.INGRESS=0]="INGRESS",e[e.EGRESS=1]="EGRESS"}(o||(t.PEER_ID=o={})),function(e){e[e.IDLE=0]="IDLE",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED"}(c||(t.PC_STATE=c={})),t.PC_STATE_CONNECTING_TIMEOUT=6e3,t.PC_STATE_DISCONNECTED_TIMEOUT=5e3,t.NEGOTIATION_TIMEOUT=1e4,t.MAX_PC_RECONNECT_COUNT=3,t.STATS_MONITOR_INTERVAL=1e3,t.STATS_REPORT_INTERVAL=15e3,function(e){e.STREAM="STREAM",e.SDP="SDP",e.PC_STATE_CHANGE="PC_STATE_CHANGE",e.ERROR="ERROR"}(d||(t.MEDIA_EVENT=d={})),function(e){e.LAYERS_UPDATE="LAYERS_UPDATE",e.MIN_BITRATE_UPDATE="MIN_BITRATE_UPDATE",e.ENCODER_RESET="ENCODER_RESET"}(l||(t.QOS_EVENT=l={})),function(e){e[e.NONE=0]="NONE",e[e.UNDERUSING=1]="UNDERUSING",e[e.NORMAL=2]="NORMAL",e[e.OVERUSING=3]="OVERUSING"}(h||(t.RESOURCE_USAGE_STATE=h={})),t.ACTIVE_SPEAKER_ID=1,t.DEFAULT_ACTIVE_SPEAKER_MID="0",function(e){e[e.PLAIN=0]="PLAIN",e[e.GZIP_BASE64=1]="GZIP_BASE64"}(u||(t.TEXT_ENCODING=u={})),t.MIN_DEGRADATION_VIDEO_SIZE_RECV=2,t.H264_HIGH_PROFILE="64",t.MAX_RECV_MLINE_NUM=27,t.RAW_STATS_LIMIT=299,t.RAW_STATS_REPORT_LIMIT=6,function(e){e[e.NET_QUALITY_UNKNOWN=-1]="NET_QUALITY_UNKNOWN",e[e.NET_QUALITY_VERY_BAD=0]="NET_QUALITY_VERY_BAD",e[e.NET_QUALITY_BAD=1]="NET_QUALITY_BAD",e[e.NET_QUALITY_NOT_GOOD=2]="NET_QUALITY_NOT_GOOD",e[e.NET_QUALITY_NORMAL=3]="NET_QUALITY_NORMAL",e[e.NET_QUALITY_GOOD=4]="NET_QUALITY_GOOD",e[e.NET_QUALITY_EXCELLENT=5]="NET_QUALITY_EXCELLENT"}(m||(t.NET_QUALITY_LEVEL=m={})),function(e){e[e.NET_BW_LEVEL_UNKNOWN=-1]="NET_BW_LEVEL_UNKNOWN",e[e.NET_BW_LEVEL_VERY_LOW=0]="NET_BW_LEVEL_VERY_LOW",e[e.NET_BW_LEVEL_LOW=1]="NET_BW_LEVEL_LOW",e[e.NET_BW_LEVEL_NORMAL=2]="NET_BW_LEVEL_NORMAL"}(S||(t.NET_BW_LEVEL=S={}))}}]);
2
- //# sourceMappingURL=https://d1cdksi819e9z7.cloudfront.net/sourcemap/wmsc.min.js-71b1cf241b7d59ce116a.map
2
+ //# sourceMappingURL=https://d1cdksi819e9z7.cloudfront.net/sourcemap/wmsc.min.js-722c6a98c1648e486f7a.map